garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /tests/e2e/fakebot.py

raw

#!/usr/bin/env python3
"""A toy bot for the end-to-end test: MCP (JSON-RPC, one message per line) on
a Unix socket, after a few seconds of "building" โ€” so `midas node bot start`
has to wait for it, as it waits for a real bot's first `cargo run`.

    python3 fakebot.py SOCKET [DELAY_S]

Tools: `echo` (says back what it is given) and `token` (whether the machine
owner's secret, E2E_TOKEN, reached the bot's environment โ€” its length and a
hash, never the value).
"""
import hashlib, json, os, socket, sys, threading, time

path = sys.argv[1]
delay = float(sys.argv[2]) if len(sys.argv) > 2 else 4.0
print(f"fakebot: building for {delay}s", flush=True)
time.sleep(delay)

TOOLS = [
    {"name": "echo", "description": "Say it back.",
     "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}},
    {"name": "token", "description": "Is E2E_TOKEN in this bot's environment?",
     "inputSchema": {"type": "object", "properties": {}}},
]

def answer(msg):
    method, mid = msg.get("method"), msg.get("id")
    if mid is None:
        return None  # a notification
    if method == "initialize":
        result = {"protocolVersion": msg["params"].get("protocolVersion", "2025-06-18"),
                  "capabilities": {"tools": {}}, "serverInfo": {"name": "fakebot", "version": "0"}}
    elif method == "ping":
        result = {}
    elif method == "tools/list":
        result = {"tools": TOOLS}
    elif method == "tools/call":
        name, args = msg["params"]["name"], msg["params"].get("arguments", {})
        if name == "echo":
            text = f"echo: {args.get('text', '')}"
        elif name == "token":
            t = os.environ.get("E2E_TOKEN")
            text = "E2E_TOKEN unset" if t is None else \
                f"E2E_TOKEN set, {len(t)} chars, sha256 {hashlib.sha256(t.encode()).hexdigest()[:16]}"
        else:
            return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": f"no tool {name}"}}
        result = {"content": [{"type": "text", "text": text}], "isError": False}
    else:
        return {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"no method {method}"}}
    return {"jsonrpc": "2.0", "id": mid, "result": result}

def serve(conn):
    with conn, conn.makefile("rwb") as f:
        for line in f:
            try:
                reply = answer(json.loads(line))
            except Exception as e:  # noqa: BLE001 โ€” a toy
                reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(e)}}
            if reply is not None:
                f.write((json.dumps(reply) + "\n").encode())
                f.flush()

os.makedirs(os.path.dirname(path), exist_ok=True)
if os.path.exists(path):
    os.unlink(path)
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
srv.bind(path)
srv.listen()
print(f"fakebot: listening on {path}", flush=True)
while True:
    c, _ = srv.accept()
    threading.Thread(target=serve, args=(c,), daemon=True).start()