Skip to content

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

Replace parent type keywords when an ArgTransform changes the type (#6246)

nate nowack38a0644806a9
diff --git a/fastmcp_slim/fastmcp/tools/tool_transform.py b/fastmcp_slim/fastmcp/tools/tool_transform.py
index 82f2c326e..fbba0fa76 100644
--- a/fastmcp_slim/fastmcp/tools/tool_transform.py
+++ b/fastmcp_slim/fastmcp/tools/tool_transform.py
@@ -27,7 +27,7 @@ from fastmcp.utilities.async_utils import (
is_coroutine_function,
)
from fastmcp.utilities.components import _convert_set_default_none
-from fastmcp.utilities.json_schema import compress_schema
+from fastmcp.utilities.json_schema import _METADATA_KEYS, compress_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import (
FastMCPBaseModel,
@@ -39,6 +39,89 @@ from fastmcp.utilities.types import (
logger = get_logger(__name__)
+# Metadata preserved when replacing a property's JSON Schema type.
+_PROPERTY_PRESERVE_KEYS = _METADATA_KEYS | frozenset({"default", "examples", "example"})
+
+
+def _is_preserved_property_key(key: str) -> bool:
+ # `x-` extension keys are annotations (UI and vendor hints), not validation.
+ return key in _PROPERTY_PRESERVE_KEYS or key.startswith("x-")
+
+
+def _strip_structural_schema_keys(schema: dict[str, Any]) -> dict[str, Any]:
+ return {k: v for k, v in schema.items() if _is_preserved_property_key(k)}
+
+
+def _schema_has_structural_keys(schema: dict[str, Any]) -> bool:
+ return any(not _is_preserved_property_key(key) for key in schema)
+
+
+def _structural_kind(schema: dict[str, Any]) -> tuple[Any, ...]:
+ """Type identity, excluding validation constraints and property metadata."""
+ for key in ("anyOf", "oneOf", "allOf"):
+ if key in schema:
+ branch_kinds: set[tuple[Any, ...]] = set()
+ for branch in schema[key]:
+ kind = _structural_kind(branch)
+ if key == "anyOf" and kind and kind[0] == "anyOf":
+ branch_kinds.update(kind[1])
+ else:
+ branch_kinds.add(kind)
+ if key == "anyOf" and len(branch_kinds) == 1:
+ return next(iter(branch_kinds))
+ return (key, frozenset(branch_kinds))
+ if "$ref" in schema:
+ return ("$ref", schema["$ref"])
+
+ schema_type = schema.get("type")
+ if schema_type is None:
+ # Mixed Literals omit type, so their values supply the primitive types.
+ values = schema.get("enum", [schema["const"]] if "const" in schema else [])
+ literal_types = {
+ type(None): "null",
+ bool: "boolean",
+ int: "integer",
+ float: "number",
+ str: "string",
+ }
+ if any(type(value) not in literal_types for value in values):
+ return ()
+ kinds = frozenset(("type", literal_types[type(value)]) for value in values)
+ if len(kinds) == 1:
+ return next(iter(kinds))
+ return ("anyOf", kinds) if kinds else ()
+
+ if isinstance(schema_type, list):
+ return (
+ "anyOf",
+ frozenset(
+ _structural_kind({**schema, "type": branch}) for branch in schema_type
+ ),
+ )
+ if schema_type == "array":
+ items = schema.get("items", {})
+ return (
+ "type",
+ "array",
+ _structural_kind(items) if isinstance(items, dict) else items,
+ tuple(_structural_kind(item) for item in schema.get("prefixItems", [])),
+ )
+ if schema_type == "object":
+ # Constrained dictionary keys put their value schema under patterns.
+ # The patterns constrain keys, but do not change their value types.
+ values = list(schema.get("patternProperties", {}).values())
+ if not values or "additionalProperties" in schema:
+ values.append(schema.get("additionalProperties", True))
+ return (
+ "type",
+ "object",
+ frozenset(
+ _structural_kind(value) if isinstance(value, dict) else value
+ for value in values
+ ),
+ )
+ return ("type", schema_type)
+
# Context variable to store current transformed tool
_current_tool: ContextVar[TransformedTool | None] = ContextVar(
@@ -564,7 +647,14 @@ class TransformedTool(Tool):
# ArgTransform takes precedence over function signature
# Start with function schema as base, then override with transformed schema
final_schema = cls._merge_schema_with_precedence(
- parsed_fn.input_schema, schema
+ parsed_fn.input_schema,
+ schema,
+ structural_override_properties=cls._arg_transform_type_override_names(
+ transform_args
+ ),
+ explicit_required_properties=cls._arg_transform_explicit_required_names(
+ transform_args
+ ),
)
else:
# With **kwargs, function can access all transformed params
@@ -573,7 +663,14 @@ class TransformedTool(Tool):
# Start with function schema as base, then override with transformed schema
final_schema = cls._merge_schema_with_precedence(
- parsed_fn.input_schema, schema
+ parsed_fn.input_schema,
+ schema,
+ structural_override_properties=cls._arg_transform_type_override_names(
+ transform_args
+ ),
+ explicit_required_properties=cls._arg_transform_explicit_required_names(
+ transform_args
+ ),
)
# Additional validation: check for naming conflicts after transformation
@@ -844,8 +941,8 @@ class TransformedTool(Tool):
# nested inside this property while $ref values still point to
# "#/$defs/..." at the root, leaving the references dangling.
extracted_defs = type_schema.pop("$defs", {})
- # Update the schema with the type information from TypeAdapter
- new_schema.update(type_schema)
+ preserved = _strip_structural_schema_keys(new_schema)
+ new_schema = {**type_schema, **preserved}
# Handle examples transformation
if transform.examples is not NotSet:
@@ -853,15 +950,55 @@ class TransformedTool(Tool):
return new_name, new_schema, is_required, extracted_defs
+ @staticmethod
+ def _arg_transform_type_override_names(
+ transform_args: dict[str, ArgTransform] | None,
+ ) -> frozenset[str]:
+ if not transform_args:
+ return frozenset()
+ names: set[str] = set()
+ for old_name, transform in transform_args.items():
+ if transform.hide or transform.type is NotSet:
+ continue
+ if transform.name is not NotSet and transform.name is not None:
+ names.add(transform.name)
+ else:
+ names.add(old_name)
+ return frozenset(names)
+
+ @staticmethod
+ def _arg_transform_explicit_required_names(
+ transform_args: dict[str, ArgTransform] | None,
+ ) -> frozenset[str]:
+ if not transform_args:
+ return frozenset()
+ names: set[str] = set()
+ for old_name, transform in transform_args.items():
+ if transform.hide or transform.required is NotSet or not transform.required:
+ continue
+ if transform.name is not NotSet and transform.name is not None:
+ names.add(transform.name)
+ else:
+ names.add(old_name)
+ return frozenset(names)
+
@staticmethod
def _merge_schema_with_precedence(
- base_schema: dict[str, Any], override_schema: dict[str, Any]
+ base_schema: dict[str, Any],
+ override_schema: dict[str, Any],
+ *,
+ structural_override_properties: frozenset[str] | None = None,
+ explicit_required_properties: frozenset[str] | None = None,
) -> dict[str, Any]:
"""Merge two schemas, with the override schema taking precedence.
Args:
base_schema: Base schema to start with
override_schema: Schema that takes precedence for overlapping properties
+ structural_override_properties: Property names whose structural schema
+ comes from the override (e.g. ArgTransform(type=...) on the parent).
+ explicit_required_properties: Property names marked
+ ArgTransform(required=True), which never inherit a base default.
Returns:
Merged schema with override taking precedence
@@ -871,13 +1008,46 @@ class TransformedTool(Tool):
override_props = override_schema.get("properties", {})
override_required = set(override_schema.get("required", []))
+ structural_override_properties = structural_override_properties or frozenset()
+ explicit_required_properties = explicit_required_properties or frozenset()
# Override properties
for param_name, param_schema in override_props.items():
if param_name in merged_props:
- # Merge the schemas, with override taking precedence
base_param = merged_props[param_name].copy()
- base_param.update(param_schema)
+ if param_name in structural_override_properties:
+ structural = {
+ key: value
+ for key, value in param_schema.items()
+ if not _is_preserved_property_key(key)
+ }
+ preserved_override = _strip_structural_schema_keys(param_schema)
+ preserved_base = _strip_structural_schema_keys(base_param)
+ base_param = {**structural, **preserved_override}
+ for key, value in preserved_base.items():
+ if key in preserved_override:
+ continue
+ if (
+ key == "default"
+ and param_name in explicit_required_properties
+ ):
+ continue
+ base_param[key] = value
+ elif _schema_has_structural_keys(base_param) and _structural_kind(
+ base_param
+ ) != _structural_kind(param_schema):
+ param_schema = _strip_structural_schema_keys(param_schema)
+ base_param.update(param_schema)
+ else:
+ if "enum" in base_param or "const" in base_param:
+ # A Literal in the transform_fn signature declares its
+ # own value set, which replaces the parent's.
+ param_schema = {
+ key: value
+ for key, value in param_schema.items()
+ if key not in ("enum", "const")
+ }
+ base_param.update(param_schema)
merged_props[param_name] = base_param
else:
merged_props[param_name] = param_schema.copy()
diff --git a/tests/tools/tool_transform/test_schema_compatibility.py b/tests/tools/tool_transform/test_schema_compatibility.py
new file mode 100644
index 000000000..812894a05
--- /dev/null
+++ b/tests/tools/tool_transform/test_schema_compatibility.py
@@ -0,0 +1,405 @@
+"""Consumer-visible schema contracts for transform_fn reannotations."""
+
+from typing import Annotated, Any, Literal
+
+import jsonschema
+import pytest
+from pydantic import Field
+
+from fastmcp import Client, FastMCP
+from fastmcp.exceptions import ToolError
+from fastmcp.tools import Tool, ToolResult, forward
+from fastmcp.tools.function_tool import FunctionTool
+from fastmcp.tools.tool_transform import ArgTransform
+
+
[email protected]("with_kwargs", [False, True])
+async def test_nullable_integer_reannotation_preserves_parent_bounds(
+ with_kwargs: bool,
+) -> None:
+ """A repeated nullable type must still advertise the bounds enforced by the parent."""
+
+ def parent(n: Annotated[int | None, Field(ge=1, le=10)]) -> str:
+ return "none" if n is None else str(n)
+
+ async def child(n: int | None) -> ToolResult:
+ return await forward(n=n)
+
+ async def child_with_kwargs(n: int | None, **kwargs: Any) -> ToolResult:
+ return await forward(n=n, **kwargs)
+
+ parent_tool = Tool.from_function(parent)
+ assert isinstance(parent_tool, FunctionTool)
+ transformed = Tool.from_tool(
+ parent_tool, transform_fn=child_with_kwargs if with_kwargs else child
+ )
+
+ async with Client(FastMCP(tools=[transformed])) as client:
+ assert (await client.call_tool("parent", {"n": 3})).data == "3"
+ assert (await client.call_tool("parent", {"n": None})).data == "none"
+ with pytest.raises(ToolError):
+ await client.call_tool("parent", {"n": 0})
+ advertised = (await client.list_tools())[0].input_schema
+
+ validator = jsonschema.Draft202012Validator(advertised)
+ assert validator.is_valid({"n": None})
+ assert validator.is_valid({"n": 1})
+ assert validator.is_valid({"n": 10})
+ assert not validator.is_valid({"n": 0})
+ assert not validator.is_valid({"n": 11})
+
+
[email protected]("with_kwargs", [False, True])
+async def test_list_reannotation_preserves_parent_length_constraint(
+ with_kwargs: bool,
+) -> None:
+ """Repeating list[int] must retain the parent minimum length on the wire."""
+
+ def parent(values: Annotated[list[int], Field(min_length=2)]) -> str:
+ return ",".join(str(value) for value in values)
+
+ async def child(values: list[int]) -> ToolResult:
+ return await forward(values=values)
+
+ async def child_with_kwargs(values: list[int], **kwargs: Any) -> ToolResult:
+ return await forward(values=values, **kwargs)
+
+ transformed = Tool.from_tool(
+ Tool.from_function(parent),
+ transform_fn=child_with_kwargs if with_kwargs else child,
+ )
+ async with Client(FastMCP(tools=[transformed])) as client:
+ assert (await client.call_tool("parent", {"values": [1, 2]})).data == "1,2"
+ with pytest.raises(ToolError):
+ await client.call_tool("parent", {"values": [1]})
+ advertised = (await client.list_tools())[0].input_schema
+
+ validator = jsonschema.Draft202012Validator(advertised)
+ assert validator.is_valid({"values": [1, 2]})
+ assert not validator.is_valid({"values": [1]})
+ assert not validator.is_valid({"values": ["1", "2"]})
+
+
[email protected]("with_kwargs", [False, True])
+async def test_changed_list_items_replace_incompatible_parent_schema(
+ with_kwargs: bool,
+) -> None:
+ """A string-list transform must advertise the string input it converts for the parent."""
+
+ def parent(values: list[int]) -> str:
+ return ",".join(str(value) for value in values)
+
+ async def child(values: list[str]) -> ToolResult:
+ return await forward(values=[int(value) for value in values])
+
+ async def child_with_kwargs(values: list[str], **kwargs: Any) -> ToolResult:
+ return await forward(values=[int(value) for value in values], **kwargs)
+
+ transformed = Tool.from_tool(
+ Tool.from_function(parent),
+ transform_fn=child_with_kwargs if with_kwargs else child,
+ )
+ async with Client(FastMCP(tools=[transformed])) as client:
+ assert (await client.call_tool("parent", {"values": ["1", "2"]})).data == "1,2"
+ advertised = (await client.list_tools())[0].input_schema
+
+ validator = jsonschema.Draft202012Validator(advertised)
+ assert validator.is_valid({"values": ["1", "2"]})
+ assert not validator.is_valid({"values": [1, 2]})
+
+
+ ("parent_type", "child_type", "allowed", "disallowed"),
+ [
+ (
+ Annotated[list[int] | None, Field(min_length=2)],
+ list[int] | None,
+ {"value": [1, 2]},
+ {"value": [1]},
+ ),
+ (
+ list[list[int]],
+ list[list[str]],
+ {"value": [["1"]]},
+ {"value": [[1]]},
+ ),
+ (
+ dict[str, int],
+ dict[str, str],
+ {"value": {"one": "1"}},
+ {"value": {"one": 1}},
+ ),
+ (
+ tuple[int, int],
+ tuple[str, str],
+ {"value": ["1", "2"]},
+ {"value": [1, 2]},
+ ),
+ (
+ tuple[int, str],
+ tuple[str, int],
+ {"value": ["1", 2]},
+ {"value": [1, "2"]},
+ ),
+ (
+ list[Annotated[str, Field(min_length=2, pattern="^a")]] | None,
+ list[str] | None,
+ {"value": ["ab"]},
+ {"value": ["bb"]},
+ ),
+ (
+ dict[Annotated[str, Field(pattern="^a")], Literal[1, "one"] | None],
+ dict[str, int | str | None],
+ {"value": {"abc": None}},
+ {"value": {"abc": 2}},
+ ),
+ ],
+ ids=[
+ "nullable-list-constraint",
+ "nested-items",
+ "mapping-values",
+ "tuple-items",
+ "tuple-item-order",
+ "nested-string-constraints",
+ "key-pattern-preserves-nullable-literal-values",
+ ],
+)
+def test_nested_schema_contracts(
+ parent_type: Any,
+ child_type: Any,
+ allowed: dict[str, Any],
+ disallowed: dict[str, Any],
+) -> None:
+ """Consumers must see compatible constraints and genuinely changed nested types."""
+
+ def parent(value: Any) -> str:
+ return str(value)
+
+ async def child(value: Any) -> str:
+ return str(value)
+
+ parent.__annotations__["value"] = parent_type
+ child.__annotations__["value"] = child_type
+
+ transformed = Tool.from_tool(Tool.from_function(parent), transform_fn=child)
+ validator = jsonschema.Draft202012Validator(transformed.parameters)
+ assert validator.is_valid(allowed)
+ assert not validator.is_valid(disallowed)
+
+
[email protected]("with_kwargs", [False, True])
+ ("parent_type", "child_type", "allowed", "disallowed"),
+ [
+ (
+ Annotated[int, Field(ge=1, le=10)] | None | str,
+ str | int | None,
+ 2,
+ 0,
+ ),
+ (Literal["fast", "slow"] | None, str | None, "fast", "other"),
+ (Literal[1, "one"], str | int, "one", 2),
+ (Literal[True, "one"], str | bool, True, False),
+ (Literal[1, "one"] | None, str | int | None, None, 2),
+ (
+ list[Literal[1, "one"] | None],
+ list[int | str | None],
+ [None, "one"],
+ ["two"],
+ ),
+ (
+ Annotated[int, Field(ge=1)] | Annotated[int, Field(le=-1)],
+ int,
+ -1,
+ 0,
+ ),
+ (Literal[1] | Literal[2], int, 2, 3),
+ (list[Literal[1] | Literal[2]], list[int], [1, 2], [3]),
+ ],
+ ids=[
+ "reordered-union",
+ "nullable-literal",
+ "mixed-literal",
+ "boolean-literal",
+ "nullable-mixed-literal",
+ "nested-nullable-mixed-literal",
+ "same-primitive-constrained-union",
+ "same-primitive-literal-union",
+ "same-primitive-nested-literal-union",
+ ],
+)
+async def test_union_reannotation_preserves_parent_constraints(
+ with_kwargs: bool,
+ parent_type: Any,
+ child_type: Any,
+ allowed: Any,
+ disallowed: Any,
+) -> None:
+ """Union order and Literal values do not change the underlying primitive types."""
+
+ def parent(value: Any) -> str:
+ return str(value)
+
+ async def child(value: Any) -> ToolResult:
+ return await forward(value=value)
+
+ async def child_with_kwargs(value: Any, **kwargs: Any) -> ToolResult:
+ return await forward(value=value, **kwargs)
+
+ parent.__annotations__["value"] = parent_type
+ child.__annotations__["value"] = child_type
+ child_with_kwargs.__annotations__["value"] = child_type
+ transformed = Tool.from_tool(
+ Tool.from_function(parent),
+ transform_fn=child_with_kwargs if with_kwargs else child,
+ )
+ async with Client(FastMCP(tools=[transformed])) as client:
+ assert (await client.call_tool("parent", {"value": allowed})).data == str(
+ allowed
+ )
+ with pytest.raises(ToolError):
+ await client.call_tool("parent", {"value": disallowed})
+ advertised = (await client.list_tools())[0].input_schema
+
+ validator = jsonschema.Draft202012Validator(advertised)
+ assert validator.is_valid({"value": allowed})
+ assert not validator.is_valid({"value": disallowed})
+
+
[email protected]("with_kwargs", [False, True])
+async def test_constrained_key_mapping_replaces_changed_value_type(
+ with_kwargs: bool,
+) -> None:
+ """Key patterns must not hide a change in the dictionary's value type."""
+
+ def parent(values: dict[Annotated[str, Field(pattern="^a")], int]) -> str:
+ return str(values["abc"])
+
+ async def child(
+ values: dict[Annotated[str, Field(pattern="^a")], str],
+ ) -> ToolResult:
+ return await forward(values={key: int(value) for key, value in values.items()})
+
+ async def child_with_kwargs(
+ values: dict[Annotated[str, Field(pattern="^a")], str], **kwargs: Any
+ ) -> ToolResult:
+ return await forward(
+ values={key: int(value) for key, value in values.items()}, **kwargs
+ )
+
+ transformed = Tool.from_tool(
+ Tool.from_function(parent),
+ transform_fn=child_with_kwargs if with_kwargs else child,
+ )
+ async with Client(FastMCP(tools=[transformed])) as client:
+ assert (await client.call_tool("parent", {"values": {"abc": "1"}})).data == "1"
+ advertised = (await client.list_tools())[0].input_schema
+
+ validator = jsonschema.Draft202012Validator(advertised)
+ assert validator.is_valid({"values": {"abc": "1"}})
+ assert not validator.is_valid({"values": {"abc": 1}})
+
+
+async def test_explicit_type_override_replaces_bounds_and_keeps_renamed_default() -> (
+ None
+):
+ """Explicit type overrides intentionally replace validation even for the same type."""
+
+ def parent(
+ n: Annotated[int | None, Field(ge=1, le=10, description="bounded")],
+ ) -> str:
+ return str(n)
+
+ async def child(value: int | None = 0) -> str:
+ return str(value)
+
+ transformed = Tool.from_tool(
+ Tool.from_function(parent),
+ transform_fn=child,
+ transform_args={"n": ArgTransform(name="value", type=int | None)},
+ )
+
+ async with Client(FastMCP(tools=[transformed])) as client:
+ assert (await client.call_tool("parent", {})).data == "0"
+ advertised = (await client.list_tools())[0].input_schema
+
+ assert advertised["properties"]["value"]["description"] == "bounded"
+ assert advertised["properties"]["value"]["default"] == 0
+ validator = jsonschema.Draft202012Validator(advertised)
+ assert validator.is_valid({})
+ assert validator.is_valid({"value": 0})
+ assert validator.is_valid({"value": None})
+
+
+async def _legacy_mode(mode: Literal["quick"]) -> ToolResult:
+ return await forward(mode="fast")
+
+
+async def _renamed_mode(mode: Literal["quick", "careful"]) -> ToolResult:
+ return await forward(mode="fast" if mode == "quick" else "slow")
+
+
+async def _widened_mode(mode: Literal["fast", "slow", "turbo"]) -> ToolResult:
+ return await forward(mode="fast" if mode == "turbo" else mode)
+
+
+ ("transform_fn", "accepted", "rejected"),
+ [
+ (_legacy_mode, "quick", "fast"),
+ (_renamed_mode, "careful", "slow"),
+ (_widened_mode, "turbo", "medium"),
+ ],
+)
+async def test_literal_reannotation_advertises_transform_fn_values(
+ transform_fn: Any, accepted: str, rejected: str
+) -> None:
+ """A transform_fn Literal replaces the parent's value set instead of merging."""
+
+ def parent(mode: Literal["fast", "slow"]) -> str:
+ return mode
+
+ transformed = Tool.from_tool(Tool.from_function(parent), transform_fn=transform_fn)
+
+ async with Client(FastMCP(tools=[transformed])) as client:
+ assert (await client.call_tool("parent", {"mode": accepted})).data in (
+ "fast",
+ "slow",
+ )
+ advertised = (await client.list_tools())[0].input_schema
+
+ validator = jsonschema.Draft202012Validator(advertised)
+ assert validator.is_valid({"mode": accepted})
+ assert not validator.is_valid({"mode": rejected})
+
+
+def test_plain_reannotation_keeps_parent_literal_values() -> None:
+ def parent(mode: Literal["fast", "slow"]) -> str:
+ return mode
+
+ async def child(mode: str) -> ToolResult:
+ return await forward(mode=mode)
+
+ transformed = Tool.from_tool(Tool.from_function(parent), transform_fn=child)
+
+ assert transformed.parameters["properties"]["mode"]["enum"] == ["fast", "slow"]
+
+
+def test_explicit_type_override_keeps_parent_extension_keys() -> None:
+ def parent(
+ value: Annotated[
+ str, Field(description="d", json_schema_extra={"x-ui": "slider"})
+ ],
+ ) -> str:
+ return value
+
+ transformed = Tool.from_tool(
+ Tool.from_function(parent),
+ transform_args={"value": ArgTransform(type=int)},
+ )
+
+ assert transformed.parameters["properties"]["value"] == {
+ "description": "d",
+ "type": "integer",
+ "x-ui": "slider",
+ }
diff --git a/tests/tools/tool_transform/test_tool_transform.py b/tests/tools/tool_transform/test_tool_transform.py
index 0f07b3c8d..e185c1576 100644
--- a/tests/tools/tool_transform/test_tool_transform.py
+++ b/tests/tools/tool_transform/test_tool_transform.py
@@ -5,8 +5,9 @@ import json
import re
import time
from dataclasses import dataclass
-from typing import Annotated, Any
+from typing import Annotated, Any, Literal
+import jsonschema
import pytest
from mcp_types import Icon, TextContent
from pydantic import BaseModel, ConfigDict, Field, with_config
@@ -380,6 +381,109 @@ async def test_arg_transform_type_raises_on_defs_name_collision():
Tool.from_tool(tool_fn, transform_args={"other": ArgTransform(type=list[Foo])})
+async def test_arg_transform_type_replaces_parent_type_keywords():
+ """Regression for #5369: ArgTransform(type=...) must replace, not merge, parent types."""
+
+ @Tool.from_function
+ def parent(x: str) -> str:
+ return x
+
+ tool = Tool.from_tool(parent, transform_args={"x": ArgTransform(type=int | None)})
+
+ prop = tool.parameters["properties"]["x"]
+ validator = jsonschema.Draft202012Validator(tool.parameters)
+ assert prop == {
+ "anyOf": [{"type": "integer"}, {"type": "null"}],
+ }
+ assert validator.is_valid({"x": 5})
+ assert validator.is_valid({"x": None})
+ assert not validator.is_valid({"x": "hello"})
+
+
+async def test_transform_fn_type_replaces_forwarded_parent_schema():
+ """Regression for #5369: transform_fn signatures must not inherit parent type keywords."""
+
+ @Tool.from_function
+ def parent(x: str) -> str:
+ return x
+
+ async def child(x: int | None) -> ToolResult:
+ return await forward(x=str(x))
+
+ tool = Tool.from_tool(parent, transform_fn=child, name="g")
+
+ prop = tool.parameters["properties"]["x"]
+ validator = jsonschema.Draft202012Validator(tool.parameters)
+ assert "type" not in prop or prop.get("type") != "string"
+ assert validator.is_valid({"x": 5})
+ assert validator.is_valid({"x": None})
+ assert not validator.is_valid({"x": "hello"})
+
+ async with Client(FastMCP(tools=[tool])) as client:
+ result = await client.call_tool("g", {"x": 5})
+ assert result.data == "5"
+
+
+async def test_arg_transform_type_keeps_transform_fn_default():
+ """ArgTransform(type=...) must not drop defaults declared on transform_fn."""
+
+ @Tool.from_function
+ def parent(x: str) -> str:
+ return x
+
+ async def child(x: int | None = 7) -> ToolResult:
+ return await forward(x=str(x) if x is not None else "")
+
+ tool = Tool.from_tool(
+ parent,
+ transform_fn=child,
+ name="with_default",
+ transform_args={"x": ArgTransform(type=int | None)},
+ )
+
+ prop = tool.parameters["properties"]["x"]
+ assert prop.get("default") == 7
+ assert "x" not in tool.parameters.get("required", [])
+
+ validator = jsonschema.Draft202012Validator(tool.parameters)
+ assert validator.is_valid({})
+ assert validator.is_valid({"x": 5})
+
+
+async def test_transform_fn_reannotation_preserves_parent_validation_keywords():
+ """transform_fn re-annotations must keep parent validation when the type kind is unchanged."""
+
+ @Tool.from_function
+ def parent(
+ mode: Literal["fast", "slow"],
+ n: Annotated[int, Field(ge=1, le=10)],
+ s: Annotated[str, Field(pattern=r"^[a-z]+$", min_length=3)],
+ ) -> str:
+ return f"{mode}:{n}:{s}"
+
+ async def child(mode: str, n: int, s: str) -> ToolResult:
+ return await forward(mode=mode, n=n, s=s)
+
+ tool = Tool.from_tool(
+ parent,
+ transform_fn=child,
+ transform_args={"mode": ArgTransform(description="how fast")},
+ )
+
+ props = tool.parameters["properties"]
+ assert props["mode"] == {
+ "description": "how fast",
+ "enum": ["fast", "slow"],
+ "type": "string",
+ }
+ assert props["n"] == {"maximum": 10, "minimum": 1, "type": "integer"}
+ assert props["s"] == {
+ "minLength": 3,
+ "pattern": "^[a-z]+$",
+ "type": "string",
+ }
+
+
async def test_forward_with_argument_mapping(add_tool):
async def custom_fn(new_x: int, **kwargs) -> str:
result = await forward(new_x=new_x, **kwargs)