|
10 | 10 | import pytest |
11 | 11 | from starlette.types import Message |
12 | 12 |
|
13 | | -from mcp import Client |
| 13 | +from mcp import Client, types |
14 | 14 | from mcp.client.streamable_http import streamable_http_client |
15 | 15 | from mcp.server import Server, ServerRequestContext, streamable_http_manager |
16 | 16 | 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 |
18 | 18 | from mcp.types import INVALID_REQUEST, ListToolsResult, PaginatedRequestParams |
19 | 19 |
|
20 | 20 |
|
@@ -413,3 +413,210 @@ def test_session_idle_timeout_rejects_non_positive(): |
413 | 413 | def test_session_idle_timeout_rejects_stateless(): |
414 | 414 | with pytest.raises(RuntimeError, match="not supported in stateless"): |
415 | 415 | StreamableHTTPSessionManager(app=Server("test"), session_idle_timeout=30, stateless=True) |
| 416 | + |
| 417 | + |
| 418 | +MCP_HEADERS = { |
| 419 | + "Accept": "application/json, text/event-stream", |
| 420 | + "Content-Type": "application/json", |
| 421 | +} |
| 422 | + |
| 423 | +_INITIALIZE_REQUEST = { |
| 424 | + "jsonrpc": "2.0", |
| 425 | + "id": 1, |
| 426 | + "method": "initialize", |
| 427 | + "params": { |
| 428 | + "protocolVersion": "2025-03-26", |
| 429 | + "capabilities": {}, |
| 430 | + "clientInfo": {"name": "test", "version": "0.1"}, |
| 431 | + }, |
| 432 | +} |
| 433 | + |
| 434 | +_INITIALIZED_NOTIFICATION = { |
| 435 | + "jsonrpc": "2.0", |
| 436 | + "method": "notifications/initialized", |
| 437 | +} |
| 438 | + |
| 439 | +_TOOL_CALL_REQUEST = { |
| 440 | + "jsonrpc": "2.0", |
| 441 | + "id": 2, |
| 442 | + "method": "tools/call", |
| 443 | + "params": {"name": "slow_tool", "arguments": {"message": "hello"}}, |
| 444 | +} |
| 445 | + |
| 446 | + |
| 447 | +def _make_slow_tool_server() -> tuple[Server, anyio.Event]: |
| 448 | + """Create an MCP server with a tool that blocks forever, returning |
| 449 | + the server and an event that fires when the tool starts executing.""" |
| 450 | + tool_started = anyio.Event() |
| 451 | + |
| 452 | + async def handle_call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> types.CallToolResult: |
| 453 | + tool_started.set() |
| 454 | + await anyio.sleep_forever() |
| 455 | + return types.CallToolResult( # pragma: no cover |
| 456 | + content=[types.TextContent(type="text", text="never reached")] |
| 457 | + ) |
| 458 | + |
| 459 | + async def handle_list_tools( |
| 460 | + ctx: ServerRequestContext, params: PaginatedRequestParams | None |
| 461 | + ) -> ListToolsResult: # pragma: no cover |
| 462 | + return ListToolsResult( |
| 463 | + tools=[ |
| 464 | + types.Tool( |
| 465 | + name="slow_tool", |
| 466 | + description="A tool that blocks forever", |
| 467 | + input_schema={"type": "object", "properties": {"message": {"type": "string"}}}, |
| 468 | + ) |
| 469 | + ] |
| 470 | + ) |
| 471 | + |
| 472 | + app = Server("test-graceful-shutdown", on_call_tool=handle_call_tool, on_list_tools=handle_list_tools) |
| 473 | + return app, tool_started |
| 474 | + |
| 475 | + |
| 476 | +@pytest.mark.anyio |
| 477 | +async def test_graceful_shutdown_terminates_active_stateless_transports(): |
| 478 | + """Verify that shutting down the session manager terminates in-flight |
| 479 | + stateless transports so SSE streams close cleanly (``more_body=False``) |
| 480 | + instead of being abruptly cancelled. |
| 481 | +
|
| 482 | + Without the graceful-drain fix, the ``run()`` finally block only cancels |
| 483 | + the task group — it never calls ``terminate()`` on active transports. |
| 484 | + This test asserts ``transport._terminated`` is True after shutdown, which |
| 485 | + fails without the fix. |
| 486 | + """ |
| 487 | + app, tool_started = _make_slow_tool_server() |
| 488 | + manager = StreamableHTTPSessionManager(app=app, stateless=True) |
| 489 | + |
| 490 | + mcp_app = StreamableHTTPASGIApp(manager) |
| 491 | + |
| 492 | + manager_ready = anyio.Event() |
| 493 | + captured_transport: StreamableHTTPServerTransport | None = None |
| 494 | + |
| 495 | + with anyio.fail_after(10): |
| 496 | + async with anyio.create_task_group() as tg: |
| 497 | + |
| 498 | + async def run_lifespan_and_shutdown(): |
| 499 | + nonlocal captured_transport |
| 500 | + async with manager.run(): |
| 501 | + manager_ready.set() |
| 502 | + with anyio.fail_after(5): |
| 503 | + await tool_started.wait() |
| 504 | + # Grab reference to the in-flight stateless transport |
| 505 | + assert len(manager._stateless_transports) == 1 |
| 506 | + captured_transport = next(iter(manager._stateless_transports)) |
| 507 | + assert not captured_transport._terminated |
| 508 | + # manager.run() exits — graceful shutdown runs here |
| 509 | + |
| 510 | + async def make_requests(): |
| 511 | + with anyio.fail_after(5): |
| 512 | + await manager_ready.wait() |
| 513 | + async with ( |
| 514 | + httpx.ASGITransport(mcp_app) as transport, |
| 515 | + httpx.AsyncClient(transport=transport, base_url="http://testserver") as client, |
| 516 | + ): |
| 517 | + # Initialize |
| 518 | + resp = await client.post("/mcp/", json=_INITIALIZE_REQUEST, headers=MCP_HEADERS) |
| 519 | + resp.raise_for_status() |
| 520 | + |
| 521 | + # Send initialized notification |
| 522 | + resp = await client.post("/mcp/", json=_INITIALIZED_NOTIFICATION, headers=MCP_HEADERS) |
| 523 | + assert resp.status_code == 202 |
| 524 | + |
| 525 | + # Send slow tool call — blocks until shutdown terminates it |
| 526 | + async with client.stream( |
| 527 | + "POST", |
| 528 | + "/mcp/", |
| 529 | + json=_TOOL_CALL_REQUEST, |
| 530 | + headers=MCP_HEADERS, |
| 531 | + timeout=httpx.Timeout(10, connect=5), |
| 532 | + ) as stream: |
| 533 | + stream.raise_for_status() |
| 534 | + async for _chunk in stream.aiter_bytes(): |
| 535 | + pass # pragma: no cover |
| 536 | + |
| 537 | + tg.start_soon(run_lifespan_and_shutdown) |
| 538 | + tg.start_soon(make_requests) |
| 539 | + |
| 540 | + assert captured_transport is not None |
| 541 | + assert captured_transport._terminated, ( |
| 542 | + "Transport should have been terminated by graceful shutdown " |
| 543 | + "(without the fix, run() only cancels the task group and never calls terminate())" |
| 544 | + ) |
| 545 | + |
| 546 | + |
| 547 | +@pytest.mark.anyio |
| 548 | +async def test_graceful_shutdown_terminates_active_stateful_transports(): |
| 549 | + """Verify that shutting down the session manager terminates in-flight |
| 550 | + stateful transports so SSE streams close cleanly. |
| 551 | +
|
| 552 | + Without the graceful-drain fix, the ``run()`` finally block only cancels |
| 553 | + the task group — it never calls ``terminate()`` on active transports. |
| 554 | + This test asserts ``transport._terminated`` is True after shutdown, which |
| 555 | + fails without the fix. |
| 556 | + """ |
| 557 | + app, tool_started = _make_slow_tool_server() |
| 558 | + manager = StreamableHTTPSessionManager(app=app, stateless=False) |
| 559 | + |
| 560 | + mcp_app = StreamableHTTPASGIApp(manager) |
| 561 | + |
| 562 | + manager_ready = anyio.Event() |
| 563 | + captured_transport: StreamableHTTPServerTransport | None = None |
| 564 | + |
| 565 | + with anyio.fail_after(10): |
| 566 | + async with anyio.create_task_group() as tg: |
| 567 | + |
| 568 | + async def run_lifespan_and_shutdown(): |
| 569 | + nonlocal captured_transport |
| 570 | + async with manager.run(): |
| 571 | + manager_ready.set() |
| 572 | + with anyio.fail_after(5): |
| 573 | + await tool_started.wait() |
| 574 | + # Grab reference to the in-flight stateful transport |
| 575 | + assert len(manager._server_instances) == 1 |
| 576 | + captured_transport = next(iter(manager._server_instances.values())) |
| 577 | + assert not captured_transport._terminated |
| 578 | + # manager.run() exits — graceful shutdown runs here |
| 579 | + |
| 580 | + async def make_requests(): |
| 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 (creates a session) |
| 588 | + resp = await client.post("/mcp/", json=_INITIALIZE_REQUEST, headers=MCP_HEADERS) |
| 589 | + resp.raise_for_status() |
| 590 | + session_id = resp.headers.get(MCP_SESSION_ID_HEADER) |
| 591 | + assert session_id is not None |
| 592 | + |
| 593 | + session_headers = { |
| 594 | + **MCP_HEADERS, |
| 595 | + MCP_SESSION_ID_HEADER: session_id, |
| 596 | + "mcp-protocol-version": "2025-03-26", |
| 597 | + } |
| 598 | + |
| 599 | + # Send initialized notification |
| 600 | + resp = await client.post("/mcp/", json=_INITIALIZED_NOTIFICATION, headers=session_headers) |
| 601 | + assert resp.status_code == 202 |
| 602 | + |
| 603 | + # Send slow tool call — blocks until shutdown terminates it |
| 604 | + async with client.stream( |
| 605 | + "POST", |
| 606 | + "/mcp/", |
| 607 | + json=_TOOL_CALL_REQUEST, |
| 608 | + headers=session_headers, |
| 609 | + timeout=httpx.Timeout(10, connect=5), |
| 610 | + ) as stream: |
| 611 | + stream.raise_for_status() |
| 612 | + async for _chunk in stream.aiter_bytes(): |
| 613 | + pass # pragma: no cover |
| 614 | + |
| 615 | + tg.start_soon(run_lifespan_and_shutdown) |
| 616 | + tg.start_soon(make_requests) |
| 617 | + |
| 618 | + assert captured_transport is not None |
| 619 | + assert captured_transport._terminated, ( |
| 620 | + "Transport should have been terminated by graceful shutdown " |
| 621 | + "(without the fix, run() only cancels the task group and never calls terminate())" |
| 622 | + ) |
0 commit comments