v1.30.0: normal streamable-HTTP session close logs "Error in standalone SSE writer" (anyio.ClosedResourceError) at ERROR

未關閉 適合新手
#3,833 2 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

評估

難度
2/5
預估耗時
1-3 小時
新手友好度
72/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
python
領域
api, backend

研究方向

從 mcp/server/streamable_http.py 開始,重點查看 standalone_sse_writer() 和 StreamableHTTPServerTransport.terminate(),接著追蹤 DELETE 清理如何關閉串流。使用提供的用戶端和伺服器範例重現問題,並檢查工作階段關閉時的伺服器記錄。完成條件是用戶端正常終止時不再產生 ERROR traceback,且有一個涵蓋串流已關閉情況的回歸測試。

由索引模型根據 Issue 內容生成。

描述

bug v1
Initial Checks
Release line

1.x (maintenance line, v1.x branch)

Description

With 1.30.0 on the server side, closing a stateful streamable-HTTP session the normal way logs an ERROR with a full traceback:

ERROR mcp.server.streamable_http: Error in standalone SSE writer
Traceback (most recent call last):
  File ".../mcp/server/streamable_http.py", line 723, in standalone_sse_writer
    async for event_message in standalone_stream_reader:
  File ".../anyio/abc/_streams.py", line 37, in __anext__
    return await self.receive()
  File ".../anyio/streams/memory.py", line 141, in receive
    raise ClosedResourceError from None
anyio.ClosedResourceError

Here, closing the normal way means the client's streamablehttp_client context exits and sends DELETE. Nothing actually fails: the calls succeed and the server keeps serving. But every session that ends puts an ERROR traceback in the server log, and that buries real errors.

Which side and which version: it depends only on the server's SDK version. I crossed the two versions:

server SDK client SDK ERROR records on close
1.29.1 1.29.1 0
1.30.0 1.30.0 1
1.30.0 1.29.1 1
1.29.1 1.30.0 0

What seems to happen (from reading the 1.30.0 source):

  • The DELETE runs StreamableHTTPServerTransport.terminate().
  • terminate() calls _clean_up_memory_streams(GET_STREAM_KEY).
  • That closes the receive stream standalone_sse_writer is still iterating, so the iteration raises ClosedResourceError instead of ending.
  • The writer's except Exception: logger.exception("Error in standalone SSE writer") reports it.

1.30.0 moved the GET handler's stream cleanup into a finally, which looks like what changed the shutdown order.

Expected: a client-initiated session termination is not logged at ERROR. Either the writer stops cleanly when its stream is closed by terminate(), or ClosedResourceError during termination is treated as a normal end, logged at DEBUG at most.

We work around it in our server with a logging.Filter on mcp.server.streamable_http that demotes exactly this record (that message plus ClosedResourceError) to DEBUG.

Example Code
"""Prints 1 ERROR record on mcp 1.30.0, 0 on 1.29.1."""
import asyncio, logging, socket, threading, time

import uvicorn
from mcp.client.session import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from mcp.server.fastmcp import FastMCP

errors = []

class Collect(logging.Handler):
    def emit(self, record):
        if record.levelno >= logging.ERROR:
            errors.append(record)

logging.getLogger("mcp.server.streamable_http").addHandler(Collect())

server = FastMCP("repro")

@server.tool()
def echo(text: str) -> str:
    return text

with socket.socket() as s:
    s.bind(("127.0.0.1", 0))
    port = s.getsockname()[1]

uv = uvicorn.Server(uvicorn.Config(server.streamable_http_app(),
                                   host="127.0.0.1", port=port, log_level="warning"))
threading.Thread(target=uv.run, daemon=True).start()
while not uv.started:
    time.sleep(0.05)

async def main():
    async with streamablehttp_client(f"http://127.0.0.1:{port}/mcp") as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            await session.list_tools()
    await asyncio.sleep(1)  # let the server process the DELETE

asyncio.run(main())
uv.should_exit = True
print(len(errors), "ERROR record(s):",
      [(r.getMessage(), type(r.exc_info[1]).__name__) for r in errors])
# 1.30.0: 1 ERROR record(s): [('Error in standalone SSE writer', 'ClosedResourceError')]
# 1.29.1: 0 ERROR record(s): []
Python & MCP Python SDK
Python 3.12.8, Linux
mcp 1.30.0 (server side; 1.29.1 does not show it)
anyio 4.16.0, starlette 1.10.0, sse-starlette 3.7.0, uvicorn 0.54.0
主要語言
Python
星號
25k
分支
4.2k
平均合併
10 分鐘
30 天內合併 PR
1

環境準備

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

modelcontextprotocol/python-sdk 的其他 Issue

查看 modelcontextprotocol/python-sdk 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。