Skip to content

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

fix(client): Prevent stale ClientGroup refreshes from replacing newer routes (#5543)

mika365d5d232cac
diff --git a/fastmcp_slim/fastmcp/client/group.py b/fastmcp_slim/fastmcp/client/group.py
index d4762f4c7..4d32023ea 100644
--- a/fastmcp_slim/fastmcp/client/group.py
+++ b/fastmcp_slim/fastmcp/client/group.py
@@ -71,6 +71,10 @@ class ClientGroup:
self._tool_routes: dict[str, ToolRoute] = {}
self._catalog_loaded = False
self._route_lock = anyio.Lock()
+ # Keep explicit refresh fetches and commits in the same order; this is
+ # separate from _route_lock because lazy discovery calls list_tools()
+ # while holding that lock.
+ self._refresh_lock = anyio.Lock()
# Member closes handed off by exiting contexts; referenced until done.
self._closers: set[asyncio.Task[bool | None]] = set()
@@ -250,30 +254,32 @@ class ClientGroup:
cache hits when staleness within the server's hint is acceptable.
"""
self._require_connected()
- tools: list[mcp_types.Tool] = []
- routes: dict[str, ToolRoute] = {}
- clients = list(self._clients.items())
- tool_lists = await gather(
- client.list_tools(cache_mode=cache_mode) for _, client in clients
- )
-
- for (server_name, client), server_tools in zip(
- clients, tool_lists, strict=True
- ):
- for tool in server_tools:
- public_name = f"{server_name}_{tool.name}"
- if public_name in routes:
- raise ValueError(f"Tool name collision: {public_name!r}")
- routes[public_name] = ToolRoute(
- server_name=server_name,
- client=client,
- upstream_name=tool.name,
- )
- tools.append(tool.model_copy(update={"name": public_name}))
+ async with self._refresh_lock:
+ self._require_connected()
+ tools: list[mcp_types.Tool] = []
+ routes: dict[str, ToolRoute] = {}
+ clients = list(self._clients.items())
+ tool_lists = await gather(
+ client.list_tools(cache_mode=cache_mode) for _, client in clients
+ )
- self._tool_routes = routes
- self._catalog_loaded = True
- return tools
+ for (server_name, client), server_tools in zip(
+ clients, tool_lists, strict=True
+ ):
+ for tool in server_tools:
+ public_name = f"{server_name}_{tool.name}"
+ if public_name in routes:
+ raise ValueError(f"Tool name collision: {public_name!r}")
+ routes[public_name] = ToolRoute(
+ server_name=server_name,
+ client=client,
+ upstream_name=tool.name,
+ )
+ tools.append(tool.model_copy(update={"name": public_name}))
+
+ self._tool_routes = routes
+ self._catalog_loaded = True
+ return tools
async def list_skills(
self, *, cache_mode: CacheMode = "use"
diff --git a/tests/client/group/test_client_group.py b/tests/client/group/test_client_group.py
index bb94ed331..2388570cf 100644
--- a/tests/client/group/test_client_group.py
+++ b/tests/client/group/test_client_group.py
@@ -425,6 +425,56 @@ async def test_explicit_list_tools_refreshes_past_client_response_cache():
assert result.data == "added"
+async def test_overlapping_refreshes_do_not_commit_out_of_order():
+ server = FastMCP("refresh-order")
+
+ @server.tool
+ def original() -> str:
+ return "original"
+
+ client = Client(FastMCPTransport(server))
+ group = ClientGroup({"server": client})
+ first_fetched = asyncio.Event()
+ release_first = asyncio.Event()
+ original_list_tools = client.list_tools
+ calls = 0
+
+ async def gated_list_tools(*, cache_mode="use"):
+ nonlocal calls
+ calls += 1
+ tools = await original_list_tools(cache_mode=cache_mode)
+ if calls == 1:
+ first_fetched.set()
+ await release_first.wait()
+ return tools
+
+ async with group:
+ with patch.object(client, "list_tools", side_effect=gated_list_tools):
+ first_refresh = asyncio.create_task(group.list_tools())
+ await asyncio.wait_for(first_fetched.wait(), timeout=1)
+
+ @server.tool
+ def added() -> str:
+ return "added"
+
+ # Give the newer refresh a chance to commit before the older one.
+ second_refresh = asyncio.create_task(group.list_tools())
+ await asyncio.wait({second_refresh}, timeout=0.5)
+ release_first.set()
+
+ first_tools, second_tools = await asyncio.gather(
+ first_refresh, second_refresh
+ )
+
+ assert [tool.name for tool in first_tools] == ["server_original"]
+ assert {tool.name for tool in second_tools} == {
+ "server_original",
+ "server_added",
+ }
+ route = await group.resolve_tool("server_added")
+ assert route.upstream_name == "added"
+
+
async def test_group_context_is_reentrant():
client = Client(make_server("server"))
group = ClientGroup({"server": client})