nulladrift 0.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2752 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { parseArgs } from "util";
5
+ import { resolve as resolve3 } from "path";
6
+
7
+ // src/lib/ui.ts
8
+ var enabled = process.stdout.isTTY === true && process.env["NO_COLOR"] === void 0 && process.env["TERM"] !== "dumb";
9
+ var wrap = (code) => (text) => enabled ? `\x1B[${code}m${text}\x1B[0m` : text;
10
+ var bold = wrap(1);
11
+ var dim = wrap(2);
12
+ var red = wrap(31);
13
+ var green = wrap(32);
14
+ var yellow = wrap(33);
15
+ var blue = wrap(34);
16
+ function truncate(text, limit = 160) {
17
+ const collapsed = text.replace(/\s+/g, " ").trim();
18
+ return collapsed.length <= limit ? collapsed : `${collapsed.slice(0, limit - 1)}\u2026`;
19
+ }
20
+
21
+ // src/config/discover.ts
22
+ import { readFile as readFile2 } from "fs/promises";
23
+ import { homedir as homedir2, platform } from "os";
24
+ import { isAbsolute, join, relative, resolve as resolve2, sep } from "path";
25
+
26
+ // src/config/parsers.ts
27
+ import { readFile } from "fs/promises";
28
+ import { resolve } from "path";
29
+ import { z } from "zod";
30
+
31
+ // src/config/expand.ts
32
+ import { homedir } from "os";
33
+ var PLACEHOLDER = /\$\{([^}]+)\}/g;
34
+ function expand(input, context) {
35
+ const unresolved = [];
36
+ const value = input.replace(PLACEHOLDER, (match, body) => {
37
+ if (body === "workspaceFolder") return context.workspaceFolder;
38
+ if (body === "userHome") return homedir();
39
+ if (body === "pathSeparator" || body === "/") return "/";
40
+ if (body.startsWith("input:") || body.startsWith("command:")) {
41
+ unresolved.push(match);
42
+ return match;
43
+ }
44
+ if (body.startsWith("env:")) {
45
+ const name = body.slice(4);
46
+ const found2 = context.env[name];
47
+ if (found2 !== void 0) return found2;
48
+ unresolved.push(match);
49
+ return match;
50
+ }
51
+ const defaultAt = body.indexOf(":-");
52
+ if (defaultAt !== -1) {
53
+ const name = body.slice(0, defaultAt);
54
+ return context.env[name] ?? body.slice(defaultAt + 2);
55
+ }
56
+ const found = context.env[body];
57
+ if (found !== void 0) return found;
58
+ unresolved.push(match);
59
+ return match;
60
+ });
61
+ return { value, unresolved };
62
+ }
63
+
64
+ // src/config/parsers.ts
65
+ var serverEntrySchema = z.looseObject({
66
+ type: z.string().optional(),
67
+ command: z.string().optional(),
68
+ args: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
69
+ env: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])).optional(),
70
+ cwd: z.string().optional(),
71
+ url: z.string().optional(),
72
+ headers: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
73
+ envFile: z.string().optional(),
74
+ headersHelper: z.string().optional(),
75
+ oauth: z.looseObject({
76
+ clientId: z.string().optional(),
77
+ clientSecret: z.string().optional(),
78
+ scope: z.string().optional(),
79
+ scopes: z.array(z.string()).optional()
80
+ }).optional()
81
+ });
82
+ var UnsupportedServerError = class extends Error {
83
+ constructor(serverName, message) {
84
+ super(message);
85
+ this.serverName = serverName;
86
+ this.name = "UnsupportedServerError";
87
+ }
88
+ serverName;
89
+ };
90
+ function scalarsToStrings(record) {
91
+ const out = {};
92
+ for (const [key, value] of Object.entries(record ?? {})) {
93
+ if (value === null) continue;
94
+ out[key] = String(value);
95
+ }
96
+ return out;
97
+ }
98
+ function resolveTransport(name, entry, context) {
99
+ const unresolved = [];
100
+ const take = (input) => {
101
+ const result = expand(input, context);
102
+ unresolved.push(...result.unresolved);
103
+ return result.value;
104
+ };
105
+ const declared = entry.type === "streamable-http" ? "http" : entry.type;
106
+ if (declared === "ws") {
107
+ throw new UnsupportedServerError(name, "WebSocket transport is not supported by the MCP specification or the SDK");
108
+ }
109
+ let transport2;
110
+ if (declared === "http" || declared === "sse" || declared === void 0 && entry.url !== void 0) {
111
+ if (entry.url === void 0) throw new UnsupportedServerError(name, `transport "${declared}" needs a url`);
112
+ const oauth = entry.oauth;
113
+ transport2 = {
114
+ type: declared === "sse" ? "sse" : "http",
115
+ url: take(entry.url),
116
+ headers: Object.fromEntries(Object.entries(scalarsToStrings(entry.headers)).map(([key, value]) => [key, take(value)])),
117
+ ...oauth === void 0 ? {} : {
118
+ oauth: {
119
+ // Expanded here so a secret can live in the environment rather than the config file.
120
+ clientId: oauth.clientId === void 0 ? void 0 : take(oauth.clientId),
121
+ clientSecret: oauth.clientSecret === void 0 ? void 0 : take(oauth.clientSecret),
122
+ scope: oauth.scope ?? oauth.scopes?.join(" ")
123
+ }
124
+ }
125
+ };
126
+ } else {
127
+ if (entry.command === void 0) throw new UnsupportedServerError(name, "stdio server has no command");
128
+ transport2 = {
129
+ type: "stdio",
130
+ command: take(entry.command),
131
+ args: (entry.args ?? []).map((argument) => take(String(argument))),
132
+ env: Object.fromEntries(Object.entries(scalarsToStrings(entry.env)).map(([key, value]) => [key, take(value)])),
133
+ cwd: entry.cwd ? take(entry.cwd) : void 0
134
+ };
135
+ }
136
+ if (unresolved.length > 0) {
137
+ const names = [...new Set(unresolved)].join(", ");
138
+ throw new UnsupportedServerError(
139
+ name,
140
+ `configuration contains placeholders this tool cannot resolve: ${names}. Editor-supplied values (\${input:...}) and unset variables have to be present in the environment when the audit runs, because a server may serve a different tool list without them.`
141
+ );
142
+ }
143
+ return transport2;
144
+ }
145
+ function detectMapKey(raw) {
146
+ if (typeof raw !== "object" || raw === null) return void 0;
147
+ const record = raw;
148
+ for (const key of ["mcpServers", "servers"]) {
149
+ if (typeof record[key] === "object" && record[key] !== null) return key;
150
+ }
151
+ return void 0;
152
+ }
153
+ async function readEnvFile(path) {
154
+ const out = {};
155
+ const text = await readFile(path, "utf8");
156
+ for (const line of text.split(/\r?\n/)) {
157
+ const trimmed = line.trim();
158
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
159
+ const at = trimmed.indexOf("=");
160
+ if (at <= 0) continue;
161
+ const key = trimmed.slice(0, at).trim().replace(/^export\s+/, "");
162
+ let value = trimmed.slice(at + 1).trim();
163
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
164
+ value = value.slice(1, -1);
165
+ }
166
+ out[key] = value;
167
+ }
168
+ return out;
169
+ }
170
+ async function parseServerMap(raw, mapKey, source, context) {
171
+ const servers = [];
172
+ const skipped = [];
173
+ if (typeof raw !== "object" || raw === null) return { servers, skipped };
174
+ const map = raw[mapKey];
175
+ if (typeof map !== "object" || map === null) return { servers, skipped };
176
+ for (const [name, value] of Object.entries(map)) {
177
+ const entry = serverEntrySchema.safeParse(value);
178
+ if (!entry.success) {
179
+ skipped.push(new UnsupportedServerError(name, `entry is not a server definition: ${entry.error.issues[0]?.message ?? "unknown"}`));
180
+ continue;
181
+ }
182
+ try {
183
+ if (entry.data.headersHelper !== void 0) {
184
+ throw new UnsupportedServerError(name, "`headersHelper` runs a command to produce headers, which this tool will not execute");
185
+ }
186
+ const transport2 = resolveTransport(name, entry.data, context);
187
+ if (transport2.type === "stdio" && entry.data.envFile !== void 0) {
188
+ const expanded = expand(entry.data.envFile, context);
189
+ if (expanded.unresolved.length > 0) {
190
+ throw new UnsupportedServerError(name, `envFile path contains unresolved placeholders: ${expanded.unresolved.join(", ")}`);
191
+ }
192
+ try {
193
+ transport2.env = { ...await readEnvFile(resolve(context.workspaceFolder, expanded.value)), ...transport2.env };
194
+ } catch (error) {
195
+ throw new UnsupportedServerError(name, `envFile ${expanded.value} could not be read: ${error.message}`);
196
+ }
197
+ }
198
+ servers.push({ name, source: { ...source }, transport: transport2 });
199
+ } catch (error) {
200
+ if (error instanceof UnsupportedServerError) skipped.push(error);
201
+ else throw error;
202
+ }
203
+ }
204
+ return { servers, skipped };
205
+ }
206
+ async function parseClaudeJson(raw, projectRoot, source, context) {
207
+ const user = await parseServerMap(raw, "mcpServers", { ...source, scope: "user" }, context);
208
+ const projects = typeof raw === "object" && raw !== null ? raw["projects"] : void 0;
209
+ const forProject = typeof projects === "object" && projects !== null ? projects[projectRoot] : void 0;
210
+ const local = forProject ? await parseServerMap(forProject, "mcpServers", { ...source, scope: "local" }, context) : { servers: [], skipped: [] };
211
+ return { servers: [...user.servers, ...local.servers], skipped: [...user.skipped, ...local.skipped] };
212
+ }
213
+ var CLIENT_MAP_KEY = {
214
+ "claude-code": "mcpServers",
215
+ "claude-desktop": "mcpServers",
216
+ vscode: "servers",
217
+ cursor: "mcpServers",
218
+ copilot: "mcpServers",
219
+ windsurf: "mcpServers",
220
+ generic: "mcpServers",
221
+ manual: "mcpServers"
222
+ };
223
+
224
+ // src/config/discover.ts
225
+ function claudeDesktopPath() {
226
+ const home = homedir2();
227
+ switch (platform()) {
228
+ case "darwin":
229
+ return join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
230
+ case "win32":
231
+ return join(process.env["APPDATA"] ?? join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
232
+ default:
233
+ return join(home, ".config", "Claude", "claude_desktop_config.json");
234
+ }
235
+ }
236
+ function candidateConfigFiles(projectRoot) {
237
+ const home = homedir2();
238
+ const copilotHome = process.env["COPILOT_HOME"] ?? join(home, ".copilot");
239
+ return [
240
+ { client: "claude-code", path: join(projectRoot, ".mcp.json"), scope: "project" },
241
+ { client: "vscode", path: join(projectRoot, ".vscode", "mcp.json"), scope: "project" },
242
+ { client: "cursor", path: join(projectRoot, ".cursor", "mcp.json"), scope: "project" },
243
+ { client: "claude-code", path: join(home, ".claude.json"), scope: "user" },
244
+ { client: "cursor", path: join(home, ".cursor", "mcp.json"), scope: "user" },
245
+ { client: "claude-desktop", path: claudeDesktopPath(), scope: "user" },
246
+ { client: "windsurf", path: join(home, ".codeium", "windsurf", "mcp_config.json"), scope: "user" },
247
+ { client: "copilot", path: join(copilotHome, "mcp-config.json"), scope: "user" }
248
+ ];
249
+ }
250
+ function portablePath(absolute, projectRoot) {
251
+ const fromProject = relative(projectRoot, absolute);
252
+ if (!fromProject.startsWith("..") && !isAbsolute(fromProject)) return fromProject.split(sep).join("/");
253
+ const fromHome = relative(homedir2(), absolute);
254
+ if (!fromHome.startsWith("..") && !isAbsolute(fromHome)) return `~/${fromHome.split(sep).join("/")}`;
255
+ return absolute.split(sep).join("/");
256
+ }
257
+ async function readJsonIfPresent(path) {
258
+ let text;
259
+ try {
260
+ text = await readFile2(path, "utf8");
261
+ } catch (error) {
262
+ const code = error.code;
263
+ if (code === "ENOENT" || code === "ENOTDIR") return { present: false };
264
+ if (code === "EACCES") return { present: true, ok: false, reason: "permission denied" };
265
+ throw error;
266
+ }
267
+ try {
268
+ return { present: true, ok: true, value: JSON.parse(text) };
269
+ } catch (error) {
270
+ return { present: true, ok: false, reason: `not valid JSON: ${error.message}` };
271
+ }
272
+ }
273
+ async function discoverServers(projectRoot, extraFiles = []) {
274
+ const context = { workspaceFolder: projectRoot, env: process.env };
275
+ const files = [
276
+ ...extraFiles.map((path) => ({ client: "generic", path: resolve2(projectRoot, path) })),
277
+ ...candidateConfigFiles(projectRoot)
278
+ ];
279
+ const byName2 = /* @__PURE__ */ new Map();
280
+ const skipped = [];
281
+ const filesRead = [];
282
+ const shadowed = [];
283
+ const problems = [];
284
+ for (const file of files) {
285
+ const read = await readJsonIfPresent(file.path);
286
+ if (!read.present) continue;
287
+ if (!read.ok) {
288
+ problems.push({ file: portablePath(file.path, projectRoot), reason: read.reason });
289
+ continue;
290
+ }
291
+ const raw = read.value;
292
+ filesRead.push(file.path);
293
+ const source = { client: file.client, file: portablePath(file.path, projectRoot) };
294
+ let mapKey = CLIENT_MAP_KEY[file.client];
295
+ if (file.client === "generic") {
296
+ mapKey = detectMapKey(raw);
297
+ if (mapKey === void 0) {
298
+ problems.push({ file: source.file, reason: "no `mcpServers` or `servers` object found; this does not look like an MCP client config" });
299
+ continue;
300
+ }
301
+ }
302
+ const parsed = file.client === "claude-code" && file.scope === "user" ? await parseClaudeJson(raw, projectRoot, source, context) : await parseServerMap(raw, mapKey, { ...source, scope: file.scope }, context);
303
+ skipped.push(...parsed.skipped);
304
+ for (const server2 of parsed.servers) {
305
+ const existing = byName2.get(server2.name);
306
+ if (existing) {
307
+ shadowed.push({ name: server2.name, keptFrom: existing.from, alsoIn: source.file });
308
+ continue;
309
+ }
310
+ byName2.set(server2.name, { server: server2, from: source.file });
311
+ }
312
+ }
313
+ return {
314
+ servers: [...byName2.values()].map((entry) => entry.server).sort((a, b) => a.name.localeCompare(b.name)),
315
+ skipped,
316
+ filesRead,
317
+ shadowed,
318
+ problems
319
+ };
320
+ }
321
+
322
+ // ../core/src/lock/canonical.ts
323
+ import { createHash } from "crypto";
324
+ var MAX_DEPTH = 100;
325
+ var tooDeep = () => new TypeError(`cannot canonicalize JSON nested deeper than ${MAX_DEPTH} levels; this is not a surface we can hash`);
326
+ function canonicalize(value, depth = 0) {
327
+ if (depth > MAX_DEPTH) throw tooDeep();
328
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
329
+ return JSON.stringify(value);
330
+ }
331
+ if (value === void 0) {
332
+ throw new TypeError("cannot canonicalize undefined; pass the value through toJson first");
333
+ }
334
+ if (typeof value === "number") {
335
+ if (!Number.isFinite(value)) throw new TypeError(`cannot canonicalize non-finite number: ${value}`);
336
+ return JSON.stringify(value === 0 ? 0 : value);
337
+ }
338
+ if (Array.isArray(value)) {
339
+ return `[${value.map((member) => canonicalize(member, depth + 1)).join(",")}]`;
340
+ }
341
+ const keys = Object.keys(value).sort();
342
+ const members = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(value[key], depth + 1)}`);
343
+ return `{${members.join(",")}}`;
344
+ }
345
+ function digest(value) {
346
+ return `sha256:${createHash("sha256").update(canonicalize(value), "utf8").digest("hex")}`;
347
+ }
348
+ function toJson(value, depth = 0) {
349
+ if (depth > MAX_DEPTH) throw tooDeep();
350
+ if (value === null) return null;
351
+ if (Array.isArray(value)) return value.map((member) => toJson(member, depth + 1));
352
+ if (typeof value === "object") {
353
+ const out = {};
354
+ for (const [key, member] of Object.entries(value)) {
355
+ if (member === void 0) continue;
356
+ out[key] = toJson(member, depth + 1);
357
+ }
358
+ return out;
359
+ }
360
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") return value;
361
+ return null;
362
+ }
363
+ function stableKey(value) {
364
+ return canonicalize(toJson(value));
365
+ }
366
+
367
+ // ../core/src/lock/jsonschema.ts
368
+ var MAX_REF_DEPTH = 32;
369
+ var MAX_VISIT_DEPTH = 12;
370
+ var MAX_FACTS = 5e3;
371
+ function asObject(value) {
372
+ return value !== null && value !== void 0 && typeof value === "object" && !Array.isArray(value) ? value : void 0;
373
+ }
374
+ function decodeToken(token) {
375
+ let decoded = token;
376
+ try {
377
+ decoded = decodeURIComponent(token);
378
+ } catch {
379
+ }
380
+ return decoded.replace(/~1/g, "/").replace(/~0/g, "~");
381
+ }
382
+ function resolvePointer(root, ref) {
383
+ if (!ref.startsWith("#")) return void 0;
384
+ const pointer = ref.slice(1);
385
+ if (pointer !== "" && !pointer.startsWith("/")) return void 0;
386
+ let node = root;
387
+ for (const token of pointer.split("/").slice(1)) {
388
+ const object = asObject(node);
389
+ if (object === void 0) return void 0;
390
+ node = object[decodeToken(token)];
391
+ }
392
+ return node;
393
+ }
394
+ function effectiveSchema(node, root, seenRefs = /* @__PURE__ */ new Set(), depth = 0) {
395
+ const object = asObject(node);
396
+ if (object === void 0) return void 0;
397
+ if (depth > MAX_REF_DEPTH) return object;
398
+ const out = {};
399
+ const merge = (source) => {
400
+ for (const [key, value] of Object.entries(source)) {
401
+ if (key === "$ref" || key === "allOf") continue;
402
+ if (key === "properties") {
403
+ const merged = { ...asObject(out["properties"]) ?? {} };
404
+ for (const [name, schema] of Object.entries(asObject(value) ?? {})) {
405
+ if (!(name in merged)) merged[name] = schema;
406
+ }
407
+ out["properties"] = merged;
408
+ } else if (key === "required" && Array.isArray(value)) {
409
+ const already = Array.isArray(out["required"]) ? out["required"] : [];
410
+ out["required"] = [...new Set([...already, ...value].filter((entry) => typeof entry === "string"))];
411
+ } else if (!(key in out)) {
412
+ out[key] = value;
413
+ }
414
+ }
415
+ };
416
+ merge(object);
417
+ const ref = object["$ref"];
418
+ if (typeof ref === "string" && !seenRefs.has(ref)) {
419
+ const resolved = effectiveSchema(resolvePointer(root, ref), root, /* @__PURE__ */ new Set([...seenRefs, ref]), depth + 1);
420
+ if (resolved) merge(resolved);
421
+ }
422
+ const allOf = object["allOf"];
423
+ if (Array.isArray(allOf)) {
424
+ for (const branch of allOf) {
425
+ const resolved = effectiveSchema(branch, root, seenRefs, depth + 1);
426
+ if (resolved) merge(resolved);
427
+ }
428
+ }
429
+ return out;
430
+ }
431
+ function alternatives(object) {
432
+ const branches = [];
433
+ for (const keyword of ["anyOf", "oneOf"]) {
434
+ const value = object[keyword];
435
+ if (!Array.isArray(value)) continue;
436
+ value.forEach((schema, index) => branches.push({ label: `${keyword}[${index}]`, schema }));
437
+ }
438
+ for (const keyword of ["then", "else", "not"]) {
439
+ if (object[keyword] !== void 0) branches.push({ label: keyword, schema: object[keyword] });
440
+ }
441
+ return branches;
442
+ }
443
+
444
+ // ../core/src/lock/normalize.ts
445
+ function resolveBehavior(annotations2) {
446
+ const readOnly = annotations2?.readOnlyHint ?? false;
447
+ return {
448
+ readOnly,
449
+ destructive: readOnly ? false : annotations2?.destructiveHint ?? true,
450
+ idempotent: readOnly ? true : annotations2?.idempotentHint ?? false,
451
+ openWorld: annotations2?.openWorldHint ?? true
452
+ };
453
+ }
454
+ function isEscalation(previous, next) {
455
+ return previous.readOnly && !next.readOnly || !previous.destructive && next.destructive || previous.idempotent && !next.idempotent || !previous.openWorld && next.openWorld;
456
+ }
457
+ function normalizeSchema(value) {
458
+ if (Array.isArray(value)) return value.map(normalizeSchema);
459
+ if (value === null || typeof value !== "object") return value;
460
+ const out = {};
461
+ for (const [key, member] of Object.entries(value)) {
462
+ if (key === "required" && Array.isArray(member) && member.every((entry) => typeof entry === "string")) {
463
+ out[key] = [...member].sort();
464
+ continue;
465
+ }
466
+ out[key] = normalizeSchema(member);
467
+ }
468
+ return out;
469
+ }
470
+ function extractHeaderParams(schema) {
471
+ const found = [];
472
+ const walk = (node, path, depth) => {
473
+ if (depth > MAX_VISIT_DEPTH) return;
474
+ const object = effectiveSchema(node, schema);
475
+ if (!object) return;
476
+ const properties = asObject(object["properties"]);
477
+ if (properties) {
478
+ for (const [name, child] of Object.entries(properties)) {
479
+ const resolved = effectiveSchema(child, schema);
480
+ if (!resolved) continue;
481
+ const header = resolved["x-mcp-header"];
482
+ if (typeof header === "string" && header.length > 0) found.push(`${[...path, name].join(".")} -> ${header}`);
483
+ walk(child, [...path, name], depth + 1);
484
+ }
485
+ }
486
+ for (const branch of alternatives(object)) walk(branch.schema, path, depth + 1);
487
+ };
488
+ walk(schema, [], 0);
489
+ return [...new Set(found)].sort();
490
+ }
491
+ function stripIgnoredMeta(meta, ignoredPrefixes) {
492
+ if (meta === null || meta === void 0 || typeof meta !== "object" || Array.isArray(meta)) return void 0;
493
+ const out = {};
494
+ for (const [key, value] of Object.entries(meta)) {
495
+ if (ignoredPrefixes.some((prefix) => key.startsWith(prefix))) continue;
496
+ out[key] = value;
497
+ }
498
+ return Object.keys(out).length > 0 ? out : void 0;
499
+ }
500
+ function sanitizeUrl(raw) {
501
+ try {
502
+ const url = new URL(raw);
503
+ url.search = "";
504
+ url.hash = "";
505
+ return url.toString();
506
+ } catch {
507
+ return raw;
508
+ }
509
+ }
510
+
511
+ // src/lock/build.ts
512
+ function byName(members) {
513
+ return [...members].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
514
+ }
515
+ function lockIcons(icons) {
516
+ if (!icons || icons.length === 0) return void 0;
517
+ return icons.map((icon2) => ({
518
+ src: icon2.src,
519
+ mimeType: icon2.mimeType,
520
+ sizes: icon2.sizes,
521
+ theme: icon2.theme
522
+ }));
523
+ }
524
+ function sealed(entry) {
525
+ return { ...entry, digest: digest(toJson(entry)) };
526
+ }
527
+ function lockTransport(server2) {
528
+ const { transport: transport2 } = server2;
529
+ if (transport2.type === "stdio") {
530
+ return {
531
+ type: "stdio",
532
+ command: transport2.command,
533
+ args: transport2.args.length > 0 ? transport2.args : void 0,
534
+ envKeys: Object.keys(transport2.env).length > 0 ? Object.keys(transport2.env).sort() : void 0,
535
+ cwd: transport2.cwd
536
+ };
537
+ }
538
+ const headerKeys = Object.keys(transport2.headers);
539
+ return {
540
+ type: transport2.type,
541
+ url: sanitizeUrl(transport2.url),
542
+ headerKeys: headerKeys.length > 0 ? headerKeys.sort() : void 0
543
+ };
544
+ }
545
+ function lockTool(tool2, ignoredMeta) {
546
+ const annotations2 = tool2.annotations;
547
+ const inputSchema = normalizeSchema(toJson(tool2.inputSchema));
548
+ const headerParams = extractHeaderParams(inputSchema);
549
+ return sealed({
550
+ name: tool2.name,
551
+ title: tool2.title,
552
+ description: tool2.description,
553
+ inputSchema,
554
+ outputSchema: tool2.outputSchema ? normalizeSchema(toJson(tool2.outputSchema)) : void 0,
555
+ annotations: annotations2 ? { ...annotations2 } : void 0,
556
+ behavior: resolveBehavior(annotations2),
557
+ headerParams: headerParams.length > 0 ? headerParams : void 0,
558
+ icons: lockIcons(tool2.icons),
559
+ meta: stripIgnoredMeta(toJson(tool2._meta), ignoredMeta)
560
+ });
561
+ }
562
+ function lockResource(resource2, ignoredMeta) {
563
+ return sealed({
564
+ uri: resource2.uri,
565
+ name: resource2.name,
566
+ title: resource2.title,
567
+ description: resource2.description,
568
+ mimeType: resource2.mimeType,
569
+ annotations: resource2.annotations ? toJson(resource2.annotations) : void 0,
570
+ icons: lockIcons(resource2.icons),
571
+ meta: stripIgnoredMeta(toJson(resource2._meta), ignoredMeta)
572
+ });
573
+ }
574
+ function lockResourceTemplate(template, ignoredMeta) {
575
+ return sealed({
576
+ uriTemplate: template.uriTemplate,
577
+ name: template.name,
578
+ title: template.title,
579
+ description: template.description,
580
+ mimeType: template.mimeType,
581
+ annotations: template.annotations ? toJson(template.annotations) : void 0,
582
+ icons: lockIcons(template.icons),
583
+ meta: stripIgnoredMeta(toJson(template._meta), ignoredMeta)
584
+ });
585
+ }
586
+ function lockPrompt(prompt2, ignoredMeta) {
587
+ return sealed({
588
+ name: prompt2.name,
589
+ title: prompt2.title,
590
+ description: prompt2.description,
591
+ arguments: prompt2.arguments && prompt2.arguments.length > 0 ? prompt2.arguments.map((argument) => ({
592
+ name: argument.name,
593
+ // The spec gives PromptArgument a `title` (it extends BaseMetadata); the SDK's type
594
+ // has not caught up, so it is read off the wire rather than skipped.
595
+ title: argument.title,
596
+ description: argument.description,
597
+ required: argument.required
598
+ })) : void 0,
599
+ icons: lockIcons(prompt2.icons),
600
+ meta: stripIgnoredMeta(toJson(prompt2._meta), ignoredMeta)
601
+ });
602
+ }
603
+ function buildLockedServer(server2, surface, policy) {
604
+ const ignoredMeta = policy?.ignoreMetaPrefixes ?? [];
605
+ const tools = byName(surface.tools).map((tool2) => lockTool(tool2, ignoredMeta));
606
+ const resources = byName(surface.resources).map((resource2) => lockResource(resource2, ignoredMeta));
607
+ const resourceTemplates = byName(surface.resourceTemplates).map((template) => lockResourceTemplate(template, ignoredMeta));
608
+ const prompts = byName(surface.prompts).map((prompt2) => lockPrompt(prompt2, ignoredMeta));
609
+ const entry = {
610
+ source: server2.source,
611
+ transport: lockTransport(server2),
612
+ protocol: surface.protocol,
613
+ serverInfo: surface.serverInfo,
614
+ capabilities: surface.capabilities,
615
+ instructions: surface.instructions,
616
+ tools: tools.length > 0 ? tools : void 0,
617
+ resources: resources.length > 0 ? resources : void 0,
618
+ resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
619
+ prompts: prompts.length > 0 ? prompts : void 0
620
+ };
621
+ const covered = {
622
+ transport: entry.transport,
623
+ protocol: entry.protocol,
624
+ serverInfo: entry.serverInfo,
625
+ capabilities: entry.capabilities,
626
+ instructions: entry.instructions,
627
+ tools: tools.map((tool2) => tool2.digest),
628
+ resources: resources.map((resource2) => resource2.digest),
629
+ resourceTemplates: resourceTemplates.map((template) => template.digest),
630
+ prompts: prompts.map((prompt2) => prompt2.digest)
631
+ };
632
+ return { kind: "mcp-server", ...entry, digest: digest(toJson(covered)) };
633
+ }
634
+
635
+ // ../core/src/lock/types.ts
636
+ var LOCKFILE_VERSION = 2;
637
+
638
+ // src/mcp/connect.ts
639
+ import { Client, SSEClientTransport, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
640
+ import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/client/stdio";
641
+
642
+ // src/mcp/oauth.ts
643
+ import { spawn } from "child_process";
644
+ import { createHash as createHash2, randomUUID } from "crypto";
645
+ import { readFileSync } from "fs";
646
+ import { mkdir, readFile as readFile3, rm, writeFile } from "fs/promises";
647
+ import { homedir as homedir3, platform as platform2 } from "os";
648
+ import { dirname, join as join2 } from "path";
649
+ import { ClientCredentialsProvider, UnauthorizedError } from "@modelcontextprotocol/client";
650
+
651
+ // src/lib/version.ts
652
+ var VERSION = "0.1.0";
653
+ var USER_AGENT = `nulladrift/${VERSION}`;
654
+
655
+ // src/mcp/oauth.ts
656
+ var DEFAULT_CALLBACK_PATH = "/callback";
657
+ function authDir() {
658
+ const base = process.env["XDG_CONFIG_HOME"] ?? join2(homedir3(), ".config");
659
+ return join2(base, "nulladrift", "auth");
660
+ }
661
+ function credentialPath(url) {
662
+ return join2(authDir(), `${createHash2("sha256").update(url).digest("hex").slice(0, 16)}.json`);
663
+ }
664
+ var InteractiveAuthRequiredError = class extends Error {
665
+ constructor(serverName) {
666
+ super(`authorization required. Run \`nulladrift login ${serverName}\` once, then re-run.`);
667
+ this.serverName = serverName;
668
+ this.name = "InteractiveAuthRequiredError";
669
+ }
670
+ serverName;
671
+ };
672
+ var FileTokenProvider = class {
673
+ constructor(serverName, serverUrl, options = { interactive: false }) {
674
+ this.serverName = serverName;
675
+ this.serverUrl = serverUrl;
676
+ this.options = options;
677
+ }
678
+ serverName;
679
+ serverUrl;
680
+ options;
681
+ cache;
682
+ /** One per login attempt, held in memory and checked against what comes back on the callback. */
683
+ stateValue = createHash2("sha256").update(randomUUID()).digest("hex").slice(0, 32);
684
+ get redirectUrl() {
685
+ return this.options.redirectUrl;
686
+ }
687
+ state() {
688
+ return this.stateValue;
689
+ }
690
+ get clientMetadata() {
691
+ return {
692
+ client_name: `nulladrift ${VERSION}`,
693
+ // A command-line tool is a native client: it cannot keep a secret in a shipped binary.
694
+ application_type: "native",
695
+ redirect_uris: this.options.redirectUrl === void 0 ? [] : [this.options.redirectUrl],
696
+ grant_types: ["authorization_code", "refresh_token"],
697
+ response_types: ["code"],
698
+ token_endpoint_auth_method: "none",
699
+ ...this.options.scope === void 0 ? {} : { scope: this.options.scope }
700
+ };
701
+ }
702
+ async read() {
703
+ if (this.cache) return this.cache;
704
+ try {
705
+ this.cache = JSON.parse(await readFile3(credentialPath(this.serverUrl), "utf8"));
706
+ } catch {
707
+ this.cache = { serverUrl: this.serverUrl };
708
+ }
709
+ return this.cache;
710
+ }
711
+ async write(patch) {
712
+ const next = { ...await this.read(), ...patch, serverUrl: this.serverUrl };
713
+ this.cache = next;
714
+ const path = credentialPath(this.serverUrl);
715
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
716
+ await writeFile(path, `${JSON.stringify(next, null, 2)}
717
+ `, { encoding: "utf8", mode: 384 });
718
+ }
719
+ async clientInformation() {
720
+ return (await this.read()).clientInformation;
721
+ }
722
+ async saveClientInformation(clientInformation) {
723
+ await this.write({ clientInformation });
724
+ }
725
+ async tokens() {
726
+ return (await this.read()).tokens;
727
+ }
728
+ async saveTokens(tokens) {
729
+ await this.write({ tokens });
730
+ }
731
+ async saveCodeVerifier(codeVerifier) {
732
+ await this.write({ codeVerifier });
733
+ }
734
+ async codeVerifier() {
735
+ const stored = (await this.read()).codeVerifier;
736
+ if (stored === void 0) throw new Error("no PKCE verifier stored; start the login again");
737
+ return stored;
738
+ }
739
+ async saveAuthorizationServerUrl(authorizationServerUrl) {
740
+ await this.write({ authorizationServerUrl });
741
+ }
742
+ async authorizationServerUrl() {
743
+ return (await this.read()).authorizationServerUrl;
744
+ }
745
+ async saveResourceUrl(resourceUrl) {
746
+ await this.write({ resourceUrl });
747
+ }
748
+ async resourceUrl() {
749
+ return (await this.read()).resourceUrl;
750
+ }
751
+ async saveDiscoveryState(discoveryState) {
752
+ await this.write({ discoveryState });
753
+ }
754
+ async discoveryState() {
755
+ return (await this.read()).discoveryState;
756
+ }
757
+ async invalidateCredentials(scope) {
758
+ if (scope === "all") {
759
+ this.cache = { serverUrl: this.serverUrl };
760
+ await rm(credentialPath(this.serverUrl), { force: true });
761
+ return;
762
+ }
763
+ const key = { client: "clientInformation", tokens: "tokens", verifier: "codeVerifier", discovery: "discoveryState" }[scope];
764
+ await this.write({ [key]: void 0 });
765
+ }
766
+ async redirectToAuthorization(authorizationUrl) {
767
+ if (!this.options.interactive) throw new InteractiveAuthRequiredError(this.serverName);
768
+ openInBrowser(authorizationUrl);
769
+ process.stderr.write(`
770
+ If a browser did not open, visit:
771
+ ${authorizationUrl.toString()}
772
+
773
+ `);
774
+ }
775
+ };
776
+ function openInBrowser(url) {
777
+ const command = platform2() === "darwin" ? "open" : platform2() === "win32" ? "cmd" : "xdg-open";
778
+ const args = platform2() === "win32" ? ["/c", "start", "", url.toString()] : [url.toString()];
779
+ try {
780
+ spawn(command, args, { detached: true, stdio: "ignore" }).unref();
781
+ } catch {
782
+ }
783
+ }
784
+ function hasStoredCredentials(url) {
785
+ try {
786
+ const stored = JSON.parse(readFileSync(credentialPath(url), "utf8"));
787
+ return typeof stored.tokens?.access_token === "string" && stored.tokens.access_token.length > 0;
788
+ } catch {
789
+ return false;
790
+ }
791
+ }
792
+ function createAuthProvider(server2, options = {}) {
793
+ if (server2.transport.type === "stdio") return void 0;
794
+ const oauth = server2.transport.oauth;
795
+ if (oauth?.clientId !== void 0 && oauth.clientSecret !== void 0) {
796
+ return new ClientCredentialsProvider({
797
+ clientId: oauth.clientId,
798
+ clientSecret: oauth.clientSecret,
799
+ clientName: `nulladrift ${VERSION}`,
800
+ ...oauth.scope === void 0 ? {} : { scope: oauth.scope }
801
+ });
802
+ }
803
+ const interactive = options.interactive ?? false;
804
+ if (!interactive && !hasStoredCredentials(server2.transport.url)) return void 0;
805
+ return new FileTokenProvider(server2.name, server2.transport.url, {
806
+ interactive,
807
+ ...oauth?.scope === void 0 ? {} : { scope: oauth.scope }
808
+ });
809
+ }
810
+
811
+ // src/mcp/types.ts
812
+ import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/client";
813
+ var UnreachableServerError = class extends Error {
814
+ constructor(serverName, message, cause) {
815
+ super(message);
816
+ this.serverName = serverName;
817
+ this.cause = cause;
818
+ this.name = "UnreachableServerError";
819
+ }
820
+ serverName;
821
+ cause;
822
+ };
823
+ function isAuthFailure(error) {
824
+ if (error instanceof UnauthorizedError2) return true;
825
+ if (error instanceof Error && error.name === "InteractiveAuthRequiredError") return true;
826
+ if (error instanceof UnreachableServerError && error.cause instanceof Error && error.cause.name === "InteractiveAuthRequiredError") return true;
827
+ const cause = error instanceof UnreachableServerError ? error.cause : void 0;
828
+ if (cause instanceof UnauthorizedError2) return true;
829
+ for (const candidate of [error, error instanceof UnreachableServerError ? error.cause : void 0]) {
830
+ const name = candidate instanceof Error ? candidate.name : "";
831
+ if (name === "RegistrationRejectedError" || name === "InsufficientScopeError" || name === "OAuthClientFlowError") return true;
832
+ }
833
+ const text = `${error instanceof Error ? error.message : String(error)}`.toLowerCase();
834
+ return /\b(401|403)\b|unauthorized|forbidden|invalid or missing.*token|authentication required|invalid_client|dynamic client registration/.test(text);
835
+ }
836
+
837
+ // src/mcp/connect.ts
838
+ var DEFAULT_TIMEOUT_MS = 3e4;
839
+ var STDERR_KEEP_BYTES = 2e3;
840
+ function buildTransport(server2, captureStderr = () => {
841
+ }, options = {}) {
842
+ const { transport: transport2 } = server2;
843
+ if (transport2.type === "stdio") {
844
+ const child = new StdioClientTransport({
845
+ command: transport2.command,
846
+ args: transport2.args,
847
+ // The server's own environment plus whatever the config sets. Never the auditor's full env.
848
+ env: { ...getDefaultEnvironment(), ...transport2.env },
849
+ cwd: transport2.cwd,
850
+ // Piped rather than inherited: a chatty server must not interleave with our report, but its
851
+ // last words are the most useful thing we can show when it fails to answer.
852
+ stderr: "pipe"
853
+ });
854
+ child.stderr?.on("data", (chunk) => captureStderr(chunk.toString("utf8")));
855
+ return child;
856
+ }
857
+ const headers = { ...transport2.headers, "user-agent": `nulladrift/${VERSION}` };
858
+ const url = new URL(transport2.url);
859
+ const authProvider = createAuthProvider(server2, options);
860
+ if (transport2.type === "sse") return new SSEClientTransport(url, { requestInit: { headers }, authProvider });
861
+ return new StreamableHTTPClientTransport(url, { requestInit: { headers }, authProvider });
862
+ }
863
+ async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS, options = {}) {
864
+ let stderrBuffer = "";
865
+ const captureStderr = (chunk) => {
866
+ stderrBuffer = (stderrBuffer + chunk).slice(-STDERR_KEEP_BYTES);
867
+ };
868
+ const client = new Client(
869
+ { name: "nulladrift", title: "nulladrift", version: VERSION },
870
+ {
871
+ /*
872
+ * We advertise nothing. An auditor never calls a tool, so it has no business offering
873
+ * elicitation, sampling or roots -- a server that asks for them gets nothing to work with.
874
+ */
875
+ capabilities: {},
876
+ versionNegotiation: { mode: "auto", probe: { timeoutMs } }
877
+ }
878
+ );
879
+ let transport2;
880
+ try {
881
+ transport2 = buildTransport(server2, captureStderr, options);
882
+ } catch (error) {
883
+ throw new UnreachableServerError(server2.name, `could not prepare transport: ${error.message}`, error);
884
+ }
885
+ try {
886
+ await client.connect(transport2, { timeout: timeoutMs });
887
+ } catch (error) {
888
+ await client.close().catch(() => {
889
+ });
890
+ const detail = stderrBuffer.trim();
891
+ throw new UnreachableServerError(
892
+ server2.name,
893
+ `${error.message}${detail ? `
894
+ server stderr: ${detail.split("\n").slice(-3).join("\n ")}` : ""}`,
895
+ error
896
+ );
897
+ }
898
+ return {
899
+ client,
900
+ stderr: () => stderrBuffer,
901
+ close: async () => {
902
+ await client.close().catch(() => {
903
+ });
904
+ }
905
+ };
906
+ }
907
+
908
+ // src/mcp/capture.ts
909
+ var FRESH = { cacheMode: "bypass" };
910
+ async function listOrEmpty(label, serverName, fetchList) {
911
+ try {
912
+ return await fetchList();
913
+ } catch (error) {
914
+ throw new UnreachableServerError(serverName, `${label} failed: ${error.message}`, error);
915
+ }
916
+ }
917
+ function readProtocol(client) {
918
+ const era = client.getProtocolEra() ?? "legacy";
919
+ const version = client.getNegotiatedProtocolVersion() ?? "unknown";
920
+ const discovered = client.getDiscoverResult();
921
+ return {
922
+ era,
923
+ version,
924
+ supportedVersions: discovered?.supportedVersions
925
+ };
926
+ }
927
+ function readServerInfo(client) {
928
+ const info = client.getServerVersion();
929
+ if (!info) return void 0;
930
+ return {
931
+ name: info.name,
932
+ title: info.title,
933
+ version: info.version,
934
+ description: info.description,
935
+ websiteUrl: info.websiteUrl
936
+ };
937
+ }
938
+ async function captureSurface(server2, timeoutMs = DEFAULT_TIMEOUT_MS) {
939
+ const connection = await connect(server2, timeoutMs);
940
+ const { client } = connection;
941
+ try {
942
+ const capabilities = client.getServerCapabilities();
943
+ const [tools, resources, resourceTemplates, prompts] = await Promise.all([
944
+ capabilities?.tools ? listOrEmpty("tools/list", server2.name, async () => (await client.listTools(void 0, FRESH)).tools) : [],
945
+ capabilities?.resources ? listOrEmpty("resources/list", server2.name, async () => (await client.listResources(void 0, FRESH)).resources) : [],
946
+ capabilities?.resources ? listOrEmpty("resources/templates/list", server2.name, async () => (await client.listResourceTemplates(void 0, FRESH)).resourceTemplates) : [],
947
+ capabilities?.prompts ? listOrEmpty("prompts/list", server2.name, async () => (await client.listPrompts(void 0, FRESH)).prompts) : []
948
+ ]);
949
+ return {
950
+ protocol: readProtocol(client),
951
+ serverInfo: readServerInfo(client),
952
+ capabilities: capabilities ? toJson(capabilities) : void 0,
953
+ // Clients place this in the model's system prompt, so it is part of the capability surface.
954
+ instructions: client.getInstructions(),
955
+ tools,
956
+ resources,
957
+ resourceTemplates,
958
+ prompts
959
+ };
960
+ } finally {
961
+ await connection.close();
962
+ }
963
+ }
964
+
965
+ // src/audit.ts
966
+ async function mapWithLimit(items, limit, worker) {
967
+ const results = new Array(items.length);
968
+ let next = 0;
969
+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
970
+ for (; ; ) {
971
+ const index = next++;
972
+ const item = items[index];
973
+ if (index >= items.length || item === void 0) return;
974
+ results[index] = await worker(item);
975
+ }
976
+ });
977
+ await Promise.all(runners);
978
+ return results;
979
+ }
980
+ async function captureAll(options) {
981
+ const discovery = await discoverServers(options.projectRoot, options.configFiles);
982
+ const captured = await mapWithLimit(discovery.servers, options.concurrency ?? 4, async (server2) => {
983
+ try {
984
+ const surface = await captureSurface(server2, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
985
+ options.onServerDone?.(server2.name, "captured");
986
+ return { name: server2.name, entry: buildLockedServer(server2, surface, options.policy) };
987
+ } catch (error) {
988
+ options.onServerDone?.(server2.name, "failed");
989
+ const reason = error instanceof UnreachableServerError ? error.message : error.message;
990
+ const kind = isAuthFailure(error) ? "auth" : "unreachable";
991
+ return { name: server2.name, failure: { server: server2.name, reason, kind } };
992
+ }
993
+ });
994
+ const subjects = {};
995
+ const unreachable = [];
996
+ for (const result of captured) {
997
+ if ("entry" in result && result.entry) subjects[result.name] = result.entry;
998
+ else if ("failure" in result && result.failure) unreachable.push(result.failure);
999
+ }
1000
+ for (const skipped of discovery.skipped) {
1001
+ unreachable.push({ server: skipped.serverName, reason: skipped.message, kind: "unreachable" });
1002
+ }
1003
+ for (const problem of discovery.problems) {
1004
+ unreachable.push({ server: problem.file, reason: problem.reason, kind: "unreachable" });
1005
+ }
1006
+ return {
1007
+ lock: {
1008
+ lockfileVersion: LOCKFILE_VERSION,
1009
+ generatedBy: `nulladrift@${VERSION}`,
1010
+ policy: options.policy,
1011
+ subjects
1012
+ },
1013
+ unreachable,
1014
+ discovery
1015
+ };
1016
+ }
1017
+
1018
+ // ../core/src/diff/schema.ts
1019
+ function numberAt(node, key) {
1020
+ const value = node[key];
1021
+ return typeof value === "number" ? value : void 0;
1022
+ }
1023
+ function collectFacts(schema) {
1024
+ const facts = /* @__PURE__ */ new Map();
1025
+ const visit = (node, path, required, depth) => {
1026
+ if (depth > MAX_VISIT_DEPTH || facts.size >= MAX_FACTS) return;
1027
+ const object = effectiveSchema(node, schema);
1028
+ if (!object) return;
1029
+ const typeValue = object["type"];
1030
+ const types = typeof typeValue === "string" ? [typeValue] : Array.isArray(typeValue) ? typeValue.filter((entry) => typeof entry === "string").sort() : void 0;
1031
+ const enumValue = object["enum"];
1032
+ facts.set(path, {
1033
+ required,
1034
+ additionalProperties: typeof object["additionalProperties"] === "boolean" ? object["additionalProperties"] : void 0,
1035
+ enumMembers: Array.isArray(enumValue) ? enumValue.map((entry) => canonicalize(entry)).sort() : void 0,
1036
+ types,
1037
+ minimum: numberAt(object, "minimum"),
1038
+ maximum: numberAt(object, "maximum"),
1039
+ minLength: numberAt(object, "minLength"),
1040
+ maxLength: numberAt(object, "maxLength")
1041
+ });
1042
+ const properties = asObject(object["properties"]);
1043
+ if (properties) {
1044
+ const requiredList = Array.isArray(object["required"]) ? object["required"].filter((entry) => typeof entry === "string") : [];
1045
+ for (const [name, child] of Object.entries(properties)) {
1046
+ visit(child, path === "" ? name : `${path}.${name}`, requiredList.includes(name), depth + 1);
1047
+ }
1048
+ }
1049
+ const items = object["items"];
1050
+ if (items !== void 0) visit(items, `${path}[]`, false, depth + 1);
1051
+ const prefixItems = object["prefixItems"];
1052
+ if (Array.isArray(prefixItems)) prefixItems.forEach((entry, index) => visit(entry, `${path}[${index}]`, false, depth + 1));
1053
+ for (const branch of alternatives(object)) visit(branch.schema, `${path}|${branch.label}`, false, depth + 1);
1054
+ };
1055
+ visit(schema, "", true, 0);
1056
+ return facts;
1057
+ }
1058
+ function isSuperset(next, previous) {
1059
+ return previous.every((entry) => next.includes(entry));
1060
+ }
1061
+ function classifySchemaChange(before, after) {
1062
+ if (stableKey(before) === stableKey(after)) return "same";
1063
+ const previous = collectFacts(before);
1064
+ const next = collectFacts(after);
1065
+ let widened = false;
1066
+ let narrowed = false;
1067
+ for (const path of /* @__PURE__ */ new Set([...previous.keys(), ...next.keys()])) {
1068
+ const a = previous.get(path);
1069
+ const b = next.get(path);
1070
+ if (!a && b) {
1071
+ widened = true;
1072
+ continue;
1073
+ }
1074
+ if (a && !b) {
1075
+ narrowed = true;
1076
+ continue;
1077
+ }
1078
+ if (!a || !b) continue;
1079
+ if (a.required && !b.required) widened = true;
1080
+ if (!a.required && b.required) narrowed = true;
1081
+ const beforeAdditional = a.additionalProperties ?? true;
1082
+ const afterAdditional = b.additionalProperties ?? true;
1083
+ if (!beforeAdditional && afterAdditional) widened = true;
1084
+ if (beforeAdditional && !afterAdditional) narrowed = true;
1085
+ if (a.enumMembers && b.enumMembers) {
1086
+ if (isSuperset(b.enumMembers, a.enumMembers) && b.enumMembers.length > a.enumMembers.length) widened = true;
1087
+ else if (isSuperset(a.enumMembers, b.enumMembers) && a.enumMembers.length > b.enumMembers.length) narrowed = true;
1088
+ else if (canonicalize(a.enumMembers) !== canonicalize(b.enumMembers)) {
1089
+ widened = true;
1090
+ narrowed = true;
1091
+ }
1092
+ } else if (a.enumMembers && !b.enumMembers) widened = true;
1093
+ else if (!a.enumMembers && b.enumMembers) narrowed = true;
1094
+ if (a.types && b.types) {
1095
+ if (isSuperset(b.types, a.types) && b.types.length > a.types.length) widened = true;
1096
+ else if (isSuperset(a.types, b.types) && a.types.length > b.types.length) narrowed = true;
1097
+ else if (canonicalize(a.types) !== canonicalize(b.types)) {
1098
+ widened = true;
1099
+ narrowed = true;
1100
+ }
1101
+ } else if (a.types && !b.types) widened = true;
1102
+ else if (!a.types && b.types) narrowed = true;
1103
+ const lowerBounds = [["minimum", a.minimum, b.minimum], ["minLength", a.minLength, b.minLength]];
1104
+ for (const [, before_, after_] of lowerBounds) {
1105
+ if (before_ !== void 0 && after_ === void 0) widened = true;
1106
+ else if (before_ === void 0 && after_ !== void 0) narrowed = true;
1107
+ else if (before_ !== void 0 && after_ !== void 0) {
1108
+ if (after_ < before_) widened = true;
1109
+ if (after_ > before_) narrowed = true;
1110
+ }
1111
+ }
1112
+ const upperBounds = [["maximum", a.maximum, b.maximum], ["maxLength", a.maxLength, b.maxLength]];
1113
+ for (const [, before_, after_] of upperBounds) {
1114
+ if (before_ !== void 0 && after_ === void 0) widened = true;
1115
+ else if (before_ === void 0 && after_ !== void 0) narrowed = true;
1116
+ else if (before_ !== void 0 && after_ !== void 0) {
1117
+ if (after_ > before_) widened = true;
1118
+ if (after_ < before_) narrowed = true;
1119
+ }
1120
+ }
1121
+ }
1122
+ if (widened && !narrowed) return "widened";
1123
+ if (narrowed && !widened) return "narrowed";
1124
+ return "changed";
1125
+ }
1126
+
1127
+ // ../core/src/changes.ts
1128
+ var CHANGE_KINDS = [
1129
+ "server.added",
1130
+ "server.removed",
1131
+ "server.renamed",
1132
+ "server.transport.changed",
1133
+ "server.identity.changed",
1134
+ "server.protocol.changed",
1135
+ "server.instructions.changed",
1136
+ "server.capabilities.widened",
1137
+ "server.capabilities.narrowed",
1138
+ "server.capabilities.changed",
1139
+ "tool.added",
1140
+ "tool.removed",
1141
+ "tool.description.changed",
1142
+ "tool.input_schema.widened",
1143
+ "tool.input_schema.narrowed",
1144
+ "tool.input_schema.changed",
1145
+ "tool.output_schema.changed",
1146
+ "tool.behavior.escalated",
1147
+ "tool.behavior.relaxed",
1148
+ "tool.header_params.changed",
1149
+ "tool.changed",
1150
+ "resource.added",
1151
+ "resource.removed",
1152
+ "resource.changed",
1153
+ "resource_template.added",
1154
+ "resource_template.removed",
1155
+ "resource_template.changed",
1156
+ "prompt.added",
1157
+ "prompt.removed",
1158
+ "prompt.changed"
1159
+ ];
1160
+ var SEVERITY = {
1161
+ "server.added": "medium",
1162
+ "server.removed": "low",
1163
+ "server.renamed": "low",
1164
+ "server.transport.changed": "high",
1165
+ "server.identity.changed": "medium",
1166
+ "server.protocol.changed": "medium",
1167
+ "server.instructions.changed": "high",
1168
+ "server.capabilities.widened": "medium",
1169
+ "server.capabilities.narrowed": "low",
1170
+ "server.capabilities.changed": "medium",
1171
+ "tool.added": "high",
1172
+ "tool.removed": "low",
1173
+ "tool.description.changed": "high",
1174
+ "tool.input_schema.widened": "high",
1175
+ "tool.input_schema.narrowed": "low",
1176
+ "tool.input_schema.changed": "medium",
1177
+ "tool.output_schema.changed": "medium",
1178
+ "tool.behavior.escalated": "high",
1179
+ "tool.behavior.relaxed": "low",
1180
+ "tool.header_params.changed": "high",
1181
+ "tool.changed": "medium",
1182
+ "resource.added": "medium",
1183
+ "resource.removed": "low",
1184
+ "resource.changed": "medium",
1185
+ "resource_template.added": "high",
1186
+ "resource_template.removed": "low",
1187
+ "resource_template.changed": "high",
1188
+ "prompt.added": "medium",
1189
+ "prompt.removed": "low",
1190
+ "prompt.changed": "medium"
1191
+ };
1192
+ var SEVERITY_RANK = { high: 0, medium: 1, low: 2 };
1193
+ function sortChanges(changes) {
1194
+ return [...changes].sort(
1195
+ (a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || a.server.localeCompare(b.server) || (a.member ?? "").localeCompare(b.member ?? "") || a.kind.localeCompare(b.kind)
1196
+ );
1197
+ }
1198
+ function serversThatShippedNothing(changes) {
1199
+ const moved = /* @__PURE__ */ new Set();
1200
+ const versioned = /* @__PURE__ */ new Set();
1201
+ for (const change2 of changes) {
1202
+ moved.add(change2.server);
1203
+ if (change2.kind === "server.identity.changed") versioned.add(change2.server);
1204
+ }
1205
+ return [...moved].filter((server2) => !versioned.has(server2)).sort();
1206
+ }
1207
+
1208
+ // ../core/src/diff/index.ts
1209
+ function change(kind, server2, summary, extra) {
1210
+ return { kind, severity: SEVERITY[kind], server: server2, summary, ...extra };
1211
+ }
1212
+ function same(a, b) {
1213
+ return stableKey(a ?? null) === stableKey(b ?? null);
1214
+ }
1215
+ function indexBy(members, key) {
1216
+ return new Map((members ?? []).map((member) => [key(member), member]));
1217
+ }
1218
+ function declaredNames(capabilities) {
1219
+ const names = [];
1220
+ for (const [key, value] of Object.entries(capabilities ?? {})) {
1221
+ if (key === "extensions" && value !== null && typeof value === "object" && !Array.isArray(value)) {
1222
+ for (const id of Object.keys(value)) names.push(`extensions/${id}`);
1223
+ continue;
1224
+ }
1225
+ names.push(key);
1226
+ }
1227
+ return names;
1228
+ }
1229
+ function compareCapabilities(before, after, name) {
1230
+ if (same(before.capabilities, after.capabilities)) return [];
1231
+ const previous = declaredNames(before.capabilities);
1232
+ const next = declaredNames(after.capabilities);
1233
+ const gained = next.filter((key) => !previous.includes(key));
1234
+ const lost = previous.filter((key) => !next.includes(key));
1235
+ if (gained.length > 0 && lost.length === 0) {
1236
+ return [change("server.capabilities.widened", name, `server now declares ${gained.join(", ")}`, { before: before.capabilities, after: after.capabilities })];
1237
+ }
1238
+ if (lost.length > 0 && gained.length === 0) {
1239
+ return [change("server.capabilities.narrowed", name, `server no longer declares ${lost.join(", ")}`, { before: before.capabilities, after: after.capabilities })];
1240
+ }
1241
+ return [change("server.capabilities.changed", name, "declared capabilities changed", { before: before.capabilities, after: after.capabilities })];
1242
+ }
1243
+ function compareTool(name, before, after) {
1244
+ if (before.digest === after.digest) return [];
1245
+ const changes = [];
1246
+ const at = { member: before.name };
1247
+ if (!same(before.description, after.description)) {
1248
+ changes.push(
1249
+ change("tool.description.changed", name, `description changed (${before.description?.length ?? 0} \u2192 ${after.description?.length ?? 0} characters)`, {
1250
+ ...at,
1251
+ before: before.description,
1252
+ after: after.description
1253
+ })
1254
+ );
1255
+ }
1256
+ const inputVerdict = classifySchemaChange(before.inputSchema, after.inputSchema);
1257
+ if (inputVerdict !== "same") {
1258
+ const kind = `tool.input_schema.${inputVerdict}`;
1259
+ const wording = inputVerdict === "widened" ? "accepts input it did not before" : inputVerdict === "narrowed" ? "accepts less input than before" : "input schema changed";
1260
+ changes.push(change(kind, name, wording, { ...at, before: before.inputSchema, after: after.inputSchema }));
1261
+ }
1262
+ if (!same(before.outputSchema, after.outputSchema)) {
1263
+ changes.push(change("tool.output_schema.changed", name, "output schema changed", { ...at, before: before.outputSchema, after: after.outputSchema }));
1264
+ }
1265
+ if (!same(before.behavior, after.behavior)) {
1266
+ const escalated = isEscalation(before.behavior, after.behavior);
1267
+ changes.push(
1268
+ change(escalated ? "tool.behavior.escalated" : "tool.behavior.relaxed", name, escalated ? describeEscalation(before, after) : "declares fewer powers than before", {
1269
+ ...at,
1270
+ before: before.behavior,
1271
+ after: after.behavior
1272
+ })
1273
+ );
1274
+ }
1275
+ if (!same(before.headerParams, after.headerParams)) {
1276
+ changes.push(
1277
+ change("tool.header_params.changed", name, "arguments mirrored into HTTP headers changed", { ...at, before: before.headerParams ?? [], after: after.headerParams ?? [] })
1278
+ );
1279
+ }
1280
+ if (changes.length === 0) {
1281
+ changes.push(change("tool.changed", name, "tool definition changed (title, icons or _meta)", { ...at, before, after }));
1282
+ }
1283
+ return changes;
1284
+ }
1285
+ function describeEscalation(before, after) {
1286
+ const gained = [];
1287
+ if (before.behavior.readOnly && !after.behavior.readOnly) gained.push("may now modify");
1288
+ if (!before.behavior.destructive && after.behavior.destructive) gained.push("may now destroy");
1289
+ if (before.behavior.idempotent && !after.behavior.idempotent) gained.push("repeat calls now compound");
1290
+ if (!before.behavior.openWorld && after.behavior.openWorld) gained.push("may now reach external systems");
1291
+ return gained.join("; ");
1292
+ }
1293
+ function compareMembers(name, before, after, spec, deep) {
1294
+ const changes = [];
1295
+ const previous = indexBy(before, spec.key);
1296
+ const next = indexBy(after, spec.key);
1297
+ for (const [key, member] of next) {
1298
+ const existing = previous.get(key);
1299
+ if (!existing) {
1300
+ changes.push(change(spec.added, name, `new ${spec.noun} ${spec.label(member)}`, { member: spec.label(member), after: member }));
1301
+ continue;
1302
+ }
1303
+ if (existing.digest === member.digest) continue;
1304
+ changes.push(...deep ? deep(key, existing, member) : [change(spec.changed, name, `${spec.noun} ${spec.label(member)} changed`, { member: spec.label(member), before: existing, after: member })]);
1305
+ }
1306
+ for (const [key, member] of previous) {
1307
+ if (!next.has(key)) changes.push(change(spec.removed, name, `${spec.noun} ${spec.label(member)} is gone`, { member: spec.label(member), before: member }));
1308
+ }
1309
+ return changes;
1310
+ }
1311
+ function compareServer(name, before, after) {
1312
+ if (before.digest === after.digest) return [];
1313
+ const changes = [];
1314
+ if (!same(before.transport, after.transport)) {
1315
+ changes.push(change("server.transport.changed", name, "the server is reached differently than when it was pinned", { before: before.transport, after: after.transport }));
1316
+ }
1317
+ if (!same(before.serverInfo, after.serverInfo)) {
1318
+ const from = before.serverInfo?.version ?? "unknown";
1319
+ const to = after.serverInfo?.version ?? "unknown";
1320
+ changes.push(change("server.identity.changed", name, `server identity changed (version ${from} \u2192 ${to})`, { before: before.serverInfo, after: after.serverInfo }));
1321
+ }
1322
+ if (!same(before.protocol, after.protocol)) {
1323
+ changes.push(
1324
+ change("server.protocol.changed", name, `protocol changed (${before.protocol.era}/${before.protocol.version} \u2192 ${after.protocol.era}/${after.protocol.version})`, {
1325
+ before: before.protocol,
1326
+ after: after.protocol
1327
+ })
1328
+ );
1329
+ }
1330
+ if (!same(before.instructions, after.instructions)) {
1331
+ changes.push(
1332
+ change("server.instructions.changed", name, "server instructions changed: this text goes into the model's system prompt", {
1333
+ before: before.instructions,
1334
+ after: after.instructions
1335
+ })
1336
+ );
1337
+ }
1338
+ changes.push(...compareCapabilities(before, after, name));
1339
+ changes.push(
1340
+ ...compareMembers(
1341
+ name,
1342
+ before.tools,
1343
+ after.tools,
1344
+ { key: (t) => t.name, label: (t) => t.name, added: "tool.added", removed: "tool.removed", changed: "tool.changed", noun: "tool" },
1345
+ (_key, a, b) => compareTool(name, a, b)
1346
+ )
1347
+ );
1348
+ changes.push(
1349
+ ...compareMembers(name, before.resources, after.resources, {
1350
+ key: (r) => r.uri,
1351
+ label: (r) => `${r.name} (${r.uri})`,
1352
+ added: "resource.added",
1353
+ removed: "resource.removed",
1354
+ changed: "resource.changed",
1355
+ noun: "resource"
1356
+ })
1357
+ );
1358
+ changes.push(
1359
+ ...compareMembers(name, before.resourceTemplates, after.resourceTemplates, {
1360
+ key: (t) => t.uriTemplate,
1361
+ // The template itself is the capability -- widening it from file:///project/{path} to
1362
+ // file:///{path} is the whole finding -- so it belongs in the label, not just the body.
1363
+ label: (t) => `${t.name} (${t.uriTemplate})`,
1364
+ added: "resource_template.added",
1365
+ removed: "resource_template.removed",
1366
+ changed: "resource_template.changed",
1367
+ noun: "resource template"
1368
+ })
1369
+ );
1370
+ changes.push(
1371
+ ...compareMembers(name, before.prompts, after.prompts, {
1372
+ key: (p) => p.name,
1373
+ label: (p) => p.name,
1374
+ added: "prompt.added",
1375
+ removed: "prompt.removed",
1376
+ changed: "prompt.changed",
1377
+ noun: "prompt"
1378
+ })
1379
+ );
1380
+ return changes;
1381
+ }
1382
+ function detectRenames(before, after, removed, added) {
1383
+ const changes = [];
1384
+ const renamed = /* @__PURE__ */ new Set();
1385
+ const availableAdds = [...added];
1386
+ for (const oldName of removed) {
1387
+ const oldEntry = before.subjects[oldName];
1388
+ if (!oldEntry) continue;
1389
+ const match = availableAdds.find((newName) => {
1390
+ const candidate = after.subjects[newName];
1391
+ return candidate !== void 0 && candidate.digest === oldEntry.digest && same(candidate.transport, oldEntry.transport);
1392
+ });
1393
+ if (!match) continue;
1394
+ availableAdds.splice(availableAdds.indexOf(match), 1);
1395
+ renamed.add(oldName);
1396
+ renamed.add(match);
1397
+ changes.push(change("server.renamed", match, `renamed from "${oldName}"; capabilities are unchanged`, { before: oldName, after: match }));
1398
+ }
1399
+ return { changes, renamed };
1400
+ }
1401
+ function diffLockfiles(before, after) {
1402
+ const beforeNames = Object.keys(before.subjects);
1403
+ const afterNames = Object.keys(after.subjects);
1404
+ const removed = beforeNames.filter((name) => !afterNames.includes(name));
1405
+ const added = afterNames.filter((name) => !beforeNames.includes(name));
1406
+ const { changes: renameChanges, renamed } = detectRenames(before, after, removed, added);
1407
+ const changes = [...renameChanges];
1408
+ for (const name of added) {
1409
+ if (renamed.has(name)) continue;
1410
+ const entry = after.subjects[name];
1411
+ const toolCount = entry?.tools?.length ?? 0;
1412
+ changes.push(change("server.added", name, `new server with ${toolCount} tool${toolCount === 1 ? "" : "s"}`, { after: entry }));
1413
+ }
1414
+ for (const name of removed) {
1415
+ if (renamed.has(name)) continue;
1416
+ changes.push(change("server.removed", name, "server is no longer configured", { before: before.subjects[name] }));
1417
+ }
1418
+ for (const name of afterNames) {
1419
+ const a = before.subjects[name];
1420
+ const b = after.subjects[name];
1421
+ if (!a || !b) continue;
1422
+ changes.push(...compareServer(name, a, b));
1423
+ }
1424
+ return sortChanges(changes);
1425
+ }
1426
+
1427
+ // src/lock/io.ts
1428
+ import { readFile as readFile4, writeFile as writeFile2 } from "fs/promises";
1429
+
1430
+ // src/lock/schema.ts
1431
+ import { z as z2 } from "zod";
1432
+ var jsonValue = z2.lazy(
1433
+ () => z2.union([z2.string(), z2.number(), z2.boolean(), z2.null(), z2.array(jsonValue), z2.record(z2.string(), jsonValue)])
1434
+ );
1435
+ var jsonObject = z2.record(z2.string(), jsonValue);
1436
+ var digestString = z2.string().regex(/^sha256:[0-9a-f]{64}$/, "expected a sha256 digest");
1437
+ var icon = z2.object({
1438
+ src: z2.string(),
1439
+ mimeType: z2.string().optional(),
1440
+ sizes: z2.array(z2.string()).optional(),
1441
+ theme: z2.enum(["light", "dark"]).optional()
1442
+ });
1443
+ var annotations = z2.object({
1444
+ title: z2.string().optional(),
1445
+ readOnlyHint: z2.boolean().optional(),
1446
+ destructiveHint: z2.boolean().optional(),
1447
+ idempotentHint: z2.boolean().optional(),
1448
+ openWorldHint: z2.boolean().optional()
1449
+ });
1450
+ var behavior = z2.object({
1451
+ readOnly: z2.boolean(),
1452
+ destructive: z2.boolean(),
1453
+ idempotent: z2.boolean(),
1454
+ openWorld: z2.boolean()
1455
+ });
1456
+ var tool = z2.object({
1457
+ name: z2.string(),
1458
+ title: z2.string().optional(),
1459
+ description: z2.string().optional(),
1460
+ inputSchema: jsonObject,
1461
+ outputSchema: jsonObject.optional(),
1462
+ annotations: annotations.optional(),
1463
+ behavior,
1464
+ headerParams: z2.array(z2.string()).optional(),
1465
+ icons: z2.array(icon).optional(),
1466
+ meta: jsonObject.optional(),
1467
+ digest: digestString
1468
+ });
1469
+ var resource = z2.object({
1470
+ uri: z2.string(),
1471
+ name: z2.string(),
1472
+ title: z2.string().optional(),
1473
+ description: z2.string().optional(),
1474
+ mimeType: z2.string().optional(),
1475
+ annotations: jsonObject.optional(),
1476
+ icons: z2.array(icon).optional(),
1477
+ meta: jsonObject.optional(),
1478
+ digest: digestString
1479
+ });
1480
+ var resourceTemplate = resource.omit({ uri: true }).extend({ uriTemplate: z2.string() });
1481
+ var prompt = z2.object({
1482
+ name: z2.string(),
1483
+ title: z2.string().optional(),
1484
+ description: z2.string().optional(),
1485
+ arguments: z2.array(
1486
+ z2.object({
1487
+ name: z2.string(),
1488
+ title: z2.string().optional(),
1489
+ description: z2.string().optional(),
1490
+ required: z2.boolean().optional()
1491
+ })
1492
+ ).optional(),
1493
+ icons: z2.array(icon).optional(),
1494
+ meta: jsonObject.optional(),
1495
+ digest: digestString
1496
+ });
1497
+ var transport = z2.union([
1498
+ z2.object({
1499
+ type: z2.literal("stdio"),
1500
+ command: z2.string(),
1501
+ args: z2.array(z2.string()).optional(),
1502
+ envKeys: z2.array(z2.string()).optional(),
1503
+ cwd: z2.string().optional()
1504
+ }),
1505
+ z2.object({
1506
+ type: z2.enum(["http", "sse"]),
1507
+ url: z2.string(),
1508
+ headerKeys: z2.array(z2.string()).optional()
1509
+ })
1510
+ ]);
1511
+ var server = z2.object({
1512
+ kind: z2.literal("mcp-server"),
1513
+ source: z2.object({
1514
+ client: z2.enum(["claude-code", "claude-desktop", "vscode", "cursor", "copilot", "windsurf", "generic", "manual"]),
1515
+ file: z2.string(),
1516
+ scope: z2.enum(["project", "user", "local"]).optional()
1517
+ }),
1518
+ transport,
1519
+ protocol: z2.object({
1520
+ era: z2.enum(["modern", "legacy"]),
1521
+ version: z2.string(),
1522
+ supportedVersions: z2.array(z2.string()).optional()
1523
+ }),
1524
+ serverInfo: z2.object({
1525
+ name: z2.string().optional(),
1526
+ title: z2.string().optional(),
1527
+ version: z2.string().optional(),
1528
+ description: z2.string().optional(),
1529
+ websiteUrl: z2.string().optional()
1530
+ }).optional(),
1531
+ capabilities: jsonObject.optional(),
1532
+ instructions: z2.string().optional(),
1533
+ tools: z2.array(tool).optional(),
1534
+ resources: z2.array(resource).optional(),
1535
+ resourceTemplates: z2.array(resourceTemplate).optional(),
1536
+ prompts: z2.array(prompt).optional(),
1537
+ digest: digestString
1538
+ });
1539
+ var lockfileSchema = z2.object({
1540
+ /*
1541
+ * An unknown version is refused rather than read optimistically: a format we do not understand
1542
+ * is exactly the case where guessing produces a confident wrong answer about what changed.
1543
+ */
1544
+ lockfileVersion: z2.literal(LOCKFILE_VERSION),
1545
+ generatedBy: z2.string().optional(),
1546
+ policy: z2.object({
1547
+ ignoreMetaPrefixes: z2.array(z2.string()).optional(),
1548
+ allowUnreachable: z2.boolean().optional()
1549
+ }).optional(),
1550
+ /*
1551
+ * One map for everything pinned, each entry saying what it is. `z.discriminatedUnion` on a
1552
+ * union of one looks odd now and is the point: a second kind is a new member here, and every
1553
+ * switch over the result stops compiling until it handles it.
1554
+ */
1555
+ subjects: z2.record(z2.string(), z2.discriminatedUnion("kind", [server]))
1556
+ });
1557
+
1558
+ // src/lock/io.ts
1559
+ var DEFAULT_LOCK_FILENAME = "mcp.lock";
1560
+ var KEY_ORDER = {
1561
+ root: ["lockfileVersion", "generatedBy", "policy", "subjects"],
1562
+ policy: ["ignoreMetaPrefixes", "allowUnreachable"],
1563
+ server: ["kind", "source", "transport", "protocol", "serverInfo", "capabilities", "instructions", "tools", "resources", "resourceTemplates", "prompts", "digest"],
1564
+ source: ["client", "file", "scope"],
1565
+ transport: ["type", "command", "args", "envKeys", "cwd", "url", "headerKeys"],
1566
+ protocol: ["era", "version", "supportedVersions"],
1567
+ serverInfo: ["name", "title", "version", "description", "websiteUrl"],
1568
+ tool: ["name", "title", "description", "inputSchema", "outputSchema", "annotations", "behavior", "headerParams", "icons", "meta", "digest"],
1569
+ resource: ["uri", "name", "title", "description", "mimeType", "annotations", "icons", "meta", "digest"],
1570
+ resourceTemplate: ["uriTemplate", "name", "title", "description", "mimeType", "annotations", "icons", "meta", "digest"],
1571
+ prompt: ["name", "title", "description", "arguments", "icons", "meta", "digest"],
1572
+ promptArgument: ["name", "title", "description", "required"],
1573
+ icon: ["src", "mimeType", "sizes", "theme"]
1574
+ };
1575
+ var CHILD_KIND = {
1576
+ policy: "policy",
1577
+ source: "source",
1578
+ transport: "transport",
1579
+ protocol: "protocol",
1580
+ serverInfo: "serverInfo",
1581
+ tools: "tool",
1582
+ resources: "resource",
1583
+ resourceTemplates: "resourceTemplate",
1584
+ prompts: "prompt",
1585
+ arguments: "promptArgument",
1586
+ icons: "icon"
1587
+ };
1588
+ var INDENT = " ";
1589
+ function isPlainObject(value) {
1590
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1591
+ }
1592
+ function printScalar(value) {
1593
+ return JSON.stringify(value);
1594
+ }
1595
+ function printObject(value, kind, depth) {
1596
+ const declared = kind ? KEY_ORDER[kind] : [];
1597
+ const present = Object.keys(value).filter((key) => value[key] !== void 0);
1598
+ const ordered = kind ? [...declared.filter((key) => present.includes(key)), ...present.filter((key) => !declared.includes(key)).sort()] : present.sort();
1599
+ if (ordered.length === 0) return "{}";
1600
+ const pad = INDENT.repeat(depth + 1);
1601
+ const body = ordered.map((key) => `${pad}${JSON.stringify(key)}: ${printNode(value[key], CHILD_KIND[key], depth + 1)}`).join(",\n");
1602
+ return `{
1603
+ ${body}
1604
+ ${INDENT.repeat(depth)}}`;
1605
+ }
1606
+ function printArray(value, kind, depth) {
1607
+ if (value.length === 0) return "[]";
1608
+ if (value.every((entry) => !isPlainObject(entry) && !Array.isArray(entry))) {
1609
+ return `[${value.map(printScalar).join(", ")}]`;
1610
+ }
1611
+ const pad = INDENT.repeat(depth + 1);
1612
+ const body = value.map((entry) => `${pad}${printNode(entry, kind, depth + 1)}`).join(",\n");
1613
+ return `[
1614
+ ${body}
1615
+ ${INDENT.repeat(depth)}]`;
1616
+ }
1617
+ function printNode(value, kind, depth) {
1618
+ if (Array.isArray(value)) return printArray(value, kind, depth);
1619
+ if (isPlainObject(value)) return printObject(value, kind, depth);
1620
+ return printScalar(value);
1621
+ }
1622
+ function serializeLockfile(lock) {
1623
+ const root = {
1624
+ lockfileVersion: lock.lockfileVersion,
1625
+ generatedBy: lock.generatedBy,
1626
+ policy: lock.policy,
1627
+ // Names sorted so that adding one produces a localized diff.
1628
+ subjects: Object.fromEntries(
1629
+ Object.keys(lock.subjects).sort().map((name) => [name, lock.subjects[name]])
1630
+ )
1631
+ };
1632
+ const pad = INDENT;
1633
+ const parts = [];
1634
+ for (const key of KEY_ORDER.root) {
1635
+ const value = root[key];
1636
+ if (value === void 0) continue;
1637
+ if (key === "subjects") {
1638
+ const names = Object.keys(value);
1639
+ const body = names.length === 0 ? "{}" : `{
1640
+ ${names.map((name) => `${INDENT.repeat(2)}${JSON.stringify(name)}: ${printNode(value[name], "server", 2)}`).join(",\n")}
1641
+ ${pad}}`;
1642
+ parts.push(`${pad}${JSON.stringify(key)}: ${body}`);
1643
+ continue;
1644
+ }
1645
+ parts.push(`${pad}${JSON.stringify(key)}: ${printNode(value, CHILD_KIND[key], 1)}`);
1646
+ }
1647
+ return `{
1648
+ ${parts.join(",\n")}
1649
+ }
1650
+ `;
1651
+ }
1652
+ function upgradeFromV1(raw) {
1653
+ const servers = isPlainObject(raw["servers"]) ? raw["servers"] : {};
1654
+ const subjects = Object.fromEntries(
1655
+ Object.entries(servers).map(([name, entry]) => [name, isPlainObject(entry) ? { kind: "mcp-server", ...entry } : entry])
1656
+ );
1657
+ const { servers: _dropped, ...rest } = raw;
1658
+ return { ...rest, lockfileVersion: LOCKFILE_VERSION, subjects };
1659
+ }
1660
+ var LockfileError = class extends Error {
1661
+ };
1662
+ function parseLockfile(text, path) {
1663
+ let raw;
1664
+ try {
1665
+ raw = JSON.parse(text);
1666
+ } catch (error) {
1667
+ throw new LockfileError(`${path} is not valid JSON: ${error.message}`);
1668
+ }
1669
+ const version = isPlainObject(raw) ? raw["lockfileVersion"] : void 0;
1670
+ if (version === 1) raw = upgradeFromV1(raw);
1671
+ else if (typeof version === "number" && version !== LOCKFILE_VERSION) {
1672
+ throw new LockfileError(
1673
+ `${path} is lockfileVersion ${version}; this build understands ${LOCKFILE_VERSION}. Upgrade nulladrift rather than letting it guess.`
1674
+ );
1675
+ }
1676
+ const parsed = lockfileSchema.safeParse(raw);
1677
+ if (!parsed.success) {
1678
+ const first = parsed.error.issues[0];
1679
+ const where = first && first.path.length > 0 ? ` at ${first.path.join(".")}` : "";
1680
+ throw new LockfileError(`${path} is not a valid lockfile${where}: ${first?.message ?? "unknown error"}`);
1681
+ }
1682
+ return parsed.data;
1683
+ }
1684
+ async function readLockfile(path) {
1685
+ let text;
1686
+ try {
1687
+ text = await readFile4(path, "utf8");
1688
+ } catch (error) {
1689
+ const code = error.code;
1690
+ if (code === "ENOENT") throw new LockfileError(`no lockfile at ${path}. Run \`nulladrift init\` first.`);
1691
+ throw new LockfileError(`could not read ${path}: ${error.message}`);
1692
+ }
1693
+ return parseLockfile(text, path);
1694
+ }
1695
+ async function writeLockfile(path, lock) {
1696
+ await writeFile2(path, serializeLockfile(lock), "utf8");
1697
+ }
1698
+
1699
+ // src/lib/exit.ts
1700
+ var EXIT_CLEAN = 0;
1701
+ var EXIT_DRIFT = 1;
1702
+ var EXIT_INCOMPLETE = 2;
1703
+ function resolveExitCode(options) {
1704
+ if (options.incompleteCount > 0) return EXIT_INCOMPLETE;
1705
+ if (options.driftCount > 0) return EXIT_DRIFT;
1706
+ return EXIT_CLEAN;
1707
+ }
1708
+
1709
+ // src/report/human.ts
1710
+ var MARK = {
1711
+ high: red,
1712
+ medium: yellow,
1713
+ low: dim
1714
+ };
1715
+ function renderTextChange(before, after) {
1716
+ const lines = [];
1717
+ if (typeof before === "string") lines.push(` ${red(`- ${truncate(before)}`)}`);
1718
+ if (typeof after === "string") lines.push(` ${green(`+ ${truncate(after)}`)}`);
1719
+ return lines;
1720
+ }
1721
+ function renderChange(change2) {
1722
+ const where = change2.member ? `${change2.server} \u203A ${change2.member}` : change2.server;
1723
+ const lines = [` ${MARK[change2.severity](change2.severity.padEnd(6))} ${bold(where)} ${dim(change2.kind)}`, ` ${change2.summary}`];
1724
+ if (change2.kind === "tool.description.changed" || change2.kind === "server.instructions.changed") {
1725
+ lines.push(...renderTextChange(change2.before, change2.after));
1726
+ }
1727
+ return lines;
1728
+ }
1729
+ function renderHumanReport(report) {
1730
+ const lines = [];
1731
+ if (report.changes.length > 0) {
1732
+ lines.push("", bold(`Drift in ${new Set(report.changes.map((change2) => change2.server)).size} of ${report.serversChecked} server(s):`), "");
1733
+ for (const change2 of report.changes) lines.push(...renderChange(change2), "");
1734
+ const quiet = serversThatShippedNothing(report.changes);
1735
+ if (quiet.length > 0) {
1736
+ lines.push(
1737
+ yellow(`${quiet.length === 1 ? "This server" : "These servers"} changed without shipping a new version:`),
1738
+ ...quiet.map((server2) => ` ${bold(server2)}`),
1739
+ ""
1740
+ );
1741
+ }
1742
+ }
1743
+ if (report.unreachable.length > 0) {
1744
+ lines.push(bold(`Could not audit ${report.unreachable.length} server(s):`), "");
1745
+ for (const failure of report.unreachable) {
1746
+ const label = failure.kind === "auth" ? yellow("needs creds") : red("unreachable");
1747
+ lines.push(` ${label} ${bold(failure.server)}`, ` ${failure.reason}`, "");
1748
+ }
1749
+ }
1750
+ if (report.changes.length === 0 && report.unreachable.length === 0) {
1751
+ lines.push(green(`\u2713 ${report.serversChecked} server(s) match ${report.lockPath}`));
1752
+ return `${lines.join("\n")}
1753
+ `;
1754
+ }
1755
+ const counts = { high: 0, medium: 0, low: 0 };
1756
+ for (const change2 of report.changes) counts[change2.severity] += 1;
1757
+ if (report.changes.length > 0) {
1758
+ lines.push(dim(`${counts.high} high \xB7 ${counts.medium} medium \xB7 ${counts.low} low`));
1759
+ lines.push(dim("Review with `nulladrift review`, or accept everything with `nulladrift review --accept-all`."));
1760
+ }
1761
+ if (report.unreachable.length > 0) {
1762
+ lines.push(dim("A server that cannot be checked fails the audit. Use --allow-unreachable to downgrade that to a warning."));
1763
+ if (report.unreachable.some((failure) => failure.kind === "auth")) {
1764
+ lines.push(
1765
+ dim("`needs creds` means the server refused this client, not that it is down. The tool list a"),
1766
+ dim("server shows may depend on who is asking, so auditing without them would pin the wrong"),
1767
+ dim("surface. Run `nulladrift login <server>` once, or set oauth.clientId/clientSecret for CI.")
1768
+ );
1769
+ }
1770
+ }
1771
+ return `${lines.join("\n")}
1772
+ `;
1773
+ }
1774
+
1775
+ // src/report/json.ts
1776
+ function renderJsonReport(report, exitCode) {
1777
+ return `${JSON.stringify(
1778
+ {
1779
+ schema: 1,
1780
+ tool: { name: "nulladrift", version: VERSION },
1781
+ lockfile: report.lockPath,
1782
+ serversChecked: report.serversChecked,
1783
+ exitCode,
1784
+ summary: {
1785
+ drifted: new Set(report.changes.map((change2) => change2.server)).size,
1786
+ changes: report.changes.length,
1787
+ unreachable: report.unreachable.length
1788
+ },
1789
+ changes: report.changes.map((change2) => ({
1790
+ kind: change2.kind,
1791
+ severity: change2.severity,
1792
+ server: change2.server,
1793
+ member: change2.member,
1794
+ summary: change2.summary,
1795
+ before: change2.before,
1796
+ after: change2.after
1797
+ })),
1798
+ unreachable: report.unreachable
1799
+ },
1800
+ null,
1801
+ 2
1802
+ )}
1803
+ `;
1804
+ }
1805
+
1806
+ // src/report/sarif.ts
1807
+ import { createHash as createHash3 } from "crypto";
1808
+
1809
+ // src/lib/meta.ts
1810
+ var BUILT_IN_DOCS_URL = void 0;
1811
+ function publishedDocsUrl() {
1812
+ const override = process.env["NULLADRIFT_DOCS_URL"];
1813
+ return override !== void 0 && override !== "" ? override.replace(/\/+$/, "") : BUILT_IN_DOCS_URL;
1814
+ }
1815
+ var DEFAULT_TELEMETRY_ENDPOINT = void 0;
1816
+ function telemetryEndpoint() {
1817
+ const override = process.env["NULLADRIFT_TELEMETRY_ENDPOINT"];
1818
+ return override !== void 0 && override !== "" ? override : DEFAULT_TELEMETRY_ENDPOINT;
1819
+ }
1820
+ function helpUriFor(anchor) {
1821
+ const base = publishedDocsUrl();
1822
+ return base === void 0 ? void 0 : `${base}/blob/main/docs/lockfile.md#${anchor}`;
1823
+ }
1824
+
1825
+ // src/report/sarif.ts
1826
+ var LEVEL = {
1827
+ high: "error",
1828
+ medium: "warning",
1829
+ low: "note"
1830
+ };
1831
+ var RULE_HELP = {
1832
+ "tool.description.changed": "A tool description is injected into the model's context. A change here can carry instructions to the agent and should be read in full, not skimmed.",
1833
+ "server.instructions.changed": "The server's instructions string is placed in the model's system prompt by the client. Treat a change the way you would treat a change to prompt source.",
1834
+ "tool.behavior.escalated": "The tool now claims a power it did not claim when it was pinned. Annotation defaults are not neutral: removing readOnlyHint is an escalation.",
1835
+ "tool.input_schema.widened": "The tool accepts input it previously rejected, enlarging what the agent can be induced to send.",
1836
+ "tool.header_params.changed": "x-mcp-header mirrors an argument's value into an HTTP header, where proxies and other intermediaries can read it.",
1837
+ "server.transport.changed": "The configured name now points at a different command or URL. This is a different server, not a changed one.",
1838
+ "server.identity.changed": "The server reports a different identity or version than the one that was reviewed."
1839
+ };
1840
+ function fingerprint(change2) {
1841
+ return createHash3("sha256").update(`${change2.kind}\0${change2.server}\0${change2.member ?? ""}`).digest("hex").slice(0, 32);
1842
+ }
1843
+ function renderSarifReport(report) {
1844
+ const used = [...new Set(report.changes.map((change2) => change2.kind))].sort();
1845
+ const document = {
1846
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
1847
+ version: "2.1.0",
1848
+ runs: [
1849
+ {
1850
+ tool: {
1851
+ driver: {
1852
+ name: "nulladrift",
1853
+ version: VERSION,
1854
+ ...publishedDocsUrl() === void 0 ? {} : { informationUri: publishedDocsUrl() },
1855
+ rules: (used.length > 0 ? used : CHANGE_KINDS.slice(0, 0)).map((kind) => ({
1856
+ id: kind,
1857
+ name: kind.split(/[._]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""),
1858
+ shortDescription: { text: `MCP capability drift: ${kind}` },
1859
+ fullDescription: { text: RULE_HELP[kind] ?? "The pinned MCP capability surface no longer matches what the server reports." },
1860
+ defaultConfiguration: { level: LEVEL[SEVERITY[kind]] },
1861
+ ...helpUriFor("6-change-taxonomy") === void 0 ? {} : { helpUri: helpUriFor("6-change-taxonomy") }
1862
+ }))
1863
+ }
1864
+ },
1865
+ results: report.changes.map((change2) => ({
1866
+ ruleId: change2.kind,
1867
+ level: LEVEL[change2.severity],
1868
+ message: { text: change2.member ? `${change2.server} \u203A ${change2.member}: ${change2.summary}` : `${change2.server}: ${change2.summary}` },
1869
+ locations: [
1870
+ {
1871
+ physicalLocation: { artifactLocation: { uri: report.lockPath } },
1872
+ logicalLocations: [{ name: change2.member ?? change2.server, fullyQualifiedName: change2.member ? `${change2.server}/${change2.member}` : change2.server, kind: "member" }]
1873
+ }
1874
+ ],
1875
+ partialFingerprints: { "mcpAuditChange/v1": fingerprint(change2) }
1876
+ }))
1877
+ }
1878
+ ]
1879
+ };
1880
+ return `${JSON.stringify(document, null, 2)}
1881
+ `;
1882
+ }
1883
+
1884
+ // src/report/markdown.ts
1885
+ var MARK2 = { high: "\u{1F534}", medium: "\u{1F7E0}", low: "\u26AA" };
1886
+ function cell(text) {
1887
+ return text.replace(/\|/g, "\\|").replace(/`/g, "\\`").replace(/\r?\n/g, " ").trim();
1888
+ }
1889
+ function row(change2) {
1890
+ const where = change2.member ? `${change2.server}/${change2.member}` : change2.server;
1891
+ return `| ${MARK2[change2.severity]} ${change2.severity} | \`${cell(where)}\` | ${cell(change2.kind)} | ${cell(change2.summary)} |`;
1892
+ }
1893
+ function renderMarkdownReport(report, options = {}) {
1894
+ if (report.changes.length === 0 && report.unreachable.length === 0) return null;
1895
+ const lines = [];
1896
+ const high = report.changes.filter((change2) => change2.severity === "high").length;
1897
+ lines.push(
1898
+ high > 0 ? `### ${report.changes.length} change${report.changes.length === 1 ? "" : "s"} to what your agents can reach, ${high} high` : `### ${report.changes.length} change${report.changes.length === 1 ? "" : "s"} to what your agents can reach`,
1899
+ "",
1900
+ "A server changed what it declares. Same version, same package: the comparison is against the",
1901
+ "surface you approved, not the version string.",
1902
+ ""
1903
+ );
1904
+ if (report.changes.length > 0) {
1905
+ lines.push("| | Where | What | Detail |", "| --- | --- | --- | --- |", ...report.changes.map(row), "");
1906
+ const quiet = serversThatShippedNothing(report.changes);
1907
+ if (quiet.length > 0) {
1908
+ lines.push(
1909
+ `> **${quiet.length === 1 ? "This server" : "These servers"} changed without shipping a new version:** ${quiet.map((server2) => `\`${cell(server2)}\``).join(", ")}`,
1910
+ ">",
1911
+ "> Same package, same version, a different declaration. Nothing was published.",
1912
+ ""
1913
+ );
1914
+ }
1915
+ }
1916
+ if (report.unreachable.length > 0) {
1917
+ lines.push(
1918
+ `<details><summary>${report.unreachable.length} server${report.unreachable.length === 1 ? "" : "s"} could not be read</summary>`,
1919
+ "",
1920
+ ...report.unreachable.map(
1921
+ (failure) => `- \`${cell(failure.server)}\` \xB7 ${failure.kind === "auth" ? "refused the audit" : "unreachable"}: ${cell(failure.reason)}`
1922
+ ),
1923
+ "",
1924
+ "</details>",
1925
+ ""
1926
+ );
1927
+ }
1928
+ lines.push(
1929
+ options.url ? `Read the full diff and rule on it: ${options.url}` : "Run `nulladrift review` to read the full diff, or `nulladrift review --accept-all` to accept every change."
1930
+ );
1931
+ return lines.join("\n");
1932
+ }
1933
+
1934
+ // src/report/comment.ts
1935
+ var MARKER = "<!-- nulladrift:surface -->";
1936
+ function targetFromEnvironment(env = process.env) {
1937
+ const token = env["GITHUB_TOKEN"];
1938
+ const repo = env["GITHUB_REPOSITORY"];
1939
+ const ref = env["GITHUB_REF"];
1940
+ if (!token || !repo || !ref) return null;
1941
+ const match = /^refs\/pull\/(\d+)\//.exec(ref);
1942
+ if (!match?.[1]) return null;
1943
+ return {
1944
+ api: (env["GITHUB_API_URL"] ?? "https://api.github.com").replace(/\/+$/, ""),
1945
+ repo,
1946
+ issue: Number(match[1]),
1947
+ token
1948
+ };
1949
+ }
1950
+ async function call(target, path, init = {}) {
1951
+ return fetch(`${target.api}/repos/${target.repo}${path}`, {
1952
+ ...init,
1953
+ headers: {
1954
+ accept: "application/vnd.github+json",
1955
+ authorization: `Bearer ${target.token}`,
1956
+ "x-github-api-version": "2022-11-28",
1957
+ ...init.body ? { "content-type": "application/json" } : {},
1958
+ ...init.headers
1959
+ },
1960
+ signal: AbortSignal.timeout(1e4)
1961
+ });
1962
+ }
1963
+ async function upsertComment(target, body) {
1964
+ const marked = `${MARKER}
1965
+ ${body}`;
1966
+ const existing = await call(target, `/issues/${target.issue}/comments?per_page=100`);
1967
+ if (existing.status === 403) return "forbidden";
1968
+ if (!existing.ok) throw new Error(`could not read the comments (${existing.status})`);
1969
+ const comments = await existing.json();
1970
+ const mine = comments.find((comment2) => comment2.body?.startsWith(MARKER));
1971
+ const written = mine ? await call(target, `/issues/comments/${mine.id}`, { method: "PATCH", body: JSON.stringify({ body: marked }) }) : await call(target, `/issues/${target.issue}/comments`, { method: "POST", body: JSON.stringify({ body: marked }) });
1972
+ if (written.status === 403) return "forbidden";
1973
+ if (!written.ok) throw new Error(`could not post the comment (${written.status})`);
1974
+ return mine ? "updated" : "created";
1975
+ }
1976
+
1977
+ // src/telemetry/index.ts
1978
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
1979
+ import { mkdir as mkdir2, readFile as readFile5, rm as rm2, writeFile as writeFile3 } from "fs/promises";
1980
+ import { homedir as homedir4 } from "os";
1981
+ import { dirname as dirname2, join as join3 } from "path";
1982
+ var PAYLOAD_SCHEMA = 2;
1983
+ var SEND_TIMEOUT_MS = 2e3;
1984
+ var ID_ROTATION_MS = 30 * 24 * 60 * 60 * 1e3;
1985
+ function configPath() {
1986
+ const base = process.env["XDG_CONFIG_HOME"] ?? join3(homedir4(), ".config");
1987
+ return join3(base, "nulladrift", "config.json");
1988
+ }
1989
+ function isCi() {
1990
+ return process.env["CI"] !== void 0 && process.env["CI"] !== "false";
1991
+ }
1992
+ async function readConfig() {
1993
+ try {
1994
+ const parsed = JSON.parse(await readFile5(configPath(), "utf8"));
1995
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
1996
+ } catch {
1997
+ return {};
1998
+ }
1999
+ }
2000
+ async function writeConfig(patch) {
2001
+ const path = configPath();
2002
+ await mkdir2(dirname2(path), { recursive: true });
2003
+ await writeFile3(path, `${JSON.stringify({ ...await readConfig(), ...patch }, null, 2)}
2004
+ `, "utf8");
2005
+ }
2006
+ async function readPreference() {
2007
+ const { telemetry } = await readConfig();
2008
+ return typeof telemetry === "boolean" ? telemetry : void 0;
2009
+ }
2010
+ async function writePreference(enabled2) {
2011
+ await writeConfig({ telemetry: enabled2 });
2012
+ }
2013
+ async function clearPreference() {
2014
+ await rm2(configPath(), { force: true });
2015
+ }
2016
+ async function resolveInstallId(now = Date.now()) {
2017
+ const config = await readConfig();
2018
+ const issuedAt = config.installIdIssuedAt ? Date.parse(config.installIdIssuedAt) : Number.NaN;
2019
+ const fresh = config.installId !== void 0 && Number.isFinite(issuedAt) && now - issuedAt < ID_ROTATION_MS;
2020
+ if (fresh && config.installId !== void 0) return config.installId;
2021
+ const installId = randomUUID2();
2022
+ await writeConfig({ installId, installIdIssuedAt: new Date(now).toISOString(), lastReportHash: void 0 });
2023
+ return installId;
2024
+ }
2025
+ function buildPayload(report, changes, installId) {
2026
+ const counts = /* @__PURE__ */ new Map();
2027
+ for (const change2 of changes) counts.set(change2.kind, (counts.get(change2.kind) ?? 0) + 1);
2028
+ return {
2029
+ schema: PAYLOAD_SCHEMA,
2030
+ installId,
2031
+ // Distinguishes two runs from the same installation; not stored, and not an identifier.
2032
+ runId: randomUUID2(),
2033
+ auditVersion: VERSION,
2034
+ context: isCi() ? "ci" : "local",
2035
+ serverCount: report.serversChecked,
2036
+ driftedServerCount: new Set(changes.map((change2) => change2.server)).size,
2037
+ changes: [...counts.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([kind, count]) => ({ kind, count }))
2038
+ };
2039
+ }
2040
+ function reportHash(payload) {
2041
+ const { schema, auditVersion, context, serverCount, driftedServerCount, changes } = payload;
2042
+ return createHash4("sha256").update(JSON.stringify({ schema, auditVersion, context, serverCount, driftedServerCount, changes })).digest("hex");
2043
+ }
2044
+ async function send(payload) {
2045
+ const endpoint = telemetryEndpoint();
2046
+ if (endpoint === void 0) return false;
2047
+ try {
2048
+ const response = await fetch(endpoint, {
2049
+ method: "POST",
2050
+ headers: { "content-type": "application/json", "user-agent": `nulladrift/${VERSION}` },
2051
+ body: JSON.stringify(payload),
2052
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
2053
+ });
2054
+ return response.ok;
2055
+ } catch {
2056
+ return false;
2057
+ }
2058
+ }
2059
+ async function reportIfChanged(report, changes, now = Date.now()) {
2060
+ if (await readPreference() !== true) return "disabled";
2061
+ if (telemetryEndpoint() === void 0) return "unavailable";
2062
+ const payload = buildPayload(report, changes, await resolveInstallId(now));
2063
+ const hash = reportHash(payload);
2064
+ if ((await readConfig()).lastReportHash === hash) return "unchanged";
2065
+ if (!await send(payload)) return "failed";
2066
+ await writeConfig({ lastReportHash: hash });
2067
+ return "sent";
2068
+ }
2069
+ function describePayload(payload) {
2070
+ return JSON.stringify(payload, null, 2);
2071
+ }
2072
+
2073
+ // src/commands/check.ts
2074
+ async function buildReport(options) {
2075
+ const committed = await readLockfile(options.lockPath);
2076
+ const result = await captureAll({
2077
+ projectRoot: options.projectRoot,
2078
+ configFiles: options.configFiles,
2079
+ timeoutMs: options.timeoutMs,
2080
+ // The committed policy governs the check, so every consumer of the repo audits identically.
2081
+ policy: committed.policy
2082
+ });
2083
+ const changes = diffLockfiles(committed, result.lock);
2084
+ const allowUnreachable = options.allowUnreachable || committed.policy?.allowUnreachable === true;
2085
+ const report = {
2086
+ changes,
2087
+ unreachable: result.unreachable,
2088
+ serversChecked: Object.keys(result.lock.subjects).length,
2089
+ lockPath: options.lockPath
2090
+ };
2091
+ return {
2092
+ report,
2093
+ exitCode: resolveExitCode({
2094
+ driftCount: changes.length,
2095
+ incompleteCount: allowUnreachable ? 0 : result.unreachable.length
2096
+ })
2097
+ };
2098
+ }
2099
+ async function runCheck(options) {
2100
+ const { report, exitCode } = await buildReport(options);
2101
+ if (options.format === "json") process.stdout.write(renderJsonReport(report, exitCode));
2102
+ else if (options.format === "sarif") process.stdout.write(renderSarifReport(report));
2103
+ else process.stdout.write(renderHumanReport(report));
2104
+ await reportIfChanged(report, report.changes);
2105
+ if (options.comment) await comment(report);
2106
+ return exitCode;
2107
+ }
2108
+ async function comment(report) {
2109
+ const target = targetFromEnvironment();
2110
+ if (!target) {
2111
+ process.stderr.write(`${dim("--comment: not a pull request build, so there is nowhere to comment.")}
2112
+ `);
2113
+ return;
2114
+ }
2115
+ const body = renderMarkdownReport(report);
2116
+ if (!body) return;
2117
+ try {
2118
+ const outcome = await upsertComment(target, body);
2119
+ if (outcome === "forbidden") {
2120
+ process.stderr.write(
2121
+ `${yellow("--comment:")} the token cannot write comments on this repository. A pull request from a fork gets a read-only token; give the job \`pull-requests: write\` if it is not one.
2122
+ `
2123
+ );
2124
+ return;
2125
+ }
2126
+ process.stderr.write(`${dim(`--comment: ${outcome} the comment on #${target.issue}.`)}
2127
+ `);
2128
+ } catch (error) {
2129
+ process.stderr.write(`${yellow("--comment:")} ${error.message}
2130
+ `);
2131
+ }
2132
+ }
2133
+
2134
+ // src/commands/init.ts
2135
+ import { access } from "fs/promises";
2136
+
2137
+ // src/commands/telemetry.ts
2138
+ import { createInterface } from "readline/promises";
2139
+ var ROTATION_DAYS = Math.round(ID_ROTATION_MS / (24 * 60 * 60 * 1e3));
2140
+ var EXAMPLE = { changes: [], lockPath: "mcp.lock", serversChecked: 7, unreachable: [] };
2141
+ async function samplePayload() {
2142
+ const { installId } = await readConfig();
2143
+ return describePayload(buildPayload(EXAMPLE, [], installId ?? "\xABminted when the first report is sent\xBB"));
2144
+ }
2145
+ function privacyNotes() {
2146
+ return [
2147
+ dim(`It goes to ${telemetryEndpoint() ?? "(no collector configured)"}. No names, no URLs, no schemas, no digests.`),
2148
+ dim(`The install id is random, generated on this machine, derived from nothing about you, and`),
2149
+ dim(`rotates every ${ROTATION_DAYS} days. It exists so reports can be grouped -- without it the numbers are`),
2150
+ dim("dominated by whoever runs CI most often. A report is sent only when the picture changes,"),
2151
+ dim("not on every run. `nulladrift telemetry off` deletes the id along with the preference.")
2152
+ ];
2153
+ }
2154
+ async function maybeOfferTelemetry() {
2155
+ if (telemetryEndpoint() === void 0) return;
2156
+ if (isCi() || process.stdin.isTTY !== true || process.stdout.isTTY !== true) return;
2157
+ if (await readPreference() !== void 0) return;
2158
+ process.stdout.write(
2159
+ [
2160
+ "",
2161
+ bold("One question, asked once."),
2162
+ "Nobody knows how often MCP tool definitions actually drift. If the answer is",
2163
+ '"almost never", this tool should not exist, and we would like to find that out.',
2164
+ "",
2165
+ dim("nulladrift can send anonymous counts after a check. In full, this is everything it would send:"),
2166
+ "",
2167
+ dim(await samplePayload()),
2168
+ "",
2169
+ ...privacyNotes(),
2170
+ ""
2171
+ ].join("\n")
2172
+ );
2173
+ const readline = createInterface({ input: process.stdin, output: process.stdout });
2174
+ try {
2175
+ const answer = (await readline.question(" Send anonymous drift counts? [y/N] ")).trim().toLowerCase();
2176
+ const enabled2 = answer === "y" || answer === "yes";
2177
+ await writePreference(enabled2);
2178
+ process.stdout.write(` ${enabled2 ? green("thank you, telemetry on") : dim("telemetry stays off")}
2179
+
2180
+ `);
2181
+ } finally {
2182
+ readline.close();
2183
+ }
2184
+ }
2185
+ async function runTelemetry(subcommand) {
2186
+ switch (subcommand) {
2187
+ case "on":
2188
+ await writePreference(true);
2189
+ process.stdout.write(
2190
+ telemetryEndpoint() === void 0 ? `${green("telemetry on")}
2191
+ ${dim(" No collector is configured in this build, so nothing will be sent until one is.")}
2192
+ ` : `${green("telemetry on")}
2193
+ `
2194
+ );
2195
+ return EXIT_CLEAN;
2196
+ case "off":
2197
+ await clearPreference();
2198
+ process.stdout.write(`${dim("telemetry off; stored preference and install id deleted")}
2199
+ `);
2200
+ return EXIT_CLEAN;
2201
+ case "status":
2202
+ case void 0: {
2203
+ const config = await readConfig();
2204
+ const issued = config.installIdIssuedAt ? new Date(config.installIdIssuedAt) : void 0;
2205
+ process.stdout.write(
2206
+ [
2207
+ `telemetry: ${config.telemetry === true ? green("on") : dim(config.telemetry === false ? "off" : "off (never asked)")}`,
2208
+ `endpoint: ${telemetryEndpoint() ?? dim("none configured, nothing is sent")}`,
2209
+ `install id: ${config.installId ?? dim("none yet")}${issued ? dim(` (issued ${issued.toISOString().slice(0, 10)}, rotates every ${ROTATION_DAYS} days)`) : ""}`,
2210
+ "",
2211
+ "A report contains these fields and nothing else (counts here are illustrative):",
2212
+ await samplePayload(),
2213
+ "",
2214
+ ...privacyNotes(),
2215
+ ""
2216
+ ].join("\n")
2217
+ );
2218
+ return EXIT_CLEAN;
2219
+ }
2220
+ default:
2221
+ process.stderr.write(`unknown telemetry subcommand "${subcommand}". Use on, off or status.
2222
+ `);
2223
+ return EXIT_CLEAN;
2224
+ }
2225
+ }
2226
+
2227
+ // src/commands/init.ts
2228
+ async function exists(path) {
2229
+ try {
2230
+ await access(path);
2231
+ return true;
2232
+ } catch {
2233
+ return false;
2234
+ }
2235
+ }
2236
+ async function runInit(options) {
2237
+ if (!options.force && await exists(options.lockPath)) {
2238
+ process.stderr.write(
2239
+ [
2240
+ red(`${options.lockPath} already exists.`),
2241
+ dim("init would replace the reviewed baseline with whatever the servers answer right now."),
2242
+ "",
2243
+ ` nulladrift check ${dim("see what moved")}`,
2244
+ ` nulladrift review ${dim("read each change and accept it")}`,
2245
+ ` nulladrift init --force ${dim("discard the existing lock and pin again from scratch")}`,
2246
+ ""
2247
+ ].join("\n")
2248
+ );
2249
+ return EXIT_INCOMPLETE;
2250
+ }
2251
+ const result = await captureAll({
2252
+ projectRoot: options.projectRoot,
2253
+ configFiles: options.configFiles,
2254
+ timeoutMs: options.timeoutMs
2255
+ });
2256
+ const names = Object.keys(result.lock.subjects);
2257
+ if (names.length === 0 && result.unreachable.length === 0) {
2258
+ process.stderr.write(
2259
+ `No MCP servers found.
2260
+ ${dim(`Looked in: ${result.discovery.filesRead.length > 0 ? result.discovery.filesRead.join(", ") : "no client config files exist for this project"}`)}
2261
+ `
2262
+ );
2263
+ return EXIT_CLEAN;
2264
+ }
2265
+ await writeLockfile(options.lockPath, result.lock);
2266
+ const lines = ["", bold(`Pinned ${names.length} server(s) to ${options.lockPath}:`), ""];
2267
+ for (const name of names) {
2268
+ const entry = result.lock.subjects[name];
2269
+ const counts = [
2270
+ `${entry?.tools?.length ?? 0} tools`,
2271
+ `${entry?.resources?.length ?? 0} resources`,
2272
+ `${entry?.resourceTemplates?.length ?? 0} templates`,
2273
+ `${entry?.prompts?.length ?? 0} prompts`
2274
+ ].join(", ");
2275
+ lines.push(` ${green("\u2713")} ${bold(name)} ${dim(counts)}`);
2276
+ const deprecated = entry?.transport.type === "sse" ? " \xB7 HTTP+SSE transport is deprecated in the spec" : "";
2277
+ lines.push(` ${dim(`${entry?.protocol.era}/${entry?.protocol.version} \xB7 from ${entry?.source.file}${deprecated}`)}`);
2278
+ }
2279
+ for (const failure of result.unreachable) {
2280
+ lines.push(` ${red("\u2717")} ${bold(failure.server)} ${dim("not pinned")}`, ` ${failure.reason}`);
2281
+ }
2282
+ for (const shadow of result.discovery.shadowed) {
2283
+ lines.push(dim(` note: "${shadow.name}" is defined in both ${shadow.keptFrom} and ${shadow.alsoIn}; kept the first.`));
2284
+ }
2285
+ lines.push("", dim("Commit mcp.lock. `nulladrift check` in CI will fail if any of this changes."), "");
2286
+ process.stdout.write(lines.join("\n"));
2287
+ await maybeOfferTelemetry();
2288
+ if (result.unreachable.length > 0 && !options.allowUnreachable) return EXIT_INCOMPLETE;
2289
+ return EXIT_CLEAN;
2290
+ }
2291
+
2292
+ // src/commands/login.ts
2293
+ import { createServer } from "http";
2294
+ import { auth } from "@modelcontextprotocol/client";
2295
+ import { rm as rm3 } from "fs/promises";
2296
+ var CALLBACK_TIMEOUT_MS = 5 * 60 * 1e3;
2297
+ async function awaitCallback(expectedState) {
2298
+ let settle;
2299
+ let fail;
2300
+ const server2 = createServer((request, response) => {
2301
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
2302
+ if (url.pathname !== DEFAULT_CALLBACK_PATH) {
2303
+ response.writeHead(404).end("not found");
2304
+ return;
2305
+ }
2306
+ const error = url.searchParams.get("error");
2307
+ const code = url.searchParams.get("code");
2308
+ const state = url.searchParams.get("state");
2309
+ if (error !== null) {
2310
+ response.writeHead(400, { "content-type": "text/plain" }).end(`authorization failed: ${error}`);
2311
+ fail?.(new Error(`${error}${url.searchParams.get("error_description") ? `: ${url.searchParams.get("error_description")}` : ""}`));
2312
+ return;
2313
+ }
2314
+ if (code === null) {
2315
+ response.writeHead(400, { "content-type": "text/plain" }).end("no authorization code in the callback");
2316
+ fail?.(new Error("callback carried no authorization code"));
2317
+ return;
2318
+ }
2319
+ if (state !== expectedState) {
2320
+ response.writeHead(400, { "content-type": "text/plain" }).end("state mismatch");
2321
+ fail?.(new Error("state parameter did not match; the login was not completed"));
2322
+ return;
2323
+ }
2324
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end("<!doctype html><title>nulladrift</title><p>Authorized. You can close this tab.");
2325
+ settle?.({ code, state, iss: url.searchParams.get("iss") ?? void 0 });
2326
+ });
2327
+ await new Promise((ready, broke) => {
2328
+ server2.once("error", broke);
2329
+ server2.listen(0, "127.0.0.1", ready);
2330
+ });
2331
+ const { port } = server2.address();
2332
+ const received = new Promise((resolve4, reject) => {
2333
+ settle = resolve4;
2334
+ fail = reject;
2335
+ setTimeout(() => reject(new Error(`no callback within ${CALLBACK_TIMEOUT_MS / 1e3}s`)), CALLBACK_TIMEOUT_MS).unref();
2336
+ });
2337
+ return {
2338
+ redirectUrl: `http://127.0.0.1:${port}${DEFAULT_CALLBACK_PATH}`,
2339
+ wait: () => received,
2340
+ close: () => server2.close()
2341
+ };
2342
+ }
2343
+ async function findServer(projectRoot, configFiles, name) {
2344
+ const discovery = await discoverServers(projectRoot, configFiles);
2345
+ const server2 = discovery.servers.find((candidate) => candidate.name === name);
2346
+ if (!server2) {
2347
+ const known = discovery.servers.map((candidate) => candidate.name);
2348
+ return { error: known.length === 0 ? "no MCP servers found in this project" : `no server named "${name}". Known: ${known.join(", ")}` };
2349
+ }
2350
+ if (server2.transport.type === "stdio") return { error: `"${name}" is a stdio server; it is launched locally and has nothing to log in to` };
2351
+ return server2;
2352
+ }
2353
+ async function runLogin(options) {
2354
+ if (options.serverName === void 0) {
2355
+ process.stderr.write(`${red("which server?")} ${dim("Usage: nulladrift login <server>")}
2356
+ `);
2357
+ return EXIT_INCOMPLETE;
2358
+ }
2359
+ const found = await findServer(options.projectRoot, options.configFiles, options.serverName);
2360
+ if ("error" in found) {
2361
+ process.stderr.write(`${red(found.error)}
2362
+ `);
2363
+ return EXIT_INCOMPLETE;
2364
+ }
2365
+ const serverUrl = found.transport.type === "stdio" ? "" : found.transport.url;
2366
+ const provider = new FileTokenProvider(found.name, serverUrl, { interactive: true });
2367
+ const callback = await awaitCallback(provider.stateValue);
2368
+ const authenticating = new FileTokenProvider(found.name, serverUrl, { interactive: true, redirectUrl: callback.redirectUrl });
2369
+ Object.assign(authenticating, { stateValue: provider.stateValue });
2370
+ try {
2371
+ process.stdout.write(`${bold(`Authorizing ${found.name}`)}
2372
+ ${dim(serverUrl)}
2373
+ `);
2374
+ const started = await auth(authenticating, { serverUrl });
2375
+ if (started === "AUTHORIZED") {
2376
+ process.stdout.write(`${green("\u2713 already authorized")}
2377
+ `);
2378
+ return EXIT_CLEAN;
2379
+ }
2380
+ const { code, iss } = await callback.wait();
2381
+ const finished = await auth(authenticating, { serverUrl, authorizationCode: code, ...iss === void 0 ? {} : { iss } });
2382
+ if (finished !== "AUTHORIZED") {
2383
+ process.stderr.write(`${red("authorization did not complete")}
2384
+ `);
2385
+ return EXIT_INCOMPLETE;
2386
+ }
2387
+ process.stdout.write(`${green(`\u2713 authorized ${found.name}`)}
2388
+ ${dim(`tokens stored in ${credentialPath(serverUrl)} (owner-only)`)}
2389
+ `);
2390
+ return EXIT_CLEAN;
2391
+ } catch (error) {
2392
+ process.stderr.write(`${red("login failed:")} ${error.message}
2393
+ `);
2394
+ return EXIT_INCOMPLETE;
2395
+ } finally {
2396
+ callback.close();
2397
+ }
2398
+ }
2399
+ async function runLogout(options) {
2400
+ if (options.serverName === void 0) {
2401
+ process.stderr.write(`${red("which server?")} ${dim("Usage: nulladrift logout <server>")}
2402
+ `);
2403
+ return EXIT_INCOMPLETE;
2404
+ }
2405
+ const found = await findServer(options.projectRoot, options.configFiles, options.serverName);
2406
+ if ("error" in found) {
2407
+ process.stderr.write(`${red(found.error)}
2408
+ `);
2409
+ return EXIT_INCOMPLETE;
2410
+ }
2411
+ const url = found.transport.type === "stdio" ? "" : found.transport.url;
2412
+ await rm3(credentialPath(url), { force: true });
2413
+ process.stdout.write(`${dim(`stored credentials for ${found.name} deleted`)}
2414
+ `);
2415
+ return EXIT_CLEAN;
2416
+ }
2417
+
2418
+ // src/report/push-error.ts
2419
+ function envelope(body) {
2420
+ try {
2421
+ const parsed = JSON.parse(body);
2422
+ const code = parsed.error?.code;
2423
+ const message = parsed.error?.message;
2424
+ if (typeof code !== "string" || typeof message !== "string") return null;
2425
+ return { code, message };
2426
+ } catch {
2427
+ return null;
2428
+ }
2429
+ }
2430
+ function describeRefusal(status, body) {
2431
+ const error = envelope(body);
2432
+ if (status === 402 && error?.code === "plan_limit") {
2433
+ return {
2434
+ planLimit: true,
2435
+ text: [
2436
+ "this organization is at its plan limit, so the reading was not recorded",
2437
+ "",
2438
+ ` ${error.message}`,
2439
+ "",
2440
+ // Said plainly because the person reading it is usually not the person who can fix it,
2441
+ // and their first instinct will be that they broke the build.
2442
+ "Nothing is wrong with this build or with the servers it audited. An owner or admin of",
2443
+ "the organization can raise the limit, and the next push will record normally."
2444
+ ].join("\n")
2445
+ };
2446
+ }
2447
+ if (status === 401 || status === 403) {
2448
+ return {
2449
+ planLimit: false,
2450
+ text: `the control plane refused this token (${status}): ${error?.message ?? body.slice(0, 300)}`
2451
+ };
2452
+ }
2453
+ return {
2454
+ planLimit: false,
2455
+ text: `control plane answered ${status}: ${error?.message ?? body.slice(0, 500)}`
2456
+ };
2457
+ }
2458
+
2459
+ // src/commands/push.ts
2460
+ function inferProject(projectRoot) {
2461
+ const fromCi = process.env["GITHUB_REPOSITORY"] ?? process.env["CI_PROJECT_PATH"] ?? process.env["BUILD_REPOSITORY_NAME"];
2462
+ if (fromCi) return fromCi;
2463
+ return projectRoot.split("/").filter(Boolean).pop() ?? "default";
2464
+ }
2465
+ function inferRef() {
2466
+ return process.env["GITHUB_REF_NAME"] ?? process.env["CI_COMMIT_REF_NAME"] ?? void 0;
2467
+ }
2468
+ function inferCommit() {
2469
+ return process.env["GITHUB_SHA"] ?? process.env["CI_COMMIT_SHA"] ?? void 0;
2470
+ }
2471
+ async function runPush(options) {
2472
+ const apiUrl = (options.apiUrl ?? process.env["NULLADRIFT_API_URL"] ?? "").replace(/\/+$/, "");
2473
+ const token = options.token ?? process.env["NULLADRIFT_TOKEN"] ?? "";
2474
+ if (!apiUrl || !token) {
2475
+ process.stderr.write(
2476
+ [
2477
+ red("push needs a control plane to push to."),
2478
+ dim(" --api <url> or NULLADRIFT_API_URL"),
2479
+ dim(" --token <token> or NULLADRIFT_TOKEN"),
2480
+ ""
2481
+ ].join("\n")
2482
+ );
2483
+ return EXIT_INCOMPLETE;
2484
+ }
2485
+ const result = await captureAll({
2486
+ projectRoot: options.projectRoot,
2487
+ configFiles: options.configFiles,
2488
+ timeoutMs: options.timeoutMs
2489
+ });
2490
+ const servers = Object.entries(result.lock.subjects).map(([name, entry]) => ({
2491
+ name,
2492
+ transport: entry.transport.type,
2493
+ protocolEra: entry.protocol.era,
2494
+ protocolVersion: entry.protocol.version,
2495
+ client: entry.source.client,
2496
+ sourceFile: entry.source.file,
2497
+ serverInfo: entry.serverInfo,
2498
+ digest: entry.digest,
2499
+ toolCount: entry.tools?.length ?? 0,
2500
+ resourceCount: entry.resources?.length ?? 0,
2501
+ promptCount: entry.prompts?.length ?? 0,
2502
+ surface: entry
2503
+ }));
2504
+ const body = {
2505
+ project: options.project ?? inferProject(options.projectRoot),
2506
+ ref: options.ref ?? inferRef(),
2507
+ commit: options.commit ?? inferCommit(),
2508
+ context: options.watch ? "watch" : process.env["CI"] !== void 0 && process.env["CI"] !== "false" ? "ci" : "local",
2509
+ collectorVersion: VERSION,
2510
+ servers,
2511
+ unreachable: result.unreachable.map((failure) => ({ server: failure.server, reason: failure.reason }))
2512
+ };
2513
+ let response;
2514
+ try {
2515
+ response = await fetch(`${apiUrl}/api/v1/ingest`, {
2516
+ method: "POST",
2517
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
2518
+ body: JSON.stringify(body),
2519
+ signal: AbortSignal.timeout(options.timeoutMs)
2520
+ });
2521
+ } catch (error) {
2522
+ process.stderr.write(`${red("could not reach the control plane:")} ${error.message}
2523
+ `);
2524
+ return EXIT_INCOMPLETE;
2525
+ }
2526
+ if (!response.ok) {
2527
+ const refusal = describeRefusal(response.status, await response.text());
2528
+ process.stderr.write(`${refusal.planLimit ? yellow("plan limit:") : red("push failed:")} ${refusal.text}
2529
+ `);
2530
+ return EXIT_INCOMPLETE;
2531
+ }
2532
+ const verdict = await response.json();
2533
+ const lines = [""];
2534
+ const mark = verdict.verdict === "clean" ? green("\u2713") : verdict.verdict === "drift" ? yellow("!") : red("\u2717");
2535
+ lines.push(`${mark} ${bold(verdict.verdict)} ${dim(`\xB7 ${servers.length} server(s) \xB7 reading ${verdict.readingId.slice(0, 8)}`)}`);
2536
+ for (const change2 of verdict.changes) {
2537
+ lines.push(` ${change2.severity === "high" ? red("\u25CF") : change2.severity === "medium" ? yellow("\u25CF") : dim("\u25CF")} ${bold(change2.server)}${change2.member ? dim(`/${change2.member}`) : ""} ${change2.summary}`);
2538
+ }
2539
+ for (const reason of verdict.decision.reasons) {
2540
+ lines.push(` ${red("blocked")} ${dim(reason.code)} ${reason.message}`);
2541
+ }
2542
+ if (verdict.verdict !== "clean") lines.push("", dim(`Review it at ${verdict.url}`));
2543
+ lines.push("");
2544
+ process.stdout.write(lines.join("\n"));
2545
+ return verdict.exitCode === 0 ? EXIT_CLEAN : verdict.exitCode === 1 ? EXIT_DRIFT : EXIT_INCOMPLETE;
2546
+ }
2547
+
2548
+ // src/commands/review.ts
2549
+ import { createInterface as createInterface2 } from "readline/promises";
2550
+ function describe(change2) {
2551
+ const head = ` ${change2.severity === "high" ? red("\u25CF") : change2.severity === "medium" ? yellow("\u25CF") : dim("\u25CF")} ${change2.member ? `${bold(change2.member)}: ` : ""}${change2.summary} ${dim(change2.kind)}`;
2552
+ if (change2.kind !== "tool.description.changed" && change2.kind !== "server.instructions.changed") return head;
2553
+ const before = typeof change2.before === "string" ? `
2554
+ ${red(`- ${truncate(change2.before, 220)}`)}` : "";
2555
+ const after = typeof change2.after === "string" ? `
2556
+ ${green(`+ ${truncate(change2.after, 220)}`)}` : "";
2557
+ return `${head}${before}${after}`;
2558
+ }
2559
+ async function runReview(options) {
2560
+ const committed = await readLockfile(options.lockPath);
2561
+ const result = await captureAll({
2562
+ projectRoot: options.projectRoot,
2563
+ configFiles: options.configFiles,
2564
+ timeoutMs: options.timeoutMs,
2565
+ policy: committed.policy
2566
+ });
2567
+ const changes = diffLockfiles(committed, result.lock);
2568
+ if (changes.length === 0) {
2569
+ process.stdout.write(`${green(`\u2713 nothing to review; ${options.lockPath} is up to date`)}
2570
+ `);
2571
+ return result.unreachable.length > 0 && !options.allowUnreachable ? EXIT_INCOMPLETE : EXIT_CLEAN;
2572
+ }
2573
+ const grouped = /* @__PURE__ */ new Map();
2574
+ for (const change2 of changes) {
2575
+ const bucket = grouped.get(change2.server) ?? [];
2576
+ bucket.push(change2);
2577
+ grouped.set(change2.server, bucket);
2578
+ }
2579
+ const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true;
2580
+ if (!options.acceptAll && !interactive) {
2581
+ process.stderr.write(
2582
+ `${red("review needs a terminal.")} Run it locally, or pass --accept-all to take every change without reading it.
2583
+ `
2584
+ );
2585
+ return EXIT_INCOMPLETE;
2586
+ }
2587
+ const next = { ...committed, subjects: { ...committed.subjects }, generatedBy: result.lock.generatedBy };
2588
+ const readline = options.acceptAll ? void 0 : createInterface2({ input: process.stdin, output: process.stdout });
2589
+ let accepted = 0;
2590
+ let declined = 0;
2591
+ try {
2592
+ for (const [serverName, serverChanges] of grouped) {
2593
+ process.stdout.write(`
2594
+ ${bold(serverName)}
2595
+ ${serverChanges.map(describe).join("\n")}
2596
+ `);
2597
+ let take = options.acceptAll;
2598
+ if (readline) {
2599
+ const answer = (await readline.question(`
2600
+ Accept these ${serverChanges.length} change(s) into the lock? [y/N] `)).trim().toLowerCase();
2601
+ take = answer === "y" || answer === "yes";
2602
+ }
2603
+ if (!take) {
2604
+ declined += 1;
2605
+ continue;
2606
+ }
2607
+ accepted += 1;
2608
+ const fresh = result.lock.subjects[serverName];
2609
+ if (fresh) next.subjects[serverName] = fresh;
2610
+ else delete next.subjects[serverName];
2611
+ for (const change2 of serverChanges) {
2612
+ if (change2.kind === "server.renamed" && typeof change2.before === "string") delete next.subjects[change2.before];
2613
+ }
2614
+ }
2615
+ } finally {
2616
+ readline?.close();
2617
+ }
2618
+ if (accepted > 0) {
2619
+ await writeLockfile(options.lockPath, next);
2620
+ process.stdout.write(`
2621
+ ${green(`\u2713 accepted ${accepted} server(s) into ${options.lockPath}`)}
2622
+ `);
2623
+ }
2624
+ if (declined > 0) process.stdout.write(`${yellow(`${declined} server(s) left unaccepted; \`check\` will still fail on them.`)}
2625
+ `);
2626
+ if (result.unreachable.length > 0 && !options.allowUnreachable) return EXIT_INCOMPLETE;
2627
+ return declined > 0 ? EXIT_DRIFT : EXIT_CLEAN;
2628
+ }
2629
+
2630
+ // src/index.ts
2631
+ var HELP = `${bold("nulladrift")} ${VERSION} - pin what your MCP servers are allowed to do
2632
+
2633
+ ${bold("Usage")}
2634
+ nulladrift init discover servers, capture capabilities, write the lock
2635
+ nulladrift check re-capture, diff against the lock, fail on drift
2636
+ nulladrift review show what changed and accept it into the lock
2637
+ nulladrift push send the surface to a control plane, which decides the verdict
2638
+ nulladrift login <server> authorize a remote server once, in a browser
2639
+ nulladrift logout <server> delete the stored credentials for a server
2640
+ nulladrift telemetry <on|off|status>
2641
+
2642
+ ${bold("Options")}
2643
+ --lock <path> lockfile to read or write (default: ./${DEFAULT_LOCK_FILENAME})
2644
+ --cwd <path> project root to scan for client configs (default: current directory)
2645
+ --config <path> audit this config file too; repeatable
2646
+ --timeout <ms> per-server timeout (default: ${DEFAULT_TIMEOUT_MS})
2647
+ --allow-unreachable a server that cannot be reached warns instead of failing
2648
+ --json machine-readable output (check)
2649
+ --sarif SARIF 2.1.0 output (check)
2650
+ --accept-all accept every change without prompting (review)
2651
+ --force re-pin over an existing lockfile, discarding it (init)
2652
+ --api <url> control plane to push to (push; or NULLADRIFT_API_URL)
2653
+ --token <token> collector token (push; or NULLADRIFT_TOKEN)
2654
+ --project <name> project name to report under (push; inferred from CI otherwise)
2655
+ --watch mark this as a scheduled reading rather than one a build asked for (push)
2656
+ --comment post the findings on the pull request being reviewed (check; needs CI)
2657
+ -h, --help this text
2658
+ -v, --version print the version
2659
+
2660
+ ${bold("Exit codes")}
2661
+ 0 everything matches the lock
2662
+ 1 drift detected
2663
+ 2 the audit could not be completed (server unreachable, or config/lockfile unreadable)
2664
+ If both happen at once the code is 2: an incomplete audit cannot claim the drift it
2665
+ found is the only drift there is.
2666
+ `;
2667
+ async function main() {
2668
+ const { values, positionals } = parseArgs({
2669
+ allowPositionals: true,
2670
+ options: {
2671
+ lock: { type: "string" },
2672
+ cwd: { type: "string" },
2673
+ config: { type: "string", multiple: true },
2674
+ timeout: { type: "string" },
2675
+ "allow-unreachable": { type: "boolean", default: false },
2676
+ json: { type: "boolean", default: false },
2677
+ sarif: { type: "boolean", default: false },
2678
+ "accept-all": { type: "boolean", default: false },
2679
+ force: { type: "boolean", default: false },
2680
+ api: { type: "string" },
2681
+ token: { type: "string" },
2682
+ project: { type: "string" },
2683
+ watch: { type: "boolean", default: false },
2684
+ comment: { type: "boolean", default: false },
2685
+ help: { type: "boolean", short: "h", default: false },
2686
+ version: { type: "boolean", short: "v", default: false }
2687
+ }
2688
+ });
2689
+ if (values.version) {
2690
+ process.stdout.write(`${VERSION}
2691
+ `);
2692
+ return EXIT_CLEAN;
2693
+ }
2694
+ const command = positionals[0];
2695
+ if (values.help || command === void 0 || command === "help") {
2696
+ process.stdout.write(`${HELP}
2697
+ `);
2698
+ return command === void 0 && !values.help ? EXIT_INCOMPLETE : EXIT_CLEAN;
2699
+ }
2700
+ if (values.json && values.sarif) {
2701
+ process.stderr.write(`${red("--json and --sarif are mutually exclusive.")}
2702
+ `);
2703
+ return EXIT_INCOMPLETE;
2704
+ }
2705
+ const timeoutMs = values.timeout === void 0 ? DEFAULT_TIMEOUT_MS : Number.parseInt(values.timeout, 10);
2706
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
2707
+ process.stderr.write(`${red(`--timeout must be a positive number of milliseconds, got "${values.timeout}".`)}
2708
+ `);
2709
+ return EXIT_INCOMPLETE;
2710
+ }
2711
+ const projectRoot = resolve3(values.cwd ?? process.cwd());
2712
+ const options = {
2713
+ projectRoot,
2714
+ lockPath: resolve3(projectRoot, values.lock ?? DEFAULT_LOCK_FILENAME),
2715
+ configFiles: values.config ?? [],
2716
+ timeoutMs,
2717
+ allowUnreachable: values["allow-unreachable"],
2718
+ format: values.sarif ? "sarif" : values.json ? "json" : "human",
2719
+ comment: values.comment
2720
+ };
2721
+ switch (command) {
2722
+ case "init":
2723
+ return runInit({ ...options, force: values.force });
2724
+ case "check":
2725
+ return runCheck(options);
2726
+ case "push":
2727
+ return runPush({ ...options, apiUrl: values.api, token: values.token, project: values.project, watch: values.watch });
2728
+ case "review":
2729
+ return runReview({ ...options, acceptAll: values["accept-all"] });
2730
+ case "login":
2731
+ return runLogin({ projectRoot, configFiles: options.configFiles, serverName: positionals[1] });
2732
+ case "logout":
2733
+ return runLogout({ projectRoot, configFiles: options.configFiles, serverName: positionals[1] });
2734
+ case "telemetry":
2735
+ return runTelemetry(positionals[1]);
2736
+ default:
2737
+ process.stderr.write(`${red(`unknown command "${command}".`)}
2738
+ ${dim("Run `nulladrift --help`.")}
2739
+ `);
2740
+ return EXIT_INCOMPLETE;
2741
+ }
2742
+ }
2743
+ main().then((code) => {
2744
+ process.exitCode = code;
2745
+ setTimeout(() => process.exit(code), 2e3).unref();
2746
+ }).catch((error) => {
2747
+ const message = error instanceof LockfileError ? error.message : error.stack ?? String(error);
2748
+ process.stderr.write(`${red("nulladrift failed:")} ${message}
2749
+ `);
2750
+ process.exitCode = EXIT_INCOMPLETE;
2751
+ });
2752
+ //# sourceMappingURL=index.js.map