Skip to content
Open
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
4 changes: 2 additions & 2 deletions src/mcp/server/stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ async def stdio_server(stdin: anyio.AsyncFile[str] | None = None, stdout: anyio.
# python is platform-dependent (Windows is particularly problematic), so we
# re-wrap the underlying binary stream to ensure UTF-8.
if not stdin:
stdin = anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding="utf-8", errors="replace"))
stdin = anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding="utf-8", errors="replace", newline=""))
if not stdout:
stdout = anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding="utf-8"))
stdout = anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding="utf-8", newline=""))

read_stream_writer, read_stream = create_context_streams[SessionMessage | Exception](0)
write_stream, write_stream_reader = create_context_streams[SessionMessage](0)
Expand Down
23 changes: 23 additions & 0 deletions tests/server/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,29 @@ async def test_stdio_server():
assert received_responses[1] == JSONRPCResponse(jsonrpc="2.0", id=4, result={})


@pytest.mark.anyio
async def test_stdio_server_uses_lf_newlines_with_default_stdout(monkeypatch: pytest.MonkeyPatch):
class UnclosableBytesIO(io.BytesIO):
def close(self) -> None:
pass

raw_stdout = UnclosableBytesIO()
monkeypatch.setattr(sys, "stdin", TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
monkeypatch.setattr(sys, "stdout", TextIOWrapper(raw_stdout, encoding="utf-8"))

response = JSONRPCRequest(jsonrpc="2.0", id=3, method="ping")

with anyio.fail_after(5):
async with stdio_server() as (read_stream, write_stream):
await read_stream.aclose()
async with write_stream: # pragma: no branch
await write_stream.send(SessionMessage(response))

raw_bytes = raw_stdout.getvalue()
assert raw_bytes.endswith(b"\n")
assert b"\r\n" not in raw_bytes


@pytest.mark.anyio
async def test_stdio_server_invalid_utf8(monkeypatch: pytest.MonkeyPatch):
"""Non-UTF-8 bytes on stdin must not crash the server.
Expand Down
Loading