Skip to content

Commit b8992b8

Browse files
committed
Fix stdio server newline translation on Windows
1 parent 616476f commit b8992b8

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

src/mcp/server/stdio.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ async def stdio_server(stdin: anyio.AsyncFile[str] | None = None, stdout: anyio.
3939
# python is platform-dependent (Windows is particularly problematic), so we
4040
# re-wrap the underlying binary stream to ensure UTF-8.
4141
if not stdin:
42-
stdin = anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding="utf-8", errors="replace"))
42+
stdin = anyio.wrap_file(TextIOWrapper(sys.stdin.buffer, encoding="utf-8", errors="replace", newline=""))
4343
if not stdout:
44-
stdout = anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding="utf-8"))
44+
stdout = anyio.wrap_file(TextIOWrapper(sys.stdout.buffer, encoding="utf-8", newline=""))
4545

4646
read_stream_writer, read_stream = create_context_streams[SessionMessage | Exception](0)
4747
write_stream, write_stream_reader = create_context_streams[SessionMessage](0)

tests/server/test_stdio.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,29 @@ async def test_stdio_server():
6363
assert received_responses[1] == JSONRPCResponse(jsonrpc="2.0", id=4, result={})
6464

6565

66+
@pytest.mark.anyio
67+
async def test_stdio_server_uses_lf_newlines_with_default_stdout(monkeypatch: pytest.MonkeyPatch):
68+
class UnclosableBytesIO(io.BytesIO):
69+
def close(self) -> None:
70+
pass
71+
72+
raw_stdout = UnclosableBytesIO()
73+
monkeypatch.setattr(sys, "stdin", TextIOWrapper(io.BytesIO(b""), encoding="utf-8"))
74+
monkeypatch.setattr(sys, "stdout", TextIOWrapper(raw_stdout, encoding="utf-8"))
75+
76+
response = JSONRPCRequest(jsonrpc="2.0", id=3, method="ping")
77+
78+
with anyio.fail_after(5):
79+
async with stdio_server() as (read_stream, write_stream):
80+
await read_stream.aclose()
81+
async with write_stream:
82+
await write_stream.send(SessionMessage(response))
83+
84+
raw_bytes = raw_stdout.getvalue()
85+
assert raw_bytes.endswith(b"\n")
86+
assert b"\r\n" not in raw_bytes
87+
88+
6689
@pytest.mark.anyio
6790
async def test_stdio_server_invalid_utf8(monkeypatch: pytest.MonkeyPatch):
6891
"""Non-UTF-8 bytes on stdin must not crash the server.

0 commit comments

Comments
 (0)