Repository navigation
Conversation
…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.
|
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:
Maintainers: reopen, remove |
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 validationRoot cause
stdin_reader()insrc/mcp/server/stdio.pyforwarded the validation fault as an exception item on the read stream andcontinued:JSONRPCDispatcher._dispatch()treats that item as follows:Only
ClientSessioninstallson_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 escapejson.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 errorfor malformed JSON and-32600 Invalid Requestfor 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_adapteris a union of four models, so a batch, a bare scalar,{}, a badjsonrpcversion and a missingmethodall fail at the envelope rung, not the JSON one.pydantic_core.from_json()is re-run to decide:-32700-32600The id is recovered, and that is load-bearing. A literal reading of §5 pins
id: nullto "the id could not be determined". But a validation failure usually leaves the id fully determinable, and the client correlates replies by id (_resolve_pendingexplicitly skipsNone:pending = self._pending.get(...) if request_id is not None else None). Answeringnullthere would leave the pending call unmatched — the exact hang this fixes. So the id is recovered from the line andnullis used only when it genuinely cannot be: absent, not aRequestId(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:jsonaccepts 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
UnicodeEncodeErrorin 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 fornull.Both
BrokenResourceErrorandClosedResourceErrorfrom 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 returns201 CreatedRoot cause
OAuthClientMetadata.redirect_uris(src/mcp/shared/auth.py) is typedlist[AnyUrl] | None = Field(..., min_length=1)so non-redirect clients — theclient_credentialsand identity-assertion extensions — can construct it withredirect_uris=None.Nonesatisfies the union and bypassesmin_length=1, so an explicit JSON"redirect_uris": nullparses.RegistrationHandler.handle()then checkedgrant_typesandresponse_typesbut neverredirect_uris, so it minted aclient_id/client_secretand persisted a client whose every/authorizerequest failsvalidate_redirect_uri()withInvalidRedirectUriError.Omitted and
[]were already rejected by the model;nullwas the only spelling that got through.Fix
An explicit check in
RegistrationHandler.handle()after thegrant_types/response_typeschecks, mirroring theprivate_key_jwtrefusal just above it:RFC 7591 §2: "Clients using flows with redirection MUST register their redirection URI values." This handler only accepts the
authorization_codegrant, which is such a flow, so such a registration can never be usable.OAuthClientMetadata.redirect_uris: list[AnyUrl] | Noneis 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):That
assert 201 == 400is the reported bug, exactly.After the fix:
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) andtests/client/test_session_group.py::…all fail withblockbuster.blockbuster.BlockingError: Blocking call to os.staton unmodifiedmainas well (verified bygit stash-ing this change and re-running: same 5 failures, same tests).Lint and types (both files):
Coverage (the repo enforces
fail_under = 100withbranch = true):With the parametrizations extended to exercise every id-shape branch,
src/mcp/server/stdio.pyhas no missing lines and is skipped by the report as fully covered. Theregister.pygaps are all pre-existing lines outside this change (the scope arm at 98, theresponse_typesarm at 112, and theregister_clienterror arms); the newredirect_urisblock at lines 134–141 is covered by theexplicit-nullcase.Tests added
tests/server/test_stdio.py(+239):test_stdio_server_answers_an_invalid_line_with_a_jsonrpc_error— 14 parametrizations over-32700/-32600and 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—nullrather than a reply that crashes the writer.test_stdio_server_acknowledges_a_line_that_is_only_a_newlinetest_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 throughMCPServer.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— partsomitted,empty-array,explicit-null; asserts400,invalid_client_metadata, noclient_idin the body, and that the provider stored nothing.test_registration_with_redirect_uris_still_succeeds— guards the fix against over-rejecting.Scope notes
on_stream_exception, so a bad line from the server already surfaces there._streamable_http_modernsends-32700/-32600); only stdio was silent.