π The fast, Pythonic way to build MCP servers and clients.
fix(client): close partial group connections on cancellation (#5519)
mikae9adf5c63586
diff --git a/fastmcp_slim/fastmcp/client/group.py b/fastmcp_slim/fastmcp/client/group.pyindex 4d32023ea..f945d2297 100644--- a/fastmcp_slim/fastmcp/client/group.py+++ b/fastmcp_slim/fastmcp/client/group.py@@ -132,39 +132,16 @@ class ClientGroup:await stack.__aenter__()# Connect concurrently: entry latency stays one handshake deep instead- # of growing linearly with the number of servers. With- # return_exceptions=True every connection attempt runs to completion,- # so on partial failure the successes are known and can be unwound.- clients = list(self._clients.values())- results = await gather(- (_enter_client_context(client) for client in clients),- return_exceptions=True,- )- errors = [result for result in results if isinstance(result, BaseException)]- if errors:- for client, result in zip(clients, results, strict=True):- if not isinstance(result, BaseException):- with contextlib.suppress(Exception):- await client._exit_context(- result.session_task,- result.task,- None,- None,- None,- )- await stack.aclose()- raise errors[0]-- for client, result in zip(clients, results, strict=True):- assert not isinstance(result, BaseException)+ # of growing linearly with the number of servers. Each member's exit is+ # registered the moment its entry succeeds, so a failed or cancelled+ # entry can unwind exactly the members that connected.+ async def enter_member(client: Client[Any]) -> None:+ entered = await _enter_client_context(client)async def exit_client(exc_type: type[BaseException] | None,exc_value: BaseException | None,traceback: TracebackType | None,- *,- client: Client[Any] = client,- entered: _EnteredClient = result,) -> bool | None:return await client._exit_context(entered.session_task,@@ -175,8 +152,28 @@ class ClientGroup:)stack.push_async_exit(exit_client)++ try:+ results = await gather(+ (enter_member(client) for client in self._clients.values()),+ return_exceptions=True,+ )+ except BaseException:+ await self._unwind_partial_entry(stack)+ raise++ errors = [result for result in results if isinstance(result, BaseException)]+ if errors:+ await self._unwind_partial_entry(stack)+ raise errors[0]return stack+ @staticmethod+ async def _unwind_partial_entry(stack: contextlib.AsyncExitStack) -> None:+ """Disconnect the members a failed or cancelled entry already connected."""+ with anyio.CancelScope(shield=True), contextlib.suppress(Exception):+ await stack.aclose()+async def __aexit__(self,exc_type: type[BaseException] | None,diff --git a/tests/client/group/test_client_group.py b/tests/client/group/test_client_group.pyindex 2388570cf..10c3b3d8b 100644--- a/tests/client/group/test_client_group.py+++ b/tests/client/group/test_client_group.py@@ -581,6 +581,40 @@ async def test_failed_entry_leaves_group_reenterable():assert result.data == "good: recovered"+async def test_cancelled_entry_disconnects_connected_members():+ """Cancelling group entry while one member is still connecting must+ disconnect the members that already connected."""+ a = Client(make_server("a"))+ b = Client(make_server("b"))+ group = ClientGroup({"a": a, "b": b})+ b_entering = anyio.Event()++ async def held_entry() -> Client[Any]:+ b_entering.set()+ await anyio.sleep_forever()+ raise AssertionError("unreachable")++ with patch.object(b, "__aenter__", held_entry):+ entry = asyncio.create_task(group.__aenter__())+ with anyio.fail_after(3):+ await b_entering.wait()+ while not a.is_connected():+ await anyio.sleep(0.01)+ entry.cancel()+ with pytest.raises(asyncio.CancelledError):+ await entry++ assert not a.is_connected()+ assert group._exit_stack is None+ assert group._nesting_counter == 0++ async with group:+ result = await group.call_tool("b_echo", {"value": "recovered"})+ assert result.data == "b: recovered"+ assert not a.is_connected()+ assert not b.is_connected()++async def test_exit_under_cancelled_scope_disconnects_members():"""A group exited by a cancelled scope must release its hold and disconnectits members, as Client does."""