Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Mask raised task errors regardless of ctx param

Jeremiah Lowinb75dde3b5cad
diff --git a/fastmcp_tasks/fastmcp_tasks/components.py b/fastmcp_tasks/fastmcp_tasks/components.py
index 3fb7e5f01..e1aae8df1 100644
--- a/fastmcp_tasks/fastmcp_tasks/components.py
+++ b/fastmcp_tasks/fastmcp_tasks/components.py
@@ -63,7 +63,13 @@ def register_component_with_docket(component: FastMCPComponent, docket: Docket)
reentrant_task_fn(component.fn, component.name), names=[component.key]
)
elif isinstance(component, Tool):
- docket.register(component.run, names=[component.key])
+ # Custom Tool subclasses route through the same wrapper so a raised
+ # error becomes a masked, completed `is_error` result β€” matching the
+ # synchronous `tools/call` path β€” rather than a Docket `FAILED` task
+ # that leaks the raw exception text past the server's masking policy.
+ docket.register(
+ reentrant_task_fn(component.run, component.name), names=[component.key]
+ )
elif isinstance(component, FunctionResource):
docket.register(component.fn, names=[component.key])
elif isinstance(component, FunctionResourceTemplate):
diff --git a/fastmcp_tasks/fastmcp_tasks/input_loop.py b/fastmcp_tasks/fastmcp_tasks/input_loop.py
index ff08a9439..c8a9f1740 100644
--- a/fastmcp_tasks/fastmcp_tasks/input_loop.py
+++ b/fastmcp_tasks/fastmcp_tasks/input_loop.py
@@ -84,12 +84,19 @@ def _resolve_docket() -> Docket | None:
def _mask_error_details() -> bool:
- """The worker server's error-masking policy, mirroring the sync call path."""
+ """The worker server's error-masking policy, mirroring the sync call path.
+
+ Resolves the owning server through ``get_server()`` (the worker-server
+ resolver) rather than ``get_context()``: a tool that raises without ever
+ requesting a ``ctx`` parameter has no active ``Context``, so reading the
+ policy off the context would silently fall back to the global default and
+ leak unmasked error text.
+ """
import fastmcp
- from fastmcp.server.dependencies import get_context
+ from fastmcp.server.dependencies import get_server
try:
- return get_context().fastmcp._mask_error_details
+ return get_server()._mask_error_details
except RuntimeError:
return fastmcp.settings.mask_error_details
diff --git a/tests/tasks/server/test_custom_subclass_tasks.py b/tests/tasks/server/test_custom_subclass_tasks.py
index 6c45baafb..cb9657849 100644
--- a/tests/tasks/server/test_custom_subclass_tasks.py
+++ b/tests/tasks/server/test_custom_subclass_tasks.py
@@ -17,6 +17,7 @@ from fastmcp_tasks.components import (
from fastmcp_tasks.models import CreateTaskResult
from fastmcp import FastMCP
+from fastmcp.exceptions import ToolError
from fastmcp.tools.base import Tool, ToolResult
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.tasks import TaskConfig
@@ -64,6 +65,26 @@ class CustomToolForbidden(Tool):
return ToolResult(content="Sync only")
+class CustomToolRaisesToolError(Tool):
+ """A custom tool whose `run` raises a `ToolError`."""
+
+ task_config: TaskConfig = TaskConfig(mode="optional")
+ parameters: dict[str, Any] = {"type": "object", "properties": {}}
+
+ async def run(self, arguments: dict[str, Any]) -> ToolResult:
+ raise ToolError("kaboom")
+
+
+class CustomToolRaisesValueError(Tool):
+ """A custom tool whose `run` raises a non-FastMCP exception."""
+
+ task_config: TaskConfig = TaskConfig(mode="optional")
+ parameters: dict[str, Any] = {"type": "object", "properties": {}}
+
+ async def run(self, arguments: dict[str, Any]) -> ToolResult:
+ raise ValueError("secret internal detail")
+
+
@pytest.fixture
def custom_tool_server() -> FastMCP:
"""A server with custom tool subclasses."""
@@ -124,6 +145,50 @@ async def test_custom_tool_forbidden_rejects_task(custom_tool_server):
assert "Sync only" in result.content[0].text
+async def test_custom_tool_raising_tool_error_completes_with_is_error():
+ """A custom Tool that raises `ToolError` is a completed, is_error task.
+
+ Same contract as a raising `FunctionTool`: a raised tool error is a
+ completed task carrying an `isError` result (never a `failed` task), and a
+ `ToolError` reaches the client verbatim β€” matching the synchronous path.
+ """
+ mcp = FastMCP("custom-raise-server")
+ mcp.add_extension(TasksExtension())
+ mcp.add_tool(CustomToolRaisesToolError(name="boom", description="raises"))
+
+ async with running_task_server(mcp):
+ final = await run_task(mcp, "boom", {})
+
+ assert final.status == "completed"
+ assert final.error is None
+ assert final.result is not None
+ assert final.result["isError"] is True
+ assert "kaboom" in final.result["content"][0]["text"]
+
+
+async def test_custom_tool_raising_generic_error_is_masked():
+ """A custom Tool's non-FastMCP exception is masked, like the sync path.
+
+ A base `Tool` subclass must route through the same error conversion as a
+ `FunctionTool`, so `mask_error_details=True` hides the raw exception text
+ rather than leaking it through Docket's `FAILED` outcome.
+ """
+ mcp = FastMCP("custom-mask-server", mask_error_details=True)
+ mcp.add_extension(TasksExtension())
+ mcp.add_tool(CustomToolRaisesValueError(name="leak", description="raises"))
+
+ async with running_task_server(mcp):
+ final = await run_task(mcp, "leak", {})
+
+ assert final.status == "completed"
+ assert final.error is None
+ assert final.result is not None
+ assert final.result["isError"] is True
+ text = final.result["content"][0]["text"]
+ assert "secret internal detail" not in text
+ assert "Error calling tool 'leak'" in text
+
+
async def test_custom_tool_registers_with_docket():
"""A task-capable custom tool registers its `run` entry point with Docket."""
tool = CustomTool(name="test", description="test")
diff --git a/tests/tasks/server/test_extension.py b/tests/tasks/server/test_extension.py
index eda1b557b..5260565a5 100644
--- a/tests/tasks/server/test_extension.py
+++ b/tests/tasks/server/test_extension.py
@@ -199,6 +199,33 @@ async def test_raised_tool_error_completes_with_is_error():
assert "kaboom" in final.result["content"][0]["text"]
+async def test_raised_generic_error_is_masked_without_ctx_param():
+ """A non-FastMCP exception is masked even when the tool takes no `ctx`.
+
+ Error masking is the server's `_mask_error_details` policy, which the task
+ error path must resolve through the worker-server resolver β€” not the active
+ `Context`. A tool that never requests `ctx` has no active context when it
+ raises, so a context-based lookup would silently fall back to the global
+ default and leak the raw exception text.
+ """
+ mcp = FastMCP("masked-task-server", mask_error_details=True)
+ mcp.add_extension(TasksExtension())
+
+ @mcp.tool(task=True)
+ async def leak() -> int:
+ raise ValueError("secret internal detail")
+
+ async with running_task_server(mcp):
+ final = await run_task(mcp, "leak", {})
+
+ assert final.status == "completed"
+ assert final.result is not None
+ assert final.result["isError"] is True
+ text = final.result["content"][0]["text"]
+ assert "secret internal detail" not in text
+ assert "Error calling tool 'leak'" in text
+
+
# ---------------------------------------------------------------------------
# Argument coercion parity
# ---------------------------------------------------------------------------