mcp-patchbay 0.0.0 → 0.1.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.
package/src/server.js ADDED
@@ -0,0 +1,864 @@
1
+ // The patchbay: an MCP server whose tools are its own five (six with confirmVia "host") plus those
2
+ // of the children that are switched on. See SPEC.md §3-§5 and §8.
3
+ import { randomUUID } from 'node:crypto';
4
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
5
+ import {
6
+ CallToolRequestSchema,
7
+ ElicitResultSchema,
8
+ ErrorCode,
9
+ InitializeRequestSchema,
10
+ ListToolsRequestSchema,
11
+ McpError,
12
+ RootsListChangedNotificationSchema,
13
+ } from '@modelcontextprotocol/sdk/types.js';
14
+ import { Child, NO_CAP_MS } from './children.js';
15
+ import { autostartFor } from './config.js';
16
+ import { buildInstructions, truncate } from './instructions.js';
17
+ import { mapTools, splitExposed } from './naming.js';
18
+ import { killGroupsLater, processStartTime } from './process.js';
19
+ import { redact } from './redact.js';
20
+ import { VERSION } from './version.js';
21
+
22
+ export const LIST_WAIT_MS = 2000;
23
+ export const AUTOSTART_WAIT_MS = 15000;
24
+ const STDIO_START_TIMEOUT_MS = 120000;
25
+ const REMOTE_START_GRACE_MS = 60000;
26
+ const CLIENT_READY_WAIT_MS = 30000;
27
+ const ENABLE_INSTRUCTIONS_MAX = 2000;
28
+ const SAMPLE_TOOLS = 10;
29
+ const ALWAYS_LOAD = { 'anthropic/alwaysLoad': true };
30
+
31
+ /**
32
+ * @typedef {'off'|'starting'|'waiting-for-sign-in'|'on'|'failed'} State
33
+ * @typedef {{
34
+ * name: string, entry: import('./config.js').ServerEntry, state: State,
35
+ * child: Child | null, lastChild?: Child, published: import('./naming.js').Published[],
36
+ * skipped: import('./naming.js').Skipped[], lastError?: string, exitError?: () => string,
37
+ * inFlight: number, startPromise: Promise<{ok: boolean, error?: string}> | null,
38
+ * confirmPromise: Promise<{ok: boolean, message?: string}> | null,
39
+ * authUrls: Set<string>, urlElicitationId?: string, startAbort?: AbortController,
40
+ * relisting: boolean, relistAgain: boolean, lastNotify?: Promise<boolean>,
41
+ * restart: {promise: Promise<any>} | null
42
+ * }} Slot
43
+ */
44
+
45
+ /** @param {unknown} data */
46
+ const ok = (data) => ({ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] });
47
+ /** @param {string} message @param {Record<string, unknown>} [extra] */
48
+ const fail = (message, extra = {}) => ({ isError: true, content: [{ type: 'text', text: JSON.stringify({ error: message, ...extra }, null, 2) }] });
49
+
50
+ export class Patchbay {
51
+ /**
52
+ * @param {import('./config.js').Config} config
53
+ * @param {object} o
54
+ * @param {import('./log.js').Logger} o.log
55
+ * @param {import('./process.js').PidFiles | null} [o.pidFiles]
56
+ * @param {NodeJS.ProcessEnv} [o.env]
57
+ * @param {string} [o.projectDir]
58
+ */
59
+ constructor(config, o) {
60
+ this.config = config;
61
+ this.log = o.log;
62
+ this.pidFiles = o.pidFiles ?? null;
63
+ this.env = o.env ?? process.env;
64
+ this.projectDir = o.projectDir ?? this.env.CLAUDE_PROJECT_DIR ?? process.cwd();
65
+ /** @type {Map<string, Slot>} */
66
+ this.slots = new Map();
67
+ /** @type {Map<string, Slot>} */
68
+ this.bySegment = new Map();
69
+ for (const name of config.order) {
70
+ const entry = config.servers[name];
71
+ /** @type {Slot} */
72
+ const slot = {
73
+ name, entry, state: 'off', child: null, published: [], skipped: [], inFlight: 0,
74
+ startPromise: null, confirmPromise: null, authUrls: new Set(), relisting: false, relistAgain: false,
75
+ restart: null,
76
+ };
77
+ this.slots.set(name, slot);
78
+ this.bySegment.set(entry.segment, slot);
79
+ }
80
+ /** @type {Map<string, {slot: Slot, original: string, child: Child}>} */
81
+ this.routes = new Map();
82
+ /** @type {Set<() => void>} */
83
+ this.listWaiters = new Set();
84
+ /** @type {string[]} */
85
+ this.autostarted = [];
86
+ this.initialized = false;
87
+ this.closed = false;
88
+ /** @type {() => void} */
89
+ let markReady = () => {};
90
+ this.clientReady = new Promise((r) => { markReady = r; });
91
+ this.markReady = markReady;
92
+
93
+ this.server = new Server({ name: 'mcp-patchbay', version: VERSION }, { capabilities: { tools: { listChanged: true } } });
94
+ this.server.onerror = (e) => this.log.debug(`protocol: ${e.message}`);
95
+ this.server.oninitialized = () => {
96
+ this.initialized = true;
97
+ this.markReady();
98
+ };
99
+ this.#registerHandlers();
100
+ }
101
+
102
+ /** The client's capabilities as recorded at initialize. */
103
+ get clientCaps() {
104
+ return this.server.getClientCapabilities() ?? {};
105
+ }
106
+
107
+ canElicitForm() {
108
+ return Boolean(this.clientCaps.elicitation?.form);
109
+ }
110
+
111
+ /** confirmVia "host": the person approves a confirm server through the host's permission prompt for enable_confirm. */
112
+ get hostConfirm() {
113
+ return this.config.confirmVia === 'host';
114
+ }
115
+
116
+ async whenClientReady() {
117
+ if (this.initialized) return true;
118
+ let t;
119
+ const r = await Promise.race([
120
+ this.clientReady.then(() => true),
121
+ new Promise((res) => { t = setTimeout(() => res(false), CLIENT_READY_WAIT_MS); }),
122
+ ]);
123
+ clearTimeout(t);
124
+ return r;
125
+ }
126
+
127
+ /** @param {import('@modelcontextprotocol/sdk/shared/transport.js').Transport} transport */
128
+ async connect(transport) {
129
+ await this.server.connect(transport);
130
+ }
131
+
132
+ #registerHandlers() {
133
+ const s = this.server;
134
+ s.setRequestHandler(InitializeRequestSchema, async (request) => {
135
+ // Let the SDK record the client's capabilities and negotiate the version, then autostart
136
+ // (children's capabilities depend on the client's) and attach our instructions.
137
+ const result = await /** @type {any} */ (s)._oninitialize(request);
138
+ await this.autostart(AUTOSTART_WAIT_MS);
139
+ result.instructions = this.instructionsText();
140
+ return result;
141
+ });
142
+ s.setRequestHandler(ListToolsRequestSchema, async () => {
143
+ const waiters = [...this.listWaiters];
144
+ this.listWaiters.clear();
145
+ // Resolve after this response has been written, so enable's answer follows it.
146
+ if (waiters.length) setImmediate(() => { for (const w of waiters) w(); });
147
+ return { tools: [...this.ownTools(), ...this.publishedTools()] };
148
+ });
149
+ s.setRequestHandler(CallToolRequestSchema, (request, extra) => this.#onCall(request, extra));
150
+ s.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
151
+ for (const slot of this.slots.values()) {
152
+ if (slot.state === 'on' && slot.child) await slot.child.rootsListChanged();
153
+ }
154
+ });
155
+ }
156
+
157
+ ownTools() {
158
+ const names = this.config.order;
159
+ /** @param {string} what */
160
+ const nameInput = (what) => ({
161
+ type: 'object',
162
+ properties: { name: { type: 'string', description: what, ...(names.length ? { enum: names } : {}) } },
163
+ required: ['name'],
164
+ additionalProperties: false,
165
+ });
166
+ const host = this.hostConfirm;
167
+ const tools = [
168
+ {
169
+ name: 'servers',
170
+ title: 'List hosted MCP servers',
171
+ description: 'Lists every MCP server the patchbay can host: name, description, policy (allow, confirm, deny), state (off, starting, on, failed, waiting-for-sign-in), tool count when on, and which ones can be enabled.',
172
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
173
+ annotations: { readOnlyHint: true, openWorldHint: false },
174
+ _meta: ALWAYS_LOAD,
175
+ },
176
+ {
177
+ name: 'enable',
178
+ title: 'Turn on a hosted MCP server',
179
+ description: host
180
+ ? 'Starts a hosted MCP server with policy allow and adds its tools, named <server>__<tool>. Servers with policy confirm are turned on with enable_confirm instead; deny servers cannot be enabled. Returns the tool count, sample tool names and the server\'s instructions.'
181
+ : 'Starts a hosted MCP server and adds its tools, named <server>__<tool>. Servers with policy confirm ask a person first; deny servers cannot be enabled. Returns the tool count, sample tool names and the server\'s instructions.',
182
+ inputSchema: nameInput('Server name, as listed by servers'),
183
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
184
+ _meta: ALWAYS_LOAD,
185
+ },
186
+ {
187
+ name: 'disable',
188
+ title: 'Turn off a hosted MCP server',
189
+ description: 'Stops a hosted MCP server and removes its tools. Refused while it still has calls in flight.',
190
+ inputSchema: nameInput('Server name'),
191
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
192
+ _meta: ALWAYS_LOAD,
193
+ },
194
+ {
195
+ name: 'restart',
196
+ title: 'Restart a hosted MCP server',
197
+ description: 'Stops and starts a hosted MCP server. No new confirmation if it is already on; otherwise behaves like enable.',
198
+ inputSchema: nameInput('Server name'),
199
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
200
+ _meta: ALWAYS_LOAD,
201
+ },
202
+ {
203
+ name: 'info',
204
+ title: 'Details of a hosted MCP server',
205
+ description: 'Shows a hosted server\'s description, policy, state, recent (redacted) stderr and, when on, its full instructions.',
206
+ inputSchema: nameInput('Server name'),
207
+ annotations: { readOnlyHint: true, openWorldHint: false },
208
+ _meta: ALWAYS_LOAD,
209
+ },
210
+ ];
211
+ if (host) {
212
+ // destructiveHint: a host that auto-approves non-destructive tools must still ask. The
213
+ // person's answer to that permission prompt is the approval (SECURITY-MODEL.md).
214
+ tools.splice(2, 0, {
215
+ name: 'enable_confirm',
216
+ title: 'Turn on a hosted MCP server that needs a person\'s approval',
217
+ description: 'Turns on a hosted MCP server whose policy is confirm, which needs the person\'s approval. The host asks the person before running this tool; their yes is the approval. Adds the server\'s tools, named <server>__<tool>, and returns the tool count, sample tool names and the server\'s instructions. Use enable for allow servers; deny servers cannot be enabled.',
218
+ inputSchema: nameInput('Server name, as listed by servers (policy confirm)'),
219
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
220
+ _meta: ALWAYS_LOAD,
221
+ });
222
+ }
223
+ return tools;
224
+ }
225
+
226
+ publishedTools() {
227
+ const out = [];
228
+ for (const name of this.config.order) {
229
+ const slot = /** @type {Slot} */ (this.slots.get(name));
230
+ if (slot.state === 'on') for (const p of slot.published) out.push(p.tool);
231
+ }
232
+ return out;
233
+ }
234
+
235
+ #rebuildRoutes() {
236
+ this.routes.clear();
237
+ for (const slot of this.slots.values()) {
238
+ if (slot.state !== 'on' || !slot.child) continue;
239
+ for (const p of slot.published) this.routes.set(p.exposed, { slot, original: p.original, child: slot.child });
240
+ }
241
+ }
242
+
243
+ /**
244
+ * @param {Slot} slot
245
+ * @param {Array<Record<string, any>>} tools
246
+ */
247
+ #publish(slot, tools) {
248
+ const { published, skipped } = mapTools(slot.entry.segment, tools);
249
+ slot.published = published;
250
+ slot.skipped = skipped;
251
+ this.#rebuildRoutes();
252
+ }
253
+
254
+ /** @param {Slot} slot */
255
+ #unpublish(slot) {
256
+ slot.published = [];
257
+ this.#rebuildRoutes();
258
+ }
259
+
260
+ /**
261
+ * Sends tools/list_changed (once the client is initialized) and resolves when the client next
262
+ * asks for tools/list, or after LIST_WAIT_MS.
263
+ * @returns {Promise<boolean>}
264
+ */
265
+ notifyToolsChanged() {
266
+ if (!this.initialized || this.closed) return Promise.resolve(false);
267
+ const seen = new Promise((resolve) => {
268
+ const done = () => { clearTimeout(t); resolve(true); };
269
+ const t = setTimeout(() => { this.listWaiters.delete(done); resolve(false); }, LIST_WAIT_MS);
270
+ this.listWaiters.add(done);
271
+ });
272
+ this.server.sendToolListChanged().catch((e) => this.log.debug(`list_changed not sent: ${e.message}`));
273
+ return /** @type {Promise<boolean>} */ (seen);
274
+ }
275
+
276
+ // ---- own tools -------------------------------------------------------------------------
277
+
278
+ /**
279
+ * @param {any} request
280
+ * @param {any} extra
281
+ */
282
+ async #onCall(request, extra) {
283
+ const name = request.params.name;
284
+ const args = request.params.arguments ?? {};
285
+ switch (name) {
286
+ case 'servers': return this.toolServers();
287
+ case 'enable': return this.toolEnable(args.name, extra);
288
+ case 'enable_confirm':
289
+ // Not listed, and not callable, unless confirmVia is "host".
290
+ if (this.hostConfirm) return this.toolEnableConfirm(args.name, extra);
291
+ return this.#forward(request, extra);
292
+ case 'disable': return this.toolDisable(args.name);
293
+ case 'restart': return this.toolRestart(args.name, extra);
294
+ case 'info': return this.toolInfo(args.name);
295
+ default: return this.#forward(request, extra);
296
+ }
297
+ }
298
+
299
+ /** @param {unknown} name */
300
+ #slotOrError(name) {
301
+ if (typeof name !== 'string' || !name) return { error: fail('name is required; call servers for the list') };
302
+ const slot = this.slots.get(name);
303
+ if (!slot) return { error: fail(`unknown server "${redact(name).slice(0, 80)}"; call servers for the list`) };
304
+ return { slot };
305
+ }
306
+
307
+ /** @param {Slot} slot */
308
+ #whyNot(slot) {
309
+ if (slot.entry.policy === 'deny') return 'policy is deny';
310
+ if (slot.state === 'on') return 'already on';
311
+ if (slot.state === 'starting' || slot.state === 'waiting-for-sign-in') return `already ${slot.state}`;
312
+ if (slot.entry.policy === 'confirm' && !this.hostConfirm && !this.canElicitForm()) {
313
+ return "needs a person's approval, but this client cannot ask (no elicitation support); a person must add it to autostart or set policy: allow";
314
+ }
315
+ return undefined;
316
+ }
317
+
318
+ toolServers() {
319
+ const servers = [];
320
+ const canEnable = [];
321
+ for (const slot of this.slots.values()) {
322
+ const whyNot = this.#whyNot(slot);
323
+ /** @type {Record<string, unknown>} */
324
+ const s = { name: slot.name, description: slot.entry.description, policy: slot.entry.policy, state: slot.state };
325
+ if (slot.state === 'on') {
326
+ s.toolCount = slot.published.length;
327
+ if (slot.skipped.length) s.skippedTools = slot.skipped;
328
+ }
329
+ if (slot.state === 'failed' && slot.lastError) s.lastError = slot.lastError;
330
+ s.canEnable = !whyNot;
331
+ if (whyNot) s.whyNot = whyNot;
332
+ else canEnable.push(slot.name);
333
+ if (!whyNot && this.hostConfirm && slot.entry.policy === 'confirm') s.enableWith = 'enable_confirm';
334
+ servers.push(s);
335
+ }
336
+ const usage = this.hostConfirm
337
+ ? 'enable {name} turns an allow server on; enable_confirm {name} turns a confirm server on after the host asks the person; disable {name} turns it off. Tools appear as <server>__<tool>.'
338
+ : 'enable {name} turns a server on; disable {name} turns it off. Tools appear as <server>__<tool>.';
339
+ return ok({ servers, canEnable, usage });
340
+ }
341
+
342
+ /** @param {Slot} slot @param {string} [message] */
343
+ #summary(slot, message) {
344
+ /** @type {Record<string, unknown>} */
345
+ const out = { name: slot.name, state: slot.state };
346
+ if (message) out.message = message;
347
+ out.toolCount = slot.published.length;
348
+ out.sampleTools = slot.published.slice(0, SAMPLE_TOOLS).map((p) => p.exposed);
349
+ if (slot.skipped.length) out.skippedTools = slot.skipped;
350
+ const instr = slot.child?.instructions;
351
+ if (instr) out.instructions = truncate(instr, ENABLE_INSTRUCTIONS_MAX);
352
+ return out;
353
+ }
354
+
355
+ /**
356
+ * @param {unknown} name
357
+ * @param {any} extra
358
+ * @param {{skipConfirm?: boolean, approved?: boolean}} [o] skipConfirm: a restart of a server
359
+ * that is on; approved: enable_confirm, whose host permission prompt was the confirmation
360
+ */
361
+ async toolEnable(name, extra, o = {}) {
362
+ const { slot, error } = this.#slotOrError(name);
363
+ if (!slot) return error;
364
+ if (slot.entry.policy === 'deny') return fail(`${slot.name} is denied by policy`);
365
+ if (slot.restart && !o.skipConfirm) {
366
+ // A restart of an approved server is stopping it; join that rather than asking a question
367
+ // whose answer the restart would ignore. If a disable cancels it, decide afresh.
368
+ await slot.restart.promise;
369
+ return this.toolEnable(name, extra, o);
370
+ }
371
+ if (slot.state === 'on') return ok(this.#summary(slot, 'already on'));
372
+ if (slot.startPromise && slot.state === 'off') {
373
+ // Disabled while starting, and that start has not unwound yet: let it, then start afresh
374
+ // (asking again: the disable ended the approval).
375
+ await slot.startPromise;
376
+ return this.toolEnable(name, extra, o);
377
+ }
378
+ if (!slot.startPromise && slot.entry.policy === 'confirm' && !o.skipConfirm && !o.approved) {
379
+ const c = await this.#confirm(slot, extra);
380
+ if (!c.ok) return fail(/** @type {string} */ (c.message));
381
+ }
382
+ if (slot.state === 'on') return ok(this.#summary(slot, 'already on'));
383
+ const r = await (slot.startPromise ?? this.startSlot(slot));
384
+ if (!r.ok) return fail(`${slot.name} failed to start: ${r.error}`, { name: slot.name, state: slot.state });
385
+ if (slot.lastNotify) await slot.lastNotify;
386
+ return ok(this.#summary(slot));
387
+ }
388
+
389
+ /**
390
+ * enable_confirm (confirmVia "host" only). The host asked the person before running it, so
391
+ * this is enable with the confirmation given. It refuses allow servers, so the host's prompt
392
+ * for this tool always means "a confirm server is about to start".
393
+ * @param {unknown} name
394
+ * @param {any} extra
395
+ */
396
+ async toolEnableConfirm(name, extra) {
397
+ const { slot, error } = this.#slotOrError(name);
398
+ if (!slot) return error;
399
+ if (slot.entry.policy === 'deny') return fail(`${slot.name} is denied by policy`);
400
+ if (slot.entry.policy === 'allow') return fail(`${slot.name} has policy allow; turn it on with enable {"name": "${slot.name}"}`);
401
+ this.log.info(`${slot.name}: approved through the host's permission prompt for enable_confirm`);
402
+ return this.toolEnable(name, extra, { approved: true });
403
+ }
404
+
405
+ /**
406
+ * Asks the person, through form elicitation, whether the agent may turn the server on.
407
+ * Fails closed in every case but an explicit accept with allow === true. With confirmVia
408
+ * "host" it never asks: the answer is to call enable_confirm.
409
+ * @param {Slot} slot
410
+ * @param {any} extra
411
+ * @returns {Promise<{ok: boolean, message?: string}>}
412
+ */
413
+ #confirm(slot, extra) {
414
+ if (this.hostConfirm) {
415
+ return Promise.resolve({
416
+ ok: false,
417
+ message: `${slot.name} needs a person's approval: call enable_confirm with {"name": "${slot.name}"}, which asks the person through the host's permission prompt.`,
418
+ });
419
+ }
420
+ if (!this.canElicitForm()) {
421
+ return Promise.resolve({
422
+ ok: false,
423
+ message: `${slot.name} needs a person's approval, but this client cannot ask (no elicitation support). A person must add it to autostart in the patchbay config, or set policy: allow.`,
424
+ });
425
+ }
426
+ if (slot.confirmPromise) return slot.confirmPromise;
427
+ const desc = slot.entry.description ? ` (${slot.entry.description})` : '';
428
+ const p = (async () => {
429
+ try {
430
+ const r = await this.server.elicitInput({
431
+ mode: 'form',
432
+ message: `Allow the agent to turn on ${slot.name}${desc}?`,
433
+ requestedSchema: {
434
+ type: 'object',
435
+ properties: { allow: { type: 'boolean', title: 'Allow', description: `Turn on ${slot.name} for this session` } },
436
+ required: ['allow'],
437
+ },
438
+ }, { signal: extra?.signal, timeout: NO_CAP_MS });
439
+ if (r.action === 'accept' && r.content?.allow === true) return { ok: true };
440
+ this.log.info(`${slot.name}: the person did not approve (${r.action})`);
441
+ return { ok: false, message: `${slot.name} was not approved by the person (${r.action === 'accept' ? 'allow was not ticked' : r.action}).` };
442
+ } catch (e) {
443
+ return { ok: false, message: `${slot.name} was not approved: the confirmation failed (${redact(/** @type {Error} */ (e).message)}).` };
444
+ }
445
+ })();
446
+ slot.confirmPromise = p;
447
+ p.finally(() => { if (slot.confirmPromise === p) slot.confirmPromise = null; });
448
+ return p;
449
+ }
450
+
451
+ /** @param {unknown} name */
452
+ async toolDisable(name) {
453
+ const { slot, error } = this.#slotOrError(name);
454
+ if (!slot) return error;
455
+ if (slot.restart) {
456
+ // The approval ends here: the restart in progress must not turn the server back on.
457
+ slot.restart = null;
458
+ if (slot.state === 'off') return ok({ name: slot.name, state: 'off', message: 'was restarting; the restart is cancelled' });
459
+ }
460
+ if (slot.state === 'off') return ok({ name: slot.name, state: 'off', message: 'already off' });
461
+ if (slot.state === 'failed') {
462
+ slot.state = 'off';
463
+ slot.lastError = undefined;
464
+ return ok({ name: slot.name, state: 'off', message: 'was failed; reset to off' });
465
+ }
466
+ if (slot.inFlight > 0) {
467
+ return fail(`${slot.name} has ${slot.inFlight} call(s) in flight; try again when they finish`, { name: slot.name, inFlight: slot.inFlight });
468
+ }
469
+ const wasOn = slot.state === 'on';
470
+ await this.#stop(slot);
471
+ if (wasOn) this.notifyToolsChanged();
472
+ this.log.info(`${slot.name}: disabled`);
473
+ return ok({ name: slot.name, state: 'off' });
474
+ }
475
+
476
+ /** @param {unknown} name @param {any} extra */
477
+ async toolRestart(name, extra) {
478
+ const { slot, error } = this.#slotOrError(name);
479
+ if (!slot) return error;
480
+ if (slot.entry.policy === 'deny') return fail(`${slot.name} is denied by policy`);
481
+ if (slot.state === 'starting' || slot.state === 'waiting-for-sign-in') {
482
+ return fail(`${slot.name} is ${slot.state}; wait for it, or disable it first`);
483
+ }
484
+ if (slot.state !== 'on' || slot.restart) return this.toolEnable(name, extra);
485
+ if (slot.inFlight > 0) {
486
+ return fail(`${slot.name} has ${slot.inFlight} call(s) in flight; try again when they finish`, { name: slot.name, inFlight: slot.inFlight });
487
+ }
488
+ // The approval of an "on" server carries over to its restart, unless a disable comes in
489
+ // while the old child is stopping (state is "off" then): disable clears this token.
490
+ const token = { promise: /** @type {Promise<any>} */ (Promise.resolve()) };
491
+ slot.restart = token;
492
+ token.promise = (async () => {
493
+ await this.#stop(slot);
494
+ if (slot.restart !== token) {
495
+ this.log.info(`${slot.name}: restart cancelled by disable`);
496
+ this.notifyToolsChanged(); // the stop took its tools away
497
+ return fail(`the restart of ${slot.name} was cancelled by a disable; it is off`, { name: slot.name, state: slot.state });
498
+ }
499
+ this.log.info(`${slot.name}: restarting`);
500
+ try {
501
+ const r = await this.toolEnable(name, extra, { skipConfirm: true });
502
+ // A start that worked announced the new tools; one that failed must still announce
503
+ // that the old ones are gone.
504
+ if (r.isError) this.notifyToolsChanged();
505
+ return r;
506
+ } finally {
507
+ if (slot.restart === token) slot.restart = null;
508
+ }
509
+ })();
510
+ return token.promise;
511
+ }
512
+
513
+ /** @param {unknown} name */
514
+ toolInfo(name) {
515
+ const { slot, error } = this.#slotOrError(name);
516
+ if (!slot) return error;
517
+ /** @type {Record<string, unknown>} */
518
+ const out = {
519
+ name: slot.name,
520
+ description: slot.entry.description,
521
+ policy: slot.entry.policy,
522
+ kind: slot.entry.kind,
523
+ state: slot.state,
524
+ inFlight: slot.inFlight,
525
+ };
526
+ if (slot.state === 'on') {
527
+ out.toolCount = slot.published.length;
528
+ out.tools = slot.published.map((p) => p.exposed);
529
+ }
530
+ if (slot.skipped.length) out.skippedTools = slot.skipped;
531
+ if (slot.lastError) out.lastError = slot.lastError;
532
+ const child = slot.child ?? slot.lastChild;
533
+ if (child) {
534
+ out.stderrTail = child.stderrTail(5);
535
+ const noise = child.noiseTail(20);
536
+ if (noise.length) out.stdoutNoise = noise;
537
+ }
538
+ if (slot.state === 'on' && slot.child?.instructions) out.instructions = slot.child.instructions;
539
+ return ok(out);
540
+ }
541
+
542
+ // ---- lifecycle of one child ------------------------------------------------------------
543
+
544
+ /**
545
+ * Starts a child (no policy checks here: callers have done them) and publishes its tools.
546
+ * @param {Slot} slot
547
+ * @returns {Promise<{ok: boolean, error?: string}>}
548
+ */
549
+ startSlot(slot) {
550
+ if (slot.startPromise) return slot.startPromise;
551
+ const entry = slot.entry;
552
+ slot.state = 'starting';
553
+ slot.lastError = undefined;
554
+ slot.exitError = undefined;
555
+ slot.authUrls = new Set();
556
+ slot.urlElicitationId = undefined;
557
+ slot.startAbort = new AbortController();
558
+ slot.lastNotify = undefined;
559
+ const child = new Child({
560
+ entry,
561
+ oauth: this.config.oauth,
562
+ clientCapabilities: this.clientCaps,
563
+ log: this.log,
564
+ pidFiles: this.pidFiles,
565
+ env: this.env,
566
+ handlers: this.#childHandlers(slot),
567
+ });
568
+ slot.child = child;
569
+ slot.lastChild = child;
570
+ child.on('auth-url', (url) => this.#onAuthUrl(slot, child, url));
571
+ child.on('exit', (info) => this.#onChildExit(slot, child, info));
572
+ child.on('tools-changed', () => { void this.#relist(slot, child); });
573
+
574
+ const timeout = entry.kind === 'url'
575
+ ? this.config.oauth.authTimeoutSeconds * 1000 + REMOTE_START_GRACE_MS
576
+ : STDIO_START_TIMEOUT_MS;
577
+
578
+ const p = (async () => {
579
+ try {
580
+ await child.start(timeout);
581
+ if (slot.child !== child) throw new Error('stopped');
582
+ const tools = await child.listTools();
583
+ if (slot.child !== child) throw new Error('stopped');
584
+ slot.state = 'on';
585
+ this.#publish(slot, tools);
586
+ this.log.info(`${slot.name}: on, ${slot.published.length} tools${slot.skipped.length ? `, ${slot.skipped.length} skipped` : ''}`);
587
+ if (slot.urlElicitationId && this.clientCaps.elicitation?.url) {
588
+ this.server.notification({ method: 'notifications/elicitation/complete', params: { elicitationId: slot.urlElicitationId } })
589
+ .catch((e) => this.log.debug(`elicitation/complete not sent: ${e.message}`));
590
+ }
591
+ slot.lastNotify = this.notifyToolsChanged();
592
+ return { ok: true };
593
+ } catch (e) {
594
+ if (slot.child === child) {
595
+ const msg = slot.exitError?.() ?? this.#describeStartError(slot, child, e, timeout);
596
+ slot.state = 'failed';
597
+ slot.lastError = msg;
598
+ slot.child = null;
599
+ this.#unpublish(slot);
600
+ this.log.warn(`${slot.name}: failed to start: ${msg}`);
601
+ await child.close().catch(() => {});
602
+ return { ok: false, error: msg };
603
+ }
604
+ return { ok: false, error: slot.lastError ?? 'disabled while starting' };
605
+ } finally {
606
+ slot.startAbort?.abort('start finished');
607
+ slot.startPromise = null;
608
+ }
609
+ })();
610
+ slot.startPromise = p;
611
+ return p;
612
+ }
613
+
614
+ /**
615
+ * @param {Slot} slot
616
+ * @param {Child} child
617
+ * @param {unknown} e
618
+ * @param {number} timeout
619
+ */
620
+ #describeStartError(slot, child, e, timeout) {
621
+ const err = /** @type {any} */ (e);
622
+ let msg;
623
+ if (err?.code === 'ENOENT') msg = `could not start ${slot.entry.kind === 'url' ? 'mcp-remote' : 'the command'}: not found (ENOENT)`;
624
+ else if (typeof err?.code === 'string') msg = `could not start: ${err.code}`;
625
+ else if (err instanceof McpError && err.code === ErrorCode.RequestTimeout) msg = `did not finish starting within ${Math.round(timeout / 1000)} s`;
626
+ else if (err instanceof McpError && err.code === ErrorCode.ConnectionClosed) msg = 'exited during startup';
627
+ else msg = String(err?.message ?? err).replace(/^MCP error -?\d+: /, '');
628
+ const last = child.stderrTail(1)[0];
629
+ if (last) msg += `; last stderr: ${last}`;
630
+ return redact(msg, child.secrets);
631
+ }
632
+
633
+ /**
634
+ * @param {Slot} slot
635
+ * @param {Child} child
636
+ * @param {{code: number|null, signal: string|null, expected: boolean}} info
637
+ */
638
+ #onChildExit(slot, child, info) {
639
+ if (info.expected || slot.child !== child) return;
640
+ const msg = info.signal ? `exited on signal ${info.signal}` : `exited with code ${info.code}`;
641
+ const describe = () => {
642
+ const last = child.stderrTail(1)[0];
643
+ return redact(last ? `${msg}; last stderr: ${last}` : msg, child.secrets);
644
+ };
645
+ if (slot.state !== 'on') {
646
+ // Read when the start fails, after the transport has closed: stderr may still be
647
+ // arriving when the exit event fires.
648
+ slot.exitError = describe;
649
+ return;
650
+ }
651
+ // Failed at once: the approval ends with the crash, so nothing may restart it without asking.
652
+ slot.state = 'failed';
653
+ slot.lastError = describe();
654
+ slot.child = null;
655
+ this.#unpublish(slot);
656
+ this.notifyToolsChanged();
657
+ // Give the last stderr lines a moment to arrive before quoting them.
658
+ setTimeout(() => {
659
+ if (slot.state === 'failed' && slot.lastChild === child) slot.lastError = describe();
660
+ this.log.warn(`${slot.name}: ${describe()}`);
661
+ }, 20);
662
+ }
663
+
664
+ /** @param {Slot} slot */
665
+ async #stop(slot) {
666
+ const child = slot.child;
667
+ slot.child = null;
668
+ slot.state = 'off';
669
+ slot.lastError = undefined;
670
+ this.#unpublish(slot);
671
+ if (child) await child.close().catch(() => {});
672
+ }
673
+
674
+ /**
675
+ * @param {Slot} slot
676
+ * @param {Child} child
677
+ */
678
+ async #relist(slot, child) {
679
+ if (slot.child !== child || slot.state !== 'on') return;
680
+ if (slot.relisting) {
681
+ slot.relistAgain = true;
682
+ return;
683
+ }
684
+ slot.relisting = true;
685
+ try {
686
+ do {
687
+ slot.relistAgain = false;
688
+ const tools = await child.listTools();
689
+ if (slot.child !== child || slot.state !== 'on') return;
690
+ this.#publish(slot, tools);
691
+ this.notifyToolsChanged();
692
+ } while (slot.relistAgain);
693
+ } catch (e) {
694
+ this.log.warn(`${slot.name}: re-listing tools failed: ${/** @type {Error} */ (e).message}`, child.secrets);
695
+ } finally {
696
+ slot.relisting = false;
697
+ }
698
+ }
699
+
700
+ /** Handlers for requests a child sends to us. @param {Slot} slot */
701
+ #childHandlers(slot) {
702
+ return {
703
+ roots: async (params, extra) => {
704
+ await this.whenClientReady();
705
+ return this.server.listRoots(params, { signal: extra.signal });
706
+ },
707
+ elicit: async (params, extra) => {
708
+ await this.whenClientReady();
709
+ const forwarded = { ...params, message: `[${slot.name}] ${params.message}` };
710
+ return this.server.request({ method: 'elicitation/create', params: forwarded }, ElicitResultSchema, { signal: extra.signal, timeout: NO_CAP_MS });
711
+ },
712
+ elicitationComplete: (params) => {
713
+ if (!this.clientCaps.elicitation?.url) return;
714
+ this.server.notification({ method: 'notifications/elicitation/complete', params })
715
+ .catch((e) => this.log.debug(`elicitation/complete not forwarded: ${e.message}`));
716
+ },
717
+ };
718
+ }
719
+
720
+ /**
721
+ * mcp-remote printed a sign-in URL. Tell the person, through the client.
722
+ * @param {Slot} slot
723
+ * @param {Child} child
724
+ * @param {string} url
725
+ */
726
+ #onAuthUrl(slot, child, url) {
727
+ if (slot.child !== child || slot.authUrls.has(url)) return;
728
+ if (slot.state !== 'starting' && slot.state !== 'waiting-for-sign-in') {
729
+ // Only a start may ask the person to sign in; a child cannot raise the prompt later.
730
+ this.log.warn(`${slot.name} asked for a sign-in while ${slot.state}; not shown. Restart it to sign in again.`, child.secrets);
731
+ return;
732
+ }
733
+ slot.authUrls.add(url);
734
+ slot.state = 'waiting-for-sign-in';
735
+ this.log.info(`${slot.name}: waiting for sign-in`);
736
+ void this.#askSignIn(slot, child, url);
737
+ }
738
+
739
+ /**
740
+ * @param {Slot} slot
741
+ * @param {Child} child
742
+ * @param {string} url sent unredacted, to the person only
743
+ */
744
+ async #askSignIn(slot, child, url) {
745
+ await this.whenClientReady();
746
+ if (slot.child !== child) return;
747
+ const caps = this.clientCaps.elicitation;
748
+ // The URL comes from the child, so the prompt is attributed like a child's own elicitation.
749
+ const message = `[${slot.name}] Sign in to ${slot.name} to finish turning it on.`;
750
+ const signal = slot.startAbort?.signal;
751
+ try {
752
+ let r;
753
+ if (caps?.url) {
754
+ const elicitationId = randomUUID();
755
+ slot.urlElicitationId = elicitationId;
756
+ r = await this.server.elicitInput({ mode: 'url', message, url, elicitationId }, { signal, timeout: NO_CAP_MS });
757
+ } else if (caps?.form) {
758
+ r = await this.server.elicitInput({
759
+ mode: 'form',
760
+ message: `${message} Open this link in your browser: ${url}`,
761
+ requestedSchema: { type: 'object', properties: { done: { type: 'boolean', title: 'I have signed in' } } },
762
+ }, { signal, timeout: NO_CAP_MS });
763
+ } else {
764
+ this.log.warn(`${slot.name} needs a sign-in, but the client cannot show a link (no elicitation support); mcp-remote tries to open a browser itself`);
765
+ return;
766
+ }
767
+ if (r.action !== 'accept' && slot.child === child && slot.state !== 'on') {
768
+ this.log.info(`${slot.name}: sign-in declined (${r.action})`);
769
+ slot.lastError = 'sign-in declined';
770
+ slot.state = 'failed';
771
+ slot.child = null;
772
+ this.#unpublish(slot);
773
+ await child.close().catch(() => {});
774
+ }
775
+ } catch (e) {
776
+ if (slot.child === child) this.log.debug(`${slot.name}: sign-in elicitation ended: ${/** @type {Error} */ (e).message}`);
777
+ }
778
+ }
779
+
780
+ // ---- proxying ---------------------------------------------------------------------------
781
+
782
+ /**
783
+ * @param {any} request
784
+ * @param {any} extra
785
+ */
786
+ async #forward(request, extra) {
787
+ const name = request.params.name;
788
+ const route = this.routes.get(name);
789
+ if (!route) {
790
+ const split = splitExposed(name);
791
+ const slot = split ? this.bySegment.get(split.segment) : undefined;
792
+ // An enabled server without that tool gets the protocol error, not advice to enable it.
793
+ if (slot && slot.state !== 'on') return fail(`${slot.name} is not enabled; call enable with {"name": "${slot.name}"} first`, { state: slot.state });
794
+ throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${redact(name).slice(0, 200)}`);
795
+ }
796
+ const { slot, original, child } = route;
797
+ const params = { ...request.params, name: original };
798
+ const token = request.params._meta?.progressToken;
799
+ /** @type {{signal?: AbortSignal, timeout: number, onprogress?: (p: any) => void}} */
800
+ const opts = { signal: extra.signal, timeout: slot.entry.timeoutMs || NO_CAP_MS };
801
+ if (token !== undefined) {
802
+ opts.onprogress = (p) => {
803
+ extra.sendNotification({ method: 'notifications/progress', params: { ...p, progressToken: token } })
804
+ .catch((e) => this.log.debug(`progress not forwarded: ${e.message}`));
805
+ };
806
+ }
807
+ slot.inFlight++;
808
+ try {
809
+ return await child.call(params, opts);
810
+ } catch (e) {
811
+ if (e instanceof McpError) {
812
+ if (e.code === ErrorCode.ConnectionClosed || child.transport?.exited) {
813
+ throw new McpError(ErrorCode.ConnectionClosed, `${slot.name} exited during the call`);
814
+ }
815
+ throw new McpError(e.code, redact(e.message.replace(/^MCP error -?\d+: /, ''), child.secrets), e.data);
816
+ }
817
+ if (child.transport?.exited) throw new McpError(ErrorCode.ConnectionClosed, `${slot.name} exited during the call`);
818
+ throw new McpError(ErrorCode.InternalError, redact(/** @type {Error} */ (e)?.message ?? String(e), child.secrets));
819
+ } finally {
820
+ slot.inFlight--;
821
+ }
822
+ }
823
+
824
+ // ---- autostart, instructions, shutdown -------------------------------------------------
825
+
826
+ /** @param {number} waitMs */
827
+ async autostart(waitMs) {
828
+ const names = autostartFor(this.config, this.projectDir).filter((n) => this.slots.get(n)?.entry.policy !== 'deny');
829
+ this.autostarted = names;
830
+ if (!names.length) return;
831
+ this.log.info(`autostart: ${names.join(', ')}`);
832
+ const all = Promise.allSettled(names.map((n) => this.startSlot(/** @type {Slot} */ (this.slots.get(n)))));
833
+ let t;
834
+ await Promise.race([all, new Promise((r) => { t = setTimeout(r, waitMs); })]);
835
+ clearTimeout(t);
836
+ }
837
+
838
+ instructionsText() {
839
+ const servers = [...this.slots.values()].map((s) => ({ name: s.name, description: s.entry.description, policy: s.entry.policy, state: s.state }));
840
+ const autostarted = this.autostarted
841
+ .map((n) => /** @type {Slot} */ (this.slots.get(n)))
842
+ .filter((s) => s.state === 'on' && s.child?.instructions)
843
+ .map((s) => ({ name: s.name, instructions: /** @type {string} */ (s.child?.instructions) }));
844
+ return buildInstructions(servers, autostarted, { confirmVia: this.config.confirmVia });
845
+ }
846
+
847
+ /**
848
+ * Synchronous: SIGTERM every child's process group, and leave a detached helper that SIGKILLs
849
+ * the groups that are still there after SHUTDOWN_KILL_DELAY_MS. Pidfiles of children whose
850
+ * exit was not seen are kept, so if the helper fails the next start's reaper finishes the job.
851
+ * Used on SIGINT/SIGTERM/stdin end.
852
+ */
853
+ shutdownSync() {
854
+ this.closed = true;
855
+ const pending = [];
856
+ for (const slot of this.slots.values()) {
857
+ try {
858
+ const pid = slot.child?.killNow();
859
+ if (pid) pending.push({ pid, start: processStartTime(pid), file: this.pidFiles?.enabled ? this.pidFiles.file(pid) : undefined });
860
+ } catch { /* keep going */ }
861
+ }
862
+ killGroupsLater(pending);
863
+ }
864
+ }