okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
8.2 KiB148 linesraw
1"""#4663: Anthropic's tool search on /v1/messages - `defer_loading` tools and `tool_reference` blocks.
2
3Claude Code (ENABLE_TOOL_SEARCH, the default behind a gateway) declares ToolSearch and a `defer_loading`
4DeferredToolPlaceholder, and names its MCP tools only in the conversation. ToolSearch's result is a tool_result of
5tool_reference blocks; from then on the found tool is in `tools` with `defer_loading: true`. Claude Code runs a call
6for a held-back tool even before it was loaded. Before this, a call for an undeclared name came back as text with
7end_turn and the session stopped; the reference was dropped; and every deferred tool was in the prompt's tool list,
8which changed the prompt's start (and so missed the prompt cache) each time a tool was loaded.
9
10    python -m unittest serve.test_tool_search -v
11"""
12import json
13import sys
14import unittest
15import urllib.request
16from pathlib import Path
17
18sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
19
20from serve.frontend import ChatTemplate, OutputParser, anthropic_to_messages, anthropic_tools  # noqa: E402
21from serve.server import ByteTokenizer, MockEngine, Service, serve  # noqa: E402
22
23ROOT = Path(__file__).resolve().parents[1]
24MCP = "mcp__plugin_ctx__ctx_search"
25SEARCH = {"name": "ToolSearch", "description": "Load deferred tools.",
26          "input_schema": {"type": "object", "properties": {"query": {"type": "string"}}}}
27PLACEHOLDER = {"name": "DeferredToolPlaceholder", "input_schema": {"type": "object"}, "defer_loading": True}
28LOADED = {"name": MCP, "description": "Search the index.", "defer_loading": True,
29          "input_schema": {"type": "object", "properties": {"queries": {"type": "array", "items": {"type": "string"}},
30                                                            "source": {"type": "string"}}}}
31CALL = f"<tool_call>\n<function={MCP}>\n<parameter=queries>\n[\"a\", \"b\"]\n</parameter>\n</function>\n</tool_call>"
32REFERENCE = [{"role": "user", "content": "find it"},
33             {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "ToolSearch",
34                                                "input": {"query": "select:" + MCP}}]},
35             {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1",
36                                           "content": [{"type": "tool_reference", "tool_name": MCP}]}]}]
37
38
39def events(text, tools, deferred, thinking=False):
40    parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True, declared_only=True, deferred=deferred)
41    return parser.feed(text) + parser.finish("stop")
42
43
44class Conversion(unittest.TestCase):
45    def test_deferred_tools_stay_out_of_the_tool_list(self):
46        _, tools, _ = anthropic_to_messages({"tools": [SEARCH, PLACEHOLDER, LOADED], "messages": REFERENCE})
47        self.assertEqual([t["name"] for t in tools], ["ToolSearch"])
48
49    def test_a_reference_loads_the_definition_where_it_is(self):
50        messages, _, _ = anthropic_to_messages({"tools": [SEARCH, LOADED], "messages": REFERENCE})
51        result = messages[-1]
52        self.assertEqual(result["role"], "tool")
53        self.assertEqual(json.loads(result["content"].removeprefix("<tools>\n").removesuffix("\n</tools>")),
54                         {"name": MCP, "description": "Search the index.", "parameters": LOADED["input_schema"]})
55
56    def test_a_reference_to_a_listed_tool_adds_nothing(self):
57        req = {"tools": [SEARCH, {**LOADED, "defer_loading": False}], "messages": REFERENCE}
58        self.assertEqual(anthropic_to_messages(req)[0][-1]["content"], "")
59
60    def test_a_reference_to_an_undeclared_tool_is_left_out(self):
61        # an old reference (its MCP server gone) must not fail the rest of the session (test_frontend pins the same)
62        self.assertEqual(anthropic_to_messages({"tools": [SEARCH], "messages": REFERENCE})[0][-1]["content"], "")
63
64    def test_the_parser_gets_every_declared_tool(self):
65        tools, deferred = anthropic_tools({"tools": [SEARCH, PLACEHOLDER, LOADED]})
66        self.assertEqual([t["name"] for t in tools], ["ToolSearch", "DeferredToolPlaceholder", MCP])
67        self.assertTrue(deferred)
68        self.assertFalse(anthropic_tools({"tools": [SEARCH]})[1])
69        self.assertEqual(anthropic_tools({}), (None, False))
70
71
72class Calls(unittest.TestCase):
73    def call(self, evs):
74        return [e.call for e in evs if e.kind == "tool_call"]
75
76    def test_an_undeclared_call_is_a_call_with_tool_search(self):
77        calls = self.call(events(CALL, [{"name": "ToolSearch"}], deferred=True))
78        self.assertEqual([(c.name, c.arguments) for c in calls], [(MCP, {"queries": ["a", "b"]})])
79
80    def test_without_tool_search_it_stays_text(self):
81        evs = events(CALL, [{"name": "ToolSearch"}], deferred=False)
82        self.assertEqual(self.call(evs), [])
83        self.assertIn("<tool_call>", "".join(e.text for e in evs if e.kind == "content"))
84
85    def test_a_loaded_deferred_tool_keeps_its_schema(self):
86        # without its schema a string that reads as a number would arrive as one, and the client refuses it
87        tools, deferred = anthropic_tools({"tools": [SEARCH, LOADED]})
88        call = self.call(events(CALL.replace("queries>\n[\"a\", \"b\"]", "source>\n42"), tools, deferred))[0]
89        self.assertEqual(call.arguments, {"source": "42"})
90
91    def test_a_call_in_the_reasoning_is_rescued_too(self):
92        calls = self.call(events("Searching.\n" + CALL, [{"name": "ToolSearch"}], deferred=True, thinking=True))
93        self.assertEqual([c.name for c in calls], [MCP])
94
95
96class Route(unittest.TestCase):
97    @classmethod
98    def setUpClass(cls):
99        tok = ByteTokenizer()
100        cls.engine = MockEngine(tok, "</think>\n\n" + CALL, max_context=16384)
101        cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
102        cls.httpd = serve(cls.svc, port=0)
103        cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
104        cls.tok = tok
105
106    @classmethod
107    def tearDownClass(cls):
108        cls.httpd.shutdown()
109        cls.httpd.server_close()
110
111    def post(self, body):
112        req = urllib.request.Request(self.base + "/v1/messages", data=json.dumps(body).encode(),
113                                     headers={"Content-Type": "application/json"})
114        with urllib.request.urlopen(req, timeout=30) as r:
115            return json.loads(r.read())
116
117    def test_claude_code_tool_search(self):
118        b = self.post({"model": "m", "max_tokens": 512, "tools": [SEARCH, PLACEHOLDER],
119                       "messages": [{"role": "user", "content": "search"}]})
120        self.assertEqual(b["stop_reason"], "tool_use")
121        use = [c for c in b["content"] if c["type"] == "tool_use"]
122        self.assertEqual([(u["name"], u["input"]) for u in use], [(MCP, {"queries": ["a", "b"]})])
123        self.assertNotIn("DeferredToolPlaceholder", self.tok.decode(self.engine.last_prompt))
124
125    def test_without_tool_search_the_rule_holds(self):
126        b = self.post({"model": "m", "max_tokens": 512, "tools": [SEARCH],
127                       "messages": [{"role": "user", "content": "search"}]})
128        self.assertEqual(b["stop_reason"], "end_turn")
129        self.assertEqual(b.get("strata_rejected_tool_calls"), [{"name": MCP, "reason": "undeclared"}])
130
131    def test_a_tool_the_conversation_called_is_a_call_without_tool_search(self):
132        # #4663 on /v1/messages: the history's tool_use blocks count as declared, as on the chat route
133        history = [{"role": "user", "content": "search"},
134                   {"role": "assistant", "content": [{"type": "tool_use", "id": "t0", "name": MCP, "input": {"queries": ["x"]}}]},
135                   {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t0", "content": "ok"}]}]
136        b = self.post({"model": "m", "max_tokens": 512, "tools": [SEARCH], "messages": history})
137        self.assertEqual(b["stop_reason"], "tool_use")
138        self.assertEqual([u["name"] for u in b["content"] if u["type"] == "tool_use"], [MCP])
139
140    def test_the_loaded_tool_is_in_the_tool_result_not_the_tool_list(self):
141        self.post({"model": "m", "max_tokens": 512, "tools": [SEARCH, PLACEHOLDER, LOADED], "messages": REFERENCE})
142        prompt = self.tok.decode(self.engine.last_prompt)
143        self.assertEqual(prompt.count(f'"name": "{MCP}"'), 1)
144        self.assertGreater(prompt.index(f'"name": "{MCP}"'), prompt.index("<tool_response>"))
145
146
147if __name__ == "__main__":
148    unittest.main()