Skip to content

fix(mcp): show the HTTP status and server reason when an MCP server rejects a connection - #5349

Open
seek-far wants to merge 3 commits into
OpenHands:mainfrom
seek-far:fix/mcp-probe-surface-http-error
Open

seek-far wants to merge 3 commits into
OpenHands:mainfrom
seek-far:fix/mcp-probe-surface-http-error

Conversation

@seek-far

@seek-far seek-far commented Sep 27, 2026 •

Copy link
Copy Markdown

HUMAN:

#5276 I have reproduced the issue in AgentCanvas with gitlab.com using two of my accounts. I have made efforts to make the code change cleaner and more maintainable. I have also done comparison tests before and after the code change.


AGENT:

Why

An MCP server can reject a connection with an HTTP error that explains the problem. In #5276, GitLab completed OAuth and then answered 403 {"message":"403 Forbidden - MCP server not enabled for any of your groups"}. OpenHands hid that reason. On current main, the mcp 2.x client turns an HTTP error from a streamable-HTTP server into Server returned an error response, Session terminated or Not Found and drops the response. For SSE it raises an HTTPStatusError whose body was never read. Agent Canvas showed Connection failed: MCPError: Server returned an error response, and the agent-server log showed only MCP test failed unexpectedly.

Summary

  • SDK (openhands/sdk/mcp/utils.py): the HTTP client of every remote MCP server (streamable HTTP and SSE) records the last 4xx/5xx response and reads its body. A GET answered with 405 is ignored, because the spec allows it. When create_mcp_tools() fails with an HTTPStatusError or one of the three stand-ins above, it raises the new MCPServerHTTPError(MCPError) from the original error. Its message is HTTP <status> <phrase> from <scheme://host:port>: <reason>. The reason comes from the WWW-Authenticate error_description, then the JSON body (error_description, message, JSON-RPC error.message, detail, a string error), then the WWW-Authenticate error, then the body text, capped at 300 characters. The URL keeps only the origin, so no userinfo, query or path. _PackageRemoteMCPServer becomes _RemoteMCPServer and keeps the Agent Plugins §7.2.1 off-origin header drop for package servers.
  • agent-server (mcp_router.py): /api/mcp/test and the OAuth test flow return that message with error_kind="unknown", which Canvas renders as Connection failed: <message>. The router also logs the message as a WARNING.
  • This takes over fix(mcp): show the HTTP status and server reason when an MCP server rejects a connection #5349. The original design was written for mcp 1.x/httpx and no longer applies after the mcp 2.x upgrade. This version merges main and reworks the fix.

Issue Number

Fixes #5276

How to Test

Agent Canvas end-to-end (OAuth + 403).

  1. Run Agent Canvas main (46f20aba) against an agent-server from this branch: OH_AGENT_SERVER_LOCAL_PATH=<this repo> npm run dev:minimal in OpenHands.
  2. Start a local mock MCP provider that implements real OAuth (dynamic client registration, consent page, token endpoint). After authorization it answers every MCP request with GitLab's 403 body.
  3. On /mcp, choose Add custom server → SHTTP → http://127.0.0.1:9301/mcp → OAuth → Test connection, then click Authorize in the popup.
  • main: Connection failed: MCPError: Server returned an error response.
  • This PR: Connection failed: HTTP 403 Forbidden from http://127.0.0.1:9301: 403 Forbidden - MCP server not enabled for any of your groups.
  • Regression check: an OAuth mock that serves tools still shows Connected — 2 tool(s) available.

Unit and integration tests (real local FastMCP/uvicorn servers, no mocks):

uv run pytest tests/sdk/mcp/test_create_mcp_tool.py -k "http_error or stand_in"
uv run pytest tests/agent_server/test_mcp_router.py -k rejected
  • test_create_mcp_tools_reports_the_server_reason_for_an_http_error[http|sse]: the server answers 403. The config URL carries user:hunter2@…?token=abc123, and the error must equal HTTP 403 Forbidden from http://127.0.0.1:<port>: <reason> exactly.
  • test_create_mcp_tools_reports_the_http_error_behind_a_404_stand_in: initialize succeeds, then tools/list gets a plain-text 404. The mcp client reports it as a stand-in, and the error is HTTP 404 Not Found from …: session not found.
  • test_http_error_reason[...]: 8 response shapes (WWW-Authenticate description and code, JSON-RPC, detail, error, plain text, truncation, empty body).
  • test_mcp_test_reports_the_reason_a_server_rejected_the_connection: the /api/mcp/test response body equals the expected JSON.
  • tests/sdk/mcp, tests/sdk/plugin, tests/agent_server/test_mcp_router.py and tests/sdk/conversation/test_local_conversation_{mcp,agent_plugins}.py pass locally (695). ruff and pyright are clean.

Video/Screenshots

Before (main 91e8b5b): OAuth completes, then the test hides the reason.

before

After (this PR): same flow; Canvas shows the status and the server's reason.

after

The original contributor's real-GitLab "before" screenshot, taken on an older release: gitlab-shttp-403-before.png

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

  • create_mcp_tools() now raises MCPServerHTTPError (a subclass of openhands.sdk.mcp.MCPError, exported from openhands.sdk.mcp) in place of the raw mcp MCPError or httpx2.HTTPStatusError, chained as __cause__. No caller in this repo catches those types.
  • Tool-call errors after a successful connection (Error calling MCP tool …) are out of scope.
  • fix(agent-server): surface HTTP error body in MCP probe failures #5346 targets the same issue in agent-server only. It cannot read the response body, so it reports only the status. I will comment there.
  • The old .pr/ evidence for the mcp 1.x design has been replaced; it is still available at commit 41b8474.

This comment/PR was created by an AI agent (OpenHands) on behalf of Graham Neubig.

seek-far and others added 2 commits September 27, 2026 23:12
The mcp client streams requests and calls raise_for_status() before
reading the body, so HTTPStatusError.response.text raised
ResponseNotRead and /api/mcp/test showed only httpx's generic message;
GitLab's "MCP server not enabled for any of your groups" was lost.

- SDK: every remote MCP server (streamable HTTP and SSE) now gets an
  httpx client whose response hook reads 4xx/5xx bodies.
  _PackageRemoteMCPServer becomes _HookedRemoteMCPServer and keeps the
  Agent Plugins off-origin header drop (section 7.2.1) for package
  servers.
- agent-server: /api/mcp/test handles HTTPStatusError and returns
  "HTTP <status> <phrase> from <url>: <reason>", taking the reason from
  the WWW-Authenticate error_description, common JSON body fields, then
  the raw body. The URL drops userinfo, query and fragment; error_kind
  stays "unknown".

Refs OpenHands#5276

Co-authored-by: openhands <openhands@all-hands.dev>
Design doc, Agent Canvas before/after screenshots, agent-server log
excerpts and the Agent Plugins matrix script. The .pr/ directory is
PR-only and removed by the PR Artifacts workflow.

Refs OpenHands#5276

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

github-actions Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

📁 PR Artifacts Notice

This PR adds or changes temporary PR-specific documents under .pr/. They stay available on this branch for review; after merge, the next release PR removes .pr/ from main.

…n errors

Merge main and rework the fix for the mcp 2.x client, which reports an HTTP
error from a streamable-HTTP server as 'Server returned an error response',
'Session terminated' or 'Not Found' and drops the response. Every remote
server's HTTP client now records its error responses, and create_mcp_tools
raises MCPServerHTTPError (status, origin, server reason) from the original
error. /api/mcp/test returns that message.

Fixes OpenHands#5276

Co-authored-by: openhands <openhands@all-hands.dev>
@neubig neubig changed the title fix(mcp): surface the server's reason for HTTP 4xx/5xx in MCP tests fix(mcp): show the HTTP status and server reason when an MCP server rejects a connection Nov 13, 2026
@neubig
neubig marked this pull request as ready for review November 13, 2026 23:50
@neubig
neubig requested a review from all-hands-bot November 13, 2026 23:52
@neubig
neubig marked this pull request as draft November 14, 2026 00:16
@neubig
neubig marked this pull request as ready for review November 14, 2026 01:33
@neubig
neubig requested review from all-hands-bot and removed request for all-hands-bot November 14, 2026 01:33

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This review was posted by an AI agent (OpenHands).

Scope: The change belongs here — MCP tool-creation behavior and the /api/mcp/test error contract are owned by this repository (SDK + Agent Server per AGENTS.md cross-repository boundaries).

Code review result: I verified the implementation against the repository guidance and found no material correctness, security, or compatibility defect on head 5d5bbb5a:

  • MCPServerHTTPError subclasses MCPError and is raised with __cause__ chained; the router's probe handler catches it before the generic MCPError branch (verified handler order), so the server's status/reason reaches both the direct /api/mcp/test response and the OAuth status endpoint, which forwards error/error_kind from the failure result.
  • The _HTTPErrorLog response hook awaits aread() before storing, so the SSE path's later HTTPStatusError handling can read .text without hitting ResponseNotRead (verified empirically on the httpx2 response objects this code produces).
  • Reason extraction follows the documented precedence (WWW-Authenticate error_description → JSON body fields → WWW-Authenticate error → raw body) with a 300-char cap and whitespace normalization; extract_field_from_www_auth semantics verified against the installed mcp version.
  • The origin-only URL (scheme://host:port) keeps userinfo, query, and path out of the new error message, matching the acceptance criteria in #5276; the message itself carries no credentials.
  • The _PackageRemoteMCPServer → _RemoteMCPServer rename preserves the Agent Plugins §7.2.1 off-origin header drop, now gated on _bind_headers_to_origin (set only for package-declared servers with literal_values), and extends the error-recording client factory to both streamable-HTTP and SSE transports. No other code references the old class name.
  • Multi-server configs record per-server error logs and the message names the origin it came from, so a wrong-server attribution cannot present a false URL.
  • Workspace test runs: tests/agent_server/test_mcp_router.py 52/52 passed (including test_mcp_test_reports_the_reason_a_server_rejected_the_connection), tests/sdk/plugin 431 passed, the new focused MCP tests (http_error, stand_in, reason) 12/12 passed, tests/sdk/conversation/test_local_conversation_mcp.py 12/13 with the single failure (test_slow_mcp_servers_start_side_by_side) reproducing identically on main (pre-existing timing-sensitive test, untouched by this diff). ruff check, ruff format --check, and pyright are clean on all changed files.

Blocking finding (non-code, must be resolved before merge): The required Validate PR description check fails on this exact head (run 43541290077): "Linked issue(s) (#5276) carry neither ready-for-dev nor a pre-rollout creation date." Issue #5276 was created 2026-09-23 (after the 2026-08-13 rollout date in .github/scripts/check_pr_description.py) and currently carries no labels, so the PR's mergeable_state is blocked. This gate is owned by the deterministic automation/maintainers, not by code in this diff, and the technical work itself is ready; the linked issue needs the ready-for-dev label (or a maintainer-granted exception per the readiness policy) before this PR can merge.

No inline findings: the two notable hardening observations (the chained __cause__ HTTPStatusError still embeds the full config URL for non-router consumers, and the stand-in mapping relies on mcp client message strings) are suggestions/defense-in-depth notes rather than demonstrated defects, since every in-repo consumer scrubs and no caller depends on the raw stand-in types.

🔄 CHANGES REQUESTED

@seek-far

Copy link
Copy Markdown
Author

@neubig Thanks for taking this over and reworking it for the mcp 2.x client.

I retested 5d5bbb5 end to end against gitlab.com, with Agent Canvas at 46f20aba (npm run dev:minimal) and two real GitLab accounts:

  • Account with MCP enabled in none of its groups (SHTTP + OAuth): Canvas shows Connection failed: HTTP 403 Forbidden from https://gitlab.com: 403 Forbidden - MCP server not enabled for any of your groups, and the agent-server logs the same reason as a WARNING.
  • Account in a group with MCP enabled (SHTTP + OAuth): Connected — 42 tool(s) available, the same tool count as my September run, so normal connections are unaffected.

For comparison, current main (5e49ddac5, without the fix) with the first account shows Connection failed: MCPError: Server returned an error response. The log has only MCP test failed unexpectedly, with a traceback that ends in the same stand-in and contains neither the status nor GitLab's reason.

I noticed that ready-for-dev was added to #5276 and then removed shortly afterwards, so Validate PR description still fails on this head. Would you mind sharing why it was removed? If there's anything I can help with, feel free to let me know.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: GitLab MCP OAuth succeeds but MCP test fails with Session terminated

3 participants