toolfunnel 0.7.0 → 0.7.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.
Files changed (67) hide show
  1. package/README.md +228 -235
  2. package/SECURITY.md +84 -84
  3. package/bin/toolfunnel.js +451 -451
  4. package/docs/KNOWN_BUGS.md +80 -80
  5. package/docs/design.md +84 -84
  6. package/docs/packaging.md +115 -115
  7. package/hooks/hooks.manifest.json +27 -27
  8. package/hooks/scripts/example-audit.js +21 -21
  9. package/hooks/scripts/example-deny-dangerous.js +39 -39
  10. package/mcp/expose.example.json +30 -30
  11. package/mcp/servers/mock-modern/server.js +147 -147
  12. package/mcp/servers/mock-upstream/server.js +380 -380
  13. package/package.json +67 -67
  14. package/src/auth/config.js +174 -174
  15. package/src/auth/install.js +181 -181
  16. package/src/auth/resource-server.js +353 -353
  17. package/src/core/child-reaper.js +61 -61
  18. package/src/core/config-home.js +134 -134
  19. package/src/core/events.js +105 -105
  20. package/src/core/hook-engine.js +329 -329
  21. package/src/core/hook-loader.js +824 -824
  22. package/src/core/hook-runner.js +566 -566
  23. package/src/core/logger.js +297 -297
  24. package/src/core/matcher.js +100 -100
  25. package/src/core/metrics.js +75 -75
  26. package/src/core/rename-migration.js +163 -163
  27. package/src/core/requires.js +138 -138
  28. package/src/core/server-config.js +98 -98
  29. package/src/extend/add-hook.md +152 -152
  30. package/src/extend/add-mcp.md +119 -119
  31. package/src/extend/configure.md +88 -88
  32. package/src/extend/create-tool.md +168 -168
  33. package/src/extend/howto.js +102 -102
  34. package/src/extend/package.md +190 -190
  35. package/src/extend/wrap.md +99 -99
  36. package/src/mcp/aggregator.js +1719 -1674
  37. package/src/mcp/expose-store.js +577 -577
  38. package/src/mcp/gated-run.js +210 -210
  39. package/src/mcp/http-transport.js +1563 -1563
  40. package/src/mcp/mcp-client.js +1070 -1070
  41. package/src/mcp/modern.js +406 -406
  42. package/src/mcp/protocol.js +468 -468
  43. package/src/mcp/server.js +3112 -3112
  44. package/src/tools/registry.js +661 -661
  45. package/src/tools/tool-state.js +170 -170
  46. package/src/ui/public/app.js +1187 -1187
  47. package/src/ui/public/index.html +286 -286
  48. package/src/ui/public/styles.css +535 -535
  49. package/src/ui/server.js +1616 -1616
  50. package/tools/scripts/base64.js +139 -139
  51. package/tools/scripts/danger.js +61 -61
  52. package/tools/scripts/echo.js +39 -39
  53. package/tools/scripts/hash.js +101 -101
  54. package/tools/scripts/json.js +109 -109
  55. package/tools/scripts/text-stats.js +131 -131
  56. package/tools/scripts/tf-env.js +43 -43
  57. package/tools/scripts/tf-hook-add.js +151 -151
  58. package/tools/scripts/tf-hook-set.js +120 -120
  59. package/tools/scripts/tf-list.js +192 -192
  60. package/tools/scripts/tf-log.js +86 -86
  61. package/tools/scripts/tf-mcp-add.js +117 -117
  62. package/tools/scripts/tf-mcp-set.js +121 -121
  63. package/tools/scripts/tf-pack.js +237 -237
  64. package/tools/scripts/tf-tool-add.js +134 -134
  65. package/tools/scripts/tf-tool-set.js +142 -142
  66. package/tools/scripts/tf-wrap.js +103 -103
  67. package/tools/scripts/uuid.js +102 -102
@@ -1,577 +1,577 @@
1
- 'use strict';
2
-
3
- /**
4
- * expose-store.js - the persisted MCP config store (the extension guide defines the
5
- * authoritative shape).
6
- *
7
- * This is a PURE, config-only module: no process spawning, no network, no MCP
8
- * client. It is the on-disk source of truth that the aggregator reads
9
- * to know WHICH upstream MCPs to connect to and WHICH of their tools to surface
10
- * downstream as curated-direct tools. Editing this store is how a human/model
11
- * authors the MCP surface; the aggregator just consumes the result.
12
- *
13
- * Persisted file shape (src/mcp/expose.json):
14
- * {
15
- * "version": 1,
16
- * "upstreams": [
17
- * { id, transport:"stdio", command, args:[], env:{}, enabled:bool, description }
18
- * ],
19
- * "expose": [
20
- * { upstream, tool, as, category, enabled:bool }
21
- * ]
22
- * }
23
- *
24
- * Two blocks (per the extension guide):
25
- * - upstreams[] - one entry per upstream MCP. `id` is the stable key referenced
26
- * by expose[].upstream. `transport:"stdio"` spawns command+args.
27
- * - expose[] - which upstream tools become curated-direct. `(upstream,tool)`
28
- * is the natural key; `as` is the downstream name the CLI sees
29
- * (defaults to `<upstream>_<tool>` so two upstreams can't collide).
30
- *
31
- * Read/write discipline (mirrors src/tools/registry.js - the safety contract):
32
- * - READS never throw and always return CLONES (callers cannot mutate internal
33
- * state, and a missing file is simply an empty store).
34
- * - WRITES validate and throw a clear error on a bad write; nothing is persisted
35
- * when validation fails.
36
- * - Persistence is ATOMIC: a temp file in the SAME directory, fsync, then rename
37
- * over the target (copied exactly from registry.js::atomicWriteJson). A crash
38
- * leaves either the old file or the new file, never a half-written config.
39
- * - loadExposeStore on a MISSING file returns an empty store bound to the path;
40
- * the file is NOT created until the first write (keeps the server starting
41
- * clean with no live upstreams).
42
- *
43
- * CommonJS only. Node built-ins only. No new npm dependency.
44
- */
45
-
46
- const fs = require('node:fs');
47
- const path = require('node:path');
48
-
49
- const VALID_TRANSPORTS = new Set(['stdio']);
50
-
51
- /** Deep-ish clone for plain JSON values (structuredClone may be absent on old node). */
52
- function clone(value) {
53
- return JSON.parse(JSON.stringify(value));
54
- }
55
-
56
- /** Sibling temps older than this are strandings, not in-flight writes (see registry.js). */
57
- const STALE_TMP_MS = 60 * 60 * 1000;
58
-
59
- /** Remove STALE stranded temps for `base` in `dir` - copied from registry.js, same rules:
60
- * scoped to the target's own temp shape, entirely best-effort. */
61
- function sweepStaleTmp(dir, base) {
62
- let names;
63
- try { names = fs.readdirSync(dir); } catch (_e) { return; }
64
- const prefix = `.${base}.`;
65
- const now = Date.now();
66
- for (const name of names) {
67
- if (!name.startsWith(prefix) || !name.endsWith('.tmp')) continue;
68
- const p = path.join(dir, name);
69
- try {
70
- if (now - fs.statSync(p).mtimeMs > STALE_TMP_MS) fs.unlinkSync(p);
71
- } catch (_e) { /* a concurrent writer renamed/removed it - fine */ }
72
- }
73
- }
74
-
75
- /**
76
- * Atomic write: serialise to a temp file in the SAME directory as the target (so
77
- * the rename is atomic on the same filesystem/drive), fsync, then rename over the
78
- * target. Copied verbatim from src/tools/registry.js so the two stores share one
79
- * proven persistence pattern - including its cleanup contract: a failed write
80
- * unlinks its own temp before rethrowing, and stale strandings are swept on the
81
- * next successful write.
82
- */
83
- function atomicWriteJson(targetPath, obj) {
84
- const dir = path.dirname(targetPath);
85
- const base = path.basename(targetPath);
86
- sweepStaleTmp(dir, base);
87
- const tmp = path.join(dir, `.${base}.${process.pid}.${Date.now()}.tmp`);
88
- const data = JSON.stringify(obj, null, 2) + '\n';
89
- try {
90
- const fd = fs.openSync(tmp, 'w');
91
- try {
92
- fs.writeSync(fd, data, 0, 'utf8');
93
- fs.fsyncSync(fd);
94
- } finally {
95
- fs.closeSync(fd);
96
- }
97
- fs.renameSync(tmp, targetPath);
98
- } catch (err) {
99
- try { fs.unlinkSync(tmp); } catch (_e) { /* best-effort - the error below is the story */ }
100
- throw err;
101
- }
102
- }
103
-
104
- /** True for a non-empty string. */
105
- function isNonEmptyString(v) {
106
- return typeof v === 'string' && v.length > 0;
107
- }
108
-
109
- const { migrateForStoreFile } = require('../core/rename-migration');
110
-
111
- /** The name an expose entry surfaces its tool under RIGHT NOW: an ENABLED entry's `as`
112
- * (self-describing since addExpose defaults it); a disabled entry does not alias - the tool
113
- * surfaces under the namespaced default. Mirrors Aggregator._surfacedName / the UI's
114
- * surfacedNameFor. */
115
- function surfacedOf(e) {
116
- return (e && e.enabled && isNonEmptyString(e.as)) ? e.as : `${e.upstream}_${e.tool}`;
117
- }
118
-
119
- /**
120
- * Normalise an env map to a NULL-PROTOTYPE object of string -> string.
121
- *
122
- * Not cosmetic - it closes two proven isolation-guard bypasses at the boundary, by making the
123
- * stored, guarded and spawned representations identical:
124
- * - `JSON.parse('{"__proto__":{...}}')` yields an OWN `__proto__` data property. Spread keeps it,
125
- * and the client's `Object.assign` env merge then uses [[Set]], firing the
126
- * Object.prototype.__proto__ setter so the payload becomes the merged env's PROTOTYPE.
127
- * child_process enumerates env with for..in ("prototype values are intentionally included"),
128
- * so the child receives those keys while an own-key walk sees nothing. Copying own keys into
129
- * a null-prototype object makes that carrier inert.
130
- * - Non-string values reach the child regardless: node builds each pair as `${key}=${value}`, so
131
- * `['--require=/outside-module.js']` stringifies to its element. Coerce here, once.
132
- *
133
- * @param {*} raw
134
- * @returns {Object<string,string>} null-prototype, string-valued
135
- */
136
- function normaliseEnv(raw) {
137
- const out = Object.create(null);
138
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
139
- for (const key of Object.getOwnPropertyNames(raw)) {
140
- if (key === '__proto__') continue; // never re-establish the carrier
141
- const v = raw[key];
142
- if (v === undefined || v === null) continue;
143
- out[key] = typeof v === 'string' ? v : String(v);
144
- }
145
- return out;
146
- }
147
-
148
- /**
149
- * Normalise a raw upstream object into the canonical shape, filling sane defaults
150
- * for the optional fields. Does NOT validate - used both on load (lenient) and as
151
- * the base for write-validation. Always returns a fresh object.
152
- */
153
- function normaliseUpstream(raw) {
154
- const u = raw && typeof raw === 'object' ? raw : {};
155
- return {
156
- // Unknown fields ride along (the same deliberate choice as /api/identity): every store
157
- // WRITE rewrites the file, so dropping unrecognised fields meant a 0.6.0 pin/unpin toggle
158
- // silently erased hand-authored extras. Known fields are normalised below.
159
- ...(u && typeof u === 'object' ? JSON.parse(JSON.stringify(u)) : {}),
160
- id: typeof u.id === 'string' ? u.id : '',
161
- transport: typeof u.transport === 'string' ? u.transport : 'stdio',
162
- command: typeof u.command === 'string' ? u.command : '',
163
- args: Array.isArray(u.args) ? u.args.slice() : [],
164
- env: normaliseEnv(u.env),
165
- enabled: typeof u.enabled === 'boolean' ? u.enabled : true,
166
- // 0.6.0 legacy shim: OPT-IN commitment flag. A pinned upstream is knowingly legacy-era -
167
- // the gateway keeps speaking MCP 2024-11-05 to it forever (never auto-upgrades), warns at
168
- // startup and on every forwarded call naming the pinned version, and tells modern clients
169
- // via result _meta. Off by default, always.
170
- legacyPin: u.legacyPin === true,
171
- // modernOnly: legacyPin's MIRROR - this upstream must speak the modern era; the client
172
- // refuses the legacy fallback at connect instead of negotiating down. Off by default
173
- // (default = speak whichever era the server understands). Era-policy switches, 2026-07-18.
174
- modernOnly: u.modernOnly === true,
175
- // allowCodeLoadingEnv: OPT-OUT of the isolation guard's code-loading env refusal for THIS
176
- // upstream (NODE_OPTIONS and friends). Same pattern as legacyPin: off by default, explicit
177
- // in config where an auditor can see it, warned on connect when it excuses something.
178
- allowCodeLoadingEnv: u.allowCodeLoadingEnv === true,
179
- // allowOutsidePaths: *** USE WITH EXTREME CAUTION ***
180
- //
181
- // This is the big one. allowCodeLoadingEnv excuses ONE class of environment variable; this
182
- // excuses the ENTIRE path guard for this upstream - args, the cwd they resolve against, and
183
- // the path-list env vars - so the server can reach anywhere on disk the account can.
184
- //
185
- // It exists because refusing outright was wrong. A filesystem server pointed at a documents
186
- // folder, a git server pointed at a repo, a database tool holding a socket somewhere else:
187
- // these live outside the config home BY NATURE, and without this flag funnel mode could not
188
- // run them at all. The honest answer is a switch the operator sets deliberately, not a wall
189
- // with no door.
190
- //
191
- // What it costs: the guard is a TRIPWIRE for configs that quietly reach outside an auditable
192
- // home. Setting this says "I know this one reaches out, and I meant it". You are then trusting
193
- // that server the way you trust anything you installed - because that is what you have done.
194
- // It buys you nothing to set it on an upstream that does not need it.
195
- //
196
- // What it does NOT excuse: the OPTION-STRING env class (NODE_OPTIONS, JAVA_TOOL_OPTIONS,
197
- // PERL5OPT, RUBYOPT...). Those are mini command lines in the runtime's own grammar - they
198
- // load code with no path to check - and they have their own flag, directly above. Setting
199
- // this one to point a git server at a repo must not silently disarm that one too: two
200
- // exemptions mean two deliberate decisions, each visible on its own line to an auditor.
201
- //
202
- // Scope is the safety property: it is read per upstream, from THIS entry, at every connect.
203
- // One upstream opting out NEVER relaxes another's guard, and the gateway warns on every
204
- // connect, ONCE PER CLASS, about everything it excused. Same pattern as legacyPin - off by
205
- // default, explicit in config where an auditor can see it, loud when it applies.
206
- allowOutsidePaths: u.allowOutsidePaths === true,
207
- // Child working directory - the wrap era-probe and the client spawn both read it; it was
208
- // dropped here, so a configured cwd never survived the store.
209
- cwd: typeof u.cwd === 'string' && u.cwd.length ? u.cwd : undefined,
210
- // Per-upstream PAYLOAD timeout (ms) for tools/call | prompts/get | resources/read -
211
- // overrides the client's 120 s default. The control-plane window is requestTimeoutMs below.
212
- timeoutMs: Number.isFinite(u.timeoutMs) && u.timeoutMs > 0 ? u.timeoutMs : undefined,
213
- // Per-upstream CONTROL-PLANE window (ms) - handshake/list/discover/ping; default 10 s.
214
- // Raise it for a server that genuinely needs longer than 10 s to boot before it can answer
215
- // its handshake (a browser, a DB, a heavy session restore). The default stays the
216
- // dead-upstream detector; this is a knowing opt-in per upstream.
217
- requestTimeoutMs: Number.isFinite(u.requestTimeoutMs) && u.requestTimeoutMs > 0
218
- ? u.requestTimeoutMs : undefined,
219
- description: typeof u.description === 'string' ? u.description : '',
220
- };
221
- }
222
-
223
- /**
224
- * Normalise a raw expose object into the canonical shape. `as` is left as-is (may
225
- * be empty); exposedName() / addExpose() apply the `<upstream>_<tool>` default so
226
- * the stored entry can carry an explicit override or fall back lazily.
227
- */
228
- function normaliseExpose(raw) {
229
- const e = raw && typeof raw === 'object' ? raw : {};
230
- return {
231
- upstream: typeof e.upstream === 'string' ? e.upstream : '',
232
- tool: typeof e.tool === 'string' ? e.tool : '',
233
- as: typeof e.as === 'string' ? e.as : '',
234
- category: typeof e.category === 'string' ? e.category : '',
235
- enabled: typeof e.enabled === 'boolean' ? e.enabled : true,
236
- };
237
- }
238
-
239
- /**
240
- * Validate an upstream entry for a WRITE. Throws a clear error on a bad shape.
241
- * - id must be a non-empty string and unique among the OTHER upstreams.
242
- * - transport must be 'stdio' (the only baseline transport).
243
- * - a stdio upstream requires a non-empty command.
244
- * @param {object} entry normalised upstream
245
- * @param {Map} byId existing upstreams keyed by id (for uniqueness)
246
- * @param {string} [ignoreId] an id to skip in the uniqueness check (updates)
247
- */
248
- function validateUpstream(entry, byId, ignoreId) {
249
- if (!isNonEmptyString(entry.id)) {
250
- throw new Error('ExposeStore: upstream.id must be a non-empty string');
251
- }
252
- if (byId.has(entry.id) && entry.id !== ignoreId) {
253
- throw new Error(`ExposeStore: upstream id "${entry.id}" already exists`);
254
- }
255
- if (!VALID_TRANSPORTS.has(entry.transport)) {
256
- throw new Error(
257
- `ExposeStore: upstream.transport must be one of ${[...VALID_TRANSPORTS].join('|')} (id=${entry.id})`
258
- );
259
- }
260
- if (entry.transport === 'stdio' && !isNonEmptyString(entry.command)) {
261
- throw new Error(`ExposeStore: stdio upstream needs a non-empty "command" (id=${entry.id})`);
262
- }
263
- if (entry.legacyPin === true && entry.modernOnly === true) {
264
- throw new Error(
265
- `ExposeStore: upstream "${entry.id}" sets BOTH legacyPin and modernOnly - they contradict (force legacy vs refuse legacy); pick one`
266
- );
267
- }
268
- return entry;
269
- }
270
-
271
- class ExposeStore {
272
- /**
273
- * @param {object} opts
274
- * @param {string} opts.filePath path to expose.json (source of truth on disk)
275
- * @param {object} [opts.data] parsed config { version, upstreams, expose }
276
- */
277
- constructor({ filePath, data } = {}) {
278
- if (!isNonEmptyString(filePath)) throw new Error('ExposeStore: filePath is required');
279
- this._filePath = filePath;
280
-
281
- const d = data && typeof data === 'object' ? data : {};
282
- this._version = typeof d.version === 'number' ? d.version : 1;
283
-
284
- // Index upstreams by id; reject duplicate ids at load (a duplicate id makes
285
- // getUpstream / cascade-remove ambiguous). Keep insertion order via the Map.
286
- this._upstreams = new Map();
287
- const rawUpstreams = Array.isArray(d.upstreams) ? d.upstreams : [];
288
- for (const raw of rawUpstreams) {
289
- const u = normaliseUpstream(raw);
290
- if (!isNonEmptyString(u.id)) {
291
- throw new Error(`ExposeStore: an upstream is missing its id in ${filePath}`);
292
- }
293
- if (this._upstreams.has(u.id)) {
294
- throw new Error(`ExposeStore: duplicate upstream id "${u.id}" in ${filePath}`);
295
- }
296
- this._upstreams.set(u.id, u);
297
- }
298
-
299
- // expose[] is kept as an ordered array; the natural key is (upstream,tool).
300
- // Reject duplicate (upstream,tool) pairs at load.
301
- this._expose = [];
302
- const seenExpose = new Set();
303
- const rawExpose = Array.isArray(d.expose) ? d.expose : [];
304
- for (const raw of rawExpose) {
305
- const e = normaliseExpose(raw);
306
- const key = `${e.upstream} ${e.tool}`;
307
- if (seenExpose.has(key)) {
308
- throw new Error(
309
- `ExposeStore: duplicate expose entry (upstream="${e.upstream}", tool="${e.tool}") in ${filePath}`
310
- );
311
- }
312
- seenExpose.add(key);
313
- this._expose.push(e);
314
- }
315
- }
316
-
317
- // ── upstreams: read API (clones, never throw) ─────────────────────────────
318
-
319
- /** @returns {Array<{id,transport,command,args,env,enabled,description}>} cloned, in order. */
320
- listUpstreams() {
321
- return [...this._upstreams.values()].map(clone);
322
- }
323
-
324
- /** @returns {object|undefined} cloned upstream entry, or undefined if unknown. */
325
- getUpstream(id) {
326
- const u = this._upstreams.get(id);
327
- return u ? clone(u) : undefined;
328
- }
329
-
330
- // ── upstreams: write API (validate + atomic persist) ──────────────────────
331
-
332
- /**
333
- * Add an upstream. Validates: unique non-empty id; transport === 'stdio';
334
- * stdio requires a non-empty command. Persists atomically. Returns the clone.
335
- */
336
- addUpstream(entry) {
337
- const u = normaliseUpstream(entry);
338
- validateUpstream(u, this._upstreams);
339
- this._upstreams.set(u.id, u);
340
- this._persist();
341
- return clone(u);
342
- }
343
-
344
- /**
345
- * Shallow-merge `patch` over an existing upstream. `id` is immutable (the key);
346
- * any `id` in the patch is ignored. Re-validates the merged result and persists.
347
- */
348
- updateUpstream(id, patch) {
349
- const existing = this._upstreams.get(id);
350
- if (!existing) throw new Error(`ExposeStore.updateUpstream: unknown upstream id "${id}"`);
351
- if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
352
- throw new Error('ExposeStore.updateUpstream: patch must be an object');
353
- }
354
- const merged = normaliseUpstream({ ...existing, ...patch, id });
355
- validateUpstream(merged, this._upstreams, id);
356
- this._upstreams.set(id, merged);
357
- this._persist();
358
- return clone(merged);
359
- }
360
-
361
- /**
362
- * Remove an upstream AND cascade-remove any expose[] entries whose `upstream`
363
- * matches this id (a dangling expose entry would reference a missing upstream).
364
- * Persists atomically. Throws on an unknown id.
365
- * @returns {true}
366
- */
367
- removeUpstream(id) {
368
- if (!this._upstreams.has(id)) {
369
- throw new Error(`ExposeStore.removeUpstream: unknown upstream id "${id}"`);
370
- }
371
- this._upstreams.delete(id);
372
- this._expose = this._expose.filter((e) => e.upstream !== id);
373
- this._persist();
374
- return true;
375
- }
376
-
377
- /** Toggle an upstream's `enabled` flag; persists. Throws on unknown id. */
378
- setUpstreamEnabled(id, enabled) {
379
- return this.updateUpstream(id, { enabled: !!enabled });
380
- }
381
-
382
- // ── expose: read API (clones, never throw) ────────────────────────────────
383
-
384
- /**
385
- * List exposed entries. Optional filters:
386
- * - `upstream` restrict to one upstream id.
387
- * - `enabledOnly` only entries with enabled === true.
388
- * @returns {Array<{upstream,tool,as,category,enabled}>} cloned, in order.
389
- */
390
- listExposed({ upstream, enabledOnly } = {}) {
391
- const out = [];
392
- for (const e of this._expose) {
393
- if (upstream && e.upstream !== upstream) continue;
394
- if (enabledOnly && e.enabled !== true) continue;
395
- out.push(clone(e));
396
- }
397
- return out;
398
- }
399
-
400
- /** @returns {object|undefined} cloned expose entry for (upstream,tool), or undefined. */
401
- getExposed(upstream, tool) {
402
- const e = this._findExpose(upstream, tool);
403
- return e ? clone(e) : undefined;
404
- }
405
-
406
- /**
407
- * The downstream name the CLI sees for an expose entry: explicit `as` if set,
408
- * else the namespaced default `<upstream>_<tool>`.
409
- * @param {{upstream,tool,as?}} e
410
- * @returns {string}
411
- */
412
- exposedName(e) {
413
- const obj = e && typeof e === 'object' ? e : {};
414
- if (isNonEmptyString(obj.as)) return obj.as;
415
- return `${obj.upstream}_${obj.tool}`;
416
- }
417
-
418
- // ── expose: write API (validate + atomic persist) ─────────────────────────
419
-
420
- /**
421
- * Add an expose entry. Validates: the `upstream` must EXIST; `tool` must be a
422
- * non-empty string; `(upstream,tool)` must be unique. `as` defaults to the
423
- * namespaced `<upstream>_<tool>`. Persists atomically. Returns the clone.
424
- */
425
- addExpose(entry) {
426
- const e = normaliseExpose(entry);
427
- if (!isNonEmptyString(e.upstream)) {
428
- throw new Error('ExposeStore.addExpose: expose.upstream must be a non-empty string');
429
- }
430
- if (!this._upstreams.has(e.upstream)) {
431
- throw new Error(`ExposeStore.addExpose: unknown upstream "${e.upstream}" (add the upstream first)`);
432
- }
433
- if (!isNonEmptyString(e.tool)) {
434
- throw new Error(`ExposeStore.addExpose: expose.tool must be a non-empty string (upstream=${e.upstream})`);
435
- }
436
- if (this._findExpose(e.upstream, e.tool)) {
437
- throw new Error(
438
- `ExposeStore.addExpose: expose entry (upstream="${e.upstream}", tool="${e.tool}") already exists`
439
- );
440
- }
441
- // Persist an explicit `as` (default the namespaced name so the stored entry
442
- // is self-describing and the aggregator never has to recompute it).
443
- e.as = isNonEmptyString(e.as) ? e.as : `${e.upstream}_${e.tool}`;
444
- // A new ENABLED alias renames the surface from the namespaced default it had while merely
445
- // lean-discovered - migrate-or-refuse, exactly like updateExpose (no-op when as == default).
446
- if (e.enabled) this._migrateSurfaced(`${e.upstream}_${e.tool}`, e.as);
447
- this._expose.push(e);
448
- this._persist();
449
- return clone(e);
450
- }
451
-
452
- /**
453
- * Shallow-merge `patch` over an existing expose entry. The natural key
454
- * `(upstream,tool)` is immutable - any `upstream`/`tool` in the patch is ignored.
455
- * Persists atomically. Throws on an unknown (upstream,tool).
456
- */
457
- updateExpose(upstream, tool, patch) {
458
- const idx = this._indexOfExpose(upstream, tool);
459
- if (idx === -1) {
460
- throw new Error(`ExposeStore.updateExpose: unknown expose entry (upstream="${upstream}", tool="${tool}")`);
461
- }
462
- if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
463
- throw new Error('ExposeStore.updateExpose: patch must be an object');
464
- }
465
- const prior = this._expose[idx];
466
- const merged = normaliseExpose({ ...prior, ...patch, upstream, tool });
467
- // Rename-safety: a change to the SURFACED name - an `as` edit OR an enabled flip
468
- // (only an ENABLED entry's `as` surfaces; a disabled entry's tool falls back to the
469
- // namespaced default) - must carry the gate matchers and tools.state.json keys with it, or
470
- // the rename is REFUSED. Runs BEFORE persist so a refusal leaves this file untouched.
471
- this._migrateSurfaced(surfacedOf(prior), surfacedOf(merged));
472
- this._expose[idx] = merged;
473
- this._persist();
474
- return clone(merged);
475
- }
476
-
477
- /** Remove an expose entry. Persists. Throws on an unknown (upstream,tool). @returns {true} */
478
- removeExpose(upstream, tool) {
479
- const idx = this._indexOfExpose(upstream, tool);
480
- if (idx === -1) {
481
- throw new Error(`ExposeStore.removeExpose: unknown expose entry (upstream="${upstream}", tool="${tool}")`);
482
- }
483
- // Removing an ENABLED aliased entry renames the surface back to the namespaced default -
484
- // same migrate-or-refuse contract as updateExpose (rename-safety).
485
- const prior = this._expose[idx];
486
- this._migrateSurfaced(surfacedOf(prior), `${prior.upstream}_${prior.tool}`);
487
- this._expose.splice(idx, 1);
488
- this._persist();
489
- return true;
490
- }
491
-
492
- /** Gate matchers + state keys follow the surfaced name (or the rename refuses; see rename-migration.js). */
493
- _migrateSurfaced(oldName, newName) {
494
- if (oldName === newName) return;
495
- migrateForStoreFile(this._filePath, oldName, newName);
496
- }
497
-
498
- /** Toggle an expose entry's `enabled` flag; persists. Throws on unknown (upstream,tool). */
499
- setExposeEnabled(upstream, tool, enabled) {
500
- return this.updateExpose(upstream, tool, { enabled: !!enabled });
501
- }
502
-
503
- // ── serialisation ─────────────────────────────────────────────────────────
504
-
505
- /** @returns {{version, upstreams, expose}} a clone of the full config (safe to mutate). */
506
- toJSON() {
507
- return {
508
- version: this._version,
509
- upstreams: [...this._upstreams.values()].map(clone),
510
- expose: this._expose.map(clone),
511
- };
512
- }
513
-
514
- // ── internals ───────────────────────────────────────────────────────────
515
-
516
- /** @returns {object|undefined} the LIVE expose entry (not a clone) for (upstream,tool). */
517
- _findExpose(upstream, tool) {
518
- return this._expose.find((e) => e.upstream === upstream && e.tool === tool);
519
- }
520
-
521
- /** @returns {number} index of the expose entry for (upstream,tool), or -1. */
522
- _indexOfExpose(upstream, tool) {
523
- return this._expose.findIndex((e) => e.upstream === upstream && e.tool === tool);
524
- }
525
-
526
- /** Serialise current state back to the config file atomically. */
527
- _persist() {
528
- atomicWriteJson(this._filePath, this.toJSON());
529
- }
530
- }
531
-
532
- /**
533
- * loadExposeStore(filePath) -> ExposeStore
534
- *
535
- * Reads + parses the config JSON at `filePath` and returns an ExposeStore bound to
536
- * it.
537
- * - MISSING file -> return an empty store bound to filePath. The file is NOT
538
- * created until the first write (keeps the server starting clean).
539
- * - MALFORMED JSON (or a duplicate id / duplicate expose key) -> throw a clear
540
- * error so misconfiguration is caught at load, not at run time.
541
- *
542
- * @param {string} filePath
543
- * @returns {ExposeStore}
544
- */
545
- function loadExposeStore(filePath) {
546
- if (!isNonEmptyString(filePath)) {
547
- throw new Error('loadExposeStore: filePath (non-empty string) is required');
548
- }
549
- let raw;
550
- try {
551
- raw = fs.readFileSync(filePath, 'utf8');
552
- } catch (err) {
553
- if (err && err.code === 'ENOENT') {
554
- // Missing file is not an error - bind an empty store; defer file creation.
555
- return new ExposeStore({ filePath, data: { version: 1, upstreams: [], expose: [] } });
556
- }
557
- throw new Error(`loadExposeStore: cannot read config at "${filePath}": ${err.message}`);
558
- }
559
- let data;
560
- try {
561
- data = JSON.parse(raw);
562
- } catch (err) {
563
- throw new Error(`loadExposeStore: config at "${filePath}" is not valid JSON: ${err.message}`);
564
- }
565
- return new ExposeStore({ filePath, data });
566
- }
567
-
568
- module.exports = {
569
- ExposeStore,
570
- loadExposeStore,
571
- // exported for unit tests / the aggregator
572
- atomicWriteJson,
573
- normaliseUpstream,
574
- normaliseExpose,
575
- validateUpstream,
576
- VALID_TRANSPORTS,
577
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * expose-store.js - the persisted MCP config store (the extension guide defines the
5
+ * authoritative shape).
6
+ *
7
+ * This is a PURE, config-only module: no process spawning, no network, no MCP
8
+ * client. It is the on-disk source of truth that the aggregator reads
9
+ * to know WHICH upstream MCPs to connect to and WHICH of their tools to surface
10
+ * downstream as curated-direct tools. Editing this store is how a human/model
11
+ * authors the MCP surface; the aggregator just consumes the result.
12
+ *
13
+ * Persisted file shape (src/mcp/expose.json):
14
+ * {
15
+ * "version": 1,
16
+ * "upstreams": [
17
+ * { id, transport:"stdio", command, args:[], env:{}, enabled:bool, description }
18
+ * ],
19
+ * "expose": [
20
+ * { upstream, tool, as, category, enabled:bool }
21
+ * ]
22
+ * }
23
+ *
24
+ * Two blocks (per the extension guide):
25
+ * - upstreams[] - one entry per upstream MCP. `id` is the stable key referenced
26
+ * by expose[].upstream. `transport:"stdio"` spawns command+args.
27
+ * - expose[] - which upstream tools become curated-direct. `(upstream,tool)`
28
+ * is the natural key; `as` is the downstream name the CLI sees
29
+ * (defaults to `<upstream>_<tool>` so two upstreams can't collide).
30
+ *
31
+ * Read/write discipline (mirrors src/tools/registry.js - the safety contract):
32
+ * - READS never throw and always return CLONES (callers cannot mutate internal
33
+ * state, and a missing file is simply an empty store).
34
+ * - WRITES validate and throw a clear error on a bad write; nothing is persisted
35
+ * when validation fails.
36
+ * - Persistence is ATOMIC: a temp file in the SAME directory, fsync, then rename
37
+ * over the target (copied exactly from registry.js::atomicWriteJson). A crash
38
+ * leaves either the old file or the new file, never a half-written config.
39
+ * - loadExposeStore on a MISSING file returns an empty store bound to the path;
40
+ * the file is NOT created until the first write (keeps the server starting
41
+ * clean with no live upstreams).
42
+ *
43
+ * CommonJS only. Node built-ins only. No new npm dependency.
44
+ */
45
+
46
+ const fs = require('node:fs');
47
+ const path = require('node:path');
48
+
49
+ const VALID_TRANSPORTS = new Set(['stdio']);
50
+
51
+ /** Deep-ish clone for plain JSON values (structuredClone may be absent on old node). */
52
+ function clone(value) {
53
+ return JSON.parse(JSON.stringify(value));
54
+ }
55
+
56
+ /** Sibling temps older than this are strandings, not in-flight writes (see registry.js). */
57
+ const STALE_TMP_MS = 60 * 60 * 1000;
58
+
59
+ /** Remove STALE stranded temps for `base` in `dir` - copied from registry.js, same rules:
60
+ * scoped to the target's own temp shape, entirely best-effort. */
61
+ function sweepStaleTmp(dir, base) {
62
+ let names;
63
+ try { names = fs.readdirSync(dir); } catch (_e) { return; }
64
+ const prefix = `.${base}.`;
65
+ const now = Date.now();
66
+ for (const name of names) {
67
+ if (!name.startsWith(prefix) || !name.endsWith('.tmp')) continue;
68
+ const p = path.join(dir, name);
69
+ try {
70
+ if (now - fs.statSync(p).mtimeMs > STALE_TMP_MS) fs.unlinkSync(p);
71
+ } catch (_e) { /* a concurrent writer renamed/removed it - fine */ }
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Atomic write: serialise to a temp file in the SAME directory as the target (so
77
+ * the rename is atomic on the same filesystem/drive), fsync, then rename over the
78
+ * target. Copied verbatim from src/tools/registry.js so the two stores share one
79
+ * proven persistence pattern - including its cleanup contract: a failed write
80
+ * unlinks its own temp before rethrowing, and stale strandings are swept on the
81
+ * next successful write.
82
+ */
83
+ function atomicWriteJson(targetPath, obj) {
84
+ const dir = path.dirname(targetPath);
85
+ const base = path.basename(targetPath);
86
+ sweepStaleTmp(dir, base);
87
+ const tmp = path.join(dir, `.${base}.${process.pid}.${Date.now()}.tmp`);
88
+ const data = JSON.stringify(obj, null, 2) + '\n';
89
+ try {
90
+ const fd = fs.openSync(tmp, 'w');
91
+ try {
92
+ fs.writeSync(fd, data, 0, 'utf8');
93
+ fs.fsyncSync(fd);
94
+ } finally {
95
+ fs.closeSync(fd);
96
+ }
97
+ fs.renameSync(tmp, targetPath);
98
+ } catch (err) {
99
+ try { fs.unlinkSync(tmp); } catch (_e) { /* best-effort - the error below is the story */ }
100
+ throw err;
101
+ }
102
+ }
103
+
104
+ /** True for a non-empty string. */
105
+ function isNonEmptyString(v) {
106
+ return typeof v === 'string' && v.length > 0;
107
+ }
108
+
109
+ const { migrateForStoreFile } = require('../core/rename-migration');
110
+
111
+ /** The name an expose entry surfaces its tool under RIGHT NOW: an ENABLED entry's `as`
112
+ * (self-describing since addExpose defaults it); a disabled entry does not alias - the tool
113
+ * surfaces under the namespaced default. Mirrors Aggregator._surfacedName / the UI's
114
+ * surfacedNameFor. */
115
+ function surfacedOf(e) {
116
+ return (e && e.enabled && isNonEmptyString(e.as)) ? e.as : `${e.upstream}_${e.tool}`;
117
+ }
118
+
119
+ /**
120
+ * Normalise an env map to a NULL-PROTOTYPE object of string -> string.
121
+ *
122
+ * Not cosmetic - it closes two proven isolation-guard bypasses at the boundary, by making the
123
+ * stored, guarded and spawned representations identical:
124
+ * - `JSON.parse('{"__proto__":{...}}')` yields an OWN `__proto__` data property. Spread keeps it,
125
+ * and the client's `Object.assign` env merge then uses [[Set]], firing the
126
+ * Object.prototype.__proto__ setter so the payload becomes the merged env's PROTOTYPE.
127
+ * child_process enumerates env with for..in ("prototype values are intentionally included"),
128
+ * so the child receives those keys while an own-key walk sees nothing. Copying own keys into
129
+ * a null-prototype object makes that carrier inert.
130
+ * - Non-string values reach the child regardless: node builds each pair as `${key}=${value}`, so
131
+ * `['--require=/outside-module.js']` stringifies to its element. Coerce here, once.
132
+ *
133
+ * @param {*} raw
134
+ * @returns {Object<string,string>} null-prototype, string-valued
135
+ */
136
+ function normaliseEnv(raw) {
137
+ const out = Object.create(null);
138
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
139
+ for (const key of Object.getOwnPropertyNames(raw)) {
140
+ if (key === '__proto__') continue; // never re-establish the carrier
141
+ const v = raw[key];
142
+ if (v === undefined || v === null) continue;
143
+ out[key] = typeof v === 'string' ? v : String(v);
144
+ }
145
+ return out;
146
+ }
147
+
148
+ /**
149
+ * Normalise a raw upstream object into the canonical shape, filling sane defaults
150
+ * for the optional fields. Does NOT validate - used both on load (lenient) and as
151
+ * the base for write-validation. Always returns a fresh object.
152
+ */
153
+ function normaliseUpstream(raw) {
154
+ const u = raw && typeof raw === 'object' ? raw : {};
155
+ return {
156
+ // Unknown fields ride along (the same deliberate choice as /api/identity): every store
157
+ // WRITE rewrites the file, so dropping unrecognised fields meant a 0.6.0 pin/unpin toggle
158
+ // silently erased hand-authored extras. Known fields are normalised below.
159
+ ...(u && typeof u === 'object' ? JSON.parse(JSON.stringify(u)) : {}),
160
+ id: typeof u.id === 'string' ? u.id : '',
161
+ transport: typeof u.transport === 'string' ? u.transport : 'stdio',
162
+ command: typeof u.command === 'string' ? u.command : '',
163
+ args: Array.isArray(u.args) ? u.args.slice() : [],
164
+ env: normaliseEnv(u.env),
165
+ enabled: typeof u.enabled === 'boolean' ? u.enabled : true,
166
+ // 0.6.0 legacy shim: OPT-IN commitment flag. A pinned upstream is knowingly legacy-era -
167
+ // the gateway keeps speaking MCP 2024-11-05 to it forever (never auto-upgrades), warns at
168
+ // startup and on every forwarded call naming the pinned version, and tells modern clients
169
+ // via result _meta. Off by default, always.
170
+ legacyPin: u.legacyPin === true,
171
+ // modernOnly: legacyPin's MIRROR - this upstream must speak the modern era; the client
172
+ // refuses the legacy fallback at connect instead of negotiating down. Off by default
173
+ // (default = speak whichever era the server understands). Era-policy switches, 2026-07-18.
174
+ modernOnly: u.modernOnly === true,
175
+ // allowCodeLoadingEnv: OPT-OUT of the isolation guard's code-loading env refusal for THIS
176
+ // upstream (NODE_OPTIONS and friends). Same pattern as legacyPin: off by default, explicit
177
+ // in config where an auditor can see it, warned on connect when it excuses something.
178
+ allowCodeLoadingEnv: u.allowCodeLoadingEnv === true,
179
+ // allowOutsidePaths: *** USE WITH EXTREME CAUTION ***
180
+ //
181
+ // This is the big one. allowCodeLoadingEnv excuses ONE class of environment variable; this
182
+ // excuses the ENTIRE path guard for this upstream - args, the cwd they resolve against, and
183
+ // the path-list env vars - so the server can reach anywhere on disk the account can.
184
+ //
185
+ // It exists because refusing outright was wrong. A filesystem server pointed at a documents
186
+ // folder, a git server pointed at a repo, a database tool holding a socket somewhere else:
187
+ // these live outside the config home BY NATURE, and without this flag funnel mode could not
188
+ // run them at all. The honest answer is a switch the operator sets deliberately, not a wall
189
+ // with no door.
190
+ //
191
+ // What it costs: the guard is a TRIPWIRE for configs that quietly reach outside an auditable
192
+ // home. Setting this says "I know this one reaches out, and I meant it". You are then trusting
193
+ // that server the way you trust anything you installed - because that is what you have done.
194
+ // It buys you nothing to set it on an upstream that does not need it.
195
+ //
196
+ // What it does NOT excuse: the OPTION-STRING env class (NODE_OPTIONS, JAVA_TOOL_OPTIONS,
197
+ // PERL5OPT, RUBYOPT...). Those are mini command lines in the runtime's own grammar - they
198
+ // load code with no path to check - and they have their own flag, directly above. Setting
199
+ // this one to point a git server at a repo must not silently disarm that one too: two
200
+ // exemptions mean two deliberate decisions, each visible on its own line to an auditor.
201
+ //
202
+ // Scope is the safety property: it is read per upstream, from THIS entry, at every connect.
203
+ // One upstream opting out NEVER relaxes another's guard, and the gateway warns on every
204
+ // connect, ONCE PER CLASS, about everything it excused. Same pattern as legacyPin - off by
205
+ // default, explicit in config where an auditor can see it, loud when it applies.
206
+ allowOutsidePaths: u.allowOutsidePaths === true,
207
+ // Child working directory - the wrap era-probe and the client spawn both read it; it was
208
+ // dropped here, so a configured cwd never survived the store.
209
+ cwd: typeof u.cwd === 'string' && u.cwd.length ? u.cwd : undefined,
210
+ // Per-upstream PAYLOAD timeout (ms) for tools/call | prompts/get | resources/read -
211
+ // overrides the client's 120 s default. The control-plane window is requestTimeoutMs below.
212
+ timeoutMs: Number.isFinite(u.timeoutMs) && u.timeoutMs > 0 ? u.timeoutMs : undefined,
213
+ // Per-upstream CONTROL-PLANE window (ms) - handshake/list/discover/ping; default 10 s.
214
+ // Raise it for a server that genuinely needs longer than 10 s to boot before it can answer
215
+ // its handshake (a browser, a DB, a heavy session restore). The default stays the
216
+ // dead-upstream detector; this is a knowing opt-in per upstream.
217
+ requestTimeoutMs: Number.isFinite(u.requestTimeoutMs) && u.requestTimeoutMs > 0
218
+ ? u.requestTimeoutMs : undefined,
219
+ description: typeof u.description === 'string' ? u.description : '',
220
+ };
221
+ }
222
+
223
+ /**
224
+ * Normalise a raw expose object into the canonical shape. `as` is left as-is (may
225
+ * be empty); exposedName() / addExpose() apply the `<upstream>_<tool>` default so
226
+ * the stored entry can carry an explicit override or fall back lazily.
227
+ */
228
+ function normaliseExpose(raw) {
229
+ const e = raw && typeof raw === 'object' ? raw : {};
230
+ return {
231
+ upstream: typeof e.upstream === 'string' ? e.upstream : '',
232
+ tool: typeof e.tool === 'string' ? e.tool : '',
233
+ as: typeof e.as === 'string' ? e.as : '',
234
+ category: typeof e.category === 'string' ? e.category : '',
235
+ enabled: typeof e.enabled === 'boolean' ? e.enabled : true,
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Validate an upstream entry for a WRITE. Throws a clear error on a bad shape.
241
+ * - id must be a non-empty string and unique among the OTHER upstreams.
242
+ * - transport must be 'stdio' (the only baseline transport).
243
+ * - a stdio upstream requires a non-empty command.
244
+ * @param {object} entry normalised upstream
245
+ * @param {Map} byId existing upstreams keyed by id (for uniqueness)
246
+ * @param {string} [ignoreId] an id to skip in the uniqueness check (updates)
247
+ */
248
+ function validateUpstream(entry, byId, ignoreId) {
249
+ if (!isNonEmptyString(entry.id)) {
250
+ throw new Error('ExposeStore: upstream.id must be a non-empty string');
251
+ }
252
+ if (byId.has(entry.id) && entry.id !== ignoreId) {
253
+ throw new Error(`ExposeStore: upstream id "${entry.id}" already exists`);
254
+ }
255
+ if (!VALID_TRANSPORTS.has(entry.transport)) {
256
+ throw new Error(
257
+ `ExposeStore: upstream.transport must be one of ${[...VALID_TRANSPORTS].join('|')} (id=${entry.id})`
258
+ );
259
+ }
260
+ if (entry.transport === 'stdio' && !isNonEmptyString(entry.command)) {
261
+ throw new Error(`ExposeStore: stdio upstream needs a non-empty "command" (id=${entry.id})`);
262
+ }
263
+ if (entry.legacyPin === true && entry.modernOnly === true) {
264
+ throw new Error(
265
+ `ExposeStore: upstream "${entry.id}" sets BOTH legacyPin and modernOnly - they contradict (force legacy vs refuse legacy); pick one`
266
+ );
267
+ }
268
+ return entry;
269
+ }
270
+
271
+ class ExposeStore {
272
+ /**
273
+ * @param {object} opts
274
+ * @param {string} opts.filePath path to expose.json (source of truth on disk)
275
+ * @param {object} [opts.data] parsed config { version, upstreams, expose }
276
+ */
277
+ constructor({ filePath, data } = {}) {
278
+ if (!isNonEmptyString(filePath)) throw new Error('ExposeStore: filePath is required');
279
+ this._filePath = filePath;
280
+
281
+ const d = data && typeof data === 'object' ? data : {};
282
+ this._version = typeof d.version === 'number' ? d.version : 1;
283
+
284
+ // Index upstreams by id; reject duplicate ids at load (a duplicate id makes
285
+ // getUpstream / cascade-remove ambiguous). Keep insertion order via the Map.
286
+ this._upstreams = new Map();
287
+ const rawUpstreams = Array.isArray(d.upstreams) ? d.upstreams : [];
288
+ for (const raw of rawUpstreams) {
289
+ const u = normaliseUpstream(raw);
290
+ if (!isNonEmptyString(u.id)) {
291
+ throw new Error(`ExposeStore: an upstream is missing its id in ${filePath}`);
292
+ }
293
+ if (this._upstreams.has(u.id)) {
294
+ throw new Error(`ExposeStore: duplicate upstream id "${u.id}" in ${filePath}`);
295
+ }
296
+ this._upstreams.set(u.id, u);
297
+ }
298
+
299
+ // expose[] is kept as an ordered array; the natural key is (upstream,tool).
300
+ // Reject duplicate (upstream,tool) pairs at load.
301
+ this._expose = [];
302
+ const seenExpose = new Set();
303
+ const rawExpose = Array.isArray(d.expose) ? d.expose : [];
304
+ for (const raw of rawExpose) {
305
+ const e = normaliseExpose(raw);
306
+ const key = `${e.upstream} ${e.tool}`;
307
+ if (seenExpose.has(key)) {
308
+ throw new Error(
309
+ `ExposeStore: duplicate expose entry (upstream="${e.upstream}", tool="${e.tool}") in ${filePath}`
310
+ );
311
+ }
312
+ seenExpose.add(key);
313
+ this._expose.push(e);
314
+ }
315
+ }
316
+
317
+ // ── upstreams: read API (clones, never throw) ─────────────────────────────
318
+
319
+ /** @returns {Array<{id,transport,command,args,env,enabled,description}>} cloned, in order. */
320
+ listUpstreams() {
321
+ return [...this._upstreams.values()].map(clone);
322
+ }
323
+
324
+ /** @returns {object|undefined} cloned upstream entry, or undefined if unknown. */
325
+ getUpstream(id) {
326
+ const u = this._upstreams.get(id);
327
+ return u ? clone(u) : undefined;
328
+ }
329
+
330
+ // ── upstreams: write API (validate + atomic persist) ──────────────────────
331
+
332
+ /**
333
+ * Add an upstream. Validates: unique non-empty id; transport === 'stdio';
334
+ * stdio requires a non-empty command. Persists atomically. Returns the clone.
335
+ */
336
+ addUpstream(entry) {
337
+ const u = normaliseUpstream(entry);
338
+ validateUpstream(u, this._upstreams);
339
+ this._upstreams.set(u.id, u);
340
+ this._persist();
341
+ return clone(u);
342
+ }
343
+
344
+ /**
345
+ * Shallow-merge `patch` over an existing upstream. `id` is immutable (the key);
346
+ * any `id` in the patch is ignored. Re-validates the merged result and persists.
347
+ */
348
+ updateUpstream(id, patch) {
349
+ const existing = this._upstreams.get(id);
350
+ if (!existing) throw new Error(`ExposeStore.updateUpstream: unknown upstream id "${id}"`);
351
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
352
+ throw new Error('ExposeStore.updateUpstream: patch must be an object');
353
+ }
354
+ const merged = normaliseUpstream({ ...existing, ...patch, id });
355
+ validateUpstream(merged, this._upstreams, id);
356
+ this._upstreams.set(id, merged);
357
+ this._persist();
358
+ return clone(merged);
359
+ }
360
+
361
+ /**
362
+ * Remove an upstream AND cascade-remove any expose[] entries whose `upstream`
363
+ * matches this id (a dangling expose entry would reference a missing upstream).
364
+ * Persists atomically. Throws on an unknown id.
365
+ * @returns {true}
366
+ */
367
+ removeUpstream(id) {
368
+ if (!this._upstreams.has(id)) {
369
+ throw new Error(`ExposeStore.removeUpstream: unknown upstream id "${id}"`);
370
+ }
371
+ this._upstreams.delete(id);
372
+ this._expose = this._expose.filter((e) => e.upstream !== id);
373
+ this._persist();
374
+ return true;
375
+ }
376
+
377
+ /** Toggle an upstream's `enabled` flag; persists. Throws on unknown id. */
378
+ setUpstreamEnabled(id, enabled) {
379
+ return this.updateUpstream(id, { enabled: !!enabled });
380
+ }
381
+
382
+ // ── expose: read API (clones, never throw) ────────────────────────────────
383
+
384
+ /**
385
+ * List exposed entries. Optional filters:
386
+ * - `upstream` restrict to one upstream id.
387
+ * - `enabledOnly` only entries with enabled === true.
388
+ * @returns {Array<{upstream,tool,as,category,enabled}>} cloned, in order.
389
+ */
390
+ listExposed({ upstream, enabledOnly } = {}) {
391
+ const out = [];
392
+ for (const e of this._expose) {
393
+ if (upstream && e.upstream !== upstream) continue;
394
+ if (enabledOnly && e.enabled !== true) continue;
395
+ out.push(clone(e));
396
+ }
397
+ return out;
398
+ }
399
+
400
+ /** @returns {object|undefined} cloned expose entry for (upstream,tool), or undefined. */
401
+ getExposed(upstream, tool) {
402
+ const e = this._findExpose(upstream, tool);
403
+ return e ? clone(e) : undefined;
404
+ }
405
+
406
+ /**
407
+ * The downstream name the CLI sees for an expose entry: explicit `as` if set,
408
+ * else the namespaced default `<upstream>_<tool>`.
409
+ * @param {{upstream,tool,as?}} e
410
+ * @returns {string}
411
+ */
412
+ exposedName(e) {
413
+ const obj = e && typeof e === 'object' ? e : {};
414
+ if (isNonEmptyString(obj.as)) return obj.as;
415
+ return `${obj.upstream}_${obj.tool}`;
416
+ }
417
+
418
+ // ── expose: write API (validate + atomic persist) ─────────────────────────
419
+
420
+ /**
421
+ * Add an expose entry. Validates: the `upstream` must EXIST; `tool` must be a
422
+ * non-empty string; `(upstream,tool)` must be unique. `as` defaults to the
423
+ * namespaced `<upstream>_<tool>`. Persists atomically. Returns the clone.
424
+ */
425
+ addExpose(entry) {
426
+ const e = normaliseExpose(entry);
427
+ if (!isNonEmptyString(e.upstream)) {
428
+ throw new Error('ExposeStore.addExpose: expose.upstream must be a non-empty string');
429
+ }
430
+ if (!this._upstreams.has(e.upstream)) {
431
+ throw new Error(`ExposeStore.addExpose: unknown upstream "${e.upstream}" (add the upstream first)`);
432
+ }
433
+ if (!isNonEmptyString(e.tool)) {
434
+ throw new Error(`ExposeStore.addExpose: expose.tool must be a non-empty string (upstream=${e.upstream})`);
435
+ }
436
+ if (this._findExpose(e.upstream, e.tool)) {
437
+ throw new Error(
438
+ `ExposeStore.addExpose: expose entry (upstream="${e.upstream}", tool="${e.tool}") already exists`
439
+ );
440
+ }
441
+ // Persist an explicit `as` (default the namespaced name so the stored entry
442
+ // is self-describing and the aggregator never has to recompute it).
443
+ e.as = isNonEmptyString(e.as) ? e.as : `${e.upstream}_${e.tool}`;
444
+ // A new ENABLED alias renames the surface from the namespaced default it had while merely
445
+ // lean-discovered - migrate-or-refuse, exactly like updateExpose (no-op when as == default).
446
+ if (e.enabled) this._migrateSurfaced(`${e.upstream}_${e.tool}`, e.as);
447
+ this._expose.push(e);
448
+ this._persist();
449
+ return clone(e);
450
+ }
451
+
452
+ /**
453
+ * Shallow-merge `patch` over an existing expose entry. The natural key
454
+ * `(upstream,tool)` is immutable - any `upstream`/`tool` in the patch is ignored.
455
+ * Persists atomically. Throws on an unknown (upstream,tool).
456
+ */
457
+ updateExpose(upstream, tool, patch) {
458
+ const idx = this._indexOfExpose(upstream, tool);
459
+ if (idx === -1) {
460
+ throw new Error(`ExposeStore.updateExpose: unknown expose entry (upstream="${upstream}", tool="${tool}")`);
461
+ }
462
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
463
+ throw new Error('ExposeStore.updateExpose: patch must be an object');
464
+ }
465
+ const prior = this._expose[idx];
466
+ const merged = normaliseExpose({ ...prior, ...patch, upstream, tool });
467
+ // Rename-safety: a change to the SURFACED name - an `as` edit OR an enabled flip
468
+ // (only an ENABLED entry's `as` surfaces; a disabled entry's tool falls back to the
469
+ // namespaced default) - must carry the gate matchers and tools.state.json keys with it, or
470
+ // the rename is REFUSED. Runs BEFORE persist so a refusal leaves this file untouched.
471
+ this._migrateSurfaced(surfacedOf(prior), surfacedOf(merged));
472
+ this._expose[idx] = merged;
473
+ this._persist();
474
+ return clone(merged);
475
+ }
476
+
477
+ /** Remove an expose entry. Persists. Throws on an unknown (upstream,tool). @returns {true} */
478
+ removeExpose(upstream, tool) {
479
+ const idx = this._indexOfExpose(upstream, tool);
480
+ if (idx === -1) {
481
+ throw new Error(`ExposeStore.removeExpose: unknown expose entry (upstream="${upstream}", tool="${tool}")`);
482
+ }
483
+ // Removing an ENABLED aliased entry renames the surface back to the namespaced default -
484
+ // same migrate-or-refuse contract as updateExpose (rename-safety).
485
+ const prior = this._expose[idx];
486
+ this._migrateSurfaced(surfacedOf(prior), `${prior.upstream}_${prior.tool}`);
487
+ this._expose.splice(idx, 1);
488
+ this._persist();
489
+ return true;
490
+ }
491
+
492
+ /** Gate matchers + state keys follow the surfaced name (or the rename refuses; see rename-migration.js). */
493
+ _migrateSurfaced(oldName, newName) {
494
+ if (oldName === newName) return;
495
+ migrateForStoreFile(this._filePath, oldName, newName);
496
+ }
497
+
498
+ /** Toggle an expose entry's `enabled` flag; persists. Throws on unknown (upstream,tool). */
499
+ setExposeEnabled(upstream, tool, enabled) {
500
+ return this.updateExpose(upstream, tool, { enabled: !!enabled });
501
+ }
502
+
503
+ // ── serialisation ─────────────────────────────────────────────────────────
504
+
505
+ /** @returns {{version, upstreams, expose}} a clone of the full config (safe to mutate). */
506
+ toJSON() {
507
+ return {
508
+ version: this._version,
509
+ upstreams: [...this._upstreams.values()].map(clone),
510
+ expose: this._expose.map(clone),
511
+ };
512
+ }
513
+
514
+ // ── internals ───────────────────────────────────────────────────────────
515
+
516
+ /** @returns {object|undefined} the LIVE expose entry (not a clone) for (upstream,tool). */
517
+ _findExpose(upstream, tool) {
518
+ return this._expose.find((e) => e.upstream === upstream && e.tool === tool);
519
+ }
520
+
521
+ /** @returns {number} index of the expose entry for (upstream,tool), or -1. */
522
+ _indexOfExpose(upstream, tool) {
523
+ return this._expose.findIndex((e) => e.upstream === upstream && e.tool === tool);
524
+ }
525
+
526
+ /** Serialise current state back to the config file atomically. */
527
+ _persist() {
528
+ atomicWriteJson(this._filePath, this.toJSON());
529
+ }
530
+ }
531
+
532
+ /**
533
+ * loadExposeStore(filePath) -> ExposeStore
534
+ *
535
+ * Reads + parses the config JSON at `filePath` and returns an ExposeStore bound to
536
+ * it.
537
+ * - MISSING file -> return an empty store bound to filePath. The file is NOT
538
+ * created until the first write (keeps the server starting clean).
539
+ * - MALFORMED JSON (or a duplicate id / duplicate expose key) -> throw a clear
540
+ * error so misconfiguration is caught at load, not at run time.
541
+ *
542
+ * @param {string} filePath
543
+ * @returns {ExposeStore}
544
+ */
545
+ function loadExposeStore(filePath) {
546
+ if (!isNonEmptyString(filePath)) {
547
+ throw new Error('loadExposeStore: filePath (non-empty string) is required');
548
+ }
549
+ let raw;
550
+ try {
551
+ raw = fs.readFileSync(filePath, 'utf8');
552
+ } catch (err) {
553
+ if (err && err.code === 'ENOENT') {
554
+ // Missing file is not an error - bind an empty store; defer file creation.
555
+ return new ExposeStore({ filePath, data: { version: 1, upstreams: [], expose: [] } });
556
+ }
557
+ throw new Error(`loadExposeStore: cannot read config at "${filePath}": ${err.message}`);
558
+ }
559
+ let data;
560
+ try {
561
+ data = JSON.parse(raw);
562
+ } catch (err) {
563
+ throw new Error(`loadExposeStore: config at "${filePath}" is not valid JSON: ${err.message}`);
564
+ }
565
+ return new ExposeStore({ filePath, data });
566
+ }
567
+
568
+ module.exports = {
569
+ ExposeStore,
570
+ loadExposeStore,
571
+ // exported for unit tests / the aggregator
572
+ atomicWriteJson,
573
+ normaliseUpstream,
574
+ normaliseExpose,
575
+ validateUpstream,
576
+ VALID_TRANSPORTS,
577
+ };