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
25 changes: 25 additions & 0 deletions src/mcp/server/stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ async def run_server():
```
"""

import json
import os
import sys
import threading
Expand Down Expand Up @@ -158,6 +159,18 @@ def release() -> None:
return os.fdopen(private_fd, mode, closefd=False), release


def _extract_request_id(line: str) -> str | int | None:
try:
parsed = json.loads(line)
except Exception:
return None
if isinstance(parsed, dict):
req_id = parsed.get("id") # type: ignore[reportUnknownMemberType]
if isinstance(req_id, str | int) and not isinstance(req_id, bool):
return req_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 +201,18 @@ async def stdin_reader():
try:
message = types.jsonrpc_message_adapter.validate_json(line, by_name=False)
except Exception as exc:
req_id = _extract_request_id(line)
if req_id is not None:
err_resp = types.JSONRPCError(
jsonrpc="2.0",
id=req_id,
error=types.ErrorData(
code=types.INVALID_REQUEST,
message=f"Invalid JSON-RPC message: {exc}",
),
)
with suppress(anyio.ClosedResourceError, anyio.BrokenResourceError):
await write_stream.send(SessionMessage(err_resp))
await read_stream_writer.send(exc)
continue

Expand Down
27 changes: 27 additions & 0 deletions tests/server/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -692,3 +692,30 @@ 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_with_error_for_invalid_json_with_id() -> None:
"""Requests that fail JSON validation (e.g. lone surrogates) still receive a JSONRPCError."""
from mcp_types import INVALID_REQUEST, JSONRPCError

stdin = io.StringIO('{"jsonrpc": "2.0", "id": 7, "method": "ping", "params": {"s": "\\ud83d"}}\n')
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,
):
async with read_stream:
item = await read_stream.receive()
assert isinstance(item, Exception)
await write_stream.aclose()

stdout.seek(0)
output_lines = stdout.readlines()
assert len(output_lines) == 1
reply = jsonrpc_message_adapter.validate_json(output_lines[0].strip())
assert isinstance(reply, JSONRPCError)
assert reply.id == 7
assert reply.error.code == INVALID_REQUEST
Loading