fix(apps): recover MCP OAuth setup after consent errors (#13855)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Connections give agents governed access to external tools.
> - MCP aggregator setup can return from provider consent to a saved
draft.
> - The branded setup did not explain failed or cancelled authorization.
> - It also offered identity changes that the server does not apply when
a saved connection resumes.
> - This pull request explains OAuth return outcomes and keeps the
displayed identity consistent with the saved policy.
> - Users can understand the outcome and retry the same connection.

## Linked Issues or Issue Description

Related: #13755 introduced the MCP aggregators. #13758 retired the
legacy Composio broker. #13584 proposes changes to the provider handoff
window; this fix retains the current handoff behavior.

**What happened?**

Cancelling Composio consent returned to the setup form with no
explanation. The same controller ignored failed OAuth callback outcomes.
Returning to Access on a saved draft also offered personal/shared
choices, although the server retains the saved identity. This could make
the OAuth request disagree with that identity.

**Expected behavior**

Explain cancellation or failure, preserve the draft, and offer Try
again. Display the retained credential identity and start OAuth with the
policy returned by the server.

**Steps to reproduce**

1. Enable MCP aggregators and start a Composio connection.
2. Continue to provider consent and cancel it.
3. Observe the return screen. Before this change, it showed the form
without cancellation feedback.
4. Go back to Access. Before this change, the form offered
personal/shared choices even though resume retains the original
identity.

**Paperclip version or commit**

Observed before the fix on `8c6cc7dccf91523e0720bd86f95487e66b4b0e63`.
The original report of successful consent leaving setup unfinished did
not reproduce. This PR addresses the recovery defects observed during
that investigation.

**Deployment mode**

Isolated local development instance and authenticated staging
deployment, with real Composio consent and provider calls.

## What Changed

- Read the OAuth callback outcome in branded MCP setup and show
cancellation or failure feedback.
- Retry the same saved draft without displaying untrusted callback error
text.
- Keep saved personal/shared identity fixed in Access and select OAuth
identity from the returned credential policy.
- Add six focused regression cases and authorization-failure Storybook
states for Arcade, Composio, and Executor.
- Document return-screen recovery and retained identity in the connector
playbook.

## Verification

- `pnpm exec vitest run ui/src/pages/apps/AppsConnect.test.tsx -t 'OAuth
return' --maxWorkers=1`: 6 passed, 143 skipped, including after
integration with current master.
- `pnpm --filter @paperclipai/ui exec tsc --noEmit`: passed.
- `pnpm check:token-gates`: passed.
- `pnpm --filter @paperclipai/ui build`: passed.
- `pnpm --filter @paperclipai/ui build-storybook`: passed for the
implementation commit.
- Browser recovery: cancelled real Composio consent, observed the new
feedback, returned to Access, retried the same personal draft, completed
consent, and ran a real tool call.
- Staging on implementation commit
`84bb40aa70662e0c8955bf692c5714661b4bea93`: fresh shared and personal
connections each completed on the first consent attempt and loaded 11
tools. Real discovery, execution, and schema calls succeeded. Both
connections stayed Connected after reload. A real agent used the shared
connection through the Paperclip gateway and returned the public
repository documentation hierarchy with one success and zero errors.
- All current-head CI gates passed on
`662f84a67e867a52a2e5526026adbed00f6b59bf`. The Cursor execution and
agent-chat browser shards each had an initial timeout; both passed on
one targeted rerun without code changes. Greptile reviewed this exact
head at 5/5, with no open review threads.
- No full local suite was run, as requested. CI provides the broader
checks. The PR adds a master merge and documentation after the
live-tested implementation commit.

## Risks

- This shared setup controller also serves Arcade and Executor. Their
callback rendering and retry behavior have focused test coverage; this
investigation used Composio for live provider testing.
- Saved identity remains fixed during resume. A different identity
requires a new connection, consistent with server behavior.
- No database, protocol, credential storage, or gateway policy changes.

## Model Used

OpenAI GPT-6 via Codex, with code editing, shell tools, and browser
testing. The exact runtime model ID and context window size are not
exposed in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-23 08:05:30 -05:00
1 parent 7944ed3d97
commit 4721f55803
9 files changed
+72 -10

No files matched your search

+6
View File
@@ -458,6 +458,12 @@ connection work or enforce a real tenant boundary. Follow these rules:
- Show browser sign-in/pending/return only for a real OAuth handoff supported by
the chosen authentication. Zapier's pasted MCP URL or bearer token requires no
Paperclip sign-in window. Advanced token/header setups need no invented OAuth step.
- On an OAuth failure or cancellation, explain the outcome on the return screen
and offer a retry of the same saved connection. Do not silently return to a blank
setup form or display untrusted provider error text from the callback URL.
- Resuming a saved connection retains its credential identity. Show that identity
as fixed in Access, and start OAuth with the credential policy returned by the
server. Do not offer personal/shared choices that the server will ignore.
- Put optional narrowing in fields marked `advanced: true`.
- Give hidden fields a `defaultValue`; never create a hidden required field the
server cannot fill.
@@ -25,9 +25,10 @@ function FieldHelp({ label, children }: { label: string; children: ReactNode })
/** Controlled presentation shared by provider setup, configuration imports and review stories.
* Authentication, persistence and calls belong to the controller, never these views. */
export function RemoteMcpConnectionSetup({ provider, state: s, actions: a, agents, connectionId }: {
export function RemoteMcpConnectionSetup({ provider, state: s, actions: a, agents, connectionId, fixedGrantKind }: {
provider: RemoteMcpProvider;
connectionId: string;
fixedGrantKind?: RemoteMcpSetupState["grantKind"];
state: RemoteMcpSetupState;
actions: RemoteMcpSetupActions;
agents: { id: string; name: string }[];
@@ -49,6 +50,7 @@ export function RemoteMcpConnectionSetup({ provider, state: s, actions: a, agent
const footer = (children: ReactNode) => <SetupWizardFooter onSaveExit={a.saveExit} disabled={busy}>{children}</SetupWizardFooter>;
const error = s.connectStatus === "invalid_url" ? { title: "Enter a valid MCP URL", body: "Paste the complete server URL, including https:// or http://. A dashboard page is not an MCP endpoint." }
: s.connectStatus === "oauth_failed" ? { title: `${provider.name} couldn’t connect`, body: "Authorization did not complete. Your saved connection is still here, so you can try again." }
: s.connectStatus === "rejected" ? { title: "Credentials were rejected", body: `Check or replace the credentials from ${provider.name}, then reconnect. Your agent access and tool choices are preserved.` }
: s.connectStatus === "unreachable" ? { title: "Paperclip could not reach this server", body: "Check that the endpoint is running and reachable from Paperclip, then try again. Your draft is still here." }
: null;
@@ -61,7 +63,7 @@ export function RemoteMcpConnectionSetup({ provider, state: s, actions: a, agent
<main className="space-y-6">
{s.notice && <p role="status" className="text-sm text-muted-foreground">{s.notice}</p>}
{s.step === "access" && <AccessStepContent agents={agents} authKind="oauth" grantKind={s.grantKind} setGrantKind={(grantKind) => { if (grantKind !== "agent") change({ grantKind }); }}
{s.step === "access" && <AccessStepContent agents={agents} authKind="oauth" grantKinds={fixedGrantKind ? [fixedGrantKind] : undefined} grantKind={s.grantKind} setGrantKind={(grantKind) => { if (grantKind !== "agent") change({ grantKind }); }}
installChoice={s.allAgents ? "all" : "specific"} setInstallChoice={(choice) => change({ allAgents: choice === "all" })}
installAgentIds={new Set(s.agentIds)} setInstallAgentIds={(ids) => change({ agentIds: [...ids] })}
submitLabel={s.setupComplete ? "Done" : "Continue"} onBack={s.setupComplete ? a.finish : a.saveExit} onContinue={s.setupComplete ? a.finish : () => a.navigate("connect")} />}
@@ -4,7 +4,7 @@ import { REMOTE_MCP_CONNECTOR_METHODS, type ToolConnection } from "@paperclipai/
import { agentsApi } from "@/api/agents";
import { toolsApi } from "@/api/tools";
import { useCompany } from "@/context/CompanyContext";
import { useNavigate } from "@/lib/router";
import { useNavigate, useSearchParams } from "@/lib/router";
import { resolveAuthorizationTarget } from "@/lib/authorizationUrl";
import { navigateTopLevel } from "@/lib/browserNavigation";
import { queryKeys } from "@/lib/queryKeys";
@@ -27,6 +27,8 @@ export function RemoteMcpProductionSetup({ providerId, connection }: {
const provider = remoteMcpProviders[providerId];
const { selectedCompanyId } = useCompany();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const oauthOutcome = connection ? searchParams.get("oauth") : null;
const queries = useQueryClient();
const accessDraftKey = `paperclip:mcp-access-draft:${selectedCompanyId}:${providerId}`;
const savedConnection = useRef(connection);
@@ -37,7 +39,7 @@ export function RemoteMcpProductionSetup({ providerId, connection }: {
setupComplete: Boolean(connection && connection.status !== "draft"),
url: typeof connection?.config?.url === "string" ? connection.config?.url : provider.defaultUrl,
auth: connection?.config?.mcpAuthMode === "bearer" ? "bearer" : connection?.authKind === "api_key" ? "headers" : provider.supportsBrowserAuth ? "auto" : "none",
token: "", headers: [], advanced: false, connectStatus: "idle", connected: false,
token: "", headers: [], advanced: false, connectStatus: oauthOutcome === "denied" ? "cancelled" : oauthOutcome === "failed" ? "oauth_failed" : "idle", connected: false,
identity: null, allAgents: true, agentIds: [], permissions: {}, tools: [], notice: connection?.authKind === "api_key" ? "Saved credentials are retained when these fields are left blank. Enter a replacement only to change them." : null, refreshing: false,
...(!connection ? readAccessDraft(accessDraftKey) : {}),
}));
@@ -93,7 +95,7 @@ export function RemoteMcpProductionSetup({ providerId, connection }: {
}
if (saveDraft) { navigate("/apps"); return; }
if (result.auth?.kind === "oauth") {
const oauth = await toolsApi.startOAuth(result.connectionId, { asCurrentUser: state.grantKind === "user" });
const oauth = await toolsApi.startOAuth(result.connectionId, { asCurrentUser: result.connection.credentialPolicy === "per_user" });
const target = resolveAuthorizationTarget(oauth.authorizationUrl);
if (!target.ok) throw new Error(target.message);
authorizationUrl.current = target.url;
@@ -129,5 +131,5 @@ export function RemoteMcpProductionSetup({ providerId, connection }: {
refresh: () => {}, reconnect: () => edit({ step: "connect" }), disconnect: () => {},
};
if (connection && !installs.data) return <div className="space-y-3 p-8"><p>{installs.isError ? "Could not load saved access. Retry before changing this connection." : "Loading saved access…"}</p>{installs.isError && <button type="button" className="text-primary underline" onClick={() => void installs.refetch()}>Try again</button>}</div>;
return <RemoteMcpConnectionSetup provider={provider} connectionId={savedConnection.current?.id ?? ""} state={state} actions={actions} agents={agents.data ?? []} />;
return <RemoteMcpConnectionSetup provider={provider} connectionId={savedConnection.current?.id ?? ""} fixedGrantKind={savedConnection.current ? savedConnection.current.credentialPolicy === "per_user" ? "user" : "organization" : undefined} state={state} actions={actions} agents={agents.data ?? []} />;
}
@@ -2,7 +2,7 @@ import type { ToolCatalogEntry } from "@paperclipai/shared";
export type ToolPermission = "allowed" | "ask_first" | "off";
export type SetupStep = "access" | "connect" | "permissions" | "management" | "draft";
export type ConnectStatus = "idle" | "connecting" | "sign_in" | "returned" | "cancelled" | "invalid_url" | "rejected" | "unreachable";
export type ConnectStatus = "idle" | "connecting" | "sign_in" | "returned" | "cancelled" | "oauth_failed" | "invalid_url" | "rejected" | "unreachable";
export interface RemoteMcpTool extends ToolCatalogEntry {
broad?: boolean;
}
+49
View File
@@ -22,6 +22,7 @@ vi.mock("@/api/instanceSettings", () => ({ instanceSettingsApi: {
const listApplicationsMock = vi.hoisted(() => vi.fn());
const listConnectionsMock = vi.hoisted(() => vi.fn());
const getConnectionMock = vi.hoisted(() => vi.fn());
const getConnectionInstallsMock = vi.hoisted(() => vi.fn());
const connectAppMock = vi.hoisted(() => vi.fn());
const startOAuthMock = vi.hoisted(() => vi.fn());
const finishAppMock = vi.hoisted(() => vi.fn());
@@ -66,6 +67,7 @@ vi.mock("@/api/tools", () => ({
listApplications: (companyId: string) => listApplicationsMock(companyId),
listConnections: (companyId: string) => listConnectionsMock(companyId),
getConnection: (id: string) => getConnectionMock(id),
getConnectionInstalls: (id: string) => getConnectionInstallsMock(id),
connectApp: (companyId: string, input: unknown) => connectAppMock(companyId, input),
startOAuth: (connectionId: string, input?: unknown) => startOAuthMock(connectionId, input),
finishApp: (companyId: string, connectionId: string, input: unknown) =>
@@ -255,6 +257,7 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {
});
listApplicationsMock.mockResolvedValue({ applications: [] });
listConnectionsMock.mockResolvedValue({ connections: [] });
getConnectionInstallsMock.mockResolvedValue({ installs: [{ targetType: "company", targetId: "company-1" }] });
startOAuthMock.mockResolvedValue({
connectionId: "conn-notion",
provider: "notion",
@@ -327,6 +330,52 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => {
expect(startOAuthMock).not.toHaveBeenCalled();
});
it.each(["arcade", "composio", "executor"])("explains a failed %s OAuth return and retries the same saved draft", async (provider) => {
const draft = { id: "conn-oauth-draft", companyId: "company-1", status: "draft", authKind: "oauth", credentialPolicy: "shared", config: { sourceTemplateKey: provider, connectionMethodKey: "mcp", url: "https://example.com/mcp" } };
mockSearch.value = `source=${provider}&resume=${draft.id}&oauth=failed&code=oauth_callback_failed&error_description=untrusted-provider-message`;
experimentalMock.mockResolvedValue({ enableMcpAggregators: true });
getConnectionMock.mockResolvedValue(draft);
connectAppMock.mockResolvedValue({ connectionId: draft.id, connection: draft, catalog: [], auth: { kind: "oauth" } });
await render();
await vi.waitFor(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("Authorization did not complete"));
expect(container.textContent).not.toContain("untrusted-provider-message");
expect(buttonByText("Try again")).toBeTruthy();
await act(async () => buttonByText("Try again")!.click());
await vi.waitFor(() => expect(startOAuthMock).toHaveBeenCalledWith(draft.id, { asCurrentUser: false }));
expect(connectAppMock).toHaveBeenCalledWith("company-1", expect.objectContaining({ resumeConnectionId: draft.id }));
expect(navigateTopLevelMock).toHaveBeenCalled();
});
it("explains a declined Composio OAuth return without discarding the draft", async () => {
mockSearch.value = "source=composio&resume=conn-oauth-draft&oauth=denied&code=oauth_authorization_denied";
experimentalMock.mockResolvedValue({ enableMcpAggregators: true });
getConnectionMock.mockResolvedValue({ id: "conn-oauth-draft", status: "draft", authKind: "oauth", config: { sourceTemplateKey: "composio", connectionMethodKey: "mcp", url: "https://connect.composio.dev/mcp" } });
await render();
await vi.waitFor(() => expect(container.textContent).toContain("Connection cancelled. Your setup details are preserved"));
expect(buttonByText("Try again")).toBeTruthy();
expect(connectAppMock).not.toHaveBeenCalled();
});
it.each([
["shared", "Any human in the organization", false],
["per_user", "Just me", true],
])("retains the %s identity when returning to Access after an OAuth return", async (credentialPolicy, identityLabel, asCurrentUser) => {
const draft = { id: "conn-oauth-draft", status: "draft", authKind: "oauth", credentialPolicy, config: { sourceTemplateKey: "composio", connectionMethodKey: "mcp", url: "https://connect.composio.dev/mcp" } };
mockSearch.value = `source=composio&resume=${draft.id}&oauth=denied`;
experimentalMock.mockResolvedValue({ enableMcpAggregators: true });
getConnectionMock.mockResolvedValue(draft);
connectAppMock.mockResolvedValue({ connectionId: draft.id, connection: draft, catalog: [], auth: { kind: "oauth" } });
await render();
await vi.waitFor(() => expect(buttonByText("Back")).toBeTruthy());
await act(async () => buttonByText("Back")!.click());
expect(container.textContent).toContain(identityLabel);
expect(container.querySelector('[role="radiogroup"][aria-label="Which humans can use this credential?"]')).toBeNull();
await act(async () => buttonByText("Continue")!.click());
await act(async () => buttonByText("Try again")!.click());
await vi.waitFor(() => expect(startOAuthMock).toHaveBeenCalledWith(draft.id, { asCurrentUser }));
expect(connectAppMock).toHaveBeenCalledWith("company-1", expect.objectContaining({ resumeConnectionId: draft.id, grantKind: asCurrentUser ? "user" : "organization" }));
});
it("shows only MCP URL setup on the BYO page", async () => {
await render(undefined, true);
@@ -63,7 +63,7 @@ export function fixtureTools(provider: RemoteMcpProviderId, broad = false) {
}
export const reviewScenarios = [
"journey", "initial", "selected_agents", "connect", "advanced", "connecting", "sign_in", "returned", "cancelled", "invalid_url", "rejected", "unreachable", "permissions", "broad", "completed", "reconnect", "draft", "new_tools", "direct_tools", "provider_pending",
"journey", "initial", "selected_agents", "connect", "advanced", "connecting", "sign_in", "returned", "cancelled", "oauth_failed", "invalid_url", "rejected", "unreachable", "permissions", "broad", "completed", "reconnect", "draft", "new_tools", "direct_tools", "provider_pending",
] as const;
export type ReviewScenario = typeof reviewScenarios[number];
@@ -77,8 +77,8 @@ export function initialReviewState(provider: RemoteMcpProviderId, scenario: Revi
if (scenario === "direct_tools") tools = [readAction("GMAIL_FETCH_EMAILS", "Fetch emails", "An individual action from an externally configured direct-tools session.")];
if (scenario === "new_tools") tools = [...tools, newFixtureTool];
const access = ["journey", "initial", "selected_agents"].includes(scenario);
const setupComplete = !access && !["connect", "advanced", "connecting", "sign_in", "cancelled", "invalid_url", "rejected", "unreachable", "draft"].includes(scenario);
const connectCases: Partial<Record<ReviewScenario, ConnectStatus>> = { connect: "idle", advanced: "idle", connecting: "connecting", sign_in: "sign_in", cancelled: "cancelled", invalid_url: "invalid_url", rejected: "rejected", unreachable: "unreachable", reconnect: "idle" };
const setupComplete = !access && !["connect", "advanced", "connecting", "sign_in", "cancelled", "oauth_failed", "invalid_url", "rejected", "unreachable", "draft"].includes(scenario);
const connectCases: Partial<Record<ReviewScenario, ConnectStatus>> = { connect: "idle", advanced: "idle", connecting: "connecting", sign_in: "sign_in", cancelled: "cancelled", oauth_failed: "oauth_failed", invalid_url: "invalid_url", rejected: "rejected", unreachable: "unreachable", reconnect: "idle" };
const isConnect = scenario in connectCases;
const state: RemoteMcpSetupState = {
step: access ? "access" : isConnect ? "connect" : scenario === "completed" ? "management" : scenario === "draft" ? "draft" : "permissions",
@@ -21,6 +21,7 @@ export const Connecting: Story = { args: { scenario: "connecting" } };
export const BrowserSignInPending: Story = { args: { scenario: "sign_in" } };
export const ReturnedFromSignIn: Story = { args: { scenario: "returned" } };
export const SignInCancelled: Story = { args: { scenario: "cancelled" } };
export const AuthorizationFailed: Story = { args: { scenario: "oauth_failed" } };
export const InvalidUrl: Story = { args: { scenario: "invalid_url" } };
export const RejectedCredentials: Story = { args: { scenario: "rejected" } };
export const UnreachableEndpoint: Story = { args: { scenario: "unreachable" } };
@@ -21,6 +21,7 @@ export const Connecting: Story = { args: { scenario: "connecting" } };
export const BrowserSignInPending: Story = { args: { scenario: "sign_in" } };
export const ReturnedFromSignIn: Story = { args: { scenario: "returned" } };
export const SignInCancelled: Story = { args: { scenario: "cancelled" } };
export const AuthorizationFailed: Story = { args: { scenario: "oauth_failed" } };
export const InvalidUrl: Story = { args: { scenario: "invalid_url" } };
export const RejectedCredentials: Story = { args: { scenario: "rejected" } };
export const UnreachableEndpoint: Story = { args: { scenario: "unreachable" } };
@@ -21,6 +21,7 @@ export const Connecting: Story = { args: { scenario: "connecting" } };
export const BrowserSignInPending: Story = { args: { scenario: "sign_in" } };
export const ReturnedFromSignIn: Story = { args: { scenario: "returned" } };
export const SignInCancelled: Story = { args: { scenario: "cancelled" } };
export const AuthorizationFailed: Story = { args: { scenario: "oauth_failed" } };
export const InvalidUrl: Story = { args: { scenario: "invalid_url" } };
export const RejectedCredentials: Story = { args: { scenario: "rejected" } };
export const UnreachableEndpoint: Story = { args: { scenario: "unreachable" } };