From 8e13b7d69d23c883c852739a2fac781feacc94c6 Mon Sep 17 00:00:00 2001 From: EnesKartal Date: Wed, 25 Nov 2026 22:02:22 +0300 Subject: [PATCH] fix(client): shield streamable_http_client session termination during cancellation --- src/mcp/client/streamable_http.py | 8 +++--- tests/shared/test_streamable_http.py | 38 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/mcp/client/streamable_http.py b/src/mcp/client/streamable_http.py index 053f1f10a9..a868797b4f 100644 --- a/src/mcp/client/streamable_http.py +++ b/src/mcp/client/streamable_http.py @@ -787,7 +787,9 @@ def start_get_stream() -> None: try: yield read_stream, write_stream finally: - if transport.session_id and terminate_on_close: - await transport.terminate_session(client) - tg.cancel_scope.cancel() + with anyio.CancelScope(shield=True): + if transport.session_id and terminate_on_close: + with anyio.move_on_after(5): + await transport.terminate_session(client) + tg.cancel_scope.cancel() await resync_tracer() diff --git a/tests/shared/test_streamable_http.py b/tests/shared/test_streamable_http.py index 655d9941dc..29f0adaa9f 100644 --- a/tests/shared/test_streamable_http.py +++ b/tests/shared/test_streamable_http.py @@ -1207,6 +1207,44 @@ async def __aexit__(self, *args: Any) -> None: assert exc_info.value.error.message == "Session not found" +@pytest.mark.anyio +async def test_streamable_http_client_sends_delete_on_cancellation(basic_app: Starlette) -> None: + """Cancelling the caller scope must not abort the DELETE session-termination request.""" + methods_seen: list[str] = [] + + class RecordingTransport(httpx2.AsyncBaseTransport): + def __init__(self, inner: StreamingASGITransport) -> None: + self.inner = inner + + async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response: + methods_seen.append(request.method) + return await self.inner.handle_async_request(request) + + async def __aenter__(self) -> RecordingTransport: + await self.inner.__aenter__() + return self + + async def __aexit__(self, *args: Any) -> None: + await self.inner.__aexit__(*args) + + httpx_client, _ = create_session_id_capturing_client( + basic_app, transport=RecordingTransport(StreamingASGITransport(basic_app)) + ) + + async with httpx_client: + with anyio.CancelScope() as scope: + async with streamable_http_client(f"{BASE_URL}/mcp", http_client=httpx_client) as ( + read_stream, + write_stream, + ): + async with ClientSession(read_stream, write_stream) as session: + await session.initialize() + scope.cancel() + await anyio.sleep_forever() + + assert "DELETE" in methods_seen + + @pytest.mark.anyio async def test_streamable_http_client_resumption(event_app: tuple[SimpleEventStore, Starlette]) -> None: """A second client resumes an interrupted request with a resumption token and receives the rest."""