Fix ClientSession error handling: add transport_exception_handler callback (Fixes #1401) - #3369
Fix ClientSession error handling: add transport_exception_handler callback (Fixes #1401)#3369mukktinaadh wants to merge 1 commit into
Conversation
…lback - Add new callback to ClientSession and Client for handling transport-level exceptions (timeouts, connection errors) - Update to use the new handler with fallback to for backwards compatibility - Make default log transport exceptions at ERROR level - Add tests for the new callback and fallback behavior Fixes modelcontextprotocol#1401
|
Thanks for the contribution. This repository only keeps pull requests open when they're linked to an issue that a maintainer has assigned to the author — CONTRIBUTING.md explains why and how we work. This PR has been closed for now because its description doesn't yet link an open issue in this repository (with If there isn't an issue for this yet, please open one — a clear description of the problem is genuinely the most useful thing for us. Then add There's no need to open a new PR — this one will be reopened. While it's closed, please push any updates as new commits rather than force-pushing, since GitHub can't reopen a PR whose branch has been rewritten. Maintainers: reopening this PR, removing the |
Summary
This PR addresses issue #1401 by adding a dedicated
transport_exception_handlercallback toClientSessionandClientclasses. This allows users to properly handle transport-level exceptions (timeouts, connection errors, etc.) instead of having them silently swallowed by the defaultmessage_handler.Changes
Core Changes (
src/mcp/client/session.py)TransportExceptionHandlerFnTprotocol for the callback typetransport_exception_handlerparameter toClientSession.__init___deliver_stream_exceptionto use the new handler with fallback tomessage_handlerfor backwards compatibility_default_message_handlerto log transport exceptions at ERROR level (so users are aware of issues even without a custom handler)Client Integration (
src/mcp/client/client.py)transport_exception_handlerfield toClientdataclass_build_sessionto pass the handler toClientSessionTests (
tests/client/test_session.py)test_transport_exception_handler_receives_exceptions_separately_from_message_handler: verifies transport exceptions go to the dedicated handler while server notifications go tomessage_handlertest_transport_exception_handler_fallback_to_message_handler: verifies backwards compatibility when no dedicated handler is providedUsage Example
Backwards Compatibility
message_handlercontinues to work unchangedtransport_exception_handleris provided, transport exceptions fall back tomessage_handlermessage_handlernow logs transport exceptions at ERROR levelTesting
All existing tests pass (5744 tests). Two new tests added for the new functionality.