Skip to content

Commit c90fb9b

Browse files
committed
fix: graceful SSE drain on session manager shutdown
Terminate all active transports before cancelling the task group during shutdown, allowing EventSourceResponse to send a final more_body=False chunk for clean HTTP close instead of a connection reset. Upstream PR: modelcontextprotocol#2239
1 parent 6450397 commit c90fb9b

3 files changed

Lines changed: 226 additions & 11 deletions

File tree

src/mcp/server/streamable_http.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -809,7 +809,7 @@ async def _validate_request_headers(self, request: Request, send: Send) -> bool:
809809

810810
async def _validate_session(self, request: Request, send: Send) -> bool:
811811
"""Validate the session ID in the request."""
812-
if not self.mcp_session_id: # pragma: lax no cover
812+
if not self.mcp_session_id:
813813
# If we're not using session IDs, return True
814814
return True
815815

@@ -842,7 +842,7 @@ async def _validate_protocol_version(self, request: Request, send: Send) -> bool
842842
protocol_version = request.headers.get(MCP_PROTOCOL_VERSION_HEADER)
843843

844844
# If no protocol version provided, assume default version
845-
if protocol_version is None: # pragma: no cover
845+
if protocol_version is None:
846846
protocol_version = DEFAULT_NEGOTIATED_VERSION
847847

848848
# Check if the protocol version is supported

src/mcp/server/streamable_http_manager.py

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,9 @@ def __init__(
9090
self._session_creation_lock = anyio.Lock()
9191
self._server_instances: dict[str, StreamableHTTPServerTransport] = {}
9292

93+
# Track in-flight stateless transports for graceful shutdown
94+
self._stateless_transports: set[StreamableHTTPServerTransport] = set()
95+
9396
# The task group will be set during lifespan
9497
self._task_group = None
9598
# Thread-safe tracking of run() calls
@@ -130,11 +133,28 @@ async def lifespan(app: Starlette) -> AsyncIterator[None]:
130133
yield # Let the application run
131134
finally:
132135
logger.info("StreamableHTTP session manager shutting down")
136+
137+
# Terminate all active transports before cancelling the task
138+
# group. This closes their in-memory streams, which lets
139+
# EventSourceResponse send a final ``more_body=False`` chunk
140+
# — a clean HTTP close instead of a connection reset.
141+
for transport in list(self._server_instances.values()):
142+
try:
143+
await transport.terminate()
144+
except Exception: # pragma: no cover
145+
logger.debug("Error terminating transport during shutdown", exc_info=True)
146+
for transport in list(self._stateless_transports):
147+
try:
148+
await transport.terminate()
149+
except Exception: # pragma: no cover
150+
logger.debug("Error terminating stateless transport during shutdown", exc_info=True)
151+
133152
# Cancel task group to stop all spawned tasks
134153
tg.cancel_scope.cancel()
135154
self._task_group = None
136155
# Clear any remaining server instances
137156
self._server_instances.clear()
157+
self._stateless_transports.clear()
138158

139159
async def handle_request(self, scope: Scope, receive: Receive, send: Send) -> None:
140160
"""Process ASGI request with proper session handling and transport setup.
@@ -166,6 +186,9 @@ async def _handle_stateless_request(self, scope: Scope, receive: Receive, send:
166186
security_settings=self.security_settings,
167187
)
168188

189+
# Track for graceful shutdown
190+
self._stateless_transports.add(http_transport)
191+
169192
# Start server in a new task
170193
async def run_stateless_server(*, task_status: TaskStatus[None] = anyio.TASK_STATUS_IGNORED):
171194
async with http_transport.connect() as streams:
@@ -185,13 +208,16 @@ async def run_stateless_server(*, task_status: TaskStatus[None] = anyio.TASK_STA
185208
# This ensures the server task is cancelled when the request
186209
# finishes, preventing zombie tasks from accumulating.
187210
# See: https://github.com/modelcontextprotocol/python-sdk/issues/1764
188-
async with anyio.create_task_group() as request_tg:
189-
await request_tg.start(run_stateless_server)
190-
# Handle the HTTP request directly in the caller's context
191-
# (not as a child task) so execution flows back naturally.
192-
await http_transport.handle_request(scope, receive, send)
193-
# Cancel the request-scoped task group to stop the server task.
194-
request_tg.cancel_scope.cancel()
211+
try:
212+
async with anyio.create_task_group() as request_tg:
213+
await request_tg.start(run_stateless_server)
214+
# Handle the HTTP request directly in the caller's context
215+
# (not as a child task) so execution flows back naturally.
216+
await http_transport.handle_request(scope, receive, send)
217+
# Cancel the request-scoped task group to stop the server task.
218+
request_tg.cancel_scope.cancel()
219+
finally:
220+
self._stateless_transports.discard(http_transport)
195221

196222
# Terminate after the task group exits — the server task is already
197223
# cancelled at this point, so this is just cleanup (sets _terminated

tests/server/test_streamable_http_manager.py

Lines changed: 191 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010
import pytest
1111
from starlette.types import Message
1212

13-
from mcp import Client
13+
from mcp import Client, types
1414
from mcp.client.streamable_http import streamable_http_client
1515
from mcp.server import Server, ServerRequestContext, streamable_http_manager
1616
from mcp.server.streamable_http import MCP_SESSION_ID_HEADER, StreamableHTTPServerTransport
17-
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
17+
from mcp.server.streamable_http_manager import StreamableHTTPASGIApp, StreamableHTTPSessionManager
1818
from mcp.types import INVALID_REQUEST, ListToolsResult, PaginatedRequestParams
1919

2020

@@ -490,3 +490,192 @@ def test_session_idle_timeout_rejects_non_positive():
490490
def test_session_idle_timeout_rejects_stateless():
491491
with pytest.raises(RuntimeError, match="not supported in stateless"):
492492
StreamableHTTPSessionManager(app=Server("test"), session_idle_timeout=30, stateless=True)
493+
494+
495+
MCP_HEADERS = {
496+
"Accept": "application/json, text/event-stream",
497+
"Content-Type": "application/json",
498+
}
499+
500+
_INITIALIZE_REQUEST = {
501+
"jsonrpc": "2.0",
502+
"id": 1,
503+
"method": "initialize",
504+
"params": {
505+
"protocolVersion": "2025-03-26",
506+
"capabilities": {},
507+
"clientInfo": {"name": "test", "version": "0.1"},
508+
},
509+
}
510+
511+
_INITIALIZED_NOTIFICATION = {
512+
"jsonrpc": "2.0",
513+
"method": "notifications/initialized",
514+
}
515+
516+
_TOOL_CALL_REQUEST = {
517+
"jsonrpc": "2.0",
518+
"id": 2,
519+
"method": "tools/call",
520+
"params": {"name": "slow_tool", "arguments": {"message": "hello"}},
521+
}
522+
523+
524+
def _make_slow_tool_server() -> tuple[Server, anyio.Event]:
525+
"""Create an MCP server with a tool that blocks forever, returning
526+
the server and an event that fires when the tool starts executing."""
527+
tool_started = anyio.Event()
528+
529+
async def handle_call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> types.CallToolResult:
530+
tool_started.set()
531+
await anyio.sleep_forever()
532+
return types.CallToolResult( # pragma: no cover
533+
content=[types.TextContent(type="text", text="never reached")]
534+
)
535+
536+
async def handle_list_tools(
537+
ctx: ServerRequestContext, params: PaginatedRequestParams | None
538+
) -> ListToolsResult: # pragma: no cover
539+
return ListToolsResult(
540+
tools=[
541+
types.Tool(
542+
name="slow_tool",
543+
description="A tool that blocks forever",
544+
input_schema={"type": "object", "properties": {"message": {"type": "string"}}},
545+
)
546+
]
547+
)
548+
549+
app = Server("test-graceful-shutdown", on_call_tool=handle_call_tool, on_list_tools=handle_list_tools)
550+
return app, tool_started
551+
552+
553+
@pytest.mark.anyio
554+
async def test_graceful_shutdown_terminates_active_stateless_transports():
555+
"""Verify that shutting down the session manager terminates in-flight
556+
stateless transports so SSE streams close cleanly (``more_body=False``)
557+
instead of being abruptly cancelled.
558+
559+
This prevents "upstream prematurely closed connection" errors at reverse
560+
proxies like nginx.
561+
"""
562+
app, tool_started = _make_slow_tool_server()
563+
manager = StreamableHTTPSessionManager(app=app, stateless=True)
564+
565+
mcp_app = StreamableHTTPASGIApp(manager)
566+
567+
manager_ready = anyio.Event()
568+
stream_outcome: str | None = None
569+
570+
with anyio.fail_after(10):
571+
async with anyio.create_task_group() as tg:
572+
573+
async def run_lifespan_and_shutdown():
574+
async with manager.run():
575+
manager_ready.set()
576+
with anyio.fail_after(5):
577+
await tool_started.wait()
578+
579+
async def make_requests():
580+
nonlocal stream_outcome
581+
with anyio.fail_after(5):
582+
await manager_ready.wait()
583+
async with (
584+
httpx.ASGITransport(mcp_app) as transport,
585+
httpx.AsyncClient(transport=transport, base_url="http://testserver") as client,
586+
):
587+
# Initialize
588+
resp = await client.post("/mcp/", json=_INITIALIZE_REQUEST, headers=MCP_HEADERS)
589+
resp.raise_for_status()
590+
591+
# Send initialized notification
592+
resp = await client.post("/mcp/", json=_INITIALIZED_NOTIFICATION, headers=MCP_HEADERS)
593+
assert resp.status_code == 202
594+
595+
# Send slow tool call — this returns an SSE stream
596+
try:
597+
async with client.stream(
598+
"POST",
599+
"/mcp/",
600+
json=_TOOL_CALL_REQUEST,
601+
headers=MCP_HEADERS,
602+
timeout=httpx.Timeout(10, connect=5),
603+
) as stream:
604+
stream.raise_for_status()
605+
async for _chunk in stream.aiter_bytes():
606+
pass # pragma: no cover
607+
stream_outcome = "clean"
608+
except httpx.RemoteProtocolError: # pragma: no cover
609+
stream_outcome = "reset"
610+
611+
tg.start_soon(run_lifespan_and_shutdown)
612+
tg.start_soon(make_requests)
613+
614+
assert stream_outcome == "clean", f"Expected clean HTTP close, got {stream_outcome}"
615+
616+
617+
@pytest.mark.anyio
618+
async def test_graceful_shutdown_terminates_active_stateful_transports():
619+
"""Verify that shutting down the session manager terminates in-flight
620+
stateful transports so SSE streams close cleanly."""
621+
app, tool_started = _make_slow_tool_server()
622+
manager = StreamableHTTPSessionManager(app=app, stateless=False)
623+
624+
mcp_app = StreamableHTTPASGIApp(manager)
625+
626+
manager_ready = anyio.Event()
627+
stream_outcome: str | None = None
628+
629+
with anyio.fail_after(10):
630+
async with anyio.create_task_group() as tg:
631+
632+
async def run_lifespan_and_shutdown():
633+
async with manager.run():
634+
manager_ready.set()
635+
with anyio.fail_after(5):
636+
await tool_started.wait()
637+
638+
async def make_requests():
639+
nonlocal stream_outcome
640+
with anyio.fail_after(5):
641+
await manager_ready.wait()
642+
async with (
643+
httpx.ASGITransport(mcp_app) as transport,
644+
httpx.AsyncClient(transport=transport, base_url="http://testserver") as client,
645+
):
646+
# Initialize (creates a session)
647+
resp = await client.post("/mcp/", json=_INITIALIZE_REQUEST, headers=MCP_HEADERS)
648+
resp.raise_for_status()
649+
session_id = resp.headers.get(MCP_SESSION_ID_HEADER)
650+
assert session_id is not None
651+
652+
session_headers = {
653+
**MCP_HEADERS,
654+
MCP_SESSION_ID_HEADER: session_id,
655+
"mcp-protocol-version": "2025-03-26",
656+
}
657+
658+
# Send initialized notification
659+
resp = await client.post("/mcp/", json=_INITIALIZED_NOTIFICATION, headers=session_headers)
660+
assert resp.status_code == 202
661+
662+
# Send slow tool call
663+
try:
664+
async with client.stream(
665+
"POST",
666+
"/mcp/",
667+
json=_TOOL_CALL_REQUEST,
668+
headers=session_headers,
669+
timeout=httpx.Timeout(10, connect=5),
670+
) as stream:
671+
stream.raise_for_status()
672+
async for _chunk in stream.aiter_bytes():
673+
pass # pragma: no cover
674+
stream_outcome = "clean"
675+
except httpx.RemoteProtocolError: # pragma: no cover
676+
stream_outcome = "reset"
677+
678+
tg.start_soon(run_lifespan_and_shutdown)
679+
tg.start_soon(make_requests)
680+
681+
assert stream_outcome == "clean", f"Expected clean HTTP close, got {stream_outcome}"

0 commit comments

Comments
 (0)