modelcontextprotocol / modelcontextprotocol/python-sdk

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

オープン 初心者向け
#1,933 コメント 8 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

bug good first issue P3
主要言語
Python
スター
24.3k
フォーク
4k
平均マージ
1日 1時間
マージ済み PR(30日)
31

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

src/mcp/server/stdio.py のリンクされた行付近にある wrapper のセットアップから始め、次に issue の最小 FastMCP 再現を実行します。stdio wrapper を閉じてもプロセスの実際の標準ストリームが閉じられなくなったことを確認し、サーバー終了後に最後の print が成功することを検証します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
2/5
見積もり時間
1〜3時間
活発さ
静か
明瞭さ
明確に書かれている
初心者へのやさしさ
68/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。