π The fast, Pythonic way to build MCP servers and clients.
fix(proxy): shield stateful proxy disconnect during session teardown (#4363)
Jeremiah Lowinddcdf648131b
diff --git a/fastmcp_slim/fastmcp/server/providers/proxy.py b/fastmcp_slim/fastmcp/server/providers/proxy.pyindex b3bcae43d..8dab75564 100644--- a/fastmcp_slim/fastmcp/server/providers/proxy.py+++ b/fastmcp_slim/fastmcp/server/providers/proxy.py@@ -1232,7 +1232,13 @@ class StatefulProxyClient(ProxyClient[ClientTransportT]):async def _on_session_exit():self._caches.pop(session)logger.debug(f"{proxy_client} will be disconnect")- await proxy_client._disconnect(force=True)+ # This callback runs while the server session's exit stack is+ # unwinding, which usually happens because the owning task is+ # being cancelled. Shield the disconnect so the forced cleanup+ # actually runs to completion instead of aborting at the first+ # cancellation checkpoint (e.g. acquiring the session lock).+ with anyio.CancelScope(shield=True):+ await proxy_client._disconnect(force=True)session._exit_stack.push_async_callback(_on_session_exit)