Repository navigation
Description
Summary
When ClientSessionGroup.connect_to_server fails to connect to a streamable-HTTP server, it raises CancelledError instead of the connection error. It also leaves the calling task in a cancelled state: asyncio.current_task().cancelling() is 1 afterwards, and every later await in that task raises CancelledError. Opening the same server with streamable_http_client + ClientSession directly raises the expected ExceptionGroup([ConnectError]) and leaves the task usable.
Likely cause
ClientSessionGroup._establish_session (mcp/client/session_group.py) cleans up the per-session exit stack in except Exception:. When the connection fails, the transport's task group cancels the host task; the resulting CancelledError is a BaseException, so it bypasses the handler. session_stack.aclose() never runs, and the transport's cancel scope stays entered on the caller's task. Catching BaseException there, or unwinding the session stack in a finally, would let the transport's task group convert the cancellation back into the real error.
Reproducer (no third-party code; nothing listening on port 9)
import asyncio
from mcp import ClientSession
from mcp.client.session_group import ClientSessionGroup, StreamableHttpParameters
from mcp.client.streamable_http import streamable_http_client
URL = "http://127.0.0.1:9/mcp" # nothing listens on port 9
async def report(label: str) -> None:
task = asyncio.current_task()
print(f" {label}: task.cancelling() = {task.cancelling()}")
try:
await asyncio.sleep(0.01)
print(f" {label}: a later await works")
except asyncio.CancelledError:
print(f" {label}: a later await raises CancelledError")
async def with_plain_client() -> None:
try:
async with streamable_http_client(URL) as (read, write), ClientSession(read, write) as session:
await session.initialize()
except BaseException as exc:
print(f"plain client raised {type(exc).__name__}: {exc!r:.120}")
await report("plain client")
async def with_session_group() -> None:
try:
async with ClientSessionGroup() as group:
await group.connect_to_server(StreamableHttpParameters(url=URL))
except BaseException as exc:
print(f"ClientSessionGroup raised {type(exc).__name__}: {exc!r:.120}")
await report("ClientSessionGroup")
asyncio.run(with_plain_client())
asyncio.run(with_session_group())Output:
plain client raised ExceptionGroup: ExceptionGroup('unhandled errors in a TaskGroup', [ConnectError('All connection attempts failed')])
plain client: task.cancelling() = 0
plain client: a later await works
ClientSessionGroup raised CancelledError: CancelledError('Cancelled via cancel scope 2892b054730')
ClientSessionGroup: task.cancelling() = 1
ClientSessionGroup: a later await raises CancelledError
Expected vs actual
| Expected | Actual | |
|---|---|---|
| Exception | the connection error (or an ExceptionGroup holding it), as with the plain client |
CancelledError |
| Caller's task afterwards | usable: cancelling() == 0 |
stuck in cancellation: cancelling() == 1 (it rises with each retry), and every later await raises |
A host application that retries, or that keeps working after one server fails, cannot recover inside the same task.
Environment
mcp2.0.0,anyio4.14.2,httpx22.13.0- CPython 3.14.10, asyncio backend
- Windows 11. Linux not tried; the code path is platform-independent.
Workaround
Do not call connect_to_server for HTTP transports. Open streamable_http_client (or sse_client) and ClientSession on the caller's own AsyncExitStack, unwind that stack on BaseException, and register the session with group.connect_with_session(server_info, session).
Activity
oliarmak-web commentedon Nov 2, 2026
I would be interested in working on this after maintainer confirmation. My proposed scope would be limited to the failed connection cleanup path in
ClientSessionGroup._establish_session: ensure the per-session exit stack is unwound when setup raises aBaseException, preserve the underlying transport error rather than leakingCancelledError, and verify that the caller task has no remaining cancellation state.I would add deterministic offline regression coverage for an unreachable Streamable HTTP endpoint, including assertions that the original connection failure is surfaced,
task.cancelling()returns to zero, a later await succeeds, and repeated failed connections do not accumulate cancellation state.Does this cleanup behavior match the intended contract, and if so, would a maintainer assign the issue to me for a focused PR?
AI disclosure: I used OpenAI Codex to help review the reported control flow and draft this proposed scope. I will personally validate the reproduction, implementation, and tests.
media-ctrl commentedon Nov 4, 2026
oliarmak-web commentedon Nov 4, 2026
Thanks for reproducing this and for testing the cleanup alternatives. Your AnyIO cancel-scope observation is important. I agree that a simple
except BaseException,finally: aclose(), or caller-sideuncancel()change would not be a defensible fix while the transport context remains owned by the caller task.I would revise my proposed scope as follows:
current_task().cancelling() == 0, a successful subsequent await, and no accumulated cancellation across repeated failures.connect_to_serverreturns and closes cleanly with the session group.The main design question is how the child task should communicate a successfully initialized session while retaining ownership of the live transport context until group shutdown. I would prefer to align on that lifecycle before implementing it.
Could a maintainer confirm whether task-owned transport lifecycle management is the intended direction and, if so, assign the issue to me for a focused implementation?
AI disclosure: I use OpenAI Codex to assist with code navigation and drafting, and I will personally reproduce, implement, and validate the behavior and tests.