Skip to content

fix: reply to invalid JSON-RPC lines on stdio; reject null redirect_uris in DCR - #3930

Closed
NUAAwqy wants to merge 1 commit into
modelcontextprotocol:mainfrom
NUAAwqy:fix/stdio-jsonrpc-errors-and-dcr-redirect-uris
Closed

NUAAwqy wants to merge 1 commit into
modelcontextprotocol:mainfrom
NUAAwqy:fix/stdio-jsonrpc-errors-and-dcr-redirect-uris

Conversation

@NUAAwqy

@NUAAwqy NUAAwqy commented Nov 25, 2026

Copy link
Copy Markdown

Fixes #3894
Fixes #3885

Two protocol-compliance defects in the same area of the SDK (a request the server cannot accept, and a registration the server should not accept). Both are silent-acceptance bugs: the server says nothing where the spec requires a rejection.


1. #3894 — stdio server sends no reply to a line that fails JSON validation

Root cause

stdin_reader() in src/mcp/server/stdio.py forwarded the validation fault as an exception item on the read stream and continued:

try:
    message = types.jsonrpc_message_adapter.validate_json(line, by_name=False)
except Exception as exc:
    await read_stream_writer.send(exc)   # nothing is ever written back
    continue

JSONRPCDispatcher._dispatch() treats that item as follows:

if isinstance(item, Exception):
    if self.on_stream_exception is None:
        logger.debug("transport yielded exception: %r", item)
        return

Only ClientSession installs on_stream_exception; a server session does not. So on a server the line was dropped at debug level — no reply, no stderr. The client's pending future stayed unresolved until its own timeout, and the whole agent turn with it.

The easy repro from the issue is a lone surrogate escape (\ud83d), the escape json.dumps(ensure_ascii=True) emits for text cut in the middle of an emoji. The line is pure ASCII, so the non-UTF-8 handling from #2302 never applies, and pydantic-core refuses it (Invalid JSON: unexpected end of hex escape).

Fix

JSON-RPC 2.0 §5 requires -32700 Parse error for malformed JSON and -32600 Invalid Request for a well-formed body that is not a valid request. The reader now answers the line instead of discarding it, and the exception item is still forwarded so observers keep their view.

Three details worth review:

Classification replays only the decode stage. The code must not be guessed from the exception type: jsonrpc_message_adapter is a union of four models, so a batch, a bare scalar, {}, a bad jsonrpc version and a missing method all fail at the envelope rung, not the JSON one. pydantic_core.from_json() is re-run to decide:

  • it raises → the JSON layer refused the line → -32700
  • it succeeds → the JSON was well formed → -32600

The id is recovered, and that is load-bearing. A literal reading of §5 pins id: null to "the id could not be determined". But a validation failure usually leaves the id fully determinable, and the client correlates replies by id (_resolve_pending explicitly skips None: pending = self._pending.get(...) if request_id is not None else None). Answering null there would leave the pending call unmatched — the exact hang this fixes. So the id is recovered from the line and null is used only when it genuinely cannot be: absent, not a RequestId (float/bool/array/object/explicit null), or a non-dict body.

Recovery uses json.loads, deliberately. This is the one place the two engines differ in our favour: json accepts the lone surrogate escape that pydantic-core refuses, so it still yields the envelope and the id. It is used only to identify a line pydantic-core already rejected — never to accept one — so the validation gate is unchanged.

An id that is itself unserializable (a string carrying the same lone surrogate) is dropped rather than echoed: echoing it would make the reply raise UnicodeEncodeError in the writer and kill the transport, trading a silent hang for a dead server. That id is undeterminable by this server, which is exactly the §5 case for null.

Both BrokenResourceError and ClosedResourceError from the reply send are swallowed, so a transport torn down between reading the line and answering it cannot kill the reader's task group.

2. #3885 — DCR accepts {"redirect_uris": null} and returns 201 Created

Root cause

OAuthClientMetadata.redirect_uris (src/mcp/shared/auth.py) is typed list[AnyUrl] | None = Field(..., min_length=1) so non-redirect clients — the client_credentials and identity-assertion extensions — can construct it with redirect_uris=None. None satisfies the union and bypasses min_length=1, so an explicit JSON "redirect_uris": null parses. RegistrationHandler.handle() then checked grant_types and response_types but never redirect_uris, so it minted a client_id/client_secret and persisted a client whose every /authorize request fails validate_redirect_uri() with InvalidRedirectUriError.

Omitted and [] were already rejected by the model; null was the only spelling that got through.

Fix

An explicit check in RegistrationHandler.handle() after the grant_types/response_types checks, mirroring the private_key_jwt refusal just above it:

if not client_metadata.redirect_uris:
    return PydanticJSONResponse(
        content=RegistrationErrorResponse(
            error="invalid_client_metadata",
            error_description="redirect_uris is required for authorization_code grant",
        ),
        status_code=400,
    )

RFC 7591 §2: "Clients using flows with redirection MUST register their redirection URI values." This handler only accepts the authorization_code grant, which is such a flow, so such a registration can never be usable.

OAuthClientMetadata.redirect_uris: list[AnyUrl] | None is left unchanged, as the issue's suggested fix asks — narrowing it would break the non-redirect client models.


Verification

Before the fix (both source files reverted to main, tests unchanged):

$ pytest tests/server/test_stdio.py -k "invalid_line or unserializable or newline or still_streams or lone_surrogate"
Results:
        18 failed
         1 passed    # the ClosedResourceError-durability test, which guards a branch this fix adds
$ pytest tests/interaction/auth/test_as_handlers.py -k "redirect_uris"
test_registration_without_redirect_uris_is_rejected_with_400[omitted]      PASSED
test_registration_without_redirect_uris_is_rejected_with_400[empty-array]  PASSED
test_registration_without_redirect_uris_is_rejected_with_400[explicit-null] FAILED
    E  assert 201 == 400
test_registration_with_redirect_uris_still_succeeds                        PASSED
        1 failed
        3 passed

That assert 201 == 400 is the reported bug, exactly.

After the fix:

$ pytest tests/server/test_stdio.py -k "invalid_line or unserializable or newline or still_streams or lone_surrogate"
        19 passed

$ pytest tests/server/test_stdio.py tests/interaction/auth/test_as_handlers.py
        50 passed

$ pytest tests/ -q
      6251 passed
         5 failed
         8 skipped
         1 xfailed

The 5 failures are pre-existing in this environment and unrelated: tests/client/test_streamable_http.py::test_streamable_http_rejects_nonpositive_sse_event_limits (×2), tests/client/test_transport_stream_cleanup.py (×2) and tests/client/test_session_group.py::… all fail with blockbuster.blockbuster.BlockingError: Blocking call to os.stat on unmodified main as well (verified by git stash-ing this change and re-running: same 5 failures, same tests).

Lint and types (both files):

$ ruff format --check … ; ruff check …
1 file already formatted / 4 files already formatted
All checks passed!

$ pyright src/mcp/server/stdio.py src/mcp/server/auth/handlers/register.py
0 errors, 0 warnings, 0 informations

Coverage (the repo enforces fail_under = 100 with branch = true):

$ coverage run --branch --source=src/mcp -m pytest tests/server/test_stdio.py tests/interaction/auth/test_as_handlers.py
$ coverage report
src/mcp/server/stdio.py                      160      2     26      1  98.39%   215, 225
src/mcp/server/auth/handlers/register.py      60      4     22      4  90.24%   73->85, 98, 112, 147->157, 172-174

With the parametrizations extended to exercise every id-shape branch, src/mcp/server/stdio.py has no missing lines and is skipped by the report as fully covered. The register.py gaps are all pre-existing lines outside this change (the scope arm at 98, the response_types arm at 112, and the register_client error arms); the new redirect_uris block at lines 134–141 is covered by the explicit-null case.

Tests added

tests/server/test_stdio.py (+239):

  • test_stdio_server_answers_an_invalid_line_with_a_jsonrpc_error — 14 parametrizations over -32700/-32600 and every id shape: int, string, bool, float, array, explicit null, absent, batch, bare scalar, blank line, truncated, plain text, and the issue's lone-surrogate line.
  • test_stdio_server_still_streams_after_answering_an_invalid_line — the repro's order: good, bad, good; the trailing request still arrives.
  • test_stdio_server_answers_a_line_whose_id_is_itself_unserializable — null rather than a reply that crashes the writer.
  • test_stdio_server_acknowledges_a_line_that_is_only_a_newline
  • test_a_dropped_reply_for_an_invalid_line_does_not_kill_the_reader — a closed write stream must not raise.
  • test_mcpserver_run_stdio_answers_the_issue_3894_lone_surrogate_line — end to end through MCPServer.run("stdio") over a gated process-stdio double, asserting by id (the transport writes the error as soon as it reads the line, so it may overtake a request still being served — which is the point).

tests/interaction/auth/test_as_handlers.py (+63):

  • test_registration_without_redirect_uris_is_rejected_with_400 — parts omitted, empty-array, explicit-null; asserts 400, invalid_client_metadata, no client_id in the body, and that the provider stored nothing.
  • test_registration_with_redirect_uris_still_succeeds — guards the fix against over-rejecting.

Scope notes

…s in DCR

A stdio server dropped any request line that failed validation without a reply,
and DCR accepted {"redirect_uris": null} and minted a client.

stdio (modelcontextprotocol#3894): the reader forwarded the parse fault as an exception item and
`continue`d. Server sessions install no `on_stream_exception`, so the dispatcher
logged it at debug level and the client's call hung until its own timeout.
JSON-RPC 2.0 §5 requires -32700 for malformed JSON and -32600 for a well-formed
body that is not a valid request.

The failure is classified by replaying only the decode stage: pydantic-core
refuses a lone surrogate escape that `json.loads` accepts, which is how the
issue's line arrives. The id is recovered from the lenient decode so the error
correlates with the client's pending call - a `null` id matches nothing - and
falls back to `null` when the id is absent, malformed, or itself unserializable.

DCR (modelcontextprotocol#3885): `OAuthClientMetadata.redirect_uris` is `list[AnyUrl] | None` so
non-redirect clients can build it with None; None satisfies the union and
bypasses `min_length=1`, so an explicit JSON null registered successfully.
RFC 7591 §2 requires redirect URIs for redirection flows, and every /authorize
call for such a client failed `validate_redirect_uri()`. RegistrationHandler
now refuses it with 400 invalid_client_metadata before minting credentials.
@github-actions github-actions Bot added the missing-issue-link Auto-closed: PR needs a linked issue assigned to its author (see CONTRIBUTING.md) label Nov 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR has been closed automatically. This repo only keeps pull requests open when they come from a maintainer, or from a contributor a maintainer has assigned to the linked issue, and you aren't currently assigned to #3894, #3885.

If a maintainer assigns you to #3894, #3885, this PR reopens on its own and there's nothing more you need to do here. Assignment is a maintainer call based on capacity; comments that only ask to be assigned don't factor in. What does help is engaging on the issue itself by confirming the repro, explaining why it matters for your use case, or describing the approach you'd take.

You're welcome to keep pushing commits here (just avoid force-pushing, since GitHub can't reopen a rewritten branch), but that on its own won't get the PR reviewed or the issue assigned, and realistically most auto-closed PRs stay closed. There's no need to open a new PR either way.

CONTRIBUTING.md has the full reasoning, but in short:

  • We're a small team with very little capacity to review community PRs right now.
  • Many recent PRs are AI-generated with little human review, and reviewing one carefully still costs a maintainer as much time as it ever did. A well-described issue is usually more useful to us than the code.

Maintainers: reopen, remove missing-issue-link, or add bypass-issue-check to override.

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

Labels

missing-issue-link Auto-closed: PR needs a linked issue assigned to its author (see CONTRIBUTING.md)

Projects

None yet

1 participant