Skip to content

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

Go

feat: redesign agent Skills and MCP capabilities (#5277)

Jiayuan Zhanga14098288be4
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index ac0ef1bd42..8bbd867fe5 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1711,6 +1711,19 @@ export class ApiClient {
});
}
+ async setAgentSkillEnabled(agentId: string, skillId: string, enabled: boolean): Promise<void> {
+ await this.fetch(`/api/agents/${agentId}/skills/${skillId}/enabled`, {
+ method: "PUT",
+ body: JSON.stringify({ enabled }),
+ });
+ }
+
+ async removeAgentSkill(agentId: string, skillId: string): Promise<void> {
+ await this.fetch(`/api/agents/${agentId}/skills/${skillId}`, {
+ method: "DELETE",
+ });
+ }
+
// Personal Access Tokens
async listPersonalAccessTokens(): Promise<PersonalAccessToken[]> {
return this.fetch("/api/tokens");
diff --git a/packages/core/runtimes/local-skills.ts b/packages/core/runtimes/local-skills.ts
index f0c711f842..7be65e4f0f 100644
--- a/packages/core/runtimes/local-skills.ts
+++ b/packages/core/runtimes/local-skills.ts
@@ -48,6 +48,8 @@ export async function resolveRuntimeLocalSkills(
return {
skills: current.skills ?? [],
supported: current.supported,
+ mcpServers: current.mcp_servers ?? [],
+ mcpSupported: current.mcp_supported === true,
};
}
@@ -101,3 +103,8 @@ export function runtimeLocalSkillsOptions(runtimeId: string | null | undefined)
retry: false,
});
}
+
+// The daemon returns both local skills and a redacted MCP inventory from the
+// same round trip. Keep the original export for import flows and use this
+// capability-oriented alias on Agent detail surfaces.
+export const runtimeCapabilitiesOptions = runtimeLocalSkillsOptions;
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 79d0d2ff0c..3980d370ec 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -409,6 +409,8 @@ export interface AgentSkillSummary {
id: string;
name: string;
description: string;
+ /** Older servers omit this field; consumers must treat that as enabled. */
+ enabled?: boolean;
}
export interface CreateAgentRequest {
@@ -624,6 +626,8 @@ export interface SkillSummary {
created_by: string | null;
created_at: string;
updated_at: string;
+ /** Present only when returned from an agent-scoped assignment endpoint. */
+ enabled?: boolean;
}
export interface Skill extends SkillSummary {
@@ -874,16 +878,27 @@ export interface RuntimeLocalSkillSummary {
* discovery omit the field; treat `undefined` as unknown rather than
* asserting either origin.
*/
- root?: "provider" | "universal";
+ root?: "provider" | "universal" | "plugin";
+ /** Enabled runtime plugin that contributed this skill, when applicable. */
+ plugin?: string;
file_count: number;
}
+export interface RuntimeLocalMcpServerSummary {
+ name: string;
+ transport?: "stdio" | "http" | "sse" | "unknown";
+ source?: string;
+ enabled: boolean;
+}
+
export interface RuntimeLocalSkillListRequest {
id: string;
runtime_id: string;
status: RuntimeLocalSkillStatus;
skills?: RuntimeLocalSkillSummary[];
supported: boolean;
+ mcp_servers?: RuntimeLocalMcpServerSummary[];
+ mcp_supported?: boolean;
error?: string;
created_at: string;
updated_at: string;
@@ -918,6 +933,8 @@ export interface RuntimeLocalSkillImportRequest {
export interface RuntimeLocalSkillsResult {
skills: RuntimeLocalSkillSummary[];
supported: boolean;
+ mcpServers: RuntimeLocalMcpServerSummary[];
+ mcpSupported: boolean;
}
export interface RuntimeLocalSkillImportResult {
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index db89e9b7e1..c0c800cff0 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -55,6 +55,7 @@ export type {
RuntimeLocalSkillImportAction,
RuntimeLocalSkillImportConflict,
RuntimeLocalSkillSummary,
+ RuntimeLocalMcpServerSummary,
RuntimeLocalSkillListRequest,
CreateRuntimeLocalSkillImportRequest,
RuntimeLocalSkillImportRequest,
diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsx
index d05a7d03cb..25030a8e50 100644
--- a/packages/views/agents/components/agent-overview-pane.tsx
+++ b/packages/views/agents/components/agent-overview-pane.tsx
@@ -396,10 +396,17 @@ export function AgentOverviewPane({
onDirtyChange={setActiveDirty}
/>
)}
- {effectiveView === "skills" && <SkillsTab agent={agent} />}
+ {effectiveView === "skills" && (
+ <SkillsTab
+ agent={agent}
+ runtime={runtime}
+ canEdit={canEdit}
+ />
+ )}
{effectiveView === "mcp_config" && (
<McpConfigTab
agent={agent}
+ runtime={runtime}
onSave={(updates) => onUpdate(agent.id, updates)}
onDirtyChange={setActiveDirty}
/>
diff --git a/packages/views/agents/components/tabs/mcp-config-model.test.ts b/packages/views/agents/components/tabs/mcp-config-model.test.ts
new file mode 100644
index 0000000000..0b308fce5c
--- /dev/null
+++ b/packages/views/agents/components/tabs/mcp-config-model.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "vitest";
+import {
+ listManagedMcpServers,
+ removeManagedMcpServer,
+ upsertManagedMcpServer,
+} from "./mcp-config-model";
+
+describe("mcp config compatibility model", () => {
+ it("reads canonical and historical OpenCode-native containers without duplication", () => {
+ const servers = listManagedMcpServers({
+ mcpServers: { shared: { command: "canonical" } },
+ mcp: {
+ shared: { type: "local", command: ["native"] },
+ legacy: { type: "remote", url: "https://example.test/mcp" },
+ },
+ });
+
+ expect(servers.map(({ name, container }) => ({ name, container }))).toEqual([
+ { name: "legacy", container: "mcp" },
+ { name: "shared", container: "mcpServers" },
+ ]);
+ });
+
+ it("updates a single legacy entry while preserving unknown document fields", () => {
+ const value = {
+ provider: "opencode",
+ mcp: {
+ legacy: { type: "remote", url: "https://old.test/mcp" },
+ sibling: { type: "local", command: ["node", "server.js"] },
+ },
+ };
+ const legacy = listManagedMcpServers(value).find(
+ (server) => server.name === "legacy",
+ );
+ expect(legacy).toBeDefined();
+
+ expect(
+ upsertManagedMcpServer(
+ value,
+ legacy!,
+ "legacy",
+ { type: "remote", url: "https://new.test/mcp" },
+ ),
+ ).toEqual({
+ provider: "opencode",
+ mcp: {
+ legacy: { type: "remote", url: "https://new.test/mcp" },
+ sibling: { type: "local", command: ["node", "server.js"] },
+ },
+ });
+ });
+
+ it("returns null only when deleting the last value from an otherwise empty document", () => {
+ const value = { mcpServers: { fetch: { command: "uvx" } } };
+ const [fetch] = listManagedMcpServers(value);
+ expect(removeManagedMcpServer(value, fetch!)).toBeNull();
+
+ const withMetadata = { version: 1, ...value };
+ const [withMetadataFetch] = listManagedMcpServers(withMetadata);
+ expect(removeManagedMcpServer(withMetadata, withMetadataFetch!)).toEqual({
+ version: 1,
+ });
+ });
+});
diff --git a/packages/views/agents/components/tabs/mcp-config-model.ts b/packages/views/agents/components/tabs/mcp-config-model.ts
new file mode 100644
index 0000000000..8898c3ba61
--- /dev/null
+++ b/packages/views/agents/components/tabs/mcp-config-model.ts
@@ -0,0 +1,93 @@
+export type McpConfigContainer = "mcpServers" | "mcp";
+
+export type ManagedMcpServer = {
+ name: string;
+ config: Record<string, unknown>;
+ container: McpConfigContainer;
+ transport: string;
+ enabled: boolean;
+};
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+export function mcpTransport(config: Record<string, unknown>): string {
+ const type = typeof config.type === "string" ? config.type.toLowerCase() : "";
+ if (config.command || type === "local" || type === "stdio") return "stdio";
+ if (type === "sse") return "sse";
+ if (
+ config.url ||
+ type === "remote" ||
+ type === "http" ||
+ type === "streamable-http"
+ ) {
+ return "http";
+ }
+ return "unknown";
+}
+
+export function listManagedMcpServers(value: unknown): ManagedMcpServer[] {
+ if (!isRecord(value)) return [];
+
+ const out: ManagedMcpServer[] = [];
+ const seen = new Set<string>();
+ for (const container of ["mcpServers", "mcp"] as const) {
+ const raw = value[container];
+ if (!isRecord(raw)) continue;
+ for (const [name, entry] of Object.entries(raw)) {
+ if (seen.has(name) || !isRecord(entry)) continue;
+ seen.add(name);
+ out.push({
+ name,
+ config: entry,
+ container,
+ transport: mcpTransport(entry),
+ enabled: entry.enabled !== false && entry.disabled !== true,
+ });
+ }
+ }
+ return out.sort((a, b) => a.name.localeCompare(b.name));
+}
+
+export function upsertManagedMcpServer(
+ value: unknown,
+ previous: ManagedMcpServer | null,
+ name: string,
+ config: Record<string, unknown>,
+): Record<string, unknown> {
+ const document = isRecord(value) ? { ...value } : {};
+ const container: McpConfigContainer = previous?.container ?? "mcpServers";
+
+ if (previous) {
+ const previousMap = isRecord(document[previous.container])
+ ? { ...(document[previous.container] as Record<string, unknown>) }
+ : {};
+ delete previousMap[previous.name];
+ document[previous.container] = previousMap;
+ }
+
+ const target = isRecord(document[container])
+ ? { ...(document[container] as Record<string, unknown>) }
+ : {};
+ target[name] = config;
+ document[container] = target;
+ return document;
+}
+
+export function removeManagedMcpServer(
+ value: unknown,
+ server: ManagedMcpServer,
+): Record<string, unknown> | null {
+ if (!isRecord(value)) return null;
+ const document = { ...value };
+ const container = isRecord(document[server.container])
+ ? { ...(document[server.container] as Record<string, unknown>) }
+ : {};
+ delete container[server.name];
+
+ if (Object.keys(container).length > 0) document[server.container] = container;
+ else delete document[server.container];
+
+ return Object.keys(document).length > 0 ? document : null;
+}
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 6aa3f91c37..9d3d1da46e 100644
--- a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
+++ b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx
@@ -1,12 +1,14 @@
// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Agent } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../../locales/en/common.json";
import enAgents from "../../../locales/en/agents.json";
+import { McpConfigTab } from "./mcp-config-tab";
const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };
@@ -17,8 +19,6 @@ vi.mock("sonner", () => ({
},
}));
-import { McpConfigTab } from "./mcp-config-tab";
-
const baseAgent: Agent = {
id: "agent-1",
workspace_id: "ws-1",
@@ -44,181 +44,174 @@ const baseAgent: Agent = {
archived_by: null,
};
+function TestShell({ children }: { children: React.ReactNode }) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ </I18nProvider>
+ );
+}
+
function renderTab(
overrides: Partial<Agent> = {},
onSave = vi.fn().mockResolvedValue(undefined),
) {
- const agent = { ...baseAgent, ...overrides };
const result = render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <McpConfigTab agent={agent} onSave={onSave} />
- </I18nProvider>,
+ <TestShell>
+ <McpConfigTab
+ agent={{ ...baseAgent, ...overrides }}
+ runtime={null}
+ onSave={onSave}
+ />
+ </TestShell>,
);
return { ...result, onSave };
}
describe("McpConfigTab", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
+ beforeEach(() => vi.clearAllMocks());
- it("renders a read-only redacted state when the server omitted the value", () => {
- // mcp_config_redacted means the server knows there IS a config but
- // hid it from this caller. The tab must NOT expose the editor or
- // any input — even an empty textarea would let a non-privileged
- // member silently overwrite an admin-owned config on save.
+ it("renders redacted managed MCP without exposing add or edit controls", () => {
renderTab({ mcp_config: null, mcp_config_redacted: true });
expect(screen.getByText(/hidden from your view/i)).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /add mcp/i })).not.toBeInTheDocument();
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
- expect(screen.queryByRole("button", { name: /save/i })).not.toBeInTheDocument();
});
- it("shows the editor empty when no config is set, and Save stays disabled", () => {
- renderTab({ mcp_config: null });
-
- const editor = screen.getByLabelText(/MCP config JSON editor/i) as HTMLTextAreaElement;
- expect(editor.value).toBe("");
+ it("projects historical aggregate config into individually managed rows", () => {
+ renderTab({
+ mcp_config: {
+ version: 1,
+ mcpServers: {
+ fetch: { command: "uvx", args: ["mcp-server-fetch"] },
+ docs: { type: "http", url: "https://example.test/mcp" },
+ },
+ },
+ });
- expect(screen.getByRole("button", { name: /save/i })).toBeDisabled();
+ expect(screen.getByText("fetch")).toBeInTheDocument();
+ expect(screen.getByText("docs")).toBeInTheDocument();
+ 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("pretty-prints the existing config and saves a parsed object", async () => {
+ it("adds one stdio server through the form and preserves historical top-level data", async () => {
const user = userEvent.setup();
- const stored = { mcpServers: { fetch: { command: "uvx" } } };
- const { onSave } = renderTab({ mcp_config: stored });
-
- const editor = screen.getByLabelText(/MCP config JSON editor/i) as HTMLTextAreaElement;
- expect(editor.value).toBe(JSON.stringify(stored, null, 2));
+ const { onSave } = renderTab({ mcp_config: { version: 1 } });
- // userEvent.type interprets `{` / `[` as keyboard modifiers, so a
- // raw JSON paste goes through fireEvent.change instead — the same
- // path the browser uses when the user pastes.
- const replacement = JSON.stringify({
- mcpServers: { fetch: { command: "npx" } },
- });
- fireEvent.change(editor, { target: { value: replacement } });
+ await user.click(screen.getByRole("button", { name: /add mcp/i }));
+ await user.type(screen.getByLabelText("Name"), "fetch");
+ await user.type(screen.getByLabelText("Command"), "uvx");
+ await user.click(screen.getByRole("button", { name: /add server/i }));
- const save = screen.getByRole("button", { name: /save/i });
- expect(save).toBeEnabled();
- await user.click(save);
-
- expect(onSave).toHaveBeenCalledTimes(1);
- // We pass the parsed object, not the raw string, so the backend
- // gets a real JSON shape and not an escaped string.
expect(onSave).toHaveBeenCalledWith({
- mcp_config: { mcpServers: { fetch: { command: "npx" } } },
+ mcp_config: {
+ version: 1,
+ mcpServers: { fetch: { command: "uvx" } },
+ },
});
});
- it("clearing the editor saves null to wipe the column", async () => {
+ it("adds one HTTP server through JSON mode", async () => {
const user = userEvent.setup();
- const { onSave } = renderTab({ mcp_config: { mcpServers: {} } });
-
- const editor = screen.getByLabelText(/MCP config JSON editor/i) as HTMLTextAreaElement;
- await user.clear(editor);
-
- const save = screen.getByRole("button", { name: /save/i });
- await user.click(save);
-
- // null is what the backend reads as "clear this column" — sending
- // an empty string or {} would either fail validation or store an
- // empty object, both of which surprise the user.
- expect(onSave).toHaveBeenCalledWith({ mcp_config: null });
- });
-
- it("disables Save and surfaces an inline error on invalid JSON", () => {
- const { onSave } = renderTab({ mcp_config: null });
-
- const editor = screen.getByLabelText(/MCP config JSON editor/i);
- fireEvent.change(editor, { target: { value: "{ not json" } });
+ const { onSave } = renderTab();
+
+ await user.click(screen.getByRole("button", { name: /add mcp/i }));
+ await user.type(screen.getByLabelText("Name"), "weather");
+ await user.click(screen.getByRole("tab", { name: "JSON" }));
+ fireEvent.change(screen.getByLabelText(/MCP server JSON configuration/i), {
+ target: {
+ value: JSON.stringify({
+ type: "http",
+ url: "https://example.invalid/mcp",
+ }),
+ },
+ });
+ await user.click(screen.getByRole("button", { name: /add server/i }));
- expect(screen.getByText(/Invalid JSON/i)).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /save/i })).toBeDisabled();
- expect(onSave).not.toHaveBeenCalled();
+ expect(onSave).toHaveBeenCalledWith({
+ mcp_config: {
+ mcpServers: {
+ weather: {
+ type: "http",
+ url: "https://example.invalid/mcp",
+ },
+ },
+ },
+ });
});
- it("rejects top-level arrays and primitives", () => {
- renderTab({ mcp_config: null });
-
- const editor = screen.getByLabelText(/MCP config JSON editor/i);
- fireEvent.change(editor, { target: { value: "[1,2,3]" } });
+ it("edits one historical server without replacing its siblings", async () => {
+ const user = userEvent.setup();
+ const existing = {
+ version: 1,
+ mcpServers: {
+ fetch: {
+ command: "uvx",
+ timeout: 30,
+ tools: { include: ["fetch_url"] },
+ },
+ docs: { url: "https://example.test/mcp" },
+ },
+ };
+ const { onSave } = renderTab({ mcp_config: existing });
+
+ await user.click(
+ screen.getByRole("button", { name: /edit mcp server fetch/i }),
+ );
+ const command = screen.getByLabelText("Command");
+ await user.clear(command);
+ await user.type(command, "npx");
+ await user.click(screen.getByRole("button", { name: /save changes/i }));
- expect(
- screen.getByText(/MCP config must be a JSON object/i),
- ).toBeInTheDocument();
- expect(screen.getByRole("button", { name: /save/i })).toBeDisabled();
+ expect(onSave).toHaveBeenCalledWith({
+ mcp_config: {
+ version: 1,
+ mcpServers: {
+ fetch: {
+ timeout: 30,
+ tools: { include: ["fetch_url"] },
+ command: "npx",
+ },
+ docs: { url: "https://example.test/mcp" },
+ },
+ },
+ });
});
- it("syncs the editor to a refreshed agent prop when the user hasn't edited", () => {
- // Reproduces the stale-editor bug: a background refetch / WS event swaps
- // in a newer `agent.mcp_config`, and the editor must follow it (so the
- // next Save writes the new value, not the old one). Comparing the draft
- // against the *previous* original — not the new one — is what makes this
- // work. Without the ref, the effect would self-defeat: on re-render the
- // draft already equals the new original, the equality check is true,
- // but the conditional only re-assigns `original` to itself, so a draft
- // that started life equal to the OLD original is never touched.
- const initial = { mcpServers: { fetch: { command: "uvx" } } };
- const updated = { mcpServers: { fetch: { command: "npx" } } };
- const agent = { ...baseAgent, mcp_config: initial };
-
- const { rerender } = render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <McpConfigTab agent={agent} onSave={vi.fn()} />
- </I18nProvider>,
- );
+ it("deletes the last managed server only after confirmation", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab({
+ mcp_config: { mcpServers: { fetch: { command: "uvx" } } },
+ });
- const editor = screen.getByLabelText(
- /MCP config JSON editor/i,
- ) as HTMLTextAreaElement;
- expect(editor.value).toBe(JSON.stringify(initial, null, 2));
-
- rerender(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <McpConfigTab
- agent={{ ...agent, mcp_config: updated }}
- onSave={vi.fn()}
- />
- </I18nProvider>,
+ await user.click(
+ screen.getByRole("button", { name: /delete mcp server fetch/i }),
);
+ expect(screen.getByText(/runtime servers are not affected/i)).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: /delete server/i }));
- // Editor follows the new prop and the dirty hint is NOT shown — if it
- // were, the next Save would write the *old* JSON back over the new one.
- expect(editor.value).toBe(JSON.stringify(updated, null, 2));
- expect(screen.queryByText(/unsaved changes/i)).not.toBeInTheDocument();
+ expect(onSave).toHaveBeenCalledWith({ mcp_config: null });
});
- it("preserves an in-flight edit when the agent prop is refreshed underneath", () => {
- // The mirror of the test above: if the user IS editing, a background
- // refresh must not clobber their draft.
- const initial = { mcpServers: { fetch: { command: "uvx" } } };
- const updated = { mcpServers: { fetch: { command: "npx" } } };
- const agent = { ...baseAgent, mcp_config: initial };
-
- const { rerender } = render(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <McpConfigTab agent={agent} onSave={vi.fn()} />
- </I18nProvider>,
- );
+ it("blocks invalid single-server JSON", async () => {
+ const user = userEvent.setup();
+ const { onSave } = renderTab();
- const editor = screen.getByLabelText(
- /MCP config JSON editor/i,
- ) as HTMLTextAreaElement;
- const draft = JSON.stringify({ mcpServers: { fetch: { command: "wip" } } });
- fireEvent.change(editor, { target: { value: draft } });
- expect(editor.value).toBe(draft);
-
- rerender(
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <McpConfigTab
- agent={{ ...agent, mcp_config: updated }}
- onSave={vi.fn()}
- />
- </I18nProvider>,
- );
+ await user.click(screen.getByRole("button", { name: /add mcp/i }));
+ await user.type(screen.getByLabelText("Name"), "broken");
+ await user.click(screen.getByRole("tab", { name: "JSON" }));
+ fireEvent.change(screen.getByLabelText(/MCP server JSON configuration/i), {
+ target: { value: "{not json" },
+ });
- expect(editor.value).toBe(draft);
+ expect(screen.getByText(/invalid json/i)).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /add server/i })).toBeDisabled();
+ expect(onSave).not.toHaveBeenCalled();
});
-
});
diff --git a/packages/views/agents/components/tabs/mcp-config-tab.tsx b/packages/views/agents/components/tabs/mcp-config-tab.tsx
index 5443e78553..b09ab67f29 100644
--- a/packages/views/agents/components/tabs/mcp-config-tab.tsx
+++ b/packages/views/agents/components/tabs/mcp-config-tab.tsx
@@ -1,205 +1,382 @@
"use client";
-import { useEffect, useMemo, useRef, useState } from "react";
-import { Eraser, Loader2, Lock, Save } from "lucide-react";
-import type { Agent } from "@multica/core/types";
+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 } from "@multica/core/types";
+import { runtimeCapabilitiesOptions } from "@multica/core/runtimes";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { Badge } from "@multica/ui/components/ui/badge";
import { Button } from "@multica/ui/components/ui/button";
-import { Textarea } from "@multica/ui/components/ui/textarea";
import { toast } from "sonner";
import { useT } from "../../../i18n";
-
-// `null` and the empty string are the two ways the user can mean "no
-// config" — the server stores either as a NULL column and the daemon
-// falls back to the runtime CLI default at launch. We normalise to
-// the empty string in the editor so the dirty check has one canonical
-// form to compare against.
-function configToText(value: unknown): string {
- if (value === null || value === undefined) return "";
- return JSON.stringify(value, null, 2);
-}
+import {
+ listManagedMcpServers,
+ removeManagedMcpServer,
+ upsertManagedMcpServer,
+ type ManagedMcpServer,
+} from "./mcp-config-model";
+import { McpServerDialog } from "./mcp-server-dialog";
export function McpConfigTab({
agent,
+ runtime,
onSave,
onDirtyChange,
}: {
agent: Agent;
+ runtime: AgentRuntime | null;
onSave: (updates: { mcp_config: unknown | null }) => Promise<void>;
onDirtyChange?: (dirty: boolean) => void;
}) {
const { t } = useT("agents");
-
+ const runtimeId =
+ runtime?.runtime_mode === "local" && runtime.status === "online"
+ ? runtime.id
+ : null;
+ const runtimeQuery = useQuery(runtimeCapabilitiesOptions(runtimeId));
const redacted = agent.mcp_config_redacted === true;
- const original = useMemo(() => configToText(agent.mcp_config), [agent.mcp_config]);
- const [text, setText] = useState(original);
- const [saving, setSaving] = useState(false);
-
- // Sync local draft when the agent prop changes (e.g. after a successful
- // save invalidates the cache and a fresh agent arrives). We only sync
- // when the user has no in-flight edits — comparing the current draft
- // against the *previous* original (not the new one) is what tells us
- // "they haven't touched this since the last sync". Comparing against
- // the new original would skip the sync whenever the server-side value
- // changes underneath an untouched draft, leaving the editor showing a
- // stale value that a later Save would write back, clobbering another
- // admin's edit.
- const previousOriginalRef = useRef(original);
- useEffect(() => {
- setText((current) =>
- current === previousOriginalRef.current ? original : current,
- );
- previousOriginalRef.current = original;
- }, [original]);
-
- const trimmed = text.trim();
- const parseResult = useMemo<
- | { ok: true; value: unknown | null }
- | { ok: false; error: string }
- >(() => {
- if (trimmed === "") return { ok: true, value: null };
- try {
- const value = JSON.parse(trimmed);
- // The MCP CLI accepts an object (`{"mcpServers": …}`); a top-level
- // array or primitive is almost certainly a user mistake, so reject
- // here rather than surprise them with a server-side error later.
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
- return {
- ok: false,
- error: "mcp_config_not_object",
- };
- }
- return { ok: true, value };
- } catch (err) {
- return {
- ok: false,
- error: err instanceof Error ? err.message : "invalid JSON",
- };
- }
- }, [trimmed]);
+ const managedServers = useMemo(
+ () => listManagedMcpServers(agent.mcp_config),
+ [agent.mcp_config],
+ );
+ const managedNames = useMemo(
+ () => new Set(managedServers.map((server) => server.name)),
+ [managedServers],
+ );
+ const [editorOpen, setEditorOpen] = useState(false);
+ const [editingServer, setEditingServer] = useState<ManagedMcpServer | null>(
+ null,
+ );
+ const [deletingServer, setDeletingServer] =
+ useState<ManagedMcpServer | null>(null);
+ const [deleting, setDeleting] = useState(false);
- const dirty = text !== original;
+ useEffect(() => onDirtyChange?.(false), [onDirtyChange]);
- useEffect(() => {
- onDirtyChange?.(dirty);
- }, [dirty, onDirtyChange]);
+ const openAddDialog = () => {
+ setEditingServer(null);
+ setEditorOpen(true);
+ };
- if (redacted) {
- return (
- <div className="space-y-3">
- <p className="flex items-center gap-2 text-sm font-medium">
- <Lock
- className="h-3.5 w-3.5 text-muted-foreground"
- aria-hidden="true"
- />
- {t(($) => $.tab_body.mcp_config.redacted_title)}
- </p>
- <p className="text-xs text-muted-foreground">
- {t(($) => $.tab_body.mcp_config.redacted_hint)}
- </p>
- </div>
- );
- }
+ const openEditDialog = (server: ManagedMcpServer) => {
+ setEditingServer(server);
+ setEditorOpen(true);
+ };
- const handleSave = async () => {
- if (!parseResult.ok) return;
- setSaving(true);
+ const handleSaveServer = async (
+ name: string,
+ config: Record<string, unknown>,
+ ) => {
+ const next = upsertManagedMcpServer(
+ agent.mcp_config,
+ editingServer,
+ name,
+ config,
+ );
try {
- await onSave({ mcp_config: parseResult.value });
- // Normalise the editor to the pretty-printed canonical form so the
- // dirty check stops firing after a successful save (the user's
- // raw input may differ from what configToText would emit).
- setText(configToText(parseResult.value));
- toast.success(t(($) => $.tab_body.mcp_config.saved_toast));
- } catch (err) {
+ await onSave({ mcp_config: next });
+ toast.success(
+ editingServer
+ ? t(($) => $.tab_body.mcp_config.updated_toast)
+ : t(($) => $.tab_body.mcp_config.added_toast),
+ );
+ } catch (error) {
toast.error(
- err instanceof Error && err.message
- ? err.message
+ error instanceof Error && error.message
+ ? error.message
: t(($) => $.tab_body.mcp_config.save_failed_toast),
);
- } finally {
- setSaving(false);
+ throw error;
}
};
- const handleClear = () => {
- setText("");
+ const handleDelete = async () => {
+ if (!deletingServer) return;
+ setDeleting(true);
+ try {
+ await onSave({
+ mcp_config: removeManagedMcpServer(agent.mcp_config, deletingServer),
+ });
+ toast.success(t(($) => $.tab_body.mcp_config.deleted_toast));
+ setDeletingServer(null);
+ } catch (error) {
+ toast.error(
+ error instanceof Error && error.message
+ ? error.message
+ : t(($) => $.tab_body.mcp_config.delete_failed_toast),
+ );
+ } finally {
+ setDeleting(false);
+ }
};
- const showInvalid = trimmed !== "" && !parseResult.ok;
- const invalidMessage = !parseResult.ok && parseResult.error === "mcp_config_not_object"
- ? t(($) => $.tab_body.mcp_config.invalid_not_object)
- : !parseResult.ok
- ? t(($) => $.tab_body.mcp_config.invalid_json, { error: parseResult.error })
- : "";
-
return (
- <div className="space-y-5">
- <div className="flex items-start justify-between gap-3">
- <p className="max-w-2xl break-words text-pretty text-sm leading-6 text-muted-foreground">
- {t(($) => $.tab_body.mcp_config.intro)}
- </p>
- {trimmed !== "" && (
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={handleClear}
- className="shrink-0"
- >
- <Eraser className="h-3 w-3" aria-hidden="true" />
- {t(($) => $.tab_body.mcp_config.clear_action)}
- </Button>
+ <div className="space-y-8">
+ <p className="max-w-2xl break-words text-pretty text-sm leading-6 text-muted-foreground">
+ {t(($) => $.tab_body.mcp_config.intro)}
+ </p>
+
+ <section className="space-y-3">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h3 className="text-sm font-medium">
+ {t(($) => $.tab_body.mcp_config.managed_title)}
+ </h3>
+ <p className="mt-1 max-w-2xl text-xs leading-5 text-muted-foreground">
+ {t(($) => $.tab_body.mcp_config.managed_hint)}
+ </p>
+ </div>
+ {!redacted && (
+ <Button size="sm" variant="outline" onClick={openAddDialog}>
+ <Plus aria-hidden="true" />
+ {t(($) => $.tab_body.mcp_config.add_action)}
+ </Button>
+ )}
+ </div>
+
+ {redacted ? (
+ <div className="flex items-start gap-2 rounded-lg border px-4 py-3">
+ <Lock
+ className="mt-0.5 h-4 w-4 text-muted-foreground"
+ aria-hidden="true"
+ />
+ <div>
+ <p className="text-sm font-medium">
+ {t(($) => $.tab_body.mcp_config.redacted_title)}
+ </p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t(($) => $.tab_body.mcp_config.redacted_hint)}
+ </p>
+ </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)}
+ />
+ ) : (
+ <McpNotice text={t(($) => $.tab_body.mcp_config.managed_empty)} />
)}
- </div>
-
- <div className="space-y-2">
- <label
- htmlFor={`agent-mcp-config-${agent.id}`}
- className="text-sm font-medium"
- >
- {t(($) => $.tab_body.mcp_config.config_label)}
- </label>
- <Textarea
- id={`agent-mcp-config-${agent.id}`}
- name="agent-mcp-config"
- autoComplete="off"
- value={text}
- onChange={(e) => setText(e.target.value)}
- placeholder={t(($) => $.tab_body.mcp_config.placeholder)}
- aria-invalid={showInvalid || undefined}
- aria-label={t(($) => $.tab_body.mcp_config.editor_aria)}
- spellCheck={false}
- rows={14}
- className="min-h-80 resize-y font-mono text-xs"
- />
- </div>
+ </section>
- {showInvalid && (
- <p className="text-xs text-destructive">{invalidMessage}</p>
+ <section className="space-y-3">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h3 className="text-sm font-medium">
+ {t(($) => $.tab_body.mcp_config.runtime_title)}
+ </h3>
+ <p className="mt-1 max-w-2xl text-xs leading-5 text-muted-foreground">
+ {t(($) => $.tab_body.mcp_config.runtime_hint, {
+ runtime: runtime?.custom_name || runtime?.name || "Runtime",
+ })}
+ </p>
+ </div>
+ {runtimeId && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => runtimeQuery.refetch()}
+ disabled={runtimeQuery.isFetching}
+ >
+ <RefreshCw
+ className={
+ runtimeQuery.isFetching
+ ? "h-3.5 w-3.5 animate-spin motion-reduce:animate-none"
+ : "h-3.5 w-3.5"
+ }
+ aria-hidden="true"
+ />
+ {t(($) => $.tab_body.mcp_config.refresh_action)}
+ </Button>
+ )}
+ </div>
+ {!runtime ? (
+ <McpNotice text={t(($) => $.tab_body.mcp_config.runtime_missing)} />
+ ) : runtime.status !== "online" ? (
+ <McpNotice text={t(($) => $.tab_body.mcp_config.runtime_offline)} />
+ ) : runtimeQuery.isLoading ? (
+ <McpNotice
+ loading
+ text={t(($) => $.tab_body.mcp_config.runtime_discovering)}
+ />
+ ) : runtimeQuery.isError ? (
+ <McpNotice text={t(($) => $.tab_body.mcp_config.runtime_failed)} />
+ ) : runtimeQuery.data?.mcpSupported !== true ? (
+ <McpNotice
+ text={t(($) => $.tab_body.mcp_config.runtime_unsupported)}
+ />
+ ) : runtimeQuery.data.mcpServers.length === 0 ? (
+ <McpNotice text={t(($) => $.tab_body.mcp_config.runtime_empty)} />
+ ) : (
+ <McpServerList
+ servers={runtimeQuery.data.mcpServers.map((server) => ({
+ name: server.name,
+ transport: server.transport || "unknown",
+ enabled: server.enabled,
+ source: server.source,
+ overridden: managedNames.has(server.name),
+ }))}
+ disabledLabel={t(($) => $.tab_body.mcp_config.runtime_disabled_badge)}
+ overriddenLabel={t(($) => $.tab_body.mcp_config.runtime_overridden_badge)}
+ />
+ )}
+ </section>
+
+ {!redacted && (
+ <McpServerDialog
+ open={editorOpen}
+ server={editingServer}
+ existingNames={managedNames}
+ onOpenChange={setEditorOpen}
+ onSave={handleSaveServer}
+ />
)}
- <div className="flex items-center justify-end gap-3">
- {dirty && (
- <span className="text-xs text-muted-foreground">
- {t(($) => $.tab_body.common.unsaved_changes)}
+ <AlertDialog
+ open={deletingServer !== null}
+ onOpenChange={(open) => !open && !deleting && setDeletingServer(null)}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.tab_body.mcp_config.delete_dialog_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.tab_body.mcp_config.delete_dialog_description, {
+ name: deletingServer?.name ?? "",
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={deleting}>
+ {t(($) => $.tab_body.mcp_config.dialog_cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={handleDelete}
+ disabled={deleting}
+ >
+ {deleting && (
+ <Loader2
+ className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none"
+ aria-hidden="true"
+ />
+ )}
+ {t(($) => $.tab_body.mcp_config.delete_action)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
+type McpServerView = {
+ name: string;
+ transport: string;
+ enabled: boolean;
+ source?: string;
+ overridden?: boolean;
+};
+
+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>
- )}
- <Button
- onClick={handleSave}
- disabled={!dirty || !parseResult.ok || saving}
- size="sm"
- >
- {saving ? (
- <Loader2
- className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none"
- aria-hidden="true"
- />
- ) : (
- <Save className="h-3.5 w-3.5" aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium">{server.name}</p>
+ <p className="text-xs text-muted-foreground">
+ <span className="uppercase">{server.transport}</span>
+ {server.source ? ` · ${server.source}` : null}
+ </p>
+ </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>
)}
- {t(($) => $.tab_body.common.save)}
- </Button>
- </div>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+function McpNotice({ text, loading = false }: { text: string; loading?: boolean }) {
+ return (
+ <div className="flex items-center gap-2 rounded-lg border border-dashed px-4 py-6 text-xs text-muted-foreground">
+ {loading ? (
+ <Loader2
+ className="h-4 w-4 animate-spin motion-reduce:animate-none"
+ aria-hidden="true"
+ />
+ ) : (
+ <Server className="h-4 w-4" aria-hidden="true" />
+ )}
+ {text}
</div>
);
}
diff --git a/packages/views/agents/components/tabs/mcp-server-dialog.tsx b/packages/views/agents/components/tabs/mcp-server-dialog.tsx
new file mode 100644
index 0000000000..4d5e233135
--- /dev/null
+++ b/packages/views/agents/components/tabs/mcp-server-dialog.tsx
@@ -0,0 +1,533 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { Loader2, Plus, Trash2 } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@multica/ui/components/ui/tabs";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import { useT } from "../../../i18n";
+import type { ManagedMcpServer } from "./mcp-config-model";
+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;
+ args: string[];
+ env: KeyValue[];
+ url: string;
+ headers: KeyValue[];
+ extras: Record<string, unknown>;
+};
+
+const emptyForm = (): McpFormState => ({
+ transport: "stdio",
+ command: "",
+ args: [],
+ env: [],
+ url: "",
+ headers: [],
+ extras: {},
+});
+
+function pairsFromRecord(value: unknown): KeyValue[] {
+ if (!isRecord(value)) return [];
+ return Object.entries(value).flatMap(([key, item]) =>
+ typeof item === "string" ? [{ key, value: item }] : [],
+ );
+}
+
+function formFromConfig(config: Record<string, unknown>): McpFormState {
+ const extras = { ...config };
+ for (const key of [
+ "type",
+ "command",
+ "args",
+ "env",
+ "environment",
+ "url",
+ "headers",
+ ]) {
+ delete extras[key];
+ }
+
+ const transport = mcpTransport(config) === "stdio" ? "stdio" : "http";
+ let command = "";
+ let args: string[] = [];
+ if (typeof config.command === "string") command = config.command;
+ else if (Array.isArray(config.command)) {
+ const tokens = config.command.filter(
+ (value): value is string => typeof value === "string",
+ );
+ command = tokens[0] ?? "";
+ args = tokens.slice(1);
+ }
+ if (Array.isArray(config.args)) {
+ args = config.args.filter(
+ (value): value is string => typeof value === "string",
+ );
+ }
+
+ return {
+ transport,
+ command,
+ args,
+ env: pairsFromRecord(config.env ?? config.environment),
+ url: typeof config.url === "string" ? config.url : "",
+ headers: pairsFromRecord(config.headers),
+ extras,
+ };
+}
+
+function recordFromPairs(pairs: KeyValue[]): Record<string, string> | undefined {
+ const entries = pairs
+ .map(({ key, value }) => [key.trim(), value] as const)
+ .filter(([key]) => key !== "");
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+}
+
+function configFromForm(form: McpFormState): Record<string, unknown> {
+ const config = { ...form.extras };
+ if (form.transport === "stdio") {
+ config.command = form.command.trim();
+ if (form.args.length > 0) config.args = form.args;
+ const env = recordFromPairs(form.env);
+ if (env) config.env = env;
+ } else {
+ config.type = "http";
+ config.url = form.url.trim();
+ const headers = recordFromPairs(form.headers);
+ if (headers) config.headers = headers;
+ }
+ return config;
+}
+
+function parseServerJson(text: string):
+ | { ok: true; value: Record<string, unknown> }
+ | { ok: false; error: string } {
+ try {
+ const value = JSON.parse(text);
+ if (!isRecord(value)) return { ok: false, error: "not_object" };
+ if (!value.command && !value.url) return { ok: false, error: "missing_target" };
+ return { ok: true, value };
+ } catch (error) {
+ return {
+ ok: false,
+ error: error instanceof Error ? error.message : "invalid JSON",
+ };
+ }
+}
+
+export function McpServerDialog({
+ open,
+ server,
+ existingNames,
+ onOpenChange,
+ onSave,
+}: {
+ open: boolean;
+ server: ManagedMcpServer | null;
+ existingNames: Set<string>;
+ onOpenChange: (open: boolean) => void;
+ onSave: (name: string, config: Record<string, unknown>) => Promise<void>;
+}) {
+ const { t } = useT("agents");
+ const [name, setName] = useState("");
+ const [mode, setMode] = useState<EditorMode>("form");
+ const [form, setForm] = useState<McpFormState>(emptyForm);
+ const [jsonText, setJsonText] = useState("{}");
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ if (!open) return;
+ const config = server?.config ?? {};
+ setName(server?.name ?? "");
+ setForm(server ? formFromConfig(config) : emptyForm());
+ setJsonText(JSON.stringify(config, null, 2));
+ setMode(server?.container === "mcp" ? "json" : "form");
+ }, [open, server]);
+
+ const jsonResult = useMemo(() => parseServerJson(jsonText), [jsonText]);
+ const trimmedName = name.trim();
+ const nameError =
+ trimmedName === ""
+ ? "required"
+ : !/^[A-Za-z0-9_-]+$/.test(trimmedName)
+ ? "format"
+ : existingNames.has(trimmedName) && trimmedName !== server?.name
+ ? "duplicate"
+ : null;
+ const formError =
+ form.transport === "stdio"
+ ? form.command.trim() === ""
+ ? "command"
+ : null
+ : form.url.trim() === ""
+ ? "url"
+ : null;
+ const canSave =
+ !saving &&
+ nameError === null &&
+ (mode === "form" ? formError === null : jsonResult.ok);
+
+ const errorMessage =
+ nameError === "required"
+ ? t(($) => $.tab_body.mcp_config.dialog_name_required)
+ : nameError === "format"
+ ? t(($) => $.tab_body.mcp_config.dialog_name_invalid)
+ : nameError === "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 handleModeChange = (next: string | number | null) => {
+ if (next !== "form" && next !== "json") return;
+ if (next === "json" && mode === "form") {
+ setJsonText(JSON.stringify(configFromForm(form), null, 2));
+ } else if (next === "form" && mode === "json" && jsonResult.ok) {
+ setForm(formFromConfig(jsonResult.value));
+ }
+ setMode(next);
+ };
+
+ const handleSave = async () => {
+ if (!canSave) 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);
+ onOpenChange(false);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ 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}
+ />
+ </div>
+
+ <Tabs value={mode} onValueChange={handleModeChange}>
+ <TabsList className="grid w-full grid-cols-2">
+ <TabsTrigger value="form" disabled={server?.container === "mcp"}>
+ {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-sm 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>
+ ))}
+ </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 }))
+ }
+ 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-xs 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-xs"
+ 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-xs 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>
+ );
+}
+
+function StringListEditor({
+ label,
+ addLabel,
+ removeLabel,
+ values,
+ onChange,
+}: {
+ label: string;
+ addLabel: string;
+ removeLabel: string;
+ values: string[];
+ onChange: (values: string[]) => void;
+}) {
+ return (
+ <fieldset className="space-y-2">
+ <legend className="text-sm 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>
+ ))}
+ <Button type="button" variant="outline" size="sm" onClick={() => onChange([...values, ""])}>
+ <Plus aria-hidden="true" />
+ {addLabel}
+ </Button>
+ </fieldset>
+ );
+}
+
+function KeyValueEditor({
+ label,
+ addLabel,
+ removeLabel,
+ rows,
+ onChange,
+}: {
+ label: string;
+ addLabel: string;
+ removeLabel: string;
+ rows: KeyValue[];
+ onChange: (rows: KeyValue[]) => void;
+}) {
+ return (
+ <fieldset className="space-y-2">
+ <legend className="text-sm font-medium">{label}</legend>
+ {rows.map((row, index) => (
+ <div key={index} className="grid grid-cols-[1fr_1fr_auto] gap-2">
+ <Input
+ aria-label={`${label} key ${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="Key"
+ />
+ <Input
+ aria-label={`${label} value ${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="Value"
+ />
+ <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>
+ ))}
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onChange([...rows, { key: "", value: "" }])}
+ >
+ <Plus aria-hidden="true" />
+ {addLabel}
+ </Button>
+ </fieldset>
+ );
+}
diff --git a/packages/views/agents/components/tabs/skills-tab.test.tsx b/packages/views/agents/components/tabs/skills-tab.test.tsx
index 0000663abe..8c7ef03a5e 100644
--- a/packages/views/agents/components/tabs/skills-tab.test.tsx
+++ b/packages/views/agents/components/tabs/skills-tab.test.tsx
@@ -3,7 +3,8 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { render, screen } from "@testing-library/react";
-import type { Agent } from "@multica/core/types";
+import userEvent from "@testing-library/user-event";
+import type { Agent, AgentRuntime } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../../locales/en/common.json";
import enAgents from "../../../locales/en/agents.json";
@@ -11,6 +12,10 @@ import enAgents from "../../../locales/en/agents.json";
const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };
const mockListSkills = vi.hoisted(() => vi.fn());
+const mockGetSkill = vi.hoisted(() => vi.fn());
+const mockSetAgentSkillEnabled = vi.hoisted(() => vi.fn());
+const mockRemoveAgentSkill = vi.hoisted(() => vi.fn());
+const mockRuntimeCapabilities = vi.hoisted(() => vi.fn());
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
@@ -19,10 +24,22 @@ vi.mock("@multica/core/hooks", () => ({
vi.mock("@multica/core/api", () => ({
api: {
listSkills: (...args: unknown[]) => mockListSkills(...args),
+ getSkill: (...args: unknown[]) => mockGetSkill(...args),
setAgentSkills: vi.fn(),
+ setAgentSkillEnabled: (...args: unknown[]) => mockSetAgentSkillEnabled(...args),
+ removeAgentSkill: (...args: unknown[]) => mockRemoveAgentSkill(...args),
},
}));
+vi.mock("@multica/core/runtimes", () => ({
+ runtimeCapabilitiesOptions: (runtimeId: string | null) => ({
+ queryKey: ["runtime-capabilities", runtimeId],
+ queryFn: () => mockRuntimeCapabilities(runtimeId),
+ enabled: Boolean(runtimeId),
+ retry: false,
+ }),
+}));
+
vi.mock("sonner", () => ({
toast: {
error: vi.fn(),
@@ -57,7 +74,10 @@ const agent: Agent = {
archived_by: null,
};
-function renderSkillsTab() {
+function renderSkillsTab(
+ agentOverrides: Partial<Agent> = {},
+ runtime: AgentRuntime | null = null,
+) {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
@@ -69,7 +89,7 @@ function renderSkillsTab() {
return render(
<I18nProvider locale="en" resources={TEST_RESOURCES}>
<QueryClientProvider client={queryClient}>
- <SkillsTab agent={agent} />
+ <SkillsTab agent={{ ...agent, ...agentOverrides }} runtime={runtime} />
</QueryClientProvider>
</I18nProvider>,
);
@@ -79,34 +99,87 @@ describe("SkillsTab", () => {
beforeEach(() => {
vi.clearAllMocks();
mockListSkills.mockResolvedValue([]);
+ mockSetAgentSkillEnabled.mockResolvedValue(undefined);
+ mockRemoveAgentSkill.mockResolvedValue(undefined);
+ mockRuntimeCapabilities.mockResolvedValue({
+ skills: [],
+ supported: true,
+ mcpServers: [],
+ mcpSupported: true,
+ });
});
- it("does not render the inline Local Runtime Skills section even for local-runtime agents", async () => {
- // The inline section auto-loaded local skills on every Skills-tab
- // entry, which was both noisy and (under multi-replica deploys) prone
- // to "request not found" because the request store is in-process.
- // Local-skill import now lives behind the explicit Skills page →
- // Add Skill → From Runtime tab; nothing here may auto-load.
+ it("separates workspace assignments from inherited runtime skills", async () => {
renderSkillsTab();
- // Top informational callout should still render; that's how we know
- // the tab body itself rendered (not stuck in a loading state).
expect(
- await screen.findByText(/Local runtime skills are always available/i),
+ await screen.findByText("Assigned to agent"),
).toBeInTheDocument();
+ expect(screen.getByText("Inherited from runtime")).toBeInTheDocument();
+ expect(screen.getByText(/Assign a local runtime/i)).toBeInTheDocument();
+ });
- // The removed section's heading and its trigger button must be gone.
- expect(screen.queryByText("Local Runtime Skills")).not.toBeInTheDocument();
- expect(
- screen.queryByRole("button", { name: /Import to Workspace/i }),
- ).not.toBeInTheDocument();
-
- // No runtime list / local-skills query should be wired up either —
- // we removed @multica/core/runtimes from this file's imports.
- // Surface it via behaviour: the `agent` here has runtime_id but the
- // tab must not invoke any runtime-list mock to render. (Both are
- // already deleted from the mock setup above; this assertion is
- // implicit — the test file would fail to import if the component
- // still referenced runtimeListOptions / runtimeLocalSkillsOptions.)
+ it("disables an assigned skill without removing it", async () => {
+ const user = userEvent.setup();
+ renderSkillsTab({
+ skills: [
+ {
+ id: "skill-1",
+ name: "Review changes",
+ description: "Review a patch",
+ enabled: true,
+ },
+ ],
+ });
+
+ await user.click(screen.getByRole("switch", { name: /Toggle Review changes/i }));
+
+ expect(mockSetAgentSkillEnabled).toHaveBeenCalledWith(
+ "agent-1",
+ "skill-1",
+ false,
+ );
+ expect(mockRemoveAgentSkill).not.toHaveBeenCalled();
+ });
+
+ it("shows inherited skills discovered from the assigned runtime", async () => {
+ mockRuntimeCapabilities.mockResolvedValue({
+ skills: [
+ {
+ key: "local-review",
+ name: "Local review",
+ description: "Host-level review workflow",
+ source_path: "~/.codex/skills/local-review",
+ provider: "codex",
+ root: "provider",
+ file_count: 2,
+ },
+ ],
+ supported: true,
+ mcpServers: [],
+ mcpSupported: true,
+ });
+ const runtime: AgentRuntime = {
+ id: "runtime-1",
+ workspace_id: "ws-1",
+ daemon_id: "daemon-1",
+ name: "Codex (Mac)",
+ runtime_mode: "local",
+ provider: "codex",
+ launch_header: "",
+ status: "online",
+ device_info: "Mac",
+ metadata: {},
+ owner_id: "user-1",
+ visibility: "private",
+ last_seen_at: null,
+ created_at: "2026-07-11T00:00:00Z",
+ updated_at: "2026-07-11T00:00:00Z",
+ };
+
+ renderSkillsTab({}, runtime);
+
+ expect(await screen.findByText("Local review")).toBeInTheDocument();
+ expect(screen.getByText("Host-level review workflow")).toBeInTheDocument();
});
});
diff --git a/packages/views/agents/components/tabs/skills-tab.tsx b/packages/views/agents/components/tabs/skills-tab.tsx
index d7a1c940fa..f84d480e27 100644
--- a/packages/views/agents/components/tabs/skills-tab.tsx
+++ b/packages/views/agents/components/tabs/skills-tab.tsx
@@ -1,123 +1,395 @@
"use client";
import { useState } from "react";
-import { FileText, Plus, Trash2 } from "lucide-react";
+import {
+ FileText,
+ Loader2,
+ Plus,
+ RefreshCw,
+ Server,
+ Trash2,
+} from "lucide-react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
-import type { Agent } from "@multica/core/types";
+import type {
+ Agent,
+ AgentRuntime,
+ RuntimeLocalSkillSummary,
+} from "@multica/core/types";
import { api } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
+import { runtimeCapabilitiesOptions } from "@multica/core/runtimes";
import {
+ skillDetailOptions,
skillListOptions,
workspaceKeys,
} from "@multica/core/workspace/queries";
+import { Badge } from "@multica/ui/components/ui/badge";
import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Switch } from "@multica/ui/components/ui/switch";
+import { cn } from "@multica/ui/lib/utils";
import { SkillAddDialog } from "../skill-add-dialog";
import { useT } from "../../../i18n";
+type SelectedSkill =
+ | { kind: "workspace"; id: string }
+ | { kind: "runtime"; skill: RuntimeLocalSkillSummary }
+ | null;
+
export function SkillsTab({
agent,
+ runtime,
+ canEdit = true,
}: {
agent: Agent;
+ runtime: AgentRuntime | null;
+ canEdit?: boolean;
}) {
const { t } = useT("agents");
const qc = useQueryClient();
const wsId = useWorkspaceId();
- // Same query the SkillAddDialog uses (TanStack Query dedupes by key, so
- // this isn't an extra request) — used here only to grey out the "Add
- // skill" button when the workspace has zero skills total. When skills
- // exist but are all already attached, we still open the dialog: it
- // filters out attached skills and renders a localised "no more skills
- // to add" empty state, which is more useful than a mysterious
- // greyed-out button.
const { data: workspaceSkills = [] } = useQuery(skillListOptions(wsId));
- const [removing, setRemoving] = useState(false);
+ const runtimeId =
+ runtime?.runtime_mode === "local" && runtime.status === "online"
+ ? runtime.id
+ : null;
+ const runtimeQuery = useQuery(runtimeCapabilitiesOptions(runtimeId));
+ const [busyId, setBusyId] = useState<string | null>(null);
const [showAdd, setShowAdd] = useState(false);
+ const [selected, setSelected] = useState<SelectedSkill>(null);
+ const selectedWorkspaceId = selected?.kind === "workspace" ? selected.id : "";
+ const detailQuery = useQuery(skillDetailOptions(wsId, selectedWorkspaceId));
+
+ const refreshAgent = async () => {
+ await qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ };
const handleRemove = async (skillId: string) => {
- setRemoving(true);
+ setBusyId(skillId);
try {
- const newIds = agent.skills
- .filter((s) => s.id !== skillId)
- .map((s) => s.id);
- await api.setAgentSkills(agent.id, { skill_ids: newIds });
- qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
- } catch (e) {
- toast.error(e instanceof Error ? e.message : t(($) => $.tab_body.skills.remove_failed_toast));
+ await api.removeAgentSkill(agent.id, skillId);
+ await refreshAgent();
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.tab_body.skills.remove_failed_toast),
+ );
} finally {
- setRemoving(false);
+ setBusyId(null);
}
};
+ const handleToggle = async (skillId: string, enabled: boolean) => {
+ setBusyId(skillId);
+ try {
+ await api.setAgentSkillEnabled(agent.id, skillId, enabled);
+ await refreshAgent();
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.tab_body.skills.toggle_failed_toast),
+ );
+ } finally {
+ setBusyId(null);
+ }
+ };
+
+ const runtimeSkills = runtimeQuery.data?.skills ?? [];
+
return (
- <div className="space-y-4">
- <div className="flex items-center justify-between gap-3">
- <p className="text-xs text-muted-foreground">
- {t(($) => $.tab_body.skills.intro)}
- </p>
- <Button
- variant="outline"
- size="sm"
- onClick={() => setShowAdd(true)}
- disabled={workspaceSkills.length === 0}
- className="shrink-0"
- >
- <Plus className="h-3 w-3" />
- {t(($) => $.tab_body.skills.add_action)}
- </Button>
- </div>
+ <div className="space-y-8">
+ <p className="text-sm leading-6 text-muted-foreground">
+ {t(($) => $.tab_body.skills.intro)}
+ </p>
- {agent.skills.length === 0 ? (
- <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-12">
- <FileText className="h-8 w-8 text-muted-foreground/40" />
- <p className="mt-3 text-sm text-muted-foreground">
- {t(($) => $.tab_body.skills.empty_title)}
- </p>
- <p className="mt-1 max-w-xs text-center text-xs text-muted-foreground">
- {t(($) => $.tab_body.skills.empty_hint)}
- </p>
- {workspaceSkills.length > 0 && (
+ <CapabilitySection
+ title={t(($) => $.tab_body.skills.assigned_title)}
+ description={t(($) => $.tab_body.skills.assigned_hint)}
+ action={
+ canEdit ? (
<Button
- onClick={() => setShowAdd(true)}
+ variant="outline"
size="sm"
- className="mt-3"
+ onClick={() => setShowAdd(true)}
+ disabled={workspaceSkills.length === 0}
>
- <Plus className="h-3 w-3" />
+ <Plus className="h-3.5 w-3.5" />
{t(($) => $.tab_body.skills.add_action)}
</Button>
- )}
- </div>
- ) : (
- <ul className="space-y-1.5">
- {agent.skills.map((skill) => (
- <li
- key={skill.id}
- className="flex items-center gap-2.5 rounded-md border px-3 py-2"
+ ) : null
+ }
+ >
+ {agent.skills.length === 0 ? (
+ <EmptyState
+ icon={<FileText className="h-6 w-6" />}
+ title={t(($) => $.tab_body.skills.empty_title)}
+ hint={t(($) => $.tab_body.skills.empty_hint)}
+ />
+ ) : (
+ <ul className="divide-y rounded-lg border bg-surface-raised/40">
+ {agent.skills.map((skill) => {
+ const enabled = skill.enabled !== false;
+ const busy = busyId === skill.id;
+ return (
+ <li key={skill.id} className="flex items-center gap-3 p-3">
+ <button
+ type="button"
+ onClick={() => setSelected({ kind: "workspace", id: skill.id })}
+ className="flex min-w-0 flex-1 items-center gap-3 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <span
+ className={cn(
+ "flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground",
+ !enabled && "opacity-50",
+ )}
+ >
+ <FileText className="h-4 w-4" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className={cn("block text-sm font-medium", !enabled && "text-muted-foreground")}>
+ {skill.name}
+ </span>
+ <span className="block truncate text-xs text-muted-foreground">
+ {skill.description || t(($) => $.tab_body.skills.no_description)}
+ </span>
+ </span>
+ </button>
+ {canEdit && (
+ <>
+ {busy ? (
+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground motion-reduce:animate-none" />
+ ) : (
+ <Switch
+ checked={enabled}
+ onCheckedChange={(checked) => handleToggle(skill.id, checked)}
+ aria-label={t(($) => $.tab_body.skills.toggle_aria, {
+ name: skill.name,
+ })}
+ />
+ )}
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => handleRemove(skill.id)}
+ disabled={busyId !== null}
+ aria-label={t(($) => $.tab_body.skills.remove_aria, {
+ name: skill.name,
+ })}
+ className="text-muted-foreground hover:text-destructive"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </Button>
+ </>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </CapabilitySection>
+
+ <CapabilitySection
+ title={t(($) => $.tab_body.skills.runtime_title)}
+ description={t(($) => $.tab_body.skills.runtime_hint, {
+ runtime: runtime?.custom_name || runtime?.name || "Runtime",
+ })}
+ action={
+ runtimeId ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => runtimeQuery.refetch()}
+ disabled={runtimeQuery.isFetching}
>
- <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <div className="text-sm font-medium">{skill.name}</div>
- {skill.description && (
- <div className="truncate text-xs text-muted-foreground">
- {skill.description}
- </div>
+ <RefreshCw
+ className={cn(
+ "h-3.5 w-3.5",
+ runtimeQuery.isFetching && "animate-spin motion-reduce:animate-none",
)}
- </div>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => handleRemove(skill.id)}
- disabled={removing}
- className="text-muted-foreground hover:text-destructive"
- >
- <Trash2 className="h-3.5 w-3.5" />
- </Button>
- </li>
- ))}
- </ul>
- )}
+ />
+ {t(($) => $.tab_body.skills.refresh_action)}
+ </Button>
+ ) : null
+ }
+ >
+ {!runtime ? (
+ <RuntimeNotice text={t(($) => $.tab_body.skills.runtime_missing)} />
+ ) : runtime.status !== "online" ? (
+ <RuntimeNotice text={t(($) => $.tab_body.skills.runtime_offline)} />
+ ) : runtimeQuery.isLoading ? (
+ <RuntimeNotice
+ loading
+ text={t(($) => $.tab_body.skills.runtime_discovering)}
+ />
+ ) : runtimeQuery.isError ? (
+ <RuntimeNotice text={t(($) => $.tab_body.skills.runtime_failed)} />
+ ) : runtimeQuery.data?.supported !== true ? (
+ <RuntimeNotice text={t(($) => $.tab_body.skills.runtime_unsupported)} />
+ ) : runtimeSkills.length === 0 ? (
+ <RuntimeNotice text={t(($) => $.tab_body.skills.runtime_empty)} />
+ ) : (
+ <ul className="divide-y rounded-lg border bg-surface-raised/40">
+ {runtimeSkills.map((skill) => (
+ <li key={`${skill.root ?? "unknown"}:${skill.key}`}>
+ <button
+ type="button"
+ onClick={() => setSelected({ kind: "runtime", skill })}
+ className="flex w-full items-center gap-3 p-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
+ >
+ <span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
+ <Server className="h-4 w-4" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-sm font-medium">{skill.name}</span>
+ <span className="block truncate text-xs text-muted-foreground">
+ {skill.description || skill.source_path}
+ </span>
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </CapabilitySection>
<SkillAddDialog agent={agent} open={showAdd} onOpenChange={setShowAdd} />
+ <SkillDetailDialog
+ selected={selected}
+ onOpenChange={(open) => !open && setSelected(null)}
+ workspaceSkill={detailQuery.data}
+ loading={selected?.kind === "workspace" && detailQuery.isLoading}
+ />
</div>
);
}
+
+function CapabilitySection({
+ title,
+ description,
+ action,
+ children,
+}: {
+ title: string;
+ description: string;
+ action?: React.ReactNode;
+ children: React.ReactNode;
+}) {
+ return (
+ <section className="space-y-3">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h3 className="text-sm font-medium">{title}</h3>
+ <p className="mt-1 text-xs leading-5 text-muted-foreground">{description}</p>
+ </div>
+ {action}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+function EmptyState({ icon, title, hint }: { icon: React.ReactNode; title: string; hint: string }) {
+ return (
+ <div className="flex flex-col items-center justify-center rounded-lg border border-dashed py-10 text-muted-foreground">
+ <span className="opacity-50">{icon}</span>
+ <p className="mt-3 text-sm">{title}</p>
+ <p className="mt-1 max-w-sm text-center text-xs">{hint}</p>
+ </div>
+ );
+}
+
+function RuntimeNotice({ text, loading = false }: { text: string; loading?: boolean }) {
+ return (
+ <div className="flex items-center gap-2 rounded-lg border border-dashed px-4 py-6 text-xs text-muted-foreground">
+ {loading ? (
+ <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
+ ) : (
+ <Server className="h-4 w-4" />
+ )}
+ {text}
+ </div>
+ );
+}
+
+function SkillDetailDialog({
+ selected,
+ onOpenChange,
+ workspaceSkill,
+ loading,
+}: {
+ selected: SelectedSkill;
+ onOpenChange: (open: boolean) => void;
+ workspaceSkill?: Awaited<ReturnType<typeof api.getSkill>>;
+ loading: boolean;
+}) {
+ const { t } = useT("agents");
+ const runtimeSkill = selected?.kind === "runtime" ? selected.skill : null;
+ const title = runtimeSkill?.name || workspaceSkill?.name || t(($) => $.tab_body.skills.detail_title);
+ const description = runtimeSkill?.description || workspaceSkill?.description;
+
+ return (
+ <Dialog open={selected !== null} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[80vh] overflow-y-auto sm:max-w-2xl">
+ <DialogHeader>
+ <div className="flex items-center gap-2 pr-8">
+ <DialogTitle>{title}</DialogTitle>
+ <Badge variant={runtimeSkill ? "secondary" : "outline"}>
+ {runtimeSkill
+ ? t(($) => $.tab_body.skills.inherited_badge)
+ : t(($) => $.tab_body.skills.workspace_badge)}
+ </Badge>
+ </div>
+ {description && <DialogDescription>{description}</DialogDescription>}
+ </DialogHeader>
+ {loading ? (
+ <div className="flex items-center gap-2 py-8 text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" />
+ {t(($) => $.tab_body.skills.detail_loading)}
+ </div>
+ ) : runtimeSkill ? (
+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-3 rounded-lg border p-4 text-xs">
+ <dt className="text-muted-foreground">{t(($) => $.tab_body.skills.detail_source)}</dt>
+ <dd className="break-all">{runtimeSkill.source_path}</dd>
+ <dt className="text-muted-foreground">{t(($) => $.tab_body.skills.detail_provider)}</dt>
+ <dd>{runtimeSkill.provider}</dd>
+ {runtimeSkill.plugin && (
+ <>
+ <dt className="text-muted-foreground">{t(($) => $.tab_body.skills.detail_plugin)}</dt>
+ <dd>{runtimeSkill.plugin}</dd>
+ </>
+ )}
+ <dt className="text-muted-foreground">{t(($) => $.tab_body.skills.detail_files)}</dt>
+ <dd>{runtimeSkill.file_count}</dd>
+ </dl>
+ ) : workspaceSkill ? (
+ <div className="space-y-4">
+ <div className="max-h-96 overflow-auto rounded-lg border bg-muted/30 p-4">
+ <pre className="whitespace-pre-wrap break-words font-mono text-xs leading-5">
+ {workspaceSkill.content}
+ </pre>
+ </div>
+ {(workspaceSkill.files ?? []).length > 0 && (
+ <div>
+ <h4 className="text-xs font-medium">{t(($) => $.tab_body.skills.detail_supporting_files)}</h4>
+ <div className="mt-2 flex flex-wrap gap-2">
+ {(workspaceSkill.files ?? []).map((file) => (
+ <Badge key={file.id} variant="outline">{file.path}</Badge>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index 7f9d6b098d..9d91bbc8dc 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -375,14 +375,67 @@
"save_failed_toast": "Failed to save custom arguments"
},
"mcp_config": {
- "intro": "Configure the MCP servers available to this agent. Leave this empty to use the runtime defaults.",
- "config_label": "Server configuration (JSON)",
- "placeholder": "{\n \"mcpServers\": {\n \"fetch\": {\n \"command\": \"uvx\",\n \"args\": [\"mcp-server-fetch\"]\n }\n }\n}",
- "editor_aria": "MCP config JSON editor",
- "clear_action": "Clear",
+ "intro": "Manage the MCP servers available to this agent. Servers managed by Multica are merged with servers inherited from the local runtime.",
+ "managed_title": "Managed by Multica",
+ "managed_hint": "Saved in Multica for this agent. These servers are merged with runtime servers; a Multica server wins when names match.",
+ "managed_empty": "No MCP servers are managed by Multica yet.",
+ "add_action": "Add MCP",
+ "agent_disabled_badge": "Off for agent",
+ "runtime_disabled_badge": "Off in runtime",
+ "runtime_overridden_badge": "Overridden by Multica",
+ "runtime_title": "Inherited from runtime",
+ "runtime_hint": "Discovered automatically from {{runtime}} and merged at task launch. URLs, headers, commands, and environment variables never leave the machine.",
+ "refresh_action": "Refresh",
+ "runtime_missing": "Assign a local runtime to discover inherited MCP servers.",
+ "runtime_offline": "The local runtime is offline. Reconnect it to refresh inherited MCP servers.",
+ "runtime_discovering": "Discovering MCP servers from the local runtime…",
+ "runtime_failed": "Couldn't discover runtime MCP servers. Try again when the runtime is online.",
+ "runtime_unsupported": "This runtime version cannot report its MCP inventory yet.",
+ "runtime_empty": "No MCP servers were found in the runtime's user configuration.",
+ "edit_aria": "Edit MCP server",
+ "delete_aria": "Delete MCP server",
+ "added_toast": "MCP server added",
+ "updated_toast": "MCP server updated",
+ "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_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_json_tab": "JSON",
+ "dialog_type_label": "Transport",
+ "dialog_type_stdio": "STDIO",
+ "dialog_type_http": "Streamable HTTP",
+ "dialog_command_label": "Command",
+ "dialog_command_required": "Enter the command used to launch this server.",
+ "dialog_args_label": "Arguments",
+ "dialog_add_arg": "Add argument",
+ "dialog_remove_arg": "Remove argument",
+ "dialog_env_label": "Environment variables",
+ "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_add_header": "Add header",
+ "dialog_remove_header": "Remove header",
+ "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_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",
+ "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",
"invalid_json": "Invalid JSON: {{error}}",
- "invalid_not_object": "MCP config must be a JSON object (e.g. {\"mcpServers\": …}).",
- "saved_toast": "MCP config saved",
"save_failed_toast": "Failed to save MCP config",
"redacted_title": "Configured — hidden from your view",
"redacted_hint": "Only the agent owner or a workspace admin can read this config."
@@ -424,7 +477,31 @@
"save_failed_toast": "Failed to save routing config"
},
"skills": {
- "intro": "Workspace skills assigned to this agent. Local runtime skills are always available automatically.",
+ "intro": "This is the agent's effective skill set. Workspace skills are managed here; local runtime skills are discovered automatically and inherited read-only.",
+ "assigned_title": "Assigned to agent",
+ "assigned_hint": "Workspace skills travel with the agent. Turn one off temporarily without removing it.",
+ "runtime_title": "Inherited from runtime",
+ "runtime_hint": "Discovered automatically from {{runtime}} and available whenever this agent runs there.",
+ "workspace_badge": "Workspace",
+ "inherited_badge": "Inherited",
+ "refresh_action": "Refresh",
+ "no_description": "No description",
+ "toggle_aria": "Toggle {{name}}",
+ "remove_aria": "Remove {{name}}",
+ "toggle_failed_toast": "Failed to change skill status",
+ "runtime_missing": "Assign a local runtime to discover inherited skills.",
+ "runtime_offline": "The local runtime is offline. Reconnect it to refresh inherited skills.",
+ "runtime_discovering": "Discovering skills from the local runtime…",
+ "runtime_failed": "Couldn't discover runtime skills. Try again when the runtime is online.",
+ "runtime_unsupported": "This runtime does not expose local skills.",
+ "runtime_empty": "No local skills were found for this runtime.",
+ "detail_title": "Skill details",
+ "detail_loading": "Loading skill details…",
+ "detail_source": "Source",
+ "detail_provider": "Provider",
+ "detail_plugin": "Plugin",
+ "detail_files": "Files",
+ "detail_supporting_files": "Supporting files",
"add_action": "Add skill",
"empty_title": "No skills assigned",
"empty_hint": "Add workspace skills to share team knowledge with this agent.",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 3d9fecfb8c..3ecde5039e 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -356,14 +356,67 @@
"save_failed_toast": "カスタム引数を保存できませんでした"
},
"mcp_config": {
- "intro": "このエージェントが使用できる MCP Server を設定します。空欄の場合はランタイムのデフォルトを使用します。",
- "config_label": "Server 設定(JSON)",
- "placeholder": "{\n \"mcpServers\": {\n \"fetch\": {\n \"command\": \"uvx\",\n \"args\": [\"mcp-server-fetch\"]\n }\n }\n}",
- "editor_aria": "MCP config JSON editor",
- "clear_action": "クリア",
+ "intro": "このエージェントが使用できる MCP Server を管理します。Multica 管理の Server とローカル Runtime から継承した Server は統合して使用されます。",
+ "managed_title": "Multica で管理",
+ "managed_hint": "このエージェント用に Multica に保存されます。Runtime MCP と統合され、同名の場合は Multica の設定が優先されます。",
+ "managed_empty": "Multica で管理されている MCP Server はありません。",
+ "add_action": "MCP を追加",
+ "agent_disabled_badge": "エージェントで無効",
+ "runtime_disabled_badge": "ランタイムで無効",
+ "runtime_overridden_badge": "Multica で上書き",
+ "runtime_title": "ランタイムから継承",
+ "runtime_hint": "{{runtime}} から自動検出し、タスク開始時にローカルで統合します。URL、ヘッダー、コマンド、環境変数はマシン外に送信されません。",
+ "refresh_action": "更新",
+ "runtime_missing": "継承 MCP サーバーを検出するには、ローカルランタイムを割り当ててください。",
+ "runtime_offline": "ローカルランタイムはオフラインです。再接続すると更新できます。",
+ "runtime_discovering": "ローカルランタイムから MCP サーバーを検出中…",
+ "runtime_failed": "ランタイムの MCP サーバーを検出できませんでした。",
+ "runtime_unsupported": "このランタイムバージョンはまだ MCP 一覧を報告できません。",
+ "runtime_empty": "ランタイムのユーザー設定に MCP サーバーが見つかりませんでした。",
+ "edit_aria": "MCP Server を編集",
+ "delete_aria": "MCP Server を削除",
+ "added_toast": "MCP Server を追加しました",
+ "updated_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_name_required": "Server 名を入力してください。",
+ "dialog_name_invalid": "英数字、ハイフン、アンダースコアのみ使用できます。",
+ "dialog_name_duplicate": "同名の Server がすでに存在します。",
+ "dialog_form_tab": "フォーム",
+ "dialog_json_tab": "JSON",
+ "dialog_type_label": "接続方式",
+ "dialog_type_stdio": "STDIO",
+ "dialog_type_http": "Streamable HTTP",
+ "dialog_command_label": "起動コマンド",
+ "dialog_command_required": "Server を起動するコマンドを入力してください。",
+ "dialog_args_label": "引数",
+ "dialog_add_arg": "引数を追加",
+ "dialog_remove_arg": "引数を削除",
+ "dialog_env_label": "環境変数",
+ "dialog_add_env": "環境変数を追加",
+ "dialog_remove_env": "環境変数を削除",
+ "dialog_url_label": "Server URL",
+ "dialog_url_required": "MCP Server URL を入力してください。",
+ "dialog_headers_label": "HTTP ヘッダー",
+ "dialog_add_header": "ヘッダーを追加",
+ "dialog_remove_header": "ヘッダーを削除",
+ "dialog_native_json_hint": "過去の Provider ネイティブ形式です。形式を変更せず JSON で編集できます。",
+ "dialog_json_label": "単一 Server 設定",
+ "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": "変更を保存",
+ "delete_dialog_title": "MCP Server を削除しますか?",
+ "delete_dialog_description": "{{name}} はこのエージェントで利用できなくなります。Runtime Server には影響しません。",
+ "delete_action": "Server を削除",
"invalid_json": "無効な JSON: {{error}}",
- "invalid_not_object": "MCP config は JSON object である必要があります(例: {\"mcpServers\": …})。",
- "saved_toast": "MCP config を保存しました",
"save_failed_toast": "MCP config を保存できませんでした",
"redacted_title": "設定済み — 現在の表示では非表示",
"redacted_hint": "この config を読み取れるのは、エージェントのオーナーまたはワークスペースの admin のみです。"
@@ -405,6 +458,30 @@
"save_failed_toast": "ルーティング設定の保存に失敗しました"
},
"skills": {
+ "assigned_title": "エージェントに割り当て済み",
+ "assigned_hint": "ワークスペースのスキルはエージェントと一緒に移動します。削除せず一時的に無効化できます。",
+ "runtime_title": "ランタイムから継承",
+ "runtime_hint": "{{runtime}} から自動検出され、このエージェントがそこで実行されるときに利用できます。",
+ "workspace_badge": "ワークスペース",
+ "inherited_badge": "継承",
+ "refresh_action": "更新",
+ "no_description": "説明なし",
+ "toggle_aria": "{{name}} の有効・無効を切り替え",
+ "remove_aria": "{{name}} を削除",
+ "toggle_failed_toast": "スキルの状態を変更できませんでした",
+ "runtime_missing": "継承スキルを検出するには、ローカルランタイムを割り当ててください。",
+ "runtime_offline": "ローカルランタイムはオフラインです。再接続すると更新できます。",
+ "runtime_discovering": "ローカルランタイムからスキルを検出中…",
+ "runtime_failed": "ランタイムのスキルを検出できませんでした。",
+ "runtime_unsupported": "このランタイムはローカルスキルを公開していません。",
+ "runtime_empty": "このランタイムにローカルスキルが見つかりませんでした。",
+ "detail_title": "スキルの詳細",
+ "detail_loading": "スキルの詳細を読み込み中…",
+ "detail_source": "ソース",
+ "detail_provider": "プロバイダー",
+ "detail_plugin": "プラグイン",
+ "detail_files": "ファイル",
+ "detail_supporting_files": "関連ファイル",
"intro": "このエージェントに割り当てられたワークスペースのスキルです。ローカルランタイムのスキルは常に自動的に利用できます。",
"add_action": "スキルを追加",
"empty_title": "割り当てられたスキルがありません",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 460e8ab0a8..cc1d28f226 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -364,14 +364,67 @@
"save_failed_toast": "사용자 지정 인자를 저장하지 못했습니다"
},
"mcp_config": {
- "intro": "이 에이전트가 사용할 MCP Server를 설정하세요. 비워 두면 런타임 기본값을 사용합니다.",
- "config_label": "Server 설정(JSON)",
- "placeholder": "{\n \"mcpServers\": {\n \"fetch\": {\n \"command\": \"uvx\",\n \"args\": [\"mcp-server-fetch\"]\n }\n }\n}",
- "editor_aria": "MCP config JSON editor",
- "clear_action": "지우기",
+ "intro": "이 에이전트가 사용할 수 있는 MCP Server를 관리합니다. Multica에서 관리하는 Server와 로컬 Runtime에서 상속한 Server가 함께 사용됩니다.",
+ "managed_title": "Multica에서 관리",
+ "managed_hint": "이 에이전트용으로 Multica에 저장됩니다. Runtime MCP와 병합되며 이름이 같으면 Multica 설정이 우선합니다.",
+ "managed_empty": "Multica에서 관리하는 MCP Server가 없습니다.",
+ "add_action": "MCP 추가",
+ "agent_disabled_badge": "에이전트에서 꺼짐",
+ "runtime_disabled_badge": "런타임에서 꺼짐",
+ "runtime_overridden_badge": "Multica에서 재정의",
+ "runtime_title": "런타임에서 상속",
+ "runtime_hint": "{{runtime}}에서 자동으로 탐색하고 작업 시작 시 로컬에서 병합합니다. URL, 헤더, 명령 및 환경 변수는 머신 외부로 전송되지 않습니다.",
+ "refresh_action": "새로고침",
+ "runtime_missing": "상속된 MCP 서버를 탐색하려면 로컬 런타임을 할당하세요.",
+ "runtime_offline": "로컬 런타임이 오프라인입니다. 다시 연결하면 새로고침할 수 있습니다.",
+ "runtime_discovering": "로컬 런타임에서 MCP 서버를 탐색하는 중…",
+ "runtime_failed": "런타임 MCP 서버를 탐색하지 못했습니다.",
+ "runtime_unsupported": "이 런타임 버전은 아직 MCP 목록을 보고할 수 없습니다.",
+ "runtime_empty": "런타임 사용자 설정에서 MCP 서버를 찾지 못했습니다.",
+ "edit_aria": "MCP Server 편집",
+ "delete_aria": "MCP Server 삭제",
+ "added_toast": "MCP Server를 추가했습니다",
+ "updated_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_name_required": "Server 이름을 입력하세요.",
+ "dialog_name_invalid": "문자, 숫자, 하이픈, 밑줄만 사용할 수 있습니다.",
+ "dialog_name_duplicate": "같은 이름의 Server가 이미 있습니다.",
+ "dialog_form_tab": "폼 설정",
+ "dialog_json_tab": "JSON 설정",
+ "dialog_type_label": "연결 방식",
+ "dialog_type_stdio": "STDIO",
+ "dialog_type_http": "Streamable HTTP",
+ "dialog_command_label": "실행 명령",
+ "dialog_command_required": "Server를 실행할 명령을 입력하세요.",
+ "dialog_args_label": "인자",
+ "dialog_add_arg": "인자 추가",
+ "dialog_remove_arg": "인자 제거",
+ "dialog_env_label": "환경 변수",
+ "dialog_add_env": "환경 변수 추가",
+ "dialog_remove_env": "환경 변수 제거",
+ "dialog_url_label": "Server URL",
+ "dialog_url_required": "MCP Server URL을 입력하세요.",
+ "dialog_headers_label": "HTTP 헤더",
+ "dialog_add_header": "헤더 추가",
+ "dialog_remove_header": "헤더 제거",
+ "dialog_native_json_hint": "기존 Provider 네이티브 형식입니다. 형식을 변경하지 않고 JSON으로 편집할 수 있습니다.",
+ "dialog_json_label": "단일 Server 설정",
+ "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": "변경 저장",
+ "delete_dialog_title": "MCP Server를 삭제할까요?",
+ "delete_dialog_description": "{{name}}은 더 이상 이 에이전트에서 사용할 수 없습니다. Runtime Server에는 영향을 주지 않습니다.",
+ "delete_action": "Server 삭제",
"invalid_json": "잘못된 JSON: {{error}}",
- "invalid_not_object": "MCP config는 JSON object여야 합니다(예: {\"mcpServers\": …}).",
- "saved_toast": "MCP config를 저장했습니다",
"save_failed_toast": "MCP config를 저장하지 못했습니다",
"redacted_title": "설정됨 - 현재 보기에서는 숨김",
"redacted_hint": "에이전트 소유자 또는 워크스페이스 관리자만 이 config를 읽을 수 있습니다."
@@ -413,6 +466,30 @@
"save_failed_toast": "라우팅 설정 저장 실패"
},
"skills": {
+ "assigned_title": "에이전트에 할당됨",
+ "assigned_hint": "워크스페이스 스킬은 에이전트와 함께 이동합니다. 제거하지 않고 일시적으로 끌 수 있습니다.",
+ "runtime_title": "런타임에서 상속",
+ "runtime_hint": "{{runtime}}에서 자동으로 탐색되며 이 에이전트가 해당 런타임에서 실행될 때 사용할 수 있습니다.",
+ "workspace_badge": "워크스페이스",
+ "inherited_badge": "상속됨",
+ "refresh_action": "새로고침",
+ "no_description": "설명 없음",
+ "toggle_aria": "{{name}} 켜기 또는 끄기",
+ "remove_aria": "{{name}} 제거",
+ "toggle_failed_toast": "스킬 상태를 변경하지 못했습니다",
+ "runtime_missing": "상속된 스킬을 탐색하려면 로컬 런타임을 할당하세요.",
+ "runtime_offline": "로컬 런타임이 오프라인입니다. 다시 연결하면 새로고침할 수 있습니다.",
+ "runtime_discovering": "로컬 런타임에서 스킬을 탐색하는 중…",
+ "runtime_failed": "런타임 스킬을 탐색하지 못했습니다.",
+ "runtime_unsupported": "이 런타임은 로컬 스킬을 제공하지 않습니다.",
+ "runtime_empty": "이 런타임에서 로컬 스킬을 찾지 못했습니다.",
+ "detail_title": "스킬 상세 정보",
+ "detail_loading": "스킬 상세 정보를 불러오는 중…",
+ "detail_source": "소스",
+ "detail_provider": "제공자",
+ "detail_plugin": "플러그인",
+ "detail_files": "파일",
+ "detail_supporting_files": "지원 파일",
"intro": "이 에이전트에 할당된 워크스페이스 스킬입니다. 로컬 런타임 스킬은 항상 자동으로 사용할 수 있습니다.",
"add_action": "스킬 추가",
"empty_title": "할당된 스킬이 없습니다",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 8e9990c3bc..5b461f64bb 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -364,14 +364,67 @@
"save_failed_toast": "保存自定义参数失败"
},
"mcp_config": {
- "intro": "配置这个智能体可以使用的 MCP Server。留空时使用运行时的默认配置。",
- "config_label": "Server 配置(JSON)",
- "placeholder": "{\n \"mcpServers\": {\n \"fetch\": {\n \"command\": \"uvx\",\n \"args\": [\"mcp-server-fetch\"]\n }\n }\n}",
- "editor_aria": "MCP 配置 JSON 编辑器",
- "clear_action": "清空",
+ "intro": "管理该智能体可用的 MCP Server。由 Multica 管理的 Server 会与本地 Runtime 继承的 Server 合并使用。",
+ "managed_title": "由 Multica 管理",
+ "managed_hint": "保存在 Multica 中并仅配置给该智能体。执行任务时会与 Runtime MCP 合并;名称相同时以 Multica 配置为准。",
+ "managed_empty": "还没有由 Multica 管理的 MCP Server。",
+ "add_action": "添加 MCP",
+ "agent_disabled_badge": "已为智能体关闭",
+ "runtime_disabled_badge": "运行时中已关闭",
+ "runtime_overridden_badge": "已由 Multica 覆盖",
+ "runtime_title": "从运行时继承",
+ "runtime_hint": "自动从 {{runtime}} 发现,并在任务启动时于本机完成合并。URL、Header、命令和环境变量等敏感值不会离开本机。",
+ "refresh_action": "刷新",
+ "runtime_missing": "请先分配一个本地运行时,以发现继承的 MCP Server。",
+ "runtime_offline": "本地运行时处于离线状态,重新连接后即可刷新继承的 MCP Server。",
+ "runtime_discovering": "正在从本地运行时发现 MCP Server…",
+ "runtime_failed": "无法发现运行时 MCP Server,请在运行时在线后重试。",
+ "runtime_unsupported": "当前运行时版本暂时无法上报 MCP 清单。",
+ "runtime_empty": "运行时的用户配置中没有发现 MCP Server。",
+ "edit_aria": "编辑 MCP Server",
+ "delete_aria": "删除 MCP Server",
+ "added_toast": "已添加 MCP Server",
+ "updated_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_name_required": "请输入 Server 名称。",
+ "dialog_name_invalid": "名称只能包含字母、数字、连字符和下划线。",
+ "dialog_name_duplicate": "已经存在同名的 Server。",
+ "dialog_form_tab": "表单配置",
+ "dialog_json_tab": "JSON 配置",
+ "dialog_type_label": "连接方式",
+ "dialog_type_stdio": "STDIO",
+ "dialog_type_http": "Streamable HTTP",
+ "dialog_command_label": "启动命令",
+ "dialog_command_required": "请输入启动该 Server 的命令。",
+ "dialog_args_label": "参数",
+ "dialog_add_arg": "添加参数",
+ "dialog_remove_arg": "移除参数",
+ "dialog_env_label": "环境变量",
+ "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_native_json_hint": "这是历史 Provider 原生格式,将继续以 JSON 原样编辑,不会自动转换。",
+ "dialog_json_label": "单个 Server 配置",
+ "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": "保存修改",
+ "delete_dialog_title": "删除 MCP Server?",
+ "delete_dialog_description": "{{name}} 将不再提供给该智能体;Runtime 中的 Server 不受影响。",
+ "delete_action": "删除 Server",
"invalid_json": "JSON 无效:{{error}}",
- "invalid_not_object": "MCP 配置必须是 JSON 对象(例如 {\"mcpServers\": …})。",
- "saved_toast": "已保存 MCP 配置",
"save_failed_toast": "保存 MCP 配置失败",
"redacted_title": "已配置 —— 当前账号无权查看",
"redacted_hint": "只有智能体所有者或工作区管理员可以读取该配置。"
@@ -413,7 +466,31 @@
"save_failed_toast": "保存路由配置失败"
},
"skills": {
- "intro": "分配给该智能体的工作区 skill。本地运行时 skill 会自动可用。",
+ "intro": "这里展示该智能体实际拥有的全部 skill。工作区 skill 可在此管理;本地运行时 skill 会自动发现并以只读方式继承。",
+ "assigned_title": "分配给智能体",
+ "assigned_hint": "工作区 skill 会跟随智能体。你可以临时关闭,而不必将其移除。",
+ "runtime_title": "从运行时继承",
+ "runtime_hint": "自动从 {{runtime}} 发现;只要该智能体在这个运行时执行,就可以直接使用。",
+ "workspace_badge": "工作区",
+ "inherited_badge": "继承",
+ "refresh_action": "刷新",
+ "no_description": "暂无描述",
+ "toggle_aria": "启用或关闭 {{name}}",
+ "remove_aria": "移除 {{name}}",
+ "toggle_failed_toast": "修改 skill 状态失败",
+ "runtime_missing": "请先分配一个本地运行时,以发现继承的 skill。",
+ "runtime_offline": "本地运行时处于离线状态,重新连接后即可刷新继承的 skill。",
+ "runtime_discovering": "正在从本地运行时发现 skill…",
+ "runtime_failed": "无法发现运行时 skill,请在运行时在线后重试。",
+ "runtime_unsupported": "该运行时不支持本地 skill 发现。",
+ "runtime_empty": "该运行时中没有发现本地 skill。",
+ "detail_title": "Skill 详情",
+ "detail_loading": "正在加载 skill 详情…",
+ "detail_source": "来源",
+ "detail_provider": "提供方",
+ "detail_plugin": "插件",
+ "detail_files": "文件数",
+ "detail_supporting_files": "附属文件",
"add_action": "添加 skill",
"empty_title": "尚未分配 skill",
"empty_hint": "添加工作区 skill,把团队知识共享给这个智能体。",
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 066bd2f010..255158e1c5 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1143,6 +1143,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/skills", h.ListAgentSkills)
r.Put("/skills", h.SetAgentSkills)
r.Post("/skills/add", h.AddAgentSkills)
+ r.Put("/skills/{skillId}/enabled", h.SetAgentSkillEnabled)
+ r.Delete("/skills/{skillId}", h.RemoveAgentSkill)
// Dedicated env-management endpoint. Owner/admin only;
// agent actors are denied. Every reveal / write is
// audited to activity_log. See MUL-2600 and
diff --git a/server/internal/daemon/claude_plugins.go b/server/internal/daemon/claude_plugins.go
new file mode 100644
index 0000000000..0900509d10
--- /dev/null
+++ b/server/internal/daemon/claude_plugins.go
@@ -0,0 +1,139 @@
+package daemon
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+)
+
+type claudePluginInstall struct {
+ ID string
+ Name string
+ InstallPath string
+}
+
+type claudeInstalledPluginsFile struct {
+ Plugins map[string][]struct {
+ Scope string `json:"scope"`
+ InstallPath string `json:"installPath"`
+ } `json:"plugins"`
+}
+
+type claudeSettingsFile struct {
+ EnabledPlugins map[string]bool `json:"enabledPlugins"`
+}
+
+type claudePluginManifest struct {
+ Name string `json:"name"`
+ Skills json.RawMessage `json:"skills"`
+ MCPServers json.RawMessage `json:"mcpServers"`
+}
+
+// listEnabledClaudePlugins resolves the current user-scope plugin installs
+// that Claude Code itself has enabled. Reading the install registry is
+// deliberate: recursively scanning ~/.claude/plugins would surface both the
+// marketplace checkout and every cached version of the same plugin.
+func listEnabledClaudePlugins(home string) []claudePluginInstall {
+ settingsRaw, err := os.ReadFile(filepath.Join(home, ".claude", "settings.json"))
+ if err != nil {
+ return nil
+ }
+ var settings claudeSettingsFile
+ if json.Unmarshal(settingsRaw, &settings) != nil || len(settings.EnabledPlugins) == 0 {
+ return nil
+ }
+
+ installedRaw, err := os.ReadFile(filepath.Join(home, ".claude", "plugins", "installed_plugins.json"))
+ if err != nil {
+ return nil
+ }
+ var installed claudeInstalledPluginsFile
+ if json.Unmarshal(installedRaw, &installed) != nil {
+ return nil
+ }
+
+ pluginIDs := make([]string, 0, len(settings.EnabledPlugins))
+ for id, enabled := range settings.EnabledPlugins {
+ if enabled {
+ pluginIDs = append(pluginIDs, id)
+ }
+ }
+ sort.Strings(pluginIDs)
+
+ plugins := make([]claudePluginInstall, 0, len(pluginIDs))
+ for _, id := range pluginIDs {
+ installs := installed.Plugins[id]
+ if len(installs) == 0 {
+ continue
+ }
+ selected := installs[len(installs)-1]
+ for _, install := range installs {
+ if install.Scope == "user" {
+ selected = install
+ }
+ }
+ installPath := strings.TrimSpace(selected.InstallPath)
+ if installPath == "" {
+ continue
+ }
+
+ name := strings.TrimSpace(strings.SplitN(id, "@", 2)[0])
+ if manifest, ok := readClaudePluginManifest(installPath); ok && strings.TrimSpace(manifest.Name) != "" {
+ name = strings.TrimSpace(manifest.Name)
+ }
+ if name == "" {
+ continue
+ }
+ plugins = append(plugins, claudePluginInstall{ID: id, Name: name, InstallPath: installPath})
+ }
+ return plugins
+}
+
+func readClaudePluginManifest(installPath string) (claudePluginManifest, bool) {
+ raw, err := os.ReadFile(filepath.Join(installPath, ".claude-plugin", "plugin.json"))
+ if err != nil {
+ return claudePluginManifest{}, false
+ }
+ var manifest claudePluginManifest
+ if json.Unmarshal(raw, &manifest) != nil {
+ return claudePluginManifest{}, false
+ }
+ return manifest, true
+}
+
+func claudePluginComponentPaths(installPath string, raw json.RawMessage, defaults ...string) []string {
+ paths := append([]string(nil), defaults...)
+ var one string
+ if json.Unmarshal(raw, &one) == nil && strings.TrimSpace(one) != "" {
+ paths = append(paths, one)
+ } else {
+ var many []string
+ if json.Unmarshal(raw, &many) == nil {
+ paths = append(paths, many...)
+ }
+ }
+
+ seen := make(map[string]bool)
+ out := make([]string, 0, len(paths))
+ for _, candidate := range paths {
+ candidate = strings.TrimSpace(candidate)
+ if candidate == "" {
+ continue
+ }
+ if !filepath.IsAbs(candidate) {
+ candidate = filepath.Join(installPath, filepath.FromSlash(candidate))
+ }
+ candidate = filepath.Clean(candidate)
+ rel, err := filepath.Rel(installPath, candidate)
+ if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ continue
+ }
+ if !seen[candidate] {
+ seen[candidate] = true
+ out = append(out, candidate)
+ }
+ }
+ return out
+}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 56f4f025c1..9a9d4d6ddb 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -2138,11 +2138,19 @@ func (d *Daemon) handleLocalSkillList(ctx context.Context, rt Runtime, requestID
})
return
}
+ mcpServers, mcpSupported, err := listRuntimeLocalMcpServers(rt.Provider)
+ if err != nil {
+ d.logger.Warn("runtime local MCP discovery failed", "runtime_id", rt.ID, "provider", rt.Provider, "error", err)
+ mcpServers = []runtimeLocalMcpServerSummary{}
+ mcpSupported = false
+ }
d.reportLocalSkillListResult(ctx, rt, requestID, map[string]any{
- "status": "completed",
- "skills": skills,
- "supported": supported,
+ "status": "completed",
+ "skills": skills,
+ "supported": supported,
+ "mcp_servers": mcpServers,
+ "mcp_supported": mcpSupported,
})
}
@@ -3589,9 +3597,19 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// Squad-leader tasks also skip reuse so a pre-fix leader session recorded
// against the user's local_directory cannot be re-entered without a lock.
var agentMcpConfig json.RawMessage
+ var effectiveMcpConfig json.RawMessage
var cursorMcpAuthSource string
if task.Agent != nil {
agentMcpConfig = task.Agent.McpConfig
+ effectiveMcpConfig = agentMcpConfig
+ if merged, mergeErr := mergeRuntimeAndAgentMcpConfig(provider, agentMcpConfig); mergeErr != nil {
+ taskLog.Warn("mcp_config: runtime merge failed; using agent configuration only",
+ "provider", provider,
+ "error", mergeErr,
+ )
+ } else {
+ effectiveMcpConfig = merged
+ }
if provider == "cursor" {
cursorMcpAuthSource = strings.TrimSpace(task.Agent.CustomEnv[execenv.CursorMcpAuthSourceEnv])
}
@@ -3612,7 +3630,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
Provider: provider,
CodexVersion: codexVersion,
OpenclawBin: openclawBin,
- McpConfig: agentMcpConfig,
+ McpConfig: effectiveMcpConfig,
CursorMcpAuthSource: cursorMcpAuthSource,
OpenclawGateway: openclawGateway,
Task: taskCtx,
@@ -3628,7 +3646,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
Provider: provider,
CodexVersion: codexVersion,
OpenclawBin: openclawBin,
- McpConfig: agentMcpConfig,
+ McpConfig: effectiveMcpConfig,
CursorMcpAuthSource: cursorMcpAuthSource,
OpenclawGateway: openclawGateway,
Task: taskCtx,
@@ -3840,7 +3858,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
var mcpConfig json.RawMessage
if task.Agent != nil {
customArgs = task.Agent.CustomArgs
- mcpConfig = task.Agent.McpConfig
+ mcpConfig = effectiveMcpConfig
}
// Two-tier model resolution: an explicit agent.model wins,
// then the daemon-wide MULTICA_<PROVIDER>_MODEL env var. If
diff --git a/server/internal/daemon/local_skills.go b/server/internal/daemon/local_skills.go
index 4ff5916990..35672f526c 100644
--- a/server/internal/daemon/local_skills.go
+++ b/server/internal/daemon/local_skills.go
@@ -38,6 +38,7 @@ type runtimeLocalSkillSummary struct {
// server treats an empty value as "unknown" rather than a provider/
// universal assertion.
Root string `json:"root,omitempty"`
+ Plugin string `json:"plugin,omitempty"`
FileCount int `json:"file_count"`
}
@@ -55,8 +56,10 @@ type runtimeLocalSkillBundle struct {
// localSkillRootsForProvider; the kind is surfaced to the UI on each
// discovered skill (see runtimeLocalSkillSummary.Root).
type localSkillRoot struct {
- path string
- kind string
+ path string
+ kind string
+ keyPrefix string
+ plugin string
}
const (
@@ -68,6 +71,11 @@ const (
// universal home-level skill store. It is always searched last so a
// same-key skill in the provider directory keeps winning.
localSkillRootUniversal = "universal"
+ // localSkillRootPlugin marks skills contributed by an enabled runtime
+ // plugin. Plugin roots use a namespace prefix so their invocation keys
+ // match Claude Code (for example paper-desktop:design-to-code) and never
+ // collide with standalone user skills.
+ localSkillRootPlugin = "plugin"
)
// localSkillRootsForProvider returns the ordered user-level skill roots
@@ -150,10 +158,28 @@ func localSkillRootsForProvider(provider string) ([]localSkillRoot, bool, error)
return nil, false, nil
}
- return []localSkillRoot{
+ roots := []localSkillRoot{
{path: providerRoot, kind: localSkillRootProvider},
{path: filepath.Join(home, ".agents", "skills"), kind: localSkillRootUniversal},
- }, true, nil
+ }
+ if provider == "claude" || provider == "codebuddy" {
+ for _, plugin := range listEnabledClaudePlugins(home) {
+ manifest, _ := readClaudePluginManifest(plugin.InstallPath)
+ for _, path := range claudePluginComponentPaths(
+ plugin.InstallPath,
+ manifest.Skills,
+ filepath.Join(plugin.InstallPath, "skills"),
+ ) {
+ roots = append(roots, localSkillRoot{
+ path: path,
+ kind: localSkillRootPlugin,
+ keyPrefix: plugin.Name + ":",
+ plugin: plugin.ID,
+ })
+ }
+ }
+ }
+ return roots, true, nil
}
func isIgnoredLocalSkillEntry(name string) bool {
@@ -332,7 +358,7 @@ func listRuntimeLocalSkills(provider string) ([]runtimeLocalSkillSummary, bool,
// drop the legitimate second entry.
rootSkills := make([]runtimeLocalSkillSummary, 0)
visited := make(map[string]bool)
- enumerateLocalSkills(provider, root.kind, root.path, root.path, 0, visited, &rootSkills)
+ enumerateLocalSkills(provider, root, root.path, root.path, 0, visited, &rootSkills)
for _, s := range rootSkills {
if seenKeys[s.Key] {
@@ -362,7 +388,9 @@ func listRuntimeLocalSkills(provider string) ([]runtimeLocalSkillSummary, bool,
// EvalSymlinks up front. Errors from EvalSymlinks just stop the descent on
// that branch — most often it's a dangling link, which we want to ignore.
func enumerateLocalSkills(
- provider, rootKind, walkRoot, currentDir string,
+ provider string,
+ root localSkillRoot,
+ walkRoot, currentDir string,
depth int,
visited map[string]bool,
skills *[]runtimeLocalSkillSummary,
@@ -405,13 +433,16 @@ func enumerateLocalSkills(
if err != nil {
continue
}
+ key = root.keyPrefix + key
content, err := readLocalSkillMainFile(path)
if err != nil {
continue
}
skillName, description := skill.ParseSkillFrontmatter(content)
- if skillName == "" {
+ if root.plugin != "" {
+ skillName = key
+ } else if skillName == "" {
skillName = filepath.Base(path)
}
@@ -426,7 +457,8 @@ func enumerateLocalSkills(
Description: description,
SourcePath: relativizeHomePath(path),
Provider: provider,
- Root: rootKind,
+ Root: root.kind,
+ Plugin: root.plugin,
// `files` is the supporting bundle (collectLocalSkillFiles
// intentionally excludes SKILL.md so the bundle's `Content`
// field can carry it without duplication on import). For the
@@ -438,7 +470,7 @@ func enumerateLocalSkills(
}
// No SKILL.md here — descend looking for nested skills.
- enumerateLocalSkills(provider, rootKind, walkRoot, path, depth+1, visited, skills)
+ enumerateLocalSkills(provider, root, walkRoot, path, depth+1, visited, skills)
}
}
@@ -464,7 +496,14 @@ func loadRuntimeLocalSkillBundle(provider, skillKey string) (*runtimeLocalSkillB
// returned, so we never silently substitute a different-content same-key
// skill from a lower-priority root.
for _, root := range roots {
- skillDir := filepath.Join(root.path, filepath.FromSlash(key))
+ rootKey := key
+ if root.keyPrefix != "" {
+ if !strings.HasPrefix(key, root.keyPrefix) {
+ continue
+ }
+ rootKey = strings.TrimPrefix(key, root.keyPrefix)
+ }
+ skillDir := filepath.Join(root.path, filepath.FromSlash(rootKey))
info, err := os.Stat(skillDir)
if err != nil {
// IsNotExist => this root simply lacks the skill, try the next.
@@ -504,7 +543,9 @@ func loadRuntimeLocalSkillBundle(provider, skillKey string) (*runtimeLocalSkillB
return nil, true, err
}
name, description := skill.ParseSkillFrontmatter(content)
- if name == "" {
+ if root.plugin != "" {
+ name = key
+ } else if name == "" {
name = filepath.Base(skillDir)
}
diff --git a/server/internal/daemon/local_skills_test.go b/server/internal/daemon/local_skills_test.go
index 32618498f7..2c85ef11c0 100644
--- a/server/internal/daemon/local_skills_test.go
+++ b/server/internal/daemon/local_skills_test.go
@@ -26,6 +26,33 @@ func writeTestLocalSkill(t *testing.T, root, rel string, files map[string]string
return skillDir
}
+func writeTestClaudePlugin(t *testing.T, home, id, name string, enabled bool) string {
+ t.Helper()
+ installPath := filepath.Join(home, ".claude", "plugins", "cache", name, "1.0.0")
+ if err := os.MkdirAll(filepath.Join(installPath, ".claude-plugin"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ manifest := `{"name":"` + name + `","skills":"./skills","mcpServers":"./mcp.json"}`
+ if err := os.WriteFile(filepath.Join(installPath, ".claude-plugin", "plugin.json"), []byte(manifest), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Join(home, ".claude", "plugins"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ installed := `{"version":2,"plugins":{"` + id + `":[{"scope":"user","installPath":"` + installPath + `"}]}}`
+ if err := os.WriteFile(filepath.Join(home, ".claude", "plugins", "installed_plugins.json"), []byte(installed), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Join(home, ".claude"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ settings := `{"enabledPlugins":{"` + id + `":` + map[bool]string{true: "true", false: "false"}[enabled] + `}}`
+ if err := os.WriteFile(filepath.Join(home, ".claude", "settings.json"), []byte(settings), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return installPath
+}
+
func TestListRuntimeLocalSkills_Claude(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
@@ -70,6 +97,55 @@ func TestListRuntimeLocalSkills_Claude(t *testing.T) {
}
}
+func TestListRuntimeLocalSkills_ClaudeEnabledPlugin(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", true)
+ writeTestLocalSkill(t, filepath.Join(installPath, "skills"), "design-to-code", map[string]string{
+ "SKILL.md": "---\nname: Design to code\ndescription: Turn a design into code\n---\n# Design\n",
+ })
+
+ skills, supported, err := listRuntimeLocalSkills("claude")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !supported || len(skills) != 1 {
+ t.Fatalf("supported=%v skills=%#v", supported, skills)
+ }
+ got := skills[0]
+ if got.Key != "paper-desktop:design-to-code" || got.Name != "paper-desktop:design-to-code" {
+ t.Fatalf("plugin skill identity = %#v", got)
+ }
+ if got.Root != localSkillRootPlugin || got.Plugin != "paper-desktop@paper" {
+ t.Fatalf("plugin skill origin = %#v", got)
+ }
+
+ bundle, supported, err := loadRuntimeLocalSkillBundle("claude", got.Key)
+ if err != nil || !supported {
+ t.Fatalf("load plugin bundle: supported=%v err=%v", supported, err)
+ }
+ if bundle.Name != got.Key || bundle.Description != "Turn a design into code" {
+ t.Fatalf("plugin bundle = %#v", bundle)
+ }
+}
+
+func TestListRuntimeLocalSkills_ClaudeDisabledPluginIsHidden(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", false)
+ writeTestLocalSkill(t, filepath.Join(installPath, "skills"), "design-to-code", map[string]string{
+ "SKILL.md": "---\nname: Design to code\n---\n",
+ })
+
+ skills, supported, err := listRuntimeLocalSkills("claude")
+ if err != nil || !supported {
+ t.Fatalf("supported=%v err=%v", supported, err)
+ }
+ if len(skills) != 0 {
+ t.Fatalf("disabled plugin skills should be hidden, got %#v", skills)
+ }
+}
+
func TestListRuntimeLocalSkills_Kiro(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
diff --git a/server/internal/daemon/runtime_mcp.go b/server/internal/daemon/runtime_mcp.go
new file mode 100644
index 0000000000..9e48f2362c
--- /dev/null
+++ b/server/internal/daemon/runtime_mcp.go
@@ -0,0 +1,375 @@
+package daemon
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/pelletier/go-toml/v2"
+)
+
+// runtimeLocalMcpServerSummary is the intentionally non-secret inventory
+// shown in Agent capabilities. Never add command arguments, URLs, headers, or
+// environment values here: this payload leaves the user's machine.
+type runtimeLocalMcpServerSummary struct {
+ Name string `json:"name"`
+ Transport string `json:"transport,omitempty"`
+ Source string `json:"source,omitempty"`
+ Enabled bool `json:"enabled"`
+}
+
+// mergeRuntimeAndAgentMcpConfig builds the task-local MCP configuration used
+// when an agent has MCP servers managed by Multica. Runtime servers are the
+// base layer and the agent's entries win on a same-name collision. The merge
+// happens inside the local daemon so runtime URLs, headers, commands, and env
+// values never need to leave the machine.
+//
+// A nil/null agent config keeps the provider's native inheritance path intact.
+// A present config (including an empty mcpServers map) opts into the merged,
+// task-local config so adding one managed server no longer disables unrelated
+// runtime servers.
+func mergeRuntimeAndAgentMcpConfig(provider string, agentConfig json.RawMessage) (json.RawMessage, error) {
+ trimmed := bytes.TrimSpace(agentConfig)
+ if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
+ return agentConfig, nil
+ }
+
+ runtimeServers, supported, err := loadRuntimeMcpServerConfigs(provider)
+ if err != nil {
+ return nil, err
+ }
+ if !supported {
+ return agentConfig, nil
+ }
+
+ var agentDocument map[string]any
+ if err := json.Unmarshal(trimmed, &agentDocument); err != nil {
+ return nil, fmt.Errorf("parse agent MCP config: %w", err)
+ }
+ agentServers := map[string]any{}
+ if servers, ok := nestedRuntimeMcpMap(agentDocument, "mcpServers"); ok {
+ agentServers = servers
+ } else if provider == "opencode" {
+ // Older OpenCode agents may store the provider-native top-level `mcp`
+ // map. Its individual entries can still flow through the existing
+ // OpenCode adapter when placed under the canonical mcpServers envelope.
+ if servers, ok := nestedRuntimeMcpMap(agentDocument, "mcp"); ok {
+ agentServers = servers
+ }
+ }
+
+ merged := make(map[string]any, len(runtimeServers)+len(agentServers))
+ for name, entry := range runtimeServers {
+ merged[name] = entry
+ }
+ for name, entry := range agentServers {
+ merged[name] = entry
+ }
+
+ raw, err := json.Marshal(map[string]any{"mcpServers": merged})
+ if err != nil {
+ return nil, fmt.Errorf("marshal merged MCP config: %w", err)
+ }
+ return raw, nil
+}
+
+// loadRuntimeMcpServerConfigs returns full, secret-bearing runtime MCP entries
+// for task-local merging. Callers must never send the result to the server or
+// logs; the public capabilities endpoint continues to use the redacted summary
+// type above.
+func loadRuntimeMcpServerConfigs(provider string) (map[string]any, bool, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return nil, false, fmt.Errorf("resolve user home: %w", err)
+ }
+
+ var path, key, format string
+ switch provider {
+ case "claude", "codebuddy":
+ path, key, format = filepath.Join(home, ".claude.json"), "mcpServers", "json"
+ case "codex":
+ codexHome := strings.TrimSpace(os.Getenv("CODEX_HOME"))
+ if codexHome == "" {
+ codexHome = filepath.Join(home, ".codex")
+ }
+ path, key, format = filepath.Join(codexHome, "config.toml"), "mcp_servers", "toml"
+ case "cursor":
+ path, key, format = filepath.Join(home, ".cursor", "mcp.json"), "mcpServers", "json"
+ case "opencode":
+ configHome := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME"))
+ if configHome == "" {
+ configHome = filepath.Join(home, ".config")
+ }
+ path, key, format = filepath.Join(configHome, "opencode", "opencode.json"), "mcp", "json"
+ case "openclaw":
+ path = strings.TrimSpace(os.Getenv("CLAWDBOT_CONFIG_PATH"))
+ if path == "" {
+ stateDir := strings.TrimSpace(os.Getenv("OPENCLAW_STATE_DIR"))
+ if stateDir == "" {
+ stateDir = filepath.Join(home, ".openclaw")
+ }
+ path = filepath.Join(stateDir, "openclaw.json")
+ }
+ key, format = "mcp.servers", "json"
+ default:
+ return map[string]any{}, false, nil
+ }
+
+ servers := map[string]any{}
+ raw, err := os.ReadFile(path)
+ if err == nil {
+ var cfg map[string]any
+ if format == "toml" {
+ if err := toml.Unmarshal(raw, &cfg); err != nil {
+ return nil, true, fmt.Errorf("parse runtime MCP config: %w", err)
+ }
+ } else if err := json.Unmarshal(raw, &cfg); err != nil {
+ return nil, true, fmt.Errorf("parse runtime MCP config: %w", err)
+ }
+ if configured, ok := nestedRuntimeMcpMap(cfg, key); ok {
+ for name, entry := range configured {
+ servers[name] = normalizeRuntimeMcpEntry(provider, entry)
+ }
+ }
+ } else if !os.IsNotExist(err) {
+ return nil, true, fmt.Errorf("read runtime MCP config: %w", err)
+ }
+
+ if provider == "claude" || provider == "codebuddy" {
+ // User configuration has the same precedence Claude uses: plugin
+ // servers only fill names not already defined by the user.
+ for name, entry := range loadClaudePluginMcpServerConfigs(home) {
+ if _, exists := servers[name]; !exists {
+ servers[name] = entry
+ }
+ }
+ }
+ return servers, true, nil
+}
+
+func normalizeRuntimeMcpEntry(provider string, value any) any {
+ entry, ok := value.(map[string]any)
+ if !ok || provider != "codex" {
+ return value
+ }
+ // Multica's canonical remote shape calls these `headers`; Codex stores
+ // them as `http_headers`. Keep the original key as well so less common
+ // Codex-specific settings round-trip through renderCodexMcpServersBlock.
+ if headers, ok := entry["http_headers"]; ok {
+ if _, exists := entry["headers"]; !exists {
+ entry["headers"] = headers
+ }
+ }
+ if _, hasURL := entry["url"]; hasURL {
+ if _, hasType := entry["type"]; !hasType {
+ entry["type"] = "http"
+ }
+ }
+ return entry
+}
+
+func loadClaudePluginMcpServerConfigs(home string) map[string]any {
+ out := map[string]any{}
+ for _, plugin := range listEnabledClaudePlugins(home) {
+ manifest, _ := readClaudePluginManifest(plugin.InstallPath)
+ paths := claudePluginComponentPaths(
+ plugin.InstallPath,
+ manifest.MCPServers,
+ filepath.Join(plugin.InstallPath, ".mcp.json"),
+ )
+ for _, path := range paths {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ continue
+ }
+ var cfg map[string]any
+ if json.Unmarshal(raw, &cfg) != nil {
+ continue
+ }
+ servers, ok := nestedRuntimeMcpMap(cfg, "mcpServers")
+ if !ok {
+ continue
+ }
+ for name, entry := range servers {
+ if _, exists := out[name]; !exists {
+ out[name] = entry
+ }
+ }
+ }
+ }
+ return out
+}
+
+func listRuntimeLocalMcpServers(provider string) ([]runtimeLocalMcpServerSummary, bool, error) {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return nil, false, fmt.Errorf("resolve user home: %w", err)
+ }
+
+ var path, key, source string
+ var format string
+ switch provider {
+ case "claude", "codebuddy":
+ path, key, source, format = filepath.Join(home, ".claude.json"), "mcpServers", "User config", "json"
+ case "codex":
+ codexHome := strings.TrimSpace(os.Getenv("CODEX_HOME"))
+ if codexHome == "" {
+ codexHome = filepath.Join(home, ".codex")
+ }
+ path, key, source, format = filepath.Join(codexHome, "config.toml"), "mcp_servers", "User config", "toml"
+ case "cursor":
+ path, key, source, format = filepath.Join(home, ".cursor", "mcp.json"), "mcpServers", "User config", "json"
+ case "opencode":
+ configHome := strings.TrimSpace(os.Getenv("XDG_CONFIG_HOME"))
+ if configHome == "" {
+ configHome = filepath.Join(home, ".config")
+ }
+ path, key, source, format = filepath.Join(configHome, "opencode", "opencode.json"), "mcp", "User config", "json"
+ case "openclaw":
+ path = strings.TrimSpace(os.Getenv("CLAWDBOT_CONFIG_PATH"))
+ if path == "" {
+ stateDir := strings.TrimSpace(os.Getenv("OPENCLAW_STATE_DIR"))
+ if stateDir == "" {
+ stateDir = filepath.Join(home, ".openclaw")
+ }
+ path = filepath.Join(stateDir, "openclaw.json")
+ }
+ key, source, format = "mcp.servers", "User config", "json"
+ default:
+ return []runtimeLocalMcpServerSummary{}, false, nil
+ }
+
+ out := make([]runtimeLocalMcpServerSummary, 0)
+ raw, err := os.ReadFile(path)
+ if err == nil {
+ var cfg map[string]any
+ if format == "toml" {
+ if err := toml.Unmarshal(raw, &cfg); err != nil {
+ return nil, true, fmt.Errorf("parse runtime MCP config: %w", err)
+ }
+ } else if err := json.Unmarshal(raw, &cfg); err != nil {
+ return nil, true, fmt.Errorf("parse runtime MCP config: %w", err)
+ }
+ if servers, ok := nestedRuntimeMcpMap(cfg, key); ok {
+ out = append(out, runtimeMcpSummaries(servers, source)...)
+ }
+ } else if !os.IsNotExist(err) {
+ return nil, true, fmt.Errorf("read runtime MCP config: %w", err)
+ }
+
+ if provider == "claude" || provider == "codebuddy" {
+ out = append(out, listClaudePluginMcpServers(home)...)
+ }
+
+ // User configuration wins on a same-name collision. Plugin entries are
+ // appended afterwards and only fill names the user config did not define.
+ deduped := make([]runtimeLocalMcpServerSummary, 0, len(out))
+ seen := make(map[string]bool)
+ for _, server := range out {
+ if seen[server.Name] {
+ continue
+ }
+ seen[server.Name] = true
+ deduped = append(deduped, server)
+ }
+ out = deduped
+ sort.Slice(out, func(i, j int) bool {
+ return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name)
+ })
+ return out, true, nil
+}
+
+func runtimeMcpSummaries(servers map[string]any, source string) []runtimeLocalMcpServerSummary {
+ out := make([]runtimeLocalMcpServerSummary, 0, len(servers))
+ for name, value := range servers {
+ entry, ok := value.(map[string]any)
+ if !ok || strings.TrimSpace(name) == "" {
+ continue
+ }
+ enabled := true
+ if value, ok := entry["enabled"].(bool); ok {
+ enabled = value
+ }
+ if value, ok := entry["disabled"].(bool); ok && value {
+ enabled = false
+ }
+ out = append(out, runtimeLocalMcpServerSummary{
+ Name: name,
+ Transport: runtimeMcpTransport(entry),
+ Source: source,
+ Enabled: enabled,
+ })
+ }
+ return out
+}
+
+func listClaudePluginMcpServers(home string) []runtimeLocalMcpServerSummary {
+ out := make([]runtimeLocalMcpServerSummary, 0)
+ for _, plugin := range listEnabledClaudePlugins(home) {
+ manifest, _ := readClaudePluginManifest(plugin.InstallPath)
+ paths := claudePluginComponentPaths(
+ plugin.InstallPath,
+ manifest.MCPServers,
+ filepath.Join(plugin.InstallPath, ".mcp.json"),
+ )
+ for _, path := range paths {
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ continue
+ }
+ var cfg map[string]any
+ if json.Unmarshal(raw, &cfg) != nil {
+ continue
+ }
+ servers, ok := nestedRuntimeMcpMap(cfg, "mcpServers")
+ if !ok {
+ continue
+ }
+ out = append(out, runtimeMcpSummaries(servers, "Claude Plugin · "+plugin.Name)...)
+ }
+ }
+ return out
+}
+
+func nestedRuntimeMcpMap(cfg map[string]any, path string) (map[string]any, bool) {
+ current := cfg
+ parts := strings.Split(path, ".")
+ for index, part := range parts {
+ value, exists := current[part]
+ if !exists {
+ return nil, false
+ }
+ mapped, ok := value.(map[string]any)
+ if !ok {
+ return nil, false
+ }
+ if index == len(parts)-1 {
+ return mapped, true
+ }
+ current = mapped
+ }
+ return nil, false
+}
+
+func runtimeMcpTransport(entry map[string]any) string {
+ kind, _ := entry["type"].(string)
+ switch strings.ToLower(kind) {
+ case "local", "stdio":
+ return "stdio"
+ case "remote", "http", "streamable-http":
+ return "http"
+ case "sse":
+ return "sse"
+ }
+ if _, ok := entry["command"]; ok {
+ return "stdio"
+ }
+ if _, ok := entry["url"]; ok {
+ return "http"
+ }
+ return "unknown"
+}
diff --git a/server/internal/daemon/runtime_mcp_test.go b/server/internal/daemon/runtime_mcp_test.go
new file mode 100644
index 0000000000..b6c0a25cf0
--- /dev/null
+++ b/server/internal/daemon/runtime_mcp_test.go
@@ -0,0 +1,183 @@
+package daemon
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestListRuntimeLocalMcpServersCodexRedactsDetails(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("CODEX_HOME", "")
+ configDir := filepath.Join(home, ".codex")
+ if err := os.MkdirAll(configDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ config := `[mcp_servers.fetch]
+command = "uvx"
+args = ["mcp-server-fetch", "--token", "secret"]
+
+[mcp_servers.docs]
+url = "https://secret.example/mcp"
+enabled = false
+`
+ if err := os.WriteFile(filepath.Join(configDir, "config.toml"), []byte(config), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ servers, supported, err := listRuntimeLocalMcpServers("codex")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !supported || len(servers) != 2 {
+ t.Fatalf("supported=%v servers=%#v", supported, servers)
+ }
+ if servers[0].Name != "docs" || servers[0].Transport != "http" || servers[0].Enabled {
+ t.Fatalf("docs summary = %#v", servers[0])
+ }
+ if servers[1].Name != "fetch" || servers[1].Transport != "stdio" || !servers[1].Enabled {
+ t.Fatalf("fetch summary = %#v", servers[1])
+ }
+}
+
+func TestListRuntimeLocalMcpServersClaudeMissingConfig(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ servers, supported, err := listRuntimeLocalMcpServers("claude")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !supported || len(servers) != 0 {
+ t.Fatalf("supported=%v servers=%#v", supported, servers)
+ }
+}
+
+func TestListRuntimeLocalMcpServersClaudeEnabledPlugin(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", true)
+ config := `{"mcpServers":{"paper":{"type":"http","url":"http://127.0.0.1:29979/mcp"}}}`
+ if err := os.WriteFile(filepath.Join(installPath, "mcp.json"), []byte(config), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ servers, supported, err := listRuntimeLocalMcpServers("claude")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !supported || len(servers) != 1 {
+ t.Fatalf("supported=%v servers=%#v", supported, servers)
+ }
+ if servers[0].Name != "paper" || servers[0].Transport != "http" || !servers[0].Enabled {
+ t.Fatalf("plugin MCP summary = %#v", servers[0])
+ }
+ if servers[0].Source != "Claude Plugin · paper-desktop" {
+ t.Fatalf("plugin MCP source = %q", servers[0].Source)
+ }
+}
+
+func TestListRuntimeLocalMcpServersUnknownProvider(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ servers, supported, err := listRuntimeLocalMcpServers("future-runtime")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if supported || len(servers) != 0 {
+ t.Fatalf("supported=%v servers=%#v", supported, servers)
+ }
+}
+
+func TestMergeRuntimeAndAgentMcpConfigClaudeCombinesAndAgentWins(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ runtimeConfig := `{"mcpServers":{"runtime-only":{"command":"runtime-cmd","env":{"TOKEN":"local-secret"}},"shared":{"command":"runtime-shared"}}}`
+ if err := os.WriteFile(filepath.Join(home, ".claude.json"), []byte(runtimeConfig), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ installPath := writeTestClaudePlugin(t, home, "paper-desktop@paper", "paper-desktop", true)
+ if err := os.WriteFile(filepath.Join(installPath, "mcp.json"), []byte(`{"mcpServers":{"paper":{"type":"http","url":"http://127.0.0.1:29979/mcp"}}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ merged, err := mergeRuntimeAndAgentMcpConfig("claude", json.RawMessage(`{"mcpServers":{"shared":{"command":"agent-shared"},"agent-only":{"url":"https://agent.example/mcp"}}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var document struct {
+ McpServers map[string]map[string]any `json:"mcpServers"`
+ }
+ if err := json.Unmarshal(merged, &document); err != nil {
+ t.Fatal(err)
+ }
+ if len(document.McpServers) != 4 {
+ t.Fatalf("merged servers = %#v", document.McpServers)
+ }
+ if got := document.McpServers["shared"]["command"]; got != "agent-shared" {
+ t.Fatalf("shared command = %#v, want agent-shared", got)
+ }
+ if got := document.McpServers["runtime-only"]["command"]; got != "runtime-cmd" {
+ t.Fatalf("runtime-only command = %#v", got)
+ }
+ if got := document.McpServers["runtime-only"]["env"].(map[string]any)["TOKEN"]; got != "local-secret" {
+ t.Fatalf("runtime secret was not preserved locally: %#v", got)
+ }
+ if got := document.McpServers["paper"]["url"]; got != "http://127.0.0.1:29979/mcp" {
+ t.Fatalf("plugin server url = %#v", got)
+ }
+}
+
+func TestMergeRuntimeAndAgentMcpConfigCodexNormalizesHeaders(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("CODEX_HOME", "")
+ configDir := filepath.Join(home, ".codex")
+ if err := os.MkdirAll(configDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ config := `[mcp_servers.docs]
+url = "https://runtime.example/mcp"
+http_headers = { Authorization = "Bearer local-secret" }
+
+[mcp_servers.fetch]
+command = "uvx"
+args = ["mcp-server-fetch"]
+`
+ if err := os.WriteFile(filepath.Join(configDir, "config.toml"), []byte(config), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ merged, err := mergeRuntimeAndAgentMcpConfig("codex", json.RawMessage(`{"mcpServers":{"agent":{"command":"node","args":["agent.js"]}}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var document struct {
+ McpServers map[string]map[string]any `json:"mcpServers"`
+ }
+ if err := json.Unmarshal(merged, &document); err != nil {
+ t.Fatal(err)
+ }
+ if len(document.McpServers) != 3 {
+ t.Fatalf("merged servers = %#v", document.McpServers)
+ }
+ if got := document.McpServers["docs"]["type"]; got != "http" {
+ t.Fatalf("docs type = %#v", got)
+ }
+ headers := document.McpServers["docs"]["headers"].(map[string]any)
+ if got := headers["Authorization"]; got != "Bearer local-secret" {
+ t.Fatalf("docs Authorization = %#v", got)
+ }
+}
+
+func TestMergeRuntimeAndAgentMcpConfigNullKeepsNativeInheritance(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ for _, raw := range []json.RawMessage{nil, json.RawMessage("null"), json.RawMessage(" null ")} {
+ merged, err := mergeRuntimeAndAgentMcpConfig("claude", raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(merged) != string(raw) {
+ t.Fatalf("merged %q = %q", string(raw), string(merged))
+ }
+ }
+}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index a9e6e5b55a..e49beee642 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -640,6 +640,7 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {
ID: uuidToString(row.ID),
Name: row.Name,
Description: row.Description,
+ Enabled: row.Enabled,
})
}
@@ -1631,6 +1632,7 @@ func (h *Handler) attachAgentSkills(ctx context.Context, resp *AgentResponse, ag
ID: uuidToString(s.ID),
Name: s.Name,
Description: s.Description,
+ Enabled: s.Enabled,
}
}
resp.Skills = out
diff --git a/server/internal/handler/runtime_local_skills.go b/server/internal/handler/runtime_local_skills.go
index b036160ab6..5bf93db659 100644
--- a/server/internal/handler/runtime_local_skills.go
+++ b/server/internal/handler/runtime_local_skills.go
@@ -88,7 +88,7 @@ type LocalSkillListStore interface {
// never start a claim they might have to abort.
HasPending(ctx context.Context, runtimeID string) (bool, error)
PopPending(ctx context.Context, runtimeID string) (*RuntimeLocalSkillListRequest, error)
- Complete(ctx context.Context, id string, skills []RuntimeLocalSkillSummary, supported bool) error
+ Complete(ctx context.Context, id string, skills []RuntimeLocalSkillSummary, supported bool, mcpServers []RuntimeLocalMcpServerSummary, mcpSupported bool) error
Fail(ctx context.Context, id string, errMsg string) error
}
@@ -178,20 +178,34 @@ type RuntimeLocalSkillSummary struct {
SourcePath string `json:"source_path"`
Provider string `json:"provider"`
// Root classifies the discovery root the daemon found this skill under:
- // "provider" (the runtime's own skill directory, e.g. ~/.claude/skills)
- // or "universal" (the cross-tool ~/.agents/skills fallback). Daemons
+ // "provider" (the runtime's own skill directory, e.g. ~/.claude/skills),
+ // "universal" (the cross-tool ~/.agents/skills fallback), or "plugin"
+ // for a skill contributed by an enabled runtime plugin. Daemons
// that predate multi-root discovery omit it; an empty value means
// "unknown" and the UI should not assert either origin.
Root string `json:"root,omitempty"`
+ Plugin string `json:"plugin,omitempty"`
FileCount int `json:"file_count"`
}
+// RuntimeLocalMcpServerSummary is deliberately non-secret. The daemon only
+// reports the configured server name, transport, and config scope; command
+// arguments, URLs, headers, and environment values never leave the machine.
+type RuntimeLocalMcpServerSummary struct {
+ Name string `json:"name"`
+ Transport string `json:"transport,omitempty"`
+ Source string `json:"source,omitempty"`
+ Enabled bool `json:"enabled"`
+}
+
type RuntimeLocalSkillListRequest struct {
ID string `json:"id"`
RuntimeID string `json:"runtime_id"`
Status RuntimeLocalSkillRequestStatus `json:"status"`
Skills []RuntimeLocalSkillSummary `json:"skills,omitempty"`
Supported bool `json:"supported"`
+ McpServers []RuntimeLocalMcpServerSummary `json:"mcp_servers,omitempty"`
+ McpSupported bool `json:"mcp_supported"`
Error string `json:"error,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
@@ -304,7 +318,7 @@ func (s *InMemoryLocalSkillListStore) PopPending(_ context.Context, runtimeID st
return oldest, nil
}
-func (s *InMemoryLocalSkillListStore) Complete(_ context.Context, id string, skills []RuntimeLocalSkillSummary, supported bool) error {
+func (s *InMemoryLocalSkillListStore) Complete(_ context.Context, id string, skills []RuntimeLocalSkillSummary, supported bool, mcpServers []RuntimeLocalMcpServerSummary, mcpSupported bool) error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -312,6 +326,8 @@ func (s *InMemoryLocalSkillListStore) Complete(_ context.Context, id string, ski
req.Status = RuntimeLocalSkillCompleted
req.Skills = skills
req.Supported = supported
+ req.McpServers = mcpServers
+ req.McpSupported = mcpSupported
req.UpdatedAt = time.Now()
}
return nil
@@ -711,10 +727,12 @@ func (h *Handler) ReportLocalSkillListResult(w http.ResponseWriter, r *http.Requ
}
var body struct {
- Status string `json:"status"`
- Skills []RuntimeLocalSkillSummary `json:"skills"`
- Supported *bool `json:"supported"`
- Error string `json:"error"`
+ Status string `json:"status"`
+ Skills []RuntimeLocalSkillSummary `json:"skills"`
+ Supported *bool `json:"supported"`
+ McpServers []RuntimeLocalMcpServerSummary `json:"mcp_servers"`
+ McpSupported *bool `json:"mcp_supported"`
+ Error string `json:"error"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
@@ -726,7 +744,11 @@ func (h *Handler) ReportLocalSkillListResult(w http.ResponseWriter, r *http.Requ
if body.Supported != nil {
supported = *body.Supported
}
- if err := h.LocalSkillListStore.Complete(r.Context(), requestID, body.Skills, supported); err != nil {
+ mcpSupported := false
+ if body.McpSupported != nil {
+ mcpSupported = *body.McpSupported
+ }
+ if err := h.LocalSkillListStore.Complete(r.Context(), requestID, body.Skills, supported, body.McpServers, mcpSupported); err != nil {
// Surface the store failure as 5xx so the daemon can retry instead
// of swallowing the report (leaves the request stuck in running
// until the server-side timeout, which is exactly the "looks OK but
diff --git a/server/internal/handler/runtime_local_skills_redis_store.go b/server/internal/handler/runtime_local_skills_redis_store.go
index d09b1ac7b5..f0dd7fec6b 100644
--- a/server/internal/handler/runtime_local_skills_redis_store.go
+++ b/server/internal/handler/runtime_local_skills_redis_store.go
@@ -223,7 +223,7 @@ func (s *RedisLocalSkillListStore) PopPending(ctx context.Context, runtimeID str
return nil, nil
}
-func (s *RedisLocalSkillListStore) Complete(ctx context.Context, id string, skills []RuntimeLocalSkillSummary, supported bool) error {
+func (s *RedisLocalSkillListStore) Complete(ctx context.Context, id string, skills []RuntimeLocalSkillSummary, supported bool, mcpServers []RuntimeLocalMcpServerSummary, mcpSupported bool) error {
req, err := s.loadListRequest(ctx, id)
if err != nil {
return err
@@ -234,6 +234,8 @@ func (s *RedisLocalSkillListStore) Complete(ctx context.Context, id string, skil
req.Status = RuntimeLocalSkillCompleted
req.Skills = skills
req.Supported = supported
+ req.McpServers = mcpServers
+ req.McpSupported = mcpSupported
req.UpdatedAt = time.Now()
return s.persistListRequest(ctx, req)
}
diff --git a/server/internal/handler/runtime_local_skills_redis_store_test.go b/server/internal/handler/runtime_local_skills_redis_store_test.go
index 066ec7f9c9..0fa3d7b1b0 100644
--- a/server/internal/handler/runtime_local_skills_redis_store_test.go
+++ b/server/internal/handler/runtime_local_skills_redis_store_test.go
@@ -75,7 +75,10 @@ func TestRedisLocalSkillListStore_CreateGetComplete(t *testing.T) {
FileCount: 2,
},
}
- if err := store.Complete(ctx, req.ID, skills, true); err != nil {
+ mcpServers := []RuntimeLocalMcpServerSummary{
+ {Name: "fetch", Transport: "stdio", Source: "User config", Enabled: true},
+ }
+ if err := store.Complete(ctx, req.ID, skills, true, mcpServers, true); err != nil {
t.Fatalf("complete: %v", err)
}
@@ -89,6 +92,9 @@ func TestRedisLocalSkillListStore_CreateGetComplete(t *testing.T) {
if len(got.Skills) != 1 || got.Skills[0].Key != "review-helper" {
t.Fatalf("skills not persisted: %+v", got.Skills)
}
+ if !got.McpSupported || len(got.McpServers) != 1 || got.McpServers[0].Name != "fetch" {
+ t.Fatalf("MCP inventory not persisted: %+v", got.McpServers)
+ }
}
// TestRedisLocalSkillListStore_PopPendingAcrossInstances is the regression
diff --git a/server/internal/handler/runtime_local_skills_test.go b/server/internal/handler/runtime_local_skills_test.go
index 5bcfc498b0..c2b16f0dfa 100644
--- a/server/internal/handler/runtime_local_skills_test.go
+++ b/server/internal/handler/runtime_local_skills_test.go
@@ -119,11 +119,13 @@ func TestInMemoryLocalSkillListStore_PreservesSummaries(t *testing.T) {
"supported": true,
"skills": []map[string]any{
{
- "key": "review-helper",
- "name": "Review Helper",
+ "key": "paper-desktop:review-helper",
+ "name": "paper-desktop:review-helper",
"description": "Review PRs",
- "source_path": "~/.claude/skills/review-helper",
+ "source_path": "~/.claude/plugins/cache/paper/skills/review-helper",
"provider": "claude",
+ "root": "plugin",
+ "plugin": "paper-desktop@paper",
"file_count": 2,
},
},
@@ -137,7 +139,7 @@ func TestInMemoryLocalSkillListStore_PreservesSummaries(t *testing.T) {
t.Fatalf("unmarshal report body: %v", err)
}
- if err := store.Complete(ctx, req.ID, parsed.Skills, true); err != nil {
+ if err := store.Complete(ctx, req.ID, parsed.Skills, true, nil, false); err != nil {
t.Fatalf("complete: %v", err)
}
got, err := store.Get(ctx, req.ID)
@@ -150,9 +152,12 @@ func TestInMemoryLocalSkillListStore_PreservesSummaries(t *testing.T) {
if len(got.Skills) != 1 {
t.Fatalf("expected 1 skill, got %d", len(got.Skills))
}
- if got.Skills[0].SourcePath != "~/.claude/skills/review-helper" {
+ if got.Skills[0].SourcePath != "~/.claude/plugins/cache/paper/skills/review-helper" {
t.Fatalf("source_path = %q", got.Skills[0].SourcePath)
}
+ if got.Skills[0].Root != "plugin" || got.Skills[0].Plugin != "paper-desktop@paper" {
+ t.Fatalf("plugin origin = %#v", got.Skills[0])
+ }
if got.Skills[0].FileCount != 2 {
t.Fatalf("file_count = %d", got.Skills[0].FileCount)
}
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.go
index 971fea9cac..e4592bdbe6 100644
--- a/server/internal/handler/skill.go
+++ b/server/internal/handler/skill.go
@@ -64,6 +64,9 @@ type SkillSummaryResponse struct {
CreatedBy *string `json:"created_by"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
+ // Enabled is only populated for agent-scoped skill responses. Workspace
+ // skill lists describe the skill itself, so they omit assignment state.
+ Enabled *bool `json:"enabled,omitempty"`
}
// AgentSkillSummary is the still-narrower shape used for skills embedded in
@@ -75,6 +78,7 @@ type AgentSkillSummary struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
+ Enabled bool `json:"enabled"`
}
type SkillFileResponse struct {
@@ -2142,6 +2146,7 @@ func (h *Handler) ListAgentSkills(w http.ResponseWriter, r *http.Request) {
s.ID, s.WorkspaceID, s.Name, s.Description, s.Config,
s.CreatedBy, s.CreatedAt, s.UpdatedAt,
)
+ resp[i].Enabled = &s.Enabled
}
writeJSON(w, http.StatusOK, resp)
}
@@ -2250,6 +2255,68 @@ func (h *Handler) AddAgentSkills(w http.ResponseWriter, r *http.Request) {
h.writeUpdatedAgentSkills(w, r, agent)
}
+func (h *Handler) SetAgentSkillEnabled(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ agent, ok := h.loadAgentForUser(w, r, id)
+ if !ok {
+ return
+ }
+ if !h.canManageAgent(w, r, agent) {
+ return
+ }
+
+ skillID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "skillId"), "skill_id")
+ if !ok {
+ return
+ }
+ var req struct {
+ Enabled *bool `json:"enabled"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Enabled == nil {
+ writeError(w, http.StatusBadRequest, "enabled is required")
+ return
+ }
+
+ rows, err := h.Queries.SetAgentSkillEnabled(r.Context(), db.SetAgentSkillEnabledParams{
+ AgentID: agent.ID,
+ SkillID: skillID,
+ Enabled: *req.Enabled,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update agent skill")
+ return
+ }
+ if rows == 0 {
+ writeError(w, http.StatusNotFound, "agent skill not found")
+ return
+ }
+
+ h.writeUpdatedAgentSkills(w, r, agent)
+}
+
+func (h *Handler) RemoveAgentSkill(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ agent, ok := h.loadAgentForUser(w, r, id)
+ if !ok {
+ return
+ }
+ if !h.canManageAgent(w, r, agent) {
+ return
+ }
+ skillID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "skillId"), "skill_id")
+ if !ok {
+ return
+ }
+ if err := h.Queries.RemoveAgentSkill(r.Context(), db.RemoveAgentSkillParams{
+ AgentID: agent.ID,
+ SkillID: skillID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to remove agent skill")
+ return
+ }
+ h.writeUpdatedAgentSkills(w, r, agent)
+}
+
func (h *Handler) validateAgentSkillIDsInWorkspace(w http.ResponseWriter, r *http.Request, agent db.Agent, skillUUIDs []pgtype.UUID) bool {
seen := map[string]struct{}{}
for _, skillID := range skillUUIDs {
@@ -2282,6 +2349,7 @@ func (h *Handler) writeUpdatedAgentSkills(w http.ResponseWriter, r *http.Request
s.ID, s.WorkspaceID, s.Name, s.Description, s.Config,
s.CreatedBy, s.CreatedAt, s.UpdatedAt,
)
+ resp[i].Enabled = &s.Enabled
}
actorType, actorID := h.resolveActor(r, requestUserID(r), uuidToString(agent.WorkspaceID))
h.publish(protocol.EventAgentStatus, uuidToString(agent.WorkspaceID), actorType, actorID, map[string]any{"agent_id": uuidToString(agent.ID), "skills": resp})
diff --git a/server/internal/handler/skill_list_test.go b/server/internal/handler/skill_list_test.go
index 2dfa458f03..8dc30515f3 100644
--- a/server/internal/handler/skill_list_test.go
+++ b/server/internal/handler/skill_list_test.go
@@ -6,6 +6,8 @@ import (
"net/http/httptest"
"strings"
"testing"
+
+ "github.com/go-chi/chi/v5"
)
// TestListSkills_OmitsContent guards the fix for GH multica-ai/multica#2174:
@@ -111,6 +113,54 @@ func TestListAgentSkills_OmitsContent(t *testing.T) {
}
}
+func TestSetAgentSkillEnabledControlsExecutionWithoutRemovingAssignment(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "Handler Skill Toggle Test", nil)
+ skillID := insertHandlerTestSkill(t, "agent-skill-toggle", "# Toggle me")
+ if _, err := testPool.Exec(context.Background(),
+ `INSERT INTO agent_skill (agent_id, skill_id) VALUES ($1, $2)`,
+ agentID, skillID,
+ ); err != nil {
+ t.Fatalf("attach skill to agent: %v", err)
+ }
+
+ setEnabled := func(enabled bool) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("PUT", "/api/agents/"+agentID+"/skills/"+skillID+"/enabled", map[string]any{
+ "enabled": enabled,
+ })
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("id", agentID)
+ rctx.URLParams.Add("skillId", skillID)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+ testHandler.SetAgentSkillEnabled(w, req)
+ return w
+ }
+
+ if w := setEnabled(false); w.Code != 200 {
+ t.Fatalf("disable skill: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Disabled assignments remain visible to management surfaces.
+ rows, err := testHandler.Queries.ListAgentSkillSummaries(context.Background(), parseUUID(agentID))
+ if err != nil || len(rows) != 1 || rows[0].Enabled {
+ t.Fatalf("disabled assignment not preserved: rows=%+v err=%v", rows, err)
+ }
+ // Execution only receives enabled skills.
+ active, err := testHandler.Queries.ListAgentSkills(context.Background(), parseUUID(agentID))
+ if err != nil || len(active) != 0 {
+ t.Fatalf("disabled skill leaked into execution: skills=%+v err=%v", active, err)
+ }
+
+ if w := setEnabled(true); w.Code != 200 {
+ t.Fatalf("enable skill: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ active, err = testHandler.Queries.ListAgentSkills(context.Background(), parseUUID(agentID))
+ if err != nil || len(active) != 1 || active[0].Name == "" {
+ t.Fatalf("re-enabled skill missing from execution: skills=%+v err=%v", active, err)
+ }
+}
+
// TestGetSkill_MalformedUUIDReturns400 guards the handler UUID parsing
// convention (CLAUDE.md → "Backend Handler UUID Parsing Convention"): raw
// `id` URL params on the request boundary must be validated with
diff --git a/server/migrations/161_agent_skill_enabled.down.sql b/server/migrations/161_agent_skill_enabled.down.sql
new file mode 100644
index 0000000000..96fb0f3a08
--- /dev/null
+++ b/server/migrations/161_agent_skill_enabled.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_skill
+DROP COLUMN enabled;
diff --git a/server/migrations/161_agent_skill_enabled.up.sql b/server/migrations/161_agent_skill_enabled.up.sql
new file mode 100644
index 0000000000..7b2d872948
--- /dev/null
+++ b/server/migrations/161_agent_skill_enabled.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_skill
+ADD COLUMN enabled BOOLEAN NOT NULL DEFAULT TRUE;
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index 9d51382c12..cb2acb3127 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -40,7 +40,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
// instead of inheriting from the outer Claude Code session.
var mcpConfigPath string
var mcpFileCleanup func() // non-nil while this function owns the temp file
- if len(opts.McpConfig) > 0 {
+ if hasManagedMcpConfig(opts.McpConfig) {
path, err := writeMcpConfigToTemp(opts.McpConfig)
if err != nil {
cancel()
@@ -571,7 +571,6 @@ func buildClaudeArgs(opts ExecOptions, logger *slog.Logger) []string {
"--output-format", "stream-json",
"--input-format", "stream-json",
"--verbose",
- "--strict-mcp-config",
"--permission-mode", "bypassPermissions",
// AskUserQuestion is Claude Code's built-in interactive question tool.
// The daemon runs Claude in non-interactive stream-json mode and has
@@ -581,6 +580,12 @@ func buildClaudeArgs(opts ExecOptions, logger *slog.Logger) []string {
// clarification belongs in an issue comment instead.
"--disallowedTools", "AskUserQuestion",
}
+ if hasManagedMcpConfig(opts.McpConfig) {
+ // A saved agent-level config is authoritative, including an explicitly
+ // empty object. With no managed config, omit strict mode so Claude can
+ // inherit the user's local runtime MCP servers.
+ args = append(args, "--strict-mcp-config")
+ }
if opts.Model != "" {
args = append(args, "--model", opts.Model)
}
diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.go
index 8f5628781e..a1c083f12b 100644
--- a/server/pkg/agent/claude_test.go
+++ b/server/pkg/agent/claude_test.go
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"runtime"
+ "slices"
"strings"
"testing"
"time"
@@ -307,7 +308,7 @@ func TestTrySendDropsWhenFull(t *testing.T) {
}
}
-func TestBuildClaudeArgsIncludesStrictMCPConfig(t *testing.T) {
+func TestBuildClaudeArgsInheritsMCPByDefault(t *testing.T) {
t.Parallel()
args := buildClaudeArgs(ExecOptions{}, slog.Default())
@@ -316,7 +317,6 @@ func TestBuildClaudeArgsIncludesStrictMCPConfig(t *testing.T) {
"--output-format", "stream-json",
"--input-format", "stream-json",
"--verbose",
- "--strict-mcp-config",
"--permission-mode", "bypassPermissions",
"--disallowedTools", "AskUserQuestion",
}
@@ -331,6 +331,15 @@ func TestBuildClaudeArgsIncludesStrictMCPConfig(t *testing.T) {
}
}
+func TestBuildClaudeArgsUsesStrictMCPForManagedConfig(t *testing.T) {
+ t.Parallel()
+
+ args := buildClaudeArgs(ExecOptions{McpConfig: json.RawMessage(`{}`)}, slog.Default())
+ if !slices.Contains(args, "--strict-mcp-config") {
+ t.Fatalf("managed MCP config must enable strict mode, got %v", args)
+ }
+}
+
func TestArgsRequestBypassPermissions(t *testing.T) {
t.Parallel()
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index 6b688114eb..7d83a4d0c9 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -2,7 +2,6 @@ package agent
import (
"bufio"
- "bytes"
"context"
"encoding/json"
"errors"
@@ -128,14 +127,7 @@ func buildCodexArgs(opts ExecOptions, logger *slog.Logger) []string {
// managed set — strict mode, no global fallback); only SQL NULL or the
// literal JSON `null` count as absent (CLI default).
func hasManagedCodexMcpConfig(raw json.RawMessage) bool {
- trimmed := bytes.TrimSpace(raw)
- if len(trimmed) == 0 {
- return false
- }
- if bytes.Equal(trimmed, []byte("null")) {
- return false
- }
- return true
+ return hasManagedMcpConfig(raw)
}
// codexManagedMcpConfigKeyRe matches the daemon-managed config namespace
diff --git a/server/pkg/agent/mcp_config.go b/server/pkg/agent/mcp_config.go
new file mode 100644
index 0000000000..85e4e5985d
--- /dev/null
+++ b/server/pkg/agent/mcp_config.go
@@ -0,0 +1,14 @@
+package agent
+
+import (
+ "bytes"
+ "encoding/json"
+)
+
+// hasManagedMcpConfig preserves the API's three-state MCP semantics. Only SQL
+// NULL / JSON null mean "inherit the runtime configuration"; any object,
+// including an explicitly empty one, is a managed set and enables strict mode.
+func hasManagedMcpConfig(raw json.RawMessage) bool {
+ trimmed := bytes.TrimSpace(raw)
+ return len(trimmed) > 0 && !bytes.Equal(trimmed, []byte("null"))
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 515f5c6830..37f4199978 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -84,6 +84,7 @@ type AgentSkill struct {
AgentID pgtype.UUID `json:"agent_id"`
SkillID pgtype.UUID `json:"skill_id"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
+ Enabled bool `json:"enabled"`
}
type AgentTaskQueue struct {
diff --git a/server/pkg/db/generated/skill.sql.go b/server/pkg/db/generated/skill.sql.go
index 415c9184e2..f958974303 100644
--- a/server/pkg/db/generated/skill.sql.go
+++ b/server/pkg/db/generated/skill.sql.go
@@ -203,6 +203,7 @@ SELECT ask.agent_id, s.name
FROM agent_skill ask
JOIN skill s ON s.id = ask.skill_id
WHERE ask.agent_id = ANY($1::uuid[])
+ AND ask.enabled = TRUE
ORDER BY ask.agent_id, s.name ASC
`
@@ -232,7 +233,7 @@ func (q *Queries) ListAgentSkillNamesByAgentIDs(ctx context.Context, agentIds []
}
const listAgentSkillSummaries = `-- name: ListAgentSkillSummaries :many
-SELECT s.id, s.workspace_id, s.name, s.description, s.config, s.created_by, s.created_at, s.updated_at
+SELECT s.id, s.workspace_id, s.name, s.description, s.config, s.created_by, s.created_at, s.updated_at, ask.enabled
FROM skill s
JOIN agent_skill ask ON ask.skill_id = s.id
WHERE ask.agent_id = $1
@@ -248,6 +249,7 @@ type ListAgentSkillSummariesRow struct {
CreatedBy pgtype.UUID `json:"created_by"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ Enabled bool `json:"enabled"`
}
// Summary variant for the agent skills list endpoint — omits `content` for
@@ -270,6 +272,7 @@ func (q *Queries) ListAgentSkillSummaries(ctx context.Context, agentID pgtype.UU
&i.CreatedBy,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Enabled,
); err != nil {
return nil, err
}
@@ -285,7 +288,7 @@ const listAgentSkills = `-- name: ListAgentSkills :many
SELECT s.id, s.workspace_id, s.name, s.description, s.content, s.config, s.created_by, s.created_at, s.updated_at FROM skill s
JOIN agent_skill ask ON ask.skill_id = s.id
-WHERE ask.agent_id = $1
+WHERE ask.agent_id = $1 AND ask.enabled = TRUE
ORDER BY s.name ASC
`
@@ -321,7 +324,7 @@ func (q *Queries) ListAgentSkills(ctx context.Context, agentID pgtype.UUID) ([]S
}
const listAgentSkillsByWorkspace = `-- name: ListAgentSkillsByWorkspace :many
-SELECT ask.agent_id, s.id, s.name, s.description
+SELECT ask.agent_id, s.id, s.name, s.description, ask.enabled
FROM agent_skill ask
JOIN skill s ON s.id = ask.skill_id
WHERE s.workspace_id = $1
@@ -333,6 +336,7 @@ type ListAgentSkillsByWorkspaceRow struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
+ Enabled bool `json:"enabled"`
}
func (q *Queries) ListAgentSkillsByWorkspace(ctx context.Context, workspaceID pgtype.UUID) ([]ListAgentSkillsByWorkspaceRow, error) {
@@ -349,6 +353,7 @@ func (q *Queries) ListAgentSkillsByWorkspace(ctx context.Context, workspaceID pg
&i.ID,
&i.Name,
&i.Description,
+ &i.Enabled,
); err != nil {
return nil, err
}
@@ -508,6 +513,26 @@ func (q *Queries) RemoveAllAgentSkills(ctx context.Context, agentID pgtype.UUID)
return err
}
+const setAgentSkillEnabled = `-- name: SetAgentSkillEnabled :execrows
+UPDATE agent_skill
+SET enabled = $3
+WHERE agent_id = $1 AND skill_id = $2
+`
+
+type SetAgentSkillEnabledParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ SkillID pgtype.UUID `json:"skill_id"`
+ Enabled bool `json:"enabled"`
+}
+
+func (q *Queries) SetAgentSkillEnabled(ctx context.Context, arg SetAgentSkillEnabledParams) (int64, error) {
+ result, err := q.db.Exec(ctx, setAgentSkillEnabled, arg.AgentID, arg.SkillID, arg.Enabled)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const updateSkill = `-- name: UpdateSkill :one
UPDATE skill SET
name = COALESCE($2, name),
diff --git a/server/pkg/db/queries/skill.sql b/server/pkg/db/queries/skill.sql
index bebf012fd9..776c8f17aa 100644
--- a/server/pkg/db/queries/skill.sql
+++ b/server/pkg/db/queries/skill.sql
@@ -80,13 +80,13 @@ DELETE FROM skill_file WHERE skill_id = $1;
-- name: ListAgentSkills :many
SELECT s.* FROM skill s
JOIN agent_skill ask ON ask.skill_id = s.id
-WHERE ask.agent_id = $1
+WHERE ask.agent_id = $1 AND ask.enabled = TRUE
ORDER BY s.name ASC;
-- name: ListAgentSkillSummaries :many
-- Summary variant for the agent skills list endpoint — omits `content` for
-- the same reason as ListSkillSummariesByWorkspace.
-SELECT s.id, s.workspace_id, s.name, s.description, s.config, s.created_by, s.created_at, s.updated_at
+SELECT s.id, s.workspace_id, s.name, s.description, s.config, s.created_by, s.created_at, s.updated_at, ask.enabled
FROM skill s
JOIN agent_skill ask ON ask.skill_id = s.id
WHERE ask.agent_id = $1
@@ -97,6 +97,7 @@ SELECT ask.agent_id, s.name
FROM agent_skill ask
JOIN skill s ON s.id = ask.skill_id
WHERE ask.agent_id = ANY(sqlc.arg('agent_ids')::uuid[])
+ AND ask.enabled = TRUE
ORDER BY ask.agent_id, s.name ASC;
-- name: AddAgentSkill :exec
@@ -104,6 +105,11 @@ INSERT INTO agent_skill (agent_id, skill_id)
VALUES ($1, $2)
ON CONFLICT DO NOTHING;
+-- name: SetAgentSkillEnabled :execrows
+UPDATE agent_skill
+SET enabled = $3
+WHERE agent_id = $1 AND skill_id = $2;
+
-- name: RemoveAgentSkill :exec
DELETE FROM agent_skill
WHERE agent_id = $1 AND skill_id = $2;
@@ -112,7 +118,7 @@ WHERE agent_id = $1 AND skill_id = $2;
DELETE FROM agent_skill WHERE agent_id = $1;
-- name: ListAgentSkillsByWorkspace :many
-SELECT ask.agent_id, s.id, s.name, s.description
+SELECT ask.agent_id, s.id, s.name, s.description, ask.enabled
FROM agent_skill ask
JOIN skill s ON s.id = ask.skill_id
WHERE s.workspace_id = $1