Skip to content

Commit 3562cd3

Browse files
committed
Answer stdio lines that fail JSON-RPC validation with a Parse error
A request line that fails validate_json (e.g. carrying a lone surrogate escape, which pydantic-core rejects) was dropped with no reply, so the client's call hung until its own timeout. Reply -32700 per JSON-RPC 2.0, echoing the request id recovered from the raw line with stdlib json - it tolerates the escapes pydantic-core rejects - or null when the id cannot be recovered. Notification-shaped lines (an object without an id member, the same key-presence rule as the streamable-HTTP entry) are never answered. Fixes #3894
1 parent 77001c9 commit 3562cd3

2 files changed

Lines changed: 211 additions & 7 deletions

File tree

‎src/mcp/server/stdio.py‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,16 @@ async def run_server():
1111
```
1212
"""
1313

14+
import json
15+
import logging
1416
import os
1517
import sys
1618
import threading
1719
from collections.abc import Callable
1820
from contextlib import asynccontextmanager, suppress
1921
from dataclasses import dataclass
2022
from io import TextIOWrapper
21-
from typing import BinaryIO, Literal, TextIO
23+
from typing import Any, BinaryIO, Literal, TextIO, cast
2224

2325
import anyio
2426
import anyio.lowlevel
@@ -28,6 +30,8 @@ async def run_server():
2830
from mcp.shared._context_streams import create_context_streams
2931
from mcp.shared.message import SessionMessage
3032

33+
logger = logging.getLogger(__name__)
34+
3135
if sys.platform != "win32": # pragma: no branch
3236
import fcntl # pragma: lax no cover - POSIX-only line, uncovered on Windows runners
3337

@@ -158,6 +162,38 @@ def release() -> None:
158162
return os.fdopen(private_fd, mode, closefd=False), release
159163

160164

165+
def _parse_error_reply(line: str) -> types.JSONRPCError | None:
166+
"""The Parse error owed for a line that failed JSON-RPC validation, or ``None``.
167+
168+
JSON-RPC 2.0: a message the server cannot read is answered with -32700,
169+
echoing the request id when the raw line yields it - stdlib ``json``
170+
tolerates escapes pydantic-core rejects (e.g. a lone surrogate escape),
171+
so the id often survives validation - and ``null`` otherwise. A
172+
notification-shaped line (an object without an ``id`` member, the same
173+
key-presence rule as the streamable-HTTP entry) is never answered.
174+
"""
175+
try:
176+
document: object = json.loads(line)
177+
except ValueError:
178+
document = None
179+
if not isinstance(document, dict):
180+
return types.JSONRPCError(
181+
jsonrpc="2.0", id=None, error=types.ErrorData(code=types.PARSE_ERROR, message="Parse error")
182+
)
183+
# json.loads is untyped; the dict-ness is proven above, so narrow explicitly.
184+
decoded = cast("dict[str, Any]", document)
185+
if "id" not in decoded and "method" in decoded:
186+
return None
187+
request_id: object = decoded.get("id")
188+
if isinstance(request_id, str | int) and not isinstance(request_id, bool):
189+
return types.JSONRPCError(
190+
jsonrpc="2.0", id=request_id, error=types.ErrorData(code=types.PARSE_ERROR, message="Parse error")
191+
)
192+
return types.JSONRPCError(
193+
jsonrpc="2.0", id=None, error=types.ErrorData(code=types.PARSE_ERROR, message="Parse error")
194+
)
195+
196+
161197
@asynccontextmanager
162198
async def stdio_server(stdin: anyio.AsyncFile[str] | None = None, stdout: anyio.AsyncFile[str] | None = None):
163199
"""Serve MCP over the process's stdin and stdout.
@@ -188,7 +224,13 @@ async def stdin_reader():
188224
try:
189225
message = types.jsonrpc_message_adapter.validate_json(line, by_name=False)
190226
except Exception as exc:
227+
logger.exception("failed to parse JSON-RPC line")
191228
await read_stream_writer.send(exc)
229+
if (reply := _parse_error_reply(line)) is not None:
230+
try:
231+
await write_stream.send(SessionMessage(reply))
232+
except (anyio.BrokenResourceError, anyio.ClosedResourceError):
233+
logger.debug("dropped parse error reply: write stream closed")
192234
continue
193235

194236
session_message = SessionMessage(message)

‎tests/server/test_stdio.py‎

Lines changed: 168 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,11 @@
1313
from mcp_types import (
1414
CLIENT_CAPABILITIES_META_KEY,
1515
CLIENT_INFO_META_KEY,
16+
PARSE_ERROR,
1617
PROTOCOL_VERSION_META_KEY,
1718
SERVER_INFO_META_KEY,
19+
ErrorData,
20+
JSONRPCError,
1821
JSONRPCMessage,
1922
JSONRPCRequest,
2023
JSONRPCResponse,
@@ -97,6 +100,127 @@ async def test_stdio_server_invalid_utf8(monkeypatch: pytest.MonkeyPatch) -> Non
97100
assert second.message == valid
98101

99102

103+
def _bad_text_line(id_json: str = "3") -> str:
104+
"""A pure-ASCII request line pydantic rejects: a lone surrogate escape (issue #3894)."""
105+
return f'{{"jsonrpc":"2.0","id":{id_json},"method":"ping","params":{{"text":"bad \\ud83d bad"}}}}'
106+
107+
108+
@pytest.mark.anyio
109+
@pytest.mark.parametrize(
110+
("line", "expected_id"),
111+
[
112+
("not json at all", None),
113+
("[1,2,3]", None),
114+
('{"foo": 1}', None),
115+
(_bad_text_line("true"), None),
116+
(_bad_text_line("{}"), None),
117+
(_bad_text_line("3"), 3),
118+
(_bad_text_line('"s3"'), "s3"),
119+
],
120+
ids=["not-json", "array", "no-id-no-method", "boolean-id", "object-id", "int-id", "str-id"],
121+
)
122+
async def test_stdio_server_answers_an_invalid_line_with_a_parse_error(
123+
line: str, expected_id: str | int | None
124+
) -> None:
125+
"""A line that fails validation is answered with -32700 echoing a recoverable id, and serving continues.
126+
127+
Spec-mandated reply shape (JSON-RPC 2.0) with SDK-defined id recovery: the
128+
raw line is re-parsed with stdlib json, which tolerates the lone surrogate
129+
escapes pydantic-core rejects, so a client's pending call can correlate.
130+
The typed API cannot produce these lines, so they are scripted raw.
131+
"""
132+
ping = JSONRPCRequest(jsonrpc="2.0", id=4, method="ping")
133+
stdin = io.StringIO(line + "\n" + ping.model_dump_json(by_alias=True, exclude_none=True) + "\n")
134+
stdout = io.StringIO()
135+
136+
with anyio.fail_after(5):
137+
async with stdio_server(stdin=anyio.AsyncFile(stdin), stdout=anyio.AsyncFile(stdout)) as (
138+
read_stream,
139+
write_stream,
140+
):
141+
async with read_stream:
142+
failure = await read_stream.receive()
143+
assert isinstance(failure, Exception)
144+
145+
followup = await read_stream.receive()
146+
assert isinstance(followup, SessionMessage)
147+
assert followup.message == ping
148+
await write_stream.aclose()
149+
150+
stdout.seek(0)
151+
output_lines = stdout.readlines()
152+
assert len(output_lines) == 1
153+
assert jsonrpc_message_adapter.validate_json(output_lines[0].strip()) == JSONRPCError(
154+
jsonrpc="2.0", id=expected_id, error=ErrorData(code=PARSE_ERROR, message="Parse error")
155+
)
156+
157+
158+
@pytest.mark.anyio
159+
async def test_stdio_server_does_not_answer_a_notification_shaped_line() -> None:
160+
"""A notification-shaped line that fails validation is dropped, never answered.
161+
162+
JSON-RPC 2.0 §4.1: the server MUST NOT reply to a notification; the
163+
unreadable line surfaces as an in-stream exception and later traffic
164+
continues (issue #3894).
165+
"""
166+
notification_line = (
167+
'{"jsonrpc":"2.0","method":"tools/call","params":{"name":"echo","arguments":{"text":"bad \\ud83d bad"}}}'
168+
)
169+
ping = JSONRPCRequest(jsonrpc="2.0", id=4, method="ping")
170+
response = JSONRPCResponse(jsonrpc="2.0", id=4, result={})
171+
stdin = io.StringIO(notification_line + "\n" + ping.model_dump_json(by_alias=True, exclude_none=True) + "\n")
172+
stdout = io.StringIO()
173+
174+
with anyio.fail_after(5):
175+
async with stdio_server(stdin=anyio.AsyncFile(stdin), stdout=anyio.AsyncFile(stdout)) as (
176+
read_stream,
177+
write_stream,
178+
):
179+
async with read_stream:
180+
failure = await read_stream.receive()
181+
assert isinstance(failure, Exception)
182+
183+
followup = await read_stream.receive()
184+
assert isinstance(followup, SessionMessage)
185+
assert followup.message == ping
186+
187+
await write_stream.send(SessionMessage(response))
188+
await write_stream.aclose()
189+
190+
stdout.seek(0)
191+
assert [jsonrpc_message_adapter.validate_json(line) for line in stdout.readlines()] == [response]
192+
193+
194+
@pytest.mark.anyio
195+
async def test_stdio_server_drops_the_parse_error_reply_when_the_write_stream_is_closed() -> None:
196+
"""A parse error reply racing a closed write stream is dropped without killing the reader.
197+
198+
SDK-defined: the dispatcher closes the write stream when the connection
199+
ends, and the transport's best-effort reply must not turn that shutdown
200+
into an error; stdin keeps being read afterwards.
201+
"""
202+
ping = JSONRPCRequest(jsonrpc="2.0", id=4, method="ping")
203+
stdin = io.StringIO(_bad_text_line("3") + "\n" + ping.model_dump_json(by_alias=True, exclude_none=True) + "\n")
204+
stdout = io.StringIO()
205+
206+
with anyio.fail_after(5):
207+
async with stdio_server(stdin=anyio.AsyncFile(stdin), stdout=anyio.AsyncFile(stdout)) as (
208+
read_stream,
209+
write_stream,
210+
):
211+
write_stream.close()
212+
async with read_stream:
213+
failure = await read_stream.receive()
214+
assert isinstance(failure, Exception)
215+
216+
followup = await read_stream.receive()
217+
assert isinstance(followup, SessionMessage)
218+
assert followup.message == ping
219+
await write_stream.aclose()
220+
221+
assert stdout.getvalue() == ""
222+
223+
100224
@contextmanager
101225
def _pipe_planted_on_fd0(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[int, int]]:
102226
"""Plants a fresh pipe on fd 0 and rebinds sys.stdin over it; yields (read_fd, write_fd).
@@ -607,15 +731,18 @@ def close(self) -> None:
607731
pass
608732

609733

610-
def _serve_stdio_and_collect(
611-
monkeypatch: pytest.MonkeyPatch, server: MCPServer, frames: list[JSONRPCRequest], responses: int
734+
def _serve_stdio_lines_and_collect(
735+
monkeypatch: pytest.MonkeyPatch, server: MCPServer, lines: list[str], responses: int
612736
) -> list[JSONRPCMessage]:
613-
"""Serve `frames` over process stdio and return the parsed response lines.
737+
"""Serve raw wire lines over process stdio and return the parsed response lines.
614738
615-
Runs the blocking server.run("stdio") in a daemon thread and signals stdin EOF only after
616-
`responses` lines arrive - as a real client would - so handlers never race EOF cancellation.
739+
`_serve_stdio_and_collect` frames typed messages; malformed wire input can
740+
only be produced as raw lines, so this twin takes them verbatim. Runs the
741+
blocking server.run("stdio") in a daemon thread and signals stdin EOF only
742+
after `responses` lines arrive - as a real client would - so handlers
743+
never race EOF cancellation.
617744
"""
618-
payload = "".join(f.model_dump_json(by_alias=True, exclude_none=True) + "\n" for f in frames).encode()
745+
payload = "".join(line + "\n" for line in lines).encode()
619746
stdin = _GatedStdin(payload)
620747
stdout = _NotifyingStdout()
621748
monkeypatch.setattr(sys, "stdin", TextIOWrapper(stdin, encoding="utf-8"))
@@ -634,6 +761,18 @@ def target() -> None:
634761
return [jsonrpc_message_adapter.validate_json(line) for line in stdout.getvalue().decode().splitlines()]
635762

636763

764+
def _serve_stdio_and_collect(
765+
monkeypatch: pytest.MonkeyPatch, server: MCPServer, frames: list[JSONRPCRequest], responses: int
766+
) -> list[JSONRPCMessage]:
767+
"""Serve `frames` over process stdio and return the parsed response lines."""
768+
return _serve_stdio_lines_and_collect(
769+
monkeypatch,
770+
server,
771+
[frame.model_dump_json(by_alias=True, exclude_none=True) for frame in frames],
772+
responses,
773+
)
774+
775+
637776
def test_mcpserver_run_stdio_serves_until_stdin_closes(monkeypatch: pytest.MonkeyPatch) -> None:
638777
"""`MCPServer.run("stdio")` serves over process stdio and returns at stdin EOF."""
639778
ping = JSONRPCRequest(jsonrpc="2.0", id=1, method="ping")
@@ -692,3 +831,26 @@ def test_mcpserver_run_stdio_serves_a_modern_connection(monkeypatch: pytest.Monk
692831
# resultType is modern-only: proves the request was served at the discovered version.
693832
assert responses[1].result["tools"] == []
694833
assert responses[1].result["resultType"] == "complete"
834+
835+
836+
def test_mcpserver_run_stdio_answers_a_malformed_line_and_keeps_serving(monkeypatch: pytest.MonkeyPatch) -> None:
837+
"""`run("stdio")` replies -32700 with the recovered id to a lone-surrogate line, then serves normally.
838+
839+
Regression for issue #3894: the reply rides the real dispatcher path, so
840+
the wire carries the Parse error for id 3 followed by the response to id 4.
841+
"""
842+
bad_line = (
843+
'{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"text":"bad \\ud83d bad"}}}'
844+
)
845+
ping = JSONRPCRequest(jsonrpc="2.0", id=4, method="ping")
846+
847+
server = MCPServer(name="ParseErrorStdioServer")
848+
responses = _serve_stdio_lines_and_collect(
849+
monkeypatch,
850+
server,
851+
[bad_line, ping.model_dump_json(by_alias=True, exclude_none=True)],
852+
2,
853+
)
854+
855+
assert responses[0] == JSONRPCError(jsonrpc="2.0", id=3, error=ErrorData(code=PARSE_ERROR, message="Parse error"))
856+
assert responses[1] == JSONRPCResponse(jsonrpc="2.0", id=4, result={})

0 commit comments

Comments
 (0)