Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

fix: check the cause of the tool error (#2674)

Rafi Olaverria820b69aa2e40
diff --git a/src/fastmcp/server/middleware/error_handling.py b/src/fastmcp/server/middleware/error_handling.py
index 7cb730d90..fc0e2a1c8 100644
--- a/src/fastmcp/server/middleware/error_handling.py
+++ b/src/fastmcp/server/middleware/error_handling.py
@@ -87,7 +87,7 @@ class ErrorHandlingMiddleware(Middleware):
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(
diff --git a/tests/server/middleware/test_error_handling.py b/tests/server/middleware/test_error_handling.py
index 1ed534709..7da8c3119 100644
--- a/tests/server/middleware/test_error_handling.py
+++ b/tests/server/middleware/test_error_handling.py
@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, MagicMock
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,
@@ -215,6 +215,23 @@ class TestErrorHandlingMiddleware:
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()