π The fast, Pythonic way to build MCP servers and clients.
Preserve tool-body timeout errors (#5940)
Wilson_Jiangbfe314ff2d2a
diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.pyindex 34ac102a8..872d31310 100644--- a/fastmcp_slim/fastmcp/tools/function_tool.py+++ b/fastmcp_slim/fastmcp/tools/function_tool.py@@ -470,6 +470,7 @@ class FunctionTool(Tool):"""Validate arguments and execute the body, applying any timeout."""try:if self.timeout is not None:+ scope = Nonetry:with anyio.fail_after(self.timeout) as scope:result = await self._execute(@@ -480,6 +481,11 @@ class FunctionTool(Tool):if anyio.current_time() >= scope.deadline:raise TimeoutErrorexcept TimeoutError:+ if scope is None or (+ not scope.cancelled_caught+ and anyio.current_time() < scope.deadline+ ):+ raiselogger.warning(f"Tool '{self.name}' timed out after {self.timeout}s. "f"Consider using task=True for long-running operations. "diff --git a/tests/tools/test_tool_timeout.py b/tests/tools/test_tool_timeout.pyindex 91241c973..657a1c14e 100644--- a/tests/tools/test_tool_timeout.py+++ b/tests/tools/test_tool_timeout.py@@ -8,7 +8,7 @@ import pytestfrom mcp.shared.exceptions import MCPErrorfrom mcp_types import TextContent-from fastmcp import FastMCP+from fastmcp import Client, FastMCPfrom fastmcp.dependencies import Dependsfrom fastmcp.exceptions import ToolErrorfrom fastmcp.tools import Tool@@ -224,3 +224,73 @@ class TestToolTimeout:# TimeoutError should be caught and converted to ToolErrorwith pytest.raises((ToolError, MCPError)):await mcp.call_tool("times_out")++ @pytest.mark.parametrize("timeout", [None, 30.0])+ @pytest.mark.parametrize("is_async", [True, False])+ async def test_body_raised_timeout_error_is_not_reported_as_deadline(+ self, timeout: float | None, is_async: bool+ ):+ """A TimeoutError raised by the tool body itself (e.g. socket.timeout)+ must surface as the tool's own error, not as the deadline firing."""+ mcp = FastMCP()++ error = TimeoutError("upstream socket timed out")++ async def async_upstream_timeout() -> str:+ raise error++ def sync_upstream_timeout() -> str:+ raise error++ fn = async_upstream_timeout if is_async else sync_upstream_timeout+ tool = Tool.from_function(fn, name="upstream_timeout", timeout=timeout)+ mcp.add_tool(tool)++ with pytest.raises(TimeoutError) as original:+ await tool.run({})+ assert original.value is error++ with pytest.raises(ToolError) as exc_info:+ await mcp.call_tool("upstream_timeout")++ assert "timed out after" not in str(exc_info.value)+ assert "upstream socket timed out" in str(exc_info.value)++ @pytest.mark.parametrize("mode", ["auto", "legacy"])+ async def test_body_timeout_over_protocol(self, mode):+ mcp = FastMCP()++ @mcp.tool(timeout=30.0)+ async def upstream_timeout() -> str:+ raise TimeoutError("upstream socket timed out")++ async with Client(mcp, mode=mode) as client:+ result = await client.call_tool("upstream_timeout", raise_on_error=False)++ assert result.is_error+ assert isinstance(result.content[0], TextContent)+ assert "upstream socket timed out" in result.content[0].text+ assert "execution timed out after" not in result.content[0].text++ async def test_inner_deadline_preserves_timeout_error(self):+ async def inner_timeout() -> str:+ with anyio.fail_after(0):+ await anyio.sleep_forever()+ return "unreachable"++ tool = Tool.from_function(inner_timeout, timeout=30.0)+ with pytest.raises(TimeoutError):+ await tool.run({})++ async def test_outer_deadline_remains_mcp_error(self):+ async def slow_tool() -> str:+ await anyio.sleep_forever()+ return "unreachable"++ tool = Tool.from_function(slow_tool, timeout=0.01)+ with pytest.raises(MCPError) as exc_info:+ await tool.run({})+ assert exc_info.value.code == -32000+ assert (+ exc_info.value.message == "Tool 'slow_tool' execution timed out after 0.01s"+ )