Skip to content

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

fix(client): preserve unique JSON arrays (#5270)

LZYd4aacb2b0585
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
index b35aaa2e7..bdd73fea8 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
@@ -55,6 +55,7 @@ from __future__ import annotations
import hashlib
import json
import keyword
+import math
import re
import sys
import threading
@@ -530,12 +531,81 @@ def _create_enum(name: str, values: list[Any]) -> type:
return Literal[tuple(values)] # type: ignore[return-value] # ty:ignore[invalid-type-form]
+def _json_values_equal(left: Any, right: Any) -> bool:
+ """Compare JSON values without treating booleans as numbers."""
+ if isinstance(left, bool) or isinstance(right, bool):
+ return isinstance(left, bool) and isinstance(right, bool) and left == right
+
+ if isinstance(left, Mapping) or isinstance(right, Mapping):
+ if not isinstance(left, Mapping) or not isinstance(right, Mapping):
+ return False
+ return left.keys() == right.keys() and all(
+ _json_values_equal(left[key], right[key]) for key in left
+ )
+
+ if isinstance(left, (list, tuple)) or isinstance(right, (list, tuple)):
+ if not isinstance(left, (list, tuple)) or not isinstance(right, (list, tuple)):
+ return False
+ return len(left) == len(right) and all(
+ _json_values_equal(left_item, right_item)
+ for left_item, right_item in zip(left, right, strict=True)
+ )
+
+ return left == right
+
+
+def _json_value_key(value: Any) -> tuple[Any, ...]:
+ """Build a hashable, type-tagged key for standard JSON values."""
+ value_type = type(value)
+ if value is None:
+ return ("null",)
+ if value_type is bool:
+ return ("boolean", value)
+ if value_type is int or value_type is float:
+ if value_type is float and not math.isfinite(value):
+ raise TypeError("Not a standard JSON number")
+ # Equal ints/floats already share a hash, without rounding large ints.
+ return ("number", value)
+ if value_type is str:
+ return ("string", value)
+ if value_type is list:
+ return ("array", tuple(_json_value_key(item) for item in value))
+ if value_type is dict and all(type(key) is str for key in value):
+ return (
+ "object",
+ frozenset((key, _json_value_key(item)) for key, item in value.items()),
+ )
+ raise TypeError("Not a standard JSON value")
+
+
+def _validate_unique_items(value: Any) -> Any:
+ """Reject duplicate JSON array items while preserving list semantics."""
+ if not isinstance(value, (list, tuple)):
+ return value
+
+ try:
+ seen: set[tuple[Any, ...]] = set()
+ for item in value:
+ key = _json_value_key(item)
+ if key in seen:
+ raise ValueError("Array items must be unique")
+ seen.add(key)
+ except (TypeError, RecursionError):
+ # Preserve existing comparisons for non-JSON Python values, including
+ # equality between those values and standard JSON values.
+ for index, item in enumerate(value):
+ if any(_json_values_equal(item, previous) for previous in value[:index]):
+ raise ValueError("Array items must be unique") from None
+
+ return value
+
+
def _create_array_type(
schema: Mapping[str, Any],
schemas: Mapping[str, Any],
resolving_refs: frozenset[str],
) -> type | Annotated[Any, ...]:
- """Create list/set type with optional constraints."""
+ """Create list type with optional constraints."""
items = schema.get("items", {})
if isinstance(items, list):
# Handle positional item schemas
@@ -545,8 +615,7 @@ def _create_array_type(
else:
# Handle single item schema
item_type = _schema_to_type(items, schemas, resolving_refs)
- base_class = set if schema.get("uniqueItems") else list
- base = base_class[item_type]
+ base = list[item_type] # type: ignore[valid-type] # ty:ignore[invalid-type-form]
constraints = {
k: v
@@ -557,7 +626,15 @@ def _create_array_type(
if v is not None
}
- return Annotated[base, Field(**constraints)] if constraints else base # type: ignore[return-value] # ty:ignore[invalid-type-form]
+ if schema.get("uniqueItems") is True:
+ constraints["json_schema_extra"] = {"uniqueItems": True}
+ return Annotated[
+ base,
+ BeforeValidator(_validate_unique_items),
+ Field(**constraints),
+ ] # type: ignore[return-value]
+
+ return Annotated[base, Field(**constraints)] if constraints else base # type: ignore[return-value]
def _return_Any() -> Any:
diff --git a/tests/client/client/test_client.py b/tests/client/client/test_client.py
index 47b0061d0..5c1ad2fcb 100644
--- a/tests/client/client/test_client.py
+++ b/tests/client/client/test_client.py
@@ -20,6 +20,7 @@ from fastmcp.client.transports import (
)
from fastmcp.server.server import FastMCP
from fastmcp.tools import ToolResult
+from fastmcp.tools.base import Tool
from tests.conftest import user_meta
@@ -955,6 +956,40 @@ async def test_client_list_dict_return_type():
assert result.data == [{"city": "NYC", "temp": 72}, {"city": "LA", "temp": 85}]
+async def test_client_decodes_unique_object_array():
+ """Object arrays with uniqueItems should populate CallToolResult.data."""
+ server = FastMCP()
+
+ async def list_users() -> dict:
+ return {"users": [{"id": 1, "admin": True}, {"id": 2, "admin": False}]}
+
+ server.add_tool(
+ Tool.from_function(
+ list_users,
+ output_schema={
+ "type": "object",
+ "properties": {
+ "users": {
+ "type": "array",
+ "uniqueItems": True,
+ "items": {"type": "object"},
+ }
+ },
+ "required": ["users"],
+ },
+ )
+ )
+
+ async with Client(server) as client:
+ result = await client.call_tool("list_users", {})
+
+ assert result.data is not None
+ assert result.data.users == [
+ {"id": 1, "admin": True},
+ {"id": 2, "admin": False},
+ ]
+
+
def test_client_new_preserves_internal_task_extension(fastmcp_server):
"""Client.new() rebuilds the clone with the auto-registered tasks claim.
diff --git a/tests/utilities/json_schema_type/test_containers.py b/tests/utilities/json_schema_type/test_containers.py
index 139124533..f2e4bdb1b 100644
--- a/tests/utilities/json_schema_type/test_containers.py
+++ b/tests/utilities/json_schema_type/test_containers.py
@@ -1,11 +1,14 @@
"""Tests for container types in JSON schema conversion."""
+from collections import UserDict
from dataclasses import Field, dataclass
+from decimal import Decimal
from typing import Any
import pytest
from pydantic import TypeAdapter, ValidationError
+from fastmcp.utilities import json_schema_type as schema_types
from fastmcp.utilities.json_schema_type import (
json_schema_to_type,
)
@@ -69,12 +72,166 @@ class TestArrayTypes:
def test_unique_items_accepts_unique(self, unique_items_array):
validator = TypeAdapter(unique_items_array)
- assert isinstance(validator.validate_python(["a", "b"]), set)
+ assert validator.validate_python(["a", "b"]) == ["a", "b"]
- def test_unique_items_converts_duplicates(self, unique_items_array):
+ def test_unique_items_rejects_duplicates(self, unique_items_array):
validator = TypeAdapter(unique_items_array)
- result = validator.validate_python(["a", "a", "b"])
- assert result == {"a", "b"}
+ with pytest.raises(ValidationError, match="Array items must be unique"):
+ validator.validate_python(["a", "a", "b"])
+
+ def test_unique_items_accepts_unique_objects(self):
+ unique_objects = json_schema_to_type(
+ {"type": "array", "items": {"type": "object"}, "uniqueItems": True}
+ )
+ validator = TypeAdapter(unique_objects)
+
+ users = [{"id": 1, "admin": True}, {"id": 2, "admin": False}]
+
+ assert validator.validate_python(users) == users
+
+ def test_unique_items_rejects_duplicate_objects(self):
+ unique_objects = json_schema_to_type(
+ {"type": "array", "items": {"type": "object"}, "uniqueItems": True}
+ )
+ validator = TypeAdapter(unique_objects)
+
+ with pytest.raises(ValidationError, match="Array items must be unique"):
+ validator.validate_python(
+ [{"id": 1, "admin": True}, {"admin": True, "id": 1}]
+ )
+
+ def test_unique_items_keeps_boolean_and_number_distinct(self):
+ unique_items = json_schema_to_type(
+ {"type": "array", "items": {}, "uniqueItems": True}
+ )
+ validator = TypeAdapter(unique_items)
+
+ assert validator.validate_python([True, 1]) == [True, 1]
+
+ def test_unique_items_is_preserved_in_generated_schema(self, unique_items_array):
+ assert TypeAdapter(unique_items_array).json_schema()["uniqueItems"] is True
+
+ @pytest.mark.parametrize(
+ "values, duplicate",
+ [
+ ([None, None], True),
+ ([True, True], True),
+ (["value", "value"], True),
+ ([1, 1.0], True),
+ ([0, -0.0], True),
+ ([True, 1], False),
+ ([False, 0], False),
+ ([2**53 + 1, float(2**53)], False),
+ ([None, False, 0, "0", [], {}], False),
+ ([[1, 2], [2, 1]], False),
+ ([[True], [1]], False),
+ ([{"a": 1, "b": 2}, {"b": 2, "a": 1.0}], True),
+ ([{"a": [1, 2]}, {"a": [1, 2]}], True),
+ ([{"a": True}, {"a": 1}], False),
+ ([{"a": {"b": [None, 1]}}, {"a": {"b": [None, 1.0]}}], True),
+ ],
+ )
+ def test_unique_items_json_equality(self, values: list[Any], duplicate: bool):
+ validator = TypeAdapter(
+ json_schema_to_type({"type": "array", "items": {}, "uniqueItems": True})
+ )
+ if duplicate:
+ with pytest.raises(ValidationError, match="Array items must be unique"):
+ validator.validate_python(values)
+ else:
+ assert validator.validate_python(values) == values
+
+ @pytest.mark.parametrize("objects", [False, True])
+ def test_unique_items_avoids_all_pairs_comparison(
+ self, monkeypatch: pytest.MonkeyPatch, objects: bool
+ ):
+ comparisons = 0
+ original = schema_types._json_values_equal
+
+ def counted(left: Any, right: Any) -> bool:
+ nonlocal comparisons
+ comparisons += 1
+ return original(left, right)
+
+ monkeypatch.setattr(schema_types, "_json_values_equal", counted)
+ values = [{"id": i} for i in range(200)] if objects else list(range(200))
+ validator = TypeAdapter(
+ json_schema_to_type({"type": "array", "items": {}, "uniqueItems": True})
+ )
+ assert validator.validate_python(values) == values
+ # Guard against quadratic comparisons without machine-dependent timings.
+ assert comparisons <= len(values)
+
+ @pytest.mark.parametrize("objects", [False, True])
+ def test_unique_items_large_array(self, objects: bool):
+ values = (
+ [{"id": i, "tags": ["value", False]} for i in range(4000)]
+ if objects
+ else list(range(4000))
+ )
+ validator = TypeAdapter(
+ json_schema_to_type({"type": "array", "items": {}, "uniqueItems": True})
+ )
+ assert validator.validate_python(values) == values
+ with pytest.raises(ValidationError, match="Array items must be unique"):
+ validator.validate_python([*values, values[-1]])
+
+ @pytest.mark.parametrize(
+ "values, duplicate",
+ [
+ ([Decimal("1"), 1], True),
+ ([1, Decimal("1")], True),
+ ([Decimal("1"), 2], False),
+ ([[1, 2], (1, 2)], True),
+ ([UserDict({"a": [1]}), {"a": [1]}], True),
+ ([UserDict({"a": [1]}), {"a": [2]}], False),
+ ([{1: "a"}, {True: "a"}], True),
+ ],
+ )
+ def test_unique_items_preserves_python_fallback(
+ self, values: list[Any], duplicate: bool
+ ):
+ validator = TypeAdapter(
+ json_schema_to_type({"type": "array", "items": {}, "uniqueItems": True})
+ )
+ if duplicate:
+ with pytest.raises(ValidationError, match="Array items must be unique"):
+ validator.validate_python(values)
+ else:
+ assert validator.validate_python(values) == values
+
+ def test_unique_items_non_finite_numbers_preserve_python_equality(self):
+ validator: TypeAdapter[Any] = TypeAdapter(
+ json_schema_to_type({"type": "array", "items": {}, "uniqueItems": True})
+ )
+ nan = float("nan")
+ assert len(validator.validate_python([nan, nan])) == 2
+ with pytest.raises(ValidationError, match="Array items must be unique"):
+ validator.validate_python([float("inf"), float("inf")])
+
+ def test_unique_items_cyclic_python_value_preserves_fallback(self):
+ cyclic: list[Any] = []
+ cyclic.append(cyclic)
+ validator: TypeAdapter[Any] = TypeAdapter(
+ json_schema_to_type({"type": "array", "items": {}, "uniqueItems": True})
+ )
+ assert validator.validate_python([cyclic])[0] is cyclic
+
+ @pytest.mark.parametrize("unique", [None, False])
+ def test_non_unique_schema_does_not_validate_uniqueness(
+ self, monkeypatch: pytest.MonkeyPatch, unique: bool | None
+ ):
+ def unexpected(value: Any) -> Any:
+ pytest.fail("Non-unique arrays must not run uniqueness validation")
+
+ monkeypatch.setattr(schema_types, "_validate_unique_items", unexpected)
+ schema: dict[str, Any] = {"type": "array", "items": {}}
+ if unique is not None:
+ schema["uniqueItems"] = unique
+ values = [{"id": 1}, {"id": 1}]
+ assert (
+ TypeAdapter(json_schema_to_type(schema)).validate_python(values) == values
+ )
class TestObjectTypes: