Title: Exception in `ClientSessionGroup` if `streamable_http` MCP server is not available · Issue #915 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: Exception in `ClientSessionGroup` if `streamable_http` MCP server is not available · Issue #915 · modelcontextprotocol/python-sdk
X Title: Exception in `ClientSessionGroup` if `streamable_http` MCP server is not available · Issue #915 · modelcontextprotocol/python-sdk
Description: 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 (...
Open Graph Description: 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...
X Description: 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...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/915
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Exception in `ClientSessionGroup` if `streamable_http` MCP server is not available","articleBody":"**Describe the bug**\nWhen 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`\n\n\u003cdetails\u003e\n\u003csummary\u003e\n(complete output collapsed)\n\u003c/summary\u003e\n\n```\nan error occurred during closing of asynchronous generator \u003casync_generator object streamablehttp_client at 0xffffa53755d0\u003e\nasyncgen: \u003casync_generator object streamablehttp_client at 0xffffa53755d0\u003e\n + Exception Group Traceback (most recent call last):\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py\", line 772, in __aexit__\n | raise BaseExceptionGroup(\n | \"unhandled errors in a TaskGroup\", self._exceptions\n | ) from None\n | BaseExceptionGroup: unhandled errors in a TaskGroup (2 sub-exceptions)\n +-+---------------- 1 ----------------\n | Traceback (most recent call last):\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_transports/default.py\", line 101, in map_httpcore_exceptions\n | yield\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_transports/default.py\", line 394, in handle_async_request\n | resp = await self._pool.handle_async_request(req)\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection_pool.py\", line 256, in handle_async_request\n | raise exc from None\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection_pool.py\", line 236, in handle_async_request\n | response = await connection.handle_async_request(\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n | pool_request.request\n | ^^^^^^^^^^^^^^^^^^^^\n | )\n | ^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection.py\", line 101, in handle_async_request\n | raise exc\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection.py\", line 78, in handle_async_request\n | stream = await self._connect(request)\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_async/connection.py\", line 124, in _connect\n | stream = await self._network_backend.connect_tcp(**kwargs)\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_backends/auto.py\", line 31, in connect_tcp\n | return await self._backend.connect_tcp(\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n | ...\u003c5 lines\u003e...\n | )\n | ^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_backends/anyio.py\", line 113, in connect_tcp\n | with map_exceptions(exc_map):\n | ~~~~~~~~~~~~~~^^^^^^^^^\n | File \"/usr/local/lib/python3.13/contextlib.py\", line 162, in __exit__\n | self.gen.throw(value)\n | ~~~~~~~~~~~~~~^^^^^^^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpcore/_exceptions.py\", line 14, in map_exceptions\n | raise to_exc(exc) from exc\n | httpcore.ConnectError: All connection attempts failed\n | \n | The above exception was the direct cause of the following exception:\n | \n | Traceback (most recent call last):\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/streamable_http.py\", line 391, in handle_request_async\n | await self._handle_post_request(ctx)\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/streamable_http.py\", line 251, in _handle_post_request\n | async with ctx.client.stream(\n | ~~~~~~~~~~~~~~~~~^\n | \"POST\",\n | ^^^^^^^\n | ...\u003c2 lines\u003e...\n | headers=headers,\n | ^^^^^^^^^^^^^^^^\n | ) as response:\n | ^\n | File \"/usr/local/lib/python3.13/contextlib.py\", line 214, in __aenter__\n | return await anext(self.gen)\n | ^^^^^^^^^^^^^^^^^^^^^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py\", line 1583, in stream\n | response = await self.send(\n | ^^^^^^^^^^^^^^^^\n | ...\u003c4 lines\u003e...\n | )\n | ^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py\", line 1629, in send\n | response = await self._send_handling_auth(\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n | ...\u003c4 lines\u003e...\n | )\n | ^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py\", line 1657, in _send_handling_auth\n | response = await self._send_handling_redirects(\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n | ...\u003c3 lines\u003e...\n | )\n | ^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py\", line 1694, in _send_handling_redirects\n | response = await self._send_single_request(request)\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_client.py\", line 1730, in _send_single_request\n | response = await transport.handle_async_request(request)\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_transports/default.py\", line 393, in handle_async_request\n | with map_httpcore_exceptions():\n | ~~~~~~~~~~~~~~~~~~~~~~~^^\n | File \"/usr/local/lib/python3.13/contextlib.py\", line 162, in __exit__\n | self.gen.throw(value)\n | ~~~~~~~~~~~~~~^^^^^^^\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/httpx/_transports/default.py\", line 118, in map_httpcore_exceptions\n | raise mapped_exc(message) from exc\n | httpx.ConnectError: All connection attempts failed\n +---------------- 2 ----------------\n | Traceback (most recent call last):\n | File \"/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/streamable_http.py\", line 492, in streamablehttp_client\n | yield (\n | ...\u003c3 lines\u003e...\n | )\n | GeneratorExit\n +------------------------------------\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/streamable_http.py\", line 464, in streamablehttp_client\n async with anyio.create_task_group() as tg:\n ~~~~~~~~~~~~~~~~~~~~~~~^^\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py\", line 778, in __aexit__\n if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__):\n ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py\", line 457, in __exit__\n raise RuntimeError(\n ...\u003c2 lines\u003e...\n )\nRuntimeError: Attempted to exit cancel scope in a different task than it was entered in\nTraceback (most recent call last):\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/anyio/streams/memory.py\", line 111, in receive\n return self.receive_nowait()\n ~~~~~~~~~~~~~~~~~~~^^\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/anyio/streams/memory.py\", line 106, in receive_nowait\n raise WouldBlock\nanyio.WouldBlock\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n File \"/workspaces/test.py\", line 14, in \u003cmodule\u003e\n asyncio.run(main())\n ~~~~~~~~~~~^^^^^^^^\n File \"/usr/local/lib/python3.13/asyncio/runners.py\", line 195, in run\n return runner.run(main)\n ~~~~~~~~~~^^^^^^\n File \"/usr/local/lib/python3.13/asyncio/runners.py\", line 118, in run\n return self._loop.run_until_complete(task)\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^\n File \"/usr/local/lib/python3.13/asyncio/base_events.py\", line 719, in run_until_complete\n return future.result()\n ~~~~~~~~~~~~~^^\n File \"/workspaces/test.py\", line 10, in main\n await client_session_group.connect_to_server(server_params)\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/session_group.py\", line 232, in connect_to_server\n server_info, session = await self._establish_session(server_params)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/session_group.py\", line 267, in _establish_session\n result = await session.initialize()\n ^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/mcp/client/session.py\", line 133, in initialize\n result = await self.send_request(\n ^^^^^^^^^^^^^^^^^^^^^^^^\n ...\u003c15 lines\u003e...\n )\n ^\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/mcp/shared/session.py\", line 283, in send_request\n response_or_error = await response_stream_reader.receive()\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/anyio/streams/memory.py\", line 119, in receive\n await receive_event.wait()\n File \"/workspaces/test/.venv/lib/python3.13/site-packages/anyio/_backends/_asyncio.py\", line 1774, in wait\n await self._event.wait()\n File \"/usr/local/lib/python3.13/asyncio/locks.py\", line 213, in wait\n await fut\nasyncio.exceptions.CancelledError: Cancelled by cancel scope ffffa51c4050\n```\n\u003c/details\u003e\n\n\n**To Reproduce**\n\nI tested this with this script:\n\n```python\nimport asyncio\n\nfrom mcp.client.session_group import ClientSessionGroup, StreamableHttpParameters\n\n\nasync def main():\n async with ClientSessionGroup() as client_session_group:\n server_params = StreamableHttpParameters(url=\"http://localhost:3001/mcp/\")\n try:\n await client_session_group.connect_to_server(server_params)\n except Exception:\n print(\"this is never reached\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n```\n\n**Expected behavior**\n\nI 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.\n\n\n**Additional context**\n- I am using version `1.9.3`\n\n","author":{"url":"https://github.com/hzeus","@type":"Person","name":"hzeus"},"datePublished":"2025-06-10T09:49:49.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":12},"url":"https://github.com/915/python-sdk/issues/915"}
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:52f27e41-e0b1-2211-dd48-86b8af228048 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | CC40:A2CB5:7EF6F4:B55116:6A606B40 |
| html-safe-nonce | 8b1afd33e14af63064cd06846eb27876fcea82703801baeecec070059f2c6cc4 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDQzQwOkEyQ0I1OjdFRjZGNDpCNTUxMTY6NkE2MDZCNDAiLCJ2aXNpdG9yX2lkIjoiMTQ2OTE4NjA3NDY4MjA5MjM1MiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | c879206cef6ba09403775828e7fa592e39109ea30db5598b58f262d4eabd18a5 |
| hovercard-subject-tag | issue:3132897135 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/915/issue_layout |
| twitter:image | https://opengraph.githubassets.com/0ef678c6cc0bbeda5d13c9fbb2102977cdb8dc432fc5e85f0587629e9bfdebef/modelcontextprotocol/python-sdk/issues/915 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/0ef678c6cc0bbeda5d13c9fbb2102977cdb8dc432fc5e85f0587629e9bfdebef/modelcontextprotocol/python-sdk/issues/915 |
| og:image:alt | 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... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | hzeus |
| hostname | github.com |
| expected-hostname | github.com |
| None | 60da8c2a42fa2bbf5f7567474990ec467836a84444262a58e200fa91b7f3d2d0 |
| turbo-cache-control | no-preview |
| go-import | github.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git |
| octolytics-dimension-user_id | 182288589 |
| octolytics-dimension-user_login | modelcontextprotocol |
| octolytics-dimension-repository_id | 862584018 |
| octolytics-dimension-repository_nwo | modelcontextprotocol/python-sdk |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 862584018 |
| octolytics-dimension-repository_network_root_nwo | modelcontextprotocol/python-sdk |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 9824515e740d83d5eb82168a089b806ab0fe04a1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width