fix(server): answer -32601 Method not found for JSON-RPC methods the MCP SDK cannot route #5923
[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.
[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.
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.
Fixed in 716fd8fdd. 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:
application/json and text/event-stream (mirroring StreamableHTTPServerTransport._check_accept_headers in the default SSE response mode; requiring both is the conservative intersection that also passes if is_json_response_enabled were on). Accept: application/json alone now falls through and gets the SDK's 406.mcp.shared.version.SUPPORTED_PROTOCOL_VERSIONS (imported from the installed SDK, same source _validate_protocol_version checks 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).application/json Content-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 8adf8b1e, pre-existing environmental, not introduced here.
Fixed in 716fd8fdd. 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 missing jsonrpc member, and a string params all fail validation and fall through to the SDK's existing 400 / INVALID_PARAMS path, exactly as before the shim existed. Batches, notifications (no id) and responses never validate as JSONRPCRequest and keep their SDK answers too (202 / -32700 / routing).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 8adf8b1e).
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
@openviking/dsh-memory-plugin@0.5.20 builds { transport: "stdio", serverName: "openviking", command: process.execPath, args: [servers/mcp-proxy.mjs], env }.
http://127.0.0.1:1933/mcp. Wire order seen at the endpoint: server/discover → initialize → notifications/initialized → tools/list.
ProtocolError: OpenViking MCP request failed. … text our harness logged comes from the proxy, not from the SDK.
A/B on the real chain
Using the SDK DSH actually loads (@modelcontextprotocol/client@2.0.0, versionNegotiation: { mode: "auto" }, same construction as dsh-mcp-client) over that proxy:
-32602 (synthetic, mimics current behavior): 1 attempt, connect() succeeded, fixture tool returned.
-32601 (this PR's behavior): 1 attempt, connect() succeeded, fixture tool returned.
-32602: 1 attempt, connect() succeeded, tools/list returned 15 real tools.
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" implication
What produced our retries was a startup race, not the error code:
giving up;
Still in favour of the change
-32601, not -32602.
716fd8fdd addresses both inline findings — envelope validation via mcp.types.JSONRPCMessage.model_validate, and the transport's 406 / 400 / 415 gates mirrored before intercepting.
mcp 1.29.0, ClientRequestType exposes 17 routable methods and server/discover is not one of them, so the derived known-set is correct here.
I am correcting the issue title and posting the full numbers in #5841.
ehz0ah
akushonkamen
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
- [x] macOS
- [ ] Linux
- [ ] Windows
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 #4651) is left untouched, as stated in the claim comment: https://github.com/volcengine/OpenViking/issues/5841#issuecomment-6114935230-32601) and removes the probe noise, without claiming any client-specific re-probe counts.