Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend): share cancellable MCP OAuth attempt lifecycle (#14540)

Lukas509a47beeaff
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx
index 80d5fb56a2..a7e1bd6c6a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/MCPToolDialog.tsx
@@ -25,11 +25,9 @@ import type { CredentialsMetaInput } from "@/lib/autogpt-server-api";
import type { MCPToolResponse } from "@/app/api/__generated__/models/mCPToolResponse";
import {
postV2DiscoverAvailableToolsOnAnMcpServer,
- postV2InitiateOauthLoginForAnMcpServer,
- postV2ExchangeOauthCodeForMcpTokens,
postV2StoreABearerTokenForAnMcpServer,
} from "@/app/api/__generated__/endpoints/mcp/mcp";
-import { openOAuthPopup } from "@/lib/oauth-popup";
+import { connectMCPOAuth } from "@/lib/mcp-oauth";
import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";
import { MCPAuthSchemeField } from "@/components/contextual/MCPAuthSchemeField/MCPAuthSchemeField";
import {
@@ -114,18 +112,20 @@ export function MCPToolDialog({
} = useMCPAuthScheme(storedAuthScheme, manualToken);
const startOAuthRef = useRef(false);
- const oauthAbortRef = useRef<((reason?: string) => void) | null>(null);
-
- // Clean up on unmount
+ const oauthRequest = useRef<AbortController | null>(null);
+ useEffect(() => () => oauthRequest.current?.abort(), []);
useEffect(() => {
- return () => {
- oauthAbortRef.current?.();
- };
- }, []);
+ if (!open) {
+ oauthRequest.current?.abort();
+ oauthRequest.current = null;
+ setOauthLoading(false);
+ setLoading(false);
+ }
+ }, [open]);
const reset = useCallback(() => {
- oauthAbortRef.current?.();
- oauthAbortRef.current = null;
+ oauthRequest.current?.abort();
+ oauthRequest.current = null;
setStep("url");
setServerUrl("");
setManualToken("");
@@ -274,92 +274,46 @@ export function MCPToolDialog({
}, [connectWithManualCredential, discoverTools, serverUrl, showManualToken]);
const handleOAuthSignIn = useCallback(async () => {
- if (!serverUrl.trim()) return;
+ if (!serverUrl.trim() || oauthRequest.current) return;
+ const controller = new AbortController();
+ oauthRequest.current = controller;
+ const { signal } = controller;
setError(null);
-
- // Abort any previous OAuth flow
- oauthAbortRef.current?.();
-
setOauthLoading(true);
try {
- // Only a 400 from the *initiate* call means "this server has no OAuth
- // to offer" and justifies the manual-token fallback. A 400 later in
- // the flow is a rejected authorization response — a failed issuer
- // check, say — and must surface as the error it is rather than an
- // invitation to paste a credential instead.
- let loginResponse: Awaited<
- ReturnType<typeof postV2InitiateOauthLoginForAnMcpServer>
- >;
- try {
- loginResponse = await postV2InitiateOauthLoginForAnMcpServer({
- server_url: serverUrl.trim(),
- });
- if (loginResponse.status !== 200) {
- throw getAPIResponseError(loginResponse.status, loginResponse.data);
- }
- } catch (error: unknown) {
- if (getErrorStatus(error) === 400) {
- setShowManualToken(true);
- setError(
- "This server does not support OAuth sign-in. Choose how its API credential should be sent.",
- );
- return;
- }
- throw error;
- }
- const { login_url, state_token } = loginResponse.data;
-
- const { promise, cleanup } = openOAuthPopup(login_url, {
- stateToken: state_token,
- useCrossOriginListeners: true,
+ const credential = await connectMCPOAuth({
+ serverURL: serverUrl.trim(),
+ signal,
+ exchange: allProviders?.mcp?.mcpOAuthCallback,
});
- oauthAbortRef.current = cleanup.abort;
-
- const result = await promise;
-
- // Exchange code for tokens via the credentials provider (updates cache)
+ signal.throwIfAborted();
+ if ("reason" in credential) {
+ if (credential.noOAuth) setShowManualToken(true);
+ setError(credential.reason);
+ return;
+ }
setLoading(true);
setOauthLoading(false);
-
- const mcpProvider = allProviders?.["mcp"];
- let callbackResult;
- if (mcpProvider) {
- callbackResult = await mcpProvider.mcpOAuthCallback(
- result.code,
- state_token,
- result.iss,
- );
- } else {
- const cbResponse = await postV2ExchangeOauthCodeForMcpTokens({
- code: result.code,
- state_token,
- iss: result.iss,
- });
- if (cbResponse.status !== 200) {
- throw getAPIResponseError(cbResponse.status, cbResponse.data);
- }
- callbackResult = cbResponse.data;
- }
-
setCredentials({
- id: callbackResult.id,
- provider: callbackResult.provider,
- type: callbackResult.type,
- title: callbackResult.title,
+ id: credential.id,
+ provider: credential.provider,
+ type: credential.type,
+ title: credential.title,
});
setCredentialServerUrl(serverUrl.trim());
setAuthRequired(false);
-
- // Discover tools now that we're authenticated
- const toolsResponse = await postV2DiscoverAvailableToolsOnAnMcpServer({
- server_url: serverUrl.trim(),
- });
- if (toolsResponse.status !== 200) {
- throw getAPIResponseError(toolsResponse.status, toolsResponse.data);
+ const response = await postV2DiscoverAvailableToolsOnAnMcpServer(
+ { server_url: serverUrl.trim() },
+ { signal },
+ );
+ signal.throwIfAborted();
+ if (response.status !== 200) {
+ throw getAPIResponseError(response.status, response.data);
}
- applyDiscoveredTools(toolsResponse);
+ applyDiscoveredTools(response);
} catch (error: unknown) {
+ if (signal.aborted) return;
const status = getErrorStatus(error);
const message = getErrorMessage(error, "Failed to complete sign-in");
if (message === "OAuth flow timed out") {
@@ -373,9 +327,13 @@ export function MCPToolDialog({
setError(message);
}
} finally {
- setOauthLoading(false);
- setLoading(false);
- oauthAbortRef.current = null;
+ if (oauthRequest.current === controller) {
+ oauthRequest.current = null;
+ if (!signal.aborted) {
+ setOauthLoading(false);
+ setLoading(false);
+ }
+ }
}
}, [serverUrl, allProviders, applyDiscoveredTools]);
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/MCPToolDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/MCPToolDialog.test.tsx
index 72fd2bd38f..4b8d0854dd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/MCPToolDialog.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/MCPToolDialog.test.tsx
@@ -1,4 +1,5 @@
import {
+ act,
fireEvent,
render,
screen,
@@ -22,6 +23,10 @@ vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({
vi.mock("@/lib/oauth-popup", () => ({
openOAuthPopup: vi.fn(),
+ // Defaults to null — the browser-blocked case — so every cell that does not
+ // care about the sign-in window behaves as it did before the window was
+ // pre-opened at all.
+ preOpenOAuthPopup: vi.fn(() => null),
}));
const PRIVATE_SERVER_URL = "https://private.example.com/mcp";
@@ -65,7 +70,9 @@ async function connectPrivateServer() {
}),
);
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(
- apiResponse(400, { detail: "OAuth not supported" }),
+ apiResponse(400, {
+ detail: { code: "no_oauth", message: "OAuth not supported" },
+ }),
);
vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce(
apiResponse(200, CREDENTIAL),
@@ -88,6 +95,89 @@ describe("MCPToolDialog credential binding", () => {
vi.clearAllMocks();
});
+ it("ignores an old initiation after closing and reopening the same dialog", async () => {
+ const {
+ postV2DiscoverAvailableToolsOnAnMcpServer,
+ postV2InitiateOauthLoginForAnMcpServer,
+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+ type LoginResponse = Awaited<
+ ReturnType<typeof postV2InitiateOauthLoginForAnMcpServer>
+ >;
+ let firstResolve!: (response: LoginResponse) => void;
+ let secondResolve!: (response: LoginResponse) => void;
+ const first = new Promise<LoginResponse>((resolve) => {
+ firstResolve = resolve;
+ });
+ const second = new Promise<LoginResponse>((resolve) => {
+ secondResolve = resolve;
+ });
+ const firstWindow = { closed: false, close: vi.fn() };
+ const secondWindow = { closed: false, close: vi.fn() };
+ vi.mocked(preOpenOAuthPopup)
+ .mockReturnValueOnce(firstWindow as unknown as Window)
+ .mockReturnValueOnce(secondWindow as unknown as Window);
+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValueOnce(
+ apiResponse(401, { detail: "Authentication required" }),
+ );
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer)
+ .mockReturnValueOnce(first)
+ .mockReturnValueOnce(second);
+ vi.mocked(openOAuthPopup).mockReturnValue({
+ promise: new Promise(() => {}),
+ cleanup: { abort: vi.fn(), signal: new AbortController().signal },
+ popupBlocked: false,
+ fallbackBlocked: false,
+ });
+ const props = { onClose: vi.fn(), onConfirm: vi.fn() };
+ const view = render(<MCPToolDialog open {...props} />);
+ fireEvent.change(screen.getByLabelText("Server URL"), {
+ target: { value: PRIVATE_SERVER_URL },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Discover Tools" }));
+ await waitFor(() =>
+ expect(postV2InitiateOauthLoginForAnMcpServer).toHaveBeenCalledTimes(1),
+ );
+
+ view.rerender(<MCPToolDialog open={false} {...props} />);
+ expect(firstWindow.close).toHaveBeenCalledOnce();
+ view.rerender(<MCPToolDialog open {...props} />);
+ fireEvent.click(screen.getByRole("button", { name: "Sign in & Connect" }));
+ await waitFor(() =>
+ expect(postV2InitiateOauthLoginForAnMcpServer).toHaveBeenCalledTimes(2),
+ );
+ await act(async () => {
+ firstResolve(
+ apiResponse(400, {
+ detail: { code: "no_oauth", message: "Old attempt" },
+ }),
+ );
+ });
+ expect(secondWindow.close).not.toHaveBeenCalled();
+ expect(screen.queryByLabelText("API token")).toBeNull();
+ expect(
+ screen.getByRole<HTMLButtonElement>("button", {
+ name: "Waiting for sign-in...",
+ }).disabled,
+ ).toBe(true);
+
+ await act(async () => {
+ secondResolve(
+ apiResponse(200, {
+ login_url: "https://login.example.com/new",
+ state_token: "new",
+ }),
+ );
+ });
+ await waitFor(() => expect(openOAuthPopup).toHaveBeenCalledOnce());
+ expect(openOAuthPopup).toHaveBeenCalledWith(
+ "https://login.example.com/new",
+ expect.objectContaining({ preOpenedWindow: secondWindow }),
+ );
+ });
+
it("surfaces a rejected authorization response instead of offering a token", async () => {
// The callback answers 400 when the RFC 9207 ``iss`` is missing or does
// not match the issuer bound at login. That is a blocked mix-up, not an
@@ -132,6 +222,93 @@ describe("MCPToolDialog credential binding", () => {
expect(screen.queryByText(/does not support OAuth/)).toBeNull();
});
+ // #14532: the sign-in window has to be opened before the initiate request is
+ // awaited — after an await iOS Safari blocks window.open() outright. Both
+ // cells drive the auto-start path (discovery answers 401), which is the only
+ // one this file's harness reaches; the button path shares the same code.
+ it("opens the sign-in window before the initiate await and hands it over", async () => {
+ const callOrder: string[] = [];
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const {
+ postV2DiscoverAvailableToolsOnAnMcpServer,
+ postV2InitiateOauthLoginForAnMcpServer,
+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+
+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValueOnce(
+ apiResponse(401, { detail: "Authentication required" }),
+ );
+ vi.mocked(preOpenOAuthPopup).mockImplementation(() => {
+ callOrder.push("preOpen");
+ return fakeWindow as unknown as Window;
+ });
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockImplementation(
+ async () => {
+ callOrder.push("initiate");
+ return apiResponse(200, {
+ login_url: "https://auth.example.com/authorize",
+ state_token: "st",
+ });
+ },
+ );
+ vi.mocked(openOAuthPopup).mockReturnValue({
+ promise: new Promise(() => {}),
+ cleanup: { abort: vi.fn(), signal: new AbortController().signal },
+ popupBlocked: false,
+ fallbackBlocked: false,
+ });
+
+ render(<MCPToolDialog open onClose={() => {}} onConfirm={vi.fn()} />);
+ fireEvent.change(screen.getByLabelText("Server URL"), {
+ target: { value: PRIVATE_SERVER_URL },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Discover Tools" }));
+
+ await waitFor(() => expect(vi.mocked(openOAuthPopup)).toHaveBeenCalled());
+ // The ordering IS the fix — asserting only that it was called would pass
+ // on a version that called it after the await, which is the bug.
+ expect(callOrder).toEqual(["preOpen", "initiate"]);
+ expect(vi.mocked(openOAuthPopup)).toHaveBeenCalledWith(
+ "https://auth.example.com/authorize",
+ expect.objectContaining({ preOpenedWindow: fakeWindow }),
+ );
+ expect(fakeWindow.close).not.toHaveBeenCalled();
+ });
+
+ it("closes the sign-in window when the server has no OAuth", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const {
+ postV2DiscoverAvailableToolsOnAnMcpServer,
+ postV2InitiateOauthLoginForAnMcpServer,
+ } = await import("@/app/api/__generated__/endpoints/mcp/mcp");
+ const { preOpenOAuthPopup } = await import("@/lib/oauth-popup");
+
+ vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValueOnce(
+ apiResponse(401, { detail: "Authentication required" }),
+ );
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(
+ fakeWindow as unknown as Window,
+ );
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(
+ apiResponse(400, {
+ detail: { code: "no_oauth", message: "OAuth not supported" },
+ }),
+ );
+
+ render(<MCPToolDialog open onClose={() => {}} onConfirm={vi.fn()} />);
+ fireEvent.change(screen.getByLabelText("Server URL"), {
+ target: { value: PRIVATE_SERVER_URL },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Discover Tools" }));
+
+ // openOAuthPopup never runs on this path, so nothing else can reach the
+ // about:blank window it left behind.
+ await waitFor(() => expect(fakeWindow.close).toHaveBeenCalled());
+ expect(await screen.findByLabelText("API token")).toBeDefined();
+ });
+
it("attaches a manually stored credential to a tool from the same server", async () => {
const {
postV2DiscoverAvailableToolsOnAnMcpServer,
@@ -219,7 +396,9 @@ describe("MCPToolDialog credential binding", () => {
}),
);
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(
- apiResponse(400, { detail: "OAuth not supported" }),
+ apiResponse(400, {
+ detail: { code: "no_oauth", message: "OAuth not supported" },
+ }),
);
vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce(
apiResponse(200, CREDENTIAL),
@@ -259,7 +438,9 @@ describe("MCPToolDialog credential binding", () => {
apiResponse(401, { detail: "Authentication required" }),
);
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(
- apiResponse(400, { detail: "OAuth not supported" }),
+ apiResponse(400, {
+ detail: { code: "no_oauth", message: "OAuth not supported" },
+ }),
);
const providers = {
@@ -308,7 +489,9 @@ describe("MCPToolDialog credential binding", () => {
apiResponse(401, { detail: "Invalid API credential" }),
);
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(
- apiResponse(400, { detail: "OAuth not supported" }),
+ apiResponse(400, {
+ detail: { code: "no_oauth", message: "OAuth not supported" },
+ }),
);
render(<MCPToolDialog open onClose={() => {}} onConfirm={() => {}} />);
@@ -335,7 +518,9 @@ describe("MCPToolDialog credential binding", () => {
apiResponse(401, { detail: "Authentication required" }),
);
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce(
- apiResponse(400, { detail: "OAuth not supported" }),
+ apiResponse(400, {
+ detail: { code: "no_oauth", message: "OAuth not supported" },
+ }),
);
render(<MCPToolDialog open onClose={() => {}} onConfirm={() => {}} />);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx
index aa6b7f0d4a..b0199be062 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/MCPSetupCard.tsx
@@ -3,8 +3,6 @@
import { useGetV1ListCredentials } from "@/app/api/__generated__/endpoints/integrations/integrations";
import {
postV2DiscoverAvailableToolsOnAnMcpServer,
- postV2ExchangeOauthCodeForMcpTokens,
- postV2InitiateOauthLoginForAnMcpServer,
postV2StoreABearerTokenForAnMcpServer,
} from "@/app/api/__generated__/endpoints/mcp/mcp";
import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
@@ -23,9 +21,9 @@ import {
validateMCPAuthCredential,
type MCPAuthScheme,
} from "@/lib/mcp-auth";
-import { getAPIResponseError, getErrorStatus } from "@/lib/mcp-errors";
+import { getErrorMessage } from "@/lib/mcp-errors";
import { normalizeMcpUrl } from "@/lib/mcp-url";
-import { openOAuthPopup } from "@/lib/oauth-popup";
+import { connectMCPOAuth } from "@/lib/mcp-oauth";
import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";
import { useContext, useEffect, useId, useRef, useState } from "react";
import { useCopilotChatActions } from "../../../../components/CopilotChatActionsProvider/useCopilotChatActions";
@@ -147,8 +145,7 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
// user couldn't see the error banner or the manual-token input. Reset
// on the next attempt so the user can retry.
const [forceDisconnected, setForceDisconnected] = useState(false);
- const oauthAbortRef = useRef<(() => void) | null>(null);
-
+ const oauthRequest = useRef<AbortController | null>(null);
// Combined view:
// 1. ``forceDisconnected`` (set by the catch block) wins.
// 2. ``localConnected`` (just completed sign-in in this component) wins.
@@ -166,118 +163,51 @@ export function MCPSetupCard({ output, retryInstruction }: Props) {
// ``true`` after a successful flow or ``false`` to drop the pill.
const setConnected = setLocalConnected;
- // Abort any in-progress OAuth popup when the component unmounts.
- useEffect(() => () => oauthAbortRef.current?.(), []);
+ useEffect(() => () => oauthRequest.current?.abort(), []);
async function handleConnect() {
- // Re-entrancy guard: a rapid double-click would otherwise race the
- // two in-flight ``handleConnect`` invocations — the second one aborts
- // the first's popup (``oauthAbortRef.current?.()``) but the first's
- // ``await promise`` then rejects with ``OAUTH_ERROR_FLOW_CANCELED``,
- // which flips ``forceDisconnected=true`` even though the second
- // attempt is still alive. Bail out cheaply when a flow is already
- // running. Button is also ``disabled={loading}`` but disabled
- // <button> elements still fire ``click`` in some browsers.
- if (loading) return;
+ if (loading || oauthRequest.current) return;
+ const controller = new AbortController();
+ oauthRequest.current = controller;
+ const { signal } = controller;
setError(null);
- // Reset showManualToken so a prior 400 doesn't keep the input visible
- // when a later attempt fails with a non-400 (e.g. network) error.
setShowManualToken(false);
setLoading(true);
- oauthAbortRef.current?.();
-
try {
- // Only a 400 from the *initiate* call means "this server has no OAuth
- // to offer" and justifies the manual-token fallback. A 400 from the
- // callback is a rejected authorization response — a failed issuer
- // check, say — and must surface as the error it is rather than an
- // invitation to paste a credential instead.
- let loginRes: Awaited<
- ReturnType<typeof postV2InitiateOauthLoginForAnMcpServer>
- >;
- try {
- loginRes = await postV2InitiateOauthLoginForAnMcpServer({
- server_url: serverUrl,
- });
- if (!(loginRes.status >= 200 && loginRes.status < 300)) {
- throw getAPIResponseError(loginRes.status, loginRes.data);
- }
- } catch (e: unknown) {
- if (getErrorStatus(e) === 400) {
- setConnected(false);
- setForceDisconnected(true);
- setShowManualToken(true);
- setError(
- "This server does not support OAuth sign-in. Choose how its API credential should be sent.",
- );
- return;
- }
- throw e;
- }
- const { login_url, state_token } = loginRes.data as {
- login_url: string;
- state_token: string;
- };
-
- const { promise, cleanup } = openOAuthPopup(login_url, {
- stateToken: state_token,
- useCrossOriginListeners: true,
+ const credential = await connectMCPOAuth({
+ serverURL: serverUrl,
+ signal,
+ exchange: allProviders?.mcp?.mcpOAuthCallback,
});
- oauthAbortRef.current = cleanup.abort;
-
- const result = await promise;
-
- const mcpProvider = allProviders?.["mcp"];
- if (mcpProvider) {
- await mcpProvider.mcpOAuthCallback(
- result.code,
- state_token,
- result.iss,
- );
- } else {
- const cbRes = await postV2ExchangeOauthCodeForMcpTokens({
- code: result.code,
- state_token,
- iss: result.iss,
- });
- if (!(cbRes.status >= 200 && cbRes.status < 300)) {
- throw getAPIResponseError(cbRes.status, cbRes.data);
- }
+ signal.throwIfAborted();
+ if ("reason" in credential) {
+ setConnected(false);
+ setForceDisconnected(true);
+ if (credential.noOAuth) setShowManualToken(true);
+ setError(credential.reason);
+ return;
}
-
- // Only clear the force-disconnect override AFTER the OAuth dance
- // completes successfully. Clearing it earlier would let
- // ``liveHasCred=true`` (Reconnect path) render the Connected pill
- // mid-flight, briefly contradicting the in-progress "Reconnecting…"
- // affordance.
setForceDisconnected(false);
setConnected(true);
onSend(retryInstruction ?? "I've connected. Please retry.");
- } catch (e: unknown) {
- const err = e as Record<string, unknown>;
- // Reconnect failures must drop the Connected view so the user sees
- // the error / manual-token input rendered by the not-connected
- // branch. Setting ``localConnected=false`` alone isn't enough when
- // a stored cred still exists (``liveHasCred=true``) — flip
- // ``forceDisconnected`` so the not-connected branch wins until the
- // user retries.
+ } catch (error: unknown) {
+ if (signal.aborted) return;
setConnected(false);
setForceDisconnected(true);
- if (
- typeof err?.message === "string" &&
- err.message === "OAuth flow timed out"
- ) {
- setError("OAuth sign-in timed out. Please try again.");
- } else {
- const msg =
- (typeof err?.message === "string" ? err.message : null) ||
- (typeof err?.detail === "string" ? err.detail : null) ||
- "Failed to complete sign-in. Please try again.";
- setError(msg);
- }
+ const message = getErrorMessage(
+ error,
+ "Failed to complete sign-in. Please try again.",
+ );
+ setError(
+ message === "OAuth flow timed out"
+ ? "OAuth sign-in timed out. Please try again."
+ : message,
+ );
} finally {
- setLoading(false);
- oauthAbortRef.current = null;
+ if (oauthRequest.current === controller) {
+ oauthRequest.current = null;
+ if (!signal.aborted) setLoading(false);
+ }
}
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx
index 4045b24bcc..d81dff9431 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunMCPTool/components/MCPSetupCard/__tests__/MCPSetupCard.test.tsx
@@ -30,6 +30,10 @@ vi.mock(
// Mock the OAuth popup utility
vi.mock("@/lib/oauth-popup", () => ({
openOAuthPopup: vi.fn(),
+ // Defaults to null — the browser-blocked case — so every cell that does not
+ // care about the sign-in window behaves as it did before the window was
+ // pre-opened at all.
+ preOpenOAuthPopup: vi.fn(() => null),
}));
// Mock the generated API functions
@@ -222,7 +226,7 @@ describe("MCPSetupCard", () => {
);
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth support" },
+ data: { detail: { code: "no_oauth", message: "No OAuth support" } },
headers: new Headers(),
} as never);
@@ -234,7 +238,7 @@ describe("MCPSetupCard", () => {
await waitFor(() => {
expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();
});
- expect(screen.getByText(/does not support OAuth/)).toBeDefined();
+ expect(screen.getByText(/No OAuth/)).toBeDefined();
});
it("surfaces a rejected authorization response instead of offering a token", async () => {
@@ -292,12 +296,12 @@ describe("MCPSetupCard", () => {
vi.mocked(postV2InitiateOauthLoginForAnMcpServer)
.mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth support" },
+ data: { detail: { code: "no_oauth", message: "No OAuth support" } },
headers: new Headers(),
} as never)
.mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth support" },
+ data: { detail: { code: "no_oauth", message: "No OAuth support" } },
headers: new Headers(),
} as never);
@@ -342,7 +346,7 @@ describe("MCPSetupCard", () => {
// First click: OAuth fails with 400 → shows manual token input
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth" },
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
headers: new Headers(),
} as never);
@@ -391,7 +395,7 @@ describe("MCPSetupCard", () => {
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth" },
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
headers: new Headers(),
} as never);
vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({
@@ -446,7 +450,7 @@ describe("MCPSetupCard", () => {
} = await import("@/app/api/__generated__/endpoints/mcp/mcp");
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth" },
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
headers: new Headers(),
} as never);
vi.mocked(postV2StoreABearerTokenForAnMcpServer).mockResolvedValueOnce({
@@ -497,7 +501,7 @@ describe("MCPSetupCard", () => {
);
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth support" },
+ data: { detail: { code: "no_oauth", message: "No OAuth support" } },
headers: new Headers(),
} as never);
@@ -512,7 +516,7 @@ describe("MCPSetupCard", () => {
await waitFor(() => {
expect(screen.getByPlaceholderText(manualTokenPlaceholder)).toBeDefined();
});
- expect(screen.getByText(/does not support OAuth/)).toBeDefined();
+ expect(screen.getByText(/No OAuth/)).toBeDefined();
expect(screen.queryByText(/connected to example\.com/i)).toBeNull();
});
@@ -531,7 +535,7 @@ describe("MCPSetupCard", () => {
);
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth support" },
+ data: { detail: { code: "no_oauth", message: "No OAuth support" } },
headers: new Headers(),
} as never);
@@ -578,7 +582,7 @@ describe("MCPSetupCard", () => {
// Drain the in-flight promise so React doesn't warn on unmount.
resolveLogin?.({
status: 400,
- data: { detail: "No OAuth" },
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
headers: new Headers(),
});
await waitFor(() => {
@@ -586,6 +590,79 @@ describe("MCPSetupCard", () => {
});
});
+ // #14532: the sign-in window has to be opened inside the tap, before the
+ // initiate request is awaited — iOS Safari discards the gesture context at
+ // the first async break and then blocks window.open() outright.
+ it("opens the sign-in window before the initiate await and hands it over", async () => {
+ const callOrder: string[] = [];
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+ vi.mocked(preOpenOAuthPopup).mockClear();
+ vi.mocked(preOpenOAuthPopup).mockImplementation(() => {
+ callOrder.push("preOpen");
+ return fakeWindow as unknown as Window;
+ });
+ vi.mocked(openOAuthPopup).mockReturnValue({
+ promise: new Promise(() => {}),
+ cleanup: { abort: vi.fn() },
+ } as never);
+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(
+ "@/app/api/__generated__/endpoints/mcp/mcp"
+ );
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockImplementation(
+ async () => {
+ callOrder.push("initiate");
+ return {
+ status: 200,
+ data: { login_url: "https://login.example.com", state_token: "tok" },
+ headers: new Headers(),
+ } as never;
+ },
+ );
+
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /connect example\.com/i }),
+ );
+
+ await waitFor(() => expect(vi.mocked(openOAuthPopup)).toHaveBeenCalled());
+ // The ordering IS the fix — asserting only that it was called would pass
+ // on a version that called it after the await, which is the bug.
+ expect(callOrder).toEqual(["preOpen", "initiate"]);
+ expect(vi.mocked(openOAuthPopup)).toHaveBeenCalledWith(
+ "https://login.example.com",
+ expect.objectContaining({ preOpenedWindow: fakeWindow }),
+ );
+ expect(fakeWindow.close).not.toHaveBeenCalled();
+ });
+
+ it("closes the sign-in window when the server has no OAuth", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const { preOpenOAuthPopup } = await import("@/lib/oauth-popup");
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(
+ fakeWindow as unknown as Window,
+ );
+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(
+ "@/app/api/__generated__/endpoints/mcp/mcp"
+ );
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
+ status: 400,
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
+ headers: new Headers(),
+ } as never);
+
+ render(<MCPSetupCard output={makeSetupOutput()} />);
+ fireEvent.click(
+ screen.getByRole("button", { name: /connect example\.com/i }),
+ );
+
+ // openOAuthPopup never runs on this path, so nothing else can reach the
+ // about:blank window it left behind.
+ await waitFor(() => expect(fakeWindow.close).toHaveBeenCalled());
+ });
+
it("shows timeout-specific error message when OAuth popup times out", async () => {
const { postV2InitiateOauthLoginForAnMcpServer } = await import(
"@/app/api/__generated__/endpoints/mcp/mcp"
@@ -700,7 +777,7 @@ describe("MCPSetupCard", () => {
} = await import("@/app/api/__generated__/endpoints/mcp/mcp");
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth" },
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
headers: new Headers(),
} as never);
@@ -794,7 +871,7 @@ describe("MCPSetupCard", () => {
} = await import("@/app/api/__generated__/endpoints/mcp/mcp");
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth" },
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
headers: new Headers(),
} as never);
vi.mocked(postV2DiscoverAvailableToolsOnAnMcpServer).mockResolvedValue({
@@ -829,7 +906,7 @@ describe("MCPSetupCard", () => {
} = await import("@/app/api/__generated__/endpoints/mcp/mcp");
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth" },
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
headers: new Headers(),
} as never);
@@ -864,7 +941,7 @@ describe("MCPSetupCard", () => {
} = await import("@/app/api/__generated__/endpoints/mcp/mcp");
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth" },
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
headers: new Headers(),
} as never);
// Never settles: pins the in-flight state.
@@ -901,7 +978,7 @@ describe("MCPSetupCard", () => {
} = await import("@/app/api/__generated__/endpoints/mcp/mcp");
vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValueOnce({
status: 400,
- data: { detail: "No OAuth" },
+ data: { detail: { code: "no_oauth", message: "No OAuth" } },
headers: new Headers(),
} as never);
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/McpConnectPanel.test.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/McpConnectPanel.test.tsx
index 9d195418f3..9a9f0dcdc8 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/McpConnectPanel.test.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/McpConnectPanel.test.tsx
@@ -1,4 +1,5 @@
import {
+ act,
cleanup,
fireEvent,
render,
@@ -12,6 +13,10 @@ import { McpConnectPanel } from "../McpConnectPanel";
vi.mock("@/lib/oauth-popup", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/oauth-popup")>()),
openOAuthPopup: vi.fn(),
+ // Defaults to null — the browser-blocked case — so every cell that does not
+ // care about the sign-in window behaves as it did before the window was
+ // pre-opened at all.
+ preOpenOAuthPopup: vi.fn(() => null),
}));
vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({
@@ -105,6 +110,195 @@ describe("McpConnectPanel", () => {
expect((connectButton as HTMLButtonElement).disabled).toBe(false);
});
+ // #14532: the sign-in window has to be opened inside the tap, before the
+ // initiate request is awaited. iOS Safari discards the gesture context at the
+ // first async break and then blocks window.open() outright — including the
+ // new-tab fallback — so on mobile nothing opened at all.
+ describe("user activation (#14532)", () => {
+ async function mockInitiateOk(record?: string[]) {
+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(
+ "@/app/api/__generated__/endpoints/mcp/mcp"
+ );
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockImplementation(
+ async () => {
+ record?.push("initiate");
+ return {
+ status: 200,
+ data: {
+ login_url: "https://login.example.com",
+ state_token: "tok",
+ },
+ headers: new Headers(),
+ } as never;
+ },
+ );
+ }
+
+ function clickConnect() {
+ fireEvent.change(screen.getByLabelText(/server url/i), {
+ target: { value: "https://mcp.example.com" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /connect/i }));
+ }
+
+ it("opens the window before the initiate await and hands it to openOAuthPopup", async () => {
+ const callOrder: string[] = [];
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+ vi.mocked(preOpenOAuthPopup).mockImplementation(() => {
+ callOrder.push("preOpen");
+ return fakeWindow as unknown as Window;
+ });
+ vi.mocked(openOAuthPopup).mockReturnValue({
+ promise: new Promise(() => {}),
+ cleanup: { abort: vi.fn() },
+ } as never);
+ await mockInitiateOk(callOrder);
+
+ render(<McpConnectPanel onSuccess={() => {}} />);
+ clickConnect();
+
+ await waitFor(() => expect(vi.mocked(openOAuthPopup)).toHaveBeenCalled());
+ // The ordering IS the fix. Asserting only that preOpenOAuthPopup was
+ // called would pass on a version that called it after the await, which
+ // is the bug.
+ expect(callOrder).toEqual(["preOpen", "initiate"]);
+ expect(vi.mocked(openOAuthPopup)).toHaveBeenCalledWith(
+ "https://login.example.com",
+ expect.objectContaining({
+ stateToken: "tok",
+ preOpenedWindow: fakeWindow,
+ useCrossOriginListeners: true,
+ }),
+ );
+ // Ownership moved to the helper, which closes it on abort.
+ expect(fakeWindow.close).not.toHaveBeenCalled();
+ });
+
+ it("closes the window when the server turns out not to support OAuth", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const { preOpenOAuthPopup } = await import("@/lib/oauth-popup");
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(
+ fakeWindow as unknown as Window,
+ );
+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(
+ "@/app/api/__generated__/endpoints/mcp/mcp"
+ );
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockRejectedValueOnce(
+ makeApiError(400, noOAuthDetail.detail),
+ );
+
+ render(<McpConnectPanel onSuccess={() => {}} />);
+ clickConnect();
+
+ // The 400 returns early from inside the try, before openOAuthPopup ever
+ // runs — an about:blank window would otherwise sit there for good.
+ await waitFor(() => expect(fakeWindow.close).toHaveBeenCalled());
+ expect(screen.getByPlaceholderText(/paste api token/i)).toBeDefined();
+ });
+
+ it("closes the window when the initiate request fails outright", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const { preOpenOAuthPopup } = await import("@/lib/oauth-popup");
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(
+ fakeWindow as unknown as Window,
+ );
+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(
+ "@/app/api/__generated__/endpoints/mcp/mcp"
+ );
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockRejectedValueOnce(
+ makeApiError(500, "server exploded"),
+ );
+
+ render(<McpConnectPanel onSuccess={() => {}} />);
+ clickConnect();
+
+ await waitFor(() => expect(fakeWindow.close).toHaveBeenCalled());
+ });
+
+ it("closes the window when the panel unmounts mid-initiation", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(
+ fakeWindow as unknown as Window,
+ );
+ const { postV2InitiateOauthLoginForAnMcpServer } = await import(
+ "@/app/api/__generated__/endpoints/mcp/mcp"
+ );
+ let release: (() => void) | undefined;
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ release = () =>
+ resolve({
+ status: 200,
+ data: {
+ login_url: "https://login.example.com",
+ state_token: "tok",
+ },
+ headers: new Headers(),
+ } as never);
+ }),
+ );
+
+ const { unmount } = render(<McpConnectPanel onSuccess={() => {}} />);
+ clickConnect();
+ await waitFor(() =>
+ expect(vi.mocked(preOpenOAuthPopup)).toHaveBeenCalled(),
+ );
+
+ // The dialog closes while the login URL is still in flight. Nothing has
+ // registered an abort yet, so the unmount cleanup is the only thing that
+ // can reach this window.
+ unmount();
+ expect(fakeWindow.close).toHaveBeenCalled();
+
+ release?.();
+ await Promise.resolve();
+ // And the continuation must not adopt a window that is already gone.
+ expect(vi.mocked(openOAuthPopup)).not.toHaveBeenCalled();
+ });
+
+ it("a double tap starts one flow, not two", async () => {
+ const fakeWindow = { closed: false, close: vi.fn() };
+ const { openOAuthPopup, preOpenOAuthPopup } = await import(
+ "@/lib/oauth-popup"
+ );
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(
+ fakeWindow as unknown as Window,
+ );
+ vi.mocked(openOAuthPopup).mockReturnValue({
+ promise: new Promise(() => {}),
+ cleanup: { abort: vi.fn() },
+ } as never);
+ await mockInitiateOk();
+
+ render(<McpConnectPanel onSuccess={() => {}} />);
+ fireEvent.change(screen.getByLabelText(/server url/i), {
+ target: { value: "https://mcp.example.com" },
+ });
+ const button = screen.getByRole("button", { name: /connect/i });
+ // Both taps inside ONE act() batch. fireEvent flushes React state
+ // between events, so two fireEvent.click calls let the second one see
+ // `isSubmitting === true` and the disabled-button guard already holds —
+ // which is exactly the flush a real double-tap inside one frame does not
+ // get. Dispatching both before the flush is what reproduces it.
+ await act(async () => {
+ button.click();
+ button.click();
+ });
+
+ await waitFor(() => expect(vi.mocked(openOAuthPopup)).toHaveBeenCalled());
+ // Two windows would mean the second flow overwrote the first's handle
+ // and the first one could never be closed.
+ expect(vi.mocked(preOpenOAuthPopup)).toHaveBeenCalledTimes(1);
+ });
+ });
+
it("allows manual authentication without first attempting OAuth", async () => {
const { postV2InitiateOauthLoginForAnMcpServer } = await import(
"@/app/api/__generated__/endpoints/mcp/mcp"
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/mcpOAuth.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/mcpOAuth.ts
deleted file mode 100644
index aeacf7d3ac..0000000000
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/mcpOAuth.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import {
- postV2ExchangeOauthCodeForMcpTokens,
- postV2InitiateOauthLoginForAnMcpServer,
-} from "@/app/api/__generated__/endpoints/mcp/mcp";
-import {
- getAPIResponseError,
- getErrorCode,
- getErrorMessage,
- getErrorStatus,
-} from "@/lib/mcp-errors";
-import { openOAuthPopup } from "@/lib/oauth-popup";
-
-interface Args {
- serverURL: string;
- scopes?: string[];
- signal: AbortSignal;
-}
-
-/** Mirrors `NO_OAUTH_CODE` in `backend/api/features/mcp/routes.py`. */
-export const NO_OAUTH_CODE = "no_oauth";
-
-export async function connectMCPOAuth({ serverURL, scopes, signal }: Args) {
- signal.throwIfAborted();
- let login;
- try {
- login = await postV2InitiateOauthLoginForAnMcpServer(
- {
- server_url: serverURL,
- ...(scopes === undefined ? {} : { scopes }),
- },
- { signal },
- );
- signal.throwIfAborted();
- if (login.status !== 200)
- throw getAPIResponseError(login.status, login.data);
- } catch (error) {
- signal.throwIfAborted();
- // The login route writes eight different 400s, each explaining a
- // different failure. Returning a bare null threw all of them away and
- // told the user to find an API token, even when the real cause was a
- // failed client registration on a server that does support OAuth. Hand
- // the reason back, with the route's own verdict on whether this server
- // has any OAuth to offer, so the caller can show one and branch on the
- // other instead of reading the prose.
- if (getErrorStatus(error) === 400)
- return {
- reason: getErrorMessage(error),
- noOAuth: getErrorCode(error) === NO_OAUTH_CODE,
- } as const;
- throw error;
- }
- signal.throwIfAborted();
- const { login_url, state_token } = login.data;
- const { promise, cleanup } = openOAuthPopup(login_url, {
- stateToken: state_token,
- useCrossOriginListeners: true,
- });
- function abortPopup() {
- cleanup.abort();
- }
- signal.addEventListener("abort", abortPopup, { once: true });
- try {
- if (signal.aborted) abortPopup();
- signal.throwIfAborted();
- const result = await promise;
- signal.throwIfAborted();
- const exchanged = await postV2ExchangeOauthCodeForMcpTokens(
- {
- code: result.code,
- state_token,
- iss: result.iss,
- },
- { signal },
- );
- signal.throwIfAborted();
- if (exchanged.status !== 200)
- throw getAPIResponseError(exchanged.status, exchanged.data);
- return exchanged.data;
- } finally {
- signal.removeEventListener("abort", abortPopup);
- }
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useMCPConnectPanel.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useMCPConnectPanel.ts
index 4fa48c8dff..567f82fcbe 100644
--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useMCPConnectPanel.ts
+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useMCPConnectPanel.ts
@@ -8,7 +8,7 @@ import { getErrorMessage } from "@/lib/mcp-errors";
import { normalizeMcpUrl } from "@/lib/mcp-url";
import { OAUTH_ERROR_FLOW_CANCELED } from "@/lib/oauth-popup";
import { invalidateConnectionQueries } from "@/lib/react-query/invalidateConnections";
-import { connectMCPOAuth } from "./mcpOAuth";
+import { connectMCPOAuth } from "@/lib/mcp-oauth";
import { storeMCPToken } from "./storeMCPToken";
import { useMCPManualAuth } from "./useMCPManualAuth";
@@ -53,7 +53,11 @@ export function useMCPConnectPanel({
manual.token.trim().length > 0;
async function handleConnect() {
- if (!canConnect) return;
+ if (
+ !canConnect ||
+ (activeRequest.current && !activeRequest.current.signal.aborted)
+ )
+ return;
setError(null);
setIsSubmitting(true);
const signal = startRequest();
@@ -103,12 +107,19 @@ export function useMCPConnectPanel({
: message,
);
} finally {
- if (!signal.aborted) setIsSubmitting(false);
+ if (activeRequest.current?.signal === signal) {
+ activeRequest.current = null;
+ if (!signal.aborted) setIsSubmitting(false);
+ }
}
}
async function handleSubmitToken() {
- if (!canSubmitToken) return;
+ if (
+ !canSubmitToken ||
+ (activeRequest.current && !activeRequest.current.signal.aborted)
+ )
+ return;
const invalid = manual.validateToken();
if (invalid) {
setError(invalid);
@@ -132,7 +143,10 @@ export function useMCPConnectPanel({
if (signal.aborted) return;
setError(getErrorMessage(error));
} finally {
- if (!signal.aborted) setIsSubmitting(false);
+ if (activeRequest.current?.signal === signal) {
+ activeRequest.current = null;
+ if (!signal.aborted) setIsSubmitting(false);
+ }
}
}
diff --git a/autogpt_platform/frontend/src/lib/__tests__/mcp-oauth.test.ts b/autogpt_platform/frontend/src/lib/__tests__/mcp-oauth.test.ts
new file mode 100644
index 0000000000..3aaad34718
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/__tests__/mcp-oauth.test.ts
@@ -0,0 +1,117 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { connectMCPOAuth } from "../mcp-oauth";
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
+import { openOAuthPopup, preOpenOAuthPopup } from "../oauth-popup";
+import {
+ postV2InitiateOauthLoginForAnMcpServer,
+ postV2ExchangeOauthCodeForMcpTokens,
+} from "@/app/api/__generated__/endpoints/mcp/mcp";
+
+vi.mock("@/app/api/__generated__/endpoints/mcp/mcp", () => ({
+ postV2InitiateOauthLoginForAnMcpServer: vi.fn(),
+ postV2ExchangeOauthCodeForMcpTokens: vi.fn(),
+}));
+vi.mock("../oauth-popup", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../oauth-popup")>()),
+ preOpenOAuthPopup: vi.fn(),
+ openOAuthPopup: vi.fn(),
+}));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+const login = {
+ status: 200 as const,
+ data: { login_url: "https://login.example.com", state_token: "state" },
+ headers: new Headers(),
+};
+
+describe("MCP OAuth attempt ownership", () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ });
+
+ it("closes a canceled initiation and ignores its late response", async () => {
+ const pending = deferred<typeof login>();
+ const popup = { closed: false, close: vi.fn() };
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(popup as unknown as Window);
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockReturnValue(
+ pending.promise,
+ );
+ const controller = new AbortController();
+ const result = connectMCPOAuth({
+ serverURL: "https://mcp.example.com",
+ signal: controller.signal,
+ });
+ const rejected = expect(result).rejects.toMatchObject({
+ name: "AbortError",
+ });
+
+ controller.abort();
+ expect(popup.close).toHaveBeenCalledOnce();
+ pending.resolve(login);
+ await rejected;
+
+ expect(openOAuthPopup).not.toHaveBeenCalled();
+ expect(postV2ExchangeOauthCodeForMcpTokens).not.toHaveBeenCalled();
+ expect(popup.close).toHaveBeenCalledOnce();
+ });
+
+ it("does not reopen a blank window the user already closed", async () => {
+ const pending = deferred<typeof login>();
+ const popup = { closed: false, close: vi.fn() };
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(popup as unknown as Window);
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockReturnValue(
+ pending.promise,
+ );
+ const result = connectMCPOAuth({
+ serverURL: "https://mcp.example.com",
+ signal: new AbortController().signal,
+ });
+ const rejected = expect(result).rejects.toThrow(
+ "Sign-in window was closed",
+ );
+ popup.closed = true;
+ pending.resolve(login);
+ await rejected;
+ expect(openOAuthPopup).not.toHaveBeenCalled();
+ });
+
+ it("rejects a late exchange result after cancellation", async () => {
+ const pending = deferred<CredentialsMetaResponse>();
+ const exchange = vi.fn(() => pending.promise);
+ vi.mocked(postV2InitiateOauthLoginForAnMcpServer).mockResolvedValue(login);
+ vi.mocked(preOpenOAuthPopup).mockReturnValue(null);
+ vi.mocked(openOAuthPopup).mockReturnValue({
+ promise: Promise.resolve({ code: "code", state: "state" }),
+ cleanup: { abort: vi.fn(), signal: new AbortController().signal },
+ popupBlocked: false,
+ fallbackBlocked: false,
+ });
+ const controller = new AbortController();
+ const result = connectMCPOAuth({
+ serverURL: "https://mcp.example.com",
+ signal: controller.signal,
+ exchange,
+ });
+ const rejected = expect(result).rejects.toMatchObject({
+ name: "AbortError",
+ });
+ await vi.waitFor(() => expect(exchange).toHaveBeenCalledOnce());
+ controller.abort();
+ pending.resolve({
+ id: "credential",
+ provider: "mcp",
+ type: "oauth2",
+ title: null,
+ scopes: null,
+ username: null,
+ });
+ await rejected;
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/mcp-oauth.ts b/autogpt_platform/frontend/src/lib/mcp-oauth.ts
new file mode 100644
index 0000000000..d9f83789e9
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/mcp-oauth.ts
@@ -0,0 +1,123 @@
+import {
+ postV2ExchangeOauthCodeForMcpTokens,
+ postV2InitiateOauthLoginForAnMcpServer,
+} from "@/app/api/__generated__/endpoints/mcp/mcp";
+import {
+ getAPIResponseError,
+ getErrorCode,
+ getErrorMessage,
+ getErrorStatus,
+} from "@/lib/mcp-errors";
+import {
+ OAUTH_ERROR_WINDOW_CLOSED,
+ openOAuthPopup,
+ preOpenOAuthPopup,
+} from "@/lib/oauth-popup";
+import type { CredentialsMetaResponse } from "@/app/api/__generated__/models/credentialsMetaResponse";
+
+interface Args {
+ serverURL: string;
+ scopes?: string[];
+ signal: AbortSignal;
+ exchange?: (
+ code: string,
+ state: string,
+ iss?: string,
+ ) => Promise<
+ Pick<CredentialsMetaResponse, "id" | "provider" | "type"> &
+ Partial<CredentialsMetaResponse>
+ >;
+}
+
+/** Mirrors `NO_OAUTH_CODE` in `backend/api/features/mcp/routes.py`. */
+export const NO_OAUTH_CODE = "no_oauth";
+
+export async function connectMCPOAuth({
+ serverURL,
+ scopes,
+ signal,
+ exchange,
+}: Args) {
+ signal.throwIfAborted();
+ const preOpenedWindow = preOpenOAuthPopup();
+ let ownsBlankWindow = true;
+ let abortPopup: (() => void) | undefined;
+ function cancel() {
+ if (abortPopup) abortPopup();
+ else if (ownsBlankWindow) {
+ ownsBlankWindow = false;
+ if (preOpenedWindow && !preOpenedWindow.closed) preOpenedWindow.close();
+ }
+ }
+ signal.addEventListener("abort", cancel, { once: true });
+ try {
+ let login;
+ try {
+ login = await postV2InitiateOauthLoginForAnMcpServer(
+ {
+ server_url: serverURL,
+ ...(scopes === undefined ? {} : { scopes }),
+ },
+ { signal },
+ );
+ signal.throwIfAborted();
+ if (login.status !== 200)
+ throw getAPIResponseError(login.status, login.data);
+ } catch (error) {
+ signal.throwIfAborted();
+ // The login route writes eight different 400s, each explaining a
+ // different failure. Returning a bare null threw all of them away and
+ // told the user to find an API token, even when the real cause was a
+ // failed client registration on a server that does support OAuth. Hand
+ // the reason back, with the route's own verdict on whether this server
+ // has any OAuth to offer, so the caller can show one and branch on the
+ // other instead of reading the prose.
+ if (getErrorStatus(error) === 400)
+ return {
+ reason: getErrorMessage(error),
+ noOAuth: getErrorCode(error) === NO_OAUTH_CODE,
+ } as const;
+ throw error;
+ }
+ signal.throwIfAborted();
+ const { login_url, state_token } = login.data;
+ if (preOpenedWindow?.closed) throw new Error(OAUTH_ERROR_WINDOW_CLOSED);
+ const { promise, cleanup } = openOAuthPopup(login_url, {
+ stateToken: state_token,
+ preOpenedWindow,
+ useCrossOriginListeners: true,
+ });
+ abortPopup = function () {
+ cleanup.abort();
+ };
+ if (signal.aborted) cancel();
+ signal.throwIfAborted();
+ const result = await promise;
+ signal.throwIfAborted();
+ if (exchange) {
+ const credential = await exchange(result.code, state_token, result.iss);
+ signal.throwIfAborted();
+ return {
+ ...credential,
+ title: credential.title ?? null,
+ scopes: credential.scopes ?? null,
+ username: credential.username ?? null,
+ };
+ }
+ const exchanged = await postV2ExchangeOauthCodeForMcpTokens(
+ {
+ code: result.code,
+ state_token,
+ iss: result.iss,
+ },
+ { signal },
+ );
+ signal.throwIfAborted();
+ if (exchanged.status !== 200)
+ throw getAPIResponseError(exchanged.status, exchanged.data);
+ return exchanged.data;
+ } finally {
+ signal.removeEventListener("abort", cancel);
+ if (!abortPopup) cancel();
+ }
+}