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.
@@ -0,0 +1,521 @@
1
+ // Child MCP servers: a custom stdio transport, spawn specs for stdio and remote (mcp-remote)
2
+ // children, and the per-child SDK Client. See SPEC.md §7 and §8.
3
+ import { spawn } from 'node:child_process';
4
+ import { EventEmitter } from 'node:events';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { createRequire } from 'node:module';
8
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
9
+ import {
10
+ CallToolResultSchema,
11
+ ElicitRequestSchema,
12
+ ElicitationCompleteNotificationSchema,
13
+ ErrorCode,
14
+ JSONRPCMessageSchema,
15
+ ListRootsRequestSchema,
16
+ McpError,
17
+ ProgressNotificationSchema,
18
+ ToolListChangedNotificationSchema,
19
+ } from '@modelcontextprotocol/sdk/types.js';
20
+ import * as z from 'zod';
21
+ import { killTree, pidAlive, SHUTDOWN_KILL_DELAY_MS } from './process.js';
22
+ import { redact, RingBuffer, secretsFor } from './redact.js';
23
+ import { VERSION } from './version.js';
24
+
25
+ const IS_WINDOWS = process.platform === 'win32';
26
+ export const AUTH_MARKER = 'Please authorize this client by visiting:';
27
+ const URL_RE = /https?:\/\/[^\s'"<>]+/;
28
+ const MAX_LINE = 64 * 1024 * 1024;
29
+ const NOISE_LINE_MAX = 500;
30
+ const KILL_GRACE_MS = 2000;
31
+ /** Largest delay setTimeout accepts; used as "no cap". */
32
+ export const NO_CAP_MS = 2147483647;
33
+
34
+ /**
35
+ * Loose tools/list result: we validate each tool separately (naming.mapTools) and keep the
36
+ * original objects, so unknown keys pass through.
37
+ */
38
+ const LooseListToolsResultSchema = z.object({
39
+ tools: z.array(z.looseObject({})),
40
+ nextCursor: z.string().optional(),
41
+ }).loose();
42
+
43
+ const RUNNERS = new Set(['npx', 'pnpx', 'bunx', 'pnpm', 'yarn', 'bun']);
44
+ const MCP_REMOTE_ARG = /^mcp-remote(?:@[^\s/]*)?$/;
45
+
46
+ /**
47
+ * Is this entry mcp-remote? Only then is its stderr watched for the sign-in line. True for `url`
48
+ * entries, for a command whose basename is mcp-remote, and for a package runner (npx, pnpx,
49
+ * bunx, pnpm, yarn, bun) with an `mcp-remote` or `mcp-remote@<version>` argument.
50
+ * @param {{kind: string, command?: string, args?: string[]}} entry
51
+ */
52
+ export function isMcpRemote(entry) {
53
+ if (entry.kind === 'url') return true;
54
+ if (typeof entry.command !== 'string') return false;
55
+ const base = path.basename(entry.command.replace(/\\/g, '/')).replace(/\.(?:cmd|exe|bat|ps1|js|mjs|cjs)$/i, '').toLowerCase();
56
+ if (base === 'mcp-remote') return true;
57
+ return RUNNERS.has(base) && (entry.args ?? []).some((a) => MCP_REMOTE_ARG.test(a));
58
+ }
59
+
60
+ /** Resolves mcp-remote's bin without npx. */
61
+ export function mcpRemoteBin(env = process.env) {
62
+ if (env.MCP_PATCHBAY_MCP_REMOTE_BIN) return env.MCP_PATCHBAY_MCP_REMOTE_BIN;
63
+ const require = createRequire(import.meta.url);
64
+ const pkgPath = require.resolve('mcp-remote/package.json');
65
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
66
+ const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin['mcp-remote'];
67
+ return path.join(path.dirname(pkgPath), bin);
68
+ }
69
+
70
+ /**
71
+ * How to spawn a child. stdio: as configured. url: node <mcp-remote> <url> --auth-timeout N
72
+ * --header K:${MCP_PATCHBAY_HEADER_i}, with the header values in the env, not in argv.
73
+ * @param {import('./config.js').ServerEntry} entry
74
+ * @param {{configDir: string, authTimeoutSeconds: number}} oauth
75
+ * @param {NodeJS.ProcessEnv} [baseEnv]
76
+ * @returns {{command: string, args: string[], env: Record<string,string>, cwd?: string}}
77
+ */
78
+ export function spawnSpec(entry, oauth, baseEnv = process.env) {
79
+ /** @type {Record<string,string>} */
80
+ const env = { .../** @type {Record<string,string>} */ (baseEnv), ...entry.env };
81
+ if (entry.kind === 'stdio') {
82
+ return { command: /** @type {string} */ (entry.command), args: [...entry.args], env, cwd: entry.cwd };
83
+ }
84
+ const args = [mcpRemoteBin(baseEnv), /** @type {string} */ (entry.url), '--auth-timeout', String(oauth.authTimeoutSeconds)];
85
+ let i = 0;
86
+ for (const [k, v] of Object.entries(entry.headers)) {
87
+ if (v.includes('${')) {
88
+ args.push('--header', `${k}:${v}`);
89
+ } else {
90
+ const ref = `MCP_PATCHBAY_HEADER_${i++}`;
91
+ env[ref] = v;
92
+ args.push('--header', `${k}:\${${ref}}`);
93
+ }
94
+ }
95
+ env.MCP_REMOTE_CONFIG_DIR = oauth.configDir;
96
+ return { command: process.execPath, args, env };
97
+ }
98
+
99
+ /**
100
+ * MCP over a child's stdio. Unlike the SDK's StdioClientTransport it passes the full env,
101
+ * detaches the child into its own process group on POSIX, tolerates non-JSON stdout lines and
102
+ * keeps redacted stderr in a ring buffer.
103
+ */
104
+ export class ChildProcessTransport {
105
+ /**
106
+ * @param {object} o
107
+ * @param {string} o.command
108
+ * @param {string[]} o.args
109
+ * @param {Record<string,string>} o.env
110
+ * @param {string} [o.cwd]
111
+ * @param {string[]} o.secrets
112
+ * @param {(raw: string) => void} [o.onStderrLine]
113
+ * @param {(pid: number) => void} [o.onSpawn]
114
+ * @param {(info: {code: number|null, signal: string|null}) => void} [o.onExit]
115
+ */
116
+ constructor(o) {
117
+ this.o = o;
118
+ this.stderr = new RingBuffer(20);
119
+ this.noise = new RingBuffer(20);
120
+ /** @type {import('node:child_process').ChildProcess | null} */
121
+ this.proc = null;
122
+ this.pid = 0;
123
+ this.exited = false;
124
+ this.closing = false;
125
+ /** @type {{code: number|null, signal: string|null} | null} */
126
+ this.exitInfo = null;
127
+ this.outBuf = '';
128
+ this.errBuf = '';
129
+ this.closed = false;
130
+ /** @type {((m: any) => void) | undefined} */ this.onmessage = undefined;
131
+ /** @type {((e: Error) => void) | undefined} */ this.onerror = undefined;
132
+ /** @type {(() => void) | undefined} */ this.onclose = undefined;
133
+ /** @type {Promise<void>} */
134
+ this.exitPromise = new Promise((r) => { this.resolveExit = r; });
135
+ }
136
+
137
+ async start() {
138
+ const o = this.o;
139
+ await new Promise((resolve, reject) => {
140
+ let proc;
141
+ try {
142
+ proc = spawn(o.command, o.args, {
143
+ cwd: o.cwd,
144
+ env: o.env,
145
+ stdio: ['pipe', 'pipe', 'pipe'],
146
+ shell: false,
147
+ windowsHide: true,
148
+ detached: !IS_WINDOWS,
149
+ });
150
+ } catch (e) {
151
+ reject(e);
152
+ return;
153
+ }
154
+ this.proc = proc;
155
+ let spawned = false;
156
+ proc.once('spawn', () => {
157
+ spawned = true;
158
+ this.pid = /** @type {number} */ (proc.pid);
159
+ o.onSpawn?.(this.pid);
160
+ resolve(undefined);
161
+ });
162
+ proc.on('error', (err) => {
163
+ if (!spawned) {
164
+ this.exited = true;
165
+ this.resolveExit?.();
166
+ reject(err);
167
+ this.#finish();
168
+ } else {
169
+ this.onerror?.(err);
170
+ }
171
+ });
172
+ proc.on('exit', (code, signal) => {
173
+ this.exited = true;
174
+ this.exitInfo = { code, signal };
175
+ // Grandchildren may keep the pipes open; give stdout a moment to drain, then finish.
176
+ const t = setTimeout(() => this.#finish(), 200);
177
+ t.unref?.();
178
+ o.onExit?.(this.exitInfo);
179
+ this.resolveExit?.();
180
+ });
181
+ proc.on('close', () => this.#finish());
182
+ proc.stdout?.setEncoding('utf8');
183
+ proc.stdout?.on('data', (chunk) => this.#onStdout(chunk));
184
+ proc.stdout?.on('error', () => {});
185
+ proc.stderr?.setEncoding('utf8');
186
+ proc.stderr?.on('data', (chunk) => this.#onStderr(chunk));
187
+ // A last line without a newline (often the reason a child died) is still a line.
188
+ proc.stderr?.on('end', () => {
189
+ if (this.errBuf) this.#stderrLine(this.errBuf.replace(/\r$/, ''));
190
+ this.errBuf = '';
191
+ });
192
+ proc.stderr?.on('error', () => {});
193
+ proc.stdin?.on('error', (err) => {
194
+ // EPIPE after the child died: report, never throw.
195
+ this.onerror?.(new Error(`stdin: ${/** @type {any} */ (err).code ?? err.message}`));
196
+ });
197
+ });
198
+ }
199
+
200
+ #finish() {
201
+ if (this.closed) return;
202
+ this.closed = true;
203
+ this.onclose?.();
204
+ }
205
+
206
+ /** @param {string} chunk */
207
+ #onStdout(chunk) {
208
+ this.outBuf += chunk;
209
+ if (this.outBuf.length > MAX_LINE && !this.outBuf.includes('\n')) {
210
+ this.noise.push(`[discarded ${this.outBuf.length} bytes without a newline]`);
211
+ this.outBuf = '';
212
+ return;
213
+ }
214
+ let i;
215
+ while ((i = this.outBuf.indexOf('\n')) !== -1) {
216
+ const line = this.outBuf.slice(0, i).replace(/\r$/, '');
217
+ this.outBuf = this.outBuf.slice(i + 1);
218
+ if (!line.trim()) continue;
219
+ let msg;
220
+ try {
221
+ msg = JSON.parse(line);
222
+ } catch {
223
+ msg = undefined;
224
+ }
225
+ if (msg !== undefined && JSONRPCMessageSchema.safeParse(msg).success) {
226
+ try {
227
+ this.onmessage?.(msg);
228
+ } catch (e) {
229
+ this.onerror?.(/** @type {Error} */ (e));
230
+ }
231
+ } else {
232
+ this.noise.push(redact(line, this.o.secrets).slice(0, NOISE_LINE_MAX));
233
+ }
234
+ }
235
+ }
236
+
237
+ /** @param {string} chunk */
238
+ #onStderr(chunk) {
239
+ this.errBuf += chunk;
240
+ if (this.errBuf.length > 1024 * 1024 && !this.errBuf.includes('\n')) this.errBuf = this.errBuf.slice(-4096);
241
+ let i;
242
+ while ((i = this.errBuf.indexOf('\n')) !== -1) {
243
+ const raw = this.errBuf.slice(0, i).replace(/\r$/, '');
244
+ this.errBuf = this.errBuf.slice(i + 1);
245
+ this.#stderrLine(raw);
246
+ }
247
+ }
248
+
249
+ /** @param {string} raw */
250
+ #stderrLine(raw) {
251
+ this.o.onStderrLine?.(raw);
252
+ if (raw.trim()) this.stderr.push(redact(raw, this.o.secrets).slice(0, NOISE_LINE_MAX));
253
+ }
254
+
255
+ /** @param {any} message */
256
+ send(message) {
257
+ return new Promise((resolve, reject) => {
258
+ const stdin = this.proc?.stdin;
259
+ if (!stdin || this.exited || !stdin.writable) {
260
+ reject(new Error('child is not running'));
261
+ return;
262
+ }
263
+ stdin.write(JSON.stringify(message) + '\n', (err) => (err ? reject(err) : resolve(undefined)));
264
+ });
265
+ }
266
+
267
+ /** Graceful: close stdin, SIGTERM the group, SIGKILL after a grace period. */
268
+ async close() {
269
+ this.closing = true;
270
+ if (this.proc && !this.exited) {
271
+ try { this.proc.stdin?.end(); } catch { /* ignore */ }
272
+ killTree(this.pid, 'SIGTERM');
273
+ const t = setTimeout(() => { if (!this.exited) killTree(this.pid, 'SIGKILL'); }, KILL_GRACE_MS);
274
+ t.unref?.();
275
+ await Promise.race([this.exitPromise, new Promise((r) => setTimeout(r, KILL_GRACE_MS + 500).unref?.())]);
276
+ clearTimeout(t);
277
+ }
278
+ // If the leader had already exited, onExit already signalled what was left of its group;
279
+ // signalling again could hit an unrelated group once the id is free for reuse.
280
+ this.#finish();
281
+ }
282
+
283
+ /**
284
+ * Synchronous SIGTERM for shutdown.
285
+ * @returns {number} the pid that was signalled and has not been seen to exit, or 0
286
+ */
287
+ killNow() {
288
+ this.closing = true;
289
+ if (this.pid && !this.exited && killTree(this.pid, 'SIGTERM')) return this.pid;
290
+ return 0;
291
+ }
292
+ }
293
+
294
+ /**
295
+ * One running child: process, transport and SDK Client.
296
+ * Events: 'auth-url' (url), 'exit' ({code, signal, expected}), 'tools-changed'.
297
+ */
298
+ export class Child extends EventEmitter {
299
+ /**
300
+ * @param {object} o
301
+ * @param {import('./config.js').ServerEntry} o.entry
302
+ * @param {{configDir: string, authTimeoutSeconds: number}} o.oauth
303
+ * @param {any} o.clientCapabilities capabilities the patchbay's own client declared
304
+ * @param {import('./log.js').Logger} o.log
305
+ * @param {import('./process.js').PidFiles | null} [o.pidFiles]
306
+ * @param {NodeJS.ProcessEnv} [o.env]
307
+ * @param {{roots?: (params: any, extra: any) => Promise<any>, elicit?: (params: any, extra: any) => Promise<any>, elicitationComplete?: (params: any) => void}} [o.handlers]
308
+ */
309
+ constructor(o) {
310
+ super();
311
+ this.o = o;
312
+ this.entry = o.entry;
313
+ this.secrets = secretsFor(o.entry);
314
+ this.expectedExit = false;
315
+ /** @type {string | undefined} */
316
+ this.instructions = undefined;
317
+ this.pendingUrlLines = 0;
318
+ /** @type {ChildProcessTransport | null} */
319
+ this.transport = null;
320
+ /** @type {Client | null} */
321
+ this.client = null;
322
+ /** Progress callbacks of calls in flight, by the progress token sent to the child. */
323
+ /** @type {Map<string, (p: any) => void>} */
324
+ this.progress = new Map();
325
+ this.progressSeq = 0;
326
+ }
327
+
328
+ get pid() {
329
+ return this.transport?.pid ?? 0;
330
+ }
331
+
332
+ /** @param {string} raw */
333
+ #watchAuth(raw) {
334
+ if (this.pendingUrlLines > 0) {
335
+ const m = URL_RE.exec(raw);
336
+ if (m) {
337
+ this.pendingUrlLines = 0;
338
+ this.emit('auth-url', m[0]);
339
+ return;
340
+ }
341
+ if (raw.trim()) this.pendingUrlLines--;
342
+ }
343
+ const at = raw.indexOf(AUTH_MARKER);
344
+ if (at !== -1) {
345
+ const m = URL_RE.exec(raw.slice(at + AUTH_MARKER.length));
346
+ if (m) this.emit('auth-url', m[0]);
347
+ else this.pendingUrlLines = 3;
348
+ }
349
+ }
350
+
351
+ /** Capabilities we declare to the child: only what the patchbay's client declared. */
352
+ childCapabilities() {
353
+ const c = this.o.clientCapabilities ?? {};
354
+ /** @type {any} */
355
+ const caps = {};
356
+ if (c.roots) caps.roots = { listChanged: true };
357
+ if (c.elicitation) caps.elicitation = JSON.parse(JSON.stringify(c.elicitation));
358
+ return caps;
359
+ }
360
+
361
+ /**
362
+ * Spawns and initializes the child.
363
+ * @param {number} timeoutMs initialize timeout
364
+ */
365
+ async start(timeoutMs) {
366
+ const { entry, oauth, log } = this.o;
367
+ if (entry.kind === 'url') {
368
+ fs.mkdirSync(oauth.configDir, { recursive: true, mode: 0o700 });
369
+ if (!IS_WINDOWS) fs.chmodSync(oauth.configDir, 0o700);
370
+ }
371
+ const spec = spawnSpec(entry, oauth, this.o.env ?? process.env);
372
+ if (spec.cwd && !fs.statSync(spec.cwd, { throwIfNoEntry: false })?.isDirectory()) {
373
+ // spawn would report this as ENOENT, which reads like "command not found".
374
+ throw new Error('the configured cwd does not exist or is not a directory');
375
+ }
376
+ // Any other child printing a sign-in line must not get a patchbay sign-in prompt.
377
+ const watchAuth = isMcpRemote(entry);
378
+ const transport = new ChildProcessTransport({
379
+ ...spec,
380
+ secrets: this.secrets,
381
+ onStderrLine: (raw) => {
382
+ if (watchAuth) this.#watchAuth(raw);
383
+ log.debug(`[${entry.name}] ${raw}`, this.secrets);
384
+ },
385
+ onSpawn: (pid) => this.o.pidFiles?.record(pid),
386
+ onExit: (info) => {
387
+ const pid = this.transport?.pid;
388
+ if (pid) {
389
+ // Take down whatever is left of the group (never a bare pid: ours is gone), then
390
+ // SIGKILL what ignored that. The leader has exited, so the group id stays reserved
391
+ // while members remain; if a process with that pid exists by then, it is a new one
392
+ // and its group is left alone. Windows has no group to address: `taskkill /PID` on
393
+ // the exited pid could hit a process that reused it, so nothing is killed there.
394
+ if (!IS_WINDOWS && killTree(pid, 'SIGTERM', { bare: false })) {
395
+ const t = setTimeout(() => { if (!pidAlive(pid)) killTree(pid, 'SIGKILL', { bare: false }); }, SHUTDOWN_KILL_DELAY_MS);
396
+ t.unref?.();
397
+ }
398
+ this.o.pidFiles?.remove(pid);
399
+ }
400
+ this.emit('exit', { ...info, expected: this.expectedExit || transport.closing });
401
+ },
402
+ });
403
+ this.transport = transport;
404
+
405
+ const client = new Client({ name: 'mcp-patchbay', version: VERSION }, { capabilities: this.childCapabilities() });
406
+ this.client = client;
407
+ const caps = this.o.clientCapabilities ?? {};
408
+ const h = this.o.handlers ?? {};
409
+ if (caps.roots && h.roots) {
410
+ client.setRequestHandler(ListRootsRequestSchema, (req, extra) => /** @type {any} */ (h.roots)(req.params, extra));
411
+ }
412
+ if (caps.elicitation && h.elicit) {
413
+ client.setRequestHandler(ElicitRequestSchema, (req, extra) => /** @type {any} */ (h.elicit)(req.params, extra));
414
+ }
415
+ client.fallbackRequestHandler = async (request) => {
416
+ switch (request.method) {
417
+ case 'sampling/createMessage':
418
+ throw new McpError(ErrorCode.MethodNotFound, 'mcp-patchbay does not forward sampling/createMessage; sampling is not available to hosted servers');
419
+ case 'roots/list':
420
+ throw new McpError(ErrorCode.MethodNotFound, "roots/list is not available: the patchbay's client did not declare the roots capability");
421
+ case 'elicitation/create':
422
+ throw new McpError(ErrorCode.MethodNotFound, "elicitation/create is not available: the patchbay's client did not declare the elicitation capability");
423
+ default:
424
+ throw new McpError(ErrorCode.MethodNotFound, `Method not found: ${request.method}`);
425
+ }
426
+ };
427
+ client.setNotificationHandler(ToolListChangedNotificationSchema, () => { this.emit('tools-changed'); });
428
+ client.setNotificationHandler(ElicitationCompleteNotificationSchema, (n) => { h.elicitationComplete?.(n.params); });
429
+ // Progress is matched here, not by the SDK's `onprogress`: the SDK runs a notification
430
+ // handler a microtask late but handles a response at once, dropping its progress handler,
431
+ // so a last progress notification read in the same chunk as the response was lost.
432
+ client.setNotificationHandler(ProgressNotificationSchema, (n) => {
433
+ const { progressToken, ...p } = n.params;
434
+ this.progress.get(String(progressToken))?.(p);
435
+ });
436
+ client.onerror = (err) => log.debug(`[${entry.name}] client error: ${err.message}`, this.secrets);
437
+
438
+ await client.connect(transport, { timeout: timeoutMs });
439
+ if (transport.pid && !transport.exited) this.o.pidFiles?.refresh(transport.pid);
440
+ this.instructions = client.getInstructions();
441
+ }
442
+
443
+ /**
444
+ * Lists all tools, following nextCursor.
445
+ * @param {number} [timeoutMs]
446
+ * @returns {Promise<Array<Record<string, any>>>}
447
+ */
448
+ async listTools(timeoutMs = 60000) {
449
+ const client = /** @type {Client} */ (this.client);
450
+ const tools = [];
451
+ /** @type {string | undefined} */
452
+ let cursor;
453
+ for (let page = 0; page < 1000; page++) {
454
+ const r = await client.request(
455
+ { method: 'tools/list', params: cursor ? { cursor } : {} },
456
+ LooseListToolsResultSchema,
457
+ { timeout: timeoutMs },
458
+ );
459
+ tools.push(...r.tools);
460
+ if (!r.nextCursor || r.nextCursor === cursor) break;
461
+ cursor = r.nextCursor;
462
+ }
463
+ return tools;
464
+ }
465
+
466
+ /**
467
+ * Forwards tools/call. Raw request, so outputSchema is not enforced (unlike callTool).
468
+ * @param {any} params
469
+ * @param {{signal?: AbortSignal, timeout: number, onprogress?: (p: any) => void}} opts
470
+ */
471
+ async call(params, opts) {
472
+ const client = /** @type {Client} */ (this.client);
473
+ const { onprogress, ...rest } = opts;
474
+ if (!onprogress) return client.request({ method: 'tools/call', params }, CallToolResultSchema, rest);
475
+ const token = `patchbay-${++this.progressSeq}`;
476
+ this.progress.set(token, onprogress);
477
+ try {
478
+ const withToken = { ...params, _meta: { ...params._meta, progressToken: token } };
479
+ return await client.request({ method: 'tools/call', params: withToken }, CallToolResultSchema, rest);
480
+ } finally {
481
+ // A progress notification read with the response is dispatched before this runs.
482
+ this.progress.delete(token);
483
+ }
484
+ }
485
+
486
+ async rootsListChanged() {
487
+ try {
488
+ await this.client?.sendRootsListChanged();
489
+ } catch (e) {
490
+ this.o.log.debug(`[${this.entry.name}] roots list_changed not sent: ${/** @type {Error} */ (e).message}`);
491
+ }
492
+ }
493
+
494
+ stderrTail(n = 5) {
495
+ return this.transport?.stderr.lines(n) ?? [];
496
+ }
497
+
498
+ noiseTail(n = 20) {
499
+ return this.transport?.noise.lines(n) ?? [];
500
+ }
501
+
502
+ /** Graceful stop. */
503
+ async close() {
504
+ this.expectedExit = true;
505
+ const t = this.transport;
506
+ if (!t) return;
507
+ await t.close();
508
+ // Keep the pidfile of a child that has not been seen to exit, so the reaper can finish it.
509
+ if (t.pid && t.exited) this.o.pidFiles?.remove(t.pid);
510
+ try { await this.client?.close(); } catch { /* already closed */ }
511
+ }
512
+
513
+ /**
514
+ * Synchronous stop for shutdown.
515
+ * @returns {number} the pid still to be confirmed gone, or 0
516
+ */
517
+ killNow() {
518
+ this.expectedExit = true;
519
+ return this.transport?.killNow() ?? 0;
520
+ }
521
+ }
package/src/cli.js ADDED
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env node
2
+ // mcp-patchbay command line. With no subcommand it serves MCP over stdio.
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { ConfigError, EX_CONFIG, loadConfig, resolveConfigPath } from './config.js';
5
+ import { createLogger } from './log.js';
6
+ import { PidFiles, pidDirFor } from './process.js';
7
+ import { redact } from './redact.js';
8
+ import { Patchbay } from './server.js';
9
+ import { VERSION } from './version.js';
10
+
11
+ const USAGE = `mcp-patchbay ${VERSION}: host MCP servers and switch them on and off mid-session
12
+
13
+ Usage:
14
+ mcp-patchbay [--config <path>]
15
+ Serve MCP over stdio. Config: --config, else $MCP_PATCHBAY_CONFIG,
16
+ else ~/.config/mcp-patchbay/servers.json
17
+ mcp-patchbay import --from <claude.json> [--project <dir>] [--out <servers.json>]
18
+ Write a patchbay config from a Claude Code config.
19
+ mcp-patchbay doctor [--config <path>] [--project <dir>] [--all] [--no-start]
20
+ Validate the config, warn about Claude Code allow rules that would approve
21
+ enable_confirm (user settings, plus <dir>/.claude with --project), and briefly
22
+ start each allow server (--all: confirm ones too; --no-start: none).
23
+ mcp-patchbay rename-permissions <settings.json> [--write] [--config <path>]
24
+ Add mcp__patchbay__... twins of mcp__... permission rules (dry run unless --write).
25
+ mcp-patchbay --help | --version
26
+ `;
27
+
28
+ /**
29
+ * Minimal argv parser: --flag value, --switch, positionals.
30
+ * @param {string[]} argv
31
+ * @param {string[]} switches flags without a value
32
+ */
33
+ export function parseArgs(argv, switches = []) {
34
+ /** @type {Record<string, string | boolean>} */
35
+ const flags = {};
36
+ const positionals = [];
37
+ for (let i = 0; i < argv.length; i++) {
38
+ const a = argv[i];
39
+ if (a.startsWith('--')) {
40
+ const eq = a.indexOf('=');
41
+ if (eq !== -1) {
42
+ flags[a.slice(2, eq)] = a.slice(eq + 1);
43
+ } else if (switches.includes(a.slice(2))) {
44
+ flags[a.slice(2)] = true;
45
+ } else {
46
+ const v = argv[i + 1];
47
+ if (v === undefined || v.startsWith('--')) throw new Error(`${a} needs a value`);
48
+ flags[a.slice(2)] = v;
49
+ i++;
50
+ }
51
+ } else {
52
+ positionals.push(a);
53
+ }
54
+ }
55
+ return { flags, positionals };
56
+ }
57
+
58
+ /** @param {string[]} argv */
59
+ async function serve(argv) {
60
+ const log = createLogger();
61
+ let flags;
62
+ try {
63
+ ({ flags } = parseArgs(argv));
64
+ } catch (e) {
65
+ process.stderr.write(`mcp-patchbay: ${/** @type {Error} */ (e).message}\n\n${USAGE}`);
66
+ process.exit(64);
67
+ }
68
+ const unknown = Object.keys(flags).filter((k) => k !== 'config');
69
+ if (unknown.length) {
70
+ process.stderr.write(`mcp-patchbay: unknown option --${unknown[0]}\n\n${USAGE}`);
71
+ process.exit(64);
72
+ }
73
+ const configPath = resolveConfigPath({ flag: /** @type {string | undefined} */ (flags.config) });
74
+ let config;
75
+ try {
76
+ config = loadConfig(configPath);
77
+ } catch (e) {
78
+ if (e instanceof ConfigError) {
79
+ process.stderr.write(`mcp-patchbay: ${e.message}\n`);
80
+ process.exit(EX_CONFIG);
81
+ }
82
+ throw e;
83
+ }
84
+
85
+ // From here on the patchbay must never die from a child's misbehaviour.
86
+ process.on('uncaughtException', (err) => log.error(`uncaught exception: ${err?.stack ?? err}`));
87
+ process.on('unhandledRejection', (reason) => log.error(`unhandled rejection: ${/** @type {any} */ (reason)?.stack ?? reason}`));
88
+
89
+ const pidFiles = new PidFiles(pidDirFor(process.env), log);
90
+ try {
91
+ pidFiles.reap();
92
+ } catch (e) {
93
+ log.warn(`reaping leftovers failed: ${/** @type {Error} */ (e).message}`);
94
+ }
95
+
96
+ const patchbay = new Patchbay(config, { log, pidFiles });
97
+ let down = false;
98
+ const shutdown = (why) => {
99
+ if (down) return;
100
+ down = true;
101
+ patchbay.shutdownSync();
102
+ log.debug(`shut down (${why})`);
103
+ process.exit(0);
104
+ };
105
+ const signals = process.platform === 'win32' ? ['SIGINT', 'SIGTERM', 'SIGBREAK'] : ['SIGINT', 'SIGTERM', 'SIGHUP'];
106
+ for (const sig of signals) process.on(sig, () => shutdown(sig));
107
+ process.stdin.on('end', () => shutdown('stdin end'));
108
+ process.stdin.on('close', () => shutdown('stdin closed'));
109
+ process.stdout.on('error', (e) => {
110
+ if (/** @type {any} */ (e).code === 'EPIPE') shutdown('stdout closed');
111
+ });
112
+
113
+ const transport = new StdioServerTransport();
114
+ await patchbay.connect(transport);
115
+ log.info(`serving ${config.order.length} server(s) from ${configPath}`);
116
+ }
117
+
118
+ async function main() {
119
+ const argv = process.argv.slice(2);
120
+ const cmd = argv[0];
121
+ if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
122
+ process.stdout.write(USAGE);
123
+ return;
124
+ }
125
+ if (cmd === '--version' || cmd === '-v') {
126
+ process.stdout.write(`${VERSION}\n`);
127
+ return;
128
+ }
129
+ if (cmd === 'import') {
130
+ const { runImport } = await import('./import.js');
131
+ process.exitCode = await runImport(argv.slice(1));
132
+ return;
133
+ }
134
+ if (cmd === 'doctor') {
135
+ const { runDoctor } = await import('./doctor.js');
136
+ process.exitCode = await runDoctor(argv.slice(1));
137
+ return;
138
+ }
139
+ if (cmd === 'rename-permissions') {
140
+ const { runRenamePermissions } = await import('./rename-permissions.js');
141
+ process.exitCode = await runRenamePermissions(argv.slice(1));
142
+ return;
143
+ }
144
+ if (cmd && !cmd.startsWith('--')) {
145
+ process.stderr.write(`mcp-patchbay: unknown command "${cmd}"\n\n${USAGE}`);
146
+ process.exitCode = 64;
147
+ return;
148
+ }
149
+ await serve(argv);
150
+ }
151
+
152
+ main().catch((e) => {
153
+ process.stderr.write(`mcp-patchbay: ${redact(/** @type {Error} */ (e)?.stack ?? e)}\n`);
154
+ process.exit(1);
155
+ });