python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

Exception in `ClientSessionGroup` if `streamable_http` MCP server is not available

Open hzeus opened this issue 1 year ago • 12 comments

Describe the bug When I use the ClientSessionGroup for a remote MCP server via remote_http for a remote server that is not running, I get exception RuntimeError: Attempted to exit cancel scope in a different task than it was entered in

(complete output collapsed)
an error occurred during closing of asynchronous generator <async_generator object streamablehttp_client at 0xffffa53755d0>
asyncgen: <async_generator object streamablehttp_client at 0xffffa53755d0>
  + Exception Group Traceback (most recent call last):
  |   File "/workspaces/test/.venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py", line 772, in __aexit__
  |     raise BaseExceptionGroup(
  |         "unhandled errors in a TaskGroup", self._exceptions
  |     ) from None
  | BaseExceptionGroup: unhandled errors in a TaskGroup (2 sub-exceptions)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_transports/default.py", line 101, in map_httpcore_exceptions
    |     yield
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_transports/default.py", line 394, in handle_async_request
    |     resp = await self._pool.handle_async_request(req)
    |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection_pool.py", line 256, in handle_async_request
    |     raise exc from None
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection_pool.py", line 236, in handle_async_request
    |     response = await connection.handle_async_request(
    |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |         pool_request.request
    |         ^^^^^^^^^^^^^^^^^^^^
    |     )
    |     ^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection.py", line 101, in handle_async_request
    |     raise exc
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection.py", line 78, in handle_async_request
    |     stream = await self._connect(request)
    |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection.py", line 124, in _connect
    |     stream = await self._network_backend.connect_tcp(**kwargs)
    |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_backends/auto.py", line 31, in connect_tcp
    |     return await self._backend.connect_tcp(
    |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |     ...<5 lines>...
    |     )
    |     ^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_backends/anyio.py", line 113, in connect_tcp
    |     with map_exceptions(exc_map):
    |          ~~~~~~~~~~~~~~^^^^^^^^^
    |   File "/usr/local/lib/python3.13/contextlib.py", line 162, in __exit__
    |     self.gen.throw(value)
    |     ~~~~~~~~~~~~~~^^^^^^^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_exceptions.py", line 14, in map_exceptions
    |     raise to_exc(exc) from exc
    | httpcore.ConnectError: All connection attempts failed
    | 
    | The above exception was the direct cause of the following exception:
    | 
    | Traceback (most recent call last):
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/streamable_http.py", line 391, in handle_request_async
    |     await self._handle_post_request(ctx)
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/streamable_http.py", line 251, in _handle_post_request
    |     async with ctx.client.stream(
    |                ~~~~~~~~~~~~~~~~~^
    |         "POST",
    |         ^^^^^^^
    |     ...<2 lines>...
    |         headers=headers,
    |         ^^^^^^^^^^^^^^^^
    |     ) as response:
    |     ^
    |   File "/usr/local/lib/python3.13/contextlib.py", line 214, in __aenter__
    |     return await anext(self.gen)
    |            ^^^^^^^^^^^^^^^^^^^^^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py", line 1583, in stream
    |     response = await self.send(
    |                ^^^^^^^^^^^^^^^^
    |     ...<4 lines>...
    |     )
    |     ^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py", line 1629, in send
    |     response = await self._send_handling_auth(
    |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |     ...<4 lines>...
    |     )
    |     ^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py", line 1657, in _send_handling_auth
    |     response = await self._send_handling_redirects(
    |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |     ...<3 lines>...
    |     )
    |     ^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py", line 1694, in _send_handling_redirects
    |     response = await self._send_single_request(request)
    |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py", line 1730, in _send_single_request
    |     response = await transport.handle_async_request(request)
    |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_transports/default.py", line 393, in handle_async_request
    |     with map_httpcore_exceptions():
    |          ~~~~~~~~~~~~~~~~~~~~~~~^^
    |   File "/usr/local/lib/python3.13/contextlib.py", line 162, in __exit__
    |     self.gen.throw(value)
    |     ~~~~~~~~~~~~~~^^^^^^^
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_transports/default.py", line 118, in map_httpcore_exceptions
    |     raise mapped_exc(message) from exc
    | httpx.ConnectError: All connection attempts failed
    +---------------- 2 ----------------
    | Traceback (most recent call last):
    |   File "/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/streamable_http.py", line 492, in streamablehttp_client
    |     yield (
    |     ...<3 lines>...
    |     )
    | GeneratorExit
    +------------------------------------

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/streamable_http.py", line 464, in streamablehttp_client
    async with anyio.create_task_group() as tg:
               ~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/workspaces/test/.venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py", line 778, in __aexit__
    if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__):
       ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspaces/test/.venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py", line 457, in __exit__
    raise RuntimeError(
    ...<2 lines>...
    )
RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
Traceback (most recent call last):
  File "/workspaces/test/.venv/lib/python3.13/site-packages/anyio/streams/memory.py", line 111, in receive
    return self.receive_nowait()
           ~~~~~~~~~~~~~~~~~~~^^
  File "/workspaces/test/.venv/lib/python3.13/site-packages/anyio/streams/memory.py", line 106, in receive_nowait
    raise WouldBlock
anyio.WouldBlock

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/workspaces/test.py", line 14, in <module>
    asyncio.run(main())
    ~~~~~~~~~~~^^^^^^^^
  File "/usr/local/lib/python3.13/asyncio/runners.py", line 195, in run
    return runner.run(main)
           ~~~~~~~~~~^^^^^^
  File "/usr/local/lib/python3.13/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "/usr/local/lib/python3.13/asyncio/base_events.py", line 719, in run_until_complete
    return future.result()
           ~~~~~~~~~~~~~^^
  File "/workspaces/test.py", line 10, in main
    await client_session_group.connect_to_server(server_params)
  File "/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/session_group.py", line 232, in connect_to_server
    server_info, session = await self._establish_session(server_params)
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/session_group.py", line 267, in _establish_session
    result = await session.initialize()
             ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/session.py", line 133, in initialize
    result = await self.send_request(
             ^^^^^^^^^^^^^^^^^^^^^^^^
    ...<15 lines>...
    )
    ^
  File "/workspaces/test/.venv/lib/python3.13/site-packages/mcp/shared/session.py", line 283, in send_request
    response_or_error = await response_stream_reader.receive()
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/workspaces/test/.venv/lib/python3.13/site-packages/anyio/streams/memory.py", line 119, in receive
    await receive_event.wait()
  File "/workspaces/test/.venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py", line 1774, in wait
    await self._event.wait()
  File "/usr/local/lib/python3.13/asyncio/locks.py", line 213, in wait
    await fut
asyncio.exceptions.CancelledError: Cancelled by cancel scope ffffa51c4050

To Reproduce

I tested this with this script:

import asyncio

from mcp.client.session_group import ClientSessionGroup, StreamableHttpParameters


async def main():
    async with ClientSessionGroup() as client_session_group:
        server_params = StreamableHttpParameters(url="http://localhost:3001/mcp/")
        try:
            await client_session_group.connect_to_server(server_params)
        except Exception:
            print("this is never reached")


if __name__ == "__main__":
    asyncio.run(main())

Expected behavior

I would like to be able to catch any error that happens during connect_to_server and handle it within my application code - in my case I am using the ClientSessionGroup for multiple MCP servers and want to provide the tools of the running MCP servers to the LLM.

Additional context

  • I am using version 1.9.3

hzeus avatar Jun 10 '25 09:06 hzeus

Is this related to https://github.com/modelcontextprotocol/python-sdk/issues/922?

mkeid avatar Jun 22 '25 17:06 mkeid

Facing the same issue here. We couldn't catch the exceptions when following the example. A 401 Unauthorized can break the whole thing. Maybe I'm just bad at async programming but it would be great if anyone could improve the example.

ChiNoel-osu avatar Aug 13 '25 09:08 ChiNoel-osu

Facing the same issue, it's breaking Google ADK too.

Trying random stuff to fix the issue lead me to this fix, probably not the best, but it works:

Changing from this

async def handle_request_async():
    if is_resumption:
        await self._handle_resumption_request(ctx)
    else:
        await self._handle_post_request(ctx)

To this

async def handle_request_async():
    try:
        if is_resumption:
            await self._handle_resumption_request(ctx)
        else:
            await self._handle_post_request(ctx)
    except Exception as e:
        logger.exception("Error handling request:")
        await read_stream_writer.send(e)

This is the source code:

https://github.com/modelcontextprotocol/python-sdk/blob/c3717e7ad333a234c11d084c047804999a88706e/src/mcp/client/streamable_http.py#L366-L421

Another thing that I noticed, if you remove tg.start_soon() and directly call await handle_request_async(), the issue is not present.

Please, feel free to correct me if I'm wrong.

giacomoferretti avatar Sep 16 '25 12:09 giacomoferretti

Potentially related: https://github.com/modelcontextprotocol/python-sdk/issues/1401

felixweinberger avatar Oct 03 '25 14:10 felixweinberger

Also hitting us on the adcp library

bokelley avatar Nov 07 '25 17:11 bokelley

LiteLLM fails with the Github MCP server because of this bug!

renne avatar Apr 28 '26 12:04 renne

reproduced on current main (616476f). when _handle_post_request raises an httpx.HTTPError (e.g. httpx.ConnectError for an unavailable server), the exception propagates out of handle_request_async, which was started via tg.start_soon in post_writer. that crashes the transport's task group from a different task than the one yielding the streams, surfacing as RuntimeError: Attempted to exit cancel scope in a different task than it was entered in instead of a catchable error at connect_to_server. present on main and v1.x — same code path.

the read stream is already typed SessionMessage | Exception and _handle_json_response / the 4xx branch already use read_stream_writer.send(SessionMessage(JSONRPCError(...))) for the same kind of "request died, tell the awaiter" handoff. scoping the new try/except to httpx.HTTPError keeps the existing auth-flow behavior (where OAuthFlowError deliberately propagates through the task group) untouched.

repro.py
import asyncio

from mcp.client.session_group import ClientSessionGroup, StreamableHttpParameters


async def main():
    async with ClientSessionGroup() as client_session_group:
        # Port 1 has nothing listening — triggers httpx.ConnectError
        server_params = StreamableHttpParameters(url="http://localhost:1/mcp/")
        try:
            await client_session_group.connect_to_server(server_params)
        except Exception as e:
            print(f"caught exception: {type(e).__name__}: {e}")
            return
    print("no exception raised")


if __name__ == "__main__":
    asyncio.run(main())
$ uv run python repro.py
...
RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
...
asyncio.exceptions.CancelledError: Cancelled by cancel scope ...

the try/except Exception in main() never executes — the error escapes the task group, not connect_to_server.

code path

src/mcp/client/streamable_http.py:

  • streamable_http_client opens anyio.create_task_group() as tg (line 567) and yields the read/write streams from the parent task.
  • post_writer runs in a child task; per-request it does tg.start_soon(handle_request_async) (line 478) for JSONRPCRequest.
  • handle_request_async calls _handle_post_request (line 474). a raw httpx.ConnectError from ctx.client.stream(...) (line 260) propagates back into the task group, which then cancels and rethrows from a different task than the one that entered the outer async with. RuntimeError from anyio._backends._asyncio:457 follows.
  • meanwhile ClientSession.initialize is awaiting response_stream_reader.receive() (shared/session.py), which is cancelled instead of receiving a usable error.
suggested fix
// src/mcp/client/streamable_http.py
                     async def handle_request_async():
-                        if is_resumption:
-                            await self._handle_resumption_request(ctx)
-                        else:
-                            await self._handle_post_request(ctx)
+                        try:
+                            if is_resumption:
+                                await self._handle_resumption_request(ctx)
+                            else:
+                                await self._handle_post_request(ctx)
+                        except httpx.HTTPError as exc:
+                            # Letting this escape into `tg` would crash the outer task group
+                            # from a different task than the one yielding the streams,
+                            # producing an uncatchable cancel-scope RuntimeError instead of
+                            # a connect error at the caller.
+                            logger.exception("Transport error handling request")
+                            if isinstance(message, JSONRPCRequest):
+                                error_data = ErrorData(code=INTERNAL_ERROR, message=f"Transport error: {exc}")
+                                error_msg = SessionMessage(
+                                    JSONRPCError(jsonrpc="2.0", id=message.id, error=error_data)
+                                )
+                                with contextlib.suppress(anyio.BrokenResourceError, anyio.ClosedResourceError):
+                                    await read_stream_writer.send(error_msg)

test to verify: tests/issues/test_915_streamable_http_unreachable.py calls ClientSessionGroup().connect_to_server(StreamableHttpParameters(url=<closed-port>)) under anyio.fail_after(10) and asserts no RuntimeError("...cancel scope...") is anywhere in the raised exception's cause/context/group tree.

needs the same backport on v1.x.

mcp-claude[bot] avatar Jun 01 '26 11:06 mcp-claude[bot]

the catch here isn't that connect_to_server throws, it's where it throws from. ClientSessionGroup stacks each server's streamablehttp_client into one task group, so a failed connect unwinds the cancel scope in a different task than entered it. your try/except around connect_to_server never sees the ConnectError, it resurfaces during teardown as the 'cancel scope in a different task' RuntimeError. one unreachable server can't be isolated at the call site, the group owns the failure and hands back a teardown error you can't map to which server died. per-server connect needs its own scope, not a shared task group, if you want the reachable servers to stay up.

m13v avatar Jun 01 '26 12:06 m13v

I reproduced this on current main and pushed a verified fix:

  • Branch: https://github.com/syf2211/python-sdk/tree/fix/915-streamable-http-unreachable-server
  • Compare: https://github.com/modelcontextprotocol/python-sdk/compare/main...syf2211:python-sdk:fix/915-streamable-http-unreachable-server

What it changes

Catch httpx.HTTPError in streamable HTTP post_writer request tasks and complete the pending JSON-RPC waiter instead of letting the exception escape into the outer transport task group (which caused the uncatchable cancel-scope RuntimeError).

Transport faults are tagged in ErrorData.data and re-raised as raw httpx errors in JSONRPCDispatcher.send_raw_request, preserving auto-mode negotiation semantics.

Validation

  • tests/issues/test_915_streamable_http_unreachable.py — passed
  • test_auto_mode_propagates_a_network_error_from_discover_without_initializing — passed
  • tests/client/test_probe.py — 21/21 passed
  • ruff check — clean

I wasn't able to open the upstream PR directly (API returns permission error). Happy to iterate on review from this branch.

syf2211 avatar Jun 26 '26 13:06 syf2211

PR ready for review

Upstream PR creation is currently blocked for my account on this repo (GraphQL FORBIDDEN). Branch is pushed and verified:

  • Compare: https://github.com/modelcontextprotocol/python-sdk/compare/main...syf2211:fix/915-streamable-http-unreachable-server
  • Branch: fix/915-streamable-http-unreachable-server

Summary

Catch httpx.HTTPError in streamable HTTP post_writer and complete the pending JSON-RPC waiter instead of letting the exception escape into the outer transport task group (fixes uncatchable cancel-scope RuntimeError).

Tests

  • tests/issues/test_915_streamable_http_unreachable.py — passed
  • tests/client/test_probe.py — 20/20 passed
  • auto-mode network error test — passed

Happy to open the PR manually if a maintainer can unblock, or feel free to cherry-pick from the compare link.

syf2211 avatar Jun 26 '26 22:06 syf2211

Working on this — catching httpx.HTTPError in streamable HTTP post_writer request tasks so transport failures complete the pending JSON-RPC waiter instead of crashing the outer task group.

devansh-dek avatar Jun 30 '26 02:06 devansh-dek

Adding a data point: this cancel-scope teardown failure also fires on a different trigger than the "server not available at startup" case in this issue — a transient HTTP error on an already-established streamable-HTTP connection.

In our case the upstream returned a 502 Bad Gateway mid-request; response.raise_for_status() in streamable_http.py raised inside the client's TaskGroup, and during teardown GeneratorExit propagated through streamablehttp_client's async generator, ending in:

RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
  File ".../anyio/_backends/_asyncio.py", line 783, in __aexit__
  File ".../mcp/client/streamable_http.py", line 565, in handle_request_async
  File ".../mcp/client/streamable_http.py", line 358, in _handle_post_request  # response.raise_for_status() -> 502
  File ".../mcp/client/streamable_http.py", line 670/722, in streamable_http_client / streamablehttp_client  # GeneratorExit

Versions: mcp 1.26.0, anyio 4.12.1, httpx 0.28.1, Python 3.12.12.

Downstream impact: in a long-lived client (an MCP→OpenAPI proxy, mcpo), this doesn't just surface as a one-off error — the failed teardown leaves a coroutine the event loop retries with no await pause, pinning one CPU core at ~100% indefinitely until the process is killed. Full downstream repro + environment: https://github.com/open-webui/mcpo/issues/302.

Suggestion (same spirit as #2443 / #3025): the teardown needs to be robust to being triggered by an in-flight HTTPStatusError, not only clean shutdown — the reader child should signal, and the owning task should close its own cancel scope, so a mid-connection error can't cross task boundaries.

jlacour-git avatar Jul 15 '26 17:07 jlacour-git