-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Handles message type Exception in lowlevel/server.py _handle_message function. Mentioned as TODO on line 528. #786
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
felixweinberger
merged 13 commits into
modelcontextprotocol:main
from
AishwaryaKalloli:main
Oct 13, 2025
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
db77e60
Handling TODO mentioned in the lowlevel/server.py.
AishwaryaKalloli ce28969
lint fix
AishwaryaKalloli 39220b0
fix: Improve exception handling in lowlevel server
felixweinberger 1934a58
Address kludex review comments - use __exit__ format for exception data
felixweinberger df6e820
Fix type annotations in test_lowlevel_exception_handling.py
felixweinberger 904294e
Remove unused Type import
felixweinberger e713784
Merge branch 'main' into main
felixweinberger 81335fb
fix: avoid exposing server exception details to clients
felixweinberger c9368c1
Merge branch 'main' into main
felixweinberger d6fba2b
fix: amend ordering to always send log message
felixweinberger 2fa2f67
fix: update tests to reflect logging
felixweinberger ebafcbe
Merge branch 'main' into main
felixweinberger c5b35bd
Merge branch 'main' into main
felixweinberger File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
from unittest.mock import AsyncMock, Mock | ||
|
||
import pytest | ||
|
||
import mcp.types as types | ||
from mcp.server.lowlevel.server import Server | ||
from mcp.server.session import ServerSession | ||
from mcp.shared.session import RequestResponder | ||
|
||
|
||
@pytest.mark.anyio | ||
async def test_exception_handling_with_raise_exceptions_true(): | ||
"""Test that exceptions are re-raised when raise_exceptions=True""" | ||
server = Server("test-server") | ||
session = Mock(spec=ServerSession) | ||
session.send_log_message = AsyncMock() | ||
|
||
test_exception = RuntimeError("Test error") | ||
|
||
with pytest.raises(RuntimeError, match="Test error"): | ||
await server._handle_message(test_exception, session, {}, raise_exceptions=True) | ||
|
||
session.send_log_message.assert_called_once() | ||
|
||
|
||
@pytest.mark.anyio | ||
@pytest.mark.parametrize( | ||
"exception_class,message", | ||
[ | ||
(ValueError, "Test validation error"), | ||
(RuntimeError, "Test runtime error"), | ||
(KeyError, "Test key error"), | ||
(Exception, "Basic error"), | ||
], | ||
) | ||
async def test_exception_handling_with_raise_exceptions_false(exception_class: type[Exception], message: str): | ||
"""Test that exceptions are logged when raise_exceptions=False""" | ||
server = Server("test-server") | ||
session = Mock(spec=ServerSession) | ||
session.send_log_message = AsyncMock() | ||
|
||
test_exception = exception_class(message) | ||
|
||
await server._handle_message(test_exception, session, {}, raise_exceptions=False) | ||
|
||
# Should send log message | ||
session.send_log_message.assert_called_once() | ||
call_args = session.send_log_message.call_args | ||
|
||
assert call_args.kwargs["level"] == "error" | ||
assert call_args.kwargs["data"] == "Internal Server Error" | ||
assert call_args.kwargs["logger"] == "mcp.server.exception_handler" | ||
|
||
|
||
@pytest.mark.anyio | ||
async def test_normal_message_handling_not_affected(): | ||
"""Test that normal messages still work correctly""" | ||
server = Server("test-server") | ||
session = Mock(spec=ServerSession) | ||
|
||
# Create a mock RequestResponder | ||
responder = Mock(spec=RequestResponder) | ||
responder.request = types.ClientRequest(root=types.PingRequest(method="ping")) | ||
responder.__enter__ = Mock(return_value=responder) | ||
responder.__exit__ = Mock(return_value=None) | ||
|
||
# Mock the _handle_request method to avoid complex setup | ||
server._handle_request = AsyncMock() | ||
|
||
# Should handle normally without any exception handling | ||
await server._handle_message(responder, session, {}, raise_exceptions=False) | ||
|
||
# Verify _handle_request was called | ||
server._handle_request.assert_called_once() |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.