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/config.js ADDED
@@ -0,0 +1,465 @@
1
+ // Config location, strict validation and the permission check. See SPEC.md §2.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { isValidSegment } from './naming.js';
6
+
7
+ export const EX_CONFIG = 78;
8
+ export const MAX_TIMEOUT_MS = 2147483647;
9
+
10
+ export class ConfigError extends Error {
11
+ /** @param {string} message */
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = 'ConfigError';
15
+ this.exitCode = EX_CONFIG;
16
+ }
17
+ }
18
+
19
+ /**
20
+ * @typedef {'allow'|'confirm'|'deny'} Policy
21
+ * @typedef {{
22
+ * name: string, segment: string, kind: 'stdio'|'url', description: string, policy: Policy,
23
+ * command?: string, args: string[], env: Record<string,string>, cwd?: string,
24
+ * url?: string, headers: Record<string,string>, prefix?: string, timeoutMs: number
25
+ * }} ServerEntry
26
+ * @typedef {'elicitation'|'host'} ConfirmVia
27
+ * @typedef {{
28
+ * version: 1, confirmVia: ConfirmVia, order: string[], servers: Record<string, ServerEntry>,
29
+ * autostart: {default: string[], projects: Record<string, string[]>},
30
+ * oauth: {configDir: string, authTimeoutSeconds: number}
31
+ * }} Config
32
+ */
33
+
34
+ /** @param {string} [home] */
35
+ export function defaultConfigPath(home = os.homedir()) {
36
+ return path.join(home, '.config', 'mcp-patchbay', 'servers.json');
37
+ }
38
+
39
+ /**
40
+ * @param {{flag?: string, env?: NodeJS.ProcessEnv}} o
41
+ */
42
+ export function resolveConfigPath({ flag, env = process.env }) {
43
+ if (flag) return flag;
44
+ if (env.MCP_PATCHBAY_CONFIG) return env.MCP_PATCHBAY_CONFIG;
45
+ return defaultConfigPath();
46
+ }
47
+
48
+ /** @param {string} p */
49
+ export function expandHome(p) {
50
+ if (p === '~') return os.homedir();
51
+ if (p.startsWith('~/') || p.startsWith('~\\')) return path.join(os.homedir(), p.slice(2));
52
+ return p;
53
+ }
54
+
55
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
56
+ const where = (p) => (p ? p : '(root)');
57
+
58
+ /**
59
+ * @param {Record<string, unknown>} obj
60
+ * @param {string[]} allowed
61
+ * @param {string} at
62
+ */
63
+ function onlyKeys(obj, allowed, at) {
64
+ for (const k of Object.keys(obj)) {
65
+ if (!allowed.includes(k)) {
66
+ throw new ConfigError(`unknown key "${k}" at ${where(at)} (allowed: ${allowed.join(', ')})`);
67
+ }
68
+ }
69
+ }
70
+
71
+ /** @param {unknown} v @param {string} at */
72
+ function stringMap(v, at, keyRe, keyWhat) {
73
+ if (!isObj(v)) throw new ConfigError(`${at} must be an object of strings`);
74
+ /** @type {Record<string,string>} */
75
+ const out = {};
76
+ for (const [k, val] of Object.entries(/** @type {object} */ (v))) {
77
+ if (!keyRe.test(k)) throw new ConfigError(`${keyWhat} "${k}" at ${at} is not valid`);
78
+ if (typeof val !== 'string') throw new ConfigError(`${at}.${k} must be a string`);
79
+ // defineProperty, not out[k] = …: a key "__proto__" must stay a key, not set the prototype.
80
+ Object.defineProperty(out, k, { value: val, enumerable: true, writable: true, configurable: true });
81
+ }
82
+ return out;
83
+ }
84
+
85
+ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
86
+ const HEADER_KEY = /^[A-Za-z0-9_-]+$/; // mcp-remote 0.15.2 parseHeaderLine
87
+ const SERVER_KEYS = ['description', 'policy', 'command', 'args', 'env', 'cwd', 'url', 'headers', 'prefix', 'timeoutMs'];
88
+ const POLICIES = ['allow', 'confirm', 'deny'];
89
+ export const CONFIRM_VIA = ['elicitation', 'host'];
90
+
91
+ /**
92
+ * @param {string} name
93
+ * @param {any} raw
94
+ * @returns {ServerEntry}
95
+ */
96
+ function validateServer(name, raw) {
97
+ const at = `servers.${name}`;
98
+ if (!isValidSegment(name)) {
99
+ throw new ConfigError(`server name "${name}" is not valid: use 1-64 of [A-Za-z0-9_-], no "__", and no trailing "_"`);
100
+ }
101
+ if (!isObj(raw)) throw new ConfigError(`${at} must be an object`);
102
+ onlyKeys(raw, SERVER_KEYS, at);
103
+ const hasCommand = raw.command !== undefined;
104
+ const hasUrl = raw.url !== undefined;
105
+ if (hasCommand === hasUrl) throw new ConfigError(`${at} must have exactly one of command or url`);
106
+
107
+ const description = raw.description ?? '';
108
+ if (typeof description !== 'string') throw new ConfigError(`${at}.description must be a string`);
109
+ if (/[\r\n]/.test(description)) throw new ConfigError(`${at}.description must be one line`);
110
+ if (description.length > 300) throw new ConfigError(`${at}.description must be at most 300 characters`);
111
+
112
+ const policy = raw.policy ?? 'confirm';
113
+ if (!POLICIES.includes(policy)) throw new ConfigError(`${at}.policy must be one of ${POLICIES.join(', ')}`);
114
+
115
+ const timeoutMs = raw.timeoutMs ?? 0;
116
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMEOUT_MS) {
117
+ throw new ConfigError(`${at}.timeoutMs must be an integer from 0 (no cap) to ${MAX_TIMEOUT_MS}`);
118
+ }
119
+
120
+ let prefix;
121
+ if (raw.prefix !== undefined) {
122
+ if (!isValidSegment(raw.prefix)) {
123
+ throw new ConfigError(`${at}.prefix "${raw.prefix}" is not valid: use 1-64 of [A-Za-z0-9_-], no "__", and no trailing "_"`);
124
+ }
125
+ prefix = raw.prefix;
126
+ }
127
+
128
+ const env = raw.env === undefined ? {} : stringMap(raw.env, `${at}.env`, ENV_KEY, 'env key');
129
+
130
+ /** @type {ServerEntry} */
131
+ const entry = {
132
+ name,
133
+ segment: prefix ?? name,
134
+ kind: hasCommand ? 'stdio' : 'url',
135
+ description,
136
+ policy,
137
+ args: [],
138
+ env,
139
+ headers: {},
140
+ timeoutMs,
141
+ };
142
+ if (prefix) entry.prefix = prefix;
143
+
144
+ if (hasCommand) {
145
+ if (typeof raw.command !== 'string' || !raw.command) throw new ConfigError(`${at}.command must be a non-empty string`);
146
+ if (raw.headers !== undefined) throw new ConfigError(`${at}.headers applies only to url servers`);
147
+ entry.command = raw.command;
148
+ if (raw.args !== undefined) {
149
+ if (!Array.isArray(raw.args) || !raw.args.every((a) => typeof a === 'string')) {
150
+ throw new ConfigError(`${at}.args must be an array of strings`);
151
+ }
152
+ entry.args = [...raw.args];
153
+ }
154
+ if (raw.cwd !== undefined) {
155
+ if (typeof raw.cwd !== 'string' || !(path.isAbsolute(raw.cwd) || path.win32.isAbsolute(raw.cwd))) {
156
+ throw new ConfigError(`${at}.cwd must be an absolute path`);
157
+ }
158
+ entry.cwd = raw.cwd;
159
+ }
160
+ } else {
161
+ if (raw.args !== undefined) throw new ConfigError(`${at}.args applies only to command servers`);
162
+ if (raw.cwd !== undefined) throw new ConfigError(`${at}.cwd applies only to command servers`);
163
+ if (typeof raw.url !== 'string') throw new ConfigError(`${at}.url must be a string`);
164
+ let u;
165
+ try {
166
+ u = new URL(raw.url);
167
+ } catch {
168
+ throw new ConfigError(`${at}.url must be an absolute http(s) URL`);
169
+ }
170
+ const loopback = u.hostname === 'localhost' || u.hostname === '127.0.0.1';
171
+ if (!(u.protocol === 'https:' || (u.protocol === 'http:' && loopback))) {
172
+ throw new ConfigError(`${at}.url must use https (plain http is only allowed for localhost and 127.0.0.1)`);
173
+ }
174
+ entry.url = raw.url;
175
+ if (raw.headers !== undefined) {
176
+ entry.headers = stringMap(raw.headers, `${at}.headers`, HEADER_KEY, 'header name');
177
+ for (const [k, v] of Object.entries(entry.headers)) {
178
+ if (/[\r\n]/.test(v)) throw new ConfigError(`${at}.headers.${k} must not contain line breaks`);
179
+ }
180
+ }
181
+ }
182
+ return entry;
183
+ }
184
+
185
+ /**
186
+ * Validates a parsed config strictly and returns a normalised copy.
187
+ * @param {any} raw
188
+ * @returns {Config}
189
+ */
190
+ export function validateConfig(raw) {
191
+ if (!isObj(raw)) throw new ConfigError('the config must be a JSON object');
192
+ onlyKeys(raw, ['version', 'confirmVia', 'servers', 'autostart', 'oauth'], '');
193
+ if (raw.version !== 1) throw new ConfigError('version must be 1');
194
+ const confirmVia = raw.confirmVia === undefined ? 'elicitation' : raw.confirmVia;
195
+ if (!CONFIRM_VIA.includes(confirmVia)) throw new ConfigError(`confirmVia must be one of ${CONFIRM_VIA.join(', ')}`);
196
+ if (raw.servers === undefined) throw new ConfigError('servers is required');
197
+ if (!isObj(raw.servers)) throw new ConfigError('servers must be an object');
198
+
199
+ /** @type {Record<string, ServerEntry>} */
200
+ const servers = {};
201
+ const order = [];
202
+ /** @type {Map<string, string>} */
203
+ const segments = new Map();
204
+ for (const [name, entry] of Object.entries(raw.servers)) {
205
+ const s = validateServer(name, entry);
206
+ const key = s.segment.toLowerCase();
207
+ const other = segments.get(key);
208
+ if (other !== undefined) {
209
+ throw new ConfigError(`servers.${name}: tool-name segment "${s.segment}" is already used by server "${other}" (names and prefixes must be unique, ignoring case)`);
210
+ }
211
+ segments.set(key, name);
212
+ servers[name] = s;
213
+ order.push(name);
214
+ }
215
+
216
+ const autostart = { default: /** @type {string[]} */ ([]), projects: /** @type {Record<string,string[]>} */ ({}) };
217
+ if (raw.autostart !== undefined) {
218
+ if (!isObj(raw.autostart)) throw new ConfigError('autostart must be an object');
219
+ onlyKeys(raw.autostart, ['default', 'projects'], 'autostart');
220
+ const names = (v, at) => {
221
+ if (!Array.isArray(v) || !v.every((x) => typeof x === 'string')) throw new ConfigError(`${at} must be an array of server names`);
222
+ for (const n of v) {
223
+ // hasOwn: "constructor", "toString" and "__proto__" are inherited, not configured servers.
224
+ if (!Object.hasOwn(servers, n)) throw new ConfigError(`${at} names unknown server "${n}"`);
225
+ if (servers[n].policy === 'deny') throw new ConfigError(`${at} names "${n}", whose policy is deny`);
226
+ }
227
+ return [...new Set(v)];
228
+ };
229
+ if (raw.autostart.default !== undefined) autostart.default = names(raw.autostart.default, 'autostart.default');
230
+ if (raw.autostart.projects !== undefined) {
231
+ if (!isObj(raw.autostart.projects)) throw new ConfigError('autostart.projects must be an object');
232
+ for (const [dir, list] of Object.entries(raw.autostart.projects)) {
233
+ if (!(path.isAbsolute(dir) || path.win32.isAbsolute(dir))) {
234
+ throw new ConfigError(`autostart.projects key "${dir}" must be an absolute path`);
235
+ }
236
+ autostart.projects[dir] = names(list, `autostart.projects["${dir}"]`);
237
+ }
238
+ }
239
+ }
240
+
241
+ const oauth = { configDir: expandHome('~/.config/mcp-patchbay/oauth'), authTimeoutSeconds: 300 };
242
+ if (raw.oauth !== undefined) {
243
+ if (!isObj(raw.oauth)) throw new ConfigError('oauth must be an object');
244
+ onlyKeys(raw.oauth, ['configDir', 'authTimeoutSeconds'], 'oauth');
245
+ if (raw.oauth.configDir !== undefined) {
246
+ if (typeof raw.oauth.configDir !== 'string' || !raw.oauth.configDir) throw new ConfigError('oauth.configDir must be a path');
247
+ const dir = expandHome(raw.oauth.configDir);
248
+ if (!(path.isAbsolute(dir) || path.win32.isAbsolute(dir))) throw new ConfigError('oauth.configDir must be absolute (or start with ~)');
249
+ oauth.configDir = dir;
250
+ }
251
+ if (raw.oauth.authTimeoutSeconds !== undefined) {
252
+ const t = raw.oauth.authTimeoutSeconds;
253
+ if (!Number.isInteger(t) || t < 1 || t > 86400) throw new ConfigError('oauth.authTimeoutSeconds must be an integer from 1 to 86400');
254
+ oauth.authTimeoutSeconds = t;
255
+ }
256
+ }
257
+
258
+ return { version: 1, confirmVia, order, servers, autostart, oauth };
259
+ }
260
+
261
+ /**
262
+ * Refuses a config file that someone else could have rewritten (POSIX only).
263
+ * @param {string} file
264
+ * @param {fs.Stats} st
265
+ */
266
+ export function checkFilePermissions(file, st) {
267
+ if (process.platform === 'win32') return;
268
+ if (st.mode & 0o022) {
269
+ throw new ConfigError(
270
+ `refusing to start: ${file} is group- or world-writable (mode ${(st.mode & 0o777).toString(8)}). ` +
271
+ `The config decides which programs run, so only you may be able to change it. Fix it with: chmod 600 ${file}`,
272
+ );
273
+ }
274
+ const uid = process.getuid?.();
275
+ if (uid !== undefined && st.uid !== uid && st.uid !== 0) {
276
+ throw new ConfigError(`refusing to start: ${file} is owned by uid ${st.uid}, not by you (uid ${uid}) or root.`);
277
+ }
278
+ }
279
+
280
+ /**
281
+ * The offset of the first JSON syntax error in `text`, or -1 if it is valid JSON. Used to report
282
+ * a location without quoting the text: V8's own message ("Unexpected token 'g', ..."B_TOKEN":
283
+ * ghp_abc"... is not valid JSON") includes a snippet of the file, which may hold a secret.
284
+ * @param {string} text
285
+ * @returns {number}
286
+ */
287
+ export function jsonErrorPosition(text) {
288
+ let i = 0;
289
+ const n = text.length;
290
+ const stop = {};
291
+ const fail = () => { throw stop; };
292
+ const ws = () => { while (i < n && ' \t\n\r'.includes(text[i])) i++; };
293
+ const str = () => {
294
+ i++;
295
+ while (i < n) {
296
+ const c = text[i];
297
+ if (c === '"') { i++; return; }
298
+ if (c < ' ') fail();
299
+ if (c === '\\') {
300
+ const e = text[i + 1];
301
+ if (e !== undefined && '"\\/bfnrt'.includes(e)) i += 2;
302
+ else if (e === 'u' && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) i += 6;
303
+ else { i++; fail(); }
304
+ } else i++;
305
+ }
306
+ fail();
307
+ };
308
+ const NUM = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
309
+ const value = () => {
310
+ ws();
311
+ const c = text[i];
312
+ if (c === '{' || c === '[') {
313
+ const close = c === '{' ? '}' : ']';
314
+ i++;
315
+ ws();
316
+ if (text[i] === close) { i++; return; }
317
+ for (;;) {
318
+ if (c === '{') {
319
+ ws();
320
+ if (text[i] !== '"') fail();
321
+ str();
322
+ ws();
323
+ if (text[i] !== ':') fail();
324
+ i++;
325
+ }
326
+ value();
327
+ ws();
328
+ if (text[i] === ',') { i++; continue; }
329
+ if (text[i] === close) { i++; return; }
330
+ fail();
331
+ }
332
+ }
333
+ if (c === '"') return str();
334
+ for (const word of ['true', 'false', 'null']) {
335
+ if (c === word[0]) {
336
+ for (const ch of word) { if (text[i] !== ch) fail(); i++; }
337
+ return;
338
+ }
339
+ }
340
+ NUM.lastIndex = i;
341
+ if (!NUM.exec(text)) fail();
342
+ i = NUM.lastIndex;
343
+ };
344
+ try {
345
+ value();
346
+ ws();
347
+ if (i < n) fail();
348
+ return -1;
349
+ } catch (e) {
350
+ if (e === stop) return i;
351
+ return -1; // too deeply nested to scan
352
+ }
353
+ }
354
+
355
+ /**
356
+ * "<what> is not valid JSON (line L, column C)", without quoting any of the text.
357
+ * @param {string} what e.g. "config /path/to/servers.json"
358
+ * @param {string} text
359
+ */
360
+ export function jsonSyntaxMessage(what, text) {
361
+ const pos = jsonErrorPosition(text);
362
+ if (pos < 0) return `${what} is not valid JSON`;
363
+ const before = text.slice(0, pos);
364
+ const line = before.split('\n').length;
365
+ const column = pos - before.lastIndexOf('\n');
366
+ return `${what} is not valid JSON (line ${line}, column ${column})`;
367
+ }
368
+
369
+ /**
370
+ * Refuses a directory holding the config (or the file a config symlink points to) that someone
371
+ * else could change: group- or world-writable (sticky or not), or owned by someone other than
372
+ * you or root. Whoever can write the directory can replace the file (POSIX only).
373
+ * @param {string} file the config path, for the message
374
+ * @param {string} dir
375
+ */
376
+ export function checkDirPermissions(file, dir) {
377
+ if (process.platform === 'win32') return;
378
+ let st;
379
+ try {
380
+ st = fs.statSync(dir);
381
+ } catch (e) {
382
+ throw new ConfigError(`cannot check the directory of config ${file}: ${/** @type {any} */ (e).code ?? e}`);
383
+ }
384
+ if (st.mode & 0o022) {
385
+ throw new ConfigError(
386
+ `refusing to start: the directory ${dir} holding config ${file} is group- or world-writable ` +
387
+ `(mode ${(st.mode & 0o7777).toString(8)}), so someone else could replace the config. ` +
388
+ `Fix it with: chmod go-w ${dir}, or move the config to a directory only you can write.`,
389
+ );
390
+ }
391
+ const uid = process.getuid?.();
392
+ if (uid !== undefined && st.uid !== uid && st.uid !== 0) {
393
+ throw new ConfigError(`refusing to start: the directory ${dir} holding config ${file} is owned by uid ${st.uid}, not by you (uid ${uid}) or root.`);
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Reads, checks and validates the config file once. The file is opened once and the checks and
399
+ * the read use that descriptor, so it cannot be swapped between check and read. A symlink is
400
+ * followed; then its target must pass the same checks, and so must the directories holding the
401
+ * link and the target (DECISIONS.md).
402
+ * @param {string} file
403
+ * @returns {Config}
404
+ */
405
+ export function loadConfig(file) {
406
+ const posix = process.platform !== 'win32';
407
+ let fd;
408
+ try {
409
+ // O_NONBLOCK: opening a FIFO must not hang startup; it is refused below as not a regular file.
410
+ fd = fs.openSync(file, posix ? fs.constants.O_RDONLY | fs.constants.O_NONBLOCK : 'r');
411
+ } catch (e) {
412
+ throw new ConfigError(`cannot read config ${file}: ${/** @type {any} */ (e).code ?? e}. Create it (see examples/servers.json) or pass --config <path>.`);
413
+ }
414
+ let text;
415
+ try {
416
+ const st = fs.fstatSync(fd);
417
+ if (!st.isFile()) throw new ConfigError(`config ${file} is not a regular file`);
418
+ checkFilePermissions(file, st);
419
+ if (posix) {
420
+ const dirs = new Set([path.dirname(path.resolve(file))]);
421
+ if (fs.lstatSync(file).isSymbolicLink()) dirs.add(path.dirname(fs.realpathSync(file)));
422
+ for (const dir of dirs) checkDirPermissions(file, dir);
423
+ }
424
+ try {
425
+ text = fs.readFileSync(fd, 'utf8');
426
+ } catch (e) {
427
+ throw new ConfigError(`cannot read config ${file}: ${/** @type {any} */ (e).code ?? e}`);
428
+ }
429
+ } finally {
430
+ fs.closeSync(fd);
431
+ }
432
+ let raw;
433
+ try {
434
+ raw = JSON.parse(text);
435
+ } catch {
436
+ // Never e.message: V8 quotes the text around the error, which may be a secret.
437
+ throw new ConfigError(jsonSyntaxMessage(`config ${file}`, text));
438
+ }
439
+ try {
440
+ return validateConfig(raw);
441
+ } catch (e) {
442
+ if (e instanceof ConfigError) e.message = `config ${file}: ${e.message}`;
443
+ throw e;
444
+ }
445
+ }
446
+
447
+ /** @param {string} p */
448
+ function normDir(p) {
449
+ let r = path.resolve(p);
450
+ if (process.platform === 'win32') r = r.toLowerCase();
451
+ return r;
452
+ }
453
+
454
+ /**
455
+ * The servers to autostart for a project directory.
456
+ * @param {Config} config
457
+ * @param {string} projectDir
458
+ */
459
+ export function autostartFor(config, projectDir) {
460
+ const want = normDir(projectDir);
461
+ for (const [dir, list] of Object.entries(config.autostart.projects)) {
462
+ if (normDir(dir) === want) return [...list];
463
+ }
464
+ return [...config.autostart.default];
465
+ }
package/src/doctor.js ADDED
@@ -0,0 +1,124 @@
1
+ // `mcp-patchbay doctor`: validate the config, check Claude Code's allow rules against
2
+ // enable_confirm, and briefly start servers. See SPEC.md §10.
3
+ import path from 'node:path';
4
+ import { Child } from './children.js';
5
+ import { ConfigError, EX_CONFIG, loadConfig, resolveConfigPath } from './config.js';
6
+ import { createLogger } from './log.js';
7
+ import { ENABLE_CONFIRM_CLIENT_NAME, scanSettings, settingsFiles } from './permissions.js';
8
+ import { PidFiles, pidDirFor } from './process.js';
9
+ import { redact } from './redact.js';
10
+
11
+ const STDIO_BUDGET_MS = 60000;
12
+
13
+ /**
14
+ * Prints what in Claude Code's settings would approve enable_confirm without asking the person.
15
+ * @param {import('./config.js').Config} config
16
+ * @param {string | undefined} project
17
+ * @param {(s: string) => void} out
18
+ * @returns {number} how many findings would weaken a confirm (counted only with confirmVia "host")
19
+ */
20
+ function checkPermissions(config, project, out) {
21
+ const host = config.confirmVia === 'host';
22
+ out(`confirmVia: ${config.confirmVia}${host ? ` (confirm servers are turned on with ${ENABLE_CONFIRM_CLIENT_NAME}, approved in the host's permission prompt)` : ''}\n`);
23
+ let findings = 0;
24
+ const label = host ? 'warning' : 'note';
25
+ const why = host
26
+ ? 'the host would run it without asking, so a confirm server would start with no person approving'
27
+ : 'harmless while confirmVia is elicitation, but it would approve enable_confirm without asking if you switch to host';
28
+ for (const r of scanSettings(settingsFiles({ project }))) {
29
+ if (r.status === 'missing') {
30
+ out(`permissions: ${r.file}: not found\n`);
31
+ continue;
32
+ }
33
+ if (r.status === 'unreadable') {
34
+ out(`permissions: ${r.file}: ${r.error}; not checked\n`);
35
+ if (host) findings++;
36
+ continue;
37
+ }
38
+ if (!r.rules.length && !r.bypass) {
39
+ out(`permissions: ${r.file}: ok, no allow rule matches ${ENABLE_CONFIRM_CLIENT_NAME}\n`);
40
+ continue;
41
+ }
42
+ for (const rule of r.rules) {
43
+ out(`permissions: ${label}: ${r.file}: allow rule "${rule}" matches ${ENABLE_CONFIRM_CLIENT_NAME}; ${why}. Remove it, or allow individual tools instead.\n`);
44
+ }
45
+ if (r.bypass) {
46
+ out(`permissions: ${label}: ${r.file}: permissions.defaultMode is bypassPermissions, which approves every tool, ${ENABLE_CONFIRM_CLIENT_NAME} included, without asking.\n`);
47
+ }
48
+ if (host) findings += r.rules.length + (r.bypass ? 1 : 0);
49
+ }
50
+ return findings;
51
+ }
52
+
53
+ /**
54
+ * @param {string[]} argv
55
+ * @param {{out?: (s: string) => void, err?: (s: string) => void}} [io]
56
+ * @returns {Promise<number>} exit code
57
+ */
58
+ export async function runDoctor(argv, io = {}) {
59
+ const out = io.out ?? ((s) => process.stdout.write(s));
60
+ const err = io.err ?? ((s) => process.stderr.write(s));
61
+ let configFlag;
62
+ let project;
63
+ let all = false;
64
+ let start = true;
65
+ for (let i = 0; i < argv.length; i++) {
66
+ if (argv[i] === '--all') all = true;
67
+ else if (argv[i] === '--no-start') start = false;
68
+ else if (argv[i] === '--config' && argv[i + 1] !== undefined) configFlag = argv[++i];
69
+ else if (argv[i].startsWith('--config=')) configFlag = argv[i].slice(9);
70
+ else if (argv[i] === '--project' && argv[i + 1] !== undefined) project = argv[++i];
71
+ else if (argv[i].startsWith('--project=')) project = argv[i].slice(10);
72
+ else {
73
+ err(`doctor: unknown argument ${argv[i]}\n`);
74
+ return 64;
75
+ }
76
+ }
77
+ if (project !== undefined) project = path.resolve(project);
78
+ const configPath = resolveConfigPath({ flag: configFlag });
79
+ let config;
80
+ try {
81
+ config = loadConfig(configPath);
82
+ } catch (e) {
83
+ if (e instanceof ConfigError) {
84
+ err(`mcp-patchbay doctor: ${e.message}\n`);
85
+ return EX_CONFIG;
86
+ }
87
+ throw e;
88
+ }
89
+ out(`config ok: ${configPath} (${config.order.length} servers)\n`);
90
+ const findings = checkPermissions(config, project, out);
91
+ if (!start) return findings ? 1 : 0;
92
+
93
+ // Child chatter goes to stderr only with MCP_PATCHBAY_DEBUG=1.
94
+ const log = createLogger({ write: (s) => err(s) });
95
+ const pidFiles = new PidFiles(pidDirFor(process.env), log);
96
+ let failed = 0;
97
+ for (const name of config.order) {
98
+ const entry = config.servers[name];
99
+ if (entry.policy === 'deny') {
100
+ out(`${name}: skipped (policy deny)\n`);
101
+ continue;
102
+ }
103
+ if (entry.policy === 'confirm' && !all) {
104
+ out(`${name}: skipped (policy confirm; use --all)\n`);
105
+ continue;
106
+ }
107
+ const child = new Child({ entry, oauth: config.oauth, clientCapabilities: {}, log, pidFiles });
108
+ child.on('auth-url', () => err(`${name}: needs a sign-in; mcp-remote should open your browser (waiting up to ${config.oauth.authTimeoutSeconds} s)\n`));
109
+ const budget = entry.kind === 'url' ? config.oauth.authTimeoutSeconds * 1000 + 60000 : STDIO_BUDGET_MS;
110
+ try {
111
+ await child.start(budget);
112
+ const tools = await child.listTools(budget);
113
+ out(`${name}: ok, ${tools.length} tool${tools.length === 1 ? '' : 's'}\n`);
114
+ } catch (e) {
115
+ failed++;
116
+ const last = child.stderrTail(1)[0];
117
+ const why = String(/** @type {any} */ (e)?.code === 'ENOENT' ? 'command not found (ENOENT)' : /** @type {Error} */ (e)?.message ?? e).replace(/^MCP error -?\d+: /, '');
118
+ out(`${name}: failed: ${redact(last ? `${why}; first stderr: ${child.stderrTail(20)[0]}` : why, child.secrets)}\n`);
119
+ } finally {
120
+ await child.close().catch(() => {});
121
+ }
122
+ }
123
+ return failed || findings ? 1 : 0;
124
+ }
package/src/fsutil.js ADDED
@@ -0,0 +1,55 @@
1
+ // Small file helpers shared by import and rename-permissions.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ /** A UTC timestamp usable in a file name. */
6
+ export function stamp(d = new Date()) {
7
+ return d.toISOString().replace(/[:.]/g, '-');
8
+ }
9
+
10
+ /**
11
+ * Copies `file` to `<file>.bak-<timestamp>` and returns the backup path, or null if `file`
12
+ * does not exist.
13
+ * @param {string} file
14
+ * @param {number} [mode] mode for the backup (default: the original's)
15
+ */
16
+ export function backup(file, mode) {
17
+ if (!fs.existsSync(file)) return null;
18
+ const st = fs.statSync(file);
19
+ let bak = `${file}.bak-${stamp()}`;
20
+ for (let i = 1; fs.existsSync(bak); i++) bak = `${file}.bak-${stamp()}-${i}`;
21
+ fs.copyFileSync(file, bak, fs.constants.COPYFILE_EXCL);
22
+ if (process.platform !== 'win32') fs.chmodSync(bak, mode ?? (st.mode & 0o777));
23
+ return bak;
24
+ }
25
+
26
+ /**
27
+ * Writes `content` atomically (temp file + rename) with the given mode. A symlink is written
28
+ * through (dotfile managers link settings files), not replaced, and the temp file never outlives
29
+ * a failure.
30
+ * @param {string} file
31
+ * @param {string} content
32
+ * @param {number} mode
33
+ */
34
+ export function writeAtomic(file, content, mode) {
35
+ let target = file;
36
+ try {
37
+ if (fs.lstatSync(file).isSymbolicLink()) target = fs.realpathSync(file);
38
+ } catch { /* a new file, or a dangling link: write the path itself */ }
39
+ const dir = path.dirname(target);
40
+ const tmp = path.join(dir, `.${path.basename(target)}.${process.pid}.${Date.now()}.tmp`);
41
+ const fd = fs.openSync(tmp, 'wx', mode);
42
+ try {
43
+ try {
44
+ fs.writeSync(fd, content);
45
+ fs.fsyncSync(fd);
46
+ } finally {
47
+ fs.closeSync(fd);
48
+ }
49
+ if (process.platform !== 'win32') fs.chmodSync(tmp, mode);
50
+ fs.renameSync(tmp, target);
51
+ } catch (e) {
52
+ try { fs.rmSync(tmp, { force: true }); } catch { /* best effort */ }
53
+ throw e;
54
+ }
55
+ }