Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): MCP Server 表的开关被拒时,原因留在那一行下面

lmlihengcc88b3d506a3
diff --git a/changelog/unreleased/2026-11-01-mcp-toggle-refusal.md b/changelog/unreleased/2026-11-01-mcp-toggle-refusal.md
new file mode 100644
index 00000000..16f3b5cb
--- /dev/null
+++ b/changelog/unreleased/2026-11-01-mcp-toggle-refusal.md
@@ -0,0 +1,53 @@
+# A refused MCP Server switch says why under that row, not in a toast that expires
+
+- **Date:** 2026-11-01
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-11-01-mcp-toggle-refusal.zh.md)
+
+The Tools tab's MCP Server table has an on/off switch per row (`config.enabled`): off keeps the
+entry and every field of it but stops the server connecting, which is how a plugin's bridge gets
+parked without being deleted. That switch writes nothing optimistically — it sends the whole
+`mcpServers` list through the one config PUT every edit here uses, and the rows keep the state the
+server has until that write lands. So a **refused** flip left the table exactly as it was, with the
+reason only in a toast that dismissed itself after six seconds: a switch that did not move and, six
+seconds later, nothing at all saying why.
+
+That sentence now stays under the row that asked, in a band of its own spanning the table's
+columns: the shared lead-in `S.common.refused`, the danger ink, `role="alert"`, clamped to two lines
+with the whole text on hover. It stays until the next flip (it is that attempt's answer, not the
+row's standing state) or until any write in this block lands — the rows are identified by their
+position in the list, and a landed write may have moved them. No new copy was written.
+
+## Details
+
+- `packages/web/src/features/agents/mcp-servers-toggle.ts` (new): `flippedEnabled()` — the list one
+ flip produces, with the rule it already had (turning a server off stores `false`, turning it back
+ on drops the key so the entry keeps following the default) — and `toggleRefusalFor()`, which row
+ may draw the sentence. The row is identified by position, not by name: the Add/Edit modal refuses
+ a duplicate name, but a hand-edited config may carry two entries of the same name, and a sentence
+ keyed by name would be drawn twice.
+- `packages/web/src/features/agents/mcp-servers-section.tsx`: a `toggleRefusal` state filled from
+ the failed PUT (via `apiErrorText`) instead of `toastError`, cleared at the start of the next flip
+ and by every write that lands; the sentence is drawn in a full-width row under its own. A
+ successful flip still says so with its toast and still reloads the rows.
+
+## Tests
+
+- `packages/web/test/mcp-servers-toggle.test.ts` (new, 8 unit cases): a flip changes exactly one
+ entry (and not the input list), off stores `false`, back on drops the key, an index that is no
+ longer there changes nothing, and only the refused row's position draws the sentence — including
+ the duplicated-name case that names cannot answer.
+- `packages/web/e2e/mcp-toggle-refusal.spec.mjs` (new, two browser cases against the real server):
+ a refused flip leaves the reason in the band under that row and nowhere else, the notification
+ region without a dismissible toast, the switch and the server's list where the server has them,
+ and the line still there seven seconds later; then, with the refusal lifted, the same switch
+ lands — the line goes, the switch turns off, the neighbour's config is untouched, and flipping it
+ back on sends the entry without an `enabled` key at all.
+
+## Compatibility
+
+- No API, on-disk or request-shape change: the PUT body is exactly the list this block built
+ before. Only the failed path stopped using a toast.
diff --git a/changelog/unreleased/2026-11-01-mcp-toggle-refusal.zh.md b/changelog/unreleased/2026-11-01-mcp-toggle-refusal.zh.md
new file mode 100644
index 00000000..17626701
--- /dev/null
+++ b/changelog/unreleased/2026-11-01-mcp-toggle-refusal.zh.md
@@ -0,0 +1,43 @@
+# MCP Server 的开关被拒时,原因留在那一行下面,不再只活六秒
+
+- **日期:** 2026-11-01
+- **类型:** fix
+- **范围:** `web`
+- **破坏性:** 无
+
+[English](2026-11-01-mcp-toggle-refusal.md)
+
+工具 tab 的 MCP Server 表每行有一个开关(`config.enabled`):关掉时条目与它的每个字段都保留,
+只是这个 Server 不再连接 —— 插件带的桥(比如 WPS 那个)就这样停在那儿,不必删掉再加回来。
+这个开关同样不做乐观写入:它把整份 `mcpServers` 列表经这块里唯一那个配置 PUT 发回去,写入
+落地之前行里显示的一直是服务端记着的状态。所以**被拒**时这张表此前什么都不会变,原因只剩一条
+六秒后自己消失的 toast:一颗没动过的开关,以及一句已经看不见的解释。
+
+现在这句话留在发起它的那一行下面 —— 一条横跨表格各列的提示带:共享引子 `S.common.refused`、
+danger 色、`role="alert"`、限两行、整句挂悬停。它留到下一次翻转(那是那一次点击的答复,不是
+这一行的长期状态),或留到这块里任意一次写入落地为止 —— 行是按它在列表里的位置认的,而落地的
+写入可能已经把它们挪过。没有新增文案。
+
+## 细节
+
+- `packages/web/src/features/agents/mcp-servers-toggle.ts`(新):`flippedEnabled()` —— 一次翻转
+ 产出的列表,沿用原来的规则(关掉写 `false`,重新打开则删掉这个键,让条目继续跟随默认值)——
+ 以及 `toggleRefusalFor()`,决定哪一行可以画这句话。行按位置认、不按名字:Add/Edit 弹窗会拒绝
+ 重名,但手改过的配置里可能有两个同名条目,按名字画的句子会画两遍。
+- `packages/web/src/features/agents/mcp-servers-section.tsx`:多一个 `toggleRefusal` 状态,由失败的
+ PUT 经 `apiErrorText` 填上(不再走 `toastError`),下一次翻转开始时清空、任意一次写入落地时也
+ 清空;句子画在它自己那一行下面、横跨整张表。成功的翻转照旧弹一条提示并重新拉取行。
+
+## 测试
+
+- `packages/web/test/mcp-servers-toggle.test.ts`(新,8 条单测):一次翻转只改一个条目(也不改传入
+ 的列表本身)、关掉写 `false`、重新打开删掉键、位置已经不存在时什么都不改,并且只有被拒那一个
+ 位置会画这句话 —— 包括「同名两条」这个按名字回答不了的情形。
+- `packages/web/e2e/mcp-toggle-refusal.spec.mjs`(新,真服务端两条):被拒的翻转把原因留在那一行
+ 下面的提示带里、别处没有,通知区里没有可点的 toast,开关与服务端的列表都还停在原处,并且 toast
+ 该消失的七秒之后那一行还在;随后放开拒绝,同一颗开关真的落地 —— 那句话消失、开关变成关、旁边
+ 那一行的配置一字未动,再把它打开时发出去的条目里根本没有 `enabled` 这个键。
+
+## 兼容
+
+- 接口、磁盘格式、请求体都没变:PUT 的正文仍是这块原本拼的那份列表。只有失败那条路不再用 toast。
diff --git a/packages/web/e2e/mcp-toggle-refusal.spec.mjs b/packages/web/e2e/mcp-toggle-refusal.spec.mjs
new file mode 100644
index 00000000..d1b029a7
--- /dev/null
+++ b/packages/web/e2e/mcp-toggle-refusal.spec.mjs
@@ -0,0 +1,185 @@
+/**
+ * Regression: the MCP Server row's on/off switch says why a flip did not settle — in a band under
+ * the row that asked — instead of leaving the table untouched with the reason in a toast that
+ * dismissed itself after six seconds.
+ *
+ * The switch writes nothing optimistically: it sends the whole `mcpServers` list through the one
+ * config PUT every edit in this block uses, and the rows keep the state the server has until that
+ * write lands. So a refused flip used to leave the table exactly as it was — the switch did not
+ * move — and six seconds later nothing on screen said why.
+ *
+ * The refusal is injected where the page's own write is: `page.route` answers the config PUT with
+ * the server's words instead of forwarding it, so the reason proved to be on screen is the one the
+ * failed request carried. The rows are seeded through the API; an entry is not connected until a
+ * Session starts, so a plain http entry is enough.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const P = "password123";
+const AGENT = "default_agent";
+
+/** The row under test, and its neighbour (which must stay quiet). */
+const NAME = "probe-mcp";
+const QUIET = "quiet-mcp";
+
+/** The refused save: a 500 the app has no code for, so its own message reaches the screen. */
+const REFUSAL = { code: "agent_config_read_only", message: "agent config is read-only" };
+/** The line the row draws: the shared lead-in plus the server's words. */
+const REFUSED_LINE = `操作被拒绝:${REFUSAL.message}`;
+
+/**
+ * Provision the user, give the Project a model (the onboarding overlay covers the page without
+ * one), and put two MCP servers on the Agent. The `PUT` replaces the whole list, so a rerun of
+ * this file alone shares one data root with earlier runs without accumulating probe rows.
+ */
+async function projectWithServers(page, user, servers) {
+ await provisionAndLogin(page.request, user, P);
+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const models = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(models.ok(), "put models").toBeTruthy();
+
+ const seeded = await putServers(page, projectId, servers);
+ expect(seeded.ok(), "seed the MCP servers").toBeTruthy();
+
+ /** The Agent's list as the server holds it: what the page reads and writes back. */
+ const listed = async () => (await readConfig(page, projectId)).config?.mcpServers ?? [];
+ return { projectId, listed };
+}
+
+/** The config write the page makes for every MCP edit (whole list, vault-style). */
+const putServers = (page, projectId, mcpServers) =>
+ page.request.put(`${BASE}/api/projects/${projectId}/agents/${AGENT}/config`, {
+ data: { config: { mcpServers } },
+ });
+
+const readConfig = async (page, projectId) =>
+ (await page.request.get(`${BASE}/api/projects/${projectId}/agents/${AGENT}/config`)).json();
+
+/**
+ * Take over the config write: every PUT is kept in `state.seen`, and while `state.refuse` is set
+ * it is answered with the server's refusal instead of reaching the real route.
+ */
+async function interceptConfigPut(page, state) {
+ await page.route("**/api/projects/*/agents/*/config", async (route) => {
+ if (route.request().method() !== "PUT") return route.fallback();
+ state.seen.push(route.request().postDataJSON());
+ if (!state.refuse) return route.fallback();
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: REFUSAL }),
+ });
+ });
+}
+
+/** One row of the Tools tab's MCP table, by its server name. */
+const row = (page, name) => page.getByRole("row", { name: new RegExp(name) });
+
+/** That row's switch — labelled `<server> enabled`, the same label the table's column uses. */
+const switchOf = (page, name) => row(page, name).getByRole("switch", { name: `${name} enabled` });
+
+/**
+ * The band under one row: the table's next `<tr>` after that row. A refused flip's sentence is
+ * drawn there rather than inside a cell — the switch's own cell is one control wide, and a long
+ * server sentence in it would squeeze the columns beside it (the name column would wrap on every
+ * row, including rows that were never written to).
+ */
+const refusalBand = (page, name) => row(page, name).locator("xpath=following-sibling::tr[1]");
+
+/** The notification region: a refusal must not be announced there (that is the old toast). */
+const notifications = (page) => page.getByRole("region", { name: "通知" });
+
+const seed = () => [
+ { name: NAME, config: { url: "https://example.com/mcp" } },
+ { name: QUIET, config: { url: "https://quiet.example.com/mcp" } },
+];
+
+test("a refused flip keeps the reason under that row, and only that row", async ({
+ page,
+}) => {
+ const { listed } = await projectWithServers(page, "r171refuse", seed());
+ const before = await listed();
+
+ const state = { seen: [], refuse: true };
+ await interceptConfigPut(page, state);
+
+ await page.goto(`/agents/${AGENT}?tab=tools`);
+ await expect(switchOf(page, NAME)).toBeVisible();
+ await expect(switchOf(page, NAME)).toBeChecked();
+
+ await switchOf(page, NAME).click();
+
+ // The reason is under the row that asked, and it is not a toast: the notification region holds
+ // no dismissible button, the neighbouring row has no band under it, and the table draws this
+ // sentence exactly once.
+ await expect(refusalBand(page, NAME).getByRole("alert")).toHaveText(REFUSED_LINE);
+ await expect(refusalBand(page, QUIET).getByRole("alert")).toHaveCount(0);
+ await expect(page.getByRole("table").last().getByRole("alert")).toHaveCount(1);
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(state.seen).toHaveLength(1);
+
+ // The switch did not move, because the server did not move: it is still on there.
+ await expect(switchOf(page, NAME)).toBeChecked();
+ expect(await listed()).toEqual(before);
+
+ // Six seconds is how long a toast lives; this line has to still be there after it.
+ await page.waitForTimeout(7_000);
+ await expect(refusalBand(page, NAME).getByRole("alert")).toHaveText(REFUSED_LINE);
+});
+
+test("the retry after a refused flip lands, clears the line, and turning it back on drops the key", async ({
+ page,
+}) => {
+ const { listed } = await projectWithServers(page, "r171retry", seed());
+
+ const state = { seen: [], refuse: true };
+ await interceptConfigPut(page, state);
+
+ await page.goto(`/agents/${AGENT}?tab=tools`);
+ await expect(switchOf(page, NAME)).toBeVisible();
+
+ await switchOf(page, NAME).click();
+ await expect(refusalBand(page, NAME).getByRole("alert")).toHaveText(REFUSED_LINE);
+
+ // Same switch, second click: this time the write lands, so the sentence goes and the switch
+ // moves to the position the server now has.
+ state.refuse = false;
+ await switchOf(page, NAME).click();
+ await expect(refusalBand(page, NAME).getByRole("alert")).toHaveCount(0);
+ await expect(switchOf(page, NAME)).not.toBeChecked();
+ expect(state.seen).toHaveLength(2);
+ // The write says `false` on that row and leaves the other one exactly as it was.
+ const off = state.seen[1].config.mcpServers;
+ expect(off.find((s) => s.name === NAME)?.config.enabled).toBe(false);
+ expect(off.find((s) => s.name === QUIET)?.config).toEqual({
+ url: "https://quiet.example.com/mcp",
+ });
+ expect((await listed()).find((s) => s.name === NAME)?.config.enabled).toBe(false);
+
+ // And back on: the entry drops the key rather than storing `true`, so it keeps following the
+ // default — the same normalization the form does.
+ await switchOf(page, NAME).click();
+ await expect(switchOf(page, NAME)).toBeChecked();
+ expect(state.seen).toHaveLength(3);
+ const on = state.seen[2].config.mcpServers.find((s) => s.name === NAME)?.config;
+ expect(on).toBeDefined();
+ expect("enabled" in on).toBe(false);
+ expect((await listed()).find((s) => s.name === NAME)?.config.enabled).toBeUndefined();
+});
diff --git a/packages/web/src/features/agents/mcp-servers-section.tsx b/packages/web/src/features/agents/mcp-servers-section.tsx
index 2f41f38b..0ff0aa3e 100644
--- a/packages/web/src/features/agents/mcp-servers-section.tsx
+++ b/packages/web/src/features/agents/mcp-servers-section.tsx
@@ -20,8 +20,13 @@
* of it, but the server is not connected in any turn, so its `mcp__*` tools leave the tool
* list. That is the way to park a plugin's bridge (the WPS add-on, say) without deleting it
* and having to re-add it later; the row dims while it is off.
+ *
+ * That switch writes nothing optimistically either — it sends the list, and the row keeps what
+ * the server has until the write lands — so a refused flip draws the server's words under the
+ * switch that asked, instead of in a toast that dismissed itself six seconds later. Which row
+ * draws it is `toggleRefusalFor`'s question (see `mcp-servers-toggle.ts`).
*/
-import { useState } from "react";
+import { Fragment, useState } from "react";
import type { MCPServerConfig } from "@adelie/core/interfaces";
import {
Button,
@@ -62,6 +67,7 @@ import {
type McpServerFormState,
type McpTransportKind,
} from "./mcp-servers-form";
+import { flippedEnabled, toggleRefusalFor, type McpToggleRefusal } from "./mcp-servers-toggle";
import { toneInk } from "../../lib/tone";
/** Maps a validation error code to its localized message. */
@@ -121,6 +127,27 @@ function TestBadge({ result }: { result: RowTestResult | undefined }) {
);
}
+/**
+ * The sentence under a row whose switch flip the server refused — `null` for every other row, and
+ * for a flip that has not been refused (the host picks the row with `toggleRefusalFor`).
+ *
+ * `line-clamp-2` keeps a long server sentence from heightening the band; the whole text is on
+ * hover, the way the list rows and the other switches in the app carry theirs.
+ */
+function ToggleRefusal({ refusal }: { refusal: string | null }) {
+ if (refusal === null) return null;
+ return (
+ <p
+ role="alert"
+ data-tooltip={S.common.refused(refusal)}
+ data-tooltip-content="text"
+ className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}
+ >
+ {S.common.refused(refusal)}
+ </p>
+ );
+}
+
export function McpServersSection({
agentId,
initial,
@@ -143,6 +170,12 @@ export function McpServersSection({
// The words for a delete the server refused, drawn inside the confirmation that asked for it
// (see confirmDelete): retrying is the next thing the person does, and the button is in there.
const [deleteRefusal, setDeleteRefusal] = useState<string | null>(null);
+ // The server's words for a flip of a row's switch it refused, drawn under that switch: the
+ // switch keeps the state the server has, so without this line a refused flip leaves nothing at
+ // all on screen once its toast is gone. Cleared at the start of every flip (it is that attempt's
+ // answer, not the row's standing state) and by every write that lands — the list those rows are
+ // taken from may have moved, and the sentence names a position in it.
+ const [toggleRefusal, setToggleRefusal] = useState<McpToggleRefusal | null>(null);
// Connectivity probe: runs the current form state through POST /config/mcp-test
// (server-side connect + discovery, nothing saved); the result pops as a toast.
const [testing, setTesting] = useState(false);
@@ -193,6 +226,9 @@ export function McpServersSection({
config: { mcpServers: next },
});
setServers(res.config.mcpServers);
+ // The rows just moved to what the server holds; a sentence about a position in the old list
+ // would point at whatever slid into it (see the state's comment).
+ setToggleRefusal(null);
toastSuccess(S.agent.savedTakesEffect);
return null;
} catch (e) {
@@ -301,21 +337,11 @@ export function McpServersSection({
/** Flips one row's switch and persists it; the whole list is PUT back, like every edit here. */
const toggleEnabled = async (index: number) => {
- const entry = servers[index];
- if (!entry) return;
- const next = servers.map((s, i) => {
- if (i !== index) return s;
- if (!enabledOf(s)) {
- // Back on: drop the key rather than store `true`, so the entry keeps following the
- // default (core reads an absent `enabled` as on — same normalization as the form).
- const config = { ...s.config };
- delete config["enabled"];
- return { name: s.name, config };
- }
- return { name: s.name, config: { ...s.config, enabled: false } };
- });
- const err = await persist(next);
- if (err !== null) toastError(err);
+ if (!servers[index]) return;
+ // This flip's answer replaces the last one's (see the state's comment).
+ setToggleRefusal(null);
+ const err = await persist(flippedEnabled(servers, index));
+ if (err !== null) setToggleRefusal({ index, text: err });
};
/**
@@ -387,57 +413,80 @@ export function McpServersSection({
</th>
</TableHead>
<TableBody>
- {servers.map((entry, index) => (
- <TableRow key={entry.name}>
- <TableCell>
- <Switch
- checked={enabledOf(entry)}
- disabled={busy}
- onChange={() => void toggleEnabled(index)}
- title={enabledOf(entry) ? S.agent.mcpDisableHint : S.agent.mcpEnableHint}
- aria-label={`${entry.name} ${S.agent.mcpEnabled}`}
- />
- </TableCell>
- <TableCell
- className={`font-mono text-xs ${enabledOf(entry) ? "" : "text-gray-400 dark:text-gray-500"}`}
- >
- {entry.name}
- </TableCell>
- <TableCell className="font-mono text-xs text-gray-500 dark:text-gray-400">
- {transportOf(entry)}
- </TableCell>
- <TableCell className="font-mono text-xs text-gray-500 dark:text-gray-400">
- {permissionOf(entry)}
- </TableCell>
- <TableCell
- className={`max-w-[360px] truncate font-mono text-xs ${
- enabledOf(entry)
- ? "text-gray-500 dark:text-gray-400"
- : "text-gray-400 dark:text-gray-500"
- }`}
- >
- {targetOf(entry)}
- </TableCell>
- {showBadges && (
- <TableCell align="right">
- <TestBadge result={rowResults.get(entry.name)} />
- </TableCell>
- )}
- <TableCell align="right" nowrap>
- <Button size="sm" variant="ghost" disabled={busy} onClick={() => openEdit(index)}>
- {S.common.edit}
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={busy}
- onClick={() => askDelete(index)}
- >
- {S.agent.mcpRemove}
- </Button>
- </TableCell>
- </TableRow>
- ))}
+ {servers.map((entry, index) => {
+ // A refused flip's sentence goes in a band of its own under that row: the switch's
+ // own cell is one control wide, and a long server sentence inside it would squeeze
+ // the columns beside it — the name column would wrap on every row, including rows
+ // that were never written to.
+ const refusal = toggleRefusalFor(toggleRefusal, index);
+ return (
+ <Fragment key={index}>
+ <TableRow>
+ <TableCell>
+ <Switch
+ checked={enabledOf(entry)}
+ disabled={busy}
+ onChange={() => void toggleEnabled(index)}
+ title={enabledOf(entry) ? S.agent.mcpDisableHint : S.agent.mcpEnableHint}
+ aria-label={`${entry.name} ${S.agent.mcpEnabled}`}
+ />
+ </TableCell>
+ <TableCell
+ className={`font-mono text-xs ${enabledOf(entry) ? "" : "text-gray-400 dark:text-gray-500"}`}
+ >
+ {entry.name}
+ </TableCell>
+ <TableCell className="font-mono text-xs text-gray-500 dark:text-gray-400">
+ {transportOf(entry)}
+ </TableCell>
+ <TableCell className="font-mono text-xs text-gray-500 dark:text-gray-400">
+ {permissionOf(entry)}
+ </TableCell>
+ <TableCell
+ className={`max-w-[360px] truncate font-mono text-xs ${
+ enabledOf(entry)
+ ? "text-gray-500 dark:text-gray-400"
+ : "text-gray-400 dark:text-gray-500"
+ }`}
+ >
+ {targetOf(entry)}
+ </TableCell>
+ {showBadges && (
+ <TableCell align="right">
+ <TestBadge result={rowResults.get(entry.name)} />
+ </TableCell>
+ )}
+ <TableCell align="right" nowrap>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={busy}
+ onClick={() => openEdit(index)}
+ >
+ {S.common.edit}
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={busy}
+ onClick={() => askDelete(index)}
+ >
+ {S.agent.mcpRemove}
+ </Button>
+ </TableCell>
+ </TableRow>
+ {refusal !== null && (
+ <TableRow>
+ {/* span every column of this table: the refusal belongs to the row, not to
+ a column of it */}
+ <TableCell colSpan={showBadges ? 7 : 6} className="pt-0">
+ <ToggleRefusal refusal={refusal} />
+ </TableCell>
+ </TableRow>
+ )}
+ </Fragment>
+ );
+ })}
</TableBody>
</Table>
)}
diff --git a/packages/web/src/features/agents/mcp-servers-toggle.ts b/packages/web/src/features/agents/mcp-servers-toggle.ts
new file mode 100644
index 00000000..ea343670
--- /dev/null
+++ b/packages/web/src/features/agents/mcp-servers-toggle.ts
@@ -0,0 +1,59 @@
+/**
+ * The MCP Server row's on/off switch: the list a flip produces, and which row draws the sentence
+ * when the write it sent is refused.
+ *
+ * The switch writes nothing optimistically — it sends the whole `mcpServers` list back through the
+ * one config PUT every edit here uses, and the rows keep the state the server has until that write
+ * lands. So a refused flip left the table exactly as it was, with the reason in a toast that
+ * dismissed itself after six seconds: a switch that did not move and, six seconds later, nothing
+ * saying why. That sentence now stays under the switch that asked, until the next flip or the next
+ * write that lands (see `mcp-servers-section.tsx`).
+ *
+ * Which row may draw it is decided here, because that question has a trap worth writing down: a
+ * server is *named*, but names are not guaranteed unique — the Add/Edit modal refuses a duplicate,
+ * while a hand-edited `system_config.yaml` may carry two entries of the same name (core warns and
+ * skips what it cannot resolve, it does not dedupe). A sentence keyed by name would then appear
+ * under both rows, and the one that was never written to would read as a failure of its own. The
+ * row is therefore identified by its position in the list the page is showing — the row whose
+ * switch was flipped, which the refused write leaves exactly where it was.
+ */
+import type { MCPServerConfig } from "@adelie/core/interfaces";
+import { enabledOf } from "./mcp-servers-form";
+
+/** The flip the server refused, named by the position of the row it was about, with the server's words (`apiErrorText`). */
+export interface McpToggleRefusal {
+ index: number;
+ text: string;
+}
+
+/**
+ * The line one row draws: the refused flip's own sentence, and nothing on any other row — the
+ * other rows were never written to, and their switches did not move either.
+ */
+export function toggleRefusalFor(refusal: McpToggleRefusal | null, index: number): string | null {
+ if (refusal === null) return null;
+ return refusal.index === index ? refusal.text : null;
+}
+
+/**
+ * The whole list as one row's switch flips it: that entry only, every other entry returned as it
+ * came in (same object, so nothing downstream sees a needless change).
+ *
+ * Turning a server *on* drops the key instead of storing `true`, so the entry keeps following the
+ * default — core reads an absent `enabled` as on, the same normalization the form does. Turning it
+ * off stores `false`, which is the only value that reads as off.
+ */
+export function flippedEnabled(
+ servers: readonly MCPServerConfig[],
+ index: number,
+): MCPServerConfig[] {
+ return servers.map((s, i) => {
+ if (i !== index) return s;
+ if (!enabledOf(s)) {
+ const config = { ...s.config };
+ delete config["enabled"];
+ return { name: s.name, config };
+ }
+ return { name: s.name, config: { ...s.config, enabled: false } };
+ });
+}
diff --git a/packages/web/test/mcp-servers-toggle.test.ts b/packages/web/test/mcp-servers-toggle.test.ts
new file mode 100644
index 00000000..cee89f42
--- /dev/null
+++ b/packages/web/test/mcp-servers-toggle.test.ts
@@ -0,0 +1,90 @@
+/**
+ * The MCP Server row's switch (src/features/agents/mcp-servers-toggle.ts): the list one flip
+ * produces, and which row draws the sentence when the write it sent is refused.
+ *
+ * The switch keeps the state the server has — nothing is written optimistically — so these are
+ * the two halves of what the person sees after a refused flip: the list must come back untouched,
+ * and only the row that asked may carry the reason.
+ */
+import { describe, expect, it } from "vitest";
+import type { MCPServerConfig } from "@adelie/core/interfaces";
+import {
+ flippedEnabled,
+ toggleRefusalFor,
+ type McpToggleRefusal,
+} from "../src/features/agents/mcp-servers-toggle";
+
+const list = (): MCPServerConfig[] => [
+ { name: "filesystem", config: { command: "npx", args: ["-y", "pkg"], enabled: false } },
+ { name: "wps", config: { url: "https://example.com/mcp", permission: "r" } },
+];
+
+describe("flippedEnabled", () => {
+ it("turns a server off by storing false, and keeps its other fields", () => {
+ const next = flippedEnabled(list(), 1);
+ expect(next[1]).toEqual({
+ name: "wps",
+ config: { url: "https://example.com/mcp", permission: "r", enabled: false },
+ });
+ });
+
+ it("turns a server back on by dropping the key, so it keeps following the default", () => {
+ const next = flippedEnabled(list(), 0);
+ // Not `enabled: true`: an absent key is what core (and the form) read as on.
+ expect(next[0]).toEqual({
+ name: "filesystem",
+ config: { command: "npx", args: ["-y", "pkg"] },
+ });
+ expect(next[0] && "enabled" in next[0].config).toBe(false);
+ });
+
+ it("leaves every other entry exactly as it came in", () => {
+ const before = list();
+ const next = flippedEnabled(before, 1);
+ expect(next[0]).toBe(before[0]);
+ // And the input list itself is untouched: the same object is read again by the next flip.
+ expect(before[1]).toEqual({
+ name: "wps",
+ config: { url: "https://example.com/mcp", permission: "r" },
+ });
+ });
+
+ it("changes nothing when the row is no longer there", () => {
+ const before = list();
+ const next = flippedEnabled(before, 2);
+ expect(next).toHaveLength(2);
+ expect(next[0]).toBe(before[0]);
+ expect(next[1]).toBe(before[1]);
+ });
+});
+
+describe("toggleRefusalFor", () => {
+ const refused: McpToggleRefusal = { index: 1, text: "配置是只读的。" };
+
+ it("draws nothing while no flip has been refused", () => {
+ expect(toggleRefusalFor(null, 0)).toBeNull();
+ expect(toggleRefusalFor(null, 1)).toBeNull();
+ });
+
+ it("draws the sentence on the row whose switch asked", () => {
+ expect(toggleRefusalFor(refused, 1)).toBe("配置是只读的。");
+ });
+
+ it("keeps quiet on the other rows — they were never written to", () => {
+ expect(toggleRefusalFor(refused, 0)).toBeNull();
+ expect(toggleRefusalFor(refused, 2)).toBeNull();
+ });
+
+ it("keeps quiet on a row that merely shares the refused row's name (a hand-edited config may)", () => {
+ // Names are not guaranteed unique, which is why the row is identified by its position: a
+ // sentence keyed by name would have been drawn twice here.
+ const duplicated: MCPServerConfig[] = [
+ { name: "dup", config: { url: "https://a.example/mcp" } },
+ { name: "dup", config: { url: "https://b.example/mcp" } },
+ ];
+ const next = flippedEnabled(duplicated, 1);
+ expect(next[1]?.config["enabled"]).toBe(false);
+ expect(toggleRefusalFor(refused, 0)).toBeNull();
+ expect(toggleRefusalFor(refused, 1)).toBe("配置是只读的。");
+ });
+});