π The fast, Pythonic way to build MCP servers and clients.
fix(tasks): retain results after tool removal (#5507)
mika711575a7acd1
diff --git a/fastmcp_tasks/fastmcp_tasks/components.py b/fastmcp_tasks/fastmcp_tasks/components.pyindex f4e6d3c22..61aa690e9 100644--- a/fastmcp_tasks/fastmcp_tasks/components.py+++ b/fastmcp_tasks/fastmcp_tasks/components.py@@ -22,10 +22,13 @@ because core still declares them.from __future__ import annotations+import functoolsimport inspectimport logging+from collections.abc import Awaitable, Callablefrom typing import TYPE_CHECKING, Any+import mcp_typesfrom pydantic import ValidationError as PydanticValidationErrorfrom fastmcp.exceptions import ValidationError@@ -34,7 +37,7 @@ from fastmcp.prompts.function_prompt import FunctionPromptfrom fastmcp.resources.base import Resourcefrom fastmcp.resources.function_resource import FunctionResourcefrom fastmcp.resources.template import FunctionResourceTemplate, ResourceTemplate-from fastmcp.tools.base import Tool+from fastmcp.tools.base import InputRequiredToolResult, Tool, ToolResultfrom fastmcp.tools.function_tool import (FunctionTool,_resolve_param_hints,@@ -42,14 +45,69 @@ from fastmcp.tools.function_tool import ()from fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.types import get_cached_typeadapter-from fastmcp_tasks.input_loop import reentrant_task_fn+from fastmcp_tasks.input_loop import _error_result, reentrant_task_fnif TYPE_CHECKING:- from collections.abc import Callable-from docket import Docketfrom docket.execution import Execution+logger = logging.getLogger(__name__)++TASK_RESULT_ENVELOPE_KEY = "__fastmcp_task_result__"+++def task_result_to_wire(tool: Tool, raw_value: Any) -> dict[str, Any]:+ """Convert a task's return value into an inlined `CallToolResult` dict.++ A raised tool error arrives as the `is_error` `ToolResult` the reentrant+ wrapper built, so it is used directly and `isError` round-trips. A normal+ return goes through the tool's own result coercion.+ """+ if isinstance(raw_value, ToolResult):+ mcp_result = raw_value.to_mcp_result()+ else:+ mcp_result = tool.convert_result(raw_value).to_mcp_result()+ if isinstance(mcp_result, mcp_types.CallToolResult):+ call_result = mcp_result+ elif isinstance(mcp_result, tuple):+ content, structured_content = mcp_result+ call_result = mcp_types.CallToolResult(+ content=content, structured_content=structured_content+ )+ else:+ call_result = mcp_types.CallToolResult(content=mcp_result)+ return call_result.model_dump(by_alias=True, mode="json", exclude_none=True)+++def _store_task_result_with_component(+ tool: Tool, fn: Callable[..., Awaitable[Any]]+) -> Callable[..., Awaitable[Any]]:+ """Persist the protocol result so later polling does not need the live Tool.++ The conversion runs in the worker, under the same masking policy as a+ raised tool error: a return value that fails to serialize becomes a masked+ `is_error` result rather than a failed task carrying the exception text.+ """++ @functools.wraps(fn)+ async def wrapper(*args: Any, **kwargs: Any) -> Any:+ result = await fn(*args, **kwargs)+ if isinstance(result, mcp_types.InputRequiredResult | InputRequiredToolResult):+ # Preserve the existing defensive failure in tasks_get for a guard+ # result that escaped the end-and-reenter loop.+ return result+ try:+ wire = task_result_to_wire(tool, result)+ except Exception as exc:+ logger.exception(+ "background task tool %r result conversion failed", tool.name+ )+ wire = task_result_to_wire(tool, _error_result(tool.name, exc))+ return {TASK_RESULT_ENVELOPE_KEY: wire}++ wrapper.__signature__ = inspect.signature(fn) # ty: ignore[unresolved-attribute]+ return wrapper+def register_component_with_docket(component: FastMCPComponent, docket: Docket) -> None:"""Register a component's callable with Docket for background execution.@@ -66,16 +124,20 @@ def register_component_with_docket(component: FastMCPComponent, docket: Docket)# InputRequiredResult drives the reentrant in-task input cycle. The# wrapper is signature-preserving, so Docket's dependency injection is# unchanged for a body that never asks for input.+ task_fn = reentrant_task_fn(component.fn, component.name)docket.register(- reentrant_task_fn(component.fn, component.name), names=[component.key]+ _store_task_result_with_component(component, task_fn),+ names=[component.key],)elif isinstance(component, Tool):# 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.+ task_fn = reentrant_task_fn(component.run, component.name)docket.register(- reentrant_task_fn(component.run, component.name), names=[component.key]+ _store_task_result_with_component(component, task_fn),+ names=[component.key],)elif isinstance(component, FunctionResource):docket.register(component.fn, names=[component.key])diff --git a/fastmcp_tasks/fastmcp_tasks/handlers.py b/fastmcp_tasks/fastmcp_tasks/handlers.pyindex 1029a4a43..eca6317a4 100644--- a/fastmcp_tasks/fastmcp_tasks/handlers.py+++ b/fastmcp_tasks/fastmcp_tasks/handlers.py@@ -29,9 +29,10 @@ from mcp.shared.exceptions import MCPErrorfrom mcp_types import INVALID_PARAMSfrom fastmcp.exceptions import NotFoundError-from fastmcp.tools.base import InputRequiredToolResult, Tool, ToolResult+from fastmcp.tools.base import InputRequiredToolResult, Toolfrom fastmcp.utilities.tasks import DEFAULT_POLL_INTERVAL_MSfrom fastmcp.utilities.versions import VersionSpec+from fastmcp_tasks.components import TASK_RESULT_ENVELOPE_KEY, task_result_to_wirefrom fastmcp_tasks.context import get_task_scope, refresh_snapshot_ttlfrom fastmcp_tasks.creation import (TASK_MAPPING_TTL_BUFFER_SECONDS,@@ -228,23 +229,7 @@ def _inline_result(tool: Tool, raw_value: Any) -> dict[str, Any]:"Guard-pattern tasks are supported for function tools."),)- # A raised tool error arrives as an is_error ToolResult the wrapper built- # (end-and-reenter G2); use it directly so isError round-trips. A normal- # return is converted through the tool's own result coercion.- if isinstance(raw_value, ToolResult):- mcp_result = raw_value.to_mcp_result()- else:- mcp_result = tool.convert_result(raw_value).to_mcp_result()- if isinstance(mcp_result, mcp_types.CallToolResult):- call_tool_result = mcp_result- elif isinstance(mcp_result, tuple):- content, structured_content = mcp_result- call_tool_result = mcp_types.CallToolResult(- content=content, structured_content=structured_content- )- else:- call_tool_result = mcp_types.CallToolResult(content=mcp_result)- return call_tool_result.model_dump(by_alias=True, mode="json", exclude_none=True)+ return task_result_to_wire(tool, raw_value)async def tasks_get(server: FastMCP, task_id: str) -> GetTaskResult:@@ -299,8 +284,17 @@ async def tasks_get(server: FastMCP, task_id: str) -> GetTaskResult:if outstanding:return build("input_required", input_requests=outstanding)raw_value = await execution.get_result(timeout=timedelta(seconds=0))- tool = await _resolve_tool(server, base_task_key)- return build("completed", result=_inline_result(tool, raw_value))+ if isinstance(raw_value, dict) and TASK_RESULT_ENVELOPE_KEY in raw_value:+ # New executions persist the converted protocol result alongside+ # the Docket result. Polling therefore remains possible after a+ # dynamic provider removes the Tool that produced it.+ result = raw_value[TASK_RESULT_ENVELOPE_KEY]+ else:+ # Retain compatibility with tasks created before this envelope was+ # introduced; their Docket result still needs the live Tool schema.+ tool = await _resolve_tool(server, base_task_key)+ result = _inline_result(tool, raw_value)+ return build("completed", result=result)if execution.state == ExecutionState.FAILED:message = "Task failed"diff --git a/tests/tasks/server/test_task_result_persistence.py b/tests/tasks/server/test_task_result_persistence.pynew file mode 100644index 000000000..58382fbd6--- /dev/null+++ b/tests/tasks/server/test_task_result_persistence.py@@ -0,0 +1,61 @@+"""A completed task's result is converted in the worker and stored with it.++`tasks/get` must keep returning the result after the producing tool is removed,+and a return value that fails to serialize must respect the server's masking+policy rather than surface its exception text.+"""++from pydantic import BaseModel, field_serializer++from fastmcp import FastMCP+from fastmcp_tasks import TasksExtension+from tests.tasks.task_helpers import get_task, run_task, running_task_server+++async def test_completed_result_survives_tool_removal():+ mcp = FastMCP("removal-server")+ mcp.add_extension(TasksExtension())++ @mcp.tool(task=True)+ async def removable_tool() -> str:+ return "done"++ async with running_task_server(mcp):+ final = await run_task(mcp, "removable_tool", {})+ assert final.status == "completed"++ mcp.local_provider.remove_tool("removable_tool")+ after = await get_task(mcp, final.task_id)++ assert after.status == "completed"+ assert after.result is not None+ assert after.result["content"][0]["text"] == "done"+++class Unserializable(BaseModel):+ value: int++ @field_serializer("value")+ def _fail(self, value: int) -> int:+ raise ValueError("synthetic serialization failure")+++async def test_result_conversion_failure_is_masked():+ mcp = FastMCP("mask-server", mask_error_details=True)+ mcp.add_extension(TasksExtension())++ @mcp.tool(task=True)+ async def bad_result() -> Unserializable:+ return Unserializable(value=1)++ async with running_task_server(mcp):+ final = await run_task(mcp, "bad_result", {})++ assert final.status == "completed"+ assert final.error is None+ assert final.status_message is None+ assert final.result is not None+ assert final.result["isError"] is True+ text = final.result["content"][0]["text"]+ assert "synthetic serialization failure" not in text+ assert "Error calling tool 'bad_result'" in text