fix(tools): handle boolean JSON subschemas during argument validation

This commit is contained in:
Kail Tian authored and chengyongru committed 2026-09-23 00:06:45 +08:00
1 parent ac89579206
commit d37e2a7a0e
2 files changed
+72 -3

No files matched your search

+10 -3
View File
@@ -48,15 +48,20 @@ class Schema(ABC):
return f"{path}.{key}" if path else key return f"{path}.{key}" if path else key
@staticmethod @staticmethod
def validate_json_schema_value(val: Any, schema: dict[str, Any], path: str = "") -> list[str]: def validate_json_schema_value(
val: Any, schema: dict[str, Any] | bool, path: str = "",
) -> list[str]:
"""Validate ``val`` against a JSON Schema fragment; returns error messages (empty means valid). """Validate ``val`` against a JSON Schema fragment; returns error messages (empty means valid).
Used by :class:`Tool` and each concrete Schema's :meth:`validate_value`. Used by :class:`Tool` and each concrete Schema's :meth:`validate_value`.
""" """
label = path or "parameter"
if isinstance(schema, bool):
return [] if schema else [f"{label} is not allowed by schema"]
raw_type = schema.get("type") raw_type = schema.get("type")
nullable = (isinstance(raw_type, list) and "null" in raw_type) or schema.get("nullable", False) nullable = (isinstance(raw_type, list) and "null" in raw_type) or schema.get("nullable", False)
t = Schema.resolve_json_schema_type(raw_type) t = Schema.resolve_json_schema_type(raw_type)
label = path or "parameter"
if nullable and val is None: if nullable and val is None:
return [] return []
@@ -255,7 +260,9 @@ class Tool(ABC):
return params return params
return self._cast_object(params, schema) return self._cast_object(params, schema)
def _cast_value(self, val: Any, schema: dict[str, Any]) -> Any: 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")) t = self._resolve_type(schema.get("type"))
if t == "boolean" and isinstance(val, bool): if t == "boolean" and isinstance(val, bool):
+62
View File
@@ -6,6 +6,7 @@ import sys
from contextlib import asynccontextmanager from contextlib import asynccontextmanager
from pathlib import Path from pathlib import Path
from types import ModuleType, SimpleNamespace from types import ModuleType, SimpleNamespace
from unittest.mock import AsyncMock
from urllib.request import getproxies_environment from urllib.request import getproxies_environment
import httpx import httpx
@@ -244,6 +245,67 @@ async def test_saved_oauth_http_403_projects_failed_runtime_without_details(
assert "app.xmind.com" not in str(snapshot) assert "app.xmind.com" not in str(snapshot)
@pytest.mark.parametrize( "value_schema, params, error",
[
pytest.param(
True, {"value": {"count": "42", "enabled": False}}, None,
id="true-property-preserves-value",
),
pytest.param(
False, {"value": None}, "value is not allowed by schema",
id="false-property-rejects-null",
),
pytest.param(False, {}, None, id="false-property-can-be-absent"),
pytest.param(
{"type": "array", "items": True},
{"value": ["42", False, None, {"nested": [1]}]},
None,
id="true-items-preserve-values",
),
pytest.param(
{"type": "array", "items": False},
{"value": [1]},
"value[0] is not allowed by schema",
id="false-items-reject-element",
),
pytest.param(
{"type": "array", "items": False}, {"value": []}, None,
id="false-items-allow-empty-array",
),
pytest.param(
{"type": "object", "properties": {"blocked": False}},
{"value": {"blocked": "x"}},
"value.blocked is not allowed by schema",
id="nested-false-property-reports-path",
),
],
)
async def test_registry_executes_mcp_tools_with_boolean_subschemas(
value_schema, params, error,
) -> None:
session = SimpleNamespace(
call_tool=AsyncMock(return_value=SimpleNamespace(content=[_FakeTextContent("ok")])),
)
tool_def = SimpleNamespace(
name="demo",
description="demo tool",
inputSchema={"type": "object", "properties": {"value": value_schema}},
)
wrapper = MCPToolWrapper(session, "test", tool_def)
registry = ToolRegistry()
registry.register(wrapper)
result = await registry.execute(wrapper.name, params)
if error is None:
assert result == "ok"
session.call_tool.assert_awaited_once_with("demo", arguments=params)
else:
assert is_tool_error_result(result)
assert f"Invalid parameters for tool '{wrapper.name}': {error}" in result
session.call_tool.assert_not_awaited()
def test_wrapper_preserves_non_nullable_unions() -> None: def test_wrapper_preserves_non_nullable_unions() -> None:
tool_def = SimpleNamespace( tool_def = SimpleNamespace(
name="demo", name="demo",