opencastle 1.1.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.
- package/README.md +1 -1
- package/dist/cli/adapters/codex.d.ts +19 -6
- package/dist/cli/adapters/codex.d.ts.map +1 -1
- package/dist/cli/adapters/codex.js +24 -7
- package/dist/cli/adapters/codex.js.map +1 -1
- package/dist/cli/adapters/single-file-base.d.ts +7 -0
- package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
- package/dist/cli/adapters/single-file-base.js +35 -20
- package/dist/cli/adapters/single-file-base.js.map +1 -1
- package/dist/cli/codex-target.test.d.ts +2 -0
- package/dist/cli/codex-target.test.d.ts.map +1 -0
- package/dist/cli/codex-target.test.js +154 -0
- package/dist/cli/codex-target.test.js.map +1 -0
- package/dist/cli/doctor.d.ts.map +1 -1
- package/dist/cli/doctor.js +2 -1
- package/dist/cli/doctor.js.map +1 -1
- package/dist/cli/init.d.ts.map +1 -1
- package/dist/cli/init.js +5 -4
- package/dist/cli/init.js.map +1 -1
- package/dist/cli/init.test.js +22 -10
- package/dist/cli/init.test.js.map +1 -1
- package/dist/cli/managed-paths.d.ts.map +1 -1
- package/dist/cli/managed-paths.js +2 -0
- package/dist/cli/managed-paths.js.map +1 -1
- package/dist/cli/mcp-audit.d.ts.map +1 -1
- package/dist/cli/mcp-audit.js +7 -3
- package/dist/cli/mcp-audit.js.map +1 -1
- package/dist/cli/mcp-file.d.ts +37 -0
- package/dist/cli/mcp-file.d.ts.map +1 -0
- package/dist/cli/mcp-file.js +291 -0
- package/dist/cli/mcp-file.js.map +1 -0
- package/dist/cli/mcp-file.test.d.ts +2 -0
- package/dist/cli/mcp-file.test.d.ts.map +1 -0
- package/dist/cli/mcp-file.test.js +121 -0
- package/dist/cli/mcp-file.test.js.map +1 -0
- package/dist/cli/mcp.d.ts +15 -0
- package/dist/cli/mcp.d.ts.map +1 -1
- package/dist/cli/mcp.js +123 -56
- package/dist/cli/mcp.js.map +1 -1
- package/dist/cli/remove.d.ts.map +1 -1
- package/dist/cli/remove.js +23 -4
- package/dist/cli/remove.js.map +1 -1
- package/dist/cli/sync-check.d.ts.map +1 -1
- package/dist/cli/sync-check.js +4 -3
- package/dist/cli/sync-check.js.map +1 -1
- package/dist/cli/sync-check.test.js +2 -2
- package/dist/cli/sync-check.test.js.map +1 -1
- package/dist/cli/types.d.ts +5 -2
- package/dist/cli/types.d.ts.map +1 -1
- package/dist/cli/types.js +3 -0
- package/dist/cli/types.js.map +1 -1
- package/dist/cli/unreadable-report.d.ts +7 -0
- package/dist/cli/unreadable-report.d.ts.map +1 -1
- package/dist/cli/unreadable-report.js +14 -0
- package/dist/cli/unreadable-report.js.map +1 -1
- package/dist/cli/update.d.ts.map +1 -1
- package/dist/cli/update.js +55 -5
- package/dist/cli/update.js.map +1 -1
- package/package.json +2 -1
- package/src/cli/adapters/codex.ts +25 -7
- package/src/cli/adapters/single-file-base.ts +46 -24
- package/src/cli/codex-target.test.ts +178 -0
- package/src/cli/doctor.ts +3 -2
- package/src/cli/init.test.ts +22 -10
- package/src/cli/init.ts +5 -4
- package/src/cli/managed-paths.ts +2 -0
- package/src/cli/mcp-audit.ts +7 -3
- package/src/cli/mcp-file.test.ts +138 -0
- package/src/cli/mcp-file.ts +302 -0
- package/src/cli/mcp.ts +130 -60
- package/src/cli/remove.ts +20 -4
- package/src/cli/sync-check.test.ts +2 -2
- package/src/cli/sync-check.ts +4 -3
- package/src/cli/types.ts +5 -2
- package/src/cli/unreadable-report.ts +14 -0
- package/src/cli/update.ts +61 -5
- package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
package/src/cli/init.test.ts
CHANGED
|
@@ -19,6 +19,7 @@ import { mkdtemp, readFile, readdir, rm, unlink, writeFile } from 'node:fs/promi
|
|
|
19
19
|
import { join, resolve } from 'node:path'
|
|
20
20
|
import { tmpdir } from 'node:os'
|
|
21
21
|
import { existsSync } from 'node:fs'
|
|
22
|
+
import { parse as parseToml } from 'smol-toml'
|
|
22
23
|
import type { StackConfig, RepoInfo } from './types.js'
|
|
23
24
|
import { updateGitignore } from './gitignore.js'
|
|
24
25
|
import {
|
|
@@ -1079,29 +1080,40 @@ describe('Codex adapter install', () => {
|
|
|
1079
1080
|
expect(content).toContain('.codex/')
|
|
1080
1081
|
})
|
|
1081
1082
|
|
|
1082
|
-
it('
|
|
1083
|
+
it('puts agents in .codex/ and skills where Codex reads them, .agents/skills/', async () => {
|
|
1083
1084
|
const adapter = await IDE_ADAPTERS['codex']()
|
|
1084
1085
|
await adapter.install(PKG_ROOT, tmpDir, STACK_SANITY_LINEAR)
|
|
1085
1086
|
expect(existsSync(join(tmpDir, '.codex', 'agents'))).toBe(true)
|
|
1086
|
-
expect(existsSync(join(tmpDir, '.
|
|
1087
|
+
expect(existsSync(join(tmpDir, '.agents', 'skills', 'testing-workflow', 'SKILL.md'))).toBe(true)
|
|
1088
|
+
// Codex has never read this; nothing should be written there.
|
|
1089
|
+
expect(existsSync(join(tmpDir, '.codex', 'skills'))).toBe(false)
|
|
1090
|
+
const root = await readFile(join(tmpDir, 'AGENTS.md'), 'utf8')
|
|
1091
|
+
expect(root).toContain('`.agents/skills/testing-workflow/SKILL.md`')
|
|
1087
1092
|
})
|
|
1088
1093
|
|
|
1089
|
-
it('
|
|
1094
|
+
it('writes MCP servers as [mcp_servers] tables in .codex/config.toml', async () => {
|
|
1090
1095
|
const adapter = await IDE_ADAPTERS['codex']()
|
|
1091
1096
|
await adapter.install(PKG_ROOT, tmpDir, STACK_SANITY_LINEAR)
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
const
|
|
1095
|
-
expect(
|
|
1097
|
+
expect(existsSync(join(tmpDir, '.codex', 'mcp.json'))).toBe(false)
|
|
1098
|
+
const text = await readFile(join(tmpDir, '.codex', 'config.toml'), 'utf8')
|
|
1099
|
+
const config = parseToml(text) as { mcp_servers: Record<string, Record<string, unknown>> }
|
|
1100
|
+
expect(Object.keys(config.mcp_servers).length).toBeGreaterThan(0)
|
|
1101
|
+
for (const entry of Object.values(config.mcp_servers)) {
|
|
1102
|
+
// Codex expands no variables, so none may be written as text.
|
|
1103
|
+
expect(JSON.stringify(entry)).not.toMatch(/\$\{[A-Z_]+\}/)
|
|
1104
|
+
expect('url' in entry || 'command' in entry).toBe(true)
|
|
1105
|
+
}
|
|
1096
1106
|
})
|
|
1097
1107
|
|
|
1098
|
-
it('getManagedPaths includes AGENTS.md
|
|
1108
|
+
it('getManagedPaths includes AGENTS.md, the .codex dirs and .agents/skills/', async () => {
|
|
1099
1109
|
const adapter = await IDE_ADAPTERS['codex']()
|
|
1100
1110
|
const paths = adapter.getManagedPaths()
|
|
1101
1111
|
expect(paths.merged).toContain('AGENTS.md')
|
|
1102
1112
|
expect(paths.framework).not.toContain('AGENTS.md')
|
|
1103
|
-
expect(paths.framework.
|
|
1104
|
-
expect(paths.
|
|
1113
|
+
expect(paths.framework).toContain('.codex/agents/')
|
|
1114
|
+
expect(paths.framework).toContain('.agents/skills/')
|
|
1115
|
+
expect(paths.framework).not.toContain('.codex/skills/')
|
|
1116
|
+
expect(paths.customizable).toContain('.codex/config.toml')
|
|
1105
1117
|
})
|
|
1106
1118
|
})
|
|
1107
1119
|
|
package/src/cli/init.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { readManifest, writeManifest, createManifest } from './manifest.js'
|
|
|
6
6
|
import { removeDirIfExists, copyDir, getOrchestratorRoot } from './copy.js'
|
|
7
7
|
import { updateGitignore } from './gitignore.js'
|
|
8
8
|
import { getCustomizationsTransform } from './stack-config.js'
|
|
9
|
-
import { getMcpConfigRelPath, stripManagedMcpServers } from './mcp.js'
|
|
9
|
+
import { getMcpConfigRelPath, stripManagedMcpServers, retireLegacyMcpConfig } from './mcp.js'
|
|
10
10
|
import { getPluginsBySubCategory } from '../orchestrator/plugins/index.js'
|
|
11
11
|
import type { PluginConfig } from '../orchestrator/plugins/types.js'
|
|
12
12
|
import { detectRepoInfo, mergeStackIntoRepoInfo, formatRepoInfo, buildDetectedToolsSet, detectCurrentIde, detectAssistantConfigs } from './detect.js'
|
|
@@ -16,7 +16,7 @@ import type { CliContext, CopyResults, IdeAdapter, IdeChoice, TechTool, TeamTool
|
|
|
16
16
|
import { bootstrapCustomizations } from './bootstrap.js'
|
|
17
17
|
import { stripManagedBlock, stripManagedBlockFromFile } from './managed-block.js'
|
|
18
18
|
import { resolveManagedPaths, declaredManagedPaths, ownerOf, removeOwnedFiles } from './managed-paths.js'
|
|
19
|
-
import { noteUnreadable } from './unreadable-report.js'
|
|
19
|
+
import { noteUnreadable, whyLeftAlone } from './unreadable-report.js'
|
|
20
20
|
import { resolveSources, materialize, hasErrors, formatIssues, requiredEnvVars } from './layers.js'
|
|
21
21
|
import { buildLock, writeLock, priorTeam } from './lock.js'
|
|
22
22
|
import { parseVersion, compareVersions } from './version-range.js'
|
|
@@ -409,6 +409,7 @@ export default async function init({ pkgRoot, args }: CliContext): Promise<void>
|
|
|
409
409
|
for (const id of dropped) {
|
|
410
410
|
if ((ides as string[]).includes(id)) continue
|
|
411
411
|
await stripManagedMcpServers(projectRoot, id as IdeChoice)
|
|
412
|
+
await retireLegacyMcpConfig(projectRoot, id as IdeChoice)
|
|
412
413
|
}
|
|
413
414
|
|
|
414
415
|
// Co-owned files are not ours to delete — take back only the block, and
|
|
@@ -659,7 +660,7 @@ export default async function init({ pkgRoot, args }: CliContext): Promise<void>
|
|
|
659
660
|
const name = isAbsolute(abs) ? relative(projectRoot, abs) : abs
|
|
660
661
|
console.log(
|
|
661
662
|
` ${c.yellow('!')} Left ${name} alone — ` +
|
|
662
|
-
(why
|
|
663
|
+
whyLeftAlone(name, why),
|
|
663
664
|
)
|
|
664
665
|
// `--force` is not decoration. A plain `sync` short-circuits when nothing
|
|
665
666
|
// has drifted, and the MCP config is a customizable path the drift checker
|
|
@@ -670,7 +671,7 @@ export default async function init({ pkgRoot, args }: CliContext): Promise<void>
|
|
|
670
671
|
// servers" for every entry, and the list now also carries generated rule and
|
|
671
672
|
// skill files, so a skipped `.cursor/rules/x.mdc` was explained in terms of a
|
|
672
673
|
// feature that has nothing to do with it.
|
|
673
|
-
const isMcp = /(^|[/\\])(\.mcp\.json|mcp\.json|opencode\.json)$/.test(name)
|
|
674
|
+
const isMcp = /(^|[/\\])(\.mcp\.json|mcp\.json|mcp_config\.json|opencode\.json|config\.toml)$/.test(name)
|
|
674
675
|
console.log(
|
|
675
676
|
` ${c.dim(
|
|
676
677
|
isMcp
|
package/src/cli/managed-paths.ts
CHANGED
|
@@ -49,6 +49,8 @@ export const ROOT_INSTRUCTION_FILES = [
|
|
|
49
49
|
*/
|
|
50
50
|
const SUPERSEDED_FRAMEWORK: Record<string, string> = {
|
|
51
51
|
'.claude/commands/': `.claude/${CLAUDE_COMMANDS_DIR}/`,
|
|
52
|
+
// Codex never read `.codex/skills/`; its skills moved to the shared location.
|
|
53
|
+
'.codex/skills/': '.agents/skills/',
|
|
52
54
|
}
|
|
53
55
|
|
|
54
56
|
function unique(values: string[]): string[] {
|
package/src/cli/mcp-audit.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { resolve } from 'node:path'
|
|
|
2
2
|
import { existsSync, readFileSync } from 'node:fs'
|
|
3
3
|
import { PLUGINS } from '../orchestrator/plugins/index.js'
|
|
4
4
|
import { getMcpConfigRelPath, upgradeGeneratedServers, canonicalJson } from './mcp.js'
|
|
5
|
+
import { parseMcpConfigText } from './mcp-file.js'
|
|
5
6
|
import type { IdeChoice } from './types.js'
|
|
6
7
|
import { disallowedBy, hostDisallowedBy, findInlineSecret, hostOfUrl, type EffectivePolicy } from './policy.js'
|
|
7
8
|
import { EDITOR_VARIABLES } from './team-config.js'
|
|
@@ -256,7 +257,7 @@ export function isPinned(launch: PackageLaunch): boolean {
|
|
|
256
257
|
function serverEntries(config: unknown): Array<[string, Record<string, unknown>]> {
|
|
257
258
|
if (!config || typeof config !== 'object') return []
|
|
258
259
|
const out: Array<[string, Record<string, unknown>]> = []
|
|
259
|
-
for (const key of ['servers', 'mcpServers', 'mcp']) {
|
|
260
|
+
for (const key of ['servers', 'mcpServers', 'mcp', 'mcp_servers']) {
|
|
260
261
|
const container = (config as Record<string, unknown>)[key]
|
|
261
262
|
if (!container || typeof container !== 'object' || Array.isArray(container)) continue
|
|
262
263
|
for (const [name, entry] of Object.entries(container as Record<string, unknown>)) {
|
|
@@ -437,6 +438,9 @@ const OWN_SPELLING: Partial<Record<IdeChoice, (name: string) => string>> = {
|
|
|
437
438
|
cursor: (n) => `\${env:${n}}`,
|
|
438
439
|
windsurf: (n) => `\${env:${n}}`,
|
|
439
440
|
opencode: (n) => `{env:${n}}`,
|
|
441
|
+
// Codex expands nothing: a variable reaches a server only by being named in
|
|
442
|
+
// a field that reads one.
|
|
443
|
+
codex: (n) => `env_vars, bearer_token_env_var or env_http_headers naming ${n}`,
|
|
440
444
|
}
|
|
441
445
|
|
|
442
446
|
/** The first `${NAME}` this target would pass through literally, as `NAME → spelling`, or null. */
|
|
@@ -444,7 +448,7 @@ function unexpandedVariable(entry: Record<string, unknown>, ide: IdeChoice): str
|
|
|
444
448
|
const spell = OWN_SPELLING[ide]
|
|
445
449
|
if (!spell) return null
|
|
446
450
|
const values: unknown[] = []
|
|
447
|
-
for (const field of ['env', 'environment', 'headers']) {
|
|
451
|
+
for (const field of ['env', 'environment', 'headers', 'http_headers']) {
|
|
448
452
|
const block = entry[field]
|
|
449
453
|
if (block && typeof block === 'object' && !Array.isArray(block)) values.push(...Object.values(block as Record<string, unknown>))
|
|
450
454
|
}
|
|
@@ -572,7 +576,7 @@ export function checkMcpSupplyChain(
|
|
|
572
576
|
if (!existsSync(abs)) return { ok: true, label: LABEL, detail: 'no MCP config' }
|
|
573
577
|
let parsed: unknown
|
|
574
578
|
try {
|
|
575
|
-
parsed =
|
|
579
|
+
parsed = parseMcpConfigText(readFileSync(abs, 'utf8'), rel)
|
|
576
580
|
} catch {
|
|
577
581
|
return { ok: true, label: LABEL, detail: `${rel} could not be read (reported above)` }
|
|
578
582
|
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { parse as parseToml } from 'smol-toml'
|
|
3
|
+
import { parseMcpConfigText, serialiseMcpConfig, TomlEditError } from './mcp-file.js'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `.codex/config.toml` holds a user's whole Codex setup — model, approvals,
|
|
7
|
+
* sandbox, profiles — beside the MCP servers OpenCastle writes. These pin the
|
|
8
|
+
* promise the JSON configs already keep: our servers change, nothing of theirs
|
|
9
|
+
* does, byte for byte.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const REL = '.codex/config.toml'
|
|
13
|
+
|
|
14
|
+
const USERS_OWN = `# My Codex setup
|
|
15
|
+
model = "gpt-5-codex"
|
|
16
|
+
approval_policy = "on-request"
|
|
17
|
+
|
|
18
|
+
[profiles.fast]
|
|
19
|
+
model = "gpt-5-codex-mini" # quick tasks
|
|
20
|
+
|
|
21
|
+
[mcp_servers.mine]
|
|
22
|
+
command = "my-server"
|
|
23
|
+
args = ["--port", "1234"]
|
|
24
|
+
|
|
25
|
+
[mcp_servers.mine.tools.dangerous]
|
|
26
|
+
approval_mode = "approve"
|
|
27
|
+
`
|
|
28
|
+
|
|
29
|
+
function serversOf(text: string): Record<string, unknown> {
|
|
30
|
+
return (parseToml(text) as { mcp_servers?: Record<string, unknown> }).mcp_servers ?? {}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe('Codex config.toml', () => {
|
|
34
|
+
it('parses to a plain object with mcp_servers as the container', () => {
|
|
35
|
+
const parsed = parseMcpConfigText(USERS_OWN, REL)
|
|
36
|
+
expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype)
|
|
37
|
+
expect(Object.keys(parsed.mcp_servers as object)).toEqual(['mine'])
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('adds a server after the user’s content and changes nothing of theirs', () => {
|
|
41
|
+
const value = parseMcpConfigText(USERS_OWN, REL)
|
|
42
|
+
;(value.mcp_servers as Record<string, unknown>).Linear = { url: 'https://mcp.linear.app/mcp' }
|
|
43
|
+
const text = serialiseMcpConfig(USERS_OWN, value, REL)
|
|
44
|
+
expect(text.startsWith(USERS_OWN)).toBe(true)
|
|
45
|
+
expect(text.slice(USERS_OWN.length)).toBe('\n[mcp_servers.Linear]\nurl = "https://mcp.linear.app/mcp"\n')
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('removes only the server it was asked to, with its sub-tables', () => {
|
|
49
|
+
const withOurs = USERS_OWN + '\n[mcp_servers.Sanity]\ncommand = "npx"\nargs = ["-y", "@sanity/mcp-server@1.2.3"]\n'
|
|
50
|
+
const value = parseMcpConfigText(withOurs, REL)
|
|
51
|
+
delete (value.mcp_servers as Record<string, unknown>).Sanity
|
|
52
|
+
expect(serialiseMcpConfig(withOurs, value, REL)).toBe(USERS_OWN)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('gives the user their file back byte for byte after an add and a remove', () => {
|
|
56
|
+
const value = parseMcpConfigText(USERS_OWN, REL)
|
|
57
|
+
;(value.mcp_servers as Record<string, unknown>).Linear = { url: 'https://mcp.linear.app/mcp' }
|
|
58
|
+
const added = serialiseMcpConfig(USERS_OWN, value, REL)
|
|
59
|
+
const back = parseMcpConfigText(added, REL)
|
|
60
|
+
delete (back.mcp_servers as Record<string, unknown>).Linear
|
|
61
|
+
expect(serialiseMcpConfig(added, back, REL)).toBe(USERS_OWN)
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('rewrites a changed server in place and keeps the tables around it', () => {
|
|
65
|
+
const before =
|
|
66
|
+
'model = "x"\n\n[mcp_servers.Sentry]\nurl = "https://old.example/mcp"\n\n[profiles.a]\nmodel = "y"\n'
|
|
67
|
+
const value = parseMcpConfigText(before, REL)
|
|
68
|
+
;(value.mcp_servers as Record<string, Record<string, unknown>>).Sentry = { url: 'https://mcp.sentry.dev/mcp' }
|
|
69
|
+
const text = serialiseMcpConfig(before, value, REL)
|
|
70
|
+
expect(text).toBe('model = "x"\n\n[mcp_servers.Sentry]\nurl = "https://mcp.sentry.dev/mcp"\n\n[profiles.a]\nmodel = "y"\n')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('quotes a server name that is not a bare key', () => {
|
|
74
|
+
const value = { mcp_servers: { 'Chrome DevTools': { command: 'npx', args: ['chrome-devtools-mcp@0.1.0'] } } }
|
|
75
|
+
const text = serialiseMcpConfig(null, value, REL)
|
|
76
|
+
expect(text).toContain('[mcp_servers."Chrome DevTools"]')
|
|
77
|
+
expect(serversOf(text)).toEqual(value.mcp_servers)
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it('writes env, env_vars and headers as values Codex reads back the same', () => {
|
|
81
|
+
const entry = {
|
|
82
|
+
url: 'https://api.example.com/mcp',
|
|
83
|
+
bearer_token_env_var: 'EXAMPLE_TOKEN',
|
|
84
|
+
http_headers: { 'X-Tenant': 'acme' },
|
|
85
|
+
env_http_headers: { 'X-Key': 'EXAMPLE_KEY' },
|
|
86
|
+
}
|
|
87
|
+
const stdio = { command: 'npx', args: ['-y', 'x@1.0.0'], env: { MODE: 'ci "quoted"\\path' }, env_vars: ['API_TOKEN'] }
|
|
88
|
+
const value = { mcp_servers: { remote: entry, local: stdio } }
|
|
89
|
+
const text = serialiseMcpConfig(null, value, REL)
|
|
90
|
+
expect(serversOf(text)).toEqual(value.mcp_servers)
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
it('keeps CRLF line endings', () => {
|
|
94
|
+
const before = USERS_OWN.replace(/\n/g, '\r\n')
|
|
95
|
+
const value = parseMcpConfigText(before, REL)
|
|
96
|
+
;(value.mcp_servers as Record<string, unknown>).Linear = { url: 'https://mcp.linear.app/mcp' }
|
|
97
|
+
const text = serialiseMcpConfig(before, value, REL)
|
|
98
|
+
expect(text.startsWith(before)).toBe(true)
|
|
99
|
+
expect(text.replace(/\r\n/g, '')).not.toContain('\n')
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
it('does not mistake a header-like line inside a multi-line string for a table', () => {
|
|
103
|
+
const before = 'instructions = """\n[mcp_servers.fake]\nnot a table\n"""\n\n[mcp_servers.real]\ncommand = "a"\n'
|
|
104
|
+
const value = parseMcpConfigText(before, REL)
|
|
105
|
+
;(value.mcp_servers as Record<string, Record<string, unknown>>).real = { command: 'b' }
|
|
106
|
+
const text = serialiseMcpConfig(before, value, REL)
|
|
107
|
+
expect(text).toContain('[mcp_servers.fake]\nnot a table')
|
|
108
|
+
expect(serversOf(text)).toEqual({ real: { command: 'b' } })
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
it('refuses rather than rewrites servers written as inline tables', () => {
|
|
112
|
+
const before = '[mcp_servers]\nmine = { command = "a" }\n'
|
|
113
|
+
const value = parseMcpConfigText(before, REL)
|
|
114
|
+
;(value.mcp_servers as Record<string, Record<string, unknown>>).mine = { command: 'b' }
|
|
115
|
+
expect(() => serialiseMcpConfig(before, value, REL)).toThrow(TomlEditError)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it('refuses to change anything outside [mcp_servers]', () => {
|
|
119
|
+
const value = parseMcpConfigText(USERS_OWN, REL)
|
|
120
|
+
value.model = 'something-else'
|
|
121
|
+
expect(() => serialiseMcpConfig(USERS_OWN, value, REL)).toThrow(TomlEditError)
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
it('leaves no [mcp_servers] residue when the last of ours goes', () => {
|
|
125
|
+
const before = 'model = "x"\n\n[mcp_servers.Linear]\nurl = "https://mcp.linear.app/mcp"\n'
|
|
126
|
+
const value = parseMcpConfigText(before, REL)
|
|
127
|
+
delete value.mcp_servers
|
|
128
|
+
expect(serialiseMcpConfig(before, value, REL)).toBe('model = "x"\n')
|
|
129
|
+
})
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
describe('JSON configs are untouched by the TOML path', () => {
|
|
133
|
+
it('keeps the file’s indentation', () => {
|
|
134
|
+
const before = '{\n\t"mcpServers": {}\n}\n'
|
|
135
|
+
const text = serialiseMcpConfig(before, { mcpServers: { a: { command: 'x' } } }, '.mcp.json')
|
|
136
|
+
expect(text).toBe('{\n\t"mcpServers": {\n\t\t"a": {\n\t\t\t"command": "x"\n\t\t}\n\t}\n}\n')
|
|
137
|
+
})
|
|
138
|
+
})
|
|
@@ -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
|
+
}
|