π OpenHands: AI-Driven Development
fix: preserve MCP credentials during Canvas mutations (#16144)
Graham Neubigbf2e37dcad66
diff --git a/__tests__/api/mcp-service/mcp-service.api.test.ts b/__tests__/api/mcp-service/mcp-service.api.test.tsindex 421789c96f..3d2f9a3bc9 100644--- a/__tests__/api/mcp-service/mcp-service.api.test.ts+++ b/__tests__/api/mcp-service/mcp-service.api.test.ts@@ -105,7 +105,7 @@ describe("McpService.testServer", () => {it("maps a stdio config to a StdioMCPServerSpec", async () => {mockTestServer.mockResolvedValue({ ok: true, tools: [] });const stdio: MCPServerConfig = {- id: "stdio-1",+ id: "my-server",type: "stdio",name: "my-server",command: "npx",@@ -118,7 +118,7 @@ describe("McpService.testServer", () => {// Exact match also guards that non-catalog servers get no `tool_call`.expect(mockTestServer).toHaveBeenCalledWith({server: {- transport: "stdio",+ type: "stdio",command: "npx",args: ["-y", "@my/mcp-server"],env: { API_KEY: "secret" },@@ -136,7 +136,7 @@ describe("McpService.testServer", () => {// -------------------------------------------------------------------------const SLACK_SERVER: MCPServerConfig = {- id: "stdio-0",+ id: "slack",type: "stdio",name: "slack",command: "npx",diff --git a/__tests__/api/settings-service.test.ts b/__tests__/api/settings-service.test.tsindex eb7211698f..a3c9088774 100644--- a/__tests__/api/settings-service.test.ts+++ b/__tests__/api/settings-service.test.ts@@ -11,6 +11,7 @@ import type { Backend } from "#/api/backend-registry/types";import { server } from "#/mocks/node";import { resetTestHandlersMockSettings } from "#/mocks/settings-handlers";import type { Settings } from "#/types/settings";+import { buildMcpServerPatch } from "#/utils/mcp-config";const mockSaveCloudSettings = vi.fn();const mockFetchCloudSettings = vi.fn();@@ -318,13 +319,7 @@ describe("SettingsService", () => {expect(settings.provider_tokens_set).toEqual({});});- it("pre-clears mcp_config before writing the new value on the local backend", async () => {- // The agent-server PATCH applies agent_settings_diff via deep-merge,- // which cannot remove name-keyed entries from mcp_config.- // saveSettings must compensate by sending a {mcp_config: null} PATCH- // first so the follow-up PATCH effectively replaces the field. Without- // this, deleting a server leaves stale MCP server keys behind and- // shifted indices produce duplicate entries.+ it("sends an mcp_config merge-patch in one request on the local backend", async () => {const patchBodies: Array<Record<string, unknown>> = [];server.use(http.patch("*/api/settings", async ({ request }) => {@@ -344,7 +339,6 @@ describe("SettingsService", () => {});expect(patchBodies).toEqual([- { agent_settings_diff: { mcp_config: null } },{agent_settings_diff: {mcp_config: { only: { url: "https://x.example" } },@@ -353,6 +347,128 @@ describe("SettingsService", () => {]);});+ it("creates, patches, and deletes one named MCP entry with one local request each", async () => {+ const requests: Array<{+ method: string;+ settingsKey: string;+ body?: Record<string, unknown>;+ }> = [];+ const response = {+ agent_settings: {},+ conversation_settings: {},+ llm_api_key_is_set: false,+ };+ server.use(+ http.post(+ "*/api/settings/mcp/:settingsKey",+ async ({ params, request }) => {+ requests.push({+ method: "POST",+ settingsKey: String(params.settingsKey),+ body: (await request.json()) as Record<string, unknown>,+ });+ return HttpResponse.json(response, { status: 201 });+ },+ ),+ http.patch(+ "*/api/settings/mcp/:settingsKey",+ async ({ params, request }) => {+ requests.push({+ method: "PATCH",+ settingsKey: String(params.settingsKey),+ body: (await request.json()) as Record<string, unknown>,+ });+ return HttpResponse.json(response);+ },+ ),+ http.delete("*/api/settings/mcp/:settingsKey", ({ params }) => {+ requests.push({+ method: "DELETE",+ settingsKey: String(params.settingsKey),+ });+ return HttpResponse.json(response);+ }),+ );++ await SettingsService.createMcpServer("docs", {+ transport: "http",+ url: "https://docs.example/mcp",+ });+ await SettingsService.patchMcpServer("github", {+ url: "https://github.example/v2/mcp",+ });+ await SettingsService.deleteMcpServer("old");++ expect(requests).toEqual([+ {+ method: "POST",+ settingsKey: "docs",+ body: {+ transport: "http",+ url: "https://docs.example/mcp",+ },+ },+ {+ method: "PATCH",+ settingsKey: "github",+ body: { url: "https://github.example/v2/mcp" },+ },+ {+ method: "DELETE",+ settingsKey: "old",+ },+ ]);+ });++ it("sends auth replacement tombstones to the named MCP endpoint", async () => {+ const patchBodies: Array<Record<string, unknown>> = [];+ server.use(+ http.patch("*/api/settings/mcp/:settingsKey", async ({ request }) => {+ patchBodies.push((await request.json()) as Record<string, unknown>);+ return HttpResponse.json({+ agent_settings: {},+ conversation_settings: {},+ llm_api_key_is_set: false,+ });+ }),+ );++ await SettingsService.patchMcpServer(+ "mail",+ buildMcpServerPatch(+ {+ transport: "http",+ url: "https://mail.example/mcp",+ auth: {+ strategy: "oauth2",+ authentication: { type: "oauth", scopes: "mail.read" },+ state: { tokens: { access_token: "**********" } },+ },+ },+ {+ id: "mail",+ type: "shttp",+ name: "mail",+ url: "https://mail.example/mcp",+ auth: { strategy: "bearer", value: "replacement-token" },+ },+ ),+ );++ expect(patchBodies).toEqual([+ {+ transport: "http",+ url: "https://mail.example/mcp",+ auth: {+ strategy: "bearer",+ value: "replacement-token",+ authentication: null,+ state: null,+ },+ },+ ]);+ });+it("does not pre-clear when the mcp_config diff is already null on the local backend", async () => {// When the caller is wiping mcp_config entirely (e.g. user removed the// last server), a single PATCH already takes effect because null is@@ -404,7 +520,7 @@ describe("SettingsService", () => {]);});- it("pre-clears mcp_config on the cloud backend before writing the new value", async () => {+ it("sends an mcp_config merge-patch in one request on the cloud backend", async () => {setRegisteredBackends([cloudBackend]);setActiveSelection({ backendId: cloudBackend.id });@@ -414,11 +530,8 @@ describe("SettingsService", () => {},});- expect(mockSaveCloudSettings).toHaveBeenCalledTimes(2);- expect(mockSaveCloudSettings).toHaveBeenNthCalledWith(1, {- agent_settings_diff: { mcp_config: null },- });- expect(mockSaveCloudSettings).toHaveBeenNthCalledWith(2, {+ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({agent_settings_diff: {mcp_config: { only: { url: "https://x.example" } },},@@ -458,10 +571,6 @@ describe("SettingsService", () => {integrations_hub: {url: "https://integrations.staging.all-hands.dev/api/mcp",headers: { Authorization: "Bearer new-key" },- // This is the one write that skips the pre-clear, so it lands as- // an RFC 7386 merge β `enabled` has to be spelled out because a- // merge cannot clear a persisted `enabled: false` by omission.- enabled: true,},},},@@ -484,8 +593,8 @@ describe("SettingsService", () => {},});- expect(mockSaveCloudSettings).toHaveBeenCalledTimes(2);- expect(mockSaveCloudSettings).toHaveBeenNthCalledWith(2, {+ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({agent_settings_diff: {mcp_config: {elevenlabs: {@@ -527,8 +636,8 @@ describe("SettingsService", () => {},});- expect(mockSaveCloudSettings).toHaveBeenCalledTimes(2);- expect(mockSaveCloudSettings).toHaveBeenNthCalledWith(2, {+ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({agent_settings_diff: {mcp_config: {notion: {@@ -543,11 +652,137 @@ describe("SettingsService", () => {});});- it("rolls back to the previous mcp_config when the second cloud PATCH fails", async () => {- // Reviewer-flagged data-loss scenario: the pre-clear succeeds, then- // the write fails (validation error, transient outage, etc.). The- // service must attempt to restore the previous mcp_config so the- // user isn't silently left with an empty MCP setup.+ it("clears cloud MCP credential headers when auth is explicitly cleared", async () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });++ await SettingsService.patchMcpServer("github", { auth: null });++ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({+ agent_settings_diff: {+ mcp_config: {+ github: { headers: null },+ },+ },+ });+ });++ it("tombstones the old credential header when a cloud MCP switches auth strategy", async () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });++ mockFetchCloudSettings.mockResolvedValue({+ mcp_config: {+ github: {+ url: "https://github.example/mcp",+ headers: { "X-API-Key": "stale-custom-header-secret" },+ },+ },+ });++ await SettingsService.patchMcpServer("github", {+ auth: { strategy: "bearer", value: "new-bearer-token" },+ });++ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({+ agent_settings_diff: {+ mcp_config: {+ github: {+ headers: {+ Authorization: "Bearer new-bearer-token",+ "X-API-Key": null,+ },+ },+ },+ },+ });+ });++ it("keeps stored non-credential headers when a cloud MCP switches auth strategy", async () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });++ mockFetchCloudSettings.mockResolvedValue({+ mcp_config: {+ github: {+ url: "https://github.example/mcp",+ headers: {+ "X-API-Key": "stale-custom-header-secret",+ "X-Trace": "on",+ },+ },+ },+ });++ await SettingsService.patchMcpServer("github", {+ auth: { strategy: "bearer", value: "new-bearer-token" },+ headers: { "X-Trace": "on" },+ });++ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({+ agent_settings_diff: {+ mcp_config: {+ github: {+ headers: {+ Authorization: "Bearer new-bearer-token",+ "X-Trace": "on",+ "X-API-Key": null,+ },+ },+ },+ },+ });+ });++ it("does not fetch stored cloud settings for a patch with no auth credential", async () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });++ await SettingsService.patchMcpConfig({+ only: { url: "https://x.example" },+ });++ expect(mockFetchCloudSettings).not.toHaveBeenCalled();+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({+ agent_settings_diff: {+ mcp_config: { only: { url: "https://x.example" } },+ },+ });+ });++ it("tombstones stored credential headers when a cloud MCP auth becomes none", async () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });++ mockFetchCloudSettings.mockResolvedValue({+ mcp_config: {+ github: {+ url: "https://github.example/mcp",+ headers: { Authorization: "Bearer stale-token" },+ },+ },+ });++ await SettingsService.patchMcpServer("github", {+ auth: { strategy: "none" },+ });++ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({+ agent_settings_diff: {+ mcp_config: {+ github: {+ headers: { Authorization: null },+ },+ },+ },+ });+ });++ it("does not mutate the prior cloud catalog before a failed merge-patch", async () => {setRegisteredBackends([cloudBackend]);setActiveSelection({ backendId: cloudBackend.id });@@ -556,16 +791,9 @@ describe("SettingsService", () => {agent_settings: { mcp_config: previousMcpConfig },});- // Pre-clear succeeds, second write fails on all retries, rollback- // succeeds. withRetry runs three attempts by default β return the- // failure deterministically so the rollback path is exercised.mockSaveCloudSettings.mockImplementation((args: { agent_settings_diff?: { mcp_config?: unknown } }) => {const mcp = args?.agent_settings_diff?.mcp_config;- if (mcp === null) return Promise.resolve(undefined); // pre-clear- // The full payload from the user contains the *new* mcp_config.- // Distinguish it from the rollback (which writes the previous- // value) by object identity on the server map.if (mcp &&typeof mcp === "object" &&@@ -573,7 +801,7 @@ describe("SettingsService", () => {) {return Promise.reject(new Error("validation failed"));}- return Promise.resolve(undefined); // rollback succeeds+ return Promise.resolve(undefined);},);@@ -585,21 +813,14 @@ describe("SettingsService", () => {}),).rejects.toThrow("validation failed");- // 3 attempts for the failed write (default withRetry retries) +- // 1 pre-clear + 1 rollback = 5 calls total. Last call MUST be the- // rollback with the previous mcp_config.- const lastCallArgs =- mockSaveCloudSettings.mock.calls[- mockSaveCloudSettings.mock.calls.length - 1- ][0];- expect(lastCallArgs).toEqual({- agent_settings_diff: { mcp_config: previousMcpConfig },- });+ expect(mockFetchCloudSettings).not.toHaveBeenCalled();+ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(3);+ expect(mockSaveCloudSettings.mock.calls).not.toContainEqual([+ { agent_settings_diff: { mcp_config: null } },+ ]);});- it("rolls back to the previous mcp_config when the second local PATCH fails", async () => {- // Same scenario as the cloud test but for the local agent-server- // path. We assert the rollback PATCH is the final request observed.+ it("does not mutate the prior local catalog before a failed merge-patch", async () => {const patchBodies: Array<Record<string, unknown>> = [];const previousMcpConfig = {existing: { url: "https://old.example" },@@ -621,8 +842,6 @@ describe("SettingsService", () => {| { mcp_config?: unknown }| undefined;const mcp = agentDiff?.mcp_config;- // Pre-clear (mcp_config: null) and rollback (mcp_config: previous)- // both succeed; only the "new" write fails.if (mcp &&typeof mcp === "object" &&@@ -649,33 +868,20 @@ describe("SettingsService", () => {}),).rejects.toBeDefined();- // Snapshot fetch must have happened before any destructive PATCH.- expect(getCount).toBeGreaterThanOrEqual(1);-- // Final PATCH is the rollback, restoring the previous mcp_config.- const last = patchBodies[patchBodies.length - 1];- expect(last).toEqual({- agent_settings_diff: { mcp_config: previousMcpConfig },- });- // And we must have done the pre-clear too.- expect(patchBodies[0]).toEqual({+ expect(getCount).toBe(0);+ expect(patchBodies).toHaveLength(3);+ expect(patchBodies).not.toContainEqual({agent_settings_diff: { mcp_config: null },});});- it("does not attempt rollback when the snapshot fetch returned no mcp_config", async () => {- // First-time install: there's nothing to roll back to. The original- // error must still propagate but we must not send a bogus rollback- // PATCH (e.g. `mcp_config: undefined`) that the backend would reject.+ it("does not fetch a snapshot or issue a destructive clear when a cloud patch fails", async () => {setRegisteredBackends([cloudBackend]);setActiveSelection({ backendId: cloudBackend.id });mockFetchCloudSettings.mockResolvedValue({ agent_settings: {} });mockSaveCloudSettings.mockImplementation(- (args: { agent_settings_diff?: { mcp_config?: unknown } }) => {- if (args?.agent_settings_diff?.mcp_config === null) {- return Promise.resolve(undefined);- }+ (_args: { agent_settings_diff?: { mcp_config?: unknown } }) => {return Promise.reject(new Error("validation failed"));},);@@ -688,26 +894,19 @@ describe("SettingsService", () => {}),).rejects.toThrow("validation failed");- // 1 pre-clear + 3 failed write attempts = 4 calls. No rollback- // attempt because the snapshot was empty. Critically, we never- // send `mcp_config: undefined` as a "rollback" since that would- // be backend-rejected or, worse, silently no-op.- expect(mockSaveCloudSettings).toHaveBeenCalledTimes(4);+ expect(mockFetchCloudSettings).not.toHaveBeenCalled();+ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(3);const sentMcpValues = mockSaveCloudSettings.mock.calls.map((call) =>(call[0] as { agent_settings_diff?: { mcp_config?: unknown } })?.agent_settings_diff?.mcp_config,);- // Every call's mcp_config is either the pre-clear null or the- // exact new value the caller asked us to write β no implicit- // rollback target leaked through.for (const mcp of sentMcpValues) {- const isPreClear = mcp === null;const isNewWrite =!!mcp &&typeof mcp === "object" &&!!(mcp as Record<string, unknown>).new;- expect(isPreClear || isNewWrite).toBe(true);+ expect(isNewWrite).toBe(true);}});diff --git a/__tests__/components/automations/recommended-automations.test.tsx b/__tests__/components/automations/recommended-automations.test.tsxindex 31d3334661..1a7c47bfe3 100644--- a/__tests__/components/automations/recommended-automations.test.tsx+++ b/__tests__/components/automations/recommended-automations.test.tsx@@ -522,8 +522,8 @@ describe("recommended automations", () => {});it("launches the recommendation after the missing MCP is installed", async () => {- const saveSpy = vi- .spyOn(SettingsService, "saveSettings")+ const createSpy = vi+ .spyOn(SettingsService, "createMcpServer").mockResolvedValue(true);renderLauncher();@@ -539,7 +539,7 @@ describe("recommended automations", () => {});fireEvent.click(screen.getByTestId("mcp-install-submit"));- await waitFor(() => expect(saveSpy).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(createSpy).toHaveBeenCalledTimes(1));await waitFor(() =>expect(mockNavigate).toHaveBeenCalledWith("/automations/new/github-pr-reviewer",diff --git a/__tests__/components/features/mcp-page/custom-server-editor.test.tsx b/__tests__/components/features/mcp-page/custom-server-editor.test.tsxindex 0e35016171..251ea09c24 100644--- a/__tests__/components/features/mcp-page/custom-server-editor.test.tsx+++ b/__tests__/components/features/mcp-page/custom-server-editor.test.tsx@@ -20,7 +20,7 @@ import type { Settings } from "#/types/settings";import type { MCPServerConfig } from "#/types/mcp-server";const EDIT_STDIO_SERVER: MCPServerConfig = {- id: "stdio-0",+ id: "github",type: "stdio",name: "github",command: "docker",@@ -28,7 +28,7 @@ const EDIT_STDIO_SERVER: MCPServerConfig = {};const EDIT_OAUTH_SERVER: MCPServerConfig = {- id: "shttp-0",+ id: "superhuman_mail",type: "shttp",name: "superhuman_mail",url: "https://mcp.mail.superhuman.com/mcp",@@ -118,6 +118,35 @@ function renderWith(ui: React.ReactNode) {describe("CustomServerEditor", () => {beforeEach(() => {vi.restoreAllMocks();+ vi.spyOn(SettingsService, "createMcpServer").mockImplementation(+ (settingsKey, server) =>+ SettingsService.saveSettings({+ agent_settings_diff: {+ mcp_config: { [settingsKey]: server },+ },+ }),+ );+ vi.spyOn(SettingsService, "patchMcpServer").mockImplementation(+ (settingsKey, patch) =>+ SettingsService.saveSettings({+ agent_settings_diff: {+ mcp_config: { [settingsKey]: patch },+ },+ }),+ );+ vi.spyOn(SettingsService, "deleteMcpServer").mockImplementation(+ (settingsKey) =>+ SettingsService.saveSettings({+ agent_settings_diff: {+ mcp_config: { [settingsKey]: null },+ },+ }),+ );+ vi.spyOn(SettingsService, "patchMcpConfig").mockImplementation((patch) =>+ SettingsService.saveSettings({+ agent_settings_diff: { mcp_config: patch },+ }),+ );vi.spyOn(SettingsService, "getSettings").mockResolvedValue(MOCK_DEFAULT_USER_SETTINGS,);diff --git a/__tests__/components/features/mcp-page/install-server-modal.test.tsx b/__tests__/components/features/mcp-page/install-server-modal.test.tsxindex eba7b806d4..78366f2d4a 100644--- a/__tests__/components/features/mcp-page/install-server-modal.test.tsx+++ b/__tests__/components/features/mcp-page/install-server-modal.test.tsx@@ -35,6 +35,14 @@ function renderWith(ui: React.ReactNode) {describe("InstallServerModal", () => {beforeEach(() => {vi.restoreAllMocks();+ vi.spyOn(SettingsService, "createMcpServer").mockImplementation(+ (settingsKey, server) =>+ SettingsService.saveSettings({+ agent_settings_diff: {+ mcp_config: { [settingsKey]: server },+ },+ }),+ );vi.spyOn(SettingsService, "getSettings").mockResolvedValue(MOCK_DEFAULT_USER_SETTINGS,);diff --git a/__tests__/components/features/mcp-page/mcp-server-health.test.tsx b/__tests__/components/features/mcp-page/mcp-server-health.test.tsxindex 25303df24a..df84ad5840 100644--- a/__tests__/components/features/mcp-page/mcp-server-health.test.tsx+++ b/__tests__/components/features/mcp-page/mcp-server-health.test.tsx@@ -16,7 +16,7 @@ import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";import type { ExtendedMCPTestResponse, MCPServerConfig } from "#/types/mcp-server";const CUSTOM_SERVER: MCPServerConfig = {- id: "shttp-0",+ id: "custom",type: "shttp",name: "custom",url: "https://mcp.example.com/mcp",@@ -24,7 +24,7 @@ const CUSTOM_SERVER: MCPServerConfig = {/** Matches the catalog `github` entry (probe spec + docsUrl). */const GITHUB_SERVER: MCPServerConfig = {- id: "shttp-0",+ id: "github",type: "shttp",name: "github",url: "https://api.githubcopilot.com/mcp/",@@ -32,7 +32,7 @@ const GITHUB_SERVER: MCPServerConfig = {};const OAUTH_SERVER: MCPServerConfig = {- id: "shttp-0",+ id: "my-oauth",type: "shttp",name: "my-oauth",url: "https://mcp.oauth.example/mcp",@@ -171,6 +171,19 @@ describe("InstalledServerCard connection health", () => {});it("re-authorizes a failed OAuth server and persists the refreshed state", async () => {+ vi.mocked(SettingsService.getSettings).mockResolvedValue({+ ...MOCK_DEFAULT_USER_SETTINGS,+ agent_settings: {+ ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,+ mcp_config: {+ "my-oauth": {+ transport: "http",+ url: OAUTH_SERVER.url!,+ auth: { strategy: "oauth2" },+ },+ },+ },+ });vi.spyOn(McpService, "testServer").mockResolvedValue({ok: false,error: "token expired",@@ -181,8 +194,8 @@ describe("InstalledServerCard connection health", () => {tools: [],oauth_state: { tokens: { access_token: "fresh-access-token" } },});- const saveSpy = vi- .spyOn(SettingsService, "saveSettings")+ const patchSpy = vi+ .spyOn(SettingsService, "patchMcpServer").mockResolvedValue(true);renderCard(OAUTH_SERVER);@@ -200,8 +213,12 @@ describe("InstalledServerCard connection health", () => {);expect(McpService.authorizeOAuth).toHaveBeenCalledTimes(1);// The refreshed oauth_state is persisted, not dropped on the floor.- expect(saveSpy).toHaveBeenCalledTimes(1);- expect(JSON.stringify(saveSpy.mock.calls[0][0])).toContain(+ await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(1));+ expect(patchSpy).toHaveBeenCalledWith(+ OAUTH_SERVER.id,+ expect.objectContaining({ auth: expect.any(Object) }),+ );+ expect(JSON.stringify(patchSpy.mock.calls[0][1])).toContain("fresh-access-token",);});diff --git a/__tests__/components/features/settings/mcp-settings/mcp-server-form.validation.test.tsx b/__tests__/components/features/settings/mcp-settings/mcp-server-form.validation.test.tsxindex 6d6530c125..1de7709896 100644--- a/__tests__/components/features/settings/mcp-settings/mcp-server-form.validation.test.tsx+++ b/__tests__/components/features/settings/mcp-settings/mcp-server-form.validation.test.tsx@@ -194,6 +194,32 @@ describe("MCPServerForm validation", () => {});});+ it("keeps raw protocol headers in the pre-save connection-test candidate", () => {+ const onTest = vi.fn();+ render(+ <MCPServerForm+ mode="edit"+ server={{+ id: "docs",+ type: "shttp",+ name: "docs",+ url: "https://docs.example/mcp",+ headers: { "X-Workspace": "canvas" },+ }}+ existingServers={[]}+ onSubmit={noop}+ onCancel={noop}+ onTest={onTest}+ />,+ );++ fireEvent.click(screen.getByTestId("mcp-test-connection"));++ expect(onTest).toHaveBeenCalledWith(+ expect.objectContaining({ headers: { "X-Workspace": "canvas" } }),+ );+ });+it("rejects an sse/shttp server name with unsafe characters", () => {const onSubmit = vi.fn();diff --git a/__tests__/hooks/mutation/use-add-mcp-server.test.ts b/__tests__/hooks/mutation/use-add-mcp-server.test.tsnew file mode 100644index 0000000000..2b81b1e62c--- /dev/null+++ b/__tests__/hooks/mutation/use-add-mcp-server.test.ts@@ -0,0 +1,107 @@+import React from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import SettingsService from "#/api/settings-service/settings-service.api";+import { useAddMcpServer } from "#/hooks/mutation/use-add-mcp-server";++const useSettingsMock = vi.fn();+vi.mock("#/hooks/query/use-settings", () => ({+ useSettings: () => useSettingsMock(),+}));++const createWrapper = () => {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ return function Wrapper({ children }: { children: React.ReactNode }) {+ return React.createElement(QueryClientProvider, { client }, children);+ };+};++describe("useAddMcpServer", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ useSettingsMock.mockReturnValue({+ data: {+ mcp_config: {+ github: {+ transport: "http",+ url: "https://github.example/mcp",+ auth: { strategy: "bearer", value: "**********" },+ },+ },+ },+ });+ });++ it("adds only one named entry and leaves siblings out of the mutation", async () => {+ const createSpy = vi+ .spyOn(SettingsService, "createMcpServer")+ .mockResolvedValue(true);+ const fetchEncryptedSpy = vi.spyOn(SettingsService, "fetchSettingsFromApi");+ const { result } = renderHook(() => useAddMcpServer(), {+ wrapper: createWrapper(),+ });++ await result.current.mutateAsync({+ id: "",+ type: "shttp",+ name: "docs",+ url: "https://docs.example/mcp",+ });++ expect(createSpy).toHaveBeenCalledOnce();+ expect(createSpy).toHaveBeenCalledWith("docs", {+ transport: "http",+ url: "https://docs.example/mcp",+ });+ expect(fetchEncryptedSpy).not.toHaveBeenCalled();+ });++ it("allocates a deterministic suffix without overwriting an existing key", async () => {+ useSettingsMock.mockReturnValue({+ data: {+ mcp_config: {+ slack: { transport: "stdio", command: "npx" },+ },+ },+ });+ const createSpy = vi+ .spyOn(SettingsService, "createMcpServer")+ .mockResolvedValue(true);+ const { result } = renderHook(() => useAddMcpServer(), {+ wrapper: createWrapper(),+ });++ await result.current.mutateAsync({+ id: "",+ type: "stdio",+ name: "slack",+ command: "npx",+ });++ expect(createSpy).toHaveBeenCalledWith("slack_1", {+ transport: "stdio",+ command: "npx",+ });+ });++ it("fails instead of reporting a successful install before settings load", async () => {+ useSettingsMock.mockReturnValue({ data: undefined });+ const createSpy = vi.spyOn(SettingsService, "createMcpServer");+ const { result } = renderHook(() => useAddMcpServer(), {+ wrapper: createWrapper(),+ });++ await expect(+ result.current.mutateAsync({+ id: "",+ type: "stdio",+ name: "filesystem",+ command: "npx",+ }),+ ).rejects.toThrow("MCP settings are still loading");+ expect(createSpy).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/hooks/mutation/use-delete-mcp-server.test.ts b/__tests__/hooks/mutation/use-delete-mcp-server.test.tsindex 6c2ed5477f..83780d9bd2 100644--- a/__tests__/hooks/mutation/use-delete-mcp-server.test.ts+++ b/__tests__/hooks/mutation/use-delete-mcp-server.test.ts@@ -1,23 +1,17 @@-import { renderHook, waitFor } from "@testing-library/react";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { describe, expect, it, vi, beforeEach } from "vitest";import React from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";import SettingsService from "#/api/settings-service/settings-service.api";import {__resetMcpHealthStoreForTests,getMcpHealthSnapshot,setMcpServerHealth,} from "#/api/mcp-health/mcp-health-store";+import { useDeleteMcpServer } from "#/hooks/mutation/use-delete-mcp-server";import type { MCPServerConfig } from "#/types/mcp-server";import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";-const useSettingsMock = vi.fn();-vi.mock("#/hooks/query/use-settings", () => ({- useSettings: () => useSettingsMock(),-}));--import { useDeleteMcpServer } from "#/hooks/mutation/use-delete-mcp-server";-const createWrapper = () => {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },@@ -32,30 +26,42 @@ const createWrapper = () => {return Wrapper;};-describe("useDeleteMcpServer - health reset", () => {+describe("useDeleteMcpServer", () => {beforeEach(() => {- vi.clearAllMocks();+ vi.restoreAllMocks();__resetMcpHealthStoreForTests();- vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);});- it("drops the deleted server's health verdict", async () => {- // A later server can legitimately produce the same health key (e.g. a- // reinstall of the same catalog entry); it must start unchecked instead- // of inheriting the deleted server's verdict.+ it("deletes by stable map key in one request", async () => {+ const deleteSpy = vi+ .spyOn(SettingsService, "deleteMcpServer")+ .mockResolvedValue(true);+ const fetchSpy = vi.spyOn(SettingsService, "fetchSettingsFromApi");const target: MCPServerConfig = {- id: "shttp-0",+ id: "github",type: "shttp",- name: "custom",- url: "https://mcp.example.com/mcp",+ name: "github",+ url: "https://github.example/mcp",};- useSettingsMock.mockReturnValue({- data: {- agent_settings: {- mcp_config: { custom: { url: target.url, transport: "http" } },- },- },+ const { result } = renderHook(() => useDeleteMcpServer(), {+ wrapper: createWrapper(),});++ await result.current.mutateAsync(target);++ expect(deleteSpy).toHaveBeenCalledOnce();+ expect(deleteSpy).toHaveBeenCalledWith("github");+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it("drops the deleted server's health verdict after success", async () => {+ vi.spyOn(SettingsService, "deleteMcpServer").mockResolvedValue(true);+ const target: MCPServerConfig = {+ id: "github",+ type: "shttp",+ name: "github",+ url: "https://github.example/mcp",+ };const key = getMcpServerHealthKey(target);setMcpServerHealth(key, {status: "healthy",@@ -63,10 +69,10 @@ describe("useDeleteMcpServer - health reset", () => {toolCount: 1,checkedAt: 1,});-const { result } = renderHook(() => useDeleteMcpServer(), {wrapper: createWrapper(),});+await result.current.mutateAsync(target);await waitFor(() => expect(getMcpHealthSnapshot()[key]).toBeUndefined());diff --git a/__tests__/hooks/mutation/use-save-settings.test.ts b/__tests__/hooks/mutation/use-save-settings.test.tsindex 988a0d2bb4..06165cb1aa 100644--- a/__tests__/hooks/mutation/use-save-settings.test.ts+++ b/__tests__/hooks/mutation/use-save-settings.test.ts@@ -41,9 +41,9 @@ describe("useSaveSettings - MCP tracking", () => {await result.current.mutateAsync({mcp_config: {- sse_servers: [{ url: "http://sse1" }, { url: "http://sse2" }],- stdio_servers: [{ name: "stdio1", command: "cmd", args: [] }],- shttp_servers: [],+ sse1: { transport: "sse", url: "http://sse1" },+ sse2: { transport: "sse", url: "http://sse2" },+ stdio1: { transport: "stdio", command: "cmd", args: [] },},});@@ -66,11 +66,7 @@ describe("useSaveSettings - MCP tracking", () => {});it("does not call trackMcpConfigUpdated when mcp_config reference is unchanged", async () => {- const sharedConfig = {- sse_servers: [],- stdio_servers: [],- shttp_servers: [],- };+ const sharedConfig = {};useSettingsMock.mockReturnValue({data: { mcp_config: sharedConfig },});@@ -91,7 +87,7 @@ describe("useSaveSettings - MCP tracking", () => {});await result.current.mutateAsync({- mcp_config: { sse_servers: [], stdio_servers: [], shttp_servers: [] },+ mcp_config: {},});await waitFor(() => {diff --git a/__tests__/hooks/mutation/use-update-mcp-server.test.ts b/__tests__/hooks/mutation/use-update-mcp-server.test.tsindex cd6d29a1d1..e86ae1c166 100644--- a/__tests__/hooks/mutation/use-update-mcp-server.test.ts+++ b/__tests__/hooks/mutation/use-update-mcp-server.test.ts@@ -1,26 +1,23 @@-import { renderHook, waitFor } from "@testing-library/react";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { describe, expect, it, vi, beforeEach } from "vitest";import React from "react";-import SettingsService, {- type SettingsApiResponse,-} from "#/api/settings-service/settings-service.api";-import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";--const useSettingsMock = vi.fn();-vi.mock("#/hooks/query/use-settings", () => ({- useSettings: () => useSettingsMock(),-}));--import { useUpdateMcpServer } from "#/hooks/mutation/use-update-mcp-server";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import SettingsService from "#/api/settings-service/settings-service.api";import {__resetMcpHealthStoreForTests,getMcpHealthSnapshot,setMcpServerHealth,} from "#/api/mcp-health/mcp-health-store";+import { useUpdateMcpServer } from "#/hooks/mutation/use-update-mcp-server";import type { MCPServerConfig } from "#/types/mcp-server";+import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";+const useSettingsMock = vi.fn();+vi.mock("#/hooks/query/use-settings", () => ({+ useSettings: () => useSettingsMock(),+}));+const createWrapper = () => {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },@@ -35,97 +32,198 @@ const createWrapper = () => {return Wrapper;};-describe("useUpdateMcpServer - stdio credential preservation", () => {+describe("useUpdateMcpServer", () => {beforeEach(() => {- vi.clearAllMocks();- vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- });-- it("saves the encrypted stdio env, not the redacted placeholder, when a stdio server is renamed", async () => {- // The redacted settings the editor reads from still carry the original name- // ("old_name") and redacted env. The user renames to "new_name" and leaves- // the secret env value as the redaction placeholder.+ vi.restoreAllMocks();+ __resetMcpHealthStoreForTests();useSettingsMock.mockReturnValue({data: {- agent_settings: {- mcp_config: {- old_name: {- command: "npx",- env: { API_KEY: REDACTED_MCP_SECRET_VALUE },+ mcp_config: {+ github: {+ transport: "http",+ url: "https://github.example/mcp",+ auth: {+ strategy: "bearer",+ value: REDACTED_MCP_SECRET_VALUE,},},+ docs: {+ transport: "http",+ url: "https://docs.example/mcp",+ },},},});+ });- vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({- agent_settings: {- mcp_config: {- old_name: {- command: "npx",- env: { API_KEY: "gAAAAA-encrypted-api-key" },- },+ it("patches one server without reading encrypted settings or resending siblings", async () => {+ const patchSpy = vi+ .spyOn(SettingsService, "patchMcpServer")+ .mockResolvedValue(true);+ const fetchEncryptedSpy = vi.spyOn(SettingsService, "fetchSettingsFromApi");+ const { result } = renderHook(() => useUpdateMcpServer(), {+ wrapper: createWrapper(),+ });++ await result.current.mutateAsync({+ serverId: "github",+ server: {+ id: "github",+ type: "shttp",+ name: "github",+ url: "https://github.example/v2/mcp",+ auth: {+ strategy: "bearer",+ value: REDACTED_MCP_SECRET_VALUE,},},- } as unknown as SettingsApiResponse);+ });++ expect(patchSpy).toHaveBeenCalledOnce();+ expect(patchSpy).toHaveBeenCalledWith("github", {+ transport: "http",+ url: "https://github.example/v2/mcp",+ });+ expect(JSON.stringify(patchSpy.mock.calls)).not.toContain(+ REDACTED_MCP_SECRET_VALUE,+ );+ expect(fetchEncryptedSpy).not.toHaveBeenCalled();+ });+ it("sends explicit auth replacement and clearing", async () => {+ const patchSpy = vi+ .spyOn(SettingsService, "patchMcpServer")+ .mockResolvedValue(true);const { result } = renderHook(() => useUpdateMcpServer(), {wrapper: createWrapper(),});await result.current.mutateAsync({- serverId: "stdio-0",+ serverId: "github",server: {- id: "stdio-0",- type: "stdio",- name: "new_name",- command: "npx",- env: { API_KEY: REDACTED_MCP_SECRET_VALUE },+ id: "github",+ type: "shttp",+ name: "github",+ url: "https://github.example/mcp",+ auth: { strategy: "bearer", value: "github_pat_new" },},});+ await result.current.mutateAsync({+ serverId: "github",+ server: {+ id: "github",+ type: "shttp",+ name: "github",+ url: "https://github.example/mcp",+ },+ });++ expect(patchSpy.mock.calls[0]?.[1]).toMatchObject({+ auth: { strategy: "bearer", value: "github_pat_new" },+ });+ expect(patchSpy.mock.calls[1]?.[1]).toMatchObject({ auth: null });+ });- await waitFor(() => expect(result.current.isSuccess).toBe(true));+ it("renames with one atomic map patch", async () => {+ const configSpy = vi+ .spyOn(SettingsService, "patchMcpConfig")+ .mockResolvedValue(true);+ const serverSpy = vi.spyOn(SettingsService, "patchMcpServer");+ const { result } = renderHook(() => useUpdateMcpServer(), {+ wrapper: createWrapper(),+ });- expect(SettingsService.saveSettings).toHaveBeenCalledTimes(1);- const savedDiff = vi.mocked(SettingsService.saveSettings).mock.calls[0][0]- .agent_settings_diff as Record<string, unknown> | undefined;- const savedSdkConfig = savedDiff?.mcp_config;- expect(savedSdkConfig).toMatchObject({- new_name: {- command: "npx",- env: { API_KEY: "gAAAAA-encrypted-api-key" },+ await result.current.mutateAsync({+ serverId: "docs",+ server: {+ id: "docs",+ type: "shttp",+ name: "reference",+ url: "https://docs.example/mcp",},});- // The literal placeholder must never round-trip into the saved config.- expect(JSON.stringify(savedSdkConfig)).not.toContain(- REDACTED_MCP_SECRET_VALUE,- );++ expect(configSpy).toHaveBeenCalledOnce();+ expect(configSpy).toHaveBeenCalledWith({+ docs: null,+ reference: {+ transport: "http",+ url: "https://docs.example/mcp",+ },+ });+ expect(serverSpy).not.toHaveBeenCalled();});-});-describe("useUpdateMcpServer - health reset", () => {- beforeEach(() => {- vi.clearAllMocks();- __resetMcpHealthStoreForTests();- vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);+ it("rejects a rename collision before issuing a request", async () => {+ const configSpy = vi.spyOn(SettingsService, "patchMcpConfig");+ const serverSpy = vi.spyOn(SettingsService, "patchMcpServer");+ const { result } = renderHook(() => useUpdateMcpServer(), {+ wrapper: createWrapper(),+ });++ await expect(+ result.current.mutateAsync({+ serverId: "docs",+ server: {+ id: "docs",+ type: "shttp",+ name: "github",+ url: "https://docs.example/mcp",+ },+ }),+ ).rejects.toThrow(/already exists/i);+ expect(configSpy).not.toHaveBeenCalled();+ expect(serverSpy).not.toHaveBeenCalled();+ });++ // @spec MCP-001 β Sparse mutations preserve sibling servers+ it("allows concurrent sparse updates to different settings keys", async () => {+ const pending = new Map<string, () => void>();+ const patchSpy = vi+ .spyOn(SettingsService, "patchMcpServer")+ .mockImplementation(+ (key) =>+ new Promise<boolean>((resolve) => {+ pending.set(key, () => resolve(true));+ }),+ );+ const { result } = renderHook(() => useUpdateMcpServer(), {+ wrapper: createWrapper(),+ });++ const github = result.current.mutateAsync({+ serverId: "github",+ server: {+ id: "github",+ type: "shttp",+ name: "github",+ url: "https://github.example/v2/mcp",+ },+ });+ const docs = result.current.mutateAsync({+ serverId: "docs",+ server: {+ id: "docs",+ type: "shttp",+ name: "docs",+ url: "https://docs.example/v2/mcp",+ },+ });++ await waitFor(() => expect(patchSpy).toHaveBeenCalledTimes(2));+ pending.get("docs")?.();+ pending.get("github")?.();+ await Promise.all([github, docs]);});- it("clears the server's stored health verdict when its config is saved", async () => {- // A verdict from before the edit describes a different credential/config- // and must not survive the save as a stale (possibly false) healthy.+ it("clears the server's stored health verdict after a successful save", async () => {+ vi.spyOn(SettingsService, "patchMcpServer").mockResolvedValue(true);const server: MCPServerConfig = {- id: "shttp-0",+ id: "docs",type: "shttp",- name: "custom",- url: "https://mcp.example.com/mcp",+ name: "docs",+ url: "https://docs.example/mcp",};- useSettingsMock.mockReturnValue({- data: {- agent_settings: {- mcp_config: { custom: { url: server.url, transport: "http" } },- },- },- });const key = getMcpServerHealthKey(server);setMcpServerHealth(key, {status: "healthy",@@ -133,14 +231,45 @@ describe("useUpdateMcpServer - health reset", () => {toolCount: 1,checkedAt: 1,});-const { result } = renderHook(() => useUpdateMcpServer(), {wrapper: createWrapper(),});+await result.current.mutateAsync({ serverId: server.id, server });- await waitFor(() =>- expect(getMcpHealthSnapshot()[key]).toBeUndefined(),- );+ await waitFor(() => expect(getMcpHealthSnapshot()[key]).toBeUndefined());+ });++ it("clears both old and new health keys after a rename", async () => {+ vi.spyOn(SettingsService, "patchMcpConfig").mockResolvedValue(true);+ const oldServer: MCPServerConfig = {+ id: "docs",+ type: "shttp",+ name: "docs",+ url: "https://docs.example/mcp",+ };+ const newServer: MCPServerConfig = { ...oldServer, name: "reference" };+ const oldKey = getMcpServerHealthKey(oldServer);+ const newKey = getMcpServerHealthKey(newServer);+ setMcpServerHealth(oldKey, {+ status: "healthy",+ verification: "verified",+ toolCount: 1,+ checkedAt: 1,+ });+ setMcpServerHealth(newKey, {+ status: "failed",+ kind: "connection",+ error: "stale",+ checkedAt: 1,+ });+ const { result } = renderHook(() => useUpdateMcpServer(), {+ wrapper: createWrapper(),+ });++ await result.current.mutateAsync({ serverId: "docs", server: newServer });++ expect(getMcpHealthSnapshot()[oldKey]).toBeUndefined();+ expect(getMcpHealthSnapshot()[newKey]).toBeUndefined();});});diff --git a/__tests__/routes/mcp-page.test.tsx b/__tests__/routes/mcp-page.test.tsxindex d3936aa54e..ab4765dc28 100644--- a/__tests__/routes/mcp-page.test.tsx+++ b/__tests__/routes/mcp-page.test.tsx@@ -236,7 +236,7 @@ describe("MCPPage", () => {expect(await screen.findByTestId("mcp-custom-editor")).toBeInTheDocument();});- it("deletes an installed stdio server through the editor", async () => {+ it("deletes an installed stdio server through the confirmation modal", async () => {// Pre-install a Slack stdio server via the SDK-shaped mcp_config// the route reads from agent_settings.mcp_config.const settingsWithSlack = buildSettings({@@ -254,108 +254,20 @@ describe("MCPPage", () => {vi.spyOn(SettingsService, "getSettings").mockResolvedValue(settingsWithSlack,);- const saveSpy = vi- .spyOn(SettingsService, "saveSettings")+ const deleteSpy = vi+ .spyOn(SettingsService, "deleteMcpServer").mockResolvedValue(true);renderPage();- // The card toggle is enable/disable now β removing goes through the- // editor, opened by clicking the card itself.fireEvent.click(await screen.findByTestId("mcp-server-item"));fireEvent.click(await screen.findByTestId("mcp-custom-editor-delete"));const confirmBtn = await screen.findByTestId("confirm-button");fireEvent.click(confirmBtn);- await waitFor(() => expect(saveSpy).toHaveBeenCalledTimes(1));- const sent = (saveSpy.mock.calls[0][0] as Record<string, unknown>)- .agent_settings_diff as { mcp_config: unknown };- // Server gets pulled out of mcp_config entirely (parseMcpConfig- // emits `null` once the last entry is removed).- expect(sent.mcp_config).toBeNull();- });-- it("disables an installed server from its card, keeping its credentials", async () => {- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- mcp_config: {- slack: {- command: "npx",- args: ["-y", "@zencoderai/slack-mcp-server"],- env: { SLACK_BOT_TOKEN: "xoxb-abc" },- },- acme_internal: {- command: "npx",- args: ["-y", "@acme/internal-mcp-server"],- enabled: false,- },- },- },- }),- );- const saveSpy = vi- .spyOn(SettingsService, "saveSettings")- .mockResolvedValue(true);-- renderPage();-- fireEvent.click(await screen.findByTestId("mcp-installed-toggle-stdio-0"));-- await waitFor(() => expect(saveSpy).toHaveBeenCalledTimes(1));- const sent = (saveSpy.mock.calls[0][0] as Record<string, unknown>)- .agent_settings_diff as { mcp_config: unknown };- // Disabling is not deleting: the entry keeps its command and secrets, and- // the already-disabled sibling is not touched on the way through.- expect(sent.mcp_config).toEqual({- slack: {- command: "npx",- args: ["-y", "@zencoderai/slack-mcp-server"],- env: { SLACK_BOT_TOKEN: "xoxb-abc" },- enabled: false,- },- acme_internal: {- command: "npx",- args: ["-y", "@acme/internal-mcp-server"],- enabled: false,- },- });- });-- it("re-enables a disabled server from its card, clearing the stored flag", async () => {- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(- buildSettings({- agent_settings: {- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,- mcp_config: {- acme_internal: {- command: "npx",- args: ["-y", "@acme/internal-mcp-server"],- enabled: false,- },- },- },- }),- );- const saveSpy = vi- .spyOn(SettingsService, "saveSettings")- .mockResolvedValue(true);-- renderPage();-- fireEvent.click(await screen.findByTestId("mcp-installed-toggle-stdio-0"));-- await waitFor(() => expect(saveSpy).toHaveBeenCalledTimes(1));- const sent = (saveSpy.mock.calls[0][0] as Record<string, unknown>)- .agent_settings_diff as { mcp_config: unknown };- expect(sent.mcp_config).toEqual({- acme_internal: {- command: "npx",- args: ["-y", "@acme/internal-mcp-server"],- },- });+ await waitFor(() => expect(deleteSpy).toHaveBeenCalledTimes(1));+ expect(deleteSpy).toHaveBeenCalledWith("slack");});it("shows the catalog description and URL on installed server cards", async () => {@@ -377,12 +289,12 @@ describe("MCPPage", () => {const card = await screen.findByTestId("mcp-server-item");expect(- within(card).getByTestId("mcp-server-description-shttp-0"),+ within(card).getByTestId("mcp-server-description-github"),).toHaveTextContent("Search code, manage issues and pull requests, and inspect repos via the GitHub API.",);expect(- within(card).getByTestId("mcp-server-detail-shttp-0"),+ within(card).getByTestId("mcp-server-detail-github"),).toHaveTextContent("https://api.githubcopilot.com/mcp/");});@@ -436,7 +348,7 @@ describe("MCPPage", () => {}),);const saveSpy = vi- .spyOn(SettingsService, "saveSettings")+ .spyOn(SettingsService, "createMcpServer").mockResolvedValue(true);renderPage();@@ -463,19 +375,11 @@ describe("MCPPage", () => {fireEvent.click(screen.getByTestId("mcp-install-submit"));await waitFor(() => expect(saveSpy).toHaveBeenCalledTimes(1));- const sent = (saveSpy.mock.calls[0][0] as Record<string, unknown>)- .agent_settings_diff as {- mcp_config: Record<string, unknown>;- };- // The original Slack stdio entry is preserved and the new stdio- // install is suffixed rather than overwriting it.- expect(Object.keys(sent.mcp_config).sort()).toEqual([- "slack",- "slack_1",- ]);- expect(sent.mcp_config).toMatchObject({- slack: { env: { SLACK_BOT_TOKEN: "xoxb-old" } },- slack_1: { env: { SLACK_BOT_TOKEN: "xoxb-new", SLACK_TEAM_ID: "T02" } },+ expect(saveSpy).toHaveBeenCalledWith("slack_1", {+ transport: "stdio",+ command: "npx",+ args: ["-y", "@zencoderai/slack-mcp-server"],+ env: { SLACK_BOT_TOKEN: "xoxb-new", SLACK_TEAM_ID: "T02" },});});diff --git a/__tests__/utils/mcp-config.test.ts b/__tests__/utils/mcp-config.test.tsindex cafb71804f..88c1a69199 100644--- a/__tests__/utils/mcp-config.test.ts+++ b/__tests__/utils/mcp-config.test.ts@@ -1,421 +1,463 @@import { describe, expect, it } from "vitest";+import type { MCPConfig } from "@openhands/typescript-client";+import type { MCPServerConfig } from "#/types/mcp-server";+import {+ buildMcpServerPatch,+ buildRenameMcpConfigPatch,+ MCP_HEADER_REMOVAL_ERROR,+ MCP_RENAME_CREDENTIAL_ERROR,+ parseMcpConfig,+ REDACTED_MCP_SECRET_VALUE,+ toCanonicalMcpServer,+} from "#/utils/mcp-config";+import { flattenMcpConfig } from "#/utils/mcp-installed-servers";++describe("canonical MCP configuration", () => {+ // @spec MCP-003 β Settings map keys are stable MCP identities+ it("keeps settings map keys as stable identities across transport grouping", () => {+ const first = parseMcpConfig({+ github: {+ transport: "http",+ url: "https://github.example/mcp",+ },+ filesystem: {+ transport: "stdio",+ command: "npx",+ args: ["-y", "@modelcontextprotocol/server-filesystem"],+ },+ });+ const reordered = parseMcpConfig({+ filesystem: {+ transport: "stdio",+ command: "npx",+ args: ["-y", "@modelcontextprotocol/server-filesystem"],+ },+ github: {+ transport: "http",+ url: "https://github.example/mcp",+ },+ });-import { parseMcpConfig, toSdkMcpConfig } from "#/utils/mcp-config";-import type { MCPConfig } from "#/types/settings";--describe("toSdkMcpConfig", () => {- it("uses bare base names when there are no collisions across server types", () => {- // The bug we're guarding against: a shared monotonic counter would- // emit "sse", "shttp_1", "myname_2" β bumping the stdio suffix every- // time another server type's count changes. With per-base collision- // suffixing, unrelated entries keep their bare names.- const config: MCPConfig = {- sse_servers: [{ url: "https://sse.example" }],- shttp_servers: [{ url: "https://shttp.example" }],- stdio_servers: [{ name: "myname", command: "/bin/run" }],- };-- const out = toSdkMcpConfig(config);-- expect(out).not.toBeNull();- expect(Object.keys(out!)).toEqual(["sse", "shttp", "myname"]);+ expect(+ flattenMcpConfig(first)+ .map(({ id }) => id)+ .sort(),+ ).toEqual(["filesystem", "github"]);+ expect(+ flattenMcpConfig(reordered)+ .map(({ id }) => id)+ .sort(),+ ).toEqual(["filesystem", "github"]);});- it("only suffixes when the same base actually collides", () => {- const config: MCPConfig = {- sse_servers: [- { url: "https://a.example" },- { url: "https://b.example" },- { url: "https://c.example" },- ],- shttp_servers: [- { url: "https://d.example" },- { url: "https://e.example" },- ],- stdio_servers: [],- };+ it("normalizes the cloud wrapper while preserving tagged auth and OAuth state", () => {+ expect(+ parseMcpConfig({+ mcpServers: {+ github: {+ url: "https://github.example/mcp",+ transport: "streamable-http",+ auth: {+ strategy: "oauth2",+ authentication: {+ type: "oauth",+ client_auth_method: "client_secret_post",+ },+ state: {+ tokens: { access_token: REDACTED_MCP_SECRET_VALUE },+ },+ },+ },+ },+ }),+ ).toEqual({+ github: {+ transport: "streamable-http",+ url: "https://github.example/mcp",+ auth: {+ strategy: "oauth2",+ authentication: {+ type: "oauth",+ client_auth_method: "client_secret_post",+ },+ state: {+ tokens: { access_token: REDACTED_MCP_SECRET_VALUE },+ },+ },+ },+ });+ });- const out = toSdkMcpConfig(config);+ it("preserves a disabled server while treating omitted enabled as true", () => {+ const config = parseMcpConfig({+ disabled: { command: "npx", enabled: false },+ enabled: { command: "npx" },+ });- expect(Object.keys(out!)).toEqual([- "sse",- "sse_1",- "sse_2",- "shttp",- "shttp_1",+ expect(flattenMcpConfig(config)).toEqual([+ expect.objectContaining({ id: "disabled", enabled: false }),+ expect.objectContaining({ id: "enabled", enabled: undefined }),]);+ expect(toCanonicalMcpServer({+ id: "disabled",+ type: "stdio",+ command: "npx",+ enabled: false,+ })).toMatchObject({ enabled: false });});+});- it("preserves stdio names verbatim when distinct, even with sse/shttp present", () => {- // Adding sse/shttp servers must not rename existing stdio entries.- // This is the exact scenario the user reported: numbers appearing- // on their stdio MCP server names when they edit unrelated entries.- const config: MCPConfig = {- sse_servers: [{ url: "https://x" }, { url: "https://y" }],- shttp_servers: [{ url: "https://z" }],- stdio_servers: [- { name: "github", command: "/bin/gh" },- { name: "filesystem", command: "/bin/fs" },- ],+describe("MCP sparse patches", () => {+ const storedRemote: MCPConfig["github"] = {+ transport: "http",+ url: "https://github.example/mcp",+ auth: {+ strategy: "bearer",+ value: REDACTED_MCP_SECRET_VALUE,+ },+ };++ // @spec MCP-002 β Secret patches preserve user intent+ it("omits unchanged redacted auth while updating a non-secret field", () => {+ const edited: MCPServerConfig = {+ id: "github",+ type: "shttp",+ name: "github",+ url: "https://github.example/v2/mcp",+ auth: storedRemote.auth ?? undefined,};- const out = toSdkMcpConfig(config);-- expect(out!).toMatchObject({- sse: { url: "https://x" },- sse_1: { url: "https://y" },- shttp: { url: "https://z" },- github: { command: "/bin/gh" },- filesystem: { command: "/bin/fs" },+ expect(buildMcpServerPatch(storedRemote, edited)).toEqual({+ transport: "http",+ url: "https://github.example/v2/mcp",});});- it("suffixes only colliding stdio names", () => {- const config: MCPConfig = {- sse_servers: [],- shttp_servers: [],- stdio_servers: [- { name: "tool", command: "/bin/a" },- { name: "tool", command: "/bin/b" },- { name: "other", command: "/bin/c" },- ],+ it("replaces auth when the user enters a new credential", () => {+ const edited: MCPServerConfig = {+ id: "github",+ type: "shttp",+ name: "github",+ url: storedRemote.url,+ auth: { strategy: "bearer", value: "github_pat_replacement" },};- const out = toSdkMcpConfig(config);-- expect(Object.keys(out!)).toEqual(["tool", "tool_1", "other"]);- });-- it("falls back to a 'stdio' base when a stdio entry has no name", () => {- const config: MCPConfig = {- sse_servers: [],- shttp_servers: [],- stdio_servers: [- { name: "", command: "/bin/a" },- { name: "", command: "/bin/b" },- ],- };-- const out = toSdkMcpConfig(config);-- expect(Object.keys(out!)).toEqual(["stdio", "stdio_1"]);+ expect(buildMcpServerPatch(storedRemote, edited)).toMatchObject({+ auth: { strategy: "bearer", value: "github_pat_replacement" },+ });});- it("uses a user-given name as the sse/shttp dict key", () => {- const config: MCPConfig = {- sse_servers: [{ name: "my_search", url: "https://sse.example" }],- shttp_servers: [{ name: "my_docs", url: "https://shttp.example" }],- stdio_servers: [],+ it("clears auth explicitly when the user selects no authentication", () => {+ const edited: MCPServerConfig = {+ id: "github",+ type: "shttp",+ name: "github",+ url: storedRemote.url,};- const out = toSdkMcpConfig(config);-- expect(Object.keys(out!)).toEqual(["my_search", "my_docs"]);- expect(out!.my_search).toMatchObject({- url: "https://sse.example",- transport: "sse",+ expect(buildMcpServerPatch(storedRemote, edited)).toMatchObject({+ auth: null,});});- it("preserves valid hyphenated MCP server names as SDK keys", () => {- const config: MCPConfig = {- sse_servers: [- { name: "integrations-hub", url: "https://hub.example/mcp" },- ],- shttp_servers: [],- stdio_servers: [{ name: "docs-server", command: "npx" }],+ it("deletes stale auth fields when replacing one strategy with another", () => {+ const storedOAuth = {+ transport: "http" as const,+ url: "https://mail.example/mcp",+ auth: {+ strategy: "oauth2" as const,+ authentication: { type: "oauth" as const, scopes: "mail.read" },+ state: { tokens: { access_token: REDACTED_MCP_SECRET_VALUE } },+ },};-- const out = toSdkMcpConfig(config);-- expect(Object.keys(out!)).toEqual([- "integrations-hub",- "docs-server",- ]);- });-- it("falls back to the base name for unnamed sse/shttp entries", () => {- const config: MCPConfig = {- sse_servers: [{ name: "named", url: "https://a" }, { url: "https://b" }],- shttp_servers: [{ url: "https://c" }],- stdio_servers: [],+ const bearerEdit: MCPServerConfig = {+ id: "mail",+ type: "shttp",+ name: "mail",+ url: storedOAuth.url,+ auth: { strategy: "bearer", value: "replacement-token" },};- const out = toSdkMcpConfig(config);-- expect(Object.keys(out!)).toEqual(["named", "sse", "shttp"]);- });+ expect(buildMcpServerPatch(storedOAuth, bearerEdit).auth).toEqual({+ strategy: "bearer",+ value: "replacement-token",+ authentication: null,+ state: null,+ });- it("de-dups colliding user-given sse/shttp names with a suffix", () => {- const config: MCPConfig = {- sse_servers: [- { name: "search", url: "https://a" },- { name: "search", url: "https://b" },- ],- shttp_servers: [],- stdio_servers: [],+ const storedHeader = {+ transport: "http" as const,+ url: "https://mail.example/mcp",+ auth: {+ strategy: "header" as const,+ headers: { "X-API-Key": REDACTED_MCP_SECRET_VALUE },+ },};-- const out = toSdkMcpConfig(config);-- expect(Object.keys(out!)).toEqual(["search", "search_1"]);- });-- it("round-trips a user-given sse/shttp name through parse β write", () => {- const persisted = {- my_search: { url: "https://x", transport: "sse" },- my_docs: { url: "https://y" },+ const oauthEdit: MCPServerConfig = {+ id: "mail",+ type: "shttp",+ name: "mail",+ url: storedHeader.url,+ auth: {+ strategy: "oauth2",+ authentication: { type: "oauth", scopes: "mail.read" },+ },};- const parsed = parseMcpConfig(persisted);-- expect(parsed.sse_servers).toEqual([- { name: "my_search", url: "https://x" },- ]);- expect(parsed.shttp_servers).toEqual([- { name: "my_docs", url: "https://y" },- ]);-- const written = toSdkMcpConfig(parsed);- expect(Object.keys(written!).sort()).toEqual(["my_docs", "my_search"]);+ expect(buildMcpServerPatch(storedHeader, oauthEdit).auth).toEqual({+ strategy: "oauth2",+ authentication: { type: "oauth", scopes: "mail.read" },+ headers: null,+ });});- it("parses cloud SDK MCPConfig wrapper shape", () => {- const persisted = {- mcpServers: {- "cloud-weather": {- url: "https://weather.example/mcp",- transport: "http",- },- "cloud-files": {- command: "uvx",- args: ["mcp-server-files"],+ // @spec MCP-002 β Secret patches preserve user intent+ it("applies added and changed header-auth headers while preserving redacted leaves", () => {+ const stored = {+ transport: "http" as const,+ url: "https://mail.example/mcp",+ auth: {+ strategy: "header" as const,+ headers: {+ "X-API-Key": REDACTED_MCP_SECRET_VALUE,+ "X-Region": "us-east-1",},},};-- const parsed = parseMcpConfig(persisted);-- expect(parsed.shttp_servers).toEqual([- { name: "cloud-weather", url: "https://weather.example/mcp" },- ]);- expect(parsed.stdio_servers).toEqual([- {- name: "cloud-files",- command: "uvx",- args: ["mcp-server-files"],+ const edited: MCPServerConfig = {+ id: "mail",+ type: "shttp",+ name: "mail",+ url: stored.url,+ auth: {+ strategy: "header",+ headers: {+ "X-API-Key": REDACTED_MCP_SECRET_VALUE,+ "X-Region": "eu-west-1",+ "X-Trace": "on",+ },},- ]);- });+ };- it("does not unwrap a valid server named mcpServers", () => {- const parsed = parseMcpConfig({- mcpServers: {- url: "https://meta.example/mcp",- },+ expect(buildMcpServerPatch(stored, edited).auth).toEqual({+ strategy: "header",+ headers: { "X-Region": "eu-west-1", "X-Trace": "on" },});-- expect(parsed.shttp_servers).toEqual([- { name: "mcpServers", url: "https://meta.example/mcp" },- ]);});- it("does not surface auto-generated sse/shttp keys as user names", () => {- // Keys matching the fallback pattern carry no user intent, so parsing- // must leave `name` unset β otherwise the auto key would become a- // sticky, user-facing name on the next edit.- const persisted = {- sse: { url: "https://a", transport: "sse" },- sse_1: { url: "https://b", transport: "sse" },- shttp: { url: "https://c" },- shttp_2: { url: "https://d" },+ // @spec MCP-002 β Secret patches preserve user intent+ it("rejects removing an individual header from header auth", () => {+ const stored = {+ transport: "http" as const,+ url: "https://mail.example/mcp",+ auth: {+ strategy: "header" as const,+ headers: {+ "X-API-Key": REDACTED_MCP_SECRET_VALUE,+ "X-Region": "us-east-1",+ },+ },+ };+ const edited: MCPServerConfig = {+ id: "mail",+ type: "shttp",+ name: "mail",+ url: stored.url,+ auth: {+ strategy: "header",+ headers: { "X-Region": "eu-west-1" },+ },};- const parsed = parseMcpConfig(persisted);-- expect(parsed.sse_servers).toEqual([- { url: "https://a" },- { url: "https://b" },- ]);- expect(parsed.shttp_servers).toEqual([- { url: "https://c" },- { url: "https://d" },- ]);- });-- it("returns null when there are no servers", () => {- expect(- toSdkMcpConfig({ sse_servers: [], shttp_servers: [], stdio_servers: [] }),- ).toBeNull();+ expect(() => buildMcpServerPatch(stored, edited)).toThrow(+ MCP_HEADER_REMOVAL_ERROR,+ );});- it("serializes remote API keys through the FastMCP auth field", () => {- const config: MCPConfig = {- sse_servers: [- {- url: "https://sse.example",- auth: { strategy: "bearer", value: "sse-secret" },+ it("patches OAuth metadata and a replacement secret without sending redacted state", () => {+ const stored = {+ transport: "http" as const,+ url: "https://mail.example/mcp",+ auth: {+ strategy: "oauth2" as const,+ authentication: {+ type: "oauth" as const,+ client_auth_method: "client_secret_post" as const,+ scopes: "mail.read",+ client_name: "OpenHands Canvas",+ client_metadata_url: "https://mail.example/oauth/client.json",+ client_id: "old-client",+ client_secret: REDACTED_MCP_SECRET_VALUE,},- ],- shttp_servers: [- {- url: "https://shttp.example",- auth: { strategy: "bearer", value: "shttp-secret" },+ state: {+ tokens: {+ access_token: REDACTED_MCP_SECRET_VALUE,+ refresh_token: REDACTED_MCP_SECRET_VALUE,+ },+ token_expires_at: 123,},- ],- stdio_servers: [],- };-- const out = toSdkMcpConfig(config);-- expect(out).toEqual({- sse: {- url: "https://sse.example",- transport: "sse",- auth: { strategy: "bearer", value: "sse-secret" },},- shttp: {- url: "https://shttp.example",- transport: "http",- auth: { strategy: "bearer", value: "shttp-secret" },+ };+ const edited: MCPServerConfig = {+ id: "mail",+ type: "shttp",+ name: "mail",+ url: stored.url,+ auth: {+ strategy: "oauth2",+ authentication: {+ type: "oauth",+ client_auth_method: "client_secret_basic",+ scopes: "mail.read mail.send",+ client_id: "new-client",+ client_secret: "replacement-secret",+ },+ state: stored.auth.state,},- });- });-- it("keeps names stable across a parse β write round trip", () => {- // Simulates loading the user's persisted settings, parsing them,- // and re-serializing on save (which is what happens on every edit).- // The keys must not drift between trips.- const persisted = {- sse: { url: "https://x", transport: "sse" },- sse_1: { url: "https://y", transport: "sse" },- shttp: { url: "https://z" },- github: { command: "/bin/gh" },};- const parsed = parseMcpConfig(persisted);- const written = toSdkMcpConfig(parsed);+ const patch = buildMcpServerPatch(stored, edited);- expect(written).not.toBeNull();- expect(Object.keys(written!).sort()).toEqual(Object.keys(persisted).sort());+ expect(patch.auth).toEqual({+ strategy: "oauth2",+ authentication: {+ type: "oauth",+ client_auth_method: "client_secret_basic",+ scopes: "mail.read mail.send",+ client_id: "new-client",+ client_secret: "replacement-secret",+ },+ });+ expect(JSON.stringify(patch)).not.toContain(REDACTED_MCP_SECRET_VALUE);});- it("does not bump the suffix on a stdio name when an sse server is added", () => {- // Concretely demonstrates the user's report: editing/adding an sse- // server must leave the stdio name untouched. The previous shared- // counter implementation would rename "myname" β "myname_2" here.- const before: MCPConfig = {- sse_servers: [{ url: "https://a" }],- shttp_servers: [],- stdio_servers: [{ name: "myname", command: "/bin/run" }],+ it("sends nested nulls for explicitly cleared OAuth authentication fields", () => {+ const stored = {+ transport: "http" as const,+ url: "https://mail.example/mcp",+ auth: {+ strategy: "oauth2" as const,+ authentication: {+ type: "oauth" as const,+ client_auth_method: "client_secret_post" as const,+ scopes: "mail.read",+ client_id: "old-client",+ client_secret: REDACTED_MCP_SECRET_VALUE,+ },+ state: {+ tokens: { access_token: REDACTED_MCP_SECRET_VALUE },+ },+ },};- const after: MCPConfig = {- sse_servers: [{ url: "https://a" }, { url: "https://b" }],- shttp_servers: [],- stdio_servers: [{ name: "myname", command: "/bin/run" }],+ const edited: MCPServerConfig = {+ id: "mail",+ type: "shttp",+ name: "mail",+ url: stored.url,+ auth: {+ strategy: "oauth2",+ authentication: { type: "oauth" },+ state: stored.auth.state,+ },};- const out1 = toSdkMcpConfig(before)!;- const out2 = toSdkMcpConfig(after)!;-- expect("myname" in out1).toBe(true);- expect("myname" in out2).toBe(true);+ expect(buildMcpServerPatch(stored, edited).auth).toEqual({+ strategy: "oauth2",+ authentication: {+ type: "oauth",+ client_auth_method: null,+ scopes: null,+ client_id: null,+ client_secret: null,+ },+ });});-});-describe("parseMcpConfig / toSdkMcpConfig β enabled flag", () => {- it("round-trips a disabled server without flagging its enabled siblings", () => {- // Every mutation re-serializes the whole map, so a disabled server has to- // survive edits made to unrelated entries. An *enabled* server must come- // back out with no flag at all β the SDK defaults `enabled` to true, and- // omitting it is what clears a previously persisted `enabled: false`.- const persisted = {- off_remote: { url: "https://off.example/mcp", enabled: false },- on_remote: { url: "https://on.example/mcp" },- off_stdio: { command: "/bin/off", enabled: false },+ it("omits unchanged redacted env leaves and deletes removed env entries", () => {+ const stored = {+ transport: "stdio" as const,+ command: "npx",+ env: {+ API_KEY: REDACTED_MCP_SECRET_VALUE,+ REGION: "us-east-1",+ },+ };+ const edited: MCPServerConfig = {+ id: "worker",+ type: "stdio",+ name: "worker",+ command: "npx",+ env: {+ API_KEY: REDACTED_MCP_SECRET_VALUE,+ REGION: "eu-west-1",+ },};- const roundTripped = toSdkMcpConfig(parseMcpConfig(persisted));+ expect(buildMcpServerPatch(stored, edited)).toMatchObject({+ env: { REGION: "eu-west-1" },+ });- expect(roundTripped).toEqual({- off_remote: {- url: "https://off.example/mcp",- transport: "http",- enabled: false,- },- on_remote: { url: "https://on.example/mcp", transport: "http" },- off_stdio: { command: "/bin/off", enabled: false },+ delete edited.env!.REGION;+ expect(buildMcpServerPatch(stored, edited)).toMatchObject({+ env: { REGION: null },});});-});-describe("parseMcpConfig / toSdkMcpConfig β auth: oauth round-trip", () => {- it("round-trips auth metadata and state for remote OAuth servers", () => {- const persisted = {- superhuman_mail: {- url: "https://mcp.mail.superhuman.com/mcp",- transport: "http",- auth: {- strategy: "oauth2",- authentication: {- type: "oauth",- client_auth_method: "none",- },- state: {- tokens: { access_token: "gAAAAencrypted-access-token" },- token_expires_at: 12345,- },- },- },+ // @spec MCP-003 β Settings map keys are stable MCP identities+ it("builds a rename as one map patch and rejects hidden secrets", () => {+ const uncredentialed = {+ transport: "http" as const,+ url: "https://docs.example/mcp",+ };+ const renamed: MCPServerConfig = {+ id: "docs",+ type: "shttp",+ name: "reference",+ url: uncredentialed.url,};- const roundTripped = toSdkMcpConfig(parseMcpConfig(persisted));-- expect(roundTripped).toEqual({- superhuman_mail: {- url: "https://mcp.mail.superhuman.com/mcp",- transport: "http",- auth: {- strategy: "oauth2",- authentication: {- type: "oauth",- client_auth_method: "none",- },- state: {- tokens: { access_token: "gAAAAencrypted-access-token" },- token_expires_at: 12345,- },- },- },+ expect(+ buildRenameMcpConfigPatch("docs", "reference", uncredentialed, renamed),+ ).toEqual({+ docs: null,+ reference: toCanonicalMcpServer(renamed),});+ expect(() =>+ buildRenameMcpConfigPatch("github", "github-renamed", storedRemote, {+ id: "github",+ type: "shttp",+ name: "github-renamed",+ url: storedRemote.url,+ auth: storedRemote.auth ?? undefined,+ }),+ ).toThrow(MCP_RENAME_CREDENTIAL_ERROR);});- it("keeps private_key_jwt OAuth client authentication metadata", () => {- const persisted = {- oauth: {- url: "https://mcp.example.com/mcp",- transport: "http",- auth: {- strategy: "oauth2",- authentication: {- type: "oauth",- client_auth_method: "private_key_jwt",- },- },- },+ // @spec MCP-003 β Settings map keys are stable MCP identities+ it("preserves stored remote metadata when renaming a server", () => {+ const stored = {+ transport: "http" as const,+ url: "https://catalog.example/mcp",+ description: "Catalog-managed server",+ icon: "catalog-icon",+ headers: { "X-Catalog-Mode": "managed" },+ sse_read_timeout: 5_000,+ keep_alive: true,+ };+ const renamed: MCPServerConfig = {+ id: "catalog",+ type: "shttp",+ name: "renamed-catalog",+ url: "https://catalog.example/v2/mcp",};- expect(toSdkMcpConfig(parseMcpConfig(persisted))).toEqual({- oauth: {- url: "https://mcp.example.com/mcp",- transport: "http",- auth: {- strategy: "oauth2",- authentication: {- type: "oauth",- client_auth_method: "private_key_jwt",- },- },+ expect(+ buildRenameMcpConfigPatch("catalog", "renamed-catalog", stored, renamed),+ ).toEqual({+ catalog: null,+ "renamed-catalog": {+ ...stored,+ url: renamed.url,},});});diff --git a/__tests__/utils/mcp-installed-servers.test.ts b/__tests__/utils/mcp-installed-servers.test.tsindex 12abe4f0bc..50199ee7a6 100644--- a/__tests__/utils/mcp-installed-servers.test.ts+++ b/__tests__/utils/mcp-installed-servers.test.ts@@ -6,31 +6,27 @@ import type { MCPConfig } from "#/types/settings";describe("flattenMcpConfig", () => {it("preserves OAuth metadata and state for installed remote servers", () => {const config: MCPConfig = {- sse_servers: [],- stdio_servers: [],- shttp_servers: [- {- name: "superhuman-mail",- url: "https://mcp.mail.superhuman.com/mcp",- auth: {- strategy: "oauth2",- authentication: {- type: "oauth",- client_auth_method: "none",- },- state: {- tokens: {- access_token: "gAAAAencrypted-access-token",- },+ "superhuman-mail": {+ transport: "http",+ url: "https://mcp.mail.superhuman.com/mcp",+ auth: {+ strategy: "oauth2",+ authentication: {+ type: "oauth",+ client_auth_method: "none",+ },+ state: {+ tokens: {+ access_token: "gAAAAencrypted-access-token",},},},- ],+ },};expect(flattenMcpConfig(config)).toEqual([{- id: "shttp-0",+ id: "superhuman-mail",type: "shttp",name: "superhuman-mail",url: "https://mcp.mail.superhuman.com/mcp",diff --git a/specs/mcp-settings.md b/specs/mcp-settings.mdnew file mode 100644index 0000000000..93eb84909e--- /dev/null+++ b/specs/mcp-settings.md@@ -0,0 +1,28 @@+# MCP Settings Specs++---++### MCP-001: Sparse mutations preserve sibling servers++- [x] Adding, updating, or deleting an MCP server shall issue exactly one+ dedicated MCP settings request containing only the affected server.+- [x] An MCP mutation shall never use redacted or encrypted settings snapshots+ as its mutation base.+- [x] Untouched sibling servers and credentials shall survive add, update,+ delete, concurrent different-key updates, and failed mutations.++### MCP-002: Secret patches preserve user intent++- [x] Omitting an unchanged secret shall preserve its stored value.+- [x] Supplying a secret shall replace its stored value.+- [x] Explicitly clearing a supported secret field shall send `null`.+- [x] The display-only redaction sentinel shall never be sent as mutation data.++### MCP-003: Settings map keys are stable MCP identities++- [x] Rendering order and transport grouping shall not change persistence+ identity.+- [x] Deletion shall address the settings map key without matching URL, command,+ or arguments.+- [x] Rename shall use one atomic map patch, reject collisions, and reject+ hidden-secret renames that could lose credentials.diff --git a/src/api/mcp-service/mcp-redacted-credentials.test.ts b/src/api/mcp-service/mcp-redacted-credentials.test.tsindex 852e483714..1ad5538d5a 100644--- a/src/api/mcp-service/mcp-redacted-credentials.test.ts+++ b/src/api/mcp-service/mcp-redacted-credentials.test.ts@@ -26,7 +26,7 @@ describe("substituteRedactedMcpCredentials", () => {} as unknown as SettingsApiResponse);const result = await substituteRedactedMcpCredentials({- id: "stdio-0",+ id: "old-name",type: "stdio",name: "new-name",command: "npx",@@ -39,7 +39,7 @@ describe("substituteRedactedMcpCredentials", () => {it("does not restore another server's secret when renamed onto an existing name", async () => {// Renaming "alpha" onto "beta"'s name must still resolve alpha's stored- // entry by position, not beta's entry (which the name match would return).+ // entry by stable key, not beta's entry.vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({agent_settings: {mcp_config: {@@ -50,7 +50,7 @@ describe("substituteRedactedMcpCredentials", () => {} as unknown as SettingsApiResponse);const result = await substituteRedactedMcpCredentials({- id: "stdio-0",+ id: "alpha",type: "stdio",name: "beta",command: "npx",@@ -73,7 +73,7 @@ describe("substituteRedactedMcpCredentials", () => {} as unknown as SettingsApiResponse);const result = await substituteRedactedMcpCredentials({- id: "stdio-0",+ id: "my-server",type: "stdio",name: "my-server",command: "npx",@@ -145,7 +145,7 @@ describe("substituteRedactedMcpCredentials", () => {} as unknown as SettingsApiResponse);const result = await substituteRedactedMcpCredentials({- id: "shttp-0",+ id: "superhuman-mail",type: "shttp",name: "superhuman-mail",url: "https://mcp.mail.superhuman.com/mcp",@@ -178,4 +178,131 @@ describe("substituteRedactedMcpCredentials", () => {},});});++ it("preserves fresh OAuth edits while substituting only redacted leaves", async () => {+ vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({+ agent_settings: {+ mcp_config: {+ "superhuman-mail": {+ url: "https://mcp.mail.superhuman.com/mcp",+ auth: {+ strategy: "oauth2",+ state: {+ tokens: {+ access_token: "gAAAAA-encrypted-access-token",+ refresh_token: "gAAAAA-encrypted-refresh-token",+ },+ client_info: {+ client_id: "old-client-id",+ client_secret: "gAAAAA-encrypted-client-secret",+ },+ },+ },+ },+ },+ },+ } as unknown as SettingsApiResponse);++ const result = await substituteRedactedMcpCredentials({+ id: "superhuman-mail",+ type: "shttp",+ name: "superhuman-mail",+ url: "https://mcp.mail.superhuman.com/mcp",+ auth: {+ strategy: "oauth2",+ state: {+ tokens: {+ access_token: REDACTED_MCP_SECRET_VALUE,+ refresh_token: REDACTED_MCP_SECRET_VALUE,+ },+ client_info: {+ client_id: "new-client-id",+ client_secret: REDACTED_MCP_SECRET_VALUE,+ },+ },+ },+ });++ expect(result.auth).toEqual({+ strategy: "oauth2",+ state: {+ tokens: {+ access_token: "gAAAAA-encrypted-access-token",+ refresh_token: "gAAAAA-encrypted-refresh-token",+ },+ client_info: {+ client_id: "new-client-id",+ client_secret: "gAAAAA-encrypted-client-secret",+ },+ },+ });+ });++ it("preserves fresh header-auth edits while substituting only redacted leaves", async () => {+ vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({+ agent_settings: {+ mcp_config: {+ mail: {+ url: "https://mail.example/mcp",+ auth: {+ strategy: "header",+ headers: {+ "X-API-Key": "gAAAAA-encrypted-api-key",+ "X-Region": "us-east-1",+ },+ },+ },+ },+ },+ } as unknown as SettingsApiResponse);++ const result = await substituteRedactedMcpCredentials({+ id: "mail",+ type: "shttp",+ name: "mail",+ url: "https://mail.example/mcp",+ auth: {+ strategy: "header",+ headers: {+ "X-API-Key": REDACTED_MCP_SECRET_VALUE,+ "X-Region": "eu-west-1",+ },+ },+ });++ expect(result.auth).toEqual({+ strategy: "header",+ headers: {+ "X-API-Key": "gAAAAA-encrypted-api-key",+ "X-Region": "eu-west-1",+ },+ });+ });++ it("replaces redacted raw remote headers with encrypted stored values", async () => {+ vi.spyOn(SettingsService, "fetchSettingsFromApi").mockResolvedValue({+ agent_settings: {+ mcp_config: {+ github: {+ url: "https://github.example/mcp",+ headers: {+ Authorization: "Bearer gAAAAA-encrypted-github-token",+ },+ },+ },+ },+ } as unknown as SettingsApiResponse);++ const result = await substituteRedactedMcpCredentials({+ id: "github",+ type: "shttp",+ name: "github",+ url: "https://github.example/mcp",+ headers: { Authorization: REDACTED_MCP_SECRET_VALUE },+ });++ expect(result.headers).toEqual({+ Authorization: "Bearer gAAAAA-encrypted-github-token",+ });+ });});diff --git a/src/api/mcp-service/mcp-redacted-credentials.ts b/src/api/mcp-service/mcp-redacted-credentials.tsindex beb8f912bb..c35abe533d 100644--- a/src/api/mcp-service/mcp-redacted-credentials.ts+++ b/src/api/mcp-service/mcp-redacted-credentials.ts@@ -31,72 +31,37 @@ const hasRedactedValue = (values: Record<string, string> | undefined) =>!!values &&Object.values(values).some((value) => value === REDACTED_MCP_SECRET_VALUE);-const remoteTransportMatches = (- type: MCPServerConfig["type"],- transport: unknown,-) => {- if (type === "sse") return transport === "sse";- if (type === "shttp") {- return (- transport === undefined ||- transport === "http" ||- transport === "shttp" ||- transport === "streamable-http"- );+/**+ * Recursively replace only the redacted display placeholders inside+ * ``submitted`` with the corresponding stored (encrypted) leaf. Fresh+ * non-redacted edits and untouched structure are preserved verbatim, so a+ * probe request exercises the server exactly as it will be persisted.+ */+function substituteRedactedLeaves<T>(submitted: T, stored: unknown): T {+ if (!isRecord(submitted)) return submitted;++ const storedRecord = isRecord(stored) ? stored : {};+ const merged: Record<string, unknown> = { ...submitted };+ for (const [key, value] of Object.entries(submitted)) {+ if (value === REDACTED_MCP_SECRET_VALUE) {+ const storedValue = storedRecord[key];+ if (+ typeof storedValue === "string" &&+ storedValue !== REDACTED_MCP_SECRET_VALUE+ ) {+ merged[key] = storedValue;+ }+ } else if (isRecord(value)) {+ merged[key] = substituteRedactedLeaves(value, storedRecord[key]);+ }}- return false;-};--// The editor assigns each stdio server an id of the form ``stdio-<i>`` matching-// its position in ``parseMcpConfig``'s stdio array. That position is stable-// across a rename because ``parseMcpConfig`` collects stdio entries (those-// without a ``url``) in ``Object.entries`` order, identical for the redacted-// and encrypted settings. Resolve the original stored entry by position so a-// renamed stdio server still finds its stored encrypted env, instead of-// looking it up by the new (no-longer-matching) display name.-const stdioIndexFromId = (id: string | undefined): number | undefined => {- if (!id) return undefined;- const match = /^stdio-(\d+)$/.exec(id);- return match ? Number.parseInt(match[1], 10) : undefined;-};--const findStoredStdioByIndex = (- id: string | undefined,- storedServers: StoredMcpConfig,-): StoredMcpServer | undefined => {- const index = stdioIndexFromId(id);- if (index === undefined) return undefined;- const stdioEntries = Object.entries(storedServers).filter(- ([, stored]) => !stored.url,- );- return stdioEntries[index]?.[1];-};+ return merged as T;+}const findStoredServer = (server: MCPServerConfig,storedServers: StoredMcpConfig,-): StoredMcpServer | undefined => {- if (server.type === "stdio") {- // Prefer the positional id: a rename changes the display name (the stored- // dict key), and a rename onto an existing name would otherwise restore the- // wrong server's secrets. Fall back to a name match only when no id-based- // position is available (e.g. configs built without an editor-assigned id).- return (- findStoredStdioByIndex(server.id, storedServers) ??- (server.name ? storedServers[server.name] : undefined)- );- }-- if (server.name && storedServers[server.name]) {- return storedServers[server.name];- }-- return Object.values(storedServers).find(- (stored) =>- stored.url === server.url &&- remoteTransportMatches(server.type, stored.transport),- );-};+): StoredMcpServer | undefined => storedServers[server.id];async function fetchEncryptedStoredServer(server: MCPServerConfig,@@ -112,8 +77,9 @@ async function fetchEncryptedStoredServer(/*** The MCP editor sees redacted settings (`**********`). When the user leaves* a secret unchanged, replace that placeholder with the stored encrypted- * env/header/OAuth state value so tests and saves round-trip the real- * credential without exposing plaintext in the browser.+ * env/header/OAuth state value so a connectivity test can exercise the real+ * credential without exposing plaintext in the browser. Persistence never+ * calls this helper; sparse settings patches omit unchanged secrets.*/export async function substituteRedactedMcpCredentials(server: MCPServerConfig,@@ -123,8 +89,11 @@ export async function substituteRedactedMcpCredentials(const redactedRemoteAuth =(server.type === "sse" || server.type === "shttp") &&hasRedactedMcpSecretLeaf(server.auth);+ const redactedRemoteHeaders =+ (server.type === "sse" || server.type === "shttp") &&+ hasRedactedValue(server.headers);- if (!redactedStdioEnv && !redactedRemoteAuth) {+ if (!redactedStdioEnv && !redactedRemoteAuth && !redactedRemoteHeaders) {return server;}@@ -146,11 +115,23 @@ export async function substituteRedactedMcpCredentials(return { ...server, env };}- if (!redactedRemoteAuth) return server;- if (isMcpAuthCredential(stored.auth)) {- return { ...server, auth: stored.auth };+ const nextServer = { ...server };+ if (redactedRemoteAuth && isMcpAuthCredential(stored.auth)) {+ nextServer.auth = substituteRedactedLeaves(server.auth, stored.auth);}- return server;+ if (redactedRemoteHeaders) {+ const storedHeaders = stringRecord(stored.headers) ?? {};+ nextServer.headers = Object.fromEntries(+ Object.entries(server.headers ?? {}).map(([key, value]) => [+ key,+ value === REDACTED_MCP_SECRET_VALUE &&+ typeof storedHeaders[key] === "string"+ ? storedHeaders[key]+ : value,+ ]),+ );+ }+ return nextServer;} catch {return server;}diff --git a/src/api/mcp-service/mcp-service.api.test.ts b/src/api/mcp-service/mcp-service.api.test.tsindex 42d46ba66a..3a849428f4 100644--- a/src/api/mcp-service/mcp-service.api.test.ts+++ b/src/api/mcp-service/mcp-service.api.test.ts@@ -78,7 +78,7 @@ describe("McpService.testServer", () => {});await McpService.testServer({- id: "shttp-0",+ id: "linear",type: "shttp",name: "linear",url: "https://mcp.linear.app/mcp",@@ -92,7 +92,7 @@ describe("McpService.testServer", () => {expect(testServer.mock.calls[0][0]).toMatchObject({name: "linear",server: {- transport: "http",+ type: "http",url: "https://mcp.linear.app/mcp",auth: { strategy: "bearer", value: encryptedAuth },},@@ -126,7 +126,7 @@ describe("McpService.testServer", () => {expect(testServer.mock.calls[0][0]).toMatchObject({name: "superhuman-mail",server: {- transport: "http",+ type: "http",url: "https://mcp.mail.superhuman.com/mcp",auth: {strategy: "oauth2",@@ -202,7 +202,7 @@ describe("McpService.testServer", () => {expect(startOAuth.mock.calls[0][0]).toMatchObject({name: "superhuman-mail",server: {- transport: "http",+ type: "http",url: "https://mcp.mail.superhuman.com/mcp",auth: {strategy: "oauth2",diff --git a/src/api/mcp-service/mcp-service.api.ts b/src/api/mcp-service/mcp-service.api.tsindex 2f2549b34d..79be35c6a8 100644--- a/src/api/mcp-service/mcp-service.api.ts+++ b/src/api/mcp-service/mcp-service.api.ts@@ -1,5 +1,5 @@import { MCPClient } from "@openhands/typescript-client/clients";-import type { MCPTestRequest } from "@openhands/typescript-client";+import type { AgentServerMCPTestRequest } from "@openhands/typescript-client";import { getAgentServerClientOptions } from "../agent-server-client-options";import {getActiveBackend,@@ -9,7 +9,6 @@ import {getCredentialValidationForServer,type CredentialValidation,} from "#/utils/mcp-credential-validation";-import type { MCPAuthCredential } from "#/types/mcp-auth";import type {ExtendedMCPTestResponse,MCPOAuthStartResponse,@@ -21,30 +20,12 @@ import { substituteRedactedMcpCredentials } from "./mcp-redacted-credentials";const OAUTH_MCP_TEST_TIMEOUT_SECONDS = 120;-type MCPTestServer = {- transport?: "stdio" | "http" | "sse";- command?: string;- args?: string[];- env?: Record<string, string>;- url?: string;- headers?: Record<string, string>;- auth?: MCPAuthCredential;-};--interface ExtendedMCPTestRequest {- server: MCPTestServer;- name?: string;- timeout?: number;- tool_call?: {- name: string;- arguments: Record<string, unknown>;- };-}--function toMcpServer(server: MCPServerConfig): MCPTestServer {+function toMcpServer(+ server: MCPServerConfig,+): AgentServerMCPTestRequest["server"] {if (server.type === "stdio") {return {- transport: "stdio",+ type: "stdio",command: server.command!,...(server.args?.length && { args: server.args }),...(server.env &&@@ -52,7 +33,7 @@ function toMcpServer(server: MCPServerConfig): MCPTestServer {};}return {- transport: server.type === "sse" ? "sse" : "http",+ type: server.type === "sse" ? "sse" : "http",url: server.url!,...(server.headers &&Object.keys(server.headers).length > 0 && { headers: server.headers }),@@ -66,7 +47,7 @@ function getMcpTestTimeout(server: MCPServerConfig): number | undefined {}async function buildMcpTestRequest(server: MCPServerConfig): Promise<{- request: ExtendedMCPTestRequest;+ request: AgentServerMCPTestRequest;substituted: MCPServerConfig;}> {const validation = getCredentialValidationForServer(server);@@ -218,7 +199,7 @@ class McpService {try {const { request, substituted } = await buildMcpTestRequest(server);const result = (await client.testServer(- request as MCPTestRequest,+ request,)) as ExtendedMCPTestResponse;// Redact against both config forms: `server` may hold fresh plaintext// input, `substituted` the stored (encrypted) round-trip values.@@ -335,7 +316,7 @@ class McpService {server: MCPServerConfig,): Promise<MCPOAuthStartResponse> {const { request } = await buildMcpTestRequest(server);- return client.startOAuth(request as MCPTestRequest);+ return client.startOAuth(request);}// typescript-client 1.36 types the OAuth probes with the generateddiff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.tsindex d01ddda79a..6da2fc926c 100644--- a/src/api/settings-service/settings-service.api.ts+++ b/src/api/settings-service/settings-service.api.ts@@ -1,11 +1,12 @@import { SettingsClient } from "@openhands/typescript-client/clients";+import type {+ MCPConfigPatch,+ MCPServer,+ MCPServerPatch,+} from "@openhands/typescript-client";import { DEFAULT_SETTINGS } from "#/services/settings";import { Settings, SettingsSchema, SettingsValue } from "#/types/settings";-import {- getSdkMcpServerMap,- hasRedactedMcpSecretLeaf,- stringRecord,-} from "#/utils/mcp-config";+import { stringRecord } from "#/utils/mcp-config";import { getActiveBackend } from "../backend-registry/active-store";import {fetchCloudConversationSettingsSchema,@@ -228,7 +229,17 @@ const headersFromMcpAuth = (}};-const cloudCompatibleMcpConfig = (value: unknown): unknown => {+/**+ * Convert SDK `auth` credentials to the cloud's header-only storage shape.+ *+ * The cloud settings endpoint applies `mcp_config` as a merge patch, so a+ * credential change must also tombstone the headers the previous credential+ * produced β otherwise stale secrets survive a strategy switch (e.g. an+ * api_key's custom header after moving to bearer). Stored headers that the+ * new credential still produces (via the patch's carried `headers` or the+ * converted auth) are left untouched; any other stored header is cleared.+ */+const cloudCompatibleMcpConfig = async (value: unknown): Promise<unknown> => {if (!isRecord(value)) return value;const hasWrapper = isRecord(value.mcpServers);@@ -236,16 +247,61 @@ const cloudCompatibleMcpConfig = (value: unknown): unknown => {? (value.mcpServers as Record<string, unknown>): value;+ const needsStoredCredential =+ Object.values(serverMap).some(+ (server) =>+ isRecord(server) && isRecord(server.auth) && server.auth !== null,+ ) && getActiveBackend().backend.kind === "cloud";++ const storedHeadersByServer = new Map<string, Record<string, string>>();+ if (needsStoredCredential) {+ try {+ const stored = await fetchCloudSettings();+ const storedMcp = isRecord(stored.mcp_config) ? stored.mcp_config : {};+ for (const [name, server] of Object.entries(storedMcp)) {+ if (isRecord(server)) {+ const headers = stringRecord(+ (server as Record<string, unknown>).headers,+ );+ if (headers) storedHeadersByServer.set(name, headers);+ }+ }+ } catch {+ // Fall back to the patch-only conversion; a transient fetch failure+ // must not block saving the user's explicit edits.+ }+ }+const converted = Object.fromEntries(Object.entries(serverMap).map(([name, server]) => {- if (!isRecord(server) || !isRecord(server.auth)) return [name, server];+ if (!isRecord(server)) return [name, server];+ if (server.auth === null) {+ const nextServer: Record<string, unknown> = {+ ...server,+ headers: null,+ };+ delete nextServer.auth;+ return [name, nextServer];+ }+ if (!isRecord(server.auth)) return [name, server];const authHeaders = headersFromMcpAuth(server.auth);if (authHeaders === null) return [name, server];const nextServer = { ...server };const existingHeaders = stringRecord(server.headers) ?? {};- const mergedHeaders = { ...existingHeaders, ...authHeaders };+ const mergedHeaders: Record<string, string | null> = {+ ...existingHeaders,+ ...authHeaders,+ };++ const storedHeaders = storedHeadersByServer.get(name);+ if (storedHeaders) {+ for (const key of Object.keys(storedHeaders)) {+ if (!(key in mergedHeaders)) mergedHeaders[key] = null;+ }+ }+delete nextServer.auth;if (Object.keys(mergedHeaders).length > 0) {nextServer.headers = mergedHeaders;@@ -259,53 +315,6 @@ const cloudCompatibleMcpConfig = (value: unknown): unknown => {return hasWrapper ? { ...value, mcpServers: converted } : converted;};-/**- * Spell out every server's `enabled` flag.- *- * `toSdkMcpConfig` omits the flag while a server is enabled and relies on the- * pre-clear below to drop a previously persisted `enabled: false`. The one- * write that skips the pre-clear β a cloud update carrying redacted secrets β- * lands as an RFC 7386 merge instead, and a merge cannot clear a key by- * omitting it. Without this, re-enabling a server on cloud would silently do- * nothing.- */-const withExplicitMcpEnabled = (value: unknown): unknown => {- if (!isRecord(value)) return value;-- const hasWrapper = isRecord(value.mcpServers);- const serverMap: Record<string, unknown> = hasWrapper- ? (value.mcpServers as Record<string, unknown>)- : value;-- const converted = Object.fromEntries(- Object.entries(serverMap).map(([name, server]) =>- isRecord(server)- ? [name, { ...server, enabled: server.enabled !== false }]- : [name, server],- ),- );-- return hasWrapper ? { ...value, mcpServers: converted } : converted;-};--const hasRedactedMcpSecrets = (mcpConfig: unknown): boolean => {- const servers = getSdkMcpServerMap(mcpConfig);- if (!servers) return false;- return Object.values(servers).some(- (server) =>- hasRedactedMcpSecretLeaf(isRecord(server) ? server.auth : undefined) ||- hasRedactedMcpSecretLeaf(isRecord(server) ? server.headers : undefined) ||- hasRedactedMcpSecretLeaf(isRecord(server) ? server.env : undefined),- );-};--const removesMcpServer = (previous: unknown, next: unknown): boolean => {- const previousServers = getSdkMcpServerMap(previous);- const nextServers = getSdkMcpServerMap(next);- if (!previousServers || !nextServers) return false;- return Object.keys(previousServers).some((name) => !(name in nextServers));-};-/*** Transform API response into Settings object with derived fields.*/@@ -520,6 +529,77 @@ class SettingsService {).getConversationSchema()) as SettingsSchema;}+ /**+ * Apply one name-keyed MCP merge patch in exactly one request. The server+ * owns the stored catalog and secret preservation; Canvas never rebuilds+ * the catalog from redacted display settings.+ */+ static async patchMcpConfig(patch: MCPConfigPatch): Promise<boolean> {+ if (getActiveBackend().backend.kind === "cloud") {+ const mcpConfig = await cloudCompatibleMcpConfig(patch);+ await withRetry(() =>+ saveCloudSettings({+ agent_settings_diff: { mcp_config: mcpConfig as SettingsValue },+ }),+ );+ } else {+ await withRetry(() =>+ new SettingsClient(getAgentServerClientOptions()).updateSettings({+ agent_settings_diff: { mcp_config: patch },+ }),+ );+ }+ clearCache();+ return true;+ }++ static async patchMcpServer(+ settingsKey: string,+ patch: MCPServerPatch,+ ): Promise<boolean> {+ if (getActiveBackend().backend.kind === "cloud") {+ return SettingsService.patchMcpConfig({ [settingsKey]: patch });+ }+ await withRetry(() =>+ new SettingsClient(getAgentServerClientOptions()).patchMcpServer(+ settingsKey,+ patch,+ ),+ );+ clearCache();+ return true;+ }++ static async createMcpServer(+ settingsKey: string,+ server: MCPServer,+ ): Promise<boolean> {+ if (getActiveBackend().backend.kind === "cloud") {+ return SettingsService.patchMcpConfig({ [settingsKey]: server });+ }+ await withRetry(() =>+ new SettingsClient(getAgentServerClientOptions()).createMcpServer(+ settingsKey,+ server,+ ),+ );+ clearCache();+ return true;+ }++ static async deleteMcpServer(settingsKey: string): Promise<boolean> {+ if (getActiveBackend().backend.kind === "cloud") {+ return SettingsService.patchMcpConfig({ [settingsKey]: null });+ }+ await withRetry(() =>+ new SettingsClient(getAgentServerClientOptions()).deleteMcpServer(+ settingsKey,+ ),+ );+ clearCache();+ return true;+ }+/*** Save settings to the agent server API.* Uses PATCH for incremental updates.@@ -564,77 +644,6 @@ class SettingsService {}const isCloud = getActiveBackend().backend.kind === "cloud";-- // The backend applies ``agent_settings_diff`` by deep-merging it into the- // existing ``agent_settings`` dict (see SDK- // ``openhands.agent_server.persistence.models._deep_merge``). That works- // for scalar fields but is wrong for ``mcp_config``, which is- // a name-keyed map: a diff that omits a server cannot remove it (stale- // key stays), and a diff whose key indices shift (e.g. after deleting- // index 0, the second server is renumbered) leaves the original keys- // behind as duplicates pointing to the wrong server config.- //- // The only way to make ``mcp_config`` behave like a replace through this- // API is to first null it out β ``null`` is not a dict, so deep-merge- // takes the else branch and sets the field to ``None`` outright β and- // then send the new value in a follow-up call. We do this for every- // ``mcp_config`` write, including adds (the wasted round-trip is- // negligible for this user action and avoids divergent code paths).- const agentDiff = payload.agent_settings_diff;- // Send a pre-clear PATCH when the diff sets ``mcp_config`` to a non-null- // value. A second PATCH below then writes the new value. Skipping the- // pre-clear when the caller is already clearing (``mcp_config: null``)- // avoids a pointless duplicate request.- const needsMcpPreClear =- !!agentDiff && "mcp_config" in agentDiff && agentDiff.mcp_config !== null;-- // The pre-clear is destructive: if the follow-up write fails after the- // clear succeeds, the user's MCP config is left empty. Snapshot the- // previous value (in raw SDK-native shape, NOT the GUI's parsed MCPConfig)- // before pre-clearing so we can attempt a best-effort rollback. The- // original write error is always re-thrown to the caller regardless- // of rollback success β the GUI's react-query mutations surface that- // as an error toast so the user knows to retry.- //- // Snapshot must be the SDK-native server map because that is what the- // backend expects on the rollback PATCH.- // ``SettingsService.getSettings`` returns a GUI Settings object whose- // ``mcp_config`` is typed as the parsed frontend MCPConfig and- // defaults to empty arrays when nothing is installed, so it is not- // suitable for round-tripping back to the backend.- let mcpConfigSnapshot: unknown = undefined;- if (needsMcpPreClear) {- try {- if (isCloud) {- const raw = (await fetchCloudSettings()) as {- agent_settings?: { mcp_config?: unknown };- };- mcpConfigSnapshot = raw?.agent_settings?.mcp_config;- } else {- const raw = (await SettingsService.fetchSettingsFromApi()) as {- agent_settings?: { mcp_config?: unknown };- };- mcpConfigSnapshot = raw?.agent_settings?.mcp_config;- }- } catch {- // Snapshot failed (network blip, etc.). Continue without rollback- // ability β the original write error will still surface.- }- }-- // Cloud settings may redact MCP env/header/auth secrets without an- // encrypted exposure mode. A pre-clear before a non-delete update can- // permanently erase unchanged secrets; for updates that keep all existing- // server keys, rely on the backend deep-merge to preserve redacted leaves- // while applying edited fields and newly typed credentials.- const shouldUseCloudMergePatchForRedactedMcpSecrets =- isCloud &&- needsMcpPreClear &&- hasRedactedMcpSecrets(mcpConfigSnapshot) &&- !removesMcpServer(mcpConfigSnapshot, agentDiff?.mcp_config);- const shouldPreClearMcpConfig =- needsMcpPreClear && !shouldUseCloudMergePatchForRedactedMcpSecrets;-if (isCloud) {const hasCloudWork =!!payload.agent_settings_diff ||@@ -643,13 +652,6 @@ class SettingsService {if (!hasCloudWork) {return true;}- if (shouldPreClearMcpConfig) {- await withRetry(() =>- saveCloudSettings({- agent_settings_diff: { mcp_config: null },- }),- );- }// Build the cloud payload from the same diffs, but as a separate// object so undefined keys don't appear in the call (saveCloudSettings// is called from tests with an exact-shape assertion).@@ -657,14 +659,10 @@ class SettingsService {if (payload.agent_settings_diff) {cloudPayload.agent_settings_diff = { ...payload.agent_settings_diff };if ("mcp_config" in cloudPayload.agent_settings_diff) {- const mcpConfig = cloudCompatibleMcpConfig(- cloudPayload.agent_settings_diff.mcp_config,- );- cloudPayload.agent_settings_diff.mcp_config = (- shouldUseCloudMergePatchForRedactedMcpSecrets- ? withExplicitMcpEnabled(mcpConfig)- : mcpConfig- ) as SettingsValue;+ cloudPayload.agent_settings_diff.mcp_config =+ (await cloudCompatibleMcpConfig(+ cloudPayload.agent_settings_diff.mcp_config,+ )) as SettingsValue;}}if (payload.conversation_settings_diff) {@@ -677,26 +675,7 @@ class SettingsService {// `saveCloudSettings` re-flattens them onto the request body.cloudPayload.app_preferences = appPreferences;}- try {- await withRetry(() => saveCloudSettings(cloudPayload));- } catch (err) {- if (shouldPreClearMcpConfig && mcpConfigSnapshot) {- // Best-effort rollback. We deliberately do not wrap in withRetry:- // the user's session is already in a degraded state and we want- // to surface the original error promptly. Swallowing the restore- // error preserves the original failure context for the caller.- try {- await saveCloudSettings({- agent_settings_diff: {- mcp_config: mcpConfigSnapshot as SettingsValue,- },- });- } catch {- // Rollback failed; the original error takes precedence.- }- }- throw err;- }+ await withRetry(() => saveCloudSettings(cloudPayload));} else {// The local agent-server PATCH /api/settings requires at least one of// the three diff fields. Skip the request entirely if nothing changed.@@ -707,36 +686,11 @@ class SettingsService {if (!hasLocalDiffs) {return true;}- if (shouldPreClearMcpConfig) {- await withRetry(() =>- new SettingsClient(getAgentServerClientOptions()).updateSettings({- agent_settings_diff: { mcp_config: null },- }),- );- }- try {- await withRetry(() =>- new SettingsClient(getAgentServerClientOptions()).updateSettings(- payload,- ),- );- } catch (err) {- if (shouldPreClearMcpConfig && mcpConfigSnapshot) {- // See cloud branch above for rationale.- try {- await new SettingsClient(- getAgentServerClientOptions(),- ).updateSettings({- agent_settings_diff: {- mcp_config: mcpConfigSnapshot as SettingsValue,- },- });- } catch {- // Rollback failed; the original error takes precedence.- }- }- throw err;- }+ await withRetry(() =>+ new SettingsClient(getAgentServerClientOptions()).updateSettings(+ payload,+ ),+ );}// Invalidate cache after successful savediff --git a/src/components/features/automations/recommended-automations-launcher.tsx b/src/components/features/automations/recommended-automations-launcher.tsxindex b98c9c4158..efe1be5b85 100644--- a/src/components/features/automations/recommended-automations-launcher.tsx+++ b/src/components/features/automations/recommended-automations-launcher.tsx@@ -74,14 +74,13 @@ export function RecommendedAutomationsLauncher({const completedInstallRef = useRef(false);const launchInFlightRef = useRef(false);- // A disabled server is withheld from the agent, so treating it as installed- // would show "Connected" for an automation that then fails at runtime.const installedMcpConfig = useMemo(() =>flattenMcpConfig(- parseMcpConfig(settings?.agent_settings?.mcp_config),+ settings?.mcp_config ??+ parseMcpConfig(settings?.agent_settings?.mcp_config),).filter((server) => server.enabled !== false),- [settings?.agent_settings?.mcp_config],+ [settings?.agent_settings?.mcp_config, settings?.mcp_config],);const launchAutomation = useCallback(diff --git a/src/components/features/mcp-page/custom-server-editor.tsx b/src/components/features/mcp-page/custom-server-editor.tsxindex 146a8cc58e..af36fe1256 100644--- a/src/components/features/mcp-page/custom-server-editor.tsx+++ b/src/components/features/mcp-page/custom-server-editor.tsx@@ -25,6 +25,7 @@ import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message"import { cn } from "#/utils/utils";import { modalTitleLgClassName } from "#/utils/modal-classes";import McpService from "#/api/mcp-service/mcp-service.api";+import { MCP_RENAME_CREDENTIAL_ERROR } from "#/utils/mcp-config";interface CustomServerEditorProps {server: MCPServerConfig;@@ -107,6 +108,10 @@ export function CustomServerEditor({// had no `onError` and the modal closed even on a 4xx/5xx, leaving// the user to discover the failure on the next page load.const handleError = (err: unknown) => {+ if (err instanceof Error && err.message === MCP_RENAME_CREDENTIAL_ERROR) {+ displayErrorToast(err.message);+ return;+ }const message = retrieveAxiosErrorMessage(err as AxiosError);displayErrorToast(message || t(I18nKey.ERROR$GENERIC));};diff --git a/src/components/features/mcp-page/install-server-modal.tsx b/src/components/features/mcp-page/install-server-modal.tsxindex a5ff4935d4..f7851567be 100644--- a/src/components/features/mcp-page/install-server-modal.tsx+++ b/src/components/features/mcp-page/install-server-modal.tsx@@ -1,7 +1,6 @@import React from "react";import { useTranslation } from "react-i18next";import { AxiosError } from "axios";-import { v4 as uuidv4 } from "uuid";import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";import { ModalCloseButton } from "#/components/shared/modals/modal-close-button";import { BrandButton } from "#/components/features/settings/brand-button";@@ -406,7 +405,7 @@ export function InstallServerModal({auth = { strategy: "header", headers: fieldHeaders };}const payload: MCPServerConfig = {- id: `${template.kind}-${uuidv4()}`,+ id: "",type: template.kind,// Name remote servers after the catalog slug (e.g. "github") so they// get a referenceable, LLM-tool-safe mcp_config key instead of the@@ -458,7 +457,7 @@ export function InstallServerModal({}const payload: MCPServerConfig = {- id: `stdio-${uuidv4()}`,+ id: "",type: "stdio",name: stdio.serverName,command: stdio.command,diff --git a/src/components/features/settings/mcp-settings/mcp-server-form.tsx b/src/components/features/settings/mcp-settings/mcp-server-form.tsxindex 4bf30b26ff..2010e6d024 100644--- a/src/components/features/settings/mcp-settings/mcp-server-form.tsx+++ b/src/components/features/settings/mcp-settings/mcp-server-form.tsx@@ -354,7 +354,7 @@ export function MCPServerForm({const buildConfig = (formData: FormData): MCPServerConfig => {const baseConfig = {- id: server?.id || `${serverType}-${Date.now()}`,+ id: server?.id || "",type: serverType,// The form has no enable/disable control (that lives on the card), so// carry the existing state forward β otherwise saving an edit to a@@ -372,6 +372,10 @@ export function MCPServerForm({...baseConfig,...(name && { name }),url: url!,+ // Raw protocol headers are not editable in this form, but they are+ // still required for the pre-save connection probe. Persistence uses+ // a sparse patch and leaves them untouched.+ ...(server?.headers && { headers: server.headers }),...(auth && { auth }),};diff --git a/src/hooks/mutation/use-add-mcp-server.ts b/src/hooks/mutation/use-add-mcp-server.tsindex c65669fed6..5472de7c58 100644--- a/src/hooks/mutation/use-add-mcp-server.ts+++ b/src/hooks/mutation/use-add-mcp-server.ts@@ -1,44 +1,37 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { useSettings } from "#/hooks/query/use-settings";import SettingsService from "#/api/settings-service/settings-service.api";-import { MCPConfig } from "#/types/settings";import type { MCPServerConfig } from "#/types/mcp-server";import {+ allocateMcpSettingsKey,parseMcpConfig,- toMcpShttpServer,- toMcpSseServer,- toMcpStdioServer,- toSdkMcpConfig,+ toCanonicalMcpServer,} from "#/utils/mcp-config";import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";+// @spec MCP-001 β Sparse mutations preserve sibling serversexport function useAddMcpServer() {const queryClient = useQueryClient();const { data: settings } = useSettings();return useMutation({mutationFn: async (server: MCPServerConfig): Promise<void> => {- if (!settings) return;-- const currentConfig = parseMcpConfig(settings.agent_settings?.mcp_config);-- const newConfig: MCPConfig = {- sse_servers: [...currentConfig.sse_servers],- stdio_servers: [...currentConfig.stdio_servers],- shttp_servers: [...currentConfig.shttp_servers],- };-- if (server.type === "sse") {- newConfig.sse_servers.push(toMcpSseServer(server));- } else if (server.type === "stdio") {- newConfig.stdio_servers.push(toMcpStdioServer(server));- } else if (server.type === "shttp") {- newConfig.shttp_servers.push(toMcpShttpServer(server));+ if (!settings) {+ throw new Error("MCP settings are still loading. Please try again.");}- await SettingsService.saveSettings({- agent_settings_diff: { mcp_config: toSdkMcpConfig(newConfig) },- });+ const currentConfig =+ settings.mcp_config ??+ parseMcpConfig(settings.agent_settings?.mcp_config);+ const settingsKey = allocateMcpSettingsKey(+ currentConfig,+ server.name,+ server.type,+ );+ await SettingsService.createMcpServer(+ settingsKey,+ toCanonicalMcpServer(server),+ );},onSuccess: () => {queryClient.invalidateQueries({diff --git a/src/hooks/mutation/use-delete-mcp-server.ts b/src/hooks/mutation/use-delete-mcp-server.tsindex c1459bdaf1..6910b70866 100644--- a/src/hooks/mutation/use-delete-mcp-server.ts+++ b/src/hooks/mutation/use-delete-mcp-server.ts@@ -1,9 +1,6 @@import { useMutation, useQueryClient } from "@tanstack/react-query";-import { useSettings } from "#/hooks/query/use-settings";import SettingsService from "#/api/settings-service/settings-service.api";-import { MCPConfig } from "#/types/settings";import { MCPServerConfig } from "#/types/mcp-server";-import { parseMcpConfig, toSdkMcpConfig } from "#/utils/mcp-config";import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";import { clearMcpServerHealth } from "#/api/mcp-health/mcp-health-store";import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";@@ -11,73 +8,17 @@ import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";/*** Delete an installed MCP server.*- * We accept the full server config (not just a synthetic id like- * `stdio-2`) and re-resolve its position inside the freshly-read- * settings at mutation time. This eliminates the race between the- * user clicking "Delete" and confirming the dialog: if the underlying- * `mcp_config` changes (background refresh, multi-tab activity,- * another mutation) the index encoded in a synthetic id can drift,- * and we would otherwise splice the wrong server.+ * The UI server id is the canonical settings map key, so deletion does not+ * read, match, or reconstruct any other catalog entries.*/+// @spec MCP-001 β Sparse mutations preserve sibling servers+// @spec MCP-003 β Settings map keys are stable MCP identitiesexport function useDeleteMcpServer() {const queryClient = useQueryClient();- const { data: settings } = useSettings();return useMutation({mutationFn: async (target: MCPServerConfig): Promise<void> => {- const currentConfig = parseMcpConfig(- settings?.agent_settings?.mcp_config,- );-- const newConfig: MCPConfig = {- sse_servers: [...currentConfig.sse_servers],- stdio_servers: [...currentConfig.stdio_servers],- shttp_servers: [...currentConfig.shttp_servers],- };-- const extractUrl = (s: unknown): string | undefined => {- if (typeof s === "string") return s;- if (s && typeof s === "object" && "url" in s) {- const v = (s as { url?: unknown }).url;- return typeof v === "string" ? v : undefined;- }- return undefined;- };-- // Each branch guards on the discriminating field(s) it relies- // on. `MCPServerConfig` marks url/name/command optional for- // historical reasons, so without these guards an entry with- // undefined identifiers could accidentally match another entry- // that's also missing the same field (e.g. two stdio servers- // both lacking `name`).- if (target.type === "sse") {- if (!target.url) return;- const idx = newConfig.sse_servers.findIndex(- (s) => extractUrl(s) === target.url,- );- if (idx >= 0) newConfig.sse_servers.splice(idx, 1);- } else if (target.type === "shttp") {- if (!target.url) return;- const idx = newConfig.shttp_servers.findIndex(- (s) => extractUrl(s) === target.url,- );- if (idx >= 0) newConfig.shttp_servers.splice(idx, 1);- } else if (target.type === "stdio") {- if (!target.name || !target.command) return;- const idx = newConfig.stdio_servers.findIndex(- (s) =>- s.name === target.name &&- s.command === target.command &&- JSON.stringify(s.args ?? []) === JSON.stringify(target.args ?? []),- );- if (idx >= 0) newConfig.stdio_servers.splice(idx, 1);- } else {- return;- }-- await SettingsService.saveSettings({- agent_settings_diff: { mcp_config: toSdkMcpConfig(newConfig) },- });+ await SettingsService.deleteMcpServer(target.id);},onSuccess: (_data, target) => {// Drop the deleted server's health entry so a later server thatdiff --git a/src/hooks/mutation/use-save-settings.ts b/src/hooks/mutation/use-save-settings.tsindex fdc8166618..33c3d6285a 100644--- a/src/hooks/mutation/use-save-settings.ts+++ b/src/hooks/mutation/use-save-settings.ts@@ -76,9 +76,14 @@ export const useSaveSettings = (| undefined;if (nextMcpConfig && currentMcpConfig !== nextMcpConfig) {+ const servers = Object.values(nextMcpConfig);trackMcpConfigUpdated({- sseServersCount: nextMcpConfig.sse_servers?.length ?? 0,- stdioServersCount: nextMcpConfig.stdio_servers?.length ?? 0,+ sseServersCount: servers.filter(+ (server) => server.transport === "sse",+ ).length,+ stdioServersCount: servers.filter(+ (server) => server.transport === "stdio",+ ).length,});}diff --git a/src/hooks/mutation/use-update-mcp-server.ts b/src/hooks/mutation/use-update-mcp-server.tsindex 8d3b495425..785f92cb93 100644--- a/src/hooks/mutation/use-update-mcp-server.ts+++ b/src/hooks/mutation/use-update-mcp-server.ts@@ -1,20 +1,18 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { useSettings } from "#/hooks/query/use-settings";import SettingsService from "#/api/settings-service/settings-service.api";-import { MCPConfig } from "#/types/settings";import { MCPServerConfig } from "#/types/mcp-server";import {+ buildMcpServerPatch,+ buildRenameMcpConfigPatch,parseMcpConfig,- toMcpShttpServer,- toMcpSseServer,- toMcpStdioServer,- toSdkMcpConfig,} from "#/utils/mcp-config";import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";import { clearMcpServerHealth } from "#/api/mcp-health/mcp-health-store";-import { substituteRedactedMcpCredentials } from "#/api/mcp-service/mcp-redacted-credentials";import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";+import { toMcpServerName } from "#/utils/mcp-server-name";+// @spec MCP-001 β Sparse mutations preserve sibling serversexport function useUpdateMcpServer() {const queryClient = useQueryClient();const { data: settings } = useSettings();@@ -26,36 +24,58 @@ export function useUpdateMcpServer() {}: {serverId: string;server: MCPServerConfig;- }): Promise<void> => {- const currentConfig = parseMcpConfig(- settings?.agent_settings?.mcp_config,- );-- const newConfig: MCPConfig = {- sse_servers: [...currentConfig.sse_servers],- stdio_servers: [...currentConfig.stdio_servers],- shttp_servers: [...currentConfig.shttp_servers],- };- const serverToSave = await substituteRedactedMcpCredentials(server);- const [serverType, indexStr] = serverId.split("-");- const index = parseInt(indexStr, 10);+ }): Promise<string> => {+ const currentConfig =+ settings?.mcp_config ??+ parseMcpConfig(settings?.agent_settings?.mcp_config);+ const previous = currentConfig[serverId];+ if (!previous) {+ throw new Error(`MCP server "${serverId}" no longer exists.`);+ }+ const previousHealthKey = getMcpServerHealthKey({+ id: serverId,+ type:+ previous.transport === "stdio"+ ? "stdio"+ : previous.transport === "sse"+ ? "sse"+ : "shttp",+ name: serverId,+ ...(previous.transport === "stdio"+ ? {+ command: previous.command,+ args: previous.args ?? undefined,+ env: previous.env ?? undefined,+ }+ : {+ url: previous.url,+ headers: previous.headers ?? undefined,+ auth: previous.auth ?? undefined,+ }),+ });- if (serverType === "sse") {- newConfig.sse_servers[index] = toMcpSseServer(serverToSave);- } else if (serverType === "stdio") {- newConfig.stdio_servers[index] = toMcpStdioServer(serverToSave);- } else if (serverType === "shttp") {- newConfig.shttp_servers[index] = toMcpShttpServer(serverToSave);+ const nextKey = toMcpServerName(server.name || serverId);+ if (nextKey !== serverId) {+ if (nextKey in currentConfig) {+ throw new Error(`MCP server "${nextKey}" already exists.`);+ }+ await SettingsService.patchMcpConfig(+ buildRenameMcpConfigPatch(serverId, nextKey, previous, server),+ );+ return previousHealthKey;}- await SettingsService.saveSettings({- agent_settings_diff: { mcp_config: toSdkMcpConfig(newConfig) },- });+ await SettingsService.patchMcpServer(+ serverId,+ buildMcpServerPatch(previous, server),+ );+ return previousHealthKey;},- onSuccess: (_data, variables) => {+ onSuccess: (previousHealthKey, variables) => {// The stored config changed, so any prior health verdict for it is// stale. This hook-level reset runs before the caller's onSuccess,// letting save flows re-seed from their fresh pre-save test result.+ clearMcpServerHealth(previousHealthKey);clearMcpServerHealth(getMcpServerHealthKey(variables.server));queryClient.invalidateQueries({queryKey: SETTINGS_QUERY_KEYS.personal(),diff --git a/src/routes/mcp.tsx b/src/routes/mcp.tsxindex 3f0c8fdb7a..a9cd0ac10a 100644--- a/src/routes/mcp.tsx+++ b/src/routes/mcp.tsx@@ -49,7 +49,9 @@ export default function MCPPage() {const [sectionFilter, setSectionFilter] =React.useState<McpSectionFilter>("all");- const mcpConfig = parseMcpConfig(settings?.agent_settings?.mcp_config);+ const mcpConfig =+ settings?.mcp_config ??+ parseMcpConfig(settings?.agent_settings?.mcp_config);const allServers = flattenMcpConfig(mcpConfig);const mcpMarketplace = getMcpMarketplaceCatalog(MCP_MARKETPLACE);diff --git a/src/services/settings.ts b/src/services/settings.tsindex 4ea15939f8..6eef5a2b10 100644--- a/src/services/settings.ts+++ b/src/services/settings.ts@@ -24,11 +24,7 @@ export const DEFAULT_SETTINGS: Settings = {search_api_key: "",is_new_user: true,disabled_skills: [],- mcp_config: {- sse_servers: [],- stdio_servers: [],- shttp_servers: [],- },+ mcp_config: {},max_budget_per_task: null,email: "",email_verified: true,diff --git a/src/types/mcp-auth.ts b/src/types/mcp-auth.tsindex 59e4f7955a..f8c6333041 100644--- a/src/types/mcp-auth.ts+++ b/src/types/mcp-auth.ts@@ -1,47 +1,19 @@-export type MCPOAuthClientAuthMethod =- | "none"- | "client_secret_post"- | "client_secret_basic"- | "private_key_jwt";--export type MCPJsonValue =- | boolean- | number- | string- | null- | MCPJsonValue[]- | { [key: string]: MCPJsonValue };--export interface MCPOAuthAuthenticationConfig {- type: "oauth";- client_auth_method?: MCPOAuthClientAuthMethod | null;- scopes?: string | string[] | null;- client_name?: string | null;- client_metadata_url?: string | null;- client_id?: string | null;- client_secret?: string | null;- additional_client_metadata?: Record<string, MCPJsonValue> | null;-}--export type MCPAuthenticationConfig = MCPOAuthAuthenticationConfig;--export interface MCPOAuthState {- tokens?: Record<string, MCPJsonValue> | null;- client_info?: Record<string, MCPJsonValue> | null;- token_expires_at?: number | null;-}--export type MCPAuthCredential =- | { strategy: "none" }- | { strategy: "api_key"; value?: string | null; header_name?: string | null }- | { strategy: "bearer"; value?: string | null }- | { strategy: "basic"; username: string; password?: string | null }- | { strategy: "header"; headers?: Record<string, string> | null }- | {- strategy: "oauth2";- authentication?: MCPAuthenticationConfig | null;- state?: MCPOAuthState | null;- };+import type {+ MCPAuthCredential,+ MCPOAuthAuthentication,+} from "@openhands/typescript-client";++export type {+ MCPAuthCredential,+ MCPOAuthAuthentication,+ MCPOAuthState,+} from "@openhands/typescript-client";++export type MCPAuthenticationConfig = MCPOAuthAuthentication;+export type MCPOAuthAuthenticationConfig = MCPOAuthAuthentication;+export type MCPOAuthClientAuthMethod = NonNullable<+ MCPOAuthAuthentication["client_auth_method"]+>;export const MCP_AUTH_STRATEGIES = ["none",diff --git a/src/types/mcp-server.ts b/src/types/mcp-server.tsindex 1c2ad1f88b..c63394ddc5 100644--- a/src/types/mcp-server.ts+++ b/src/types/mcp-server.ts@@ -1,4 +1,11 @@-import type { MCPTestFailureKind } from "@openhands/typescript-client";+import type {+ AgentServerMCPOAuthStatusResponse,+ AgentServerMCPStartOAuthResponse,+ AgentServerMCPTestResponse,+ AgentServerMCPToolCall,+ AgentServerMCPToolCallResult,+ MCPTestFailureKind,+} from "@openhands/typescript-client";import type { MCPAuthCredential, MCPOAuthState } from "./mcp-auth";export type MCPServerType = "sse" | "stdio" | "shttp";@@ -21,52 +28,46 @@ export interface MCPServerConfig {enabled?: boolean;}-export interface MCPTestToolCall {- name: string;- arguments: Record<string, unknown>;-}--export interface MCPTestToolResult {- is_error: boolean;- text: string;-}+export type MCPTestToolCall = AgentServerMCPToolCall;+export type MCPTestToolResult = AgentServerMCPToolCallResult;export type ExtendedMCPTestFailureKind = MCPTestFailureKind | "credentials";-export interface ExtendedMCPTestSuccess {+type GeneratedMCPTestSuccess = Extract<+ AgentServerMCPTestResponse,+ { ok?: true }+>;+type GeneratedMCPTestFailure = Extract<+ AgentServerMCPTestResponse,+ { error: string }+>;++export type ExtendedMCPTestSuccess = Omit<+ GeneratedMCPTestSuccess,+ "ok" | "tools" | "oauth_state"+> & {ok: true;tools: string[];tool_result?: MCPTestToolResult | null;oauth_state?: MCPOAuthState | null;-}+};-export interface ExtendedMCPTestFailure {+export type ExtendedMCPTestFailure = Omit<+ GeneratedMCPTestFailure,+ "ok" | "error_kind"+> & {ok: false;- error: string;error_kind: ExtendedMCPTestFailureKind;-}+};export type ExtendedMCPTestResponse =| ExtendedMCPTestSuccess| ExtendedMCPTestFailure;-export interface MCPOAuthStartResponse {- ok: boolean;- job_id?: string | null;- authorization_url?: string | null;- error?: string | null;- error_kind?: MCPTestFailureKind | null;-}--export interface MCPOAuthStatusResponse {- ok: boolean;- status: "pending" | "authorizing" | "succeeded" | "failed";- job_id: string;- authorization_url?: string | null;- callback_ready?: boolean;- tools?: string[] | null;- tool_result?: MCPTestToolResult | null;+export type MCPOAuthStartResponse = AgentServerMCPStartOAuthResponse;+export type MCPOAuthStatusResponse = Omit<+ AgentServerMCPOAuthStatusResponse,+ "oauth_state"+> & {oauth_state?: MCPOAuthState | null;- error?: string | null;- error_kind?: MCPTestFailureKind | null;-}+};diff --git a/src/types/settings.ts b/src/types/settings.tsindex 286829f6ee..d4b3d574b5 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -1,5 +1,6 @@+import type { MCPConfig } from "@openhands/typescript-client";+export type { MCPConfig } from "@openhands/typescript-client";import type { SkillCategoryId } from "@openhands/extensions/skills";-import type { MCPAuthCredential } from "./mcp-auth";export const ProviderOptions = {github: "github",@@ -17,37 +18,6 @@ export type ProviderToken = {host: string | null;};-export type MCPSSEServer = {- name?: string;- url: string;- headers?: Record<string, string>;- auth?: MCPAuthCredential;- enabled?: boolean;-};--export type MCPStdioServer = {- name: string;- command: string;- args?: string[];- env?: Record<string, string>;- enabled?: boolean;-};--export type MCPSHTTPServer = {- name?: string;- url: string;- headers?: Record<string, string>;- timeout?: number;- auth?: MCPAuthCredential;- enabled?: boolean;-};--export type MCPConfig = {- sse_servers: (string | MCPSSEServer)[];- stdio_servers: MCPStdioServer[];- shttp_servers: (string | MCPSHTTPServer)[];-};-export type SettingsChoiceValue = boolean | number | string;export type SettingsChoice = {diff --git a/src/utils/mcp-config.ts b/src/utils/mcp-config.tsindex ee1034d621..1880dd8ff5 100644--- a/src/utils/mcp-config.ts+++ b/src/utils/mcp-config.ts@@ -1,49 +1,18 @@-import {- MCPConfig,- MCPSSEServer,- MCPSHTTPServer,- MCPStdioServer,- SettingsValue,-} from "#/types/settings";import type {MCPAuthCredential,- MCPAuthenticationConfig,- MCPJsonValue,- MCPOAuthState,-} from "#/types/mcp-auth";+ MCPConfig,+ MCPConfigPatch,+ MCPServer,+ MCPServerPatch,+} from "@openhands/typescript-client";+import { isMcpAuthCredential } from "#/types/mcp-auth";import type { MCPServerConfig } from "#/types/mcp-server";import { toMcpServerName } from "#/utils/mcp-server-name";-const EMPTY_MCP_CONFIG: MCPConfig = {- sse_servers: [],- stdio_servers: [],- shttp_servers: [],-};-export const REDACTED_MCP_SECRET_VALUE = "**********";-type SdkMcpServerConfig = Record<string, SettingsValue | MCPAuthCredential>;-type SdkMcpConfig = Record<string, SdkMcpServerConfig>;--/**- * The dict key for an SSE/SHTTP server doubles as its display name once a- * user provides one. Keys that match the auto-generated fallback pattern- * (``sse``, ``shttp``, ``shttp_1``, β¦) emitted by {@link toSdkMcpConfig}- * carry no user intent, so we surface them as "no name" β re-serializing- * regenerates the identical fallback key and existing configs are left- * untouched.- */-function userGivenServerName(- serverName: string,- base: "sse" | "shttp",-): string | undefined {- const autoGenerated = new RegExp(`^${base}(_\\d+)?$`);- return autoGenerated.test(serverName) ? undefined : serverName;-}--function isRecord(value: unknown): value is Record<string, unknown> {- return !!value && typeof value === "object" && !Array.isArray(value);-}+const isRecord = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === "object" && !Array.isArray(value);export function getSdkMcpServerMap(value: unknown,@@ -75,326 +44,397 @@ export function stringRecord(export function hasRedactedMcpSecretLeaf(value: unknown): boolean {if (value === REDACTED_MCP_SECRET_VALUE) return true;if (Array.isArray(value)) return value.some(hasRedactedMcpSecretLeaf);- if (isRecord(value))+ if (isRecord(value)) {return Object.values(value).some(hasRedactedMcpSecretLeaf);+ }return false;}-function getOAuthState(value: unknown): MCPOAuthState | undefined {- if (!isRecord(value)) return undefined;- const state: MCPOAuthState = {};- if (isRecord(value.tokens)) {- state.tokens = value.tokens as NonNullable<MCPOAuthState["tokens"]>;- }- if (isRecord(value.client_info)) {- state.client_info = value.client_info as NonNullable<- MCPOAuthState["client_info"]- >;+// Agent Server persists this optional field, but typescript-client 1.36.1+// does not yet expose it in its generated MCP model types.+export const getMcpServerEnabled = (server: MCPServer): boolean | undefined =>+ (server as MCPServer & { enabled?: unknown }).enabled === false+ ? false+ : undefined;++const normalizeTransport = (+ value: unknown,+): MCPServer["transport"] | undefined => {+ if (value === "stdio" || value === "sse" || value === "streamable-http") {+ return value;}- if (- typeof value.token_expires_at === "number" ||- value.token_expires_at === null- ) {- state.token_expires_at = value.token_expires_at;+ if (value === "http" || value === "shttp" || value === undefined) {+ return "http";}- return Object.keys(state).length > 0 ? state : undefined;-}+ return undefined;+};-function normalizeTaggedAuthCredential(- value: unknown,-): MCPAuthCredential | undefined {- if (!isRecord(value)) return undefined;- switch (value.strategy) {- case "none":- return { strategy: "none" };- case "api_key":- if (typeof value.value !== "string") return undefined;- return {- strategy: "api_key",- value: value.value,- ...(typeof value.header_name === "string" && {- header_name: value.header_name,+/**+ * Normalize the SDK and legacy cloud wrapper shapes into the client-owned,+ * name-keyed MCPConfig. The map key remains the server's persistence identity.+ */+// @spec MCP-003 β Settings map keys are stable MCP identities+export function parseMcpConfig(value: unknown): MCPConfig {+ const serverMap = getSdkMcpServerMap(value);+ if (!serverMap) return {};++ const config: MCPConfig = {};+ for (const [settingsKey, candidate] of Object.entries(serverMap)) {+ if (!isRecord(candidate)) continue;++ if (typeof candidate.command === "string") {+ config[settingsKey] = {+ transport: "stdio",+ command: candidate.command,+ ...(Array.isArray(candidate.args) &&+ candidate.args.every((arg) => typeof arg === "string") && {+ args: candidate.args as string[],+ }),+ ...(stringRecord(candidate.env) && {+ env: stringRecord(candidate.env),}),+ ...(typeof candidate.cwd === "string" && { cwd: candidate.cwd }),+ ...(typeof candidate.description === "string" && {+ description: candidate.description,+ }),+ ...(typeof candidate.icon === "string" && { icon: candidate.icon }),+ ...(typeof candidate.timeout === "number" && {+ timeout: candidate.timeout,+ }),+ ...(candidate.enabled === false && { enabled: false }),};- case "bearer":- if (typeof value.value !== "string") return undefined;- return { strategy: "bearer", value: value.value };- case "basic":- if (- typeof value.username !== "string" ||- typeof value.password !== "string"- ) {- return undefined;- }- return {- strategy: "basic",- username: value.username,- password: value.password,- };- case "header": {- const headers = stringRecord(value.headers);- return headers ? { strategy: "header", headers } : undefined;- }- case "oauth2": {- const authentication = getAuthenticationConfig(value.authentication);- const state = getOAuthState(value.state);- return {- strategy: "oauth2",- ...(authentication && { authentication }),- ...(state && { state }),- };+ continue;}- default:- return undefined;- }-}-function authCredentialFromServerConfig(- serverConfig: Record<string, unknown>,-): MCPAuthCredential | undefined {- return normalizeTaggedAuthCredential(serverConfig.auth);-}--function getRemoteSecretFields(entry: {- auth?: MCPAuthCredential;- headers?: Record<string, string>;-}): Partial<SdkMcpServerConfig> {- const fields: Partial<SdkMcpServerConfig> = {};- if (entry.auth && !hasRedactedMcpSecretLeaf(entry.auth)) {- fields.auth = entry.auth;- }- if (entry.headers && Object.keys(entry.headers).length > 0) {- fields.headers = entry.headers;+ if (typeof candidate.url !== "string") continue;+ const transport = normalizeTransport(candidate.transport);+ if (!transport || transport === "stdio") continue;+ config[settingsKey] = {+ transport,+ url: candidate.url,+ ...(stringRecord(candidate.headers) && {+ headers: stringRecord(candidate.headers),+ }),+ ...(isMcpAuthCredential(candidate.auth) && {+ auth: candidate.auth,+ }),+ ...(typeof candidate.description === "string" && {+ description: candidate.description,+ }),+ ...(typeof candidate.icon === "string" && { icon: candidate.icon }),+ ...(typeof candidate.timeout === "number" && {+ timeout: candidate.timeout,+ }),+ ...(typeof candidate.sse_read_timeout === "number" && {+ sse_read_timeout: candidate.sse_read_timeout,+ }),+ ...(typeof candidate.keep_alive === "boolean" && {+ keep_alive: candidate.keep_alive,+ }),+ ...(candidate.enabled === false && { enabled: false }),+ };}- return fields;+ return config;}-/**- * Only an explicit ``false`` is carried. Every mutation round-trips the whole- * server map through these converters, so preserving the flag here is what- * stops adding or deleting one server from silently re-enabling another.- */-function disabledField(server: { enabled?: boolean }) {- return server.enabled === false ? { enabled: false as const } : {};-}+export function toCanonicalMcpServer(server: MCPServerConfig): MCPServer {+ if (server.type === "stdio") {+ return {+ transport: "stdio",+ command: server.command!,+ ...(server.args?.length ? { args: server.args } : {}),+ ...(server.env && Object.keys(server.env).length > 0+ ? { env: server.env }+ : {}),+ ...(server.enabled === false && { enabled: false }),+ };+ }-function getRemoteServerFields(server: MCPServerConfig) {return {- ...(server.name && { name: server.name }),+ transport: server.type === "sse" ? "sse" : "http",url: server.url!,- ...(server.headers && { headers: server.headers }),- ...(server.auth && { auth: server.auth }),- ...disabledField(server),+ ...(server.headers && Object.keys(server.headers).length > 0+ ? { headers: server.headers }+ : {}),+ ...(server.auth ? { auth: server.auth } : {}),+ ...(server.type === "shttp" && server.timeout !== undefined+ ? { timeout: server.timeout }+ : {}),+ ...(server.enabled === false && { enabled: false }),};}-export function toMcpSseServer(server: MCPServerConfig): MCPSSEServer {- return getRemoteServerFields(server);-}--export function toMcpShttpServer(server: MCPServerConfig): MCPSHTTPServer {- return {- ...getRemoteServerFields(server),- ...(server.timeout !== undefined && { timeout: server.timeout }),- };-}+const buildEnabledPatch = (+ previous: MCPServer,+ edited: MCPServerConfig,+): MCPServerPatch => {+ if (edited.enabled === false) return { enabled: false } as MCPServerPatch;+ return getMcpServerEnabled(previous) === false+ ? ({ enabled: true } as MCPServerPatch)+ : {};+};-export function toMcpStdioServer(server: MCPServerConfig): MCPStdioServer {- return {- name: server.name!,- command: server.command!,- ...(server.args && { args: server.args }),- ...(server.env && { env: server.env }),- ...disabledField(server),- };-}+const buildStringMapPatch = (+ previous: Record<string, string> | null | undefined,+ next: Record<string, string> | undefined,+): Record<string, string | null> | null | undefined => {+ if (!next) return previous ? null : undefined;-function getAuthenticationConfig(- value: unknown,-): MCPAuthenticationConfig | undefined {- if (!value || typeof value !== "object") return undefined;- const record = value as Record<string, unknown>;- if (record.type !== "oauth") return undefined;- const authentication: MCPAuthenticationConfig = { type: "oauth" };- if (- record.client_auth_method === "none" ||- record.client_auth_method === "client_secret_post" ||- record.client_auth_method === "client_secret_basic" ||- record.client_auth_method === "private_key_jwt"- ) {- authentication.client_auth_method = record.client_auth_method;- }- if (typeof record.scopes === "string") {- authentication.scopes = record.scopes;- } else if (- Array.isArray(record.scopes) &&- record.scopes.every((scope) => typeof scope === "string")- ) {- authentication.scopes = record.scopes;+ const patch: Record<string, string | null> = {};+ for (const [key, value] of Object.entries(next)) {+ if (value !== REDACTED_MCP_SECRET_VALUE) {+ patch[key] = value;+ }}- if (typeof record.client_name === "string") {- authentication.client_name = record.client_name;+ for (const key of Object.keys(previous ?? {})) {+ if (!(key in next)) patch[key] = null;}- if (typeof record.client_metadata_url === "string") {- authentication.client_metadata_url = record.client_metadata_url;+ return Object.keys(patch).length > 0 ? patch : undefined;+};++type OAuthCredential = Extract<MCPAuthCredential, { strategy: "oauth2" }>;+type OAuthCredentialPatch = Extract<+ NonNullable<MCPServerPatch["auth"]>,+ { strategy: "oauth2" }+>;+const OAUTH_EDITABLE_AUTHENTICATION_FIELDS = [+ "client_auth_method",+ "scopes",+ "client_id",+ "client_secret",+] as const;++const buildRedactionSafeNestedPatch = (+ previous: unknown,+ next: unknown,+): unknown | undefined => {+ if (next === REDACTED_MCP_SECRET_VALUE || next === undefined) {+ return undefined;}- if (typeof record.client_id === "string") {- authentication.client_id = record.client_id;+ if (next === null) return null;+ if (Array.isArray(next)) {+ if (hasRedactedMcpSecretLeaf(next)) return undefined;+ return JSON.stringify(previous) === JSON.stringify(next) ? undefined : next;}- if (typeof record.client_secret === "string") {- authentication.client_secret = record.client_secret;+ if (!isRecord(next)) {+ return Object.is(previous, next) ? undefined : next;}- if (- record.additional_client_metadata &&- typeof record.additional_client_metadata === "object" &&- !Array.isArray(record.additional_client_metadata)- ) {- authentication.additional_client_metadata =- record.additional_client_metadata as Record<string, MCPJsonValue>;- }- return authentication;-}-/**- * Parse the SDK-native ``agent_settings.mcp_config`` value and convert it- * to the frontend MCPConfig format used by UI components.- */-export function parseMcpConfig(value: unknown): MCPConfig {- const mcpConfig = getSdkMcpServerMap(value);- if (!mcpConfig) {- return { ...EMPTY_MCP_CONFIG };+ const previousRecord = isRecord(previous) ? previous : {};+ const patch: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(next)) {+ const nestedPatch = buildRedactionSafeNestedPatch(+ previousRecord[key],+ value,+ );+ if (nestedPatch !== undefined) patch[key] = nestedPatch;}+ return Object.keys(patch).length > 0 ? patch : undefined;+};- const sseServers: (string | MCPSSEServer)[] = [];- const stdioServers: MCPStdioServer[] = [];- const shttpServers: (string | MCPSHTTPServer)[] = [];-- for (const [serverName, serverConfig] of Object.entries(mcpConfig)) {- if (!isRecord(serverConfig)) continue;-- const url = serverConfig.url as string | undefined;-- // The SDK omits ``enabled`` while it holds its default (true), so only an- // explicit ``false`` marks a server as switched off.- const disabled = serverConfig.enabled === false;+const buildOAuthAuthenticationPatch = (+ previous: OAuthCredential["authentication"],+ edited: OAuthCredential["authentication"],+): OAuthCredentialPatch["authentication"] | undefined => {+ if (edited === undefined) return undefined;+ if (edited === null) return null;++ const nestedPatch = buildRedactionSafeNestedPatch(previous, edited);+ const patch = isRecord(nestedPatch) ? { ...nestedPatch } : {};+ const previousRecord = isRecord(previous) ? previous : {};+ for (const key of OAUTH_EDITABLE_AUTHENTICATION_FIELDS) {+ if (key in previousRecord && !(key in edited)) patch[key] = null;+ }+ if (Object.keys(patch).length === 0) return undefined;+ return { type: "oauth", ...patch } as NonNullable<+ OAuthCredentialPatch["authentication"]+ >;+};- if (url) {- const transport = serverConfig.transport as string | undefined;- const auth = authCredentialFromServerConfig(serverConfig);- const headers = stringRecord(serverConfig.headers);+const withAuthStrategyReplacementDeletes = <T extends MCPAuthCredential>(+ previous: MCPAuthCredential | null | undefined,+ patch: T,+): T => {+ if (!previous || previous.strategy === patch.strategy) return patch;- if (transport === "sse") {- const name = userGivenServerName(serverName, "sse");- const server: MCPSSEServer = { url };- if (name) server.name = name;- if (auth) server.auth = auth;- if (headers) server.headers = headers;- if (disabled) server.enabled = false;- sseServers.push(server);- } else {- const name = userGivenServerName(serverName, "shttp");- const server: MCPSHTTPServer = { url };- if (name) server.name = name;- if (serverConfig.timeout != null) {- server.timeout = serverConfig.timeout as number;- }- if (auth) server.auth = auth;- if (headers) server.headers = headers;- if (disabled) server.enabled = false;- shttpServers.push(server);- }- } else {- if (typeof serverConfig.command !== "string") continue;- const stdioServer: MCPStdioServer = {- name: serverName,- command: serverConfig.command,- };- if (serverConfig.args) {- stdioServer.args = serverConfig.args as string[];- }- if (serverConfig.env) {- stdioServer.env = serverConfig.env as Record<string, string>;- }- if (disabled) stdioServer.enabled = false;- stdioServers.push(stdioServer);+ const replacement = { ...patch } as Record<string, unknown>;+ for (const key of Object.keys(previous)) {+ if (key !== "strategy" && !(key in replacement)) {+ replacement[key] = null;}}+ return replacement as T;+};+type HeaderAuthCredential = Extract<MCPAuthCredential, { strategy: "header" }>;++export const MCP_HEADER_REMOVAL_ERROR =+ "Removing an individual header from header authentication is not supported yet. Replace the credential or clear authentication, then re-enter the headers you want to keep.";++const buildHeaderAuthCredentialPatch = (+ previous: MCPAuthCredential | null | undefined,+ edited: HeaderAuthCredential,+): NonNullable<MCPServerPatch["auth"]> | undefined => {+ const previousHeaders =+ previous?.strategy === "header" ? previous.headers : undefined;+ const headersPatch = buildStringMapPatch(previousHeaders, edited.headers);+ if (!headersPatch) return undefined;+ if (Object.values(headersPatch).some((value) => value === null)) {+ throw new Error(MCP_HEADER_REMOVAL_ERROR);+ }return {- sse_servers: sseServers,- stdio_servers: stdioServers,- shttp_servers: shttpServers,+ strategy: "header",+ headers: headersPatch as Record<string, string>,};-}+};++const buildOAuthCredentialPatch = (+ previous: MCPAuthCredential | null | undefined,+ edited: OAuthCredential,+): OAuthCredentialPatch | undefined => {+ const previousOAuth = previous?.strategy === "oauth2" ? previous : undefined;+ const authentication = buildOAuthAuthenticationPatch(+ previousOAuth?.authentication,+ edited.authentication,+ );+ const state = buildRedactionSafeNestedPatch(+ previousOAuth?.state,+ edited.state,+ );+ if (previousOAuth && authentication === undefined && state === undefined) {+ return undefined;+ }+ return withAuthStrategyReplacementDeletes(previous, {+ strategy: "oauth2",+ ...(authentication !== undefined && { authentication }),+ ...(state !== undefined && { state }),+ } as OAuthCredentialPatch);+};/**- * Convert the frontend MCPConfig format back to the SDK-native server map- * expected by agent_settings.mcp_config on the backend.- *- * Names are only suffixed (``_1``, ``_2``, β¦) when an earlier entry has- * already claimed the bare base name. We intentionally do NOT use a single- * monotonic counter across server types: that would, for example, rename a- * stdio server "myname" to "myname_1" the moment any sse/shttp entry is- * persisted ahead of it, and shift the suffix on every save as the count- * of other server types changes. With per-base collision suffixing,- * unrelated entries keep their human-meaningful names stable across edits.- *- * ``enabled`` is only emitted when a server is switched off β the SDK defaults- * it to true. Omitting it is what *clears* a previously persisted- * ``enabled: false``, and that only works because ``saveSettings`` pre-clears- * ``mcp_config`` to null before every write (see- * ``settings-service.api.ts``), turning the backend's RFC 7386 merge into a- * full replace. If that pre-clear is ever removed, re-enabling a server- * becomes a silent no-op.+ * Build one sparse MCP server merge-patch from an editor result. Redacted+ * values are display-only and are never mutation inputs.*/-export function toSdkMcpConfig(config: MCPConfig): SdkMcpConfig | null {- const mcpConfig: SdkMcpConfig = {};-- const reserve = (base: string): string => {- const safeBase = toMcpServerName(base);- if (!(safeBase in mcpConfig)) return safeBase;- let i = 1;- while (`${safeBase}_${i}` in mcpConfig) i += 1;- return `${safeBase}_${i}`;+// @spec MCP-002 β Secret patches preserve user intent+export function buildMcpServerPatch(+ previous: MCPServer,+ edited: MCPServerConfig,+): MCPServerPatch {+ const enabled = buildEnabledPatch(previous, edited);+ if (edited.type === "stdio") {+ const env = buildStringMapPatch(+ previous.transport === "stdio" ? previous.env : undefined,+ edited.env,+ );+ return {+ transport: "stdio",+ command: edited.command!,+ ...(edited.args?.length+ ? { args: edited.args }+ : previous.transport === "stdio" && previous.args+ ? { args: null }+ : {}),+ ...(env !== undefined ? { env } : {}),+ ...enabled,+ };+ }++ const previousRemote = previous.transport === "stdio" ? undefined : previous;+ const patch: MCPServerPatch = {+ transport: edited.type === "sse" ? "sse" : "http",+ url: edited.url!,+ ...enabled,};- for (const entry of config.sse_servers) {- const server: SdkMcpServerConfig = {};- let name: string | undefined;- if (typeof entry === "string") {- server.url = entry;- } else {- name = entry.name;- server.url = entry.url;- Object.assign(server, getRemoteSecretFields(entry), disabledField(entry));- }- server.transport = "sse";- mcpConfig[reserve(name || "sse")] = server;+ if (edited.type === "shttp") {+ if (edited.timeout !== undefined) patch.timeout = edited.timeout;+ else if (previousRemote?.timeout !== undefined) patch.timeout = null;}- for (const entry of config.shttp_servers) {- const server: SdkMcpServerConfig = { transport: "http" };- let name: string | undefined;- if (typeof entry === "string") {- server.url = entry;- } else {- name = entry.name;- server.url = entry.url;- Object.assign(server, getRemoteSecretFields(entry), disabledField(entry));- if (entry.timeout != null) server.timeout = entry.timeout;+ if (edited.auth) {+ if (edited.auth.strategy === "oauth2") {+ const auth = buildOAuthCredentialPatch(previousRemote?.auth, edited.auth);+ if (auth !== undefined) patch.auth = auth;+ } else if (+ edited.auth.strategy === "header" &&+ previousRemote?.auth?.strategy === "header"+ ) {+ const auth = buildHeaderAuthCredentialPatch(+ previousRemote.auth,+ edited.auth,+ );+ if (auth !== undefined) patch.auth = auth;+ } else if (!hasRedactedMcpSecretLeaf(edited.auth)) {+ patch.auth = withAuthStrategyReplacementDeletes(+ previousRemote?.auth,+ edited.auth,+ );}- mcpConfig[reserve(name || "shttp")] = server;+ } else if (previousRemote?.auth) {+ patch.auth = null;}- for (const entry of config.stdio_servers) {- const server: SdkMcpServerConfig = {- command: entry.command,- };- if (entry.args) server.args = entry.args;- if (entry.env) server.env = entry.env;- Object.assign(server, disabledField(entry));- mcpConfig[reserve(entry.name || "stdio")] = server;+ return patch;+}++const applyMcpServerPatch = (+ previous: MCPServer,+ patch: MCPServerPatch,+): MCPServer => {+ const apply = (base: unknown, next: unknown): Record<string, unknown> => {+ const merged = isRecord(base) ? { ...base } : {};+ if (!isRecord(next)) return merged;++ for (const [key, value] of Object.entries(next)) {+ if (value === null) {+ delete merged[key];+ } else if (isRecord(value)) {+ merged[key] = apply(merged[key], value);+ } else {+ merged[key] = value;+ }+ }+ return merged;+ };++ return apply(previous, patch) as MCPServer;+};++export const MCP_RENAME_CREDENTIAL_ERROR =+ "Replace or clear the stored credential before renaming this MCP server.";++// @spec MCP-003 β Settings map keys are stable MCP identities+export function buildRenameMcpConfigPatch(+ oldKey: string,+ newKey: string,+ previous: MCPServer,+ edited: MCPServerConfig,+): MCPConfigPatch {+ const previousSecrets =+ previous.transport === "stdio"+ ? previous.env+ : { auth: previous.auth, headers: previous.headers };+ if (hasRedactedMcpSecretLeaf(previousSecrets)) {+ throw new Error(MCP_RENAME_CREDENTIAL_ERROR);}+ const renamedServer = applyMcpServerPatch(+ previous,+ buildMcpServerPatch(previous, edited),+ );+ return {+ [oldKey]: null,+ [newKey]: renamedServer,+ };+}- return Object.keys(mcpConfig).length > 0 ? mcpConfig : null;+export function allocateMcpSettingsKey(+ config: MCPConfig,+ preferredName: string | undefined,+ fallback: "sse" | "shttp" | "stdio",+): string {+ const base = toMcpServerName(preferredName || fallback);+ if (!(base in config)) return base;+ let suffix = 1;+ while (`${base}_${suffix}` in config) suffix += 1;+ return `${base}_${suffix}`;}diff --git a/src/utils/mcp-installed-servers.ts b/src/utils/mcp-installed-servers.tsindex 0cdfb2a700..bcee63ba66 100644--- a/src/utils/mcp-installed-servers.ts+++ b/src/utils/mcp-installed-servers.ts@@ -1,35 +1,28 @@-import { MCPServerConfig } from "#/types/mcp-server";-import { MCPConfig } from "#/types/settings";+import type { MCPConfig } from "@openhands/typescript-client";+import type { MCPServerConfig } from "#/types/mcp-server";+import { getMcpServerEnabled } from "./mcp-config";export function flattenMcpConfig(config: MCPConfig): MCPServerConfig[] {- return [- ...config.sse_servers.map((server, index) => ({- id: `sse-${index}`,- type: "sse" as const,- name: typeof server === "object" ? server.name : undefined,- url: typeof server === "string" ? server : server.url,- headers: typeof server === "object" ? server.headers : undefined,- auth: typeof server === "object" ? server.auth : undefined,- enabled: typeof server === "object" ? server.enabled : undefined,- })),- ...config.stdio_servers.map((server, index) => ({- id: `stdio-${index}`,- type: "stdio" as const,- name: server.name,- command: server.command,- args: server.args,- env: server.env,- enabled: server.enabled,- })),- ...config.shttp_servers.map((server, index) => ({- id: `shttp-${index}`,- type: "shttp" as const,- name: typeof server === "object" ? server.name : undefined,- url: typeof server === "string" ? server : server.url,- headers: typeof server === "object" ? server.headers : undefined,- timeout: typeof server === "object" ? server.timeout : undefined,- auth: typeof server === "object" ? server.auth : undefined,- enabled: typeof server === "object" ? server.enabled : undefined,- })),- ];+ return Object.entries(config).map(([settingsKey, server]) =>+ server.transport === "stdio"+ ? {+ id: settingsKey,+ type: "stdio",+ name: settingsKey,+ command: server.command,+ args: server.args ?? undefined,+ env: server.env ?? undefined,+ enabled: getMcpServerEnabled(server),+ }+ : {+ id: settingsKey,+ type: server.transport === "sse" ? "sse" : "shttp",+ name: settingsKey,+ url: server.url,+ headers: server.headers ?? undefined,+ timeout: server.timeout ?? undefined,+ auth: server.auth ?? undefined,+ enabled: getMcpServerEnabled(server),+ },+ );}diff --git a/src/utils/mcp-server-health-key.ts b/src/utils/mcp-server-health-key.tsindex c8e78da926..be224dfdeb 100644--- a/src/utils/mcp-server-health-key.ts+++ b/src/utils/mcp-server-health-key.ts@@ -7,10 +7,8 @@ const sortedKeys = (record?: Record<string, string> | null): string[] =>* Stable identity for a server's health entry.** Built from the server's structural, non-secret fields. Names are included- * because persisted configs are keyed by name (`toSdkMcpConfig` suffixes- * duplicates `github` β `github_1`), which makes the key unique per stored- * server and stable across list reordering β unlike the positional- * `sse-0`/`stdio-1` ids from `flattenMcpConfig`. Secret VALUES are excluded:+ * because persisted configs are keyed by name, which makes the key unique per+ * stored server and stable across list reordering. Secret VALUES are excluded:* the same credential legitimately appears as plaintext at install time,* `**********` in redacted settings, and ciphertext in test requests, so any* of them would make the key flap. A structural edit (URL, command, headerdiff --git a/tests/e2e/mock-llm/mcp/mock-llm-mcp-github.spec.ts b/tests/e2e/mock-llm/mcp/mock-llm-mcp-github.spec.tsindex 76437def88..282775eef7 100644--- a/tests/e2e/mock-llm/mcp/mock-llm-mcp-github.spec.ts+++ b/tests/e2e/mock-llm/mcp/mock-llm-mcp-github.spec.ts@@ -233,4 +233,130 @@ test.describe("MCP GitHub server install flow", () => {const githubStillPresent = mcpConfig?.github != null;expect(githubStillPresent).toBe(false);});++ // @spec MCP-001 β Sparse mutations preserve sibling servers+ test("regression: sibling create, edit, and delete preserve GitHub credentials with one MCP request each", async ({+ page,+ }) => {+ test.setTimeout(120_000);+ await ensureMockLLMProfile(page);+ const installResp = await page.request.patch(+ `${BACKEND_URL}/api/settings`,+ {+ headers: {+ "X-Session-API-Key": SESSION_API_KEY,+ "Content-Type": "application/json",+ },+ data: {+ agent_settings_diff: {+ mcp_config: {+ github: {+ transport: "http",+ url: GITHUB_HOSTED_MCP_URL,+ auth: { strategy: "api_key", value: FAKE_PAT },+ },+ },+ },+ },+ },+ );+ expect(installResp.ok()).toBe(true);++ await routeSessionApiKey(page);+ const mcpTestBodies: Array<Record<string, unknown>> = [];+ await page.route("**/api/mcp/test", async (route) => {+ mcpTestBodies.push(route.request().postDataJSON());+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ ok: true,+ tools: ["get_me"],+ tool_result: { is_error: false, text: '{"login":"octocat"}' },+ }),+ });+ });++ const mutationRequests: Array<{+ method: string;+ pathname: string;+ body?: Record<string, unknown>;+ }> = [];+ page.on("request", (request) => {+ const pathname = new URL(request.url()).pathname;+ if (pathname.startsWith("/api/settings/mcp/")) {+ mutationRequests.push({+ method: request.method(),+ pathname,+ ...(request.postData() ? { body: request.postDataJSON() } : {}),+ });+ }+ });++ await page.goto("/mcp", { waitUntil: "domcontentloaded" });+ await dismissAnalyticsModal(page);+ await expect(page.getByTestId("mcp-installed-list")).toBeVisible({+ timeout: 10_000,+ });++ const verifyStoredGitHubCredential = async () => {+ const before = mcpTestBodies.length;+ await page.locator('[data-server-id="github"]').press("Enter");+ await expect(page.getByTestId("mcp-custom-editor")).toBeVisible();+ await page.getByTestId("mcp-test-connection").click();+ await expect(page.getByTestId("mcp-test-message")).toBeVisible();+ expect(mcpTestBodies).toHaveLength(before + 1);+ const request = mcpTestBodies.at(-1) as {+ name?: string;+ server?: {+ type?: string;+ auth?: { strategy?: string; value?: string };+ };+ };+ expect(request.name).toBe("github");+ expect(request.server).toMatchObject({+ type: "http",+ auth: { strategy: "api_key" },+ });+ expect(request.server?.auth?.value).toBeTruthy();+ expect(request.server?.auth?.value).not.toBe("**********");+ expect(request.server?.auth?.value).not.toBe(FAKE_PAT);+ await page.getByTestId("mcp-custom-editor-close").click();+ await expect(page.getByTestId("mcp-custom-editor")).not.toBeVisible();+ };++ await page.getByTestId("mcp-add-custom-server").click();+ await page.getByTestId("server-name-input").fill("docs");+ await page.getByTestId("url-input").fill("https://docs.example/mcp");+ await page.getByTestId("submit-button").click();+ await expect(page.getByTestId("mcp-custom-editor")).not.toBeVisible();+ await page.locator('[data-server-id="docs"]').press("Enter");+ await page.getByTestId("url-input").fill("https://docs.example/v2/mcp");+ await page.getByTestId("submit-button").click();+ await expect(page.getByTestId("mcp-custom-editor")).not.toBeVisible();+ await page.locator('[data-server-id="docs"]').press("Enter");+ await page.getByTestId("mcp-custom-editor-delete").click();+ await page.getByTestId("confirm-button").click();+ await expect(page.locator('[data-server-id="docs"]')).not.toBeVisible();+ expect(mutationRequests.map(({ method, pathname }) => `${method} ${pathname}`)).toEqual([+ "POST /api/settings/mcp/docs",+ "PATCH /api/settings/mcp/docs",+ "DELETE /api/settings/mcp/docs",+ ]);+ expect(JSON.stringify(mutationRequests)).not.toContain("github");+ await verifyStoredGitHubCredential();++ const settingsResp = await page.request.get(`${BACKEND_URL}/api/settings`, {+ headers: { "X-Session-API-Key": SESSION_API_KEY },+ });+ expect(settingsResp.ok()).toBe(true);+ const settings = await settingsResp.json();+ expect(settings.agent_settings.mcp_config).toMatchObject({+ github: {+ url: GITHUB_HOSTED_MCP_URL,+ auth: { strategy: "api_key", value: "**********" },+ },+ });+ expect(settings.agent_settings.mcp_config.docs).toBeUndefined();+ });});