π The fast, Pythonic way to build MCP servers and clients.
Stop the SSE endpoint sending a second response after its stream (#6431)
nate nowack3fed0541f1bf
diff --git a/fastmcp_slim/fastmcp/server/http.py b/fastmcp_slim/fastmcp/server/http.pyindex 8a31201ea..7bab7ed24 100644--- a/fastmcp_slim/fastmcp/server/http.py+++ b/fastmcp_slim/fastmcp/server/http.py@@ -466,6 +466,16 @@ def _served_resource_metadata_url(return None+class _SSEEndpoint:+ """Serve an ASGI handler from a `Route` without request/response wrapping."""++ def __init__(self, app: ASGIApp):+ self.app = app++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ await self.app(scope, receive, send)++def create_sse_app(server: FastMCP[LifespanResultT],message_path: str,@@ -519,14 +529,15 @@ def create_sse_app()# Create handler for SSE connections- async def handle_sse(scope: Scope, receive: Receive, send: Send) -> Response:+ # connect_sse sends the whole response, so this is a raw ASGI app: a+ # request/response endpoint would send a second response after the stream.+ async def handle_sse(scope: Scope, receive: Receive, send: Send) -> None:async with sse.connect_sse(scope, receive, send) as streams:await server._mcp_server.run(streams[0],streams[1],server._mcp_server.create_initialization_options(),)- return Response()# Set up auth if enabledif auth:@@ -572,13 +583,10 @@ def create_sse_app(else:# auth=None removes bearer-token enforcement. A gateway's authentication# is outside FastMCP's guarantees and must prevent direct unauthenticated access.- async def sse_endpoint(request: Request) -> Response:- return await handle_sse(request.scope, request.receive, request._send)-server_routes.append(Route(sse_path,- endpoint=sse_endpoint,+ endpoint=_SSEEndpoint(handle_sse),methods=["GET"],))diff --git a/tests/server/http/test_http_middleware.py b/tests/server/http/test_http_middleware.pyindex df4182008..f9e90f4b8 100644--- a/tests/server/http/test_http_middleware.py+++ b/tests/server/http/test_http_middleware.py@@ -3,6 +3,7 @@from collections.abc import Callablefrom typing import Any+import anyioimport httpx2from httpx2 import ASGITransportfrom starlette.middleware import Middleware@@ -10,7 +11,7 @@ from starlette.middleware.base import BaseHTTPMiddlewarefrom starlette.requests import Requestfrom starlette.responses import JSONResponsefrom starlette.routing import BaseRoute, Route-from starlette.types import ASGIApp+from starlette.types import ASGIApp, Messagefrom fastmcp.server import FastMCPfrom fastmcp.server.http import create_sse_app, create_streamable_http_app@@ -227,3 +228,51 @@ async def test_multiple_middleware_ordering():assert response.status_code == 200assert response.headers["X-First-Header"] == "first"assert response.headers["X-Second-Header"] == "second"+++class PassthroughMiddleware(BaseHTTPMiddleware):+ async def dispatch(self, request: Request, call_next: Callable):+ return await call_next(request)+++async def test_sse_stream_closes_cleanly_through_base_http_middleware():+ """The SSE endpoint must not send a second response after its stream ends."""+ server = FastMCP(name="TestServer")+ app = server.http_app(+ transport="sse",+ middleware=[Middleware(PassthroughMiddleware)], # type: ignore[arg-type]+ )++ sent: list[Message] = []+ stream_opened = anyio.Event()++ async def receive() -> Message:+ await stream_opened.wait()+ return {"type": "http.disconnect"}++ async def send(message: Message) -> None:+ sent.append(message)+ if message["type"] == "http.response.body" and message.get("body"):+ stream_opened.set()++ scope = {+ "type": "http",+ "asgi": {"version": "3.0"},+ "http_version": "1.1",+ "method": "GET",+ "scheme": "http",+ "path": "/sse",+ "raw_path": b"/sse",+ "query_string": b"",+ "root_path": "",+ "headers": [(b"host", b"127.0.0.1")],+ "client": ("127.0.0.1", 12345),+ "server": ("127.0.0.1", 80),+ }++ with anyio.fail_after(5):+ await app(scope, receive, send)++ response_starts = [m for m in sent if m["type"] == "http.response.start"]+ assert len(response_starts) == 1+ assert response_starts[0]["status"] == 200