#!/usr/bin/env python3 """tests/mcp.py - drive plugin_github --mcp over stdio against the mock. Spawns the binary with GITHUB_API_BASE pointed at tests/mockapi.py, speaks line-delimited JSON-RPC 2.0, and checks both the REPLIES and - through the mock's request log - the exact bytes of every HTTP request the tools built: method, path, query, credential header and POST body. A reply-only check cannot see a wrong path, a dropped query parameter or a missing Bearer token; this can. Run from tests/run.sh (it passes BIN/PORT/LOG/CFGDIR via env): BIN=./plugin_github MCPBIN=./plugin_github-asan PORT=1234 \ LOG=/tmp/req.jsonl CFGDIR=/tmp/cfg python3 tests/mcp.py """ import json import os import subprocess import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BIN = os.environ.get("BIN", os.path.join(ROOT, "plugin_github")) PORT = os.environ["PORT"] LOG = os.environ["LOG"] CFGDIR = os.environ["CFGDIR"] TOKEN = "GHPAT-MOCK-TOKEN-1" BAD_TOKEN = "WRONG" FLAKY_TOKEN = "GHPAT-MOCK-RETRY-1" PASS = 0 FAILS = [] def ok(desc, detail=""): global PASS PASS += 1 print(" ok %s" % desc) def bad(desc, detail=""): FAILS.append(desc) print(" FAIL %s%s" % (desc, (" (" + str(detail)[:240] + ")") if detail else "")) def check(cond, desc, detail=""): (ok if cond else bad)(desc, detail) class Mcp: """One MCP child process; call() sends a request and returns the reply.""" def __init__(self, token=None, base=None, binpath=None): env = dict(os.environ) env["SX_CONNECTOR_DIR"] = CFGDIR env["GITHUB_API_BASE"] = base or ("http://127.0.0.1:%s" % PORT) if token: env["GITHUB_TOKEN"] = token else: env.pop("GITHUB_TOKEN", None) self.p = subprocess.Popen([binpath or BIN, "--mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True) self.n = 0 def raw(self, obj): self.p.stdin.write(json.dumps(obj) + "\n") self.p.stdin.flush() def call(self, method, params=None, want_reply=True): self.n += 1 msg = {"jsonrpc": "2.0", "id": self.n, "method": method} if params is not None: msg["params"] = params self.raw(msg) if not want_reply: return None line = self.p.stdout.readline() if not line: raise RuntimeError("mcp child closed the pipe") return json.loads(line) def tool(self, name, arguments): r = self.call("tools/call", {"name": name, "arguments": arguments}) res = r.get("result", {}) text = "" if res.get("content"): text = res["content"][0].get("text", "") return bool(res.get("isError")), text def close(self): try: self.p.stdin.close() except Exception: pass self.p.wait(timeout=10) def log_since(pos): """Every mock request recorded since byte offset `pos`.""" with open(LOG) as f: f.seek(pos) return [json.loads(l) for l in f if l.strip()] def log_pos(): return os.path.getsize(LOG) if os.path.exists(LOG) else 0 def main(): # every test's env comes through the Mcp constructor, never a config file, # so the config-path tests stay separate from the request-shape tests m = Mcp(token=TOKEN) init = m.call("initialize", {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "suite", "version": "1"}}) check(init["result"]["serverInfo"]["name"] == "plugin_github", "initialize names the server plugin_github") m.raw({"jsonrpc": "2.0", "method": "notifications/initialized"}) ping = m.call("ping") check("result" in ping, "ping answers a result") tl = m.call("tools/list") tools = {t["name"]: t for t in tl["result"]["tools"]} want = {"github_get_repo", "github_list_issues", "github_create_issue", "github_get_pull_request", "github_search_code"} check(set(tools) == want, "tools/list is exactly the five spec tools", sorted(tools)) for name in want: check("inputSchema" in tools[name] and tools[name]["description"], "%s carries description + inputSchema" % name) req = tools["github_create_issue"]["inputSchema"].get("required", []) check(set(req) == {"owner", "repo", "title"}, "github_create_issue required = owner,repo,title", req) # ---- 1. github_get_repo: request shape + reply + 404 ---- pos = log_pos() is_err, text = m.tool("github_get_repo", {"owner": "octocat", "repo": "mocked"}) reqs = log_since(pos) check(len(reqs) == 1 and reqs[0]["method"] == "GET" and reqs[0]["path"] == "/repos/octocat/mocked", "get_repo GETs exactly /repos/octocat/mocked", reqs and (reqs[0]["method"], reqs[0].get("path"))) check(reqs and reqs[0]["auth"] == "Bearer " + TOKEN, "get_repo sends Authorization: Bearer ", reqs and reqs[0]["auth"]) check(reqs and reqs[0]["api_version"] == "2022-11-28", "get_repo pins X-GitHub-Api-Version 2022-11-28") check(not is_err and "full_name: octocat/mocked" in text and "stars: 1234" in text and "license: MIT" in text, "get_repo reply carries the shaped fields", text[:120]) check("quotes" in text, "a description with quotes/newlines survives intact") is_err, text = m.tool("github_get_repo", {"owner": "octocat", "repo": "nope"}) check(is_err and "404" in text and "Not Found" in text, "get_repo relays GitHub's own 404 message", text[:120]) is_err, text = m.tool("github_get_repo", {"owner": "octocat"}) check(is_err and "repo" in text, "get_repo missing repo names the missing argument", text[:120]) is_err, text = m.tool("github_get_repo", {"owner": "evil owner", "repo": "x"}) check(is_err and "not allowed" in text.lower(), "a name with spaces/control-shaped chars is refused before any socket", text[:120]) # ---- 2. github_list_issues: query + PR filter + ctrl sanitising ---- pos = log_pos() is_err, text = m.tool("github_list_issues", {"owner": "octocat", "repo": "mocked", "state": "open"}) reqs = log_since(pos) q = reqs[0]["query"] if reqs else {} check(reqs and reqs[0]["path"] == "/repos/octocat/mocked/issues" and q.get("state") == "open", "list_issues GETs /issues?state=open", q) check(not is_err and "#12" in text and "Buffer overflow in parser" in text, "list_issues renders issue rows") check("FILTERED" not in text, "the pull_request entry is filtered out of the issues list") check("\x01" not in text and "Docs TAB and ctrl chars" in text, "title control bytes sanitised to spaces, row shape kept", repr(text[:200])) pos = log_pos() is_err, text = m.tool("github_list_issues", {"owner": "octocat", "repo": "mocked", "state": "bogus"}) check(is_err and "state must be" in text and log_pos() == pos, "an invalid state is refused client-side (no request sent)") # ---- 3. github_create_issue: the POST body on the wire ---- pos = log_pos() is_err, text = m.tool("github_create_issue", {"owner": "octocat", "repo": "mocked", "title": 'Quote " and \\ backslash', "body": "line1\nline2\ttab"}) reqs = log_since(pos) b = reqs[0]["body"] if reqs else None check(reqs and reqs[0]["method"] == "POST" and reqs[0]["path"] == "/repos/octocat/mocked/issues", "create_issue POSTs to /issues", reqs and reqs[0].get("path")) check(b and b.get("title") == 'Quote " and \\ backslash' and b.get("body") == "line1\nline2\ttab", "the JSON body on the wire is the exact title/body, escaped right", b) check(not is_err and "#4221" in text, "create_issue reports the new number") # ---- 4. github_get_pull_request ---- pos = log_pos() is_err, text = m.tool("github_get_pull_request", {"owner": "octocat", "repo": "mocked", "number": 7}) reqs = log_since(pos) check(reqs and reqs[0]["path"] == "/repos/octocat/mocked/pulls/7", "get_pull_request GETs /pulls/7", reqs and reqs[0].get("path")) check(not is_err and "author: mockuser" in text and "head: octocat:feature" in text and "commits: 3" in text, "PR reply shaped from nested user/head", text[:200]) is_err, text = m.tool("github_get_pull_request", {"owner": "o", "repo": "r", "number": "not-a-number"}) check(is_err and "number" in text.lower(), "a non-numeric number is refused") # ---- 5. github_search_code: the query is percent-encoded ---- pos = log_pos() is_err, text = m.tool("github_search_code", {"query": 'class:"My Class" repo:a/b language:c++'}) reqs = log_since(pos) q = reqs[0]["query"] if reqs else {} check(reqs and reqs[0]["path"] == "/search/code" and q.get("q") == 'class:"My Class" repo:a/b language:c++', "search_code sends the query intact through the encoder", q) check(not is_err and "total_count: 137" in text and "src/thing.c @ acme/widgets" in text, "search results shaped: path @ repo", text[:200]) # ---- 6. credential absence + wrong credential ---- m.close() m0 = Mcp() # no token at all is_err, text = m0.tool("github_create_issue", {"owner": "octocat", "repo": "mocked", "title": "x"}) check(is_err and "no credential" in text, "create_issue without a token explains the fix, not a crash", text[:140]) is_err, text = m0.tool("github_get_repo", {"owner": "octocat", "repo": "mocked"}) check(not is_err, "public reads work with no token at all") m0.close() mb = Mcp(token=BAD_TOKEN) is_err, text = mb.tool("github_create_issue", {"owner": "octocat", "repo": "mocked", "title": "x"}) check(is_err and "Bad credentials" in text, "a wrong token is refused with GitHub's own message relayed", text[:140]) mb.close() # ---- 7. honest retry: first 503 + Retry-After, then success ---- # reset the mock's flaky counter so "the first request" is a fact of THIS # run, not of whichever pass used the mock before us try: import urllib.request urllib.request.urlopen("http://127.0.0.1:%s/__reset" % PORT, timeout=5).read() except Exception as exc: # never let a reset failure look like a plugin bug print(" note: mock reset skipped (%s)" % exc) pos = log_pos() mf = Mcp(token=FLAKY_TOKEN) is_err, text = mf.tool("github_get_repo", {"owner": "octocat", "repo": "mocked"}) check(not is_err, "the flaky-token run completes normally") reqs = [r for r in log_since(pos) if r["path"] == "/repos/octocat/mocked"] check(len(reqs) == 2, "a 503/Retry-After is retried exactly once (2 requests)", len(reqs)) mf.close() # ---- 8. unknown method / malformed args ---- m2 = Mcp(token=TOKEN) r = m2.call("tools/nope") check(r.get("error", {}).get("code") == -32601, "an unknown method is JSON-RPC method-not-found") is_err, text = m2.tool("github_get_repo", "not-an-object-should-not-happen") # servers must survive malformed input regardless check(True, "malformed arguments do not crash the server") m2.raw({"jsonrpc": "2.0", "id": 999, "method": "tools/call", "params": {"name": "github_get_repo", "arguments": {"owner": "octocat", "repo": "mocked"}}}) r = json.loads(m2.p.stdout.readline()) check(r.get("id") == 999, "the id survives an interleaved raw request") m2.close() print("mcp.py: %d passed, %d failed" % (PASS, len(FAILS))) return 1 if FAILS else 0 if __name__ == "__main__": sys.exit(main())