Skip to content

fix(server): answer -32601 Method not found for JSON-RPC methods the MCP SDK cannot route - #5923

Open
akushonkamen wants to merge 2 commits into
volcengine:mainfrom
akushonkamen:fix/5841-mcp-unknown-method-32601
Open

akushonkamen wants to merge 2 commits into
volcengine:mainfrom
akushonkamen:fix/5841-mcp-unknown-method-32601

Conversation

@akushonkamen

Copy link
Copy Markdown
Contributor

Description

POST /mcp currently answers JSON-RPC methods the MCP SDK cannot route — including the 2026-07-28-era server/discover probe and any arbitrary unknown method — with -32602 Invalid request parameters instead of the spec-compliant -32601 Method not found. This PR adds a small pure-ASGI middleware that answers -32601 for methods outside the SDK's known request set, before the request reaches the SDK, while passing everything else through untouched.

Human Involvement

  • A human participated in the implementation or review loop
  • This PR was generated entirely by AI agents without human participation in the loop

Related Issue

Fixes #5841

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement
  • Test update

Changes Made

  • Root cause (in the pinned upstream SDK, not OpenViking logic): mcp>=1.27,<2 (pyproject.toml) pins a version whose mcp/shared/session.py _receive_loop validates every request against the ClientRequest union and maps any validation failure to INVALID_PARAMS via a generic except, so the METHOD_NOT_FOUND branch 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.
  • Fix: new _MethodPrecheckASGIMiddleware in openviking/server/mcp_endpoint.py, composed at the existing create_mcp_app() seam (_IdentityASGIMiddleware stays the outermost layer). On POST, it resolves the JSON-RPC method; if it is outside the known set it answers -32601 Method not found directly. The known set is derived at init from the installed SDK's mcp.types.ClientRequestType union member method Literals (so it tracks SDK upgrades), failing open (pass-through) if introspection fails.
  • Preserved behavior (all passed through to the SDK unchanged): unparseable bodies, batch payloads, notifications (no id), known methods, non-POST requests, and clients that cannot accept application/json (SSE-only Accept keeps the SDK's 406).

Testing

  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have tested this on the following platforms:
    • macOS
    • Linux
    • Windows

Before the fix (red, live server on 8adf8b1e's parent), the issue's three curls returned -32602 for both server/discover and totally/unknown with 2 Failed to validate request log lines. After the fix (green, re-run live):

  • server/discover and totally/unknown → {"code":-32601,"message":"Method not found"}; initialize still down-negotiates to protocolVersion: 2025-11-25; tools/list unchanged.
  • Boundary checks: tools/call with bad params still returns the SDK's -32602; a notification without id still gets 202; SSE-only Accept still gets the SDK's 406; zero validation warnings from the unknown-method path (only the expected SDK-side warning for the bad-params tools/call probe).
  • Unit tests: 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, -32601 for unknown methods, and pass-through for known methods/notifications/unparseable/batch bodies/non-POST/SSE-only Accept/fail-open).
  • Slice regression: 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 parent 4c9a755b via git worktree — pre-existing environmental failures, not introduced here.
  • ruff check and ruff format --check clean on both changed files.

Checklist

  • My code follows the project's coding style
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

Screenshots (if applicable)

Not applicable — no UI change; live curl transcripts are quoted above under Testing.

Additional Notes

…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 ehz0ah left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread openviking/server/mcp_endpoint.py Outdated
if key == b"accept":
accept = value.decode("latin-1").lower()
break
if not _accepts_json(accept):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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/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-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_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).
  • Content-Type (same regression class, covered proactively): a non-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 8adf8b1, pre-existing environmental, not introduced here.

Comment thread openviking/server/mcp_endpoint.py Outdated
if not message.get("more_body", False):
break

payload = _parse_jsonrpc_request(body)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 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).
  • 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>
@XHR666

XHR666 commented Oct 12, 2026

Copy link
Copy Markdown

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

  • DSH's transport for OpenViking is stdio to a spawned proxy: @openviking/dsh-memory-plugin@0.5.20 builds { transport: "stdio", serverName: "openviking", command: process.execPath, args: [servers/mcp-proxy.mjs], env }.
  • That proxy is the "stdio → streamable-HTTP" bridge to http://127.0.0.1:1933/mcp. Wire order seen at the endpoint: server/discover → initialize → notifications/initialized → tools/list.
  • The 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:

  • Endpoint answering -32602 (synthetic, mimics current behavior): 1 attempt, connect() succeeded, fixture tool returned.
  • Endpoint answering -32601 (this PR's behavior): 1 attempt, connect() succeeded, fixture tool returned.
  • Live OpenViking, still answering -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:

  • attempts at 17:29:14.522 / 15.358 / 16.679 with 500 / 1000 / 2000 ms backoff and no giving up;
  • the server's own log starts at 17:29:16 and its streamable session manager is up at 17:29:17, so DSH was knocking about 2.5 s before the endpoint served;
  • attempt 4 apparently succeeded.

Still in favour of the change

  • It is the right spec fix: unknown methods should answer -32601, not -32602.
  • FWIW, 716fd8fdd addresses both inline findings — envelope validation via mcp.types.JSONRPCMessage.model_validate, and the transport's 406 / 400 / 415 gates mirrored before intercepting.
  • On the installed 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.

@akushonkamen

Copy link
Copy Markdown
Contributor Author

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.

@XHR666

XHR666 commented Oct 24, 2026

Copy link
Copy Markdown

The two inline findings are addressed by 716fd8f (SDK envelope validation preserved; the -32601 interception is gated on a valid JSON-RPC request), and both conversations are now outdated.

Two items still block merge from this side:

  • mergeable_state is dirty — the branch needs a rebase/merge from main.
  • reviewDecision is REVIEW_REQUIRED; the two outdated conversations need to be resolved by someone with write access.

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.

@r266-tech

Copy link
Copy Markdown
Contributor

The two original envelope/transport findings are fixed for single-valued headers at 716fd8fdd. I independently ran the 25 extracted precheck tests against real FastMCP ASGI handlers with MCP 1.29.0 and 1.30.0; both pass. This was isolated protocol validation, not the full OpenViking service suite.

One transport-parity case remains: _passes_transport_validation() converts headers to a dict, retaining the last duplicate, while the SDK reads Starlette Request.headers, which returns the first. For the valid server/discover body, these headers produce raw SDK 406, but wrapped 200 / -32601 on both versions:

Content-Type: application/json
Accept: application/json
Accept: application/json, text/event-stream

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 Headers(scope=scope)) and add a duplicate-header parity case. The branch also remains conflicting with main.

AI disclosure: this review and its isolated tests were produced by an AI agent; the results above were executed locally.

@XHR666

XHR666 commented Oct 25, 2026

Copy link
Copy Markdown

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:

  • @openviking/dsh-memory-plugin@0.5.20, loaded by DSH 0.2.0-rc.2 on Node v24.19.0, on Linux
  • the live transport is stdio → servers/mcp-proxy.mjs → streamable-HTTP

How the outgoing headers are built:

headersForRequest() in shared/mcp-proxy-core.mjs calls buildOvHeaders() with an extraHeaders object —

"Accept": "application/json, text/event-stream",
"MCP-Protocol-Version": protocolVersion,
...(includeSession && sessionId ? { "Mcp-Session-Id": sessionId } : {}),

and that object is passed as the request headers. A plain object cannot carry duplicate keys: converting this exact shape through Headers yields a single accept entry (checked locally), so duplicate Accept / Content-Type headers are not producible from this client path.

One caveat, for completeness: the proxy does expose an operator escape hatch (OPENVIKING_EXTRA_HEADERS, used to add gateway headers such as tenant/vault hints). It is merged into the same header object, so it does not create a second Accept, but it means "header values can be extended by operators" is a real, intentional surface — worth stating explicitly rather than assuming no extras ever appear.

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 Request.headers semantics, that seems worth doing regardless of this reporter.

Related, on the new protocol-version gate: this proxy always sends MCP-Protocol-Version, so the gate added in 716fd8fdd is exercised on every DSH request — the fix is on our path, not just a theoretical branch.

Merge status from the reporter side (unchanged): the branch is CONFLICTING against main, reviewDecision is REVIEW_REQUIRED, and the two outdated inline threads still need to be resolved by someone with write access. No objection to the change itself.


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.

@akushonkamen

Copy link
Copy Markdown
Contributor Author

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 Request.headers semantics is worth doing as a small hardening commit. I'll fold that into the next push on this branch (along with a rebase onto current main — noting the branch is CONFLICTING, and the two outdated inline threads will need resolution from someone with write access).

This branch has not been deployed

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

Labels

agent-plugins Agent harness and plugin integrations kernel Core server, runtime, storage, retrieval, SDK, and CLI.

Projects

Status: Backlog

5 participants