fix: use JSON equality for enum validation

This commit is contained in:
KennySimpson authored and Xubin Ren committed 2026-10-18 20:36:33 +08:00
1 parent 9fe061a537
commit 23bf1b87cd
2 files changed
+66 -1

No files matched your search

+21 -1
View File
@@ -33,6 +33,26 @@ def _is_json_integer(value: object) -> bool:
)
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 left is right
if isinstance(left, list) and isinstance(right, list):
left_items = cast(list[Any], left)
right_items = cast(list[Any], right)
return len(left_items) == len(right_items) and all(
_json_values_equal(a, b) for a, b in zip(left_items, right_items)
)
if isinstance(left, dict) and isinstance(right, dict):
left_object = cast(dict[str, Any], left)
right_object = cast(dict[str, Any], right)
return left_object.keys() == right_object.keys() and all(
_json_values_equal(value, right_object[key])
for key, value in left_object.items()
)
return left == right
class Schema(ABC):
"""Abstract base for JSON Schema fragments describing tool parameters.
@@ -107,7 +127,7 @@ class Schema(ABC):
return [f"{label} must be finite"]
errors: list[str] = []
if "enum" in schema and val not in schema["enum"]:
if "enum" in schema and not any(_json_values_equal(val, item) for item in schema["enum"]):
errors.append(f"{label} must be one of {schema['enum']}")
if t in ("integer", "number"):
if "minimum" in schema and val < schema["minimum"]:
+45
View File
@@ -194,6 +194,51 @@ def test_validate_params_enum_and_min_length() -> None:
assert any("mode must be one of" in e for e in errors)
@pytest.mark.parametrize(
"value, allowed, valid",
[
(True, 1, False),
(False, 0, False),
(1, True, False),
(0, False, False),
([True], [1], False),
({"enabled": True}, {"enabled": 1}, False),
(1.0, 1, True),
(True, True, True),
("x", "x", True),
({"a": 1, "b": 2}, {"b": 2.0, "a": 1.0}, True),
],
)
@pytest.mark.asyncio
async def test_registry_enforces_json_enum_equality(value, allowed, valid) -> None:
calls = []
class EnumTool(SampleTool):
@property
def parameters(self) -> dict[str, Any]:
return {
"type": "object",
"properties": {"value": {"enum": [allowed]}},
"required": ["value"],
}
async def execute(self, **kwargs: Any) -> str:
calls.append(kwargs["value"])
return "ok"
registry = ToolRegistry()
registry.register(EnumTool())
result = await registry.execute("sample", {"value": value})
if valid:
assert result == "ok"
assert calls == [value]
else:
assert "value must be one of" in result
assert calls == []
def test_validate_params_nested_object_and_array() -> None:
tool = SampleTool()
errors = tool.validate_params(