fix: handle ClosedResourceError when logging errors to disconnected clients#2170
Open
giulio-leone wants to merge 1 commit intomodelcontextprotocol:mainfrom
Open
Conversation
…lients Wrap send_log_message() in _handle_message's exception handler with a try/except for ClosedResourceError and BrokenResourceError. When a client disconnects during request processing, the server catches the stream exception but then crashes trying to send the error log back through the already-closed write stream. Closes modelcontextprotocol#2064 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #2064
When a client disconnects while a stateless streamable-HTTP server is processing a request, the exception handler in
_handle_messagetries tosend_log_message()back to the client. Since the session's write stream is already closed, this raisesClosedResourceError, which is unhandled and crashes the session with anExceptionGroup.Root Cause
_handle_message(lowlevel/server.py) has anExceptioncase that:session.send_log_message()to notify the client ❌ — crashes if the client is goneFix
Wrap the
send_log_message()call with a try/except foranyio.ClosedResourceErrorandanyio.BrokenResourceError. When the write stream is closed (client disconnected), the error is silently discarded with a debug log.Tests
All 475 server tests pass (2 consecutive clean runs).
ruff checkandruff formatclean.