π The fast, Pythonic way to build MCP servers and clients.
Keep string length and pattern constraints when a format is set (#5208)
nate nowack87b5c741a460
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.pyindex de1db2900..779d08faa 100644--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py@@ -61,6 +61,7 @@ from collections.abc import Callable, Mappingfrom copy import deepcopyfrom dataclasses import MISSING, field, make_dataclassfrom datetime import date, datetime+from functools import lru_cachefrom typing import (Annotated,Any,@@ -269,12 +270,8 @@ def _create_string_type(schema: Mapping[str, Any]) -> type | Annotated[Any, ...]if "const" in schema:return Literal[schema["const"]] # type: ignore- if fmt := schema.get("format"):- if fmt == "uri":- return AnyUrl- elif fmt == "uri-reference":- return str- return FORMAT_TYPES.get(fmt, str)+ fmt = schema.get("format")+ base: Any = FORMAT_TYPES.get(fmt, str) if fmt else strconstraints = {k: v@@ -287,7 +284,7 @@ def _create_string_type(schema: Mapping[str, Any]) -> type | Annotated[Any, ...]}if not constraints:- return str+ return baseannotated: Any = Annotated[str, StringConstraints(**constraints)]@@ -312,7 +309,34 @@ def _create_string_type(schema: Mapping[str, Any]) -> type | Annotated[Any, ...]else:annotated = Annotated[str, pattern_field] # type: ignore[valid-type]- return annotated+ if base is str:+ return annotated+ return _constrain_raw_string(base, **constraints)+++@lru_cache(maxsize=1024)+def _constrain_raw_string(+ base: Any,+ min_length: int | None = None,+ max_length: int | None = None,+ pattern: str | None = None,+) -> Any:+ """Apply string keywords to the raw instance before `base` parses it, as JSON Schema does.++ Cached so a schema seen on every tool call maps to one type, and so one TypeAdapter.+ """+ raw = TypeAdapter(+ Annotated[+ str,+ StringConstraints(+ min_length=min_length, max_length=max_length, pattern=pattern+ ),+ ]+ )+ return Annotated[+ base,+ BeforeValidator(lambda v: raw.validate_python(v) if isinstance(v, str) else v),+ ]def _create_numeric_type(diff --git a/tests/utilities/json_schema_type/test_constraints.py b/tests/utilities/json_schema_type/test_constraints.pyindex 53a1d9a1e..51cba38e6 100644--- a/tests/utilities/json_schema_type/test_constraints.py+++ b/tests/utilities/json_schema_type/test_constraints.py@@ -1,9 +1,10 @@"""Tests for type constraints in JSON schema conversion."""from dataclasses import Field+from datetime import datetime, timezoneimport pytest-from pydantic import TypeAdapter, ValidationError+from pydantic import AnyUrl, TypeAdapter, ValidationErrorfrom fastmcp.utilities.json_schema_type import (json_schema_to_type,@@ -130,3 +131,52 @@ class TestNumberConstraints:validator = TypeAdapter(exclusive_max_number)with pytest.raises(ValidationError):validator.validate_python(100)+++class TestStringFormatConstraints:+ """String keywords apply to the raw string whatever its `format` (#4404)."""++ @pytest.mark.parametrize(+ ("schema", "valid", "invalid"),+ [+ ({"format": "phone", "maxLength": 3}, "abc", "abcd"),+ ({"format": "phone", "minLength": 3}, "abc", "ab"),+ ({"format": "uri-reference", "maxLength": 5}, "a/b", "too/long/path"),+ ({"format": "uri-reference", "pattern": "^/"}, "/a", "a"),+ ({"format": "email", "maxLength": 10}, "[email protected]", "[email protected]"),+ (+ {"format": "uri", "maxLength": 14},+ "https://a.co",+ "https://example.com/x",+ ),+ (+ {"format": "date-time", "maxLength": 20},+ "2026-09-22T00:00:00Z",+ "2026-09-22T00:00:00.000000+00:00",+ ),+ ({"format": "json", "maxLength": 5}, '"ab"', '"abcdef"'),+ ],+ )+ def test_constraints_survive_format(self, schema, valid, invalid):+ validator = TypeAdapter(json_schema_to_type({"type": "string", **schema}))+ validator.validate_python(valid)+ with pytest.raises(ValidationError):+ validator.validate_python(invalid)++ def test_constrained_format_still_parses(self):+ schema = {"type": "string", "format": "date-time", "maxLength": 20}+ parsed = TypeAdapter(json_schema_to_type(schema)).validate_python(+ "2026-09-22T00:00:00Z"+ )+ assert parsed == datetime(2026, 9, 22, tzinfo=timezone.utc)++ def test_format_without_constraints_is_unchanged(self):+ assert (+ json_schema_to_type({"type": "string", "format": "date-time"}) is datetime+ )+ assert json_schema_to_type({"type": "string", "format": "uri"}) is AnyUrl++ def test_repeat_schema_maps_to_one_type(self):+ """The client converts a tool's output schema on every call, so repeats must hit its adapter cache."""+ schema = {"type": "string", "format": "email", "maxLength": 10}+ assert json_schema_to_type(schema) is json_schema_to_type(dict(schema))