mcp-patchbay 0.0.0-stage → 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/CHANGELOG.md +103 -0
- package/LICENSE +201 -0
- package/NOTICE +8 -0
- package/README.md +376 -2
- package/SECURITY-MODEL.md +229 -0
- package/SECURITY.md +26 -0
- package/examples/servers.json +54 -0
- package/package.json +47 -4
- package/src/children.js +521 -0
- package/src/cli.js +155 -0
- package/src/config.js +465 -0
- package/src/doctor.js +124 -0
- package/src/fsutil.js +55 -0
- package/src/import.js +168 -0
- package/src/instructions.js +88 -0
- package/src/log.js +22 -0
- package/src/naming.js +96 -0
- package/src/permissions.js +72 -0
- package/src/process.js +367 -0
- package/src/redact.js +132 -0
- package/src/rename-permissions.js +158 -0
- package/src/server.js +864 -0
- package/src/version.js +4 -0
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
|
+
}
|
package/src/import.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// `mcp-patchbay import`: build servers.json from a Claude Code config. See SPEC.md §10.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { defaultConfigPath, jsonSyntaxMessage, validateConfig } from './config.js';
|
|
5
|
+
import { backup, writeAtomic } from './fsutil.js';
|
|
6
|
+
import { isValidSegment } from './naming.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @typedef {{name: string, reason: string}} Skip
|
|
10
|
+
* @typedef {{name: string, policy: string, kind: string}} Imported
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** @param {string} name */
|
|
14
|
+
function unhostable(name) {
|
|
15
|
+
if (name.startsWith('claude.ai ')) return 'a claude.ai connector; Claude Code hosts these itself';
|
|
16
|
+
if (name.startsWith('plugin:')) return 'a plugin server; Claude Code manages these itself';
|
|
17
|
+
if (name.startsWith('claude-in-chrome')) return 'claude-in-chrome is built into Claude Code';
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param {any} def */
|
|
22
|
+
function isSelf(def) {
|
|
23
|
+
const parts = [def?.command, ...(Array.isArray(def?.args) ? def.args : [])].filter((x) => typeof x === 'string');
|
|
24
|
+
return parts.some((p) => /mcp-patchbay/.test(p));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Converts one Claude Code server definition. Returns the entry or a reason to skip.
|
|
29
|
+
* @param {string} name
|
|
30
|
+
* @param {any} def
|
|
31
|
+
* @returns {{entry?: any, kind?: string, reason?: string}}
|
|
32
|
+
*/
|
|
33
|
+
function convert(name, def) {
|
|
34
|
+
const bad = unhostable(name);
|
|
35
|
+
if (bad) return { reason: bad };
|
|
36
|
+
if (!isValidSegment(name)) return { reason: 'name is not valid here (use [A-Za-z0-9_-], no "__", no trailing "_", at most 64)' };
|
|
37
|
+
if (!def || typeof def !== 'object') return { reason: 'definition is not an object' };
|
|
38
|
+
if (isSelf(def)) return { reason: 'this is mcp-patchbay itself' };
|
|
39
|
+
const type = def.type ?? (def.url ? 'http' : 'stdio');
|
|
40
|
+
if (type === 'http' || type === 'sse') {
|
|
41
|
+
if (typeof def.url !== 'string') return { reason: `type ${type} without a url` };
|
|
42
|
+
const entry = { description: `Imported from Claude Code (${type})`, url: def.url };
|
|
43
|
+
if (def.headers && Object.keys(def.headers).length) entry.headers = { ...def.headers };
|
|
44
|
+
return { entry, kind: type };
|
|
45
|
+
}
|
|
46
|
+
if (type === 'stdio') {
|
|
47
|
+
if (typeof def.command !== 'string' || !def.command) return { reason: 'stdio without a command' };
|
|
48
|
+
/** @type {any} */
|
|
49
|
+
const entry = { description: 'Imported from Claude Code (stdio)', command: def.command };
|
|
50
|
+
if (Array.isArray(def.args) && def.args.length) entry.args = [...def.args];
|
|
51
|
+
if (def.env && Object.keys(def.env).length) entry.env = { ...def.env };
|
|
52
|
+
if (typeof def.cwd === 'string') entry.cwd = def.cwd;
|
|
53
|
+
return { entry, kind: 'stdio' };
|
|
54
|
+
}
|
|
55
|
+
return { reason: `transport type "${type}" is not supported` };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {{from: string, project?: string, out: string}} o
|
|
60
|
+
*/
|
|
61
|
+
export function importClaudeConfig(o) {
|
|
62
|
+
const text = fs.readFileSync(o.from, 'utf8');
|
|
63
|
+
let raw;
|
|
64
|
+
try {
|
|
65
|
+
raw = JSON.parse(text);
|
|
66
|
+
} catch {
|
|
67
|
+
// Never the parser's message: it quotes the text around the error (env values, tokens).
|
|
68
|
+
throw new Error(jsonSyntaxMessage(o.from, text));
|
|
69
|
+
}
|
|
70
|
+
/** @type {Record<string, any>} */
|
|
71
|
+
const defs = { ...(raw.mcpServers ?? {}) };
|
|
72
|
+
/** @type {string[]} */
|
|
73
|
+
let disabled = [];
|
|
74
|
+
if (o.project) {
|
|
75
|
+
const proj = raw.projects && Object.hasOwn(raw.projects, o.project) ? raw.projects[o.project] : undefined;
|
|
76
|
+
if (!proj) throw new Error(`project "${o.project}" not found in ${o.from}`);
|
|
77
|
+
Object.assign(defs, proj.mcpServers ?? {});
|
|
78
|
+
disabled = Array.isArray(proj.disabledMcpServers) ? proj.disabledMcpServers : [];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** @type {Record<string, any>} */
|
|
82
|
+
const servers = {};
|
|
83
|
+
/** @type {Skip[]} */
|
|
84
|
+
const skipped = [];
|
|
85
|
+
/** @type {Imported[]} */
|
|
86
|
+
const imported = [];
|
|
87
|
+
for (const [name, def] of Object.entries(defs)) {
|
|
88
|
+
const { entry, kind, reason } = convert(name, def);
|
|
89
|
+
if (!entry) {
|
|
90
|
+
skipped.push({ name, reason: /** @type {string} */ (reason) });
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const policy = disabled.includes(name) ? 'confirm' : 'allow';
|
|
94
|
+
const ordered = { description: entry.description, policy, ...entry };
|
|
95
|
+
// Each entry must validate on its own, so one odd server cannot sink the whole import.
|
|
96
|
+
try {
|
|
97
|
+
validateConfig({ version: 1, servers: { [name]: ordered } });
|
|
98
|
+
} catch (e) {
|
|
99
|
+
skipped.push({ name, reason: `not valid here: ${/** @type {Error} */ (e).message}` });
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
servers[name] = ordered;
|
|
103
|
+
imported.push({ name, policy, kind: /** @type {string} */ (kind) });
|
|
104
|
+
}
|
|
105
|
+
/** @type {any} */
|
|
106
|
+
// Claude Code shows its own permission prompt for every tool call, so confirm goes through it
|
|
107
|
+
// (enable_confirm); its form elicitation is not answered by a person in every Claude Code UI.
|
|
108
|
+
const config = { version: 1, confirmVia: 'host', servers, autostart: { default: [], projects: {} } };
|
|
109
|
+
if (o.project) {
|
|
110
|
+
config.autostart.projects[o.project] = imported.filter((i) => !disabled.includes(i.name)).map((i) => i.name);
|
|
111
|
+
}
|
|
112
|
+
validateConfig(config);
|
|
113
|
+
return { config, imported, skipped };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* @param {string[]} argv
|
|
118
|
+
* @returns {Promise<number>}
|
|
119
|
+
*/
|
|
120
|
+
export async function runImport(argv) {
|
|
121
|
+
/** @type {Record<string, string>} */
|
|
122
|
+
const flags = {};
|
|
123
|
+
for (let i = 0; i < argv.length; i++) {
|
|
124
|
+
const a = argv[i];
|
|
125
|
+
if (['--from', '--project', '--out'].includes(a)) {
|
|
126
|
+
if (argv[i + 1] === undefined) {
|
|
127
|
+
process.stderr.write(`import: ${a} needs a value\n`);
|
|
128
|
+
return 64;
|
|
129
|
+
}
|
|
130
|
+
flags[a.slice(2)] = argv[++i];
|
|
131
|
+
} else {
|
|
132
|
+
process.stderr.write(`import: unknown argument ${a}\nUsage: mcp-patchbay import --from <claude.json> [--project <dir>] [--out <servers.json>]\n`);
|
|
133
|
+
return 64;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!flags.from) {
|
|
137
|
+
process.stderr.write('import: --from <claude.json> is required (usually ~/.claude.json)\n');
|
|
138
|
+
return 64;
|
|
139
|
+
}
|
|
140
|
+
const out = path.resolve(flags.out ?? defaultConfigPath());
|
|
141
|
+
let result;
|
|
142
|
+
try {
|
|
143
|
+
result = importClaudeConfig({ from: flags.from, project: flags.project, out });
|
|
144
|
+
} catch (e) {
|
|
145
|
+
process.stderr.write(`import: ${/** @type {Error} */ (e).message}\n`);
|
|
146
|
+
return 1;
|
|
147
|
+
}
|
|
148
|
+
const dir = path.dirname(out);
|
|
149
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
150
|
+
const bak = backup(out, 0o600);
|
|
151
|
+
writeAtomic(out, JSON.stringify(result.config, null, 2) + '\n', 0o600);
|
|
152
|
+
|
|
153
|
+
const lines = [];
|
|
154
|
+
lines.push(`Imported ${result.imported.length} server(s):`);
|
|
155
|
+
for (const i of result.imported) lines.push(` ${i.name} (${i.kind}, policy ${i.policy})`);
|
|
156
|
+
if (result.skipped.length) {
|
|
157
|
+
lines.push(`Skipped ${result.skipped.length}:`);
|
|
158
|
+
for (const s of result.skipped) lines.push(` ${s.name}: ${s.reason}`);
|
|
159
|
+
}
|
|
160
|
+
if (flags.project) {
|
|
161
|
+
lines.push(`Autostart for ${flags.project}: ${result.config.autostart.projects[flags.project].join(', ') || '(none)'}`);
|
|
162
|
+
}
|
|
163
|
+
lines.push('confirmVia: host (confirm servers are turned on with enable_confirm, which Claude Code asks you about; run mcp-patchbay doctor to check that no allow rule approves it)');
|
|
164
|
+
if (bak) lines.push(`Backed up the previous file to ${bak}`);
|
|
165
|
+
lines.push(`Wrote ${out} (mode 0600). Env and header values were copied but are not shown.`);
|
|
166
|
+
process.stdout.write(lines.join('\n') + '\n');
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// The patchbay's own `instructions` (initialize result). See SPEC.md §3.4.
|
|
2
|
+
|
|
3
|
+
export const MAX_INSTRUCTIONS = 4096;
|
|
4
|
+
const CATALOGUE_MAX = 3000;
|
|
5
|
+
const DESCRIPTION_MAX = 120;
|
|
6
|
+
const TRUNC = '…[truncated]';
|
|
7
|
+
|
|
8
|
+
const HEADER = [
|
|
9
|
+
'mcp-patchbay hosts the MCP servers listed below and can switch them on and off during the session.',
|
|
10
|
+
'Call `servers` for their current state, `enable` {name} to turn one on (its tools then appear as <server>__<tool>; some servers need a person to approve), and `disable` {name} to turn it off again. `info` {name} shows a server\'s own instructions.',
|
|
11
|
+
'Servers:',
|
|
12
|
+
].join('\n');
|
|
13
|
+
|
|
14
|
+
const HOST_HEADER = [
|
|
15
|
+
'mcp-patchbay hosts the MCP servers listed below and can switch them on and off during the session.',
|
|
16
|
+
'Call `servers` for their current state, `enable` {name} to turn on an allow server, or `enable_confirm` {name} to turn on a confirm server (the host asks the person first). Their tools then appear as <server>__<tool>. `disable` {name} turns one off again. `info` {name} shows a server\'s own instructions.',
|
|
17
|
+
'Servers:',
|
|
18
|
+
].join('\n');
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Water-fills `budget` over items of the given lengths: each gets min(length, equal share of
|
|
22
|
+
* what is left), with unused share redistributed.
|
|
23
|
+
* @param {number[]} lengths
|
|
24
|
+
* @param {number} budget
|
|
25
|
+
* @returns {number[]}
|
|
26
|
+
*/
|
|
27
|
+
export function fairShare(lengths, budget) {
|
|
28
|
+
const out = lengths.map(() => 0);
|
|
29
|
+
let left = Math.max(0, budget);
|
|
30
|
+
const order = lengths.map((len, i) => ({ len, i })).sort((a, b) => a.len - b.len);
|
|
31
|
+
let remaining = order.length;
|
|
32
|
+
for (const { len, i } of order) {
|
|
33
|
+
const share = Math.floor(left / remaining);
|
|
34
|
+
const take = Math.min(len, share);
|
|
35
|
+
out[i] = take;
|
|
36
|
+
left -= take;
|
|
37
|
+
remaining--;
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param {string} s @param {number} n */
|
|
43
|
+
export function truncate(s, n) {
|
|
44
|
+
if (s.length <= n) return s;
|
|
45
|
+
if (n <= TRUNC.length) return s.slice(0, Math.max(0, n));
|
|
46
|
+
return s.slice(0, n - TRUNC.length) + TRUNC;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {Array<{name: string, description: string, policy: string, state: string}>} servers
|
|
51
|
+
* @param {Array<{name: string, instructions: string}>} autostarted those that are on and have instructions
|
|
52
|
+
* @param {{confirmVia?: string}} [o]
|
|
53
|
+
* @returns {string}
|
|
54
|
+
*/
|
|
55
|
+
export function buildInstructions(servers, autostarted, o = {}) {
|
|
56
|
+
const header = o.confirmVia === 'host' ? HOST_HEADER : HEADER;
|
|
57
|
+
const lines = [];
|
|
58
|
+
let used = header.length;
|
|
59
|
+
for (let i = 0; i < servers.length; i++) {
|
|
60
|
+
const s = servers[i];
|
|
61
|
+
const desc = s.description ? `: ${truncate(s.description, DESCRIPTION_MAX)}` : '';
|
|
62
|
+
const line = `- ${s.name} [${s.policy === 'deny' ? 'deny' : `${s.state}, ${s.policy}`}]${desc}`;
|
|
63
|
+
const more = servers.length - i;
|
|
64
|
+
const tail = `- … ${more} more; call servers`;
|
|
65
|
+
if (used + 1 + line.length + 1 + tail.length > CATALOGUE_MAX && i < servers.length - 1) {
|
|
66
|
+
lines.push(tail);
|
|
67
|
+
used += 1 + tail.length;
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
lines.push(line);
|
|
71
|
+
used += 1 + line.length;
|
|
72
|
+
}
|
|
73
|
+
let text = `${header}\n${lines.join('\n')}`;
|
|
74
|
+
|
|
75
|
+
const blocks = autostarted.filter((a) => a.instructions);
|
|
76
|
+
if (blocks.length) {
|
|
77
|
+
const heads = blocks.map((b) => `\n\n## ${b.name} instructions\n`);
|
|
78
|
+
const overhead = heads.reduce((n, h) => n + h.length, 0);
|
|
79
|
+
const budget = MAX_INSTRUCTIONS - text.length - overhead;
|
|
80
|
+
const shares = fairShare(blocks.map((b) => b.instructions.length), budget);
|
|
81
|
+
blocks.forEach((b, i) => {
|
|
82
|
+
if (shares[i] <= 0) return;
|
|
83
|
+
text += heads[i] + truncate(b.instructions, shares[i]);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
if (text.length > MAX_INSTRUCTIONS) text = truncate(text, MAX_INSTRUCTIONS);
|
|
87
|
+
return text;
|
|
88
|
+
}
|
package/src/log.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// stderr-only logging. stdout belongs to MCP.
|
|
2
|
+
import { redact } from './redact.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @typedef {{info: (msg: string, secrets?: string[]) => void, warn: (msg: string, secrets?: string[]) => void, error: (msg: string, secrets?: string[]) => void, debug: (msg: string, secrets?: string[]) => void}} Logger
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @param {{debug?: boolean, write?: (s: string) => void}} [o]
|
|
10
|
+
* @returns {Logger}
|
|
11
|
+
*/
|
|
12
|
+
export function createLogger(o = {}) {
|
|
13
|
+
const write = o.write ?? ((s) => { try { process.stderr.write(s); } catch { /* stderr gone */ } });
|
|
14
|
+
const debugOn = o.debug ?? process.env.MCP_PATCHBAY_DEBUG === '1';
|
|
15
|
+
const emit = (level, msg, secrets) => write(`[mcp-patchbay] ${level}: ${redact(msg, secrets)}\n`);
|
|
16
|
+
return {
|
|
17
|
+
info: (m, s) => emit('info', m, s),
|
|
18
|
+
warn: (m, s) => emit('warn', m, s),
|
|
19
|
+
error: (m, s) => emit('error', m, s),
|
|
20
|
+
debug: (m, s) => { if (debugOn) emit('debug', m, s); },
|
|
21
|
+
};
|
|
22
|
+
}
|
package/src/naming.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// The public naming contract: how a child's tool name becomes the name the client sees.
|
|
2
|
+
// See SPEC.md §4 and README "Naming contract".
|
|
3
|
+
import { ToolSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
+
|
|
5
|
+
/** What Claude Code puts in front of every tool of a server registered as "patchbay". */
|
|
6
|
+
export const CLIENT_PREFIX = 'mcp__patchbay__';
|
|
7
|
+
/** Claude Code's limit on a full tool name. */
|
|
8
|
+
export const MAX_CLIENT_NAME = 128;
|
|
9
|
+
export const SEPARATOR = '__';
|
|
10
|
+
|
|
11
|
+
const SEGMENT_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Server names and prefixes: [A-Za-z0-9_-]{1,64}, no "__", no trailing "_".
|
|
15
|
+
* Together these make the first "__" in an exposed name the separator.
|
|
16
|
+
* @param {string} s
|
|
17
|
+
*/
|
|
18
|
+
export function isValidSegment(s) {
|
|
19
|
+
return typeof s === 'string' && SEGMENT_RE.test(s) && !s.includes('__') && !s.endsWith('_');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param {string} name */
|
|
23
|
+
export function sanitizeToolName(name) {
|
|
24
|
+
return String(name).replace(/[^A-Za-z0-9_-]/g, '_');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {string} segment
|
|
29
|
+
* @param {string} tool original tool name
|
|
30
|
+
*/
|
|
31
|
+
export function exposedName(segment, tool) {
|
|
32
|
+
return `${segment}${SEPARATOR}${sanitizeToolName(tool)}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Splits an exposed name on its first "__".
|
|
37
|
+
* @param {string} name
|
|
38
|
+
* @returns {{segment: string, tool: string} | null}
|
|
39
|
+
*/
|
|
40
|
+
export function splitExposed(name) {
|
|
41
|
+
const i = name.indexOf(SEPARATOR);
|
|
42
|
+
if (i <= 0) return null;
|
|
43
|
+
const tool = name.slice(i + SEPARATOR.length);
|
|
44
|
+
if (!tool) return null;
|
|
45
|
+
return { segment: name.slice(0, i), tool };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* @typedef {{exposed: string, original: string, tool: Record<string, unknown>}} Published
|
|
50
|
+
* @typedef {{tool: string, reason: string}} Skipped
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Maps a child's tools to published tools. The published tool object is the child's object
|
|
55
|
+
* with only `name` replaced; everything else (schemas, annotations, title, _meta, unknown keys)
|
|
56
|
+
* passes through unchanged.
|
|
57
|
+
* @param {string} segment
|
|
58
|
+
* @param {Array<Record<string, any>>} tools raw tools from the child's tools/list
|
|
59
|
+
* @returns {{published: Published[], skipped: Skipped[]}}
|
|
60
|
+
*/
|
|
61
|
+
export function mapTools(segment, tools) {
|
|
62
|
+
/** @type {Published[]} */
|
|
63
|
+
const published = [];
|
|
64
|
+
/** @type {Skipped[]} */
|
|
65
|
+
const skipped = [];
|
|
66
|
+
/** @type {Map<string, string>} */
|
|
67
|
+
const taken = new Map();
|
|
68
|
+
for (const tool of tools) {
|
|
69
|
+
const original = typeof tool?.name === 'string' ? tool.name : '';
|
|
70
|
+
if (!original) {
|
|
71
|
+
skipped.push({ tool: original, reason: 'empty name' });
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (!ToolSchema.safeParse(tool).success) {
|
|
75
|
+
skipped.push({ tool: original, reason: 'invalid tool definition' });
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (tool.execution?.taskSupport === 'required') {
|
|
79
|
+
skipped.push({ tool: original, reason: 'requires task-augmented calls, which the patchbay does not support' });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const exposed = exposedName(segment, original);
|
|
83
|
+
if (CLIENT_PREFIX.length + exposed.length > MAX_CLIENT_NAME) {
|
|
84
|
+
skipped.push({ tool: original, reason: `name too long: ${CLIENT_PREFIX}${exposed} exceeds ${MAX_CLIENT_NAME} characters` });
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const clash = taken.get(exposed);
|
|
88
|
+
if (clash !== undefined) {
|
|
89
|
+
skipped.push({ tool: original, reason: `name collides with ${clash} after sanitizing` });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
taken.set(exposed, original);
|
|
93
|
+
published.push({ exposed, original, tool: { ...tool, name: exposed } });
|
|
94
|
+
}
|
|
95
|
+
return { published, skipped };
|
|
96
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Claude Code permission rules that would approve enable_confirm without asking the person.
|
|
2
|
+
// Used by `doctor` (to warn) and `rename-permissions` (never to write one). See SECURITY-MODEL.md.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { jsonSyntaxMessage } from './config.js';
|
|
7
|
+
import { CLIENT_PREFIX } from './naming.js';
|
|
8
|
+
|
|
9
|
+
export const ENABLE_CONFIRM_CLIENT_NAME = `${CLIENT_PREFIX}enable_confirm`;
|
|
10
|
+
const SERVER_RULE = CLIENT_PREFIX.slice(0, -2); // "mcp__patchbay": the whole server
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Would this permission rule match the client name of enable_confirm? Covers the exact name,
|
|
14
|
+
* the whole-server rule `mcp__patchbay`, and any rule with `*` wildcards (`mcp__patchbay__*`,
|
|
15
|
+
* `mcp__*`, `*`). A rule with a parenthesised specifier is treated by what precedes it.
|
|
16
|
+
* @param {unknown} rule
|
|
17
|
+
*/
|
|
18
|
+
export function ruleMatchesEnableConfirm(rule) {
|
|
19
|
+
if (typeof rule !== 'string') return false;
|
|
20
|
+
let r = rule.trim();
|
|
21
|
+
const paren = r.indexOf('(');
|
|
22
|
+
if (paren !== -1) r = r.slice(0, paren);
|
|
23
|
+
if (r === SERVER_RULE) return true;
|
|
24
|
+
if (!r.includes('*')) return r === ENABLE_CONFIRM_CLIENT_NAME;
|
|
25
|
+
const escaped = r.split('*').map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
26
|
+
return new RegExp(`^${escaped.join('.*')}$`).test(ENABLE_CONFIRM_CLIENT_NAME);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The Claude Code settings files doctor reads: the user's, and with a project dir, the project's.
|
|
31
|
+
* @param {{home?: string, project?: string}} [o]
|
|
32
|
+
*/
|
|
33
|
+
export function settingsFiles(o = {}) {
|
|
34
|
+
const home = o.home ?? os.homedir();
|
|
35
|
+
const files = [path.join(home, '.claude', 'settings.json'), path.join(home, '.claude', 'settings.local.json')];
|
|
36
|
+
if (o.project) files.push(path.join(o.project, '.claude', 'settings.json'), path.join(o.project, '.claude', 'settings.local.json'));
|
|
37
|
+
return files;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Reads each settings file and reports what would approve enable_confirm without a prompt:
|
|
42
|
+
* allow rules that match it, and `permissions.defaultMode: "bypassPermissions"`.
|
|
43
|
+
* @param {string[]} files
|
|
44
|
+
* @returns {Array<{file: string, status: 'missing'|'unreadable'|'ok', error?: string, rules: string[], bypass: boolean}>}
|
|
45
|
+
*/
|
|
46
|
+
export function scanSettings(files) {
|
|
47
|
+
return files.map((file) => {
|
|
48
|
+
let text;
|
|
49
|
+
try {
|
|
50
|
+
text = fs.readFileSync(file, 'utf8');
|
|
51
|
+
} catch (e) {
|
|
52
|
+
const code = /** @type {any} */ (e).code;
|
|
53
|
+
if (code === 'ENOENT') return { file, status: 'missing', rules: [], bypass: false };
|
|
54
|
+
return { file, status: 'unreadable', error: `cannot read: ${code ?? e}`, rules: [], bypass: false };
|
|
55
|
+
}
|
|
56
|
+
let settings;
|
|
57
|
+
try {
|
|
58
|
+
settings = JSON.parse(text);
|
|
59
|
+
} catch {
|
|
60
|
+
// Never the parser's message: it quotes the text around the error (settings can hold env).
|
|
61
|
+
return { file, status: 'unreadable', error: jsonSyntaxMessage(file, text), rules: [], bypass: false };
|
|
62
|
+
}
|
|
63
|
+
const perms = settings?.permissions ?? {};
|
|
64
|
+
const allow = Array.isArray(perms.allow) ? perms.allow : [];
|
|
65
|
+
return {
|
|
66
|
+
file,
|
|
67
|
+
status: 'ok',
|
|
68
|
+
rules: allow.filter(ruleMatchesEnableConfirm),
|
|
69
|
+
bypass: perms.defaultMode === 'bypassPermissions',
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
}
|