@shumkov/orchestra 0.12.6 → 0.13.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/README.md CHANGED
@@ -27,6 +27,29 @@ const {
27
27
  // and file cap (maxOutboundFileBytes); the engine stays chat-network-agnostic.
28
28
  ```
29
29
 
30
+ ## MCP servers on the CLI backend
31
+
32
+ The CLI backend runs `claude` with `--strict-mcp-config`, so a session sees only the
33
+ channels bridge plus the servers its chat config names. Put Claude's own `mcpServers`
34
+ shape on the chat or on a topic:
35
+
36
+ ```json
37
+ { "mcpServers": { "canva": { "type": "http", "url": "https://mcp.canva.com/mcp" } } }
38
+ ```
39
+
40
+ - A topic's non-null `mcpServers` replaces the chat's set; `{}` drops it.
41
+ - Entries are validated strictly (known fields per type); a bad entry is skipped with a
42
+ `cli-mcp-servers` event and a warning, and the session still starts. The bridge name is
43
+ reserved.
44
+ - An OAuth server reuses an existing `claude mcp add` login only with the same name, type,
45
+ exact URL and headers. Each configured server's `authenticate` /
46
+ `complete_authentication` tools are denied: an operator logs in interactively.
47
+ - Changes apply when `claude` next starts (a new session, a reload, a respawn).
48
+ - Call `sweepStaleMcpConfigs({ sessionPrefix })` at boot to remove mcp-config files left by
49
+ dead sessions; they hold secrets.
50
+
51
+ Design: [`docs/CLI_MCP_SERVERS_SPEC.md`](docs/CLI_MCP_SERVERS_SPEC.md).
52
+
30
53
  ## Licence
31
54
 
32
55
  MIT.
@@ -0,0 +1,225 @@
1
+ # CLI backend: configured MCP servers next to the bridge
2
+
3
+ Status: reviewed (two spec reviewers, 25 Nov 2026), review fixes folded in.
4
+
5
+ ## Problem
6
+
7
+ The CLI backend (`lib/process/cli-process.js`, `_spawnTmuxClaude`) always starts
8
+ `claude` with `--strict-mcp-config` and one `--mcp-config` file that holds only the
9
+ channels bridge. Strict mode is required: it keeps the user's and project's MCP servers
10
+ out of bot sessions, and the bridge must be the only `channels` server. As a side
11
+ effect, there is no way to give a chat or a topic any other MCP server:
12
+
13
+ - MCP servers registered with `claude mcp add` (user, project or local scope), a repo's
14
+ `.mcp.json` and plugin servers are all ignored under strict mode.
15
+ - An agent file's frontmatter `mcpServers` is ignored for a main-thread `--agent`
16
+ (verified with Claude CLI 2.1.322, with and without strict mode).
17
+ - A consumer's agent-bundle `settings.json` `mcpServers` only reaches the SDK backend.
18
+
19
+ Concrete case: UMI's instagram role (Shumabit bot, marketing forum topic 1306) needs the
20
+ Canva MCP. The CLI already has Canva's OAuth stored. A contained test on the production
21
+ host proved the target behaviour: the pinned CLI with `--strict-mcp-config` and an
22
+ `--mcp-config` holding `{"canva":{"type":"http","url":"https://mcp.canva.com/mcp"}}`
23
+ connected Canva (source `dynamic`, 46 tools), and a read-only `search-designs` returned
24
+ real designs, reusing the stored OAuth entry.
25
+
26
+ ## Chosen approach
27
+
28
+ `CliProcess` reads an `mcpServers` object from the resolved chat config, with the same
29
+ topic-over-chat precedence it uses for `agent`, `cwd` and `isolateUserConfig`. It
30
+ validates the entries strictly and writes the valid ones into the existing 0600
31
+ mcp-config file next to the bridge. For every configured server it also denies that
32
+ server's OAuth tools. Otherwise the argv is unchanged: still `--strict-mcp-config`, still
33
+ one `--mcp-config <file>` as the last flag.
34
+
35
+ ```jsonc
36
+ // consumer config (polygram: config.json → chats[<id>] or chats[<id>].topics[<thread>])
37
+ "mcpServers": {
38
+ "canva": { "type": "http", "url": "https://mcp.canva.com/mcp" }
39
+ }
40
+ ```
41
+
42
+ Written file (the bridge key is first in insertion order, so Claude starts it first, and
43
+ it is assigned again last, so a configured entry can never replace it):
44
+
45
+ ```json
46
+ { "mcpServers": {
47
+ "polygram-bridge": { "command": "node", "args": ["…/channels-bridge.mjs"], "env": { … } },
48
+ "canva": { "type": "http", "url": "https://mcp.canva.com/mcp" }
49
+ } }
50
+ ```
51
+
52
+ Built as `{ [bridge]: def, ...servers, [bridge]: def }`.
53
+
54
+ ### OAuth reuse rule
55
+
56
+ The CLI stores MCP OAuth under `mcpOAuth["<name>|<sha256(JSON{type,url,headers})>[0:16]"]`
57
+ in `~/.claude/.credentials.json`. A configured server reuses an existing login only if the
58
+ **name, type, exact URL (no added or dropped trailing slash) and headers** equal the
59
+ `claude mcp add` registration. Verified on the VPS: `canva` and a probe named
60
+ `canva-probe` with the same URL got the same hash suffix but separate entries; the probe
61
+ had no token. Anything else means a new, unauthenticated entry.
62
+
63
+ ### Precedence: topic replaces chat
64
+
65
+ When a topic sets `mcpServers` (non-null), it replaces the chat's whole set; it does not
66
+ merge per server name. `null` or absent at topic level inherits the chat's. A topic's
67
+ `{}` drops the chat's servers. A legacy string topic config (a bare name) inherits the
68
+ chat's.
69
+
70
+ - Same rule as `agent`, `cwd` and `isolateUserConfig` in this backend.
71
+ - Rejected: per-name merge. Not needed for the use case, and it would need a removal
72
+ marker.
73
+
74
+ ### Validation (strict)
75
+
76
+ A small pure module `lib/process/cli-mcp-servers.js`,
77
+ `resolveConfiguredMcpServers({ value, reservedName })` → `{ servers, skipped }`, unit-tested
78
+ without tmux.
79
+
80
+ - `value` absent or `null`: no extra servers. The written file is byte-identical to
81
+ today's.
82
+ - `value` not a plain object: no extra servers, one skip with reason `not-an-object`.
83
+ - Per entry, all must hold or the entry is skipped:
84
+ - name matches `^[A-Za-z0-9_-]{1,64}$` (`invalid-name`) and is not the bridge name
85
+ (`reserved-name`);
86
+ - value is a plain object with only known fields for its type (`invalid-definition`
87
+ otherwise):
88
+ - `http` / `sse`: `type` (required), `url` (required, `https:` or `http:` URL),
89
+ `headers` (object of strings), `oauth` (object), `timeout` (finite number > 0);
90
+ - `stdio`: `type: "stdio"` (optional), `command` (non-empty string), `args` (array of
91
+ strings), `env` (object of strings), `timeout` (finite number > 0).
92
+ - A skipped entry never stops the session: it starts with the bridge and the valid rest.
93
+
94
+ **Settled on the pinned CLI (2.1.322, VPS, 25 Nov 2026):** a file with one valid server
95
+ and three bad entries (`{"type":"http"}` without a url, `{"foo":1}`, a bare number)
96
+ started normally: the bad entries were dropped silently, Canva connected with all 46
97
+ tools. So the CLI does not reject the whole file over a bad entry, but it also gives no
98
+ signal. Orchestra validates before writing so a typo is visible in its event and logs,
99
+ and so a future CLI that is stricter cannot take the bridge down.
100
+
101
+ ### Denying OAuth tools
102
+
103
+ When an HTTP server has no usable token, the interactive CLI (the CLI backend runs the
104
+ TUI) exposes `mcp__<name>__authenticate` and `mcp__<name>__complete_authentication`. Under
105
+ `bypassPermissions` a role could start an OAuth flow from a group chat. Verified on
106
+ 2.1.322: a `canva-probe` server without a token showed both tools in the TUI (not in
107
+ `-p`).
108
+
109
+ For every configured server, `CliProcess` adds
110
+ `--disallowedTools mcp__<n>__authenticate,mcp__<n>__complete_authentication,…` (one
111
+ comma-joined argument, placed before `--settings`). Verified on 2.1.322 under
112
+ `--permission-mode bypassPermissions --dangerously-skip-permissions`: with the flag, both
113
+ tools are gone (ToolSearch finds nothing) and the probe left no credential entry. A
114
+ re-login is an operator action: Ivan runs `claude` → `/mcp` interactively as the bot user
115
+ in the working directory where the server is registered (`/home/shumabit/shumabit-claude`
116
+ for Canva).
117
+
118
+ ### Logging and secrets
119
+
120
+ Server definitions may carry secrets (`headers.Authorization`, `env` tokens).
121
+
122
+ - Values are written only to the mcp-config file (mode 0600, re-chmodded, removed on
123
+ teardown). The file path is in argv; contents never are.
124
+ - One `cli-mcp-servers` event per spawn through `_logEvent`, with names and types only:
125
+ `{ servers: [{ name, type }], skipped: [{ name, reason }] }`. Not emitted when nothing
126
+ is configured. `reason` is a fixed code, never a value.
127
+ - A skipped entry also logs one `logger.warn` line with the name and the code.
128
+ - Boot cleanup: `sweepStaleMcpConfigs({ sessionPrefix, dir, minAgeMs })` removes
129
+ `<prefix>-<hex32>-mcp.json` files older than `minAgeMs` (default 15 minutes) whose
130
+ `<prefix>-<hex32>.sock` is missing or refuses a connection (its daemon is gone). A file
131
+ whose socket accepts belongs to a live session, possibly another bot's daemon under the
132
+ same Linux user and prefix, and stays. The consumer calls it at boot next to the tmux
133
+ orphan sweep. Today 11 such files sit in the VPS's `/tmp`, each holding a bridge socket
134
+ secret.
135
+ - Why the age floor (code review, reproduced): a release restarts both bots together, so
136
+ one daemon's sweep can run while the other's sessions are cold-starting. Probing a
137
+ starting session's socket used to take its single bridge slot and fail the start with
138
+ `BRIDGE_DISCONNECTED`. Young files are therefore never probed, and, as the lasting fix,
139
+ `ChannelsBridgeServer` gives the slot only to a connection that passes the hello
140
+ handshake: an unauthenticated connection never blocks the real bridge and its close is
141
+ never reported as `bridge-disconnected`.
142
+ - Invalid names (including `__proto__`, which would otherwise silently become the
143
+ object's prototype) are reported cut to 64 characters.
144
+
145
+ ### When a change takes effect
146
+
147
+ MCP servers are fixed when `claude` starts.
148
+
149
+ - `/new` (fresh conversation), `/reload` (same conversation, `--resume`), an idle eviction,
150
+ a crash respawn or a daemon restart start a new `claude` with the current config.
151
+ - A warm process keeps its spawn-time servers. `mcpServers` is not a spawn-identity field:
152
+ a respawn with `--resume` and a different server set continues the same conversation.
153
+ - The consumer decides when its config changes (polygram: at boot only; see its spec).
154
+
155
+ ### Failure modes (measured on 2.1.322 where marked)
156
+
157
+ | Failure | Behaviour |
158
+ | --- | --- |
159
+ | Invalid entry | Skipped by Orchestra, warn + event; session starts with the rest. The CLI would also drop it silently (measured). |
160
+ | Server needs OAuth | Status `needs-auth`, no tools; its OAuth tools are denied (measured). The role says the tool is not connected. |
161
+ | Server unreachable (`https://10.255.255.1/mcp`, packets dropped) | TUI reached its prompt in about 1 s with the server still pending; it then showed as `failed` (measured). In `-p` mode the first turn waited for the 30 s MCP connect timeout (33.5 s vs 17 s), which does not apply to the TUI the CLI backend runs. |
162
+ | Name collision with the bridge | Skipped as `reserved-name`; bridge assigned last regardless. |
163
+
164
+ ### Security and limits
165
+
166
+ - Config is operator-owned (`config.json`, 0600). polygram's `/config` does not expose
167
+ `mcpServers`.
168
+ - A server is scoped to the chat or topic that names it. Isolation is config-only: all
169
+ bots of a host may run as one Linux user and share `~/.claude/.credentials.json`.
170
+ - Strict mode stays on, so nothing else leaks in.
171
+ - Content a server returns (Canva designs, comments, assets) is data, not instructions;
172
+ consumers say so in the skills that use it.
173
+ - No approval gate is added on any server's write tools. For Canva, Ivan granted the
174
+ instagram role full use of UMI-owned Canva items (25 Nov 2026); per-design rules stay in
175
+ the `umi-canva` skill.
176
+
177
+ ## Interface
178
+
179
+ - New `lib/process/cli-mcp-servers.js`: `resolveConfiguredMcpServers`,
180
+ `buildMcpConfig({ bridgeName, bridgeDef, servers })`, `authToolDenyList(servers)`,
181
+ `sweepStaleMcpConfigs({ sessionPrefix, dir, logger })`.
182
+ - `index.js` exports `sweepStaleMcpConfigs` (next to `orphanSweep`).
183
+ - `CliProcess._spawnTmuxClaude`: topic resolution moves above the mcp-config write; the
184
+ file is built with `buildMcpConfig`; `--disallowedTools` added when servers exist; the
185
+ event is emitted.
186
+ - `README.md` documents the config key.
187
+
188
+ ## Tests (TDD)
189
+
190
+ `tests/cli-mcp-servers.test.js`:
191
+ - absent/null → `{}`; non-object → `{}` + `not-an-object`;
192
+ - valid http (with headers, oauth, timeout), sse and stdio pass through;
193
+ - bad name, reserved name, missing url/command, `ftp:` URL, unknown field, non-string
194
+ header, non-array args → each skipped with its code, others kept;
195
+ - `buildMcpConfig`: bridge first in key order, bridge definition wins over a same-named
196
+ entry;
197
+ - deny list: two tools per server, comma-joined;
198
+ - sweep: removes a file with no socket and one whose socket refuses; keeps one whose socket
199
+ accepts; ignores unrelated names.
200
+
201
+ `tests/cli-process.test.js` (existing fake tmux pattern):
202
+ - no `mcpServers`: the file holds only the bridge and argv has no `--disallowedTools`
203
+ (guards every other consumer);
204
+ - chat `mcpServers`: file holds bridge + canva; `--disallowedTools` present;
205
+ `--mcp-config` still last;
206
+ - topic replaces chat; topic `{}` → bridge only; topic without the key, topic `null` and a
207
+ legacy string topic inherit the chat's;
208
+ - secrets in `headers`/`env` absent from argv, events and logger output; file mode 0600.
209
+
210
+ ## Verification
211
+
212
+ Done before implementation (VPS, pinned 2.1.322, temp dirs, private tmux socket, artifacts
213
+ removed): the three measurements above (bad entries, needs-auth probe with and without
214
+ the deny flag, unreachable server timing).
215
+
216
+ After deploy (polygram rollout): the instagram topic's respawned session (a `/reload` or a
217
+ normal message, which resumes) lists `mcp__canva__*` and a read-only `search-designs`
218
+ works; the `cli-mcp-servers` events show canva only for topic 1306, none for `cmo`
219
+ (chat-level General) or other topics.
220
+
221
+ ## Out of scope
222
+
223
+ - Per-name merging, agent-level MCP for the CLI backend.
224
+ - The tmux and Codex backends (the key does nothing there).
225
+ - Water: unaffected unless its config sets `mcpServers`.
package/index.js CHANGED
@@ -38,6 +38,7 @@ const hookSettings = require('./lib/process/hook-settings');
38
38
  const hookEventTail = require('./lib/process/hook-event-tail');
39
39
  const startupGate = require('./lib/tmux/startup-gate');
40
40
  const attachmentBase = require('./lib/process/attachment-base');
41
+ const { sweepStaleMcpConfigs } = require('./lib/process/cli-mcp-servers');
41
42
 
42
43
  const { createTmuxRunner } = require('./lib/tmux/tmux-runner');
43
44
  const orphanSweep = require('./lib/tmux/orphan-sweep');
@@ -60,6 +61,8 @@ module.exports = {
60
61
  ChannelsBridgeServer, bridgeProtocol,
61
62
  // tmux lifecycle
62
63
  createTmuxRunner, orphanSweep, pollScheduler, logTail, startupGate,
64
+ // boot cleanup of mcp-config files left by dead CLI sessions
65
+ sweepStaleMcpConfigs,
63
66
  // claude binary pin+vendor
64
67
  claudeBin,
65
68
  // observability
@@ -27,7 +27,8 @@
27
27
  * ListToolsRequest received from claude). 0.12 P1.6
28
28
  * cold-spawn race fix — see channels-bridge.mjs.
29
29
  * 'bridge-message', msg — every validated bridge→daemon message (post-auth)
30
- * 'bridge-disconnected' — single-bridge connection closed
30
+ * 'bridge-disconnected' — the authenticated bridge connection closed
31
+ * (an unauthenticated connection never fires it)
31
32
  * 'error', err — socket-level errors (rare; non-fatal)
32
33
  */
33
34
 
@@ -61,8 +62,9 @@ class ChannelsBridgeServer extends EventEmitter {
61
62
  this.label = label;
62
63
 
63
64
  this.server = null;
64
- this.conn = null; // current bridge connection (one per session)
65
+ this.conn = null; // the authenticated bridge connection (one per session)
65
66
  this.authenticated = false;
67
+ this._pendingConns = new Set(); // connected, not yet authenticated
66
68
  }
67
69
 
68
70
  /**
@@ -131,6 +133,12 @@ class ChannelsBridgeServer extends EventEmitter {
131
133
  try { this.conn.end(); } catch {}
132
134
  this.conn = null;
133
135
  }
136
+ // server.close() waits for every open connection, so unauthenticated
137
+ // ones would otherwise hold teardown open.
138
+ for (const pending of this._pendingConns) {
139
+ try { pending.destroy(); } catch {}
140
+ }
141
+ this._pendingConns.clear();
134
142
  if (this.server) {
135
143
  await new Promise(resolve => this.server.close(() => resolve()));
136
144
  this.server = null;
@@ -141,14 +149,18 @@ class ChannelsBridgeServer extends EventEmitter {
141
149
  // ─── private ──────────────────────────────────────────────────────
142
150
 
143
151
  _onConnect(conn) {
144
- // Single bridge per session — reject second connections.
152
+ // Single bridge per session — reject connections once a bridge has
153
+ // authenticated. `this.conn` is set only on successful hello: the socket
154
+ // sits in a shared directory, and an unauthenticated connection (another
155
+ // daemon's liveness probe, a stray client) must neither take the slot
156
+ // from the real bridge nor have its close reported as the bridge dying.
145
157
  if (this.conn && !this.conn.destroyed) {
146
158
  this.logger.warn?.(`[${this.label}] extra bridge connection rejected`);
147
159
  try { conn.write(JSON.stringify({ kind: 'hello_reject', reason: 'already-connected' }) + '\n'); } catch {}
148
160
  conn.end();
149
161
  return;
150
162
  }
151
- this.conn = conn;
163
+ this._pendingConns.add(conn);
152
164
  let buf = '';
153
165
  let authenticated = false;
154
166
 
@@ -186,6 +198,8 @@ class ChannelsBridgeServer extends EventEmitter {
186
198
  // instance never happens — only a hijacker would.
187
199
  const verdict = this._verifyHelloAuth(raw);
188
200
  if (verdict.ok) {
201
+ this._pendingConns.delete(conn);
202
+ this.conn = conn;
189
203
  authenticated = true;
190
204
  this.authenticated = true;
191
205
  this.sockSecret = null; // invalidate — single-shot per instance
@@ -194,9 +208,10 @@ class ChannelsBridgeServer extends EventEmitter {
194
208
  }
195
209
  this.logger.warn?.(`[${this.label}] hello rejected — reason=${verdict.reason}`);
196
210
  try { conn.write(JSON.stringify({ kind: 'hello_reject', reason: 'auth' }) + '\n'); } catch {}
211
+ // A rejected connection never held the slot, so the live bridge
212
+ // (if any) keeps it.
213
+ this._pendingConns.delete(conn);
197
214
  conn.end();
198
- this.conn = null;
199
- this.authenticated = false;
200
215
  return;
201
216
  }
202
217
 
@@ -228,6 +243,7 @@ class ChannelsBridgeServer extends EventEmitter {
228
243
  });
229
244
 
230
245
  conn.on('close', () => {
246
+ this._pendingConns.delete(conn);
231
247
  if (this.conn === conn) {
232
248
  this.conn = null;
233
249
  this.authenticated = false;
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Configured MCP servers for the CLI backend.
3
+ *
4
+ * The CLI backend runs claude with --strict-mcp-config, so the only MCP
5
+ * servers a session gets are the ones in the mcp-config file CliProcess
6
+ * writes. A consumer may name extra servers per chat or topic
7
+ * (`mcpServers`, in Claude's own shape); this module decides which of them
8
+ * are written next to the channels bridge.
9
+ *
10
+ * Rules:
11
+ * - Validation is strict: only known fields per server type. A bad entry
12
+ * is skipped, never fatal, so one typo cannot take a topic offline.
13
+ * (Claude CLI 2.1.322 drops bad entries silently; checking here makes
14
+ * the skip visible and does not depend on the CLI staying lenient.)
15
+ * - The bridge name is reserved, and buildMcpConfig assigns the bridge
16
+ * last as well as first, so no entry can replace it.
17
+ * - Skip records carry a name and a fixed reason code, never a server
18
+ * definition: definitions may hold secrets (headers, env).
19
+ *
20
+ * See docs/CLI_MCP_SERVERS_SPEC.md.
21
+ */
22
+
23
+ 'use strict';
24
+
25
+ const fs = require('node:fs');
26
+ const net = require('node:net');
27
+ const os = require('node:os');
28
+ const path = require('node:path');
29
+
30
+ // Claude's MCP server name rule; the name becomes the mcp__<name>__ prefix.
31
+ const MAX_NAME_LENGTH = 64;
32
+ const SERVER_NAME_RE = new RegExp(`^[A-Za-z0-9_-]{1,${MAX_NAME_LENGTH}}$`);
33
+ // A session that is still starting may have written its config but not yet
34
+ // finished its bridge handshake; the sweep never touches or probes files
35
+ // younger than this. Sessions start in seconds, so 15 minutes is ample.
36
+ const DEFAULT_SWEEP_MIN_AGE_MS = 15 * 60 * 1000;
37
+
38
+ const REMOTE_FIELDS = new Set(['type', 'url', 'headers', 'oauth', 'timeout']);
39
+ const STDIO_FIELDS = new Set(['type', 'command', 'args', 'env', 'timeout']);
40
+
41
+ function isPlainObject(v) {
42
+ return v !== null && typeof v === 'object' && !Array.isArray(v)
43
+ && Object.getPrototypeOf(v) === Object.prototype;
44
+ }
45
+
46
+ function isStringMap(v) {
47
+ return isPlainObject(v) && Object.values(v).every(x => typeof x === 'string');
48
+ }
49
+
50
+ function onlyFields(def, allowed) {
51
+ return Object.keys(def).every(k => allowed.has(k));
52
+ }
53
+
54
+ function validTimeout(def) {
55
+ return def.timeout === undefined
56
+ || (typeof def.timeout === 'number' && Number.isFinite(def.timeout) && def.timeout > 0);
57
+ }
58
+
59
+ function isRemoteUrl(u) {
60
+ if (typeof u !== 'string') return false;
61
+ try {
62
+ const { protocol } = new URL(u);
63
+ return protocol === 'https:' || protocol === 'http:';
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ function isValidDefinition(def) {
70
+ if (!isPlainObject(def)) return false;
71
+ if (!validTimeout(def)) return false;
72
+ if (def.type === 'http' || def.type === 'sse') {
73
+ return onlyFields(def, REMOTE_FIELDS)
74
+ && isRemoteUrl(def.url)
75
+ && (def.headers === undefined || isStringMap(def.headers))
76
+ && (def.oauth === undefined || isPlainObject(def.oauth));
77
+ }
78
+ if (def.type === undefined || def.type === 'stdio') {
79
+ return onlyFields(def, STDIO_FIELDS)
80
+ && typeof def.command === 'string' && def.command.length > 0
81
+ && (def.args === undefined
82
+ || (Array.isArray(def.args) && def.args.every(a => typeof a === 'string')))
83
+ && (def.env === undefined || isStringMap(def.env));
84
+ }
85
+ return false;
86
+ }
87
+
88
+ /**
89
+ * @param {object} opts
90
+ * @param {*} opts.value — the resolved `mcpServers` config value
91
+ * @param {string} opts.reservedName — the channels bridge's server name
92
+ * @returns {{ servers: object, skipped: Array<{name: ?string, reason: string}> }}
93
+ */
94
+ function resolveConfiguredMcpServers({ value, reservedName }) {
95
+ if (value === undefined || value === null) return { servers: {}, skipped: [] };
96
+ if (!isPlainObject(value)) {
97
+ return { servers: {}, skipped: [{ name: null, reason: 'not-an-object' }] };
98
+ }
99
+ const servers = {};
100
+ const skipped = [];
101
+ for (const [name, def] of Object.entries(value)) {
102
+ // `__proto__` passes the character rule, but assigning it below would set
103
+ // the object's prototype and drop the entry silently.
104
+ if (!SERVER_NAME_RE.test(name) || name === '__proto__') {
105
+ // Cut for logs and events: a name is operator config, but an
106
+ // unbounded one would flood both.
107
+ skipped.push({ name: name.slice(0, MAX_NAME_LENGTH), reason: 'invalid-name' });
108
+ } else if (name === reservedName) {
109
+ skipped.push({ name, reason: 'reserved-name' });
110
+ } else if (!isValidDefinition(def)) {
111
+ skipped.push({ name, reason: 'invalid-definition' });
112
+ } else {
113
+ servers[name] = def;
114
+ }
115
+ }
116
+ return { servers, skipped };
117
+ }
118
+
119
+ /**
120
+ * The mcp-config file body. The bridge key comes first so claude starts it
121
+ * first, and is assigned again after the configured servers so a same-named
122
+ * entry can never replace it, even if validation were bypassed.
123
+ */
124
+ function buildMcpConfig({ bridgeName, bridgeDef, servers }) {
125
+ return {
126
+ mcpServers: { [bridgeName]: bridgeDef, ...servers, [bridgeName]: bridgeDef },
127
+ };
128
+ }
129
+
130
+ /**
131
+ * A server without a usable OAuth token exposes mcp__<name>__authenticate and
132
+ * mcp__<name>__complete_authentication in the interactive CLI. A bot session
133
+ * must never start an OAuth flow (an operator logs in interactively), so both
134
+ * are denied for every configured server. Returns one comma-joined value for
135
+ * --disallowedTools, or null when there is nothing to deny.
136
+ */
137
+ function authToolDenyList(servers) {
138
+ const names = Object.keys(servers || {});
139
+ if (names.length === 0) return null;
140
+ return names
141
+ .flatMap(n => [`mcp__${n}__authenticate`, `mcp__${n}__complete_authentication`])
142
+ .join(',');
143
+ }
144
+
145
+ function socketAccepts(sockPath, timeoutMs = 1000) {
146
+ return new Promise((resolve) => {
147
+ const sock = net.connect(sockPath);
148
+ const done = (ok) => { sock.destroy(); resolve(ok); };
149
+ sock.setTimeout(timeoutMs, () => done(false));
150
+ sock.once('connect', () => done(true));
151
+ sock.once('error', () => done(false));
152
+ });
153
+ }
154
+
155
+ /**
156
+ * Boot-time removal of mcp-config files left by sessions whose daemon died
157
+ * (a clean teardown removes its own file). They hold the bridge socket secret
158
+ * and any configured server's headers. Under one Linux user several daemons
159
+ * may share the prefix and the directory, and a release restarts them
160
+ * together, so:
161
+ * - a file younger than minAgeMs is left alone and its socket is never
162
+ * probed (a starting session must not see a stranger's connection);
163
+ * - an older file stays while its session socket accepts connections.
164
+ *
165
+ * @param {object} opts
166
+ * @param {string} opts.sessionPrefix — e.g. 'polygram'
167
+ * @param {string} [opts.dir=os.tmpdir()]
168
+ * @param {number} [opts.minAgeMs=15 min]
169
+ * @param {object} [opts.logger=console]
170
+ * @returns {Promise<{ removed: string[], errors: Array<{file: string, error: string}> }>}
171
+ */
172
+ async function sweepStaleMcpConfigs({
173
+ sessionPrefix, dir = os.tmpdir(), minAgeMs = DEFAULT_SWEEP_MIN_AGE_MS, logger = console,
174
+ } = {}) {
175
+ if (typeof sessionPrefix !== 'string' || sessionPrefix.length === 0) {
176
+ throw new TypeError('sweepStaleMcpConfigs: sessionPrefix required');
177
+ }
178
+ const escaped = sessionPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
179
+ const re = new RegExp(`^${escaped}-([0-9a-f]{32})-mcp\\.json$`);
180
+ let entries;
181
+ try {
182
+ entries = fs.readdirSync(dir);
183
+ } catch {
184
+ return { removed: [], errors: [] };
185
+ }
186
+ const removed = [];
187
+ const errors = [];
188
+ for (const file of entries) {
189
+ const m = re.exec(file);
190
+ if (!m) continue;
191
+ let mtimeMs;
192
+ try {
193
+ ({ mtimeMs } = fs.statSync(path.join(dir, file)));
194
+ } catch {
195
+ continue; // gone already (its session tore down)
196
+ }
197
+ if (Date.now() - mtimeMs < minAgeMs) continue;
198
+ const sockPath = path.join(dir, `${sessionPrefix}-${m[1]}.sock`);
199
+ if (fs.existsSync(sockPath) && await socketAccepts(sockPath)) continue;
200
+ try {
201
+ fs.unlinkSync(path.join(dir, file));
202
+ removed.push(file);
203
+ } catch (err) {
204
+ errors.push({ file, error: err.message });
205
+ logger.warn?.(`[mcp-config-sweep] remove ${file} failed: ${err.message}`);
206
+ }
207
+ }
208
+ if (removed.length > 0) {
209
+ logger.log?.(`[mcp-config-sweep] removed ${removed.length} stale mcp-config file(s)`);
210
+ }
211
+ return { removed, errors };
212
+ }
213
+
214
+ module.exports = {
215
+ resolveConfiguredMcpServers,
216
+ buildMcpConfig,
217
+ authToolDenyList,
218
+ sweepStaleMcpConfigs,
219
+ };
@@ -48,6 +48,11 @@ const path = require('node:path');
48
48
  const { Process, UnsupportedOperationError } = require('./process');
49
49
  const { ChannelsBridgeServer } = require('./channels-bridge-server');
50
50
  const { writeHookFiles, removeHookFiles } = require('./hook-settings');
51
+ const {
52
+ resolveConfiguredMcpServers,
53
+ buildMcpConfig,
54
+ authToolDenyList,
55
+ } = require('./cli-mcp-servers');
51
56
  const { createHookTail } = require('./hook-event-tail');
52
57
  // Single source of truth for the question wait: the daemon owns the question
53
58
  // lifecycle (answer or {timedout} sweep), and we pass this to the bridge so its
@@ -808,15 +813,34 @@ class CliProcess extends Process {
808
813
 
809
814
  async _spawnTmuxClaude({ tmuxName, opts }) {
810
815
  const bridgeEnv = this._bridgeEnv();
811
- const mcpConfig = {
812
- mcpServers: {
813
- [this.bridgeServerName]: {
814
- command: 'node',
815
- args: [BRIDGE_PATH],
816
- env: bridgeEnv,
817
- },
818
- },
819
- };
816
+
817
+ // Resolve the topic override FIRST: it selects the configured MCP servers
818
+ // written below, and the cwd the --resume file-check uses.
819
+ const topicConfig = opts.threadId && opts.chatConfig?.topics?.[opts.threadId];
820
+
821
+ // Configured MCP servers (chat or topic `mcpServers`), next to the bridge.
822
+ // A topic's non-null value replaces the chat's set as a whole, like agent
823
+ // and cwd. Strict mode stays on, so these are the only servers besides
824
+ // the bridge. See docs/CLI_MCP_SERVERS_SPEC.md.
825
+ const { servers: configuredMcpServers, skipped: skippedMcpServers } = resolveConfiguredMcpServers({
826
+ value: topicConfig?.mcpServers != null ? topicConfig.mcpServers : opts.chatConfig?.mcpServers,
827
+ reservedName: this.bridgeServerName,
828
+ });
829
+ for (const { name, reason } of skippedMcpServers) {
830
+ this.logger.warn?.(`[${this.label}] channels: configured MCP server ${name ?? '(mcpServers)'} skipped: ${reason}`);
831
+ }
832
+ const configuredNames = Object.keys(configuredMcpServers);
833
+ if (configuredNames.length > 0 || skippedMcpServers.length > 0) {
834
+ this._logEvent('cli-mcp-servers', {
835
+ servers: configuredNames.map(name => ({ name, type: configuredMcpServers[name].type || 'stdio' })),
836
+ skipped: skippedMcpServers,
837
+ });
838
+ }
839
+ const mcpConfig = buildMcpConfig({
840
+ bridgeName: this.bridgeServerName,
841
+ bridgeDef: { command: 'node', args: [BRIDGE_PATH], env: bridgeEnv },
842
+ servers: configuredMcpServers,
843
+ });
820
844
 
821
845
  // Review P0 #1: write mcp-config to a 0o600 tmp file and pass the FILE
822
846
  // PATH in argv. Inline JSON in argv would expose ORCHESTRA_SOCK_SECRET +
@@ -843,10 +867,8 @@ class CliProcess extends Process {
843
867
  '--dangerously-load-development-channels', `server:${this.bridgeServerName}`,
844
868
  ];
845
869
 
846
- // Resolve config FIRST so the --resume file-check below has the correct
847
- // cwd (it picks up topic precedence). Other flags get pushed in order
848
- // after this.
849
- const topicConfig = opts.threadId && opts.chatConfig?.topics?.[opts.threadId];
870
+ // Resolve the rest of the config before other flags so the --resume
871
+ // file-check below has the correct cwd (topic precedence).
850
872
  const agent = topicConfig?.agent || opts.chatConfig?.agent || opts.agent;
851
873
  const model = this._resolveModel(opts);
852
874
  const effort = this._resolveEffort(opts);
@@ -1259,6 +1281,14 @@ class CliProcess extends Process {
1259
1281
  });
1260
1282
  this._hookNdjsonPath = hookNdjsonPath;
1261
1283
  this._hookSettingsPath = hookSettingsPath;
1284
+
1285
+ // A configured server without a usable OAuth token exposes
1286
+ // authenticate/complete_authentication tools; a bot session must never
1287
+ // start an OAuth flow. One comma-joined value, ahead of the variadic
1288
+ // --settings / --mcp-config tail.
1289
+ const deniedAuthTools = authToolDenyList(configuredMcpServers);
1290
+ if (deniedAuthTools) claudeArgs.push('--disallowedTools', deniedAuthTools);
1291
+
1262
1292
  claudeArgs.push('--settings', hookSettingsPath);
1263
1293
 
1264
1294
  // --mcp-config MUST be last (variadic flag)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.12.6",
3
+ "version": "0.13.0",
4
4
  "description": "Transport-agnostic session engine for Claude Code and the native Codex app-server: spawn, steer, supervise, observe turns, and recover.",
5
5
  "type": "commonjs",
6
6
  "main": "index.js",