From a3f2133ab140437c30c81e932d027b51d1146b10 Mon Sep 17 00:00:00 2001 From: karthik Date: Fri, 23 Jan 2026 10:33:45 -0500 Subject: [PATCH] fix: handle EndOfStream and ClosedResourceError in send_request Fixes #1717 The `send_request` method only catches `TimeoutError` from the `response_stream_reader.receive()` call. If `receive()` raises `EndOfStream` or `ClosedResourceError` (e.g., when the connection closes unexpectedly), these exceptions propagate without being caught, potentially leaving `response_or_error` unassigned and causing an `UnboundLocalError` at the subsequent isinstance check. This adds explicit handling for these stream closure exceptions, converting them to `McpError` with `CONNECTION_CLOSED` error code. Co-Authored-By: Claude Opus 4.5 --- src/mcp/shared/session.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/mcp/shared/session.py b/src/mcp/shared/session.py index 341e1fac0..6764ce7cf 100644 --- a/src/mcp/shared/session.py +++ b/src/mcp/shared/session.py @@ -280,6 +280,16 @@ async def send_request( ), ) ) + except (anyio.EndOfStream, anyio.ClosedResourceError) as e: + raise McpError( + ErrorData( + code=CONNECTION_CLOSED, + message=( + f"Connection closed while waiting for response to " + f"{request.__class__.__name__}: {e}" + ), + ) + ) if isinstance(response_or_error, JSONRPCError): raise McpError(response_or_error.error)