Skip to content

[Bug]: MCP OAuth install fails after consent — callback_handler returns a tuple while mcp 2.x expects AuthorizationCodeResult #4818

Closed

Description

@VascoSch92

Is there an existing issue for the same bug?

  • I have searched existing issues and this is not a duplicate.

Bug Description

_BrowserCoordinatedOAuth.callback_handler in openhands-agent-server/openhands/agent_server/mcp_router.py returns tuple[str, str | None]. That is the contract mcp 1.x used. mcp 2.x changed it to AuthorizationCodeResult and reads .state off the return value, so every OAuth-based MCP server install now fails immediately after the user authorizes, with:

MCP test connection failed for server '<name>': Client failed to connect: 'tuple' object has no attribute 'state'

The user-visible symptom in Agent Canvas is the misleading banner "Could not reach the server. Check the URL and server type." The provider is reachable and the OAuth flow succeeds end to end. In a real GitLab reproduction, discovery returned 200, POST /oauth/register returned 201, GET /oauth/authorize returned 302, and the user approved the consent screen. Across ten failed attempts the provider returned no error beyond the expected initial 401 challenge that starts the flow. The crash is entirely client-side, after the redirect.

This is not tied to one agent-server release. The method is byte-identical in 1.42.1, 1.44.1 and on main (94fca57). What changed is the resolved dependency: openhands-sdk declares fastmcp>=3.0.0 with no ceiling, so a fresh install of either release now pulls fastmcp 4.0.1 with mcp 2.1.1.

uv pip compile openhands-agent-server==1.42.1  --no-cache  ->  fastmcp 4.0.1, mcp 2.1.1
uv pip compile openhands-agent-server==1.44.1  --no-cache  ->  fastmcp 4.0.1, mcp 2.1.1
uv pip compile openhands-agent-server==1.44.1 + "fastmcp<4" ->  fastmcp 3.4.7, mcp 1.29.1

Why CI does not catch it. The root pyproject.toml sets [tool.uv] exclude-newer = "7 days" and uv.lock pins fastmcp 3.2.0 / mcp 1.28.1, so every workspace install and CI run gets a working pair. Only consumers that resolve from PyPI without the lock (for example the Agent Canvas uvx invocation) hit this.

Root cause is a fork, not just a type. _BrowserCoordinatedOAuth.callback_handler is a copy of fastmcp's own OAuth.callback_handler (34 vs 33 non-blank lines, 66% identical line for line). The only intended addition is self._job.set_callback_ready(callback_url). Copying froze three behaviors that have since drifted:

Behavior fastmcp base the forked copy
Return value tracks the installed version (tuple in 3.x, AuthorizationCodeResult in 4.x) always a tuple — this outage
Callback host passes host=self._callback_host omits it, so the server binds create_oauth_callback_server's default
Timeout uses self._callback_timeout hardcodes 300.0, ignoring the constructor argument

The existing # type: ignore[return-value] on the return line was already suppressing the mismatch.

Note that fastmcp 4's base also forwards RFC 9207 iss, which the fork drops.

Expected Behavior

Completing the provider's OAuth consent screen connects the MCP server, regardless of which mcp / fastmcp version the environment resolved.

Actual Behavior

The flow dies right after the redirect with AttributeError: 'tuple' object has no attribute 'state', surfaced to the UI as "Could not reach the server."

Reproduced offline on main (94fca57) with no network, no browser and no provider account. Two virtualenvs are built over byte-identical agent-server source; only the MCP client libraries differ.

git clone https://github.com/OpenHands/software-agent-sdk.git && cd software-agent-sdk
git checkout 94fca57

# NOTE: run the installs from outside the repo. The root pyproject sets
# exclude-newer = "7 days", which hides fastmcp 4 and makes the bug vanish.
cd /
uv venv /opt/mcp1 --python 3.13
VIRTUAL_ENV=/opt/mcp1 uv pip install --no-cache \
  <repo>/openhands-sdk <repo>/openhands-agent-server "fastmcp<4"

uv venv /opt/mcp2 --python 3.13
VIRTUAL_ENV=/opt/mcp2 uv pip install --no-cache \
  <repo>/openhands-sdk <repo>/openhands-agent-server "fastmcp==4.0.1" "mcp==2.1.1"

/opt/mcp1/bin/python repro.py    # OK
/opt/mcp2/bin/python repro.py    # AttributeError: 'tuple' object has no attribute 'state'

repro.py runs the real _BrowserCoordinatedOAuth against a stub OAuth authorization server, with a thread standing in for the browser. A self-contained Dockerfile and the script are attached in the comment below.

Observed traceback in the failing environment:

File "/opt/mcp2/lib/python3.13/site-packages/mcp/client/auth/oauth2.py", line 421,
  in _perform_authorization_code_grant
    if result.state is None or not secrets.compare_digest(result.state, state):
AttributeError: 'tuple' object has no attribute 'state'

Matrix over the same source, six runs:

mcp 1.x   | as shipped                          OK
mcp 2.1.1 | as shipped                          FAILS ('tuple' has no attribute 'state')
mcp 1.x   | delegate to fastmcp (proposed fix)  OK
mcp 2.1.1 | delegate to fastmcp (proposed fix)  OK

Steps to Reproduce

  1. Install openhands-agent-server from PyPI (or from this repo, from outside the repo root so exclude-newer does not apply) so that fastmcp 4.x / mcp 2.1.x resolve.
  2. In Agent Canvas, add an MCP server that authenticates with OAuth, for example https://gitlab.com/api/v4/mcp, and click Install.
  3. Complete the provider's consent screen.
  4. The dialog shows "Could not reach the server. Check the URL and server type", and the agent-server log shows MCP test connection failed ... 'tuple' object has no attribute 'state'.

Acceptance Criteria

  • _BrowserCoordinatedOAuth.callback_handler no longer reimplements fastmcp's OAuth.callback_handler; it publishes the callback URL and delegates via super(), so the return type tracks the installed fastmcp by construction.
  • Installing an OAuth-authenticated MCP server succeeds with fastmcp 4.x / mcp 2.1.x resolved.
  • The same flow still succeeds with fastmcp 3.x / mcp 1.x resolved.
  • The RFC 9207 iss value returned by the callback is no longer discarded.
  • The configured callback_host and callback_timeout are honoured rather than hardcoded.
  • A regression test covers the OAuth callback flow against a stub authorization server, so a future contract change fails CI rather than only PyPI consumers.
  • CI exercises a resolution that is not pinned by uv.lock, or openhands-sdk declares a fastmcp ceiling, so this class of drift is caught before release.

Installation Method

Other

If you selected "Other", please specify

uvx / uv pip install from PyPI, as Agent Canvas does; also reproduced from a source checkout of main.

SDK Version

main @ 94fca57, and released 1.42.1 and 1.44.1 (the method is identical in all three).

Version Confirmation

  • I have confirmed this bug exists on the LATEST version of OpenHands SDK

Proposed Fix

async def callback_handler(self):
    self._job.set_callback_ready(
        f"http://{self._callback_host}:{self.redirect_port}/callback"
    )
    return await super().callback_handler()

Verified in both environments. It is version-agnostic by construction, stops discarding iss, and removes the two latent divergences above. It is behaviour-preserving today because the defaults coincide (callback_timeout=300.0, and the host resolves to the same loopback address).

Caveat for review: this relies on _callback_host and _callback_timeout, which are private attributes of fastmcp's class. The current code already depends on redirect_port and on the private create_oauth_callback_server, so it is not new coupling, but it is worth a deliberate decision.

A narrower alternative is to adapt the tuple behind a guarded import of mcp.shared.auth.AuthorizationCodeResult (absent in mcp 1.x, so it cannot be a straight swap). That also passes the matrix, but it keeps the fork and still drops iss.

Suggested stopgap, independent of the code fix: add a fastmcp<4 ceiling so PyPI consumers stop resolving the broken pair, then lift it once the delegation lands.

Activity

  1. added
    bug
    on Sep 2, 2026
  2. added
    ready-for-dev
    on Sep 2, 2026
  3. github-actions commented on Sep 2, 2026

    @github-actions
    Contributor

    ✅ ready-for-dev label applied

    This issue meets the readiness criteria and is ready for contribution.
    A contributor can now open a PR that links this issue (Fixes #<number>).

    This is an automated check — no AI was used to generate this comment.

  4. VascoSch92 commented on Sep 2, 2026

    @VascoSch92
    MemberAuthor

    Self-contained reproduction. No network at run time, no browser, no provider account: the image ships a stub OAuth authorization server and a thread that plays the browser.

    docker build -t mcp-oauth-repro .
    docker run --rm mcp-oauth-repro   # exits 1 when the bug reproduces

    It builds two virtualenvs over byte-identical agent-server source (the entrypoint diffs the installed mcp_router.py against the checkout and prints the result), then runs the flow as shipped and with each candidate fix.

    Pass --build-arg SDK_REF=main to retest a newer revision.

    Dockerfile
    # syntax=docker/dockerfile:1
    FROM python:3.13-slim
    
    # Pinned so the reproduction stays stable; override to test another revision:
    #   docker build --build-arg SDK_REF=main -t mcp-oauth-repro .
    ARG SDK_REF=94fca57
    ARG SDK_REPO=https://github.com/OpenHands/software-agent-sdk.git
    
    RUN apt-get update \
     && apt-get install -y --no-install-recommends git ca-certificates curl \
     && rm -rf /var/lib/apt/lists/*
    
    COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
    
    WORKDIR /src
    RUN git clone --filter=blob:none "$SDK_REPO" sdk \
     && cd sdk && git checkout "$SDK_REF" && git rev-parse HEAD > /src/SDK_COMMIT
    
    # Two environments over the SAME agent-server source. Only the MCP client
    # libraries differ, which is the whole point of the experiment.
    #
    # The repo root pyproject sets `exclude-newer = "7 days"`, which hides fastmcp 4
    # from a workspace resolve, so both installs run from / with --no-cache.
    WORKDIR /
    RUN uv venv /opt/mcp1 --python 3.13 \
     && VIRTUAL_ENV=/opt/mcp1 uv pip install --no-cache \
          /src/sdk/openhands-sdk /src/sdk/openhands-agent-server "fastmcp<4"
    
    RUN uv venv /opt/mcp2 --python 3.13 \
     && VIRTUAL_ENV=/opt/mcp2 uv pip install --no-cache \
          /src/sdk/openhands-sdk /src/sdk/openhands-agent-server \
          "fastmcp==4.0.1" "mcp==2.1.1"
    
    COPY repro.py /opt/repro.py
    COPY run-matrix.sh /opt/run-matrix.sh
    RUN chmod +x /opt/run-matrix.sh
    
    ENV OPENHANDS_SUPPRESS_BANNER=1 \
        LOG_LEVEL=WARNING \
        PYTHONWARNINGS=ignore \
        PYTHONUNBUFFERED=1
    ENTRYPOINT ["/opt/run-matrix.sh"]
    run-matrix.sh
    #!/usr/bin/env bash
    # Runs the OAuth callback flow across both MCP client versions, with the
    # agent-server code as shipped and with the proposed fix.
    set -u
    
    echo "OpenHands agent-server MCP OAuth callback reproduction"
    echo "SDK commit under test: $(cat /src/SDK_COMMIT)"
    echo
    
    # Prove both environments run byte-identical agent-server source.
    SRC=/src/sdk/openhands-agent-server/openhands/agent_server/mcp_router.py
    for venv in /opt/mcp1 /opt/mcp2; do
      installed=$("$venv/bin/python" -c \
        'import openhands.agent_server.mcp_router as m; print(m.__file__)' 2>/dev/null)
      if diff -q "$SRC" "$installed" >/dev/null 2>&1; then
        echo "  $venv: mcp_router.py identical to the checkout"
      else
        echo "  $venv: WARNING - mcp_router.py differs from the checkout"
      fi
    done
    echo
    
    declare -a NAMES RESULTS
    run() {
      local label="$1" venv="$2"; shift 2
      echo "=============================================================="
      echo "CASE: $label"
      echo "=============================================================="
      "$venv/bin/python" /opt/repro.py "$@"
      local rc=$?
      NAMES+=("$label")
      case $rc in
        0) RESULTS+=("OK          (callback consumed)") ;;
        1) RESULTS+=("REPRODUCED  ('tuple' has no attribute 'state')") ;;
        *) RESULTS+=("INCONCLUSIVE (rc=$rc)") ;;
      esac
      echo
      return 0
    }
    
    run "mcp 1.x   | as shipped"   /opt/mcp1
    run "mcp 2.1.1 | as shipped"   /opt/mcp2
    run "mcp 1.x   | fix A adapt"  /opt/mcp1 --fix
    run "mcp 2.1.1 | fix A adapt"  /opt/mcp2 --fix
    run "mcp 1.x   | fix B delegate" /opt/mcp1 --delegate
    run "mcp 2.1.1 | fix B delegate" /opt/mcp2 --delegate
    
    echo "=============================================================="
    echo "SUMMARY"
    echo "=============================================================="
    for i in "${!NAMES[@]}"; do
      printf '  %-30s %s\n' "${NAMES[$i]}" "${RESULTS[$i]}"
    done
    echo
    
    if [[ "${RESULTS[1]}" == REPRODUCED* ]]; then
      echo "Bug reproduced: same agent-server source, only the mcp version differs."
      exit 1
    fi
    echo "Bug did NOT reproduce (check the dependency versions printed above)."
    exit 0
    repro.py
    """Reproduce the OpenHands agent-server MCP OAuth callback failure, offline.
    
    Drives the real `_BrowserCoordinatedOAuth` from
    `openhands.agent_server.mcp_router` through a full authorization-code flow
    against a stub OAuth + MCP server, with a thread standing in for the browser.
    No network access and no GitLab account are needed.
    
    The bug: `callback_handler` returns `tuple[str, str | None]`, which is what
    mcp 1.x unpacked. mcp 2.x instead expects an `AuthorizationCodeResult` and
    reads `.state` off it, so the flow dies right after the user authorizes.
    
    Usage:
        python repro.py           # agent-server code exactly as shipped
        python repro.py --fix     # with a version-aware callback_handler
    
    Exit codes:
        0  callback consumed correctly (flow reached the token exchange)
        1  BUG REPRODUCED ('tuple' object has no attribute 'state')
        2  inconclusive (failed or hung before the callback was consumed)
    """
    
    import asyncio
    import importlib.metadata as md
    import json
    import os
    import sys
    import threading
    import time
    import urllib.parse
    import urllib.request
    from http.server import BaseHTTPRequestHandler, HTTPServer
    
    from fastmcp import Client
    from fastmcp.client.auth.oauth import OAuth
    from openhands.agent_server.mcp_router import _BrowserCoordinatedOAuth
    
    try:  # mcp >= 2.0
        from mcp.shared.auth import AuthorizationCodeResult
    except ImportError:  # mcp 1.x wants a plain tuple
        AuthorizationCodeResult = None
    
    HOST = "127.0.0.1"
    AUTH_CODE = "stub-auth-code"
    hit = {"token": False}
    
    
    class StubHandler(BaseHTTPRequestHandler):
        """Minimal OAuth authorization server + protected MCP resource."""
    
        def log_message(self, *args):
            pass
    
        @property
        def base(self):
            return f"http://{HOST}:{self.server.server_address[1]}"
    
        def _json(self, code, payload):
            body = json.dumps(payload).encode()
            self.send_response(code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
    
        def do_GET(self):
            path = urllib.parse.urlparse(self.path).path
            if path.startswith("/.well-known/oauth-protected-resource"):
                return self._json(
                    200,
                    {"resource": f"{self.base}/mcp", "authorization_servers": [self.base]},
                )
            if path.startswith("/.well-known/oauth-authorization-server") or path.startswith(
                "/.well-known/openid-configuration"
            ):
                return self._json(
                    200,
                    {
                        "issuer": self.base,
                        "authorization_endpoint": f"{self.base}/authorize",
                        "token_endpoint": f"{self.base}/token",
                        "registration_endpoint": f"{self.base}/register",
                        "response_types_supported": ["code"],
                        "grant_types_supported": ["authorization_code", "refresh_token"],
                        "code_challenge_methods_supported": ["S256"],
                        "scopes_supported": ["mcp"],
                        "token_endpoint_auth_methods_supported": [
                            "none",
                            "client_secret_post",
                        ],
                    },
                )
            if path == "/authorize":
                query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
                redirect_uri = query.get("redirect_uri", [""])[0]
                state = query.get("state", [""])[0]
                self.send_response(302)
                self.send_header(
                    "Location",
                    f"{redirect_uri}?code={AUTH_CODE}&state={urllib.parse.quote(state)}",
                )
                self.end_headers()
                return
            self._json(404, {"error": "not_found"})
    
        def do_POST(self):
            path = urllib.parse.urlparse(self.path).path
            if path == "/register":
                length = int(self.headers.get("Content-Length") or 0)
                body = json.loads(self.rfile.read(length) or b"{}")
                return self._json(
                    201,
                    {
                        "client_id": "stub-client-id",
                        "client_id_issued_at": 0,
                        "redirect_uris": body.get("redirect_uris", []),
                        "token_endpoint_auth_method": "none",
                        "grant_types": ["authorization_code", "refresh_token"],
                        "response_types": ["code"],
                        "scope": "mcp",
                    },
                )
            if path == "/token":
                hit["token"] = True
                return self._json(
                    200,
                    {
                        "access_token": "stub-access-token",
                        "token_type": "Bearer",
                        "expires_in": 3600,
                        "scope": "mcp",
                    },
                )
            if path == "/mcp":
                # Unauthenticated call: advertise the protected-resource metadata so
                # the client starts the OAuth flow, exactly as GitLab does.
                self.send_response(401)
                self.send_header(
                    "WWW-Authenticate",
                    f'Bearer resource_metadata="{self.base}'
                    '/.well-known/oauth-protected-resource/mcp"',
                )
                self.send_header("Content-Length", "0")
                self.end_headers()
                return
            self._json(404, {"error": "not_found"})
    
    
    class StubJob:
        """Stands in for _MCPOAuthProbeJob, and plays the browser."""
    
        def __init__(self):
            self.id = "repro-job"
            self.state = None
    
        def set_authorization_url(self, url):
            query = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)
            self.state = query.get("state", [""])[0]
    
        def set_callback_ready(self, callback_url):
            def visit():
                target = (
                    f"{callback_url}?code={AUTH_CODE}"
                    f"&state={urllib.parse.quote(self.state or '')}"
                )
                # The callback server is launched with start_soon and may not be
                # listening yet, so retry instead of giving up on the first refusal.
                last = None
                for attempt in range(40):
                    try:
                        urllib.request.urlopen(target, timeout=5).read()
                        print(f"  [browser-stub] callback delivered (try {attempt + 1})")
                        return
                    except Exception as exc:
                        last = exc
                        time.sleep(0.25)
                print(f"  [browser-stub] FAILED to deliver callback: {last!r}")
    
            threading.Thread(target=visit, daemon=True).start()
    
    
    class FixedOAuth(_BrowserCoordinatedOAuth):
        """Fix A: adapt the forked method's tuple to whatever mcp expects.
    
        Keeps the fork, so it still drifts from fastmcp and drops RFC 9207 `iss`.
        """
    
        async def callback_handler(self):
            code, state = await super().callback_handler()
            if AuthorizationCodeResult is None:
                return code, state
            return AuthorizationCodeResult(code=code, state=state)
    
    
    class DelegatingOAuth(_BrowserCoordinatedOAuth):
        """Fix B: stop forking. Publish the callback URL, then let fastmcp do it.
    
        fastmcp's own OAuth.callback_handler is what the forked method was copied
        from; delegating means the return type tracks the installed version by
        construction, and `iss` stops being dropped.
        """
    
        async def callback_handler(self):
            self._job.set_callback_ready(
                f"http://{self._callback_host}:{self.redirect_port}/callback"
            )
            return await OAuth.callback_handler(self)
    
    
    def _watchdog(seconds=90):
        def bark():
            time.sleep(seconds)
            print(f"\nWATCHDOG: no result after {seconds}s")
            print("RESULT: INCONCLUSIVE (flow hung)")
            os._exit(2)
    
        threading.Thread(target=bark, daemon=True).start()
    
    
    async def main(mode):
        server = HTTPServer((HOST, 0), StubHandler)
        threading.Thread(target=server.serve_forever, daemon=True).start()
        url = f"http://{HOST}:{server.server_address[1]}/mcp"
    
        print(f"  agent-server = {md.version('openhands-agent-server')}")
        print(f"  fastmcp      = {md.version('fastmcp')}")
        print(f"  mcp          = {md.version('mcp')}")
        print(f"  AuthorizationCodeResult importable = {AuthorizationCodeResult is not None}")
        labels = {"shipped": "as shipped (fork)",
                  "adapt": "fix A: adapt tuple -> AuthorizationCodeResult",
                  "delegate": "fix B: delegate to fastmcp OAuth"}
        print(f"  callback_handler = {labels[mode]}")
    
        cls = {"shipped": _BrowserCoordinatedOAuth, "adapt": FixedOAuth,
               "delegate": DelegatingOAuth}[mode]
        client = Client(url, auth=cls(job=StubJob(), mcp_url=url, scopes="mcp"))
    
        try:
            async with client:
                pass
        except Exception as exc:
            chain, err, seen = [], exc, set()
            while err is not None and id(err) not in seen:
                seen.add(id(err))
                chain.append(f"{type(err).__name__}: {err}")
                err = err.__cause__ or err.__context__
                if len(chain) > 12:
                    break
            if any("'tuple' object has no attribute 'state'" in c for c in chain):
                print("\n  exception chain:")
                for line in chain:
                    print(f"    {line}")
                print("\nRESULT: BUG REPRODUCED")
                return 1
            if not hit["token"]:
                print("\n  exception chain:")
                for line in chain:
                    print(f"    {line}")
                print("\nRESULT: INCONCLUSIVE (died before the callback was consumed)")
                return 2
            # Anything after the token exchange is this stub not speaking MCP.
    
        print("\nRESULT: OK (callback consumed, flow reached the token exchange)")
        return 0
    
    
    if __name__ == "__main__":
        _watchdog()
        mode = "shipped"
        if "--fix" in sys.argv:
            mode = "adapt"
        if "--delegate" in sys.argv:
            mode = "delegate"
        sys.exit(asyncio.run(main(mode)))
  5. added
    priority:high
    release-note-required
    on Sep 2, 2026
  6. jpelletier1 commented on Sep 2, 2026

    @jpelletier1
    Contributor

    @VascoSch92 Is this related to: OpenHands/OpenHands#17077

    The symptom I was seeing was OAuth sessions were not being refreshed, and Atlassian and GitLab servers were rejecting because the Callback URI was 'invalid'. I think it has to do with these root causes:

    • Token expiry not loaded on init: FastMCP's OAuthClientProvider._initialize() loads tokens and client info from storage but NOT token_expiry_time. Without the expiry, is_token_valid() always returns True for any access token — even expired ones — so the refresh-token flow is never triggered. The expired token gets sent, the server returns 401, and a full browser re-authorization is attempted (which fails in the runtime context).

    • Random callback port: The OAuth callback server used a random port on each authorization attempt. OAuth providers like Atlassian Rovo and GitLab that require pre-registered redirect URIs reject callbacks with unregistered ports.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmcppriority:highready-for-devrelease-note-required

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions