Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: preserve sibling MCP servers when saving to a cloud backend (#17467)

Hiep Le486bb7bd3be9
diff --git a/__tests__/api/settings-service.test.ts b/__tests__/api/settings-service.test.ts
index 85364c2d55..bf9b9663ef 100644
--- a/__tests__/api/settings-service.test.ts
+++ b/__tests__/api/settings-service.test.ts
@@ -656,13 +656,30 @@ describe("SettingsService", () => {
setRegisteredBackends([cloudBackend]);
setActiveSelection({ backendId: cloudBackend.id });
+ mockFetchCloudSettings.mockResolvedValue({
+ agent_settings: {
+ mcp_config: {
+ github: {
+ url: "https://github.example/mcp",
+ headers: { Authorization: "**********" },
+ },
+ },
+ },
+ });
+
await SettingsService.patchMcpServer("github", { auth: null });
expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);
+ // `auth: null` is explicit: an omitted `auth` makes the cloud restore the
+ // stored credential next to the cleared headers.
expect(mockSaveCloudSettings).toHaveBeenCalledWith({
agent_settings_diff: {
mcp_config: {
- github: { headers: null },
+ github: {
+ url: "https://github.example/mcp",
+ headers: null,
+ auth: null,
+ },
},
},
});
@@ -673,10 +690,12 @@ describe("SettingsService", () => {
setActiveSelection({ backendId: cloudBackend.id });
mockFetchCloudSettings.mockResolvedValue({
- mcp_config: {
- github: {
- url: "https://github.example/mcp",
- headers: { "X-API-Key": "stale-custom-header-secret" },
+ agent_settings: {
+ mcp_config: {
+ github: {
+ url: "https://github.example/mcp",
+ headers: { "X-API-Key": "stale-custom-header-secret" },
+ },
},
},
});
@@ -685,15 +704,17 @@ describe("SettingsService", () => {
auth: { strategy: "bearer", value: "new-bearer-token" },
});
+ expect(mockFetchCloudSettings).toHaveBeenCalledTimes(1);
expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);
+ // The stale header tombstone is resolved client-side: the cloud replaces
+ // the catalog for this map and rejects `null` header values.
expect(mockSaveCloudSettings).toHaveBeenCalledWith({
agent_settings_diff: {
mcp_config: {
github: {
- headers: {
- Authorization: "Bearer new-bearer-token",
- "X-API-Key": null,
- },
+ url: "https://github.example/mcp",
+ headers: { Authorization: "Bearer new-bearer-token" },
+ auth: null,
},
},
},
@@ -705,12 +726,14 @@ describe("SettingsService", () => {
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",
+ agent_settings: {
+ mcp_config: {
+ github: {
+ url: "https://github.example/mcp",
+ headers: {
+ "X-API-Key": "stale-custom-header-secret",
+ "X-Trace": "on",
+ },
},
},
},
@@ -726,29 +749,135 @@ describe("SettingsService", () => {
agent_settings_diff: {
mcp_config: {
github: {
+ url: "https://github.example/mcp",
headers: {
- Authorization: "Bearer new-bearer-token",
"X-Trace": "on",
- "X-API-Key": null,
+ Authorization: "Bearer new-bearer-token",
},
+ auth: null,
},
},
},
});
});
- it("does not fetch stored cloud settings for a patch with no auth credential", async () => {
+ it("resends the stored cloud catalog when adding a server so siblings survive", async () => {
+ // OHE-3248: the cloud replaces the whole catalog for an `mcp_config` map
+ // without a `null` entry, so a one-key add would erase every other server.
setRegisteredBackends([cloudBackend]);
setActiveSelection({ backendId: cloudBackend.id });
+ mockFetchCloudSettings.mockResolvedValue({
+ agent_settings: {
+ mcp_config: {
+ github: {
+ url: "https://github.example/mcp",
+ headers: { Authorization: "**********" },
+ },
+ },
+ },
+ });
+
await SettingsService.patchMcpConfig({
only: { url: "https://x.example" },
});
- expect(mockFetchCloudSettings).not.toHaveBeenCalled();
+ expect(mockFetchCloudSettings).toHaveBeenCalledTimes(1);
+ // The untouched sibling is resent verbatim, redaction included: the cloud
+ // restores its secret by key.
expect(mockSaveCloudSettings).toHaveBeenCalledWith({
agent_settings_diff: {
- mcp_config: { only: { url: "https://x.example" } },
+ mcp_config: {
+ github: {
+ url: "https://github.example/mcp",
+ headers: { Authorization: "**********" },
+ },
+ only: { url: "https://x.example" },
+ },
+ },
+ });
+ });
+
+ it("merges a sparse cloud update onto the stored server and keeps its siblings", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+
+ mockFetchCloudSettings.mockResolvedValue({
+ agent_settings: {
+ mcp_config: {
+ github: {
+ url: "https://github.example/mcp",
+ auth: { strategy: "bearer", value: "**********" },
+ },
+ linear: {
+ url: "https://mcp.linear.app/mcp",
+ auth: { strategy: "bearer", value: "**********" },
+ },
+ },
+ },
+ });
+
+ await SettingsService.patchMcpServer("github", {
+ transport: "http",
+ url: "https://github.example/mcp",
+ enabled: false,
+ } as Parameters<typeof SettingsService.patchMcpServer>[1]);
+
+ expect(mockSaveCloudSettings).toHaveBeenCalledWith({
+ agent_settings_diff: {
+ mcp_config: {
+ github: {
+ url: "https://github.example/mcp",
+ auth: { strategy: "bearer", value: "**********" },
+ transport: "http",
+ enabled: false,
+ },
+ linear: {
+ url: "https://mcp.linear.app/mcp",
+ auth: { strategy: "bearer", value: "**********" },
+ },
+ },
+ },
+ });
+ });
+
+ it("fails a cloud add without saving when the stored catalog cannot be read", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+
+ mockFetchCloudSettings.mockRejectedValue(new Error("catalog unavailable"));
+
+ await expect(
+ SettingsService.createMcpServer("only", {
+ transport: "http",
+ url: "https://x.example",
+ }),
+ ).rejects.toThrow("catalog unavailable");
+
+ // Falling back to the one-key map would wipe the siblings.
+ expect(mockSaveCloudSettings).not.toHaveBeenCalled();
+ });
+
+ it("sends a sparse map without reading the catalog for a cloud delete or rename", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+
+ await SettingsService.deleteMcpServer("github");
+ await SettingsService.patchMcpConfig({
+ github: null,
+ hub: { transport: "http", url: "https://github.example/mcp" },
+ });
+
+ expect(mockFetchCloudSettings).not.toHaveBeenCalled();
+ expect(mockSaveCloudSettings).toHaveBeenNthCalledWith(1, {
+ agent_settings_diff: { mcp_config: { github: null } },
+ });
+ expect(mockSaveCloudSettings).toHaveBeenNthCalledWith(2, {
+ agent_settings_diff: {
+ mcp_config: {
+ github: null,
+ hub: { transport: "http", url: "https://github.example/mcp" },
+ },
},
});
});
@@ -758,10 +887,12 @@ describe("SettingsService", () => {
setActiveSelection({ backendId: cloudBackend.id });
mockFetchCloudSettings.mockResolvedValue({
- mcp_config: {
- github: {
- url: "https://github.example/mcp",
- headers: { Authorization: "Bearer stale-token" },
+ agent_settings: {
+ mcp_config: {
+ github: {
+ url: "https://github.example/mcp",
+ headers: { Authorization: "Bearer stale-token" },
+ },
},
},
});
@@ -771,11 +902,15 @@ describe("SettingsService", () => {
});
expect(mockSaveCloudSettings).toHaveBeenCalledTimes(1);
+ // `headers: {}` is required, not cosmetic: an omitted `headers` makes the
+ // cloud carry the stale Authorization header back.
expect(mockSaveCloudSettings).toHaveBeenCalledWith({
agent_settings_diff: {
mcp_config: {
github: {
- headers: { Authorization: null },
+ url: "https://github.example/mcp",
+ headers: {},
+ auth: null,
},
},
},
diff --git a/specs/mcp-settings.md b/specs/mcp-settings.md
index 93eb84909e..e6f8d1187b 100644
--- a/specs/mcp-settings.md
+++ b/specs/mcp-settings.md
@@ -6,8 +6,14 @@
- [x] Adding, updating, or deleting an MCP server shall issue exactly one
dedicated MCP settings request containing only the affected server.
+ On a cloud backend, an add or update first reads the stored catalog and
+ writes it back in full, because the cloud replaces the whole catalog for
+ an `mcp_config` map without `null` entries (OHE-3248).
- [x] An MCP mutation shall never use redacted or encrypted settings snapshots
- as its mutation base.
+ as its mutation base. On a cloud backend, untouched sibling servers are
+ resent verbatim from the redacted settings read (the cloud restores their
+ secrets by key); redacted values are still never used as input for the
+ mutated server.
- [x] Untouched sibling servers and credentials shall survive add, update,
delete, concurrent different-key updates, and failed mutations.
diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.ts
index dd323a9bdb..e31f579c51 100644
--- a/src/api/settings-service/settings-service.api.ts
+++ b/src/api/settings-service/settings-service.api.ts
@@ -6,7 +6,11 @@ import type {
} from "@openhands/typescript-client";
import { DEFAULT_SETTINGS } from "#/services/settings";
import { Settings, SettingsSchema, SettingsValue } from "#/types/settings";
-import { stringRecord } from "#/utils/mcp-config";
+import {
+ applyMcpServerPatch,
+ getSdkMcpServerMap,
+ stringRecord,
+} from "#/utils/mcp-config";
import type { SkillEnablement } from "#/utils/skill-enablement";
import { getActiveBackend } from "../backend-registry/active-store";
import {
@@ -186,6 +190,23 @@ const clearCache = () => {
const isRecord = (value: unknown): value is Record<string, unknown> =>
!!value && typeof value === "object" && !Array.isArray(value);
+/**
+ * Raw name-keyed MCP server map from a cloud `GET /api/v1/settings` response,
+ * exactly as returned (secrets redacted to "**********"). The cloud nests the
+ * catalog under `agent_settings.mcp_config`; a flat `mcp_config` is accepted
+ * as a fallback. Deliberately not `parseMcpConfig`: untouched servers are
+ * resent verbatim so the cloud's by-key secret restore matches them.
+ */
+const readCloudMcpCatalog = (stored: unknown): Record<string, unknown> => {
+ if (!isRecord(stored)) return {};
+ const agentSettings = isRecord(stored.agent_settings)
+ ? stored.agent_settings
+ : undefined;
+ return (
+ getSdkMcpServerMap(agentSettings?.mcp_config ?? stored.mcp_config) ?? {}
+ );
+};
+
const basicAuthHeader = (username: string, password: string): string => {
const token = btoa(`${username}:${password}`);
return `Basic ${token}`;
@@ -235,14 +256,24 @@ const headersFromMcpAuth = (
/**
* 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.
+ * Only the entries in `value` are converted. The cloud `POST /api/v1/settings`
+ * applies an `mcp_config` map WITHOUT a `null` entry as a full-catalog
+ * replacement and only a map WITH a `null` entry (delete / rename) as a
+ * sparse merge β€” see `buildCloudMcpConfigPayload`. 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 with a `null` tombstone. On
+ * the replace path the caller resolves those tombstones client-side (the
+ * cloud rejects `null` header values there); on the sparse path they are sent
+ * as-is. `storedServers` is the already-read cloud catalog; when omitted it is
+ * read lazily, and only if the patch carries a credential.
*/
-const cloudCompatibleMcpConfig = async (value: unknown): Promise<unknown> => {
+const cloudCompatibleMcpConfig = async (
+ value: unknown,
+ storedServers?: Record<string, unknown>,
+): Promise<unknown> => {
if (!isRecord(value)) return value;
const hasWrapper = isRecord(value.mcpServers);
@@ -251,27 +282,31 @@ const cloudCompatibleMcpConfig = async (value: unknown): Promise<unknown> => {
: value;
const needsStoredCredential =
+ storedServers === undefined &&
Object.values(serverMap).some(
(server) =>
isRecord(server) && isRecord(server.auth) && server.auth !== null,
- ) && getActiveBackend().backend.kind === "cloud";
+ ) &&
+ 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);
- }
+ const collectStoredHeaders = (servers: Record<string, unknown>) => {
+ for (const [name, server] of Object.entries(servers)) {
+ if (isRecord(server)) {
+ const headers = stringRecord(server.headers);
+ if (headers) storedHeadersByServer.set(name, headers);
}
+ }
+ };
+ if (storedServers) {
+ collectStoredHeaders(storedServers);
+ } else if (needsStoredCredential) {
+ try {
+ collectStoredHeaders(readCloudMcpCatalog(await fetchCloudSettings()));
} catch {
- // Fall back to the patch-only conversion; a transient fetch failure
- // must not block saving the user's explicit edits.
+ // Tombstone enrichment on the sparse path only: fall back to the
+ // patch-only conversion; a transient fetch failure must not block
+ // saving the user's explicit edits.
}
}
@@ -318,6 +353,64 @@ const cloudCompatibleMcpConfig = async (value: unknown): Promise<unknown> => {
return hasWrapper ? { ...value, mcpServers: converted } : converted;
};
+/**
+ * Build the `mcp_config` value for a cloud `POST /api/v1/settings`.
+ *
+ * The cloud applies a map WITHOUT a `null` entry as a full-catalog
+ * replacement (the bundled settings UI resends the whole catalog) and only a
+ * map WITH a `null` entry (delete / rename) as a sparse merge. Sending a
+ * sparse add/update as-is therefore erases every other stored server
+ * (OHE-3248). For add/update, resend the whole stored catalog: untouched
+ * siblings verbatim from the redacted GET (the cloud restores "**********"
+ * secrets by key), patched entries merged onto their stored entry
+ * client-side. Redacted values are never used as input for the patched entry.
+ */
+const buildCloudMcpConfigPayload = async (
+ patch: MCPConfigPatch,
+): Promise<unknown> => {
+ const hasDeletion = Object.values(patch).some((server) => server === null);
+ if (hasDeletion) return cloudCompatibleMcpConfig(patch);
+
+ // A failed read must fail the mutation: the only fallback is the sparse
+ // payload, which the cloud would apply as "replace the catalog with this
+ // one server".
+ const catalog = readCloudMcpCatalog(
+ await withRetry(() => fetchCloudSettings()),
+ );
+ const converted = await cloudCompatibleMcpConfig(patch, catalog);
+ if (!isRecord(converted)) return converted;
+
+ const next: Record<string, unknown> = { ...catalog };
+ for (const [key, rawEntry] of Object.entries(patch)) {
+ const stored = catalog[key];
+ const entry = converted[key];
+ if (!isRecord(stored) || !isRecord(rawEntry) || !isRecord(entry)) {
+ // New server: `createMcpServer` always sends a complete `MCPServer`.
+ next[key] = entry;
+ continue;
+ }
+ // Sparse `MCPServerPatch` onto the stored entry. Nested `null`s (header
+ // tombstones) delete keys client-side β€” the cloud rejects `null` header
+ // values on the replace path.
+ const merged = applyMcpServerPatch(
+ stored as unknown as MCPServer,
+ entry as MCPServerPatch,
+ ) as unknown as Record<string, unknown>;
+ // A secret carrier cleared by the patch must reach the cloud as an
+ // explicit `null`: an omitted `headers`/`env`/`auth` makes the cloud carry
+ // the stored secret back.
+ for (const field of ["headers", "env", "auth"] as const) {
+ if (entry[field] === null) merged[field] = null;
+ }
+ // The credential was converted into headers (or cleared): drop the stored
+ // `auth` explicitly, otherwise the cloud restores the previous credential
+ // next to the new Authorization header.
+ if ("auth" in rawEntry && !("auth" in entry)) merged.auth = null;
+ next[key] = merged;
+ }
+ return next;
+};
+
/**
* Read the skill allow-/deny-lists off a raw API response β€” for
* `getSettingsForConversation`, which returns the encrypted dump as-is rather
@@ -555,13 +648,17 @@ class SettingsService {
}
/**
- * 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.
+ * Apply one name-keyed MCP merge patch. Locally this is exactly one PATCH
+ * (the agent-server deep-merges `mcp_config`). On cloud it is one GET plus
+ * one POST carrying the full catalog, because the cloud replaces the whole
+ * catalog for a map without `null` entries β€” see
+ * `buildCloudMcpConfigPayload`. Untouched siblings are resent verbatim from
+ * the redacted GET (the cloud restores their secrets by key); redacted
+ * values are never used as input for the patched entry.
*/
static async patchMcpConfig(patch: MCPConfigPatch): Promise<boolean> {
if (getActiveBackend().backend.kind === "cloud") {
- const mcpConfig = await cloudCompatibleMcpConfig(patch);
+ const mcpConfig = await buildCloudMcpConfigPayload(patch);
await withRetry(() =>
saveCloudSettings({
agent_settings_diff: { mcp_config: mcpConfig as SettingsValue },
@@ -628,6 +725,10 @@ class SettingsService {
/**
* Save settings to the agent server API.
* Uses PATCH for incremental updates.
+ *
+ * On cloud, an `agent_settings_diff.mcp_config` map without a `null` entry
+ * replaces the whole stored catalog: send a full catalog here, or use
+ * `patchMcpConfig` for sparse MCP mutations.
*/
static async saveSettings(
settings: Partial<Settings> & Record<string, unknown>,
diff --git a/src/utils/mcp-config.ts b/src/utils/mcp-config.ts
index 1880dd8ff5..09a7aa3003 100644
--- a/src/utils/mcp-config.ts
+++ b/src/utils/mcp-config.ts
@@ -377,7 +377,7 @@ export function buildMcpServerPatch(
return patch;
}
-const applyMcpServerPatch = (
+export const applyMcpServerPatch = (
previous: MCPServer,
patch: MCPServerPatch,
): MCPServer => {