nulladrift 0.1.5 → 0.2.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,386 +4,172 @@
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.changed",
30
+ "resource.added",
31
+ "resource.removed",
32
+ "resource.changed",
33
+ "resource_template.added",
34
+ "resource_template.removed",
35
+ "resource_template.changed",
36
+ "prompt.added",
37
+ "prompt.removed",
38
+ "prompt.changed"
39
+ ];
40
+ var SEVERITY = {
41
+ "server.added": "medium",
42
+ "server.removed": "low",
43
+ "server.renamed": "low",
44
+ "server.transport.changed": "high",
45
+ "server.identity.changed": "medium",
46
+ "server.protocol.changed": "medium",
47
+ "server.instructions.changed": "high",
48
+ "server.capabilities.widened": "medium",
49
+ "server.capabilities.narrowed": "low",
50
+ "server.capabilities.changed": "medium",
51
+ "tool.added": "high",
52
+ "tool.removed": "low",
53
+ "tool.description.changed": "high",
54
+ "tool.input_schema.widened": "high",
55
+ "tool.input_schema.narrowed": "low",
56
+ "tool.input_schema.changed": "medium",
57
+ "tool.output_schema.changed": "medium",
58
+ "tool.behavior.escalated": "high",
59
+ "tool.behavior.relaxed": "low",
60
+ "tool.header_params.changed": "high",
61
+ "tool.changed": "medium",
62
+ "resource.added": "medium",
63
+ "resource.removed": "low",
64
+ "resource.changed": "medium",
65
+ "resource_template.added": "high",
66
+ "resource_template.removed": "low",
67
+ "resource_template.changed": "high",
68
+ "prompt.added": "medium",
69
+ "prompt.removed": "low",
70
+ "prompt.changed": "medium"
71
+ };
72
+ var SEVERITY_RANK = { high: 0, medium: 1, low: 2 };
73
+ function sortChanges(changes) {
74
+ return [...changes].sort(
75
+ (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
76
  );
24
77
  }
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`;
78
+ function serversThatShippedNothing(changes) {
79
+ const moved = /* @__PURE__ */ new Set();
80
+ const versioned = /* @__PURE__ */ new Set();
81
+ for (const change2 of changes) {
82
+ moved.add(change2.server);
83
+ if (change2.kind === "server.identity.changed") versioned.add(change2.server);
84
+ }
85
+ return [...moved].filter((server2) => !versioned.has(server2)).sort();
28
86
  }
29
87
 
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
- }
88
+ // ../core/src/lock/types.ts
89
+ var LOCKFILE_VERSION = 2;
72
90
 
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);
91
+ // ../core/src/lock/canonical.ts
92
+ import { createHash } from "crypto";
93
+ var MAX_DEPTH = 100;
94
+ var tooDeep = () => new TypeError(`cannot canonicalize JSON nested deeper than ${MAX_DEPTH} levels; this is not a surface we can hash`);
95
+ function canonicalize(value, depth = 0) {
96
+ if (depth > MAX_DEPTH) throw tooDeep();
97
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
98
+ return JSON.stringify(value);
104
99
  }
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");
100
+ if (value === void 0) {
101
+ throw new TypeError("cannot canonicalize undefined; pass the value through toJson first");
117
102
  }
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
- };
103
+ if (typeof value === "number") {
104
+ if (!Number.isFinite(value)) throw new TypeError(`cannot canonicalize non-finite number: ${value}`);
105
+ return JSON.stringify(value === 0 ? 0 : value);
144
106
  }
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
- );
107
+ if (Array.isArray(value)) {
108
+ return `[${value.map((member) => canonicalize(member, depth + 1)).join(",")}]`;
151
109
  }
152
- return transport2;
110
+ const keys = Object.keys(value).sort();
111
+ const members = keys.map((key) => `${JSON.stringify(key)}:${canonicalize(value[key], depth + 1)}`);
112
+ return `{${members.join(",")}}`;
153
113
  }
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;
114
+ function digest(value) {
115
+ return `sha256:${createHash("sha256").update(canonicalize(value), "utf8").digest("hex")}`;
116
+ }
117
+ function toJson(value, depth = 0) {
118
+ if (depth > MAX_DEPTH) throw tooDeep();
119
+ if (value === null) return null;
120
+ if (Array.isArray(value)) return value.map((member) => toJson(member, depth + 1));
121
+ if (typeof value === "object") {
122
+ const out = {};
123
+ for (const [key, member] of Object.entries(value)) {
124
+ if (member === void 0) continue;
125
+ out[key] = toJson(member, depth + 1);
126
+ }
127
+ return out;
159
128
  }
160
- return void 0;
129
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") return value;
130
+ return null;
161
131
  }
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] };
132
+ function stableKey(value) {
133
+ return canonicalize(toJson(value));
221
134
  }
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
135
 
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("/");
136
+ // ../core/src/lock/reseal.ts
137
+ function sealMember(member) {
138
+ const { digest: _discarded, ...body } = member;
139
+ return { ...body, digest: digest(toJson(body)) };
265
140
  }
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}` };
141
+ function reseal(entry) {
142
+ switch (entry.kind) {
143
+ case "mcp-server":
144
+ return resealMcpServer(entry);
280
145
  }
281
146
  }
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
- }
147
+ function resealMcpServer(entry) {
148
+ const tools = (entry.tools ?? []).map((tool2) => sealMember(tool2));
149
+ const resources = (entry.resources ?? []).map((resource2) => sealMember(resource2));
150
+ const resourceTemplates = (entry.resourceTemplates ?? []).map((template) => sealMember(template));
151
+ const prompts = (entry.prompts ?? []).map((prompt2) => sealMember(prompt2));
152
+ const covered = {
153
+ transport: entry.transport,
154
+ protocol: entry.protocol,
155
+ serverInfo: entry.serverInfo,
156
+ capabilities: entry.capabilities,
157
+ instructions: entry.instructions,
158
+ tools: tools.map((tool2) => tool2.digest),
159
+ resources: resources.map((resource2) => resource2.digest),
160
+ resourceTemplates: resourceTemplates.map((template) => template.digest),
161
+ prompts: prompts.map((prompt2) => prompt2.digest)
162
+ };
332
163
  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
164
+ ...entry,
165
+ tools: tools.length > 0 ? tools : void 0,
166
+ resources: resources.length > 0 ? resources : void 0,
167
+ resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
168
+ prompts: prompts.length > 0 ? prompts : void 0,
169
+ digest: digest(toJson(covered))
339
170
  };
340
171
  }
341
172
 
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")}`;
367
- }
368
- function toJson(value, depth = 0) {
369
- if (depth > MAX_DEPTH) throw tooDeep();
370
- if (value === null) return null;
371
- if (Array.isArray(value)) return value.map((member) => toJson(member, depth + 1));
372
- if (typeof value === "object") {
373
- const out = {};
374
- for (const [key, member] of Object.entries(value)) {
375
- if (member === void 0) continue;
376
- out[key] = toJson(member, depth + 1);
377
- }
378
- return out;
379
- }
380
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") return value;
381
- return null;
382
- }
383
- function stableKey(value) {
384
- return canonicalize(toJson(value));
385
- }
386
-
387
173
  // ../core/src/lock/jsonschema.ts
388
174
  var MAX_REF_DEPTH = 32;
389
175
  var MAX_VISIT_DEPTH = 12;
@@ -522,986 +308,1465 @@ function sanitizeUrl(raw) {
522
308
  const url = new URL(raw);
523
309
  url.search = "";
524
310
  url.hash = "";
311
+ url.username = "";
312
+ url.password = "";
525
313
  return url.toString();
526
314
  } catch {
527
315
  return raw;
528
316
  }
529
317
  }
530
318
 
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);
319
+ // ../core/src/diff/schema.ts
320
+ function numberAt(node, key) {
321
+ const value = node[key];
322
+ return typeof value === "number" ? value : void 0;
534
323
  }
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
- }));
324
+ function collectFacts(schema) {
325
+ const facts = /* @__PURE__ */ new Map();
326
+ const visit = (node, path, required, depth) => {
327
+ if (depth > MAX_VISIT_DEPTH || facts.size >= MAX_FACTS) return;
328
+ const object = effectiveSchema(node, schema);
329
+ if (!object) return;
330
+ const typeValue = object["type"];
331
+ const types = typeof typeValue === "string" ? [typeValue] : Array.isArray(typeValue) ? typeValue.filter((entry) => typeof entry === "string").sort() : void 0;
332
+ const enumValue = object["enum"];
333
+ facts.set(path, {
334
+ required,
335
+ additionalProperties: typeof object["additionalProperties"] === "boolean" ? object["additionalProperties"] : void 0,
336
+ enumMembers: Array.isArray(enumValue) ? enumValue.map((entry) => canonicalize(entry)).sort() : void 0,
337
+ types,
338
+ minimum: numberAt(object, "minimum"),
339
+ maximum: numberAt(object, "maximum"),
340
+ minLength: numberAt(object, "minLength"),
341
+ maxLength: numberAt(object, "maxLength")
342
+ });
343
+ const properties = asObject(object["properties"]);
344
+ if (properties) {
345
+ const requiredList = Array.isArray(object["required"]) ? object["required"].filter((entry) => typeof entry === "string") : [];
346
+ for (const [name, child] of Object.entries(properties)) {
347
+ visit(child, path === "" ? name : `${path}.${name}`, requiredList.includes(name), depth + 1);
348
+ }
349
+ }
350
+ const items = object["items"];
351
+ if (items !== void 0) visit(items, `${path}[]`, false, depth + 1);
352
+ const prefixItems = object["prefixItems"];
353
+ if (Array.isArray(prefixItems)) prefixItems.forEach((entry, index) => visit(entry, `${path}[${index}]`, false, depth + 1));
354
+ for (const branch of alternatives(object)) visit(branch.schema, `${path}|${branch.label}`, false, depth + 1);
355
+ };
356
+ visit(schema, "", true, 0);
357
+ return facts;
543
358
  }
544
- function sealed(entry) {
545
- return { ...entry, digest: digest(toJson(entry)) };
359
+ function isSuperset(next, previous) {
360
+ return previous.every((entry) => next.includes(entry));
546
361
  }
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
- };
362
+ function classifySchemaChange(before, after) {
363
+ if (stableKey(before) === stableKey(after)) return "same";
364
+ const previous = collectFacts(before);
365
+ const next = collectFacts(after);
366
+ let widened = false;
367
+ let narrowed = false;
368
+ for (const path of /* @__PURE__ */ new Set([...previous.keys(), ...next.keys()])) {
369
+ const a = previous.get(path);
370
+ const b = next.get(path);
371
+ if (!a && b) {
372
+ widened = true;
373
+ continue;
374
+ }
375
+ if (a && !b) {
376
+ narrowed = true;
377
+ continue;
378
+ }
379
+ if (!a || !b) continue;
380
+ if (a.required && !b.required) widened = true;
381
+ if (!a.required && b.required) narrowed = true;
382
+ const beforeAdditional = a.additionalProperties ?? true;
383
+ const afterAdditional = b.additionalProperties ?? true;
384
+ if (!beforeAdditional && afterAdditional) widened = true;
385
+ if (beforeAdditional && !afterAdditional) narrowed = true;
386
+ if (a.enumMembers && b.enumMembers) {
387
+ if (isSuperset(b.enumMembers, a.enumMembers) && b.enumMembers.length > a.enumMembers.length) widened = true;
388
+ else if (isSuperset(a.enumMembers, b.enumMembers) && a.enumMembers.length > b.enumMembers.length) narrowed = true;
389
+ else if (canonicalize(a.enumMembers) !== canonicalize(b.enumMembers)) {
390
+ widened = true;
391
+ narrowed = true;
392
+ }
393
+ } else if (a.enumMembers && !b.enumMembers) widened = true;
394
+ else if (!a.enumMembers && b.enumMembers) narrowed = true;
395
+ if (a.types && b.types) {
396
+ if (isSuperset(b.types, a.types) && b.types.length > a.types.length) widened = true;
397
+ else if (isSuperset(a.types, b.types) && a.types.length > b.types.length) narrowed = true;
398
+ else if (canonicalize(a.types) !== canonicalize(b.types)) {
399
+ widened = true;
400
+ narrowed = true;
401
+ }
402
+ } else if (a.types && !b.types) widened = true;
403
+ else if (!a.types && b.types) narrowed = true;
404
+ const lowerBounds = [["minimum", a.minimum, b.minimum], ["minLength", a.minLength, b.minLength]];
405
+ for (const [, before_, after_] of lowerBounds) {
406
+ if (before_ !== void 0 && after_ === void 0) widened = true;
407
+ else if (before_ === void 0 && after_ !== void 0) narrowed = true;
408
+ else if (before_ !== void 0 && after_ !== void 0) {
409
+ if (after_ < before_) widened = true;
410
+ if (after_ > before_) narrowed = true;
411
+ }
412
+ }
413
+ const upperBounds = [["maximum", a.maximum, b.maximum], ["maxLength", a.maxLength, b.maxLength]];
414
+ for (const [, before_, after_] of upperBounds) {
415
+ if (before_ !== void 0 && after_ === void 0) widened = true;
416
+ else if (before_ === void 0 && after_ !== void 0) narrowed = true;
417
+ else if (before_ !== void 0 && after_ !== void 0) {
418
+ if (after_ > before_) widened = true;
419
+ if (after_ < before_) narrowed = true;
420
+ }
421
+ }
557
422
  }
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
- };
423
+ if (widened && !narrowed) return "widened";
424
+ if (narrowed && !widened) return "narrowed";
425
+ return "changed";
564
426
  }
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
- });
427
+
428
+ // ../core/src/diff/index.ts
429
+ function change(kind, server2, summary, extra) {
430
+ return { kind, severity: SEVERITY[kind], server: server2, summary, ...extra };
581
431
  }
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
- });
432
+ function same(a, b) {
433
+ return stableKey(a ?? null) === stableKey(b ?? null);
593
434
  }
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
- });
435
+ function indexBy(members, key) {
436
+ return new Map((members ?? []).map((member) => [key(member), member]));
605
437
  }
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
- });
438
+ function declaredNames(capabilities) {
439
+ const names = [];
440
+ for (const [key, value] of Object.entries(capabilities ?? {})) {
441
+ if (key === "extensions" && value !== null && typeof value === "object" && !Array.isArray(value)) {
442
+ for (const id of Object.keys(value)) names.push(`extensions/${id}`);
443
+ continue;
444
+ }
445
+ names.push(key);
446
+ }
447
+ return names;
622
448
  }
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)) };
449
+ function compareCapabilities(before, after, name) {
450
+ if (same(before.capabilities, after.capabilities)) return [];
451
+ const previous = declaredNames(before.capabilities);
452
+ const next = declaredNames(after.capabilities);
453
+ const gained = next.filter((key) => !previous.includes(key));
454
+ const lost = previous.filter((key) => !next.includes(key));
455
+ if (gained.length > 0 && lost.length === 0) {
456
+ return [change("server.capabilities.widened", name, `server now declares ${gained.join(", ")}`, { before: before.capabilities, after: after.capabilities })];
457
+ }
458
+ if (lost.length > 0 && gained.length === 0) {
459
+ return [change("server.capabilities.narrowed", name, `server no longer declares ${lost.join(", ")}`, { before: before.capabilities, after: after.capabilities })];
460
+ }
461
+ return [change("server.capabilities.changed", name, "declared capabilities changed", { before: before.capabilities, after: after.capabilities })];
653
462
  }
654
-
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");
680
- }
681
- function credentialPath(url) {
682
- return join2(authDir(), `${createHash2("sha256").update(url).digest("hex").slice(0, 16)}.json`);
683
- }
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";
463
+ function compareTool(name, before, after) {
464
+ if (before.digest === after.digest) return [];
465
+ const changes = [];
466
+ const at = { member: before.name };
467
+ if (!same(before.description, after.description)) {
468
+ changes.push(
469
+ change("tool.description.changed", name, `description changed (${before.description?.length ?? 0} \u2192 ${after.description?.length ?? 0} characters)`, {
470
+ ...at,
471
+ before: before.description,
472
+ after: after.description
473
+ })
474
+ );
689
475
  }
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;
476
+ const inputVerdict = classifySchemaChange(before.inputSchema, after.inputSchema);
477
+ if (inputVerdict !== "same") {
478
+ const kind = `tool.input_schema.${inputVerdict}`;
479
+ const wording = inputVerdict === "widened" ? "accepts input it did not before" : inputVerdict === "narrowed" ? "accepts less input than before" : "input schema changed";
480
+ changes.push(change(kind, name, wording, { ...at, before: before.inputSchema, after: after.inputSchema }));
697
481
  }
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;
482
+ if (!same(before.outputSchema, after.outputSchema)) {
483
+ changes.push(change("tool.output_schema.changed", name, "output schema changed", { ...at, before: before.outputSchema, after: after.outputSchema }));
706
484
  }
707
- state() {
708
- return this.stateValue;
485
+ if (!same(before.behavior, after.behavior)) {
486
+ const escalated = isEscalation(before.behavior, after.behavior);
487
+ changes.push(
488
+ change(escalated ? "tool.behavior.escalated" : "tool.behavior.relaxed", name, escalated ? describeEscalation(before, after) : "declares fewer powers than before", {
489
+ ...at,
490
+ before: before.behavior,
491
+ after: after.behavior
492
+ })
493
+ );
709
494
  }
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
- };
495
+ if (!same(before.headerParams, after.headerParams)) {
496
+ changes.push(
497
+ change("tool.header_params.changed", name, "arguments mirrored into HTTP headers changed", { ...at, before: before.headerParams ?? [], after: after.headerParams ?? [] })
498
+ );
721
499
  }
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 };
500
+ if (changes.length === 0) {
501
+ changes.push(change("tool.changed", name, "tool definition changed (title, icons or _meta)", { ...at, before, after }));
502
+ }
503
+ return changes;
504
+ }
505
+ function describeEscalation(before, after) {
506
+ const gained = [];
507
+ if (before.behavior.readOnly && !after.behavior.readOnly) gained.push("may now modify");
508
+ if (!before.behavior.destructive && after.behavior.destructive) gained.push("may now destroy");
509
+ if (before.behavior.idempotent && !after.behavior.idempotent) gained.push("repeat calls now compound");
510
+ if (!before.behavior.openWorld && after.behavior.openWorld) gained.push("may now reach external systems");
511
+ return gained.join("; ");
512
+ }
513
+ function compareMembers(name, before, after, spec, deep) {
514
+ const changes = [];
515
+ const previous = indexBy(before, spec.key);
516
+ const next = indexBy(after, spec.key);
517
+ for (const [key, member] of next) {
518
+ const existing = previous.get(key);
519
+ if (!existing) {
520
+ changes.push(change(spec.added, name, `new ${spec.noun} ${spec.label(member)}`, { member: spec.label(member), after: member }));
521
+ continue;
728
522
  }
729
- return this.cache;
523
+ if (existing.digest === member.digest) continue;
524
+ 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 })]);
730
525
  }
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 });
526
+ for (const [key, member] of previous) {
527
+ if (!next.has(key)) changes.push(change(spec.removed, name, `${spec.noun} ${spec.label(member)} is gone`, { member: spec.label(member), before: member }));
738
528
  }
739
- async clientInformation() {
740
- return (await this.read()).clientInformation;
529
+ return changes;
530
+ }
531
+ function compareServer(name, before, after) {
532
+ if (before.digest === after.digest) return [];
533
+ const changes = [];
534
+ if (!same(before.transport, after.transport)) {
535
+ changes.push(change("server.transport.changed", name, "the server is reached differently than when it was pinned", { before: before.transport, after: after.transport }));
741
536
  }
742
- async saveClientInformation(clientInformation) {
743
- await this.write({ clientInformation });
537
+ if (!same(before.serverInfo, after.serverInfo)) {
538
+ const from = before.serverInfo?.version ?? "unknown";
539
+ const to = after.serverInfo?.version ?? "unknown";
540
+ changes.push(change("server.identity.changed", name, `server identity changed (version ${from} \u2192 ${to})`, { before: before.serverInfo, after: after.serverInfo }));
744
541
  }
745
- async tokens() {
746
- return (await this.read()).tokens;
542
+ if (!same(before.protocol, after.protocol)) {
543
+ changes.push(
544
+ change("server.protocol.changed", name, `protocol changed (${before.protocol.era}/${before.protocol.version} \u2192 ${after.protocol.era}/${after.protocol.version})`, {
545
+ before: before.protocol,
546
+ after: after.protocol
547
+ })
548
+ );
747
549
  }
748
- async saveTokens(tokens) {
749
- await this.write({ tokens });
550
+ if (!same(before.instructions, after.instructions)) {
551
+ changes.push(
552
+ change("server.instructions.changed", name, "server instructions changed: this text goes into the model's system prompt", {
553
+ before: before.instructions,
554
+ after: after.instructions
555
+ })
556
+ );
750
557
  }
751
- async saveCodeVerifier(codeVerifier) {
752
- await this.write({ codeVerifier });
558
+ changes.push(...compareCapabilities(before, after, name));
559
+ changes.push(
560
+ ...compareMembers(
561
+ name,
562
+ before.tools,
563
+ after.tools,
564
+ { key: (t) => t.name, label: (t) => t.name, added: "tool.added", removed: "tool.removed", changed: "tool.changed", noun: "tool" },
565
+ (_key, a, b) => compareTool(name, a, b)
566
+ )
567
+ );
568
+ changes.push(
569
+ ...compareMembers(name, before.resources, after.resources, {
570
+ key: (r) => r.uri,
571
+ label: (r) => `${r.name} (${r.uri})`,
572
+ added: "resource.added",
573
+ removed: "resource.removed",
574
+ changed: "resource.changed",
575
+ noun: "resource"
576
+ })
577
+ );
578
+ changes.push(
579
+ ...compareMembers(name, before.resourceTemplates, after.resourceTemplates, {
580
+ key: (t) => t.uriTemplate,
581
+ // The template itself is the capability -- widening it from file:///project/{path} to
582
+ // file:///{path} is the whole finding -- so it belongs in the label, not just the body.
583
+ label: (t) => `${t.name} (${t.uriTemplate})`,
584
+ added: "resource_template.added",
585
+ removed: "resource_template.removed",
586
+ changed: "resource_template.changed",
587
+ noun: "resource template"
588
+ })
589
+ );
590
+ changes.push(
591
+ ...compareMembers(name, before.prompts, after.prompts, {
592
+ key: (p) => p.name,
593
+ label: (p) => p.name,
594
+ added: "prompt.added",
595
+ removed: "prompt.removed",
596
+ changed: "prompt.changed",
597
+ noun: "prompt"
598
+ })
599
+ );
600
+ return changes;
601
+ }
602
+ function detectRenames(before, after, removed, added) {
603
+ const changes = [];
604
+ const renamed = /* @__PURE__ */ new Set();
605
+ const availableAdds = [...added];
606
+ for (const oldName of removed) {
607
+ const oldEntry = before.subjects[oldName];
608
+ if (!oldEntry) continue;
609
+ const match = availableAdds.find((newName) => {
610
+ const candidate = after.subjects[newName];
611
+ return candidate !== void 0 && candidate.digest === oldEntry.digest && same(candidate.transport, oldEntry.transport);
612
+ });
613
+ if (!match) continue;
614
+ availableAdds.splice(availableAdds.indexOf(match), 1);
615
+ renamed.add(oldName);
616
+ renamed.add(match);
617
+ changes.push(change("server.renamed", match, `renamed from "${oldName}"; capabilities are unchanged`, { before: oldName, after: match }));
753
618
  }
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;
619
+ return { changes, renamed };
620
+ }
621
+ function diffLockfiles(before, after) {
622
+ const beforeNames = Object.keys(before.subjects);
623
+ const afterNames = Object.keys(after.subjects);
624
+ const removed = beforeNames.filter((name) => !afterNames.includes(name));
625
+ const added = afterNames.filter((name) => !beforeNames.includes(name));
626
+ const { changes: renameChanges, renamed } = detectRenames(before, after, removed, added);
627
+ const changes = [...renameChanges];
628
+ for (const name of added) {
629
+ if (renamed.has(name)) continue;
630
+ const entry = after.subjects[name];
631
+ const toolCount = entry?.tools?.length ?? 0;
632
+ changes.push(change("server.added", name, `new server with ${toolCount} tool${toolCount === 1 ? "" : "s"}`, { after: entry }));
758
633
  }
759
- async saveAuthorizationServerUrl(authorizationServerUrl) {
760
- await this.write({ authorizationServerUrl });
634
+ for (const name of removed) {
635
+ if (renamed.has(name)) continue;
636
+ changes.push(change("server.removed", name, "server is no longer configured", { before: before.subjects[name] }));
761
637
  }
762
- async authorizationServerUrl() {
763
- return (await this.read()).authorizationServerUrl;
638
+ for (const name of afterNames) {
639
+ const a = before.subjects[name];
640
+ const b = after.subjects[name];
641
+ if (!a || !b) continue;
642
+ changes.push(...compareServer(name, a, b));
764
643
  }
765
- async saveResourceUrl(resourceUrl) {
766
- await this.write({ resourceUrl });
644
+ return sortChanges(changes);
645
+ }
646
+
647
+ // ../core/src/risk/capability.ts
648
+ var CAPABILITY_SEVERITIES = ["critical", "high", "medium", "low"];
649
+ var RULES = [
650
+ { 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)(_|$)/ },
651
+ // `source` is deliberately absent: in `copy_file(source, destination)` it is a path, and
652
+ // labelling a file copy as arbitrary code execution at CRITICAL is the false positive that
653
+ // teaches people to stop reading the line. `code` has to be the whole argument name for the
654
+ // same reason -- a crawl of 468 published tools flagged `location_code` as arbitrary code
655
+ // execution, and `country_code`, `status_code` and `zip_code` are all waiting behind it.
656
+ { 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)(_|$)/ },
657
+ { kind: "credential-access", severity: "critical", name: /(^|_)(secret|secrets|credential|credentials|token|keychain|vault|password)(_|$)/, arg: /(^|_)(secret|credential|password|private_key|api_key|access_token)(_|$)/ },
658
+ { 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)(_|$)/ },
659
+ { 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)(_|$)/ },
660
+ // Narrowed to things that are actually SQL-shaped. `query`, `select` and `update` on their
661
+ // own matched `simulate-research-query`, `browser_select_option` and `trigger-resource-update`,
662
+ // none of which is a database.
663
+ { kind: "database", severity: "high", name: /(^|_)(sql|execute_sql|run_sql|query_db|db_query|migrate)(_|$)/, arg: /(^|_)(sql|statement|dsn|connection_string)(_|$)/ },
664
+ { kind: "privilege", severity: "high", name: /(^|_)(sudo|root|admin|grant|revoke|permission|permissions|acl|policy)(_|$)/, arg: /(^|_)(role|scope|scopes|permission|permissions|privilege)(_|$)/ },
665
+ { kind: "agent-control", severity: "high", name: /(^|_)(prompt|system_prompt|instruction|instructions|memory|context|persona)(_|$)/, arg: /(^|_)(system_prompt|instruction|instructions|persona)(_|$)/ },
666
+ { kind: "env-access", severity: "medium", name: /(^|_)(env|environment|getenv|setenv|config|settings)(_|$)/, arg: /(^|_)(env|environment|env_var)(_|$)/ },
667
+ { 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)(_|$)/ }
668
+ ];
669
+ var CONFUSABLES = {
670
+ "\u0430": "a",
671
+ "\u0435": "e",
672
+ "\u043E": "o",
673
+ "\u0441": "c",
674
+ "\u0440": "p",
675
+ "\u0445": "x",
676
+ "\u0443": "y",
677
+ "\u0456": "i",
678
+ "\u0458": "j",
679
+ "\u04BB": "h",
680
+ "\u0501": "d",
681
+ "\u051B": "q",
682
+ "\u03BF": "o",
683
+ "\u03B1": "a",
684
+ "\u03B5": "e",
685
+ "\u03BD": "v",
686
+ "\u03C1": "p",
687
+ "\u03C5": "u",
688
+ "\u0131": "i",
689
+ "\u1E9E": "s"
690
+ };
691
+ var CONFUSABLE_PATTERN = new RegExp(`[${Object.keys(CONFUSABLES).join("")}]`, "g");
692
+ function normalize(identifier) {
693
+ return identifier.toLowerCase().replace(CONFUSABLE_PATTERN, (character) => CONFUSABLES[character] ?? character).replace(/[-.\s/]+/g, "_");
694
+ }
695
+ function argumentNames(inputSchema, depth = 0) {
696
+ if (depth > 6 || typeof inputSchema !== "object" || inputSchema === null) return [];
697
+ const node = inputSchema;
698
+ const names = [];
699
+ const properties = node.properties;
700
+ if (typeof properties === "object" && properties !== null) {
701
+ for (const [name, child] of Object.entries(properties)) {
702
+ names.push(name);
703
+ names.push(...argumentNames(child, depth + 1));
704
+ }
767
705
  }
768
- async resourceUrl() {
769
- return (await this.read()).resourceUrl;
770
- }
771
- async saveDiscoveryState(discoveryState) {
772
- await this.write({ discoveryState });
773
- }
774
- async discoveryState() {
775
- return (await this.read()).discoveryState;
776
- }
777
- async invalidateCredentials(scope) {
778
- if (scope === "all") {
779
- this.cache = { serverUrl: this.serverUrl };
780
- await rm(credentialPath(this.serverUrl), { force: true });
781
- return;
782
- }
783
- const key = { client: "clientInformation", tokens: "tokens", verifier: "codeVerifier", discovery: "discoveryState" }[scope];
784
- await this.write({ [key]: void 0 });
785
- }
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()}
792
-
793
- `);
794
- }
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 {
802
- }
803
- }
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;
706
+ if (node.items !== void 0) names.push(...argumentNames(node.items, depth + 1));
707
+ return names;
708
+ }
709
+ function toolCapabilities(tool2) {
710
+ const name = normalize(tool2.name ?? "");
711
+ const args = argumentNames(tool2.inputSchema).map((argument) => [argument, normalize(argument)]);
712
+ const found = /* @__PURE__ */ new Map();
713
+ for (const rule of RULES) {
714
+ if (found.has(rule.kind)) continue;
715
+ if (rule.name?.test(name)) {
716
+ found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: "name" });
717
+ continue;
718
+ }
719
+ const hit = rule.arg ? args.find(([, normalized]) => rule.arg?.test(normalized)) : void 0;
720
+ if (hit) found.set(rule.kind, { kind: rule.kind, severity: rule.severity, evidence: `arg:${hit[0]}` });
810
721
  }
722
+ return [...found.values()].sort(
723
+ (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
724
+ );
811
725
  }
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
- });
726
+ function surfaceCapabilities(tools) {
727
+ const byKind = /* @__PURE__ */ new Map();
728
+ for (const tool2 of tools) {
729
+ for (const capability of toolCapabilities(tool2)) {
730
+ const existing = byKind.get(capability.kind);
731
+ if (existing) existing.tools.push(tool2.name ?? "?");
732
+ else byKind.set(capability.kind, { ...capability, tools: [tool2.name ?? "?"] });
733
+ }
822
734
  }
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 }
828
- });
735
+ return [...byKind.values()].sort(
736
+ (a, b) => CAPABILITY_SEVERITIES.indexOf(a.severity) - CAPABILITY_SEVERITIES.indexOf(b.severity) || a.kind.localeCompare(b.kind)
737
+ );
829
738
  }
830
739
 
831
- // src/mcp/types.ts
832
- import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/client";
833
- var UnreachableServerError = class extends Error {
834
- constructor(serverName, message, cause) {
835
- super(message);
836
- this.serverName = serverName;
837
- this.cause = cause;
838
- this.name = "UnreachableServerError";
839
- }
840
- serverName;
841
- cause;
740
+ // ../core/src/risk/steering.ts
741
+ var PATTERNS = [
742
+ // Imperatives aimed at the reader of the prompt, not at a person reading documentation.
743
+ { kind: "model-directive", pattern: /\b(ignore|disregard|override)\s+(all\s+)?(previous|prior|earlier|above)\b[^.]{0,80}/gi },
744
+ { kind: "model-directive", pattern: /\b(before|prior to)\s+(answering|responding|using this tool|continuing)\b[^.]{0,80}/gi },
745
+ { 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 },
746
+ { kind: "model-directive", pattern: /\byou\s+(must|should|are required to)\s+(also\s+)?(read|send|include|call|fetch)\b[^.]{0,60}/gi },
747
+ // Paths that only appear in a description when something wants their contents.
748
+ { kind: "credential-path", pattern: /(~|\$HOME|\/home\/[\w.-]+|\/Users\/[\w.-]+)?[/\\]?\.(aws\/credentials|ssh\/id_[\w]+|npmrc|netrc|git-credentials|kube\/config|env)\b/gi },
749
+ { kind: "credential-path", pattern: /\b(id_rsa|id_ed25519|authorized_keys|\.pem|service-account\.json)\b/gi },
750
+ { kind: "exfiltration", pattern: /\b(send|post|upload|transmit|forward|exfiltrate)\s+[^.]{0,40}\bto\s+(https?:\/\/|[\w.-]+\.[a-z]{2,})/gi },
751
+ { kind: "exfiltration", pattern: /\b(include|append|attach)\s+(its|the|their)\s+contents?\b[^.]{0,60}/gi },
752
+ // Characters that make text render as something other than what it is.
753
+ { kind: "hidden-text", pattern: /[\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]+/g }
754
+ ];
755
+ var CONFUSABLES2 = {
756
+ "\u0430": "a",
757
+ "\u0435": "e",
758
+ "\u043E": "o",
759
+ "\u0441": "c",
760
+ "\u0440": "p",
761
+ "\u0445": "x",
762
+ "\u0443": "y",
763
+ "\u0456": "i",
764
+ "\u03BF": "o",
765
+ "\u03B1": "a",
766
+ "\u03B5": "e",
767
+ "\u03C1": "p"
842
768
  };
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";
769
+ var CONFUSABLE_PATTERN2 = new RegExp(`[${Object.keys(CONFUSABLES2).join("")}]`, "g");
770
+ function fold(text) {
771
+ return text.replace(CONFUSABLE_PATTERN2, (character) => CONFUSABLES2[character] ?? character);
853
772
  }
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;
773
+ function steeringSignals(text, field) {
774
+ if (!text) return [];
775
+ const found = [];
776
+ const seen = /* @__PURE__ */ new Set();
777
+ const folded = fold(text);
778
+ for (const { kind, pattern } of PATTERNS) {
779
+ for (const match of folded.matchAll(pattern)) {
780
+ const at = match.index ?? 0;
781
+ const raw = text.slice(at, at + match[0].length).trim();
782
+ if (raw.length === 0) continue;
783
+ 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;
784
+ const key = `${kind}\0${quote}`;
785
+ if (seen.has(key)) continue;
786
+ seen.add(key);
787
+ found.push({ kind, quote, field });
788
+ }
863
789
  }
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);
790
+ return found;
868
791
  }
869
792
 
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;
793
+ // ../core/src/risk/surface-text.ts
794
+ var MAX_NODES = 2e4;
795
+ function schemaText(root, rootPath, out) {
796
+ const stack = [{ node: root, path: rootPath }];
797
+ const seen = /* @__PURE__ */ new WeakSet();
798
+ let budget = MAX_NODES;
799
+ while (stack.length > 0 && budget-- > 0) {
800
+ const { node, path } = stack.pop();
801
+ if (typeof node !== "object" || node === null) continue;
802
+ if (seen.has(node)) continue;
803
+ seen.add(node);
804
+ const schema = node;
805
+ if (typeof schema.description === "string") out.push({ field: path, text: schema.description });
806
+ if (typeof schema.title === "string") out.push({ field: `${path}.title`, text: schema.title });
807
+ const properties = schema.properties;
808
+ if (typeof properties === "object" && properties !== null) {
809
+ for (const [name, child] of Object.entries(properties)) {
810
+ stack.push({ node: child, path: `${path}.${name}` });
811
+ }
812
+ }
813
+ if (schema.items !== void 0) stack.push({ node: schema.items, path: `${path}[]` });
889
814
  }
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());
901
815
  }
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);
816
+ function surfaceText(subject) {
817
+ const out = [];
818
+ const push = (field, text) => {
819
+ if (typeof text === "string" && text.length > 0) out.push({ field, text });
906
820
  };
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 } }
821
+ push("instructions", subject.instructions);
822
+ for (const tool2 of subject.tools ?? []) {
823
+ const where = tool2.name ?? "?";
824
+ push(`${where}.title`, tool2.title);
825
+ push(`${where}.description`, tool2.description);
826
+ schemaText(tool2.inputSchema, `${where}.inputSchema`, out);
827
+ schemaText(tool2.outputSchema, `${where}.outputSchema`, out);
828
+ }
829
+ for (const prompt2 of subject.prompts ?? []) {
830
+ const where = prompt2.name ?? "?";
831
+ push(`prompt:${where}.title`, prompt2.title);
832
+ push(`prompt:${where}.description`, prompt2.description);
833
+ for (const argument of prompt2.arguments ?? []) {
834
+ push(`prompt:${where}.${argument.name ?? "?"}`, argument.description);
916
835
  }
917
- );
918
- 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);
923
836
  }
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
935
- );
837
+ for (const resource2 of subject.resources ?? []) {
838
+ const where = resource2.name ?? resource2.uri ?? "?";
839
+ push(`resource:${where}.title`, resource2.title);
840
+ push(`resource:${where}.description`, resource2.description);
936
841
  }
937
- return {
938
- client,
939
- stderr: () => stderrBuffer,
940
- close: async () => {
941
- await client.close().catch(() => {
942
- });
943
- }
944
- };
842
+ for (const template of subject.resourceTemplates ?? []) {
843
+ const where = template.name ?? template.uriTemplate ?? "?";
844
+ push(`template:${where}.title`, template.title);
845
+ push(`template:${where}.description`, template.description);
846
+ }
847
+ return out;
945
848
  }
946
849
 
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);
850
+ // ../core/src/risk/arrival.ts
851
+ function identity(signal) {
852
+ return `${signal.field}\0${signal.kind}\0${signal.quote}`;
853
+ }
854
+ function signalsFor(subject) {
855
+ if (typeof subject !== "object" || subject === null) return [];
856
+ return surfaceText(subject).flatMap(
857
+ (piece) => steeringSignals(piece.text, piece.field)
858
+ );
859
+ }
860
+ function newSteering(committed, observed) {
861
+ const found = [];
862
+ for (const [server2, subject] of Object.entries(observed.subjects ?? {})) {
863
+ const before = new Set(signalsFor(committed.subjects?.[server2]).map(identity));
864
+ const signals = signalsFor(subject).filter((signal) => !before.has(identity(signal)));
865
+ if (signals.length > 0) found.push({ server: server2, signals });
954
866
  }
867
+ return found.sort((a, b) => a.server.localeCompare(b.server));
955
868
  }
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
- };
869
+
870
+ // src/lib/ui.ts
871
+ var enabled = process.stdout.isTTY === true && process.env["NO_COLOR"] === void 0 && process.env["TERM"] !== "dumb";
872
+ var wrap = (code) => (text) => enabled ? `\x1B[${code}m${text}\x1B[0m` : text;
873
+ var bold = wrap(1);
874
+ var dim = wrap(2);
875
+ var red = wrap(31);
876
+ var green = wrap(32);
877
+ var yellow = wrap(33);
878
+ var blue = wrap(34);
879
+ function visibleControls(text) {
880
+ return text.replace(
881
+ // C0 and C1 controls and DEL, plus the bidirectional overrides and zero-width characters
882
+ // that change what a line appears to say without changing what it is.
883
+ // eslint-disable-next-line no-control-regex
884
+ /[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g,
885
+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
886
+ );
965
887
  }
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
- };
888
+ function truncate(text, limit = 160) {
889
+ const collapsed = visibleControls(text).replace(/\s+/g, " ").trim();
890
+ return collapsed.length <= limit ? collapsed : `${collapsed.slice(0, limit - 1)}\u2026`;
976
891
  }
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();
1001
- }
892
+ function elideMiddle(path, limit) {
893
+ if (path.length <= limit) return path;
894
+ const keep = Math.floor((limit - 1) / 2);
895
+ return `${path.slice(0, keep)}\u2026${path.slice(-keep)}`;
1002
896
  }
1003
897
 
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);
1014
- }
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
- 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) };
1026
- } 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 } };
898
+ // src/config/discover.ts
899
+ import { readFile as readFile2 } from "fs/promises";
900
+ import { homedir as homedir2, platform } from "os";
901
+ import { isAbsolute, join, relative, resolve as resolve2, sep } from "path";
902
+
903
+ // src/config/parsers.ts
904
+ import { readFile } from "fs/promises";
905
+ import { resolve } from "path";
906
+ import { z } from "zod";
907
+
908
+ // src/config/expand.ts
909
+ import { homedir } from "os";
910
+ var PLACEHOLDER = /\$\{([^}]+)\}/g;
911
+ function expand(input, context) {
912
+ const unresolved = [];
913
+ const value = input.replace(PLACEHOLDER, (match, body) => {
914
+ if (body === "workspaceFolder") return context.workspaceFolder;
915
+ if (body === "userHome") return homedir();
916
+ if (body === "pathSeparator" || body === "/") return "/";
917
+ if (body.startsWith("input:") || body.startsWith("command:")) {
918
+ unresolved.push(match);
919
+ return match;
920
+ }
921
+ if (body.startsWith("env:")) {
922
+ const name = body.slice(4);
923
+ const found2 = context.env[name];
924
+ if (found2 !== void 0) return found2;
925
+ unresolved.push(match);
926
+ return match;
927
+ }
928
+ const defaultAt = body.indexOf(":-");
929
+ if (defaultAt !== -1) {
930
+ const name = body.slice(0, defaultAt);
931
+ return context.env[name] ?? body.slice(defaultAt + 2);
1031
932
  }
933
+ const found = context.env[body];
934
+ if (found !== void 0) return found;
935
+ unresolved.push(match);
936
+ return match;
1032
937
  });
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
- }
1039
- for (const skipped of discovery.skipped) {
1040
- unreachable.push({ server: skipped.serverName, reason: skipped.message, kind: "unreachable" });
1041
- }
1042
- for (const problem of discovery.problems) {
1043
- unreachable.push({ server: problem.file, reason: problem.reason, kind: "unreachable" });
1044
- }
1045
- return {
1046
- lock: {
1047
- lockfileVersion: LOCKFILE_VERSION,
1048
- generatedBy: `nulladrift@${VERSION}`,
1049
- policy: options.policy,
1050
- subjects
1051
- },
1052
- unreachable,
1053
- discovery
1054
- };
938
+ return { value, unresolved };
1055
939
  }
1056
940
 
1057
- // ../core/src/diff/schema.ts
1058
- function numberAt(node, key) {
1059
- const value = node[key];
1060
- return typeof value === "number" ? value : void 0;
941
+ // src/config/parsers.ts
942
+ var serverEntrySchema = z.looseObject({
943
+ type: z.string().optional(),
944
+ command: z.string().optional(),
945
+ args: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
946
+ env: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])).optional(),
947
+ cwd: z.string().optional(),
948
+ url: z.string().optional(),
949
+ headers: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
950
+ envFile: z.string().optional(),
951
+ headersHelper: z.string().optional(),
952
+ oauth: z.looseObject({
953
+ clientId: z.string().optional(),
954
+ clientSecret: z.string().optional(),
955
+ scope: z.string().optional(),
956
+ scopes: z.array(z.string()).optional()
957
+ }).optional()
958
+ });
959
+ var UnsupportedServerError = class extends Error {
960
+ constructor(serverName, message) {
961
+ super(message);
962
+ this.serverName = serverName;
963
+ this.name = "UnsupportedServerError";
964
+ }
965
+ serverName;
966
+ };
967
+ function scalarsToStrings(record) {
968
+ const out = {};
969
+ for (const [key, value] of Object.entries(record ?? {})) {
970
+ if (value === null) continue;
971
+ out[key] = String(value);
972
+ }
973
+ return out;
1061
974
  }
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);
975
+ function resolveTransport(name, entry, context) {
976
+ const unresolved = [];
977
+ const take = (input) => {
978
+ const result = expand(input, context);
979
+ unresolved.push(...result.unresolved);
980
+ return result.value;
1093
981
  };
1094
- visit(schema, "", true, 0);
1095
- return facts;
982
+ const declared = entry.type === "streamable-http" ? "http" : entry.type;
983
+ if (declared === "ws") {
984
+ throw new UnsupportedServerError(name, "WebSocket transport is not supported by the MCP specification or the SDK");
985
+ }
986
+ let transport2;
987
+ if (declared === "http" || declared === "sse" || declared === void 0 && entry.url !== void 0) {
988
+ if (entry.url === void 0) throw new UnsupportedServerError(name, `transport "${declared}" needs a url`);
989
+ const oauth = entry.oauth;
990
+ transport2 = {
991
+ type: declared === "sse" ? "sse" : "http",
992
+ url: take(entry.url),
993
+ asWritten: { url: String(entry.url) },
994
+ headers: Object.fromEntries(Object.entries(scalarsToStrings(entry.headers)).map(([key, value]) => [key, take(value)])),
995
+ ...oauth === void 0 ? {} : {
996
+ oauth: {
997
+ // Expanded here so a secret can live in the environment rather than the config file.
998
+ clientId: oauth.clientId === void 0 ? void 0 : take(oauth.clientId),
999
+ clientSecret: oauth.clientSecret === void 0 ? void 0 : take(oauth.clientSecret),
1000
+ scope: oauth.scope ?? oauth.scopes?.join(" ")
1001
+ }
1002
+ }
1003
+ };
1004
+ } else {
1005
+ if (entry.command === void 0) throw new UnsupportedServerError(name, "stdio server has no command");
1006
+ transport2 = {
1007
+ type: "stdio",
1008
+ command: take(entry.command),
1009
+ args: (entry.args ?? []).map((argument) => take(String(argument))),
1010
+ asWritten: { command: String(entry.command), args: (entry.args ?? []).map((argument) => String(argument)) },
1011
+ env: Object.fromEntries(Object.entries(scalarsToStrings(entry.env)).map(([key, value]) => [key, take(value)])),
1012
+ cwd: entry.cwd ? take(entry.cwd) : void 0
1013
+ };
1014
+ }
1015
+ if (unresolved.length > 0) {
1016
+ const names = [...new Set(unresolved)].join(", ");
1017
+ throw new UnsupportedServerError(
1018
+ name,
1019
+ `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.`
1020
+ );
1021
+ }
1022
+ return transport2;
1096
1023
  }
1097
- function isSuperset(next, previous) {
1098
- return previous.every((entry) => next.includes(entry));
1024
+ function detectMapKey(raw) {
1025
+ if (typeof raw !== "object" || raw === null) return void 0;
1026
+ const record = raw;
1027
+ for (const key of ["mcpServers", "servers"]) {
1028
+ if (typeof record[key] === "object" && record[key] !== null) return key;
1029
+ }
1030
+ return void 0;
1099
1031
  }
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;
1111
- continue;
1032
+ async function readEnvFile(path) {
1033
+ const out = {};
1034
+ const text = await readFile(path, "utf8");
1035
+ for (const line of text.split(/\r?\n/)) {
1036
+ const trimmed = line.trim();
1037
+ if (trimmed === "" || trimmed.startsWith("#")) continue;
1038
+ const at = trimmed.indexOf("=");
1039
+ if (at <= 0) continue;
1040
+ const key = trimmed.slice(0, at).trim().replace(/^export\s+/, "");
1041
+ let value = trimmed.slice(at + 1).trim();
1042
+ if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
1043
+ value = value.slice(1, -1);
1112
1044
  }
1113
- if (a && !b) {
1114
- narrowed = true;
1045
+ out[key] = value;
1046
+ }
1047
+ return out;
1048
+ }
1049
+ async function parseServerMap(raw, mapKey, source, context) {
1050
+ const servers = [];
1051
+ const skipped = [];
1052
+ if (typeof raw !== "object" || raw === null) return { servers, skipped };
1053
+ const map = raw[mapKey];
1054
+ if (typeof map !== "object" || map === null) return { servers, skipped };
1055
+ for (const [name, value] of Object.entries(map)) {
1056
+ const entry = serverEntrySchema.safeParse(value);
1057
+ if (!entry.success) {
1058
+ skipped.push(new UnsupportedServerError(name, `entry is not a server definition: ${entry.error.issues[0]?.message ?? "unknown"}`));
1115
1059
  continue;
1116
1060
  }
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;
1061
+ try {
1062
+ if (entry.data.headersHelper !== void 0) {
1063
+ throw new UnsupportedServerError(name, "`headersHelper` runs a command to produce headers, which this tool will not execute");
1130
1064
  }
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;
1065
+ const transport2 = resolveTransport(name, entry.data, context);
1066
+ if (transport2.type === "stdio" && entry.data.envFile !== void 0) {
1067
+ const expanded = expand(entry.data.envFile, context);
1068
+ if (expanded.unresolved.length > 0) {
1069
+ throw new UnsupportedServerError(name, `envFile path contains unresolved placeholders: ${expanded.unresolved.join(", ")}`);
1070
+ }
1071
+ try {
1072
+ transport2.env = { ...await readEnvFile(resolve(context.workspaceFolder, expanded.value)), ...transport2.env };
1073
+ } catch (error) {
1074
+ throw new UnsupportedServerError(name, `envFile ${expanded.value} could not be read: ${error.message}`);
1075
+ }
1139
1076
  }
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;
1077
+ servers.push({ name, source: { ...source }, transport: transport2 });
1078
+ } catch (error) {
1079
+ if (error instanceof UnsupportedServerError) skipped.push(error);
1080
+ else throw error;
1081
+ }
1082
+ }
1083
+ return { servers, skipped };
1084
+ }
1085
+ async function parseClaudeJson(raw, projectRoot, source, context) {
1086
+ const user = await parseServerMap(raw, "mcpServers", { ...source, scope: "user" }, context);
1087
+ const projects = typeof raw === "object" && raw !== null ? raw["projects"] : void 0;
1088
+ const forProject = typeof projects === "object" && projects !== null ? projects[projectRoot] : void 0;
1089
+ const local = forProject ? await parseServerMap(forProject, "mcpServers", { ...source, scope: "local" }, context) : { servers: [], skipped: [] };
1090
+ return { servers: [...user.servers, ...local.servers], skipped: [...user.skipped, ...local.skipped] };
1091
+ }
1092
+ var CLIENT_MAP_KEY = {
1093
+ "claude-code": "mcpServers",
1094
+ "claude-desktop": "mcpServers",
1095
+ vscode: "servers",
1096
+ cursor: "mcpServers",
1097
+ copilot: "mcpServers",
1098
+ windsurf: "mcpServers",
1099
+ generic: "mcpServers",
1100
+ manual: "mcpServers"
1101
+ };
1102
+
1103
+ // src/config/discover.ts
1104
+ function claudeDesktopPath() {
1105
+ const home = homedir2();
1106
+ switch (platform()) {
1107
+ case "darwin":
1108
+ return join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
1109
+ case "win32":
1110
+ return join(process.env["APPDATA"] ?? join(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json");
1111
+ default:
1112
+ return join(home, ".config", "Claude", "claude_desktop_config.json");
1113
+ }
1114
+ }
1115
+ function candidateConfigFiles(projectRoot) {
1116
+ const home = homedir2();
1117
+ const copilotHome = process.env["COPILOT_HOME"] ?? join(home, ".copilot");
1118
+ return [
1119
+ { client: "claude-code", path: join(projectRoot, ".mcp.json"), scope: "project" },
1120
+ { client: "vscode", path: join(projectRoot, ".vscode", "mcp.json"), scope: "project" },
1121
+ { client: "cursor", path: join(projectRoot, ".cursor", "mcp.json"), scope: "project" },
1122
+ { client: "claude-code", path: join(home, ".claude.json"), scope: "user" },
1123
+ { client: "cursor", path: join(home, ".cursor", "mcp.json"), scope: "user" },
1124
+ { client: "claude-desktop", path: claudeDesktopPath(), scope: "user" },
1125
+ { client: "windsurf", path: join(home, ".codeium", "windsurf", "mcp_config.json"), scope: "user" },
1126
+ { client: "copilot", path: join(copilotHome, "mcp-config.json"), scope: "user" }
1127
+ ];
1128
+ }
1129
+ function portablePath(absolute, projectRoot) {
1130
+ const fromProject = relative(projectRoot, absolute);
1131
+ if (!fromProject.startsWith("..") && !isAbsolute(fromProject)) return fromProject.split(sep).join("/");
1132
+ const fromHome = relative(homedir2(), absolute);
1133
+ if (!fromHome.startsWith("..") && !isAbsolute(fromHome)) return `~/${fromHome.split(sep).join("/")}`;
1134
+ return absolute.split(sep).join("/");
1135
+ }
1136
+ async function readJsonIfPresent(path) {
1137
+ let text;
1138
+ try {
1139
+ text = await readFile2(path, "utf8");
1140
+ } catch (error) {
1141
+ const code = error.code;
1142
+ if (code === "ENOENT" || code === "ENOTDIR") return { present: false };
1143
+ if (code === "EACCES") return { present: true, ok: false, reason: "permission denied" };
1144
+ throw error;
1145
+ }
1146
+ try {
1147
+ return { present: true, ok: true, value: JSON.parse(text) };
1148
+ } catch (error) {
1149
+ return { present: true, ok: false, reason: `not valid JSON: ${error.message}` };
1150
+ }
1151
+ }
1152
+ function anchorCwd(server2, projectRoot) {
1153
+ const { transport: transport2 } = server2;
1154
+ if (transport2.type !== "stdio" || transport2.cwd === void 0 || isAbsolute(transport2.cwd)) return server2;
1155
+ return { ...server2, transport: { ...transport2, cwd: resolve2(projectRoot, transport2.cwd) } };
1156
+ }
1157
+ function describeSearch(searched, filesRead) {
1158
+ const read = new Set(filesRead);
1159
+ const lines = searched.map((path) => ` ${(read.has(path) ? "read" : "absent").padEnd(6)} ${path}`);
1160
+ return lines.join("\n");
1161
+ }
1162
+ async function discoverServers(projectRoot, extraFiles = []) {
1163
+ const context = { workspaceFolder: projectRoot, env: process.env };
1164
+ const files = [
1165
+ ...extraFiles.map((path) => ({ client: "generic", path: resolve2(projectRoot, path) })),
1166
+ ...candidateConfigFiles(projectRoot)
1167
+ ];
1168
+ const byName2 = /* @__PURE__ */ new Map();
1169
+ const skipped = [];
1170
+ const filesRead = [];
1171
+ const shadowed = [];
1172
+ const problems = [];
1173
+ const requested = new Set(files.filter((file) => file.client === "generic").map((file) => file.path));
1174
+ for (const file of files) {
1175
+ const read = await readJsonIfPresent(file.path);
1176
+ if (!read.present) {
1177
+ if (requested.has(file.path)) {
1178
+ problems.push({ file: portablePath(file.path, projectRoot), reason: "no such file; it was named with --config" });
1149
1179
  }
1180
+ continue;
1150
1181
  }
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;
1182
+ if (!read.ok) {
1183
+ problems.push({ file: portablePath(file.path, projectRoot), reason: read.reason });
1184
+ continue;
1185
+ }
1186
+ const raw = read.value;
1187
+ filesRead.push(file.path);
1188
+ const source = { client: file.client, file: portablePath(file.path, projectRoot) };
1189
+ let mapKey = CLIENT_MAP_KEY[file.client];
1190
+ if (file.client === "generic") {
1191
+ mapKey = detectMapKey(raw);
1192
+ if (mapKey === void 0) {
1193
+ problems.push({ file: source.file, reason: "no `mcpServers` or `servers` object found; this does not look like an MCP client config" });
1194
+ continue;
1158
1195
  }
1159
1196
  }
1197
+ const parsed = file.client === "claude-code" && file.scope === "user" ? await parseClaudeJson(raw, projectRoot, source, context) : await parseServerMap(raw, mapKey, { ...source, scope: file.scope }, context);
1198
+ skipped.push(...parsed.skipped);
1199
+ for (const server2 of parsed.servers.map((entry) => anchorCwd(entry, projectRoot))) {
1200
+ const existing = byName2.get(server2.name);
1201
+ if (existing) {
1202
+ shadowed.push({ name: server2.name, keptFrom: existing.from, alsoIn: source.file });
1203
+ continue;
1204
+ }
1205
+ byName2.set(server2.name, { server: server2, from: source.file });
1206
+ }
1160
1207
  }
1161
- if (widened && !narrowed) return "widened";
1162
- if (narrowed && !widened) return "narrowed";
1163
- return "changed";
1208
+ return {
1209
+ servers: [...byName2.values()].map((entry) => entry.server).sort((a, b) => a.name.localeCompare(b.name)),
1210
+ skipped,
1211
+ filesRead,
1212
+ searched: files.map((file) => file.path),
1213
+ shadowed,
1214
+ problems
1215
+ };
1164
1216
  }
1165
1217
 
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
- );
1218
+ // src/lock/build.ts
1219
+ function byName(members) {
1220
+ return [...members].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1236
1221
  }
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);
1222
+ function lockIcons(icons) {
1223
+ if (!icons || icons.length === 0) return void 0;
1224
+ return icons.map((icon2) => ({
1225
+ src: icon2.src,
1226
+ mimeType: icon2.mimeType,
1227
+ sizes: icon2.sizes,
1228
+ theme: icon2.theme
1229
+ }));
1230
+ }
1231
+ function sealed(entry) {
1232
+ return { ...entry, digest: digest(toJson(entry)) };
1233
+ }
1234
+ function lockTransport(server2) {
1235
+ const { transport: transport2 } = server2;
1236
+ if (transport2.type === "stdio") {
1237
+ const command = transport2.asWritten?.command ?? transport2.command;
1238
+ const args = transport2.asWritten?.args ?? transport2.args;
1239
+ return {
1240
+ type: "stdio",
1241
+ command,
1242
+ args: args.length > 0 ? args : void 0,
1243
+ envKeys: Object.keys(transport2.env).length > 0 ? Object.keys(transport2.env).sort() : void 0,
1244
+ cwd: transport2.cwd
1245
+ };
1243
1246
  }
1244
- return [...moved].filter((server2) => !versioned.has(server2)).sort();
1247
+ const headerKeys = Object.keys(transport2.headers);
1248
+ return {
1249
+ type: transport2.type,
1250
+ url: sanitizeUrl(transport2.asWritten?.url ?? transport2.url),
1251
+ headerKeys: headerKeys.length > 0 ? headerKeys.sort() : void 0
1252
+ };
1245
1253
  }
1246
-
1247
- // ../core/src/diff/index.ts
1248
- function change(kind, server2, summary, extra) {
1249
- return { kind, severity: SEVERITY[kind], server: server2, summary, ...extra };
1254
+ function lockTool(tool2, ignoredMeta) {
1255
+ const annotations2 = tool2.annotations;
1256
+ const inputSchema = normalizeSchema(toJson(tool2.inputSchema));
1257
+ const headerParams = extractHeaderParams(inputSchema);
1258
+ return sealed({
1259
+ name: tool2.name,
1260
+ title: tool2.title,
1261
+ description: tool2.description,
1262
+ inputSchema,
1263
+ outputSchema: tool2.outputSchema ? normalizeSchema(toJson(tool2.outputSchema)) : void 0,
1264
+ annotations: annotations2 ? { ...annotations2 } : void 0,
1265
+ behavior: resolveBehavior(annotations2),
1266
+ headerParams: headerParams.length > 0 ? headerParams : void 0,
1267
+ icons: lockIcons(tool2.icons),
1268
+ meta: stripIgnoredMeta(toJson(tool2._meta), ignoredMeta)
1269
+ });
1250
1270
  }
1251
- function same(a, b) {
1252
- return stableKey(a ?? null) === stableKey(b ?? null);
1271
+ function lockResource(resource2, ignoredMeta) {
1272
+ return sealed({
1273
+ uri: resource2.uri,
1274
+ name: resource2.name,
1275
+ title: resource2.title,
1276
+ description: resource2.description,
1277
+ mimeType: resource2.mimeType,
1278
+ annotations: resource2.annotations ? toJson(resource2.annotations) : void 0,
1279
+ icons: lockIcons(resource2.icons),
1280
+ meta: stripIgnoredMeta(toJson(resource2._meta), ignoredMeta)
1281
+ });
1253
1282
  }
1254
- function indexBy(members, key) {
1255
- return new Map((members ?? []).map((member) => [key(member), member]));
1283
+ function lockResourceTemplate(template, ignoredMeta) {
1284
+ return sealed({
1285
+ uriTemplate: template.uriTemplate,
1286
+ name: template.name,
1287
+ title: template.title,
1288
+ description: template.description,
1289
+ mimeType: template.mimeType,
1290
+ annotations: template.annotations ? toJson(template.annotations) : void 0,
1291
+ icons: lockIcons(template.icons),
1292
+ meta: stripIgnoredMeta(toJson(template._meta), ignoredMeta)
1293
+ });
1256
1294
  }
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;
1295
+ function lockPrompt(prompt2, ignoredMeta) {
1296
+ return sealed({
1297
+ name: prompt2.name,
1298
+ title: prompt2.title,
1299
+ description: prompt2.description,
1300
+ arguments: prompt2.arguments && prompt2.arguments.length > 0 ? prompt2.arguments.map((argument) => ({
1301
+ name: argument.name,
1302
+ // The spec gives PromptArgument a `title` (it extends BaseMetadata); the SDK's type
1303
+ // has not caught up, so it is read off the wire rather than skipped.
1304
+ title: argument.title,
1305
+ description: argument.description,
1306
+ required: argument.required
1307
+ })) : void 0,
1308
+ icons: lockIcons(prompt2.icons),
1309
+ meta: stripIgnoredMeta(toJson(prompt2._meta), ignoredMeta)
1310
+ });
1311
+ }
1312
+ function buildLockedServer(server2, surface, policy) {
1313
+ const ignoredMeta = policy?.ignoreMetaPrefixes ?? [];
1314
+ const tools = byName(surface.tools).map((tool2) => lockTool(tool2, ignoredMeta));
1315
+ const resources = byName(surface.resources).map((resource2) => lockResource(resource2, ignoredMeta));
1316
+ const resourceTemplates = byName(surface.resourceTemplates).map((template) => lockResourceTemplate(template, ignoredMeta));
1317
+ const prompts = byName(surface.prompts).map((prompt2) => lockPrompt(prompt2, ignoredMeta));
1318
+ const entry = {
1319
+ source: server2.source,
1320
+ transport: lockTransport(server2),
1321
+ protocol: surface.protocol,
1322
+ serverInfo: surface.serverInfo,
1323
+ capabilities: surface.capabilities,
1324
+ instructions: surface.instructions,
1325
+ tools: tools.length > 0 ? tools : void 0,
1326
+ resources: resources.length > 0 ? resources : void 0,
1327
+ resourceTemplates: resourceTemplates.length > 0 ? resourceTemplates : void 0,
1328
+ prompts: prompts.length > 0 ? prompts : void 0
1329
+ };
1330
+ const covered = {
1331
+ transport: entry.transport,
1332
+ protocol: entry.protocol,
1333
+ serverInfo: entry.serverInfo,
1334
+ capabilities: entry.capabilities,
1335
+ instructions: entry.instructions,
1336
+ tools: tools.map((tool2) => tool2.digest),
1337
+ resources: resources.map((resource2) => resource2.digest),
1338
+ resourceTemplates: resourceTemplates.map((template) => template.digest),
1339
+ prompts: prompts.map((prompt2) => prompt2.digest)
1340
+ };
1341
+ return { kind: "mcp-server", ...entry, digest: digest(toJson(covered)) };
1342
+ }
1343
+
1344
+ // src/mcp/connect.ts
1345
+ import { Client, SSEClientTransport, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
1346
+ import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/client/stdio";
1347
+
1348
+ // src/mcp/oauth.ts
1349
+ import { spawn } from "child_process";
1350
+ import { createHash as createHash2, randomUUID } from "crypto";
1351
+ import { readFileSync } from "fs";
1352
+ import { mkdir, readFile as readFile3, rm, writeFile } from "fs/promises";
1353
+ import { homedir as homedir3, platform as platform2 } from "os";
1354
+ import { dirname, join as join2 } from "path";
1355
+ import { ClientCredentialsProvider, UnauthorizedError } from "@modelcontextprotocol/client";
1356
+
1357
+ // src/lib/version.ts
1358
+ var VERSION = "0.2.0";
1359
+ var USER_AGENT = `nulladrift/${VERSION}`;
1360
+
1361
+ // src/mcp/oauth.ts
1362
+ var DEFAULT_CALLBACK_PATH = "/callback";
1363
+ function authDir() {
1364
+ const base = process.env["XDG_CONFIG_HOME"] ?? join2(homedir3(), ".config");
1365
+ return join2(base, "nulladrift", "auth");
1366
+ }
1367
+ function credentialPath(url) {
1368
+ return join2(authDir(), `${createHash2("sha256").update(url).digest("hex").slice(0, 16)}.json`);
1369
+ }
1370
+ var InteractiveAuthRequiredError = class extends Error {
1371
+ constructor(serverName) {
1372
+ super(`authorization required. Run \`nulladrift login ${serverName}\` once, then re-run.`);
1373
+ this.serverName = serverName;
1374
+ this.name = "InteractiveAuthRequiredError";
1375
+ }
1376
+ serverName;
1377
+ };
1378
+ var FileTokenProvider = class {
1379
+ constructor(serverName, serverUrl, options = { interactive: false }) {
1380
+ this.serverName = serverName;
1381
+ this.serverUrl = serverUrl;
1382
+ this.options = options;
1383
+ }
1384
+ serverName;
1385
+ serverUrl;
1386
+ options;
1387
+ cache;
1388
+ /** One per login attempt, held in memory and checked against what comes back on the callback. */
1389
+ stateValue = createHash2("sha256").update(randomUUID()).digest("hex").slice(0, 32);
1390
+ get redirectUrl() {
1391
+ return this.options.redirectUrl;
1392
+ }
1393
+ state() {
1394
+ return this.stateValue;
1395
+ }
1396
+ get clientMetadata() {
1397
+ return {
1398
+ client_name: `nulladrift ${VERSION}`,
1399
+ // A command-line tool is a native client: it cannot keep a secret in a shipped binary.
1400
+ application_type: "native",
1401
+ redirect_uris: this.options.redirectUrl === void 0 ? [] : [this.options.redirectUrl],
1402
+ grant_types: ["authorization_code", "refresh_token"],
1403
+ response_types: ["code"],
1404
+ token_endpoint_auth_method: "none",
1405
+ ...this.options.scope === void 0 ? {} : { scope: this.options.scope }
1406
+ };
1407
+ }
1408
+ async read() {
1409
+ if (this.cache) return this.cache;
1410
+ try {
1411
+ this.cache = JSON.parse(await readFile3(credentialPath(this.serverUrl), "utf8"));
1412
+ } catch {
1413
+ this.cache = { serverUrl: this.serverUrl };
1263
1414
  }
1264
- names.push(key);
1415
+ return this.cache;
1265
1416
  }
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 })];
1417
+ async write(patch) {
1418
+ const next = { ...await this.read(), ...patch, serverUrl: this.serverUrl };
1419
+ this.cache = next;
1420
+ const path = credentialPath(this.serverUrl);
1421
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
1422
+ await writeFile(path, `${JSON.stringify(next, null, 2)}
1423
+ `, { encoding: "utf8", mode: 384 });
1424
+ }
1425
+ async clientInformation() {
1426
+ return (await this.read()).clientInformation;
1427
+ }
1428
+ async saveClientInformation(clientInformation) {
1429
+ await this.write({ clientInformation });
1430
+ }
1431
+ async tokens() {
1432
+ return (await this.read()).tokens;
1276
1433
  }
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 })];
1434
+ async saveTokens(tokens) {
1435
+ await this.write({ tokens });
1279
1436
  }
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
- );
1437
+ async saveCodeVerifier(codeVerifier) {
1438
+ await this.write({ codeVerifier });
1294
1439
  }
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 }));
1440
+ async codeVerifier() {
1441
+ const stored = (await this.read()).codeVerifier;
1442
+ if (stored === void 0) throw new Error("no PKCE verifier stored; start the login again");
1443
+ return stored;
1300
1444
  }
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 }));
1445
+ async saveAuthorizationServerUrl(authorizationServerUrl) {
1446
+ await this.write({ authorizationServerUrl });
1303
1447
  }
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
- );
1448
+ async authorizationServerUrl() {
1449
+ return (await this.read()).authorizationServerUrl;
1313
1450
  }
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
- );
1451
+ async saveResourceUrl(resourceUrl) {
1452
+ await this.write({ resourceUrl });
1318
1453
  }
1319
- if (changes.length === 0) {
1320
- changes.push(change("tool.changed", name, "tool definition changed (title, icons or _meta)", { ...at, before, after }));
1454
+ async resourceUrl() {
1455
+ return (await this.read()).resourceUrl;
1321
1456
  }
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;
1457
+ async saveDiscoveryState(discoveryState) {
1458
+ await this.write({ discoveryState });
1459
+ }
1460
+ async discoveryState() {
1461
+ return (await this.read()).discoveryState;
1462
+ }
1463
+ async invalidateCredentials(scope) {
1464
+ if (scope === "all") {
1465
+ this.cache = { serverUrl: this.serverUrl };
1466
+ await rm(credentialPath(this.serverUrl), { force: true });
1467
+ return;
1341
1468
  }
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 })]);
1469
+ const key = { client: "clientInformation", tokens: "tokens", verifier: "codeVerifier", discovery: "discoveryState" }[scope];
1470
+ await this.write({ [key]: void 0 });
1344
1471
  }
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 }));
1472
+ async redirectToAuthorization(authorizationUrl) {
1473
+ if (!this.options.interactive) throw new InteractiveAuthRequiredError(this.serverName);
1474
+ openInBrowser(authorizationUrl);
1475
+ process.stderr.write(`
1476
+ If a browser did not open, visit:
1477
+ ${authorizationUrl.toString()}
1478
+
1479
+ `);
1347
1480
  }
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 }));
1481
+ };
1482
+ function openInBrowser(url) {
1483
+ const command = platform2() === "darwin" ? "open" : platform2() === "win32" ? "cmd" : "xdg-open";
1484
+ const args = platform2() === "win32" ? ["/c", "start", "", url.toString()] : [url.toString()];
1485
+ try {
1486
+ spawn(command, args, { detached: true, stdio: "ignore" }).unref();
1487
+ } catch {
1355
1488
  }
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 }));
1489
+ }
1490
+ function hasStoredCredentials(url) {
1491
+ try {
1492
+ const stored = JSON.parse(readFileSync(credentialPath(url), "utf8"));
1493
+ return typeof stored.tokens?.access_token === "string" && stored.tokens.access_token.length > 0;
1494
+ } catch {
1495
+ return false;
1360
1496
  }
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
- );
1497
+ }
1498
+ function createAuthProvider(server2, options = {}) {
1499
+ if (server2.transport.type === "stdio") return void 0;
1500
+ const oauth = server2.transport.oauth;
1501
+ if (oauth?.clientId !== void 0 && oauth.clientSecret !== void 0) {
1502
+ return new ClientCredentialsProvider({
1503
+ clientId: oauth.clientId,
1504
+ clientSecret: oauth.clientSecret,
1505
+ clientName: `nulladrift ${VERSION}`,
1506
+ ...oauth.scope === void 0 ? {} : { scope: oauth.scope }
1507
+ });
1368
1508
  }
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
- );
1509
+ const interactive = options.interactive ?? false;
1510
+ if (!interactive && !hasStoredCredentials(server2.transport.url)) return void 0;
1511
+ return new FileTokenProvider(server2.name, server2.transport.url, {
1512
+ interactive,
1513
+ ...oauth?.scope === void 0 ? {} : { scope: oauth.scope }
1514
+ });
1515
+ }
1516
+
1517
+ // src/mcp/types.ts
1518
+ import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/client";
1519
+ var UnreachableServerError = class extends Error {
1520
+ constructor(serverName, message, cause) {
1521
+ super(message);
1522
+ this.serverName = serverName;
1523
+ this.cause = cause;
1524
+ this.name = "UnreachableServerError";
1376
1525
  }
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
- })
1408
- );
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
- })
1526
+ serverName;
1527
+ cause;
1528
+ };
1529
+ function authFailureKind(error) {
1530
+ if (!isAuthFailure(error)) return void 0;
1531
+ const text = `${error instanceof Error ? error.message : String(error)}`.toLowerCase();
1532
+ const cause = error instanceof UnreachableServerError && error.cause instanceof Error ? error.cause.message.toLowerCase() : "";
1533
+ const both = `${text} ${cause}`;
1534
+ const scoped = [error, error instanceof UnreachableServerError ? error.cause : void 0].some(
1535
+ (candidate) => candidate instanceof Error && candidate.name === "InsufficientScopeError"
1418
1536
  );
1419
- return changes;
1537
+ if (scoped || /\b403\b|forbidden|insufficient[_ ]scope/.test(both)) return "forbidden";
1538
+ return "auth";
1539
+ }
1540
+ function isAuthFailure(error) {
1541
+ if (error instanceof UnauthorizedError2) return true;
1542
+ if (error instanceof Error && error.name === "InteractiveAuthRequiredError") return true;
1543
+ if (error instanceof UnreachableServerError && error.cause instanceof Error && error.cause.name === "InteractiveAuthRequiredError") return true;
1544
+ const cause = error instanceof UnreachableServerError ? error.cause : void 0;
1545
+ if (cause instanceof UnauthorizedError2) return true;
1546
+ for (const candidate of [error, error instanceof UnreachableServerError ? error.cause : void 0]) {
1547
+ const name = candidate instanceof Error ? candidate.name : "";
1548
+ if (name === "RegistrationRejectedError" || name === "InsufficientScopeError" || name === "OAuthClientFlowError") return true;
1549
+ }
1550
+ const outer = `${error instanceof Error ? error.message : String(error)}`;
1551
+ const inner = error instanceof UnreachableServerError && error.cause instanceof Error ? error.cause.message : "";
1552
+ const text = `${outer} ${inner}`.toLowerCase();
1553
+ return /\b(401|403)\b|unauthorized|forbidden|invalid or missing.*token|authentication required|invalid_client|dynamic client registration/.test(text);
1554
+ }
1555
+
1556
+ // src/mcp/connect.ts
1557
+ var DEFAULT_TIMEOUT_MS = 3e4;
1558
+ var STDERR_KEEP_BYTES = 2e3;
1559
+ function buildTransport(server2, captureStderr = () => {
1560
+ }, options = {}) {
1561
+ const { transport: transport2 } = server2;
1562
+ if (transport2.type === "stdio") {
1563
+ const child = new StdioClientTransport({
1564
+ command: transport2.command,
1565
+ args: transport2.args,
1566
+ // The server's own environment plus whatever the config sets. Never the auditor's full env.
1567
+ env: { ...getDefaultEnvironment(), ...transport2.env },
1568
+ cwd: transport2.cwd,
1569
+ // Piped rather than inherited: a chatty server must not interleave with our report, but its
1570
+ // last words are the most useful thing we can show when it fails to answer.
1571
+ stderr: "pipe"
1572
+ });
1573
+ child.stderr?.on("data", (chunk) => captureStderr(chunk.toString("utf8")));
1574
+ return child;
1575
+ }
1576
+ const headers = { ...transport2.headers, "user-agent": `nulladrift/${VERSION}` };
1577
+ const url = new URL(transport2.url);
1578
+ const authProvider = createAuthProvider(server2, options);
1579
+ if (transport2.type === "sse") return new SSEClientTransport(url, { requestInit: { headers }, authProvider });
1580
+ return new StreamableHTTPClientTransport(url, { requestInit: { headers }, authProvider });
1420
1581
  }
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);
1582
+ function diagnosticLines(stderr, limit = 3) {
1583
+ 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));
1584
+ const named = lines.filter((line) => /\b(error|exception|cannot|failed|refused|denied|not found|enoent|eacces)\b/i.test(line));
1585
+ const chosen = named.length > 0 ? named : lines;
1586
+ return chosen.slice(0, limit).map((line) => line.trim());
1587
+ }
1588
+ async function connect(server2, timeoutMs = DEFAULT_TIMEOUT_MS, options = {}) {
1589
+ let stderrBuffer = "";
1590
+ const captureStderr = (chunk) => {
1591
+ stderrBuffer = (stderrBuffer + chunk).slice(-STDERR_KEEP_BYTES);
1592
+ };
1593
+ const client = new Client(
1594
+ { name: "nulladrift", title: "nulladrift", version: VERSION },
1595
+ {
1596
+ /*
1597
+ * We advertise nothing. An auditor never calls a tool, so it has no business offering
1598
+ * elicitation, sampling or roots -- a server that asks for them gets nothing to work with.
1599
+ */
1600
+ capabilities: {},
1601
+ versionNegotiation: { mode: "auto", probe: { timeoutMs } }
1602
+ }
1603
+ );
1604
+ let transport2;
1605
+ try {
1606
+ transport2 = buildTransport(server2, captureStderr, options);
1607
+ } catch (error) {
1608
+ throw new UnreachableServerError(server2.name, `could not prepare transport: ${error.message}`, error);
1609
+ }
1610
+ try {
1611
+ await client.connect(transport2, { timeout: timeoutMs });
1612
+ } catch (error) {
1613
+ await client.close().catch(() => {
1431
1614
  });
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 }));
1615
+ const detail = stderrBuffer.trim();
1616
+ throw new UnreachableServerError(
1617
+ server2.name,
1618
+ `${error.message}${detail ? `
1619
+ server stderr: ${diagnosticLines(detail).join("\n ")}` : ""}`,
1620
+ error
1621
+ );
1437
1622
  }
1438
- return { changes, renamed };
1623
+ return {
1624
+ client,
1625
+ stderr: () => stderrBuffer,
1626
+ close: async () => {
1627
+ await client.close().catch(() => {
1628
+ });
1629
+ }
1630
+ };
1439
1631
  }
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 }));
1632
+
1633
+ // src/mcp/capture.ts
1634
+ var FRESH = { cacheMode: "bypass" };
1635
+ function describeListFailure(error) {
1636
+ const message = error?.message ?? String(error);
1637
+ if (error instanceof RangeError || /maximum call stack|stack size exceeded|too much recursion/i.test(message)) {
1638
+ 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
1639
  }
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] }));
1640
+ return message;
1641
+ }
1642
+ async function listOrEmpty(label, serverName, fetchList) {
1643
+ try {
1644
+ return await fetchList();
1645
+ } catch (error) {
1646
+ throw new UnreachableServerError(serverName, `${label} failed: ${describeListFailure(error)}`, error);
1456
1647
  }
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));
1648
+ }
1649
+ function readProtocol(client) {
1650
+ const era = client.getProtocolEra() ?? "legacy";
1651
+ const version = client.getNegotiatedProtocolVersion() ?? "unknown";
1652
+ const discovered = client.getDiscoverResult();
1653
+ return {
1654
+ era,
1655
+ version,
1656
+ supportedVersions: discovered?.supportedVersions
1657
+ };
1658
+ }
1659
+ function readServerInfo(client) {
1660
+ const info = client.getServerVersion();
1661
+ if (!info) return void 0;
1662
+ return {
1663
+ name: info.name,
1664
+ title: info.title,
1665
+ version: info.version,
1666
+ description: info.description,
1667
+ websiteUrl: info.websiteUrl
1668
+ };
1669
+ }
1670
+ async function captureSurface(server2, timeoutMs = DEFAULT_TIMEOUT_MS) {
1671
+ const connection = await connect(server2, timeoutMs);
1672
+ const { client } = connection;
1673
+ try {
1674
+ const capabilities = client.getServerCapabilities();
1675
+ const [tools, resources, resourceTemplates, prompts] = await Promise.all([
1676
+ capabilities?.tools ? listOrEmpty("tools/list", server2.name, async () => (await client.listTools(void 0, FRESH)).tools) : [],
1677
+ capabilities?.resources ? listOrEmpty("resources/list", server2.name, async () => (await client.listResources(void 0, FRESH)).resources) : [],
1678
+ capabilities?.resources ? listOrEmpty("resources/templates/list", server2.name, async () => (await client.listResourceTemplates(void 0, FRESH)).resourceTemplates) : [],
1679
+ capabilities?.prompts ? listOrEmpty("prompts/list", server2.name, async () => (await client.listPrompts(void 0, FRESH)).prompts) : []
1680
+ ]);
1681
+ return {
1682
+ protocol: readProtocol(client),
1683
+ serverInfo: readServerInfo(client),
1684
+ capabilities: capabilities ? toJson(capabilities) : void 0,
1685
+ // Clients place this in the model's system prompt, so it is part of the capability surface.
1686
+ instructions: client.getInstructions(),
1687
+ tools,
1688
+ resources,
1689
+ resourceTemplates,
1690
+ prompts
1691
+ };
1692
+ } finally {
1693
+ await connection.close();
1462
1694
  }
1463
- return sortChanges(changes);
1464
1695
  }
1465
1696
 
1466
- // ../core/src/lock/reseal.ts
1467
- function sealMember(member) {
1468
- const { digest: _discarded, ...body } = member;
1469
- return { ...body, digest: digest(toJson(body)) };
1697
+ // src/audit.ts
1698
+ async function mapWithLimit(items, limit, worker) {
1699
+ const results = new Array(items.length);
1700
+ let next = 0;
1701
+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
1702
+ for (; ; ) {
1703
+ const index = next++;
1704
+ const item = items[index];
1705
+ if (index >= items.length || item === void 0) return;
1706
+ results[index] = await worker(item);
1707
+ }
1708
+ });
1709
+ await Promise.all(runners);
1710
+ return results;
1470
1711
  }
1471
- function reseal(entry) {
1472
- switch (entry.kind) {
1473
- case "mcp-server":
1474
- return resealMcpServer(entry);
1712
+ async function withDeadline(ms, name, run) {
1713
+ let timer;
1714
+ try {
1715
+ return await Promise.race([
1716
+ run(),
1717
+ new Promise((_resolve, reject) => {
1718
+ timer = setTimeout(() => reject(new UnreachableServerError(name, `did not finish within ${ms}ms`)), ms);
1719
+ timer.unref?.();
1720
+ })
1721
+ ]);
1722
+ } finally {
1723
+ if (timer) clearTimeout(timer);
1475
1724
  }
1476
1725
  }
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
- };
1726
+ async function captureAll(options) {
1727
+ const discovery = await discoverServers(options.projectRoot, options.configFiles);
1728
+ const captured = await mapWithLimit(discovery.servers, options.concurrency ?? 4, async (server2) => {
1729
+ try {
1730
+ const surface = await withDeadline(
1731
+ options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
1732
+ server2.name,
1733
+ () => captureSurface(server2, options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
1734
+ );
1735
+ options.onServerDone?.(server2.name, "captured");
1736
+ return { name: server2.name, entry: buildLockedServer(server2, surface, options.policy) };
1737
+ } catch (error) {
1738
+ options.onServerDone?.(server2.name, "failed");
1739
+ const reason = error instanceof UnreachableServerError ? error.message : error.message;
1740
+ const kind = authFailureKind(error) ?? "unreachable";
1741
+ return { name: server2.name, failure: { server: server2.name, reason, kind } };
1742
+ }
1743
+ });
1744
+ const subjects = {};
1745
+ const unreachable = [];
1746
+ for (const result of captured) {
1747
+ if ("entry" in result && result.entry) subjects[result.name] = result.entry;
1748
+ else if ("failure" in result && result.failure) unreachable.push(result.failure);
1749
+ }
1750
+ for (const skipped of discovery.skipped) {
1751
+ unreachable.push({ server: skipped.serverName, reason: skipped.message, kind: "unreachable" });
1752
+ }
1753
+ for (const problem of discovery.problems) {
1754
+ unreachable.push({ server: problem.file, reason: problem.reason, kind: "unreachable" });
1755
+ }
1493
1756
  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))
1757
+ lock: {
1758
+ lockfileVersion: LOCKFILE_VERSION,
1759
+ generatedBy: `nulladrift@${VERSION}`,
1760
+ policy: options.policy,
1761
+ subjects
1762
+ },
1763
+ unreachable,
1764
+ discovery
1500
1765
  };
1501
1766
  }
1502
1767
 
1503
1768
  // src/lock/io.ts
1504
- import { readFile as readFile4, writeFile as writeFile2 } from "fs/promises";
1769
+ import { lstat, readFile as readFile4, rename, rm as rm2, writeFile as writeFile2 } from "fs/promises";
1505
1770
 
1506
1771
  // src/lock/schema.ts
1507
1772
  import { z as z2 } from "zod";
@@ -1774,7 +2039,23 @@ async function readLockfile(path) {
1774
2039
  }
1775
2040
  async function writeLockfile(path, lock) {
1776
2041
  try {
1777
- await writeFile2(path, serializeLockfile(lock), "utf8");
2042
+ const link = await lstat(path).catch(() => void 0);
2043
+ if (link?.isSymbolicLink()) {
2044
+ 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.`);
2045
+ }
2046
+ } catch (error) {
2047
+ if (error instanceof LockfileError) throw error;
2048
+ }
2049
+ try {
2050
+ const temporary = `${path}.${process.pid}.tmp`;
2051
+ await writeFile2(temporary, serializeLockfile(lock), "utf8");
2052
+ try {
2053
+ await rename(temporary, path);
2054
+ } catch (error) {
2055
+ await rm2(temporary, { force: true }).catch(() => {
2056
+ });
2057
+ throw error;
2058
+ }
1778
2059
  } catch (error) {
1779
2060
  const code = error.code;
1780
2061
  if (code === "ENOENT") throw new LockfileError(`cannot write ${path}: the directory does not exist. Note that --lock is resolved against --cwd.`);
@@ -1813,11 +2094,33 @@ function renderChange(change2) {
1813
2094
  }
1814
2095
  return lines;
1815
2096
  }
2097
+ function renderSteering(report) {
2098
+ const found = report.steering ?? [];
2099
+ if (found.length === 0) return [];
2100
+ const total = found.reduce((sum, server2) => sum + server2.signals.length, 0);
2101
+ const lines = [
2102
+ yellow(`${total} new passage(s) in ${found.length} server(s) read as instructions to the model:`),
2103
+ ""
2104
+ ];
2105
+ for (const { server: server2, signals } of found) {
2106
+ lines.push(` ${bold(server2)}`);
2107
+ const byField = /* @__PURE__ */ new Map();
2108
+ for (const signal of signals) byField.set(signal.field, [...byField.get(signal.field) ?? [], signal.quote]);
2109
+ const fields = [...byField];
2110
+ for (const [field, quotes] of fields.slice(0, 4)) {
2111
+ const more = quotes.length > 1 ? ` (+${quotes.length - 1} more here)` : "";
2112
+ lines.push(` ${dim(`${elideMiddle(field, 52)}: ${truncate(quotes[0] ?? "", 72)}${more}`)}`);
2113
+ }
2114
+ if (fields.length > 4) lines.push(` ${dim(`+${fields.length - 4} more field(s)`)}`);
2115
+ }
2116
+ 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.'), "");
2117
+ return lines;
2118
+ }
1816
2119
  function renderHumanReport(report) {
1817
2120
  const lines = [];
1818
2121
  if (report.changes.length > 0) {
1819
2122
  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):`;
2123
+ const heading = drifted > report.serversChecked ? `Drift in ${drifted} server(s); ${report.serversChecked} still configured:` : `Drift in ${drifted} of ${report.serversChecked} server(s):`;
1821
2124
  lines.push("", bold(heading), "");
1822
2125
  for (const change2 of report.changes) lines.push(...renderChange(change2), "");
1823
2126
  const quiet = serversThatShippedNothing(report.changes);
@@ -1836,6 +2139,7 @@ function renderHumanReport(report) {
1836
2139
  lines.push(` ${label} ${bold(failure.server)}`, ` ${failure.reason}`, "");
1837
2140
  }
1838
2141
  }
2142
+ lines.push(...renderSteering(report));
1839
2143
  if (report.changes.length === 0 && report.unreachable.length === 0) {
1840
2144
  lines.push(green(`\u2713 ${report.serversChecked} server(s) match ${report.lockPath}`));
1841
2145
  return `${lines.join("\n")}
@@ -1881,7 +2185,12 @@ function renderJsonReport(report, exitCode) {
1881
2185
  summary: {
1882
2186
  drifted: new Set(report.changes.map((change2) => change2.server)).size,
1883
2187
  changes: report.changes.length,
1884
- unreachable: report.unreachable.length
2188
+ unreachable: report.unreachable.length,
2189
+ /*
2190
+ * Counted separately from `changes` because it is not part of the verdict. A consumer
2191
+ * that gates on this field is gating on a regex, which is the thing this must never be.
2192
+ */
2193
+ steering: (report.steering ?? []).reduce((sum, server2) => sum + server2.signals.length, 0)
1885
2194
  },
1886
2195
  changes: report.changes.map((change2) => ({
1887
2196
  kind: change2.kind,
@@ -1892,7 +2201,9 @@ function renderJsonReport(report, exitCode) {
1892
2201
  before: change2.before,
1893
2202
  after: change2.after
1894
2203
  })),
1895
- unreachable: report.unreachable
2204
+ unreachable: report.unreachable,
2205
+ /** Text that began addressing the model since the lock was approved. Reported, never gated. */
2206
+ steering: report.steering ?? []
1896
2207
  },
1897
2208
  null,
1898
2209
  2
@@ -2022,6 +2333,26 @@ function renderMarkdownReport(report, options = {}) {
2022
2333
  );
2023
2334
  }
2024
2335
  }
2336
+ const steering = report.steering ?? [];
2337
+ if (steering.length > 0) {
2338
+ const total = steering.reduce((sum, server2) => sum + server2.signals.length, 0);
2339
+ lines.push(
2340
+ `<details><summary>${total} new passage${total === 1 ? "" : "s"} read as instructions to the model</summary>`,
2341
+ "",
2342
+ "Text a model is shown, which began addressing it since this lock was approved. A server",
2343
+ 'documenting "before using this tool, call authenticate first" has the same shape as an',
2344
+ "attack, so this is something to read rather than a verdict. It did not affect the result.",
2345
+ "",
2346
+ "| Server | Field | Passage |",
2347
+ "| --- | --- | --- |",
2348
+ ...steering.flatMap(
2349
+ ({ server: server2, signals }) => signals.slice(0, 10).map((signal) => `| \`${cell(server2)}\` | \`${cell(signal.field)}\` | ${cell(signal.quote)} |`)
2350
+ ),
2351
+ "",
2352
+ "</details>",
2353
+ ""
2354
+ );
2355
+ }
2025
2356
  if (report.unreachable.length > 0) {
2026
2357
  lines.push(
2027
2358
  `<details><summary>${report.unreachable.length} server${report.unreachable.length === 1 ? "" : "s"} could not be read</summary>`,
@@ -2085,7 +2416,7 @@ ${body}`;
2085
2416
 
2086
2417
  // src/telemetry/index.ts
2087
2418
  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";
2419
+ import { mkdir as mkdir2, readFile as readFile5, rm as rm3, writeFile as writeFile3 } from "fs/promises";
2089
2420
  import { homedir as homedir4 } from "os";
2090
2421
  import { dirname as dirname2, join as join3 } from "path";
2091
2422
  var PAYLOAD_SCHEMA = 2;
@@ -2120,7 +2451,7 @@ async function writePreference(enabled2) {
2120
2451
  await writeConfig({ telemetry: enabled2 });
2121
2452
  }
2122
2453
  async function clearPreference() {
2123
- await rm2(configPath(), { force: true });
2454
+ await rm3(configPath(), { force: true });
2124
2455
  }
2125
2456
  async function resolveInstallId(now = Date.now()) {
2126
2457
  const config = await readConfig();
@@ -2193,6 +2524,12 @@ async function buildReport(options) {
2193
2524
  const allowUnreachable = options.allowUnreachable || committed.policy?.allowUnreachable === true;
2194
2525
  const report = {
2195
2526
  changes,
2527
+ /*
2528
+ * Reported, never gated. The exit code below is computed from drift and unreachable servers
2529
+ * exactly as before: a pattern that fires on "before using this tool, call authenticate
2530
+ * first" must not be able to fail somebody's build.
2531
+ */
2532
+ steering: newSteering(committed, result.lock),
2196
2533
  unreachable: result.unreachable,
2197
2534
  serversChecked: Object.keys(result.lock.subjects).length,
2198
2535
  lockPath: options.lockPath,
@@ -2242,7 +2579,7 @@ async function comment(report) {
2242
2579
  }
2243
2580
 
2244
2581
  // src/commands/init.ts
2245
- import { access } from "fs/promises";
2582
+ import { lstat as lstat2 } from "fs/promises";
2246
2583
 
2247
2584
  // src/commands/telemetry.ts
2248
2585
  import { createInterface } from "readline/promises";
@@ -2337,7 +2674,7 @@ ${dim(" No collector is configured in this build, so nothing will be sent until
2337
2674
  // src/commands/init.ts
2338
2675
  async function exists(path) {
2339
2676
  try {
2340
- await access(path);
2677
+ await lstat2(path);
2341
2678
  return true;
2342
2679
  } catch {
2343
2680
  return false;
@@ -2391,6 +2728,33 @@ async function runInit(options) {
2391
2728
  lines.push(` ${green("\u2713")} ${bold(name)} ${dim(counts)}`);
2392
2729
  const deprecated = entry?.transport.type === "sse" ? " \xB7 HTTP+SSE transport is deprecated in the spec" : "";
2393
2730
  lines.push(` ${dim(`${entry?.protocol.era}/${entry?.protocol.version} \xB7 from ${entry?.source.file}${deprecated}`)}`);
2731
+ const tools = entry?.tools ?? [];
2732
+ const capabilities = surfaceCapabilities(tools);
2733
+ if (capabilities.length > 0) {
2734
+ const worst = capabilities.filter((capability) => capability.severity === "critical" || capability.severity === "high");
2735
+ const paint = worst.length > 0 ? yellow : dim;
2736
+ lines.push(` ${paint(`can: ${capabilities.map((capability) => capability.kind).join(", ")}`)}`);
2737
+ for (const capability of worst) {
2738
+ lines.push(` ${dim(`${capability.kind} \xB7 ${capability.tools.slice(0, 3).join(", ")}${capability.tools.length > 3 ? ` +${capability.tools.length - 3}` : ""}`)}`);
2739
+ }
2740
+ }
2741
+ const steering = (entry ? surfaceText(entry) : []).flatMap(
2742
+ (piece) => steeringSignals(piece.text, piece.field)
2743
+ );
2744
+ if (steering.length > 0) {
2745
+ const byField = /* @__PURE__ */ new Map();
2746
+ for (const signal of steering) byField.set(signal.field, [...byField.get(signal.field) ?? [], signal.quote]);
2747
+ const fields = [...byField];
2748
+ lines.push(
2749
+ ` ${yellow(`${fields.length} field(s) carry text read as instructions to the model, not documentation:`)}`
2750
+ );
2751
+ for (const [field, quotes] of fields.slice(0, 4)) {
2752
+ const more = quotes.length > 1 ? dim(` (+${quotes.length - 1} more here)`) : "";
2753
+ lines.push(` ${dim(`${elideMiddle(field, 52)}: ${truncate(quotes[0] ?? "", 72)}`)}${more}`);
2754
+ }
2755
+ if (fields.length > 4) lines.push(` ${dim(`+${fields.length - 4} more field(s)`)}`);
2756
+ lines.push(` ${dim("A signal to read, not a verdict. It never fails a build.")}`);
2757
+ }
2394
2758
  }
2395
2759
  for (const failure of result.unreachable) {
2396
2760
  lines.push(` ${red("\u2717")} ${bold(failure.server)} ${dim("not pinned")}`, ` ${failure.reason}`);
@@ -2412,7 +2776,7 @@ async function runInit(options) {
2412
2776
  // src/commands/login.ts
2413
2777
  import { createServer } from "http";
2414
2778
  import { auth } from "@modelcontextprotocol/client";
2415
- import { rm as rm3 } from "fs/promises";
2779
+ import { rm as rm4 } from "fs/promises";
2416
2780
  var CALLBACK_TIMEOUT_MS = 5 * 60 * 1e3;
2417
2781
  async function awaitCallback(expectedState) {
2418
2782
  let settle;
@@ -2529,7 +2893,7 @@ async function runLogout(options) {
2529
2893
  return EXIT_INCOMPLETE;
2530
2894
  }
2531
2895
  const url = found.transport.type === "stdio" ? "" : found.transport.url;
2532
- await rm3(credentialPath(url), { force: true });
2896
+ await rm4(credentialPath(url), { force: true });
2533
2897
  process.stdout.write(`${dim(`stored credentials for ${found.name} deleted`)}
2534
2898
  `);
2535
2899
  return EXIT_CLEAN;