opencastle 1.0.0 → 1.1.1

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 (118) hide show
  1. package/README.md +9 -4
  2. package/dist/cli/adapters/claude-code.d.ts +8 -4
  3. package/dist/cli/adapters/claude-code.d.ts.map +1 -1
  4. package/dist/cli/adapters/claude-code.js +13 -7
  5. package/dist/cli/adapters/claude-code.js.map +1 -1
  6. package/dist/cli/adapters/codex.d.ts +19 -6
  7. package/dist/cli/adapters/codex.d.ts.map +1 -1
  8. package/dist/cli/adapters/codex.js +24 -7
  9. package/dist/cli/adapters/codex.js.map +1 -1
  10. package/dist/cli/adapters/single-file-base.d.ts +15 -1
  11. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  12. package/dist/cli/adapters/single-file-base.js +46 -21
  13. package/dist/cli/adapters/single-file-base.js.map +1 -1
  14. package/dist/cli/adapters/vscode.d.ts +11 -1
  15. package/dist/cli/adapters/vscode.d.ts.map +1 -1
  16. package/dist/cli/adapters/vscode.js +48 -8
  17. package/dist/cli/adapters/vscode.js.map +1 -1
  18. package/dist/cli/codex-target.test.d.ts +2 -0
  19. package/dist/cli/codex-target.test.d.ts.map +1 -0
  20. package/dist/cli/codex-target.test.js +154 -0
  21. package/dist/cli/codex-target.test.js.map +1 -0
  22. package/dist/cli/command-namespace.d.ts +91 -0
  23. package/dist/cli/command-namespace.d.ts.map +1 -0
  24. package/dist/cli/command-namespace.js +218 -0
  25. package/dist/cli/command-namespace.js.map +1 -0
  26. package/dist/cli/command-namespace.test.d.ts +2 -0
  27. package/dist/cli/command-namespace.test.d.ts.map +1 -0
  28. package/dist/cli/command-namespace.test.js +356 -0
  29. package/dist/cli/command-namespace.test.js.map +1 -0
  30. package/dist/cli/copy.d.ts +1 -1
  31. package/dist/cli/copy.d.ts.map +1 -1
  32. package/dist/cli/copy.js +3 -2
  33. package/dist/cli/copy.js.map +1 -1
  34. package/dist/cli/doctor.d.ts.map +1 -1
  35. package/dist/cli/doctor.js +2 -1
  36. package/dist/cli/doctor.js.map +1 -1
  37. package/dist/cli/doctor.test.js +2 -2
  38. package/dist/cli/doctor.test.js.map +1 -1
  39. package/dist/cli/explain.d.ts.map +1 -1
  40. package/dist/cli/explain.js +13 -1
  41. package/dist/cli/explain.js.map +1 -1
  42. package/dist/cli/github-report.js +1 -1
  43. package/dist/cli/github-report.js.map +1 -1
  44. package/dist/cli/init.d.ts.map +1 -1
  45. package/dist/cli/init.js +45 -10
  46. package/dist/cli/init.js.map +1 -1
  47. package/dist/cli/init.test.js +31 -14
  48. package/dist/cli/init.test.js.map +1 -1
  49. package/dist/cli/managed-paths.d.ts +18 -1
  50. package/dist/cli/managed-paths.d.ts.map +1 -1
  51. package/dist/cli/managed-paths.js +74 -2
  52. package/dist/cli/managed-paths.js.map +1 -1
  53. package/dist/cli/manifest.d.ts.map +1 -1
  54. package/dist/cli/manifest.js +2 -0
  55. package/dist/cli/manifest.js.map +1 -1
  56. package/dist/cli/mcp-audit.d.ts.map +1 -1
  57. package/dist/cli/mcp-audit.js +7 -3
  58. package/dist/cli/mcp-audit.js.map +1 -1
  59. package/dist/cli/mcp-file.d.ts +37 -0
  60. package/dist/cli/mcp-file.d.ts.map +1 -0
  61. package/dist/cli/mcp-file.js +291 -0
  62. package/dist/cli/mcp-file.js.map +1 -0
  63. package/dist/cli/mcp-file.test.d.ts +2 -0
  64. package/dist/cli/mcp-file.test.d.ts.map +1 -0
  65. package/dist/cli/mcp-file.test.js +121 -0
  66. package/dist/cli/mcp-file.test.js.map +1 -0
  67. package/dist/cli/mcp.d.ts +15 -0
  68. package/dist/cli/mcp.d.ts.map +1 -1
  69. package/dist/cli/mcp.js +123 -56
  70. package/dist/cli/mcp.js.map +1 -1
  71. package/dist/cli/remove.d.ts.map +1 -1
  72. package/dist/cli/remove.js +45 -8
  73. package/dist/cli/remove.js.map +1 -1
  74. package/dist/cli/sync-check.d.ts.map +1 -1
  75. package/dist/cli/sync-check.js +26 -7
  76. package/dist/cli/sync-check.js.map +1 -1
  77. package/dist/cli/sync-check.test.js +2 -2
  78. package/dist/cli/sync-check.test.js.map +1 -1
  79. package/dist/cli/types.d.ts +37 -2
  80. package/dist/cli/types.d.ts.map +1 -1
  81. package/dist/cli/types.js +3 -0
  82. package/dist/cli/types.js.map +1 -1
  83. package/dist/cli/unreadable-report.d.ts +7 -0
  84. package/dist/cli/unreadable-report.d.ts.map +1 -1
  85. package/dist/cli/unreadable-report.js +14 -0
  86. package/dist/cli/unreadable-report.js.map +1 -1
  87. package/dist/cli/update.d.ts.map +1 -1
  88. package/dist/cli/update.js +69 -5
  89. package/dist/cli/update.js.map +1 -1
  90. package/package.json +3 -2
  91. package/src/cli/adapters/claude-code.ts +13 -7
  92. package/src/cli/adapters/codex.ts +25 -7
  93. package/src/cli/adapters/single-file-base.ts +66 -26
  94. package/src/cli/adapters/vscode.ts +51 -10
  95. package/src/cli/codex-target.test.ts +178 -0
  96. package/src/cli/command-namespace.test.ts +417 -0
  97. package/src/cli/command-namespace.ts +222 -0
  98. package/src/cli/copy.ts +6 -2
  99. package/src/cli/doctor.test.ts +2 -2
  100. package/src/cli/doctor.ts +3 -2
  101. package/src/cli/explain.ts +13 -1
  102. package/src/cli/github-report.ts +1 -1
  103. package/src/cli/init.test.ts +31 -14
  104. package/src/cli/init.ts +48 -11
  105. package/src/cli/managed-paths.ts +75 -3
  106. package/src/cli/manifest.ts +2 -0
  107. package/src/cli/mcp-audit.ts +7 -3
  108. package/src/cli/mcp-file.test.ts +138 -0
  109. package/src/cli/mcp-file.ts +302 -0
  110. package/src/cli/mcp.ts +130 -60
  111. package/src/cli/remove.ts +40 -8
  112. package/src/cli/sync-check.test.ts +2 -2
  113. package/src/cli/sync-check.ts +23 -6
  114. package/src/cli/types.ts +37 -2
  115. package/src/cli/unreadable-report.ts +14 -0
  116. package/src/cli/update.ts +73 -5
  117. package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
  118. package/src/orchestrator/prompts/bootstrap-customizations.prompt.md +4 -4
@@ -0,0 +1,302 @@
1
+ import { parse as parseToml } from 'smol-toml'
2
+
3
+ /**
4
+ * Reading and writing an MCP config file in whatever language it is written in.
5
+ *
6
+ * Every target but one keeps its servers in JSON. Codex CLI keeps them in
7
+ * `.codex/config.toml`, beside the rest of the project's Codex settings, and
8
+ * OpenCastle wrote `.codex/mcp.json` — a file Codex has never read — so no
9
+ * integration or team server reached Codex at all. The merge, strip, audit and
10
+ * drift logic all work on a parsed object; this is the one place that knows a
11
+ * config can be TOML, so none of them has to.
12
+ *
13
+ * `config.toml` is co-owned the way `opencode.json` is: the user's model,
14
+ * approval and sandbox settings sit beside our servers. Re-serialising it whole
15
+ * would restyle it and drop every comment, so a TOML write changes only the
16
+ * `[mcp_servers.<name>]` tables whose value changed and leaves every other byte
17
+ * as it was.
18
+ */
19
+
20
+ /** Thrown when a TOML config is shaped so that a change cannot be made without rewriting the user's text. */
21
+ export class TomlEditError extends Error {
22
+ constructor(message: string) {
23
+ super(message)
24
+ this.name = 'TomlEditError'
25
+ }
26
+ }
27
+
28
+ export function isTomlConfig(rel: string): boolean {
29
+ return rel.endsWith('.toml')
30
+ }
31
+
32
+ /** Parse a config's text. Throws, as `JSON.parse` does, when it does not parse. */
33
+ export function parseMcpConfigText(text: string, rel: string): Record<string, unknown> {
34
+ if (isTomlConfig(rel)) return plain(parseToml(text)) as Record<string, unknown>
35
+ return JSON.parse(text) as Record<string, unknown>
36
+ }
37
+
38
+ /**
39
+ * The text to write for `value`, given what the file held before (`null` when
40
+ * it is being created).
41
+ */
42
+ export function serialiseMcpConfig(before: string | null, value: Record<string, unknown>, rel: string): string {
43
+ if (isTomlConfig(rel)) return writeToml(before ?? '', value)
44
+ return before === null ? JSON.stringify(value, null, 2) + '\n' : serialiseLike(before, value)
45
+ }
46
+
47
+ // ── JSON ──────────────────────────────────────────────────────
48
+
49
+ /**
50
+ * The indentation a file already uses, so merging into it does not restyle it.
51
+ *
52
+ * `JSON.stringify(x, null, 2)` re-indented every co-owned config we touched. A
53
+ * hand-written tab-indented `opencode.json` — OpenCode's entire project config —
54
+ * came back two-space indented from a merge that added one key, and never came back
55
+ * from the uninstall at all: 111 bytes in, 114 out, for a strip that took nothing
56
+ * of theirs. Byte fidelity is a claim this tool makes about co-owned files, and a
57
+ * JSON config is one of those.
58
+ *
59
+ * Read from the first indented line, which is what every formatter agrees on.
60
+ * Falls back to two spaces for a file we are creating or one written on a single
61
+ * line, which is what this always did.
62
+ */
63
+ function indentOf(text: string): string | number {
64
+ const m = /\n([ \t]+)\S/.exec(text)
65
+ if (m) return m[1].includes('\t') ? '\t' : m[1].length
66
+ // A config written on one line has no indentation, and expanding it to three is
67
+ // as much a restyle as collapsing it would be. `0` is what `JSON.stringify` takes
68
+ // for "no whitespace".
69
+ return text.trim().includes('\n') ? 2 : 0
70
+ }
71
+
72
+ /**
73
+ * Re-serialise a config the way the file was already written.
74
+ *
75
+ * Indentation and line endings both, because `JSON.stringify` emits `\n` whatever
76
+ * it was handed and a CRLF config came back LF from a merge that added one key.
77
+ * The same rule `.gitignore` follows: a CRLF file stays CRLF.
78
+ */
79
+ export function serialiseLike(original: string, value: unknown): string {
80
+ const text = JSON.stringify(value, null, indentOf(original)) + '\n'
81
+ return /\r\n/.test(original) ? text.replace(/\n/g, '\r\n') : text
82
+ }
83
+
84
+ // ── TOML ──────────────────────────────────────────────────────
85
+
86
+ const SERVERS = 'mcp_servers'
87
+
88
+ /** smol-toml builds objects with no prototype; the rest of the code expects plain ones. */
89
+ function plain(value: unknown): unknown {
90
+ if (Array.isArray(value)) return value.map(plain)
91
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
92
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, plain(v)]))
93
+ }
94
+ return value
95
+ }
96
+
97
+ /** Key order is not meaning. */
98
+ function canonical(value: unknown): string {
99
+ return JSON.stringify(value, (_key, v) =>
100
+ v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date)
101
+ ? Object.fromEntries(Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
102
+ : v,
103
+ )
104
+ }
105
+
106
+ function tomlKey(key: string): string {
107
+ return /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key)
108
+ }
109
+
110
+ /**
111
+ * A TOML basic string. JSON's escapes are TOML's, except that TOML also forbids
112
+ * a raw DEL, which JSON leaves alone.
113
+ */
114
+ function tomlString(s: string): string {
115
+ return JSON.stringify(s).replace(/\u007f/g, '\\u007F')
116
+ }
117
+
118
+ function tomlValue(value: unknown): string {
119
+ if (typeof value === 'string') return tomlString(value)
120
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value)
121
+ if (Array.isArray(value)) return `[${value.map(tomlValue).join(', ')}]`
122
+ if (value && typeof value === 'object') {
123
+ const fields = Object.entries(value).filter(([, v]) => v !== undefined)
124
+ return fields.length === 0 ? '{}' : `{ ${fields.map(([k, v]) => `${tomlKey(k)} = ${tomlValue(v)}`).join(', ')} }`
125
+ }
126
+ throw new TomlEditError(`cannot write ${String(value)} as TOML`)
127
+ }
128
+
129
+ /** One server as a `[mcp_servers.<key>]` table. */
130
+ function serverTable(key: string, entry: unknown, eol: string): string {
131
+ const lines = [`[${SERVERS}.${tomlKey(key)}]`]
132
+ for (const [k, v] of Object.entries((entry ?? {}) as Record<string, unknown>)) {
133
+ if (v === undefined) continue
134
+ lines.push(`${tomlKey(k)} = ${tomlValue(v)}`)
135
+ }
136
+ return lines.join(eol) + eol
137
+ }
138
+
139
+ interface Segment {
140
+ /** The table this run of lines belongs to, as its dotted key; `null` before the first header. */
141
+ path: string[] | null
142
+ lines: string[]
143
+ }
144
+
145
+ const HEADER = /^[ \t]*\[\[?[ \t]*(.+?)[ \t]*\]\]?[ \t]*(?:#.*)?\r?\n?$/
146
+
147
+ /** Split a dotted key into its parts, unquoting quoted ones. */
148
+ function splitKey(key: string): string[] {
149
+ const parts: string[] = []
150
+ let current = ''
151
+ let quote: string | null = null
152
+ for (let i = 0; i < key.length; i++) {
153
+ const ch = key[i]
154
+ if (quote) {
155
+ if (ch === '\\' && quote === '"') {
156
+ current += key[++i] ?? ''
157
+ } else if (ch === quote) {
158
+ quote = null
159
+ } else {
160
+ current += ch
161
+ }
162
+ } else if (ch === '"' || ch === "'") {
163
+ quote = ch
164
+ } else if (ch === '.') {
165
+ parts.push(current.trim())
166
+ current = ''
167
+ } else {
168
+ current += ch
169
+ }
170
+ }
171
+ parts.push(current.trim())
172
+ return parts
173
+ }
174
+
175
+ /**
176
+ * The file as runs of lines, one per table.
177
+ *
178
+ * A line that looks like a header inside a multi-line string is not one; the
179
+ * string delimiters are tracked so it stays with the table it belongs to. Odd
180
+ * layouts this misreads are caught afterwards: every write is parsed back and
181
+ * compared with what was meant.
182
+ */
183
+ function segments(text: string): Segment[] {
184
+ const lines = text.split(/(?<=\n)/)
185
+ const out: Segment[] = [{ path: null, lines: [] }]
186
+ let open: '"""' | "'''" | null = null
187
+ for (const line of lines) {
188
+ if (!open) {
189
+ const header = HEADER.exec(line)
190
+ if (header && !line.trimStart().startsWith('#')) {
191
+ out.push({ path: splitKey(header[1]), lines: [line] })
192
+ continue
193
+ }
194
+ }
195
+ out[out.length - 1].lines.push(line)
196
+ for (const m of line.matchAll(/"""|'''/g)) {
197
+ if (!open) open = m[0] as '"""' | "'''"
198
+ else if (open === m[0]) open = null
199
+ }
200
+ }
201
+ return out
202
+ }
203
+
204
+ /** The blank and comment lines a segment ends with — they introduce whatever follows it. */
205
+ function tailOf(seg: Segment): string[] {
206
+ const tail: string[] = []
207
+ for (let i = seg.lines.length - 1; i > 0; i--) {
208
+ const t = seg.lines[i].trim()
209
+ if (t === '' || t.startsWith('#')) tail.unshift(seg.lines[i])
210
+ else break
211
+ }
212
+ return tail
213
+ }
214
+
215
+ function serverOf(seg: Segment): string | undefined {
216
+ return seg.path && seg.path[0] === SERVERS && seg.path.length >= 2 ? seg.path[1] : undefined
217
+ }
218
+
219
+ function without(value: Record<string, unknown>, key: string): Record<string, unknown> {
220
+ const { [key]: _drop, ...rest } = value
221
+ return rest
222
+ }
223
+
224
+ /** An empty `[mcp_servers]` and none at all say the same thing to Codex. */
225
+ function normalised(value: unknown): unknown {
226
+ const v = value as Record<string, unknown>
227
+ const servers = v[SERVERS]
228
+ return servers && typeof servers === 'object' && Object.keys(servers).length === 0 ? without(v, SERVERS) : v
229
+ }
230
+
231
+ /**
232
+ * Write `value` over `before`, touching only the server tables that changed.
233
+ *
234
+ * Everything outside `[mcp_servers]` must be what the file already says —
235
+ * OpenCastle never edits a user's Codex settings — and the result is parsed
236
+ * back before it is returned, so a layout this cannot edit cleanly is refused
237
+ * rather than written wrong.
238
+ */
239
+ function writeToml(before: string, value: Record<string, unknown>): string {
240
+ const eol = /\r\n/.test(before) ? '\r\n' : '\n'
241
+ const old = (before.trim() === '' ? {} : plain(parseToml(before))) as Record<string, unknown>
242
+ if (canonical(without(old, SERVERS)) !== canonical(without(value, SERVERS))) {
243
+ throw new TomlEditError('only the [mcp_servers] tables of a Codex config are ours to change')
244
+ }
245
+ const oldServers = (old[SERVERS] ?? {}) as Record<string, unknown>
246
+ const newServers = (value[SERVERS] ?? {}) as Record<string, unknown>
247
+
248
+ const out: string[] = []
249
+ const rewritten = new Set<string>()
250
+ // Whether the file now ends where a dropped table used to be. The blank line
251
+ // that separated our first table from the user's last one was ours, written
252
+ // when we appended; left behind, an install and uninstall would not give the
253
+ // user back their file byte for byte.
254
+ let endsOnDrop = false
255
+ for (const seg of segments(before)) {
256
+ const key = serverOf(seg)
257
+ if (key === undefined) {
258
+ out.push(...seg.lines)
259
+ endsOnDrop = false
260
+ continue
261
+ }
262
+ const tail = tailOf(seg)
263
+ if (!(key in newServers)) {
264
+ // A comment before the next table is about that table; keep it.
265
+ if (tail.some((l) => l.trim().startsWith('#'))) out.push(...tail)
266
+ endsOnDrop = true
267
+ continue
268
+ }
269
+ endsOnDrop = false
270
+ if (canonical(oldServers[key]) === canonical(newServers[key])) {
271
+ out.push(...seg.lines)
272
+ continue
273
+ }
274
+ // A changed server is written whole at its first table; its sub-tables go.
275
+ if (rewritten.has(key)) {
276
+ if (tail.some((l) => l.trim().startsWith('#'))) out.push(...tail)
277
+ continue
278
+ }
279
+ rewritten.add(key)
280
+ out.push(serverTable(key, newServers[key], eol), ...tail)
281
+ }
282
+
283
+ let text = out.join('')
284
+ if (endsOnDrop) text = text.trim() === '' ? '' : text.replace(/(\r?\n)+$/, eol)
285
+ const added = Object.keys(newServers).filter((k) => !(k in oldServers))
286
+ if (added.length > 0) {
287
+ if (text !== '' && !text.endsWith('\n')) text += eol
288
+ if (text.trim() !== '' && !/(\r?\n){2}$/.test(text)) text += eol
289
+ text += added.map((k) => serverTable(k, newServers[k], eol)).join(eol)
290
+ }
291
+
292
+ let check: unknown
293
+ try {
294
+ check = plain(parseToml(text))
295
+ } catch (err) {
296
+ throw new TomlEditError(`the edit would not parse — ${(err as Error).message}`)
297
+ }
298
+ if (canonical(normalised(check)) !== canonical(normalised(value))) {
299
+ throw new TomlEditError('its [mcp_servers] are written in a way this cannot edit line by line, e.g. as inline tables')
300
+ }
301
+ return text
302
+ }
package/src/cli/mcp.ts CHANGED
@@ -8,6 +8,7 @@ import type { McpInput, McpServerConfig, EnvVarRequirement } from '../orchestrat
8
8
  import type { ScaffoldResult, StackConfig, RepoInfo, IdeChoice, CopyResults } from './types.js';
9
9
  import type { TeamMcpPlan } from './layers.js';
10
10
  import { EDITOR_VARIABLES, type TeamMcpServer } from './team-config.js';
11
+ import { parseMcpConfigText, serialiseMcpConfig, TomlEditError } from './mcp-file.js';
11
12
 
12
13
  // ── IDE-specific MCP format transformation ────────────────────
13
14
 
@@ -63,6 +64,12 @@ function editorVariableFor(ide: IdeChoice, name: string, original: string): stri
63
64
  return original;
64
65
  }
65
66
 
67
+ /** The variable a value is wholly a reference to — `${NAME}` and nothing else — or null. */
68
+ function wholeReference(value: string): string | null {
69
+ const m = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(value);
70
+ return m && !EDITOR_VARIABLES.has(m[1]) ? m[1] : null;
71
+ }
72
+
66
73
  /** Rewrite every `${NAME}` in a value into the target's own spelling. */
67
74
  function rewriteRefs(value: string, ide: IdeChoice): string {
68
75
  return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (m, name: string) =>
@@ -87,7 +94,6 @@ function transformMcpForIde(
87
94
  case 'cursor':
88
95
  case 'claude-code':
89
96
  case 'windsurf':
90
- case 'codex':
91
97
  case 'antigravity': {
92
98
  // mcpServers format — no 'type' field
93
99
  const mcpServers: Record<string, unknown> = {};
@@ -115,6 +121,53 @@ function transformMcpForIde(
115
121
  return { mcpServers };
116
122
  }
117
123
 
124
+ case 'codex': {
125
+ // Codex CLI reads `[mcp_servers.<name>]` tables in `.codex/config.toml`
126
+ // and expands no variables anywhere in them. What it offers instead is
127
+ // structural: `env_vars` forwards a variable from the environment Codex
128
+ // was started in, `bearer_token_env_var` sends `Authorization: Bearer`
129
+ // with one, and `env_http_headers` sets a header to one. A reference that
130
+ // is exactly one of those shapes is written as it; anything else is left
131
+ // as written, and `doctor` says so.
132
+ const mcp_servers: Record<string, unknown> = {};
133
+ for (const [name, server] of Object.entries(servers)) {
134
+ if (server.type === 'stdio') {
135
+ const env: Record<string, string> = {};
136
+ const envVars: string[] = [];
137
+ for (const [key, value] of Object.entries(server.env ?? {})) {
138
+ if (wholeReference(value) === key) envVars.push(key);
139
+ else env[key] = value;
140
+ }
141
+ mcp_servers[name] = {
142
+ command: server.command,
143
+ ...(server.args && { args: server.args }),
144
+ ...(Object.keys(env).length > 0 && { env }),
145
+ ...(envVars.length > 0 && { env_vars: envVars }),
146
+ };
147
+ } else if (server.type === 'http') {
148
+ const url = (server.url ?? '').replace(/\$\{input:\w+\}/g, 'REPLACE_ME');
149
+ const literal: Record<string, string> = {};
150
+ const fromEnv: Record<string, string> = {};
151
+ let bearer: string | undefined;
152
+ for (const [header, value] of Object.entries(server.headers ?? {})) {
153
+ const token = /^Bearer\s+(\$\{[A-Za-z_][A-Za-z0-9_]*\})$/.exec(value);
154
+ const bearerVar = header.toLowerCase() === 'authorization' && token ? wholeReference(token[1]) : null;
155
+ const whole = wholeReference(value);
156
+ if (bearerVar) bearer = bearerVar;
157
+ else if (whole) fromEnv[header] = whole;
158
+ else literal[header] = value;
159
+ }
160
+ mcp_servers[name] = {
161
+ url,
162
+ ...(bearer && { bearer_token_env_var: bearer }),
163
+ ...(Object.keys(literal).length > 0 && { http_headers: literal }),
164
+ ...(Object.keys(fromEnv).length > 0 && { env_http_headers: fromEnv }),
165
+ };
166
+ }
167
+ }
168
+ return { mcp_servers };
169
+ }
170
+
118
171
  case 'opencode': {
119
172
  // OpenCode format — type: "local"/"remote", command as array
120
173
  const mcp: Record<string, unknown> = {};
@@ -149,41 +202,6 @@ function transformMcpForIde(
149
202
  }
150
203
  }
151
204
 
152
- /**
153
- * The indentation a file already uses, so merging into it does not restyle it.
154
- *
155
- * `JSON.stringify(x, null, 2)` re-indented every co-owned config we touched. A
156
- * hand-written tab-indented `opencode.json` — OpenCode's entire project config —
157
- * came back two-space indented from a merge that added one key, and never came back
158
- * from the uninstall at all: 111 bytes in, 114 out, for a strip that took nothing
159
- * of theirs. Byte fidelity is a claim this tool makes about co-owned files, and a
160
- * JSON config is one of those.
161
- *
162
- * Read from the first indented line, which is what every formatter agrees on.
163
- * Falls back to two spaces for a file we are creating or one written on a single
164
- * line, which is what this always did.
165
- */
166
- function indentOf(text: string): string | number {
167
- const m = /\n([ \t]+)\S/.exec(text);
168
- if (m) return m[1].includes('\t') ? '\t' : m[1].length;
169
- // A config written on one line has no indentation, and expanding it to three is
170
- // as much a restyle as collapsing it would be. `0` is what `JSON.stringify` takes
171
- // for "no whitespace".
172
- return text.trim().includes('\n') ? 2 : 0;
173
- }
174
-
175
- /**
176
- * Re-serialise a config the way the file was already written.
177
- *
178
- * Indentation and line endings both, because `JSON.stringify` emits `\n` whatever
179
- * it was handed and a CRLF config came back LF from a merge that added one key.
180
- * The same rule `.gitignore` follows: a CRLF file stays CRLF.
181
- */
182
- function serialiseLike(original: string, value: unknown): string {
183
- const text = JSON.stringify(value, null, indentOf(original)) + '\n';
184
- return /\r\n/.test(original) ? text.replace(/\n/g, '\r\n') : text;
185
- }
186
-
187
205
  /**
188
206
  * One plugin's server as the VS Code–format config, with the env vars other
189
207
  * targets need spelled out — they have no `envFile`.
@@ -206,7 +224,8 @@ function serverFor(
206
224
  return serverConfig;
207
225
  }
208
226
 
209
- function containerKeyFor(ide: IdeChoice): string {
227
+ export function containerKeyFor(ide: IdeChoice): string {
228
+ if (ide === 'codex') return 'mcp_servers';
210
229
  return ide === 'opencode' ? 'mcp' : ide === 'vscode' ? 'servers' : 'mcpServers';
211
230
  }
212
231
 
@@ -418,6 +437,20 @@ export function upgradeGeneratedServers(
418
437
  return upgraded;
419
438
  }
420
439
 
440
+ /**
441
+ * The text to write, or the same refusal an unparseable config gets when a
442
+ * TOML config is laid out in a way that cannot be changed line by line —
443
+ * named and left alone, never rewritten wholesale.
444
+ */
445
+ function serialiseOrRefuse(before: string | null, value: Record<string, unknown>, rel: string): string {
446
+ try {
447
+ return serialiseMcpConfig(before, value, rel);
448
+ } catch (err) {
449
+ if (err instanceof TomlEditError) throw new UnreadableConfigError(rel, 'uneditable');
450
+ throw err;
451
+ }
452
+ }
453
+
421
454
  /**
422
455
  * Scaffold or merge the MCP server config into the target project.
423
456
  *
@@ -487,17 +520,12 @@ export async function scaffoldMcpConfig(
487
520
  }
488
521
  let existing: Record<string, unknown>;
489
522
  try {
490
- existing = JSON.parse(existingContent) as Record<string, unknown>;
523
+ existing = parseMcpConfigText(existingContent, destRelPath);
491
524
  } catch {
492
525
  throw new UnreadableConfigError(destRelPath);
493
526
  }
494
527
 
495
- // Determine the server container key for this IDE
496
- const containerKey = resolvedIde === 'opencode'
497
- ? 'mcp'
498
- : resolvedIde === 'vscode'
499
- ? 'servers'
500
- : 'mcpServers';
528
+ const containerKey = containerKeyFor(resolvedIde);
501
529
 
502
530
  if (!existing[containerKey]) {
503
531
  existing[containerKey] = {};
@@ -539,13 +567,13 @@ export async function scaffoldMcpConfig(
539
567
  return { path: destPath, action: 'skipped', team: teamChanges };
540
568
  }
541
569
 
542
- await writeFile(destPath, serialiseLike(existingContent, existing));
570
+ await writeFile(destPath, serialiseOrRefuse(existingContent, existing, destRelPath));
543
571
  return { path: destPath, action: 'created', team: teamChanges };
544
572
  }
545
573
 
546
574
  const teamChanges = applyTeamPlan(output, resolvedIde, team);
547
575
  await mkdir(dirname(destPath), { recursive: true });
548
- await writeFile(destPath, JSON.stringify(output, null, 2) + '\n');
576
+ await writeFile(destPath, serialiseOrRefuse(null, output, destRelPath));
549
577
 
550
578
  return { path: destPath, action: 'created', team: teamChanges };
551
579
  }
@@ -568,7 +596,7 @@ export function getMcpConfigRelPath(ide: IdeChoice): string {
568
596
  case 'windsurf':
569
597
  return '.windsurf/mcp.json';
570
598
  case 'codex':
571
- return '.codex/mcp.json';
599
+ return '.codex/config.toml';
572
600
  case 'antigravity':
573
601
  return '.agents/mcp_config.json';
574
602
  }
@@ -611,9 +639,7 @@ export async function scaffoldMcpConfigInto(
611
639
  if (result.team?.removed.length) (results.mcpTeamRemoved ??= []).push(...result.team.removed);
612
640
  } catch (err) {
613
641
  if (!(err instanceof UnreadableConfigError)) throw err;
614
- (results.unreadable ??= []).push(
615
- err.reason === 'unreadable' ? `${err.file}\u0000unreadable` : err.file,
616
- );
642
+ (results.unreadable ??= []).push(err.reason === 'unparseable' ? err.file : `${err.file}\u0000${err.reason}`);
617
643
  }
618
644
  }
619
645
 
@@ -641,8 +667,8 @@ export function willKeepSomethingAfterStrip(
641
667
  teamInputs: string[] = [],
642
668
  ): boolean {
643
669
  const containerKeys = ide
644
- ? [ide === 'opencode' ? 'mcp' : ide === 'vscode' ? 'servers' : 'mcpServers']
645
- : ['mcp', 'servers', 'mcpServers']
670
+ ? [containerKeyFor(ide)]
671
+ : ['mcp', 'servers', 'mcpServers', 'mcp_servers']
646
672
 
647
673
  const ourServerKeys = new Set([
648
674
  ...Object.values(PLUGINS)
@@ -680,7 +706,47 @@ export async function stripManagedMcpServers(
680
706
  teamKeys: string[] = [],
681
707
  teamInputs: string[] = [],
682
708
  ): Promise<'deleted' | 'stripped' | 'absent' | 'unreadable'> {
683
- const destPath = resolve(projectRoot, getMcpConfigRelPath(ide));
709
+ return stripConfigAt(projectRoot, getMcpConfigRelPath(ide), ide, createdByUs, teamKeys, teamInputs);
710
+ }
711
+
712
+ /**
713
+ * MCP configs a release before this one wrote where the assistant never looks.
714
+ *
715
+ * Codex CLI reads project servers only from `.codex/config.toml`; the
716
+ * `.codex/mcp.json` OpenCastle wrote for it was never loaded, so every server
717
+ * in it was one Codex did not have.
718
+ */
719
+ export const LEGACY_MCP_CONFIGS: Partial<Record<IdeChoice, string>> = {
720
+ codex: '.codex/mcp.json',
721
+ };
722
+
723
+ /**
724
+ * Take our servers back out of a target's legacy MCP config, and delete it if
725
+ * we created it and nothing of the user's is left. Anything they added stays —
726
+ * it never reached the assistant either, and `sync` says where it belongs.
727
+ */
728
+ export async function retireLegacyMcpConfig(
729
+ projectRoot: string,
730
+ ide: IdeChoice,
731
+ createdByUs = false,
732
+ teamKeys: string[] = [],
733
+ teamInputs: string[] = [],
734
+ ): Promise<'deleted' | 'stripped' | 'absent' | 'unreadable'> {
735
+ const rel = LEGACY_MCP_CONFIGS[ide];
736
+ if (!rel) return 'absent';
737
+ // No `ide`: the legacy file is in the shape it was written in, not today's.
738
+ return stripConfigAt(projectRoot, rel, undefined, createdByUs, teamKeys, teamInputs);
739
+ }
740
+
741
+ async function stripConfigAt(
742
+ projectRoot: string,
743
+ rel: string,
744
+ ide: IdeChoice | undefined,
745
+ createdByUs: boolean,
746
+ teamKeys: string[],
747
+ teamInputs: string[],
748
+ ): Promise<'deleted' | 'stripped' | 'absent' | 'unreadable'> {
749
+ const destPath = resolve(projectRoot, rel);
684
750
  if (!existsSync(destPath)) return 'absent';
685
751
 
686
752
  let before: string;
@@ -691,7 +757,7 @@ export async function stripManagedMcpServers(
691
757
  }
692
758
  let parsed: Record<string, unknown>;
693
759
  try {
694
- parsed = JSON.parse(before) as Record<string, unknown>;
760
+ parsed = parseMcpConfigText(before, rel);
695
761
  } catch {
696
762
  // Not ours to repair. Leaving it alone beats deleting something unreadable,
697
763
  // but 'stripped' would have removal report "kept your content in N file(s)"
@@ -734,7 +800,12 @@ export async function stripManagedMcpServers(
734
800
 
735
801
  // The file's own indentation, not ours. Taking our servers out of a
736
802
  // tab-indented config used to restyle every line of it.
737
- await writeFile(destPath, serialiseLike(before, parsed));
803
+ try {
804
+ await writeFile(destPath, serialiseMcpConfig(before, parsed, rel));
805
+ } catch (err) {
806
+ if (err instanceof TomlEditError) return 'unreadable';
807
+ throw err;
808
+ }
738
809
  return 'stripped';
739
810
  }
740
811
 
@@ -778,12 +849,11 @@ export async function rebuildMcpConfig(
778
849
  }
779
850
  let existing: Record<string, unknown>;
780
851
  try {
781
- existing = JSON.parse(before) as Record<string, unknown>;
852
+ existing = parseMcpConfigText(before, destRelPath);
782
853
  } catch {
783
854
  throw new UnreadableConfigError(destRelPath);
784
855
  }
785
- const containerKey =
786
- ide === 'opencode' ? 'mcp' : ide === 'vscode' ? 'servers' : 'mcpServers';
856
+ const containerKey = containerKeyFor(ide);
787
857
 
788
858
  const existingServers = (existing[containerKey] ?? {}) as Record<string, unknown>;
789
859
 
@@ -868,11 +938,11 @@ export async function rebuildMcpConfig(
868
938
  // policies, and the user's formatting lost to the stricter of them.
869
939
  let unchanged = false;
870
940
  try {
871
- unchanged = JSON.stringify(JSON.parse(before)) === JSON.stringify(existing);
941
+ unchanged = JSON.stringify(parseMcpConfigText(before, destRelPath)) === JSON.stringify(existing);
872
942
  } catch {
873
943
  unchanged = false;
874
944
  }
875
- if (!unchanged) await writeFile(destPath, serialiseLike(before, existing));
945
+ if (!unchanged) await writeFile(destPath, serialiseOrRefuse(before, existing, destRelPath));
876
946
 
877
947
  // Re-scaffold: merges new plugin servers into the cleaned config, and writes
878
948
  // the team's servers exactly as its layers define them.