π The fast, Pythonic way to build MCP servers and clients.
Add @handle_tool_errors decorator for standardized error handling (#2885)
Diogo Santosb776089ecc06
diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.pyindex 1172793c9..27494f706 100644--- a/src/fastmcp/server/server.py+++ b/src/fastmcp/server/server.py@@ -1095,6 +1095,18 @@ class FastMCP(raiseexcept Exception as e:logger.exception(f"Error calling tool {name!r}")+ # Handle actionable errors that should reach the LLM+ # even when masking is enabled+ if isinstance(e, httpx.HTTPStatusError):+ if e.response.status_code == 429:+ raise ToolError(+ "Rate limited by upstream API, please retry later"+ ) from e+ if isinstance(e, httpx.TimeoutException):+ raise ToolError(+ "Upstream request timed out, please retry"+ ) from e+ # Standard masking logicif self._mask_error_details:raise ToolError(f"Error calling tool {name!r}") from eraise ToolError(f"Error calling tool {name!r}: {e}") from e@@ -1198,6 +1210,17 @@ class FastMCP(raiseexcept Exception as e:logger.exception(f"Error reading resource {uri!r}")+ # Handle actionable errors that should reach the LLM+ if isinstance(e, httpx.HTTPStatusError):+ if e.response.status_code == 429:+ raise ResourceError(+ "Rate limited by upstream API, please retry later"+ ) from e+ if isinstance(e, httpx.TimeoutException):+ raise ResourceError(+ "Upstream request timed out, please retry"+ ) from e+ # Standard masking logicif self._mask_error_details:raise ResourceError(f"Error reading resource {uri!r}"@@ -1226,6 +1249,17 @@ class FastMCP(raiseexcept Exception as e:logger.exception(f"Error reading resource {uri!r}")+ # Handle actionable errors that should reach the LLM+ if isinstance(e, httpx.HTTPStatusError):+ if e.response.status_code == 429:+ raise ResourceError(+ "Rate limited by upstream API, please retry later"+ ) from e+ if isinstance(e, httpx.TimeoutException):+ raise ResourceError(+ "Upstream request timed out, please retry"+ ) from e+ # Standard masking logicif self._mask_error_details:raise ResourceError(f"Error reading resource {uri!r}") from eraise ResourceError(f"Error reading resource {uri!r}: {e}") from e