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