← Back to Pull requests

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

Open
akushonkamen opened this pull request with 658 lines diff across 2 files
View on GitHub
akushonkamen akushonkamen commented on Oct 12, 2026 01:15 UTC
Author

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:

  • - [x] 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

  • This is a repo-side compatibility shim: the proper fix is upstream in modelcontextprotocol/python-sdk#3557. The mcp>=1.27,<2 pin (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

  • Scope per the issue discussion: the remaining agreed-upon fact is that the server answers the wrong JSON-RPC code for unknown methods; this PR restores spec compliance (-32601) and removes the probe noise, without claiming any client-specific re-probe counts.
  • Diff: 658 lines (+655 / -3) across 2 files Reviewer: ehz0ah Review duration: 2609m
    All Vouch review confidence checks passed
    Residual risk 0.04 = Change Risk (0.43) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.43 · 658 lines diff across 2 files
    0.43
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.96 · 5 substantive comment(s)
    0.96
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Real PR Conversation Timeline
    7 items
    ehz0ah ehz0ah commented on code on Oct 12, 2026 04:09 UTC
    Code Review
    openviking/server/mcp_endpoint.py:1
    @@ -244,6 +255,147 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send):
                 _request_url_ctx.reset(url_token)
     
     
    +def _client_request_method_literals() -> frozenset[str] | None:
    +    """Derive the JSON-RPC method names the installed mcp SDK can route.
    +
    +    Walks ``mcp.types.ClientRequestType`` (a union of request models whose
    +    ``method`` field is a ``Literal``) and collects every literal, so the set
    +    tracks the installed SDK version instead of a hand-maintained list. Older
    +    SDKs expose the same union as ``ClientRequest = Annotated[Union[...], ...]``;
    +    both shapes are handled.
    +
    +    Returns ``None`` when the union cannot be introspected, in which case the
    +    pre-check middleware must stay passive (fail-open) rather than risk
    +    answering -32601 for a method the SDK would actually route.
    +    """
    +    union = getattr(mcp_types, "ClientRequestType", None) or getattr(
    +        mcp_types, "ClientRequest", None
    +    )
    +    if union is None:
    +        return None
    +    stack = [union]
    +    methods: set[str] = set()
    +    while stack:
    +        current = stack.pop()
    +        args = get_args(current)
    +        if args:
    +            # Expand Annotated[...] / Union[...] wrappers down to model classes.
    +            stack.extend(args)
    +            continue
    +        if isinstance(current, type):
    +            field = current.model_fields.get("method")
    +            if field is not None:
    +                methods.update(
    +                    literal for literal in get_args(field.annotation) if isinstance(literal, str)
    +                )
    +    return frozenset(methods) or None
    +
    +
    +def _parse_jsonrpc_request(body: bytes) -> dict[str, Any] | None:
    +    """Parse a single JSON-RPC request object from an HTTP body, else ``None``.
    +
    +    Batch payloads (lists), non-JSON bodies and objects without a string
    +    ``method`` return ``None`` so the SDK keeps answering them unchanged.
    +    """
    +    try:
    +        payload = json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return None
    +    if not isinstance(payload, dict):
    +        return None
    +    if not isinstance(payload.get("method"), str) or not payload.get("method"):
    +        return None
    +    return payload
    +
    +
    +def _replay_receive(buffered: list[dict], receive: Receive) -> Receive:
    +    """Re-deliver an already-consumed ASGI request body to the wrapped app."""
    +    queue = list(buffered)
    +
    +    async def replay() -> dict:
    +        if queue:
    +            return queue.pop(0)
    +        return await receive()
    +
    +    return replay
    +
    +
    +def _accepts_json(accept: str) -> bool:
    +    """True unless every listed media type would reject an application/json body."""
    +    if not accept.strip():
    +        return True  # absent Accept header: RFC 9110 treats it as */*
    +    for part in accept.split(","):
    +        media = part.split(";")[0].strip().lower()
    +        if media in ("application/json", "application/*", "*/*"):
    +            return True
    +    return False
    +
    +
    +class _MethodPrecheckASGIMiddleware:
    +    """Answer ``-32601 Method not found`` for JSON-RPC methods the SDK cannot route.
    +
    +    The pinned mcp SDK (``mcp>=1.27,<2``; upstream modelcontextprotocol/python-sdk#3557)
    +    validates every request against its ``ClientRequest`` union and maps *any*
    +    validation failure to ``INVALID_PARAMS`` (``mcp/shared/session.py``), so unknown
    +    methods — e.g. 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, so they keep re-probing before falling back.
    +
    +    This middleware resolves the method *before* the request enters the SDK,
    +    with the known set derived from the installed SDK (see
    +    ``_client_request_method_literals``). Bodies that are not single JSON-RPC
    +    request objects, notifications (no ``id``), known methods and non-POST
    +    requests are passed through untouched. This is a compatibility shim; the
    +    proper fix is upstream.
    +    """
    +
    +    def __init__(self, app: ASGIApp, known_methods: frozenset[str] | None = None):
    +        self.app = app
    +        self.known_methods = (
    +            known_methods if known_methods is not None else _client_request_method_literals()
    +        )
    +
    +    async def __call__(self, scope: Scope, receive: Receive, send: Send):
    +        if scope["type"] != "http" or scope.get("method") != "POST" or not self.known_methods:
    +            return await self.app(scope, receive, send)
    +
    +        body = b""
    +        buffered: list[dict] = []
    +        while True:
    +            message = await receive()
    +            buffered.append(message)
    +            if message["type"] == "http.disconnect":
    +                return
    +            if message["type"] != "http.request":
    +                break
    +            body += message.get("body", b"")
    +            if not message.get("more_body", False):
    +                break
    +
    +        payload = _parse_jsonrpc_request(body)
    +        if payload is None or payload["method"] in self.known_methods or "id" not in payload:
    +            # Unparseable / known / notification: let the SDK answer as before.
    +            return await self.app(scope, _replay_receive(buffered, receive), send)
    +
    +        accept = ""
    +        for key, value in scope.get("headers") or []:
    +            if key == b"accept":
    +                accept = value.decode("latin-1").lower()
    +                break
    +        if not _accepts_json(accept):

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

    ehz0ah ehz0ah commented on code on Oct 12, 2026 04:09 UTC
    Code Review
    openviking/server/mcp_endpoint.py:1
    @@ -244,6 +255,147 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send):
                 _request_url_ctx.reset(url_token)
     
     
    +def _client_request_method_literals() -> frozenset[str] | None:
    +    """Derive the JSON-RPC method names the installed mcp SDK can route.
    +
    +    Walks ``mcp.types.ClientRequestType`` (a union of request models whose
    +    ``method`` field is a ``Literal``) and collects every literal, so the set
    +    tracks the installed SDK version instead of a hand-maintained list. Older
    +    SDKs expose the same union as ``ClientRequest = Annotated[Union[...], ...]``;
    +    both shapes are handled.
    +
    +    Returns ``None`` when the union cannot be introspected, in which case the
    +    pre-check middleware must stay passive (fail-open) rather than risk
    +    answering -32601 for a method the SDK would actually route.
    +    """
    +    union = getattr(mcp_types, "ClientRequestType", None) or getattr(
    +        mcp_types, "ClientRequest", None
    +    )
    +    if union is None:
    +        return None
    +    stack = [union]
    +    methods: set[str] = set()
    +    while stack:
    +        current = stack.pop()
    +        args = get_args(current)
    +        if args:
    +            # Expand Annotated[...] / Union[...] wrappers down to model classes.
    +            stack.extend(args)
    +            continue
    +        if isinstance(current, type):
    +            field = current.model_fields.get("method")
    +            if field is not None:
    +                methods.update(
    +                    literal for literal in get_args(field.annotation) if isinstance(literal, str)
    +                )
    +    return frozenset(methods) or None
    +
    +
    +def _parse_jsonrpc_request(body: bytes) -> dict[str, Any] | None:
    +    """Parse a single JSON-RPC request object from an HTTP body, else ``None``.
    +
    +    Batch payloads (lists), non-JSON bodies and objects without a string
    +    ``method`` return ``None`` so the SDK keeps answering them unchanged.
    +    """
    +    try:
    +        payload = json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return None
    +    if not isinstance(payload, dict):
    +        return None
    +    if not isinstance(payload.get("method"), str) or not payload.get("method"):
    +        return None
    +    return payload
    +
    +
    +def _replay_receive(buffered: list[dict], receive: Receive) -> Receive:
    +    """Re-deliver an already-consumed ASGI request body to the wrapped app."""
    +    queue = list(buffered)
    +
    +    async def replay() -> dict:
    +        if queue:
    +            return queue.pop(0)
    +        return await receive()
    +
    +    return replay
    +
    +
    +def _accepts_json(accept: str) -> bool:
    +    """True unless every listed media type would reject an application/json body."""
    +    if not accept.strip():
    +        return True  # absent Accept header: RFC 9110 treats it as */*
    +    for part in accept.split(","):
    +        media = part.split(";")[0].strip().lower()
    +        if media in ("application/json", "application/*", "*/*"):
    +            return True
    +    return False
    +
    +
    +class _MethodPrecheckASGIMiddleware:
    +    """Answer ``-32601 Method not found`` for JSON-RPC methods the SDK cannot route.
    +
    +    The pinned mcp SDK (``mcp>=1.27,<2``; upstream modelcontextprotocol/python-sdk#3557)
    +    validates every request against its ``ClientRequest`` union and maps *any*
    +    validation failure to ``INVALID_PARAMS`` (``mcp/shared/session.py``), so unknown
    +    methods — e.g. 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, so they keep re-probing before falling back.
    +
    +    This middleware resolves the method *before* the request enters the SDK,
    +    with the known set derived from the installed SDK (see
    +    ``_client_request_method_literals``). Bodies that are not single JSON-RPC
    +    request objects, notifications (no ``id``), known methods and non-POST
    +    requests are passed through untouched. This is a compatibility shim; the
    +    proper fix is upstream.
    +    """
    +
    +    def __init__(self, app: ASGIApp, known_methods: frozenset[str] | None = None):
    +        self.app = app
    +        self.known_methods = (
    +            known_methods if known_methods is not None else _client_request_method_literals()
    +        )
    +
    +    async def __call__(self, scope: Scope, receive: Receive, send: Send):
    +        if scope["type"] != "http" or scope.get("method") != "POST" or not self.known_methods:
    +            return await self.app(scope, receive, send)
    +
    +        body = b""
    +        buffered: list[dict] = []
    +        while True:
    +            message = await receive()
    +            buffered.append(message)
    +            if message["type"] == "http.disconnect":
    +                return
    +            if message["type"] != "http.request":
    +                break
    +            body += message.get("body", b"")
    +            if not message.get("more_body", False):
    +                break
    +
    +        payload = _parse_jsonrpc_request(body)

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

    ehz0ah ehz0ah requested changes on Oct 12, 2026 04:09 UTC
    Changes Requested Reviewer

    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.

    akushonkamen akushonkamen commented on code on Oct 12, 2026 13:16 UTC
    Code Review
    openviking/server/mcp_endpoint.py:1
    @@ -244,6 +255,147 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send):
                 _request_url_ctx.reset(url_token)
     
     
    +def _client_request_method_literals() -> frozenset[str] | None:
    +    """Derive the JSON-RPC method names the installed mcp SDK can route.
    +
    +    Walks ``mcp.types.ClientRequestType`` (a union of request models whose
    +    ``method`` field is a ``Literal``) and collects every literal, so the set
    +    tracks the installed SDK version instead of a hand-maintained list. Older
    +    SDKs expose the same union as ``ClientRequest = Annotated[Union[...], ...]``;
    +    both shapes are handled.
    +
    +    Returns ``None`` when the union cannot be introspected, in which case the
    +    pre-check middleware must stay passive (fail-open) rather than risk
    +    answering -32601 for a method the SDK would actually route.
    +    """
    +    union = getattr(mcp_types, "ClientRequestType", None) or getattr(
    +        mcp_types, "ClientRequest", None
    +    )
    +    if union is None:
    +        return None
    +    stack = [union]
    +    methods: set[str] = set()
    +    while stack:
    +        current = stack.pop()
    +        args = get_args(current)
    +        if args:
    +            # Expand Annotated[...] / Union[...] wrappers down to model classes.
    +            stack.extend(args)
    +            continue
    +        if isinstance(current, type):
    +            field = current.model_fields.get("method")
    +            if field is not None:
    +                methods.update(
    +                    literal for literal in get_args(field.annotation) if isinstance(literal, str)
    +                )
    +    return frozenset(methods) or None
    +
    +
    +def _parse_jsonrpc_request(body: bytes) -> dict[str, Any] | None:
    +    """Parse a single JSON-RPC request object from an HTTP body, else ``None``.
    +
    +    Batch payloads (lists), non-JSON bodies and objects without a string
    +    ``method`` return ``None`` so the SDK keeps answering them unchanged.
    +    """
    +    try:
    +        payload = json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return None
    +    if not isinstance(payload, dict):
    +        return None
    +    if not isinstance(payload.get("method"), str) or not payload.get("method"):
    +        return None
    +    return payload
    +
    +
    +def _replay_receive(buffered: list[dict], receive: Receive) -> Receive:
    +    """Re-deliver an already-consumed ASGI request body to the wrapped app."""
    +    queue = list(buffered)
    +
    +    async def replay() -> dict:
    +        if queue:
    +            return queue.pop(0)
    +        return await receive()
    +
    +    return replay
    +
    +
    +def _accepts_json(accept: str) -> bool:
    +    """True unless every listed media type would reject an application/json body."""
    +    if not accept.strip():
    +        return True  # absent Accept header: RFC 9110 treats it as */*
    +    for part in accept.split(","):
    +        media = part.split(";")[0].strip().lower()
    +        if media in ("application/json", "application/*", "*/*"):
    +            return True
    +    return False
    +
    +
    +class _MethodPrecheckASGIMiddleware:
    +    """Answer ``-32601 Method not found`` for JSON-RPC methods the SDK cannot route.
    +
    +    The pinned mcp SDK (``mcp>=1.27,<2``; upstream modelcontextprotocol/python-sdk#3557)
    +    validates every request against its ``ClientRequest`` union and maps *any*
    +    validation failure to ``INVALID_PARAMS`` (``mcp/shared/session.py``), so unknown
    +    methods — e.g. 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, so they keep re-probing before falling back.
    +
    +    This middleware resolves the method *before* the request enters the SDK,
    +    with the known set derived from the installed SDK (see
    +    ``_client_request_method_literals``). Bodies that are not single JSON-RPC
    +    request objects, notifications (no ``id``), known methods and non-POST
    +    requests are passed through untouched. This is a compatibility shim; the
    +    proper fix is upstream.
    +    """
    +
    +    def __init__(self, app: ASGIApp, known_methods: frozenset[str] | None = None):
    +        self.app = app
    +        self.known_methods = (
    +            known_methods if known_methods is not None else _client_request_method_literals()
    +        )
    +
    +    async def __call__(self, scope: Scope, receive: Receive, send: Send):
    +        if scope["type"] != "http" or scope.get("method") != "POST" or not self.known_methods:
    +            return await self.app(scope, receive, send)
    +
    +        body = b""
    +        buffered: list[dict] = []
    +        while True:
    +            message = await receive()
    +            buffered.append(message)
    +            if message["type"] == "http.disconnect":
    +                return
    +            if message["type"] != "http.request":
    +                break
    +            body += message.get("body", b"")
    +            if not message.get("more_body", False):
    +                break
    +
    +        payload = _parse_jsonrpc_request(body)
    +        if payload is None or payload["method"] in self.known_methods or "id" not in payload:
    +            # Unparseable / known / notification: let the SDK answer as before.
    +            return await self.app(scope, _replay_receive(buffered, receive), send)
    +
    +        accept = ""
    +        for key, value in scope.get("headers") or []:
    +            if key == b"accept":
    +                accept = value.decode("latin-1").lower()
    +                break
    +        if not _accepts_json(accept):

    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:

  • 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 8adf8b1e, pre-existing environmental, not introduced here.

    akushonkamen akushonkamen commented on code on Oct 12, 2026 13:16 UTC
    Code Review
    openviking/server/mcp_endpoint.py:1
    @@ -244,6 +255,147 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send):
                 _request_url_ctx.reset(url_token)
     
     
    +def _client_request_method_literals() -> frozenset[str] | None:
    +    """Derive the JSON-RPC method names the installed mcp SDK can route.
    +
    +    Walks ``mcp.types.ClientRequestType`` (a union of request models whose
    +    ``method`` field is a ``Literal``) and collects every literal, so the set
    +    tracks the installed SDK version instead of a hand-maintained list. Older
    +    SDKs expose the same union as ``ClientRequest = Annotated[Union[...], ...]``;
    +    both shapes are handled.
    +
    +    Returns ``None`` when the union cannot be introspected, in which case the
    +    pre-check middleware must stay passive (fail-open) rather than risk
    +    answering -32601 for a method the SDK would actually route.
    +    """
    +    union = getattr(mcp_types, "ClientRequestType", None) or getattr(
    +        mcp_types, "ClientRequest", None
    +    )
    +    if union is None:
    +        return None
    +    stack = [union]
    +    methods: set[str] = set()
    +    while stack:
    +        current = stack.pop()
    +        args = get_args(current)
    +        if args:
    +            # Expand Annotated[...] / Union[...] wrappers down to model classes.
    +            stack.extend(args)
    +            continue
    +        if isinstance(current, type):
    +            field = current.model_fields.get("method")
    +            if field is not None:
    +                methods.update(
    +                    literal for literal in get_args(field.annotation) if isinstance(literal, str)
    +                )
    +    return frozenset(methods) or None
    +
    +
    +def _parse_jsonrpc_request(body: bytes) -> dict[str, Any] | None:
    +    """Parse a single JSON-RPC request object from an HTTP body, else ``None``.
    +
    +    Batch payloads (lists), non-JSON bodies and objects without a string
    +    ``method`` return ``None`` so the SDK keeps answering them unchanged.
    +    """
    +    try:
    +        payload = json.loads(body)
    +    except (json.JSONDecodeError, UnicodeDecodeError):
    +        return None
    +    if not isinstance(payload, dict):
    +        return None
    +    if not isinstance(payload.get("method"), str) or not payload.get("method"):
    +        return None
    +    return payload
    +
    +
    +def _replay_receive(buffered: list[dict], receive: Receive) -> Receive:
    +    """Re-deliver an already-consumed ASGI request body to the wrapped app."""
    +    queue = list(buffered)
    +
    +    async def replay() -> dict:
    +        if queue:
    +            return queue.pop(0)
    +        return await receive()
    +
    +    return replay
    +
    +
    +def _accepts_json(accept: str) -> bool:
    +    """True unless every listed media type would reject an application/json body."""
    +    if not accept.strip():
    +        return True  # absent Accept header: RFC 9110 treats it as */*
    +    for part in accept.split(","):
    +        media = part.split(";")[0].strip().lower()
    +        if media in ("application/json", "application/*", "*/*"):
    +            return True
    +    return False
    +
    +
    +class _MethodPrecheckASGIMiddleware:
    +    """Answer ``-32601 Method not found`` for JSON-RPC methods the SDK cannot route.
    +
    +    The pinned mcp SDK (``mcp>=1.27,<2``; upstream modelcontextprotocol/python-sdk#3557)
    +    validates every request against its ``ClientRequest`` union and maps *any*
    +    validation failure to ``INVALID_PARAMS`` (``mcp/shared/session.py``), so unknown
    +    methods — e.g. 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, so they keep re-probing before falling back.
    +
    +    This middleware resolves the method *before* the request enters the SDK,
    +    with the known set derived from the installed SDK (see
    +    ``_client_request_method_literals``). Bodies that are not single JSON-RPC
    +    request objects, notifications (no ``id``), known methods and non-POST
    +    requests are passed through untouched. This is a compatibility shim; the
    +    proper fix is upstream.
    +    """
    +
    +    def __init__(self, app: ASGIApp, known_methods: frozenset[str] | None = None):
    +        self.app = app
    +        self.known_methods = (
    +            known_methods if known_methods is not None else _client_request_method_literals()
    +        )
    +
    +    async def __call__(self, scope: Scope, receive: Receive, send: Send):
    +        if scope["type"] != "http" or scope.get("method") != "POST" or not self.known_methods:
    +            return await self.app(scope, receive, send)
    +
    +        body = b""
    +        buffered: list[dict] = []
    +        while True:
    +            message = await receive()
    +            buffered.append(message)
    +            if message["type"] == "http.disconnect":
    +                return
    +            if message["type"] != "http.request":
    +                break
    +            body += message.get("body", b"")
    +            if not message.get("more_body", False):
    +                break
    +
    +        payload = _parse_jsonrpc_request(body)

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

  • 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 8adf8b1e).

    XHR666 XHR666 commented on Oct 12, 2026 14:12 UTC
    Contributor

    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.

    Reviewers
    Assignees
    akushonkamen akushonkamen
    Labels
    risk: low confidence: 89.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 43.3% (MEDIUM) · Higher = larger blast radius
    43.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.8% · Lower = rushed or shallow review
    89.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.4% · Safe to merge
    4.4%