diff --git a/.pr/issue-5276-after-pr.png b/.pr/issue-5276-after-pr.png new file mode 100644 index 00000000000..35b5615750b Binary files /dev/null and b/.pr/issue-5276-after-pr.png differ diff --git a/.pr/issue-5276-before-main.png b/.pr/issue-5276-before-main.png new file mode 100644 index 00000000000..b090f2909d4 Binary files /dev/null and b/.pr/issue-5276-before-main.png differ diff --git a/openhands-agent-server/openhands/agent_server/mcp_router.py b/openhands-agent-server/openhands/agent_server/mcp_router.py index cc8599cc001..211f8b328e0 100644 --- a/openhands-agent-server/openhands/agent_server/mcp_router.py +++ b/openhands-agent-server/openhands/agent_server/mcp_router.py @@ -56,7 +56,11 @@ MCPOAuthStateResponse, MCPServer, ) -from openhands.sdk.mcp.exceptions import MCPError, MCPTimeoutError +from openhands.sdk.mcp.exceptions import ( + MCPError, + MCPServerHTTPError, + MCPTimeoutError, +) from openhands.sdk.mcp.oauth import MCPOAuth from openhands.sdk.skills.utils import SecretLookup, expand_mcp_servers from openhands.sdk.utils.cipher import Cipher @@ -657,6 +661,11 @@ def _probe_mcp_server( message = scrub(str(exc)) logger.info("MCP test timed out for server %r: %s", request.name, message) return MCPTestFailure(error=message, error_kind="timeout") + except MCPServerHTTPError as exc: + # The server answered and refused: its reason is the useful part. + detail = scrub(str(exc)) + logger.warning("MCP test failed for server %r: %s", request.name, detail) + return MCPTestFailure(error=detail, error_kind="unknown") except MCPError as exc: # ``MCPError("MCP Connection Failure")`` is what client.connect() # raises when the underlying fastmcp client fails to start. Surface diff --git a/openhands-sdk/openhands/sdk/mcp/__init__.py b/openhands-sdk/openhands/sdk/mcp/__init__.py index c9e77adfbd0..446c8c57384 100644 --- a/openhands-sdk/openhands/sdk/mcp/__init__.py +++ b/openhands-sdk/openhands/sdk/mcp/__init__.py @@ -12,7 +12,11 @@ MCPServer, to_fastmcp_mcp_config, ) -from openhands.sdk.mcp.exceptions import MCPError, MCPTimeoutError +from openhands.sdk.mcp.exceptions import ( + MCPError, + MCPServerHTTPError, + MCPTimeoutError, +) if TYPE_CHECKING: @@ -56,5 +60,6 @@ def __getattr__(name: str): "create_mcp_tools", "to_fastmcp_mcp_config", "MCPError", + "MCPServerHTTPError", "MCPTimeoutError", ] diff --git a/openhands-sdk/openhands/sdk/mcp/exceptions.py b/openhands-sdk/openhands/sdk/mcp/exceptions.py index 6a627110c45..32bb004be97 100644 --- a/openhands-sdk/openhands/sdk/mcp/exceptions.py +++ b/openhands-sdk/openhands/sdk/mcp/exceptions.py @@ -17,3 +17,25 @@ def __init__(self, message: str, timeout: float, config: dict | None = None): self.timeout = timeout self.config = config super().__init__(message) + + +class MCPServerHTTPError(MCPError): + """An MCP server answered with an HTTP error status. + + The message names the status, the server's origin and the reason the + server gave, which the MCP client otherwise reduces to a stand-in such as + ``Server returned an error response`` or ``Session terminated``. + """ + + status_code: int + url: str + reason: str | None + + def __init__( + self, status_code: int, reason_phrase: str, url: str, reason: str | None + ): + self.status_code = status_code + self.url = url + self.reason = reason + message = f"HTTP {status_code} {reason_phrase} from {url}" + super().__init__(f"{message}: {reason}" if reason else message) diff --git a/openhands-sdk/openhands/sdk/mcp/utils.py b/openhands-sdk/openhands/sdk/mcp/utils.py index e3e2d75c832..33642049dde 100644 --- a/openhands-sdk/openhands/sdk/mcp/utils.py +++ b/openhands-sdk/openhands/sdk/mcp/utils.py @@ -2,8 +2,9 @@ import asyncio import inspect +import json import logging -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Awaitable, Callable, Mapping, Sequence from typing import Any, Protocol import httpx2 @@ -11,11 +12,12 @@ from fastmcp.client.auth import OAuth from fastmcp.client.logging import LogMessage from fastmcp.client.messages import MessageHandler -from fastmcp.client.transports import StreamableHttpTransport +from fastmcp.client.transports import SSETransport, StreamableHttpTransport from fastmcp.mcp_config import MCPConfig as FastMCPConfig, RemoteMCPServer from key_value.aio.protocols import AsyncKeyValue +from mcp.client.auth.utils import extract_field_from_www_auth from mcp.shared._httpx_utils import create_mcp_http_client -from pydantic import ValidationError +from pydantic import PrivateAttr, ValidationError from openhands.sdk.logger import get_logger from openhands.sdk.mcp.client import MCPClient, ToolsReconciledCallback @@ -26,7 +28,7 @@ enabled_mcp_servers, to_fastmcp_mcp_config, ) -from openhands.sdk.mcp.exceptions import MCPTimeoutError +from openhands.sdk.mcp.exceptions import MCPServerHTTPError, MCPTimeoutError from openhands.sdk.mcp.oauth import MCPOAuth from openhands.sdk.mcp.tool import MCPToolDefinition @@ -120,34 +122,74 @@ def _oauth_auth_from_authentication_config( ) -class _PackageRemoteMCPServer(RemoteMCPServer): - """A package-declared remote server whose headers stay on its own origin. +class _HTTPErrorLog: + """The last HTTP error response an MCP server's client received.""" - Agent Plugins §7.2.1: configured headers must not follow a redirect to a - different origin. httpx strips only ``Authorization`` there, so this - server's HTTP client drops every configured header name from any request - that leaves the configured origin. + def __init__(self) -> None: + self.last: httpx2.Response | None = None + + async def record(self, response: httpx2.Response) -> None: + if not response.is_error: + return + # A streamable-HTTP server without a server-to-client stream answers + # the client's GET with 405; the spec makes that a normal reply. + if response.status_code == 405 and response.request.method == "GET": + return + # The transport streams responses and may never read an error body. + await response.aread() + self.last = response + + +class _RemoteMCPServer(RemoteMCPServer): + """A remote server whose HTTP client reports the server's error responses. + + The MCP client turns an HTTP error from the server into a stand-in such as + ``Server returned an error response`` or ``Session terminated`` and drops + the response, so the server's reason (e.g. GitLab's "MCP server not + enabled for any of your groups") never reaches the user. This server's + client records its error responses in ``_http_errors`` instead. + + A package-declared server also keeps its headers on its own origin (Agent + Plugins §7.2.1): httpx strips only ``Authorization`` on a cross-origin + redirect, so every configured header name is dropped from any request + that leaves it. """ + _http_errors: _HTTPErrorLog = PrivateAttr(default_factory=_HTTPErrorLog) + _bind_headers_to_origin: bool = PrivateAttr(default=False) + def to_transport(self): # type: ignore[override] transport = super().to_transport() - if isinstance(transport, StreamableHttpTransport) and self.headers: - transport.httpx_client_factory = _origin_bound_client_factory( - self.url, tuple(self.headers) + if not isinstance(transport, (StreamableHttpTransport, SSETransport)): + return transport + request_hooks = [] + if self._bind_headers_to_origin and self.headers: + request_hooks.append( + _drop_headers_off_origin(self.url, tuple(self.headers)) ) + transport.httpx_client_factory = _mcp_http_client_factory( + request_hooks, self._http_errors.record + ) return transport -def _origin_bound_client_factory(url: str, header_names: tuple[str, ...]): +def _drop_headers_off_origin(url: str, header_names: tuple[str, ...]): origin = _origin(httpx2.URL(url)) - async def drop_headers_off_origin(request: httpx2.Request) -> None: + async def hook(request: httpx2.Request) -> None: # Request hooks run on every redirect hop, after httpx has copied the # previous request's headers onto the next one. if _origin(request.url) != origin: for name in header_names: request.headers.pop(name, None) + return hook + + +def _mcp_http_client_factory( + request_hooks: list[Callable[[httpx2.Request], Awaitable[None]]], + response_hook: Callable[[httpx2.Response], Awaitable[None]], +): def factory( headers: dict[str, str] | None = None, timeout: httpx2.Timeout | None = None, @@ -155,12 +197,88 @@ def factory( **_: object, ) -> httpx2.AsyncClient: client = create_mcp_http_client(headers=headers, timeout=timeout, auth=auth) - client.event_hooks = {"request": [drop_headers_off_origin], "response": []} + client.event_hooks = {"request": request_hooks, "response": [response_hook]} return client return factory +# What the MCP client reports instead of a streamable-HTTP error response. +_HTTP_ERROR_STAND_INS = frozenset( + {"Server returned an error response", "Session terminated", "Not Found"} +) +_HTTP_ERROR_REASON_MAX_CHARS = 300 + + +def _server_http_error( + exc: BaseException, config: FastMCPConfig +) -> MCPServerHTTPError | None: + """The HTTP error response behind ``exc``, if a server rejected a request.""" + if isinstance(exc, httpx2.HTTPStatusError): + response = exc.response + elif isinstance(exc, mcp.MCPError) and exc.message in _HTTP_ERROR_STAND_INS: + responses = [ + server._http_errors.last + for server in config.mcpServers.values() + if isinstance(server, _RemoteMCPServer) + ] + response = next((r for r in responses if r is not None), None) + else: + return None + if response is None: + return None + url = response.request.url + return MCPServerHTTPError( + status_code=response.status_code, + reason_phrase=response.reason_phrase, + url=f"{url.scheme}://{url.netloc.decode()}", + reason=_http_error_reason(response), + ) + + +def _http_error_reason(response: httpx2.Response) -> str | None: + """The most readable reason a server gave for rejecting a request. + + RFC 6750 puts it in ``WWW-Authenticate``'s ``error_description``, but most + servers send only an error code there and explain in a JSON body. + """ + try: + text = response.text.strip() + except httpx2.ResponseNotRead: + text = "" + candidates = [ + extract_field_from_www_auth(response, "error_description"), + *_json_body_reasons(text), + extract_field_from_www_auth(response, "error"), + text, + ] + reason = next((c for c in candidates if c), None) + if reason is None: + return None + reason = " ".join(reason.split()) + if len(reason) > _HTTP_ERROR_REASON_MAX_CHARS: + reason = reason[: _HTTP_ERROR_REASON_MAX_CHARS - 3] + "..." + return reason + + +def _json_body_reasons(text: str) -> list[str]: + try: + body = json.loads(text) + except ValueError: + return [] + if not isinstance(body, dict): + return [] + error = body.get("error") + candidates = [ + body.get("error_description"), + body.get("message"), + error.get("message") if isinstance(error, dict) else None, + body.get("detail"), + error, + ] + return [c for c in candidates if isinstance(c, str)] + + def _origin(url: httpx2.URL) -> tuple[str, str, int | None]: default_port = {"http": 80, "https": 443}.get(url.scheme) return url.scheme, url.host, url.port or default_port @@ -195,12 +313,13 @@ def _prepare_mcp_config( raise ValueError(f"No valid MCP servers among: {', '.join(sorted(servers))}") prepared = FastMCPConfig.model_validate({"mcpServers": valid}) - for server_name, server_spec in mcp_config.items(): - server = prepared.mcpServers.get(server_name) - if server_spec.literal_values and isinstance(server, RemoteMCPServer): - prepared.mcpServers[server_name] = _PackageRemoteMCPServer.model_validate( - server.model_dump() - ) + for server_name, server in list(prepared.mcpServers.items()): + if not isinstance(server, RemoteMCPServer): + continue + remote = _RemoteMCPServer.model_validate(server.model_dump()) + spec = mcp_config.get(server_name) + remote._bind_headers_to_origin = spec is not None and spec.literal_values + prepared.mcpServers[server_name] = remote for server_name, server_spec in mcp_config.items(): auth = server_spec.auth @@ -463,13 +582,16 @@ def create_mcp_tools( raise MCPTimeoutError( error_msg, timeout=timeout, config=config.model_dump() ) from e - except BaseException: + except BaseException as exc: try: client.sync_close() except Exception as close_exc: logger.warning( "Failed to close MCP client during error cleanup", exc_info=close_exc ) + http_error = _server_http_error(exc, config) + if http_error is not None: + raise http_error from exc raise logger.info("Created %d MCP tools", len(client.tools)) diff --git a/tests/agent_server/test_mcp_router.py b/tests/agent_server/test_mcp_router.py index 842838cb129..c79b9c45586 100644 --- a/tests/agent_server/test_mcp_router.py +++ b/tests/agent_server/test_mcp_router.py @@ -14,6 +14,7 @@ import httpx import pytest from fastapi.testclient import TestClient +from fastmcp import FastMCP from pydantic import SecretStr from openhands.agent_server.api import create_app @@ -43,8 +44,11 @@ # is perfectly portable and exercises the same connect/list-tools code path # the endpoint relies on. from tests.sdk.mcp.test_create_mcp_tool import ( # noqa: E402 + _GITLAB_REASON, MCPTestServer, + RejectRequests, _find_free_port, + _serve, ) @@ -949,6 +953,28 @@ def test_mcp_test_remote_unreachable(client: TestClient): assert body["error_kind"] in {"connection", "timeout"} +def test_mcp_test_reports_the_reason_a_server_rejected_the_connection( + client: TestClient, +): + app = FastMCP("rejecting-server").http_app(path="/mcp") + app.add_middleware(RejectRequests) + with _serve(app) as port: + response = client.post( + "/api/mcp/test", + json={ + "server": {"transport": "http", "url": f"http://127.0.0.1:{port}/mcp"}, + "timeout": 10.0, + }, + ) + + assert response.status_code == 200, response.text + assert response.json() == { + "ok": False, + "error": f"HTTP 403 Forbidden from http://127.0.0.1:{port}: {_GITLAB_REASON}", + "error_kind": "unknown", + } + + # --------------------------------------------------------------------------- # Validation # --------------------------------------------------------------------------- diff --git a/tests/sdk/mcp/test_create_mcp_tool.py b/tests/sdk/mcp/test_create_mcp_tool.py index 8f8dc583313..9f82c31863e 100644 --- a/tests/sdk/mcp/test_create_mcp_tool.py +++ b/tests/sdk/mcp/test_create_mcp_tool.py @@ -7,20 +7,23 @@ import threading import time from collections.abc import Generator +from contextlib import contextmanager from pathlib import Path from typing import Literal from unittest.mock import MagicMock, patch import httpx +import httpx2 import pytest import uvicorn from fastmcp import FastMCP from fastmcp.client.auth import OAuth from fastmcp.mcp_config import MCPConfig as FastMCPConfig, RemoteMCPServer from key_value.aio.stores.memory import MemoryStore +from mcp import MCPError as MCPClientError from pydantic import SecretStr from starlette.middleware.base import BaseHTTPMiddleware -from starlette.responses import PlainTextResponse +from starlette.responses import JSONResponse, PlainTextResponse from openhands.sdk.mcp import create_mcp_tools from openhands.sdk.mcp.config import ( @@ -34,9 +37,13 @@ coerce_mcp_config, to_fastmcp_mcp_config, ) -from openhands.sdk.mcp.exceptions import MCPError, MCPTimeoutError +from openhands.sdk.mcp.exceptions import ( + MCPError, + MCPServerHTTPError, + MCPTimeoutError, +) from openhands.sdk.mcp.oauth import MCPOAuth -from openhands.sdk.mcp.utils import _prepare_mcp_config +from openhands.sdk.mcp.utils import _http_error_reason, _prepare_mcp_config logger = logging.getLogger(__name__) @@ -865,3 +872,129 @@ async def dispatch(self, request, call_next): finally: server.should_exit = True thread.join(timeout=5) + + +_GITLAB_REASON = "403 Forbidden - MCP server not enabled for any of your groups" + + +class RejectRequests(BaseHTTPMiddleware): + """Answer MCP requests the way GitLab does when MCP is off for the user.""" + + async def dispatch(self, request, call_next): + return JSONResponse({"message": _GITLAB_REASON}, status_code=403) + + +class EndSessionOnToolsList(BaseHTTPMiddleware): + """Initialize normally, then answer ``tools/list`` with a plain-text 404.""" + + async def dispatch(self, request, call_next): + body = (await request.body()).replace(b" ", b"") + if b'"method":"tools/list"' in body: + return PlainTextResponse("session not found", status_code=404) + return await call_next(request) + + +@contextmanager +def _serve(app) -> Generator[int]: + port = _find_free_port() + server = uvicorn.Server( + uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error") + ) + thread = threading.Thread(target=server.run, daemon=True) + thread.start() + _wait_for_port(port) + try: + yield port + finally: + server.should_exit = True + thread.join(timeout=5) + + +@pytest.mark.parametrize("transport", ["http", "sse"]) +def test_create_mcp_tools_reports_the_server_reason_for_an_http_error( + transport: MCPTransport, +): + path = "/sse" if transport == "sse" else "/mcp" + app = FastMCP("rejecting-server").http_app(path=path, transport=transport) + app.add_middleware(RejectRequests) + with _serve(app) as port: + config = { + "gitlab": { + "transport": transport, + "url": f"http://user:hunter2@127.0.0.1:{port}{path}?token=abc123", + } + } + with pytest.raises(MCPServerHTTPError) as exc_info: + create_mcp_tools(coerce_mcp_config(config), timeout=10) + + error = exc_info.value + assert str(error) == ( + f"HTTP 403 Forbidden from http://127.0.0.1:{port}: {_GITLAB_REASON}" + ) + assert (error.status_code, error.reason) == (403, _GITLAB_REASON) + assert error.__cause__ is not None + + +def test_create_mcp_tools_reports_the_http_error_behind_a_404_stand_in(): + server = FastMCP("session-ending-server") + + @server.tool() + def ping() -> str: + return "pong" + + app = server.http_app(path="/mcp", stateless_http=False) + app.add_middleware(EndSessionOnToolsList) + with _serve(app) as port: + config = { + "server": {"transport": "http", "url": f"http://127.0.0.1:{port}/mcp"} + } + with pytest.raises(MCPServerHTTPError) as exc_info: + create_mcp_tools(coerce_mcp_config(config), timeout=10) + + assert str(exc_info.value) == ( + f"HTTP 404 Not Found from http://127.0.0.1:{port}: session not found" + ) + # The MCP client reports the 404 as "Session terminated" or "Not Found". + assert isinstance(exc_info.value.__cause__, MCPClientError) + + +@pytest.mark.parametrize( + ("headers", "body", "reason"), + [ + pytest.param( + { + "WWW-Authenticate": 'Bearer error="invalid_token", ' + 'error_description="The token expired"' + }, + '{"message": "ignored"}', + "The token expired", + id="www-authenticate-description", + ), + pytest.param( + {"WWW-Authenticate": 'Bearer error="insufficient_scope"'}, + "", + "insufficient_scope", + id="www-authenticate-error-code", + ), + pytest.param( + {}, + '{"jsonrpc": "2.0", "id": 1, "error": {"code": -32600, "message": "No"}}', + "No", + id="json-rpc-error", + ), + pytest.param({}, '{"detail": "Not allowed"}', "Not allowed", id="detail"), + pytest.param({}, '{"error": "access_denied"}', "access_denied", id="error"), + pytest.param({}, " plain\n text ", "plain text", id="plain-text"), + pytest.param({}, "x" * 400, "x" * 297 + "...", id="long-body-is-cut"), + pytest.param({}, "", None, id="empty-body"), + ], +) +def test_http_error_reason(headers: dict, body: str, reason: str | None): + response = httpx2.Response( + 403, + headers=headers, + text=body, + request=httpx2.Request("POST", "https://example.com/mcp"), + ) + + assert _http_error_reason(response) == reason