okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3cabb9e3f
main
1"""serve/test_mcp.py - tools from MCP servers (serve/mcp.py) and the web app's tool loop, against the mock engine and 2the fake MCP server in serve/mcp_fake_server.py (no GPU, no pack, no MCP SDK). 3 4python -m unittest serve.test_mcp -v 5""" 6from __future__import annotations 7 8import json 9import os 10import sys 11import tempfile 12import threading 13import time 14import unittest 15import urllib .error 16import urllib .request 17from pathlib import Path 18 19sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 20from serve import mcp_fake_server as fake # noqa: E402 21from serve .frontend import ChatTemplate # noqa: E402 22from serve .mcp import McpCancelled ,McpHub ,hub_from_config # noqa: E402 23from serve .server import ByteTokenizer ,MockEngine ,Service ,serve # noqa: E402 24 25ROOT = Path (__file__ ).resolve ().parents [1 ] 26FAKE = str (ROOT / "serve" / "mcp_fake_server.py" ) 27CTX = 8192 28 29 30def stdio (* args ,** extra ): 31return {"command" :sys .executable ,"args" : [FAKE ,* args ],** extra } 32 33 34def call_script (name ,** params ): 35"""The model's text for one tool call, as Qwen's template asks for it.""" 36body = "" .join (f"<parameter= { k } >\n { v } \n</parameter>\n" for k ,v in params .items ()) 37return f"</think>\n\nLet me check.\n\n<tool_call>\n<function= { name } >\n { body } </function>\n</tool_call>" 38 39 40class ScriptedEngine (MockEngine ): 41"""A mock engine with one script per call (the last one repeats): a tool call first, then the answer.""" 42 43def __init__ (self ,tok ,scripts ,max_context = CTX ,delay_s = 0.0 ): 44super ().__init__ (tok ,list (scripts ),max_context = max_context ,delay_s = delay_s ) 45self .prompts = [] 46 47def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ): 48self .prompts .append (list (ids )) 49yield from super ().generate (ids ,max_new ,sampling ,cancel ,embeddings ) 50 51def prompt_text (self ,i ): 52return bytes (t for t in self .prompts [i ]if t < 256 ).decode ("utf-8" ,"replace" ) 53 54 55# ------------------------------------------------------------------------------------------------ the client 56class Client (unittest .TestCase ): 57"""The stdio client against the fake server: start, pagination, calls, errors, crashes, timeouts, the cap.""" 58 59@classmethod 60def setUpClass (cls ): 61cls .log = tempfile .NamedTemporaryFile (delete = False ,suffix = ".jsonl" ) 62cls .log .close () 63os .environ ["FAKE_MCP_LOG" ]= cls .log .name 64cls .hub = McpHub ({"fake" :stdio (),"paged" :stdio ("--page" ,"4" ),"broken" :stdio ("--crash-at-start" ), 65"missing" : {"command" :"strata-no-such-program" }}, 66 {"timeout_s" :1.5 ,"max_result_chars" :1000 }) 67cls .hub .start (wait = True ) 68 69@classmethod 70def tearDownClass (cls ): 71cls .hub .close () 72del os .environ ["FAKE_MCP_LOG" ] 73os .unlink (cls .log .name ) 74 75def test_initialize_and_list_every_page (self ): 76s = self .hub .servers ["fake" ] 77self .assertEqual (s .status ,"ready" ) 78self .assertEqual (s .info ["name" ],"fake" ) 79self .assertEqual (s .info ["protocol" ],"2025-06-18" ) 80want = [t ["name" ]for t in fake .TOOLS ] 81self .assertEqual ([t ["name" ]for t in s .tools ],want )# 3 pages of 2 82self .assertEqual ([t ["name" ]for t in self .hub .servers ["paged" ].tools ],want )# 2 pages of 4 83 84def test_namespaced_openai_tools (self ): 85tools = self .hub .openai_tools () 86names = [t ["function" ]["name" ]for t in tools ] 87self .assertIn ("fake__echo" ,names ) 88self .assertIn ("paged__echo" ,names ) 89echo = next (t for t in tools if t ["function" ]["name" ]== "fake__echo" ) 90self .assertEqual (echo ["type" ],"function" ) 91self .assertEqual (echo ["function" ]["parameters" ]["properties" ]["text" ]["type" ],"string" ) 92 93def test_a_server_that_fails_is_left_out (self ): 94for name ,why in (("broken" ,"missing configuration" ), ("missing" ,"could not start" )): 95with self .subTest (name = name ): 96s = self .hub .servers [name ] 97self .assertEqual (s .status ,"failed" ) 98self .assertIn (why ,s .error ) 99self .assertFalse ([t for t in self .hub .template_tools ()if t ["name" ].startswith (name + "__" )]) 100st = {s ["name" ]:s for s in self .hub .status ()["servers" ]} 101self .assertEqual (st ["broken" ]["status" ],"failed" ) 102self .assertEqual (st ["fake" ]["status" ],"ready" ) 103 104def test_call (self ): 105self .hub .routes () 106r = self .hub .call ("fake__echo" , {"text" :"hello wörld" }) 107self .assertEqual ((r ["ok" ],r ["text" ],r ["server" ],r ["tool" ]), (True ,"hello wörld" ,"fake" ,"echo" )) 108self .assertEqual (self .hub .call ("fake__add" , {"a" :2 ,"b" :40 })["text" ],"42" ) 109 110def test_errors_become_text (self ): 111self .hub .routes () 112r = self .hub .call ("fake__fail" , {})# the tool's own error (isError) 113self .assertFalse (r ["ok" ]) 114self .assertEqual (r ["text" ],"error: it failed on purpose" ) 115r = self .hub .call ("nobody__nothing" , {})# not a tool at all 116self .assertTrue (r ["text" ].startswith ("error: there is no tool" )) 117# a JSON-RPC error from the server 118s = self .hub .servers ["fake" ] 119with self .assertRaises (Exception )as ctx : 120s .call ("no-such-tool" , {},5 ) 121self .assertIn ("unknown tool" ,str (ctx .exception )) 122 123def test_timeout (self ): 124self .hub .routes () 125t0 = time .monotonic () 126r = self .hub .call ("fake__sleep" , {"seconds" :5 }) 127self .assertLess (time .monotonic ()- t0 ,4 ) 128self .assertFalse (r ["ok" ]) 129self .assertIn ("timed out after 1.5 s" ,r ["text" ]) 130self .assertEqual (self .hub .call ("fake__echo" , {"text" :"still here" })["text" ],"still here" ) 131 132def test_truncation (self ): 133self .hub .routes () 134r = self .hub .call ("fake__big" , {"n" :50000 }) 135self .assertTrue (r ["ok" ]) 136self .assertTrue (r ["truncated" ]) 137self .assertEqual (r ["chars" ],50000 ) 138self .assertTrue (r ["text" ].startswith ("y" * 1000 + "\n\n[... truncated" )) 139self .assertIn ("50,000 characters" ,r ["text" ]) 140self .assertLess (len (r ["text" ]),1200 ) 141 142def test_crash_mid_call_then_restart (self ): 143hub = McpHub ({"solo" :stdio ()}, {"timeout_s" :5 }) 144hub .start (wait = True ) 145try : 146hub .routes () 147r = hub .call ("solo__die" , {}) 148self .assertFalse (r ["ok" ]) 149self .assertIn ("the server stopped" ,r ["text" ]) 150self .assertIn ("dying on purpose" ,r ["text" ]) 151self .assertEqual (hub .servers ["solo" ].status ,"stopped" ) 152self .assertIn ("solo__echo" ,hub .routes ())# its tools stay: the next call restarts it 153self .assertEqual (hub .call ("solo__echo" , {"text" :"back" })["text" ],"back" ) 154self .assertEqual (hub .servers ["solo" ].status ,"ready" ) 155finally : 156hub .close () 157 158def test_cancel (self ): 159self .hub .routes () 160cancel = threading .Event () 161threading .Timer (0.3 ,cancel .set ).start () 162t0 = time .monotonic () 163with self .assertRaises (McpCancelled ): 164self .hub .call ("fake__sleep" , {"seconds" :1.2 },cancel ) 165self .assertLess (time .monotonic ()- t0 ,1.0 ) 166time .sleep (0.3 ) 167seen = [json .loads (line )for line in Path (self .log .name ).read_text ().splitlines ()] 168self .assertTrue (any ("cancelled" in e for e in seen ),seen )# notifications/cancelled reached the server 169 170 171class HttpClient (unittest .TestCase ): 172"""Streamable HTTP: JSON answers, an event-stream answer, the session id.""" 173 174@classmethod 175def setUpClass (cls ): 176cls .httpd = fake .http_server (0 ) 177url = f"http://127.0.0.1: { cls . httpd . server_address [ 1 ] } /mcp" 178cls .hub = McpHub ({"web" : {"url" :url },"down" : {"url" :"http://127.0.0.1:9/mcp" }}, {"timeout_s" :1.5 }) 179cls .hub .start (wait = True ) 180 181@classmethod 182def tearDownClass (cls ): 183cls .hub .close () 184cls .httpd .shutdown () 185cls .httpd .server_close () 186 187def test_list_and_call (self ): 188s = self .hub .servers ["web" ] 189self .assertEqual (s .status ,"ready" ,s .error ) 190self .assertEqual (len (s .tools ),len (fake .TOOLS ))# pages, with the session id on each request 191self .assertEqual (s .transport .session ,"s-1" ) 192self .hub .routes () 193self .assertEqual (self .hub .call ("web__echo" , {"text" :"over http" })["text" ],"over http" )# event stream 194self .assertEqual (self .hub .call ("web__fail" , {})["text" ],"error: it failed on purpose" ) 195 196def test_timeout_and_unreachable (self ): 197self .hub .routes () 198r = self .hub .call ("web__sleep" , {"seconds" :4 }) 199self .assertIn ("timed out" ,r ["text" ]) 200self .assertEqual (self .hub .servers ["down" ].status ,"failed" ) 201self .assertIn ("could not reach" ,self .hub .servers ["down" ].error ) 202 203 204class Config (unittest .TestCase ): 205def test_both_spellings_and_the_file (self ): 206with tempfile .TemporaryDirectory ()as d : 207path = os .path .join (d ,"claude_desktop_config.json" ) 208Path (path ).write_text (json .dumps ({"mcpServers" : {"b" : {"url" :"http://x/mcp" },"a" :stdio ()}}), 209encoding = "utf-8" ) 210hub = hub_from_config ({"mcp_servers" : {"a" : {"command" :"old" }}, 211"mcpServers" : {"c" :stdio (),"off" : {"command" :"x" ,"disabled" :True }}, 212"mcp" : {"timeout_s" :5 ,"max_result_chars" :100 ,"max_rounds" :3 }},path ) 213self .assertEqual (sorted (hub .servers ), ["a" ,"b" ,"c" ]) 214self .assertEqual (hub .servers ["a" ].cfg ["command" ],sys .executable )# the file wins a name clash 215self .assertEqual (hub .servers ["b" ].kind ,"http" ) 216self .assertEqual ((hub .settings ["timeout_s" ],hub .settings ["max_result_chars" ],hub .settings ["max_rounds" ]), 217 (5.0 ,100 ,3 )) 218self .assertIsNone (hub_from_config ({})) 219self .assertEqual (McpHub ({}).settings ["max_result_chars" ],20000 ) 220 221def test_bad_entries_stop_the_start (self ): 222for cfg in ({"mcp_servers" : {"x" : {}}}, {"mcp_servers" : {"x" : {"command" :"a" ,"args" :"b" }}}, 223 {"mcp_servers" : ["x" ]}, {"mcpServers" : {"x" : {"url" :"http://a" ,"type" :"sse" }}}, 224 {"mcp_servers" : {"x" : {"command" :"a" }},"mcp" : {"timeout_s" :0 }}, 225 {"mcp_servers" : {"x" : {"command" :"a" }},"mcp" : {"max_rounds" :1.5 }}): 226with self .subTest (cfg = cfg ),self .assertRaises (SystemExit ): 227hub_from_config (cfg ) 228with self .assertRaises (SystemExit ): 229hub_from_config ({},os .path .join (tempfile .gettempdir (),"strata-no-such-mcp.json" )) 230 231 232# ------------------------------------------------------------------------------------------------ the tool loop 233class ToolLoop (unittest .TestCase ): 234"""The web app's chat (`"strata_mcp": true`): the model calls an MCP tool, the server runs it and the model 235answers with its result; plain API requests never see the MCP tools.""" 236 237def setUp (self ): 238self .log = tempfile .NamedTemporaryFile (delete = False ,suffix = ".jsonl" ) 239self .log .close () 240os .environ ["FAKE_MCP_LOG" ]= self .log .name 241self .hub = McpHub ({"fake" :stdio (),"broken" :stdio ("--crash-at-start" )}, 242 {"timeout_s" :10 ,"max_result_chars" :500 ,"max_rounds" :2 }) 243self .hub .start (wait = True ) 244self .httpd = None 245 246def tearDown (self ): 247if self .httpd : 248self .httpd .shutdown () 249self .httpd .server_close () 250self .hub .close () 251del os .environ ["FAKE_MCP_LOG" ] 252os .unlink (self .log .name ) 253 254def start (self ,* scripts ,delay_s = 0.0 ): 255tok = ByteTokenizer () 256self .engine = ScriptedEngine (tok ,list (scripts ),delay_s = delay_s ) 257self .svc = Service (self .engine ,tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" )) 258self .svc .mcp = self .hub 259self .httpd = serve (self .svc ,port = 0 ) 260self .base = f"http://127.0.0.1: { self . httpd . server_address [ 1 ] } " 261 262def post (self ,body ,headers = None ,stream = True ): 263body = {"model" :"m" ,"messages" : [{"role" :"user" ,"content" :"check it" }],"stream" :stream ,** body } 264req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 265headers = {"Content-Type" :"application/json" ,** (headers or {})}) 266try : 267with urllib .request .urlopen (req ,timeout = 30 )as r : 268text = r .read ().decode () 269return r .status ,text 270except urllib .error .HTTPError as e : 271with e : 272return e .code ,e .read ().decode () 273 274@staticmethod 275def chunks (text ): 276return [json .loads (line [6 :])for line in text .splitlines ()if line .startswith ("data: {" )] 277 278def test_tool_call_then_answer (self ): 279self .start (call_script ("fake__echo" ,text = "hello from the tool" ),"</think>\n\nThe tool said hello." ) 280code ,text = self .post ({"strata_mcp" :True }) 281self .assertEqual (code ,200 ,text ) 282cs = self .chunks (text ) 283mcp = [c ["strata_mcp" ]for c in cs if "strata_mcp" in c ] 284self .assertEqual ([m ["event" ]for m in mcp ], ["start" ,"call" ,"result" ]) 285self .assertEqual (mcp [1 ]["arguments" ], {"text" :"hello from the tool" }) 286self .assertEqual ((mcp [1 ]["server" ],mcp [1 ]["tool" ]), ("fake" ,"echo" )) 287self .assertEqual ((mcp [2 ]["ok" ],mcp [2 ]["text" ]), (True ,"hello from the tool" )) 288self .assertEqual (len ({m ["id" ]for m in mcp }),1 ) 289content = "" .join ((c ["choices" ][0 ]["delta" ].get ("content" )or "" )for c in cs ) 290self .assertEqual (content ,"Let me check.The tool said hello." ) 291self .assertFalse ([c for c in cs if c ["choices" ][0 ]["delta" ].get ("tool_calls" )])# nothing for the client to run 292self .assertEqual (cs [- 1 ]["choices" ][0 ]["finish_reason" ],"stop" ) 293self .assertEqual (len (self .engine .prompts ),2 ) 294first ,second = self .engine .prompt_text (0 ),self .engine .prompt_text (1 ) 295self .assertIn ('"name": "fake__echo"' ,first )# the MCP tools are in the prompt 296self .assertNotIn ("broken__" ,first )# the server that failed is left out 297self .assertIn ("<function=fake__echo>\n<parameter=text>\nhello from the tool\n</parameter>" ,second ) 298self .assertIn ("<tool_response>\nhello from the tool\n</tool_response>" ,second ) 299self .assertEqual (cs [- 1 ]["usage" ]["prompt_tokens" ],len (self .engine .prompts [1 ])) 300 301def test_a_call_the_output_ends_inside_is_not_run (self ): 302"""#211: the model's turn ends inside an MCP call: nothing runs (it used to run with no arguments).""" 303script = call_script ("fake__echo" ,text = "hello from the tool" ) 304self .start (script [:script .index ("from the tool" )],"</think>\n\nnever" ) 305code ,text = self .post ({"strata_mcp" :True }) 306self .assertEqual (code ,200 ,text ) 307cs = self .chunks (text ) 308mcp = [c ["strata_mcp" ]for c in cs if "strata_mcp" in c ] 309self .assertEqual ([m ["event" ]for m in mcp ], ["start" ])# the web app shows it as "Not run" at the end 310self .assertEqual (len (self .engine .prompts ),1 ) 311self .assertNotIn ('"call"' ,Path (self .log .name ).read_text ())# nothing ran 312self .assertEqual (cs [- 1 ]["choices" ][0 ]["finish_reason" ],"stop" ) 313 314def test_non_stream (self ): 315self .start (call_script ("fake__add" ,a = 2 ,b = 3 ),"</think>\n\n5." ) 316code ,text = self .post ({"strata_mcp" :True },stream = False ) 317self .assertEqual (code ,200 ,text ) 318msg = json .loads (text )["choices" ][0 ]["message" ] 319self .assertEqual (msg ["content" ],"Let me check.5." ) 320self .assertEqual (msg ["strata_mcp" ][- 1 ]["text" ],"5" ) 321 322def test_plain_requests_get_no_mcp_tools (self ): 323self .start (call_script ("fake__echo" ,text = "x" ),"</think>\n\nnever" ) 324code ,text = self .post ({}) 325self .assertEqual (code ,200 ,text ) 326self .assertNotIn ("fake__echo" ,self .engine .prompt_text (0 )) 327cs = self .chunks (text ) 328self .assertFalse ([c for c in cs if "strata_mcp" in c ]) 329# #3075: a request that declared no tools gets no tool call back; the call is the text it was written as 330self .assertEqual (cs [- 1 ]["choices" ][0 ]["finish_reason" ],"stop" ) 331self .assertFalse ([tc for c in cs for tc in c ["choices" ][0 ]["delta" ].get ("tool_calls" )or []]) 332self .assertIn ("<function=fake__echo>" ,"" .join (c ["choices" ][0 ]["delta" ].get ("content" )or "" for c in cs )) 333self .assertEqual (len (self .engine .prompts ),1 ) 334self .assertNotIn ('"call"' ,Path (self .log .name ).read_text ())# nothing ran 335for req in ({"strata_mcp" :"yes" }, {"strata_mcp" :1 }):# only a real true opts in 336self .post (req ) 337self .assertNotIn ("fake__echo" ,self .engine .prompt_text (- 1 )) 338 339def test_own_tools_still_go_to_the_client (self ): 340own = [{"type" :"function" ,"function" : {"name" :"lookup" ,"parameters" : {"type" :"object" ,"properties" : { 341"q" : {"type" :"string" }}}}}] 342self .start (call_script ("lookup" ,q = "x" ),"</think>\n\nnever" ) 343code ,text = self .post ({"strata_mcp" :True ,"tools" :own }) 344cs = self .chunks (text ) 345calls = [tc for c in cs for tc in c ["choices" ][0 ]["delta" ].get ("tool_calls" )or []] 346self .assertEqual (calls [0 ]["function" ]["name" ],"lookup" ) 347self .assertEqual (cs [- 1 ]["choices" ][0 ]["finish_reason" ],"tool_calls" ) 348self .assertIn ('"name": "lookup"' ,self .engine .prompt_text (0 )) 349self .assertIn ('"name": "fake__echo"' ,self .engine .prompt_text (0 )) 350self .assertEqual (len (self .engine .prompts ),1 ) 351 352def test_tool_error_is_a_result (self ): 353self .start (call_script ("fake__fail" ),"</think>\n\nIt failed." ) 354code ,text = self .post ({"strata_mcp" :True }) 355mcp = [c ["strata_mcp" ]for c in self .chunks (text )if "strata_mcp" in c ] 356self .assertEqual ((mcp [- 1 ]["ok" ],mcp [- 1 ]["text" ]), (False ,"error: it failed on purpose" )) 357self .assertIn ("<tool_response>\nerror: it failed on purpose\n</tool_response>" ,self .engine .prompt_text (1 )) 358self .assertEqual (self .chunks (text )[- 1 ]["choices" ][0 ]["finish_reason" ],"stop" ) 359 360def test_truncated_for_the_model (self ): 361self .start (call_script ("fake__big" ,n = 3000 ),"</think>\n\nLong." ) 362self .post ({"strata_mcp" :True }) 363second = self .engine .prompt_text (1 ) 364self .assertIn ("y" * 500 + "\n\n[... truncated: the tool returned 3,000 characters" ,second ) 365self .assertNotIn ("y" * 501 ,second ) 366 367def test_max_rounds (self ): 368self .start (call_script ("fake__echo" ,text = "first result" ), 369call_script ("fake__echo" ,text = "second result" ),"</think>\n\nSummary of both results." ) 370code ,text = self .post ({"strata_mcp" :True }) 371self .assertEqual (code ,200 ,text ) 372chunks = self .chunks (text ) 373mcp = [chunk ["strata_mcp" ]for chunk in chunks if "strata_mcp" in chunk ] 374self .assertEqual (len (self .engine .prompts ),3 ) 375self .assertEqual (sum (m ["event" ]== "call" for m in mcp ),2 ) 376self .assertIn ({"event" :"limit" ,"max_rounds" :2 },mcp ) 377self .assertFalse (any (m .get ("skipped" )for m in mcp )) 378self .assertIn ("Summary of both results." ,"" .join (chunk ["choices" ][0 ]["delta" ].get ("content" ,"" ) 379for chunk in chunks )) 380final_prompt = self .engine .prompt_text (2 ) 381self .assertIn ("<tool_response>\nfirst result\n</tool_response>" ,final_prompt ) 382self .assertIn ("<tool_response>\nsecond result\n</tool_response>" ,final_prompt ) 383self .assertIn ("No tools are available for this final reply" ,final_prompt ) 384self .assertNotIn ("<tools>" ,final_prompt ) 385self .assertEqual (chunks [- 1 ]["choices" ][0 ]["finish_reason" ],"stop" ) 386self .assertEqual (chunks [- 1 ]["usage" ]["prompt_tokens" ],len (self .engine .prompts [2 ])) 387 388def test_max_rounds_non_stream_with_existing_system (self ): 389self .hub .settings ["max_rounds" ]= 1 390self .start (call_script ("fake__add" ,a = 2 ,b = 3 ),"</think>\n\nThe result is 5." ) 391code ,text = self .post ({"strata_mcp" :True ,"messages" : [ 392 {"role" :"system" ,"content" :"Keep answers concise." }, 393 {"role" :"developer" ,"content" :"Use the provided evidence." }, 394 {"role" :"user" ,"content" :"Add 2 and 3." }]},stream = False ) 395self .assertEqual (code ,200 ,text ) 396response = json .loads (text ) 397self .assertIn ("The result is 5." ,response ["choices" ][0 ]["message" ]["content" ]) 398final_prompt = self .engine .prompt_text (1 ) 399self .assertIn ("Keep answers concise." ,final_prompt ) 400self .assertIn ("Use the provided evidence." ,final_prompt ) 401self .assertIn ("<tool_response>\n5\n</tool_response>" ,final_prompt ) 402self .assertNotIn ("<tools>" ,final_prompt ) 403 404def test_max_rounds_counts_rounds_with_multiple_calls (self ): 405self .hub .settings ["max_rounds" ]= 1 406self .start (call_script ("fake__echo" ,text = "source A" )+ "\n" + 407call_script ("fake__echo" ,text = "source B" ),"</think>\n\nBoth sources agree." ) 408code ,text = self .post ({"strata_mcp" :True }) 409self .assertEqual (code ,200 ,text ) 410chunks = self .chunks (text ) 411mcp = [chunk ["strata_mcp" ]for chunk in chunks if "strata_mcp" in chunk ] 412calls = [event for event in mcp if event ["event" ]== "call" ] 413self .assertEqual ([event ["round" ]for event in calls ], [1 ,1 ]) 414self .assertEqual (len (self .engine .prompts ),2 ) 415self .assertIn ("<tool_response>\nsource A\n</tool_response>" ,self .engine .prompt_text (1 )) 416self .assertIn ("<tool_response>\nsource B\n</tool_response>" ,self .engine .prompt_text (1 )) 417self .assertIn ("Both sources agree." ,"" .join (chunk ["choices" ][0 ]["delta" ].get ("content" ,"" ) 418for chunk in chunks )) 419 420def test_sixteen_rounds_then_final_answer (self ): 421self .hub .settings ["max_rounds" ]= 16 422scripts = [call_script ("fake__echo" ,text = f"source { index } " )for index in range (16 )] 423self .start (* scripts ,"</think>\n\nSummary after sixteen rounds." ) 424code ,text = self .post ({"strata_mcp" :True }) 425self .assertEqual (code ,200 ,text ) 426chunks = self .chunks (text ) 427mcp = [chunk ["strata_mcp" ]for chunk in chunks if "strata_mcp" in chunk ] 428self .assertEqual (sum (event ["event" ]== "call" for event in mcp ),16 ) 429self .assertIn ({"event" :"limit" ,"max_rounds" :16 },mcp ) 430self .assertEqual (len (self .engine .prompts ),17 ) 431final_prompt = self .engine .prompt_text (16 ) 432self .assertIn ("<tool_response>\nsource 0\n</tool_response>" ,final_prompt ) 433self .assertIn ("<tool_response>\nsource 15\n</tool_response>" ,final_prompt ) 434self .assertNotIn ("<tools>" ,final_prompt ) 435self .assertIn ("Summary after sixteen rounds." ,"" .join (chunk ["choices" ][0 ]["delta" ].get ("content" ,"" ) 436for chunk in chunks )) 437 438def test_max_rounds_preserves_errors_and_disables_client_tools (self ): 439self .hub .settings ["max_rounds" ]= 1 440own = [{"type" :"function" ,"function" : {"name" :"lookup" ,"parameters" : {"type" :"object" }}}] 441self .start (call_script ("fake__fail" ),"</think>\n\nThe source failed; here is what is known." ) 442code ,text = self .post ({"strata_mcp" :True ,"tools" :own }) 443self .assertEqual (code ,200 ,text ) 444chunks = self .chunks (text ) 445self .assertFalse (any (chunk ["choices" ][0 ]["delta" ].get ("tool_calls" )for chunk in chunks )) 446self .assertIn ("error: it failed on purpose" ,self .engine .prompt_text (1 )) 447self .assertNotIn ("<tools>" ,self .engine .prompt_text (1 )) 448self .assertIn ("here is what is known" ,"" .join (chunk ["choices" ][0 ]["delta" ].get ("content" ,"" ) 449for chunk in chunks )) 450 451def test_max_rounds_does_not_execute_more_calls (self ): 452self .hub .settings ["max_rounds" ]= 1 453self .start (call_script ("fake__echo" ,text = "known" ),call_script ("fake__echo" ,text = "must not run" )) 454code ,text = self .post ({"strata_mcp" :True }) 455self .assertEqual (code ,200 ,text ) 456self .assertEqual (len (self .engine .prompts ),2 ) 457mcp = [chunk ["strata_mcp" ]for chunk in self .chunks (text )if "strata_mcp" in chunk ] 458self .assertEqual (sum (event ["event" ]== "call" for event in mcp ),1 ) 459self .assertNotIn ("must not run" ,Path (self .log .name ).read_text ()) 460 461def test_stop_during_a_tool (self ): 462"""Closing the connection while a slow tool runs stops the tool (notifications/cancelled) and the loop.""" 463self .start (call_script ("fake__sleep" ,seconds = 8 ),"</think>\n\nnever" ) 464body = {"model" :"m" ,"messages" : [{"role" :"user" ,"content" :"x" }],"stream" :True ,"strata_mcp" :True } 465req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 466headers = {"Content-Type" :"application/json" }) 467r = urllib .request .urlopen (req ,timeout = 30 ) 468for raw in r : 469if b'"event": "call"' in raw : 470break 471r .close ()# the web app's Stop aborts the fetch 472t0 = time .monotonic () 473while time .monotonic ()- t0 < 6 and "cancelled" not in Path (self .log .name ).read_text (): 474time .sleep (0.1 ) 475self .assertIn ("cancelled" ,Path (self .log .name ).read_text ()) 476self .assertLess (time .monotonic ()- t0 ,6 ) 477time .sleep (0.5 ) 478self .assertEqual (len (self .engine .prompts ),1 )# no second round 479self .assertFalse (self .svc .status ["busy" ]) 480 481def test_only_from_the_app_s_own_page (self ): 482self .start ("</think>\n\nhi" ) 483req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = json .dumps ( 484 {"model" :"m" ,"messages" : [{"role" :"user" ,"content" :"x" }],"strata_mcp" :True }).encode (), 485headers = {"Content-Type" :"text/plain" })# a cross-site "simple" request 486with self .assertRaises (urllib .error .HTTPError )as ctx : 487urllib .request .urlopen (req ,timeout = 10 ) 488self .assertEqual (ctx .exception .code ,415 ) 489code ,_ = self .post ({"strata_mcp" :True }, {"Origin" :"http://evil.example" }) 490self .assertEqual (code ,403 ) 491self .assertEqual (self .engine .prompts , []) 492host = self .base .split ("://" ,1 )[1 ] 493code ,_ = self .post ({"strata_mcp" :True }, {"Origin" :"http://" + host }) 494self .assertEqual (code ,200 ) 495 496def test_get_mcp (self ): 497self .start ("</think>\n\nhi" ) 498with urllib .request .urlopen (self .base + "/mcp" ,timeout = 10 )as r : 499st = json .loads (r .read ()) 500servers = {s ["name" ]:s for s in st ["servers" ]} 501self .assertEqual (servers ["fake" ]["status" ],"ready" ) 502self .assertEqual (servers ["fake" ]["transport" ],"stdio" ) 503self .assertIn ("fake__echo" , [t ["name" ]for t in servers ["fake" ]["tools" ]]) 504self .assertEqual (servers ["broken" ]["status" ],"failed" ) 505self .assertIn ("missing configuration" ,servers ["broken" ]["error" ]) 506self .assertEqual (st ["tools" ],len (fake .TOOLS )) 507self .assertEqual (st ["settings" ]["max_rounds" ],2 ) 508self .svc .api_key = "k" 509with self .assertRaises (urllib .error .HTTPError ): 510urllib .request .urlopen (self .base + "/mcp" ,timeout = 10 ) 511self .svc .api_key = "" 512 513 514class NoServers (unittest .TestCase ): 515def test_opt_in_without_servers_is_a_plain_chat (self ): 516tok = ByteTokenizer () 517svc = Service (ScriptedEngine (tok , ["</think>\n\nhi" ]),tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" )) 518httpd = serve (svc ,port = 0 ) 519try : 520base = f"http://127.0.0.1: { httpd . server_address [ 1 ] } " 521with urllib .request .urlopen (base + "/mcp" ,timeout = 10 )as r : 522self .assertEqual (json .loads (r .read ()), {"servers" : [],"tools" :0 }) 523req = urllib .request .Request (base + "/v1/chat/completions" ,data = json .dumps ( 524 {"model" :"m" ,"messages" : [{"role" :"user" ,"content" :"x" }],"strata_mcp" :True }).encode (), 525headers = {"Content-Type" :"application/json" }) 526with urllib .request .urlopen (req ,timeout = 10 )as r : 527self .assertEqual (json .loads (r .read ())["choices" ][0 ]["message" ]["content" ],"hi" ) 528finally : 529httpd .shutdown () 530httpd .server_close () 531 532 533if __name__ == "__main__" : 534unittest .main ()