Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/fastmcp/server/middleware/error_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def _transform_error(self, error: Exception) -> Exception:
return error

# Map common exceptions to appropriate MCP error codes
error_type = type(error)
error_type = type(error.__cause__) if error.__cause__ else type(error)

if error_type in (ValueError, TypeError):
return McpError(
Expand Down
19 changes: 18 additions & 1 deletion tests/server/middleware/test_error_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import pytest
from mcp import McpError

from fastmcp.exceptions import NotFoundError
from fastmcp.exceptions import NotFoundError, ToolError
from fastmcp.server.middleware.error_handling import (
ErrorHandlingMiddleware,
RetryMiddleware,
Expand Down Expand Up @@ -215,6 +215,23 @@ async def test_on_message_error_transform(self, mock_context, caplog):
assert "Invalid params: test error" in exc_info.value.error.message
assert "Error in test_method: ValueError: test error" in caplog.text

async def test_on_message_error_transform_tool_error(self, mock_context, caplog):
"""Test error handling with transformation and cause type."""
middleware = ErrorHandlingMiddleware()
tool_error = ToolError("test error")
tool_error.__cause__ = ValueError()
mock_call_next = AsyncMock(side_effect=tool_error)

with caplog_for_fastmcp(caplog):
with caplog.at_level(logging.ERROR):
with pytest.raises(McpError) as exc_info:
await middleware.on_message(mock_context, mock_call_next)

assert isinstance(exc_info.value, McpError)
assert exc_info.value.error.code == -32602
assert "Invalid params: test error" in exc_info.value.error.message
assert "Error in test_method: ToolError: test error" in caplog.text

def test_get_error_stats(self, mock_context):
"""Test getting error statistics."""
middleware = ErrorHandlingMiddleware()
Expand Down
Loading