fix(tools): preserve valid JSON Schema union arguments

This commit is contained in:
Kail Tian authored and Xubin Ren committed 2026-10-03 01:16:54 +08:00
1 parent 5825e15a6f
commit 432421bceb
3 files changed
+141 -1

No files matched your search

+27 -1
View File
@@ -43,6 +43,18 @@ class Schema(ABC):
return cast(str | None, next((x for x in types if x != "null"), None))
return cast(str | None, t)
@staticmethod
def match_json_schema_type(val: Any, types: list[Any]) -> str | None:
"""Select a union member matching the value without coercion."""
for t in types:
if not isinstance(t, str) or t not in _JSON_TYPE_MAP:
continue
if t in ("integer", "number") and isinstance(val, bool):
continue
if isinstance(val, _JSON_TYPE_MAP[t]):
return t
return None
@staticmethod
def subpath(path: str, key: str) -> str:
return f"{path}.{key}" if path else key
@@ -65,6 +77,12 @@ class Schema(ABC):
if nullable and val is None:
return []
if isinstance(raw_type, list):
types = [item for item in cast(list[Any], raw_type) if item != "null"]
if len(types) > 1:
t = Schema.match_json_schema_type(val, types)
if t is None:
return [f"{label} should match one of the types {types}"]
if t == "integer" and (not isinstance(val, int) or isinstance(val, bool)):
return [f"{label} should be integer"]
if t == "number" and (
@@ -263,7 +281,15 @@ class Tool(ABC):
def _cast_value(self, val: Any, schema: dict[str, Any] | bool) -> Any:
if isinstance(schema, bool):
return val
t = self._resolve_type(schema.get("type"))
raw_type = schema.get("type")
t = self._resolve_type(raw_type)
if isinstance(raw_type, list):
types = [item for item in cast(list[Any], raw_type) if item != "null"]
if len(types) > 1:
# A union does not imply a preferred type or a safe conversion target.
t = Schema.match_json_schema_type(val, types)
if t is None:
return val
if t == "boolean" and isinstance(val, bool):
return val
+26
View File
@@ -307,6 +307,32 @@ async def test_registry_executes_mcp_tools_with_boolean_subschemas(
session.call_tool.assert_not_awaited()
@pytest.mark.parametrize("types", [["integer", "string"], ["string", "integer"]])
@pytest.mark.parametrize("value", ["00123", "doc-A", 42])
async def test_registry_preserves_mcp_type_union_arguments(types, value) -> None:
session = SimpleNamespace(
call_tool=AsyncMock(return_value=SimpleNamespace(content=[_FakeTextContent("ok")])),
)
tool_def = SimpleNamespace(
name="lookup",
description="Look up an id without changing its type or value.",
inputSchema={
"type": "object",
"properties": {"id": {"type": types}},
"required": ["id"],
},
)
wrapper = MCPToolWrapper(session, "test", tool_def)
registry = ToolRegistry()
registry.register(wrapper)
result = await registry.execute(wrapper.name, {"id": value})
assert result == "ok"
session.call_tool.assert_awaited_once_with("lookup", arguments={"id": value})
assert type(session.call_tool.call_args.kwargs["arguments"]["id"]) is type(value)
def test_wrapper_preserves_non_nullable_unions() -> None:
tool_def = SimpleNamespace(
name="demo",
+88
View File
@@ -573,6 +573,94 @@ def test_cast_params_nested_object() -> None:
assert result["config"]["debug"] is True
@pytest.mark.parametrize("types", [["array", "object"], ["object", "array"]])
@pytest.mark.parametrize(
"value, expected", [(["2"], [2]), ({"count": "2"}, {"count": 2})],
)
def test_cast_type_union_recurses_into_matching_container(types, value, expected) -> None:
tool = CastTestTool({
"type": "object",
"properties": {"value": {
"type": types,
"properties": {"count": {"type": "integer", "minimum": 1}},
"items": {"type": "integer", "minimum": 1},
}},
})
result = tool.cast_params({"value": value})
assert result == {"value": expected}
assert tool.validate_params(result) == []
invalid = {"count": 0} if isinstance(value, dict) else [0]
assert "must be >= 1" in "; ".join(tool.validate_params({"value": invalid}))
@pytest.mark.parametrize("types", [["integer", "string"], ["string", "integer"]])
@pytest.mark.parametrize(
"value, error", [(0, "must be >= 1"), ("ab", "must be at least 3 chars")],
)
def test_type_union_enforces_matching_type_constraints(types, value, error) -> None:
tool = CastTestTool({
"type": "object",
"properties": {"value": {"type": types, "minimum": 1, "minLength": 3}},
})
result = tool.cast_params({"value": value})
assert result["value"] is value
assert error in "; ".join(tool.validate_params(result))
@pytest.mark.parametrize("types", [["integer", "string"], ["string", "integer"]])
@pytest.mark.parametrize("value", [True, 1.5, None])
def test_type_union_rejects_undeclared_types_without_coercion(types, value) -> None:
tool = CastTestTool({
"type": "object",
"properties": {"value": {"type": types}},
})
result = tool.cast_params({"value": value})
assert result["value"] is value
assert tool.validate_params(result)
@pytest.mark.parametrize(
"types, value, error",
[
(["number", "boolean", "null"], True, None),
(["number", "boolean", "null"], 1.5, None),
(["number", "boolean", "null"], None, None),
(["string", "number"], float("inf"), "value must be finite"),
(["string", "number"], float("nan"), "value must be finite"),
],
)
def test_type_union_preserves_numeric_boolean_and_null_values(types, value, error) -> None:
for order in (types, types[::-1]):
tool = CastTestTool({
"type": "object",
"properties": {"value": {"type": order}},
})
result = tool.cast_params({"value": value})
assert result["value"] is value
assert tool.validate_params(result) == ([error] if error else [])
@pytest.mark.parametrize("value, expected", [("42", 42), (None, None)])
def test_nullable_integer_retains_safe_casts(value, expected) -> None:
tool = CastTestTool({
"type": "object",
"properties": {"value": {"type": ["integer", "null"]}},
})
result = tool.cast_params({"value": value})
assert result == {"value": expected}
assert tool.validate_params(result) == []
def test_cast_params_bool_not_cast_to_int() -> None:
"""Booleans should not be silently cast to integers."""
tool = CastTestTool(