Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5421: make workspace MCP servers an explicit per-agent assignment (#6976)
Bohan Jiang2c0912b6ec76
diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex a307827d31..0b218e80eb 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -255,12 +255,13 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| | `avatar <id>` | アバターをアップロード | || | `env get/set <agent-id>` | カスタム環境変数の読み書き(owner と admin のみ) | || | `skills list/set/add <agent-id>` | 紐付けられたスキルを管理 | `--skill-ids`(`set` は全置換、`add` は追加) |+| | `mcp list/add/enable/disable/remove <agent-id>` | ワークスペース MCP サーバーをこのエージェントに割り当て | server id は `workspace mcp list` から取得。ライブラリの項目はここで追加するまで機能しません。`disable` は割り当てを残したまま送信を停止します || `autopilot` | `list/get/create/update/delete` | オートパイロットを管理 | `create`: `--title`、`--agent`、`--mode`(いずれも必須)、`--priority`、`--project`、`--subscriber`(繰り返し可) || | `trigger <id>` | 手動で 1 回トリガー | || | `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 つのサーバーだけを変更 |+| | `mcp list/add/update/remove` | ワークスペースの MCP サーバーライブラリを管理 | 書き込みは owner/admin のみ。ここに追加したサーバーはどのエージェントにも割り当てられません — `multica agent mcp add` で割り当てます。`list` は名前と transport のみを表示し、保存されたエントリは書き込み専用でどのロールにも返りません。`--server-config-file` / `--server-config-stdin` はトークンをシェル履歴から守ります || | `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 2015d964f6..f29d0ca701 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -255,12 +255,13 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| | `avatar <id>` | 아바타 업로드 | || | `env get/set <agent-id>` | 사용자 지정 환경 변수 읽기/쓰기(owner와 admin만) | || | `skills list/set/add <agent-id>` | 연결된 스킬 관리 | `--skill-ids`(`set`은 전체 교체, `add`는 증분 추가) |+| | `mcp list/add/enable/disable/remove <agent-id>` | 워크스페이스 MCP 서버를 이 에이전트에 할당 | server id는 `workspace mcp list`에서 확인. 라이브러리 항목은 여기서 추가하기 전까지 동작하지 않으며, `disable`은 할당을 유지한 채 전달만 중단합니다 || `autopilot` | `list/get/create/update/delete` | 자동화 관리 | `create`: `--title`, `--agent`, `--mode`(모두 필수), `--priority`, `--project`, `--subscriber`(반복 가능) || | `trigger <id>` | 수동으로 한 번 트리거 | || | `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>`은 문서 전체 없이 서버 하나만 변경 |+| | `mcp list/add/update/remove` | 워크스페이스의 MCP 서버 라이브러리를 관리 | 쓰기는 owner/admin 전용. 여기에 추가한 서버는 어떤 에이전트에도 할당되지 않으며 `multica agent mcp add`로 할당합니다. `list`는 이름과 transport만 표시하고, 저장된 항목은 쓰기 전용이라 어떤 역할에도 반환되지 않습니다. `--server-config-file` / `--server-config-stdin`은 토큰이 셸 기록에 남지 않게 합니다 || | `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 1a80f29c9e..d7ed3bca66 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -276,12 +276,13 @@ The tables below cover every current top-level command, grouped the way the CLI| | `avatar <id>` | Upload an avatar | || | `env get/set <agent-id>` | Read and write custom environment variables (owner and admin only) | || | `skills list/set/add <agent-id>` | Manage attached skills | `--skill-ids` (`set` replaces the full list, `add` appends) |+| | `mcp list/add/enable/disable/remove <agent-id>` | Assign workspace MCP servers to this agent | Take the server id from `workspace mcp list`. A library entry does nothing until it is added here; `disable` stops sending it without dropping the assignment || `autopilot` | `list/get/create/update/delete` | Manage automations | `create`: `--title`, `--agent`, `--mode` (all required), `--priority`, `--project`, `--subscriber` (repeatable) || | `trigger <id>` | Trigger a run manually | || | `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 |+| | `mcp list/add/update/remove` | Manage the workspace's MCP server library | Writes are owner/admin. A server added here is assigned to no agent — give it to one with `multica agent mcp add`. `list` shows names and transports only; the stored entry is write-only and never returned. `--server-config-file` / `--server-config-stdin` keep tokens out of shell history || | `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 8371ca8e38..cc2333ff8c 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -255,12 +255,13 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| | `avatar <id>` | 上传头像 | || | `env get/set <agent-id>` | 读写自定义环境变量(仅 owner 和 admin) | || | `skills list/set/add <agent-id>` | 管理绑定的 skill | `--skill-ids`(`set` 全量替换,`add` 增量添加) |+| | `mcp list/add/enable/disable/remove <agent-id>` | 给该 agent 分配工作区 MCP 服务 | server id 从 `workspace mcp list` 获取。库里的条目在这里添加之前不会生效;`disable` 只停止下发,保留分配 || `autopilot` | `list/get/create/update/delete` | 管理自动化 | `create`:`--title`、`--agent`、`--mode`(均必填)、`--priority`、`--project`、`--subscriber`(可重复) || | `trigger <id>` | 手动触发一次 | || | `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>` 无需持有整份文档即可改动单个服务 |+| | `mcp list/add/update/remove` | 管理工作区的 MCP 服务库 | 写操作需要 owner/admin。这里添加的服务不会分配给任何 agent——用 `multica agent mcp add` 分配给某个 agent。`list` 只列出名称与 transport;存储的条目是只写的,任何角色都读不回。`--server-config-file` / `--server-config-stdin` 避免 token 进入 shell 历史 || | `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 b5a4fdc693..60c9fe2381 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -2069,7 +2069,7 @@ describe("ApiClient refreshSkill response schema", () => {});});-describe("ApiClient workspace MCP configuration", () => {+describe("ApiClient workspace MCP servers", () => {function stubJSON(body: unknown) {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(body), {@@ -2081,97 +2081,118 @@ describe("ApiClient workspace MCP configuration", () => {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 server = {+ id: "srv-1",+ workspace_id: "ws-1",+ name: "linear",+ transport: "http",+ created_at: "2026-08-14T00:00:00Z",+ updated_at: "2026-08-14T00:00:00Z",+ };++ it("parses the workspace library", async () => {+ stubJSON([server]);const result = await new ApiClient("https://api.example.test")- .getWorkspaceMcpConfig("ws-1");+ .listWorkspaceMcpServers("ws-1");- expect(result.server_count).toBe(1);- expect(result.servers[0]).toMatchObject({ name: "linear", transport: "http" });+ expect(result).toHaveLength(1);+ expect(result[0]).toMatchObject({ id: "srv-1", name: "linear", transport: "http" });+ // No binding in the library listing, so no toggle to report.+ expect(result[0]?.enabled).toBeUndefined();});- // 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,- });+ it("falls back safely when the library response is malformed", async () => {+ stubJSON({ nope: true });const result = await new ApiClient("https://api.example.test")- .getWorkspaceMcpConfig("ws-1");+ .listWorkspaceMcpServers("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,- });+ expect(result).toEqual([]);});- it("falls back safely when the inventory response is malformed", async () => {- stubJSON({ workspace_id: 42, servers: "not-an-array" });+ // The write-only boundary is enforced on the client too: a server that+ // regressed to returning the stored entry must not have it land in the+ // parsed object or the query cache.+ it("strips secret-bearing fields the server should never have sent", async () => {+ stubJSON([{+ ...server,+ config: { headers: { Authorization: "Bearer sk-live-doc" } },+ url: "https://mcp.example/sk-live-url",+ headers: { Authorization: "Bearer sk-live-header" },+ }]);const result = await new ApiClient("https://api.example.test")- .getWorkspaceMcpConfig("ws-1");+ .listWorkspaceMcpServers("ws-1");- expect(result).toEqual({ workspace_id: "", servers: [], server_count: 0 });+ expect(JSON.stringify(result)).not.toContain("sk-live");+ expect(result[0]).toEqual(server);});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,- });+ stubJSON([{ ...server, transport: "websocket" }]);const result = await new ApiClient("https://api.example.test")- .getWorkspaceMcpConfig("ws-1");+ .listWorkspaceMcpServers("ws-1");- expect(result.servers).toHaveLength(1);- expect(result.servers[0]?.transport).toBe("websocket");+ expect(result).toHaveLength(1);+ expect(result[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 });+ it("POSTs a name and entry when creating a library server", async () => {+ const fetchMock = stubJSON(server);await new ApiClient("https://api.example.test")- .upsertWorkspaceMcpServer("ws-1", "my server", { url: "https://mcp.example" });+ .createWorkspaceMcpServer("ws-1", "linear", { 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" });+ expect(url).toContain("/api/workspaces/ws-1/mcp-servers");+ expect(init.method).toBe("POST");+ expect(JSON.parse(String(init.body))).toEqual({+ name: "linear",+ config: { url: "https://mcp.example" },+ });});- it("DELETEs one server by name", async () => {- const fetchMock = stubJSON({ workspace_id: "ws-1", servers: [], server_count: 0 });+ it("sends only what changed when updating a library server", async () => {+ const fetchMock = stubJSON(server);await new ApiClient("https://api.example.test")- .deleteWorkspaceMcpServer("ws-1", "linear");+ .updateWorkspaceMcpServer("ws-1", "srv-1", { name: "linear-v2" });const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];- expect(url).toContain("/api/workspaces/ws-1/mcp-config/servers/linear");+ expect(url).toContain("/api/workspaces/ws-1/mcp-servers/srv-1");+ expect(init.method).toBe("PUT");+ // A rename must not blank the stored entry.+ expect(JSON.parse(String(init.body))).toEqual({ name: "linear-v2" });+ });++ it("assigns and un-assigns a server on the agent routes", async () => {+ const assigned = [{ ...server, enabled: true }];+ let fetchMock = stubJSON(assigned);++ const added = await new ApiClient("https://api.example.test")+ .addAgentMcpServer("agent-1", "srv-1");+ expect(added[0]?.enabled).toBe(true);+ let [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(url).toContain("/api/agents/agent-1/mcp-servers");+ expect(init.method).toBe("POST");+ expect(JSON.parse(String(init.body))).toEqual({ server_id: "srv-1" });++ fetchMock = stubJSON([{ ...server, enabled: false }]);+ const toggled = await new ApiClient("https://api.example.test")+ .setAgentMcpServerEnabled("agent-1", "srv-1", false);+ expect(toggled[0]?.enabled).toBe(false);+ [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(url).toContain("/api/agents/agent-1/mcp-servers/srv-1/enabled");+ expect(init.method).toBe("PUT");++ fetchMock = stubJSON([]);+ await new ApiClient("https://api.example.test").removeAgentMcpServer("agent-1", "srv-1");+ [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(url).toContain("/api/agents/agent-1/mcp-servers/srv-1");expect(init.method).toBe("DELETE");});});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex a1d4854c05..746106d999 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -50,7 +50,7 @@ import type {IssueReaction,Workspace,WorkspaceRepo,- WorkspaceMcpConfig,+ WorkspaceMcpServer,MemberWithUser,User,Skill,@@ -372,12 +372,13 @@ import {EMPTY_ISSUE_VIEW_PREFERENCE,EMPTY_PLUGIN_CATALOG,EMPTY_PLUGIN_INSTALLATION,- EMPTY_WORKSPACE_MCP_CONFIG,+ EMPTY_WORKSPACE_MCP_SERVER,EMPTY_PLUGIN_INSTALLATION_LIST,PluginCatalogResponseSchema,PluginInstallationListResponseSchema,PluginInstallationSchema,- WorkspaceMcpConfigSchema,+ WorkspaceMcpServerListSchema,+ WorkspaceMcpServerSchema,type IssueView,type IssueViewPreference,type CreateIssueViewRequest,@@ -2290,44 +2291,104 @@ 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.+ * The workspace's MCP server library. The response carries identity and+ * transport only — the stored entries are 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",+ async listWorkspaceMcpServers(workspaceId: string): Promise<WorkspaceMcpServer[]> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/mcp-servers`);+ return parseWithFallback(raw, WorkspaceMcpServerListSchema, [] as WorkspaceMcpServer[], {+ endpoint: "GET /api/workspaces/{id}/mcp-servers",});}/**- * 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.+ * Adds a server to the library. It is assigned to NO agent — an agent gets+ * it only through addAgentMcpServer.*/- async upsertWorkspaceMcpServer(+ async createWorkspaceMcpServer(workspaceId: string,name: string,- entry: Record<string, unknown>,- ): Promise<WorkspaceMcpConfig> {+ config: Record<string, unknown>,+ ): Promise<WorkspaceMcpServer> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/mcp-servers`, {+ method: "POST",+ body: JSON.stringify({ name, config }),+ });+ return parseWithFallback(raw, WorkspaceMcpServerSchema, EMPTY_WORKSPACE_MCP_SERVER, {+ endpoint: "POST /api/workspaces/{id}/mcp-servers",+ });+ }++ /**+ * Renames a library entry, replaces its configuration, or both. Agents keep+ * their assignment across a rename because assignments key off the id.+ */+ async updateWorkspaceMcpServer(+ workspaceId: string,+ serverId: string,+ update: { name?: string; config?: Record<string, unknown> },+ ): Promise<WorkspaceMcpServer> {+ const raw = await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/mcp-servers/${encodeURIComponent(serverId)}`,+ { method: "PUT", body: JSON.stringify(update) },+ );+ return parseWithFallback(raw, WorkspaceMcpServerSchema, EMPTY_WORKSPACE_MCP_SERVER, {+ endpoint: "PUT /api/workspaces/{id}/mcp-servers/{serverId}",+ });+ }++ /** Removes a library entry and every assignment to it. */+ async deleteWorkspaceMcpServer(workspaceId: string, serverId: string): Promise<void> {+ await this.fetch<unknown>(+ `/api/workspaces/${workspaceId}/mcp-servers/${encodeURIComponent(serverId)}`,+ { method: "DELETE" },+ );+ }++ /** The workspace MCP servers assigned to this agent, with their toggles. */+ async listAgentMcpServers(agentId: string): Promise<WorkspaceMcpServer[]> {+ const raw = await this.fetch<unknown>(`/api/agents/${agentId}/mcp-servers`);+ return parseWithFallback(raw, WorkspaceMcpServerListSchema, [] as WorkspaceMcpServer[], {+ endpoint: "GET /api/agents/{id}/mcp-servers",+ });+ }++ /**+ * Gives one workspace server to this agent. Every write returns the+ * resulting assignment list, so the client never has to guess the state.+ */+ async addAgentMcpServer(agentId: string, serverId: string): Promise<WorkspaceMcpServer[]> {+ const raw = await this.fetch<unknown>(`/api/agents/${agentId}/mcp-servers`, {+ method: "POST",+ body: JSON.stringify({ server_id: serverId }),+ });+ return parseWithFallback(raw, WorkspaceMcpServerListSchema, [] as WorkspaceMcpServer[], {+ endpoint: "POST /api/agents/{id}/mcp-servers",+ });+ }++ async setAgentMcpServerEnabled(+ agentId: string,+ serverId: string,+ enabled: boolean,+ ): Promise<WorkspaceMcpServer[]> {const raw = await this.fetch<unknown>(- `/api/workspaces/${workspaceId}/mcp-config/servers/${encodeURIComponent(name)}`,- { method: "PUT", body: JSON.stringify(entry) },+ `/api/agents/${agentId}/mcp-servers/${encodeURIComponent(serverId)}/enabled`,+ { method: "PUT", body: JSON.stringify({ enabled }) },);- return parseWithFallback(raw, WorkspaceMcpConfigSchema, EMPTY_WORKSPACE_MCP_CONFIG, {- endpoint: "PUT /api/workspaces/{id}/mcp-config/servers/{name}",+ return parseWithFallback(raw, WorkspaceMcpServerListSchema, [] as WorkspaceMcpServer[], {+ endpoint: "PUT /api/agents/{id}/mcp-servers/{serverId}/enabled",});}- /** Removes one shared MCP server; removing the last one clears the layer. */- async deleteWorkspaceMcpServer(workspaceId: string, name: string): Promise<WorkspaceMcpConfig> {+ async removeAgentMcpServer(agentId: string, serverId: string): Promise<WorkspaceMcpServer[]> {const raw = await this.fetch<unknown>(- `/api/workspaces/${workspaceId}/mcp-config/servers/${encodeURIComponent(name)}`,+ `/api/agents/${agentId}/mcp-servers/${encodeURIComponent(serverId)}`,{ method: "DELETE" },);- return parseWithFallback(raw, WorkspaceMcpConfigSchema, EMPTY_WORKSPACE_MCP_CONFIG, {- endpoint: "DELETE /api/workspaces/{id}/mcp-config/servers/{name}",+ return parseWithFallback(raw, WorkspaceMcpServerListSchema, [] as WorkspaceMcpServer[], {+ endpoint: "DELETE /api/agents/{id}/mcp-servers/{serverId}",});}diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 7d61301f60..a977920b96 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -70,7 +70,7 @@ import type {TimelineEntry,User,WebhookDelivery,- WorkspaceMcpConfig,+ WorkspaceMcpServer,} from "../types";import type { CloudRuntimeNode } from "../runtimes/cloud-runtime";import type { CreateFeedbackResponse } from "../feedback/types";@@ -2569,32 +2569,35 @@ export const EMPTY_SKILL: Skill = {};/**- * Read shape of the workspace's shared MCP configuration.+ * Read shape of one workspace MCP server.*- * 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.+ * This is the ONLY schema 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+ * stored entry (or a `url` / `headers` on the summary) 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 summary.** `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({+ id: z.string().default(""),+ workspace_id: z.string().default(""),name: z.string().default(""),transport: z.string().default("unknown"),- enabled: z.boolean().default(true),+ enabled: z.boolean().optional(),+ created_at: z.string().default(""),+ updated_at: z.string().default(""),});-export const WorkspaceMcpConfigSchema = z.object({- workspace_id: z.string().default(""),- servers: z.array(WorkspaceMcpServerSchema).default([]),- server_count: z.number().default(0),-});+export const WorkspaceMcpServerListSchema = z.array(WorkspaceMcpServerSchema);-export const EMPTY_WORKSPACE_MCP_CONFIG: WorkspaceMcpConfig = {+export const EMPTY_WORKSPACE_MCP_SERVER: WorkspaceMcpServer = {+ id: "",workspace_id: "",- servers: [],- server_count: 0,+ name: "",+ transport: "unknown",+ created_at: "",+ updated_at: "",};diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 6d9550ba52..851e925fa3 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, WorkspaceMcpServer, WorkspaceMcpConfig, Member, MemberRole, User, MemberWithUser, Invitation } from "./workspace";+export type { Workspace, WorkspaceRepo, WorkspaceMcpServer, 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 f8363c798b..5f94b1c324 100644--- a/packages/core/types/workspace.ts+++ b/packages/core/types/workspace.ts@@ -20,24 +20,24 @@ export interface Workspace {}/**- * One MCP server shared by the workspace, as returned by- * `GET /api/workspaces/{id}/mcp-config`.+ * One MCP server in the workspace's library.** 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.+ *+ * `enabled` is only present on an AGENT's assignment list, where it is the+ * per-agent toggle; the workspace library listing has no binding to report.*/export interface WorkspaceMcpServer {+ id: string;+ workspace_id: string;name: string;transport: string;- enabled: boolean;-}--export interface WorkspaceMcpConfig {- workspace_id: string;- servers: WorkspaceMcpServer[];- server_count: number;+ enabled?: boolean;+ created_at: string;+ updated_at: string;}export interface Member {diff --git a/packages/core/workspace/mutations.ts b/packages/core/workspace/mutations.tsindex 9f442296c7..f8d11f46e5 100644--- a/packages/core/workspace/mutations.ts+++ b/packages/core/workspace/mutations.ts@@ -89,25 +89,72 @@ 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.+ * Adds a server to the workspace library. It is assigned to no agent: an+ * agent owner gives it to their agent separately.*/-export function useUpsertWorkspaceMcpServer(wsId: string) {+export function useCreateWorkspaceMcpServer(wsId: string) {const queryClient = useQueryClient();return useMutation({- mutationFn: ({ name, entry }: { name: string; entry: Record<string, unknown> }) =>- api.upsertWorkspaceMcpServer(wsId, name, entry),+ mutationFn: ({ name, config }: { name: string; config: Record<string, unknown> }) =>+ api.createWorkspaceMcpServer(wsId, name, config),onSettled: () =>- queryClient.invalidateQueries({ queryKey: workspaceKeys.mcpConfig(wsId) }),+ queryClient.invalidateQueries({ queryKey: workspaceKeys.mcpServers(wsId) }),+ });+}++export function useUpdateWorkspaceMcpServer(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: ({ serverId, ...update }: {+ serverId: string;+ name?: string;+ config?: Record<string, unknown>;+ }) => api.updateWorkspaceMcpServer(wsId, serverId, update),+ onSettled: () =>+ queryClient.invalidateQueries({ queryKey: workspaceKeys.mcpServers(wsId) }),});}export function useDeleteWorkspaceMcpServer(wsId: string) {const queryClient = useQueryClient();return useMutation({- mutationFn: (name: string) => api.deleteWorkspaceMcpServer(wsId, name),+ mutationFn: (serverId: string) => api.deleteWorkspaceMcpServer(wsId, serverId),+ onSettled: () => {+ queryClient.invalidateQueries({ queryKey: workspaceKeys.mcpServers(wsId) });+ // Deleting a library entry drops it from every agent that had it, so+ // no agent's assignment list can be trusted afterwards.+ queryClient.invalidateQueries({ queryKey: ["agents"] });+ },+ });+}++/**+ * Assignment writes all return the agent's resulting list, so the cache is+ * updated from the server's answer rather than a guess.+ */+function useAgentMcpMutation<TVariables>(+ agentId: string,+ mutationFn: (variables: TVariables) => Promise<unknown>,+) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn,onSettled: () =>- queryClient.invalidateQueries({ queryKey: workspaceKeys.mcpConfig(wsId) }),+ queryClient.invalidateQueries({ queryKey: ["agents", agentId, "mcp-servers"] }),});}++export function useAddAgentMcpServer(agentId: string) {+ return useAgentMcpMutation(agentId, (serverId: string) =>+ api.addAgentMcpServer(agentId, serverId));+}++export function useSetAgentMcpServerEnabled(agentId: string) {+ return useAgentMcpMutation(agentId, ({ serverId, enabled }: { serverId: string; enabled: boolean }) =>+ api.setAgentMcpServerEnabled(agentId, serverId, enabled));+}++export function useRemoveAgentMcpServer(agentId: string) {+ return useAgentMcpMutation(agentId, (serverId: string) =>+ api.removeAgentMcpServer(agentId, serverId));+}diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.tsindex d883c9e31a..cd44e238db 100644--- a/packages/core/workspace/queries.ts+++ b/packages/core/workspace/queries.ts@@ -17,7 +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,+ mcpServers: (wsId: string) => ["workspaces", wsId, "mcp-servers"] as const,};export function workspaceListOptions() {@@ -137,14 +137,23 @@ export function assigneeFrequencyOptions(wsId: string) {}/**- * 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.+ * The workspace's MCP server library. Fetched for plain members too — the+ * payload is names and transports only, and an agent owner needs to see what+ * is available to assign.*/-export function workspaceMcpConfigOptions(wsId: string) {+export function workspaceMcpServersOptions(wsId: string) {return queryOptions({- queryKey: workspaceKeys.mcpConfig(wsId),- queryFn: () => api.getWorkspaceMcpConfig(wsId),+ queryKey: workspaceKeys.mcpServers(wsId),+ queryFn: () => api.listWorkspaceMcpServers(wsId),enabled: wsId !== "",});}++/** The workspace MCP servers assigned to one agent, with their toggles. */+export function agentMcpServersOptions(agentId: string) {+ return queryOptions({+ queryKey: ["agents", agentId, "mcp-servers"] as const,+ queryFn: () => api.listAgentMcpServers(agentId),+ enabled: agentId !== "",+ });+}diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsxindex 42bdf765e3..e99f5cbf1f 100644--- a/packages/views/agents/components/agent-overview-pane.tsx+++ b/packages/views/agents/components/agent-overview-pane.tsx@@ -437,6 +437,7 @@ export function AgentOverviewPane({<McpConfigTabagent={agent}runtime={runtime}+ canEdit={canEdit}onSave={(updates) => onUpdate(agent.id, updates)}onDirtyChange={setActiveDirty}/>diff --git a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx b/packages/views/agents/components/tabs/mcp-config-tab.test.tsxindex d1a546808e..d081655abc 100644--- a/packages/views/agents/components/tabs/mcp-config-tab.test.tsx+++ b/packages/views/agents/components/tabs/mcp-config-tab.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdomimport { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen } from "@testing-library/react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { Agent, AgentRuntime } from "@multica/core/types";@@ -14,20 +14,48 @@ import { McpConfigTab } from "./mcp-config-tab";const TEST_RESOURCES = { en: { common: enCommon, agents: enAgents } };const mockRuntimeCapabilities = vi.hoisted(() => vi.fn());+const mockAddServer = vi.hoisted(() => vi.fn());+const mockSetEnabled = vi.hoisted(() => vi.fn());+const mockRemoveServer = vi.hoisted(() => vi.fn());+const workspaceMcp = vi.hoisted(() => ({- data: { workspace_id: "ws-1", servers: [] as Array<Record<string, unknown>>, server_count: 0 },+ // Servers ASSIGNED to this agent, and the workspace library to pick from.+ assigned: [] as Array<Record<string, unknown>>,+ library: [] as Array<Record<string, unknown>>,}));-// 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.+// The workspace section reads the agent's assignments plus the library.+// Stubbing the query options keeps this a pure render test — the real ones+// would hit fetch.vi.mock("@multica/core/workspace/queries", () => ({- workspaceMcpConfigOptions: (wsId: string) => ({- queryKey: ["workspaces", wsId, "mcp-config"],- queryFn: () => Promise.resolve(workspaceMcp.data),+ agentMcpServersOptions: (agentId: string) => ({+ queryKey: ["agents", agentId, "mcp-servers"],+ queryFn: () => Promise.resolve(workspaceMcp.assigned),+ enabled: agentId !== "",+ }),+ workspaceMcpServersOptions: (wsId: string) => ({+ queryKey: ["workspaces", wsId, "mcp-servers"],+ queryFn: () => Promise.resolve(workspaceMcp.library),enabled: wsId !== "",}),}));+vi.mock("@multica/core/workspace/mutations", () => ({+ useAddAgentMcpServer: () => ({ mutateAsync: mockAddServer, isPending: false }),+ useSetAgentMcpServerEnabled: () => ({ mutateAsync: mockSetEnabled, isPending: false }),+ useRemoveAgentMcpServer: () => ({ mutateAsync: mockRemoveServer, isPending: false }),+}));++const wsServer = (over: Record<string, unknown>) => ({+ id: "srv-1",+ workspace_id: "ws-1",+ name: "shared-linear",+ transport: "http",+ created_at: "2026-08-14T00:00:00Z",+ updated_at: "2026-08-14T00:00:00Z",+ ...over,+});+// The tab reads discovery through runtimeCapabilitiesOptions; existing tests// render with runtime={null} so the query stays disabled and never fires.vi.mock("@multica/core/runtimes", async () => {@@ -127,7 +155,11 @@ const onlineRuntime: AgentRuntime = {describe("McpConfigTab", () => {beforeEach(() => {vi.clearAllMocks();- workspaceMcp.data = { workspace_id: "ws-1", servers: [], server_count: 0 };+ workspaceMcp.assigned = [];+ workspaceMcp.library = [];+ mockAddServer.mockResolvedValue([]);+ mockSetEnabled.mockResolvedValue([]);+ mockRemoveServer.mockResolvedValue([]);});it("renders redacted managed MCP without exposing add or edit controls", () => {@@ -315,33 +347,79 @@ describe("McpConfigTab", () => {});});-// 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", () => {+// The workspace layer (GH #6062) reaches an agent only when someone assigns+// it, so the tab has to show what is assigned, let an owner assign more, and+// never imply an unassigned library entry is in play.+describe("McpConfigTab workspace servers", () => {beforeEach(() => {vi.clearAllMocks();- workspaceMcp.data = { workspace_id: "ws-1", servers: [], server_count: 0 };+ workspaceMcp.assigned = [];+ workspaceMcp.library = [];+ mockAddServer.mockResolvedValue([]);+ mockSetEnabled.mockResolvedValue([]);+ mockRemoveServer.mockResolvedValue([]);});- 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,- };+ it("lists the workspace servers assigned to this agent", async () => {+ workspaceMcp.assigned = [wsServer({ enabled: true })];renderTab({ mcp_config: null });expect(await screen.findByText("shared-linear")).toBeInTheDocument();- expect(screen.getByText(/Inherited from workspace/)).toBeInTheDocument();+ expect(screen.getByText(/From the workspace library/)).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,- };+ // The defining property of this model: a library entry nobody assigned must+ // not appear as if the agent had it.+ it("does not show unassigned library servers as the agent's", async () => {+ workspaceMcp.library = [wsServer({ name: "not-assigned" })];+ renderTab({ mcp_config: null });++ expect(+ await screen.findByText(/No workspace MCP servers assigned/),+ ).toBeInTheDocument();+ expect(screen.queryByText("not-assigned")).toBeNull();+ });++ it("assigns a library server through the picker", async () => {+ const user = userEvent.setup();+ workspaceMcp.library = [wsServer({ id: "srv-9", name: "pickable" })];+ renderTab({ mcp_config: null });++ await user.click(await screen.findByRole("button", { name: /Add from workspace/ }));+ await user.click(await screen.findByRole("menuitem", { name: /pickable/ }));++ await waitFor(() => expect(mockAddServer).toHaveBeenCalledWith("srv-9"));+ });++ it("toggles an assignment off without dropping it", async () => {+ const user = userEvent.setup();+ workspaceMcp.assigned = [wsServer({ enabled: true })];+ renderTab({ mcp_config: null });++ await user.click(+ await screen.findByRole("switch", { name: /Enable shared-linear/i }),+ );++ await waitFor(() =>+ expect(mockSetEnabled).toHaveBeenCalledWith({ serverId: "srv-1", enabled: false }),+ );+ expect(mockRemoveServer).not.toHaveBeenCalled();+ });++ it("removes an assignment", async () => {+ const user = userEvent.setup();+ workspaceMcp.assigned = [wsServer({ enabled: true })];+ renderTab({ mcp_config: null });++ await user.click(+ await screen.findByRole("button", { name: /Remove shared-linear/i }),+ );++ await waitFor(() => expect(mockRemoveServer).toHaveBeenCalledWith("srv-1"));+ });++ it("marks an assigned server the agent overrides by name", async () => {+ workspaceMcp.assigned = [wsServer({ name: "linear", enabled: true })];renderTab({mcp_config: { mcpServers: { linear: { url: "https://agent.example" } } },});@@ -349,83 +427,78 @@ describe("McpConfigTab workspace inheritance", () => {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: {} });+ // A member without edit rights can still read what the agent runs with —+ // the inventory carries no credential material — but every write affordance+ // is hidden rather than left to 403 on click.+ it("hides the assignment controls from a viewer who cannot edit", async () => {+ workspaceMcp.assigned = [wsServer({ enabled: true })];+ workspaceMcp.library = [wsServer({ id: "srv-9", name: "pickable" })];+ render(+ <TestShell>+ <McpConfigTab+ agent={baseAgent}+ runtime={null}+ canEdit={false}+ onSave={vi.fn()}+ />+ </TestShell>,+ );- 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();+ expect(await screen.findByText("shared-linear")).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /Add from workspace/ })).toBeNull();+ expect(screen.queryByRole("switch")).toBeNull();+ expect(screen.queryByRole("button", { name: /Remove shared-linear/i })).toBeNull();});- it("renders an empty state when the workspace shares nothing", async () => {+ it("points at workspace Settings when the library is empty", async () => {renderTab({ mcp_config: null });expect(- await screen.findByText(/workspace shares no MCP servers/),+ await screen.findByText(/no MCP servers to assign yet/i),).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.+// The runtime section's Overridden badge has to reflect the REAL precedence:+// runtime < (assigned workspace servers + the agent's own).describe("McpConfigTab effective set", () => {beforeEach(() => {vi.clearAllMocks();- workspaceMcp.data = { workspace_id: "ws-1", servers: [], server_count: 0 };+ workspaceMcp.assigned = [];+ workspaceMcp.library = [];});- 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,- };+ it("marks a runtime server shadowed by an assigned server as overridden", async () => {+ workspaceMcp.assigned = [wsServer({ name: "fetch", enabled: true })];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,- };+ // A switched-off assignment is not sent, so it shadows nothing.+ it("does not mark a runtime server overridden by a disabled assignment", async () => {+ workspaceMcp.assigned = [wsServer({ name: "fetch", enabled: false })];mockRuntimeCapabilities.mockResolvedValue({mcpSupported: true,mcpServers: [{ name: "fetch", transport: "stdio", enabled: true, source: "runtime" }],});- renderTab({ mcp_config: {} }, vi.fn(), onlineRuntime);+ renderTab({ mcp_config: null }, vi.fn(), onlineRuntime);- expect(- await screen.findByText(/inherits none of the workspace/i),- ).toBeInTheDocument();+ // "fetch" renders twice — once as the (disabled) assignment, once as the+ // runtime's own server — which is exactly the state under test.+ await waitFor(() => expect(screen.getAllByText("fetch")).toHaveLength(2));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.+ // Same transport hazard as before, reached through the SAVED config: the+ // form emits `type: "http"`, so neither entry may be editable through it.+ // `websocket` is the one that catches using mcpTransport() for this.it.each([["sse", { type: "sse", url: "https://sse.example" }],["websocket", { type: "websocket", url: "wss://example.test" }],@@ -466,20 +539,4 @@ describe("McpConfigTab effective set", () => {"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 fd0b63b8de..b7641cdc35 100644--- a/packages/views/agents/components/tabs/mcp-config-tab.tsx+++ b/packages/views/agents/components/tabs/mcp-config-tab.tsx@@ -11,13 +11,21 @@ import {Trash2,} from "lucide-react";import { useQuery } from "@tanstack/react-query";-import type { Agent, AgentRuntime } from "@multica/core/types";+import type { Agent, AgentRuntime, WorkspaceMcpServer } from "@multica/core/types";import { ApiError } from "@multica/core/api";import {runtimeCapabilitiesOptions,runtimeDisplayLabel,} from "@multica/core/runtimes";-import { workspaceMcpConfigOptions } from "@multica/core/workspace/queries";+import {+ agentMcpServersOptions,+ workspaceMcpServersOptions,+} from "@multica/core/workspace/queries";+import {+ useAddAgentMcpServer,+ useRemoveAgentMcpServer,+ useSetAgentMcpServerEnabled,+} from "@multica/core/workspace/mutations";import {AlertDialog,AlertDialogAction,@@ -30,6 +38,13 @@ import {} from "@multica/ui/components/ui/alert-dialog";import { Badge } from "@multica/ui/components/ui/badge";import { Button } from "@multica/ui/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { Switch } from "@multica/ui/components/ui/switch";import { toast } from "sonner";import { useT } from "../../../i18n";import {@@ -43,11 +58,18 @@ import { McpServerDialog } from "./mcp-server-dialog";export function McpConfigTab({agent,runtime,+ canEdit = true,onSave,onDirtyChange,}: {agent: Agent;runtime: AgentRuntime | null;+ /**+ * Whether this viewer may change the agent. A member without it can still+ * read the inventory — it carries no credential material — but every write+ * affordance is hidden rather than left to 403 on click.+ */+ canEdit?: boolean;onSave: (updates: { mcp_config: unknown | null }) => Promise<void>;onDirtyChange?: (dirty: boolean) => void;}) {@@ -57,12 +79,17 @@ 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 ?? ""),+ // The workspace MCP servers ASSIGNED to this agent, plus the library to pick+ // from (GH #6062). A library entry does nothing until it is added here, and+ // each assignment carries its own toggle. The API returns names and+ // transports only — never the stored credentials.+ const assignedQuery = useQuery(agentMcpServersOptions(agent.id));+ const libraryQuery = useQuery(+ workspaceMcpServersOptions(agent.workspace_id ?? ""),);+ const addServer = useAddAgentMcpServer(agent.id);+ const setServerEnabled = useSetAgentMcpServerEnabled(agent.id);+ const removeServer = useRemoveAgentMcpServer(agent.id);const redacted = agent.mcp_config_redacted === true;const managedServers = useMemo(() => listManagedMcpServers(agent.mcp_config),@@ -72,30 +99,28 @@ 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;+ const assignedServers = assignedQuery.data ?? [];+ const assignedIds = useMemo(+ () => new Set(assignedServers.map((server) => server.id)),+ [assignedServers],+ );+ // What is still available to assign. An entry the agent already has is not+ // offered again.+ const availableServers = (libraryQuery.data ?? []).filter(+ (server) => !assignedIds.has(server.id),+ );// 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.+ // runtime < (assigned workspace servers + the agent's own), so an assigned+ // server hides a same-named runtime one too — marking only the agent's own+ // names would under-report it. A disabled assignment shadows nothing.const effectiveNames = useMemo(() => {const names = new Set(managedNames);- if (inheritsWorkspace) {- for (const server of workspaceServers) names.add(server.name);+ for (const server of assignedServers) {+ if (server.enabled !== false) names.add(server.name);}return names;- }, [managedNames, inheritsWorkspace, workspaceServers]);+ }, [managedNames, assignedServers]);+const [editorOpen, setEditorOpen] = useState(false);const [editingServer, setEditingServer] = useState<ManagedMcpServer | null>(null,@@ -143,6 +168,35 @@ export function McpConfigTab({}};+ // Assignment writes return the agent's resulting list, so failures surface+ // as a toast and the cache re-syncs from the server rather than a guess.+ const runAssignmentAction = async (action: () => Promise<unknown>) => {+ try {+ await action();+ } catch (error) {+ toast.error(+ error instanceof Error && error.message+ ? error.message+ : t(($) => $.tab_body.mcp_config.workspace_action_failed),+ );+ }+ };++ const handleAddWorkspaceServer = (serverId: string) =>+ runAssignmentAction(async () => {+ await addServer.mutateAsync(serverId);+ toast.success(t(($) => $.tab_body.mcp_config.workspace_added_toast));+ });++ const handleToggleWorkspaceServer = (serverId: string, enabled: boolean) =>+ runAssignmentAction(() => setServerEnabled.mutateAsync({ serverId, enabled }));++ const handleRemoveWorkspaceServer = (serverId: string) =>+ runAssignmentAction(async () => {+ await removeServer.mutateAsync(serverId);+ toast.success(t(($) => $.tab_body.mcp_config.workspace_removed_toast));+ });+const handleDelete = async () => {if (!deletingServer) return;setDeleting(true);@@ -217,35 +271,49 @@ 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 className="flex items-start justify-between gap-4">+ <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>+ {canEdit && availableServers.length > 0 && (+ <McpWorkspaceServerPicker+ servers={availableServers}+ disabled={addServer.isPending}+ onSelect={(serverId) => void handleAddWorkspaceServer(serverId)}+ />+ )}</div>- {redacted ? (- <McpNotice text={t(($) => $.tab_body.mcp_config.workspace_unknown)} />- ) : optedOutOfWorkspace ? (- <McpNotice text={t(($) => $.tab_body.mcp_config.workspace_opted_out)} />- ) : workspaceMcpQuery.isLoading ? (+ {assignedQuery.isLoading ? (<McpNoticeloadingtext={t(($) => $.tab_body.mcp_config.workspace_loading)}/>- ) : workspaceServers.length === 0 ? (- <McpNotice text={t(($) => $.tab_body.mcp_config.workspace_empty)} />+ ) : assignedServers.length > 0 ? (+ <ul className="divide-y divide-surface-border rounded-lg border">+ {assignedServers.map((server) => (+ <McpWorkspaceServerRow+ key={server.id}+ server={server}+ overridden={managedNames.has(server.name)}+ canEdit={canEdit}+ busy={setServerEnabled.isPending || removeServer.isPending}+ onToggle={(enabled) => void handleToggleWorkspaceServer(server.id, enabled)}+ onRemove={() => void handleRemoveWorkspaceServer(server.id)}+ />+ ))}+ </ul>) : (- <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)}+ <McpNotice+ text={+ (libraryQuery.data ?? []).length === 0+ ? t(($) => $.tab_body.mcp_config.workspace_library_empty)+ : t(($) => $.tab_body.mcp_config.workspace_none_assigned)+ }/>)}</section>@@ -377,6 +445,111 @@ type McpServerView = {overridden?: boolean;};+/**+ * One workspace server assigned to this agent: the per-agent toggle plus the+ * affordance to take it away. The entry itself is never shown — it is+ * write-only and lives in workspace Settings.+ */+function McpWorkspaceServerRow({+ server,+ overridden,+ canEdit,+ busy,+ onToggle,+ onRemove,+}: {+ server: WorkspaceMcpServer;+ overridden: boolean;+ canEdit: boolean;+ busy: boolean;+ onToggle: (enabled: boolean) => void;+ onRemove: () => void;+}) {+ const { t } = useT("agents");+ const enabled = server.enabled !== false;+ return (+ <li className="flex items-center gap-3 px-4 py-3">+ <Server className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />+ <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>+ {overridden && (+ <Badge variant="secondary">+ {t(($) => $.tab_body.mcp_config.workspace_overridden_badge)}+ </Badge>+ )}+ </div>+ <p className="mt-0.5 text-caption text-muted-foreground">+ {server.transport || "unknown"}+ </p>+ </div>+ {canEdit && (+ <>+ <Switch+ checked={enabled}+ disabled={busy}+ onCheckedChange={onToggle}+ aria-label={t(($) => $.tab_body.mcp_config.workspace_toggle_aria, {+ name: server.name,+ })}+ />+ <Button+ variant="ghost"+ size="icon"+ disabled={busy}+ onClick={onRemove}+ aria-label={t(($) => $.tab_body.mcp_config.workspace_remove_aria, {+ name: server.name,+ })}+ >+ <Trash2 className="h-4 w-4" aria-hidden="true" />+ </Button>+ </>+ )}+ {!canEdit && !enabled && (+ <Badge variant="secondary">+ {t(($) => $.tab_body.mcp_config.workspace_disabled_badge)}+ </Badge>+ )}+ </li>+ );+}++/** Picks an unassigned workspace server to give to this agent. */+function McpWorkspaceServerPicker({+ servers,+ disabled,+ onSelect,+}: {+ servers: WorkspaceMcpServer[];+ disabled: boolean;+ onSelect: (serverId: string) => void;+}) {+ const { t } = useT("agents");+ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button size="sm" variant="outline" disabled={disabled}>+ <Plus aria-hidden="true" />+ {t(($) => $.tab_body.mcp_config.workspace_add_action)}+ </Button>+ }+ />+ <DropdownMenuContent align="end">+ {servers.map((server) => (+ <DropdownMenuItem key={server.id} onClick={() => onSelect(server.id)}>+ <span className="truncate">{server.name}</span>+ <span className="ml-2 text-caption text-muted-foreground">+ {server.transport || "unknown"}+ </span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}+function McpServerList({servers,disabledLabel,diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 3efdb9ea21..25dfb6aba6 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -516,15 +516,20 @@"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.",+ "workspace_title": "From the workspace library",+ "workspace_action_failed": "Could not update this agent's MCP servers",+ "workspace_removed_toast": "MCP server removed from this agent",+ "workspace_added_toast": "MCP server added to this agent",+ "workspace_remove_aria": "Remove {{name}} from this agent",+ "workspace_toggle_aria": "Enable {{name}} for this agent",+ "workspace_library_empty": "This workspace has no MCP servers to assign yet. Add them in workspace Settings → MCP.",+ "workspace_none_assigned": "No workspace MCP servers assigned to this agent yet.",+ "workspace_add_action": "Add from workspace",+ "workspace_hint": "MCP servers this agent has been given from the workspace library. Nothing is assigned automatically — add what this agent should use, and switch one off to stop sending it without losing the assignment. The agent's own servers above win on a name collision.",+ "workspace_loading": "Loading assigned servers…","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",+ "workspace_disabled_badge": "Disabled","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 fae93c447d..36e2b0fbb3 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -165,18 +165,18 @@},"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.",+ "description": "A library of MCP servers for this workspace. Adding one here gives it to no agent — an agent owner assigns it on the agent's own MCP tab, where it also gets a per-agent on/off toggle.","servers_title": "Shared servers",- "write_only_note": "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.",+ "write_only_note": "Saved configurations are write-only — urls, commands, headers, and environment values are never shown again, so editing a server replaces its configuration. Renaming is safe: agents keep their assignment.","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.",+ "empty_description": "Add a server here, then assign it to the agents that should use it from their own MCP tab.","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_description": "{{name}} will be removed from the library and from every agent it is assigned to, taking effect on their next task.","delete_confirm": "Remove","cancel": "Cancel","added_toast": "Shared MCP server added",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex c4fa495ba6..cd4c95a5fb 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -398,15 +398,20 @@"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 設定は閲覧できないため、ワークスペースから何を継承するかはここでは判断できません。",+ "workspace_title": "ワークスペースライブラリから",+ "workspace_action_failed": "このエージェントの MCP サーバーを更新できませんでした",+ "workspace_removed_toast": "このエージェントから MCP サーバーを削除しました",+ "workspace_added_toast": "このエージェントに MCP サーバーを追加しました",+ "workspace_remove_aria": "このエージェントから {{name}} を削除",+ "workspace_toggle_aria": "このエージェントで {{name}} を有効化",+ "workspace_library_empty": "このワークスペースにはまだ割り当て可能な MCP サーバーがありません。ワークスペース設定 → MCP で追加してください。",+ "workspace_none_assigned": "このエージェントにはまだワークスペース MCP サーバーが割り当てられていません。",+ "workspace_add_action": "ワークスペースから追加",+ "workspace_hint": "ワークスペースライブラリからこのエージェントに割り当てられた MCP サーバー。自動では割り当てられません。使うものを追加し、オフにすると割り当てを残したまま送信を止められます。名前が衝突した場合は上のエージェント自身のサーバーが優先されます。",+ "workspace_loading": "割り当て済みサーバーを読み込み中…","dialog_name_locked": "ここでは名前を変更できません。変更すると別のサーバーが追加され、元のサーバーが残ります。削除してから追加し直してください。",- "workspace_disabled_badge": "無効","workspace_overridden_badge": "上書き",+ "workspace_disabled_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 c47e79835b..595bff5b96 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -165,18 +165,18 @@},"mcp": {"title": "MCP",- "description": "このワークスペースの全エージェントで共有する MCP サーバー。同じ設定をエージェントごとに入力し直す必要がなくなります。",+ "description": "このワークスペースの MCP サーバーライブラリ。ここに追加してもどのエージェントにも割り当てられません。エージェントの所有者が各エージェントの MCP タブで割り当て、エージェントごとにオン/オフを切り替えます。","servers_title": "共有サーバー",- "write_only_note": "独自の MCP 設定を持たないエージェントはこれらのサーバーを継承します。独自の設定を持つエージェントはその上にマージされ、名前が衝突した場合はエージェント側が優先されます。保存された設定は書き込み専用です — url、コマンド、ヘッダー、環境変数は二度と表示されないため、サーバーの編集は設定の置き換えになります。",+ "write_only_note": "保存された設定は書き込み専用です — url、コマンド、ヘッダー、環境変数は二度と表示されないため、サーバーの編集は設定の置き換えになります。名前の変更は安全です。割り当ては維持されます。","add_server": "サーバーを追加","edit_server": "サーバーを編集","remove_server": "サーバーを削除","empty_title": "共有 MCP サーバーはありません",- "empty_description": "ここにサーバーを追加すると、オプトアウトしていない限り、ワークスペース内の全エージェントが次のタスクから継承します。",+ "empty_description": "まずここにサーバーを追加し、使用するエージェントの MCP タブから割り当ててください。","disabled_badge": "無効","admin_only_note": "共有 MCP サーバーを変更できるのはワークスペースの owner と admin のみです。","delete_title": "共有サーバーを削除しますか?",- "delete_description": "{{name}} は次のタスクからこのワークスペースのエージェントに共有されなくなります。同名のサーバーを自分で定義しているエージェントには影響しません。",+ "delete_description": "{{name}} はライブラリからも、割り当てられている全エージェントからも削除され、各エージェントの次のタスクから反映されます。","delete_confirm": "削除","cancel": "キャンセル","added_toast": "共有 MCP サーバーを追加しました",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 6c8d4f1789..1af11b3077 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -406,15 +406,20 @@"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 설정을 볼 수 없어 워크스페이스에서 무엇을 상속하는지 여기서는 판단할 수 없습니다.",+ "workspace_title": "워크스페이스 라이브러리에서",+ "workspace_action_failed": "이 에이전트의 MCP 서버를 업데이트하지 못했습니다",+ "workspace_removed_toast": "이 에이전트에서 MCP 서버를 제거했습니다",+ "workspace_added_toast": "이 에이전트에 MCP 서버를 추가했습니다",+ "workspace_remove_aria": "이 에이전트에서 {{name}} 제거",+ "workspace_toggle_aria": "이 에이전트에서 {{name}} 활성화",+ "workspace_library_empty": "이 워크스페이스에는 아직 할당할 MCP 서버가 없습니다. 워크스페이스 설정 → MCP에서 추가하세요.",+ "workspace_none_assigned": "이 에이전트에 할당된 워크스페이스 MCP 서버가 아직 없습니다.",+ "workspace_add_action": "워크스페이스에서 추가",+ "workspace_hint": "워크스페이스 라이브러리에서 이 에이전트에 할당된 MCP 서버입니다. 자동으로 할당되지 않으며, 필요한 것을 추가하고 스위치를 끄면 할당은 유지한 채 전달만 중단됩니다. 이름이 충돌하면 위의 에이전트 자체 서버가 우선합니다.",+ "workspace_loading": "할당된 서버를 불러오는 중…","dialog_name_locked": "여기서는 이름을 바꿀 수 없습니다. 이름을 바꾸면 서버가 하나 더 추가되고 기존 서버가 남습니다. 제거 후 다시 추가하세요.",- "workspace_disabled_badge": "비활성화됨","workspace_overridden_badge": "재정의됨",+ "workspace_disabled_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 476c1330b9..7eb2db4259 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -165,18 +165,18 @@},"mcp": {"title": "MCP",- "description": "이 워크스페이스의 모든 에이전트가 공유하는 MCP 서버입니다. 같은 설정을 에이전트마다 다시 입력할 필요가 없습니다.",+ "description": "이 워크스페이스의 MCP 서버 라이브러리입니다. 여기에 추가해도 어떤 에이전트에도 할당되지 않으며, 에이전트 소유자가 해당 에이전트의 MCP 탭에서 할당하고 에이전트별로 켜고 끌 수 있습니다.","servers_title": "공유 서버",- "write_only_note": "자체 MCP 설정이 없는 에이전트는 이 서버들을 상속합니다. 자체 설정이 있는 에이전트는 그 위에 병합되며 이름이 충돌하면 에이전트 쪽이 우선합니다. 저장된 설정은 쓰기 전용이라 url, 명령, 헤더, 환경 변수는 다시 표시되지 않으므로 서버 편집은 설정을 교체하는 것입니다.",+ "write_only_note": "저장된 설정은 쓰기 전용이라 url, 명령, 헤더, 환경 변수는 다시 표시되지 않으므로 서버 편집은 설정을 교체하는 것입니다. 이름 변경은 안전하며 할당은 유지됩니다.","add_server": "서버 추가","edit_server": "서버 편집","remove_server": "서버 제거","empty_title": "공유 MCP 서버가 없습니다",- "empty_description": "여기에 서버를 추가하면 옵트아웃하지 않은 한 워크스페이스의 모든 에이전트가 다음 작업부터 상속합니다.",+ "empty_description": "여기에 서버를 추가한 뒤, 사용할 에이전트의 MCP 탭에서 할당하세요.","disabled_badge": "비활성화됨","admin_only_note": "공유 MCP 서버는 워크스페이스 owner와 admin만 변경할 수 있습니다.","delete_title": "공유 서버를 제거할까요?",- "delete_description": "{{name}}은(는) 다음 작업부터 이 워크스페이스의 에이전트에 공유되지 않습니다. 같은 이름의 서버를 직접 정의한 에이전트는 영향을 받지 않습니다.",+ "delete_description": "{{name}}은(는) 라이브러리와 할당된 모든 에이전트에서 제거되며 각 에이전트의 다음 작업부터 적용됩니다.","delete_confirm": "제거","cancel": "취소","added_toast": "공유 MCP 서버를 추가했습니다",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex e9a26aa46b..ebf58e2a34 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -505,15 +505,20 @@"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 配置,因此这里无法确定它从工作区继承了什么。",+ "workspace_title": "来自工作区库",+ "workspace_action_failed": "更新该智能体的 MCP 服务失败",+ "workspace_removed_toast": "已从该智能体移除 MCP 服务",+ "workspace_added_toast": "已为该智能体添加 MCP 服务",+ "workspace_remove_aria": "从该智能体移除 {{name}}",+ "workspace_toggle_aria": "为该智能体启用 {{name}}",+ "workspace_library_empty": "本工作区还没有可分配的 MCP 服务。请在工作区设置 → MCP 中添加。",+ "workspace_none_assigned": "还没有给该智能体分配工作区 MCP 服务。",+ "workspace_add_action": "从工作区添加",+ "workspace_hint": "从工作区库分配给该智能体的 MCP 服务。不会自动分配——需要用哪个就加哪个;关掉开关会停止下发但保留分配。上面该智能体自己的服务在同名时优先。",+ "workspace_loading": "正在加载已分配的服务…","dialog_name_locked": "这里不能改名——改名会新增一个服务并把原来的留在那里。请改用移除后重新添加。",- "workspace_disabled_badge": "已禁用","workspace_overridden_badge": "已覆盖",+ "workspace_disabled_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 2c785dfbb5..86fb02fd04 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -165,18 +165,18 @@},"mcp": {"title": "MCP",- "description": "与本工作区所有智能体共享的 MCP 服务,不必在每个智能体上重复录入同一批配置。",+ "description": "本工作区的 MCP 服务库。在这里添加不会分配给任何智能体——由智能体的负责人在该智能体自己的 MCP 页里分配,并可按智能体单独开关。","servers_title": "共享服务",- "write_only_note": "没有自己 MCP 配置的智能体会继承这些服务;有自己配置的智能体在其之上合并,同名时以智能体自己的为准。已保存的配置是只写的——URL、命令、请求头和环境变量不会再次展示,因此编辑一个服务等于整条替换它的配置。",+ "write_only_note": "已保存的配置是只写的——URL、命令、请求头和环境变量不会再次展示,因此编辑一个服务等于整条替换它的配置。改名是安全的:已分配的智能体不受影响。","add_server": "添加服务","edit_server": "编辑服务","remove_server": "移除服务","empty_title": "还没有共享的 MCP 服务",- "empty_description": "在这里添加服务后,工作区内所有智能体会在下一个任务开始时继承它——除非该智能体已明确退出。",+ "empty_description": "先在这里添加服务,再到需要用它的智能体的 MCP 页里分配。","disabled_badge": "已禁用","admin_only_note": "只有工作区 owner 和 admin 可以修改共享的 MCP 服务。","delete_title": "移除共享服务?",- "delete_description": "{{name}} 将在本工作区智能体的下一个任务起不再共享。自己定义了同名服务的智能体不受影响。",+ "delete_description": "{{name}} 将从服务库以及所有已分配的智能体上移除,在它们的下一个任务起生效。","delete_confirm": "移除","cancel": "取消","added_toast": "已添加共享 MCP 服务",diff --git a/packages/views/settings/components/mcp-tab.test.tsx b/packages/views/settings/components/mcp-tab.test.tsxindex 906f3d92e7..669bc11320 100644--- a/packages/views/settings/components/mcp-tab.test.tsx+++ b/packages/views/settings/components/mcp-tab.test.tsx@@ -9,32 +9,37 @@ 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 mockCreate = vi.hoisted(() => vi.fn());+const mockUpdate = vi.hoisted(() => vi.fn());const mockDelete = vi.hoisted(() => vi.fn());+const server = (over: Record<string, unknown>) => ({+ id: "srv-1",+ workspace_id: "workspace-1",+ name: "linear",+ transport: "http",+ created_at: "2026-08-14T00:00:00Z",+ updated_at: "2026-08-14T00:00:00Z",+ ...over,+});+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,- },+ servers: [] as Array<Record<string, unknown>>,isLoading: false,role: "owner" as "owner" | "admin" | "member",}));vi.mock("@tanstack/react-query", () => ({- useQuery: () => ({ data: data.config, isLoading: data.isLoading }),+ useQuery: () => ({ data: data.servers, isLoading: data.isLoading }),}));vi.mock("@multica/core/workspace/queries", () => ({- workspaceMcpConfigOptions: () => ({ queryKey: ["workspaces", "workspace-1", "mcp-config"] }),+ workspaceMcpServersOptions: () => ({ queryKey: ["workspaces", "workspace-1", "mcp-servers"] }),}));vi.mock("@multica/core/workspace/mutations", () => ({- useUpsertWorkspaceMcpServer: () => ({ mutateAsync: mockUpsert, isPending: false }),+ useCreateWorkspaceMcpServer: () => ({ mutateAsync: mockCreate, isPending: false }),+ useUpdateWorkspaceMcpServer: () => ({ mutateAsync: mockUpdate, isPending: false }),useDeleteWorkspaceMcpServer: () => ({ mutateAsync: mockDelete, isPending: false }),}));@@ -67,29 +72,25 @@ describe("McpTab", () => {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({});+ data.servers = [+ server({ id: "srv-1", name: "linear", transport: "http" }),+ server({ id: "srv-2", name: "local-tool", transport: "stdio" }),+ ];+ mockCreate.mockResolvedValue({});+ mockUpdate.mockResolvedValue({});mockDelete.mockResolvedValue({});});- it("lists the shared servers with their transport and disabled state", () => {+ it("lists the library servers with their transport", () => {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 () => {+ it("adds a server to the library", async () => {const user = userEvent.setup();render(<McpTab />, { wrapper: Wrapper });@@ -100,21 +101,19 @@ describe("McpTab", () => {await user.click(screen.getByRole("button", { name: "Add Server" }));await waitFor(() =>- expect(mockUpsert).toHaveBeenCalledWith(+ expect(mockCreate).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");+ // never resends, anything else.+ const call = mockCreate.mock.calls[0]![0] as { config: Record<string, unknown> };+ expect(call.config).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 () => {+ // Renaming is safe in this model — assignments key off the server id — so+ // the name field stays editable and the update targets the opened entry.+ it("edits a library server by id, so a rename keeps its assignments", async () => {const user = userEvent.setup();render(<McpTab />, { wrapper: Wrapper });@@ -122,19 +121,19 @@ describe("McpTab", () => {const nameInput = screen.getByLabelText("Name") as HTMLInputElement;expect(nameInput.value).toBe("linear");- expect(nameInput).toHaveAttribute("readonly");+ expect(nameInput).not.toHaveAttribute("readonly");- // Even if something did change the field, the upsert targets the entry- // that was opened.+ await user.clear(nameInput);+ await user.type(nameInput, "linear-v2");await user.type(screen.getByLabelText("Server URL"), "https://linear-v2.example");await user.click(screen.getByRole("button", { name: "Save Changes" }));await waitFor(() =>- expect(mockUpsert).toHaveBeenCalledWith(- expect.objectContaining({ name: "linear" }),+ expect(mockUpdate).toHaveBeenCalledWith(+ expect.objectContaining({ serverId: "srv-1", name: "linear-v2" }),),);- expect(mockUpsert).toHaveBeenCalledTimes(1);+ expect(mockCreate).not.toHaveBeenCalled();});// The saved entry cannot be read back, but the safe summary still knows the@@ -162,11 +161,7 @@ describe("McpTab", () => {"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,- };+ data.servers = [server({ name: "streamy", transport })];render(<McpTab />, { wrapper: Wrapper });await user.click(screen.getByRole("button", { name: "Edit server" }));@@ -191,7 +186,7 @@ describe("McpTab", () => {await user.click(screen.getAllByRole("button", { name: "Remove server" })[0]!);await user.click(screen.getByRole("button", { name: "Remove" }));- await waitFor(() => expect(mockDelete).toHaveBeenCalledWith("linear"));+ await waitFor(() => expect(mockDelete).toHaveBeenCalledWith("srv-1"));});it("hides every write affordance from a plain member", () => {@@ -208,8 +203,8 @@ describe("McpTab", () => {).toBeInTheDocument();});- it("renders an empty state when the workspace shares nothing", () => {- data.config = { workspace_id: "workspace-1", servers: [], server_count: 0 };+ it("renders an empty state when the library is empty", () => {+ data.servers = [];render(<McpTab />, { wrapper: Wrapper });expect(screen.getByText("No shared MCP servers")).toBeInTheDocument();@@ -223,10 +218,10 @@ describe("McpTab", () => {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+ it("survives a payload that is not an array", () => {+ // Backend drift: the schema defaults the list to [], but the component// must not crash if it ever arrives undefined.- data.config = { workspace_id: "workspace-1" } as typeof data.config;+ data.servers = undefined as unknown as typeof data.servers;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.tsxindex 5463a75857..d8ae1c7dd3 100644--- a/packages/views/settings/components/mcp-tab.tsx+++ b/packages/views/settings/components/mcp-tab.tsx@@ -18,10 +18,11 @@ 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 { workspaceMcpServersOptions } from "@multica/core/workspace/queries";import {+ useCreateWorkspaceMcpServer,useDeleteWorkspaceMcpServer,- useUpsertWorkspaceMcpServer,+ useUpdateWorkspaceMcpServer,} from "@multica/core/workspace/mutations";import type { WorkspaceMcpServer } from "@multica/core/types";import { McpServerDialog } from "../../agents/components/tabs/mcp-server-dialog";@@ -30,18 +31,19 @@ import { useT } from "../../i18n";import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";/**- * Workspace-level MCP servers (GH #6062).+ * The workspace MCP server library (GH #6062).** Two things shape this screen and are worth stating up front:*+ * - A server added here is given to NO agent. It is a library entry, exactly+ * like a workspace skill: an agent owner assigns it on the agent's own MCP+ * tab, where it also gets a per-agent on/off toggle. Nothing here reaches an+ * agent implicitly.* - The stored configuration is WRITE-ONLY. The API returns names and* transports, never urls / commands / headers / env, so there is no* "current value" to prefill and editing a server means supplying its- * configuration again. The UI says so rather than pretending the empty- * form is the saved state.- * - 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.+ * configuration again. The UI says so rather than pretending the empty form+ * is the saved state.*/export function McpTab() {const { t } = useT("settings");@@ -51,11 +53,12 @@ export function McpTab() {const canManage =currentMember.role === "owner" || currentMember.role === "admin";- const configQuery = useQuery(workspaceMcpConfigOptions(wsId));- const upsertServer = useUpsertWorkspaceMcpServer(wsId);+ const serversQuery = useQuery(workspaceMcpServersOptions(wsId));+ const createServer = useCreateWorkspaceMcpServer(wsId);+ const updateServer = useUpdateWorkspaceMcpServer(wsId);const deleteServer = useDeleteWorkspaceMcpServer(wsId);- const servers = configQuery.data?.servers ?? [];+ const servers = serversQuery.data ?? [];const existingNames = useMemo(() => new Set(servers.map((server) => server.name)),[servers],@@ -65,7 +68,9 @@ export function McpTab() {const [editingServer, setEditingServer] = useState<WorkspaceMcpServer | null>(null,);- const [deletingName, setDeletingName] = useState<string | null>(null);+ const [deletingServer, setDeletingServer] = useState<WorkspaceMcpServer | 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@@ -77,7 +82,9 @@ export function McpTab() {config: {},container: "mcpServers",transport: editingServer.transport,- enabled: editingServer.enabled,+ // The library has no per-agent toggle; this field only feeds the+ // dialog's shape.+ enabled: true,}: null;@@ -85,12 +92,14 @@ export function McpTab() {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 });+ if (editingServer) {+ // Renaming is safe here: assignments key off the server id, so an+ // agent that uses this server keeps using it.+ await updateServer.mutateAsync({ serverId: editingServer.id, name, config });+ } else {+ await createServer.mutateAsync({ name, config });+ }toast.success(editingServer? t(($) => $.mcp.updated_toast)@@ -107,11 +116,11 @@ export function McpTab() {};const handleDelete = async () => {- if (!deletingName) return;+ if (!deletingServer) return;try {- await deleteServer.mutateAsync(deletingName);+ await deleteServer.mutateAsync(deletingServer.id);toast.success(t(($) => $.mcp.removed_toast));- setDeletingName(null);+ setDeletingServer(null);} catch (error) {toast.error(error instanceof Error && error.message@@ -145,7 +154,7 @@ export function McpTab() {}><SettingsCard>- {configQuery.isLoading ? (+ {serversQuery.isLoading ? (<div className="flex items-center justify-center py-8 text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /></div>@@ -170,7 +179,7 @@ export function McpTab() {setEditingServer(server);setEditorOpen(true);}}- onDelete={() => setDeletingName(server.name)}+ onDelete={() => setDeletingServer(server)}/>))}</ul>@@ -187,24 +196,21 @@ export function McpTab() {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}+ open={deletingServer !== null}onOpenChange={(open) => {- if (!open) setDeletingName(null);+ if (!open) setDeletingServer(null);}}><AlertDialogContent><AlertDialogHeader><AlertDialogTitle>{t(($) => $.mcp.delete_title)}</AlertDialogTitle><AlertDialogDescription>- {t(($) => $.mcp.delete_description, { name: deletingName ?? "" })}+ {t(($) => $.mcp.delete_description, { name: deletingServer?.name ?? "" })}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>diff --git a/server/cmd/multica/cmd_agent_mcp.go b/server/cmd/multica/cmd_agent_mcp.gonew file mode 100644index 0000000000..b2a4623d29--- /dev/null+++ b/server/cmd/multica/cmd_agent_mcp.go@@ -0,0 +1,166 @@+package main++import (+ "context"+ "fmt"+ "net/url"+ "strings"++ "github.com/spf13/cobra"++ "github.com/multica-ai/multica/server/internal/cli"+)++// Assigning a workspace MCP server to an agent, mirroring `agent skills`.+// Kept in its own file so cmd_agent.go's line references — which the+// multica-creating-agents source map cites — stay stable.++var agentMcpCmd = &cobra.Command{+ Use: "mcp",+ Short: "Manage which workspace MCP servers an agent uses",+ Long: "Assigns MCP servers from the workspace library to an agent. A library " ++ "entry does nothing until it is added to an agent here, and each " ++ "assignment carries its own on/off toggle — the same shape as workspace " ++ "skills.\n\n" ++ "This is separate from the agent's OWN mcp_config ('agent update " ++ "--mcp-config'), which holds servers private to that agent. Both are " ++ "merged at claim time; the agent's own entry wins on a name collision.",+}++var agentMcpListCmd = &cobra.Command{+ Use: "list <agent-id>",+ Short: "List the workspace MCP servers assigned to an agent",+ Args: exactArgs(1),+ RunE: runAgentMcpList,+}++var agentMcpAddCmd = &cobra.Command{+ Use: "add <agent-id> <server-id>",+ Short: "Give a workspace MCP server to an agent",+ Long: "Assigns a workspace MCP server to this agent, enabled. Take the server " ++ "id from 'multica workspace mcp list'. Adding one twice is a no-op.",+ Args: exactArgs(2),+ RunE: runAgentMcpAdd,+}++var agentMcpEnableCmd = &cobra.Command{+ Use: "enable <agent-id> <server-id>",+ Short: "Turn an assigned MCP server back on for this agent",+ Args: exactArgs(2),+ RunE: runAgentMcpEnable,+}++var agentMcpDisableCmd = &cobra.Command{+ Use: "disable <agent-id> <server-id>",+ Short: "Turn an assigned MCP server off for this agent",+ Long: "Stops the agent from receiving this server without dropping the " ++ "assignment, so turning it back on later is one command.",+ Args: exactArgs(2),+ RunE: runAgentMcpDisable,+}++var agentMcpRemoveCmd = &cobra.Command{+ Use: "remove <agent-id> <server-id>",+ Short: "Take a workspace MCP server away from an agent",+ Long: "Removes the assignment. The workspace library entry itself is " ++ "untouched and other agents keep theirs.",+ Args: exactArgs(2),+ RunE: runAgentMcpRemove,+}++func init() {+ agentCmd.AddCommand(agentMcpCmd)+ agentMcpCmd.AddCommand(agentMcpListCmd)+ agentMcpCmd.AddCommand(agentMcpAddCmd)+ agentMcpCmd.AddCommand(agentMcpEnableCmd)+ agentMcpCmd.AddCommand(agentMcpDisableCmd)+ agentMcpCmd.AddCommand(agentMcpRemoveCmd)++ for _, cmd := range []*cobra.Command{+ agentMcpListCmd, agentMcpAddCmd, agentMcpEnableCmd, agentMcpDisableCmd, agentMcpRemoveCmd,+ } {+ cmd.Flags().String("output", "table", "Output format: table or json")+ }+}++func agentMcpPath(agentID string, parts ...string) string {+ path := "/api/agents/" + url.PathEscape(agentID) + "/mcp-servers"+ for _, part := range parts {+ path += "/" + url.PathEscape(part)+ }+ return path+}++func runAgentMcpList(cmd *cobra.Command, args []string) error {+ agentID := strings.TrimSpace(args[0])+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var servers []workspaceMcpServer+ if err := client.GetJSON(ctx, agentMcpPath(agentID), &servers); err != nil {+ return fmt.Errorf("list agent mcp servers: %w", err)+ }+ return printWorkspaceMcpServers(cmd, servers)+}++func runAgentMcpAdd(cmd *cobra.Command, args []string) error {+ agentID, serverID := strings.TrimSpace(args[0]), strings.TrimSpace(args[1])+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var servers []workspaceMcpServer+ body := map[string]any{"server_id": serverID}+ if err := client.PostJSON(ctx, agentMcpPath(agentID), body, &servers); err != nil {+ return fmt.Errorf("add agent mcp server: %w", err)+ }+ return printWorkspaceMcpServers(cmd, servers)+}++func runAgentMcpEnable(cmd *cobra.Command, args []string) error {+ return setAgentMcpEnabled(cmd, args, true)+}++func runAgentMcpDisable(cmd *cobra.Command, args []string) error {+ return setAgentMcpEnabled(cmd, args, false)+}++func setAgentMcpEnabled(cmd *cobra.Command, args []string, enabled bool) error {+ agentID, serverID := strings.TrimSpace(args[0]), strings.TrimSpace(args[1])+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var servers []workspaceMcpServer+ body := map[string]any{"enabled": enabled}+ if err := client.PutJSON(ctx, agentMcpPath(agentID, serverID, "enabled"), body, &servers); err != nil {+ return fmt.Errorf("update agent mcp server: %w", err)+ }+ return printWorkspaceMcpServers(cmd, servers)+}++func runAgentMcpRemove(cmd *cobra.Command, args []string) error {+ agentID, serverID := strings.TrimSpace(args[0]), strings.TrimSpace(args[1])+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var servers []workspaceMcpServer+ if err := client.DeleteJSONResponse(ctx, agentMcpPath(agentID, serverID), &servers); err != nil {+ return fmt.Errorf("remove agent mcp server: %w", err)+ }+ return printWorkspaceMcpServers(cmd, servers)+}diff --git a/server/cmd/multica/cmd_workspace.go b/server/cmd/multica/cmd_workspace.goindex e12bceab5f..b8dc152f8d 100644--- a/server/cmd/multica/cmd_workspace.go+++ b/server/cmd/multica/cmd_workspace.go@@ -101,63 +101,57 @@ var workspaceSwitchCmd = &cobra.Command{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" ++ Short: "Manage the workspace's MCP server library",+ Long: "Manages the workspace's library of MCP servers. A server added here " ++ "is given to NO agent: it reaches an agent only when someone assigns it " ++ "to that agent ('multica agent mcp add'), which also carries a per-agent " ++ "on/off toggle. Same shape as workspace skills.\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.",+ "and transports, never the urls, commands, headers, or env.",}-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 " ++var workspaceMcpListCmd = &cobra.Command{+ Use: "list [workspace-id|slug|prefix]",+ Short: "List the workspace's MCP servers",+ Long: "Lists the workspace MCP library 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",+ "session URL is a credential on its own.",Args: cobra.MaximumNArgs(1),- RunE: runWorkspaceMcpSet,+ RunE: runWorkspaceMcpList,}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" ++ Short: "Add an MCP server to the workspace library (admin/owner only)",+ Long: "Adds an MCP server to the workspace library. It is assigned to no " ++ "agent — use 'multica agent mcp add <agent-id> <server-id>' to give it to " ++ "one.\n\n" +"The payload is a single server entry, the same object shape that sits " +- "under a name in \"mcpServers\".",+ "under a name in \"mcpServers\". Prefer --server-config-file or " ++ "--server-config-stdin: MCP entries routinely carry API tokens, and an " ++ "inline value ends up in shell history and 'ps'.",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 workspaceMcpUpdateCmd = &cobra.Command{+ Use: "update <server-id> [workspace-id|slug|prefix]",+ Short: "Rename or replace a workspace MCP server (admin/owner only)",+ Long: "Renames a server, replaces its configuration, or both. Agents keep " ++ "their assignment across a rename because assignments key off the server " ++ "id, not its name.",+ Args: cobra.RangeArgs(1, 2),+ RunE: runWorkspaceMcpUpdate,+}+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.",+ Use: "remove <server-id> [workspace-id|slug|prefix]",+ Short: "Remove an MCP server from the workspace library (admin/owner only)",+ Long: "Removes the server from the library and from every agent it was " ++ "assigned to.",Args: cobra.RangeArgs(1, 2),RunE: runWorkspaceMcpRemove,}@@ -172,9 +166,9 @@ func init() {workspaceCmd.AddCommand(workspaceUpdateCmd)workspaceCmd.AddCommand(workspaceSwitchCmd)workspaceCmd.AddCommand(workspaceMcpCmd)- workspaceMcpCmd.AddCommand(workspaceMcpGetCmd)- workspaceMcpCmd.AddCommand(workspaceMcpSetCmd)+ workspaceMcpCmd.AddCommand(workspaceMcpListCmd)workspaceMcpCmd.AddCommand(workspaceMcpAddCmd)+ workspaceMcpCmd.AddCommand(workspaceMcpUpdateCmd)workspaceMcpCmd.AddCommand(workspaceMcpRemoveCmd)workspaceListCmd.Flags().String("output", "table", "Output format: table or json")@@ -200,18 +194,19 @@ func init() {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")+ workspaceMcpListCmd.Flags().String("output", "json", "Output format: table or json")+ // Same three mutually-exclusive secret-safe channels as `agent update`,+ // resolved by the shared resolveMcpJSONObject so every surface agrees on+ // what a valid payload is.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")+ workspaceMcpUpdateCmd.Flags().String("name", "", "New server name")+ workspaceMcpUpdateCmd.Flags().String("server-config", "", "Replacement server entry as JSON (avoid: lands in shell history)")+ workspaceMcpUpdateCmd.Flags().Bool("server-config-stdin", false, "Read the replacement server entry JSON from stdin")+ workspaceMcpUpdateCmd.Flags().String("server-config-file", "", "Read the replacement server entry JSON from a file")+ workspaceMcpUpdateCmd.Flags().String("output", "json", "Output format: table or json")workspaceMcpRemoveCmd.Flags().String("output", "json", "Output format: table or json")}@@ -607,7 +602,7 @@ func runWorkspaceUpdate(cmd *cobra.Command, args []string) error {return printWorkspace(cmd, ws)}-func runWorkspaceMcpGet(cmd *cobra.Command, args []string) error {+func runWorkspaceMcpList(cmd *cobra.Command, args []string) error {wsID, err := resolveWorkspaceArg(cmd, args)if err != nil {return err@@ -624,16 +619,20 @@ func runWorkspaceMcpGet(cmd *cobra.Command, args []string) error {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)+ var servers []workspaceMcpServer+ if err := client.GetJSON(ctx, "/api/workspaces/"+wsID+"/mcp-servers", &servers); err != nil {+ return fmt.Errorf("list workspace mcp servers: %w", err)}- return printWorkspaceMcpConfig(cmd, resp)+ return printWorkspaceMcpServers(cmd, servers)}-func runWorkspaceMcpSet(cmd *cobra.Command, args []string) error {- wsID, err := resolveWorkspaceArg(cmd, args)+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}@@ -641,12 +640,12 @@ func runWorkspaceMcpSet(cmd *cobra.Command, args []string) error {return fmt.Errorf("workspace ID is required: pass an id/slug/prefix as argument or set MULTICA_WORKSPACE_ID")}- mcpConfig, ok, err := resolveMcpConfig(cmd)+ entry, ok, err := resolveMcpJSONObject(cmd, "server-config", false)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")+ return fmt.Errorf("one of --server-config, --server-config-stdin, or --server-config-file is required")}client, err := newAPIClient(cmd)@@ -657,19 +656,19 @@ func runWorkspaceMcpSet(cmd *cobra.Command, args []string) error {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)+ var server workspaceMcpServer+ body := map[string]any{"name": serverName, "config": entry}+ if err := client.PostJSON(ctx, "/api/workspaces/"+wsID+"/mcp-servers", body, &server); err != nil {+ return fmt.Errorf("add workspace mcp server: %w", err)}- return printWorkspaceMcpConfig(cmd, resp)+ return printWorkspaceMcpServers(cmd, []workspaceMcpServer{server})}-func runWorkspaceMcpAdd(cmd *cobra.Command, args []string) error {- serverName := strings.TrimSpace(args[0])- if serverName == "" {- return fmt.Errorf("server name must not be empty")+func runWorkspaceMcpUpdate(cmd *cobra.Command, args []string) error {+ serverID := strings.TrimSpace(args[0])+ if serverID == "" {+ return fmt.Errorf("server ID must not be empty")}wsID, err := resolveWorkspaceArg(cmd, args[1:])if err != nil {@@ -679,12 +678,20 @@ func runWorkspaceMcpAdd(cmd *cobra.Command, args []string) error {return fmt.Errorf("workspace ID is required: pass an id/slug/prefix as argument or set MULTICA_WORKSPACE_ID")}+ body := map[string]any{}+ if cmd.Flags().Changed("name") {+ name, _ := cmd.Flags().GetString("name")+ body["name"] = strings.TrimSpace(name)+ }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")+ if ok {+ body["config"] = entry+ }+ if len(body) == 0 {+ return fmt.Errorf("nothing to update; pass --name and/or one of --server-config, --server-config-stdin, --server-config-file")}client, err := newAPIClient(cmd)@@ -695,19 +702,19 @@ func runWorkspaceMcpAdd(cmd *cobra.Command, args []string) error {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)+ var server workspaceMcpServer+ path := "/api/workspaces/" + wsID + "/mcp-servers/" + url.PathEscape(serverID)+ if err := client.PutJSON(ctx, path, body, &server); err != nil {+ return fmt.Errorf("update workspace mcp server: %w", err)}- return printWorkspaceMcpConfig(cmd, resp)+ return printWorkspaceMcpServers(cmd, []workspaceMcpServer{server})}func runWorkspaceMcpRemove(cmd *cobra.Command, args []string) error {- serverName := strings.TrimSpace(args[0])- if serverName == "" {- return fmt.Errorf("server name must not be empty")+ serverID := strings.TrimSpace(args[0])+ if serverID == "" {+ return fmt.Errorf("server ID must not be empty")}wsID, err := resolveWorkspaceArg(cmd, args[1:])if err != nil {@@ -725,55 +732,54 @@ func runWorkspaceMcpRemove(cmd *cobra.Command, args []string) error {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 {+ path := "/api/workspaces/" + wsID + "/mcp-servers/" + url.PathEscape(serverID)+ if err := client.DeleteJSON(ctx, path); 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"`+ fmt.Fprintf(os.Stdout, "removed MCP server %s\n", serverID)+ return nil}-type workspaceMcpInventoryRow struct {+// workspaceMcpServer 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 a stored entry, or a `url` /+// `headers` inside one, cannot reach stdout through ANY output format. Fields+// not declared here are dropped by encoding/json.+type workspaceMcpServer struct {+ ID string `json:"id"`Name string `json:"name"`Transport string `json:"transport"`- Enabled bool `json:"enabled"`+ // Only set on an agent's assignment list; nil in the workspace library.+ Enabled *bool `json:"enabled,omitempty"`}-// 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 {+// printWorkspaceMcpServers renders an MCP server list. There is no entry to+// print in either format: the API never returns a stored configuration, and+// the type above is what guarantees this command cannot print one even if the+// API changed its mind.+func printWorkspaceMcpServers(cmd *cobra.Command, servers []workspaceMcpServer) error {output, _ := cmd.Flags().GetString("output")if output != "table" {- return cli.PrintJSON(os.Stdout, resp)+ return cli.PrintJSON(os.Stdout, servers)}- if len(resp.Servers) == 0 {- fmt.Fprintln(os.Stdout, "no MCP servers shared by this workspace")+ if len(servers) == 0 {+ fmt.Fprintln(os.Stdout, "no MCP servers")return nil}- rows := make([][]string, 0, len(resp.Servers))- for _, server := range resp.Servers {- status := "enabled"- if !server.Enabled {- status = "disabled"+ rows := make([][]string, 0, len(servers))+ for _, server := range servers {+ status := ""+ if server.Enabled != nil {+ status = "enabled"+ if !*server.Enabled {+ status = "disabled"+ }}- rows = append(rows, []string{server.Name, server.Transport, status})+ rows = append(rows, []string{server.ID, server.Name, server.Transport, status})}- cli.PrintTable(os.Stdout, []string{"NAME", "TRANSPORT", "STATUS"}, rows)+ cli.PrintTable(os.Stdout, []string{"ID", "NAME", "TRANSPORT", "STATUS"}, rows)return nil}diff --git a/server/cmd/multica/cmd_workspace_mcp_test.go b/server/cmd/multica/cmd_workspace_mcp_test.goindex 8ee9171857..424eee30f7 100644--- a/server/cmd/multica/cmd_workspace_mcp_test.go+++ b/server/cmd/multica/cmd_workspace_mcp_test.go@@ -1,7 +1,6 @@package mainimport (- "bytes""encoding/json""net/http""net/http/httptest"@@ -13,7 +12,11 @@ import ("github.com/spf13/cobra")-const testWorkspaceMcpID = "workspace-123"+const (+ testWorkspaceMcpID = "workspace-123"+ testMcpServerID = "11111111-1111-1111-1111-111111111111"+ testMcpAgentID = "22222222-2222-2222-2222-222222222222"+)func newWorkspaceMcpTestCmd(use string) *cobra.Command {cmd := &cobra.Command{Use: use}@@ -22,150 +25,128 @@ func newWorkspaceMcpTestCmd(use string) *cobra.Command {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":+ case "add", "update":cmd.Flags().String("server-config", "", "")cmd.Flags().Bool("server-config-stdin", false, "")cmd.Flags().String("server-config-file", "", "")+ if use == "update" {+ cmd.Flags().String("name", "", "")+ }}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})- }+// serverResponse is what every MCP endpoint returns: identity and transport,+// never the stored entry.+func serverResponse(name string) map[string]any {return map[string]any{+ "id": testMcpServerID,"workspace_id": testWorkspaceMcpID,- "servers": servers,- "server_count": len(servers),+ "name": name,+ "transport": "http",+ "created_at": "2026-08-14T00:00:00Z",+ "updated_at": "2026-08-14T00:00:00Z",+ }+}++// poisonedServerResponse is what a regressed (or hostile) server would send:+// the correct summary PLUS the stored entry. Nothing from it may reach stdout,+// in ANY output format — the CLI decodes into a named struct precisely so it+// cannot.+func poisonedServerResponse(name string) map[string]any {+ resp := serverResponse(name)+ resp["config"] = map[string]any{+ "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["url"] = "https://mcp.example/sk-live-flat-leak"+ return resp+}++var workspaceMcpLeakMarkers = []string{+ "sk-live-url-leak",+ "sk-live-header-leak",+ "sk-live-env-leak",+ "sk-live-flat-leak",+ "config",+ "headers",}-func TestRunWorkspaceMcpGetListsInventory(t *testing.T) {+func mcpTestServer(t *testing.T, handler http.HandlerFunc) {+ t.Helper()t.Setenv("HOME", t.TempDir())t.Setenv("MULTICA_TOKEN", "test-token")t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)+ srv := httptest.NewServer(handler)+ t.Cleanup(srv.Close)+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+}+func TestRunWorkspaceMcpListShowsTheLibrary(t *testing.T) {var gotMethod, gotPath string- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {gotMethod, gotPath = r.Method, r.URL.Pathw.Header().Set("Content-Type", "application/json")- _ = json.NewEncoder(w).Encode(inventoryResponse("linear"))- }))- defer srv.Close()- t.Setenv("MULTICA_SERVER_URL", srv.URL)+ _ = json.NewEncoder(w).Encode([]map[string]any{serverResponse("linear")})+ })- cmd := newWorkspaceMcpTestCmd("get")+ cmd := newWorkspaceMcpTestCmd("list")_ = cmd.Flags().Set("output", "table")- out, err := captureStdout(t, func() error { return runWorkspaceMcpGet(cmd, nil) })+ out, err := captureStdout(t, func() error { return runWorkspaceMcpList(cmd, nil) })if err != nil {- t.Fatalf("runWorkspaceMcpGet: %v", err)+ t.Fatalf("runWorkspaceMcpList: %v", err)}if gotMethod != http.MethodGet {t.Fatalf("method = %s, want GET", gotMethod)}- if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-config" {+ if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-servers" {t.Fatalf("path = %q", gotPath)}- if !strings.Contains(out, "linear") || !strings.Contains(out, "http") {+ if !strings.Contains(out, "linear") || !strings.Contains(out, testMcpServerID) {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) {+func TestRunWorkspaceMcpListEmptyLibrary(t *testing.T) {+ mcpTestServer(t, 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)+ _ = json.NewEncoder(w).Encode([]map[string]any{})+ })- cmd := newWorkspaceMcpTestCmd("get")+ cmd := newWorkspaceMcpTestCmd("list")_ = cmd.Flags().Set("output", "table")- out, err := captureStdout(t, func() error { return runWorkspaceMcpGet(cmd, nil) })+ out, err := captureStdout(t, func() error { return runWorkspaceMcpList(cmd, nil) })if err != nil {- t.Fatalf("runWorkspaceMcpGet: %v", err)+ t.Fatalf("runWorkspaceMcpList: %v", err)}- if !strings.Contains(out, "no MCP servers shared") {+ if !strings.Contains(out, "no MCP servers") {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.+// Both output modes, because the JSON one is the DEFAULT: a renderer that+// echoed the decoded response would leak there first.+func TestRunWorkspaceMcpNeverPrintsSecrets(t *testing.T) {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) {+ mcpTestServer(t, 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)+ _ = json.NewEncoder(w).Encode([]map[string]any{poisonedServerResponse("linear")})+ })- cmd := newWorkspaceMcpTestCmd("get")+ cmd := newWorkspaceMcpTestCmd("list")_ = cmd.Flags().Set("output", output)- out, err := captureStdout(t, func() error { return runWorkspaceMcpGet(cmd, nil) })+ out, err := captureStdout(t, func() error { return runWorkspaceMcpList(cmd, nil) })if err != nil {- t.Fatalf("runWorkspaceMcpGet: %v", err)+ t.Fatalf("runWorkspaceMcpList: %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)}@@ -173,20 +154,14 @@ func TestRunWorkspaceMcpGetNeverPrintsSecrets(t *testing.T) {}}-// 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) {+// The write paths render the same shape, so they need the same guard — a write+// response is where a server is most likely to echo back what it just stored.+func TestRunWorkspaceMcpAddNeverPrintsSecrets(t *testing.T) {+ mcpTestServer(t, 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)+ w.WriteHeader(http.StatusCreated)+ _ = json.NewEncoder(w).Encode(poisonedServerResponse("linear"))+ })cmd := newWorkspaceMcpTestCmd("add")_ = cmd.Flags().Set("server-config", `{"url":"https://mcp.example"}`)@@ -201,245 +176,267 @@ func TestRunWorkspaceMcpWritesNeverPrintSecrets(t *testing.T) {}}-func TestRunWorkspaceMcpSetSendsDocument(t *testing.T) {- t.Setenv("HOME", t.TempDir())- t.Setenv("MULTICA_TOKEN", "test-token")- t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)-+func TestRunWorkspaceMcpAddPostsNameAndEntry(t *testing.T) {var gotMethod, gotPath stringvar gotBody map[string]any- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {gotMethod, gotPath = r.Method, r.URL.Pathif 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)+ w.WriteHeader(http.StatusCreated)+ _ = json.NewEncoder(w).Encode(serverResponse("linear"))+ })- path := filepath.Join(t.TempDir(), "mcp.json")- if err := os.WriteFile(path, []byte(`{"mcpServers":{"linear":{"url":"https://linear.example"}}}`), 0o600); err != nil {+ path := filepath.Join(t.TempDir(), "linear.json")+ if err := os.WriteFile(path, []byte(`{"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)+ cmd := newWorkspaceMcpTestCmd("add")+ _ = cmd.Flags().Set("server-config-file", path)+ 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 gotMethod != http.MethodPost {+ t.Fatalf("method = %s, want POST", gotMethod)}- if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-config" {+ if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-servers" {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 gotBody["name"] != "linear" {+ t.Fatalf("body name = %v, want linear", gotBody["name"])}- if !strings.Contains(rawBody, `"mcp_config":null`) {- t.Fatalf("body = %q, want an explicit null to clear", rawBody)+ entry, _ := gotBody["config"].(map[string]any)+ if entry == nil || entry["url"] != "https://linear.example" {+ t.Fatalf("body config = %v, want the file contents", gotBody["config"])}}-func TestRunWorkspaceMcpSetRequiresAnInputChannel(t *testing.T) {- t.Setenv("HOME", t.TempDir())- t.Setenv("MULTICA_TOKEN", "test-token")- t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)+func TestRunWorkspaceMcpAddRequiresAnInputChannel(t *testing.T) {+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {})- cmd := newWorkspaceMcpTestCmd("set")- err := runWorkspaceMcpSet(cmd, nil)- if err == nil || !strings.Contains(err.Error(), "--mcp-config") {+ 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 TestRunWorkspaceMcpSetRejectsMultipleInputChannels(t *testing.T) {- t.Setenv("HOME", t.TempDir())- t.Setenv("MULTICA_TOKEN", "test-token")- t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)+// `null` clears a whole document elsewhere; for a single entry it is far more+// likely to be a mistake, so it is rejected.+func TestRunWorkspaceMcpAddRejectsNullEntry(t *testing.T) {+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {})- 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)+ 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")}}-func TestRunWorkspaceMcpAddUpsertsOneServer(t *testing.T) {- t.Setenv("HOME", t.TempDir())- t.Setenv("MULTICA_TOKEN", "test-token")- t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)-+func TestRunWorkspaceMcpUpdateSendsOnlyWhatChanged(t *testing.T) {var gotMethod, gotPath stringvar gotBody map[string]any- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {gotMethod, gotPath = r.Method, r.URL.Pathif 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)+ _ = json.NewEncoder(w).Encode(serverResponse("linear-v2"))+ })- 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)+ cmd := newWorkspaceMcpTestCmd("update")+ _ = cmd.Flags().Set("name", "linear-v2")+ if _, err := captureStdout(t, func() error { return runWorkspaceMcpUpdate(cmd, []string{testMcpServerID}) }); err != nil {+ t.Fatalf("runWorkspaceMcpUpdate: %v", err)}if gotMethod != http.MethodPut {t.Fatalf("method = %s, want PUT", gotMethod)}- if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-config/servers/linear" {+ if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-servers/"+testMcpServerID {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)+ if gotBody["name"] != "linear-v2" {+ t.Fatalf("body name = %v, want linear-v2", gotBody["name"])+ }+ // A rename must not silently blank the stored entry.+ if _, sent := gotBody["config"]; sent {+ t.Fatalf("body sent config on a rename-only update: %v", 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)+func TestRunWorkspaceMcpUpdateRequiresSomethingToChange(t *testing.T) {+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {})+ cmd := newWorkspaceMcpTestCmd("update")+ err := runWorkspaceMcpUpdate(cmd, []string{testMcpServerID})+ if err == nil || !strings.Contains(err.Error(), "nothing to update") {+ t.Fatalf("error = %v, want a nothing-to-update error", err)+ }+}++func TestRunWorkspaceMcpRemoveDeletesTheLibraryEntry(t *testing.T) {+ var gotMethod, gotPath string+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {+ gotMethod, gotPath = r.Method, r.URL.Path+ w.WriteHeader(http.StatusNoContent)+ })++ cmd := newWorkspaceMcpTestCmd("remove")+ if _, err := captureStdout(t, func() error { return runWorkspaceMcpRemove(cmd, []string{testMcpServerID}) }); err != nil {+ t.Fatalf("runWorkspaceMcpRemove: %v", err)+ }++ if gotMethod != http.MethodDelete {+ t.Fatalf("method = %s, want DELETE", gotMethod)+ }+ if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-servers/"+testMcpServerID {+ t.Fatalf("path = %q", gotPath)+ }+}++// The positional workspace argument is honoured, so an admin can target a+// workspace that is not their profile default.+func TestRunWorkspaceMcpUsesWorkspaceArgument(t *testing.T) {+ const wsUUID = "33333333-3333-3333-3333-333333333333"var gotPath string- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {gotPath = r.URL.Pathw.Header().Set("Content-Type", "application/json")- _ = json.NewEncoder(w).Encode(inventoryResponse("my server"))- }))- defer srv.Close()- t.Setenv("MULTICA_SERVER_URL", srv.URL)+ _ = json.NewEncoder(w).Encode([]map[string]any{})+ })- 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)+ cmd := newWorkspaceMcpTestCmd("list")+ if _, err := captureStdout(t, func() error { return runWorkspaceMcpList(cmd, []string{wsUUID}) }); err != nil {+ t.Fatalf("runWorkspaceMcpList: %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)+ if gotPath != "/api/workspaces/"+wsUUID+"/mcp-servers" {+ t.Fatalf("path = %q, want the positional workspace to win", 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)+func newAgentMcpTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "mcp"}+ cmd.Flags().String("workspace-id", "", "")+ cmd.Flags().String("profile", "", "")+ cmd.Flags().String("server-url", "", "")+ cmd.Flags().String("output", "table", "")+ return cmd+}- 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")+func TestRunAgentMcpAddAssignsAServer(t *testing.T) {+ var gotMethod, gotPath string+ var gotBody map[string]any+ mcpTestServer(t, 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)+ }+ server := serverResponse("linear")+ server["enabled"] = true+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode([]map[string]any{server})+ })++ cmd := newAgentMcpTestCmd()+ out, err := captureStdout(t, func() error { return runAgentMcpAdd(cmd, []string{testMcpAgentID, testMcpServerID}) })+ if err != nil {+ t.Fatalf("runAgentMcpAdd: %v", err)}- 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")+ if gotMethod != http.MethodPost {+ t.Fatalf("method = %s, want POST", gotMethod)+ }+ if gotPath != "/api/agents/"+testMcpAgentID+"/mcp-servers" {+ t.Fatalf("path = %q", gotPath)+ }+ if gotBody["server_id"] != testMcpServerID {+ t.Fatalf("body server_id = %v, want %s", gotBody["server_id"], testMcpServerID)+ }+ if !strings.Contains(out, "enabled") {+ t.Fatalf("table output missing the assignment state: %q", out)}}-func TestRunWorkspaceMcpAddRequiresAnInputChannel(t *testing.T) {- t.Setenv("HOME", t.TempDir())- t.Setenv("MULTICA_TOKEN", "test-token")- t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)+func TestRunAgentMcpDisableAndEnable(t *testing.T) {+ var gotPath string+ var gotBody map[string]any+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {+ gotPath = r.URL.Path+ if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {+ t.Fatalf("decode request body: %v", err)+ }+ server := serverResponse("linear")+ server["enabled"] = gotBody["enabled"]+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode([]map[string]any{server})+ })- 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)+ cmd := newAgentMcpTestCmd()+ out, err := captureStdout(t, func() error { return runAgentMcpDisable(cmd, []string{testMcpAgentID, testMcpServerID}) })+ if err != nil {+ t.Fatalf("runAgentMcpDisable: %v", err)+ }+ if gotPath != "/api/agents/"+testMcpAgentID+"/mcp-servers/"+testMcpServerID+"/enabled" {+ t.Fatalf("path = %q", gotPath)+ }+ if gotBody["enabled"] != false {+ t.Fatalf("body enabled = %v, want false", gotBody["enabled"])+ }+ if !strings.Contains(out, "disabled") {+ t.Fatalf("table output should show the server as disabled: %q", out)}-}-func TestRunWorkspaceMcpRemoveDeletesOneServer(t *testing.T) {- t.Setenv("HOME", t.TempDir())- t.Setenv("MULTICA_TOKEN", "test-token")- t.Setenv("MULTICA_WORKSPACE_ID", testWorkspaceMcpID)+ if _, err := captureStdout(t, func() error { return runAgentMcpEnable(cmd, []string{testMcpAgentID, testMcpServerID}) }); err != nil {+ t.Fatalf("runAgentMcpEnable: %v", err)+ }+ if gotBody["enabled"] != true {+ t.Fatalf("body enabled = %v, want true", gotBody["enabled"])+ }+}+func TestRunAgentMcpRemoveDropsTheAssignment(t *testing.T) {var gotMethod, gotPath string- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {gotMethod, gotPath = r.Method, r.URL.Pathw.Header().Set("Content-Type", "application/json")- _ = json.NewEncoder(w).Encode(inventoryResponse())- }))- defer srv.Close()- t.Setenv("MULTICA_SERVER_URL", srv.URL)+ _ = json.NewEncoder(w).Encode([]map[string]any{})+ })- cmd := newWorkspaceMcpTestCmd("remove")- if _, err := captureStdout(t, func() error { return runWorkspaceMcpRemove(cmd, []string{"linear"}) }); err != nil {- t.Fatalf("runWorkspaceMcpRemove: %v", err)+ cmd := newAgentMcpTestCmd()+ if _, err := captureStdout(t, func() error { return runAgentMcpRemove(cmd, []string{testMcpAgentID, testMcpServerID}) }); err != nil {+ t.Fatalf("runAgentMcpRemove: %v", err)}-if gotMethod != http.MethodDelete {t.Fatalf("method = %s, want DELETE", gotMethod)}- if gotPath != "/api/workspaces/"+testWorkspaceMcpID+"/mcp-config/servers/linear" {+ if gotPath != "/api/agents/"+testMcpAgentID+"/mcp-servers/"+testMcpServerID {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+func TestRunAgentMcpListNeverPrintsSecrets(t *testing.T) {+ mcpTestServer(t, func(w http.ResponseWriter, r *http.Request) {+ server := poisonedServerResponse("linear")+ server["enabled"] = truew.Header().Set("Content-Type", "application/json")- _ = json.NewEncoder(w).Encode(inventoryResponse())- }))- defer srv.Close()- t.Setenv("MULTICA_SERVER_URL", srv.URL)+ _ = json.NewEncoder(w).Encode([]map[string]any{server})+ })- cmd := newWorkspaceMcpTestCmd("remove")- if _, err := captureStdout(t, func() error { return runWorkspaceMcpRemove(cmd, []string{"linear", wsUUID}) }); err != nil {- t.Fatalf("runWorkspaceMcpRemove: %v", err)+ cmd := newAgentMcpTestCmd()+ _ = cmd.Flags().Set("output", "json")+ out, err := captureStdout(t, func() error { return runAgentMcpList(cmd, []string{testMcpAgentID}) })+ if err != nil {+ t.Fatalf("runAgentMcpList: %v", err)}- if gotPath != "/api/workspaces/"+wsUUID+"/mcp-config/servers/linear" {- t.Fatalf("path = %q, want the positional workspace to win", gotPath)+ for _, marker := range workspaceMcpLeakMarkers {+ if strings.Contains(out, marker) {+ t.Fatalf("agent mcp list leaked %q: %q", marker, out)+ }}}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex ca5fcc2449..8dc2ec10d2 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1160,11 +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)+ // The workspace MCP library — member-visible so an agent+ // owner can see what is available to add to their agent.+ // The payload is names and transports only; the stored+ // entries are write-only.+ r.Get("/mcp-servers", h.ListWorkspaceMcpServers)r.Get("/plugins", h.ListPlugins)r.Get("/plugins/private", h.ListPrivatePlugins)r.Get("/plugins/private/{pluginRef}", h.GetPrivatePluginStatus)@@ -1182,14 +1182,12 @@ 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)+ // Curating the shared MCP library is an admin action.+ // Creating an entry binds it to no agent; an agent owner+ // adds it to their own agent through the agent routes.+ r.Post("/mcp-servers", h.CreateWorkspaceMcpServer)+ r.Put("/mcp-servers/{serverId}", h.UpdateWorkspaceMcpServer)+ r.Delete("/mcp-servers/{serverId}", h.DeleteWorkspaceMcpServer)// Custom runtime profile mutations (admin-only).r.Post("/runtime-profiles", h.CreateRuntimeProfile)r.Patch("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)@@ -1611,6 +1609,14 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Put("/skills/{skillId}/enabled", h.SetAgentSkillEnabled)r.Put("/runtime-skills/enabled", h.SetAgentRuntimeSkillEnabled)r.Delete("/skills/{skillId}", h.RemoveAgentSkill)+ // Workspace MCP servers assigned to this agent. Mirrors+ // the skills routes above: a library entry does nothing+ // until it is added here, and the binding carries its own+ // enabled toggle.+ r.Get("/mcp-servers", h.ListAgentMcpServers)+ r.Post("/mcp-servers", h.AddAgentMcpServer)+ r.Put("/mcp-servers/{serverId}/enabled", h.SetAgentMcpServerEnabled)+ r.Delete("/mcp-servers/{serverId}", h.RemoveAgentMcpServer)// Dedicated env-management endpoint. Admits the agent// owner or a workspace owner/admin; agent actors are// denied. Every reveal / write is audited todiff --git a/server/internal/daemon/runtime_mcp_workspace_test.go b/server/internal/daemon/runtime_mcp_workspace_test.goindex 953fed8454..bfe5c940b4 100644--- a/server/internal/daemon/runtime_mcp_workspace_test.go+++ b/server/internal/daemon/runtime_mcp_workspace_test.go@@ -10,18 +10,18 @@ import ()// 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.+// through — the server's binding 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 {+func effectiveServerNames(t *testing.T, provider string, bound []handler.WorkspaceMcpBinding, agentCfg string) map[string]any {t.Helper()- resolved, err := handler.ResolveWorkspaceMcpConfig(json.RawMessage(workspaceCfg), json.RawMessage(agentCfg))+ resolved, err := handler.ResolveAgentMcpConfig(bound, json.RawMessage(agentCfg))if err != nil {- t.Fatalf("ResolveWorkspaceMcpConfig: %v", err)+ t.Fatalf("ResolveAgentMcpConfig: %v", err)}merged, err := mergeRuntimeAndAgentMcpConfig(provider, resolved)if err != nil {@@ -55,15 +55,15 @@ func writeOpencodeRuntimeConfig(t *testing.T, servers string) {}// 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.+// container must keep them once it is given a workspace server. The daemon's+// merge only falls back to `mcp` when `mcpServers` is ABSENT, so a resolver+// that wrote bound 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"}}}`,+ []handler.WorkspaceMcpBinding{{Name: "shared", Config: json.RawMessage(`{"url":"https://shared.example"}`)}},`{"mcp":{"private":{"command":"private-server"}}}`)for _, name := range []string{"runtime-local", "shared", "private"} {@@ -76,32 +76,31 @@ func TestWorkspaceResolveThenRuntimeMergeKeepsLegacyOpencodeServers(t *testing.T}}-// 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) {+// The same agent with nothing assigned to it must be untouched: the resolver+// passes the agent config through verbatim, so the daemon still takes its+// legacy-container fallback.+func TestWorkspaceResolveWithoutBoundServersLeavesLegacyOpencodeAgentAlone(t *testing.T) {writeOpencodeRuntimeConfig(t, `{"runtime-local":{"command":"runtime-server"}}`)- servers := effectiveServerNames(t, "opencode", "", `{"mcp":{"private":{"command":"private-server"}}}`)+ servers := effectiveServerNames(t, "opencode", nil, `{"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) {+// An agent with nothing assigned keeps running with only its runtime's own+// servers — a library entry nobody added must not reach it through the daemon+// merge either.+func TestWorkspaceResolveWithNoBindingsKeepsOnlyRuntimeServers(t *testing.T) {writeOpencodeRuntimeConfig(t, `{"runtime-local":{"command":"runtime-server"}}`)- servers := effectiveServerNames(t, "opencode",- `{"mcpServers":{"shared":{"url":"https://shared.example"}}}`, `{}`)+ servers := effectiveServerNames(t, "opencode", nil, "")- 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)+ if len(servers) != 0 {+ // A nil managed config means the provider keeps its native+ // inheritance; the daemon returns it unchanged rather than building a+ // merged document.+ t.Fatalf("effective set = %v, want the native path (no managed document)", servers)}}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 381dfecef6..d574db76bc 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1821,20 +1821,27 @@ 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+ // Fold in the workspace MCP servers this agent has been explicitly+ // given (GH #6062). Only bound AND enabled servers are read, so a+ // workspace library entry nobody added reaches nothing. Read on every+ // claim, exactly like the agent column, so an admin's edit or a toggle+ // lands on the agent's next task with nothing to restart. Errors —+ // including a failed read — leave the agent config untouched: a broken+ // shared entry must never take away servers the agent runs with today.+ if bound, err := h.Queries.ListEnabledAgentMcpServers(r.Context(), agent.ID); err != nil {+ slog.Warn("daemon claim: load agent mcp servers failed; using agent mcp_config",+ "task_id", uuidToString(task.ID), "agent_id", uuidToString(agent.ID), "error", err)+ } else if len(bound) > 0 {+ bindings := make([]WorkspaceMcpBinding, 0, len(bound))+ for _, server := range bound {+ bindings = append(bindings, WorkspaceMcpBinding{Name: server.Name, Config: json.RawMessage(server.Config)})+ }+ if resolved, err := ResolveAgentMcpConfig(bindings, mcpConfig); err != nil {+ slog.Warn("daemon claim: resolve agent mcp servers failed; falling back to agent mcp_config",+ "task_id", uuidToString(task.ID), "agent_id", uuidToString(agent.ID), "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 thediff --git a/server/internal/handler/daemon_claim_workspace_mcp_test.go b/server/internal/handler/daemon_claim_workspace_mcp_test.goindex 3c76885f12..5b8e331360 100644--- a/server/internal/handler/daemon_claim_workspace_mcp_test.go+++ b/server/internal/handler/daemon_claim_workspace_mcp_test.go@@ -34,12 +34,19 @@ func claimAgentMcpConfigForTest(t *testing.T, runtimeID string) json.RawMessage}// 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 {+// saved mcp_config, one queued task ready to claim, and binds the named+// workspace MCP servers to that agent.+func setupWorkspaceMcpClaimFixture(t *testing.T, ctx context.Context, name, agentMcpConfig string, bind ...string) string {t.Helper()runtimeID := createClaimReclaimRuntime(t, ctx, name+" runtime")agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, name+" agent")+ for _, serverID := range bind {+ if _, err := testPool.Exec(ctx,+ `INSERT INTO agent_mcp_server (agent_id, server_id) VALUES ($1, $2)`, agentID, serverID); err != nil {+ t.Fatalf("setup: bind mcp server: %v", err)+ }+ }var stored []byteif agentMcpConfig != "" {@@ -62,56 +69,78 @@ func setupWorkspaceMcpClaimFixture(t *testing.T, ctx context.Context, name, agenreturn 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) {+// The claim payload is where a bound workspace server actually reaches an+// agent, so assert the resolved document on the wire — not just the resolver.+func TestClaimTaskByRuntime_CarriesBoundWorkspaceMcpServers(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", "")+ serverID := createWorkspaceMcpServerForTest(t, "shared", `{"url":"https://shared.example"}`)+ runtimeID := setupWorkspaceMcpClaimFixture(t, ctx, "ws-mcp-bound", "", serverID)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))+ t.Fatalf("agent should run the server it was given, got %v", serverNames(servers))}}-func TestClaimTaskByRuntime_MergesWorkspaceAndAgentMcpConfig(t *testing.T) {+// The defining property, asserted end to end: a library entry nobody added+// reaches nothing, however many agents exist.+func TestClaimTaskByRuntime_UnboundWorkspaceMcpServerReachesNoAgent(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"}}}`)+ createWorkspaceMcpServerForTest(t, "shared", `{"url":"https://shared.example"}`)+ runtimeID := setupWorkspaceMcpClaimFixture(t, ctx, "ws-mcp-unbound", "")- servers := decodeServers(t, claimAgentMcpConfigForTest(t, runtimeID))- if len(servers) != 3 {- t.Fatalf("server set = %v, want shared/linear/private", serverNames(servers))+ mcpConfig := claimAgentMcpConfigForTest(t, runtimeID)+ if servers := decodeServers(t, mcpConfig); len(servers) != 0 {+ t.Fatalf("an unassigned workspace server reached the agent: %v", 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"])+ // And nothing managed at all, so the runtime keeps its native inheritance.+ if len(mcpConfig) != 0 {+ t.Fatalf("mcp_config = %s, want nothing managed", mcpConfig)}}-func TestClaimTaskByRuntime_ZeroServerAgentIgnoresWorkspaceMcpConfig(t *testing.T) {+// A binding that is switched off is the same as not having it, without losing+// the assignment.+func TestClaimTaskByRuntime_DisabledBindingIsNotCarried(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", `{}`)+ serverID := createWorkspaceMcpServerForTest(t, "shared", `{"url":"https://shared.example"}`)+ runtimeID := setupWorkspaceMcpClaimFixture(t, ctx, "ws-mcp-disabled", "", serverID)+ if _, err := testPool.Exec(ctx,+ `UPDATE agent_mcp_server SET enabled = FALSE WHERE server_id = $1`, serverID); err != nil {+ t.Fatalf("disable binding: %v", err)+ }- mcpConfig := claimAgentMcpConfigForTest(t, runtimeID)- if servers := decodeServers(t, mcpConfig); len(servers) != 0 {- t.Fatalf("opted-out agent received %v", serverNames(servers))+ if servers := decodeServers(t, claimAgentMcpConfigForTest(t, runtimeID)); len(servers) != 0 {+ t.Fatalf("a disabled binding was carried: %v", serverNames(servers))+ }+}++func TestClaimTaskByRuntime_MergesBoundAndAgentOwnMcpServers(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ shared := createWorkspaceMcpServerForTest(t, "shared", `{"url":"https://shared.example"}`)+ linear := createWorkspaceMcpServerForTest(t, "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"}}}`,+ shared, linear)++ servers := decodeServers(t, claimAgentMcpConfigForTest(t, runtimeID))+ if len(servers) != 3 {+ t.Fatalf("server set = %v, want shared/linear/private", 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)+ entry, _ := servers["linear"].(map[string]any)+ if entry["url"] != "https://agent-linear.example" {+ t.Errorf("the agent's own entry must win the name collision, got %v", entry["url"])}}diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex e327897a1c..889edc39e5 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -168,35 +168,12 @@ func (h *Handler) ListWorkspaces(w http.ResponseWriter, r *http.Request) {resp := make([]WorkspaceResponse, len(workspaces))for i, ws := range workspaces {- resp[i] = h.listWorkspacesRowToResponse(ws)+ resp[i] = h.workspaceToResponse(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_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 42eb91c93d..4953031e63 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -80,6 +80,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"lark_outbound_card_message": workspaceDelete,"lark_user_binding": workspaceDelete,"member": workspaceDelete,+ "agent_mcp_server": workspaceDelete,+ "workspace_mcp_server": workspaceDelete,"notification_preference": workspaceDelete,"personal_access_token": workspaceDeleteKeep,"pinned_item": workspaceDelete,diff --git a/server/internal/handler/workspace_mcp.go b/server/internal/handler/workspace_mcp.goindex 354d9bd20e..542a64148c 100644--- a/server/internal/handler/workspace_mcp.go+++ b/server/internal/handler/workspace_mcp.go@@ -15,109 +15,92 @@ import (// `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+// WorkspaceMcpBinding is one workspace MCP server that an agent has been+// explicitly given: the name it is mounted under plus its entry.+type WorkspaceMcpBinding struct {+ Name string+ Config json.RawMessage+}++// ResolveAgentMcpConfig folds the workspace MCP servers BOUND to an agent into+// that agent's own mcp_config and returns what the claim should carry. It runs+// before the per-task overlay (mergeMCPOverlay), so the full precedence chain+// on a claim is://-// The resolution contract (GH #6062, MUL-5421):+// bound workspace servers < agent's own servers < per-task overlay//-// - 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.+// The contract (GH #6062, MUL-5421)://-// - 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.+// - Only servers explicitly bound to this agent and left enabled are folded+// in. A workspace MCP server is a LIBRARY entry, exactly like a workspace+// skill: creating one gives it to nobody. Nothing about this layer reaches+// an agent implicitly, which is what keeps shared credentials from+// spreading to agents no one opted in.//-// - 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.+// - The agent's own entry WINS on a name collision. Its config is the more+// specific statement, and it is the one an agent owner edits directly.//-// - 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.+// - An agent with no bindings and no config of its own resolves to nil —+// "nothing managed" — so its runtime keeps its native MCP inheritance.//-// 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+// Shape: the result is NORMALIZED onto the canonical `mcpServers` container,+// including an agent's legacy top-level `mcp` entries. Normalizing is+// mandatory, not cosmetic: the daemon's runtime merge only falls back to the+// legacy container when `mcpServers` is ABSENT+// (`internal/daemon/runtime_mcp.go`), so writing bound 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.+// the daemon read the bound set and silently drop the agent's own servers.//-// 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) {+// Failure mode: on a malformed agent config the config is returned unchanged+// along with the error. Binding a shared server must never take away servers+// the agent runs with today.+func ResolveAgentMcpConfig(bound []WorkspaceMcpBinding, agentMcpConfig json.RawMessage) (json.RawMessage, error) {+ if len(bound) == 0 {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)+ shared := make(map[string]json.RawMessage, len(bound))+ for _, server := range bound {+ if server.Name == "" || !hasManagedJSON(server.Config) {+ continue+ }+ shared[server.Name] = server.Config}- if len(wsServers) == 0 {- // Nothing shared — leave the agent layer exactly as it was.+ if len(shared) == 0 {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)+ // The agent declares nothing of its own: it runs with exactly the+ // servers it was given.+ out, err := json.Marshal(map[string]any{"mcpServers": shared})if err != nil {- return nil, fmt.Errorf("resolve workspace mcp_config: marshal workspace document: %w", err)+ return nil, fmt.Errorf("resolve agent mcp_config: marshal bound servers: %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)+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("resolve agent mcp_config: parse agent mcp_config: %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.+ // The agent may declare this name in either container; 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`).+ // 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)+ return passthroughAgentMcpConfig(agentMcpConfig), fmt.Errorf("resolve agent mcp_config: agent %s: %w", container, err)}for name, server := range own {merged[name] = server@@ -135,21 +118,21 @@ func ResolveWorkspaceMcpConfig(workspaceMcpConfig, agentMcpConfig json.RawMessag}serversBytes, err := json.Marshal(merged)if err != nil {- return nil, fmt.Errorf("resolve workspace mcp_config: marshal merged servers: %w", err)+ return nil, fmt.Errorf("resolve agent mcp_config: marshal merged servers: %w", err)}out["mcpServers"] = serversBytesfinal, err := json.Marshal(out)if err != nil {- return nil, fmt.Errorf("resolve workspace mcp_config: marshal merged document: %w", err)+ return nil, fmt.Errorf("resolve agent 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.+// what "the agent already owns this name" keys 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.RawMessageif err := json.Unmarshal(raw, &doc); err != nil {@@ -171,39 +154,39 @@ func parseMcpDocument(raw json.RawMessage) (map[string]json.RawMessage, map[strireturn 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 {+// validateWorkspaceMcpServerEntry checks the shape of ONE server entry before+// it is stored. Deliberately shallow — shape only, never the contents, which+// are runtime-specific and carry secrets we do not want to inspect or echo+// back in an error.+func validateWorkspaceMcpServerEntry(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")+ return errors.New("config must be a JSON object")}- 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")+ var entry map[string]json.RawMessage+ if err := json.Unmarshal(trimmed, &entry); err != nil {+ // Never wrap: the underlying error can echo fragments of an entry that+ // routinely embeds API tokens.+ return errors.New("config must be a JSON object")}- 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`)+ if len(entry) == 0 {+ return errors.New("config must not be empty")}- 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+}++// validateWorkspaceMcpServerName checks a server name. The name is what the+// runtime mounts the server under and what an agent's own config collides+// with, so it follows the same rule the agent settings dialog enforces.+func validateWorkspaceMcpServerName(name string) error {+ if name == "" {+ return errors.New("name is required")+ }+ for _, r := range name {+ switch {+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':+ default:+ return errors.New("name may only contain letters, digits, hyphens, and underscores")}}return nildiff --git a/server/internal/handler/workspace_mcp_api.go b/server/internal/handler/workspace_mcp_api.goindex 5264b35692..60088d9f9c 100644--- a/server/internal/handler/workspace_mcp_api.go+++ b/server/internal/handler/workspace_mcp_api.go@@ -1,12 +1,9 @@package handlerimport (- "bytes""encoding/json"- "errors""log/slog""net/http"- "sort""strings""github.com/go-chi/chi/v5"@@ -15,35 +12,35 @@ import (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+// WorkspaceMcpServerResponse is the intentionally non-secret shape of one+// workspace MCP server. Never add `url`, `command`, `args`, `headers`, or+// `env`: 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"`+// `Enabled` is only meaningful on the agent-scoped list, where it reflects the+// binding's toggle; it is omitted on the workspace library listing.+type WorkspaceMcpServerResponse struct {+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ Name string `json:"name"`+ Transport string `json:"transport"`+ Enabled *bool `json:"enabled,omitempty"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`}-// 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.+// mcpTransportOf classifies a server entry for display, and — because the+// client uses it to decide whether the guided form may edit an entry — it must+// not be lossy about an explicit `type`.+//+// An unrecognised explicit type is returned VERBATIM rather than inferred from+// the presence of a `url`. Reporting `{"type":"websocket","url":"wss://…"}` as+// "http" would tell the settings UI the form can express it, and saving from+// that form rewrites the entry to `type: "http"` — silently changing the+// protocol. Only an entry with NO explicit type is inferred from command / url,+// which is lossless because the form writes that same shape back.func mcpTransportOf(entry json.RawMessage) string {var e struct {Type string `json:"type"`@@ -53,13 +50,16 @@ func mcpTransportOf(entry json.RawMessage) string {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 declared := strings.ToLower(strings.TrimSpace(e.Type)); declared != "" {+ switch declared {+ case "local", "stdio":+ return "stdio"+ case "remote", "http", "streamable-http":+ return "http"+ }+ // `sse` and anything a newer client invents land here unchanged. The+ // response schema keeps transport a free string for exactly this.+ return declared}if len(e.Command) > 0 {return "stdio"@@ -70,62 +70,21 @@ func mcpTransportOf(entry json.RawMessage) string {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+func workspaceMcpServerToResponse(server db.WorkspaceMcpServer) WorkspaceMcpServerResponse {+ return WorkspaceMcpServerResponse{+ ID: uuidToString(server.ID),+ WorkspaceID: uuidToString(server.WorkspaceID),+ Name: server.Name,+ Transport: mcpTransportOf(server.Config),+ CreatedAt: timestampToString(server.CreatedAt),+ UpdatedAt: timestampToString(server.UpdatedAt),}- 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) {+// ListWorkspaceMcpServers returns the workspace's MCP library. Member-visible:+// the payload carries no credential material, and an agent owner needs to see+// what is available to add.+func (h *Handler) ListWorkspaceMcpServers(w http.ResponseWriter, r *http.Request) {workspaceID := workspaceIDFromURL(r, "id")idUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")if !ok {@@ -134,25 +93,29 @@ func (h *Handler) GetWorkspaceMcpConfig(w http.ResponseWriter, r *http.Request)if _, ok := h.workspaceMember(w, r, workspaceID); !ok {return}- ws, err := h.Queries.GetWorkspace(r.Context(), idUUID)+ servers, err := h.Queries.ListWorkspaceMcpServers(r.Context(), idUUID)if err != nil {- writeError(w, http.StatusNotFound, "workspace not found")+ writeError(w, http.StatusInternalServerError, "failed to list workspace MCP servers")return}- writeJSON(w, http.StatusOK, buildWorkspaceMcpConfigResponse(ws))+ resp := make([]WorkspaceMcpServerResponse, 0, len(servers))+ for _, server := range servers {+ resp = append(resp, workspaceMcpServerToResponse(server))+ }+ writeJSON(w, http.StatusOK, resp)}-// 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.+// requireWorkspaceMcpWriter 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: adding a shared 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")+ writeError(w, http.StatusForbidden, "agents cannot modify the workspace MCP servers")return false}if !roleAllowed(member.Role, "owner", "admin") {@@ -162,19 +125,17 @@ func (h *Handler) requireWorkspaceMcpWriter(w http.ResponseWriter, r *http.Requereturn 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"`+// WorkspaceMcpServerRequest carries one server entry. `config` is the object+// that sits under a name in `mcpServers`; it is write-only and never returned.+type WorkspaceMcpServerRequest struct {+ Name string `json:"name"`+ Config json.RawMessage `json:"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) {+// CreateWorkspaceMcpServer adds a server to the workspace library. It is bound+// to NO agent — the library entry has to be added to an agent before it does+// anything, which is the whole shape of this feature.+func (h *Handler) CreateWorkspaceMcpServer(w http.ResponseWriter, r *http.Request) {workspaceID := workspaceIDFromURL(r, "id")idUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")if !ok {@@ -184,46 +145,66 @@ func (h *Handler) UpdateWorkspaceMcpConfig(w http.ResponseWriter, r *http.Requesreturn}- var req UpdateWorkspaceMcpConfigRequest+ var req WorkspaceMcpServerRequestif 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")+ name := strings.TrimSpace(req.Name)+ if err := validateWorkspaceMcpServerName(name); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ if err := validateWorkspaceMcpServerEntry(req.Config); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }++ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create the MCP server")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ // Join the workspace teardown fence (#5219): this table has no FK, so+ // without the shared lock a create committing after DeleteWorkspace swept+ // would leave a row pointing at a workspace that no longer exists.+ if _, err := qtx.LockWorkspaceForChatSessionCreate(r.Context(), idUUID); err != nil {+ writeError(w, http.StatusNotFound, "workspace not found")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())+ server, err := qtx.CreateWorkspaceMcpServer(r.Context(), db.CreateWorkspaceMcpServerParams{+ WorkspaceID: idUUID,+ Name: name,+ Config: append([]byte(nil), req.Config...),+ CreatedBy: parseUUID(requestUserID(r)),+ })+ if err != nil {+ if isUniqueViolation(err) {+ writeError(w, http.StatusConflict, "an MCP server with this name already exists in the workspace")return}- ws, err = h.Queries.SetWorkspaceMcpConfig(r.Context(), db.SetWorkspaceMcpConfigParams{- ID: idUUID,- McpConfig: append([]byte(nil), req.McpConfig...),- })+ slog.Warn("create workspace mcp server failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to create the MCP server")+ return}- 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")+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create the MCP server")return}-- h.writeWorkspaceMcpConfigResult(w, r, ws, "replaced")+ // Name only — never the entry — so the audit trail cannot become a second+ // copy of the workspace's credentials.+ slog.Info("workspace mcp server created", append(logger.RequestAttrs(r),+ "workspace_id", workspaceID, "server_id", uuidToString(server.ID), "name", server.Name)...)+ writeJSON(w, http.StatusCreated, workspaceMcpServerToResponse(server))}-// 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) {+// UpdateWorkspaceMcpServer replaces one library entry. Renaming is safe here:+// bindings key off the id, so an agent that uses this server keeps using it.+func (h *Handler) UpdateWorkspaceMcpServer(w http.ResponseWriter, r *http.Request) {workspaceID := workspaceIDFromURL(r, "id")idUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")if !ok {@@ -232,42 +213,49 @@ func (h *Handler) UpsertWorkspaceMcpServer(w http.ResponseWriter, r *http.Requesif !h.requireWorkspaceMcpWriter(w, r, workspaceID) {return}- name := strings.TrimSpace(chi.URLParam(r, "serverName"))- if name == "" {- writeError(w, http.StatusBadRequest, "server name is required")+ serverUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "serverId"), "server id")+ if !ok {return}- var entry json.RawMessage- if err := json.NewDecoder(r.Body).Decode(&entry); err != nil {+ var req WorkspaceMcpServerRequest+ if err := json.NewDecoder(r.Body).Decode(&req); 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+ params := db.UpdateWorkspaceMcpServerParams{ID: serverUUID, WorkspaceID: idUUID}+ if name := strings.TrimSpace(req.Name); name != "" {+ if err := validateWorkspaceMcpServerName(name); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ params.Name = pgtype.Text{String: name, Valid: true}}- if verr := validateWorkspaceMcpConfig(probe); verr != nil {- writeError(w, http.StatusBadRequest, verr.Error())- return+ if len(req.Config) > 0 {+ if err := validateWorkspaceMcpServerEntry(req.Config); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ params.Config = append([]byte(nil), req.Config...)}- ws, ok := h.mutateWorkspaceMcpServers(w, r, idUUID, workspaceID, func(servers map[string]json.RawMessage) error {- servers[name] = entry- return nil- })- if !ok {+ server, err := h.Queries.UpdateWorkspaceMcpServer(r.Context(), params)+ if err != nil {+ if isUniqueViolation(err) {+ writeError(w, http.StatusConflict, "an MCP server with this name already exists in the workspace")+ return+ }+ writeError(w, http.StatusNotFound, "MCP server not found")return}- h.writeWorkspaceMcpConfigResult(w, r, ws, "server_upserted")+ slog.Info("workspace mcp server updated", append(logger.RequestAttrs(r),+ "workspace_id", workspaceID, "server_id", uuidToString(server.ID), "name", server.Name)...)+ writeJSON(w, http.StatusOK, workspaceMcpServerToResponse(server))}-// 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.+// DeleteWorkspaceMcpServer removes a library entry and every binding to it, in+// one transaction — the binding table carries no FK, so an orphaned row would+// otherwise keep pointing at a server that no longer exists.func (h *Handler) DeleteWorkspaceMcpServer(w http.ResponseWriter, r *http.Request) {workspaceID := workspaceIDFromURL(r, "id")idUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")@@ -277,119 +265,266 @@ func (h *Handler) DeleteWorkspaceMcpServer(w http.ResponseWriter, r *http.Requesif !h.requireWorkspaceMcpWriter(w, r, workspaceID) {return}- name := strings.TrimSpace(chi.URLParam(r, "serverName"))- if name == "" {- writeError(w, http.StatusBadRequest, "server name is required")+ serverUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "serverId"), "server id")+ if !ok {+ return+ }++ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete the MCP server")return}+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)- 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+ // Exclusive row lock first: an assignment writer holds this row FOR SHARE+ // while it inserts, so taking it here means a concurrent add either lands+ // before this transaction (and is swept below) or waits and then finds the+ // server gone. Without it the add could insert after the sweep, leaving a+ // binding to a server that no longer exists.+ if _, err := qtx.LockWorkspaceMcpServerForUpdate(r.Context(), db.LockWorkspaceMcpServerForUpdateParams{+ ID: serverUUID,+ WorkspaceID: idUUID,+ }); err != nil {+ writeError(w, http.StatusNotFound, "MCP server not found")+ return+ }++ rows, err := qtx.DeleteWorkspaceMcpServer(r.Context(), db.DeleteWorkspaceMcpServerParams{+ ID: serverUUID,+ WorkspaceID: idUUID,})- if !ok {+ if err != nil {+ slog.Warn("delete workspace mcp server failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to delete the MCP server")+ return+ }+ if rows == 0 {+ writeError(w, http.StatusNotFound, "MCP server not found")+ return+ }+ if err := qtx.DeleteAgentMcpServersByServer(r.Context(), serverUUID); err != nil {+ slog.Warn("sweep agent mcp bindings failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to delete the MCP server")+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete the MCP server")return}- h.writeWorkspaceMcpConfigResult(w, r, ws, "server_deleted")+ slog.Info("workspace mcp server deleted", append(logger.RequestAttrs(r),+ "workspace_id", workspaceID, "server_id", uuidToString(serverUUID))...)+ w.WriteHeader(http.StatusNoContent)}-// 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"}+// ListAgentMcpServers returns the workspace servers bound to this agent, with+// each binding's toggle state.+func (h *Handler) ListAgentMcpServers(w http.ResponseWriter, r *http.Request) {+ agent, ok := h.loadAgentForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ rows, err := h.Queries.ListAgentMcpServers(r.Context(), agent.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list the agent's MCP servers")+ return+ }+ resp := make([]WorkspaceMcpServerResponse, 0, len(rows))+ for _, row := range rows {+ enabled := row.Enabled+ resp = append(resp, WorkspaceMcpServerResponse{+ ID: uuidToString(row.ID),+ WorkspaceID: uuidToString(row.WorkspaceID),+ Name: row.Name,+ Transport: mcpTransportOf(row.Config),+ Enabled: &enabled,+ CreatedAt: timestampToString(row.CreatedAt),+ UpdatedAt: timestampToString(row.UpdatedAt),+ })+ }+ writeJSON(w, http.StatusOK, resp)+}-type workspaceMcpError struct {- status int- message string+// requireAgentMcpWriter resolves the agent and enforces who may change its+// bindings. Same rule as the agent's own mcp_config: the agent owner or a+// workspace owner/admin, never an agent actor.+func (h *Handler) requireAgentMcpWriter(w http.ResponseWriter, r *http.Request) (db.Agent, bool) {+ agent, ok := h.loadAgentForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return db.Agent{}, false+ }+ workspaceID := uuidToString(agent.WorkspaceID)+ if actorType, _ := h.resolveActor(r, requestUserID(r), workspaceID); actorType == "agent" {+ writeError(w, http.StatusForbidden, "agents cannot modify MCP server assignments")+ return db.Agent{}, false+ }+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return db.Agent{}, false+ }+ if !canViewAgentSecrets(agent, requestUserID(r), member.Role) {+ writeError(w, http.StatusForbidden, "insufficient permissions")+ return db.Agent{}, false+ }+ return agent, true}-func (e *workspaceMcpError) Error() string { return e.message }+// AddAgentMcpServerRequest names the library entry to attach.+type AddAgentMcpServerRequest struct {+ ServerID string `json:"server_id"`+}-// 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) {+// AddAgentMcpServer gives one workspace MCP server to this agent. This is the+// only way a library entry reaches an agent.+func (h *Handler) AddAgentMcpServer(w http.ResponseWriter, r *http.Request) {+ agent, ok := h.requireAgentMcpWriter(w, r)+ if !ok {+ return+ }+ var req AddAgentMcpServerRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ serverUUID, ok := parseUUIDOrBadRequest(w, strings.TrimSpace(req.ServerID), "server_id")+ if !ok {+ return+ }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+ writeError(w, http.StatusInternalServerError, "failed to add the MCP server")+ return}defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)- current, err := qtx.LockWorkspaceMcpConfig(r.Context(), idUUID)- if err != nil {+ // Same fence as every other workspace-scoped insert (#5219): the binding+ // has no FK, so a write committing after DeleteWorkspace swept would+ // outlive the agent and the server it names.+ if _, err := qtx.LockWorkspaceForChatSessionCreate(r.Context(), agent.WorkspaceID); err != nil {writeError(w, http.StatusNotFound, "workspace not found")- return db.Workspace{}, false+ return}-- 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+ // Scope check AND the delete protocol in one statement: the row must+ // belong to this agent's workspace — an id from another workspace would+ // bind across the tenant boundary — and holding it FOR SHARE serializes+ // this insert against DeleteWorkspaceMcpServer's sweep.+ if _, err := qtx.LockWorkspaceMcpServerForShare(r.Context(), db.LockWorkspaceMcpServerForShareParams{+ ID: serverUUID,+ WorkspaceID: agent.WorkspaceID,+ }); err != nil {+ writeError(w, http.StatusNotFound, "MCP server not found in this workspace")+ return}+ if err := qtx.AddAgentMcpServer(r.Context(), db.AddAgentMcpServerParams{+ AgentID: agent.ID,+ ServerID: serverUUID,+ }); err != nil {+ slog.Warn("add agent mcp server failed", append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(agent.ID))...)+ writeError(w, http.StatusInternalServerError, "failed to add the MCP server")+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to add the MCP server")+ return+ }+ slog.Info("agent mcp server added", append(logger.RequestAttrs(r),+ "agent_id", uuidToString(agent.ID), "server_id", uuidToString(serverUUID))...)+ h.writeAgentMcpServers(w, r, agent.ID)+}- 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+// SetAgentMcpServerEnabledRequest carries the per-agent toggle.+type SetAgentMcpServerEnabledRequest struct {+ Enabled *bool `json:"enabled"`+}++// SetAgentMcpServerEnabled flips one binding's toggle without dropping it, so+// turning a server back on does not mean finding it again.+func (h *Handler) SetAgentMcpServerEnabled(w http.ResponseWriter, r *http.Request) {+ agent, ok := h.requireAgentMcpWriter(w, r)+ if !ok {+ return+ }+ serverUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "serverId"), "server id")+ if !ok {+ return+ }+ var req SetAgentMcpServerEnabledRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return}+ if req.Enabled == nil {+ writeError(w, http.StatusBadRequest, "enabled is required")+ return+ }+ rows, err := h.Queries.SetAgentMcpServerEnabled(r.Context(), db.SetAgentMcpServerEnabledParams{+ AgentID: agent.ID,+ ServerID: serverUUID,+ Enabled: *req.Enabled,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update the MCP server")+ return+ }+ if rows == 0 {+ writeError(w, http.StatusNotFound, "this MCP server is not assigned to the agent")+ return+ }+ slog.Info("agent mcp server toggled", append(logger.RequestAttrs(r),+ "agent_id", uuidToString(agent.ID), "server_id", uuidToString(serverUUID), "enabled", *req.Enabled)...)+ h.writeAgentMcpServers(w, r, agent.ID)+}- 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})- }+// RemoveAgentMcpServer takes a workspace server away from this agent. The+// library entry itself is untouched.+func (h *Handler) RemoveAgentMcpServer(w http.ResponseWriter, r *http.Request) {+ agent, ok := h.requireAgentMcpWriter(w, r)+ if !ok {+ return+ }+ serverUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "serverId"), "server id")+ if !ok {+ return}+ rows, err := h.Queries.RemoveAgentMcpServer(r.Context(), db.RemoveAgentMcpServerParams{+ AgentID: agent.ID,+ ServerID: serverUUID,+ })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+ writeError(w, http.StatusInternalServerError, "failed to remove the MCP server")+ return}- 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+ if rows == 0 {+ writeError(w, http.StatusNotFound, "this MCP server is not assigned to the agent")+ return}- return ws, true+ slog.Info("agent mcp server removed", append(logger.RequestAttrs(r),+ "agent_id", uuidToString(agent.ID), "server_id", uuidToString(serverUUID))...)+ h.writeAgentMcpServers(w, r, agent.ID)}-// 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)...)+// writeAgentMcpServers returns the agent's binding list after a mutation, so+// the client never has to guess the resulting state.+func (h *Handler) writeAgentMcpServers(w http.ResponseWriter, r *http.Request, agentID pgtype.UUID) {+ rows, err := h.Queries.ListAgentMcpServers(r.Context(), agentID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list the agent's MCP servers")+ return+ }+ resp := make([]WorkspaceMcpServerResponse, 0, len(rows))+ for _, row := range rows {+ enabled := row.Enabled+ resp = append(resp, WorkspaceMcpServerResponse{+ ID: uuidToString(row.ID),+ WorkspaceID: uuidToString(row.WorkspaceID),+ Name: row.Name,+ Transport: mcpTransportOf(row.Config),+ Enabled: &enabled,+ CreatedAt: timestampToString(row.CreatedAt),+ UpdatedAt: timestampToString(row.UpdatedAt),+ })+ }writeJSON(w, http.StatusOK, resp)}diff --git a/server/internal/handler/workspace_mcp_api_test.go b/server/internal/handler/workspace_mcp_api_test.goindex af29be9d33..32740e973a 100644--- a/server/internal/handler/workspace_mcp_api_test.go+++ b/server/internal/handler/workspace_mcp_api_test.go@@ -11,53 +11,41 @@ import (const workspaceMcpTestSecret = "sk-live-workspace-should-never-be-echoed"-var workspaceMcpTestDoc = `{"mcpServers":{"linear":{"url":"https://linear.example","headers":{"Authorization":"Bearer ` + workspaceMcpTestSecret + `"}}}}`+var workspaceMcpTestEntry = `{"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) {+// createWorkspaceMcpServerForTest seeds one library entry and removes it (plus+// any bindings) afterwards, so these tests can share the fixture workspace.+func createWorkspaceMcpServerForTest(t *testing.T, name, config string) 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)+ var id string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO workspace_mcp_server (workspace_id, name, config)+ VALUES ($1, $2, $3)+ RETURNING id+ `, testWorkspaceID, name, config).Scan(&id); err != nil {+ t.Fatalf("create workspace mcp server: %v", err)}t.Cleanup(func() {- testPool.Exec(context.Background(), `UPDATE workspace SET mcp_config = $1 WHERE id = $2`, previous, testWorkspaceID)+ ctx := context.Background()+ testPool.Exec(ctx, `DELETE FROM agent_mcp_server WHERE server_id = $1`, id)+ testPool.Exec(ctx, `DELETE FROM workspace_mcp_server WHERE id = $1`, id)})+ return id}-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) {+func listWorkspaceMcpServersForTest(t *testing.T, mutate func(*http.Request)) (int, []WorkspaceMcpServerResponse, string) {t.Helper()- req := newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/mcp-config", nil)+ req := newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/mcp-servers", nil)req = withURLParam(req, "id", testWorkspaceID)if mutate != nil {mutate(req)}w := httptest.NewRecorder()- testHandler.GetWorkspaceMcpConfig(w, req)+ testHandler.ListWorkspaceMcpServers(w, req)- var resp WorkspaceMcpConfigResponse+ var resp []WorkspaceMcpServerResponseraw := w.Body.String()if w.Code == http.StatusOK {if err := json.Unmarshal([]byte(raw), &resp); err != nil {@@ -67,17 +55,17 @@ func getWorkspaceMcpConfigForTest(t *testing.T, mutate func(*http.Request)) (intreturn 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) {+// The stored entry is write-only (GH #6062): the read path returns the+// non-secret summary and nothing else, for EVERY role. Asserted on the raw+// body, not the decoded struct, so adding a secret-bearing field later fails+// here.+func TestListWorkspaceMcpServers_NeverEchoesSecrets(t *testing.T) {if testHandler == nil {t.Skip("database not available")}- setWorkspaceMcpConfigForTest(t, workspaceMcpTestDoc)+ createWorkspaceMcpServerForTest(t, "linear", workspaceMcpTestEntry)- code, resp, raw := getWorkspaceMcpConfigForTest(t, nil)+ code, resp, raw := listWorkspaceMcpServersForTest(t, nil)if code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", code, raw)}@@ -89,315 +77,345 @@ func TestGetWorkspaceMcpConfig_NeverEchoesSecrets(t *testing.T) {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)+ var found *WorkspaceMcpServerResponse+ for i := range resp {+ if resp[i].Name == "linear" {+ found = &resp[i]+ }}- if len(resp.Servers) != 0 || resp.ServerCount != 0 {- t.Errorf("expected an empty inventory, got %+v", resp.Servers)+ if found == nil {+ t.Fatalf("expected the server in the library listing, got %+v", resp)}-}--// 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 found.Transport != "http" {+ t.Errorf("transport = %q, want http", found.Transport)}- if len(resp.Servers) != 0 {- t.Errorf("expected an empty inventory for a malformed document, got %+v", resp.Servers)+ // The library listing has no binding, so no toggle state to report.+ if found.Enabled != nil {+ t.Errorf("library listing must not carry an enabled flag, got %v", *found.Enabled)}}-func updateWorkspaceMcpConfigForTest(t *testing.T, body any, mutate func(*http.Request)) (int, WorkspaceMcpConfigResponse, string) {+func createWorkspaceMcpServerViaAPI(t *testing.T, body any, mutate func(*http.Request)) (int, WorkspaceMcpServerResponse, string) {t.Helper()- req := newRequest(http.MethodPut, "/api/workspaces/"+testWorkspaceID+"/mcp-config", body)+ req := newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/mcp-servers", body)req = withURLParam(req, "id", testWorkspaceID)if mutate != nil {mutate(req)}w := httptest.NewRecorder()- testHandler.UpdateWorkspaceMcpConfig(w, req)+ testHandler.CreateWorkspaceMcpServer(w, req)- var resp WorkspaceMcpConfigResponse+ var resp WorkspaceMcpServerResponseraw := w.Body.String()- if w.Code == http.StatusOK {+ if w.Code == http.StatusCreated {if err := json.Unmarshal([]byte(raw), &resp); err != nil {t.Fatalf("decode response: %v", err)}+ t.Cleanup(func() {+ ctx := context.Background()+ testPool.Exec(ctx, `DELETE FROM agent_mcp_server WHERE server_id = $1`, resp.ID)+ testPool.Exec(ctx, `DELETE FROM workspace_mcp_server WHERE id = $1`, resp.ID)+ })}return w.Code, resp, raw}-func TestUpdateWorkspaceMcpConfig_SetAndClear(t *testing.T) {+// The defining property of the redesign: creating a library entry gives it to+// nobody. Adding a server must not touch any agent.+func TestCreateWorkspaceMcpServer_BindsToNoAgent(t *testing.T) {if testHandler == nil {t.Skip("database not available")}- setWorkspaceMcpConfigForTest(t, "")+ agentID := createHandlerTestAgent(t, "ws-mcp-unbound-agent", nil)- code, resp, raw := updateWorkspaceMcpConfigForTest(t, map[string]any{- "mcp_config": json.RawMessage(workspaceMcpTestDoc),+ code, resp, raw := createWorkspaceMcpServerViaAPI(t, map[string]any{+ "name": "linear",+ "config": json.RawMessage(workspaceMcpTestEntry),}, nil)- if code != http.StatusOK {- t.Fatalf("expected 200, got %d: %s", code, raw)+ if code != http.StatusCreated {+ t.Fatalf("expected 201, 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))+ t.Fatalf("create response echoed the entry: %s", raw)}- // 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)+ var bindings int+ if err := testPool.QueryRow(context.Background(),+ `SELECT count(*) FROM agent_mcp_server WHERE server_id = $1`, resp.ID).Scan(&bindings); err != nil {+ t.Fatalf("count bindings: %v", err)+ }+ if bindings != 0 {+ t.Fatalf("creating a library entry bound it to %d agent(s); it must bind to none", bindings)}- if stored := storedWorkspaceMcpConfig(t); stored != "" {- t.Fatalf("expected NULL after clear, got %s", stored)+ // And the agent sees nothing until someone adds it.+ if servers := listAgentMcpServersForTest(t, agentID); len(servers) != 0 {+ t.Fatalf("agent already has %d MCP server(s) without being given any", len(servers))}}-func TestUpdateWorkspaceMcpConfig_RejectsBadShape(t *testing.T) {+func TestCreateWorkspaceMcpServer_RejectsBadInput(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{}}}},- {},+ {"name": "", "config": map[string]any{"url": "https://mcp.example"}},+ {"name": "has space", "config": map[string]any{"url": "https://mcp.example"}},+ {"name": "ok", "config": map[string]any{}},+ {"name": "ok", "config": "not-an-object"},+ {"name": "ok"},} {- code, _, raw := updateWorkspaceMcpConfigForTest(t, body, nil)+ code, _, raw := createWorkspaceMcpServerViaAPI(t, body, nil)if code != http.StatusBadRequest {t.Errorf("body %v: expected 400, got %d: %s", body, code, raw)}}+}++func TestCreateWorkspaceMcpServer_RejectsDuplicateName(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ createWorkspaceMcpServerForTest(t, "linear", workspaceMcpTestEntry)- if stored := storedWorkspaceMcpConfig(t); stored != "" {- t.Fatalf("a rejected write must not touch the stored document, got %s", stored)+ code, _, raw := createWorkspaceMcpServerViaAPI(t, map[string]any{+ "name": "linear",+ "config": map[string]any{"url": "https://other.example"},+ }, nil)+ if code != http.StatusConflict {+ t.Fatalf("expected 409 for a duplicate name, got %d: %s", code, raw)}}-// 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) {+// Curating the library stays a human admin action: a task token running under+// an owner's PAT must not be able to add a shared server.+func TestCreateWorkspaceMcpServer_DeniesAgentActor(t *testing.T) {if testHandler == nil {t.Skip("database not available")}- setWorkspaceMcpConfigForTest(t, "")-- caller := createHandlerTestAgent(t, "ws-mcp-writer", nil)+ caller := createHandlerTestAgent(t, "ws-mcp-lib-writer", nil)taskID := insertHandlerTestTask(t, caller)- asAgent := func(req *http.Request) {++ code, _, raw := createWorkspaceMcpServerViaAPI(t, map[string]any{+ "name": "linear",+ "config": map[string]any{"url": "https://mcp.example"},+ }, 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)+ })+ if code != http.StatusForbidden {+ t.Fatalf("expected 403 for an agent actor, got %d: %s", code, raw)}+}- 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)+// Renaming is safe in this model precisely because bindings key off the id.+func TestUpdateWorkspaceMcpServer_RenameKeepsBindings(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")}+ serverID := createWorkspaceMcpServerForTest(t, "linear", workspaceMcpTestEntry)+ agentID := createHandlerTestAgent(t, "ws-mcp-rename-agent", nil)+ addAgentMcpServerForTest(t, agentID, serverID)- 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)+ req := newRequest(http.MethodPut, "/api/workspaces/"+testWorkspaceID+"/mcp-servers/"+serverID,+ map[string]any{"name": "linear-v2"})+ req = withURLParams(req, "id", testWorkspaceID, "serverId", serverID)+ w := httptest.NewRecorder()+ testHandler.UpdateWorkspaceMcpServer(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}-}-func upsertWorkspaceMcpServerForTest(t *testing.T, name string, entry any, mutate func(*http.Request)) (int, WorkspaceMcpConfigResponse, string) {- t.Helper()+ servers := listAgentMcpServersForTest(t, agentID)+ if len(servers) != 1 || servers[0].Name != "linear-v2" {+ t.Fatalf("binding did not follow the rename: %+v", servers)+ }+}- req := newRequest(http.MethodPut, "/api/workspaces/"+testWorkspaceID+"/mcp-config/servers/"+name, entry)- req = withURLParams(req, "id", testWorkspaceID, "serverName", name)- if mutate != nil {- mutate(req)+// Deleting a library entry has to sweep its bindings: the junction carries no+// foreign key, so an orphan would keep pointing at a server that is gone.+func TestDeleteWorkspaceMcpServer_SweepsBindings(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")}+ serverID := createWorkspaceMcpServerForTest(t, "linear", workspaceMcpTestEntry)+ agentID := createHandlerTestAgent(t, "ws-mcp-delete-agent", nil)+ addAgentMcpServerForTest(t, agentID, serverID)++ req := newRequest(http.MethodDelete, "/api/workspaces/"+testWorkspaceID+"/mcp-servers/"+serverID, nil)+ req = withURLParams(req, "id", testWorkspaceID, "serverId", serverID)w := httptest.NewRecorder()- testHandler.UpsertWorkspaceMcpServer(w, req)+ testHandler.DeleteWorkspaceMcpServer(w, req)+ if w.Code != http.StatusNoContent {+ t.Fatalf("expected 204, got %d: %s", w.Code, w.Body.String())+ }- 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)- }+ var bindings int+ if err := testPool.QueryRow(context.Background(),+ `SELECT count(*) FROM agent_mcp_server WHERE server_id = $1`, serverID).Scan(&bindings); err != nil {+ t.Fatalf("count bindings: %v", err)+ }+ if bindings != 0 {+ t.Fatalf("delete left %d orphaned binding(s)", bindings)}- return w.Code, resp, raw}-func deleteWorkspaceMcpServerForTest(t *testing.T, name string) (int, WorkspaceMcpConfigResponse, string) {+func listAgentMcpServersForTest(t *testing.T, agentID string) []WorkspaceMcpServerResponse {t.Helper()- req := newRequest(http.MethodDelete, "/api/workspaces/"+testWorkspaceID+"/mcp-config/servers/"+name, nil)- req = withURLParams(req, "id", testWorkspaceID, "serverName", name)+ req := newRequest(http.MethodGet, "/api/agents/"+agentID+"/mcp-servers", nil)+ req = withURLParam(req, "id", agentID)w := httptest.NewRecorder()- testHandler.DeleteWorkspaceMcpServer(w, req)+ testHandler.ListAgentMcpServers(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ListAgentMcpServers: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp []WorkspaceMcpServerResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ return resp+}- 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)- }+func addAgentMcpServerForTest(t *testing.T, agentID, serverID string) []WorkspaceMcpServerResponse {+ t.Helper()++ req := newRequest(http.MethodPost, "/api/agents/"+agentID+"/mcp-servers",+ map[string]any{"server_id": serverID})+ req = withURLParam(req, "id", agentID)+ w := httptest.NewRecorder()+ testHandler.AddAgentMcpServer(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("AddAgentMcpServer: expected 200, got %d: %s", w.Code, w.Body.String())}- return w.Code, resp, raw+ var resp []WorkspaceMcpServerResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ return resp}-// 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) {+func TestAgentMcpServerBinding_AddToggleRemove(t *testing.T) {if testHandler == nil {t.Skip("database not available")}- setWorkspaceMcpConfigForTest(t, workspaceMcpTestDoc)+ serverID := createWorkspaceMcpServerForTest(t, "linear", workspaceMcpTestEntry)+ agentID := createHandlerTestAgent(t, "ws-mcp-binding-agent", nil)- 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)+ // Add — the response is the resulting binding list, so the client never+ // has to guess.+ servers := addAgentMcpServerForTest(t, agentID, serverID)+ if len(servers) != 1 || servers[0].ID != serverID {+ t.Fatalf("expected the server to be bound, got %+v", servers)}- if resp.ServerCount != 2 {- t.Fatalf("server_count = %d, want 2 (%+v)", resp.ServerCount, resp.Servers)+ if servers[0].Enabled == nil || !*servers[0].Enabled {+ t.Fatalf("a freshly added server must be enabled, got %+v", servers[0])}- 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])+ // Adding twice is idempotent rather than an error.+ if servers = addAgentMcpServerForTest(t, agentID, serverID); len(servers) != 1 {+ t.Fatalf("re-adding duplicated the binding: %+v", servers)}- // 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))++ // Toggle off — the binding survives so turning it back on is one click.+ req := newRequest(http.MethodPut, "/api/agents/"+agentID+"/mcp-servers/"+serverID+"/enabled",+ map[string]any{"enabled": false})+ req = withURLParams(req, "id", agentID, "serverId", serverID)+ w := httptest.NewRecorder()+ testHandler.SetAgentMcpServerEnabled(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("SetAgentMcpServerEnabled: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ servers = listAgentMcpServersForTest(t, agentID)+ if len(servers) != 1 || servers[0].Enabled == nil || *servers[0].Enabled {+ t.Fatalf("expected the binding to survive as disabled, got %+v", servers)}- // 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)+ // Remove — the library entry itself is untouched.+ req = newRequest(http.MethodDelete, "/api/agents/"+agentID+"/mcp-servers/"+serverID, nil)+ req = withURLParams(req, "id", agentID, "serverId", serverID)+ w = httptest.NewRecorder()+ testHandler.RemoveAgentMcpServer(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("RemoveAgentMcpServer: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if servers = listAgentMcpServersForTest(t, agentID); len(servers) != 0 {+ t.Fatalf("expected no bindings after removal, got %+v", servers)}- if resp.ServerCount != 2 {- t.Fatalf("replace: server_count = %d, want 2", resp.ServerCount)+ var libraryRows int+ if err := testPool.QueryRow(context.Background(),+ `SELECT count(*) FROM workspace_mcp_server WHERE id = $1`, serverID).Scan(&libraryRows); err != nil {+ t.Fatalf("count library rows: %v", err)}- if strings.Contains(storedWorkspaceMcpConfig(t), workspaceMcpTestSecret) {- t.Errorf("replacing an entry must overwrite it, not merge into it: %s", storedWorkspaceMcpConfig(t))+ if libraryRows != 1 {+ t.Fatalf("removing a binding deleted the library entry")}}-func TestUpsertWorkspaceMcpServer_RejectsBadEntry(t *testing.T) {+// A server id from another workspace must not bind across the tenant boundary.+func TestAddAgentMcpServer_RejectsServerFromAnotherWorkspace(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)- }+ ctx := context.Background()+ var otherWorkspaceID, otherServerID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ('Other WS', 'ws-mcp-other', '', 'OTH')+ RETURNING id+ `).Scan(&otherWorkspaceID); err != nil {+ t.Fatalf("create other workspace: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, otherWorkspaceID) })+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace_mcp_server (workspace_id, name, config)+ VALUES ($1, 'foreign', '{"url":"https://foreign.example"}')+ RETURNING id+ `, otherWorkspaceID).Scan(&otherServerID); err != nil {+ t.Fatalf("create foreign server: %v", err)}- if stored := storedWorkspaceMcpConfig(t); stored != "" {- t.Fatalf("a rejected upsert must not write, got %s", stored)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM workspace_mcp_server WHERE id = $1`, otherServerID)+ })++ agentID := createHandlerTestAgent(t, "ws-mcp-tenant-agent", nil)+ req := newRequest(http.MethodPost, "/api/agents/"+agentID+"/mcp-servers",+ map[string]any{"server_id": otherServerID})+ req = withURLParam(req, "id", agentID)+ w := httptest.NewRecorder()+ testHandler.AddAgentMcpServer(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for a server from another workspace, got %d: %s", w.Code, w.Body.String())}}-// 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) {+// The agent's binding list is secret-free too, and an agent actor may not+// change its own assignments.+func TestAgentMcpServerBinding_ResponseIsSecretFreeAndAgentActorsCannotWrite(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)- }+ serverID := createWorkspaceMcpServerForTest(t, "linear", workspaceMcpTestEntry)+ agentID := createHandlerTestAgent(t, "ws-mcp-actor-agent", nil)- 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)+ req := newRequest(http.MethodGet, "/api/agents/"+agentID+"/mcp-servers", nil)+ req = withURLParam(req, "id", agentID)+ w := httptest.NewRecorder()+ testHandler.ListAgentMcpServers(w, req)+ if strings.Contains(w.Body.String(), workspaceMcpTestSecret) {+ t.Fatalf("agent binding list echoed the entry: %s", w.Body.String())+ }++ taskID := insertHandlerTestTask(t, agentID)+ req = newRequest(http.MethodPost, "/api/agents/"+agentID+"/mcp-servers",+ map[string]any{"server_id": serverID})+ req = withURLParam(req, "id", agentID)+ req.Header.Set("X-Actor-Source", "task_token")+ req.Header.Set("X-Agent-ID", agentID)+ req.Header.Set("X-Task-ID", taskID)+ w = httptest.NewRecorder()+ testHandler.AddAgentMcpServer(w, req)+ if w.Code != http.StatusForbidden {+ t.Fatalf("expected 403 for an agent actor, got %d: %s", w.Code, w.Body.String())}}diff --git a/server/internal/handler/workspace_mcp_race_test.go b/server/internal/handler/workspace_mcp_race_test.gonew file mode 100644index 0000000000..f1271e90b8--- /dev/null+++ b/server/internal/handler/workspace_mcp_race_test.go@@ -0,0 +1,221 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"+)++// Neither workspace_mcp_server nor agent_mcp_server carries a foreign key+// (repo rule), so nothing in the database catches a write that lands after the+// row it depends on is gone. These two tests drive the actual races with two+// concurrent transactions rather than asserting the sequential outcome, which+// is what a lock protocol has to be tested against.+//+// They reuse the fence-test helpers from workspace_delete_fence_test.go:+// waitForBlockedWriter proves the second transaction is genuinely parked on a+// lock instead of merely being slow.++// A create arriving mid-teardown must not leave a library row pointing at a+// workspace that no longer exists.+func TestWorkspaceMcpServerCreate_CannotLandAfterWorkspaceTeardownCommits(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var victimID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ('MCP Race WS', 'ws-mcp-race-create', '', 'MRC')+ RETURNING id+ `).Scan(&victimID); err != nil {+ t.Fatalf("create victim workspace: %v", err)+ }+ t.Cleanup(func() {+ bg := context.Background()+ testPool.Exec(bg, `DELETE FROM workspace_mcp_server WHERE workspace_id = $1`, victimID)+ testPool.Exec(bg, `DELETE FROM workspace WHERE id = $1`, victimID)+ })+ if _, err := testPool.Exec(ctx,+ `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`,+ victimID, testUserID); err != nil {+ t.Fatalf("add member: %v", err)+ }++ teardown, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin teardown: %v", err)+ }+ committed := false+ defer func() {+ if !committed {+ _ = teardown.Rollback(ctx)+ }+ }()+ // The order DeleteWorkspace uses: take the row exclusively, then sweep.+ if _, err := teardown.Exec(ctx, `SELECT id FROM workspace WHERE id = $1 FOR UPDATE`, victimID); err != nil {+ t.Fatalf("lock workspace: %v", err)+ }++ var wg sync.WaitGroup+ var writerCode int+ writerPID := make(chan int32, 1)+ wg.Add(1)+ go func() {+ defer wg.Done()+ bg := context.Background()+ conn, err := testPool.Acquire(bg)+ if err != nil {+ close(writerPID)+ return+ }+ defer conn.Release()+ var pid int32+ if err := conn.QueryRow(bg, `SELECT pg_backend_pid()`).Scan(&pid); err != nil {+ close(writerPID)+ return+ }+ writerPID <- pid++ // The handler's own transaction, on this connection, so the race waits+ // on a backend the test can observe.+ h := *testHandler+ h.TxStarter = conn+ h.Queries = testHandler.Queries++ req := newRequest(http.MethodPost, "/api/workspaces/"+victimID+"/mcp-servers", map[string]any{+ "name": "raced",+ "config": map[string]any{"url": "https://mcp.example"},+ })+ req.Header.Set("X-Workspace-ID", victimID)+ req = withURLParam(req, "id", victimID)+ w := httptest.NewRecorder()+ h.CreateWorkspaceMcpServer(w, req)+ writerCode = w.Code+ }()++ pid, ok := <-writerPID+ if !ok {+ wg.Wait()+ t.Fatal("writer could not start")+ }+ waitForBlockedWriter(t, ctx, pid)++ if _, err := teardown.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, victimID); err != nil {+ t.Fatalf("delete workspace: %v", err)+ }+ if err := teardown.Commit(ctx); err != nil {+ t.Fatalf("commit teardown: %v", err)+ }+ committed = true++ wg.Wait()++ if writerCode == http.StatusCreated {+ t.Fatalf("the queued create landed after teardown committed (status %d); the fence did not hold", writerCode)+ }+ var orphans int+ if err := testPool.QueryRow(ctx,+ `SELECT count(*) FROM workspace_mcp_server WHERE workspace_id = $1`, victimID).Scan(&orphans); err != nil {+ t.Fatalf("count orphans: %v", err)+ }+ if orphans != 0 {+ t.Fatalf("teardown left %d MCP server row(s) behind for a deleted workspace", orphans)+ }+}++// An assignment arriving while a library entry is being deleted must not leave+// a binding to a server that no longer exists.+func TestAgentMcpServerAdd_CannotLandAfterServerDeleteCommits(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ serverID := createWorkspaceMcpServerForTest(t, "raced-server", `{"url":"https://mcp.example"}`)+ agentID := createHandlerTestAgent(t, "ws-mcp-race-agent", nil)++ deleter, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin deleter: %v", err)+ }+ committed := false+ defer func() {+ if !committed {+ _ = deleter.Rollback(ctx)+ }+ }()+ // The order DeleteWorkspaceMcpServer uses: take the server row+ // exclusively, then delete and sweep its bindings.+ if _, err := deleter.Exec(ctx,+ `SELECT id FROM workspace_mcp_server WHERE id = $1 FOR UPDATE`, serverID); err != nil {+ t.Fatalf("lock server: %v", err)+ }++ var wg sync.WaitGroup+ var writerCode int+ writerPID := make(chan int32, 1)+ wg.Add(1)+ go func() {+ defer wg.Done()+ bg := context.Background()+ conn, err := testPool.Acquire(bg)+ if err != nil {+ close(writerPID)+ return+ }+ defer conn.Release()+ var pid int32+ if err := conn.QueryRow(bg, `SELECT pg_backend_pid()`).Scan(&pid); err != nil {+ close(writerPID)+ return+ }+ writerPID <- pid++ h := *testHandler+ h.TxStarter = conn+ h.Queries = testHandler.Queries++ req := newRequest(http.MethodPost, "/api/agents/"+agentID+"/mcp-servers",+ map[string]any{"server_id": serverID})+ req = withURLParam(req, "id", agentID)+ w := httptest.NewRecorder()+ h.AddAgentMcpServer(w, req)+ writerCode = w.Code+ }()++ pid, ok := <-writerPID+ if !ok {+ wg.Wait()+ t.Fatal("writer could not start")+ }+ waitForBlockedWriter(t, ctx, pid)++ if _, err := deleter.Exec(ctx, `DELETE FROM agent_mcp_server WHERE server_id = $1`, serverID); err != nil {+ t.Fatalf("sweep bindings: %v", err)+ }+ if _, err := deleter.Exec(ctx, `DELETE FROM workspace_mcp_server WHERE id = $1`, serverID); err != nil {+ t.Fatalf("delete server: %v", err)+ }+ if err := deleter.Commit(ctx); err != nil {+ t.Fatalf("commit delete: %v", err)+ }+ committed = true++ wg.Wait()++ if writerCode == http.StatusOK {+ t.Fatalf("the queued assignment landed after the server was deleted (status %d)", writerCode)+ }+ var orphans int+ if err := testPool.QueryRow(ctx,+ `SELECT count(*) FROM agent_mcp_server WHERE server_id = $1`, serverID).Scan(&orphans); err != nil {+ t.Fatalf("count orphans: %v", err)+ }+ if orphans != 0 {+ t.Fatalf("delete left %d orphaned binding(s)", orphans)+ }+}diff --git a/server/internal/handler/workspace_mcp_test.go b/server/internal/handler/workspace_mcp_test.goindex 69dd733643..569b492e08 100644--- a/server/internal/handler/workspace_mcp_test.go+++ b/server/internal/handler/workspace_mcp_test.go@@ -30,91 +30,94 @@ func serverNames(servers map[string]any) []string {return names}-func TestResolveWorkspaceMcpConfig(t *testing.T) {- const wsDoc = `{"mcpServers":{"shared":{"url":"https://shared.example"},"linear":{"url":"https://ws-linear.example"}}}`+func bindings(pairs ...string) []WorkspaceMcpBinding {+ out := make([]WorkspaceMcpBinding, 0, len(pairs)/2)+ for i := 0; i+1 < len(pairs); i += 2 {+ out = append(out, WorkspaceMcpBinding{Name: pairs[i], Config: json.RawMessage(pairs[i+1])})+ }+ return out+}+func TestResolveAgentMcpConfig(t *testing.T) {tests := []struct {name string- workspace string+ bound []WorkspaceMcpBindingagent stringwantServers map[string]string // server name -> expected urlwantNil 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",+ // The whole point of the binding model: an agent runs with exactly+ // the workspace servers it was given, and nothing else.+ name: "agent with no config of its own runs the servers it was given",+ bound: bindings("shared", `{"url":"https://shared.example"}`),+ agent: "",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"}}}`,+ name: "bound servers union with the agent's own",+ bound: bindings("shared", `{"url":"https://shared.example"}`),+ 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"}}}`,+ name: "the agent's own entry wins on a name collision",+ bound: bindings("linear", `{"url":"https://ws-linear.example"}`),+ 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"}}}`,+ // The legacy entry both shadows the bound one AND survives, folded+ // into the canonical container the daemon actually reads.+ name: "a legacy-container name shadows the bound server and survives",+ bound: bindings("linear", `{"url":"https://ws-linear.example"}`, "shared", `{"url":"https://shared.example"}`),+ 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"}}}`,+ // Nothing bound: an unassigned library entry is invisible here,+ // and the agent keeps exactly what it had.+ name: "no bindings leaves the agent config alone",+ bound: nil,+ 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 bound and nothing configured stays nil",+ bound: nil,+ agent: "",+ wantNil: true,},{- name: "nothing configured anywhere stays nil",- workspace: "",- agent: "",- wantNil: true,+ // A managed-but-empty agent config keeps meaning "no servers of my+ // own"; it is not an opt-out signal any more, because there is+ // nothing to opt out of — bindings are already explicit.+ name: "a managed-but-empty agent config still receives its bindings",+ bound: bindings("shared", `{"url":"https://shared.example"}`),+ agent: `{}`,+ wantServers: map[string]string{+ "shared": "https://shared.example",+ },},}for _, tc := range tests {t.Run(tc.name, func(t *testing.T) {- got, err := ResolveWorkspaceMcpConfig(json.RawMessage(tc.workspace), json.RawMessage(tc.agent))+ got, err := ResolveAgentMcpConfig(tc.bound, json.RawMessage(tc.agent))if err != nil {- t.Fatalf("ResolveWorkspaceMcpConfig: unexpected error: %v", err)+ t.Fatalf("ResolveAgentMcpConfig: unexpected error: %v", err)}if tc.wantNil {if got != nil {@@ -139,45 +142,18 @@ func TestResolveWorkspaceMcpConfig(t *testing.T) {}}-// 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"}}}`+// entries behind in `mcp` while writing bound ones into `mcpServers` made the+// daemon read the bound set and drop the agent's own servers entirely.+func TestResolveAgentMcpConfig_FoldsLegacyContainerIntoCanonical(t *testing.T) {const agentCfg = `{"mcp":{"legacy":{"command":"legacy-server"}},"inputs":[{"id":"token"}]}`- got, err := ResolveWorkspaceMcpConfig(json.RawMessage(wsDoc), json.RawMessage(agentCfg))+ got, err := ResolveAgentMcpConfig(bindings("shared", `{"url":"https://shared.example"}`), json.RawMessage(agentCfg))if err != nil {- t.Fatalf("ResolveWorkspaceMcpConfig: unexpected error: %v", err)+ t.Fatalf("ResolveAgentMcpConfig: unexpected error: %v", err)}var doc map[string]anyif err := json.Unmarshal(got, &doc); err != nil {@@ -197,13 +173,12 @@ func TestResolveWorkspaceMcpConfig_FoldsLegacyContainerIntoCanonical(t *testing.// 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"}}}`+func TestResolveAgentMcpConfig_CanonicalContainerWinsOverLegacy(t *testing.T) {const agentCfg = `{"mcpServers":{"dup":{"url":"https://canonical.example"}},"mcp":{"dup":{"url":"https://legacy.example"}}}`- got, err := ResolveWorkspaceMcpConfig(json.RawMessage(wsDoc), json.RawMessage(agentCfg))+ got, err := ResolveAgentMcpConfig(bindings("shared", `{"url":"https://shared.example"}`), json.RawMessage(agentCfg))if err != nil {- t.Fatalf("ResolveWorkspaceMcpConfig: unexpected error: %v", err)+ t.Fatalf("ResolveAgentMcpConfig: unexpected error: %v", err)}servers := decodeServers(t, got)dup, _ := servers["dup"].(map[string]any)@@ -212,16 +187,14 @@ func TestResolveWorkspaceMcpConfig_CanonicalContainerWinsOverLegacy(t *testing.T}}-// 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))+// Fail-soft: a malformed agent document must never cost the agent its servers.+// It reports the error and returns the agent config untouched.+func TestResolveAgentMcpConfig_MalformedAgentConfigIsReturnedUnchanged(t *testing.T) {+ for _, agentCfg := range []string{`{"mcpServers":[]}`, `not json`, `{"mcpServers":{"broken":"not-an-object"}}`} {+ t.Run(agentCfg, func(t *testing.T) {+ got, err := ResolveAgentMcpConfig(bindings("shared", `{"url":"https://shared.example"}`), json.RawMessage(agentCfg))if err == nil {- t.Fatalf("expected an error for workspace document %s", wsDoc)+ t.Fatalf("expected an error for agent document %s", agentCfg)}if string(got) != agentCfg {t.Fatalf("agent config = %s, want it returned unchanged (%s)", got, agentCfg)@@ -230,16 +203,17 @@ func TestResolveWorkspaceMcpConfig_MalformedWorkspaceKeepsAgentConfig(t *testing}}-// 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"}}}`+// The claim path applies the bindings before the per-task overlay, so the two+// merges have to compose into bound < agent < overlay.+func TestResolveAgentMcpConfig_ComposesWithTaskOverlay(t *testing.T) {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))+ resolved, err := ResolveAgentMcpConfig(+ bindings("shared", `{"url":"https://shared.example"}`, "composio", `{"url":"https://ws-composio.example"}`),+ json.RawMessage(agentCfg))if err != nil {- t.Fatalf("ResolveWorkspaceMcpConfig: unexpected error: %v", err)+ t.Fatalf("ResolveAgentMcpConfig: unexpected error: %v", err)}merged, err := mergeMCPOverlay(resolved, json.RawMessage(overlay))if err != nil {@@ -251,56 +225,67 @@ func TestResolveWorkspaceMcpConfig_ComposesWithTaskOverlay(t *testing.T) {}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"])+ t.Errorf("overlay must win over the bound entry, got %v", composio["url"])}}-func TestValidateWorkspaceMcpConfig(t *testing.T) {+func TestValidateWorkspaceMcpServerEntry(t *testing.T) {tests := []struct {name stringraw stringwantErr bool}{- {name: "servers", raw: `{"mcpServers":{"a":{"url":"https://a.example"}}}`},- {name: "empty object", raw: `{}`},- {name: "empty server map", raw: `{"mcpServers":{}}`},+ {name: "stdio entry", raw: `{"command":"npx","args":["-y","server"]}`},+ {name: "http entry", raw: `{"type":"http","url":"https://mcp.example"}`},+ {name: "empty object", raw: `{}`, wantErr: true},{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: "null", raw: `null`, 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))+ err := validateWorkspaceMcpServerEntry(json.RawMessage(tc.raw))if tc.wantErr && err == nil {- t.Fatalf("validateWorkspaceMcpConfig(%s): expected an error", tc.raw)+ t.Fatalf("validateWorkspaceMcpServerEntry(%s): expected an error", tc.raw)}if !tc.wantErr && err != nil {- t.Fatalf("validateWorkspaceMcpConfig(%s): unexpected error: %v", tc.raw, err)+ t.Fatalf("validateWorkspaceMcpServerEntry(%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+// Validation errors are surfaced to the caller verbatim, and a server entry is+// exactly where a token sits — so the message must never quote input.+func TestValidateWorkspaceMcpServerEntry_ErrorNeverEchoesInput(t *testing.T) {+ secret := `{"headers":{"Authorization":"Bearer sk-live-should-not-leak"` // deliberately truncated- err := validateWorkspaceMcpConfig(json.RawMessage(secret))+ err := validateWorkspaceMcpServerEntry(json.RawMessage(secret))if err == nil {- t.Fatal("expected an error for a truncated document")+ t.Fatal("expected an error for a truncated entry")}if strings.Contains(err.Error(), "sk-live-should-not-leak") {t.Fatalf("validation error leaked input: %q", err.Error())}}+func TestValidateWorkspaceMcpServerName(t *testing.T) {+ for _, name := range []string{"linear", "local-tool", "my_server", "abc123"} {+ if err := validateWorkspaceMcpServerName(name); err != nil {+ t.Errorf("validateWorkspaceMcpServerName(%q): unexpected error: %v", name, err)+ }+ }+ // The name is what a runtime mounts the server under, so keep it to the+ // same character set the agent settings dialog enforces.+ for _, name := range []string{"", "has space", "dot.name", "slash/name", "emoji🎉"} {+ if err := validateWorkspaceMcpServerName(name); err == nil {+ t.Errorf("validateWorkspaceMcpServerName(%q): expected an error", name)+ }+ }+}+func TestParseMcpDocument_NamesSpanBothContainers(t *testing.T) {_, names, err := parseMcpDocument(json.RawMessage(`{"mcpServers":{"a":{}},"mcp":{"b":{}}}`))if err != nil {@@ -311,3 +296,40 @@ func TestParseMcpDocument_NamesSpanBothContainers(t *testing.T) {t.Fatalf("names = %v, want %v", names, want)}}++// mcpTransportOf feeds the client's "can the guided form edit this?" guard, so+// it must never launder an unknown protocol into a known one. Reporting+// {"type":"websocket","url":"wss://…"} as http would let the settings form+// open and rewrite the entry to type:"http" on save — the exact failure the+// front-end guard exists to prevent.+func TestMcpTransportOf(t *testing.T) {+ tests := []struct {+ name string+ entry string+ want string+ }{+ {name: "explicit stdio", entry: `{"type":"stdio","command":"x"}`, want: "stdio"},+ {name: "explicit local", entry: `{"type":"local","command":"x"}`, want: "stdio"},+ {name: "explicit http", entry: `{"type":"http","url":"https://x"}`, want: "http"},+ {name: "explicit streamable-http", entry: `{"type":"streamable-http","url":"https://x"}`, want: "http"},+ {name: "explicit sse", entry: `{"type":"sse","url":"https://x"}`, want: "sse"},+ // The regression: an unknown type with a url must NOT become http.+ {name: "unknown type with url", entry: `{"type":"websocket","url":"wss://x"}`, want: "websocket"},+ {name: "unknown type with command", entry: `{"type":"grpc","command":"x"}`, want: "grpc"},+ {name: "unknown type is normalized to lower case", entry: `{"type":"WebSocket","url":"wss://x"}`, want: "websocket"},+ // Inference only when nothing was declared — that is lossless, because+ // the form writes the same shape back.+ {name: "inferred stdio", entry: `{"command":"x"}`, want: "stdio"},+ {name: "inferred http", entry: `{"url":"https://x"}`, want: "http"},+ {name: "nothing to go on", entry: `{}`, want: "unknown"},+ {name: "malformed", entry: `not json`, want: "unknown"},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if got := mcpTransportOf(json.RawMessage(tc.entry)); got != tc.want {+ t.Fatalf("mcpTransportOf(%s) = %q, want %q", tc.entry, got, tc.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 cb21daa126..40688701f2 100644--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md+++ b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md@@ -242,36 +242,36 @@ 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+#### Workspace 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:+A workspace keeps a LIBRARY of MCP servers (workspace Settings → MCP, or+`multica workspace mcp list|add|update|remove`). Adding one there gives it to+NO agent — same shape as a workspace skill. It reaches an agent only when+someone assigns it:-| Agent `mcp_config` | Effective set |+```bash+multica workspace mcp list --output table # find the server id+multica agent mcp add <agent-id> <server-id> # give it to one agent+multica agent mcp disable <agent-id> <server-id> # stop sending it, keep the assignment+multica agent mcp remove <agent-id> <server-id> # take it away+```++At claim time the effective set is:++| Layer | Reaches the agent when || --- | --- |-| `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.+| runtime-local servers | always (the daemon merges the runtime's own file) |+| workspace servers | assigned to THIS agent and left enabled |+| the agent's own `mcp_config` | always; it WINS on a name collision |++Two consequences worth knowing before writing an agent's config: assigning a+shared server does not require re-listing it in `mcp_config` (they merge), and+`mcp_config` is now only about servers private to that agent — a+managed-but-empty `{}` no longer means anything about the workspace layer,+because nothing is inherited in the first place.++The stored entry is **write-only** — reads return the server's name and+transport, never urls, commands, headers, or env, for any role.## Skill bindingdiff --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 cc3da17344..78a6ad74b4 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,8 +66,8 @@ 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 |+| Assigned workspace MCP servers folded into the agent's | `internal/handler/workspace_mcp.go` `ResolveAgentMcpConfig`; applied in `internal/handler/daemon.go` `buildClaimedTaskResponse` | Only servers bound to this agent AND enabled are folded in; union by name with the agent's own winning; both containers normalized onto `mcpServers`; read on every claim, so an assignment or toggle lands on the agent's next task |+| Workspace MCP library + assignment API | `internal/handler/workspace_mcp_api.go` | `GET /api/workspaces/{id}/mcp-servers` returns name / transport only, never the entry, for any role; `POST`/`PUT`/`DELETE` on the library are owner/admin; `GET`/`POST`/`PUT .../enabled`/`DELETE /api/agents/{id}/mcp-servers` manage one agent's assignments and admit the agent owner or a workspace owner/admin. Every write refuses agent actors. Deleting a library entry sweeps its bindings in the same transaction (no FK) || 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 |diff --git a/server/migrations/315_workspace_mcp_server.down.sql b/server/migrations/315_workspace_mcp_server.down.sqlnew file mode 100644index 0000000000..dbb3194656--- /dev/null+++ b/server/migrations/315_workspace_mcp_server.down.sql@@ -0,0 +1,2 @@+DROP TABLE IF EXISTS agent_mcp_server;+DROP TABLE IF EXISTS workspace_mcp_server;diff --git a/server/migrations/315_workspace_mcp_server.up.sql b/server/migrations/315_workspace_mcp_server.up.sqlnew file mode 100644index 0000000000..90e19c45c8--- /dev/null+++ b/server/migrations/315_workspace_mcp_server.up.sql@@ -0,0 +1,35 @@+-- Workspace MCP servers as an explicit per-agent assignment (GH #6062,+-- MUL-5421), replacing the inherit-by-default document added in 314.+--+-- A workspace-level library of MCP servers plus an explicit per-agent binding,+-- deliberately shaped like `skill` + `agent_skill`: creating a server here+-- gives it to NOBODY. It reaches an agent only when someone adds it to that+-- agent, and the binding carries its own on/off toggle. Nothing about this+-- layer propagates implicitly — that is the whole point of the shape, and the+-- reason 314's model is being replaced rather than extended.+--+-- No foreign keys (repo rule): the application sweeps `agent_mcp_server` when+-- an agent or a server goes away, and both tables on workspace delete.+CREATE TABLE workspace_mcp_server (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ name TEXT NOT NULL,+ -- One MCP server entry: the object that sits under a name in+ -- `mcpServers`. Secret-bearing (urls, headers, env), never returned by the+ -- API — see the write-only contract in workspace_mcp_api.go.+ config JSONB NOT NULL,+ created_by UUID,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE TABLE agent_mcp_server (+ agent_id UUID NOT NULL,+ server_id UUID NOT NULL,+ -- Bound but switched off: the agent keeps the association and the toggle+ -- state, exactly like agent_skill.enabled, so turning it back on does not+ -- mean finding the server again.+ enabled BOOLEAN NOT NULL DEFAULT TRUE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (agent_id, server_id)+);diff --git a/server/migrations/316_workspace_mcp_server_name_unique.down.sql b/server/migrations/316_workspace_mcp_server_name_unique.down.sqlnew file mode 100644index 0000000000..c3219e274a--- /dev/null+++ b/server/migrations/316_workspace_mcp_server_name_unique.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_workspace_mcp_server_workspace_name;diff --git a/server/migrations/316_workspace_mcp_server_name_unique.up.sql b/server/migrations/316_workspace_mcp_server_name_unique.up.sqlnew file mode 100644index 0000000000..77f759ff9a--- /dev/null+++ b/server/migrations/316_workspace_mcp_server_name_unique.up.sql@@ -0,0 +1,6 @@+-- Names identify a server to an agent's runtime, so they must not collide+-- inside a workspace. Concurrent build per the repo migration rule; kept in+-- its own single-statement file because Postgres rejects CONCURRENTLY inside a+-- transaction or a multi-command string.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_workspace_mcp_server_workspace_name+ ON workspace_mcp_server (workspace_id, name);diff --git a/server/migrations/317_agent_mcp_server_server_index.down.sql b/server/migrations/317_agent_mcp_server_server_index.down.sqlnew file mode 100644index 0000000000..8d1936be01--- /dev/null+++ b/server/migrations/317_agent_mcp_server_server_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_mcp_server_server;diff --git a/server/migrations/317_agent_mcp_server_server_index.up.sql b/server/migrations/317_agent_mcp_server_server_index.up.sqlnew file mode 100644index 0000000000..fbfa966ac3--- /dev/null+++ b/server/migrations/317_agent_mcp_server_server_index.up.sql@@ -0,0 +1,5 @@+-- Reverse lookup for the sweep that runs when a workspace server is deleted+-- (and for "which agents use this server" later). The forward direction is+-- already covered by the (agent_id, server_id) primary key.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_mcp_server_server+ ON agent_mcp_server (server_id);diff --git a/server/migrations/318_drop_workspace_mcp_config.down.sql b/server/migrations/318_drop_workspace_mcp_config.down.sqlnew file mode 100644index 0000000000..9687afdcb4--- /dev/null+++ b/server/migrations/318_drop_workspace_mcp_config.down.sql@@ -0,0 +1 @@+ALTER TABLE workspace ADD COLUMN IF NOT EXISTS mcp_config jsonb;diff --git a/server/migrations/318_drop_workspace_mcp_config.up.sql b/server/migrations/318_drop_workspace_mcp_config.up.sqlnew file mode 100644index 0000000000..30f0c2e418--- /dev/null+++ b/server/migrations/318_drop_workspace_mcp_config.up.sql@@ -0,0 +1,18 @@+-- Drops the inherit-by-default column added in 314. Its model — every agent+-- picks the workspace document up automatically — is replaced by the explicit+-- assignment in 315, so leaving the column would keep a second, silently+-- inherited source of MCP servers alive.+--+-- No data migration, and no expand-contract window, by explicit maintainer+-- decision (Bohan, 2026-08-14): 314 shipped and merged in this same cycle and+-- was never deployed, so no environment has a binary that reads this column+-- and no workspace has ever stored a document in it. There is nothing to+-- preserve and no old instance to keep compatible.+--+-- If that ever stops being true — a deploy of 314 happens before this lands —+-- this file must become the CONTRACT half of an expand-contract pair instead:+-- convert each `mcpServers` entry into a `workspace_mcp_server` row with ZERO+-- `agent_mcp_server` bindings (which preserves the entries without giving them+-- to any agent, the behaviour being removed), ship the reading code first, and+-- drop the column only after the old binaries are gone.+ALTER TABLE workspace DROP COLUMN IF EXISTS mcp_config;diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex cc7ef7f33c..4dc8d3f1ec 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -71,6 +71,13 @@ type AgentInvocationTarget struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type AgentMcpServer struct {+ AgentID pgtype.UUID `json:"agent_id"`+ ServerID pgtype.UUID `json:"server_id"`+ Enabled bool `json:"enabled"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type AgentRuntime struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`@@ -1393,8 +1400,7 @@ 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"`- McpConfig []byte `json:"mcp_config"`+ AttributionFailClosed bool `json:"attribution_fail_closed"`}type WorkspaceInvitation struct {@@ -1409,3 +1415,13 @@ type WorkspaceInvitation struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`ExpiresAt pgtype.Timestamptz `json:"expires_at"`}++type WorkspaceMcpServer struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Name string `json:"name"`+ Config []byte `json:"config"`+ CreatedBy pgtype.UUID `json:"created_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.goindex c5e4b650e8..324f50cf47 100644--- a/server/pkg/db/generated/workspace.sql.go+++ b/server/pkg/db/generated/workspace.sql.go@@ -11,40 +11,10 @@ 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, mcp_config+RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed`type CreateWorkspaceParams struct {@@ -78,7 +48,6 @@ func (q *Queries) CreateWorkspace(ctx context.Context, arg CreateWorkspaceParams&i.IssueCounter,&i.AvatarUrl,&i.AttributionFailClosed,- &i.McpConfig,)return i, err}@@ -150,6 +119,20 @@ cleared_issue_properties AS (cleared_quick_actions AS (DELETE FROM quick_action WHERE workspace_id = $1),+ws_mcp_servers AS (+ SELECT id FROM workspace_mcp_server WHERE workspace_id = $1+),+cleared_agent_mcp_bindings AS (+ -- agent_mcp_server carries no FK in either direction, so sweep it from+ -- both sides: the workspace's own servers, and any binding held by an+ -- agent that is about to be removed with the workspace.+ DELETE FROM agent_mcp_server+ WHERE server_id IN (SELECT id FROM ws_mcp_servers)+ OR agent_id IN (SELECT id FROM ws_agents)+),+cleared_workspace_mcp_servers AS (+ DELETE FROM workspace_mcp_server WHERE workspace_id = $1+),deleted_pending_check_suites AS (DELETE FROM github_pending_check_suite WHERE workspace_id = $1),@@ -224,7 +207,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, mcp_config FROM workspace+SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed FROM workspaceWHERE id = $1`@@ -245,7 +228,6 @@ func (q *Queries) GetWorkspace(ctx context.Context, id pgtype.UUID) (Workspace,&i.IssueCounter,&i.AvatarUrl,&i.AttributionFailClosed,- &i.McpConfig,)return i, err}@@ -265,7 +247,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, mcp_config FROM workspace+SELECT id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed FROM workspaceWHERE slug = $1`@@ -286,27 +268,10 @@ 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@@ -367,31 +332,15 @@ WHERE m.user_id = $1ORDER BY w.created_at ASC`-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) {+func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]Workspace, error) {rows, err := q.db.Query(ctx, listWorkspaces, userID)if err != nil {return nil, err}defer rows.Close()- items := []ListWorkspacesRow{}+ items := []Workspace{}for rows.Next() {- var i ListWorkspacesRow+ var i Workspaceif err := rows.Scan(&i.ID,&i.Name,@@ -461,60 +410,6 @@ 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),@@ -526,7 +421,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, mcp_config+RETURNING id, name, slug, description, settings, created_at, updated_at, context, repos, issue_prefix, issue_counter, avatar_url, attribution_fail_closed`type UpdateWorkspaceParams struct {@@ -566,7 +461,6 @@ 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/generated/workspace_mcp.sql.go b/server/pkg/db/generated/workspace_mcp.sql.gonew file mode 100644index 0000000000..4d1383e44d--- /dev/null+++ b/server/pkg/db/generated/workspace_mcp.sql.go@@ -0,0 +1,356 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: workspace_mcp.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const addAgentMcpServer = `-- name: AddAgentMcpServer :exec+INSERT INTO agent_mcp_server (agent_id, server_id)+VALUES ($1, $2)+ON CONFLICT DO NOTHING+`++type AddAgentMcpServerParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ ServerID pgtype.UUID `json:"server_id"`+}++func (q *Queries) AddAgentMcpServer(ctx context.Context, arg AddAgentMcpServerParams) error {+ _, err := q.db.Exec(ctx, addAgentMcpServer, arg.AgentID, arg.ServerID)+ return err+}++const createWorkspaceMcpServer = `-- name: CreateWorkspaceMcpServer :one+INSERT INTO workspace_mcp_server (workspace_id, name, config, created_by)+VALUES ($1, $2, $3, $4)+RETURNING id, workspace_id, name, config, created_by, created_at, updated_at+`++type CreateWorkspaceMcpServerParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Name string `json:"name"`+ Config []byte `json:"config"`+ CreatedBy pgtype.UUID `json:"created_by"`+}++func (q *Queries) CreateWorkspaceMcpServer(ctx context.Context, arg CreateWorkspaceMcpServerParams) (WorkspaceMcpServer, error) {+ row := q.db.QueryRow(ctx, createWorkspaceMcpServer,+ arg.WorkspaceID,+ arg.Name,+ arg.Config,+ arg.CreatedBy,+ )+ var i WorkspaceMcpServer+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.Config,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const deleteAgentMcpServersByServer = `-- name: DeleteAgentMcpServersByServer :exec+DELETE FROM agent_mcp_server WHERE server_id = $1+`++// Bindings carry no FK, so removing a library entry must sweep them explicitly+// in the same transaction as the delete.+func (q *Queries) DeleteAgentMcpServersByServer(ctx context.Context, serverID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteAgentMcpServersByServer, serverID)+ return err+}++const deleteWorkspaceMcpServer = `-- name: DeleteWorkspaceMcpServer :execrows+DELETE FROM workspace_mcp_server+WHERE id = $1 AND workspace_id = $2+`++type DeleteWorkspaceMcpServerParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) DeleteWorkspaceMcpServer(ctx context.Context, arg DeleteWorkspaceMcpServerParams) (int64, error) {+ result, err := q.db.Exec(ctx, deleteWorkspaceMcpServer, arg.ID, arg.WorkspaceID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const getWorkspaceMcpServer = `-- name: GetWorkspaceMcpServer :one+SELECT id, workspace_id, name, config, created_by, created_at, updated_at FROM workspace_mcp_server+WHERE id = $1 AND workspace_id = $2+`++type GetWorkspaceMcpServerParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++func (q *Queries) GetWorkspaceMcpServer(ctx context.Context, arg GetWorkspaceMcpServerParams) (WorkspaceMcpServer, error) {+ row := q.db.QueryRow(ctx, getWorkspaceMcpServer, arg.ID, arg.WorkspaceID)+ var i WorkspaceMcpServer+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.Config,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const listAgentMcpServers = `-- name: ListAgentMcpServers :many+SELECT s.id, s.workspace_id, s.name, s.config, s.created_at, s.updated_at, ams.enabled+FROM workspace_mcp_server s+JOIN agent_mcp_server ams ON ams.server_id = s.id+WHERE ams.agent_id = $1+ORDER BY s.name ASC+`++type ListAgentMcpServersRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Name string `json:"name"`+ Config []byte `json:"config"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+ Enabled bool `json:"enabled"`+}++// Every workspace server bound to this agent, enabled or not, for the agent+// settings list. `enabled` comes from the binding.+func (q *Queries) ListAgentMcpServers(ctx context.Context, agentID pgtype.UUID) ([]ListAgentMcpServersRow, error) {+ rows, err := q.db.Query(ctx, listAgentMcpServers, agentID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListAgentMcpServersRow{}+ for rows.Next() {+ var i ListAgentMcpServersRow+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.Config,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Enabled,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listEnabledAgentMcpServers = `-- name: ListEnabledAgentMcpServers :many+SELECT s.name, s.config+FROM workspace_mcp_server s+JOIN agent_mcp_server ams ON ams.server_id = s.id+WHERE ams.agent_id = $1 AND ams.enabled = TRUE+ORDER BY s.name ASC+`++type ListEnabledAgentMcpServersRow struct {+ Name string `json:"name"`+ Config []byte `json:"config"`+}++// Claim path: only bound AND enabled servers reach the runtime. An unbound+// workspace server is invisible to this agent — creating one gives it to+// nobody until someone adds it here.+func (q *Queries) ListEnabledAgentMcpServers(ctx context.Context, agentID pgtype.UUID) ([]ListEnabledAgentMcpServersRow, error) {+ rows, err := q.db.Query(ctx, listEnabledAgentMcpServers, agentID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListEnabledAgentMcpServersRow{}+ for rows.Next() {+ var i ListEnabledAgentMcpServersRow+ if err := rows.Scan(&i.Name, &i.Config); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listWorkspaceMcpServers = `-- name: ListWorkspaceMcpServers :many+SELECT id, workspace_id, name, config, created_by, created_at, updated_at FROM workspace_mcp_server+WHERE workspace_id = $1+ORDER BY name ASC+`++// The workspace's MCP library. Returns `config` because the callers that need+// it (claim assembly, the write path's read-modify-write) run server-side; the+// HTTP layer projects it down to the non-secret inventory.+func (q *Queries) ListWorkspaceMcpServers(ctx context.Context, workspaceID pgtype.UUID) ([]WorkspaceMcpServer, error) {+ rows, err := q.db.Query(ctx, listWorkspaceMcpServers, workspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []WorkspaceMcpServer{}+ for rows.Next() {+ var i WorkspaceMcpServer+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.Config,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const lockWorkspaceMcpServerForShare = `-- name: LockWorkspaceMcpServerForShare :one+SELECT id FROM workspace_mcp_server+WHERE id = $1 AND workspace_id = $2+FOR SHARE+`++type LockWorkspaceMcpServerForShareParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Taken by the assignment writer before it inserts. A shared row lock+// conflicts with the exclusive lock DeleteWorkspaceMcpServer takes, so an+// assignment can never land in the window between that delete sweeping the+// bindings and committing — the junction has no FK to catch the orphan.+func (q *Queries) LockWorkspaceMcpServerForShare(ctx context.Context, arg LockWorkspaceMcpServerForShareParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, lockWorkspaceMcpServerForShare, arg.ID, arg.WorkspaceID)+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err+}++const lockWorkspaceMcpServerForUpdate = `-- name: LockWorkspaceMcpServerForUpdate :one+SELECT id FROM workspace_mcp_server+WHERE id = $1 AND workspace_id = $2+FOR UPDATE+`++type LockWorkspaceMcpServerForUpdateParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// The delete half of the same protocol: take the row exclusively first, so a+// concurrent assignment either lands before this transaction (and is swept) or+// waits and then finds the server gone.+func (q *Queries) LockWorkspaceMcpServerForUpdate(ctx context.Context, arg LockWorkspaceMcpServerForUpdateParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, lockWorkspaceMcpServerForUpdate, arg.ID, arg.WorkspaceID)+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err+}++const removeAgentMcpServer = `-- name: RemoveAgentMcpServer :execrows+DELETE FROM agent_mcp_server+WHERE agent_id = $1 AND server_id = $2+`++type RemoveAgentMcpServerParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ ServerID pgtype.UUID `json:"server_id"`+}++func (q *Queries) RemoveAgentMcpServer(ctx context.Context, arg RemoveAgentMcpServerParams) (int64, error) {+ result, err := q.db.Exec(ctx, removeAgentMcpServer, arg.AgentID, arg.ServerID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const setAgentMcpServerEnabled = `-- name: SetAgentMcpServerEnabled :execrows+UPDATE agent_mcp_server+SET enabled = $3+WHERE agent_id = $1 AND server_id = $2+`++type SetAgentMcpServerEnabledParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ ServerID pgtype.UUID `json:"server_id"`+ Enabled bool `json:"enabled"`+}++func (q *Queries) SetAgentMcpServerEnabled(ctx context.Context, arg SetAgentMcpServerEnabledParams) (int64, error) {+ result, err := q.db.Exec(ctx, setAgentMcpServerEnabled, arg.AgentID, arg.ServerID, arg.Enabled)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const updateWorkspaceMcpServer = `-- name: UpdateWorkspaceMcpServer :one+UPDATE workspace_mcp_server SET+ name = COALESCE($3, name),+ config = COALESCE($4, config),+ updated_at = now()+WHERE id = $1 AND workspace_id = $2+RETURNING id, workspace_id, name, config, created_by, created_at, updated_at+`++type UpdateWorkspaceMcpServerParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Name pgtype.Text `json:"name"`+ Config []byte `json:"config"`+}++// Full replace of one entry. The name can change here (unlike the previous+// document model) because bindings key off the id, so a rename cannot orphan+// the agents that use it.+func (q *Queries) UpdateWorkspaceMcpServer(ctx context.Context, arg UpdateWorkspaceMcpServerParams) (WorkspaceMcpServer, error) {+ row := q.db.QueryRow(ctx, updateWorkspaceMcpServer,+ arg.ID,+ arg.WorkspaceID,+ arg.Name,+ arg.Config,+ )+ var i WorkspaceMcpServer+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.Config,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sqlindex 87e567b4f9..75b11e0203 100644--- a/server/pkg/db/queries/workspace.sql+++ b/server/pkg/db/queries/workspace.sql@@ -39,39 +39,6 @@ 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)@@ -195,6 +162,20 @@ cleared_issue_properties AS (cleared_quick_actions AS (DELETE FROM quick_action WHERE workspace_id = $1),+ws_mcp_servers AS (+ SELECT id FROM workspace_mcp_server WHERE workspace_id = $1+),+cleared_agent_mcp_bindings AS (+ -- agent_mcp_server carries no FK in either direction, so sweep it from+ -- both sides: the workspace's own servers, and any binding held by an+ -- agent that is about to be removed with the workspace.+ DELETE FROM agent_mcp_server+ WHERE server_id IN (SELECT id FROM ws_mcp_servers)+ OR agent_id IN (SELECT id FROM ws_agents)+),+cleared_workspace_mcp_servers AS (+ DELETE FROM workspace_mcp_server WHERE workspace_id = $1+),deleted_pending_check_suites AS (DELETE FROM github_pending_check_suite WHERE workspace_id = $1),diff --git a/server/pkg/db/queries/workspace_mcp.sql b/server/pkg/db/queries/workspace_mcp.sqlnew file mode 100644index 0000000000..e5d8813efa--- /dev/null+++ b/server/pkg/db/queries/workspace_mcp.sql@@ -0,0 +1,86 @@+-- name: ListWorkspaceMcpServers :many+-- The workspace's MCP library. Returns `config` because the callers that need+-- it (claim assembly, the write path's read-modify-write) run server-side; the+-- HTTP layer projects it down to the non-secret inventory.+SELECT * FROM workspace_mcp_server+WHERE workspace_id = $1+ORDER BY name ASC;++-- name: LockWorkspaceMcpServerForShare :one+-- Taken by the assignment writer before it inserts. A shared row lock+-- conflicts with the exclusive lock DeleteWorkspaceMcpServer takes, so an+-- assignment can never land in the window between that delete sweeping the+-- bindings and committing — the junction has no FK to catch the orphan.+SELECT id FROM workspace_mcp_server+WHERE id = $1 AND workspace_id = $2+FOR SHARE;++-- name: LockWorkspaceMcpServerForUpdate :one+-- The delete half of the same protocol: take the row exclusively first, so a+-- concurrent assignment either lands before this transaction (and is swept) or+-- waits and then finds the server gone.+SELECT id FROM workspace_mcp_server+WHERE id = $1 AND workspace_id = $2+FOR UPDATE;++-- name: GetWorkspaceMcpServer :one+SELECT * FROM workspace_mcp_server+WHERE id = $1 AND workspace_id = $2;++-- name: CreateWorkspaceMcpServer :one+INSERT INTO workspace_mcp_server (workspace_id, name, config, created_by)+VALUES ($1, $2, $3, $4)+RETURNING *;++-- name: UpdateWorkspaceMcpServer :one+-- Full replace of one entry. The name can change here (unlike the previous+-- document model) because bindings key off the id, so a rename cannot orphan+-- the agents that use it.+UPDATE workspace_mcp_server SET+ name = COALESCE(sqlc.narg('name'), name),+ config = COALESCE(sqlc.narg('config'), config),+ updated_at = now()+WHERE id = $1 AND workspace_id = $2+RETURNING *;++-- name: DeleteWorkspaceMcpServer :execrows+DELETE FROM workspace_mcp_server+WHERE id = $1 AND workspace_id = $2;++-- name: DeleteAgentMcpServersByServer :exec+-- Bindings carry no FK, so removing a library entry must sweep them explicitly+-- in the same transaction as the delete.+DELETE FROM agent_mcp_server WHERE server_id = $1;++-- name: ListAgentMcpServers :many+-- Every workspace server bound to this agent, enabled or not, for the agent+-- settings list. `enabled` comes from the binding.+SELECT s.id, s.workspace_id, s.name, s.config, s.created_at, s.updated_at, ams.enabled+FROM workspace_mcp_server s+JOIN agent_mcp_server ams ON ams.server_id = s.id+WHERE ams.agent_id = $1+ORDER BY s.name ASC;++-- name: ListEnabledAgentMcpServers :many+-- Claim path: only bound AND enabled servers reach the runtime. An unbound+-- workspace server is invisible to this agent — creating one gives it to+-- nobody until someone adds it here.+SELECT s.name, s.config+FROM workspace_mcp_server s+JOIN agent_mcp_server ams ON ams.server_id = s.id+WHERE ams.agent_id = $1 AND ams.enabled = TRUE+ORDER BY s.name ASC;++-- name: AddAgentMcpServer :exec+INSERT INTO agent_mcp_server (agent_id, server_id)+VALUES ($1, $2)+ON CONFLICT DO NOTHING;++-- name: SetAgentMcpServerEnabled :execrows+UPDATE agent_mcp_server+SET enabled = $3+WHERE agent_id = $1 AND server_id = $2;++-- name: RemoveAgentMcpServer :execrows+DELETE FROM agent_mcp_server+WHERE agent_id = $1 AND server_id = $2;