diff --git a/openhands-agent-server/openhands/agent_server/mcp_router.py b/openhands-agent-server/openhands/agent_server/mcp_router.py index be518b2117f..0344776644d 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,21 @@ 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, - ) - 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, - ) + async def callback_handler(self): + """Publish the callback URL, then defer to FastMCP. - 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") + 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) + 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..c43f8633e1c 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,10 @@ 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, ): + """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"}} @@ -783,48 +783,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 + sentinel = object() + seen: list[bool] = [] - 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) - - 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):