Skip to content

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

fix: preserve referenced schema definitions (#5588)

Jialiang Liang5f1d1529ca3e
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema.py b/fastmcp_slim/fastmcp/utilities/json_schema.py
index 3a4079e41..fcec042eb 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema.py
@@ -80,7 +80,7 @@ def _resolve_local_ref(
"""
hops = _hops if _hops is not None else [0]
fragment = ref[1:]
- parts = unquote(fragment.lstrip("/")).split("/") if fragment else []
+ parts = unquote(fragment).lstrip("/").split("/") if fragment else []
node: Any = schema
for part in parts:
while node is not schema and isinstance(node, dict) and "$ref" in node:
@@ -120,7 +120,7 @@ def ref_target_name(
called ``Alias One`` as ``Alias%20One``, and neither decoded name appears
in the raw text.
"""
- parts = unquote(ref[1:].lstrip("/")).split("/")
+ parts = unquote(ref[1:]).lstrip("/").split("/")
for root in roots:
depth = len(root)
if parts[:depth] == list(root) and len(parts) > depth and parts[depth]:
@@ -783,8 +783,9 @@ def _single_pass_optimize(
# still pins the referenced $def as "used".
if prune_defs:
ref = node.get("$ref")
- if isinstance(ref, str) and ref.startswith("#/$defs/"):
- # Decode the pointer: escaped, percent-encoded, and
+ if isinstance(ref, str) and ref.startswith("#"):
+ # Decode the pointer before matching it: escaped,
+ # percent-encoded (including `%24defs` and `%2F`), and
# sub-pointer references resolve to a definition whose
# name is not the raw text of the segment.
referenced_def = ref_target_name(ref)
diff --git a/tests/tools/tool_transform/test_schemas.py b/tests/tools/tool_transform/test_schemas.py
index 09d70df78..7373f8faa 100644
--- a/tests/tools/tool_transform/test_schemas.py
+++ b/tests/tools/tool_transform/test_schemas.py
@@ -3,6 +3,7 @@ from typing import Annotated, Any
import pytest
from dirty_equals import IsList
from inline_snapshot import snapshot
+from jsonschema import Draft202012Validator
from mcp_types import TextContent
from pydantic import BaseModel, Field, TypeAdapter
@@ -19,6 +20,28 @@ def get_property(tool: Tool, name: str) -> dict[str, Any]:
return tool.parameters["properties"][name]
+def test_renaming_tool_preserves_encoded_parameter_reference():
+ def echo(value: str) -> str:
+ return value
+
+ schema = {
+ "type": "object",
+ "properties": {"value": {"$ref": "#/$defs/Display~1name"}},
+ "required": ["value"],
+ "$defs": {"Display/name": {"type": "string", "minLength": 1}},
+ }
+ parent = FunctionTool(name="echo", parameters=schema, fn=echo)
+
+ transformed = Tool.from_tool(parent, name="renamed_echo")
+ advertised_schema = transformed.to_mcp_tool().input_schema
+
+ assert advertised_schema["$defs"] == schema["$defs"]
+ validator = Draft202012Validator(advertised_schema)
+ assert validator.is_valid({"value": "hello"})
+ assert not validator.is_valid({"value": ""})
+ assert parent.parameters == schema
+
+
@pytest.fixture
def add_tool() -> FunctionTool:
def add(
diff --git a/tests/utilities/test_json_schema_references.py b/tests/utilities/test_json_schema_references.py
new file mode 100644
index 000000000..d483099e9
--- /dev/null
+++ b/tests/utilities/test_json_schema_references.py
@@ -0,0 +1,67 @@
+import pytest
+
+from fastmcp.utilities.json_schema import compress_schema
+
+
+class TestDefinitionReferences:
+ @pytest.mark.parametrize(
+ ("definition_name", "ref"),
+ [
+ ("Name", "#/$defs/Name"),
+ ("Name/part", "#/$defs/Name~1part"),
+ ("Name~part", "#/$defs/Name~0part"),
+ ("Name~1part", "#/$defs/Name~01part"),
+ ("Name part", "#/$defs/Name%20part"),
+ ("Name%2Fpart", "#/$defs/Name%252Fpart"),
+ ("Name", "#/%24defs/Name"),
+ ("Name", "#%2F$defs%2FName"),
+ ],
+ )
+ def test_keeps_encoded_definition_references(self, definition_name: str, ref: str):
+ schema = {
+ "type": "object",
+ "properties": {"value": {"$ref": "#/$defs/Alias"}},
+ "$defs": {
+ "Alias": {"$ref": ref},
+ definition_name: {"type": "string"},
+ "Unused": {"type": "number"},
+ },
+ }
+
+ result = compress_schema(schema)
+
+ assert result["$defs"] == {
+ "Alias": {"$ref": ref},
+ definition_name: {"type": "string"},
+ }
+ assert result["properties"] == schema["properties"]
+
+ @pytest.mark.parametrize(
+ "ref",
+ [
+ "#/$defs/Envelope/properties/name",
+ "#/$defs/Envelope%2Fproperties%2Fname",
+ ],
+ )
+ def test_keeps_owner_of_nested_definition_reference(self, ref: str):
+ envelope = {
+ "type": "object",
+ "properties": {"name": {"$ref": "#/$defs/Leaf"}},
+ }
+ schema = {
+ "type": "object",
+ "properties": {"value": {"$ref": ref}},
+ "$defs": {
+ "Envelope": envelope,
+ "Leaf": {"type": "string"},
+ "name": {"type": "number"},
+ },
+ }
+
+ result = compress_schema(schema)
+
+ assert result["$defs"] == {
+ "Envelope": envelope,
+ "Leaf": {"type": "string"},
+ }
+ assert result["properties"] == schema["properties"]