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