| 1 | #!/usr/bin/env python3 |
| 2 | """tests/mcp.py - drive plugin_github --mcp over stdio against the mock. |
| 3 | |
| 4 | Spawns the binary with GITHUB_API_BASE pointed at tests/mockapi.py, speaks |
| 5 | line-delimited JSON-RPC 2.0, and checks both the REPLIES and - through the |
| 6 | mock's request log - the exact bytes of every HTTP request the tools built: |
| 7 | method, path, query, credential header and POST body. A reply-only check |
| 8 | cannot see a wrong path, a dropped query parameter or a missing Bearer token; |
| 9 | this can. |
| 10 | |
| 11 | Run from tests/run.sh (it passes BIN/PORT/LOG/CFGDIR via env): |
| 12 | BIN=./plugin_github MCPBIN=./plugin_github-asan PORT=1234 \ |
| 13 | LOG=/tmp/req.jsonl CFGDIR=/tmp/cfg python3 tests/mcp.py |
| 14 | """ |
| 15 | |
| 16 | import json |
| 17 | import os |
| 18 | import subprocess |
| 19 | import sys |
| 20 | |
| 21 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 22 | BIN = os.environ.get("BIN", os.path.join(ROOT, "plugin_github")) |
| 23 | PORT = os.environ["PORT"] |
| 24 | LOG = os.environ["LOG"] |
| 25 | CFGDIR = os.environ["CFGDIR"] |
| 26 | TOKEN = "GHPAT-MOCK-TOKEN-1" |
| 27 | BAD_TOKEN = "WRONG" |
| 28 | FLAKY_TOKEN = "GHPAT-MOCK-RETRY-1" |
| 29 | |
| 30 | PASS = 0 |
| 31 | FAILS = [] |
| 32 | |
| 33 | |
| 34 | def ok(desc, detail=""): |
| 35 | global PASS |
| 36 | PASS += 1 |
| 37 | print(" ok %s" % desc) |
| 38 | |
| 39 | |
| 40 | def bad(desc, detail=""): |
| 41 | FAILS.append(desc) |
| 42 | print(" FAIL %s%s" % (desc, (" (" + str(detail)[:240] + ")") if detail else "")) |
| 43 | |
| 44 | |
| 45 | def check(cond, desc, detail=""): |
| 46 | (ok if cond else bad)(desc, detail) |
| 47 | |
| 48 | |
| 49 | class Mcp: |
| 50 | """One MCP child process; call() sends a request and returns the reply.""" |
| 51 | |
| 52 | def __init__(self, token=None, base=None, binpath=None): |
| 53 | env = dict(os.environ) |
| 54 | env["SX_CONNECTOR_DIR"] = CFGDIR |
| 55 | env["GITHUB_API_BASE"] = base or ("http://127.0.0.1:%s" % PORT) |
| 56 | if token: |
| 57 | env["GITHUB_TOKEN"] = token |
| 58 | else: |
| 59 | env.pop("GITHUB_TOKEN", None) |
| 60 | self.p = subprocess.Popen([binpath or BIN, "--mcp"], |
| 61 | stdin=subprocess.PIPE, stdout=subprocess.PIPE, |
| 62 | env=env, text=True) |
| 63 | self.n = 0 |
| 64 | |
| 65 | def raw(self, obj): |
| 66 | self.p.stdin.write(json.dumps(obj) + "\n") |
| 67 | self.p.stdin.flush() |
| 68 | |
| 69 | def call(self, method, params=None, want_reply=True): |
| 70 | self.n += 1 |
| 71 | msg = {"jsonrpc": "2.0", "id": self.n, "method": method} |
| 72 | if params is not None: |
| 73 | msg["params"] = params |
| 74 | self.raw(msg) |
| 75 | if not want_reply: |
| 76 | return None |
| 77 | line = self.p.stdout.readline() |
| 78 | if not line: |
| 79 | raise RuntimeError("mcp child closed the pipe") |
| 80 | return json.loads(line) |
| 81 | |
| 82 | def tool(self, name, arguments): |
| 83 | r = self.call("tools/call", {"name": name, "arguments": arguments}) |
| 84 | res = r.get("result", {}) |
| 85 | text = "" |
| 86 | if res.get("content"): |
| 87 | text = res["content"][0].get("text", "") |
| 88 | return bool(res.get("isError")), text |
| 89 | |
| 90 | def close(self): |
| 91 | try: |
| 92 | self.p.stdin.close() |
| 93 | except Exception: |
| 94 | pass |
| 95 | self.p.wait(timeout=10) |
| 96 | |
| 97 | |
| 98 | def log_since(pos): |
| 99 | """Every mock request recorded since byte offset `pos`.""" |
| 100 | with open(LOG) as f: |
| 101 | f.seek(pos) |
| 102 | return [json.loads(l) for l in f if l.strip()] |
| 103 | |
| 104 | |
| 105 | def log_pos(): |
| 106 | return os.path.getsize(LOG) if os.path.exists(LOG) else 0 |
| 107 | |
| 108 | |
| 109 | def main(): |
| 110 | # every test's env comes through the Mcp constructor, never a config file, |
| 111 | # so the config-path tests stay separate from the request-shape tests |
| 112 | m = Mcp(token=TOKEN) |
| 113 | |
| 114 | init = m.call("initialize", {"protocolVersion": "2024-11-05", |
| 115 | "capabilities": {}, |
| 116 | "clientInfo": {"name": "suite", "version": "1"}}) |
| 117 | check(init["result"]["serverInfo"]["name"] == "plugin_github", |
| 118 | "initialize names the server plugin_github") |
| 119 | |
| 120 | m.raw({"jsonrpc": "2.0", "method": "notifications/initialized"}) |
| 121 | ping = m.call("ping") |
| 122 | check("result" in ping, "ping answers a result") |
| 123 | |
| 124 | tl = m.call("tools/list") |
| 125 | tools = {t["name"]: t for t in tl["result"]["tools"]} |
| 126 | want = {"github_get_repo", "github_list_issues", "github_create_issue", |
| 127 | "github_get_pull_request", "github_search_code"} |
| 128 | check(set(tools) == want, "tools/list is exactly the five spec tools", |
| 129 | sorted(tools)) |
| 130 | for name in want: |
| 131 | check("inputSchema" in tools[name] and tools[name]["description"], |
| 132 | "%s carries description + inputSchema" % name) |
| 133 | req = tools["github_create_issue"]["inputSchema"].get("required", []) |
| 134 | check(set(req) == {"owner", "repo", "title"}, |
| 135 | "github_create_issue required = owner,repo,title", req) |
| 136 | |
| 137 | # ---- 1. github_get_repo: request shape + reply + 404 ---- |
| 138 | pos = log_pos() |
| 139 | is_err, text = m.tool("github_get_repo", {"owner": "octocat", "repo": "mocked"}) |
| 140 | reqs = log_since(pos) |
| 141 | check(len(reqs) == 1 and reqs[0]["method"] == "GET" |
| 142 | and reqs[0]["path"] == "/repos/octocat/mocked", |
| 143 | "get_repo GETs exactly /repos/octocat/mocked", |
| 144 | reqs and (reqs[0]["method"], reqs[0].get("path"))) |
| 145 | check(reqs and reqs[0]["auth"] == "Bearer " + TOKEN, |
| 146 | "get_repo sends Authorization: Bearer <token>", reqs and reqs[0]["auth"]) |
| 147 | check(reqs and reqs[0]["api_version"] == "2022-11-28", |
| 148 | "get_repo pins X-GitHub-Api-Version 2022-11-28") |
| 149 | check(not is_err and "full_name: octocat/mocked" in text |
| 150 | and "stars: 1234" in text and "license: MIT" in text, |
| 151 | "get_repo reply carries the shaped fields", text[:120]) |
| 152 | check("quotes" in text, "a description with quotes/newlines survives intact") |
| 153 | |
| 154 | is_err, text = m.tool("github_get_repo", {"owner": "octocat", "repo": "nope"}) |
| 155 | check(is_err and "404" in text and "Not Found" in text, |
| 156 | "get_repo relays GitHub's own 404 message", text[:120]) |
| 157 | |
| 158 | is_err, text = m.tool("github_get_repo", {"owner": "octocat"}) |
| 159 | check(is_err and "repo" in text, |
| 160 | "get_repo missing repo names the missing argument", text[:120]) |
| 161 | |
| 162 | is_err, text = m.tool("github_get_repo", {"owner": "evil owner", "repo": "x"}) |
| 163 | check(is_err and "not allowed" in text.lower(), |
| 164 | "a name with spaces/control-shaped chars is refused before any socket", |
| 165 | text[:120]) |
| 166 | |
| 167 | # ---- 2. github_list_issues: query + PR filter + ctrl sanitising ---- |
| 168 | pos = log_pos() |
| 169 | is_err, text = m.tool("github_list_issues", |
| 170 | {"owner": "octocat", "repo": "mocked", "state": "open"}) |
| 171 | reqs = log_since(pos) |
| 172 | q = reqs[0]["query"] if reqs else {} |
| 173 | check(reqs and reqs[0]["path"] == "/repos/octocat/mocked/issues" |
| 174 | and q.get("state") == "open", |
| 175 | "list_issues GETs /issues?state=open", q) |
| 176 | check(not is_err and "#12" in text and "Buffer overflow in parser" in text, |
| 177 | "list_issues renders issue rows") |
| 178 | check("FILTERED" not in text, |
| 179 | "the pull_request entry is filtered out of the issues list") |
| 180 | check("\x01" not in text and "Docs TAB and ctrl chars" in text, |
| 181 | "title control bytes sanitised to spaces, row shape kept", repr(text[:200])) |
| 182 | |
| 183 | pos = log_pos() |
| 184 | is_err, text = m.tool("github_list_issues", |
| 185 | {"owner": "octocat", "repo": "mocked", "state": "bogus"}) |
| 186 | check(is_err and "state must be" in text and log_pos() == pos, |
| 187 | "an invalid state is refused client-side (no request sent)") |
| 188 | |
| 189 | # ---- 3. github_create_issue: the POST body on the wire ---- |
| 190 | pos = log_pos() |
| 191 | is_err, text = m.tool("github_create_issue", |
| 192 | {"owner": "octocat", "repo": "mocked", |
| 193 | "title": 'Quote " and \\ backslash', |
| 194 | "body": "line1\nline2\ttab"}) |
| 195 | reqs = log_since(pos) |
| 196 | b = reqs[0]["body"] if reqs else None |
| 197 | check(reqs and reqs[0]["method"] == "POST" |
| 198 | and reqs[0]["path"] == "/repos/octocat/mocked/issues", |
| 199 | "create_issue POSTs to /issues", reqs and reqs[0].get("path")) |
| 200 | check(b and b.get("title") == 'Quote " and \\ backslash' |
| 201 | and b.get("body") == "line1\nline2\ttab", |
| 202 | "the JSON body on the wire is the exact title/body, escaped right", |
| 203 | b) |
| 204 | check(not is_err and "#4221" in text, "create_issue reports the new number") |
| 205 | |
| 206 | # ---- 4. github_get_pull_request ---- |
| 207 | pos = log_pos() |
| 208 | is_err, text = m.tool("github_get_pull_request", |
| 209 | {"owner": "octocat", "repo": "mocked", "number": 7}) |
| 210 | reqs = log_since(pos) |
| 211 | check(reqs and reqs[0]["path"] == "/repos/octocat/mocked/pulls/7", |
| 212 | "get_pull_request GETs /pulls/7", reqs and reqs[0].get("path")) |
| 213 | check(not is_err and "author: mockuser" in text and "head: octocat:feature" in text |
| 214 | and "commits: 3" in text, "PR reply shaped from nested user/head", text[:200]) |
| 215 | |
| 216 | is_err, text = m.tool("github_get_pull_request", |
| 217 | {"owner": "o", "repo": "r", "number": "not-a-number"}) |
| 218 | check(is_err and "number" in text.lower(), "a non-numeric number is refused") |
| 219 | |
| 220 | # ---- 5. github_search_code: the query is percent-encoded ---- |
| 221 | pos = log_pos() |
| 222 | is_err, text = m.tool("github_search_code", |
| 223 | {"query": 'class:"My Class" repo:a/b language:c++'}) |
| 224 | reqs = log_since(pos) |
| 225 | q = reqs[0]["query"] if reqs else {} |
| 226 | check(reqs and reqs[0]["path"] == "/search/code" |
| 227 | and q.get("q") == 'class:"My Class" repo:a/b language:c++', |
| 228 | "search_code sends the query intact through the encoder", q) |
| 229 | check(not is_err and "total_count: 137" in text |
| 230 | and "src/thing.c @ acme/widgets" in text, |
| 231 | "search results shaped: path @ repo", text[:200]) |
| 232 | |
| 233 | # ---- 6. credential absence + wrong credential ---- |
| 234 | m.close() |
| 235 | m0 = Mcp() # no token at all |
| 236 | is_err, text = m0.tool("github_create_issue", |
| 237 | {"owner": "octocat", "repo": "mocked", "title": "x"}) |
| 238 | check(is_err and "no credential" in text, |
| 239 | "create_issue without a token explains the fix, not a crash", text[:140]) |
| 240 | is_err, text = m0.tool("github_get_repo", {"owner": "octocat", "repo": "mocked"}) |
| 241 | check(not is_err, "public reads work with no token at all") |
| 242 | m0.close() |
| 243 | |
| 244 | mb = Mcp(token=BAD_TOKEN) |
| 245 | is_err, text = mb.tool("github_create_issue", |
| 246 | {"owner": "octocat", "repo": "mocked", "title": "x"}) |
| 247 | check(is_err and "Bad credentials" in text, |
| 248 | "a wrong token is refused with GitHub's own message relayed", text[:140]) |
| 249 | mb.close() |
| 250 | |
| 251 | # ---- 7. honest retry: first 503 + Retry-After, then success ---- |
| 252 | # reset the mock's flaky counter so "the first request" is a fact of THIS |
| 253 | # run, not of whichever pass used the mock before us |
| 254 | try: |
| 255 | import urllib.request |
| 256 | urllib.request.urlopen("http://127.0.0.1:%s/__reset" % PORT, timeout=5).read() |
| 257 | except Exception as exc: # never let a reset failure look like a plugin bug |
| 258 | print(" note: mock reset skipped (%s)" % exc) |
| 259 | pos = log_pos() |
| 260 | mf = Mcp(token=FLAKY_TOKEN) |
| 261 | is_err, text = mf.tool("github_get_repo", {"owner": "octocat", "repo": "mocked"}) |
| 262 | check(not is_err, "the flaky-token run completes normally") |
| 263 | reqs = [r for r in log_since(pos) if r["path"] == "/repos/octocat/mocked"] |
| 264 | check(len(reqs) == 2, "a 503/Retry-After is retried exactly once (2 requests)", |
| 265 | len(reqs)) |
| 266 | mf.close() |
| 267 | |
| 268 | # ---- 8. unknown method / malformed args ---- |
| 269 | m2 = Mcp(token=TOKEN) |
| 270 | r = m2.call("tools/nope") |
| 271 | check(r.get("error", {}).get("code") == -32601, |
| 272 | "an unknown method is JSON-RPC method-not-found") |
| 273 | is_err, text = m2.tool("github_get_repo", "not-an-object-should-not-happen") |
| 274 | # servers must survive malformed input regardless |
| 275 | check(True, "malformed arguments do not crash the server") |
| 276 | m2.raw({"jsonrpc": "2.0", "id": 999, "method": "tools/call", |
| 277 | "params": {"name": "github_get_repo", |
| 278 | "arguments": {"owner": "octocat", "repo": "mocked"}}}) |
| 279 | r = json.loads(m2.p.stdout.readline()) |
| 280 | check(r.get("id") == 999, "the id survives an interleaved raw request") |
| 281 | m2.close() |
| 282 | |
| 283 | print("mcp.py: %d passed, %d failed" % (PASS, len(FAILS))) |
| 284 | return 1 if FAILS else 0 |
| 285 | |
| 286 | |
| 287 | if __name__ == "__main__": |
| 288 | sys.exit(main()) |