Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5421: workspace-level MCP configuration (resolution contract, write-only API, Settings UI, CLI) (#6961)
Bohan Jiang736838af8629
diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex c007689a70..c01070d451 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -260,6 +260,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| | `runs <id>` | 実行履歴を表示 | || | `trigger-add/trigger-update/trigger-delete/trigger-rotate-url` | スケジュールと webhook のトリガーを管理 | || `workspace` | `list/get/create/update/switch` | ワークスペースを管理。`switch` は現在のプロファイルのデフォルトワークスペースを設定 | |+| | `mcp get/set/add/remove` | ワークスペース内の全エージェントで共有する MCP サーバーを管理 | 書き込みは owner/admin のみ。`get` は名前と transport のみを表示し、保存された設定は書き込み専用でどのロールにも返らない。`set` はドキュメント全体を置換(`--mcp-config-file` / `--mcp-config-stdin` はトークンをシェル履歴から守る。`--mcp-config null` で削除)。`add <name>` / `remove <name>` はドキュメント全体を持たずに 1 つのサーバーだけを変更 || | `member list/invite <email>` | メンバーの表示と招待 | `invite`: `--role`(member または admin。デフォルトは member) || `repo` | `list/add/remove/checkout` | ワークスペースのリポジトリを管理し、ローカルにチェックアウト | `--url`(繰り返し可);`checkout`: `--ref` || `skill` | `list/get/create/update/delete` | スキルを管理 | |diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex 00da30b4cd..958bd6a2ce 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -260,6 +260,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| | `runs <id>` | 실행 기록 확인 | || | `trigger-add/trigger-update/trigger-delete/trigger-rotate-url` | 일정 및 webhook 트리거 관리 | || `workspace` | `list/get/create/update/switch` | 워크스페이스 관리. `switch`는 현재 profile의 기본 워크스페이스 설정 | |+| | `mcp get/set/add/remove` | 워크스페이스의 모든 에이전트가 공유하는 MCP 서버를 관리 | 쓰기는 owner/admin 전용. `get`은 이름과 transport만 표시하며, 저장된 설정은 쓰기 전용이라 어떤 역할에도 반환되지 않음. `set`은 문서 전체를 교체(`--mcp-config-file` / `--mcp-config-stdin`은 토큰이 셸 기록에 남지 않게 함, `--mcp-config null`로 삭제). `add <name>` / `remove <name>`은 문서 전체 없이 서버 하나만 변경 || | `member list/invite <email>` | 멤버 확인 및 초대 전송 | `invite`: `--role`(member 또는 admin, 기본 member) || `repo` | `list/add/remove/checkout` | 워크스페이스 저장소 관리 및 로컬 checkout | `--url`(반복 가능). `checkout`: `--ref` || `skill` | `list/get/create/update/delete` | 스킬 관리 | |diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex 5eb8f469ed..8f51729793 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -281,6 +281,7 @@ The tables below cover every current top-level command, grouped the way the CLI| | `runs <id>` | View run history | || | `trigger-add/trigger-update/trigger-delete/trigger-rotate-url` | Manage schedule and webhook triggers | || `workspace` | `list/get/create/update/switch` | Manage workspaces; `switch` sets the current profile's default workspace | |+| | `mcp get/set/add/remove` | Manage the MCP servers shared by every agent in the workspace | Writes are owner/admin. `get` lists names and transports only — the stored configuration is write-only and never returned. `set` replaces the whole document (`--mcp-config-file` / `--mcp-config-stdin` keep tokens out of shell history; `--mcp-config null` clears it); `add <name>` / `remove <name>` change one server without holding the document || | `member list/invite <email>` | View members, send invites | `invite`: `--role` (member or admin, default member) || `repo` | `list/add/remove/checkout` | Manage workspace repositories and check them out locally | `--url` (repeatable); `checkout`: `--ref` || `skill` | `list/get/create/update/delete` | Manage skills | |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex e1510c5961..a1ac19055d 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -260,6 +260,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| | `runs <id>` | 查看运行历史 | || | `trigger-add/trigger-update/trigger-delete/trigger-rotate-url` | 管理定时和 webhook 触发器 | || `workspace` | `list/get/create/update/switch` | 管理工作区;`switch` 设置当前 profile 的默认工作区 | |+| | `mcp get/set/add/remove` | 管理工作区内所有 agent 共享的 MCP 服务 | 写操作需要 owner/admin。`get` 只列出名称与 transport——存储的配置是只写的,任何角色都读不回。`set` 整份替换(`--mcp-config-file` / `--mcp-config-stdin` 避免 token 进入 shell 历史;`--mcp-config null` 清空);`add <name>` / `remove <name>` 无需持有整份文档即可改动单个服务 || | `member list/invite <email>` | 查看成员、发出邀请 | `invite`:`--role`(member 或 admin,默认 member) || `repo` | `list/add/remove/checkout` | 管理工作区仓库并检出到本机 | `--url`(可重复);`checkout`:`--ref` || `skill` | `list/get/create/update/delete` | 管理 skill | |diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 133130c523..b5a4fdc693 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -2068,3 +2068,110 @@ describe("ApiClient refreshSkill response schema", () => {});});});++describe("ApiClient workspace MCP configuration", () => {+ function stubJSON(body: unknown) {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify(body), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+ }++ it("parses the shared server inventory", async () => {+ stubJSON({+ workspace_id: "ws-1",+ servers: [{ name: "linear", transport: "http", enabled: true }],+ server_count: 1,+ });++ const result = await new ApiClient("https://api.example.test")+ .getWorkspaceMcpConfig("ws-1");++ expect(result.server_count).toBe(1);+ expect(result.servers[0]).toMatchObject({ name: "linear", transport: "http" });+ });++ // The write-only boundary is enforced on the client too: a server that+ // regressed to returning the document, or a `url` / `headers` inside a+ // server entry, must not land in the parsed object or the query cache.+ it("strips secret-bearing fields the server should never have sent", async () => {+ stubJSON({+ workspace_id: "ws-1",+ mcp_config: {+ mcpServers: { linear: { headers: { Authorization: "Bearer sk-live-doc" } } },+ },+ servers: [{+ name: "linear",+ transport: "http",+ enabled: true,+ url: "https://mcp.example/sk-live-url",+ headers: { Authorization: "Bearer sk-live-header" },+ env: { TOKEN: "sk-live-env" },+ }],+ server_count: 1,+ });++ const result = await new ApiClient("https://api.example.test")+ .getWorkspaceMcpConfig("ws-1");++ expect(JSON.stringify(result)).not.toContain("sk-live");+ expect(result).toEqual({+ workspace_id: "ws-1",+ servers: [{ name: "linear", transport: "http", enabled: true }],+ server_count: 1,+ });+ });++ it("falls back safely when the inventory response is malformed", async () => {+ stubJSON({ workspace_id: 42, servers: "not-an-array" });++ const result = await new ApiClient("https://api.example.test")+ .getWorkspaceMcpConfig("ws-1");++ expect(result).toEqual({ workspace_id: "", servers: [], server_count: 0 });+ });++ it("keeps an unknown transport rather than dropping the server", async () => {+ // Enum drift from a newer backend must degrade, not disappear: the row+ // still renders and the UI's default branch labels it.+ stubJSON({+ workspace_id: "ws-1",+ servers: [{ name: "future", transport: "websocket", enabled: true }],+ server_count: 1,+ });++ const result = await new ApiClient("https://api.example.test")+ .getWorkspaceMcpConfig("ws-1");++ expect(result.servers).toHaveLength(1);+ expect(result.servers[0]?.transport).toBe("websocket");+ });++ it("PUTs a single server entry to the per-server endpoint", async () => {+ const fetchMock = stubJSON({ workspace_id: "ws-1", servers: [], server_count: 0 });++ await new ApiClient("https://api.example.test")+ .upsertWorkspaceMcpServer("ws-1", "my server", { url: "https://mcp.example" });++ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ // The name is a path segment, so it has to be encoded.+ expect(url).toContain("/api/workspaces/ws-1/mcp-config/servers/my%20server");+ expect(init.method).toBe("PUT");+ expect(JSON.parse(String(init.body))).toEqual({ url: "https://mcp.example" });+ });++ it("DELETEs one server by name", async () => {+ const fetchMock = stubJSON({ workspace_id: "ws-1", servers: [], server_count: 0 });++ await new ApiClient("https://api.example.test")+ .deleteWorkspaceMcpServer("ws-1", "linear");++ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(url).toContain("/api/workspaces/ws-1/mcp-config/servers/linear");+ expect(init.method).toBe("DELETE");+ });+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex f0a3a241ad..a1d4854c05 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -50,6 +50,7 @@ import type {IssueReaction,Workspace,WorkspaceRepo,+ WorkspaceMcpConfig,MemberWithUser,User,Skill,@@ -371,10 +372,12 @@ import {EMPTY_ISSUE_VIEW_PREFERENCE,EMPTY_PLUGIN_CATALOG,EMPTY_PLUGIN_INSTALLATION,+ EMPTY_WORKSPACE_MCP_CONFIG,EMPTY_PLUGIN_INSTALLATION_LIST,PluginCatalogResponseSchema,PluginInstallationListResponseSchema,PluginInstallationSchema,+ WorkspaceMcpConfigSchema,type IssueView,type IssueViewPreference,type CreateIssueViewRequest,@@ -2286,6 +2289,48 @@ export class ApiClient {});}+ /**+ * Lists the MCP servers the workspace shares with every agent. The response+ * carries names and transports only — the stored configuration is+ * write-only server-side, so there is nothing here to redact.+ */+ async getWorkspaceMcpConfig(workspaceId: string): Promise<WorkspaceMcpConfig> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/mcp-config`);+ return parseWithFallback(raw, WorkspaceMcpConfigSchema, EMPTY_WORKSPACE_MCP_CONFIG, {+ endpoint: "GET /api/workspaces/{id}/mcp-config",+ });+ }++ /**+ * Adds or replaces ONE shared MCP server. Per-server rather than a whole+ * document write because the client can never read the document back, so a+ * read-modify-write is impossible; the server merges under a row lock.+ */+ async upsertWorkspaceMcpServer(+ workspaceId: string,+ name: string,+ entry: Record<string, unknown>,+ ): Promise<WorkspaceMcpConfig> {+ const raw = await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/mcp-config/servers/${encodeURIComponent(name)}`,+ { method: "PUT", body: JSON.stringify(entry) },+ );+ return parseWithFallback(raw, WorkspaceMcpConfigSchema, EMPTY_WORKSPACE_MCP_CONFIG, {+ endpoint: "PUT /api/workspaces/{id}/mcp-config/servers/{name}",+ });+ }++ /** Removes one shared MCP server; removing the last one clears the layer. */+ async deleteWorkspaceMcpServer(workspaceId: string, name: string): Promise<WorkspaceMcpConfig> {+ const raw = await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/mcp-config/servers/${encodeURIComponent(name)}`,+ { method: "DELETE" },+ );+ return parseWithFallback(raw, WorkspaceMcpConfigSchema, EMPTY_WORKSPACE_MCP_CONFIG, {+ endpoint: "DELETE /api/workspaces/{id}/mcp-config/servers/{name}",+ });+ }+async installPlugin(workspaceId: string, request: PluginReleaseRequest): Promise<PluginInstallation> {const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/install`, {method: "POST",diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex bebdceee05..7d61301f60 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -70,6 +70,7 @@ import type {TimelineEntry,User,WebhookDelivery,+ WorkspaceMcpConfig,} from "../types";import type { CloudRuntimeNode } from "../runtimes/cloud-runtime";import type { CreateFeedbackResponse } from "../feedback/types";@@ -2566,3 +2567,34 @@ export const EMPTY_SKILL: Skill = {updated_at: "",files: [],};++/**+ * Read shape of the workspace's shared MCP configuration.+ *+ * These two are the ONLY schemas in this file that must not be `.loose()`.+ * Everywhere else, keeping unknown fields is forward-compatibility; here it+ * would be a hole in the write-only boundary — a server that regressed to+ * returning the document (or a server entry's `url` / `headers`) would have it+ * land in the parsed object and in the query cache. zod strips unknown keys by+ * default, so the client only ever holds the safe inventory.+ *+ * `transport` stays a plain string (not an enum) so an unknown value from a+ * newer backend still parses — the UI has a default branch for it.+ */+export const WorkspaceMcpServerSchema = z.object({+ name: z.string().default(""),+ transport: z.string().default("unknown"),+ enabled: z.boolean().default(true),+});++export const WorkspaceMcpConfigSchema = z.object({+ workspace_id: z.string().default(""),+ servers: z.array(WorkspaceMcpServerSchema).default([]),+ server_count: z.number().default(0),+});++export const EMPTY_WORKSPACE_MCP_CONFIG: WorkspaceMcpConfig = {+ workspace_id: "",+ servers: [],+ server_count: 0,+};diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex fef7d8f2f5..6d9550ba52 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -76,7 +76,7 @@ export type {MikaBootstrapResponse,} from "./agent";export { RUNTIME_PROFILE_PROTOCOL_FAMILIES } from "./agent";-export type { Workspace, WorkspaceRepo, Member, MemberRole, User, MemberWithUser, Invitation } from "./workspace";+export type { Workspace, WorkspaceRepo, WorkspaceMcpServer, WorkspaceMcpConfig, Member, MemberRole, User, MemberWithUser, Invitation } from "./workspace";export type {PluginBinding,PluginInstallation,diff --git a/packages/core/types/workspace.ts b/packages/core/types/workspace.tsindex dbf3f5591f..f8363c798b 100644--- a/packages/core/types/workspace.ts+++ b/packages/core/types/workspace.ts@@ -19,6 +19,27 @@ export interface Workspace {updated_at: string;}+/**+ * One MCP server shared by the workspace, as returned by+ * `GET /api/workspaces/{id}/mcp-config`.+ *+ * This is the WHOLE read shape: the stored configuration is write-only, so+ * urls, commands, headers, and env never leave the server for any role. UI+ * that needs to change an entry sends a replacement rather than editing what+ * it read back.+ */+export interface WorkspaceMcpServer {+ name: string;+ transport: string;+ enabled: boolean;+}++export interface WorkspaceMcpConfig {+ workspace_id: string;+ servers: WorkspaceMcpServer[];+ server_count: number;+}+export interface Member {id: string;workspace_id: string;diff --git a/packages/core/workspace/mutations.ts b/packages/core/workspace/mutations.tsindex d9cef177cc..9f442296c7 100644--- a/packages/core/workspace/mutations.ts+++ b/packages/core/workspace/mutations.ts@@ -87,3 +87,27 @@ export function useDeleteWorkspace() {},});}++/**+ * Adds or replaces one shared MCP server. There is no client-side merge: the+ * document is never returned, so the server does the read-modify-write and+ * hands back the refreshed inventory.+ */+export function useUpsertWorkspaceMcpServer(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: ({ name, entry }: { name: string; entry: Record<string, unknown> }) =>+ api.upsertWorkspaceMcpServer(wsId, name, entry),+ onSettled: () =>+ queryClient.invalidateQueries({ queryKey: workspaceKeys.mcpConfig(wsId) }),+ });+}++export function useDeleteWorkspaceMcpServer(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (name: string) => api.deleteWorkspaceMcpServer(wsId, name),+ onSettled: () =>+ queryClient.invalidateQueries({ queryKey: workspaceKeys.mcpConfig(wsId) }),+ });+}diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.tsindex 795d9e464c..d883c9e31a 100644--- a/packages/core/workspace/queries.ts+++ b/packages/core/workspace/queries.ts@@ -17,6 +17,7 @@ export const workspaceKeys = {["workspaces", wsId, "squads", squadId, "members-status"] as const,skills: (wsId: string) => ["workspaces", wsId, "skills"] as const,assigneeFrequency: (wsId: string) => ["workspaces", wsId, "assignee-frequency"] as const,+ mcpConfig: (wsId: string) => ["workspaces", wsId, "mcp-config"] as const,};export function workspaceListOptions() {@@ -134,3 +135,16 @@ export function assigneeFrequencyOptions(wsId: string) {queryFn: () => api.getAssigneeFrequency(),});}++/**+ * The workspace's shared MCP servers. Used by workspace Settings to manage+ * them and by the agent MCP tab to show what an agent inherits, so it is+ * fetched for plain members too — the payload is names and transports only.+ */+export function workspaceMcpConfigOptions(wsId: string) {+ return queryOptions({+ queryKey: workspaceKeys.mcpConfig(wsId),+ queryFn: () => api.getWorkspaceMcpConfig(wsId),+ enabled: wsId !== "",+ });+}diff --git a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx b/packages/views/agents/components/tabs/mcp-config-tab.test.tsxindex 608af96048..d1a546808e 100644--- a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx+++ b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx@@ -14,6 +14,19 @@ import { McpConfigTab } from "./mcp-config-tab";const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };const mockRuntimeCapabilities = vi.hoisted(() => vi.fn());+const workspaceMcp = vi.hoisted(() => ({+ data: { workspace_id: "ws-1", servers: [] as Array<Record<string, unknown>>, server_count: 0 },+}));++// The inherited section reads the workspace's shared servers. Stubbing the+// query options keeps this a pure render test — the real one would hit fetch.+vi.mock("@multica/core/workspace/queries", () => ({+ workspaceMcpConfigOptions: (wsId: string) => ({+ queryKey: ["workspaces", wsId, "mcp-config"],+ queryFn: () => Promise.resolve(workspaceMcp.data),+ enabled: wsId !== "",+ }),+}));// The tab reads discovery through runtimeCapabilitiesOptions; existing tests// render with runtime={null} so the query stays disabled and never fires.@@ -112,7 +125,10 @@ const onlineRuntime: AgentRuntime = {};describe("McpConfigTab", () => {- beforeEach(() => vi.clearAllMocks());+ beforeEach(() => {+ vi.clearAllMocks();+ workspaceMcp.data = { workspace_id: "ws-1", servers: [], server_count: 0 };+ });it("renders redacted managed MCP without exposing add or edit controls", () => {renderTab({ mcp_config: null, mcp_config_redacted: true });@@ -298,3 +314,172 @@ describe("McpConfigTab", () => {).toBeInTheDocument();});});++// The workspace layer (GH #6062) is what an agent runs with on top of its own+// servers, so the tab has to make it visible — including which shared servers+// this agent overrides, and when it inherits nothing at all.+describe("McpConfigTab workspace inheritance", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ workspaceMcp.data = { workspace_id: "ws-1", servers: [], server_count: 0 };+ });++ it("lists the servers inherited from the workspace", async () => {+ workspaceMcp.data = {+ workspace_id: "ws-1",+ servers: [{ name: "shared-linear", transport: "http", enabled: true }],+ server_count: 1,+ };+ renderTab({ mcp_config: null });++ expect(await screen.findByText("shared-linear")).toBeInTheDocument();+ expect(screen.getByText(/Inherited from workspace/)).toBeInTheDocument();+ });++ it("marks a shared server the agent overrides by name", async () => {+ workspaceMcp.data = {+ workspace_id: "ws-1",+ servers: [{ name: "linear", transport: "http", enabled: true }],+ server_count: 1,+ };+ renderTab({+ mcp_config: { mcpServers: { linear: { url: "https://agent.example" } } },+ });++ expect(await screen.findByText("Overridden")).toBeInTheDocument();+ });++ it("says an agent with a managed-but-empty config inherits nothing", async () => {+ workspaceMcp.data = {+ workspace_id: "ws-1",+ servers: [{ name: "shared-linear", transport: "http", enabled: true }],+ server_count: 1,+ };+ renderTab({ mcp_config: {} });++ expect(+ await screen.findByText(/inherits none of the workspace/i),+ ).toBeInTheDocument();+ // The shared server must NOT be listed as inherited: this agent opted out.+ expect(screen.queryByText("shared-linear")).toBeNull();+ });++ it("renders an empty state when the workspace shares nothing", async () => {+ renderTab({ mcp_config: null });++ expect(+ await screen.findByText(/workspace shares no MCP servers/),+ ).toBeInTheDocument();+ });+});++// The runtime section's Overridden badge has to reflect the REAL precedence —+// runtime < workspace < agent — and the whole inheritance story has to go+// quiet when the agent's own config is hidden from this viewer.+describe("McpConfigTab effective set", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ workspaceMcp.data = { workspace_id: "ws-1", servers: [], server_count: 0 };+ });++ it("marks a runtime server shadowed by a workspace server as overridden", async () => {+ workspaceMcp.data = {+ workspace_id: "ws-1",+ servers: [{ name: "fetch", transport: "http", enabled: true }],+ server_count: 1,+ };+ mockRuntimeCapabilities.mockResolvedValue({+ mcpSupported: true,+ mcpServers: [{ name: "fetch", transport: "stdio", enabled: true, source: "runtime" }],+ });+ renderTab({ mcp_config: null }, vi.fn(), onlineRuntime);++ // The shared server hides the runtime's same-named one, even though the+ // agent itself declares nothing.+ expect(+ await screen.findByText("Overridden by Multica"),+ ).toBeInTheDocument();+ });++ it("does not mark a runtime server overridden when the agent opted out", async () => {+ workspaceMcp.data = {+ workspace_id: "ws-1",+ servers: [{ name: "fetch", transport: "http", enabled: true }],+ server_count: 1,+ };+ mockRuntimeCapabilities.mockResolvedValue({+ mcpSupported: true,+ mcpServers: [{ name: "fetch", transport: "stdio", enabled: true, source: "runtime" }],+ });+ renderTab({ mcp_config: {} }, vi.fn(), onlineRuntime);++ expect(+ await screen.findByText(/inherits none of the workspace/i),+ ).toBeInTheDocument();+ expect(screen.queryByText("Overridden by Multica")).toBeNull();+ });++ // Same transport hazard on the agent side, reached through the SAVED config+ // rather than a summary: the form emits `type: "http"`, so neither entry may+ // be editable through it.+ //+ // `websocket` is the one that catches using mcpTransport() for this: that+ // display classifier buckets any entry with a `url` as http, so the unknown+ // type would look form-editable and be rewritten on save.+ it.each([+ ["sse", { type: "sse", url: "https://sse.example" }],+ ["websocket", { type: "websocket", url: "wss://example.test" }],+ ])("edits an agent's %s server through JSON, not the form", async (_label, entry) => {+ const user = userEvent.setup();+ renderTab({ mcp_config: { mcpServers: { streamy: entry } } });++ await user.click(+ screen.getByRole("button", { name: /edit mcp server streamy/i }),+ );++ expect(screen.getByRole("tab", { name: "JSON" })).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(screen.getByRole("tab", { name: "Form" })).toHaveAttribute(+ "aria-disabled",+ "true",+ );+ });++ // The common shapes must stay on the form — this guard is about entries the+ // form would CHANGE, not a general retreat to the JSON editor.+ it.each([+ ["stdio", { command: "uvx" }],+ ["typed http", { type: "http", url: "https://mcp.example" }],+ ["untyped url", { url: "https://mcp.example" }],+ ])("keeps editing a %s server on the form", async (_label, entry) => {+ const user = userEvent.setup();+ renderTab({ mcp_config: { mcpServers: { normal: entry } } });++ await user.click(+ screen.getByRole("button", { name: /edit mcp server normal/i }),+ );++ expect(screen.getByRole("tab", { name: "Form" })).toHaveAttribute(+ "aria-selected",+ "true",+ );+ });++ it("says inheritance cannot be determined when mcp_config is redacted", async () => {+ workspaceMcp.data = {+ workspace_id: "ws-1",+ servers: [{ name: "shared-linear", transport: "http", enabled: true }],+ server_count: 1,+ };+ renderTab({ mcp_config: null, mcp_config_redacted: true });++ expect(+ await screen.findByText(/cannot be determined/i),+ ).toBeInTheDocument();+ // Claiming the agent inherits these would be a guess: a hidden config may+ // be an explicit empty document, or may override some of these names.+ expect(screen.queryByText("shared-linear")).toBeNull();+ });+});diff --git a/packages/views/agents/components/tabs/mcp-config-tab.tsx b/packages/views/agents/components/tabs/mcp-config-tab.tsxindex 0a1698181c..fd0b63b8de 100644--- a/packages/views/agents/components/tabs/mcp-config-tab.tsx+++ b/packages/views/agents/components/tabs/mcp-config-tab.tsx@@ -17,6 +17,7 @@ import {runtimeCapabilitiesOptions,runtimeDisplayLabel,} from "@multica/core/runtimes";+import { workspaceMcpConfigOptions } from "@multica/core/workspace/queries";import {AlertDialog,AlertDialogAction,@@ -56,6 +57,12 @@ export function McpConfigTab({? runtime.id: null;const runtimeQuery = useQuery(runtimeCapabilitiesOptions(runtimeId));+ // What this agent inherits from the workspace (GH #6062). Read-only here:+ // the shared set is edited in workspace Settings, and the API returns names+ // and transports only — never the shared credentials.+ const workspaceMcpQuery = useQuery(+ workspaceMcpConfigOptions(agent.workspace_id ?? ""),+ );const redacted = agent.mcp_config_redacted === true;const managedServers = useMemo(() => listManagedMcpServers(agent.mcp_config),@@ -65,6 +72,30 @@ export function McpConfigTab({() => new Set(managedServers.map((server) => server.name)),[managedServers],);+ const workspaceServers = workspaceMcpQuery.data?.servers ?? [];+ // The resolution contract's opt-out: an agent whose saved configuration+ // declares NO servers inherits none of the workspace's. `null` / absent+ // means "not configured at the agent layer", which DOES inherit — so key+ // this off a present-but-empty document, not off an empty list.+ const optedOutOfWorkspace =+ !redacted &&+ agent.mcp_config !== null &&+ agent.mcp_config !== undefined &&+ managedServers.length === 0;+ // When mcp_config is redacted this view cannot tell an explicit empty+ // document (opted out) from one that overrides some names, so it must not+ // claim either. Everything inheritance-related below says "unknown".+ const inheritsWorkspace = !redacted && !optedOutOfWorkspace;+ // Names that shadow a runtime server in the effective set. The daemon merges+ // runtime < (workspace + agent), so a shared server hides a same-named+ // runtime one too — marking only the agent's names under-reports it.+ const effectiveNames = useMemo(() => {+ const names = new Set(managedNames);+ if (inheritsWorkspace) {+ for (const server of workspaceServers) names.add(server.name);+ }+ return names;+ }, [managedNames, inheritsWorkspace, workspaceServers]);const [editorOpen, setEditorOpen] = useState(false);const [editingServer, setEditingServer] = useState<ManagedMcpServer | null>(null,@@ -185,6 +216,40 @@ export function McpConfigTab({)}</section>+ <section className="space-y-3">+ <div>+ <h3 className="text-body font-medium">+ {t(($) => $.tab_body.mcp_config.workspace_title)}+ </h3>+ <p className="mt-1 max-w-2xl text-caption leading-5 text-muted-foreground">+ {t(($) => $.tab_body.mcp_config.workspace_hint)}+ </p>+ </div>+ {redacted ? (+ <McpNotice text={t(($) => $.tab_body.mcp_config.workspace_unknown)} />+ ) : optedOutOfWorkspace ? (+ <McpNotice text={t(($) => $.tab_body.mcp_config.workspace_opted_out)} />+ ) : workspaceMcpQuery.isLoading ? (+ <McpNotice+ loading+ text={t(($) => $.tab_body.mcp_config.workspace_loading)}+ />+ ) : workspaceServers.length === 0 ? (+ <McpNotice text={t(($) => $.tab_body.mcp_config.workspace_empty)} />+ ) : (+ <McpServerList+ servers={workspaceServers.map((server) => ({+ name: server.name,+ transport: server.transport || "unknown",+ enabled: server.enabled,+ overridden: managedNames.has(server.name),+ }))}+ disabledLabel={t(($) => $.tab_body.mcp_config.workspace_disabled_badge)}+ overriddenLabel={t(($) => $.tab_body.mcp_config.workspace_overridden_badge)}+ />+ )}+ </section>+<section className="space-y-3"><div className="flex items-start justify-between gap-4"><div>@@ -247,7 +312,7 @@ export function McpConfigTab({transport: server.transport || "unknown",enabled: server.enabled,source: server.source,- overridden: managedNames.has(server.name),+ overridden: effectiveNames.has(server.name),}))}disabledLabel={t(($) => $.tab_body.mcp_config.runtime_disabled_badge)}overriddenLabel={t(($) => $.tab_body.mcp_config.runtime_overridden_badge)}diff --git a/packages/views/agents/components/tabs/mcp-server-dialog.tsx b/packages/views/agents/components/tabs/mcp-server-dialog.tsxindex 952d38d1bb..6199035a1c 100644--- a/packages/views/agents/components/tabs/mcp-server-dialog.tsx+++ b/packages/views/agents/components/tabs/mcp-server-dialog.tsx@@ -104,6 +104,49 @@ function recordFromPairs(pairs: KeyValue[]): Record<string, string> | undefinedreturn entries.length > 0 ? Object.fromEntries(entries) : undefined;}+/**+ * The guided form can only express two transports, and saving from it REWRITES+ * the entry (`configFromForm` emits `type: "http"` for anything non-stdio). An+ * entry on any other transport — `sse` today, whatever a newer backend reports+ * tomorrow — must therefore never be routed through the form, or editing it+ * would silently change its protocol and can break the server outright.+ * Those entries take the JSON path, which round-trips whatever is typed.+ *+ * This one classifies a NON-secret summary transport, which the server emits+ * from a closed set (stdio / http / sse / unknown).+ */+function formCanExpressTransport(transport: string): boolean {+ return transport === "stdio" || transport === "http";+}++/** The `type` values `configFromForm` can write back without changing them. */+const FORM_EXPRESSIBLE_TYPES = new Set([+ "local",+ "stdio",+ "remote",+ "http",+ "streamable-http",+]);++/**+ * Whether the form can round-trip a SAVED entry.+ *+ * Deliberately does not reuse `mcpTransport`: that is a lossy DISPLAY+ * classifier — it reports "http" for any entry carrying a `url`, whatever its+ * `type` — so `{"type":"websocket","url":"wss://…"}` would look form-editable+ * and be rewritten to `type: "http"` on save. Safety decisions need the+ * explicit value, not the display bucket.+ */+function formCanExpressConfig(config: Record<string, unknown>): boolean {+ const type =+ typeof config.type === "string" ? config.type.trim().toLowerCase() : "";+ if (type !== "") return FORM_EXPRESSIBLE_TYPES.has(type);+ // No explicit type: the form infers stdio from `command` and http from+ // `url`, and writes that same shape back. With neither there is nothing for+ // it to express, so leave the entry to the JSON editor.+ return config.command !== undefined || config.url !== undefined;+}+function configFromForm(form: McpFormState): Record<string, unknown> {const config = { ...form.extras };if (form.transport === "stdio") {@@ -136,16 +179,38 @@ function parseServerJson(text: string):}}+/**+ * Whether the guided form can edit this entry without changing it. The legacy+ * `mcp` container is provider-native and must round-trip verbatim; so is any+ * entry whose transport the form cannot express. When the caller could not read+ * the saved config back, the safe summary's transport is the only signal.+ */+function formSupportsServer(server: ManagedMcpServer): boolean {+ if (server.container === "mcp") return false;+ // With a saved entry in hand, judge the entry itself; the summary transport+ // is only a fallback for callers that could not read one back.+ return Object.keys(server.config).length > 0+ ? formCanExpressConfig(server.config)+ : formCanExpressTransport(server.transport);+}+export function McpServerDialog({open,server,existingNames,+ lockName = false,onOpenChange,onSave,}: {open: boolean;server: ManagedMcpServer | null;existingNames: Set<string>;+ /**+ * Pins the name while editing. Callers whose backend has no atomic rename+ * must set this: letting the field change would turn "save" into "create a+ * second server" and silently leave the original behind.+ */+ lockName?: boolean;onOpenChange: (open: boolean) => void;onSave: (name: string, config: Record<string, unknown>) => Promise<void>;}) {@@ -160,11 +225,25 @@ export function McpServerDialog({if (!open) return;const config = server?.config ?? {};setName(server?.name ?? "");- setForm(server ? formFromConfig(config) : emptyForm());+ // A caller that cannot read the saved entry back (the workspace layer is+ // write-only) passes an empty config with the transport from the safe+ // summary. Seeding from `formFromConfig({})` there would open an http form+ // for a known stdio server, so take the transport from the summary.+ setForm(+ !server+ ? emptyForm()+ : Object.keys(config).length > 0+ ? formFromConfig(config)+ : { ...emptyForm(), transport: server.transport === "stdio" ? "stdio" : "http" },+ );setJsonText(JSON.stringify(config, null, 2));- setMode(server?.container === "mcp" ? "json" : "form");+ setMode(server && !formSupportsServer(server) ? "json" : "form");}, [open, server]);+ // The form is unavailable — not merely unselected — for entries it cannot+ // represent, so switching to it cannot rewrite them either.+ const formAvailable = !server || formSupportsServer(server);+const jsonResult = useMemo(() => parseServerJson(jsonText), [jsonText]);const trimmedName = name.trim();const nameError =@@ -261,12 +340,20 @@ export function McpServerDialog({onChange={(event) => setName(event.target.value)}placeholder={t(($) => $.tab_body.mcp_config.dialog_name_placeholder)}aria-invalid={nameError !== null || undefined}+ readOnly={lockName}+ aria-readonly={lockName || undefined}+ className={lockName ? "text-muted-foreground" : undefined}/>+ {lockName ? (+ <p className="text-caption text-muted-foreground">+ {t(($) => $.tab_body.mcp_config.dialog_name_locked)}+ </p>+ ) : null}</div><Tabs value={mode} onValueChange={handleModeChange}><TabsList className="grid w-full grid-cols-2">- <TabsTrigger value="form" disabled={server?.container === "mcp"}>+ <TabsTrigger value="form" disabled={!formAvailable}>{t(($) => $.tab_body.mcp_config.dialog_form_tab)}</TabsTrigger><TabsTrigger value="json">diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 29160aa5ce..3efdb9ea21 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -516,6 +516,15 @@"agent_disabled_badge": "Off for agent","runtime_disabled_badge": "Off in runtime","runtime_overridden_badge": "Overridden by Multica",+ "workspace_title": "Inherited from workspace",+ "workspace_hint": "MCP servers shared with every agent in this workspace. Manage them in workspace Settings → MCP; this agent's own servers win on a name collision.",+ "workspace_loading": "Loading shared servers…",+ "workspace_empty": "This workspace shares no MCP servers.",+ "workspace_opted_out": "This agent's own configuration declares no MCP servers, so it inherits none of the workspace's. Its runtime's local servers still apply. Remove its configuration entirely to inherit again.",+ "workspace_unknown": "This agent's own MCP configuration is not visible to you, so what it inherits from the workspace cannot be determined here.",+ "dialog_name_locked": "The name cannot be changed here — renaming would add a second server and leave this one behind. Remove and re-add it instead.",+ "workspace_disabled_badge": "Disabled",+ "workspace_overridden_badge": "Overridden","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",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 882f4b1ed5..fae93c447d 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -163,6 +163,28 @@"start_date": "Start date"}},+ "mcp": {+ "title": "MCP",+ "description": "MCP servers shared with every agent in this workspace, so the same server does not have to be re-entered on each agent.",+ "servers_title": "Shared servers",+ "write_only_note": "An agent with no MCP configuration of its own inherits these servers; an agent with its own merges on top and wins on a name collision. Saved configurations are write-only — urls, commands, headers, and environment values are never shown again, so editing a server replaces its configuration.",+ "add_server": "Add server",+ "edit_server": "Edit server",+ "remove_server": "Remove server",+ "empty_title": "No shared MCP servers",+ "empty_description": "Add a server here and every agent in the workspace inherits it on its next task, unless the agent has opted out.",+ "disabled_badge": "Disabled",+ "admin_only_note": "Only workspace owners and admins can change the shared MCP servers.",+ "delete_title": "Remove shared server?",+ "delete_description": "{{name}} will stop being shared with this workspace's agents on their next task. Agents that define a server with the same name themselves are unaffected.",+ "delete_confirm": "Remove",+ "cancel": "Cancel",+ "added_toast": "Shared MCP server added",+ "updated_toast": "Shared MCP server updated",+ "removed_toast": "Shared MCP server removed",+ "save_failed_toast": "Could not save the shared MCP server",+ "remove_failed_toast": "Could not remove the shared MCP server"+ },"page": {"title": "Settings","my_account": "My Account",@@ -185,6 +207,7 @@"properties": "Properties","quick_actions": "Quick Actions","plugins": "Plugins",+ "mcp": "MCP","billing": "Billing"}},diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 2726ef820f..c4fa495ba6 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -398,6 +398,15 @@"agent_disabled_badge": "エージェントで無効","runtime_disabled_badge": "ランタイムで無効","runtime_overridden_badge": "Multica で上書き",+ "workspace_title": "ワークスペースから継承",+ "workspace_hint": "このワークスペースの全エージェントで共有される MCP サーバー。ワークスペース設定 → MCP で管理します。名前が衝突した場合はこのエージェント自身のサーバーが優先されます。",+ "workspace_loading": "共有サーバーを読み込み中…",+ "workspace_empty": "このワークスペースは MCP サーバーを共有していません。",+ "workspace_opted_out": "このエージェント自身の設定は MCP サーバーを 1 つも宣言していないため、ワークスペースのサーバーを継承しません。ランタイムのローカルサーバーは引き続き有効です。継承を再開するには独自の設定を完全に削除してください。",+ "workspace_unknown": "このエージェント自身の MCP 設定は閲覧できないため、ワークスペースから何を継承するかはここでは判断できません。",+ "dialog_name_locked": "ここでは名前を変更できません。変更すると別のサーバーが追加され、元のサーバーが残ります。削除してから追加し直してください。",+ "workspace_disabled_badge": "無効",+ "workspace_overridden_badge": "上書き","runtime_title": "ランタイムから継承","runtime_hint": "{{runtime}} から自動検出し、作業開始時にローカルで統合します。URL、ヘッダー、コマンド、環境変数はマシン外に送信されません。","refresh_action": "更新",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex c823d7655e..c47e79835b 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -163,6 +163,28 @@"start_date": "開始日"}},+ "mcp": {+ "title": "MCP",+ "description": "このワークスペースの全エージェントで共有する MCP サーバー。同じ設定をエージェントごとに入力し直す必要がなくなります。",+ "servers_title": "共有サーバー",+ "write_only_note": "独自の MCP 設定を持たないエージェントはこれらのサーバーを継承します。独自の設定を持つエージェントはその上にマージされ、名前が衝突した場合はエージェント側が優先されます。保存された設定は書き込み専用です — url、コマンド、ヘッダー、環境変数は二度と表示されないため、サーバーの編集は設定の置き換えになります。",+ "add_server": "サーバーを追加",+ "edit_server": "サーバーを編集",+ "remove_server": "サーバーを削除",+ "empty_title": "共有 MCP サーバーはありません",+ "empty_description": "ここにサーバーを追加すると、オプトアウトしていない限り、ワークスペース内の全エージェントが次のタスクから継承します。",+ "disabled_badge": "無効",+ "admin_only_note": "共有 MCP サーバーを変更できるのはワークスペースの owner と admin のみです。",+ "delete_title": "共有サーバーを削除しますか?",+ "delete_description": "{{name}} は次のタスクからこのワークスペースのエージェントに共有されなくなります。同名のサーバーを自分で定義しているエージェントには影響しません。",+ "delete_confirm": "削除",+ "cancel": "キャンセル",+ "added_toast": "共有 MCP サーバーを追加しました",+ "updated_toast": "共有 MCP サーバーを更新しました",+ "removed_toast": "共有 MCP サーバーを削除しました",+ "save_failed_toast": "共有 MCP サーバーを保存できませんでした",+ "remove_failed_toast": "共有 MCP サーバーを削除できませんでした"+ },"page": {"title": "設定","my_account": "マイアカウント",@@ -185,6 +207,7 @@"properties": "プロパティ","quick_actions": "クイックアクション","plugins": "Plugins",+ "mcp": "MCP","billing": "請求とプラン"}},diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 990c980668..6c8d4f1789 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -406,6 +406,15 @@"agent_disabled_badge": "에이전트에서 꺼짐","runtime_disabled_badge": "런타임에서 꺼짐","runtime_overridden_badge": "Multica에서 재정의",+ "workspace_title": "워크스페이스에서 상속",+ "workspace_hint": "이 워크스페이스의 모든 에이전트가 공유하는 MCP 서버입니다. 워크스페이스 설정 → MCP에서 관리하며, 이름이 충돌하면 이 에이전트의 서버가 우선합니다.",+ "workspace_loading": "공유 서버를 불러오는 중…",+ "workspace_empty": "이 워크스페이스는 MCP 서버를 공유하지 않습니다.",+ "workspace_opted_out": "이 에이전트의 자체 설정에 MCP 서버가 하나도 없으므로 워크스페이스의 서버를 상속하지 않습니다. 런타임의 로컬 서버는 그대로 적용됩니다. 다시 상속하려면 자체 설정을 완전히 제거하세요.",+ "workspace_unknown": "이 에이전트의 자체 MCP 설정을 볼 수 없어 워크스페이스에서 무엇을 상속하는지 여기서는 판단할 수 없습니다.",+ "dialog_name_locked": "여기서는 이름을 바꿀 수 없습니다. 이름을 바꾸면 서버가 하나 더 추가되고 기존 서버가 남습니다. 제거 후 다시 추가하세요.",+ "workspace_disabled_badge": "비활성화됨",+ "workspace_overridden_badge": "재정의됨","runtime_title": "런타임에서 상속","runtime_hint": "{{runtime}}에서 자동으로 탐색하고 작업 시작 시 로컬에서 병합합니다. URL, 헤더, 명령 및 환경 변수는 머신 외부로 전송되지 않습니다.","refresh_action": "새로고침",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex c0d2e558be..476c1330b9 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -163,6 +163,28 @@"start_date": "시작일"}},+ "mcp": {+ "title": "MCP",+ "description": "이 워크스페이스의 모든 에이전트가 공유하는 MCP 서버입니다. 같은 설정을 에이전트마다 다시 입력할 필요가 없습니다.",+ "servers_title": "공유 서버",+ "write_only_note": "자체 MCP 설정이 없는 에이전트는 이 서버들을 상속합니다. 자체 설정이 있는 에이전트는 그 위에 병합되며 이름이 충돌하면 에이전트 쪽이 우선합니다. 저장된 설정은 쓰기 전용이라 url, 명령, 헤더, 환경 변수는 다시 표시되지 않으므로 서버 편집은 설정을 교체하는 것입니다.",+ "add_server": "서버 추가",+ "edit_server": "서버 편집",+ "remove_server": "서버 제거",+ "empty_title": "공유 MCP 서버가 없습니다",+ "empty_description": "여기에 서버를 추가하면 옵트아웃하지 않은 한 워크스페이스의 모든 에이전트가 다음 작업부터 상속합니다.",+ "disabled_badge": "비활성화됨",+ "admin_only_note": "공유 MCP 서버는 워크스페이스 owner와 admin만 변경할 수 있습니다.",+ "delete_title": "공유 서버를 제거할까요?",+ "delete_description": "{{name}}은(는) 다음 작업부터 이 워크스페이스의 에이전트에 공유되지 않습니다. 같은 이름의 서버를 직접 정의한 에이전트는 영향을 받지 않습니다.",+ "delete_confirm": "제거",+ "cancel": "취소",+ "added_toast": "공유 MCP 서버를 추가했습니다",+ "updated_toast": "공유 MCP 서버를 업데이트했습니다",+ "removed_toast": "공유 MCP 서버를 제거했습니다",+ "save_failed_toast": "공유 MCP 서버를 저장하지 못했습니다",+ "remove_failed_toast": "공유 MCP 서버를 제거하지 못했습니다"+ },"page": {"title": "설정","my_account": "내 계정",@@ -185,6 +207,7 @@"properties": "속성","quick_actions": "퀵 액션","plugins": "Plugins",+ "mcp": "MCP","billing": "결제 및 요금제"}},diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex b94db98d60..e9a26aa46b 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -505,6 +505,15 @@"agent_disabled_badge": "已为智能体关闭","runtime_disabled_badge": "运行时中已关闭","runtime_overridden_badge": "已由 Multica 覆盖",+ "workspace_title": "从工作区继承",+ "workspace_hint": "与本工作区所有智能体共享的 MCP 服务。在工作区设置 → MCP 中管理;同名时以本智能体自己的配置为准。",+ "workspace_loading": "正在加载共享服务…",+ "workspace_empty": "本工作区没有共享任何 MCP 服务。",+ "workspace_opted_out": "该智能体自己的配置没有声明任何 MCP 服务,因此不继承工作区的服务;它所在运行时的本地服务仍然生效。完全移除它自己的配置即可恢复继承。",+ "workspace_unknown": "你无权查看该智能体自己的 MCP 配置,因此这里无法确定它从工作区继承了什么。",+ "dialog_name_locked": "这里不能改名——改名会新增一个服务并把原来的留在那里。请改用移除后重新添加。",+ "workspace_disabled_badge": "已禁用",+ "workspace_overridden_badge": "已覆盖","runtime_title": "从运行时继承","runtime_hint": "自动从 {{runtime}} 发现,并在 task 启动时于本机完成合并。URL、Header、命令和环境变量等敏感值不会离开本机。","refresh_action": "刷新",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex f2a9ce39dd..2c785dfbb5 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -163,6 +163,28 @@"start_date": "开始日期"}},+ "mcp": {+ "title": "MCP",+ "description": "与本工作区所有智能体共享的 MCP 服务,不必在每个智能体上重复录入同一批配置。",+ "servers_title": "共享服务",+ "write_only_note": "没有自己 MCP 配置的智能体会继承这些服务;有自己配置的智能体在其之上合并,同名时以智能体自己的为准。已保存的配置是只写的——URL、命令、请求头和环境变量不会再次展示,因此编辑一个服务等于整条替换它的配置。",+ "add_server": "添加服务",+ "edit_server": "编辑服务",+ "remove_server": "移除服务",+ "empty_title": "还没有共享的 MCP 服务",+ "empty_description": "在这里添加服务后,工作区内所有智能体会在下一个任务开始时继承它——除非该智能体已明确退出。",+ "disabled_badge": "已禁用",+ "admin_only_note": "只有工作区 owner 和 admin 可以修改共享的 MCP 服务。",+ "delete_title": "移除共享服务?",+ "delete_description": "{{name}} 将在本工作区智能体的下一个任务起不再共享。自己定义了同名服务的智能体不受影响。",+ "delete_confirm": "移除",+ "cancel": "取消",+ "added_toast": "已添加共享 MCP 服务",+ "updated_toast": "已更新共享 MCP 服务",+ "removed_toast": "已移除共享 MCP 服务",+ "save_failed_toast": "共享 MCP 服务保存失败",+ "remove_failed_toast": "共享 MCP 服务移除失败"+ },"page": {"title": "设置","my_account": "我的账号",@@ -185,6 +207,7 @@"properties": "属性","quick_actions": "快捷操作","plugins": "Plugins",+ "mcp": "MCP","billing": "账单与套餐"}},diff --git a/packages/views/settings/components/index.ts b/packages/views/settings/components/index.tsindex 718f5a01b4..151a57313d 100644--- a/packages/views/settings/components/index.ts+++ b/packages/views/settings/components/index.ts@@ -1,5 +1,6 @@export { SettingsPage } from "./settings-page";export type { ExtraSettingsTab } from "./settings-page";export { PluginsTab } from "./plugins-tab";+export { McpTab } from "./mcp-tab";export { LabelsTab } from "./labels-tab";export { BillingTab } from "./billing-tab";diff --git a/packages/views/settings/components/mcp-tab.test.tsx b/packages/views/settings/components/mcp-tab.test.tsxnew file mode 100644index 0000000000..906f3d92e7--- /dev/null+++ b/packages/views/settings/components/mcp-tab.test.tsx@@ -0,0 +1,234 @@+// @vitest-environment jsdom++import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../locales/en/common.json";+import enSettings from "../../locales/en/settings.json";+import enAgents from "../../locales/en/agents.json";++const mockUpsert = vi.hoisted(() => vi.fn());+const mockDelete = vi.hoisted(() => vi.fn());++const data = vi.hoisted(() => ({+ config: {+ workspace_id: "workspace-1",+ servers: [+ { name: "linear", transport: "http", enabled: true },+ { name: "local-tool", transport: "stdio", enabled: false },+ ],+ server_count: 2,+ },+ isLoading: false,+ role: "owner" as "owner" | "admin" | "member",+}));++vi.mock("@tanstack/react-query", () => ({+ useQuery: () => ({ data: data.config, isLoading: data.isLoading }),+}));++vi.mock("@multica/core/workspace/queries", () => ({+ workspaceMcpConfigOptions: () => ({ queryKey: ["workspaces", "workspace-1", "mcp-config"] }),+}));++vi.mock("@multica/core/workspace/mutations", () => ({+ useUpsertWorkspaceMcpServer: () => ({ mutateAsync: mockUpsert, isPending: false }),+ useDeleteWorkspaceMcpServer: () => ({ mutateAsync: mockDelete, isPending: false }),+}));++vi.mock("@multica/core/paths", () => ({+ useCurrentWorkspace: () => ({ id: "workspace-1", name: "Acme", slug: "acme" }),+}));++vi.mock("@multica/core/permissions", () => ({+ useCurrentMember: () => ({ role: data.role, isLoading: false }),+}));++vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++import { McpTab } from "./mcp-tab";++const TEST_RESOURCES = {+ en: { common: enCommon, settings: enSettings, agents: enAgents },+};++function Wrapper({ children }: { children: ReactNode }) {+ return (+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ );+}++describe("McpTab", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ data.role = "owner";+ data.isLoading = false;+ data.config = {+ workspace_id: "workspace-1",+ servers: [+ { name: "linear", transport: "http", enabled: true },+ { name: "local-tool", transport: "stdio", enabled: false },+ ],+ server_count: 2,+ };+ mockUpsert.mockResolvedValue({});+ mockDelete.mockResolvedValue({});+ });++ it("lists the shared servers with their transport and disabled state", () => {+ render(<McpTab />, { wrapper: Wrapper });++ expect(screen.getByText("linear")).toBeInTheDocument();+ expect(screen.getByText("HTTP")).toBeInTheDocument();+ expect(screen.getByText("local-tool")).toBeInTheDocument();+ expect(screen.getByText("stdio")).toBeInTheDocument();+ expect(screen.getByText("Disabled")).toBeInTheDocument();+ });++ it("adds a server through the per-server endpoint", async () => {+ const user = userEvent.setup();+ render(<McpTab />, { wrapper: Wrapper });++ await user.click(screen.getByRole("button", { name: /Add server/ }));+ await user.type(screen.getByLabelText("Name"), "github");+ // The shared dialog defaults to the STDIO transport.+ await user.type(screen.getByLabelText("Command"), "github-mcp");+ await user.click(screen.getByRole("button", { name: "Add Server" }));++ await waitFor(() =>+ expect(mockUpsert).toHaveBeenCalledWith(+ expect.objectContaining({ name: "github" }),+ ),+ );+ // The entry is sent on its own — the client never holds, and therefore+ // never resends, the rest of the shared document.+ const call = mockUpsert.mock.calls[0]![0] as { entry: Record<string, unknown> };+ expect(call.entry).not.toHaveProperty("mcpServers");+ });++ // Regression: the shared dialog lets the name be edited, and the API has no+ // atomic rename. Without pinning the name, "editing" linear to linear-v2+ // would create a second server, leave linear behind, and still toast+ // "updated".+ it("pins the name while editing so a rename cannot orphan the original", async () => {+ const user = userEvent.setup();+ render(<McpTab />, { wrapper: Wrapper });++ await user.click(screen.getAllByRole("button", { name: "Edit server" })[0]!);++ const nameInput = screen.getByLabelText("Name") as HTMLInputElement;+ expect(nameInput.value).toBe("linear");+ expect(nameInput).toHaveAttribute("readonly");++ // Even if something did change the field, the upsert targets the entry+ // that was opened.+ await user.type(screen.getByLabelText("Server URL"), "https://linear-v2.example");+ await user.click(screen.getByRole("button", { name: "Save Changes" }));++ await waitFor(() =>+ expect(mockUpsert).toHaveBeenCalledWith(+ expect.objectContaining({ name: "linear" }),+ ),+ );+ expect(mockUpsert).toHaveBeenCalledTimes(1);+ });++ // The saved entry cannot be read back, but the safe summary still knows the+ // transport — so the empty form must open on the right one instead of+ // defaulting a stdio server to HTTP.+ it("opens the edit form on the server's own transport", async () => {+ const user = userEvent.setup();+ render(<McpTab />, { wrapper: Wrapper });++ // Row 1 is the stdio server.+ await user.click(screen.getAllByRole("button", { name: "Edit server" })[1]!);++ expect(screen.getByRole("button", { name: "STDIO" })).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ expect(screen.getByLabelText("Command")).toBeInTheDocument();+ });++ // Regression: the guided form only speaks stdio/http and REWRITES the entry+ // on save (`type: "http"`), so editing an SSE server through it would change+ // its protocol and can break the server. The server returns `sse`, so this is+ // reachable, not hypothetical — those entries take the JSON path instead.+ it.each(["sse", "websocket"])(+ "edits a %s server through JSON, never the transport-rewriting form",+ async (transport) => {+ const user = userEvent.setup();+ data.config = {+ workspace_id: "workspace-1",+ servers: [{ name: "streamy", transport, enabled: true }],+ server_count: 1,+ };+ render(<McpTab />, { wrapper: Wrapper });++ await user.click(screen.getByRole("button", { name: "Edit server" }));++ expect(screen.getByRole("tab", { name: "JSON" })).toHaveAttribute(+ "aria-selected",+ "true",+ );+ // Not merely unselected: switching to the form would rewrite the entry.+ expect(screen.getByRole("tab", { name: "Form" })).toHaveAttribute(+ "aria-disabled",+ "true",+ );+ expect(screen.queryByLabelText("Server URL")).toBeNull();+ },+ );++ it("removes a server after confirmation", async () => {+ const user = userEvent.setup();+ render(<McpTab />, { wrapper: Wrapper });++ await user.click(screen.getAllByRole("button", { name: "Remove server" })[0]!);+ await user.click(screen.getByRole("button", { name: "Remove" }));++ await waitFor(() => expect(mockDelete).toHaveBeenCalledWith("linear"));+ });++ it("hides every write affordance from a plain member", () => {+ data.role = "member";+ render(<McpTab />, { wrapper: Wrapper });++ // The inventory itself stays visible — it carries no credential material.+ expect(screen.getByText("linear")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /Add server/ })).toBeNull();+ expect(screen.queryByRole("button", { name: "Edit server" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Remove server" })).toBeNull();+ expect(+ screen.getByText(/Only workspace owners and admins/),+ ).toBeInTheDocument();+ });++ it("renders an empty state when the workspace shares nothing", () => {+ data.config = { workspace_id: "workspace-1", servers: [], server_count: 0 };+ render(<McpTab />, { wrapper: Wrapper });++ expect(screen.getByText("No shared MCP servers")).toBeInTheDocument();+ });++ // The document is write-only, so the screen must never imply it is showing+ // a saved configuration: it says an edit replaces the entry.+ it("states that saved configurations are write-only", () => {+ render(<McpTab />, { wrapper: Wrapper });++ expect(screen.getByText(/write-only/)).toBeInTheDocument();+ });++ it("survives a server payload with no servers array", () => {+ // Backend drift: the schema defaults `servers` to [], but the component+ // must not crash if it ever arrives undefined.+ data.config = { workspace_id: "workspace-1" } as typeof data.config;+ render(<McpTab />, { wrapper: Wrapper });++ expect(screen.getByText("No shared MCP servers")).toBeInTheDocument();+ });+});diff --git a/packages/views/settings/components/mcp-tab.tsx b/packages/views/settings/components/mcp-tab.tsxnew file mode 100644index 0000000000..5463a75857--- /dev/null+++ b/packages/views/settings/components/mcp-tab.tsx@@ -0,0 +1,297 @@+"use client";++import { useMemo, useState } from "react";+import { Loader2, Pencil, Plus, Server, Trash2 } from "lucide-react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+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 { useCurrentWorkspace } from "@multica/core/paths";+import { useCurrentMember } from "@multica/core/permissions";+import { workspaceMcpConfigOptions } from "@multica/core/workspace/queries";+import {+ useDeleteWorkspaceMcpServer,+ useUpsertWorkspaceMcpServer,+} from "@multica/core/workspace/mutations";+import type { WorkspaceMcpServer } from "@multica/core/types";+import { McpServerDialog } from "../../agents/components/tabs/mcp-server-dialog";+import type { ManagedMcpServer } from "../../agents/components/tabs/mcp-config-model";+import { useT } from "../../i18n";+import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";++/**+ * Workspace-level MCP servers (GH #6062).+ *+ * Two things shape this screen and are worth stating up front:+ *+ * - The stored configuration is WRITE-ONLY. The API returns names and+ * transports, never urls / commands / headers / env, so there is no+ * "current value" to prefill and editing a server means supplying its+ * configuration again. The UI says so rather than pretending the empty+ * form is the saved state.+ * - Because the client cannot read the document, it cannot do the+ * read-modify-write the agent tab does. Each row maps to a per-server+ * endpoint and the server merges under a row lock.+ */+export function McpTab() {+ const { t } = useT("settings");+ const workspace = useCurrentWorkspace();+ const wsId = workspace?.id ?? "";+ const currentMember = useCurrentMember(wsId);+ const canManage =+ currentMember.role === "owner" || currentMember.role === "admin";++ const configQuery = useQuery(workspaceMcpConfigOptions(wsId));+ const upsertServer = useUpsertWorkspaceMcpServer(wsId);+ const deleteServer = useDeleteWorkspaceMcpServer(wsId);++ const servers = configQuery.data?.servers ?? [];+ const existingNames = useMemo(+ () => new Set(servers.map((server) => server.name)),+ [servers],+ );++ const [editorOpen, setEditorOpen] = useState(false);+ const [editingServer, setEditingServer] = useState<WorkspaceMcpServer | null>(+ null,+ );+ const [deletingName, setDeletingName] = useState<string | null>(null);++ // The dialog is shared with the agent MCP tab, which hands it the saved+ // entry to prefill. Here there is nothing to prefill — an edit always+ // starts from an empty form and REPLACES the entry. The transport still+ // comes from the safe summary so the form opens on the right one.+ const dialogServer: ManagedMcpServer | null = editingServer+ ? {+ name: editingServer.name,+ config: {},+ container: "mcpServers",+ transport: editingServer.transport,+ enabled: editingServer.enabled,+ }+ : null;++ const handleSaveServer = async (+ name: string,+ config: Record<string, unknown>,+ ) => {+ // The name is pinned while editing (see lockName below), so an edit can+ // only ever replace the entry it opened — never create a second one and+ // leave the original behind while reporting "updated".+ const targetName = editingServer ? editingServer.name : name;+ try {+ await upsertServer.mutateAsync({ name: targetName, entry: config });+ toast.success(+ editingServer+ ? t(($) => $.mcp.updated_toast)+ : t(($) => $.mcp.added_toast),+ );+ } catch (error) {+ toast.error(+ error instanceof Error && error.message+ ? error.message+ : t(($) => $.mcp.save_failed_toast),+ );+ throw error;+ }+ };++ const handleDelete = async () => {+ if (!deletingName) return;+ try {+ await deleteServer.mutateAsync(deletingName);+ toast.success(t(($) => $.mcp.removed_toast));+ setDeletingName(null);+ } catch (error) {+ toast.error(+ error instanceof Error && error.message+ ? error.message+ : t(($) => $.mcp.remove_failed_toast),+ );+ }+ };++ return (+ <SettingsTab+ title={t(($) => $.mcp.title)}+ description={t(($) => $.mcp.description)}+ >+ <SettingsSection+ title={t(($) => $.mcp.servers_title)}+ description={t(($) => $.mcp.write_only_note)}+ action={+ canManage ? (+ <Button+ size="sm"+ onClick={() => {+ setEditingServer(null);+ setEditorOpen(true);+ }}+ >+ <Plus className="h-4 w-4" />+ {t(($) => $.mcp.add_server)}+ </Button>+ ) : null+ }+ >+ <SettingsCard>+ {configQuery.isLoading ? (+ <div className="flex items-center justify-center py-8 text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" />+ </div>+ ) : servers.length === 0 ? (+ <div className="px-4 py-8 text-center">+ <Server className="mx-auto h-5 w-5 text-muted-foreground" />+ <p className="mt-3 text-body font-medium">+ {t(($) => $.mcp.empty_title)}+ </p>+ <p className="mx-auto mt-1 max-w-md text-caption leading-5 text-muted-foreground">+ {t(($) => $.mcp.empty_description)}+ </p>+ </div>+ ) : (+ <ul className="divide-y divide-surface-border">+ {servers.map((server) => (+ <McpServerRow+ key={server.name}+ server={server}+ canManage={canManage}+ onEdit={() => {+ setEditingServer(server);+ setEditorOpen(true);+ }}+ onDelete={() => setDeletingName(server.name)}+ />+ ))}+ </ul>+ )}+ </SettingsCard>+ {!canManage && !currentMember.isLoading ? (+ <p className="px-0.5 text-caption text-muted-foreground">+ {t(($) => $.mcp.admin_only_note)}+ </p>+ ) : null}+ </SettingsSection>++ <McpServerDialog+ open={editorOpen}+ server={dialogServer}+ existingNames={existingNames}+ // No atomic rename exists on this API: renaming would add a server+ // and orphan the old one, so editing pins the name.+ lockName={editingServer !== null}+ onOpenChange={setEditorOpen}+ onSave={handleSaveServer}+ />++ <AlertDialog+ open={deletingName !== null}+ onOpenChange={(open) => {+ if (!open) setDeletingName(null);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.mcp.delete_title)}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $.mcp.delete_description, { name: deletingName ?? "" })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={deleteServer.isPending}>+ {t(($) => $.mcp.cancel)}+ </AlertDialogCancel>+ <AlertDialogAction+ onClick={(event) => {+ event.preventDefault();+ void handleDelete();+ }}+ disabled={deleteServer.isPending}+ >+ {deleteServer.isPending ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : null}+ {t(($) => $.mcp.delete_confirm)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </SettingsTab>+ );+}++function McpServerRow({+ server,+ canManage,+ onEdit,+ onDelete,+}: {+ server: WorkspaceMcpServer;+ canManage: boolean;+ onEdit: () => void;+ onDelete: () => void;+}) {+ const { t } = useT("settings");+ return (+ <li className="flex items-center gap-3 px-4 py-3">+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2">+ <span className="truncate text-body font-medium">{server.name}</span>+ {server.enabled === false ? (+ <Badge variant="secondary">{t(($) => $.mcp.disabled_badge)}</Badge>+ ) : null}+ </div>+ <p className="mt-0.5 text-caption text-muted-foreground">+ {transportLabel(server.transport)}+ </p>+ </div>+ {canManage ? (+ <div className="flex shrink-0 items-center gap-1">+ <Button+ variant="ghost"+ size="icon"+ onClick={onEdit}+ aria-label={t(($) => $.mcp.edit_server)}+ >+ <Pencil className="h-4 w-4" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onClick={onDelete}+ aria-label={t(($) => $.mcp.remove_server)}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>+ ) : null}+ </li>+ );+}++/**+ * `transport` is a server-driven string, so an unknown value from a newer+ * backend renders as itself instead of disappearing.+ */+function transportLabel(transport: string): string {+ switch (transport) {+ case "stdio":+ return "stdio";+ case "http":+ return "HTTP";+ case "sse":+ return "SSE";+ default:+ return transport || "unknown";+ }+}diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex dc5b5c063d..640abdf9a4 100644--- a/packages/views/settings/components/settings-page.tsx+++ b/packages/views/settings/components/settings-page.tsx@@ -18,6 +18,7 @@ import {Zap,Blocks,CreditCard,+ Server,} from "lucide-react";import { GitHubMark } from "./github-mark";import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";@@ -46,6 +47,7 @@ import { PropertiesTab } from "./properties-tab";import { QuickActionsTab } from "./quick-actions-tab";import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";import { PluginsTab } from "./plugins-tab";+import { McpTab } from "./mcp-tab";import { BillingTab } from "./billing-tab";import { CollapsedNavTrigger } from "../../layout/page-header";import { useT } from "../../i18n";@@ -72,6 +74,7 @@ const WORKSPACE_TAB_KEYS = ["labels","properties","quick_actions",+ "mcp","plugins",] as const;const WORKSPACE_TAB_VALUES = {@@ -85,6 +88,7 @@ const WORKSPACE_TAB_VALUES = {labels: "labels",properties: "properties",quick_actions: "quick-actions",+ mcp: "mcp",plugins: "plugins",} as const;const WORKSPACE_TAB_ICONS = {@@ -98,6 +102,7 @@ const WORKSPACE_TAB_ICONS = {labels: Tags,properties: SlidersHorizontal,quick_actions: Zap,+ mcp: Server,plugins: Blocks,} as const;@@ -276,6 +281,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {<TabsContent value="labels"><LabelsTab /></TabsContent><TabsContent value="properties"><PropertiesTab /></TabsContent><TabsContent value="quick-actions"><QuickActionsTab /></TabsContent>+ <TabsContent value="mcp"><McpTab /></TabsContent>{pluginsEnabled ? <TabsContent value="plugins"><PluginsTab /></TabsContent> : null}{extraAccountTabs?.map((tab) => (<TabsContent key={tab.value} value={tab.value}>{tab.content}</TabsContent>diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex 012b3f4588..ca31ae6d8f 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -1300,50 +1300,77 @@ func resolveCustomEnv(cmd *cobra.Command) (map[string]string, bool, error) {// parseMcpConfig validates the --mcp-config value and returns the raw JSON to// send. It accepts a JSON object (the MCP config, e.g. {"mcpServers": {…}}) or-// the literal `null` to clear the agent's config. A top-level array or-// primitive is rejected because it can never be a valid MCP config — this-// mirrors the agent-settings UI (mcp-config-tab.tsx). Empty/whitespace input-// is rejected rather than treated as a clear: for the stdin/file channels it-// almost always signals an upstream failure (missing file, unset pipe) rather-// than a deliberate clear, and silently wiping a secret-bearing field is the-// wrong default — pass an explicit `null` to clear.+// the literal `null` to clear the agent's config.+func parseMcpConfig(raw string) (json.RawMessage, error) {+ return parseMcpJSONObject("--mcp-config", raw, true)+}++// parseMcpJSONObject validates a JSON-object payload supplied through one of+// the secret-safe flag channels. A top-level array or primitive is rejected+// because it can never be a valid MCP payload — this mirrors the agent-settings+// UI (mcp-config-tab.tsx). Empty/whitespace input is rejected rather than+// treated as a clear: for the stdin/file channels it almost always signals an+// upstream failure (missing file, unset pipe) rather than a deliberate clear,+// and silently wiping a secret-bearing field is the wrong default.+//+// allowNull controls whether the literal `null` is accepted as the clear+// sentinel. It is not for a single server entry, where removing something has+// its own command and `null` is far more likely to be a mistake.//// The payload is treated as secret material (MCP entries routinely carry API// tokens), so parse errors never wrap the underlying json error, which can// echo short fragments of malformed input.-func parseMcpConfig(raw string) (json.RawMessage, error) {+func parseMcpJSONObject(flag, raw string, allowNull bool) (json.RawMessage, error) {trimmed := strings.TrimSpace(raw)if trimmed == "" {- return nil, fmt.Errorf("--mcp-config: empty input; pass 'null' to clear or a JSON object to set")+ if allowNull {+ return nil, fmt.Errorf("%s: empty input; pass 'null' to clear or a JSON object to set", flag)+ }+ return nil, fmt.Errorf("%s: empty input; pass a JSON object", flag)}var probe anyif err := json.Unmarshal([]byte(trimmed), &probe); err != nil {- return nil, fmt.Errorf("--mcp-config must be a valid JSON object, or 'null' to clear")+ if allowNull {+ return nil, fmt.Errorf("%s must be a valid JSON object, or 'null' to clear", flag)+ }+ return nil, fmt.Errorf("%s must be a valid JSON object", flag)}- // null → clear (NULL column server-side; on create it is a no-op).if probe == nil {- return json.RawMessage("null"), nil+ if allowNull {+ // null → clear (NULL column server-side; on create it is a no-op).+ return json.RawMessage("null"), nil+ }+ return nil, fmt.Errorf("%s must be a JSON object, not null", flag)}if _, ok := probe.(map[string]any); !ok {- return nil, fmt.Errorf("--mcp-config must be a JSON object, or 'null' to clear")+ if allowNull {+ return nil, fmt.Errorf("%s must be a JSON object, or 'null' to clear", flag)+ }+ return nil, fmt.Errorf("%s must be a JSON object", flag)}return json.RawMessage(trimmed), nil}// resolveMcpConfig collects the --mcp-config, --mcp-config-stdin, and// --mcp-config-file flags and returns the raw JSON value to send, a bool-// indicating whether the caller supplied any of them, and any error. The-// three input channels are mutually exclusive so callers can't accidentally-// provide a secret twice. Stdin and file inputs exist to keep mcp_config —-// which routinely embeds API tokens — out of shell history and 'ps'. Mirrors+// indicating whether the caller supplied any of them, and any error. Mirrors// resolveCustomEnv; the only behavioural difference is the clear sentinel// (`null` here vs `{}` for custom_env), because mcp_config distinguishes an// explicit empty object from an absent config server-side.func resolveMcpConfig(cmd *cobra.Command) (json.RawMessage, bool, error) {- inline := cmd.Flags().Changed("mcp-config")- fromStdin, _ := cmd.Flags().GetBool("mcp-config-stdin")- filePath, _ := cmd.Flags().GetString("mcp-config-file")- fromFile := cmd.Flags().Changed("mcp-config-file")+ return resolveMcpJSONObject(cmd, "mcp-config", true)+}++// resolveMcpJSONObject collects the `<prefix>`, `<prefix>-stdin`, and+// `<prefix>-file` flags. The three input channels are mutually exclusive so+// callers can't accidentally provide a secret twice. Stdin and file inputs+// exist to keep payloads — which routinely embed API tokens — out of shell+// history and 'ps'.+func resolveMcpJSONObject(cmd *cobra.Command, prefix string, allowNull bool) (json.RawMessage, bool, error) {+ inline := cmd.Flags().Changed(prefix)+ fromStdin, _ := cmd.Flags().GetBool(prefix + "-stdin")+ filePath, _ := cmd.Flags().GetString(prefix + "-file")+ fromFile := cmd.Flags().Changed(prefix + "-file")count := 0if inline {@@ -1359,39 +1386,43 @@ func resolveMcpConfig(cmd *cobra.Command) (json.RawMessage, bool, error) {case count == 0:return nil, false, nilcase count > 1:- return nil, false, fmt.Errorf("--mcp-config, --mcp-config-stdin, and --mcp-config-file are mutually exclusive; pick one")+ return nil, false, fmt.Errorf("--%s, --%s-stdin, and --%s-file are mutually exclusive; pick one", prefix, prefix, prefix)}+ clearHint := ""+ if allowNull {+ clearHint = "; pass 'null' to clear"+ }var raw stringswitch {case inline:- raw, _ = cmd.Flags().GetString("mcp-config")+ raw, _ = cmd.Flags().GetString(prefix)case fromStdin:buf, err := io.ReadAll(cmd.InOrStdin())if err != nil {- return nil, false, fmt.Errorf("read --mcp-config-stdin: %w", err)+ return nil, false, fmt.Errorf("read --%s-stdin: %w", prefix, err)}raw = string(buf)if strings.TrimSpace(raw) == "" {- return nil, false, fmt.Errorf("--mcp-config-stdin: empty input; pass 'null' to clear")+ return nil, false, fmt.Errorf("--%s-stdin: empty input%s", prefix, clearHint)}case fromFile:if filePath == "" {- return nil, false, fmt.Errorf("--mcp-config-file: path must not be empty")+ return nil, false, fmt.Errorf("--%s-file: path must not be empty", prefix)}buf, err := os.ReadFile(filePath)if err != nil {// Filesystem errors may include the path but not the contents —// safe to surface via %w.- return nil, false, fmt.Errorf("read --mcp-config-file: %w", err)+ return nil, false, fmt.Errorf("read --%s-file: %w", prefix, err)}raw = string(buf)if strings.TrimSpace(raw) == "" {- return nil, false, fmt.Errorf("--mcp-config-file %q: empty contents; pass 'null' to clear", filePath)+ return nil, false, fmt.Errorf("--%s-file %q: empty contents%s", prefix, filePath, clearHint)}}- mc, err := parseMcpConfig(raw)+ mc, err := parseMcpJSONObject("--"+prefix, raw, allowNull)if err != nil {return nil, false, err}diff --git a/server/cmd/multica/cmd_workspace.go b/server/cmd/multica/cmd_workspace.goindex eebde81f22..e12bceab5f 100644--- a/server/cmd/multica/cmd_workspace.go+++ b/server/cmd/multica/cmd_workspace.go@@ -3,6 +3,7 @@ package mainimport ("context""fmt"+ "net/url""os""strings""text/tabwriter"@@ -98,6 +99,69 @@ var workspaceSwitchCmd = &cobra.Command{RunE: runWorkspaceSwitch,}+var workspaceMcpCmd = &cobra.Command{+ Use: "mcp",+ Short: "Manage the workspace's shared MCP configuration",+ Long: "Manages the MCP servers shared by every agent in the workspace. An " ++ "agent that has no mcp_config of its own inherits them; an agent with " ++ "its own config merges on top, winning on server-name collisions; an " ++ "agent whose mcp_config declares no servers inherits none of them (its " ++ "runtime's own local servers still apply).\n\n" ++ "The stored configuration is write-only: reads return the server names " ++ "and transports, never the urls, commands, headers, or env. Use 'add' / " ++ "'remove' to change one server without holding the whole document.",+}++var workspaceMcpGetCmd = &cobra.Command{+ Use: "get [workspace-id|slug|prefix]",+ Short: "List the MCP servers shared by the workspace",+ Long: "Lists the shared MCP servers by name and transport. The stored " ++ "configuration itself is write-only and is never returned — to anyone, " ++ "including owners — because MCP entries routinely embed API tokens and a " ++ "session URL is a credential on its own. Keep the source document " ++ "wherever you manage secrets, and use 'set' / 'add' to push changes.",+ Args: cobra.MaximumNArgs(1),+ RunE: runWorkspaceMcpGet,+}++var workspaceMcpSetCmd = &cobra.Command{+ Use: "set [workspace-id|slug|prefix]",+ Short: "Replace the workspace's shared MCP configuration (admin/owner only)",+ Long: "Replaces the whole shared MCP document — it is not merged with what is " ++ "already stored, so removing a server means sending the document without " ++ "it. Pass 'null' to clear the workspace layer entirely.\n\n" ++ "Prefer --mcp-config-file or --mcp-config-stdin: MCP entries routinely " ++ "carry API tokens, and an inline value ends up in shell history and 'ps'.",+ Example: " multica workspace mcp set --mcp-config-file ./mcp.json\n" ++ " multica workspace mcp set --mcp-config null",+ Args: cobra.MaximumNArgs(1),+ RunE: runWorkspaceMcpSet,+}++var workspaceMcpAddCmd = &cobra.Command{+ Use: "add <server-name> [workspace-id|slug|prefix]",+ Short: "Add or replace one shared MCP server (admin/owner only)",+ Long: "Adds a shared MCP server, or replaces one that already has this name. " ++ "The other shared servers are left alone, so this is the incremental " ++ "counterpart to 'set' — and the only way to edit one server without " ++ "holding the whole document, which the API never returns.\n\n" ++ "The payload is a single server entry, the same object shape that sits " ++ "under a name in \"mcpServers\".",+ Example: " multica workspace mcp add linear --server-config-file ./linear.json\n" ++ " echo '{\"url\":\"https://mcp.example\"}' | multica workspace mcp add example --server-config-stdin",+ Args: cobra.RangeArgs(1, 2),+ RunE: runWorkspaceMcpAdd,+}++var workspaceMcpRemoveCmd = &cobra.Command{+ Use: "remove <server-name> [workspace-id|slug|prefix]",+ Short: "Remove one shared MCP server (admin/owner only)",+ Long: "Removes a shared MCP server by name. Removing the last one clears the " ++ "workspace layer entirely, so agents fall back to their own configuration.",+ Args: cobra.RangeArgs(1, 2),+ RunE: runWorkspaceMcpRemove,+}+func init() {workspaceCmd.AddCommand(workspaceListCmd)workspaceCmd.AddCommand(workspaceCreateCmd)@@ -107,6 +171,11 @@ func init() {workspaceMemberCmd.AddCommand(workspaceMemberInviteCmd)workspaceCmd.AddCommand(workspaceUpdateCmd)workspaceCmd.AddCommand(workspaceSwitchCmd)+ workspaceCmd.AddCommand(workspaceMcpCmd)+ workspaceMcpCmd.AddCommand(workspaceMcpGetCmd)+ workspaceMcpCmd.AddCommand(workspaceMcpSetCmd)+ workspaceMcpCmd.AddCommand(workspaceMcpAddCmd)+ workspaceMcpCmd.AddCommand(workspaceMcpRemoveCmd)workspaceListCmd.Flags().String("output", "table", "Output format: table or json")workspaceListCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")@@ -130,6 +199,20 @@ func init() {workspaceUpdateCmd.Flags().Bool("context-stdin", false, "Read context from stdin (preserves multi-line content verbatim)")workspaceUpdateCmd.Flags().String("issue-prefix", "", "New issue prefix (uppercased server-side)")workspaceUpdateCmd.Flags().String("output", "json", "Output format: table or json")++ workspaceMcpGetCmd.Flags().String("output", "json", "Output format: table or json")+ // Same three mutually-exclusive input channels as `agent update`, resolved+ // by the shared resolveMcpConfig so both surfaces agree on what a valid+ // document is and on 'null' meaning clear.+ workspaceMcpSetCmd.Flags().String("mcp-config", "", "MCP configuration as JSON, or 'null' to clear (avoid: lands in shell history)")+ workspaceMcpSetCmd.Flags().Bool("mcp-config-stdin", false, "Read the MCP configuration JSON from stdin")+ workspaceMcpSetCmd.Flags().String("mcp-config-file", "", "Read the MCP configuration JSON from a file")+ workspaceMcpSetCmd.Flags().String("output", "json", "Output format: table or json")+ workspaceMcpAddCmd.Flags().String("server-config", "", "Server entry as JSON (avoid: lands in shell history)")+ workspaceMcpAddCmd.Flags().Bool("server-config-stdin", false, "Read the server entry JSON from stdin")+ workspaceMcpAddCmd.Flags().String("server-config-file", "", "Read the server entry JSON from a file")+ workspaceMcpAddCmd.Flags().String("output", "json", "Output format: table or json")+ workspaceMcpRemoveCmd.Flags().String("output", "json", "Output format: table or json")}// workspaceSummary is the subset of fields the CLI needs from /api/workspaces@@ -524,6 +607,176 @@ func runWorkspaceUpdate(cmd *cobra.Command, args []string) error {return printWorkspace(cmd, ws)}+func runWorkspaceMcpGet(cmd *cobra.Command, args []string) error {+ wsID, err := resolveWorkspaceArg(cmd, args)+ if err != nil {+ return err+ }+ if wsID == "" {+ return fmt.Errorf("workspace ID is required: pass an id/slug/prefix as argument or set MULTICA_WORKSPACE_ID")+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var resp workspaceMcpInventory+ if err := client.GetJSON(ctx, "/api/workspaces/"+wsID+"/mcp-config", &resp); err != nil {+ return fmt.Errorf("get workspace mcp config: %w", err)+ }++ return printWorkspaceMcpConfig(cmd, resp)+}++func runWorkspaceMcpSet(cmd *cobra.Command, args []string) error {+ wsID, err := resolveWorkspaceArg(cmd, args)+ if err != nil {+ return err+ }+ if wsID == "" {+ return fmt.Errorf("workspace ID is required: pass an id/slug/prefix as argument or set MULTICA_WORKSPACE_ID")+ }++ mcpConfig, ok, err := resolveMcpConfig(cmd)+ if err != nil {+ return err+ }+ if !ok {+ return fmt.Errorf("one of --mcp-config, --mcp-config-stdin, or --mcp-config-file is required; pass 'null' to clear")+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var resp workspaceMcpInventory+ body := map[string]any{"mcp_config": mcpConfig}+ if err := client.PutJSON(ctx, "/api/workspaces/"+wsID+"/mcp-config", body, &resp); err != nil {+ return fmt.Errorf("set workspace mcp config: %w", err)+ }++ return printWorkspaceMcpConfig(cmd, resp)+}++func runWorkspaceMcpAdd(cmd *cobra.Command, args []string) error {+ serverName := strings.TrimSpace(args[0])+ if serverName == "" {+ return fmt.Errorf("server name must not be empty")+ }+ wsID, err := resolveWorkspaceArg(cmd, args[1:])+ if err != nil {+ return err+ }+ if wsID == "" {+ return fmt.Errorf("workspace ID is required: pass an id/slug/prefix as argument or set MULTICA_WORKSPACE_ID")+ }++ entry, ok, err := resolveMcpJSONObject(cmd, "server-config", false)+ if err != nil {+ return err+ }+ if !ok {+ return fmt.Errorf("one of --server-config, --server-config-stdin, or --server-config-file is required")+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var resp workspaceMcpInventory+ path := "/api/workspaces/" + wsID + "/mcp-config/servers/" + url.PathEscape(serverName)+ if err := client.PutJSON(ctx, path, entry, &resp); err != nil {+ return fmt.Errorf("add workspace mcp server: %w", err)+ }++ return printWorkspaceMcpConfig(cmd, resp)+}++func runWorkspaceMcpRemove(cmd *cobra.Command, args []string) error {+ serverName := strings.TrimSpace(args[0])+ if serverName == "" {+ return fmt.Errorf("server name must not be empty")+ }+ wsID, err := resolveWorkspaceArg(cmd, args[1:])+ if err != nil {+ return err+ }+ if wsID == "" {+ return fmt.Errorf("workspace ID is required: pass an id/slug/prefix as argument or set MULTICA_WORKSPACE_ID")+ }++ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var resp workspaceMcpInventory+ path := "/api/workspaces/" + wsID + "/mcp-config/servers/" + url.PathEscape(serverName)+ if err := client.DeleteJSONResponse(ctx, path, &resp); err != nil {+ return fmt.Errorf("remove workspace mcp server: %w", err)+ }++ return printWorkspaceMcpConfig(cmd, resp)+}++// workspaceMcpInventory is the CLI's half of the write-only boundary. Decoding+// into named fields — rather than a map[string]any that gets re-encoded — means+// a server that regressed to returning the stored document, or a `url` /+// `headers` inside a server entry, cannot reach stdout through ANY output+// format. Fields not declared here are dropped by encoding/json.+type workspaceMcpInventory struct {+ WorkspaceID string `json:"workspace_id"`+ Servers []workspaceMcpInventoryRow `json:"servers"`+ ServerCount int `json:"server_count"`+}++type workspaceMcpInventoryRow struct {+ Name string `json:"name"`+ Transport string `json:"transport"`+ Enabled bool `json:"enabled"`+}++// printWorkspaceMcpConfig renders the shared MCP server inventory returned by+// every workspace-mcp command. There is no document to print in either format:+// the API never returns the stored configuration, and the type above is what+// guarantees this command cannot print one even if the API changed its mind.+func printWorkspaceMcpConfig(cmd *cobra.Command, resp workspaceMcpInventory) error {+ output, _ := cmd.Flags().GetString("output")+ if output != "table" {+ return cli.PrintJSON(os.Stdout, resp)+ }++ if len(resp.Servers) == 0 {+ fmt.Fprintln(os.Stdout, "no MCP servers shared by this workspace")+ return nil+ }+ rows := make([][]string, 0, len(resp.Servers))+ for _, server := range resp.Servers {+ status := "enabled"+ if !server.Enabled {+ status = "disabled"+ }+ rows = append(rows, []string{server.Name, server.Transport, status})+ }+ cli.PrintTable(os.Stdout, []string{"NAME", "TRANSPORT", "STATUS"}, rows)+ return nil+}+func runWorkspaceMembers(cmd *cobra.Command, args []string) error {wsID, err := resolveWorkspaceArg(cmd, args)if err != nil {diff --git a/server/cmd/multica/cmd_workspace_mcp_test.go b/server/cmd/multica/cmd_workspace_mcp_test.gonew file mode 100644index 0000000000..8ee9171857--- /dev/null+++ b/server/cmd/multica/cmd_workspace_mcp_test.go@@ -0,0 +1,445 @@+package main++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/spf13/cobra"+)++const testWorkspaceMcpID = "workspace-123"++func newWorkspaceMcpTestCmd(use string) *cobra.Command {+ cmd := &cobra.Command{Use: use}+ cmd.Flags().String("workspace-id", "", "")+ cmd.Flags().String("profile", "", "")+ cmd.Flags().String("server-url", "", "")+ cmd.Flags().String("output", "json", "")+ switch use {+ case "set":+ cmd.Flags().String("mcp-config", "", "")+ cmd.Flags().Bool("mcp-config-stdin", false, "")+ cmd.Flags().String("mcp-config-file", "", "")+ case "add":+ cmd.Flags().String("server-config", "", "")+ cmd.Flags().Bool("server-config-stdin", false, "")+ cmd.Flags().String("server-config-file", "", "")+ }+ return cmd+}++// inventoryResponse is what every workspace-mcp endpoint returns: names and+// transports, never the stored document.+func inventoryResponse(names ...string) map[string]any {+ servers := make([]map[string]any, 0, len(names))+ for _, name := range names {+ servers = append(servers, map[string]any{"name": name, "transport": "http", "enabled": true})+ }+ return map[string]any{+ "workspace_id": testWorkspaceMcpID,+ "servers": servers,+ "server_count": len(servers),+ }+}++func TestRunWorkspaceMcpGetListsInventory(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ var gotMethod, gotPath string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotMethod, gotPath = r.Method, r.URL.Path+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(inventoryResponse("linear"))+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newWorkspaceMcpTestCmd("get")+ _ = cmd.Flags().Set("output", "table")+ out, err := captureStdout(t, func() error { return runWorkspaceMcpGet(cmd, nil) })+ if err != nil {+ t.Fatalf("runWorkspaceMcpGet: %v", err)+ }++ if gotMethod != http.MethodGet {+ t.Fatalf("method = %s, want GET", gotMethod)+ }+ if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-config" {+ t.Fatalf("path = %q", gotPath)+ }+ if !strings.Contains(out, "linear") || !strings.Contains(out, "http") {+ t.Fatalf("table output missing the server row: %q", out)+ }+}++func TestRunWorkspaceMcpGetEmptyInventory(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(inventoryResponse())+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newWorkspaceMcpTestCmd("get")+ _ = cmd.Flags().Set("output", "table")+ out, err := captureStdout(t, func() error { return runWorkspaceMcpGet(cmd, nil) })+ if err != nil {+ t.Fatalf("runWorkspaceMcpGet: %v", err)+ }+ if !strings.Contains(out, "no MCP servers shared") {+ t.Fatalf("expected the empty-state line, got %q", out)+ }+}++// poisonedInventoryResponse is what a regressed (or hostile) server would send:+// the correct inventory PLUS the stored document at the top level and secret+// fields inside a server entry. Nothing from it may reach stdout, in ANY output+// format — the CLI decodes into a named struct precisely so it cannot.+func poisonedInventoryResponse() map[string]any {+ resp := inventoryResponse()+ resp["servers"] = []map[string]any{{+ "name": "linear",+ "transport": "http",+ "enabled": true,+ // Secret material smuggled inside the safe summary.+ "url": "https://mcp.example/sk-live-url-leak",+ "headers": map[string]any{"Authorization": "Bearer sk-live-header-leak"},+ "env": map[string]any{"TOKEN": "sk-live-env-leak"},+ }}+ resp["server_count"] = 1+ // Secret material smuggled at the top level.+ resp["mcp_config"] = map[string]any{+ "mcpServers": map[string]any{+ "linear": map[string]any{"headers": map[string]any{"Authorization": "Bearer sk-live-doc-leak"}},+ },+ }+ return resp+}++var workspaceMcpLeakMarkers = []string{+ "sk-live-url-leak",+ "sk-live-header-leak",+ "sk-live-env-leak",+ "sk-live-doc-leak",+ "mcp_config",+ "headers",+}++func TestRunWorkspaceMcpGetNeverPrintsSecrets(t *testing.T) {+ // Both output modes, because the JSON one is the DEFAULT: a renderer that+ // echoed the decoded response would leak there first.+ for _, output := range []string{"json", "table"} {+ t.Run(output, func(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(poisonedInventoryResponse())+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newWorkspaceMcpTestCmd("get")+ _ = cmd.Flags().Set("output", output)+ out, err := captureStdout(t, func() error { return runWorkspaceMcpGet(cmd, nil) })+ if err != nil {+ t.Fatalf("runWorkspaceMcpGet: %v", err)+ }++ for _, marker := range workspaceMcpLeakMarkers {+ if strings.Contains(out, marker) {+ t.Fatalf("%s output leaked %q: %q", output, marker, out)+ }+ }+ // The safe inventory still renders.+ if !strings.Contains(out, "linear") {+ t.Fatalf("%s output dropped the server name: %q", output, out)+ }+ })+ }+}++// The write paths render the same inventory, so they need the same guard —+// the response to a write is where a server is most likely to echo back what+// it just stored.+func TestRunWorkspaceMcpWritesNeverPrintSecrets(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(poisonedInventoryResponse())+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newWorkspaceMcpTestCmd("add")+ _ = cmd.Flags().Set("server-config", `{"url":"https://mcp.example"}`)+ out, err := captureStdout(t, func() error { return runWorkspaceMcpAdd(cmd, []string{"linear"}) })+ if err != nil {+ t.Fatalf("runWorkspaceMcpAdd: %v", err)+ }+ for _, marker := range workspaceMcpLeakMarkers {+ if strings.Contains(out, marker) {+ t.Fatalf("add output leaked %q: %q", marker, out)+ }+ }+}++func TestRunWorkspaceMcpSetSendsDocument(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ var gotMethod, gotPath string+ var gotBody map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotMethod, gotPath = r.Method, r.URL.Path+ if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {+ t.Fatalf("decode request body: %v", err)+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(inventoryResponse("linear"))+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ path := filepath.Join(t.TempDir(), "mcp.json")+ if err := os.WriteFile(path, []byte(`{"mcpServers":{"linear":{"url":"https://linear.example"}}}`), 0o600); err != nil {+ t.Fatalf("write config file: %v", err)+ }++ cmd := newWorkspaceMcpTestCmd("set")+ _ = cmd.Flags().Set("mcp-config-file", path)+ if _, err := captureStdout(t, func() error { return runWorkspaceMcpSet(cmd, nil) }); err != nil {+ t.Fatalf("runWorkspaceMcpSet: %v", err)+ }++ if gotMethod != http.MethodPut {+ t.Fatalf("method = %s, want PUT", gotMethod)+ }+ if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-config" {+ t.Fatalf("path = %q", gotPath)+ }+ doc, _ := gotBody["mcp_config"].(map[string]any)+ if doc == nil {+ t.Fatalf("body = %v, want the document under mcp_config", gotBody)+ }+ if _, ok := doc["mcpServers"]; !ok {+ t.Fatalf("mcp_config = %v, want the file contents", doc)+ }+}++func TestRunWorkspaceMcpSetNullClears(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ var rawBody string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var buf bytes.Buffer+ _, _ = buf.ReadFrom(r.Body)+ rawBody = buf.String()+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(inventoryResponse())+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newWorkspaceMcpTestCmd("set")+ _ = cmd.Flags().Set("mcp-config", "null")+ if _, err := captureStdout(t, func() error { return runWorkspaceMcpSet(cmd, nil) }); err != nil {+ t.Fatalf("runWorkspaceMcpSet: %v", err)+ }+ if !strings.Contains(rawBody, `"mcp_config":null`) {+ t.Fatalf("body = %q, want an explicit null to clear", rawBody)+ }+}++func TestRunWorkspaceMcpSetRequiresAnInputChannel(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ cmd := newWorkspaceMcpTestCmd("set")+ err := runWorkspaceMcpSet(cmd, nil)+ if err == nil || !strings.Contains(err.Error(), "--mcp-config") {+ t.Fatalf("error = %v, want it to name the required flags", err)+ }+}++func TestRunWorkspaceMcpSetRejectsMultipleInputChannels(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ cmd := newWorkspaceMcpTestCmd("set")+ _ = cmd.Flags().Set("mcp-config", "{}")+ _ = cmd.Flags().Set("mcp-config-file", "/tmp/does-not-matter.json")+ err := runWorkspaceMcpSet(cmd, nil)+ if err == nil || !strings.Contains(err.Error(), "mutually exclusive") {+ t.Fatalf("error = %v, want a mutual-exclusion error", err)+ }+}++func TestRunWorkspaceMcpAddUpsertsOneServer(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ var gotMethod, gotPath string+ var gotBody map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotMethod, gotPath = r.Method, r.URL.Path+ if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {+ t.Fatalf("decode request body: %v", err)+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(inventoryResponse("linear"))+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newWorkspaceMcpTestCmd("add")+ _ = cmd.Flags().Set("server-config", `{"url":"https://linear.example"}`)+ if _, err := captureStdout(t, func() error { return runWorkspaceMcpAdd(cmd, []string{"linear"}) }); err != nil {+ t.Fatalf("runWorkspaceMcpAdd: %v", err)+ }++ if gotMethod != http.MethodPut {+ t.Fatalf("method = %s, want PUT", gotMethod)+ }+ if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-config/servers/linear" {+ t.Fatalf("path = %q", gotPath)+ }+ // The entry is sent as the whole body — not wrapped in mcp_config, and not+ // wrapped in an mcpServers envelope.+ if gotBody["url"] != "https://linear.example" {+ t.Fatalf("body = %v, want the bare server entry", gotBody)+ }+}++// A server name is a path segment: anything needing escaping must survive.+func TestRunWorkspaceMcpAddEscapesServerName(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ var gotPath string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotPath = r.URL.Path+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(inventoryResponse("my server"))+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newWorkspaceMcpTestCmd("add")+ _ = cmd.Flags().Set("server-config", `{"url":"https://x.example"}`)+ if _, err := captureStdout(t, func() error { return runWorkspaceMcpAdd(cmd, []string{"my server"}) }); err != nil {+ t.Fatalf("runWorkspaceMcpAdd: %v", err)+ }+ // net/http decodes the escaped segment back before it reaches the handler.+ if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-config/servers/my server" {+ t.Fatalf("path = %q, want the name preserved through escaping", gotPath)+ }+}++// `null` clears the whole layer, which is `set`'s job — for a single entry it+// is far more likely to be a mistake, so it is rejected rather than obeyed.+func TestRunWorkspaceMcpAddRejectsNullEntry(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ cmd := newWorkspaceMcpTestCmd("add")+ _ = cmd.Flags().Set("server-config", "null")+ if err := runWorkspaceMcpAdd(cmd, []string{"linear"}); err == nil {+ t.Fatal("expected 'null' to be rejected for a single server entry")+ }++ cmd = newWorkspaceMcpTestCmd("add")+ _ = cmd.Flags().Set("server-config", `["not-an-object"]`)+ if err := runWorkspaceMcpAdd(cmd, []string{"linear"}); err == nil {+ t.Fatal("expected a non-object entry to be rejected")+ }+}++func TestRunWorkspaceMcpAddRequiresAnInputChannel(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ cmd := newWorkspaceMcpTestCmd("add")+ err := runWorkspaceMcpAdd(cmd, []string{"linear"})+ if err == nil || !strings.Contains(err.Error(), "--server-config") {+ t.Fatalf("error = %v, want it to name the required flags", err)+ }+}++func TestRunWorkspaceMcpRemoveDeletesOneServer(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)++ var gotMethod, gotPath string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotMethod, gotPath = r.Method, r.URL.Path+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(inventoryResponse())+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newWorkspaceMcpTestCmd("remove")+ if _, err := captureStdout(t, func() error { return runWorkspaceMcpRemove(cmd, []string{"linear"}) }); err != nil {+ t.Fatalf("runWorkspaceMcpRemove: %v", err)+ }++ if gotMethod != http.MethodDelete {+ t.Fatalf("method = %s, want DELETE", gotMethod)+ }+ if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-config/servers/linear" {+ t.Fatalf("path = %q", gotPath)+ }+}++// The positional workspace argument is honoured on every subcommand, so an+// admin can target a workspace that is not their profile default.+func TestRunWorkspaceMcpUsesWorkspaceArgument(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")++ const wsUUID = "11111111-1111-1111-1111-111111111111"+ var gotPath string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotPath = r.URL.Path+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(inventoryResponse())+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := newWorkspaceMcpTestCmd("remove")+ if _, err := captureStdout(t, func() error { return runWorkspaceMcpRemove(cmd, []string{"linear", wsUUID}) }); err != nil {+ t.Fatalf("runWorkspaceMcpRemove: %v", err)+ }+ if gotPath != "/api/workspaces/"+wsUUID+"/mcp-config/servers/linear" {+ t.Fatalf("path = %q, want the positional workspace to win", gotPath)+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 90bc2ae1f0..ca5fcc2449 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1160,6 +1160,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// are admin-gated below).r.Get("/runtime-profiles", h.ListRuntimeProfiles)r.Get("/runtime-profiles/{profileId}", h.GetRuntimeProfile)+ // Shared MCP configuration — member-visible so the agent+ // settings UI can show what an agent inherits; the handler+ // redacts the document itself for everyone who cannot+ // write it (and for agent actors unconditionally).+ r.Get("/mcp-config", h.GetWorkspaceMcpConfig)r.Get("/plugins", h.ListPlugins)r.Get("/plugins/private", h.ListPrivatePlugins)r.Get("/plugins/private/{pluginRef}", h.GetPrivatePluginStatus)@@ -1177,6 +1182,14 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Delete("/", h.DeleteMember)})r.Delete("/invitations/{invitationId}", h.RevokeInvitation)+ // Writing shared MCP servers is an admin action: the+ // document reaches every agent in the workspace. The+ // whole-document PUT is the declarative path (CLI); the+ // per-server routes are what the settings UI uses, since+ // the document is never echoed back for it to edit.+ r.Put("/mcp-config", h.UpdateWorkspaceMcpConfig)+ r.Put("/mcp-config/servers/{serverName}", h.UpsertWorkspaceMcpServer)+ r.Delete("/mcp-config/servers/{serverName}", h.DeleteWorkspaceMcpServer)// Custom runtime profile mutations (admin-only).r.Post("/runtime-profiles", h.CreateRuntimeProfile)r.Patch("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)diff --git a/server/internal/daemon/runtime_mcp_workspace_test.go b/server/internal/daemon/runtime_mcp_workspace_test.gonew file mode 100644index 0000000000..953fed8454--- /dev/null+++ b/server/internal/daemon/runtime_mcp_workspace_test.go@@ -0,0 +1,107 @@+package daemon++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/multica-ai/multica/server/internal/handler"+)++// effectiveServerNames runs the full chain a claimed task actually goes+// through — the server's workspace/agent resolution followed by this daemon's+// runtime merge — and returns the server set the provider would end up with.+//+// Testing the two halves separately is not enough: they agree on the wire+// shape only if the resolver emits its result in the container this merge+// reads, and that coupling is exactly what regressed OpenCode agents.+func effectiveServerNames(t *testing.T, provider, workspaceCfg, agentCfg string) map[string]any {+ t.Helper()++ resolved, err := handler.ResolveWorkspaceMcpConfig(json.RawMessage(workspaceCfg), json.RawMessage(agentCfg))+ if err != nil {+ t.Fatalf("ResolveWorkspaceMcpConfig: %v", err)+ }+ merged, err := mergeRuntimeAndAgentMcpConfig(provider, resolved)+ if err != nil {+ t.Fatalf("mergeRuntimeAndAgentMcpConfig: %v", err)+ }+ if len(merged) == 0 {+ return nil+ }+ var doc struct {+ McpServers map[string]any `json:"mcpServers"`+ }+ if err := json.Unmarshal(merged, &doc); err != nil {+ t.Fatalf("unmarshal merged document %s: %v", merged, err)+ }+ return doc.McpServers+}++func writeOpencodeRuntimeConfig(t *testing.T, servers string) {+ t.Helper()++ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("XDG_CONFIG_HOME", "")+ dir := filepath.Join(home, ".config", "opencode")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatalf("create opencode config dir: %v", err)+ }+ if err := os.WriteFile(filepath.Join(dir, "opencode.json"), []byte(`{"mcp":`+servers+`}`), 0o600); err != nil {+ t.Fatalf("write opencode config: %v", err)+ }+}++// An OpenCode agent that stored its servers under the legacy top-level `mcp`+// container must keep them once the workspace starts sharing servers. The+// daemon's merge only falls back to `mcp` when `mcpServers` is ABSENT, so a+// resolver that wrote shared servers into `mcpServers` and left the agent's+// entries beside them would silently drop every private server.+func TestWorkspaceResolveThenRuntimeMergeKeepsLegacyOpencodeServers(t *testing.T) {+ writeOpencodeRuntimeConfig(t, `{"runtime-local":{"command":"runtime-server"}}`)++ servers := effectiveServerNames(t, "opencode",+ `{"mcpServers":{"shared":{"url":"https://shared.example"}}}`,+ `{"mcp":{"private":{"command":"private-server"}}}`)++ for _, name := range []string{"runtime-local", "shared", "private"} {+ if _, ok := servers[name]; !ok {+ t.Errorf("effective set is missing %q: %v", name, servers)+ }+ }+ if len(servers) != 3 {+ t.Fatalf("effective set = %v, want runtime-local + shared + private", servers)+ }+}++// The same agent, before the workspace shares anything, must be untouched:+// with no workspace document the resolver passes the agent config through+// verbatim, so the daemon still takes its legacy-container fallback.+func TestWorkspaceResolveWithoutSharedServersLeavesLegacyOpencodeAgentAlone(t *testing.T) {+ writeOpencodeRuntimeConfig(t, `{"runtime-local":{"command":"runtime-server"}}`)++ servers := effectiveServerNames(t, "opencode", "", `{"mcp":{"private":{"command":"private-server"}}}`)++ if len(servers) != 2 || servers["private"] == nil || servers["runtime-local"] == nil {+ t.Fatalf("effective set = %v, want runtime-local + private", servers)+ }+}++// An agent that opted out (managed but empty) keeps running with only its+// runtime's own servers — the shared ones must not reach it through the+// daemon merge either.+func TestWorkspaceResolveThenRuntimeMergeHonorsAgentOptOut(t *testing.T) {+ writeOpencodeRuntimeConfig(t, `{"runtime-local":{"command":"runtime-server"}}`)++ servers := effectiveServerNames(t, "opencode",+ `{"mcpServers":{"shared":{"url":"https://shared.example"}}}`, `{}`)++ if _, leaked := servers["shared"]; leaked {+ t.Fatalf("opted-out agent received the shared server: %v", servers)+ }+ if len(servers) != 1 || servers["runtime-local"] == nil {+ t.Fatalf("effective set = %v, want only the runtime's own server", servers)+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex cb0af31d51..efa5b59705 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1803,6 +1803,21 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQuif agent.McpConfig != nil {mcpConfig = json.RawMessage(agent.McpConfig)}+ // Layer the workspace's shared MCP document UNDER the agent's own+ // config (GH #6062). Read on every claim, exactly like the agent+ // column, so an admin's edit reaches every agent on its next task+ // without restarting anything. Errors — including a failed read —+ // leave the agent config untouched: a broken or unreachable shared+ // document must never take away servers the agent runs with today.+ if wsMcpConfig, err := h.Queries.GetWorkspaceMcpConfig(r.Context(), agent.WorkspaceID); err != nil {+ slog.Warn("daemon claim: load workspace mcp_config failed; using agent mcp_config",+ "task_id", uuidToString(task.ID), "workspace_id", uuidToString(agent.WorkspaceID), "error", err)+ } else if resolved, err := ResolveWorkspaceMcpConfig(json.RawMessage(wsMcpConfig), mcpConfig); err != nil {+ slog.Warn("daemon claim: resolve workspace mcp_config failed; falling back to agent mcp_config",+ "task_id", uuidToString(task.ID), "workspace_id", uuidToString(agent.WorkspaceID), "error", err)+ } else {+ mcpConfig = resolved+ }// Layer the per-task overlay (set at enqueue from the initiator// user's active integrations — currently Composio) on top of the// agent's saved mcp_config. Overlay wins on server-name collisionsdiff --git a/server/internal/handler/daemon_claim_workspace_mcp_test.go b/server/internal/handler/daemon_claim_workspace_mcp_test.gonew file mode 100644index 0000000000..3c76885f12--- /dev/null+++ b/server/internal/handler/daemon_claim_workspace_mcp_test.go@@ -0,0 +1,117 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++// claimAgentMcpConfigForTest runs one claim for the given runtime and returns+// the mcp_config the daemon would receive for the claimed task's agent.+func claimAgentMcpConfigForTest(t *testing.T, runtimeID string) json.RawMessage {+ t.Helper()++ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "ws-mcp-daemon")+ req = withURLParam(req, "runtimeId", runtimeID)+ testHandler.ClaimTaskByRuntime(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ClaimTaskByRuntime: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var claimResp struct {+ Task *AgentTaskResponse `json:"task"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &claimResp); err != nil {+ t.Fatalf("decode claim: %v", err)+ }+ if claimResp.Task == nil || claimResp.Task.Agent == nil {+ t.Fatalf("missing task agent in claim response: %s", w.Body.String())+ }+ return claimResp.Task.Agent.McpConfig+}++// setupWorkspaceMcpClaimFixture creates a runtime, an agent with the given+// saved mcp_config, and one queued task ready to claim.+func setupWorkspaceMcpClaimFixture(t *testing.T, ctx context.Context, name, agentMcpConfig string) string {+ t.Helper()++ runtimeID := createClaimReclaimRuntime(t, ctx, name+" runtime")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, name+" agent")++ var stored []byte+ if agentMcpConfig != "" {+ stored = []byte(agentMcpConfig)+ }+ if _, err := testPool.Exec(ctx, `UPDATE agent SET mcp_config = $1 WHERE id = $2`, stored, agentID); err != nil {+ t.Fatalf("setup: set agent mcp_config: %v", err)+ }++ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)+ VALUES ($1, $2, $3, 'queued', 0)+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {+ t.Fatalf("setup: create task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })++ return runtimeID+}++// The claim payload is where the workspace layer actually reaches an agent, so+// assert the resolved document on the wire — not just the merge helper.+func TestClaimTaskByRuntime_InheritsWorkspaceMcpConfig(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ setWorkspaceMcpConfigForTest(t, `{"mcpServers":{"shared":{"url":"https://shared.example"}}}`)+ runtimeID := setupWorkspaceMcpClaimFixture(t, ctx, "ws-mcp-inherit", "")++ servers := decodeServers(t, claimAgentMcpConfigForTest(t, runtimeID))+ if len(servers) != 1 || servers["shared"] == nil {+ t.Fatalf("agent with no saved config should inherit the shared server, got %v", serverNames(servers))+ }+}++func TestClaimTaskByRuntime_MergesWorkspaceAndAgentMcpConfig(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ setWorkspaceMcpConfigForTest(t, `{"mcpServers":{"shared":{"url":"https://shared.example"},"linear":{"url":"https://ws-linear.example"}}}`)+ runtimeID := setupWorkspaceMcpClaimFixture(t, ctx, "ws-mcp-merge",+ `{"mcpServers":{"private":{"url":"https://private.example"},"linear":{"url":"https://agent-linear.example"}}}`)++ servers := decodeServers(t, claimAgentMcpConfigForTest(t, runtimeID))+ if len(servers) != 3 {+ t.Fatalf("server set = %v, want shared/linear/private", serverNames(servers))+ }+ linear, _ := servers["linear"].(map[string]any)+ if linear["url"] != "https://agent-linear.example" {+ t.Errorf("agent must win the name collision, got %v", linear["url"])+ }+}++func TestClaimTaskByRuntime_ZeroServerAgentIgnoresWorkspaceMcpConfig(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ setWorkspaceMcpConfigForTest(t, `{"mcpServers":{"shared":{"url":"https://shared.example"}}}`)+ runtimeID := setupWorkspaceMcpClaimFixture(t, ctx, "ws-mcp-optout", `{}`)++ mcpConfig := claimAgentMcpConfigForTest(t, runtimeID)+ if servers := decodeServers(t, mcpConfig); len(servers) != 0 {+ t.Fatalf("opted-out agent received %v", serverNames(servers))+ }+ // Still managed-but-empty, which is what keeps the runtime's own MCP+ // servers suppressed for this agent.+ if string(mcpConfig) != `{}` {+ t.Fatalf("mcp_config = %s, want the agent's own empty document", mcpConfig)+ }+}diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 889edc39e5..e327897a1c 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -168,12 +168,35 @@ func (h *Handler) ListWorkspaces(w http.ResponseWriter, r *http.Request) {resp := make([]WorkspaceResponse, len(workspaces))for i, ws := range workspaces {- resp[i] = h.workspaceToResponse(ws)+ resp[i] = h.listWorkspacesRowToResponse(ws)}writeJSON(w, http.StatusOK, resp)}+// listWorkspacesRowToResponse renders the deliberately narrow ListWorkspaces+// projection. That query names its columns instead of selecting the whole row+// so the workspace switcher never loads mcp_config — a secret-bearing document+// no list consumer needs (MUL-5421) — which is also why this cannot simply+// reuse workspaceToResponse's db.Workspace parameter.+func (h *Handler) listWorkspacesRowToResponse(row db.ListWorkspacesRow) WorkspaceResponse {+ return h.workspaceToResponse(db.Workspace{+ ID: row.ID,+ Name: row.Name,+ Slug: row.Slug,+ Description: row.Description,+ Settings: row.Settings,+ CreatedAt: row.CreatedAt,+ UpdatedAt: row.UpdatedAt,+ Context: row.Context,+ Repos: row.Repos,+ IssuePrefix: row.IssuePrefix,+ IssueCounter: row.IssueCounter,+ AvatarUrl: row.AvatarUrl,+ AttributionFailClosed: row.AttributionFailClosed,+ })+}+func (h *Handler) GetWorkspace(w http.ResponseWriter, r *http.Request) {id := workspaceIDFromURL(r, "id")idUUID, ok := parseUUIDOrBadRequest(w, id, "workspace id")diff --git a/server/internal/handler/workspace_mcp.go b/server/internal/handler/workspace_mcp.gonew file mode 100644index 0000000000..354d9bd20e--- /dev/null+++ b/server/internal/handler/workspace_mcp.go@@ -0,0 +1,210 @@+package handler++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+)++// mcpServerContainers are the two top-level keys an mcp_config document may+// keep its servers under. `mcpServers` is the Claude-style container every+// runtime consumes; `mcp` is a legacy spelling a few agents still carry and+// which the agent settings UI keeps editing in place (mcp-config-model.ts).+// Both are read when deciding what an agent already declares; only+// `mcpServers` is ever written.+var mcpServerContainers = [...]string{"mcpServers", "mcp"}++// ResolveWorkspaceMcpConfig layers the workspace's shared MCP document UNDER+// an agent's own mcp_config and returns the agent's effective configuration.+// It runs before the per-task overlay (mergeMCPOverlay), so the full+// precedence chain on a claim is:+//+// workspace < agent < per-task overlay+//+// The resolution contract (GH #6062, MUL-5421):+//+// - Agent config absent (SQL NULL / JSON `null`) means "nothing configured+// at the agent layer", so the workspace document is inherited whole. This+// is the case that removes the copy-paste: an agent nobody has touched+// picks up every shared server.+//+// - An agent config that declares NO servers is an explicit "this agent runs+// with zero MCP" (that is exactly what `{}` and `{"mcpServers":{}}` mean+// today under the three-state contract from #3545) and therefore opts the+// agent out of the workspace layer entirely. Preserving this is what keeps+// shared credentials from silently propagating into an agent that was+// deliberately given none.+//+// - Otherwise the two are merged by SERVER NAME and the AGENT wins on a+// collision. Union rather than replacement is deliberate: if declaring one+// private server dropped every shared one, agents would be right back to+// re-entering the workspace's servers by hand.+//+// - A workspace document that declares no servers means "nothing shared",+// not "strict empty". It leaves the agent config untouched, so setting an+// empty workspace document can never flip inheriting agents into the+// managed-empty mode that suppresses their runtime's own MCP servers.+//+// Shape: the AGENT document owns the result's top-level keys, and the merged+// result is NORMALIZED onto the canonical `mcpServers` container. Normalizing+// is mandatory, not cosmetic: the daemon's own runtime merge only falls back+// to the legacy top-level `mcp` container when `mcpServers` is ABSENT+// (`internal/daemon/runtime_mcp.go`), so writing shared servers into+// `mcpServers` while leaving an agent's legacy entries beside them would make+// the daemon read the shared set and silently drop that agent's own servers.+// Folding both containers into one is what keeps a legacy OpenCode agent+// running with everything it had. A workspace server is skipped when the agent+// declares that name in EITHER container, so the merge can never produce the+// same server twice.+//+// Failure mode matches mergeMCPOverlay: on malformed input the agent config is+// returned unchanged along with the error. A bad shared document must never+// take away servers an agent runs with today.+func ResolveWorkspaceMcpConfig(workspaceMcpConfig, agentMcpConfig json.RawMessage) (json.RawMessage, error) {+ if !hasManagedJSON(workspaceMcpConfig) {+ return passthroughAgentMcpConfig(agentMcpConfig), nil+ }++ wsDoc, wsServers, err := parseMcpDocument(workspaceMcpConfig)+ if err != nil {+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("resolve workspace mcp_config: parse workspace document: %w", err)+ }+ if len(wsServers) == 0 {+ // Nothing shared — leave the agent layer exactly as it was.+ return passthroughAgentMcpConfig(agentMcpConfig), nil+ }++ if !hasManagedJSON(agentMcpConfig) {+ // Inherit whole. Re-marshal so the daemon receives the canonical+ // shape regardless of how Postgres stored the JSONB bytes.+ out, err := json.Marshal(wsDoc)+ if err != nil {+ return nil, fmt.Errorf("resolve workspace mcp_config: marshal workspace document: %w", err)+ }+ return out, nil+ }++ agentDoc, agentServers, err := parseMcpDocument(agentMcpConfig)+ if err != nil {+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("resolve workspace mcp_config: parse agent mcp_config: %w", err)+ }+ if len(agentServers) == 0 {+ // Explicit "zero MCP for this agent" — opt out of the workspace layer.+ return passthroughAgentMcpConfig(agentMcpConfig), nil+ }++ // Only the workspace's `mcpServers` entries are shared; a workspace+ // document is validated on write to keep its servers in that container.+ shared, err := unmarshalServerMap(wsDoc["mcpServers"])+ if err != nil {+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("resolve workspace mcp_config: workspace mcpServers: %w", err)+ }++ merged := make(map[string]json.RawMessage, len(shared)+len(agentServers))+ for name, server := range shared {+ // The agent may declare this name in the legacy container instead;+ // agentServers spans both, so this check covers each spelling.+ if _, taken := agentServers[name]; taken {+ continue+ }+ merged[name] = server+ }+ // Fold the agent's own entries in, legacy container first so a name+ // present in both resolves to the canonical one — the precedence the+ // agent settings UI already shows (mcp-config-model.ts reads `mcpServers`+ // before `mcp`).+ for _, container := range [...]string{"mcp", "mcpServers"} {+ own, err := unmarshalServerMap(agentDoc[container])+ if err != nil {+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("resolve workspace mcp_config: agent %s: %w", container, err)+ }+ for name, server := range own {+ merged[name] = server+ }+ }++ out := make(map[string]json.RawMessage, len(agentDoc)+1)+ for k, v := range agentDoc {+ // Both containers are consumed into the canonical map above; leaving+ // the legacy key behind would hand the daemon a second, stale copy.+ if k == "mcpServers" || k == "mcp" {+ continue+ }+ out[k] = v+ }+ serversBytes, err := json.Marshal(merged)+ if err != nil {+ return nil, fmt.Errorf("resolve workspace mcp_config: marshal merged servers: %w", err)+ }+ out["mcpServers"] = serversBytes++ final, err := json.Marshal(out)+ if err != nil {+ return nil, fmt.Errorf("resolve workspace mcp_config: marshal merged document: %w", err)+ }+ return final, nil+}++// parseMcpDocument decodes an mcp_config document into its top-level keys plus+// the set of server names it declares across BOTH containers. The name set is+// what the resolution contract keys "declares no servers" and "agent already+// owns this name" off, so it must span the legacy spelling too.+func parseMcpDocument(raw json.RawMessage) (map[string]json.RawMessage, map[string]struct{}, error) {+ var doc map[string]json.RawMessage+ if err := json.Unmarshal(raw, &doc); err != nil {+ return nil, nil, err+ }+ if doc == nil {+ doc = map[string]json.RawMessage{}+ }+ names := map[string]struct{}{}+ for _, container := range mcpServerContainers {+ servers, err := unmarshalServerMap(doc[container])+ if err != nil {+ return nil, nil, fmt.Errorf("%s: %w", container, err)+ }+ for name := range servers {+ names[name] = struct{}{}+ }+ }+ return doc, names, nil+}++// validateWorkspaceMcpConfig checks the shape of a shared document before it+// is stored. The agent column is effectively unvalidated server-side (the+// agent settings UI is what enforces shape there), but one bad workspace+// document reaches EVERY agent in the workspace, so it is worth rejecting at+// the edge rather than fail-softing on every claim afterwards.+//+// The check stays deliberately shallow — shape only, never the contents of a+// server entry, which are runtime-specific and carry secrets we do not want to+// inspect or echo back in an error.+func validateWorkspaceMcpConfig(raw json.RawMessage) error {+ trimmed := bytes.TrimSpace(raw)+ if len(trimmed) == 0 {+ return errors.New("mcp_config must be a JSON object, or null to clear")+ }+ var doc map[string]json.RawMessage+ if err := json.Unmarshal(trimmed, &doc); err != nil {+ // Never wrap: the underlying error can echo fragments of a document+ // whose server entries routinely embed API tokens.+ return errors.New("mcp_config must be a JSON object, or null to clear")+ }+ if _, legacy := doc["mcp"]; legacy {+ return errors.New(`mcp_config: shared servers must be declared under "mcpServers"; the legacy "mcp" container is not supported at the workspace level`)+ }+ servers, err := unmarshalServerMap(doc["mcpServers"])+ if err != nil {+ return fmt.Errorf("mcp_config: %w", err)+ }+ if len(servers) == 0 && len(doc) > 0 {+ // An object with unrelated top-level keys and no servers would be+ // stored and then ignored by the resolver — reject rather than+ // silently no-op.+ if _, ok := doc["mcpServers"]; !ok {+ return errors.New(`mcp_config: expected an "mcpServers" object; pass null to clear the workspace configuration`)+ }+ }+ return nil+}diff --git a/server/internal/handler/workspace_mcp_api.go b/server/internal/handler/workspace_mcp_api.gonew file mode 100644index 0000000000..5264b35692--- /dev/null+++ b/server/internal/handler/workspace_mcp_api.go@@ -0,0 +1,395 @@+package handler++import (+ "bytes"+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "sort"+ "strings"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/logger"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// WorkspaceMcpServerSummary is the intentionally non-secret inventory of one+// shared server. Never add `url`, `command`, `args`, `headers`, or `env` here:+// upstream #6062 asks for shared secrets to be write-only, and every one of+// those fields routinely carries a token (a Composio-style session URL is a+// bearer credential on its own). Mirrors the daemon's own+// runtimeLocalMcpServerSummary, which draws the same line for the same reason.+type WorkspaceMcpServerSummary struct {+ Name string `json:"name"`+ Transport string `json:"transport"`+ Enabled bool `json:"enabled"`+}++// WorkspaceMcpConfigResponse is the read shape of the shared MCP+// configuration. There is deliberately NO document field and no+// `_redacted` flag: the stored document is never echoed back to anyone,+// regardless of role, so the topology an admin needs for auditing is not+// coupled to reading the credentials back out.+//+// Editing therefore goes through the per-server upsert/delete endpoints+// rather than a client-side read-modify-write.+type WorkspaceMcpConfigResponse struct {+ WorkspaceID string `json:"workspace_id"`+ Servers []WorkspaceMcpServerSummary `json:"servers"`+ ServerCount int `json:"server_count"`+}++// mcpTransportOf classifies a server entry for display. Mirrors the+// front-end's mcpTransport (mcp-config-model.ts) so the same entry is+// labelled identically wherever it is listed.+func mcpTransportOf(entry json.RawMessage) string {+ var e struct {+ Type string `json:"type"`+ Command json.RawMessage `json:"command"`+ URL json.RawMessage `json:"url"`+ }+ if err := json.Unmarshal(entry, &e); err != nil {+ return "unknown"+ }+ switch strings.ToLower(strings.TrimSpace(e.Type)) {+ case "local", "stdio":+ return "stdio"+ case "sse":+ return "sse"+ case "remote", "http", "streamable-http":+ return "http"+ }+ if len(e.Command) > 0 {+ return "stdio"+ }+ if len(e.URL) > 0 {+ return "http"+ }+ return "unknown"+}++// mcpServerEnabled reports whether an entry is active. Matches the front-end+// rule: enabled unless `enabled:false` or `disabled:true`.+func mcpServerEnabled(entry json.RawMessage) bool {+ var e struct {+ Enabled *bool `json:"enabled"`+ Disabled *bool `json:"disabled"`+ }+ if err := json.Unmarshal(entry, &e); err != nil {+ return true+ }+ if e.Enabled != nil && !*e.Enabled {+ return false+ }+ if e.Disabled != nil && *e.Disabled {+ return false+ }+ return true+}++// buildWorkspaceMcpConfigResponse summarizes the stored document. A malformed+// document yields an empty inventory rather than an error: the read path is+// used by settings screens that must still render, and the resolver already+// fails soft on the same input.+func buildWorkspaceMcpConfigResponse(ws db.Workspace) WorkspaceMcpConfigResponse {+ resp := WorkspaceMcpConfigResponse{+ WorkspaceID: uuidToString(ws.ID),+ Servers: []WorkspaceMcpServerSummary{},+ }+ raw := json.RawMessage(ws.McpConfig)+ if !hasManagedJSON(raw) {+ return resp+ }+ doc, _, err := parseMcpDocument(raw)+ if err != nil {+ return resp+ }+ servers, err := unmarshalServerMap(doc["mcpServers"])+ if err != nil {+ return resp+ }+ for name, entry := range servers {+ resp.Servers = append(resp.Servers, WorkspaceMcpServerSummary{+ Name: name,+ Transport: mcpTransportOf(entry),+ Enabled: mcpServerEnabled(entry),+ })+ }+ sort.Slice(resp.Servers, func(i, j int) bool { return resp.Servers[i].Name < resp.Servers[j].Name })+ resp.ServerCount = len(resp.Servers)+ return resp+}++// GetWorkspaceMcpConfig returns the non-secret inventory of shared servers.+// Member-visible: the agent settings view shows what an agent inherits, and+// there is nothing secret in the payload to gate.+func (h *Handler) GetWorkspaceMcpConfig(w http.ResponseWriter, r *http.Request) {+ workspaceID := workspaceIDFromURL(r, "id")+ idUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ if _, ok := h.workspaceMember(w, r, workspaceID); !ok {+ return+ }+ ws, err := h.Queries.GetWorkspace(r.Context(), idUUID)+ if err != nil {+ writeError(w, http.StatusNotFound, "workspace not found")+ return+ }+ writeJSON(w, http.StatusOK, buildWorkspaceMcpConfigResponse(ws))+}++// requireWorkspaceMcpWriter resolves the caller and enforces the write gate.+// The router already restricts these routes to owner/admin, but an agent actor+// running under an owner's PAT would satisfy that gate: handing every agent in+// the workspace a new MCP server has to stay a human admin action.+func (h *Handler) requireWorkspaceMcpWriter(w http.ResponseWriter, r *http.Request, workspaceID string) bool {+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return false+ }+ if actorType, _ := h.resolveActor(r, requestUserID(r), workspaceID); actorType == "agent" {+ writeError(w, http.StatusForbidden, "agents cannot modify the workspace MCP configuration")+ return false+ }+ if !roleAllowed(member.Role, "owner", "admin") {+ writeError(w, http.StatusForbidden, "insufficient permissions")+ return false+ }+ return true+}++// UpdateWorkspaceMcpConfigRequest carries the whole shared document. The field+// is a raw message so an absent key (nothing to do) stays distinguishable from+// an explicit `null` (clear the workspace layer) — the same three-state+// contract the agent column uses.+type UpdateWorkspaceMcpConfigRequest struct {+ McpConfig json.RawMessage `json:"mcp_config"`+}++// UpdateWorkspaceMcpConfig replaces the whole shared document. This is the+// declarative path (`multica workspace mcp set`) for callers that keep the+// document in a file; the UI edits one server at a time through the routes+// below, because it cannot read the current document back.+func (h *Handler) UpdateWorkspaceMcpConfig(w http.ResponseWriter, r *http.Request) {+ workspaceID := workspaceIDFromURL(r, "id")+ idUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ if !h.requireWorkspaceMcpWriter(w, r, workspaceID) {+ return+ }++ var req UpdateWorkspaceMcpConfigRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if len(bytes.TrimSpace(req.McpConfig)) == 0 {+ writeError(w, http.StatusBadRequest, "mcp_config is required; pass null to clear the workspace configuration")+ return+ }++ var (+ ws db.Workspace+ err error+ )+ if bytes.Equal(bytes.TrimSpace(req.McpConfig), []byte("null")) {+ ws, err = h.Queries.ClearWorkspaceMcpConfig(r.Context(), idUUID)+ } else {+ if verr := validateWorkspaceMcpConfig(req.McpConfig); verr != nil {+ writeError(w, http.StatusBadRequest, verr.Error())+ return+ }+ ws, err = h.Queries.SetWorkspaceMcpConfig(r.Context(), db.SetWorkspaceMcpConfigParams{+ ID: idUUID,+ McpConfig: append([]byte(nil), req.McpConfig...),+ })+ }+ if err != nil {+ slog.Warn("update workspace mcp_config failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to update workspace mcp_config")+ return+ }++ h.writeWorkspaceMcpConfigResult(w, r, ws, "replaced")+}++// UpsertWorkspaceMcpServer adds or replaces ONE shared server by name. This is+// what the settings UI uses: since the stored document is never echoed back,+// the client cannot do a read-modify-write, so the merge happens server-side+// under a row lock.+func (h *Handler) UpsertWorkspaceMcpServer(w http.ResponseWriter, r *http.Request) {+ workspaceID := workspaceIDFromURL(r, "id")+ idUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ if !h.requireWorkspaceMcpWriter(w, r, workspaceID) {+ return+ }+ name := strings.TrimSpace(chi.URLParam(r, "serverName"))+ if name == "" {+ writeError(w, http.StatusBadRequest, "server name is required")+ return+ }++ var entry json.RawMessage+ if err := json.NewDecoder(r.Body).Decode(&entry); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ // Validate the entry as a one-server document so the shape rules (and the+ // no-input-echo error contract) stay in one place.+ probe, err := json.Marshal(map[string]any{"mcpServers": map[string]json.RawMessage{name: entry}})+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to validate server entry")+ return+ }+ if verr := validateWorkspaceMcpConfig(probe); verr != nil {+ writeError(w, http.StatusBadRequest, verr.Error())+ return+ }++ ws, ok := h.mutateWorkspaceMcpServers(w, r, idUUID, workspaceID, func(servers map[string]json.RawMessage) error {+ servers[name] = entry+ return nil+ })+ if !ok {+ return+ }+ h.writeWorkspaceMcpConfigResult(w, r, ws, "server_upserted")+}++// DeleteWorkspaceMcpServer removes ONE shared server by name. Removing the+// last one clears the column, so agents fall back to their own configuration+// rather than inheriting an empty managed document.+func (h *Handler) DeleteWorkspaceMcpServer(w http.ResponseWriter, r *http.Request) {+ workspaceID := workspaceIDFromURL(r, "id")+ idUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }+ if !h.requireWorkspaceMcpWriter(w, r, workspaceID) {+ return+ }+ name := strings.TrimSpace(chi.URLParam(r, "serverName"))+ if name == "" {+ writeError(w, http.StatusBadRequest, "server name is required")+ return+ }++ ws, ok := h.mutateWorkspaceMcpServers(w, r, idUUID, workspaceID, func(servers map[string]json.RawMessage) error {+ if _, exists := servers[name]; !exists {+ return errWorkspaceMcpServerNotFound+ }+ delete(servers, name)+ return nil+ })+ if !ok {+ return+ }+ h.writeWorkspaceMcpConfigResult(w, r, ws, "server_deleted")+}++// errWorkspaceMcpServerNotFound turns a mutate callback into a 404 without the+// callback needing the ResponseWriter.+var errWorkspaceMcpServerNotFound = &workspaceMcpError{status: http.StatusNotFound, message: "shared MCP server not found"}++type workspaceMcpError struct {+ status int+ message string+}++func (e *workspaceMcpError) Error() string { return e.message }++// mutateWorkspaceMcpServers applies a per-server edit under a row lock so two+// admins editing different servers at the same time cannot lose one another's+// write — the read-modify-write the client can no longer do itself.+func (h *Handler) mutateWorkspaceMcpServers(+ w http.ResponseWriter,+ r *http.Request,+ idUUID pgtype.UUID,+ workspaceID string,+ apply func(servers map[string]json.RawMessage) error,+) (db.Workspace, bool) {+ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ slog.Error("workspace mcp server edit: begin tx failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to update workspace mcp_config")+ return db.Workspace{}, false+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ current, err := qtx.LockWorkspaceMcpConfig(r.Context(), idUUID)+ if err != nil {+ writeError(w, http.StatusNotFound, "workspace not found")+ return db.Workspace{}, false+ }++ servers := map[string]json.RawMessage{}+ if hasManagedJSON(current) {+ doc, _, derr := parseMcpDocument(current)+ if derr != nil {+ writeError(w, http.StatusConflict, "the stored workspace MCP configuration is malformed; replace it with PUT /mcp-config")+ return db.Workspace{}, false+ }+ parsed, perr := unmarshalServerMap(doc["mcpServers"])+ if perr != nil {+ writeError(w, http.StatusConflict, "the stored workspace MCP configuration is malformed; replace it with PUT /mcp-config")+ return db.Workspace{}, false+ }+ servers = parsed+ }++ if aerr := apply(servers); aerr != nil {+ var wErr *workspaceMcpError+ if errors.As(aerr, &wErr) {+ writeError(w, wErr.status, wErr.message)+ } else {+ writeError(w, http.StatusBadRequest, aerr.Error())+ }+ return db.Workspace{}, false+ }++ var ws db.Workspace+ if len(servers) == 0 {+ // Removing the last shared server means "nothing shared" — clear the+ // column instead of storing an empty document, so the resolver's+ // "workspace declares no servers" path is reached the same way whether+ // the admin deleted servers one by one or cleared the whole layer.+ ws, err = qtx.ClearWorkspaceMcpConfig(r.Context(), idUUID)+ } else {+ var doc []byte+ doc, err = json.Marshal(map[string]any{"mcpServers": servers})+ if err == nil {+ ws, err = qtx.SetWorkspaceMcpConfig(r.Context(), db.SetWorkspaceMcpConfigParams{ID: idUUID, McpConfig: doc})+ }+ }+ if err != nil {+ slog.Warn("workspace mcp server edit failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to update workspace mcp_config")+ return db.Workspace{}, false+ }+ if err := tx.Commit(r.Context()); err != nil {+ slog.Error("workspace mcp server edit: commit failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to update workspace mcp_config")+ return db.Workspace{}, false+ }+ return ws, true+}++// writeWorkspaceMcpConfigResult logs the change and returns the inventory.+// Server names and count only — never the document — so neither the log nor+// the response becomes a second copy of the workspace's credentials.+func (h *Handler) writeWorkspaceMcpConfigResult(w http.ResponseWriter, r *http.Request, ws db.Workspace, action string) {+ resp := buildWorkspaceMcpConfigResponse(ws)+ slog.Info("workspace mcp_config updated", append(logger.RequestAttrs(r),+ "workspace_id", uuidToString(ws.ID), "action", action, "server_count", resp.ServerCount)...)+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/workspace_mcp_api_test.go b/server/internal/handler/workspace_mcp_api_test.gonew file mode 100644index 0000000000..af29be9d33--- /dev/null+++ b/server/internal/handler/workspace_mcp_api_test.go@@ -0,0 +1,403 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++const workspaceMcpTestSecret = "sk-live-workspace-should-never-be-echoed"++var workspaceMcpTestDoc = `{"mcpServers":{"linear":{"url":"https://linear.example","headers":{"Authorization":"Bearer ` + workspaceMcpTestSecret + `"}}}}`++// setWorkspaceMcpConfigForTest stores a shared document and restores whatever+// was there afterwards, so these tests can run against the shared fixture+// workspace without leaking state into the rest of the suite.+func setWorkspaceMcpConfigForTest(t *testing.T, doc string) {+ t.Helper()++ ctx := context.Background()+ var previous []byte+ if err := testPool.QueryRow(ctx, `SELECT mcp_config FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&previous); err != nil {+ t.Fatalf("load workspace mcp_config: %v", err)+ }+ // An empty string means "unconfigured" — store SQL NULL, not invalid JSON.+ var next []byte+ if doc != "" {+ next = []byte(doc)+ }+ if _, err := testPool.Exec(ctx, `UPDATE workspace SET mcp_config = $1 WHERE id = $2`, next, testWorkspaceID); err != nil {+ t.Fatalf("set workspace mcp_config: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `UPDATE workspace SET mcp_config = $1 WHERE id = $2`, previous, testWorkspaceID)+ })+}++func storedWorkspaceMcpConfig(t *testing.T) string {+ t.Helper()+ var stored []byte+ if err := testPool.QueryRow(context.Background(), `SELECT mcp_config FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&stored); err != nil {+ t.Fatalf("read back mcp_config: %v", err)+ }+ return string(stored)+}++func getWorkspaceMcpConfigForTest(t *testing.T, mutate func(*http.Request)) (int, WorkspaceMcpConfigResponse, string) {+ t.Helper()++ req := newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/mcp-config", nil)+ req = withURLParam(req, "id", testWorkspaceID)+ if mutate != nil {+ mutate(req)+ }+ w := httptest.NewRecorder()+ testHandler.GetWorkspaceMcpConfig(w, req)++ var resp WorkspaceMcpConfigResponse+ raw := w.Body.String()+ if w.Code == http.StatusOK {+ if err := json.Unmarshal([]byte(raw), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ }+ return w.Code, resp, raw+}++// The shared document is write-only (GH #6062): the read path returns the+// non-secret inventory and nothing else, for EVERY role. This is the test that+// pins that contract — it asserts on the raw response body, not the decoded+// struct, so adding a secret-bearing field later fails here.+func TestGetWorkspaceMcpConfig_NeverEchoesSecrets(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, workspaceMcpTestDoc)++ code, resp, raw := getWorkspaceMcpConfigForTest(t, nil)+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", code, raw)+ }+ // The workspace owner is the most privileged caller there is; if anyone+ // could read the credential back it would be this request.+ if strings.Contains(raw, workspaceMcpTestSecret) {+ t.Fatalf("response echoed the shared credential: %s", raw)+ }+ if strings.Contains(raw, "linear.example") {+ t.Fatalf("response echoed the server URL, which is itself credential material: %s", raw)+ }+ if len(resp.Servers) != 1 || resp.Servers[0].Name != "linear" {+ t.Fatalf("expected the server inventory, got %+v", resp.Servers)+ }+ if resp.Servers[0].Transport != "http" || !resp.Servers[0].Enabled {+ t.Errorf("inventory = %+v, want an enabled http server", resp.Servers[0])+ }+ if resp.ServerCount != 1 {+ t.Errorf("server_count = %d, want 1", resp.ServerCount)+ }+}++// The inventory is member-visible so an agent's settings view can show what it+// inherits; there is nothing secret in it to gate on role.+func TestGetWorkspaceMcpConfig_InventoryVisibleToPlainMember(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, workspaceMcpTestDoc)++ ctx := context.Background()+ var plainUserID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO "user" (name, email)+ VALUES ('Workspace MCP Member', '[email protected]')+ RETURNING id+ `).Scan(&plainUserID); err != nil {+ t.Fatalf("create member user: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM "user" WHERE email = '[email protected]'`)+ })+ if _, err := testPool.Exec(ctx, `+ INSERT INTO member (workspace_id, user_id, role)+ VALUES ($1, $2, 'member')+ `, testWorkspaceID, plainUserID); err != nil {+ t.Fatalf("add workspace member: %v", err)+ }++ code, resp, raw := getWorkspaceMcpConfigForTest(t, func(req *http.Request) {+ req.Header.Set("X-User-ID", plainUserID)+ })+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", code, raw)+ }+ if strings.Contains(raw, workspaceMcpTestSecret) {+ t.Fatalf("response echoed the shared credential to a plain member: %s", raw)+ }+ if resp.ServerCount != 1 {+ t.Errorf("server_count = %d, want 1", resp.ServerCount)+ }+}++func TestGetWorkspaceMcpConfig_UnconfiguredWorkspace(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, "")++ code, resp, raw := getWorkspaceMcpConfigForTest(t, nil)+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", code, raw)+ }+ if len(resp.Servers) != 0 || resp.ServerCount != 0 {+ t.Errorf("expected an empty inventory, got %+v", resp.Servers)+ }+}++// A document that somehow became malformed must still render the settings+// screen rather than 500 it.+func TestGetWorkspaceMcpConfig_MalformedDocumentYieldsEmptyInventory(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, `{"mcpServers":{"broken":"not-an-object"}}`)++ code, resp, raw := getWorkspaceMcpConfigForTest(t, nil)+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", code, raw)+ }+ if len(resp.Servers) != 0 {+ t.Errorf("expected an empty inventory for a malformed document, got %+v", resp.Servers)+ }+}++func updateWorkspaceMcpConfigForTest(t *testing.T, body any, mutate func(*http.Request)) (int, WorkspaceMcpConfigResponse, string) {+ t.Helper()++ req := newRequest(http.MethodPut, "/api/workspaces/"+testWorkspaceID+"/mcp-config", body)+ req = withURLParam(req, "id", testWorkspaceID)+ if mutate != nil {+ mutate(req)+ }+ w := httptest.NewRecorder()+ testHandler.UpdateWorkspaceMcpConfig(w, req)++ var resp WorkspaceMcpConfigResponse+ raw := w.Body.String()+ if w.Code == http.StatusOK {+ if err := json.Unmarshal([]byte(raw), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ }+ return w.Code, resp, raw+}++func TestUpdateWorkspaceMcpConfig_SetAndClear(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, "")++ code, resp, raw := updateWorkspaceMcpConfigForTest(t, map[string]any{+ "mcp_config": json.RawMessage(workspaceMcpTestDoc),+ }, nil)+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", code, raw)+ }+ if resp.ServerCount != 1 {+ t.Errorf("server_count = %d, want 1", resp.ServerCount)+ }+ // Even the write response — sent to the admin who just supplied the+ // document — does not echo it back.+ if strings.Contains(raw, workspaceMcpTestSecret) {+ t.Fatalf("write response echoed the shared credential: %s", raw)+ }+ if !strings.Contains(storedWorkspaceMcpConfig(t), workspaceMcpTestSecret) {+ t.Fatalf("stored document = %s, want the submitted one", storedWorkspaceMcpConfig(t))+ }++ // An explicit null clears the layer; every inheriting agent falls back to+ // its own config on the next claim.+ code, _, raw = updateWorkspaceMcpConfigForTest(t, map[string]any{"mcp_config": nil}, nil)+ if code != http.StatusOK {+ t.Fatalf("clear: expected 200, got %d: %s", code, raw)+ }+ if stored := storedWorkspaceMcpConfig(t); stored != "" {+ t.Fatalf("expected NULL after clear, got %s", stored)+ }+}++func TestUpdateWorkspaceMcpConfig_RejectsBadShape(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, "")++ for _, body := range []map[string]any{+ {"mcp_config": []any{}},+ {"mcp_config": "nope"},+ {"mcp_config": map[string]any{"mcpServers": map[string]any{"a": "not-an-object"}}},+ {"mcp_config": map[string]any{"mcp": map[string]any{"a": map[string]any{}}}},+ {},+ } {+ code, _, raw := updateWorkspaceMcpConfigForTest(t, body, nil)+ if code != http.StatusBadRequest {+ t.Errorf("body %v: expected 400, got %d: %s", body, code, raw)+ }+ }++ if stored := storedWorkspaceMcpConfig(t); stored != "" {+ t.Fatalf("a rejected write must not touch the stored document, got %s", stored)+ }+}++// Writing shared servers stays a human admin action: a task token that happens+// to run under an owner's PAT must not be able to hand every agent in the+// workspace a new MCP server.+func TestUpdateWorkspaceMcpConfig_DeniesAgentActor(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, "")++ caller := createHandlerTestAgent(t, "ws-mcp-writer", nil)+ taskID := insertHandlerTestTask(t, caller)+ asAgent := func(req *http.Request) {+ req.Header.Set("X-Actor-Source", "task_token")+ req.Header.Set("X-Agent-ID", caller)+ req.Header.Set("X-Task-ID", taskID)+ }++ code, _, raw := updateWorkspaceMcpConfigForTest(t, map[string]any{+ "mcp_config": json.RawMessage(workspaceMcpTestDoc),+ }, asAgent)+ if code != http.StatusForbidden {+ t.Fatalf("full replace: expected 403 for an agent actor, got %d: %s", code, raw)+ }++ code, _, raw = upsertWorkspaceMcpServerForTest(t, "linear", map[string]any{"url": "https://x.example"}, asAgent)+ if code != http.StatusForbidden {+ t.Fatalf("per-server upsert: expected 403 for an agent actor, got %d: %s", code, raw)+ }+}++func upsertWorkspaceMcpServerForTest(t *testing.T, name string, entry any, mutate func(*http.Request)) (int, WorkspaceMcpConfigResponse, string) {+ t.Helper()++ req := newRequest(http.MethodPut, "/api/workspaces/"+testWorkspaceID+"/mcp-config/servers/"+name, entry)+ req = withURLParams(req, "id", testWorkspaceID, "serverName", name)+ if mutate != nil {+ mutate(req)+ }+ w := httptest.NewRecorder()+ testHandler.UpsertWorkspaceMcpServer(w, req)++ var resp WorkspaceMcpConfigResponse+ raw := w.Body.String()+ if w.Code == http.StatusOK {+ if err := json.Unmarshal([]byte(raw), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ }+ return w.Code, resp, raw+}++func deleteWorkspaceMcpServerForTest(t *testing.T, name string) (int, WorkspaceMcpConfigResponse, string) {+ t.Helper()++ req := newRequest(http.MethodDelete, "/api/workspaces/"+testWorkspaceID+"/mcp-config/servers/"+name, nil)+ req = withURLParams(req, "id", testWorkspaceID, "serverName", name)+ w := httptest.NewRecorder()+ testHandler.DeleteWorkspaceMcpServer(w, req)++ var resp WorkspaceMcpConfigResponse+ raw := w.Body.String()+ if w.Code == http.StatusOK {+ if err := json.Unmarshal([]byte(raw), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ }+ return w.Code, resp, raw+}++// The per-server path is what the settings UI uses: because it can never read+// the document, the server has to do the read-modify-write for it — and must+// not disturb the servers the caller did not mention.+func TestUpsertWorkspaceMcpServer_MergesWithoutReadingBack(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, workspaceMcpTestDoc)++ code, resp, raw := upsertWorkspaceMcpServerForTest(t, "github", map[string]any{"command": "github-mcp"}, nil)+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", code, raw)+ }+ if resp.ServerCount != 2 {+ t.Fatalf("server_count = %d, want 2 (%+v)", resp.ServerCount, resp.Servers)+ }+ if resp.Servers[0].Name != "github" || resp.Servers[0].Transport != "stdio" {+ t.Errorf("inventory[0] = %+v, want the new stdio server first (sorted)", resp.Servers[0])+ }+ // The untouched server keeps its credential in storage.+ if !strings.Contains(storedWorkspaceMcpConfig(t), workspaceMcpTestSecret) {+ t.Fatalf("upsert dropped the existing server's credentials: %s", storedWorkspaceMcpConfig(t))+ }++ // Replacing an existing name overwrites just that entry.+ code, resp, raw = upsertWorkspaceMcpServerForTest(t, "linear", map[string]any{"url": "https://linear-v2.example"}, nil)+ if code != http.StatusOK {+ t.Fatalf("replace: expected 200, got %d: %s", code, raw)+ }+ if resp.ServerCount != 2 {+ t.Fatalf("replace: server_count = %d, want 2", resp.ServerCount)+ }+ if strings.Contains(storedWorkspaceMcpConfig(t), workspaceMcpTestSecret) {+ t.Errorf("replacing an entry must overwrite it, not merge into it: %s", storedWorkspaceMcpConfig(t))+ }+}++func TestUpsertWorkspaceMcpServer_RejectsBadEntry(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, "")++ for _, entry := range []any{"not-an-object", []any{}, 42} {+ code, _, raw := upsertWorkspaceMcpServerForTest(t, "bad", entry, nil)+ if code != http.StatusBadRequest {+ t.Errorf("entry %v: expected 400, got %d: %s", entry, code, raw)+ }+ }+ if stored := storedWorkspaceMcpConfig(t); stored != "" {+ t.Fatalf("a rejected upsert must not write, got %s", stored)+ }+}++// Deleting the last shared server clears the column rather than storing an+// empty document, so inheriting agents fall back to their own config instead+// of being handed a managed-empty one.+func TestDeleteWorkspaceMcpServer_LastServerClearsTheLayer(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ setWorkspaceMcpConfigForTest(t, workspaceMcpTestDoc)++ code, _, raw := deleteWorkspaceMcpServerForTest(t, "does-not-exist")+ if code != http.StatusNotFound {+ t.Fatalf("expected 404 for an unknown server, got %d: %s", code, raw)+ }++ code, resp, raw := deleteWorkspaceMcpServerForTest(t, "linear")+ if code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", code, raw)+ }+ if resp.ServerCount != 0 {+ t.Errorf("server_count = %d, want 0", resp.ServerCount)+ }+ if stored := storedWorkspaceMcpConfig(t); stored != "" {+ t.Fatalf("expected NULL after removing the last server, got %s", stored)+ }+}diff --git a/server/internal/handler/workspace_mcp_test.go b/server/internal/handler/workspace_mcp_test.gonew file mode 100644index 0000000000..69dd733643--- /dev/null+++ b/server/internal/handler/workspace_mcp_test.go@@ -0,0 +1,313 @@+package handler++import (+ "encoding/json"+ "reflect"+ "strings"+ "testing"+)++// decodeServers pulls the `mcpServers` map out of a resolved document so+// assertions can compare server sets without depending on key order.+func decodeServers(t *testing.T, raw json.RawMessage) map[string]any {+ t.Helper()+ if len(raw) == 0 {+ return nil+ }+ var doc map[string]any+ if err := json.Unmarshal(raw, &doc); err != nil {+ t.Fatalf("unmarshal resolved document %s: %v", raw, err)+ }+ servers, _ := doc["mcpServers"].(map[string]any)+ return servers+}++func serverNames(servers map[string]any) []string {+ names := make([]string, 0, len(servers))+ for name := range servers {+ names = append(names, name)+ }+ return names+}++func TestResolveWorkspaceMcpConfig(t *testing.T) {+ const wsDoc = `{"mcpServers":{"shared":{"url":"https://shared.example"},"linear":{"url":"https://ws-linear.example"}}}`++ tests := []struct {+ name string+ workspace string+ agent string+ wantServers map[string]string // server name -> expected url+ wantNil bool+ }{+ {+ name: "agent absent inherits the whole workspace document",+ workspace: wsDoc,+ agent: "",+ wantServers: map[string]string{+ "shared": "https://shared.example",+ "linear": "https://ws-linear.example",+ },+ },+ {+ name: "agent json null inherits too",+ workspace: wsDoc,+ agent: "null",+ wantServers: map[string]string{+ "shared": "https://shared.example",+ "linear": "https://ws-linear.example",+ },+ },+ {+ name: "agent servers union with the workspace's",+ workspace: wsDoc,+ agent: `{"mcpServers":{"private":{"url":"https://private.example"}}}`,+ wantServers: map[string]string{+ "shared": "https://shared.example",+ "linear": "https://ws-linear.example",+ "private": "https://private.example",+ },+ },+ {+ name: "agent wins on a server-name collision",+ workspace: wsDoc,+ agent: `{"mcpServers":{"linear":{"url":"https://agent-linear.example"}}}`,+ wantServers: map[string]string{+ "shared": "https://shared.example",+ "linear": "https://agent-linear.example",+ },+ },+ {+ // The legacy entry both shadows the shared one AND survives, now+ // folded into the canonical container the daemon actually reads.+ name: "an agent name in the legacy container shadows the shared one and survives",+ workspace: wsDoc,+ agent: `{"mcp":{"linear":{"url":"https://legacy-linear.example"}}}`,+ wantServers: map[string]string{+ "shared": "https://shared.example",+ "linear": "https://legacy-linear.example",+ },+ },+ {+ name: "no workspace document leaves the agent config alone",+ workspace: "",+ agent: `{"mcpServers":{"private":{"url":"https://private.example"}}}`,+ wantServers: map[string]string{+ "private": "https://private.example",+ },+ },+ {+ name: "an empty workspace document shares nothing",+ workspace: `{"mcpServers":{}}`,+ agent: "",+ wantNil: true,+ },+ {+ name: "nothing configured anywhere stays nil",+ workspace: "",+ agent: "",+ wantNil: true,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got, err := ResolveWorkspaceMcpConfig(json.RawMessage(tc.workspace), json.RawMessage(tc.agent))+ if err != nil {+ t.Fatalf("ResolveWorkspaceMcpConfig: unexpected error: %v", err)+ }+ if tc.wantNil {+ if got != nil {+ t.Fatalf("expected nil result, got %s", got)+ }+ return+ }+ servers := decodeServers(t, got)+ if len(servers) != len(tc.wantServers) {+ t.Fatalf("server set = %v, want %v", serverNames(servers), tc.wantServers)+ }+ for name, wantURL := range tc.wantServers {+ entry, ok := servers[name].(map[string]any)+ if !ok {+ t.Fatalf("missing server %q in %v", name, serverNames(servers))+ }+ if entry["url"] != wantURL {+ t.Errorf("server %q url = %v, want %v", name, entry["url"], wantURL)+ }+ }+ })+ }+}++// An agent whose saved config declares no servers is the explicit "this agent+// runs with zero MCP" state from #3545. Sharing a workspace document must not+// hand it credentials it was deliberately not given — that silent propagation+// is the main risk of an inheritance layer, so it gets its own test.+func TestResolveWorkspaceMcpConfig_ZeroServerAgentOptsOut(t *testing.T) {+ const wsDoc = `{"mcpServers":{"shared":{"url":"https://shared.example"}}}`++ for _, agentCfg := range []string{`{}`, `{"mcpServers":{}}`, `{"mcp":{}}`} {+ t.Run(agentCfg, func(t *testing.T) {+ got, err := ResolveWorkspaceMcpConfig(json.RawMessage(wsDoc), json.RawMessage(agentCfg))+ if err != nil {+ t.Fatalf("ResolveWorkspaceMcpConfig: unexpected error: %v", err)+ }+ if servers := decodeServers(t, got); len(servers) != 0 {+ t.Fatalf("opted-out agent inherited %v", serverNames(servers))+ }+ // The agent document must also survive byte-for-byte: the+ // three-state contract keys strict mode off "managed but empty",+ // which a nil result would silently turn back into "inherit".+ if string(got) != agentCfg {+ t.Fatalf("agent document = %s, want it returned unchanged (%s)", got, agentCfg)+ }+ })+ }+}++// The agent's servers must survive whichever container they were stored in,+// and the result must be normalized onto `mcpServers`. This is the case that+// regressed OpenCode agents: the daemon's runtime merge only falls back to the+// legacy `mcp` container when `mcpServers` is absent, so leaving the agent's+// entries behind in `mcp` while writing shared ones into `mcpServers` made the+// daemon read the shared set and drop the agent's own servers entirely.+func TestResolveWorkspaceMcpConfig_FoldsLegacyContainerIntoCanonical(t *testing.T) {+ const wsDoc = `{"mcpServers":{"shared":{"url":"https://shared.example"}}}`+ const agentCfg = `{"mcp":{"legacy":{"command":"legacy-server"}},"inputs":[{"id":"token"}]}`++ got, err := ResolveWorkspaceMcpConfig(json.RawMessage(wsDoc), json.RawMessage(agentCfg))+ if err != nil {+ t.Fatalf("ResolveWorkspaceMcpConfig: unexpected error: %v", err)+ }+ var doc map[string]any+ if err := json.Unmarshal(got, &doc); err != nil {+ t.Fatalf("unmarshal merged document: %v", err)+ }+ if _, ok := doc["mcp"]; ok {+ t.Errorf("legacy container must be consumed, not left beside mcpServers: %s", got)+ }+ if _, ok := doc["inputs"]; !ok {+ t.Errorf("merge dropped the agent's non-server top-level key: %s", got)+ }+ servers := decodeServers(t, got)+ if len(servers) != 2 || servers["shared"] == nil || servers["legacy"] == nil {+ t.Fatalf("effective server set = %v, want shared + legacy", serverNames(servers))+ }+}++// A name present in BOTH containers resolves to the canonical entry — the+// precedence the agent settings UI already displays.+func TestResolveWorkspaceMcpConfig_CanonicalContainerWinsOverLegacy(t *testing.T) {+ const wsDoc = `{"mcpServers":{"shared":{"url":"https://shared.example"}}}`+ const agentCfg = `{"mcpServers":{"dup":{"url":"https://canonical.example"}},"mcp":{"dup":{"url":"https://legacy.example"}}}`++ got, err := ResolveWorkspaceMcpConfig(json.RawMessage(wsDoc), json.RawMessage(agentCfg))+ if err != nil {+ t.Fatalf("ResolveWorkspaceMcpConfig: unexpected error: %v", err)+ }+ servers := decodeServers(t, got)+ dup, _ := servers["dup"].(map[string]any)+ if dup["url"] != "https://canonical.example" {+ t.Fatalf("dup url = %v, want the canonical container to win", dup["url"])+ }+}++// Fail-soft: a malformed shared document must never take away servers the+// agent runs with today. It reports the error and returns the agent config.+func TestResolveWorkspaceMcpConfig_MalformedWorkspaceKeepsAgentConfig(t *testing.T) {+ const agentCfg = `{"mcpServers":{"private":{"url":"https://private.example"}}}`++ for _, wsDoc := range []string{`{"mcpServers":[]}`, `not json`, `{"mcpServers":{"broken":"not-an-object"}}`} {+ t.Run(wsDoc, func(t *testing.T) {+ got, err := ResolveWorkspaceMcpConfig(json.RawMessage(wsDoc), json.RawMessage(agentCfg))+ if err == nil {+ t.Fatalf("expected an error for workspace document %s", wsDoc)+ }+ if string(got) != agentCfg {+ t.Fatalf("agent config = %s, want it returned unchanged (%s)", got, agentCfg)+ }+ })+ }+}++// The claim path applies the workspace layer before the per-task overlay, so+// the two merges have to compose into workspace < agent < overlay.+func TestResolveWorkspaceMcpConfig_ComposesWithTaskOverlay(t *testing.T) {+ const wsDoc = `{"mcpServers":{"shared":{"url":"https://shared.example"},"composio":{"url":"https://ws-composio.example"}}}`+ const agentCfg = `{"mcpServers":{"private":{"url":"https://private.example"}}}`+ const overlay = `{"mcpServers":{"composio":{"url":"https://session-composio.example"}}}`++ resolved, err := ResolveWorkspaceMcpConfig(json.RawMessage(wsDoc), json.RawMessage(agentCfg))+ if err != nil {+ t.Fatalf("ResolveWorkspaceMcpConfig: unexpected error: %v", err)+ }+ merged, err := mergeMCPOverlay(resolved, json.RawMessage(overlay))+ if err != nil {+ t.Fatalf("mergeMCPOverlay: unexpected error: %v", err)+ }+ servers := decodeServers(t, merged)+ if len(servers) != 3 {+ t.Fatalf("server set = %v, want shared/composio/private", serverNames(servers))+ }+ composio, _ := servers["composio"].(map[string]any)+ if composio["url"] != "https://session-composio.example" {+ t.Errorf("overlay must win over the workspace entry, got %v", composio["url"])+ }+}++func TestValidateWorkspaceMcpConfig(t *testing.T) {+ tests := []struct {+ name string+ raw string+ wantErr bool+ }{+ {name: "servers", raw: `{"mcpServers":{"a":{"url":"https://a.example"}}}`},+ {name: "empty object", raw: `{}`},+ {name: "empty server map", raw: `{"mcpServers":{}}`},+ {name: "array", raw: `[]`, wantErr: true},+ {name: "string", raw: `"nope"`, wantErr: true},+ {name: "servers not an object", raw: `{"mcpServers":[]}`, wantErr: true},+ {name: "server entry not an object", raw: `{"mcpServers":{"a":"https://a.example"}}`, wantErr: true},+ {name: "empty server name", raw: `{"mcpServers":{"":{"url":"https://a.example"}}}`, wantErr: true},+ {name: "legacy container", raw: `{"mcp":{"a":{"url":"https://a.example"}}}`, wantErr: true},+ {name: "no servers key", raw: `{"inputs":[]}`, wantErr: true},+ {name: "empty input", raw: ``, wantErr: true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ err := validateWorkspaceMcpConfig(json.RawMessage(tc.raw))+ if tc.wantErr && err == nil {+ t.Fatalf("validateWorkspaceMcpConfig(%s): expected an error", tc.raw)+ }+ if !tc.wantErr && err != nil {+ t.Fatalf("validateWorkspaceMcpConfig(%s): unexpected error: %v", tc.raw, err)+ }+ })+ }+}++// Validation errors are surfaced to the caller verbatim, and a shared document+// is exactly where a token would sit — so the message must never quote input.+func TestValidateWorkspaceMcpConfig_ErrorNeverEchoesInput(t *testing.T) {+ secret := `{"mcpServers":{"a":{"headers":{"Authorization":"Bearer sk-live-should-not-leak"` // deliberately truncated++ err := validateWorkspaceMcpConfig(json.RawMessage(secret))+ if err == nil {+ t.Fatal("expected an error for a truncated document")+ }+ if strings.Contains(err.Error(), "sk-live-should-not-leak") {+ t.Fatalf("validation error leaked input: %q", err.Error())+ }+}++func TestParseMcpDocument_NamesSpanBothContainers(t *testing.T) {+ _, names, err := parseMcpDocument(json.RawMessage(`{"mcpServers":{"a":{}},"mcp":{"b":{}}}`))+ if err != nil {+ t.Fatalf("parseMcpDocument: unexpected error: %v", err)+ }+ want := map[string]struct{}{"a": {}, "b": {}}+ if !reflect.DeepEqual(names, want) {+ t.Fatalf("names = %v, want %v", names, want)+ }+}diff --git a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.mdindex 4144ec44a0..cb21daa126 100644--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md+++ b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md@@ -242,6 +242,37 @@ Two ways `mcp_config` differs from `custom_env`:Provider support is not uniform: Qwen Code accepts a managed `mcp_config` through a daemon-owned 0600 temporary JSON file passed with `--mcp-config`; it is removed when the run exits. Leave the field unset (`null`) to inherit Qwen Code native settings.+#### Workspace-level MCP servers++A workspace can share one MCP document with every agent in it — from workspace+Settings → MCP in the UI, or on the CLI with `multica workspace mcp get` (lists+the servers; the document itself is never returned) plus `set` / `add` /+`remove`, which require owner or admin. The agent's own `mcp_config` is+resolved on top of it at claim time, so what an agent actually runs with is:++| Agent `mcp_config` | Effective set |+| --- | --- |+| `null` (unset) | the workspace's servers |+| declares ≥1 server | workspace servers **plus** its own; the agent wins on a name collision |+| declares no server (`{}` or `{"mcpServers":{}}`) | none of the workspace's — the "no managed servers of my own" state also opts out of the workspace layer. The agent's RUNTIME-local servers still apply: the daemon merges runtime servers under whatever the claim carries |++Two consequences worth knowing before writing an agent's config: an agent that+should keep its own private server does NOT need to re-list the shared ones+(they merge), and a config that declares no servers is the only way to keep the+workspace's servers away from an agent. That is not the same as "no MCP at all"+— the runtime's own local servers are merged by the daemon either way.++The merge also normalizes: an agent that stored its servers under the legacy+top-level `mcp` container gets them folded into `mcpServers` in the resolved+payload, because the daemon's runtime merge only reads the legacy container+when `mcpServers` is absent.++The workspace document itself is **write-only** — `GET` returns only the+server names / transports, never urls, commands, headers, or env, for any+role. That is why editing one shared server goes through+`PUT /api/workspaces/{id}/mcp-config/servers/{name}` (`workspace mcp add`)+rather than a read-modify-write of the whole document.+## Skill bindingCreating an agent does NOT bind any workspace skill — binding is a separatediff --git a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.mdindex 477b5cd91e..cc3da17344 100644--- a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md+++ b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md@@ -66,6 +66,9 @@ go test ./internal/service -run TestBuiltinSkillsConformToTemplate| `mcp_config` null-skip on create | 704–705 | raw JSON copied through unless the body value is the literal `null` || `mcp_config` redacted on read | 54, 848–851 | `redactMcpConfig` sets `McpConfigRedacted=true`; a private agent read by a member also redacts (494, 509) || Qwen Code managed-MCP injection | `pkg/agent/qwen.go` | Non-null `mcp_config` is written to a daemon-owned 0600 temporary JSON file and passed with `--mcp-config`; the file is removed after the process exits, while `null` preserves native inheritance. |+| Workspace MCP layer resolved under the agent's | `internal/handler/workspace_mcp.go` `ResolveWorkspaceMcpConfig`; applied in `internal/handler/daemon.go` `buildClaimedTaskResponse` | Union by server name with the agent winning; an agent config declaring zero servers opts out; both containers normalized onto `mcpServers`; read on every claim, so an admin edit lands on the agent's next task |+| Workspace MCP read/write API | `internal/handler/workspace_mcp_api.go` | `GET /api/workspaces/{id}/mcp-config` returns the non-secret inventory (name / transport / enabled) and never the document, for any role; `PUT /mcp-config` (full replace, `null` clears) and `PUT`/`DELETE /mcp-config/servers/{name}` (per-server, row-locked read-modify-write) are owner/admin and refuse agent actors |+| Effective-set regression guard | `internal/daemon/runtime_mcp_workspace_test.go` | Runs resolve -> `mergeRuntimeAndAgentMcpConfig` for OpenCode; catches a resolver that emits a container the daemon merge would not read || Random emoji avatar default | `agent_avatar.go` 11–32; `agent.go` 1127–1133 | Omitted, empty, or whitespace-only `avatar_url` becomes a cryptographically selected `emoji:<glyph>` sentinel; explicit values are preserved. || `CreateAgent` insert params | `agent.go` create path | Persists avatar_url, runtime_config, instructions, custom_env, custom_args, model, thinking_level, service_tier, mcp_config, visibility, max_concurrent_tasks || `UpdateAgent` rejects `custom_env` | 910–913 | if `custom_env` present in body → 400 "use PUT /api/agents/{id}/env (or `multica agent env set`)" |diff --git a/server/migrations/314_workspace_mcp_config.down.sql b/server/migrations/314_workspace_mcp_config.down.sqlnew file mode 100644index 0000000000..a1b657daf9--- /dev/null+++ b/server/migrations/314_workspace_mcp_config.down.sql@@ -0,0 +1 @@+ALTER TABLE workspace DROP COLUMN IF EXISTS mcp_config;diff --git a/server/migrations/314_workspace_mcp_config.up.sql b/server/migrations/314_workspace_mcp_config.up.sqlnew file mode 100644index 0000000000..ab9a05c57c--- /dev/null+++ b/server/migrations/314_workspace_mcp_config.up.sql@@ -0,0 +1,11 @@+-- Workspace-level MCP configuration (GH #6062, MUL-5421).+--+-- Shares one MCP server set across every agent in the workspace instead of+-- forcing the same servers to be re-entered on each agent. Deliberately the+-- same shape as agent.mcp_config (046_agent_mcp_config): a nullable JSONB+-- document holding `{"mcpServers": {<name>: {...}}}`.+--+-- NULL keeps its meaning from the agent column — "nothing configured at this+-- layer" — so every existing workspace starts out with no shared servers and+-- no agent's effective configuration changes until an admin sets one.+ALTER TABLE workspace ADD COLUMN mcp_config jsonb;diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 5c7aca4507..cc7ef7f33c 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1393,7 +1393,8 @@ type Workspace struct {IssueCounter int32 `json:"issue_counter"`AvatarUrl pgtype.Text `json:"avatar_url"`// When TRUE, an agent run that resolves to no precise accountable human (would be owner_fallback) is refused at enqueue instead of degrading to the agent owner (MUL-4302 §3.5). Default FALSE = owner_fallback. Never affects authorization (originator_user_id).- AttributionFailClosed bool `json:"attribution_fail_closed"`+ AttributionFailClosed bool `json:"attribution_fail_closed"`+ McpConfig []byte `json:"mcp_config"`}type WorkspaceInvitation struct {diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.goindex 5a94e22b46..c5e4b650e8 100644--- a/server/pkg/db/generated/workspace.sql.go+++ b/server/pkg/db/generated/workspace.sql.go@@ -11,10 +11,40 @@ import ("github.com/jackc/pgx/v5/pgtype")+const clearWorkspaceMcpConfig = `-- name: ClearWorkspaceMcpConfig :one+UPDATE workspace SET mcp_config = NULL, updated_at = now()+WHERE id = $1+RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed, mcp_config+`++// Restores the "nothing shared at this layer" state. Every agent that was+// inheriting falls back to its own mcp_config on its next claim.+func (q *Queries) ClearWorkspaceMcpConfig(ctx context.Context, id pgtype.UUID) (Workspace, error) {+ row := q.db.QueryRow(ctx, clearWorkspaceMcpConfig, id)+ var i Workspace+ err := row.Scan(+ &i.ID,+ &i.Name,+ &i.Slug,+ &i.Description,+ &i.Settings,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Context,+ &i.Repos,+ &i.IssuePrefix,+ &i.IssueCounter,+ &i.AvatarUrl,+ &i.AttributionFailClosed,+ &i.McpConfig,+ )+ return i, err+}+const createWorkspace = `-- name: CreateWorkspace :oneINSERT INTO workspace (name, slug, description, context, issue_prefix)VALUES ($1, $2, $3, $4, $5)-RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed+RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed, mcp_config`type CreateWorkspaceParams struct {@@ -48,6 +78,7 @@ func (q *Queries) CreateWorkspace(ctx context.Context, arg CreateWorkspaceParams&i.IssueCounter,&i.AvatarUrl,&i.AttributionFailClosed,+ &i.McpConfig,)return i, err}@@ -193,7 +224,7 @@ func (q *Queries) GetDaemonWorkspace(ctx context.Context, id pgtype.UUID) (GetDa}const getWorkspace = `-- name: GetWorkspace :one-SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed FROM workspace+SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed, mcp_config FROM workspaceWHERE id = $1`@@ -214,6 +245,7 @@ func (q *Queries) GetWorkspace(ctx context.Context, id pgtype.UUID) (Workspace,&i.IssueCounter,&i.AvatarUrl,&i.AttributionFailClosed,+ &i.McpConfig,)return i, err}@@ -233,7 +265,7 @@ func (q *Queries) GetWorkspaceAttributionFailClosed(ctx context.Context, id pgty}const getWorkspaceBySlug = `-- name: GetWorkspaceBySlug :one-SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed FROM workspace+SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed, mcp_config FROM workspaceWHERE slug = $1`@@ -254,10 +286,27 @@ func (q *Queries) GetWorkspaceBySlug(ctx context.Context, slug string) (Workspac&i.IssueCounter,&i.AvatarUrl,&i.AttributionFailClosed,+ &i.McpConfig,)return i, err}+const getWorkspaceMcpConfig = `-- name: GetWorkspaceMcpConfig :one+SELECT mcp_config FROM workspace+WHERE id = $1+`++// Lean read of the workspace's shared MCP document for the daemon claim path,+// which resolves it under every agent's own mcp_config on each claim. Kept+// narrow (like GetWorkspaceAttributionFailClosed) so the hot path never drags+// settings/repos/context along. NULL = nothing shared at this layer.+func (q *Queries) GetWorkspaceMcpConfig(ctx context.Context, id pgtype.UUID) ([]byte, error) {+ row := q.db.QueryRow(ctx, getWorkspaceMcpConfig, id)+ var mcp_config []byte+ err := row.Scan(&mcp_config)+ return mcp_config, err+}+const incrementIssueCounter = `-- name: IncrementIssueCounter :oneUPDATE workspace SET issue_counter = issue_counter + 1WHERE id = $1@@ -318,15 +367,31 @@ WHERE m.user_id = $1ORDER BY w.created_at ASC`-func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]Workspace, error) {+type ListWorkspacesRow struct {+ ID pgtype.UUID `json:"id"`+ Name string `json:"name"`+ Slug string `json:"slug"`+ Description pgtype.Text `json:"description"`+ Settings []byte `json:"settings"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ Context pgtype.Text `json:"context"`+ Repos []byte `json:"repos"`+ IssuePrefix string `json:"issue_prefix"`+ IssueCounter int32 `json:"issue_counter"`+ AvatarUrl pgtype.Text `json:"avatar_url"`+ AttributionFailClosed bool `json:"attribution_fail_closed"`+}++func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]ListWorkspacesRow, error) {rows, err := q.db.Query(ctx, listWorkspaces, userID)if err != nil {return nil, err}defer rows.Close()- items := []Workspace{}+ items := []ListWorkspacesRow{}for rows.Next() {- var i Workspace+ var i ListWorkspacesRowif err := rows.Scan(&i.ID,&i.Name,@@ -396,6 +461,60 @@ func (q *Queries) LockWorkspaceForDelete(ctx context.Context, id pgtype.UUID) (preturn id_2, err}+const lockWorkspaceMcpConfig = `-- name: LockWorkspaceMcpConfig :one+SELECT mcp_config FROM workspace+WHERE id = $1+FOR UPDATE+`++// Read-for-update half of the per-server edit path. The shared document is+// never echoed back to clients, so a UI cannot do the read-modify-write+// itself; the server does it instead, and this lock is what keeps two admins+// editing different servers from losing one another's write. Takes only the+// workspace row, so it cannot deadlock against the workspace -> chat_session+// -> agent_task_queue lock order used elsewhere.+func (q *Queries) LockWorkspaceMcpConfig(ctx context.Context, id pgtype.UUID) ([]byte, error) {+ row := q.db.QueryRow(ctx, lockWorkspaceMcpConfig, id)+ var mcp_config []byte+ err := row.Scan(&mcp_config)+ return mcp_config, err+}++const setWorkspaceMcpConfig = `-- name: SetWorkspaceMcpConfig :one+UPDATE workspace SET mcp_config = $2, updated_at = now()+WHERE id = $1+RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed, mcp_config+`++type SetWorkspaceMcpConfigParams struct {+ ID pgtype.UUID `json:"id"`+ McpConfig []byte `json:"mcp_config"`+}++// Writes the shared MCP document. Mirrors the agent column's two-query+// pattern: COALESCE cannot restore NULL, so clearing has its own query below.+func (q *Queries) SetWorkspaceMcpConfig(ctx context.Context, arg SetWorkspaceMcpConfigParams) (Workspace, error) {+ row := q.db.QueryRow(ctx, setWorkspaceMcpConfig, arg.ID, arg.McpConfig)+ var i Workspace+ err := row.Scan(+ &i.ID,+ &i.Name,+ &i.Slug,+ &i.Description,+ &i.Settings,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Context,+ &i.Repos,+ &i.IssuePrefix,+ &i.IssueCounter,+ &i.AvatarUrl,+ &i.AttributionFailClosed,+ &i.McpConfig,+ )+ return i, err+}+const updateWorkspace = `-- name: UpdateWorkspace :oneUPDATE workspace SETname = COALESCE($2, name),@@ -407,7 +526,7 @@ UPDATE workspace SETavatar_url = COALESCE($8, avatar_url),updated_at = now()WHERE id = $1-RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed+RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed, mcp_config`type UpdateWorkspaceParams struct {@@ -447,6 +566,7 @@ func (q *Queries) UpdateWorkspace(ctx context.Context, arg UpdateWorkspaceParams&i.IssueCounter,&i.AvatarUrl,&i.AttributionFailClosed,+ &i.McpConfig,)return i, err}diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sqlindex 0e391b6f0c..87e567b4f9 100644--- a/server/pkg/db/queries/workspace.sql+++ b/server/pkg/db/queries/workspace.sql@@ -39,6 +39,39 @@ WHERE slug = $1;SELECT attribution_fail_closed FROM workspaceWHERE id = $1;+-- name: GetWorkspaceMcpConfig :one+-- Lean read of the workspace's shared MCP document for the daemon claim path,+-- which resolves it under every agent's own mcp_config on each claim. Kept+-- narrow (like GetWorkspaceAttributionFailClosed) so the hot path never drags+-- settings/repos/context along. NULL = nothing shared at this layer.+SELECT mcp_config FROM workspace+WHERE id = $1;++-- name: LockWorkspaceMcpConfig :one+-- Read-for-update half of the per-server edit path. The shared document is+-- never echoed back to clients, so a UI cannot do the read-modify-write+-- itself; the server does it instead, and this lock is what keeps two admins+-- editing different servers from losing one another's write. Takes only the+-- workspace row, so it cannot deadlock against the workspace -> chat_session+-- -> agent_task_queue lock order used elsewhere.+SELECT mcp_config FROM workspace+WHERE id = $1+FOR UPDATE;++-- name: SetWorkspaceMcpConfig :one+-- Writes the shared MCP document. Mirrors the agent column's two-query+-- pattern: COALESCE cannot restore NULL, so clearing has its own query below.+UPDATE workspace SET mcp_config = $2, updated_at = now()+WHERE id = $1+RETURNING *;++-- name: ClearWorkspaceMcpConfig :one+-- Restores the "nothing shared at this layer" state. Every agent that was+-- inheriting falls back to its own mcp_config on its next claim.+UPDATE workspace SET mcp_config = NULL, updated_at = now()+WHERE id = $1+RETURNING *;+-- name: CreateWorkspace :oneINSERT INTO workspace (name, slug, description, context, issue_prefix)VALUES ($1, $2, $3, $4, $5)