dsh-hiss-plugins 1.3.1 → 1.5.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.
@@ -1,15 +1,123 @@
1
1
  import * as McpClient from "@deepseek-ai/dsh-mcp-client";
2
- import { findConfigPath, loadServers } from "./config.js";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { dispatch } from "./actions.js";
5
+ import { entryFromInput, findConfigPath, loadServers, managerEntry, readConfig, validateEntry, writeConfig } from "./config.js";
6
+ import { normalizeState, readState, statePath, withServer, withTool, writeState } from "./state.js";
3
7
  import { countTools, renderStatus } from "./status.js";
8
+ import { buildView, denyFor } from "./view.js";
4
9
 
5
10
  export const name = "project-mcp";
6
11
  export const inject = ["agents"];
7
12
 
13
+ /** The dialog route: same-origin POST from the browser half, one JSON answer. */
14
+ const DIALOG_PATH = "/hiss-mcp/action";
15
+ /** A dialog request larger than this is not a switch or a server entry. */
16
+ const BODY_LIMIT = 64 * 1024;
17
+
18
+ /**
19
+ * Per-agent bookkeeping: the fibers this row mounted and the restriction in force.
20
+ * A restriction is per agent scope, so toggling one tool means re-applying the
21
+ * whole deny set for that agent, never a global switch.
22
+ *
23
+ * The record lives on the agent object under a global symbol: mounts survive a
24
+ * row reload (they belong to the agent scope, not this fiber), so a module-level
25
+ * Map would forget their unmount handles on every reload and remount duplicates.
26
+ */
27
+ const RECORDS = Symbol.for("dsh-hiss-plugins.project-mcp.records");
28
+
8
29
  /** Readable text for anything a rejected promise or a schema can throw. */
9
30
  function message(error) {
10
31
  return error instanceof Error ? error.message : String(error);
11
32
  }
12
33
 
34
+ /** One agent's mounted servers, remembered deny set, and live restriction disposer. */
35
+ function recordFor(agent) {
36
+ if (agent[RECORDS] === undefined) agent[RECORDS] = { servers: new Map(), deny: new Set(), lift: undefined };
37
+ return agent[RECORDS];
38
+ }
39
+
40
+ /** The session directory an agent reads its project from. */
41
+ function cwdOf(agent) {
42
+ const cwd = agent?.session?.header?.cwd;
43
+ return typeof cwd === "string" && cwd !== "" ? cwd : undefined;
44
+ }
45
+
46
+ /** A host service when this profile has one, without requiring it. */
47
+ function serviceOf(ctx, key) {
48
+ return typeof ctx.get === "function" ? ctx.get(key) : ctx[key];
49
+ }
50
+
51
+ /** The switches one workspace remembers. */
52
+ function switchesOf(state, cwd) {
53
+ const entry = normalizeState(state).workspaces[resolve(cwd)];
54
+ return { disabledTools: entry?.disabledTools ?? [], disabledServers: entry?.disabledServers ?? [] };
55
+ }
56
+
57
+ /** The public tool names a scope sees, or the global view when no scope is given. */
58
+ function toolNamesOf(ctx, scope) {
59
+ return ctx.tools.schemas(scope).map((schema) => schema.name);
60
+ }
61
+
62
+ /**
63
+ * Hide the tools this workspace switched off from one agent.
64
+ *
65
+ * `tools.restrict` only reaches global registrations, refuses unknown names, and
66
+ * applies to one agent scope, so the deny set is filtered against what actually
67
+ * exists and re-applied after the tool list changes. The deny set is recorded
68
+ * before the call: `restrict` emits `tools/change`, and the re-entrant pass must
69
+ * see an unchanged set and stop.
70
+ *
71
+ * @param {object} ctx - host context, for logging and the global tool view.
72
+ * @param {object} agent - the live agent whose scope hides the tools.
73
+ * @param {object} state - the switch state to apply.
74
+ * @returns {void}
75
+ */
76
+ function applyRestriction(ctx, agent, state) {
77
+ const cwd = cwdOf(agent);
78
+ if (cwd === undefined || agent?.ctx?.tools === undefined) return;
79
+ const deny = denyFor(switchesOf(state, cwd).disabledTools, toolNamesOf(ctx, undefined));
80
+ const record = recordFor(agent);
81
+ const same = deny.length === record.deny.size && deny.every((tool) => record.deny.has(tool));
82
+ if (same) return;
83
+ let lift = () => {};
84
+ if (deny.length > 0) {
85
+ try {
86
+ // The new restriction is applied before the old one is lifted, so a
87
+ // refusal leaves the previous deny set in force instead of none.
88
+ lift = agent.ctx.tools.restrict({ deny });
89
+ } catch (error) {
90
+ ctx.logger.warn(`project-mcp: could not hide ${deny.join(", ")} for ${String(agent.id)}: ${message(error)}`);
91
+ return;
92
+ }
93
+ }
94
+ record.lift?.();
95
+ record.lift = deny.length === 0 ? undefined : lift;
96
+ record.deny = new Set(deny);
97
+ }
98
+
99
+ /** Mount one declared server into an agent scope and remember how to unmount it. */
100
+ async function mountServer(ctx, agent, spec) {
101
+ let config;
102
+ try {
103
+ // The bridge's own schema is the gate: it decides what a server may
104
+ // ask the host process to do, and it rejects a name that would make
105
+ // an unusable tool namespace.
106
+ config = McpClient.Config(spec);
107
+ } catch (error) {
108
+ ctx.logger.warn(`project-mcp: "${spec.serverName}" is not a usable MCP server: ${message(error)}`);
109
+ return false;
110
+ }
111
+ try {
112
+ const fiber = await agent.ctx.plugin(McpClient, config);
113
+ recordFor(agent).servers.set(spec.serverName, fiber);
114
+ return true;
115
+ } catch (error) {
116
+ ctx.logger.warn(`project-mcp: "${spec.serverName}" failed to start: ${message(error)}`);
117
+ return false;
118
+ }
119
+ }
120
+
13
121
  /**
14
122
  * Mount every server declared by the session project's `.mcp.json` into one
15
123
  * agent's own scope. `agent.ctx` is the agent's scoped context, so the mount
@@ -23,11 +131,12 @@ function message(error) {
23
131
  *
24
132
  * @param {import("@deepseek-ai/cordis").Context} ctx - host context, for logging.
25
133
  * @param {{ session?: { header?: { cwd?: string } }, ctx?: unknown }} agent - the live agent.
134
+ * @param {object} [state] - the switch state; a switched-off server is not mounted.
26
135
  * @returns {Promise<number>} how many servers were mounted.
27
136
  */
28
- export async function mountProjectMcp(ctx, agent) {
29
- const cwd = agent?.session?.header?.cwd;
30
- if (typeof cwd !== "string" || cwd === "") return 0;
137
+ export async function mountProjectMcp(ctx, agent, state) {
138
+ const cwd = cwdOf(agent);
139
+ if (cwd === undefined) return 0;
31
140
  const configPath = await findConfigPath(cwd);
32
141
  if (configPath === undefined) return 0;
33
142
 
@@ -42,24 +151,14 @@ export async function mountProjectMcp(ctx, agent) {
42
151
  ctx.logger.warn(`project-mcp: ${configPath}: "${serverName}" was skipped: ${reason}`);
43
152
  }
44
153
 
154
+ const disabled = state === undefined ? [] : switchesOf(state, cwd).disabledServers;
45
155
  let mounted = 0;
46
156
  for (const { serverName, spec } of loaded.servers) {
47
- let config;
48
- try {
49
- // The bridge's own schema is the gate: it decides what a server may
50
- // ask the host process to do, and it rejects a name that would make
51
- // an unusable tool namespace.
52
- config = McpClient.Config(spec);
53
- } catch (error) {
54
- ctx.logger.warn(`project-mcp: ${configPath}: "${serverName}" is not a usable MCP server: ${message(error)}`);
55
- continue;
56
- }
57
- try {
58
- await agent.ctx.plugin(McpClient, config);
59
- mounted += 1;
60
- } catch (error) {
61
- ctx.logger.warn(`project-mcp: ${configPath}: "${serverName}" failed to start: ${message(error)}`);
62
- }
157
+ if (disabled.includes(serverName)) continue;
158
+ // A reload reaches agents that already carry these mounts; mounting again
159
+ // would collide on the tool names inside the same agent scope.
160
+ if (recordFor(agent).servers.has(serverName)) continue;
161
+ if (await mountServer(ctx, agent, spec)) mounted += 1;
63
162
  }
64
163
  return mounted;
65
164
  }
@@ -102,7 +201,7 @@ async function runMcp(ctx, invocation) {
102
201
  if (typeof cwd !== "string" || cwd === "") {
103
202
  return { kind: "error", text: "No session working directory; no project MCP servers are mounted." };
104
203
  }
105
- const toolNames = ctx.tools.schemas(invocation.agent).map((schema) => schema.name);
204
+ const toolNames = toolNamesOf(ctx, invocation.agent);
106
205
  const configPath = await findConfigPath(cwd);
107
206
  if (configPath === undefined) {
108
207
  return { kind: "success", text: renderStatus({ cwd, otherTools: countTools(toolNames, []).other }) };
@@ -138,6 +237,287 @@ async function runMcp(ctx, invocation) {
138
237
  }),
139
238
  };
140
239
  }
240
+ /**
241
+ * The servers configured outside this workspace, so the dialog can list one that
242
+ * currently exposes no tools and offer its master switch. The manager is optional:
243
+ * a profile without it falls back to whatever the tool names reveal.
244
+ *
245
+ * A name still declared by the workspace is not filtered out: a server registered
246
+ * globally while its local copy is switched off must appear in the global column,
247
+ * which is the whole point of "register globally".
248
+ *
249
+ * @param {object} ctx - host context.
250
+ * @returns {{ name: string, managed: boolean, enabled: boolean }[]} the manager's servers.
251
+ */
252
+ function globalServersOf(ctx) {
253
+ const manager = serviceOf(ctx, "mcpManager");
254
+ if (manager === undefined || typeof manager.list !== "function") return [];
255
+ return manager.list()
256
+ .filter((entry) => typeof entry?.name === "string")
257
+ .map((entry) => ({ name: entry.name, managed: true, enabled: entry.status?.state !== "disabled" }));
258
+ }
259
+
260
+ /**
261
+ * Wait for the manager to report a server the settings just wrote, so the dialog
262
+ * shows it where it now lives instead of one beat late.
263
+ * @param {object} ctx - host context.
264
+ * @param {string} serverName - the server that was just configured.
265
+ * @returns {Promise<void>} settles after the manager reports it, or after ~2s.
266
+ */
267
+ async function settleManager(ctx, serverName) {
268
+ const manager = serviceOf(ctx, "mcpManager");
269
+ if (manager === undefined || typeof manager.list !== "function") return;
270
+ for (let attempt = 0; attempt < 40; attempt += 1) {
271
+ if (manager.list().some((entry) => entry?.name === serverName)) return;
272
+ await new Promise((resolve) => setTimeout(resolve, 50));
273
+ }
274
+ }
275
+
276
+ /** The two-section view for one agent.
277
+ * @param {object} ctx - host context.
278
+ * @param {object} agent - the live agent.
279
+ * @param {string} cwd - the session workspace directory.
280
+ * @param {object} state - the switch state.
281
+ * @returns {Promise<object>} the dialog view.
282
+ */
283
+ async function viewOf(ctx, agent, cwd, state) {
284
+ const { disabledTools, disabledServers } = switchesOf(state, cwd);
285
+ const configPath = await findConfigPath(cwd);
286
+ let workspaceServers = [];
287
+ let workspaceError;
288
+ if (configPath !== undefined) {
289
+ try {
290
+ const loaded = await loadServers(configPath, cwd);
291
+ workspaceServers = loaded.servers.map((entry) => entry.serverName);
292
+ } catch (error) {
293
+ // A broken project file must not blank the whole dialog: the global
294
+ // section and the add form do not depend on it.
295
+ workspaceServers = [];
296
+ workspaceError = message(error);
297
+ }
298
+ }
299
+ return {
300
+ ...buildView({
301
+ cwd,
302
+ toolNames: toolNamesOf(ctx, agent),
303
+ globalServers: globalServersOf(ctx),
304
+ workspaceServers,
305
+ disabledTools,
306
+ disabledServers,
307
+ }),
308
+ ...(workspaceError === undefined ? {} : { workspaceError }),
309
+ };
310
+ }
311
+
312
+ /** True for a plain object, so arrays and null are rejected as records. */
313
+ function isRecord(value) {
314
+ return value !== null && typeof value === "object" && !Array.isArray(value);
315
+ }
316
+
317
+ /** The declared servers of one document, refusing an array-shaped `mcpServers`. */
318
+ function declaredServers(parsed) {
319
+ return isRecord(parsed.mcpServers) ? parsed.mcpServers : {};
320
+ }
321
+
322
+ /**
323
+ * Serialize every read-modify-write the dialog performs. Two windows toggling at
324
+ * once would otherwise read the same state and let the later write win.
325
+ */
326
+ let mutationTail = Promise.resolve();
327
+
328
+ /**
329
+ * Run one mutation after the previous one settled.
330
+ * @param {() => Promise<object>} change - the read-modify-write.
331
+ * @returns {Promise<object>} what the mutation produced.
332
+ */
333
+ function mutate(change) {
334
+ const next = mutationTail.then(change);
335
+ mutationTail = next.then(() => {}, () => {});
336
+ return next;
337
+ }
338
+
339
+ /** Every live agent reading one workspace. */
340
+ function agentsInWorkspace(ctx, cwd) {
341
+ return ctx.agents.list().filter((agent) => cwdOf(agent) === cwd);
342
+ }
343
+
344
+ /** Unmount one remembered server for one agent. */
345
+ async function unmountServer(agent, serverName) {
346
+ const record = recordFor(agent);
347
+ const fiber = record.servers.get(serverName);
348
+ if (fiber === undefined) return;
349
+ record.servers.delete(serverName);
350
+ await fiber?.dispose?.();
351
+ }
352
+
353
+ /** Mount one declared server by name, or report that the project no longer declares it. */
354
+ async function mountNamed(ctx, agent, cwd, serverName) {
355
+ if (recordFor(agent).servers.has(serverName)) return;
356
+ const configPath = await findConfigPath(cwd);
357
+ if (configPath === undefined) throw new Error(`no .mcp.json for ${cwd}`);
358
+ const loaded = await loadServers(configPath, cwd);
359
+ const found = loaded.servers.find((entry) => entry.serverName === serverName);
360
+ if (found === undefined) throw new Error(`"${serverName}" is not declared in ${configPath}`);
361
+ await mountServer(ctx, agent, found.spec);
362
+ }
363
+
364
+ /**
365
+ * The host operations the dialog dispatcher calls, bound to the live host.
366
+ * @param {object} ctx - host context.
367
+ * @param {{ path?: string }} [options] - the state file, defaulting to the harness home (tests pass a temp path).
368
+ * @returns {object} one method per dialog action.
369
+ */
370
+ export function depsFor(ctx, options = {}) {
371
+ const path = options.path ?? statePath(homedir());
372
+ const agentOf = (sessionId) => {
373
+ const agent = typeof ctx.agents?.get === "function" ? ctx.agents.get(sessionId) : undefined;
374
+ if (agent === undefined) throw new Error(`no live agent for session ${String(sessionId)}`);
375
+ const cwd = cwdOf(agent);
376
+ if (cwd === undefined) throw new Error("the session has no working directory");
377
+ return { agent, cwd };
378
+ };
379
+ const settings = () => {
380
+ const service = serviceOf(ctx, "settings");
381
+ if (service === undefined || typeof service.update !== "function") {
382
+ throw new Error("this profile has no settings service; global MCP servers cannot be added here");
383
+ }
384
+ return service;
385
+ };
386
+ return {
387
+ async status(sessionId) {
388
+ const { agent, cwd } = agentOf(sessionId);
389
+ return viewOf(ctx, agent, cwd, await readState(path));
390
+ },
391
+ async setTool(sessionId, tool, enabled) {
392
+ const { cwd } = agentOf(sessionId);
393
+ // Only a real MCP tool name is switchable: the dialog renders just those,
394
+ // and a stray name here would hide an unrelated tool with no row to undo it.
395
+ if (typeof tool !== "string" || !tool.startsWith("mcp__")) throw new Error(`"${String(tool)}" is not an MCP tool name`);
396
+ if (!toolNamesOf(ctx, undefined).includes(tool)) throw new Error(`"${tool}" is not a tool of any connected MCP server`);
397
+ const state = await mutate(async () => {
398
+ const next = withTool(await readState(path), cwd, tool, enabled);
399
+ await writeState(path, next);
400
+ return next;
401
+ });
402
+ // One workspace's switch reaches every agent reading that workspace.
403
+ for (const agent of agentsInWorkspace(ctx, cwd)) applyRestriction(ctx, agent, state);
404
+ const { agent } = agentOf(sessionId);
405
+ return viewOf(ctx, agent, cwd, state);
406
+ },
407
+ async setServer(sessionId, server, enabled) {
408
+ const { agent, cwd } = agentOf(sessionId);
409
+ const state = await mutate(async () => {
410
+ const next = withServer(await readState(path), cwd, server, enabled);
411
+ await writeState(path, next);
412
+ return next;
413
+ });
414
+ for (const target of agentsInWorkspace(ctx, cwd)) {
415
+ if (enabled) await mountNamed(ctx, target, cwd, server);
416
+ else await unmountServer(target, server);
417
+ }
418
+ return viewOf(ctx, agent, cwd, state);
419
+ },
420
+ async setGlobalServer(sessionId, server, enabled) {
421
+ const { agent, cwd } = agentOf(sessionId);
422
+ if (!globalServersOf(ctx).some((entry) => entry.name === server)) {
423
+ throw new Error(`"${server}" is not a server this profile manages globally`);
424
+ }
425
+ await settings().update("mcp-manager", { servers: { [server]: { enabled } } });
426
+ await settleManager(ctx, server);
427
+ return viewOf(ctx, agent, cwd, await readState(path));
428
+ },
429
+ async add(sessionId, input) {
430
+ const { agent, cwd } = agentOf(sessionId);
431
+ const serverName = String(input.name ?? "").trim();
432
+ const entry = entryFromInput(input);
433
+ validateEntry(serverName, entry, cwd);
434
+ if (input.scope === "global") {
435
+ if (globalServersOf(ctx).some((server) => server.name === serverName)) throw new Error(`"${serverName}" is already a global MCP server`);
436
+ await settings().update("mcp-manager", { servers: { [serverName]: managerEntry(entry, cwd) } });
437
+ await settleManager(ctx, serverName);
438
+ } else {
439
+ const configPath = (await findConfigPath(cwd)) ?? join(resolve(cwd), ".mcp.json");
440
+ await mutate(async () => {
441
+ const parsed = await readConfig(configPath);
442
+ const declared = declaredServers(parsed);
443
+ if (Object.hasOwn(declared, serverName)) throw new Error(`"${serverName}" already exists in ${configPath}`);
444
+ await writeConfig(configPath, { ...parsed, mcpServers: { ...declared, [serverName]: entry } });
445
+ return {};
446
+ });
447
+ for (const target of agentsInWorkspace(ctx, cwd)) await mountNamed(ctx, target, cwd, serverName);
448
+ }
449
+ return viewOf(ctx, agent, cwd, await readState(path));
450
+ },
451
+ async promote(sessionId, serverName) {
452
+ const { agent, cwd } = agentOf(sessionId);
453
+ const configPath = await findConfigPath(cwd);
454
+ if (configPath === undefined) throw new Error(`no .mcp.json for ${cwd}`);
455
+ const parsed = await readConfig(configPath);
456
+ const entry = declaredServers(parsed)[serverName];
457
+ if (entry === undefined) throw new Error(`"${serverName}" is not declared in ${configPath}`);
458
+ const projectDir = dirname(resolve(configPath));
459
+ validateEntry(serverName, entry, projectDir);
460
+ await settings().update("mcp-manager", { servers: { [serverName]: managerEntry(entry, projectDir) } });
461
+ await settleManager(ctx, serverName);
462
+ // The workspace copy stays exactly as it was: the dialog lists the server in
463
+ // both columns, and this session keeps using the copy it already mounted.
464
+ return viewOf(ctx, agent, cwd, await readState(path));
465
+ },
466
+ };
467
+ }
468
+
469
+ /** Answer one request with JSON. */
470
+ function respond(response, status, answer) {
471
+ response.writeHead(status, { "content-type": "application/json; charset=utf-8" });
472
+ response.end(JSON.stringify(answer));
473
+ }
474
+
475
+ /**
476
+ * Serve one dialog request: read the body, hand it to the dispatcher, write its answer.
477
+ * The route is same-origin only (the host's own authorization still applies); a
478
+ * body over the limit is refused unread.
479
+ * @param {object} ctx - host context.
480
+ * @param {import("node:http").IncomingMessage} request - the request.
481
+ * @param {import("node:http").ServerResponse} response - the response.
482
+ * @returns {Promise<void>}
483
+ */
484
+ async function serveDialog(ctx, request, response) {
485
+ if (request.method !== "POST") {
486
+ respond(response, 405, { ok: false, error: { code: "method-not-allowed", message: "POST only" } });
487
+ return;
488
+ }
489
+ let size = 0;
490
+ const chunks = [];
491
+ for await (const chunk of request) {
492
+ size += chunk.length;
493
+ if (size > BODY_LIMIT) {
494
+ respond(response, 413, { ok: false, error: { code: "too-large", message: `body over ${String(BODY_LIMIT)} bytes` } });
495
+ return;
496
+ }
497
+ chunks.push(chunk);
498
+ }
499
+ let body;
500
+ try {
501
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
502
+ } catch (error) {
503
+ respond(response, 400, { ok: false, error: { code: "invalid-body", message: message(error) } });
504
+ return;
505
+ }
506
+ respond(response, 200, await dispatch(body, depsFor(ctx)));
507
+ }
508
+
509
+ /** Mount the dialog route when this profile has a Web server; other profiles lose only the dialog. */
510
+ function registerDialogRoute(ctx) {
511
+ ctx.inject(["webServer"], (serverCtx) => {
512
+ const webServer = serviceOf(serverCtx, "webServer");
513
+ if (webServer === undefined || typeof webServer.register !== "function" || typeof serverCtx.effect !== "function") return;
514
+ serverCtx.effect(() => webServer.register({
515
+ kind: "exact",
516
+ path: DIALOG_PATH,
517
+ handler: (request, response) => serveDialog(ctx, request, response),
518
+ }), "project-mcp.dialog");
519
+ });
520
+ }
141
521
 
142
522
  /**
143
523
  * Mount the project's servers for every agent whose session directory declares
@@ -147,16 +527,42 @@ async function runMcp(ctx, invocation) {
147
527
  * @param {import("@deepseek-ai/cordis").Context} ctx - the host context.
148
528
  */
149
529
  export function apply(ctx) {
530
+ const path = statePath(homedir());
531
+ // This row injects only `agents`: reading `ctx.tools` without injecting it throws
532
+ // in Cordis. Everything that touches the tool registry therefore runs on the
533
+ // context the optional `tools` injection hands back.
534
+ let toolCtx;
535
+ const restrictAll = (state) => {
536
+ if (toolCtx === undefined) return;
537
+ for (const agent of ctx.agents.list()) applyRestriction(toolCtx, agent, state);
538
+ };
150
539
  const wire = async (agent) => {
151
540
  try {
152
- const mounted = await mountProjectMcp(ctx, agent);
541
+ const state = await readState(path);
542
+ const mounted = await mountProjectMcp(ctx, agent, state);
543
+ if (toolCtx !== undefined) applyRestriction(toolCtx, agent, state);
153
544
  if (mounted > 0) ctx.logger.info(`project-mcp: mounted ${mounted} server(s) for ${agent.id}`);
154
545
  } catch (error) {
155
546
  ctx.logger.warn(`project-mcp: mounting failed for ${String(agent?.id)}: ${message(error)}`);
156
547
  }
157
548
  };
158
549
  ctx.on("agent/created", ({ agent }) => wire(agent));
550
+ ctx.on("agent/disposed", ({ agent }) => {
551
+ // The mounts and the restriction belong to the agent scope and die with it.
552
+ delete agent[RECORDS];
553
+ });
554
+ // A server registers its tools only after it connects, so a switched-off tool
555
+ // usually appears later than the agent: re-apply whenever the tool list moves.
556
+ ctx.on("tools/change", () => {
557
+ void readState(path).then(restrictAll).catch(() => {});
558
+ });
559
+ ctx.inject(["tools"], (injected) => {
560
+ toolCtx = injected;
561
+ // Agents created before the injection settled still need their restriction.
562
+ void readState(path).then(restrictAll).catch(() => {});
563
+ registerDialogRoute(injected);
564
+ });
159
565
  // A reload mid-session must reach agents that are already live.
160
566
  for (const agent of ctx.agents.list()) void wire(agent);
161
567
  registerStatusCommand(ctx);
162
- }
568
+ }
@@ -0,0 +1,154 @@
1
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { dirname, join, resolve } from "node:path";
3
+
4
+ /**
5
+ * Per-workspace MCP switch state, owned by the `/mcp` dialog.
6
+ *
7
+ * A switch is remembered per workspace directory, so turning a tool off in one
8
+ * project never reaches another. The file is untrusted local state: a corrupt or
9
+ * hand-edited document degrades to "everything on" instead of failing the row.
10
+ *
11
+ * @module dsh-hiss-plugins/project-mcp/state
12
+ */
13
+
14
+ /** One workspace's switches; both lists hold names, absent means enabled. */
15
+ function emptyWorkspace() {
16
+ return { disabledTools: [], disabledServers: [] };
17
+ }
18
+
19
+ /**
20
+ * The state with no switches remembered.
21
+ * @returns {{ workspaces: Record<string, { disabledTools: string[], disabledServers: string[] }> }}
22
+ */
23
+ export function emptyState() {
24
+ return { workspaces: {} };
25
+ }
26
+
27
+ /** Every string of a list, ignoring anything else. */
28
+ function strings(value) {
29
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
30
+ }
31
+
32
+ /**
33
+ * Coerce anything read from disk into a usable state.
34
+ * @param {unknown} raw - parsed JSON, or whatever readState managed to produce.
35
+ * @returns {{ workspaces: Record<string, { disabledTools: string[], disabledServers: string[] }> }}
36
+ */
37
+ export function normalizeState(raw) {
38
+ const state = emptyState();
39
+ if (raw === null || typeof raw !== "object") return state;
40
+ const workspaces = raw.workspaces;
41
+ if (workspaces === null || typeof workspaces !== "object") return state;
42
+ for (const [cwd, entry] of Object.entries(workspaces)) {
43
+ if (entry === null || typeof entry !== "object") continue;
44
+ state.workspaces[cwd] = {
45
+ disabledTools: strings(entry.disabledTools),
46
+ disabledServers: strings(entry.disabledServers),
47
+ };
48
+ }
49
+ return state;
50
+ }
51
+
52
+ /** The switches remembered for one directory, or the all-on default. */
53
+ function workspaceOf(state, cwd) {
54
+ return normalizeState(state).workspaces[resolve(cwd)];
55
+ }
56
+
57
+ /**
58
+ * Whether a tool is enabled in one workspace.
59
+ * @param {object} state - the current state.
60
+ * @param {string} cwd - the workspace directory.
61
+ * @param {string} tool - the public tool name.
62
+ * @returns {boolean} true when the workspace has not turned it off.
63
+ */
64
+ export function isToolEnabled(state, cwd, tool) {
65
+ return !(workspaceOf(state, cwd)?.disabledTools.includes(tool) ?? false);
66
+ }
67
+
68
+ /**
69
+ * Whether a project server is enabled in one workspace.
70
+ * @param {object} state - the current state.
71
+ * @param {string} cwd - the workspace directory.
72
+ * @param {string} server - the server name declared by `.mcp.json`.
73
+ * @returns {boolean} true when the workspace has not turned it off.
74
+ */
75
+ export function isServerEnabled(state, cwd, server) {
76
+ return !(workspaceOf(state, cwd)?.disabledServers.includes(server) ?? false);
77
+ }
78
+
79
+ /**
80
+ * Return a copy with one name added to (or removed from) a workspace list.
81
+ * @param {object} state - the current state; never mutated.
82
+ * @param {string} cwd - the workspace directory.
83
+ * @param {string} name - the tool or server name.
84
+ * @param {boolean} enabled - the switch position to record.
85
+ * @param {"disabledTools" | "disabledServers"} field - which list to edit.
86
+ * @returns {object} the new state.
87
+ */
88
+ function withName(state, cwd, name, enabled, field) {
89
+ const next = normalizeState(state);
90
+ const key = resolve(cwd);
91
+ const entry = next.workspaces[key] ?? emptyWorkspace();
92
+ const others = entry[field].filter((candidate) => candidate !== name);
93
+ next.workspaces[key] = { ...entry, [field]: enabled ? others : [...others, name] };
94
+ return next;
95
+ }
96
+
97
+ /**
98
+ * Record one tool switch for one workspace.
99
+ * @param {object} state - the current state; never mutated.
100
+ * @param {string} cwd - the workspace directory.
101
+ * @param {string} tool - the public tool name.
102
+ * @param {boolean} enabled - whether the tool should be visible.
103
+ * @returns {object} the new state.
104
+ */
105
+ export function withTool(state, cwd, tool, enabled) {
106
+ return withName(state, cwd, tool, enabled, "disabledTools");
107
+ }
108
+
109
+ /**
110
+ * Record one project-server switch for one workspace.
111
+ * @param {object} state - the current state; never mutated.
112
+ * @param {string} cwd - the workspace directory.
113
+ * @param {string} server - the server name declared by `.mcp.json`.
114
+ * @param {boolean} enabled - whether the server should be mounted.
115
+ * @returns {object} the new state.
116
+ */
117
+ export function withServer(state, cwd, server, enabled) {
118
+ return withName(state, cwd, server, enabled, "disabledServers");
119
+ }
120
+
121
+ /**
122
+ * Where the state document lives under a harness home.
123
+ * @param {string} home - the user's home directory.
124
+ * @returns {string} the absolute state path.
125
+ */
126
+ export function statePath(home) {
127
+ return join(home, ".dsh", "hiss-mcp.json");
128
+ }
129
+
130
+ /**
131
+ * Read the state document; a missing, corrupt, or unrecognizable file reads as empty.
132
+ * @param {string} path - the state path.
133
+ * @returns {Promise<object>} the normalized state.
134
+ */
135
+ export async function readState(path) {
136
+ try {
137
+ return normalizeState(JSON.parse(await readFile(path, "utf8")));
138
+ } catch {
139
+ return emptyState();
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Write the state document atomically: a rename never leaves a half-written file.
145
+ * @param {string} path - the state path.
146
+ * @param {object} state - the state to record.
147
+ * @returns {Promise<void>}
148
+ */
149
+ export async function writeState(path, state) {
150
+ await mkdir(dirname(path), { recursive: true });
151
+ const temporary = `${path}.${String(process.pid)}.${String(Date.now())}.tmp`;
152
+ await writeFile(temporary, `${JSON.stringify(normalizeState(state), null, 2)}\n`);
153
+ await rename(temporary, path);
154
+ }