Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix: cancel orphaned session_task when Client._disconnect times out (#4011)

Jeremiah Lowin485747353e90
diff --git a/src/fastmcp/client/client.py b/src/fastmcp/client/client.py
index c2004be7b..80c9bfbeb 100644
--- a/src/fastmcp/client/client.py
+++ b/src/fastmcp/client/client.py
@@ -528,11 +528,7 @@ class Client(
return await self._connect()
async def __aexit__(self, exc_type, exc_val, exc_tb):
- # Use a timeout to prevent hanging during cleanup if the connection is in a bad
- # state (e.g., rate-limited). The MCP SDK's transport may try to terminate the
- # session which can hang if the server is unresponsive.
- with anyio.move_on_after(self._disconnect_timeout):
- await self._disconnect()
+ await self._disconnect()
async def _connect(self):
"""
@@ -659,16 +655,25 @@ class Client(
return
session_task = self._session_state.session_task
self._session_state.stop_event.set()
- # wait for session to finish to ensure state has been reset
+ # Wait (bounded) for the runner to unwind gracefully. If it
+ # overruns β€” e.g. the transport's termination POST is blocked on
+ # a stale HTTP keep-alive connection β€” cancel the background
+ # task so transport resources (httpx connections, subprocess
+ # pipes) are actually released instead of leaking into the
+ # event loop. Force paths additionally shield the wait so an
+ # outer cancellation can't abandon cleanup half-done.
try:
- if force:
+ with anyio.CancelScope(shield=force):
+ with anyio.move_on_after(self._disconnect_timeout):
+ with suppress(asyncio.CancelledError):
+ await session_task
+ finally:
+ if not session_task.done():
+ session_task.cancel()
with anyio.CancelScope(shield=True):
with anyio.move_on_after(self._disconnect_timeout):
- with suppress(asyncio.CancelledError):
+ with suppress(Exception):
await session_task
- else:
- await session_task
- finally:
self._session_state.session_task = None
async def _session_runner(self):
diff --git a/tests/client/client/test_client.py b/tests/client/client/test_client.py
index 7257490f8..bfe95a97f 100644
--- a/tests/client/client/test_client.py
+++ b/tests/client/client/test_client.py
@@ -618,6 +618,49 @@ async def test_force_close_cancelled_wait_starts_fresh_session(fastmcp_server):
assert original_session_task.done()
+async def test_disconnect_with_hanging_transport_does_not_leak_session_task(
+ fastmcp_server, monkeypatch
+):
+ """A hung transport teardown must not leak the background session task.
+
+ Simulates the failure mode reported in
+ https://github.com/PrefectHQ/fastmcp/issues/3947: the remote HTTP server
+ has dropped the keep-alive connection, so the termination POST inside
+ the transport never returns. ``__aexit__`` must bound the wait and
+ cancel the runner so a subsequent Client can reuse the same transport
+ resources.
+ """
+ monkeypatch.setattr(fastmcp.settings, "client_disconnect_timeout", 0.2)
+
+ disconnect_started = anyio.Event()
+ never_allow_disconnect = anyio.Event()
+
+ client = Client(
+ transport=_DelayedDisconnectTransport(
+ FastMCPTransport(fastmcp_server),
+ disconnect_started=disconnect_started,
+ allow_disconnect=never_allow_disconnect,
+ )
+ )
+
+ async with client:
+ tools = await client.list_tools()
+ assert len(tools) == 3
+ session_task = client._session_state.session_task
+ assert session_task is not None
+
+ # Transport hung during teardown; the client should have bounded the
+ # wait, cancelled the runner, and cleared its own reference.
+ assert disconnect_started.is_set()
+ assert client._session_state.session_task is None
+ assert session_task.done()
+
+ # And the Client is reusable for a fresh session.
+ async with client:
+ tools = await client.list_tools()
+ assert len(tools) == 3
+
+
async def test_concurrent_client_context_managers():
"""
Test that concurrent client usage doesn't cause cross-task cancel scope issues.