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