toolfunnel 0.5.0 → 0.6.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 (69) hide show
  1. package/README.md +231 -167
  2. package/bin/toolfunnel.js +372 -147
  3. package/docs/KNOWN_BUGS.md +99 -33
  4. package/docs/MANUAL.pdf +0 -0
  5. package/docs/design.md +70 -0
  6. package/docs/packaging.md +115 -115
  7. package/hooks/hooks.manifest.json +27 -27
  8. package/hooks/scripts/example-audit.js +21 -21
  9. package/hooks/scripts/example-deny-dangerous.js +31 -31
  10. package/mcp/expose.example.json +30 -30
  11. package/mcp/servers/mock-modern/server.js +147 -0
  12. package/mcp/servers/mock-upstream/server.js +192 -12
  13. package/package.json +1 -1
  14. package/src/auth/config.js +174 -174
  15. package/src/auth/install.js +181 -181
  16. package/src/auth/resource-server.js +344 -344
  17. package/src/core/config-home.js +134 -134
  18. package/src/core/events.js +105 -105
  19. package/src/core/hook-engine.js +275 -275
  20. package/src/core/hook-loader.js +791 -791
  21. package/src/core/hook-runner.js +346 -346
  22. package/src/core/logger.js +171 -171
  23. package/src/core/matcher.js +51 -51
  24. package/src/core/metrics.js +75 -75
  25. package/src/core/requires.js +138 -138
  26. package/src/core/server-config.js +98 -77
  27. package/src/core/tool-registry.js +180 -180
  28. package/src/extend/add-hook.md +152 -142
  29. package/src/extend/add-mcp.md +122 -121
  30. package/src/extend/configure.md +87 -0
  31. package/src/extend/create-tool.md +168 -152
  32. package/src/extend/howto.js +102 -98
  33. package/src/extend/package.md +187 -187
  34. package/src/extend/wrap.md +99 -0
  35. package/src/mcp/aggregator.js +1246 -807
  36. package/src/mcp/expose-store.js +460 -430
  37. package/src/mcp/gated-run.js +201 -194
  38. package/src/mcp/http-transport.js +1311 -1012
  39. package/src/mcp/mcp-client.js +907 -530
  40. package/src/mcp/modern.js +372 -0
  41. package/src/mcp/protocol.js +468 -466
  42. package/src/mcp/server.js +2688 -1405
  43. package/src/packages/packager.js +715 -715
  44. package/src/tools/drift.js +138 -138
  45. package/src/tools/registry.js +513 -513
  46. package/src/tools/tool-state.js +170 -104
  47. package/src/ui/public/app.js +1174 -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 +1348 -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 +112 -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 +227 -216
@@ -1,807 +1,1246 @@
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 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, 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.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, allowOutsidePaths, clientInfo) {
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
+ // allowOutsidePaths: TRUE only for the currently-WRAPPED upstream (transparent-wrapper mode -
125
+ // the operator explicitly made this server the entire surface, e.g. server-filesystem serving
126
+ // a documents folder). Warn instead of refuse; funnel-mode upstreams keep the hard guard.
127
+ for (const arg of args) {
128
+ if (looksLikePath(arg) && !isInside(v3Root, arg)) {
129
+ if (allowOutsidePaths === true) {
130
+ process.stderr.write(`[toolfunnel] isolation: WRAPPED upstream "${id}" uses a path outside the gateway root ` +
131
+ `("${arg}") - permitted in transparent-wrapper mode. To restrict what it can do post-wrap, see the ` +
132
+ `manual's "Wrapping & security" section (PreToolUse gate, per-tool enabled:false).\n`);
133
+ break; // one warning covers the upstream; every arg is permitted under the wrap
134
+ }
135
+ throw new Error(`isolation: upstream ${id} references a path outside the gateway root`);
136
+ }
137
+ }
138
+
139
+ return new McpClient({
140
+ id: upstream.id,
141
+ command: upstream.command,
142
+ args: upstream.args,
143
+ env: upstream.env,
144
+ // Child cwd from config - the wrap era-probe reads it too; it never survived the store
145
+ // before. Default = the CONFIG HOME (v3Root), NOT the gateway's process cwd:
146
+ // the isolation guard above resolves relative args against the home, so the spawn must
147
+ // resolve them against the SAME base or a guard-passing relative path fails to spawn
148
+ // whenever --config-dir differs from the launch directory (guard-base and spawn-base agree
149
+ // by construction).
150
+ cwd: isNonEmptyString(upstream && upstream.cwd) ? upstream.cwd : v3Root,
151
+ // Per-upstream `timeoutMs` config -> the client's PAYLOAD window (tools/call | prompts/get |
152
+ // resources/read; default 120 s).
153
+ toolTimeoutMs: Number.isFinite(upstream && upstream.timeoutMs) && upstream.timeoutMs > 0
154
+ ? upstream.timeoutMs : undefined,
155
+ // Per-upstream `requestTimeoutMs` config -> the CONTROL window (handshake/list/discover/
156
+ // ping; default 10 s = the dead-upstream detector). Opt-in for slow-boot servers that
157
+ // cannot answer initialize inside 10 s - without it they can never be attached at all.
158
+ requestTimeoutMs: Number.isFinite(upstream && upstream.requestTimeoutMs) && upstream.requestTimeoutMs > 0
159
+ ? upstream.requestTimeoutMs : undefined,
160
+ // legacyPin FORCES the legacy era: skip the modern server/discover probe and go straight to
161
+ // the initialize handshake, so a pinned upstream is genuinely spoken to as 2024-11-05 (the pin
162
+ // is an ENFORCED policy, not just a warning). Off by default.
163
+ forceLegacy: !!(upstream && upstream.legacyPin === true),
164
+ // modernOnly (legacyPin's mirror): refuse the legacy fallback - a non-modern upstream fails
165
+ // the connect with a clear error instead of negotiating down. Store validation refuses the
166
+ // legacyPin+modernOnly contradiction before it ever reaches here.
167
+ modernOnly: !!(upstream && upstream.modernOnly === true),
168
+ // clientInfo: the identity presented to this upstream (identity mirroring / configured
169
+ // identity). null/undefined -> McpClient's built-in default, wire behaviour unchanged.
170
+ clientInfo: clientInfo || undefined,
171
+ onClose, // unexpected death -> the aggregator schedules a background reconnect
172
+ });
173
+ }
174
+
175
+ /**
176
+ * Aggregator - owns the live upstream connections and the curated-expose computation.
177
+ *
178
+ * Lifecycle: `new Aggregator({ store, v3Root, clientFactory })`
179
+ * -> `await connectAll()` (or `await discover(id)` lazily)
180
+ * -> `exposedToolDefinitions()` / `resolveExposedExecution(name, args)`
181
+ * -> `await closeAll()` (idempotent).
182
+ */
183
+ class Aggregator {
184
+ /**
185
+ * @param {object} opts
186
+ * @param {object} opts.store an ExposeStore (the on-disk MCP config).
187
+ * @param {string} [opts.v3Root] sandbox root for the isolation guard (default: the gateway root).
188
+ * @param {Function} [opts.clientFactory] (upstreamEntry, v3Root) -> McpClient. Default enforces isolation.
189
+ * @param {Function} [opts.wrapTargetProvider] () -> the currently-WRAPPED upstream id (or null).
190
+ * Read fresh at each connect: the wrapped upstream is EXEMPT from the path-isolation
191
+ * guard (by design - a wrap is an explicit "this server IS my whole
192
+ * surface" declaration, so ToolFunnel is a transparent wrapper in that incidence; the
193
+ * operator gets a strong warning + post-wrap restriction docs instead of a refusal).
194
+ * Funnel-mode upstreams keep the guard unchanged.
195
+ * @param {Function} [opts.clientInfoProvider] (upstreamId) -> {name, version}|null. The identity
196
+ * to PRESENT to that upstream. Read fresh at each connect (same pattern as the wrap-target
197
+ * provider) so a mirror captured after boot is honoured by the next (re)connect. null ->
198
+ * McpClient's built-in default.
199
+ */
200
+ constructor({ store, v3Root, clientFactory, onToolsChanged, wrapTargetProvider, clientInfoProvider } = {}) {
201
+ if (!store || typeof store !== 'object') {
202
+ throw new Error('Aggregator: a `store` (ExposeStore) is required');
203
+ }
204
+ this._store = store;
205
+ this._v3Root = isNonEmptyString(v3Root) ? v3Root : DEFAULT_ROOT;
206
+ // Called when the LIVE tool set changes OUT OF BAND (a background reconnect recovers or finally
207
+ // loses an upstream) so the transport can emit notifications/tools/list_changed. Default no-op;
208
+ // the server wires it to emitToolsListChanged(send). Settable so reloadExpose can re-wire the
209
+ // new instance.
210
+ this.onToolsChanged = typeof onToolsChanged === 'function' ? onToolsChanged : () => {};
211
+ // Called with (upstreamId, notification) for each server-initiated CHANGE notification from an
212
+ // upstream (resources/updated, resources/list_changed, prompts/list_changed, tools/list_changed)
213
+ // so the transport can bridge it to a modern client's subscriptions/listen stream. Default no-op;
214
+ // the server/http host wires it. Settable so reloadExpose can re-wire the new instance.
215
+ this.onUpstreamNotification = () => {};
216
+ // Called with (upstreamId, requestMsg, client) for each SERVER-INITIATED REQUEST from an
217
+ // upstream (elicitation/create, sampling/createMessage, roots/list - Bridge B). The handler
218
+ // owns answering via client.respondToServer(Error). Default: -32601, so an unwired build
219
+ // never leaves an upstream holding an open request. Settable; reloadExpose carries it over.
220
+ this.onUpstreamServerRequest = (uid, msg, client) => {
221
+ try { client.respondToServerError(msg.id, -32601, 'Method not found: ' + msg.method); } catch (_e) { /* never throw */ }
222
+ };
223
+ // When a passthrough WRAP is active, the wrapped upstream's request-scoped chatter
224
+ // (notifications/message, notifications/progress) also bridges - connected directly, the
225
+ // client would receive it. The server keeps this current with the live wrap state.
226
+ this.wrapChatterUpstream = null;
227
+ this._wrapTargetProvider = typeof wrapTargetProvider === 'function' ? wrapTargetProvider : null;
228
+ this._clientInfoProvider = typeof clientInfoProvider === 'function' ? clientInfoProvider : null;
229
+ // The factory receives (upstream, v3Root, onClose). A caller-supplied factory may ignore the
230
+ // extra args; the default uses v3Root for isolation and onClose for death-driven reconnect.
231
+ // The wrap-target check runs PER CONNECT (fresh provider read), so a wrap set after boot is
232
+ // honoured by the next connect attempt.
233
+ this._clientFactory =
234
+ typeof clientFactory === 'function'
235
+ ? (upstream, onClose) => clientFactory(upstream, this._v3Root, onClose)
236
+ : (upstream, onClose) => defaultClientFactory(upstream, this._v3Root, onClose,
237
+ this._isWrapTarget(upstream && upstream.id),
238
+ this._readClientInfo(upstream && upstream.id));
239
+
240
+ /** @type {Map<string, object>} upstreamId -> connected McpClient */
241
+ this._clients = new Map();
242
+ /** @type {Map<string, Array>} upstreamId -> discovered tool defs [{name,description,inputSchema}] */
243
+ this._tools = new Map();
244
+ /** @type {Map<string, Promise>} upstreamId -> in-flight connect promise (race guard for ensureConnected) */
245
+ this._connecting = new Map();
246
+ /** @type {Set<string>} agreed resource-subscription URIs - replayed onto every (re)connect
247
+ * of a subscribe-capable legacy upstream so the channel survives reconnects */
248
+ this._subscribedUris = new Set();
249
+ /** @type {Map<string, any>} upstreamId -> pending background-reconnect timer (one per upstream) */
250
+ this._reconnectTimers = new Map();
251
+ /** Set true by closeAll(). A torn-down aggregator (e.g. swapped out by reloadExpose) must NEVER
252
+ * (re)connect - a captured execute thunk holding this instance would otherwise spawn an orphan
253
+ * upstream child on it that nothing ever closes. ensureConnected/connectAll check this. */
254
+ this._closed = false;
255
+ }
256
+
257
+ /**
258
+ * Connect every ENABLED upstream in the store, caching each connected client and its
259
+ * discovered tools. NEVER throws - a per-upstream failure (isolation guard, spawn
260
+ * failure, handshake timeout, listTools failure) is collected into failed[]. An
261
+ * upstream already connected (cached) is treated as connected without reconnecting.
262
+ *
263
+ * @returns {Promise<{ connected: string[], failed: Array<{id:string, error:string}> }>}
264
+ */
265
+ async connectAll() {
266
+ const connected = [];
267
+ const failed = [];
268
+ if (this._closed) return { connected, failed }; // a closed (torn-down) aggregator never connects
269
+
270
+ let upstreams;
271
+ try {
272
+ upstreams = this._store.listUpstreams();
273
+ } catch (err) {
274
+ // listUpstreams() shouldn't throw (it clones), but never let it sink connectAll.
275
+ return { connected, failed: [{ id: '(store)', error: errMsg(err) }] };
276
+ }
277
+
278
+ for (const upstream of upstreams) {
279
+ if (!upstream || upstream.enabled !== true) continue; // only ENABLED upstreams
280
+
281
+ const id = upstream.id;
282
+ if (this._clients.has(id)) {
283
+ // Already connected this session - keep it; don't double-spawn.
284
+ connected.push(id);
285
+ continue;
286
+ }
287
+
288
+ try {
289
+ await this._connectOne(upstream);
290
+ connected.push(id);
291
+ } catch (err) {
292
+ // Clean up any half-built client so a failure leaves no zombie/cache entry.
293
+ this._discard(id);
294
+ const error = errMsg(err);
295
+ logger.log({ type: 'mcp', event: 'connect_failed', upstream: id, error });
296
+ failed.push({ id, error });
297
+ }
298
+ }
299
+
300
+ return { connected, failed };
301
+ }
302
+
303
+ /**
304
+ * Discover one upstream's tool surface. Connects the upstream if it isn't already
305
+ * (lazily, honouring the isolation guard), runs tools/list, caches and returns the
306
+ * raw tool definitions [{name, description, inputSchema}]. This is what the MCP
307
+ * Manager 'discover' button calls.
308
+ *
309
+ * Unlike connectAll this MAY reject (it is a direct user action, so the UI wants the
310
+ * error) - but it cleans up a failed connection so no zombie child is left.
311
+ *
312
+ * @param {string} upstreamId
313
+ * @returns {Promise<Array<{name:string, description?:string, inputSchema?:object}>>}
314
+ */
315
+ async discover(upstreamId) {
316
+ if (!isNonEmptyString(upstreamId)) {
317
+ throw new Error('Aggregator.discover: upstreamId (non-empty string) is required');
318
+ }
319
+
320
+ // Route through ensureConnected: it JOINS an in-flight connect via _connecting instead of
321
+ // racing it - two concurrent discover() calls used to double-spawn the child and leak the
322
+ // loser without closing it. ensureConnected also reaps its own failed connects.
323
+ // allowDisabled: discover is the ONE caller permitted to connect a disabled upstream -
324
+ // inspecting its tools pre-enable worked before the race fix and stays supported.
325
+ try {
326
+ await this.ensureConnected(upstreamId, { allowDisabled: true });
327
+ } catch (err) {
328
+ throw new Error(`Aggregator.discover: cannot connect "${upstreamId}": ${errMsg(err)}`);
329
+ }
330
+ // Re-list even when the fast path returned a cached client - the discover button must always
331
+ // reflect live state (a fresh connect lists twice; cheap, and the semantics stay honest).
332
+ return await this._listAndCache(upstreamId);
333
+ }
334
+
335
+ /**
336
+ * @returns {Object<string, Array>} a clone map of upstreamId -> cached discovered tools.
337
+ * Only includes upstreams that have been connected/discovered this session.
338
+ */
339
+ toolsByUpstream() {
340
+ const out = {};
341
+ for (const [id, tools] of this._tools) {
342
+ out[id] = cloneTools(tools);
343
+ }
344
+ return out;
345
+ }
346
+
347
+ /**
348
+ * The CURATED-DIRECT tool definitions to advertise downstream. For each ENABLED
349
+ * expose[] entry whose upstream is CONNECTED and ACTUALLY advertises the named tool:
350
+ * - name = store.exposedName(entry) (the downstream `as` name)
351
+ * - description = '[' + upstream + '] ' + (upstream tool description || 'tool')
352
+ * - inputSchema = the upstream tool's inputSchema || { type:'object' }
353
+ *
354
+ * Entries whose upstream isn't connected, or whose named tool the upstream doesn't
355
+ * advertise, are silently skipped (you can't expose a tool that isn't there).
356
+ *
357
+ * @returns {Array<{name:string, description:string, inputSchema:object}>}
358
+ */
359
+ exposedToolDefinitions() {
360
+ const defs = [];
361
+ let exposed;
362
+ try {
363
+ exposed = this._store.listExposed({ enabledOnly: true });
364
+ } catch (_err) {
365
+ return defs; // never throw out of a definition build
366
+ }
367
+
368
+ for (const e of exposed) {
369
+ if (!e || !this._clients.has(e.upstream)) continue; // upstream not connected
370
+ const upstreamTools = this._tools.get(e.upstream) || [];
371
+ const upstreamTool = upstreamTools.find((t) => t && t.name === e.tool);
372
+ if (!upstreamTool) continue; // upstream doesn't actually advertise this tool
373
+
374
+ const name = this._store.exposedName(e);
375
+ const desc =
376
+ isNonEmptyString(upstreamTool.description) ? upstreamTool.description : 'tool';
377
+ const inputSchema =
378
+ upstreamTool.inputSchema && typeof upstreamTool.inputSchema === 'object'
379
+ ? upstreamTool.inputSchema
380
+ : { type: 'object' };
381
+
382
+ defs.push({
383
+ name,
384
+ description: `[${e.upstream}] ${desc}`,
385
+ inputSchema: cloneJson(inputSchema),
386
+ });
387
+ }
388
+ return defs;
389
+ }
390
+
391
+ /**
392
+ * Is `name` a downstream `as` name currently exposed (enabled) AND backed by a
393
+ * connected upstream that advertises the underlying tool? Mirrors the set
394
+ * exposedToolDefinitions() advertises.
395
+ * @param {string} name
396
+ * @returns {boolean}
397
+ */
398
+ isExposed(name) {
399
+ return this._findExposedExecution(name) !== null;
400
+ }
401
+
402
+ /**
403
+ * Resolve a downstream `as` name + args into an executor. Returns
404
+ * { execute, toolName, upstream } | null
405
+ * where:
406
+ * - execute() invokes the connected client's callTool(<real upstream tool name>, args)
407
+ * - toolName = the downstream `as` (what PreToolUse matchers see - the gate matches
408
+ * the downstream name, execution hits the real upstream tool)
409
+ * - upstream = the upstream id
410
+ * Returns null if `name` is not exposed/enabled or its upstream isn't connected.
411
+ *
412
+ * @param {string} name downstream `as` name
413
+ * @param {any} args structured arguments forwarded verbatim to callTool
414
+ * @returns {{ execute: Function, toolName: string, upstream: string } | null}
415
+ */
416
+ resolveExposedExecution(name, args, meta) {
417
+ const hit = this._findExposedExecution(name);
418
+ if (!hit) return null;
419
+ const { client, realTool, upstream, exposedName } = hit;
420
+ return {
421
+ // The execute thunk is the seam the server calls AFTER the PreToolUse gate allows it.
422
+ execute: this._forwardExecutor(client, realTool, args, meta),
423
+ toolName: exposedName, // downstream name - the gate's matcher target
424
+ upstream,
425
+ };
426
+ }
427
+
428
+ // ── lean register forwarding (slice 2) ──────────────────────────────────────
429
+ // The LEAN path surfaces an attached upstream's tools through the 4 meta-tools (toolfunnel_list_tools
430
+ // / _tool_instructions / _run_tool) instead of injecting them top-level every turn. The full
431
+ // discovered set of every CONNECTED + enabled upstream is surfaced (attaching an MCP makes its
432
+ // tools appear with no per-tool curation); expose[]/hot governs only the SEPARATE top-level
433
+ // (curated-direct) promotion. A lean tool is surfaced under its enabled expose `as` if one exists,
434
+ // else the namespaced default `<upstream>_<tool>` - so the lean name equals the curated-direct name
435
+ // for an exposed tool and ONE PreToolUse rule gates both routes. All of this lives here in the
436
+ // aggregator (it owns the connections, the _clients/_tools caches, and the connect log chokepoint).
437
+
438
+ /**
439
+ * The single forward seam: a thunk that calls the upstream's real tool. Shared by the
440
+ * curated-direct path (resolveExposedExecution, transparent envelope passthrough) and the lean
441
+ * path (resolveLeanExecution, which unwraps). Kept tiny so both routes execute identically.
442
+ * @param {object} client a connected McpClient
443
+ * @param {string} realTool the upstream's own tool name
444
+ * @param {any} args
445
+ * @returns {() => Promise<any>}
446
+ */
447
+ _forwardExecutor(client, realTool, args, meta) {
448
+ return () => {
449
+ this._warnIfPinned(client.id, realTool);
450
+ return client.callTool(realTool, args, meta);
451
+ };
452
+ }
453
+
454
+ /**
455
+ * Legacy shim PER-CALL warning (the pin's contract: warn on every forwarded call, naming the
456
+ * upstream + version). Called from BOTH forward paths - curated-direct (_forwardExecutor) and
457
+ * lean (resolveLeanExecution's own closure; it cannot use _forwardExecutor because it needs
458
+ * ensureConnected + envelope unwrapping). Checked at CALL time so a live expose.json edit takes
459
+ * effect immediately; stderr + activity log, never the content. NEVER throws.
460
+ * @param {string} upstreamId
461
+ * @param {string} realTool the upstream's own tool name
462
+ */
463
+ _warnIfPinned(upstreamId, realTool) {
464
+ try {
465
+ const upstream = this._store.getUpstream(upstreamId);
466
+ if (upstream && upstream.legacyPin === true) {
467
+ process.stderr.write(
468
+ `[toolfunnel] legacy shim: forwarding "${realTool}" to pinned legacy upstream ` +
469
+ `"${upstreamId}" (MCP ${LEGACY_UPSTREAM_VERSION})\n`
470
+ );
471
+ logger.log({ type: 'mcp', event: 'legacy_shim_call', upstream: upstreamId, tool: realTool, protocolVersion: LEGACY_UPSTREAM_VERSION });
472
+ }
473
+ } catch (_e) { /* the warning must never affect the call */ }
474
+ }
475
+
476
+ /**
477
+ * Legacy-shim info for a surfaced OR original call name: { upstream, protocolVersion } when the
478
+ * tool belongs to a PINNED (legacyPin) upstream, else null. Used by the modern era to tag
479
+ * results with _meta["io.toolfunnel/legacyShim"] - metadata, never content. NEVER throws.
480
+ * @param {string} name the name a client called (surfaced `<upstream>_<tool>`/`as`, or the
481
+ * ORIGINAL tool name under passthrough)
482
+ * @returns {{ upstream: string, protocolVersion: string } | null}
483
+ */
484
+ legacyShimInfo(name) {
485
+ if (typeof name !== 'string' || name.length === 0) return null;
486
+ try {
487
+ const d = this.leanToolDefinitions().find((x) => x && (x.name === name || x.tool === name));
488
+ if (!d) return null;
489
+ const upstream = this._store.getUpstream(d.upstream);
490
+ if (!upstream || upstream.legacyPin !== true) return null;
491
+ return { upstream: d.upstream, protocolVersion: LEGACY_UPSTREAM_VERSION };
492
+ } catch (_e) {
493
+ return null;
494
+ }
495
+ }
496
+
497
+ /**
498
+ * The wrapped upstream's OWN identity, extracted from its captured `initialize` result - so a
499
+ * passthrough WRAP can present the wrapped server verbatim (indistinguishable from connecting to
500
+ * it directly, save for the ToolFunnel process). Returns { protocolVersion, serverInfo,
501
+ * capabilities, instructions } with best-effort extraction (some servers nest capabilities /
502
+ * instructions inside serverInfo), or null if the upstream isn't connected. NEVER throws.
503
+ * @param {string} upstreamId
504
+ * @returns {{ protocolVersion?:string, serverInfo?:object, capabilities?:object, instructions?:string } | null}
505
+ */
506
+ wrappedIdentity(upstreamId) {
507
+ try {
508
+ const client = this._clients.get(upstreamId);
509
+ if (!client || typeof client.initializeResult === 'undefined') return null;
510
+ const init = client.initializeResult;
511
+ if (!init || typeof init !== 'object') return null;
512
+ const si = init.serverInfo && typeof init.serverInfo === 'object' ? init.serverInfo : {};
513
+ // serverInfo passes VERBATIM minus the two fields some servers wrongly nest inside it
514
+ // (capabilities/instructions - extracted separately below). A whitelist here ate the spec's
515
+ // own serverInfo.title (2025-06-18) through the wrap - proven against the real
516
+ // server-everything (wrap-lab, 2026-07-17). Blocklist, so future identity fields survive.
517
+ const serverInfo = {};
518
+ for (const k of Object.keys(si)) {
519
+ if (k === 'capabilities' || k === 'instructions') continue;
520
+ serverInfo[k] = cloneJson(si[k]);
521
+ }
522
+ return {
523
+ protocolVersion: typeof init.protocolVersion === 'string' ? init.protocolVersion : undefined,
524
+ serverInfo: Object.keys(serverInfo).length ? serverInfo : undefined,
525
+ // capabilities / instructions: prefer top-level (standard), fall back to serverInfo-nested.
526
+ capabilities: (init.capabilities && typeof init.capabilities === 'object') ? init.capabilities
527
+ : (si.capabilities && typeof si.capabilities === 'object') ? si.capabilities : undefined,
528
+ instructions: typeof init.instructions === 'string' ? init.instructions
529
+ : typeof si.instructions === 'string' ? si.instructions : undefined,
530
+ };
531
+ } catch (_e) {
532
+ return null;
533
+ }
534
+ }
535
+
536
+ /**
537
+ * Forward a RAW JSON-RPC method to a connected upstream and return its result - the passthrough
538
+ * WRAP's relay for non-tool methods (resources/*, prompts/*, logging/*, ping...) so a wrapped
539
+ * server behaves exactly as it would connected directly. Uses a LIVE client only (no synchronous
540
+ * (re)connect - same rule as the lean run path). Throws if the upstream is not connected or the
541
+ * call fails; the caller shapes that into a JSON-RPC error.
542
+ * @param {string} upstreamId
543
+ * @param {string} method
544
+ * @param {any} params
545
+ * @returns {Promise<any>}
546
+ */
547
+ async forwardRaw(upstreamId, method, params, out) {
548
+ const client = await this.ensureConnected(upstreamId, { allowConnect: false });
549
+ if (!client || typeof client.request !== 'function') {
550
+ throw new Error(`upstream "${upstreamId}" is not connected`);
551
+ }
552
+ return await client.request(method, params, out);
553
+ }
554
+
555
+ /** The clientInfo to PRESENT to `upstreamId`, or null for the built-in. Fresh provider read per
556
+ * call (per-connect, same as the wrap-target check); NEVER throws. */
557
+ _readClientInfo(upstreamId) {
558
+ try {
559
+ const info = this._clientInfoProvider ? this._clientInfoProvider(upstreamId) : null;
560
+ return info && typeof info === 'object' &&
561
+ typeof info.name === 'string' && info.name.length ? info : null;
562
+ } catch (_e) {
563
+ return null; // a broken provider degrades to the built-in identity
564
+ }
565
+ }
566
+
567
+ /** Is `upstreamId` the currently-wrapped upstream? Fresh provider read per call; NEVER throws.
568
+ * Drives the per-connect isolation exemption (transparent-wrapper mode). */
569
+ _isWrapTarget(upstreamId) {
570
+ try {
571
+ return !!(this._wrapTargetProvider && isNonEmptyString(upstreamId) &&
572
+ this._wrapTargetProvider() === upstreamId);
573
+ } catch (_e) {
574
+ return false; // a broken provider must degrade to the SAFE default (guard applies)
575
+ }
576
+ }
577
+
578
+ /** Set the wrap-chatter scope. When the passthrough TARGET CHANGES (A->B, A->null, null->A) the
579
+ * recorded resource subscriptions belong to the OLD context and must not replay onto the new
580
+ * one - a client of wrap B never subscribed to wrap A's URIs. A
581
+ * same-value re-arm (every message does one) clears nothing. */
582
+ setWrapChatterUpstream(v) {
583
+ const next = v == null ? null : v;
584
+ if (next !== this.wrapChatterUpstream && this._subscribedUris instanceof Set) {
585
+ this._subscribedUris.clear();
586
+ }
587
+ this.wrapChatterUpstream = next;
588
+ }
589
+
590
+ /** Relay a client NOTIFICATION to an upstream (wrap passthrough: notifications/cancelled,
591
+ * notifications/progress ...). Fire-and-forget; never throws, never answers. */
592
+ notifyRaw(upstreamId, method, params) {
593
+ try {
594
+ const client = this._clients.get(upstreamId);
595
+ if (client && typeof client.notify === 'function') client.notify(method, params);
596
+ } catch (_e) { /* fire-and-forget */ }
597
+ }
598
+
599
+ /** TRUE if a connected upstream can ACTUALLY deliver per-URI resource updates. That means a
600
+ * LEGACY upstream advertising resources.subscribe (we forward the subscribes; it emits
601
+ * resources/updated). A MODERN upstream does NOT count: its only notification channel is a
602
+ * subscriptions/listen stream this client does not yet open (28-July item), so counting it
603
+ * agreed a channel nothing would ever feed. Under a wrap only the WRAPPED
604
+ * upstream counts - delivery is filtered to it, so another upstream honouring the channel
605
+ * would be agreed-then-dropped. The ack must never promise a dead channel. */
606
+ canHonourResourceSubscriptions() {
607
+ for (const [id, client] of this._clients) {
608
+ if (!client) continue;
609
+ if (this.wrapChatterUpstream && id !== this.wrapChatterUpstream) continue;
610
+ if (client.era === 'modern') continue;
611
+ const caps = client.initializeResult && client.initializeResult.capabilities;
612
+ if (caps && caps.resources && caps.resources.subscribe) return true;
613
+ }
614
+ return false;
615
+ }
616
+
617
+ /** Best-effort: forward resources/subscribe for each URI to every subscribe-capable legacy
618
+ * upstream in scope (the wrapped one only, under a wrap). The URIs are RECORDED
619
+ * so every later (re)connect replays them: a reconnected upstream is a fresh process that
620
+ * remembers no subscriptions, and without the replay the client's agreed channel went silently
621
+ * dead forever. Fire-and-forget; never throws. */
622
+ subscribeResources(uris) {
623
+ try {
624
+ const list = Array.isArray(uris) ? uris.filter((u) => typeof u === 'string' && u.length) : [];
625
+ if (!list.length) return;
626
+ for (const uri of list) this._subscribedUris.add(uri);
627
+ for (const [id, client] of this._clients) {
628
+ if (this.wrapChatterUpstream && id !== this.wrapChatterUpstream) continue;
629
+ if (!client || client.era !== 'legacy' || typeof client.request !== 'function') continue;
630
+ const caps = client.initializeResult && client.initializeResult.capabilities;
631
+ if (!(caps && caps.resources && caps.resources.subscribe)) continue;
632
+ for (const uri of list) client.request('resources/subscribe', { uri }).catch(() => {});
633
+ }
634
+ } catch (_e) { /* never throw */ }
635
+ }
636
+
637
+ /** Replay the recorded resource subscriptions onto ONE freshly-connected upstream.
638
+ * Called from _connectOne so every connect path - startup, lazy, background reconnect, reload -
639
+ * re-arms the channel. Same scope rules as subscribeResources. Never throws. */
640
+ _replaySubscriptions(upstreamId) {
641
+ try {
642
+ if (!this._subscribedUris || this._subscribedUris.size === 0) return;
643
+ if (this.wrapChatterUpstream && upstreamId !== this.wrapChatterUpstream) return;
644
+ const client = this._clients.get(upstreamId);
645
+ if (!client || client.era !== 'legacy' || typeof client.request !== 'function') return;
646
+ const caps = client.initializeResult && client.initializeResult.capabilities;
647
+ if (!(caps && caps.resources && caps.resources.subscribe)) return;
648
+ for (const uri of this._subscribedUris) client.request('resources/subscribe', { uri }).catch(() => {});
649
+ } catch (_e) { /* never throw */ }
650
+ }
651
+
652
+ /** The change-notification methods an upstream may push that we bridge to modern clients. Anything
653
+ * else from the upstream is ignored (request-scoped notifications ride their own request stream). */
654
+ static get BRIDGED_NOTIFICATIONS() {
655
+ return new Set([
656
+ 'notifications/tools/list_changed',
657
+ 'notifications/prompts/list_changed',
658
+ 'notifications/resources/list_changed',
659
+ 'notifications/resources/updated',
660
+ ]);
661
+ }
662
+
663
+ /**
664
+ * Forward a server-initiated CHANGE notification from an upstream to the transport hook, which
665
+ * fans it to modern subscriptions/listen streams. Only the known change methods pass; the
666
+ * notification is handed on verbatim (the transport tags + filters per subscription). NEVER
667
+ * throws (an onNotification handler must never break the client's read loop).
668
+ * @param {string} upstreamId
669
+ * @param {object} notification a JSON-RPC notification { method, params? }
670
+ */
671
+ _forwardUpstreamNotification(upstreamId, notification) {
672
+ try {
673
+ if (this._closed) return; // a swapped-out/torn-down aggregator must never fan out (F9)
674
+ if (!notification || typeof notification.method !== 'string') return;
675
+ const isWrapChatter = this.wrapChatterUpstream === upstreamId &&
676
+ (notification.method === 'notifications/message' || notification.method === 'notifications/progress');
677
+ if (!Aggregator.BRIDGED_NOTIFICATIONS.has(notification.method) && !isWrapChatter) return;
678
+ // Forward a CLEAN notification only - a misbehaving upstream's stray `id: null` field would
679
+ // read as a response to downstream parsers (F7).
680
+ const clean = { jsonrpc: '2.0', method: notification.method };
681
+ if (notification.params !== undefined) clean.params = notification.params;
682
+ const emit = () => {
683
+ try {
684
+ if (typeof this.onUpstreamNotification === 'function') {
685
+ this.onUpstreamNotification(upstreamId, clean);
686
+ }
687
+ } catch (_e) { /* never let a bridged notification break the read loop */ }
688
+ };
689
+ if (notification.method === 'notifications/tools/list_changed') {
690
+ // A relayed "tools changed" must not point the client at a STALE surface - refresh the
691
+ // cache FIRST, then relay, so the re-fetch sees the new list (F2/B-M4). onToolsChanged
692
+ // fires too so ToolFunnel's own funnel-mode signal stays coherent.
693
+ this._listAndCache(upstreamId)
694
+ .then(() => { try { if (typeof this.onToolsChanged === 'function') this.onToolsChanged(); } catch (_e) { /* ignore */ } })
695
+ .catch(() => { /* refresh failed - still relay; the old cache is the best we have */ })
696
+ .then(emit);
697
+ return;
698
+ }
699
+ emit();
700
+ } catch (_e) { /* never let a bridged notification break the read loop */ }
701
+ }
702
+
703
+ /**
704
+ * The downstream name a discovered upstream tool is surfaced under: its ENABLED expose `as` if one
705
+ * exists for (upstream, tool), else the namespaced default `<upstream>_<tool>` (matching
706
+ * expose-store.exposedName). Keeps the lean list and the lean run path in agreement, and aligns an
707
+ * exposed tool's lean name with its curated-direct top-level name. Never throws.
708
+ * @param {string} upstreamId
709
+ * @param {string} toolName
710
+ * @returns {string}
711
+ */
712
+ _surfacedName(upstreamId, toolName) {
713
+ try {
714
+ const exposed = this._store.listExposed({ enabledOnly: true });
715
+ for (const e of exposed) {
716
+ if (e && e.upstream === upstreamId && e.tool === toolName) return this._store.exposedName(e);
717
+ }
718
+ } catch (_e) {
719
+ /* fall through to the default */
720
+ }
721
+ return `${upstreamId}_${toolName}`;
722
+ }
723
+
724
+ /**
725
+ * Connect an upstream ON DEMAND and return the ready McpClient. Idempotent + race-safe:
726
+ * - fast path: a cached client that is still `connected` is returned as-is; a cached-but-DEAD
727
+ * client (its child exited - McpClient flips `connected` but stays in the cache) is logged as a
728
+ * disconnect, discarded, and reconnected - a reconnect re-lists the upstream's tools.
729
+ * - concurrent callers JOIN the same in-flight connect promise (keyed in _connecting), which
730
+ * resolves only AFTER _listAndCache - so no caller ever sees the half-built client that
731
+ * _connectOne caches BEFORE the handshake completes (the double-spawn / mid-handshake race).
732
+ * Throws on an unknown/disabled upstream or a connect/list failure (the caller surfaces it; for the
733
+ * lean run path that means gatedRun returns { ok:false, error } cleanly).
734
+ * @param {string} upstreamId
735
+ * @returns {Promise<object>} the connected McpClient
736
+ */
737
+ async ensureConnected(upstreamId, opts) {
738
+ if (!isNonEmptyString(upstreamId)) throw new Error('Aggregator.ensureConnected: upstreamId (non-empty string) is required');
739
+ // allowConnect:false (the RUN path) must NEVER block on a connect - not a from-scratch connect
740
+ // (connect()+tools/list, ~20s, would freeze the serialized stdio chain and starve pings) AND not
741
+ // by JOINING an in-flight background reconnect (same latency). It returns a live client or fails
742
+ // clean; the background reconnect owns recovery and the run retries next turn. allowConnect
743
+ // defaults true (the background path connects / joins).
744
+ const allowConnect = !(opts && opts.allowConnect === false);
745
+ // allowDisabled: ONLY the discover path sets it - inspecting a disabled upstream's tools
746
+ // ("what does this have, before I enable it?") is a deliberate operator action that worked
747
+ // before discover was routed through here for the race fix. Every
748
+ // other caller keeps the refusal; a disabled upstream's tools stay OFF the lean surface
749
+ // regardless (leanToolDefinitions checks enabled itself).
750
+ const allowDisabled = !!(opts && opts.allowDisabled === true);
751
+ // A torn-down aggregator (swapped out by reloadExpose, then closeAll'd) must NEVER (re)connect:
752
+ // a captured execute thunk holding this instance would otherwise spawn an ORPHAN child on it.
753
+ if (this._closed) throw new Error('Aggregator.ensureConnected: aggregator is closed (config reloaded) - retry on the current one');
754
+
755
+ // A connect already in flight: JOIN it - BEFORE inspecting the cache. _connectOne caches the
756
+ // client pre-handshake, so a concurrent caller inspecting first sees `connected:false`, reads
757
+ // it as stale, closes it (killing the in-flight child mid-handshake) and then joins the
758
+ // connect it just doomed - both callers fail. The RUN path
759
+ // (allowConnect:false) still never joins - joining would block the stdio chain.
760
+ if (this._connecting.has(upstreamId)) {
761
+ if (!(opts && opts.allowConnect === false)) return this._connecting.get(upstreamId);
762
+ throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" is not connected (reconnecting in background)`);
763
+ }
764
+
765
+ // Fast path: a live cached client serves BOTH modes immediately.
766
+ const existing = this._clients.get(upstreamId);
767
+ if (existing) {
768
+ const alive = typeof existing.connected === 'boolean' ? existing.connected : true;
769
+ if (alive) return existing;
770
+ // Dead cached client. The RUN path fails clean (never (re)connects); the background path drops
771
+ // it and reconnects below.
772
+ if (!allowConnect) {
773
+ throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" disconnected (reconnecting in background)`);
774
+ }
775
+ logger.log({ type: 'mcp', event: 'disconnect', upstream: upstreamId, reason: 'stale' });
776
+ this._discard(upstreamId);
777
+ } else if (!allowConnect) {
778
+ // Not connected. The RUN path neither connects NOR joins an in-flight connect - joining would
779
+ // block the stdio chain for the connect+list latency (the head-of-line freeze this mode avoids).
780
+ throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" is not connected (reconnecting in background)`);
781
+ }
782
+
783
+ // Background path only (allowConnect): connect from scratch. In-flight connects were joined
784
+ // at the top of the method (before cache inspection - the mid-connect discard race); nothing
785
+ // between there and here awaits, so no new entry can have appeared.
786
+ const upstream = this._store.getUpstream(upstreamId);
787
+ if (!upstream) throw new Error(`Aggregator.ensureConnected: unknown upstream "${upstreamId}"`);
788
+ if (upstream.enabled !== true && !allowDisabled) throw new Error(`Aggregator.ensureConnected: upstream "${upstreamId}" is disabled`);
789
+
790
+ const promise = (async () => {
791
+ await this._connectOne(upstream); // caches client + tools, logs the connect
792
+ return this._clients.get(upstreamId);
793
+ })();
794
+ this._connecting.set(upstreamId, promise);
795
+ try {
796
+ return await promise;
797
+ } catch (err) {
798
+ this._discard(upstreamId); // reap the half-spawned child; leave no zombie/cache entry
799
+ throw err;
800
+ } finally {
801
+ this._connecting.delete(upstreamId);
802
+ }
803
+ }
804
+
805
+ /**
806
+ * Force a fresh connect of `upstreamId` presenting the CURRENT provider-supplied identity -
807
+ * the wrap identity-mirror's inline path. Settles any in-flight connect FIRST: discarding a
808
+ * half-built client and then joining its doomed promise leaves the upstream wedged with no
809
+ * background reconnect and no self-heal. Rejects
810
+ * like ensureConnected on failure.
811
+ */
812
+ async reconnect(upstreamId) {
813
+ if (!isNonEmptyString(upstreamId)) throw new Error('Aggregator.reconnect: upstreamId (non-empty string) is required');
814
+ while (this._connecting.has(upstreamId)) {
815
+ try { await this._connecting.get(upstreamId); } catch (_e) { /* settled is all we need */ }
816
+ }
817
+ this._discard(upstreamId);
818
+ try {
819
+ return await this.ensureConnected(upstreamId);
820
+ } catch (err) {
821
+ // This path DESTROYED a (possibly healthy) connection, and the deliberate close means
822
+ // onClose never fires - without this, one transient connect failure leaves no client, no
823
+ // in-flight connect AND no retry timer: the upstream is wedged until an external kick
824
+ // while ensureConnected's "reconnecting in background" message lies. The destroyer owns the retry. A stale PENDING timer (a prior death's slow
825
+ // 30s keepalive) must be cleared first - _scheduleReconnect's one-timer guard would
826
+ // otherwise no-op and leave the upstream on the long window instead of the immediate
827
+ // retry this path promises.
828
+ const stale = this._reconnectTimers.get(upstreamId);
829
+ if (stale) { clearTimeout(stale); this._reconnectTimers.delete(upstreamId); }
830
+ this._scheduleReconnect(upstreamId, 0);
831
+ throw err;
832
+ }
833
+ }
834
+
835
+ /**
836
+ * UNEXPECTED upstream death (fired by McpClient.onClose). Log it, drop the dead client so it
837
+ * leaves the lean list, tell the client the tool set shrank, then schedule a BACKGROUND reconnect.
838
+ * Keeping recovery off the serialized stdio chain is what closes the head-of-line regression: a run
839
+ * during the down-window fails clean (ensureConnected allowConnect:false) instead of blocking.
840
+ * @param {string} upstreamId
841
+ */
842
+ _handleUpstreamDown(upstreamId) {
843
+ if (this._closed) return;
844
+ logger.log({ type: 'mcp', event: 'disconnect', upstream: upstreamId, reason: 'died' });
845
+ this._discard(upstreamId); // remove the dead client + its tools -> drops from the lean list
846
+ this._signalToolsChanged(upstreamId); // list_changed only if the upstream is on the top-level surface
847
+ this._scheduleReconnect(upstreamId, 0);
848
+ }
849
+
850
+ /**
851
+ * Does this upstream contribute to the TOP-LEVEL tools/list (i.e. has an ENABLED expose[] entry)?
852
+ * Only then does its death/recovery change tools/list and warrant a notifications/tools/list_changed.
853
+ * A lean-only upstream's tools live behind toolfunnel_list_tools (pulled per call), so notifying for
854
+ * one is spurious (the client re-fetches and sees no diff). Never throws.
855
+ * @param {string} upstreamId
856
+ * @returns {boolean}
857
+ */
858
+ _affectsTopLevel(upstreamId) {
859
+ try {
860
+ // Under a WRAP the wrapped upstream IS the entire top-level surface - its death/recovery
861
+ // changes tools/list even with an empty expose[] (a typical wrap has no expose
862
+ // entries, so death/recovery was silent and clients held a stale surface forever).
863
+ // wrapChatterUpstream mirrors the live wrap state (armed at boot, per message, on reload).
864
+ if (this.wrapChatterUpstream && this.wrapChatterUpstream === upstreamId) return true;
865
+ // Hot-promoted upstream tools sit on the funnel's top-level surface without an expose[]
866
+ // entry; the host injects this predicate (armWrapChatter) because promotion lives in the
867
+ // tool-state overlay the aggregator has no business reading directly.
868
+ if (typeof this.topLevelUpstreamExtra === 'function' && this.topLevelUpstreamExtra(upstreamId)) return true;
869
+ return this._store.listExposed({ enabledOnly: true }).some((e) => e && e.upstream === upstreamId);
870
+ } catch (_e) {
871
+ return false;
872
+ }
873
+ }
874
+
875
+ /** Fire onToolsChanged ONLY when the upstream is actually on the top-level surface (else the
876
+ * notification is spurious - its lean tools refresh on the next toolfunnel_list_tools). Never throws. */
877
+ _signalToolsChanged(upstreamId) {
878
+ if (!this._affectsTopLevel(upstreamId)) return;
879
+ try { this.onToolsChanged(); } catch (_e) { /* never throw out of an event handler */ }
880
+ }
881
+
882
+ /**
883
+ * Schedule ONE background reconnect attempt with exponential backoff: 1s,2s,4s,8s,16s, then capped
884
+ * at 30s. After the fast phase it does NOT give up - it falls back to a slow 30s keepalive so a long
885
+ * transient outage still self-heals (a detached/disabled upstream stops it via getUpstream; closeAll
886
+ * stops it via _closed). On success the tools are re-listed and a top-level change is signalled. One
887
+ * timer per upstream (no pile-up); the timer is unref'd so it never keeps the process alive. NEVER throws.
888
+ * @param {string} upstreamId
889
+ * @param {number} attempt
890
+ */
891
+ _scheduleReconnect(upstreamId, attempt) {
892
+ if (this._closed) return;
893
+ if (this._reconnectTimers.has(upstreamId)) return; // a reconnect is already pending for this id
894
+ const upstream = this._store.getUpstream(upstreamId);
895
+ if (!upstream || upstream.enabled !== true) return; // detached/disabled - stop trying
896
+ const MAX_FAST_ATTEMPTS = 6; // exponential phase; beyond it, a slow keepalive at the 30s cap
897
+ const delay = Math.min(1000 * Math.pow(2, attempt), 30000);
898
+ const timer = setTimeout(async () => {
899
+ this._reconnectTimers.delete(upstreamId);
900
+ if (this._closed) return;
901
+ const u = this._store.getUpstream(upstreamId);
902
+ if (!u || u.enabled !== true) return;
903
+ try {
904
+ await this.ensureConnected(upstreamId); // allowConnect default - connects + re-lists, off-chain
905
+ logger.log({ type: 'mcp', event: 'reconnect', upstream: upstreamId, attempt });
906
+ this._signalToolsChanged(upstreamId);
907
+ } catch (err) {
908
+ logger.log({ type: 'mcp', event: 'reconnect_failed', upstream: upstreamId, attempt, error: errMsg(err) });
909
+ // Log the fast->slow transition exactly ONCE - when the counter FIRST reaches the cap. The
910
+ // old guard sat on the re-entry side, where the capped counter re-satisfied it every 30s
911
+ // forever against a permanently-dead upstream (log spam, not information).
912
+ if (attempt + 1 === MAX_FAST_ATTEMPTS) {
913
+ logger.log({ type: 'mcp', event: 'reconnect_slow', upstream: upstreamId, attempts: MAX_FAST_ATTEMPTS });
914
+ }
915
+ // Keep escalating to the cap, then keep retrying slowly (cap the counter so the delay stays
916
+ // at 30s) - never permanently give up while the upstream stays enabled.
917
+ this._scheduleReconnect(upstreamId, Math.min(attempt + 1, MAX_FAST_ATTEMPTS));
918
+ }
919
+ }, delay);
920
+ if (timer && typeof timer.unref === 'function') timer.unref();
921
+ this._reconnectTimers.set(upstreamId, timer);
922
+ }
923
+
924
+ /**
925
+ * The LEAN tool definitions: every discovered tool of every CONNECTED + enabled upstream, surfaced
926
+ * for toolfunnel_list_tools. Each: { name, description, inputSchema, upstream, tool }. The FULL
927
+ * discovered set (not just expose[]) - attaching an MCP makes its tools appear leanly with no
928
+ * curation. Only connected upstreams contribute (we need their real schemas); a not-yet-connected
929
+ * upstream's tools simply appear once it connects (the next list call reflects it - no
930
+ * notification needed, the lean surface is delivered inside a per-call meta-tool). Never throws.
931
+ * @returns {Array<{name:string, description:string, inputSchema:object, upstream:string, tool:string}>}
932
+ */
933
+ leanToolDefinitions() {
934
+ const defs = [];
935
+ const seen = new Set(); // surfaced-name collision guard - the list must agree with resolve (first wins)
936
+ try {
937
+ for (const [upstreamId, tools] of this._tools) {
938
+ if (!this._clients.has(upstreamId)) continue; // connected only
939
+ const upstream = this._store.getUpstream(upstreamId);
940
+ if (upstream && upstream.enabled === false) continue; // skip an explicitly-disabled upstream
941
+ if (!Array.isArray(tools)) continue;
942
+ for (const t of tools) {
943
+ if (!t || !isNonEmptyString(t.name)) continue;
944
+ const name = this._surfacedName(upstreamId, t.name);
945
+ if (seen.has(name)) {
946
+ // Two tools collapse to one surfaced name (underscore ambiguity, or a duplicate `as`).
947
+ // resolveLeanExecution returns the FIRST match, so advertise only the first - the list
948
+ // must never show a name that resolves to a different tool. Log the shadowing.
949
+ logger.log({ type: 'mcp', event: 'name_collision', upstream: upstreamId, tool: t.name, surfaced: name });
950
+ continue;
951
+ }
952
+ seen.add(name);
953
+ const schema = t.inputSchema && typeof t.inputSchema === 'object' ? t.inputSchema : { type: 'object' };
954
+ defs.push({
955
+ name,
956
+ description: isNonEmptyString(t.description) ? t.description : '',
957
+ inputSchema: cloneJson(schema),
958
+ upstream: upstreamId,
959
+ tool: t.name,
960
+ });
961
+ }
962
+ }
963
+ } catch (_e) {
964
+ /* never throw out of a definition build - return what we have */
965
+ }
966
+ return defs;
967
+ }
968
+
969
+ /**
970
+ * Resolve a lean downstream name + args into a forwarding executor for toolfunnel_run_tool. Matches
971
+ * by ITERATION over discovered tools (computing each tool's surfaced name) - never by parsing the
972
+ * name (underscore-ambiguous). The execute thunk lazy-(re)connects via ensureConnected and UNWRAPS
973
+ * the upstream MCP envelope to a clean payload, so run_tool returns the upstream's content (e.g.
974
+ * "pong"), not a stringified envelope. The connect is INSIDE the thunk -> a PreToolUse deny spawns
975
+ * nothing. The gate matches `toolName` (the surfaced name). Returns null if no connected upstream
976
+ * advertises a tool with this surfaced name (-> protocol's clean "not runnable" error).
977
+ * @param {string} name surfaced downstream name
978
+ * @param {any} args
979
+ * @returns {{ execute: () => Promise<any>, toolName: string, upstream: string } | null}
980
+ */
981
+ resolveLeanExecution(name, args) {
982
+ if (!isNonEmptyString(name)) return null;
983
+ for (const [upstreamId, tools] of this._tools) {
984
+ if (!this._clients.has(upstreamId)) continue;
985
+ if (!Array.isArray(tools)) continue;
986
+ for (const t of tools) {
987
+ if (!t || !isNonEmptyString(t.name)) continue;
988
+ if (this._surfacedName(upstreamId, t.name) !== name) continue;
989
+ const realTool = t.name;
990
+ const self = this;
991
+ const execute = async () => {
992
+ // allowConnect:false - the run path NEVER synchronously (re)connects (that would freeze the
993
+ // stdio loop, starving pings). It uses a live client or joins an in-flight background
994
+ // reconnect, else fails clean; the onClose-driven background reconnect owns recovery.
995
+ const client = await self.ensureConnected(upstreamId, { allowConnect: false });
996
+ self._warnIfPinned(upstreamId, realTool);
997
+ const envelope = await client.callTool(realTool, args);
998
+ // Preserve the upstream's failure signal. callTool RESOLVES even on isError:true, so a
999
+ // failed upstream call must become a THROW -> gatedRun returns { ok:false } -> run_tool
1000
+ // surfaces isError:true. Otherwise a failed call would be reported as success - and the
1001
+ // lean path must agree with curated-direct's isError passthrough.
1002
+ const payload = unwrapEnvelope(envelope);
1003
+ if (envelope && typeof envelope === 'object' && envelope.isError === true) {
1004
+ const text = typeof payload === 'string' ? payload : safeStringify(payload);
1005
+ const err = new Error(text && text.length ? text : 'upstream tool reported an error');
1006
+ err.upstreamToolError = true;
1007
+ throw err;
1008
+ }
1009
+ return payload;
1010
+ };
1011
+ return { execute, toolName: name, upstream: upstreamId };
1012
+ }
1013
+ }
1014
+ return null;
1015
+ }
1016
+
1017
+ /**
1018
+ * resolveRawExecution - the passthrough (WRAP) twin of resolveLeanExecution. Its execute returns
1019
+ * the upstream's tools/call result VERBATIM - multi-block content, isError, structuredContent
1020
+ * and any future fields untouched. A wrapped client must receive exactly what a direct client
1021
+ * would; the lean unwrap (single text block, throw-on-isError) destroys that. No unwrap, no
1022
+ * throw-on-isError: the envelope IS the product. Uses client.request() so a modern upstream
1023
+ * gets its per-request _meta trio.
1024
+ * @param {string} name surfaced downstream name
1025
+ * @param {any} args
1026
+ * @returns {{ execute: () => Promise<any>, toolName: string, upstream: string } | null}
1027
+ */
1028
+ resolveRawExecution(name, args, meta, out) {
1029
+ if (!isNonEmptyString(name)) return null;
1030
+ for (const [upstreamId, tools] of this._tools) {
1031
+ if (!this._clients.has(upstreamId)) continue;
1032
+ if (!Array.isArray(tools)) continue;
1033
+ for (const t of tools) {
1034
+ if (!t || !isNonEmptyString(t.name)) continue;
1035
+ if (this._surfacedName(upstreamId, t.name) !== name) continue;
1036
+ const realTool = t.name;
1037
+ const self = this;
1038
+ const execute = async () => {
1039
+ // allowConnect:false - same freeze-avoidance rule as the lean path.
1040
+ const client = await self.ensureConnected(upstreamId, { allowConnect: false });
1041
+ self._warnIfPinned(upstreamId, realTool);
1042
+ const params = { name: realTool, arguments: args == null ? {} : args };
1043
+ // The caller's request-scoped _meta (progressToken, trace keys - already stripped of
1044
+ // protocol keys) rides the forward: a direct server would receive it, so the wrapped
1045
+ // one must too - without it the upstream never emits progress for the call.
1046
+ if (meta && typeof meta === 'object' && Object.keys(meta).length) params._meta = meta;
1047
+ // `out.rpcId` is set synchronously at issue time - the caller's cancel-translation
1048
+ // hook (the same contract as forwardRaw's).
1049
+ return await client.request('tools/call', params, out);
1050
+ };
1051
+ return { execute, toolName: name, upstream: upstreamId };
1052
+ }
1053
+ }
1054
+ return null;
1055
+ }
1056
+
1057
+ /**
1058
+ * Close every cached client and clear the caches. Idempotent - safe to call twice and
1059
+ * safe when nothing was ever connected. NEVER throws (close() on McpClient never throws).
1060
+ * @returns {Promise<void>}
1061
+ */
1062
+ async closeAll() {
1063
+ this._closed = true; // latch BEFORE teardown so any in-flight execute thunk refuses to re-spawn
1064
+ for (const [, timer] of this._reconnectTimers) {
1065
+ try { clearTimeout(timer); } catch (_e) { /* ignore */ }
1066
+ }
1067
+ this._reconnectTimers.clear();
1068
+ for (const [id, client] of this._clients) {
1069
+ try {
1070
+ if (client && typeof client.close === 'function') client.close();
1071
+ // Activity log (self-gating): the disconnect half. A reload closes the old aggregator here,
1072
+ // so a reconnect reads as a disconnect line followed by a connect line for the same id.
1073
+ logger.log({ type: 'mcp', event: 'disconnect', upstream: id });
1074
+ } catch (_e) {
1075
+ /* McpClient.close never throws, but never let teardown sink the loop */
1076
+ }
1077
+ }
1078
+ this._clients.clear();
1079
+ this._tools.clear();
1080
+ }
1081
+
1082
+ // ── internals ──────────────────────────────────────────────────────────────
1083
+
1084
+ /**
1085
+ * Connect a single upstream entry and cache the client + its discovered tools.
1086
+ * Throws on factory (isolation), connect, or listTools failure - callers decide
1087
+ * whether to collect (connectAll) or surface (discover) the error. On throw, the
1088
+ * caller is responsible for _discard()-ing the id.
1089
+ * @param {object} upstream a normalised ExposeStore upstream
1090
+ */
1091
+ async _connectOne(upstream) {
1092
+ // The factory may throw (isolation guard) - that propagates out as a connect failure. Pass an
1093
+ // onClose so an UNEXPECTED upstream death triggers a BACKGROUND reconnect (not a lazy one in the
1094
+ // run path, which would freeze the stdio chain).
1095
+ const client = this._clientFactory(upstream, () => this._handleUpstreamDown(upstream.id));
1096
+ if (!client || typeof client.connect !== 'function') {
1097
+ throw new Error(`clientFactory returned an invalid client for "${upstream.id}"`);
1098
+ }
1099
+ // Bridge this upstream's server-initiated change-notifications to the transport (which fans them
1100
+ // out to modern subscriptions/listen streams). Filtered to the known change methods so arbitrary
1101
+ // upstream chatter never reaches a client. NEVER throws.
1102
+ client.onNotification = (n) => this._forwardUpstreamNotification(upstream.id, n);
1103
+ // Bridge B: surface server-initiated requests with the upstream id + the live client (the
1104
+ // handler answers on it). Guarded so a handler bug can never break the client's read loop.
1105
+ client.onServerRequest = (m) => {
1106
+ try {
1107
+ if (this._closed) { client.respondToServerError(m.id, -32603, 'shutting down'); return; }
1108
+ this.onUpstreamServerRequest(upstream.id, m, client);
1109
+ } catch (_e) {
1110
+ try { client.respondToServerError(m.id, -32603, 'request failed'); } catch (_e2) { /* ignore */ }
1111
+ }
1112
+ };
1113
+ // Cache the client BEFORE connect so a connect-failure path can still _discard() and
1114
+ // close any half-spawned child.
1115
+ this._clients.set(upstream.id, client);
1116
+ await client.connect();
1117
+ await this._listAndCache(upstream.id);
1118
+ // Re-arm any agreed resource subscriptions on the fresh process - every connect
1119
+ // path funnels through here, so reconnects and reloads replay uniformly.
1120
+ this._replaySubscriptions(upstream.id);
1121
+ // Activity log (self-gating; no-op unless logging is enabled): the upstream half of connect
1122
+ // logging. EVERY connect flows through here - startup connectAll, a live reload, a lazy
1123
+ // discover, and (later) a health-driven reconnect - so all of them are logged uniformly.
1124
+ logger.log({
1125
+ type: 'mcp',
1126
+ event: 'connect',
1127
+ upstream: upstream.id,
1128
+ command: upstream.command,
1129
+ tools: (this._tools.get(upstream.id) || []).length,
1130
+ });
1131
+ // Legacy shim STARTUP warning (the pin's contract: warn at startup AND per call, naming the
1132
+ // version). stderr, so the operator sees it without the client's content ever growing.
1133
+ if (upstream.legacyPin === true) {
1134
+ try {
1135
+ process.stderr.write(
1136
+ `[toolfunnel] legacy shim: upstream "${upstream.id}" is PINNED to MCP ${LEGACY_UPSTREAM_VERSION} ` +
1137
+ '(legacyPin) - this gateway keeps it working for modern clients; it cannot speak 2026-07-28 itself.\n'
1138
+ );
1139
+ } catch (_e) { /* never let a warning sink a connect */ }
1140
+ logger.log({ type: 'mcp', event: 'legacy_shim_connect', upstream: upstream.id, protocolVersion: LEGACY_UPSTREAM_VERSION });
1141
+ }
1142
+ }
1143
+
1144
+ /** tools/list one connected upstream and cache the result; returns a clone. */
1145
+ async _listAndCache(upstreamId) {
1146
+ const client = this._clients.get(upstreamId);
1147
+ if (!client) throw new Error(`no connected client for "${upstreamId}"`);
1148
+ const tools = await client.listTools();
1149
+ const safe = Array.isArray(tools) ? tools.filter((t) => t && isNonEmptyString(t.name)) : [];
1150
+ this._tools.set(upstreamId, safe);
1151
+ return cloneTools(safe);
1152
+ }
1153
+
1154
+ /** Tear down + forget a cached client (used on a failed connect). Never throws. */
1155
+ _discard(upstreamId) {
1156
+ const client = this._clients.get(upstreamId);
1157
+ if (client && typeof client.close === 'function') {
1158
+ try { client.close(); } catch (_e) { /* never throw */ }
1159
+ }
1160
+ this._clients.delete(upstreamId);
1161
+ this._tools.delete(upstreamId);
1162
+ }
1163
+
1164
+ /**
1165
+ * Shared lookup behind isExposed / resolveExposedExecution: find the ENABLED expose
1166
+ * entry whose downstream name === `name`, whose upstream is connected, and whose real
1167
+ * tool the upstream advertises. Returns the resolution context or null.
1168
+ * @param {string} name
1169
+ * @returns {{ client:object, realTool:string, upstream:string, exposedName:string } | null}
1170
+ */
1171
+ _findExposedExecution(name) {
1172
+ if (!isNonEmptyString(name)) return null;
1173
+ let exposed;
1174
+ try {
1175
+ exposed = this._store.listExposed({ enabledOnly: true });
1176
+ } catch (_err) {
1177
+ return null;
1178
+ }
1179
+ for (const e of exposed) {
1180
+ if (!e) continue;
1181
+ if (this._store.exposedName(e) !== name) continue;
1182
+ const client = this._clients.get(e.upstream);
1183
+ if (!client) continue; // upstream not connected
1184
+ const upstreamTools = this._tools.get(e.upstream) || [];
1185
+ if (!upstreamTools.some((t) => t && t.name === e.tool)) continue; // tool not advertised
1186
+ return { client, realTool: e.tool, upstream: e.upstream, exposedName: name };
1187
+ }
1188
+ return null;
1189
+ }
1190
+ }
1191
+
1192
+ // ── small helpers (no external deps) ───────────────────────────────────────────
1193
+
1194
+ /** Extract a clean message from any thrown value. */
1195
+ function errMsg(err) {
1196
+ return (err && err.message) || String(err);
1197
+ }
1198
+
1199
+ /** JSON.stringify that never throws (circular/oddball values fall back to String). */
1200
+ function safeStringify(value) {
1201
+ try { return JSON.stringify(value); } catch (_e) { return String(value); }
1202
+ }
1203
+
1204
+ /**
1205
+ * Turn an upstream MCP tools/call envelope { content:[...], isError? } into a clean payload for the
1206
+ * LEAN run path. A single text block -> its string (so toolfunnel_run_tool returns "pong", matching
1207
+ * what the curated-direct content passthrough surfaces); otherwise the content array; otherwise the
1208
+ * value as-is when it isn't an envelope. This is what avoids double-wrapping the envelope as JSON
1209
+ * inside wrapProtocolResult (the curated-direct path passes the envelope through transparently
1210
+ * instead; the lean path goes through protocol.runTool -> wrapProtocolResult, so it unwraps here).
1211
+ * NOTE (slice 2): an upstream isError:true is surfaced as its text content with ok:true (homogeneous
1212
+ * with how local tools surface error text) - mapping isError -> ok:false is a later concern.
1213
+ * @param {*} envelope
1214
+ * @returns {*}
1215
+ */
1216
+ function unwrapEnvelope(envelope) {
1217
+ if (!envelope || typeof envelope !== 'object') return envelope;
1218
+ const content = envelope.content;
1219
+ if (Array.isArray(content)) {
1220
+ if (content.length === 1 && content[0] && content[0].type === 'text' && typeof content[0].text === 'string') {
1221
+ return content[0].text;
1222
+ }
1223
+ return content;
1224
+ }
1225
+ return envelope;
1226
+ }
1227
+
1228
+ /** Plain-JSON deep clone (schemas are JSON; structuredClone may be absent on old node). */
1229
+ function cloneJson(value) {
1230
+ return JSON.parse(JSON.stringify(value));
1231
+ }
1232
+
1233
+ /** Clone an array of tool defs so callers can't mutate the aggregator's cache. */
1234
+ function cloneTools(tools) {
1235
+ return Array.isArray(tools) ? tools.map((t) => cloneJson(t)) : [];
1236
+ }
1237
+
1238
+ module.exports = {
1239
+ Aggregator,
1240
+ // exported for unit tests / reuse
1241
+ defaultClientFactory,
1242
+ looksLikePath,
1243
+ isInside,
1244
+ unwrapEnvelope,
1245
+ DEFAULT_ROOT,
1246
+ };