python-sdk
python-sdk copied to clipboard
Improve exception handling for ClientDisconnect errors
Fix: Handle ClientDisconnect gracefully (return 499, not 500)
Problem
ClientDisconnect exceptions are currently handled incorrectly in StreamableHTTPServerTransport._handle_post_request:
- Returns HTTP 500 (Internal Server Error)
- Logs as ERROR with full traceback
- Triggers production 5XX alerts
ClientDisconnect occurs during normal operations when clients disconnect mid-request due to:
- Network timeouts
- User cancellations
- Load balancer timeouts
- Mobile network interruptions
These are client-side events, not server failures, and should not be treated as server errors.
Root Cause
The broad except Exception handler in _handle_post_request catches ClientDisconnect before it can be handled appropriately, resulting in incorrect error logging and HTTP status codes.
File: src/mcp/server/streamable_http.py (lines ~490-500)
Solution
This PR adds a specific ClientDisconnect exception handler before the broad Exception handler:
- Catches
ClientDisconnectexplicitly - Returns HTTP 499 (Client Closed Request) instead of 500
- Logs as INFO instead of ERROR
- Follows the same pattern as other 4xx responses in the file