fix: decode nested JSON tool arguments by schema

This commit is contained in:
Ruiming Zhao authored and Xubin Ren committed 2026-10-25 13:04:53 +08:00
1 parent c9bd5ebb45
commit 6b930432cb
4 files changed
+244

No files matched your search

+63
View File
@@ -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,
+136
View File
@@ -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(