fix(stdio): serve bufferless std streams as text instead of crashing

Closed
ST
2mo ago
+45-4

What this is now

This PR originally fixed #1933 (stdio_server closing the real process std handles). #3117 has since landed and fixes that properly, with a much better design than what I had here. So I have dropped my original commits entirely and rebased onto current main.

What is left is one narrower bug that #3117 does not cover.

The bug

_claim_fd starts with:

if not _is_backed_by_fd(stream, fd):
    return stream.buffer, None

and _is_backed_by_fd returns False in three cases, one of which is the stream having no .buffer at all:

except (AttributeError, OSError, ValueError):
    return False

So on that path the fallback dereferences the attribute it just proved may be missing. If sys.stdin / sys.stdout have been replaced with io.StringIO, stdio_server() raises before serving a single message:

AttributeError: '_io.StringIO' object has no attribute 'buffer'

Reproduced against a4f4ccd0:

sys.stdin, sys.stdout = io.StringIO(""), io.StringIO()
async with stdio_server() as (r, w):   # AttributeError
    ...

It is not a hypothetical stream shape. Test harnesses do it, and so do embedded hosts that swap the std streams to capture output.

The fix

Return None for the buffer in that one case and serve the text stream in place. A bufferless stream is already text, so there is no binary layer to re-encode and none for _UnownedTextWrapper to protect from close. Every other path still returns a binary stream and is untouched.

Verification

Local, on a4f4ccd0 with the commit applied:

  • repro above raises AttributeError before, exits cleanly after
  • new regression test test_stdio_server_serves_bufferless_std_streams_in_place round-trips a request and a response through io.StringIO streams
  • tests/server/test_stdio.py 18 passed
  • full suite 5582 passed, 9 skipped, 1 xfailed
  • ruff check and ruff format --check clean, pyright 0 errors
  • branch coverage on src/mcp/server/stdio.py back to 100.00%, which the fail_under = 100 gate needs

Disclosure

Written with AI assistance, reviewed and verified by me. Happy to reshape or split this if you would rather have it another way.