Skip to content

Fix ClientSessionGroup cleanup logic #787

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 23, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/mcp/client/session_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ class ClientSessionGroup:
the client and can be accessed via the session.

Example Usage:
name_fn = lambda name, server_info: f"{(server_info.name)}-{name}"
name_fn = lambda name, server_info: f"{(server_info.name)}_{name}"
async with ClientSessionGroup(component_name_hook=name_fn) as group:
for server_params in server_params:
group.connect_to_server(server_param)
await group.connect_to_server(server_param)
...

"""
Expand Down Expand Up @@ -145,14 +145,15 @@ async def __aexit__(
) -> bool | None:
"""Closes session exit stacks and main exit stack upon completion."""

# Only close the main exit stack if we created it
if self._owns_exit_stack:
await self._exit_stack.aclose()

# Concurrently close session stacks.
async with anyio.create_task_group() as tg:
for exit_stack in self._session_exit_stacks.values():
tg.start_soon(exit_stack.aclose)

# Only close the main exit stack if we created it
if self._owns_exit_stack:
await self._exit_stack.aclose()

@property
def sessions(self) -> list[mcp.ClientSession]:
Expand Down
Loading