🙌 OpenHands: AI-Driven Development
feat: show actionable connection health on installed server cards (#1833)
Hiep Lea8edaa7cf4be
diff --git a/__tests__/api/mcp-health/mcp-health-store.test.ts b/__tests__/api/mcp-health/mcp-health-store.test.tsnew file mode 100644index 0000000000..1bad49135c--- /dev/null+++ b/__tests__/api/mcp-health/mcp-health-store.test.ts@@ -0,0 +1,64 @@+import { beforeEach, describe, expect, it } from "vitest";+import {+ __resetMcpHealthStoreForTests,+ beginMcpHealthCheck,+ clearMcpServerHealth,+ getMcpHealthSnapshot,+ resolveMcpHealthCheck,+} from "#/api/mcp-health/mcp-health-store";+import type { McpServerHealth } from "#/types/mcp-health";++const HEALTHY: McpServerHealth = {+ status: "healthy",+ verification: "verified",+ toolCount: 3,+ checkedAt: 1,+};++const FAILED: McpServerHealth = {+ status: "failed",+ kind: "connection",+ error: "refused",+ checkedAt: 2,+};++describe("mcp-health-store", () => {+ beforeEach(() => {+ __resetMcpHealthStoreForTests();+ });++ it("marks a check as in flight and commits its result", () => {+ const checkId = beginMcpHealthCheck("key");+ expect(getMcpHealthSnapshot().key).toEqual({ status: "checking", checkId });++ resolveMcpHealthCheck("key", checkId, HEALTHY);++ expect(getMcpHealthSnapshot().key).toEqual(HEALTHY);+ });++ it("drops a stale result that was superseded by a newer check", () => {+ const staleId = beginMcpHealthCheck("key");+ const freshId = beginMcpHealthCheck("key");++ // The slow older probe must not overwrite the newer probe's lifecycle.+ resolveMcpHealthCheck("key", staleId, HEALTHY);+ expect(getMcpHealthSnapshot().key).toEqual({+ status: "checking",+ checkId: freshId,+ });++ resolveMcpHealthCheck("key", freshId, FAILED);+ expect(getMcpHealthSnapshot().key).toEqual(FAILED);+ });++ it("drops a result whose entry was cleared mid-flight", () => {+ // e.g. the server was edited or deleted while its probe was running —+ // the late result must not resurrect a verdict for a gone config.+ const checkId = beginMcpHealthCheck("key");+ clearMcpServerHealth("key");++ resolveMcpHealthCheck("key", checkId, HEALTHY);++ expect(getMcpHealthSnapshot().key).toBeUndefined();+ });+});diff --git a/__tests__/api/mcp-health/probe-mcp-server-health.test.ts b/__tests__/api/mcp-health/probe-mcp-server-health.test.tsnew file mode 100644index 0000000000..7fc8d71ac7--- /dev/null+++ b/__tests__/api/mcp-health/probe-mcp-server-health.test.ts@@ -0,0 +1,179 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ __resetMcpHealthStoreForTests,+ getMcpHealthSnapshot,+ setMcpServerHealth,+} from "#/api/mcp-health/mcp-health-store";+import {+ interpretMcpTestResponse,+ probeMcpServerHealth,+ seedMcpServerHealth,+} from "#/api/mcp-health/probe-mcp-server-health";+import McpService from "#/api/mcp-service/mcp-service.api";+import type { ExtendedMCPTestResponse, MCPServerConfig } from "#/types/mcp-server";+import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";++/** Matches the catalog `github` entry, so the `get_me` probe spec applies. */+const GITHUB: MCPServerConfig = {+ id: "shttp-0",+ type: "shttp",+ name: "github",+ url: "https://api.githubcopilot.com/mcp/",+ auth: { strategy: "api_key", value: "github_pat_x" },+};++/** Matches no catalog entry, so no probe spec exists. */+const CUSTOM: MCPServerConfig = {+ id: "shttp-1",+ type: "shttp",+ name: "custom",+ url: "https://mcp.example.com/mcp",+};++describe("interpretMcpTestResponse", () => {+ it("passes a non-auth connection failure through with its kind", () => {+ const health = interpretMcpTestResponse(CUSTOM, {+ ok: false,+ error: "connection refused",+ error_kind: "connection",+ });++ expect(health).toMatchObject({+ status: "failed",+ kind: "connection",+ error: "connection refused",+ });+ });++ it("reclassifies a connection failure with auth-rejection text as a credentials failure", () => {+ // Hosted servers reject bad tokens at the HTTP handshake, which the+ // backend can only report as a connection failure.+ const health = interpretMcpTestResponse(GITHUB, {+ ok: false,+ error: "Client error '401 Unauthorized' for url …",+ error_kind: "connection",+ });++ expect(health).toMatchObject({ status: "failed", kind: "credentials" });+ });++ it("reports verified health when the read-only probe tool ran cleanly", () => {+ const health = interpretMcpTestResponse(GITHUB, {+ ok: true,+ tools: ["get_me", "search_code"],+ tool_result: { is_error: false, text: '{"login":"octocat"}' },+ });++ expect(health).toMatchObject({+ status: "healthy",+ verification: "verified",+ toolCount: 2,+ });+ });++ it("downgrades to connectivity-only when the probe tool is not advertised", () => {+ const health = interpretMcpTestResponse(GITHUB, {+ ok: true,+ tools: ["search_code"],+ tool_result: {+ is_error: true,+ text: "Tool 'get_me' not advertised by server",+ },+ });++ expect(health).toMatchObject({+ status: "healthy",+ verification: "connectivity-only",+ });+ });++ it("reports connectivity-only for servers without a probe spec", () => {+ const health = interpretMcpTestResponse(CUSTOM, {+ ok: true,+ tools: ["a"],+ });++ expect(health).toMatchObject({+ status: "healthy",+ verification: "connectivity-only",+ toolCount: 1,+ });+ });+});++describe("probeMcpServerHealth", () => {+ beforeEach(() => {+ __resetMcpHealthStoreForTests();+ vi.restoreAllMocks();+ });++ it("publishes checking while the probe runs, then the interpreted result", async () => {+ let resolveProbe!: (value: ExtendedMCPTestResponse) => void;+ vi.spyOn(McpService, "testServer").mockReturnValue(+ new Promise((resolve) => {+ resolveProbe = resolve;+ }),+ );+ const key = getMcpServerHealthKey(CUSTOM);++ const probe = probeMcpServerHealth(CUSTOM);+ expect(getMcpHealthSnapshot()[key]).toMatchObject({ status: "checking" });++ resolveProbe({ ok: true, tools: ["a", "b"] });+ await probe;++ expect(getMcpHealthSnapshot()[key]).toMatchObject({+ status: "healthy",+ verification: "connectivity-only",+ toolCount: 2,+ });+ });++ it("converts a thrown transport error into a failed verdict", async () => {+ vi.spyOn(McpService, "testServer").mockRejectedValue(+ new Error("network down"),+ );++ await probeMcpServerHealth(CUSTOM);++ expect(getMcpHealthSnapshot()[getMcpServerHealthKey(CUSTOM)]).toMatchObject(+ { status: "failed", kind: "unknown", error: "network down" },+ );+ });+});++describe("seedMcpServerHealth", () => {+ beforeEach(() => {+ __resetMcpHealthStoreForTests();+ });++ it("publishes the saved server's health from its pre-save test result", () => {+ seedMcpServerHealth(CUSTOM, { ok: true, tools: ["a"] }, []);++ expect(getMcpHealthSnapshot()[getMcpServerHealthKey(CUSTOM)]).toMatchObject(+ { status: "healthy" },+ );+ });++ it("skips seeding when another installed server shares the health key", () => {+ // A second install of the same catalog entry collides on the key until+ // the save suffixes its name; it must not overwrite the first card.+ const existingVerdict = {+ status: "failed",+ kind: "credentials",+ error: "bad token",+ checkedAt: 1,+ } as const;+ setMcpServerHealth(getMcpServerHealthKey(GITHUB), existingVerdict);++ seedMcpServerHealth(+ { ...GITHUB, id: "shttp-9" },+ { ok: true, tools: ["get_me"] },+ [GITHUB],+ );++ expect(getMcpHealthSnapshot()[getMcpServerHealthKey(GITHUB)]).toEqual(+ existingVerdict,+ );+ });+});diff --git a/__tests__/api/mcp-service/mcp-service.api.test.ts b/__tests__/api/mcp-service/mcp-service.api.test.tsindex eb2d6321c6..421789c96f 100644--- a/__tests__/api/mcp-service/mcp-service.api.test.ts+++ b/__tests__/api/mcp-service/mcp-service.api.test.ts@@ -218,6 +218,103 @@ describe("McpService.testServer", () => {expect(result).toEqual({ ok: true, tools: ["a", "b"] });});+ it("skips credential interpretation when the probe tool is not advertised", async () => {+ // A server variant that doesn't expose the probe tool (e.g. Slack's+ // hosted MCP) returns a deterministic "not advertised" tool error; that+ // proves nothing about credentials and must not block the install.+ const response = {+ ok: true,+ tools: ["conversations_history"],+ tool_result: {+ is_error: true,+ text: "Tool 'slack_list_channels' not advertised by server",+ },+ };+ mockTestServer.mockResolvedValue(response);++ const result = await McpService.testServer(SLACK_SERVER);++ expect(result).toEqual(response);+ });++ // -------------------------------------------------------------------------+ // Read-only credential probes for the hosted GitHub and Linear servers+ // -------------------------------------------------------------------------++ const GITHUB_SERVER: MCPServerConfig = {+ id: "shttp-0",+ type: "shttp",+ name: "github",+ url: "https://api.githubcopilot.com/mcp/",+ auth: { strategy: "api_key", value: "github_pat_LIVETOKENVALUE" },+ };++ const LINEAR_SERVER: MCPServerConfig = {+ id: "shttp-1",+ type: "shttp",+ name: "linear",+ url: "https://mcp.linear.app/mcp",+ auth: { strategy: "bearer", value: "lin_api_LIVETOKEN" },+ };++ it("attaches the read-only GitHub probe (get_me) to matching servers", async () => {+ mockTestServer.mockResolvedValue({ ok: true, tools: [] });++ await McpService.testServer(GITHUB_SERVER);++ expect(mockTestServer).toHaveBeenCalledWith(+ expect.objectContaining({+ tool_call: { name: "get_me", arguments: {} },+ }),+ );+ });++ it("attaches the read-only Linear probe (list_teams) to matching servers", async () => {+ mockTestServer.mockResolvedValue({ ok: true, tools: [] });++ await McpService.testServer(LINEAR_SERVER);++ expect(mockTestServer).toHaveBeenCalledWith(+ expect.objectContaining({+ tool_call: { name: "list_teams", arguments: {} },+ }),+ );+ });++ it("maps an errored GitHub probe call to a redacted credentials failure", async () => {+ mockTestServer.mockResolvedValue({+ ok: true,+ tools: ["get_me"],+ tool_result: {+ is_error: true,+ text: "401 for token github_pat_LIVETOKENVALUE",+ },+ });++ const result = await McpService.testServer(GITHUB_SERVER);++ // Interpretation runs on already-redacted text, so the surfaced+ // credentials error never contains the configured secret.+ expect(result).toEqual({+ ok: false,+ error: `401 for token ${REDACTED_MCP_SECRET_VALUE}`,+ error_kind: "credentials",+ });+ });++ it("redacts configured secrets from failure error text", async () => {+ mockTestServer.mockResolvedValue({+ ok: false,+ error: "handshake rejected Bearer github_pat_LIVETOKENVALUE",+ error_kind: "connection",+ });++ const result = await McpService.testServer(GITHUB_SERVER);++ expect(result).toMatchObject({ ok: false, error_kind: "connection" });+ expect(JSON.stringify(result)).not.toContain("github_pat_LIVETOKENVALUE");+ });+// -------------------------------------------------------------------------// Redacted-secret round-trip for the edit flow//diff --git a/__tests__/components/features/mcp-page/custom-server-editor.test.tsx b/__tests__/components/features/mcp-page/custom-server-editor.test.tsxindex 24855ed558..0e35016171 100644--- a/__tests__/components/features/mcp-page/custom-server-editor.test.tsx+++ b/__tests__/components/features/mcp-page/custom-server-editor.test.tsx@@ -5,6 +5,12 @@ import { AxiosError } from "axios";import { beforeEach, describe, expect, it, vi } from "vitest";import SettingsService from "#/api/settings-service/settings-service.api";import McpService from "#/api/mcp-service/mcp-service.api";+import {+ __resetMcpHealthStoreForTests,+ getMcpHealthSnapshot,+ setMcpServerHealth,+} from "#/api/mcp-health/mcp-health-store";+import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";import { ActiveBackendProvider } from "#/contexts/active-backend-context";import { CustomServerEditor } from "#/components/features/mcp-page/custom-server-editor";@@ -235,6 +241,37 @@ describe("CustomServerEditor", () => {);});+ it("reseeds the edited server's health from the fresh pre-save test", async () => {+ // Arrange: the installed card shows a failure; the user re-saves the+ // server (e.g. after fixing the credential) and the pre-save test now+ // passes. The card must flip to healthy without a page reload — the+ // server's own prior entry is overwritten, not duplicate-guarded.+ __resetMcpHealthStoreForTests();+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettingsWithMcp(),+ );+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);+ const key = getMcpServerHealthKey(EDIT_STDIO_SERVER);+ setMcpServerHealth(key, {+ status: "failed",+ kind: "credentials",+ error: "invalid_auth",+ checkedAt: 1,+ });++ const onClose = vi.fn();+ renderWith(<EditEditorOnceSettingsLoaded onClose={onClose} />);+ await screen.findByTestId("mcp-custom-editor");++ // Act: save without structural changes (test passes via the beforeEach+ // McpService.testServer mock).+ fireEvent.click(screen.getByTestId("submit-button"));++ // Assert: the same health key now carries the fresh healthy verdict.+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));+ expect(getMcpHealthSnapshot()[key]).toMatchObject({ status: "healthy" });+ });+it("persists OAuth state returned by the connection test when editing", async () => {vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettingsWithMcp({diff --git a/__tests__/components/features/mcp-page/install-server-modal.test.tsx b/__tests__/components/features/mcp-page/install-server-modal.test.tsxindex 99e62d1a59..3f7a993393 100644--- a/__tests__/components/features/mcp-page/install-server-modal.test.tsx+++ b/__tests__/components/features/mcp-page/install-server-modal.test.tsx@@ -3,6 +3,11 @@ import { render, screen, fireEvent, waitFor } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import SettingsService from "#/api/settings-service/settings-service.api";import McpService from "#/api/mcp-service/mcp-service.api";+import {+ __resetMcpHealthStoreForTests,+ getMcpHealthSnapshot,+} from "#/api/mcp-health/mcp-health-store";+import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";import { SecretsService } from "#/api/secrets-service";import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";import { ActiveBackendProvider } from "#/contexts/active-backend-context";@@ -47,7 +52,7 @@ describe("InstallServerModal", () => {.mockResolvedValue(true);const onClose = vi.fn();- renderWith(<InstallServerModal entry={slack} onClose={onClose} />);+ renderWith(<InstallServerModal existingServers={[]} entry={slack} onClose={onClose} />);await screen.findByTestId("mcp-install-modal");@@ -81,6 +86,45 @@ describe("InstallServerModal", () => {expect(onClose).toHaveBeenCalled();});+ it("seeds the new card's health from the pre-save connection test", async () => {+ // Arrange: a fresh install whose pre-save test passes. Its card must+ // show a verdict immediately after install, without a second probe.+ __resetMcpHealthStoreForTests();+ const slack = MCP_MARKETPLACE.find((e) => e.id === "slack")!;+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);++ renderWith(+ <InstallServerModal existingServers={[]} entry={slack} onClose={vi.fn()} />,+ );+ await screen.findByTestId("mcp-install-modal");++ // Act: complete the install.+ fireEvent.change(screen.getByTestId("mcp-install-field-SLACK_BOT_TOKEN"), {+ target: { value: "xoxb-abc" },+ });+ fireEvent.change(screen.getByTestId("mcp-install-field-SLACK_TEAM_ID"), {+ target: { value: "T01" },+ });+ fireEvent.click(screen.getByTestId("mcp-install-submit"));++ // Assert: the health store carries the saved config's verdict (the+ // mocked test returns no tool_result, so it proves connectivity only).+ const expectedKey = getMcpServerHealthKey({+ id: "irrelevant-for-key",+ type: "stdio",+ name: "slack",+ command: "npx",+ args: ["-y", "@zencoderai/slack-mcp-server"],+ env: { SLACK_TEAM_ID: "T01", SLACK_BOT_TOKEN: "xoxb-abc" },+ });+ await waitFor(() =>+ expect(getMcpHealthSnapshot()[expectedKey]).toMatchObject({+ status: "healthy",+ verification: "connectivity-only",+ }),+ );+ });+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@@ -94,7 +138,7 @@ describe("InstallServerModal", () => {.mockResolvedValue(true);const onClose = vi.fn();- renderWith(<InstallServerModal entry={tavily} onClose={onClose} />);+ renderWith(<InstallServerModal existingServers={[]} entry={tavily} onClose={onClose} />);await screen.findByTestId("mcp-install-modal");@@ -148,7 +192,7 @@ describe("InstallServerModal", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderWith(<InstallServerModal entry={entry} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={entry} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");@@ -192,7 +236,7 @@ describe("InstallServerModal", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderWith(<InstallServerModal entry={entry} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={entry} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");// The add-mcp-server mutation bails when useSettings() hasn't@@ -240,7 +284,7 @@ describe("InstallServerModal", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderWith(<InstallServerModal entry={entry} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={entry} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");await waitFor(() => expect(getSpy).toHaveBeenCalled());fireEvent.click(screen.getByTestId("mcp-install-submit"));@@ -303,7 +347,7 @@ describe("InstallServerModal", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderWith(<InstallServerModal entry={entry} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={entry} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");await waitFor(() => expect(SettingsService.getSettings).toHaveBeenCalled());@@ -382,7 +426,7 @@ describe("InstallServerModal", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderWith(<InstallServerModal entry={entry} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={entry} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");await waitFor(() => expect(SettingsService.getSettings).toHaveBeenCalled());@@ -431,7 +475,7 @@ describe("InstallServerModal", () => {.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);- renderWith(<InstallServerModal entry={linear} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={linear} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");// Wait for useSettings() so the add-mcp-server mutation doesn't bail.await waitFor(() => expect(getSpy).toHaveBeenCalled());@@ -470,7 +514,7 @@ describe("InstallServerModal", () => {it("closes from the top-right close button", async () => {const onClose = vi.fn();const slack = MCP_MARKETPLACE.find((e) => e.id === "slack")!;- renderWith(<InstallServerModal entry={slack} onClose={onClose} />);+ renderWith(<InstallServerModal existingServers={[]} entry={slack} onClose={onClose} />);await screen.findByTestId("mcp-install-modal");fireEvent.click(screen.getByTestId("mcp-install-modal-close"));@@ -480,7 +524,7 @@ describe("InstallServerModal", () => {it("places Cancel before Install in the footer so the dominant action is the last focusable button", async () => {// Arrange: render with any marketplace entry so the footer is mounted.const slack = MCP_MARKETPLACE.find((e) => e.id === "slack")!;- renderWith(<InstallServerModal entry={slack} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={slack} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");// Act: locate both footer buttons.@@ -523,7 +567,7 @@ describe("InstallServerModal", () => {],};- renderWith(<InstallServerModal entry={entry} onClose={onClose} />);+ renderWith(<InstallServerModal existingServers={[]} entry={entry} onClose={onClose} />);await screen.findByTestId("mcp-install-modal");// Wait for settings to load so the mutation isn't a no-op.@@ -554,7 +598,7 @@ describe("InstallServerModal", () => {error_kind: "credentials",});- renderWith(<InstallServerModal entry={slack} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={slack} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");// Act: fill the required fields and install.@@ -604,7 +648,7 @@ describe("InstallServerModal", () => {],};- renderWith(<InstallServerModal entry={entry} onClose={onClose} />);+ renderWith(<InstallServerModal existingServers={[]} entry={entry} onClose={onClose} />);await screen.findByTestId("mcp-install-modal");await waitFor(() => expect(SettingsService.getSettings).toHaveBeenCalled());@@ -643,7 +687,7 @@ describe("InstallServerModal", () => {],};- renderWith(<InstallServerModal entry={entry} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={entry} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");await waitFor(() => expect(SettingsService.getSettings).toHaveBeenCalled());@@ -741,7 +785,7 @@ describe("InstallServerModal", () => {});it("pre-checks the toggle for password-type envFields", async () => {- renderWith(<InstallServerModal entry={STDIO_ENTRY} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={STDIO_ENTRY} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");const toggle = screen.getByTestId("mcp-install-save-secret-API_KEY");@@ -749,7 +793,7 @@ describe("InstallServerModal", () => {});it("leaves non-password envFields unchecked by default", async () => {- renderWith(<InstallServerModal entry={STDIO_ENTRY} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={STDIO_ENTRY} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");const toggle = screen.getByTestId("mcp-install-save-secret-USERNAME");@@ -757,7 +801,7 @@ describe("InstallServerModal", () => {});it("does not render a toggle for argFields", async () => {- renderWith(<InstallServerModal entry={STDIO_ENTRY} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={STDIO_ENTRY} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");expect(@@ -766,7 +810,7 @@ describe("InstallServerModal", () => {});it("toggling the checkbox updates its checked state", async () => {- renderWith(<InstallServerModal entry={STDIO_ENTRY} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={STDIO_ENTRY} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");// USERNAME starts unchecked; clicking it should flip to checked.@@ -784,7 +828,7 @@ describe("InstallServerModal", () => {it("setValue preserves savedAsSecret state when a field value changes", async () => {// Before the ...prev bug-fix in setValue, calling onChange on any field// would reset savedAsSecret to {}, unchecking all toggles silently.- renderWith(<InstallServerModal entry={STDIO_ENTRY} onClose={vi.fn()} />);+ renderWith(<InstallServerModal existingServers={[]} entry={STDIO_ENTRY} onClose={vi.fn()} />);await screen.findByTestId("mcp-install-modal");// API_KEY starts pre-checked. Typing a new value should leave it checked.@@ -799,7 +843,7 @@ describe("InstallServerModal", () => {it("calls createSecret for checked envFields after a successful install", async () => {vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);const onClose = vi.fn();- renderWith(<InstallServerModal entry={STDIO_ENTRY} onClose={onClose} />);+ renderWith(<InstallServerModal existingServers={[]} entry={STDIO_ENTRY} onClose={onClose} />);await screen.findByTestId("mcp-install-modal");await waitFor(() =>expect(SettingsService.getSettings).toHaveBeenCalled(),@@ -830,7 +874,7 @@ describe("InstallServerModal", () => {it("saves hosted MCP credentials as named secrets when configured", async () => {vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);const onClose = vi.fn();- renderWith(<InstallServerModal entry={SHTTP_ENTRY} onClose={onClose} />);+ renderWith(<InstallServerModal existingServers={[]} entry={SHTTP_ENTRY} onClose={onClose} />);await screen.findByTestId("mcp-install-modal");await waitFor(() =>expect(SettingsService.getSettings).toHaveBeenCalled(),@@ -879,6 +923,7 @@ describe("InstallServerModal", () => {renderWith(<InstallServerModal+ existingServers={[]}entry={SHTTP_ENTRY}onClose={onClose}onSuccess={onSuccess}@@ -913,7 +958,7 @@ describe("InstallServerModal", () => {it("does not call createSecret when all toggles are unchecked before install", async () => {vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);const onClose = vi.fn();- renderWith(<InstallServerModal entry={STDIO_ENTRY} onClose={onClose} />);+ renderWith(<InstallServerModal existingServers={[]} entry={STDIO_ENTRY} onClose={onClose} />);await screen.findByTestId("mcp-install-modal");await waitFor(() =>expect(SettingsService.getSettings).toHaveBeenCalled(),@@ -942,7 +987,7 @@ describe("InstallServerModal", () => {new Error("forbidden"),);const onClose = vi.fn();- renderWith(<InstallServerModal entry={STDIO_ENTRY} onClose={onClose} />);+ renderWith(<InstallServerModal existingServers={[]} entry={STDIO_ENTRY} onClose={onClose} />);await screen.findByTestId("mcp-install-modal");await waitFor(() =>expect(SettingsService.getSettings).toHaveBeenCalled(),diff --git a/__tests__/components/features/mcp-page/mcp-server-health.test.tsx b/__tests__/components/features/mcp-page/mcp-server-health.test.tsxnew file mode 100644index 0000000000..4373dab31b--- /dev/null+++ b/__tests__/components/features/mcp-page/mcp-server-health.test.tsx@@ -0,0 +1,204 @@+import React from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { __resetMcpHealthStoreForTests } from "#/api/mcp-health/mcp-health-store";+import McpService from "#/api/mcp-service/mcp-service.api";+import SettingsService from "#/api/settings-service/settings-service.api";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import { InstalledServerCard } from "#/components/features/mcp-page/installed-server-card";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";+import type { ExtendedMCPTestResponse, MCPServerConfig } from "#/types/mcp-server";++const CUSTOM_SERVER: MCPServerConfig = {+ id: "shttp-0",+ type: "shttp",+ name: "custom",+ url: "https://mcp.example.com/mcp",+};++/** Matches the catalog `github` entry (probe spec + docsUrl). */+const GITHUB_SERVER: MCPServerConfig = {+ id: "shttp-0",+ type: "shttp",+ name: "github",+ url: "https://api.githubcopilot.com/mcp/",+ auth: { strategy: "api_key", value: "github_pat_x" },+};++const OAUTH_SERVER: MCPServerConfig = {+ id: "shttp-0",+ type: "shttp",+ name: "my-oauth",+ url: "https://mcp.oauth.example/mcp",+ auth: { strategy: "oauth2" },+};++function renderCard(+ server: MCPServerConfig,+ { onEdit = vi.fn(), onDelete = vi.fn() } = {},+) {+ render(+ <InstalledServerCard server={server} onEdit={onEdit} onDelete={onDelete} />,+ {+ wrapper: ({ children }) => (+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ <ActiveBackendProvider>{children}</ActiveBackendProvider>+ </QueryClientProvider>+ ),+ },+ );+ return { onEdit, onDelete };+}++const healthDot = () => screen.getByTestId("mcp-health-dot");+const probeButton = (id: string) =>+ screen.getByTestId(`mcp-health-probe-${id}`);++describe("InstalledServerCard connection health", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ __resetMcpHealthStoreForTests();+ // The backend registry persists to localStorage; wipe it before the+ // reset re-reads storage so each test starts on the default local backend.+ window.localStorage.clear();+ __resetActiveStoreForTests();+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ MOCK_DEFAULT_USER_SETTINGS,+ );+ });++ it("probes on demand: unchecked → checking → healthy with connectivity-only labeling", async () => {+ let resolveProbe!: (value: ExtendedMCPTestResponse) => void;+ vi.spyOn(McpService, "testServer").mockReturnValue(+ new Promise((resolve) => {+ resolveProbe = resolve;+ }),+ );+ renderCard(CUSTOM_SERVER);+ expect(healthDot()).toHaveAttribute("data-status", "unchecked");++ fireEvent.click(probeButton(CUSTOM_SERVER.id));+ expect(healthDot()).toHaveAttribute("data-status", "checking");++ resolveProbe({ ok: true, tools: ["a", "b"] });+ await waitFor(() =>+ expect(healthDot()).toHaveAttribute("data-status", "healthy-connectivity"),+ );+ // The explicit "proves connectivity only" hint must accompany the result.+ expect(+ screen.getByText("MCP$HEALTH_CONNECTIVITY_ONLY_HINT"),+ ).toBeInTheDocument();+ });++ it("offers Retry, Update credentials, and docs on a credentials failure, routing the fix to the editor only", async () => {+ vi.spyOn(McpService, "testServer").mockResolvedValue({+ ok: false,+ error: "invalid_auth",+ error_kind: "credentials",+ });+ const { onEdit } = renderCard(GITHUB_SERVER);++ fireEvent.click(probeButton(GITHUB_SERVER.id));+ await waitFor(() =>+ expect(healthDot()).toHaveAttribute("data-status", "failed"),+ );++ // Probing must not have bubbled into the card's edit action.+ expect(onEdit).not.toHaveBeenCalled();+ expect(probeButton(GITHUB_SERVER.id)).toHaveTextContent("MCP$HEALTH_RETRY");+ expect(+ screen.getByRole("link", { name: "MCP$VIEW_DOCS" }),+ ).toHaveAttribute("href", "https://github.com/github/github-mcp-server");++ fireEvent.click(+ screen.getByTestId(`mcp-health-update-credentials-${GITHUB_SERVER.id}`),+ );+ expect(onEdit).toHaveBeenCalledTimes(1);+ });++ it("Retry re-probes and moves the card to healthy in place", async () => {+ vi.spyOn(McpService, "testServer")+ .mockResolvedValueOnce({+ ok: false,+ error: "refused",+ error_kind: "connection",+ })+ .mockResolvedValueOnce({ ok: true, tools: ["a"] });+ renderCard(CUSTOM_SERVER);++ fireEvent.click(probeButton(CUSTOM_SERVER.id));+ await waitFor(() =>+ expect(healthDot()).toHaveAttribute("data-status", "failed"),+ );++ fireEvent.click(probeButton(CUSTOM_SERVER.id));+ await waitFor(() =>+ expect(healthDot()).toHaveAttribute("data-status", "healthy-connectivity"),+ );+ });++ it("renders no health section on cloud backends", () => {+ setRegisteredBackends([+ {+ id: "cloud-1",+ name: "Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "k",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud-1" });++ renderCard(CUSTOM_SERVER);++ expect(+ screen.queryByTestId(`mcp-server-health-${CUSTOM_SERVER.id}`),+ ).not.toBeInTheDocument();+ });++ it("re-authorizes a failed OAuth server and persists the refreshed state", async () => {+ vi.spyOn(McpService, "testServer").mockResolvedValue({+ ok: false,+ error: "token expired",+ error_kind: "unknown",+ });+ vi.spyOn(McpService, "authorizeOAuth").mockResolvedValue({+ ok: true,+ tools: [],+ oauth_state: { tokens: { access_token: "fresh-access-token" } },+ });+ const saveSpy = vi+ .spyOn(SettingsService, "saveSettings")+ .mockResolvedValue(true);+ renderCard(OAUTH_SERVER);++ fireEvent.click(probeButton(OAUTH_SERVER.id));+ await waitFor(() =>+ expect(healthDot()).toHaveAttribute("data-status", "failed"),+ );++ fireEvent.click(+ screen.getByTestId(`mcp-health-reauthorize-${OAUTH_SERVER.id}`),+ );++ await waitFor(() =>+ expect(healthDot()).toHaveAttribute("data-status", "healthy-connectivity"),+ );+ 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(+ "fresh-access-token",+ );+ });+});diff --git a/__tests__/hooks/mutation/use-delete-mcp-server.test.ts b/__tests__/hooks/mutation/use-delete-mcp-server.test.tsnew file mode 100644index 0000000000..6c2ed5477f--- /dev/null+++ b/__tests__/hooks/mutation/use-delete-mcp-server.test.ts@@ -0,0 +1,74 @@+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 from "#/api/settings-service/settings-service.api";+import {+ __resetMcpHealthStoreForTests,+ getMcpHealthSnapshot,+ setMcpServerHealth,+} from "#/api/mcp-health/mcp-health-store";+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 } },+ });+ function Wrapper({ children }: { children: React.ReactNode }) {+ return React.createElement(+ QueryClientProvider,+ { client: queryClient },+ children,+ );+ }+ return Wrapper;+};++describe("useDeleteMcpServer - health reset", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ __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.+ const target: MCPServerConfig = {+ id: "shttp-0",+ type: "shttp",+ name: "custom",+ url: "https://mcp.example.com/mcp",+ };+ useSettingsMock.mockReturnValue({+ data: {+ agent_settings: {+ mcp_config: { custom: { url: target.url, transport: "http" } },+ },+ },+ });+ const key = getMcpServerHealthKey(target);+ setMcpServerHealth(key, {+ status: "healthy",+ verification: "verified",+ 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-update-mcp-server.test.ts b/__tests__/hooks/mutation/use-update-mcp-server.test.tsindex 54435b3352..cd6d29a1d1 100644--- a/__tests__/hooks/mutation/use-update-mcp-server.test.ts+++ b/__tests__/hooks/mutation/use-update-mcp-server.test.ts@@ -13,6 +13,13 @@ vi.mock("#/hooks/query/use-settings", () => ({}));import { useUpdateMcpServer } from "#/hooks/mutation/use-update-mcp-server";+import {+ __resetMcpHealthStoreForTests,+ getMcpHealthSnapshot,+ setMcpServerHealth,+} from "#/api/mcp-health/mcp-health-store";+import type { MCPServerConfig } from "#/types/mcp-server";+import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";const createWrapper = () => {const queryClient = new QueryClient({@@ -95,3 +102,45 @@ describe("useUpdateMcpServer - stdio credential preservation", () => {);});});++describe("useUpdateMcpServer - health reset", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ __resetMcpHealthStoreForTests();+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);+ });++ 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.+ const server: MCPServerConfig = {+ id: "shttp-0",+ type: "shttp",+ name: "custom",+ url: "https://mcp.example.com/mcp",+ };+ useSettingsMock.mockReturnValue({+ data: {+ agent_settings: {+ mcp_config: { custom: { url: server.url, transport: "http" } },+ },+ },+ });+ const key = getMcpServerHealthKey(server);+ setMcpServerHealth(key, {+ status: "healthy",+ verification: "verified",+ toolCount: 1,+ checkedAt: 1,+ });++ const { result } = renderHook(() => useUpdateMcpServer(), {+ wrapper: createWrapper(),+ });+ await result.current.mutateAsync({ serverId: server.id, server });++ await waitFor(() =>+ expect(getMcpHealthSnapshot()[key]).toBeUndefined(),+ );+ });+});diff --git a/__tests__/utils/mcp-server-health-key.test.ts b/__tests__/utils/mcp-server-health-key.test.tsnew file mode 100644index 0000000000..c3a268ad4f--- /dev/null+++ b/__tests__/utils/mcp-server-health-key.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from "vitest";+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 GITHUB: MCPServerConfig = {+ id: "shttp-0",+ type: "shttp",+ name: "github",+ url: "https://api.githubcopilot.com/mcp/",+ auth: { strategy: "api_key", value: "github_pat_real" },+};++describe("getMcpServerHealthKey", () => {+ it("is stable across positional ids and secret-value forms of the same server", () => {+ // The same stored server appears with plaintext at install time, the+ // redaction placeholder after a settings read, and a shifted positional+ // id after an unrelated delete — all must share one health entry.+ const redactedLater: MCPServerConfig = {+ ...GITHUB,+ id: "shttp-3",+ auth: { strategy: "api_key", value: REDACTED_MCP_SECRET_VALUE },+ };++ expect(getMcpServerHealthKey(redactedLater)).toBe(+ getMcpServerHealthKey(GITHUB),+ );+ });++ it("distinguishes same-shaped servers by name", () => {+ // Duplicate installs of one catalog entry are stored as `github` and+ // `github_1`; their credentials (and health) are independent.+ const second: MCPServerConfig = { ...GITHUB, name: "github_1" };++ expect(getMcpServerHealthKey(second)).not.toBe(+ getMcpServerHealthKey(GITHUB),+ );+ });++ it("changes when the structural config changes", () => {+ const movedUrl: MCPServerConfig = {+ ...GITHUB,+ url: "https://other.example.com/mcp",+ };++ expect(getMcpServerHealthKey(movedUrl)).not.toBe(+ getMcpServerHealthKey(GITHUB),+ );+ });++ it("tracks stdio env structure but not env values", () => {+ const stdio: MCPServerConfig = {+ id: "stdio-0",+ type: "stdio",+ name: "slack",+ command: "npx",+ args: ["-y", "@zencoderai/slack-mcp-server"],+ env: { SLACK_BOT_TOKEN: "xoxb-one" },+ };+ const rotatedToken: MCPServerConfig = {+ ...stdio,+ env: { SLACK_BOT_TOKEN: "xoxb-two" },+ };+ const extraEnvVar: MCPServerConfig = {+ ...stdio,+ env: { SLACK_BOT_TOKEN: "xoxb-one", SLACK_TEAM_ID: "T01" },+ };++ expect(getMcpServerHealthKey(rotatedToken)).toBe(+ getMcpServerHealthKey(stdio),+ );+ expect(getMcpServerHealthKey(extraEnvVar)).not.toBe(+ getMcpServerHealthKey(stdio),+ );+ });+});diff --git a/__tests__/utils/redact-mcp-secrets.test.ts b/__tests__/utils/redact-mcp-secrets.test.tsnew file mode 100644index 0000000000..425281b33f--- /dev/null+++ b/__tests__/utils/redact-mcp-secrets.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from "vitest";+import type { MCPServerConfig } from "#/types/mcp-server";+import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";+import { redactMcpSecrets } from "#/utils/redact-mcp-secrets";++describe("redactMcpSecrets", () => {+ it("masks configured secret values wherever they appear in the text", () => {+ const server: MCPServerConfig = {+ id: "stdio-0",+ type: "stdio",+ command: "npx",+ env: { API_TOKEN: "env-secret-value" },+ };++ const redacted = redactMcpSecrets(+ "spawn failed: API_TOKEN=env-secret-value was rejected",+ server,+ );++ expect(redacted).toBe(+ `spawn failed: API_TOKEN=${REDACTED_MCP_SECRET_VALUE} was rejected`,+ );+ });++ it("masks secrets embedded in the server URL (userinfo and secret-named query params)", () => {+ const server: MCPServerConfig = {+ id: "shttp-0",+ type: "shttp",+ url: "https://user:[email protected]/mcp?api_key=querysecret456",+ };++ const redacted = redactMcpSecrets(+ "401 for url https://user:[email protected]/mcp?api_key=querysecret456",+ server,+ );++ expect(redacted).not.toContain("urlpass123");+ expect(redacted).not.toContain("querysecret456");+ });++ it("masks well-known token shapes even without a server config", () => {+ const redacted = redactMcpSecrets(+ "rejected github_pat_ABCDEFGHIJKLMNOPQRSTUV and xoxb-1234-abcd " ++ "with header Bearer sometoken12345",+ );++ expect(redacted).not.toContain("github_pat_ABCDEFGHIJKLMNOPQRSTUV");+ expect(redacted).not.toContain("xoxb-1234-abcd");+ expect(redacted).not.toContain("sometoken12345");+ expect(redacted).toContain(REDACTED_MCP_SECRET_VALUE);+ });++ it("does not treat the redaction placeholder or very short values as secrets", () => {+ const server: MCPServerConfig = {+ id: "stdio-0",+ type: "stdio",+ command: "npx",+ env: { UNCHANGED: REDACTED_MCP_SECRET_VALUE, REGION: "eu" },+ };++ // "eu" appears inside ordinary words; masking it would mangle the text.+ const text = "could not resolve eu endpoint";++ expect(redactMcpSecrets(text, server)).toBe(text);+ });+});diff --git a/src/api/mcp-health/mcp-health-store.ts b/src/api/mcp-health/mcp-health-store.tsnew file mode 100644index 0000000000..a410305b40--- /dev/null+++ b/src/api/mcp-health/mcp-health-store.ts@@ -0,0 +1,79 @@+import type { McpServerHealth } from "#/types/mcp-health";++type Listener = () => void;++export type McpHealthMap = Record<string, McpServerHealth>;++/**+ * In-memory MCP connection-health store, keyed by+ * `getMcpServerHealthKey(server)`. Mirrors the module-store shape of+ * `#/api/backend-registry/health-store` but is deliberately NOT persisted:+ * a health verdict is only as fresh as its probe, so a page reload resets+ * every server to "unchecked" instead of resurrecting a possibly-stale+ * "healthy".+ */+let healthMap: McpHealthMap = {};+const listeners = new Set<Listener>();+let nextCheckId = 1;++function commit(next: McpHealthMap): void {+ healthMap = next;+ listeners.forEach((listener) => listener());+}++export function getMcpHealthSnapshot(): McpHealthMap {+ return healthMap;+}++export function subscribeMcpHealth(listener: Listener): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/** Mark a probe as in flight and return its id for `resolveMcpHealthCheck`. */+export function beginMcpHealthCheck(key: string): number {+ const checkId = nextCheckId;+ nextCheckId += 1;+ commit({ ...healthMap, [key]: { status: "checking", checkId } });+ return checkId;+}++/**+ * Commit a probe result, but only while the entry is still the `checking`+ * state that probe created. A slow older probe can never overwrite a newer+ * probe's result, and a probe whose server was edited, deleted, or reseeded+ * mid-flight (entry cleared or replaced) is silently dropped — a stale+ * check can never land a false verdict.+ */+export function resolveMcpHealthCheck(+ key: string,+ checkId: number,+ health: McpServerHealth,+): void {+ const current = healthMap[key];+ if (current?.status !== "checking" || current.checkId !== checkId) {+ return;+ }+ commit({ ...healthMap, [key]: health });+}++/** Unconditional write — used to seed health from a pre-save test result. */+export function setMcpServerHealth(key: string, health: McpServerHealth): void {+ commit({ ...healthMap, [key]: health });+}++/** Drop the entry (back to "unchecked") — used when a server changes or is deleted. */+export function clearMcpServerHealth(key: string): void {+ if (!(key in healthMap)) return;+ const { [key]: _removed, ...rest } = healthMap;+ commit(rest);+}++/** Test-only: reset state and listeners. */+export function __resetMcpHealthStoreForTests(): void {+ healthMap = {};+ listeners.clear();+ nextCheckId = 1;+}diff --git a/src/api/mcp-health/probe-mcp-server-health.ts b/src/api/mcp-health/probe-mcp-server-health.tsnew file mode 100644index 0000000000..0bff9a5b72--- /dev/null+++ b/src/api/mcp-health/probe-mcp-server-health.ts@@ -0,0 +1,135 @@+import McpService from "#/api/mcp-service/mcp-service.api";+import type { McpServerHealth } from "#/types/mcp-health";+import type {+ ExtendedMCPTestResponse,+ MCPServerConfig,+} from "#/types/mcp-server";+import { getCredentialValidationForServer } from "#/utils/mcp-credential-validation";+import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";+import { redactMcpSecrets } from "#/utils/redact-mcp-secrets";+import {+ beginMcpHealthCheck,+ resolveMcpHealthCheck,+ setMcpServerHealth,+} from "./mcp-health-store";++/**+ * Conservative auth-failure sniffing for hosted servers that reject a bad+ * token at the HTTP handshake: the backend can only classify those as+ * `connection`/`unknown` (the MCP connection itself failed), but the+ * guidance the user needs is the credentials one.+ */+const AUTH_FAILURE_TEXT =+ /\b(401|403)\b|unauthorized|forbidden|invalid[ _-]?(token|credentials?|api[ _-]?key)/i;++function failedHealth(+ server: MCPServerConfig,+ error: unknown,+): McpServerHealth {+ const message = error instanceof Error ? error.message : String(error);+ return {+ status: "failed",+ kind: "unknown",+ error: redactMcpSecrets(message, server),+ checkedAt: Date.now(),+ };+}++/**+ * Map a test/OAuth probe response (already secret-redacted and+ * credential-interpreted by `McpService`) to a card health state.+ *+ * `verified` requires the catalog entry's read-only probe tool to have been+ * advertised AND invoked without error; everything else that connected is+ * `connectivity-only` — truthfully labeled, never silently upgraded.+ */+export function interpretMcpTestResponse(+ server: MCPServerConfig,+ response: ExtendedMCPTestResponse,+): McpServerHealth {+ const checkedAt = Date.now();+ if (!response.ok) {+ const kind =+ (response.error_kind === "connection" ||+ response.error_kind === "unknown") &&+ AUTH_FAILURE_TEXT.test(response.error)+ ? "credentials"+ : response.error_kind;+ return { status: "failed", kind, error: response.error, checkedAt };+ }+ const validation = getCredentialValidationForServer(server);+ const verified =+ !!validation &&+ response.tools.includes(validation.toolCall.name) &&+ !!response.tool_result &&+ !response.tool_result.is_error;+ return {+ status: "healthy",+ verification: verified ? "verified" : "connectivity-only",+ toolCount: response.tools.length,+ checkedAt,+ };+}++/** Run the non-mutating connection probe and publish the result. */+export async function probeMcpServerHealth(+ server: MCPServerConfig,+): Promise<void> {+ const key = getMcpServerHealthKey(server);+ const checkId = beginMcpHealthCheck(key);+ let health: McpServerHealth;+ try {+ const response = await McpService.testServer(server);+ health = interpretMcpTestResponse(server, response);+ } catch (error) {+ health = failedHealth(server, error);+ }+ resolveMcpHealthCheck(key, checkId, health);+}++/**+ * Run the interactive OAuth authorization probe and publish the result.+ * Returns the raw response (null on transport error) so the caller can+ * persist a refreshed `oauth_state`.+ */+export async function reauthorizeMcpServerHealth(+ server: MCPServerConfig,+): Promise<ExtendedMCPTestResponse | null> {+ const key = getMcpServerHealthKey(server);+ const checkId = beginMcpHealthCheck(key);+ try {+ const response = await McpService.authorizeOAuth(server);+ resolveMcpHealthCheck(+ key,+ checkId,+ interpretMcpTestResponse(server, response),+ );+ return response;+ } catch (error) {+ resolveMcpHealthCheck(key, checkId, failedHealth(server, error));+ return null;+ }+}++/**+ * Publish a just-saved server's health from the pre-save test result the+ * install/edit flow already produced (same config, moments earlier), so its+ * card shows a verdict immediately without a second probe.+ *+ * `otherServers` are the servers whose health must NOT be overwritten —+ * callers pass the pre-save list, excluding the server being saved. When a+ * same-shape duplicate exists (health keys exclude secret values, so two+ * installs of one catalog entry can collide until the save suffixes the+ * name), the seed is skipped and the new card simply starts "unchecked".+ */+export function seedMcpServerHealth(+ server: MCPServerConfig,+ response: ExtendedMCPTestResponse,+ otherServers: MCPServerConfig[],+): void {+ const key = getMcpServerHealthKey(server);+ if (otherServers.some((other) => getMcpServerHealthKey(other) === key)) {+ return;+ }+ setMcpServerHealth(key, interpretMcpTestResponse(server, response));+}diff --git a/src/api/mcp-service/mcp-service.api.ts b/src/api/mcp-service/mcp-service.api.tsindex 0d734df4a5..66ecd6027f 100644--- a/src/api/mcp-service/mcp-service.api.ts+++ b/src/api/mcp-service/mcp-service.api.ts@@ -5,7 +5,10 @@ import {getActiveBackend,getRegisteredBackends,} from "../backend-registry/active-store";-import { getCredentialValidationForServer } from "#/utils/mcp-credential-validation";+import {+ getCredentialValidationForServer,+ type CredentialValidation,+} from "#/utils/mcp-credential-validation";import type { MCPAuthCredential } from "#/types/mcp-auth";import type {ExtendedMCPTestResponse,@@ -13,6 +16,7 @@ import type {MCPOAuthStatusResponse,MCPServerConfig,} from "#/types/mcp-server";+import { redactMcpSecrets } from "#/utils/redact-mcp-secrets";import { substituteRedactedMcpCredentials } from "./mcp-redacted-credentials";const OAUTH_MCP_TEST_TIMEOUT_SECONDS = 120;@@ -61,22 +65,81 @@ function getMcpTestTimeout(server: MCPServerConfig): number | undefined {return OAUTH_MCP_TEST_TIMEOUT_SECONDS;}-async function buildMcpTestRequest(- server: MCPServerConfig,-): Promise<ExtendedMCPTestRequest> {+async function buildMcpTestRequest(server: MCPServerConfig): Promise<{+ request: ExtendedMCPTestRequest;+ substituted: MCPServerConfig;+}> {const validation = getCredentialValidationForServer(server);- const serverSpec = toMcpServer(- await substituteRedactedMcpCredentials(server),- );+ const substituted = await substituteRedactedMcpCredentials(server);+ const serverSpec = toMcpServer(substituted);const timeout = getMcpTestTimeout(server);return {- server: serverSpec,- ...(server.name ? { name: server.name } : {}),- ...(timeout !== undefined ? { timeout } : {}),- ...(validation ? { tool_call: validation.toolCall } : {}),+ request: {+ server: serverSpec,+ ...(server.name ? { name: server.name } : {}),+ ...(timeout !== undefined ? { timeout } : {}),+ ...(validation ? { tool_call: validation.toolCall } : {}),+ },+ substituted,};}+function redactMcpTestResponse(+ result: ExtendedMCPTestResponse,+ redactionSources: (MCPServerConfig | undefined)[],+): ExtendedMCPTestResponse {+ if (!result.ok) {+ return {+ ...result,+ error: redactMcpSecrets(result.error, ...redactionSources),+ };+ }+ if (result.tool_result) {+ return {+ ...result,+ tool_result: {+ ...result.tool_result,+ text: redactMcpSecrets(result.tool_result.text, ...redactionSources),+ },+ };+ }+ return result;+}++/**+ * Display-boundary post-processing shared by the test and OAuth probes:+ * scrub secrets from error/tool-result text, then let the catalog entry's+ * credential validation turn a failed read-only tool call into a+ * `credentials` failure. The interpretation only runs when the probe tool+ * is actually advertised in `tools` — a server variant that doesn't expose+ * the tool (e.g. a hosted alternative to the stdio server the spec was+ * written for) must degrade to a connectivity-only success, not be+ * misreported as bad credentials.+ */+function finalizeMcpTestResponse(+ result: ExtendedMCPTestResponse,+ validation: CredentialValidation | undefined,+ redactionSources: (MCPServerConfig | undefined)[],+): ExtendedMCPTestResponse {+ const redacted = redactMcpTestResponse(result, redactionSources);+ if (+ redacted.ok &&+ validation &&+ redacted.tool_result &&+ redacted.tools.includes(validation.toolCall.name)+ ) {+ const credentialError = validation.interpret(redacted.tool_result);+ if (credentialError) {+ return {+ ok: false,+ error: credentialError,+ error_kind: "credentials",+ };+ }+ }+ return redacted;+}+function getMcpProbeOptions(): { host: string; apiKey?: string } {const active = getActiveBackend().backend;if (active.kind === "local") {@@ -153,21 +216,13 @@ class McpService {const { host, apiKey } = getAgentServerClientOptions();const client = new MCPClient({ host, ...(apiKey ? { apiKey } : {}) });try {- const request = await buildMcpTestRequest(server);+ const { request, substituted } = await buildMcpTestRequest(server);const result = (await client.testServer(request as MCPTestRequest,)) as ExtendedMCPTestResponse;- if (result.ok && validation && result.tool_result) {- const credentialError = validation.interpret(result.tool_result);- if (credentialError) {- return {- ok: false,- error: credentialError,- error_kind: "credentials",- };- }- }- return result;+ // Redact against both config forms: `server` may hold fresh plaintext+ // input, `substituted` the stored (encrypted) round-trip values.+ return finalizeMcpTestResponse(result, validation, [substituted, server]);} finally {client.close();}@@ -212,17 +267,20 @@ class McpService {static async authorizeOAuth(server: MCPServerConfig,): Promise<ExtendedMCPTestResponse> {+ const validation = getCredentialValidationForServer(server);+ const finalize = (result: ExtendedMCPTestResponse) =>+ finalizeMcpTestResponse(result, validation, [server]);const popup = window.open("about:blank", "_blank");const client = createMcpProbeClient();try {const start = await McpService.startOAuthWithClient(client, server);if (!start.ok || !start.job_id || !start.authorization_url) {popup?.close();- return {+ return finalize({ok: false,error: start.error || "Could not start OAuth authorization",error_kind: start.error_kind || "unknown",- };+ });}let status = await McpService.getOAuthStatusWithClient(@@ -232,7 +290,7 @@ class McpService {for (let attempt = 0; attempt < 20; attempt += 1) {if (status.status === "succeeded" || status.status === "failed") {popup?.close();- return oauthStatusToTestResponse(status);+ return finalize(oauthStatusToTestResponse(status));}if (status.callback_ready) break;await sleep(250);@@ -258,7 +316,7 @@ class McpService {);if (status.status === "succeeded" || status.status === "failed") {popup?.close();- return oauthStatusToTestResponse(status);+ return finalize(oauthStatusToTestResponse(status));}}@@ -276,7 +334,7 @@ class McpService {client: MCPClient,server: MCPServerConfig,): Promise<MCPOAuthStartResponse> {- const request = await buildMcpTestRequest(server);+ const { request } = await buildMcpTestRequest(server);return client.startOAuth(request as MCPTestRequest);}diff --git a/src/components/features/automations/recommended-automations-launcher.tsx b/src/components/features/automations/recommended-automations-launcher.tsxindex fe8a04fa8e..4c3c391cef 100644--- a/src/components/features/automations/recommended-automations-launcher.tsx+++ b/src/components/features/automations/recommended-automations-launcher.tsx@@ -235,6 +235,7 @@ export function RecommendedAutomationsLauncher({<InstallServerModalkey={installEntry.id}entry={installEntry}+ existingServers={installedMcpConfig}onClose={cancelInstallFlow}onSuccess={handleInstallSuccess}/>diff --git a/src/components/features/mcp-page/custom-server-editor.tsx b/src/components/features/mcp-page/custom-server-editor.tsxindex a8a5d566df..146a8cc58e 100644--- a/src/components/features/mcp-page/custom-server-editor.tsx+++ b/src/components/features/mcp-page/custom-server-editor.tsx@@ -9,20 +9,18 @@ import {MCPServerForm,type TestMessage,} from "#/components/features/settings/mcp-settings/mcp-server-form";+import { seedMcpServerHealth } from "#/api/mcp-health/probe-mcp-server-health";import { useAddMcpServer } from "#/hooks/mutation/use-add-mcp-server";import { useUpdateMcpServer } from "#/hooks/mutation/use-update-mcp-server";import { useDeleteMcpServer } from "#/hooks/mutation/use-delete-mcp-server";import { useTestMcpServer } from "#/hooks/mutation/use-test-mcp-server";import { useActiveBackend } from "#/contexts/active-backend-context";-import {- ExtendedMCPTestFailure,- ExtendedMCPTestResponse,- MCPServerConfig,-} from "#/types/mcp-server";+import { ExtendedMCPTestResponse, MCPServerConfig } from "#/types/mcp-server";import {displayErrorToast,displaySuccessToast,} from "#/utils/custom-toast-handlers";+import { makeMcpTestErrorMessage } from "#/utils/mcp-test-error-message";import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";import { cn } from "#/utils/utils";import { modalTitleLgClassName } from "#/utils/modal-classes";@@ -73,19 +71,6 @@ export function CustomServerEditor({const isDismissBlocked =isPending || isTesting || isOauthTesting || showDeleteConfirm;- const makeTestErrorMessage = (failure: ExtendedMCPTestFailure): string => {- switch (failure.error_kind) {- case "timeout":- return t(I18nKey.MCP$TEST_ERROR_TIMEOUT);- case "connection":- return t(I18nKey.MCP$TEST_ERROR_CONNECTION);- case "credentials":- return t(I18nKey.MCP$TEST_ERROR_CREDENTIALS, { error: failure.error });- default:- return t(I18nKey.MCP$TEST_ERROR_UNKNOWN, { error: failure.error });- }- };-const testMessage: TestMessage | null = React.useMemo(() => {const result = oauthTestResult ?? testResult;if (!result) return null;@@ -95,9 +80,28 @@ export function CustomServerEditor({text: t(I18nKey.MCP$TEST_SUCCESS, { count: result.tools.length }),};}- return { ok: false, text: makeTestErrorMessage(result) };+ return {+ ok: false,+ text: makeMcpTestErrorMessage(t, result.error_kind, result.error),+ };}, [oauthTestResult, testResult, t]);+ // A save always follows a fresh successful probe of the exact config being+ // saved, so publish that result to the card's health entry. On cloud+ // backends the probe is synthetic — never present it as a health verdict.+ const seedSavedServerHealth = (+ serverToSave: MCPServerConfig,+ result: ExtendedMCPTestResponse,+ ) => {+ if (isCloudBackend) return;+ // When editing, the server's own entry must be overwritten, so only the+ // OTHER servers guard against a same-key collision.+ const otherServers = isEditing+ ? existingServers.filter((existing) => existing.id !== server.id)+ : existingServers;+ seedMcpServerHealth(serverToSave, result, otherServers);+ };+// Shared error handler so both add and update surface backend errors// as a toast instead of failing silently — previously these calls// had no `onError` and the modal closed even on a 4xx/5xx, leaving@@ -122,14 +126,18 @@ export function CustomServerEditor({auth: { ...payload.auth!, state: result.oauth_state },}: payload;+ const onSaved = () => {+ seedSavedServerHealth(serverToSave, result);+ onClose();+ };if (isEditing) {updateMcpServer({ serverId: server.id, server: serverToSave },- { onSuccess: onClose, onError: handleError },+ { onSuccess: onSaved, onError: handleError },);} else {addMcpServer(serverToSave, {- onSuccess: onClose,+ onSuccess: onSaved,onError: handleError,});}@@ -151,14 +159,18 @@ export function CustomServerEditor({auth: { ...payload.auth, state: result.oauth_state },}: payload;+ const onSaved = () => {+ seedSavedServerHealth(serverToSave, result);+ onClose();+ };if (isEditing) {updateMcpServer({ serverId: server.id, server: serverToSave },- { onSuccess: onClose, onError: handleError },+ { onSuccess: onSaved, onError: handleError },);} else {addMcpServer(serverToSave, {- onSuccess: onClose,+ onSuccess: onSaved,onError: handleError,});}diff --git a/src/components/features/mcp-page/install-server-modal.tsx b/src/components/features/mcp-page/install-server-modal.tsxindex efd389548a..e916220d13 100644--- a/src/components/features/mcp-page/install-server-modal.tsx+++ b/src/components/features/mcp-page/install-server-modal.tsx@@ -13,8 +13,10 @@ import type {MarketplaceField,} from "@openhands/extensions/integrations";import { McpLogoBadge } from "#/components/features/mcp-logo-badge";-import { ExtendedMCPTestFailure, MCPServerConfig } from "#/types/mcp-server";+import { MCPServerConfig } from "#/types/mcp-server";import type { MCPAuthCredential } from "#/types/mcp-auth";+import { seedMcpServerHealth } from "#/api/mcp-health/probe-mcp-server-health";+import { useActiveBackend } from "#/contexts/active-backend-context";import { useAddMcpServer } from "#/hooks/mutation/use-add-mcp-server";import { useTestMcpServer } from "#/hooks/mutation/use-test-mcp-server";import { displaySuccessToast } from "#/utils/custom-toast-handlers";@@ -25,6 +27,7 @@ import {} from "#/utils/mcp-marketplace-utils";import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";import { useSaveFieldsAsSecrets } from "#/hooks/mutation/use-save-fields-as-secrets";+import { makeMcpTestErrorMessage } from "#/utils/mcp-test-error-message";import { modalTitleLgClassName } from "#/utils/modal-classes";import McpService from "#/api/mcp-service/mcp-service.api";import { toMcpServerName } from "#/utils/mcp-server-name";@@ -64,6 +67,8 @@ function renderHelperText(text: string): React.ReactNode {interface InstallServerModalProps {entry: MarketplaceEntry;+ /** Servers installed before this modal opened — guards health seeding. */+ existingServers: MCPServerConfig[];onClose: () => void;onSuccess?: (entry: MarketplaceEntry) => void;}@@ -144,6 +149,7 @@ function makeInitialState(entry: MarketplaceEntry): FieldState {// button, which opens `CustomServerEditor` instead.export function InstallServerModal({entry,+ existingServers,onClose,onSuccess,}: InstallServerModalProps) {@@ -151,6 +157,10 @@ export function InstallServerModal({const { mutate: addMcpServer, isPending: isAdding } = useAddMcpServer();const { mutate: testMcpServer, isPending: isTesting } = useTestMcpServer();const saveFieldsAsSecrets = useSaveFieldsAsSecrets();+ // Cloud backends get a synthetic test success (no local test endpoint);+ // never seed card health from it.+ const { backend } = useActiveBackend();+ const isCloudBackend = backend.kind === "cloud";const [state, setState] = React.useState<FieldState>(() =>makeInitialState(entry),@@ -225,26 +235,15 @@ export function InstallServerModal({return Promise.resolve();};- const makeTestErrorMessage = (failure: ExtendedMCPTestFailure): string => {- switch (failure.error_kind) {- case "timeout":- return t(I18nKey.MCP$TEST_ERROR_TIMEOUT);- case "connection":- return t(I18nKey.MCP$TEST_ERROR_CONNECTION);- case "credentials":- return t(I18nKey.MCP$TEST_ERROR_CREDENTIALS, { error: failure.error });- default:- return t(I18nKey.MCP$TEST_ERROR_UNKNOWN, { error: failure.error });- }- };-const submitServer = (payload: MCPServerConfig) => {if (payload.auth?.strategy === "oauth2") {setIsAuthorizingOAuth(true);void McpService.authorizeOAuth(payload).then((result) => {if (!result.ok) {- setGlobalError(makeTestErrorMessage(result));+ setGlobalError(+ makeMcpTestErrorMessage(t, result.error_kind, result.error),+ );return;}const serverToSave = result.oauth_state@@ -255,6 +254,9 @@ export function InstallServerModal({: payload;addMcpServer(serverToSave, {onSuccess: () => {+ if (!isCloudBackend) {+ seedMcpServerHealth(serverToSave, result, existingServers);+ }displaySuccessToast(t(I18nKey.MCP$INSTALL_SUCCESS));setIsFinalizingInstall(true);void (async () => {@@ -282,7 +284,9 @@ export function InstallServerModal({testMcpServer(payload, {onSuccess: (result) => {if (!result.ok) {- setGlobalError(makeTestErrorMessage(result));+ setGlobalError(+ makeMcpTestErrorMessage(t, result.error_kind, result.error),+ );// Modal stays open — do NOT call onClose.return;}@@ -295,6 +299,9 @@ export function InstallServerModal({: payload;addMcpServer(serverToSave, {onSuccess: () => {+ if (!isCloudBackend) {+ seedMcpServerHealth(serverToSave, result, existingServers);+ }displaySuccessToast(t(I18nKey.MCP$INSTALL_SUCCESS));setIsFinalizingInstall(true);void (async () => {diff --git a/src/components/features/mcp-page/installed-server-card.tsx b/src/components/features/mcp-page/installed-server-card.tsxindex 3f64588f2a..885a842c66 100644--- a/src/components/features/mcp-page/installed-server-card.tsx+++ b/src/components/features/mcp-page/installed-server-card.tsx@@ -16,6 +16,7 @@ import {extensionModuleCardSurfaceClassName,} from "#/utils/extension-module-card-classes";import { getInstalledServerTitle } from "#/utils/mcp-installed-server-display";+import { McpServerHealthSection } from "./mcp-server-health";interface InstalledServerCardProps {server: MCPServerConfig;@@ -127,6 +128,12 @@ export function InstalledServerCard({{detailLine}</p>) : null}++ <McpServerHealthSection+ server={server}+ catalog={catalog}+ onEdit={onEdit}+ /></div></div></div>diff --git a/src/components/features/mcp-page/mcp-server-health.tsx b/src/components/features/mcp-page/mcp-server-health.tsxnew file mode 100644index 0000000000..c2980304e8--- /dev/null+++ b/src/components/features/mcp-page/mcp-server-health.tsx@@ -0,0 +1,198 @@+import React from "react";+import { AxiosError } from "axios";+import { useTranslation } from "react-i18next";+import type { TFunction } from "i18next";+import { I18nKey } from "#/i18n/declaration";+import { seedMcpServerHealth } from "#/api/mcp-health/probe-mcp-server-health";+import { useActiveBackend } from "#/contexts/active-backend-context";+import { useUpdateMcpServer } from "#/hooks/mutation/use-update-mcp-server";+import { useMcpServerHealth } from "#/hooks/use-mcp-server-health";+import type { McpServerHealth } from "#/types/mcp-health";+import { MCPServerConfig } from "#/types/mcp-server";+import { displayErrorToast } from "#/utils/custom-toast-handlers";+import type { MarketplaceEntry } from "#/utils/mcp-marketplace-utils";+import { makeMcpTestErrorMessage } from "#/utils/mcp-test-error-message";+import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";+import { cn } from "#/utils/utils";++interface McpServerHealthSectionProps {+ server: MCPServerConfig;+ catalog: MarketplaceEntry | undefined;+ onEdit: () => void;+}++const DOT_CLASS_BY_STATUS: Record<McpServerHealth["status"], string> = {+ unchecked: "bg-[var(--oh-text-tertiary)]",+ checking: "bg-[var(--oh-interactive-selected)] animate-pulse",+ healthy: "bg-[var(--oh-status-success)]",+ failed: "bg-red-500",+};++const actionClassName =+ "text-xs text-[var(--oh-muted)] underline transition-colors hover:text-white disabled:cursor-not-allowed disabled:opacity-60";++function getDotStatus(health: McpServerHealth): string {+ if (health.status === "healthy") {+ return health.verification === "verified"+ ? "healthy"+ : "healthy-connectivity";+ }+ return health.status;+}++function getStatusLabel(+ t: TFunction<"openhands">,+ health: McpServerHealth,+): string {+ switch (health.status) {+ case "checking":+ return t(I18nKey.MCP$HEALTH_STATUS_CHECKING);+ case "healthy":+ return health.verification === "verified"+ ? t(I18nKey.MCP$HEALTH_STATUS_VERIFIED, { count: health.toolCount })+ : t(I18nKey.MCP$HEALTH_STATUS_CONNECTIVITY_ONLY);+ case "failed":+ return makeMcpTestErrorMessage(t, health.kind, health.error);+ default:+ return t(I18nKey.MCP$HEALTH_STATUS_UNCHECKED);+ }+}++/**+ * Connection-health row for an installed server card: status dot + label,+ * a Test connection / Retry action, and — on failure — the relevant+ * recovery actions (fix credentials, re-run OAuth, open the docs).+ *+ * Renders nothing for cloud backends: the test endpoint only exists on the+ * local agent-server (`McpService.testServer` short-circuits cloud with a+ * synthetic success that must not be presented as a health verdict).+ */+export function McpServerHealthSection({+ server,+ catalog,+ onEdit,+}: McpServerHealthSectionProps) {+ const { t } = useTranslation("openhands");+ const { backend } = useActiveBackend();+ const { health, probe, reauthorize } = useMcpServerHealth(server);+ const { mutate: updateMcpServer } = useUpdateMcpServer();++ if (backend.kind === "cloud") return null;++ const isChecking = health.status === "checking";+ const isFailed = health.status === "failed";+ const label = getStatusLabel(t, health);++ const handleReauthorize = async () => {+ const result = await reauthorize();+ if (+ !result?.ok ||+ !result.oauth_state ||+ server.auth?.strategy !== "oauth2"+ ) {+ return;+ }+ // Persist the refreshed tokens, mirroring the editor's OAuth save path.+ const serverToSave: MCPServerConfig = {+ ...server,+ auth: { ...server.auth, state: result.oauth_state },+ };+ updateMcpServer(+ { serverId: server.id, server: serverToSave },+ {+ // The update mutation clears this server's health entry; re-seed it+ // from the probe that just succeeded so the verdict survives the save.+ onSuccess: () => seedMcpServerHealth(serverToSave, result, []),+ onError: (err: unknown) =>+ displayErrorToast(+ retrieveAxiosErrorMessage(err as AxiosError) ||+ t(I18nKey.ERROR$GENERIC),+ ),+ },+ );+ };++ return (+ // Propagation stopper: the card root is a role="button" that opens the+ // editor on click/Enter; interactions inside the health row must not+ // double as "edit server".+ <div+ data-testid={`mcp-server-health-${server.id}`}+ role="presentation"+ className="flex flex-col gap-1.5"+ onClick={(event) => event.stopPropagation()}+ onKeyDown={(event) => event.stopPropagation()}+ >+ <div className="flex items-center gap-2">+ <span+ data-testid="mcp-health-dot"+ data-status={getDotStatus(health)}+ aria-hidden="true"+ className={cn(+ "inline-block h-2 w-2 shrink-0 rounded-full",+ DOT_CLASS_BY_STATUS[health.status],+ )}+ />+ <p+ data-testid={`mcp-health-label-${server.id}`}+ className={cn(+ "line-clamp-2 break-words text-xs",+ isFailed ? "text-red-500" : "text-tertiary-alt",+ )}+ title={label}+ >+ {label}+ </p>+ </div>++ {health.status === "healthy" &&+ health.verification === "connectivity-only" ? (+ <p className="text-xs text-tertiary-light">+ {t(I18nKey.MCP$HEALTH_CONNECTIVITY_ONLY_HINT)}+ </p>+ ) : null}++ <div className="flex flex-wrap items-center gap-3">+ <button+ type="button"+ data-testid={`mcp-health-probe-${server.id}`}+ className={actionClassName}+ onClick={() => void probe()}+ disabled={isChecking}+ >+ {isFailed ? t(I18nKey.MCP$HEALTH_RETRY) : t(I18nKey.MCP$TEST_BUTTON)}+ </button>+ {isFailed && health.kind === "credentials" ? (+ <button+ type="button"+ data-testid={`mcp-health-update-credentials-${server.id}`}+ className={actionClassName}+ onClick={onEdit}+ >+ {t(I18nKey.MCP$HEALTH_UPDATE_CREDENTIALS)}+ </button>+ ) : null}+ {isFailed && server.auth?.strategy === "oauth2" ? (+ <button+ type="button"+ data-testid={`mcp-health-reauthorize-${server.id}`}+ className={actionClassName}+ onClick={() => void handleReauthorize()}+ >+ {t(I18nKey.MCP$HEALTH_REAUTHORIZE)}+ </button>+ ) : null}+ {isFailed && catalog?.docsUrl ? (+ <a+ href={catalog.docsUrl}+ target="_blank"+ rel="noreferrer"+ className={actionClassName}+ >+ {t(I18nKey.MCP$VIEW_DOCS)}+ </a>+ ) : null}+ </div>+ </div>+ );+}diff --git a/src/hooks/mutation/use-delete-mcp-server.ts b/src/hooks/mutation/use-delete-mcp-server.tsindex 08860b9594..c1459bdaf1 100644--- a/src/hooks/mutation/use-delete-mcp-server.ts+++ b/src/hooks/mutation/use-delete-mcp-server.ts@@ -5,6 +5,8 @@ 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";/*** Delete an installed MCP server.@@ -77,7 +79,11 @@ export function useDeleteMcpServer() {agent_settings_diff: { mcp_config: toSdkMcpConfig(newConfig) },});},- onSuccess: () => {+ onSuccess: (_data, target) => {+ // Drop the deleted server's health entry so a later server that+ // happens to produce the same key starts "unchecked" instead of+ // inheriting this one's verdict.+ clearMcpServerHealth(getMcpServerHealthKey(target));queryClient.invalidateQueries({queryKey: SETTINGS_QUERY_KEYS.personal(),});diff --git a/src/hooks/mutation/use-update-mcp-server.ts b/src/hooks/mutation/use-update-mcp-server.tsindex 5ab0ee2c2f..8d3b495425 100644--- a/src/hooks/mutation/use-update-mcp-server.ts+++ b/src/hooks/mutation/use-update-mcp-server.ts@@ -11,7 +11,9 @@ import {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";export function useUpdateMcpServer() {const queryClient = useQueryClient();@@ -50,7 +52,11 @@ export function useUpdateMcpServer() {agent_settings_diff: { mcp_config: toSdkMcpConfig(newConfig) },});},- onSuccess: () => {+ onSuccess: (_data, 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(getMcpServerHealthKey(variables.server));queryClient.invalidateQueries({queryKey: SETTINGS_QUERY_KEYS.personal(),});diff --git a/src/hooks/use-mcp-server-health.ts b/src/hooks/use-mcp-server-health.tsnew file mode 100644index 0000000000..aa117f7f37--- /dev/null+++ b/src/hooks/use-mcp-server-health.ts@@ -0,0 +1,40 @@+import React from "react";+import {+ getMcpHealthSnapshot,+ subscribeMcpHealth,+} from "#/api/mcp-health/mcp-health-store";+import {+ probeMcpServerHealth,+ reauthorizeMcpServerHealth,+} from "#/api/mcp-health/probe-mcp-server-health";+import { UNCHECKED_MCP_HEALTH, type McpServerHealth } from "#/types/mcp-health";+import type { MCPServerConfig } from "#/types/mcp-server";+import { getMcpServerHealthKey } from "#/utils/mcp-server-health-key";++/**+ * Subscribe to an installed server's connection health and expose the+ * probe actions bound to its current config.+ */+export function useMcpServerHealth(server: MCPServerConfig) {+ const key = getMcpServerHealthKey(server);+ const health: McpServerHealth = React.useSyncExternalStore(+ subscribeMcpHealth,+ () => getMcpHealthSnapshot()[key] ?? UNCHECKED_MCP_HEALTH,+ );++ // Keep the latest config without re-creating the callbacks every render+ // (settings refetches rebuild the server objects each time).+ const serverRef = React.useRef(server);+ serverRef.current = server;++ const probe = React.useCallback(+ () => probeMcpServerHealth(serverRef.current),+ [],+ );+ const reauthorize = React.useCallback(+ () => reauthorizeMcpServerHealth(serverRef.current),+ [],+ );++ return { health, probe, reauthorize };+}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex fff215e409..04b9ae1f43 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -15163,6 +15163,142 @@"tr": "Bağlandı — {{count}} araç kullanılabilir","uk": "З'єднано — доступно інструментів: {{count}}"},+ "MCP$HEALTH_STATUS_UNCHECKED": {+ "ar": "لم يتم التحقق بعد",+ "ca": "Encara no s'ha comprovat",+ "de": "Noch nicht geprüft",+ "en": "Not checked yet",+ "es": "Aún no comprobado",+ "fr": "Pas encore vérifié",+ "it": "Non ancora verificato",+ "ja": "未確認",+ "ko-KR": "아직 확인되지 않음",+ "no": "Ikke sjekket ennå",+ "pt": "Ainda não verificado",+ "tr": "Henüz kontrol edilmedi",+ "uk": "Ще не перевірено",+ "zh-CN": "尚未检查",+ "zh-TW": "尚未檢查"+ },+ "MCP$HEALTH_STATUS_CHECKING": {+ "ar": "جارٍ التحقق من الاتصال…",+ "ca": "S'està comprovant la connexió…",+ "de": "Verbindung wird geprüft…",+ "en": "Checking connection…",+ "es": "Comprobando la conexión…",+ "fr": "Vérification de la connexion…",+ "it": "Verifica della connessione…",+ "ja": "接続を確認中…",+ "ko-KR": "연결 확인 중…",+ "no": "Sjekker tilkoblingen…",+ "pt": "Verificando a conexão…",+ "tr": "Bağlantı kontrol ediliyor…",+ "uk": "Перевірка з'єднання…",+ "zh-CN": "正在检查连接…",+ "zh-TW": "正在檢查連線…"+ },+ "MCP$HEALTH_STATUS_VERIFIED": {+ "ar": "متصل — تم التحقق من بيانات الاعتماد ({{count}} أداة/أدوات)",+ "ca": "Connectat — credencials verificades ({{count}} eina/es)",+ "de": "Verbunden — Anmeldedaten bestätigt ({{count}} Tool(s))",+ "en": "Connected — credentials verified ({{count}} tool(s))",+ "es": "Conectado — credenciales verificadas ({{count}} herramienta(s))",+ "fr": "Connecté — identifiants vérifiés ({{count}} outil(s))",+ "it": "Connesso — credenziali verificate ({{count}} strumento/i)",+ "ja": "接続済み — 認証情報を確認しました(ツール{{count}}件)",+ "ko-KR": "연결됨 — 자격 증명 확인됨 (도구 {{count}}개)",+ "no": "Tilkoblet — påloggingsinformasjonen er bekreftet ({{count}} verktøy)",+ "pt": "Conectado — credenciais verificadas ({{count}} ferramenta(s))",+ "tr": "Bağlandı — kimlik bilgileri doğrulandı ({{count}} araç)",+ "uk": "Підключено — облікові дані підтверджено ({{count}} інструмент(и))",+ "zh-CN": "已连接 — 凭据已验证({{count}} 个工具)",+ "zh-TW": "已連線 — 憑證已驗證({{count}} 個工具)"+ },+ "MCP$HEALTH_STATUS_CONNECTIVITY_ONLY": {+ "ar": "يمكن الوصول إليه — لم يتم التحقق من بيانات الاعتماد",+ "ca": "Accessible — credencials no verificades",+ "de": "Erreichbar — Anmeldedaten nicht bestätigt",+ "en": "Reachable — credentials not verified",+ "es": "Accesible — credenciales sin verificar",+ "fr": "Accessible — identifiants non vérifiés",+ "it": "Raggiungibile — credenziali non verificate",+ "ja": "接続可能 — 認証情報は未確認",+ "ko-KR": "연결 가능 — 자격 증명 미확인",+ "no": "Tilgjengelig — påloggingsinformasjonen er ikke bekreftet",+ "pt": "Acessível — credenciais não verificadas",+ "tr": "Erişilebilir — kimlik bilgileri doğrulanmadı",+ "uk": "Доступний — облікові дані не підтверджено",+ "zh-CN": "可访问 — 凭据未验证",+ "zh-TW": "可連線 — 憑證未驗證"+ },+ "MCP$HEALTH_CONNECTIVITY_ONLY_HINT": {+ "ar": "يثبت هذا الفحص فقط أنه يمكن الوصول إلى الخادم وإدراج أدواته؛ ولا يتحقق من بيانات الاعتماد الخاصة بك.",+ "ca": "Aquesta comprovació només demostra que el servidor és accessible i llista les seves eines; no verifica les vostres credencials.",+ "de": "Diese Prüfung zeigt nur, dass der Server erreichbar ist und seine Tools auflistet; Ihre Anmeldedaten werden nicht überprüft.",+ "en": "This check only proves the server is reachable and lists its tools; it does not verify your credentials.",+ "es": "Esta comprobación solo demuestra que el servidor es accesible y lista sus herramientas; no verifica tus credenciales.",+ "fr": "Cette vérification prouve uniquement que le serveur est accessible et liste ses outils ; elle ne vérifie pas vos identifiants.",+ "it": "Questo controllo dimostra solo che il server è raggiungibile ed elenca i suoi strumenti; non verifica le tue credenziali.",+ "ja": "このチェックはサーバーに接続してツール一覧を取得できることのみを確認します。認証情報の有効性は確認しません。",+ "ko-KR": "이 확인은 서버에 연결하여 도구 목록을 가져올 수 있는지만 증명하며, 자격 증명의 유효성은 확인하지 않습니다.",+ "no": "Denne sjekken viser bare at serveren er tilgjengelig og lister verktøyene; den bekrefter ikke påloggingsinformasjonen din.",+ "pt": "Esta verificação apenas comprova que o servidor está acessível e lista suas ferramentas; ela não valida suas credenciais.",+ "tr": "Bu kontrol yalnızca sunucuya erişilebildiğini ve araçlarının listelenebildiğini kanıtlar; kimlik bilgilerinizi doğrulamaz.",+ "uk": "Ця перевірка лише підтверджує, що сервер доступний і перелічує його інструменти; вона не перевіряє ваші облікові дані.",+ "zh-CN": "此检查仅证明服务器可访问并能列出其工具;不会验证您的凭据。",+ "zh-TW": "此檢查僅證明伺服器可連線並能列出其工具;不會驗證您的憑證。"+ },+ "MCP$HEALTH_RETRY": {+ "ar": "إعادة المحاولة",+ "ca": "Torna-ho a provar",+ "de": "Erneut versuchen",+ "en": "Retry",+ "es": "Reintentar",+ "fr": "Réessayer",+ "it": "Riprova",+ "ja": "再試行",+ "ko-KR": "다시 시도",+ "no": "Prøv på nytt",+ "pt": "Tentar novamente",+ "tr": "Yeniden dene",+ "uk": "Повторити",+ "zh-CN": "重试",+ "zh-TW": "重試"+ },+ "MCP$HEALTH_UPDATE_CREDENTIALS": {+ "ar": "تحديث بيانات الاعتماد",+ "ca": "Actualitza les credencials",+ "de": "Anmeldedaten aktualisieren",+ "en": "Update credentials",+ "es": "Actualizar credenciales",+ "fr": "Mettre à jour les identifiants",+ "it": "Aggiorna le credenziali",+ "ja": "認証情報を更新",+ "ko-KR": "자격 증명 업데이트",+ "no": "Oppdater påloggingsinformasjon",+ "pt": "Atualizar credenciais",+ "tr": "Kimlik bilgilerini güncelle",+ "uk": "Оновити облікові дані",+ "zh-CN": "更新凭据",+ "zh-TW": "更新憑證"+ },+ "MCP$HEALTH_REAUTHORIZE": {+ "ar": "إعادة التفويض",+ "ca": "Torna a autoritzar",+ "de": "Erneut autorisieren",+ "en": "Re-authorize",+ "es": "Volver a autorizar",+ "fr": "Réautoriser",+ "it": "Autorizza di nuovo",+ "ja": "再認可",+ "ko-KR": "다시 인증",+ "no": "Autoriser på nytt",+ "pt": "Reautorizar",+ "tr": "Yeniden yetkilendir",+ "uk": "Повторно авторизувати",+ "zh-CN": "重新授权",+ "zh-TW": "重新授權"+ },"MCP$TEST_ERROR_TIMEOUT": {"en": "Connection timed out. Check the URL and try again.","ja": "接続がタイムアウトしました。URLを確認して、もう一度お試しください。",diff --git a/src/routes/mcp.tsx b/src/routes/mcp.tsxindex cb3850256c..394fe82180 100644--- a/src/routes/mcp.tsx+++ b/src/routes/mcp.tsx@@ -182,6 +182,7 @@ export default function MCPPage() {{installEntry && (<InstallServerModalentry={installEntry}+ existingServers={allServers}onClose={() => setInstallEntry(null)}/>)}diff --git a/src/types/mcp-health.ts b/src/types/mcp-health.tsnew file mode 100644index 0000000000..a048e08201--- /dev/null+++ b/src/types/mcp-health.ts@@ -0,0 +1,27 @@+import type { ExtendedMCPTestFailureKind } from "#/types/mcp-server";++/** How strongly the last successful check proved the server works. */+export type McpHealthVerification =+ // A representative read-only tool call succeeded — credentials exercised.+ | "verified"+ // Connect + tools/list only — proves connectivity, not credentials.+ | "connectivity-only";++export type McpServerHealth =+ | { status: "unchecked" }+ | { status: "checking"; checkId: number }+ | {+ status: "healthy";+ verification: McpHealthVerification;+ toolCount: number;+ checkedAt: number;+ }+ | {+ status: "failed";+ kind: ExtendedMCPTestFailureKind;+ /** Redacted, display-safe error detail. */+ error: string;+ checkedAt: number;+ };++export const UNCHECKED_MCP_HEALTH: McpServerHealth = { status: "unchecked" };diff --git a/src/utils/mcp-credential-validation.ts b/src/utils/mcp-credential-validation.tsindex b7a261ae6a..e1558fe366 100644--- a/src/utils/mcp-credential-validation.ts+++ b/src/utils/mcp-credential-validation.ts@@ -38,7 +38,30 @@ const SLACK_AUTH_FAILURES = new Set(["token_expired",]);+/**+ * Interpreter for hosted HTTP API servers (GitHub, Linear). The service only+ * calls `interpret` when the probe tool was advertised by the server AND+ * invoked, so `is_error` here means the read-only call itself failed — for a+ * "who am I" / "list teams" probe that is an auth/permission failure.+ */+const interpretReadOnlyToolResult = (+ toolResult: MCPTestToolResult,+): string | null =>+ toolResult.is_error ? toolResult.text || "tool call failed" : null;+const VALIDATION_BY_ENTRY_ID: Record<string, CredentialValidation> = {+ github: {+ // Official GitHub MCP server (api.githubcopilot.com): read-only+ // "get details of the authenticated user".+ toolCall: { name: "get_me", arguments: {} },+ interpret: interpretReadOnlyToolResult,+ },+ linear: {+ // Linear hosted MCP (mcp.linear.app): read-only teams listing with no+ // required arguments.+ toolCall: { name: "list_teams", arguments: {} },+ interpret: interpretReadOnlyToolResult,+ },slack: {// Read-only: lists at most one channel. The Slack MCP server returns// the raw Slack API JSON ({ok: boolean, error?: string}) as text.diff --git a/src/utils/mcp-server-health-key.ts b/src/utils/mcp-server-health-key.tsnew file mode 100644index 0000000000..c8e78da926--- /dev/null+++ b/src/utils/mcp-server-health-key.ts@@ -0,0 +1,43 @@+import type { MCPServerConfig } from "#/types/mcp-server";++const sortedKeys = (record?: Record<string, string> | null): string[] =>+ Object.keys(record ?? {}).sort();++/**+ * 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:+ * 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, header+ * names, auth strategy, ...) therefore produces a new key, orphaning the old+ * health entry instead of misattributing it.+ */+export function getMcpServerHealthKey(server: MCPServerConfig): string {+ if (server.type === "stdio") {+ return JSON.stringify({+ type: server.type,+ name: server.name ?? "",+ command: server.command ?? "",+ args: server.args ?? [],+ envKeys: sortedKeys(server.env),+ });+ }+ return JSON.stringify({+ type: server.type,+ name: server.name ?? "",+ url: server.url ?? "",+ headerKeys: sortedKeys(server.headers),+ authStrategy: server.auth?.strategy ?? "",+ authHeaderName:+ server.auth?.strategy === "api_key"+ ? (server.auth.header_name ?? "")+ : "",+ authHeaderKeys:+ server.auth?.strategy === "header" ? sortedKeys(server.auth.headers) : [],+ });+}diff --git a/src/utils/mcp-test-error-message.ts b/src/utils/mcp-test-error-message.tsnew file mode 100644index 0000000000..18e1f15440--- /dev/null+++ b/src/utils/mcp-test-error-message.ts@@ -0,0 +1,25 @@+import type { TFunction } from "i18next";+import { I18nKey } from "#/i18n/declaration";+import type { ExtendedMCPTestFailureKind } from "#/types/mcp-server";++/**+ * Kind-specific, localized guidance for a failed MCP connection test.+ * `error` is interpolated for the kinds whose message surfaces the provider+ * detail — callers pass display-safe (redacted) text.+ */+export function makeMcpTestErrorMessage(+ t: TFunction<"openhands">,+ errorKind: ExtendedMCPTestFailureKind,+ error: string,+): string {+ switch (errorKind) {+ case "timeout":+ return t(I18nKey.MCP$TEST_ERROR_TIMEOUT);+ case "connection":+ return t(I18nKey.MCP$TEST_ERROR_CONNECTION);+ case "credentials":+ return t(I18nKey.MCP$TEST_ERROR_CREDENTIALS, { error });+ default:+ return t(I18nKey.MCP$TEST_ERROR_UNKNOWN, { error });+ }+}diff --git a/src/utils/redact-mcp-secrets.ts b/src/utils/redact-mcp-secrets.tsnew file mode 100644index 0000000000..6d00969b6c--- /dev/null+++ b/src/utils/redact-mcp-secrets.ts@@ -0,0 +1,130 @@+import type { MCPServerConfig } from "#/types/mcp-server";+import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";++/**+ * Minimum length for a config value to be treated as a redactable secret.+ * Shorter strings are too likely to collide with ordinary words in an+ * error message and would mangle it without hiding anything meaningful.+ */+const MIN_SECRET_LENGTH = 4;++const SECRETLIKE_PARAM_NAME = /token|key|secret|auth/i;++/**+ * Token shapes that may appear in backend error text even when the browser+ * never held the plaintext value (stored secrets round-trip encrypted and+ * are decrypted server-side, so a spawn/connect error can echo them back).+ */+const GENERIC_SECRET_PATTERNS: RegExp[] = [+ // GitHub personal access tokens (classic and fine-grained).+ /\bgh[pousr]_[A-Za-z0-9]{16,}\b/g,+ /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,+ // Slack workspace tokens (xoxb-, xoxp-, xoxs-, ...).+ /\bxox[a-z](?:-[A-Za-z0-9]+)+/g,+ // Linear API keys.+ /\blin_api_[A-Za-z0-9]{10,}\b/g,+ // JWT-shaped values (three base64url segments starting with "eyJ").+ /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\b/g,+];++// "Bearer <token>" keeps its prefix so the message stays readable.+const BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi;++function addValue(values: Set<string>, value: unknown): void {+ if (typeof value !== "string") return;+ if (value.length < MIN_SECRET_LENGTH) return;+ if (value === REDACTED_MCP_SECRET_VALUE) return;+ values.add(value);+}++function addRecordValues(+ values: Set<string>,+ record: Record<string, unknown> | null | undefined,+): void {+ for (const value of Object.values(record ?? {})) {+ addValue(values, value);+ }+}++function addUrlSecrets(values: Set<string>, rawUrl: string | undefined): void {+ if (!rawUrl) return;+ try {+ const url = new URL(rawUrl);+ addValue(values, url.username);+ addValue(values, url.password);+ addValue(values, decodeURIComponent(url.username));+ addValue(values, decodeURIComponent(url.password));+ url.searchParams.forEach((value, name) => {+ if (SECRETLIKE_PARAM_NAME.test(name)) addValue(values, value);+ });+ } catch {+ // Not a parseable URL — nothing to collect.+ }+}++function addAuthSecrets(+ values: Set<string>,+ auth: MCPServerConfig["auth"],+): void {+ if (!auth) return;+ switch (auth.strategy) {+ case "api_key":+ case "bearer":+ addValue(values, auth.value);+ break;+ case "basic":+ addValue(values, auth.username);+ addValue(values, auth.password);+ break;+ case "header":+ addRecordValues(values, auth.headers);+ break;+ case "oauth2":+ addValue(values, auth.authentication?.client_secret);+ addRecordValues(values, auth.state?.tokens);+ break;+ default:+ break;+ }+}++/**+ * Collect every secret VALUE a server config may carry, longest first so+ * replacing a shorter secret can never split a longer one that contains it.+ */+export function collectMcpSecretValues(server: MCPServerConfig): string[] {+ const values = new Set<string>();+ addRecordValues(values, server.env);+ addRecordValues(values, server.headers);+ addAuthSecrets(values, server.auth);+ addUrlSecrets(values, server.url);+ return [...values].sort((a, b) => b.length - a.length);+}++/**+ * Scrub secrets from MCP test/probe error text before it is displayed.+ * Replaces every known secret value from the given server config(s), then+ * applies generic token patterns as a safety net for plaintext the browser+ * never saw (e.g. values decrypted server-side and echoed in an error).+ */+export function redactMcpSecrets(+ text: string,+ ...servers: (MCPServerConfig | undefined)[]+): string {+ if (!text) return text;+ let redacted = text;+ for (const server of servers) {+ if (!server) continue;+ for (const value of collectMcpSecretValues(server)) {+ redacted = redacted.split(value).join(REDACTED_MCP_SECRET_VALUE);+ }+ }+ redacted = redacted.replace(+ BEARER_PATTERN,+ `Bearer ${REDACTED_MCP_SECRET_VALUE}`,+ );+ for (const pattern of GENERIC_SECRET_PATTERNS) {+ redacted = redacted.replace(pattern, REDACTED_MCP_SECRET_VALUE);+ }+ return redacted;+}diff --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 5ef407679a..76437def88 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@@ -113,12 +113,19 @@ test.describe("MCP GitHub server install flow", () => {await routeSessionApiKey(page);// Intercept the MCP test endpoint to return success; the test environment- // should not contact GitHub's hosted MCP endpoint.+ // should not contact GitHub's hosted MCP endpoint. Mirror the real+ // agent-server success shape: `tools` (a required field) lists the+ // advertised tools including the `get_me` credential probe, and+ // `tool_result` carries that read-only probe's passing outcome.await page.route("**/api/mcp/test", async (route) => {await route.fulfill({status: 200,contentType: "application/json",- body: JSON.stringify({ ok: true }),+ body: JSON.stringify({+ ok: true,+ tools: ["get_me", "list_issues"],+ tool_result: { is_error: false, text: '{"login":"octocat"}' },+ }),});});