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
33.4 KiB731 linesraw
1"""serve/mcp.py - tools from MCP (Model Context Protocol) servers for the web app's chats.
2
3The user lists servers in the run config (`"mcp_servers"`, or Claude Desktop's `"mcpServers"` block pasted as is) or
4in a separate file (`--mcp-config`).  Each one is either a program Strata starts (`command`, `args`, `env`, `cwd`:
5the stdio transport, newline-delimited JSON-RPC 2.0 on its stdin/stdout) or an address (`url`, `headers`: the
6Streamable HTTP transport, JSON-RPC POSTed, answered as JSON or as an event stream).  Both are implemented here with
7the standard library only; no MCP SDK is needed.
8
9`McpHub` owns every configured server: it starts them in the background when the server starts, offers their tools to
10the model as OpenAI function tools named `<server>__<tool>` (two servers may both have a `search`), and routes a call
11back to the server that has it.  A server that does not start is left out with one log line; the chat works without
12it.  A server that stops later (a crash) is started again on its next call.
13
14Tool results reach the model as text: the MCP content blocks joined, capped at `max_result_chars` (a directory tree or
15a web page can be megabytes, far more than a context holds) with a note saying so.  A failed call - the tool's own
16error, a crash, a timeout - becomes a result that starts with "error:", so the model can react instead of the chat
17breaking.
18"""
19from __future__ import annotations
20
21import collections
22import base64
23import hashlib
24from pathlib import Path
25import json
26import os
27import re
28import shutil
29import signal
30import subprocess
31import sys
32import threading
33import time
34import urllib.error
35import urllib.request
36
37from serve import lifeline
38
39PROTOCOL = "2025-06-18"               # the MCP revision Strata asks for; the server's answer is used as given
40DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0, "image_results": False}
41
42
43class McpError(RuntimeError):
44    """A server answered with an error, stopped, or could not be reached."""
45
46
47class McpTimeout(McpError):
48    pass
49
50
51class McpCancelled(McpError):
52    """The chat was stopped while the call ran."""
53
54
55class _Slot:
56    """One request waiting for its response."""
57
58    def __init__(self):
59        self.done = threading.Event()
60        self.msg = None
61        self.error = None
62
63
64def _wait(slot: _Slot, timeout: float, cancel: threading.Event | None, what: str):
65    """Wait for a response, checking the chat's stop button and the deadline a few times a second."""
66    deadline = time.monotonic() + timeout
67    while not slot.done.wait(0.05):
68        if cancel is not None and cancel.is_set():
69            raise McpCancelled("stopped")
70        if time.monotonic() > deadline:
71            raise McpTimeout(f"{what} timed out after {timeout:g} s")
72    if slot.error:
73        raise slot.error
74    msg = slot.msg
75    if "error" in msg:
76        err = msg["error"] if isinstance(msg["error"], dict) else {"message": str(msg["error"])}
77        raise McpError(f"{err.get('message') or 'error'} (code {err.get('code')})")
78    return msg.get("result") or {}
79
80
81# ------------------------------------------------------------------------------------------------ transports
82class StdioTransport:
83    """A server Strata starts: JSON-RPC messages one per line on its stdin and stdout; its stderr is its log."""
84    kind = "stdio"
85
86    def __init__(self, name: str, cfg: dict):
87        self.name, self.cfg = name, cfg
88        self.proc = None
89        self.lock = threading.Lock()                    # the pending requests
90        self.write_lock = threading.Lock()              # stdin; separate, so a full pipe can't block the reader
91        self.pending: dict[int, _Slot] = {}
92        self.next_id = 0
93        self.stderr = collections.deque(maxlen=40)       # its last log lines, for the error message when it fails
94        self.protocol = PROTOCOL
95
96    def start(self):
97        env = dict(os.environ)
98        env.update({str(k): str(v) for k, v in (self.cfg.get("env") or {}).items()})
99        command = str(self.cfg["command"])
100        # On Windows `npx`, `uvx` and friends are .cmd files that CreateProcess finds only with their extension
101        exe = shutil.which(command, path=env.get("PATH")) or command
102        extra = {}
103        if os.name == "nt":
104            extra["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0)
105        else:
106            extra["start_new_session"] = True           # its own process group, so close() ends its children too
107        try:
108            self.proc = lifeline.popen([exe, *[str(a) for a in self.cfg.get("args") or []]], "mcp", stdin=subprocess.PIPE,
109                                       stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.cfg.get("cwd") or None,
110                                       env=env, **extra)
111        except OSError as e:
112            raise McpError(f"could not start {command!r}: {e}") from None
113        self._err_reader = threading.Thread(target=self._read_stderr, daemon=True)
114        self._err_reader.start()
115        threading.Thread(target=self._read, daemon=True).start()
116
117    def alive(self) -> bool:
118        return self.proc is not None and self.proc.poll() is None and not getattr(self, "ended", False)
119
120    @staticmethod
121    def _lines(f):
122        """A pipe's lines until it closes (or close() closed it under us)."""
123        try:
124            yield from f
125        except (OSError, ValueError):
126            return
127
128    def _read_stderr(self):
129        for raw in self._lines(self.proc.stderr):
130            line = raw.decode("utf-8", "replace").rstrip()
131            if line:
132                self.stderr.append(line)
133                if os.environ.get("STRATA_DEBUG"):
134                    print(f"[mcp {self.name}] {line}", flush=True)
135
136    def _read(self):
137        for raw in self._lines(self.proc.stdout):
138            line = raw.decode("utf-8", "replace").strip()
139            if not line:
140                continue
141            try:
142                msg = json.loads(line)
143            except ValueError:                           # a server that prints to stdout; the spec forbids it
144                self.stderr.append(line)
145                continue
146            for m in msg if isinstance(msg, list) else [msg]:
147                if isinstance(m, dict):
148                    self._dispatch(m)
149        self.ended = True
150        # the server's last log line says why it stopped: let the stderr reader take it first (the pipe closes with
151        # the process), or the error raced it and said only "the server stopped"
152        self._err_reader.join(1.0)
153        code = self.proc.poll()
154        err = McpError(f"the server stopped{f' (exit code {code})' if code is not None else ''}{self._tail()}")
155        with self.lock:
156            slots, self.pending = list(self.pending.values()), {}
157        for s in slots:
158            s.error = err
159            s.done.set()
160
161    def _tail(self) -> str:
162        return f": {self.stderr[-1][:300]}" if self.stderr else ""
163
164    def _dispatch(self, m: dict):
165        if "method" in m:
166            if "id" in m:                                # a request from the server: we offer no client features
167                try:
168                    if m["method"] == "ping":
169                        self._send({"jsonrpc": "2.0", "id": m["id"], "result": {}})
170                    else:
171                        self._send({"jsonrpc": "2.0", "id": m["id"],
172                                    "error": {"code": -32601, "message": f"method not supported: {m['method']}"}})
173                except McpError:
174                    pass
175            return                                       # notifications (log messages, list changes): not used
176        with self.lock:
177            slot = self.pending.pop(m.get("id"), None)
178        if slot is not None:                             # an answer to a call that timed out is simply dropped
179            slot.msg = m
180            slot.done.set()
181
182    def _send(self, msg: dict):
183        data = json.dumps(msg, ensure_ascii=False).encode("utf-8") + b"\n"
184        try:
185            with self.write_lock:
186                self.proc.stdin.write(data)
187                self.proc.stdin.flush()
188        except (OSError, ValueError):
189            raise McpError(f"the server stopped{self._tail()}") from None
190
191    def request(self, method: str, params: dict, timeout: float, cancel=None):
192        if not self.alive():
193            raise McpError(f"the server is not running{self._tail()}")
194        slot = _Slot()
195        with self.lock:
196            self.next_id += 1
197            rid = self.next_id
198            self.pending[rid] = slot
199        try:
200            self._send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
201            return _wait(slot, timeout, cancel, method)
202        except (McpTimeout, McpCancelled) as e:
203            with self.lock:
204                self.pending.pop(rid, None)
205            try:                                         # tell the server to stop working on it
206                self.notify("notifications/cancelled", {"requestId": rid, "reason": str(e)})
207            except McpError:
208                pass
209            raise
210
211    def notify(self, method: str, params: dict | None = None):
212        self._send({"jsonrpc": "2.0", "method": method, **({"params": params} if params is not None else {})})
213
214    def close(self):
215        """As the spec says: close its stdin, give it a moment to exit, then end it (and what it started)."""
216        p = self.proc
217        if p is None:
218            return
219        try:
220            p.stdin.close()
221        except OSError:
222            pass
223        try:
224            p.wait(timeout=2)
225        except subprocess.TimeoutExpired:
226            self._kill_tree(p)
227        for f in (p.stdout, p.stderr):
228            try:
229                f.close()
230            except OSError:
231                pass
232
233    @staticmethod
234    def _kill_tree(p):
235        try:
236            if os.name == "nt":                          # npx.cmd -> node: end the whole tree
237                subprocess.run(["taskkill", "/PID", str(p.pid), "/T", "/F"], stdout=subprocess.DEVNULL,
238                               stderr=subprocess.DEVNULL, timeout=10)
239            else:
240                os.killpg(p.pid, signal.SIGTERM)
241                try:
242                    p.wait(timeout=2)
243                except subprocess.TimeoutExpired:
244                    os.killpg(p.pid, signal.SIGKILL)
245        except (OSError, subprocess.SubprocessError):
246            pass
247        try:
248            p.kill()
249        except OSError:
250            pass
251
252
253class HttpTransport:
254    """A server at an address (Streamable HTTP): every message is a POST; the answer is JSON or an event stream that
255    carries it.  The session id the server hands out at `initialize` rides on every later request."""
256    kind = "http"
257
258    def __init__(self, name: str, cfg: dict):
259        self.name, self.url = name, str(cfg["url"])
260        self.headers = {str(k): str(v) for k, v in (cfg.get("headers") or {}).items()}
261        self.session = None
262        self.protocol = None                             # sent as MCP-Protocol-Version once negotiated
263        self.next_id = 0
264        self.lock = threading.Lock()
265        self.broken = None
266
267    def start(self):
268        pass
269
270    def alive(self) -> bool:
271        return self.broken is None
272
273    def _headers(self) -> dict:
274        h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
275             "User-Agent": "strata", **self.headers}
276        if self.session:
277            h["Mcp-Session-Id"] = self.session
278        if self.protocol:
279            h["MCP-Protocol-Version"] = self.protocol
280        return h
281
282    def _post(self, msg: dict, rid, timeout: float, slot: _Slot | None):
283        try:
284            req = urllib.request.Request(self.url, data=json.dumps(msg, ensure_ascii=False).encode("utf-8"),
285                                         headers=self._headers(), method="POST")
286            with urllib.request.urlopen(req, timeout=timeout) as r:
287                if r.headers.get("Mcp-Session-Id"):
288                    self.session = r.headers["Mcp-Session-Id"]
289                if slot is None:                         # a notification: 202, nothing to read
290                    return
291                ctype = r.headers.get("Content-Type", "")
292                if "text/event-stream" in ctype:
293                    found = self._from_events(r, rid)
294                else:
295                    body = r.read()
296                    found = None
297                    parsed = json.loads(body) if body.strip() else None
298                    for m in parsed if isinstance(parsed, list) else [parsed]:
299                        if isinstance(m, dict) and m.get("id") == rid and "method" not in m:
300                            found = m
301                if found is None:
302                    raise McpError("the server's answer did not contain a response")
303                slot.msg = found
304        except urllib.error.HTTPError as e:
305            detail = ""
306            try:
307                detail = e.read().decode("utf-8", "replace")[:300]
308            except OSError:
309                pass
310            if e.code == 404 and self.session:           # the session expired: a restart starts a new one
311                self.broken = McpError("the server ended the session")
312            err = McpError(f"HTTP {e.code} {e.reason}{': ' + detail if detail else ''}")
313            if slot is None:
314                raise err from None
315            slot.error = err
316        except (OSError, ValueError, McpError) as e:
317            err = e if isinstance(e, McpError) else McpError(f"could not reach {self.url}: {e}")
318            if slot is None:
319                raise err from None
320            slot.error = err
321        finally:
322            if slot is not None:
323                slot.done.set()
324
325    @staticmethod
326    def _from_events(r, rid):
327        """Read the event stream until the event that answers `rid` (it may carry notifications first)."""
328        data = []
329        for raw in r:
330            line = raw.decode("utf-8", "replace").rstrip("\r\n")
331            if line.startswith("data:"):
332                data.append(line[5:].lstrip(" "))
333            elif not line and data:
334                try:
335                    m = json.loads("\n".join(data))
336                except ValueError:
337                    m = None
338                data = []
339                for x in m if isinstance(m, list) else [m]:
340                    if isinstance(x, dict) and x.get("id") == rid and "method" not in x:
341                        return x
342        return None
343
344    def request(self, method: str, params: dict, timeout: float, cancel=None):
345        if self.broken:
346            raise self.broken
347        with self.lock:
348            self.next_id += 1
349            rid = self.next_id
350        slot = _Slot()
351        # the POST runs on its own thread so the stop button and the deadline are noticed while it waits
352        threading.Thread(target=self._post, args=({"jsonrpc": "2.0", "id": rid, "method": method, "params": params},
353                                                  rid, timeout + 5, slot), daemon=True).start()
354        try:
355            return _wait(slot, timeout, cancel, method)
356        except (McpTimeout, McpCancelled) as e:
357            threading.Thread(target=self._quiet_notify, args=("notifications/cancelled",
358                                                              {"requestId": rid, "reason": str(e)}), daemon=True).start()
359            raise
360
361    def _quiet_notify(self, method, params):
362        try:
363            self.notify(method, params)
364        except McpError:
365            pass
366
367    def notify(self, method: str, params: dict | None = None):
368        self._post({"jsonrpc": "2.0", "method": method, **({"params": params} if params is not None else {})},
369                   None, 10, None)
370
371    def close(self):
372        if not self.session:
373            return
374        try:                                             # end the session on the server (it may not allow that)
375            req = urllib.request.Request(self.url, headers=self._headers(), method="DELETE")
376            urllib.request.urlopen(req, timeout=3).close()
377        except (OSError, ValueError):
378            pass
379
380
381# ------------------------------------------------------------------------------------------------ one server
382class McpServer:
383    """One configured server: started once (and again after it stopped), with the tools it listed."""
384
385    def __init__(self, name: str, cfg: dict, settings: dict):
386        self.name, self.cfg, self.settings = name, cfg, settings
387        self.kind = "http" if cfg.get("url") else "stdio"
388        self.status = "idle"             # idle -> starting -> ready | failed; ready -> stopped when it ends
389        self.error = None
390        self.tools: list[dict] = []
391        self.info: dict = {}
392        self.transport = None
393        self.lock = threading.Lock()
394        self.last_start = 0.0
395
396    def start(self) -> bool:
397        with self.lock:
398            return self._start()
399
400    def _start(self) -> bool:
401        if self.transport is not None:
402            self.transport.close()
403        self.status, self.error, self.last_start = "starting", None, time.monotonic()
404        t = HttpTransport(self.name, self.cfg) if self.kind == "http" else StdioTransport(self.name, self.cfg)
405        self.transport = t
406        timeout = float(self.settings["start_timeout_s"])
407        try:
408            t.start()
409            res = t.request("initialize", {"protocolVersion": PROTOCOL, "capabilities": {},
410                                           "clientInfo": {"name": "strata", "title": "Strata", "version": "1"}},
411                            timeout)
412            t.protocol = str(res.get("protocolVersion") or PROTOCOL)
413            self.info = {k: v for k, v in (res.get("serverInfo") or {}).items() if k in ("name", "title", "version")}
414            self.info["protocol"] = t.protocol
415            t.notify("notifications/initialized")
416            tools, cursor = [], None
417            for _ in range(100):                         # pages; a server that never stops paging is cut off
418                try:
419                    page = t.request("tools/list", {"cursor": cursor} if cursor else {}, timeout)
420                except McpError as e:
421                    if "code -32601" in str(e) and not tools:   # a server without tools (prompts/resources only)
422                        break
423                    raise
424                tools += [x for x in page.get("tools") or [] if isinstance(x, dict) and x.get("name")]
425                cursor = page.get("nextCursor")
426                if not cursor:
427                    break
428            self.tools, self.status = tools, "ready"
429            names = ", ".join(x["name"] for x in tools[:8]) + (", ..." if len(tools) > 8 else "")
430            print(f"[strata] MCP server {self.name!r}: {len(tools)} tool{'s' * (len(tools) != 1)}"
431                  f"{' (' + names + ')' if tools else ''}", flush=True)
432            return True
433        except McpError as e:
434            self.status, self.error, self.tools = "failed", str(e), []
435            t.close()
436            print(f"[strata] MCP server {self.name!r} did not start: {e}. Its tools are left out; the chat works "
437                  "without them.", flush=True)
438            return False
439
440    def call(self, tool: str, arguments: dict, timeout: float, cancel=None) -> dict:
441        with self.lock:
442            if self.transport is None or not self.transport.alive():
443                # it stopped since its last call (a crash, an expired session): start it again; one that failed to
444                # start is tried again at most every 10 s, so a broken command does not run on every call
445                if self.status == "failed" and time.monotonic() - self.last_start < 10:
446                    raise McpError(f"the server is not running ({self.error or 'it stopped'})")
447                print(f"[strata] MCP server {self.name!r} had stopped; starting it again", flush=True)
448                if not self._start():
449                    raise McpError(f"the server could not be started again: {self.error}")
450            t = self.transport
451        try:
452            return t.request("tools/call", {"name": tool, "arguments": arguments}, timeout, cancel)
453        except McpError as e:
454            if not t.alive():
455                self.status, self.error = "stopped", str(e)
456            raise
457
458    def close(self):
459        with self.lock:
460            if self.transport is not None:
461                self.transport.close()
462            if self.status in ("ready", "starting"):
463                self.status = "stopped"
464
465
466# ------------------------------------------------------------------------------------------------ the hub
467def result_text(result: dict) -> str:
468    """An MCP tool result as the text the model reads: the text blocks as they are, other blocks named."""
469    parts = []
470    for block in result.get("content") or []:
471        if not isinstance(block, dict):
472            continue
473        kind = block.get("type")
474        if kind == "text":
475            parts.append(str(block.get("text", "")))
476        elif kind == "resource":
477            res = block.get("resource") or {}
478            parts.append(str(res["text"]) if "text" in res else f"[resource {res.get('uri', '')} "
479                                                                  f"({res.get('mimeType', 'binary')}), not shown]")
480        elif kind == "resource_link":
481            parts.append(f"[resource link: {block.get('name') or ''} {block.get('uri', '')}]".replace("  ", " "))
482        elif kind in ("image", "audio"):
483            size = len(block.get("data") or "") * 3 // 4
484            parts.append(f"[{kind} ({block.get('mimeType', '?')}, {size:,} bytes): not shown to the model]")
485        else:
486            parts.append(json.dumps(block, ensure_ascii=False))
487    if not parts and result.get("structuredContent") is not None:
488        parts.append(json.dumps(result["structuredContent"], ensure_ascii=False))
489    return "\n".join(parts)
490
491
492def cache_images(result, directory):
493    """Keep raster tool outputs outside chat history; never expose arbitrary tool paths."""
494    images = []
495    directory = Path(directory)
496    types = {"image/png": ("png", b"\x89PNG\r\n\x1a\n"), "image/jpeg": ("jpg", b"\xff\xd8\xff"),
497             "image/webp": ("webp", b"RIFF")}
498    for block in result.get("content") or []:
499        if not isinstance(block, dict):
500            continue
501        mime = block.get("mimeType")
502        if block.get("type") != "image" or mime not in types or len(images) >= 4:
503            continue
504        encoded = block.get("data")
505        if not isinstance(encoded, str) or len(encoded) > 24_000_000:
506            continue
507        try:
508            data = base64.b64decode(encoded, validate=True)
509        except (ValueError, TypeError):
510            continue
511        ext, magic = types[mime]
512        if not data.startswith(magic) or (ext == "webp" and data[8:12] != b"WEBP"):
513            continue
514        directory.mkdir(parents=True, exist_ok=True)
515        name = hashlib.sha256(data).hexdigest() + "." + ext
516        target = directory / name
517        if not target.exists():
518            temporary = directory / (name + "." + os.urandom(8).hex() + ".tmp")
519            try:
520                temporary.write_bytes(data)
521                os.replace(temporary, target)
522            finally:
523                temporary.unlink(missing_ok=True)
524        images.append({"url": "tool-media/" + name, "mimeType": mime, "name": "tool-image." + ext})
525    return images
526
527
528def _clean(name: str) -> str:
529    return re.sub(r"[^A-Za-z0-9_-]", "_", str(name)) or "x"
530
531
532class McpHub:
533    """Every configured server, and the merged, namespaced tool list the model sees."""
534
535    def __init__(self, servers: dict[str, dict], settings: dict | None = None):
536        self.media_dir = None
537        self.settings = {**DEFAULTS, **(settings or {})}
538        self.servers = {name: McpServer(name, cfg, self.settings) for name, cfg in servers.items()}
539        self.threads: list[threading.Thread] = []
540        self._routes: dict[str, tuple[McpServer, str]] = {}
541
542    def start(self, wait: bool = False):
543        """Start every server on its own thread (npx may download a package first: that must not delay the chat)."""
544        self.threads = [threading.Thread(target=s.start, daemon=True, name=f"mcp-{s.name}")
545                        for s in self.servers.values()]
546        for t in self.threads:
547            t.start()
548        if wait:
549            self.wait(None)
550
551    def wait(self, timeout: float | None) -> None:
552        """Wait (up to `timeout` s in all) for servers that are still starting."""
553        end = None if timeout is None else time.monotonic() + timeout
554        for t in self.threads:
555            t.join(None if end is None else max(0.0, end - time.monotonic()))
556
557    def routes(self) -> dict[str, tuple[McpServer, str]]:
558        """tool name the model sees -> (server, the tool's own name).  A server that stopped after it was ready keeps
559        its tools here: a call starts it again."""
560        out = {}
561        for s in self.servers.values():
562            if s.status not in ("ready", "stopped"):
563                continue
564            for t in s.tools:
565                name = f"{_clean(s.name)}__{_clean(t['name'])}"[:64]
566                n = 2
567                while name in out:                       # two names that differ only in cleaned characters
568                    name = f"{name[:60]}_{n}"
569                    n += 1
570                out[name] = (s, t["name"])
571        self._routes = out
572        return out
573
574    def template_tools(self, exclude=()) -> list[dict]:
575        """The tools in the chat template's form ({name, description, parameters}); `exclude`: names the request
576        brought itself (those win)."""
577        out = []
578        for name, (s, tool) in self.routes().items():
579            if name in exclude:
580                continue
581            t = next(x for x in s.tools if x["name"] == tool)
582            schema = t.get("inputSchema") if isinstance(t.get("inputSchema"), dict) else {}
583            out.append({"name": name, "description": str(t.get("description") or t.get("title") or ""),
584                        "parameters": schema or {"type": "object", "properties": {}}})
585        return out
586
587    def openai_tools(self) -> list[dict]:
588        return [{"type": "function", "function": t} for t in self.template_tools()]
589
590    def call(self, name: str, arguments: dict, cancel: threading.Event | None = None) -> dict:
591        """Run one tool -> {"ok", "text" (what the model reads, capped), "chars" (its full length), "truncated",
592        "ms", "server", "tool"}.  Errors become text starting with "error:"; only McpCancelled is raised."""
593        t0 = time.monotonic()
594        server, tool = self._routes.get(name) or self.routes().get(name, (None, name))
595        out = {"server": server.name if server else None, "tool": tool}
596        if server is None:
597            text, ok = f"error: there is no tool named {name!r}", False
598        else:
599            try:
600                res = server.call(tool, arguments if isinstance(arguments, dict) else {},
601                                  float(self.settings["timeout_s"]), cancel)
602                text, ok = result_text(res), not res.get("isError")
603                if ok and self.settings["image_results"] and self.media_dir is not None:
604                    try:
605                        images = cache_images(res, self.media_dir)
606                    except OSError as e:
607                        print(f"[strata] MCP image cache unavailable: {e}", file=sys.stderr, flush=True)
608                    else:
609                        if images:
610                            out["images"] = images
611                if not ok:
612                    text = "error: " + (text or "the tool reported an error")
613            except McpCancelled:
614                raise
615            except McpError as e:
616                text, ok = f"error: {e}", False
617        cap = int(self.settings["max_result_chars"])
618        full = len(text)
619        if cap > 0 and full > cap:
620            text = text[:cap] + (f"\n\n[... truncated: the tool returned {full:,} characters; only the first "
621                                 f"{cap:,} are shown]")
622        if ok and out.get("images"):
623            out["model_content"] = [{"type": "text", "text": text.replace(": not shown to the model]", ": image attached]")}] + [
624                {"type": "image", "source": str(Path(self.media_dir) / im["url"].split("/")[-1])}
625                for im in out["images"]]
626        out.update(ok=ok, text=text, chars=full, truncated=cap > 0 and full > cap,
627                   ms=int((time.monotonic() - t0) * 1000))
628        return out
629
630    def status(self) -> dict:
631        """GET /mcp: every server, its state and its tools (for the web app)."""
632        routes = self.routes()
633        servers = []
634        for s in self.servers.values():
635            names = {tool: n for n, (srv, tool) in routes.items() if srv is s}
636            servers.append({"name": s.name, "transport": s.kind, "status": s.status, "error": s.error,
637                            "info": s.info,
638                            "tools": [{"name": names.get(t["name"], t["name"]), "tool": t["name"],
639                                       "description": str(t.get("description") or "")[:300]} for t in s.tools]})
640        return {"servers": servers, "tools": len(routes),
641                "settings": {k: self.settings[k] for k in ("timeout_s", "max_result_chars", "max_rounds")}}
642
643    def close(self):
644        for s in self.servers.values():
645            try:
646                s.close()
647            except Exception:  # noqa: BLE001 - closing is best effort
648                pass
649
650
651# ------------------------------------------------------------------------------------------------ config
652def _check_server(name, cfg, where) -> dict:
653    if not isinstance(cfg, dict):
654        raise SystemExit(f"[strata] {where}: MCP server {name!r} must be an object with \"command\" or \"url\"")
655    if cfg.get("url"):
656        if cfg.get("type") == "sse":
657            raise SystemExit(f"[strata] {where}: MCP server {name!r} uses the old SSE transport (\"type\": \"sse\"); "
658                             "Strata speaks Streamable HTTP - most servers offer it at /mcp")
659        if not isinstance(cfg.get("headers") or {}, dict):
660            raise SystemExit(f"[strata] {where}: MCP server {name!r}: \"headers\" must be an object")
661        return cfg
662    if not isinstance(cfg.get("command"), str) or not cfg["command"].strip():
663        raise SystemExit(f"[strata] {where}: MCP server {name!r} needs \"command\" (a program to start) or \"url\"")
664    if not isinstance(cfg.get("args") or [], list):
665        raise SystemExit(f"[strata] {where}: MCP server {name!r}: \"args\" must be a list")
666    if not isinstance(cfg.get("env") or {}, dict):
667        raise SystemExit(f"[strata] {where}: MCP server {name!r}: \"env\" must be an object")
668    return cfg
669
670
671def servers_from(block, where: str) -> dict[str, dict]:
672    """{"name": {...}} with the entries checked; `"disabled": true` leaves one out."""
673    if block is None:
674        return {}
675    if not isinstance(block, dict):
676        raise SystemExit(f"[strata] {where}: the MCP servers must be an object {{\"name\": {{...}}}}")
677    return {str(n): _check_server(n, c, where) for n, c in block.items()
678            if not (isinstance(c, dict) and c.get("disabled") is True)}
679
680
681def settings_from(cfg: dict) -> dict:
682    """The run config's optional `"mcp"` block: timeout_s, max_result_chars, max_rounds, start_timeout_s, image_results."""
683    out = {}
684    for key, value in (cfg.get("mcp") or {}).items():
685        number = isinstance(value, (int, float)) and not isinstance(value, bool)
686        if key == "image_results":
687            if not isinstance(value, bool):
688                raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a boolean")
689            out[key] = value
690        elif key in ("timeout_s", "start_timeout_s"):
691            if not number or value <= 0:
692                raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a number of seconds > 0")
693            out[key] = float(value)
694        elif key in ("max_result_chars", "max_rounds"):
695            if not number or value != int(value) or value < 1:
696                raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a positive integer")
697            out[key] = int(value)
698        else:
699            print(f"[strata] config mcp.{key}={value!r}: unknown key, ignored", flush=True)
700    return out
701
702
703def hub_from_config(cfg: dict, mcp_config_path: str | None = None) -> McpHub | None:
704    """The run config's `"mcp_servers"` (or `"mcpServers"`) plus the servers in the --mcp-config file (Claude
705    Desktop's format: {"mcpServers": {...}}); a name in both takes the file's entry.  None when there are none."""
706    servers = {}
707    servers.update(servers_from(cfg.get("mcp_servers"), "config mcp_servers"))
708    servers.update(servers_from(cfg.get("mcpServers"), "config mcpServers"))
709    if mcp_config_path:
710        try:
711            with open(mcp_config_path, encoding="utf-8-sig") as f:
712                data = json.load(f)
713        except (OSError, ValueError) as e:
714            raise SystemExit(f"[strata] --mcp-config {mcp_config_path}: {e}") from None
715        block = data.get("mcpServers", data.get("mcp_servers")) if isinstance(data, dict) else None
716        if block is None:
717            raise SystemExit(f"[strata] --mcp-config {mcp_config_path}: expected {{\"mcpServers\": {{...}}}}")
718        servers.update(servers_from(block, f"--mcp-config {mcp_config_path}"))
719    if not servers:
720        return None
721    return McpHub(servers, settings_from(cfg))
722
723
724if __name__ == "__main__":                               # python -m serve.mcp config.json: list what a config offers
725    hub = hub_from_config(json.load(open(sys.argv[1], encoding="utf-8-sig")) if len(sys.argv) > 1 else {},
726                          sys.argv[2] if len(sys.argv) > 2 else None)
727    if hub is None:
728        sys.exit("no MCP servers configured")
729    hub.start(wait=True)
730    print(json.dumps(hub.status(), indent=1))
731    hub.close()