Skip to content

Commit a21b714

Browse files
giulio-leoneCopilot
andcommitted
fix: catch ClosedResourceError in error handler to prevent crash on client disconnect
When a client disconnects during request processing, _handle_message receives the exception and tries to send a log message back to the client via send_log_message(). Since the write stream is already closed, this raises ClosedResourceError (or BrokenResourceError), which is unhandled and crashes the stateless session with an ExceptionGroup. Wrap the send_log_message() call in a try/except that catches both anyio.ClosedResourceError and anyio.BrokenResourceError, since failing to notify a disconnected client is expected and harmless. This is a different code path from PR #1384, which fixed the message router loop. This fix covers the _handle_post_request → _handle_message → send_log_message error recovery path. Fixes #2064 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 62575ed commit a21b714

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

src/mcp/server/lowlevel/server.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -417,11 +417,16 @@ async def _handle_message(
417417
)
418418
case Exception():
419419
logger.error(f"Received exception from stream: {message}")
420-
await session.send_log_message(
421-
level="error",
422-
data="Internal Server Error",
423-
logger="mcp.server.exception_handler",
424-
)
420+
try:
421+
await session.send_log_message(
422+
level="error",
423+
data="Internal Server Error",
424+
logger="mcp.server.exception_handler",
425+
)
426+
except (anyio.ClosedResourceError, anyio.BrokenResourceError):
427+
logger.warning(
428+
"Could not send error log to client: connection already closed"
429+
)
425430
if raise_exceptions:
426431
raise message
427432
case _:

0 commit comments

Comments
 (0)