Skip to content
refs
History
99 lines · 5.7 KBRaw
1import assert from "node:assert/strict";
2import { execFileSync, spawn } from "node:child_process";
3import fs from "node:fs";
4import http from "node:http";
5import net from "node:net";
6import os from "node:os";
7import path from "node:path";
8import readline from "node:readline";
9import { test } from "node:test";
10
11const CLI = new URL("../refs.mjs", import.meta.url).pathname;
12const TOKEN = "refs_agent_0123456789abcdef";
13
14function git(cwd: string, env: NodeJS.ProcessEnv, args: string[], input?: string): string {
15 return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", env, input, stdio: ["pipe", "pipe", "ignore"] });
16}
17
18test("the MCP proxy hands refs_take's token to git's credential helper, never to the model, and takes it back on release", async (t) => {
19 const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-"));
20 const clone = path.join(home, "clone");
21 const calls: Record<string, unknown>[] = [];
22 const server = http.createServer(async (request, response) => {
23 let body = "";
24 for await (const chunk of request) body += chunk;
25 if (!body) return response.writeHead(204).end();
26 const message = JSON.parse(body);
27 calls.push(message.params.arguments);
28 const refs = message.params.name === "refs_take" ? { remote, token: TOKEN } : { remote };
29 const text = message.params.arguments.credentials === "helper" ? "git in this clone already authenticates as this session." : `Bearer ${TOKEN}`;
30 response.writeHead(200, { "content-type": "application/json", "mcp-session-id": "c.claude-code" }).end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text }], _meta: { refs } } }));
31 });
32 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
33 const origin = `http://127.0.0.1:${(server.address() as net.AddressInfo).port}`;
34 const remote = `${origin}/refs/demo.git`;
35 const daemon = net.createServer((socket) => socket.end(JSON.stringify({ connected: true }) + "\n")).listen(path.join(home, "daemon.sock"));
36 t.after(() => (server.close(), daemon.close(), fs.rmSync(home, { recursive: true, force: true })));
37
38 fs.mkdirSync(path.join(home, "bin"));
39 fs.writeFileSync(path.join(home, "bin", "refs"), `#!/bin/sh\nexec "${process.execPath}" "${CLI}" "$@"\n`, { mode: 0o755 });
40 fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify({ origin, accessToken: "oauth", expiresAt: Date.now() / 1000 + 3600 }));
41 const env = { ...process.env, REFS_HOME: home, GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1" };
42 fs.mkdirSync(clone);
43 git(clone, env, ["init", "-q"]);
44 git(clone, env, ["remote", "add", "origin", remote]);
45 git(clone, env, ["config", `http.${remote}.extraHeader`, `Authorization: Bearer refs_agent_stale`]);
46
47 const proxy = spawn(process.execPath, [CLI, "mcp"], { cwd: clone, env, stdio: ["pipe", "pipe", "inherit"] });
48 t.after(() => proxy.kill());
49 const answers = readline.createInterface({ input: proxy.stdout! })[Symbol.asyncIterator]();
50 const call = async (id: number, name: string, args: Record<string, unknown>) => {
51 proxy.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }) + "\n");
52 return (await answers.next()).value as string;
53 };
54 const fill = () => git(clone, env, ["credential", "fill"], `url=${remote}\n\n`);
55
56 const taken = await call(1, "refs_take", { task: 7 });
57 assert.doesNotMatch(taken, /refs_agent_/);
58 assert.equal(calls[0].credentials, "helper");
59 assert.equal((fs.statSync(path.join(home, "git-tokens.json")).mode & 0o777).toString(8), "600");
60 assert.throws(() => git(clone, env, ["config", "--get-all", `http.${remote}.extraHeader`]));
61 assert.match(fill(), new RegExp(`username=x-token\npassword=${TOKEN}\n`));
62
63 const released = await call(2, "refs_release", {});
64 assert.doesNotMatch(released, /"refs"/);
65 assert.throws(() => git(clone, env, ["config", "--get-all", `credential.${remote}.helper`]));
66 assert.deepEqual(JSON.parse(fs.readFileSync(path.join(home, "git-tokens.json"), "utf8")), {});
67
68});
69
70test("outside a refs clone, the MCP server answers on its own, offers no tools and never calls refs", async (t) => {
71 const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-"));
72 t.after(() => fs.rmSync(home, { recursive: true, force: true }));
73 const project = path.join(home, "project");
74 fs.mkdirSync(project);
75 const env = { ...process.env, REFS_HOME: home, GIT_CONFIG_NOSYSTEM: "1" };
76 git(project, env, ["init", "-q"]);
77 git(project, env, ["remote", "add", "origin", "https://github.com/someone/project.git"]);
78
79 for (const credentials of [null, { origin: "http://127.0.0.1:9", accessToken: "expired", expiresAt: 0 }]) {
80 if (credentials) fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify(credentials));
81 const messages = [
82 { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } },
83 { jsonrpc: "2.0", method: "notifications/initialized" },
84 { jsonrpc: "2.0", id: 2, method: "tools/list" },
85 { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "refs_events", arguments: { event: "UserPromptSubmit" } } },
86 ];
87 const output = execFileSync(process.execPath, [CLI, "mcp"], { cwd: project, env, input: messages.map((message) => JSON.stringify(message)).join("\n") + "\n", encoding: "utf8", timeout: 5000 });
88 const answers = output.trim().split("\n").map((line) => JSON.parse(line));
89 assert.deepEqual(
90 answers.map((answer) => [answer.id, answer.result]),
91 [
92 [1, { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "refs", version: "0.1.0" } }],
93 [2, { tools: [] }],
94 [3, { content: [] }],
95 ],
96 );
97 assert.equal(fs.existsSync(path.join(home, "daemon.log")), false);
98 }
99});