modelcontextprotocol / modelcontextprotocol/python-sdk

StreamableHTTP: a client disconnect while reading the POST body is logged as an exception and answered 500

未关闭 适合新手
#3,469 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

v1 v2
主要语言
Python
星标
24.3k
派生
4k
平均合并
1 天 1 小时
30 天内合并 PR
31

描述

Initial Checks
Release line

2.x (current stable), and the same on 1.28.1

Description

StreamableHTTPServerTransport._handle_post_request reads the request body inside its blanket except Exception. When the client goes away before the body arrives, await request.body() raises starlette.requests.ClientDisconnect, the transport logs it with logger.exception("Error handling POST request") and answers 500. That is a normal network event on a public MCP endpoint (mobile clients, proxies with short timeouts, health probes), and it lands as an unhandled server error with a stack trace in every log aggregator. #2064 / #2257 handled the disconnect in _handle_message; this is the earlier point, in streamable_http.py (the body = await request.body() line and the except Exception as err below it). The SSE transport has no handling for it either.

Example Code
import asyncio
import importlib.metadata as md
import logging

from mcp.server.streamable_http import StreamableHTTPServerTransport

records = []


class Capture(logging.Handler):
    def emit(self, record):
        records.append(record)


logging.getLogger("mcp").addHandler(Capture())
logging.getLogger("mcp").setLevel(logging.DEBUG)


async def main():
    transport = StreamableHTTPServerTransport(mcp_session_id=None)
    scope = {
        "type": "http", "method": "POST", "path": "/mcp", "query_string": b"", "headers": [
            (b"content-type", b"application/json"),
            (b"accept", b"application/json, text/event-stream"),
            (b"content-length", b"58"),
        ],
    }

    async def receive():  # the client went away before sending its body
        return {"type": "http.disconnect"}

    sent = []

    async def send(message):
        sent.append(message)

    async with transport.connect():
        try:
            await asyncio.wait_for(transport.handle_request(scope, receive, send), timeout=5)
        except asyncio.TimeoutError:
            print("handle_request did not return within 5s")
    status = next((m["status"] for m in sent if m["type"] == "http.response.start"), None)
    print(f"mcp {md.version('mcp')}: response status = {status}")
    for r in records:
        if r.levelno >= logging.ERROR:
            print(f"  logged {r.levelname} by {r.name}: {r.getMessage()} | exc: {type(r.exc_info[1]).__name__ if r.exc_info else None}")


try:
    asyncio.run(asyncio.wait_for(main(), timeout=15))
except asyncio.TimeoutError:
    print("main did not finish within 15s")

Output on 1.28.1 and 2.1.1:

mcp 2.1.1: response status = 500
  logged ERROR by mcp.server.streamable_http: Error handling POST request | exc: ClientDisconnect

(The script caps handle_request at 5 s because the stub send / receive is not a real ASGI server; the 500 and the log line are sent before that.)

Expected: ClientDisconnect caught before the generic handler, logged at debug or info, and no response attempted, since there is nobody to answer.

Python & MCP Python SDK

Python 3.12.13, mcp 1.28.1 and 2.1.1, starlette 1.3.1, macOS

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 mcp/server/streamable_http.py 中的 StreamableHTTPServerTransport._handle_post_request 开始,重点查看 body = await request.body() 这一行以及后面的通用异常处理器。对比 _handle_message 中现有的断开连接处理,该处理在 #2064 和 #2257 中有引用。完成标准是:ClientDisconnect 得到处理时不会产生错误堆栈跟踪或 500 响应,并且回归覆盖验证了该行为。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
api, backend
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
活跃
描述清晰度
描述清楚
新手友好度
78/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。