okami.mom/strata

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

Niko1221Merge f-027-gh-app: GitHub app and Terminal items for 0.2.73cabb9e3f

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