π The fast, Pythonic way to build MCP servers and clients.
Reject missing and unexpected arguments at task submission (#5622)
Asem ahmed41df2f2888c9
diff --git a/fastmcp_tasks/fastmcp_tasks/components.py b/fastmcp_tasks/fastmcp_tasks/components.pyindex 2e9dec039..f4e6d3c22 100644--- a/fastmcp_tasks/fastmcp_tasks/components.py+++ b/fastmcp_tasks/fastmcp_tasks/components.py@@ -22,6 +22,7 @@ because core still declares them.from __future__ import annotations+import inspectimport loggingfrom typing import TYPE_CHECKING, Any@@ -44,6 +45,8 @@ from fastmcp.utilities.types import get_cached_typeadapterfrom fastmcp_tasks.input_loop import reentrant_task_fnif TYPE_CHECKING:+ from collections.abc import Callable+from docket import Docketfrom docket.execution import Execution@@ -171,16 +174,43 @@ def coerce_task_arguments(wrapper_fn = without_injected_parameters(component.fn, run_in_thread=component.run_in_thread)- hints = _resolve_param_hints(wrapper_fn)-- coerced = dict(arguments)- for name, value in arguments.items():- annotation = hints.get(name)- if annotation is None:- continue- adapter = get_cached_typeadapter(annotation)- try:- coerced[name] = _validate_input(adapter, value, strict=strict)- except PydanticValidationError as e:- raise ValidationError(str(e), log_level=logging.WARNING) from e- return coerced++ # Validate the whole call through the same Pydantic call schema the+ # synchronous path builds, so "required", "unknown" and "default" mean the+ # same thing on both paths. Left unchecked, a bad call is only rejected+ # inside the worker, as a task that completes with an opaque error instead+ # of a validation failure.+ adapter = get_cached_typeadapter(_call_shape_probe(wrapper_fn))+ try:+ validated: dict[str, Any] = _validate_input(adapter, arguments, strict=strict)+ except PydanticValidationError as e:+ raise ValidationError(str(e), log_level=logging.WARNING) from e++ # Return the validated call, defaults included: the worker invokes the tool+ # function directly, so a parameter whose default only Pydantic knows about+ # (``Annotated[int, Field(default=5)]``) must arrive with its value filled in.+ return validated+++def _call_shape_probe(fn: Callable[..., Any]) -> Callable[..., dict[str, Any]]:+ """Mirror ``fn``'s signature on a function that only returns its keyword arguments.++ ``TypeAdapter`` validates a callable's arguments by calling it, so validating+ a task submission against ``fn`` itself would run the tool. The probe has the+ identical parameters, defaults and resolved annotations, so Pydantic builds+ the identical call schema, and calling it returns what was validated.+ """++ def probe(*args: Any, **kwargs: Any) -> dict[str, Any]:+ return inspect.signature(probe).bind(*args, **kwargs).arguments++ hints = _resolve_param_hints(fn)+ sig = inspect.signature(fn)+ annotations = {+ name: hints.get(name, param.annotation)+ for name, param in sig.parameters.items()+ if name in hints or param.annotation is not inspect.Parameter.empty+ }+ probe.__signature__ = sig # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]+ probe.__annotations__ = annotations+ return probediff --git a/tests/tasks/server/test_task_tools.py b/tests/tasks/server/test_task_tools.pyindex 2dd166090..063fcad01 100644--- a/tests/tasks/server/test_task_tools.py+++ b/tests/tasks/server/test_task_tools.py@@ -21,7 +21,7 @@ from fastmcp_tasks.models import CreateTaskResultfrom pydantic import BaseModel, Fieldimport fastmcp.tools.function_tool as function_tool-from fastmcp import FastMCP+from fastmcp import Context, FastMCPfrom fastmcp.exceptions import ValidationErrorfrom fastmcp.tools.function_tool import _resolve_param_hintsfrom fastmcp_tasks import TasksExtension@@ -135,6 +135,64 @@ async def test_task_submission_honors_strict_input_validation():await submit_task(mcp, "square", {"n": "1"})+async def test_task_submission_rejects_missing_and_unexpected_arguments():+ """A call with a missing or unknown argument is rejected at submission.++ The synchronous path raises a validation error for both. The task path must+ too, rather than creating a task that only fails once a worker runs it.+ """+ mcp = FastMCP("argument-shape-task-server")+ mcp.add_extension(TasksExtension())++ @mcp.tool(task=True)+ async def add(ctx: Context, a: int, b: int = 1) -> int:+ return a + b++ async with running_task_server(mcp):+ for arguments in ({"b": 2}, {"a": 1, "c": 3}):+ with pytest.raises(ValidationError):+ await call_tool_without_optin(mcp, "add", arguments)+ with pytest.raises(ValidationError):+ await submit_task(mcp, "add", arguments)++ final = await run_task(mcp, "add", {"a": 1})+ assert final.status == "completed"+ assert final.result is not None+ assert final.result["structuredContent"] == {"result": 2}+++async def test_task_submission_uses_the_pydantic_definition_of_required():+ """Submission agrees with the synchronous path on what is required.++ ``Field(default=...)`` inside ``Annotated`` makes a parameter optional even+ though the Python signature has no default, and ``x: str = Field(...)`` makes+ a parameter required even though the Python signature does have one.+ """+ mcp = FastMCP("pydantic-required-task-server")+ mcp.add_extension(TasksExtension())++ @mcp.tool(task=True)+ async def annotated_default(x: Annotated[int, Field(default=5)]) -> int:+ return x++ @mcp.tool(task=True)+ async def described_query(query: str = Field(description="the query")) -> str:+ return query++ async with running_task_server(mcp):+ sync_result = await call_tool_without_optin(mcp, "annotated_default", {})+ final = await run_task(mcp, "annotated_default", {})+ assert final.status == "completed"+ assert final.result is not None+ assert final.result["structuredContent"] == sync_result.structured_content+ assert final.result["structuredContent"] == {"result": 5}++ with pytest.raises(ValidationError):+ await call_tool_without_optin(mcp, "described_query", {})+ with pytest.raises(ValidationError):+ await submit_task(mcp, "described_query", {})++async def test_valid_argument_submits_under_strict_validation():"""A well-typed argument still submits fine when strict validation is on."""mcp = FastMCP("strict-task-valid-server", strict_input_validation=True)