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

+1 -1
View File
@@ -144,7 +144,7 @@ Important files:
Tool behavior is part of the model contract. Keep user-visible tool names, schemas, and error messages stable unless a change is intentional.
Before tool execution, schema-guided casting can decode a nested JSON string when the declared type requires an object or array. Simple container-only unions are supported without selecting a preferred branch. String-accepting unions, malformed JSON, mismatched values, and schemas without an explicit container type stay unchanged. This step does not infer types through references or composition rules. The model-facing schema and original tool-call arguments in history remain unchanged.
Before tool execution, arguments are validated against JSON Schema without coercion. Numeric strings and serialized nested objects or arrays are rejected when their JSON types do not match the schema; actionable tool errors let the model correct the call. MCP validation uses the server's original input schema, independently of provider-facing adaptations. Validation defaults to draft 2020-12, honors supported explicit dialects, and does not retrieve external references. The original tool-call arguments in history remain unchanged. JSON Schema integers include numbers such as 2.0; built-in tools adapt these validated values to Python integers where an index is required.
## Config and Paths
+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))
+6
View File
@@ -48,6 +48,10 @@ dependencies = [
"setproctitle>=1.3.7,<2.0.0; sys_platform != 'win32'",
"questionary>=2.1.1,<3.0.0",
"mcp>=1.26.0,<2.0.0",
# 4.21 fixes recursive enum equality for booleans versus 0/1.
"jsonschema>=4.21.0,<5.0.0",
"referencing>=0.30.0,<1.0.0",
"regex>=2024.11.6",
"json-repair>=0.57.0,<1.0.0",
"chardet>=3.0.2,<6.0.0",
"openai>=2.8.0",
@@ -108,6 +112,8 @@ dev = [
"virtualenv>=20.35.4,<21.0.0",
"ruff>=0.1.0",
"basedpyright>=1.39.0,<2.0.0",
"types-jsonschema>=4.20.0,<5.0.0",
"types-regex>=2024.11.6",
"setproctitle>=1.3.7,<2.0.0",
"pymupdf>=1.25.0",
"pypdf>=6.21.3,<7.0.0",
+14 -5
View File
@@ -31,7 +31,7 @@ _MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
({"anyOf": [{"type": "object"}, {"type": "string"}]}, '{"count":12}', '{"count":12}'),
({"type": "array", "items": {"type": "integer"}}, '["1","2"]', [1, 2]),
])
async def test_nested_arguments_reach_mcp_without_rewriting_model_history(schema, emitted, expected):
async def test_mcp_arguments_can_be_corrected_without_rewriting_model_history(schema, emitted, expected):
from mcp.server.lowlevel import Server
from mcp.shared.memory import create_connected_server_and_client_session
from mcp.types import TextContent
@@ -63,18 +63,27 @@ async def test_nested_arguments_reach_mcp_without_rewriting_model_history(schema
schemas_before = json.dumps(registry.get_definitions())
call = ToolCallRequest(id="nested", name=tool.name, arguments={"value": emitted})
original_call = call.to_openai_tool_call()
responses = [LLMResponse(content=None, tool_calls=[call])]
needs_correction = emitted != expected
if needs_correction:
corrected = ToolCallRequest(id="corrected", name=tool.name, arguments={"value": expected})
responses.append(LLMResponse(content=None, tool_calls=[corrected]))
responses.append(LLMResponse(content="done"))
provider = MagicMock()
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[call]), LLMResponse(content="done"),
])
provider.chat_stream_with_retry = AsyncMock(side_effect=responses)
result = await AgentRunner().run(make_run_spec(
provider, tools=registry, model="test-model", max_iterations=2,
provider, tools=registry, model="test-model", max_iterations=len(responses),
initial_messages=[{"role": "user", "content": "echo the value"}],
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
))
assert result.final_content == "done"
assert received == [("echo", {"value": expected})]
requests = provider.chat_stream_with_retry.await_args_list
if needs_correction:
error = next(m for m in requests[1].kwargs["messages"] if m.get("role") == "tool")
assert "Invalid parameters" in error["content"]
assert "value:" in error["content"]
assert "is not of type" in error["content"]
model_call = next(m for m in requests[1].kwargs["messages"] if m.get("tool_calls"))
assert model_call["tool_calls"] == [original_call]
assert call.to_openai_tool_call() == original_call
@@ -117,9 +117,6 @@ async def test_loader_entry_point_error_wrapper_preserves_tool_api(tmp_path):
def concurrency_safe(self) -> bool:
return False
def cast_params(self, params: dict) -> dict:
return {"value": str(params["value"])}
def validate_params(self, params: dict) -> list[str]:
return [] if params == {"value": "1"} else ["bad value"]
@@ -143,7 +140,6 @@ async def test_loader_entry_point_error_wrapper_preserves_tool_api(tmp_path):
assert tool.config_key == "api_plugin"
assert tool.read_only is True
assert tool.concurrency_safe is False
assert tool.cast_params({"value": 1}) == {"value": "1"}
assert tool.validate_params({"value": "1"}) == []
assert tool.to_schema() == {"name": "api_plugin", "custom": True}
+9 -5
View File
@@ -26,7 +26,8 @@ def _job(service: CronService):
)
async def test_history_reads_recent_runs_without_changing_job(tmp_path: Path, monkeypatch) -> None:
@pytest.mark.parametrize("limit", [2, 2.0])
async def test_history_reads_recent_runs_without_changing_job(tmp_path: Path, monkeypatch, limit) -> None:
now = 1773673200000
monkeypatch.setattr(cron_service, "_now_ms", lambda: now)
outcomes = iter(["ok"] * 5 + ["error", "skipped"])
@@ -56,7 +57,7 @@ async def test_history_reads_recent_runs_without_changing_job(tmp_path: Path, mo
default = await registry.execute("cron", {"action": "history", "job_id": job.id})
assert len([line for line in default.splitlines() if line.startswith("- ")]) == 5
limited = await registry.execute("cron", {"action": "history", "job_id": job.id, "limit": 2})
limited = await registry.execute("cron", {"action": "history", "job_id": job.id, "limit": limit})
assert "Report failed" in limited and "Chat busy" in limited
assert "125ms" in limited and "America/Denver" in limited
assert "ok" not in limited
@@ -87,9 +88,12 @@ async def test_history_reports_unknown_job(tmp_path: Path) -> None:
assert "job missing not found" in result
@pytest.mark.parametrize("limit", [0, 21])
async def test_history_validates_limit(tmp_path: Path, limit: int) -> None:
@pytest.mark.parametrize("limit, reason", [
(0, "is less than the minimum of 1"),
(21, "is greater than the maximum of 20"),
])
async def test_history_validates_limit(tmp_path: Path, limit: int, reason: str) -> None:
result = await _registry(CronService(tmp_path / "jobs.json")).execute(
"cron", {"action": "history", "job_id": "test", "limit": limit},
)
assert "limit must be" in result
assert f"limit: {limit} {reason}" in result
@@ -100,3 +100,15 @@ class TestSchemaSelfDescribesRequirements:
# accidentally introduced).
tool = CronTool(_SvcStub())
assert tool.parameters["required"] == ["action"]
async def test_invalid_action_returns_tool_error_and_allows_correction(registry):
from nanobot.agent.tools.registry import is_tool_error_result
arguments = {"action": ["list"]}
result = await registry.execute("cron", arguments)
assert is_tool_error_result(result)
assert "action:" in result and "string" in result
assert arguments == {"action": ["list"]}
assert await registry.execute("cron", {"action": "list"}) == "No scheduled jobs."
@@ -163,7 +163,8 @@ async def test_structured_calls_keep_arguments_out_of_text_and_preserve_validati
call = result.tool_calls[0]
assert (call.id, call.name, call.arguments) == ("call_fixture", "exec_session", arguments)
assert tool.validate_params(call.arguments) == (
["timeout_ms should be integer"] if isinstance(timeout_ms, dict) else []
[f"timeout_ms: {timeout_ms!r} is not of type 'integer', 'null'"]
if isinstance(timeout_ms, dict) else []
)
if stream:
assert "".join(deltas) == text
+3 -2
View File
@@ -406,11 +406,12 @@ def test_exec_session_wait_for_searches_before_response_truncation():
assert len(result.partition("\n")[0]) == 10_000
def test_exec_one_shot_accepts_max_output_tokens_alias(tmp_path):
@pytest.mark.parametrize("limit", [1000, 1000.0])
def test_exec_one_shot_accepts_max_output_tokens_alias(tmp_path, limit):
async def run() -> str:
tool = ExecTool(working_dir=str(tmp_path), timeout=5)
command = _python_command("print('A' * 2000)")
return await tool.execute(command=command, max_output_tokens=1000, yield_time_ms=10000)
return await tool.execute(command=command, max_output_tokens=limit, yield_time_ms=10000)
result = asyncio.run(run())
+35
View File
@@ -556,3 +556,38 @@ class TestWorkspaceRestriction:
)
assert "Patch applied:" in result
assert target.read_text(encoding="utf-8") == "after\n"
@pytest.mark.parametrize("offset, limit", [(2.0, 1), (2, 1.0)])
async def test_read_file_accepts_json_integers_without_changing_arguments(tmp_path, offset, limit):
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
path = tmp_path / "integer-offset.txt"
path.write_text("first\nsecond\nthird\n", encoding="utf-8")
registry = ToolRegistry()
registry.register(ReadFileTool(workspace=tmp_path))
arguments = {"path": str(path), "offset": offset, "limit": limit}
result = await registry.execute("read_file", arguments)
assert not is_tool_error_result(result)
assert result.startswith("2| second\n")
assert "Use offset=3 to continue" in result
assert type(arguments["offset"]) is type(offset)
assert type(arguments["limit"]) is type(limit)
async def test_edit_file_accepts_json_integer_occurrence(tmp_path):
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
path = tmp_path / "integer-occurrence.txt"
path.write_text("first first", encoding="utf-8")
registry = ToolRegistry()
registry.register(EditFileTool(workspace=tmp_path))
arguments = {"path": str(path), "old_text": "first", "new_text": "second", "occurrence": 2.0}
result = await registry.execute("edit_file", arguments)
assert not is_tool_error_result(result)
assert path.read_text(encoding="utf-8") == "first second"
assert type(arguments["occurrence"]) is float
+239
View File
@@ -0,0 +1,239 @@
"""Tool calls use the server's schema, reject invalid arguments, and allow correction."""
from copy import deepcopy
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import pytest
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.mcp import MCPToolWrapper
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
@tool_parameters({
"type": "object",
"properties": {"count": {"type": "integer"}},
"required": ["count"],
})
class CountingTool(Tool):
name = "counting"
description = "Count without changing the supplied value."
def __init__(self):
self.calls = []
async def execute(self, **kwargs):
self.calls.append(kwargs)
return "ok"
async def test_model_can_correct_type_error_and_retry():
tool = CountingTool()
registry = ToolRegistry()
registry.register(tool)
arguments = {"count": "123"}
result = await registry.execute(tool.name, arguments)
assert is_tool_error_result(result)
assert "count: '123' is not of type 'integer'" in result
assert arguments == {"count": "123"}
assert tool.calls == []
assert await registry.execute(tool.name, {"count": 123}) == "ok"
assert tool.calls == [{"count": 123}]
def make_mcp_registry(schema):
session = SimpleNamespace(call_tool=AsyncMock(return_value=SimpleNamespace(content=[])))
wrapper = MCPToolWrapper(session, "schema", SimpleNamespace(
name="check", description="Check arguments", inputSchema=schema,
))
registry = ToolRegistry()
registry.register(wrapper)
return registry, wrapper, session
ADDRESS_SCHEMA = {
"type": "object",
"$defs": {
"Address/model": {
"type": "object",
"properties": {"city": {"type": "string"}, "zip": {"type": "integer"}},
"required": ["city", "zip"],
},
},
"properties": {
"addr": {"$ref": "#/$defs/Address~1model"},
"count": {"anyOf": [{"type": "integer"}, {"type": "string"}]},
},
"required": ["addr"],
}
@pytest.mark.parametrize("arguments, expected", [
({"addr": {"zip": "98101"}}, ["addr:", "city", "addr.zip:", "integer"]),
({"addr": "Seattle"}, ["addr:", "object"]),
({"addr": '{"city":"Seattle","zip":98101}'}, ["addr:", "object"]),
({"addr": {"city": "Seattle", "zip": 98101}, "count": {}}, ["count:", "integer", "string"]),
])
async def test_mcp_ref_and_union_errors_reach_model(arguments, expected):
registry, wrapper, session = make_mcp_registry(deepcopy(ADDRESS_SCHEMA))
result = await registry.execute(wrapper.name, arguments)
assert is_tool_error_result(result)
for text in expected:
assert text in result
session.call_tool.assert_not_awaited()
@pytest.mark.parametrize("count", [3, "three"])
def test_mcp_ref_and_union_accept_valid_arguments(count):
registry, wrapper, _ = make_mcp_registry(deepcopy(ADDRESS_SCHEMA))
arguments = {"addr": {"city": "Seattle", "zip": 98101}, "count": count}
_, prepared, error = registry.prepare_call(wrapper.name, arguments)
assert error is None
assert prepared == arguments
def test_mcp_nullable_model_validates_original_schema():
schema = deepcopy(ADDRESS_SCHEMA)
schema["properties"]["addr"] = {
"anyOf": [{"$ref": "#/$defs/Address~1model"}, {"type": "null"}],
"default": None,
}
original = deepcopy(schema)
registry, wrapper, _ = make_mcp_registry(schema)
assert wrapper.parameters["properties"]["addr"]["nullable"] is True
assert registry.prepare_call(wrapper.name, {"addr": None})[2] is None
assert schema == original
@pytest.mark.parametrize("parent", [
{"type": "page_id", "page_id": "synthetic-page"},
{"type": "database_id", "database_id": "synthetic-database"},
{"type": "workspace"},
])
def test_notion_style_parent_discriminator_accepts_one_branch(parent):
# Same oneOf/const structure as @notionhq/notion-mcp-server's move-page parent.
schema = {
"type": "object",
"properties": {"parent": {"$ref": "#/$defs/parent"}},
"$defs": {"parent": {"oneOf": [
{"type": "object", "properties": {"type": {"const": "page_id"}, "page_id": {"type": "string"}}, "required": ["type", "page_id"]},
{"type": "object", "properties": {"type": {"const": "database_id"}, "database_id": {"type": "string"}}, "required": ["type", "database_id"]},
{"type": "object", "properties": {"type": {"const": "workspace"}}, "required": ["type"]},
]}},
}
registry, wrapper, _ = make_mcp_registry(schema)
assert registry.prepare_call(wrapper.name, {"parent": parent})[2] is None
error = registry.prepare_call(wrapper.name, {"parent": {**parent, "type": "invalid"}})[2]
assert is_tool_error_result(error)
assert "parent.type:" in error
@pytest.mark.parametrize("dialect, array_schema", [
("http://json-schema.org/draft-07/schema#", {
"type": "array", "items": [{"type": "string"}, {"type": "integer"}],
"additionalItems": False,
}),
("https://json-schema.org/draft/2020-12/schema", {
"type": "array", "prefixItems": [{"type": "string"}, {"type": "integer"}],
"items": False,
}),
])
def test_positional_array_schemas_validate_without_casting(dialect, array_schema):
registry, wrapper, _ = make_mcp_registry({
"$schema": dialect, "type": "object", "properties": {"pair": array_schema},
})
assert registry.prepare_call(wrapper.name, {"pair": ["a", 1]})[2] is None
error = registry.prepare_call(wrapper.name, {"pair": ["a", "1"]})[2]
assert is_tool_error_result(error)
assert "pair[1]: '1' is not of type 'integer'" in error
assert is_tool_error_result(registry.prepare_call(wrapper.name, {"pair": ["a", 1, 2]})[2])
def test_malformed_server_schema_returns_tool_error():
registry, wrapper, _ = make_mcp_registry({
"type": "object", "properties": {"pair": {"type": "array", "items": []}},
})
error = registry.prepare_call(wrapper.name, {"pair": [1]})[2]
assert is_tool_error_result(error)
assert "Invalid tool schema" in error
@pytest.mark.parametrize("reference", ["https://example.invalid/schema", "file:///private/schema.json"])
def test_server_schema_cannot_load_external_references(monkeypatch, reference):
retrieve = Mock(side_effect=AssertionError("Schema validation must not perform I/O"))
monkeypatch.setattr("urllib.request.urlopen", retrieve)
registry, wrapper, _ = make_mcp_registry({
"type": "object", "properties": {"value": {"$ref": reference}},
})
error = registry.prepare_call(wrapper.name, {"value": 1})[2]
assert is_tool_error_result(error)
assert "resolve" in error.lower()
retrieve.assert_not_called()
@pytest.mark.parametrize("dialect", [
"https://example.invalid/unsupported-dialect", {}, [], None,
])
async def test_invalid_declared_dialect_returns_error_without_calling_server(dialect):
registry, wrapper, session = make_mcp_registry({
"$schema": dialect, "type": "object", "properties": {},
})
result = await registry.execute(wrapper.name, {})
assert is_tool_error_result(result)
assert "Invalid tool schema" in result
assert ("Unsupported JSON Schema dialect" if isinstance(dialect, str) else "$schema must be a string") in result
session.call_tool.assert_not_awaited()
@pytest.mark.parametrize("amount, valid", [
(4.02, True), (4.021, False), (-4.02, True), (0.07000000000000002, False),
])
async def test_decimal_multiple_of_does_not_use_binary_rounding_or_tolerance(amount, valid):
registry, wrapper, session = make_mcp_registry({
"type": "object", "properties": {"amount": {"type": "number", "multipleOf": 0.01}},
})
arguments = {"amount": amount}
result = await registry.execute(wrapper.name, arguments)
assert is_tool_error_result(result) is not valid
assert arguments == {"amount": amount}
assert session.call_tool.await_count == int(valid)
if not valid:
assert "amount:" in result and "multiple" in result
@pytest.mark.parametrize("dialect", [None, "http://json-schema.org/draft-07/schema#"])
@pytest.mark.parametrize("expression, name, valid", [
(r"^\p{L}+$", "北京", True),
(r"^\p{L}+$", "123", False),
("[", "北京", False),
])
async def test_string_pattern_uses_unicode_engine_and_rejects_invalid_schema(dialect, expression, name, valid):
schema = {"type": "object", "properties": {"name": {"type": "string", "pattern": expression}}}
if dialect is not None:
schema["$schema"] = dialect
registry, wrapper, session = make_mcp_registry(schema)
result = await registry.execute(wrapper.name, {"name": name})
assert is_tool_error_result(result) is not valid
assert session.call_tool.await_count == int(valid)
if not valid:
assert ("Invalid tool schema" if expression == "[" else "name:") in result
@@ -0,0 +1,50 @@
"""Validate schemas generated by a real FastMCP server before submitting calls."""
from typing import Annotated
import pytest
from mcp.server.fastmcp import FastMCP
from mcp.shared.memory import create_connected_server_and_client_session
from pydantic import Field
from nanobot.agent.tools.mcp import MCPToolWrapper
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
@pytest.mark.parametrize("tool_name, valid, invalid", [
("amount", 4.02, 4.021),
("name", "北京", "123"),
])
async def test_fastmcp_decimal_and_unicode_constraints(tool_name, valid, invalid):
server = FastMCP("schema-compatibility")
calls = []
@server.tool()
def amount(value: Annotated[float, Field(multiple_of=0.01)]) -> str:
calls.append(value)
return f"accepted {value}"
@server.tool()
def name(value: Annotated[str, Field(pattern=r"^\p{L}+$")]) -> str:
calls.append(value)
return f"accepted {value}"
async with create_connected_server_and_client_session(server._mcp_server) as client:
definition = next(tool for tool in (await client.list_tools()).tools if tool.name == tool_name)
direct = await client.call_tool(tool_name, {"value": valid})
assert not direct.isError
assert calls == [valid]
registry = ToolRegistry()
wrapper = MCPToolWrapper(client, "compatibility", definition)
registry.register(wrapper)
arguments = {"value": valid}
result = await registry.execute(wrapper.name, arguments)
assert result == f"accepted {valid}"
assert arguments == {"value": valid}
assert calls == [valid, valid]
result = await registry.execute(wrapper.name, {"value": invalid})
assert is_tool_error_result(result)
assert "value:" in result
assert calls == [valid, valid]
+6 -6
View File
@@ -258,7 +258,7 @@ async def test_saved_oauth_http_403_projects_failed_runtime_without_details(
id="true-property-preserves-value",
),
pytest.param(
False, {"value": None}, "value is not allowed by schema",
False, {"value": None}, "parameters: False schema does not allow None",
id="false-property-rejects-null",
),
pytest.param(False, {}, None, id="false-property-can-be-absent"),
@@ -271,7 +271,7 @@ async def test_saved_oauth_http_403_projects_failed_runtime_without_details(
pytest.param(
{"type": "array", "items": False},
{"value": [1]},
"value[0] is not allowed by schema",
"value: Expected at most 0 items but found 1 extra: 1",
id="false-items-reject-element",
),
pytest.param(
@@ -281,8 +281,8 @@ async def test_saved_oauth_http_403_projects_failed_runtime_without_details(
pytest.param(
{"type": "object", "properties": {"blocked": False}},
{"value": {"blocked": "x"}},
"value.blocked is not allowed by schema",
id="nested-false-property-reports-path",
"value: False schema does not allow 'x'",
id="nested-false-property-rejects-value",
),
],
)
@@ -2452,8 +2452,8 @@ def test_long_server_name_tools_are_matched_by_server_name() -> None:
@pytest.mark.parametrize("params, error", [
({"team": "nanobot", "query": "bug"}, None),
({"team": "nanobot", "customView": "saved-view"}, None),
({"query": "bug"}, "missing required team"),
({"team": "nanobot", "customView": ""}, "customView must be at least 1 chars"),
({"query": "bug"}, "parameters:"),
({"team": "nanobot", "customView": ""}, "customView:"),
])
async def test_optional_mcp_filters_reach_server_unchanged(params, error):
async def call_tool(name, arguments):
+28
View File
@@ -1081,3 +1081,31 @@ async def test_grep_closes_document_stream_and_preserves_locators(tmp_path, monk
else:
assert result.startswith("source.pdf\n")
assert visited == [2]
@pytest.mark.parametrize("operation", ["find_files", "grep_content", "grep_files"])
async def test_search_tools_accept_json_integer_pagination_and_context(tmp_path, operation):
from nanobot.agent.tools.registry import ToolRegistry
for name in ("a.txt", "b.txt", "c.txt"):
(tmp_path / name).write_text("before\nneedle\nafter\n", encoding="utf-8")
if operation == "find_files":
tool = FindFilesTool(workspace=tmp_path)
arguments = {"head_limit": 1.0, "offset": 1.0}
else:
tool = GrepTool(workspace=tmp_path)
arguments = {"pattern": "needle", "head_limit": 1.0, "offset": 1.0,
"context_before": 1.0, "context_after": 1.0}
if operation == "grep_files":
arguments["output_mode"] = "files_with_matches"
registry = ToolRegistry()
registry.register(tool)
integers = {key: int(value) if isinstance(value, float) else value for key, value in arguments.items()}
expected = await registry.execute(tool.name, integers)
result = await registry.execute(tool.name, arguments)
assert not is_tool_error_result(expected)
assert result == expected
assert type(arguments["head_limit"]) is float
assert type(arguments["offset"]) is float
+42 -26
View File
@@ -8,7 +8,7 @@ import pytest
from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.filesystem import ReadFileTool
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
class _FakeTool(Tool):
@@ -135,7 +135,7 @@ def test_prepare_call_parses_json_string_arguments() -> None:
assert error is None
def test_prepare_call_decodes_json_string_for_nested_object_schema() -> None:
def test_prepare_call_reports_json_string_for_nested_object_schema() -> None:
registry = ToolRegistry()
registry.register(
_FakeTool(
@@ -179,9 +179,11 @@ def test_prepare_call_decodes_json_string_for_nested_object_schema() -> None:
)
assert tool is not None
assert error is None
assert error is not None
assert "target:" in error
assert "is not of type 'object'" in error
assert params == {
"target": {"type": "path", "path": "Projects/nanobot.md"},
"target": '{"type":"path","path":"Projects/nanobot.md"}',
"format": "content",
}
@@ -228,7 +230,7 @@ def test_prepare_call_rejects_malformed_json_string_arguments() -> None:
[{"type": "object"}, {}],
[{"type": "object"}, True],
])
def test_nested_json_cast_preserves_unions_that_can_accept_strings(union, branches):
def test_string_values_satisfy_unions_that_allow_strings(union, branches):
registry = ToolRegistry()
registry.register(_FakeTool("echo", {
"type": "object", "properties": {"value": {union: branches}},
@@ -240,7 +242,7 @@ def test_nested_json_cast_preserves_unions_that_can_accept_strings(union, branch
@pytest.mark.parametrize("encoded", [True, False])
def test_nested_json_cast_does_not_select_the_first_object_branch(encoded):
def test_object_union_requires_an_object_value(encoded):
registry = ToolRegistry()
registry.register(_FakeTool("echo", {
"type": "object", "properties": {"value": {"oneOf": [
@@ -249,25 +251,33 @@ def test_nested_json_cast_does_not_select_the_first_object_branch(encoded):
]}},
}))
value = {"count": 12}
_, params, error = registry.prepare_call("echo", {"value": json.dumps(value) if encoded else value})
assert error is None
assert params == {"value": value}
arguments = {"value": json.dumps(value) if encoded else value}
_, params, error = registry.prepare_call("echo", arguments)
assert params == arguments
if encoded:
assert is_tool_error_result(error)
assert "value:" in error
assert "is not of type 'object'" in error
else:
assert error is None
@pytest.mark.parametrize("schema, value, expected", [
({"type": "object"}, '{"count":12}', {"count": 12}),
({"type": "array"}, '[{"count":12}]', [{"count": 12}]),
({"type": ["object", "null"]}, '{"count":12}', {"count": 12}),
({"type": ["object", "array"]}, '[1,2]', [1, 2]),
({"anyOf": [{"type": "object"}, {"type": "array"}]}, '[1,2]', [1, 2]),
({"type": ["string", "object"]}, '{"count":12}', '{"count":12}'),
({"type": ["object", "string"]}, '{"count":12}', '{"count":12}'),
({"type": "object"}, '{count:12}', '{count:12}'),
({"type": "object"}, '[1,2]', '[1,2]'),
({"type": "array"}, '{"count":12}', '{"count":12}'),
({"$ref": "#/$defs/options"}, '{"count":12}', '{"count":12}'),
@pytest.mark.parametrize("schema, value, valid", [
({"type": "object"}, {"count": 12}, True),
({"type": "array"}, [{"count": 12}], True),
({"type": "object"}, '{"count":12}', False),
({"type": "array"}, '[{"count":12}]', False),
({"type": ["object", "null"]}, '{"count":12}', False),
({"type": ["object", "array"]}, '[1,2]', False),
({"anyOf": [{"type": "object"}, {"type": "array"}]}, '[1,2]', False),
({"type": ["string", "object"]}, '{"count":12}', True),
({"type": ["object", "string"]}, '{"count":12}', True),
({"type": "object"}, '{count:12}', False),
({"type": "object"}, '[1,2]', False),
({"type": "array"}, '{"count":12}', False),
({"$ref": "#/$defs/options"}, '{"count":12}', False),
])
def test_nested_container_decoding_is_lossless_and_schema_directed(schema, value, expected):
def test_registry_validates_values_without_mutating_arguments_or_schema(schema, value, valid):
registry = ToolRegistry()
registry.register(_FakeTool("echo", {
"type": "object", "properties": {"value": schema},
@@ -276,10 +286,16 @@ def test_nested_container_decoding_is_lossless_and_schema_directed(schema, value
original = {"value": value}
schemas_before = json.dumps(registry.get_definitions())
arguments_before = json.dumps(original)
_, params, _ = registry.prepare_call("echo", original)
assert params == {"value": expected}
_, params, error = registry.prepare_call("echo", original)
assert params == original
assert json.dumps(original) == arguments_before
assert json.dumps(registry.get_definitions()) == schemas_before
if valid:
assert error is None
else:
assert is_tool_error_result(error)
assert "value:" in error
assert "is not of type" in error
def test_prepare_call_rejects_scalar_for_single_required_parameter() -> None:
@@ -301,7 +317,7 @@ def test_prepare_call_rejects_scalar_for_single_required_parameter() -> None:
assert "parameters must be a JSON object" in error
def test_prepare_call_rejects_unquoted_scalar_strings_before_schema_cast() -> None:
def test_prepare_call_rejects_unquoted_scalar_strings() -> None:
registry = ToolRegistry()
registry.register(_FakeTool(
"message",
@@ -391,7 +407,7 @@ async def test_registry_rejects_unknown_builtin_tool_parameters(tmp_path) -> Non
)
assert "Invalid parameters" in result
assert "unexpected parameter line_limit" in result
assert "Additional properties are not allowed ('line_limit' was unexpected)" in result
assert "one" not in result
+77 -279
View File
@@ -113,7 +113,7 @@ def test_schema_validate_value_matches_tool_validate_params() -> None:
expected = _Mini().validate_params(params)
assert Schema.validate_json_schema_value(params, root, "") == expected
assert obj.validate_value(params, "") == expected
assert IntegerSchema(minimum=1).validate_value(0, "n") == ["n must be >= 1"]
assert IntegerSchema(minimum=1).validate_value(0, "n") == ["n: 0 is less than the minimum of 1"]
def test_schema_classes_equivalent_to_sample_tool_parameters() -> None:
@@ -150,7 +150,7 @@ async def test_registry_executes_decorated_tool_end_to_end() -> None:
reg = ToolRegistry()
reg.register(DecoratedSampleTool())
ok = await reg.execute("decorated_sample", {"query": "hello", "count": "3"})
ok = await reg.execute("decorated_sample", {"query": "hello", "count": 3})
assert ok == "ok:3"
err = await reg.execute("decorated_sample", {"query": "h", "count": 3})
@@ -162,35 +162,35 @@ def test_integer_schema_accepts_integral_json_numbers(schema_type) -> None:
assert Schema.validate_json_schema_value(3.0, {"type": schema_type}) == []
async def test_registry_casts_integral_json_number_to_integer() -> None:
async def test_registry_preserves_integral_json_number() -> None:
reg = ToolRegistry()
reg.register(DecoratedSampleTool())
result = await reg.execute("decorated_sample", {"query": "hello", "count": 3.0})
assert result == "ok:3"
assert result == "ok:3.0"
def test_validate_params_missing_required() -> None:
tool = SampleTool()
errors = tool.validate_params({"query": "hi"})
assert "missing required count" in "; ".join(errors)
assert "'count' is a required property" in "; ".join(errors)
def test_validate_params_type_and_range() -> None:
tool = SampleTool()
errors = tool.validate_params({"query": "hi", "count": 0})
assert any("count must be >= 1" in e for e in errors)
assert any("count: 0 is less than the minimum of 1" in e for e in errors)
errors = tool.validate_params({"query": "hi", "count": "2"})
assert any("count should be integer" in e for e in errors)
assert any("count: '2' is not of type 'integer'" in e for e in errors)
def test_validate_params_enum_and_min_length() -> None:
tool = SampleTool()
errors = tool.validate_params({"query": "h", "count": 2, "mode": "slow"})
assert any("query must be at least 2 chars" in e for e in errors)
assert any("mode must be one of" in e for e in errors)
assert any("query: 'h' is too short" in e for e in errors)
assert any("mode: 'slow' is not one of" in e for e in errors)
@pytest.mark.parametrize(
@@ -234,7 +234,7 @@ async def test_registry_enforces_json_enum_equality(value, allowed, valid) -> No
assert result == "ok"
assert calls == [value]
else:
assert "value must be one of" in result
assert f"value: {value!r} is not one of" in result
assert calls == []
@@ -247,8 +247,8 @@ def test_validate_params_nested_object_and_array() -> None:
"meta": {"flags": [1, "ok"]},
}
)
assert any("missing required meta.tag" in e for e in errors)
assert any("meta.flags[0] should be string" in e for e in errors)
assert any("meta: 'tag' is a required property" in e for e in errors)
assert any("meta.flags[0]: 1 is not of type 'string'" in e for e in errors)
def test_validate_params_ignores_unknown_fields() -> None:
@@ -260,7 +260,7 @@ def test_validate_params_ignores_unknown_fields() -> None:
def test_tool_parameters_schema_rejects_unknown_fields_by_default() -> None:
tool = DecoratedSampleTool()
errors = tool.validate_params({"query": "hi", "count": 2, "extra": "x"})
assert errors == ["unexpected parameter extra"]
assert errors == ["parameters: Additional properties are not allowed ('extra' was unexpected)"]
def test_validate_params_validates_typed_additional_properties() -> None:
@@ -269,11 +269,11 @@ def test_validate_params_validates_typed_additional_properties() -> None:
"properties": {},
"additionalProperties": {"type": "integer"},
}
tool = CastTestTool(schema)
tool = SchemaTestTool(schema)
errors = tool.validate_params({"extra": "2"})
assert errors == ["extra should be integer"]
assert errors == ["extra: '2' is not of type 'integer'"]
async def test_registry_returns_validation_error() -> None:
@@ -597,19 +597,19 @@ def test_exec_extract_absolute_paths_ignores_pipe_tilde() -> None:
assert not any(p.startswith("~") for p in paths)
class CastTestTool(Tool):
"""Minimal tool for testing cast_params."""
class SchemaTestTool(Tool):
"""Minimal tool with a supplied parameter schema."""
def __init__(self, schema: dict[str, Any]) -> None:
self._schema = schema
@property
def name(self) -> str:
return "cast_test"
return "schema_test"
@property
def description(self) -> str:
return "test tool for casting"
return "test tool for schema validation"
@property
def parameters(self) -> dict[str, Any]:
@@ -619,81 +619,32 @@ class CastTestTool(Tool):
return "ok"
def test_cast_params_string_to_int() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"count": {"type": "integer"}},
}
)
result = tool.cast_params({"count": "42"})
assert result["count"] == 42
assert isinstance(result["count"], int)
@pytest.mark.parametrize("schema, value, valid", [
({"type": "integer"}, "42", 42),
({"type": "number"}, "3.14", 3.14),
({"type": "boolean"}, "false", False),
({"type": "string"}, 123, "123"),
({"type": "array", "items": {"type": "integer"}}, ["1", "2"], [1, 2]),
({"type": "object", "properties": {"port": {"type": "integer"}}}, {"port": "8080"}, {"port": 8080}),
])
def test_registry_rejects_wrong_types_and_accepts_corrected_arguments(schema, value, valid):
tool = SchemaTestTool({"type": "object", "properties": {"value": schema}})
registry = ToolRegistry()
registry.register(tool)
_, arguments, error = registry.prepare_call(tool.name, {"value": value})
def test_cast_params_string_to_number() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"rate": {"type": "number"}},
}
)
result = tool.cast_params({"rate": "3.14"})
assert result["rate"] == 3.14
assert isinstance(result["rate"], float)
def test_cast_params_string_to_bool() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"enabled": {"type": "boolean"}},
}
)
assert tool.cast_params({"enabled": "true"})["enabled"] is True
assert tool.cast_params({"enabled": "false"})["enabled"] is False
assert tool.cast_params({"enabled": "1"})["enabled"] is True
def test_cast_params_array_items() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {
"nums": {"type": "array", "items": {"type": "integer"}},
},
}
)
result = tool.cast_params({"nums": ["1", "2", "3"]})
assert result["nums"] == [1, 2, 3]
def test_cast_params_nested_object() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {
"config": {
"type": "object",
"properties": {
"port": {"type": "integer"},
"debug": {"type": "boolean"},
},
},
},
}
)
result = tool.cast_params({"config": {"port": "8080", "debug": "true"}})
assert result["config"]["port"] == 8080
assert result["config"]["debug"] is True
assert arguments == {"value": value}
assert error is not None
assert "value" in error
assert "is not of type" in error
assert registry.prepare_call(tool.name, {"value": valid})[2] is None
@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({
@pytest.mark.parametrize("value", [[2], {"count": 2}])
def test_type_union_validates_matching_container(types, value) -> None:
tool = SchemaTestTool({
"type": "object",
"properties": {"value": {
"type": types,
@@ -702,42 +653,33 @@ def test_cast_type_union_recurses_into_matching_container(types, value, expected
}},
})
result = tool.cast_params({"value": value})
assert result == {"value": expected}
assert tool.validate_params(result) == []
assert tool.validate_params({"value": value}) == []
invalid = {"count": 0} if isinstance(value, dict) else [0]
assert "must be >= 1" in "; ".join(tool.validate_params({"value": invalid}))
assert "is less than the minimum of 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")],
"value, error", [(0, "is less than the minimum of 1"), ("ab", "is too short")],
)
def test_type_union_enforces_matching_type_constraints(types, value, error) -> None:
tool = CastTestTool({
tool = SchemaTestTool({
"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))
assert error in "; ".join(tool.validate_params({"value": value}))
@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({
tool = SchemaTestTool({
"type": "object",
"properties": {"value": {"type": types}},
})
result = tool.cast_params({"value": value})
assert result["value"] is value
assert tool.validate_params(result)
assert tool.validate_params({"value": value})
@pytest.mark.parametrize(
@@ -746,176 +688,73 @@ def test_type_union_rejects_undeclared_types_without_coercion(types, value) -> N
(["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"),
(["string", "number"], float("inf"), "value: inf is not of type 'string', 'number'"),
(["string", "number"], float("nan"), "value: nan is not of type 'string', 'number'"),
],
)
def test_type_union_preserves_numeric_boolean_and_null_values(types, value, error) -> None:
for order in (types, types[::-1]):
tool = CastTestTool({
tool = SchemaTestTool({
"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 [])
errors = tool.validate_params({"value": value})
expected = f"value: {value!r} is not of type {', '.join(repr(t) for t in order)}"
assert errors == ([expected] if error else [])
@pytest.mark.parametrize("value, expected", [("42", 42), (None, None)])
def test_nullable_integer_retains_safe_casts(value, expected) -> None:
tool = CastTestTool({
@pytest.mark.parametrize("value", [42, None])
def test_nullable_integer_accepts_integer_and_null(value) -> None:
tool = SchemaTestTool({
"type": "object",
"properties": {"value": {"type": ["integer", "null"]}},
})
result = tool.cast_params({"value": value})
assert result == {"value": expected}
assert tool.validate_params(result) == []
assert tool.validate_params({"value": value}) == []
def test_cast_params_bool_not_cast_to_int() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"count": {"type": "integer"}},
}
)
result = tool.cast_params({"count": True})
assert result["count"] is True
errors = tool.validate_params(result)
assert any("count should be integer" in e for e in errors)
def test_cast_params_preserves_empty_string() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"name": {"type": "string"}},
}
)
result = tool.cast_params({"name": ""})
assert result["name"] == ""
def test_cast_params_bool_string_false() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"flag": {"type": "boolean"}},
}
)
assert tool.cast_params({"flag": "false"})["flag"] is False
assert tool.cast_params({"flag": "False"})["flag"] is False
assert tool.cast_params({"flag": "0"})["flag"] is False
assert tool.cast_params({"flag": "no"})["flag"] is False
assert tool.cast_params({"flag": "NO"})["flag"] is False
def test_cast_params_bool_string_invalid() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"flag": {"type": "boolean"}},
}
)
result = tool.cast_params({"flag": "random"})
assert result["flag"] == "random"
result = tool.cast_params({"flag": "maybe"})
assert result["flag"] == "maybe"
def test_cast_params_invalid_string_to_int() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"count": {"type": "integer"}},
}
)
result = tool.cast_params({"count": "abc"})
assert result["count"] == "abc"
result = tool.cast_params({"count": "12.5.7"})
assert result["count"] == "12.5.7"
def test_cast_params_invalid_string_to_number() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"rate": {"type": "number"}},
}
)
result = tool.cast_params({"rate": "not_a_number"})
assert result["rate"] == "not_a_number"
def test_validate_params_rejects_boolean_as_integer() -> None:
tool = SchemaTestTool({"type": "object", "properties": {"count": {"type": "integer"}}})
assert tool.validate_params({"count": True}) == ["count: True is not of type 'integer'"]
@pytest.mark.parametrize(
"value",
[float("nan"), float("inf"), float("-inf"), "NaN", "Infinity", "-Infinity"],
)
def test_cast_params_rejects_non_finite_numbers(value: float | str) -> None:
tool = CastTestTool(
def test_validate_params_rejects_non_finite_numbers(value: float | str) -> None:
tool = SchemaTestTool(
{
"type": "object",
"properties": {"rate": {"type": "number"}},
}
)
result = tool.cast_params({"rate": value})
assert tool.validate_params(result) == ["rate must be finite"]
assert tool.validate_params({"rate": value}) == [f"rate: {value!r} is not of type 'number'"]
def test_validate_params_bool_not_accepted_as_number() -> None:
tool = CastTestTool(
tool = SchemaTestTool(
{
"type": "object",
"properties": {"rate": {"type": "number"}},
}
)
errors = tool.validate_params({"rate": False})
assert any("rate should be number" in e for e in errors)
assert errors == ["rate: False is not of type 'number'"]
def test_cast_params_none_values() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {
"name": {"type": "string"},
"count": {"type": "integer"},
"items": {"type": "array"},
"config": {"type": "object"},
},
}
)
result = tool.cast_params(
{
"name": None,
"count": None,
"items": None,
"config": None,
}
)
assert result["name"] is None
assert result["count"] is None
assert result["items"] is None
assert result["config"] is None
@pytest.mark.parametrize("schema_type", ["string", "integer", "array", "object"])
def test_validate_params_rejects_undeclared_null(schema_type) -> None:
tool = SchemaTestTool({"type": "object", "properties": {"value": {"type": schema_type}}})
assert tool.validate_params({"value": None}) == [f"value: None is not of type '{schema_type}'"]
def test_cast_params_single_value_not_auto_wrapped_to_array() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"items": {"type": "array"}},
}
)
result = tool.cast_params({"items": 5})
assert result["items"] == 5
result = tool.cast_params({"items": "text"})
assert result["items"] == "text"
@pytest.mark.parametrize("value", [5, "text"])
def test_validate_params_rejects_scalar_for_array(value) -> None:
tool = SchemaTestTool({"type": "object", "properties": {"items": {"type": "array"}}})
assert tool.validate_params({"items": value}) == [f"items: {value!r} is not of type 'array'"]
async def test_completed_exec_returns_exit_code() -> None:
@@ -1055,20 +894,12 @@ def test_exec_runtime_schema_matches_configured_limit(limit, runtime_parameter)
assert ExecTool().parameters["properties"][runtime_parameter]["maximum"] == 86400
def test_resolve_type_simple_string() -> None:
assert Tool._resolve_type("string") == "string"
def test_resolve_type_union_with_null() -> None:
assert Tool._resolve_type(["string", "null"]) == "string"
@pytest.mark.parametrize("raw_type", ["null", ["null"]])
@pytest.mark.parametrize("value", ["", 0, False, [], {}])
def test_null_only_schema_rejects_non_null_values(raw_type, value) -> None:
schema = {"type": raw_type}
assert Schema.validate_json_schema_value(value, schema, "value") == [
"value should be null"
f"value: {value!r} is not of type 'null'"
]
assert Schema.validate_json_schema_value(None, schema) == []
@@ -1077,14 +908,13 @@ def test_null_only_schema_rejects_non_null_values(raw_type, value) -> None:
"schema",
[
{"type": ["string", "null"], "enum": ["fast"]},
{"type": "string", "nullable": True, "enum": ["fast"]},
{"type": ["integer", "null"], "enum": [1]},
{"type": ["string", "integer", "null"], "enum": ["fast", 1]},
],
)
def test_nullable_schema_still_enforces_enum(schema) -> None:
assert Schema.validate_json_schema_value(None, schema, "mode") == [
f"mode must be one of {schema['enum']}"
f"mode: None is not one of {schema['enum']}"
]
assert Schema.validate_json_schema_value(None, {**schema, "enum": [None]}) == []
for value in schema["enum"]:
@@ -1096,16 +926,8 @@ def test_nullable_string_schema_enforces_enum() -> None:
assert StringSchema(nullable=True, enum=["fast", None]).validate_value(None) == []
def test_resolve_type_only_null() -> None:
assert Tool._resolve_type(["null"]) is None
def test_resolve_type_none_input() -> None:
assert Tool._resolve_type(None) is None
def test_validate_nullable_param_accepts_string() -> None:
tool = CastTestTool(
tool = SchemaTestTool(
{
"type": "object",
"properties": {"name": {"type": ["string", "null"]}},
@@ -1116,7 +938,7 @@ def test_validate_nullable_param_accepts_string() -> None:
def test_validate_nullable_param_accepts_none() -> None:
tool = CastTestTool(
tool = SchemaTestTool(
{
"type": "object",
"properties": {"name": {"type": ["string", "null"]}},
@@ -1126,30 +948,6 @@ def test_validate_nullable_param_accepts_none() -> None:
assert errors == []
def test_validate_nullable_flag_accepts_none() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"name": {"type": "string", "nullable": True}},
}
)
errors = tool.validate_params({"name": None})
assert errors == []
def test_cast_nullable_param_no_crash() -> None:
tool = CastTestTool(
{
"type": "object",
"properties": {"name": {"type": ["string", "null"]}},
}
)
result = tool.cast_params({"name": "hello"})
assert result["name"] == "hello"
result = tool.cast_params({"name": None})
assert result["name"] is None
@pytest.mark.parametrize("command", [
"cat ~unknown/file.txt",
"cat --config=~unknown/file.txt",
@@ -102,3 +102,21 @@ async def test_execute_rejects_invalid_url_after_cleaning(url):
data = json.loads(result)
assert "error" in data
assert "URL validation failed" in data["error"]
async def test_web_fetch_accepts_json_integer_character_limit(monkeypatch):
from nanobot.agent.tools.registry import ToolRegistry
monkeypatch.setattr(FakeResponse, "headers", {"content-type": "text/plain"})
monkeypatch.setattr(FakeResponse, "text", "x" * 200)
registry = ToolRegistry()
registry.register(WebFetchTool())
arguments = {"url": "https://example.com/page", "maxChars": 100.0}
with _patched_web_fetch():
result = await registry.execute("web_fetch", arguments)
data = json.loads(result)
assert data["text"].partition("\n\n")[2] == "x" * 100
assert data["truncated"] is True
assert type(arguments["maxChars"]) is float
+3 -2
View File
@@ -71,7 +71,8 @@ def test_search_concurrency_without_api_key(
@pytest.mark.asyncio
async def test_brave_search(monkeypatch):
@pytest.mark.parametrize("count", [1, 1.0])
async def test_brave_search(monkeypatch, count):
async def mock_get(self, url, **kw):
assert "brave" in url
assert kw["headers"]["X-Subscription-Token"] == "brave-key"
@@ -82,7 +83,7 @@ async def test_brave_search(monkeypatch):
monkeypatch.setattr(httpx.AsyncClient, "get", mock_get)
tool = _tool(provider="brave", api_key="brave-key", user_agent="nanobot-search-test")
result = await tool.execute(query="nanobot", count=1)
result = await tool.execute(query="nanobot", count=count)
assert "NanoBot" in result
assert "https://example.com" in result