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/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
+ }