diff --git a/src/mcp/client/sse.py b/src/mcp/client/sse.py index 791c602cd..aa4bb1fed 100644 --- a/src/mcp/client/sse.py +++ b/src/mcp/client/sse.py @@ -111,7 +111,11 @@ async def sse_reader( raise sse_exc except Exception as exc: logger.exception("Error in sse_reader") - await read_stream_writer.send(exc) + try: + await read_stream_writer.send(exc) + except anyio.ClosedResourceError: + # Stream already closed during shutdown, which is expected + logger.debug("Stream closed during error handling - ignoring") finally: await read_stream_writer.aclose() @@ -142,7 +146,13 @@ async def post_writer(endpoint_url: str): try: yield read_stream, write_stream finally: - tg.cancel_scope.cancel() + # FIX: Removed manual tg.cancel_scope.cancel() that violated anyio lifecycle + # The original code called tg.cancel_scope.cancel() here, but this caused: + # "RuntimeError: Attempted to exit cancel scope in a different task than it was entered in" + # + # The task group's __aexit__ will properly cancel all child tasks when + # this context manager exits, so no manual cancellation is needed. + pass finally: await read_stream_writer.aclose() await write_stream.aclose()