Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(mcp): improve server configuration and management (#8021)

YYClawd5cd0f30093f
diff --git a/packages/core/workspace/mutations.test.tsx b/packages/core/workspace/mutations.test.tsx
index 2618c88798..e60930c933 100644
--- a/packages/core/workspace/mutations.test.tsx
+++ b/packages/core/workspace/mutations.test.tsx
@@ -2,15 +2,19 @@
* @vitest-environment jsdom
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { act, renderHook } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
import { defaultStorage } from "../platform/storage";
-import type { Workspace } from "../types";
-import { useCreateWorkspace, useDeleteWorkspace } from "./mutations";
-import { workspaceKeys } from "./queries";
+import type { Workspace, WorkspaceMcpServer } from "../types";
+import {
+ useCreateWorkspace,
+ useDeleteWorkspace,
+ useUpdateWorkspaceMcpServer,
+} from "./mutations";
+import { agentMcpServersOptions, workspaceKeys } from "./queries";
import {
isWorkspaceDeletePending,
unmarkWorkspaceDeletePending,
@@ -235,3 +239,119 @@ describe("useDeleteWorkspace", () => {
expect(isWorkspaceDeletePending("ws-2")).toBe(false);
});
});
+
+describe("useUpdateWorkspaceMcpServer", () => {
+ let qc: QueryClient;
+
+ beforeEach(() => {
+ qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ });
+
+ afterEach(() => {
+ qc.clear();
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ {
+ change: "renaming a server",
+ update: { name: "renamed" },
+ expected: { name: "renamed", transport: "http" },
+ },
+ {
+ change: "replacing HTTP configuration with stdio",
+ update: { config: { command: "mcp-server", args: [] } },
+ expected: { name: "original", transport: "stdio" },
+ },
+ ])("refreshes active and invalidates inactive agent assignments after $change", async ({ update, expected }) => {
+ const original: WorkspaceMcpServer = {
+ id: "server-1",
+ workspace_id: "ws-1",
+ name: "original",
+ transport: "http",
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ };
+ let current = original;
+ const updateWorkspaceMcpServer = vi.fn<ApiClient["updateWorkspaceMcpServer"]>()
+ .mockImplementation(async () => {
+ current = { ...original, ...expected };
+ return current;
+ });
+ const listAgentMcpServers = vi.fn<ApiClient["listAgentMcpServers"]>()
+ .mockImplementation(async () => [{ ...current, enabled: true }]);
+ setApiInstance({ updateWorkspaceMcpServer, listAgentMcpServers } as unknown as ApiClient);
+
+ const activeKey = agentMcpServersOptions("agent-1").queryKey;
+ const inactiveKey = agentMcpServersOptions("agent-2").queryKey;
+ qc.setQueryData(workspaceKeys.mcpServers("ws-1"), [original]);
+ qc.setQueryData(activeKey, [{ ...original, enabled: true }]);
+ qc.setQueryData(inactiveKey, [{ ...original, enabled: false }]);
+
+ const { result } = renderHook(() => ({
+ assignment: useQuery(agentMcpServersOptions("agent-1")),
+ updateServer: useUpdateWorkspaceMcpServer("ws-1"),
+ }), { wrapper: createWrapper(qc) });
+
+ // Infinity staleTime reproduces a previously visited agent page whose
+ // assignment otherwise never refreshes when the workspace library changes.
+ expect(result.current.assignment.data).toEqual([{ ...original, enabled: true }]);
+ expect(listAgentMcpServers).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await result.current.updateServer.mutateAsync({ serverId: "server-1", ...update });
+ });
+
+ expect(updateWorkspaceMcpServer).toHaveBeenCalledWith("ws-1", "server-1", update);
+ expect(qc.getQueryState(workspaceKeys.mcpServers("ws-1"))?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(inactiveKey)?.isInvalidated).toBe(true);
+ await waitFor(() => {
+ expect(result.current.assignment.data).toEqual([{ ...original, ...expected, enabled: true }]);
+ });
+ expect(listAgentMcpServers).toHaveBeenCalledWith("agent-1");
+ });
+
+ it("refetches authoritative assignments while preserving a failed update's rejection", async () => {
+ const original: WorkspaceMcpServer = {
+ id: "server-1",
+ workspace_id: "ws-1",
+ name: "original",
+ transport: "http",
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ };
+ const responseLost = new Error("response lost after update committed");
+ const authoritative = [{ ...original, name: "renamed", enabled: false }];
+ const updateWorkspaceMcpServer = vi.fn<ApiClient["updateWorkspaceMcpServer"]>()
+ .mockRejectedValue(responseLost);
+ const listAgentMcpServers = vi.fn<ApiClient["listAgentMcpServers"]>()
+ .mockResolvedValue(authoritative);
+ setApiInstance({ updateWorkspaceMcpServer, listAgentMcpServers } as unknown as ApiClient);
+
+ qc.setQueryData(workspaceKeys.mcpServers("ws-1"), [original]);
+ qc.setQueryData(agentMcpServersOptions("agent-1").queryKey, [
+ { ...original, enabled: true },
+ ]);
+ const { result } = renderHook(() => ({
+ assignment: useQuery(agentMcpServersOptions("agent-1")),
+ updateServer: useUpdateWorkspaceMcpServer("ws-1"),
+ }), { wrapper: createWrapper(qc) });
+
+ expect(listAgentMcpServers).not.toHaveBeenCalled();
+ await act(async () => {
+ await expect(result.current.updateServer.mutateAsync({
+ serverId: "server-1",
+ name: "renamed",
+ })).rejects.toBe(responseLost);
+ });
+
+ expect(qc.getQueryState(workspaceKeys.mcpServers("ws-1"))?.isInvalidated).toBe(true);
+ await waitFor(() => {
+ expect(result.current.assignment.data).toEqual(authoritative);
+ expect(result.current.updateServer.error).toBe(responseLost);
+ });
+ expect(listAgentMcpServers).toHaveBeenCalledWith("agent-1");
+ });
+});
diff --git a/packages/core/workspace/mutations.ts b/packages/core/workspace/mutations.ts
index f8d11f46e5..2eee3e44aa 100644
--- a/packages/core/workspace/mutations.ts
+++ b/packages/core/workspace/mutations.ts
@@ -111,7 +111,12 @@ export function useUpdateWorkspaceMcpServer(wsId: string) {
config?: Record<string, unknown>;
}) => api.updateWorkspaceMcpServer(wsId, serverId, update),
onSettled: () =>
- queryClient.invalidateQueries({ queryKey: workspaceKeys.mcpServers(wsId) }),
+ Promise.all([
+ queryClient.invalidateQueries({ queryKey: workspaceKeys.mcpServers(wsId) }),
+ // Assignments include the library entry's name and transport, so every
+ // agent's cached projection may change when the entry is updated.
+ queryClient.invalidateQueries({ queryKey: ["agents"] }),
+ ]),
});
}
diff --git a/packages/views/agents/components/tabs/mcp-config-model.test.ts b/packages/views/agents/components/tabs/mcp-config-model.test.ts
index ea45b8261b..7d8ab0f17d 100644
--- a/packages/views/agents/components/tabs/mcp-config-model.test.ts
+++ b/packages/views/agents/components/tabs/mcp-config-model.test.ts
@@ -2,11 +2,23 @@
import { describe, expect, it } from "vitest";
import {
listManagedMcpServers,
+ mcpTransportLabel,
removeManagedMcpServer,
upsertManagedMcpServer,
} from "./mcp-config-model";
describe("mcp config compatibility model", () => {
+ it("uses the same user-facing transport names across MCP surfaces", () => {
+ expect(mcpTransportLabel("stdio")).toBe("STDIO");
+ expect(mcpTransportLabel("LOCAL")).toBe("STDIO");
+ expect(mcpTransportLabel("http")).toBe("Streamable HTTP");
+ expect(mcpTransportLabel("remote")).toBe("Streamable HTTP");
+ expect(mcpTransportLabel("streamable-http")).toBe("Streamable HTTP");
+ expect(mcpTransportLabel("sse")).toBe("SSE");
+ expect(mcpTransportLabel(" websocket ")).toBe("websocket");
+ expect(mcpTransportLabel(" ")).toBe("Unknown");
+ });
+
it("reads canonical and historical OpenCode-native containers without duplication", () => {
const servers = listManagedMcpServers({
mcpServers: { shared: { command: "canonical" } },
diff --git a/packages/views/agents/components/tabs/mcp-config-model.ts b/packages/views/agents/components/tabs/mcp-config-model.ts
index 8898c3ba61..1f66008cac 100644
--- a/packages/views/agents/components/tabs/mcp-config-model.ts
+++ b/packages/views/agents/components/tabs/mcp-config-model.ts
@@ -1,3 +1,5 @@
+export { mcpTransportLabel } from "../../../common/mcp-transport";
+
export type McpConfigContainer = "mcpServers" | "mcp";
export type ManagedMcpServer = {
diff --git a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
index ca3a22d3e7..6d65ceae31 100644
--- a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
+++ b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Agent, AgentRuntime } from "@multica/core/types";
@@ -178,26 +178,266 @@ describe("McpConfigTab", () => {
version: 1,
mcpServers: {
fetch: { command: "uvx", args: ["mcp-server-fetch"] },
- docs: { type: "http", url: "https://example.test/mcp" },
+ docs: { type: "http", url: "https://example.test/mcp", enabled: false },
},
},
});
expect(screen.getByText("fetch")).toBeInTheDocument();
expect(screen.getByText("docs")).toBeInTheDocument();
+ expect(
+ within(screen.getByText("docs").closest("li")!).getByText("Off for agent"),
+ ).toBeVisible();
+ expect(screen.getByLabelText("STDIO")).toBeInTheDocument();
+ expect(screen.getByLabelText("Streamable HTTP")).toBeInTheDocument();
+ expect(screen.getByText("STDIO")).toBeVisible();
+ expect(screen.getByText("Streamable HTTP")).toBeVisible();
expect(screen.getByRole("heading", { name: /managed by multica/i })).toBeInTheDocument();
expect(screen.getByRole("heading", { name: /inherited from runtime/i })).toBeInTheDocument();
expect(screen.queryByLabelText(/MCP config JSON editor/i)).not.toBeInTheDocument();
});
+ it("renames a managed server inline without changing its configuration", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({
+ mcp_config: {
+ version: 1,
+ mcpServers: {
+ fetch: { command: "uvx", args: ["mcp-server-fetch"] },
+ },
+ },
+ });
+
+ await user.click(
+ screen.getByRole("button", { name: /rename server fetch/i }),
+ );
+ const input = screen.getByRole("textbox", { name: "Rename server" });
+ await user.clear(input);
+ await user.type(input, "fetch-v2");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+
+ expect(onSave).toHaveBeenCalledWith({
+ mcp_config: {
+ version: 1,
+ mcpServers: {
+ "fetch-v2": { command: "uvx", args: ["mcp-server-fetch"] },
+ },
+ },
+ });
+ });
+
+ it("preserves a refreshed server config when an inline rename is submitted", async () => {
+ const user = userEvent.setup();
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const initialConfig = {
+ version: 1,
+ mcpServers: {
+ fetch: { command: "uvx", args: ["old"] },
+ },
+ };
+ const view = renderTab({ mcp_config: initialConfig }, onSave);
+
+ await user.click(
+ screen.getByRole("button", { name: /rename server fetch/i }),
+ );
+ const input = screen.getByRole("textbox", { name: "Rename server" });
+ await user.clear(input);
+ await user.type(input, "fetch-v2");
+
+ view.rerender(
+ <TestShell>
+ <McpConfigTab
+ agent={{
+ ...baseAgent,
+ mcp_config: {
+ version: 1,
+ mcpServers: {
+ fetch: { command: "uvx", args: ["new"] },
+ },
+ },
+ }}
+ runtime={null}
+ currentUserId="user-1"
+ onSave={onSave}
+ />
+ </TestShell>,
+ );
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+
+ expect(onSave).toHaveBeenCalledWith({
+ mcp_config: {
+ version: 1,
+ mcpServers: {
+ "fetch-v2": { command: "uvx", args: ["new"] },
+ },
+ },
+ });
+ });
+
+ it("rejects a managed rename when refreshed data removed the original server", async () => {
+ const user = userEvent.setup();
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const otherContainer = { fetch: { command: "other-mcp-server" } };
+ const view = renderTab({
+ mcp_config: {
+ mcpServers: { fetch: { command: "uvx" } },
+ mcp: otherContainer,
+ },
+ }, onSave);
+
+ await user.click(screen.getByRole("button", { name: /rename server fetch/i }));
+ const input = screen.getByRole("textbox", { name: "Rename server" });
+ await user.clear(input);
+ await user.type(input, "fetch-v2");
+
+ // Removing the original entry reveals the same name in another supported
+ // container. The draft must not rename this different server or recreate
+ // the deleted entry from its stale snapshot.
+ view.rerender(
+ <TestShell>
+ <McpConfigTab
+ agent={{ ...baseAgent, mcp_config: { mcp: otherContainer } }}
+ runtime={null}
+ currentUserId="user-1"
+ onSave={onSave}
+ />
+ </TestShell>,
+ );
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+
+ expect(screen.getByRole("alert")).toHaveTextContent("Could not rename the MCP server");
+ expect(onSave).not.toHaveBeenCalled();
+ expect(input).toHaveValue("fetch-v2");
+ expect(input).not.toBeDisabled();
+ });
+
+ it("validates every managed rename branch and cancels a no-op", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({
+ mcp_config: {
+ version: 1,
+ mcpServers: {
+ fetch: { command: "uvx" },
+ docs: { url: "https://example.test/mcp" },
+ },
+ },
+ });
+
+ await user.click(
+ screen.getByRole("button", { name: /rename server fetch/i }),
+ );
+ const input = screen.getByRole("textbox", { name: "Rename server" });
+
+ await user.clear(input);
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+ expect(screen.getByText("Enter a server name.")).toBeInTheDocument();
+
+ await user.type(input, "bad name");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+ expect(
+ screen.getByText("Use only letters, numbers, hyphens, and underscores."),
+ ).toBeInTheDocument();
+
+ await user.clear(input);
+ await user.type(input, "docs");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+ expect(
+ screen.getByText("A server with this name already exists."),
+ ).toBeInTheDocument();
+ expect(onSave).not.toHaveBeenCalled();
+
+ await user.clear(input);
+ await user.type(input, "fetch");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+ expect(screen.queryByRole("textbox", { name: "Rename server" })).toBeNull();
+ expect(onSave).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { reason: "an API error", error: new Error("Rename failed"), message: "Rename failed" },
+ { reason: "an empty error", error: new Error(""), message: "Could not rename the MCP server" },
+ { reason: "a non-Error rejection", error: null, message: "Could not rename the MCP server" },
+ ])("keeps a managed server rename open after $reason", async ({ error, message }) => {
+ const user = userEvent.setup();
+ const onSave = vi.fn().mockRejectedValueOnce(error);
+ renderTab(
+ {
+ mcp_config: {
+ version: 1,
+ mcpServers: {
+ fetch: { command: "uvx", args: ["mcp-server-fetch"] },
+ },
+ },
+ },
+ onSave,
+ );
+
+ await user.click(
+ screen.getByRole("button", { name: /rename server fetch/i }),
+ );
+ const input = screen.getByRole("textbox", { name: "Rename server" });
+ await user.clear(input);
+ await user.type(input, "fetch-v2");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(message);
+ expect(input).toHaveValue("fetch-v2");
+ expect(input).not.toBeDisabled();
+ });
+
+ it("blocks competing managed actions while an inline rename is pending", async () => {
+ const user = userEvent.setup();
+ let finishRename!: () => void;
+ const onSave = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishRename = resolve;
+ }),
+ );
+ renderTab(
+ {
+ mcp_config: {
+ version: 1,
+ mcpServers: {
+ fetch: { command: "uvx" },
+ docs: { url: "https://example.test/mcp" },
+ },
+ },
+ },
+ onSave,
+ );
+
+ await user.click(
+ screen.getByRole("button", { name: /rename server fetch/i }),
+ );
+ const input = screen.getByRole("textbox", { name: "Rename server" });
+ await user.clear(input);
+ await user.type(input, "fetch-v2");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+
+ await waitFor(() => expect(onSave).toHaveBeenCalledOnce());
+ expect(input).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Save name" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Cancel rename" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: /Add MCP/i })).toBeDisabled();
+ expect(
+ screen.getByRole("button", { name: /rename server docs/i }),
+ ).toBeDisabled();
+
+ finishRename();
+ await waitFor(() =>
+ expect(screen.queryByRole("textbox", { name: "Rename server" })).toBeNull(),
+ );
+ });
+
it("adds one stdio server through the form and preserves historical top-level data", async () => {
const user = userEvent.setup();
const { onSave } = renderTab({ mcp_config: { version: 1 } });
await user.click(screen.getByRole("button", { name: /add mcp/i }));
- await user.type(screen.getByLabelText("Name"), "fetch");
+ await user.type(screen.getByLabelText("Server name"), "fetch");
await user.type(screen.getByLabelText("Command"), "uvx");
- await user.click(screen.getByRole("button", { name: /add server/i }));
+ await user.click(screen.getByRole("button", { name: "Add" }));
expect(onSave).toHaveBeenCalledWith({
mcp_config: {
@@ -207,12 +447,24 @@ describe("McpConfigTab", () => {
});
});
+ it("opens a new agent MCP dialog without displaying validation errors", async () => {
+ const user = userEvent.setup();
+ renderTab();
+
+ await user.click(screen.getByRole("button", { name: /add mcp/i }));
+
+ expect(screen.getByLabelText("Server name")).not.toHaveAttribute("aria-invalid");
+ expect(screen.getByLabelText("Command")).not.toHaveAttribute("aria-invalid");
+ expect(screen.queryByText("Enter a server name.")).toBeNull();
+ expect(screen.queryByText(/Enter the command used/)).toBeNull();
+ });
+
it("adds one HTTP server through JSON mode", async () => {
const user = userEvent.setup();
const { onSave } = renderTab();
await user.click(screen.getByRole("button", { name: /add mcp/i }));
- await user.type(screen.getByLabelText("Name"), "weather");
+ await user.type(screen.getByLabelText("Server name"), "weather");
await user.click(screen.getByRole("tab", { name: "JSON" }));
fireEvent.change(screen.getByLabelText(/MCP server JSON configuration/i), {
target: {
@@ -222,7 +474,7 @@ describe("McpConfigTab", () => {
}),
},
});
- await user.click(screen.getByRole("button", { name: /add server/i }));
+ await user.click(screen.getByRole("button", { name: "Add" }));
expect(onSave).toHaveBeenCalledWith({
mcp_config: {
@@ -252,12 +504,13 @@ describe("McpConfigTab", () => {
const { onSave } = renderTab({ mcp_config: existing });
await user.click(
- screen.getByRole("button", { name: /edit mcp server fetch/i }),
+ screen.getByRole("button", { name: /edit configuration fetch/i }),
);
+ expect(screen.queryByLabelText("Server name")).not.toBeInTheDocument();
const command = screen.getByLabelText("Command");
await user.clear(command);
await user.type(command, "npx");
- await user.click(screen.getByRole("button", { name: /save changes/i }));
+ await user.click(screen.getByRole("button", { name: "Save" }));
expect(onSave).toHaveBeenCalledWith({
mcp_config: {
@@ -274,6 +527,135 @@ describe("McpConfigTab", () => {
});
});
+ it("round-trips empty stdio arguments and environment values", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({
+ mcp_config: {
+ mcpServers: {
+ fetch: {
+ command: "uvx",
+ args: [""],
+ env: { EMPTY_VALUE: "" },
+ },
+ },
+ },
+ });
+
+ await user.click(
+ screen.getByRole("button", { name: /edit configuration fetch/i }),
+ );
+ expect(screen.getByLabelText("Startup arguments 1")).toHaveValue("");
+ expect(
+ screen.getByLabelText("Environment variables: Value 1"),
+ ).toHaveValue("");
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(onSave).toHaveBeenCalledWith({
+ mcp_config: {
+ mcpServers: {
+ fetch: {
+ command: "uvx",
+ args: [""],
+ env: { EMPTY_VALUE: "" },
+ },
+ },
+ },
+ });
+ });
+
+ it("preserves leading, middle, and trailing empty stdio arguments", async () => {
+ const user = userEvent.setup();
+ const args = ["", "2222", "", "333", ""];
+ const { onSave } = renderTab({
+ mcp_config: {
+ mcpServers: {
+ fetch: { command: "uvx", args },
+ },
+ },
+ });
+
+ await user.click(
+ screen.getByRole("button", { name: /edit configuration fetch/i }),
+ );
+ for (const [index, value] of args.entries()) {
+ expect(screen.getByLabelText(`Startup arguments ${index + 1}`)).toHaveValue(
+ value,
+ );
+ }
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(onSave).toHaveBeenCalledWith({
+ mcp_config: {
+ mcpServers: {
+ fetch: { command: "uvx", args },
+ },
+ },
+ });
+ });
+
+ it("saves leading, middle, and trailing empty rows added in the form", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({
+ mcp_config: {
+ mcpServers: {
+ fetch: { command: "uvx" },
+ },
+ },
+ });
+
+ await user.click(
+ screen.getByRole("button", { name: /edit configuration fetch/i }),
+ );
+ const addArgument = screen.getByRole("button", { name: "Add argument" });
+ for (let index = 0; index < 5; index += 1) {
+ await user.click(addArgument);
+ }
+ await user.type(screen.getByLabelText("Startup arguments 2"), "2222");
+ await user.type(screen.getByLabelText("Startup arguments 4"), "333");
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(onSave).toHaveBeenCalledWith({
+ mcp_config: {
+ mcpServers: {
+ fetch: { command: "uvx", args: ["", "2222", "", "333", ""] },
+ },
+ },
+ });
+ });
+
+ it("round-trips empty HTTP header values", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({
+ mcp_config: {
+ mcpServers: {
+ docs: {
+ type: "http",
+ url: "https://example.test/mcp",
+ headers: { "X-Empty": "" },
+ },
+ },
+ },
+ });
+
+ await user.click(
+ screen.getByRole("button", { name: /edit configuration docs/i }),
+ );
+ expect(screen.getByLabelText("HTTP headers: Value 1")).toHaveValue("");
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(onSave).toHaveBeenCalledWith({
+ mcp_config: {
+ mcpServers: {
+ docs: {
+ type: "http",
+ url: "https://example.test/mcp",
+ headers: { "X-Empty": "" },
+ },
+ },
+ },
+ });
+ });
+
it("deletes the last managed server only after confirmation", async () => {
const user = userEvent.setup();
const { onSave } = renderTab({
@@ -294,14 +676,20 @@ describe("McpConfigTab", () => {
const { onSave } = renderTab();
await user.click(screen.getByRole("button", { name: /add mcp/i }));
- await user.type(screen.getByLabelText("Name"), "broken");
+ await user.type(screen.getByLabelText("Server name"), "broken");
await user.click(screen.getByRole("tab", { name: "JSON" }));
fireEvent.change(screen.getByLabelText(/MCP server JSON configuration/i), {
target: { value: "{not json" },
});
+ expect(screen.queryByText(/invalid json/i)).toBeNull();
+ const addButton = screen.getByRole("button", { name: "Add" });
+ expect(addButton).toBeEnabled();
+
+ await user.click(addButton);
+
expect(screen.getByText(/invalid json/i)).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /add server/i })).toBeDisabled();
+ expect(screen.getByLabelText(/MCP server JSON configuration/i)).toHaveFocus();
expect(onSave).not.toHaveBeenCalled();
});
@@ -317,7 +705,8 @@ describe("McpConfigTab", () => {
renderTab({}, undefined, onlineRuntime);
- expect(await screen.findByText("linear")).toBeInTheDocument();
+ const row = (await screen.findByText("linear")).closest("li")!;
+ expect(within(row).getByText("Streamable HTTP")).toBeVisible();
});
it("shows a permission notice when capability discovery is forbidden", async () => {
@@ -377,7 +766,8 @@ describe("McpConfigTab workspace servers", () => {
workspaceMcp.assigned = [wsServer({ enabled: true })];
renderTab({ mcp_config: null });
- expect(await screen.findByText("shared-linear")).toBeInTheDocument();
+ const row = (await screen.findByText("shared-linear")).closest("li")!;
+ expect(within(row).getByText("Streamable HTTP")).toBeVisible();
expect(screen.getByText(/From the workspace library/)).toBeInTheDocument();
});
@@ -399,7 +789,9 @@ describe("McpConfigTab workspace servers", () => {
renderTab({ mcp_config: null });
await user.click(await screen.findByRole("button", { name: /Add from workspace/ }));
- await user.click(await screen.findByRole("menuitem", { name: /pickable/ }));
+ const option = await screen.findByRole("menuitem", { name: /pickable/ });
+ expect(within(option).getByText("Streamable HTTP")).toBeVisible();
+ await user.click(option);
await waitFor(() => expect(mockAddServer).toHaveBeenCalledWith("srv-9"));
});
@@ -449,7 +841,13 @@ describe("McpConfigTab workspace servers", () => {
render(
<TestShell>
<McpConfigTab
- agent={baseAgent}
+ agent={{
+ ...baseAgent,
+ mcp_config: {
+ version: 1,
+ mcpServers: { fetch: { command: "uvx" } },
+ },
+ }}
runtime={null}
canEdit={false}
onSave={vi.fn()}
@@ -458,6 +856,11 @@ describe("McpConfigTab workspace servers", () => {
);
expect(await screen.findByText("shared-linear")).toBeInTheDocument();
+ expect(screen.getByText("fetch")).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /Add MCP/i })).toBeNull();
+ expect(screen.queryByRole("button", { name: /Rename server fetch/i })).toBeNull();
+ expect(screen.queryByRole("button", { name: /Edit configuration fetch/i })).toBeNull();
+ expect(screen.queryByRole("button", { name: /Delete MCP server fetch/i })).toBeNull();
expect(screen.queryByRole("button", { name: /Add from workspace/ })).toBeNull();
expect(screen.queryByRole("switch")).toBeNull();
expect(screen.queryByRole("button", { name: /Remove shared-linear/i })).toBeNull();
@@ -520,14 +923,14 @@ describe("McpConfigTab effective set", () => {
renderTab({ mcp_config: { mcpServers: { streamy: entry } } });
await user.click(
- screen.getByRole("button", { name: /edit mcp server streamy/i }),
+ screen.getByRole("button", { name: /edit configuration streamy/i }),
);
expect(screen.getByRole("tab", { name: "JSON" })).toHaveAttribute(
"aria-selected",
"true",
);
- expect(screen.getByRole("tab", { name: "Form" })).toHaveAttribute(
+ expect(screen.getByRole("tab", { name: "Visual editor" })).toHaveAttribute(
"aria-disabled",
"true",
);
@@ -544,10 +947,10 @@ describe("McpConfigTab effective set", () => {
renderTab({ mcp_config: { mcpServers: { normal: entry } } });
await user.click(
- screen.getByRole("button", { name: /edit mcp server normal/i }),
+ screen.getByRole("button", { name: /edit configuration normal/i }),
);
- expect(screen.getByRole("tab", { name: "Form" })).toHaveAttribute(
+ expect(screen.getByRole("tab", { name: "Visual editor" })).toHaveAttribute(
"aria-selected",
"true",
);
diff --git a/packages/views/agents/components/tabs/mcp-config-tab.tsx b/packages/views/agents/components/tabs/mcp-config-tab.tsx
index 473d3ed08d..cab59cf58b 100644
--- a/packages/views/agents/components/tabs/mcp-config-tab.tsx
+++ b/packages/views/agents/components/tabs/mcp-config-tab.tsx
@@ -4,11 +4,9 @@ import { useEffect, useMemo, useState } from "react";
import {
Loader2,
Lock,
- Pencil,
Plus,
RefreshCw,
Server,
- Trash2,
} from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import type { Agent, AgentRuntime, WorkspaceMcpServer } from "@multica/core/types";
@@ -47,9 +45,15 @@ import {
} from "@multica/ui/components/ui/dropdown-menu";
import { Switch } from "@multica/ui/components/ui/switch";
import { toast } from "sonner";
+import {
+ McpRemoveButton,
+ McpServerRow,
+ McpTransportIcon,
+} from "../../../common/mcp-server-row";
import { useT } from "../../../i18n";
import {
listManagedMcpServers,
+ mcpTransportLabel,
removeManagedMcpServer,
upsertManagedMcpServer,
type ManagedMcpServer,
@@ -132,22 +136,102 @@ export function McpConfigTab({
const [editingServer, setEditingServer] = useState<ManagedMcpServer | null>(
null,
);
+ const [renamingServer, setRenamingServer] =
+ useState<ManagedMcpServer | null>(null);
+ const [renameDraft, setRenameDraft] = useState("");
+ const [renameError, setRenameError] = useState("");
+ const [renamePending, setRenamePending] = useState(false);
const [deletingServer, setDeletingServer] =
useState<ManagedMcpServer | null>(null);
const [deleting, setDeleting] = useState(false);
useEffect(() => onDirtyChange?.(false), [onDirtyChange]);
+ const startRename = (server: ManagedMcpServer) => {
+ if (renamePending) return;
+ setRenamingServer(server);
+ setRenameDraft(server.name);
+ setRenameError("");
+ };
+
+ const cancelRename = () => {
+ if (renamePending) return;
+ setRenamingServer(null);
+ setRenameDraft("");
+ setRenameError("");
+ };
+
const openAddDialog = () => {
+ cancelRename();
setEditingServer(null);
setEditorOpen(true);
};
const openEditDialog = (server: ManagedMcpServer) => {
+ cancelRename();
setEditingServer(server);
setEditorOpen(true);
};
+ const handleRename = async () => {
+ if (!renamingServer || renamePending) return;
+ const name = renameDraft.trim();
+ if (name === "") {
+ setRenameError(t(($) => $.tab_body.mcp_config.dialog_name_required));
+ return;
+ }
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) {
+ setRenameError(t(($) => $.tab_body.mcp_config.dialog_name_invalid));
+ return;
+ }
+ if (name !== renamingServer.name && managedNames.has(name)) {
+ setRenameError(t(($) => $.tab_body.mcp_config.dialog_name_duplicate));
+ return;
+ }
+ if (name === renamingServer.name) {
+ cancelRename();
+ return;
+ }
+
+ // The agent may refresh while the inline editor is open. Renaming must
+ // preserve the latest server config instead of restoring the snapshot
+ // captured when editing began.
+ const currentServer = managedServers.find(
+ (server) =>
+ server.container === renamingServer.container &&
+ server.name === renamingServer.name,
+ );
+ if (!currentServer) {
+ setRenameError(t(($) => $.tab_body.mcp_config.rename_failed_toast));
+ return;
+ }
+
+ setRenamePending(true);
+ try {
+ await onSave({
+ mcp_config: upsertManagedMcpServer(
+ agent.mcp_config,
+ currentServer,
+ name,
+ currentServer.config,
+ ),
+ });
+ toast.success(t(($) => $.tab_body.mcp_config.renamed_toast));
+ setRenamingServer(null);
+ setRenameDraft("");
+ setRenameError("");
+ } catch (error) {
+ const message =
+ error instanceof Error && error.message
+ ? error.message
+ : t(($) => $.tab_body.mcp_config.rename_failed_toast);
+ setRenameError(message);
+ toast.error(message);
+ } finally {
+ setRenamePending(false);
+ }
+ };
+
const handleSaveServer = async (
name: string,
config: Record<string, unknown>,
@@ -234,8 +318,13 @@ export function McpConfigTab({
<h3 className="text-body font-medium">
{t(($) => $.tab_body.mcp_config.managed_title)}
</h3>
- {!redacted && (
- <Button size="sm" variant="outline" onClick={openAddDialog}>
+ {!redacted && canEdit && (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={renamePending}
+ onClick={openAddDialog}
+ >
<Plus aria-hidden="true" />
{t(($) => $.tab_body.mcp_config.add_action)}
</Button>
@@ -258,14 +347,56 @@ export function McpConfigTab({
</div>
</div>
) : managedServers.length > 0 ? (
- <McpServerList
- servers={managedServers}
- disabledLabel={t(($) => $.tab_body.mcp_config.agent_disabled_badge)}
- onEdit={openEditDialog}
- onDelete={setDeletingServer}
- editLabel={t(($) => $.tab_body.mcp_config.edit_aria)}
- deleteLabel={t(($) => $.tab_body.mcp_config.delete_aria)}
- />
+ <ul className="divide-y rounded-lg border bg-surface-raised/40">
+ {managedServers.map((server) => (
+ <McpServerRow
+ key={server.name}
+ name={server.name}
+ transport={server.transport}
+ status={
+ !server.enabled ? (
+ <Badge variant="secondary">
+ {t(($) => $.tab_body.mcp_config.agent_disabled_badge)}
+ </Badge>
+ ) : undefined
+ }
+ canManage={canEdit}
+ actionsDisabled={renamePending}
+ rename={
+ renamingServer?.name === server.name
+ ? {
+ draft: renameDraft,
+ error: renameError,
+ pending: renamePending,
+ onChange: (value) => {
+ setRenameDraft(value);
+ setRenameError("");
+ },
+ onCancel: cancelRename,
+ onSubmit: () => void handleRename(),
+ }
+ : undefined
+ }
+ labels={{
+ rename: t(($) => $.tab_body.mcp_config.rename_action),
+ renameAria: t(($) => $.tab_body.mcp_config.rename_server),
+ renameSave: t(($) => $.tab_body.mcp_config.rename_save),
+ renameCancel: t(($) => $.tab_body.mcp_config.rename_cancel),
+ configure: t(($) => $.tab_body.mcp_config.edit_config),
+ configureAria: t(($) => $.tab_body.mcp_config.edit_config),
+ remove: t(($) => $.tab_body.mcp_config.delete_action_short),
+ removeAria: t(($) => $.tab_body.mcp_config.delete_aria),
+ }}
+ configureKind="edit"
+ onRenameStart={() => startRename(server)}
+ onConfigure={() => openEditDialog(server)}
+ onRemove={() => {
+ cancelRename();
+ setDeletingServer(server);
+ }}
+ />
+ ))}
+ </ul>
) : (
<McpNotice text={t(($) => $.tab_body.mcp_config.managed_empty)} />
)}
@@ -390,6 +521,7 @@ export function McpConfigTab({
open={editorOpen}
server={editingServer}
existingNames={managedNames}
+ hideNameWhenEditing
onOpenChange={setEditorOpen}
onSave={handleSaveServer}
/>
@@ -465,12 +597,8 @@ function McpWorkspaceServerRow({
const { t } = useT("agents");
const enabled = server.enabled !== false;
return (
- // Same row shape as the other two lists on this tab — icon chip, name,
- // transport — so the three sources read as one inventory.
- <li className="flex items-center gap-3 p-3">
- <span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
- <Server className="h-4 w-4" aria-hidden="true" />
- </span>
+ <li className="group flex min-h-16 items-center gap-3 px-4 py-3 transition-colors hover:bg-muted/30">
+ <McpTransportIcon transport={server.transport} />
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-center gap-2">
<span className="truncate text-body font-medium">{server.name}</span>
@@ -480,12 +608,12 @@ function McpWorkspaceServerRow({
</Badge>
)}
</div>
- <p className="text-caption uppercase text-muted-foreground">
- {server.transport || "unknown"}
+ <p className="text-caption text-muted-foreground">
+ {mcpTransportLabel(server.transport)}
</p>
</div>
{canEdit && (
- <>
+ <div className="flex shrink-0 items-center gap-0.5 text-muted-foreground">
<Switch
checked={enabled}
disabled={busy}
@@ -494,18 +622,16 @@ function McpWorkspaceServerRow({
name: server.name,
})}
/>
- <Button
- variant="ghost"
- size="icon"
+ <div className="mx-1 h-4 w-px bg-surface-border" aria-hidden="true" />
+ <McpRemoveButton
disabled={busy}
onClick={onRemove}
- aria-label={t(($) => $.tab_body.mcp_config.workspace_remove_aria, {
+ ariaLabel={t(($) => $.tab_body.mcp_config.workspace_remove_aria, {
name: server.name,
})}
- >
- <Trash2 className="h-4 w-4" aria-hidden="true" />
- </Button>
- </>
+ tooltipLabel={t(($) => $.tab_body.mcp_config.workspace_remove_action)}
+ />
+ </div>
)}
{!canEdit && !enabled && (
<Badge variant="secondary">
@@ -551,8 +677,8 @@ function McpWorkspaceServerPicker({
onClick={() => onSelect(server.id)}
>
<span className="min-w-0 flex-1 truncate">{server.name}</span>
- <span className="shrink-0 text-caption uppercase text-muted-foreground">
- {server.transport || "unknown"}
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {mcpTransportLabel(server.transport)}
</span>
</DropdownMenuItem>
))}
@@ -565,60 +691,35 @@ function McpServerList({
servers,
disabledLabel,
overriddenLabel,
- onEdit,
- onDelete,
- editLabel,
- deleteLabel,
}: {
servers: McpServerView[];
disabledLabel: string;
overriddenLabel?: string;
- onEdit?: (server: ManagedMcpServer) => void;
- onDelete?: (server: ManagedMcpServer) => void;
- editLabel?: string;
- deleteLabel?: string;
}) {
return (
<ul className="divide-y rounded-lg border bg-surface-raised/40">
{servers.map((server) => (
- <li key={server.name} className="flex items-center gap-3 p-3">
- <span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
- <Server className="h-4 w-4" aria-hidden="true" />
- </span>
+ <li
+ key={server.name}
+ className="group flex min-h-16 items-center gap-3 px-4 py-3 transition-colors hover:bg-muted/30"
+ >
+ <McpTransportIcon transport={server.transport} />
<div className="min-w-0 flex-1">
<p className="truncate text-body font-medium">{server.name}</p>
<p className="text-caption text-muted-foreground">
- <span className="uppercase">{server.transport}</span>
- {server.source ? ` · ${server.source}` : null}
+ {mcpTransportLabel(server.transport)}
</p>
+ {server.source ? (
+ <p className="text-caption text-muted-foreground">
+ {server.source}
+ </p>
+ ) : null}
</div>
{server.overridden && overriddenLabel ? (
<Badge variant="outline">{overriddenLabel}</Badge>
) : !server.enabled ? (
<Badge variant="outline">{disabledLabel}</Badge>
) : null}
- {onEdit && onDelete && (
- <div className="flex items-center gap-1">
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- aria-label={`${editLabel} ${server.name}`}
- onClick={() => onEdit(server as ManagedMcpServer)}
- >
- <Pencil aria-hidden="true" />
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- aria-label={`${deleteLabel} ${server.name}`}
- onClick={() => onDelete(server as ManagedMcpServer)}
- >
- <Trash2 aria-hidden="true" />
- </Button>
- </div>
- )}
</li>
))}
</ul>
diff --git a/packages/views/agents/components/tabs/mcp-server-dialog.test.tsx b/packages/views/agents/components/tabs/mcp-server-dialog.test.tsx
new file mode 100644
index 0000000000..7f862eb67c
--- /dev/null
+++ b/packages/views/agents/components/tabs/mcp-server-dialog.test.tsx
@@ -0,0 +1,238 @@
+// @vitest-environment jsdom
+
+import type { ComponentProps, ReactNode } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../../locales/en/common.json";
+import enAgents from "../../../locales/en/agents.json";
+import type { ManagedMcpServer } from "./mcp-config-model";
+import { McpServerDialog } from "./mcp-server-dialog";
+
+const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };
+
+function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ {children}
+ </I18nProvider>
+ );
+}
+
+function managedServer(overrides: Partial<ManagedMcpServer> = {}): ManagedMcpServer {
+ return {
+ name: "fetch",
+ config: { command: "uvx" },
+ container: "mcpServers",
+ transport: "stdio",
+ enabled: true,
+ ...overrides,
+ };
+}
+
+function renderDialog(overrides: Partial<ComponentProps<typeof McpServerDialog>> = {}) {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const onOpenChange = vi.fn();
+ const props = {
+ open: true,
+ server: null,
+ existingNames: new Set<string>(),
+ onSave,
+ onOpenChange,
+ ...overrides,
+ };
+ const view = render(<McpServerDialog {...props} />, { wrapper: Wrapper });
+ return { ...view, onSave: props.onSave, onOpenChange: props.onOpenChange };
+}
+
+describe("McpServerDialog", () => {
+ it.each(["context7.dev", "legacy server", " padded "])(
+ "edits configuration while preserving the historical name %s exactly",
+ async (name) => {
+ const user = userEvent.setup();
+ const { onSave, onOpenChange } = renderDialog({
+ server: managedServer({ name }),
+ existingNames: new Set([name]),
+ hideNameWhenEditing: true,
+ });
+
+ expect(screen.queryByLabelText("Server name")).toBeNull();
+ await user.clear(screen.getByLabelText("Command"));
+ await user.type(screen.getByLabelText("Command"), "updated-command");
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() =>
+ expect(onSave).toHaveBeenCalledWith(name, { command: "updated-command" }),
+ );
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ },
+ );
+
+ it.each(["create", "rename"])(
+ "rejects a newly entered historical-style name during %s",
+ async (action) => {
+ const user = userEvent.setup();
+ const { onSave, onOpenChange } = renderDialog({
+ server: action === "rename" ? managedServer() : null,
+ });
+
+ const input = screen.getByLabelText("Server name");
+ await user.clear(input);
+ await user.type(input, "context7.dev");
+ if (action === "create") {
+ await user.type(screen.getByLabelText("Command"), "uvx");
+ }
+ await user.click(screen.getByRole("button", {
+ name: action === "create" ? "Add" : "Save",
+ }));
+
+ expect(input).toHaveFocus();
+ expect(input).toHaveAttribute("aria-invalid", "true");
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "Use only letters, numbers, hyphens, and underscores.",
+ );
+ expect(onSave).not.toHaveBeenCalled();
+ expect(onOpenChange).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ ["sse", "STDIO", "Command", "uvx", { command: "uvx" }],
+ ["websocket", "Streamable HTTP", "Server URL", "https://new.example/mcp", {
+ type: "http", url: "https://new.example/mcp",
+ }],
+ ])(
+ "replaces a %s server through the visual editor using %s",
+ async (transport, selected, label, value, expected) => {
+ const user = userEvent.setup();
+ const { onSave } = renderDialog({
+ server: managedServer({ transport, config: {} }),
+ replacementMode: true,
+ });
+
+ expect(screen.getByRole("tab", { name: "JSON" })).toHaveAttribute(
+ "aria-selected", "true",
+ );
+ await user.click(screen.getByRole("tab", { name: "Visual editor" }));
+ await user.click(screen.getByRole("button", { name: new RegExp(`^${selected}`) }));
+ await user.type(screen.getByLabelText(label), value);
+ await user.click(screen.getByRole("button", { name: "Replace configuration" }));
+
+ expect(onSave).toHaveBeenCalledWith("fetch", expected);
+ },
+ );
+
+ it("blocks duplicate submits and dismissal until a save completes", async () => {
+ const user = userEvent.setup();
+ let finishSave!: () => void;
+ const onSave = vi.fn(() => new Promise<void>((resolve) => { finishSave = resolve; }));
+ const { onOpenChange } = renderDialog({ server: managedServer(), onSave });
+
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();
+ fireEvent.submit(screen.getByLabelText("Command").closest("form")!);
+ await user.keyboard("{Escape}");
+ await user.click(screen.getByRole("button", { name: "Close" }));
+ expect(screen.getByRole("dialog")).toBeVisible();
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect(onSave).toHaveBeenCalledExactlyOnceWith("fetch", { command: "uvx" });
+
+ finishSave();
+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
+ });
+
+ it.each(["Cancel", "Close", "Escape"])(
+ "discards an unsaved draft when dismissed with %s",
+ async (action) => {
+ const user = userEvent.setup();
+ const { onSave, onOpenChange } = renderDialog();
+ await user.type(screen.getByLabelText("Server name"), "draft");
+
+ if (action === "Escape") await user.keyboard("{Escape}");
+ else await user.click(screen.getByRole("button", { name: action }));
+
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(onSave).not.toHaveBeenCalled();
+ },
+ );
+
+ it("clears submitted JSON errors when returning to the visual editor", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderDialog();
+ await user.type(screen.getByLabelText("Server name"), "fetch");
+ await user.type(screen.getByLabelText("Command"), "uvx");
+ await user.click(screen.getByRole("tab", { name: "JSON" }));
+ fireEvent.change(screen.getByLabelText("MCP server JSON configuration"), {
+ target: { value: "{invalid" },
+ });
+ await user.click(screen.getByRole("button", { name: "Add" }));
+ expect(screen.getByRole("alert")).toHaveTextContent("Invalid JSON");
+
+ await user.click(screen.getByRole("tab", { name: "Visual editor" }));
+
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(screen.getByLabelText("Command")).toHaveValue("uvx");
+ expect(screen.getByLabelText("Command")).not.toHaveAttribute("aria-invalid");
+ await user.click(screen.getByRole("button", { name: "Add" }));
+ expect(onSave).toHaveBeenCalledWith("fetch", { command: "uvx" });
+ });
+
+ it("removes one argument and environment row while preserving their siblings", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderDialog({
+ server: managedServer({
+ config: {
+ command: "uvx",
+ args: ["first", "remove", "last"],
+ env: { FIRST: "one", REMOVE: "two", LAST: "three" },
+ },
+ }),
+ });
+
+ await user.click(screen.getByRole("button", { name: "Remove argument 2" }));
+ await user.clear(screen.getByLabelText("Startup arguments 2"));
+ await user.type(screen.getByLabelText("Startup arguments 2"), "updated-last");
+ await user.click(screen.getByRole("button", { name: "Remove environment variable 2" }));
+ await user.clear(screen.getByLabelText("Environment variables: Variable name 2"));
+ await user.type(screen.getByLabelText("Environment variables: Variable name 2"), "UPDATED");
+ await user.clear(screen.getByLabelText("Environment variables: Value 2"));
+ await user.type(screen.getByLabelText("Environment variables: Value 2"), "four");
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(onSave).toHaveBeenCalledWith("fetch", {
+ command: "uvx",
+ args: ["first", "updated-last"],
+ env: { FIRST: "one", UPDATED: "four" },
+ });
+ });
+
+ it("removes one HTTP header while preserving and editing its siblings", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderDialog({
+ server: managedServer({
+ transport: "http",
+ config: {
+ type: "http",
+ url: "https://example.test/mcp",
+ headers: { First: "one", Remove: "two", Last: "three" },
+ },
+ }),
+ });
+
+ await user.click(screen.getByRole("button", { name: "Remove header 2" }));
+ await user.clear(screen.getByLabelText("HTTP headers: Header name 2"));
+ await user.type(screen.getByLabelText("HTTP headers: Header name 2"), "Updated");
+ await user.clear(screen.getByLabelText("HTTP headers: Value 2"));
+ await user.type(screen.getByLabelText("HTTP headers: Value 2"), "four");
+ await user.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(onSave).toHaveBeenCalledWith("fetch", {
+ type: "http",
+ url: "https://example.test/mcp",
+ headers: { First: "one", Updated: "four" },
+ });
+ });
+});
diff --git a/packages/views/agents/components/tabs/mcp-server-dialog.tsx b/packages/views/agents/components/tabs/mcp-server-dialog.tsx
index 4c8337edb5..48cc4a61ff 100644
--- a/packages/views/agents/components/tabs/mcp-server-dialog.tsx
+++ b/packages/views/agents/components/tabs/mcp-server-dialog.tsx
@@ -1,18 +1,30 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
-import { Loader2, Plus, Trash2 } from "lucide-react";
+import {
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { Globe2, Loader2, Plus, SquareTerminal, Trash2 } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
import {
Dialog,
DialogContent,
DialogDescription,
- DialogFooter,
DialogHeader,
DialogTitle,
} from "@multica/ui/components/ui/dialog";
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from "@multica/ui/components/ui/field";
import { Input } from "@multica/ui/components/ui/input";
-import { Label } from "@multica/ui/components/ui/label";
import {
Tabs,
TabsContent,
@@ -27,7 +39,6 @@ import { isRecord, mcpTransport } from "./mcp-config-model";
type EditorMode = "form" | "json";
type FormTransport = "stdio" | "http";
type KeyValue = { key: string; value: string };
-
type McpFormState = {
transport: FormTransport;
command: string;
@@ -199,6 +210,8 @@ export function McpServerDialog({
server,
existingNames,
lockName = false,
+ replacementMode = false,
+ hideNameWhenEditing = false,
onOpenChange,
onSave,
}: {
@@ -211,6 +224,17 @@ export function McpServerDialog({
* second server" and silently leave the original behind.
*/
lockName?: boolean;
+ /**
+ * Starts from an intentionally blank config and replaces the saved entry.
+ * Used by the write-only workspace library, where saved values cannot be
+ * read back and renaming is handled separately in the list.
+ */
+ replacementMode?: boolean;
+ /**
+ * Keeps configuration editing separate from list-level renaming. The saved
+ * name still participates in validation and is passed back unchanged.
+ */
+ hideNameWhenEditing?: boolean;
onOpenChange: (open: boolean) => void;
onSave: (name: string, config: Record<string, unknown>) => Promise<void>;
}) {
@@ -220,15 +244,22 @@ export function McpServerDialog({
const [form, setForm] = useState<McpFormState>(emptyForm);
const [jsonText, setJsonText] = useState("{}");
const [saving, setSaving] = useState(false);
+ const [saveAttempted, setSaveAttempted] = useState(false);
+ const fieldId = useId();
+ const nameInputRef = useRef<HTMLInputElement>(null);
+ const commandInputRef = useRef<HTMLInputElement>(null);
+ const urlInputRef = useRef<HTMLInputElement>(null);
+ const jsonInputRef = useRef<HTMLTextAreaElement>(null);
+ const formId = `${fieldId}-form`;
+ const nameHidden = replacementMode || (hideNameWhenEditing && server !== null);
useEffect(() => {
if (!open) return;
- const config = server?.config ?? {};
+ const config = replacementMode ? {} : (server?.config ?? {});
setName(server?.name ?? "");
- // A caller that cannot read the saved entry back (the workspace layer is
- // write-only) passes an empty config with the transport from the safe
- // summary. Seeding from `formFromConfig({})` there would open an http form
- // for a known stdio server, so take the transport from the summary.
+ // A caller on an older backend may have only the safe transport summary.
+ // Seeding from `formFromConfig({})` there would open an HTTP form for a
+ // known stdio server, so take the transport from the summary.
setForm(
!server
? emptyForm()
@@ -238,22 +269,29 @@ export function McpServerDialog({
);
setJsonText(JSON.stringify(config, null, 2));
setMode(server && !formSupportsServer(server) ? "json" : "form");
- }, [open, server]);
+ setSaveAttempted(false);
+ }, [open, replacementMode, server]);
// The form is unavailable — not merely unselected — for entries it cannot
// represent, so switching to it cannot rewrite them either.
- const formAvailable = !server || formSupportsServer(server);
+ const formAvailable = replacementMode || !server || formSupportsServer(server);
const jsonResult = useMemo(() => parseServerJson(jsonText), [jsonText]);
- const trimmedName = name.trim();
+ // Existing entries can originate from a runtime or API with a broader name
+ // grammar. Configuration edits must retain that identity verbatim; only
+ // newly entered names go through the create/rename validation below.
+ const preservesServerName = server !== null && name === server.name;
+ const submittedName = preservesServerName ? name : name.trim();
const nameError =
- trimmedName === ""
- ? "required"
- : !/^[A-Za-z0-9_-]+$/.test(trimmedName)
- ? "format"
- : existingNames.has(trimmedName) && trimmedName !== server?.name
- ? "duplicate"
- : null;
+ preservesServerName
+ ? null
+ : submittedName === ""
+ ? "required"
+ : !/^[A-Za-z0-9_-]+$/.test(submittedName)
+ ? "format"
+ : existingNames.has(submittedName) && submittedName !== server?.name
+ ? "duplicate"
+ : null;
const formError =
form.transport === "stdio"
? form.command.trim() === ""
@@ -262,31 +300,40 @@ export function McpServerDialog({
: form.url.trim() === ""
? "url"
: null;
- const canSave =
- !saving &&
- nameError === null &&
- (mode === "form" ? formError === null : jsonResult.ok);
+ const visibleNameError = saveAttempted ? nameError : null;
+ const visibleFormError = saveAttempted ? formError : null;
+ const visibleJsonError = saveAttempted && !jsonResult.ok ? jsonResult : null;
- const errorMessage =
- nameError === "required"
+ const nameErrorMessage =
+ visibleNameError === "required"
? t(($) => $.tab_body.mcp_config.dialog_name_required)
- : nameError === "format"
+ : visibleNameError === "format"
? t(($) => $.tab_body.mcp_config.dialog_name_invalid)
- : nameError === "duplicate"
+ : visibleNameError === "duplicate"
? t(($) => $.tab_body.mcp_config.dialog_name_duplicate)
- : mode === "form" && formError === "command"
- ? t(($) => $.tab_body.mcp_config.dialog_command_required)
- : mode === "form" && formError === "url"
- ? t(($) => $.tab_body.mcp_config.dialog_url_required)
- : mode === "json" && !jsonResult.ok && jsonResult.error === "not_object"
- ? t(($) => $.tab_body.mcp_config.dialog_json_object)
- : mode === "json" && !jsonResult.ok && jsonResult.error === "missing_target"
- ? t(($) => $.tab_body.mcp_config.dialog_json_target)
- : mode === "json" && !jsonResult.ok
- ? t(($) => $.tab_body.mcp_config.invalid_json, {
- error: jsonResult.error,
- })
- : "";
+ : "";
+ const formErrorMessage =
+ mode === "form" && visibleFormError === "command"
+ ? t(($) => $.tab_body.mcp_config.dialog_command_required)
+ : mode === "form" && visibleFormError === "url"
+ ? t(($) => $.tab_body.mcp_config.dialog_url_required)
+ : "";
+ const jsonErrorMessage =
+ mode === "json" && visibleJsonError?.error === "not_object"
+ ? t(($) => $.tab_body.mcp_config.dialog_json_object)
+ : mode === "json" && visibleJsonError?.error === "missing_target"
+ ? t(($) => $.tab_body.mcp_config.dialog_json_target)
+ : mode === "json" && visibleJsonError
+ ? t(($) => $.tab_body.mcp_config.invalid_json, {
+ error: visibleJsonError.error,
+ })
+ : "";
+
+ const nameHintId = `${fieldId}-name-hint`;
+ const nameErrorId = `${fieldId}-name-error`;
+ const commandErrorId = `${fieldId}-command-error`;
+ const urlErrorId = `${fieldId}-url-error`;
+ const jsonErrorId = `${fieldId}-json-error`;
const handleModeChange = (next: string | number | null) => {
if (next !== "form" && next !== "json") return;
@@ -295,18 +342,30 @@ export function McpServerDialog({
} else if (next === "form" && mode === "json" && jsonResult.ok) {
setForm(formFromConfig(jsonResult.value));
}
+ setSaveAttempted(false);
setMode(next);
};
const handleSave = async () => {
- if (!canSave) return;
+ setSaveAttempted(true);
+ if (
+ saving ||
+ nameError !== null ||
+ (mode === "form" ? formError !== null : !jsonResult.ok)
+ ) {
+ if (nameError !== null) nameInputRef.current?.focus();
+ else if (mode === "json") jsonInputRef.current?.focus();
+ else if (formError === "command") commandInputRef.current?.focus();
+ else if (formError === "url") urlInputRef.current?.focus();
+ return;
+ }
let config: Record<string, unknown>;
if (mode === "form") config = configFromForm(form);
else if (jsonResult.ok) config = jsonResult.value;
else return;
setSaving(true);
try {
- await onSave(trimmedName, config);
+ await onSave(submittedName, config);
onOpenChange(false);
} finally {
setSaving(false);
@@ -315,190 +374,309 @@ export function McpServerDialog({
return (
<Dialog open={open} onOpenChange={(next) => !saving && onOpenChange(next)}>
- <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
- <DialogHeader>
- <DialogTitle>
- {server
- ? t(($) => $.tab_body.mcp_config.dialog_edit_title)
- : t(($) => $.tab_body.mcp_config.dialog_add_title)}
- </DialogTitle>
- <DialogDescription>
- {t(($) => $.tab_body.mcp_config.dialog_description)}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-2">
- <Label htmlFor="mcp-server-name">
- {t(($) => $.tab_body.mcp_config.dialog_name_label)}
- </Label>
- <Input
- id="mcp-server-name"
- name="mcp-server-name"
- autoComplete="off"
- spellCheck={false}
- value={name}
- onChange={(event) => setName(event.target.value)}
- placeholder={t(($) => $.tab_body.mcp_config.dialog_name_placeholder)}
- aria-invalid={nameError !== null || undefined}
- readOnly={lockName}
- aria-readonly={lockName || undefined}
- className={lockName ? "text-muted-foreground" : undefined}
- />
- {lockName ? (
- <p className="text-caption text-muted-foreground">
- {t(($) => $.tab_body.mcp_config.dialog_name_locked)}
- </p>
- ) : null}
- </div>
-
- <Tabs value={mode} onValueChange={handleModeChange}>
- <TabsList className="grid w-full grid-cols-2">
- <TabsTrigger value="form" disabled={!formAvailable}>
- {t(($) => $.tab_body.mcp_config.dialog_form_tab)}
- </TabsTrigger>
- <TabsTrigger value="json">
- {t(($) => $.tab_body.mcp_config.dialog_json_tab)}
- </TabsTrigger>
- </TabsList>
-
- <TabsContent value="form" className="space-y-5 pt-2">
- <fieldset className="space-y-2">
- <legend className="text-body font-medium">
- {t(($) => $.tab_body.mcp_config.dialog_type_label)}
- </legend>
- <div className="grid grid-cols-2 gap-2">
- {(["stdio", "http"] as const).map((transport) => (
- <Button
- key={transport}
- type="button"
- variant={form.transport === transport ? "secondary" : "outline"}
- aria-pressed={form.transport === transport}
- onClick={() => setForm((current) => ({ ...current, transport }))}
- >
- {transport === "stdio"
- ? t(($) => $.tab_body.mcp_config.dialog_type_stdio)
- : t(($) => $.tab_body.mcp_config.dialog_type_http)}
- </Button>
- ))}
+ <DialogContent className="flex max-h-[88vh] flex-col gap-0 overscroll-contain p-0 sm:max-w-2xl [&_[data-slot=dialog-close]]:top-5 [&_[data-slot=dialog-close]]:right-5">
+ <DialogHeader className="shrink-0 border-b border-surface-border px-6 py-6 pr-14 sm:px-8 sm:pr-16">
+ <DialogTitle>
+ {replacementMode
+ ? t(($) => $.tab_body.mcp_config.dialog_replace_title, {
+ name: server?.name ?? "",
+ })
+ : server && hideNameWhenEditing
+ ? t(($) => $.tab_body.mcp_config.dialog_edit_title_named, {
+ name: server.name,
+ })
+ : server
+ ? t(($) => $.tab_body.mcp_config.dialog_edit_title)
+ : t(($) => $.tab_body.mcp_config.dialog_add_title)}
+ </DialogTitle>
+ <DialogDescription>
+ {replacementMode
+ ? t(($) => $.tab_body.mcp_config.dialog_replace_description)
+ : t(($) => $.tab_body.mcp_config.dialog_description)}
+ </DialogDescription>
+ </DialogHeader>
+
+ <form
+ id={formId}
+ data-slot="mcp-dialog-scroll-area"
+ className="min-h-0 flex-1 overflow-y-auto overscroll-contain px-6 py-7 sm:px-8 sm:py-8"
+ noValidate
+ onSubmit={(event) => {
+ event.preventDefault();
+ void handleSave();
+ }}
+ >
+ <FieldGroup className="gap-8">
+ {!nameHidden ? (
+ <Field>
+ <FieldLabel htmlFor="mcp-server-name">
+ {t(($) => $.tab_body.mcp_config.dialog_name_label)}
+ </FieldLabel>
+ <Input
+ ref={nameInputRef}
+ id="mcp-server-name"
+ name="mcp-server-name"
+ autoFocus
+ required
+ autoComplete="off"
+ spellCheck={false}
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ aria-invalid={nameErrorMessage ? true : undefined}
+ aria-describedby={nameErrorMessage ? nameErrorId : nameHintId}
+ readOnly={lockName}
+ aria-readonly={lockName || undefined}
+ className={
+ lockName
+ ? "text-muted-foreground aria-invalid:border-input aria-invalid:ring-0"
+ : "aria-invalid:border-input aria-invalid:ring-0"
+ }
+ />
+ {nameErrorMessage ? (
+ <FieldError id={nameErrorId} className="text-caption">
+ {nameErrorMessage}
+ </FieldError>
+ ) : (
+ <FieldDescription id={nameHintId} className="text-caption">
+ {lockName
+ ? t(($) => $.tab_body.mcp_config.dialog_name_locked)
+ : t(($) => $.tab_body.mcp_config.dialog_name_hint)}
+ </FieldDescription>
+ )}
+ </Field>
+ ) : null}
+
+ <Tabs value={mode} onValueChange={handleModeChange} className="gap-7">
+ <div className="space-y-3">
+ <p className="text-body font-medium">
+ {t(($) => $.tab_body.mcp_config.dialog_editor_label)}
+ </p>
+ <TabsList className="grid w-full grid-cols-2">
+ <TabsTrigger value="form" disabled={!formAvailable}>
+ {t(($) => $.tab_body.mcp_config.dialog_form_tab)}
+ </TabsTrigger>
+ <TabsTrigger value="json">
+ {t(($) => $.tab_body.mcp_config.dialog_json_tab)}
+ </TabsTrigger>
+ </TabsList>
+ </div>
+
+ <TabsContent value="form" className="space-y-6">
+ <fieldset className="space-y-3">
+ <legend className="text-body font-medium">
+ {t(($) => $.tab_body.mcp_config.dialog_type_label)}
+ </legend>
+ <div className="grid gap-3 sm:grid-cols-2">
+ {(["stdio", "http"] as const).map((transport) => {
+ const selected = form.transport === transport;
+ const Icon = transport === "stdio" ? SquareTerminal : Globe2;
+ return (
+ <button
+ key={transport}
+ type="button"
+ aria-pressed={selected}
+ className={cn(
+ "flex min-h-16 items-center gap-3 rounded-lg border px-4 py-3 text-left transition-colors",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ selected
+ ? "border-primary bg-accent/50"
+ : "border-surface-border hover:bg-accent/30",
+ )}
+ onClick={() => {
+ setSaveAttempted(false);
+ setForm((current) => ({ ...current, transport }));
+ }}
+ >
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
+ <Icon aria-hidden="true" />
+ </span>
+ <span className="min-w-0">
+ <span className="block text-body font-medium text-foreground">
+ {transport === "stdio"
+ ? t(($) => $.tab_body.mcp_config.dialog_type_stdio)
+ : t(($) => $.tab_body.mcp_config.dialog_type_http)}
+ </span>
+ <span className="mt-0.5 block text-caption font-normal text-muted-foreground">
+ {transport === "stdio"
+ ? t(($) => $.tab_body.mcp_config.dialog_type_stdio_hint)
+ : t(($) => $.tab_body.mcp_config.dialog_type_http_hint)}
+ </span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </fieldset>
+
+ {form.transport === "stdio" ? (
+ <FieldGroup className="gap-7">
+ <Field>
+ <FieldLabel htmlFor="mcp-server-command">
+ {t(($) => $.tab_body.mcp_config.dialog_command_label)}
+ </FieldLabel>
+ <Input
+ ref={commandInputRef}
+ id="mcp-server-command"
+ name="mcp-server-command"
+ // Example CLI executable: a format hint, not translatable copy.
+ // eslint-disable-next-line no-restricted-syntax
+ placeholder="npx"
+ required
+ autoComplete="off"
+ spellCheck={false}
+ value={form.command}
+ onChange={(event) => {
+ setForm((current) => ({
+ ...current,
+ command: event.target.value,
+ }));
+ }}
+ aria-invalid={formErrorMessage ? true : undefined}
+ aria-describedby={
+ formErrorMessage ? commandErrorId : undefined
+ }
+ className="aria-invalid:border-input aria-invalid:ring-0"
+ />
+ {formErrorMessage ? (
+ <FieldError id={commandErrorId} className="text-caption">
+ {formErrorMessage}
+ </FieldError>
+ ) : null}
+ </Field>
+ <StringListEditor
+ label={t(($) => $.tab_body.mcp_config.dialog_args_label)}
+ description={t(($) => $.tab_body.mcp_config.dialog_args_hint)}
+ addLabel={t(($) => $.tab_body.mcp_config.dialog_add_arg)}
+ removeLabel={t(($) => $.tab_body.mcp_config.dialog_remove_arg)}
+ values={form.args}
+ onChange={(args) =>
+ setForm((current) => ({ ...current, args }))
+ }
+ />
+ <KeyValueEditor
+ label={t(($) => $.tab_body.mcp_config.dialog_env_label)}
+ description={t(($) => $.tab_body.mcp_config.dialog_env_hint)}
+ addLabel={t(($) => $.tab_body.mcp_config.dialog_add_env)}
+ removeLabel={t(($) => $.tab_body.mcp_config.dialog_remove_env)}
+ keyLabel={t(($) => $.tab_body.mcp_config.dialog_env_key)}
+ valueLabel={t(($) => $.tab_body.mcp_config.dialog_value)}
+ rows={form.env}
+ onChange={(env) =>
+ setForm((current) => ({ ...current, env }))
+ }
+ />
+ </FieldGroup>
+ ) : (
+ <FieldGroup className="gap-7">
+ <Field>
+ <FieldLabel htmlFor="mcp-server-url">
+ {t(($) => $.tab_body.mcp_config.dialog_url_label)}
+ </FieldLabel>
+ <Input
+ ref={urlInputRef}
+ id="mcp-server-url"
+ name="mcp-server-url"
+ placeholder="https://mcp.example.com/mcp"
+ type="url"
+ inputMode="url"
+ required
+ autoComplete="off"
+ spellCheck={false}
+ value={form.url}
+ onChange={(event) => {
+ setForm((current) => ({
+ ...current,
+ url: event.target.value,
+ }));
+ }}
+ aria-invalid={formErrorMessage ? true : undefined}
+ aria-describedby={formErrorMessage ? urlErrorId : undefined}
+ className="aria-invalid:border-input aria-invalid:ring-0"
+ />
+ {formErrorMessage ? (
+ <FieldError id={urlErrorId} className="text-caption">
+ {formErrorMessage}
+ </FieldError>
+ ) : null}
+ </Field>
+ <KeyValueEditor
+ label={t(($) => $.tab_body.mcp_config.dialog_headers_label)}
+ description={t(($) => $.tab_body.mcp_config.dialog_headers_hint)}
+ addLabel={t(($) => $.tab_body.mcp_config.dialog_add_header)}
+ removeLabel={t(($) => $.tab_body.mcp_config.dialog_remove_header)}
+ keyLabel={t(($) => $.tab_body.mcp_config.dialog_header_key)}
+ valueLabel={t(($) => $.tab_body.mcp_config.dialog_value)}
+ rows={form.headers}
+ onChange={(headers) =>
+ setForm((current) => ({ ...current, headers }))
+ }
+ />
+ </FieldGroup>
+ )}
+ </TabsContent>
+
+ <TabsContent value="json">
+ <Field>
+ <FieldLabel htmlFor="mcp-server-json">
+ {t(($) => $.tab_body.mcp_config.dialog_json_label)}
+ </FieldLabel>
+ {server?.container === "mcp" ? (
+ <FieldDescription className="text-caption">
+ {t(($) => $.tab_body.mcp_config.dialog_native_json_hint)}
+ </FieldDescription>
+ ) : null}
+ <Textarea
+ ref={jsonInputRef}
+ id="mcp-server-json"
+ name="mcp-server-json"
+ autoComplete="off"
+ spellCheck={false}
+ rows={14}
+ className="min-h-72 resize-none font-mono text-caption leading-5 aria-invalid:border-input aria-invalid:ring-0"
+ value={jsonText}
+ onChange={(event) => setJsonText(event.target.value)}
+ aria-invalid={jsonErrorMessage ? true : undefined}
+ aria-describedby={jsonErrorMessage ? jsonErrorId : undefined}
+ aria-label={t(($) => $.tab_body.mcp_config.dialog_json_aria)}
+ />
+ {jsonErrorMessage ? (
+ <FieldError id={jsonErrorId} className="text-caption">
+ {jsonErrorMessage}
+ </FieldError>
+ ) : null}
+ </Field>
+ </TabsContent>
+ </Tabs>
+ </FieldGroup>
+ </form>
+
+ <div
+ data-slot="mcp-dialog-footer"
+ className="flex shrink-0 justify-end gap-2 border-t bg-muted/30 px-6 py-3 sm:px-8"
+ >
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={saving}
+ >
+ {t(($) => $.tab_body.mcp_config.dialog_cancel)}
+ </Button>
+ <Button type="submit" size="sm" form={formId} disabled={saving}>
+ {saving ? (
+ <Loader2
+ className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none"
+ aria-hidden="true"
+ />
+ ) : null}
+ {replacementMode
+ ? t(($) => $.tab_body.mcp_config.dialog_replace_action)
+ : server
+ ? t(($) => $.tab_body.mcp_config.dialog_update_action)
+ : t(($) => $.tab_body.mcp_config.dialog_add_action)}
+ </Button>
</div>
- </fieldset>
-
- {form.transport === "stdio" ? (
- <>
- <div className="space-y-2">
- <Label htmlFor="mcp-server-command">
- {t(($) => $.tab_body.mcp_config.dialog_command_label)}
- </Label>
- <Input
- id="mcp-server-command"
- name="mcp-server-command"
- autoComplete="off"
- spellCheck={false}
- value={form.command}
- onChange={(event) =>
- setForm((current) => ({ ...current, command: event.target.value }))
- }
- // An example command the user types, not copy.
- // eslint-disable-next-line no-restricted-syntax
- placeholder="npx"
- aria-invalid={formError === "command" || undefined}
- />
- </div>
- <StringListEditor
- label={t(($) => $.tab_body.mcp_config.dialog_args_label)}
- addLabel={t(($) => $.tab_body.mcp_config.dialog_add_arg)}
- removeLabel={t(($) => $.tab_body.mcp_config.dialog_remove_arg)}
- values={form.args}
- onChange={(args) => setForm((current) => ({ ...current, args }))}
- />
- <KeyValueEditor
- label={t(($) => $.tab_body.mcp_config.dialog_env_label)}
- addLabel={t(($) => $.tab_body.mcp_config.dialog_add_env)}
- removeLabel={t(($) => $.tab_body.mcp_config.dialog_remove_env)}
- rows={form.env}
- onChange={(env) => setForm((current) => ({ ...current, env }))}
- />
- </>
- ) : (
- <>
- <div className="space-y-2">
- <Label htmlFor="mcp-server-url">
- {t(($) => $.tab_body.mcp_config.dialog_url_label)}
- </Label>
- <Input
- id="mcp-server-url"
- name="mcp-server-url"
- type="url"
- inputMode="url"
- autoComplete="off"
- spellCheck={false}
- value={form.url}
- onChange={(event) =>
- setForm((current) => ({ ...current, url: event.target.value }))
- }
- placeholder="https://mcp.example.com/mcp"
- aria-invalid={formError === "url" || undefined}
- />
- </div>
- <KeyValueEditor
- label={t(($) => $.tab_body.mcp_config.dialog_headers_label)}
- addLabel={t(($) => $.tab_body.mcp_config.dialog_add_header)}
- removeLabel={t(($) => $.tab_body.mcp_config.dialog_remove_header)}
- rows={form.headers}
- onChange={(headers) =>
- setForm((current) => ({ ...current, headers }))
- }
- />
- </>
- )}
- </TabsContent>
-
- <TabsContent value="json" className="space-y-2 pt-2">
- {server?.container === "mcp" && (
- <p className="text-caption text-muted-foreground">
- {t(($) => $.tab_body.mcp_config.dialog_native_json_hint)}
- </p>
- )}
- <Label htmlFor="mcp-server-json">
- {t(($) => $.tab_body.mcp_config.dialog_json_label)}
- </Label>
- <Textarea
- id="mcp-server-json"
- name="mcp-server-json"
- autoComplete="off"
- spellCheck={false}
- rows={12}
- className="min-h-64 resize-y font-mono text-caption"
- value={jsonText}
- onChange={(event) => setJsonText(event.target.value)}
- aria-invalid={!jsonResult.ok || undefined}
- aria-label={t(($) => $.tab_body.mcp_config.dialog_json_aria)}
- />
- </TabsContent>
- </Tabs>
-
- {errorMessage && (
- <p className="text-caption text-destructive" aria-live="polite">
- {errorMessage}
- </p>
- )}
-
- <DialogFooter>
- <Button variant="ghost" onClick={() => onOpenChange(false)} disabled={saving}>
- {t(($) => $.tab_body.mcp_config.dialog_cancel)}
- </Button>
- <Button onClick={handleSave} disabled={!canSave}>
- {saving && (
- <Loader2
- className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none"
- aria-hidden="true"
- />
- )}
- {server
- ? t(($) => $.tab_body.mcp_config.dialog_update_action)
- : t(($) => $.tab_body.mcp_config.dialog_add_action)}
- </Button>
- </DialogFooter>
</DialogContent>
</Dialog>
);
@@ -506,132 +684,166 @@ export function McpServerDialog({
function StringListEditor({
label,
+ description,
addLabel,
removeLabel,
values,
onChange,
}: {
label: string;
+ description: string;
addLabel: string;
removeLabel: string;
values: string[];
onChange: (values: string[]) => void;
}) {
+ const labelId = useId();
return (
- <fieldset className="space-y-2">
- <legend className="text-body font-medium">{label}</legend>
- {values.map((value, index) => (
- <div key={index} className="flex gap-2">
- <Input
- aria-label={`${label} ${index + 1}`}
- name={`mcp-argument-${index}`}
- autoComplete="off"
- spellCheck={false}
- value={value}
- onChange={(event) =>
- onChange(values.map((item, itemIndex) =>
- itemIndex === index ? event.target.value : item,
- ))
- }
- />
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- aria-label={`${removeLabel} ${index + 1}`}
- onClick={() => onChange(values.filter((_, itemIndex) => itemIndex !== index))}
- >
- <Trash2 aria-hidden="true" />
- </Button>
+ <div role="group" aria-labelledby={labelId} className="space-y-3">
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <p id={labelId} className="text-body font-medium">
+ {label}
+ </p>
+ <p className="mt-1 text-caption text-muted-foreground">{description}</p>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="shrink-0"
+ onClick={() => onChange([...values, ""])}
+ >
+ <Plus aria-hidden="true" />
+ {addLabel}
+ </Button>
+ </div>
+ {values.length > 0 ? (
+ <div className="space-y-2">
+ {values.map((value, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <Input
+ aria-label={`${label} ${index + 1}`}
+ name={`mcp-argument-${index}`}
+ autoComplete="off"
+ spellCheck={false}
+ value={value}
+ onChange={(event) =>
+ onChange(values.map((item, itemIndex) =>
+ itemIndex === index ? event.target.value : item,
+ ))
+ }
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="shrink-0 text-muted-foreground hover:text-destructive"
+ aria-label={`${removeLabel} ${index + 1}`}
+ onClick={() =>
+ onChange(values.filter((_, itemIndex) => itemIndex !== index))
+ }
+ >
+ <Trash2 aria-hidden="true" />
+ </Button>
+ </div>
+ ))}
</div>
- ))}
- <Button type="button" variant="outline" size="sm" onClick={() => onChange([...values, ""])}>
- <Plus aria-hidden="true" />
- {addLabel}
- </Button>
- </fieldset>
+ ) : null}
+ </div>
);
}
function KeyValueEditor({
label,
+ description,
addLabel,
removeLabel,
+ keyLabel,
+ valueLabel,
rows,
onChange,
}: {
label: string;
+ description: string;
addLabel: string;
removeLabel: string;
+ keyLabel: string;
+ valueLabel: string;
rows: KeyValue[];
onChange: (rows: KeyValue[]) => void;
}) {
- // `label` / `addLabel` / `removeLabel` arrive translated from the caller, but
- // the per-row strings are this component's own — including the aria-labels,
- // which used to concatenate an English word onto a translated label and read
- // out half in each language.
- const { t } = useT("agents");
+ const labelId = useId();
return (
- <fieldset className="space-y-2">
- <legend className="text-body font-medium">{label}</legend>
- {rows.map((row, index) => (
- <div key={index} className="grid grid-cols-[1fr_1fr_auto] gap-2">
- <Input
- aria-label={t(($) => $.tab_body.mcp_config.dialog_pair_key_aria, {
- label,
- index: index + 1,
- })}
- name={`mcp-pair-key-${index}`}
- autoComplete="off"
- spellCheck={false}
- value={row.key}
- onChange={(event) =>
- onChange(rows.map((item, itemIndex) =>
- itemIndex === index ? { ...item, key: event.target.value } : item,
- ))
- }
- placeholder={t(
- ($) => $.tab_body.mcp_config.dialog_pair_key_placeholder,
- )}
- />
- <Input
- aria-label={t(($) => $.tab_body.mcp_config.dialog_pair_value_aria, {
- label,
- index: index + 1,
- })}
- name={`mcp-pair-value-${index}`}
- autoComplete="off"
- spellCheck={false}
- value={row.value}
- onChange={(event) =>
- onChange(rows.map((item, itemIndex) =>
- itemIndex === index ? { ...item, value: event.target.value } : item,
- ))
- }
- placeholder={t(
- ($) => $.tab_body.mcp_config.dialog_pair_value_placeholder,
- )}
- />
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- aria-label={`${removeLabel} ${index + 1}`}
- onClick={() => onChange(rows.filter((_, itemIndex) => itemIndex !== index))}
- >
- <Trash2 aria-hidden="true" />
- </Button>
+ <div role="group" aria-labelledby={labelId} className="space-y-3">
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <p id={labelId} className="text-body font-medium">
+ {label}
+ </p>
+ <p className="mt-1 text-caption text-muted-foreground">{description}</p>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="shrink-0"
+ onClick={() => onChange([...rows, { key: "", value: "" }])}
+ >
+ <Plus aria-hidden="true" />
+ {addLabel}
+ </Button>
+ </div>
+ {rows.length > 0 ? (
+ <div className="space-y-2">
+ {rows.map((row, index) => (
+ <div key={index} className="flex items-start gap-2">
+ <div className="grid min-w-0 flex-1 gap-2 sm:grid-cols-2">
+ <Input
+ aria-label={`${label}: ${keyLabel} ${index + 1}`}
+ name={`mcp-pair-key-${index}`}
+ autoComplete="off"
+ spellCheck={false}
+ value={row.key}
+ onChange={(event) =>
+ onChange(rows.map((item, itemIndex) =>
+ itemIndex === index
+ ? { ...item, key: event.target.value }
+ : item,
+ ))
+ }
+ />
+ <Input
+ aria-label={`${label}: ${valueLabel} ${index + 1}`}
+ name={`mcp-pair-value-${index}`}
+ autoComplete="off"
+ spellCheck={false}
+ value={row.value}
+ onChange={(event) =>
+ onChange(rows.map((item, itemIndex) =>
+ itemIndex === index
+ ? { ...item, value: event.target.value }
+ : item,
+ ))
+ }
+ />
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="shrink-0 text-muted-foreground hover:text-destructive"
+ aria-label={`${removeLabel} ${index + 1}`}
+ onClick={() =>
+ onChange(rows.filter((_, itemIndex) => itemIndex !== index))
+ }
+ >
+ <Trash2 aria-hidden="true" />
+ </Button>
+ </div>
+ ))}
</div>
- ))}
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => onChange([...rows, { key: "", value: "" }])}
- >
- <Plus aria-hidden="true" />
- {addLabel}
- </Button>
- </fieldset>
+ ) : null}
+ </div>
);
}
diff --git a/packages/views/common/mcp-server-row.test.tsx b/packages/views/common/mcp-server-row.test.tsx
new file mode 100644
index 0000000000..d7f258641b
--- /dev/null
+++ b/packages/views/common/mcp-server-row.test.tsx
@@ -0,0 +1,121 @@
+// @vitest-environment jsdom
+
+import type { ReactElement, ReactNode } from "react";
+import { describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+vi.mock("@multica/ui/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
+ TooltipTrigger: ({ render }: { render: ReactElement }) => render,
+ TooltipContent: ({ children }: { children: ReactNode }) => (
+ <span data-testid="tooltip-content">{children}</span>
+ ),
+}));
+
+import { McpRemoveButton, McpServerRow } from "./mcp-server-row";
+
+describe("McpServerRow", () => {
+ it("keeps concise tooltip text separate from row-specific accessible names", () => {
+ render(
+ <ul>
+ <McpServerRow
+ name="linear"
+ transport="stdio"
+ canManage
+ labels={{
+ rename: "Rename",
+ renameAria: "Rename server",
+ renameSave: "Save name",
+ renameCancel: "Cancel rename",
+ configure: "Edit configuration",
+ configureAria: "Edit configuration",
+ remove: "Delete",
+ removeAria: "Delete MCP server",
+ }}
+ configureKind="edit"
+ onRenameStart={vi.fn()}
+ onConfigure={vi.fn()}
+ onRemove={vi.fn()}
+ />
+ </ul>,
+ );
+
+ expect(
+ screen.getAllByTestId("tooltip-content").map((node) => node.textContent),
+ ).toEqual(["STDIO", "Rename", "Edit configuration", "Delete"]);
+ expect(
+ screen.getByRole("button", { name: "Rename server linear" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Edit configuration linear" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Delete MCP server linear" }),
+ ).toBeInTheDocument();
+ });
+
+ it("cancels inline rename when Escape is pressed", async () => {
+ const user = userEvent.setup();
+ const onCancel = vi.fn();
+ render(
+ <ul>
+ <McpServerRow
+ name="linear"
+ transport="http"
+ canManage
+ rename={{
+ draft: "linear-v2",
+ error: "",
+ pending: false,
+ onChange: vi.fn(),
+ onCancel,
+ onSubmit: vi.fn(),
+ }}
+ labels={{
+ rename: "Rename",
+ renameAria: "Rename server",
+ renameSave: "Save name",
+ renameCancel: "Cancel rename",
+ configure: "Edit configuration",
+ configureAria: "Edit configuration",
+ remove: "Delete",
+ removeAria: "Delete MCP server",
+ }}
+ configureKind="edit"
+ onRenameStart={vi.fn()}
+ onConfigure={vi.fn()}
+ onRemove={vi.fn()}
+ />
+ </ul>,
+ );
+
+ const input = screen.getByRole("textbox", { name: "Rename server" });
+ await user.click(input);
+ await user.keyboard("{Escape}");
+
+ expect(onCancel).toHaveBeenCalledOnce();
+ });
+});
+
+describe("McpRemoveButton", () => {
+ it("does not repeat the assigned server name in its tooltip", () => {
+ render(
+ <McpRemoveButton
+ ariaLabel="Remove shared-linear from this agent"
+ tooltipLabel="Remove"
+ onClick={vi.fn()}
+ />,
+ );
+
+ expect(screen.getByTestId("tooltip-content")).toHaveTextContent("Remove");
+ expect(screen.getByTestId("tooltip-content")).not.toHaveTextContent(
+ "shared-linear",
+ );
+ expect(
+ screen.getByRole("button", {
+ name: "Remove shared-linear from this agent",
+ }),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/common/mcp-server-row.tsx b/packages/views/common/mcp-server-row.tsx
new file mode 100644
index 0000000000..da930dc67a
--- /dev/null
+++ b/packages/views/common/mcp-server-row.tsx
@@ -0,0 +1,271 @@
+"use client";
+
+import { useId, type ReactNode } from "react";
+import {
+ Check,
+ Globe2,
+ Loader2,
+ Pencil,
+ RefreshCw,
+ Server,
+ SlidersHorizontal,
+ SquareTerminal,
+ Trash2,
+ X,
+} from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { mcpTransportLabel } from "./mcp-transport";
+
+export type McpServerRowLabels = {
+ rename: string;
+ renameAria: string;
+ renameSave: string;
+ renameCancel: string;
+ configure: string;
+ configureAria: string;
+ remove: string;
+ removeAria: string;
+};
+
+export type McpServerRenameState = {
+ draft: string;
+ error: string;
+ pending: boolean;
+ onChange: (value: string) => void;
+ onCancel: () => void;
+ onSubmit: () => void;
+};
+
+export function McpTransportIcon({ transport }: { transport: string }) {
+ const normalizedTransport = transport.trim().toLowerCase();
+ const transportLabel = mcpTransportLabel(transport);
+ const TransportIcon =
+ normalizedTransport === "stdio" || normalizedTransport === "local"
+ ? SquareTerminal
+ : normalizedTransport === "http" ||
+ normalizedTransport === "remote" ||
+ normalizedTransport === "streamable-http"
+ ? Globe2
+ : Server;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ tabIndex={0}
+ role="img"
+ aria-label={transportLabel}
+ className="flex size-9 shrink-0 items-center justify-center rounded-lg border border-surface-border bg-muted/40 text-muted-foreground outline-none transition-colors hover:bg-muted focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
+ >
+ <TransportIcon className="size-4" aria-hidden="true" />
+ </span>
+ }
+ />
+ <TooltipContent>{transportLabel}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+/** One destructive row action, with identical resting and hover treatment. */
+export function McpRemoveButton({
+ ariaLabel,
+ tooltipLabel,
+ disabled = false,
+ onClick,
+}: {
+ ariaLabel: string;
+ tooltipLabel: string;
+ disabled?: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
+ onClick={onClick}
+ disabled={disabled}
+ aria-label={ariaLabel}
+ >
+ <Trash2 />
+ </Button>
+ }
+ />
+ <TooltipContent>{tooltipLabel}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+/**
+ * Shared MCP inventory row used wherever Multica owns the server entry.
+ *
+ * Data writes remain the caller's responsibility: workspace settings replaces
+ * a write-only config, while an agent edits its readable local config. Keeping
+ * those semantics outside this component prevents the visual treatment and
+ * the security contract from becoming coupled again.
+ */
+export function McpServerRow({
+ name,
+ transport,
+ status,
+ canManage,
+ actionsDisabled = false,
+ rename,
+ labels,
+ configureKind,
+ onRenameStart,
+ onConfigure,
+ onRemove,
+}: {
+ name: string;
+ transport: string;
+ status?: ReactNode;
+ canManage: boolean;
+ actionsDisabled?: boolean;
+ rename?: McpServerRenameState;
+ labels: McpServerRowLabels;
+ configureKind: "edit" | "replace";
+ onRenameStart: () => void;
+ onConfigure: () => void;
+ onRemove: () => void;
+}) {
+ const errorId = `${useId()}-rename-error`;
+ const ConfigureIcon =
+ configureKind === "replace" ? RefreshCw : SlidersHorizontal;
+
+ return (
+ <li className="group flex min-h-16 items-center gap-3 px-4 py-3 transition-colors hover:bg-muted/30">
+ <McpTransportIcon transport={transport} />
+
+ <div className="min-w-0 flex-1 has-[form]:space-y-2">
+ <div className="flex min-w-0 items-center gap-2">
+ {rename ? (
+ <form
+ className="flex min-w-0 flex-1 items-start gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ rename.onSubmit();
+ }}
+ >
+ <div className="min-w-0 flex-1 sm:max-w-96">
+ <Input
+ autoFocus
+ className="bg-background"
+ value={rename.draft}
+ onChange={(event) => rename.onChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ rename.onCancel();
+ }
+ }}
+ aria-label={labels.renameAria}
+ aria-invalid={rename.error ? true : undefined}
+ aria-describedby={rename.error ? errorId : undefined}
+ disabled={rename.pending}
+ />
+ {rename.error ? (
+ <p
+ id={errorId}
+ role="alert"
+ className="mt-1 text-caption text-destructive"
+ >
+ {rename.error}
+ </p>
+ ) : null}
+ </div>
+ <Button
+ type="submit"
+ variant="secondary"
+ size="icon-sm"
+ className="mt-0.5"
+ disabled={rename.pending}
+ aria-label={labels.renameSave}
+ >
+ {rename.pending ? (
+ <Loader2 className="animate-spin motion-reduce:animate-none" />
+ ) : (
+ <Check />
+ )}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="mt-0.5 text-muted-foreground"
+ disabled={rename.pending}
+ onClick={rename.onCancel}
+ aria-label={labels.renameCancel}
+ >
+ <X />
+ </Button>
+ </form>
+ ) : (
+ <span className="truncate text-body font-medium">{name}</span>
+ )}
+ {status}
+ </div>
+ <p className="text-caption text-muted-foreground">
+ {mcpTransportLabel(transport)}
+ </p>
+ </div>
+
+ {canManage && !rename ? (
+ <div className="flex shrink-0 items-center gap-0.5 text-muted-foreground">
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ onClick={onRenameStart}
+ disabled={actionsDisabled}
+ aria-label={`${labels.renameAria} ${name}`}
+ >
+ <Pencil />
+ </Button>
+ }
+ />
+ <TooltipContent>{labels.rename}</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ onClick={onConfigure}
+ disabled={actionsDisabled}
+ aria-label={`${labels.configureAria} ${name}`}
+ >
+ <ConfigureIcon />
+ </Button>
+ }
+ />
+ <TooltipContent>{labels.configure}</TooltipContent>
+ </Tooltip>
+ <div className="mx-1 h-4 w-px bg-surface-border" aria-hidden="true" />
+ <McpRemoveButton
+ ariaLabel={`${labels.removeAria} ${name}`}
+ tooltipLabel={labels.remove}
+ disabled={actionsDisabled}
+ onClick={onRemove}
+ />
+ </div>
+ ) : null}
+ </li>
+ );
+}
diff --git a/packages/views/common/mcp-transport.ts b/packages/views/common/mcp-transport.ts
new file mode 100644
index 0000000000..9196b27dab
--- /dev/null
+++ b/packages/views/common/mcp-transport.ts
@@ -0,0 +1,17 @@
+/** User-facing protocol names shared by every MCP inventory and editor. */
+export function mcpTransportLabel(transport: string): string {
+ const normalized = transport.trim().toLowerCase();
+ switch (normalized) {
+ case "local":
+ case "stdio":
+ return "STDIO";
+ case "remote":
+ case "http":
+ case "streamable-http":
+ return "Streamable HTTP";
+ case "sse":
+ return "SSE";
+ default:
+ return transport.trim() || "Unknown";
+ }
+}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index feffaae8c5..5f2216a3e0 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -546,6 +546,7 @@
"workspace_removed_toast": "MCP server removed from this agent",
"workspace_added_toast": "MCP server added to this agent",
"workspace_remove_aria": "Remove {{name}} from this agent",
+ "workspace_remove_action": "Remove",
"workspace_toggle_aria": "Enable {{name}} for this agent",
"workspace_library_empty": "This workspace has no MCP servers to assign yet. Add them in workspace Settings → MCP.",
"workspace_none_assigned": "No workspace MCP servers assigned to this agent yet.",
@@ -564,50 +565,67 @@
"runtime_forbidden": "You don't have permission to view this runtime's MCP servers.",
"runtime_unsupported": "This runtime version cannot report its MCP inventory yet.",
"runtime_empty": "No MCP servers were found in the runtime's user configuration.",
+ "rename_server": "Rename server",
+ "rename_action": "Rename",
+ "rename_save": "Save name",
+ "rename_cancel": "Cancel rename",
+ "edit_config": "Edit configuration",
"edit_aria": "Edit MCP server",
"delete_aria": "Delete MCP server",
+ "delete_action_short": "Delete",
"added_toast": "MCP server added",
"updated_toast": "MCP server updated",
+ "renamed_toast": "MCP server renamed",
+ "rename_failed_toast": "Could not rename the MCP server",
"deleted_toast": "MCP server deleted",
"delete_failed_toast": "Failed to delete MCP server",
"dialog_add_title": "Add MCP Server",
"dialog_edit_title": "Edit MCP Server",
- "dialog_description": "Use the guided form or edit the configuration for this single server as JSON.",
- "dialog_name_label": "Name",
- "dialog_name_placeholder": "e.g. context7",
+ "dialog_edit_title_named": "Edit configuration for {{name}}",
+ "dialog_replace_title": "Replace configuration for {{name}}",
+ "dialog_description": "Choose a connection method and enter its settings. Switch to JSON for advanced configuration.",
+ "dialog_replace_description": "To protect sensitive information, saved values aren't shown again. Enter the complete new configuration. Existing agent assignments will stay the same.",
+ "dialog_name_label": "Server name",
+ "dialog_name_hint": "Used to identify this server at runtime. Use letters, numbers, hyphens, and underscores.",
"dialog_name_required": "Enter a server name.",
"dialog_name_invalid": "Use only letters, numbers, hyphens, and underscores.",
"dialog_name_duplicate": "A server with this name already exists.",
- "dialog_form_tab": "Form",
+ "dialog_editor_label": "Configuration",
+ "dialog_form_tab": "Visual editor",
"dialog_json_tab": "JSON",
"dialog_type_label": "Transport",
"dialog_type_stdio": "STDIO",
+ "dialog_type_stdio_hint": "Start a local command-line process",
"dialog_type_http": "Streamable HTTP",
+ "dialog_type_http_hint": "Connect to a remote HTTP endpoint",
"dialog_command_label": "Command",
"dialog_command_required": "Enter the command used to launch this server.",
- "dialog_args_label": "Arguments",
+ "dialog_args_label": "Startup arguments",
+ "dialog_args_hint": "Passed to the command in this order.",
"dialog_add_arg": "Add argument",
"dialog_remove_arg": "Remove argument",
"dialog_env_label": "Environment variables",
+ "dialog_env_hint": "Injected only when this server starts.",
+ "dialog_env_key": "Variable name",
+ "dialog_value": "Value",
"dialog_add_env": "Add environment variable",
"dialog_remove_env": "Remove environment variable",
"dialog_url_label": "Server URL",
"dialog_url_required": "Enter the MCP server URL.",
"dialog_headers_label": "HTTP headers",
+ "dialog_headers_hint": "Sent with every HTTP request.",
+ "dialog_header_key": "Header name",
"dialog_add_header": "Add header",
"dialog_remove_header": "Remove header",
- "dialog_pair_key_placeholder": "Key",
- "dialog_pair_value_placeholder": "Value",
- "dialog_pair_key_aria": "{{label}} key {{index}}",
- "dialog_pair_value_aria": "{{label}} value {{index}}",
"dialog_native_json_hint": "This historical provider-native entry can be edited in JSON without changing its format.",
- "dialog_json_label": "Server configuration",
+ "dialog_json_label": "Configuration JSON",
"dialog_json_aria": "MCP server JSON configuration",
"dialog_json_object": "The server configuration must be a JSON object.",
"dialog_json_target": "The server configuration must include a command or URL.",
"dialog_cancel": "Cancel",
- "dialog_add_action": "Add Server",
- "dialog_update_action": "Save Changes",
+ "dialog_add_action": "Add",
+ "dialog_update_action": "Save",
+ "dialog_replace_action": "Replace configuration",
"delete_dialog_title": "Delete MCP Server?",
"delete_dialog_description": "{{name}} will no longer be available to this agent. Runtime servers are not affected.",
"delete_action": "Delete Server",
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 3b292b66b5..b68248fb61 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -290,10 +290,18 @@
"title": "MCP",
"description": "A library of MCP servers for this workspace. Adding one here gives it to no agent — an agent owner assigns it on the agent's own MCP tab, where it also gets a per-agent on/off toggle.",
"servers_title": "Shared servers",
- "write_only_note": "Saved configurations are write-only — urls, commands, headers, and environment values are never shown again, so editing a server replaces its configuration. Renaming is safe: agents keep their assignment.",
+ "write_only_note": "For security, saved URLs, commands, headers, and environment values aren't shown again. To change them, enter a complete new configuration. Renaming keeps the current configuration and agent assignments.",
"add_server": "Add server",
- "edit_server": "Edit server",
+ "rename_server": "Rename server",
+ "rename_action": "Rename",
+ "replace_config": "Replace configuration",
+ "rename_save": "Save name",
+ "rename_cancel": "Cancel rename",
+ "rename_required": "Enter a server name.",
+ "rename_invalid": "Use only letters, numbers, hyphens, and underscores.",
+ "rename_duplicate": "A server with this name already exists.",
"remove_server": "Remove server",
+ "remove_action": "Delete",
"empty_title": "No shared MCP servers",
"empty_description": "Add a server here, then assign it to the agents that should use it from their own MCP tab.",
"disabled_badge": "Disabled",
@@ -304,8 +312,10 @@
"cancel": "Cancel",
"added_toast": "Shared MCP server added",
"updated_toast": "Shared MCP server updated",
+ "renamed_toast": "Shared MCP server renamed",
"removed_toast": "Shared MCP server removed",
"save_failed_toast": "Could not save the shared MCP server",
+ "rename_failed_toast": "Could not rename the shared MCP server",
"remove_failed_toast": "Could not remove the shared MCP server"
},
"page": {
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index e2504d3a8a..2ba1a1b76a 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -427,6 +427,7 @@
"workspace_removed_toast": "このエージェントから MCP サーバーを削除しました",
"workspace_added_toast": "このエージェントに MCP サーバーを追加しました",
"workspace_remove_aria": "このエージェントから {{name}} を削除",
+ "workspace_remove_action": "削除",
"workspace_toggle_aria": "このエージェントで {{name}} を有効化",
"workspace_library_empty": "このワークスペースにはまだ割り当て可能な MCP サーバーがありません。ワークスペース設定 → MCP で追加してください。",
"workspace_none_assigned": "このエージェントにはまだワークスペース MCP サーバーが割り当てられていません。",
@@ -445,50 +446,67 @@
"runtime_forbidden": "このランタイムの MCP サーバーを表示する権限がありません。",
"runtime_unsupported": "このランタイムバージョンはまだ MCP 一覧を報告できません。",
"runtime_empty": "ランタイムのユーザー設定に MCP サーバーが見つかりませんでした。",
+ "rename_server": "MCP Server の名前を変更",
+ "rename_action": "名前を変更",
+ "rename_save": "名前を保存",
+ "rename_cancel": "名前の変更をキャンセル",
+ "edit_config": "設定を編集",
"edit_aria": "MCP Server を編集",
"delete_aria": "MCP Server を削除",
+ "delete_action_short": "削除",
"added_toast": "MCP Server を追加しました",
"updated_toast": "MCP Server を更新しました",
+ "renamed_toast": "MCP Server の名前を変更しました",
+ "rename_failed_toast": "MCP Server の名前を変更できませんでした",
"deleted_toast": "MCP Server を削除しました",
"delete_failed_toast": "MCP Server を削除できませんでした",
"dialog_add_title": "MCP Server を追加",
"dialog_edit_title": "MCP Server を編集",
- "dialog_description": "フォームまたは JSON で、この 1 つの Server の設定を編集します。",
- "dialog_name_label": "名前",
- "dialog_name_placeholder": "例: context7",
+ "dialog_edit_title_named": "{{name}} の設定を編集",
+ "dialog_replace_title": "{{name}} の設定を置き換え",
+ "dialog_description": "接続方式を選んで設定を入力します。高度な設定には JSON を使用できます。",
+ "dialog_replace_description": "機密情報を保護するため、保存済みの内容は再表示されません。新しい設定をすべて入力してください。既存のエージェントへの割り当ては変わりません。",
+ "dialog_name_label": "Server 名",
+ "dialog_name_hint": "Runtime でこの Server を識別する名前です。英数字、ハイフン、アンダースコアを使用できます。",
"dialog_name_required": "Server 名を入力してください。",
"dialog_name_invalid": "英数字、ハイフン、アンダースコアのみ使用できます。",
"dialog_name_duplicate": "同名の Server がすでに存在します。",
- "dialog_form_tab": "フォーム",
+ "dialog_editor_label": "設定方法",
+ "dialog_form_tab": "ビジュアル",
"dialog_json_tab": "JSON",
"dialog_type_label": "接続方式",
"dialog_type_stdio": "STDIO",
+ "dialog_type_stdio_hint": "ローカルのコマンドラインプロセスを起動",
"dialog_type_http": "Streamable HTTP",
+ "dialog_type_http_hint": "リモート HTTP サービスに接続",
"dialog_command_label": "起動コマンド",
"dialog_command_required": "Server を起動するコマンドを入力してください。",
- "dialog_args_label": "引数",
+ "dialog_args_label": "起動引数",
+ "dialog_args_hint": "この順序で起動コマンドに渡されます。",
"dialog_add_arg": "引数を追加",
"dialog_remove_arg": "引数を削除",
"dialog_env_label": "環境変数",
+ "dialog_env_hint": "この Server の起動時にのみ設定されます。",
+ "dialog_env_key": "変数名",
+ "dialog_value": "値",
"dialog_add_env": "環境変数を追加",
"dialog_remove_env": "環境変数を削除",
"dialog_url_label": "Server URL",
"dialog_url_required": "MCP Server URL を入力してください。",
"dialog_headers_label": "HTTP ヘッダー",
+ "dialog_headers_hint": "各 HTTP リクエストに付与されます。",
+ "dialog_header_key": "ヘッダー名",
"dialog_add_header": "ヘッダーを追加",
"dialog_remove_header": "ヘッダーを削除",
- "dialog_pair_key_placeholder": "キー",
- "dialog_pair_value_placeholder": "値",
- "dialog_pair_key_aria": "{{label}}:キー {{index}}",
- "dialog_pair_value_aria": "{{label}}:値 {{index}}",
"dialog_native_json_hint": "過去の Provider ネイティブ形式です。形式を変更せず JSON で編集できます。",
- "dialog_json_label": "単一 Server 設定",
+ "dialog_json_label": "設定 JSON",
"dialog_json_aria": "MCP Server JSON 設定",
"dialog_json_object": "Server 設定は JSON オブジェクトである必要があります。",
"dialog_json_target": "Server 設定には command または url が必要です。",
"dialog_cancel": "キャンセル",
- "dialog_add_action": "Server を追加",
- "dialog_update_action": "変更を保存",
+ "dialog_add_action": "追加",
+ "dialog_update_action": "保存",
+ "dialog_replace_action": "設定を置き換え",
"delete_dialog_title": "MCP Server を削除しますか?",
"delete_dialog_description": "{{name}} はこのエージェントで利用できなくなります。Runtime Server には影響しません。",
"delete_action": "Server を削除",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 76e741fa93..0a844f571e 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -290,10 +290,18 @@
"title": "MCP",
"description": "このワークスペースの MCP サーバーライブラリ。ここに追加してもどのエージェントにも割り当てられません。エージェントの所有者が各エージェントの MCP タブで割り当て、エージェントごとにオン/オフを切り替えます。",
"servers_title": "共有サーバー",
- "write_only_note": "保存された設定は書き込み専用です — url、コマンド、ヘッダー、環境変数は二度と表示されないため、サーバーの編集は設定の置き換えになります。名前の変更は安全です。割り当ては維持されます。",
+ "write_only_note": "機密情報を保護するため、保存した URL、コマンド、ヘッダー、環境変数は再表示されません。変更する場合は、新しい設定をすべて入力してください。名前だけを変更しても、現在の設定とエージェントへの割り当ては維持されます。",
"add_server": "サーバーを追加",
- "edit_server": "サーバーを編集",
+ "rename_server": "サーバー名を変更",
+ "rename_action": "名前を変更",
+ "replace_config": "設定を置き換え",
+ "rename_save": "名前を保存",
+ "rename_cancel": "名前の変更をキャンセル",
+ "rename_required": "サーバー名を入力してください。",
+ "rename_invalid": "英字、数字、ハイフン、アンダースコアのみ使用できます。",
+ "rename_duplicate": "同じ名前のサーバーがすでに存在します。",
"remove_server": "サーバーを削除",
+ "remove_action": "削除",
"empty_title": "共有 MCP サーバーはありません",
"empty_description": "まずここにサーバーを追加し、使用するエージェントの MCP タブから割り当ててください。",
"disabled_badge": "無効",
@@ -304,8 +312,10 @@
"cancel": "キャンセル",
"added_toast": "共有 MCP サーバーを追加しました",
"updated_toast": "共有 MCP サーバーを更新しました",
+ "renamed_toast": "共有 MCP サーバーの名前を変更しました",
"removed_toast": "共有 MCP サーバーを削除しました",
"save_failed_toast": "共有 MCP サーバーを保存できませんでした",
+ "rename_failed_toast": "共有 MCP サーバーの名前を変更できませんでした",
"remove_failed_toast": "共有 MCP サーバーを削除できませんでした"
},
"page": {
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 1cdae8410c..632ff7d747 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -435,6 +435,7 @@
"workspace_removed_toast": "이 에이전트에서 MCP 서버를 제거했습니다",
"workspace_added_toast": "이 에이전트에 MCP 서버를 추가했습니다",
"workspace_remove_aria": "이 에이전트에서 {{name}} 제거",
+ "workspace_remove_action": "제거",
"workspace_toggle_aria": "이 에이전트에서 {{name}} 활성화",
"workspace_library_empty": "이 워크스페이스에는 아직 할당할 MCP 서버가 없습니다. 워크스페이스 설정 → MCP에서 추가하세요.",
"workspace_none_assigned": "이 에이전트에 할당된 워크스페이스 MCP 서버가 아직 없습니다.",
@@ -453,50 +454,67 @@
"runtime_forbidden": "이 런타임의 MCP 서버를 볼 수 있는 권한이 없습니다.",
"runtime_unsupported": "이 런타임 버전은 아직 MCP 목록을 보고할 수 없습니다.",
"runtime_empty": "런타임 사용자 설정에서 MCP 서버를 찾지 못했습니다.",
+ "rename_server": "MCP Server 이름 변경",
+ "rename_action": "이름 변경",
+ "rename_save": "이름 저장",
+ "rename_cancel": "이름 변경 취소",
+ "edit_config": "설정 편집",
"edit_aria": "MCP Server 편집",
"delete_aria": "MCP Server 삭제",
+ "delete_action_short": "삭제",
"added_toast": "MCP Server를 추가했습니다",
"updated_toast": "MCP Server를 업데이트했습니다",
+ "renamed_toast": "MCP Server 이름을 변경했습니다",
+ "rename_failed_toast": "MCP Server 이름을 변경하지 못했습니다",
"deleted_toast": "MCP Server를 삭제했습니다",
"delete_failed_toast": "MCP Server를 삭제하지 못했습니다",
"dialog_add_title": "MCP Server 추가",
"dialog_edit_title": "MCP Server 편집",
- "dialog_description": "폼 또는 JSON으로 이 Server 하나의 설정을 편집하세요.",
- "dialog_name_label": "이름",
- "dialog_name_placeholder": "예: context7",
+ "dialog_edit_title_named": "{{name}} 설정 편집",
+ "dialog_replace_title": "{{name}} 설정 교체",
+ "dialog_description": "연결 방식을 선택하고 설정을 입력하세요. 고급 설정에는 JSON을 사용할 수 있습니다.",
+ "dialog_replace_description": "민감한 정보를 보호하기 위해 저장된 내용은 다시 표시되지 않습니다. 새 설정을 모두 입력하세요. 기존 에이전트 할당은 그대로 유지됩니다.",
+ "dialog_name_label": "Server 이름",
+ "dialog_name_hint": "Runtime에서 이 Server를 식별하는 이름입니다. 문자, 숫자, 하이픈, 밑줄을 사용할 수 있습니다.",
"dialog_name_required": "Server 이름을 입력하세요.",
"dialog_name_invalid": "문자, 숫자, 하이픈, 밑줄만 사용할 수 있습니다.",
"dialog_name_duplicate": "같은 이름의 Server가 이미 있습니다.",
- "dialog_form_tab": "폼 설정",
- "dialog_json_tab": "JSON 설정",
+ "dialog_editor_label": "설정 방식",
+ "dialog_form_tab": "비주얼 설정",
+ "dialog_json_tab": "JSON",
"dialog_type_label": "연결 방식",
"dialog_type_stdio": "STDIO",
+ "dialog_type_stdio_hint": "로컬 명령줄 프로세스 실행",
"dialog_type_http": "Streamable HTTP",
+ "dialog_type_http_hint": "원격 HTTP 서비스에 연결",
"dialog_command_label": "실행 명령",
"dialog_command_required": "Server를 실행할 명령을 입력하세요.",
- "dialog_args_label": "인자",
+ "dialog_args_label": "실행 인자",
+ "dialog_args_hint": "이 순서대로 실행 명령에 전달됩니다.",
"dialog_add_arg": "인자 추가",
"dialog_remove_arg": "인자 제거",
"dialog_env_label": "환경 변수",
+ "dialog_env_hint": "이 Server가 시작될 때만 주입됩니다.",
+ "dialog_env_key": "변수 이름",
+ "dialog_value": "값",
"dialog_add_env": "환경 변수 추가",
"dialog_remove_env": "환경 변수 제거",
"dialog_url_label": "Server URL",
"dialog_url_required": "MCP Server URL을 입력하세요.",
"dialog_headers_label": "HTTP 헤더",
+ "dialog_headers_hint": "각 HTTP 요청과 함께 전송됩니다.",
+ "dialog_header_key": "헤더 이름",
"dialog_add_header": "헤더 추가",
"dialog_remove_header": "헤더 제거",
- "dialog_pair_key_placeholder": "키",
- "dialog_pair_value_placeholder": "값",
- "dialog_pair_key_aria": "{{label}} 키 {{index}}",
- "dialog_pair_value_aria": "{{label}} 값 {{index}}",
"dialog_native_json_hint": "기존 Provider 네이티브 형식입니다. 형식을 변경하지 않고 JSON으로 편집할 수 있습니다.",
- "dialog_json_label": "단일 Server 설정",
+ "dialog_json_label": "설정 JSON",
"dialog_json_aria": "MCP Server JSON 설정",
"dialog_json_object": "Server 설정은 JSON 객체여야 합니다.",
"dialog_json_target": "Server 설정에 command 또는 url이 필요합니다.",
"dialog_cancel": "취소",
- "dialog_add_action": "Server 추가",
- "dialog_update_action": "변경 저장",
+ "dialog_add_action": "추가",
+ "dialog_update_action": "저장",
+ "dialog_replace_action": "설정 교체",
"delete_dialog_title": "MCP Server를 삭제할까요?",
"delete_dialog_description": "{{name}}은 더 이상 이 에이전트에서 사용할 수 없습니다. Runtime Server에는 영향을 주지 않습니다.",
"delete_action": "Server 삭제",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index c89cbcf901..d36319c7f8 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -290,10 +290,18 @@
"title": "MCP",
"description": "이 워크스페이스의 MCP 서버 라이브러리입니다. 여기에 추가해도 어떤 에이전트에도 할당되지 않으며, 에이전트 소유자가 해당 에이전트의 MCP 탭에서 할당하고 에이전트별로 켜고 끌 수 있습니다.",
"servers_title": "공유 서버",
- "write_only_note": "저장된 설정은 쓰기 전용이라 url, 명령, 헤더, 환경 변수는 다시 표시되지 않으므로 서버 편집은 설정을 교체하는 것입니다. 이름 변경은 안전하며 할당은 유지됩니다.",
+ "write_only_note": "민감한 정보를 보호하기 위해 저장된 URL, 명령, 헤더, 환경 변수는 다시 표시되지 않습니다. 변경하려면 새 설정을 모두 입력하세요. 이름만 바꾸면 현재 설정과 에이전트 할당은 그대로 유지됩니다.",
"add_server": "서버 추가",
- "edit_server": "서버 편집",
+ "rename_server": "서버 이름 변경",
+ "rename_action": "이름 변경",
+ "replace_config": "설정 교체",
+ "rename_save": "이름 저장",
+ "rename_cancel": "이름 변경 취소",
+ "rename_required": "서버 이름을 입력하세요.",
+ "rename_invalid": "문자, 숫자, 하이픈, 밑줄만 사용할 수 있습니다.",
+ "rename_duplicate": "같은 이름의 서버가 이미 있습니다.",
"remove_server": "서버 제거",
+ "remove_action": "삭제",
"empty_title": "공유 MCP 서버가 없습니다",
"empty_description": "여기에 서버를 추가한 뒤, 사용할 에이전트의 MCP 탭에서 할당하세요.",
"disabled_badge": "비활성화됨",
@@ -304,8 +312,10 @@
"cancel": "취소",
"added_toast": "공유 MCP 서버를 추가했습니다",
"updated_toast": "공유 MCP 서버를 업데이트했습니다",
+ "renamed_toast": "공유 MCP 서버 이름을 변경했습니다",
"removed_toast": "공유 MCP 서버를 제거했습니다",
"save_failed_toast": "공유 MCP 서버를 저장하지 못했습니다",
+ "rename_failed_toast": "공유 MCP 서버 이름을 변경하지 못했습니다",
"remove_failed_toast": "공유 MCP 서버를 제거하지 못했습니다"
},
"page": {
diff --git a/packages/views/locales/mcp.test.ts b/packages/views/locales/mcp.test.ts
new file mode 100644
index 0000000000..2aa38eb803
--- /dev/null
+++ b/packages/views/locales/mcp.test.ts
@@ -0,0 +1,106 @@
+// @vitest-environment node
+
+import { describe, expect, it } from "vitest";
+import { SUPPORTED_LOCALES } from "@multica/core/i18n";
+import { createI18n } from "@multica/core/i18n/react";
+import enAgents from "./en/agents.json";
+import enSettings from "./en/settings.json";
+import { RESOURCES } from "./index";
+
+const AGENT_KEYS = Object.keys(enAgents.tab_body.mcp_config) as Array<
+ keyof typeof enAgents.tab_body.mcp_config
+>;
+const SETTINGS_KEYS = Object.keys(enSettings.mcp) as Array<
+ keyof typeof enSettings.mcp
+>;
+
+describe("MCP locale contracts", () => {
+ it.each(SUPPORTED_LOCALES)(
+ "resolves every MCP message without fallback or unexpanded tokens in %s",
+ (locale) => {
+ const i18n = createI18n(locale, RESOURCES);
+ const messages = [
+ ...AGENT_KEYS.map((key) => ({
+ namespace: "agents",
+ key: `tab_body.mcp_config.${key}`,
+ source: enAgents.tab_body.mcp_config[key],
+ resolve: (params: Record<string, string>) =>
+ i18n.t(($) => $.tab_body.mcp_config[key], {
+ ns: "agents",
+ ...params,
+ }),
+ })),
+ ...SETTINGS_KEYS.map((key) => ({
+ namespace: "settings",
+ key: `mcp.${key}`,
+ source: enSettings.mcp[key],
+ resolve: (params: Record<string, string>) =>
+ i18n.t(($) => $.mcp[key], { ns: "settings", ...params }),
+ })),
+ ];
+ for (const { namespace, key, source, resolve } of messages) {
+ const context = `${locale}:${namespace}:${key}`;
+ // Check the selected bundle directly: an English fallback can make
+ // i18next.t appear successful after a translation has disappeared.
+ expect(i18n.getResource(locale, namespace, key), context).toBeTypeOf(
+ "string",
+ );
+ const tokens = [...source.matchAll(/\{\{(\w+)\}\}/g)].map(
+ (match) => match[1]!,
+ );
+ const params = Object.fromEntries(
+ tokens.map((token) => [token, `test-${token}`]),
+ );
+ const resolved = resolve(params);
+ expect(resolved.trim().length, context).toBeGreaterThan(0);
+ expect(resolved, context).not.toBe(key);
+ expect(resolved, context).not.toContain("{{");
+ for (const token of tokens) {
+ expect(resolved, context).toContain(`test-${token}`);
+ }
+ }
+ },
+ );
+
+ it.each([
+ ["en", "Rename", "Edit configuration", "Replace configuration"],
+ ["zh-Hans", "重命名", "编辑配置", "替换配置"],
+ ["ja", "名前を変更", "設定を編集", "設定を置き換え"],
+ ["ko", "이름 변경", "설정 편집", "설정 교체"],
+ ] as const)(
+ "distinguishes rename, readable editing, and replacement actions in %s",
+ (locale, rename, edit, replace) => {
+ const i18n = createI18n(locale, RESOURCES);
+ const agentT = i18n.getFixedT(locale, "agents");
+ const settingsT = i18n.getFixedT(locale, "settings");
+
+ expect(agentT(($) => $.tab_body.mcp_config.rename_action)).toBe(rename);
+ expect(settingsT(($) => $.mcp.rename_action)).toBe(rename);
+ expect(agentT(($) => $.tab_body.mcp_config.edit_config)).toBe(edit);
+ expect(agentT(($) => $.tab_body.mcp_config.dialog_replace_action)).toBe(
+ replace,
+ );
+ expect(settingsT(($) => $.mcp.replace_config)).toBe(replace);
+ expect(new Set([rename, edit, replace]).size).toBe(3);
+ },
+ );
+
+ it.each(SUPPORTED_LOCALES)(
+ "identifies the target server in edit and replacement titles in %s",
+ (locale) => {
+ const i18n = createI18n(locale, RESOURCES);
+ const name = "org.example-mcp";
+ const edit = i18n.t(($) => $.tab_body.mcp_config.dialog_edit_title_named, {
+ ns: "agents",
+ name,
+ });
+ const replace = i18n.t(($) => $.tab_body.mcp_config.dialog_replace_title, {
+ ns: "agents",
+ name,
+ });
+ expect(edit).toContain(name);
+ expect(replace).toContain(name);
+ expect(edit).not.toBe(replace);
+ },
+ );
+});
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 296f292cd5..6f293c9a3b 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -524,85 +524,103 @@
},
"mcp_config": {
"managed_title": "由 Multica 管理",
- "managed_empty": "还没有由 Multica 管理的 MCP Server。",
- "add_action": "添加 MCP",
- "agent_disabled_badge": "已为智能体关闭",
- "runtime_disabled_badge": "运行时中已关闭",
+ "managed_empty": "暂无由 Multica 管理的 MCP Server。",
+ "add_action": "添加 MCP Server",
+ "agent_disabled_badge": "已对该智能体关闭",
+ "runtime_disabled_badge": "已在运行时中关闭",
"runtime_overridden_badge": "已由 Multica 覆盖",
- "workspace_title": "来自工作区库",
- "workspace_action_failed": "更新该智能体的 MCP 服务失败",
- "workspace_removed_toast": "已从该智能体移除 MCP 服务",
- "workspace_added_toast": "已为该智能体添加 MCP 服务",
+ "workspace_title": "工作区 MCP Server",
+ "workspace_action_failed": "无法更新该智能体的 MCP Server",
+ "workspace_removed_toast": "已从该智能体移除 MCP Server",
+ "workspace_added_toast": "已为该智能体添加 MCP Server",
"workspace_remove_aria": "从该智能体移除 {{name}}",
+ "workspace_remove_action": "移除",
"workspace_toggle_aria": "为该智能体启用 {{name}}",
- "workspace_library_empty": "本工作区还没有可分配的 MCP 服务。请在工作区设置 → MCP 中添加。",
- "workspace_none_assigned": "还没有给该智能体分配工作区 MCP 服务。",
+ "workspace_library_empty": "工作区中暂无可分配的 MCP Server。请先前往“工作区设置 → MCP”添加。",
+ "workspace_none_assigned": "该智能体尚未分配工作区 MCP Server。",
"workspace_add_action": "从工作区添加",
- "workspace_loading": "正在加载已分配的服务…",
- "dialog_name_locked": "这里不能改名——改名会新增一个服务并把原来的留在那里。请改用移除后重新添加。",
+ "workspace_loading": "正在加载已分配的 MCP Server...",
+ "dialog_name_locked": "保存时不能修改名称。如需重命名,请删除后重新添加。",
"workspace_overridden_badge": "已覆盖",
"workspace_disabled_badge": "已禁用",
"runtime_title": "从运行时继承",
"runtime_title_named": "从 {{runtime}} 继承",
"refresh_action": "刷新",
- "runtime_missing": "请先分配一个本地运行时,以发现继承的 MCP Server。",
- "runtime_offline": "本地运行时处于离线状态,重新连接后即可刷新继承的 MCP Server。",
+ "runtime_missing": "请先为该智能体分配本地运行时,以发现继承的 MCP Server。",
+ "runtime_offline": "本地运行时已离线。重新连接后,可刷新继承的 MCP Server。",
"runtime_discovering": "正在从本地运行时发现 MCP Server…",
- "runtime_failed": "无法发现运行时 MCP Server,请重试。",
- "runtime_forbidden": "没有权限查看该运行时的 MCP Server。",
- "runtime_unsupported": "当前运行时版本暂时无法上报 MCP 清单。",
- "runtime_empty": "运行时的用户配置中没有发现 MCP Server。",
+ "runtime_failed": "无法获取运行时中的 MCP Server,请重试。",
+ "runtime_forbidden": "你没有权限查看该运行时中的 MCP Server。",
+ "runtime_unsupported": "当前运行时版本暂不支持上报 MCP Server 清单。",
+ "runtime_empty": "运行时的用户配置中暂无 MCP Server。",
+ "rename_server": "重命名 MCP Server",
+ "rename_action": "重命名",
+ "rename_save": "保存名称",
+ "rename_cancel": "取消重命名",
+ "edit_config": "编辑配置",
"edit_aria": "编辑 MCP Server",
"delete_aria": "删除 MCP Server",
+ "delete_action_short": "删除",
"added_toast": "已添加 MCP Server",
"updated_toast": "已更新 MCP Server",
+ "renamed_toast": "已重命名 MCP Server",
+ "rename_failed_toast": "无法重命名 MCP Server",
"deleted_toast": "已删除 MCP Server",
- "delete_failed_toast": "删除 MCP Server 失败",
+ "delete_failed_toast": "无法删除 MCP Server",
"dialog_add_title": "添加 MCP Server",
"dialog_edit_title": "编辑 MCP Server",
- "dialog_description": "普通用户可以使用表单,也可以用 JSON 编辑当前这一个 Server 的配置。",
+ "dialog_edit_title_named": "编辑 {{name}} 的配置",
+ "dialog_replace_title": "替换 {{name}} 的配置",
+ "dialog_description": "选择连接方式并填写配置信息。如需编辑完整配置,可切换到 JSON。",
+ "dialog_replace_description": "为保护敏感信息,已保存的内容不会再次显示。请填写一份完整的新配置;替换后,现有的智能体分配不会改变。",
"dialog_name_label": "名称",
- "dialog_name_placeholder": "例如 context7",
- "dialog_name_required": "请输入 Server 名称。",
+ "dialog_name_hint": "可使用字母、数字、连字符和下划线。",
+ "dialog_name_required": "请输入名称。",
"dialog_name_invalid": "名称只能包含字母、数字、连字符和下划线。",
- "dialog_name_duplicate": "已经存在同名的 Server。",
- "dialog_form_tab": "表单配置",
- "dialog_json_tab": "JSON 配置",
+ "dialog_name_duplicate": "已存在同名的 MCP Server。",
+ "dialog_editor_label": "配置方式",
+ "dialog_form_tab": "可视化配置",
+ "dialog_json_tab": "JSON",
"dialog_type_label": "连接方式",
"dialog_type_stdio": "STDIO",
+ "dialog_type_stdio_hint": "在本地启动命令行进程",
"dialog_type_http": "Streamable HTTP",
+ "dialog_type_http_hint": "连接远程 HTTP 服务",
"dialog_command_label": "启动命令",
- "dialog_command_required": "请输入启动该 Server 的命令。",
- "dialog_args_label": "参数",
+ "dialog_command_required": "请输入启动命令。",
+ "dialog_args_label": "启动参数",
+ "dialog_args_hint": "启动时,这些参数将按顺序追加到命令后。",
"dialog_add_arg": "添加参数",
"dialog_remove_arg": "移除参数",
"dialog_env_label": "环境变量",
+ "dialog_env_hint": "启动进程时,将注入这些环境变量。",
+ "dialog_env_key": "变量名",
+ "dialog_value": "值",
"dialog_add_env": "添加环境变量",
"dialog_remove_env": "移除环境变量",
- "dialog_url_label": "Server URL",
- "dialog_url_required": "请输入 MCP Server URL。",
- "dialog_headers_label": "HTTP Headers",
- "dialog_add_header": "添加 Header",
- "dialog_remove_header": "移除 Header",
- "dialog_pair_key_placeholder": "键",
- "dialog_pair_value_placeholder": "值",
- "dialog_pair_key_aria": "{{label}}:键 {{index}}",
- "dialog_pair_value_aria": "{{label}}:值 {{index}}",
- "dialog_native_json_hint": "这是历史 Provider 原生格式,将继续以 JSON 原样编辑,不会自动转换。",
- "dialog_json_label": "单个 Server 配置",
+ "dialog_url_label": "服务地址",
+ "dialog_url_required": "请输入服务地址。",
+ "dialog_headers_label": "HTTP 请求头",
+ "dialog_headers_hint": "连接时,这些请求头会随每个 HTTP 请求发送。",
+ "dialog_header_key": "请求头名称",
+ "dialog_add_header": "添加请求头",
+ "dialog_remove_header": "移除请求头",
+ "dialog_native_json_hint": "该 MCP Server 使用旧版 Provider 原生格式。使用 JSON 编辑时,格式不会自动转换。",
+ "dialog_json_label": "配置 JSON",
"dialog_json_aria": "MCP Server JSON 配置",
- "dialog_json_object": "Server 配置必须是 JSON 对象。",
- "dialog_json_target": "Server 配置必须包含 command 或 url。",
+ "dialog_json_object": "配置必须为 JSON 对象。",
+ "dialog_json_target": "配置中必须包含 command 或 url。",
"dialog_cancel": "取消",
- "dialog_add_action": "添加 Server",
- "dialog_update_action": "保存修改",
+ "dialog_add_action": "添加",
+ "dialog_update_action": "保存",
+ "dialog_replace_action": "替换配置",
"delete_dialog_title": "删除 MCP Server?",
- "delete_dialog_description": "{{name}} 将不再提供给该智能体;运行时中的 Server 不受影响。",
- "delete_action": "删除 Server",
+ "delete_dialog_description": "{{name}} 将从该智能体移除;从运行时继承的 MCP Server 不受影响。",
+ "delete_action": "删除 MCP Server",
"invalid_json": "JSON 无效:{{error}}",
- "save_failed_toast": "保存 MCP 配置失败",
- "redacted_title": "已配置——对你隐藏",
- "redacted_hint": "只有智能体所有者或工作区管理员可以读取该配置。"
+ "save_failed_toast": "无法保存 MCP 配置",
+ "redacted_title": "已配置,但当前不可见",
+ "redacted_hint": "只有智能体 owner 或工作区 admin 可以查看此配置。"
},
"composio_mcp": {
"subtitle": "勾选 toolkit,只在你自己(这个智能体的创建者)直接或通过下级智能体链路触发这个智能体时,才把它挂载为 MCP server。",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 43e1627ead..8fac8a548d 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -288,25 +288,35 @@
},
"mcp": {
"title": "MCP",
- "description": "本工作区的 MCP 服务库。在这里添加不会分配给任何智能体——由智能体的负责人在该智能体自己的 MCP 页里分配,并可按智能体单独开关。",
- "servers_title": "共享服务",
- "write_only_note": "已保存的配置是只写的——URL、命令、请求头和环境变量不会再次展示,因此编辑一个服务等于整条替换它的配置。改名是安全的:已分配的智能体不受影响。",
- "add_server": "添加服务",
- "edit_server": "编辑服务",
- "remove_server": "移除服务",
- "empty_title": "还没有共享的 MCP 服务",
- "empty_description": "先在这里添加服务,再到需要用它的智能体的 MCP 页里分配。",
+ "description": "在这里集中管理工作区的 MCP Server。添加后不会自动分配;智能体 owner 可在对应智能体的 MCP 页面中分配并单独启停。",
+ "servers_title": "共享 MCP Server",
+ "write_only_note": "为保护敏感信息,配置保存后不会再次显示。需要调整时,请填写一份完整的新配置;只修改名称不会影响当前配置和智能体分配。",
+ "add_server": "添加 MCP Server",
+ "rename_server": "重命名 MCP Server",
+ "rename_action": "重命名",
+ "replace_config": "替换配置",
+ "rename_save": "保存名称",
+ "rename_cancel": "取消重命名",
+ "rename_required": "请输入 MCP Server 名称。",
+ "rename_invalid": "仅可使用字母、数字、连字符和下划线。",
+ "rename_duplicate": "已存在同名 MCP Server。",
+ "remove_server": "移除 MCP Server",
+ "remove_action": "删除",
+ "empty_title": "暂无共享 MCP Server",
+ "empty_description": "先在这里添加 MCP Server,再前往对应智能体的 MCP 页面完成分配。",
"disabled_badge": "已禁用",
- "admin_only_note": "只有工作区 owner 和 admin 可以修改共享的 MCP 服务。",
- "delete_title": "移除共享服务?",
- "delete_description": "{{name}} 将从服务库以及所有已分配的智能体上移除,从各智能体的下一次运行起生效。",
+ "admin_only_note": "只有工作区 owner 和 admin 可以管理共享 MCP Server。",
+ "delete_title": "移除共享 MCP Server?",
+ "delete_description": "这会将 {{name}} 从工作区服务库和所有已分配的智能体中移除,从各智能体的下一次运行起生效。",
"delete_confirm": "移除",
"cancel": "取消",
- "added_toast": "已添加共享 MCP 服务",
- "updated_toast": "已更新共享 MCP 服务",
- "removed_toast": "已移除共享 MCP 服务",
- "save_failed_toast": "共享 MCP 服务保存失败",
- "remove_failed_toast": "共享 MCP 服务移除失败"
+ "added_toast": "已添加共享 MCP Server",
+ "updated_toast": "已更新共享 MCP Server",
+ "renamed_toast": "已重命名共享 MCP Server",
+ "removed_toast": "已移除共享 MCP Server",
+ "save_failed_toast": "无法保存共享 MCP Server",
+ "rename_failed_toast": "无法重命名共享 MCP Server",
+ "remove_failed_toast": "无法移除共享 MCP Server"
},
"page": {
"title": "设置",
diff --git a/packages/views/settings/components/mcp-tab.test.tsx b/packages/views/settings/components/mcp-tab.test.tsx
index c89f139488..66c30ad6fc 100644
--- a/packages/views/settings/components/mcp-tab.test.tsx
+++ b/packages/views/settings/components/mcp-tab.test.tsx
@@ -2,7 +2,7 @@
import type { ReactNode } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
@@ -81,13 +81,39 @@ describe("McpTab", () => {
mockDelete.mockResolvedValue({});
});
- it("lists the library servers with their transport", () => {
+ it("shows each transport as visible text beside its labeled icon", async () => {
+ const user = userEvent.setup();
+ data.servers[1] = server({ id: "srv-2", name: "local-tool", transport: "stdio", enabled: false });
render(<McpTab />, { wrapper: Wrapper });
expect(screen.getByText("linear")).toBeInTheDocument();
- expect(screen.getByText("HTTP")).toBeInTheDocument();
+ expect(screen.getByLabelText("Streamable HTTP")).toBeInTheDocument();
expect(screen.getByText("local-tool")).toBeInTheDocument();
- expect(screen.getByText("stdio")).toBeInTheDocument();
+ expect(screen.getByLabelText("STDIO")).toBeInTheDocument();
+ expect(screen.getByText("Streamable HTTP")).toBeVisible();
+ expect(screen.getByText("STDIO")).toBeVisible();
+ expect(screen.getByText("Disabled")).toBeVisible();
+ const replaceButton = screen.getByRole("button", {
+ name: "Replace configuration linear",
+ });
+ expect(replaceButton).toHaveTextContent(/^$/);
+ await user.hover(replaceButton);
+ expect(await screen.findByText("Replace configuration", { exact: true })).toBeVisible();
+ });
+
+ it.each([
+ ["linear", "Server URL", "https://mcp.example.com/mcp"],
+ ["local-tool", "Command", "npx"],
+ ])("provides a connection example when replacing %s", async (name, label, example) => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(
+ screen.getByRole("button", { name: `Replace configuration ${name}` }),
+ );
+
+ expect(screen.getByLabelText(label)).toHaveValue("");
+ expect(screen.getByLabelText(label)).toHaveAttribute("placeholder", example);
});
it("adds a server to the library", async () => {
@@ -95,85 +121,378 @@ describe("McpTab", () => {
render(<McpTab />, { wrapper: Wrapper });
await user.click(screen.getByRole("button", { name: /Add server/ }));
- await user.type(screen.getByLabelText("Name"), "github");
+ await user.type(screen.getByLabelText("Server name"), "github");
// The shared dialog defaults to the STDIO transport.
await user.type(screen.getByLabelText("Command"), "github-mcp");
- await user.click(screen.getByRole("button", { name: "Add Server" }));
+ await user.click(screen.getByRole("button", { name: "Add argument" }));
+ await user.type(screen.getByLabelText("Startup arguments 1"), " ");
+ await user.click(screen.getByRole("button", { name: "Add argument" }));
+ await user.type(screen.getByLabelText("Startup arguments 2"), "--stdio");
+ await user.click(
+ screen.getByRole("button", { name: "Add environment variable" }),
+ );
+ await user.type(
+ screen.getByLabelText("Environment variables: Variable name 1"),
+ "EMPTY_VALUE",
+ );
+ await user.type(
+ screen.getByLabelText("Environment variables: Value 1"),
+ " ",
+ );
+ await user.click(screen.getByRole("button", { name: "Add" }));
await waitFor(() =>
expect(mockCreate).toHaveBeenCalledWith(
expect.objectContaining({ name: "github" }),
),
);
- // The entry is sent on its own — the client never holds, and therefore
- // never resends, anything else.
+ // Every added row is explicit user input. Whitespace and empty values can
+ // carry meaning for process arguments and environment variables.
const call = mockCreate.mock.calls[0]![0] as { config: Record<string, unknown> };
- expect(call.config).not.toHaveProperty("mcpServers");
+ expect(call.config).toEqual({
+ command: "github-mcp",
+ args: [" ", "--stdio"],
+ env: { EMPTY_VALUE: " " },
+ });
+ });
+
+ it("opens a new shared dialog without displaying validation errors", async () => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: /Add server/ }));
+
+ expect(screen.getByLabelText("Server name")).not.toHaveAttribute("aria-invalid");
+ expect(screen.getByLabelText("Command")).not.toHaveAttribute("aria-invalid");
+ expect(screen.queryByText("Enter a server name.")).toBeNull();
+ expect(screen.queryByText(/Enter the command used/)).toBeNull();
+ });
+
+ it("waits for an explicit save attempt before showing inline validation", async () => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: /Add server/ }));
+ const nameInput = screen.getByLabelText("Server name");
+ await user.click(nameInput);
+ await user.tab();
+
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(nameInput).not.toHaveAttribute("aria-invalid");
+
+ await user.click(screen.getByRole("button", { name: "Add" }));
+
+ const error = screen.getByText("Enter a server name.");
+ expect(error).toHaveTextContent("Enter a server name.");
+ expect(nameInput).toHaveAttribute("aria-describedby", error.id);
+ expect(error.parentElement).toBe(nameInput.parentElement);
+ expect(nameInput).toHaveFocus();
+ });
+
+ it("focuses the missing connection field after a save attempt", async () => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: /Add server/ }));
+ await user.type(screen.getByLabelText("Server name"), "github");
+ await user.click(screen.getByRole("button", { name: "Add" }));
+
+ expect(screen.getByLabelText("Command")).toHaveFocus();
+ expect(
+ screen.getByText("Enter the command used to launch this server."),
+ ).toBeInTheDocument();
+ });
+
+ it("focuses a missing URL and clears the error when transport changes", async () => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: /Add server/ }));
+ await user.type(screen.getByLabelText("Server name"), "remote");
+ await user.click(screen.getByRole("button", { name: /^Streamable HTTP/ }));
+ await user.click(screen.getByRole("button", { name: "Add" }));
+
+ const urlInput = screen.getByLabelText("Server URL");
+ expect(urlInput).toHaveFocus();
+ expect(screen.getByText("Enter the MCP server URL.")).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /^STDIO/ }));
+ expect(screen.queryByText("Enter the MCP server URL.")).toBeNull();
+ expect(screen.getByLabelText("Command")).not.toHaveAttribute("aria-invalid");
+ });
+
+ it.each([
+ ["invalid name", "Use only letters, numbers, hyphens, and underscores."],
+ ["linear", "A server with this name already exists."],
+ ])("rejects the server name %s with its precise inline error", async (name, message) => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: /Add server/ }));
+ const nameInput = screen.getByLabelText("Server name");
+ await user.type(nameInput, name);
+ await user.type(screen.getByLabelText("Command"), "tool");
+ await user.click(screen.getByRole("button", { name: "Add" }));
+
+ const error = screen.getByText(message);
+ expect(nameInput).toHaveFocus();
+ expect(nameInput).toHaveAttribute("aria-describedby", error.id);
+ expect(mockCreate).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["[]", "The server configuration must be a JSON object."],
+ ["{}", "The server configuration must include a command or URL."],
+ ])("rejects semantic JSON error for %s", async (json, message) => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(screen.getByRole("button", { name: /Add server/ }));
+ await user.type(screen.getByLabelText("Server name"), "github");
+ await user.click(screen.getByRole("tab", { name: "JSON" }));
+ const jsonInput = screen.getByLabelText("MCP server JSON configuration");
+ fireEvent.change(jsonInput, { target: { value: json } });
+ await user.click(screen.getByRole("button", { name: "Add" }));
+
+ const error = screen.getByText(message);
+ expect(jsonInput).toHaveFocus();
+ expect(jsonInput).toHaveAttribute("aria-describedby", error.id);
+ expect(mockCreate).not.toHaveBeenCalled();
+ });
+
+ it("keeps the footer outside the scroll area and caps the dialog to the viewport", async () => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ const expectStableDialogLayout = () => {
+ const dialog = screen.getByRole("dialog");
+ const scrollArea = dialog.querySelector<HTMLElement>(
+ '[data-slot="mcp-dialog-scroll-area"]',
+ );
+ const footer = dialog.querySelector<HTMLElement>(
+ '[data-slot="mcp-dialog-footer"]',
+ );
+ const submit = screen.getByRole("button", { name: "Add" });
+
+ expect(dialog).toHaveClass("flex", "max-h-[88vh]", "flex-col");
+ expect(scrollArea).toHaveClass("overflow-y-auto");
+ expect(scrollArea).not.toContainElement(footer);
+ expect(footer).toHaveClass("shrink-0", "border-t", "bg-muted/30");
+ expect(submit).toHaveAttribute("form", scrollArea?.id);
+ };
+
+ await user.click(screen.getByRole("button", { name: /Add server/ }));
+ expectStableDialogLayout();
+
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+
+ await user.click(screen.getByRole("button", { name: /Add server/ }));
+ expectStableDialogLayout();
});
- // Renaming is safe in this model — assignments key off the server id — so
- // the name field stays editable and the update targets the opened entry.
- it("edits a library server by id, so a rename keeps its assignments", async () => {
+ it("renames a library server inline without replacing its config", async () => {
const user = userEvent.setup();
render(<McpTab />, { wrapper: Wrapper });
- await user.click(screen.getAllByRole("button", { name: "Edit server" })[0]!);
+ await user.click(
+ screen.getAllByRole("button", { name: /Rename server/ })[0]!,
+ );
- const nameInput = screen.getByLabelText("Name") as HTMLInputElement;
- expect(nameInput.value).toBe("linear");
- expect(nameInput).not.toHaveAttribute("readonly");
+ const nameInput = screen.getByRole("textbox", { name: "Rename server" });
+ expect(nameInput).toHaveValue("linear");
+ expect(screen.queryByRole("dialog")).toBeNull();
await user.clear(nameInput);
await user.type(nameInput, "linear-v2");
- await user.type(screen.getByLabelText("Server URL"), "https://linear-v2.example");
- await user.click(screen.getByRole("button", { name: "Save Changes" }));
+ await user.click(screen.getByRole("button", { name: "Save name" }));
await waitFor(() =>
- expect(mockUpdate).toHaveBeenCalledWith(
- expect.objectContaining({ serverId: "srv-1", name: "linear-v2" }),
- ),
+ expect(mockUpdate).toHaveBeenCalledWith({
+ serverId: "srv-1",
+ name: "linear-v2",
+ }),
);
expect(mockCreate).not.toHaveBeenCalled();
});
+ it("validates every inline rename branch and cancels a no-op", async () => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(
+ screen.getAllByRole("button", { name: /Rename server/ })[1]!,
+ );
+ const nameInput = screen.getByRole("textbox", { name: "Rename server" });
+
+ await user.clear(nameInput);
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+ expect(screen.getByText("Enter a server name.")).toBeInTheDocument();
+ expect(nameInput).toHaveAttribute("aria-invalid", "true");
+
+ await user.type(nameInput, "bad name");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+ expect(
+ screen.getByText("Use only letters, numbers, hyphens, and underscores."),
+ ).toBeInTheDocument();
+
+ await user.clear(nameInput);
+ await user.type(nameInput, "linear");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+
+ expect(
+ screen.getByText("A server with this name already exists."),
+ ).toBeInTheDocument();
+ expect(nameInput).toHaveAttribute("aria-invalid", "true");
+ expect(mockUpdate).not.toHaveBeenCalled();
+
+ await user.clear(nameInput);
+ await user.type(nameInput, "local-tool");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+ expect(screen.queryByRole("textbox", { name: "Rename server" })).toBeNull();
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { reason: "an API error", error: new Error("Rename failed"), message: "Rename failed" },
+ { reason: "an empty error", error: new Error(""), message: "Could not rename the shared MCP server" },
+ { reason: "a non-Error rejection", error: null, message: "Could not rename the shared MCP server" },
+ ])("keeps inline rename open after $reason", async ({ error, message }) => {
+ const user = userEvent.setup();
+ mockUpdate.mockRejectedValueOnce(error);
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(
+ screen.getAllByRole("button", { name: /Rename server/ })[0]!,
+ );
+ const nameInput = screen.getByRole("textbox", { name: "Rename server" });
+ await user.clear(nameInput);
+ await user.type(nameInput, "linear-v2");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(message);
+ expect(nameInput).toHaveValue("linear-v2");
+ expect(nameInput).not.toBeDisabled();
+ });
+
+ it("blocks competing library actions while an inline rename is pending", async () => {
+ const user = userEvent.setup();
+ let finishRename!: () => void;
+ mockUpdate.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishRename = () => resolve({});
+ }),
+ );
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(
+ screen.getAllByRole("button", { name: /Rename server/ })[0]!,
+ );
+ const nameInput = screen.getByRole("textbox", { name: "Rename server" });
+ await user.clear(nameInput);
+ await user.type(nameInput, "linear-v2");
+ await user.click(screen.getByRole("button", { name: "Save name" }));
+
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledOnce());
+ expect(nameInput).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Save name" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: "Cancel rename" })).toBeDisabled();
+ expect(screen.getByRole("button", { name: /Add server/ })).toBeDisabled();
+
+ finishRename();
+ await waitFor(() =>
+ expect(screen.queryByRole("textbox", { name: "Rename server" })).toBeNull(),
+ );
+ });
+
+ it("replaces the full config without sending a name change", async () => {
+ const user = userEvent.setup();
+ render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(
+ screen.getAllByRole("button", {
+ name: /^Replace configuration /,
+ })[0]!,
+ );
+
+ expect(
+ screen.getByRole("heading", { name: "Replace configuration for linear" }),
+ ).toBeInTheDocument();
+ expect(screen.queryByLabelText("Server name")).toBeNull();
+ expect(screen.queryByText("Name", { exact: true })).toBeNull();
+ expect(screen.getByRole("dialog")).toHaveTextContent("linear");
+ expect(screen.getByLabelText("Server URL")).toHaveValue("");
+
+ await user.type(screen.getByLabelText("Server URL"), "https://linear-v2.example");
+ await user.click(screen.getByRole("button", { name: "Replace configuration" }));
+
+ await waitFor(() =>
+ expect(mockUpdate).toHaveBeenCalledWith({
+ serverId: "srv-1",
+ config: { type: "http", url: "https://linear-v2.example" },
+ }),
+ );
+ });
+
+ it("keeps an in-progress replacement when the settings page rerenders", async () => {
+ const user = userEvent.setup();
+ const view = render(<McpTab />, { wrapper: Wrapper });
+
+ await user.click(
+ screen.getAllByRole("button", {
+ name: /^Replace configuration /,
+ })[0]!,
+ );
+ const urlInput = screen.getByLabelText("Server URL");
+ await user.type(urlInput, "https://draft.example/mcp");
+
+ view.rerender(<McpTab />);
+
+ expect(urlInput).toHaveValue("https://draft.example/mcp");
+ });
+
// The saved entry cannot be read back, but the safe summary still knows the
- // transport — so the empty form must open on the right one instead of
- // defaulting a stdio server to HTTP.
- it("opens the edit form on the server's own transport", async () => {
+ // transport — so the blank replacement form opens on the right one.
+ it("opens the replacement form on the server's own transport", async () => {
const user = userEvent.setup();
render(<McpTab />, { wrapper: Wrapper });
// Row 1 is the stdio server.
- await user.click(screen.getAllByRole("button", { name: "Edit server" })[1]!);
+ await user.click(
+ screen.getAllByRole("button", {
+ name: /^Replace configuration /,
+ })[1]!,
+ );
- expect(screen.getByRole("button", { name: "STDIO" })).toHaveAttribute(
+ expect(screen.getByRole("button", { name: /^STDIO/ })).toHaveAttribute(
"aria-pressed",
"true",
);
- expect(screen.getByLabelText("Command")).toBeInTheDocument();
+ expect(screen.getByLabelText("Command")).toHaveValue("");
});
- // Regression: the guided form only speaks stdio/http and REWRITES the entry
- // on save (`type: "http"`), so editing an SSE server through it would change
- // its protocol and can break the server. The server returns `sse`, so this is
- // reachable, not hypothetical — those entries take the JSON path instead.
+ // Unknown transports start in JSON because that best reflects the inventory,
+ // but replacement is explicit, so the user may intentionally switch to the
+ // visual editor and replace it with STDIO or HTTP.
it.each(["sse", "websocket"])(
- "edits a %s server through JSON, never the transport-rewriting form",
+ "starts a %s replacement in JSON while keeping the visual editor available",
async (transport) => {
const user = userEvent.setup();
data.servers = [server({ name: "streamy", transport })];
render(<McpTab />, { wrapper: Wrapper });
- await user.click(screen.getByRole("button", { name: "Edit server" }));
+ await user.click(
+ screen.getByRole("button", { name: /^Replace configuration / }),
+ );
expect(screen.getByRole("tab", { name: "JSON" })).toHaveAttribute(
"aria-selected",
"true",
);
- // Not merely unselected: switching to the form would rewrite the entry.
- expect(screen.getByRole("tab", { name: "Form" })).toHaveAttribute(
+ expect(screen.getByRole("tab", { name: "Visual editor" })).toHaveAttribute(
"aria-disabled",
- "true",
+ "false",
);
expect(screen.queryByLabelText("Server URL")).toBeNull();
},
@@ -183,7 +502,9 @@ describe("McpTab", () => {
const user = userEvent.setup();
render(<McpTab />, { wrapper: Wrapper });
- await user.click(screen.getAllByRole("button", { name: "Remove server" })[0]!);
+ await user.click(
+ screen.getAllByRole("button", { name: /Remove server/ })[0]!,
+ );
await user.click(screen.getByRole("button", { name: "Remove" }));
await waitFor(() => expect(mockDelete).toHaveBeenCalledWith("srv-1"));
@@ -196,8 +517,11 @@ describe("McpTab", () => {
// The inventory itself stays visible — it carries no credential material.
expect(screen.getByText("linear")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: /Add server/ })).toBeNull();
- expect(screen.queryByRole("button", { name: "Edit server" })).toBeNull();
- expect(screen.queryByRole("button", { name: "Remove server" })).toBeNull();
+ expect(screen.queryByRole("button", { name: /Rename server/ })).toBeNull();
+ expect(
+ screen.queryByRole("button", { name: /^Replace configuration / }),
+ ).toBeNull();
+ expect(screen.queryByRole("button", { name: /Remove server/ })).toBeNull();
expect(
screen.getByText(/Only workspace owners and admins/),
).toBeInTheDocument();
diff --git a/packages/views/settings/components/mcp-tab.tsx b/packages/views/settings/components/mcp-tab.tsx
index d8ae1c7dd3..e262fded0a 100644
--- a/packages/views/settings/components/mcp-tab.tsx
+++ b/packages/views/settings/components/mcp-tab.tsx
@@ -1,7 +1,7 @@
"use client";
import { useMemo, useState } from "react";
-import { Loader2, Pencil, Plus, Server, Trash2 } from "lucide-react";
+import { Loader2, Plus, Server } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import {
@@ -27,6 +27,7 @@ import {
import type { WorkspaceMcpServer } from "@multica/core/types";
import { McpServerDialog } from "../../agents/components/tabs/mcp-server-dialog";
import type { ManagedMcpServer } from "../../agents/components/tabs/mcp-config-model";
+import { McpServerRow } from "../../common/mcp-server-row";
import { useT } from "../../i18n";
import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";
@@ -41,9 +42,9 @@ import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";
* agent implicitly.
* - The stored configuration is WRITE-ONLY. The API returns names and
* transports, never urls / commands / headers / env, so there is no
- * "current value" to prefill and editing a server means supplying its
- * configuration again. The UI says so rather than pretending the empty form
- * is the saved state.
+ * "current value" to prefill and replacing a server means supplying its
+ * complete configuration again. Renaming stays separate and never touches
+ * the write-only entry.
*/
export function McpTab() {
const { t } = useT("settings");
@@ -58,7 +59,7 @@ export function McpTab() {
const updateServer = useUpdateWorkspaceMcpServer(wsId);
const deleteServer = useDeleteWorkspaceMcpServer(wsId);
- const servers = serversQuery.data ?? [];
+ const servers = useMemo(() => serversQuery.data ?? [], [serversQuery.data]);
const existingNames = useMemo(
() => new Set(servers.map((server) => server.name)),
[servers],
@@ -68,6 +69,11 @@ export function McpTab() {
const [editingServer, setEditingServer] = useState<WorkspaceMcpServer | null>(
null,
);
+ const [renamingServer, setRenamingServer] =
+ useState<WorkspaceMcpServer | null>(null);
+ const [renameDraft, setRenameDraft] = useState("");
+ const [renameError, setRenameError] = useState("");
+ const [renamePending, setRenamePending] = useState(false);
const [deletingServer, setDeletingServer] = useState<WorkspaceMcpServer | null>(
null,
);
@@ -76,17 +82,21 @@ export function McpTab() {
// entry to prefill. Here there is nothing to prefill — an edit always
// starts from an empty form and REPLACES the entry. The transport still
// comes from the safe summary so the form opens on the right one.
- const dialogServer: ManagedMcpServer | null = editingServer
- ? {
- name: editingServer.name,
- config: {},
- container: "mcpServers",
- transport: editingServer.transport,
- // The library has no per-agent toggle; this field only feeds the
- // dialog's shape.
- enabled: true,
- }
- : null;
+ const dialogServer: ManagedMcpServer | null = useMemo(
+ () =>
+ editingServer
+ ? {
+ name: editingServer.name,
+ config: {},
+ container: "mcpServers",
+ transport: editingServer.transport,
+ // The library has no per-agent toggle; this field only feeds the
+ // dialog's shape.
+ enabled: true,
+ }
+ : null,
+ [editingServer],
+ );
const handleSaveServer = async (
name: string,
@@ -94,9 +104,7 @@ export function McpTab() {
) => {
try {
if (editingServer) {
- // Renaming is safe here: assignments key off the server id, so an
- // agent that uses this server keeps using it.
- await updateServer.mutateAsync({ serverId: editingServer.id, name, config });
+ await updateServer.mutateAsync({ serverId: editingServer.id, config });
} else {
await createServer.mutateAsync({ name, config });
}
@@ -115,6 +123,59 @@ export function McpTab() {
}
};
+ const startRename = (server: WorkspaceMcpServer) => {
+ if (renamePending) return;
+ setRenamingServer(server);
+ setRenameDraft(server.name);
+ setRenameError("");
+ };
+
+ const cancelRename = () => {
+ if (renamePending) return;
+ setRenamingServer(null);
+ setRenameDraft("");
+ setRenameError("");
+ };
+
+ const handleRename = async () => {
+ if (!renamingServer || renamePending) return;
+ const name = renameDraft.trim();
+ if (name === "") {
+ setRenameError(t(($) => $.mcp.rename_required));
+ return;
+ }
+ if (!/^[A-Za-z0-9_-]+$/.test(name)) {
+ setRenameError(t(($) => $.mcp.rename_invalid));
+ return;
+ }
+ if (name !== renamingServer.name && existingNames.has(name)) {
+ setRenameError(t(($) => $.mcp.rename_duplicate));
+ return;
+ }
+ if (name === renamingServer.name) {
+ cancelRename();
+ return;
+ }
+
+ setRenamePending(true);
+ try {
+ await updateServer.mutateAsync({ serverId: renamingServer.id, name });
+ toast.success(t(($) => $.mcp.renamed_toast));
+ setRenamingServer(null);
+ setRenameDraft("");
+ setRenameError("");
+ } catch (error) {
+ const message =
+ error instanceof Error && error.message
+ ? error.message
+ : t(($) => $.mcp.rename_failed_toast);
+ setRenameError(message);
+ toast.error(message);
+ } finally {
+ setRenamePending(false);
+ }
+ };
+
const handleDelete = async () => {
if (!deletingServer) return;
try {
@@ -142,7 +203,9 @@ export function McpTab() {
canManage ? (
<Button
size="sm"
+ disabled={renamePending}
onClick={() => {
+ cancelRename();
setEditingServer(null);
setEditorOpen(true);
}}
@@ -173,13 +236,53 @@ export function McpTab() {
{servers.map((server) => (
<McpServerRow
key={server.name}
- server={server}
+ name={server.name}
+ transport={server.transport}
+ status={
+ server.enabled === false ? (
+ <Badge variant="secondary">
+ {t(($) => $.mcp.disabled_badge)}
+ </Badge>
+ ) : undefined
+ }
canManage={canManage}
- onEdit={() => {
+ actionsDisabled={renamePending}
+ rename={
+ renamingServer?.id === server.id
+ ? {
+ draft: renameDraft,
+ error: renameError,
+ pending: renamePending,
+ onChange: (value) => {
+ setRenameDraft(value);
+ setRenameError("");
+ },
+ onCancel: cancelRename,
+ onSubmit: () => void handleRename(),
+ }
+ : undefined
+ }
+ labels={{
+ rename: t(($) => $.mcp.rename_action),
+ renameAria: t(($) => $.mcp.rename_server),
+ renameSave: t(($) => $.mcp.rename_save),
+ renameCancel: t(($) => $.mcp.rename_cancel),
+ configure: t(($) => $.mcp.replace_config),
+ configureAria: t(($) => $.mcp.replace_config),
+ remove: t(($) => $.mcp.remove_action),
+ removeAria: t(($) => $.mcp.remove_server),
+ }}
+ configureKind="replace"
+ onRenameStart={() => startRename(server)}
+ onConfigure={() => {
+ cancelRename();
setEditingServer(server);
setEditorOpen(true);
}}
- onDelete={() => setDeletingServer(server)}
+ onRemove={() => {
+ cancelRename();
+ setDeletingServer(server);
+ }}
/>
))}
</ul>
@@ -196,6 +299,7 @@ export function McpTab() {
open={editorOpen}
server={dialogServer}
existingNames={existingNames}
+ replacementMode={editingServer !== null}
onOpenChange={setEditorOpen}
onSave={handleSaveServer}
/>
@@ -235,69 +339,3 @@ export function McpTab() {
</SettingsTab>
);
}
-
-function McpServerRow({
- server,
- canManage,
- onEdit,
- onDelete,
-}: {
- server: WorkspaceMcpServer;
- canManage: boolean;
- onEdit: () => void;
- onDelete: () => void;
-}) {
- const { t } = useT("settings");
- return (
- <li className="flex items-center gap-3 px-4 py-3">
- <div className="min-w-0 flex-1">
- <div className="flex min-w-0 items-center gap-2">
- <span className="truncate text-body font-medium">{server.name}</span>
- {server.enabled === false ? (
- <Badge variant="secondary">{t(($) => $.mcp.disabled_badge)}</Badge>
- ) : null}
- </div>
- <p className="mt-0.5 text-caption text-muted-foreground">
- {transportLabel(server.transport)}
- </p>
- </div>
- {canManage ? (
- <div className="flex shrink-0 items-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- onClick={onEdit}
- aria-label={t(($) => $.mcp.edit_server)}
- >
- <Pencil className="h-4 w-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={onDelete}
- aria-label={t(($) => $.mcp.remove_server)}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
- ) : null}
- </li>
- );
-}
-
-/**
- * `transport` is a server-driven string, so an unknown value from a newer
- * backend renders as itself instead of disappearing.
- */
-function transportLabel(transport: string): string {
- switch (transport) {
- case "stdio":
- return "stdio";
- case "http":
- return "HTTP";
- case "sse":
- return "SSE";
- default:
- return transport || "unknown";
- }
-}
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index 0633316cff..7009c55d00 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -2032,6 +2032,29 @@ func TestUpdateAgentMcpConfigObjectUpdatesValue(t *testing.T) {
assertJSONEqual(t, fetchAgentMcpConfig(t, agentID), `{"preset":"new"}`)
}
+func TestUpdateAgentMcpConfigPreservesBoundaryEmptyArguments(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "Handler Mcp Empty Args", nil)
+ want := `{"mcpServers":{"fetch":{"command":"uvx","args":["","2222","","333",""]}}}`
+
+ req := newRequest("PUT", "/api/agents/"+agentID, map[string]any{
+ "mcp_config": map[string]any{
+ "mcpServers": map[string]any{
+ "fetch": map[string]any{
+ "command": "uvx",
+ "args": []string{"", "2222", "", "333", ""},
+ },
+ },
+ },
+ })
+ req = withURLParam(req, "id", agentID)
+ w := testutil.Call(t, testHandler.UpdateAgent, req).Want(http.StatusOK)
+
+ var updated AgentResponse
+ w.JSON(&updated)
+ assertJSONEqual(t, updated.McpConfig, want)
+ assertJSONEqual(t, fetchAgentMcpConfig(t, agentID), want)
+}
+
func TestCreateAgentMcpConfigNullStoresSQLNull(t *testing.T) {
req := newRequest("POST", "/api/agents", map[string]any{
"name": "Handler Mcp Create Null",