Skip to content

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

fix(client): hydrate formatted scalars and positional array items (#5203)

FanouZeng-TT1ed0e6d467cf
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
index bdd73fea8..304c93fa8 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
@@ -5,7 +5,7 @@ for validation with Pydantic. It supports:
- Basic types (string, number, integer, boolean, null)
- Complex types (arrays, objects)
-- Format constraints (date-time, email, uri)
+- Format constraints (date-time, date, time, duration, uuid, email, uri)
- Numeric constraints (minimum, maximum, multipleOf)
- String constraints (minLength, maxLength, pattern)
- Array constraints (minItems, maxItems, uniqueItems)
@@ -65,7 +65,7 @@ from collections.abc import Callable, Hashable, Mapping
from contextvars import ContextVar
from copy import deepcopy
from dataclasses import MISSING, dataclass, field, make_dataclass
-from datetime import date, datetime
+from datetime import date, datetime, time, timedelta
from functools import lru_cache
from typing import (
Annotated,
@@ -77,6 +77,7 @@ from typing import (
Union,
cast,
)
+from uuid import UUID
from pydantic import (
AnyUrl,
@@ -148,6 +149,10 @@ _UnsatisfiableType = Annotated[Any, BeforeValidator(_reject_all)]
FORMAT_TYPES: dict[str, Any] = {
"date-time": datetime,
+ "date": date,
+ "time": time,
+ "duration": timedelta,
+ "uuid": UUID,
"email": EmailStr,
"uri": AnyUrl,
"json": Json,
@@ -605,9 +610,22 @@ def _create_array_type(
schemas: Mapping[str, Any],
resolving_refs: frozenset[str],
) -> type | Annotated[Any, ...]:
- """Create list type with optional constraints."""
+ """Create list/tuple type with optional constraints."""
+ prefix_items = schema.get("prefixItems")
items = schema.get("items", {})
- if isinstance(items, list):
+ if isinstance(prefix_items, list) and schema.get("minItems") == len(
+ prefix_items
+ ) == schema.get("maxItems"):
+ # A positional schema (JSON Schema 2020-12) whose length is pinned to
+ # the number of positions is an exact tuple β€” this is the shape a
+ # fixed-length tuple annotation serializes to. Hydrate every position
+ # from its own schema so positional items keep their types instead of
+ # degrading to untyped objects.
+ positional_types = tuple(
+ _schema_to_type(s, schemas, resolving_refs) for s in prefix_items
+ )
+ base = tuple[positional_types] # type: ignore[valid-type] # ty:ignore[invalid-type-form]
+ elif isinstance(items, list):
# Handle positional item schemas
item_types = [_schema_to_type(s, schemas, resolving_refs) for s in items]
combined = Union[tuple(item_types)] # noqa: UP007
diff --git a/tests/client/test_result_hydration.py b/tests/client/test_result_hydration.py
new file mode 100644
index 000000000..915952d7c
--- /dev/null
+++ b/tests/client/test_result_hydration.py
@@ -0,0 +1,68 @@
+"""Hydration of ``Client.call_tool(...).data`` from the server's output schema.
+
+The client rebuilds Python types from the output schema, so every ``format``
+and positional item schema the server emits has to survive that round trip.
+"""
+
+from datetime import date, datetime, time, timedelta
+from uuid import UUID
+
+from pydantic import BaseModel
+
+from fastmcp import Client, FastMCP
+
+
+class Reading(BaseModel):
+ ts: datetime
+ day: date
+ at: time
+ dur: timedelta
+ ident: UUID
+
+
+class TestStructuredResultHydration:
+ async def test_annotated_scalar_formats_arrive_as_python_types(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def read() -> Reading:
+ return Reading(
+ ts=datetime(2024, 1, 1, 12),
+ day=date(2024, 1, 1),
+ at=time(1, 2),
+ dur=timedelta(days=1),
+ ident=UUID(int=7),
+ )
+
+ async with Client(mcp) as client:
+ data = (await client.call_tool("read")).data
+
+ assert data.ts == datetime(2024, 1, 1, 12)
+ assert data.day == date(2024, 1, 1)
+ assert data.at == time(1, 2)
+ assert data.dur == timedelta(days=1)
+ assert data.ident == UUID(int=7)
+
+ async def test_fixed_length_tuple_result_keeps_positions(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def first_seen() -> tuple[date, int]:
+ return (date(2026, 8, 27), 3)
+
+ async with Client(mcp) as client:
+ data = (await client.call_tool("first_seen")).data
+
+ assert data == (date(2026, 8, 27), 3)
+
+ async def test_formats_hydrate_inside_collections(self):
+ mcp = FastMCP()
+
+ @mcp.tool
+ def recent() -> dict[str, list[date]]:
+ return {"days": [date(2026, 8, 27), date(2026, 8, 28)]}
+
+ async with Client(mcp) as client:
+ data = (await client.call_tool("recent")).data
+
+ assert data["days"] == [date(2026, 8, 27), date(2026, 8, 28)]
diff --git a/tests/utilities/json_schema_type/test_containers.py b/tests/utilities/json_schema_type/test_containers.py
index f2e4bdb1b..292727ed0 100644
--- a/tests/utilities/json_schema_type/test_containers.py
+++ b/tests/utilities/json_schema_type/test_containers.py
@@ -2,6 +2,7 @@
from collections import UserDict
from dataclasses import Field, dataclass
+from datetime import date
from decimal import Decimal
from typing import Any
@@ -385,3 +386,80 @@ class TestObjectTypes:
object = json_schema_to_type(schema)
object_schema = TypeAdapter(object).json_schema()
assert object_schema == schema
+
+
+class TestPositionalArrayTypes:
+ """Positional (``prefixItems``) arrays hydrate per position when pinned."""
+
+ @pytest.fixture
+ def fixed_length_positional_array(self):
+ return json_schema_to_type(
+ {
+ "type": "array",
+ "prefixItems": [
+ {"type": "string", "format": "date"},
+ {"type": "integer"},
+ ],
+ "minItems": 2,
+ "maxItems": 2,
+ }
+ )
+
+ @pytest.fixture
+ def unpinned_positional_array(self):
+ return json_schema_to_type(
+ {
+ "type": "array",
+ "prefixItems": [
+ {"type": "string", "format": "date"},
+ {"type": "integer"},
+ ],
+ }
+ )
+
+ def test_fixed_length_positional_array_hydrates_each_position(
+ self, fixed_length_positional_array
+ ):
+ validator = TypeAdapter(fixed_length_positional_array)
+ result = validator.validate_python(["2024-01-01", 3])
+ assert result == (date(2024, 1, 1), 3)
+ assert isinstance(result[0], date)
+
+ def test_fixed_length_positional_array_rejects_wrong_length(
+ self, fixed_length_positional_array
+ ):
+ validator = TypeAdapter(fixed_length_positional_array)
+ with pytest.raises(ValidationError):
+ validator.validate_python(["2024-01-01"])
+
+ def test_fixed_length_positional_array_rejects_wrong_position_type(
+ self, fixed_length_positional_array
+ ):
+ validator = TypeAdapter(fixed_length_positional_array)
+ with pytest.raises(ValidationError):
+ validator.validate_python(["2024-01-01", "not-an-integer"])
+
+ def test_unpinned_positional_array_keeps_list_semantics(
+ self, unpinned_positional_array
+ ):
+ validator = TypeAdapter(unpinned_positional_array)
+ result = validator.validate_python(["2024-01-01", 3, "extra"])
+ assert isinstance(result, list)
+ assert result == ["2024-01-01", 3, "extra"]
+
+ def test_fixed_length_positional_array_preserves_uniqueness(self):
+ validator = TypeAdapter(
+ json_schema_to_type(
+ {
+ "type": "array",
+ "prefixItems": [{"type": "integer"}, {"type": "integer"}],
+ "minItems": 2,
+ "maxItems": 2,
+ "uniqueItems": True,
+ }
+ )
+ )
+ assert validator.validate_python([1, 2]) == (1, 2)
+ assert validator.json_schema()["uniqueItems"] is True
+ with pytest.raises(ValidationError, match="Array items must be unique"):
+ validator.validate_python([1, 1])
diff --git a/tests/utilities/json_schema_type/test_formats.py b/tests/utilities/json_schema_type/test_formats.py
index 781b81a82..8fe6380c6 100644
--- a/tests/utilities/json_schema_type/test_formats.py
+++ b/tests/utilities/json_schema_type/test_formats.py
@@ -1,7 +1,8 @@
"""Tests for format handling in JSON schema conversion."""
from dataclasses import Field
-from datetime import datetime
+from datetime import date, datetime, time, timedelta
+from uuid import UUID
import pytest
from pydantic import AnyUrl, TypeAdapter, ValidationError
@@ -38,6 +39,26 @@ class TestFormatTypes:
def json_format(self):
return json_schema_to_type({"type": "string", "format": "json"})
+ @pytest.fixture
+ def date_format(self):
+ return json_schema_to_type({"type": "string", "format": "date"})
+
+ @pytest.fixture
+ def time_format(self):
+ return json_schema_to_type({"type": "string", "format": "time"})
+
+ @pytest.fixture
+ def duration_format(self):
+ return json_schema_to_type({"type": "string", "format": "duration"})
+
+ @pytest.fixture
+ def uuid_format(self):
+ return json_schema_to_type({"type": "string", "format": "uuid"})
+
+ @pytest.fixture
+ def unknown_format(self):
+ return json_schema_to_type({"type": "string", "format": "not-a-real-format"})
+
@pytest.fixture
def mixed_formats_object(self):
return json_schema_to_type(
@@ -112,3 +133,52 @@ class TestFormatTypes:
)
assert isinstance(result.full_uri, AnyUrl)
assert isinstance(result.ref_uri, str)
+
+ def test_date_valid(self, date_format):
+ validator = TypeAdapter(date_format)
+ result = validator.validate_python("2024-01-01")
+ assert isinstance(result, date)
+ assert result == date(2024, 1, 1)
+
+ def test_date_invalid(self, date_format):
+ validator = TypeAdapter(date_format)
+ with pytest.raises(ValidationError):
+ validator.validate_python("not-a-date")
+
+ def test_time_valid(self, time_format):
+ validator = TypeAdapter(time_format)
+ result = validator.validate_python("12:34:56")
+ assert isinstance(result, time)
+ assert result == time(12, 34, 56)
+
+ def test_time_invalid(self, time_format):
+ validator = TypeAdapter(time_format)
+ with pytest.raises(ValidationError):
+ validator.validate_python("not-a-time")
+
+ def test_duration_valid(self, duration_format):
+ validator = TypeAdapter(duration_format)
+ result = validator.validate_python("P1D")
+ assert isinstance(result, timedelta)
+ assert result == timedelta(days=1)
+
+ def test_duration_invalid(self, duration_format):
+ validator = TypeAdapter(duration_format)
+ with pytest.raises(ValidationError):
+ validator.validate_python("not-a-duration")
+
+ def test_uuid_valid(self, uuid_format):
+ validator = TypeAdapter(uuid_format)
+ result = validator.validate_python("00000000-0000-0000-0000-000000000007")
+ assert isinstance(result, UUID)
+ assert result == UUID(int=7)
+
+ def test_uuid_invalid(self, uuid_format):
+ validator = TypeAdapter(uuid_format)
+ with pytest.raises(ValidationError):
+ validator.validate_python("not-a-uuid")
+
+ def test_unmapped_format_falls_back_to_string(self, unknown_format):
+ validator = TypeAdapter(unknown_format)
+ result = validator.validate_python("anything")
+ assert isinstance(result, str)