Skip to content

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

Propagate child cancellation from gather (#5161)

Dennis Khylkouskif8439a3e9f5f
diff --git a/fastmcp_slim/fastmcp/utilities/async_utils.py b/fastmcp_slim/fastmcp/utilities/async_utils.py
index 978c84a6e..f5e3b1134 100644
--- a/fastmcp_slim/fastmcp/utilities/async_utils.py
+++ b/fastmcp_slim/fastmcp/utilities/async_utils.py
@@ -85,14 +85,18 @@ async def gather(
List of results in the same order as input awaitables.
"""
results: list[T | BaseException] = []
+ cancelled: BaseException | None = None
async def run_at(i: int, aw: Awaitable[T]) -> None:
+ nonlocal cancelled
try:
results[i] = await aw
except BaseException as e:
if return_exceptions:
results[i] = e
else:
+ if cancelled is None and isinstance(e, anyio.get_cancelled_exc_class()):
+ cancelled = e
raise
pending = enumerate(awaitables)
@@ -117,4 +121,7 @@ async def gather(
remaining.close()
raise
+ # Task groups suppress child cancellation, but incomplete results are invalid.
+ if cancelled is not None:
+ raise cancelled
return results
diff --git a/tests/client/group/test_client_group.py b/tests/client/group/test_client_group.py
index bb5d0d6c2..4b1a496af 100644
--- a/tests/client/group/test_client_group.py
+++ b/tests/client/group/test_client_group.py
@@ -83,6 +83,19 @@ async def test_clients_negotiate_independently():
assert not modern.is_connected()
+async def test_list_tools_propagates_child_cancellation():
+ healthy = Client(make_server("healthy"))
+ cancelled = Client(make_server("cancelled"))
+ group = ClientGroup({"healthy": healthy, "cancelled": cancelled})
+
+ async with group:
+ original_tools = await group.list_tools()
+ with patch.object(cancelled, "list_tools", side_effect=asyncio.CancelledError):
+ with pytest.raises(asyncio.CancelledError):
+ await group.list_tools()
+ assert await group.list_tools() == original_tools
+
+
async def test_from_config_applies_mode_per_server():
config = MCPConfig(
mcpServers={
diff --git a/tests/utilities/test_async_utils.py b/tests/utilities/test_async_utils.py
index 7f9d02d5d..788d2678f 100644
--- a/tests/utilities/test_async_utils.py
+++ b/tests/utilities/test_async_utils.py
@@ -1,5 +1,6 @@
"""Tests for fastmcp.utilities.async_utils."""
+import asyncio
import functools
import inspect
from collections.abc import Awaitable, Iterator
@@ -56,12 +57,63 @@ class TestIsCoroutineFunction:
class TestGather:
+ @pytest.mark.parametrize("return_exceptions", [False, True])
+ async def test_child_cancellation(self, return_exceptions: bool) -> None:
+ async def cancel() -> int:
+ raise asyncio.CancelledError("child cancelled")
+
+ if return_exceptions:
+ results = await gather([cancel(), _async_fn(1)], return_exceptions=True)
+ assert isinstance(results[0], asyncio.CancelledError)
+ assert results[1] == 1
+ else:
+ with pytest.raises(asyncio.CancelledError, match="child cancelled"):
+ await gather([cancel(), _async_fn(1)])
+
+ async def test_child_cancellation_cleans_up_siblings(self) -> None:
+ started = anyio.Event()
+ finished = anyio.Event()
+
+ async def sibling() -> None:
+ try:
+ started.set()
+ await anyio.sleep_forever()
+ finally:
+ finished.set()
+
+ async def cancel() -> None:
+ await started.wait()
+ raise asyncio.CancelledError
+
+ with pytest.raises(asyncio.CancelledError):
+ await gather([sibling(), cancel()])
+ assert finished.is_set()
+
async def test_returns_results_in_input_order(self) -> None:
async def value(result: int) -> int:
return result
assert await gather([value(1), value(2), value(3)]) == [1, 2, 3]
+ async def test_successful_none_result(self) -> None:
+ async def value() -> None:
+ return None
+
+ assert await gather([value()]) == [None]
+
+ async def test_parent_cancellation(self) -> None:
+ started = anyio.Event()
+
+ async def child() -> None:
+ started.set()
+ await anyio.sleep_forever()
+
+ task = asyncio.create_task(gather([child()]))
+ await started.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
async def test_accepts_a_generator(self) -> None:
async def value(result: int) -> int:
return result