Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .pr/issue-5276-after-pr.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added .pr/issue-5276-before-main.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 10 additions & 1 deletion openhands-agent-server/openhands/agent_server/mcp_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion openhands-sdk/openhands/sdk/mcp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -56,5 +60,6 @@ def __getattr__(name: str):
"create_mcp_tools",
"to_fastmcp_mcp_config",
"MCPError",
"MCPServerHTTPError",
"MCPTimeoutError",
]
22 changes: 22 additions & 0 deletions openhands-sdk/openhands/sdk/mcp/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
168 changes: 145 additions & 23 deletions openhands-sdk/openhands/sdk/mcp/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,22 @@

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
import mcp.types
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
Expand All @@ -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

Expand Down Expand Up @@ -120,47 +122,163 @@ 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,
auth: httpx2.Auth | None = None,
**_: 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand Down
26 changes: 26 additions & 0 deletions tests/agent_server/test_mcp_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
)


Expand Down Expand Up @@ -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
# ---------------------------------------------------------------------------
Expand Down
Loading
Loading