From 1d067ec64bff5bb4f178bad952ed192a3d65b02d Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Wed, 2 Sep 2026 12:28:07 +0200 Subject: [PATCH 1/2] fix(agent-server): delegate MCP OAuth callback to FastMCP instead of forking it _BrowserCoordinatedOAuth.callback_handler was a copy of FastMCP's own OAuth.callback_handler, added only so the callback URL could be published to the frontend. The copy froze the return type as tuple[str, str | None], which mcp 1.x unpacked but mcp 2.x rejects: it expects an AuthorizationCodeResult and reads .state off it. Every OAuth MCP server install therefore failed right after the user authorized, with "'tuple' object has no attribute 'state'", surfaced in the UI as "Could not reach the server". Publish the callback URL, then defer to super(). The return type now tracks whichever FastMCP is installed, and the RFC 9207 iss value is no longer dropped. Fixes #4818 --- .../openhands/agent_server/mcp_router.py | 64 +++++++------------ tests/agent_server/test_mcp_router.py | 57 ++++++----------- 2 files changed, 43 insertions(+), 78 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/mcp_router.py b/openhands-agent-server/openhands/agent_server/mcp_router.py index be518b2117f..b3d7b0f7a01 100644 --- a/openhands-agent-server/openhands/agent_server/mcp_router.py +++ b/openhands-agent-server/openhands/agent_server/mcp_router.py @@ -26,15 +26,10 @@ from typing import Annotated, Any, Literal from urllib.parse import urlparse -import anyio import httpx import mcp.types from fastapi import APIRouter, HTTPException, Request from fastmcp.client.auth.oauth import ClientNotFoundError, OAuth -from fastmcp.client.oauth_callback import ( - OAuthCallbackResult, - create_oauth_callback_server, -) from pydantic import BaseModel, Field, model_validator from openhands.agent_server._secrets_exposure import get_cipher @@ -468,44 +463,29 @@ async def redirect_handler(self, authorization_url: str) -> None: logger.info("MCP OAuth authorization URL captured for job %s", self._job.id) self._job.set_authorization_url(authorization_url) - async def callback_handler(self) -> tuple[str, str | None]: - """Run FastMCP's callback server and expose readiness to the frontend.""" - result = OAuthCallbackResult() - result_ready = anyio.Event() - server = create_oauth_callback_server( - port=self.redirect_port, - server_url=self.mcp_url, - result_container=result, - result_ready=result_ready, - ) + async def callback_handler(self): + """Expose callback readiness to the frontend, then defer to FastMCP. + + This used to reimplement FastMCP's own ``callback_handler`` so it could + publish the callback URL. That copy froze the return type as + ``tuple[str, str | None]``, which mcp 1.x unpacked but mcp 2.x rejects: + it expects an ``AuthorizationCodeResult`` and reads ``.state`` off it, + so every OAuth server install failed right after the user authorized + with ``'tuple' object has no attribute 'state'``. Delegating keeps the + return type in step with whichever fastmcp is installed, and stops the + RFC 9207 ``iss`` value from being dropped. + + ``redirect_port`` is the only attribute read here because it is the one + FastMCP has exposed across every 3.x and 4.x release. + """ callback_url = f"http://localhost:{self.redirect_port}/callback" - callback_timeout = 300.0 - - async with anyio.create_task_group() as tg: - tg.start_soon(server.serve) - self._job.set_callback_ready(callback_url) - logger.info( - "MCP OAuth callback server ready for job %s at %s", - self._job.id, - callback_url, - ) - - try: - with anyio.fail_after(callback_timeout): - await result_ready.wait() - if result.error: - raise result.error - return result.code, result.state # type: ignore[return-value] - except TimeoutError as e: - raise TimeoutError( - f"OAuth callback timed out after {callback_timeout} seconds" - ) from e - finally: - server.should_exit = True - await anyio.sleep(0.1) - tg.cancel_scope.cancel() - - raise RuntimeError("OAuth callback handler could not be started") + self._job.set_callback_ready(callback_url) + logger.info( + "MCP OAuth callback server ready for job %s at %s", + self._job.id, + callback_url, + ) + return await super().callback_handler() def _run_tool_call( diff --git a/tests/agent_server/test_mcp_router.py b/tests/agent_server/test_mcp_router.py index 193766bfc42..a2f9bfe4912 100644 --- a/tests/agent_server/test_mcp_router.py +++ b/tests/agent_server/test_mcp_router.py @@ -9,7 +9,6 @@ from collections.abc import Generator from types import SimpleNamespace -import anyio import pytest from fastapi.testclient import TestClient from pydantic import SecretStr @@ -769,9 +768,17 @@ def fake_create_mcp_tools( assert access_token != "oauth-access-token" -def test_browser_coordinated_oauth_callback_handler_uses_fastmcp_callback_api( +def test_browser_coordinated_oauth_callback_handler_delegates_to_fastmcp( monkeypatch: pytest.MonkeyPatch, ): + """The override must publish the callback URL and return FastMCP's result as-is. + + It used to reimplement FastMCP's callback_handler, which froze the return + type as a tuple. mcp 2.x expects an AuthorizationCodeResult and reads + `.state` off it, so the copy broke every OAuth install with + "'tuple' object has no attribute 'state'". Passing the base result through + untouched keeps this working across both contracts. + """ job = _MCPOAuthProbeJob( request=MCPTestRequest.model_validate( {"server": {"transport": "http", "url": "https://mcp.example.com/mcp"}} @@ -783,48 +790,26 @@ def test_browser_coordinated_oauth_callback_handler_uses_fastmcp_callback_api( mcp_url="https://mcp.example.com/mcp", callback_port=64801, ) - calls: list[dict[str, object]] = [] - - class FakeServer: - should_exit = False - - def __init__(self, *, result_container, result_ready): - self.result_container = result_container - self.result_ready = result_ready - async def serve(self): - self.result_container.code = "oauth-code" - self.result_container.state = "oauth-state" - self.result_ready.set() - while not self.should_exit: - await anyio.sleep(0.01) + sentinel = object() + seen: list[bool] = [] - def fake_create_oauth_callback_server(**kwargs): - calls.append(kwargs) - return FakeServer( - result_container=kwargs["result_container"], - result_ready=kwargs["result_ready"], - ) + async def fake_base_callback_handler(self): + # The URL must be published before the base blocks on the callback, + # otherwise the frontend never learns where to send the browser. + seen.append(job.callback_ready.is_set()) + return sentinel monkeypatch.setattr( - "openhands.agent_server.mcp_router.create_oauth_callback_server", - fake_create_oauth_callback_server, + "fastmcp.client.auth.oauth.OAuth.callback_handler", + fake_base_callback_handler, ) - code, state = asyncio.run(oauth.callback_handler()) + result = asyncio.run(oauth.callback_handler()) - assert (code, state) == ("oauth-code", "oauth-state") - assert job.callback_ready.is_set() + assert result is sentinel + assert seen == [True] assert job.callback_url == "http://localhost:64801/callback" - assert calls == [ - { - "port": 64801, - "server_url": "https://mcp.example.com/mcp", - "result_container": calls[0]["result_container"], - "result_ready": calls[0]["result_ready"], - } - ] - assert "host" not in calls[0] def test_mcp_oauth_callback_rejects_unknown_job(client: TestClient): From 2dc61c283f39ec80a43efc5b292213186e0e9a7d Mon Sep 17 00:00:00 2001 From: VascoSch92 Date: Wed, 2 Sep 2026 12:33:55 +0200 Subject: [PATCH 2/2] docs(agent-server): trim the callback_handler docstrings --- .../openhands/agent_server/mcp_router.py | 18 +++++------------- tests/agent_server/test_mcp_router.py | 9 +-------- 2 files changed, 6 insertions(+), 21 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/mcp_router.py b/openhands-agent-server/openhands/agent_server/mcp_router.py index b3d7b0f7a01..0344776644d 100644 --- a/openhands-agent-server/openhands/agent_server/mcp_router.py +++ b/openhands-agent-server/openhands/agent_server/mcp_router.py @@ -464,19 +464,11 @@ async def redirect_handler(self, authorization_url: str) -> None: self._job.set_authorization_url(authorization_url) async def callback_handler(self): - """Expose callback readiness to the frontend, then defer to FastMCP. - - This used to reimplement FastMCP's own ``callback_handler`` so it could - publish the callback URL. That copy froze the return type as - ``tuple[str, str | None]``, which mcp 1.x unpacked but mcp 2.x rejects: - it expects an ``AuthorizationCodeResult`` and reads ``.state`` off it, - so every OAuth server install failed right after the user authorized - with ``'tuple' object has no attribute 'state'``. Delegating keeps the - return type in step with whichever fastmcp is installed, and stops the - RFC 9207 ``iss`` value from being dropped. - - ``redirect_port`` is the only attribute read here because it is the one - FastMCP has exposed across every 3.x and 4.x release. + """Publish the callback URL, then defer to FastMCP. + + Reimplementing this froze the return type as a tuple, which mcp 2.x + rejects -- it wants an ``AuthorizationCodeResult``. Only + ``redirect_port`` is read: ``_callback_host`` is absent in fastmcp 3.2.0. """ callback_url = f"http://localhost:{self.redirect_port}/callback" self._job.set_callback_ready(callback_url) diff --git a/tests/agent_server/test_mcp_router.py b/tests/agent_server/test_mcp_router.py index a2f9bfe4912..c43f8633e1c 100644 --- a/tests/agent_server/test_mcp_router.py +++ b/tests/agent_server/test_mcp_router.py @@ -771,14 +771,7 @@ def fake_create_mcp_tools( def test_browser_coordinated_oauth_callback_handler_delegates_to_fastmcp( monkeypatch: pytest.MonkeyPatch, ): - """The override must publish the callback URL and return FastMCP's result as-is. - - It used to reimplement FastMCP's callback_handler, which froze the return - type as a tuple. mcp 2.x expects an AuthorizationCodeResult and reads - `.state` off it, so the copy broke every OAuth install with - "'tuple' object has no attribute 'state'". Passing the base result through - untouched keeps this working across both contracts. - """ + """Return FastMCP's result untouched; re-wrapping it broke mcp 2.x.""" job = _MCPOAuthProbeJob( request=MCPTestRequest.model_validate( {"server": {"transport": "http", "url": "https://mcp.example.com/mcp"}}