Skip to content

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

Key cached schema adapters by the normalized schema (#5436)

Jeremiah Lowina4f656c36852
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
index 5c68ecc80..5107b78ed 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
@@ -340,8 +340,10 @@ def json_schema_to_type(
# Normalise YAML-parsed types (datetime/date β†’ str, non-str keys β†’ str)
# so that downstream json.dumps/hashing and default values work correctly.
- schema = _normalize_yaml_types(schema)
+ return _convert_normalized(_normalize_yaml_types(schema), name)
+
+def _convert_normalized(schema: dict[str, Any], name: str | None) -> type:
root_hash, root_size = _schema_digest(schema)
token = _conversion.set(_Conversion(root_hash=root_hash, root_size=root_size))
try:
@@ -362,11 +364,14 @@ def json_schema_to_type_adapter(schema: Mapping[str, Any] | bool) -> TypeAdapter
Adapters are cached by schema content in a bounded cache, so the classes
they hold are released when they are evicted.
"""
+ if isinstance(schema, bool):
+ return TypeAdapter(json_schema_to_type(schema))
_check_nesting(schema)
+ schema = _normalize_yaml_types(schema)
key, size = _schema_digest(schema)
adapter = _adapters.get(key)
if adapter is None:
- adapter = TypeAdapter(json_schema_to_type(schema))
+ adapter = TypeAdapter(_convert_normalized(schema, None))
_adapters.put(key, adapter, size)
return adapter
diff --git a/tests/utilities/json_schema_type/test_generated_classes.py b/tests/utilities/json_schema_type/test_generated_classes.py
index 8693bc511..caa5e91d6 100644
--- a/tests/utilities/json_schema_type/test_generated_classes.py
+++ b/tests/utilities/json_schema_type/test_generated_classes.py
@@ -642,6 +642,27 @@ class TestClassCache:
assert len(json_schema_type._classes) == 0
+ def test_adapters_are_cached_by_normalized_schema(self):
+ boolean_key: dict[Any, Any] = {
+ "type": "object",
+ "properties": {True: {"type": "integer"}},
+ }
+ string_key: dict[Any, Any] = {
+ "type": "object",
+ "properties": {"true": {"type": "integer"}},
+ }
+ capitalized_key: dict[Any, Any] = {
+ "type": "object",
+ "properties": {"True": {"type": "integer"}},
+ }
+
+ assert json_schema_to_type_adapter(string_key).validate_python({"true": 1})
+ adapter = json_schema_to_type_adapter(boolean_key)
+
+ assert adapter.validate_python({"True": 1})
+ assert adapter is json_schema_to_type_adapter(capitalized_key)
+ assert adapter is not json_schema_to_type_adapter(string_key)
+
def test_evicted_classes_are_released(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(json_schema_type._classes, "max_entries", 2)
monkeypatch.setattr(json_schema_type._adapters, "max_entries", 2)