fix(tools): validate arguments with jsonschema without coercion (#6648)

Co-authored-by: xiong-wei1 <2318942410@qq.com>
This commit is contained in:
chengyongruandxiong-wei1 authored and GitHub committed 2026-11-13 13:32:12 +08:00
1 parent 25ed91ffeb
commit 8cce73465b
27 files changed
+689 -614

No files matched your search

+2 -264
View File
@@ -1,7 +1,5 @@
from __future__ import annotations
import json
import math
import typing
from abc import ABC, abstractmethod
from collections.abc import Callable
@@ -16,41 +14,6 @@ if typing.TYPE_CHECKING:
_ToolT = TypeVar("_ToolT", bound="Tool")
_JSON_TYPE_MAP: dict[str, type | tuple[type, ...]] = {
"string": str,
"integer": int,
"number": (int, float),
"boolean": bool,
"array": list,
"object": dict,
}
def _is_json_integer(value: object) -> bool:
return not isinstance(value, bool) and (
isinstance(value, int) or (isinstance(value, float) and value.is_integer())
)
def _json_values_equal(left: Any, right: Any) -> bool:
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.
@@ -59,32 +22,6 @@ class Schema(ABC):
:meth:`validate_json_schema_value` and :meth:`fragment` are the shared validation and normalization entry points.
"""
@staticmethod
def resolve_json_schema_type(t: Any) -> str | None:
"""Resolve the non-null type name from JSON Schema ``type`` (e.g. ``['string','null']`` -> ``'string'``)."""
if isinstance(t, list):
types = cast(list[Any], t)
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 t == "integer" and _is_json_integer(val):
return t
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
@staticmethod
def validate_json_schema_value(
val: Any, schema: dict[str, Any] | bool, path: str = "",
@@ -93,85 +30,9 @@ class Schema(ABC):
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"]
from nanobot.agent.tools.json_schema import validate_value
raw_type = schema.get("type")
nullable = (isinstance(raw_type, list) and "null" in raw_type) or schema.get("nullable", False)
t = Schema.resolve_json_schema_type(raw_type)
if (raw_type == "null" or raw_type == ["null"]) and val is not None:
return [f"{label} should be null"]
if nullable and val is None:
if "enum" in schema and val not in schema["enum"]:
return [f"{label} must be one of {schema['enum']}"]
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 _is_json_integer(val):
return [f"{label} should be integer"]
if t == "number" and (
not isinstance(val, _JSON_TYPE_MAP["number"]) or isinstance(val, bool)
):
return [f"{label} should be number"]
if t in _JSON_TYPE_MAP and t not in ("integer", "number") and not isinstance(val, _JSON_TYPE_MAP[t]):
return [f"{label} should be {t}"]
if t == "number" and isinstance(val, float) and not math.isfinite(val):
return [f"{label} must be finite"]
errors: list[str] = []
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"]:
errors.append(f"{label} must be >= {schema['minimum']}")
if "maximum" in schema and val > schema["maximum"]:
errors.append(f"{label} must be <= {schema['maximum']}")
if t == "string":
string_value = cast(str, val)
if "minLength" in schema and len(string_value) < schema["minLength"]:
errors.append(f"{label} must be at least {schema['minLength']} chars")
if "maxLength" in schema and len(string_value) > schema["maxLength"]:
errors.append(f"{label} must be at most {schema['maxLength']} chars")
if t == "object":
object_value = cast(dict[str, Any], val)
props = cast(dict[str, Any], schema.get("properties", {}))
required = cast(list[Any], schema.get("required", []))
for k in required:
if k not in object_value:
errors.append(f"missing required {Schema.subpath(path, k)}")
additional = schema.get("additionalProperties", True)
for k, v in object_value.items():
if k in props:
errors.extend(Schema.validate_json_schema_value(v, props[k], Schema.subpath(path, k)))
elif additional is False:
errors.append(f"unexpected parameter {Schema.subpath(path, k)}")
elif isinstance(additional, dict):
errors.extend(
Schema.validate_json_schema_value(
v,
cast(dict[str, Any], additional),
Schema.subpath(path, k),
)
)
if t == "array":
array_value = cast(list[Any], val)
if "minItems" in schema and len(array_value) < schema["minItems"]:
errors.append(f"{label} must have at least {schema['minItems']} items")
if "maxItems" in schema and len(array_value) > schema["maxItems"]:
errors.append(f"{label} must be at most {schema['maxItems']} items")
if "items" in schema:
prefix = f"{path}[{{}}]" if path else "[{}]"
for i, item in enumerate(array_value):
errors.extend(
Schema.validate_json_schema_value(item, schema["items"], prefix.format(i))
)
return errors
return validate_value(val, schema, path)
@staticmethod
def fragment(value: Any) -> dict[str, Any]:
@@ -214,15 +75,6 @@ class ToolResult(str):
class Tool(ABC):
"""Agent capability: read files, run commands, etc."""
_TYPE_MAP = _JSON_TYPE_MAP
_BOOL_TRUE = frozenset(("true", "1", "yes"))
_BOOL_FALSE = frozenset(("false", "0", "no"))
@staticmethod
def _resolve_type(t: Any) -> str | None:
"""Pick first non-null type from JSON Schema unions like ``['string','null']``."""
return Schema.resolve_json_schema_type(t)
@property
@abstractmethod
def name(self) -> str:
@@ -286,120 +138,6 @@ class Tool(ABC):
def error(content: str) -> ToolResult:
return ToolResult.error(content)
def _cast_object(self, obj: Any, schema: dict[str, Any]) -> dict[str, Any]:
if not isinstance(obj, dict):
return obj
props = cast(dict[str, Any], schema.get("properties", {}))
additional = schema.get("additionalProperties")
casted: dict[str, Any] = {}
object_value = cast(dict[str, Any], obj)
for k, v in object_value.items():
if k in props:
casted[k] = self._cast_value(v, props[k])
elif isinstance(additional, dict):
casted[k] = self._cast_value(v, cast(dict[str, Any], additional))
else:
casted[k] = v
return casted
def cast_params(self, params: dict[str, Any]) -> dict[str, Any]:
"""Apply safe schema-driven casts before validation."""
schema = self.parameters or {}
if schema.get("type", "object") != "object":
return params
return self._cast_object(params, schema)
@staticmethod
def _container_types(schema: dict[str, Any]) -> set[str]:
"""Recognize explicit container-only types, without choosing a union branch."""
options = [schema] if "type" in schema else schema.get("oneOf", schema.get("anyOf"))
if not isinstance(options, list) or not options:
return set()
types: set[str] = set()
for option in cast(list[Any], options):
if not isinstance(option, dict):
return set()
raw_type = cast(dict[str, Any], option).get("type")
members = cast(list[Any], raw_type) if isinstance(raw_type, list) else [raw_type]
for member in members:
if not isinstance(member, str) or member not in {"object", "array", "null"}:
return set()
if member != "null":
types.add(member)
return types
@classmethod
def _decode_json_container(cls, value: Any, schema: dict[str, Any]) -> Any:
"""Decode a JSON string only when it contains the expected container type."""
if not isinstance(value, str):
return value
stripped = value.strip()
expected_type = "object" if stripped.startswith("{") else "array"
if not stripped.startswith(("{", "[")) or expected_type not in cls._container_types(schema):
return value
try:
parsed = json.loads(stripped)
except (TypeError, ValueError):
return value
if expected_type == "object" and isinstance(parsed, dict):
return cast(dict[str, Any], parsed)
if expected_type == "array" and isinstance(parsed, list):
return cast(list[Any], parsed)
return value
def _cast_value(self, val: Any, schema: dict[str, Any] | bool) -> Any:
if isinstance(schema, bool):
return val
val = self._decode_json_container(val, schema)
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
if t == "integer" and _is_json_integer(val):
return int(val) if isinstance(val, float) else val
if t in self._TYPE_MAP and t not in ("boolean", "integer", "array", "object"):
expected = self._TYPE_MAP[t]
if isinstance(val, expected):
return val
if isinstance(val, str) and t in ("integer", "number"):
try:
return int(val) if t == "integer" else float(val)
except ValueError:
return val
if t == "string":
return val if val is None else str(val)
if t == "boolean" and isinstance(val, str):
low = val.lower()
if low in self._BOOL_TRUE:
return True
if low in self._BOOL_FALSE:
return False
return val
if t == "array" and isinstance(val, list):
items = schema.get("items")
array_value = cast(list[Any], val)
return [self._cast_value(x, items) for x in array_value] if items else array_value
if t == "object" and isinstance(val, dict):
return self._cast_object(val, schema)
return val
def validate_params(self, params: dict[str, Any]) -> list[str]:
"""Validate against JSON schema; empty list means valid."""
if not isinstance(cast(object, params), dict):
+3 -1
View File
@@ -116,6 +116,8 @@ class CronTool(Tool):
def validate_params(self, params: dict[str, Any]) -> list[str]:
errors = super().validate_params(params)
if errors:
return errors
action = params.get("action")
if action == "add" and not str(params.get("message") or "").strip():
errors.append("message is required when action='add'")
@@ -347,7 +349,7 @@ class CronTool(Tool):
return f"No recorded runs for job {job_id}."
lines = [f"Recent runs for '{job.name}' (id: {job.id}), newest first:"]
display_tz = self._display_timezone(job.schedule)
for run in reversed(job.state.run_history[-limit:]):
for run in reversed(job.state.run_history[-int(limit):]):
timestamp = self._format_timestamp(run.run_at_ms, display_tz)
lines.append(f"- {timestamp} — {run.status} ({run.duration_ms}ms)")
if run.error:
+1 -1
View File
@@ -671,7 +671,7 @@ DEFAULT_EXEC_SESSION_MANAGER = ExecSessionManager()
def clamp_session_int(value: int | None, default: int, minimum: int, maximum: int) -> int:
if value is None:
return default
return min(max(value, minimum), maximum)
return int(min(max(value, minimum), maximum))
def _truncate_output(output: str, max_output_chars: int) -> tuple[str, int]:
+4 -1
View File
@@ -396,6 +396,9 @@ class ReadFileTool(_FsTool):
**kwargs: Any,
) -> Any:
try:
# JSON Schema integers include 2.0; Python indices require int objects.
offset = int(offset)
limit = int(limit) if limit is not None else None
if not path:
return ToolResult.error("Error reading file: Unknown path")
@@ -1159,7 +1162,7 @@ class EditFileTool(_FsTool):
if replace_all:
selected = matches
elif occurrence is not None:
selected = [matches[occurrence - 1]]
selected = [matches[int(occurrence) - 1]]
elif line_hint is not None:
candidates = [match for match in matches if _match_covers_line(match, line_hint)]
if not candidates:
+114
View File
@@ -0,0 +1,114 @@
"""Standards-based tool validation and actionable errors, without argument coercion."""
from __future__ import annotations
import json
import math
from collections.abc import Callable, Iterator
from fractions import Fraction
from functools import lru_cache
from typing import Any, cast
import regex
from jsonschema import Draft202012Validator, TypeChecker
from jsonschema.exceptions import SchemaError, ValidationError
from jsonschema.protocols import Validator
from jsonschema.validators import (
extend, # pyright: ignore[reportUnknownVariableType]
validator_for,
)
from referencing import Registry
from referencing.exceptions import Unresolvable
def _finite_number(_checker: TypeChecker, value: Any) -> bool:
# Python's JSON decoder accepts NaN/Infinity, but JSON numbers must be finite.
return Draft202012Validator.TYPE_CHECKER.is_type(value, "number") and (
not isinstance(value, float) or math.isfinite(value)
)
def _multiple_of(
validator: Validator, divisor: int | float, value: Any, _schema: Any,
) -> Iterator[ValidationError]:
if validator.is_type(value, "number"):
# Decimal JSON spellings, not binary float fractions or an epsilon tolerance.
quotient = Fraction(str(value)) / Fraction(str(divisor))
if quotient.denominator != 1:
yield ValidationError(f"{value!r} is not a multiple of {divisor}")
@lru_cache(maxsize=128)
def _pattern(expression: str) -> regex.Pattern[str]:
return regex.compile(expression)
def _string_pattern(
validator: Validator, expression: str, value: Any, _schema: Any,
) -> Iterator[ValidationError]:
if validator.is_type(value, "string") and not _pattern(expression).search(value):
yield ValidationError(f"{value!r} does not match {expression!r}")
def _check_schema(cls: type[Validator], schema: Any) -> None:
metaschema_cls = validator_for(cls.META_SCHEMA, default=cls)
metaschema = metaschema_cls(cls.META_SCHEMA, format_checker=cls.FORMAT_CHECKER)
for error in metaschema.iter_errors(schema):
# jsonschema checks regex syntax with stdlib re. String patterns use our
# Unicode-capable engine; other schema/keyword checks remain unchanged.
if (
error.validator == "format" and error.validator_value == "regex"
and error.absolute_path and error.absolute_path[-1] == "pattern"
):
try:
_pattern(error.instance)
except regex.error:
pass
else:
continue
raise SchemaError.create_from(error)
@lru_cache(maxsize=128)
def _validator(schema_json: str) -> Validator:
schema: dict[str, Any] | bool = json.loads(schema_json)
if isinstance(schema, dict) and "$schema" in schema:
if not isinstance(schema["$schema"], str):
raise SchemaError("$schema must be a string")
# None disables the library's fallback; its stubs only accept a class.
cls = cast(Callable[..., type[Validator] | None], validator_for)(schema, default=None)
if cls is None:
raise SchemaError(f"Unsupported JSON Schema dialect: {schema['$schema']}")
else:
cls = Draft202012Validator
_check_schema(cls, schema)
# The library's factory returns a Validator class; its stubs leave extend untyped.
cls = cast(type[Validator], extend(
cls, validators={"multipleOf": _multiple_of, "pattern": _string_pattern},
type_checker=cls.TYPE_CHECKER.redefine("number", _finite_number),
))
# An empty registry resolves in-document refs only, without HTTP or file retrieval.
return cls(schema, registry=Registry[Any]())
def _error_messages(error: ValidationError, path: str) -> Iterator[str]:
suffix = error.json_path.removeprefix("$")
label = f"{path}{suffix}" if path else suffix.removeprefix(".")
yield f"{label or 'parameters'}: {error.message}"
for child in error.context:
yield from _error_messages(child, path)
def validate_value(value: Any, schema: dict[str, Any] | bool, path: str = "") -> list[str]:
"""Validate with the declared dialect (2020-12 by default); return model-facing errors."""
try:
validator = _validator(json.dumps(schema))
return list(dict.fromkeys(
message
for error in validator.iter_errors(value)
for message in _error_messages(error, path)
))
except SchemaError as exc:
return [f"Invalid tool schema: {exc.message}"]
except Unresolvable as exc:
return [f"Invalid tool schema: cannot resolve reference {exc}"]
-3
View File
@@ -177,9 +177,6 @@ class _LegacyErrorPrefixTool(Tool):
if callable(set_context):
set_context(ctx)
def cast_params(self, params: dict[str, Any]) -> dict[str, Any]:
return self._wrapped.cast_params(params)
def validate_params(self, params: dict[str, Any]) -> list[str]:
return self._wrapped.validate_params(params)
+6 -1
View File
@@ -15,7 +15,7 @@ from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeVar, cast
import httpx
from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.base import Schema, Tool, ToolResult
from nanobot.agent.tools.context import tool_log_content_allowed
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.config.network import NetworkConfig
@@ -714,6 +714,7 @@ class MCPToolWrapper(_MCPWrapperBase):
self._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_{tool_def.name}")
self._description = tool_def.description or tool_def.name
raw_schema = tool_def.inputSchema or {"type": "object", "properties": {}}
self._input_schema = raw_schema
self._parameters = _normalize_schema_for_openai(raw_schema)
self._tool_timeout = tool_timeout
# Replay is opt-in through explicit server declarations, not inferred
@@ -740,6 +741,10 @@ class MCPToolWrapper(_MCPWrapperBase):
def parameters(self) -> dict[str, Any]:
return self._parameters
def validate_params(self, params: dict[str, Any]) -> list[str]:
# Provider adaptations are not the server's validation contract.
return Schema.validate_json_schema_value(params, self._input_schema)
async def execute(self, **kwargs: Any) -> str:
result = await self._request_with_recovery(
lambda session: session.call_tool(self._original_name, arguments=kwargs),
+5 -5
View File
@@ -122,7 +122,7 @@ class ToolRegistry:
name: str,
params: Any,
) -> tuple[Tool | None, Any, str | None]:
"""Resolve, cast, and validate one tool call."""
"""Resolve and validate one tool call without changing argument values."""
tool = self.get(name)
if not tool:
suggestion = self._suggest_name(str(name))
@@ -148,13 +148,13 @@ class ToolRegistry:
)
)
cast_params = tool.cast_params(cast(dict[str, Any], params))
errors = tool.validate_params(cast_params)
arguments = cast(dict[str, Any], params)
errors = tool.validate_params(arguments)
if errors:
return tool, cast_params, (
return tool, arguments, (
ToolResult.error(f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors))
)
return tool, cast_params, None
return tool, arguments, None
@classmethod
def _coerce_argument_value(cls, value: Any) -> Any:
+7 -5
View File
@@ -416,8 +416,8 @@ class FindFilesTool(_SearchTool):
file_type=type,
include_dirs=include_dirs,
sort=sort,
head_limit=head_limit,
offset=offset,
head_limit=int(head_limit) if head_limit is not None else None,
offset=int(offset),
cancelled=cancelled,
)
except asyncio.CancelledError:
@@ -667,9 +667,11 @@ class GrepTool(_SearchTool):
self._execute_sync,
pattern=pattern, path=path, glob=glob, type=type, pages=pages,
case_insensitive=case_insensitive, fixed_strings=fixed_strings,
output_mode=output_mode, context_before=context_before, context_after=context_after,
max_matches=max_matches, max_results=max_results, head_limit=head_limit,
offset=offset, cancelled=cancelled,
output_mode=output_mode, context_before=int(context_before), context_after=int(context_after),
max_matches=int(max_matches) if max_matches is not None else None,
max_results=int(max_results) if max_results is not None else None,
head_limit=int(head_limit) if head_limit is not None else None,
offset=int(offset), cancelled=cancelled,
)
except asyncio.CancelledError:
cancelled.set()
+2 -2
View File
@@ -495,7 +495,7 @@ class WebSearchTool(Tool):
) -> str:
self._refresh_config()
provider = self.config.provider.strip().lower() or "brave"
n = min(max(count or self.config.max_results, 1), 10)
n = int(min(max(count or self.config.max_results, 1), 10))
if provider == "olostep":
return await self._search_olostep(query, n)
@@ -1314,7 +1314,7 @@ class WebFetchTool(Tool):
) -> Any:
url = url.strip(" \t\r\n`\"'")
extract_mode = kwargs.pop("extractMode", extract_mode)
max_chars = cast(int, kwargs.pop("maxChars", max_chars) or self.max_chars)
max_chars = int(kwargs.pop("maxChars", max_chars) or self.max_chars)
is_valid, error_msg = _validate_url_safe(url)
if not is_valid:
return ToolResult.error(json.dumps({"error": f"URL validation failed: {error_msg}", "url": url}, ensure_ascii=False))