toolfunnel 0.5.0 → 0.7.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 (72) hide show
  1. package/README.md +235 -167
  2. package/SECURITY.md +84 -0
  3. package/bin/toolfunnel.js +451 -147
  4. package/docs/KNOWN_BUGS.md +80 -33
  5. package/docs/MANUAL.pdf +0 -0
  6. package/docs/design.md +84 -0
  7. package/docs/packaging.md +115 -115
  8. package/hooks/hooks.manifest.json +27 -27
  9. package/hooks/scripts/example-audit.js +21 -21
  10. package/hooks/scripts/example-deny-dangerous.js +39 -31
  11. package/mcp/expose.example.json +30 -30
  12. package/mcp/servers/mock-modern/server.js +147 -0
  13. package/mcp/servers/mock-upstream/server.js +222 -12
  14. package/package.json +67 -65
  15. package/src/auth/config.js +174 -174
  16. package/src/auth/install.js +181 -181
  17. package/src/auth/resource-server.js +353 -344
  18. package/src/core/child-reaper.js +61 -0
  19. package/src/core/config-home.js +134 -134
  20. package/src/core/events.js +105 -105
  21. package/src/core/hook-engine.js +329 -275
  22. package/src/core/hook-loader.js +824 -791
  23. package/src/core/hook-runner.js +566 -346
  24. package/src/core/logger.js +297 -171
  25. package/src/core/matcher.js +100 -51
  26. package/src/core/metrics.js +75 -75
  27. package/src/core/rename-migration.js +163 -0
  28. package/src/core/requires.js +138 -138
  29. package/src/core/server-config.js +98 -77
  30. package/src/extend/add-hook.md +152 -142
  31. package/src/extend/add-mcp.md +119 -121
  32. package/src/extend/configure.md +88 -0
  33. package/src/extend/create-tool.md +168 -152
  34. package/src/extend/howto.js +102 -98
  35. package/src/extend/package.md +190 -187
  36. package/src/extend/wrap.md +99 -0
  37. package/src/mcp/aggregator.js +1674 -807
  38. package/src/mcp/expose-store.js +577 -430
  39. package/src/mcp/gated-run.js +210 -194
  40. package/src/mcp/http-transport.js +1563 -1012
  41. package/src/mcp/mcp-client.js +1070 -530
  42. package/src/mcp/modern.js +406 -0
  43. package/src/mcp/protocol.js +468 -466
  44. package/src/mcp/server.js +3112 -1405
  45. package/src/tools/registry.js +661 -513
  46. package/src/tools/tool-state.js +170 -104
  47. package/src/ui/public/app.js +1187 -1055
  48. package/src/ui/public/index.html +286 -249
  49. package/src/ui/public/styles.css +535 -535
  50. package/src/ui/server.js +1616 -1190
  51. package/tools/scripts/base64.js +139 -139
  52. package/tools/scripts/danger.js +61 -61
  53. package/tools/scripts/echo.js +39 -39
  54. package/tools/scripts/hash.js +101 -101
  55. package/tools/scripts/json.js +109 -109
  56. package/tools/scripts/text-stats.js +131 -131
  57. package/tools/scripts/tf-env.js +43 -43
  58. package/tools/scripts/tf-hook-add.js +151 -151
  59. package/tools/scripts/tf-hook-set.js +120 -112
  60. package/tools/scripts/tf-list.js +192 -192
  61. package/tools/scripts/tf-log.js +86 -86
  62. package/tools/scripts/tf-mcp-add.js +117 -117
  63. package/tools/scripts/tf-mcp-set.js +121 -102
  64. package/tools/scripts/tf-pack.js +237 -237
  65. package/tools/scripts/tf-tool-add.js +134 -129
  66. package/tools/scripts/tf-tool-set.js +142 -142
  67. package/tools/scripts/tf-wrap.js +103 -0
  68. package/tools/scripts/uuid.js +102 -102
  69. package/tools/tools.register.json +14 -3
  70. package/src/core/tool-registry.js +0 -180
  71. package/src/packages/packager.js +0 -715
  72. package/src/tools/drift.js +0 -138
@@ -1,807 +1,1674 @@
1
- 'use strict';
2
-
3
- /**
4
- * aggregator.js — the upstream-MCP connection + curated-expose layer.
5
- *
6
- * The aggregator is the bridge between the persisted MCP config (src/mcp/expose-store.js)
7
- * and the live upstream MCP servers (src/mcp/mcp-client.js). It:
8
- *
9
- * 1. CONNECTS one McpClient per ENABLED upstream in the ExposeStore (connectAll),
10
- * caching the connected client + its discovered tools. A failed upstream never
11
- * sinks the others — failures are collected, not thrown.
12
- * 2. DISCOVERS an upstream's tool surface on demand (discover) — what the MCP
13
- * Manager UI's 'discover' button calls.
14
- * 3. Computes the CURATED-DIRECT tool definitions to advertise downstream
15
- * (exposedToolDefinitions) — only for ENABLED expose[] entries whose upstream
16
- * is connected AND actually advertises the named tool. Each definition is
17
- * renamed to its downstream `as` name (what the CLI / PreToolUse matchers see).
18
- * 4. RESOLVES a downstream call back to its upstream client + real tool name
19
- * (resolveExposedExecution) — the seam the MCP server's curated-direct call
20
- * path uses to actually execute, AFTER the hook gate has run.
21
- *
22
- * Decoupling note: downstream the CLI sees the renamed `as` tool; upstream we call
23
- * the REAL tool name. resolveExposedExecution carries BOTH so the gate (PreToolUse)
24
- * matches on the downstream name while execution hits the real upstream.
25
- *
26
- * SAFETY CONTRACT (mirrors expose-store.js / mcp-client.js):
27
- * - connectAll / discover / closeAll NEVER throw. connectAll collects per-upstream
28
- * failures into failed[]; a dead/misconfigured upstream cannot crash the server
29
- * start. closeAll is idempotent and tears down every cached client.
30
- * - The DEFAULT clientFactory enforces the HARD ISOLATION rule: a vendored upstream
31
- * may only reference CODE/FILES inside the gateway root. The
32
- * guard is applied to the ARGS (the script path, db files, … that the interpreter
33
- * is pointed at): any arg that is an absolute path, or that looks like a file path
34
- * (contains a path separator), MUST resolve inside v3Root — otherwise the factory
35
- * throws and connectAll records the upstream in failed[]. The COMMAND slot is the
36
- * interpreter/executable (node, npx, or an absolute path to a node binary that by
37
- * definition lives OUTSIDE the project, e.g. process.execPath / a system node.exe)
38
- * and is therefore NOT subject to the in-sandbox requirement — bare commands AND an
39
- * absolute interpreter path are both allowed. Isolation is about WHAT CODE runs in
40
- * the spawned process, not which interpreter binary runs it; the args are that code.
41
- * This is what stops a config from pointing at a live `.mcp.json` server's script
42
- * outside the sandbox while still letting the system node interpreter spawn it.
43
- *
44
- * CommonJS only. Node built-ins only. No new npm dependency. No @modelcontextprotocol/sdk.
45
- */
46
-
47
- const path = require('node:path');
48
-
49
- const { McpClient } = require('./mcp-client');
50
- const logger = require('../core/logger');
51
-
52
- // The sandbox root = the CONFIG HOME (TOOLFUNNEL_HOME / --config-dir; defaults to the package
53
- // root — see src/core/config-home.js). Used as the isolation boundary the default clientFactory
54
- // enforces: a pack's path-shaped upstream args live under the home, so the home is the boundary.
55
- // A caller may override via opts.v3Root for tests.
56
- const { resolveConfigHome } = require('../core/config-home');
57
- const DEFAULT_ROOT = resolveConfigHome();
58
-
59
- /** True for a non-empty string. */
60
- function isNonEmptyString(v) {
61
- return typeof v === 'string' && v.length > 0;
62
- }
63
-
64
- /**
65
- * Does this argv token LOOK like a file path? An absolute path (path.isAbsolute) or
66
- * any token containing a path separator ('/' or '\\') is treated as a path reference
67
- * and must be confined to v3Root. A bare token like 'node', 'npx', 'server' or a flag
68
- * like '--port' is NOT a path and is always allowed.
69
- * @param {string} arg
70
- * @returns {boolean}
71
- */
72
- function looksLikePath(arg) {
73
- if (!isNonEmptyString(arg)) return false;
74
- if (path.isAbsolute(arg)) return true;
75
- return arg.indexOf('/') !== -1 || arg.indexOf('\\') !== -1;
76
- }
77
-
78
- /**
79
- * Is `target` inside `root` (or equal to it)? Compares fully-resolved, normalised
80
- * absolute paths. A relative `target` is resolved AGAINST root (so 'vendor/x/server.js'
81
- * checks the in-sandbox location). Returns false for anything that escapes root via
82
- * '..' or an absolute path elsewhere on disk.
83
- * @param {string} root absolute sandbox root
84
- * @param {string} target path token (absolute or relative)
85
- * @returns {boolean}
86
- */
87
- function isInside(root, target) {
88
- const resolvedRoot = path.resolve(root);
89
- // An absolute target is checked as-is; a relative one is resolved within the root so
90
- // a vendored relative path ('vendor/foo/server.js') is judged at its in-sandbox spot.
91
- const resolvedTarget = path.isAbsolute(target)
92
- ? path.resolve(target)
93
- : path.resolve(resolvedRoot, target);
94
- const rel = path.relative(resolvedRoot, resolvedTarget);
95
- // Inside iff the relative path neither starts with '..' nor is itself absolute
96
- // (an absolute `rel` happens on win32 across drive letters). '' (equal) counts as inside.
97
- return rel === '' || (!rel.startsWith('..' + path.sep) && rel !== '..' && !path.isAbsolute(rel));
98
- }
99
-
100
- /**
101
- * The DEFAULT clientFactory. Constructs a McpClient for an upstream entry AFTER
102
- * enforcing the isolation guard on the ARGS: every arg that looks like a file path
103
- * (an absolute path, or any token containing a path separator) must resolve inside
104
- * `v3Root`. Throws a clear 'isolation: …' error otherwise — connectAll catches that
105
- * into failed[].
106
- *
107
- * The COMMAND slot is intentionally NOT guarded: it names the interpreter/executable
108
- * (e.g. 'node', 'npx', or an absolute path to a node binary such as process.execPath /
109
- * a system node.exe) which by definition lives OUTSIDE the project. Isolation is about
110
- * WHAT CODE the spawned process runs — that is the args (the server script + any data
111
- * files it loads) — not which interpreter binary launches it. Guarding the command too
112
- * would wrongly reject every vendored upstream the moment it is run by the system node.
113
- *
114
- * @param {object} upstream a normalised ExposeStore upstream { id, command, args, env, … }
115
- * @param {string} v3Root the sandbox root the upstream's path-shaped ARGS must stay inside
116
- * @returns {McpClient}
117
- */
118
- function defaultClientFactory(upstream, v3Root, onClose) {
119
- const id = isNonEmptyString(upstream && upstream.id) ? upstream.id : '(unknown)';
120
- const args = Array.isArray(upstream && upstream.args) ? upstream.args : [];
121
-
122
- // Guard every path-shaped arg (server scripts, db files, …). The command (interpreter)
123
- // is NOT guarded — see the function doc: it is the executable, not the code being run.
124
- for (const arg of args) {
125
- if (looksLikePath(arg) && !isInside(v3Root, arg)) {
126
- throw new Error(`isolation: upstream ${id} references a path outside the gateway root`);
127
- }
128
- }
129
-
130
- return new McpClient({
131
- id: upstream.id,
132
- command: upstream.command,
133
- args: upstream.args,
134
- env: upstream.env,
135
- onClose, // unexpected death → the aggregator schedules a background reconnect
136
- });
137
- }
138
-
139
- /**
140
- * Aggregator — owns the live upstream connections and the curated-expose computation.
141
- *
142
- * Lifecycle: `new Aggregator({ store, v3Root, clientFactory })`
143
- * → `await connectAll()` (or `await discover(id)` lazily)
144
- * → `exposedToolDefinitions()` / `resolveExposedExecution(name, args)`
145
- * → `await closeAll()` (idempotent).
146
- */
147
- class Aggregator {
148
- /**
149
- * @param {object} opts
150
- * @param {object} opts.store an ExposeStore (the on-disk MCP config).
151
- * @param {string} [opts.v3Root] sandbox root for the isolation guard (default: the gateway root).
152
- * @param {Function} [opts.clientFactory] (upstreamEntry, v3Root) -> McpClient. Default enforces isolation.
153
- */
154
- constructor({ store, v3Root, clientFactory, onToolsChanged } = {}) {
155
- if (!store || typeof store !== 'object') {
156
- throw new Error('Aggregator: a `store` (ExposeStore) is required');
157
- }
158
- this._store = store;
159
- this._v3Root = isNonEmptyString(v3Root) ? v3Root : DEFAULT_ROOT;
160
- // Called when the LIVE tool set changes OUT OF BAND (a background reconnect recovers or finally
161
- // loses an upstream) so the transport can emit notifications/tools/list_changed. Default no-op;
162
- // the server wires it to emitToolsListChanged(send). Settable so reloadExpose can re-wire the
163
- // new instance.
164
- this.onToolsChanged = typeof onToolsChanged === 'function' ? onToolsChanged : () => {};
165
- // The factory receives (upstream, v3Root, onClose). A caller-supplied factory may ignore the
166
- // extra args; the default uses v3Root for isolation and onClose for death-driven reconnect.
167
- this._clientFactory =
168
- typeof clientFactory === 'function'
169
- ? (upstream, onClose) => clientFactory(upstream, this._v3Root, onClose)
170
- : (upstream, onClose) => defaultClientFactory(upstream, this._v3Root, onClose);
171
-
172
- /** @type {Map<string, object>} upstreamId -> connected McpClient */
173
- this._clients = new Map();
174
- /** @type {Map<string, Array>} upstreamId -> discovered tool defs [{name,description,inputSchema}] */
175
- this._tools = new Map();
176
- /** @type {Map<string, Promise>} upstreamId -> in-flight connect promise (race guard for ensureConnected) */
177
- this._connecting = new Map();
178
- /** @type {Map<string, any>} upstreamId -> pending background-reconnect timer (one per upstream) */
179
- this._reconnectTimers = new Map();
180
- /** Set true by closeAll(). A torn-down aggregator (e.g. swapped out by reloadExpose) must NEVER
181
- * (re)connect — a captured execute thunk holding this instance would otherwise spawn an orphan
182
- * upstream child on it that nothing ever closes. ensureConnected/connectAll check this. */
183
- this._closed = false;
184
- }
185
-
186
- /**
187
- * Connect every ENABLED upstream in the store, caching each connected client and its
188
- * discovered tools. NEVER throws — a per-upstream failure (isolation guard, spawn
189
- * failure, handshake timeout, listTools failure) is collected into failed[]. An
190
- * upstream already connected (cached) is treated as connected without reconnecting.
191
- *
192
- * @returns {Promise<{ connected: string[], failed: Array<{id:string, error:string}> }>}
193
- */
194
- async connectAll() {
195
- const connected = [];
196
- const failed = [];
197
- if (this._closed) return { connected, failed }; // a closed (torn-down) aggregator never connects
198
-
199
- let upstreams;
200
- try {
201
- upstreams = this._store.listUpstreams();
202
- } catch (err) {
203
- // listUpstreams() shouldn't throw (it clones), but never let it sink connectAll.
204
- return { connected, failed: [{ id: '(store)', error: errMsg(err) }] };
205
- }
206
-
207
- for (const upstream of upstreams) {
208
- if (!upstream || upstream.enabled !== true) continue; // only ENABLED upstreams
209
-
210
- const id = upstream.id;
211
- if (this._clients.has(id)) {
212
- // Already connected this session — keep it; don't double-spawn.
213
- connected.push(id);
214
- continue;
215
- }
216
-
217
- try {
218
- await this._connectOne(upstream);
219
- connected.push(id);
220
- } catch (err) {
221
- // Clean up any half-built client so a failure leaves no zombie/cache entry.
222
- this._discard(id);
223
- const error = errMsg(err);
224
- logger.log({ type: 'mcp', event: 'connect_failed', upstream: id, error });
225
- failed.push({ id, error });
226
- }
227
- }
228
-
229
- return { connected, failed };
230
- }
231
-
232
- /**
233
- * Discover one upstream's tool surface. Connects the upstream if it isn't already
234
- * (lazily, honouring the isolation guard), runs tools/list, caches and returns the
235
- * raw tool definitions [{name, description, inputSchema}]. This is what the MCP
236
- * Manager 'discover' button calls.
237
- *
238
- * Unlike connectAll this MAY reject (it is a direct user action, so the UI wants the
239
- * error) — but it cleans up a failed connection so no zombie child is left.
240
- *
241
- * @param {string} upstreamId
242
- * @returns {Promise<Array<{name:string, description?:string, inputSchema?:object}>>}
243
- */
244
- async discover(upstreamId) {
245
- if (!isNonEmptyString(upstreamId)) {
246
- throw new Error('Aggregator.discover: upstreamId (non-empty string) is required');
247
- }
248
-
249
- // If connected already, re-list so the discover button always reflects live state.
250
- if (this._clients.has(upstreamId)) {
251
- const tools = await this._listAndCache(upstreamId);
252
- return tools;
253
- }
254
-
255
- const upstream = this._store.getUpstream(upstreamId);
256
- if (!upstream) {
257
- throw new Error(`Aggregator.discover: unknown upstream "${upstreamId}"`);
258
- }
259
-
260
- try {
261
- await this._connectOne(upstream);
262
- } catch (err) {
263
- this._discard(upstreamId);
264
- throw new Error(`Aggregator.discover: cannot connect "${upstreamId}": ${errMsg(err)}`);
265
- }
266
- // _connectOne already cached the tools; return them (clone so callers can't mutate).
267
- return cloneTools(this._tools.get(upstreamId) || []);
268
- }
269
-
270
- /**
271
- * @returns {Object<string, Array>} a clone map of upstreamId -> cached discovered tools.
272
- * Only includes upstreams that have been connected/discovered this session.
273
- */
274
- toolsByUpstream() {
275
- const out = {};
276
- for (const [id, tools] of this._tools) {
277
- out[id] = cloneTools(tools);
278
- }
279
- return out;
280
- }
281
-
282
- /**
283
- * The CURATED-DIRECT tool definitions to advertise downstream. For each ENABLED
284
- * expose[] entry whose upstream is CONNECTED and ACTUALLY advertises the named tool:
285
- * - name = store.exposedName(entry) (the downstream `as` name)
286
- * - description = '[' + upstream + '] ' + (upstream tool description || 'tool')
287
- * - inputSchema = the upstream tool's inputSchema || { type:'object' }
288
- *
289
- * Entries whose upstream isn't connected, or whose named tool the upstream doesn't
290
- * advertise, are silently skipped (you can't expose a tool that isn't there).
291
- *
292
- * @returns {Array<{name:string, description:string, inputSchema:object}>}
293
- */
294
- exposedToolDefinitions() {
295
- const defs = [];
296
- let exposed;
297
- try {
298
- exposed = this._store.listExposed({ enabledOnly: true });
299
- } catch (_err) {
300
- return defs; // never throw out of a definition build
301
- }
302
-
303
- for (const e of exposed) {
304
- if (!e || !this._clients.has(e.upstream)) continue; // upstream not connected
305
- const upstreamTools = this._tools.get(e.upstream) || [];
306
- const upstreamTool = upstreamTools.find((t) => t && t.name === e.tool);
307
- if (!upstreamTool) continue; // upstream doesn't actually advertise this tool
308
-
309
- const name = this._store.exposedName(e);
310
- const desc =
311
- isNonEmptyString(upstreamTool.description) ? upstreamTool.description : 'tool';
312
- const inputSchema =
313
- upstreamTool.inputSchema && typeof upstreamTool.inputSchema === 'object'
314
- ? upstreamTool.inputSchema
315
- : { type: 'object' };
316
-
317
- defs.push({
318
- name,
319
- description: `[${e.upstream}] ${desc}`,
320
- inputSchema: cloneJson(inputSchema),
321
- });
322
- }
323
- return defs;
324
- }
325
-
326
- /**
327
- * Is `name` a downstream `as` name currently exposed (enabled) AND backed by a
328
- * connected upstream that advertises the underlying tool? Mirrors the set
329
- * exposedToolDefinitions() advertises.
330
- * @param {string} name
331
- * @returns {boolean}
332
- */
333
- isExposed(name) {
334
- return this._findExposedExecution(name) !== null;
335
- }
336
-
337
- /**
338
- * Resolve a downstream `as` name + args into an executor. Returns
339
- * { execute, toolName, upstream } | null
340
- * where:
341
- * - execute() invokes the connected client's callTool(<real upstream tool name>, args)
342
- * - toolName = the downstream `as` (what PreToolUse matchers see — the gate matches
343
- * the downstream name, execution hits the real upstream tool)
344
- * - upstream = the upstream id
345
- * Returns null if `name` is not exposed/enabled or its upstream isn't connected.
346
- *
347
- * @param {string} name downstream `as` name
348
- * @param {any} args structured arguments forwarded verbatim to callTool
349
- * @returns {{ execute: Function, toolName: string, upstream: string } | null}
350
- */
351
- resolveExposedExecution(name, args) {
352
- const hit = this._findExposedExecution(name);
353
- if (!hit) return null;
354
- const { client, realTool, upstream, exposedName } = hit;
355
- return {
356
- // The execute thunk is the seam the server calls AFTER the PreToolUse gate allows it.
357
- execute: this._forwardExecutor(client, realTool, args),
358
- toolName: exposedName, // downstream name — the gate's matcher target
359
- upstream,
360
- };
361
- }
362
-
363
- // ── lean register forwarding (slice 2) ──────────────────────────────────────
364
- // The LEAN path surfaces an attached upstream's tools through the 4 meta-tools (toolfunnel_list_tools
365
- // / _tool_instructions / _run_tool) instead of injecting them top-level every turn. The full
366
- // discovered set of every CONNECTED + enabled upstream is surfaced (attaching an MCP makes its
367
- // tools appear with no per-tool curation); expose[]/hot governs only the SEPARATE top-level
368
- // (curated-direct) promotion. A lean tool is surfaced under its enabled expose `as` if one exists,
369
- // else the namespaced default `<upstream>_<tool>` — so the lean name equals the curated-direct name
370
- // for an exposed tool and ONE PreToolUse rule gates both routes. All of this lives here in the
371
- // aggregator (it owns the connections, the _clients/_tools caches, and the connect log chokepoint).
372
-
373
- /**
374
- * The single forward seam: a thunk that calls the upstream's real tool. Shared by the
375
- * curated-direct path (resolveExposedExecution, transparent envelope passthrough) and the lean
376
- * path (resolveLeanExecution, which unwraps). Kept tiny so both routes execute identically.
377
- * @param {object} client a connected McpClient
378
- * @param {string} realTool the upstream's own tool name
379
- * @param {any} args
380
- * @returns {() => Promise<any>}
381
- */
382
- _forwardExecutor(client, realTool, args) {
383
- return () => client.callTool(realTool, args);
384
- }
385
-
386
- /**
387
- * The downstream name a discovered upstream tool is surfaced under: its ENABLED expose `as` if one
388
- * exists for (upstream, tool), else the namespaced default `<upstream>_<tool>` (matching
389
- * expose-store.exposedName). Keeps the lean list and the lean run path in agreement, and aligns an
390
- * exposed tool's lean name with its curated-direct top-level name. Never throws.
391
- * @param {string} upstreamId
392
- * @param {string} toolName
393
- * @returns {string}
394
- */
395
- _surfacedName(upstreamId, toolName) {
396
- try {
397
- const exposed = this._store.listExposed({ enabledOnly: true });
398
- for (const e of exposed) {
399
- if (e && e.upstream === upstreamId && e.tool === toolName) return this._store.exposedName(e);
400
- }
401
- } catch (_e) {
402
- /* fall through to the default */
403
- }
404
- return `${upstreamId}_${toolName}`;
405
- }
406
-
407
- /**
408
- * Connect an upstream ON DEMAND and return the ready McpClient. Idempotent + race-safe:
409
- * - fast path: a cached client that is still `connected` is returned as-is; a cached-but-DEAD
410
- * client (its child exited — McpClient flips `connected` but stays in the cache) is logged as a
411
- * disconnect, discarded, and reconnected — a reconnect re-lists the upstream's tools.
412
- * - concurrent callers JOIN the same in-flight connect promise (keyed in _connecting), which
413
- * resolves only AFTER _listAndCache — so no caller ever sees the half-built client that
414
- * _connectOne caches BEFORE the handshake completes (the double-spawn / mid-handshake race).
415
- * Throws on an unknown/disabled upstream or a connect/list failure (the caller surfaces it; for the
416
- * lean run path that means gatedRun returns { ok:false, error } cleanly).
417
- * @param {string} upstreamId
418
- * @returns {Promise<object>} the connected McpClient
419
- */
420
- async ensureConnected(upstreamId, opts) {
421
- if (!isNonEmptyString(upstreamId)) throw new Error('Aggregator.ensureConnected: upstreamId (non-empty string) is required');
422
- // allowConnect:false (the RUN path) must NEVER block on a connect — not a from-scratch connect
423
- // (connect()+tools/list, ~20s, would freeze the serialized stdio chain and starve pings) AND not
424
- // by JOINING an in-flight background reconnect (same latency). It returns a live client or fails
425
- // clean; the background reconnect owns recovery and the run retries next turn. allowConnect
426
- // defaults true (the background path connects / joins).
427
- const allowConnect = !(opts && opts.allowConnect === false);
428
- // A torn-down aggregator (swapped out by reloadExpose, then closeAll'd) must NEVER (re)connect:
429
- // a captured execute thunk holding this instance would otherwise spawn an ORPHAN child on it.
430
- if (this._closed) throw new Error('Aggregator.ensureConnected: aggregator is closed (config reloaded) — retry on the current one');
431
-
432
- // Fast path: a live cached client serves BOTH modes immediately.
433
- const existing = this._clients.get(upstreamId);
434
- if (existing) {
435
- const alive = typeof existing.connected === 'boolean' ? existing.connected : true;
436
- if (alive) return existing;
437
- // Dead cached client. The RUN path fails clean (never (re)connects); the background path drops
438
- // it and reconnects below.
439
- if (!allowConnect) {
440
- throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" disconnected (reconnecting in background)`);
441
- }
442
- logger.log({ type: 'mcp', event: 'disconnect', upstream: upstreamId, reason: 'stale' });
443
- this._discard(upstreamId);
444
- } else if (!allowConnect) {
445
- // Not connected. The RUN path neither connects NOR joins an in-flight connect — joining would
446
- // block the stdio chain for the connect+list latency (the head-of-line freeze this mode avoids).
447
- throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" is not connected (reconnecting in background)`);
448
- }
449
-
450
- // Background path only (allowConnect): join an in-flight connect, else connect from scratch. The
451
- // _connecting promise resolves only AFTER _listAndCache, so _connectOne caching the client before
452
- // its handshake completes never exposes a half-built client to a joiner.
453
- if (this._connecting.has(upstreamId)) return this._connecting.get(upstreamId);
454
-
455
- const upstream = this._store.getUpstream(upstreamId);
456
- if (!upstream) throw new Error(`Aggregator.ensureConnected: unknown upstream "${upstreamId}"`);
457
- if (upstream.enabled !== true) throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" is disabled`);
458
-
459
- const promise = (async () => {
460
- await this._connectOne(upstream); // caches client + tools, logs the connect
461
- return this._clients.get(upstreamId);
462
- })();
463
- this._connecting.set(upstreamId, promise);
464
- try {
465
- return await promise;
466
- } catch (err) {
467
- this._discard(upstreamId); // reap the half-spawned child; leave no zombie/cache entry
468
- throw err;
469
- } finally {
470
- this._connecting.delete(upstreamId);
471
- }
472
- }
473
-
474
- /**
475
- * UNEXPECTED upstream death (fired by McpClient.onClose). Log it, drop the dead client so it
476
- * leaves the lean list, tell the client the tool set shrank, then schedule a BACKGROUND reconnect.
477
- * Keeping recovery off the serialized stdio chain is what closes the head-of-line regression: a run
478
- * during the down-window fails clean (ensureConnected allowConnect:false) instead of blocking.
479
- * @param {string} upstreamId
480
- */
481
- _handleUpstreamDown(upstreamId) {
482
- if (this._closed) return;
483
- logger.log({ type: 'mcp', event: 'disconnect', upstream: upstreamId, reason: 'died' });
484
- this._discard(upstreamId); // remove the dead client + its tools → drops from the lean list
485
- this._signalToolsChanged(upstreamId); // list_changed only if the upstream is on the top-level surface
486
- this._scheduleReconnect(upstreamId, 0);
487
- }
488
-
489
- /**
490
- * Does this upstream contribute to the TOP-LEVEL tools/list (i.e. has an ENABLED expose[] entry)?
491
- * Only then does its death/recovery change tools/list and warrant a notifications/tools/list_changed.
492
- * A lean-only upstream's tools live behind toolfunnel_list_tools (pulled per call), so notifying for
493
- * one is spurious (the client re-fetches and sees no diff). Never throws.
494
- * @param {string} upstreamId
495
- * @returns {boolean}
496
- */
497
- _affectsTopLevel(upstreamId) {
498
- try {
499
- return this._store.listExposed({ enabledOnly: true }).some((e) => e && e.upstream === upstreamId);
500
- } catch (_e) {
501
- return false;
502
- }
503
- }
504
-
505
- /** Fire onToolsChanged ONLY when the upstream is actually on the top-level surface (else the
506
- * notification is spurious — its lean tools refresh on the next toolfunnel_list_tools). Never throws. */
507
- _signalToolsChanged(upstreamId) {
508
- if (!this._affectsTopLevel(upstreamId)) return;
509
- try { this.onToolsChanged(); } catch (_e) { /* never throw out of an event handler */ }
510
- }
511
-
512
- /**
513
- * Schedule ONE background reconnect attempt with exponential backoff: 1s,2s,4s,8s,16s, then capped
514
- * at 30s. After the fast phase it does NOT give up — it falls back to a slow 30s keepalive so a long
515
- * transient outage still self-heals (a detached/disabled upstream stops it via getUpstream; closeAll
516
- * stops it via _closed). On success the tools are re-listed and a top-level change is signalled. One
517
- * timer per upstream (no pile-up); the timer is unref'd so it never keeps the process alive. NEVER throws.
518
- * @param {string} upstreamId
519
- * @param {number} attempt
520
- */
521
- _scheduleReconnect(upstreamId, attempt) {
522
- if (this._closed) return;
523
- if (this._reconnectTimers.has(upstreamId)) return; // a reconnect is already pending for this id
524
- const upstream = this._store.getUpstream(upstreamId);
525
- if (!upstream || upstream.enabled !== true) return; // detached/disabled — stop trying
526
- const MAX_FAST_ATTEMPTS = 6; // exponential phase; beyond it, a slow keepalive at the 30s cap
527
- const delay = Math.min(1000 * Math.pow(2, attempt), 30000);
528
- const timer = setTimeout(async () => {
529
- this._reconnectTimers.delete(upstreamId);
530
- if (this._closed) return;
531
- const u = this._store.getUpstream(upstreamId);
532
- if (!u || u.enabled !== true) return;
533
- try {
534
- await this.ensureConnected(upstreamId); // allowConnect default — connects + re-lists, off-chain
535
- logger.log({ type: 'mcp', event: 'reconnect', upstream: upstreamId, attempt });
536
- this._signalToolsChanged(upstreamId);
537
- } catch (err) {
538
- logger.log({ type: 'mcp', event: 'reconnect_failed', upstream: upstreamId, attempt, error: errMsg(err) });
539
- // Log the fast→slow transition exactly ONCE — when the counter FIRST reaches the cap. The
540
- // old guard sat on the re-entry side, where the capped counter re-satisfied it every 30s
541
- // forever against a permanently-dead upstream (log spam, not information).
542
- if (attempt + 1 === MAX_FAST_ATTEMPTS) {
543
- logger.log({ type: 'mcp', event: 'reconnect_slow', upstream: upstreamId, attempts: MAX_FAST_ATTEMPTS });
544
- }
545
- // Keep escalating to the cap, then keep retrying slowly (cap the counter so the delay stays
546
- // at 30s) — never permanently give up while the upstream stays enabled.
547
- this._scheduleReconnect(upstreamId, Math.min(attempt + 1, MAX_FAST_ATTEMPTS));
548
- }
549
- }, delay);
550
- if (timer && typeof timer.unref === 'function') timer.unref();
551
- this._reconnectTimers.set(upstreamId, timer);
552
- }
553
-
554
- /**
555
- * The LEAN tool definitions: every discovered tool of every CONNECTED + enabled upstream, surfaced
556
- * for toolfunnel_list_tools. Each: { name, description, inputSchema, upstream, tool }. The FULL
557
- * discovered set (not just expose[]) — attaching an MCP makes its tools appear leanly with no
558
- * curation. Only connected upstreams contribute (we need their real schemas); a not-yet-connected
559
- * upstream's tools simply appear once it connects (the next list call reflects it — no
560
- * notification needed, the lean surface is delivered inside a per-call meta-tool). Never throws.
561
- * @returns {Array<{name:string, description:string, inputSchema:object, upstream:string, tool:string}>}
562
- */
563
- leanToolDefinitions() {
564
- const defs = [];
565
- const seen = new Set(); // surfaced-name collision guard — the list must agree with resolve (first wins)
566
- try {
567
- for (const [upstreamId, tools] of this._tools) {
568
- if (!this._clients.has(upstreamId)) continue; // connected only
569
- const upstream = this._store.getUpstream(upstreamId);
570
- if (upstream && upstream.enabled === false) continue; // skip an explicitly-disabled upstream
571
- if (!Array.isArray(tools)) continue;
572
- for (const t of tools) {
573
- if (!t || !isNonEmptyString(t.name)) continue;
574
- const name = this._surfacedName(upstreamId, t.name);
575
- if (seen.has(name)) {
576
- // Two tools collapse to one surfaced name (underscore ambiguity, or a duplicate `as`).
577
- // resolveLeanExecution returns the FIRST match, so advertise only the first — the list
578
- // must never show a name that resolves to a different tool. Log the shadowing.
579
- logger.log({ type: 'mcp', event: 'name_collision', upstream: upstreamId, tool: t.name, surfaced: name });
580
- continue;
581
- }
582
- seen.add(name);
583
- const schema = t.inputSchema && typeof t.inputSchema === 'object' ? t.inputSchema : { type: 'object' };
584
- defs.push({
585
- name,
586
- description: isNonEmptyString(t.description) ? t.description : '',
587
- inputSchema: cloneJson(schema),
588
- upstream: upstreamId,
589
- tool: t.name,
590
- });
591
- }
592
- }
593
- } catch (_e) {
594
- /* never throw out of a definition build — return what we have */
595
- }
596
- return defs;
597
- }
598
-
599
- /**
600
- * Resolve a lean downstream name + args into a forwarding executor for toolfunnel_run_tool. Matches
601
- * by ITERATION over discovered tools (computing each tool's surfaced name) — never by parsing the
602
- * name (underscore-ambiguous). The execute thunk lazy-(re)connects via ensureConnected and UNWRAPS
603
- * the upstream MCP envelope to a clean payload, so run_tool returns the upstream's content (e.g.
604
- * "pong"), not a stringified envelope. The connect is INSIDE the thunk → a PreToolUse deny spawns
605
- * nothing. The gate matches `toolName` (the surfaced name). Returns null if no connected upstream
606
- * advertises a tool with this surfaced name (→ protocol's clean "not runnable" error).
607
- * @param {string} name surfaced downstream name
608
- * @param {any} args
609
- * @returns {{ execute: () => Promise<any>, toolName: string, upstream: string } | null}
610
- */
611
- resolveLeanExecution(name, args) {
612
- if (!isNonEmptyString(name)) return null;
613
- for (const [upstreamId, tools] of this._tools) {
614
- if (!this._clients.has(upstreamId)) continue;
615
- if (!Array.isArray(tools)) continue;
616
- for (const t of tools) {
617
- if (!t || !isNonEmptyString(t.name)) continue;
618
- if (this._surfacedName(upstreamId, t.name) !== name) continue;
619
- const realTool = t.name;
620
- const self = this;
621
- const execute = async () => {
622
- // allowConnect:false — the run path NEVER synchronously (re)connects (that would freeze the
623
- // stdio loop, starving pings). It uses a live client or joins an in-flight background
624
- // reconnect, else fails clean; the onClose-driven background reconnect owns recovery.
625
- const client = await self.ensureConnected(upstreamId, { allowConnect: false });
626
- const envelope = await client.callTool(realTool, args);
627
- // Preserve the upstream's failure signal. callTool RESOLVES even on isError:true, so a
628
- // failed upstream call must become a THROW → gatedRun returns { ok:false } → run_tool
629
- // surfaces isError:true. Otherwise a failed call would be reported as success — and the
630
- // lean path must agree with curated-direct's isError passthrough.
631
- const payload = unwrapEnvelope(envelope);
632
- if (envelope && typeof envelope === 'object' && envelope.isError === true) {
633
- const text = typeof payload === 'string' ? payload : safeStringify(payload);
634
- const err = new Error(text && text.length ? text : 'upstream tool reported an error');
635
- err.upstreamToolError = true;
636
- throw err;
637
- }
638
- return payload;
639
- };
640
- return { execute, toolName: name, upstream: upstreamId };
641
- }
642
- }
643
- return null;
644
- }
645
-
646
- /**
647
- * Close every cached client and clear the caches. Idempotent — safe to call twice and
648
- * safe when nothing was ever connected. NEVER throws (close() on McpClient never throws).
649
- * @returns {Promise<void>}
650
- */
651
- async closeAll() {
652
- this._closed = true; // latch BEFORE teardown so any in-flight execute thunk refuses to re-spawn
653
- for (const [, timer] of this._reconnectTimers) {
654
- try { clearTimeout(timer); } catch (_e) { /* ignore */ }
655
- }
656
- this._reconnectTimers.clear();
657
- for (const [id, client] of this._clients) {
658
- try {
659
- if (client && typeof client.close === 'function') client.close();
660
- // Activity log (self-gating): the disconnect half. A reload closes the old aggregator here,
661
- // so a reconnect reads as a disconnect line followed by a connect line for the same id.
662
- logger.log({ type: 'mcp', event: 'disconnect', upstream: id });
663
- } catch (_e) {
664
- /* McpClient.close never throws, but never let teardown sink the loop */
665
- }
666
- }
667
- this._clients.clear();
668
- this._tools.clear();
669
- }
670
-
671
- // ── internals ──────────────────────────────────────────────────────────────
672
-
673
- /**
674
- * Connect a single upstream entry and cache the client + its discovered tools.
675
- * Throws on factory (isolation), connect, or listTools failure — callers decide
676
- * whether to collect (connectAll) or surface (discover) the error. On throw, the
677
- * caller is responsible for _discard()-ing the id.
678
- * @param {object} upstream a normalised ExposeStore upstream
679
- */
680
- async _connectOne(upstream) {
681
- // The factory may throw (isolation guard) — that propagates out as a connect failure. Pass an
682
- // onClose so an UNEXPECTED upstream death triggers a BACKGROUND reconnect (not a lazy one in the
683
- // run path, which would freeze the stdio chain).
684
- const client = this._clientFactory(upstream, () => this._handleUpstreamDown(upstream.id));
685
- if (!client || typeof client.connect !== 'function') {
686
- throw new Error(`clientFactory returned an invalid client for "${upstream.id}"`);
687
- }
688
- // Cache the client BEFORE connect so a connect-failure path can still _discard() and
689
- // close any half-spawned child.
690
- this._clients.set(upstream.id, client);
691
- await client.connect();
692
- await this._listAndCache(upstream.id);
693
- // Activity log (self-gating; no-op unless logging is enabled): the upstream half of connect
694
- // logging. EVERY connect flows through here — startup connectAll, a live reload, a lazy
695
- // discover, and (later) a health-driven reconnect — so all of them are logged uniformly.
696
- logger.log({
697
- type: 'mcp',
698
- event: 'connect',
699
- upstream: upstream.id,
700
- command: upstream.command,
701
- tools: (this._tools.get(upstream.id) || []).length,
702
- });
703
- }
704
-
705
- /** tools/list one connected upstream and cache the result; returns a clone. */
706
- async _listAndCache(upstreamId) {
707
- const client = this._clients.get(upstreamId);
708
- if (!client) throw new Error(`no connected client for "${upstreamId}"`);
709
- const tools = await client.listTools();
710
- const safe = Array.isArray(tools) ? tools.filter((t) => t && isNonEmptyString(t.name)) : [];
711
- this._tools.set(upstreamId, safe);
712
- return cloneTools(safe);
713
- }
714
-
715
- /** Tear down + forget a cached client (used on a failed connect). Never throws. */
716
- _discard(upstreamId) {
717
- const client = this._clients.get(upstreamId);
718
- if (client && typeof client.close === 'function') {
719
- try { client.close(); } catch (_e) { /* never throw */ }
720
- }
721
- this._clients.delete(upstreamId);
722
- this._tools.delete(upstreamId);
723
- }
724
-
725
- /**
726
- * Shared lookup behind isExposed / resolveExposedExecution: find the ENABLED expose
727
- * entry whose downstream name === `name`, whose upstream is connected, and whose real
728
- * tool the upstream advertises. Returns the resolution context or null.
729
- * @param {string} name
730
- * @returns {{ client:object, realTool:string, upstream:string, exposedName:string } | null}
731
- */
732
- _findExposedExecution(name) {
733
- if (!isNonEmptyString(name)) return null;
734
- let exposed;
735
- try {
736
- exposed = this._store.listExposed({ enabledOnly: true });
737
- } catch (_err) {
738
- return null;
739
- }
740
- for (const e of exposed) {
741
- if (!e) continue;
742
- if (this._store.exposedName(e) !== name) continue;
743
- const client = this._clients.get(e.upstream);
744
- if (!client) continue; // upstream not connected
745
- const upstreamTools = this._tools.get(e.upstream) || [];
746
- if (!upstreamTools.some((t) => t && t.name === e.tool)) continue; // tool not advertised
747
- return { client, realTool: e.tool, upstream: e.upstream, exposedName: name };
748
- }
749
- return null;
750
- }
751
- }
752
-
753
- // ── small helpers (no external deps) ───────────────────────────────────────────
754
-
755
- /** Extract a clean message from any thrown value. */
756
- function errMsg(err) {
757
- return (err && err.message) || String(err);
758
- }
759
-
760
- /** JSON.stringify that never throws (circular/oddball values fall back to String). */
761
- function safeStringify(value) {
762
- try { return JSON.stringify(value); } catch (_e) { return String(value); }
763
- }
764
-
765
- /**
766
- * Turn an upstream MCP tools/call envelope { content:[...], isError? } into a clean payload for the
767
- * LEAN run path. A single text block -> its string (so toolfunnel_run_tool returns "pong", matching
768
- * what the curated-direct content passthrough surfaces); otherwise the content array; otherwise the
769
- * value as-is when it isn't an envelope. This is what avoids double-wrapping the envelope as JSON
770
- * inside wrapProtocolResult (the curated-direct path passes the envelope through transparently
771
- * instead; the lean path goes through protocol.runTool -> wrapProtocolResult, so it unwraps here).
772
- * NOTE (slice 2): an upstream isError:true is surfaced as its text content with ok:true (homogeneous
773
- * with how local tools surface error text) — mapping isError -> ok:false is a later concern.
774
- * @param {*} envelope
775
- * @returns {*}
776
- */
777
- function unwrapEnvelope(envelope) {
778
- if (!envelope || typeof envelope !== 'object') return envelope;
779
- const content = envelope.content;
780
- if (Array.isArray(content)) {
781
- if (content.length === 1 && content[0] && content[0].type === 'text' && typeof content[0].text === 'string') {
782
- return content[0].text;
783
- }
784
- return content;
785
- }
786
- return envelope;
787
- }
788
-
789
- /** Plain-JSON deep clone (schemas are JSON; structuredClone may be absent on old node). */
790
- function cloneJson(value) {
791
- return JSON.parse(JSON.stringify(value));
792
- }
793
-
794
- /** Clone an array of tool defs so callers can't mutate the aggregator's cache. */
795
- function cloneTools(tools) {
796
- return Array.isArray(tools) ? tools.map((t) => cloneJson(t)) : [];
797
- }
798
-
799
- module.exports = {
800
- Aggregator,
801
- // exported for unit tests / reuse
802
- defaultClientFactory,
803
- looksLikePath,
804
- isInside,
805
- unwrapEnvelope,
806
- DEFAULT_ROOT,
807
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * aggregator.js - the upstream-MCP connection + curated-expose layer.
5
+ *
6
+ * The aggregator is the bridge between the persisted MCP config (src/mcp/expose-store.js)
7
+ * and the live upstream MCP servers (src/mcp/mcp-client.js). It:
8
+ *
9
+ * 1. CONNECTS one McpClient per ENABLED upstream in the ExposeStore (connectAll),
10
+ * caching the connected client + its discovered tools. A failed upstream never
11
+ * sinks the others - failures are collected, not thrown.
12
+ * 2. DISCOVERS an upstream's tool surface on demand (discover) - what the MCP
13
+ * Manager UI's 'discover' button calls.
14
+ * 3. Computes the CURATED-DIRECT tool definitions to advertise downstream
15
+ * (exposedToolDefinitions) - only for ENABLED expose[] entries whose upstream
16
+ * is connected, enabled, AND actually advertises the named tool. Each definition is
17
+ * renamed to its downstream `as` name (what the CLI / PreToolUse matchers see).
18
+ * 4. RESOLVES a downstream call back to its upstream client + real tool name
19
+ * (resolveExposedExecution) - the seam the MCP server's curated-direct call
20
+ * path uses to actually execute, AFTER the hook gate has run.
21
+ *
22
+ * Decoupling note: downstream the CLI sees the renamed `as` tool; upstream we call
23
+ * the REAL tool name. resolveExposedExecution carries BOTH so the gate (PreToolUse)
24
+ * matches on the downstream name while execution hits the real upstream.
25
+ *
26
+ * SAFETY CONTRACT (mirrors expose-store.js / mcp-client.js):
27
+ * - connectAll / discover / closeAll NEVER throw. connectAll collects per-upstream
28
+ * failures into failed[]; a dead/misconfigured upstream cannot crash the server
29
+ * start. closeAll is idempotent and tears down every cached client.
30
+ * - The DEFAULT clientFactory enforces the HARD ISOLATION rule: a vendored upstream
31
+ * may only reference CODE/FILES inside the gateway root. The
32
+ * guard is applied to the ARGS (the script path, db files, ... that the interpreter
33
+ * is pointed at): any arg that is an absolute path, or that looks like a file path
34
+ * (contains a path separator), MUST resolve inside gatewayRoot - otherwise the factory
35
+ * throws and connectAll records the upstream in failed[]. The COMMAND slot is the
36
+ * interpreter/executable (node, npx, or an absolute path to a node binary that by
37
+ * definition lives OUTSIDE the project, e.g. process.execPath / a system node.exe)
38
+ * and is therefore NOT subject to the in-sandbox requirement - bare commands AND an
39
+ * absolute interpreter path are both allowed. Isolation is about WHAT CODE runs in
40
+ * the spawned process, not which interpreter binary runs it; the args are that code.
41
+ * This is what stops a config from pointing at a live `.mcp.json` server's script
42
+ * outside the sandbox while still letting the system node interpreter spawn it.
43
+ *
44
+ * CommonJS only. Node built-ins only. No new npm dependency. No @modelcontextprotocol/sdk.
45
+ */
46
+
47
+ const path = require('node:path');
48
+
49
+ const { McpClient, PROTOCOL_VERSION: LEGACY_UPSTREAM_VERSION } = require('./mcp-client');
50
+ const logger = require('../core/logger');
51
+
52
+ // The sandbox root = the CONFIG HOME (TOOLFUNNEL_HOME / --config-dir; defaults to the package
53
+ // root - see src/core/config-home.js). Used as the isolation boundary the default clientFactory
54
+ // enforces: a pack's path-shaped upstream args live under the home, so the home is the boundary.
55
+ // A caller may override via opts.gatewayRoot for tests.
56
+ const { resolveConfigHome } = require('../core/config-home');
57
+ const DEFAULT_ROOT = resolveConfigHome();
58
+
59
+ /** True for a non-empty string. */
60
+ function isNonEmptyString(v) {
61
+ return typeof v === 'string' && v.length > 0;
62
+ }
63
+
64
+ /**
65
+ * Does this argv token LOOK like a file path? An absolute path (path.isAbsolute) or
66
+ * any token containing a path separator ('/' or '\\') is treated as a path reference
67
+ * and must be confined to gatewayRoot. A bare token like 'node', 'npx', 'server' or a flag
68
+ * like '--port' is NOT a path and is always allowed.
69
+ * @param {string} arg
70
+ * @returns {boolean}
71
+ */
72
+ function looksLikePath(arg) {
73
+ if (!isNonEmptyString(arg)) return false;
74
+ if (path.isAbsolute(arg)) return true;
75
+ // win32 DRIVE-RELATIVE form ('C:foo.js') - path.win32.isAbsolute() is false for it and it holds
76
+ // no separator, so without this it looked like a bare token and skipped the guard entirely.
77
+ if (/^[A-Za-z]:/.test(arg)) return true;
78
+ return arg.indexOf('/') !== -1 || arg.indexOf('\\') !== -1;
79
+ }
80
+
81
+ /**
82
+ * The path-shaped candidates inside a single argv token. A runtime option in `--flag=value` form
83
+ * (node's --require=, --import=, --experimental-loader=, and their Deno/Bun kin) interprets only
84
+ * the part AFTER the first '=' as a path. The whole token '--require=../x.js' carries no '..'
85
+ * segment of its own, so a check of the token alone judges it inside the root while the child
86
+ * resolves the value and leaves it. So the value after the first '=' is returned as its own
87
+ * candidate, checked alongside the whole token. A non-path value ('--port=8080') simply fails
88
+ * looksLikePath() and is ignored; an inside value still resolves inside and passes.
89
+ * @param {string} arg
90
+ * @returns {string[]}
91
+ */
92
+ function argPathCandidates(arg) {
93
+ if (!isNonEmptyString(arg)) return [];
94
+ const out = [arg];
95
+ const eq = arg.indexOf('=');
96
+ if (eq !== -1 && eq < arg.length - 1) out.push(arg.slice(eq + 1));
97
+ return out;
98
+ }
99
+
100
+ /**
101
+ * Is this a win32 DRIVE-RELATIVE reference ('C:foo', drive letter + colon + no separator)?
102
+ * It resolves against the CHILD's per-drive current directory - a base the guard cannot pin -
103
+ * so it can never be PROVEN inside the root: path.resolve(root, 'C:x') judges it optimistically
104
+ * when root shares the drive. There is no legitimate in-sandbox use (an inside path can always
105
+ * be written absolutely or plainly relative), so it is refused outright wherever paths are
106
+ * guarded. Checked on every platform: a config is portable and gets run somewhere else.
107
+ * @param {string} t
108
+ * @returns {boolean}
109
+ */
110
+ function isDriveRelative(t) {
111
+ return /^[A-Za-z]:(?![\\/])/.test(t);
112
+ }
113
+
114
+ // Environment variables that make a child load code, whatever its args say (0.7.0). Two classes with two rules. All platforms' vars are checked on all platforms because
115
+ // a config is portable and gets run somewhere else, and keys are compared CASE-INSENSITIVELY
116
+ // everywhere because Windows env lookup is case-insensitive - `node_options` reaches the child
117
+ // exactly as `NODE_OPTIONS` does, so an exact-case allowlist was a one-character bypass there.
118
+ //
119
+ // OPTION-STRING vars are a mini command line in the runtime's OWN grammar: quoting, `=` forms,
120
+ // `file:`/`data:` URLs, inspector flags. A path-shaped guard cannot verify them (quoted
121
+ // values, URL specifiers and a bare `--inspect` all defeat any tokeniser written here),
122
+ // and a guard that cannot verify must refuse, not guess. Refused outright in funnel mode; the
123
+ // operator's deliberate opt-out is `allowCodeLoadingEnv: true` on the upstream entry (the
124
+ // legacyPin pattern - off by default, visible in config, warned when it excuses something).
125
+ const CODE_OPT_ENV = [
126
+ 'NODE_OPTIONS',
127
+ 'JAVA_TOOL_OPTIONS',
128
+ '_JAVA_OPTIONS',
129
+ 'PERL5OPT',
130
+ 'RUBYOPT',
131
+ ];
132
+ // PATH / PATH-LIST vars name locations directly and ARE checkable: extract pieces, judge each
133
+ // against the root. This list is a FLOOR, not a boundary - runtimes keep minting code-loading
134
+ // vars, and the `command` slot is arbitrary by design (see SECURITY.md: the guard is a tripwire
135
+ // for out-of-root references in an auditable config home, not a sandbox against an untrusted
136
+ // pack author).
137
+ const CODE_PATH_ENV = [
138
+ 'NODE_PATH',
139
+ 'NODE_REPL_EXTERNAL_MODULE',
140
+ 'LD_PRELOAD',
141
+ 'LD_LIBRARY_PATH',
142
+ 'LD_AUDIT',
143
+ 'DYLD_INSERT_LIBRARIES',
144
+ 'DYLD_LIBRARY_PATH',
145
+ 'DYLD_FRAMEWORK_PATH',
146
+ 'PYTHONPATH',
147
+ 'PYTHONSTARTUP',
148
+ 'PYTHONHOME',
149
+ 'PYTHONEXECUTABLE',
150
+ 'PERL5LIB',
151
+ 'RUBYLIB',
152
+ 'GEM_PATH',
153
+ 'CLASSPATH',
154
+ 'BASH_ENV',
155
+ 'ENV',
156
+ 'DOTNET_STARTUP_HOOKS',
157
+ 'CORECLR_PROFILER_PATH',
158
+ ];
159
+
160
+ /**
161
+ * Is `target` inside `root` (or equal to it)? Compares fully-resolved, normalised
162
+ * absolute paths. A relative `target` is resolved AGAINST root (so 'vendor/x/server.js'
163
+ * checks the in-sandbox location). Returns false for anything that escapes root via
164
+ * '..' or an absolute path elsewhere on disk.
165
+ * @param {string} root absolute sandbox root
166
+ * @param {string} target path token (absolute or relative)
167
+ * @returns {boolean}
168
+ */
169
+ function isInside(root, target) {
170
+ const resolvedRoot = path.resolve(root);
171
+ // An absolute target is checked as-is; a relative one is resolved within the root so
172
+ // a vendored relative path ('vendor/foo/server.js') is judged at its in-sandbox spot.
173
+ const resolvedTarget = path.isAbsolute(target)
174
+ ? path.resolve(target)
175
+ : path.resolve(resolvedRoot, target);
176
+ const rel = path.relative(resolvedRoot, resolvedTarget);
177
+ // Inside iff the relative path neither starts with '..' nor is itself absolute
178
+ // (an absolute `rel` happens on win32 across drive letters). '' (equal) counts as inside.
179
+ return rel === '' || (!rel.startsWith('..' + path.sep) && rel !== '..' && !path.isAbsolute(rel));
180
+ }
181
+
182
+ /**
183
+ * The DEFAULT clientFactory. Constructs a McpClient for an upstream entry AFTER
184
+ * enforcing the isolation guard on the ARGS: every arg that looks like a file path
185
+ * (an absolute path, or any token containing a path separator) must resolve inside
186
+ * `gatewayRoot`. Throws a clear 'isolation: ...' error otherwise - connectAll catches that
187
+ * into failed[].
188
+ *
189
+ * The COMMAND slot is intentionally NOT guarded: it names the interpreter/executable
190
+ * (e.g. 'node', 'npx', or an absolute path to a node binary such as process.execPath /
191
+ * a system node.exe) which by definition lives OUTSIDE the project. Isolation is about
192
+ * WHAT CODE the spawned process runs - that is the args (the server script + any data
193
+ * files it loads) - not which interpreter binary launches it. Guarding the command too
194
+ * would wrongly reject every vendored upstream the moment it is run by the system node.
195
+ *
196
+ * @param {object} upstream a normalised ExposeStore upstream { id, command, args, env, ... }
197
+ * @param {string} gatewayRoot the sandbox root the upstream's path-shaped ARGS must stay inside
198
+ * @returns {McpClient}
199
+ */
200
+ function defaultClientFactory(upstream, gatewayRoot, onClose, allowOutsidePaths, clientInfo, eraHint) {
201
+ const id = isNonEmptyString(upstream && upstream.id) ? upstream.id : '(unknown)';
202
+ const args = Array.isArray(upstream && upstream.args) ? upstream.args : [];
203
+ // The caller passes TRUE for the wrapped upstream; the upstream may also claim the exemption for
204
+ // itself in config. Either way it is decided HERE, per upstream, from THIS upstream's own entry -
205
+ // there is no shared or latched state, so one server's opt-out can never relax another's guard.
206
+ const outsideAllowed = allowOutsidePaths === true || (upstream && upstream.allowOutsidePaths === true);
207
+ const byConfig = allowOutsidePaths !== true && outsideAllowed;
208
+
209
+ // Guard every field that decides WHAT CODE the spawned process runs: path-shaped args, the cwd
210
+ // they resolve against, and the env vars that load code irrespective of args. The command
211
+ // (interpreter) is NOT guarded - see the function doc: it is the executable, not the code.
212
+ // allowOutsidePaths: TRUE only for the currently-WRAPPED upstream (transparent-wrapper mode -
213
+ // the operator explicitly made this server the entire surface, e.g. server-filesystem serving
214
+ // a documents folder). Warn instead of refuse; funnel-mode upstreams keep the hard guard.
215
+ // ONE notice per CLASS, not per upstream: `warnedPath` covers the path class (args + cwd); the
216
+ // env section below keeps its OWN flag. A single shared flag let the first path finding consume
217
+ // the only slot, so an env finding - the class that loads code - was excused in total silence,
218
+ // precisely for the operator who opted out and most needs the audit trail.
219
+ let warnedPath = false;
220
+ const refuse = (what) => {
221
+ if (outsideAllowed === true) {
222
+ if (!warnedPath) {
223
+ warnedPath = true;
224
+ // Name the REAL reason. Reporting a config opt-out as transparent-wrapper mode would put a
225
+ // false explanation in the operator's log for the one event they most need to trace.
226
+ process.stderr.write(byConfig
227
+ ? `[toolfunnel] isolation: upstream "${id}" reaches outside the gateway root (${what}) - ` +
228
+ `permitted because its config sets allowOutsidePaths:true. This upstream is NOT isolated ` +
229
+ `to the config home; every tool it serves runs with that exemption. Remove the flag to ` +
230
+ `restore the guard, or gate the tools with a PreToolUse hook.\n`
231
+ : `[toolfunnel] isolation: WRAPPED upstream "${id}" reaches outside the gateway root ` +
232
+ `(${what}) - permitted in transparent-wrapper mode. To restrict what it can do post-wrap, see the ` +
233
+ `manual's "Wrapping & security" section (PreToolUse gate, per-tool enabled:false).\n`);
234
+ }
235
+ return false; // permitted under the wrap, or by this upstream's own opt-out
236
+ }
237
+ throw new Error(`isolation: upstream ${id} references a path outside the gateway root`);
238
+ };
239
+
240
+ for (const arg of args) {
241
+ // Check the whole token AND the value after a '=' (the --flag=value form the child splits) -
242
+ // either escaping the root refuses the arg. The notice still names the whole token.
243
+ const escapes = argPathCandidates(arg).some(
244
+ (cand) => looksLikePath(cand) && (isDriveRelative(cand) || !isInside(gatewayRoot, cand))
245
+ );
246
+ if (escapes) {
247
+ if (refuse(`arg "${arg}"`) === false) break; // one notice covers the path class
248
+ }
249
+ }
250
+
251
+ // cwd - the SPAWN BASE (0.7.0). Guarded because it decides where a bare, separator-free arg like
252
+ // 'server.js' actually resolves: looksLikePath() is false for such a token so the loop above
253
+ // never sees it, while the child resolves it against cwd. Until 0.7.0 the comment below claimed
254
+ // guard-base and spawn-base "agree by construction" - true only while cwd was unset.
255
+ // Drive-relative gets the same outright refusal as everywhere else: 'C:denied' resolves
256
+ // against the child's per-drive current directory, and isInside() judging it against the root
257
+ // is optimistic-and-wrong whenever the root shares the drive.
258
+ if (isNonEmptyString(upstream && upstream.cwd)
259
+ && (isDriveRelative(upstream.cwd) || !isInside(gatewayRoot, upstream.cwd))) {
260
+ refuse(`cwd "${upstream.cwd}"`);
261
+ }
262
+
263
+ // env - CODE-LOADING variables (0.7.0). A value in any of these loads code
264
+ // into the child however clean the args are (reachable in-band: tf_mcp_add forwards env
265
+ // verbatim). Keys are matched CASE-INSENSITIVELY on every platform - Windows env lookup is
266
+ // case-insensitive, so `node_options` is `NODE_OPTIONS` to the child - and every platform's
267
+ // variable is checked on every platform: a pack authored on Linux gets run on Windows and back.
268
+ //
269
+ // `allowCodeLoadingEnv: true` on the upstream entry is the operator's explicit opt-out for the
270
+ // whole class: the finding downgrades to a once-per-upstream stderr warning naming the flag.
271
+ const envObj = upstream && typeof upstream.env === 'object' && upstream.env ? upstream.env : null;
272
+ if (envObj) {
273
+ const envAllowed = (upstream && upstream.allowCodeLoadingEnv === true);
274
+ // The env class's OWN notice flag - deliberately independent of `warnedPath` (see above).
275
+ let warnedEnv = false;
276
+ const envNotice = (why) => {
277
+ if (warnedEnv) return;
278
+ warnedEnv = true;
279
+ process.stderr.write(`[toolfunnel] isolation: upstream "${id}" sets code-loading env ${why}`);
280
+ };
281
+ // Which flag excuses an env finding depends on its KIND:
282
+ // 'opt' - option-string vars (NODE_OPTIONS et al.): not path-checkable, so ONLY the class's
283
+ // own flag (allowCodeLoadingEnv) or the WRAP excuses them. allowOutsidePaths does
284
+ // NOT: it is documented (expose-store) as args/cwd/path-list scope, and letting the
285
+ // path flag silently disarm this separately-audited class was a cross-flag grant
286
+ // the operator never made.
287
+ // 'path' - path-list vars (NODE_PATH et al.): inside the path flag's documented scope, so
288
+ // wrap, allowCodeLoadingEnv or allowOutsidePaths excuses - each loudly, by name.
289
+ const refuseEnv = (what, kind) => {
290
+ if (envAllowed) {
291
+ envNotice(`(${what}) - permitted by allowCodeLoadingEnv:true on this upstream. Remove the ` +
292
+ 'flag to restore the refusal.\n');
293
+ return false;
294
+ }
295
+ if (allowOutsidePaths === true) {
296
+ envNotice(`(${what}) - permitted in transparent-wrapper mode (this upstream IS the ` +
297
+ 'surface). To restrict it post-wrap, see the manual\'s "Wrapping & security" section.\n');
298
+ return false;
299
+ }
300
+ if (kind === 'path' && outsideAllowed === true) {
301
+ envNotice(`(${what}) - permitted because its config sets allowOutsidePaths:true ` +
302
+ '(path-list env is within that flag\'s scope). Remove the flag to restore the guard.\n');
303
+ return false;
304
+ }
305
+ throw new Error(`isolation: upstream ${id} sets code-loading env (${what})`);
306
+ };
307
+ // Enumerate EXACTLY as child_process does: `for...in`, which walks own AND INHERITED keys
308
+ // (node's normalizeSpawnArguments: "Prototype values are intentionally included"). An
309
+ // Object.keys() walk was blind to a `__proto__` carrier - JSON.parse makes `__proto__` an OWN
310
+ // data property, spread preserves it, and the client's Object.assign merge then uses [[Set]],
311
+ // firing the Object.prototype.__proto__ setter and installing the payload as the merged env's
312
+ // PROTOTYPE: invisible to Object.keys, delivered to the child.
313
+ for (const key in envObj) {
314
+ const upper = String(key).toUpperCase();
315
+ // A `__proto__` key is refused OUTRIGHT, whatever it carries. It is not an env var: it is
316
+ // the carrier that turns into the merged env's PROTOTYPE at the client's Object.assign, and
317
+ // from there into real variables for the child (for..in). Nothing legitimate needs it.
318
+ if (key === '__proto__') {
319
+ refuseEnv('env "__proto__" (a prototype carrier, not an environment variable)', 'opt');
320
+ continue;
321
+ }
322
+ // Judge the value as the spawn will USE it, not as it was authored. node builds each pair as
323
+ // `${key}=${value}`, so a one-element array becomes its element verbatim and a number becomes
324
+ // its digits. Testing isNonEmptyString FIRST let every non-string value skip both lists -
325
+ // again the guard reading a different representation than the consumer. A value that cannot
326
+ // even be coerced is unverifiable in a code-loading slot, so it is refused rather than
327
+ // skipped (the same rule the option-string class already follows).
328
+ const rawValue = envObj[key];
329
+ if (rawValue === undefined || rawValue === null) continue;
330
+ let raw;
331
+ try {
332
+ raw = typeof rawValue === 'string' ? rawValue : String(rawValue);
333
+ } catch (_e) {
334
+ if (CODE_OPT_ENV.includes(upper) || CODE_PATH_ENV.includes(upper)) {
335
+ refuseEnv(`env ${key} (value cannot be read as a string, so it cannot be verified)`,
336
+ CODE_OPT_ENV.includes(upper) ? 'opt' : 'path');
337
+ }
338
+ continue;
339
+ }
340
+ if (raw.length === 0) continue;
341
+ if (CODE_OPT_ENV.includes(upper)) {
342
+ // Not path-checkable (see the class doc above the lists) - the VALUE is irrelevant.
343
+ if (refuseEnv(`env ${key} (option-string vars are not path-checkable)`, 'opt') === false) continue;
344
+ continue;
345
+ }
346
+ if (!CODE_PATH_ENV.includes(upper)) continue;
347
+ // Path / path-list value: pieces are EXTRACTED (not split) so a drive-lettered piece
348
+ // ('C:\x', 'C:x') survives whole on every platform - splitting 'C:relative\denied' on ':'
349
+ // yields fragments that resolve inside the root while the child resolves the real path
350
+ // outside it. Both ';' and ':' end a piece everywhere (a POSIX filename containing ';'
351
+ // may be shredded and falsely refused - conservative, never a false allow).
352
+ const parts = (raw.match(/[A-Za-z]:[^;:]*|[^;:]+/g) || []).filter((t) => t.length > 0);
353
+ if (parts.length === 0) continue;
354
+ if (parts.some((t) => isDriveRelative(t) || !isInside(gatewayRoot, t))) {
355
+ refuseEnv(`env ${key}="${raw}"`, 'path');
356
+ }
357
+ }
358
+ }
359
+
360
+ return new McpClient({
361
+ id: upstream.id,
362
+ command: upstream.command,
363
+ args: upstream.args,
364
+ env: upstream.env,
365
+ // Child cwd from config - the wrap era-probe reads it too; it never survived the store
366
+ // before. Default = the CONFIG HOME (gatewayRoot), NOT the gateway's process cwd:
367
+ // the isolation guard above resolves relative args against the home, so the spawn must
368
+ // resolve them against the SAME base or a guard-passing relative path fails to spawn
369
+ // whenever --config-dir differs from the launch directory (guard-base and spawn-base agree
370
+ // by construction).
371
+ cwd: isNonEmptyString(upstream && upstream.cwd) ? upstream.cwd : gatewayRoot,
372
+ // Per-upstream `timeoutMs` config -> the client's PAYLOAD window (tools/call | prompts/get |
373
+ // resources/read; default 120 s).
374
+ toolTimeoutMs: Number.isFinite(upstream && upstream.timeoutMs) && upstream.timeoutMs > 0
375
+ ? upstream.timeoutMs : undefined,
376
+ // Per-upstream `requestTimeoutMs` config -> the CONTROL window (handshake/list/discover/
377
+ // ping; default 10 s = the dead-upstream detector). Opt-in for slow-boot servers that
378
+ // cannot answer initialize inside 10 s - without it they can never be attached at all.
379
+ requestTimeoutMs: Number.isFinite(upstream && upstream.requestTimeoutMs) && upstream.requestTimeoutMs > 0
380
+ ? upstream.requestTimeoutMs : undefined,
381
+ // legacyPin FORCES the legacy era: skip the modern server/discover probe and go straight to
382
+ // the initialize handshake, so a pinned upstream is genuinely spoken to as 2024-11-05 (the pin
383
+ // is an ENFORCED policy, not just a warning). Off by default.
384
+ forceLegacy: !!(upstream && upstream.legacyPin === true),
385
+ // modernOnly (legacyPin's mirror): refuse the legacy fallback - a non-modern upstream fails
386
+ // the connect with a clear error instead of negotiating down. Store validation refuses the
387
+ // legacyPin+modernOnly contradiction before it ever reaches here.
388
+ modernOnly: !!(upstream && upstream.modernOnly === true),
389
+ // The aggregator's era memo (last successful connect): 'legacy' lets a reconnect skip the
390
+ // server/discover probe. The client ignores it under modernOnly; the aggregator clears it on
391
+ // a failed connect and on an explicit reconnect().
392
+ eraHint: eraHint === 'legacy' ? 'legacy' : undefined,
393
+ // clientInfo: the identity presented to this upstream (identity mirroring / configured
394
+ // identity). null/undefined -> McpClient's built-in default, wire behaviour unchanged.
395
+ clientInfo: clientInfo || undefined,
396
+ onClose, // unexpected death -> the aggregator schedules a background reconnect
397
+ });
398
+ }
399
+
400
+ /**
401
+ * Aggregator - owns the live upstream connections and the curated-expose computation.
402
+ *
403
+ * Lifecycle: `new Aggregator({ store, gatewayRoot, clientFactory })`
404
+ * -> `await connectAll()` (or `await discover(id)` lazily)
405
+ * -> `exposedToolDefinitions()` / `resolveExposedExecution(name, args)`
406
+ * -> `await closeAll()` (idempotent).
407
+ */
408
+ class Aggregator {
409
+ /**
410
+ * @param {object} opts
411
+ * @param {object} opts.store an ExposeStore (the on-disk MCP config).
412
+ * @param {string} [opts.gatewayRoot] sandbox root for the isolation guard (default: the gateway root).
413
+ * @param {Function} [opts.clientFactory] (upstreamEntry, gatewayRoot) -> McpClient. Default enforces isolation.
414
+ * @param {Function} [opts.wrapTargetProvider] () -> the currently-WRAPPED upstream id (or null).
415
+ * Read fresh at each connect: the wrapped upstream is EXEMPT from the path-isolation
416
+ * guard (by design - a wrap is an explicit "this server IS my whole
417
+ * surface" declaration, so ToolFunnel is a transparent wrapper in that incidence; the
418
+ * operator gets a strong warning + post-wrap restriction docs instead of a refusal).
419
+ * Funnel-mode upstreams keep the guard unchanged.
420
+ * @param {Function} [opts.clientInfoProvider] (upstreamId) -> {name, version}|null. The identity
421
+ * to PRESENT to that upstream. Read fresh at each connect (same pattern as the wrap-target
422
+ * provider) so a mirror captured after boot is honoured by the next (re)connect. null ->
423
+ * McpClient's built-in default.
424
+ */
425
+ constructor({ store, gatewayRoot, clientFactory, onToolsChanged, wrapTargetProvider, clientInfoProvider } = {}) {
426
+ if (!store || typeof store !== 'object') {
427
+ throw new Error('Aggregator: a `store` (ExposeStore) is required');
428
+ }
429
+ this._store = store;
430
+ this._gatewayRoot = isNonEmptyString(gatewayRoot) ? gatewayRoot : DEFAULT_ROOT;
431
+ // Called when the LIVE tool set changes OUT OF BAND (a background reconnect recovers or finally
432
+ // loses an upstream) so the transport can emit notifications/tools/list_changed. Default no-op;
433
+ // the server wires it to emitToolsListChanged(send). Settable so reloadExpose can re-wire the
434
+ // new instance.
435
+ this.onToolsChanged = typeof onToolsChanged === 'function' ? onToolsChanged : () => {};
436
+ // Called with (upstreamId, notification) for each server-initiated CHANGE notification from an
437
+ // upstream (resources/updated, resources/list_changed, prompts/list_changed, tools/list_changed)
438
+ // so the transport can bridge it to a modern client's subscriptions/listen stream. Default no-op;
439
+ // the server/http host wires it. Settable so reloadExpose can re-wire the new instance.
440
+ this.onUpstreamNotification = () => {};
441
+ // Called with (upstreamId, requestMsg, client) for each SERVER-INITIATED REQUEST from an
442
+ // upstream (elicitation/create, sampling/createMessage, roots/list - the elicitation bridge). The handler
443
+ // owns answering via client.respondToServer(Error). Default: -32601, so an unwired build
444
+ // never leaves an upstream holding an open request. Settable; reloadExpose carries it over.
445
+ this.onUpstreamServerRequest = (uid, msg, client) => {
446
+ try { client.respondToServerError(msg.id, -32601, 'Method not found: ' + msg.method); } catch (_e) { /* never throw */ }
447
+ };
448
+ // When a passthrough WRAP is active, the wrapped upstream's request-scoped chatter
449
+ // (notifications/message, notifications/progress) also bridges - connected directly, the
450
+ // client would receive it. The server keeps this current with the live wrap state.
451
+ this.wrapChatterUpstream = null;
452
+ this._wrapTargetProvider = typeof wrapTargetProvider === 'function' ? wrapTargetProvider : null;
453
+ this._clientInfoProvider = typeof clientInfoProvider === 'function' ? clientInfoProvider : null;
454
+ // The factory receives (upstream, gatewayRoot, onClose). A caller-supplied factory may ignore the
455
+ // extra args; the default uses gatewayRoot for isolation and onClose for death-driven reconnect.
456
+ // The wrap-target check runs PER CONNECT (fresh provider read), so a wrap set after boot is
457
+ // honoured by the next connect attempt.
458
+ this._clientFactory =
459
+ typeof clientFactory === 'function'
460
+ ? (upstream, onClose) => clientFactory(upstream, this._gatewayRoot, onClose)
461
+ : (upstream, onClose) => defaultClientFactory(upstream, this._gatewayRoot, onClose,
462
+ this._isWrapTarget(upstream && upstream.id),
463
+ this._readClientInfo(upstream && upstream.id),
464
+ this._eraMemo.get(upstream && upstream.id));
465
+
466
+ /** @type {Map<string, object>} upstreamId -> connected McpClient */
467
+ this._clients = new Map();
468
+ /** @type {Map<string, Array>} upstreamId -> discovered tool defs [{name,description,inputSchema}] */
469
+ this._tools = new Map();
470
+ /** @type {Map<string, Promise>} upstreamId -> in-flight connect promise (race guard for ensureConnected) */
471
+ this._connecting = new Map();
472
+ /** @type {Set<string>} agreed resource-subscription URIs - replayed onto every (re)connect
473
+ * of a subscribe-capable legacy upstream so the channel survives reconnects */
474
+ this._subscribedUris = new Set();
475
+ /** @type {Map<string, number>} uri -> LISTEN-owned refcount. subscribeResources
476
+ * increments; releaseResources decrements and unsubscribes upstream at zero. The wrap-forward
477
+ * recording (a client's own resources/subscribe) writes the Set directly and is NOT counted
478
+ * here - the client manages that lifetime itself. */
479
+ this._subscribedRefs = new Map();
480
+ /** @type {Map<string, any>} upstreamId -> pending background-reconnect timer (one per upstream) */
481
+ this._reconnectTimers = new Map();
482
+ /** @type {Set<string>} upstreams whose reconnect ATTEMPT is currently executing (between the timer
483
+ * firing - which deletes its own entry from _reconnectTimers - and the attempt settling). While an
484
+ * id is in here, _handleUpstreamDown must NOT seed a fresh attempt-0: the in-flight attempt's own
485
+ * catch owns the next backoff step. Without this, a death DURING an attempt's tools/list re-seeds
486
+ * the 1s floor and the one-timer guard then swallows the escalation - a permanent 1s respawn loop. */
487
+ this._reconnecting = new Set();
488
+ /** @type {Map<string, 'modern'|'legacy'>} upstreamId -> era negotiated at the LAST successful
489
+ * connect. A death-driven reconnect passes it to the client as eraHint so a legacy upstream
490
+ * skips the server/discover probe (worst case ~3s against a server that silently drops unknown
491
+ * methods) instead of re-paying it on every respawn. Lifecycle: SET on a successful connect,
492
+ * CLEARED when a connect fails (the hinted attempt may be why - the next retry re-negotiates
493
+ * in full, so an upstream upgraded across a restart self-heals) and by an explicit reconnect()
494
+ * (a manual kick deliberately re-negotiates). A config reload swaps in a fresh Aggregator, so
495
+ * a changed entry never inherits a stale memo. */
496
+ this._eraMemo = new Map();
497
+ /** Set true by closeAll(). A torn-down aggregator (e.g. swapped out by reloadExpose) must NEVER
498
+ * (re)connect - a captured execute thunk holding this instance would otherwise spawn an orphan
499
+ * upstream child on it that nothing ever closes. ensureConnected/connectAll check this. */
500
+ this._closed = false;
501
+ }
502
+
503
+ /**
504
+ * Connect every ENABLED upstream in the store, caching each connected client and its
505
+ * discovered tools. NEVER throws - a per-upstream failure (isolation guard, spawn
506
+ * failure, handshake timeout, listTools failure) is collected into failed[]. An
507
+ * upstream already connected (cached) is treated as connected without reconnecting.
508
+ *
509
+ * @returns {Promise<{ connected: string[], failed: Array<{id:string, error:string}> }>}
510
+ */
511
+ async connectAll() {
512
+ const connected = [];
513
+ const failed = [];
514
+ if (this._closed) return { connected, failed }; // a closed (torn-down) aggregator never connects
515
+
516
+ let upstreams;
517
+ try {
518
+ upstreams = this._store.listUpstreams();
519
+ } catch (err) {
520
+ // listUpstreams() shouldn't throw (it clones), but never let it sink connectAll.
521
+ return { connected, failed: [{ id: '(store)', error: errMsg(err) }] };
522
+ }
523
+
524
+ for (const upstream of upstreams) {
525
+ if (!upstream || upstream.enabled !== true) continue; // only ENABLED upstreams
526
+
527
+ const id = upstream.id;
528
+ if (this._clients.has(id)) {
529
+ // Already connected this session - keep it; don't double-spawn.
530
+ connected.push(id);
531
+ continue;
532
+ }
533
+
534
+ try {
535
+ await this._connectOne(upstream);
536
+ connected.push(id);
537
+ } catch (err) {
538
+ // Clean up any half-built client so a failure leaves no zombie/cache entry.
539
+ this._discard(id);
540
+ const error = errMsg(err);
541
+ logger.log({ type: 'mcp', event: 'connect_failed', upstream: id, error });
542
+ failed.push({ id, error });
543
+ }
544
+ }
545
+
546
+ return { connected, failed };
547
+ }
548
+
549
+ /**
550
+ * Discover one upstream's tool surface. Connects the upstream if it isn't already
551
+ * (lazily, honouring the isolation guard), runs tools/list, caches and returns the
552
+ * raw tool definitions [{name, description, inputSchema}]. This is what the MCP
553
+ * Manager 'discover' button calls.
554
+ *
555
+ * Unlike connectAll this MAY reject (it is a direct user action, so the UI wants the
556
+ * error) - but it cleans up a failed connection so no zombie child is left.
557
+ *
558
+ * @param {string} upstreamId
559
+ * @returns {Promise<Array<{name:string, description?:string, inputSchema?:object}>>}
560
+ */
561
+ async discover(upstreamId) {
562
+ if (!isNonEmptyString(upstreamId)) {
563
+ throw new Error('Aggregator.discover: upstreamId (non-empty string) is required');
564
+ }
565
+
566
+ // Route through ensureConnected: it JOINS an in-flight connect via _connecting instead of
567
+ // racing it - two concurrent discover() calls used to double-spawn the child and leak the
568
+ // loser without closing it. ensureConnected also reaps its own failed connects.
569
+ // allowDisabled: discover is the ONE caller permitted to connect a disabled upstream -
570
+ // inspecting its tools pre-enable worked before the race fix and stays supported.
571
+ try {
572
+ await this.ensureConnected(upstreamId, { allowDisabled: true });
573
+ } catch (err) {
574
+ throw new Error(`Aggregator.discover: cannot connect "${upstreamId}": ${errMsg(err)}`);
575
+ }
576
+ // Re-list even when the fast path returned a cached client - the discover button must always
577
+ // reflect live state (a fresh connect lists twice; cheap, and the semantics stay honest).
578
+ return await this._listAndCache(upstreamId);
579
+ }
580
+
581
+ /**
582
+ * @returns {Object<string, Array>} a clone map of upstreamId -> cached discovered tools.
583
+ * Only includes upstreams that have been connected/discovered this session.
584
+ */
585
+ toolsByUpstream() {
586
+ const out = {};
587
+ for (const [id, tools] of this._tools) {
588
+ out[id] = cloneTools(tools);
589
+ }
590
+ return out;
591
+ }
592
+
593
+ /**
594
+ * The CURATED-DIRECT tool definitions to advertise downstream. For each ENABLED
595
+ * expose[] entry whose upstream is CONNECTED, ENABLED and ACTUALLY advertises the named tool:
596
+ * - name = store.exposedName(entry) (the downstream `as` name)
597
+ * - description = '[' + upstream + '] ' + (upstream tool description || 'tool')
598
+ * - inputSchema = the upstream tool's inputSchema || { type:'object' }
599
+ *
600
+ * Entries whose upstream isn't connected, is explicitly disabled (the row's own flag
601
+ * cannot override the upstream's - a discover-cached client doesn't re-admit it), or
602
+ * whose named tool the upstream doesn't advertise, are silently skipped.
603
+ *
604
+ * @returns {Array<{name:string, description:string, inputSchema:object}>}
605
+ */
606
+ exposedToolDefinitions() {
607
+ const defs = [];
608
+ let exposed;
609
+ try {
610
+ exposed = this._store.listExposed({ enabledOnly: true });
611
+ } catch (_err) {
612
+ return defs; // never throw out of a definition build
613
+ }
614
+
615
+ for (const e of exposed) {
616
+ if (!e || !this._clients.has(e.upstream)) continue; // upstream not connected
617
+ const upstream = this._store.getUpstream(e.upstream);
618
+ if (upstream && upstream.enabled === false) continue; // skip an explicitly-disabled upstream
619
+ const upstreamTools = this._tools.get(e.upstream) || [];
620
+ const upstreamTool = upstreamTools.find((t) => t && t.name === e.tool);
621
+ if (!upstreamTool) continue; // upstream doesn't actually advertise this tool
622
+
623
+ const name = this._store.exposedName(e);
624
+ const desc =
625
+ isNonEmptyString(upstreamTool.description) ? upstreamTool.description : 'tool';
626
+ const inputSchema =
627
+ upstreamTool.inputSchema && typeof upstreamTool.inputSchema === 'object'
628
+ ? upstreamTool.inputSchema
629
+ : { type: 'object' };
630
+
631
+ defs.push(withForwardedToolMeta({
632
+ name,
633
+ description: `[${e.upstream}] ${desc}`,
634
+ inputSchema: sanitiseXMcpHeaders(cloneJson(inputSchema)),
635
+ }, upstreamTool));
636
+ }
637
+ return defs;
638
+ }
639
+
640
+ /**
641
+ * The upstream ids in STORE order (expose.json's own sequence) - the stable advertisement
642
+ * order handleToolsList's hot-upstream block iterates by. Connection-map order
643
+ * shifts on death/recovery re-insertion; the store's order never does. NEVER throws.
644
+ * @returns {string[]}
645
+ */
646
+ upstreamOrder() {
647
+ try {
648
+ return this._store.listUpstreams().map((u) => u && u.id).filter(Boolean);
649
+ } catch (_e) {
650
+ return [];
651
+ }
652
+ }
653
+
654
+ /**
655
+ * Is `name` a downstream `as` name currently exposed (enabled) AND backed by a
656
+ * connected upstream that advertises the underlying tool? Mirrors the set
657
+ * exposedToolDefinitions() advertises.
658
+ * @param {string} name
659
+ * @returns {boolean}
660
+ */
661
+ isExposed(name) {
662
+ return this._findExposedExecution(name) !== null;
663
+ }
664
+
665
+ /**
666
+ * Resolve a downstream `as` name + args into an executor. Returns
667
+ * { execute, toolName, upstream } | null
668
+ * where:
669
+ * - execute() invokes the connected client's callTool(<real upstream tool name>, args)
670
+ * - toolName = the downstream `as` (what PreToolUse matchers see - the gate matches
671
+ * the downstream name, execution hits the real upstream tool)
672
+ * - upstream = the upstream id
673
+ * Returns null if `name` is not exposed/enabled or its upstream isn't connected.
674
+ *
675
+ * @param {string} name downstream `as` name
676
+ * @param {any} args structured arguments forwarded verbatim to callTool
677
+ * @returns {{ execute: Function, toolName: string, upstream: string } | null}
678
+ */
679
+ resolveExposedExecution(name, args, meta) {
680
+ const hit = this._findExposedExecution(name);
681
+ if (!hit) return null;
682
+ const { client, realTool, upstream, exposedName } = hit;
683
+ return {
684
+ // The execute thunk is the seam the server calls AFTER the PreToolUse gate allows it.
685
+ execute: this._forwardExecutor(client, realTool, args, meta),
686
+ toolName: exposedName, // downstream name - the gate's matcher target
687
+ upstream,
688
+ };
689
+ }
690
+
691
+ // ── lean register forwarding ──────────────────────────────────────
692
+ // The LEAN path surfaces an attached upstream's tools through the 4 meta-tools (toolfunnel_list_tools
693
+ // / _tool_instructions / _run_tool) instead of injecting them top-level every turn. The full
694
+ // discovered set of every CONNECTED + enabled upstream is surfaced (attaching an MCP makes its
695
+ // tools appear with no per-tool curation); expose[]/hot governs only the SEPARATE top-level
696
+ // (curated-direct) promotion. A lean tool is surfaced under its enabled expose `as` if one exists,
697
+ // else the namespaced default `<upstream>_<tool>` - so the lean name equals the curated-direct name
698
+ // for an exposed tool and ONE PreToolUse rule gates both routes. All of this lives here in the
699
+ // aggregator (it owns the connections, the _clients/_tools caches, and the connect log chokepoint).
700
+
701
+ /**
702
+ * The single forward seam: a thunk that calls the upstream's real tool. Shared by the
703
+ * curated-direct path (resolveExposedExecution, transparent envelope passthrough) and the lean
704
+ * path (resolveLeanExecution, which unwraps). Kept tiny so both routes execute identically.
705
+ * @param {object} client a connected McpClient
706
+ * @param {string} realTool the upstream's own tool name
707
+ * @param {any} args
708
+ * @returns {() => Promise<any>}
709
+ */
710
+ _forwardExecutor(client, realTool, args, meta) {
711
+ return () => {
712
+ this._warnIfPinned(client.id, realTool);
713
+ return client.callTool(realTool, args, meta);
714
+ };
715
+ }
716
+
717
+ /**
718
+ * Legacy shim PER-CALL warning (the pin's contract: warn on every forwarded call, naming the
719
+ * upstream + version). Called from BOTH forward paths - curated-direct (_forwardExecutor) and
720
+ * lean (resolveLeanExecution's own closure; it cannot use _forwardExecutor because it needs
721
+ * ensureConnected + envelope unwrapping). Checked at CALL time so a live expose.json edit takes
722
+ * effect immediately; stderr + activity log, never the content. NEVER throws.
723
+ * @param {string} upstreamId
724
+ * @param {string} realTool the upstream's own tool name
725
+ */
726
+ _warnIfPinned(upstreamId, realTool) {
727
+ try {
728
+ const upstream = this._store.getUpstream(upstreamId);
729
+ if (upstream && upstream.legacyPin === true) {
730
+ process.stderr.write(
731
+ `[toolfunnel] legacy shim: forwarding "${realTool}" to pinned legacy upstream ` +
732
+ `"${upstreamId}" (MCP ${LEGACY_UPSTREAM_VERSION})\n`
733
+ );
734
+ logger.log({ type: 'mcp', event: 'legacy_shim_call', upstream: upstreamId, tool: realTool, protocolVersion: LEGACY_UPSTREAM_VERSION });
735
+ }
736
+ } catch (_e) { /* the warning must never affect the call */ }
737
+ }
738
+
739
+ /**
740
+ * Legacy-shim info for a surfaced OR original call name: { upstream, protocolVersion } when the
741
+ * tool belongs to a PINNED (legacyPin) upstream, else null. Used by the modern era to tag
742
+ * results with _meta["io.toolfunnel/legacyShim"] - metadata, never content. NEVER throws.
743
+ * @param {string} name the name a client called (surfaced `<upstream>_<tool>`/`as`, or the
744
+ * ORIGINAL tool name under passthrough)
745
+ * @returns {{ upstream: string, protocolVersion: string } | null}
746
+ */
747
+ legacyShimInfo(name) {
748
+ if (typeof name !== 'string' || name.length === 0) return null;
749
+ try {
750
+ const d = this.leanToolDefinitions().find((x) => x && (x.name === name || x.tool === name));
751
+ if (!d) return null;
752
+ const upstream = this._store.getUpstream(d.upstream);
753
+ if (!upstream || upstream.legacyPin !== true) return null;
754
+ return { upstream: d.upstream, protocolVersion: LEGACY_UPSTREAM_VERSION };
755
+ } catch (_e) {
756
+ return null;
757
+ }
758
+ }
759
+
760
+ /**
761
+ * The wrapped upstream's OWN identity, extracted from its captured `initialize` result - so a
762
+ * passthrough WRAP can present the wrapped server verbatim (indistinguishable from connecting to
763
+ * it directly, save for the ToolFunnel process). Returns { protocolVersion, serverInfo,
764
+ * capabilities, instructions } with best-effort extraction (some servers nest capabilities /
765
+ * instructions inside serverInfo), or null if the upstream isn't connected. NEVER throws.
766
+ * @param {string} upstreamId
767
+ * @returns {{ protocolVersion?:string, serverInfo?:object, capabilities?:object, instructions?:string } | null}
768
+ */
769
+ wrappedIdentity(upstreamId) {
770
+ try {
771
+ const client = this._clients.get(upstreamId);
772
+ if (!client || typeof client.initializeResult === 'undefined') return null;
773
+ const init = client.initializeResult;
774
+ if (!init || typeof init !== 'object') return null;
775
+ const si = init.serverInfo && typeof init.serverInfo === 'object' ? init.serverInfo : {};
776
+ // serverInfo passes VERBATIM minus the two fields some servers wrongly nest inside it
777
+ // (capabilities/instructions - extracted separately below). A whitelist here ate the spec's
778
+ // own serverInfo.title (2025-06-18) through the wrap - proven against the real
779
+ // server-everything (found wire-testing the wrap, 2026-07-17). Blocklist, so future identity fields survive.
780
+ const serverInfo = {};
781
+ for (const k of Object.keys(si)) {
782
+ if (k === 'capabilities' || k === 'instructions') continue;
783
+ serverInfo[k] = cloneJson(si[k]);
784
+ }
785
+ return {
786
+ protocolVersion: typeof init.protocolVersion === 'string' ? init.protocolVersion : undefined,
787
+ serverInfo: Object.keys(serverInfo).length ? serverInfo : undefined,
788
+ // capabilities / instructions: prefer top-level (standard), fall back to serverInfo-nested.
789
+ capabilities: (init.capabilities && typeof init.capabilities === 'object') ? init.capabilities
790
+ : (si.capabilities && typeof si.capabilities === 'object') ? si.capabilities : undefined,
791
+ instructions: typeof init.instructions === 'string' ? init.instructions
792
+ : typeof si.instructions === 'string' ? si.instructions : undefined,
793
+ };
794
+ } catch (_e) {
795
+ return null;
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Forward a RAW JSON-RPC method to a connected upstream and return its result - the passthrough
801
+ * WRAP's relay for non-tool methods (resources/*, prompts/*, logging/*, ping...) so a wrapped
802
+ * server behaves exactly as it would connected directly. Uses a LIVE client only (no synchronous
803
+ * (re)connect - same rule as the lean run path). Throws if the upstream is not connected or the
804
+ * call fails; the caller shapes that into a JSON-RPC error.
805
+ * @param {string} upstreamId
806
+ * @param {string} method
807
+ * @param {any} params
808
+ * @returns {Promise<any>}
809
+ */
810
+ async forwardRaw(upstreamId, method, params, out) {
811
+ const client = await this.ensureConnected(upstreamId, { allowConnect: false });
812
+ if (!client || typeof client.request !== 'function') {
813
+ throw new Error(`upstream "${upstreamId}" is not connected`);
814
+ }
815
+ return await client.request(method, params, out);
816
+ }
817
+
818
+ /** The clientInfo to PRESENT to `upstreamId`, or null for the built-in. Fresh provider read per
819
+ * call (per-connect, same as the wrap-target check); NEVER throws. */
820
+ _readClientInfo(upstreamId) {
821
+ try {
822
+ const info = this._clientInfoProvider ? this._clientInfoProvider(upstreamId) : null;
823
+ return info && typeof info === 'object' &&
824
+ typeof info.name === 'string' && info.name.length ? info : null;
825
+ } catch (_e) {
826
+ return null; // a broken provider degrades to the built-in identity
827
+ }
828
+ }
829
+
830
+ /** Is `upstreamId` the currently-wrapped upstream? Fresh provider read per call; NEVER throws.
831
+ * Drives the per-connect isolation exemption (transparent-wrapper mode). */
832
+ _isWrapTarget(upstreamId) {
833
+ try {
834
+ return !!(this._wrapTargetProvider && isNonEmptyString(upstreamId) &&
835
+ this._wrapTargetProvider() === upstreamId);
836
+ } catch (_e) {
837
+ return false; // a broken provider must degrade to the SAFE default (guard applies)
838
+ }
839
+ }
840
+
841
+ /** Set the wrap-chatter scope. When the passthrough TARGET CHANGES (A->B, A->null, null->A) the
842
+ * recorded resource subscriptions belong to the OLD context and must not replay onto the new
843
+ * one - a client of wrap B never subscribed to wrap A's URIs. A
844
+ * same-value re-arm (every message does one) clears nothing. */
845
+ setWrapChatterUpstream(v) {
846
+ const next = v == null ? null : v;
847
+ if (next !== this.wrapChatterUpstream && this._subscribedUris instanceof Set) {
848
+ this._subscribedUris.clear();
849
+ if (this._subscribedRefs instanceof Map) this._subscribedRefs.clear(); // 5.4: refs go with the context
850
+ }
851
+ this.wrapChatterUpstream = next;
852
+ }
853
+
854
+ /** Relay a client NOTIFICATION to an upstream (wrap passthrough: notifications/cancelled,
855
+ * notifications/progress ...). Fire-and-forget; never throws, never answers. */
856
+ notifyRaw(upstreamId, method, params) {
857
+ try {
858
+ const client = this._clients.get(upstreamId);
859
+ if (client && typeof client.notify === 'function') client.notify(method, params);
860
+ } catch (_e) { /* fire-and-forget */ }
861
+ }
862
+
863
+ /** TRUE if a connected upstream can ACTUALLY deliver per-URI resource updates. That means a
864
+ * LEGACY upstream advertising resources.subscribe (we forward the subscribes; it emits
865
+ * resources/updated). A MODERN upstream does NOT count: its only notification channel is a
866
+ * subscriptions/listen stream this client does not yet open (28-July item), so counting it
867
+ * agreed a channel nothing would ever feed. Under a wrap only the WRAPPED
868
+ * upstream counts - delivery is filtered to it, so another upstream honouring the channel
869
+ * would be agreed-then-dropped. The ack must never promise a dead channel. */
870
+ canHonourResourceSubscriptions() {
871
+ for (const [id, client] of this._clients) {
872
+ if (!client) continue;
873
+ if (this.wrapChatterUpstream && id !== this.wrapChatterUpstream) continue;
874
+ if (client.era === 'modern') continue;
875
+ const caps = client.initializeResult && client.initializeResult.capabilities;
876
+ if (caps && caps.resources && caps.resources.subscribe) return true;
877
+ }
878
+ return false;
879
+ }
880
+
881
+ /** Best-effort: forward resources/subscribe for each URI to every subscribe-capable legacy
882
+ * upstream in scope (the wrapped one only, under a wrap). The URIs are RECORDED
883
+ * so every later (re)connect replays them: a reconnected upstream is a fresh process that
884
+ * remembers no subscriptions, and without the replay the client's agreed channel went silently
885
+ * dead forever. Fire-and-forget; never throws. */
886
+ subscribeResources(uris) {
887
+ try {
888
+ const list = Array.isArray(uris) ? uris.filter((u) => typeof u === 'string' && u.length) : [];
889
+ if (!list.length) return;
890
+ // 5.4: refcount per LISTEN-owned uri; the upstream subscribe is sent on the 0->1 crossing
891
+ // only (a re-listen agreeing the same uri must not spam idempotent subscribes).
892
+ const fresh = [];
893
+ for (const uri of list) {
894
+ const n = this._subscribedRefs.get(uri) || 0;
895
+ this._subscribedRefs.set(uri, n + 1);
896
+ if (!this._subscribedUris.has(uri)) { this._subscribedUris.add(uri); fresh.push(uri); }
897
+ }
898
+ if (!fresh.length) return;
899
+ for (const [id, client] of this._clients) {
900
+ if (this.wrapChatterUpstream && id !== this.wrapChatterUpstream) continue;
901
+ if (!client || client.era !== 'legacy' || typeof client.request !== 'function') continue;
902
+ const caps = client.initializeResult && client.initializeResult.capabilities;
903
+ if (!(caps && caps.resources && caps.resources.subscribe)) continue;
904
+ for (const uri of fresh) client.request('resources/subscribe', { uri }).catch(() => {});
905
+ }
906
+ } catch (_e) { /* never throw */ }
907
+ }
908
+
909
+ /**
910
+ * Release LISTEN-owned resource subscriptions (the refcount leak's fix). Decrements each
911
+ * uri's refcount; on the 1->0 crossing the uri leaves the replay set and the upstream is told
912
+ * resources/unsubscribe (same scope rules as subscribeResources). ACCEPTED EDGE, documented:
913
+ * a uri subscribed BOTH by a listen agreement and a client's own wrap-forwarded
914
+ * resources/subscribe shares one upstream channel - when the last listen releases, the
915
+ * upstream unsubscribe fires and the recorded Set entry goes with it (the exotic overlap is
916
+ * not disambiguated). NEVER throws.
917
+ * @param {string[]} uris
918
+ */
919
+ releaseResources(uris) {
920
+ try {
921
+ const list = Array.isArray(uris) ? uris.filter((u) => typeof u === 'string' && u.length) : [];
922
+ if (!list.length) return;
923
+ const gone = [];
924
+ for (const uri of list) {
925
+ const n = this._subscribedRefs.get(uri) || 0;
926
+ if (n <= 1) {
927
+ if (n === 1) this._subscribedRefs.delete(uri);
928
+ if (this._subscribedUris.has(uri)) { this._subscribedUris.delete(uri); gone.push(uri); }
929
+ } else {
930
+ this._subscribedRefs.set(uri, n - 1);
931
+ }
932
+ }
933
+ if (!gone.length) return;
934
+ for (const [id, client] of this._clients) {
935
+ if (this.wrapChatterUpstream && id !== this.wrapChatterUpstream) continue;
936
+ if (!client || client.era !== 'legacy' || typeof client.request !== 'function') continue;
937
+ const caps = client.initializeResult && client.initializeResult.capabilities;
938
+ if (!(caps && caps.resources && caps.resources.subscribe)) continue;
939
+ for (const uri of gone) client.request('resources/unsubscribe', { uri }).catch(() => {});
940
+ }
941
+ } catch (_e) { /* never throw */ }
942
+ }
943
+
944
+ /** Replay the recorded resource subscriptions onto ONE freshly-connected upstream.
945
+ * Called from _connectOne so every connect path - startup, lazy, background reconnect, reload -
946
+ * re-arms the channel. Same scope rules as subscribeResources. Never throws. */
947
+ _replaySubscriptions(upstreamId) {
948
+ try {
949
+ if (!this._subscribedUris || this._subscribedUris.size === 0) return;
950
+ if (this.wrapChatterUpstream && upstreamId !== this.wrapChatterUpstream) return;
951
+ const client = this._clients.get(upstreamId);
952
+ if (!client || client.era !== 'legacy' || typeof client.request !== 'function') return;
953
+ const caps = client.initializeResult && client.initializeResult.capabilities;
954
+ if (!(caps && caps.resources && caps.resources.subscribe)) return;
955
+ for (const uri of this._subscribedUris) client.request('resources/subscribe', { uri }).catch(() => {});
956
+ } catch (_e) { /* never throw */ }
957
+ }
958
+
959
+ /** The change-notification methods an upstream may push that we bridge to modern clients. Anything
960
+ * else from the upstream is ignored (request-scoped notifications ride their own request stream). */
961
+ static get BRIDGED_NOTIFICATIONS() {
962
+ return new Set([
963
+ 'notifications/tools/list_changed',
964
+ 'notifications/prompts/list_changed',
965
+ 'notifications/resources/list_changed',
966
+ 'notifications/resources/updated',
967
+ ]);
968
+ }
969
+
970
+ /**
971
+ * Forward a server-initiated CHANGE notification from an upstream to the transport hook, which
972
+ * fans it to modern subscriptions/listen streams. Only the known change methods pass; the
973
+ * notification is handed on verbatim (the transport tags + filters per subscription). NEVER
974
+ * throws (an onNotification handler must never break the client's read loop).
975
+ * @param {string} upstreamId
976
+ * @param {object} notification a JSON-RPC notification { method, params? }
977
+ */
978
+ _forwardUpstreamNotification(upstreamId, notification) {
979
+ try {
980
+ if (this._closed) return; // a swapped-out/torn-down aggregator must never fan out (F9)
981
+ if (!notification || typeof notification.method !== 'string') return;
982
+ // tasks/status rides the wrap-chatter lane too: the wrap advertises the
983
+ // upstream's `tasks` capability verbatim, so a task started through the wrap owes its
984
+ // status notifications exactly as a direct connection would deliver them (2025-11-25
985
+ // schema TaskStatusNotification). Wrapped upstream only - same scope as message/progress.
986
+ const isWrapChatter = this.wrapChatterUpstream === upstreamId &&
987
+ (notification.method === 'notifications/message' || notification.method === 'notifications/progress' ||
988
+ notification.method === 'notifications/tasks/status');
989
+ if (!Aggregator.BRIDGED_NOTIFICATIONS.has(notification.method) && !isWrapChatter) return;
990
+ // Forward a CLEAN notification only - a misbehaving upstream's stray `id: null` field would
991
+ // read as a response to downstream parsers (F7).
992
+ const clean = { jsonrpc: '2.0', method: notification.method };
993
+ if (notification.params !== undefined) clean.params = notification.params;
994
+ const emit = () => {
995
+ try {
996
+ if (typeof this.onUpstreamNotification === 'function') {
997
+ this.onUpstreamNotification(upstreamId, clean);
998
+ }
999
+ } catch (_e) { /* never let a bridged notification break the read loop */ }
1000
+ };
1001
+ if (notification.method === 'notifications/tools/list_changed') {
1002
+ // A relayed "tools changed" must not point the client at a STALE surface - refresh the
1003
+ // cache FIRST, then relay, so the re-fetch sees the new list (F2/B-M4). onToolsChanged
1004
+ // fires too so ToolFunnel's own funnel-mode signal stays coherent.
1005
+ this._listAndCache(upstreamId)
1006
+ .then(() => { try { if (typeof this.onToolsChanged === 'function') this.onToolsChanged(); } catch (_e) { /* ignore */ } })
1007
+ .catch(() => { /* refresh failed - still relay; the old cache is the best we have */ })
1008
+ .then(emit);
1009
+ return;
1010
+ }
1011
+ emit();
1012
+ } catch (_e) { /* never let a bridged notification break the read loop */ }
1013
+ }
1014
+
1015
+ /**
1016
+ * The downstream name a discovered upstream tool is surfaced under: its ENABLED expose `as` if one
1017
+ * exists for (upstream, tool), else the namespaced default `<upstream>_<tool>` (matching
1018
+ * expose-store.exposedName). Keeps the lean list and the lean run path in agreement, and aligns an
1019
+ * exposed tool's lean name with its curated-direct top-level name. Never throws.
1020
+ * @param {string} upstreamId
1021
+ * @param {string} toolName
1022
+ * @returns {string}
1023
+ */
1024
+ _surfacedName(upstreamId, toolName) {
1025
+ try {
1026
+ const exposed = this._store.listExposed({ enabledOnly: true });
1027
+ for (const e of exposed) {
1028
+ if (e && e.upstream === upstreamId && e.tool === toolName) return this._store.exposedName(e);
1029
+ }
1030
+ } catch (_e) {
1031
+ /* fall through to the default */
1032
+ }
1033
+ return `${upstreamId}_${toolName}`;
1034
+ }
1035
+
1036
+ /**
1037
+ * Connect an upstream ON DEMAND and return the ready McpClient. Idempotent + race-safe:
1038
+ * - fast path: a cached client that is still `connected` is returned as-is; a cached-but-DEAD
1039
+ * client (its child exited - McpClient flips `connected` but stays in the cache) is logged as a
1040
+ * disconnect, discarded, and reconnected - a reconnect re-lists the upstream's tools.
1041
+ * - concurrent callers JOIN the same in-flight connect promise (keyed in _connecting), which
1042
+ * resolves only AFTER _listAndCache - so no caller ever sees the half-built client that
1043
+ * _connectOne caches BEFORE the handshake completes (the double-spawn / mid-handshake race).
1044
+ * Throws on an unknown/disabled upstream or a connect/list failure (the caller surfaces it; for the
1045
+ * lean run path that means gatedRun returns { ok:false, error } cleanly).
1046
+ * @param {string} upstreamId
1047
+ * @returns {Promise<object>} the connected McpClient
1048
+ */
1049
+ async ensureConnected(upstreamId, opts) {
1050
+ if (!isNonEmptyString(upstreamId)) throw new Error('Aggregator.ensureConnected: upstreamId (non-empty string) is required');
1051
+ // allowConnect:false (the RUN path) must NEVER block on a connect - not a from-scratch connect
1052
+ // (connect()+tools/list, ~20s, would freeze the serialized stdio chain and starve pings) AND not
1053
+ // by JOINING an in-flight background reconnect (same latency). It returns a live client or fails
1054
+ // clean; the background reconnect owns recovery and the run retries next turn. allowConnect
1055
+ // defaults true (the background path connects / joins).
1056
+ const allowConnect = !(opts && opts.allowConnect === false);
1057
+ // allowDisabled: ONLY the discover path sets it - inspecting a disabled upstream's tools
1058
+ // ("what does this have, before I enable it?") is a deliberate operator action that worked
1059
+ // before discover was routed through here for the race fix. Every
1060
+ // other caller keeps the refusal; a disabled upstream's tools stay OFF the lean surface
1061
+ // regardless (leanToolDefinitions checks enabled itself).
1062
+ const allowDisabled = !!(opts && opts.allowDisabled === true);
1063
+ // A torn-down aggregator (swapped out by reloadExpose, then closeAll'd) must NEVER (re)connect:
1064
+ // a captured execute thunk holding this instance would otherwise spawn an ORPHAN child on it.
1065
+ if (this._closed) throw new Error('Aggregator.ensureConnected: aggregator is closed (config reloaded) - retry on the current one');
1066
+
1067
+ // A connect already in flight: JOIN it - BEFORE inspecting the cache. _connectOne caches the
1068
+ // client pre-handshake, so a concurrent caller inspecting first sees `connected:false`, reads
1069
+ // it as stale, closes it (killing the in-flight child mid-handshake) and then joins the
1070
+ // connect it just doomed - both callers fail. The RUN path
1071
+ // (allowConnect:false) still never joins - joining would block the stdio chain.
1072
+ if (this._connecting.has(upstreamId)) {
1073
+ if (!(opts && opts.allowConnect === false)) return this._connecting.get(upstreamId);
1074
+ throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" is not connected (reconnecting in background)`);
1075
+ }
1076
+
1077
+ // Fast path: a live cached client serves BOTH modes immediately.
1078
+ const existing = this._clients.get(upstreamId);
1079
+ if (existing) {
1080
+ const alive = typeof existing.connected === 'boolean' ? existing.connected : true;
1081
+ if (alive) return existing;
1082
+ // Dead cached client. The RUN path fails clean (never (re)connects); the background path drops
1083
+ // it and reconnects below.
1084
+ if (!allowConnect) {
1085
+ throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" disconnected (reconnecting in background)`);
1086
+ }
1087
+ logger.log({ type: 'mcp', event: 'disconnect', upstream: upstreamId, reason: 'stale' });
1088
+ this._discard(upstreamId);
1089
+ } else if (!allowConnect) {
1090
+ // Not connected. The RUN path neither connects NOR joins an in-flight connect - joining would
1091
+ // block the stdio chain for the connect+list latency (the head-of-line freeze this mode avoids).
1092
+ throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" is not connected (reconnecting in background)`);
1093
+ }
1094
+
1095
+ // Background path only (allowConnect): connect from scratch. In-flight connects were joined
1096
+ // at the top of the method (before cache inspection - the mid-connect discard race); nothing
1097
+ // between there and here awaits, so no new entry can have appeared.
1098
+ const upstream = this._store.getUpstream(upstreamId);
1099
+ if (!upstream) throw new Error(`Aggregator.ensureConnected: unknown upstream "${upstreamId}"`);
1100
+ if (upstream.enabled !== true && !allowDisabled) throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" is disabled`);
1101
+
1102
+ const promise = (async () => {
1103
+ await this._connectOne(upstream); // caches client + tools, logs the connect
1104
+ return this._clients.get(upstreamId);
1105
+ })();
1106
+ this._connecting.set(upstreamId, promise);
1107
+ try {
1108
+ return await promise;
1109
+ } catch (err) {
1110
+ this._discard(upstreamId); // reap the half-spawned child; leave no zombie/cache entry
1111
+ throw err;
1112
+ } finally {
1113
+ this._connecting.delete(upstreamId);
1114
+ }
1115
+ }
1116
+
1117
+ /**
1118
+ * Force a fresh connect of `upstreamId` presenting the CURRENT provider-supplied identity -
1119
+ * the wrap identity-mirror's inline path. Settles any in-flight connect FIRST: discarding a
1120
+ * half-built client and then joining its doomed promise leaves the upstream wedged with no
1121
+ * background reconnect and no self-heal. Rejects
1122
+ * like ensureConnected on failure.
1123
+ */
1124
+ async reconnect(upstreamId) {
1125
+ if (!isNonEmptyString(upstreamId)) throw new Error('Aggregator.reconnect: upstreamId (non-empty string) is required');
1126
+ while (this._connecting.has(upstreamId)) {
1127
+ try { await this._connecting.get(upstreamId); } catch (_e) { /* settled is all we need */ }
1128
+ }
1129
+ this._discard(upstreamId);
1130
+ // A MANUAL kick deliberately re-runs the full era negotiation - the operator may have just
1131
+ // upgraded the server, and "reconnect" should observe reality, not replay a memo of it.
1132
+ this._eraMemo.delete(upstreamId);
1133
+ try {
1134
+ return await this.ensureConnected(upstreamId);
1135
+ } catch (err) {
1136
+ // This path DESTROYED a (possibly healthy) connection, and the deliberate close means
1137
+ // onClose never fires - without this, one transient connect failure leaves no client, no
1138
+ // in-flight connect AND no retry timer: the upstream is wedged until an external kick
1139
+ // while ensureConnected's "reconnecting in background" message lies. The destroyer owns the retry. A stale PENDING timer (a prior death's slow
1140
+ // 30s keepalive) must be cleared first - _scheduleReconnect's one-timer guard would
1141
+ // otherwise no-op and leave the upstream on the long window instead of the immediate
1142
+ // retry this path promises.
1143
+ const stale = this._reconnectTimers.get(upstreamId);
1144
+ if (stale) { clearTimeout(stale); this._reconnectTimers.delete(upstreamId); }
1145
+ this._scheduleReconnect(upstreamId, 0);
1146
+ throw err;
1147
+ }
1148
+ }
1149
+
1150
+ /**
1151
+ * UNEXPECTED upstream death (fired by McpClient.onClose). Log it, drop the dead client so it
1152
+ * leaves the lean list, tell the client the tool set shrank, then schedule a BACKGROUND reconnect.
1153
+ * Keeping recovery off the serialized stdio chain is what closes the head-of-line regression: a run
1154
+ * during the down-window fails clean (ensureConnected allowConnect:false) instead of blocking.
1155
+ * @param {string} upstreamId
1156
+ */
1157
+ _handleUpstreamDown(upstreamId) {
1158
+ if (this._closed) return;
1159
+ logger.log({ type: 'mcp', event: 'disconnect', upstream: upstreamId, reason: 'died' });
1160
+ this._discard(upstreamId); // remove the dead client + its tools -> drops from the lean list
1161
+ this._signalToolsChanged(upstreamId); // list_changed only if the upstream is on the top-level surface
1162
+ // If a reconnect ATTEMPT is already executing, it owns the next backoff step (its catch escalates
1163
+ // attempt+1). Seeding attempt-0 here would reset the delay to 1s on every mid-attempt death, and
1164
+ // the one-timer guard would then swallow the attempt's escalation - a permanent 1s respawn loop.
1165
+ // Only start a fresh cycle when no attempt is in flight (the ordinary first death of a live upstream).
1166
+ if (this._reconnecting.has(upstreamId)) return;
1167
+ this._scheduleReconnect(upstreamId, 0);
1168
+ }
1169
+
1170
+ /**
1171
+ * Does this upstream contribute to the TOP-LEVEL tools/list (i.e. has an ENABLED expose[] entry)?
1172
+ * Only then does its death/recovery change tools/list and warrant a notifications/tools/list_changed.
1173
+ * A lean-only upstream's tools live behind toolfunnel_list_tools (pulled per call), so notifying for
1174
+ * one is spurious (the client re-fetches and sees no diff). Never throws.
1175
+ * @param {string} upstreamId
1176
+ * @returns {boolean}
1177
+ */
1178
+ _affectsTopLevel(upstreamId) {
1179
+ try {
1180
+ // Under a WRAP the wrapped upstream IS the entire top-level surface - its death/recovery
1181
+ // changes tools/list even with an empty expose[] (a typical wrap has no expose
1182
+ // entries, so death/recovery was silent and clients held a stale surface forever).
1183
+ // wrapChatterUpstream mirrors the live wrap state (armed at boot, per message, on reload).
1184
+ if (this.wrapChatterUpstream && this.wrapChatterUpstream === upstreamId) return true;
1185
+ // Hot-promoted upstream tools sit on the funnel's top-level surface without an expose[]
1186
+ // entry; the host injects this predicate (armWrapChatter) because promotion lives in the
1187
+ // tool-state overlay the aggregator has no business reading directly.
1188
+ if (typeof this.topLevelUpstreamExtra === 'function' && this.topLevelUpstreamExtra(upstreamId)) return true;
1189
+ return this._store.listExposed({ enabledOnly: true }).some((e) => e && e.upstream === upstreamId);
1190
+ } catch (_e) {
1191
+ return false;
1192
+ }
1193
+ }
1194
+
1195
+ /** Fire onToolsChanged ONLY when the upstream is actually on the top-level surface (else the
1196
+ * notification is spurious - its lean tools refresh on the next toolfunnel_list_tools). Never throws. */
1197
+ _signalToolsChanged(upstreamId) {
1198
+ if (!this._affectsTopLevel(upstreamId)) return;
1199
+ try { this.onToolsChanged(); } catch (_e) { /* never throw out of an event handler */ }
1200
+ }
1201
+
1202
+ /**
1203
+ * Schedule ONE background reconnect attempt with exponential backoff: 1s,2s,4s,8s,16s, then capped
1204
+ * at 30s. After the fast phase it does NOT give up - it falls back to a slow 30s keepalive so a long
1205
+ * transient outage still self-heals (a detached/disabled upstream stops it via getUpstream; closeAll
1206
+ * stops it via _closed). On success the tools are re-listed and a top-level change is signalled. One
1207
+ * timer per upstream (no pile-up); the timer is unref'd so it never keeps the process alive. NEVER throws.
1208
+ * @param {string} upstreamId
1209
+ * @param {number} attempt
1210
+ */
1211
+ _scheduleReconnect(upstreamId, attempt) {
1212
+ if (this._closed) return;
1213
+ if (this._reconnectTimers.has(upstreamId)) return; // a reconnect is already pending for this id
1214
+ const upstream = this._store.getUpstream(upstreamId);
1215
+ if (!upstream || upstream.enabled !== true) return; // detached/disabled - stop trying
1216
+ const MAX_FAST_ATTEMPTS = 6; // exponential phase; beyond it, a slow keepalive at the 30s cap
1217
+ const delay = Math.min(1000 * Math.pow(2, attempt), 30000);
1218
+ const timer = setTimeout(async () => {
1219
+ this._reconnectTimers.delete(upstreamId);
1220
+ if (this._closed) return;
1221
+ const u = this._store.getUpstream(upstreamId);
1222
+ if (!u || u.enabled !== true) return;
1223
+ // Mark the attempt in flight so a death DURING ensureConnected's connect/list (onClose ->
1224
+ // _handleUpstreamDown) does not re-seed attempt-0: THIS attempt's catch owns the escalation.
1225
+ this._reconnecting.add(upstreamId);
1226
+ try {
1227
+ await this.ensureConnected(upstreamId); // allowConnect default - connects + re-lists, off-chain
1228
+ logger.log({ type: 'mcp', event: 'reconnect', upstream: upstreamId, attempt });
1229
+ this._signalToolsChanged(upstreamId);
1230
+ } catch (err) {
1231
+ logger.log({ type: 'mcp', event: 'reconnect_failed', upstream: upstreamId, attempt, error: errMsg(err) });
1232
+ // Log the fast->slow transition exactly ONCE - when the counter FIRST reaches the cap. The
1233
+ // old guard sat on the re-entry side, where the capped counter re-satisfied it every 30s
1234
+ // forever against a permanently-dead upstream (log spam, not information).
1235
+ if (attempt + 1 === MAX_FAST_ATTEMPTS) {
1236
+ logger.log({ type: 'mcp', event: 'reconnect_slow', upstream: upstreamId, attempts: MAX_FAST_ATTEMPTS });
1237
+ }
1238
+ // Keep escalating to the cap, then keep retrying slowly (cap the counter so the delay stays
1239
+ // at 30s) - never permanently give up while the upstream stays enabled. The escalation is
1240
+ // scheduled while still in flight (the guard below checks _reconnectTimers, which is empty
1241
+ // because a mid-attempt death was skipped) - the finally then releases the marker.
1242
+ this._scheduleReconnect(upstreamId, Math.min(attempt + 1, MAX_FAST_ATTEMPTS));
1243
+ } finally {
1244
+ this._reconnecting.delete(upstreamId);
1245
+ }
1246
+ }, delay);
1247
+ if (timer && typeof timer.unref === 'function') timer.unref();
1248
+ this._reconnectTimers.set(upstreamId, timer);
1249
+ }
1250
+
1251
+ /**
1252
+ * The LEAN tool definitions: every discovered tool of every CONNECTED + enabled upstream, surfaced
1253
+ * for toolfunnel_list_tools. Each: { name, description, inputSchema, upstream, tool }. The FULL
1254
+ * discovered set (not just expose[]) - attaching an MCP makes its tools appear leanly with no
1255
+ * curation. Only connected upstreams contribute (we need their real schemas); a not-yet-connected
1256
+ * upstream's tools simply appear once it connects (the next list call reflects it - no
1257
+ * notification needed, the lean surface is delivered inside a per-call meta-tool). Never throws.
1258
+ * @returns {Array<{name:string, description:string, inputSchema:object, upstream:string, tool:string}>}
1259
+ */
1260
+ leanToolDefinitions() {
1261
+ const defs = [];
1262
+ const seen = new Set(); // surfaced-name collision guard - the list must agree with resolve (first wins)
1263
+ try {
1264
+ for (const [upstreamId, tools] of this._tools) {
1265
+ if (!this._clients.has(upstreamId)) continue; // connected only
1266
+ const upstream = this._store.getUpstream(upstreamId);
1267
+ if (upstream && upstream.enabled === false) continue; // skip an explicitly-disabled upstream
1268
+ if (!Array.isArray(tools)) continue;
1269
+ for (const t of tools) {
1270
+ if (!t || !isNonEmptyString(t.name)) continue;
1271
+ const name = this._surfacedName(upstreamId, t.name);
1272
+ if (seen.has(name)) {
1273
+ // Two tools collapse to one surfaced name (underscore ambiguity, or a duplicate `as`).
1274
+ // resolveLeanExecution returns the FIRST match, so advertise only the first - the list
1275
+ // must never show a name that resolves to a different tool. Log the shadowing.
1276
+ logger.log({ type: 'mcp', event: 'name_collision', upstream: upstreamId, tool: t.name, surfaced: name });
1277
+ continue;
1278
+ }
1279
+ seen.add(name);
1280
+ const schema = t.inputSchema && typeof t.inputSchema === 'object' ? t.inputSchema : { type: 'object' };
1281
+ defs.push(withForwardedToolMeta({
1282
+ name,
1283
+ description: isNonEmptyString(t.description) ? t.description : '',
1284
+ inputSchema: sanitiseXMcpHeaders(cloneJson(schema)),
1285
+ upstream: upstreamId,
1286
+ tool: t.name,
1287
+ }, t));
1288
+ }
1289
+ }
1290
+ } catch (_e) {
1291
+ /* never throw out of a definition build - return what we have */
1292
+ }
1293
+ return defs;
1294
+ }
1295
+
1296
+ /**
1297
+ * Resolve a lean downstream name + args into a forwarding executor for toolfunnel_run_tool. Matches
1298
+ * by ITERATION over discovered tools (computing each tool's surfaced name) - never by parsing the
1299
+ * name (underscore-ambiguous). The execute thunk lazy-(re)connects via ensureConnected and UNWRAPS
1300
+ * the upstream MCP envelope to a clean payload, so run_tool returns the upstream's content (e.g.
1301
+ * "pong"), not a stringified envelope. The connect is INSIDE the thunk -> a PreToolUse deny spawns
1302
+ * nothing. The gate matches `toolName` (the surfaced name). Returns null if no connected + enabled
1303
+ * upstream advertises a tool with this surfaced name (-> protocol's clean "not runnable" error) -
1304
+ * the same connected/enabled predicate leanToolDefinitions lists by, so hidden means not runnable.
1305
+ * @param {string} name surfaced downstream name
1306
+ * @param {any} args
1307
+ * @returns {{ execute: () => Promise<any>, toolName: string, upstream: string } | null}
1308
+ */
1309
+ resolveLeanExecution(name, args) {
1310
+ if (!isNonEmptyString(name)) return null;
1311
+ for (const [upstreamId, tools] of this._tools) {
1312
+ if (!this._clients.has(upstreamId)) continue;
1313
+ const upstream = this._store.getUpstream(upstreamId);
1314
+ if (upstream && upstream.enabled === false) continue; // skip an explicitly-disabled upstream
1315
+ if (!Array.isArray(tools)) continue;
1316
+ for (const t of tools) {
1317
+ if (!t || !isNonEmptyString(t.name)) continue;
1318
+ if (this._surfacedName(upstreamId, t.name) !== name) continue;
1319
+ const realTool = t.name;
1320
+ const self = this;
1321
+ const execute = async () => {
1322
+ // allowConnect:false - the run path NEVER synchronously (re)connects (that would freeze the
1323
+ // stdio loop, starving pings). It uses a live client or joins an in-flight background
1324
+ // reconnect, else fails clean; the onClose-driven background reconnect owns recovery.
1325
+ const client = await self.ensureConnected(upstreamId, { allowConnect: false });
1326
+ self._warnIfPinned(upstreamId, realTool);
1327
+ const envelope = await client.callTool(realTool, args);
1328
+ // Preserve the upstream's failure signal. callTool RESOLVES even on isError:true, so a
1329
+ // failed upstream call must become a THROW -> gatedRun returns { ok:false } -> run_tool
1330
+ // surfaces isError:true. Otherwise a failed call would be reported as success - and the
1331
+ // lean path must agree with curated-direct's isError passthrough.
1332
+ const payload = unwrapEnvelope(envelope);
1333
+ if (envelope && typeof envelope === 'object' && envelope.isError === true) {
1334
+ const text = typeof payload === 'string' ? payload : safeStringify(payload);
1335
+ const err = new Error(text && text.length ? text : 'upstream tool reported an error');
1336
+ err.upstreamToolError = true;
1337
+ throw err;
1338
+ }
1339
+ return payload;
1340
+ };
1341
+ return { execute, toolName: name, upstream: upstreamId };
1342
+ }
1343
+ }
1344
+ return null;
1345
+ }
1346
+
1347
+ /**
1348
+ * resolveRawExecution - the passthrough (WRAP) twin of resolveLeanExecution. Its execute returns
1349
+ * the upstream's tools/call result VERBATIM - multi-block content, isError, structuredContent
1350
+ * and any future fields untouched. A wrapped client must receive exactly what a direct client
1351
+ * would; the lean unwrap (single text block, throw-on-isError) destroys that. No unwrap, no
1352
+ * throw-on-isError: the envelope IS the product. Uses client.request() so a modern upstream
1353
+ * gets its per-request _meta trio.
1354
+ * @param {string} name surfaced downstream name
1355
+ * @param {any} args
1356
+ * @returns {{ execute: () => Promise<any>, toolName: string, upstream: string } | null}
1357
+ */
1358
+ resolveRawExecution(name, args, meta, out) {
1359
+ if (!isNonEmptyString(name)) return null;
1360
+ for (const [upstreamId, tools] of this._tools) {
1361
+ if (!this._clients.has(upstreamId)) continue;
1362
+ const upstream = this._store.getUpstream(upstreamId);
1363
+ if (upstream && upstream.enabled === false) continue; // skip an explicitly-disabled upstream
1364
+ if (!Array.isArray(tools)) continue;
1365
+ for (const t of tools) {
1366
+ if (!t || !isNonEmptyString(t.name)) continue;
1367
+ if (this._surfacedName(upstreamId, t.name) !== name) continue;
1368
+ const realTool = t.name;
1369
+ const self = this;
1370
+ const execute = async () => {
1371
+ // allowConnect:false - same freeze-avoidance rule as the lean path.
1372
+ const client = await self.ensureConnected(upstreamId, { allowConnect: false });
1373
+ self._warnIfPinned(upstreamId, realTool);
1374
+ const params = { name: realTool, arguments: args == null ? {} : args };
1375
+ // The caller's request-scoped _meta (progressToken, trace keys - already stripped of
1376
+ // protocol keys) rides the forward: a direct server would receive it, so the wrapped
1377
+ // one must too - without it the upstream never emits progress for the call.
1378
+ if (meta && typeof meta === 'object' && Object.keys(meta).length) params._meta = meta;
1379
+ // `out.rpcId` is set synchronously at issue time - the caller's cancel-translation
1380
+ // hook (the same contract as forwardRaw's).
1381
+ return await client.request('tools/call', params, out);
1382
+ };
1383
+ return { execute, toolName: name, upstream: upstreamId };
1384
+ }
1385
+ }
1386
+ return null;
1387
+ }
1388
+
1389
+ /**
1390
+ * Close every cached client and clear the caches. Idempotent - safe to call twice and
1391
+ * safe when nothing was ever connected. NEVER throws (close() on McpClient never throws).
1392
+ * @returns {Promise<void>}
1393
+ */
1394
+ async closeAll() {
1395
+ this._closed = true; // latch BEFORE teardown so any in-flight execute thunk refuses to re-spawn
1396
+ for (const [, timer] of this._reconnectTimers) {
1397
+ try { clearTimeout(timer); } catch (_e) { /* ignore */ }
1398
+ }
1399
+ this._reconnectTimers.clear();
1400
+ this._reconnecting.clear(); // no in-flight attempt survives teardown (its finally is a no-op then)
1401
+ for (const [id, client] of this._clients) {
1402
+ try {
1403
+ if (client && typeof client.close === 'function') client.close();
1404
+ // Activity log (self-gating): the disconnect half. A reload closes the old aggregator here,
1405
+ // so a reconnect reads as a disconnect line followed by a connect line for the same id.
1406
+ logger.log({ type: 'mcp', event: 'disconnect', upstream: id });
1407
+ } catch (_e) {
1408
+ /* McpClient.close never throws, but never let teardown sink the loop */
1409
+ }
1410
+ }
1411
+ this._clients.clear();
1412
+ this._tools.clear();
1413
+ }
1414
+
1415
+ // ── internals ──────────────────────────────────────────────────────────────
1416
+
1417
+ /**
1418
+ * Connect a single upstream entry and cache the client + its discovered tools.
1419
+ * Throws on factory (isolation), connect, or listTools failure - callers decide
1420
+ * whether to collect (connectAll) or surface (discover) the error. On throw, the
1421
+ * caller is responsible for _discard()-ing the id.
1422
+ * @param {object} upstream a normalised ExposeStore upstream
1423
+ */
1424
+ async _connectOne(upstream) {
1425
+ // The factory may throw (isolation guard) - that propagates out as a connect failure. Pass an
1426
+ // onClose so an UNEXPECTED upstream death triggers a BACKGROUND reconnect (not a lazy one in the
1427
+ // run path, which would freeze the stdio chain).
1428
+ const client = this._clientFactory(upstream, () => this._handleUpstreamDown(upstream.id));
1429
+ if (!client || typeof client.connect !== 'function') {
1430
+ throw new Error(`clientFactory returned an invalid client for "${upstream.id}"`);
1431
+ }
1432
+ // Bridge this upstream's server-initiated change-notifications to the transport (which fans them
1433
+ // out to modern subscriptions/listen streams). Filtered to the known change methods so arbitrary
1434
+ // upstream chatter never reaches a client. NEVER throws.
1435
+ client.onNotification = (n) => this._forwardUpstreamNotification(upstream.id, n);
1436
+ // Elicitation bridge: surface server-initiated requests with the upstream id + the live client (the
1437
+ // handler answers on it). Guarded so a handler bug can never break the client's read loop.
1438
+ client.onServerRequest = (m) => {
1439
+ try {
1440
+ if (this._closed) { client.respondToServerError(m.id, -32603, 'shutting down'); return; }
1441
+ this.onUpstreamServerRequest(upstream.id, m, client);
1442
+ } catch (_e) {
1443
+ try { client.respondToServerError(m.id, -32603, 'request failed'); } catch (_e2) { /* ignore */ }
1444
+ }
1445
+ };
1446
+ // Cache the client BEFORE connect so a connect-failure path can still _discard() and
1447
+ // close any half-spawned child.
1448
+ this._clients.set(upstream.id, client);
1449
+ try {
1450
+ await client.connect();
1451
+ // The LIST is part of the connect contract: a handshake that cannot list its tools is a
1452
+ // FAILED connect to every caller, and the era observation must not outlive it either.
1453
+ await this._listAndCache(upstream.id);
1454
+ } catch (err) {
1455
+ // The failed attempt may have been era-HINTED (probe skipped on the memo). Whatever the
1456
+ // cause - handshake or the post-handshake list - a failure invalidates the observation:
1457
+ // clear it so the NEXT attempt re-runs the full negotiation. An upstream upgraded to
1458
+ // modern-only across a restart recovers on the following backoff retry instead of failing
1459
+ // hinted forever.
1460
+ this._eraMemo.delete(upstream.id);
1461
+ throw err;
1462
+ }
1463
+ // Remember the negotiated era so a death-driven reconnect can skip the probe (eraHint) - but
1464
+ // only a DEFINITIVE observation (the probe was ANSWERED). A probe that timed out proves
1465
+ // nothing about the upstream's eras, and memoising that fallback would pin a merely-SLOW
1466
+ // dual-era upstream to legacy on every future reconnect. A hinted connect (probe skipped)
1467
+ // leaves the existing memo in place.
1468
+ if (client.eraDefinitive !== false) this._eraMemo.set(upstream.id, client.era);
1469
+ // Re-arm any agreed resource subscriptions on the fresh process - every connect
1470
+ // path funnels through here, so reconnects and reloads replay uniformly.
1471
+ this._replaySubscriptions(upstream.id);
1472
+ // Activity log (self-gating; no-op unless logging is enabled): the upstream half of connect
1473
+ // logging. EVERY connect flows through here - startup connectAll, a live reload, a lazy
1474
+ // discover, and (later) a health-driven reconnect - so all of them are logged uniformly.
1475
+ logger.log({
1476
+ type: 'mcp',
1477
+ event: 'connect',
1478
+ upstream: upstream.id,
1479
+ command: upstream.command,
1480
+ tools: (this._tools.get(upstream.id) || []).length,
1481
+ });
1482
+ // Legacy shim STARTUP warning (the pin's contract: warn at startup AND per call, naming the
1483
+ // version). stderr, so the operator sees it without the client's content ever growing.
1484
+ if (upstream.legacyPin === true) {
1485
+ try {
1486
+ process.stderr.write(
1487
+ `[toolfunnel] legacy shim: upstream "${upstream.id}" is PINNED to MCP ${LEGACY_UPSTREAM_VERSION} ` +
1488
+ '(legacyPin) - this gateway keeps it working for modern clients; it cannot speak 2026-07-28 itself.\n'
1489
+ );
1490
+ } catch (_e) { /* never let a warning sink a connect */ }
1491
+ logger.log({ type: 'mcp', event: 'legacy_shim_connect', upstream: upstream.id, protocolVersion: LEGACY_UPSTREAM_VERSION });
1492
+ }
1493
+ }
1494
+
1495
+ /** tools/list one connected upstream and cache the result; returns a clone. */
1496
+ async _listAndCache(upstreamId) {
1497
+ const client = this._clients.get(upstreamId);
1498
+ if (!client) throw new Error(`no connected client for "${upstreamId}"`);
1499
+ const tools = await client.listTools();
1500
+ const safe = Array.isArray(tools) ? tools.filter((t) => t && isNonEmptyString(t.name)) : [];
1501
+ this._tools.set(upstreamId, safe);
1502
+ return cloneTools(safe);
1503
+ }
1504
+
1505
+ /** Tear down + forget a cached client (used on a failed connect). Never throws. */
1506
+ _discard(upstreamId) {
1507
+ const client = this._clients.get(upstreamId);
1508
+ if (client && typeof client.close === 'function') {
1509
+ try { client.close(); } catch (_e) { /* never throw */ }
1510
+ }
1511
+ this._clients.delete(upstreamId);
1512
+ this._tools.delete(upstreamId);
1513
+ }
1514
+
1515
+ /**
1516
+ * Shared lookup behind isExposed / resolveExposedExecution: find the ENABLED expose
1517
+ * entry whose downstream name === `name`, whose upstream is connected AND enabled, and
1518
+ * whose real tool the upstream advertises. Returns the resolution context or null.
1519
+ * @param {string} name
1520
+ * @returns {{ client:object, realTool:string, upstream:string, exposedName:string } | null}
1521
+ */
1522
+ _findExposedExecution(name) {
1523
+ if (!isNonEmptyString(name)) return null;
1524
+ let exposed;
1525
+ try {
1526
+ exposed = this._store.listExposed({ enabledOnly: true });
1527
+ } catch (_err) {
1528
+ return null;
1529
+ }
1530
+ for (const e of exposed) {
1531
+ if (!e) continue;
1532
+ if (this._store.exposedName(e) !== name) continue;
1533
+ const client = this._clients.get(e.upstream);
1534
+ if (!client) continue; // upstream not connected
1535
+ const upstream = this._store.getUpstream(e.upstream);
1536
+ if (upstream && upstream.enabled === false) continue; // skip an explicitly-disabled upstream
1537
+ const upstreamTools = this._tools.get(e.upstream) || [];
1538
+ if (!upstreamTools.some((t) => t && t.name === e.tool)) continue; // tool not advertised
1539
+ return { client, realTool: e.tool, upstream: e.upstream, exposedName: name };
1540
+ }
1541
+ return null;
1542
+ }
1543
+ }
1544
+
1545
+ // ── small helpers (no external deps) ───────────────────────────────────────────
1546
+
1547
+ /** Extract a clean message from any thrown value. */
1548
+ function errMsg(err) {
1549
+ return (err && err.message) || String(err);
1550
+ }
1551
+
1552
+ /** JSON.stringify that never throws (circular/oddball values fall back to String). */
1553
+ function safeStringify(value) {
1554
+ try { return JSON.stringify(value); } catch (_e) { return String(value); }
1555
+ }
1556
+
1557
+ /**
1558
+ * Turn an upstream MCP tools/call envelope { content:[...], isError? } into a clean payload for the
1559
+ * LEAN run path. A single text block -> its string (so toolfunnel_run_tool returns "pong", matching
1560
+ * what the curated-direct content passthrough surfaces); otherwise the content array; otherwise the
1561
+ * value as-is when it isn't an envelope. This is what avoids double-wrapping the envelope as JSON
1562
+ * inside wrapProtocolResult (the curated-direct path passes the envelope through transparently
1563
+ * instead; the lean path goes through protocol.runTool -> wrapProtocolResult, so it unwraps here).
1564
+ * NOTE: an upstream isError:true is surfaced as its text content with ok:true (homogeneous
1565
+ * with how local tools surface error text) - mapping isError -> ok:false is a later concern.
1566
+ * @param {*} envelope
1567
+ * @returns {*}
1568
+ */
1569
+ function unwrapEnvelope(envelope) {
1570
+ if (!envelope || typeof envelope !== 'object') return envelope;
1571
+ const content = envelope.content;
1572
+ if (Array.isArray(content)) {
1573
+ if (content.length === 1 && content[0] && content[0].type === 'text' && typeof content[0].text === 'string') {
1574
+ return content[0].text;
1575
+ }
1576
+ return content;
1577
+ }
1578
+ return envelope;
1579
+ }
1580
+
1581
+ /** Plain-JSON deep clone (schemas are JSON; structuredClone may be absent on old node). */
1582
+ function cloneJson(value) {
1583
+ return JSON.parse(JSON.stringify(value));
1584
+ }
1585
+
1586
+ /** The upstream tool-def metadata the funnel FORWARDS onto advertised defs.
1587
+ * ICONS ARE WITHHELD by policy: 2025-11-25 and 2026-07-28 both require icon consumers to
1588
+ * verify icon URIs are SAME-ORIGIN with the server, so gateway-forwarded icons are third-party
1589
+ * URLs a conforming client must reject - or worse, trust as ours. Reversible (adding a field
1590
+ * later is non-breaking); the decision is open - forwarding them later flips it here. */
1591
+ const FORWARDED_TOOL_META = Object.freeze(['title', 'annotations', 'outputSchema', '_meta', 'execution']);
1592
+
1593
+ /** Selectively copy the forwardable metadata from a RAW discovered def onto an advertised def.
1594
+ * NEVER a spread: lean defs carry internal routing ids (upstream/tool), and a spread would
1595
+ * also inherit unknown future fields sight-unseen (the explicit selective-add rule). Mutates + returns def. */
1596
+ function withForwardedToolMeta(def, raw) {
1597
+ if (!raw || typeof raw !== 'object') return def;
1598
+ for (const k of FORWARDED_TOOL_META) {
1599
+ if (raw[k] !== undefined && def[k] === undefined) def[k] = cloneJson(raw[k]);
1600
+ }
1601
+ return def;
1602
+ }
1603
+
1604
+ /** HTTP field-name token syntax (RFC 9110 §5.1) - the constraint on x-mcp-header values. */
1605
+ const XMCP_TCHAR = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1606
+
1607
+ /**
1608
+ * Strip INVALID `x-mcp-header` annotations from an advertised inputSchema, in place (0.7.0
1609
+ * ingest hygiene). The spec makes a single malformed annotation invalidate the WHOLE tool -
1610
+ * conforming Streamable-HTTP clients MUST drop it from tools/list - so forwarding a broken
1611
+ * upstream annotation verbatim makes the tool vanish client-side. Valid = on a pure
1612
+ * `properties` chain from the root, a non-empty tchar token, on a string/integer/boolean
1613
+ * param, case-insensitively unique among the valid set. Everything else is deleted (the TOOL
1614
+ * survives; the annotation was the contaminant). The WRAP path stays raw-verbatim - a wrapped
1615
+ * server's brokenness is presented faithfully, exactly as a direct connection would.
1616
+ * @param {object} schema the advertised (already-cloned) inputSchema - mutated
1617
+ * @returns {object} schema
1618
+ */
1619
+ function sanitiseXMcpHeaders(schema) {
1620
+ if (!schema || typeof schema !== 'object') return schema;
1621
+ const valid = []; // { node, name } - candidates that pass every per-node rule
1622
+ const strip = []; // nodes whose annotation is deleted
1623
+ (function walk(node, onChain) {
1624
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return;
1625
+ if (Object.prototype.hasOwnProperty.call(node, 'x-mcp-header')) {
1626
+ const v = node['x-mcp-header'];
1627
+ const okType = node.type === 'string' || node.type === 'integer' || node.type === 'boolean';
1628
+ if (onChain && typeof v === 'string' && XMCP_TCHAR.test(v) && okType) valid.push({ node, name: v.toLowerCase() });
1629
+ else strip.push(node);
1630
+ }
1631
+ for (const k of Object.keys(node)) {
1632
+ const child = node[k];
1633
+ if (!child || typeof child !== 'object') continue;
1634
+ if (k === 'properties' && !Array.isArray(child)) {
1635
+ for (const sub of Object.values(child)) walk(sub, onChain); // the chain continues
1636
+ } else if (Array.isArray(child)) {
1637
+ for (const el of child) walk(el, false); // items/oneOf/... break the chain
1638
+ } else {
1639
+ walk(child, false);
1640
+ }
1641
+ }
1642
+ })(schema, true);
1643
+ const seen = new Map();
1644
+ for (const e of valid) seen.set(e.name, (seen.get(e.name) || 0) + 1);
1645
+ for (const e of valid) if (seen.get(e.name) > 1) strip.push(e.node); // ambiguous duplicates: all go
1646
+ for (const n of strip) delete n['x-mcp-header'];
1647
+ return schema;
1648
+ }
1649
+
1650
+ /** Clone an array of tool defs so callers can't mutate the aggregator's cache. */
1651
+ function cloneTools(tools) {
1652
+ return Array.isArray(tools) ? tools.map((t) => cloneJson(t)) : [];
1653
+ }
1654
+
1655
+ module.exports = {
1656
+ Aggregator,
1657
+ // exported for unit tests / reuse
1658
+ defaultClientFactory,
1659
+ looksLikePath,
1660
+ isInside,
1661
+ unwrapEnvelope,
1662
+ DEFAULT_ROOT,
1663
+ // 3.7: the forwardable def metadata + the selective-add - server.js's hot-promotion
1664
+ // projection uses the same list so the two advertised paths can never drift apart again.
1665
+ FORWARDED_TOOL_META,
1666
+ withForwardedToolMeta,
1667
+ // 4.3: ingest hygiene for x-mcp-header annotations (exported for tests).
1668
+ sanitiseXMcpHeaders,
1669
+ // A3: the wrap-time SECURITY NOTICE (bin/toolfunnel.js) enumerates the same classes the guard
1670
+ // judges - shared lists, so the two surfaces can never classify differently.
1671
+ isDriveRelative,
1672
+ CODE_OPT_ENV,
1673
+ CODE_PATH_ENV,
1674
+ };