hmcp-gateway 0.0.2 → 0.1.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.
Files changed (102) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +41 -9
  3. package/bin/hmcp-gateway.js +20 -0
  4. package/catalog/atlassian.yaml +41 -0
  5. package/catalog/brave-search.yaml +57 -0
  6. package/catalog/context7.yaml +42 -0
  7. package/catalog/fetch.yaml +37 -0
  8. package/catalog/figma.yaml +48 -0
  9. package/catalog/filesystem.yaml +48 -0
  10. package/catalog/git.yaml +48 -0
  11. package/catalog/github.yaml +103 -0
  12. package/catalog/huggingface.yaml +59 -0
  13. package/catalog/linear.yaml +47 -0
  14. package/catalog/memory.yaml +47 -0
  15. package/catalog/notion.yaml +41 -0
  16. package/catalog/playwright.yaml +38 -0
  17. package/catalog/postgres.yaml +66 -0
  18. package/catalog/sentry.yaml +39 -0
  19. package/catalog/sequential-thinking.yaml +29 -0
  20. package/catalog/stripe.yaml +41 -0
  21. package/catalog/supabase.yaml +45 -0
  22. package/catalog/time.yaml +49 -0
  23. package/dist/adopt-cli.d.ts +351 -0
  24. package/dist/adopt-cli.js +1857 -0
  25. package/dist/adopt-emit.d.ts +64 -0
  26. package/dist/adopt-emit.js +248 -0
  27. package/dist/adopt-plan.d.ts +108 -0
  28. package/dist/adopt-plan.js +386 -0
  29. package/dist/catalog.d.ts +140 -0
  30. package/dist/catalog.js +250 -0
  31. package/dist/classify.d.ts +23 -0
  32. package/dist/classify.js +47 -0
  33. package/dist/cli.d.ts +2 -0
  34. package/dist/cli.js +535 -0
  35. package/dist/client-allow.d.ts +42 -0
  36. package/dist/client-allow.js +95 -0
  37. package/dist/client-config.d.ts +200 -0
  38. package/dist/client-config.js +784 -0
  39. package/dist/config-source.d.ts +106 -0
  40. package/dist/config-source.js +156 -0
  41. package/dist/config.d.ts +159 -0
  42. package/dist/config.js +330 -0
  43. package/dist/connect-client.d.ts +49 -0
  44. package/dist/connect-client.js +249 -0
  45. package/dist/contracts.d.ts +251 -0
  46. package/dist/contracts.js +9 -0
  47. package/dist/credential.d.ts +63 -0
  48. package/dist/credential.js +136 -0
  49. package/dist/draft.d.ts +71 -0
  50. package/dist/draft.js +596 -0
  51. package/dist/exposure-cli.d.ts +28 -0
  52. package/dist/exposure-cli.js +119 -0
  53. package/dist/gateway.d.ts +756 -0
  54. package/dist/gateway.js +2106 -0
  55. package/dist/index.d.ts +26 -0
  56. package/dist/index.js +26 -0
  57. package/dist/notify.d.ts +44 -0
  58. package/dist/notify.js +93 -0
  59. package/dist/oauth.d.ts +139 -0
  60. package/dist/oauth.js +641 -0
  61. package/dist/observe.d.ts +10 -0
  62. package/dist/observe.js +26 -0
  63. package/dist/open.d.ts +24 -0
  64. package/dist/open.js +31 -0
  65. package/dist/packs.d.ts +119 -0
  66. package/dist/packs.js +131 -0
  67. package/dist/pin-cli.d.ts +28 -0
  68. package/dist/pin-cli.js +103 -0
  69. package/dist/probe-upstream.d.ts +31 -0
  70. package/dist/probe-upstream.js +377 -0
  71. package/dist/registry-map.d.ts +39 -0
  72. package/dist/registry-map.js +390 -0
  73. package/dist/rule-cli.d.ts +51 -0
  74. package/dist/rule-cli.js +412 -0
  75. package/dist/serve-http.d.ts +67 -0
  76. package/dist/serve-http.js +478 -0
  77. package/dist/snippet.d.ts +20 -0
  78. package/dist/snippet.js +826 -0
  79. package/dist/status-cli.d.ts +61 -0
  80. package/dist/status-cli.js +195 -0
  81. package/dist/suggest-cli.d.ts +43 -0
  82. package/dist/suggest-cli.js +279 -0
  83. package/dist/toolname.d.ts +47 -0
  84. package/dist/toolname.js +149 -0
  85. package/dist/upstream-errors.d.ts +54 -0
  86. package/dist/upstream-errors.js +330 -0
  87. package/dist/upstream.d.ts +128 -0
  88. package/dist/upstream.js +413 -0
  89. package/dist/version.d.ts +10 -0
  90. package/dist/version.js +11 -0
  91. package/package.json +50 -6
  92. package/packs/brave-search.yaml +20 -0
  93. package/packs/context7.yaml +13 -0
  94. package/packs/fetch.yaml +14 -0
  95. package/packs/filesystem.yaml +79 -0
  96. package/packs/git.yaml +29 -0
  97. package/packs/github.yaml +47 -0
  98. package/packs/huggingface.yaml +16 -0
  99. package/packs/memory.yaml +23 -0
  100. package/packs/playwright.yaml +41 -0
  101. package/packs/sequential-thinking.yaml +13 -0
  102. package/packs/time.yaml +14 -0
@@ -0,0 +1,784 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { z } from "zod";
5
+ import { canonicalJson } from "hmcp-core";
6
+ /**
7
+ * Claude Code's own MCP server configuration: finding it, reading it, and
8
+ * putting it back.
9
+ *
10
+ * This is the one file in the gateway that touches a config another program
11
+ * owns, and that ownership drives two departures from how every other schema
12
+ * here is written.
13
+ *
14
+ * The schemas are loose rather than `.strict()`. The gateway's own config is
15
+ * strict because the gateway defines it, and an unknown key there is a typo
16
+ * worth refusing. This format belongs to Claude Code, which adds fields
17
+ * between releases; a strict parse would make `adopt` refuse a config that is
18
+ * perfectly good and merely newer than this build.
19
+ *
20
+ * And entries are validated one at a time rather than as a whole file, so a
21
+ * single malformed entry costs itself and not every sibling. That is the same
22
+ * reasoning as `dropUnknownKinds` in core's registry: a config shared between
23
+ * versions must not let one bad row hide the rest.
24
+ */
25
+ /** A server Claude Code starts as a child process. */
26
+ export const ClaudeStdioServerSchema = z.looseObject({
27
+ type: z.literal("stdio").optional(),
28
+ command: z.string().min(1),
29
+ args: z.array(z.string()).default([]),
30
+ env: z.record(z.string(), z.string()).default({})
31
+ });
32
+ /** A server Claude Code reaches over the network. */
33
+ export const ClaudeRemoteServerSchema = z.looseObject({
34
+ type: z.enum(["http", "sse"]),
35
+ url: z.string().min(1),
36
+ headers: z.record(z.string(), z.string()).default({})
37
+ });
38
+ export function isRemote(server) {
39
+ return server.type === "http" || server.type === "sse";
40
+ }
41
+ /**
42
+ * The transport a remote entry with no `type` means. Cursor and Windsurf
43
+ * write `{"url": ...}` (Windsurf: `serverUrl`) and decide by trying; the old
44
+ * SSE servers conventionally end their path in `/sse`, and everything else is
45
+ * streamable HTTP.
46
+ */
47
+ function remoteTypeFor(url) {
48
+ try {
49
+ return /\/sse\/?$/.test(new URL(url).pathname) ? "sse" : "http";
50
+ }
51
+ catch {
52
+ return "http";
53
+ }
54
+ }
55
+ export class ClientConfigError extends Error {
56
+ }
57
+ /**
58
+ * Claude Desktop's configuration file.
59
+ *
60
+ * Three different places, and the file is the application's own: it is only
61
+ * ever read, written back whole, and backed up first.
62
+ */
63
+ function claudeDesktopPath(home, platform) {
64
+ const file = "claude_desktop_config.json";
65
+ if (platform === "win32")
66
+ return join(home, "AppData", "Roaming", "Claude", file);
67
+ if (platform === "darwin")
68
+ return join(home, "Library", "Application Support", "Claude", file);
69
+ return join(home, ".config", "Claude", file);
70
+ }
71
+ /**
72
+ * VS Code's user-wide `mcp.json`, in the profile folder beside its
73
+ * `settings.json` -- which moves per platform the same way Claude Desktop's
74
+ * file does. (Insiders keeps its own under `Code - Insiders`; stable is the
75
+ * one most people have.)
76
+ */
77
+ function vscodeUserPath(home, platform) {
78
+ if (platform === "win32")
79
+ return join(home, "AppData", "Roaming", "Code", "User", "mcp.json");
80
+ if (platform === "darwin")
81
+ return join(home, "Library", "Application Support", "Code", "User", "mcp.json");
82
+ return join(home, ".config", "Code", "User", "mcp.json");
83
+ }
84
+ /**
85
+ * The three places Claude Code keeps MCP servers, in the order it resolves
86
+ * them.
87
+ *
88
+ * `local` is per-project state inside the user-wide file, which is why its
89
+ * entry is keyed by an absolute project path rather than living next to the
90
+ * project.
91
+ */
92
+ export function scopeTargets(options = {}) {
93
+ const cwd = resolve(options.cwd ?? process.cwd());
94
+ const home = options.home ?? homedir();
95
+ const platform = options.platform ?? process.platform;
96
+ const claudeJson = join(home, ".claude.json");
97
+ const code = "Claude Code";
98
+ return [
99
+ { scope: "project", path: join(cwd, ".mcp.json"), where: "mcpServers", key: "mcpServers", client: code },
100
+ {
101
+ scope: "local",
102
+ path: claudeJson,
103
+ where: `projects[${cwd}].mcpServers`,
104
+ key: "mcpServers",
105
+ client: code
106
+ },
107
+ { scope: "user", path: claudeJson, where: "mcpServers", key: "mcpServers", client: code },
108
+ {
109
+ scope: "claude-desktop",
110
+ path: claudeDesktopPath(home, platform),
111
+ where: "mcpServers",
112
+ key: "mcpServers",
113
+ client: "Claude Desktop"
114
+ },
115
+ {
116
+ scope: "cursor-project",
117
+ path: join(cwd, ".cursor", "mcp.json"),
118
+ where: "mcpServers",
119
+ key: "mcpServers",
120
+ client: "Cursor (this project)"
121
+ },
122
+ {
123
+ scope: "cursor-user",
124
+ path: join(home, ".cursor", "mcp.json"),
125
+ where: "mcpServers",
126
+ key: "mcpServers",
127
+ client: "Cursor (all projects)"
128
+ },
129
+ {
130
+ scope: "vscode-project",
131
+ path: join(cwd, ".vscode", "mcp.json"),
132
+ where: "servers",
133
+ key: "servers",
134
+ client: "VS Code (this project)"
135
+ },
136
+ {
137
+ scope: "vscode-user",
138
+ path: vscodeUserPath(home, platform),
139
+ where: "servers",
140
+ key: "servers",
141
+ client: "VS Code (all projects)"
142
+ },
143
+ {
144
+ // The same place on every platform (under %USERPROFILE% on Windows),
145
+ // and the same shape as Claude Desktop's file.
146
+ scope: "windsurf",
147
+ path: join(home, ".codeium", "windsurf", "mcp_config.json"),
148
+ where: "mcpServers",
149
+ key: "mcpServers",
150
+ client: "Windsurf"
151
+ }
152
+ ];
153
+ }
154
+ function targetFor(scope, options) {
155
+ const target = scopeTargets(options).find((t) => t.scope === scope);
156
+ if (!target)
157
+ throw new ClientConfigError(`unknown scope "${scope}"`);
158
+ return target;
159
+ }
160
+ function asRecord(value) {
161
+ return typeof value === "object" && value !== null && !Array.isArray(value)
162
+ ? value
163
+ : undefined;
164
+ }
165
+ /**
166
+ * Reads one scope.
167
+ *
168
+ * A missing file is an empty scope rather than an error, matching
169
+ * `readRegistry`: not having adopted anything yet is a state, not a fault.
170
+ */
171
+ export function readClientConfig(scope, options = {}) {
172
+ const target = targetFor(scope, options);
173
+ if (!existsSync(target.path)) {
174
+ return { target, text: null, jsonc: false, raw: {}, servers: {}, exists: false };
175
+ }
176
+ const text = readFileSync(target.path, "utf8");
177
+ let parsed;
178
+ let jsonc = false;
179
+ try {
180
+ parsed = JSON.parse(text);
181
+ }
182
+ catch {
183
+ try {
184
+ parsed = JSON.parse(stripJsonc(text));
185
+ jsonc = true;
186
+ }
187
+ catch (err) {
188
+ throw new ClientConfigError(`${target.client}'s settings file can't be read: it has a mistake in it, so nothing was changed. ` +
189
+ `Open ${target.path} in a text editor, fix it, and try again. (${err.message})`);
190
+ }
191
+ }
192
+ const raw = asRecord(parsed);
193
+ if (!raw) {
194
+ throw new ClientConfigError(`${target.client}'s settings file (${target.path}) doesn't hold the settings this expects, so nothing was changed.`);
195
+ }
196
+ return { target, text, jsonc, raw, servers: serversIn(raw, target), exists: true };
197
+ }
198
+ /**
199
+ * JSON with comments, as VS Code reads its `mcp.json`: `//` and block
200
+ * comments and trailing commas removed, everything inside strings left alone.
201
+ * Every removed character becomes a space (newlines kept), so positions and
202
+ * line numbers in an error still point at the person's own file.
203
+ */
204
+ export function stripJsonc(text) {
205
+ const out = text.split("");
206
+ let i = 0;
207
+ const blank = (from, to) => {
208
+ for (let k = from; k < to; k++)
209
+ if (out[k] !== "\n" && out[k] !== "\r")
210
+ out[k] = " ";
211
+ };
212
+ while (i < text.length) {
213
+ const c = text[i];
214
+ if (c === '"') {
215
+ i++;
216
+ while (i < text.length && text[i] !== '"')
217
+ i += text[i] === "\\" ? 2 : 1;
218
+ i++;
219
+ }
220
+ else if (c === "/" && text[i + 1] === "/") {
221
+ const end = text.indexOf("\n", i);
222
+ const stop = end === -1 ? text.length : end;
223
+ blank(i, stop);
224
+ i = stop;
225
+ }
226
+ else if (c === "/" && text[i + 1] === "*") {
227
+ const end = text.indexOf("*/", i + 2);
228
+ const stop = end === -1 ? text.length : end + 2;
229
+ blank(i, stop);
230
+ i = stop;
231
+ }
232
+ else {
233
+ i++;
234
+ }
235
+ }
236
+ // Trailing commas: a comma followed only by whitespace before } or ].
237
+ const joined = out.join("");
238
+ const result = joined.split("");
239
+ let inString = false;
240
+ for (let k = 0; k < joined.length; k++) {
241
+ const c = joined[k];
242
+ if (inString) {
243
+ if (c === "\\")
244
+ k++;
245
+ else if (c === '"')
246
+ inString = false;
247
+ continue;
248
+ }
249
+ if (c === '"')
250
+ inString = true;
251
+ else if (c === ",") {
252
+ let j = k + 1;
253
+ while (j < joined.length && /\s/.test(joined[j]))
254
+ j++;
255
+ if (joined[j] === "}" || joined[j] === "]")
256
+ result[k] = " ";
257
+ }
258
+ }
259
+ return result.join("");
260
+ }
261
+ /**
262
+ * Where the value of a top-level key sits in JSONC text: `[start, end)`, or
263
+ * undefined when the key is not at the top level. Strings and comments are
264
+ * stepped over, so a key's name inside a comment or a value is not found.
265
+ */
266
+ function topLevelValueSpan(text, key) {
267
+ const clean = stripJsonc(text);
268
+ let depth = 0;
269
+ let i = 0;
270
+ let expectKey = false;
271
+ while (i < clean.length) {
272
+ const c = clean[i];
273
+ if (c === '"') {
274
+ const start = i;
275
+ i++;
276
+ while (i < clean.length && clean[i] !== '"')
277
+ i += clean[i] === "\\" ? 2 : 1;
278
+ i++;
279
+ if (depth === 1 && expectKey) {
280
+ const name = JSON.parse(clean.slice(start, i));
281
+ let j = i;
282
+ while (/\s/.test(clean[j] ?? ""))
283
+ j++;
284
+ if (clean[j] === ":") {
285
+ j++;
286
+ while (/\s/.test(clean[j] ?? ""))
287
+ j++;
288
+ if (name === key)
289
+ return [j, valueEnd(clean, j)];
290
+ i = valueEnd(clean, j);
291
+ expectKey = false;
292
+ continue;
293
+ }
294
+ }
295
+ continue;
296
+ }
297
+ if (c === "{" || c === "[") {
298
+ depth++;
299
+ if (depth === 1)
300
+ expectKey = true;
301
+ }
302
+ else if (c === "}" || c === "]")
303
+ depth--;
304
+ else if (c === "," && depth === 1)
305
+ expectKey = true;
306
+ i++;
307
+ }
308
+ return undefined;
309
+ }
310
+ /** Where the JSON value starting at `from` ends, in comment-free text. */
311
+ function valueEnd(clean, from) {
312
+ let i = from;
313
+ let depth = 0;
314
+ while (i < clean.length) {
315
+ const c = clean[i];
316
+ if (c === '"') {
317
+ i++;
318
+ while (i < clean.length && clean[i] !== '"')
319
+ i += clean[i] === "\\" ? 2 : 1;
320
+ i++;
321
+ if (depth === 0)
322
+ return i;
323
+ continue;
324
+ }
325
+ if (c === "{" || c === "[")
326
+ depth++;
327
+ else if (c === "}" || c === "]") {
328
+ depth--;
329
+ if (depth === 0)
330
+ return i + 1;
331
+ if (depth < 0)
332
+ return i;
333
+ }
334
+ else if (depth === 0 && (c === "," || /\s/.test(c)))
335
+ return i;
336
+ i++;
337
+ }
338
+ return i;
339
+ }
340
+ /** The indent a file uses (two spaces, four, a tab), so a rewrite looks like the file it replaces. */
341
+ function detectIndent(text) {
342
+ if (!text)
343
+ return 2;
344
+ const lead = /\n([ \t]+)\S/.exec(text)?.[1];
345
+ if (!lead)
346
+ return 2;
347
+ return lead.startsWith("\t") ? "\t" : lead.length;
348
+ }
349
+ /**
350
+ * Whether the file reads the same as `value`: same keys and values, whatever
351
+ * the spacing. Used to decide that an undo may put the original bytes back.
352
+ */
353
+ export function sameJson(a, b) {
354
+ return canonicalJson(a) === canonicalJson(b);
355
+ }
356
+ /** The `mcpServers` object this scope reads, or an empty one. */
357
+ function serversIn(raw, target) {
358
+ if (target.scope !== "local")
359
+ return asRecord(raw[target.key]) ?? {};
360
+ const projects = asRecord(raw["projects"]) ?? {};
361
+ const key = projectKey(target);
362
+ return asRecord(asRecord(projects[key])?.["mcpServers"]) ?? {};
363
+ }
364
+ /** `projects[<abs cwd>]`, recovered from the target's own `where`. */
365
+ function projectKey(target) {
366
+ const match = /^projects\[(.*)\]\.mcpServers$/.exec(target.where);
367
+ if (!match)
368
+ throw new ClientConfigError(`cannot read a project key out of "${target.where}"`);
369
+ return match[1];
370
+ }
371
+ /**
372
+ * Validates each entry on its own.
373
+ *
374
+ * An entry carrying `type: "http"` or `"sse"` is held to the remote shape
375
+ * rather than being offered to both: a remote entry missing its `url` should
376
+ * report that, not the stdio schema's complaint about a missing `command`.
377
+ */
378
+ export function parseServers(raw) {
379
+ const servers = new Map();
380
+ const malformed = [];
381
+ for (const name of Object.keys(raw).sort()) {
382
+ const entry = asRecord(raw[name]);
383
+ if (!entry) {
384
+ malformed.push({ name, message: "the entry is not a JSON object" });
385
+ continue;
386
+ }
387
+ let type = entry["type"];
388
+ let candidate = entry;
389
+ /*
390
+ * Cursor's and Windsurf's remote shape: a `url` (Windsurf: `serverUrl`)
391
+ * and no `type`, no `command`. Read as the remote server it is rather
392
+ * than as a stdio server missing its command.
393
+ */
394
+ const url = typeof entry["url"] === "string" ? entry["url"] : typeof entry["serverUrl"] === "string" ? entry["serverUrl"] : undefined;
395
+ if (type === undefined && entry["command"] === undefined && url !== undefined) {
396
+ type = remoteTypeFor(url);
397
+ candidate = { ...entry, type, url };
398
+ }
399
+ const schema = type === "http" || type === "sse" || type === "streamable-http"
400
+ ? ClaudeRemoteServerSchema
401
+ : type === undefined || type === "stdio"
402
+ ? ClaudeStdioServerSchema
403
+ : undefined;
404
+ if (type === "streamable-http")
405
+ candidate = { ...candidate, type: "http" };
406
+ if (!schema) {
407
+ malformed.push({
408
+ name,
409
+ message: `it says it connects in a way this doesn't know (${JSON.stringify(type)}), so it was left as it is.`
410
+ });
411
+ continue;
412
+ }
413
+ const result = schema.safeParse(candidate);
414
+ if (!result.success) {
415
+ malformed.push({ name, message: plainEntryProblem(result.error.issues, schema === ClaudeRemoteServerSchema) });
416
+ continue;
417
+ }
418
+ servers.set(name, result.data);
419
+ }
420
+ return { servers, malformed };
421
+ }
422
+ /**
423
+ * Why an entry could not be read, in words a person can act on. The schema's
424
+ * own issue paths ("command: Invalid input: expected string") are kept in
425
+ * brackets for whoever wants them.
426
+ */
427
+ function plainEntryProblem(issues, remote) {
428
+ const fields = [...new Set(issues.map((i) => String(i.path[0] ?? "")))];
429
+ const technical = issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
430
+ let lead;
431
+ if (!remote && fields.includes("command"))
432
+ lead = "it has neither a program to start nor a web address";
433
+ else if (remote && fields.includes("url"))
434
+ lead = "it has no web address";
435
+ else if (fields.includes("args"))
436
+ lead = "the list of what to pass the program isn't a list of words";
437
+ else if (fields.includes("env"))
438
+ lead = "one of its settings (env) isn't plain text";
439
+ else if (fields.includes("headers"))
440
+ lead = "one of its headers isn't plain text";
441
+ else
442
+ lead = "part of it isn't in the shape this expects";
443
+ return `Its entry in the app's settings couldn't be read: ${lead}. It was left as it is. (${technical})`;
444
+ }
445
+ /**
446
+ * Which scope `adopt` should act on when nobody said.
447
+ *
448
+ * More than one populated scope refuses rather than merging. Which project
449
+ * sees which server is a semantic Claude Code owns, and collapsing three
450
+ * scopes into one gateway would change it -- a user-scope server would start
451
+ * being visible only in the project that happened to run `adopt`.
452
+ */
453
+ export function resolveScope(explicit, options = {}) {
454
+ if (explicit)
455
+ return targetFor(explicit, options);
456
+ const populated = scopeTargets(options)
457
+ .map((target) => ({ target, count: Object.keys(readClientConfig(target.scope, options).servers).length }))
458
+ .filter((s) => s.count > 0);
459
+ if (populated.length === 1)
460
+ return populated[0].target;
461
+ if (populated.length === 0) {
462
+ throw new ClientConfigError("found no MCP servers to adopt. Looked in:\n" +
463
+ scopeTargets(options)
464
+ .map((t) => ` ${t.scope.padEnd(15)} ${t.client}: ${t.path} (${t.where})`)
465
+ .join("\n"));
466
+ }
467
+ /*
468
+ * More than one place has servers, which is now the ordinary case: someone
469
+ * with both Claude Code and Cursor has two. Which client sees which server
470
+ * is the client's business, and adopting all of them would put one
471
+ * gateway's entry into configs the person may not have meant to touch.
472
+ */
473
+ throw new ClientConfigError("more than one place has MCP servers, and which client sees which server is that client's to " +
474
+ "decide, not this command's. Pass --scope to say which one to adopt:\n" +
475
+ populated
476
+ .map((s) => ` --scope ${s.target.scope.padEnd(15)} ${s.count} server(s) in ${s.target.path} (${s.target.client})`)
477
+ .join("\n"));
478
+ }
479
+ /** The whole file as it will be with `servers` in this scope. */
480
+ function withServers(file, servers) {
481
+ const raw = structuredClone(file.raw);
482
+ if (file.target.scope === "local") {
483
+ const projects = asRecord(raw["projects"]) ?? {};
484
+ const key = projectKey(file.target);
485
+ const project = asRecord(projects[key]) ?? {};
486
+ raw["projects"] = { ...projects, [key]: { ...project, mcpServers: servers } };
487
+ }
488
+ else {
489
+ raw[file.target.key] = servers;
490
+ }
491
+ return raw;
492
+ }
493
+ /**
494
+ * Writes `servers` back into the scope, leaving the rest of the file alone.
495
+ *
496
+ * The file keeps its own indent and its trailing newline (or lack of one).
497
+ * A file with comments (VS Code's JSONC) has only the server list's value
498
+ * replaced in its text, so every comment outside that list survives.
499
+ */
500
+ export function writeClientConfig(file, servers) {
501
+ const raw = withServers(file, servers);
502
+ const indent = detectIndent(file.text);
503
+ const newline = file.text === null || file.text.endsWith("\n") ? "\n" : "";
504
+ if (file.jsonc && file.text !== null && file.target.scope !== "local") {
505
+ writeTextPreservingMode(file.target.path, spliceTopLevel(file.text, file.target.key, servers, indent));
506
+ return;
507
+ }
508
+ writeTextPreservingMode(file.target.path, `${JSON.stringify(raw, null, indent)}${newline}`);
509
+ }
510
+ /** `text` with the top-level `key`'s value replaced by `value`, or the key added at the end. */
511
+ function spliceTopLevel(text, key, value, indent) {
512
+ const unit = typeof indent === "number" ? " ".repeat(indent) : indent;
513
+ const body = JSON.stringify(value, null, indent).replace(/\n/g, `\n${unit}`);
514
+ const span = topLevelValueSpan(text, key);
515
+ if (span)
516
+ return text.slice(0, span[0]) + body + text.slice(span[1]);
517
+ const clean = stripJsonc(text);
518
+ const close = clean.lastIndexOf("}");
519
+ const before = clean.slice(0, close).trimEnd();
520
+ const comma = before.endsWith("{") ? "" : ",";
521
+ // Insert right after the last real character, so a trailing comment stays where it was.
522
+ const at = before.length;
523
+ return `${text.slice(0, at)}${comma}\n${unit}${JSON.stringify(key)}: ${body}\n${text.slice(close)}`;
524
+ }
525
+ /**
526
+ * Undo's write: puts `servers` back, and when that leaves the file exactly as
527
+ * it was before (same keys and values), writes the original bytes from the
528
+ * whole-file copy and removes the copy, so a file under version control shows
529
+ * no diff. A file that did not exist before and is now an empty skeleton is
530
+ * removed. Anything else -- the person changed the file since -- is written
531
+ * with the file's own indent, and the copy stays.
532
+ */
533
+ export function restoreClientConfig(file, servers) {
534
+ const raw = withServers(file, servers);
535
+ const copy = wholeFileBackupPath(file.target);
536
+ if (existsSync(copy)) {
537
+ const original = readFileSync(copy, "utf8");
538
+ let parsed;
539
+ try {
540
+ parsed = JSON.parse(original);
541
+ }
542
+ catch {
543
+ try {
544
+ parsed = JSON.parse(stripJsonc(original));
545
+ }
546
+ catch {
547
+ parsed = undefined;
548
+ }
549
+ }
550
+ if (parsed !== undefined && sameJson(parsed, raw)) {
551
+ writeTextPreservingMode(file.target.path, original);
552
+ unlinkSync(copy);
553
+ return { how: "bytes", backupLeft: null };
554
+ }
555
+ writeClientConfig(file, servers);
556
+ return { how: "rewritten", backupLeft: copy };
557
+ }
558
+ if (isEmptySkeleton(raw, file.target)) {
559
+ if (existsSync(file.target.path))
560
+ unlinkSync(file.target.path);
561
+ return { how: "removed", backupLeft: null };
562
+ }
563
+ writeClientConfig(file, servers);
564
+ return { how: "rewritten", backupLeft: null };
565
+ }
566
+ /** `{"mcpServers": {}}`, or `{"projects": {"<dir>": {"mcpServers": {}}}}`: all a connect left behind. */
567
+ function isEmptySkeleton(raw, target) {
568
+ if (target.scope === "local") {
569
+ const projects = asRecord(raw["projects"]);
570
+ if (!projects || Object.keys(raw).length !== 1 || Object.keys(projects).length !== 1)
571
+ return false;
572
+ const project = asRecord(projects[projectKey(target)]);
573
+ return !!project && Object.keys(project).length === 1 && Object.keys(asRecord(project["mcpServers"]) ?? { x: 1 }).length === 0;
574
+ }
575
+ return Object.keys(raw).length === 1 && Object.keys(asRecord(raw[target.key]) ?? { x: 1 }).length === 0;
576
+ }
577
+ /**
578
+ * Atomic write through a temporary file, as `writeRegistry` does: a crash
579
+ * mid-write must not leave a half-written config that then fails to parse and
580
+ * takes every one of the user's MCP servers with it.
581
+ *
582
+ * The existing mode is preserved rather than assumed. `~/.claude.json` is
583
+ * `0600` on a normal install and holds an OAuth account; widening it while
584
+ * adding a server would be a quiet regression. A file we are creating gets
585
+ * `0600` outright. (Backups are written by `writePrivateText`, always 0600.)
586
+ */
587
+ function writeTextPreservingMode(path, text) {
588
+ const mode = existsSync(path) ? statSync(path).mode & 0o777 : 0o600;
589
+ mkdirSync(dirname(path), { recursive: true });
590
+ const tmp = join(dirname(path), `.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
591
+ writeFileSync(tmp, text, { encoding: "utf8", mode });
592
+ renameSync(tmp, path);
593
+ }
594
+ /**
595
+ * Where a project's backups go: under the project's own `.hmcp/`, which is
596
+ * kept out of git, rather than loose in the project folder beside the file
597
+ * people commit (UT5 round 3). Null for a file outside any project.
598
+ */
599
+ function projectBackupDir(target) {
600
+ if (target.scope === "project")
601
+ return join(dirname(target.path), ".hmcp", "backups");
602
+ if (target.scope === "cursor-project" || target.scope === "vscode-project")
603
+ return join(dirname(dirname(target.path)), ".hmcp", "backups");
604
+ return null;
605
+ }
606
+ /** `.mcp.json`, `.vscode-mcp.json`, `.cursor-mcp.json`: the file's place in the project, as one name. */
607
+ function projectBackupStem(target) {
608
+ return target.scope === "project" ? basename(target.path) : `${basename(dirname(target.path))}-${basename(target.path)}`;
609
+ }
610
+ /**
611
+ * Makes sure git skips the backups folder even if the person removed the
612
+ * `.hmcp/.gitignore` to share the toolbox's settings: the backups hold the
613
+ * app's original entries, keys and all.
614
+ */
615
+ function keepBackupsOutOfGit(dir) {
616
+ privateBackupDir(dir);
617
+ const ignore = join(dir, ".gitignore");
618
+ if (existsSync(ignore))
619
+ return;
620
+ try {
621
+ writeFileSync(ignore, "# Written by hardened-mcp. Backups of your AI app's settings, as they were before the toolbox was connected.\n" +
622
+ "# They can hold keys, so they are kept out of git. Undo puts them back and removes them.\n" +
623
+ "*\n", { encoding: "utf8" });
624
+ }
625
+ catch {
626
+ /* best effort */
627
+ }
628
+ }
629
+ /**
630
+ * A project's backups folder, readable by its owner only (R2 round 4, R4-2).
631
+ * The folders above it are made with the usual mode: `.hmcp` holds the
632
+ * toolbox's settings too, and is not this function's to narrow. A folder an
633
+ * earlier build made at 0755 is narrowed here.
634
+ */
635
+ function privateBackupDir(dir) {
636
+ mkdirSync(dirname(dir), { recursive: true });
637
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
638
+ try {
639
+ chmodSync(dir, 0o700);
640
+ }
641
+ catch {
642
+ /* best effort: Windows has no such modes */
643
+ }
644
+ }
645
+ /**
646
+ * A backup's write: atomic, and readable by its owner only, whatever mode the
647
+ * file it copies has. A backup holds the app's original entries, keys and
648
+ * all; a project's `.mcp.json` is often 0644 because it is meant to be
649
+ * shared, and its copy must not be (R4-2). Undo writes the original bytes
650
+ * back into the app's own file, which keeps that file's mode, so the backup's
651
+ * mode never reaches it.
652
+ */
653
+ function writePrivateText(path, text) {
654
+ mkdirSync(dirname(path), { recursive: true });
655
+ const tmp = join(dirname(path), `.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
656
+ writeFileSync(tmp, text, { encoding: "utf8", mode: 0o600 });
657
+ try {
658
+ chmodSync(tmp, 0o600);
659
+ }
660
+ catch {
661
+ /* best effort */
662
+ }
663
+ renameSync(tmp, path);
664
+ }
665
+ /** After undo: the project's backups folder goes once nothing but its own `.gitignore` is left in it. */
666
+ export function tidyProjectBackups(target) {
667
+ const dir = projectBackupDir(target);
668
+ if (!dir || !existsSync(dir))
669
+ return;
670
+ try {
671
+ const left = readdirSync(dir);
672
+ if (left.every((name) => name === ".gitignore"))
673
+ rmSync(dir, { recursive: true, force: true });
674
+ }
675
+ catch {
676
+ /* best effort */
677
+ }
678
+ }
679
+ /** A verbatim copy of the file before adoption touched it. One made by an earlier build, beside the file, is still used. */
680
+ export function wholeFileBackupPath(target) {
681
+ const legacy = `${target.path}.hmcp-backup`;
682
+ const dir = projectBackupDir(target);
683
+ if (!dir)
684
+ return legacy;
685
+ const current = join(dir, `${projectBackupStem(target)}.hmcp-backup`);
686
+ return existsSync(legacy) && !existsSync(current) ? legacy : current;
687
+ }
688
+ /**
689
+ * The structured record `--revert` reads. Claude Code's file sits in the home
690
+ * folder itself, and its record went beside it, loose in the home folder
691
+ * (UT5); it is kept under that folder's `.hmcp` now. A project's record goes
692
+ * under the project's `.hmcp/backups` (UT5 round 3). A record left by an
693
+ * earlier build where it used to go is still read and removed.
694
+ */
695
+ export function backupPath(target) {
696
+ const found = existingBackupPath(target);
697
+ return found ?? newBackupPath(target);
698
+ }
699
+ function newBackupPath(target) {
700
+ if (target.scope === "user" || target.scope === "local")
701
+ return join(dirname(target.path), ".hmcp", `${basename(target.path)}.adopt-backup.json`);
702
+ const dir = projectBackupDir(target);
703
+ if (dir)
704
+ return join(dir, `${projectBackupStem(target)}.adopt-backup.json`);
705
+ return legacyBackupPath(target);
706
+ }
707
+ function legacyBackupPath(target) {
708
+ return join(dirname(target.path), ".hmcp-adopt-backup.json");
709
+ }
710
+ /** Where this target's record is now, if it has one. */
711
+ export function existingBackupPath(target) {
712
+ for (const path of [newBackupPath(target), legacyBackupPath(target)])
713
+ if (existsSync(path))
714
+ return path;
715
+ return undefined;
716
+ }
717
+ export const AdoptBackupSchema = z
718
+ .object({
719
+ version: z.literal(1),
720
+ created_at: z.string(),
721
+ /*
722
+ * Every scope this build knows, and a backup written by a build that knew
723
+ * one more is still readable: a reverting user is often on a different
724
+ * version from the one that adopted.
725
+ */
726
+ scope: z.string().min(1),
727
+ config_path: z.string(),
728
+ gateway_entry_name: z.string(),
729
+ /** The original entries, verbatim, keyed by the name they had. */
730
+ replaced: z.record(z.string(), z.unknown()),
731
+ generated: z.array(z.string()),
732
+ registry_id: z.string().optional(),
733
+ /**
734
+ * The allow rule adopt added to the client's own settings, when it added
735
+ * one. Absent when the rule was declined or was already there, so revert
736
+ * only ever removes what adopt put in.
737
+ */
738
+ client_allow: z.object({ path: z.string(), rule: z.string() }).strict().optional()
739
+ })
740
+ .strict();
741
+ export function readBackup(target) {
742
+ const path = backupPath(target);
743
+ if (!existsSync(path))
744
+ return undefined;
745
+ let parsed;
746
+ try {
747
+ parsed = JSON.parse(readFileSync(path, "utf8"));
748
+ }
749
+ catch (err) {
750
+ throw new ClientConfigError(`${path} is not valid JSON: ${err.message}`);
751
+ }
752
+ const result = AdoptBackupSchema.safeParse(parsed);
753
+ if (!result.success) {
754
+ throw new ClientConfigError(`${path} is not a backup this build understands:\n` +
755
+ result.error.issues.map((i) => ` ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n"));
756
+ }
757
+ return result.data;
758
+ }
759
+ export function writeBackup(target, backup) {
760
+ AdoptBackupSchema.parse(backup);
761
+ const path = backupPath(target);
762
+ mkdirSync(dirname(path), { recursive: true });
763
+ const dir = projectBackupDir(target);
764
+ if (dir && dirname(path) === dir)
765
+ keepBackupsOutOfGit(dir);
766
+ writePrivateText(path, `${JSON.stringify(backup, null, 2)}\n`);
767
+ }
768
+ /**
769
+ * Copies the file byte for byte, for the human who would rather just move it
770
+ * back, and for undo to put back exactly. A second connection to the same
771
+ * file (its adoption record is already there) keeps the first copy: that one
772
+ * is the file as it was before any of this.
773
+ */
774
+ export function writeWholeFileBackup(file) {
775
+ if (!file.exists || file.text === null)
776
+ return;
777
+ const copy = wholeFileBackupPath(file.target);
778
+ if (existsSync(copy) && existsSync(backupPath(file.target)))
779
+ return;
780
+ const dir = projectBackupDir(file.target);
781
+ if (dir && dirname(copy) === dir)
782
+ keepBackupsOutOfGit(dir);
783
+ writePrivateText(copy, file.text);
784
+ }