Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/mcp/server/stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ async def run_server():
```
"""

import json
import os
import sys
import threading
from collections.abc import Callable
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass
from io import TextIOWrapper
from typing import BinaryIO, Literal, TextIO
from typing import Any, BinaryIO, Literal, TextIO, cast

import anyio
import anyio.lowlevel
Expand Down Expand Up @@ -158,6 +159,19 @@ def release() -> None:
return os.fdopen(private_fd, mode, closefd=False), release


def _extract_request_id(line: str) -> types.RequestId | None:
"""Best-effort extraction of JSON-RPC request `id` when `validate_json` fails."""
try:
raw: Any = json.loads(line)
except Exception:
return None
if isinstance(raw, dict):
raw_id: Any = cast(dict[str, Any], raw).get("id")
if isinstance(raw_id, str) or (isinstance(raw_id, int) and not isinstance(raw_id, bool)):
return raw_id
return None


@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.
Expand Down Expand Up @@ -188,6 +202,16 @@ async def stdin_reader():
try:
message = types.jsonrpc_message_adapter.validate_json(line, by_name=False)
except Exception as exc:
error_response = types.JSONRPCError(
jsonrpc="2.0",
id=_extract_request_id(line),
error=types.ErrorData(
code=types.PARSE_ERROR,
message=f"Invalid JSON-RPC message: {exc}",
),
)
with suppress(anyio.ClosedResourceError):
await write_stream.send(SessionMessage(error_response))
await read_stream_writer.send(exc)
continue

Expand Down
30 changes: 30 additions & 0 deletions tests/server/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -692,3 +692,33 @@ 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"


@pytest.mark.anyio
async def test_stdio_server_replies_parse_error_on_invalid_json_line() -> None:
"""Invalid JSON-RPC request lines (such as lone surrogates) must return -32700 instead of hanging."""
import json

lone_surrogate_line = (
'{"jsonrpc":"2.0","id":3,"method":"tools/call",'
'"params":{"name":"echo","arguments":{"text":"bad \\ud83d bad"}}}\n'
)
malformed_line = "{not valid json\n"
stdin = anyio.wrap_file(io.StringIO(lone_surrogate_line + malformed_line))
out_buf = io.StringIO()
stdout = anyio.wrap_file(out_buf)

with anyio.fail_after(5):
async with stdio_server(stdin=stdin, stdout=stdout) as (read_stream, write_stream):
async with read_stream, write_stream:
received = [item async for item in read_stream]

assert len(received) == 2
assert all(isinstance(item, Exception) for item in received)

lines = [json.loads(line) for line in out_buf.getvalue().splitlines() if line.strip()]
assert len(lines) == 2
assert lines[0]["id"] == 3
assert lines[0]["error"]["code"] == -32700
assert lines[1]["id"] is None
assert lines[1]["error"]["code"] == -32700
Loading