dsh-mcp-manager-plus 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,1058 @@
1
+ /**
2
+ * dsh-mcp-manager-plus — host half.
3
+ *
4
+ * Serves a small loopback HTTP API over the harness web server so the browser
5
+ * settings page ("MCP 管理") can list, add, edit, enable/disable, restart and
6
+ * delete MCP servers.
7
+ *
8
+ * Durability and live effect are the same mechanism. The profile's user patch
9
+ * layer (`$DSH_HOME/profiles/<profile>/cordis.patch.yml`) is the durable
10
+ * record, and the profile runs with `patchReload: live`, so the loader
11
+ * re-composes the tree about a second after the file changes. This plugin
12
+ * therefore never mutates the running loader tree for a configuration change:
13
+ * it writes the file and reports the live state the loader converges to (which
14
+ * the browser half polls for, briefly, after a write).
15
+ *
16
+ * Safety rules:
17
+ * - Only loopback requests are answered.
18
+ * - A write is refused unless the resulting document still parses as a
19
+ * top-level YAML array of loader patch rows, so a bad edit can never brick
20
+ * the next boot.
21
+ * - Credential-shaped config values (`KEY|PASSWORD|SECRET|TOKEN`) are masked on
22
+ * read and restored from the previous value when written back unchanged.
23
+ *
24
+ * @module dsh-mcp-manager-plus
25
+ */
26
+
27
+ import { accessSync, constants, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
28
+ import { createRequire } from 'node:module';
29
+ import { dirname, join } from 'node:path';
30
+ import { pathToFileURL, fileURLToPath } from 'node:url';
31
+ import { homedir } from 'node:os';
32
+ import {
33
+ MCP_CLIENT_PACKAGE,
34
+ ROW_ID_PREFIX,
35
+ appendBlock,
36
+ dropDisabledOverrides,
37
+ dropOverrides,
38
+ emitDisabledBlock,
39
+ emitInsertBlock,
40
+ insertedIds,
41
+ joinTopLevel,
42
+ readDocument,
43
+ readPatchText,
44
+ removeRowFromBlock,
45
+ updateRowInBlock,
46
+ validateDocument,
47
+ } from './patch.js';
48
+ import { parseMcpConfig } from './import.js';
49
+
50
+ /** Route prefix for this plugin's API. */
51
+ const API_PREFIX = '/mcp-manager-plus';
52
+ /** How long a listing may be reused, in ms. */
53
+ const CACHE_TTL_MS = 300;
54
+ /** Config keys whose values never travel to the browser in the clear. */
55
+ const SECRET_KEY_RE = /KEY|PASSWORD|SECRET|TOKEN/i;
56
+ /** The mask the browser receives and may echo back unchanged. */
57
+ const SECRET_MASK = '••••••••';
58
+ /** Config keys this plugin models explicitly; every other key passes through. */
59
+ const STRUCTURED_KEYS = new Set([
60
+ 'serverName',
61
+ 'transport',
62
+ 'command',
63
+ 'args',
64
+ 'env',
65
+ 'cwd',
66
+ 'url',
67
+ 'headers',
68
+ ]);
69
+
70
+ /**
71
+ * Built-in harness tool providers that present an MCP-shaped tool set. They
72
+ * are shown read-only so the page accounts for every tool source, matching the
73
+ * "Built-in" row a user sees beside their own servers.
74
+ */
75
+ const BUILTIN_PROVIDERS = [
76
+ { service: 'computerUse', serverName: 'computer-use', label: 'Computer Use' },
77
+ { service: 'browserUse', serverName: 'browser-use', label: 'Browser Use' },
78
+ ];
79
+
80
+ // ── response language ───────────────────────────────────────────────────────
81
+
82
+ /**
83
+ * User-facing host strings in the two shipped languages. The browser picks one
84
+ * per request with a `?lang=` query parameter; anything unrecognized falls
85
+ * back to Chinese, this deployment's default. `{name}`-style placeholders are
86
+ * filled by `tr`.
87
+ */
88
+ const MSGS = {
89
+ zh: {
90
+ loopbackOnly: '仅允许本机访问',
91
+ unknownRoute: '未知接口 {route}',
92
+ bodyTooLarge: '请求体过大',
93
+ badJson: '请求体不是合法 JSON:{detail}',
94
+ rowMissingId: '缺少行 id',
95
+ builtinMissingId: '内置行缺少 id,无法切换',
96
+ nameRequired: '服务名不能为空',
97
+ nameInvalid: '服务名只能包含字母、数字、下划线和连字符,长度 1–32',
98
+ writeCancelled: '{reason}(已取消写入)',
99
+ editTargetMissing: '未找到要编辑的服务器 {name}',
100
+ nameTaken: '服务名 {name} 已存在',
101
+ idTaken: '行 id {id} 已被占用,请换一个服务名',
102
+ removeTargetMissing: '未找到受管行 {id}(部署内置的服务器不能删除,只能停用)',
103
+ restartTargetMissing: '未找到服务器 {id}',
104
+ restartDisabled: '服务器 {name} 已停用,请先启用',
105
+ restartUnmounted: '服务器 {name} 未挂载,无法重启',
106
+ restartUnsupported: '当前载入器不支持就地重启,请重启 dsh 进程',
107
+ restarted: '已重启 {name}',
108
+ noServerName: '行 {id} 缺少 config.serverName,已跳过管理',
109
+ builtinSuffix: '(内置)',
110
+ importNone: '未能导入任何服务器:{detail}',
111
+ importRecognized: '已识别 {source} 配置',
112
+ importCreated: '新增 {names}',
113
+ importUpdated: '更新 {names}',
114
+ importSkipped: '跳过 {names}',
115
+ importUnnamed: '未命名',
116
+ editSingleOnly: '编辑模式一次只能保存一个服务器,但配置里有 {count} 个:{names}',
117
+ noServerEntries: '未在配置中找到任何 MCP 服务器条目',
118
+ importEditUpdated: '已识别 {source} 配置;更新 {name}',
119
+ renamedFrom: '(由 {name} 重命名)',
120
+ },
121
+ en: {
122
+ loopbackOnly: 'Only local (loopback) requests are allowed',
123
+ unknownRoute: 'Unknown endpoint {route}',
124
+ bodyTooLarge: 'Request body too large',
125
+ badJson: 'Request body is not valid JSON: {detail}',
126
+ rowMissingId: 'Missing row id',
127
+ builtinMissingId: 'Built-in row has no id and cannot be toggled',
128
+ nameRequired: 'Server name must not be empty',
129
+ nameInvalid: 'Server name may only contain letters, digits, underscores and hyphens, 1–32 characters',
130
+ writeCancelled: '{reason} (write cancelled)',
131
+ editTargetMissing: 'Server to edit not found: {name}',
132
+ nameTaken: 'Server name {name} already exists',
133
+ idTaken: 'Row id {id} is already taken; choose another server name',
134
+ removeTargetMissing: 'Managed row {id} not found (bundle-provided servers cannot be deleted, only disabled)',
135
+ restartTargetMissing: 'Server not found: {id}',
136
+ restartDisabled: 'Server {name} is disabled; enable it first',
137
+ restartUnmounted: 'Server {name} is not mounted and cannot be restarted',
138
+ restartUnsupported: 'The current loader does not support in-place restarts; restart the dsh process',
139
+ restarted: 'Restarted {name}',
140
+ noServerName: 'Row {id} lacks config.serverName; skipped from management',
141
+ builtinSuffix: ' (built-in)',
142
+ importNone: 'No servers could be imported: {detail}',
143
+ importRecognized: 'Recognized {source} configuration',
144
+ importCreated: 'Added {names}',
145
+ importUpdated: 'Updated {names}',
146
+ importSkipped: 'Skipped {names}',
147
+ importUnnamed: 'Unnamed',
148
+ editSingleOnly: 'Edit mode saves one server at a time, but the configuration contains {count}: {names}',
149
+ noServerEntries: 'No MCP server entries found in the configuration',
150
+ importEditUpdated: 'Recognized {source} configuration; updated {name}',
151
+ renamedFrom: ' (renamed from {name})',
152
+ },
153
+ };
154
+
155
+ /**
156
+ * Translate one message key for a request's language.
157
+ * @param lang - `'en'` or anything else (treated as Chinese).
158
+ * @param key - a `MSGS` key; an unknown key falls back to the key itself.
159
+ * @param params - placeholder values for `{name}` slots.
160
+ */
161
+ function tr(lang, key, params) {
162
+ const table = lang === 'en' ? MSGS.en : MSGS.zh;
163
+ let text = table[key] !== undefined ? table[key] : key;
164
+ if (params !== undefined) {
165
+ text = text.replace(/\{(\w+)\}/gu, (match, name) =>
166
+ params[name] !== undefined ? String(params[name]) : match,
167
+ );
168
+ }
169
+ return text;
170
+ }
171
+
172
+ /** The language a request asked for; `'en'` or the Chinese default. */
173
+ function requestLang(url) {
174
+ return url.searchParams.get('lang') === 'en' ? 'en' : 'zh';
175
+ }
176
+
177
+ /** Join a display list the way the current language spells it. */
178
+ function joinList(lang, names) {
179
+ return names.join(lang === 'en' ? ', ' : '、');
180
+ }
181
+
182
+ /**
183
+ * Load `js-yaml` with the entry-list dialect — a `!!js` tag carrying an
184
+ * expression node — which is exactly the dialect the loader's include plugin
185
+ * parses.
186
+ *
187
+ * Resolution is anchored deliberately. This package is installed into a
188
+ * profile, and `js-yaml` reaches it hoisted at the profile root; a plain
189
+ * `import('js-yaml')` also works there, but a linked or nested install can put
190
+ * the plugin somewhere that walk does not reach. So the profile directory is
191
+ * tried first — that is where the loader's own include plugin resolves it from
192
+ * — with a normal import as the fallback.
193
+ *
194
+ * @param ctx - host context, used to anchor resolution at the profile directory.
195
+ * @returns the module plus a schema able to round-trip `!!js` scalars.
196
+ */
197
+ async function loadYaml(ctx) {
198
+ const yaml = await resolveYaml(resolvePatchPath(ctx).profileDir);
199
+ const jsExpr = new yaml.Type('tag:yaml.org,2002:js', {
200
+ kind: 'scalar',
201
+ resolve: (data) => typeof data === 'string',
202
+ construct: (data) => ({ __jsExpr: data }),
203
+ predicate: (value) =>
204
+ value !== null && typeof value === 'object' && typeof value.__jsExpr === 'string',
205
+ represent: (value) => value.__jsExpr,
206
+ });
207
+ return { yaml, schema: yaml.JSON_SCHEMA.extend(jsExpr) };
208
+ }
209
+
210
+ /** Resolve the `js-yaml` module, preferring the profile's own copy. */
211
+ async function resolveYaml(anchorDir) {
212
+ const candidates = [];
213
+ if (typeof anchorDir === 'string' && anchorDir !== '') candidates.push(anchorDir);
214
+ // The plugin's own package directory: an installed copy sits inside the
215
+ // profile's node_modules, so this reaches the same hoisted `js-yaml` even
216
+ // when the profile directory could not be resolved from the loader.
217
+ candidates.push(dirname(fileURLToPath(import.meta.url)));
218
+ candidates.push(process.cwd());
219
+ const home = dshHome();
220
+ candidates.push(join(home, 'profiles', argvProfile() ?? 'web'));
221
+ candidates.push(join(home, 'profiles'));
222
+
223
+ for (const anchor of candidates) {
224
+ try {
225
+ const require = createRequire(join(anchor, 'package.json'));
226
+ const loaded = await import(pathToFileURL(require.resolve('js-yaml')).href);
227
+ return loaded.default ?? loaded;
228
+ } catch {
229
+ // Try the next anchor.
230
+ }
231
+ }
232
+ // Last resort: an ordinary bare import, which succeeds when this package was
233
+ // installed with `js-yaml` as a real dependency.
234
+ const loaded = await import('js-yaml');
235
+ return loaded.default ?? loaded;
236
+ }
237
+
238
+ /** The harness home, honouring a `DSH_HOME` override. */
239
+ function dshHome() {
240
+ const override = process.env.DSH_HOME;
241
+ return override && override.trim() !== '' ? override : join(homedir(), '.dsh');
242
+ }
243
+
244
+ /** The profile this process booted, from `--profile <name>` when present. */
245
+ function argvProfile() {
246
+ const argv = process.argv;
247
+ const flag = argv.indexOf('--profile');
248
+ if (flag !== -1 && flag + 1 < argv.length && !argv[flag + 1].startsWith('-')) return argv[flag + 1];
249
+ return undefined;
250
+ }
251
+
252
+ /**
253
+ * Resolve the user patch file. The authoritative answer is the
254
+ * `cordis:include` entry the loader actually read — a host that owns the
255
+ * profile directory, such as DSH Desktop, may place it elsewhere — with the
256
+ * conventional path as the fallback.
257
+ * @param ctx - host context holding the loader.
258
+ * @returns `{ patchPath, profileDir }`.
259
+ */
260
+ function resolvePatchPath(ctx) {
261
+ const loader = ctx.get('loader');
262
+ if (loader !== undefined && typeof loader.entries === 'function') {
263
+ for (const entry of loader.entries()) {
264
+ const options = entry.options ?? {};
265
+ if (options.name !== 'cordis:include') continue;
266
+ const config = options.config;
267
+ if (config === null || typeof config !== 'object') continue;
268
+ const path = config.path;
269
+ if (typeof path !== 'string' || !path.includes('cordis.yml')) continue;
270
+ const patchPath = fromFileUrl(path).replace(/cordis\.yml$/u, 'cordis.patch.yml');
271
+ return { patchPath, profileDir: dirname(patchPath) };
272
+ }
273
+ }
274
+ const profileDir = join(dshHome(), 'profiles', argvProfile() ?? 'web');
275
+ return { patchPath: join(profileDir, 'cordis.patch.yml'), profileDir };
276
+ }
277
+
278
+ /** Resolve a `file://` URL or plain path to a native path. */
279
+ function fromFileUrl(value) {
280
+ if (!value.startsWith('file://')) return value;
281
+ try {
282
+ const path = new URL(value).pathname;
283
+ // Windows file URLs carry a leading slash before the drive letter.
284
+ return /^\/[A-Za-z]:/u.test(path) ? path.slice(1) : path;
285
+ } catch {
286
+ return value.replace(/^file:\/\//u, '');
287
+ }
288
+ }
289
+
290
+ // ── secret handling ─────────────────────────────────────────────────────────
291
+
292
+ /** Mask credential-shaped values in a shallow string map. */
293
+ function maskMap(map) {
294
+ if (map === null || typeof map !== 'object' || Array.isArray(map)) return {};
295
+ const masked = {};
296
+ for (const [key, value] of Object.entries(map)) {
297
+ masked[key] =
298
+ SECRET_KEY_RE.test(key) && typeof value === 'string' && value !== '' ? SECRET_MASK : value;
299
+ }
300
+ return masked;
301
+ }
302
+
303
+ /** Restore masked values from the previous map so an untouched field round-trips. */
304
+ function unmaskMap(next, previous) {
305
+ if (next === null || typeof next !== 'object' || Array.isArray(next)) return {};
306
+ const restored = {};
307
+ for (const [key, value] of Object.entries(next)) {
308
+ const before = previous !== null && typeof previous === 'object' ? previous[key] : undefined;
309
+ restored[key] = value === SECRET_MASK && typeof before === 'string' ? before : value;
310
+ }
311
+ return restored;
312
+ }
313
+
314
+ // ── live-state reads ────────────────────────────────────────────────────────
315
+
316
+ /** Cordis fiber states, mirrored as the readable phase the browser shows. */
317
+ const FIBER_PHASE = { 0: 'pending', 1: 'loading', 2: 'active', 3: 'failed', 4: null, 5: 'unloading' };
318
+
319
+ /**
320
+ * Find the live loader entry for one managed server. Matching is by package
321
+ * plus `config.serverName` rather than by entry id, because a row inside an
322
+ * include subtree carries a prefixed id this plugin cannot predict.
323
+ * @param ctx - host context.
324
+ * @param serverName - the `serverName` the row configured.
325
+ * @returns the entry, or undefined.
326
+ */
327
+ function findEntry(ctx, serverName) {
328
+ const loader = ctx.get('loader');
329
+ if (loader === undefined || typeof loader.entries !== 'function') return undefined;
330
+ for (const entry of loader.entries()) {
331
+ const options = entry.options ?? {};
332
+ if (options.name !== MCP_CLIENT_PACKAGE) continue;
333
+ const config = options.config;
334
+ if (config === null || typeof config !== 'object') continue;
335
+ if (config.serverName === serverName) return entry;
336
+ }
337
+ return undefined;
338
+ }
339
+
340
+ /** Read one entry's live phase. */
341
+ function phaseOf(entry, disabled) {
342
+ if (disabled) return 'disabled';
343
+ if (entry === undefined) return 'pending';
344
+ const fiber = entry.fiber;
345
+ if (fiber === undefined) return entry.disabled === true ? 'disabled' : 'pending';
346
+ return FIBER_PHASE[fiber.state] ?? null;
347
+ }
348
+
349
+ /** Every model-facing tool schema, defensively read. */
350
+ function schemasOf(ctx) {
351
+ const tools = ctx.get('tools');
352
+ if (tools === undefined || typeof tools.schemas !== 'function') return [];
353
+ try {
354
+ return tools.schemas();
355
+ } catch {
356
+ return [];
357
+ }
358
+ }
359
+
360
+ /**
361
+ * The MCP tools a server currently contributes. Names are
362
+ * `mcp__<serverName>__<rawName>`; the separating `__` is the LAST one, which is
363
+ * the bridge's own naming contract.
364
+ * @param ctx - host context.
365
+ * @param serverName - the server namespace.
366
+ * @returns `{ name, fullName, description }` rows using raw tool names.
367
+ */
368
+ function toolsOfServer(ctx, serverName) {
369
+ const prefix = `mcp__${serverName}__`;
370
+ const found = [];
371
+ for (const schema of schemasOf(ctx)) {
372
+ const name = schema?.name;
373
+ if (typeof name !== 'string' || !name.startsWith(prefix)) continue;
374
+ found.push({
375
+ name: name.slice(prefix.length),
376
+ fullName: name,
377
+ description: typeof schema.description === 'string' ? schema.description : '',
378
+ });
379
+ }
380
+ found.sort((a, b) => a.name.localeCompare(b.name));
381
+ return found;
382
+ }
383
+
384
+ /**
385
+ * Tools a built-in provider service contributes. The service owns a
386
+ * registration surface but publishes no catalog of its own names, so the list
387
+ * is derived from the registry by the provider's naming convention: built-in
388
+ * tools carry no `mcp__` namespace, and the service key maps to a snake-case
389
+ * prefix (`computerUse` → `computer_use_`). A service with no matching tools
390
+ * reports an empty list rather than a wrong one.
391
+ * @param ctx - host context.
392
+ * @param key - the service key.
393
+ * @returns tool rows.
394
+ */
395
+ function toolsOfBuiltin(ctx, key) {
396
+ const snake = key.replace(/[A-Z]/gu, (c) => `_${c.toLowerCase()}`);
397
+ const found = [];
398
+ for (const schema of schemasOf(ctx)) {
399
+ const name = schema?.name;
400
+ if (typeof name !== 'string' || name.startsWith('mcp__')) continue;
401
+ if (!name.startsWith(`${snake}_`) && !name.startsWith(`${snake}-`)) continue;
402
+ found.push({
403
+ name,
404
+ fullName: name,
405
+ description: typeof schema.description === 'string' ? schema.description : '',
406
+ });
407
+ }
408
+ found.sort((a, b) => a.name.localeCompare(b.name));
409
+ return found;
410
+ }
411
+
412
+ // ── inventory ───────────────────────────────────────────────────────────────
413
+
414
+ /**
415
+ * Build the server inventory the browser renders: user-managed rows from the
416
+ * profile patch layer, deployment-provided rows from the composed tree, and the
417
+ * harness's built-in tool providers.
418
+ * @param ctx - host context.
419
+ * @param document - the parsed patch document.
420
+ * @param lang - response language for issue strings and display labels.
421
+ * @returns `{ servers, issues }`.
422
+ */
423
+ function buildInventory(ctx, document, lang = 'zh') {
424
+ const issues = [...document.issues];
425
+ const servers = [];
426
+ const claimed = new Set();
427
+
428
+ for (const row of document.rows) {
429
+ const config = row.config;
430
+ const serverName = typeof config.serverName === 'string' ? config.serverName : '';
431
+ if (serverName === '') {
432
+ issues.push(tr(lang, 'noServerName', { id: row.id || '(no id)' }));
433
+ continue;
434
+ }
435
+ claimed.add(serverName);
436
+ const disabled = document.overrides.disabled.get(row.id) === true;
437
+ const entry = findEntry(ctx, serverName);
438
+ const tools = disabled ? [] : toolsOfServer(ctx, serverName);
439
+ servers.push({
440
+ id: row.id,
441
+ serverName,
442
+ displayName: serverName,
443
+ source: 'user',
444
+ origin: 'patch',
445
+ editable: true,
446
+ removable: true,
447
+ enabled: !disabled,
448
+ transport: config.transport === 'streamable-http' ? 'streamable-http' : 'stdio',
449
+ command: typeof config.command === 'string' ? config.command : '',
450
+ args: Array.isArray(config.args) ? config.args.filter((a) => typeof a === 'string') : [],
451
+ env: maskMap(config.env),
452
+ cwd: typeof config.cwd === 'string' ? config.cwd : '',
453
+ url: typeof config.url === 'string' ? config.url : '',
454
+ headers: maskMap(config.headers),
455
+ live: {
456
+ mounted: entry !== undefined,
457
+ phase: phaseOf(entry, disabled),
458
+ toolCount: tools.length,
459
+ tools,
460
+ },
461
+ });
462
+ }
463
+
464
+ // Deployment-provided MCP rows: composed rows the user patch layer does not
465
+ // own. They are togglable through the patch layer — that is what the layer is
466
+ // for — but never editable here, because their configuration belongs to a
467
+ // bundle.
468
+ const loader = ctx.get('loader');
469
+ if (loader !== undefined && typeof loader.entries === 'function') {
470
+ for (const entry of loader.entries()) {
471
+ const options = entry.options ?? {};
472
+ if (options.name !== MCP_CLIENT_PACKAGE) continue;
473
+ const config = options.config;
474
+ if (config === null || typeof config !== 'object') continue;
475
+ const serverName = typeof config.serverName === 'string' ? config.serverName : '';
476
+ if (serverName === '' || claimed.has(serverName)) continue;
477
+ claimed.add(serverName);
478
+ const id = typeof options.id === 'string' ? options.id : '';
479
+ const off = entry.disabled === true || (id !== '' && document.overrides.disabled.get(id) === true);
480
+ const tools = off ? [] : toolsOfServer(ctx, serverName);
481
+ servers.push({
482
+ id,
483
+ serverName,
484
+ displayName: serverName,
485
+ source: 'bundle',
486
+ origin: 'bundle',
487
+ editable: false,
488
+ removable: false,
489
+ enabled: !off,
490
+ transport: config.transport === 'streamable-http' ? 'streamable-http' : 'stdio',
491
+ command: typeof config.command === 'string' ? config.command : '',
492
+ args: Array.isArray(config.args) ? config.args.filter((a) => typeof a === 'string') : [],
493
+ env: maskMap(config.env),
494
+ cwd: typeof config.cwd === 'string' ? config.cwd : '',
495
+ url: typeof config.url === 'string' ? config.url : '',
496
+ headers: maskMap(config.headers),
497
+ live: {
498
+ mounted: entry.fiber !== undefined,
499
+ phase: phaseOf(entry, off),
500
+ toolCount: tools.length,
501
+ tools,
502
+ },
503
+ });
504
+ }
505
+ }
506
+
507
+ for (const provider of BUILTIN_PROVIDERS) {
508
+ if (ctx.get(provider.service) === undefined) continue;
509
+ if (claimed.has(provider.serverName)) continue;
510
+ claimed.add(provider.serverName);
511
+ const tools = toolsOfBuiltin(ctx, provider.service);
512
+ servers.push({
513
+ id: `builtin-${provider.serverName}`,
514
+ serverName: provider.serverName,
515
+ displayName: `${provider.label}${tr(lang, 'builtinSuffix')}`,
516
+ source: 'builtin',
517
+ origin: 'harness',
518
+ editable: false,
519
+ removable: false,
520
+ enabled: true,
521
+ transport: 'built-in',
522
+ command: '',
523
+ args: [],
524
+ env: {},
525
+ cwd: '',
526
+ url: '',
527
+ headers: {},
528
+ live: { mounted: true, phase: 'active', toolCount: tools.length, tools },
529
+ });
530
+ }
531
+
532
+ const order = { user: 0, bundle: 1, builtin: 2 };
533
+ servers.sort((a, b) => {
534
+ const bySource = (order[a.source] ?? 9) - (order[b.source] ?? 9);
535
+ return bySource !== 0 ? bySource : a.serverName.localeCompare(b.serverName);
536
+ });
537
+
538
+ return { servers, issues };
539
+ }
540
+
541
+ // ── config normalization ────────────────────────────────────────────────────
542
+
543
+ /**
544
+ * Validate a server name against the bridge's own contract.
545
+ * @param name - the submitted name.
546
+ * @param lang - response language for the error message.
547
+ * @returns an error message, or null when acceptable.
548
+ */
549
+ function validateServerName(name, lang = 'zh') {
550
+ if (typeof name !== 'string' || name.trim() === '') return tr(lang, 'nameRequired');
551
+ if (!/^[A-Za-z0-9_-]{1,32}$/u.test(name)) {
552
+ return tr(lang, 'nameInvalid');
553
+ }
554
+ return null;
555
+ }
556
+
557
+ /**
558
+ * Normalize a submitted form into the bridge's own config key set.
559
+ *
560
+ * An OMITTED field is not the same as an emptied one: a caller that does not
561
+ * send `env` at all is preserving it, while a caller that sends an empty object
562
+ * is clearing it. That distinction is what keeps a partial update from silently
563
+ * deleting configuration it never mentioned.
564
+ * @param input - the submitted form.
565
+ * @param previous - the row's existing config, when this is an edit.
566
+ * @returns the config to write.
567
+ */
568
+ function normalizeConfig(input, previous) {
569
+ const config = { serverName: input.serverName };
570
+ const http = input.transport === 'streamable-http';
571
+ config.transport = http ? 'streamable-http' : 'stdio';
572
+ if (http) {
573
+ if (typeof input.url === 'string' && input.url.trim() !== '') config.url = input.url.trim();
574
+ else if (typeof previous?.url === 'string') config.url = previous.url;
575
+ const headers = input.headers === undefined ? previous?.headers : unmaskMap(input.headers, previous?.headers);
576
+ if (headers !== null && typeof headers === 'object' && Object.keys(headers).length > 0) {
577
+ config.headers = headers;
578
+ }
579
+ } else {
580
+ if (typeof input.command === 'string' && input.command.trim() !== '') config.command = input.command.trim();
581
+ else if (typeof previous?.command === 'string') config.command = previous.command;
582
+ const args =
583
+ input.args === undefined
584
+ ? previous?.args
585
+ : Array.isArray(input.args)
586
+ ? input.args.filter((a) => typeof a === 'string' && a !== '')
587
+ : undefined;
588
+ if (Array.isArray(args) && args.length > 0) config.args = args;
589
+ const env = input.env === undefined ? previous?.env : unmaskMap(input.env, previous?.env);
590
+ if (env !== null && typeof env === 'object' && Object.keys(env).length > 0) config.env = env;
591
+ if (typeof input.cwd === 'string' && input.cwd.trim() !== '') config.cwd = input.cwd.trim();
592
+ else if (typeof previous?.cwd === 'string') config.cwd = previous.cwd;
593
+ }
594
+ // Pass through every key this form does not model, so editing a server never
595
+ // silently drops configuration it already carried.
596
+ if (previous !== null && typeof previous === 'object') {
597
+ for (const [key, value] of Object.entries(previous)) {
598
+ if (key in config || STRUCTURED_KEYS.has(key)) continue;
599
+ config[key] = value;
600
+ }
601
+ }
602
+ return config;
603
+ }
604
+
605
+ // ── writes ──────────────────────────────────────────────────────────────────
606
+
607
+ /** Serialize writes: two concurrent edits must not interleave a read-modify-write. */
608
+ let writeQueue = Promise.resolve();
609
+ function queuedWrite(task) {
610
+ const run = writeQueue.then(task, task);
611
+ writeQueue = run.then(
612
+ () => undefined,
613
+ () => undefined,
614
+ );
615
+ return run;
616
+ }
617
+
618
+ /**
619
+ * Atomically replace the patch file after validating the candidate.
620
+ * @param patchPath - absolute path.
621
+ * @param text - candidate document.
622
+ * @param yaml - the `js-yaml` module.
623
+ * @param schema - the entry-list schema.
624
+ * @param lang - response language for the refusal message.
625
+ */
626
+ function commit(patchPath, text, yaml, schema, lang = 'zh') {
627
+ const invalid = validateDocument(text, yaml, schema);
628
+ if (invalid !== null) throw new Error(tr(lang, 'writeCancelled', { reason: invalid }));
629
+ mkdirSync(dirname(patchPath), { recursive: true });
630
+ const temp = `${patchPath}.tmp-${process.pid}-${Date.now()}`;
631
+ writeFileSync(temp, text);
632
+ renameSync(temp, patchPath);
633
+ }
634
+
635
+ /**
636
+ * Insert or update one managed server in the profile patch layer.
637
+ * @param ctx - host context.
638
+ * @param input - the submitted form (`originalName` identifies the edited row).
639
+ * @param lang - response language for error messages.
640
+ * @returns `{ action, id, serverName }`.
641
+ */
642
+ async function saveServer(ctx, input, lang = 'zh') {
643
+ const serverName = typeof input.serverName === 'string' ? input.serverName.trim() : '';
644
+ const invalid = validateServerName(serverName, lang);
645
+ if (invalid !== null) throw new Error(invalid);
646
+ const { patchPath } = resolvePatchPath(ctx);
647
+ const { yaml, schema } = await loadYaml(ctx);
648
+
649
+ return queuedWrite(async () => {
650
+ let document = readDocument(readPatchText(patchPath), yaml, schema);
651
+ // `originalName` is what makes this an EDIT: it names the row being
652
+ // changed, which is how a rename keeps its row id and its overrides. With
653
+ // no `originalName` this is a CREATE, and a name already in use is an
654
+ // error rather than a silent overwrite of someone else's server.
655
+ const originalName = typeof input.originalName === 'string' ? input.originalName.trim() : '';
656
+ const editing = originalName !== '';
657
+ const existing = editing
658
+ ? document.rows.find((row) => row.config.serverName === originalName)
659
+ : undefined;
660
+ if (editing && existing === undefined) {
661
+ throw new Error(tr(lang, 'editTargetMissing', { name: originalName }));
662
+ }
663
+ if (!editing && document.rows.some((row) => row.config.serverName === serverName)) {
664
+ throw new Error(tr(lang, 'nameTaken', { name: serverName }));
665
+ }
666
+ const config = normalizeConfig({ ...input, serverName }, existing?.config ?? null);
667
+
668
+ if (existing !== undefined) {
669
+ // Rewriting through the block helper keeps every sibling row in the same
670
+ // `- insert:` block, and keeps this row's id.
671
+ const text = updateRowInBlock(
672
+ document.parts,
673
+ existing,
674
+ { id: existing.id, name: MCP_CLIENT_PACKAGE, config },
675
+ yaml,
676
+ schema,
677
+ );
678
+ commit(patchPath, text, yaml, schema, lang);
679
+ return { action: 'updated', id: existing.id, serverName };
680
+ }
681
+
682
+ const id = `${ROW_ID_PREFIX}${serverName}`;
683
+ const taken = insertedIds(document.parts, yaml, schema);
684
+ // A name that already appears as an override target is taken too: writing
685
+ // an insert under it would produce two rows sharing one id.
686
+ for (const overrideId of document.overrides.items.keys()) taken.add(overrideId);
687
+ if (taken.has(id)) throw new Error(tr(lang, 'idTaken', { id }));
688
+ const text = appendBlock(
689
+ document.parts,
690
+ emitInsertBlock([{ id, name: MCP_CLIENT_PACKAGE, config }]),
691
+ );
692
+ commit(patchPath, text, yaml, schema, lang);
693
+ return { action: 'created', id, serverName };
694
+ });
695
+ }
696
+
697
+ /**
698
+ * Enable or disable one server through the patch layer.
699
+ *
700
+ * The `disabled` override is the only lever a user layer has, and its meaning
701
+ * depends on which layer wrote the row:
702
+ * - off → append `- id` + `disabled: true`, which wins over any lower layer;
703
+ * - on for a row this plugin inserted → drop the override (the row is on by
704
+ * default), because `disabled: false` would be redundant noise;
705
+ * - on for a row a bundle inserted → write `disabled: false`, since dropping
706
+ * the override cannot re-enable a row a lower layer holds down.
707
+ * @param ctx - host context.
708
+ * @param input - `{ id, enabled, source }`.
709
+ * @param lang - response language for error messages.
710
+ */
711
+ async function toggleServer(ctx, input, lang = 'zh') {
712
+ const id = typeof input.id === 'string' ? input.id : '';
713
+ if (id === '') throw new Error(tr(lang, 'rowMissingId'));
714
+ const enabled = input.enabled === true;
715
+ const { patchPath } = resolvePatchPath(ctx);
716
+ const { yaml, schema } = await loadYaml(ctx);
717
+
718
+ return queuedWrite(async () => {
719
+ const document = readDocument(readPatchText(patchPath), yaml, schema);
720
+ const ownedByPlugin = document.rows.some((row) => row.id === id);
721
+ if (!ownedByPlugin && id === '') throw new Error(tr(lang, 'builtinMissingId'));
722
+
723
+ const { parts } = dropDisabledOverrides(document.parts, [id], yaml, schema);
724
+ const block = !enabled
725
+ ? emitDisabledBlock(id, true)
726
+ : ownedByPlugin
727
+ ? null
728
+ : emitDisabledBlock(id, false);
729
+ const text = block === null ? joinTopLevel(parts) : appendBlock(parts, block);
730
+ commit(patchPath, text, yaml, schema, lang);
731
+ return { action: enabled ? 'enabled' : 'disabled', id };
732
+ });
733
+ }
734
+
735
+ /**
736
+ * Remove one managed server: its row inside its insert block, plus every
737
+ * override that targeted it.
738
+ * @param ctx - host context.
739
+ * @param input - `{ id }`.
740
+ * @param lang - response language for error messages.
741
+ */
742
+ async function removeServer(ctx, input, lang = 'zh') {
743
+ const id = typeof input.id === 'string' ? input.id : '';
744
+ if (id === '') throw new Error(tr(lang, 'rowMissingId'));
745
+ const { patchPath } = resolvePatchPath(ctx);
746
+ const { yaml, schema } = await loadYaml(ctx);
747
+
748
+ return queuedWrite(async () => {
749
+ let document = readDocument(readPatchText(patchPath), yaml, schema);
750
+ const target = document.rows.find((row) => row.id === id);
751
+ if (target === undefined) {
752
+ throw new Error(tr(lang, 'removeTargetMissing', { id }));
753
+ }
754
+ // Dropping the row keeps its siblings; only an emptied block disappears.
755
+ let text = removeRowFromBlock(document.parts, target, yaml, schema).text;
756
+ document = readDocument(text, yaml, schema);
757
+ text = joinTopLevel(dropOverrides(document.parts, [id], yaml, schema).parts);
758
+ commit(patchPath, text, yaml, schema, lang);
759
+ return { action: 'removed', id };
760
+ });
761
+ }
762
+
763
+ /**
764
+ * Restart one server's live connection by disposing and re-initializing its
765
+ * loader entry. The row's configuration is untouched, so a server whose
766
+ * transport died — a crashed stdio child past its reconnect budget — recovers
767
+ * without a process restart.
768
+ * @param ctx - host context.
769
+ * @param input - `{ id }`.
770
+ * @param lang - response language for messages.
771
+ * @returns a message describing what happened.
772
+ */
773
+ async function restartServer(ctx, input, lang = 'zh') {
774
+ const id = typeof input.id === 'string' ? input.id : '';
775
+ if (id === '') throw new Error(tr(lang, 'rowMissingId'));
776
+ const { patchPath } = resolvePatchPath(ctx);
777
+ const { yaml, schema } = await loadYaml(ctx);
778
+ const document = readDocument(readPatchText(patchPath), yaml, schema);
779
+ const inventory = buildInventory(ctx, document, lang);
780
+ const server = inventory.servers.find((entry) => entry.id === id);
781
+ if (server === undefined) throw new Error(tr(lang, 'restartTargetMissing', { id }));
782
+ if (!server.enabled) throw new Error(tr(lang, 'restartDisabled', { name: server.serverName }));
783
+ const entry = findEntry(ctx, server.serverName);
784
+ if (entry === undefined) throw new Error(tr(lang, 'restartUnmounted', { name: server.serverName }));
785
+ if (typeof entry._dispose !== 'function' || typeof entry.init !== 'function') {
786
+ throw new Error(tr(lang, 'restartUnsupported'));
787
+ }
788
+ await entry._dispose();
789
+ await entry.init();
790
+ return tr(lang, 'restarted', { name: server.serverName });
791
+ }
792
+
793
+ /**
794
+ * Import servers from a pasted configuration document. The document may come
795
+ * from any of the tools this module's parser understands — Claude Code, Cursor,
796
+ * VS Code, Codex, OpenCode, Continue, Pi, Cherry Studio, Windsurf, Qoder,
797
+ * CodeBuddy, TRAE, ZCode, or this plugin's own output — because the parser
798
+ * normalizes their dialects. See `./import.js` for the shape table.
799
+ *
800
+ * `input.originalName` turns this into a single-server EDIT from the JSON
801
+ * editor: the paste is then expected to describe exactly the row named by
802
+ * `originalName`, and renaming it there renames that row (keeping its id and
803
+ * its overrides) instead of creating a second server beside it.
804
+ * @param ctx - host context.
805
+ * @param input - `{ json, originalName? }` (json may be a string or object).
806
+ * @param lang - response language for messages.
807
+ * @returns `{ message, created, updated }`.
808
+ */
809
+ async function importServers(ctx, input, lang = 'zh') {
810
+ const { servers: parsed, source } = parseMcpConfig(input.json);
811
+
812
+ const originalName = typeof input.originalName === 'string' ? input.originalName.trim() : '';
813
+ if (originalName !== '') return importSingleEdit(ctx, parsed, originalName, source, lang);
814
+
815
+ // Re-importing a configuration is an ordinary way to update a server, so an
816
+ // entry naming one that already exists is sent as an edit rather than
817
+ // refused as a duplicate.
818
+ const { patchPath } = resolvePatchPath(ctx);
819
+ const { yaml, schema } = await loadYaml(ctx);
820
+ const existing = new Set(
821
+ readDocument(readPatchText(patchPath), yaml, schema)
822
+ .rows.map((row) => row.config.serverName)
823
+ .filter((name) => typeof name === 'string'),
824
+ );
825
+
826
+ const created = [];
827
+ const updated = [];
828
+ const skipped = [];
829
+ for (const entry of parsed) {
830
+ const serverName = entry.serverName;
831
+ if (serverName === '') {
832
+ skipped.push(tr(lang, 'importUnnamed'));
833
+ continue;
834
+ }
835
+ // One bad entry must not abandon the rest of a paste: the others are
836
+ // usually fine, so report the failure and keep going.
837
+ try {
838
+ const result = await saveServer(ctx, {
839
+ serverName,
840
+ originalName: existing.has(serverName) ? serverName : undefined,
841
+ transport: entry.transport,
842
+ command: entry.command,
843
+ args: entry.args,
844
+ env: entry.env,
845
+ cwd: entry.cwd,
846
+ url: entry.url,
847
+ headers: entry.headers,
848
+ }, lang);
849
+ (result.action === 'created' ? created : updated).push(result.serverName);
850
+ } catch (error) {
851
+ skipped.push(`${serverName}(${String(error?.message ?? error)})`);
852
+ }
853
+ }
854
+
855
+ if (created.length === 0 && updated.length === 0) {
856
+ throw new Error(tr(lang, 'importNone', { detail: skipped.join(lang === 'en' ? '; ' : ';') }));
857
+ }
858
+
859
+ const parts = [tr(lang, 'importRecognized', { source })];
860
+ if (created.length > 0) parts.push(tr(lang, 'importCreated', { names: joinList(lang, created) }));
861
+ if (updated.length > 0) parts.push(tr(lang, 'importUpdated', { names: joinList(lang, updated) }));
862
+ if (skipped.length > 0) parts.push(tr(lang, 'importSkipped', { names: skipped.join(lang === 'en' ? '; ' : ';') }));
863
+ return { message: parts.join(lang === 'en' ? '; ' : ';'), created, updated, skipped };
864
+ }
865
+
866
+ /**
867
+ * Apply a JSON-editor paste to exactly one existing server.
868
+ *
869
+ * The paste is the whole row, so it must describe one server and no more: a
870
+ * document naming several would leave the user guessing which one won. The
871
+ * entry's own name is what the row becomes, so renaming inside the JSON is a
872
+ * rename of that row — `originalName` is what keeps it from turning into a new
873
+ * server beside the old one.
874
+ * @param ctx - host context.
875
+ * @param parsed - servers the paste described.
876
+ * @param originalName - the row being edited.
877
+ * @param source - the detected dialect, for the message.
878
+ * @param lang - response language for messages.
879
+ * @returns `{ message, created, updated }`.
880
+ */
881
+ async function importSingleEdit(ctx, parsed, originalName, source, lang = 'zh') {
882
+ if (parsed.length === 0) throw new Error(tr(lang, 'noServerEntries'));
883
+ if (parsed.length > 1) {
884
+ const names = joinList(lang, parsed.map((entry) => entry.serverName));
885
+ throw new Error(tr(lang, 'editSingleOnly', { count: parsed.length, names }));
886
+ }
887
+
888
+ const entry = parsed[0];
889
+ const serverName = entry.serverName !== '' ? entry.serverName : originalName;
890
+ const result = await saveServer(ctx, {
891
+ serverName,
892
+ originalName,
893
+ transport: entry.transport,
894
+ command: entry.command,
895
+ args: entry.args,
896
+ env: entry.env,
897
+ cwd: entry.cwd,
898
+ url: entry.url,
899
+ headers: entry.headers,
900
+ }, lang);
901
+
902
+ const renamed = serverName !== originalName ? tr(lang, 'renamedFrom', { name: originalName }) : '';
903
+ return {
904
+ message: tr(lang, 'importEditUpdated', { source, name: serverName }) + renamed,
905
+ created: [],
906
+ updated: [serverName],
907
+ skipped: [],
908
+ };
909
+ }
910
+
911
+ // ── HTTP plumbing ───────────────────────────────────────────────────────────
912
+
913
+ /** Read a JSON request body with a size ceiling. */
914
+ async function readJsonBody(req, lang = 'zh', limitBytes = 512 * 1024) {
915
+ const chunks = [];
916
+ let total = 0;
917
+ for await (const chunk of req) {
918
+ total += chunk.length;
919
+ if (total > limitBytes) throw new Error(tr(lang, 'bodyTooLarge'));
920
+ chunks.push(chunk);
921
+ }
922
+ const text = Buffer.concat(chunks).toString('utf8');
923
+ if (text.trim() === '') return {};
924
+ try {
925
+ return JSON.parse(text);
926
+ } catch (error) {
927
+ throw new Error(tr(lang, 'badJson', { detail: String(error?.message ?? error) }));
928
+ }
929
+ }
930
+
931
+ /** Whether a request originated on the loopback interface. */
932
+ function isLoopback(req) {
933
+ const address = req.socket?.remoteAddress ?? '';
934
+ return (
935
+ address === '127.0.0.1' ||
936
+ address === '::1' ||
937
+ address === '::ffff:127.0.0.1' ||
938
+ address.startsWith('127.')
939
+ );
940
+ }
941
+
942
+ /** Write one JSON response. */
943
+ function sendJson(res, status, value) {
944
+ res.writeHead(status, {
945
+ 'content-type': 'application/json; charset=utf-8',
946
+ 'cache-control': 'no-store',
947
+ });
948
+ res.end(JSON.stringify(value));
949
+ }
950
+
951
+ export const name = 'dsh-mcp-manager-plus';
952
+ export const inject = ['webServer'];
953
+
954
+ /**
955
+ * Register the management API on the harness web server.
956
+ * @param ctx - host context carrying `webServer`.
957
+ */
958
+ export function apply(ctx) {
959
+ /** Last inventory snapshot, so a burst of page loads costs one file read. */
960
+ let cache = null;
961
+
962
+ const listServers = async (lang = 'zh') => {
963
+ const { patchPath, profileDir } = resolvePatchPath(ctx);
964
+ const now = Date.now();
965
+ if (cache !== null && now - cache.at < CACHE_TTL_MS && cache.patchPath === patchPath) {
966
+ return cache.value;
967
+ }
968
+ const { yaml, schema } = await loadYaml(ctx);
969
+ const document = readDocument(readPatchText(patchPath), yaml, schema);
970
+ const inventory = buildInventory(ctx, document, lang);
971
+ // Report writability before an edit rather than after one fails. Probing
972
+ // the directory covers a patch file that does not exist yet; probing the
973
+ // file covers one that a previous tool left read-only.
974
+ let writable = true;
975
+ try {
976
+ if (existsSync(patchPath)) accessSync(patchPath, constants.W_OK);
977
+ else accessSync(dirname(patchPath), constants.W_OK);
978
+ } catch {
979
+ writable = false;
980
+ }
981
+ const value = {
982
+ patchPath,
983
+ profileDir,
984
+ writable,
985
+ servers: inventory.servers,
986
+ issues: inventory.issues,
987
+ };
988
+ cache = { at: now, patchPath, value };
989
+ return value;
990
+ };
991
+
992
+ const handler = async (req, res) => {
993
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
994
+ const lang = requestLang(url);
995
+ if (!isLoopback(req)) {
996
+ sendJson(res, 403, { error: tr(lang, 'loopbackOnly') });
997
+ return;
998
+ }
999
+ const route = url.pathname.slice(API_PREFIX.length);
1000
+
1001
+ try {
1002
+ if (route === '/servers' && req.method === 'GET') {
1003
+ sendJson(res, 200, await listServers(lang));
1004
+ return;
1005
+ }
1006
+ if (route === '/refresh' && req.method === 'POST') {
1007
+ cache = null;
1008
+ sendJson(res, 200, await listServers(lang));
1009
+ return;
1010
+ }
1011
+ if (route === '/save' && req.method === 'POST') {
1012
+ const result = await saveServer(ctx, await readJsonBody(req, lang), lang);
1013
+ cache = null;
1014
+ sendJson(res, 200, { ok: true, ...result, state: await listServers(lang) });
1015
+ return;
1016
+ }
1017
+ if (route === '/toggle' && req.method === 'POST') {
1018
+ const result = await toggleServer(ctx, await readJsonBody(req, lang), lang);
1019
+ cache = null;
1020
+ sendJson(res, 200, { ok: true, ...result, state: await listServers(lang) });
1021
+ return;
1022
+ }
1023
+ if (route === '/remove' && req.method === 'POST') {
1024
+ const result = await removeServer(ctx, await readJsonBody(req, lang), lang);
1025
+ cache = null;
1026
+ sendJson(res, 200, { ok: true, ...result, state: await listServers(lang) });
1027
+ return;
1028
+ }
1029
+ if (route === '/restart' && req.method === 'POST') {
1030
+ const message = await restartServer(ctx, await readJsonBody(req, lang), lang);
1031
+ cache = null;
1032
+ sendJson(res, 200, { ok: true, message, state: await listServers(lang) });
1033
+ return;
1034
+ }
1035
+ if (route === '/import' && req.method === 'POST') {
1036
+ const result = await importServers(ctx, await readJsonBody(req, lang), lang);
1037
+ cache = null;
1038
+ sendJson(res, 200, { ok: true, ...result, state: await listServers(lang) });
1039
+ return;
1040
+ }
1041
+ sendJson(res, 404, { error: tr(lang, 'unknownRoute', { route }) });
1042
+ } catch (error) {
1043
+ sendJson(res, 400, { error: String(error?.message ?? error) });
1044
+ }
1045
+ };
1046
+
1047
+ ctx.effect(
1048
+ () =>
1049
+ ctx.webServer.register({
1050
+ kind: 'prefix',
1051
+ path: API_PREFIX,
1052
+ handler,
1053
+ }),
1054
+ 'dsh-mcp-manager-plus: management API',
1055
+ );
1056
+ }
1057
+
1058
+ export default { name, inject, apply };