python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

fix: preserve stdio streams in server transport

Open pranjalbhatia710 opened this issue 6 months ago • 6 comments

Summary

  • duplicate the process stdin/stdout file descriptors before wrapping them for the stdio server transport
  • close only the duplicated wrapper streams on shutdown, preserving the original process-level streams
  • extend the stdio regression test to assert the original sys.stdin/sys.stdout wrappers remain usable after the server exits

Fixes #1933

Test plan

  • uv run --frozen pytest tests/server/test_stdio.py -q
  • uv run --frozen ruff check src/mcp/server/stdio.py tests/server/test_stdio.py
  • uv run --frozen pyright src/mcp/server/stdio.py tests/server/test_stdio.py

pranjalbhatia710 avatar May 31 '26 07:05 pranjalbhatia710

Thanks for checking this on Windows. I kept the real-stdio path on duplicated file descriptors, but added a fallback for fileno-less in-memory stdin/stdout replacements so the old test/embedding shape continues to work. Added a regression test for that path too.\n\nValidated locally:\n\nconsole\nuv run --frozen pytest tests/server/test_stdio.py -q\n# 3 passed\nuv run --frozen ruff check src/mcp/server/stdio.py tests/server/test_stdio.py\n# All checks passed\nuv run --frozen pyright src/mcp/server/stdio.py tests/server/test_stdio.py\n# 0 errors\ngit diff --check origin/main...HEAD\n

pranjalbhatia710 avatar Jun 03 '26 06:06 pranjalbhatia710

One more CI follow-up: the Python 3.14 lowest-direct jobs exposed an AnyIO subprocess startup SyntaxWarning being forwarded through stderr before the expected clean-exit marker. I adjusted the stdio interaction test to keep proving the child exited cleanly while tolerating dependency startup warnings before that marker.\n\nAdditional local validation:\n\nconsole\nuv run --frozen pytest tests/server/test_stdio.py tests/interaction/transports/test_stdio.py -q\n# 5 passed\nuv run --frozen ruff check src/mcp/server/stdio.py tests/server/test_stdio.py tests/interaction/transports/test_stdio.py\n# All checks passed\nuv run --frozen pyright src/mcp/server/stdio.py tests/server/test_stdio.py tests/interaction/transports/test_stdio.py\n# 0 errors\ngit diff --check origin/main...HEAD\n

pranjalbhatia710 avatar Jun 03 '26 06:06 pranjalbhatia710

Thanks for rechecking this on Windows. That remaining edge is real: the current fallback fixes the fileno-less crash, but it does not fully preserve replacement in-memory wrappers after the context exits.

I think the stronger guarantee is worth keeping, especially for embedders/tests that temporarily replace stdio. I’ll update the fallback so it avoids closing the caller-provided fileno-less wrappers, then rerun the focused stdio tests plus ruff/pyright. Also noted on the existing errlog=errlog pyright issue in the broader interaction test file. That looks pre-existing and outside this branch, so I’ll keep the validation scope explicit.

pranjalbhatia710 avatar Jun 03 '26 19:06 pranjalbhatia710

Updated this edge case in e626a5e: the fileno-less fallback now reuses the caller-provided sys.stdin / sys.stdout wrappers instead of creating TextIOWrapper objects around their buffers, so exiting stdio_server() no longer closes those replacement streams.

I also extended test_stdio_server_supports_fileno_less_standard_streams to assert the replacement wrappers remain open and writable/readable after the context exits.

Validated locally:

uv run --frozen pytest tests/server/test_stdio.py -q
# 3 passed
uv run --frozen pytest tests/server/test_stdio.py tests/interaction/transports/test_stdio.py -q
# 5 passed
uv run --frozen ruff check src/mcp/server/stdio.py tests/server/test_stdio.py tests/interaction/transports/test_stdio.py
# All checks passed
uv run --frozen pyright src/mcp/server/stdio.py tests/server/test_stdio.py
# 0 errors
git diff --check origin/main...HEAD

pranjalbhatia710 avatar Jun 04 '26 06:06 pranjalbhatia710

Cross-reference / consolidation note (verified independently from CI, not a fix request)

The tests/interaction/transports/test_stdio.py::test_tool_call_and_notification_round_trip_over_a_stdio_subprocess change in this PR is fixing a pre-existing, main-wide failure on the test (3.14, lowest-direct, windows-latest) matrix cell — not anything specific to this PR's feature work. I hit the identical red cell on two of my own unrelated PRs (auth/OAuth client changes that don't touch stdio at all), and reproduced the root cause:

  • lowest-direct pins anyio==4.9 (the floor from pyproject.toml: anyio>=4.9).
  • anyio/from_thread.py:119 is return result inside a finally: block. Python 3.14 emits SyntaxWarning: 'return' in a 'finally' block to stderr when the child process byte-compiles that module.
  • The child's stderr then reads ...from_thread.py:119: SyntaxWarning: 'return' in a 'finally' block\n stdio-echo: clean exit\n, so the byte-exact captured_stderr == snapshot("stdio-echo: clean exit\n") assertion fails.
  • I confirmed the return-in-finally is still present in anyio 4.10/4.11/4.12, so bumping the lower bound does not fix it — the test assertion is the right place to fix.

This is currently being patched, in parallel, inside 6 open PRs that each bundle it as collateral with unrelated work:

PR Approach
#2734 captured_stderr.endswith(snapshot("stdio-echo: clean exit\n"))
#2745 captured_stderr.endswith("stdio-echo: clean exit\n")
#2766 captured_stderr.endswith("stdio-echo: clean exit\n")
#2774 captured_stderr.endswith("stdio-echo: clean exit\n")
#2778 captured_stderr.splitlines(keepends=True)[-1:] == snapshot([...])
#2773 child env PYTHONWARNINGS=ignore::SyntaxWarning

All six are functionally equivalent for the test's stated intent (the docstring/comment says the assertion's purpose is to prove the child wrote clean exit on its own + that the transport passes stderr through — not that stderr is byte-pristine). I verified str.endswith(snapshot(...)) works (inline-snapshot's proxy forwards to the underlying str), so #2734's form is valid.

Recommendation: land one focused fix for this (the .endswith(...) last-line check reads cleanest and keeps the snapshot semantics), and drop the test edit from the other PRs to keep each PR scoped to its actual feature. I did not open a 7th duplicate PR for this — flagging instead so the parallel edits can be consolidated.

Bartok9 avatar Jun 05 '26 06:06 Bartok9

Rebased this on latest main to clear the dirty state. While resolving the rebase I dropped the collateral tests/interaction/transports/test_stdio.py stderr assertion tweak, since main now handles the Python 3.14/AnyIO startup warning via PYTHONWARNINGS and the useful part of this PR is the stdio preservation fix.\n\nCurrent branch keeps the focused changes to:\n- duplicate real stdin/stdout fds before wrapping them so process stdio wrappers stay open\n- support fileno-less replacement streams without closing caller-provided wrappers\n- cover the real-fd, fileno-less, invalid UTF-8, and MCPServer.run stdio paths\n\nValidated after rebase:\n\nconsole\nuv run --frozen pytest tests/server/test_stdio.py -q\n# 5 passed\nuv run --frozen ruff check src/mcp/server/stdio.py tests/server/test_stdio.py\n# All checks passed\nuv run --frozen pyright src/mcp/server/stdio.py tests/server/test_stdio.py\n# 0 errors\ngit diff --check origin/main...HEAD\n

pranjalbhatia710 avatar Jun 07 '26 15:06 pranjalbhatia710