diff --git a/doc/connections/CONNECTOR-PLAYBOOK.md b/doc/connections/CONNECTOR-PLAYBOOK.md index bda8100bc78..99f4021340c 100644 --- a/doc/connections/CONNECTOR-PLAYBOOK.md +++ b/doc/connections/CONNECTOR-PLAYBOOK.md @@ -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. diff --git a/ui/src/features/connections/remote-mcp/RemoteMcpConnectionSetup.tsx b/ui/src/features/connections/remote-mcp/RemoteMcpConnectionSetup.tsx index d6e0f1ffda5..4abd08da386 100644 --- a/ui/src/features/connections/remote-mcp/RemoteMcpConnectionSetup.tsx +++ b/ui/src/features/connections/remote-mcp/RemoteMcpConnectionSetup.tsx @@ -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) => {children}; 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
{s.notice &&

{s.notice}

} - {s.step === "access" && { if (grantKind !== "agent") change({ grantKind }); }} + {s.step === "access" && { 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")} />} diff --git a/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.tsx b/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.tsx index 9c34e49a251..02cbc3ff3a6 100644 --- a/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.tsx +++ b/ui/src/features/connections/remote-mcp/RemoteMcpProductionSetup.tsx @@ -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

{installs.isError ? "Could not load saved access. Retry before changing this connection." : "Loading saved access…"}

{installs.isError && }
; - return ; + return ; } diff --git a/ui/src/features/connections/remote-mcp/types.ts b/ui/src/features/connections/remote-mcp/types.ts index 509e63a20f3..5d94314c670 100644 --- a/ui/src/features/connections/remote-mcp/types.ts +++ b/ui/src/features/connections/remote-mcp/types.ts @@ -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; } diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index 3e1c928e962..93e93966cc1 100644 --- a/ui/src/pages/apps/AppsConnect.test.tsx +++ b/ui/src/pages/apps/AppsConnect.test.tsx @@ -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); diff --git a/ui/storybook/fixtures/remoteMcpConnections.ts b/ui/storybook/fixtures/remoteMcpConnections.ts index a21c6ae8b01..e5869e76b3f 100644 --- a/ui/storybook/fixtures/remoteMcpConnections.ts +++ b/ui/storybook/fixtures/remoteMcpConnections.ts @@ -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> = { 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> = { 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", diff --git a/ui/storybook/stories/ArcadeConnection.stories.tsx b/ui/storybook/stories/ArcadeConnection.stories.tsx index c319aeaa91a..77bd60bc7af 100644 --- a/ui/storybook/stories/ArcadeConnection.stories.tsx +++ b/ui/storybook/stories/ArcadeConnection.stories.tsx @@ -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" } }; diff --git a/ui/storybook/stories/ComposioConnection.stories.tsx b/ui/storybook/stories/ComposioConnection.stories.tsx index a47c5a27ac2..e4169d0824d 100644 --- a/ui/storybook/stories/ComposioConnection.stories.tsx +++ b/ui/storybook/stories/ComposioConnection.stories.tsx @@ -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" } }; diff --git a/ui/storybook/stories/ExecutorConnection.stories.tsx b/ui/storybook/stories/ExecutorConnection.stories.tsx index 1e1f98dbe5c..df5dbfe2c16 100644 --- a/ui/storybook/stories/ExecutorConnection.stories.tsx +++ b/ui/storybook/stories/ExecutorConnection.stories.tsx @@ -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" } };