π The fast, Pythonic way to build MCP servers and clients.
Keep task config and execution on transformed tools (#5793)
Winorenb4c48a284b9f
diff --git a/fastmcp_slim/fastmcp/tools/tool_transform.py b/fastmcp_slim/fastmcp/tools/tool_transform.pyindex e11796dfc..85b7fd5c0 100644--- a/fastmcp_slim/fastmcp/tools/tool_transform.py+++ b/fastmcp_slim/fastmcp/tools/tool_transform.py@@ -759,6 +759,8 @@ class TransformedTool(Tool):meta=final_meta,transform_args=transform_args,auth=tool.auth,+ task_config=tool.task_config,+ execution=tool.execution,)return transformed_tooldiff --git a/fastmcp_tasks/fastmcp_tasks/components.py b/fastmcp_tasks/fastmcp_tasks/components.pyindex 61aa690e9..e1bbe4a49 100644--- a/fastmcp_tasks/fastmcp_tasks/components.py+++ b/fastmcp_tasks/fastmcp_tasks/components.py@@ -43,6 +43,7 @@ from fastmcp.tools.function_tool import (_resolve_param_hints,_validate_input,)+from fastmcp.tools.tool_transform import TransformedToolfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.types import get_cached_typeadapterfrom fastmcp_tasks.input_loop import _error_result, reentrant_task_fn@@ -221,13 +222,18 @@ def coerce_task_arguments(task's Redis metadata and initial status notification exist β otherwise acoercion failure during queueing would orphan a task the client has alreadyobserved. Only ``FunctionTool`` splats arguments into a typed Python callable- and therefore mirrors the synchronous validation path; every other component- type is a no-op passthrough.+ and therefore mirrors the synchronous validation path; ``TransformedTool`` is+ checked against its own advertised schema (see+ ``_validate_transformed_arguments``); every other component type is a no-op+ passthrough.When ``strict`` is set (server-level ``strict_input_validation``), argumentsare validated in strict mode so the task path rejects lax coercions (e.g. thestring ``"1"`` into an ``int``) exactly as the synchronous call path does."""+ if isinstance(component, TransformedTool):+ return _validate_transformed_arguments(component, arguments)+if not isinstance(component, FunctionTool):return arguments@@ -254,6 +260,55 @@ def coerce_task_arguments(return validated+def _validate_transformed_arguments(+ tool: TransformedTool,+ arguments: dict[str, Any],+) -> dict[str, Any]:+ """Reject a transformed-tool submission its own advertised schema forbids.++ A transformed tool is registered with Docket as a base ``Tool``, so the+ worker invokes ``TransformedTool.run`` β the only place its argument+ contract is enforced. Submission happens before that, so without this check+ a call the synchronous path rejects is instead persisted as a task and only+ surfaces as an ``is_error`` result once a worker picks it up.++ The checks mirror what the forwarding function performs before it runs the+ parent: unknown arguments and, after schema defaults are applied, missing+ required ones. Both are read off ``parameters``, which is the same schema+ advertised to clients, so "required" and "unknown" mean here what they mean+ on the wire.++ Type and constraint violations are deliberately left to the worker. The+ forwarding function rewrites arguments back onto the parent tool (renames,+ hidden constants, injected defaults), and the parent validates them against+ its own call schema; reproducing that rewrite here would duplicate the+ transform's argument rules rather than reuse them.+ """+ parameters = tool.parameters or {}+ properties = parameters.get("properties", {})++ supplied = set(arguments) | {+ name+ for name, schema in properties.items()+ if isinstance(schema, dict) and "default" in schema+ }+ unknown = sorted(set(arguments) - set(properties))+ missing = sorted(set(parameters.get("required", [])) - supplied)++ if not (unknown or missing):+ return arguments++ details = []+ if unknown:+ details.append(f"unexpected argument(s): {', '.join(unknown)}")+ if missing:+ details.append(f"missing required argument(s): {', '.join(missing)}")+ raise ValidationError(+ f"Invalid arguments for tool {tool.name!r}: {'; '.join(details)}",+ log_level=logging.WARNING,+ )++def _call_shape_probe(fn: Callable[..., Any]) -> Callable[..., dict[str, Any]]:"""Mirror ``fn``'s signature on a function that only returns its keyword arguments.diff --git a/tests/tasks/server/test_task_transformed_tools.py b/tests/tasks/server/test_task_transformed_tools.pynew file mode 100644index 000000000..c047f2fbc--- /dev/null+++ b/tests/tasks/server/test_task_transformed_tools.py@@ -0,0 +1,105 @@+"""Task submission for transformed tools (SEP-2663, tools only).++A transformed tool stays task-capable (#5780), so its arguments now reach the+task-submission path, which runs before ``TransformedTool.run`` β the only place+a transform enforces its argument contract. These tests pin the submission-time+gate: a call the synchronous path rejects must raise instead of being persisted+as a task that only fails once a worker picks it up.+"""++from __future__ import annotations++import pytest++from fastmcp import FastMCP+from fastmcp.exceptions import ToolError, ValidationError+from fastmcp.server.transforms import ToolTransform+from fastmcp.tools import Tool+from fastmcp.tools.tool_transform import ArgTransform, ToolTransformConfig+from fastmcp_tasks import TasksExtension+from tests.tasks.task_helpers import (+ call_tool_without_optin,+ run_task,+ running_task_server,+ submit_task,+)+++def _server() -> FastMCP:+ """A server whose only tool is task-enabled and renamed by a transform."""+ mcp = FastMCP("transformed-task-server")+ mcp.add_extension(TasksExtension())++ @mcp.tool(task=True)+ async def add(a: int, b: int = 1) -> int:+ return a + b++ mcp.add_transform(ToolTransform({"add": ToolTransformConfig(name="add_v2")}))+ return mcp+++async def test_transformed_submission_rejects_missing_required():+ """A call missing a required argument raises instead of creating a task."""+ mcp = _server()+ async with running_task_server(mcp):+ with pytest.raises(ToolError):+ await call_tool_without_optin(mcp, "add_v2", {"b": 2})+ with pytest.raises(ValidationError, match="missing required argument"):+ await submit_task(mcp, "add_v2", {"b": 2})+++async def test_transformed_submission_rejects_unknown_argument():+ """An argument the transform does not expose raises instead of queueing."""+ mcp = _server()+ async with running_task_server(mcp):+ with pytest.raises(ToolError):+ await call_tool_without_optin(mcp, "add_v2", {"a": 1, "c": 3})+ with pytest.raises(ValidationError, match="unexpected argument"):+ await submit_task(mcp, "add_v2", {"a": 1, "c": 3})+++async def test_transformed_submission_accepts_omitted_default():+ """A schema default satisfies ``required`` exactly as it does for a plain tool."""+ mcp = _server()+ async with running_task_server(mcp):+ final = await run_task(mcp, "add_v2", {"a": 1})+ assert final.status == "completed"+ assert final.result is not None+ assert final.result["structuredContent"] == {"result": 2}+++async def test_transformed_submission_accepts_an_explicit_default():+ """Passing the defaulted argument explicitly still submits."""+ mcp = _server()+ async with running_task_server(mcp):+ final = await run_task(mcp, "add_v2", {"a": 1, "b": 4})+ assert final.status == "completed"+ assert final.result is not None+ assert final.result["structuredContent"] == {"result": 5}+++async def test_renamed_argument_submission_uses_the_transformed_name():+ """A renamed argument is accepted under its new name and rejected under the old."""++ async def scale(factor: int) -> int:+ return factor * 2++ parent = Tool.from_function(scale, name="scale", task=True)+ renamed = Tool.from_tool(+ parent,+ name="scale_v2",+ transform_args={"factor": ArgTransform(name="multiplier")},+ )++ mcp = FastMCP("renamed-arg-task-server")+ mcp.add_extension(TasksExtension())+ mcp.add_tool(renamed)++ async with running_task_server(mcp):+ with pytest.raises(ValidationError, match="unexpected argument"):+ await submit_task(mcp, "scale_v2", {"factor": 2})+ final = await run_task(mcp, "scale_v2", {"multiplier": 3})++ assert final.status == "completed"+ assert final.result is not None+ assert final.result["structuredContent"] == {"result": 6}diff --git a/tests/tools/tool_transform/test_task_config.py b/tests/tools/tool_transform/test_task_config.pynew file mode 100644index 000000000..9591abdbb--- /dev/null+++ b/tests/tools/tool_transform/test_task_config.py@@ -0,0 +1,96 @@+"""Transformed tools keep their background-task capability (SEP-2663, tools only).++Transforms are the only wrapping path that rebuilds a tool from a parent; the+mount path (`FastMCPProviderTool.wrap`) already carries `task_config` and+`execution` across. A rename or rewrap must not silently downgrade a task-enabled+tool to foreground-only.+"""++import pytest+from mcp_types import ToolExecution++from fastmcp import FastMCP+from fastmcp.server.transforms import ToolTransform+from fastmcp.tools import Tool+from fastmcp.tools.tool_transform import ToolTransformConfig+from fastmcp.utilities.tasks import TaskConfig+++def task_tool():+ """A task-enabled tool: `task=True` yields mode `optional`."""++ async def slow(x: int) -> int:+ return x++ return Tool.from_function(slow, name="slow", task=True)+++def plain_tool():+ """A tool with no task support."""++ async def quick(x: int) -> int:+ return x++ return Tool.from_function(quick, name="quick")+++def test_transform_inherits_task_config(task_tool):+ """A pure rename preserves the parent's task mode."""+ assert task_tool.task_config.mode == "optional"++ transformed = Tool.from_tool(task_tool, name="slow_v2")++ assert transformed.task_config.mode == "optional"+ assert transformed.task_config.supports_tasks()+++def test_transformed_tool_advertises_execution_on_wire(task_tool):+ """The wire tool must advertise task execution so clients can opt in."""+ assert task_tool.to_mcp_tool().execution is not None++ transformed = Tool.from_tool(task_tool, name="slow_v2")++ execution = transformed.to_mcp_tool().execution+ assert execution is not None+ assert execution.task_support == "optional"+++def test_transform_preserves_explicit_execution_without_task_support(plain_tool):+ """`execution` is threaded separately from `task_config`.++ `to_mcp_tool()` only derives `execution` from `task_config` when the tool has+ no explicit `execution`, so a parent that advertises execution on its own+ (e.g. a proxied tool) would lose it if only `task_config` were carried over.+ """+ parent = plain_tool.model_copy(+ update={+ "task_config": TaskConfig(mode="forbidden"),+ "execution": ToolExecution(task_support="required"),+ }+ )+ assert parent.to_mcp_tool().execution is not None++ transformed = Tool.from_tool(parent, name="quick_v2")++ assert not transformed.task_config.supports_tasks()+ assert transformed.execution == parent.execution+ assert transformed.to_mcp_tool().execution is not None+++def test_transform_does_not_add_task_support(plain_tool):+ """A tool without task support stays forbidden after a transform."""+ transformed = Tool.from_tool(plain_tool, name="quick_v2")++ assert transformed.task_config.mode == "forbidden"+ assert transformed.to_mcp_tool().execution is None+++async def test_server_transform_keeps_task_tool_registered(task_tool):+ """A server-level rename keeps the tool in `get_tasks()`."""+ mcp = FastMCP("test")+ mcp.add_transform(ToolTransform({"slow": ToolTransformConfig(name="slow_v2")}))+ mcp.add_tool(task_tool)++ assert [c.name for c in await mcp.get_tasks()] == ["slow_v2"]