Skip to content

Commit 8b4b731

Browse files
author
Yurii Kulaksyz
committed
Fix unhandled TaskGroup exceptions that occur in transport layer
1 parent d0443a1 commit 8b4b731

File tree

2 files changed

+25
-10
lines changed

2 files changed

+25
-10
lines changed

src/mcp/client/sse.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,8 @@ async def sse_client(
5151
read_stream_writer, read_stream = anyio.create_memory_object_stream(0)
5252
write_stream, write_stream_reader = anyio.create_memory_object_stream(0)
5353

54-
async with anyio.create_task_group() as tg:
55-
try:
54+
try:
55+
async with anyio.create_task_group() as tg:
5656
logger.debug(f"Connecting to SSE endpoint: {remove_request_params(url)}")
5757
async with httpx_client_factory(
5858
headers=headers, auth=auth, timeout=httpx.Timeout(timeout, read=sse_read_timeout)
@@ -139,6 +139,14 @@ async def post_writer(endpoint_url: str):
139139
yield read_stream, write_stream
140140
finally:
141141
tg.cancel_scope.cancel()
142-
finally:
143-
await read_stream_writer.aclose()
144-
await write_stream.aclose()
142+
except Exception as e:
143+
logger.error(f"TaskGroup exception in SSE transport: {e}")
144+
try:
145+
await read_stream_writer.send(e)
146+
except Exception:
147+
logger.error(f"Failed to send TaskGroup exception to read stream: {e}")
148+
raise
149+
150+
finally:
151+
await read_stream_writer.aclose()
152+
await write_stream.aclose()

src/mcp/client/streamable_http.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -471,8 +471,8 @@ async def streamablehttp_client(
471471
read_stream_writer, read_stream = anyio.create_memory_object_stream[SessionMessage | Exception](0)
472472
write_stream, write_stream_reader = anyio.create_memory_object_stream[SessionMessage](0)
473473

474-
async with anyio.create_task_group() as tg:
475-
try:
474+
try:
475+
async with anyio.create_task_group() as tg:
476476
logger.debug(f"Connecting to StreamableHTTP endpoint: {url}")
477477

478478
async with httpx_client_factory(
@@ -504,6 +504,13 @@ def start_get_stream() -> None:
504504
if transport.session_id and terminate_on_close:
505505
await transport.terminate_session(client)
506506
tg.cancel_scope.cancel()
507-
finally:
508-
await read_stream_writer.aclose()
509-
await write_stream.aclose()
507+
except Exception as e:
508+
logger.error(f"TaskGroup exception in StreamableHTTP transport: {e}")
509+
try:
510+
await read_stream_writer.send(e)
511+
except Exception:
512+
logger.error(f"Failed to send TaskGroup exception to read stream: {e}")
513+
raise
514+
finally:
515+
await read_stream_writer.aclose()
516+
await write_stream.aclose()

0 commit comments

Comments
 (0)