dsh-hiss-plugins 1.4.0 → 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.
package/README.md CHANGED
@@ -162,8 +162,10 @@ colgrep command:"init" / command:"status" / command:"clear"
162
162
  - **首轮即生效**:挂载发生在 `agent/created`(宿主会 await 这个监听器)里,会话第一次对话就能看到工具;插件 reload 时也会给已经活着的 agent 补挂一次。
163
163
  - **${VAR} 展开**:`${TOKEN}` / `${TOKEN:-默认值}` 在挂载时用宿主进程环境求值,`.mcp.json` 里不必写明文密钥。
164
164
  - **失败不致命**:坏 JSON、不支持的 transport、起不来的 server 都只影响它自己,打一条 warn,会话照常开。
165
- - **`/mcp` 看状态**:在本项目的会话里执行 `/mcp`,逐条列出 `.mcp.json` 声明的 server 与其实时状态 —— `connected, N tools`(MCP 桥连上并同步工具后才注册工具)、`no tools`(没连上,或 server 本身不暴露工具)、`skipped`(条目映射不了)、`unusable`(宿主 MCP 桥的 schema 拒绝);另外报告本会话里来自项目外配置的 MCP 工具总数。状态读的是当前 agent 自己的工具表,所以列的是**此刻真正可用**的工具;命令不接受参数。
165
+ - **`/mcp` 看状态(文本报告)**:在本项目的会话里执行 `/mcp`,逐条列出 `.mcp.json` 声明的 server 与其实时状态 —— `connected, N tools`(MCP 桥连上并同步工具后才注册工具)、`no tools`(没连上,或 server 本身不暴露工具)、`skipped`(条目映射不了)、`unusable`(宿主 MCP 桥的 schema 拒绝);另外报告本会话里来自项目外配置的 MCP 工具总数。状态读的是当前 agent 自己的工具表,所以列的是**此刻真正可用**的工具;命令不接受参数。
166
166
  - **新会话里立即显示**:DSH 的 Web 客户端在会话还没有任何 turn 时把整段对话当 blank 隐藏(只有 `turn/start` 会清 `sessionListMetadata.blank`),而 `/mcp` 只写 `command/run`/`command/done`。浏览器半因此给 `/mcp` 注册了一个非 `command` 的**伴随节点**(`hiss-mcp-command`,零尺寸),chat 视图立即激活——不必再先发一条消息。
167
+ - **`/mcp` 弹窗(Web GUI)**:输入框里敲 `/mcp`(不带参数)打开对话框,而不是发消息。布局是**左右两栏**:左边「全局 MCP」、右边「当前工作区 MCP」。每台服务器默认**折叠**,点「N 个工具」展开列表;展开后全局那栏每个工具一个开关(关掉后模型这一轮就看不到它),工作区那栏工具只读。两种服务器都带**整台开关**:全局那台写 mcp-manager 的 `enabled`(对所有会话生效),工作区那台即时挂载/卸载。工作区服务器旁的「注册到全局」把它的配置写进全局后,它**立刻同时出现在两栏**:全局那份对所有会话生效,工作区那份保持原样、继续给本会话用(想只留全局那份,就把工作区那栏的开关关掉)。右下「添加 MCP」按钮展开新增表单(选全局或工作区),标题栏「刷新」重新读取状态。开关状态按**工作区路径**记在 `~/.dsh/hiss-mcp.json`,换项目互不影响。带参数的 `/mcp` 仍走上面的文本报告(headless / ACP 也用它)。
168
+ - **为什么工作区服务器不能逐工具关**:DSH 只允许在 agent scope 屏蔽**全局层**注册的工具(`tools.restrict`),项目 MCP 工具挂在 agent 自己的 scope 里,只能整台挂载/卸载。要逐工具控制,点该服务器的「注册到全局」把它写进全局配置(mcp-manager),它随后出现在全局区、可逐工具开关。
167
169
 
168
170
  `.mcp.json` 就是 Claude Code 的项目级 MCP 配置文件:
169
171
 
@@ -202,11 +204,15 @@ colgrep command:"init" / command:"status" / command:"clear"
202
204
 
203
205
  已知限制:
204
206
 
205
- 1. **不热重载**:改完 `.mcp.json` 要开新会话(或重启 dsh)。已存在的会话仍用挂载时的配置。
207
+ 1. **手改 `.mcp.json` 不热重载**:改完文件要开新会话(或重启 dsh);弹窗里的服务器开关与新增是即时生效的。
206
208
  2. **每个会话一套连接**:多会话同时开在同一项目会各起一份 MCP server 进程。
207
209
  3. **不支持 `sse`**:宿主 MCP 桥只支持 `stdio` 与 `streamable-http`,`sse` 条目会被跳过并告警。
208
210
  4. **只看 `.mcp.json`**:不读 `.dsh/mcp.yml`、用户层配置或 `~/.claude.json`。
209
- 5. **`/mcp` 只列本项目声明的 server**:项目外(profile / preset 里)配置的 MCP server 只计入末尾的工具总数,不列名字 —— 宿主没有公开这些行的配置,公开的工具名也按设计不可反解出 server 名。
211
+ 5. **文本报告只列本项目声明的 server**:项目外(profile / preset 里)配置的 MCP server 只计入末尾的工具总数,不列名字。Web 弹窗会经 mcp-manager 的清单列出这些全局服务器名(它只给名字与状态,不给连接探活)。
212
+ 6. **弹窗不做连接探测**:没连上的服务器显示「未连接 / 0 个工具」,不主动 probe(probe 会真的拉起一个 server 进程)。
213
+ 7. **新增表单的 args 按空白切分**:参数里带空格(如含空格的路径)无法在表单表达,需手改 `.mcp.json`。
214
+ 8. **开关状态按目录路径记**:同一个项目用不同写法(盘符大小写、符号链接)打开会话,会各记一套开关。
215
+ 9. **注册到全局后同一台会有两份连接**:全局一份(所有会话)+ 本会话的项目挂载一份,工具名在 agent scope 里以后者为准;不需要时把工作区那栏的开关关掉。
210
216
 
211
217
  ## 功能:git-bash
212
218
 
@@ -404,8 +410,8 @@ test/ node:test:<feature>/ 九个目录 + manifest / patch / c
404
410
  ## 发布(给维护者)
405
411
 
406
412
  ```powershell
407
- git tag dsh-hiss-plugins@1.4.0 # 必须与本目录 package.json 的 version 逐字一致
408
- git push origin dsh-hiss-plugins@1.4.0
413
+ git tag dsh-hiss-plugins@1.5.0 # 必须与本目录 package.json 的 version 逐字一致
414
+ git push origin dsh-hiss-plugins@1.5.0
409
415
  ```
410
416
 
411
417
  CI(`.github/workflows/publish.yml`,Windows runner)解析 tag、跑全量测试,再用 **npm trusted publishing(OIDC,无需任何 token)** 发布;包内 `prepublishOnly` 会再跑一次 `npm test`。手工发布:`npm publish`(`publishConfig.access` 已设为 public),发版前先 `node ../scripts/smoke-profile.mjs` 走一遍真实安装 + 真启动。发布新版本前记得递增 `package.json` 的 `version`。
package/lib/client.js CHANGED
@@ -62,6 +62,20 @@ window.__ModuleLoader__.load({
62
62
  const LAN_HEADER_STYLE = { display: "flex", alignItems: "center", justifyContent: "space-between", gap: "12px" };
63
63
  const LAN_HINT_STYLE = { margin: 0, color: "var(--dsw-alias-label-tertiary)", fontSize: "13px", lineHeight: "20px" };
64
64
  const LAN_FRAME_STYLE = { width: "100%", height: "360px", border: "none", borderRadius: "8px", background: "#fff", display: "block" };
65
+ /** The MCP dialog: same shell as the phone popup, one column of servers inside. */
66
+ const MCP_DIALOG_STYLE = { width: "880px", maxWidth: "calc(100vw - 32px)", maxHeight: "calc(100vh - 48px)", overflow: "auto", display: "flex", flexDirection: "column", gap: "14px", padding: "16px", borderRadius: "12px", background: "var(--dsw-alias-bg-primary, #fff)", color: "var(--dsw-alias-label-primary)", boxShadow: "0 18px 48px rgba(0, 0, 0, 0.28)" };
67
+ /** Two columns: global on the left, the workspace on the right. */
68
+ const MCP_COLUMNS_STYLE = { display: "flex", gap: "16px", alignItems: "flex-start" };
69
+ const MCP_COLUMN_STYLE = { display: "flex", flexDirection: "column", gap: "8px", flex: "1 1 0", minWidth: 0 };
70
+ const MCP_ACTIONS_STYLE = { display: "inline-flex", gap: "8px" };
71
+ const MCP_SECTION_STYLE = { display: "flex", flexDirection: "column", gap: "6px" };
72
+ const MCP_SERVER_STYLE = { display: "flex", flexDirection: "column", gap: "4px", padding: "8px 10px", border: "0.5px solid var(--dsw-alias-settings-card-stroke, var(--dsw-alias-border-l3))", borderRadius: "10px" };
73
+ const MCP_SERVER_HEADER = { display: "flex", alignItems: "center", gap: "10px" };
74
+ const MCP_TOOL_STYLE = { display: "flex", alignItems: "center", gap: "8px", fontSize: "13px", lineHeight: "20px" };
75
+ const MCP_TOOL_NAME_STYLE = { fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: "12px", color: "var(--dsw-alias-label-secondary, var(--dsw-alias-label-tertiary))" };
76
+ const MCP_FIELD_STYLE = { display: "flex", flexDirection: "column", gap: "2px" };
77
+ const MCP_INPUT_STYLE = { font: "inherit", fontSize: "13px", padding: "4px 6px", borderRadius: "6px", border: "0.5px solid var(--dsw-alias-border-l3)", background: "transparent", color: "var(--dsw-alias-label-primary)" };
78
+ const MCP_FORM_STYLE = { display: "flex", flexDirection: "column", gap: "8px", paddingTop: "8px", borderTop: "0.5px solid var(--dsw-alias-border-l3)" };
65
79
 
66
80
  /**
67
81
  * Copy for the management tab; the `locale/*.json` files carry the same entries, where the
@@ -101,6 +115,38 @@ window.__ModuleLoader__.load({
101
115
  lanNotInstalled: "这个 profile 里没有 lan-access 行。",
102
116
  lanReadOnly: "无法在这个页面启用 lan-access 行({reason})。",
103
117
  lanFrameFailed: "二维码页没有响应;请先打开 /lan-access 检查原因。",
118
+ mcpTitle: "MCP 服务器",
119
+ mcpClose: "关闭",
120
+ mcpLoading: "正在读取 MCP 状态…",
121
+ mcpFailed: "操作失败:{error}",
122
+ mcpGlobal: "全局 MCP",
123
+ mcpLocal: "当前工作区 MCP",
124
+ mcpNoGlobal: "没有全局 MCP 服务器。",
125
+ mcpNoLocal: "这个工作区没有 .mcp.json 服务器。",
126
+ mcpNoTools: "没有工具(未连接,或服务器没有工具)。",
127
+ mcpConnected: "已连接",
128
+ mcpNotConnected: "未连接",
129
+ mcpToolToggle: "开关 {name}",
130
+ mcpServerToggle: "开关服务器 {name}",
131
+ mcpPromote: "注册到全局",
132
+ mcpAddTitle: "新增 MCP 服务器",
133
+ mcpAddName: "名称",
134
+ mcpAddScope: "作用域",
135
+ mcpAddGlobal: "全局(所有会话)",
136
+ mcpAddWorkspace: "当前工作区",
137
+ mcpAddType: "类型",
138
+ mcpAddStdio: "stdio(启动命令)",
139
+ mcpAddHttp: "http(URL)",
140
+ mcpAddCommand: "命令",
141
+ mcpAddArgs: "参数(空格分隔)",
142
+ mcpAddUrl: "URL",
143
+ mcpAddSubmit: "添加",
144
+ mcpRefresh: "刷新",
145
+ mcpAdd: "添加 MCP",
146
+ mcpExpand: "{count} 个工具",
147
+ mcpCollapse: "收起",
148
+ mcpExpandAria: "展开 {name} 的工具",
149
+ mcpCollapseAria: "收起 {name} 的工具",
104
150
  };
105
151
  /** English dictionary checked against the Chinese key set. */
106
152
  const en = {
@@ -136,6 +182,38 @@ window.__ModuleLoader__.load({
136
182
  lanNotInstalled: "This profile has no lan-access row.",
137
183
  lanReadOnly: "The lan-access row cannot be enabled from here ({reason}).",
138
184
  lanFrameFailed: "The QR page did not answer; open /lan-access to see why.",
185
+ mcpTitle: "MCP servers",
186
+ mcpClose: "Close",
187
+ mcpLoading: "Reading MCP state…",
188
+ mcpFailed: "The operation failed: {error}",
189
+ mcpGlobal: "Global MCP",
190
+ mcpLocal: "Workspace MCP",
191
+ mcpNoGlobal: "No global MCP servers.",
192
+ mcpNoLocal: "This workspace declares no .mcp.json servers.",
193
+ mcpNoTools: "No tools (not connected, or the server exposes none).",
194
+ mcpConnected: "Connected",
195
+ mcpNotConnected: "Not connected",
196
+ mcpToolToggle: "Toggle {name}",
197
+ mcpServerToggle: "Toggle server {name}",
198
+ mcpPromote: "Register globally",
199
+ mcpAddTitle: "Add an MCP server",
200
+ mcpAddName: "Name",
201
+ mcpAddScope: "Scope",
202
+ mcpAddGlobal: "Global (every session)",
203
+ mcpAddWorkspace: "This workspace",
204
+ mcpAddType: "Type",
205
+ mcpAddStdio: "stdio (a command)",
206
+ mcpAddHttp: "http (a URL)",
207
+ mcpAddCommand: "Command",
208
+ mcpAddArgs: "Arguments (space separated)",
209
+ mcpAddUrl: "URL",
210
+ mcpAddSubmit: "Add",
211
+ mcpRefresh: "Refresh",
212
+ mcpAdd: "Add MCP",
213
+ mcpExpand: "{count} tools",
214
+ mcpCollapse: "Collapse",
215
+ mcpExpandAria: "Expand the tools of {name}",
216
+ mcpCollapseAria: "Collapse the tools of {name}",
139
217
  };
140
218
 
141
219
  /** Read one thrown value as text. */
@@ -531,6 +609,251 @@ window.__ModuleLoader__.load({
531
609
  });
532
610
  }
533
611
 
612
+ /** Values the `/mcp` dialog needs from apply(): its store, the bound lookup and the host call. */
613
+ const mcpUi = {
614
+ store: null,
615
+ t: (key) => key,
616
+ post: async () => ({}),
617
+ };
618
+
619
+ /**
620
+ * Dialog state shared by the decorator that opens it and the overlay that draws it.
621
+ * @returns a tiny external store holding the open dialog's session.
622
+ */
623
+ function createDialogStore() {
624
+ let current = { open: false, sessionId: "" };
625
+ const listeners = new Set();
626
+ const set = (next) => {
627
+ if (next.open === current.open && next.sessionId === current.sessionId) return;
628
+ current = next;
629
+ for (const listener of [...listeners]) listener();
630
+ };
631
+ return {
632
+ get: () => current,
633
+ open(sessionId) {
634
+ set({ open: true, sessionId });
635
+ },
636
+ close() {
637
+ set({ open: false, sessionId: current.sessionId });
638
+ },
639
+ listen(listener) {
640
+ listeners.add(listener);
641
+ return () => {
642
+ listeners.delete(listener);
643
+ };
644
+ },
645
+ };
646
+ }
647
+
648
+ /** Subscribe a component to the dialog store. */
649
+ function useDialog(store) {
650
+ const [dialog, setDialog] = React.useState(store.get());
651
+ React.useEffect(() => store.listen(() => setDialog(store.get())), []);
652
+ return dialog;
653
+ }
654
+
655
+ /** The empty add-server form. */
656
+ function emptyForm() {
657
+ return { name: "", scope: "workspace", type: "stdio", command: "", args: "", url: "" };
658
+ }
659
+
660
+ /** One master switch, so both columns read the same. */
661
+ function switchControl(checked, label, onChange) {
662
+ return jsx("label", { style: SWITCH_STYLE, children: jsx("input", {
663
+ type: "checkbox",
664
+ checked,
665
+ "aria-label": label,
666
+ onChange: (event) => onChange(event.currentTarget.checked),
667
+ }) });
668
+ }
669
+
670
+ /**
671
+ * One server card: master switch, connection line, the expand toggle, and — when
672
+ * open — its tools. Collapsed is the default: a real MCP server exposes a dozen.
673
+ * @param server - one entry of the dialog view.
674
+ * @param side - "global" or "local".
675
+ * @param view - the dialog's bound lookups and actions.
676
+ * @returns the card element.
677
+ */
678
+ function serverBlock(server, side, view) {
679
+ const { t, expanded, onExpand, onTool, onServer, onGlobalServer, onPromote } = view;
680
+ const key = `${side}:${server.name}`;
681
+ const open = expanded[key] === true;
682
+ const header = [jsx("strong", { key: "name", children: server.name })];
683
+ if (side === "local") {
684
+ header.push(switchControl(server.enabled, t("mcpServerToggle", { name: server.name }), (value) => onServer(server.name, value)));
685
+ header.push(jsx("button", {
686
+ key: "promote",
687
+ type: "button",
688
+ style: BUTTON_STYLE,
689
+ onClick: () => onPromote(server.name),
690
+ children: t("mcpPromote"),
691
+ }));
692
+ } else if (server.managed) {
693
+ header.push(switchControl(server.enabled, t("mcpServerToggle", { name: server.name }), (value) => onGlobalServer(server.name, value)));
694
+ }
695
+ header.push(jsx("span", { key: "status", style: DESCRIPTION_STYLE, children: server.tools.length === 0 ? t("mcpNotConnected") : t("mcpConnected") }));
696
+ header.push(jsx("button", {
697
+ key: "expand",
698
+ type: "button",
699
+ style: BUTTON_STYLE,
700
+ "aria-label": open ? t("mcpCollapseAria", { name: server.name }) : t("mcpExpandAria", { name: server.name }),
701
+ onClick: () => onExpand(key),
702
+ children: open ? t("mcpCollapse") : t("mcpExpand", { count: server.tools.length }),
703
+ }));
704
+ const tools = open && server.tools.length > 0
705
+ ? [jsx("ul", { key: "tools", style: LIST_STYLE, children: server.tools.map((tool) => jsxs("li", {
706
+ style: MCP_TOOL_STYLE,
707
+ children: [
708
+ side === "global" ? jsx("input", {
709
+ type: "checkbox",
710
+ checked: tool.enabled,
711
+ "aria-label": t("mcpToolToggle", { name: tool.name }),
712
+ onChange: (event) => onTool(tool.name, event.currentTarget.checked),
713
+ }) : null,
714
+ jsx("code", { style: MCP_TOOL_NAME_STYLE, children: tool.name }),
715
+ ],
716
+ }, tool.name)) })]
717
+ : [];
718
+ return jsxs("li", { style: MCP_SERVER_STYLE, children: [jsx("div", { style: MCP_SERVER_HEADER, children: header }), ...tools] }, server.name);
719
+ }
720
+
721
+ /** The `/mcp` dialog: two columns, collapsed servers, and the add form behind a button. */
722
+ function McpDialog() {
723
+ const { store, t, post } = mcpUi;
724
+ const dialog = useDialog(store);
725
+ const [state, setState] = React.useState({ kind: "idle" });
726
+ const [notice, setNotice] = React.useState(null);
727
+ const [expanded, setExpanded] = React.useState({});
728
+ const [formOpen, setFormOpen] = React.useState(false);
729
+ const [form, setForm] = React.useState(emptyForm());
730
+ React.useEffect(() => {
731
+ if (!dialog.open) return undefined;
732
+ let current = true;
733
+ setState({ kind: "loading" });
734
+ Promise.resolve().then(() => post({ action: "status", sessionId: dialog.sessionId })).then((value) => {
735
+ if (current) setState({ kind: "ready", view: value });
736
+ }, (error) => {
737
+ if (current) setState({ kind: "error", message: messageOf(error) });
738
+ });
739
+ return () => {
740
+ current = false;
741
+ };
742
+ }, [dialog.open, dialog.sessionId]);
743
+ React.useEffect(() => {
744
+ if (!dialog.open) return undefined;
745
+ const onKey = (event) => {
746
+ if (event.key === "Escape") store.close();
747
+ };
748
+ globalThis.window?.addEventListener?.("keydown", onKey);
749
+ return () => globalThis.window?.removeEventListener?.("keydown", onKey);
750
+ }, [dialog.open, store]);
751
+ if (!dialog.open) return null;
752
+ /** Run one request and re-render from the answer; resolves to whether it worked. */
753
+ const run = (body) => {
754
+ setNotice(null);
755
+ return Promise.resolve().then(() => post({ ...body, sessionId: dialog.sessionId })).then((value) => {
756
+ setState({ kind: "ready", view: value });
757
+ return true;
758
+ }, (error) => {
759
+ setNotice(messageOf(error));
760
+ return false;
761
+ });
762
+ };
763
+ const handlers = {
764
+ t,
765
+ expanded,
766
+ onExpand: (key) => setExpanded((old) => ({ ...old, [key]: old[key] !== true })),
767
+ onTool: (tool, enabled) => run({ action: "set-tool", tool, enabled }),
768
+ onServer: (server, enabled) => run({ action: "set-server", server, enabled }),
769
+ onGlobalServer: (server, enabled) => run({ action: "set-global-server", server, enabled }),
770
+ onPromote: (server) => run({ action: "promote", server }),
771
+ };
772
+ const field = (label, key, placeholder) => jsxs("label", { style: MCP_FIELD_STYLE, children: [
773
+ jsx("span", { style: DESCRIPTION_STYLE, children: label }),
774
+ jsx("input", {
775
+ type: "text",
776
+ value: form[key],
777
+ placeholder,
778
+ style: MCP_INPUT_STYLE,
779
+ onChange: (event) => {
780
+ const value = event.currentTarget.value;
781
+ setForm((old) => ({ ...old, [key]: value }));
782
+ },
783
+ }),
784
+ ] });
785
+ const view = state.kind === "ready" ? state.view : undefined;
786
+ const submit = () => {
787
+ run({
788
+ action: "add-server",
789
+ server: { name: form.name, scope: form.scope, type: form.type, command: form.command, args: form.args, url: form.url },
790
+ }).then((accepted) => {
791
+ if (accepted) {
792
+ setForm(emptyForm());
793
+ setFormOpen(false);
794
+ }
795
+ });
796
+ };
797
+ const column = (side, title, empty, entries) => jsxs("section", { style: MCP_COLUMN_STYLE, children: [
798
+ jsx("strong", { children: title }),
799
+ entries.length === 0 ? jsx("p", { style: DESCRIPTION_STYLE, children: empty }) : jsx("ul", { style: LIST_STYLE, children: entries.map((server) => serverBlock(server, side, handlers)) }),
800
+ ] });
801
+ return jsx("div", {
802
+ role: "presentation",
803
+ style: LAN_OVERLAY_STYLE,
804
+ onClick: () => store.close(),
805
+ children: jsxs("div", {
806
+ role: "dialog",
807
+ "aria-modal": "true",
808
+ "aria-label": t("mcpTitle"),
809
+ style: MCP_DIALOG_STYLE,
810
+ onClick: (event) => event.stopPropagation(),
811
+ children: [
812
+ jsxs("div", { style: LAN_HEADER_STYLE, children: [
813
+ jsx("strong", { children: t("mcpTitle") }),
814
+ jsxs("span", { style: MCP_ACTIONS_STYLE, children: [
815
+ jsx("button", { type: "button", style: BUTTON_STYLE, "aria-label": t("mcpRefresh"), onClick: () => run({ action: "status" }), children: t("mcpRefresh") }),
816
+ jsx("button", { type: "button", style: BUTTON_STYLE, onClick: () => store.close(), children: t("mcpClose") }),
817
+ ] }),
818
+ ] }),
819
+ state.kind === "loading" ? jsx("p", { role: "status", style: DESCRIPTION_STYLE, children: t("mcpLoading") }) : null,
820
+ state.kind === "error" ? jsx("p", { role: "alert", style: DESCRIPTION_STYLE, children: t("mcpFailed", { error: state.message }) }) : null,
821
+ view !== undefined && view.workspaceError !== undefined ? jsx("p", { role: "alert", style: DESCRIPTION_STYLE, children: t("mcpFailed", { error: view.workspaceError }) }) : null,
822
+ view === undefined ? null : jsxs("div", { style: MCP_COLUMNS_STYLE, children: [
823
+ column("global", t("mcpGlobal"), t("mcpNoGlobal"), view.global),
824
+ jsxs("section", { style: MCP_COLUMN_STYLE, children: [
825
+ jsx("strong", { children: t("mcpLocal") }),
826
+ view.local.length === 0 ? jsx("p", { style: DESCRIPTION_STYLE, children: t("mcpNoLocal") }) : jsx("ul", { style: LIST_STYLE, children: view.local.map((server) => serverBlock(server, "local", handlers)) }),
827
+ jsx("button", { type: "button", style: BUTTON_STYLE, "aria-label": t("mcpAdd"), onClick: () => setFormOpen((old) => !old), children: t("mcpAdd") }),
828
+ formOpen ? jsxs("div", { style: MCP_FORM_STYLE, children: [
829
+ field(t("mcpAddName"), "name", "my-server"),
830
+ jsxs("label", { style: MCP_FIELD_STYLE, children: [
831
+ jsx("span", { style: DESCRIPTION_STYLE, children: t("mcpAddScope") }),
832
+ jsxs("select", { value: form.scope, style: MCP_INPUT_STYLE, onChange: (event) => { const value = event.currentTarget.value; setForm((old) => ({ ...old, scope: value })); }, children: [
833
+ jsx("option", { value: "workspace", children: t("mcpAddWorkspace") }),
834
+ jsx("option", { value: "global", children: t("mcpAddGlobal") }),
835
+ ] }),
836
+ ] }),
837
+ jsxs("label", { style: MCP_FIELD_STYLE, children: [
838
+ jsx("span", { style: DESCRIPTION_STYLE, children: t("mcpAddType") }),
839
+ jsxs("select", { value: form.type, style: MCP_INPUT_STYLE, onChange: (event) => { const value = event.currentTarget.value; setForm((old) => ({ ...old, type: value })); }, children: [
840
+ jsx("option", { value: "stdio", children: t("mcpAddStdio") }),
841
+ jsx("option", { value: "http", children: t("mcpAddHttp") }),
842
+ ] }),
843
+ ] }),
844
+ form.type === "http" ? field(t("mcpAddUrl"), "url", "https://example.com/mcp") : null,
845
+ form.type === "http" ? null : field(t("mcpAddCommand"), "command", "npx"),
846
+ form.type === "http" ? null : field(t("mcpAddArgs"), "args", "-y @modelcontextprotocol/server-filesystem ."),
847
+ jsx("button", { type: "button", style: BUTTON_STYLE, onClick: submit, children: t("mcpAddSubmit") }),
848
+ ] }) : null,
849
+ ] }),
850
+ ] }),
851
+ notice === null ? null : jsx("p", { role: "alert", style: DESCRIPTION_STYLE, children: t("mcpFailed", { error: notice }) }),
852
+ ],
853
+ }),
854
+ });
855
+ }
856
+
534
857
  /** Host commands whose run this browser half projects into the chat view. */
535
858
  const PROJECTED_COMMANDS = new Set(["mcp", "lan"]);
536
859
  /**
@@ -668,6 +991,42 @@ window.__ModuleLoader__.load({
668
991
  lanUi.t = t;
669
992
  lanUi.ensureEnabled = ensureLanEnabled;
670
993
  lanUi.probe = probeLanPage;
994
+ mcpUi.store = createDialogStore();
995
+ mcpUi.t = t;
996
+ /**
997
+ * Call the host's dialog route: same origin, one JSON answer, failures as text.
998
+ * @param body - the request without its session id.
999
+ * @returns the answer's `value`.
1000
+ */
1001
+ mcpUi.post = async (body) => {
1002
+ const response = await fetch("/hiss-mcp/action", {
1003
+ method: "POST",
1004
+ headers: { "content-type": "application/json" },
1005
+ body: JSON.stringify(body),
1006
+ });
1007
+ let answer = null;
1008
+ try {
1009
+ answer = await response.json();
1010
+ } catch {
1011
+ answer = null;
1012
+ }
1013
+ if (answer !== null && answer.ok === false) throw new Error(answer.error?.message ?? "the host refused the request");
1014
+ if (!response.ok) throw new Error(answer?.error?.message ?? `HTTP ${String(response.status)}`);
1015
+ return answer?.value;
1016
+ };
1017
+ // The dialog replaces the chat text report a bare /mcp used to log; an argued
1018
+ // /mcp still reaches the host command, which answers with its usage line.
1019
+ // Optional: a host without the command surface keeps the tab and the phone popup.
1020
+ if (typeof ctx.inject === "function") ctx.inject(["commandUi"], (uiCtx) => uiCtx.commandUi.decorate({
1021
+ name: "mcp",
1022
+ available: () => true,
1023
+ ui: {
1024
+ kind: "action",
1025
+ run: (session) => {
1026
+ mcpUi.store.open(session.sessionId);
1027
+ },
1028
+ },
1029
+ }));
671
1030
  ctx.slots.inject("sidebar.footer.action", () => ctx.slots.register({
672
1031
  name: "sidebar.footer.action",
673
1032
  id: "lan-access",
@@ -675,16 +1034,25 @@ window.__ModuleLoader__.load({
675
1034
  locale: NS,
676
1035
  label: () => t("lanButton"),
677
1036
  }, LanAccessButton));
678
- ctx.slots.inject("shell.overlay", () => ctx.slots.register({
679
- name: "shell.overlay",
680
- id: "lan-access.popup",
681
- order: 900,
682
- locale: NS,
683
- }, LanAccessPopup));
1037
+ ctx.slots.inject("shell.overlay", () => {
1038
+ const popup = ctx.slots.register({
1039
+ name: "shell.overlay",
1040
+ id: "lan-access.popup",
1041
+ order: 900,
1042
+ locale: NS,
1043
+ }, LanAccessPopup);
1044
+ ctx.slots.register({
1045
+ name: "shell.overlay",
1046
+ id: "mcp.dialog",
1047
+ order: 901,
1048
+ locale: NS,
1049
+ }, McpDialog);
1050
+ return popup;
1051
+ });
684
1052
  }
685
1053
 
686
1054
  exports.apply = apply;
687
1055
  exports.inject = inject;
688
1056
  return module.exports;
689
1057
  },
690
- });
1058
+ });
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The `/mcp` dialog's action surface: one dispatcher over the dialog's five requests,
3
+ * so the HTTP seam in `index.js` only reads a body and writes a JSON answer.
4
+ *
5
+ * Every dependency is injected: the dispatcher never imports a host package, which is
6
+ * what lets the whole request matrix run offline against fakes.
7
+ *
8
+ * @module dsh-hiss-plugins/project-mcp/actions
9
+ */
10
+
11
+ /** Read one thrown value as text. */
12
+ function messageOf(error) {
13
+ return error instanceof Error ? error.message : String(error);
14
+ }
15
+
16
+ /** Refuse one request with a code the dialog can branch on. */
17
+ function refusal(code, message) {
18
+ return { ok: false, error: { code, message } };
19
+ }
20
+
21
+ /**
22
+ * Run one dialog request.
23
+ * @param {object} body - the parsed request body.
24
+ * @param {object} deps - the host operations the dispatcher may call (status, setTool,
25
+ * setServer, add, promote). Every method receives the session id first.
26
+ * @returns {Promise<{ ok: true, value: unknown } | { ok: false, error: { code: string, message: string } }>}
27
+ * the answer the dialog reads.
28
+ */
29
+ export async function dispatch(body, deps) {
30
+ const action = body?.action;
31
+ const sessionId = body?.sessionId;
32
+ if (typeof sessionId !== "string" || sessionId === "") return refusal("invalid-request", "sessionId is required");
33
+ if (typeof action !== "string") return refusal("unknown-action", "unknown action \"undefined\"");
34
+ try {
35
+ if (action === "status") return { ok: true, value: await deps.status(sessionId) };
36
+ if (action === "set-tool" || action === "set-server" || action === "set-global-server") {
37
+ if (typeof body.enabled !== "boolean") return refusal("invalid-request", "enabled must be a boolean");
38
+ const field = action === "set-tool" ? "tool" : "server";
39
+ const name = body[field];
40
+ if (typeof name !== "string" || name === "") return refusal("invalid-request", `${field} is required`);
41
+ const value = action === "set-tool"
42
+ ? await deps.setTool(sessionId, name, body.enabled)
43
+ : action === "set-server"
44
+ ? await deps.setServer(sessionId, name, body.enabled)
45
+ : await deps.setGlobalServer(sessionId, name, body.enabled);
46
+ return { ok: true, value };
47
+ }
48
+ if (action === "add-server") {
49
+ if (body.server === null || typeof body.server !== "object") return refusal("invalid-request", "server is required");
50
+ return { ok: true, value: await deps.add(sessionId, body.server) };
51
+ }
52
+ if (action === "promote") {
53
+ if (typeof body.server !== "string" || body.server === "") return refusal("invalid-request", "server is required");
54
+ return { ok: true, value: await deps.promote(sessionId, body.server) };
55
+ }
56
+ return refusal("unknown-action", `unknown action "${action}"`);
57
+ } catch (error) {
58
+ return refusal("failed", messageOf(error));
59
+ }
60
+ }
@@ -1,4 +1,5 @@
1
- import { access, readFile } from "node:fs/promises";
1
+ import { randomUUID } from "node:crypto";
2
+ import { access, chmod, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
2
3
  import { dirname, join, resolve } from "node:path";
3
4
 
4
5
  /**
@@ -156,3 +157,120 @@ export async function loadServers(configPath, cwd) {
156
157
  }
157
158
  return { servers, skipped };
158
159
  }
160
+ /** Names the MCP bridge accepts as a tool namespace. */
161
+ const SERVER_NAME = /^[A-Za-z0-9_-]{1,32}$/;
162
+
163
+ /**
164
+ * Validate one server entry a user typed into the dialog before it reaches any file.
165
+ * @param {string} serverName - the entry key, which becomes the tool namespace.
166
+ * @param {unknown} entry - the raw entry value.
167
+ * @param {string} projectDir - directory holding `.mcp.json`, the stdio default cwd.
168
+ * @returns {void}
169
+ * @throws when the name or the entry could not be used.
170
+ */
171
+ export function validateEntry(serverName, entry, projectDir) {
172
+ if (!SERVER_NAME.test(serverName)) {
173
+ throw new Error(`"${serverName}": name must match ${String(SERVER_NAME)}`);
174
+ }
175
+ toSpec(serverName, entry, projectDir);
176
+ }
177
+
178
+ /**
179
+ * Read one `.mcp.json` as a plain document, so a write can keep every unrelated key.
180
+ * @param {string} configPath - absolute path to the `.mcp.json`.
181
+ * @returns {Promise<Record<string, unknown>>} the parsed object, or `{}` when the file is absent.
182
+ * @throws when the file exists but is not a JSON object.
183
+ */
184
+ export async function readConfig(configPath) {
185
+ let raw;
186
+ try {
187
+ raw = await readFile(configPath, "utf8");
188
+ } catch (error) {
189
+ // Only an absent file reads as empty: a locked or unreadable one must fail
190
+ // the write path instead of being replaced by a document holding one server.
191
+ if (error?.code === "ENOENT") return {};
192
+ throw error;
193
+ }
194
+ let parsed;
195
+ try {
196
+ parsed = JSON.parse(raw);
197
+ } catch (error) {
198
+ throw new Error(`${configPath} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
199
+ }
200
+ if (!isRecord(parsed)) throw new Error(`${configPath} must contain a JSON object`);
201
+ return parsed;
202
+ }
203
+
204
+ /**
205
+ * Write one `.mcp.json` atomically: a rename never leaves a half-written config.
206
+ * @param {string} configPath - absolute path to the `.mcp.json`.
207
+ * @param {Record<string, unknown>} parsed - the document to write.
208
+ * @returns {Promise<void>}
209
+ */
210
+ export async function writeConfig(configPath, parsed) {
211
+ await mkdir(dirname(resolve(configPath)), { recursive: true });
212
+ // A token-bearing .mcp.json must not lose its mode to the rename, and a
213
+ // failed write must not leave a tmp file in the project directory.
214
+ const mode = await stat(configPath).then((info) => info.mode & 0o777, () => undefined);
215
+ const temporary = `${configPath}.${randomUUID()}.tmp`;
216
+ try {
217
+ await writeFile(temporary, `${JSON.stringify(parsed, null, 2)}\n`);
218
+ if (mode !== undefined) await chmod(temporary, mode);
219
+ await rename(temporary, configPath);
220
+ } finally {
221
+ await unlink(temporary).catch(() => {});
222
+ }
223
+ }
224
+ /** Split a dialog argument line into argv, without shell quoting. */
225
+ export function splitArgs(value) {
226
+ if (Array.isArray(value)) return value.filter((entry) => typeof entry === "string");
227
+ return typeof value === "string" ? value.split(/\s+/).filter((entry) => entry !== "") : [];
228
+ }
229
+
230
+ /**
231
+ * A `.mcp.json` entry built from the dialog add form.
232
+ * @param {object} input - the form values.
233
+ * @returns {Record<string, unknown>} the entry to store under `mcpServers`.
234
+ */
235
+ export function entryFromInput(input) {
236
+ if (input.type === "http") {
237
+ return {
238
+ type: "http",
239
+ url: String(input.url ?? ""),
240
+ ...(isRecord(input.headers) ? { headers: input.headers } : {}),
241
+ };
242
+ }
243
+ const args = splitArgs(input.args);
244
+ return {
245
+ type: "stdio",
246
+ command: String(input.command ?? ""),
247
+ ...(args.length === 0 ? {} : { args }),
248
+ ...(isRecord(input.env) ? { env: input.env } : {}),
249
+ };
250
+ }
251
+
252
+ /**
253
+ * The manager-shaped entry one declared server becomes when registered globally.
254
+ * @param {unknown} entry - the `.mcp.json` entry.
255
+ * @param {string} projectDir - directory holding that `.mcp.json`.
256
+ * @returns {Record<string, unknown>} the entry `mcp-manager` accepts.
257
+ */
258
+ export function managerEntry(entry, projectDir) {
259
+ const fields = isRecord(entry) ? entry : {};
260
+ if (fields.type === "http") {
261
+ return {
262
+ transport: "streamable-http",
263
+ url: String(fields.url ?? ""),
264
+ headers: isRecord(fields.headers) ? fields.headers : {},
265
+ enabled: true,
266
+ };
267
+ }
268
+ return {
269
+ transport: "stdio",
270
+ command: String(fields.command ?? ""),
271
+ args: Array.isArray(fields.args) ? fields.args.filter((arg) => typeof arg === "string") : [],
272
+ env: isRecord(fields.env) ? fields.env : {},
273
+ cwd: resolve(projectDir, typeof fields.cwd === "string" ? fields.cwd : "."),
274
+ enabled: true,
275
+ };
276
+ }