dsh-mcp-manager-plus 0.4.5 → 0.5.2

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 CHANGED
@@ -24,9 +24,19 @@
24
24
  * @module dsh-mcp-manager-plus
25
25
  */
26
26
 
27
- import { accessSync, constants, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
28
- import { dirname, join } from 'node:path';
29
- import { fileURLToPath } from 'node:url';
27
+ import {
28
+ accessSync,
29
+ constants,
30
+ existsSync,
31
+ mkdirSync,
32
+ readFileSync,
33
+ renameSync,
34
+ statSync,
35
+ writeFileSync,
36
+ } from 'node:fs';
37
+ import { createRequire } from 'node:module';
38
+ import { dirname, isAbsolute, join, resolve as resolvePath } from 'node:path';
39
+ import { fileURLToPath, pathToFileURL } from 'node:url';
30
40
  import { homedir } from 'node:os';
31
41
  import {
32
42
  MCP_CLIENT_PACKAGE,
@@ -55,6 +65,14 @@ const CACHE_TTL_MS = 300;
55
65
  const SECRET_KEY_RE = /KEY|PASSWORD|SECRET|TOKEN/i;
56
66
  /** The mask the browser receives and may echo back unchanged. */
57
67
  const SECRET_MASK = '••••••••';
68
+ /** Package id; also the directory name under the profile's `plugin-data`. */
69
+ const PLUGIN_ID = 'dsh-mcp-manager-plus';
70
+ /** File name of the durable project-binding table. */
71
+ const BINDINGS_FILE = 'bindings.json';
72
+ /** How long a binding read may be reused, in ms. */
73
+ const BINDINGS_TTL_MS = 1000;
74
+ /** The bridge's namespace prefix on every MCP tool name. */
75
+ const MCP_TOOL_PREFIX = 'mcp__';
58
76
  /** Config keys this plugin models explicitly; every other key passes through. */
59
77
  const STRUCTURED_KEYS = new Set([
60
78
  'serverName',
@@ -119,6 +137,10 @@ const MSGS = {
119
137
  renamedFrom: '(由 {name} 重命名)',
120
138
  yamlDegraded:
121
139
  '解析到的 js-yaml({source})不支持 !!js 自定义类型,已改用兼容解析;面板功能不受影响',
140
+ bindSaved: '项目绑定已保存:{name}',
141
+ bindCleared: '已解除项目绑定:{name},改为全局可用',
142
+ bindUnknownServer: '未找到服务器 {name}',
143
+ bindPathsAbsolute: '项目路径必须是绝对路径:{path}',
122
144
  },
123
145
  en: {
124
146
  loopbackOnly: 'Only local (loopback) requests are allowed',
@@ -153,6 +175,10 @@ const MSGS = {
153
175
  renamedFrom: ' (renamed from {name})',
154
176
  yamlDegraded:
155
177
  'The js-yaml in use ({source}) does not support the !!js custom type; a compatible parser is active and the panel stays fully usable',
178
+ bindSaved: 'Project binding saved: {name}',
179
+ bindCleared: 'Project binding removed: {name}; it is available everywhere again',
180
+ bindUnknownServer: 'Server not found: {name}',
181
+ bindPathsAbsolute: 'A project path must be absolute: {path}',
156
182
  },
157
183
  };
158
184
 
@@ -303,6 +329,401 @@ function unmaskMap(next, previous) {
303
329
  return restored;
304
330
  }
305
331
 
332
+ // ── project bindings ────────────────────────────────────────────────────────
333
+
334
+ /**
335
+ * Where the durable project-binding table lives.
336
+ *
337
+ * Binding state is deliberately NOT the profile patch layer. That layer
338
+ * composes the running tree, so writing a binding into it would remount every
339
+ * MCP connection on every binding edit; bindings are ordinary plugin data,
340
+ * stored beside the patch file, and they take effect in the running process the
341
+ * moment they are written.
342
+ *
343
+ * `DSH_MCP_MANAGER_BINDINGS` overrides the location (tests, unusual installs).
344
+ * @param ctx - host context.
345
+ * @returns an absolute path.
346
+ */
347
+ function resolveBindingsPath(ctx) {
348
+ const override = process.env.DSH_MCP_MANAGER_BINDINGS;
349
+ if (override !== undefined && override.trim() !== '') return override;
350
+ const { profileDir } = resolvePatchPath(ctx);
351
+ return join(profileDir, 'plugin-data', PLUGIN_ID, BINDINGS_FILE);
352
+ }
353
+
354
+ /**
355
+ * The comparison key for a directory: separators normalized, trailing
356
+ * separators dropped, and case-folded on Windows, whose filesystem is
357
+ * case-insensitive. A leading `~` expands to the home directory.
358
+ * @param value - a path.
359
+ * @returns the key, or `''` for an empty path.
360
+ */
361
+ function pathKey(value) {
362
+ let text = String(value ?? '').trim();
363
+ if (text === '') return '';
364
+ if (text === '~' || text.startsWith('~/') || text.startsWith('~\\')) {
365
+ text = join(homedir(), text.slice(1));
366
+ }
367
+ const trimmed = text.replace(/[\\/]+$/u, '').replace(/\\/gu, '/');
368
+ if (trimmed === '') return '/';
369
+ return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed;
370
+ }
371
+
372
+ /**
373
+ * Whether a session directory is the bound project itself or lives inside it.
374
+ * @param candidate - the session's effective directory.
375
+ * @param root - a bound project path.
376
+ * @returns true when the directory is covered by the binding.
377
+ */
378
+ function isWithin(candidate, root) {
379
+ const a = pathKey(candidate);
380
+ const b = pathKey(root);
381
+ if (a === '' || b === '') return false;
382
+ if (a === b) return true;
383
+ return a.startsWith(b.endsWith('/') ? b : `${b}/`);
384
+ }
385
+
386
+ /**
387
+ * Accept a submitted project path. A relative path is refused rather than
388
+ * quietly stored: it could never match a session directory, so the binding
389
+ * would look configured while doing nothing.
390
+ * @param value - the submitted path.
391
+ * @returns the trimmed path, or null when it is not absolute.
392
+ */
393
+ function normalizeBindingPath(value) {
394
+ const text = String(value ?? '').trim();
395
+ if (text === '') return null;
396
+ if (text === '~' || text.startsWith('~/') || text.startsWith('~\\')) return text;
397
+ return isAbsolute(text) ? text : null;
398
+ }
399
+
400
+ /**
401
+ * Normalize a parsed binding table. Both the canonical shape
402
+ * (`{ version, servers: { name: { paths: [...] } } }`) and a hand-written
403
+ * shorthand (`{ name: ["C:\\dir"] }`) are accepted, and anything unusable is
404
+ * dropped rather than throwing.
405
+ * @param parsed - the decoded JSON value.
406
+ * @returns `{ version: 1, servers }`.
407
+ */
408
+ function normalizeBindings(parsed) {
409
+ const servers = {};
410
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
411
+ return { version: 1, servers };
412
+ }
413
+ const source =
414
+ parsed.servers !== null && typeof parsed.servers === 'object' ? parsed.servers : parsed;
415
+ for (const [name, entry] of Object.entries(source)) {
416
+ if (!/^[A-Za-z0-9_-]{1,32}$/u.test(name)) continue;
417
+ const raw = Array.isArray(entry)
418
+ ? entry
419
+ : entry !== null && typeof entry === 'object' && Array.isArray(entry.paths)
420
+ ? entry.paths
421
+ : undefined;
422
+ if (raw === undefined) continue;
423
+ const paths = [];
424
+ for (const item of raw) {
425
+ const accepted = typeof item === 'string' ? normalizeBindingPath(item) : null;
426
+ if (accepted === null) continue;
427
+ if (paths.some((existing) => pathKey(existing) === pathKey(accepted))) continue;
428
+ paths.push(accepted);
429
+ }
430
+ if (paths.length > 0) servers[name] = { paths };
431
+ }
432
+ return { version: 1, servers };
433
+ }
434
+
435
+ /** Last binding snapshot; invalidated on write and refreshed when the file changes. */
436
+ let bindingsCache = null;
437
+
438
+ /**
439
+ * Read the binding table, tolerating a missing or damaged file.
440
+ *
441
+ * A damaged table reads as "no bindings" — the pre-feature behaviour — so a bad
442
+ * edit can never make a user's MCP servers unusable everywhere.
443
+ * @param ctx - host context.
444
+ * @returns `{ version: 1, servers }`.
445
+ */
446
+ function readBindings(ctx) {
447
+ const path = resolveBindingsPath(ctx);
448
+ const now = Date.now();
449
+ let stamp = -1;
450
+ try {
451
+ stamp = statSync(path).mtimeMs;
452
+ } catch {
453
+ stamp = -1;
454
+ }
455
+ if (
456
+ bindingsCache !== null &&
457
+ bindingsCache.path === path &&
458
+ bindingsCache.stamp === stamp &&
459
+ now - bindingsCache.at < BINDINGS_TTL_MS
460
+ ) {
461
+ return bindingsCache.value;
462
+ }
463
+ let value = { version: 1, servers: {} };
464
+ if (stamp !== -1) {
465
+ try {
466
+ value = normalizeBindings(JSON.parse(readFileSync(path, 'utf8')));
467
+ } catch {
468
+ value = { version: 1, servers: {} };
469
+ }
470
+ }
471
+ bindingsCache = { path, stamp, at: now, value };
472
+ return value;
473
+ }
474
+
475
+ /**
476
+ * Replace the binding table atomically, with sorted keys so the file diffs
477
+ * cleanly.
478
+ * @param ctx - host context.
479
+ * @param servers - the `servers` map to persist.
480
+ * @returns the absolute path written.
481
+ */
482
+ function writeBindings(ctx, servers) {
483
+ const path = resolveBindingsPath(ctx);
484
+ const sorted = {};
485
+ for (const name of Object.keys(servers).sort()) sorted[name] = servers[name];
486
+ mkdirSync(dirname(path), { recursive: true });
487
+ const temp = `${path}.tmp-${process.pid}-${Date.now()}`;
488
+ writeFileSync(temp, `${JSON.stringify({ version: 1, servers: sorted }, null, 2)}\n`);
489
+ renameSync(temp, path);
490
+ bindingsCache = null;
491
+ return path;
492
+ }
493
+
494
+ /**
495
+ * The active binding for one server.
496
+ * @param table - a table from {@link readBindings}.
497
+ * @param serverName - the server namespace.
498
+ * @returns the binding, or null when the server is global.
499
+ */
500
+ function bindingOf(table, serverName) {
501
+ const entry = table.servers[serverName];
502
+ if (entry === undefined || !Array.isArray(entry.paths) || entry.paths.length === 0) return null;
503
+ return entry;
504
+ }
505
+
506
+ /**
507
+ * The server namespace a bridge tool belongs to. A `serverName` may itself
508
+ * contain `_`, so the separating `__` is the LAST one — the bridge's own naming
509
+ * contract.
510
+ * @param name - a tool name.
511
+ * @returns the server name, or undefined when this is not an MCP tool.
512
+ */
513
+ function serverOfToolName(name) {
514
+ if (typeof name !== 'string' || !name.startsWith(MCP_TOOL_PREFIX)) return undefined;
515
+ const rest = name.slice(MCP_TOOL_PREFIX.length);
516
+ const index = rest.lastIndexOf('__');
517
+ if (index <= 0) return undefined;
518
+ return rest.slice(0, index);
519
+ }
520
+
521
+ /** Every registered tool name a server currently contributes. */
522
+ function toolNamesOfServer(ctx, serverName) {
523
+ const prefix = `${MCP_TOOL_PREFIX}${serverName}__`;
524
+ const names = [];
525
+ for (const schema of schemasOf(ctx)) {
526
+ const name = schema?.name;
527
+ if (typeof name === 'string' && name.startsWith(prefix)) names.push(name);
528
+ }
529
+ return names;
530
+ }
531
+
532
+ /**
533
+ * The directory a session runs in.
534
+ *
535
+ * `workingDirectory` is the live owner of the effective directory and is
536
+ * preferred; the session header's original `cwd` is the fallback, and the
537
+ * deployment default is the last resort. An undeterminable directory leaves the
538
+ * caller unenforced, so an unknown directory never locks a user out of their
539
+ * own servers.
540
+ * @param ctx - host context.
541
+ * @param agent - the agent on whose behalf a call runs.
542
+ * @returns an absolute directory, or undefined when none can be read.
543
+ */
544
+ function cwdOfAgent(ctx, agent) {
545
+ const session = agent !== null && typeof agent === 'object' ? agent.session : undefined;
546
+ let wd;
547
+ try {
548
+ wd = ctx.get('workingDirectory');
549
+ } catch {
550
+ wd = undefined;
551
+ }
552
+ if (wd !== undefined && session !== undefined && typeof wd.get === 'function') {
553
+ try {
554
+ const dir = wd.get(session);
555
+ if (typeof dir === 'string' && dir !== '') return dir;
556
+ } catch {
557
+ // Fall through to the session header.
558
+ }
559
+ }
560
+ const header = session !== undefined ? session.header : undefined;
561
+ if (header !== undefined && typeof header.cwd === 'string' && header.cwd !== '') return header.cwd;
562
+ if (wd !== undefined && typeof wd.defaultDirectory === 'string' && wd.defaultDirectory !== '') {
563
+ return wd.defaultDirectory;
564
+ }
565
+ return undefined;
566
+ }
567
+
568
+ /** The denial a guard returns: the model learns why, and where to change it. */
569
+ function bindingDenial(toolName, serverName, cwd, paths) {
570
+ return (
571
+ `MCP 项目绑定:工具 ${toolName} 在当前项目不可用(当前目录 ${cwd})。` +
572
+ `服务器 "${serverName}" 只绑定到:${paths.join('、')}。可在「设置 → MCP 管理 → 项目绑定」中修改。` +
573
+ ` / Project binding: "${serverName}" is bound to ${paths.join(', ')}, so ${toolName} is unavailable in ${cwd}.`
574
+ );
575
+ }
576
+
577
+ /** The agent-scoped restriction last applied to each live agent. */
578
+ const agentBindings = new WeakMap();
579
+
580
+ /**
581
+ * Bring one agent's tool visibility in line with the binding table.
582
+ *
583
+ * A restricted server's tools are hidden from that agent with an agent-scoped
584
+ * `tools.restrict()` — the only context in which that call is legal. The work is
585
+ * skipped when nothing changed, so calling it on every step is cheap. Nothing
586
+ * here may throw: a failure inside an `agent/pre-step` listener would fail the
587
+ * step.
588
+ * @param ctx - host context.
589
+ * @param agent - the agent to bring up to date.
590
+ */
591
+ function syncAgentBindings(ctx, agent) {
592
+ try {
593
+ if (agent === null || typeof agent !== 'object') return;
594
+ const agentCtx = agent.ctx;
595
+ if (agentCtx === undefined || agentCtx === null) return;
596
+ let scoped;
597
+ try {
598
+ scoped = agentCtx.tools;
599
+ } catch {
600
+ scoped = undefined;
601
+ }
602
+ if (scoped === undefined && typeof agentCtx.get === 'function') {
603
+ try {
604
+ scoped = agentCtx.get('tools');
605
+ } catch {
606
+ scoped = undefined;
607
+ }
608
+ }
609
+ if (scoped === undefined || typeof scoped.restrict !== 'function') return;
610
+
611
+ const cwd = cwdOfAgent(ctx, agent);
612
+ const known = cwd !== undefined && cwd !== '';
613
+ const table = readBindings(ctx);
614
+ const deny = [];
615
+ for (const serverName of Object.keys(table.servers)) {
616
+ const binding = bindingOf(table, serverName);
617
+ if (binding === null) continue;
618
+ // Fail open, exactly like the per-call guard: when this session's
619
+ // directory cannot be determined we hide nothing, rather than locking a
620
+ // user out of a project the plugin failed to recognize. Hiding the tools
621
+ // while the guard still allows the call would also be self-contradictory.
622
+ if (!known) continue;
623
+ if (binding.paths.some((root) => isWithin(cwd, root))) continue;
624
+ for (const name of toolNamesOfServer(ctx, serverName)) deny.push(name);
625
+ }
626
+ deny.sort();
627
+
628
+ const state = agentBindings.get(agent);
629
+ const signature = deny.join('\n');
630
+ if (state !== undefined && state.signature === signature) return;
631
+ if (state !== undefined) {
632
+ for (const dispose of state.disposers) {
633
+ try {
634
+ dispose();
635
+ } catch {
636
+ // A disposer that fails must not stop the new restriction.
637
+ }
638
+ }
639
+ }
640
+ const disposers = [];
641
+ if (deny.length > 0) {
642
+ try {
643
+ disposers.push(scoped.restrict({ deny }));
644
+ } catch {
645
+ // An empty filter, an unknown name, or a registration that vanished
646
+ // between the listing and the call: the per-call guard still enforces
647
+ // the binding, so losing the schema filter is not a hole.
648
+ }
649
+ }
650
+ agentBindings.set(agent, { signature, disposers });
651
+ } catch {
652
+ // Never let enforcement break a step.
653
+ }
654
+ }
655
+
656
+ /** Bring every live agent up to date, after a binding edit. */
657
+ function syncAllAgents(ctx) {
658
+ let agents;
659
+ try {
660
+ agents = ctx.get('agents');
661
+ } catch {
662
+ return;
663
+ }
664
+ if (agents === undefined || typeof agents.list !== 'function') return;
665
+ let list;
666
+ try {
667
+ list = agents.list();
668
+ } catch {
669
+ return;
670
+ }
671
+ if (!Array.isArray(list)) return;
672
+ for (const agent of list) syncAgentBindings(ctx, agent);
673
+ }
674
+
675
+ /**
676
+ * Install project-binding enforcement.
677
+ *
678
+ * Two independent layers, because they cover different things:
679
+ * - a global monotonic `tools.guard`, denying a bound server's tool call from a
680
+ * session outside its projects. This is the hard rule, and it also covers
681
+ * sessions that already existed, a directory changed mid-session, and the
682
+ * moment before a scope restriction is re-applied;
683
+ * - agent-scoped `tools.restrict`, applied at `agent/created` and re-checked at
684
+ * every `agent/pre-step`, which keeps the tools out of the model's schema list
685
+ * in the first place.
686
+ * @param ctx - host context.
687
+ */
688
+ function applyProjectBindings(ctx) {
689
+ let tools;
690
+ try {
691
+ tools = ctx.get('tools');
692
+ } catch {
693
+ tools = undefined;
694
+ }
695
+ if (tools !== undefined && typeof tools.guard === 'function') {
696
+ ctx.effect(
697
+ () =>
698
+ tools.guard((exec) => {
699
+ const serverName = serverOfToolName(exec?.name);
700
+ if (serverName === undefined) return undefined;
701
+ const binding = bindingOf(readBindings(ctx), serverName);
702
+ if (binding === null) return undefined;
703
+ const cwd = cwdOfAgent(ctx, exec.agent);
704
+ if (cwd === undefined || cwd === '') return undefined;
705
+ if (binding.paths.some((root) => isWithin(cwd, root))) return undefined;
706
+ return bindingDenial(exec.name, serverName, cwd, binding.paths);
707
+ }),
708
+ 'dsh-mcp-manager-plus: project binding guard',
709
+ );
710
+ }
711
+ if (typeof ctx.on !== 'function') return;
712
+ ctx.effect(() => {
713
+ const offCreated = ctx.on('agent/created', (payload) => {
714
+ syncAgentBindings(ctx, payload?.agent);
715
+ });
716
+ const offStep = ctx.on('agent/pre-step', (payload, next) => {
717
+ syncAgentBindings(ctx, payload?.agent);
718
+ return typeof next === 'function' ? next() : undefined;
719
+ });
720
+ return () => {
721
+ if (typeof offCreated === 'function') offCreated();
722
+ if (typeof offStep === 'function') offStep();
723
+ };
724
+ }, 'dsh-mcp-manager-plus: project binding scope');
725
+ }
726
+
306
727
  // ── live-state reads ────────────────────────────────────────────────────────
307
728
 
308
729
  /** Cordis fiber states, mirrored as the readable phase the browser shows. */
@@ -340,6 +761,293 @@ function phaseOf(entry, disabled) {
340
761
  return FIBER_PHASE[fiber.state] ?? null;
341
762
  }
342
763
 
764
+ /** Longest diagnostic string copied out of a live bridge status. */
765
+ const STATUS_TEXT_LIMIT = 600;
766
+ /**
767
+ * Diagnostic override for the module that reports connection state. Set it to a
768
+ * file path or `file:` URL to read a nonstandard bridge copy; tests use it to
769
+ * inject a fake without requiring the real package.
770
+ */
771
+ const STATUS_OVERRIDE_ENV = 'DSH_MCP_MANAGER_STATUS_MODULE';
772
+
773
+ /**
774
+ * Resolved status readers, one promise per host context. Resolution imports
775
+ * code (slow, and it may legitimately fail), so a listing burst must not retry
776
+ * it; the readers themselves are stateless probes over live fibers.
777
+ */
778
+ const STATUS_READERS = new WeakMap();
779
+
780
+ /**
781
+ * The `connectionStatusOf` export of a bridge module, or `null` when this copy
782
+ * predates the status API. Older bridges export no such function at all — that
783
+ * is the case the tool-count fallback exists for.
784
+ * @param mod - a module namespace.
785
+ * @returns the function, or null.
786
+ */
787
+ function connectionStatusFunction(mod) {
788
+ if (mod === null || (typeof mod !== 'object' && typeof mod !== 'function')) return null;
789
+ if (typeof mod.connectionStatusOf === 'function') return mod.connectionStatusOf;
790
+ const fallback = mod.default;
791
+ if (
792
+ fallback !== null &&
793
+ typeof fallback === 'object' &&
794
+ typeof fallback.connectionStatusOf === 'function'
795
+ ) {
796
+ return fallback.connectionStatusOf;
797
+ }
798
+ return null;
799
+ }
800
+
801
+ /** Bound diagnostic text: error strings can carry a whole child-process dump. */
802
+ function statusText(value) {
803
+ const text = typeof value === 'string' ? value : value instanceof Error ? value.message : '';
804
+ if (text === '') return '';
805
+ return text.length > STATUS_TEXT_LIMIT ? `${text.slice(0, STATUS_TEXT_LIMIT)}…` : text;
806
+ }
807
+
808
+ /**
809
+ * Copy a bridge status into plain data. Only known fields are copied, so a
810
+ * future bridge state cannot smuggle an arbitrary object graph into the HTTP
811
+ * response, and every field is validated before the browser sees it.
812
+ * @param status - one `McpConnectionStatus` value.
813
+ * @returns the snapshot sent as `live.connection`.
814
+ */
815
+ function snapshotConnection(status) {
816
+ const snapshot = { state: status.state };
817
+ if (typeof status.toolCount === 'number' && Number.isFinite(status.toolCount)) {
818
+ snapshot.toolCount = status.toolCount;
819
+ }
820
+ if (typeof status.connectedAt === 'number' && Number.isFinite(status.connectedAt)) {
821
+ snapshot.connectedAt = status.connectedAt;
822
+ }
823
+ if (typeof status.attempt === 'number' && Number.isFinite(status.attempt)) {
824
+ snapshot.attempt = status.attempt;
825
+ }
826
+ if (typeof status.maxAttempts === 'number' && Number.isFinite(status.maxAttempts)) {
827
+ snapshot.maxAttempts = status.maxAttempts;
828
+ }
829
+ if (typeof status.nextRetryAtMs === 'number' && Number.isFinite(status.nextRetryAtMs)) {
830
+ snapshot.nextRetryAtMs = status.nextRetryAtMs;
831
+ }
832
+ if (typeof status.reason === 'string' && status.reason !== '') {
833
+ snapshot.reason = status.reason;
834
+ }
835
+ const lastError = statusText(status.lastError);
836
+ if (lastError !== '') snapshot.lastError = lastError;
837
+ if (status.result !== null && typeof status.result === 'object') {
838
+ if (typeof status.result.closeConfirmed === 'boolean') {
839
+ snapshot.closeConfirmed = status.result.closeConfirmed;
840
+ }
841
+ const cleanupError = statusText(status.result.cleanupError);
842
+ if (cleanupError !== '') snapshot.cleanupError = cleanupError;
843
+ }
844
+ return snapshot;
845
+ }
846
+
847
+ /**
848
+ * Ask every resolved bridge copy for this entry's connection status.
849
+ *
850
+ * The bridge keeps status cells in a `WeakMap` keyed by the live fiber, so a
851
+ * handle exists only in the module instance that actually applied the entry.
852
+ * Probing all copies is what makes the read independent of which copy the
853
+ * loader picked. A fake fiber (tests) has no `ctx.fiber` and makes the probe
854
+ * throw — that is caught and treated as "this copy does not own the entry".
855
+ * @param entry - the live loader entry.
856
+ * @param readers - resolved `connectionStatusOf` functions.
857
+ * @returns a snapshot, or null when no copy owns the entry.
858
+ */
859
+ function connectionOf(entry, readers) {
860
+ if (!Array.isArray(readers) || readers.length === 0) return null;
861
+ const fiber = entry?.fiber;
862
+ if (fiber === undefined) return null;
863
+ for (const reader of readers) {
864
+ let handle;
865
+ try {
866
+ handle = reader.connectionStatusOf(fiber);
867
+ } catch {
868
+ continue;
869
+ }
870
+ if (handle === null || typeof handle !== 'object') continue;
871
+ if (typeof handle.current !== 'function') continue;
872
+ let status;
873
+ try {
874
+ status = handle.current();
875
+ } catch {
876
+ continue;
877
+ }
878
+ if (status === null || typeof status !== 'object') continue;
879
+ if (typeof status.state !== 'string' || status.state === '') continue;
880
+ return snapshotConnection(status);
881
+ }
882
+ return null;
883
+ }
884
+
885
+ /**
886
+ * The connection projection for one row.
887
+ *
888
+ * A loader phase of `active` only proves the bridge plugin mounted; the MCP
889
+ * child process starts afterwards, so a crashed handshake leaves the fiber
890
+ * active forever. The bridge's own status is the authoritative answer when it
891
+ * can be read. When it cannot, a mounted, enabled server exposing zero tools is
892
+ * reported as `unknown` rather than `connected` — the two facts contradict each
893
+ * other, and the honest reading is that the handshake was not observed.
894
+ * @param entry - the live loader entry, when mounted.
895
+ * @param phase - the projected loader phase.
896
+ * @param disabled - whether the row is disabled by the patch layer.
897
+ * @param toolCount - registered tool count for this server.
898
+ * @param readers - resolved bridge status readers.
899
+ * @returns `live.connection`, or null when there is nothing to say.
900
+ */
901
+ function liveConnectionOf(entry, phase, disabled, toolCount, readers) {
902
+ if (disabled || phase !== 'active') return null;
903
+ const observed = connectionOf(entry, readers);
904
+ if (observed !== null) return observed;
905
+ return toolCount === 0 ? { state: 'unknown' } : null;
906
+ }
907
+
908
+ /** Normalize a diagnostic override into an importable URL. */
909
+ function statusOverrideUrl(specifier) {
910
+ // An absolute path has to win over the scheme test: on Windows `C:\bridge.mjs`
911
+ // starts with a colon-terminated run of letters, which reads as the `c:`
912
+ // scheme, and importing it as a URL fails rather than loading the file.
913
+ if (isAbsolute(specifier)) return pathToFileURL(specifier).href;
914
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/u.test(specifier)) return specifier;
915
+ return pathToFileURL(resolvePath(process.cwd(), specifier)).href;
916
+ }
917
+
918
+ /**
919
+ * The anchors a bridge module is resolved through, in order.
920
+ *
921
+ * The profile anchor is the one that matches the loader's own view; the
922
+ * bundled Electron tree is the copy that carries the status API when the
923
+ * profile's hoisted copy is older; the rest cover a CLI install and a linked
924
+ * development checkout.
925
+ * @param profileDir - the profile directory, when known.
926
+ * @returns candidate directories.
927
+ */
928
+ function statusResolutionAnchors(profileDir) {
929
+ const anchors = [];
930
+ const add = (value) => {
931
+ if (typeof value === 'string' && value !== '' && !anchors.includes(value)) {
932
+ anchors.push(value);
933
+ }
934
+ };
935
+ add(profileDir);
936
+ add(process.cwd());
937
+ const pluginLib = dirname(fileURLToPath(import.meta.url));
938
+ add(dirname(pluginLib));
939
+ add(pluginLib);
940
+ const home = dshHome();
941
+ if (home !== '') add(join(home, 'profiles'));
942
+ const resources = typeof process.resourcesPath === 'string' ? process.resourcesPath : '';
943
+ if (resources !== '') {
944
+ add(join(resources, 'app.asar', 'dsh'));
945
+ add(join(resources, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-mcp-client'));
946
+ }
947
+ const entrypoint = process.argv[1];
948
+ if (typeof entrypoint === 'string' && entrypoint !== '') add(dirname(entrypoint));
949
+ return anchors;
950
+ }
951
+
952
+ /**
953
+ * Resolve every importable copy of the MCP bridge that exposes
954
+ * `connectionStatusOf`.
955
+ *
956
+ * Four routes are tried because the running tree differs by deployment: a bare
957
+ * import (a Vite-backed loader may rewrite it), the loader's own internal
958
+ * importer (the exact module instance it applied), the profile/bundled anchors,
959
+ * and finally nothing — in which case the tool-count fallback still keeps the
960
+ * badge honest.
961
+ * @param ctx - host context.
962
+ * @param profileDir - the profile directory, when known.
963
+ * @returns `[{ source, connectionStatusOf }]`.
964
+ */
965
+ async function loadStatusReaders(ctx, profileDir) {
966
+ const readers = [];
967
+ /** @param mod - candidate module. @param source - where it came from. */
968
+ const add = (mod, source) => {
969
+ const fn = connectionStatusFunction(mod);
970
+ if (fn === null) return false;
971
+ if (readers.some((reader) => reader.connectionStatusOf === fn)) return true;
972
+ readers.push({ source, connectionStatusOf: fn });
973
+ return true;
974
+ };
975
+
976
+ // A diagnostic/test override wins outright when it works: the caller asked
977
+ // for exactly one module, and mixing it with guessed copies would make the
978
+ // answer non-deterministic.
979
+ const override = process.env[STATUS_OVERRIDE_ENV];
980
+ if (typeof override === 'string' && override.trim() !== '') {
981
+ try {
982
+ if (add(await import(statusOverrideUrl(override.trim())), 'override')) return readers;
983
+ } catch {
984
+ // Fall through to the normal resolution routes.
985
+ }
986
+ }
987
+
988
+ try {
989
+ add(await import(MCP_CLIENT_PACKAGE), 'bare');
990
+ } catch {
991
+ // Older Node resolution cannot see the profile's copy.
992
+ }
993
+
994
+ const loader = ctx.get('loader');
995
+ const internal = loader?.internal;
996
+ if (internal !== undefined && typeof internal.import === 'function') {
997
+ const bases = new Set();
998
+ if (typeof ctx.baseUrl === 'string' && ctx.baseUrl !== '') bases.add(ctx.baseUrl);
999
+ if (loader !== undefined && typeof loader.entries === 'function') {
1000
+ try {
1001
+ for (const entry of loader.entries()) {
1002
+ const baseUrl = entry?.fiber?.ctx?.baseUrl;
1003
+ if (typeof baseUrl === 'string' && baseUrl !== '') bases.add(baseUrl);
1004
+ }
1005
+ } catch {
1006
+ // A loader that cannot enumerate entries still answers for itself.
1007
+ }
1008
+ }
1009
+ for (const baseUrl of bases) {
1010
+ try {
1011
+ add(await internal.import(MCP_CLIENT_PACKAGE, baseUrl, {}), `loader:${baseUrl}`);
1012
+ } catch {
1013
+ // The internal importer only accepts bases it can resolve from.
1014
+ }
1015
+ }
1016
+ }
1017
+
1018
+ for (const anchor of statusResolutionAnchors(profileDir)) {
1019
+ let resolved;
1020
+ try {
1021
+ resolved = createRequire(join(anchor, 'package.json')).resolve(MCP_CLIENT_PACKAGE);
1022
+ } catch {
1023
+ continue;
1024
+ }
1025
+ try {
1026
+ add(await import(pathToFileURL(resolved).href), resolved);
1027
+ } catch {
1028
+ // Resolvable but not importable (a native-only or broken copy).
1029
+ }
1030
+ }
1031
+
1032
+ return readers;
1033
+ }
1034
+
1035
+ /**
1036
+ * Resolve (and cache) the status readers for one host context. Resolution is
1037
+ * asynchronous, so callers await this before projecting the inventory; later
1038
+ * projections reuse the same readers.
1039
+ * @param ctx - host context.
1040
+ * @param profileDir - the profile directory, when known.
1041
+ * @returns the reader list (possibly empty).
1042
+ */
1043
+ function prepareStatusReaders(ctx, profileDir) {
1044
+ const cached = STATUS_READERS.get(ctx);
1045
+ if (cached !== undefined) return cached;
1046
+ const pending = loadStatusReaders(ctx, profileDir).catch(() => []);
1047
+ STATUS_READERS.set(ctx, pending);
1048
+ return pending;
1049
+ }
1050
+
343
1051
  /** Every model-facing tool schema, defensively read. */
344
1052
  function schemasOf(ctx) {
345
1053
  const tools = ctx.get('tools');
@@ -412,12 +1120,19 @@ function toolsOfBuiltin(ctx, key) {
412
1120
  * @param ctx - host context.
413
1121
  * @param document - the parsed patch document.
414
1122
  * @param lang - response language for issue strings and display labels.
1123
+ * @param statusReaders - resolved bridge status readers, when available.
415
1124
  * @returns `{ servers, issues }`.
416
1125
  */
417
- function buildInventory(ctx, document, lang = 'zh') {
1126
+ function buildInventory(ctx, document, lang = 'zh', statusReaders = null) {
418
1127
  const issues = [...document.issues];
419
1128
  const servers = [];
420
1129
  const claimed = new Set();
1130
+ const table = readBindings(ctx);
1131
+ /** The binding projection the page renders for one server. */
1132
+ const bindingsOf = (name) => {
1133
+ const binding = bindingOf(table, name);
1134
+ return { paths: binding === null ? [] : [...binding.paths], restricted: binding !== null };
1135
+ };
421
1136
 
422
1137
  for (const row of document.rows) {
423
1138
  const config = row.config;
@@ -430,6 +1145,15 @@ function buildInventory(ctx, document, lang = 'zh') {
430
1145
  const disabled = document.overrides.disabled.get(row.id) === true;
431
1146
  const entry = findEntry(ctx, serverName);
432
1147
  const tools = disabled ? [] : toolsOfServer(ctx, serverName);
1148
+ const phase = phaseOf(entry, disabled);
1149
+ const live = {
1150
+ mounted: entry !== undefined,
1151
+ phase,
1152
+ toolCount: tools.length,
1153
+ tools,
1154
+ };
1155
+ const connection = liveConnectionOf(entry, phase, disabled, tools.length, statusReaders);
1156
+ if (connection !== null) live.connection = connection;
433
1157
  servers.push({
434
1158
  id: row.id,
435
1159
  serverName,
@@ -446,12 +1170,8 @@ function buildInventory(ctx, document, lang = 'zh') {
446
1170
  cwd: typeof config.cwd === 'string' ? config.cwd : '',
447
1171
  url: typeof config.url === 'string' ? config.url : '',
448
1172
  headers: maskMap(config.headers),
449
- live: {
450
- mounted: entry !== undefined,
451
- phase: phaseOf(entry, disabled),
452
- toolCount: tools.length,
453
- tools,
454
- },
1173
+ binding: bindingsOf(serverName),
1174
+ live,
455
1175
  });
456
1176
  }
457
1177
 
@@ -472,6 +1192,15 @@ function buildInventory(ctx, document, lang = 'zh') {
472
1192
  const id = typeof options.id === 'string' ? options.id : '';
473
1193
  const off = entry.disabled === true || (id !== '' && document.overrides.disabled.get(id) === true);
474
1194
  const tools = off ? [] : toolsOfServer(ctx, serverName);
1195
+ const phase = phaseOf(entry, off);
1196
+ const live = {
1197
+ mounted: entry.fiber !== undefined,
1198
+ phase,
1199
+ toolCount: tools.length,
1200
+ tools,
1201
+ };
1202
+ const connection = liveConnectionOf(entry, phase, off, tools.length, statusReaders);
1203
+ if (connection !== null) live.connection = connection;
475
1204
  servers.push({
476
1205
  id,
477
1206
  serverName,
@@ -488,12 +1217,8 @@ function buildInventory(ctx, document, lang = 'zh') {
488
1217
  cwd: typeof config.cwd === 'string' ? config.cwd : '',
489
1218
  url: typeof config.url === 'string' ? config.url : '',
490
1219
  headers: maskMap(config.headers),
491
- live: {
492
- mounted: entry.fiber !== undefined,
493
- phase: phaseOf(entry, off),
494
- toolCount: tools.length,
495
- tools,
496
- },
1220
+ binding: bindingsOf(serverName),
1221
+ live,
497
1222
  });
498
1223
  }
499
1224
  }
@@ -519,6 +1244,7 @@ function buildInventory(ctx, document, lang = 'zh') {
519
1244
  cwd: '',
520
1245
  url: '',
521
1246
  headers: {},
1247
+ binding: { paths: [], restricted: false },
522
1248
  live: { mounted: true, phase: 'active', toolCount: tools.length, tools },
523
1249
  });
524
1250
  }
@@ -803,10 +1529,11 @@ async function remountEntry(entry, serverName, lang) {
803
1529
  async function restartServer(ctx, input, lang = 'zh') {
804
1530
  const id = typeof input.id === 'string' ? input.id : '';
805
1531
  if (id === '') throw new Error(tr(lang, 'rowMissingId'));
806
- const { patchPath } = resolvePatchPath(ctx);
1532
+ const { patchPath, profileDir } = resolvePatchPath(ctx);
807
1533
  const { yaml, schema } = await loadYaml(ctx);
808
1534
  const document = readDocument(readPatchText(patchPath), yaml, schema);
809
- const inventory = buildInventory(ctx, document, lang);
1535
+ const statusReaders = await prepareStatusReaders(ctx, profileDir);
1536
+ const inventory = buildInventory(ctx, document, lang, statusReaders);
810
1537
  const server = inventory.servers.find((entry) => entry.id === id);
811
1538
  if (server === undefined) throw new Error(tr(lang, 'restartTargetMissing', { id }));
812
1539
  if (!server.enabled) throw new Error(tr(lang, 'restartDisabled', { name: server.serverName }));
@@ -816,6 +1543,66 @@ async function restartServer(ctx, input, lang = 'zh') {
816
1543
  return tr(lang, 'restarted', { name: server.serverName });
817
1544
  }
818
1545
 
1546
+ /**
1547
+ * Bind one server to a set of project directories, or clear its binding.
1548
+ *
1549
+ * An empty path list clears the binding and returns the server to "available in
1550
+ * every project". The server must already exist in the inventory: binding a
1551
+ * name nothing serves would look configured and never do anything.
1552
+ *
1553
+ * The write lands in the binding table, not the patch layer, so it takes effect
1554
+ * in the running process immediately — no loader generation is involved. Live
1555
+ * agents are re-synced here as well, so an open session sees the change on its
1556
+ * next step.
1557
+ * @param ctx - host context.
1558
+ * @param input - `{ serverName, paths }`.
1559
+ * @param lang - response language for error messages.
1560
+ * @returns `{ action, serverName, paths, message }`.
1561
+ */
1562
+ async function bindServer(ctx, input, lang = 'zh') {
1563
+ const serverName = typeof input.serverName === 'string' ? input.serverName.trim() : '';
1564
+ const invalid = validateServerName(serverName, lang);
1565
+ if (invalid !== null) throw new Error(invalid);
1566
+
1567
+ const { patchPath, profileDir } = resolvePatchPath(ctx);
1568
+ const { yaml, schema } = await loadYaml(ctx);
1569
+ const document = readDocument(readPatchText(patchPath), yaml, schema);
1570
+ const statusReaders = await prepareStatusReaders(ctx, profileDir);
1571
+ const known = buildInventory(ctx, document, lang, statusReaders).servers.some(
1572
+ (server) => server.serverName === serverName,
1573
+ );
1574
+ if (!known) throw new Error(tr(lang, 'bindUnknownServer', { name: serverName }));
1575
+
1576
+ const submitted = Array.isArray(input.paths) ? input.paths : [];
1577
+ const paths = [];
1578
+ for (const item of submitted) {
1579
+ if (typeof item !== 'string' || item.trim() === '') continue;
1580
+ const accepted = normalizeBindingPath(item);
1581
+ if (accepted === null) {
1582
+ throw new Error(tr(lang, 'bindPathsAbsolute', { path: item.trim() }));
1583
+ }
1584
+ if (paths.some((existing) => pathKey(existing) === pathKey(accepted))) continue;
1585
+ paths.push(accepted);
1586
+ }
1587
+
1588
+ const table = readBindings(ctx);
1589
+ const servers = { ...table.servers };
1590
+ if (paths.length === 0) delete servers[serverName];
1591
+ else servers[serverName] = { paths };
1592
+ writeBindings(ctx, servers);
1593
+ syncAllAgents(ctx);
1594
+
1595
+ return {
1596
+ action: paths.length === 0 ? 'cleared' : 'bound',
1597
+ serverName,
1598
+ paths,
1599
+ message:
1600
+ paths.length === 0
1601
+ ? tr(lang, 'bindCleared', { name: serverName })
1602
+ : tr(lang, 'bindSaved', { name: serverName }),
1603
+ };
1604
+ }
1605
+
819
1606
  /**
820
1607
  * Import servers from a pasted configuration document. The document may come
821
1608
  * from any of the tools this module's parser understands — Claude Code, Cursor,
@@ -975,7 +1762,11 @@ function sendJson(res, status, value) {
975
1762
  }
976
1763
 
977
1764
  export const name = 'dsh-mcp-manager-plus';
978
- export const inject = ['webServer'];
1765
+ // `tools` is a hard dependency, not a `ctx.get` probe: the project-binding
1766
+ // guard and the agent-scoped restrictions are the whole of this plugin's
1767
+ // enforcement, and a declared service parks the plugin until its provider
1768
+ // exists rather than silently applying with no enforcer.
1769
+ export const inject = ['webServer', 'tools'];
979
1770
 
980
1771
  /**
981
1772
  * Register the management API on the harness web server.
@@ -993,7 +1784,8 @@ export function apply(ctx) {
993
1784
  }
994
1785
  const { yaml, schema, degraded, source } = await loadYaml(ctx);
995
1786
  const document = readDocument(readPatchText(patchPath), yaml, schema);
996
- const inventory = buildInventory(ctx, document, lang);
1787
+ const statusReaders = await prepareStatusReaders(ctx, profileDir);
1788
+ const inventory = buildInventory(ctx, document, lang, statusReaders);
997
1789
  // Say so rather than silently parsing with a weaker engine: the user's
998
1790
  // patch file is still fully managed, but a report that mentions it saves a
999
1791
  // round trip.
@@ -1010,6 +1802,7 @@ export function apply(ctx) {
1010
1802
  }
1011
1803
  const value = {
1012
1804
  patchPath,
1805
+ bindingsPath: resolveBindingsPath(ctx),
1013
1806
  profileDir,
1014
1807
  writable,
1015
1808
  servers: inventory.servers,
@@ -1062,6 +1855,12 @@ export function apply(ctx) {
1062
1855
  sendJson(res, 200, { ok: true, message, state: await listServers(lang) });
1063
1856
  return;
1064
1857
  }
1858
+ if (route === '/bind' && req.method === 'POST') {
1859
+ const result = await bindServer(ctx, await readJsonBody(req, lang), lang);
1860
+ cache = null;
1861
+ sendJson(res, 200, { ok: true, ...result, state: await listServers(lang) });
1862
+ return;
1863
+ }
1065
1864
  if (route === '/import' && req.method === 'POST') {
1066
1865
  const result = await importServers(ctx, await readJsonBody(req, lang), lang);
1067
1866
  cache = null;
@@ -1083,6 +1882,8 @@ export function apply(ctx) {
1083
1882
  }),
1084
1883
  'dsh-mcp-manager-plus: management API',
1085
1884
  );
1885
+
1886
+ applyProjectBindings(ctx);
1086
1887
  }
1087
1888
 
1088
1889
  export default { name, inject, apply };