fix: use os.dup to avoid closing real stdin/stdout in stdio_server#2737
Open
xlyoung wants to merge 1 commit into
Open
fix: use os.dup to avoid closing real stdin/stdout in stdio_server#2737xlyoung wants to merge 1 commit into
xlyoung wants to merge 1 commit into
Conversation
Fixes modelcontextprotocol#1933 When stdio_server() wraps sys.stdin.buffer/sys.stdout.buffer directly, closing the context manager also closes the real file descriptors, causing ValueError on subsequent I/O operations. Fix: Use os.dup() to duplicate file descriptors before wrapping them. This ensures closing the wrappers doesn't affect the real stdin/stdout. Added fallback for environments where fileno() is not available (e.g., BytesIO-backed streams in tests).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1933
Problem
When
stdio_server()wrapssys.stdin.buffer/sys.stdout.bufferdirectly, closing the context manager also closes the real file descriptors, causingValueError: I/O operation on closed fileon subsequent I/O operations.Fix
Use
os.dup()to duplicate file descriptors before wrapping them. This ensures closing the wrappers does not affect the real stdin/stdout.Added fallback for environments where
fileno()is not available (e.g., BytesIO-backed streams in tests).Testing
test_stdio_server_uses_os_dupto verify the fix-raceflag