"""Tiny MCP server for tests. stdio (default) or streamable HTTP: `fake_mcp.py http PORT`. Tools: echo(message), add(a,b), crash() (exits the process), big() (large output), slow(). One prompt, one resource. """ import json, os, sys, time TOOLS = [ {"name": "echo", "description": "Echo a message back\nsecond line ignored in index", "inputSchema": {"type": "object", "properties": {"message": {"type": "string"}}, "required": ["message"]}}, {"name": "add", "description": "Add two integers", "inputSchema": {"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"]}}, {"name": "crash", "description": "Kill the server", "inputSchema": {"type": "object", "properties": {}}}, {"name": "big", "description": "Large output", "inputSchema": {"type": "object", "properties": {}}}, {"name": "slow", "description": "Sleeps 5s", "inputSchema": {"type": "object", "properties": {}}}, ] def handle(m): meth, p, i = m.get("method"), m.get("params") or {}, m.get("id") if i is None: return None r = None if meth == "initialize": time.sleep(float(os.environ.get("FAKE_INIT_DELAY", "0"))) r = {"protocolVersion": p.get("protocolVersion"), "serverInfo": {"name": "fake", "version": "1"}, "capabilities": {"tools": {}, "prompts": {}, "resources": {}}, "instructions": "Use echo for tests."} elif meth == "tools/list": # paginate: first page 2 tools if p.get("cursor") == "p2": r = {"tools": TOOLS[2:]} else: r = {"tools": TOOLS[:2], "nextCursor": "p2"} elif meth == "tools/call": n, a = p["name"], p.get("arguments") or {} if n == "echo": r = {"content": [{"type": "text", "text": "echo: " + a["message"]}]} elif n == "add": r = {"content": [{"type": "text", "text": str(a["a"] + a["b"])}]} elif n == "crash": sys.exit(3) elif n == "big": r = {"content": [{"type": "text", "text": "x" * 100000}]} elif n == "slow": time.sleep(5) r = {"content": [{"type": "text", "text": "late"}]} else: r = {"content": [{"type": "text", "text": "no such tool"}], "isError": True} elif meth == "prompts/list": r = {"prompts": [{"name": "review", "description": "Review a file", "arguments": [{"name": "path", "required": True}]}]} elif meth == "prompts/get": r = {"messages": [{"role": "user", "content": {"type": "text", "text": "Please review " + p["arguments"].get("path", "?")}}]} elif meth == "resources/list": r = {"resources": [{"uri": "mem://notes", "name": "notes"}]} elif meth == "resources/read": r = {"contents": [{"uri": p["uri"], "text": "note body"}]} else: return {"jsonrpc": "2.0", "id": i, "error": {"code": -32601, "message": "method not found"}} return {"jsonrpc": "2.0", "id": i, "result": r} if len(sys.argv) > 1 and sys.argv[1] == "http": import http.server, urllib.parse # `http PORT oauth`: OAuth-protected. Code login yields a1 (3600s) which the server rejects, so the client # must refresh (r1 -> a2). Only a2 is accepted. OAUTH = len(sys.argv) > 3 and sys.argv[3] == "oauth" ORIGIN = "http://127.0.0.1:" + sys.argv[2] class H(http.server.BaseHTTPRequestHandler): def log_message(self, *a): pass def _json(self, o): self.send_response(200); self.send_header("content-type", "application/json"); self.end_headers() self.wfile.write(json.dumps(o).encode()) def do_GET(self): if self.path == "/prm": return self._json({"authorization_servers": [ORIGIN]}) if self.path == "/.well-known/oauth-authorization-server": return self._json({"authorization_endpoint": ORIGIN + "/authorize", "token_endpoint": ORIGIN + "/token", "registration_endpoint": ORIGIN + "/register"}) self.send_response(404); self.end_headers() def do_POST(self): if OAUTH and self.path in ("/register", "/token"): body = self.rfile.read(int(self.headers["content-length"])) if self.path == "/register": return self._json({"client_id": "c1"}) f = {k: v[0] for k, v in urllib.parse.parse_qs(body.decode()).items()} if f.get("grant_type") == "authorization_code" and f.get("code") == "abc" and f.get("code_verifier") and f.get("client_id") == "c1" and f.get("resource", "").endswith("/mcp"): return self._json({"access_token": "a1", "refresh_token": "r1", "expires_in": 3600}) if f.get("grant_type") == "refresh_token" and f.get("refresh_token") == "r1": return self._json({"access_token": "a2", "expires_in": 3600}) self.send_response(400); self.end_headers(); return if self.headers.get("authorization") != ("Bearer a2" if OAUTH else "Bearer t0k"): self.send_response(401) if OAUTH: self.send_header("www-authenticate", 'Bearer resource_metadata="%s/prm"' % ORIGIN) self.end_headers(); return m = json.loads(self.rfile.read(int(self.headers["content-length"]))) if m.get("method") != "initialize" and self.headers.get("mcp-session-id") != "s1": self.send_response(400); self.end_headers(); return r = handle(m) if r is None: self.send_response(202); self.end_headers(); return self.send_response(200) self.send_header("mcp-session-id", "s1") # answer tools/call as SSE, everything else as JSON if m.get("method") == "tools/call": self.send_header("content-type", "text/event-stream"); self.end_headers() self.wfile.write(b'event: message\ndata: {"jsonrpc":"2.0","method":"notifications/progress","params":{}}\n\n') self.wfile.write(("event: message\ndata: " + json.dumps(r) + "\n\n").encode()) else: self.send_header("content-type", "application/json"); self.end_headers() self.wfile.write(json.dumps(r).encode()) http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[2])), H).serve_forever() else: for line in sys.stdin: r = handle(json.loads(line)) if r is not None: sys.stdout.write(json.dumps(r) + "\n") sys.stdout.flush()