| 1 | #!/usr/bin/env python3 |
| 2 | """tests/mcp.py - drive ./plugin_fetch --mcp from a JSON call list. |
| 3 | |
| 4 | The offline suite has to speak real MCP frames to the binary, and doing that |
| 5 | from /bin/sh means quoting JSON inside shell strings (a heredoc expands the \n |
| 6 | escapes inside JSON string values into real newlines and hands the connector |
| 7 | invalid frames). This helper keeps the wire protocol in one place: it opens the |
| 8 | connector, performs `initialize` and `notifications/initialized`, then sends |
| 9 | one frame per entry, and prints a flat `KEY<TAB>status<TAB>text` line per call |
| 10 | that run.sh can grep. |
| 11 | |
| 12 | Every line the connector writes to stdout is a JSON-RPC frame, so this reads |
| 13 | them all and matches on id. Server-side noise (stderr, unparseable lines) is |
| 14 | reported, not hidden. |
| 15 | |
| 16 | tests/mcp.py <binary> <calls.json> [KEY=VALUE ...] |
| 17 | |
| 18 | calls.json is a list of objects: |
| 19 | |
| 20 | {"call":"<key>", "tool":"fetch", "args":{...}} a tools/call |
| 21 | {"call":"<key>", "method":"tools/list"} a raw method |
| 22 | {"call":"<key>", "raw":"<literal line>"} a raw stdout line |
| 23 | (parse-error paths) |
| 24 | |
| 25 | `"args"` values are sent verbatim, so a call can pass a string where an int is |
| 26 | expected, an empty args object, or no args at all. |
| 27 | """ |
| 28 | |
| 29 | import json |
| 30 | import os |
| 31 | import subprocess |
| 32 | import sys |
| 33 | |
| 34 | PROTO = "2024-11-05" |
| 35 | |
| 36 | |
| 37 | def main(): |
| 38 | if len(sys.argv) < 3: |
| 39 | print("usage: mcp.py <binary> <calls.json> [KEY=VALUE ...]", file=sys.stderr) |
| 40 | return 2 |
| 41 | binary, calls_path = sys.argv[1], sys.argv[2] |
| 42 | env = dict(os.environ) |
| 43 | for kv in sys.argv[3:]: |
| 44 | if "=" in kv: |
| 45 | k, v = kv.split("=", 1) |
| 46 | env[k] = v |
| 47 | |
| 48 | with open(calls_path, "r", encoding="utf-8") as f: |
| 49 | calls = json.load(f) |
| 50 | |
| 51 | frames = [ |
| 52 | {"jsonrpc": "2.0", "id": 1, "method": "initialize", |
| 53 | "params": {"protocolVersion": PROTO, "capabilities": {}, |
| 54 | "clientInfo": {"name": "plugin_fetch-tests", "version": "1"}}}, |
| 55 | {"jsonrpc": "2.0", "method": "notifications/initialized"}, |
| 56 | ] |
| 57 | keys = [] |
| 58 | for i, c in enumerate(calls, start=2): |
| 59 | if "raw" in c: |
| 60 | frames.append(c["raw"]) |
| 61 | keys.append((c.get("call", "raw%d" % i), |
| 62 | i if "id" in str(c["raw"]) else None)) |
| 63 | continue |
| 64 | if "method" in c: |
| 65 | frames.append({"jsonrpc": "2.0", "id": i, "method": c["method"], |
| 66 | "params": c.get("params", {})}) |
| 67 | else: |
| 68 | frames.append({"jsonrpc": "2.0", "id": i, "method": "tools/call", |
| 69 | "params": {"name": c.get("tool", "fetch"), |
| 70 | "arguments": c.get("args", {})}}) |
| 71 | keys.append((c.get("call", c.get("tool", "call%d" % i)), i)) |
| 72 | |
| 73 | stdin_data = "\n".join( |
| 74 | f if isinstance(f, str) else json.dumps(f) for f in frames) + "\n" |
| 75 | |
| 76 | try: |
| 77 | proc = subprocess.run([binary, "--mcp"], input=stdin_data, |
| 78 | capture_output=True, text=True, env=env, |
| 79 | timeout=180) |
| 80 | except subprocess.TimeoutExpired: |
| 81 | print("_timeout\tinfo\tthe connector did not finish") |
| 82 | return 1 |
| 83 | |
| 84 | by_id, unparsed = {}, [] |
| 85 | for line in proc.stdout.splitlines(): |
| 86 | line = line.strip() |
| 87 | if not line: |
| 88 | continue |
| 89 | try: |
| 90 | d = json.loads(line) |
| 91 | except ValueError: |
| 92 | unparsed.append(line) |
| 93 | continue |
| 94 | if "id" in d: |
| 95 | by_id[d["id"]] = d |
| 96 | |
| 97 | for key, ident in keys: |
| 98 | if ident is None: |
| 99 | continue |
| 100 | d = by_id.get(ident) |
| 101 | if d is None: |
| 102 | print("%s\tmissing\t(no response)" % key) |
| 103 | continue |
| 104 | if "error" in d: |
| 105 | print("%s\trpcerr\t%s" % (key, json.dumps(d["error"]))) |
| 106 | continue |
| 107 | res = d.get("result", {}) |
| 108 | if "content" in res: |
| 109 | text = "".join(c.get("text", "") for c in res.get("content", [])) |
| 110 | # one call must be one line so awk -F'\t' can pick it out: real |
| 111 | # newlines in the fetched text become literal \n sequences. |
| 112 | text = text.replace("\\", "\\\\").replace("\n", "\\n") |
| 113 | print("%s\t%s\t%s" % (key, "err" if res.get("isError") else "ok", text)) |
| 114 | else: |
| 115 | print("%s\tok\t%s" % (key, json.dumps(res))) |
| 116 | |
| 117 | if unparsed: |
| 118 | print("_unparsed\tinfo\t%s" % " | ".join(unparsed)[:400]) |
| 119 | if proc.stderr: |
| 120 | print("_stderr\tinfo\t%s" % proc.stderr.strip().replace("\n", " | ")[:400]) |
| 121 | return 0 |
| 122 | |
| 123 | |
| 124 | if __name__ == "__main__": |
| 125 | sys.exit(main()) |