Repository navigation
fix(server): answer -32601 Method not found for JSON-RPC methods the MCP SDK cannot route - #5923
akushonkamen wants to merge 2 commits into
Conversation
…MCP SDK cannot route The pinned mcp SDK (mcp>=1.27,<2) validates every request against its ClientRequest union and maps any validation failure to INVALID_PARAMS (mcp/shared/session.py), so unknown methods — including the 2026-07-28-era server/discover probe — are answered -32602 instead of the spec-compliant -32601. Clients treat -32602 as a fixable-parameter error rather than the definitive legacy-fallback signal and keep re-probing before falling back. The proper fix is upstream (modelcontextprotocol/python-sdk#3557); this adds a repo-side compatibility shim. _MethodPrecheckASGIMiddleware resolves the JSON-RPC method before the request enters the SDK and answers -32601 for methods outside the known set, which is derived from the installed SDK's ClientRequestType union at init time so it tracks SDK upgrades (fail-open when introspection fails). Unparseable bodies, batch payloads, notifications (no id), known methods, non-POST requests and clients that cannot accept application/json are passed through untouched, keeping SDK-owned behavior (parse errors, -32602 parameter errors, 406 accept negotiation) unchanged. Regression tests cover the derived method set, -32601 for server/discover and arbitrary unknown methods, and pass-through for known methods, notifications, unparseable/batch bodies, non-POST verbs and SSE-only Accept headers. AI-assisted contribution: investigation and patch prepared with AI assistance under human review. Fixes volcengine#5841 Signed-off-by: akushonkamen <akushonkamen@163.com>
ehz0ah
left a comment
There was a problem hiding this comment.
The unknown-method correction works, but the early response changes existing request validation. Please address the two inline findings before merge.
I tested the exact middleware from 8adf8b1e against real loopback FastMCP HTTP servers with MCP SDK 1.29.0 and 1.30.0, comparing the original handler with the wrapped handler. I checked 18 cases on each version. Initialization, tools/list and tools/call still worked. The 12 added middleware test cases also passed when run in isolation. This was a protocol-level reproduction, not a full OpenViking service run.
| if key == b"accept": | ||
| accept = value.decode("latin-1").lower() | ||
| break | ||
| if not _accepts_json(accept): |
There was a problem hiding this comment.
[Bug] (blocking) Preserve the SDK's HTTP validation before returning the unknown-method error.
With this valid body:
{"jsonrpc":"2.0","id":7,"method":"server/discover","params":{}}and Content-Type: application/json, the real SDK handler returns HTTP 406 for Accept: application/json. This middleware returns HTTP 200 / -32601. With the normal Accept: application/json, text/event-stream but MCP-Protocol-Version: invalid, the result changes from HTTP 400 to HTTP 200 / -32601. Both reproduce on SDK 1.29.0 and 1.30.0.
No tool executes, but the client gets a method error instead of the transport error. Please preserve these checks and cover them against the real SDK handler. The recording downstream in the current tests cannot detect this regression.
There was a problem hiding this comment.
Fixed in 716fd8f. The middleware no longer intercepts requests the SDK transport would reject — it mirrors the transport's HTTP-layer gates and passes through on any doubt, so a request the SDK answers 406/400 keeps that response:
- Accept: interception now requires both
application/jsonandtext/event-stream(mirroringStreamableHTTPServerTransport._check_accept_headersin the default SSE response mode; requiring both is the conservative intersection that also passes ifis_json_response_enabledwere on).Accept: application/jsonalone now falls through and gets the SDK's 406. - MCP-Protocol-Version: a present header whose value is not in
mcp.shared.version.SUPPORTED_PROTOCOL_VERSIONS(imported from the installed SDK, same source_validate_protocol_versionchecks against) is passed through and keeps the SDK's 400. The header is imported at init; if the SDK ever stops exposing the set, carrying the header disables interception entirely (fail-safe). - Content-Type (same regression class, covered proactively): a non-
application/jsonContent-Type is also passed through now — the SDK's transport security rejects those POSTs with 400 (and the transport itself checks 415) before the method matters.
Coverage, against the real SDK handler as requested: test_precheck_matches_real_sdk_transport_for_non_interceptable_requests drives a real FastMCP Streamable HTTP app raw and middleware-wrapped (same composition as create_mcp_app: middleware over the SDK route handler, session manager started via its lifespan) and asserts byte-identical responses for accept-missing-event-stream (406), unsupported-protocol-version (400), content-type-not-json (400) plus the three envelope cases. Unit-level gates: test_precheck_passes_unknown_method_through_when_accept_lacks_event_stream, ..._when_protocol_version_unsupported, ..._when_content_type_not_json, each asserting the downstream SDK handler is reached with the body intact. The old _accepts_json check (which only required some JSON acceptance) is gone.
Numbers: precheck/parity subset 25 passed (was 12); tests/server/ -k "mcp or endpoint": 333 passed, 3 failed — the same 3 failures (test_write_append_missing_file_fails, test_forget_directory_without_recursive_fails, test_mcp_skill_import_and_vector_rebuild_preserve_l1_frontmatter) reproduce identically on unmodified 8adf8b1, pre-existing environmental, not introduced here.
| if not message.get("more_body", False): | ||
| break | ||
|
|
||
| payload = _parse_jsonrpc_request(body) |
There was a problem hiding this comment.
[Bug] (blocking) Only intercept a valid JSON-RPC request.
_parse_jsonrpc_request() checks the method string, but not the envelope. With normal MCP headers, this malformed body:
{"jsonrpc":"1.0","id":7,"method":"server/discover","params":{}}returns HTTP 400 / -32602 through the original SDK handler, but HTTP 200 / -32601 with this middleware. Missing jsonrpc or a string params produces the same change. I reproduced all three on SDK 1.29.0 and 1.30.0.
Please leave malformed messages on the SDK's existing validation path. The correction should change only the error for a valid request whose method is unsupported.
There was a problem hiding this comment.
Fixed in 716fd8f. Envelope validation is no longer hand-rolled: _parse_jsonrpc_request now validates the body with mcp.types.JSONRPCMessage.model_validate — the exact model StreamableHTTPServerTransport._handle_post_request validates against — and only a decoded JSONRPCRequest can proceed to interception. So:
{"jsonrpc":"1.0", ...}(literal mismatch), a missingjsonrpcmember, and a stringparamsall fail validation and fall through to the SDK's existing 400 / INVALID_PARAMS path, exactly as before the shim existed. Batches, notifications (noid) and responses never validate asJSONRPCRequestand keep their SDK answers too (202 / -32700 / routing).- Interception now requires all three: valid envelope and method outside the SDK-derived known set and pass of the transport's Content-Type/Accept/protocol-version gates (see the reply on the other finding). "The correction changes only the error for a valid request whose method is unsupported" is now literally the code path.
Parity for your three reproductions is pinned against the real FastMCP Streamable HTTP handler in test_precheck_matches_real_sdk_transport_for_non_interceptable_requests (cases wrong-jsonrpc-version, missing-jsonrpc, params-not-an-object: raw and wrapped responses byte-identical, both 400), plus unit-level test_precheck_passes_malformed_envelopes_to_sdk asserting the bodies reach the downstream SDK handler unchanged. The intended change is pinned by test_precheck_answers_32601_where_real_sdk_answers_32602: valid envelope + server/discover + compliant headers → raw SDK answers -32602 (SSE frame), wrapped answers -32601.
Numbers: precheck/parity subset 25 passed; tests/server/ -k "mcp or endpoint" 333 passed / 3 pre-existing environmental failures (reproduced identically on unmodified 8adf8b1).
Blocking review on volcengine#5923 showed the pre-check middleware answered -32601 for requests the SDK transport itself rejects, silently changing transport-level outcomes: - `Accept: application/json` alone (SDK: 406 in the default SSE response mode) and `MCP-Protocol-Version: invalid` (SDK: 400) got HTTP 200 / -32601 instead. - Malformed envelopes the transport answers 400 / INVALID_PARAMS (jsonrpc "1.0", missing jsonrpc, non-object params) were intercepted too, because the hand-rolled parse only looked at `method`. The middleware now intercepts only when the SDK transport would have accepted the request. Envelope validation is delegated to the SDK's own `mcp.types.JSONRPCMessage` model — the exact one `StreamableHTTPServerTransport._handle_post_request` uses — so parse errors, wrong/missing jsonrpc, non-object params, batches, notifications and responses all keep the SDK's existing answer. Before intercepting, the middleware also mirrors the transport's Content-Type, Accept and MCP-Protocol-Version gates (importing the SDK's supported-version set), passing through on any doubt, so a request the SDK answers 406/400 keeps that response byte-identical. Parity is pinned against a real FastMCP Streamable HTTP handler driven raw and middleware-wrapped (same composition as create_mcp_app), both for the non-interceptable cases and for the one intended difference (valid envelope + unknown method: raw SDK -32602, shim -32601). Signed-off-by: akushonkamen <akushonkamen@163.com> Co-authored-by: GLM (glm-5.3-flash) <noreply@anthropic.com>
|
Reporter here (the DSH host in #5841). I ran this end-to-end on the real chain, and it changes what I would claim for this PR. The chain
A/B on the real chainUsing the SDK DSH actually loads (
So the error code alone does not break the client — it falls back cleanly either way, which matches @r266-tech. I am withdrawing the "this unblocks DSH" implicationWhat produced our retries was a startup race, not the error code:
Still in favour of the change
I am correcting the issue title and posting the full numbers in #5841. |
|
Thank you for running this end-to-end on the real DSH chain — that A/B is far more valuable than the synthetic reasoning in the original claim, and the correction is appreciated. Two takeaways on our side: first, we accept your withdrawal of the "this unblocks DSH" implication — the retries were a startup race (client knocking ~2.5 s before the streamable session manager was up), not the error code, so this PR should be judged purely as a spec-correctness fix. Second, your numbers independently confirm the client falls back cleanly with either code, which supports r266-tech's report and our own reading. We agree with your conclusion: unknown methods should answer -32601, and the change is worth keeping on its own merits. Thanks also for cross-checking the derived known-set against the installed SDK's routable methods; the envelope-validation and transport-gate fixes you noted in 716fd8f are covered in the replies to the inline findings above. |
|
The two inline findings are addressed by Two items still block merge from this side:
Requesting a final review when convenient. Disclosure: this comment was prepared with AI assistance (analysis and GitHub API readings); the numbers above were verified against the GitHub API immediately before posting. |
|
The two original envelope/transport findings are fixed for single-valued headers at One transport-parity case remains: The same difference occurs with duplicate protocol-version or content-type headers: rejected first value, acceptable last value gives raw 400, wrapped 200. Please use the same header lookup as the SDK (e.g. Starlette AI disclosure: this review and its isolated tests were produced by an AI agent; the results above were executed locally. |
|
On the remaining duplicate-header case raised above: it is not reachable from the DSH side, based on the proxy that is actually loaded here. What is running:
How the outgoing headers are built:
and that object is passed as the request One caveat, for completeness: the proxy does expose an operator escape hatch ( On the finding itself: I am not disputing it. For a client that can emit duplicate headers, the middleware's last-wins dict conversion is a genuine SDK-parity gap, and pinning the single-valued case does not cover it. It just does not block the DSH path; if it is cheap to align the dict conversion with the SDK's first-wins Related, on the new protocol-version gate: this proxy always sends Merge status from the reporter side (unchanged): the branch is Disclosure: this comment was prepared with AI assistance; the referenced source lines, the header construction behaviour, and the API readings above were verified before posting. |
|
Thanks for the thorough trace — the header-construction analysis makes the reachability picture clear. Agreed on the takeaway: the duplicate-header last-wins dict conversion is a real SDK-parity gap even though the DSH path can't produce it, and aligning the middleware with the SDK's first-wins |
Description
POST /mcpcurrently answers JSON-RPC methods the MCP SDK cannot route — including the 2026-07-28-eraserver/discoverprobe and any arbitrary unknown method — with-32602 Invalid request parametersinstead of the spec-compliant-32601 Method not found. This PR adds a small pure-ASGI middleware that answers-32601for methods outside the SDK's known request set, before the request reaches the SDK, while passing everything else through untouched.Human Involvement
Related Issue
Fixes #5841
Type of Change
Changes Made
mcp>=1.27,<2(pyproject.toml) pins a version whosemcp/shared/session.py_receive_loopvalidates every request against theClientRequestunion and maps any validation failure toINVALID_PARAMSvia a genericexcept, so theMETHOD_NOT_FOUNDbranch is unreachable. The transport layer (streamable_http.py) only validates the envelope, so unknown methods do reach the session layer. Confirmed against the installed package source on this machine, matching the reporter's venv observation._MethodPrecheckASGIMiddlewareinopenviking/server/mcp_endpoint.py, composed at the existingcreate_mcp_app()seam (_IdentityASGIMiddlewarestays the outermost layer). OnPOST, it resolves the JSON-RPCmethod; if it is outside the known set it answers-32601 Method not founddirectly. The known set is derived at init from the installed SDK'smcp.types.ClientRequestTypeunion membermethodLiterals (so it tracks SDK upgrades), failing open (pass-through) if introspection fails.id), known methods, non-POST requests, and clients that cannot acceptapplication/json(SSE-onlyAcceptkeeps the SDK's 406).Testing
Before the fix (red, live server on
8adf8b1e's parent), the issue's three curls returned-32602for bothserver/discoverandtotally/unknownwith 2Failed to validate requestlog lines. After the fix (green, re-run live):server/discoverandtotally/unknown→{"code":-32601,"message":"Method not found"};initializestill down-negotiates toprotocolVersion: 2025-11-25;tools/listunchanged.tools/callwith bad params still returns the SDK's-32602; a notification withoutidstill gets202; SSE-onlyAcceptstill gets the SDK's406; zero validation warnings from the unknown-method path (only the expected SDK-side warning for the bad-paramstools/callprobe).OPENVIKING_CONFIG_FILE=... uv run python -m pytest tests/server/test_mcp_endpoint.py -q -k "precheck or method_literals"→ 12 passed (new tests cover the derived method set,-32601for unknown methods, and pass-through for known methods/notifications/unparseable/batch bodies/non-POST/SSE-only Accept/fail-open).uv run python -m pytest tests/server/ -q -k "mcp or endpoint" -n 4 --no-cov -o addopts=''→ 320 passed, 3 failed; all 3 failures (test_write_append_missing_file_fails,test_forget_directory_without_recursive_fails,test_mcp_skill_import_and_vector_rebuild_preserve_l1_frontmatter) reproduce identically on clean parent4c9a755bviagit worktree— pre-existing environmental failures, not introduced here.ruff checkandruff format --checkclean on both changed files.Checklist
Screenshots (if applicable)
Not applicable — no UI change; live curl transcripts are quoted above under Testing.
Additional Notes
modelcontextprotocol/python-sdk#3557. Themcp>=1.27,<2pin (and the intent behind open PR chore(deps): update mcp requirement from <2,>=1.27 to >=1.27,<3 #4651) is left untouched, as stated in the claim comment: [Bug]: /mcp answers unknown methods (including the 2026-07-28 server/discover probe) with -32602, so modern MCP clients re-probe 17× before falling back #5841 (comment)-32601) and removes the probe noise, without claiming any client-specific re-probe counts.