Skip to content

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

Compare JSON const and enum values by JSON equality (#6126)

prassu0177eac6f36e4ab
diff --git a/fastmcp_slim/fastmcp/utilities/json_schema_type.py b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
index b1bb8e393..c913927d7 100644
--- a/fastmcp_slim/fastmcp/utilities/json_schema_type.py
+++ b/fastmcp_slim/fastmcp/utilities/json_schema_type.py
@@ -87,6 +87,7 @@ from pydantic import (
EmailStr,
Field,
Json,
+ PlainValidator,
StringConstraints,
TypeAdapter,
create_model,
@@ -571,15 +572,39 @@ def _create_numeric_type(
return Annotated[base, Field(**constraints)] if constraints else base # type: ignore[return-value] # ty:ignore[invalid-type-form]
-def _create_enum(name: str, values: list[Any]) -> type:
+def _create_enum(name: str, values: list[Any]) -> Any:
"""Create enum type from list of values."""
if not values:
# Empty enum means no value is valid (same semantics as ``false``
# schema). Return the unsatisfiable type instead of ``Literal[()]``
# which triggers an AssertionError in Pydantic.
- return _UnsatisfiableType # type: ignore[return-value] # ty:ignore[invalid-return-type]
+ return _UnsatisfiableType
# Always return Literal for enum fields to preserve the literal nature
- return Literal[tuple(values)] # type: ignore[return-value] # ty:ignore[invalid-type-form]
+ literal = Literal[tuple(values)] # ty:ignore[invalid-type-form]
+ if all(value is None or isinstance(value, str) for value in values):
+ return literal
+
+ try:
+ hash(literal)
+ except TypeError:
+ hashable = False
+ else:
+ hashable = True
+
+ # Pydantic matches Literal values with Python equality, so True would pass
+ # for 1, also inside arrays and objects.
+ def check(value: Any) -> Any:
+ for allowed in values:
+ if _json_values_equal(value, allowed):
+ return allowed if hashable else value
+ raise ValueError(f"Input should be one of {values!r}")
+
+ if not hashable:
+ # A Literal holding an object or array cannot be hashed into a Union.
+ return Annotated[
+ Any, BeforeValidator(check), Field(json_schema_extra={"enum": values})
+ ]
+ return Annotated[literal, PlainValidator(check, json_schema_input_type=literal)]
def _json_values_equal(left: Any, right: Any) -> bool:
@@ -828,7 +853,7 @@ def _convert_schema(
return resolved_refs[ref]
if "const" in schema:
- return Literal[schema["const"]] # type: ignore
+ return _create_enum(f"Const_{len(_classes)}", [schema["const"]])
if "enum" in schema:
return _create_enum(f"Enum_{len(_classes)}", schema["enum"])
diff --git a/tests/client/test_result_hydration.py b/tests/client/test_result_hydration.py
index 915952d7c..1406aaf5a 100644
--- a/tests/client/test_result_hydration.py
+++ b/tests/client/test_result_hydration.py
@@ -5,8 +5,10 @@ and positional item schema the server emits has to survive that round trip.
"""
from datetime import date, datetime, time, timedelta
+from typing import Any
from uuid import UUID
+import pytest
from pydantic import BaseModel
from fastmcp import Client, FastMCP
@@ -21,6 +23,48 @@ class Reading(BaseModel):
class TestStructuredResultHydration:
+ @pytest.mark.parametrize(
+ ("field_schema", "value", "expected"),
+ [
+ ({"enum": [1, True]}, 1.0, 1),
+ ({"enum": [True, 1]}, 1.0, 1),
+ ({"enum": [1, True]}, 1, 1),
+ ({"enum": [1, True]}, True, True),
+ ({"enum": [0, False]}, 0.0, 0),
+ ({"enum": [False, 0]}, 0.0, 0),
+ ({"enum": [0, False]}, False, False),
+ ({"enum": [1.0, True]}, 1, 1.0),
+ ({"enum": [True, 1.0]}, 1, 1.0),
+ ({"const": 1}, 1.0, 1),
+ ({"const": 1.0}, 1, 1.0),
+ ({"anyOf": [{"const": 1}, {}]}, True, True),
+ ({"anyOf": [{"const": {}}, {"const": 1}]}, 1, 1),
+ ({"anyOf": [{"const": []}, {"const": 1}]}, [], []),
+ ],
+ )
+ async def test_const_enum_results_preserve_json_value_types(
+ self, field_schema: dict[str, Any], value: Any, expected: Any
+ ) -> None:
+ mcp = FastMCP()
+
+ @mcp.tool(
+ output_schema={
+ "type": "object",
+ "properties": {"value": field_schema},
+ "required": ["value"],
+ }
+ )
+ def constrained_result() -> dict[str, Any]:
+ return {"value": value}
+
+ async with Client(mcp) as client:
+ result = await client.call_tool("constrained_result")
+
+ assert result.structured_content == {"value": value}
+ assert type(result.structured_content["value"]) is type(value)
+ assert result.data.value == expected
+ assert type(result.data.value) is type(expected)
+
async def test_annotated_scalar_formats_arrive_as_python_types(self):
mcp = FastMCP()
diff --git a/tests/utilities/json_schema_type/test_json_schema_type.py b/tests/utilities/json_schema_type/test_json_schema_type.py
index df61408b7..a1c9a18da 100644
--- a/tests/utilities/json_schema_type/test_json_schema_type.py
+++ b/tests/utilities/json_schema_type/test_json_schema_type.py
@@ -4,7 +4,7 @@ import dataclasses
import warnings
from dataclasses import Field
from enum import Enum
-from typing import Any, Literal, cast
+from typing import Any, Literal, cast, get_args
import pytest
from pydantic import TypeAdapter, ValidationError
@@ -281,12 +281,74 @@ class TestConstrainedTypes:
validator = TypeAdapter(MyEnum)
schema = validator.json_schema()
type_ = json_schema_to_type(schema)
- assert type_ == Literal[1, 2]
+ assert get_args(type_)[0] == Literal[1, 2]
assert TypeAdapter(type_).validate_python(1) == 1
assert TypeAdapter(type_).validate_python(2) == 2
with pytest.raises(ValidationError):
TypeAdapter(type_).validate_python(3)
+ @pytest.mark.parametrize(
+ "values",
+ [
+ [1, True],
+ [True, 1],
+ [0, False],
+ [False, 0],
+ [1.0, True],
+ [True, 1.0],
+ [0.0, False],
+ [False, 0.0],
+ ],
+ )
+ def test_mixed_boolean_numeric_enums_preserve_value_types(
+ self, values: list[int | float | bool]
+ ) -> None:
+ validator = TypeAdapter(json_schema_to_type({"enum": values}))
+ for value in values:
+ result = validator.validate_python(value)
+ assert result == value
+ assert type(result) is type(value)
+ number = next(value for value in values if not isinstance(value, bool))
+ alternate = int(number) if isinstance(number, float) else float(number)
+ result = validator.validate_python(alternate)
+ assert result == number
+ assert type(result) is type(number)
+ for expected, actual in zip(
+ values, validator.json_schema()["enum"], strict=True
+ ):
+ assert actual == expected
+ assert type(actual) is type(expected)
+
+ @pytest.mark.parametrize(
+ "schema, value",
+ [
+ ({"const": 1}, True),
+ ({"enum": [1]}, True),
+ ({"const": True}, 1),
+ ({"const": [1]}, [True]),
+ ({"enum": [{"a": 0}]}, {"a": False}),
+ ],
+ )
+ def test_const_and_enum_reject_booleans_for_numbers(
+ self, schema: dict[str, Any], value: Any
+ ):
+ with pytest.raises(ValidationError):
+ TypeAdapter(json_schema_to_type(schema)).validate_python(value)
+
+ def test_boolean_falls_through_numeric_const_in_union(self):
+ validator = TypeAdapter(json_schema_to_type({"anyOf": [{"const": 1}, {}]}))
+ assert validator.validate_python(1) == 1
+ assert validator.validate_python(True) is True
+
+ def test_object_const_in_union(self):
+ validator = TypeAdapter(
+ json_schema_to_type({"anyOf": [{"const": {}}, {"const": 1}]})
+ )
+ assert validator.validate_python({}) == {}
+ assert validator.validate_python(1) == 1
+ with pytest.raises(ValidationError):
+ validator.validate_python({"a": 1})
+
def test_choice(self):
validator = TypeAdapter(Literal["x", "y"])
schema = validator.json_schema()