Skip to content

Commit ad7adbc

Browse files
committed
fix(stdio): handle lone surrogates and reply with parse error on invalid JSON
Fixes #3894. A stdio server previously dropped any input line that failed JSON validation, leaving the client hanging indefinitely until timeout. In addition, lone surrogates in JSON strings were rejected by Pydantic's JSON parser. This fix: 1. Sanitizes lone UTF-16 surrogates to U+FFFD before validation while preserving valid surrogate pairs. 2. Replies with a JSON-RPC Parse Error (-32700) on invalid JSON lines instead of silently dropping them, attempting to preserve the request id when extractable. 3. Continues to deliver the parse exception to the reader stream for backwards compatibility.
1 parent 77001c9 commit ad7adbc

2 files changed

Lines changed: 110 additions & 1 deletion

File tree

‎src/mcp/server/stdio.py‎

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

14+
import json
1415
import os
16+
import re
1517
import sys
1618
import threading
1719
from collections.abc import Callable
@@ -31,6 +33,32 @@ async def run_server():
3133
if sys.platform != "win32": # pragma: no branch
3234
import fcntl # pragma: lax no cover - POSIX-only line, uncovered on Windows runners
3335

36+
_SURROGATE_ESCAPE_PATTERN = re.compile(
37+
r"(\\u[dD][89abAB][0-9a-fA-F]{2})((?:\\u[dD][c-fC-F][0-9a-fA-F]{2})?)"
38+
r"|(\\u[dD][c-fC-F][0-9a-fA-F]{2})"
39+
)
40+
_RECOVER_ID_PATTERN = re.compile(r'"id"\s*:\s*([0-9]+|"(?:[^"\\]|\\.)*")')
41+
42+
43+
def _sanitize_lone_surrogates(text: str) -> str:
44+
"""Replace unescaped and escaped lone UTF-16 surrogates with U+FFFD.
45+
46+
Pairs of surrogate escapes like \ud83d\ude00 form valid characters and are preserved.
47+
Unpaired surrogates (e.g. lone \ud83d) are rejected by Pydantic's JSON parser.
48+
"""
49+
text = text.encode("utf-16", "surrogatepass").decode("utf-16", "replace")
50+
51+
def repl(m: re.Match[str]) -> str:
52+
high, low, lone_low = m.group(1), m.group(2), m.group(3)
53+
if lone_low:
54+
return "\ufffd"
55+
if high and not low:
56+
return "\ufffd"
57+
return m.group(0)
58+
59+
return _SURROGATE_ESCAPE_PATTERN.sub(repl, text)
60+
61+
3462
# Stream-claim contract (design and attack log in PR #3117):
3563
# - _claims is the single authority for who owns fd 0/1; mutated only under the
3664
# lock, only by acquire's insert and release's deregister.
@@ -186,8 +214,27 @@ async def stdin_reader():
186214
async with read_stream_writer:
187215
async for line in stdin:
188216
try:
189-
message = types.jsonrpc_message_adapter.validate_json(line, by_name=False)
217+
clean_line = _sanitize_lone_surrogates(line)
218+
message = types.jsonrpc_message_adapter.validate_json(clean_line, by_name=False)
190219
except Exception as exc:
220+
req_id: str | int | None = None
221+
try:
222+
m = _RECOVER_ID_PATTERN.search(line)
223+
if m:
224+
raw_val = m.group(1)
225+
req_id = json.loads(raw_val) if raw_val.startswith('"') else int(raw_val)
226+
except Exception:
227+
pass
228+
229+
err_msg = types.JSONRPCError(
230+
jsonrpc="2.0",
231+
id=req_id,
232+
error=types.ErrorData(code=types.PARSE_ERROR, message=f"Parse error: {exc}"),
233+
)
234+
try:
235+
await write_stream.send(SessionMessage(err_msg))
236+
except (anyio.BrokenResourceError, anyio.ClosedResourceError):
237+
pass
191238
await read_stream_writer.send(exc)
192239
continue
193240

‎tests/server/test_stdio.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
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+
JSONRPCError,
1820
JSONRPCMessage,
1921
JSONRPCRequest,
2022
JSONRPCResponse,
@@ -692,3 +694,63 @@ def test_mcpserver_run_stdio_serves_a_modern_connection(monkeypatch: pytest.Monk
692694
# resultType is modern-only: proves the request was served at the discovered version.
693695
assert responses[1].result["tools"] == []
694696
assert responses[1].result["resultType"] == "complete"
697+
698+
699+
@pytest.mark.anyio
700+
async def test_stdio_server_lone_surrogate_and_parse_error_handling() -> None:
701+
"""Stdio server sanitizes lone surrogate escapes and replies with -32700 on invalid JSON."""
702+
lone_surrogate_line = (
703+
'{"jsonrpc":"2.0","id":1,"method":"tools/call",'
704+
'"params":{"name":"echo","arguments":{"text":"bad \\ud83d bad"}}}\n'
705+
)
706+
valid_pair_line = (
707+
'{"jsonrpc":"2.0","id":2,"method":"tools/call",'
708+
'"params":{"name":"echo","arguments":{"text":"good \\ud83d\\ude00 smile"}}}\n'
709+
)
710+
invalid_json_with_id = '{"jsonrpc":"2.0","id":42,"method":"tools/call", INVALID_SYNTAX}\n'
711+
invalid_json_no_id = "{not even json}\n"
712+
713+
in_data = (lone_surrogate_line + valid_pair_line + invalid_json_with_id + invalid_json_no_id).encode("utf-8")
714+
stdin = anyio.wrap_file(TextIOWrapper(io.BytesIO(in_data), encoding="utf-8"))
715+
out_buf = io.BytesIO()
716+
stdout = anyio.wrap_file(TextIOWrapper(out_buf, encoding="utf-8"))
717+
718+
async with stdio_server(stdin, stdout) as (read_stream, write_stream):
719+
async with read_stream:
720+
# 1. Lone surrogate line should be sanitized and delivered as a valid JSONRPCRequest
721+
msg1 = await read_stream.receive()
722+
assert isinstance(msg1, SessionMessage)
723+
assert isinstance(msg1.message, JSONRPCRequest)
724+
assert msg1.message.id == 1
725+
assert msg1.message.params["arguments"]["text"] == "bad \ufffd bad"
726+
727+
# 2. Valid surrogate pair should be preserved
728+
msg2 = await read_stream.receive()
729+
assert isinstance(msg2, SessionMessage)
730+
assert isinstance(msg2.message, JSONRPCRequest)
731+
assert msg2.message.id == 2
732+
assert msg2.message.params["arguments"]["text"] == "good \U0001f600 smile"
733+
734+
# 3. Invalid JSON with id should deliver an Exception to read_stream
735+
exc3 = await read_stream.receive()
736+
assert isinstance(exc3, Exception)
737+
738+
# 4. Invalid JSON without id should deliver an Exception to read_stream
739+
exc4 = await read_stream.receive()
740+
assert isinstance(exc4, Exception)
741+
742+
await write_stream.aclose()
743+
744+
out_buf.seek(0)
745+
lines = [line_str.strip() for line_str in out_buf.getvalue().decode("utf-8").splitlines() if line_str.strip()]
746+
assert len(lines) == 2
747+
748+
res1 = jsonrpc_message_adapter.validate_json(lines[0])
749+
assert isinstance(res1, JSONRPCError)
750+
assert res1.id == 42
751+
assert res1.error.code == PARSE_ERROR
752+
753+
res2 = jsonrpc_message_adapter.validate_json(lines[1])
754+
assert isinstance(res2, JSONRPCError)
755+
assert res2.id is None
756+
assert res2.error.code == PARSE_ERROR

0 commit comments

Comments
 (0)