@phyzess/kitto 0.2.1 → 0.3.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.
@@ -0,0 +1,500 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { loadDshYaml } from '../integration/scoped-dsh/native.mjs';
5
+ import {
6
+ bearerCredentialReference, bearerCredentialTemplate, credentialReference, credentialTemplate,
7
+ literalSecretsIn, literalValueReason, transportCredentialProblem, unresolvedPlaceholdersIn,
8
+ } from './mcp-credentials.mjs';
9
+
10
+ export { loadDshYaml };
11
+
12
+ const pluginName = '@deepseek-ai/dsh-mcp-client';
13
+ const managerName = '@deepseek-ai/dsh-mcp-manager';
14
+ const managerId = 'mcp-manager';
15
+ const rowPrefix = 'kitto-mcp-';
16
+ const serverNamePattern = /^[A-Za-z0-9_-]{1,32}$/;
17
+ const optOut = 'KITTO_NO_MCP_SYNC';
18
+ // DSH's patch dialect preserves `!!js` expressions as inert values.
19
+ const yamlOptions = { customTags: [{ tag: 'tag:yaml.org,2002:js', resolve: value => value }] };
20
+
21
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
22
+ const isKittoRow = row => isObject(row) && typeof row.id === 'string' && row.id.startsWith(rowPrefix);
23
+
24
+ /** Pi stores its platform differences as macOS/Linux overlays. */
25
+ export function platformOverlay(platform = process.platform) {
26
+ if (platform === 'darwin' || platform === 'macos') return 'macos';
27
+ if (platform === 'linux') return 'linux';
28
+ return null;
29
+ }
30
+
31
+ async function readJson(path) {
32
+ let text;
33
+ try {
34
+ text = await readFile(path, 'utf8');
35
+ } catch (error) {
36
+ if (error.code === 'ENOENT') return null;
37
+ throw error;
38
+ }
39
+ try {
40
+ return JSON.parse(text);
41
+ } catch (error) {
42
+ throw new Error(`Invalid JSON in ${path}: ${error.message}`);
43
+ }
44
+ }
45
+
46
+ async function readPatch(path) {
47
+ try {
48
+ const info = await lstat(path);
49
+ if (!info.isFile()) throw new Error(`DSH home patch is not a regular file: ${path}`);
50
+ return { content: await readFile(path, 'utf8'), mode: info.mode & 0o777 };
51
+ } catch (error) {
52
+ if (error.code !== 'ENOENT') throw error;
53
+ return { content: null, mode: 0o600 };
54
+ }
55
+ }
56
+
57
+ function merge(base, over) {
58
+ if (!isObject(base) || !isObject(over)) return over;
59
+ const result = { ...base };
60
+ for (const [key, value] of Object.entries(over)) result[key] = key in result ? merge(result[key], value) : value;
61
+ return result;
62
+ }
63
+
64
+ function mcpServers(value, path) {
65
+ if (value === null) return {};
66
+ if (!isObject(value) || (value.mcpServers !== undefined && !isObject(value.mcpServers))) {
67
+ throw new Error(`${path} must contain an mcpServers object.`);
68
+ }
69
+ return value.mcpServers ?? {};
70
+ }
71
+
72
+ /** A literal secret or an unresolved `YOUR_*` placeholder anywhere in an entry. */
73
+ function scanLiteralCredentials(entry) {
74
+ const [secret] = literalSecretsIn(entry);
75
+ if (secret) return `contains a literal secret (${secret.label}) at ${secret.path}`;
76
+ const [placeholder] = unresolvedPlaceholdersIn(entry);
77
+ if (placeholder) return `still contains an unresolved YOUR_* placeholder at ${placeholder.path}`;
78
+ return null;
79
+ }
80
+
81
+ /** Map reference-only stdio env vars to DSH credential templates. */
82
+ function dshEnv(env) {
83
+ if (!isObject(env)) return { skip: 'env is not an object of strings' };
84
+ const mapped = {};
85
+ for (const [name, value] of Object.entries(env)) {
86
+ if (typeof value !== 'string') return { skip: `env.${name} is not a string` };
87
+ const reference = credentialReference(value);
88
+ if (reference === null) return { skip: literalValueReason(`env.${name}`, value) };
89
+ mapped[name] = credentialTemplate(reference);
90
+ }
91
+ return Object.keys(mapped).length ? { value: mapped } : {};
92
+ }
93
+
94
+ /**
95
+ * Map reference-only HTTP headers to DSH credential templates. Authorization
96
+ * may keep its `Bearer ` scheme; every other header must be a whole `${VAR}`.
97
+ */
98
+ function dshHeaders(headers) {
99
+ if (!isObject(headers)) return { skip: 'headers is not an object of strings' };
100
+ const mapped = {};
101
+ for (const [name, value] of Object.entries(headers)) {
102
+ if (typeof value !== 'string') return { skip: `headers.${name} is not a string` };
103
+ const authorization = name.toLowerCase() === 'authorization';
104
+ const bearer = authorization ? bearerCredentialReference(value) : null;
105
+ const reference = bearer ?? credentialReference(value);
106
+ if (reference === null) {
107
+ return { skip: literalValueReason(`headers.${name}`, value, { authorization }) };
108
+ }
109
+ mapped[name] = bearer ? bearerCredentialTemplate(reference) : credentialTemplate(reference);
110
+ }
111
+ return Object.keys(mapped).length ? { value: mapped } : {};
112
+ }
113
+
114
+ /**
115
+ * Read the portable Pi MCP declarations: the repository base plus the current
116
+ * platform overlay. Private and machine-local Pi files are only read when the
117
+ * caller opts in with `includePrivate`; by default they stay out because they
118
+ * are machine-specific. Credential-bearing env/headers must be whole `${VAR}`
119
+ * references, which become DSH credential templates; every literal value or
120
+ * literal secret skips that server with a reason that never quotes the value.
121
+ */
122
+ export async function piMcpServers(source, platform = process.platform, { includePrivate = false } = {}) {
123
+ const sources = [join(source, 'config/pi/mcp.json')];
124
+ const overlayName = platformOverlay(platform);
125
+ if (overlayName) sources.push(join(source, 'config/pi/platform', overlayName, 'mcp.json'));
126
+ if (includePrivate) {
127
+ // Machine-local overrides first, then the private file: the same precedence
128
+ // Pi's own merge uses, and both files are optional.
129
+ sources.push(join(source, 'config/pi/local/mcp.json'));
130
+ sources.push(join(source, 'config/pi/mcp.private.json'));
131
+ }
132
+ const merged = {};
133
+ for (const path of sources) {
134
+ const declared = mcpServers(await readJson(path), path);
135
+ for (const [name, entry] of Object.entries(declared)) merged[name] = merge(merged[name], entry);
136
+ }
137
+
138
+ const servers = [], skipped = [];
139
+ for (const [name, entry] of Object.entries(merged)) {
140
+ if (name.startsWith('_') || !isObject(entry) || entry.enabled === false) continue;
141
+ const skip = reason => skipped.push({ name, reason });
142
+ if (!serverNamePattern.test(name)) { skip('not a valid DSH server name'); continue; }
143
+ const literal = scanLiteralCredentials(entry);
144
+ if (literal) { skip(literal); continue; }
145
+ const transportProblem = transportCredentialProblem(entry);
146
+ if (transportProblem) { skip(`${transportProblem}; only env/headers references are synced`); continue; }
147
+ const env = entry.env === undefined ? undefined : dshEnv(entry.env);
148
+ const headers = entry.headers === undefined ? undefined : dshHeaders(entry.headers);
149
+ if (entry.url !== undefined) {
150
+ if (typeof entry.url !== 'string' || !entry.url) { skip('url is not a string'); continue; }
151
+ if (entry.type !== undefined && !['http', 'streamable-http'].includes(entry.type)) { skip(`Pi transport ${entry.type} is not supported by DSH`); continue; }
152
+ if (entry.url.includes('${')) { skip('url contains a credential template; only env/headers references are synced'); continue; }
153
+ if (env) { skip('env is only synced for stdio servers'); continue; }
154
+ if (headers?.skip) { skip(headers.skip); continue; }
155
+ const server = { name, transport: 'streamable-http', url: entry.url };
156
+ if (headers?.value) { server.headers = headers.value; server.expandTemplates = true; }
157
+ servers.push(server);
158
+ } else if (entry.command !== undefined) {
159
+ if (typeof entry.command !== 'string' || !entry.command) { skip('command is not a string'); continue; }
160
+ if (entry.type !== undefined && entry.type !== 'stdio') { skip(`Pi transport ${entry.type} is not supported by DSH`); continue; }
161
+ const args = entry.args ?? [];
162
+ if (!Array.isArray(args) || args.some(arg => typeof arg !== 'string')) { skip('args is not a string array'); continue; }
163
+ if (entry.command.includes('${') || args.some(arg => arg.includes('${'))) {
164
+ skip('command or args contain a credential template; only env/headers references are synced');
165
+ continue;
166
+ }
167
+ if (headers) { skip('headers are only synced for HTTP servers'); continue; }
168
+ if (env?.skip) { skip(env.skip); continue; }
169
+ const server = { name, transport: 'stdio', command: entry.command, args };
170
+ if (env?.value) { server.env = env.value; server.expandTemplates = true; }
171
+ servers.push(server);
172
+ } else {
173
+ skip('no command or url');
174
+ }
175
+ }
176
+ return { servers, skipped };
177
+ }
178
+
179
+ /**
180
+ * The DSH mcp-client rows for the selected servers. Credential-bearing rows
181
+ * carry `${credential:REF}` templates and opt into `expandTemplates`, so DSH
182
+ * resolves them from its credential provider at runtime and keeps the raw
183
+ * secret out of both this file and its diagnostics.
184
+ */
185
+ export function dshMcpRows(servers) {
186
+ return servers.map(server => ({
187
+ id: rowPrefix + server.name,
188
+ name: pluginName,
189
+ config: server.transport === 'stdio'
190
+ ? {
191
+ serverName: server.name,
192
+ transport: 'stdio',
193
+ command: server.command,
194
+ args: server.args,
195
+ ...(server.env ? { env: server.env } : {}),
196
+ ...(server.expandTemplates ? { expandTemplates: true } : {}),
197
+ }
198
+ : {
199
+ serverName: server.name,
200
+ transport: 'streamable-http',
201
+ url: server.url,
202
+ ...(server.headers ? { headers: server.headers } : {}),
203
+ ...(server.expandTemplates ? { expandTemplates: true } : {}),
204
+ },
205
+ }));
206
+ }
207
+
208
+ function parsePatch(text, yaml, label) {
209
+ const document = yaml.parseDocument(text, yamlOptions);
210
+ if (document.errors.length) throw new Error(`${label} is not valid YAML: ${document.errors[0].message}`);
211
+ const empty = yaml.isScalar(document.contents) && document.contents.value === null;
212
+ if (document.contents !== null && !empty && !yaml.isSeq(document.contents)) {
213
+ throw new Error(`${label} must be a top-level YAML sequence.`);
214
+ }
215
+ let value;
216
+ try {
217
+ value = document.toJS();
218
+ } catch (error) {
219
+ throw new Error(`${label} cannot be read: ${error.message}`);
220
+ }
221
+ return { document, value };
222
+ }
223
+
224
+ function remember(declared, name, location) {
225
+ if (typeof name === 'string' && !declared.has(name)) declared.set(name, location);
226
+ }
227
+
228
+ /**
229
+ * Collect server names another declaration would load: any `serverName`, plus
230
+ * the enabled keys of an `mcp-manager` `servers` map.
231
+ */
232
+ function collectDeclared(value, declared, location) {
233
+ if (Array.isArray(value)) {
234
+ for (const entry of value) collectDeclared(entry, declared, location);
235
+ return;
236
+ }
237
+ if (!isObject(value)) return;
238
+ if ((value.name === managerName || value.id === managerId) && isObject(value.config?.servers)) {
239
+ for (const [name, entry] of Object.entries(value.config.servers)) {
240
+ if (!isObject(entry) || entry.enabled !== false) remember(declared, name, `${location} (mcp-manager)`);
241
+ }
242
+ }
243
+ for (const [key, entry] of Object.entries(value)) {
244
+ if (key === 'serverName' && typeof entry === 'string') remember(declared, entry, location);
245
+ else collectDeclared(entry, declared, location);
246
+ }
247
+ }
248
+
249
+ /** Server names declared by profile patches; the home patch applies to all profiles. */
250
+ async function profileDeclaredServers(state, yaml) {
251
+ const declared = new Map();
252
+ const directory = join(state.dshHome, 'profiles');
253
+ let entries;
254
+ try {
255
+ entries = await readdir(directory, { withFileTypes: true });
256
+ } catch (error) {
257
+ if (error.code === 'ENOENT') return declared;
258
+ throw error;
259
+ }
260
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
261
+ if (!entry.isDirectory()) continue;
262
+ const path = join(directory, entry.name, 'cordis.patch.yml');
263
+ let content;
264
+ try {
265
+ content = await readFile(path, 'utf8');
266
+ } catch (error) {
267
+ if (error.code === 'ENOENT') continue;
268
+ throw error;
269
+ }
270
+ if (!content.trim()) continue;
271
+ const { value } = parsePatch(content, yaml, `DSH profile patch ${path}`);
272
+ collectDeclared(value, declared, path);
273
+ }
274
+ return declared;
275
+ }
276
+
277
+ /** Full lines belonging to a top-level sequence item, dash included. */
278
+ function lineRange(text, node) {
279
+ let start = text.lastIndexOf('\n', node.range[0] - 1) + 1;
280
+ // `- # note` on its own line pushes the mapping down; keep the dash line too.
281
+ if (!/^\s*-/.test(text.slice(start, node.range[0]))) {
282
+ const previous = text.lastIndexOf('\n', start - 2) + 1;
283
+ if (/^\s*-(?:\s|$)/.test(text.slice(previous, start).replace(/\r?\n$/, ''))) start = previous;
284
+ }
285
+ let end = node.range[1];
286
+ if (text[end - 1] !== '\n') {
287
+ const next = text.indexOf('\n', end);
288
+ end = next === -1 ? text.length : next + 1;
289
+ }
290
+ return [start, end];
291
+ }
292
+
293
+ function sameRows(left, right) {
294
+ if (left.length !== right.length) return false;
295
+ const canon = list => list.map(row => JSON.stringify(row)).sort();
296
+ const a = canon(left), b = canon(right);
297
+ return a.every((value, index) => value === b[index]);
298
+ }
299
+
300
+ /**
301
+ * Split a trailing document-end marker so new rows stay in the same document.
302
+ * Only a column-0 `...` ends the document; indented `...` is block-scalar
303
+ * content. Comments and blank lines after the marker are kept verbatim.
304
+ */
305
+ function splitDocumentEnd(text) {
306
+ const lines = [];
307
+ let offset = 0;
308
+ for (const line of text.split('\n')) {
309
+ lines.push({ start: offset, text: line });
310
+ offset += line.length + 1;
311
+ }
312
+ for (let index = lines.length - 1; index >= 0; index--) {
313
+ const line = lines[index].text.replace(/\r$/, '');
314
+ if (line.trim() === '' || /^\s*#/.test(line)) continue;
315
+ if (!/^\.\.\.(?:[ \t]+#[^\n]*)?[ \t]*$/.test(line)) return { body: text, end: '' };
316
+ return { body: text.slice(0, lines[index].start), end: text.slice(lines[index].start) };
317
+ }
318
+ return { body: text, end: '' };
319
+ }
320
+
321
+ /** Refuse to write text that DSH itself could not load as a patch list. */
322
+ function validatePatch(text, yaml) {
323
+ const document = yaml.parseDocument(text, yamlOptions);
324
+ if (document.errors.length) {
325
+ throw new Error(`Refusing to write the DSH home patch: ${document.errors[0].message}`);
326
+ }
327
+ let value;
328
+ try {
329
+ value = document.toJS();
330
+ } catch (error) {
331
+ throw new Error(`Refusing to write the DSH home patch: ${error.message}`);
332
+ }
333
+ if (!Array.isArray(value)) throw new Error('Refusing to write the DSH home patch: it would not be a top-level YAML sequence.');
334
+ }
335
+
336
+ async function writePatch(path, text, before, mode) {
337
+ await mkdir(dirname(path), { recursive: true });
338
+ const temporary = `${path}.${randomUUID()}.tmp`;
339
+ try {
340
+ await writeFile(temporary, text, { flag: 'wx', mode });
341
+ if ((await readPatch(path)).content !== before) throw new Error(`DSH home patch changed during the update: ${path}`);
342
+ await rename(temporary, path);
343
+ } finally {
344
+ await rm(temporary, { force: true });
345
+ }
346
+ }
347
+
348
+ /**
349
+ * Compute the next `cordis.patch.yml`. Only whole top-level insert items whose
350
+ * rows all carry a `kitto-mcp-*` id are rewritten; every other line is kept.
351
+ * `declared` maps server names already owned elsewhere to their location.
352
+ */
353
+ export function planDshMcp({ content, rows, yaml, declared = new Map(), location = 'DSH home patch' }) {
354
+ if (!yaml) throw new Error('DSH MCP sync needs the YAML module bundled with DSH.');
355
+ const text = content ?? '';
356
+ let base = text;
357
+ const items = [];
358
+ const found = new Map(declared);
359
+ if (text.trim()) {
360
+ const parsed = parsePatch(text, yaml, 'DSH home patch');
361
+ const sequence = parsed.document.contents;
362
+ const emptyScalar = yaml.isScalar(sequence) && sequence.value === null;
363
+ if (sequence?.flow) {
364
+ if (sequence.items.length) throw new Error('DSH home patch uses flow-style YAML; convert it to block style before syncing MCP servers.');
365
+ base = text.slice(0, sequence.range[0]) + text.slice(sequence.range[1]);
366
+ } else if (emptyScalar) {
367
+ // A top-level `null`/`~`/empty document is an empty patch list; keep its comments.
368
+ base = text.slice(0, sequence.range[0]) + text.slice(sequence.range[1]);
369
+ } else if (Array.isArray(parsed.value)) {
370
+ for (const [index, item] of sequence.items.entries()) items.push({ value: parsed.value[index], range: lineRange(text, item) });
371
+ }
372
+ }
373
+
374
+ const removable = [];
375
+ for (const item of items) {
376
+ const value = item.value;
377
+ const insert = isObject(value) && Array.isArray(value.insert) ? value.insert : [];
378
+ const kitto = insert.filter(isKittoRow);
379
+ if (kitto.length) {
380
+ if (!isObject(value) || Object.keys(value).length !== 1 || kitto.length !== insert.length) {
381
+ throw new Error('DSH home patch mixes kitto-mcp-* rows with other entries; keep them in their own insert item.');
382
+ }
383
+ removable.push(item);
384
+ continue;
385
+ }
386
+ collectDeclared(value, found, location);
387
+ }
388
+
389
+ const removed = removable.flatMap(item => item.value.insert);
390
+ const conflicts = [];
391
+ const desired = rows.filter(row => {
392
+ const where = found.get(row.config.serverName);
393
+ if (where === undefined) return true;
394
+ conflicts.push({ row, location: where });
395
+ return false;
396
+ });
397
+ if (sameRows(removed, desired)) return { changed: false, text, conflicts, removed };
398
+
399
+ for (const { range } of removable.sort((left, right) => right.range[0] - left.range[0])) {
400
+ base = base.slice(0, range[0]) + base.slice(range[1]);
401
+ }
402
+ const { body, end } = splitDocumentEnd(base);
403
+ const trimmed = body.replace(/[ \t\r\n]+$/, '');
404
+ let core;
405
+ if (desired.length) {
406
+ const blocks = yaml.stringify(desired.map(row => ({ insert: [row] })), { lineWidth: 0, singleQuote: true });
407
+ core = trimmed ? `${trimmed}\n\n${blocks}` : blocks;
408
+ } else if (!trimmed) {
409
+ core = '[]\n';
410
+ } else {
411
+ core = parsePatch(trimmed, yaml, 'DSH home patch').value === null ? `${trimmed}\n[]\n` : `${trimmed}\n`;
412
+ }
413
+ if (!core.endsWith('\n')) core += '\n';
414
+ const next = core + end;
415
+ if (next === text) return { changed: false, text, conflicts, removed };
416
+ validatePatch(next, yaml);
417
+ return { changed: true, text: next, conflicts, removed };
418
+ }
419
+
420
+ /** Preview or apply the portable Pi MCP servers to the DSH home patch. */
421
+ export async function syncDshMcp(state, {
422
+ dryRun = false, yaml, log = console.log, warn = console.warn,
423
+ includePrivate = state.includePrivate === true,
424
+ } = {}) {
425
+ if (process.env[optOut] === '1') {
426
+ log(`mcp dsh: skipped (${optOut}=1)`);
427
+ return { changed: false, disabled: true };
428
+ }
429
+ if (!state.source) throw new Error('DSH MCP sync requires a configuration source.');
430
+ if (!state.dshHome) throw new Error('DSH MCP sync requires the DSH home directory.');
431
+ const path = join(state.dshHome, 'cordis.patch.yml');
432
+ const { servers, skipped } = await piMcpServers(state.source, process.platform, { includePrivate });
433
+ for (const item of skipped) warn(`mcp dsh: skipped ${item.name} (${item.reason})`);
434
+ const rows = dshMcpRows(servers);
435
+ const { content, mode } = await readPatch(path);
436
+ if (!rows.length && content === null) return { changed: false, path, skipped, conflicts: [] };
437
+
438
+ let module = yaml;
439
+ if (!module) {
440
+ try {
441
+ module = await loadDshYaml();
442
+ } catch (error) {
443
+ warn(`mcp dsh: skipped (cannot load the yaml module bundled with DSH: ${error.message})`);
444
+ return { changed: false, path, skipped, conflicts: [], unavailable: true };
445
+ }
446
+ }
447
+ const declared = rows.length ? await profileDeclaredServers(state, module) : new Map();
448
+ const plan = planDshMcp({ content, rows, yaml: module, declared, location: path });
449
+ for (const conflict of plan.conflicts) {
450
+ warn(`mcp dsh: skipped ${conflict.row.config.serverName} (already declared in ${conflict.location})`);
451
+ }
452
+ if (!plan.changed) {
453
+ log(`mcp dsh: up to date (${path})`);
454
+ return { changed: false, path, skipped, conflicts: plan.conflicts };
455
+ }
456
+ const synced = rows.length - plan.conflicts.length;
457
+ const summary = `${synced} server${synced === 1 ? '' : 's'}`;
458
+ if (dryRun) {
459
+ log(`mcp dsh: would update ${path} (${summary})`);
460
+ return { changed: true, path, skipped, conflicts: plan.conflicts };
461
+ }
462
+ await writePatch(path, plan.text, content, mode);
463
+ log(`mcp dsh: updated ${path} (${summary}); restart DSH to load them.`);
464
+ return { changed: true, path, skipped, conflicts: plan.conflicts };
465
+ }
466
+
467
+ /** Remove Kitto-owned rows from the DSH home patch; needs no configuration source. */
468
+ export async function removeDshMcp(state, { dryRun = false, yaml, log = console.log, warn = console.warn } = {}) {
469
+ if (!state.dshHome) throw new Error('DSH MCP removal requires the DSH home directory.');
470
+ const path = join(state.dshHome, 'cordis.patch.yml');
471
+ const { content, mode } = await readPatch(path);
472
+ if (content === null) return { changed: false, path, removed: [] };
473
+
474
+ let module = yaml;
475
+ if (!module) {
476
+ try {
477
+ module = await loadDshYaml();
478
+ } catch (error) {
479
+ warn(`mcp dsh: skipped (cannot load the yaml module bundled with DSH: ${error.message})`);
480
+ return { changed: false, path, removed: [], unavailable: true };
481
+ }
482
+ }
483
+ let plan;
484
+ try {
485
+ plan = planDshMcp({ content, rows: [], yaml: module, location: path });
486
+ } catch (error) {
487
+ warn(`mcp dsh: skipped removal (${error.message})`);
488
+ return { changed: false, path, removed: [], skipped: error.message };
489
+ }
490
+ if (!plan.changed) return { changed: false, path, removed: [] };
491
+ const names = plan.removed.map(row => row.config?.serverName ?? row.id);
492
+ const summary = `${names.length} Kitto MCP server${names.length === 1 ? '' : 's'}`;
493
+ if (dryRun) {
494
+ log(`mcp dsh: would remove ${summary} from ${path}`);
495
+ return { changed: true, path, removed: names };
496
+ }
497
+ await writePatch(path, plan.text, content, mode);
498
+ log(`mcp dsh: removed ${summary} from ${path}`);
499
+ return { changed: true, path, removed: names };
500
+ }
package/lib/parity.mjs ADDED
@@ -0,0 +1,64 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { piServers } from './dependencies.mjs';
4
+ import { isDesktopProfile } from './dsh-profile.mjs';
5
+
6
+ // Match the names codex mcp itself writes: bare keys, or quoted names such as
7
+ // `dot.name` (Kitto sync accepts the same set).
8
+ const CODEX_SECTION = /^\[mcp_servers\.(?:"([^"]+)"|([A-Za-z0-9_-]+))\]\s*$/gm;
9
+ const DSH_SERVER = /^\s*serverName:\s*["']?([A-Za-z0-9_-]+)["']?\s*$/gm;
10
+
11
+ async function optionalText(path) {
12
+ try {
13
+ return await readFile(path, 'utf8');
14
+ } catch (error) {
15
+ if (error.code === 'ENOENT') return '';
16
+ throw error;
17
+ }
18
+ }
19
+
20
+ function names(text, pattern) {
21
+ return [...new Set([...text.matchAll(pattern)].map(match => match[2] ?? match[1]))].sort();
22
+ }
23
+
24
+ export async function codexMcpNames(home) {
25
+ if (!home) return [];
26
+ return names(await optionalText(join(home, 'config.toml')), CODEX_SECTION);
27
+ }
28
+
29
+ export async function dshMcpNames(home, profile = 'web') {
30
+ if (!home) return [];
31
+ const files = [join(home, 'cordis.patch.yml'), join(home, 'profiles', profile, 'cordis.patch.yml')];
32
+ const found = new Set();
33
+ for (const file of files) for (const name of names(await optionalText(file), DSH_SERVER)) found.add(name);
34
+ return [...found].sort();
35
+ }
36
+
37
+ /** Compare the MCP server names each selected host actually loads. */
38
+ export async function mcpParity(state) {
39
+ const hosts = {}, globalOnly = [];
40
+ if (state.agents?.includes('pi')) hosts.pi = Object.keys(await piServers(state)).sort();
41
+ if (state.agents?.includes('codex')) hosts.codex = await codexMcpNames(state.codexHome);
42
+ if (state.agents?.includes('dsh')) {
43
+ // The app-managed Desktop profile deliberately receives no Kitto MCP rows.
44
+ if (isDesktopProfile(state.dshProfile)) globalOnly.push('dsh');
45
+ else hosts.dsh = await dshMcpNames(state.dshHome, state.dshProfile || 'web');
46
+ }
47
+ const all = [...new Set(Object.values(hosts).flat())].sort();
48
+ const missing = {};
49
+ for (const [host, entries] of Object.entries(hosts)) missing[host] = all.filter(name => !entries.includes(name));
50
+ return { hosts, all, missing, globalOnly };
51
+ }
52
+
53
+ export async function printMcpParity(state, log = console.log) {
54
+ const parity = await mcpParity(state);
55
+ if (Object.keys(parity.hosts).length === 0 && parity.globalOnly.length === 0) return parity;
56
+ for (const [host, entries] of Object.entries(parity.hosts)) {
57
+ log(`mcp ${host}: ${entries.length ? entries.join(', ') : '(none)'}`);
58
+ }
59
+ for (const host of parity.globalOnly) log(`mcp ${host}: (global-only; MCP sync disabled)`);
60
+ for (const [host, entries] of Object.entries(parity.missing)) {
61
+ if (entries.length) log(`mcp missing on ${host}: ${entries.join(', ')}`);
62
+ }
63
+ return parity;
64
+ }