A local-first multi-agent app development platform, built on PenguinHarness
/**
* Tools tab's "MCP Server" block: a table of configured servers (name / transport /
* target) with vault-style immediate persistence — Add/Edit happens in a modal whose
* fields follow the chosen transport, deletion sits behind a confirmation. Every
* operation PUTs the whole `mcpServers` list through the config route; the server
* re-validates each entry via the core transport resolver, so a rejected save surfaces
* inside the modal instead of half-applying.
*
* Connectivity testing mirrors the models page: the modal carries a standalone
* "test connection" button in a top action row (a connecting answer pops as a toast with the
* tool count and latency — the models dialog idiom — while a refused probe keeps its sentence
* under that button, see `mcp-test-refusal.ts`), and the section header offers a bulk test that
* probes every configured server sequentially behind a confirm dialog, writing a
* tone-colored badge onto each row as its result lands (the group speed-test idiom).
*
* The permission control mirrors the builtin tool table's, with a third `auto` state: it
* decides which of the server's tool calls stop for approval, and nothing about what the
* remote server is able to do.
*
* Each row carries an on/off switch (`config.enabled`): off keeps the entry and every field
* 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 { Fragment, useState } from "react";
import type { MCPServerConfig } from "@adelie/core/interfaces";
import {
Button,
ConfirmModal,
InfoPopover,
Input,
Modal,
OptionMenu,
Segmented,
SettingsEmpty,
Switch,
Table,
TableBody,
TableCell,
TableHead,
TableHeaderCell,
TableRow,
Textarea,
toastSuccess,
} from "@adelie/ui";
import type { OptionMenuChoice } from "@adelie/ui";
import * as api from "../../api/endpoints";
import type { McpServerTestResponse } from "@adelie/server/api";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { useProject } from "../../state/project";
import {
emptyMcpForm,
enabledOf,
formToServer,
permissionOf,
serverToForm,
transportOf,
type McpFormError,
type McpFormField,
type McpPermissionMode,
type McpServerFormState,
type McpTransportKind,
} from "./mcp-servers-form";
import { flippedEnabled, toggleRefusalFor, type McpToggleRefusal } from "./mcp-servers-toggle";
import { mcpTestRefusal } from "./mcp-test-refusal";
import { toneInk } from "../../lib/tone";
/** Maps a validation error code to its localized message. */
function errorText(err: McpFormError | undefined): string | undefined {
if (!err) return undefined;
switch (err.code) {
case "required":
return S.common.requiredField;
case "name_charset":
return S.agent.mcpNameInvalid;
case "url_invalid":
return S.agent.mcpUrlInvalid;
case "kv_line":
return S.agent.mcpLineInvalid(err.line ?? 1);
case "number":
return S.agent.mcpNumberInvalid;
case "duplicate":
return S.agent.mcpDuplicateName;
}
}
/** Table cell summary: the spawn line for stdio, the URL for http/sse. */
function targetOf(entry: MCPServerConfig): string {
const c = entry.config;
if (typeof c["url"] === "string") return c["url"];
const command = typeof c["command"] === "string" ? c["command"] : "";
const args = Array.isArray(c["args"]) ? c["args"].map((a) => String(a)).join(" ") : "";
return args ? `${command} ${args}` : command;
}
/** One row's bulk-test outcome ("pending" while its turn runs). */
type RowTestResult = McpServerTestResponse | "pending";
/** Row badge for the bulk test (the model card's speed-badge idiom: small, tone-colored, reason on hover). */
function TestBadge({ result }: { result: RowTestResult | undefined }) {
if (result === undefined) return null;
if (result === "pending") {
return (
<span className="text-xs whitespace-nowrap text-gray-400">{S.agent.mcpTestPending}</span>
);
}
if (result.ok) {
return (
<span className={`text-xs font-medium whitespace-nowrap ${toneInk.success}`}>
{S.agent.mcpTestBadge(result.tools?.length ?? 0, result.latencyMs)}
</span>
);
}
return (
<span
data-tooltip={result.error}
data-tooltip-extra
className={`text-xs font-medium whitespace-nowrap ${toneInk.danger}`}
>
{S.agent.mcpTestBadgeFail}
</span>
);
}
/**
* 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,
}: {
agentId: string;
initial: MCPServerConfig[];
}) {
const { currentProject } = useProject();
const projectId = currentProject?.projectId ?? null;
const [servers, setServers] = useState<MCPServerConfig[]>(initial);
const [busy, setBusy] = useState(false);
// Modal state: editIndex null = adding, a number = editing that row; closed when form is null.
const [form, setForm] = useState<McpServerFormState | null>(null);
const [editIndex, setEditIndex] = useState<number | null>(null);
const [fieldErrors, setFieldErrors] = useState<Partial<Record<McpFormField, McpFormError>>>({});
// Server-side rejection (transport validation 400) rendered at the modal's foot.
const [modalError, setModalError] = useState<string | null>(null);
const [deleting, setDeleting] = useState<number | null>(null);
// 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). A probe that connects pops as a toast; one
// that does not leaves its sentence under the button that asked (see `mcp-test-refusal.ts`),
// because a failed probe changes nothing else on the card — without that line the form looks
// exactly as it did before the press. Cleared by every edit to the form (the probe sent exactly
// these values) and at the start of the next probe.
const [testing, setTesting] = useState(false);
const [testRefusal, setTestRefusal] = useState<string | null>(null);
// Bulk test: confirm dialog open / run in progress / per-row results keyed by server name.
const [testAllOpen, setTestAllOpen] = useState(false);
const [testAllRunning, setTestAllRunning] = useState(false);
const [rowResults, setRowResults] = useState<Map<string, RowTestResult>>(new Map());
// http leads (the Add modal's default), stdio second, legacy sse last.
const transportOptions: ReadonlyArray<{ value: McpTransportKind; label: string }> = [
{ value: "http", label: "http" },
{ value: "stdio", label: "stdio" },
{ value: "sse", label: "sse" },
];
const transportHints: Record<McpTransportKind, string> = {
http: S.agent.mcpTransportHttp,
stdio: S.agent.mcpTransportStdio,
sse: S.agent.mcpTransportSse,
};
// auto leads (the default); an explicit level below it overrides every tool's readOnlyHint.
const permissionOptions: ReadonlyArray<OptionMenuChoice<McpPermissionMode>> = [
{
value: "auto",
triggerLabel: S.agent.mcpPermissionAuto,
label: S.agent.mcpPermissionAutoLabel,
description: S.agent.mcpPermissionAutoDescription,
},
{
value: "r",
triggerLabel: "r",
label: S.agent.permissionReadLabel,
description: S.agent.mcpPermissionReadDescription,
},
{
value: "rw",
triggerLabel: "rw",
label: S.agent.permissionReadWriteLabel,
description: S.agent.mcpPermissionReadWriteDescription,
},
];
/** Persist the full list (immediate, vault-style); returns null on success or an error message. */
const persist = async (next: MCPServerConfig[]): Promise<string | null> => {
if (!projectId || !agentId) return S.common.unknownError;
setBusy(true);
try {
const res = await api.putAgentConfig(projectId, agentId, {
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) {
return apiErrorText(e);
} finally {
setBusy(false);
}
};
const openAdd = () => {
setForm(emptyMcpForm());
setEditIndex(null);
setFieldErrors({});
setModalError(null);
setTestRefusal(null);
};
const openEdit = (index: number) => {
const entry = servers[index];
if (!entry) return;
setForm(serverToForm(entry));
setEditIndex(index);
setFieldErrors({});
setModalError(null);
setTestRefusal(null);
};
const closeModal = () => {
setForm(null);
setEditIndex(null);
};
const patchForm = (patch: Partial<McpServerFormState>) => {
setForm((prev) => (prev ? { ...prev, ...patch } : prev));
setFieldErrors({});
setModalError(null);
// The probe sent the whole form, so any edit makes its sentence describe values that are no
// longer on screen.
setTestRefusal(null);
};
/** Probes the current form state (unsaved values on purpose: verify before persisting). */
const testConnection = async () => {
if (!form || !projectId) return;
const built = formToServer(form);
if (!built.ok) {
setFieldErrors(built.errors);
return;
}
// This probe's answer replaces the last one's (see the state's comment).
setTestRefusal(null);
setTesting(true);
try {
const res = await api.testAgentMcpServer(projectId, agentId, built.server);
const refusal = mcpTestRefusal({ result: res });
if (refusal === null) toastSuccess(S.agent.mcpTestOk(res.tools?.length ?? 0, res.latencyMs));
else setTestRefusal(refusal);
} catch (e) {
setTestRefusal(mcpTestRefusal({ result: null, error: e }));
} finally {
setTesting(false);
}
};
/**
* Bulk test (section-level): every configured server through the same probe, strictly
* sequential — parallel probes would spawn every stdio child at once — with each row's
* badge updating as its result lands.
*/
const runTestAll = async () => {
if (!projectId) return;
setTestAllRunning(true);
try {
for (const entry of servers) {
setRowResults((prev) => new Map(prev).set(entry.name, "pending"));
let result: McpServerTestResponse;
try {
result = await api.testAgentMcpServer(projectId, agentId, entry);
} catch (e) {
result = { ok: false, error: apiErrorText(e) };
}
setRowResults((prev) => new Map(prev).set(entry.name, result));
}
} finally {
setTestAllRunning(false);
}
};
const submitModal = async () => {
if (!form) return;
const built = formToServer(form);
if (!built.ok) {
setFieldErrors(built.errors);
return;
}
// Same-name collision against the other rows (the edited row may keep its own name);
// rendered under the name field itself, like every other validation error.
const clash = servers.some((s, i) => i !== editIndex && s.name === built.server.name);
if (clash) {
setFieldErrors({ name: { code: "duplicate" } });
return;
}
const next =
editIndex === null
? [...servers, built.server]
: servers.map((s, i) => (i === editIndex ? built.server : s));
const err = await persist(next);
if (err !== null) {
setModalError(err);
return;
}
closeModal();
};
/** Flips one row's switch and persists it; the whole list is PUT back, like every edit here. */
const toggleEnabled = async (index: number) => {
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 });
};
/**
* The delete row's button: opens the confirmation without the previous attempt's reason —
* that sentence belonged to the attempt before, not to the row this one is about.
*/
const askDelete = (index: number) => {
setDeleting(index);
setDeleteRefusal(null);
};
/**
* Deletes one row through the same whole-list PUT as every other edit here. The confirmation
* closes on the answer, not on the request: a refused write leaves the list exactly as it was
* (nothing was removed, on either side), so the card stays open with the server's words in it
* and the same button retries. Closing it as the request left used to take the reason away —
* it landed in a toast that dismisses itself after six seconds and sits above the card.
*/
const confirmDelete = async () => {
if (deleting === null) return;
const err = await persist(servers.filter((_, i) => i !== deleting));
if (err !== null) {
setDeleteRefusal(err);
return;
}
setDeleting(null);
setDeleteRefusal(null);
};
if (!projectId) return null;
// The form's target field (command / url) — the same gate the models dialog uses for its
// test button (disabled until the identity is filled in).
const targetFilled =
form !== null &&
(form.transport === "stdio" ? form.command.trim() !== "" : form.url.trim() !== "");
const showBadges = rowResults.size > 0;
return (
<div className="space-y-4">
<p className="flex items-center gap-1.5 text-xs font-medium text-gray-500">
{S.agent.mcpServers}
<InfoPopover label={S.agent.mcpServers}>{S.agent.mcpDesc}</InfoPopover>
</p>
{servers.length === 0 ? (
<SettingsEmpty>{S.agent.mcpEmpty}</SettingsEmpty>
) : (
<Table tableClassName="min-w-[520px]">
<TableHead>
<TableHeaderCell>{S.agent.mcpEnabled}</TableHeaderCell>
<TableHeaderCell>{S.agent.mcpName}</TableHeaderCell>
<TableHeaderCell>{S.agent.mcpTransport}</TableHeaderCell>
<TableHeaderCell>{S.agent.mcpPermission}</TableHeaderCell>
<TableHeaderCell>{S.agent.mcpTarget}</TableHeaderCell>
{/* Bulk-test badge column appears only once results exist (no headline). */}
{showBadges && <TableHeaderCell />}
{/* Bulk test lives in the table's own header bar, over the actions column: a
tighter cell than a column name's, so the button does not heighten the bar. */}
<th scope="col" className="px-3 py-1 text-right font-normal whitespace-nowrap">
<Button
size="sm"
variant="ghost"
disabled={busy || testAllRunning}
onClick={() => setTestAllOpen(true)}
>
{testAllRunning ? S.agent.mcpTestPending : S.agent.mcpTest}
</Button>
</th>
</TableHead>
<TableBody>
{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>
)}
<Button size="sm" variant="primary" disabled={busy} onClick={openAdd}>
{S.agent.mcpAdd}
</Button>
<Modal
open={form !== null}
title={editIndex === null ? S.agent.mcpAdd : S.agent.mcpEditTitle}
onClose={closeModal}
footer={
<>
<Button size="sm" onClick={closeModal}>
{S.common.cancel}
</Button>
<Button size="sm" variant="primary" disabled={busy} onClick={() => void submitModal()}>
{S.common.save}
</Button>
</>
}
>
{form && (
<div className="space-y-3">
{/* Transport first, as tab-style switches — the choice decides every field below. */}
<div className="space-y-1">
<Segmented
options={transportOptions}
value={form.transport}
onChange={(v) => patchForm({ transport: v })}
/>
<p className="text-xs text-gray-400 dark:text-gray-500">
{transportHints[form.transport]}
</p>
</div>
{/* Entry-level action right under the tabs — the models dialog idiom: a standalone
test button, enabled once the target (command / url) is filled in; a connecting
answer pops as a toast, a refused one stays below (see `mcp-test-refusal.ts`). */}
<div className="flex flex-wrap items-center gap-2">
<Button
size="sm"
disabled={testing || busy || !targetFilled}
onClick={() => void testConnection()}
>
{testing ? S.agent.mcpTesting : S.agent.mcpTest}
</Button>
</div>
{testRefusal !== null && (
// Under the button that asked, not over the card: `line-clamp-2` keeps a long
// stderr tail from heightening the modal, and the whole sentence is on hover, the
// way every other refusal slot in the app carries its longer form.
<p
role="alert"
data-tooltip={testRefusal}
data-tooltip-content="text"
className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}
>
{testRefusal}
</p>
)}
<Input
size="sm"
label={S.agent.mcpName}
required
hint={S.agent.mcpNameHint}
error={errorText(fieldErrors.name)}
value={form.name}
onChange={(e) => patchForm({ name: e.target.value })}
className="font-mono"
placeholder="filesystem"
autoComplete="off"
/>
{form.transport === "stdio" ? (
<>
<Input
size="sm"
label={S.agent.mcpCommand}
required
error={errorText(fieldErrors.command)}
value={form.command}
onChange={(e) => patchForm({ command: e.target.value })}
className="font-mono"
placeholder="npx"
autoComplete="off"
/>
<Textarea
size="sm"
mono
label={S.agent.mcpArgs}
hint={S.agent.mcpArgsHint}
rows={3}
value={form.argsText}
onChange={(e) => patchForm({ argsText: e.target.value })}
placeholder={"-y\n@modelcontextprotocol/server-filesystem\n."}
/>
<Textarea
size="sm"
mono
label={S.agent.mcpEnv}
hint={S.agent.mcpEnvHint}
error={errorText(fieldErrors.env)}
rows={2}
value={form.envText}
onChange={(e) => patchForm({ envText: e.target.value })}
placeholder="API_TOKEN=..."
/>
<Input
size="sm"
label={S.agent.mcpCwd}
hint={S.agent.mcpCwdHint}
value={form.cwd}
onChange={(e) => patchForm({ cwd: e.target.value })}
className="font-mono"
autoComplete="off"
/>
</>
) : (
<>
<Input
size="sm"
label={S.agent.mcpUrl}
required
error={errorText(fieldErrors.url)}
value={form.url}
onChange={(e) => patchForm({ url: e.target.value })}
className="font-mono"
placeholder="https://example.com/mcp"
autoComplete="off"
/>
<Textarea
size="sm"
mono
label={S.agent.mcpHeaders}
hint={S.agent.mcpHeadersHint}
error={errorText(fieldErrors.headers)}
rows={2}
value={form.headersText}
onChange={(e) => patchForm({ headersText: e.target.value })}
placeholder="Authorization: Bearer ..."
/>
</>
)}
<div className="space-y-1">
<OptionMenu
mono
size="sm"
fullWidth
label={S.agent.mcpPermission}
options={permissionOptions}
value={form.permission}
onChange={(v) => patchForm({ permission: v })}
/>
<p className="text-xs text-gray-400 dark:text-gray-500">
{S.agent.mcpPermissionHint}
</p>
</div>
<div className="grid grid-cols-3 gap-2">
<Input
size="sm"
label={S.agent.mcpConnectTimeout}
error={errorText(fieldErrors.connectTimeoutMs)}
value={form.connectTimeoutMs}
inputMode="numeric"
onChange={(e) => patchForm({ connectTimeoutMs: e.target.value })}
className="font-mono"
autoComplete="off"
/>
<Input
size="sm"
label={S.agent.toolTimeout}
error={errorText(fieldErrors.timeoutMs)}
value={form.timeoutMs}
inputMode="numeric"
onChange={(e) => patchForm({ timeoutMs: e.target.value })}
className="font-mono"
autoComplete="off"
/>
<Input
size="sm"
label={S.agent.toolMaxOutput}
error={errorText(fieldErrors.maxOutputLength)}
value={form.maxOutputLength}
inputMode="numeric"
onChange={(e) => patchForm({ maxOutputLength: e.target.value })}
className="font-mono"
autoComplete="off"
/>
</div>
<p className="text-xs text-gray-400 dark:text-gray-500">{S.agent.mcpBudgetsHint}</p>
{modalError && <p className="text-xs text-red-600 dark:text-red-400">{modalError}</p>}
</div>
)}
</Modal>
{/* Bulk-test confirm (the group speed-test idiom): explain what will run, then go. */}
<Modal
open={testAllOpen}
title={S.agent.mcpTest}
onClose={() => setTestAllOpen(false)}
footer={
<>
<Button size="sm" onClick={() => setTestAllOpen(false)}>
{S.common.cancel}
</Button>
<Button
size="sm"
variant="primary"
onClick={() => {
setTestAllOpen(false);
void runTestAll();
}}
>
{S.agent.mcpTestAllStart}
</Button>
</>
}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{S.agent.mcpTestAllConfirm(servers.length)}
</p>
</Modal>
<ConfirmModal
open={deleting !== null}
title={S.agent.mcpDeleteTitle}
busy={busy}
onClose={() => setDeleting(null)}
onConfirm={() => void confirmDelete()}
confirmLabel={S.common.confirm}
cancelLabel={S.common.cancel}
refusal={deleteRefusal === null ? undefined : S.common.refused(deleteRefusal)}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{deleting !== null ? S.agent.mcpDeleteConfirm(servers[deleting]?.name ?? "") : ""}
</p>
</ConfirmModal>
</div>
);
}