diff --git a/src/mcp/server/auth/handlers/register.py b/src/mcp/server/auth/handlers/register.py index 621a0f37d6..c8c5d25a99 100644 --- a/src/mcp/server/auth/handlers/register.py +++ b/src/mcp/server/auth/handlers/register.py @@ -117,6 +117,29 @@ async def handle(self, request: Request) -> Response: 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 a registration without redirect URIs can + # never be used: every /authorize call would fail + # `validate_redirect_uri()` with `InvalidRedirectUriError`. Refuse it here, + # before minting credentials, rather than persisting a dead client. + # + # `redirect_uris` is `list[AnyUrl] | None` on `OAuthClientMetadata` because + # non-redirect clients (the client_credentials and identity-assertion + # extensions) build it with `redirect_uris=None`. `None` satisfies that union + # and bypasses `min_length=1`, so an explicit JSON `"redirect_uris": null` + # parses - and would otherwise register successfully. Omitted and `[]` are + # already rejected by the model; this closes the third spelling, matching the + # check `private_key_jwt` above. + 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, + ) + client_id_issued_at = int(time.time()) # RFC 7591 §3.2.1: client_secret_expires_at is REQUIRED whenever a client_secret is # issued, with 0 (not omission) meaning it never expires; a public client gets none. diff --git a/src/mcp/server/stdio.py b/src/mcp/server/stdio.py index de8bbae5f1..5c28cffc27 100644 --- a/src/mcp/server/stdio.py +++ b/src/mcp/server/stdio.py @@ -11,6 +11,8 @@ async def run_server(): ``` """ +import json +import logging import os import sys import threading @@ -18,16 +20,20 @@ async def run_server(): from contextlib import asynccontextmanager, suppress from dataclasses import dataclass from io import TextIOWrapper -from typing import BinaryIO, Literal, TextIO +from typing import Any, BinaryIO, Final, Literal, TextIO, cast import anyio import anyio.lowlevel import mcp_types as types +import pydantic_core from mcp.os.win32.utilities import rebind_std_handle_to_fd from mcp.shared._context_streams import create_context_streams +from mcp.shared._stream_protocols import WriteStream from mcp.shared.message import SessionMessage +logger = logging.getLogger(__name__) + if sys.platform != "win32": # pragma: no branch import fcntl # pragma: lax no cover - POSIX-only line, uncovered on Windows runners @@ -158,6 +164,114 @@ def release() -> None: return os.fdopen(private_fd, mode, closefd=False), release +_PARSE_ERROR_MESSAGE: Final = "Parse error" +"""JSON-RPC 2.0 §5 wording for -32700: the line was not well-formed JSON.""" + +_INVALID_REQUEST_MESSAGE: Final = "Invalid Request" +"""JSON-RPC 2.0 §5 wording for -32600: well-formed JSON that is not one usable message.""" + + +def _lenient_decode(line: str) -> Any: + """Decode a line with Python's `json`, which tolerates what pydantic-core refuses. + + Used only to *identify* a line pydantic-core rejected, never to accept one: + the engines disagree on invalid Unicode escapes. A lone surrogate such as + `\\ud83d` - the escape `json.dumps(ensure_ascii=True)` writes for half of a + sliced emoji - decodes under `json` and is refused by pydantic-core, so + `json` still yields the envelope, and with it the id the client awaits. + + Returns the decoded value, or `None` when even `json` cannot parse the line. + """ + try: + return json.loads(line) + except (ValueError, RecursionError): + # Not just JSONDecodeError: oversized integer literals raise bare + # ValueError and deep nesting raises RecursionError. + return None + + +def _recover_request_id(line: str) -> types.RequestId | None: + """The request id of a rejected line, when it carries one the wire accepts. + + JSON-RPC 2.0 §5: an error response carries the id of the request it answers, + and `null` only when the id could not be determined. A line that *validated* + badly usually still identifies itself, and answering with `null` would leave + the client's pending call unmatched - precisely the hang being fixed, since + a `null` id correlates with nothing in a client's pending map. + + Only the envelope's own top-level `id` counts: an `id` nested inside `params` + is a tool argument, and attributing the reply to it would resolve an + unrelated request. A member that is not a valid `RequestId` (a float, a bool, + an array, an object, or an explicit `null`) is dropped rather than echoed, + because putting it on the wire would violate the same spec. + """ + decoded = _lenient_decode(line) + if not isinstance(decoded, dict): + return None + envelope = cast("dict[str, Any]", decoded) + raw_id: Any = envelope.get("id") + # `bool` subclasses `int`; JSON `true` is not a request id. + if isinstance(raw_id, bool): + return None + if isinstance(raw_id, str): + # The lenient decoder tolerates a string id carrying the same lone + # surrogate that got the line rejected; echoing it would make the reply + # itself unserializable and take the writer down. Such an id is + # undeterminable for this server, so it is answered with `null`. + try: + raw_id.encode("utf-8") + except UnicodeEncodeError: + return None + return raw_id + if isinstance(raw_id, int): + return raw_id + return None + + +def _invalid_line_response(line: str) -> types.JSONRPCError: + """The JSON-RPC error owed to a client whose request line could not be accepted. + + The code follows the rung the line failed at, which is read by replaying only + the decode stage: `-32700 Parse error` when the JSON layer refuses the line, + `-32600 Invalid Request` when the JSON is well-formed but not one message. + (`jsonrpc_message_adapter` is a union of the four message models, so a batch, + a bare scalar, `{}`, a bad `jsonrpc` version or a missing `method` all fail + the envelope rung rather than the JSON one.) + """ + try: + pydantic_core.from_json(line) + except ValueError: + code, message = types.PARSE_ERROR, _PARSE_ERROR_MESSAGE + else: + code, message = types.INVALID_REQUEST, _INVALID_REQUEST_MESSAGE + return types.JSONRPCError( + jsonrpc="2.0", + id=_recover_request_id(line), + error=types.ErrorData(code=code, message=message), + ) + + +async def _reply_to_invalid_line(write_stream: WriteStream[SessionMessage], line: str, exc: Exception) -> None: + """Send the error reply for an unusable line instead of leaving the client to time out. + + `JSONRPCDispatcher._dispatch` drops a bare `Exception` item when no + `on_stream_exception` observer is installed, and a server session installs + none - so forwarding the exception alone, as this reader used to, produced + silence on the wire. The exception is still forwarded (observers keep seeing + it); the reply is what unblocks the caller. + """ + response = _invalid_line_response(line) + # Warning, not debug: the line is discarded, and that is worth an operator's + # attention - the issue reported the silence on stderr as part of the defect. + logger.warning("rejected stdin line as %s (%s)", response.error.message, type(exc).__name__) + try: + await write_stream.send(SessionMessage(response)) + except (anyio.BrokenResourceError, anyio.ClosedResourceError): + # The session already tore down; a reply that was never written must not + # take the reader's task group with it. + logger.debug("dropped %s reply: write stream closed", response.error.code) + + @asynccontextmanager async def stdio_server(stdin: anyio.AsyncFile[str] | None = None, stdout: anyio.AsyncFile[str] | None = None): """Serve MCP over the process's stdin and stdout. @@ -188,6 +302,9 @@ async def stdin_reader(): try: message = types.jsonrpc_message_adapter.validate_json(line, by_name=False) except Exception as exc: + # Forward the fault to observers, and answer the client: + # a dropped line leaves its call pending until timeout. + await _reply_to_invalid_line(write_stream, line, exc) await read_stream_writer.send(exc) continue diff --git a/tests/interaction/auth/test_as_handlers.py b/tests/interaction/auth/test_as_handlers.py index 1876cd7181..d153a4f584 100644 --- a/tests/interaction/auth/test_as_handlers.py +++ b/tests/interaction/auth/test_as_handlers.py @@ -256,6 +256,69 @@ async def test_registration_with_invalid_metadata_is_rejected_with_400( ) +@requirement("hosting:auth:as:register-error-response") +@pytest.mark.parametrize( + ("label", "payload"), + [ + # RFC 7591 §2 makes redirect_uris REQUIRED for redirection flows; the model + # rejects the three spellings below at parse time. + ("omitted", {}), + ("empty-array", {"redirect_uris": []}), + # The one the model lets through: `list[AnyUrl] | None` is there so non-redirect + # clients (client_credentials, identity assertion) can build the model with None, + # and None satisfies the union, bypassing min_length=1 (issue #3885). + ("explicit-null", {"redirect_uris": None}), + ], + ids=["omitted", "empty-array", "explicit-null"], +) +async def test_registration_without_redirect_uris_is_rejected_with_400( + as_app: tuple[httpx2.AsyncClient, InMemoryAuthorizationServerProvider], + label: str, + payload: dict[str, object], +) -> None: + """Registration without usable redirect URIs is refused, and nothing is persisted. + + Regression lock for issue #3885: `{"redirect_uris": null}` returned `201 Created`, + minting a client_id/client_secret and storing a client whose every `/authorize` + request would then fail `validate_redirect_uri()` with `InvalidRedirectUriError`. + RFC 7591 §2: "Clients using flows with redirection MUST register their redirection + URI values"; this handler only accepts the authorization_code grant. + """ + http, provider = as_app + registered_before = len(provider.clients) + + response = await http.post("/register", json=payload | {"client_name": label}) + + assert response.status_code == 400, label + body = response.json() + assert body["error"] == "invalid_client_metadata", label + # The description is the model's for the two it rejects itself, and the handler's + # own for the null spelling; either way the defect is named. + assert "redirect_uris" in body["error_description"], label + # No credentials minted, nothing stored: the refusal is total, not cosmetic. + assert "client_id" not in body, label + assert len(provider.clients) == registered_before, label + + +@requirement("hosting:auth:as:register-error-response") +async def test_registration_with_redirect_uris_still_succeeds( + as_app: tuple[httpx2.AsyncClient, InMemoryAuthorizationServerProvider], +) -> None: + """The new null check does not narrow the accepted path: a normal registration still 201s. + + Guards against over-rejecting - `redirect_uris` present and non-empty must keep + working, and the stored client must be able to resolve its redirect. + """ + http, provider = as_app + + response = await http.post("/register", json=oauth_client_metadata().model_dump(mode="json", exclude_none=True)) + + assert response.status_code == 201 + client_info = OAuthClientInformationFull.model_validate_json(response.content) + assert client_info.redirect_uris + assert provider.clients[client_info.client_id].redirect_uris == client_info.redirect_uris + + @requirement("hosting:auth:as:register-echo") @pytest.mark.parametrize("application_type", ["web", "native"]) async def test_registration_response_echoes_the_registered_application_type( diff --git a/tests/server/test_stdio.py b/tests/server/test_stdio.py index eafd1fca59..21d3c0461e 100644 --- a/tests/server/test_stdio.py +++ b/tests/server/test_stdio.py @@ -9,6 +9,7 @@ import anyio import anyio.to_thread +import mcp_types as types import pytest from mcp_types import ( CLIENT_CAPABILITIES_META_KEY, @@ -26,6 +27,15 @@ from mcp.server.stdio import stdio_server from mcp.shared.message import SessionMessage +LONE_SURROGATE_LINE = ( + '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"text":"bad \\ud83d bad"}}}' +) +"""The request line from issue #3894: pure ASCII, but pydantic-core rejects the escape. + +`json.dumps(ensure_ascii=True)` emits `\\ud83d` for text cut in the middle of an emoji, so +this is what a real client produces from a sliced stream - not a hand-crafted attack. +""" + @pytest.mark.anyio async def test_stdio_server_round_trips_messages_over_injected_streams() -> None: @@ -97,6 +107,167 @@ async def test_stdio_server_invalid_utf8(monkeypatch: pytest.MonkeyPatch) -> Non assert second.message == valid +async def _serve_lines( + lines: list[str], +) -> tuple[list[SessionMessage | Exception], list[JSONRPCMessage]]: + """Drive `stdio_server()` over injected streams with `lines` on stdin. + + Returns what the transport handed the session (one item per line) and what it wrote + to the wire. The test plays the session's part here, so only the *transport's* own + output lands in the second list - the error replies this fix adds. The write side is + closed before the context exits, or the writer task never finishes and the task-group + join deadlocks. + """ + stdin = io.StringIO("".join(line if line.endswith("\n") else line + "\n" for line in lines)) + stdout = io.StringIO() + + with anyio.fail_after(5): + async with stdio_server(stdin=anyio.AsyncFile(stdin), stdout=anyio.AsyncFile(stdout)) as ( + read_stream, + write_stream, + ): + try: + async with read_stream: + # One item per line, so the reader never blocks on a full stream. + received: list[SessionMessage | Exception] = [await read_stream.receive() for _ in lines] + finally: + await write_stream.aclose() + + stdout.seek(0) + return received, [jsonrpc_message_adapter.validate_json(line) for line in stdout.readlines()] + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("label", "line", "expected_id", "expected_code"), + [ + # Well-formed JSON, unusable envelope: -32600. The id is recoverable, so the + # client's pending call is answered rather than left to time out. + ("missing-method", '{"jsonrpc":"2.0","id":7}', 7, types.INVALID_REQUEST), + ("wrong-version", '{"jsonrpc":"1.0","id":8,"method":"ping"}', 8, types.INVALID_REQUEST), + ("params-not-object", '{"jsonrpc":"2.0","id":10,"method":"ping","params":[1]}', 10, types.INVALID_REQUEST), + # A string id is a valid RequestId, so it is echoed verbatim. + ("string-id", '{"jsonrpc":"2.0","id":"req-a","method":7}', "req-a", types.INVALID_REQUEST), + # Well-formed JSON with no usable id: -32600 with `id: null`. `true` is a bool, + # not the int it subclasses; a float and an array match neither RequestId arm. + # Each needs another defect to reach the envelope rung: on its own an unusable + # `id` makes the union fall through to the notification arm, which ignores it. + ("bool-id", '{"jsonrpc":"2.0","id":true,"method":7}', None, types.INVALID_REQUEST), + ("float-id", '{"jsonrpc":"1.0","id":1.5,"method":"ping"}', None, types.INVALID_REQUEST), + ("array-id", '{"jsonrpc":"1.0","id":[1],"method":"ping"}', None, types.INVALID_REQUEST), + ("explicit-null-id", '{"jsonrpc":"2.0","id":null,"method":7}', None, types.INVALID_REQUEST), + ("empty-object", "{}", None, types.INVALID_REQUEST), + ("batch-array", '[{"jsonrpc":"2.0","id":1,"method":"ping"}]', None, types.INVALID_REQUEST), + ("bare-scalar", "123", None, types.INVALID_REQUEST), + # Not JSON at all: -32700, with the id recovered from the lenient decode where + # one exists (the lone surrogate case from issue #3894) and `null` otherwise. + ("lone-surrogate", LONE_SURROGATE_LINE, 3, types.PARSE_ERROR), + ("truncated", '{"jsonrpc":"2.0","id":3,"method":', None, types.PARSE_ERROR), + ("plain-text", "not json", None, types.PARSE_ERROR), + ], +) +async def test_stdio_server_answers_an_invalid_line_with_a_jsonrpc_error( + label: str, line: str, expected_id: object, expected_code: int +) -> None: + """A stdin line that fails validation gets the JSON-RPC error it is owed, not silence. + + Regression lock for issue #3894: the reader forwarded the exception and dropped the + line, and because server sessions install no `on_stream_exception` the dispatcher + logged it at debug level. The client's call then 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. + """ + valid = JSONRPCRequest(jsonrpc="2.0", id=1, method="ping") + + received, written = await _serve_lines([valid.model_dump_json(by_alias=True), line]) + + # The valid request still reaches the session, unchanged. + assert received[0] == SessionMessage(valid), label + # The bad line surfaces as an exception to observers, as before, *and* on the wire. + assert isinstance(received[1], Exception), label + assert len(written) == 1, f"{label}: expected exactly one reply line, got {written!r}" + error = written[0] + assert isinstance(error, types.JSONRPCError), label + assert error.id == expected_id, label + assert error.error.code == expected_code, label + + +@pytest.mark.anyio +async def test_stdio_server_still_streams_after_answering_an_invalid_line() -> None: + """Answering a bad line does not end the stream: later requests are served normally. + + The issue's repro sent a normal call, a lone-surrogate line, then another normal call; + the trailing call arriving proves the reader kept going (it already `continue`d, so + this locks the behaviour the fix must not regress). + """ + first = JSONRPCRequest(jsonrpc="2.0", id=1, method="ping") + last = JSONRPCRequest(jsonrpc="2.0", id=4, method="ping") + + received, written = await _serve_lines( + [first.model_dump_json(by_alias=True), LONE_SURROGATE_LINE, last.model_dump_json(by_alias=True)] + ) + + assert received[0] == SessionMessage(first) + assert isinstance(received[1], Exception) + assert received[2] == SessionMessage(last) + assert [reply.id for reply in written if isinstance(reply, types.JSONRPCError)] == [3] + + +@pytest.mark.anyio +async def test_stdio_server_answers_a_line_whose_id_is_itself_unserializable() -> None: + """A lone surrogate in the id itself is answered with `id: null`, not dropped. + + Echoing that id would put it back on the wire, where serializing the reply raises + `UnicodeEncodeError` and kills the writer - trading a silent hang for a dead transport. + An id this server cannot reproduce is undeterminable, and §5 answers those with `null`. + """ + valid = JSONRPCRequest(jsonrpc="2.0", id=1, method="ping") + + _, written = await _serve_lines( + [valid.model_dump_json(by_alias=True), '{"jsonrpc":"2.0","id":"bad \\ud83d","method":"ping"}'] + ) + + assert len(written) == 1 + error = written[0] + assert isinstance(error, types.JSONRPCError) + assert error.id is None + assert error.error.code == types.PARSE_ERROR + + +@pytest.mark.anyio +async def test_stdio_server_acknowledges_a_line_that_is_only_a_newline() -> None: + """A blank line is malformed JSON, so it is answered with `-32700` and an `id: null`.""" + valid = JSONRPCRequest(jsonrpc="2.0", id=1, method="ping") + + _, written = await _serve_lines([valid.model_dump_json(by_alias=True), ""]) + + assert len(written) == 1 + error = written[0] + assert isinstance(error, types.JSONRPCError) + assert error.id is None + assert error.error.code == types.PARSE_ERROR + + +@pytest.mark.anyio +async def test_a_dropped_reply_for_an_invalid_line_does_not_kill_the_reader() -> None: + """If the session closed the write stream first, the reply send is swallowed, not raised. + + A transport torn down between reading a bad line and answering it must not surface a + `ClosedResourceError` from the reader's task group - the pre-fix code never wrote, so + this path is new and needs its own lock. + """ + line = '{"jsonrpc":"2.0","id":3,"method":"ping","params":[1]}' + + with anyio.fail_after(5): + async with stdio_server( + stdin=anyio.AsyncFile(io.StringIO(line + "\n")), stdout=anyio.AsyncFile(io.StringIO()) + ) as (read_stream, write_stream): + await write_stream.aclose() + async with read_stream: # pragma: no branch + first = await read_stream.receive() + assert isinstance(first, Exception) + + @contextmanager def _pipe_planted_on_fd0(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[int, int]]: """Plants a fresh pipe on fd 0 and rebinds sys.stdin over it; yields (read_fd, write_fd). @@ -616,6 +787,16 @@ def _serve_stdio_and_collect( `responses` lines arrive - as a real client would - so handlers never race EOF cancellation. """ payload = "".join(f.model_dump_json(by_alias=True, exclude_none=True) + "\n" for f in frames).encode() + return _serve_raw_stdio_and_collect(monkeypatch, server, payload, responses) + + +def _serve_raw_stdio_and_collect( + monkeypatch: pytest.MonkeyPatch, server: MCPServer, payload: bytes, responses: int +) -> list[JSONRPCMessage]: + """Like `_serve_stdio_and_collect`, but the caller supplies the exact wire bytes. + + Needed for a line that a model cannot produce: the issue's lone-surrogate request. + """ stdin = _GatedStdin(payload) stdout = _NotifyingStdout() monkeypatch.setattr(sys, "stdin", TextIOWrapper(stdin, encoding="utf-8")) @@ -692,3 +873,61 @@ def test_mcpserver_run_stdio_serves_a_modern_connection(monkeypatch: pytest.Monk # resultType is modern-only: proves the request was served at the discovered version. assert responses[1].result["tools"] == [] assert responses[1].result["resultType"] == "complete" + + +def test_mcpserver_run_stdio_answers_the_issue_3894_lone_surrogate_line( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """End to end over process stdio: the issue's bad line is answered, and serving continues. + + The reported repro is `initialize`, a normal `tools/call`, the lone-surrogate line, then a + normal call again. Before the fix the third line produced nothing and the client hung; here + the error arrives addressed to id 3 and the trailing call is still served. + """ + initialize = JSONRPCRequest( + jsonrpc="2.0", + id=1, + method="initialize", + params={ + "protocolVersion": "2025-06-18", + "capabilities": {}, + "clientInfo": {"name": "repro", "version": "0"}, + }, + ) + normal = JSONRPCRequest( + jsonrpc="2.0", id=2, method="tools/call", params={"name": "echo", "arguments": {"text": "hello"}} + ) + after = JSONRPCRequest( + jsonrpc="2.0", id=4, method="tools/call", params={"name": "echo", "arguments": {"text": "world"}} + ) + + payload = "".join( + [ + initialize.model_dump_json(by_alias=True, exclude_unset=True) + "\n", + normal.model_dump_json(by_alias=True) + "\n", + LONE_SURROGATE_LINE + "\n", + after.model_dump_json(by_alias=True) + "\n", + ] + ).encode() + + # The loom is never touched: the bad line fails before dispatch, which is the point. + server = MCPServer(name="LoneSurrogateServer") + + @server.tool(name="echo") + def echo(text: str) -> str: + return text + + responses = _serve_raw_stdio_and_collect(monkeypatch, server, payload, 4) + + # Replies are correlated by id, not by arrival order: the error is written by the + # transport reader the moment the bad line is read, so it can overtake a request + # the dispatcher is still serving. That is the point - it needs no round trip. + by_id = {response.id: response for response in responses} + assert set(by_id) == {1, 2, 3, 4} + + assert isinstance(by_id[1], JSONRPCResponse) + assert isinstance(by_id[2], JSONRPCResponse) + # The line that used to vanish now carries a reply the client can correlate. + assert isinstance(by_id[3], types.JSONRPCError) + assert by_id[3].error.code == types.PARSE_ERROR + assert isinstance(by_id[4], JSONRPCResponse)