Skip to content

Commit 963ab13

Browse files
fix(agent): reject duplicate client tool names
Tool calls are dispatched by name to the first matching client tool, so two tools with the same name let the first one receive arguments the model or an approver meant for the other, including an approved call resumed with a different tool list. call_model now raises when client tool names collide.
1 parent a5251c4 commit 963ab13

3 files changed

Lines changed: 96 additions & 1 deletion

File tree

‎src/openrouter_agent/model_result.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
StepResult,
3030
Tool,
3131
UnsentToolResult,
32+
assert_unique_client_tool_names,
3233
get_tool_function,
3334
is_auto_resolvable_tool,
3435
is_client_tool,
@@ -100,6 +101,7 @@ def _find_latest_user_string_index(items: Sequence[Any]) -> int:
100101

101102
class ModelResult:
102103
def __init__(self, options: Mapping[str, Any]) -> None:
104+
assert_unique_client_tool_names(options.get("tools"))
103105
self.options = dict(options)
104106
self._run_task: Optional[asyncio.Task[Any]] = None
105107
self._final_response: Any = None

‎src/openrouter_agent/tool_types.py‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from dataclasses import dataclass
44
from enum import Enum
5-
from typing import Any, Callable, Dict, List, Mapping, Optional, Protocol, Sequence, Union
5+
from typing import Any, Callable, Dict, List, Mapping, Optional, Protocol, Sequence, Set, Union
66

77
from typing_extensions import Literal, TypeAlias, TypedDict
88

@@ -275,6 +275,36 @@ def get_tool_function(tool: Mapping[str, Any]) -> Dict[str, Any]:
275275
return value if isinstance(value, dict) else {}
276276

277277

278+
def find_duplicate_client_tool_name(tools: Sequence[Mapping[str, Any]]) -> Optional[str]:
279+
"""Return the first client tool name that appears more than once, or `None`.
280+
Server tools have no client name and are skipped."""
281+
seen: Set[str] = set()
282+
for candidate in tools:
283+
if is_server_tool(candidate):
284+
continue
285+
name = get_tool_function(candidate).get("name")
286+
if not isinstance(name, str):
287+
continue
288+
if name in seen:
289+
return name
290+
seen.add(name)
291+
return None
292+
293+
294+
def assert_unique_client_tool_names(tools: Optional[Sequence[Mapping[str, Any]]]) -> None:
295+
"""Raise when two client tools share a name. Calls are dispatched by name, so a
296+
duplicate would let whichever tool is listed first receive arguments the model
297+
(or an approver) meant for the other."""
298+
if not tools:
299+
return
300+
name = find_duplicate_client_tool_name(tools)
301+
if name is not None:
302+
raise ValueError(
303+
f'Duplicate tool name "{name}": every tool passed to call_model must have a unique name. '
304+
"Rename one, or prefix the names of MCP tools when combining them with local tools."
305+
)
306+
307+
278308
def has_execute_function(tool: Mapping[str, Any]) -> bool:
279309
fn = get_tool_function(tool)
280310
return is_client_tool(tool) and callable(fn.get("execute"))
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from __future__ import annotations
2+
3+
from typing import Any, Dict, List
4+
5+
import pytest
6+
7+
from openrouter_agent import call_model, tool
8+
from openrouter_agent.model_result import ModelResult
9+
from tests._fixtures import MemoryStateAccessor, QueuedClient, text_response, tool_call_response
10+
11+
12+
def _tool(name: str, hits: List[Dict[str, Any]], **kwargs: Any) -> Any:
13+
def execute(params: Dict[str, Any], ctx: Any) -> Dict[str, Any]:
14+
hits.append(params)
15+
return {"ok": True}
16+
17+
return tool(name=name, input_schema=dict, output_schema=dict, execute=execute, **kwargs)
18+
19+
20+
def test_rejects_two_client_tools_with_the_same_name() -> None:
21+
first = _tool("read_value", [])
22+
second = _tool("read_value", [])
23+
24+
with pytest.raises(ValueError, match='Duplicate tool name "read_value"'):
25+
ModelResult({"model": "test", "input": "hi", "tools": [first, second]})
26+
with pytest.raises(ValueError, match='Duplicate tool name "read_value"'):
27+
call_model(QueuedClient([]), {"model": "test", "input": "hi", "tools": [first, second]})
28+
29+
30+
def test_allows_distinct_names() -> None:
31+
ModelResult({"model": "test", "input": "hi", "tools": [_tool("a", []), _tool("b", [])]})
32+
33+
34+
async def test_approved_call_does_not_run_on_a_same_named_tool_added_before_resume() -> None:
35+
state = MemoryStateAccessor()
36+
approved_hits: List[Dict[str, Any]] = []
37+
other_hits: List[Dict[str, Any]] = []
38+
approved = _tool("read_value", approved_hits, require_approval=True)
39+
other = _tool("read_value", other_hits)
40+
41+
first = call_model(
42+
QueuedClient([tool_call_response("resp_1", "read_value", call_id="call_1")]),
43+
{"model": "test", "input": "read it", "tools": [approved], "state": state},
44+
)
45+
await first.get_response()
46+
assert state.stored is not None
47+
assert state.stored.status == "awaiting_approval"
48+
49+
with pytest.raises(ValueError, match="Duplicate tool name"):
50+
call_model(
51+
QueuedClient([text_response("resp_done", "done")]),
52+
{
53+
"model": "test",
54+
"input": [],
55+
"tools": [other, approved],
56+
"state": state,
57+
"approve_tool_calls": ["call_1"],
58+
},
59+
)
60+
61+
assert other_hits == []
62+
assert approved_hits == []
63+
assert state.stored.status == "awaiting_approval"

0 commit comments

Comments
 (0)