π The fast, Pythonic way to build MCP servers and clients.
Release a Client's session hold before any await when a context exits (#5223)
nate nowackc6165d919388
diff --git a/fastmcp_slim/fastmcp/client/client.py b/fastmcp_slim/fastmcp/client/client.pyindex 148bf7609..c0d023d09 100644--- a/fastmcp_slim/fastmcp/client/client.py+++ b/fastmcp_slim/fastmcp/client/client.py@@ -580,6 +580,8 @@ class Client(# Normally disconnects complete in <100ms; this is a safety net for# unresponsive servers.self._disconnect_timeout: float = fastmcp.settings.client_disconnect_timeout+ # Session stops handed off by exiting contexts; referenced until done.+ self._stoppers: set[asyncio.Task[None]] = set()# Session context management - see class docstring for detailed explanationself._session_state = ClientSessionState()@@ -1063,39 +1065,67 @@ class Client(that was resetting events outside the lock, causing race conditions.Event recreation now happens only in _connect() when actually needed."""+ if force:+ # An explicit close stops the session it finds, in order with the+ # contexts around it, so it runs here under the lock as before.+ await self._stop_session(None, force=True)+ return++ # Release this context's hold before any await. A context that exits+ # because it was cancelled can be interrupted at every await below, by+ # an enclosing anyio scope or by a native cancellation that repeats+ # while it unwinds (as when a caller runs each tool call in its own+ # task). A hold that is never released keeps the client connected for+ # good, so a nested exit finishes here without awaiting at all.+ self._session_state.nesting_counter = max(+ 0, self._session_state.nesting_counter - 1+ )+ if self._session_state.nesting_counter > 0:+ return++ held = self._session_state.session_task+ if held is None:+ return+ # Stop the session in its own task. The exiting context never waits on+ # the session lock itself, since another task can hold it through a+ # reconnect that is slow or never finishes: a cancelled exit returns at+ # once through the shield, and the stop still runs to completion.+ stopper = asyncio.create_task(self._stop_session(held, force=False))+ self._stoppers.add(stopper)+ stopper.add_done_callback(self._stoppers.discard)+ await asyncio.shield(stopper)++ async def _stop_session(+ self, held: asyncio.Task[Any] | None, *, force: bool+ ) -> None:+ """Stop the session. A last exit passes the session it held, and the stop is+ skipped if another context now uses it; a forced stop takes whatever is current."""# ensure only one session is running at a time to avoid race conditionsasync with self._session_state.lock:- # if we are forcing a disconnect, reset the nesting counterif force:self._session_state.nesting_counter = 0-- # otherwise decrement to check if we are done nesting- else:- self._session_state.nesting_counter = max(- 0, self._session_state.nesting_counter - 1- )-- # if we are still nested, return- if self._session_state.nesting_counter > 0:+ session_task = self._session_state.session_task+ elif (+ self._session_state.session_task is not held+ or self._session_state.nesting_counter > 0+ ):+ # Stopped already, or another context connected while we waited.return-- # stop the active session- if self._session_state.session_task is None:+ else:+ session_task = held+ if session_task is None:return- session_task = self._session_state.session_taskself._session_state.stop_event.set()# 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.+ # event loop.try:- with anyio.CancelScope(shield=force):- with anyio.move_on_after(self._disconnect_timeout):- with suppress(asyncio.CancelledError):- await session_task+ with anyio.move_on_after(self._disconnect_timeout):+ with suppress(asyncio.CancelledError):+ await session_taskfinally:if not session_task.done():session_task.cancel()diff --git a/fastmcp_slim/fastmcp/client/group.py b/fastmcp_slim/fastmcp/client/group.pyindex 307aade55..22e62857b 100644--- a/fastmcp_slim/fastmcp/client/group.py+++ b/fastmcp_slim/fastmcp/client/group.py@@ -2,6 +2,7 @@from __future__ import annotations+import asyncioimport contextlibimport datetimefrom collections.abc import Mapping@@ -53,6 +54,8 @@ class ClientGroup:self._tool_routes: dict[str, ToolRoute] = {}self._catalog_loaded = Falseself._route_lock = anyio.Lock()+ # Member closes handed off by exiting contexts; referenced until done.+ self._closers: set[asyncio.Task[bool | None]] = set()@propertydef clients(self) -> Mapping[str, Client[Any]]:@@ -130,19 +133,38 @@ class ClientGroup:exc_type: type[BaseException] | None,exc_value: BaseException | None,traceback: TracebackType | None,+ ) -> bool | None:+ # Release this context's hold before any await, as Client does: a context+ # exited by cancellation can be interrupted at every await, and a hold+ # that is never released keeps every member connected for good.+ self._nesting_counter = max(0, self._nesting_counter - 1)+ held = self._exit_stack+ if self._nesting_counter > 0 or held is None:+ return None+ # Close the members in their own task, so a cancelled exit returns at+ # once instead of waiting on the lifecycle lock, and the close still runs.+ closer = asyncio.create_task(+ self._close_members(held, exc_type, exc_value, traceback)+ )+ self._closers.add(closer)+ closer.add_done_callback(self._closers.discard)+ return await asyncio.shield(closer)++ async def _close_members(+ self,+ held: contextlib.AsyncExitStack,+ exc_type: type[BaseException] | None,+ exc_value: BaseException | None,+ traceback: TracebackType | None,) -> bool | None:async with self._lifecycle_lock:- self._nesting_counter = max(0, self._nesting_counter - 1)- if self._nesting_counter > 0:+ if self._exit_stack is not held or self._nesting_counter > 0:+ # Closed already, or another context entered while we waited.return None-- stack = self._exit_stackself._exit_stack = Noneself._tool_routes.clear()self._catalog_loaded = False- if stack is not None:- return await stack.__aexit__(exc_type, exc_value, traceback)- return None+ return await held.__aexit__(exc_type, exc_value, traceback)def _require_connected(self) -> None:disconnected = [diff --git a/tests/client/client/test_client.py b/tests/client/client/test_client.pyindex 0db2a7fa9..800988cd0 100644--- a/tests/client/client/test_client.py+++ b/tests/client/client/test_client.py@@ -902,3 +902,183 @@ def test_client_new_preserves_internal_task_extension(fastmcp_server):assert clone is not clientassert ClientCreateTaskResult in clone._claim_by_modelassert clone._claim_by_model is not client._claim_by_model+++class _ReconnectGateTransport(ClientTransport):+ """Connects at once the first time; every later connect waits for `gate`."""++ def __init__(self, inner: ClientTransport) -> None:+ self._inner = inner+ self.gate = anyio.Event()+ self.connects = 0+ self.reconnect_started = anyio.Event()++ @contextlib.asynccontextmanager+ async def connect_session(+ self, **session_kwargs: Any+ ) -> AsyncIterator[ClientSession]:+ self.connects += 1+ if self.connects > 1:+ self.reconnect_started.set()+ await self.gate.wait()+ async with self._inner.connect_session(**session_kwargs) as session:+ yield session++ async def close(self) -> None:+ await self._inner.close()+++class TestExitUnderCancelledScope:+ """An `async with client` exited by a cancelled anyio scope must release its+ hold on the session. It used to skip the release, leaving the client connected+ for good: every later exit saw a stale nesting count and never disconnected."""++ @pytest.fixture+ def server(self) -> FastMCP:+ mcp = FastMCP("slow")++ @mcp.tool+ async def slow() -> str:+ await anyio.sleep(10)+ return "done"++ @mcp.tool+ def fast() -> str:+ return "fast"++ return mcp++ @staticmethod+ def assert_disconnected(client: Client) -> None:+ assert client._session_state.nesting_counter == 0+ assert client._session_state.session_task is None+ assert not client.is_connected()++ @classmethod+ async def assert_eventually_disconnected(cls, client: Client) -> None:+ """A cancelled exit returns at once and stops the session in its own task."""+ with anyio.fail_after(3):+ while client._session_state.session_task is not None:+ await anyio.sleep(0.01)+ cls.assert_disconnected(client)++ async def test_move_on_after_stops_the_session(self, server: FastMCP):+ client = Client(server)+ with anyio.move_on_after(0.2) as scope:+ async with client:+ await client.call_tool("slow", {})+ assert scope.cancelled_caught+ await self.assert_eventually_disconnected(client)++ async def test_fail_after_still_raises(self, server: FastMCP):+ client = Client(server)+ with pytest.raises(TimeoutError):+ with anyio.fail_after(0.2):+ async with client:+ await client.call_tool("slow", {})+ await self.assert_eventually_disconnected(client)++ async def test_inner_exit_keeps_the_outer_context(self, server: FastMCP):+ client = Client(server)+ async with client:+ with anyio.move_on_after(0.2):+ async with client:+ await client.call_tool("slow", {})+ assert client._session_state.nesting_counter == 1+ assert (await client.call_tool("fast", {})).data == "fast"+ self.assert_disconnected(client)++ async def test_later_contexts_disconnect_normally(self, server: FastMCP):+ client = Client(server)+ with anyio.move_on_after(0.2):+ async with client:+ await client.call_tool("slow", {})+ async with client:+ assert (await client.call_tool("fast", {})).data == "fast"+ self.assert_disconnected(client)++ async def test_nested_exit_in_a_task_cancelled_by_its_awaiter(+ self, server: FastMCP+ ):+ """LangChain runs each tool call in its own task and awaits it, so a deadline+ on the caller reaches the call as a native cancellation, which can repeat+ while the call's `async with client` is unwinding."""+ client = Client(server)++ async def tool_call() -> None:+ async with client:+ await client.call_tool("slow", {})++ async with client:+ with anyio.move_on_after(0.2):+ await asyncio.create_task(tool_call())+ assert client._session_state.nesting_counter == 1+ assert (await client.call_tool("fast", {})).data == "fast"+ self.assert_disconnected(client)++ async def test_timed_out_exit_is_not_held_by_another_tasks_connect(+ self, server: FastMCP+ ):+ """The exiting context must not wait on the session lock: another task can+ hold it through a reconnect that is slow or never finishes."""+ transport = _ReconnectGateTransport(FastMCPTransport(server))+ client = Client(transport)+ a_inside = anyio.Event()+ a_returned = anyio.Event()+ b_release = anyio.Event()++ async def a() -> None:+ with anyio.move_on_after(0.3):+ async with client:+ a_inside.set()+ await anyio.sleep(10)+ a_returned.set()++ async def b() -> None:+ await a_inside.wait()+ await client.close()+ async with client:+ await b_release.wait()++ async with anyio.create_task_group() as tg:+ tg.start_soon(a)+ tg.start_soon(b)+ await transport.reconnect_started.wait()+ with anyio.fail_after(2):+ await a_returned.wait()+ transport.gate.set()+ b_release.set()+ self.assert_disconnected(client)++ async def test_natively_cancelled_only_context_stops_the_session(+ self, server: FastMCP+ ):+ """A native cancellation, repeated by the awaiter's scope, must not stop the+ last exit from stopping the session."""+ client = Client(server)++ async def tool_call() -> None:+ async with client:+ await client.call_tool("slow", {})++ with anyio.move_on_after(0.2):+ await asyncio.create_task(tool_call())+ await self.assert_eventually_disconnected(client)++ async def test_close_racing_a_new_context_leaves_that_context_connected(+ self, server: FastMCP+ ):+ """close() stops the session it finds before a context entered after it+ can reuse that session, as on 4.0.5."""+ client = Client(server)+ await client._connect()+ close = asyncio.create_task(client.close())++ async def enter_and_call() -> str:+ async with client:+ await anyio.sleep(0.05)+ return (await client.call_tool("fast", {})).data++ assert await asyncio.create_task(enter_and_call()) == "fast"+ await close+ self.assert_disconnected(client)diff --git a/tests/client/group/test_client_group.py b/tests/client/group/test_client_group.pyindex 8b4f58de6..bb5d0d6c2 100644--- a/tests/client/group/test_client_group.py+++ b/tests/client/group/test_client_group.py@@ -4,6 +4,7 @@ from contextlib import asynccontextmanagerfrom typing import Anyfrom unittest.mock import patch+import anyioimport pytestfrom pydantic import ConfigDict@@ -418,3 +419,20 @@ async def test_failed_entry_leaves_group_reenterable():async with group:result = await group.call_tool("good_echo", {"value": "recovered"})assert result.data == "good: recovered"+++async def test_exit_under_cancelled_scope_disconnects_members():+ """A group exited by a cancelled scope must release its hold and disconnect+ its members, as Client does."""+ servers = {name: FastMCP(name) for name in ("a", "b")}+ group = ClientGroup({name: Client(server) for name, server in servers.items()})++ with anyio.move_on_after(0.2):+ async with group:+ await anyio.sleep(10)++ with anyio.fail_after(3):+ while any(client.is_connected() for client in group.clients.values()):+ await anyio.sleep(0.01)+ assert group._nesting_counter == 0+ assert group._exit_stack is Nonediff --git a/tests/client/test_stdio.py b/tests/client/test_stdio.pyindex 84232ce3e..da8e9ca8e 100644--- a/tests/client/test_stdio.py+++ b/tests/client/test_stdio.py@@ -1,5 +1,4 @@import asyncio-import contextlibimport gcimport inspectimport os@@ -295,29 +294,24 @@ class TestKeepAlive:await wait_for_process_exit(pid)- @pytest.mark.filterwarnings(- "ignore:Exception ignored in.*coroutine:pytest.PytestUnraisableExceptionWarning"- )async def test_client_abandoned_by_cancellation_does_not_wedge_transport(self, stdio_script):- """A Client left behind by a cancelled scope, once garbage-collected, must- not leave the transport unusable for the next Client.-- Abandoning a Client this way leaks its session runner, a known issue that- finalization reports as `coroutine ignored GeneratorExit`; that noise is- tolerated here so the test checks only that the next Client connects.- """+ """A Client exited by a cancelled scope, once garbage-collected, must not+ leave the transport unusable for the next Client, and must stop its+ subprocess rather than leak its session."""transport = PythonStdioTransport(stdio_script, keep_alive=False)with anyio.move_on_after(0.5):async with Client(transport) as abandoned:- await abandoned.ping()+ pid = (await abandoned.call_tool("pid")).dataawait anyio.sleep(10)+ with anyio.fail_after(3):+ while abandoned.is_connected():+ await anyio.sleep(0.01)del abandoned- await asyncio.sleep(0.1)- with contextlib.suppress(RuntimeError):- gc_collect_harder()+ gc_collect_harder()+ await wait_for_process_exit(pid)with anyio.fail_after(3):async with Client(transport) as client: