okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
714ff8242
main
1"""serve/mcp_fake_server.py - a small MCP server for serve/test_mcp.py (no MCP SDK, no network beyond localhost). 2 3python serve/mcp_fake_server.py stdio: JSON-RPC lines on stdin/stdout 4python serve/mcp_fake_server.py --http 8765 Streamable HTTP on 127.0.0.1:8765/mcp 5 6Tools: echo (returns its text), fail (a tool error, isError), sleep (answers after `seconds`), big (`n` characters), 7die (the process exits mid-call), add (two integers). tools/list pages two tools at a time (`--page N`), so the 8client's pagination is exercised. `--crash-at-start` exits before answering anything. With FAKE_MCP_LOG set, the 9server appends what it saw (calls, cancellations) to that file, one JSON line each. 10""" 11from __future__import annotations 12 13import json 14import os 15import socketserver 16import sys 17import threading 18import time 19from http .server import BaseHTTPRequestHandler ,ThreadingHTTPServer 20 21TOOLS = [ 22 {"name" :"echo" ,"description" :"Returns the text it is given." , 23"inputSchema" : {"type" :"object" ,"properties" : {"text" : {"type" :"string" }},"required" : ["text" ]}}, 24 {"name" :"fail" ,"description" :"Always fails." ,"inputSchema" : {"type" :"object" ,"properties" : {}}}, 25 {"name" :"sleep" ,"description" :"Waits, then answers." , 26"inputSchema" : {"type" :"object" ,"properties" : {"seconds" : {"type" :"number" }}}}, 27 {"name" :"big" ,"description" :"Returns n characters." , 28"inputSchema" : {"type" :"object" ,"properties" : {"n" : {"type" :"integer" }}}}, 29 {"name" :"die" ,"description" :"Ends the server." ,"inputSchema" : {"type" :"object" ,"properties" : {}}}, 30 {"name" :"add" ,"description" :"Adds two integers." , 31"inputSchema" : {"type" :"object" ,"properties" : {"a" : {"type" :"integer" },"b" : {"type" :"integer" }}}}, 32] 33PAGE = 2 34cancelled :set = set () 35 36 37def log (event :dict ): 38path = os .environ .get ("FAKE_MCP_LOG" ) 39if path : 40with open (path ,"a" ,encoding = "utf-8" )as f : 41f .write (json .dumps (event )+ "\n" ) 42 43 44def text (t ,error = False ): 45return {"content" : [{"type" :"text" ,"text" :t }],"isError" :error } 46 47 48def handle (msg :dict ): 49"""-> the response for a request, None for a notification.""" 50method ,rid ,params = msg .get ("method" ),msg .get ("id" ),msg .get ("params" )or {} 51if "id" not in msg : 52if method == "notifications/cancelled" : 53cancelled .add (params .get ("requestId" )) 54log ({"cancelled" :params .get ("requestId" )}) 55return None 56if method == "initialize" : 57return {"jsonrpc" :"2.0" ,"id" :rid ,"result" : { 58"protocolVersion" :params .get ("protocolVersion" ,"2025-06-18" ),"capabilities" : {"tools" : {}}, 59"serverInfo" : {"name" :"fake" ,"version" :"0.1" }}} 60if method == "tools/list" : 61start = int (params .get ("cursor" )or 0 ) 62page = {"tools" :TOOLS [start :start + PAGE ]} 63if start + PAGE < len (TOOLS ): 64page ["nextCursor" ]= str (start + PAGE ) 65return {"jsonrpc" :"2.0" ,"id" :rid ,"result" :page } 66if method == "tools/call" : 67name ,args = params .get ("name" ),params .get ("arguments" )or {} 68log ({"call" :name ,"arguments" :args }) 69if name == "echo" : 70result = text (str (args .get ("text" ,"" ))) 71elif name == "fail" : 72result = text ("it failed on purpose" ,error = True ) 73elif name == "sleep" : 74time .sleep (float (args .get ("seconds" ,1 ))) 75result = text ("slept" ) 76elif name == "big" : 77result = text ("y" * int (args .get ("n" ,100000 ))) 78elif name == "die" : 79sys .stderr .write ("dying on purpose\n" ) 80sys .stderr .flush () 81os ._exit (3 ) 82elif name == "add" : 83result = text (str (int (args .get ("a" ,0 ))+ int (args .get ("b" ,0 )))) 84else : 85return {"jsonrpc" :"2.0" ,"id" :rid ,"error" : {"code" :- 32602 ,"message" :f"unknown tool { name } " }} 86return {"jsonrpc" :"2.0" ,"id" :rid ,"result" :result } 87return {"jsonrpc" :"2.0" ,"id" :rid ,"error" : {"code" :- 32601 ,"message" :f"no method { method } " }} 88 89 90def stdio (): 91for f in (sys .stdin ,sys .stdout ,sys .stderr ):# MCP's stdio is UTF-8, whatever the Windows code page is 92f .reconfigure (encoding = "utf-8" ) 93out = threading .Lock () 94 95def answer (msg ): 96r = handle (msg ) 97if r is not None and msg .get ("id" )not in cancelled : 98with out : 99sys .stdout .write (json .dumps (r )+ "\n" ) 100sys .stdout .flush () 101 102for line in sys .stdin : 103if not line .strip (): 104continue 105msg = json .loads (line ) 106if msg .get ("method" )== "tools/call" :# calls on threads: a slow one must not block cancellation 107threading .Thread (target = answer ,args = (msg ,),daemon = True ).start () 108else : 109answer (msg ) 110 111 112class _NoLookupServer (ThreadingHTTPServer ): 113"""http.server's server_bind also asks socket.getfqdn for the address, which stalled 35 s in every new process on GitHub's macOS runner.""" 114 115def server_bind (self ): 116socketserver .TCPServer .server_bind (self ) 117self .server_name ,self .server_port = self .server_address [:2 ] 118 119 120def http_server (port :int = 0 )-> ThreadingHTTPServer : 121"""Streamable HTTP at /mcp: JSON answers, except tools/call, which answers as an event stream (a progress 122notification first); a session id from initialize is required afterwards.""" 123sessions = set () 124 125class H (BaseHTTPRequestHandler ): 126protocol_version = "HTTP/1.0" 127 128def log_message (self ,* a ): 129pass 130 131def do_POST (self ): 132msg = json .loads (self .rfile .read (int (self .headers .get ("Content-Length" ,0 )))) 133if msg .get ("method" )!= "initialize" and self .headers .get ("Mcp-Session-Id" )not in sessions : 134self .send_response (400 ) 135self .end_headers () 136return 137r = handle (msg ) 138if r is None : 139self .send_response (202 ) 140self .end_headers () 141return 142if msg .get ("method" )== "tools/call" : 143self .send_response (200 ) 144self .send_header ("Content-Type" ,"text/event-stream" ) 145self .end_headers () 146note = {"jsonrpc" :"2.0" ,"method" :"notifications/progress" ,"params" : {"progress" :1 }} 147self .wfile .write (b"event: message\ndata: " + json .dumps (note ).encode ()+ b"\n\n" ) 148self .wfile .write (b"event: message\ndata: " + json .dumps (r ).encode ()+ b"\n\n" ) 149return 150body = json .dumps (r ).encode () 151self .send_response (200 ) 152self .send_header ("Content-Type" ,"application/json" ) 153self .send_header ("Content-Length" ,str (len (body ))) 154if msg .get ("method" )== "initialize" : 155sid = f"s- { len ( sessions ) + 1 } " 156sessions .add (sid ) 157self .send_header ("Mcp-Session-Id" ,sid ) 158self .end_headers () 159self .wfile .write (body ) 160 161def do_DELETE (self ): 162sessions .discard (self .headers .get ("Mcp-Session-Id" )) 163self .send_response (200 ) 164self .end_headers () 165 166httpd = _NoLookupServer (("127.0.0.1" ,port ),H ) 167threading .Thread (target = httpd .serve_forever ,daemon = True ).start () 168return httpd 169 170 171if __name__ == "__main__" : 172if "--page" in sys .argv : 173PAGE = int (sys .argv [sys .argv .index ("--page" )+ 1 ]) 174if "--crash-at-start" in sys .argv : 175sys .stderr .write ("cannot start: missing configuration\n" ) 176sys .exit (2 ) 177if "--http" in sys .argv : 178server = http_server (int (sys .argv [sys .argv .index ("--http" )+ 1 ])) 179f"listening on http://127.0.0.1: { server . server_address [ 1 ] } /mcp" ,flush = True ) 180threading .Event ().wait () 181stdio ()