Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions core/agent_runtime/tools/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,34 @@ def validate_value(self, value: Any, path: str = "") -> list[str]:
return Schema.validate_json_schema_value(value, self.to_json_schema(), path)


def format_invalid_input(tool_name: str, errors: list[str]) -> str:
"""The one message a rejected tool call produces.

Shape ported from the Rotifer Protocol CLI (measured 2026-11-27): error
code first, then which contract was violated, then one line per offending
field, then an explicit statement that nothing ran plus what to do next.

The "nothing was run" line is the load-bearing one. A rejected call never
reaches ``execute``, but a model reading a bare field list cannot tell a
pre-flight rejection from a partial execution and guesses the wrong
recovery.

Two deliberate departures from the original. The leading ``Error:`` stays
because the runner, the session reducer and the evidence ledger all key
off it. And each line keeps the accepted values where the schema declares
them: the original says "must be equal to one of the allowed values" and
then withholds them, which costs the caller another round trip to find
out what it should have passed.
"""

detail = "\n".join(f" - {error}" for error in errors)
return (
f"Error: INVALID_INPUT — the input does not match `{tool_name}`'s "
f"inputSchema\n{detail}\n"
f"Nothing was run. Fix the field(s) above and call `{tool_name}` again."
)


class Tool(ABC):
"""Agent capability: read files, run commands, etc."""

Expand Down Expand Up @@ -338,6 +366,28 @@ def validate_params(self, params: dict[str, Any]) -> list[str]:
params, {**schema, "type": "object"}, ""
)

def unknown_param_names(self, params: dict[str, Any]) -> list[str]:
"""Keys the caller sent that the tool's schema never declared.

Mirrors :meth:`_cast_object`'s escape hatches exactly — a schema with
no declared ``properties``, or one that opts into
``"additionalProperties": true``, accepts anything, so nothing is
unknown. Everywhere else ``_cast_object`` drops the key, and a silent
drop is how a caller keeps making the same malformed call: it never
learns the argument was ignored. Naming the keys here is what lets
``prepare_call`` report them instead of dropping them.
"""

if not isinstance(params, dict):
return []
schema = self.parameters or {}
props = schema.get("properties", {})
if not props:
return []
if schema.get("additionalProperties", False) is True:
return []
return [key for key in params if key not in props]

def to_schema(self) -> dict[str, Any]:
return {
"type": "function",
Expand Down
21 changes: 14 additions & 7 deletions core/agent_runtime/tools/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from contextlib import AsyncExitStack
from typing import Any

from core.agent_runtime.tools.base import Tool
from core.agent_runtime.tools.base import Tool, format_invalid_input
from core.agent_runtime.tools.semantic_hint import build_miss_message
from core.agent_runtime.tools.model_notes import ERROR_HINT

Expand Down Expand Up @@ -97,14 +97,21 @@ def prepare_call(
),
)

props = (tool.parameters or {}).get("properties", {})
accepted = ", ".join(sorted(props)) if props else "none (free-form)"
# Unknown keys are reported, never silently dropped. A drop teaches the
# caller nothing, so the same malformed call comes back; naming the key
# next to what the tool does accept ends the loop in one turn. They are
# listed first because a stray key is the likeliest root cause when a
# required field also looks missing.
errors = [
f"unknown parameter {key!r} is not declared (accepted: {accepted})"
for key in tool.unknown_param_names(params)
]
cast_params = tool.cast_params(params)
errors = tool.validate_params(cast_params)
errors.extend(tool.validate_params(cast_params))
if errors:
return (
tool,
cast_params,
(f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors)),
)
return tool, cast_params, format_invalid_input(name, errors)
return tool, cast_params, None

async def execute(self, name: str, params: dict[str, Any]) -> Any:
Expand Down
193 changes: 193 additions & 0 deletions tests/test_tool_schema_precheck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
"""Schema pre-check on the tool boundary: reject before execute, and say why.

The pre-check itself predates this file — ``prepare_call`` already refused a
call that failed ``validate_params`` and returned before ``execute``. What these
tests pin is the two things it did not do:

1. **Report unknown keys instead of dropping them.** ``_cast_object`` discarded
anything the schema had not declared, so a caller that invented a field got
a normal-looking success and repeated the same mistake. (Measured cause of a
documented 20-turn loop sending an undeclared ``justification``.)
2. **Say that nothing ran.** A bare field list is indistinguishable from a
partial execution to a model choosing its recovery.

The message shape is ported from the Rotifer Protocol CLI (measured
2026-11-27): error code, violated contract, one line per offending field, then
"nothing was run".
"""

from __future__ import annotations

import asyncio
import sys
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))

from core.agent_runtime.tools.base import Tool, format_invalid_input, tool_parameters
from core.agent_runtime.tools.registry import ToolRegistry

_RUNS: list[dict[str, Any]] = []


@tool_parameters(
{
"type": "object",
"properties": {
"path": {"type": "string"},
"limit": {"type": "integer"},
"mode": {"type": "string", "enum": ["read", "write"]},
},
"required": ["path"],
}
)
class _StrictTool(Tool):
@property
def name(self) -> str:
return "strict_demo"

@property
def description(self) -> str:
return "Demo tool with a closed parameter set."

async def execute(self, **kwargs: Any) -> Any:
_RUNS.append(kwargs)
return "ran"


@tool_parameters(
{
"type": "object",
"properties": {"path": {"type": "string"}},
"additionalProperties": True,
}
)
class _PassthroughTool(Tool):
@property
def name(self) -> str:
return "passthrough_demo"

@property
def description(self) -> str:
return "Demo tool that opts into extra keys."

async def execute(self, **kwargs: Any) -> Any:
_RUNS.append(kwargs)
return "ran"


@tool_parameters({"type": "object", "properties": {}})
class _OpenTool(Tool):
@property
def name(self) -> str:
return "open_demo"

@property
def description(self) -> str:
return "Demo tool that declares no properties."

async def execute(self, **kwargs: Any) -> Any:
_RUNS.append(kwargs)
return "ran"


def _registry() -> ToolRegistry:
registry = ToolRegistry()
registry.register(_StrictTool())
registry.register(_PassthroughTool())
registry.register(_OpenTool())
return registry


def _call(name: str, params: dict[str, Any]) -> Any:
_RUNS.clear()
return asyncio.run(_registry().execute(name, params))


# ---- unknown keys are reported, not dropped --------------------------------


def test_unknown_key_is_named_and_nothing_runs():
result = _call("strict_demo", {"path": "a.txt", "justification": "because"})

assert "INVALID_INPUT" in result
assert "justification" in result
assert "strict_demo" in result
assert "Nothing was run" in result
assert _RUNS == [], "a rejected call must never reach execute()"


def test_unknown_key_message_lists_what_is_accepted():
result = _call("strict_demo", {"path": "a.txt", "bogus": 1})

assert "accepted: limit, mode, path" in result


def test_unknown_key_is_reported_before_the_missing_required_field():
# The stray key is the likelier root cause, so it leads.
result = _call("strict_demo", {"justification": "x"})
unknown_at = result.index("justification")
missing_at = result.index("missing required path")
assert unknown_at < missing_at


# ---- the closed/open distinction is honoured -------------------------------


def test_additional_properties_tool_accepts_extra_keys():
result = _call("passthrough_demo", {"path": "a.txt", "extra": 1})
assert result == "ran"
assert _RUNS == [{"path": "a.txt", "extra": 1}]


def test_tool_with_no_declared_properties_accepts_anything():
result = _call("open_demo", {"anything": 1})
assert result == "ran"


# ---- type and enum violations still reject ---------------------------------


def test_wrong_type_is_named_and_nothing_runs():
result = _call("strict_demo", {"path": "a.txt", "limit": "ten"})
assert "INVALID_INPUT" in result
assert "limit" in result
assert "integer" in result
assert "Nothing was run" in result
assert _RUNS == []


def test_enum_violation_names_the_allowed_values():
# The original CLI withholds the enum it is complaining about; ours must not.
result = _call("strict_demo", {"path": "a.txt", "mode": "append"})
assert "mode" in result
assert "read" in result and "write" in result
assert _RUNS == []


def test_valid_call_still_runs():
result = _call("strict_demo", {"path": "a.txt", "limit": 10})
assert result == "ran"
assert _RUNS == [{"path": "a.txt", "limit": 10}]


# ---- the message shape itself ---------------------------------------------


def test_format_keeps_the_error_prefix_downstream_keys_off():
# runner.py, events/session.py and evidence_ledger.py all test
# ``startswith("Error")``; changing that prefix silently demotes a
# rejection to a success in three places.
message = format_invalid_input("some_tool", ["boom"])
assert message.startswith("Error")
assert "INVALID_INPUT" in message
assert message.rstrip().endswith("again.")


def test_format_lists_one_line_per_error():
message = format_invalid_input("t", ["first problem", "second problem"])
assert " - first problem" in message
assert " - second problem" in message
Loading