modelcontextprotocol / modelcontextprotocol/python-sdk
FastMCP: streamable_http_app() silently breaks when BaseHTTPMiddleware is added
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 24.3k
- Forks
- 4k
- Merge medio
- 1 d 1 h
- PR fusionados (30 d)
- 31
Descripción
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
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza en el punto de entrada FastMCP.streamable_http_app() e inspecciona cómo se registra el middleware alrededor de la aplicación HTTP transmitible. Reproduce el fallo con el ejemplo no-op de BaseHTTPMiddleware y determina después cómo deberían funcionar la detección durante el inicio y el comportamiento de las advertencias. Se considera terminado cuando el fallo se muestra claramente y se dirige a los usuarios hacia Middleware de FastMCP o la solución alternativa de ASGI sin procesar.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- backend-api-design
- Tipo de issue
- Error
- Dificultad
- 3/5
- Tiempo estimado
- 1-2 días
- Estado de actividad
- Activo
- Claridad
- Bastante claro
- Aptitud para principiantes
- 64/100