#!/usr/bin/env python3 """tests/mcp.py - drive ./plugin_fetch --mcp from a JSON call list. The offline suite has to speak real MCP frames to the binary, and doing that from /bin/sh means quoting JSON inside shell strings (a heredoc expands the \n escapes inside JSON string values into real newlines and hands the connector invalid frames). This helper keeps the wire protocol in one place: it opens the connector, performs `initialize` and `notifications/initialized`, then sends one frame per entry, and prints a flat `KEYstatustext` line per call that run.sh can grep. Every line the connector writes to stdout is a JSON-RPC frame, so this reads them all and matches on id. Server-side noise (stderr, unparseable lines) is reported, not hidden. tests/mcp.py [KEY=VALUE ...] calls.json is a list of objects: {"call":"", "tool":"fetch", "args":{...}} a tools/call {"call":"", "method":"tools/list"} a raw method {"call":"", "raw":""} a raw stdout line (parse-error paths) `"args"` values are sent verbatim, so a call can pass a string where an int is expected, an empty args object, or no args at all. """ import json import os import subprocess import sys PROTO = "2024-11-05" def main(): if len(sys.argv) < 3: print("usage: mcp.py [KEY=VALUE ...]", file=sys.stderr) return 2 binary, calls_path = sys.argv[1], sys.argv[2] env = dict(os.environ) for kv in sys.argv[3:]: if "=" in kv: k, v = kv.split("=", 1) env[k] = v with open(calls_path, "r", encoding="utf-8") as f: calls = json.load(f) frames = [ {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": PROTO, "capabilities": {}, "clientInfo": {"name": "plugin_fetch-tests", "version": "1"}}}, {"jsonrpc": "2.0", "method": "notifications/initialized"}, ] keys = [] for i, c in enumerate(calls, start=2): if "raw" in c: frames.append(c["raw"]) keys.append((c.get("call", "raw%d" % i), i if "id" in str(c["raw"]) else None)) continue if "method" in c: frames.append({"jsonrpc": "2.0", "id": i, "method": c["method"], "params": c.get("params", {})}) else: frames.append({"jsonrpc": "2.0", "id": i, "method": "tools/call", "params": {"name": c.get("tool", "fetch"), "arguments": c.get("args", {})}}) keys.append((c.get("call", c.get("tool", "call%d" % i)), i)) stdin_data = "\n".join( f if isinstance(f, str) else json.dumps(f) for f in frames) + "\n" try: proc = subprocess.run([binary, "--mcp"], input=stdin_data, capture_output=True, text=True, env=env, timeout=180) except subprocess.TimeoutExpired: print("_timeout\tinfo\tthe connector did not finish") return 1 by_id, unparsed = {}, [] for line in proc.stdout.splitlines(): line = line.strip() if not line: continue try: d = json.loads(line) except ValueError: unparsed.append(line) continue if "id" in d: by_id[d["id"]] = d for key, ident in keys: if ident is None: continue d = by_id.get(ident) if d is None: print("%s\tmissing\t(no response)" % key) continue if "error" in d: print("%s\trpcerr\t%s" % (key, json.dumps(d["error"]))) continue res = d.get("result", {}) if "content" in res: text = "".join(c.get("text", "") for c in res.get("content", [])) # one call must be one line so awk -F'\t' can pick it out: real # newlines in the fetched text become literal \n sequences. text = text.replace("\\", "\\\\").replace("\n", "\\n") print("%s\t%s\t%s" % (key, "err" if res.get("isError") else "ok", text)) else: print("%s\tok\t%s" % (key, json.dumps(res))) if unparsed: print("_unparsed\tinfo\t%s" % " | ".join(unparsed)[:400]) if proc.stderr: print("_stderr\tinfo\t%s" % proc.stderr.strip().replace("\n", " | ")[:400]) return 0 if __name__ == "__main__": sys.exit(main())