Skip to content

fix: handle ClientDisconnect gracefully instead of returning HTTP 500#2161

Closed
giulio-leone wants to merge 3 commits intomodelcontextprotocol:mainfrom
giulio-leone:fix/client-disconnect-http-500
Closed

fix: handle ClientDisconnect gracefully instead of returning HTTP 500#2161
giulio-leone wants to merge 3 commits intomodelcontextprotocol:mainfrom
giulio-leone:fix/client-disconnect-http-500

Conversation

@giulio-leone
Copy link

Summary

Fixes #1648

ClientDisconnect is raised by Starlette when a client disconnects mid-request (network timeouts, user cancellation, load balancer timeouts). This is a normal client-side event, not a server failure.

Problem

The broad except Exception handler in _handle_post_request catches ClientDisconnect and:

  • Logs it as ERROR with full traceback
  • Returns HTTP 500 Internal Server Error
  • Triggers false 5XX alerts in production monitoring

Fix

Catch ClientDisconnect before the generic except Exception handler:

  • Log at INFO level (this is an expected operational event)
  • Return early without sending a response (the client is already gone)
  • Properly clean up by notifying the writer about the disconnection

Test Results

475 server tests pass (2 consecutive clean runs).

ClientDisconnect is raised by Starlette when a client disconnects
mid-request (network timeouts, user cancellation, load balancer
timeouts). This is a normal client-side event, not a server failure.

Previously, the broad 'except Exception' handler in
_handle_post_request caught ClientDisconnect and:
- Logged it as ERROR with full traceback
- Returned HTTP 500 Internal Server Error
- Triggered false 5XX alerts in production

Now ClientDisconnect is caught before the generic handler and:
- Logged at INFO level (expected operational event)
- Returns early without sending a response (client is gone)
- Properly cleans up by notifying the writer

Fixes modelcontextprotocol#1648
@giulio-leone giulio-leone force-pushed the fix/client-disconnect-http-500 branch from 6a76777 to 4f3c799 Compare February 28, 2026 14:41
…educe complexity

Reduces C901 complexity of _handle_post_request from 26 to within
the limit by extracting JSON-RPC body parsing and session validation
into dedicated helper methods.
@giulio-leone
Copy link
Author

Closing to reduce noise — focusing on the most impactful PRs. Happy to reopen if there's interest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ClientDisconnect returns HTTP 500

1 participant