hmcp-gateway 0.1.0 → 0.2.1

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.
@@ -0,0 +1,578 @@
1
+ import { resolve, dirname } from "node:path";
2
+ import { SECRET_VALUE_PATTERNS, isSecretRef } from "hmcp-core";
3
+ import { loadGatewayConfig } from "./config.js";
4
+ import { ClientConfigError, isRemote, parseServers, readBackup, readClientConfig, sameJson, scopeTargets, writeBackup, writeClientConfig } from "./client-config.js";
5
+ import { planAdoption } from "./adopt-plan.js";
6
+ import { headerSecretName } from "./adopt-cli.js";
7
+ import { readDesktopExtensions } from "./desktop-extensions.js";
8
+ /**
9
+ * Bringing the servers an app already runs into a toolbox that was connected
10
+ * to it from the console -- and taking them out of the app's own settings, so
11
+ * they run only through the toolbox.
12
+ *
13
+ * Why not `adopt`: adopt writes gateway.yaml and policy.yaml from scratch, and
14
+ * a toolbox connected from the console is one the person built there, with
15
+ * their own servers and rules in it. So this reuses adopt's reading and
16
+ * planning (the same translation from an app's entry to an upstream, the same
17
+ * name rules, the same idea of which values are keys) and leaves writing the
18
+ * toolbox to the console, which already knows how to add a server to an
19
+ * existing gateway.yaml without disturbing anything else in it.
20
+ *
21
+ * The undo rides on the record `connectClient` already writes. That record
22
+ * has a `replaced` map -- empty for a console connection -- which is exactly
23
+ * what "Undo connection" (and `adopt --revert`) put back. Each server taken
24
+ * out of the app goes into it first, so undoing the whole connection gives
25
+ * the app back every server it had, and the file comes back byte for byte.
26
+ */
27
+ export class ImportClientError extends ClientConfigError {
28
+ }
29
+ const INTERPOLATION = /\$\{[^}]*\}/;
30
+ /** Scopes whose servers Claude Code (or the editor) starts in the project folder. */
31
+ const PROJECT_SCOPES = new Set(["project", "local", "cursor-project", "vscode-project"]);
32
+ /**
33
+ * Whether an app entry is a toolbox of ours: by name, by what it runs, and by
34
+ * the gateway.yaml it is pointed at -- the same three ways adopt and connect
35
+ * recognise one, since any of them can be defeated by a rename.
36
+ */
37
+ function isToolboxEntry(name, server, entryName, gatewayConfig, target) {
38
+ if (name === entryName)
39
+ return true;
40
+ if (isRemote(server))
41
+ return false;
42
+ const words = [server.command, ...server.args];
43
+ if (words.some((w) => w.includes("hmcp-gateway") || w.replace(/\\/g, "/").endsWith("gateway/dist/cli.js")))
44
+ return true;
45
+ const at = server.args.indexOf("-c");
46
+ const value = at >= 0 ? server.args[at + 1] : undefined;
47
+ return value !== undefined && gatewayConfig !== undefined && resolve(dirname(target.path), value) === gatewayConfig;
48
+ }
49
+ /** Where a `${VAR}` sits in an entry, for the reason; undefined when nowhere. */
50
+ function interpolated(server) {
51
+ if (isRemote(server)) {
52
+ if (INTERPOLATION.test(server.url))
53
+ return "its web address";
54
+ const header = Object.entries(server.headers).find(([, v]) => INTERPOLATION.test(v))?.[0];
55
+ return header !== undefined ? `its ${header} header` : undefined;
56
+ }
57
+ if (INTERPOLATION.test(server.command) || server.args.some((a) => INTERPOLATION.test(a)))
58
+ return "its command line";
59
+ const env = Object.entries(server.env).find(([, v]) => INTERPOLATION.test(v))?.[0];
60
+ return env !== undefined ? `its ${env} setting` : undefined;
61
+ }
62
+ /** Whether an app entry runs `serve -c <this gateway.yaml>`. */
63
+ function pointsAt(server, gatewayConfig, target) {
64
+ if (isRemote(server))
65
+ return false;
66
+ const at = server.args.indexOf("-c");
67
+ const value = at >= 0 ? server.args[at + 1] : undefined;
68
+ return value !== undefined && resolve(dirname(target.path), value) === gatewayConfig;
69
+ }
70
+ /**
71
+ * Whether this very place in the app's settings runs this toolbox: an entry
72
+ * under the toolbox's name that points at its gateway.yaml.
73
+ *
74
+ * The connection's undo record alone is not enough. Claude Code keeps one
75
+ * record for `local` across every project (it sits beside `~/.claude.json`,
76
+ * and says nothing about which project), and a person can delete the entry
77
+ * by hand; either way the record says "connected" for servers the toolbox
78
+ * never runs. So the app's own file is asked.
79
+ */
80
+ export function runsToolbox(options, entryName, gatewayConfigPath) {
81
+ const scopeOptions = { cwd: options.cwd, home: options.home, ...(options.platform !== undefined ? { platform: options.platform } : {}) };
82
+ const target = scopeTargets(scopeOptions).find((t) => t.scope === options.scope);
83
+ if (!target)
84
+ return false;
85
+ try {
86
+ const entry = parseServers(readClientConfig(options.scope, scopeOptions).servers).servers.get(entryName);
87
+ return entry !== undefined && pointsAt(entry, resolve(gatewayConfigPath), target);
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
93
+ /** A setting's value as the app sees it, or undefined when it can't be read here (a key that isn't in the locked keys). */
94
+ function resolvedValue(value, secrets) {
95
+ if (typeof value === "string")
96
+ return value;
97
+ if (!isSecretRef(value) || !secrets)
98
+ return undefined;
99
+ let entry;
100
+ try {
101
+ entry = secrets.get(value.secret);
102
+ }
103
+ catch {
104
+ return undefined;
105
+ }
106
+ return entry?.kind === "value" ? `${value.prefix ?? ""}${entry.value}` : undefined;
107
+ }
108
+ /** The same names, each with the same value, every one of them readable. */
109
+ function sameSettings(app, toolbox, secrets) {
110
+ const names = Object.keys(app).sort();
111
+ if (JSON.stringify(names) !== JSON.stringify(Object.keys(toolbox).sort()))
112
+ return false;
113
+ return names.every((name) => resolvedValue(toolbox[name], secrets) === app[name]);
114
+ }
115
+ /**
116
+ * The upstream already in the toolbox that is this same server: the same
117
+ * program, arguments, folder and settings (keys included), or the same
118
+ * address and headers.
119
+ *
120
+ * The same command is not enough. A person's own GitHub server and the
121
+ * toolbox's work one both run `npx github-mcp`; taking the app's copy out on
122
+ * the strength of that would quietly move the person onto the other account.
123
+ * Whenever anything can't be compared -- a key that can't be read, a setting
124
+ * passed through from the gateway's environment, a sign-in -- it is not the
125
+ * same, and comes in as a server of its own.
126
+ */
127
+ function sameAs(server, upstreams, cwd, secrets) {
128
+ if (isRemote(server)) {
129
+ return upstreams.find((u) => u.transport === "http" &&
130
+ u.url === server.url &&
131
+ !u.oauth &&
132
+ !u.credential_passthrough.enabled &&
133
+ sameSettings(server.headers, u.headers, secrets))?.name;
134
+ }
135
+ return upstreams.find((u) => u.transport === "stdio" &&
136
+ u.command === server.command &&
137
+ JSON.stringify(u.args) === JSON.stringify(server.args) &&
138
+ (u.cwd === undefined ? cwd === undefined : cwd !== undefined && resolve(u.cwd) === resolve(cwd)) &&
139
+ u.pass_env.length === 0 &&
140
+ sameSettings(server.env, u.env, secrets))?.name;
141
+ }
142
+ /** Words that, as part of a setting's, flag's or header's name, say it carries a key. */
143
+ const KEY_WORDS = new Set([
144
+ "key", "apikey", "token", "secret", "password", "passwd", "pwd", "pat",
145
+ "auth", "authorization", "bearer", "cookie", "sig", "signature", "credential", "credentials"
146
+ ]);
147
+ /** A flag named for where a key is kept, not the key: `--token-file /etc/x`. */
148
+ const POINTER_WORDS = new Set(["file", "path", "dir", "env", "name"]);
149
+ /** Values that switch a key-named flag off rather than carry a key: `--auth none`. */
150
+ const OFF_VALUES = new Set(["none", "false", "off", "no", "disabled"]);
151
+ /** A name's words: `tavilyApiKey` and `--stripe-api-key` both read as words, `api` and `key`. */
152
+ function nameWords(name) {
153
+ return name
154
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
155
+ .toLowerCase()
156
+ .split(/[^a-z0-9]+/)
157
+ .filter(Boolean);
158
+ }
159
+ function keyishName(name) {
160
+ return nameWords(name).some((w) => KEY_WORDS.has(w));
161
+ }
162
+ /** Whether a flag, given this value, is handing over a key. `--no-auth` and `--auth none` are not. */
163
+ function flagHoldsKey(flag, value) {
164
+ if (!/^--?[A-Za-z]/.test(flag) || /^--?no-/i.test(flag))
165
+ return false;
166
+ const words = nameWords(flag);
167
+ if (words.length === 0 || POINTER_WORDS.has(words[words.length - 1]) || !words.some((w) => KEY_WORDS.has(w)))
168
+ return false;
169
+ return !OFF_VALUES.has(value.trim().toLowerCase());
170
+ }
171
+ /** A `--header` value, `Name: value`, whose name says it carries a key: `Authorization`, `X-API-Key`, `Cookie`. */
172
+ function headerHoldsKey(value) {
173
+ const name = /^\s*([A-Za-z0-9_-]+)\s*[:=]/.exec(value)?.[1];
174
+ return name !== undefined && keyishName(name);
175
+ }
176
+ /** Bits per character: a key is close to random, a word or a slug is not. */
177
+ function entropy(text) {
178
+ const counts = new Map();
179
+ for (const c of text)
180
+ counts.set(c, (counts.get(c) ?? 0) + 1);
181
+ let bits = 0;
182
+ for (const n of counts.values())
183
+ bits -= (n / text.length) * Math.log2(n / text.length);
184
+ return bits;
185
+ }
186
+ /**
187
+ * A web address path part that is a key in all but name: long, letters and
188
+ * digits mixed, and close to random -- the way some services put the key in
189
+ * the address itself (`/mcp/<key>/sse`).
190
+ */
191
+ function opaqueSegment(segment) {
192
+ return segment.length >= 24 && /^[A-Za-z0-9_-]+$/.test(segment) && /[A-Za-z]/.test(segment) && /[0-9]/.test(segment) && entropy(segment) >= 4;
193
+ }
194
+ /** A `config=` parameter that carries settings (JSON, or base64 of it), which is where such a service keeps the key. */
195
+ function configData(value) {
196
+ const v = value.trim();
197
+ return v.startsWith("{") || (v.length >= 16 && /^[A-Za-z0-9+/_-]+={0,2}$/.test(v));
198
+ }
199
+ /**
200
+ * The pieces of one word that are, or carry, a key: a known key shape, a
201
+ * password in a web address, a key-named or settings-carrying query
202
+ * parameter, or a key-shaped part of an address's path. Empty when there are
203
+ * none; otherwise the whole word first, then each piece, so a message
204
+ * quoting either can have it taken out.
205
+ *
206
+ * A content digest (`img@sha256:<hex>`) and a commit (`repo#<sha>`,
207
+ * `pkg@<sha>`) are long hex too, and are not keys: they are set aside before
208
+ * the shapes are looked for.
209
+ */
210
+ function keyParts(word) {
211
+ const text = word.replace(/\bsha(?:256|384|512):[0-9a-f]{32,}/gi, "").replace(/[@#][0-9a-f]{40,64}\b/gi, "");
212
+ const pieces = [];
213
+ for (const p of SECRET_VALUE_PATTERNS) {
214
+ const m = p.regex.exec(text);
215
+ if (m)
216
+ pieces.push(m[0]);
217
+ }
218
+ const userinfo = /[a-z][a-z0-9+.-]*:\/\/[^/\s@]*:([^/\s@]+)@/i.exec(text);
219
+ if (userinfo)
220
+ pieces.push(userinfo[1]);
221
+ const url = /[a-z][a-z0-9+.-]*:\/\/\S+/i.exec(text)?.[0];
222
+ if (url !== undefined) {
223
+ try {
224
+ const parsed = new URL(url);
225
+ if (parsed.password)
226
+ pieces.push(decodeURIComponent(parsed.password));
227
+ for (const [name, value] of parsed.searchParams) {
228
+ if (value && (keyishName(name) || (name.toLowerCase() === "config" && configData(value))))
229
+ pieces.push(value);
230
+ }
231
+ for (const segment of parsed.pathname.split("/"))
232
+ if (opaqueSegment(segment))
233
+ pieces.push(segment);
234
+ }
235
+ catch {
236
+ /* not an address after all */
237
+ }
238
+ }
239
+ return pieces.length > 0 ? [word, ...pieces] : [];
240
+ }
241
+ /**
242
+ * Every part of a command line (or an address) that is a key, for refusing
243
+ * the server and for taking those parts out of anything shown about it: the
244
+ * shapes `keyParts` finds, the value given to a key-named flag
245
+ * (`--github-token <key>`, `--stripe-api-key=<key>`), and a `--header` / `-H`
246
+ * value naming a credential header.
247
+ */
248
+ export function keyWords(words) {
249
+ const out = [];
250
+ words.forEach((word, i) => {
251
+ out.push(...keyParts(word));
252
+ const eq = /^(--?[^=\s]+)=(.+)$/s.exec(word);
253
+ const prev = i > 0 ? words[i - 1] : "";
254
+ if (eq && (flagHoldsKey(eq[1], eq[2]) || (/^(--header|-H)$/.test(eq[1]) && headerHoldsKey(eq[2]))))
255
+ out.push(eq[2]);
256
+ else if (!word.startsWith("-") && (flagHoldsKey(prev, word) || (/^(--header|-H)$/.test(prev) && headerHoldsKey(word))))
257
+ out.push(word);
258
+ });
259
+ return [...new Set(out)];
260
+ }
261
+ /**
262
+ * Whether a server's command line or address carries a key. The toolbox can
263
+ * lock a key that is a setting or a header -- gateway.yaml then only names it
264
+ * -- but one inside a command line or an address would be written into
265
+ * gateway.yaml as it is, and shown wherever the server is.
266
+ */
267
+ function keyInCommandOrAddress(server) {
268
+ return keyWords(isRemote(server) ? [server.url] : [server.command, ...server.args]).length > 0;
269
+ }
270
+ /**
271
+ * Settings that are plainly not secrets, and so are written into the
272
+ * server's own settings as they are. Everything else an imported server
273
+ * sets goes into the locked keys: a password is often called something no
274
+ * pattern recognises (`DB_PASS`, `CONN`), and a value that looks harmless
275
+ * (`redis://:pw@cache`) can still be one. A folder setting stays plain only
276
+ * when its value is a plain path.
277
+ */
278
+ export function plainSetting(name, value) {
279
+ if (/^(PATH|NODE_ENV|LOG_LEVEL|DEBUG|TZ|LANG)$/.test(name) || /^LC_[A-Z_]+$/.test(name))
280
+ return true;
281
+ return /_(DIR|PATH)$/.test(name) && !value.includes("://") && !value.includes("@");
282
+ }
283
+ /** The env and header names whose values a plan would lock. */
284
+ function keySettingsOf(plan) {
285
+ const planned = plan.upstreams[0];
286
+ if (!planned)
287
+ return [];
288
+ if (planned.upstream.transport === "http")
289
+ return [...(planned.lockHeaders ?? [])];
290
+ return planned.upstream.pass_env.filter((name) => !plainSetting(name, plan.gatewayEnv[name] ?? ""));
291
+ }
292
+ /**
293
+ * Every server the app has (and, for Claude Desktop, every extension), each
294
+ * with whether it can come into the toolbox and the name it would have there.
295
+ *
296
+ * Reads only. Names are worked out over the whole list in a fixed order --
297
+ * the app's entries by name, then extensions by id -- so the name shown in a
298
+ * list is the name a later import of any part of that list uses.
299
+ */
300
+ export function importCandidates(options) {
301
+ const platform = options.platform ?? process.platform;
302
+ const scopeOptions = { cwd: options.cwd, home: options.home, platform };
303
+ const target = scopeTargets(scopeOptions).find((t) => t.scope === options.scope);
304
+ if (!target)
305
+ throw new ImportClientError(`"${options.scope}" is not an app this version knows`);
306
+ const gatewayConfig = options.gatewayConfigPath !== undefined ? resolve(options.gatewayConfigPath) : undefined;
307
+ const entryName = options.entryName ?? "hmcp";
308
+ const existing = gatewayConfig !== undefined ? loadGatewayConfig(gatewayConfig).config.upstreams : [];
309
+ const taken = new Set(existing.map((u) => u.name));
310
+ const file = readClientConfig(options.scope, scopeOptions);
311
+ const { servers, malformed } = parseServers(file.servers);
312
+ const candidates = [];
313
+ const plan = (original, server, cwd) => {
314
+ const none = { keySettings: [], needsLocalHttp: false };
315
+ if (isRemote(server) && server.type === "sse") {
316
+ return {
317
+ ...none,
318
+ importable: false,
319
+ reason: "It uses an older connection type (SSE) that your toolbox can't sit in front of. Keep it in the app, or ask its maker for its newer web address."
320
+ };
321
+ }
322
+ if (isRemote(server)) {
323
+ try {
324
+ new URL(server.url);
325
+ }
326
+ catch {
327
+ return { ...none, importable: false, reason: "Its web address can't be read. Fix it in the app's settings, then check again." };
328
+ }
329
+ }
330
+ if (keyInCommandOrAddress(server)) {
331
+ return {
332
+ ...none,
333
+ importable: false,
334
+ reason: "Its command or address contains a key, which the toolbox can't lock. Keep it in the app, or add it from the " +
335
+ "console with the key typed in."
336
+ };
337
+ }
338
+ const where = interpolated(server);
339
+ if (where !== undefined) {
340
+ return {
341
+ ...none,
342
+ importable: false,
343
+ reason: `${where[0].toUpperCase()}${where.slice(1)} is filled in from a variable (\${...}) that the app takes from its own ` +
344
+ `environment, which the toolbox can't see. Keep it in the app, or add it from the console with the value typed in.`
345
+ };
346
+ }
347
+ /*
348
+ * Planned on its own rather than with its neighbours: adopt refuses two
349
+ * servers that set the same variable to different values, because its
350
+ * toolbox entry can carry only one. Here each server's values go into its
351
+ * own upstream (or the locked keys), so there is nothing to share.
352
+ */
353
+ const single = planAdoption(new Map([[original, server]]), {
354
+ gatewayEntryName: entryName,
355
+ ...(gatewayConfig !== undefined ? { gatewayConfigPath: gatewayConfig } : {}),
356
+ allowLocalHttp: true,
357
+ reservedNames: [...taken]
358
+ });
359
+ const planned = single.upstreams[0];
360
+ if (!planned) {
361
+ const skip = single.skipped[0];
362
+ return { ...none, importable: false, reason: skip ? `${skip.reason}; ${skip.remedy}` : "It can't be brought in." };
363
+ }
364
+ taken.add(planned.upstream.name);
365
+ const withCwd = cwd !== undefined && planned.upstream.transport === "stdio" && !planned.upstream.cwd
366
+ ? { ...single, upstreams: [{ ...planned, upstream: { ...planned.upstream, cwd } }] }
367
+ : single;
368
+ return {
369
+ importable: true,
370
+ upstreamName: planned.upstream.name,
371
+ plan: withCwd,
372
+ keySettings: keySettingsOf(withCwd),
373
+ needsLocalHttp: single.egressNeedsLocalHttp
374
+ };
375
+ };
376
+ const projectCwd = PROJECT_SCOPES.has(options.scope) ? resolve(options.cwd) : undefined;
377
+ for (const [name, server] of [...servers.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
378
+ if (isToolboxEntry(name, server, entryName, gatewayConfig, target))
379
+ continue;
380
+ const base = { key: name, name, source: "config", transport: server.type ?? "stdio", entry: file.servers[name] };
381
+ const already = sameAs(server, existing, projectCwd, options.secrets);
382
+ if (already !== undefined) {
383
+ candidates.push({ ...base, importable: true, upstreamName: already, inToolbox: already, keySettings: [], needsLocalHttp: false });
384
+ continue;
385
+ }
386
+ candidates.push({ ...base, ...plan(name, server, projectCwd) });
387
+ }
388
+ if (options.scope === "claude-desktop") {
389
+ for (const ext of readDesktopExtensions({ home: options.home, platform })) {
390
+ const base = { key: ext.id, name: ext.displayName, source: "extension", transport: "stdio", enabled: ext.enabled };
391
+ if (!ext.importable || !ext.server) {
392
+ candidates.push({ ...base, importable: false, ...(ext.reason ? { reason: ext.reason } : {}), keySettings: [], needsLocalHttp: false });
393
+ continue;
394
+ }
395
+ const already = sameAs(ext.server, existing, ext.dir, options.secrets);
396
+ if (already !== undefined) {
397
+ candidates.push({ ...base, importable: true, upstreamName: already, inToolbox: already, keySettings: [], needsLocalHttp: false });
398
+ continue;
399
+ }
400
+ candidates.push({ ...base, ...plan(ext.name, ext.server, ext.dir) });
401
+ }
402
+ }
403
+ return { target, candidates, malformed };
404
+ }
405
+ /**
406
+ * Where one server's values go once it runs from the toolbox rather than from
407
+ * the app.
408
+ *
409
+ * Adopt moves a stdio server's settings onto the toolbox's own entry in the
410
+ * app and passes them on by name. That entry here is the console's, shared by
411
+ * every server in the toolbox, so each value goes with its server instead:
412
+ * every setting becomes a locked key that gateway.yaml only names, except the
413
+ * few that are plainly not secrets (`plainSetting`: a log level, a folder),
414
+ * which are written into that server's own settings as they were. A web
415
+ * server's credential headers are locked as adopt locks them.
416
+ *
417
+ * Pure: it reads `store` to reuse a key already holding the same value, and
418
+ * writes nothing. `taken` (name to value) is shared by every server in one
419
+ * import, so two never pick one name for different values; a name two of
420
+ * them pick for the same value is listed by both, and created once.
421
+ */
422
+ export function planImportSecrets(plan, store, taken = new Map()) {
423
+ const locks = [];
424
+ const free = (name, value) => {
425
+ const saved = store.get(name);
426
+ const batch = taken.get(name);
427
+ return (saved === undefined || (saved.kind === "value" && saved.value === value)) && (batch === undefined || batch === value);
428
+ };
429
+ const nameFor = (upstream, setting, value) => {
430
+ const first = headerSecretName(store, upstream, setting, value);
431
+ let name = first;
432
+ for (let n = 2; !free(name, value); n++)
433
+ name = `${first}-${n}`;
434
+ taken.set(name, value);
435
+ return name;
436
+ };
437
+ const upstreams = plan.upstreams.map((planned) => {
438
+ const upstream = planned.upstream;
439
+ if (upstream.transport === "stdio") {
440
+ const env = { ...upstream.env };
441
+ for (const key of upstream.pass_env) {
442
+ const value = plan.gatewayEnv[key];
443
+ if (value === undefined)
444
+ continue;
445
+ if (!plainSetting(key, value)) {
446
+ const name = nameFor(upstream.name, key, value);
447
+ locks.push({ name, value, label: `${key} for ${planned.originalName}` });
448
+ env[key] = { secret: name };
449
+ }
450
+ else {
451
+ env[key] = value;
452
+ }
453
+ }
454
+ return { ...planned, upstream: { ...upstream, env, pass_env: [] } };
455
+ }
456
+ const headers = { ...upstream.headers };
457
+ for (const header of planned.lockHeaders ?? []) {
458
+ const value = headers[header];
459
+ if (typeof value !== "string")
460
+ continue;
461
+ const prefix = /^(Bearer|Basic|Token) /i.exec(value)?.[0];
462
+ const secret = prefix ? value.slice(prefix.length) : value;
463
+ const name = nameFor(upstream.name, header, secret);
464
+ locks.push({ name, value: secret, label: `${header} for ${planned.originalName}` });
465
+ headers[header] = prefix ? { secret: name, prefix } : { secret: name };
466
+ }
467
+ return { ...planned, upstream: { ...upstream, headers } };
468
+ });
469
+ return { plan: { ...plan, upstreams, gatewayEnv: {}, secretsOnDisk: false }, locks };
470
+ }
471
+ function targetAndRecord(options) {
472
+ const scopeOptions = { cwd: options.cwd, home: options.home, ...(options.platform !== undefined ? { platform: options.platform } : {}) };
473
+ const target = scopeTargets(scopeOptions).find((t) => t.scope === options.scope);
474
+ if (!target)
475
+ throw new ImportClientError(`"${options.scope}" is not an app this version knows`);
476
+ const backup = readBackup(target);
477
+ /*
478
+ * Claude Code's `user` and `local` share one record, so the record must be
479
+ * this scope's own: moving a server out of one under the other's record
480
+ * would put it back into the wrong place on undo.
481
+ */
482
+ if (!backup || backup.scope !== options.scope) {
483
+ throw new ImportClientError(`${target.client} isn't connected to a toolbox from the console, so there is nothing to bring its servers into. Connect the app first.`);
484
+ }
485
+ return { target, backup, scopeOptions };
486
+ }
487
+ /**
488
+ * The record, and the app's file holding the toolbox's own entry. Claude
489
+ * Code's `local` record is shared by every project, so a project without the
490
+ * entry is not connected whatever the record says -- and neither is one whose
491
+ * entry was deleted by hand.
492
+ */
493
+ function connectedTargetAndRecord(options) {
494
+ const found = targetAndRecord(options);
495
+ const file = readClientConfig(options.scope, found.scopeOptions);
496
+ if (!Object.hasOwn(file.servers, found.backup.gateway_entry_name)) {
497
+ throw new ImportClientError(`${found.target.client} here doesn't run the toolbox (its "${found.backup.gateway_entry_name}" entry isn't in ${found.target.path} ` +
498
+ `under ${found.target.where}), so there is nothing to bring its servers into. Connect the app first.`);
499
+ }
500
+ return { ...found, file };
501
+ }
502
+ /**
503
+ * Takes these entries out of the app's settings, keeping each in the
504
+ * connection's undo record first.
505
+ *
506
+ * `expected` is each entry as it was when it was checked: one that changed
507
+ * since (the person edited it, or the app rewrote it) is not taken out on the
508
+ * strength of a check of something else. The record is written before the
509
+ * app's file, so there is no moment when a server is in neither; if the app's
510
+ * file can't be written, the record goes back as it was.
511
+ */
512
+ export function moveOutOfClient(options, expected) {
513
+ const { target, backup, file } = connectedTargetAndRecord(options);
514
+ const names = Object.keys(expected);
515
+ for (const name of names) {
516
+ if (name === backup.gateway_entry_name)
517
+ throw new ImportClientError(`"${name}" is the toolbox's own entry in ${target.client}.`);
518
+ if (!Object.hasOwn(file.servers, name) || !sameJson(file.servers[name], expected[name])) {
519
+ throw new ImportClientError(`"${name}" changed in ${target.client}'s settings since it was checked, so nothing was moved. Check again.`);
520
+ }
521
+ // The same entry kept already (the app wrote its old list back since) is not a second server.
522
+ if (Object.hasOwn(backup.replaced, name) && !sameJson(backup.replaced[name], file.servers[name])) {
523
+ throw new ImportClientError(`The undo record for ${target.client} already keeps a server called "${name}", so this one can't be kept there too. ` +
524
+ `Rename one of them in ${target.path}, then try again.`);
525
+ }
526
+ }
527
+ const moved = Object.fromEntries(names.map((name) => [name, file.servers[name]]));
528
+ const rest = Object.fromEntries(Object.entries(file.servers).filter(([name]) => !names.includes(name)));
529
+ writeBackup(target, { ...backup, replaced: { ...backup.replaced, ...moved } });
530
+ try {
531
+ writeClientConfig(file, rest);
532
+ }
533
+ catch (err) {
534
+ writeBackup(target, backup);
535
+ throw err;
536
+ }
537
+ return { configPath: target.path, moved: names };
538
+ }
539
+ /**
540
+ * Puts entries taken out by `moveOutOfClient` back into the app's settings,
541
+ * from the undo record, and takes them out of the record.
542
+ *
543
+ * A name in use in the app again is refused, as Undo connection refuses it:
544
+ * whatever is there now was put there on purpose -- unless it is the very
545
+ * entry being put back, which needs nothing. Names the record no longer holds
546
+ * (the whole connection was undone meanwhile) are reported, not guessed.
547
+ *
548
+ * `where` is the place in the app's settings the servers were taken from, as
549
+ * the import recorded it: Claude Code's `local` record is shared by every
550
+ * project, and a server is never put back into a different one.
551
+ */
552
+ export function putBackInClient(options, names, from = {}) {
553
+ const { target, backup } = targetAndRecord(options);
554
+ if (from.where !== undefined && from.where !== target.where) {
555
+ throw new ImportClientError(`These servers were taken from a different place in ${target.client}'s settings (${from.where}), so they were not put back here (${target.where}).`);
556
+ }
557
+ const file = readClientConfig(options.scope, { cwd: options.cwd, home: options.home, ...(options.platform !== undefined ? { platform: options.platform } : {}) });
558
+ const clashes = names.filter((name) => Object.hasOwn(file.servers, name) && !(Object.hasOwn(backup.replaced, name) && sameJson(file.servers[name], backup.replaced[name])));
559
+ if (clashes.length > 0) {
560
+ throw new ImportClientError(`${target.client} has a server under ${clashes.map((n) => `"${n}"`).join(", ")} again, so nothing was put back: ` +
561
+ `putting it back would replace what is there now. Rename or remove ${clashes.length === 1 ? "it" : "them"} in ${target.path}, then try again.`);
562
+ }
563
+ const restored = names.filter((name) => Object.hasOwn(backup.replaced, name));
564
+ const missing = names.filter((name) => !Object.hasOwn(backup.replaced, name));
565
+ if (restored.length === 0)
566
+ return { configPath: target.path, restored, missing };
567
+ const entries = Object.fromEntries(restored.map((name) => [name, backup.replaced[name]]));
568
+ const kept = Object.fromEntries(Object.entries(backup.replaced).filter(([name]) => !restored.includes(name)));
569
+ writeBackup(target, { ...backup, replaced: kept });
570
+ try {
571
+ writeClientConfig(file, { ...file.servers, ...entries });
572
+ }
573
+ catch (err) {
574
+ writeBackup(target, backup);
575
+ throw err;
576
+ }
577
+ return { configPath: target.path, restored, missing };
578
+ }
package/dist/index.d.ts CHANGED
@@ -22,5 +22,10 @@ export * from "./upstream-errors.js";
22
22
  export * from "./oauth.js";
23
23
  export * from "./probe-upstream.js";
24
24
  export * from "./connect-client.js";
25
+ export * from "./desktop-extensions.js";
26
+ export * from "./import-client.js";
27
+ export * from "./guard.js";
28
+ export * from "./guard-install.js";
25
29
  export { configTextDigest, diffUpstreams } from "./config-source.js";
26
30
  export { applyPack, loadPacks, type Pack, type PackRuleOut } from "./packs.js";
31
+ export * from "./github-doors.js";
package/dist/index.js CHANGED
@@ -22,5 +22,10 @@ export * from "./upstream-errors.js";
22
22
  export * from "./oauth.js";
23
23
  export * from "./probe-upstream.js";
24
24
  export * from "./connect-client.js";
25
+ export * from "./desktop-extensions.js";
26
+ export * from "./import-client.js";
27
+ export * from "./guard.js";
28
+ export * from "./guard-install.js";
25
29
  export { configTextDigest, diffUpstreams } from "./config-source.js";
26
30
  export { applyPack, loadPacks } from "./packs.js";
31
+ export * from "./github-doors.js";
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Codex's `config.toml` (shared with the ChatGPT desktop app): reading it,
3
+ * and changing only the MCP server tables in it.
4
+ *
5
+ * The TOML library is used to read, never to write. Writing a whole TOML
6
+ * document back from its parsed value loses every comment and all of the
7
+ * person's layout, in a file they edit by hand. So every change here is a
8
+ * cut or an append on the file's own text: a server's table (and its
9
+ * `[mcp_servers.<name>.*]` sub-tables) removed, or a new table added at the
10
+ * end. After each change the result is read again and must equal the
11
+ * original with exactly that change, or nothing is written.
12
+ *
13
+ * A file whose servers are written in a form these cuts cannot handle safely
14
+ * -- an inline table, dotted keys, an array of tables, a server split across
15
+ * the file -- can be read and listed, but is refused for editing.
16
+ */
17
+ export declare class TomlEditError extends Error {
18
+ }
19
+ /** The file as a plain JSON value: no null prototypes, dates as their TOML text. */
20
+ export declare function parseToml(text: string): Record<string, unknown>;
21
+ /**
22
+ * Why this file's servers cannot be changed by cutting and appending text, or
23
+ * null when they can. Names a form, never a value.
24
+ */
25
+ export declare function tomlEditProblem(text: string): string | null;
26
+ /** A TOML basic string: quotes, backslashes and control characters escaped. */
27
+ export declare function tomlString(value: string): string;
28
+ /** A key, bare when TOML allows it and quoted otherwise. */
29
+ export declare function tomlKey(key: string): string;
30
+ /** `[a.b]` with its plain settings, then each table-valued setting as a `[a.b.<key>]` of its own. */
31
+ export declare function tomlTable(path: readonly string[], value: Record<string, unknown>, eol?: string): string;
32
+ /** Whether two read TOML documents say the same, a missing `mcp_servers` and an empty one being the same. */
33
+ export declare function sameToml(a: unknown, b: unknown): boolean;
34
+ /**
35
+ * The file's text with its servers changed from `current` to `next`: each
36
+ * server that went or changed has its tables cut out, each one that is new
37
+ * or changed is appended at the end. Everything else is the file's own bytes.
38
+ *
39
+ * Refuses, with nothing written by the caller, when the servers are in a form
40
+ * this cannot cut safely or when the result does not read back as exactly
41
+ * the intended change.
42
+ */
43
+ export declare function editTomlServers(text: string, next: Record<string, unknown>): string;