Skip to content

Fix unhandled TaskGroup exceptions that occur in transport layer #999

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
18 changes: 13 additions & 5 deletions src/mcp/client/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ async def sse_client(
read_stream_writer, read_stream = anyio.create_memory_object_stream(0)
write_stream, write_stream_reader = anyio.create_memory_object_stream(0)

async with anyio.create_task_group() as tg:
try:
try:
async with anyio.create_task_group() as tg:
logger.debug(f"Connecting to SSE endpoint: {remove_request_params(url)}")
async with httpx_client_factory(
headers=headers, auth=auth, timeout=httpx.Timeout(timeout, read=sse_read_timeout)
Expand Down Expand Up @@ -139,6 +139,14 @@ async def post_writer(endpoint_url: str):
yield read_stream, write_stream
finally:
tg.cancel_scope.cancel()
finally:
await read_stream_writer.aclose()
await write_stream.aclose()
except Exception as e:
logger.error(f"TaskGroup exception in SSE transport: {e}")
try:
await read_stream_writer.send(e)
except Exception:
logger.error(f"Failed to send TaskGroup exception to read stream: {e}")
raise

finally:
await read_stream_writer.aclose()
await write_stream.aclose()
17 changes: 12 additions & 5 deletions src/mcp/client/streamable_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,8 +471,8 @@ async def streamablehttp_client(
read_stream_writer, read_stream = anyio.create_memory_object_stream[SessionMessage | Exception](0)
write_stream, write_stream_reader = anyio.create_memory_object_stream[SessionMessage](0)

async with anyio.create_task_group() as tg:
try:
try:
async with anyio.create_task_group() as tg:
logger.debug(f"Connecting to StreamableHTTP endpoint: {url}")

async with httpx_client_factory(
Expand Down Expand Up @@ -504,6 +504,13 @@ def start_get_stream() -> None:
if transport.session_id and terminate_on_close:
await transport.terminate_session(client)
tg.cancel_scope.cancel()
finally:
await read_stream_writer.aclose()
await write_stream.aclose()
except Exception as e:
logger.error(f"TaskGroup exception in StreamableHTTP transport: {e}")
try:
await read_stream_writer.send(e)
except Exception:
logger.error(f"Failed to send TaskGroup exception to read stream: {e}")
raise
finally:
await read_stream_writer.aclose()
await write_stream.aclose()
Loading