π The fast, Pythonic way to build MCP servers and clients.
fix(middleware): map exception subclasses in ErrorHandlingMiddleware (#6257)
nate nowack28e5e39742c5
diff --git a/fastmcp_slim/fastmcp/server/middleware/error_handling.py b/fastmcp_slim/fastmcp/server/middleware/error_handling.pyindex 729c927c4..e0727c3de 100644--- a/fastmcp_slim/fastmcp/server/middleware/error_handling.py+++ b/fastmcp_slim/fastmcp/server/middleware/error_handling.py@@ -87,21 +87,22 @@ class ErrorHandlingMiddleware(Middleware):if not self.transform_errors:return error- # Map common exceptions to appropriate MCP error codes+ # Map common exceptions to appropriate MCP error codes. Match subclasses+ # too: pydantic's ValidationError, for one, is a ValueError.error_type = type(error.__cause__) if error.__cause__ else type(error)- if error_type in (ValueError, TypeError, ValidationError):+ if issubclass(error_type, (ValueError, TypeError, ValidationError)):return MCPError(code=-32602, message=f"Invalid params: {error!s}")- elif error_type in (FileNotFoundError, KeyError, NotFoundError):+ elif issubclass(error_type, (FileNotFoundError, KeyError, NotFoundError)):# MCP spec defines -32002 specifically for resource not foundmethod = context.method or ""if method.startswith("resources/"):return MCPError(code=-32002, message=f"Resource not found: {error!s}")return MCPError(code=-32001, message=f"Not found: {error!s}")- elif error_type is PermissionError:+ elif issubclass(error_type, PermissionError):return MCPError(code=-32000, message=f"Permission denied: {error!s}")# asyncio.TimeoutError is a subclass of TimeoutError in Python 3.10, alias in 3.11+- elif error_type in (TimeoutError, asyncio.TimeoutError):+ elif issubclass(error_type, (TimeoutError, asyncio.TimeoutError)):return MCPError(code=-32000, message=f"Request timeout: {error!s}")else:return MCPError(code=-32603, message=f"Internal error: {error!s}")diff --git a/tests/server/middleware/test_error_handling.py b/tests/server/middleware/test_error_handling.pyindex c6bca0b8d..0fb26ad19 100644--- a/tests/server/middleware/test_error_handling.py+++ b/tests/server/middleware/test_error_handling.py@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMockimport pytestfrom mcp import MCPErrorfrom mcp_types import TextContent+from pydantic import BaseModel, model_validatorfrom fastmcp import FastMCPfrom fastmcp.client import Client@@ -135,6 +136,25 @@ class TestErrorHandlingMiddleware:assert result.error.code == -32602assert "Invalid params: test error" in result.error.message+ def test_transform_error_classifies_subclasses(self, mock_context):+ """Subclasses of a mapped exception get that exception's code."""++ class Unreadable(UnicodeDecodeError):+ pass++ middleware = ErrorHandlingMiddleware()+ cases: list[tuple[Exception, int]] = [+ (UnicodeDecodeError("utf-8", b"\xff", 0, 1, "bad"), -32602),+ (Unreadable("utf-8", b"\xff", 0, 1, "bad"), -32602),+ (IsADirectoryError("dir"), -32603),+ (TimeoutError("slow"), -32000),+ ]++ for error, code in cases:+ result = middleware._transform_error(error, mock_context)+ assert isinstance(result, MCPError)+ assert result.error.code == code, error+def test_transform_error_not_found_for_resource_method(self):"""Test that not-found errors use -32002 for resource methods."""middleware = ErrorHandlingMiddleware()@@ -776,3 +796,36 @@ async def test_prompt_handler_failure_remains_internal(await client.get_prompt("summarize", {"topic": "valid"})assert exc_info.value.error.code == -32603+++class _Payload(BaseModel):+ @model_validator(mode="before")+ @classmethod+ def reject(cls, value: object) -> object:+ raise ValueError("invalid payload")++[email protected]("mode", ["auto", "legacy"])+ ("tool", "arguments"),+ [("concat", {"wrong": "x"}), ("submit", {"payload": {}})],+)+async def test_tool_argument_validation_maps_to_invalid_params(+ mode: Literal["auto", "legacy"], tool: str, arguments: dict[str, object]+) -> None:+ server = FastMCP(middleware=[ErrorHandlingMiddleware()])++ @server.tool+ def concat(a: str, b: str) -> str:+ return a + b++ @server.tool+ def submit(payload: _Payload) -> str:+ return "ok"++ async with Client(server, mode=mode) as client:+ with pytest.raises(MCPError) as exc_info:+ await client.call_tool(tool, arguments)++ assert exc_info.value.error.code == -32602+ assert exc_info.value.error.message.startswith("Invalid params:")