modelcontextprotocol / modelcontextprotocol/python-sdk

Using transport="stdio" closes real stdio, causing ValueError after server exits

Đang mở Phù hợp với người mới
#1,933 8 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

bug good first issue P3
Ngôn ngữ chính
Python
Star
24.3k
Fork
4k
Merge trung bình
1 ngày 1 giờ
Pull request đã merge (30 ngày)
31

Mô tả

Initial Checks
Description

Hi! I ran into an issue where running the server with transport="stdio" causes subsequent stdio operations to fail after the server exits.

Minimal reproduction
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Demo")
mcp.run(transport="stdio")
print("?")

When using Ctrl+D to exit the server, the final print raises:

Traceback (most recent call last):
  File "...", line 5, in <module>
    print("?")
ValueError: I/O operation on closed file.

I’m not sure if this is intended behavior though.

Likely cause

In stdio.py, stdio is wrapped like this:
https://github.com/modelcontextprotocol/python-sdk/blob/5301298225968ce0fa8ae62870f950709da14dc6/src/mcp/server/stdio.py#L44-L47

When these wrappers are closed, they also close the sys.stdin.buffer / sys.stdout.buffer.

Proposed fix
    if not stdin:
        stdin_fd = os.dup(sys.stdin.fileno())
        stdin_bin = os.fdopen(stdin_fd, "rb", closefd=True)
        stdin = anyio.wrap_file(TextIOWrapper(stdin_bin, encoding="utf-8"))
    if not stdout:
        stdout_fd = os.dup(sys.stdout.fileno())
        stdout_bin = os.fdopen(stdout_fd, "wb", closefd=True)
        stdout = anyio.wrap_file(TextIOWrapper(stdout_bin, encoding="utf-8"))
Python & MCP Python SDK
Python 3.10.15
mcp==1.25.0

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu trong src/mcp/server/stdio.py, xung quanh phần thiết lập wrapper ở các dòng được liên kết, sau đó chạy bản tái hiện FastMCP tối thiểu từ issue. Xác nhận rằng việc đóng các wrapper stdio không còn đóng các luồng đầu ra tiêu chuẩn thực của tiến trình, và kiểm tra rằng print cuối cùng thực thi thành công sau khi server thoát.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
backend
Loại issue
Lỗi
Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức độ hoạt động
Ít trao đổi
Độ rõ ràng
Đặc tả rõ ràng
Mức phù hợp với người mới
68/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.