@chroxy/server 0.10.0 → 0.11.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.
Files changed (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -4,11 +4,31 @@
4
4
  * Foundation only for #4048/#4076: parse Claude-style mcpServers blocks and
5
5
  * expose safe read-only metadata. This module deliberately does not spawn MCP
6
6
  * children or wire tools.
7
+ *
8
+ * NOT byok-only despite the filename: `resolveClaudeConfigWritePath` +
9
+ * `writeClaudeConfigAtomic` are the SINGLE writer for `~/.claude.json` across the
10
+ * whole server, and `claude-tui/pty-driver.js`'s `ensureCwdTrusted` goes through
11
+ * them too (#7046). A second hand-rolled `writeFileSync(tmp)` → `renameSync(tmp,
12
+ * config)` over this file is how the symlink-destroying / mode-widening defect
13
+ * came to exist in two places at once — add callers here, not copies.
7
14
  */
8
15
 
9
- import { existsSync, readFileSync, statSync } from 'node:fs'
16
+ import {
17
+ chmodSync,
18
+ existsSync,
19
+ lstatSync,
20
+ readFileSync,
21
+ realpathSync,
22
+ renameSync,
23
+ statSync,
24
+ unlinkSync,
25
+ writeFileSync,
26
+ } from 'node:fs'
27
+ import { randomUUID } from 'node:crypto'
10
28
  import { homedir } from 'node:os'
11
- import { join } from 'node:path'
29
+ import { dirname, join } from 'node:path'
30
+ import { lookup as dnsLookup } from 'node:dns/promises'
31
+ import { fsyncForDurability, confirmRenameDurable } from './platform.js'
12
32
 
13
33
  /**
14
34
  * Defensive upper bound on the size of `~/.claude.json`. Today the file is
@@ -51,6 +71,17 @@ function coerceStringArray(value, { warnings, serverName }) {
51
71
  return out
52
72
  }
53
73
 
74
+ /**
75
+ * Keys that must never be assigned into a string→string map we build with `{}`.
76
+ * `map.__proto__ = 'some string'` hits `Object.prototype`'s `__proto__` setter,
77
+ * which ignores non-object values — so the key vanished SILENTLY, and a caller
78
+ * who asked for `env.__proto__` got a server spawned without it and no
79
+ * explanation. `constructor` / `prototype` are plain own-property writes (no
80
+ * setter) but are refused alongside it: a map key that shadows an object internal
81
+ * is never a legitimate environment variable or HTTP header (#7001 review).
82
+ */
83
+ const UNSAFE_MAP_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
84
+
54
85
  /**
55
86
  * Coerce an env object to string→string only. Pushes one warning per dropped
56
87
  * key naming the server, the offending field (`env.<KEY>`), and the value's
@@ -67,6 +98,14 @@ function coerceEnv(value, { warnings, serverName }) {
67
98
  const env = {}
68
99
  for (const [key, raw] of Object.entries(value)) {
69
100
  if (typeof key !== 'string' || key.length === 0) continue
101
+ if (UNSAFE_MAP_KEYS.has(key)) {
102
+ // Warn rather than drop silently: on the WRITE path
103
+ // (normalizeMcpServerConfig) any warning is escalated to a rejection, so
104
+ // the caller is told the key is refused instead of receiving an `ok` for a
105
+ // config that quietly lost it.
106
+ warnings.push(`MCP server ${serverName}: refusing env.${key} (reserved object key, never a real environment variable)`)
107
+ continue
108
+ }
70
109
  if (typeof raw === 'string') {
71
110
  env[key] = raw
72
111
  } else {
@@ -78,11 +117,326 @@ function coerceEnv(value, { warnings, serverName }) {
78
117
  return env
79
118
  }
80
119
 
120
+ /**
121
+ * Coerce an HTTP `headers` object to string→string only, for remote (#6821)
122
+ * MCP transports. Same defensive shape as coerceEnv: one warning per dropped
123
+ * key naming the field (`headers.<KEY>`), and the whole field is dropped with
124
+ * a single warning if it is not a plain object. Header VALUES (bearer tokens,
125
+ * api keys) are never logged or surfaced — the warning names only the key.
126
+ */
127
+ function coerceHeaders(value, { warnings, serverName }) {
128
+ if (value == null) return {}
129
+ if (typeof value !== 'object' || Array.isArray(value)) {
130
+ warnings.push(
131
+ `MCP server ${serverName}: ignoring headers (expected object, got ${Array.isArray(value) ? 'array' : typeof value})`,
132
+ )
133
+ return {}
134
+ }
135
+ const headers = {}
136
+ for (const [key, raw] of Object.entries(value)) {
137
+ if (typeof key !== 'string' || key.length === 0) continue
138
+ if (UNSAFE_MAP_KEYS.has(key)) {
139
+ // Same silent-drop hazard as env.__proto__ — refuse explicitly (#7001 review).
140
+ warnings.push(`MCP server ${serverName}: refusing headers.${key} (reserved object key, never a real HTTP header)`)
141
+ continue
142
+ }
143
+ if (typeof raw === 'string') {
144
+ headers[key] = raw
145
+ } else {
146
+ warnings.push(
147
+ `MCP server ${serverName}: dropping headers.${key} (expected string, got ${typeof raw})`,
148
+ )
149
+ }
150
+ }
151
+ return headers
152
+ }
153
+
154
+ /**
155
+ * True when a hostname (or a bare IP from dns.lookup) targets the cloud
156
+ * metadata service / IPv4 link-local range — never a legitimate MCP server
157
+ * (#6821, sharpest edge of #6834). Covers:
158
+ * - 169.254.0.0/16 (link-local; the metadata endpoint 169.254.169.254
159
+ * lives here). The WHATWG URL parser canonicalizes hex/decimal/octal
160
+ * host tricks (0xa9fea9fe, 2852039166) to dotted-quad first, so a
161
+ * literal-host check on the PARSED hostname catches those too.
162
+ * - IPv4-mapped IPv6 forms of the same range: the URL parser serializes
163
+ * them as hex groups (`::ffff:a9fe:xxxx`; a9fe == 169.254), dns.lookup
164
+ * may return the dotted form (`::ffff:169.254.x.x`).
165
+ * - fd00:ec2::254, the AWS IMDS IPv6 endpoint (URL-canonical compressed
166
+ * form plus the expanded spelling).
167
+ * Deliberately does NOT block loopback / RFC1918 generally — localhost MCP
168
+ * servers are legitimate; the broader egress policy is #6834's scope.
169
+ */
170
+ export function isBlockedMetadataHost(hostname) {
171
+ if (typeof hostname !== 'string' || hostname.length === 0) return false
172
+ let h = hostname.toLowerCase()
173
+ if (h.startsWith('[') && h.endsWith(']')) h = h.slice(1, -1)
174
+ const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/)
175
+ if (v4) return Number(v4[1]) === 169 && Number(v4[2]) === 254
176
+ if (/^::ffff:a9fe:[0-9a-f]{1,4}$/.test(h)) return true
177
+ const mapped = h.match(/^::ffff:(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/)
178
+ if (mapped) return Number(mapped[1]) === 169 && Number(mapped[2]) === 254
179
+ if (h === 'fd00:ec2::254' || h === 'fd00:ec2:0:0:0:0:0:254') return true
180
+ return false
181
+ }
182
+
183
+ /**
184
+ * Return a credential-stripped form of an MCP server url, safe to log or
185
+ * surface as metadata (#6821). Strips URL userinfo (`user:pass@`), the query
186
+ * string, and the fragment — any of which can carry a token — while keeping
187
+ * the origin + path that identify the endpoint. An unparseable url yields a
188
+ * fixed placeholder so a malformed value can never leak verbatim.
189
+ */
190
+ export function redactMcpUrl(url) {
191
+ if (typeof url !== 'string' || url.length === 0) return ''
192
+ try {
193
+ const u = new URL(url)
194
+ u.username = ''
195
+ u.password = ''
196
+ u.search = ''
197
+ u.hash = ''
198
+ return u.toString()
199
+ } catch {
200
+ return '[unparseable url]'
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Classify a bare IP address for trust-prompt display (#6834). Returns one of
206
+ * 'loopback' | 'private' | 'link-local' | 'public' | 'unknown'. Purely for the
207
+ * human-facing consent string — the cloud-metadata range is hard-BLOCKED
208
+ * upstream (isBlockedMetadataHost, at config-parse and request time) so a
209
+ * metadata address never reaches this classifier.
210
+ *
211
+ * Covers the common private ranges a "remote" MCP server might secretly point
212
+ * at: IPv4 loopback (127/8), RFC1918 (10/8, 172.16/12, 192.168/16), link-local
213
+ * (169.254/16), and their IPv6 equivalents (::1, fc00::/7 ULA, fe80::/10
214
+ * link-local). IPv4-mapped IPv6 (`::ffff:a.b.c.d`) is unwrapped to its v4 form
215
+ * first. Anything else is 'public'. Best-effort — an unrecognisable string maps
216
+ * to 'unknown' (shown as such), never throws.
217
+ */
218
+ export function classifyIpAddress(ip) {
219
+ if (typeof ip !== 'string' || ip.length === 0) return 'unknown'
220
+ let h = ip.toLowerCase().trim()
221
+ if (h.startsWith('[') && h.endsWith(']')) h = h.slice(1, -1)
222
+ const zone = h.indexOf('%') // strip an IPv6 zone id (fe80::1%en0)
223
+ if (zone !== -1) h = h.slice(0, zone)
224
+ // IPv4-mapped IPv6 (::ffff:a.b.c.d) — classify by the embedded v4 address.
225
+ const mapped = h.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)
226
+ if (mapped) h = mapped[1]
227
+ const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
228
+ if (v4) {
229
+ const a = Number(v4[1])
230
+ const b = Number(v4[2])
231
+ if (v4.slice(1).some((o) => Number(o) > 255)) return 'unknown'
232
+ if (a === 127) return 'loopback'
233
+ if (a === 10) return 'private'
234
+ if (a === 172 && b >= 16 && b <= 31) return 'private'
235
+ if (a === 192 && b === 168) return 'private'
236
+ if (a === 169 && b === 254) return 'link-local'
237
+ return 'public'
238
+ }
239
+ // IPv6 literals.
240
+ if (h === '::1') return 'loopback'
241
+ // Link-local is fe80::/10 — the leading hextet spans fe80 through febf (top
242
+ // 10 bits fixed: 1111111010). Match the first two hex digits (fe) plus the
243
+ // third digit constrained to 8..b, not just the `fe80` literal. The trailing
244
+ // `:` covers both `fe80:...` and the compressed `fe80::...` (which begins `:`).
245
+ if (/^fe[89ab][0-9a-f]:/.test(h)) return 'link-local'
246
+ if (/^f[cd][0-9a-f]{2}:/.test(h)) return 'private' // fc00::/7 unique-local
247
+ if (h.includes(':')) return 'public'
248
+ return 'unknown'
249
+ }
250
+
251
+ // Human-readable label per classification, for the trust-prompt string.
252
+ const _CLASSIFICATION_LABELS = {
253
+ loopback: 'loopback',
254
+ private: 'private LAN',
255
+ 'link-local': 'link-local',
256
+ public: 'public',
257
+ unknown: 'unknown',
258
+ }
259
+
260
+ // Order of "notability" when a host resolves to several addresses — the most
261
+ // internal wins the summary label so a remote server that ALSO resolves to an
262
+ // internal address surfaces that fact at consent time.
263
+ const _CLASSIFICATION_PRIORITY = ['loopback', 'private', 'link-local', 'public', 'unknown']
264
+
265
+ // #6852 — cap on the trust-prompt DNS lookup. resolveTrustAddress runs inside
266
+ // the fleet's withTrustStoreLock (byok-mcp-fleet.js), so a slow/hanging
267
+ // resolver would both delay the consent prompt AND hold the lock for every
268
+ // other MCP client. 2s is generous for a real resolver yet bounds the worst
269
+ // case; on timeout we fall back to the same graceful "could not resolve host".
270
+ export const DEFAULT_TRUST_DNS_TIMEOUT_MS = 2000
271
+
272
+ // Resolved by the timeout arm of the lookup race (distinct from any address the
273
+ // resolver could return), so a timeout maps to the graceful fallback.
274
+ const _LOOKUP_TIMEOUT = Symbol('trust-address-lookup-timeout')
275
+
276
+ function _summariseClassification(classifications) {
277
+ for (const c of _CLASSIFICATION_PRIORITY) {
278
+ if (classifications.includes(c)) return c
279
+ }
280
+ return 'unknown'
281
+ }
282
+
283
+ /**
284
+ * Best-effort resolution of a remote MCP server url's host, for the first-use
285
+ * trust prompt (#6834). Returns a small structured record describing WHERE the
286
+ * host actually points so a user approving a 'remote' server can see when it
287
+ * resolves to a loopback / private / internal address and make an informed
288
+ * consent decision (owner decision 2026-07-18: display, don't block).
289
+ *
290
+ * Shape: `{ resolved, hostname, addresses, classification, display }`.
291
+ * - resolved:false + display 'could not resolve host' when the url is
292
+ * unparseable OR DNS lookup fails / returns nothing. NEVER throws.
293
+ * - a literal IP host is classified directly (no DNS round-trip).
294
+ * - a DNS name is resolved via `lookup(..., { all: true })`; the summary
295
+ * classification is the most-internal of the returned addresses.
296
+ *
297
+ * The `lookup` seam is injectable (defaults to node:dns/promises lookup — the
298
+ * same resolver the transport's metadata guard uses) so tests never touch real
299
+ * DNS. Credentials are NOT this function's concern: pass an already-redacted or
300
+ * raw url — only the hostname is read, and only IPs are returned.
301
+ *
302
+ * The lookup is bounded by `timeoutMs` (#6852): resolveTrustAddress runs under
303
+ * the fleet's trust-store lock, so a hanging resolver must not stall the prompt
304
+ * or the lock — a timeout falls back to 'could not resolve host'. The timer
305
+ * itself is injectable via `setTimer`/`clearTimer` (default node globals) so a
306
+ * test can drive the timeout deterministically — firing it by hand instead of
307
+ * waiting on the wall clock (#6908) — with no real DNS and no real timer.
308
+ */
309
+ export async function resolveTrustAddress(
310
+ url,
311
+ {
312
+ lookup = dnsLookup,
313
+ timeoutMs = DEFAULT_TRUST_DNS_TIMEOUT_MS,
314
+ setTimer = setTimeout,
315
+ clearTimer = clearTimeout,
316
+ } = {},
317
+ ) {
318
+ const miss = (hostname = null) => ({
319
+ resolved: false,
320
+ hostname,
321
+ addresses: [],
322
+ classification: 'unknown',
323
+ display: 'could not resolve host',
324
+ })
325
+ let hostname
326
+ try {
327
+ hostname = new URL(url).hostname
328
+ } catch {
329
+ return miss()
330
+ }
331
+ if (!hostname) return miss()
332
+ const bare = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname
333
+ // Short-circuit ONLY for a syntactically-valid IP literal. A dotted-quad-
334
+ // shaped string with an out-of-range octet (e.g. 999.1.1.1) is NOT an IP —
335
+ // classifyIpAddress returns 'unknown' — so it is really a hostname and must
336
+ // go through the DNS path, not be echoed as a misleading "resolves to
337
+ // 999.1.1.1". A bracketed / colon-bearing IPv6 host is always a literal.
338
+ const looksLikeLiteral = /^[\d.]+$/.test(bare) || bare.includes(':')
339
+ const literalClass = looksLikeLiteral ? classifyIpAddress(bare) : 'unknown'
340
+ if (looksLikeLiteral && literalClass !== 'unknown') {
341
+ return {
342
+ resolved: true,
343
+ hostname,
344
+ addresses: [bare],
345
+ classification: literalClass,
346
+ display: `resolves to ${bare} (${_CLASSIFICATION_LABELS[literalClass] || literalClass})`,
347
+ }
348
+ }
349
+ let timer
350
+ try {
351
+ // Bound the lookup: whichever settles first wins. The timeout arm RESOLVES
352
+ // with a sentinel (never rejects) so a slow resolver maps to the graceful
353
+ // fallback, not an error. Promise.race registers a reaction on the lookup
354
+ // promise, so a late rejection from the loser stays handled. The timer is
355
+ // NOT unref'd — it is always cleared in `finally` once the race settles, so
356
+ // it never outlives this (awaited) resolution, and keeping the loop alive
357
+ // while we resolve is the intended behaviour. `setTimer`/`clearTimer` are
358
+ // injectable (default globals) so a test drives the timeout deterministically.
359
+ const timeoutArm = new Promise((resolve) => {
360
+ timer = setTimer(() => resolve(_LOOKUP_TIMEOUT), timeoutMs)
361
+ })
362
+ const addrs = await Promise.race([lookup(bare, { all: true }), timeoutArm])
363
+ if (addrs === _LOOKUP_TIMEOUT) return miss(hostname)
364
+ const addresses = (Array.isArray(addrs) ? addrs : [])
365
+ .map((a) => (a && typeof a.address === 'string' ? a.address : null))
366
+ .filter(Boolean)
367
+ if (addresses.length === 0) return miss(hostname)
368
+ const classifications = addresses.map(classifyIpAddress)
369
+ const classification = _summariseClassification(classifications)
370
+ return {
371
+ resolved: true,
372
+ hostname,
373
+ addresses,
374
+ classification,
375
+ display: `resolves to ${addresses.join(', ')} (${_CLASSIFICATION_LABELS[classification] || classification})`,
376
+ }
377
+ } catch {
378
+ return miss(hostname)
379
+ } finally {
380
+ clearTimer(timer)
381
+ }
382
+ }
383
+
384
+ /**
385
+ * Parse a remote (streamable-HTTP / SSE) MCP server entry (#6821). Claude
386
+ * Code represents these in `~/.claude.json` as `{ "type": "http"|"sse",
387
+ * "url": "https://...", "headers": { ... } }` — no `command`. Returns a
388
+ * normalized `{ name, type, url, headers }` server or null (with a warning)
389
+ * when the entry is unusable. Only http(s) urls are accepted; file:/ws:/etc.
390
+ * are rejected so a config typo can't point the transport at a local socket.
391
+ */
392
+ function parseRemoteEntry(name, entry, { warnings }) {
393
+ const url = typeof entry.url === 'string' ? entry.url.trim() : ''
394
+ if (!url) {
395
+ warnings.push(`Skipping MCP server ${name}: url is required for a remote (http/sse) server`)
396
+ return null
397
+ }
398
+ let parsedUrl
399
+ try {
400
+ parsedUrl = new URL(url)
401
+ } catch {
402
+ warnings.push(`Skipping MCP server ${name}: url is not a valid URL`)
403
+ return null
404
+ }
405
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
406
+ warnings.push(`Skipping MCP server ${name}: url must be http(s) (got ${parsedUrl.protocol})`)
407
+ return null
408
+ }
409
+ // #6834 sharp edge, folded in pre-merge: the cloud-metadata service /
410
+ // link-local range is never a legitimate MCP server. Refused again at
411
+ // request time in MCPRemoteClient for configs that bypass this parser.
412
+ if (isBlockedMetadataHost(parsedUrl.hostname)) {
413
+ warnings.push(`Skipping MCP server ${name}: url targets a cloud-metadata / link-local address (refused)`)
414
+ return null
415
+ }
416
+ const rawType = typeof entry.type === 'string' ? entry.type.trim().toLowerCase() : ''
417
+ // 'sse' selects the legacy HTTP+SSE two-endpoint transport; everything else
418
+ // ('http', 'streamable-http', or an inferred remote with only a url) maps to
419
+ // the modern Streamable HTTP transport.
420
+ const type = rawType === 'sse' ? 'sse' : 'http'
421
+ return {
422
+ name,
423
+ type,
424
+ url,
425
+ headers: coerceHeaders(entry.headers, { warnings, serverName: name }),
426
+ }
427
+ }
428
+
81
429
  /**
82
430
  * Parse a Claude-style MCP config object.
83
431
  *
432
+ * Handles two server shapes (#6821):
433
+ * - stdio: `{ command, args, env }` — spawned as a local child process.
434
+ * - remote: `{ type: 'http'|'sse', url, headers }` — connected over the
435
+ * network. A remote entry is recognised by an explicit `type` of
436
+ * http/streamable-http/sse, or by carrying a `url` without a `command`.
437
+ *
84
438
  * @param {unknown} raw
85
- * @returns {{ servers: Array<{ name: string, command: string, args: string[], env: Record<string, string> }>, warnings: string[] }}
439
+ * @returns {{ servers: Array<object>, warnings: string[] }}
86
440
  */
87
441
  export function parseClaudeMcpConfig(raw) {
88
442
  const warnings = []
@@ -105,7 +459,29 @@ export function parseClaudeMcpConfig(raw) {
105
459
  warnings.push(`Skipping MCP server ${name}: entry must be an object`)
106
460
  continue
107
461
  }
108
- if (typeof entry.command !== 'string' || entry.command.length === 0) {
462
+ const rawType = typeof entry.type === 'string' ? entry.type.trim().toLowerCase() : ''
463
+ const hasCommand = typeof entry.command === 'string' && entry.command.length > 0
464
+ const hasUrl = typeof entry.url === 'string' && entry.url.trim().length > 0
465
+ const isRemote =
466
+ rawType === 'http' || rawType === 'streamable-http' || rawType === 'sse' || (!hasCommand && hasUrl)
467
+ // #7001 review: an entry carrying BOTH a command and a url is AMBIGUOUS —
468
+ // whichever branch wins, the other field is dropped and the caller is never
469
+ // told which transport it actually got. The read path stays lenient (it warns
470
+ // and still resolves a usable server, so a hand-edited config keeps working),
471
+ // but a WRITE escalates every warning to a rejection, so `add_mcp_server`
472
+ // refuses it rather than silently persisting one of the two shapes.
473
+ if (hasCommand && hasUrl) {
474
+ warnings.push(
475
+ `MCP server ${name}: ambiguous config — carries BOTH command (stdio) and url (remote); ` +
476
+ `resolving as ${isRemote ? 'remote (command ignored)' : 'stdio (url ignored)'}. Specify exactly one transport.`,
477
+ )
478
+ }
479
+ if (isRemote) {
480
+ const remote = parseRemoteEntry(name, entry, { warnings })
481
+ if (remote) servers.push(remote)
482
+ continue
483
+ }
484
+ if (!hasCommand) {
109
485
  warnings.push(`Skipping MCP server ${name}: command is required`)
110
486
  continue
111
487
  }
@@ -150,6 +526,17 @@ export function loadClaudeMcpConfig(filePath = defaultClaudeConfigPath()) {
150
526
  }
151
527
 
152
528
  export function toMcpServerMetadata(server) {
529
+ // Remote transport (#6821): expose the transport type + a credential-stripped
530
+ // url + header KEY names only. Header values (bearer tokens, api keys) and any
531
+ // url userinfo/query never appear in metadata that could reach a log or wire.
532
+ if (typeof server.url === 'string' && server.url.length > 0) {
533
+ return Object.freeze({
534
+ name: server.name,
535
+ type: server.type || 'http',
536
+ url: redactMcpUrl(server.url),
537
+ headerKeys: Object.freeze(Object.keys(server.headers || {}).sort()),
538
+ })
539
+ }
153
540
  return Object.freeze({
154
541
  name: server.name,
155
542
  command: server.command,
@@ -157,3 +544,813 @@ export function toMcpServerMetadata(server) {
157
544
  envKeys: Object.freeze(Object.keys(server.env).sort()),
158
545
  })
159
546
  }
547
+
548
+ /**
549
+ * Collect the NAMES of every configured MCP server in an `mcpServers` block,
550
+ * without the exec-oriented validation `parseClaudeMcpConfig` applies.
551
+ *
552
+ * `parseClaudeMcpConfig` is built for the byok stdio exec path — it requires a
553
+ * `command` and drops any entry without one. For pure VISIBILITY (#6820) we
554
+ * want every declared server by name, including remote/HTTP transports (which
555
+ * carry `url`/`type` instead of `command`). So this is deliberately lenient:
556
+ * any key mapping to a non-null object counts. Malformed entries accumulate a
557
+ * warning rather than throwing.
558
+ *
559
+ * @param {unknown} mcpBlock — the `mcpServers` object from a config source
560
+ * @param {{ warnings: string[], source: string }} ctx
561
+ * @returns {string[]} declared server names (order preserved)
562
+ */
563
+ function collectConfiguredNames(mcpBlock, { warnings, source }) {
564
+ const names = []
565
+ if (mcpBlock == null) return names
566
+ if (typeof mcpBlock !== 'object' || Array.isArray(mcpBlock)) {
567
+ warnings.push(`${source}: mcpServers must be an object`)
568
+ return names
569
+ }
570
+ for (const [name, entry] of Object.entries(mcpBlock)) {
571
+ if (!name) {
572
+ warnings.push(`${source}: skipping MCP server with empty name`)
573
+ continue
574
+ }
575
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
576
+ warnings.push(`${source}: skipping MCP server ${name} (entry must be an object)`)
577
+ continue
578
+ }
579
+ names.push(name)
580
+ }
581
+ return names
582
+ }
583
+
584
+ /**
585
+ * Resolve the project-scoped config block Claude Code stores under
586
+ * `projects[<realpath(cwd)>]` in `~/.claude.json`. Claude keys these by the
587
+ * realpath, so try that first and fall back to the literal `cwd` (a cwd that no
588
+ * longer resolves — e.g. a removed test tmp dir — still matches a literal key).
589
+ *
590
+ * @param {unknown} raw — parsed `~/.claude.json`
591
+ * @param {string} cwd
592
+ * @returns {object|null}
593
+ */
594
+ function resolveProjectBlock(raw, cwd) {
595
+ if (!cwd) return null
596
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
597
+ const projects = raw.projects
598
+ if (!projects || typeof projects !== 'object' || Array.isArray(projects)) return null
599
+ let realCwd = cwd
600
+ try {
601
+ realCwd = realpathSync(cwd)
602
+ } catch {
603
+ // cwd may not exist (tests / stale dir) — fall through to the literal key.
604
+ }
605
+ if (Object.prototype.hasOwnProperty.call(projects, realCwd)) return projects[realCwd]
606
+ if (Object.prototype.hasOwnProperty.call(projects, cwd)) return projects[cwd]
607
+ return null
608
+ }
609
+
610
+ /**
611
+ * Discover the CONFIGURED (not live-connected) MCP servers a Claude Code
612
+ * session running in `cwd` would load. This is the honest fallback the
613
+ * claude-tui provider uses (#6820): the interactive TUI communicates over a
614
+ * PTY + hook payloads and exposes NO runtime MCP status, unlike the SDK/CLI
615
+ * stream-json `system/init` event that carries live `mcp_servers` with real
616
+ * connection status. So the TUI path can only report what the config DECLARES.
617
+ *
618
+ * Merges the three sources Claude Code itself reads, deduped by name (first
619
+ * source wins on a name collision, matching read precedence):
620
+ * 1. user/global scope — `mcpServers` at the root of `~/.claude.json`
621
+ * 2. project scope — `projects[<realpath(cwd)>].mcpServers` in `~/.claude.json`
622
+ * 3. project-local — `mcpServers` in `<cwd>/.mcp.json`
623
+ *
624
+ * Never throws: each read is guarded and failures accumulate as warnings, so a
625
+ * corrupt config can't take down session start.
626
+ *
627
+ * @param {string} cwd — the session's working directory
628
+ * @param {{ configPath?: string }} [opts]
629
+ * @returns {{ servers: Array<{ name: string }>, warnings: string[] }}
630
+ */
631
+ export function discoverConfiguredMcpServers(cwd, { configPath = defaultClaudeConfigPath() } = {}) {
632
+ const warnings = []
633
+ const byName = new Map()
634
+ const add = (names) => {
635
+ for (const name of names) {
636
+ if (!byName.has(name)) byName.set(name, { name })
637
+ }
638
+ }
639
+
640
+ const readJson = (filePath, source) => {
641
+ try {
642
+ // statSync before readFileSync so a pathologically large file (see
643
+ // CLAUDE_CONFIG_MAX_BYTES) doesn't block session start.
644
+ const stat = statSync(filePath)
645
+ if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
646
+ warnings.push(
647
+ `MCP config ${filePath} exceeds size cap (${stat.size} bytes > ${CLAUDE_CONFIG_MAX_BYTES} bytes); skipping load`,
648
+ )
649
+ return null
650
+ }
651
+ return JSON.parse(readFileSync(filePath, 'utf8'))
652
+ } catch (err) {
653
+ warnings.push(`${source}: failed to read ${filePath}: ${err?.message || String(err)}`)
654
+ return null
655
+ }
656
+ }
657
+
658
+ // 1 + 2 — ~/.claude.json global root + project-scoped block.
659
+ if (configPath && existsSync(configPath)) {
660
+ const raw = readJson(configPath, 'user config')
661
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
662
+ add(collectConfiguredNames(raw.mcpServers, { warnings, source: 'user config mcpServers' }))
663
+ const projectBlock = resolveProjectBlock(raw, cwd)
664
+ if (projectBlock && typeof projectBlock === 'object' && !Array.isArray(projectBlock)) {
665
+ add(collectConfiguredNames(projectBlock.mcpServers, {
666
+ warnings,
667
+ source: 'project config mcpServers',
668
+ }))
669
+ }
670
+ }
671
+ }
672
+
673
+ // 3 — <cwd>/.mcp.json project-local.
674
+ if (cwd) {
675
+ const mcpJsonPath = join(cwd, '.mcp.json')
676
+ if (existsSync(mcpJsonPath)) {
677
+ const raw = readJson(mcpJsonPath, 'project .mcp.json')
678
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
679
+ add(collectConfiguredNames(raw.mcpServers, {
680
+ warnings,
681
+ source: 'project .mcp.json mcpServers',
682
+ }))
683
+ }
684
+ }
685
+ }
686
+
687
+ return { servers: [...byName.values()], warnings }
688
+ }
689
+
690
+ // ---------------------------------------------------------------------------
691
+ // #6974 — MCP server add/remove (config MUTATION).
692
+ //
693
+ // Everything above this line READS. This section is the only write path into
694
+ // `~/.claude.json`, a file this module's header explicitly calls out as "owned
695
+ // by Claude Code, not by us". We are a guest in someone else's file, so the
696
+ // rules below are deliberately conservative:
697
+ //
698
+ // 1. READ-MODIFY-WRITE, never generate. We parse the whole file, touch only
699
+ // the one `mcpServers` key we were asked to, and write the rest back
700
+ // byte-equivalent. Any key Claude Code owns (projects, history,
701
+ // oauthAccount, …) survives untouched.
702
+ // 2. BAIL on a malformed file — never clobber. If the existing config is
703
+ // unparseable we refuse the mutation with a clear error rather than
704
+ // "recovering" by overwriting it with a fresh object. A user whose config
705
+ // we cannot read is a user whose config we must not destroy.
706
+ // 3. ATOMIC + durable write (temp file + fsync + rename + parent-dir fsync).
707
+ // A crash mid-write leaves the original file intact, never a truncated
708
+ // one. See writeClaudeConfigAtomic for the mode-preservation rationale.
709
+ // 4. Persist only NORMALIZED entries. What lands on disk is rebuilt from
710
+ // `parseClaudeMcpConfig`'s output, not copied from the caller's payload,
711
+ // so a client cannot inject arbitrary keys into the user's config.
712
+ //
713
+ // Note on execution: adding a server does NOT itself execute anything. The
714
+ // live-fleet wiring (byok-mcp-fleet `addServer`) spawns through the SAME
715
+ // first-use trust gate as any other server, so the user still gets the
716
+ // `requestMcpTrust` prompt before a new command runs (#4457).
717
+ // ---------------------------------------------------------------------------
718
+
719
+ /**
720
+ * Charset for a NEWLY ADDED MCP server name: a lowercase identifier — leading
721
+ * lowercase letter, then lowercase letters / digits / dash / underscore, max 64
722
+ * chars. Mirrors the `PROVIDER_ID_RE` "lowercase identifier" rule in
723
+ * anthropic-compatible-config.js, widened by `_` because real MCP server names
724
+ * use it (`ccd_session_mgmt`).
725
+ *
726
+ * Being a strict allow-list, this also forecloses a family of problems for free:
727
+ * no `.` or `/` (so a name can never read as a path or traverse), no uppercase
728
+ * (so two names can't collide case-insensitively), and no whitespace/control
729
+ * characters (so a name can't be visually spoofed in the picker).
730
+ */
731
+ export const MCP_SERVER_NAME_RE = /^[a-z][a-z0-9_-]{0,63}$/
732
+
733
+ /**
734
+ * Names that must never be used as an object key we assign into, regardless of
735
+ * charset — assigning these shadows or mutates object internals. `__proto__` is
736
+ * already refused by MCP_SERVER_NAME_RE (leading `_`), but `constructor` and
737
+ * `prototype` are pure lowercase letters and WOULD pass it, so they are refused
738
+ * explicitly here. Also applied on the removal path, which uses a laxer charset.
739
+ */
740
+ const UNSAFE_MCP_SERVER_NAMES = new Set(['__proto__', 'constructor', 'prototype'])
741
+
742
+ /**
743
+ * Upper bound on a removable name. Removal accepts a much laxer charset than
744
+ * `add` (see validateMcpServerNameForRemoval) so a server the `claude` CLI
745
+ * created under a name Chroxy would not have minted is still removable.
746
+ */
747
+ const MCP_SERVER_NAME_MAX = 256
748
+
749
+ /**
750
+ * Validate a name for ADDING a server: the strict lowercase-identifier rule.
751
+ *
752
+ * Beyond the charset there is one non-obvious hard constraint: the name must not
753
+ * contain `__`. MCP tools are namespaced on the wire as `mcp__<server>__<tool>`
754
+ * and `parseMcpToolName` (src/mcp-tools.js) splits on the FIRST `__` after the
755
+ * prefix — so a server named `a__b` would have its tools parsed as server `a`,
756
+ * tool `b__…`, silently routing calls to the wrong (or a nonexistent) server.
757
+ * Refuse it at the door rather than persisting a name that mis-routes.
758
+ *
759
+ * @param {unknown} name
760
+ * @returns {{ ok: true, name: string } | { ok: false, error: string }}
761
+ */
762
+ export function validateNewMcpServerName(name) {
763
+ if (typeof name !== 'string' || name.length === 0) {
764
+ return { ok: false, error: 'MCP server name is required' }
765
+ }
766
+ if (UNSAFE_MCP_SERVER_NAMES.has(name)) {
767
+ return { ok: false, error: `MCP server name '${name}' is reserved` }
768
+ }
769
+ if (!MCP_SERVER_NAME_RE.test(name)) {
770
+ return {
771
+ ok: false,
772
+ error:
773
+ `Invalid MCP server name ${JSON.stringify(name)}: expected a lowercase identifier ` +
774
+ '(letters, digits, dash, underscore; must start with a letter, max 64 chars)',
775
+ }
776
+ }
777
+ if (name.includes('__')) {
778
+ return {
779
+ ok: false,
780
+ error:
781
+ `Invalid MCP server name ${JSON.stringify(name)}: '__' is the MCP tool-namespace ` +
782
+ 'separator (mcp__<server>__<tool>) and would mis-route this server\'s tools',
783
+ }
784
+ }
785
+ return { ok: true, name }
786
+ }
787
+
788
+ /**
789
+ * Validate a name for REMOVING a server. Deliberately laxer than the add rule:
790
+ * a server configured by the `claude` CLI (or hand-edited) may carry a name
791
+ * Chroxy would never mint — uppercase, dots, whatever — and the user must still
792
+ * be able to remove it. So this only refuses what is genuinely unsafe to use as
793
+ * a lookup/delete key: empty, over-long, control characters, or a reserved key.
794
+ * Removal cannot create anything, so no charset policy is warranted.
795
+ *
796
+ * @param {unknown} name
797
+ * @returns {{ ok: true, name: string } | { ok: false, error: string }}
798
+ */
799
+ export function validateMcpServerNameForRemoval(name) {
800
+ if (typeof name !== 'string' || name.length === 0) {
801
+ return { ok: false, error: 'MCP server name is required' }
802
+ }
803
+ if (name.length > MCP_SERVER_NAME_MAX) {
804
+ return { ok: false, error: `MCP server name exceeds ${MCP_SERVER_NAME_MAX} characters` }
805
+ }
806
+ if (UNSAFE_MCP_SERVER_NAMES.has(name)) {
807
+ return { ok: false, error: `MCP server name '${name}' is reserved` }
808
+ }
809
+ if (/[\x00-\x1f\x7f]/.test(name)) {
810
+ return { ok: false, error: 'MCP server name must not contain control characters' }
811
+ }
812
+ return { ok: true, name }
813
+ }
814
+
815
+ /**
816
+ * Validate + normalize a proposed server config into the exact object to
817
+ * persist. Validation is delegated to `parseClaudeMcpConfig` — the SAME parser
818
+ * the read path uses — by round-tripping a single-entry probe block through it,
819
+ * so a config we accept for writing is by construction a config we can read
820
+ * back. Two deliberate tightenings over the read path:
821
+ *
822
+ * - the read path is LENIENT (it coerces a bad `args[3]` away with a warning
823
+ * and carries on, because a partly-usable config beats no session). A WRITE
824
+ * must not silently persist something other than what the user asked for, so
825
+ * ANY warning is escalated to a rejection.
826
+ * - the persisted entry is rebuilt from the parser's normalized output, so
827
+ * unknown/extra keys in the caller's payload are dropped rather than written
828
+ * into the user's config.
829
+ *
830
+ * @param {string} name — already validated by validateNewMcpServerName
831
+ * @param {unknown} config
832
+ * @returns {{ ok: true, entry: object } | { ok: false, error: string }}
833
+ */
834
+ export function normalizeMcpServerConfig(name, config) {
835
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
836
+ return { ok: false, error: 'MCP server config must be an object' }
837
+ }
838
+ // A computed key always defines an OWN property (unlike a literal
839
+ // `__proto__:`), and `name` is validated upstream, so this probe cannot be
840
+ // turned into a prototype write.
841
+ const { servers, warnings } = parseClaudeMcpConfig({ mcpServers: { [name]: config } })
842
+ if (servers.length !== 1) {
843
+ return {
844
+ ok: false,
845
+ error: warnings[0] || `config for '${name}' is not a usable MCP server entry`,
846
+ }
847
+ }
848
+ if (warnings.length > 0) return { ok: false, error: warnings[0] }
849
+
850
+ const parsed = servers[0]
851
+ // Remote (http/sse) transport — persist type + url + non-empty headers only.
852
+ if (typeof parsed.url === 'string' && parsed.url.length > 0) {
853
+ const entry = { type: parsed.type, url: parsed.url }
854
+ if (Object.keys(parsed.headers || {}).length > 0) entry.headers = { ...parsed.headers }
855
+ return { ok: true, entry }
856
+ }
857
+ // stdio transport — persist command + non-empty args/env only, so a minimal
858
+ // add produces a minimal diff in the user's file.
859
+ const entry = { command: parsed.command }
860
+ if (parsed.args.length > 0) entry.args = [...parsed.args]
861
+ if (Object.keys(parsed.env || {}).length > 0) entry.env = { ...parsed.env }
862
+ return { ok: true, entry }
863
+ }
864
+
865
+ /**
866
+ * Read `~/.claude.json` for a read-modify-write cycle.
867
+ *
868
+ * Unlike `loadClaudeMcpConfig` (which fails OPEN — a corrupt config yields an
869
+ * empty server list so session start survives), this fails CLOSED: a file we
870
+ * cannot parse is a file we must not overwrite, so every unreadable/malformed
871
+ * case returns `ok: false` and the caller aborts the mutation. A MISSING file is
872
+ * not an error — it is the first-write case and yields an empty object.
873
+ *
874
+ * @param {string} filePath
875
+ * @returns {{ ok: true, raw: object, mode: number|null, existed: boolean } | { ok: false, error: string }}
876
+ */
877
+ export function readClaudeConfigForMutation(filePath) {
878
+ if (!filePath) return { ok: false, error: 'No Claude config path resolved' }
879
+ if (!existsSync(filePath)) {
880
+ // First write — we create the file. `mode: null` tells the writer to use a
881
+ // fresh-file default (0600) rather than preserving anything.
882
+ return { ok: true, raw: {}, mode: null, existed: false }
883
+ }
884
+ let stat
885
+ try {
886
+ stat = statSync(filePath)
887
+ } catch (err) {
888
+ return { ok: false, error: `Cannot stat ${filePath}: ${err?.message || String(err)}` }
889
+ }
890
+ if (stat.size > CLAUDE_CONFIG_MAX_BYTES) {
891
+ return {
892
+ ok: false,
893
+ error: `Config ${filePath} exceeds the ${CLAUDE_CONFIG_MAX_BYTES}-byte cap (${stat.size} bytes); refusing to rewrite it`,
894
+ }
895
+ }
896
+ let text
897
+ try {
898
+ text = readFileSync(filePath, 'utf8')
899
+ } catch (err) {
900
+ return { ok: false, error: `Cannot read ${filePath}: ${err?.message || String(err)}` }
901
+ }
902
+ let raw
903
+ try {
904
+ raw = JSON.parse(text)
905
+ } catch {
906
+ // The parser's message can quote surrounding bytes (which may include a
907
+ // token from elsewhere in the file), so it is deliberately NOT echoed.
908
+ return {
909
+ ok: false,
910
+ error: `Config ${filePath} is not valid JSON; refusing to overwrite it. Fix or move the file, then retry.`,
911
+ }
912
+ }
913
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
914
+ return { ok: false, error: `Config ${filePath} root must be a JSON object; refusing to overwrite it` }
915
+ }
916
+ return { ok: true, raw, mode: stat.mode & 0o777, existed: true }
917
+ }
918
+
919
+ /**
920
+ * #7002 — resolve the path the atomic write must actually LAND on.
921
+ *
922
+ * The write is `writeFileSync(tmp)` → `renameSync(tmp, dest)`, and `rename(2)`
923
+ * replaces the FINAL PATH COMPONENT itself. If that component is a symlink — the
924
+ * common dotfiles-repo arrangement, `~/.claude.json` → `~/dotfiles/claude.json` —
925
+ * the rename destroys the LINK and leaves a regular file in its place: the user's
926
+ * dotfiles link silently disappears and their real config stops receiving
927
+ * updates. (The read path follows the link, so nothing complains.) So a symlinked
928
+ * destination must be resolved to its target and written THERE.
929
+ *
930
+ * TRUST ASSUMPTION, stated plainly: `~/.claude.json` and any link the user has
931
+ * put in its place are USER-OWNED, USER-AUTHORED configuration. We follow the
932
+ * link because a user who symlinked their own config meant it. What we do NOT do
933
+ * is follow it blindly — resolving a symlink and writing to whatever it points at
934
+ * is precisely how a planted link turns "write my config" into "write an arbitrary
935
+ * file", so the resolved target must satisfy all of:
936
+ *
937
+ * - it resolves at all (a DANGLING link is refused, not materialized — creating
938
+ * the missing target would be us inventing a file at an attacker-chosen path)
939
+ * - it is a REGULAR file (no directory, fifo, socket or device)
940
+ * - it is owned by the uid we run as (a link into another user's file is refused)
941
+ *
942
+ * RACE HONESTY: resolution happens ONCE, and the subsequent `rename` re-walks the
943
+ * path by name, so an attacker who can replace the link between the two syscalls
944
+ * can still redirect the write (classic TOCTOU). This is NOT closed here — POSIX
945
+ * offers no "rename onto this exact inode" primitive to close it with. The
946
+ * residual exposure requires write access to the user's own `$HOME`, which is
947
+ * already game over for a config the daemon reads and executes commands from;
948
+ * see the follow-up issue referenced in the PR for a fully race-free design.
949
+ *
950
+ * @param {string} filePath
951
+ * @returns {{ ok: true, path: string, viaSymlink: boolean } | { ok: false, error: string }}
952
+ */
953
+ export function resolveClaudeConfigWritePath(filePath) {
954
+ let link
955
+ try {
956
+ link = lstatSync(filePath)
957
+ } catch {
958
+ // Missing (the first-write case) or unstattable — write the path as given,
959
+ // exactly as before this fix.
960
+ return { ok: true, path: filePath, viaSymlink: false }
961
+ }
962
+ if (!link.isSymbolicLink()) return { ok: true, path: filePath, viaSymlink: false }
963
+
964
+ let resolved
965
+ try {
966
+ resolved = realpathSync(filePath)
967
+ } catch (err) {
968
+ return {
969
+ ok: false,
970
+ error: `${filePath} is a symlink whose target cannot be resolved (${err?.code || err?.message || String(err)}); refusing to replace the link with a regular file. Fix or remove the link, then retry.`,
971
+ }
972
+ }
973
+ let target
974
+ try {
975
+ target = lstatSync(resolved)
976
+ } catch (err) {
977
+ return {
978
+ ok: false,
979
+ error: `${filePath} is a symlink to ${resolved}, which cannot be stat'd (${err?.code || err?.message || String(err)}); refusing to write through it.`,
980
+ }
981
+ }
982
+ if (!target.isFile()) {
983
+ return {
984
+ ok: false,
985
+ error: `${filePath} is a symlink to ${resolved}, which is not a regular file; refusing to write through it.`,
986
+ }
987
+ }
988
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
989
+ if (uid !== null && target.uid !== uid) {
990
+ return {
991
+ ok: false,
992
+ error: `${filePath} is a symlink to ${resolved}, which is owned by uid ${target.uid} rather than uid ${uid}; refusing to write through it.`,
993
+ }
994
+ }
995
+ return { ok: true, path: resolved, viaSymlink: true }
996
+ }
997
+
998
+ /**
999
+ * #7002 — the residual risk of PRESERVING a destination's mode.
1000
+ *
1001
+ * `writeClaudeConfigAtomic` deliberately does not force 0600 on a file the user
1002
+ * (or Claude Code) already owns. That is the right call for permissions, but it
1003
+ * leaves one case where Chroxy is the party making things worse: an existing
1004
+ * config that is group/world-readable, plus a new entry carrying `env` or
1005
+ * `headers` — the two fields that routinely hold API tokens. We do not silently
1006
+ * re-permission the file; we say so loudly instead, naming the file and its mode,
1007
+ * so the user can tighten it themselves.
1008
+ *
1009
+ * Returns `null` when there is nothing to warn about (owner-only mode, no
1010
+ * secret-bearing field, or a file WE created — those get 0600). The message never
1011
+ * echoes a secret VALUE, only the field names.
1012
+ *
1013
+ * @param {{ filePath: string, mode: number|null|undefined, entry: object }} args
1014
+ * @returns {string|null}
1015
+ */
1016
+ export function describeConfigModeSecretWarning({ filePath, mode, entry } = {}) {
1017
+ if (mode === null || mode === undefined) return null
1018
+ // The trigger is the WHOLE `0o077` superset, not just the read bits, and the
1019
+ // wording says "accessible" rather than "readable" to match it (review of
1020
+ // #7040). Group/other WRITE is the sharper edge, not a lesser one: another
1021
+ // local user who can rewrite `~/.claude.json` substitutes MCP server commands
1022
+ // the daemon then spawns. Including the (meaningless-on-a-JSON-file) execute
1023
+ // bit costs at most a harmless false positive on a pathological mode like
1024
+ // 0o611, which is the right side to err on for a security advisory.
1025
+ const otherBits = mode & 0o077
1026
+ if (otherBits === 0) return null
1027
+ const fields = ['env', 'headers'].filter((key) => {
1028
+ const value = entry?.[key]
1029
+ return value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0
1030
+ })
1031
+ if (fields.length === 0) return null
1032
+ const octal = (mode & 0o777).toString(8).padStart(3, '0')
1033
+ return (
1034
+ `${filePath} is mode ${octal} (accessible beyond its owner) and the MCP server entry just added carries ` +
1035
+ `${fields.join(' and ')}, which commonly hold API tokens. Chroxy preserved the file's existing permissions ` +
1036
+ `rather than changing them — tighten it yourself with: chmod 600 ${filePath}`
1037
+ )
1038
+ }
1039
+
1040
+ /**
1041
+ * Atomically write the mutated config back.
1042
+ *
1043
+ * temp file → exact mode → fsync(file) → rename → fsync(parent dir), the same
1044
+ * shape as `writeFileRestricted(..., { durable: true })` in platform.js, with
1045
+ * one deliberate difference: this PRESERVES the destination's existing mode
1046
+ * instead of forcing 0600. `~/.claude.json` belongs to Claude Code; silently
1047
+ * re-permissioning a user's file as a side effect of "add an MCP server" is not
1048
+ * ours to do. A file we CREATE gets 0600 (it can hold OAuth material).
1049
+ *
1050
+ * The write is durable (fsync before rename, dir fsync after) on BOTH add and
1051
+ * remove. Remove is the load-bearing case — it is a capability REDUCTION, and
1052
+ * the #6914/#6927 precedent is that a security-tightening write must survive
1053
+ * power loss rather than silently reappearing after a crash. Add rides the same
1054
+ * path because one code path is cheaper to keep correct than two, and the cost
1055
+ * (one fsync of a few KB, on an operation a user performs rarely) is noise.
1056
+ *
1057
+ * A SYMLINKED destination is written THROUGH (the link survives, its target gets
1058
+ * the bytes) or refused — never replaced. See `resolveClaudeConfigWritePath` for
1059
+ * the trust assumption and the race caveat (#7002).
1060
+ *
1061
+ * SHARED, not byok-local: `claude-tui/pty-driver.js`'s `ensureCwdTrusted` (the
1062
+ * DEFAULT provider's trust pre-write, which runs on far more start()s than any
1063
+ * MCP mutation) commits through this function too (#7046). Callers that need
1064
+ * "best effort" — a refusal must not fail session start — catch and log; callers
1065
+ * that owe the user an answer surface the error.
1066
+ *
1067
+ * #7054: the post-rename directory fsync no longer THROWS. The rename has
1068
+ * already published the file, so a dir-fsync failure means the write LANDED and
1069
+ * only its directory entry's durability is unproven — throwing reported a landed
1070
+ * write as failed (#7067). It is returned instead; callers on a
1071
+ * capability-REDUCTION path propagate it (see `removeMcpServerFromConfig`).
1072
+ *
1073
+ * @param {string} filePath
1074
+ * @param {object} value — the full config object to serialize
1075
+ * @param {{ mode: number|null }} opts — `null` mode = new file, use 0600
1076
+ * @returns {{ durabilityUnconfirmed: string | null }}
1077
+ */
1078
+ export function writeClaudeConfigAtomic(filePath, value, { mode }) {
1079
+ const resolved = resolveClaudeConfigWritePath(filePath)
1080
+ if (!resolved.ok) throw new Error(resolved.error)
1081
+ // Everything below targets the RESOLVED path: the sidecar has to live in the
1082
+ // target's directory (rename is only atomic within one filesystem, and a
1083
+ // dotfiles target is frequently on a different one from $HOME), and the
1084
+ // dir-fsync has to be the target's directory too.
1085
+ const destPath = resolved.path
1086
+ const payload = `${JSON.stringify(value, null, 2)}\n`
1087
+ const targetMode = mode === null || mode === undefined ? 0o600 : mode
1088
+ // Per-call random suffix, NOT process.pid: concurrent sessions in one daemon
1089
+ // share a pid and would race for the same sidecar path (#3922).
1090
+ const tmpPath = `${destPath}.chroxy.${randomUUID()}.tmp`
1091
+ try {
1092
+ // `mode` is only honoured on create, and umask can strip bits from it — so
1093
+ // restate the exact mode afterwards. The intermediate mode can only ever be
1094
+ // TIGHTER than the target (umask removes bits, never adds), so there is no
1095
+ // window in which the temp file is more permissive than the destination
1096
+ // already was.
1097
+ writeFileSync(tmpPath, payload, { mode: targetMode })
1098
+ chmodSync(tmpPath, targetMode)
1099
+ fsyncForDurability(tmpPath)
1100
+ } catch (err) {
1101
+ try { unlinkSync(tmpPath) } catch { /* nothing to clean up */ }
1102
+ throw err
1103
+ }
1104
+ // A failing rename (EXDEV, FS quota, ACL) would otherwise leave the sidecar
1105
+ // behind — and this sidecar is not inert: it holds the full config, including
1106
+ // any `env` / `headers` the caller just supplied. Unlink it and re-throw the
1107
+ // ORIGINAL rename error, not a cleanup-side ENOENT. Same shape as the #4463 fix
1108
+ // in byok-mcp-trust.js `recordTrust`.
1109
+ try {
1110
+ renameSync(tmpPath, destPath)
1111
+ } catch (err) {
1112
+ try { unlinkSync(tmpPath) } catch { /* may already be gone */ }
1113
+ throw err
1114
+ }
1115
+ // Make the rename itself durable, not just the bytes it points at.
1116
+ //
1117
+ // #7054/#7067: this used to be an UNWRAPPED call, so a post-rename
1118
+ // directory-fsync failure THREW — after the rename had already published the
1119
+ // file. The write succeeded; only its directory entry's durability was
1120
+ // unproven. Both callers were harmed by that lie: `ensureCwdTrusted` treats a
1121
+ // throw as "skip the pre-write", so the user got claude's trust dialog for a
1122
+ // trust write that had actually landed; the MCP add/remove paths reported a
1123
+ // failure for a config change that was on disk. Shared verdict now — report,
1124
+ // never throw — via the one implementation in platform.js.
1125
+ return confirmRenameDurable(destPath, { durable: true })
1126
+ }
1127
+
1128
+ /**
1129
+ * Resolve the `projects` key under which cwd's config block lives, for a WRITE.
1130
+ *
1131
+ * Claude Code keys project blocks by `realpath(cwd)`. Reads tolerate either
1132
+ * spelling (see resolveProjectBlock), so a write must target the key that
1133
+ * ALREADY exists — writing the realpath when a literal-cwd key is present would
1134
+ * create a second, shadowed block that the read path never reaches. Falls back
1135
+ * to the realpath (or literal cwd, if it does not resolve) as the key to create.
1136
+ *
1137
+ * @param {object} raw — parsed config
1138
+ * @param {string} cwd
1139
+ * @returns {string} the projects key to read/write
1140
+ */
1141
+ function resolveProjectKeyForWrite(raw, cwd) {
1142
+ let realCwd = cwd
1143
+ try {
1144
+ realCwd = realpathSync(cwd)
1145
+ } catch {
1146
+ // cwd may not resolve (removed dir) — the literal key is the best we have.
1147
+ }
1148
+ const projects = raw?.projects
1149
+ if (projects && typeof projects === 'object' && !Array.isArray(projects)) {
1150
+ if (Object.prototype.hasOwnProperty.call(projects, realCwd)) return realCwd
1151
+ if (Object.prototype.hasOwnProperty.call(projects, cwd)) return cwd
1152
+ }
1153
+ return realCwd
1154
+ }
1155
+
1156
+ /** The config scopes a mutation may target. */
1157
+ export const MCP_WRITE_SCOPES = Object.freeze(['user', 'project'])
1158
+
1159
+ /**
1160
+ * Why `.mcp.json` is NOT a writable scope: the third read source
1161
+ * (`<cwd>/.mcp.json`) is a project-local file that is normally checked into the
1162
+ * user's git repository. Mutating it from a chat client would dirty their
1163
+ * working tree and could land in a commit unnoticed. Both writable scopes live
1164
+ * in `~/.claude.json`, which is machine-local user state.
1165
+ */
1166
+
1167
+ /**
1168
+ * Everything `addMcpServerToConfig` does EXCEPT the write: validate the name and
1169
+ * scope, normalize the config, read the existing file, locate the target block,
1170
+ * and refuse a duplicate name. Returns the located block + parsed tree so the
1171
+ * caller can either commit (write) or discard (plan).
1172
+ *
1173
+ * Split out for #7001's deny-before-write ordering: the trust prompt has to run
1174
+ * BEFORE anything is persisted, and prompting for an add that was going to fail
1175
+ * validation or EXISTS anyway is both bad UX and a needless prompt. `raw` is a
1176
+ * per-call freshly-parsed tree, so the plan path mutating it (creating an empty
1177
+ * `mcpServers` block) is discarded harmlessly.
1178
+ *
1179
+ * The commit path re-runs this, so the read→check→write critical section stays
1180
+ * synchronous and `await`-free: a plan result is ADVISORY, never the authority.
1181
+ */
1182
+ function prepareAddMcpServer({ name, config, scope = 'user', cwd, configPath = defaultClaudeConfigPath() } = {}) {
1183
+ const validName = validateNewMcpServerName(name)
1184
+ if (!validName.ok) return { ok: false, error: validName.error }
1185
+ if (!MCP_WRITE_SCOPES.includes(scope)) {
1186
+ return { ok: false, error: `Unknown MCP config scope '${scope}' (expected 'user' or 'project')` }
1187
+ }
1188
+ if (scope === 'project' && (typeof cwd !== 'string' || cwd.length === 0)) {
1189
+ return { ok: false, error: 'Project scope requires a session working directory' }
1190
+ }
1191
+ const normalized = normalizeMcpServerConfig(validName.name, config)
1192
+ if (!normalized.ok) return { ok: false, error: normalized.error }
1193
+
1194
+ // Read-modify-write, synchronously and with no `await` in between, so the
1195
+ // window in which a concurrent `claude` CLI edit could be lost is the syscall
1196
+ // span rather than an event-loop turn. (A cross-process lock is not available
1197
+ // — `claude` takes none — so narrowing the window is the honest ceiling.)
1198
+ const read = readClaudeConfigForMutation(configPath)
1199
+ if (!read.ok) return { ok: false, error: read.error }
1200
+ const raw = read.raw
1201
+
1202
+ let block
1203
+ if (scope === 'user') {
1204
+ if (raw.mcpServers != null && (typeof raw.mcpServers !== 'object' || Array.isArray(raw.mcpServers))) {
1205
+ return { ok: false, error: 'Existing user-scope mcpServers is not an object; refusing to replace it' }
1206
+ }
1207
+ if (raw.mcpServers == null) raw.mcpServers = {}
1208
+ block = raw.mcpServers
1209
+ } else {
1210
+ if (raw.projects != null && (typeof raw.projects !== 'object' || Array.isArray(raw.projects))) {
1211
+ return { ok: false, error: 'Existing projects block is not an object; refusing to replace it' }
1212
+ }
1213
+ if (raw.projects == null) raw.projects = {}
1214
+ const key = resolveProjectKeyForWrite(raw, cwd)
1215
+ const existing = raw.projects[key]
1216
+ if (existing != null && (typeof existing !== 'object' || Array.isArray(existing))) {
1217
+ return { ok: false, error: `Existing project block for ${key} is not an object; refusing to replace it` }
1218
+ }
1219
+ // Preserve every other key Claude Code keeps on the project block
1220
+ // (allowedTools, history, …) — only mcpServers is ours to touch.
1221
+ if (existing == null) raw.projects[key] = {}
1222
+ const projectBlock = raw.projects[key]
1223
+ if (projectBlock.mcpServers != null && (typeof projectBlock.mcpServers !== 'object' || Array.isArray(projectBlock.mcpServers))) {
1224
+ return { ok: false, error: `Existing project-scope mcpServers for ${key} is not an object; refusing to replace it` }
1225
+ }
1226
+ if (projectBlock.mcpServers == null) projectBlock.mcpServers = {}
1227
+ block = projectBlock.mcpServers
1228
+ }
1229
+
1230
+ if (Object.prototype.hasOwnProperty.call(block, validName.name)) {
1231
+ return {
1232
+ ok: false,
1233
+ code: 'EXISTS',
1234
+ error: `An MCP server named '${validName.name}' already exists in ${scope} scope. Remove it first to replace it.`,
1235
+ }
1236
+ }
1237
+ return { ok: true, raw, block, mode: read.mode, entry: normalized.entry, scope, name: validName.name, configPath }
1238
+ }
1239
+
1240
+ /**
1241
+ * #7001: DRY-RUN of an add — every check `addMcpServerToConfig` performs, with no
1242
+ * write. Returns the exact normalized `entry` that WOULD be persisted, so a caller
1243
+ * can obtain the user's spawn-trust decision for that precise config before
1244
+ * anything reaches disk (a denied add must leave no config entry behind).
1245
+ *
1246
+ * @returns {{ ok: true, entry: object, scope: string } | { ok: false, error: string, code?: string }}
1247
+ */
1248
+ export function planAddMcpServerToConfig(opts = {}) {
1249
+ const prepared = prepareAddMcpServer(opts)
1250
+ if (!prepared.ok) return prepared.code ? { ok: false, error: prepared.error, code: prepared.code } : { ok: false, error: prepared.error }
1251
+ return { ok: true, entry: prepared.entry, scope: prepared.scope }
1252
+ }
1253
+
1254
+ /**
1255
+ * Add (or refuse to overwrite) one MCP server in the user's config.
1256
+ *
1257
+ * Scope selects WHERE: 'user' → the root `mcpServers` block; 'project' →
1258
+ * `projects[<realpath(cwd)>].mcpServers`. There is no "wherever it fits"
1259
+ * fallback — an ambiguous write to a user's config is worse than an error.
1260
+ *
1261
+ * Refuses (rather than overwrites) an existing name in the target scope: an
1262
+ * overwrite would silently replace a command the user trusts with a different
1263
+ * one, which is exactly the substitution the trust store exists to prevent.
1264
+ *
1265
+ * NOTE (#7001): this is the COMMIT. On the WS add path the caller must already
1266
+ * have obtained the user's spawn-trust decision (via `planAddMcpServerToConfig`)
1267
+ * — persisting first and prompting afterwards leaves a denied server configured.
1268
+ *
1269
+ * @param {object} opts
1270
+ * @param {string} opts.name
1271
+ * @param {unknown} opts.config
1272
+ * @param {'user'|'project'} [opts.scope]
1273
+ * @param {string} [opts.cwd] — required for scope 'project'
1274
+ * @param {string} [opts.configPath]
1275
+ * @returns {{ ok: true, entry: object, scope: string, warning?: string } | { ok: false, error: string, code?: string }}
1276
+ */
1277
+ export function addMcpServerToConfig(opts = {}) {
1278
+ const prepared = prepareAddMcpServer(opts)
1279
+ if (!prepared.ok) return prepared.code ? { ok: false, error: prepared.error, code: prepared.code } : { ok: false, error: prepared.error }
1280
+ prepared.block[prepared.name] = prepared.entry
1281
+ writeClaudeConfigAtomic(prepared.configPath, prepared.raw, { mode: prepared.mode })
1282
+ // #7002: computed from the mode we just PRESERVED and the entry we just wrote,
1283
+ // so it only fires when Chroxy is the party that put secret material into a
1284
+ // group/world-readable file. Advisory — we still do not re-permission the file.
1285
+ const warning = describeConfigModeSecretWarning({
1286
+ filePath: prepared.configPath,
1287
+ mode: prepared.mode,
1288
+ entry: prepared.entry,
1289
+ })
1290
+ const result = { ok: true, entry: prepared.entry, scope: prepared.scope }
1291
+ if (warning) result.warning = warning
1292
+ return result
1293
+ }
1294
+
1295
+ /**
1296
+ * Remove one MCP server from the user's config, in the named scope only.
1297
+ *
1298
+ * Returns `found: false` (no write performed) when the name is absent from the
1299
+ * REQUESTED scope, even if it exists in the other one — a remove that silently
1300
+ * jumped scope could delete a shared user-scope server when the caller meant to
1301
+ * detach a project-scope one. The caller surfaces the scope in its error so a
1302
+ * client can retry against the right one.
1303
+ *
1304
+ * @param {object} opts
1305
+ * @param {string} opts.name
1306
+ * @param {'user'|'project'} [opts.scope]
1307
+ * @param {string} [opts.cwd] — required for scope 'project'
1308
+ * @param {string} [opts.configPath]
1309
+ * @returns {{ ok: true, found: boolean, scope: string } | { ok: false, error: string }}
1310
+ */
1311
+ export function removeMcpServerFromConfig({ name, scope = 'user', cwd, configPath = defaultClaudeConfigPath() } = {}) {
1312
+ const validName = validateMcpServerNameForRemoval(name)
1313
+ if (!validName.ok) return { ok: false, error: validName.error }
1314
+ if (!MCP_WRITE_SCOPES.includes(scope)) {
1315
+ return { ok: false, error: `Unknown MCP config scope '${scope}' (expected 'user' or 'project')` }
1316
+ }
1317
+ if (scope === 'project' && (typeof cwd !== 'string' || cwd.length === 0)) {
1318
+ return { ok: false, error: 'Project scope requires a session working directory' }
1319
+ }
1320
+
1321
+ const read = readClaudeConfigForMutation(configPath)
1322
+ if (!read.ok) return { ok: false, error: read.error }
1323
+ if (!read.existed) return { ok: true, found: false, scope }
1324
+ const raw = read.raw
1325
+
1326
+ let block = null
1327
+ if (scope === 'user') {
1328
+ if (raw.mcpServers && typeof raw.mcpServers === 'object' && !Array.isArray(raw.mcpServers)) {
1329
+ block = raw.mcpServers
1330
+ }
1331
+ } else {
1332
+ const projects = raw.projects
1333
+ if (projects && typeof projects === 'object' && !Array.isArray(projects)) {
1334
+ const key = resolveProjectKeyForWrite(raw, cwd)
1335
+ const projectBlock = Object.prototype.hasOwnProperty.call(projects, key) ? projects[key] : null
1336
+ if (projectBlock && typeof projectBlock === 'object' && !Array.isArray(projectBlock)) {
1337
+ const servers = projectBlock.mcpServers
1338
+ if (servers && typeof servers === 'object' && !Array.isArray(servers)) block = servers
1339
+ }
1340
+ }
1341
+ }
1342
+ if (!block || !Object.prototype.hasOwnProperty.call(block, validName.name)) {
1343
+ // Nothing to do — and crucially, NO write. A no-op remove must not rewrite
1344
+ // the user's file (nor risk clobbering a concurrent edit for nothing).
1345
+ return { ok: true, found: false, scope }
1346
+ }
1347
+
1348
+ delete block[validName.name]
1349
+ const { durabilityUnconfirmed } = writeClaudeConfigAtomic(configPath, raw, { mode: read.mode }) ?? {}
1350
+ // #7054/#7068: REMOVE is the load-bearing durable case — this write is durable
1351
+ // precisely so a capability REDUCTION cannot silently reappear after a power
1352
+ // loss. Dropping the caveat here would sever the only caller-visible signal on
1353
+ // the one path that exists to carry it, which is the same false-green #7068
1354
+ // had to undo on the token revoke. Propagate rather than swallow.
1355
+ return { ok: true, found: true, scope, ...(durabilityUnconfirmed ? { durabilityUnconfirmed } : {}) }
1356
+ }