-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathmcp-config.mts
More file actions
388 lines (362 loc) · 11.5 KB
/
Copy pathmcp-config.mts
File metadata and controls
388 lines (362 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/**
* @file Pure adapters from the fleet-canonical Claude `.mcp.json` shape to
* project-local Codex/OpenCode/Kimi configs and Kimi's per-user MCP file.
* Credentials never belong in the canonical or generated project files; each
* client owns OAuth state in its user data directory.
*/
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import { errorMessage } from '@socketsecurity/lib-stable/errors/message'
import { isMainModule } from './_shared/is-main-module.mts'
import { REPO_ROOT } from './paths.mts'
export type PortableMcpServer =
| {
args: string[]
command: string
kind: 'stdio'
}
| {
kind: 'http'
url: string
}
export type PortableMcpServers = Readonly<Record<string, PortableMcpServer>>
// Boundary + known secret-bearing key name + boundary, including snake/kebab case.
const CREDENTIAL_KEY_PATTERN =
/(?:^|[-_])(?:auth(?:orization)?|bearer|credential|password|secret|token)(?:$|[-_])/i
const CREDENTIAL_VALUE_PATTERN = /\bbearer\s+[a-z\d._~+/=-]+/i
function assertNoCredentials(value: unknown, location = '.mcp.json'): void {
if (typeof value === 'string') {
if (CREDENTIAL_VALUE_PATTERN.test(value)) {
throw new Error(
`Committed MCP config contains a credential at ${location}`,
)
}
return
}
if (Array.isArray(value)) {
for (let index = 0; index < value.length; index += 1) {
assertNoCredentials(value[index], `${location}[${index}]`)
}
return
}
if (!isRecord(value)) {
return
}
const entries = Object.entries(value)
for (let i = 0, { length } = entries; i < length; i += 1) {
const [key, child] = entries[i]!
if (CREDENTIAL_KEY_PATTERN.test(key)) {
throw new Error(
`Committed MCP config contains a credential field at ${location}.${key}`,
)
}
assertNoCredentials(child, `${location}.${key}`)
}
}
function compactKimiArgsArrays(
text: string,
servers: PortableMcpServers,
): string {
let result = text
const items = Object.values(servers)
for (let i = 0, { length } = items; i < length; i += 1) {
const server = items[i]!
if (server.kind !== 'stdio' || server.args.length === 0) {
continue
}
const compact = ` "args": [${server.args.map(value => JSON.stringify(value)).join(', ')}]`
if (compact.length > 80) {
continue
}
const expanded = [
' "args": [',
...server.args.map(
(value, index) =>
` ${JSON.stringify(value)}${index + 1 < server.args.length ? ',' : ''}`,
),
' ]',
].join('\n')
result = result.replace(expanded, compact)
}
return result
}
function compactOpenCodeCommandArrays(
text: string,
servers: PortableMcpServers,
): string {
let result = text
const items = Object.values(servers)
for (let i = 0, { length } = items; i < length; i += 1) {
const server = items[i]!
if (server.kind !== 'stdio') {
continue
}
const command = [server.command, ...server.args]
const compact = ` "command": [${command.map(value => JSON.stringify(value)).join(', ')}]`
if (compact.length > 80) {
continue
}
const expanded = [
' "command": [',
...command.map(
(value, index) =>
` ${JSON.stringify(value)}${index + 1 < command.length ? ',' : ''}`,
),
' ]',
].join('\n')
result = result.replace(expanded, compact)
}
return result
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function main(): void {
if (!process.argv.includes('--write')) {
throw new Error(
'Usage: node scripts/fleet/mcp-config.mts --write (regenerates project MCP client configs)',
)
}
writeMcpClientConfigs(REPO_ROOT)
process.stdout.write(
'Generated .codex/config.toml, opencode.json, and .kimi-code/mcp.json.\n',
)
}
function parseStringArray(value: unknown, field: string): string[] {
if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) {
throw new Error(`MCP server ${field} must be an array of strings`)
}
return [...value]
}
function runMain(): void {
try {
main()
} catch (error) {
process.stderr.write(`${errorMessage(error)}\n`)
process.exitCode = 1
}
}
function sortRecord<T>(record: Readonly<Record<string, T>>): Record<string, T> {
return Object.fromEntries(
Object.entries(record).toSorted(([left], [right]) =>
left < right ? -1 : left > right ? 1 : 0,
),
)
}
function tomlString(value: string): string {
return JSON.stringify(value)
}
function tomlStringArray(values: readonly string[]): string[] {
const compact = JSON.stringify(values)
if (`args = ${compact}`.length <= 80) {
return [`args = ${compact}`]
}
return ['args = [', ...values.map(value => ` ${tomlString(value)},`), ']']
}
/**
* Merge the canonical server definitions into Kimi's user-owned config. Kimi
* has no project discovery file, so local servers receive an absolute cwd while
* unrelated user servers and credentials remain untouched.
*/
export function mergeKimiMcpConfig(
currentText: string,
servers: PortableMcpServers,
repoRoot: string,
): string {
let parsed: unknown
try {
parsed = JSON.parse(currentText)
} catch {
throw new Error('Existing Kimi MCP config must contain valid JSON')
}
if (!isRecord(parsed)) {
throw new Error('Existing Kimi MCP config must be a JSON object')
}
const existing = parsed['mcpServers']
if (existing !== undefined && !isRecord(existing)) {
throw new Error('Existing Kimi mcpServers value must be a JSON object')
}
const mcpServers: Record<string, unknown> = { ...(existing ?? {}) }
for (const [name, server] of Object.entries(servers)) {
mcpServers[name] =
server.kind === 'http'
? { auth: 'oauth', type: 'http', url: server.url }
: {
args: server.args,
command: server.command,
cwd: repoRoot,
}
}
return `${JSON.stringify(
{ ...parsed, mcpServers: sortRecord(mcpServers) },
undefined,
2,
)}\n`
}
/**
* Parse and validate the one committed MCP authority.
*/
export function parseCanonicalMcpConfig(text: string): PortableMcpServers {
let parsed: unknown
try {
parsed = JSON.parse(text)
} catch {
throw new Error('Canonical .mcp.json must contain valid JSON')
}
assertNoCredentials(parsed)
if (!isRecord(parsed) || !isRecord(parsed['mcpServers'])) {
throw new Error('Canonical .mcp.json must contain an mcpServers object')
}
const servers: Record<string, PortableMcpServer> = {}
for (const [name, rawServer] of Object.entries(parsed['mcpServers'])) {
if (!isRecord(rawServer)) {
throw new Error(`MCP server ${name} must be an object`)
}
if (rawServer['type'] === 'http') {
const url = rawServer['url']
if (typeof url !== 'string' || url.length === 0) {
throw new Error(`HTTP MCP server ${name} must have a URL`)
}
servers[name] = { kind: 'http', url }
continue
}
const command = rawServer['command']
if (typeof command !== 'string' || command.length === 0) {
throw new Error(`stdio MCP server ${name} must have a command`)
}
servers[name] = {
args: parseStringArray(rawServer['args'] ?? [], `${name}.args`),
command,
kind: 'stdio',
}
}
return sortRecord(servers)
}
/**
* Render the trusted-project `.codex/config.toml` MCP section.
*/
export function renderCodexMcpConfig(servers: PortableMcpServers): string {
const lines = [
'# Generated from ../.mcp.json by scripts/fleet/mcp-config.mts.',
'# OAuth credentials stay in Codex user storage; do not add them here.',
]
for (const [name, server] of Object.entries(sortRecord(servers))) {
lines.push('', `[mcp_servers.${name}]`)
if (server.kind === 'http') {
lines.push(`url = ${tomlString(server.url)}`)
} else {
lines.push(`command = ${tomlString(server.command)}`)
lines.push(...tomlStringArray(server.args))
}
}
return `${lines.join('\n')}\n`
}
/**
* Render the project `.codex/hooks.json` — a PreToolUse guard that blocks edits
* to fleet-canonical files, the Codex analog of the Claude no-fleet-fork-guard.
* Static (server-independent): Codex discovers `<repo>/.codex/hooks.json` as
* the project hook layer, matches `tool_name` against the regex, and runs the
* shared cross-CLI shim which shares its block decision with every other CLI.
*/
export function renderCodexHooksConfig(): string {
return `${JSON.stringify(
{
description:
'Fleet guard: block edits to fleet-canonical files. Generated by scripts/fleet/mcp-config.mts.',
hooks: {
PreToolUse: [
{
hooks: [
{
command: 'node scripts/fleet/cross-cli/pretooluse-hook.mts',
timeout: 10,
type: 'command',
},
],
matcher: 'apply_patch|shell|local_shell',
},
],
},
},
undefined,
2,
)}\n`
}
/**
* Render OpenCode's project-root `opencode.json`.
*/
export function renderOpenCodeMcpConfig(servers: PortableMcpServers): string {
const mcp: Record<string, unknown> = {}
for (const [name, server] of Object.entries(sortRecord(servers))) {
mcp[name] =
server.kind === 'http'
? { enabled: true, type: 'remote', url: server.url }
: {
command: [server.command, ...server.args],
enabled: true,
type: 'local',
}
}
const rendered = JSON.stringify(
{ $schema: 'https://opencode.ai/config.json', mcp },
undefined,
2,
)
return `${compactOpenCodeCommandArrays(rendered, servers)}\n`
}
/**
* Render Kimi's project-local `~/.kimi-code/mcp.json` adapter. Kimi resolves
* stdio commands relative to the project root when the file lives at
* `<project>/.kimi-code/mcp.json`, so no `cwd` is needed.
*/
export function renderKimiProjectMcpConfig(
servers: PortableMcpServers,
): string {
const mcpServers: Record<string, unknown> = {}
for (const [name, server] of Object.entries(sortRecord(servers))) {
mcpServers[name] =
server.kind === 'http'
? { auth: 'oauth', type: 'http', url: server.url }
: { args: server.args, command: server.command }
}
const rendered = JSON.stringify(
{ mcpServers: sortRecord(mcpServers) },
undefined,
2,
)
return `${compactKimiArgsArrays(rendered, servers)}\n`
}
/**
* Regenerate the three committed project adapters from `.mcp.json`.
*/
export function writeMcpClientConfigs(repoRoot: string): void {
const templateRoot = path.join(repoRoot, 'template', 'base')
const configRoot = existsSync(path.join(templateRoot, '.mcp.json'))
? templateRoot
: repoRoot
const servers = parseCanonicalMcpConfig(
readFileSync(path.join(configRoot, '.mcp.json'), 'utf8'),
)
mkdirSync(path.join(configRoot, '.codex'), { recursive: true })
mkdirSync(path.join(configRoot, '.kimi-code'), { recursive: true })
writeFileSync(
path.join(configRoot, '.codex', 'config.toml'),
renderCodexMcpConfig(servers),
)
writeFileSync(
path.join(configRoot, '.codex', 'hooks.json'),
renderCodexHooksConfig(),
)
writeFileSync(
path.join(configRoot, 'opencode.json'),
renderOpenCodeMcpConfig(servers),
)
writeFileSync(
path.join(configRoot, '.kimi-code', 'mcp.json'),
renderKimiProjectMcpConfig(servers),
)
}
if (isMainModule(import.meta.url)) {
runMain()
}