fix(tools): validate arguments with jsonschema without coercion (#6648)
Co-authored-by: xiong-wei1 <2318942410@qq.com>
This commit is contained in:
1 parent
25ed91ffeb
commit
8cce73465b
27 files changed
+689
-614
No files matched your search
@@ -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}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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]
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
Reference in new issue
Block a user