Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Fix MCP marketplace: deletes that duplicate, renames on every edit, Slack-twice, and Tavily that silently no-ops (#388)

Robert Brennan921ea743ef20
diff --git a/__tests__/api/settings-service.test.ts b/__tests__/api/settings-service.test.ts
index 90789ad563..f235ecf244 100644
--- a/__tests__/api/settings-service.test.ts
+++ b/__tests__/api/settings-service.test.ts
@@ -278,6 +278,286 @@ 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.mcpServers.
+ // 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 mcpServers keys behind and
+ // shifted indices produce duplicate entries.
+ const patchBodies: Array<Record<string, unknown>> = [];
+ server.use(
+ http.patch("*/api/settings", 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.saveSettings({
+ agent_settings_diff: {
+ mcp_config: { mcpServers: { only: { url: "https://x.example" } } },
+ },
+ });
+
+ expect(patchBodies).toEqual([
+ { agent_settings_diff: { mcp_config: null } },
+ {
+ agent_settings_diff: {
+ mcp_config: { mcpServers: { only: { url: "https://x.example" } } },
+ },
+ },
+ ]);
+ });
+
+ 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
+ // not a dict and deep-merge replaces rather than recurses. A second
+ // clear would be wasted work.
+ const patchBodies: Array<Record<string, unknown>> = [];
+ server.use(
+ http.patch("*/api/settings", 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.saveSettings({
+ agent_settings_diff: { mcp_config: null },
+ });
+
+ expect(patchBodies).toEqual([
+ { agent_settings_diff: { mcp_config: null } },
+ ]);
+ });
+
+ it("does not pre-clear when the diff has no mcp_config on the local backend", async () => {
+ // A typical settings save (LLM model, condenser, …) must NOT incur the
+ // mcp_config pre-clear round-trip β€” that would needlessly drop the
+ // user's MCP servers if anything ever raced.
+ const patchBodies: Array<Record<string, unknown>> = [];
+ server.use(
+ http.patch("*/api/settings", 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.saveSettings({
+ agent_settings_diff: { agent: "CodeActAgent" },
+ });
+
+ expect(patchBodies).toEqual([
+ { agent_settings_diff: { agent: "CodeActAgent" } },
+ ]);
+ });
+
+ it("pre-clears mcp_config on the cloud backend before writing the new value", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+
+ await SettingsService.saveSettings({
+ agent_settings_diff: {
+ mcp_config: { mcpServers: { only: { url: "https://x.example" } } },
+ },
+ });
+
+ expect(mockSaveCloudSettings).toHaveBeenCalledTimes(2);
+ expect(mockSaveCloudSettings).toHaveBeenNthCalledWith(1, {
+ agent_settings_diff: { mcp_config: null },
+ });
+ expect(mockSaveCloudSettings).toHaveBeenNthCalledWith(2, {
+ agent_settings_diff: {
+ mcp_config: { mcpServers: { only: { url: "https://x.example" } } },
+ },
+ });
+ });
+
+ 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.
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+
+ const previousMcpConfig = {
+ mcpServers: { existing: { url: "https://old.example" } },
+ };
+ mockFetchCloudSettings.mockResolvedValue({
+ 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 mcpServers.
+ if (
+ mcp &&
+ typeof mcp === "object" &&
+ "mcpServers" in (mcp as Record<string, unknown>) &&
+ (mcp as { mcpServers: Record<string, unknown> }).mcpServers.new
+ ) {
+ return Promise.reject(new Error("validation failed"));
+ }
+ return Promise.resolve(undefined); // rollback succeeds
+ },
+ );
+
+ await expect(
+ SettingsService.saveSettings({
+ agent_settings_diff: {
+ mcp_config: { mcpServers: { new: { url: "https://new.example" } } },
+ },
+ }),
+ ).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 },
+ });
+ });
+
+ 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.
+ const patchBodies: Array<Record<string, unknown>> = [];
+ const previousMcpServers = {
+ existing: { url: "https://old.example" },
+ };
+ let getCount = 0;
+ server.use(
+ http.get("*/api/settings", () => {
+ getCount += 1;
+ return HttpResponse.json({
+ agent_settings: { mcp_config: { mcpServers: previousMcpServers } },
+ conversation_settings: {},
+ llm_api_key_is_set: false,
+ });
+ }),
+ http.patch("*/api/settings", async ({ request }) => {
+ const body = (await request.json()) as Record<string, unknown>;
+ patchBodies.push(body);
+ const agentDiff = body.agent_settings_diff as
+ | { 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" &&
+ "mcpServers" in (mcp as Record<string, unknown>) &&
+ (mcp as { mcpServers: Record<string, unknown> }).mcpServers.new
+ ) {
+ return HttpResponse.json(
+ { error: "validation failed" },
+ { status: 400 },
+ );
+ }
+ return HttpResponse.json({
+ agent_settings: {},
+ conversation_settings: {},
+ llm_api_key_is_set: false,
+ });
+ }),
+ );
+
+ await expect(
+ SettingsService.saveSettings({
+ agent_settings_diff: {
+ mcp_config: { mcpServers: { new: { url: "https://new.example" } } },
+ },
+ }),
+ ).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: { mcpServers: previousMcpServers } },
+ });
+ // And we must have done the pre-clear too.
+ expect(patchBodies[0]).toEqual({
+ 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.
+ 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);
+ }
+ return Promise.reject(new Error("validation failed"));
+ },
+ );
+
+ await expect(
+ SettingsService.saveSettings({
+ agent_settings_diff: {
+ mcp_config: { mcpServers: { new: { url: "https://new.example" } } },
+ },
+ }),
+ ).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);
+ 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" &&
+ "mcpServers" in (mcp as Record<string, unknown>) &&
+ !!(mcp as { mcpServers: Record<string, unknown> }).mcpServers.new;
+ expect(isPreClear || isNewWrite).toBe(true);
+ }
+ });
+
it("lets the cloud response override locally-stored app preferences", async () => {
// Arrange: localStorage holds a stale "fr" while the cloud is the
// authoritative source and returns "ja".
@@ -297,5 +577,4 @@ describe("SettingsService", () => {
// Assert: the server wins.
expect(settings.language).toBe("ja");
});
-
});
diff --git a/__tests__/components/features/mcp-page/install-server-modal.test.tsx b/__tests__/components/features/mcp-page/install-server-modal.test.tsx
index 8bf10d9d56..49c70b4469 100644
--- a/__tests__/components/features/mcp-page/install-server-modal.test.tsx
+++ b/__tests__/components/features/mcp-page/install-server-modal.test.tsx
@@ -69,7 +69,13 @@ describe("InstallServerModal", () => {
expect(onClose).toHaveBeenCalled();
});
- it("installs Tavily by writing search_api_key", async () => {
+ it("installs Tavily as a stdio MCP server with TAVILY_API_KEY env", async () => {
+ // Tavily was previously a fake `kind: "tavily-builtin"` template
+ // that called saveSettings({ search_api_key }) β€” but that field
+ // was dropped on the floor in both local and cloud save paths, so
+ // installing Tavily silently did nothing. It's now a regular
+ // stdio MCP entry (`npx -y tavily-mcp` + TAVILY_API_KEY) that
+ // goes through the same mcp_config write as every other entry.
const tavily = MCP_MARKETPLACE.find((e) => e.id === "tavily")!;
const saveSpy = vi
.spyOn(SettingsService, "saveSettings")
@@ -80,14 +86,26 @@ describe("InstallServerModal", () => {
await screen.findByTestId("mcp-install-modal");
- fireEvent.change(screen.getByTestId("mcp-install-field-search_api_key"), {
+ // Submit with no key fails the required-field check.
+ fireEvent.click(screen.getByTestId("mcp-install-submit"));
+ await waitFor(() => expect(saveSpy).not.toHaveBeenCalled());
+
+ fireEvent.change(screen.getByTestId("mcp-install-field-TAVILY_API_KEY"), {
target: { value: "tvly-secret" },
});
fireEvent.click(screen.getByTestId("mcp-install-submit"));
await waitFor(() => expect(saveSpy).toHaveBeenCalledTimes(1));
- expect(saveSpy.mock.calls[0][0]).toEqual({
- search_api_key: "tvly-secret",
+ const sent = (saveSpy.mock.calls[0][0] as Record<string, unknown>)
+ .agent_settings_diff as {
+ mcp_config: { mcpServers: Record<string, unknown> };
+ };
+ expect(sent.mcp_config.mcpServers).toMatchObject({
+ tavily: {
+ command: "npx",
+ args: ["-y", "tavily-mcp"],
+ env: { TAVILY_API_KEY: "tvly-secret" },
+ },
});
expect(onClose).toHaveBeenCalled();
});
@@ -130,23 +148,6 @@ describe("InstallServerModal", () => {
await waitFor(() => expect(saveSpy).toHaveBeenCalledTimes(1));
});
- it("renders an inline error when Tavily submit is clicked with no key", async () => {
- const tavily = MCP_MARKETPLACE.find((e) => e.id === "tavily")!;
- const saveSpy = vi
- .spyOn(SettingsService, "saveSettings")
- .mockResolvedValue(true);
-
- renderWith(<InstallServerModal entry={tavily} onClose={vi.fn()} />);
- await screen.findByTestId("mcp-install-modal");
-
- fireEvent.click(screen.getByTestId("mcp-install-submit"));
-
- // Error state set in handleTavilySubmit must actually render
- // (previously it was set but never displayed).
- await screen.findByText("MCP$ERROR_FIELD_REQUIRED");
- expect(saveSpy).not.toHaveBeenCalled();
- });
-
it("allows submitting an shttp template with no key when apiKeyOptional is true", async () => {
const entry: MarketplaceEntry = {
id: "synthetic-optional",
diff --git a/__tests__/routes/mcp-page.test.tsx b/__tests__/routes/mcp-page.test.tsx
index 2a71f6bea5..311b5146d9 100644
--- a/__tests__/routes/mcp-page.test.tsx
+++ b/__tests__/routes/mcp-page.test.tsx
@@ -166,9 +166,26 @@ describe("MCPPage", () => {
expect(sent.mcp_config).toBeNull();
});
- it("badges Tavily as installed when search_api_key_set is true", async () => {
+ it("badges Tavily as installed when the persisted mcp_config contains it", async () => {
+ // Tavily is now a regular stdio MCP entry (it used to claim to be
+ // a built-in driven by search_api_key, but that field was never
+ // forwarded to either backend). Installation status comes from
+ // the same mcp_config lookup as every other entry.
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
- buildSettings({ search_api_key_set: true }),
+ buildSettings({
+ agent_settings: {
+ ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,
+ mcp_config: {
+ mcpServers: {
+ tavily: {
+ command: "npx",
+ args: ["-y", "tavily-mcp"],
+ env: { TAVILY_API_KEY: "tvly-secret" },
+ },
+ },
+ },
+ },
+ }),
);
renderPage();
@@ -179,4 +196,73 @@ describe("MCPPage", () => {
).toBeInTheDocument();
expect(screen.getByTestId("mcp-installed-list")).toBeInTheDocument();
});
+
+ it("opens the install modal in add-only mode for a marketplace tile that's already installed", async () => {
+ // Regression test: clicking an installed marketplace tile must
+ // open a fresh "Install" modal so the user can add a second
+ // instance (e.g. a second Slack workspace). Previously this
+ // coerced into edit mode and `Save changes` overwrote the
+ // existing entry, so the second instance never landed and the
+ // first one got clobbered.
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
+ buildSettings({
+ agent_settings: {
+ ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,
+ mcp_config: {
+ mcpServers: {
+ slack: {
+ command: "npx",
+ args: ["-y", "@modelcontextprotocol/server-slack"],
+ env: { SLACK_BOT_TOKEN: "xoxb-old", SLACK_TEAM_ID: "T01" },
+ },
+ },
+ },
+ },
+ }),
+ );
+ const saveSpy = vi
+ .spyOn(SettingsService, "saveSettings")
+ .mockResolvedValue(true);
+
+ renderPage();
+
+ const tile = await screen.findByTestId("mcp-marketplace-card-slack");
+ // The tile shows the Installed badge but the click should still
+ // open an add-flow modal β€” not jump to an edit form.
+ expect(
+ screen.getByTestId("mcp-marketplace-installed-slack"),
+ ).toBeInTheDocument();
+ fireEvent.click(tile);
+
+ await screen.findByTestId("mcp-install-modal");
+ // Action label confirms add-only semantics (no `Save changes`).
+ expect(screen.getByTestId("mcp-install-submit")).toHaveTextContent(
+ "MCP$INSTALL_BUTTON",
+ );
+
+ fireEvent.change(screen.getByTestId("mcp-install-field-SLACK_BOT_TOKEN"), {
+ target: { value: "xoxb-new" },
+ });
+ fireEvent.change(screen.getByTestId("mcp-install-field-SLACK_TEAM_ID"), {
+ target: { value: "T02" },
+ });
+ 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: { mcpServers: Record<string, unknown> };
+ };
+ // The original Slack entry is preserved AND a second one is added
+ // alongside it (suffix-collided name comes from the per-base
+ // uniqueness logic in toSdkMcpConfig).
+ expect(Object.keys(sent.mcp_config.mcpServers).sort()).toEqual([
+ "slack",
+ "slack_1",
+ ]);
+ expect(sent.mcp_config.mcpServers).toMatchObject({
+ slack: { env: { SLACK_BOT_TOKEN: "xoxb-old" } },
+ slack_1: { 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.ts
new file mode 100644
index 0000000000..1fa12ef79c
--- /dev/null
+++ b/__tests__/utils/mcp-config.test.ts
@@ -0,0 +1,153 @@
+import { describe, expect, it } from "vitest";
+
+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!.mcpServers)).toEqual(["sse", "shttp", "myname"]);
+ });
+
+ 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: [],
+ };
+
+ const out = toSdkMcpConfig(config);
+
+ expect(Object.keys(out!.mcpServers)).toEqual([
+ "sse",
+ "sse_1",
+ "sse_2",
+ "shttp",
+ "shttp_1",
+ ]);
+ });
+
+ 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" },
+ ],
+ };
+
+ const out = toSdkMcpConfig(config);
+
+ expect(out!.mcpServers).toMatchObject({
+ sse: { url: "https://x" },
+ sse_1: { url: "https://y" },
+ shttp: { url: "https://z" },
+ github: { command: "/bin/gh" },
+ filesystem: { command: "/bin/fs" },
+ });
+ });
+
+ 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" },
+ ],
+ };
+
+ const out = toSdkMcpConfig(config);
+
+ expect(Object.keys(out!.mcpServers)).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!.mcpServers)).toEqual(["stdio", "stdio_1"]);
+ });
+
+ it("returns null when there are no servers", () => {
+ expect(
+ toSdkMcpConfig({ sse_servers: [], shttp_servers: [], stdio_servers: [] }),
+ ).toBeNull();
+ });
+
+ 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 = {
+ mcpServers: {
+ 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);
+
+ expect(written).not.toBeNull();
+ expect(Object.keys(written!.mcpServers).sort()).toEqual(
+ Object.keys(persisted.mcpServers).sort(),
+ );
+ });
+
+ 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" }],
+ };
+ const after: MCPConfig = {
+ sse_servers: [{ url: "https://a" }, { url: "https://b" }],
+ shttp_servers: [],
+ stdio_servers: [{ name: "myname", command: "/bin/run" }],
+ };
+
+ const out1 = toSdkMcpConfig(before)!.mcpServers;
+ const out2 = toSdkMcpConfig(after)!.mcpServers;
+
+ expect("myname" in out1).toBe(true);
+ expect("myname" in out2).toBe(true);
+ });
+});
diff --git a/__tests__/utils/mcp-marketplace-utils.test.ts b/__tests__/utils/mcp-marketplace-utils.test.ts
index 7dca314e00..f3a91a179e 100644
--- a/__tests__/utils/mcp-marketplace-utils.test.ts
+++ b/__tests__/utils/mcp-marketplace-utils.test.ts
@@ -24,10 +24,7 @@ describe("findInstalledMatch", () => {
args: ["-y", "@modelcontextprotocol/server-slack"],
},
]);
- expect(result).toEqual({
- kind: "mcp",
- server: expect.objectContaining({ id: "stdio-0" }),
- });
+ expect(result).toEqual(expect.objectContaining({ id: "stdio-0" }));
});
it("does not match a different stdio name", () => {
@@ -43,17 +40,21 @@ describe("findInstalledMatch", () => {
expect(result).toBeNull();
});
- it("returns the tavily-builtin variant when search_api_key_set", () => {
- expect(
- findInstalledMatch(tavilyEntry.template, [], {
- search_api_key_set: true,
- }),
- ).toEqual({ kind: "tavily-builtin" });
- expect(
- findInstalledMatch(tavilyEntry.template, [], {
- search_api_key_set: false,
- }),
- ).toBeNull();
+ it("matches Tavily as a stdio server by name", () => {
+ // Tavily lives in the catalog as a stdio MCP entry (the previous
+ // tavily-builtin / search_api_key flow never persisted anywhere
+ // and silently dropped the key); confirm the now-uniform match.
+ const result = findInstalledMatch(tavilyEntry.template, [
+ {
+ id: "stdio-0",
+ type: "stdio",
+ name: "tavily",
+ command: "npx",
+ args: ["-y", "tavily-mcp"],
+ env: { TAVILY_API_KEY: "tvly-secret" },
+ },
+ ]);
+ expect(result).toEqual(expect.objectContaining({ id: "stdio-0" }));
});
it("matches SSE servers loosely on URL", () => {
@@ -64,10 +65,7 @@ describe("findInstalledMatch", () => {
url: "https://mcp.linear.app/sse/",
},
]);
- expect(result).toEqual({
- kind: "mcp",
- server: expect.objectContaining({ id: "sse-0" }),
- });
+ expect(result).toEqual(expect.objectContaining({ id: "sse-0" }));
});
it("returns null when servers carry malformed urls (defensive)", () => {
diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.ts
index 97312b3862..4ab46358e0 100644
--- a/src/api/settings-service/settings-service.api.ts
+++ b/src/api/settings-service/settings-service.api.ts
@@ -355,6 +355,63 @@ 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.mcpServers``, 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 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 shape (``{ mcpServers: { name: cfg }}``)
+ // 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.
+ }
+ }
+
if (isCloud) {
const hasCloudWork =
!!payload.agent_settings_diff ||
@@ -364,12 +421,38 @@ class SettingsService {
if (!hasCloudWork) {
return true;
}
- await withRetry(() =>
- saveCloudSettings({
- ...payload,
- ...(hasAppPreferences ? { app_preferences: appPreferences } : {}),
- }),
- );
+ if (needsMcpPreClear) {
+ await withRetry(() =>
+ saveCloudSettings({
+ agent_settings_diff: { mcp_config: null },
+ }),
+ );
+ }
+ try {
+ await withRetry(() =>
+ saveCloudSettings({
+ ...payload,
+ ...(hasAppPreferences ? { app_preferences: appPreferences } : {}),
+ }),
+ );
+ } catch (err) {
+ if (needsMcpPreClear && 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;
+ }
} else {
// The local agent-server PATCH /api/settings rejects unknown fields and
// requires at least one of the two diff fields. Strip disabled_skills
@@ -388,11 +471,36 @@ class SettingsService {
}
return true;
}
- await withRetry(() =>
- new SettingsClient(getAgentServerClientOptions()).updateSettings(
- localPayload,
- ),
- );
+ if (needsMcpPreClear) {
+ await withRetry(() =>
+ new SettingsClient(getAgentServerClientOptions()).updateSettings({
+ agent_settings_diff: { mcp_config: null },
+ }),
+ );
+ }
+ try {
+ await withRetry(() =>
+ new SettingsClient(getAgentServerClientOptions()).updateSettings(
+ localPayload,
+ ),
+ );
+ } catch (err) {
+ if (needsMcpPreClear && 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;
+ }
}
// Invalidate cache after successful save
diff --git a/src/components/features/mcp-page/install-server-modal.tsx b/src/components/features/mcp-page/install-server-modal.tsx
index d70a0b5249..75ae5549be 100644
--- a/src/components/features/mcp-page/install-server-modal.tsx
+++ b/src/components/features/mcp-page/install-server-modal.tsx
@@ -6,21 +6,13 @@ import { BrandButton } from "#/components/features/settings/brand-button";
import { SettingsInput } from "#/components/features/settings/settings-input";
import { I18nKey } from "#/i18n/declaration";
import { MarketplaceEntry } from "#/constants/mcp-marketplace";
-import {
- ExistingInstall,
- MCPServerConfig,
- isMcpInstall,
-} from "#/types/mcp-server";
+import { MCPServerConfig } from "#/types/mcp-server";
import { useAddMcpServer } from "#/hooks/mutation/use-add-mcp-server";
-import { useUpdateMcpServer } from "#/hooks/mutation/use-update-mcp-server";
-import { useSaveSettings } from "#/hooks/mutation/use-save-settings";
import { displaySuccessToast } from "#/utils/custom-toast-handlers";
import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
interface InstallServerModalProps {
entry: MarketplaceEntry;
- /** Existing install (if any) β€” drives Edit vs Add. */
- existing?: ExistingInstall | null;
onClose: () => void;
}
@@ -40,31 +32,29 @@ function makeInitialState(entry: MarketplaceEntry): FieldState {
}
} else if (entry.template.kind === "shttp" || entry.template.kind === "sse") {
values.api_key = "";
- } else if (entry.template.kind === "tavily-builtin") {
- values.search_api_key = "";
}
return { values, errors: {} };
}
+// The marketplace install modal is intentionally add-only: clicking
+// a catalog tile always appends a new server (the user might want
+// two Slack workspaces, two Postgres connections, etc.) even when
+// one of the same template kind is already installed. Editing an
+// existing server is reached via the installed-server-card's edit
+// button, which opens `CustomServerEditor` instead.
export function InstallServerModal({
entry,
- existing,
onClose,
}: InstallServerModalProps) {
const { t } = useTranslation("openhands");
const { mutate: addMcpServer, isPending: isAdding } = useAddMcpServer();
- const { mutate: updateMcpServer, isPending: isUpdating } =
- useUpdateMcpServer();
- const { mutate: saveSettings, isPending: isSavingSettings } =
- useSaveSettings();
const [state, setState] = React.useState<FieldState>(() =>
makeInitialState(entry),
);
const [globalError, setGlobalError] = React.useState<string | null>(null);
- const isEditing = !!existing;
- const isPending = isAdding || isUpdating || isSavingSettings;
+ const isPending = isAdding;
const setValue = (key: string, value: string) => {
setState((prev) => ({
@@ -74,60 +64,24 @@ export function InstallServerModal({
setGlobalError(null);
};
- // ------------------------------------------------------------------
- // Shared add-or-update plumbing. Every per-template handler funnels
- // through this to keep success/error handling consistent (single
- // toast + single error path), and to centralize the "create new vs.
- // update existing" branching.
- // ------------------------------------------------------------------
const submitServer = (payload: MCPServerConfig) => {
- const onSuccess = () => {
- displaySuccessToast(t(I18nKey.MCP$INSTALL_SUCCESS));
- onClose();
- };
- const onError = (err: unknown) => {
- const message = retrieveAxiosErrorMessage(err as AxiosError);
- setGlobalError(message || t(I18nKey.ERROR$GENERIC));
- };
- if (isMcpInstall(existing)) {
- updateMcpServer(
- { serverId: existing.server.id, server: payload },
- { onSuccess, onError },
- );
- } else {
- addMcpServer(payload, { onSuccess, onError });
- }
+ addMcpServer(payload, {
+ onSuccess: () => {
+ displaySuccessToast(t(I18nKey.MCP$INSTALL_SUCCESS));
+ onClose();
+ },
+ onError: (err: unknown) => {
+ const message = retrieveAxiosErrorMessage(err as AxiosError);
+ setGlobalError(message || t(I18nKey.ERROR$GENERIC));
+ },
+ });
};
// ------------------------------------------------------------------
// Per-template submit handlers. Each is small and self-contained:
// validate user input, build the payload, then hand off to
- // submitServer / saveSettings.
+ // submitServer.
// ------------------------------------------------------------------
- const handleTavilySubmit = () => {
- const key = state.values.search_api_key?.trim() ?? "";
- if (!key && !isEditing) {
- setState((prev) => ({
- ...prev,
- errors: { search_api_key: t(I18nKey.MCP$ERROR_FIELD_REQUIRED) },
- }));
- return;
- }
- saveSettings(
- { search_api_key: key },
- {
- onSuccess: () => {
- displaySuccessToast(t(I18nKey.MCP$INSTALL_SUCCESS));
- onClose();
- },
- onError: (err) => {
- const message = retrieveAxiosErrorMessage(err as AxiosError);
- setGlobalError(message || t(I18nKey.ERROR$GENERIC));
- },
- },
- );
- };
-
const handleHttpServerSubmit = () => {
// TS narrows this branch to shttp|sse; the equality guard is a
// runtime/defensive belt to make the helper safe in isolation.
@@ -142,9 +96,8 @@ export function InstallServerModal({
}));
return;
}
- const existingMcp = isMcpInstall(existing) ? existing.server : null;
const payload: MCPServerConfig = {
- id: existingMcp?.id ?? `${entry.template.kind}-${Date.now()}`,
+ id: `${entry.template.kind}-${Date.now()}`,
type: entry.template.kind,
url: entry.template.url,
...(apiKey && { api_key: apiKey }),
@@ -188,9 +141,8 @@ export function InstallServerModal({
}
}
- const existingMcp = isMcpInstall(existing) ? existing.server : null;
const payload: MCPServerConfig = {
- id: existingMcp?.id ?? `stdio-${Date.now()}`,
+ id: `stdio-${Date.now()}`,
type: "stdio",
name: stdio.serverName,
command: stdio.command,
@@ -203,7 +155,6 @@ export function InstallServerModal({
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setGlobalError(null);
- if (entry.template.kind === "tavily-builtin") return handleTavilySubmit();
if (entry.template.kind === "shttp" || entry.template.kind === "sse") {
return handleHttpServerSubmit();
}
@@ -211,32 +162,6 @@ export function InstallServerModal({
};
const renderFields = () => {
- if (entry.template.kind === "tavily-builtin") {
- return (
- <div className="flex flex-col gap-1">
- <SettingsInput
- testId="mcp-install-field-search_api_key"
- name="search_api_key"
- type="password"
- label={t(I18nKey.SETTINGS$SEARCH_API_KEY)}
- value={state.values.search_api_key ?? ""}
- onChange={(v) => setValue("search_api_key", v)}
- placeholder="tvly-..."
- className="w-full"
- />
- {/* `handleTavilySubmit` sets this error on submit when the
- key is empty; render it inline so the user actually sees
- the validation failure (previously the state was set but
- never displayed). */}
- {state.errors.search_api_key && (
- <p className="text-xs text-red-500">
- {state.errors.search_api_key}
- </p>
- )}
- </div>
- );
- }
-
if (entry.template.kind === "shttp" || entry.template.kind === "sse") {
const apiKeyOptional = entry.template.apiKeyOptional ?? false;
return (
@@ -392,11 +317,9 @@ export function InstallServerModal({
testId="mcp-install-submit"
className="w-full text-center"
>
- {(() => {
- if (isPending) return t(I18nKey.SETTINGS$SAVING);
- if (isEditing) return t(I18nKey.SETTINGS$MCP_SAVE_SERVER);
- return t(I18nKey.MCP$INSTALL_BUTTON);
- })()}
+ {isPending
+ ? t(I18nKey.SETTINGS$SAVING)
+ : t(I18nKey.MCP$INSTALL_BUTTON)}
</BrandButton>
<BrandButton
type="button"
diff --git a/src/components/features/mcp-page/installed-server-card.tsx b/src/components/features/mcp-page/installed-server-card.tsx
index fc3524ebbb..216e0592f9 100644
--- a/src/components/features/mcp-page/installed-server-card.tsx
+++ b/src/components/features/mcp-page/installed-server-card.tsx
@@ -9,10 +9,6 @@ import { cn } from "#/utils/utils";
interface InstalledServerCardProps {
server: MCPServerConfig;
- /** Force a specific marketplace catalog id β€” used for Tavily where the
- * persisted shape (search_api_key) doesn't look like a normal MCP
- * server. */
- catalogIdOverride?: string;
onEdit: () => void;
onDelete: () => void;
}
@@ -46,7 +42,6 @@ function getServerSubtitle(server: MCPServerConfig): string {
export function InstalledServerCard({
server,
- catalogIdOverride,
onEdit,
onDelete,
}: InstalledServerCardProps) {
@@ -55,15 +50,11 @@ export function InstalledServerCard({
// and `findInstalledMatch` agree on URL canonicalization (trailing
// slashes, query strings, default ports) and stay in sync when one
// is updated.
- const catalog = catalogIdOverride
- ? MCP_MARKETPLACE.find((entry) => entry.id === catalogIdOverride)
- : findCatalogEntryForServer(server, MCP_MARKETPLACE);
+ const catalog = findCatalogEntryForServer(server, MCP_MARKETPLACE);
const title = catalog?.name ?? getServerTitle(server);
- const subtitle = catalogIdOverride ? "" : getServerSubtitle(server);
- const transport = catalogIdOverride
- ? t(I18nKey.MCP$TRANSPORT_BUILTIN)
- : getServerTransportLabel(server.type);
+ const subtitle = getServerSubtitle(server);
+ const transport = getServerTransportLabel(server.type);
return (
<div
diff --git a/src/components/features/mcp-page/installed-servers-section.tsx b/src/components/features/mcp-page/installed-servers-section.tsx
index 72edaad90c..d5ad2b36bd 100644
--- a/src/components/features/mcp-page/installed-servers-section.tsx
+++ b/src/components/features/mcp-page/installed-servers-section.tsx
@@ -7,38 +7,28 @@ interface InstalledServersSectionProps {
/** Already-filtered list β€” search filtering happens upstream. */
servers: MCPServerConfig[];
/**
- * Tavily has a virtual "installed" card when search_api_key is set
- * on the backend. Pass `true` when it matches the current search.
- */
- tavilyBuiltinInstalled?: boolean;
- /**
- * True iff there is at least one installed server (or the Tavily
- * builtin) before applying the search filter. Lets the section
- * differentiate "nothing installed yet" from "no installed servers
- * match the current search".
+ * True iff there is at least one installed server before applying
+ * the search filter. Lets the section differentiate "nothing
+ * installed yet" from "no installed servers match the current
+ * search".
*/
hasAnyInstalled: boolean;
/** Current search query β€” empty string means no filter applied. */
query?: string;
onEdit: (server: MCPServerConfig) => void;
onDelete: (serverId: string) => void;
- onConfigureTavilyBuiltin?: () => void;
- onRemoveTavilyBuiltin?: () => void;
}
export function InstalledServersSection({
servers,
- tavilyBuiltinInstalled,
hasAnyInstalled,
query = "",
onEdit,
onDelete,
- onConfigureTavilyBuiltin,
- onRemoveTavilyBuiltin,
}: InstalledServersSectionProps) {
const { t } = useTranslation("openhands");
- const isEmpty = servers.length === 0 && !tavilyBuiltinInstalled;
+ const isEmpty = servers.length === 0;
if (isEmpty) {
// Filter narrowed everything out β€” vs. nothing was installed in
@@ -75,14 +65,6 @@ export function InstalledServersSection({
data-testid="mcp-installed-list"
className="grid gap-3 grid-cols-1 md:grid-cols-2"
>
- {tavilyBuiltinInstalled && (
- <InstalledServerCard
- catalogIdOverride="tavily"
- server={{ id: "tavily-builtin", type: "shttp" }}
- onEdit={() => onConfigureTavilyBuiltin?.()}
- onDelete={() => onRemoveTavilyBuiltin?.()}
- />
- )}
{servers.map((server) => (
<InstalledServerCard
key={server.id}
diff --git a/src/components/features/mcp-page/marketplace-card.tsx b/src/components/features/mcp-page/marketplace-card.tsx
index b6efd69845..392f1c27af 100644
--- a/src/components/features/mcp-page/marketplace-card.tsx
+++ b/src/components/features/mcp-page/marketplace-card.tsx
@@ -24,8 +24,6 @@ export function MarketplaceCard({
return "HTTP";
case "sse":
return "SSE";
- case "tavily-builtin":
- return t(I18nKey.MCP$TRANSPORT_BUILTIN);
default:
return "";
}
diff --git a/src/constants/mcp-marketplace.tsx b/src/constants/mcp-marketplace.tsx
index 16aa4eecb4..550acac363 100644
--- a/src/constants/mcp-marketplace.tsx
+++ b/src/constants/mcp-marketplace.tsx
@@ -74,14 +74,6 @@ export interface MarketplaceField {
}
export type MarketplaceTemplate =
- | {
- kind: "tavily-builtin";
- // Tavily has first-class support inside the agent server: it
- // reads `search_api_key` and registers a Tavily MCP server
- // automatically. The marketplace card maps to that flow rather
- // than a manual MCP entry to keep it consistent with the legacy
- // "Built-in search" setting.
- }
| {
kind: "shttp";
url: string;
@@ -218,15 +210,29 @@ export const MCP_MARKETPLACE: MarketplaceEntry[] = [
name: "Tavily",
description:
"Production-grade web search optimized for LLM agents. Free tier available.",
- docsUrl: "https://tavily.com/",
+ docsUrl: "https://github.com/tavily-ai/tavily-mcp",
// Tavily isn't in the simple-icons set; use a search glyph on
// their brand blue tile so the marketplace stays icon-consistent.
logo: <Search className={LOGO} strokeWidth={2.5} />,
iconBg: "#2563EB",
keywords: ["search", "web", "browsing", "research"],
installHint:
- "Paste your Tavily API key. OpenHands wires up the Tavily MCP server automatically.",
- template: { kind: "tavily-builtin" },
+ "Paste your Tavily API key β€” the official tavily-mcp package runs via npx.",
+ template: {
+ kind: "stdio",
+ serverName: "tavily",
+ command: "npx",
+ args: ["-y", "tavily-mcp"],
+ envFields: [
+ {
+ key: "TAVILY_API_KEY",
+ label: "Tavily API key",
+ type: "password",
+ placeholder: "tvly-...",
+ required: true,
+ },
+ ],
+ },
},
// -- Hosted, first-party --------------------------------------------
diff --git a/src/routes/mcp.tsx b/src/routes/mcp.tsx
index 84fff72cfe..b77974390d 100644
--- a/src/routes/mcp.tsx
+++ b/src/routes/mcp.tsx
@@ -8,7 +8,6 @@ import { BackendSyncedSettingsBadge } from "#/components/features/settings/backe
import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";
import { useSettings } from "#/hooks/query/use-settings";
import { useDeleteMcpServer } from "#/hooks/mutation/use-delete-mcp-server";
-import { useSaveSettings } from "#/hooks/mutation/use-save-settings";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { parseMcpConfig } from "#/utils/mcp-config";
import {
@@ -20,11 +19,10 @@ import {
findCatalogEntryForServer,
findInstalledMatch,
installedServerMatchesQuery,
- marketplaceEntryMatchesQuery,
} from "#/utils/mcp-marketplace-utils";
import { MCP_MARKETPLACE, MarketplaceEntry } from "#/constants/mcp-marketplace";
import { MCPConfig } from "#/types/settings";
-import { ExistingInstall, MCPServerConfig } from "#/types/mcp-server";
+import { MCPServerConfig } from "#/types/mcp-server";
import {
InstalledServersSection,
MarketplaceSearch,
@@ -59,19 +57,11 @@ function flattenMcpConfig(config: MCPConfig): MCPServerConfig[] {
];
}
-// Looked up lazily inside the component so we don't crash at module
-// load if the catalog ever drops Tavily.
-function getTavilyEntry(): MarketplaceEntry | undefined {
- return MCP_MARKETPLACE.find((e) => e.id === "tavily");
-}
-
export default function MCPPage() {
const { t } = useTranslation("openhands");
const { data: settings, isLoading } = useSettings();
const { mutate: deleteMcpServer, isPending: isDeleting } =
useDeleteMcpServer();
- const { mutate: saveSettings, isPending: isSavingSettings } =
- useSaveSettings();
const activeBackend = useActiveBackend();
const backendKind = activeBackend.backend.kind;
@@ -80,16 +70,14 @@ export default function MCPPage() {
const [editingServer, setEditingServer] =
React.useState<MCPServerConfig | null>(null);
const [serverToDelete, setServerToDelete] =
- React.useState<ExistingInstall | null>(null);
+ React.useState<MCPServerConfig | null>(null);
const [searchQuery, setSearchQuery] = React.useState("");
- const tavilyEntry = getTavilyEntry();
const mcpConfig = parseMcpConfig(settings?.agent_settings?.mcp_config);
const allServers = flattenMcpConfig(mcpConfig);
- const tavilyBuiltinInstalled = !!settings?.search_api_key_set;
const isInstalled = (entry: MarketplaceEntry) =>
- !!findInstalledMatch(entry.template, allServers, settings);
+ !!findInstalledMatch(entry.template, allServers);
// Filter installed servers by the search query. We pair each server
// with its catalog entry (if any) so the search can match friendly
@@ -102,10 +90,6 @@ export default function MCPPage() {
searchQuery,
),
);
- const tavilyVisibleAfterSearch =
- tavilyBuiltinInstalled &&
- !!tavilyEntry &&
- marketplaceEntryMatchesQuery(tavilyEntry, searchQuery);
const handleMarketplaceClick = (entry: MarketplaceEntry) => {
setInstallEntry(entry);
@@ -117,32 +101,16 @@ export default function MCPPage() {
const handleDeleteClick = (serverId: string) => {
const target = allServers.find((s) => s.id === serverId);
- if (target) setServerToDelete({ kind: "mcp", server: target });
+ if (target) setServerToDelete(target);
};
const handleConfirmDelete = () => {
if (!serverToDelete) return;
- if (serverToDelete.kind === "tavily-builtin") {
- saveSettings(
- { search_api_key: "" },
- {
- onSuccess: () => {
- displaySuccessToast(t(I18nKey.MCP$REMOVE_SUCCESS));
- setServerToDelete(null);
- },
- onError: (err) => {
- const message = retrieveAxiosErrorMessage(err as AxiosError);
- displayErrorToast(message || t(I18nKey.ERROR$GENERIC));
- },
- },
- );
- return;
- }
// Pass the full server config β€” useDeleteMcpServer re-resolves its
// position against the fresh settings at mutation time, so a
// background refresh between this click and confirm cannot point
// us at the wrong index.
- deleteMcpServer(serverToDelete.server, {
+ deleteMcpServer(serverToDelete, {
onSuccess: () => {
displaySuccessToast(t(I18nKey.MCP$REMOVE_SUCCESS));
setServerToDelete(null);
@@ -165,12 +133,6 @@ export default function MCPPage() {
);
}
- // Existing match for the install modal β€” drives Add vs Edit and the
- // optional "Remove" affordance for already-installed catalog entries.
- const installExisting = installEntry
- ? findInstalledMatch(installEntry.template, allServers, settings)
- : null;
-
return (
<main
data-testid="mcp-page"
@@ -205,17 +167,10 @@ export default function MCPPage() {
</h2>
<InstalledServersSection
servers={filteredInstalledServers}
- tavilyBuiltinInstalled={tavilyVisibleAfterSearch}
- hasAnyInstalled={allServers.length > 0 || tavilyBuiltinInstalled}
+ hasAnyInstalled={allServers.length > 0}
query={searchQuery}
onEdit={handleEdit}
onDelete={handleDeleteClick}
- onConfigureTavilyBuiltin={
- tavilyEntry ? () => setInstallEntry(tavilyEntry) : undefined
- }
- onRemoveTavilyBuiltin={() =>
- setServerToDelete({ kind: "tavily-builtin" })
- }
/>
</section>
@@ -230,7 +185,6 @@ export default function MCPPage() {
{installEntry && (
<InstallServerModal
entry={installEntry}
- existing={installExisting}
onClose={() => setInstallEntry(null)}
/>
)}
@@ -251,7 +205,7 @@ export default function MCPPage() {
text={t(I18nKey.SETTINGS$MCP_CONFIRM_DELETE)}
onCancel={() => setServerToDelete(null)}
onConfirm={handleConfirmDelete}
- isConfirming={isDeleting || isSavingSettings}
+ isConfirming={isDeleting}
/>
)}
</main>
diff --git a/src/types/mcp-server.ts b/src/types/mcp-server.ts
index 6f34df04b5..c71d025c7a 100644
--- a/src/types/mcp-server.ts
+++ b/src/types/mcp-server.ts
@@ -16,19 +16,3 @@ export interface MCPServerConfig {
args?: string[];
env?: Record<string, string>;
}
-
-/**
- * Discriminated union describing the "existing install" referenced
- * from various MCP UI surfaces (install modal, delete confirmation,
- * etc.). Previously these surfaces juggled
- * `MCPServerConfig | "tavily-builtin" | null`, which made the
- * Tavily-builtin case look like an arbitrary string and required
- * the same string check at every callsite.
- */
-export type ExistingInstall =
- | { kind: "mcp"; server: MCPServerConfig }
- | { kind: "tavily-builtin" };
-
-export const isMcpInstall = (
- i: ExistingInstall | null | undefined,
-): i is { kind: "mcp"; server: MCPServerConfig } => i?.kind === "mcp";
diff --git a/src/utils/mcp-config.ts b/src/utils/mcp-config.ts
index 907e09e605..68c8915c40 100644
--- a/src/utils/mcp-config.ts
+++ b/src/utils/mcp-config.ts
@@ -41,7 +41,6 @@ export function parseMcpConfig(value: unknown): MCPConfig {
const mcpServers = obj.mcpServers as Record<string, Record<string, unknown>>;
for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
- // eslint-disable-next-line no-continue
if (!serverConfig || typeof serverConfig !== "object") continue;
const url = serverConfig.url as string | undefined;
@@ -89,15 +88,23 @@ export function parseMcpConfig(value: unknown): MCPConfig {
/**
* Convert the frontend MCPConfig format back to the SDK { mcpServers: { ... } }
* shape 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.
*/
export function toSdkMcpConfig(config: MCPConfig): SdkMcpConfig | null {
const mcpServers: Record<string, SdkMcpServerConfig> = {};
- let counter = 0;
- const nextName = (base: string): string => {
- const name = counter === 0 ? base : `${base}_${counter}`;
- counter += 1;
- return name;
+ const reserve = (base: string): string => {
+ if (!(base in mcpServers)) return base;
+ let i = 1;
+ while (`${base}_${i}` in mcpServers) i += 1;
+ return `${base}_${i}`;
};
for (const entry of config.sse_servers) {
@@ -109,7 +116,7 @@ export function toSdkMcpConfig(config: MCPConfig): SdkMcpConfig | null {
if (entry.api_key) server.auth = entry.api_key;
}
server.transport = "sse";
- mcpServers[nextName("sse")] = server;
+ mcpServers[reserve("sse")] = server;
}
for (const entry of config.shttp_servers) {
@@ -121,7 +128,7 @@ export function toSdkMcpConfig(config: MCPConfig): SdkMcpConfig | null {
if (entry.api_key) server.auth = entry.api_key;
if (entry.timeout != null) server.timeout = entry.timeout;
}
- mcpServers[nextName("shttp")] = server;
+ mcpServers[reserve("shttp")] = server;
}
for (const entry of config.stdio_servers) {
@@ -130,7 +137,7 @@ export function toSdkMcpConfig(config: MCPConfig): SdkMcpConfig | null {
};
if (entry.args) server.args = entry.args;
if (entry.env) server.env = entry.env;
- mcpServers[nextName(entry.name || "stdio")] = server;
+ mcpServers[reserve(entry.name || "stdio")] = server;
}
return Object.keys(mcpServers).length > 0 ? { mcpServers } : null;
diff --git a/src/utils/mcp-marketplace-utils.ts b/src/utils/mcp-marketplace-utils.ts
index 4b9c5d27a7..3274fddbf2 100644
--- a/src/utils/mcp-marketplace-utils.ts
+++ b/src/utils/mcp-marketplace-utils.ts
@@ -1,9 +1,8 @@
-import { ExistingInstall, MCPServerConfig } from "#/types/mcp-server";
+import { MCPServerConfig } from "#/types/mcp-server";
import {
MarketplaceEntry,
MarketplaceTemplate,
} from "#/constants/mcp-marketplace";
-import { Settings } from "#/types/settings";
const tryUrl = (raw: string): URL | null => {
try {
@@ -43,40 +42,37 @@ export function urlsMatch(a: unknown, b: unknown): boolean {
/**
* Decide whether a marketplace template is already represented by one
* of the installed MCP servers. Used to render an "Installed" badge on
- * the marketplace tile.
+ * the marketplace tile. Returns the first matching server, or null.
*/
export function findInstalledMatch(
template: MarketplaceTemplate,
servers: MCPServerConfig[],
- settings?: Pick<Settings, "search_api_key_set">,
-): ExistingInstall | null {
- if (template.kind === "tavily-builtin") {
- return settings?.search_api_key_set ? { kind: "tavily-builtin" } : null;
- }
-
+): MCPServerConfig | null {
if (template.kind === "shttp") {
const tplUrl = template.url;
if (!tplUrl) return null;
- const match = servers.find(
- (s) => s.type === "shttp" && !!s.url && urlsMatch(s.url, tplUrl),
+ return (
+ servers.find(
+ (s) => s.type === "shttp" && !!s.url && urlsMatch(s.url, tplUrl),
+ ) ?? null
);
- return match ? { kind: "mcp", server: match } : null;
}
if (template.kind === "sse") {
const tplUrl = template.url;
if (!tplUrl) return null;
- const match = servers.find(
- (s) => s.type === "sse" && !!s.url && urlsMatch(s.url, tplUrl),
+ return (
+ servers.find(
+ (s) => s.type === "sse" && !!s.url && urlsMatch(s.url, tplUrl),
+ ) ?? null
);
- return match ? { kind: "mcp", server: match } : null;
}
// stdio: match on the registered server name.
- const match = servers.find(
- (s) => s.type === "stdio" && s.name === template.serverName,
+ return (
+ servers.find((s) => s.type === "stdio" && s.name === template.serverName) ??
+ null
);
- return match ? { kind: "mcp", server: match } : null;
}
export function isMarketplaceEntryAvailable(
@@ -155,7 +151,6 @@ export function findCatalogEntryForServer(
): MarketplaceEntry | undefined {
return catalog.find((entry) => {
const tpl = entry.template;
- if (tpl.kind === "tavily-builtin") return false;
if (tpl.kind === "stdio")
return server.type === "stdio" && server.name === tpl.serverName;
// Reuse the same loose URL match as `findInstalledMatch` so a