diff --git a/docs/architecture.md b/docs/architecture.md index 4297705d1..8b5b90c5f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -144,6 +144,8 @@ 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. + ## Config and Paths The config schema lives in `nanobot/config/schema.py`. Loading and saving live in `nanobot/config/loader.py`. Runtime path helpers live in `nanobot/config/paths.py`. diff --git a/nanobot/agent/tools/base.py b/nanobot/agent/tools/base.py index b724586f6..52a1c1927 100644 --- a/nanobot/agent/tools/base.py +++ b/nanobot/agent/tools/base.py @@ -1,6 +1,7 @@ """Base class for agent tools.""" from __future__ import annotations +import json import math import typing from abc import ABC, abstractmethod @@ -310,9 +311,51 @@ class Tool(ABC): 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): diff --git a/tests/agent/test_runner_tool_execution.py b/tests/agent/test_runner_tool_execution.py index c61c2f009..49645b5ed 100644 --- a/tests/agent/test_runner_tool_execution.py +++ b/tests/agent/test_runner_tool_execution.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import json from typing import Any from unittest.mock import AsyncMock, MagicMock, patch @@ -24,6 +25,68 @@ from nanobot.providers.openai_responses.parsing import parse_response_output _MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars +@pytest.mark.parametrize("schema, emitted, expected", [ + ({"oneOf": [ + {"type": "object", "properties": {"count": {"type": "string"}}, "required": ["count"]}, + {"type": "object", "properties": {"count": {"type": "integer"}}, "required": ["count"]}, + ]}, '{"count":12}', {"count": 12}), + ({"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): + from mcp.server.lowlevel import Server + from mcp.shared.memory import create_connected_server_and_client_session + from mcp.types import TextContent + from mcp.types import Tool as MCPTool + + from nanobot.agent.loop import AgentLoop + from nanobot.agent.tools.mcp import MCPToolWrapper + from nanobot.session.manager import Session + + server = Server("nested-arguments-test") + received = [] + + @server.list_tools() + async def list_tools(): + return [MCPTool(name="echo", inputSchema={ + "type": "object", "properties": {"value": schema}, "required": ["value"], + })] + + @server.call_tool() + async def call_tool(name, arguments): + received.append((name, arguments)) + return [TextContent(type="text", text="accepted")] + + async with create_connected_server_and_client_session(server) as client: + definition = (await client.list_tools()).tools[0] + registry = ToolRegistry() + tool = MCPToolWrapper(client, "test", definition) + registry.register(tool) + schemas_before = json.dumps(registry.get_definitions()) + call = ToolCallRequest(id="nested", name=tool.name, arguments={"value": emitted}) + original_call = call.to_openai_tool_call() + provider = MagicMock() + provider.chat_stream_with_retry = AsyncMock(side_effect=[ + LLMResponse(content=None, tool_calls=[call]), LLMResponse(content="done"), + ]) + result = await AgentRunner().run(make_run_spec( + provider, tools=registry, model="test-model", max_iterations=2, + 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 + 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 + assert all(json.dumps(r.kwargs["tools"]) == schemas_before for r in requests) + session = Session(key="test:nested-arguments") + AgentLoop.__new__(AgentLoop)._save_turn(session, result.messages, skip=0) + replay = next(m for m in session.get_history() if m.get("tool_calls")) + assert replay["tool_calls"] == [original_call] + + class _DelayTool(Tool): def __init__( self, diff --git a/tests/tools/test_tool_registry.py b/tests/tools/test_tool_registry.py index 26949983c..0805895e7 100644 --- a/tests/tools/test_tool_registry.py +++ b/tests/tools/test_tool_registry.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json from typing import Any from unittest.mock import AsyncMock @@ -134,6 +135,80 @@ 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: + registry = ToolRegistry() + registry.register( + _FakeTool( + "read_note", + { + "type": "object", + "properties": { + "target": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": {"type": "string"}, + "path": {"type": "string"}, + }, + "required": ["type", "path"], + }, + { + "type": "object", + "properties": { + "type": {"type": "string"}, + "name": {"type": "string"}, + }, + "required": ["type", "name"], + }, + ], + }, + "format": {"type": "string"}, + }, + "required": ["target", "format"], + }, + ) + ) + + tool, params, error = registry.prepare_call( + "read_note", + { + "target": '{"type":"path","path":"Projects/nanobot.md"}', + "format": "content", + }, + ) + + assert tool is not None + assert error is None + assert params == { + "target": {"type": "path", "path": "Projects/nanobot.md"}, + "format": "content", + } + + +def test_prepare_call_preserves_json_like_text_for_string_schema() -> None: + registry = ToolRegistry() + registry.register( + _FakeTool( + "echo_text", + { + "type": "object", + "properties": {"value": {"type": "string"}}, + "required": ["value"], + }, + ) + ) + + tool, params, error = registry.prepare_call( + "echo_text", + {"value": '{"type":"path"}'}, + ) + + assert tool is not None + assert error is None + assert params == {"value": '{"type":"path"}'} + + def test_prepare_call_rejects_malformed_json_string_arguments() -> None: registry = ToolRegistry() registry.register(_FakeTool("read_file")) @@ -146,6 +221,67 @@ def test_prepare_call_rejects_malformed_json_string_arguments() -> None: assert "parameters must be a JSON object" in error +@pytest.mark.parametrize("union", ["oneOf", "anyOf"]) +@pytest.mark.parametrize("branches", [ + [{"type": "object"}, {"type": "string"}], + [{"type": "string"}, {"type": "object"}], + [{"type": "object"}, {}], + [{"type": "object"}, True], +]) +def test_nested_json_cast_preserves_unions_that_can_accept_strings(union, branches): + registry = ToolRegistry() + registry.register(_FakeTool("echo", { + "type": "object", "properties": {"value": {union: branches}}, + })) + original = {"value": '{"mode":"text"}'} + _, params, error = registry.prepare_call("echo", original) + assert error is None + assert params == original + + +@pytest.mark.parametrize("encoded", [True, False]) +def test_nested_json_cast_does_not_select_the_first_object_branch(encoded): + registry = ToolRegistry() + registry.register(_FakeTool("echo", { + "type": "object", "properties": {"value": {"oneOf": [ + {"type": "object", "properties": {"count": {"type": "string"}}}, + {"type": "object", "properties": {"count": {"type": "integer"}}}, + ]}}, + })) + 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} + + +@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}'), +]) +def test_nested_container_decoding_is_lossless_and_schema_directed(schema, value, expected): + registry = ToolRegistry() + registry.register(_FakeTool("echo", { + "type": "object", "properties": {"value": schema}, + "$defs": {"options": {"type": "object"}}, + })) + 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} + assert json.dumps(original) == arguments_before + assert json.dumps(registry.get_definitions()) == schemas_before + + def test_prepare_call_rejects_scalar_for_single_required_parameter() -> None: registry = ToolRegistry() registry.register(_FakeTool(