Skip to content

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

fix: strip titles from bare-metadata nodes (Gemini 2.5 Flash) (#3881)

Jeremiah Lowinfa9ad6cb8189
diff --git a/src/fastmcp/utilities/json_schema.py b/src/fastmcp/utilities/json_schema.py
index fc4e069c6..b33c4f945 100644
--- a/src/fastmcp/utilities/json_schema.py
+++ b/src/fastmcp/utilities/json_schema.py
@@ -304,6 +304,85 @@ def _prune_param(schema: dict[str, Any], param: str) -> dict[str, Any]:
return schema
+# JSON Schema structural keywords β€” a node containing any of these is a
+# schema, so a string "title" sibling is metadata we can safely drop.
+_SCHEMA_KEYWORDS = frozenset(
+ {
+ "type",
+ "properties",
+ "$ref",
+ "items",
+ "allOf",
+ "oneOf",
+ "anyOf",
+ "required",
+ }
+)
+
+# Pure schema-metadata keys. A node containing only these (e.g. Pydantic's
+# `{"title": "X"}` for Any-typed fields) is also a schema, just one with no
+# structural keywords alongside β€” still safe to strip title from.
+_METADATA_KEYS = frozenset(
+ {
+ "title",
+ "description",
+ "deprecated",
+ "readOnly",
+ "writeOnly",
+ }
+)
+
+# Keywords whose values are literal user data, not sub-schemas. Skipping
+# recursion here prevents `default: {"title": "X"}` from losing the "title"
+# data value because it happens to look metadata-shaped. Includes both
+# `examples` (JSON Schema draft 7+) and `example` (OpenAPI/Swagger 2.0).
+_LITERAL_KEYWORDS = frozenset({"default", "const", "examples", "example", "enum"})
+
+# Keys whose values are dicts of arbitrary-name -> sub-schema. When we see
+# these, we traverse into each sub-schema regardless of its name β€” the keys
+# are user property/definition names, not schema keywords, so a property
+# literally named "enum" or "default" must not be confused with the
+# schema keywords of the same name.
+#
+# `dependencies` is a draft-07 keyword whose values can be sub-schemas OR
+# lists of required property names; list values short-circuit in the list
+# branch, so including it here is safe for both shapes.
+_SUBSCHEMA_MAP_KEYS = frozenset(
+ {
+ "properties",
+ "patternProperties",
+ "$defs",
+ "definitions",
+ "dependentSchemas",
+ "dependencies",
+ }
+)
+
+# Keys whose values are a single sub-schema (not a dict of sub-schemas).
+# We traverse into them and treat the result as a schema node.
+# `additionalItems` is the draft-07 predecessor of `unevaluatedItems`.
+# `contentSchema` is a 2019-09+ keyword for typed string payloads.
+_SUBSCHEMA_VALUE_KEYS = frozenset(
+ {
+ "items",
+ "additionalItems",
+ "additionalProperties",
+ "contains",
+ "contentSchema",
+ "propertyNames",
+ "unevaluatedItems",
+ "unevaluatedProperties",
+ "if",
+ "then",
+ "else",
+ "not",
+ }
+)
+
+# Keys whose values are LISTS of sub-schemas.
+_SUBSCHEMA_LIST_KEYS = frozenset({"allOf", "anyOf", "oneOf", "prefixItems"})
+
+
def _single_pass_optimize(
schema: dict[str, Any],
prune_titles: bool = False,
@@ -370,13 +449,25 @@ def _single_pass_optimize(
current_def_name: str | None = None,
skip_defs_section: bool = False,
depth: int = 0,
+ in_schema: bool = True,
) -> None:
- """Traverse schema tree, collecting $ref info and applying cleanups."""
+ """Traverse schema tree, collecting $ref info and applying cleanups.
+
+ The `in_schema` flag tracks whether the current node is reached via a
+ known JSON-Schema-valued position (root, `properties` value, `items`,
+ `allOf` element, etc.). When False β€” e.g. we descended through a user
+ extension key like `x-ui` whose payload is opaque to us β€” we still
+ collect `$ref` references (they may point at `$defs` the user cares
+ about) but we skip all cleanups so we don't mutate user data that
+ happens to look metadata-shaped.
+ """
if depth > 50: # Prevent infinite recursion
return
if isinstance(node, dict):
- # Collect $ref references for unused definition removal
+ # Collect $ref references for unused definition removal. We do
+ # this regardless of `in_schema` β€” a $ref in a user extension
+ # still pins the referenced $def as "used".
if prune_defs:
ref = node.get("$ref") # type: ignore
if isinstance(ref, str) and ref.startswith("#/$defs/"):
@@ -388,58 +479,111 @@ def _single_pass_optimize(
# We're in the main schema, so this is a root reference
root_refs.add(referenced_def)
- # Apply cleanups
- # Only remove "title" if it's a schema metadata field
- # Schema objects have keywords like "type", "properties", "$ref", etc.
- # If we see these, then "title" is metadata, not a property name
- if prune_titles and "title" in node:
- # Only remove "title" if it's a string (schema metadata).
- # In a "properties" dict, "title" would be a dict (a sub-schema
- # for a parameter named "title"), which we must preserve.
- if isinstance(node["title"], str) and any( # type: ignore
- k in node
- for k in [
- "type",
- "properties",
- "$ref",
- "items",
- "allOf",
- "oneOf",
- "anyOf",
- "required",
- ]
+ # Cleanups only run when we know this node is a schema, never on
+ # user extension payloads (`json_schema_extra={"x-ui": {...}}`).
+ if in_schema:
+ # Only remove "title" when it's schema metadata. A schema
+ # node is either (a) one containing a structural keyword or
+ # (b) one containing only metadata keys β€” Pydantic emits
+ # bare `{"title": "X"}` for Any-typed fields with no sibling
+ # type/properties, and Gemini 2.5 Flash rejects those with
+ # MALFORMED_FUNCTION_CALL. The `isinstance(str)` guard
+ # protects against deleting a user property literally named
+ # "title" (its value would be a dict, not a string).
+ if (
+ prune_titles
+ and "title" in node
+ and isinstance(node["title"], str) # type: ignore
+ and (
+ any(k in node for k in _SCHEMA_KEYWORDS)
+ or all(k in _METADATA_KEYS for k in node)
+ )
):
node.pop("title") # type: ignore
- if (
- prune_additional_properties
- and node.get("additionalProperties") is False # type: ignore
- ):
- node.pop("additionalProperties") # type: ignore
+ if (
+ prune_additional_properties
+ and node.get("additionalProperties") is False # type: ignore
+ ):
+ node.pop("additionalProperties") # type: ignore
# Recursive traversal
for key, value in node.items():
if skip_defs_section and key == "$defs":
continue # Skip $defs during main schema traversal
- # Handle schema composition keywords with special traversal
- if key in ["allOf", "oneOf", "anyOf"] and isinstance(value, list):
+ # If we're not in a schema context, keep $ref-collecting but
+ # don't promote sub-values to schema context β€” user extension
+ # payloads can contain anything and must not be interpreted
+ # as schemas.
+ if not in_schema:
+ traverse_and_clean(
+ value, current_def_name, depth=depth + 1, in_schema=False
+ )
+ continue
+
+ # Arbitrary-key dicts of sub-schemas. The keys are user names
+ # (property/definition names), not schema keywords, so we
+ # must NOT apply the literal-keyword skip to them β€” a user
+ # property named "enum" or "default" still needs its
+ # sub-schema traversed (e.g. to collect $ref references).
+ if key in _SUBSCHEMA_MAP_KEYS and isinstance(value, dict):
+ for sub_schema in value.values():
+ traverse_and_clean(
+ sub_schema,
+ current_def_name,
+ depth=depth + 1,
+ in_schema=True,
+ )
+ continue
+
+ # Don't descend into keywords that carry literal data, not
+ # sub-schemas β€” `default: {"title": "X"}` is a user value,
+ # not schema metadata, and stripping "title" there would
+ # corrupt it.
+ if key in _LITERAL_KEYWORDS:
+ continue
+
+ # Keywords whose values are sub-schemas (or lists thereof).
+ if key in _SUBSCHEMA_LIST_KEYS and isinstance(value, list):
for item in value:
- traverse_and_clean(item, current_def_name, depth=depth + 1)
- else:
- traverse_and_clean(value, current_def_name, depth=depth + 1)
+ traverse_and_clean(
+ item,
+ current_def_name,
+ depth=depth + 1,
+ in_schema=True,
+ )
+ continue
+
+ if key in _SUBSCHEMA_VALUE_KEYS:
+ traverse_and_clean(
+ value,
+ current_def_name,
+ depth=depth + 1,
+ in_schema=True,
+ )
+ continue
+
+ # Unknown keys (user extensions like `x-ui`, vendor
+ # metadata, etc.) β€” descend for $ref collection but mark
+ # in_schema=False so cleanups don't touch user payloads.
+ traverse_and_clean(
+ value, current_def_name, depth=depth + 1, in_schema=False
+ )
elif isinstance(node, list):
for item in node:
- traverse_and_clean(item, current_def_name, depth=depth + 1)
+ traverse_and_clean(
+ item, current_def_name, depth=depth + 1, in_schema=in_schema
+ )
# Phase 2: Traverse main schema (excluding $defs section)
- traverse_and_clean(schema, skip_defs_section=True)
+ traverse_and_clean(schema, skip_defs_section=True, in_schema=True)
# Phase 3: Traverse $defs to find inter-definition references
if prune_defs and defs:
for def_name, def_schema in defs.items():
- traverse_and_clean(def_schema, current_def_name=def_name)
+ traverse_and_clean(def_schema, current_def_name=def_name, in_schema=True)
# Phase 4: Remove unused definitions
def is_def_used(def_name: str, visiting: set[str] | None = None) -> bool:
diff --git a/tests/tools/tool/test_tool.py b/tests/tools/tool/test_tool.py
index b9c14a9f3..00bd5d9e4 100644
--- a/tests/tools/tool/test_tool.py
+++ b/tests/tools/tool/test_tool.py
@@ -279,7 +279,7 @@ class TestToolFromFunction:
"tags": set(),
"parameters": {
"additionalProperties": False,
- "properties": {"x": {"title": "X"}},
+ "properties": {"x": {}},
"required": ["x"],
"type": "object",
},
diff --git a/tests/utilities/test_json_schema.py b/tests/utilities/test_json_schema.py
index 8802d69a4..644366057 100644
--- a/tests/utilities/test_json_schema.py
+++ b/tests/utilities/test_json_schema.py
@@ -450,6 +450,107 @@ class TestCompressSchema:
assert "title" not in compressed["properties"]["title"]
assert "title" not in compressed["properties"]["type"]
+ def test_prune_titles_on_bare_metadata_node(self):
+ """Pydantic emits `{"title": "X"}` for Any-typed fields with no sibling
+ `type`/`properties`. Gemini 2.5 Flash rejects these with
+ MALFORMED_FUNCTION_CALL, so we need to strip the title even without a
+ schema keyword β€” as long as every remaining key is metadata."""
+ schema = {
+ "type": "object",
+ "properties": {
+ "anyfield": {"title": "Anyfield"},
+ "described_any": {"title": "Described", "description": "anything"},
+ },
+ }
+
+ compressed = compress_schema(schema, prune_titles=True)
+
+ assert "title" not in compressed["properties"]["anyfield"]
+ assert "title" not in compressed["properties"]["described_any"]
+ # description survives β€” it's also metadata but prune_titles only
+ # targets "title" specifically
+ assert compressed["properties"]["described_any"]["description"] == "anything"
+
+ def test_prune_titles_on_draft07_and_legacy_keywords(self):
+ """Sub-schemas under draft-07 and 2019-09+ keywords that previous
+ drafts still use must be treated as schemas, not opaque payload β€”
+ `dependencies`, `additionalItems`, `contentSchema` all hold
+ sub-schemas in at least some JSON Schema drafts."""
+ schema = {
+ "type": "object",
+ "properties": {
+ "payload": {
+ "type": "string",
+ "contentMediaType": "application/json",
+ "contentSchema": {
+ "type": "object",
+ "title": "Payload",
+ },
+ },
+ "items_field": {
+ "type": "array",
+ "items": [{"type": "string", "title": "First"}],
+ "additionalItems": {"type": "number", "title": "Extra"},
+ },
+ },
+ "dependencies": {
+ "credit_card": {
+ "type": "object",
+ "title": "HasBillingAddress",
+ "required": ["billing_address"],
+ }
+ },
+ }
+
+ compressed = compress_schema(schema, prune_titles=True)
+
+ # title metadata stripped from sub-schemas reachable through
+ # draft-07 / 2019-09+ keywords
+ assert "title" not in compressed["properties"]["payload"]["contentSchema"]
+ assert "title" not in compressed["properties"]["items_field"]["items"][0]
+ assert "title" not in compressed["properties"]["items_field"]["additionalItems"]
+ assert "title" not in compressed["dependencies"]["credit_card"]
+
+ def test_prune_titles_preserves_user_extension_payloads(self):
+ """User extensions (json_schema_extra, x-* vendor keys) carry opaque
+ payloads that may look metadata-shaped. They must not be touched."""
+ schema = {
+ "type": "object",
+ "x-ui": {"title": "Dashboard", "description": "sidebar label"},
+ "properties": {
+ "config": {
+ "type": "object",
+ "x-widget": {"title": "Dropdown"},
+ }
+ },
+ }
+
+ compressed = compress_schema(schema, prune_titles=True)
+
+ assert compressed["x-ui"] == {
+ "title": "Dashboard",
+ "description": "sidebar label",
+ }
+ assert compressed["properties"]["config"]["x-widget"] == {"title": "Dropdown"}
+
+ def test_prune_titles_does_not_recurse_into_default_values(self):
+ """A user default that happens to be a dict shaped like schema metadata
+ must not be corrupted β€” `default` holds literal values, not sub-schemas."""
+ schema = {
+ "type": "object",
+ "properties": {
+ "config": {
+ "type": "object",
+ "default": {"title": "My Dashboard", "type": "vis"},
+ }
+ },
+ }
+
+ compressed = compress_schema(schema, prune_titles=True)
+
+ default = compressed["properties"]["config"]["default"]
+ assert default == {"title": "My Dashboard", "type": "vis"}
+
def test_title_pruning_with_nested_properties(self):
"""Test that nested property structures are handled correctly."""
schema = {