Skip to content

🙌 OpenHands: AI-Driven Development

feat: validate MCP server connectivity before saving (#785) (#816)

Tim O'Farrell463deff24a97
diff --git a/__tests__/api/mcp-service/mcp-service.api.test.ts b/__tests__/api/mcp-service/mcp-service.api.test.ts
new file mode 100644
index 0000000000..57abd159fb
--- /dev/null
+++ b/__tests__/api/mcp-service/mcp-service.api.test.ts
@@ -0,0 +1,90 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import McpService from "#/api/mcp-service/mcp-service.api";
+import type { MCPServerConfig } from "#/types/mcp-server";
+
+// 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(() => ({
+ mockTestServer: vi.fn(),
+}));
+
+vi.mock("@openhands/typescript-client/clients", () => ({
+ // Real class so `new MCPClient(...)` works; testServer delegates to the
+ // shared spy so each test can configure the return value independently.
+ MCPClient: class {
+ // eslint-disable-next-line class-methods-use-this
+ testServer = mockTestServer;
+
+ // eslint-disable-next-line class-methods-use-this
+ close = vi.fn();
+ },
+}));
+
+vi.mock("#/api/agent-server-client-options", () => ({
+ getAgentServerClientOptions: () => ({
+ host: "http://localhost:3000",
+ apiKey: "test-key",
+ }),
+}));
+
+const SERVER: MCPServerConfig = {
+ id: "shttp-1",
+ type: "shttp",
+ url: "https://mcp.example.com/mcp",
+};
+
+describe("McpService.testServer", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("passes success responses through unchanged", async () => {
+ mockTestServer.mockResolvedValue({ ok: true, tools: ["search", "fetch"] });
+
+ const result = await McpService.testServer(SERVER);
+
+ expect(result).toEqual({ ok: true, tools: ["search", "fetch"] });
+ });
+
+ it("passes failure responses through unchanged (no server-side escaping)", async () => {
+ // The backend returns plain text; HTML-escaping of {{-error}} is handled
+ // by the i18next no-escape prefix in the translation string, not here.
+ mockTestServer.mockResolvedValue({
+ ok: false,
+ error: "Client error '401 Unauthorized' for url https://mcp.example.com/mcp",
+ error_kind: "unknown",
+ });
+
+ const result = await McpService.testServer(SERVER);
+
+ expect(result).toEqual({
+ ok: false,
+ error: "Client error '401 Unauthorized' for url https://mcp.example.com/mcp",
+ error_kind: "unknown",
+ });
+ });
+
+ it("maps a stdio config to a StdioMCPServerSpec", async () => {
+ mockTestServer.mockResolvedValue({ ok: true, tools: [] });
+ const stdio: MCPServerConfig = {
+ id: "stdio-1",
+ type: "stdio",
+ name: "my-server",
+ command: "npx",
+ args: ["-y", "@my/mcp-server"],
+ env: { API_KEY: "secret" },
+ };
+
+ await McpService.testServer(stdio);
+
+ expect(mockTestServer).toHaveBeenCalledWith({
+ server: {
+ type: "stdio",
+ command: "npx",
+ args: ["-y", "@my/mcp-server"],
+ env: { API_KEY: "secret" },
+ },
+ name: "my-server",
+ });
+ });
+});
diff --git a/__tests__/components/automations/recommended-automations.test.tsx b/__tests__/components/automations/recommended-automations.test.tsx
index 29357adca7..16f8118e73 100644
--- a/__tests__/components/automations/recommended-automations.test.tsx
+++ b/__tests__/components/automations/recommended-automations.test.tsx
@@ -2,6 +2,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, 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 {
consumePendingTaskDraft,
getConversationState,
@@ -116,6 +117,11 @@ describe("recommended automations", () => {
mockUseSettings.mockReturnValue({
data: settingsWithMcpConfig({ mcpServers: {} }),
});
+ // Pre-flight connectivity test must pass so save mutations are reached.
+ vi.spyOn(McpService, "testServer").mockResolvedValue({
+ ok: true,
+ tools: [],
+ });
});
afterEach(() => {
diff --git a/__tests__/components/features/mcp-page/custom-server-editor.test.tsx b/__tests__/components/features/mcp-page/custom-server-editor.test.tsx
index 486cbd0e4f..fa39221871 100644
--- a/__tests__/components/features/mcp-page/custom-server-editor.test.tsx
+++ b/__tests__/components/features/mcp-page/custom-server-editor.test.tsx
@@ -4,6 +4,7 @@ import { render, screen, fireEvent, waitFor } from "@testing-library/react";
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 { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
import { CustomServerEditor } from "#/components/features/mcp-page/custom-server-editor";
@@ -89,6 +90,11 @@ describe("CustomServerEditor", () => {
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
MOCK_DEFAULT_USER_SETTINGS,
);
+ // Pre-flight connectivity test must pass so the save mutation is reached.
+ vi.spyOn(McpService, "testServer").mockResolvedValue({
+ ok: true,
+ tools: [],
+ });
});
it("keeps the modal open and does not call onClose when the add mutation fails", async () => {
diff --git a/__tests__/components/features/mcp-page/install-server-modal.test.tsx b/__tests__/components/features/mcp-page/install-server-modal.test.tsx
index 56926d0e7c..7007a89df0 100644
--- a/__tests__/components/features/mcp-page/install-server-modal.test.tsx
+++ b/__tests__/components/features/mcp-page/install-server-modal.test.tsx
@@ -2,6 +2,7 @@ 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 SettingsService from "#/api/settings-service/settings-service.api";
+import McpService from "#/api/mcp-service/mcp-service.api";
import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
import { InstallServerModal } from "#/components/features/mcp-page/install-server-modal";
@@ -30,6 +31,11 @@ describe("InstallServerModal", () => {
vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
MOCK_DEFAULT_USER_SETTINGS,
);
+ // Default: pre-flight test passes so existing save tests remain unaffected.
+ vi.spyOn(McpService, "testServer").mockResolvedValue({
+ ok: true,
+ tools: [],
+ });
});
it("requires Slack token + team id and posts a stdio mcp_config diff", async () => {
@@ -208,4 +214,123 @@ describe("InstallServerModal", () => {
cancel.compareDocumentPosition(submit) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
});
+
+ it("shows an inline error, does not save, and keeps the modal open when the pre-flight test fails", async () => {
+ vi.spyOn(McpService, "testServer").mockResolvedValue({
+ ok: false,
+ error: "ECONNREFUSED",
+ error_kind: "connection",
+ });
+ const saveSpy = vi
+ .spyOn(SettingsService, "saveSettings")
+ .mockResolvedValue(true);
+ const onClose = vi.fn();
+
+ const entry: MarketplaceEntry = {
+ id: "synthetic-test-fail",
+ name: "Failing Server",
+ description: "Always fails the connection test.",
+ iconBg: "#000000",
+ template: {
+ kind: "shttp",
+ url: "https://example.com/mcp",
+ apiKeyOptional: true,
+ },
+ };
+
+ renderWith(<InstallServerModal entry={entry} onClose={onClose} />);
+ await screen.findByTestId("mcp-install-modal");
+
+ // Wait for settings to load so the mutation isn't a no-op.
+ await waitFor(() =>
+ expect(SettingsService.getSettings).toHaveBeenCalled(),
+ );
+
+ fireEvent.click(screen.getByTestId("mcp-install-submit"));
+
+ // Error message must appear.
+ await waitFor(() =>
+ expect(screen.getByTestId("mcp-install-modal-error")).toBeInTheDocument(),
+ );
+
+ // Save must never have been called.
+ expect(saveSpy).not.toHaveBeenCalled();
+
+ // Modal must stay open.
+ expect(onClose).not.toHaveBeenCalled();
+ expect(screen.getByTestId("mcp-install-modal")).toBeInTheDocument();
+ });
+
+ it("calls save and closes the modal when the pre-flight test succeeds", async () => {
+ vi.spyOn(McpService, "testServer").mockResolvedValue({
+ ok: true,
+ tools: ["tool_a"],
+ });
+ const saveSpy = vi
+ .spyOn(SettingsService, "saveSettings")
+ .mockResolvedValue(true);
+ const onClose = vi.fn();
+
+ const entry: MarketplaceEntry = {
+ id: "synthetic-test-pass",
+ name: "Passing Server",
+ description: "Always passes the connection test.",
+ iconBg: "#000000",
+ template: {
+ kind: "shttp",
+ url: "https://example.com/mcp",
+ apiKeyOptional: true,
+ },
+ };
+
+ renderWith(<InstallServerModal entry={entry} onClose={onClose} />);
+ await screen.findByTestId("mcp-install-modal");
+
+ await waitFor(() =>
+ expect(SettingsService.getSettings).toHaveBeenCalled(),
+ );
+
+ fireEvent.click(screen.getByTestId("mcp-install-submit"));
+
+ await waitFor(() => expect(saveSpy).toHaveBeenCalledTimes(1));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(
+ screen.queryByTestId("mcp-install-modal-error"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows Verifying… on the install button while the pre-flight test is in flight", async () => {
+ // Never resolve so the test stays pending long enough to observe the label.
+ vi.spyOn(McpService, "testServer").mockImplementation(
+ () => new Promise(() => {}),
+ );
+
+ const entry: MarketplaceEntry = {
+ id: "synthetic-pending",
+ name: "Pending Server",
+ description: "Connection test never resolves.",
+ iconBg: "#000000",
+ template: {
+ kind: "shttp",
+ url: "https://example.com/mcp",
+ apiKeyOptional: true,
+ },
+ };
+
+ renderWith(<InstallServerModal entry={entry} onClose={vi.fn()} />);
+ await screen.findByTestId("mcp-install-modal");
+
+ await waitFor(() =>
+ expect(SettingsService.getSettings).toHaveBeenCalled(),
+ );
+
+ fireEvent.click(screen.getByTestId("mcp-install-submit"));
+
+ // In tests i18n keys are returned as-is, so the button shows the key name.
+ await waitFor(() =>
+ expect(screen.getByTestId("mcp-install-submit")).toHaveTextContent(
+ "MCP$VERIFYING",
+ ),
+ );
+ });
});
diff --git a/__tests__/hooks/mutation/use-test-mcp-server.test.ts b/__tests__/hooks/mutation/use-test-mcp-server.test.ts
new file mode 100644
index 0000000000..0fa9be536e
--- /dev/null
+++ b/__tests__/hooks/mutation/use-test-mcp-server.test.ts
@@ -0,0 +1,145 @@
+import { describe, expect, it, vi, afterEach, beforeEach } from "vitest";
+import React from "react";
+import { renderHook, waitFor, act } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { useTestMcpServer } from "#/hooks/mutation/use-test-mcp-server";
+import McpService from "#/api/mcp-service/mcp-service.api";
+import type { MCPServerConfig } from "#/types/mcp-server";
+
+vi.mock("#/api/mcp-service/mcp-service.api", () => ({
+ default: { testServer: vi.fn() },
+}));
+
+const SHTTP_SERVER: MCPServerConfig = {
+ id: "shttp-1",
+ type: "shttp",
+ url: "https://mcp.example.com/mcp",
+ api_key: "secret-key",
+};
+
+describe("useTestMcpServer", () => {
+ let queryClient: QueryClient;
+ let wrapper: ({
+ children,
+ }: {
+ children: React.ReactNode;
+ }) => React.ReactElement;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ children,
+ );
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ vi.clearAllMocks();
+ });
+
+ it("returns ok=true and tool list on success", async () => {
+ vi.mocked(McpService.testServer).mockResolvedValue({
+ ok: true,
+ tools: ["search", "fetch"],
+ });
+
+ const { result } = renderHook(() => useTestMcpServer(), { wrapper });
+
+ act(() => {
+ result.current.mutate(SHTTP_SERVER);
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(McpService.testServer).toHaveBeenCalledWith(SHTTP_SERVER);
+ expect(result.current.data).toEqual({ ok: true, tools: ["search", "fetch"] });
+ });
+
+ it("returns ok=false with error_kind=timeout on timeout failure", async () => {
+ vi.mocked(McpService.testServer).mockResolvedValue({
+ ok: false,
+ error: "timed out",
+ error_kind: "timeout",
+ });
+
+ const { result } = renderHook(() => useTestMcpServer(), { wrapper });
+
+ act(() => {
+ result.current.mutate(SHTTP_SERVER);
+ });
+
+ // The mutation resolves (HTTP 200) even though ok=false — check isSuccess.
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(result.current.data).toEqual({
+ ok: false,
+ error: "timed out",
+ error_kind: "timeout",
+ });
+ });
+
+ it("returns ok=false with error_kind=connection on connection failure", async () => {
+ vi.mocked(McpService.testServer).mockResolvedValue({
+ ok: false,
+ error: "ECONNREFUSED",
+ error_kind: "connection",
+ });
+
+ const { result } = renderHook(() => useTestMcpServer(), { wrapper });
+
+ act(() => {
+ result.current.mutate(SHTTP_SERVER);
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(result.current.data).toMatchObject({
+ ok: false,
+ error_kind: "connection",
+ });
+ });
+
+ it("returns ok=false with error_kind=unknown on generic failure", async () => {
+ vi.mocked(McpService.testServer).mockResolvedValue({
+ ok: false,
+ error: "unexpected error",
+ error_kind: "unknown",
+ });
+
+ const { result } = renderHook(() => useTestMcpServer(), { wrapper });
+
+ act(() => {
+ result.current.mutate(SHTTP_SERVER);
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(result.current.data).toMatchObject({
+ ok: false,
+ error_kind: "unknown",
+ });
+ });
+
+ it("transitions to error state when the network call itself throws", async () => {
+ vi.mocked(McpService.testServer).mockRejectedValue(
+ new Error("Network error"),
+ );
+
+ const { result } = renderHook(() => useTestMcpServer(), { wrapper });
+
+ await act(async () => {
+ result.current.mutate(SHTTP_SERVER);
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(result.current.data).toBeUndefined();
+ });
+});
diff --git a/__tests__/routes/mcp-page.test.tsx b/__tests__/routes/mcp-page.test.tsx
index cf164f52f1..d98d917eee 100644
--- a/__tests__/routes/mcp-page.test.tsx
+++ b/__tests__/routes/mcp-page.test.tsx
@@ -3,6 +3,7 @@ import { render, screen, within, fireEvent, waitFor } from "@testing-library/rea
import { beforeEach, describe, expect, it, vi } from "vitest";
import MCPPage from "#/routes/mcp";
import SettingsService from "#/api/settings-service/settings-service.api";
+import McpService from "#/api/mcp-service/mcp-service.api";
import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
import { Settings } from "#/types/settings";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
@@ -36,6 +37,11 @@ function renderPage() {
describe("MCPPage", () => {
beforeEach(() => {
vi.restoreAllMocks();
+ // Pre-flight connectivity test must pass so save mutations are reached.
+ vi.spyOn(McpService, "testServer").mockResolvedValue({
+ ok: true,
+ tools: [],
+ });
});
it("renders the empty installed state and the marketplace", async () => {
diff --git a/src/api/mcp-service/mcp-service.api.ts b/src/api/mcp-service/mcp-service.api.ts
new file mode 100644
index 0000000000..6e8c6bfa3c
--- /dev/null
+++ b/src/api/mcp-service/mcp-service.api.ts
@@ -0,0 +1,42 @@
+import { MCPClient } from "@openhands/typescript-client/clients";
+import type {
+ MCPServerSpec,
+ MCPTestResponse,
+} from "@openhands/typescript-client";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
+import type { MCPServerConfig } from "#/types/mcp-server";
+
+function toMcpServerSpec(server: MCPServerConfig): MCPServerSpec {
+ if (server.type === "stdio") {
+ return {
+ type: "stdio",
+ command: server.command!,
+ ...(server.args?.length && { args: server.args }),
+ ...(server.env &&
+ Object.keys(server.env).length > 0 && { env: server.env }),
+ };
+ }
+ return {
+ type: server.type,
+ url: server.url!,
+ ...(server.api_key ? { api_key: server.api_key } : {}),
+ };
+}
+
+class McpService {
+ static async testServer(server: MCPServerConfig): Promise<MCPTestResponse> {
+ const { host, apiKey } = getAgentServerClientOptions();
+ const client = new MCPClient({ host, ...(apiKey ? { apiKey } : {}) });
+ try {
+ return await client.testServer({
+ server: toMcpServerSpec(server),
+ ...(server.name ? { name: server.name } : {}),
+ ...(server.timeout ? { timeout: server.timeout } : {}),
+ });
+ } finally {
+ client.close();
+ }
+ }
+}
+
+export default McpService;
diff --git a/src/components/features/mcp-page/custom-server-editor.tsx b/src/components/features/mcp-page/custom-server-editor.tsx
index 8ddfba9e5e..c86fa39e5f 100644
--- a/src/components/features/mcp-page/custom-server-editor.tsx
+++ b/src/components/features/mcp-page/custom-server-editor.tsx
@@ -1,14 +1,19 @@
import React from "react";
import { AxiosError } from "axios";
import { useTranslation } from "react-i18next";
+import type { MCPTestFailure } from "@openhands/typescript-client";
import { I18nKey } from "#/i18n/declaration";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
import { ModalCloseButton } from "#/components/shared/modals/modal-close-button";
import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";
-import { MCPServerForm } from "#/components/features/settings/mcp-settings/mcp-server-form";
+import {
+ MCPServerForm,
+ type TestMessage,
+} from "#/components/features/settings/mcp-settings/mcp-server-form";
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 { MCPServerConfig } from "#/types/mcp-server";
import {
displayErrorToast,
@@ -38,11 +43,40 @@ export function CustomServerEditor({
useUpdateMcpServer();
const { mutate: deleteMcpServer, isPending: isDeleting } =
useDeleteMcpServer();
+ const {
+ mutate: testServer,
+ isPending: isTesting,
+ data: testResult,
+ reset: resetTest,
+ } = useTestMcpServer();
const [showDeleteConfirm, setShowDeleteConfirm] = React.useState(false);
const isEditing = !!server.id;
const isPending = isAdding || isUpdating || isDeleting;
- const isDismissBlocked = isPending || showDeleteConfirm;
+ const isDismissBlocked = isPending || isTesting || showDeleteConfirm;
+
+ const makeTestErrorMessage = (failure: MCPTestFailure): string => {
+ switch (failure.error_kind) {
+ case "timeout":
+ return t(I18nKey.MCP$TEST_ERROR_TIMEOUT);
+ case "connection":
+ return t(I18nKey.MCP$TEST_ERROR_CONNECTION);
+ default:
+ return t(I18nKey.MCP$TEST_ERROR_UNKNOWN, { error: failure.error });
+ }
+ };
+
+ const testMessage: TestMessage | null = React.useMemo(() => {
+ if (!testResult) return null;
+ if (testResult.ok) {
+ return {
+ ok: true,
+ text: t(I18nKey.MCP$TEST_SUCCESS, { count: testResult.tools.length }),
+ };
+ }
+ return { ok: false, text: makeTestErrorMessage(testResult) };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [testResult, t]);
// Shared error handler so both add and update surface backend errors
// as a toast instead of failing silently — previously these calls
@@ -54,14 +88,28 @@ export function CustomServerEditor({
};
const handleSubmit = (payload: MCPServerConfig) => {
- if (isEditing) {
- updateMcpServer(
- { serverId: server.id, server: payload },
- { onSuccess: onClose, onError: handleError },
- );
- } else {
- addMcpServer(payload, { onSuccess: onClose, onError: handleError });
- }
+ resetTest();
+ testServer(payload, {
+ onSuccess: (result) => {
+ if (!result.ok) {
+ // Test failed — modal stays open, error shown via testMessage.
+ return;
+ }
+ if (isEditing) {
+ updateMcpServer(
+ { serverId: server.id, server: payload },
+ { onSuccess: onClose, onError: handleError },
+ );
+ } else {
+ addMcpServer(payload, { onSuccess: onClose, onError: handleError });
+ }
+ },
+ onError: handleError,
+ });
+ };
+
+ const handleTestClick = (payload: MCPServerConfig) => {
+ testServer(payload);
};
const handleConfirmDelete = () => {
@@ -114,6 +162,9 @@ export function CustomServerEditor({
onCancel={onClose}
onDelete={isEditing ? () => setShowDeleteConfirm(true) : undefined}
isActionDisabled={isPending}
+ onTest={handleTestClick}
+ isTestPending={isTesting}
+ testMessage={testMessage}
/>
</div>
</ModalBackdrop>
diff --git a/src/components/features/mcp-page/install-server-modal.tsx b/src/components/features/mcp-page/install-server-modal.tsx
index 13259b5b2f..30742244d1 100644
--- a/src/components/features/mcp-page/install-server-modal.tsx
+++ b/src/components/features/mcp-page/install-server-modal.tsx
@@ -1,6 +1,7 @@
import React from "react";
import { useTranslation } from "react-i18next";
import { AxiosError } from "axios";
+import type { MCPTestFailure } from "@openhands/typescript-client";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
import { ModalCloseButton } from "#/components/shared/modals/modal-close-button";
import { BrandButton } from "#/components/features/settings/brand-button";
@@ -10,6 +11,7 @@ import type { McpCatalogEntry as MarketplaceEntry } from "@openhands/extensions/
import { McpLogoBadge } from "#/components/features/mcp-logo-badge";
import { MCPServerConfig } from "#/types/mcp-server";
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";
import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
@@ -52,13 +54,14 @@ export function InstallServerModal({
}: InstallServerModalProps) {
const { t } = useTranslation("openhands");
const { mutate: addMcpServer, isPending: isAdding } = useAddMcpServer();
+ const { mutate: testMcpServer, isPending: isTesting } = useTestMcpServer();
const [state, setState] = React.useState<FieldState>(() =>
makeInitialState(entry),
);
const [globalError, setGlobalError] = React.useState<string | null>(null);
- const isPending = isAdding;
+ const isPending = isTesting || isAdding;
const setValue = (key: string, value: string) => {
setState((prev) => ({
@@ -68,12 +71,36 @@ export function InstallServerModal({
setGlobalError(null);
};
+ const makeTestErrorMessage = (failure: MCPTestFailure): string => {
+ switch (failure.error_kind) {
+ case "timeout":
+ return t(I18nKey.MCP$TEST_ERROR_TIMEOUT);
+ case "connection":
+ return t(I18nKey.MCP$TEST_ERROR_CONNECTION);
+ default:
+ return t(I18nKey.MCP$TEST_ERROR_UNKNOWN, { error: failure.error });
+ }
+ };
+
const submitServer = (payload: MCPServerConfig) => {
- addMcpServer(payload, {
- onSuccess: () => {
- displaySuccessToast(t(I18nKey.MCP$INSTALL_SUCCESS));
- onSuccess?.(entry);
- onClose();
+ testMcpServer(payload, {
+ onSuccess: (result) => {
+ if (!result.ok) {
+ setGlobalError(makeTestErrorMessage(result));
+ // Modal stays open — do NOT call onClose.
+ return;
+ }
+ addMcpServer(payload, {
+ onSuccess: () => {
+ displaySuccessToast(t(I18nKey.MCP$INSTALL_SUCCESS));
+ onSuccess?.(entry);
+ onClose();
+ },
+ onError: (err: unknown) => {
+ const message = retrieveAxiosErrorMessage(err as AxiosError);
+ setGlobalError(message || t(I18nKey.ERROR$GENERIC));
+ },
+ });
},
onError: (err: unknown) => {
const message = retrieveAxiosErrorMessage(err as AxiosError);
@@ -304,7 +331,7 @@ export function InstallServerModal({
{globalError && (
<p
data-testid="mcp-install-modal-error"
- className="text-sm text-red-500"
+ className="text-sm text-red-500 whitespace-pre-wrap"
>
{globalError}
</p>
@@ -325,9 +352,11 @@ export function InstallServerModal({
isDisabled={isPending}
testId="mcp-install-submit"
>
- {isPending
- ? t(I18nKey.SETTINGS$SAVING)
- : t(I18nKey.MCP$INSTALL_BUTTON)}
+ {isTesting
+ ? t(I18nKey.MCP$VERIFYING)
+ : isAdding
+ ? t(I18nKey.SETTINGS$SAVING)
+ : t(I18nKey.MCP$INSTALL_BUTTON)}
</BrandButton>
</div>
</form>
diff --git a/src/components/features/settings/mcp-settings/mcp-server-form.tsx b/src/components/features/settings/mcp-settings/mcp-server-form.tsx
index 935a546b33..6c6d7788e3 100644
--- a/src/components/features/settings/mcp-settings/mcp-server-form.tsx
+++ b/src/components/features/settings/mcp-settings/mcp-server-form.tsx
@@ -8,19 +8,13 @@ import { BrandButton } from "../brand-button";
import { OptionalTag } from "../optional-tag";
import { cn } from "#/utils/utils";
import { formControlMultilineFieldClassName } from "#/utils/form-control-classes";
+import type { MCPServerConfig } from "#/types/mcp-server";
type MCPServerType = "sse" | "stdio" | "shttp";
-interface MCPServerConfig {
- id: string;
- type: MCPServerType;
- name?: string;
- url?: string;
- api_key?: string;
- timeout?: number;
- command?: string;
- args?: string[];
- env?: Record<string, string>;
+export interface TestMessage {
+ ok: boolean;
+ text: string;
}
interface MCPServerFormProps {
@@ -31,6 +25,9 @@ interface MCPServerFormProps {
onCancel: () => void;
onDelete?: () => void;
isActionDisabled?: boolean;
+ onTest?: (server: MCPServerConfig) => void;
+ isTestPending?: boolean;
+ testMessage?: TestMessage | null;
}
export function MCPServerForm({
@@ -41,12 +38,16 @@ export function MCPServerForm({
onCancel,
onDelete,
isActionDisabled = false,
+ onTest,
+ isTestPending = false,
+ testMessage = null,
}: MCPServerFormProps) {
const { t } = useTranslation("openhands");
const [serverType, setServerType] = React.useState<MCPServerType>(
server?.type || "sse",
);
const [error, setError] = React.useState<string | null>(null);
+ const formRef = React.useRef<HTMLFormElement>(null);
const serverTypeOptions = [
{ key: "sse", label: t(I18nKey.SETTINGS$MCP_SERVER_TYPE_SSE) },
@@ -214,18 +215,7 @@ export function MCPServerForm({
.join("\n");
};
- const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
- event.preventDefault();
- setError(null);
-
- const formData = new FormData(event.currentTarget);
- const validationError = validateForm(formData);
-
- if (validationError) {
- setError(validationError);
- return;
- }
-
+ const buildConfig = (formData: FormData): MCPServerConfig => {
const baseConfig = {
id: server?.id || `${serverType}-${Date.now()}`,
type: serverType,
@@ -250,29 +240,57 @@ export function MCPServerForm({
}
}
- onSubmit(serverConfig);
- } else if (serverType === "stdio") {
- const name = formData.get("name")?.toString().trim();
- const command = formData.get("command")?.toString().trim();
- const argsString = formData.get("args")?.toString().trim();
- const envString = formData.get("env")?.toString().trim();
-
- const args = argsString
- ? argsString
- .split("\n")
- .map((arg) => arg.trim())
- .filter(Boolean)
- : [];
- const env = parseEnvironmentVariables(envString || "");
-
- onSubmit({
- ...baseConfig,
- name: name!,
- command: command!,
- ...(args.length > 0 && { args }),
- ...(Object.keys(env).length > 0 && { env }),
- });
+ return serverConfig;
}
+
+ // stdio
+ const name = formData.get("name")?.toString().trim();
+ const command = formData.get("command")?.toString().trim();
+ const argsString = formData.get("args")?.toString().trim();
+ const envString = formData.get("env")?.toString().trim();
+
+ const args = argsString
+ ? argsString
+ .split("\n")
+ .map((arg) => arg.trim())
+ .filter(Boolean)
+ : [];
+ const env = parseEnvironmentVariables(envString || "");
+
+ return {
+ ...baseConfig,
+ name: name!,
+ command: command!,
+ ...(args.length > 0 && { args }),
+ ...(Object.keys(env).length > 0 && { env }),
+ };
+ };
+
+ const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ setError(null);
+
+ const formData = new FormData(event.currentTarget);
+ const validationError = validateForm(formData);
+
+ if (validationError) {
+ setError(validationError);
+ return;
+ }
+
+ onSubmit(buildConfig(formData));
+ };
+
+ const handleTestClick = () => {
+ if (!onTest || !formRef.current) return;
+ setError(null);
+ const formData = new FormData(formRef.current);
+ const validationError = validateForm(formData);
+ if (validationError) {
+ setError(validationError);
+ return;
+ }
+ onTest(buildConfig(formData));
};
const formTestId =
@@ -280,6 +298,7 @@ export function MCPServerForm({
return (
<form
+ ref={formRef}
data-testid={formTestId}
onSubmit={handleSubmit}
className="flex flex-col items-start gap-6"
@@ -415,6 +434,19 @@ export function MCPServerForm({
</>
)}
+ {testMessage && (
+ <p
+ data-testid="mcp-test-message"
+ className={
+ testMessage.ok
+ ? "text-sm text-green-500 whitespace-pre-wrap"
+ : "text-sm text-red-500 whitespace-pre-wrap"
+ }
+ >
+ {testMessage.text}
+ </p>
+ )}
+
<div
className={cn(
"flex w-full items-center gap-2",
@@ -445,11 +477,24 @@ export function MCPServerForm({
>
{t(I18nKey.BUTTON$CANCEL)}
</BrandButton>
+ {onTest && (
+ <BrandButton
+ testId="mcp-test-connection"
+ type="button"
+ variant="secondary"
+ onClick={handleTestClick}
+ isDisabled={isActionDisabled || isTestPending}
+ >
+ {isTestPending
+ ? t(I18nKey.MCP$VERIFYING)
+ : t(I18nKey.MCP$TEST_BUTTON)}
+ </BrandButton>
+ )}
<BrandButton
testId="submit-button"
type="submit"
variant="primary"
- isDisabled={isActionDisabled}
+ isDisabled={isActionDisabled || isTestPending}
>
{mode === "add" && t(I18nKey.SETTINGS$MCP_ADD_SERVER)}
{mode === "edit" && t(I18nKey.SETTINGS$MCP_SAVE_SERVER)}
diff --git a/src/hooks/mutation/use-test-mcp-server.ts b/src/hooks/mutation/use-test-mcp-server.ts
new file mode 100644
index 0000000000..fc014a7eef
--- /dev/null
+++ b/src/hooks/mutation/use-test-mcp-server.ts
@@ -0,0 +1,9 @@
+import { useMutation } from "@tanstack/react-query";
+import McpService from "#/api/mcp-service/mcp-service.api";
+import type { MCPServerConfig } from "#/types/mcp-server";
+
+export function useTestMcpServer() {
+ return useMutation({
+ mutationFn: (server: MCPServerConfig) => McpService.testServer(server),
+ });
+}
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 0bb8bf1a0d..c8b7973719 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -13718,6 +13718,24 @@
"uk": "Сервер MCP видалено.",
"ca": "Servidor MCP eliminat."
},
+ "MCP$TEST_BUTTON": {
+ "en": "Test connection"
+ },
+ "MCP$VERIFYING": {
+ "en": "Verifying…"
+ },
+ "MCP$TEST_SUCCESS": {
+ "en": "Connected — {{count}} tool(s) available"
+ },
+ "MCP$TEST_ERROR_TIMEOUT": {
+ "en": "Connection timed out. Check the URL and try again."
+ },
+ "MCP$TEST_ERROR_CONNECTION": {
+ "en": "Could not reach the server. Check the URL and server type."
+ },
+ "MCP$TEST_ERROR_UNKNOWN": {
+ "en": "Connection failed: {{-error}}"
+ },
"MCP$EDIT_SERVER_ARIA": {
"en": "Edit {{name}}",
"ja": "{{name}} を編集",