nulladrift 0.1.5 → 0.3.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 CHANGED
@@ -4,366 +4,122 @@
4
4
  import { parseArgs } from "util";
5
5
  import { resolve as resolve3 } from "path";
6
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 visibleControls(text) {
17
- return text.replace(
18
- // C0 and C1 controls and DEL, plus the bidirectional overrides and zero-width characters
19
- // that change what a line appears to say without changing what it is.
20
- // eslint-disable-next-line no-control-regex
21
- /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g,
22
- (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
7
+ // ../core/src/changes.ts
8
+ var CHANGE_KINDS = [
9
+ "server.added",
10
+ "server.removed",
11
+ "server.renamed",
12
+ "server.transport.changed",
13
+ "server.identity.changed",
14
+ "server.protocol.changed",
15
+ "server.instructions.changed",
16
+ "server.capabilities.widened",
17
+ "server.capabilities.narrowed",
18
+ "server.capabilities.changed",
19
+ "tool.added",
20
+ "tool.removed",
21
+ "tool.description.changed",
22
+ "tool.input_schema.widened",
23
+ "tool.input_schema.narrowed",
24
+ "tool.input_schema.changed",
25
+ "tool.output_schema.changed",
26
+ "tool.behavior.escalated",
27
+ "tool.behavior.relaxed",
28
+ "tool.header_params.changed",
29
+ "tool.capability.gained",
30
+ "tool.changed",
31
+ "resource.added",
32
+ "resource.removed",
33
+ "resource.changed",
34
+ "resource_template.added",
35
+ "resource_template.removed",
36
+ "resource_template.changed",
37
+ "prompt.added",
38
+ "prompt.removed",
39
+ "prompt.changed"
40
+ ];
41
+ var SEVERITY = {
42
+ "server.added": "medium",
43
+ "server.removed": "low",
44
+ "server.renamed": "low",
45
+ "server.transport.changed": "high",
46
+ "server.identity.changed": "medium",
47
+ "server.protocol.changed": "medium",
48
+ "server.instructions.changed": "high",
49
+ "server.capabilities.widened": "medium",
50
+ "server.capabilities.narrowed": "low",
51
+ "server.capabilities.changed": "medium",
52
+ "tool.added": "high",
53
+ "tool.removed": "low",
54
+ "tool.description.changed": "high",
55
+ "tool.input_schema.widened": "high",
56
+ "tool.input_schema.narrowed": "low",
57
+ "tool.input_schema.changed": "medium",
58
+ "tool.output_schema.changed": "medium",
59
+ "tool.behavior.escalated": "high",
60
+ "tool.behavior.relaxed": "low",
61
+ "tool.header_params.changed": "high",
62
+ /*
63
+ * Severity is set per change rather than read from here: what a tool gained decides it. A
64
+ * `command` argument is not the same finding as a `url` one, and flattening both to one number
65
+ * is how "accepts input it did not before" came to describe arbitrary command execution.
66
+ */
67
+ "tool.capability.gained": "high",
68
+ "tool.changed": "medium",
69
+ "resource.added": "medium",
70
+ "resource.removed": "low",
71
+ "resource.changed": "medium",
72
+ "resource_template.added": "high",
73
+ "resource_template.removed": "low",
74
+ "resource_template.changed": "high",
75
+ "prompt.added": "medium",
76
+ "prompt.removed": "low",
77
+ "prompt.changed": "medium"
78
+ };
79
+ var SEVERITY_RANK = { high: 0, medium: 1, low: 2 };
80
+ function sortChanges(changes) {
81
+ return [...changes].sort(
82
+ (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)
23
83
  );
24
84
  }
25
- function truncate(text, limit = 160) {
26
- const collapsed = visibleControls(text).replace(/\s+/g, " ").trim();
27
- return collapsed.length <= limit ? collapsed : `${collapsed.slice(0, limit - 1)}\u2026`;
85
+ function serversThatShippedNothing(changes) {
86
+ const moved = /* @__PURE__ */ new Set();
87
+ const versioned = /* @__PURE__ */ new Set();
88
+ for (const change2 of changes) {
89
+ moved.add(change2.server);
90
+ if (change2.kind === "server.identity.changed") versioned.add(change2.server);
91
+ }
92
+ return [...moved].filter((server2) => !versioned.has(server2)).sort();
28
93
  }
29
94
 
30
- // src/config/discover.ts
31
- import { readFile as readFile2 } from "fs/promises";
32
- import { homedir as homedir2, platform } from "os";
33
- import { isAbsolute, join, relative, resolve as resolve2, sep } from "path";
34
-
35
- // src/config/parsers.ts
36
- import { readFile } from "fs/promises";
37
- import { resolve } from "path";
38
- import { z } from "zod";
39
-
40
- // src/config/expand.ts
41
- import { homedir } from "os";
42
- var PLACEHOLDER = /\$\{([^}]+)\}/g;
43
- function expand(input, context) {
44
- const unresolved = [];
45
- const value = input.replace(PLACEHOLDER, (match, body) => {
46
- if (body === "workspaceFolder") return context.workspaceFolder;
47
- if (body === "userHome") return homedir();
48
- if (body === "pathSeparator" || body === "/") return "/";
49
- if (body.startsWith("input:") || body.startsWith("command:")) {
50
- unresolved.push(match);
51
- return match;
52
- }
53
- if (body.startsWith("env:")) {
54
- const name = body.slice(4);
55
- const found2 = context.env[name];
56
- if (found2 !== void 0) return found2;
57
- unresolved.push(match);
58
- return match;
59
- }
60
- const defaultAt = body.indexOf(":-");
61
- if (defaultAt !== -1) {
62
- const name = body.slice(0, defaultAt);
63
- return context.env[name] ?? body.slice(defaultAt + 2);
64
- }
65
- const found = context.env[body];
66
- if (found !== void 0) return found;
67
- unresolved.push(match);
68
- return match;
69
- });
70
- return { value, unresolved };
71
- }
95
+ // ../core/src/lock/types.ts
96
+ var LOCKFILE_VERSION = 2;
72
97
 
73
- // src/config/parsers.ts
74
- var serverEntrySchema = z.looseObject({
75
- type: z.string().optional(),
76
- command: z.string().optional(),
77
- args: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
78
- env: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])).optional(),
79
- cwd: z.string().optional(),
80
- url: z.string().optional(),
81
- headers: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
82
- envFile: z.string().optional(),
83
- headersHelper: z.string().optional(),
84
- oauth: z.looseObject({
85
- clientId: z.string().optional(),
86
- clientSecret: z.string().optional(),
87
- scope: z.string().optional(),
88
- scopes: z.array(z.string()).optional()
89
- }).optional()
90
- });
91
- var UnsupportedServerError = class extends Error {
92
- constructor(serverName, message) {
93
- super(message);
94
- this.serverName = serverName;
95
- this.name = "UnsupportedServerError";
96
- }
97
- serverName;
98
- };
99
- function scalarsToStrings(record) {
100
- const out = {};
101
- for (const [key, value] of Object.entries(record ?? {})) {
102
- if (value === null) continue;
103
- out[key] = String(value);
98
+ // ../core/src/lock/canonical.ts
99
+ import { createHash } from "crypto";
100
+ var MAX_DEPTH = 100;
101
+ var tooDeep = () => new TypeError(`cannot canonicalize JSON nested deeper than ${MAX_DEPTH} levels; this is not a surface we can hash`);
102
+ function canonicalize(value, depth = 0) {
103
+ if (depth > MAX_DEPTH) throw tooDeep();
104
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
105
+ return JSON.stringify(value);
104
106
  }
105
- return out;
106
- }
107
- function resolveTransport(name, entry, context) {
108
- const unresolved = [];
109
- const take = (input) => {
110
- const result = expand(input, context);
111
- unresolved.push(...result.unresolved);
112
- return result.value;
113
- };
114
- const declared = entry.type === "streamable-http" ? "http" : entry.type;
115
- if (declared === "ws") {
116
- throw new UnsupportedServerError(name, "WebSocket transport is not supported by the MCP specification or the SDK");
107
+ if (value === void 0) {
108
+ throw new TypeError("cannot canonicalize undefined; pass the value through toJson first");
117
109
  }
118
- let transport2;
119
- if (declared === "http" || declared === "sse" || declared === void 0 && entry.url !== void 0) {
120
- if (entry.url === void 0) throw new UnsupportedServerError(name, `transport "${declared}" needs a url`);
121
- const oauth = entry.oauth;
122
- transport2 = {
123
- type: declared === "sse" ? "sse" : "http",
124
- url: take(entry.url),
125
- headers: Object.fromEntries(Object.entries(scalarsToStrings(entry.headers)).map(([key, value]) => [key, take(value)])),
126
- ...oauth === void 0 ? {} : {
127
- oauth: {
128
- // Expanded here so a secret can live in the environment rather than the config file.
129
- clientId: oauth.clientId === void 0 ? void 0 : take(oauth.clientId),
130
- clientSecret: oauth.clientSecret === void 0 ? void 0 : take(oauth.clientSecret),
131
- scope: oauth.scope ?? oauth.scopes?.join(" ")
132
- }
133
- }
134
- };
135
- } else {
136
- if (entry.command === void 0) throw new UnsupportedServerError(name, "stdio server has no command");
137
- transport2 = {
138
- type: "stdio",
139
- command: take(entry.command),
140
- args: (entry.args ?? []).map((argument) => take(String(argument))),
141
- env: Object.fromEntries(Object.entries(scalarsToStrings(entry.env)).map(([key, value]) => [key, take(value)])),
142
- cwd: entry.cwd ? take(entry.cwd) : void 0
143
- };
110
+ if (typeof value === "number") {
111
+ if (!Number.isFinite(value)) throw new TypeError(`cannot canonicalize non-finite number: ${value}`);
112
+ return JSON.stringify(value === 0 ? 0 : value);
144
113
  }
145
- if (unresolved.length > 0) {
146
- const names = [...new Set(unresolved)].join(", ");
147
- throw new UnsupportedServerError(
148
- name,
149
- `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.`
150
- );
114
+ if (Array.isArray(value)) {
115
+ return `[${value.map((member) => canonicalize(member, depth + 1)).join(",")}]`;
151
116
  }
152
- return transport2;
117
+ const keys = Object.keys(value).sort();
118
+ const members = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(value[key], depth + 1)}`);
119
+ return `{${members.join(",")}}`;
153
120
  }
154
- function detectMapKey(raw) {
155
- if (typeof raw !== "object" || raw === null) return void 0;
156
- const record = raw;
157
- for (const key of ["mcpServers", "servers"]) {
158
- if (typeof record[key] === "object" && record[key] !== null) return key;
159
- }
160
- return void 0;
161
- }
162
- async function readEnvFile(path) {
163
- const out = {};
164
- const text = await readFile(path, "utf8");
165
- for (const line of text.split(/\r?\n/)) {
166
- const trimmed = line.trim();
167
- if (trimmed === "" || trimmed.startsWith("#")) continue;
168
- const at = trimmed.indexOf("=");
169
- if (at <= 0) continue;
170
- const key = trimmed.slice(0, at).trim().replace(/^export\s+/, "");
171
- let value = trimmed.slice(at + 1).trim();
172
- if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
173
- value = value.slice(1, -1);
174
- }
175
- out[key] = value;
176
- }
177
- return out;
178
- }
179
- async function parseServerMap(raw, mapKey, source, context) {
180
- const servers = [];
181
- const skipped = [];
182
- if (typeof raw !== "object" || raw === null) return { servers, skipped };
183
- const map = raw[mapKey];
184
- if (typeof map !== "object" || map === null) return { servers, skipped };
185
- for (const [name, value] of Object.entries(map)) {
186
- const entry = serverEntrySchema.safeParse(value);
187
- if (!entry.success) {
188
- skipped.push(new UnsupportedServerError(name, `entry is not a server definition: ${entry.error.issues[0]?.message ?? "unknown"}`));
189
- continue;
190
- }
191
- try {
192
- if (entry.data.headersHelper !== void 0) {
193
- throw new UnsupportedServerError(name, "`headersHelper` runs a command to produce headers, which this tool will not execute");
194
- }
195
- const transport2 = resolveTransport(name, entry.data, context);
196
- if (transport2.type === "stdio" && entry.data.envFile !== void 0) {
197
- const expanded = expand(entry.data.envFile, context);
198
- if (expanded.unresolved.length > 0) {
199
- throw new UnsupportedServerError(name, `envFile path contains unresolved placeholders: ${expanded.unresolved.join(", ")}`);
200
- }
201
- try {
202
- transport2.env = { ...await readEnvFile(resolve(context.workspaceFolder, expanded.value)), ...transport2.env };
203
- } catch (error) {
204
- throw new UnsupportedServerError(name, `envFile ${expanded.value} could not be read: ${error.message}`);
205
- }
206
- }
207
- servers.push({ name, source: { ...source }, transport: transport2 });
208
- } catch (error) {
209
- if (error instanceof UnsupportedServerError) skipped.push(error);
210
- else throw error;
211
- }
212
- }
213
- return { servers, skipped };
214
- }
215
- async function parseClaudeJson(raw, projectRoot, source, context) {
216
- const user = await parseServerMap(raw, "mcpServers", { ...source, scope: "user" }, context);
217
- const projects = typeof raw === "object" && raw !== null ? raw["projects"] : void 0;
218
- const forProject = typeof projects === "object" && projects !== null ? projects[projectRoot] : void 0;
219
- const local = forProject ? await parseServerMap(forProject, "mcpServers", { ...source, scope: "local" }, context) : { servers: [], skipped: [] };
220
- return { servers: [...user.servers, ...local.servers], skipped: [...user.skipped, ...local.skipped] };
221
- }
222
- var CLIENT_MAP_KEY = {
223
- "claude-code": "mcpServers",
224
- "claude-desktop": "mcpServers",
225
- vscode: "servers",
226
- cursor: "mcpServers",
227
- copilot: "mcpServers",
228
- windsurf: "mcpServers",
229
- generic: "mcpServers",
230
- manual: "mcpServers"
231
- };
232
-
233
- // src/config/discover.ts
234
- function claudeDesktopPath() {
235
- const home = homedir2();
236
- switch (platform()) {
237
- case "darwin":
238
- return join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
239
- case "win32":
240
- return join(process.env["APPDATA"] ?? join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
241
- default:
242
- return join(home, ".config", "Claude", "claude_desktop_config.json");
243
- }
244
- }
245
- function candidateConfigFiles(projectRoot) {
246
- const home = homedir2();
247
- const copilotHome = process.env["COPILOT_HOME"] ?? join(home, ".copilot");
248
- return [
249
- { client: "claude-code", path: join(projectRoot, ".mcp.json"), scope: "project" },
250
- { client: "vscode", path: join(projectRoot, ".vscode", "mcp.json"), scope: "project" },
251
- { client: "cursor", path: join(projectRoot, ".cursor", "mcp.json"), scope: "project" },
252
- { client: "claude-code", path: join(home, ".claude.json"), scope: "user" },
253
- { client: "cursor", path: join(home, ".cursor", "mcp.json"), scope: "user" },
254
- { client: "claude-desktop", path: claudeDesktopPath(), scope: "user" },
255
- { client: "windsurf", path: join(home, ".codeium", "windsurf", "mcp_config.json"), scope: "user" },
256
- { client: "copilot", path: join(copilotHome, "mcp-config.json"), scope: "user" }
257
- ];
258
- }
259
- function portablePath(absolute, projectRoot) {
260
- const fromProject = relative(projectRoot, absolute);
261
- if (!fromProject.startsWith("..") && !isAbsolute(fromProject)) return fromProject.split(sep).join("/");
262
- const fromHome = relative(homedir2(), absolute);
263
- if (!fromHome.startsWith("..") && !isAbsolute(fromHome)) return `~/${fromHome.split(sep).join("/")}`;
264
- return absolute.split(sep).join("/");
265
- }
266
- async function readJsonIfPresent(path) {
267
- let text;
268
- try {
269
- text = await readFile2(path, "utf8");
270
- } catch (error) {
271
- const code = error.code;
272
- if (code === "ENOENT" || code === "ENOTDIR") return { present: false };
273
- if (code === "EACCES") return { present: true, ok: false, reason: "permission denied" };
274
- throw error;
275
- }
276
- try {
277
- return { present: true, ok: true, value: JSON.parse(text) };
278
- } catch (error) {
279
- return { present: true, ok: false, reason: `not valid JSON: ${error.message}` };
280
- }
281
- }
282
- function anchorCwd(server2, projectRoot) {
283
- const { transport: transport2 } = server2;
284
- if (transport2.type !== "stdio" || transport2.cwd === void 0 || isAbsolute(transport2.cwd)) return server2;
285
- return { ...server2, transport: { ...transport2, cwd: resolve2(projectRoot, transport2.cwd) } };
286
- }
287
- function describeSearch(searched, filesRead) {
288
- const read = new Set(filesRead);
289
- const lines = searched.map((path) => ` ${(read.has(path) ? "read" : "absent").padEnd(6)} ${path}`);
290
- return lines.join("\n");
291
- }
292
- async function discoverServers(projectRoot, extraFiles = []) {
293
- const context = { workspaceFolder: projectRoot, env: process.env };
294
- const files = [
295
- ...extraFiles.map((path) => ({ client: "generic", path: resolve2(projectRoot, path) })),
296
- ...candidateConfigFiles(projectRoot)
297
- ];
298
- const byName2 = /* @__PURE__ */ new Map();
299
- const skipped = [];
300
- const filesRead = [];
301
- const shadowed = [];
302
- const problems = [];
303
- for (const file of files) {
304
- const read = await readJsonIfPresent(file.path);
305
- if (!read.present) continue;
306
- if (!read.ok) {
307
- problems.push({ file: portablePath(file.path, projectRoot), reason: read.reason });
308
- continue;
309
- }
310
- const raw = read.value;
311
- filesRead.push(file.path);
312
- const source = { client: file.client, file: portablePath(file.path, projectRoot) };
313
- let mapKey = CLIENT_MAP_KEY[file.client];
314
- if (file.client === "generic") {
315
- mapKey = detectMapKey(raw);
316
- if (mapKey === void 0) {
317
- problems.push({ file: source.file, reason: "no `mcpServers` or `servers` object found; this does not look like an MCP client config" });
318
- continue;
319
- }
320
- }
321
- const parsed = file.client === "claude-code" && file.scope === "user" ? await parseClaudeJson(raw, projectRoot, source, context) : await parseServerMap(raw, mapKey, { ...source, scope: file.scope }, context);
322
- skipped.push(...parsed.skipped);
323
- for (const server2 of parsed.servers.map((entry) => anchorCwd(entry, projectRoot))) {
324
- const existing = byName2.get(server2.name);
325
- if (existing) {
326
- shadowed.push({ name: server2.name, keptFrom: existing.from, alsoIn: source.file });
327
- continue;
328
- }
329
- byName2.set(server2.name, { server: server2, from: source.file });
330
- }
331
- }
332
- return {
333
- servers: [...byName2.values()].map((entry) => entry.server).sort((a, b) => a.name.localeCompare(b.name)),
334
- skipped,
335
- filesRead,
336
- searched: files.map((file) => file.path),
337
- shadowed,
338
- problems
339
- };
340
- }
341
-
342
- // ../core/src/lock/canonical.ts
343
- import { createHash } from "crypto";
344
- var MAX_DEPTH = 100;
345
- var tooDeep = () => new TypeError(`cannot canonicalize JSON nested deeper than ${MAX_DEPTH} levels; this is not a surface we can hash`);
346
- function canonicalize(value, depth = 0) {
347
- if (depth > MAX_DEPTH) throw tooDeep();
348
- if (value === null || typeof value === "boolean" || typeof value === "string") {
349
- return JSON.stringify(value);
350
- }
351
- if (value === void 0) {
352
- throw new TypeError("cannot canonicalize undefined; pass the value through toJson first");
353
- }
354
- if (typeof value === "number") {
355
- if (!Number.isFinite(value)) throw new TypeError(`cannot canonicalize non-finite number: ${value}`);
356
- return JSON.stringify(value === 0 ? 0 : value);
357
- }
358
- if (Array.isArray(value)) {
359
- return `[${value.map((member) => canonicalize(member, depth + 1)).join(",")}]`;
360
- }
361
- const keys = Object.keys(value).sort();
362
- const members = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(value[key], depth + 1)}`);
363
- return `{${members.join(",")}}`;
364
- }
365
- function digest(value) {
366
- return `sha256:${createHash("sha256").update(canonicalize(value), "utf8").digest("hex")}`;
121
+ function digest(value) {
122
+ return `sha256:${createHash("sha256").update(canonicalize(value), "utf8").digest("hex")}`;
367
123
  }
368
124
  function toJson(value, depth = 0) {
369
125
  if (depth > MAX_DEPTH) throw tooDeep();
@@ -384,6 +140,43 @@ function stableKey(value) {
384
140
  return canonicalize(toJson(value));
385
141
  }
386
142
 
143
+ // ../core/src/lock/reseal.ts
144
+ function sealMember(member) {
145
+ const { digest: _discarded, ...body } = member;
146
+ return { ...body, digest: digest(toJson(body)) };
147
+ }
148
+ function reseal(entry) {
149
+ switch (entry.kind) {
150
+ case "mcp-server":
151
+ return resealMcpServer(entry);
152
+ }
153
+ }
154
+ function resealMcpServer(entry) {
155
+ const tools = (entry.tools ?? []).map((tool2) => sealMember(tool2));
156
+ const resources = (entry.resources ?? []).map((resource2) => sealMember(resource2));
157
+ const resourceTemplates = (entry.resourceTemplates ?? []).map((template) => sealMember(template));
158
+ const prompts = (entry.prompts ?? []).map((prompt2) => sealMember(prompt2));
159
+ const covered = {
160
+ transport: entry.transport,
161
+ protocol: entry.protocol,
162
+ serverInfo: entry.serverInfo,
163
+ capabilities: entry.capabilities,
164
+ instructions: entry.instructions,
165
+ tools: tools.map((tool2) => tool2.digest),
166
+ resources: resources.map((resource2) => resource2.digest),
167
+ resourceTemplates: resourceTemplates.map((template) => template.digest),
168
+ prompts: prompts.map((prompt2) => prompt2.digest)
169
+ };
170
+ return {
171
+ ...entry,
172
+ tools: tools.length > 0 ? tools : void 0,
173
+ resources: resources.length > 0 ? resources : void 0,
174
+ resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
175
+ prompts: prompts.length > 0 ? prompts : void 0,
176
+ digest: digest(toJson(covered))
177
+ };
178
+ }
179
+
387
180
  // ../core/src/lock/jsonschema.ts
388
181
  var MAX_REF_DEPTH = 32;
389
182
  var MAX_VISIT_DEPTH = 12;
@@ -522,986 +315,1534 @@ function sanitizeUrl(raw) {
522
315
  const url = new URL(raw);
523
316
  url.search = "";
524
317
  url.hash = "";
318
+ url.username = "";
319
+ url.password = "";
525
320
  return url.toString();
526
321
  } catch {
527
322
  return raw;
528
323
  }
529
324
  }
530
325
 
531
- // src/lock/build.ts
532
- function byName(members) {
533
- return [...members].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
326
+ // ../core/src/risk/capability.ts
327
+ var CAPABILITY_SEVERITIES = ["critical", "high", "medium", "low"];
328
+ var CAPABILITY_KINDS = [
329
+ "process-exec",
330
+ "code-eval",
331
+ "credential-access",
332
+ "file-write",
333
+ "network-egress",
334
+ "database",
335
+ "privilege",
336
+ "agent-control",
337
+ "env-access",
338
+ "file-read"
339
+ ];
340
+ var RULES = [
341
+ { kind: "process-exec", severity: "critical", name: /(^|_)(exec|execute|spawn|shell|bash|sh|cmd|command|run_command|terminal|subprocess)(_|$)/, arg: /(^|_)(command|cmd|argv|shell|exec|script)(_|$)/ },
342
+ // `source` is deliberately absent: in `copy_file(source, destination)` it is a path, and
343
+ // labelling a file copy as arbitrary code execution at CRITICAL is the false positive that
344
+ // teaches people to stop reading the line. `code` has to be the whole argument name for the
345
+ // same reason -- a crawl of 468 published tools flagged `location_code` as arbitrary code
346
+ // execution, and `country_code`, `status_code` and `zip_code` are all waiting behind it.
347
+ { kind: "code-eval", severity: "critical", name: /(^|_)(eval|evaluate|run_code|exec_code|interpret|compile)(_|$)/, arg: /^code$|(^|_)(source_code|code_to_run|js_code|python_code|expression|program|snippet)(_|$)/ },
348
+ { kind: "credential-access", severity: "critical", name: /(^|_)(secret|secrets|credential|credentials|token|keychain|vault|password)(_|$)/, arg: /(^|_)(secret|credential|password|private_key|api_key|access_token)(_|$)/ },
349
+ { kind: "file-write", severity: "high", name: /(^|_)(write|create_file|put_file|save|delete|remove|unlink|rename|move|copy|chmod|mkdir|rmdir|edit)(_|$)/, arg: /(^|_)(contents|content|data|destination|dest_path|target_path)(_|$)/ },
350
+ { kind: "network-egress", severity: "high", name: /(^|_)(fetch|request|http|curl|download|upload|post|webhook|navigate|browse|send)(_|$)/, arg: /(^|_)(url|uri|endpoint|host|hostname|webhook|callback)(_|$)/ },
351
+ // Narrowed to things that are actually SQL-shaped. `query`, `select` and `update` on their
352
+ // own matched `simulate-research-query`, `browser_select_option` and `trigger-resource-update`,
353
+ // none of which is a database.
354
+ { kind: "database", severity: "high", name: /(^|_)(sql|execute_sql|run_sql|query_db|db_query|migrate)(_|$)/, arg: /(^|_)(sql|statement|dsn|connection_string)(_|$)/ },
355
+ { kind: "privilege", severity: "high", name: /(^|_)(sudo|root|admin|grant|revoke|permission|permissions|acl|policy)(_|$)/, arg: /(^|_)(role|scope|scopes|permission|permissions|privilege)(_|$)/ },
356
+ { kind: "agent-control", severity: "high", name: /(^|_)(prompt|system_prompt|instruction|instructions|memory|context|persona)(_|$)/, arg: /(^|_)(system_prompt|instruction|instructions|persona)(_|$)/ },
357
+ { kind: "env-access", severity: "medium", name: /(^|_)(env|environment|getenv|setenv|config|settings)(_|$)/, arg: /(^|_)(env|environment|env_var)(_|$)/ },
358
+ { kind: "file-read", severity: "low", name: /(^|_)(read|read_file|cat|open|load|list_directory|ls|glob|search_files)(_|$)/, arg: /(^|_)(path|file|filename|filepath|directory|dir)(_|$)/ }
359
+ ];
360
+ var CONFUSABLES = {
361
+ "\u0430": "a",
362
+ "\u0435": "e",
363
+ "\u043E": "o",
364
+ "\u0441": "c",
365
+ "\u0440": "p",
366
+ "\u0445": "x",
367
+ "\u0443": "y",
368
+ "\u0456": "i",
369
+ "\u0458": "j",
370
+ "\u04BB": "h",
371
+ "\u0501": "d",
372
+ "\u051B": "q",
373
+ "\u03BF": "o",
374
+ "\u03B1": "a",
375
+ "\u03B5": "e",
376
+ "\u03BD": "v",
377
+ "\u03C1": "p",
378
+ "\u03C5": "u",
379
+ "\u0131": "i",
380
+ "\u1E9E": "s"
381
+ };
382
+ var CONFUSABLE_PATTERN = new RegExp(`[${Object.keys(CONFUSABLES).join("")}]`, "g");
383
+ function normalize(identifier) {
384
+ return identifier.toLowerCase().replace(CONFUSABLE_PATTERN, (character) => CONFUSABLES[character] ?? character).replace(/[-.\s/]+/g, "_");
534
385
  }
535
- function lockIcons(icons) {
536
- if (!icons || icons.length === 0) return void 0;
537
- return icons.map((icon2) => ({
538
- src: icon2.src,
539
- mimeType: icon2.mimeType,
540
- sizes: icon2.sizes,
541
- theme: icon2.theme
542
- }));
386
+ function argumentNames(inputSchema, depth = 0) {
387
+ if (depth > 6 || typeof inputSchema !== "object" || inputSchema === null) return [];
388
+ const node = inputSchema;
389
+ const names = [];
390
+ const properties = node.properties;
391
+ if (typeof properties === "object" && properties !== null) {
392
+ for (const [name, child] of Object.entries(properties)) {
393
+ names.push(name);
394
+ names.push(...argumentNames(child, depth + 1));
395
+ }
396
+ }
397
+ if (node.items !== void 0) names.push(...argumentNames(node.items, depth + 1));
398
+ return names;
543
399
  }
544
- function sealed(entry) {
545
- return { ...entry, digest: digest(toJson(entry)) };
400
+ function toolCapabilities(tool2) {
401
+ const name = normalize(tool2.name ?? "");
402
+ const args = argumentNames(tool2.inputSchema).map((argument) => [argument, normalize(argument)]);
403
+ const found = /* @__PURE__ */ new Map();
404
+ for (const rule of RULES) {
405
+ if (found.has(rule.kind)) continue;
406
+ if (rule.name?.test(name)) {
407
+ found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: "name" });
408
+ continue;
409
+ }
410
+ const hit = rule.arg ? args.find(([, normalized]) => rule.arg?.test(normalized)) : void 0;
411
+ if (hit) found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: `arg:${hit[0]}` });
412
+ }
413
+ return [...found.values()].sort(
414
+ (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
415
+ );
546
416
  }
547
- function lockTransport(server2) {
548
- const { transport: transport2 } = server2;
549
- if (transport2.type === "stdio") {
550
- return {
551
- type: "stdio",
552
- command: transport2.command,
553
- args: transport2.args.length > 0 ? transport2.args : void 0,
554
- envKeys: Object.keys(transport2.env).length > 0 ? Object.keys(transport2.env).sort() : void 0,
555
- cwd: transport2.cwd
556
- };
417
+ function surfaceCapabilities(tools) {
418
+ const byKind = /* @__PURE__ */ new Map();
419
+ for (const tool2 of tools) {
420
+ for (const capability of toolCapabilities(tool2)) {
421
+ const existing = byKind.get(capability.kind);
422
+ if (existing) existing.tools.push(tool2.name ?? "?");
423
+ else byKind.set(capability.kind, { ...capability, tools: [tool2.name ?? "?"] });
424
+ }
557
425
  }
558
- const headerKeys = Object.keys(transport2.headers);
559
- return {
560
- type: transport2.type,
561
- url: sanitizeUrl(transport2.url),
562
- headerKeys: headerKeys.length > 0 ? headerKeys.sort() : void 0
563
- };
564
- }
565
- function lockTool(tool2, ignoredMeta) {
566
- const annotations2 = tool2.annotations;
567
- const inputSchema = normalizeSchema(toJson(tool2.inputSchema));
568
- const headerParams = extractHeaderParams(inputSchema);
569
- return sealed({
570
- name: tool2.name,
571
- title: tool2.title,
572
- description: tool2.description,
573
- inputSchema,
574
- outputSchema: tool2.outputSchema ? normalizeSchema(toJson(tool2.outputSchema)) : void 0,
575
- annotations: annotations2 ? { ...annotations2 } : void 0,
576
- behavior: resolveBehavior(annotations2),
577
- headerParams: headerParams.length > 0 ? headerParams : void 0,
578
- icons: lockIcons(tool2.icons),
579
- meta: stripIgnoredMeta(toJson(tool2._meta), ignoredMeta)
580
- });
426
+ return [...byKind.values()].sort(
427
+ (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
428
+ );
581
429
  }
582
- function lockResource(resource2, ignoredMeta) {
583
- return sealed({
584
- uri: resource2.uri,
585
- name: resource2.name,
586
- title: resource2.title,
587
- description: resource2.description,
588
- mimeType: resource2.mimeType,
589
- annotations: resource2.annotations ? toJson(resource2.annotations) : void 0,
590
- icons: lockIcons(resource2.icons),
591
- meta: stripIgnoredMeta(toJson(resource2._meta), ignoredMeta)
592
- });
430
+
431
+ // ../core/src/diff/schema.ts
432
+ function numberAt(node, key) {
433
+ const value = node[key];
434
+ return typeof value === "number" ? value : void 0;
593
435
  }
594
- function lockResourceTemplate(template, ignoredMeta) {
595
- return sealed({
596
- uriTemplate: template.uriTemplate,
597
- name: template.name,
598
- title: template.title,
599
- description: template.description,
600
- mimeType: template.mimeType,
601
- annotations: template.annotations ? toJson(template.annotations) : void 0,
602
- icons: lockIcons(template.icons),
603
- meta: stripIgnoredMeta(toJson(template._meta), ignoredMeta)
604
- });
436
+ function collectFacts(schema) {
437
+ const facts = /* @__PURE__ */ new Map();
438
+ const visit = (node, path, required, depth) => {
439
+ if (depth > MAX_VISIT_DEPTH || facts.size >= MAX_FACTS) return;
440
+ const object = effectiveSchema(node, schema);
441
+ if (!object) return;
442
+ const typeValue = object["type"];
443
+ const types = typeof typeValue === "string" ? [typeValue] : Array.isArray(typeValue) ? typeValue.filter((entry) => typeof entry === "string").sort() : void 0;
444
+ const enumValue = object["enum"];
445
+ facts.set(path, {
446
+ required,
447
+ additionalProperties: typeof object["additionalProperties"] === "boolean" ? object["additionalProperties"] : void 0,
448
+ enumMembers: Array.isArray(enumValue) ? enumValue.map((entry) => canonicalize(entry)).sort() : void 0,
449
+ types,
450
+ minimum: numberAt(object, "minimum"),
451
+ maximum: numberAt(object, "maximum"),
452
+ minLength: numberAt(object, "minLength"),
453
+ maxLength: numberAt(object, "maxLength")
454
+ });
455
+ const properties = asObject(object["properties"]);
456
+ if (properties) {
457
+ const requiredList = Array.isArray(object["required"]) ? object["required"].filter((entry) => typeof entry === "string") : [];
458
+ for (const [name, child] of Object.entries(properties)) {
459
+ visit(child, path === "" ? name : `${path}.${name}`, requiredList.includes(name), depth + 1);
460
+ }
461
+ }
462
+ const items = object["items"];
463
+ if (items !== void 0) visit(items, `${path}[]`, false, depth + 1);
464
+ const prefixItems = object["prefixItems"];
465
+ if (Array.isArray(prefixItems)) prefixItems.forEach((entry, index) => visit(entry, `${path}[${index}]`, false, depth + 1));
466
+ for (const branch of alternatives(object)) visit(branch.schema, `${path}|${branch.label}`, false, depth + 1);
467
+ };
468
+ visit(schema, "", true, 0);
469
+ return facts;
605
470
  }
606
- function lockPrompt(prompt2, ignoredMeta) {
607
- return sealed({
608
- name: prompt2.name,
609
- title: prompt2.title,
610
- description: prompt2.description,
611
- arguments: prompt2.arguments && prompt2.arguments.length > 0 ? prompt2.arguments.map((argument) => ({
612
- name: argument.name,
613
- // The spec gives PromptArgument a `title` (it extends BaseMetadata); the SDK's type
614
- // has not caught up, so it is read off the wire rather than skipped.
615
- title: argument.title,
616
- description: argument.description,
617
- required: argument.required
618
- })) : void 0,
619
- icons: lockIcons(prompt2.icons),
620
- meta: stripIgnoredMeta(toJson(prompt2._meta), ignoredMeta)
621
- });
471
+ function isSuperset(next, previous) {
472
+ return previous.every((entry) => next.includes(entry));
622
473
  }
623
- function buildLockedServer(server2, surface, policy) {
624
- const ignoredMeta = policy?.ignoreMetaPrefixes ?? [];
625
- const tools = byName(surface.tools).map((tool2) => lockTool(tool2, ignoredMeta));
626
- const resources = byName(surface.resources).map((resource2) => lockResource(resource2, ignoredMeta));
627
- const resourceTemplates = byName(surface.resourceTemplates).map((template) => lockResourceTemplate(template, ignoredMeta));
628
- const prompts = byName(surface.prompts).map((prompt2) => lockPrompt(prompt2, ignoredMeta));
629
- const entry = {
630
- source: server2.source,
631
- transport: lockTransport(server2),
632
- protocol: surface.protocol,
633
- serverInfo: surface.serverInfo,
634
- capabilities: surface.capabilities,
635
- instructions: surface.instructions,
636
- tools: tools.length > 0 ? tools : void 0,
637
- resources: resources.length > 0 ? resources : void 0,
638
- resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
639
- prompts: prompts.length > 0 ? prompts : void 0
640
- };
641
- const covered = {
642
- transport: entry.transport,
643
- protocol: entry.protocol,
644
- serverInfo: entry.serverInfo,
645
- capabilities: entry.capabilities,
646
- instructions: entry.instructions,
647
- tools: tools.map((tool2) => tool2.digest),
648
- resources: resources.map((resource2) => resource2.digest),
649
- resourceTemplates: resourceTemplates.map((template) => template.digest),
650
- prompts: prompts.map((prompt2) => prompt2.digest)
651
- };
652
- return { kind: "mcp-server", ...entry, digest: digest(toJson(covered)) };
474
+ function classifySchemaChange(before, after) {
475
+ if (stableKey(before) === stableKey(after)) return "same";
476
+ const previous = collectFacts(before);
477
+ const next = collectFacts(after);
478
+ let widened = false;
479
+ let narrowed = false;
480
+ for (const path of /* @__PURE__ */ new Set([...previous.keys(), ...next.keys()])) {
481
+ const a = previous.get(path);
482
+ const b = next.get(path);
483
+ if (!a && b) {
484
+ widened = true;
485
+ continue;
486
+ }
487
+ if (a && !b) {
488
+ narrowed = true;
489
+ continue;
490
+ }
491
+ if (!a || !b) continue;
492
+ if (a.required && !b.required) widened = true;
493
+ if (!a.required && b.required) narrowed = true;
494
+ const beforeAdditional = a.additionalProperties ?? true;
495
+ const afterAdditional = b.additionalProperties ?? true;
496
+ if (!beforeAdditional && afterAdditional) widened = true;
497
+ if (beforeAdditional && !afterAdditional) narrowed = true;
498
+ if (a.enumMembers && b.enumMembers) {
499
+ if (isSuperset(b.enumMembers, a.enumMembers) && b.enumMembers.length > a.enumMembers.length) widened = true;
500
+ else if (isSuperset(a.enumMembers, b.enumMembers) && a.enumMembers.length > b.enumMembers.length) narrowed = true;
501
+ else if (canonicalize(a.enumMembers) !== canonicalize(b.enumMembers)) {
502
+ widened = true;
503
+ narrowed = true;
504
+ }
505
+ } else if (a.enumMembers && !b.enumMembers) widened = true;
506
+ else if (!a.enumMembers && b.enumMembers) narrowed = true;
507
+ if (a.types && b.types) {
508
+ if (isSuperset(b.types, a.types) && b.types.length > a.types.length) widened = true;
509
+ else if (isSuperset(a.types, b.types) && a.types.length > b.types.length) narrowed = true;
510
+ else if (canonicalize(a.types) !== canonicalize(b.types)) {
511
+ widened = true;
512
+ narrowed = true;
513
+ }
514
+ } else if (a.types && !b.types) widened = true;
515
+ else if (!a.types && b.types) narrowed = true;
516
+ const lowerBounds = [["minimum", a.minimum, b.minimum], ["minLength", a.minLength, b.minLength]];
517
+ for (const [, before_, after_] of lowerBounds) {
518
+ if (before_ !== void 0 && after_ === void 0) widened = true;
519
+ else if (before_ === void 0 && after_ !== void 0) narrowed = true;
520
+ else if (before_ !== void 0 && after_ !== void 0) {
521
+ if (after_ < before_) widened = true;
522
+ if (after_ > before_) narrowed = true;
523
+ }
524
+ }
525
+ const upperBounds = [["maximum", a.maximum, b.maximum], ["maxLength", a.maxLength, b.maxLength]];
526
+ for (const [, before_, after_] of upperBounds) {
527
+ if (before_ !== void 0 && after_ === void 0) widened = true;
528
+ else if (before_ === void 0 && after_ !== void 0) narrowed = true;
529
+ else if (before_ !== void 0 && after_ !== void 0) {
530
+ if (after_ > before_) widened = true;
531
+ if (after_ < before_) narrowed = true;
532
+ }
533
+ }
534
+ }
535
+ if (widened && !narrowed) return "widened";
536
+ if (narrowed && !widened) return "narrowed";
537
+ return "changed";
653
538
  }
654
539
 
655
- // ../core/src/lock/types.ts
656
- var LOCKFILE_VERSION = 2;
657
-
658
- // src/mcp/connect.ts
659
- import { Client, SSEClientTransport, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
660
- import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/client/stdio";
661
-
662
- // src/mcp/oauth.ts
663
- import { spawn } from "child_process";
664
- import { createHash as createHash2, randomUUID } from "crypto";
665
- import { readFileSync } from "fs";
666
- import { mkdir, readFile as readFile3, rm, writeFile } from "fs/promises";
667
- import { homedir as homedir3, platform as platform2 } from "os";
668
- import { dirname, join as join2 } from "path";
669
- import { ClientCredentialsProvider, UnauthorizedError } from "@modelcontextprotocol/client";
670
-
671
- // src/lib/version.ts
672
- var VERSION = "0.1.5";
673
- var USER_AGENT = `nulladrift/${VERSION}`;
674
-
675
- // src/mcp/oauth.ts
676
- var DEFAULT_CALLBACK_PATH = "/callback";
677
- function authDir() {
678
- const base = process.env["XDG_CONFIG_HOME"] ?? join2(homedir3(), ".config");
679
- return join2(base, "nulladrift", "auth");
540
+ // ../core/src/diff/index.ts
541
+ function change(kind, server2, summary, extra) {
542
+ return { kind, severity: SEVERITY[kind], server: server2, summary, ...extra };
680
543
  }
681
- function credentialPath(url) {
682
- return join2(authDir(), `${createHash2("sha256").update(url).digest("hex").slice(0, 16)}.json`);
544
+ function same(a, b) {
545
+ return stableKey(a ?? null) === stableKey(b ?? null);
683
546
  }
684
- var InteractiveAuthRequiredError = class extends Error {
685
- constructor(serverName) {
686
- super(`authorization required. Run \`nulladrift login ${serverName}\` once, then re-run.`);
687
- this.serverName = serverName;
688
- this.name = "InteractiveAuthRequiredError";
547
+ function indexBy(members, key) {
548
+ return new Map((members ?? []).map((member) => [key(member), member]));
549
+ }
550
+ function declaredNames(capabilities) {
551
+ const names = [];
552
+ for (const [key, value] of Object.entries(capabilities ?? {})) {
553
+ if (key === "extensions" && value !== null && typeof value === "object" && !Array.isArray(value)) {
554
+ for (const id of Object.keys(value)) names.push(`extensions/${id}`);
555
+ continue;
556
+ }
557
+ names.push(key);
689
558
  }
690
- serverName;
691
- };
692
- var FileTokenProvider = class {
693
- constructor(serverName, serverUrl, options = { interactive: false }) {
694
- this.serverName = serverName;
695
- this.serverUrl = serverUrl;
696
- this.options = options;
559
+ return names;
560
+ }
561
+ function compareCapabilities(before, after, name) {
562
+ if (same(before.capabilities, after.capabilities)) return [];
563
+ const previous = declaredNames(before.capabilities);
564
+ const next = declaredNames(after.capabilities);
565
+ const gained = next.filter((key) => !previous.includes(key));
566
+ const lost = previous.filter((key) => !next.includes(key));
567
+ if (gained.length > 0 && lost.length === 0) {
568
+ return [change("server.capabilities.widened", name, `server now declares ${gained.join(", ")}`, { before: before.capabilities, after: after.capabilities })];
697
569
  }
698
- serverName;
699
- serverUrl;
700
- options;
701
- cache;
702
- /** One per login attempt, held in memory and checked against what comes back on the callback. */
703
- stateValue = createHash2("sha256").update(randomUUID()).digest("hex").slice(0, 32);
704
- get redirectUrl() {
705
- return this.options.redirectUrl;
570
+ if (lost.length > 0 && gained.length === 0) {
571
+ return [change("server.capabilities.narrowed", name, `server no longer declares ${lost.join(", ")}`, { before: before.capabilities, after: after.capabilities })];
706
572
  }
707
- state() {
708
- return this.stateValue;
573
+ return [change("server.capabilities.changed", name, "declared capabilities changed", { before: before.capabilities, after: after.capabilities })];
574
+ }
575
+ var CAPABILITY_SEVERITY = {
576
+ critical: "high",
577
+ high: "high",
578
+ medium: "medium",
579
+ low: "low"
580
+ };
581
+ function compareToolCapabilities(server2, before, after) {
582
+ const previous = indexBy(before, (tool2) => tool2.name);
583
+ const changes = [];
584
+ for (const tool2 of after ?? []) {
585
+ const existing = previous.get(tool2.name);
586
+ if (!existing) continue;
587
+ const had = new Set(toolCapabilities(existing).map((capability) => capability.kind));
588
+ for (const capability of toolCapabilities(tool2)) {
589
+ if (had.has(capability.kind)) continue;
590
+ changes.push(
591
+ change("tool.capability.gained", server2, `can now ${capability.kind} (${capability.evidence})`, {
592
+ member: tool2.name,
593
+ severity: CAPABILITY_SEVERITY[capability.severity],
594
+ after: { kind: capability.kind, severity: capability.severity, evidence: capability.evidence }
595
+ })
596
+ );
597
+ }
709
598
  }
710
- get clientMetadata() {
711
- return {
712
- client_name: `nulladrift ${VERSION}`,
713
- // A command-line tool is a native client: it cannot keep a secret in a shipped binary.
714
- application_type: "native",
715
- redirect_uris: this.options.redirectUrl === void 0 ? [] : [this.options.redirectUrl],
716
- grant_types: ["authorization_code", "refresh_token"],
717
- response_types: ["code"],
718
- token_endpoint_auth_method: "none",
719
- ...this.options.scope === void 0 ? {} : { scope: this.options.scope }
720
- };
599
+ return changes;
600
+ }
601
+ function compareTool(name, before, after) {
602
+ if (before.digest === after.digest) return [];
603
+ const changes = [];
604
+ const at = { member: before.name };
605
+ if (!same(before.description, after.description)) {
606
+ changes.push(
607
+ change("tool.description.changed", name, `description changed (${before.description?.length ?? 0} \u2192 ${after.description?.length ?? 0} characters)`, {
608
+ ...at,
609
+ before: before.description,
610
+ after: after.description
611
+ })
612
+ );
721
613
  }
722
- async read() {
723
- if (this.cache) return this.cache;
724
- try {
725
- this.cache = JSON.parse(await readFile3(credentialPath(this.serverUrl), "utf8"));
726
- } catch {
727
- this.cache = { serverUrl: this.serverUrl };
728
- }
729
- return this.cache;
614
+ const inputVerdict = classifySchemaChange(before.inputSchema, after.inputSchema);
615
+ if (inputVerdict !== "same") {
616
+ const kind = `tool.input_schema.${inputVerdict}`;
617
+ const wording = inputVerdict === "widened" ? "accepts input it did not before" : inputVerdict === "narrowed" ? "accepts less input than before" : "input schema changed";
618
+ changes.push(change(kind, name, wording, { ...at, before: before.inputSchema, after: after.inputSchema }));
730
619
  }
731
- async write(patch) {
732
- const next = { ...await this.read(), ...patch, serverUrl: this.serverUrl };
733
- this.cache = next;
734
- const path = credentialPath(this.serverUrl);
735
- await mkdir(dirname(path), { recursive: true, mode: 448 });
736
- await writeFile(path, `${JSON.stringify(next, null, 2)}
737
- `, { encoding: "utf8", mode: 384 });
620
+ if (!same(before.outputSchema, after.outputSchema)) {
621
+ changes.push(change("tool.output_schema.changed", name, "output schema changed", { ...at, before: before.outputSchema, after: after.outputSchema }));
738
622
  }
739
- async clientInformation() {
740
- return (await this.read()).clientInformation;
623
+ if (!same(before.behavior, after.behavior)) {
624
+ const escalated = isEscalation(before.behavior, after.behavior);
625
+ changes.push(
626
+ change(escalated ? "tool.behavior.escalated" : "tool.behavior.relaxed", name, escalated ? describeEscalation(before, after) : "declares fewer powers than before", {
627
+ ...at,
628
+ before: before.behavior,
629
+ after: after.behavior
630
+ })
631
+ );
741
632
  }
742
- async saveClientInformation(clientInformation) {
743
- await this.write({ clientInformation });
633
+ if (!same(before.headerParams, after.headerParams)) {
634
+ changes.push(
635
+ change("tool.header_params.changed", name, "arguments mirrored into HTTP headers changed", { ...at, before: before.headerParams ?? [], after: after.headerParams ?? [] })
636
+ );
744
637
  }
745
- async tokens() {
746
- return (await this.read()).tokens;
638
+ if (changes.length === 0) {
639
+ changes.push(change("tool.changed", name, "tool definition changed (title, icons or _meta)", { ...at, before, after }));
747
640
  }
748
- async saveTokens(tokens) {
749
- await this.write({ tokens });
641
+ return changes;
642
+ }
643
+ function describeEscalation(before, after) {
644
+ const gained = [];
645
+ if (before.behavior.readOnly && !after.behavior.readOnly) gained.push("may now modify");
646
+ if (!before.behavior.destructive && after.behavior.destructive) gained.push("may now destroy");
647
+ if (before.behavior.idempotent && !after.behavior.idempotent) gained.push("repeat calls now compound");
648
+ if (!before.behavior.openWorld && after.behavior.openWorld) gained.push("may now reach external systems");
649
+ return gained.join("; ");
650
+ }
651
+ function compareMembers(name, before, after, spec, deep) {
652
+ const changes = [];
653
+ const previous = indexBy(before, spec.key);
654
+ const next = indexBy(after, spec.key);
655
+ for (const [key, member] of next) {
656
+ const existing = previous.get(key);
657
+ if (!existing) {
658
+ const extra = spec.arriving?.(member);
659
+ changes.push(
660
+ change(spec.added, name, `new ${spec.noun} ${spec.label(member)}${extra ? ` \xB7 ${extra}` : ""}`, { member: spec.label(member), after: member })
661
+ );
662
+ continue;
663
+ }
664
+ if (existing.digest === member.digest) continue;
665
+ 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 })]);
750
666
  }
751
- async saveCodeVerifier(codeVerifier) {
752
- await this.write({ codeVerifier });
667
+ for (const [key, member] of previous) {
668
+ if (!next.has(key)) changes.push(change(spec.removed, name, `${spec.noun} ${spec.label(member)} is gone`, { member: spec.label(member), before: member }));
753
669
  }
754
- async codeVerifier() {
755
- const stored = (await this.read()).codeVerifier;
756
- if (stored === void 0) throw new Error("no PKCE verifier stored; start the login again");
757
- return stored;
670
+ return changes;
671
+ }
672
+ function compareServer(name, before, after) {
673
+ if (before.digest === after.digest) return [];
674
+ const changes = [];
675
+ if (!same(before.transport, after.transport)) {
676
+ changes.push(change("server.transport.changed", name, "the server is reached differently than when it was pinned", { before: before.transport, after: after.transport }));
758
677
  }
759
- async saveAuthorizationServerUrl(authorizationServerUrl) {
760
- await this.write({ authorizationServerUrl });
678
+ if (!same(before.serverInfo, after.serverInfo)) {
679
+ const from = before.serverInfo?.version ?? "unknown";
680
+ const to = after.serverInfo?.version ?? "unknown";
681
+ changes.push(change("server.identity.changed", name, `server identity changed (version ${from} \u2192 ${to})`, { before: before.serverInfo, after: after.serverInfo }));
761
682
  }
762
- async authorizationServerUrl() {
763
- return (await this.read()).authorizationServerUrl;
683
+ if (!same(before.protocol, after.protocol)) {
684
+ changes.push(
685
+ change("server.protocol.changed", name, `protocol changed (${before.protocol.era}/${before.protocol.version} \u2192 ${after.protocol.era}/${after.protocol.version})`, {
686
+ before: before.protocol,
687
+ after: after.protocol
688
+ })
689
+ );
764
690
  }
765
- async saveResourceUrl(resourceUrl) {
766
- await this.write({ resourceUrl });
691
+ if (!same(before.instructions, after.instructions)) {
692
+ changes.push(
693
+ change("server.instructions.changed", name, "server instructions changed: this text goes into the model's system prompt", {
694
+ before: before.instructions,
695
+ after: after.instructions
696
+ })
697
+ );
698
+ }
699
+ changes.push(...compareCapabilities(before, after, name));
700
+ changes.push(
701
+ ...compareMembers(
702
+ name,
703
+ before.tools,
704
+ after.tools,
705
+ {
706
+ key: (t) => t.name,
707
+ label: (t) => t.name,
708
+ added: "tool.added",
709
+ removed: "tool.removed",
710
+ changed: "tool.changed",
711
+ noun: "tool",
712
+ arriving: (t) => {
713
+ const can = toolCapabilities(t);
714
+ return can.length > 0 ? `can ${can.map((capability) => capability.kind).join(", ")}` : "";
715
+ }
716
+ },
717
+ (_key, a, b) => compareTool(name, a, b)
718
+ )
719
+ );
720
+ changes.push(...compareToolCapabilities(name, before.tools, after.tools));
721
+ changes.push(
722
+ ...compareMembers(name, before.resources, after.resources, {
723
+ key: (r) => r.uri,
724
+ label: (r) => `${r.name} (${r.uri})`,
725
+ added: "resource.added",
726
+ removed: "resource.removed",
727
+ changed: "resource.changed",
728
+ noun: "resource"
729
+ })
730
+ );
731
+ changes.push(
732
+ ...compareMembers(name, before.resourceTemplates, after.resourceTemplates, {
733
+ key: (t) => t.uriTemplate,
734
+ // The template itself is the capability -- widening it from file:///project/{path} to
735
+ // file:///{path} is the whole finding -- so it belongs in the label, not just the body.
736
+ label: (t) => `${t.name} (${t.uriTemplate})`,
737
+ added: "resource_template.added",
738
+ removed: "resource_template.removed",
739
+ changed: "resource_template.changed",
740
+ noun: "resource template"
741
+ })
742
+ );
743
+ changes.push(
744
+ ...compareMembers(name, before.prompts, after.prompts, {
745
+ key: (p) => p.name,
746
+ label: (p) => p.name,
747
+ added: "prompt.added",
748
+ removed: "prompt.removed",
749
+ changed: "prompt.changed",
750
+ noun: "prompt"
751
+ })
752
+ );
753
+ return changes;
754
+ }
755
+ function detectRenames(before, after, removed, added) {
756
+ const changes = [];
757
+ const renamed = /* @__PURE__ */ new Set();
758
+ const availableAdds = [...added];
759
+ for (const oldName of removed) {
760
+ const oldEntry = before.subjects[oldName];
761
+ if (!oldEntry) continue;
762
+ const match = availableAdds.find((newName) => {
763
+ const candidate = after.subjects[newName];
764
+ return candidate !== void 0 && candidate.digest === oldEntry.digest && same(candidate.transport, oldEntry.transport);
765
+ });
766
+ if (!match) continue;
767
+ availableAdds.splice(availableAdds.indexOf(match), 1);
768
+ renamed.add(oldName);
769
+ renamed.add(match);
770
+ changes.push(change("server.renamed", match, `renamed from "${oldName}"; capabilities are unchanged`, { before: oldName, after: match }));
767
771
  }
768
- async resourceUrl() {
769
- return (await this.read()).resourceUrl;
772
+ return { changes, renamed };
773
+ }
774
+ function diffLockfiles(before, after) {
775
+ const beforeNames = Object.keys(before.subjects);
776
+ const afterNames = Object.keys(after.subjects);
777
+ const removed = beforeNames.filter((name) => !afterNames.includes(name));
778
+ const added = afterNames.filter((name) => !beforeNames.includes(name));
779
+ const { changes: renameChanges, renamed } = detectRenames(before, after, removed, added);
780
+ const changes = [...renameChanges];
781
+ for (const name of added) {
782
+ if (renamed.has(name)) continue;
783
+ const entry = after.subjects[name];
784
+ const toolCount = entry?.tools?.length ?? 0;
785
+ changes.push(change("server.added", name, `new server with ${toolCount} tool${toolCount === 1 ? "" : "s"}`, { after: entry }));
770
786
  }
771
- async saveDiscoveryState(discoveryState) {
772
- await this.write({ discoveryState });
787
+ for (const name of removed) {
788
+ if (renamed.has(name)) continue;
789
+ changes.push(change("server.removed", name, "server is no longer configured", { before: before.subjects[name] }));
773
790
  }
774
- async discoveryState() {
775
- return (await this.read()).discoveryState;
791
+ for (const name of afterNames) {
792
+ const a = before.subjects[name];
793
+ const b = after.subjects[name];
794
+ if (!a || !b) continue;
795
+ changes.push(...compareServer(name, a, b));
776
796
  }
777
- async invalidateCredentials(scope) {
778
- if (scope === "all") {
779
- this.cache = { serverUrl: this.serverUrl };
780
- await rm(credentialPath(this.serverUrl), { force: true });
781
- return;
797
+ return sortChanges(changes);
798
+ }
799
+
800
+ // ../core/src/risk/steering.ts
801
+ var PATTERNS = [
802
+ // Imperatives aimed at the reader of the prompt, not at a person reading documentation.
803
+ { kind: "model-directive", pattern: /\b(ignore|disregard|override)\s+(all\s+)?(previous|prior|earlier|above)\b[^.]{0,80}/gi },
804
+ { kind: "model-directive", pattern: /\b(before|prior to)\s+(answering|responding|using this tool|continuing)\b[^.]{0,80}/gi },
805
+ { kind: "model-directive", pattern: /\b(do not|don't|never)\s+(tell|mention|inform|reveal|show)\s+(the\s+)?(user|human|operator)\b[^.]{0,60}/gi },
806
+ { kind: "model-directive", pattern: /\byou\s+(must|should|are required to)\s+(also\s+)?(read|send|include|call|fetch)\b[^.]{0,60}/gi },
807
+ // Paths that only appear in a description when something wants their contents.
808
+ { kind: "credential-path", pattern: /(~|\$HOME|\/home\/[\w.-]+|\/Users\/[\w.-]+)?[/\\]?\.(aws\/credentials|ssh\/id_[\w]+|npmrc|netrc|git-credentials|kube\/config|env)\b/gi },
809
+ { kind: "credential-path", pattern: /\b(id_rsa|id_ed25519|authorized_keys|\.pem|service-account\.json)\b/gi },
810
+ { kind: "exfiltration", pattern: /\b(send|post|upload|transmit|forward|exfiltrate)\s+[^.]{0,40}\bto\s+(https?:\/\/|[\w.-]+\.[a-z]{2,})/gi },
811
+ { kind: "exfiltration", pattern: /\b(include|append|attach)\s+(its|the|their)\s+contents?\b[^.]{0,60}/gi },
812
+ // Characters that make text render as something other than what it is.
813
+ { kind: "hidden-text", pattern: /[\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]+/g }
814
+ ];
815
+ var CONFUSABLES2 = {
816
+ "\u0430": "a",
817
+ "\u0435": "e",
818
+ "\u043E": "o",
819
+ "\u0441": "c",
820
+ "\u0440": "p",
821
+ "\u0445": "x",
822
+ "\u0443": "y",
823
+ "\u0456": "i",
824
+ "\u03BF": "o",
825
+ "\u03B1": "a",
826
+ "\u03B5": "e",
827
+ "\u03C1": "p"
828
+ };
829
+ var CONFUSABLE_PATTERN2 = new RegExp(`[${Object.keys(CONFUSABLES2).join("")}]`, "g");
830
+ function fold(text) {
831
+ return text.replace(CONFUSABLE_PATTERN2, (character) => CONFUSABLES2[character] ?? character);
832
+ }
833
+ function steeringSignals(text, field) {
834
+ if (!text) return [];
835
+ const found = [];
836
+ const seen = /* @__PURE__ */ new Set();
837
+ const folded = fold(text);
838
+ for (const { kind, pattern } of PATTERNS) {
839
+ for (const match of folded.matchAll(pattern)) {
840
+ const at = match.index ?? 0;
841
+ const raw = text.slice(at, at + match[0].length).trim();
842
+ if (raw.length === 0) continue;
843
+ const quote = /^[\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]+$/.test(raw) ? `${raw.length} invisible character(s)` : raw.length > 120 ? `${raw.slice(0, 119)}\u2026` : raw;
844
+ const key = `${kind}\0${quote}`;
845
+ if (seen.has(key)) continue;
846
+ seen.add(key);
847
+ found.push({ kind, quote, field });
782
848
  }
783
- const key = { client: "clientInformation", tokens: "tokens", verifier: "codeVerifier", discovery: "discoveryState" }[scope];
784
- await this.write({ [key]: void 0 });
785
849
  }
786
- async redirectToAuthorization(authorizationUrl) {
787
- if (!this.options.interactive) throw new InteractiveAuthRequiredError(this.serverName);
788
- openInBrowser(authorizationUrl);
789
- process.stderr.write(`
790
- If a browser did not open, visit:
791
- ${authorizationUrl.toString()}
850
+ return found;
851
+ }
792
852
 
793
- `);
853
+ // ../core/src/risk/policy.ts
854
+ function capabilityViolations(lock, denied) {
855
+ if (!denied || denied.length === 0) return [];
856
+ const forbidden = new Set(denied);
857
+ const found = [];
858
+ for (const [server2, subject] of Object.entries(lock.subjects ?? {})) {
859
+ for (const tool2 of subject.tools ?? []) {
860
+ for (const capability of toolCapabilities(tool2)) {
861
+ if (!forbidden.has(capability.kind)) continue;
862
+ found.push({ server: server2, tool: tool2.name ?? "?", kind: capability.kind, severity: capability.severity, evidence: capability.evidence });
863
+ }
864
+ }
794
865
  }
795
- };
796
- function openInBrowser(url) {
797
- const command = platform2() === "darwin" ? "open" : platform2() === "win32" ? "cmd" : "xdg-open";
798
- const args = platform2() === "win32" ? ["/c", "start", "", url.toString()] : [url.toString()];
799
- try {
800
- spawn(command, args, { detached: true, stdio: "ignore" }).unref();
801
- } catch {
866
+ return found.sort((a, b) => a.server.localeCompare(b.server) || a.tool.localeCompare(b.tool) || a.kind.localeCompare(b.kind));
867
+ }
868
+
869
+ // ../core/src/risk/surface-text.ts
870
+ var MAX_NODES = 2e4;
871
+ function schemaText(root, rootPath, out) {
872
+ const stack = [{ node: root, path: rootPath }];
873
+ const seen = /* @__PURE__ */ new WeakSet();
874
+ let budget = MAX_NODES;
875
+ while (stack.length > 0 && budget-- > 0) {
876
+ const { node, path } = stack.pop();
877
+ if (typeof node !== "object" || node === null) continue;
878
+ if (seen.has(node)) continue;
879
+ seen.add(node);
880
+ const schema = node;
881
+ if (typeof schema.description === "string") out.push({ field: path, text: schema.description });
882
+ if (typeof schema.title === "string") out.push({ field: `${path}.title`, text: schema.title });
883
+ const properties = schema.properties;
884
+ if (typeof properties === "object" && properties !== null) {
885
+ for (const [name, child] of Object.entries(properties)) {
886
+ stack.push({ node: child, path: `${path}.${name}` });
887
+ }
888
+ }
889
+ if (schema.items !== void 0) stack.push({ node: schema.items, path: `${path}[]` });
802
890
  }
803
891
  }
804
- function hasStoredCredentials(url) {
805
- try {
806
- const stored = JSON.parse(readFileSync(credentialPath(url), "utf8"));
807
- return typeof stored.tokens?.access_token === "string" && stored.tokens.access_token.length > 0;
808
- } catch {
809
- return false;
892
+ function surfaceText(subject) {
893
+ const out = [];
894
+ const push = (field, text) => {
895
+ if (typeof text === "string" && text.length > 0) out.push({ field, text });
896
+ };
897
+ push("instructions", subject.instructions);
898
+ for (const tool2 of subject.tools ?? []) {
899
+ const where = tool2.name ?? "?";
900
+ push(`${where}.title`, tool2.title);
901
+ push(`${where}.description`, tool2.description);
902
+ schemaText(tool2.inputSchema, `${where}.inputSchema`, out);
903
+ schemaText(tool2.outputSchema, `${where}.outputSchema`, out);
904
+ }
905
+ for (const prompt2 of subject.prompts ?? []) {
906
+ const where = prompt2.name ?? "?";
907
+ push(`prompt:${where}.title`, prompt2.title);
908
+ push(`prompt:${where}.description`, prompt2.description);
909
+ for (const argument of prompt2.arguments ?? []) {
910
+ push(`prompt:${where}.${argument.name ?? "?"}`, argument.description);
911
+ }
912
+ }
913
+ for (const resource2 of subject.resources ?? []) {
914
+ const where = resource2.name ?? resource2.uri ?? "?";
915
+ push(`resource:${where}.title`, resource2.title);
916
+ push(`resource:${where}.description`, resource2.description);
810
917
  }
918
+ for (const template of subject.resourceTemplates ?? []) {
919
+ const where = template.name ?? template.uriTemplate ?? "?";
920
+ push(`template:${where}.title`, template.title);
921
+ push(`template:${where}.description`, template.description);
922
+ }
923
+ return out;
811
924
  }
812
- function createAuthProvider(server2, options = {}) {
813
- if (server2.transport.type === "stdio") return void 0;
814
- const oauth = server2.transport.oauth;
815
- if (oauth?.clientId !== void 0 && oauth.clientSecret !== void 0) {
816
- return new ClientCredentialsProvider({
817
- clientId: oauth.clientId,
818
- clientSecret: oauth.clientSecret,
819
- clientName: `nulladrift ${VERSION}`,
820
- ...oauth.scope === void 0 ? {} : { scope: oauth.scope }
821
- });
925
+
926
+ // ../core/src/risk/arrival.ts
927
+ function identity(signal) {
928
+ return `${signal.field}\0${signal.kind}\0${signal.quote}`;
929
+ }
930
+ function signalsFor(subject) {
931
+ if (typeof subject !== "object" || subject === null) return [];
932
+ return surfaceText(subject).flatMap(
933
+ (piece) => steeringSignals(piece.text, piece.field)
934
+ );
935
+ }
936
+ function newSteering(committed, observed) {
937
+ const found = [];
938
+ for (const [server2, subject] of Object.entries(observed.subjects ?? {})) {
939
+ const before = new Set(signalsFor(committed.subjects?.[server2]).map(identity));
940
+ const signals = signalsFor(subject).filter((signal) => !before.has(identity(signal)));
941
+ if (signals.length > 0) found.push({ server: server2, signals });
822
942
  }
823
- const interactive = options.interactive ?? false;
824
- if (!interactive && !hasStoredCredentials(server2.transport.url)) return void 0;
825
- return new FileTokenProvider(server2.name, server2.transport.url, {
826
- interactive,
827
- ...oauth?.scope === void 0 ? {} : { scope: oauth.scope }
943
+ return found.sort((a, b) => a.server.localeCompare(b.server));
944
+ }
945
+
946
+ // src/lib/ui.ts
947
+ var enabled = process.stdout.isTTY === true && process.env["NO_COLOR"] === void 0 && process.env["TERM"] !== "dumb";
948
+ var wrap = (code) => (text) => enabled ? `\x1B[${code}m${text}\x1B[0m` : text;
949
+ var bold = wrap(1);
950
+ var dim = wrap(2);
951
+ var red = wrap(31);
952
+ var green = wrap(32);
953
+ var yellow = wrap(33);
954
+ var blue = wrap(34);
955
+ function visibleControls(text) {
956
+ return text.replace(
957
+ // C0 and C1 controls and DEL, plus the bidirectional overrides and zero-width characters
958
+ // that change what a line appears to say without changing what it is.
959
+ // eslint-disable-next-line no-control-regex
960
+ /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g,
961
+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
962
+ );
963
+ }
964
+ function truncate(text, limit = 160) {
965
+ const collapsed = visibleControls(text).replace(/\s+/g, " ").trim();
966
+ return collapsed.length <= limit ? collapsed : `${collapsed.slice(0, limit - 1)}\u2026`;
967
+ }
968
+ function elideMiddle(path, limit) {
969
+ if (path.length <= limit) return path;
970
+ const keep = Math.floor((limit - 1) / 2);
971
+ return `${path.slice(0, keep)}\u2026${path.slice(-keep)}`;
972
+ }
973
+
974
+ // src/config/discover.ts
975
+ import { readFile as readFile2 } from "fs/promises";
976
+ import { homedir as homedir2, platform } from "os";
977
+ import { isAbsolute, join, relative, resolve as resolve2, sep } from "path";
978
+
979
+ // src/config/parsers.ts
980
+ import { readFile } from "fs/promises";
981
+ import { resolve } from "path";
982
+ import { z } from "zod";
983
+
984
+ // src/config/expand.ts
985
+ import { homedir } from "os";
986
+ var PLACEHOLDER = /\$\{([^}]+)\}/g;
987
+ function expand(input, context) {
988
+ const unresolved = [];
989
+ const value = input.replace(PLACEHOLDER, (match, body) => {
990
+ if (body === "workspaceFolder") return context.workspaceFolder;
991
+ if (body === "userHome") return homedir();
992
+ if (body === "pathSeparator" || body === "/") return "/";
993
+ if (body.startsWith("input:") || body.startsWith("command:")) {
994
+ unresolved.push(match);
995
+ return match;
996
+ }
997
+ if (body.startsWith("env:")) {
998
+ const name = body.slice(4);
999
+ const found2 = context.env[name];
1000
+ if (found2 !== void 0) return found2;
1001
+ unresolved.push(match);
1002
+ return match;
1003
+ }
1004
+ const defaultAt = body.indexOf(":-");
1005
+ if (defaultAt !== -1) {
1006
+ const name = body.slice(0, defaultAt);
1007
+ return context.env[name] ?? body.slice(defaultAt + 2);
1008
+ }
1009
+ const found = context.env[body];
1010
+ if (found !== void 0) return found;
1011
+ unresolved.push(match);
1012
+ return match;
828
1013
  });
1014
+ return { value, unresolved };
829
1015
  }
830
1016
 
831
- // src/mcp/types.ts
832
- import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/client";
833
- var UnreachableServerError = class extends Error {
834
- constructor(serverName, message, cause) {
1017
+ // src/config/parsers.ts
1018
+ var serverEntrySchema = z.looseObject({
1019
+ type: z.string().optional(),
1020
+ command: z.string().optional(),
1021
+ args: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
1022
+ env: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])).optional(),
1023
+ cwd: z.string().optional(),
1024
+ url: z.string().optional(),
1025
+ headers: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
1026
+ envFile: z.string().optional(),
1027
+ headersHelper: z.string().optional(),
1028
+ oauth: z.looseObject({
1029
+ clientId: z.string().optional(),
1030
+ clientSecret: z.string().optional(),
1031
+ scope: z.string().optional(),
1032
+ scopes: z.array(z.string()).optional()
1033
+ }).optional()
1034
+ });
1035
+ var UnsupportedServerError = class extends Error {
1036
+ constructor(serverName, message) {
835
1037
  super(message);
836
1038
  this.serverName = serverName;
837
- this.cause = cause;
838
- this.name = "UnreachableServerError";
1039
+ this.name = "UnsupportedServerError";
839
1040
  }
840
1041
  serverName;
841
- cause;
842
1042
  };
843
- function authFailureKind(error) {
844
- if (!isAuthFailure(error)) return void 0;
845
- const text = `${error instanceof Error ? error.message : String(error)}`.toLowerCase();
846
- const cause = error instanceof UnreachableServerError && error.cause instanceof Error ? error.cause.message.toLowerCase() : "";
847
- const both = `${text} ${cause}`;
848
- const scoped = [error, error instanceof UnreachableServerError ? error.cause : void 0].some(
849
- (candidate) => candidate instanceof Error && candidate.name === "InsufficientScopeError"
850
- );
851
- if (scoped || /\b403\b|forbidden|insufficient[_ ]scope/.test(both)) return "forbidden";
852
- return "auth";
853
- }
854
- function isAuthFailure(error) {
855
- if (error instanceof UnauthorizedError2) return true;
856
- if (error instanceof Error && error.name === "InteractiveAuthRequiredError") return true;
857
- if (error instanceof UnreachableServerError && error.cause instanceof Error && error.cause.name === "InteractiveAuthRequiredError") return true;
858
- const cause = error instanceof UnreachableServerError ? error.cause : void 0;
859
- if (cause instanceof UnauthorizedError2) return true;
860
- for (const candidate of [error, error instanceof UnreachableServerError ? error.cause : void 0]) {
861
- const name = candidate instanceof Error ? candidate.name : "";
862
- if (name === "RegistrationRejectedError" || name === "InsufficientScopeError" || name === "OAuthClientFlowError") return true;
863
- }
864
- const outer = `${error instanceof Error ? error.message : String(error)}`;
865
- const inner = error instanceof UnreachableServerError && error.cause instanceof Error ? error.cause.message : "";
866
- const text = `${outer} ${inner}`.toLowerCase();
867
- return /\b(401|403)\b|unauthorized|forbidden|invalid or missing.*token|authentication required|invalid_client|dynamic client registration/.test(text);
868
- }
869
-
870
- // src/mcp/connect.ts
871
- var DEFAULT_TIMEOUT_MS = 3e4;
872
- var STDERR_KEEP_BYTES = 2e3;
873
- function buildTransport(server2, captureStderr = () => {
874
- }, options = {}) {
875
- const { transport: transport2 } = server2;
876
- if (transport2.type === "stdio") {
877
- const child = new StdioClientTransport({
878
- command: transport2.command,
879
- args: transport2.args,
880
- // The server's own environment plus whatever the config sets. Never the auditor's full env.
881
- env: { ...getDefaultEnvironment(), ...transport2.env },
882
- cwd: transport2.cwd,
883
- // Piped rather than inherited: a chatty server must not interleave with our report, but its
884
- // last words are the most useful thing we can show when it fails to answer.
885
- stderr: "pipe"
886
- });
887
- child.stderr?.on("data", (chunk) => captureStderr(chunk.toString("utf8")));
888
- return child;
889
- }
890
- const headers = { ...transport2.headers, "user-agent": `nulladrift/${VERSION}` };
891
- const url = new URL(transport2.url);
892
- const authProvider = createAuthProvider(server2, options);
893
- if (transport2.type === "sse") return new SSEClientTransport(url, { requestInit: { headers }, authProvider });
894
- return new StreamableHTTPClientTransport(url, { requestInit: { headers }, authProvider });
895
- }
896
- function diagnosticLines(stderr, limit = 3) {
897
- const lines = stderr.split("\n").map((line) => line.trimEnd()).filter((line) => line.trim().length > 0).filter((line) => !/^\s*(at\s|\^+$|[}\])]+$|Node\.js v[\d.]+$)/.test(line));
898
- const named = lines.filter((line) => /\b(error|exception|cannot|failed|refused|denied|not found|enoent|eacces)\b/i.test(line));
899
- const chosen = named.length > 0 ? named : lines;
900
- return chosen.slice(0, limit).map((line) => line.trim());
1043
+ function scalarsToStrings(record) {
1044
+ const out = {};
1045
+ for (const [key, value] of Object.entries(record ?? {})) {
1046
+ if (value === null) continue;
1047
+ out[key] = String(value);
1048
+ }
1049
+ return out;
901
1050
  }
902
- async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS, options = {}) {
903
- let stderrBuffer = "";
904
- const captureStderr = (chunk) => {
905
- stderrBuffer = (stderrBuffer + chunk).slice(-STDERR_KEEP_BYTES);
1051
+ function resolveTransport(name, entry, context) {
1052
+ const unresolved = [];
1053
+ const take = (input) => {
1054
+ const result = expand(input, context);
1055
+ unresolved.push(...result.unresolved);
1056
+ return result.value;
906
1057
  };
907
- const client = new Client(
908
- { name: "nulladrift", title: "nulladrift", version: VERSION },
909
- {
910
- /*
911
- * We advertise nothing. An auditor never calls a tool, so it has no business offering
912
- * elicitation, sampling or roots -- a server that asks for them gets nothing to work with.
913
- */
914
- capabilities: {},
915
- versionNegotiation: { mode: "auto", probe: { timeoutMs } }
916
- }
917
- );
1058
+ const declared = entry.type === "streamable-http" ? "http" : entry.type;
1059
+ if (declared === "ws") {
1060
+ throw new UnsupportedServerError(name, "WebSocket transport is not supported by the MCP specification or the SDK");
1061
+ }
918
1062
  let transport2;
919
- try {
920
- transport2 = buildTransport(server2, captureStderr, options);
921
- } catch (error) {
922
- throw new UnreachableServerError(server2.name, `could not prepare transport: ${error.message}`, error);
1063
+ if (declared === "http" || declared === "sse" || declared === void 0 && entry.url !== void 0) {
1064
+ if (entry.url === void 0) throw new UnsupportedServerError(name, `transport "${declared}" needs a url`);
1065
+ const oauth = entry.oauth;
1066
+ transport2 = {
1067
+ type: declared === "sse" ? "sse" : "http",
1068
+ url: take(entry.url),
1069
+ asWritten: { url: String(entry.url) },
1070
+ headers: Object.fromEntries(Object.entries(scalarsToStrings(entry.headers)).map(([key, value]) => [key, take(value)])),
1071
+ ...oauth === void 0 ? {} : {
1072
+ oauth: {
1073
+ // Expanded here so a secret can live in the environment rather than the config file.
1074
+ clientId: oauth.clientId === void 0 ? void 0 : take(oauth.clientId),
1075
+ clientSecret: oauth.clientSecret === void 0 ? void 0 : take(oauth.clientSecret),
1076
+ scope: oauth.scope ?? oauth.scopes?.join(" ")
1077
+ }
1078
+ }
1079
+ };
1080
+ } else {
1081
+ if (entry.command === void 0) throw new UnsupportedServerError(name, "stdio server has no command");
1082
+ transport2 = {
1083
+ type: "stdio",
1084
+ command: take(entry.command),
1085
+ args: (entry.args ?? []).map((argument) => take(String(argument))),
1086
+ asWritten: { command: String(entry.command), args: (entry.args ?? []).map((argument) => String(argument)) },
1087
+ env: Object.fromEntries(Object.entries(scalarsToStrings(entry.env)).map(([key, value]) => [key, take(value)])),
1088
+ cwd: entry.cwd ? take(entry.cwd) : void 0
1089
+ };
923
1090
  }
924
- try {
925
- await client.connect(transport2, { timeout: timeoutMs });
926
- } catch (error) {
927
- await client.close().catch(() => {
928
- });
929
- const detail = stderrBuffer.trim();
930
- throw new UnreachableServerError(
931
- server2.name,
932
- `${error.message}${detail ? `
933
- server stderr: ${diagnosticLines(detail).join("\n ")}` : ""}`,
934
- error
1091
+ if (unresolved.length > 0) {
1092
+ const names = [...new Set(unresolved)].join(", ");
1093
+ throw new UnsupportedServerError(
1094
+ name,
1095
+ `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.`
935
1096
  );
936
1097
  }
937
- return {
938
- client,
939
- stderr: () => stderrBuffer,
940
- close: async () => {
941
- await client.close().catch(() => {
942
- });
943
- }
944
- };
1098
+ return transport2;
945
1099
  }
946
-
947
- // src/mcp/capture.ts
948
- var FRESH = { cacheMode: "bypass" };
949
- async function listOrEmpty(label, serverName, fetchList) {
950
- try {
951
- return await fetchList();
952
- } catch (error) {
953
- throw new UnreachableServerError(serverName, `${label} failed: ${error.message}`, error);
1100
+ function detectMapKey(raw) {
1101
+ if (typeof raw !== "object" || raw === null) return void 0;
1102
+ const record = raw;
1103
+ for (const key of ["mcpServers", "servers"]) {
1104
+ if (typeof record[key] === "object" && record[key] !== null) return key;
954
1105
  }
1106
+ return void 0;
955
1107
  }
956
- function readProtocol(client) {
957
- const era = client.getProtocolEra() ?? "legacy";
958
- const version = client.getNegotiatedProtocolVersion() ?? "unknown";
959
- const discovered = client.getDiscoverResult();
960
- return {
961
- era,
962
- version,
963
- supportedVersions: discovered?.supportedVersions
964
- };
965
- }
966
- function readServerInfo(client) {
967
- const info = client.getServerVersion();
968
- if (!info) return void 0;
969
- return {
970
- name: info.name,
971
- title: info.title,
972
- version: info.version,
973
- description: info.description,
974
- websiteUrl: info.websiteUrl
975
- };
976
- }
977
- async function captureSurface(server2, timeoutMs = DEFAULT_TIMEOUT_MS) {
978
- const connection = await connect(server2, timeoutMs);
979
- const { client } = connection;
980
- try {
981
- const capabilities = client.getServerCapabilities();
982
- const [tools, resources, resourceTemplates, prompts] = await Promise.all([
983
- capabilities?.tools ? listOrEmpty("tools/list", server2.name, async () => (await client.listTools(void 0, FRESH)).tools) : [],
984
- capabilities?.resources ? listOrEmpty("resources/list", server2.name, async () => (await client.listResources(void 0, FRESH)).resources) : [],
985
- capabilities?.resources ? listOrEmpty("resources/templates/list", server2.name, async () => (await client.listResourceTemplates(void 0, FRESH)).resourceTemplates) : [],
986
- capabilities?.prompts ? listOrEmpty("prompts/list", server2.name, async () => (await client.listPrompts(void 0, FRESH)).prompts) : []
987
- ]);
988
- return {
989
- protocol: readProtocol(client),
990
- serverInfo: readServerInfo(client),
991
- capabilities: capabilities ? toJson(capabilities) : void 0,
992
- // Clients place this in the model's system prompt, so it is part of the capability surface.
993
- instructions: client.getInstructions(),
994
- tools,
995
- resources,
996
- resourceTemplates,
997
- prompts
998
- };
999
- } finally {
1000
- await connection.close();
1108
+ async function readEnvFile(path) {
1109
+ const out = {};
1110
+ const text = await readFile(path, "utf8");
1111
+ for (const line of text.split(/\r?\n/)) {
1112
+ const trimmed = line.trim();
1113
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
1114
+ const at = trimmed.indexOf("=");
1115
+ if (at <= 0) continue;
1116
+ const key = trimmed.slice(0, at).trim().replace(/^export\s+/, "");
1117
+ let value = trimmed.slice(at + 1).trim();
1118
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1119
+ value = value.slice(1, -1);
1120
+ }
1121
+ out[key] = value;
1001
1122
  }
1123
+ return out;
1002
1124
  }
1003
-
1004
- // src/audit.ts
1005
- async function mapWithLimit(items, limit, worker) {
1006
- const results = new Array(items.length);
1007
- let next = 0;
1008
- const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
1009
- for (; ; ) {
1010
- const index = next++;
1011
- const item = items[index];
1012
- if (index >= items.length || item === void 0) return;
1013
- results[index] = await worker(item);
1125
+ async function parseServerMap(raw, mapKey, source, context) {
1126
+ const servers = [];
1127
+ const skipped = [];
1128
+ if (typeof raw !== "object" || raw === null) return { servers, skipped };
1129
+ const map = raw[mapKey];
1130
+ if (typeof map !== "object" || map === null) return { servers, skipped };
1131
+ for (const [name, value] of Object.entries(map)) {
1132
+ const entry = serverEntrySchema.safeParse(value);
1133
+ if (!entry.success) {
1134
+ skipped.push(new UnsupportedServerError(name, `entry is not a server definition: ${entry.error.issues[0]?.message ?? "unknown"}`));
1135
+ continue;
1014
1136
  }
1015
- });
1016
- await Promise.all(runners);
1017
- return results;
1018
- }
1019
- async function captureAll(options) {
1020
- const discovery = await discoverServers(options.projectRoot, options.configFiles);
1021
- const captured = await mapWithLimit(discovery.servers, options.concurrency ?? 4, async (server2) => {
1022
1137
  try {
1023
- const surface = await captureSurface(server2, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1024
- options.onServerDone?.(server2.name, "captured");
1025
- return { name: server2.name, entry: buildLockedServer(server2, surface, options.policy) };
1138
+ if (entry.data.headersHelper !== void 0) {
1139
+ throw new UnsupportedServerError(name, "`headersHelper` runs a command to produce headers, which this tool will not execute");
1140
+ }
1141
+ const transport2 = resolveTransport(name, entry.data, context);
1142
+ if (transport2.type === "stdio" && entry.data.envFile !== void 0) {
1143
+ const expanded = expand(entry.data.envFile, context);
1144
+ if (expanded.unresolved.length > 0) {
1145
+ throw new UnsupportedServerError(name, `envFile path contains unresolved placeholders: ${expanded.unresolved.join(", ")}`);
1146
+ }
1147
+ try {
1148
+ transport2.env = { ...await readEnvFile(resolve(context.workspaceFolder, expanded.value)), ...transport2.env };
1149
+ } catch (error) {
1150
+ throw new UnsupportedServerError(name, `envFile ${expanded.value} could not be read: ${error.message}`);
1151
+ }
1152
+ }
1153
+ servers.push({ name, source: { ...source }, transport: transport2 });
1026
1154
  } catch (error) {
1027
- options.onServerDone?.(server2.name, "failed");
1028
- const reason = error instanceof UnreachableServerError ? error.message : error.message;
1029
- const kind = authFailureKind(error) ?? "unreachable";
1030
- return { name: server2.name, failure: { server: server2.name, reason, kind } };
1155
+ if (error instanceof UnsupportedServerError) skipped.push(error);
1156
+ else throw error;
1031
1157
  }
1032
- });
1033
- const subjects = {};
1034
- const unreachable = [];
1035
- for (const result of captured) {
1036
- if ("entry" in result && result.entry) subjects[result.name] = result.entry;
1037
- else if ("failure" in result && result.failure) unreachable.push(result.failure);
1038
1158
  }
1039
- for (const skipped of discovery.skipped) {
1040
- unreachable.push({ server: skipped.serverName, reason: skipped.message, kind: "unreachable" });
1159
+ return { servers, skipped };
1160
+ }
1161
+ async function parseClaudeJson(raw, projectRoot, source, context) {
1162
+ const user = await parseServerMap(raw, "mcpServers", { ...source, scope: "user" }, context);
1163
+ const projects = typeof raw === "object" && raw !== null ? raw["projects"] : void 0;
1164
+ const forProject = typeof projects === "object" && projects !== null ? projects[projectRoot] : void 0;
1165
+ const local = forProject ? await parseServerMap(forProject, "mcpServers", { ...source, scope: "local" }, context) : { servers: [], skipped: [] };
1166
+ return { servers: [...user.servers, ...local.servers], skipped: [...user.skipped, ...local.skipped] };
1167
+ }
1168
+ var CLIENT_MAP_KEY = {
1169
+ "claude-code": "mcpServers",
1170
+ "claude-desktop": "mcpServers",
1171
+ vscode: "servers",
1172
+ cursor: "mcpServers",
1173
+ copilot: "mcpServers",
1174
+ windsurf: "mcpServers",
1175
+ generic: "mcpServers",
1176
+ manual: "mcpServers"
1177
+ };
1178
+
1179
+ // src/config/discover.ts
1180
+ function claudeDesktopPath() {
1181
+ const home = homedir2();
1182
+ switch (platform()) {
1183
+ case "darwin":
1184
+ return join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
1185
+ case "win32":
1186
+ return join(process.env["APPDATA"] ?? join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
1187
+ default:
1188
+ return join(home, ".config", "Claude", "claude_desktop_config.json");
1189
+ }
1190
+ }
1191
+ function candidateConfigFiles(projectRoot) {
1192
+ const home = homedir2();
1193
+ const copilotHome = process.env["COPILOT_HOME"] ?? join(home, ".copilot");
1194
+ return [
1195
+ { client: "claude-code", path: join(projectRoot, ".mcp.json"), scope: "project" },
1196
+ { client: "vscode", path: join(projectRoot, ".vscode", "mcp.json"), scope: "project" },
1197
+ { client: "cursor", path: join(projectRoot, ".cursor", "mcp.json"), scope: "project" },
1198
+ { client: "claude-code", path: join(home, ".claude.json"), scope: "user" },
1199
+ { client: "cursor", path: join(home, ".cursor", "mcp.json"), scope: "user" },
1200
+ { client: "claude-desktop", path: claudeDesktopPath(), scope: "user" },
1201
+ { client: "windsurf", path: join(home, ".codeium", "windsurf", "mcp_config.json"), scope: "user" },
1202
+ { client: "copilot", path: join(copilotHome, "mcp-config.json"), scope: "user" }
1203
+ ];
1204
+ }
1205
+ function portablePath(absolute, projectRoot) {
1206
+ const fromProject = relative(projectRoot, absolute);
1207
+ if (!fromProject.startsWith("..") && !isAbsolute(fromProject)) return fromProject.split(sep).join("/");
1208
+ const fromHome = relative(homedir2(), absolute);
1209
+ if (!fromHome.startsWith("..") && !isAbsolute(fromHome)) return `~/${fromHome.split(sep).join("/")}`;
1210
+ return absolute.split(sep).join("/");
1211
+ }
1212
+ async function readJsonIfPresent(path) {
1213
+ let text;
1214
+ try {
1215
+ text = await readFile2(path, "utf8");
1216
+ } catch (error) {
1217
+ const code = error.code;
1218
+ if (code === "ENOENT" || code === "ENOTDIR") return { present: false };
1219
+ if (code === "EACCES") return { present: true, ok: false, reason: "permission denied" };
1220
+ throw error;
1041
1221
  }
1042
- for (const problem of discovery.problems) {
1043
- unreachable.push({ server: problem.file, reason: problem.reason, kind: "unreachable" });
1222
+ try {
1223
+ return { present: true, ok: true, value: JSON.parse(text) };
1224
+ } catch (error) {
1225
+ return { present: true, ok: false, reason: `not valid JSON: ${error.message}` };
1044
1226
  }
1045
- return {
1046
- lock: {
1047
- lockfileVersion: LOCKFILE_VERSION,
1048
- generatedBy: `nulladrift@${VERSION}`,
1049
- policy: options.policy,
1050
- subjects
1051
- },
1052
- unreachable,
1053
- discovery
1054
- };
1055
- }
1056
-
1057
- // ../core/src/diff/schema.ts
1058
- function numberAt(node, key) {
1059
- const value = node[key];
1060
- return typeof value === "number" ? value : void 0;
1061
1227
  }
1062
- function collectFacts(schema) {
1063
- const facts = /* @__PURE__ */ new Map();
1064
- const visit = (node, path, required, depth) => {
1065
- if (depth > MAX_VISIT_DEPTH || facts.size >= MAX_FACTS) return;
1066
- const object = effectiveSchema(node, schema);
1067
- if (!object) return;
1068
- const typeValue = object["type"];
1069
- const types = typeof typeValue === "string" ? [typeValue] : Array.isArray(typeValue) ? typeValue.filter((entry) => typeof entry === "string").sort() : void 0;
1070
- const enumValue = object["enum"];
1071
- facts.set(path, {
1072
- required,
1073
- additionalProperties: typeof object["additionalProperties"] === "boolean" ? object["additionalProperties"] : void 0,
1074
- enumMembers: Array.isArray(enumValue) ? enumValue.map((entry) => canonicalize(entry)).sort() : void 0,
1075
- types,
1076
- minimum: numberAt(object, "minimum"),
1077
- maximum: numberAt(object, "maximum"),
1078
- minLength: numberAt(object, "minLength"),
1079
- maxLength: numberAt(object, "maxLength")
1080
- });
1081
- const properties = asObject(object["properties"]);
1082
- if (properties) {
1083
- const requiredList = Array.isArray(object["required"]) ? object["required"].filter((entry) => typeof entry === "string") : [];
1084
- for (const [name, child] of Object.entries(properties)) {
1085
- visit(child, path === "" ? name : `${path}.${name}`, requiredList.includes(name), depth + 1);
1086
- }
1087
- }
1088
- const items = object["items"];
1089
- if (items !== void 0) visit(items, `${path}[]`, false, depth + 1);
1090
- const prefixItems = object["prefixItems"];
1091
- if (Array.isArray(prefixItems)) prefixItems.forEach((entry, index) => visit(entry, `${path}[${index}]`, false, depth + 1));
1092
- for (const branch of alternatives(object)) visit(branch.schema, `${path}|${branch.label}`, false, depth + 1);
1093
- };
1094
- visit(schema, "", true, 0);
1095
- return facts;
1228
+ function anchorCwd(server2, projectRoot) {
1229
+ const { transport: transport2 } = server2;
1230
+ if (transport2.type !== "stdio" || transport2.cwd === void 0 || isAbsolute(transport2.cwd)) return server2;
1231
+ return { ...server2, transport: { ...transport2, cwd: resolve2(projectRoot, transport2.cwd) } };
1096
1232
  }
1097
- function isSuperset(next, previous) {
1098
- return previous.every((entry) => next.includes(entry));
1233
+ function describeSearch(searched, filesRead) {
1234
+ const read = new Set(filesRead);
1235
+ const lines = searched.map((path) => ` ${(read.has(path) ? "read" : "absent").padEnd(6)} ${path}`);
1236
+ return lines.join("\n");
1099
1237
  }
1100
- function classifySchemaChange(before, after) {
1101
- if (stableKey(before) === stableKey(after)) return "same";
1102
- const previous = collectFacts(before);
1103
- const next = collectFacts(after);
1104
- let widened = false;
1105
- let narrowed = false;
1106
- for (const path of /* @__PURE__ */ new Set([...previous.keys(), ...next.keys()])) {
1107
- const a = previous.get(path);
1108
- const b = next.get(path);
1109
- if (!a && b) {
1110
- widened = true;
1238
+ async function discoverServers(projectRoot, extraFiles = []) {
1239
+ const context = { workspaceFolder: projectRoot, env: process.env };
1240
+ const files = [
1241
+ ...extraFiles.map((path) => ({ client: "generic", path: resolve2(projectRoot, path) })),
1242
+ ...candidateConfigFiles(projectRoot)
1243
+ ];
1244
+ const byName2 = /* @__PURE__ */ new Map();
1245
+ const skipped = [];
1246
+ const filesRead = [];
1247
+ const shadowed = [];
1248
+ const problems = [];
1249
+ const requested = new Set(files.filter((file) => file.client === "generic").map((file) => file.path));
1250
+ for (const file of files) {
1251
+ const read = await readJsonIfPresent(file.path);
1252
+ if (!read.present) {
1253
+ if (requested.has(file.path)) {
1254
+ problems.push({ file: portablePath(file.path, projectRoot), reason: "no such file; it was named with --config" });
1255
+ }
1111
1256
  continue;
1112
1257
  }
1113
- if (a && !b) {
1114
- narrowed = true;
1258
+ if (!read.ok) {
1259
+ problems.push({ file: portablePath(file.path, projectRoot), reason: read.reason });
1115
1260
  continue;
1116
1261
  }
1117
- if (!a || !b) continue;
1118
- if (a.required && !b.required) widened = true;
1119
- if (!a.required && b.required) narrowed = true;
1120
- const beforeAdditional = a.additionalProperties ?? true;
1121
- const afterAdditional = b.additionalProperties ?? true;
1122
- if (!beforeAdditional && afterAdditional) widened = true;
1123
- if (beforeAdditional && !afterAdditional) narrowed = true;
1124
- if (a.enumMembers && b.enumMembers) {
1125
- if (isSuperset(b.enumMembers, a.enumMembers) && b.enumMembers.length > a.enumMembers.length) widened = true;
1126
- else if (isSuperset(a.enumMembers, b.enumMembers) && a.enumMembers.length > b.enumMembers.length) narrowed = true;
1127
- else if (canonicalize(a.enumMembers) !== canonicalize(b.enumMembers)) {
1128
- widened = true;
1129
- narrowed = true;
1130
- }
1131
- } else if (a.enumMembers && !b.enumMembers) widened = true;
1132
- else if (!a.enumMembers && b.enumMembers) narrowed = true;
1133
- if (a.types && b.types) {
1134
- if (isSuperset(b.types, a.types) && b.types.length > a.types.length) widened = true;
1135
- else if (isSuperset(a.types, b.types) && a.types.length > b.types.length) narrowed = true;
1136
- else if (canonicalize(a.types) !== canonicalize(b.types)) {
1137
- widened = true;
1138
- narrowed = true;
1139
- }
1140
- } else if (a.types && !b.types) widened = true;
1141
- else if (!a.types && b.types) narrowed = true;
1142
- const lowerBounds = [["minimum", a.minimum, b.minimum], ["minLength", a.minLength, b.minLength]];
1143
- for (const [, before_, after_] of lowerBounds) {
1144
- if (before_ !== void 0 && after_ === void 0) widened = true;
1145
- else if (before_ === void 0 && after_ !== void 0) narrowed = true;
1146
- else if (before_ !== void 0 && after_ !== void 0) {
1147
- if (after_ < before_) widened = true;
1148
- if (after_ > before_) narrowed = true;
1262
+ const raw = read.value;
1263
+ filesRead.push(file.path);
1264
+ const source = { client: file.client, file: portablePath(file.path, projectRoot) };
1265
+ let mapKey = CLIENT_MAP_KEY[file.client];
1266
+ if (file.client === "generic") {
1267
+ mapKey = detectMapKey(raw);
1268
+ if (mapKey === void 0) {
1269
+ problems.push({ file: source.file, reason: "no `mcpServers` or `servers` object found; this does not look like an MCP client config" });
1270
+ continue;
1149
1271
  }
1150
1272
  }
1151
- const upperBounds = [["maximum", a.maximum, b.maximum], ["maxLength", a.maxLength, b.maxLength]];
1152
- for (const [, before_, after_] of upperBounds) {
1153
- if (before_ !== void 0 && after_ === void 0) widened = true;
1154
- else if (before_ === void 0 && after_ !== void 0) narrowed = true;
1155
- else if (before_ !== void 0 && after_ !== void 0) {
1156
- if (after_ > before_) widened = true;
1157
- if (after_ < before_) narrowed = true;
1273
+ const parsed = file.client === "claude-code" && file.scope === "user" ? await parseClaudeJson(raw, projectRoot, source, context) : await parseServerMap(raw, mapKey, { ...source, scope: file.scope }, context);
1274
+ skipped.push(...parsed.skipped);
1275
+ for (const server2 of parsed.servers.map((entry) => anchorCwd(entry, projectRoot))) {
1276
+ const existing = byName2.get(server2.name);
1277
+ if (existing) {
1278
+ shadowed.push({ name: server2.name, keptFrom: existing.from, alsoIn: source.file });
1279
+ continue;
1158
1280
  }
1281
+ byName2.set(server2.name, { server: server2, from: source.file });
1159
1282
  }
1160
1283
  }
1161
- if (widened && !narrowed) return "widened";
1162
- if (narrowed && !widened) return "narrowed";
1163
- return "changed";
1284
+ return {
1285
+ servers: [...byName2.values()].map((entry) => entry.server).sort((a, b) => a.name.localeCompare(b.name)),
1286
+ skipped,
1287
+ filesRead,
1288
+ searched: files.map((file) => file.path),
1289
+ shadowed,
1290
+ problems
1291
+ };
1164
1292
  }
1165
-
1166
- // ../core/src/changes.ts
1167
- var CHANGE_KINDS = [
1168
- "server.added",
1169
- "server.removed",
1170
- "server.renamed",
1171
- "server.transport.changed",
1172
- "server.identity.changed",
1173
- "server.protocol.changed",
1174
- "server.instructions.changed",
1175
- "server.capabilities.widened",
1176
- "server.capabilities.narrowed",
1177
- "server.capabilities.changed",
1178
- "tool.added",
1179
- "tool.removed",
1180
- "tool.description.changed",
1181
- "tool.input_schema.widened",
1182
- "tool.input_schema.narrowed",
1183
- "tool.input_schema.changed",
1184
- "tool.output_schema.changed",
1185
- "tool.behavior.escalated",
1186
- "tool.behavior.relaxed",
1187
- "tool.header_params.changed",
1188
- "tool.changed",
1189
- "resource.added",
1190
- "resource.removed",
1191
- "resource.changed",
1192
- "resource_template.added",
1193
- "resource_template.removed",
1194
- "resource_template.changed",
1195
- "prompt.added",
1196
- "prompt.removed",
1197
- "prompt.changed"
1198
- ];
1199
- var SEVERITY = {
1200
- "server.added": "medium",
1201
- "server.removed": "low",
1202
- "server.renamed": "low",
1203
- "server.transport.changed": "high",
1204
- "server.identity.changed": "medium",
1205
- "server.protocol.changed": "medium",
1206
- "server.instructions.changed": "high",
1207
- "server.capabilities.widened": "medium",
1208
- "server.capabilities.narrowed": "low",
1209
- "server.capabilities.changed": "medium",
1210
- "tool.added": "high",
1211
- "tool.removed": "low",
1212
- "tool.description.changed": "high",
1213
- "tool.input_schema.widened": "high",
1214
- "tool.input_schema.narrowed": "low",
1215
- "tool.input_schema.changed": "medium",
1216
- "tool.output_schema.changed": "medium",
1217
- "tool.behavior.escalated": "high",
1218
- "tool.behavior.relaxed": "low",
1219
- "tool.header_params.changed": "high",
1220
- "tool.changed": "medium",
1221
- "resource.added": "medium",
1222
- "resource.removed": "low",
1223
- "resource.changed": "medium",
1224
- "resource_template.added": "high",
1225
- "resource_template.removed": "low",
1226
- "resource_template.changed": "high",
1227
- "prompt.added": "medium",
1228
- "prompt.removed": "low",
1229
- "prompt.changed": "medium"
1230
- };
1231
- var SEVERITY_RANK = { high: 0, medium: 1, low: 2 };
1232
- function sortChanges(changes) {
1233
- return [...changes].sort(
1234
- (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)
1235
- );
1293
+
1294
+ // src/lock/build.ts
1295
+ function byName(members) {
1296
+ return [...members].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1236
1297
  }
1237
- function serversThatShippedNothing(changes) {
1238
- const moved = /* @__PURE__ */ new Set();
1239
- const versioned = /* @__PURE__ */ new Set();
1240
- for (const change2 of changes) {
1241
- moved.add(change2.server);
1242
- if (change2.kind === "server.identity.changed") versioned.add(change2.server);
1298
+ function lockIcons(icons) {
1299
+ if (!icons || icons.length === 0) return void 0;
1300
+ return icons.map((icon2) => ({
1301
+ src: icon2.src,
1302
+ mimeType: icon2.mimeType,
1303
+ sizes: icon2.sizes,
1304
+ theme: icon2.theme
1305
+ }));
1306
+ }
1307
+ function sealed(entry) {
1308
+ return { ...entry, digest: digest(toJson(entry)) };
1309
+ }
1310
+ function lockTransport(server2) {
1311
+ const { transport: transport2 } = server2;
1312
+ if (transport2.type === "stdio") {
1313
+ const command = transport2.asWritten?.command ?? transport2.command;
1314
+ const args = transport2.asWritten?.args ?? transport2.args;
1315
+ return {
1316
+ type: "stdio",
1317
+ command,
1318
+ args: args.length > 0 ? args : void 0,
1319
+ envKeys: Object.keys(transport2.env).length > 0 ? Object.keys(transport2.env).sort() : void 0,
1320
+ cwd: transport2.cwd
1321
+ };
1243
1322
  }
1244
- return [...moved].filter((server2) => !versioned.has(server2)).sort();
1323
+ const headerKeys = Object.keys(transport2.headers);
1324
+ return {
1325
+ type: transport2.type,
1326
+ url: sanitizeUrl(transport2.asWritten?.url ?? transport2.url),
1327
+ headerKeys: headerKeys.length > 0 ? headerKeys.sort() : void 0
1328
+ };
1245
1329
  }
1246
-
1247
- // ../core/src/diff/index.ts
1248
- function change(kind, server2, summary, extra) {
1249
- return { kind, severity: SEVERITY[kind], server: server2, summary, ...extra };
1330
+ function lockTool(tool2, ignoredMeta) {
1331
+ const annotations2 = tool2.annotations;
1332
+ const inputSchema = normalizeSchema(toJson(tool2.inputSchema));
1333
+ const headerParams = extractHeaderParams(inputSchema);
1334
+ return sealed({
1335
+ name: tool2.name,
1336
+ title: tool2.title,
1337
+ description: tool2.description,
1338
+ inputSchema,
1339
+ outputSchema: tool2.outputSchema ? normalizeSchema(toJson(tool2.outputSchema)) : void 0,
1340
+ annotations: annotations2 ? { ...annotations2 } : void 0,
1341
+ behavior: resolveBehavior(annotations2),
1342
+ headerParams: headerParams.length > 0 ? headerParams : void 0,
1343
+ icons: lockIcons(tool2.icons),
1344
+ meta: stripIgnoredMeta(toJson(tool2._meta), ignoredMeta)
1345
+ });
1250
1346
  }
1251
- function same(a, b) {
1252
- return stableKey(a ?? null) === stableKey(b ?? null);
1347
+ function lockResource(resource2, ignoredMeta) {
1348
+ return sealed({
1349
+ uri: resource2.uri,
1350
+ name: resource2.name,
1351
+ title: resource2.title,
1352
+ description: resource2.description,
1353
+ mimeType: resource2.mimeType,
1354
+ annotations: resource2.annotations ? toJson(resource2.annotations) : void 0,
1355
+ icons: lockIcons(resource2.icons),
1356
+ meta: stripIgnoredMeta(toJson(resource2._meta), ignoredMeta)
1357
+ });
1253
1358
  }
1254
- function indexBy(members, key) {
1255
- return new Map((members ?? []).map((member) => [key(member), member]));
1359
+ function lockResourceTemplate(template, ignoredMeta) {
1360
+ return sealed({
1361
+ uriTemplate: template.uriTemplate,
1362
+ name: template.name,
1363
+ title: template.title,
1364
+ description: template.description,
1365
+ mimeType: template.mimeType,
1366
+ annotations: template.annotations ? toJson(template.annotations) : void 0,
1367
+ icons: lockIcons(template.icons),
1368
+ meta: stripIgnoredMeta(toJson(template._meta), ignoredMeta)
1369
+ });
1256
1370
  }
1257
- function declaredNames(capabilities) {
1258
- const names = [];
1259
- for (const [key, value] of Object.entries(capabilities ?? {})) {
1260
- if (key === "extensions" && value !== null && typeof value === "object" && !Array.isArray(value)) {
1261
- for (const id of Object.keys(value)) names.push(`extensions/${id}`);
1262
- continue;
1371
+ function lockPrompt(prompt2, ignoredMeta) {
1372
+ return sealed({
1373
+ name: prompt2.name,
1374
+ title: prompt2.title,
1375
+ description: prompt2.description,
1376
+ arguments: prompt2.arguments && prompt2.arguments.length > 0 ? prompt2.arguments.map((argument) => ({
1377
+ name: argument.name,
1378
+ // The spec gives PromptArgument a `title` (it extends BaseMetadata); the SDK's type
1379
+ // has not caught up, so it is read off the wire rather than skipped.
1380
+ title: argument.title,
1381
+ description: argument.description,
1382
+ required: argument.required
1383
+ })) : void 0,
1384
+ icons: lockIcons(prompt2.icons),
1385
+ meta: stripIgnoredMeta(toJson(prompt2._meta), ignoredMeta)
1386
+ });
1387
+ }
1388
+ function buildLockedServer(server2, surface, policy) {
1389
+ const ignoredMeta = policy?.ignoreMetaPrefixes ?? [];
1390
+ const tools = byName(surface.tools).map((tool2) => lockTool(tool2, ignoredMeta));
1391
+ const resources = byName(surface.resources).map((resource2) => lockResource(resource2, ignoredMeta));
1392
+ const resourceTemplates = byName(surface.resourceTemplates).map((template) => lockResourceTemplate(template, ignoredMeta));
1393
+ const prompts = byName(surface.prompts).map((prompt2) => lockPrompt(prompt2, ignoredMeta));
1394
+ const entry = {
1395
+ source: server2.source,
1396
+ transport: lockTransport(server2),
1397
+ protocol: surface.protocol,
1398
+ serverInfo: surface.serverInfo,
1399
+ capabilities: surface.capabilities,
1400
+ instructions: surface.instructions,
1401
+ tools: tools.length > 0 ? tools : void 0,
1402
+ resources: resources.length > 0 ? resources : void 0,
1403
+ resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
1404
+ prompts: prompts.length > 0 ? prompts : void 0
1405
+ };
1406
+ const covered = {
1407
+ transport: entry.transport,
1408
+ protocol: entry.protocol,
1409
+ serverInfo: entry.serverInfo,
1410
+ capabilities: entry.capabilities,
1411
+ instructions: entry.instructions,
1412
+ tools: tools.map((tool2) => tool2.digest),
1413
+ resources: resources.map((resource2) => resource2.digest),
1414
+ resourceTemplates: resourceTemplates.map((template) => template.digest),
1415
+ prompts: prompts.map((prompt2) => prompt2.digest)
1416
+ };
1417
+ return { kind: "mcp-server", ...entry, digest: digest(toJson(covered)) };
1418
+ }
1419
+
1420
+ // src/mcp/connect.ts
1421
+ import { Client, SSEClientTransport, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
1422
+ import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/client/stdio";
1423
+
1424
+ // src/mcp/oauth.ts
1425
+ import { spawn } from "child_process";
1426
+ import { createHash as createHash2, randomUUID } from "crypto";
1427
+ import { readFileSync } from "fs";
1428
+ import { mkdir, readFile as readFile3, rm, writeFile } from "fs/promises";
1429
+ import { homedir as homedir3, platform as platform2 } from "os";
1430
+ import { dirname, join as join2 } from "path";
1431
+ import { ClientCredentialsProvider, UnauthorizedError } from "@modelcontextprotocol/client";
1432
+
1433
+ // src/lib/version.ts
1434
+ var VERSION = "0.3.0";
1435
+ var USER_AGENT = `nulladrift/${VERSION}`;
1436
+
1437
+ // src/mcp/oauth.ts
1438
+ var DEFAULT_CALLBACK_PATH = "/callback";
1439
+ function authDir() {
1440
+ const base = process.env["XDG_CONFIG_HOME"] ?? join2(homedir3(), ".config");
1441
+ return join2(base, "nulladrift", "auth");
1442
+ }
1443
+ function credentialPath(url) {
1444
+ return join2(authDir(), `${createHash2("sha256").update(url).digest("hex").slice(0, 16)}.json`);
1445
+ }
1446
+ var InteractiveAuthRequiredError = class extends Error {
1447
+ constructor(serverName) {
1448
+ super(`authorization required. Run \`nulladrift login ${serverName}\` once, then re-run.`);
1449
+ this.serverName = serverName;
1450
+ this.name = "InteractiveAuthRequiredError";
1451
+ }
1452
+ serverName;
1453
+ };
1454
+ var FileTokenProvider = class {
1455
+ constructor(serverName, serverUrl, options = { interactive: false }) {
1456
+ this.serverName = serverName;
1457
+ this.serverUrl = serverUrl;
1458
+ this.options = options;
1459
+ }
1460
+ serverName;
1461
+ serverUrl;
1462
+ options;
1463
+ cache;
1464
+ /** One per login attempt, held in memory and checked against what comes back on the callback. */
1465
+ stateValue = createHash2("sha256").update(randomUUID()).digest("hex").slice(0, 32);
1466
+ get redirectUrl() {
1467
+ return this.options.redirectUrl;
1468
+ }
1469
+ state() {
1470
+ return this.stateValue;
1471
+ }
1472
+ get clientMetadata() {
1473
+ return {
1474
+ client_name: `nulladrift ${VERSION}`,
1475
+ // A command-line tool is a native client: it cannot keep a secret in a shipped binary.
1476
+ application_type: "native",
1477
+ redirect_uris: this.options.redirectUrl === void 0 ? [] : [this.options.redirectUrl],
1478
+ grant_types: ["authorization_code", "refresh_token"],
1479
+ response_types: ["code"],
1480
+ token_endpoint_auth_method: "none",
1481
+ ...this.options.scope === void 0 ? {} : { scope: this.options.scope }
1482
+ };
1483
+ }
1484
+ async read() {
1485
+ if (this.cache) return this.cache;
1486
+ try {
1487
+ this.cache = JSON.parse(await readFile3(credentialPath(this.serverUrl), "utf8"));
1488
+ } catch {
1489
+ this.cache = { serverUrl: this.serverUrl };
1263
1490
  }
1264
- names.push(key);
1491
+ return this.cache;
1265
1492
  }
1266
- return names;
1267
- }
1268
- function compareCapabilities(before, after, name) {
1269
- if (same(before.capabilities, after.capabilities)) return [];
1270
- const previous = declaredNames(before.capabilities);
1271
- const next = declaredNames(after.capabilities);
1272
- const gained = next.filter((key) => !previous.includes(key));
1273
- const lost = previous.filter((key) => !next.includes(key));
1274
- if (gained.length > 0 && lost.length === 0) {
1275
- return [change("server.capabilities.widened", name, `server now declares ${gained.join(", ")}`, { before: before.capabilities, after: after.capabilities })];
1493
+ async write(patch) {
1494
+ const next = { ...await this.read(), ...patch, serverUrl: this.serverUrl };
1495
+ this.cache = next;
1496
+ const path = credentialPath(this.serverUrl);
1497
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
1498
+ await writeFile(path, `${JSON.stringify(next, null, 2)}
1499
+ `, { encoding: "utf8", mode: 384 });
1276
1500
  }
1277
- if (lost.length > 0 && gained.length === 0) {
1278
- return [change("server.capabilities.narrowed", name, `server no longer declares ${lost.join(", ")}`, { before: before.capabilities, after: after.capabilities })];
1501
+ async clientInformation() {
1502
+ return (await this.read()).clientInformation;
1279
1503
  }
1280
- return [change("server.capabilities.changed", name, "declared capabilities changed", { before: before.capabilities, after: after.capabilities })];
1281
- }
1282
- function compareTool(name, before, after) {
1283
- if (before.digest === after.digest) return [];
1284
- const changes = [];
1285
- const at = { member: before.name };
1286
- if (!same(before.description, after.description)) {
1287
- changes.push(
1288
- change("tool.description.changed", name, `description changed (${before.description?.length ?? 0} \u2192 ${after.description?.length ?? 0} characters)`, {
1289
- ...at,
1290
- before: before.description,
1291
- after: after.description
1292
- })
1293
- );
1504
+ async saveClientInformation(clientInformation) {
1505
+ await this.write({ clientInformation });
1506
+ }
1507
+ async tokens() {
1508
+ return (await this.read()).tokens;
1509
+ }
1510
+ async saveTokens(tokens) {
1511
+ await this.write({ tokens });
1512
+ }
1513
+ async saveCodeVerifier(codeVerifier) {
1514
+ await this.write({ codeVerifier });
1515
+ }
1516
+ async codeVerifier() {
1517
+ const stored = (await this.read()).codeVerifier;
1518
+ if (stored === void 0) throw new Error("no PKCE verifier stored; start the login again");
1519
+ return stored;
1294
1520
  }
1295
- const inputVerdict = classifySchemaChange(before.inputSchema, after.inputSchema);
1296
- if (inputVerdict !== "same") {
1297
- const kind = `tool.input_schema.${inputVerdict}`;
1298
- const wording = inputVerdict === "widened" ? "accepts input it did not before" : inputVerdict === "narrowed" ? "accepts less input than before" : "input schema changed";
1299
- changes.push(change(kind, name, wording, { ...at, before: before.inputSchema, after: after.inputSchema }));
1521
+ async saveAuthorizationServerUrl(authorizationServerUrl) {
1522
+ await this.write({ authorizationServerUrl });
1300
1523
  }
1301
- if (!same(before.outputSchema, after.outputSchema)) {
1302
- changes.push(change("tool.output_schema.changed", name, "output schema changed", { ...at, before: before.outputSchema, after: after.outputSchema }));
1524
+ async authorizationServerUrl() {
1525
+ return (await this.read()).authorizationServerUrl;
1303
1526
  }
1304
- if (!same(before.behavior, after.behavior)) {
1305
- const escalated = isEscalation(before.behavior, after.behavior);
1306
- changes.push(
1307
- change(escalated ? "tool.behavior.escalated" : "tool.behavior.relaxed", name, escalated ? describeEscalation(before, after) : "declares fewer powers than before", {
1308
- ...at,
1309
- before: before.behavior,
1310
- after: after.behavior
1311
- })
1312
- );
1527
+ async saveResourceUrl(resourceUrl) {
1528
+ await this.write({ resourceUrl });
1313
1529
  }
1314
- if (!same(before.headerParams, after.headerParams)) {
1315
- changes.push(
1316
- change("tool.header_params.changed", name, "arguments mirrored into HTTP headers changed", { ...at, before: before.headerParams ?? [], after: after.headerParams ?? [] })
1317
- );
1530
+ async resourceUrl() {
1531
+ return (await this.read()).resourceUrl;
1318
1532
  }
1319
- if (changes.length === 0) {
1320
- changes.push(change("tool.changed", name, "tool definition changed (title, icons or _meta)", { ...at, before, after }));
1533
+ async saveDiscoveryState(discoveryState) {
1534
+ await this.write({ discoveryState });
1321
1535
  }
1322
- return changes;
1323
- }
1324
- function describeEscalation(before, after) {
1325
- const gained = [];
1326
- if (before.behavior.readOnly && !after.behavior.readOnly) gained.push("may now modify");
1327
- if (!before.behavior.destructive && after.behavior.destructive) gained.push("may now destroy");
1328
- if (before.behavior.idempotent && !after.behavior.idempotent) gained.push("repeat calls now compound");
1329
- if (!before.behavior.openWorld && after.behavior.openWorld) gained.push("may now reach external systems");
1330
- return gained.join("; ");
1331
- }
1332
- function compareMembers(name, before, after, spec, deep) {
1333
- const changes = [];
1334
- const previous = indexBy(before, spec.key);
1335
- const next = indexBy(after, spec.key);
1336
- for (const [key, member] of next) {
1337
- const existing = previous.get(key);
1338
- if (!existing) {
1339
- changes.push(change(spec.added, name, `new ${spec.noun} ${spec.label(member)}`, { member: spec.label(member), after: member }));
1340
- continue;
1536
+ async discoveryState() {
1537
+ return (await this.read()).discoveryState;
1538
+ }
1539
+ async invalidateCredentials(scope) {
1540
+ if (scope === "all") {
1541
+ this.cache = { serverUrl: this.serverUrl };
1542
+ await rm(credentialPath(this.serverUrl), { force: true });
1543
+ return;
1341
1544
  }
1342
- if (existing.digest === member.digest) continue;
1343
- 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 })]);
1545
+ const key = { client: "clientInformation", tokens: "tokens", verifier: "codeVerifier", discovery: "discoveryState" }[scope];
1546
+ await this.write({ [key]: void 0 });
1344
1547
  }
1345
- for (const [key, member] of previous) {
1346
- if (!next.has(key)) changes.push(change(spec.removed, name, `${spec.noun} ${spec.label(member)} is gone`, { member: spec.label(member), before: member }));
1548
+ async redirectToAuthorization(authorizationUrl) {
1549
+ if (!this.options.interactive) throw new InteractiveAuthRequiredError(this.serverName);
1550
+ openInBrowser(authorizationUrl);
1551
+ process.stderr.write(`
1552
+ If a browser did not open, visit:
1553
+ ${authorizationUrl.toString()}
1554
+
1555
+ `);
1347
1556
  }
1348
- return changes;
1349
- }
1350
- function compareServer(name, before, after) {
1351
- if (before.digest === after.digest) return [];
1352
- const changes = [];
1353
- if (!same(before.transport, after.transport)) {
1354
- changes.push(change("server.transport.changed", name, "the server is reached differently than when it was pinned", { before: before.transport, after: after.transport }));
1557
+ };
1558
+ function openInBrowser(url) {
1559
+ const command = platform2() === "darwin" ? "open" : platform2() === "win32" ? "cmd" : "xdg-open";
1560
+ const args = platform2() === "win32" ? ["/c", "start", "", url.toString()] : [url.toString()];
1561
+ try {
1562
+ spawn(command, args, { detached: true, stdio: "ignore" }).unref();
1563
+ } catch {
1355
1564
  }
1356
- if (!same(before.serverInfo, after.serverInfo)) {
1357
- const from = before.serverInfo?.version ?? "unknown";
1358
- const to = after.serverInfo?.version ?? "unknown";
1359
- changes.push(change("server.identity.changed", name, `server identity changed (version ${from} \u2192 ${to})`, { before: before.serverInfo, after: after.serverInfo }));
1565
+ }
1566
+ function hasStoredCredentials(url) {
1567
+ try {
1568
+ const stored = JSON.parse(readFileSync(credentialPath(url), "utf8"));
1569
+ return typeof stored.tokens?.access_token === "string" && stored.tokens.access_token.length > 0;
1570
+ } catch {
1571
+ return false;
1360
1572
  }
1361
- if (!same(before.protocol, after.protocol)) {
1362
- changes.push(
1363
- change("server.protocol.changed", name, `protocol changed (${before.protocol.era}/${before.protocol.version} \u2192 ${after.protocol.era}/${after.protocol.version})`, {
1364
- before: before.protocol,
1365
- after: after.protocol
1366
- })
1367
- );
1573
+ }
1574
+ function createAuthProvider(server2, options = {}) {
1575
+ if (server2.transport.type === "stdio") return void 0;
1576
+ const oauth = server2.transport.oauth;
1577
+ if (oauth?.clientId !== void 0 && oauth.clientSecret !== void 0) {
1578
+ return new ClientCredentialsProvider({
1579
+ clientId: oauth.clientId,
1580
+ clientSecret: oauth.clientSecret,
1581
+ clientName: `nulladrift ${VERSION}`,
1582
+ ...oauth.scope === void 0 ? {} : { scope: oauth.scope }
1583
+ });
1368
1584
  }
1369
- if (!same(before.instructions, after.instructions)) {
1370
- changes.push(
1371
- change("server.instructions.changed", name, "server instructions changed: this text goes into the model's system prompt", {
1372
- before: before.instructions,
1373
- after: after.instructions
1374
- })
1375
- );
1585
+ const interactive = options.interactive ?? false;
1586
+ if (!interactive && !hasStoredCredentials(server2.transport.url)) return void 0;
1587
+ return new FileTokenProvider(server2.name, server2.transport.url, {
1588
+ interactive,
1589
+ ...oauth?.scope === void 0 ? {} : { scope: oauth.scope }
1590
+ });
1591
+ }
1592
+
1593
+ // src/mcp/types.ts
1594
+ import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/client";
1595
+ var UnreachableServerError = class extends Error {
1596
+ constructor(serverName, message, cause) {
1597
+ super(message);
1598
+ this.serverName = serverName;
1599
+ this.cause = cause;
1600
+ this.name = "UnreachableServerError";
1376
1601
  }
1377
- changes.push(...compareCapabilities(before, after, name));
1378
- changes.push(
1379
- ...compareMembers(
1380
- name,
1381
- before.tools,
1382
- after.tools,
1383
- { key: (t) => t.name, label: (t) => t.name, added: "tool.added", removed: "tool.removed", changed: "tool.changed", noun: "tool" },
1384
- (_key, a, b) => compareTool(name, a, b)
1385
- )
1386
- );
1387
- changes.push(
1388
- ...compareMembers(name, before.resources, after.resources, {
1389
- key: (r) => r.uri,
1390
- label: (r) => `${r.name} (${r.uri})`,
1391
- added: "resource.added",
1392
- removed: "resource.removed",
1393
- changed: "resource.changed",
1394
- noun: "resource"
1395
- })
1396
- );
1397
- changes.push(
1398
- ...compareMembers(name, before.resourceTemplates, after.resourceTemplates, {
1399
- key: (t) => t.uriTemplate,
1400
- // The template itself is the capability -- widening it from file:///project/{path} to
1401
- // file:///{path} is the whole finding -- so it belongs in the label, not just the body.
1402
- label: (t) => `${t.name} (${t.uriTemplate})`,
1403
- added: "resource_template.added",
1404
- removed: "resource_template.removed",
1405
- changed: "resource_template.changed",
1406
- noun: "resource template"
1407
- })
1602
+ serverName;
1603
+ cause;
1604
+ };
1605
+ function authFailureKind(error) {
1606
+ if (!isAuthFailure(error)) return void 0;
1607
+ const text = `${error instanceof Error ? error.message : String(error)}`.toLowerCase();
1608
+ const cause = error instanceof UnreachableServerError && error.cause instanceof Error ? error.cause.message.toLowerCase() : "";
1609
+ const both = `${text} ${cause}`;
1610
+ const scoped = [error, error instanceof UnreachableServerError ? error.cause : void 0].some(
1611
+ (candidate) => candidate instanceof Error && candidate.name === "InsufficientScopeError"
1408
1612
  );
1409
- changes.push(
1410
- ...compareMembers(name, before.prompts, after.prompts, {
1411
- key: (p) => p.name,
1412
- label: (p) => p.name,
1413
- added: "prompt.added",
1414
- removed: "prompt.removed",
1415
- changed: "prompt.changed",
1416
- noun: "prompt"
1417
- })
1613
+ if (scoped || /\b403\b|forbidden|insufficient[_ ]scope/.test(both)) return "forbidden";
1614
+ return "auth";
1615
+ }
1616
+ function isAuthFailure(error) {
1617
+ if (error instanceof UnauthorizedError2) return true;
1618
+ if (error instanceof Error && error.name === "InteractiveAuthRequiredError") return true;
1619
+ if (error instanceof UnreachableServerError && error.cause instanceof Error && error.cause.name === "InteractiveAuthRequiredError") return true;
1620
+ const cause = error instanceof UnreachableServerError ? error.cause : void 0;
1621
+ if (cause instanceof UnauthorizedError2) return true;
1622
+ for (const candidate of [error, error instanceof UnreachableServerError ? error.cause : void 0]) {
1623
+ const name = candidate instanceof Error ? candidate.name : "";
1624
+ if (name === "RegistrationRejectedError" || name === "InsufficientScopeError" || name === "OAuthClientFlowError") return true;
1625
+ }
1626
+ const outer = `${error instanceof Error ? error.message : String(error)}`;
1627
+ const inner = error instanceof UnreachableServerError && error.cause instanceof Error ? error.cause.message : "";
1628
+ const text = `${outer} ${inner}`.toLowerCase();
1629
+ return /\b(401|403)\b|unauthorized|forbidden|invalid or missing.*token|authentication required|invalid_client|dynamic client registration/.test(text);
1630
+ }
1631
+
1632
+ // src/mcp/connect.ts
1633
+ var DEFAULT_TIMEOUT_MS = 3e4;
1634
+ var STDERR_KEEP_BYTES = 2e3;
1635
+ function buildTransport(server2, captureStderr = () => {
1636
+ }, options = {}) {
1637
+ const { transport: transport2 } = server2;
1638
+ if (transport2.type === "stdio") {
1639
+ const child = new StdioClientTransport({
1640
+ command: transport2.command,
1641
+ args: transport2.args,
1642
+ // The server's own environment plus whatever the config sets. Never the auditor's full env.
1643
+ env: { ...getDefaultEnvironment(), ...transport2.env },
1644
+ cwd: transport2.cwd,
1645
+ // Piped rather than inherited: a chatty server must not interleave with our report, but its
1646
+ // last words are the most useful thing we can show when it fails to answer.
1647
+ stderr: "pipe"
1648
+ });
1649
+ child.stderr?.on("data", (chunk) => captureStderr(chunk.toString("utf8")));
1650
+ return child;
1651
+ }
1652
+ const headers = { ...transport2.headers, "user-agent": `nulladrift/${VERSION}` };
1653
+ const url = new URL(transport2.url);
1654
+ const authProvider = createAuthProvider(server2, options);
1655
+ if (transport2.type === "sse") return new SSEClientTransport(url, { requestInit: { headers }, authProvider });
1656
+ return new StreamableHTTPClientTransport(url, { requestInit: { headers }, authProvider });
1657
+ }
1658
+ function diagnosticLines(stderr, limit = 3) {
1659
+ const lines = stderr.split("\n").map((line) => line.trimEnd()).filter((line) => line.trim().length > 0).filter((line) => !/^\s*(at\s|\^+$|[}\])]+$|Node\.js v[\d.]+$)/.test(line));
1660
+ const named = lines.filter((line) => /\b(error|exception|cannot|failed|refused|denied|not found|enoent|eacces)\b/i.test(line));
1661
+ const chosen = named.length > 0 ? named : lines;
1662
+ return chosen.slice(0, limit).map((line) => line.trim());
1663
+ }
1664
+ async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS, options = {}) {
1665
+ let stderrBuffer = "";
1666
+ const captureStderr = (chunk) => {
1667
+ stderrBuffer = (stderrBuffer + chunk).slice(-STDERR_KEEP_BYTES);
1668
+ };
1669
+ const client = new Client(
1670
+ { name: "nulladrift", title: "nulladrift", version: VERSION },
1671
+ {
1672
+ /*
1673
+ * We advertise nothing. An auditor never calls a tool, so it has no business offering
1674
+ * elicitation, sampling or roots -- a server that asks for them gets nothing to work with.
1675
+ */
1676
+ capabilities: {},
1677
+ versionNegotiation: { mode: "auto", probe: { timeoutMs } }
1678
+ }
1418
1679
  );
1419
- return changes;
1420
- }
1421
- function detectRenames(before, after, removed, added) {
1422
- const changes = [];
1423
- const renamed = /* @__PURE__ */ new Set();
1424
- const availableAdds = [...added];
1425
- for (const oldName of removed) {
1426
- const oldEntry = before.subjects[oldName];
1427
- if (!oldEntry) continue;
1428
- const match = availableAdds.find((newName) => {
1429
- const candidate = after.subjects[newName];
1430
- return candidate !== void 0 && candidate.digest === oldEntry.digest && same(candidate.transport, oldEntry.transport);
1680
+ let transport2;
1681
+ try {
1682
+ transport2 = buildTransport(server2, captureStderr, options);
1683
+ } catch (error) {
1684
+ throw new UnreachableServerError(server2.name, `could not prepare transport: ${error.message}`, error);
1685
+ }
1686
+ try {
1687
+ await client.connect(transport2, { timeout: timeoutMs });
1688
+ } catch (error) {
1689
+ await client.close().catch(() => {
1431
1690
  });
1432
- if (!match) continue;
1433
- availableAdds.splice(availableAdds.indexOf(match), 1);
1434
- renamed.add(oldName);
1435
- renamed.add(match);
1436
- changes.push(change("server.renamed", match, `renamed from "${oldName}"; capabilities are unchanged`, { before: oldName, after: match }));
1691
+ const detail = stderrBuffer.trim();
1692
+ throw new UnreachableServerError(
1693
+ server2.name,
1694
+ `${error.message}${detail ? `
1695
+ server stderr: ${diagnosticLines(detail).join("\n ")}` : ""}`,
1696
+ error
1697
+ );
1437
1698
  }
1438
- return { changes, renamed };
1699
+ return {
1700
+ client,
1701
+ stderr: () => stderrBuffer,
1702
+ close: async () => {
1703
+ await client.close().catch(() => {
1704
+ });
1705
+ }
1706
+ };
1439
1707
  }
1440
- function diffLockfiles(before, after) {
1441
- const beforeNames = Object.keys(before.subjects);
1442
- const afterNames = Object.keys(after.subjects);
1443
- const removed = beforeNames.filter((name) => !afterNames.includes(name));
1444
- const added = afterNames.filter((name) => !beforeNames.includes(name));
1445
- const { changes: renameChanges, renamed } = detectRenames(before, after, removed, added);
1446
- const changes = [...renameChanges];
1447
- for (const name of added) {
1448
- if (renamed.has(name)) continue;
1449
- const entry = after.subjects[name];
1450
- const toolCount = entry?.tools?.length ?? 0;
1451
- changes.push(change("server.added", name, `new server with ${toolCount} tool${toolCount === 1 ? "" : "s"}`, { after: entry }));
1708
+
1709
+ // src/mcp/capture.ts
1710
+ var FRESH = { cacheMode: "bypass" };
1711
+ function describeListFailure(error) {
1712
+ const message = error?.message ?? String(error);
1713
+ if (error instanceof RangeError || /maximum call stack|stack size exceeded|too much recursion/i.test(message)) {
1714
+ return "the declared surface is nested too deeply to parse. Nothing was pinned. A legitimate schema is a few levels deep; this one is deep enough to exhaust the parser, which is a property of the declaration and not of your project.";
1452
1715
  }
1453
- for (const name of removed) {
1454
- if (renamed.has(name)) continue;
1455
- changes.push(change("server.removed", name, "server is no longer configured", { before: before.subjects[name] }));
1716
+ return message;
1717
+ }
1718
+ async function listOrEmpty(label, serverName, fetchList) {
1719
+ try {
1720
+ return await fetchList();
1721
+ } catch (error) {
1722
+ throw new UnreachableServerError(serverName, `${label} failed: ${describeListFailure(error)}`, error);
1456
1723
  }
1457
- for (const name of afterNames) {
1458
- const a = before.subjects[name];
1459
- const b = after.subjects[name];
1460
- if (!a || !b) continue;
1461
- changes.push(...compareServer(name, a, b));
1724
+ }
1725
+ function readProtocol(client) {
1726
+ const era = client.getProtocolEra() ?? "legacy";
1727
+ const version = client.getNegotiatedProtocolVersion() ?? "unknown";
1728
+ const discovered = client.getDiscoverResult();
1729
+ return {
1730
+ era,
1731
+ version,
1732
+ supportedVersions: discovered?.supportedVersions
1733
+ };
1734
+ }
1735
+ function readServerInfo(client) {
1736
+ const info = client.getServerVersion();
1737
+ if (!info) return void 0;
1738
+ return {
1739
+ name: info.name,
1740
+ title: info.title,
1741
+ version: info.version,
1742
+ description: info.description,
1743
+ websiteUrl: info.websiteUrl
1744
+ };
1745
+ }
1746
+ async function captureSurface(server2, timeoutMs = DEFAULT_TIMEOUT_MS) {
1747
+ const connection = await connect(server2, timeoutMs);
1748
+ const { client } = connection;
1749
+ try {
1750
+ const capabilities = client.getServerCapabilities();
1751
+ const [tools, resources, resourceTemplates, prompts] = await Promise.all([
1752
+ capabilities?.tools ? listOrEmpty("tools/list", server2.name, async () => (await client.listTools(void 0, FRESH)).tools) : [],
1753
+ capabilities?.resources ? listOrEmpty("resources/list", server2.name, async () => (await client.listResources(void 0, FRESH)).resources) : [],
1754
+ capabilities?.resources ? listOrEmpty("resources/templates/list", server2.name, async () => (await client.listResourceTemplates(void 0, FRESH)).resourceTemplates) : [],
1755
+ capabilities?.prompts ? listOrEmpty("prompts/list", server2.name, async () => (await client.listPrompts(void 0, FRESH)).prompts) : []
1756
+ ]);
1757
+ return {
1758
+ protocol: readProtocol(client),
1759
+ serverInfo: readServerInfo(client),
1760
+ capabilities: capabilities ? toJson(capabilities) : void 0,
1761
+ // Clients place this in the model's system prompt, so it is part of the capability surface.
1762
+ instructions: client.getInstructions(),
1763
+ tools,
1764
+ resources,
1765
+ resourceTemplates,
1766
+ prompts
1767
+ };
1768
+ } finally {
1769
+ await connection.close();
1462
1770
  }
1463
- return sortChanges(changes);
1464
1771
  }
1465
1772
 
1466
- // ../core/src/lock/reseal.ts
1467
- function sealMember(member) {
1468
- const { digest: _discarded, ...body } = member;
1469
- return { ...body, digest: digest(toJson(body)) };
1773
+ // src/audit.ts
1774
+ async function mapWithLimit(items, limit, worker) {
1775
+ const results = new Array(items.length);
1776
+ let next = 0;
1777
+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
1778
+ for (; ; ) {
1779
+ const index = next++;
1780
+ const item = items[index];
1781
+ if (index >= items.length || item === void 0) return;
1782
+ results[index] = await worker(item);
1783
+ }
1784
+ });
1785
+ await Promise.all(runners);
1786
+ return results;
1470
1787
  }
1471
- function reseal(entry) {
1472
- switch (entry.kind) {
1473
- case "mcp-server":
1474
- return resealMcpServer(entry);
1788
+ async function withDeadline(ms, name, run) {
1789
+ let timer;
1790
+ try {
1791
+ return await Promise.race([
1792
+ run(),
1793
+ new Promise((_resolve, reject) => {
1794
+ timer = setTimeout(() => reject(new UnreachableServerError(name, `did not finish within ${ms}ms`)), ms);
1795
+ timer.unref?.();
1796
+ })
1797
+ ]);
1798
+ } finally {
1799
+ if (timer) clearTimeout(timer);
1475
1800
  }
1476
1801
  }
1477
- function resealMcpServer(entry) {
1478
- const tools = (entry.tools ?? []).map((tool2) => sealMember(tool2));
1479
- const resources = (entry.resources ?? []).map((resource2) => sealMember(resource2));
1480
- const resourceTemplates = (entry.resourceTemplates ?? []).map((template) => sealMember(template));
1481
- const prompts = (entry.prompts ?? []).map((prompt2) => sealMember(prompt2));
1482
- const covered = {
1483
- transport: entry.transport,
1484
- protocol: entry.protocol,
1485
- serverInfo: entry.serverInfo,
1486
- capabilities: entry.capabilities,
1487
- instructions: entry.instructions,
1488
- tools: tools.map((tool2) => tool2.digest),
1489
- resources: resources.map((resource2) => resource2.digest),
1490
- resourceTemplates: resourceTemplates.map((template) => template.digest),
1491
- prompts: prompts.map((prompt2) => prompt2.digest)
1492
- };
1802
+ async function captureAll(options) {
1803
+ const discovery = await discoverServers(options.projectRoot, options.configFiles);
1804
+ const captured = await mapWithLimit(discovery.servers, options.concurrency ?? 4, async (server2) => {
1805
+ try {
1806
+ const surface = await withDeadline(
1807
+ options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1808
+ server2.name,
1809
+ () => captureSurface(server2, options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
1810
+ );
1811
+ options.onServerDone?.(server2.name, "captured");
1812
+ return { name: server2.name, entry: buildLockedServer(server2, surface, options.policy) };
1813
+ } catch (error) {
1814
+ options.onServerDone?.(server2.name, "failed");
1815
+ const reason = error instanceof UnreachableServerError ? error.message : error.message;
1816
+ const kind = authFailureKind(error) ?? "unreachable";
1817
+ return { name: server2.name, failure: { server: server2.name, reason, kind } };
1818
+ }
1819
+ });
1820
+ const subjects = {};
1821
+ const unreachable = [];
1822
+ for (const result of captured) {
1823
+ if ("entry" in result && result.entry) subjects[result.name] = result.entry;
1824
+ else if ("failure" in result && result.failure) unreachable.push(result.failure);
1825
+ }
1826
+ for (const skipped of discovery.skipped) {
1827
+ unreachable.push({ server: skipped.serverName, reason: skipped.message, kind: "unreachable" });
1828
+ }
1829
+ for (const problem of discovery.problems) {
1830
+ unreachable.push({ server: problem.file, reason: problem.reason, kind: "unreachable" });
1831
+ }
1493
1832
  return {
1494
- ...entry,
1495
- tools: tools.length > 0 ? tools : void 0,
1496
- resources: resources.length > 0 ? resources : void 0,
1497
- resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
1498
- prompts: prompts.length > 0 ? prompts : void 0,
1499
- digest: digest(toJson(covered))
1833
+ lock: {
1834
+ lockfileVersion: LOCKFILE_VERSION,
1835
+ generatedBy: `nulladrift@${VERSION}`,
1836
+ policy: options.policy,
1837
+ subjects
1838
+ },
1839
+ unreachable,
1840
+ discovery
1500
1841
  };
1501
1842
  }
1502
1843
 
1503
1844
  // src/lock/io.ts
1504
- import { readFile as readFile4, writeFile as writeFile2 } from "fs/promises";
1845
+ import { lstat, readFile as readFile4, rename, rm as rm2, writeFile as writeFile2 } from "fs/promises";
1505
1846
 
1506
1847
  // src/lock/schema.ts
1507
1848
  import { z as z2 } from "zod";
@@ -1621,7 +1962,13 @@ var lockfileSchema = z2.object({
1621
1962
  generatedBy: z2.string().optional(),
1622
1963
  policy: z2.object({
1623
1964
  ignoreMetaPrefixes: z2.array(z2.string()).optional(),
1624
- allowUnreachable: z2.boolean().optional()
1965
+ allowUnreachable: z2.boolean().optional(),
1966
+ /*
1967
+ * Validated against the real list rather than accepted as free strings: a policy with
1968
+ * `process_exec` in it would otherwise parse, forbid nothing, and read in the diff of
1969
+ * whoever added it as though the rule were in force.
1970
+ */
1971
+ deniedCapabilities: z2.array(z2.enum(CAPABILITY_KINDS)).optional()
1625
1972
  }).optional(),
1626
1973
  /*
1627
1974
  * One map for everything pinned, each entry saying what it is. `z.discriminatedUnion` on a
@@ -1635,7 +1982,7 @@ var lockfileSchema = z2.object({
1635
1982
  var DEFAULT_LOCK_FILENAME = "mcp.lock";
1636
1983
  var KEY_ORDER = {
1637
1984
  root: ["lockfileVersion", "generatedBy", "policy", "subjects"],
1638
- policy: ["ignoreMetaPrefixes", "allowUnreachable"],
1985
+ policy: ["ignoreMetaPrefixes", "allowUnreachable", "deniedCapabilities"],
1639
1986
  server: ["kind", "source", "transport", "protocol", "serverInfo", "capabilities", "instructions", "tools", "resources", "resourceTemplates", "prompts", "digest"],
1640
1987
  source: ["client", "file", "scope"],
1641
1988
  transport: ["type", "command", "args", "envKeys", "cwd", "url", "headerKeys"],
@@ -1774,7 +2121,23 @@ async function readLockfile(path) {
1774
2121
  }
1775
2122
  async function writeLockfile(path, lock) {
1776
2123
  try {
1777
- await writeFile2(path, serializeLockfile(lock), "utf8");
2124
+ const link = await lstat(path).catch(() => void 0);
2125
+ if (link?.isSymbolicLink()) {
2126
+ throw new LockfileError(`refusing to write ${path}: it is a symbolic link. A lockfile is a real file in the project, and following the link would write somewhere else.`);
2127
+ }
2128
+ } catch (error) {
2129
+ if (error instanceof LockfileError) throw error;
2130
+ }
2131
+ try {
2132
+ const temporary = `${path}.${process.pid}.tmp`;
2133
+ await writeFile2(temporary, serializeLockfile(lock), "utf8");
2134
+ try {
2135
+ await rename(temporary, path);
2136
+ } catch (error) {
2137
+ await rm2(temporary, { force: true }).catch(() => {
2138
+ });
2139
+ throw error;
2140
+ }
1778
2141
  } catch (error) {
1779
2142
  const code = error.code;
1780
2143
  if (code === "ENOENT") throw new LockfileError(`cannot write ${path}: the directory does not exist. Note that --lock is resolved against --cwd.`);
@@ -1813,11 +2176,52 @@ function renderChange(change2) {
1813
2176
  }
1814
2177
  return lines;
1815
2178
  }
2179
+ function renderSteering(report) {
2180
+ const found = report.steering ?? [];
2181
+ if (found.length === 0) return [];
2182
+ const total = found.reduce((sum, server2) => sum + server2.signals.length, 0);
2183
+ const lines = [
2184
+ yellow(`${total} new passage(s) in ${found.length} server(s) read as instructions to the model:`),
2185
+ ""
2186
+ ];
2187
+ for (const { server: server2, signals } of found) {
2188
+ lines.push(` ${bold(server2)}`);
2189
+ const byField = /* @__PURE__ */ new Map();
2190
+ for (const signal of signals) byField.set(signal.field, [...byField.get(signal.field) ?? [], signal.quote]);
2191
+ const fields = [...byField];
2192
+ for (const [field, quotes] of fields.slice(0, 4)) {
2193
+ const more = quotes.length > 1 ? ` (+${quotes.length - 1} more here)` : "";
2194
+ lines.push(` ${dim(`${elideMiddle(field, 52)}: ${truncate(quotes[0] ?? "", 72)}${more}`)}`);
2195
+ }
2196
+ if (fields.length > 4) lines.push(` ${dim(`+${fields.length - 4} more field(s)`)}`);
2197
+ }
2198
+ lines.push("", dim("This did not change the verdict. Read the passages and decide; a server documenting"), dim('"before using this tool, call authenticate first" has the same shape as an attack.'), "");
2199
+ return lines;
2200
+ }
2201
+ function renderViolations(report) {
2202
+ const found = report.violations ?? [];
2203
+ if (found.length === 0) return [];
2204
+ const lines = ["", bold(red(`${found.length} capability(ies) this project does not permit:`)), ""];
2205
+ for (const violation of found) {
2206
+ lines.push(
2207
+ ` ${red("denied")} ${bold(`${violation.server} \u203A ${violation.tool}`)} ${dim(violation.kind)}`,
2208
+ ` ${violation.severity} \xB7 ${violation.evidence}`
2209
+ );
2210
+ }
2211
+ lines.push(
2212
+ "",
2213
+ dim("Set by `policy.deniedCapabilities` in the lockfile. Accepting the change does not clear"),
2214
+ dim("this; remove the capability, or change the policy deliberately."),
2215
+ ""
2216
+ );
2217
+ return lines;
2218
+ }
1816
2219
  function renderHumanReport(report) {
1817
2220
  const lines = [];
2221
+ lines.push(...renderViolations(report));
1818
2222
  if (report.changes.length > 0) {
1819
2223
  const drifted = new Set(report.changes.map((change2) => change2.server)).size;
1820
- const heading = report.serversChecked === 0 ? `Drift in ${drifted} server(s), none of which is still configured:` : `Drift in ${drifted} of ${report.serversChecked} server(s):`;
2224
+ const heading = drifted > report.serversChecked ? `Drift in ${drifted} server(s); ${report.serversChecked} still configured:` : `Drift in ${drifted} of ${report.serversChecked} server(s):`;
1821
2225
  lines.push("", bold(heading), "");
1822
2226
  for (const change2 of report.changes) lines.push(...renderChange(change2), "");
1823
2227
  const quiet = serversThatShippedNothing(report.changes);
@@ -1836,7 +2240,8 @@ function renderHumanReport(report) {
1836
2240
  lines.push(` ${label} ${bold(failure.server)}`, ` ${failure.reason}`, "");
1837
2241
  }
1838
2242
  }
1839
- if (report.changes.length === 0 && report.unreachable.length === 0) {
2243
+ lines.push(...renderSteering(report));
2244
+ if (report.changes.length === 0 && report.unreachable.length === 0 && (report.violations ?? []).length === 0) {
1840
2245
  lines.push(green(`\u2713 ${report.serversChecked} server(s) match ${report.lockPath}`));
1841
2246
  return `${lines.join("\n")}
1842
2247
  `;
@@ -1881,7 +2286,14 @@ function renderJsonReport(report, exitCode) {
1881
2286
  summary: {
1882
2287
  drifted: new Set(report.changes.map((change2) => change2.server)).size,
1883
2288
  changes: report.changes.length,
1884
- unreachable: report.unreachable.length
2289
+ unreachable: report.unreachable.length,
2290
+ /*
2291
+ * Counted separately from `changes` because it is not part of the verdict. A consumer
2292
+ * that gates on this field is gating on a regex, which is the thing this must never be.
2293
+ */
2294
+ steering: (report.steering ?? []).reduce((sum, server2) => sum + server2.signals.length, 0),
2295
+ /** Unlike steering, these DO decide the exit code. */
2296
+ violations: (report.violations ?? []).length
1885
2297
  },
1886
2298
  changes: report.changes.map((change2) => ({
1887
2299
  kind: change2.kind,
@@ -1892,7 +2304,10 @@ function renderJsonReport(report, exitCode) {
1892
2304
  before: change2.before,
1893
2305
  after: change2.after
1894
2306
  })),
1895
- unreachable: report.unreachable
2307
+ unreachable: report.unreachable,
2308
+ /** Text that began addressing the model since the lock was approved. Reported, never gated. */
2309
+ steering: report.steering ?? [],
2310
+ violations: report.violations ?? []
1896
2311
  },
1897
2312
  null,
1898
2313
  2
@@ -1926,7 +2341,10 @@ var LEVEL = {
1926
2341
  medium: "warning",
1927
2342
  low: "note"
1928
2343
  };
2344
+ var DENIED_RULE = "policy.capability.denied";
2345
+ var STEERING_RULE = "steering.passage.arrived";
1929
2346
  var RULE_HELP = {
2347
+ "tool.capability.gained": "A tool gained a capability it did not declare before, derived from its name, its argument names and the shape of its schema. The severity is the capability's, not the schema change's: gaining a `command` argument is not the same finding as gaining an optional string.",
1930
2348
  "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.",
1931
2349
  "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.",
1932
2350
  "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.",
@@ -1944,8 +2362,32 @@ function sarifUri(report) {
1944
2362
  if (rel === "" || rel.startsWith("..") || isAbsolute2(rel)) return report.lockPath;
1945
2363
  return rel.split(sep2).join("/");
1946
2364
  }
1947
- function renderSarifReport(report) {
2365
+ function renderSarifReport(report, options = {}) {
1948
2366
  const used = [...new Set(report.changes.map((change2) => change2.kind))].sort();
2367
+ const violations = report.violations ?? [];
2368
+ const steering = options.steering ? report.steering ?? [] : [];
2369
+ const at = (name, qualified) => [
2370
+ {
2371
+ physicalLocation: { artifactLocation: { uri: sarifUri(report), uriBaseId: "%SRCROOT%" } },
2372
+ logicalLocations: [{ name, fullyQualifiedName: qualified, kind: "member" }]
2373
+ }
2374
+ ];
2375
+ const extraRules = [
2376
+ ...violations.length > 0 ? [{
2377
+ id: DENIED_RULE,
2378
+ name: "PolicyCapabilityDenied",
2379
+ shortDescription: { text: "A capability this project does not permit" },
2380
+ fullDescription: { text: "A pinned tool has a capability listed in policy.deniedCapabilities. Derived from the shape of the declaration, and not cleared by accepting the change." },
2381
+ defaultConfiguration: { level: "error" }
2382
+ }] : [],
2383
+ ...steering.length > 0 ? [{
2384
+ id: STEERING_RULE,
2385
+ name: "SteeringPassageArrived",
2386
+ shortDescription: { text: "Text that began addressing the model" },
2387
+ fullDescription: { text: "A passage a model is shown started reading as an instruction since this lock was approved. A signal to read, not a verdict: legitimate servers trip the same shape. It does not affect the exit code." },
2388
+ defaultConfiguration: { level: "note" }
2389
+ }] : []
2390
+ ];
1949
2391
  const document = {
1950
2392
  $schema: "https://json.schemastore.org/sarif-2.1.0.json",
1951
2393
  version: "2.1.0",
@@ -1956,28 +2398,44 @@ function renderSarifReport(report) {
1956
2398
  name: "nulladrift",
1957
2399
  version: VERSION,
1958
2400
  ...publishedDocsUrl() === void 0 ? {} : { informationUri: publishedDocsUrl() },
1959
- rules: (used.length > 0 ? used : CHANGE_KINDS.slice(0, 0)).map((kind) => ({
1960
- id: kind,
1961
- name: kind.split(/[._]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""),
1962
- shortDescription: { text: `MCP capability drift: ${kind}` },
1963
- fullDescription: { text: RULE_HELP[kind] ?? "The pinned MCP capability surface no longer matches what the server reports." },
1964
- defaultConfiguration: { level: LEVEL[SEVERITY[kind]] },
1965
- ...helpUriFor("6-change-taxonomy") === void 0 ? {} : { helpUri: helpUriFor("6-change-taxonomy") }
1966
- }))
2401
+ rules: [
2402
+ ...(used.length > 0 ? used : CHANGE_KINDS.slice(0, 0)).map((kind) => ({
2403
+ id: kind,
2404
+ name: kind.split(/[._]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(""),
2405
+ shortDescription: { text: `MCP capability drift: ${kind}` },
2406
+ fullDescription: { text: RULE_HELP[kind] ?? "The pinned MCP capability surface no longer matches what the server reports." },
2407
+ defaultConfiguration: { level: LEVEL[SEVERITY[kind]] },
2408
+ ...helpUriFor("6-change-taxonomy") === void 0 ? {} : { helpUri: helpUriFor("6-change-taxonomy") }
2409
+ })),
2410
+ ...extraRules
2411
+ ]
1967
2412
  }
1968
2413
  },
1969
- results: report.changes.map((change2) => ({
1970
- ruleId: change2.kind,
1971
- level: LEVEL[change2.severity],
1972
- message: { text: change2.member ? `${change2.server} \u203A ${change2.member}: ${change2.summary}` : `${change2.server}: ${change2.summary}` },
1973
- locations: [
1974
- {
1975
- physicalLocation: { artifactLocation: { uri: sarifUri(report), uriBaseId: "%SRCROOT%" } },
1976
- logicalLocations: [{ name: change2.member ?? change2.server, fullyQualifiedName: change2.member ? `${change2.server}/${change2.member}` : change2.server, kind: "member" }]
1977
- }
1978
- ],
1979
- partialFingerprints: { "mcpAuditChange/v1": fingerprint(change2) }
1980
- }))
2414
+ results: [
2415
+ ...report.changes.map((change2) => ({
2416
+ ruleId: change2.kind,
2417
+ level: LEVEL[change2.severity],
2418
+ message: { text: change2.member ? `${change2.server} \u203A ${change2.member}: ${change2.summary}` : `${change2.server}: ${change2.summary}` },
2419
+ locations: at(change2.member ?? change2.server, change2.member ? `${change2.server}/${change2.member}` : change2.server),
2420
+ partialFingerprints: { "mcpAuditChange/v1": fingerprint(change2) }
2421
+ })),
2422
+ ...violations.map((violation) => ({
2423
+ ruleId: DENIED_RULE,
2424
+ level: "error",
2425
+ message: { text: `${violation.server} \u203A ${violation.tool}: ${violation.kind} is not permitted here (${violation.evidence})` },
2426
+ locations: at(violation.tool, `${violation.server}/${violation.tool}`),
2427
+ partialFingerprints: { "mcpAuditChange/v1": `${violation.server}/${violation.tool}/${violation.kind}` }
2428
+ })),
2429
+ ...steering.flatMap(
2430
+ ({ server: server2, signals }) => signals.map((signal) => ({
2431
+ ruleId: STEERING_RULE,
2432
+ level: "note",
2433
+ message: { text: `${server2} \u203A ${signal.field}: ${signal.quote}` },
2434
+ locations: at(signal.field, `${server2}/${signal.field}`),
2435
+ partialFingerprints: { "mcpAuditChange/v1": `${server2}/${signal.field}/${signal.kind}` }
2436
+ }))
2437
+ )
2438
+ ]
1981
2439
  }
1982
2440
  ]
1983
2441
  };
@@ -2022,6 +2480,26 @@ function renderMarkdownReport(report, options = {}) {
2022
2480
  );
2023
2481
  }
2024
2482
  }
2483
+ const steering = report.steering ?? [];
2484
+ if (steering.length > 0) {
2485
+ const total = steering.reduce((sum, server2) => sum + server2.signals.length, 0);
2486
+ lines.push(
2487
+ `<details><summary>${total} new passage${total === 1 ? "" : "s"} read as instructions to the model</summary>`,
2488
+ "",
2489
+ "Text a model is shown, which began addressing it since this lock was approved. A server",
2490
+ 'documenting "before using this tool, call authenticate first" has the same shape as an',
2491
+ "attack, so this is something to read rather than a verdict. It did not affect the result.",
2492
+ "",
2493
+ "| Server | Field | Passage |",
2494
+ "| --- | --- | --- |",
2495
+ ...steering.flatMap(
2496
+ ({ server: server2, signals }) => signals.slice(0, 10).map((signal) => `| \`${cell(server2)}\` | \`${cell(signal.field)}\` | ${cell(signal.quote)} |`)
2497
+ ),
2498
+ "",
2499
+ "</details>",
2500
+ ""
2501
+ );
2502
+ }
2025
2503
  if (report.unreachable.length > 0) {
2026
2504
  lines.push(
2027
2505
  `<details><summary>${report.unreachable.length} server${report.unreachable.length === 1 ? "" : "s"} could not be read</summary>`,
@@ -2085,7 +2563,7 @@ ${body}`;
2085
2563
 
2086
2564
  // src/telemetry/index.ts
2087
2565
  import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
2088
- import { mkdir as mkdir2, readFile as readFile5, rm as rm2, writeFile as writeFile3 } from "fs/promises";
2566
+ import { mkdir as mkdir2, readFile as readFile5, rm as rm3, writeFile as writeFile3 } from "fs/promises";
2089
2567
  import { homedir as homedir4 } from "os";
2090
2568
  import { dirname as dirname2, join as join3 } from "path";
2091
2569
  var PAYLOAD_SCHEMA = 2;
@@ -2120,7 +2598,7 @@ async function writePreference(enabled2) {
2120
2598
  await writeConfig({ telemetry: enabled2 });
2121
2599
  }
2122
2600
  async function clearPreference() {
2123
- await rm2(configPath(), { force: true });
2601
+ await rm3(configPath(), { force: true });
2124
2602
  }
2125
2603
  async function resolveInstallId(now = Date.now()) {
2126
2604
  const config = await readConfig();
@@ -2193,6 +2671,17 @@ async function buildReport(options) {
2193
2671
  const allowUnreachable = options.allowUnreachable || committed.policy?.allowUnreachable === true;
2194
2672
  const report = {
2195
2673
  changes,
2674
+ /*
2675
+ * Reported, never gated. The exit code below is computed from drift and unreachable servers
2676
+ * exactly as before: a pattern that fires on "before using this tool, call authenticate
2677
+ * first" must not be able to fail somebody's build.
2678
+ */
2679
+ steering: newSteering(committed, result.lock),
2680
+ /*
2681
+ * Against the freshly read surface, not the diff. A rule saying nothing here may execute
2682
+ * processes has to fail on the day it is added, not on the next day a server happens to move.
2683
+ */
2684
+ violations: capabilityViolations(result.lock, committed.policy?.deniedCapabilities),
2196
2685
  unreachable: result.unreachable,
2197
2686
  serversChecked: Object.keys(result.lock.subjects).length,
2198
2687
  lockPath: options.lockPath,
@@ -2201,7 +2690,12 @@ async function buildReport(options) {
2201
2690
  return {
2202
2691
  report,
2203
2692
  exitCode: resolveExitCode({
2204
- driftCount: changes.length,
2693
+ /*
2694
+ * A forbidden capability fails the build like drift does. It is not drift -- nothing moved
2695
+ * -- but the surface is not one the project permits, and `review --accept-all` must not be
2696
+ * able to make it pass: policy is the thing acceptance cannot overrule.
2697
+ */
2698
+ driftCount: changes.length + (report.violations?.length ?? 0),
2205
2699
  incompleteCount: allowUnreachable ? 0 : result.unreachable.length
2206
2700
  })
2207
2701
  };
@@ -2209,7 +2703,7 @@ async function buildReport(options) {
2209
2703
  async function runCheck(options) {
2210
2704
  const { report, exitCode } = await buildReport(options);
2211
2705
  if (options.format === "json") process.stdout.write(renderJsonReport(report, exitCode));
2212
- else if (options.format === "sarif") process.stdout.write(renderSarifReport(report));
2706
+ else if (options.format === "sarif") process.stdout.write(renderSarifReport(report, { steering: options.sarifSteering }));
2213
2707
  else process.stdout.write(renderHumanReport(report));
2214
2708
  await reportIfChanged(report, report.changes);
2215
2709
  if (options.comment) await comment(report);
@@ -2242,7 +2736,7 @@ async function comment(report) {
2242
2736
  }
2243
2737
 
2244
2738
  // src/commands/init.ts
2245
- import { access } from "fs/promises";
2739
+ import { lstat as lstat2 } from "fs/promises";
2246
2740
 
2247
2741
  // src/commands/telemetry.ts
2248
2742
  import { createInterface } from "readline/promises";
@@ -2337,7 +2831,7 @@ ${dim(" No collector is configured in this build, so nothing will be sent until
2337
2831
  // src/commands/init.ts
2338
2832
  async function exists(path) {
2339
2833
  try {
2340
- await access(path);
2834
+ await lstat2(path);
2341
2835
  return true;
2342
2836
  } catch {
2343
2837
  return false;
@@ -2391,6 +2885,33 @@ async function runInit(options) {
2391
2885
  lines.push(` ${green("\u2713")} ${bold(name)} ${dim(counts)}`);
2392
2886
  const deprecated = entry?.transport.type === "sse" ? " \xB7 HTTP+SSE transport is deprecated in the spec" : "";
2393
2887
  lines.push(` ${dim(`${entry?.protocol.era}/${entry?.protocol.version} \xB7 from ${entry?.source.file}${deprecated}`)}`);
2888
+ const tools = entry?.tools ?? [];
2889
+ const capabilities = surfaceCapabilities(tools);
2890
+ if (capabilities.length > 0) {
2891
+ const worst = capabilities.filter((capability) => capability.severity === "critical" || capability.severity === "high");
2892
+ const paint = worst.length > 0 ? yellow : dim;
2893
+ lines.push(` ${paint(`can: ${capabilities.map((capability) => capability.kind).join(", ")}`)}`);
2894
+ for (const capability of worst) {
2895
+ lines.push(` ${dim(`${capability.kind} \xB7 ${capability.tools.slice(0, 3).join(", ")}${capability.tools.length > 3 ? ` +${capability.tools.length - 3}` : ""}`)}`);
2896
+ }
2897
+ }
2898
+ const steering = (entry ? surfaceText(entry) : []).flatMap(
2899
+ (piece) => steeringSignals(piece.text, piece.field)
2900
+ );
2901
+ if (steering.length > 0) {
2902
+ const byField = /* @__PURE__ */ new Map();
2903
+ for (const signal of steering) byField.set(signal.field, [...byField.get(signal.field) ?? [], signal.quote]);
2904
+ const fields = [...byField];
2905
+ lines.push(
2906
+ ` ${yellow(`${fields.length} field(s) carry text read as instructions to the model, not documentation:`)}`
2907
+ );
2908
+ for (const [field, quotes] of fields.slice(0, 4)) {
2909
+ const more = quotes.length > 1 ? dim(` (+${quotes.length - 1} more here)`) : "";
2910
+ lines.push(` ${dim(`${elideMiddle(field, 52)}: ${truncate(quotes[0] ?? "", 72)}`)}${more}`);
2911
+ }
2912
+ if (fields.length > 4) lines.push(` ${dim(`+${fields.length - 4} more field(s)`)}`);
2913
+ lines.push(` ${dim("A signal to read, not a verdict. It never fails a build.")}`);
2914
+ }
2394
2915
  }
2395
2916
  for (const failure of result.unreachable) {
2396
2917
  lines.push(` ${red("\u2717")} ${bold(failure.server)} ${dim("not pinned")}`, ` ${failure.reason}`);
@@ -2412,7 +2933,7 @@ async function runInit(options) {
2412
2933
  // src/commands/login.ts
2413
2934
  import { createServer } from "http";
2414
2935
  import { auth } from "@modelcontextprotocol/client";
2415
- import { rm as rm3 } from "fs/promises";
2936
+ import { rm as rm4 } from "fs/promises";
2416
2937
  var CALLBACK_TIMEOUT_MS = 5 * 60 * 1e3;
2417
2938
  async function awaitCallback(expectedState) {
2418
2939
  let settle;
@@ -2529,7 +3050,7 @@ async function runLogout(options) {
2529
3050
  return EXIT_INCOMPLETE;
2530
3051
  }
2531
3052
  const url = found.transport.type === "stdio" ? "" : found.transport.url;
2532
- await rm3(credentialPath(url), { force: true });
3053
+ await rm4(credentialPath(url), { force: true });
2533
3054
  process.stdout.write(`${dim(`stored credentials for ${found.name} deleted`)}
2534
3055
  `);
2535
3056
  return EXIT_CLEAN;
@@ -2675,6 +3196,30 @@ ${dim(`Looked in: ${looked}`)}
2675
3196
 
2676
3197
  // src/commands/review.ts
2677
3198
  import { createInterface as createInterface2 } from "readline/promises";
3199
+ function describeSurface(subject, previous) {
3200
+ if (typeof subject !== "object" || subject === null) return [];
3201
+ const entry = subject;
3202
+ const lines = [];
3203
+ const capabilities = surfaceCapabilities(entry.tools ?? []);
3204
+ if (capabilities.length > 0) {
3205
+ const worst = capabilities.some((c) => c.severity === "critical" || c.severity === "high");
3206
+ const text = ` after accepting, this server can: ${capabilities.map((c) => c.kind).join(", ")}`;
3207
+ lines.push(worst ? yellow(text) : dim(text));
3208
+ }
3209
+ const had = new Set(
3210
+ (typeof previous === "object" && previous !== null ? surfaceText(previous).flatMap((piece) => steeringSignals(piece.text, piece.field)) : []).map((signal) => `${signal.field}\0${signal.kind}\0${signal.quote}`)
3211
+ );
3212
+ const steering = surfaceText(entry).flatMap((piece) => steeringSignals(piece.text, piece.field)).filter((signal) => !had.has(`${signal.field}\0${signal.kind}\0${signal.quote}`));
3213
+ if (steering.length > 0) {
3214
+ lines.push(yellow(` ${steering.length} new passage(s) here read as instructions to the model:`));
3215
+ const byField = /* @__PURE__ */ new Map();
3216
+ for (const signal of steering) if (!byField.has(signal.field)) byField.set(signal.field, signal.quote);
3217
+ for (const [field, quote] of [...byField].slice(0, 3)) {
3218
+ lines.push(dim(` ${elideMiddle(field, 52)}: ${truncate(quote, 72)}`));
3219
+ }
3220
+ }
3221
+ return lines;
3222
+ }
2678
3223
  function describe(change2) {
2679
3224
  const head = ` ${change2.severity === "high" ? red("\u25CF") : change2.severity === "medium" ? yellow("\u25CF") : dim("\u25CF")} ${change2.member ? `${bold(change2.member)}: ` : ""}${change2.summary} ${dim(change2.kind)}`;
2680
3225
  if (change2.kind !== "tool.description.changed" && change2.kind !== "server.instructions.changed") return head;
@@ -2718,10 +3263,14 @@ async function runReview(options) {
2718
3263
  let declined = 0;
2719
3264
  try {
2720
3265
  for (const [serverName, serverChanges] of grouped) {
2721
- process.stdout.write(`
3266
+ const context = describeSurface(result.lock.subjects[serverName], committed.subjects[serverName]);
3267
+ process.stdout.write(
3268
+ `
2722
3269
  ${bold(serverName)}
2723
3270
  ${serverChanges.map(describe).join("\n")}
2724
- `);
3271
+ ${context.length > 0 ? `${context.join("\n")}
3272
+ ` : ""}`
3273
+ );
2725
3274
  let take = options.acceptAll;
2726
3275
  if (readline) {
2727
3276
  const answer = (await readline.question(`
@@ -2775,6 +3324,7 @@ ${bold("Options")}
2775
3324
  --allow-unreachable a server that cannot be reached warns instead of failing
2776
3325
  --json machine-readable output (check)
2777
3326
  --sarif SARIF 2.1.0 output (check)
3327
+ --sarif-steering also emit steering passages as SARIF notes (off: an alert is a gate)
2778
3328
  --accept-all accept every change without prompting (review)
2779
3329
  --force re-pin over an existing lockfile, discarding it (init)
2780
3330
  --api <url> control plane to push to (push; or NULLADRIFT_API_URL)
@@ -2803,6 +3353,7 @@ async function main() {
2803
3353
  "allow-unreachable": { type: "boolean", default: false },
2804
3354
  json: { type: "boolean", default: false },
2805
3355
  sarif: { type: "boolean", default: false },
3356
+ "sarif-steering": { type: "boolean", default: false },
2806
3357
  "accept-all": { type: "boolean", default: false },
2807
3358
  force: { type: "boolean", default: false },
2808
3359
  api: { type: "string" },
@@ -2844,6 +3395,7 @@ async function main() {
2844
3395
  timeoutMs,
2845
3396
  allowUnreachable: values["allow-unreachable"],
2846
3397
  format: values.sarif ? "sarif" : values.json ? "json" : "human",
3398
+ sarifSteering: values["sarif-steering"] === true,
2847
3399
  comment: values.comment
2848
3400
  };
2849
3401
  switch (command) {