π OpenHands: AI-Driven Development
feat: test remote MCP servers on cloud backends via the app server (#17276)
Hiep Le9c974b1d9c34
diff --git a/__tests__/api/cloud/mcp-service.test.ts b/__tests__/api/cloud/mcp-service.test.tsnew file mode 100644index 0000000000..0a19a09f88--- /dev/null+++ b/__tests__/api/cloud/mcp-service.test.ts@@ -0,0 +1,147 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import type { Backend } from "#/api/backend-registry/types";+import {+ getCloudMcpOAuthStatus,+ startCloudMcpOAuth,+ testCloudMcpServer,+} from "#/api/cloud/mcp-service.api";+import {+ getFetchCall,+ getJsonBody,+ mockJsonResponse,+} from "./fetch-test-utils";++const cloudBackend: Backend = {+ id: "prod",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "bearer-token",+ kind: "cloud",+};++const originalFetch = global.fetch;+const fetchMock = vi.fn();++beforeEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id });+ fetchMock.mockReset();+ global.fetch = fetchMock as typeof fetch;+});++afterEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ fetchMock.mockReset();+ global.fetch = originalFetch;+});++describe("testCloudMcpServer", () => {+ it("posts the probe request to /api/v1/mcp/test on the active cloud backend", async () => {+ // Arrange+ fetchMock.mockResolvedValue(+ mockJsonResponse({+ ok: false,+ error: "refused",+ error_kind: "connection",+ }),+ );+ const request = {+ name: "jira",+ server: {+ type: "http" as const,+ url: "https://mcp-jira.example.com/mcp",+ },+ timeout: 15,+ };++ // Act+ const result = await testCloudMcpServer(request);++ // Assert+ const [url, init] = getFetchCall(fetchMock);+ expect(url).toBe(`${cloudBackend.host}/api/v1/mcp/test`);+ expect(init).toMatchObject({+ method: "POST",+ headers: { Authorization: "Bearer bearer-token" },+ });+ expect(getJsonBody(init)).toEqual(request);+ expect(result).toEqual({+ ok: false,+ error: "refused",+ error_kind: "connection",+ });+ });+});++describe("startCloudMcpOAuth", () => {+ it("posts the OAuth start request to /api/v1/mcp/oauth/start", async () => {+ // Arrange+ fetchMock.mockResolvedValue(+ mockJsonResponse({+ ok: true,+ job_id: "job-1",+ authorization_url: "https://auth.example/authorize",+ }),+ );+ const request: Parameters<typeof startCloudMcpOAuth>[0] = {+ name: "atlassian",+ server: {+ type: "http",+ url: "https://mcp.atlassian.com/v1/mcp/authv2",+ auth: {+ strategy: "oauth2",+ authentication: { type: "oauth", client_auth_method: "none" },+ },+ },+ timeout: 120,+ };++ // Act+ const result = await startCloudMcpOAuth(request);++ // Assert+ const [url, init] = getFetchCall(fetchMock);+ expect(url).toBe(`${cloudBackend.host}/api/v1/mcp/oauth/start`);+ expect(init).toMatchObject({ method: "POST" });+ expect(getJsonBody(init)).toEqual(request);+ expect(result).toEqual({+ ok: true,+ job_id: "job-1",+ authorization_url: "https://auth.example/authorize",+ });+ });+});++describe("getCloudMcpOAuthStatus", () => {+ it("reads the job from /api/v1/mcp/oauth/status/{job_id}", async () => {+ // Arrange+ fetchMock.mockResolvedValue(+ mockJsonResponse({+ ok: true,+ status: "authorizing",+ job_id: "job/1",+ callback_ready: true,+ }),+ );++ // Act+ const result = await getCloudMcpOAuthStatus("job/1");++ // Assert+ const [url, init] = getFetchCall(fetchMock);+ expect(url).toBe(`${cloudBackend.host}/api/v1/mcp/oauth/status/job%2F1`);+ expect(init).toMatchObject({ method: "GET" });+ expect(result).toMatchObject({+ status: "authorizing",+ callback_ready: true,+ });+ });+});diff --git a/__tests__/api/mcp-service/mcp-service.api.test.ts b/__tests__/api/mcp-service/mcp-service.api.test.tsindex 3d2f9a3bc9..b1c81e5886 100644--- a/__tests__/api/mcp-service/mcp-service.api.test.ts+++ b/__tests__/api/mcp-service/mcp-service.api.test.ts@@ -9,8 +9,9 @@ import { REDACTED_MCP_SECRET_VALUE } from "#/utils/mcp-config";// vi.mock factories are hoisted before imports, so spy functions must be// created with vi.hoisted() to be in scope inside the factory.-const { mockTestServer } = vi.hoisted(() => ({+const { mockTestServer, mockTestCloudServer } = vi.hoisted(() => ({mockTestServer: vi.fn(),+ mockTestCloudServer: vi.fn(),}));vi.mock("@openhands/typescript-client/clients", () => ({@@ -36,6 +37,10 @@ vi.mock("#/api/backend-registry/active-store", () => ({getActiveBackend: vi.fn(),}));+vi.mock("#/api/cloud/mcp-service.api", () => ({+ testCloudMcpServer: mockTestCloudServer,+}));+const mockGetActiveBackend = vi.mocked(activeStore.getActiveBackend);const localActive = () =>@@ -379,17 +384,48 @@ describe("McpService.testServer", () => {);});- it("short-circuits with a synthetic ok response on cloud backends", async () => {- // Regression: when the active backend is cloud, the local agent-server's- // /api/mcp/test endpoint is not reachable. Previously, the helper threw+ it("short-circuits stdio servers with a synthetic ok response on cloud backends", async () => {+ // Regression: stdio servers spawn inside the cloud sandbox, which the+ // browser cannot reach. Previously, the helper threw// `NoBackendAvailableError("No backend is configured.")` which surfaced// in the install modal and blocked users from creating any MCP server// (e.g. Slack) on a cloud session.cloudActive();- const result = await McpService.testServer(SERVER);+ const result = await McpService.testServer(SLACK_SERVER);expect(result).toEqual({ ok: true, tools: [] });expect(mockTestServer).not.toHaveBeenCalled();+ expect(mockTestCloudServer).not.toHaveBeenCalled();+ });++ it("probes remote servers on cloud backends through the app server", async () => {+ cloudActive();+ mockTestCloudServer.mockResolvedValue({ ok: true, tools: ["get_me"] });+ const fetchSettings = vi.spyOn(SettingsService, "fetchSettingsFromApi");++ const result = await McpService.testServer({+ ...SERVER,+ headers: { "X-Team": "team-1" },+ auth: { strategy: "bearer", value: REDACTED_MCP_SECRET_VALUE },+ });++ expect(result).toEqual({ ok: true, tools: ["get_me"] });+ expect(mockTestServer).not.toHaveBeenCalled();+ // Unchanged secrets are restored by the app server from the stored+ // server (sent as `name`), not fetched from a local agent-server; `auth`+ // is flattened to headers the way cloud saves persist it.+ expect(fetchSettings).not.toHaveBeenCalled();+ expect(mockTestCloudServer).toHaveBeenCalledWith({+ name: SERVER.id,+ server: {+ type: "http",+ url: SERVER.url,+ headers: {+ "X-Team": "team-1",+ Authorization: `Bearer ${REDACTED_MCP_SECRET_VALUE}`,+ },+ },+ });});});diff --git a/__tests__/components/features/mcp-page/custom-server-editor.test.tsx b/__tests__/components/features/mcp-page/custom-server-editor.test.tsxindex 251ea09c24..ae1037c01f 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,11 @@ 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 {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";import {__resetMcpHealthStoreForTests,getMcpHealthSnapshot,@@ -38,6 +43,14 @@ const EDIT_OAUTH_SERVER: MCPServerConfig = {},};+const EDIT_REMOTE_SERVER: MCPServerConfig = {+ id: "jira",+ type: "shttp",+ name: "jira",+ url: "https://mcp-jira.example.com/mcp",+ auth: { strategy: "bearer", value: "**********" },+};+function buildSettingsWithMcp(overrides: Partial<Settings> = {}): Settings {return {...MOCK_DEFAULT_USER_SETTINGS,@@ -85,6 +98,22 @@ function EditEditorOnceSettingsLoaded({ onClose }: { onClose: () => void }) {);}+function EditRemoteEditorOnceSettingsLoaded({+ onClose,+}: {+ onClose: () => void;+}) {+ const { data } = useSettings();+ if (!data) return null;+ return (+ <CustomServerEditor+ server={EDIT_REMOTE_SERVER}+ existingServers={[EDIT_REMOTE_SERVER]}+ onClose={onClose}+ />+ );+}+function EditOAuthEditorOnceSettingsLoaded({onClose,}: {@@ -118,6 +147,10 @@ function renderWith(ui: React.ReactNode) {describe("CustomServerEditor", () => {beforeEach(() => {vi.restoreAllMocks();+ // 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, "createMcpServer").mockImplementation((settingsKey, server) =>SettingsService.saveSettings({@@ -270,6 +303,63 @@ describe("CustomServerEditor", () => {);});+ it("offers Test connection for remote servers on cloud backends and shows the result", async () => {+ // Arrange: a cloud backend is active and the probe (routed through the+ // app server) succeeds.+ setRegisteredBackends([+ {+ id: "cloud-1",+ name: "Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "k",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud-1" });+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettingsWithMcp(),+ );+ const testSpy = vi+ .spyOn(McpService, "testServer")+ .mockResolvedValue({ ok: true, tools: ["search_issues"] });+ renderWith(<EditRemoteEditorOnceSettingsLoaded onClose={vi.fn()} />);+ await screen.findByTestId("mcp-custom-editor");++ // Act+ fireEvent.click(screen.getByTestId("mcp-test-connection"));++ // Assert+ await waitFor(() =>+ expect(screen.getByTestId("mcp-test-message")).toHaveTextContent(+ "MCP$TEST_SUCCESS",+ ),+ );+ expect(testSpy).toHaveBeenCalledWith(+ expect.objectContaining({ type: "shttp", url: EDIT_REMOTE_SERVER.url }),+ );+ });++ it("hides Test connection for stdio servers on cloud backends", async () => {+ setRegisteredBackends([+ {+ id: "cloud-1",+ name: "Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "k",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud-1" });+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettingsWithMcp(),+ );++ renderWith(<EditEditorOnceSettingsLoaded onClose={vi.fn()} />);+ await screen.findByTestId("mcp-custom-editor");++ expect(screen.queryByTestId("mcp-test-connection")).not.toBeInTheDocument();+ });+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@@ -301,6 +391,49 @@ describe("CustomServerEditor", () => {expect(getMcpHealthSnapshot()[key]).toMatchObject({ status: "healthy" });});+ it("runs the OAuth flow from Test connection on cloud backends", async () => {+ // Arrange: a cloud backend is active and an OAuth server is being edited.+ setRegisteredBackends([+ {+ id: "cloud-1",+ name: "Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "k",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud-1" });+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(+ buildSettingsWithMcp(),+ );+ const authorizeSpy = vi+ .spyOn(McpService, "authorizeOAuth")+ .mockResolvedValue({ ok: true, tools: ["search_mail"] });+ const testSpy = vi+ .spyOn(McpService, "testServer")+ .mockResolvedValue({ ok: true, tools: [] });+ renderWith(<EditOAuthEditorOnceSettingsLoaded onClose={vi.fn()} />);+ await screen.findByTestId("mcp-custom-editor");++ // Act+ fireEvent.click(screen.getByTestId("mcp-test-connection"));++ // Assert+ await waitFor(() =>+ expect(screen.getByTestId("mcp-test-message")).toHaveTextContent(+ "MCP$TEST_SUCCESS",+ ),+ );+ expect(authorizeSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "shttp",+ url: EDIT_OAUTH_SERVER.url,+ auth: expect.objectContaining({ strategy: "oauth2" }),+ }),+ );+ expect(testSpy).not.toHaveBeenCalled();+ });+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 78366f2d4a..685dea8070 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 {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";import {__resetMcpHealthStoreForTests,getMcpHealthSnapshot,@@ -35,6 +40,10 @@ function renderWith(ui: React.ReactNode) {describe("InstallServerModal", () => {beforeEach(() => {vi.restoreAllMocks();+ // 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, "createMcpServer").mockImplementation((settingsKey, server) =>SettingsService.saveSettings({@@ -133,6 +142,92 @@ describe("InstallServerModal", () => {);});+ it("seeds a remote catalog server's health on cloud backends", async () => {+ // Arrange: on a cloud backend remote servers are probed through the app+ // server, so the pre-save verdict is real and must reach the card.+ __resetMcpHealthStoreForTests();+ setRegisteredBackends([+ {+ id: "cloud-1",+ name: "Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "k",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud-1" });+ const linear = getMcpMarketplaceCatalog(MCP_MARKETPLACE).find(+ (e) => e.id === "linear",+ )!;+ const getSpy = vi+ .spyOn(SettingsService, "getSettings")+ .mockResolvedValue(MOCK_DEFAULT_USER_SETTINGS);+ vi.spyOn(SettingsService, "saveSettings").mockResolvedValue(true);+ renderWith(+ <InstallServerModal+ existingServers={[]}+ entry={linear}+ onClose={vi.fn()}+ />,+ );+ await screen.findByTestId("mcp-install-modal");+ await waitFor(() => expect(getSpy).toHaveBeenCalled());++ // Act+ fireEvent.change(screen.getByTestId("mcp-install-field-api_key"), {+ target: { value: "lin_api_secret" },+ });+ fireEvent.click(screen.getByTestId("mcp-install-submit"));++ // Assert+ await waitFor(() =>+ expect(Object.values(getMcpHealthSnapshot())).toEqual([+ expect.objectContaining({ status: "healthy" }),+ ]),+ );+ });++ it("does not seed a stdio catalog server's health on cloud backends", async () => {+ // Arrange: stdio servers cannot be probed off-sandbox, so their cloud+ // pre-save test is synthetic and must not become a health verdict.+ __resetMcpHealthStoreForTests();+ setRegisteredBackends([+ {+ id: "cloud-1",+ name: "Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "k",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud-1" });+ const slack = MCP_MARKETPLACE.find((e) => e.id === "slack")!;+ const saveSpy = vi+ .spyOn(SettingsService, "saveSettings")+ .mockResolvedValue(true);+ renderWith(+ <InstallServerModal+ existingServers={[]}+ entry={slack}+ onClose={vi.fn()}+ />,+ );+ await screen.findByTestId("mcp-install-modal");++ // Act+ 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 install still completes, but no verdict is recorded.+ await waitFor(() => expect(saveSpy).toHaveBeenCalledTimes(1));+ expect(getMcpHealthSnapshot()).toEqual({});+ });+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 fielddiff --git a/__tests__/components/features/mcp-page/mcp-server-health.test.tsx b/__tests__/components/features/mcp-page/mcp-server-health.test.tsxindex df84ad5840..257a9cfada 100644--- a/__tests__/components/features/mcp-page/mcp-server-health.test.tsx+++ b/__tests__/components/features/mcp-page/mcp-server-health.test.tsx@@ -31,6 +31,14 @@ const GITHUB_SERVER: MCPServerConfig = {auth: { strategy: "api_key", value: "github_pat_x" },};+const STDIO_SERVER: MCPServerConfig = {+ id: "local-tool",+ type: "stdio",+ name: "local-tool",+ command: "npx",+ args: ["-y", "local-tool"],+};+const OAUTH_SERVER: MCPServerConfig = {id: "my-oauth",type: "shttp",@@ -151,7 +159,7 @@ describe("InstalledServerCard connection health", () => {);});- it("renders no health section on cloud backends", () => {+ it("renders the health section for remote servers on cloud backends", () => {setRegisteredBackends([{id: "cloud-1",@@ -166,7 +174,27 @@ describe("InstalledServerCard connection health", () => {renderCard(CUSTOM_SERVER);expect(- screen.queryByTestId(`mcp-server-health-${CUSTOM_SERVER.id}`),+ screen.getByTestId(`mcp-server-health-${CUSTOM_SERVER.id}`),+ ).toBeInTheDocument();+ expect(probeButton(CUSTOM_SERVER.id)).toBeInTheDocument();+ });++ it("renders no health section for stdio servers on cloud backends", () => {+ setRegisteredBackends([+ {+ id: "cloud-1",+ name: "Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "k",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud-1" });++ renderCard(STDIO_SERVER);++ expect(+ screen.queryByTestId(`mcp-server-health-${STDIO_SERVER.id}`),).not.toBeInTheDocument();});diff --git a/src/api/cloud/mcp-service.api.ts b/src/api/cloud/mcp-service.api.tsnew file mode 100644index 0000000000..c5a95751b7--- /dev/null+++ b/src/api/cloud/mcp-service.api.ts@@ -0,0 +1,74 @@+import type { AgentServerMCPTestRequest } from "@openhands/typescript-client";+import { getActiveBackend } from "../backend-registry/active-store";+import type { Backend } from "../backend-registry/types";+import type {+ ExtendedMCPTestResponse,+ MCPOAuthStartResponse,+ MCPOAuthStatusResponse,+} from "#/types/mcp-server";+import { callCloudProxy } from "./proxy";++const DEFAULT_MCP_TEST_TIMEOUT_SECONDS = 15;+// `POST /api/v1/mcp/oauth/start` answers as soon as the provider's+// authorization URL is known and waits at most 30s for it.+const OAUTH_START_DEADLINE_SECONDS = 35;++function getActiveCloudBackend(): Backend {+ const active = getActiveBackend().backend;+ if (active.kind !== "cloud") {+ throw new Error("Cloud MCP test call requires a cloud backend.");+ }+ return active;+}++/**+ * Probe a remote MCP server through the cloud backend's+ * `POST /api/v1/mcp/test`, which shares the agent-server test contract+ * (HTTP 200 with `ok: false` for connection/timeout failures). The probe+ * lists tools and may then run one read-only tool call, each bounded by+ * `timeout`, so the request deadline covers both plus a margin.+ */+export async function testCloudMcpServer(+ request: AgentServerMCPTestRequest,+): Promise<ExtendedMCPTestResponse> {+ const backend = getActiveCloudBackend();+ const timeout = request.timeout ?? DEFAULT_MCP_TEST_TIMEOUT_SECONDS;+ return callCloudProxy<ExtendedMCPTestResponse>({+ backend,+ method: "POST",+ path: "/api/v1/mcp/test",+ body: request,+ timeoutSeconds: 2 * timeout + 5,+ });+}++/**+ * Start an OAuth install probe through the cloud backend's+ * `POST /api/v1/mcp/oauth/start`. Same contract as the agent-server route:+ * the response carries the provider's authorization URL for the popup, the+ * provider redirects that popup to the app server's own callback, and+ * `getCloudMcpOAuthStatus` reports progress and the final OAuth state.+ */+export async function startCloudMcpOAuth(+ request: AgentServerMCPTestRequest,+): Promise<MCPOAuthStartResponse> {+ const backend = getActiveCloudBackend();+ return callCloudProxy<MCPOAuthStartResponse>({+ backend,+ method: "POST",+ path: "/api/v1/mcp/oauth/start",+ body: request,+ timeoutSeconds: OAUTH_START_DEADLINE_SECONDS,+ });+}++export async function getCloudMcpOAuthStatus(+ jobId: string,+): Promise<MCPOAuthStatusResponse> {+ const backend = getActiveCloudBackend();+ return callCloudProxy<MCPOAuthStatusResponse>({+ backend,+ method: "GET",+ path: `/api/v1/mcp/oauth/status/${encodeURIComponent(jobId)}`,+ });+}diff --git a/src/api/mcp-service/mcp-service.api.test.ts b/src/api/mcp-service/mcp-service.api.test.tsindex c57f32af0f..6d2af2b8e2 100644--- a/src/api/mcp-service/mcp-service.api.test.ts+++ b/src/api/mcp-service/mcp-service.api.test.ts@@ -4,6 +4,11 @@ import {setActiveSelection,setRegisteredBackends,} from "../backend-registry/active-store";+import {+ getCloudMcpOAuthStatus,+ startCloudMcpOAuth,+ testCloudMcpServer,+} from "../cloud/mcp-service.api";import SettingsService from "../settings-service/settings-service.api";import McpService from "./mcp-service.api";import type { MCPServerConfig } from "#/types/mcp-server";@@ -13,6 +18,12 @@ vi.mock("@openhands/typescript-client/clients", () => ({MCPClient: vi.fn(),}));+vi.mock("../cloud/mcp-service.api", () => ({+ testCloudMcpServer: vi.fn(),+ startCloudMcpOAuth: vi.fn(),+ getCloudMcpOAuthStatus: vi.fn(),+}));+const testServer = vi.fn();const startOAuth = vi.fn();const getOAuthStatus = vi.fn();@@ -87,7 +98,7 @@ describe("McpService.testServer", () => {vi.restoreAllMocks();});- it("allows Cloud configuration without calling the local probe or reading local secrets", async () => {+ it("probes Cloud configuration through the app server without calling the local probe or reading local secrets", async () => {setRegisteredBackends([{id: "cloud",@@ -99,10 +110,15 @@ describe("McpService.testServer", () => {]);setActiveSelection({ backendId: "cloud", orgId: null });const fetchSettings = vi.spyOn(SettingsService, "fetchSettingsFromApi");+ vi.mocked(testCloudMcpServer).mockResolvedValueOnce({+ ok: true,+ tools: [],+ });await expect(McpService.testServer(oauthServer())).resolves.toEqual({ok: true,tools: [],});+ expect(testCloudMcpServer).toHaveBeenCalledOnce();expect(MCPClient).not.toHaveBeenCalled();expect(fetchSettings).not.toHaveBeenCalled();});@@ -586,7 +602,7 @@ describe("McpService.testServer", () => {});});- it("uses a registered local backend when OAuth starts from a cloud session", async () => {+ it("starts OAuth through the app server, not a registered local backend, from a cloud session", async () => {setRegisteredBackends([{id: "cloud",@@ -604,17 +620,23 @@ describe("McpService.testServer", () => {},]);setActiveSelection({ backendId: "cloud", orgId: "org-1" });+ vi.mocked(startCloudMcpOAuth).mockResolvedValueOnce({+ ok: true,+ job_id: "job-1",+ authorization_url: "https://auth.example/authorize",+ });- await McpService.startOAuth(oauthServer());-- expect(MCPClient).toHaveBeenCalledWith({- host: "http://127.0.0.1:8001",- apiKey: "local-key",- timeout: 125_000,+ await expect(McpService.startOAuth(oauthServer())).resolves.toEqual({+ ok: true,+ job_id: "job-1",+ authorization_url: "https://auth.example/authorize",});++ expect(startCloudMcpOAuth).toHaveBeenCalledOnce();+ expect(MCPClient).not.toHaveBeenCalled();});- it("omits an empty fallback API key when probing OAuth from the cloud", async () => {+ it("polls OAuth status through the app server from a cloud session", async () => {setRegisteredBackends([{id: "cloud",@@ -632,16 +654,20 @@ describe("McpService.testServer", () => {},]);setActiveSelection({ backendId: "cloud", orgId: "org-1" });+ vi.mocked(getCloudMcpOAuthStatus).mockResolvedValueOnce({+ ok: true,+ status: "pending",+ job_id: "job-on-cloud",+ callback_ready: false,+ });- await McpService.getOAuthStatus("job-with-fallback");+ await McpService.getOAuthStatus("job-on-cloud");- expect(MCPClient).toHaveBeenCalledWith({- host: "http://127.0.0.1:8001",- timeout: 125_000,- });+ expect(getCloudMcpOAuthStatus).toHaveBeenCalledWith("job-on-cloud");+ expect(MCPClient).not.toHaveBeenCalled();});- it("rejects OAuth when no registered local backend is reachable", async () => {+ it("starts OAuth from a cloud session without a reachable local backend", async () => {setRegisteredBackends([{id: "cloud",@@ -659,10 +685,17 @@ describe("McpService.testServer", () => {},]);setActiveSelection({ backendId: "cloud", orgId: "org-1" });+ vi.mocked(startCloudMcpOAuth).mockResolvedValueOnce({+ ok: true,+ job_id: "job-1",+ authorization_url: "https://auth.example/authorize",+ });- await expect(McpService.startOAuth(oauthServer())).rejects.toThrow(- "OAuth authorization requires a reachable local backend.",- );+ await expect(McpService.startOAuth(oauthServer())).resolves.toMatchObject({+ ok: true,+ job_id: "job-1",+ });+ expect(startCloudMcpOAuth).toHaveBeenCalledOnce();expect(MCPClient).not.toHaveBeenCalled();});@@ -959,3 +992,97 @@ describe("McpService.testServer", () => {expect(close).toHaveBeenCalledOnce();});});++describe("McpService.authorizeOAuth on cloud backends", () => {+ const ROVO: MCPServerConfig = {+ id: "atlassian_rovo",+ type: "shttp",+ name: "Atlassian Rovo",+ url: "https://mcp.atlassian.com/v1/mcp/authv2",+ auth: {+ strategy: "oauth2",+ authentication: { type: "oauth", client_auth_method: "none" },+ },+ };+ const AUTHORIZATION_URL = "https://auth.atlassian.com/authorize?state=s";+ let popup: { close: ReturnType<typeof vi.fn>; location: { href: string } };++ beforeEach(() => {+ vi.clearAllMocks();+ setRegisteredBackends([+ {+ id: "cloud",+ name: "Cloud",+ host: "https://app.all-hands.dev",+ apiKey: "bearer-token",+ kind: "cloud",+ },+ ]);+ setActiveSelection({ backendId: "cloud", orgId: null });+ popup = { close: vi.fn(), location: { href: "" } };+ vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window);+ vi.mocked(startCloudMcpOAuth).mockReset();+ vi.mocked(getCloudMcpOAuthStatus).mockReset();+ vi.mocked(startCloudMcpOAuth).mockResolvedValue({+ ok: true,+ job_id: "job-1",+ authorization_url: AUTHORIZATION_URL,+ });+ vi.mocked(getCloudMcpOAuthStatus)+ .mockResolvedValueOnce({+ ok: true,+ status: "authorizing",+ job_id: "job-1",+ callback_ready: true,+ })+ .mockResolvedValue({+ ok: true,+ status: "succeeded",+ job_id: "job-1",+ callback_ready: true,+ tools: ["search"],+ oauth_state: { tokens: { access_token: "plain-access-token" } },+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("runs the OAuth flow through the app server instead of a local agent-server", async () => {+ vi.useFakeTimers();+ try {+ // Act+ const pending = McpService.authorizeOAuth(ROVO);+ await vi.advanceTimersByTimeAsync(1000);+ const result = await pending;++ // Assert+ expect(MCPClient).not.toHaveBeenCalled();+ expect(startCloudMcpOAuth).toHaveBeenCalledTimes(1);+ expect(vi.mocked(startCloudMcpOAuth).mock.calls[0][0]).toMatchObject({+ name: "atlassian_rovo",+ server: { type: "http", url: ROVO.url, auth: ROVO.auth },+ timeout: 120,+ });+ expect(popup.location.href).toBe(AUTHORIZATION_URL);+ expect(getCloudMcpOAuthStatus).toHaveBeenCalledWith("job-1");+ expect(popup.close).toHaveBeenCalledTimes(1);+ expect(result).toMatchObject({+ ok: true,+ tools: ["search"],+ oauth_state: { tokens: { access_token: "plain-access-token" } },+ });+ } finally {+ vi.useRealTimers();+ }+ });++ it("closes the popup when the app server call fails", async () => {+ vi.mocked(startCloudMcpOAuth).mockRejectedValue(new Error("boom"));++ await expect(McpService.authorizeOAuth(ROVO)).rejects.toThrow("boom");++ expect(popup.close).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/api/mcp-service/mcp-service.api.ts b/src/api/mcp-service/mcp-service.api.tsindex 79be35c6a8..32bffcfa9a 100644--- a/src/api/mcp-service/mcp-service.api.ts+++ b/src/api/mcp-service/mcp-service.api.ts@@ -5,6 +5,12 @@ import {getActiveBackend,getRegisteredBackends,} from "../backend-registry/active-store";+import {+ getCloudMcpOAuthStatus,+ startCloudMcpOAuth,+ testCloudMcpServer,+} from "../cloud/mcp-service.api";+import { headersFromMcpAuth } from "../settings-service/settings-service.api";import {getCredentialValidationForServer,type CredentialValidation,@@ -19,6 +25,8 @@ import { redactMcpSecrets } from "#/utils/redact-mcp-secrets";import { substituteRedactedMcpCredentials } from "./mcp-redacted-credentials";const OAUTH_MCP_TEST_TIMEOUT_SECONDS = 120;+// Upper bound accepted by the app server's `POST /api/v1/mcp/test`.+const MAX_CLOUD_MCP_TEST_TIMEOUT_SECONDS = 120;function toMcpServer(server: MCPServerConfig,@@ -149,6 +157,17 @@ function createMcpProbeClient(): MCPClient {});}+/**+ * OAuth probes run on the local agent-server (`/api/mcp/oauth/*`) or, for+ * cloud backends, on the app server (`/api/v1/mcp/oauth/*`). Both share the+ * start/status contract, so callers only differ in transport.+ */+interface McpOAuthTransport {+ start(server: MCPServerConfig): Promise<MCPOAuthStartResponse>;+ status(jobId: string): Promise<MCPOAuthStatusResponse>;+ close(): void;+}+function oauthStatusToTestResponse(status: MCPOAuthStatusResponse,): ExtendedMCPTestResponse {@@ -180,18 +199,17 @@ class McpService {static async testServer(server: MCPServerConfig,): Promise<ExtendedMCPTestResponse> {- // The MCP connectivity-test endpoint lives on the local agent-server. It- // spawns the configured stdio command / opens an SSE-or-SHTTP connection- // from that process's environment. Cloud backends don't expose this- // endpoint to the frontend β the MCP server would actually run inside the- // cloud sandbox, which isn't reachable from the browser before the user- // starts a conversation. Calling `getAgentServerClientOptions()` here for- // a cloud-active session would throw `NoBackendAvailableError("No backend- // is configured.")` and block the install flow entirely. Short-circuit- // with a synthetic success so saving proceeds; any real connection- // failure surfaces inside the conversation runtime instead.if (getActiveBackend().backend.kind === "cloud") {- return { ok: true, tools: [] };+ // A stdio server spawns inside the cloud sandbox, which isn't reachable+ // from the browser before the user starts a conversation, so it cannot+ // be probed from the settings page. Short-circuit with a synthetic+ // success so saving/installing proceeds; any real failure surfaces+ // inside the conversation runtime instead. (Throwing here would block+ // the install flow entirely β see the cloud regression test.)+ if (server.type === "stdio") {+ return { ok: true, tools: [] };+ }+ return McpService.testRemoteServerViaCloud(server);}const validation = getCredentialValidationForServer(server);const { host, apiKey } = getAgentServerClientOptions();@@ -209,26 +227,68 @@ class McpService {}}+ /**+ * Remote servers on cloud backends are probed by the app server's+ * `POST /api/v1/mcp/test`. Unchanged (redacted) credentials are not+ * substituted here: the app server restores them from the stored server of+ * the same settings key, which is why the key is sent as `name`. `auth` is+ * flattened to headers the same way cloud saves persist it so that+ * restoration matches; an `auth` that cannot be flattened (e.g. OAuth+ * without tokens) is passed through and the app server answers with a+ * structured failure.+ */+ private static async testRemoteServerViaCloud(+ server: MCPServerConfig,+ ): Promise<ExtendedMCPTestResponse> {+ const validation = getCredentialValidationForServer(server);+ const authHeaders = server.auth+ ? headersFromMcpAuth({ ...server.auth })+ : null;+ const headers = { ...server.headers, ...authHeaders };+ const name = server.id || server.name;+ const timeout = getMcpTestTimeout(server);+ const request: AgentServerMCPTestRequest = {+ server: {+ type: server.type === "sse" ? "sse" : "http",+ url: server.url!,+ ...(Object.keys(headers).length > 0 && { headers }),+ ...(server.auth && authHeaders === null && { auth: server.auth }),+ },+ ...(name ? { name } : {}),+ ...(timeout !== undefined && {+ timeout: Math.min(timeout, MAX_CLOUD_MCP_TEST_TIMEOUT_SECONDS),+ }),+ ...(validation ? { tool_call: validation.toolCall } : {}),+ };+ const result = await testCloudMcpServer(request);+ return finalizeMcpTestResponse(result, validation, [server]);+ }+static async startOAuth(server: MCPServerConfig,): Promise<MCPOAuthStartResponse> {- const client = createMcpProbeClient();+ const transport = McpService.createOAuthTransport();try {- return await McpService.startOAuthWithClient(client, server);+ return await transport.start(server);} finally {- client.close();+ transport.close();}}static async getOAuthStatus(jobId: string): Promise<MCPOAuthStatusResponse> {- const client = createMcpProbeClient();+ const transport = McpService.createOAuthTransport();try {- return await McpService.getOAuthStatusWithClient(client, jobId);+ return await transport.status(jobId);} finally {- client.close();+ transport.close();}}+ /**+ * Local agent-server only: hands a captured loopback callback URL to the+ * probe. On cloud backends the provider redirects straight to the app+ * server's callback route, so there is nothing to submit.+ */static async submitOAuthCallback(jobId: string,callbackUrl: string,@@ -251,10 +311,13 @@ class McpService {const validation = getCredentialValidationForServer(server);const finalize = (result: ExtendedMCPTestResponse) =>finalizeMcpTestResponse(result, validation, [server]);+ // Opened synchronously inside the click handler so popup blockers allow+ // it; every failure path below closes it again.const popup = window.open("about:blank", "_blank");- const client = createMcpProbeClient();+ let transport: McpOAuthTransport | null = null;try {- const start = await McpService.startOAuthWithClient(client, server);+ transport = McpService.createOAuthTransport();+ const start = await transport.start(server);if (!start.ok || !start.job_id || !start.authorization_url) {popup?.close();return finalize({@@ -264,10 +327,7 @@ class McpService {});}- let status = await McpService.getOAuthStatusWithClient(- client,- start.job_id,- );+ let status = await transport.status(start.job_id);for (let attempt = 0; attempt < 20; attempt += 1) {if (status.status === "succeeded" || status.status === "failed") {popup?.close();@@ -275,10 +335,7 @@ class McpService {}if (status.callback_ready) break;await sleep(250);- status = await McpService.getOAuthStatusWithClient(- client,- start.job_id,- );+ status = await transport.status(start.job_id);}if (popup) {@@ -291,10 +348,7 @@ class McpService {attempt += 1) {await sleep(1000);- status = await McpService.getOAuthStatusWithClient(- client,- start.job_id,- );+ status = await transport.status(start.job_id);if (status.status === "succeeded" || status.status === "failed") {popup?.close();return finalize(oauthStatusToTestResponse(status));@@ -306,9 +360,44 @@ class McpService {error: "OAuth authorization timed out",error_kind: "timeout",};+ } catch (err) {+ popup?.close();+ throw err;} finally {- client.close();+ transport?.close();+ }+ }++ /**+ * The cloud request is built like the cloud connection test: unchanged+ * (redacted) credentials are restored server-side from the stored server of+ * the same settings key (hence `name`), and `auth` stays the `oauth2`+ * credential so the app server runs the OAuth flow rather than flattening+ * it to headers.+ */+ private static createOAuthTransport(): McpOAuthTransport {+ if (getActiveBackend().backend.kind === "cloud") {+ return {+ start: (server) => {+ const validation = getCredentialValidationForServer(server);+ const name = server.id || server.name;+ return startCloudMcpOAuth({+ server: toMcpServer(server),+ ...(name ? { name } : {}),+ timeout: OAUTH_MCP_TEST_TIMEOUT_SECONDS,+ ...(validation ? { tool_call: validation.toolCall } : {}),+ });+ },+ status: getCloudMcpOAuthStatus,+ close: () => {},+ };}+ const client = createMcpProbeClient();+ return {+ start: (server) => McpService.startOAuthWithClient(client, server),+ status: (jobId) => McpService.getOAuthStatusWithClient(client, jobId),+ close: () => client.close(),+ };}private static async startOAuthWithClient(diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.tsindex e31f579c51..441578a23d 100644--- a/src/api/settings-service/settings-service.api.ts+++ b/src/api/settings-service/settings-service.api.ts@@ -212,7 +212,7 @@ const basicAuthHeader = (username: string, password: string): string => {return `Basic ${token}`;};-const headersFromMcpAuth = (+export const headersFromMcpAuth = (auth: Record<string, unknown>,): Record<string, string> | null => {switch (auth.strategy) {diff --git a/src/components/features/mcp-page/custom-server-editor.tsx b/src/components/features/mcp-page/custom-server-editor.tsxindex 84a2a1b58e..5e8d44905b 100644--- a/src/components/features/mcp-page/custom-server-editor.tsx+++ b/src/components/features/mcp-page/custom-server-editor.tsx@@ -53,6 +53,7 @@ export function CustomServerEditor({mutate: testServer,isPending: isTesting,data: testResult,+ variables: testedServer,reset: resetTest,} = useTestMcpServer();const [showDeleteConfirm, setShowDeleteConfirm] = React.useState(false);@@ -60,12 +61,15 @@ export function CustomServerEditor({React.useState<ExtendedMCPTestResponse | null>(null);const [isOauthTesting, setIsOauthTesting] = React.useState(false);- // The MCP connectivity-test endpoint only exists on the local agent-server.- // For cloud backends `McpService.testServer` short-circuits with a synthetic- // success so the save still completes; we hide the manual "Test connection"- // button here so cloud users aren't shown a misleading "0 tools" result.+ // stdio servers cannot be probed from a cloud backend (they spawn inside the+ // sandbox): `McpService.testServer` short-circuits them with a synthetic+ // success so the save still completes. Hide the manual "Test connection"+ // button and the resulting message for them so cloud users aren't shown a+ // misleading "0 tools" result. Remote servers are probed via the app server.const { backend } = useActiveBackend();const isCloudBackend = backend.kind === "cloud";+ const isSyntheticTestResult =+ isCloudBackend && !oauthTestResult && testedServer?.type === "stdio";const isEditing = !!server.id;const isPending = isAdding || isUpdating || isDeleting;@@ -88,13 +92,14 @@ export function CustomServerEditor({}, [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.+ // saved, so publish that result to the card's health entry. For stdio+ // servers on cloud backends the probe is synthetic β never present it as a+ // health verdict.const seedSavedServerHealth = (serverToSave: MCPServerConfig,result: ExtendedMCPTestResponse,) => {- if (isCloudBackend) return;+ if (isCloudBackend && serverToSave.type === "stdio") 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@@ -186,7 +191,7 @@ export function CustomServerEditor({const handleTestClick = (payload: MCPServerConfig) => {setOauthTestResult(null);- if (payload.auth?.strategy === "oauth2" && !isCloudBackend) {+ if (payload.auth?.strategy === "oauth2") {setIsOauthTesting(true);void McpService.authorizeOAuth(payload).then(setOauthTestResult)@@ -247,9 +252,10 @@ export function CustomServerEditor({onCancel={onClose}onDelete={isEditing ? () => setShowDeleteConfirm(true) : undefined}isActionDisabled={isPending}- onTest={isCloudBackend ? undefined : handleTestClick}+ onTest={handleTestClick}isTestPending={isTesting || isOauthTesting}- testMessage={isCloudBackend ? null : testMessage}+ testMessage={isSyntheticTestResult ? null : testMessage}+ isStdioTestUnavailable={isCloudBackend}/></div></ModalBackdrop>diff --git a/src/components/features/mcp-page/install-server-modal.tsx b/src/components/features/mcp-page/install-server-modal.tsxindex 993a44d55b..60532808f5 100644--- a/src/components/features/mcp-page/install-server-modal.tsx+++ b/src/components/features/mcp-page/install-server-modal.tsx@@ -156,8 +156,6 @@ 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";@@ -174,6 +172,9 @@ export function InstallServerModal({const [isAuthorizingOAuth, setIsAuthorizingOAuth] = React.useState(false);const option = getInstallableMcpConnectionOption(entry);const template = option?.transport;+ // stdio servers on cloud backends get a synthetic test success (they only+ // run inside the sandbox); never seed card health from it.+ const isSyntheticTest = isCloudBackend && template?.kind === "stdio";const isPending =isTesting || isAuthorizingOAuth || isAdding || isFinalizingInstall;@@ -254,7 +255,7 @@ export function InstallServerModal({: payload;addMcpServer(serverToSave, {onSuccess: () => {- if (!isCloudBackend) {+ if (!isSyntheticTest) {seedMcpServerHealth(serverToSave, result, existingServers);}displaySuccessToast(t(I18nKey.MCP$INSTALL_SUCCESS));@@ -299,7 +300,7 @@ export function InstallServerModal({: payload;addMcpServer(serverToSave, {onSuccess: () => {- if (!isCloudBackend) {+ if (!isSyntheticTest) {seedMcpServerHealth(serverToSave, result, existingServers);}displaySuccessToast(t(I18nKey.MCP$INSTALL_SUCCESS));diff --git a/src/components/features/mcp-page/mcp-server-health.tsx b/src/components/features/mcp-page/mcp-server-health.tsxindex df23446426..8ea6185a5b 100644--- a/src/components/features/mcp-page/mcp-server-health.tsx+++ b/src/components/features/mcp-page/mcp-server-health.tsx@@ -63,9 +63,10 @@ function getStatusLabel(* 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).+ * Renders nothing for stdio servers on cloud backends: those spawn inside+ * the cloud sandbox, so `McpService.testServer` short-circuits them with a+ * synthetic success that must not be presented as a health verdict. Remote+ * servers on cloud backends are probed through the app server.*/export function McpServerHealthSection({server,@@ -77,7 +78,7 @@ export function McpServerHealthSection({const { health, probe, reauthorize } = useMcpServerHealth(server);const { mutate: updateMcpServer } = useUpdateMcpServer();- if (backend.kind === "cloud") return null;+ if (backend.kind === "cloud" && server.type === "stdio") return null;const isChecking = health.status === "checking";const isFailed = health.status === "failed";diff --git a/src/components/features/settings/mcp-settings/mcp-server-form.tsx b/src/components/features/settings/mcp-settings/mcp-server-form.tsxindex eec8941007..2649ca5d49 100644--- a/src/components/features/settings/mcp-settings/mcp-server-form.tsx+++ b/src/components/features/settings/mcp-settings/mcp-server-form.tsx@@ -39,6 +39,12 @@ interface MCPServerFormProps {onTest?: (server: MCPServerConfig) => void;isTestPending?: boolean;testMessage?: TestMessage | null;+ /**+ * Hide the Test button while the form describes a stdio server. Cloud+ * backends can only probe remote servers; the type is live form state in+ * add mode, so the form owns this decision.+ */+ isStdioTestUnavailable?: boolean;}export function MCPServerForm({@@ -52,6 +58,7 @@ export function MCPServerForm({onTest,isTestPending = false,testMessage = null,+ isStdioTestUnavailable = false,}: MCPServerFormProps) {const { t } = useTranslation("openhands");const [serverType, setServerType] = React.useState<MCPServerType>(@@ -733,7 +740,7 @@ export function MCPServerForm({>{t(I18nKey.BUTTON$CANCEL)}</BrandButton>- {onTest && (+ {onTest && !(isStdioTestUnavailable && serverType === "stdio") && (<BrandButtontestId="mcp-test-connection"type="button"