Skip to content

🚀 The fast, Pythonic way to build MCP servers and clients.

docs: clarify tool errors and middleware transformations (#5566)

Sora Miyawaki / 宮脇蒼空93c9e1bb6a01
diff --git a/docs/servers/middleware.mdx b/docs/servers/middleware.mdx
index 46ee4ebde..c9c34300c 100644
--- a/docs/servers/middleware.mdx
+++ b/docs/servers/middleware.mdx
@@ -535,7 +535,9 @@ mcp.add_middleware(SlidingWindowRateLimitingMiddleware(
from fastmcp.server.middleware.error_handling import ErrorHandlingMiddleware, RetryMiddleware
```
-`ErrorHandlingMiddleware` provides centralized error logging and transformation. `RetryMiddleware` automatically retries with exponential backoff for transient failures.
+`ErrorHandlingMiddleware` logs and counts exceptions that pass through it, and optionally transforms them into JSON-RPC errors. It is not required to return [tool error results](/servers/tools#error-handling). `RetryMiddleware` automatically retries with exponential backoff for transient failures.
+
+Set `transform_errors=False` to add logging and error statistics while preserving exceptions for the normal protocol handlers:
```python
from fastmcp import FastMCP
@@ -550,17 +552,30 @@ def my_error_callback(error: Exception, context: MiddlewareContext) -> None:
mcp = FastMCP("MyServer")
mcp.add_middleware(ErrorHandlingMiddleware(
include_traceback=True,
- transform_errors=True,
- error_callback=my_error_callback
+ transform_errors=False,
+ error_callback=my_error_callback,
))
```
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `include_traceback` | `bool` | `False` | Include stack traces in logs |
-| `transform_errors` | `bool` | `True` | Convert exceptions to MCP errors |
+| `transform_errors` | `bool` | `True` | Convert exceptions to JSON-RPC errors; `False` preserves the original exception |
| `error_callback` | `Callable` | `None` | Custom callback on errors |
+With the default `transform_errors=True`, existing `MCPError` instances pass through unchanged. Otherwise, the middleware maps the immediate chained cause's type, if present, or the exception's own type. Each row also matches subclasses of the listed types:
+
+| Exception type | JSON-RPC code |
+|----------------|---------------|
+| `ValueError`, `TypeError`, FastMCP `ValidationError` | `-32602` (invalid params) |
+| `FileNotFoundError`, `KeyError`, `NotFoundError` | `-32002` for `resources/*`; `-32001` otherwise |
+| `PermissionError`, `TimeoutError`, `asyncio.TimeoutError` | `-32000` |
+| Other exceptions | `-32603` (internal error) |
+
+FastMCP's `ToolError` and `AuthorizationError` have no dedicated mappings: without a mapped cause, they become `-32603`. Because the cause takes precedence, a `ToolError` chained from `ValueError` becomes `-32602`, even if that `ValueError` came from a bug inside the tool. Use `transform_errors=False` when these generic mappings do not fit your application.
+
+This middleware logs every caught exception at `ERROR`, independently of the exception's `log_level` and `transform_errors`. Its logs, the resulting protocol response, and [OpenTelemetry span status](/servers/telemetry#error-handling) are separate signals. Do not infer a JSON-RPC code or span status from the log level.
+
For automatic retries:
```python
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index e29f37742..809e57cbc 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -834,39 +834,45 @@ For reusable serialization across multiple tools, create a wrapper decorator tha
<VersionBadge version="2.4.1" />
-If your tool encounters an error, you can raise a standard Python exception (`ValueError`, `TypeError`, `FileNotFoundError`, custom exceptions, etc.) or a FastMCP `ToolError`.
+Use `ToolError` to give the LLM a message it can act on, including for expected business errors such as an invalid date range or an entity ID that does not exist. It is not reserved for server bugs.
-By default, exceptions are converted into an MCP error response to be sent back to the client LLM. This helps the LLM understand failures and react appropriately. Validation warnings identify the tool and, for Pydantic errors, include the error count and built-in error types (such as `int_parsing`). Custom error codes are reported as `custom_error`. Argument values, validation locations, and validator messages are omitted because they may contain private client data. This does not change the validation details returned to the caller or redact explicit debug logging or custom middleware logs.
+The exceptions in `fastmcp.exceptions` describe different contexts:
-If you want to mask internal error details for security reasons, you can:
+| Exception | When to use it |
+|-----------|----------------|
+| `ToolError` | A tool cannot complete its operation. Give the caller a safe, actionable message so it can correct its arguments or choose another action. |
+| `ValidationError` | Parameter or return-value validation fails. FastMCP also raises this for function-tool argument validation. This is distinct from `pydantic.ValidationError`. The protocol response for either depends on where the error is handled, as described below. |
+| `AuthorizationError` | An [authorization check](/servers/authorization) or custom middleware denies access. Component-level authorization can hide components from lookup and listing, so the result depends on where the check runs. |
+| `NotFoundError` | FastMCP component lookup fails, such as a missing tool, resource, or prompt. For a missing business entity inside a tool, use `ToolError` with a message about that entity. |
-1. Use the `mask_error_details=True` parameter when creating your `FastMCP` instance:
-```python
-mcp = FastMCP(name="SecureServer", mask_error_details=True)
-```
+With default error handling, `ToolError`, FastMCP's `ValidationError`, and `AuthorizationError` reaching the `tools/call` handler become a tool result with `isError: true`. This is a JSON-RPC **result** describing a failed tool call, distinct from a JSON-RPC **error** with a numeric code. Other operations and [error-handling middleware](/servers/middleware#error-handling) have their own mappings; changing the exception class alone does not select a wire error code.
+
+Set `mask_error_details=True` to mask ordinary exceptions raised during tool execution. Explicit FastMCP errors such as `ToolError` and `ValidationError` keep their messages, so those messages must be safe to send to the caller. For example, this tool exposes an actionable date-range error while masking unexpected internal failures:
-2. Or use `ToolError` to explicitly control what error information is sent to clients:
```python
+import logging
+from datetime import date
+
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
+mcp = FastMCP("DateTools", mask_error_details=True)
+
+
@mcp.tool
-def divide(a: float, b: float) -> float:
- """Divide a by b."""
-
- if b == 0:
- # Error messages from ToolError are always sent to clients,
- # regardless of mask_error_details setting
- raise ToolError("Division by zero is not allowed.")
-
- # If mask_error_details=True, this message would be masked
- if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
- raise TypeError("Both arguments must be numbers.")
-
- return a / b
+def count_days(start_date: date, end_date: date) -> int:
+ """Count the days in a date range."""
+ if start_date >= end_date:
+ raise ToolError(
+ "start_date must be before end_date. Please correct the date range.",
+ log_level=logging.WARNING,
+ )
+ return (end_date - start_date).days
```
-When `mask_error_details=True`, only error messages from `ToolError` will include details, other exceptions will be converted to a generic message.
+The `log_level` argument controls the tool-execution log entry for `ToolError` (default: `logging.ERROR`). FastMCP's `ValidationError` is logged at `WARNING` during tool execution. Validation warnings identify the tool and, for Pydantic errors, include the error count and built-in error types (such as `int_parsing`). Custom error codes are reported as `custom_error`. Argument values, validation locations, and validator messages are omitted because they may contain private client data. This does not change the validation details returned to the caller or redact explicit debug logging or custom middleware logs.
+
+Log severity, MCP responses, and trace status are separate. Exceptions propagating through a recorded FastMCP server span mark it `ERROR`, as described in [Telemetry error handling](/servers/telemetry#error-handling). Lowering `log_level` changes logging, not this span handling. External dashboards may apply their own classification.
## Timeouts