π The fast, Pythonic way to build MCP servers and clients.
Validate positional array prefixes separately from their tails (#6146)
ppy6646771593b4
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.pyindex 664af2dd9..5f4b982e7 100644--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py@@ -89,6 +89,9 @@ from pydantic import (ConfigDict,EmailStr,Field,+ GetCoreSchemaHandler,+ GetJsonSchemaHandler,+ GetPydanticSchema,Json,PlainValidator,StringConstraints,@@ -98,6 +101,7 @@ from pydantic import ()from pydantic.fields import FieldInfofrom pydantic_core import SchemaError as _PydanticSchemaError+from pydantic_core import core_schemafrom typing_extensions import TypedDict__all__ = ["JSONSchema", "json_schema_to_type"]@@ -311,6 +315,11 @@ def json_schema_to_type(Returns:A Python type (typically a dataclass for objects) with Pydantic validation+ Positional arrays validate each present ``prefixItems`` position and+ apply ``items`` only to the tail. Arrays pinned to the prefix length+ hydrate as tuples; other arrays remain lists. Unrestricted tails preserve+ prefix values for compatibility; constrained tails hydrate each position.+Raises:ValueError: If a name is provided for a non-object schema, or if theschema is too deeply nested or too large to convert.@@ -789,6 +798,110 @@ def _validate_unique_items(value: Any) -> Any:return value+def _create_prefix_items_type(+ prefix_types: tuple[Any, ...], item_type: Any, schema: Mapping[str, Any]+) -> Any:+ """Validate positions while preserving unrestricted-list compatibility."""+ minimum = _count(schema.get("minItems"))+ maximum = _count(schema.get("maxItems"), maximum=True)+ preserve_prefix_values = item_type is Any or item_type is object++ def preserve_value(+ value: Any, handler: core_schema.ValidatorFunctionWrapHandler+ ) -> Any:+ handler(value)+ return value++ def validate_list(+ value: Any, handler: core_schema.ValidatorFunctionWrapHandler+ ) -> list[Any]:+ if not isinstance(value, list):+ return list(handler(value))+ if minimum is not None and len(value) < minimum:+ raise ValueError(f"Array should have at least {minimum} items")+ if maximum is not None and len(value) > maximum:+ raise ValueError(f"Array should have at most {maximum} items")+ # Missing prefix positions are optional. Discard the defaults used by+ # the tuple validator instead of appending values to a shorter array.+ return list(handler(tuple(value))[: len(value)])++ def serialize_list(+ value: list[Any], handler: core_schema.SerializerFunctionWrapHandler+ ) -> list[Any]:+ return list(handler(tuple(value)))++ def build_schema(+ _source: Any, handler: GetCoreSchemaHandler+ ) -> core_schema.CoreSchema:+ def build_positions(json_input: bool) -> core_schema.CoreSchema:+ def item_schema(item: Any) -> core_schema.CoreSchema:+ converted = handler.generate_schema(item)+ if json_input:+ # A wrap handler receives Python values. Restore JSON input+ # semantics so strict dates still accept JSON date strings.+ return core_schema.no_info_before_validator_function(+ json.dumps,+ core_schema.json_schema(converted),+ json_schema_input_schema=converted,+ )+ return converted++ positions: list[core_schema.CoreSchema] = [+ core_schema.with_default_schema(+ core_schema.no_info_wrap_validator_function(+ preserve_value,+ item_schema(position_type),+ serialization=core_schema.simple_ser_schema("any"),+ )+ if preserve_prefix_values+ else item_schema(position_type),+ default=None,+ )+ for position_type in prefix_types+ ]+ positions.append(item_schema(item_type))+ return core_schema.tuple_schema(+ positions,+ variadic_item_index=len(prefix_types),+ min_length=0,+ )++ positional_schema = build_positions(json_input=False)+ validated = core_schema.no_info_wrap_validator_function(+ validate_list, positional_schema+ )+ return core_schema.json_or_python_schema(+ json_schema=core_schema.no_info_wrap_validator_function(+ validate_list, build_positions(json_input=True)+ ),+ python_schema=core_schema.chain_schema(+ [core_schema.list_schema(), validated]+ ),+ serialization=core_schema.wrap_serializer_function_ser_schema(+ serialize_list, schema=positional_schema+ ),+ )++ def build_json_schema(+ core: core_schema.CoreSchema, handler: GetJsonSchemaHandler+ ) -> dict[str, Any]:+ result = handler(core)+ if minimum is not None:+ result["minItems"] = minimum+ if maximum is not None:+ result["maxItems"] = maximum+ for index, position in enumerate(result.get("prefixItems", [])):+ if prefix_types[index] is _UnsatisfiableType:+ result["prefixItems"][index] = False+ elif isinstance(position, dict):+ position.pop("default", None)+ if item_type is _UnsatisfiableType:+ result["items"] = False+ return result++ return Annotated[list[Any], GetPydanticSchema(build_schema, build_json_schema)]++def _create_array_type(schema: Mapping[str, Any],schemas: Mapping[str, Any],@@ -809,6 +922,19 @@ def _create_array_type(_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(prefix_items, list):+ prefix_types = tuple(+ _schema_to_type(s, schemas, resolving_refs) for s in prefix_items+ )+ item_type = _schema_to_type(items, schemas, resolving_refs)+ base = _create_prefix_items_type(prefix_types, item_type, schema)+ if schema.get("uniqueItems") is True:+ return Annotated[+ base,+ BeforeValidator(_validate_unique_items),+ Field(json_schema_extra={"uniqueItems": True}),+ ]+ return baseelif isinstance(items, list):# Handle positional item schemasitem_types = [_schema_to_type(s, schemas, resolving_refs) for s in items]diff --git a/tests/utilities/json_schema_type/test_prefix_items.py b/tests/utilities/json_schema_type/test_prefix_items.pynew file mode 100644index 000000000..6e7dd65fa--- /dev/null+++ b/tests/utilities/json_schema_type/test_prefix_items.py@@ -0,0 +1,234 @@+"""Unpinned JSON Schema arrays validate prefix and trailing items separately."""++from datetime import date+from typing import Any++import pytest+from jsonschema import Draft202012Validator+from pydantic import TypeAdapter, ValidationError++from fastmcp import Client, FastMCP+from fastmcp.utilities.json_schema_type import json_schema_to_type++[email protected]("value", [[], ["a"], ["a", 2], ["a", 2, 3.5]])+def test_prefix_items_do_not_use_the_tail_schema(value: list[Any]) -> None:+ adapter = TypeAdapter(+ json_schema_to_type(+ {+ "type": "array",+ "prefixItems": [{"type": "string"}],+ "items": {"type": "number"},+ }+ )+ )+ result = adapter.validate_python(value)+ assert result == value+ assert type(result) is list++[email protected]("tail", [{}, {"items": True}, {"items": False}])[email protected]("value", [[], ["a"], ["a", 2]])+def test_prefix_items_accept_missing_positions(+ tail: dict[str, Any], value: list[Any]+) -> None:+ adapter = TypeAdapter(+ json_schema_to_type(+ {+ "type": "array",+ "prefixItems": [{"type": "string"}, {"type": "integer"}],+ **tail,+ }+ )+ )+ assert adapter.validate_python(value) == value++[email protected]("tail", [{}, {"items": True}, {"items": False}])+def test_prefix_items_reject_an_invalid_present_position(tail: dict[str, Any]) -> None:+ adapter = TypeAdapter(+ json_schema_to_type(+ {"type": "array", "prefixItems": [{"type": "string"}], **tail}+ )+ )+ with pytest.raises(ValidationError):+ adapter.validate_python([1])++[email protected]("items", [False, {"type": "number"}])+def test_prefix_items_reject_invalid_tail(items: Any) -> None:+ adapter = TypeAdapter(+ json_schema_to_type(+ {+ "type": "array",+ "prefixItems": [{"type": "string"}],+ "items": items,+ }+ )+ )+ with pytest.raises(ValidationError):+ adapter.validate_python(["a", "invalid"])+++def test_unpinned_prefix_and_tail_formats_keep_existing_hydration() -> None:+ adapter = TypeAdapter(+ json_schema_to_type(+ {+ "type": "array",+ "prefixItems": [{"type": "string", "format": "date"}],+ "items": {"type": "string", "format": "date"},+ }+ )+ )+ result = adapter.validate_python(["2026-10-29", "2026-10-30"])+ assert result == [date(2026, 10, 29), date(2026, 10, 30)]+ assert type(result[0]) is date+ assert type(result) is list+ assert adapter.dump_python(result) == result+ assert adapter.dump_json(result) == b'["2026-10-29","2026-10-30"]'+ assert adapter.validate_json('["2026-10-29","2026-10-30"]', strict=True) == result++[email protected]("tail", [{}, {"items": True}, {"items": {}}])+def test_unrestricted_tail_preserves_existing_prefix_values(+ tail: dict[str, Any],+) -> None:+ adapter = TypeAdapter(+ json_schema_to_type(+ {+ "type": "array",+ "prefixItems": [{"type": "string", "format": "date"}],+ **tail,+ }+ )+ )+ result = adapter.validate_python(["2026-10-29", "tail"])+ assert result == ["2026-10-29", "tail"]+ assert type(result[0]) is str+ assert adapter.validate_json('["2026-10-29","tail"]', strict=True) == result+++async def test_client_hydrates_date_prefix_with_date_tail() -> None:+ server = FastMCP()++ @server.tool(+ output_schema={+ "type": "object",+ "properties": {+ "value": {+ "type": "array",+ "prefixItems": [{"type": "string", "format": "date"}],+ "items": {"type": "string", "format": "date"},+ }+ },+ "required": ["value"],+ }+ )+ def read_dates() -> dict[str, Any]:+ return {"value": ["2026-10-29", "2026-10-30"]}++ async with Client(server) as client:+ result = await client.call_tool("read_dates")++ assert result.structured_content == {"value": ["2026-10-29", "2026-10-30"]}+ assert result.data.value == [date(2026, 10, 29), date(2026, 10, 30)]+ assert type(result.data.value[0]) is date++[email protected]("value", [[], ["a", 1, 2], ["a", "a"]])+def test_prefix_items_keep_length_and_uniqueness_constraints(value: list[Any]) -> None:+ adapter = TypeAdapter(+ json_schema_to_type(+ {+ "type": "array",+ "prefixItems": [{"type": "string"}],+ "items": True,+ "minItems": 1,+ "maxItems": 2,+ "uniqueItems": True,+ }+ )+ )+ with pytest.raises(ValidationError):+ adapter.validate_python(value)+ assert adapter.validate_python(["a", 1]) == ["a", 1]+++async def test_client_data_keeps_a_valid_prefix_with_a_typed_tail() -> None:+ server = FastMCP()++ @server.tool(+ output_schema={+ "type": "object",+ "properties": {+ "value": {+ "type": "array",+ "prefixItems": [{"type": "string"}],+ "items": {"type": "number"},+ }+ },+ "required": ["value"],+ }+ )+ def read() -> dict[str, Any]:+ return {"value": ["a", 2]}++ async with Client(server) as client:+ result = await client.call_tool("read")++ assert result.structured_content == {"value": ["a", 2]}+ assert result.data.value == ["a", 2]+ assert type(result.data.value) is list++[email protected]("constraints", [{}, {"minItems": 1, "maxItems": 3}])[email protected]("items", [False, True, {"type": "number"}])+def test_exported_schema_agrees_with_positional_validation(+ constraints: dict[str, Any], items: Any+) -> None:+ schema = {+ "type": "array",+ "prefixItems": [{"type": "string"}],+ "items": items,+ **constraints,+ }+ adapter = TypeAdapter(json_schema_to_type(schema))+ original = Draft202012Validator(schema)+ exported = Draft202012Validator(adapter.json_schema())+ for value in ([], ["a"], ["a", 2], ["a", "tail"], [1]):+ assert exported.is_valid(value) == original.is_valid(value)+++def test_prefix_items_resolve_references_and_validate_json() -> None:+ adapter = TypeAdapter(+ json_schema_to_type(+ {+ "type": "array",+ "prefixItems": [{"$ref": "#/$defs/Name"}],+ "$defs": {"Name": {"type": "string", "minLength": 2}},+ "items": False,+ }+ )+ )+ assert adapter.validate_json("[]") == []+ assert adapter.validate_json('["ok"]') == ["ok"]+ with pytest.raises(ValidationError):+ adapter.validate_json('["x"]')+++def test_strict_validation_keeps_list_container_semantics() -> None:+ adapter = TypeAdapter(+ json_schema_to_type(+ {+ "type": "array",+ "prefixItems": [{"type": "string"}],+ "items": {"type": "integer"},+ }+ )+ )+ assert adapter.validate_python(["a", 2], strict=True) == ["a", 2]+ assert adapter.validate_json('["a", 2]', strict=True) == ["a", 2]+ with pytest.raises(ValidationError):+ adapter.validate_python(("a", 2), strict=True)+ with pytest.raises(ValidationError):+ adapter.validate_python(["a", "2"], strict=True)