Skip to content

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

fix(tools): reject results returned after timeout deadlines (#5379)

HootRock3e445e0803f0
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index fb06ddb63..6c487ad14 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -849,7 +849,7 @@ When `mask_error_details=True`, only error messages from `ToolError` will includ
<VersionBadge version="3.0.0" />
-Tools can specify a `timeout` parameter to limit how long execution can take. When the timeout is exceeded, the client receives an MCP error and the tool stops processing. This protects your server from unexpectedly slow operations that could block resources or leave clients waiting indefinitely.
+Tools can specify a `timeout` parameter to reject operations that take too long. When the timeout is exceeded, the client receives an MCP error instead of the tool's result.
```python
from fastmcp import FastMCP
@@ -866,6 +866,10 @@ async def fetch_data(url: str) -> dict:
Timeouts are specified in seconds as a float. When a tool exceeds its timeout, FastMCP returns an MCP error with code `-32000` and a message indicating which tool timed out and how long it ran. Both sync and async tools support timeouts—sync functions run in thread pools, so the timeout applies to the entire operation regardless of execution model.
+<Note>
+Async tools are cancelled at their next cancellation checkpoint. Synchronous worker threads cannot be interrupted: FastMCP waits for the worker to finish before returning the timeout error, keeping its dependencies available until then. A timeout does not undo side effects or stop a synchronous tool that never returns.
+</Note>
+
<Note>
Tools must explicitly opt-in to timeouts. There is no server-level default timeout setting.
</Note>
diff --git a/fastmcp_slim/fastmcp/tools/function_tool.py b/fastmcp_slim/fastmcp/tools/function_tool.py
index 3444cff4d..39aaf2bf9 100644
--- a/fastmcp_slim/fastmcp/tools/function_tool.py
+++ b/fastmcp_slim/fastmcp/tools/function_tool.py
@@ -424,10 +424,14 @@ class FunctionTool(Tool):
try:
if self.timeout is not None:
try:
- with anyio.fail_after(self.timeout):
+ with anyio.fail_after(self.timeout) as scope:
result = await self._execute(
type_adapter, exec_is_async, arguments, strict=strict
)
+ # Worker threads shield cancellation until they finish.
+ # Reject their result if execution outlasted the deadline.
+ if anyio.current_time() >= scope.deadline:
+ raise TimeoutError
except TimeoutError:
logger.warning(
f"Tool '{self.name}' timed out after {self.timeout}s. "
diff --git a/tests/tools/test_tool_timeout.py b/tests/tools/test_tool_timeout.py
index 43532cbee..91241c973 100644
--- a/tests/tools/test_tool_timeout.py
+++ b/tests/tools/test_tool_timeout.py
@@ -1,6 +1,7 @@
"""Tests for tool timeout functionality."""
import time
+from contextlib import asynccontextmanager
import anyio
import pytest
@@ -8,7 +9,9 @@ from mcp.shared.exceptions import MCPError
from mcp_types import TextContent
from fastmcp import FastMCP
+from fastmcp.dependencies import Depends
from fastmcp.exceptions import ToolError
+from fastmcp.tools import Tool
class TestToolTimeout:
@@ -83,13 +86,44 @@ class TestToolTimeout:
assert exc_info.value is not None
async def test_sync_timeout_exceeded(self):
- """Sync tool timeout works with CPU-bound operations."""
- pytest.skip(
- "Sync timeouts require thread pool execution (coming in future commit)"
- )
- # Note: time.sleep() blocks the event loop and cannot be interrupted
- # by anyio.fail_after(). This will work once sync functions run in
- # thread pools (commit 8c471a49).
+ """A sync result returned after the deadline is a timeout error."""
+
+ def slow_sync_tool() -> str:
+ time.sleep(0.1)
+ return "late result"
+
+ tool = Tool.from_function(slow_sync_tool, timeout=0.01)
+
+ with pytest.raises(MCPError) as exc_info:
+ await tool.run({})
+
+ assert exc_info.value.code == -32000
+ assert "slow_sync_tool" in exc_info.value.message
+
+ async def test_sync_timeout_preserves_dependency_lifetime(self):
+ """Dependencies remain available until a timed-out worker finishes."""
+ mcp = FastMCP()
+ events: list[str] = []
+
+ @asynccontextmanager
+ async def resource():
+ events.append("opened")
+ try:
+ yield events
+ finally:
+ events.append("closed")
+
+ @mcp.tool(timeout=0.01)
+ def slow_sync_tool(state: list[str] = Depends(resource)) -> str:
+ state.append("started")
+ time.sleep(0.1)
+ state.append("finished")
+ return "late result"
+
+ with pytest.raises(ToolError, match="timed out"):
+ await mcp.call_tool("slow_sync_tool")
+
+ assert events == ["opened", "started", "finished", "closed"]
async def test_timeout_error_raises_tool_error(self):
"""Timeout error is converted to ToolError and logs warning."""