modelcontextprotocol / modelcontextprotocol/python-sdk

FastMCP: streamable_http_app() silently breaks when BaseHTTPMiddleware is added

オープン
#2,702 コメント 5 件 リアクション 0 件 担当者 0 名 GitHub で見る

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

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

説明

Description

Adding a Starlette BaseHTTPMiddleware (e.g., for auth) to FastMCP.streamable_http_app() silently breaks the MCP server. Every request crashes with ClosedResourceError — the client sees "peer closed connection without sending complete message body."

Reproduction

from mcp.server.fastmcp import FastMCP
from starlette.middleware.base import BaseHTTPMiddleware

mcp = FastMCP("test")

# Any BaseHTTPMiddleware — even a no-op passthrough
class AuthMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        return await call_next(request)

mcp.streamable_http_app().add_middleware(BaseHTTPMiddleware, dispatch=AuthMiddleware)

Run the server, send any MCP initialize request → ClosedResourceError.

Root cause

BaseHTTPMiddleware wraps the ASGI receive/send channels in a way incompatible with SSE streaming. This is a known Starlette limitation (encode/starlette#919), but FastMCP users hit it naturally when they reach for the obvious auth pattern.

Expected behavior

At minimum: warn at startup when a BaseHTTPMiddleware subclass is detected on a streamable HTTP app. Ideally: document prominently that users should use FastMCP's own Middleware class (fastmcp.server.middleware.Middleware) instead of Starlette's BaseHTTPMiddleware.

Workaround (raw ASGI middleware)

from starlette.types import ASGIApp, Receive, Scope, Send

class RawAuthMiddleware:
    def __init__(self, app: ASGIApp):
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send):
        # auth check here — read headers from scope
        await self.app(scope, receive, send)

mcp.streamable_http_app().add_middleware(RawAuthMiddleware)

Environment

  • mcp / FastMCP from modelcontextprotocol/python-sdk
  • Starlette (any version — this is architectural, not a regression)
  • Python 3.12

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

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

はじめの一歩

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

調査の方向性

FastMCP.streamable_http_app() エントリーポイントから始め、streamable HTTP アプリの周囲にミドルウェアがどのように登録されているかを調査します。no-op の BaseHTTPMiddleware の例で失敗を再現し、そのうえで起動時の検出と警告の動作がどうあるべきかを判断します。失敗が明確に表面化され、ユーザーが FastMCP の Middleware または raw ASGI の回避策へ案内されれば完了です。

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

評価

技術スタック
python
領域
backend-api-design
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
活発
明瞭さ
おおむね明確
初心者へのやさしさ
64/100

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

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