okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1306424be
main
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 10python -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 ): 40parser = OutputParser (thinking = thinking ,tools = tools ,stream_tools = True ,declared_only = True ,deferred = deferred ) 41return parser .feed (text )+ parser .finish ("stop" ) 42 43 44class Conversion (unittest .TestCase ): 45def test_deferred_tools_stay_out_of_the_tool_list (self ): 46_ ,tools ,_ = anthropic_to_messages ({"tools" : [SEARCH ,PLACEHOLDER ,LOADED ],"messages" :REFERENCE }) 47self .assertEqual ([t ["name" ]for t in tools ], ["ToolSearch" ]) 48 49def test_a_reference_loads_the_definition_where_it_is (self ): 50messages ,_ ,_ = anthropic_to_messages ({"tools" : [SEARCH ,LOADED ],"messages" :REFERENCE }) 51result = messages [- 1 ] 52self .assertEqual (result ["role" ],"tool" ) 53self .assertEqual (json .loads (result ["content" ].removeprefix ("<tools>\n" ).removesuffix ("\n</tools>" )), 54 {"name" :MCP ,"description" :"Search the index." ,"parameters" :LOADED ["input_schema" ]}) 55 56def test_a_reference_to_a_listed_tool_adds_nothing (self ): 57req = {"tools" : [SEARCH , {** LOADED ,"defer_loading" :False }],"messages" :REFERENCE } 58self .assertEqual (anthropic_to_messages (req )[0 ][- 1 ]["content" ],"" ) 59 60def 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) 62self .assertEqual (anthropic_to_messages ({"tools" : [SEARCH ],"messages" :REFERENCE })[0 ][- 1 ]["content" ],"" ) 63 64def test_the_parser_gets_every_declared_tool (self ): 65tools ,deferred = anthropic_tools ({"tools" : [SEARCH ,PLACEHOLDER ,LOADED ]}) 66self .assertEqual ([t ["name" ]for t in tools ], ["ToolSearch" ,"DeferredToolPlaceholder" ,MCP ]) 67self .assertTrue (deferred ) 68self .assertFalse (anthropic_tools ({"tools" : [SEARCH ]})[1 ]) 69self .assertEqual (anthropic_tools ({}), (None ,False )) 70 71 72class Calls (unittest .TestCase ): 73def call (self ,evs ): 74return [e .call for e in evs if e .kind == "tool_call" ] 75 76def test_an_undeclared_call_is_a_call_with_tool_search (self ): 77calls = self .call (events (CALL , [{"name" :"ToolSearch" }],deferred = True )) 78self .assertEqual ([(c .name ,c .arguments )for c in calls ], [(MCP , {"queries" : ["a" ,"b" ]})]) 79 80def test_without_tool_search_it_stays_text (self ): 81evs = events (CALL , [{"name" :"ToolSearch" }],deferred = False ) 82self .assertEqual (self .call (evs ), []) 83self .assertIn ("<tool_call>" ,"" .join (e .text for e in evs if e .kind == "content" )) 84 85def 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 87tools ,deferred = anthropic_tools ({"tools" : [SEARCH ,LOADED ]}) 88call = self .call (events (CALL .replace ("queries>\n[\"a\", \"b\"]" ,"source>\n42" ),tools ,deferred ))[0 ] 89self .assertEqual (call .arguments , {"source" :"42" }) 90 91def test_a_call_in_the_reasoning_is_rescued_too (self ): 92calls = self .call (events ("Searching.\n" + CALL , [{"name" :"ToolSearch" }],deferred = True ,thinking = True )) 93self .assertEqual ([c .name for c in calls ], [MCP ]) 94 95 96class Route (unittest .TestCase ): 97@classmethod 98def setUpClass (cls ): 99tok = ByteTokenizer () 100cls .engine = MockEngine (tok ,"</think>\n\n" + CALL ,max_context = 16384 ) 101cls .svc = Service (cls .engine ,tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" )) 102cls .httpd = serve (cls .svc ,port = 0 ) 103cls .base = f"http://127.0.0.1: { cls . httpd . server_address [ 1 ] } " 104cls .tok = tok 105 106@classmethod 107def tearDownClass (cls ): 108cls .httpd .shutdown () 109cls .httpd .server_close () 110 111def post (self ,body ): 112req = urllib .request .Request (self .base + "/v1/messages" ,data = json .dumps (body ).encode (), 113headers = {"Content-Type" :"application/json" }) 114with urllib .request .urlopen (req ,timeout = 30 )as r : 115return json .loads (r .read ()) 116 117def test_claude_code_tool_search (self ): 118b = self .post ({"model" :"m" ,"max_tokens" :512 ,"tools" : [SEARCH ,PLACEHOLDER ], 119"messages" : [{"role" :"user" ,"content" :"search" }]}) 120self .assertEqual (b ["stop_reason" ],"tool_use" ) 121use = [c for c in b ["content" ]if c ["type" ]== "tool_use" ] 122self .assertEqual ([(u ["name" ],u ["input" ])for u in use ], [(MCP , {"queries" : ["a" ,"b" ]})]) 123self .assertNotIn ("DeferredToolPlaceholder" ,self .tok .decode (self .engine .last_prompt )) 124 125def test_without_tool_search_the_rule_holds (self ): 126b = self .post ({"model" :"m" ,"max_tokens" :512 ,"tools" : [SEARCH ], 127"messages" : [{"role" :"user" ,"content" :"search" }]}) 128self .assertEqual (b ["stop_reason" ],"end_turn" ) 129self .assertEqual (b .get ("strata_rejected_tool_calls" ), [{"name" :MCP ,"reason" :"undeclared" }]) 130 131def 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 133history = [{"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" }]}] 136b = self .post ({"model" :"m" ,"max_tokens" :512 ,"tools" : [SEARCH ],"messages" :history }) 137self .assertEqual (b ["stop_reason" ],"tool_use" ) 138self .assertEqual ([u ["name" ]for u in b ["content" ]if u ["type" ]== "tool_use" ], [MCP ]) 139 140def test_the_loaded_tool_is_in_the_tool_result_not_the_tool_list (self ): 141self .post ({"model" :"m" ,"max_tokens" :512 ,"tools" : [SEARCH ,PLACEHOLDER ,LOADED ],"messages" :REFERENCE }) 142prompt = self .tok .decode (self .engine .last_prompt ) 143self .assertEqual (prompt .count (f'"name": " { MCP } "' ),1 ) 144self .assertGreater (prompt .index (f'"name": " { MCP } "' ),prompt .index ("<tool_response>" )) 145 146 147if __name__ == "__main__" : 148unittest .main ()