Skip to content

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

fix(tool_transform): hoist $defs to schema root when ArgTransform introduces them (#4101)

Sarthak Bhardwajb8597f941df1
diff --git a/src/fastmcp/tools/tool_transform.py b/src/fastmcp/tools/tool_transform.py
index 1dcc52662..e7e0cea06 100644
--- a/src/fastmcp/tools/tool_transform.py
+++ b/src/fastmcp/tools/tool_transform.py
@@ -680,11 +680,27 @@ class TransformedTool(Tool):
)
if transform_result:
- new_name, new_schema, is_required = transform_result
+ new_name, new_schema, is_required, extracted_defs = transform_result
new_props[new_name] = new_schema
new_to_old[new_name] = old_name
if is_required:
new_required.add(new_name)
+ # Hoist any $defs introduced by an ArgTransform(type=...) so that
+ # $ref values like "#/$defs/..." resolve at the schema root.
+ # Fail loudly on key collisions whose schemas differ, since
+ # silently overwriting would point earlier $ref values at the
+ # wrong type. Identical re-introductions are a no-op.
+ for def_name, def_schema in extracted_defs.items():
+ existing = parent_defs.get(def_name)
+ if existing is not None and existing != def_schema:
+ raise ValueError(
+ f"$defs collision for '{def_name}': an ArgTransform "
+ f"introduces a definition with the same name as an "
+ f"existing $defs entry but a different schema. "
+ f"Rename one of the colliding types to avoid the "
+ f"conflict."
+ )
+ parent_defs[def_name] = def_schema
schema = {
"type": "object",
@@ -741,7 +757,7 @@ class TransformedTool(Tool):
old_schema: dict[str, Any],
transform: ArgTransform,
is_required: bool,
- ) -> tuple[str, dict[str, Any], bool] | None:
+ ) -> tuple[str, dict[str, Any], bool, dict[str, Any]] | None:
"""Apply transformation to a single parameter.
This method handles the transformation of a single argument according to
@@ -754,8 +770,10 @@ class TransformedTool(Tool):
is_required: Whether the original parameter was required.
Returns:
- Tuple of (new_name, new_schema, new_is_required) if parameter should be kept,
- None if parameter should be dropped.
+ Tuple of (new_name, new_schema, new_is_required, extracted_defs) if
+ parameter should be kept, None if parameter should be dropped.
+ extracted_defs contains any $defs pulled off a type transform so the
+ caller can hoist them to the schema root.
"""
if transform.hide:
return None
@@ -792,9 +810,15 @@ class TransformedTool(Tool):
is_required = False
# Handle type transformation
+ extracted_defs: dict[str, Any] = {}
if transform.type is not NotSet:
# Use TypeAdapter to get proper JSON schema for the type
type_schema = get_cached_typeadapter(transform.type).json_schema()
+ # Strip $defs from the type schema so they can be hoisted to the
+ # root of the parent schema by the caller. Otherwise they would be
+ # 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)
@@ -802,7 +826,7 @@ class TransformedTool(Tool):
if transform.examples is not NotSet:
new_schema["examples"] = transform.examples
- return new_name, new_schema, is_required
+ return new_name, new_schema, is_required, extracted_defs
@staticmethod
def _merge_schema_with_precedence(
diff --git a/tests/tools/tool_transform/test_tool_transform.py b/tests/tools/tool_transform/test_tool_transform.py
index ba5d46555..2e0b7e975 100644
--- a/tests/tools/tool_transform/test_tool_transform.py
+++ b/tests/tools/tool_transform/test_tool_transform.py
@@ -270,6 +270,81 @@ async def test_hidden_param_prunes_defs():
}
+async def test_arg_transform_type_hoists_defs_to_root():
+ """Regression test for #4093: ArgTransform(type=...) must hoist any $defs
+ introduced by the new type to the schema root, not leave them nested
+ inside the property where $ref values like '#/$defs/...' would dangle.
+ """
+
+ class Filter(BaseModel):
+ value: str
+
+ @Tool.from_function
+ def search(query: str, filters: dict | None = None) -> str:
+ return ""
+
+ new_tool = Tool.from_tool(
+ search, transform_args={"filters": ArgTransform(type=list[Filter])}
+ )
+
+ schema = new_tool.parameters
+ assert "$defs" in schema
+ assert "Filter" in schema["$defs"]
+ assert "$defs" not in schema["properties"]["filters"]
+ assert schema["properties"]["filters"]["items"] == {"$ref": "#/$defs/Filter"}
+
+
+async def test_arg_transform_type_merges_with_parent_defs():
+ """When the parent tool already has $defs, ArgTransform(type=...) defs
+ should be merged into the existing root $defs alongside them."""
+
+ class Existing(BaseModel):
+ a: int
+
+ class Added(BaseModel):
+ b: int
+
+ @Tool.from_function
+ def tool_fn(x: Existing, y: dict | None = None) -> int:
+ return x.a + (y["b"] if y else 0)
+
+ new_tool = Tool.from_tool(
+ tool_fn, transform_args={"y": ArgTransform(type=list[Added])}
+ )
+
+ schema = new_tool.parameters
+ assert "Existing" in schema["$defs"]
+ assert "Added" in schema["$defs"]
+ assert "$defs" not in schema["properties"]["y"]
+
+
+async def test_arg_transform_type_raises_on_defs_name_collision():
+ """ArgTransform must not silently overwrite a parent's $defs entry when
+ the colliding name maps to a different schema; refs already copied from
+ the parent would then resolve to the wrong type."""
+
+ class Foo(BaseModel):
+ a: int
+
+ @Tool.from_function
+ def tool_fn(foo: Foo, other: dict | None = None) -> int:
+ return foo.a
+
+ # Parent already defines `Foo`; introduce a transform whose new type is
+ # also exposed under the `Foo` key in $defs but with a different schema.
+ # We do this by mutating the parent tool's parameters in place to plant a
+ # colliding definition, then applying a transform that re-introduces it.
+ tool_fn.parameters["$defs"]["Foo"] = {
+ "type": "object",
+ "properties": {"different": {"type": "string"}},
+ "required": ["different"],
+ "title": "Foo",
+ }
+
+ with pytest.raises(ValueError, match=r"\$defs collision for 'Foo'"):
+ Tool.from_tool(tool_fn, transform_args={"other": ArgTransform(type=list[Foo])})
+
+
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)