Skip to content

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

Keep $ref pointers when inlining would produce an oversized schema (#5421)

Jeremiah Lowin54657de2e00e
diff --git a/docs/servers/server.mdx b/docs/servers/server.mdx
index ee778f887..7ec9ca4a4 100644
--- a/docs/servers/server.mdx
+++ b/docs/servers/server.mdx
@@ -199,7 +199,7 @@ These parameters tune how the server processes requests and communicates with cl
</ParamField>
<ParamField body="dereference_schemas" type="bool" default="True">
- Automatically dereference `$ref` pointers in JSON schemas generated from complex Pydantic models. Most clients require flat schemas without `$ref`, so this should usually stay enabled
+ Automatically dereference `$ref` pointers in JSON schemas generated from complex Pydantic models. Most clients require flat schemas without `$ref`, so this should usually stay enabled. Schemas whose inlined form would be very large keep their `$defs`, with only a root-level `$ref` resolved, as recursive schemas already do.
</ParamField>
<ParamField body="cache_ttl" type="int | None" default="None">
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index 7eb320555..fb06ddb63 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -206,7 +206,7 @@ Inline sync calls have no cancellation checkpoints, so `timeout` cannot interrup
By default, FastMCP converts Python functions into MCP tools by inspecting the function's signature and type annotations. This allows you to use standard Python type annotations for your tools. In general, the framework strives to "just work": idiomatic Python behaviors like parameter defaults and type annotations are automatically translated into MCP schemas. However, there are a number of ways to customize the behavior of your tools.
<Note>
-FastMCP automatically dereferences `$ref` entries in tool schemas to ensure compatibility with MCP clients that don't fully support JSON Schema references (e.g., VS Code Copilot, Claude Desktop). This means complex Pydantic models with shared types are inlined in the schema rather than using `$defs` references.
+FastMCP automatically dereferences `$ref` entries in tool schemas to ensure compatibility with MCP clients that don't fully support JSON Schema references (e.g., VS Code Copilot, Claude Desktop). This means complex Pydantic models with shared types are inlined in the schema rather than using `$defs` references. Schemas whose inlined form would be very large keep their `$defs`, with only a root-level `$ref` resolved, as recursive schemas already do.
Dereferencing happens at serve-time via middleware, so your schemas are stored with `$ref` intact and only inlined when sent to clients. If you know your clients handle `$ref` correctly and prefer smaller schemas, you can opt out:
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema.py b/fastmcp_slim/fastmcp/utilities/json_schema.py
index 5bc83d184..e9f2ec778 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema.py
@@ -1,7 +1,10 @@
from __future__ import annotations
from collections import defaultdict
+from collections.abc import Sequence
+from contextlib import suppress
from typing import Any
+from urllib.parse import unquote
def replace_refs(*args: Any, **kwargs: Any) -> Any:
@@ -45,51 +48,145 @@ def _copy_schema(schema: dict[str, Any]) -> dict[str, Any]:
return root
-def _defs_have_cycles(defs: dict[str, Any]) -> bool:
- """Check whether any definitions in ``$defs`` form a reference cycle.
+# Inlining a `$ref` copies its target, so an acyclic reference graph can expand
+# to many times its own size. `dereference_refs` only inlines when the result
+# stays within these limits; larger graphs keep their references.
+_MAX_INLINED_NODES = 100_000
+_MAX_INLINED_DEPTH = 128
+_MAX_INLINED_TEXT = 5_000_000
+_MAX_ROOT_REF_HOPS = 32
- A cycle means a definition directly or transitively references itself
- (e.g. Node β†’ children β†’ Node, or A β†’ B β†’ A). ``jsonref.replace_refs``
- silently produces Python-level object cycles for these, which Pydantic's
- serializer rejects.
+
+class _CannotInline(Exception):
+ """A schema's local references can't be inlined within the limits."""
+
+
+def _resolve_local_ref(
+ schema: dict[str, Any], ref: str, _hops: list[int] | None = None
+) -> Any:
+ """Resolve a local `$ref` (`#...`) by walking its JSON pointer through *schema*.
+
+ This uses the same pointer syntax as `jsonref` but doesn't normalize the
+ reference as a URL, so it can pick a different target than `jsonref` for
+ unusual pointers. `dereference_refs` therefore measures the result
+ `jsonref` actually built as well.
+
+ Like `jsonref`, a pointer that reaches a node that is itself a local
+ `$ref` continues through that reference's target, so
+ `#/$defs/Alias/properties/x` resolves when `Alias` refers to another
+ definition. The number of such references followed during one lookup is
+ limited, which also stops reference cycles. The root itself is never
+ followed, so a root-level `$ref` doesn't redirect its own pointers.
"""
- if not defs:
- return False
+ hops = _hops if _hops is not None else [0]
+ fragment = ref[1:]
+ 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:
+ inner = node["$ref"]
+ if not isinstance(inner, str) or not inner.startswith("#"):
+ break
+ hops[0] += 1
+ if hops[0] > _MAX_ROOT_REF_HOPS:
+ raise _CannotInline(f"Too many references in pointer: {ref}")
+ node = _resolve_local_ref(schema, inner, hops)
+ key: str | int = part.replace("~1", "/").replace("~0", "~")
+ if isinstance(node, Sequence):
+ with suppress(ValueError):
+ key = int(key)
+ try:
+ node = node[key]
+ except (LookupError, TypeError) as e:
+ raise _CannotInline(f"Unresolvable reference: {ref}") from e
+ return node
+
+
+def _within_inline_limits(root: dict[str, Any], *, follow_refs: bool) -> bool:
+ """Check the node count and depth of *root* once fully expanded.
+
+ Containers that appear in several places are measured once and the result
+ reused, so the walk is linear in the number of distinct containers.
+ Reaching a container again while it is still being measured means there
+ is a cycle, which can't be expanded.
+
+ With *follow_refs*, each local `$ref` also counts the target found by
+ `_resolve_local_ref`, which measures what inlining *root* would produce
+ without building it. The measurement covers the whole schema, including
+ unused `$defs` entries and keywords next to `$ref`, because
+ `dereference_refs` processes both. Without *follow_refs*, `$ref` values
+ are plain data, which measures a structure that is already inlined.
+ """
+ # (nodes, height) of each measured container, by id.
+ sizes: dict[int, tuple[int, int]] = {}
+ in_progress: set[int] = set()
+
+ def measure(node: dict[str, Any] | list[Any], depth: int) -> tuple[int, int]:
+ if depth > _MAX_INLINED_DEPTH:
+ raise _CannotInline("Inlined schema is too deep")
+ identity = id(node)
+ if identity in sizes:
+ nodes, height = sizes[identity]
+ elif identity in in_progress:
+ raise _CannotInline("References form a cycle")
+ else:
+ in_progress.add(identity)
+ children = list(node.values()) if isinstance(node, dict) else node
+ if follow_refs and isinstance(node, dict):
+ ref = node.get("$ref")
+ if isinstance(ref, str) and ref.startswith("#"):
+ children = [*children, _resolve_local_ref(root, ref)]
+ nodes, height = 1, 0
+ for child in children:
+ if isinstance(child, dict | list):
+ child_nodes, child_height = measure(child, depth + 1)
+ nodes += child_nodes
+ height = max(height, child_height + 1)
+ else:
+ nodes += 1
+ if nodes > _MAX_INLINED_NODES:
+ raise _CannotInline("Inlined schema is too large")
+ in_progress.remove(identity)
+ sizes[identity] = nodes, height
+ if depth + height > _MAX_INLINED_DEPTH:
+ raise _CannotInline("Inlined schema is too deep")
+ return nodes, height
- # Build adjacency: def_name -> set of def_names it references.
- edges: dict[str, set[str]] = defaultdict(set)
-
- def _collect_refs(obj: Any, source: str) -> None:
- if isinstance(obj, dict):
- ref = obj.get("$ref")
- if isinstance(ref, str) and ref.startswith("#/$defs/"):
- edges[source].add(ref.split("/")[-1])
- for v in obj.values():
- _collect_refs(v, source)
- elif isinstance(obj, list):
- for item in obj:
- _collect_refs(item, source)
-
- for name, definition in defs.items():
- _collect_refs(definition, name)
-
- # DFS cycle detection.
- UNVISITED, IN_STACK, DONE = 0, 1, 2
- state: dict[str, int] = defaultdict(int)
-
- def _has_cycle(node: str) -> bool:
- state[node] = IN_STACK
- for neighbor in edges.get(node, ()):
- if neighbor not in defs:
- continue
- if state[neighbor] == IN_STACK:
- return True
- if state[neighbor] == UNVISITED and _has_cycle(neighbor):
- return True
- state[node] = DONE
+ try:
+ measure(root, 0)
+ except (_CannotInline, RecursionError):
return False
+ return True
- return any(state[name] == UNVISITED and _has_cycle(name) for name in defs)
+
+def _text_within_limit(schema: dict[str, Any]) -> bool:
+ """Check the total length of every key and scalar value in *schema*.
+
+ Inlining shares scalar objects rather than copying them, so a repeated
+ long string or large number costs little to build but still adds to the
+ serialized size. Numbers count at least their decimal digits and sign.
+ """
+ total = 0
+ stack: list[Any] = [schema]
+ while stack:
+ node = stack.pop()
+ if isinstance(node, dict):
+ total += sum(len(key) for key in node if isinstance(key, str))
+ stack.extend(node.values())
+ elif isinstance(node, list):
+ stack.extend(node)
+ elif isinstance(node, str):
+ total += len(node)
+ elif isinstance(node, bool) or node is None:
+ total += 5
+ elif isinstance(node, int):
+ # A bound on the decimal digits that avoids converting huge ints.
+ total += node.bit_length() // 3 + 2
+ elif isinstance(node, float):
+ total += len(repr(node))
+ if total > _MAX_INLINED_TEXT:
+ return False
+ return True
def _strip_remote_refs(obj: Any) -> Any:
@@ -192,9 +289,9 @@ def dereference_refs(schema: dict[str, Any]) -> dict[str, Any]:
This is necessary because some MCP clients (e.g., VS Code Copilot) don't
properly handle $ref in tool input schemas.
- For self-referencing/circular schemas where full dereferencing is not possible,
- this function falls back to resolving only the root-level $ref while preserving
- $defs for nested references.
+ For circular schemas, and for schemas whose inlined form would be very large
+ or deeply nested, this function falls back to resolving only the root-level
+ $ref while preserving $defs for nested references.
Only local ``$ref`` values (those starting with ``#``) are resolved.
Remote URIs (``http://``, ``file://``, etc.) are stripped before
@@ -219,11 +316,11 @@ def dereference_refs(schema: dict[str, Any]) -> dict[str, Any]:
# Strip any remote $ref values before processing to prevent SSRF / LFI.
schema = _strip_remote_refs(schema)
- # Circular $defs can't be fully inlined β€” jsonref.replace_refs produces
- # Python dicts with object-identity cycles that Pydantic's model_dump
- # rejects with "Circular reference detected (id repeated)".
- # Detect cycles up front and fall back to root-only resolution.
- if _defs_have_cycles(schema.get("$defs", {})):
+ # Check before inlining anything. Circular references can't be inlined:
+ # jsonref.replace_refs produces Python dicts with object-identity cycles
+ # that Pydantic's model_dump rejects. Acyclic graphs can still expand far
+ # beyond their own size, so oversized results are refused as well.
+ if not _within_inline_limits(schema, follow_refs=True):
return resolve_root_ref(schema)
# Most schema operations do not dereference. Keep jsonref (and its requests
@@ -238,8 +335,7 @@ def dereference_refs(schema: dict[str, Any]) -> dict[str, Any]:
# Merge sibling keywords that were lost during dereferencing
# Pydantic puts description, default, examples as siblings to $ref
- defs = schema.get("$defs", {})
- merged = _merge_ref_siblings(schema, dereferenced, defs)
+ merged = _merge_ref_siblings(schema, dereferenced, schema)
# Type assertion: top-level schema is always a dict
assert isinstance(merged, dict)
dereferenced = merged
@@ -248,6 +344,12 @@ def dereference_refs(schema: dict[str, Any]) -> dict[str, Any]:
if "$defs" in dereferenced:
dereferenced = {k: v for k, v in dereferenced.items() if k != "$defs"}
+ # jsonref can resolve some pointers to different targets than the
+ # check above, so measure what it built (shared containers, not yet
+ # copied) before the discriminator pass copies the whole tree.
+ if not _within_inline_limits(dereferenced, follow_refs=False):
+ return resolve_root_ref(schema)
+
# Strip `discriminator` keys β€” they contain `mapping` values that
# point at `#/$defs/...` entries we just removed. `discriminator`
# is an OpenAPI extension; after inlining, the `anyOf` variants
@@ -255,9 +357,11 @@ def dereference_refs(schema: dict[str, Any]) -> dict[str, Any]:
# mapping redundant.
dereferenced = _strip_discriminator(dereferenced)
+ if not _text_within_limit(dereferenced):
+ return resolve_root_ref(schema)
return dereferenced
- except (JsonRefError, RecursionError):
+ except (JsonRefError, RecursionError, _CannotInline):
# Self-referencing/circular schemas can't be fully dereferenced.
# RecursionError covers circular $ref using JSON Pointer paths
# (e.g. "#/properties/nodes/items") that bypass $defs-based cycle
@@ -269,7 +373,7 @@ def dereference_refs(schema: dict[str, Any]) -> dict[str, Any]:
def _merge_ref_siblings(
original: Any,
dereferenced: Any,
- defs: dict[str, Any],
+ schema: dict[str, Any],
visited: set[str] | None = None,
) -> Any:
"""Merge sibling keywords from original $ref nodes into dereferenced schema.
@@ -281,8 +385,8 @@ def _merge_ref_siblings(
Args:
original: The original schema with $ref and potential siblings
dereferenced: The schema after jsonref processing
- defs: The $defs from the original schema, for looking up referenced definitions
- visited: Set of definition names already being processed (prevents cycles)
+ schema: The original root schema, for looking up referenced definitions
+ visited: Set of references already being processed (prevents cycles)
Returns:
The dereferenced schema with sibling keywords restored
@@ -296,15 +400,19 @@ def _merge_ref_siblings(
ref = original["$ref"]
siblings = {k: v for k, v in original.items() if k not in ("$ref", "$defs")}
- # Look up the referenced definition to process its nested siblings
- if isinstance(ref, str) and ref.startswith("#/$defs/"):
- def_name = ref.split("/")[-1]
- # Prevent infinite recursion on circular references
- if def_name in defs and def_name not in visited:
- # Recursively process the definition's content for nested siblings
- dereferenced = _merge_ref_siblings(
- defs[def_name], dereferenced, defs, visited | {def_name}
- )
+ # Process the definition jsonref inlined here for its nested siblings.
+ # Prevent infinite recursion on circular references.
+ if (
+ isinstance(ref, str)
+ and ref.startswith("#/$defs/")
+ and ref not in visited
+ ):
+ dereferenced = _merge_ref_siblings(
+ _resolve_local_ref(schema, ref),
+ dereferenced,
+ schema,
+ visited | {ref},
+ )
if siblings:
# Merge local siblings, which take precedence
@@ -317,7 +425,7 @@ def _merge_ref_siblings(
result = {}
for key, value in dereferenced.items():
if key in original:
- result[key] = _merge_ref_siblings(original[key], value, defs, visited)
+ result[key] = _merge_ref_siblings(original[key], value, schema, visited)
else:
result[key] = value
return result
@@ -326,7 +434,7 @@ def _merge_ref_siblings(
# Process list items in parallel
min_len = min(len(original), len(dereferenced))
return [
- _merge_ref_siblings(o, d, defs, visited)
+ _merge_ref_siblings(o, d, schema, visited)
for o, d in zip(original[:min_len], dereferenced[:min_len], strict=False)
] + dereferenced[min_len:]
@@ -356,33 +464,50 @@ def resolve_root_ref(schema: dict[str, Any]) -> dict[str, Any]:
>>> resolved = resolve_root_ref(schema)
>>> # Result: {"type": "object", "properties": {...}, "$defs": {...}}
"""
- # Only resolve if we have $ref at root level with $defs but no explicit type
- if "$ref" in schema and "$defs" in schema and "type" not in schema:
- ref = schema["$ref"]
- # Only handle local $defs references
- if isinstance(ref, str) and ref.startswith("#/$defs/"):
- def_name = ref.split("/")[-1]
- defs = schema["$defs"]
- if def_name in defs:
- # Create a new schema by copying the referenced definition
- resolved = dict(defs[def_name])
-
- # Preserve root-level sibling metadata from the original schema.
- # Pydantic may put user-facing fields such as title, description,
- # default, or examples next to the root $ref. Those fields still
- # describe the root schema even when we can only resolve that
- # root reference for circular schemas.
- resolved.update(
- {
- key: value
- for key, value in schema.items()
- if key not in {"$ref", "$defs"}
- }
- )
+ # Only resolve a local $ref at the root when there is no explicit type.
+ # The pointer is walked the same way `dereference_refs` measures it, so
+ # every supported form (`#/$defs/Name`, `#/definitions/Name`, escaped or
+ # percent-encoded segments) resolves to the same target. A definition
+ # that is itself only a `$ref` is an alias, so the chain is followed
+ # until a definition with its own content (or a type) is reached.
+ ref = schema.get("$ref")
+ if "type" in schema or not isinstance(ref, str) or not ref.startswith("#"):
+ return schema
+
+ # Preserve root-level sibling metadata from the original schema.
+ # Pydantic may put user-facing fields such as title, description,
+ # default, or examples next to the root $ref. Those fields still
+ # describe the root schema even when we can only resolve that
+ # root reference for circular schemas. Siblings include `$defs` (or
+ # `definitions`), which stay for nested references. Keywords on each
+ # alias are kept too, with the outer schema taking precedence.
+ resolved = {key: value for key, value in schema.items() if key != "$ref"}
+ visited: set[str] = set()
+ for _ in range(_MAX_ROOT_REF_HOPS):
+ if ref in visited:
+ return schema
+ visited.add(ref)
+ try:
+ target = _resolve_local_ref(schema, ref)
+ except _CannotInline:
+ return schema
+ if not isinstance(target, dict) or target is schema:
+ return schema
- # Preserve $defs for nested references (other fields may still use them)
- resolved["$defs"] = defs
- return resolved
+ next_ref = target.get("$ref")
+ is_alias = (
+ "type" not in target
+ and isinstance(next_ref, str)
+ and next_ref.startswith("#")
+ )
+ if is_alias:
+ kept = {key: value for key, value in target.items() if key != "$ref"}
+ else:
+ kept = target
+ resolved = {**kept, **resolved}
+ if not is_alias:
+ return resolved
+ ref = next_ref
return schema
diff --git a/tests/utilities/test_json_schema.py b/tests/utilities/test_json_schema.py
index b97153b02..62d4a3e1b 100644
--- a/tests/utilities/test_json_schema.py
+++ b/tests/utilities/test_json_schema.py
@@ -3,6 +3,7 @@ import sys
from typing import Any
from unittest.mock import patch
+import pytest
from jsonref import replace_refs
from fastmcp.utilities.json_schema import (
@@ -1026,6 +1027,95 @@ class TestResolveRootRef:
# Should return original schema unchanged
assert result is schema
+ @pytest.mark.parametrize(
+ ("defs_key", "pointers"),
+ [
+ ("$defs", ["#/$defs/Actual"]),
+ ("$defs", ["#/$defs/Alias", "#/$defs/Actual"]),
+ ("$defs", ["#/$defs/Alias1", "#/$defs/Alias2", "#/$defs/Actual"]),
+ (
+ "definitions",
+ ["#/definitions/Alias", "#/definitions/Actual"],
+ ),
+ (
+ "$defs",
+ ["#/$defs/Alias%20One", "#/$defs/Actual"],
+ ),
+ (
+ "$defs",
+ ["#/$defs/a~1b", "#/$defs/Actual"],
+ ),
+ ],
+ )
+ def test_follows_alias_chain_to_object_definition(
+ self, defs_key: str, pointers: list[str]
+ ):
+ decoded = {
+ "Alias%20One": "Alias One",
+ "a~1b": "a/b",
+ }
+ defs: dict[str, Any] = {
+ "Actual": {
+ "type": "object",
+ "properties": {"id": {"type": "string"}},
+ "required": ["id"],
+ }
+ }
+ for pointer, next_pointer in zip(pointers, pointers[1:], strict=False):
+ name = pointer.rsplit("/", 1)[1]
+ defs[decoded.get(name, name)] = {"$ref": next_pointer}
+ schema = {defs_key: defs, "$ref": pointers[0]}
+
+ result = resolve_root_ref(schema)
+
+ assert result["type"] == "object"
+ assert result["properties"] == {"id": {"type": "string"}}
+ assert result["required"] == ["id"]
+ assert "$ref" not in result
+ assert result[defs_key] == defs
+
+ def test_alias_chain_keeps_outer_siblings(self):
+ schema = {
+ "title": "Outer",
+ "$defs": {
+ "Alias": {
+ "title": "Middle",
+ "description": "Middle text",
+ "$ref": "#/$defs/Actual",
+ },
+ "Actual": {
+ "title": "Inner",
+ "type": "object",
+ "properties": {"id": {"type": "string"}},
+ },
+ },
+ "$ref": "#/$defs/Alias",
+ }
+
+ result = resolve_root_ref(schema)
+
+ assert result["type"] == "object"
+ assert result["title"] == "Outer"
+ assert result["description"] == "Middle text"
+
+ @pytest.mark.parametrize(
+ "defs",
+ [
+ {"A": {"$ref": "#/$defs/A"}},
+ {"A": {"$ref": "#/$defs/B"}, "B": {"$ref": "#/$defs/A"}},
+ {
+ "A": {"$ref": "#/$defs/B"},
+ "B": {"$ref": "#/$defs/C"},
+ "C": {"$ref": "#/$defs/A"},
+ },
+ {"A": {"$ref": "#/$defs/Missing"}},
+ ],
+ )
+ def test_alias_cycle_or_missing_target_is_unchanged(self, defs: dict[str, Any]):
+ schema = {"$defs": defs, "$ref": "#/$defs/A"}
+
+ assert resolve_root_ref(schema) is schema
+
class TestStripRemoteRefs:
"""Tests for _strip_remote_refs which prevents SSRF/LFI via $ref."""
diff --git a/tests/utilities/test_json_schema_expansion.py b/tests/utilities/test_json_schema_expansion.py
new file mode 100644
index 000000000..ce23c1f7a
--- /dev/null
+++ b/tests/utilities/test_json_schema_expansion.py
@@ -0,0 +1,269 @@
+"""`dereference_refs` inlines references unless the result would be very large."""
+
+from collections.abc import Callable
+from typing import Any
+
+import pytest
+
+from fastmcp import Client, FastMCP
+from fastmcp.tools import Tool
+from fastmcp.utilities.json_schema import dereference_refs
+
+
+def nested_union_schema(
+ levels: int,
+ *,
+ defs_key: str = "$defs",
+ pointer: str = "#/$defs/{}",
+) -> dict[str, Any]:
+ """Each level is a union of three references to the level below."""
+ defs: dict[str, Any] = {"L0": {"type": "string"}}
+ for i in range(1, levels + 1):
+ defs[f"L{i}"] = {"anyOf": [{"$ref": pointer.format(f"L{i - 1}")}] * 3}
+ return {
+ "type": "object",
+ "properties": {"x": {"$ref": pointer.format(f"L{levels}")}},
+ defs_key: defs,
+ }
+
+
+def lists_through_refs_schema(levels: int) -> dict[str, Any]:
+ """Each `P{i}` refers to `D{i}`, so `#/$defs/P{i}/x` means `D{i}["x"]`."""
+ defs: dict[str, Any] = {"D0": {"x": [0]}, "P0": {"$ref": "#/$defs/D0", "x": 0}}
+ for i in range(1, levels + 1):
+ defs[f"D{i}"] = {"x": [{"$ref": f"#/$defs/P{i - 1}/x"}] * 3}
+ defs[f"P{i}"] = {"$ref": f"#/$defs/D{i}", "x": 0}
+ return {
+ "type": "object",
+ "properties": {"v": {"items": {"$ref": f"#/$defs/P{levels}/x"}}},
+ "$defs": defs,
+ }
+
+
+def lists_with_tab_in_pointers_schema(levels: int) -> dict[str, Any]:
+ """URL parsing removes the tab, so `#/$defs/D\\t{i}` means `D{i}`."""
+ defs: dict[str, Any] = {"D0": [0]}
+ for i in range(1, levels + 1):
+ defs[f"D{i}"] = [{"$ref": f"#/$defs/D\t{i - 1}"}] * 3
+ defs[f"D\t{i - 1}"] = 0
+ return {
+ "type": "object",
+ "properties": {"v": {"items": {"$ref": f"#/$defs/D{levels}"}}},
+ "$defs": defs,
+ }
+
+
+POINTER_FORMS = [
+ pytest.param("$defs", "#/$defs/{}", id="defs"),
+ pytest.param("definitions", "#/definitions/{}", id="definitions"),
+ pytest.param("definitions", "#definitions/{}", id="no-leading-slash"),
+ pytest.param("definitions", "#//definitions/{}", id="double-slash"),
+ pytest.param("my defs", "#/my%20defs/{}", id="percent-encoded"),
+ pytest.param("my/defs", "#/my~1defs/{}", id="tilde-encoded"),
+]
+
+LIST_SCHEMAS = [lists_through_refs_schema, lists_with_tab_in_pointers_schema]
+
+
[email protected](("defs_key", "pointer"), POINTER_FORMS)
+def test_large_schema_keeps_defs(defs_key: str, pointer: str) -> None:
+ schema = nested_union_schema(9, defs_key=defs_key, pointer=pointer)
+ assert dereference_refs(schema) == schema
+
+
[email protected](("defs_key", "pointer"), POINTER_FORMS)
+def test_schema_is_inlined(defs_key: str, pointer: str) -> None:
+ schema = nested_union_schema(4, defs_key=defs_key, pointer=pointer)
+ value = dereference_refs(schema)["properties"]["x"]
+ for _ in range(4):
+ assert len(value["anyOf"]) == 3
+ value = value["anyOf"][0]
+ assert value == {"type": "string"}
+
+
[email protected]("build", LIST_SCHEMAS)
+def test_large_list_schema_keeps_defs(
+ build: Callable[[int], dict[str, Any]],
+) -> None:
+ schema = build(11)
+ assert dereference_refs(schema) == schema
+
+
[email protected]("build", LIST_SCHEMAS)
+def test_list_schema_is_inlined(build: Callable[[int], dict[str, Any]]) -> None:
+ value = dereference_refs(build(3))["properties"]["v"]["items"]
+ for _ in range(3):
+ assert len(value) == 3
+ value = value[0]
+ assert value == [0]
+
+
+def alias_pointer_schema() -> dict[str, Any]:
+ """`#/$defs/Alias/properties/value` passes through `Alias`, a reference to `Actual`."""
+ return {
+ "type": "object",
+ "properties": {"v": {"$ref": "#/$defs/Alias/properties/value"}},
+ "$defs": {
+ "Alias": {"$ref": "#/$defs/Actual"},
+ "Actual": {
+ "type": "object",
+ "properties": {"value": {"type": "string"}},
+ },
+ },
+ }
+
+
+def test_pointer_through_alias_definition_is_inlined() -> None:
+ result = dereference_refs(alias_pointer_schema())
+ assert result["properties"]["v"] == {"type": "string"}
+ assert "$defs" not in result
+
+
+def test_pointer_through_chain_of_aliases_is_inlined() -> None:
+ schema = alias_pointer_schema()
+ schema["$defs"]["Alias"] = {"$ref": "#/$defs/Alias2"}
+ schema["$defs"]["Alias2"] = {"$ref": "#/$defs/Actual"}
+ result = dereference_refs(schema)
+ assert result["properties"]["v"] == {"type": "string"}
+
+
+def test_pointer_through_cyclic_aliases_keeps_defs() -> None:
+ schema = alias_pointer_schema()
+ schema["$defs"]["Alias"] = {"$ref": "#/$defs/Alias2"}
+ schema["$defs"]["Alias2"] = {"$ref": "#/$defs/Alias"}
+ assert dereference_refs(schema) == schema
+
+
+def test_pointer_through_unresolvable_alias_keeps_defs() -> None:
+ schema = alias_pointer_schema()
+ schema["$defs"]["Alias"] = {"$ref": "#/$defs/Missing"}
+ assert dereference_refs(schema) == schema
+
+
+def test_large_unused_definitions_keep_defs() -> None:
+ schema = nested_union_schema(9)
+ schema["properties"] = {}
+ assert dereference_refs(schema) == schema
+
+
+def test_repeated_long_description_keeps_defs() -> None:
+ schema = {
+ "type": "object",
+ "properties": {f"p{i}": {"$ref": "#/$defs/Leaf"} for i in range(40)},
+ "$defs": {"Leaf": {"type": "string", "description": "x" * 150_000}},
+ }
+ assert dereference_refs(schema) == schema
+
+
+def test_repeated_large_examples_keep_defs() -> None:
+ schema = {
+ "type": "object",
+ "properties": {f"p{i}": {"$ref": "#/$defs/Leaf"} for i in range(150)},
+ "$defs": {"Leaf": {"type": "integer", "examples": [10**4000] * 10}},
+ }
+ assert dereference_refs(schema) == schema
+
+
+def test_large_discriminated_union_keeps_defs() -> None:
+ schema = {
+ "type": "object",
+ "properties": {
+ "x": {
+ "discriminator": {"propertyName": "t" * 3000},
+ "anyOf": [{"type": "object"}] * 2000,
+ }
+ },
+ "$defs": {},
+ }
+ assert dereference_refs(schema) == schema
+
+
+def test_long_reference_chain_keeps_defs() -> None:
+ defs: dict[str, Any] = {
+ f"L{i}": {"$ref": f"#/$defs/L{i - 1}"} for i in range(1999, 0, -1)
+ }
+ defs["L0"] = {"type": "string"}
+ schema = {
+ "type": "object",
+ "properties": {"x": {"$ref": "#/$defs/L1999"}},
+ "$defs": defs,
+ }
+ assert dereference_refs(schema) == schema
+
+
+def test_large_schema_still_resolves_root_reference() -> None:
+ schema = nested_union_schema(9)
+ defs = schema.pop("$defs")
+ defs["Root"] = schema
+ result = dereference_refs({"$ref": "#/$defs/Root", "$defs": defs})
+ assert result == {**schema, "$defs": defs}
+
+
[email protected](("defs_key", "pointer"), POINTER_FORMS)
+def test_large_schema_resolves_root_reference_in_every_pointer_form(
+ defs_key: str, pointer: str
+) -> None:
+ schema = nested_union_schema(9, defs_key=defs_key, pointer=pointer)
+ defs = schema.pop(defs_key)
+ defs["Root"] = schema
+ result = dereference_refs({"$ref": pointer.format("Root"), defs_key: defs})
+ assert result == {**schema, defs_key: defs}
+
+
[email protected]("aliases", [1, 2, 3])
+def test_large_schema_resolves_root_reference_through_aliases(aliases: int) -> None:
+ schema = nested_union_schema(9)
+ defs = schema.pop("$defs")
+ defs["Actual"] = schema
+ names = [f"Alias{i}" for i in range(aliases)] + ["Actual"]
+ for name, target in zip(names, names[1:], strict=False):
+ defs[name] = {"$ref": f"#/$defs/{target}"}
+ result = dereference_refs({"$ref": f"#/$defs/{names[0]}", "$defs": defs})
+ assert result == {**schema, "$defs": defs}
+
+
+def test_sibling_keywords_come_from_the_referenced_definition() -> None:
+ schema = {
+ "type": "object",
+ "properties": {"x": {"$ref": "#/$defs/Holder/properties/Item"}},
+ "$defs": {
+ "Holder": {"properties": {"Item": {"type": "integer"}}},
+ "Item": {"$ref": "#/$defs/Text", "description": "A text item"},
+ "Text": {"type": "string"},
+ },
+ }
+ assert dereference_refs(schema)["properties"]["x"] == {"type": "integer"}
+
+
+ ("key", "pointer"),
+ [
+ ("", "#/properties/"),
+ ("a/b", "#/properties/a~1b"),
+ ("a b", "#/properties/a%20b"),
+ ("a~b", "#/properties/a~0b"),
+ ("a", "#properties/a"),
+ ],
+)
+def test_pointer_segments_resolve_like_jsonref(key: str, pointer: str) -> None:
+ schema = {"properties": {key: {"type": "string"}, "copy": {"$ref": pointer}}}
+ assert dereference_refs(schema)["properties"]["copy"] == {"type": "string"}
+
+
+async def test_list_tools_keeps_defs_for_large_schema() -> None:
+ def echo(x: str) -> str:
+ return x
+
+ schema = nested_union_schema(9)
+ server = FastMCP("test")
+ server.add_tool(
+ Tool.from_function(echo).model_copy(
+ update={"parameters": schema, "output_schema": schema}
+ )
+ )
+
+ async with Client(server) as client:
+ tools = await client.list_tools()
+
+ assert tools[0].input_schema == schema
+ assert tools[0].output_schema == schema