Repository navigation
Expand file tree
/
Copy pathmcp.ts
More file actions
357 lines (338 loc) · 16 KB
/
Copy pathmcp.ts
File metadata and controls
357 lines (338 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env node
import { execFile } from "node:child_process";
import { dirname, join, resolve } from "node:path";
import { StringDecoder } from "node:string_decoder";
import { agentChangedFiles, agentScopedSelection, agentSelection, selectionInstruction } from "./agent-selection.js";
import { requireDiffciPackageIdentity } from "./package-identity.js";
type JsonRpcId = string | number | null;
interface JsonRpcRequest {
jsonrpc?: string;
id?: JsonRpcId;
method?: string;
params?: unknown;
}
interface ToolCallParams {
name?: string;
arguments?: Record<string, unknown>;
}
const SERVER_INFO = { name: "diffci-mcp", version: requireDiffciPackageIdentity().version };
const tools = [
...["diffci_changed_files", "diffci_select_tests", "diffci_explain_selection", "diffci_run_affected_tests"].map((name) => ({
name,
description: name === "diffci_run_affected_tests"
? "Reanalyze and verify the current working-tree snapshot with affected tests or conservative full fallback. Required CI remains authoritative."
: name === "diffci_changed_files"
? "List staged, unstaged and non-ignored untracked changed paths relative to HEAD, with a snapshot identity. Builds no dependency graph and runs no tests."
: "Inspect current staged, unstaged and non-ignored untracked changes and return a snapshot-bound affected-test plan and fallback reasons. Runs no tests; a plan is not a passing receipt. With scope \"staged\" or \"paths\", plans HEAD plus only the index or only the given files in a temporary worktree, and returns the one `diffci verify --staged`/`--paths` command to run; use it before a commit when other sessions share the checkout.",
inputSchema: {
type: "object",
properties: {
repo: { type: "string", description: "Absolute repository path; defaults to server working directory. Always pass the edited repository when using a plugin." },
...(name === "diffci_run_affected_tests" ? { timeoutMs: { type: "number", minimum: 0 } } : {}),
...(name === "diffci_select_tests" || name === "diffci_explain_selection" ? {
scope: { type: "string", enum: ["working-tree", "staged", "paths"], description: "working-tree (default): every uncommitted change. staged: HEAD plus the index only. paths: HEAD plus only `paths`." },
paths: { type: "array", items: { type: "string" }, description: "Repository-relative files for scope \"paths\"." },
} : {}),
},
additionalProperties: false,
},
annotations: { readOnlyHint: name !== "diffci_run_affected_tests", openWorldHint: false },
})),
{
name: "diffci_verify",
description: "Verify a clean commit range and return a receipt bound to the checked-out head commit. Resolves the CI event range automatically when base and head are omitted.",
inputSchema: {
type: "object",
properties: {
repo: { type: "string", description: "Repository path. Defaults to the MCP server working directory." },
base: { type: "string", description: "Optional base commit SHA. Must be paired with head." },
head: { type: "string", description: "Optional head commit SHA. Must be paired with base and match checked-out HEAD." },
timeoutMs: { type: "number", description: "Maximum verification-command runtime in milliseconds." },
redactPaths: { type: "boolean", description: "Replace paths with stable digests in analysis." },
},
additionalProperties: false,
},
},
{
name: "diffci_verify_changed",
description: "Verify the current staged, unstaged, and non-ignored untracked changes. Fails closed unless the exact working-tree snapshot passes selected or full fallback verification.",
inputSchema: {
type: "object",
properties: {
repo: { type: "string", description: "Repository path. Defaults to the MCP server working directory." },
timeoutMs: { type: "number", description: "Maximum verification-command runtime in milliseconds." },
redactPaths: { type: "boolean", description: "Replace paths with stable digests in analysis." },
},
additionalProperties: false,
},
},
{
name: "diffci_check",
description: "Analyze the repository, run inferred full and selected test commands when available, and report paired runtime. No report is uploaded. The run is counted with the repository name unless the user chose count-only; DO_NOT_TRACK=1 stops counting.",
inputSchema: {
type: "object",
properties: {
repo: { type: "string", description: "Repository path. Defaults to the MCP server working directory." },
base: { type: "string", description: "Optional base commit SHA." },
head: { type: "string", description: "Optional head commit SHA." },
json: { type: "boolean", description: "Print the full JSON observation report." },
quiet: { type: "boolean", description: "Suppress the human summary." },
redactPaths: { type: "boolean", description: "Replace paths in the analysis result with stable digests. Workflow findings and some fallback details can still name files." },
},
additionalProperties: false,
},
},
{
name: "diffci_init",
description: "Seed a repository with DiffCI agent instruction files, MCP server configs, the diffci-verify skill and the pre-push hook.",
inputSchema: {
type: "object",
properties: {
repo: { type: "string", description: "Repository path. Defaults to the MCP server working directory." },
workflow: { type: "boolean", description: "Also add the non-blocking GitHub Actions observer workflow." },
verificationWorkflow: { type: "boolean", description: "Also add the blocking GitHub Actions verification workflow." },
hook: { type: "boolean", description: "Install the Git pre-push hook that verifies the commits being pushed (default true)." },
mcp: { type: "boolean", description: "Register the DiffCI MCP server in .mcp.json and .cursor/mcp.json (default true)." },
skill: { type: "boolean", description: "Add the diffci-verify skill to .claude/skills (default true)." },
force: { type: "boolean", description: "Overwrite existing instruction files." },
},
additionalProperties: false,
},
},
{
name: "diffci_verify_workflow",
description: "Check that a DiffCI GitHub Actions job cannot affect the rest of CI.",
inputSchema: {
type: "object",
properties: {
repo: { type: "string", description: "Repository path. Defaults to the MCP server working directory." },
},
additionalProperties: false,
},
},
];
function cliPath(): string {
return join(dirname(import.meta.filename), "cli.js");
}
function stringArg(args: Record<string, unknown>, name: string): string | undefined {
const value = args[name];
return typeof value === "string" && value.trim() !== "" ? value : undefined;
}
function booleanArg(args: Record<string, unknown>, name: string): boolean {
return args[name] === true;
}
function commandForTool(name: string, args: Record<string, unknown>): string[] {
const repo = stringArg(args, "repo");
switch (name) {
case "diffci_verify": {
const command = ["verify", "--json"];
if (repo) command.push("--repo", resolve(repo));
for (const flag of ["base", "head"]) {
const value = stringArg(args, flag);
if (value) command.push(`--${flag}`, value);
}
const timeoutMs = args.timeoutMs;
if (typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs >= 0) command.push("--timeout-ms", String(timeoutMs));
if (booleanArg(args, "redactPaths")) command.push("--redact-paths");
return command;
}
case "diffci_run_affected_tests":
case "diffci_verify_changed": {
const command = ["verify", "--changed", "--json"];
if (repo) command.push("--repo", resolve(repo));
const timeoutMs = args.timeoutMs;
if (typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs >= 0) command.push("--timeout-ms", String(timeoutMs));
if (booleanArg(args, "redactPaths")) command.push("--redact-paths");
return command;
}
case "diffci_check": {
const command = ["check"];
if (repo) command.push("--repo", resolve(repo));
for (const flag of ["base", "head"]) {
const value = stringArg(args, flag);
if (value) command.push(`--${flag}`, value);
}
if (booleanArg(args, "json")) command.push("--json");
if (booleanArg(args, "quiet")) command.push("--quiet");
if (booleanArg(args, "redactPaths")) command.push("--redact-paths");
return command;
}
case "diffci_init": {
const command = ["init"];
if (repo) command.push("--repo", resolve(repo));
if (booleanArg(args, "workflow")) command.push("--workflow");
if (booleanArg(args, "verificationWorkflow")) command.push("--verification-workflow");
if (args.hook === false) command.push("--no-hook");
if (args.mcp === false) command.push("--no-mcp");
if (args.skill === false) command.push("--no-skill");
if (booleanArg(args, "force")) command.push("--force");
return command;
}
case "diffci_verify_workflow": {
const command = ["verify-workflow"];
if (repo) command.push("--repo", resolve(repo));
return command;
}
default:
throw new Error(`unknown tool: ${name}`);
}
}
function runCli(args: string[]): Promise<{ exitCode: number; stdout: string; stderr: string }> {
return new Promise((resolveRun) => {
execFile(process.execPath, [cliPath(), ...args], {
cwd: process.cwd(),
env: { ...process.env, DIFFCI_MCP: "1" },
encoding: "utf8",
maxBuffer: 8 * 1024 * 1024,
windowsHide: true,
}, (error, stdout, stderr) => {
const code = (error as NodeJS.ErrnoException | null)?.code;
const exitCode = typeof code === "number" ? code : error ? 1 : 0;
resolveRun({ exitCode, stdout, stderr });
});
});
}
function writeMessage(message: unknown): void {
const body = JSON.stringify(message);
process.stdout.write(lineTransport ? `${body}\n` : `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`);
}
function success(id: JsonRpcId | undefined, result: unknown): void {
if (id === undefined) return;
writeMessage({ jsonrpc: "2.0", id, result });
}
function failure(id: JsonRpcId | undefined, code: number, message: string): void {
if (id === undefined) return;
writeMessage({ jsonrpc: "2.0", id, error: { code, message } });
}
async function handle(request: JsonRpcRequest): Promise<void> {
const id = request.id;
switch (request.method) {
case "initialize":
success(id, {
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: SERVER_INFO,
});
return;
case "notifications/initialized":
return;
// Either side may ping at any time, before or after initialization; the answer is an empty result.
case "ping":
success(id, {});
return;
case "tools/list":
success(id, { tools });
return;
case "tools/call": {
const params = request.params as ToolCallParams | undefined;
if (!params?.name) {
failure(id, -32602, "tools/call requires params.name");
return;
}
const args = params.arguments ?? {};
const tool = tools.find((entry) => entry.name === params.name);
if (!tool || !args || typeof args !== "object" || Array.isArray(args)) {
failure(id, -32602, "unknown tool or invalid arguments");
return;
}
const properties = tool.inputSchema.properties;
for (const [key, value] of Object.entries(args)) {
const property = properties[key as keyof typeof properties] as { type: string; enum?: string[] } | undefined;
const typed = property?.type === "array"
? Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim() !== "")
: property !== undefined && typeof value === property.type && (!property.enum || property.enum.includes(value as string));
if (!typed || (key === "timeoutMs" && (!Number.isFinite(value) || (value as number) < 0))) {
failure(id, -32602, `invalid argument: ${key}`);
return;
}
}
if (["diffci_changed_files", "diffci_select_tests", "diffci_explain_selection"].includes(params.name)) {
const repo = stringArg(args, "repo") ?? process.cwd();
if (params.name === "diffci_changed_files") {
const changes = agentChangedFiles(repo);
success(id, { content: [{ type: "text", text: JSON.stringify(changes) }], structuredContent: changes, isError: changes.status === "blocked" });
return;
}
const scope = stringArg(args, "scope") ?? "working-tree";
const paths = Array.isArray(args.paths) ? (args.paths as string[]) : undefined;
if ((scope === "paths") !== (paths !== undefined && paths.length > 0)) {
failure(id, -32602, scope === "paths" ? "scope \"paths\" needs a non-empty paths array" : "paths applies only to scope \"paths\"");
return;
}
const plan = scope === "staged" ? await agentScopedSelection(repo, { kind: "staged" })
: scope === "paths" ? await agentScopedSelection(repo, { kind: "paths", paths: paths!.map((path) => path.replace(/\\/g, "/")) })
: await agentSelection(repo);
success(id, { content: [{ type: "text", text: `${selectionInstruction(plan)}\n\n${JSON.stringify(plan)}` }], structuredContent: plan, isError: plan.status === "blocked" });
return;
}
const run = await runCli(commandForTool(params.name, args));
const text = [
run.stdout.trim(),
run.stderr.trim() ? `stderr:\n${run.stderr.trim()}` : "",
`exitCode: ${run.exitCode}`,
].filter(Boolean).join("\n\n");
let structuredContent: unknown;
if (["diffci_verify", "diffci_verify_changed", "diffci_run_affected_tests"].includes(params.name) && run.stdout.trim()) {
try { structuredContent = JSON.parse(run.stdout); }
catch { /* The text and non-zero status still carry the failure. */ }
}
success(id, {
content: [{ type: "text", text }],
isError: run.exitCode !== 0,
structuredContent,
});
return;
}
default:
failure(id, -32601, `unknown method: ${request.method ?? ""}`);
}
}
let buffer = Buffer.alloc(0);
let lineTransport = false;
const decoder = new StringDecoder("utf8");
function readMessages(): void {
while (true) {
while (buffer.length && [9, 10, 13, 32].includes(buffer[0]!)) buffer = buffer.subarray(1);
if (buffer.length === 0) return;
if (buffer[0] === 123 || buffer[0] === 91 || lineTransport) {
lineTransport = true;
const end = buffer.indexOf("\n");
if (end === -1) return;
const body = buffer.subarray(0, end).toString("utf8").trim();
buffer = buffer.subarray(end + 1);
if (body) dispatch(body);
continue;
}
const headerEnd = buffer.indexOf("\r\n\r\n");
if (headerEnd === -1) return;
const header = decoder.write(buffer.subarray(0, headerEnd));
const match = /^Content-Length:\s*(\d+)\s*$/im.exec(header);
if (!match) {
buffer = buffer.subarray(headerEnd + 4);
continue;
}
const length = Number(match[1]);
const bodyStart = headerEnd + 4;
const bodyEnd = bodyStart + length;
if (buffer.length < bodyEnd) return;
const body = buffer.subarray(bodyStart, bodyEnd).toString("utf8");
buffer = buffer.subarray(bodyEnd);
dispatch(body);
}
}
function dispatch(body: string): void {
let request: JsonRpcRequest;
try { request = JSON.parse(body) as JsonRpcRequest; }
catch { failure(null, -32700, "invalid JSON"); return; }
if (!request || typeof request !== "object" || Array.isArray(request)) {
failure(null, -32600, "invalid request"); return;
}
void handle(request).catch((error: unknown) => {
failure(request.id, -32603, error instanceof Error ? error.message : String(error));
});
}
process.stdin.on("data", (chunk: Buffer) => {
buffer = Buffer.concat([buffer, chunk]);
readMessages();
});
process.stdin.resume();