From a1b9eed57d32e78da6f0af851ef9cf305327d4d3 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Mon, 30 Nov 2026 14:20:23 -0600
Subject: [PATCH] fix(mcp): stop masking upstream MCP and OAuth 502 errors as
Paperclip outages (#23295)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Users connect external MCP servers and OAuth apps in Paperclip so
agents can use their tools
> - When a remote MCP server or OAuth authorization server rejects
automatic registration or discovery (for example, returning HTTP 400
`invalid_redirect_uri` during Dynamic Client Registration), Paperclip
returns HTTP 502 with a structured upstream error payload
> - The UI error classifier previously treated every HTTP 502 without a
`CODE_COPY` entry as a Paperclip outage, so it discarded the server
message and showed "Paperclip is temporarily unavailable"
> - This pull request shares a canonical allowlist of upstream
MCP/OAuth/remote HTTP 502 error codes between the server and UI,
preserves upstream error messages with accurate retryability, shows
clear sign-in guidance with Paperclip's copyable callback URL, and
resumes the saved draft connection during manual client recovery
> - The benefit is that users immediately see why a remote MCP server
rejected sign-in and how to fix it (allowlisting Paperclip's callback
URL or entering a client ID) without hitting a false Paperclip outage or
creating duplicate connections
## Linked Issues or Issue Description
**What happened?**
When a user connects a remote MCP server with browser sign-in and the
remote authorization server rejects Dynamic Client Registration (for
example, returning HTTP 400 `invalid_redirect_uri` because it requires a
client allowlist), the Paperclip server returns HTTP 502 with `{ error:
"The authorization server rejected Paperclip's callback URL.", details:
{ code: "oauth_dynamic_client_registration_failed", providerError:
"invalid_redirect_uri", status: 400 } }`. The UI classified that HTTP
502 as a transient connectivity outage and displayed "Paperclip is
temporarily unavailable. Please try again in a moment." instead of the
actual reason.
**Expected behavior**
Paperclip should preserve its server-authored error message for
allowlisted upstream HTTP 502 responses, derive `retryable` accurately
(non-retryable for permanent upstream rejections, retryable for upstream
outages/5xx/rate-limits/timeouts), and avoid triggering the app-wide
outage banner. In the MCP connection flow, Paperclip should explain why
the remote server rejected automatic sign-in setup, expand the Browser
sign-in section with Paperclip's copyable callback URL above Client ID
and Client secret, and resume the saved draft connection instead of
creating duplicate numbered connections when the user retries.
**Steps to reproduce**
1. Open Apps and connect a custom MCP server URL whose OAuth
authorization server rejects Dynamic Client Registration (such as HTTP
400 `invalid_redirect_uri` or another upstream registration/metadata
error).
2. Start browser sign-in.
3. Observe that Paperclip previously showed "Paperclip is temporarily
unavailable. Please try again in a moment." instead of explaining the
callback URL or registration rejection.
**Paperclip version or commit**
Reproduced on `master` at commit `2d764bebc6` (and prior `bc98abda0c`).
**Deployment mode**
Other (applies to both Paperclip Cloud and self-hosted deployments).
## What Changed
- **Shared contracts (`packages/shared`)**:
- Added `packages/shared/src/upstream-failure-codes.ts` (re-exported
from `packages/shared/src/index.ts`) defining the single canonical
allowlist of upstream HTTP 502 error codes
(`UPSTREAM_MCP_OAUTH_FAILURE_CODES`,
`UPSTREAM_REMOTE_HTTP_FAILURE_CODES`,
`UPSTREAM_BAD_GATEWAY_FAILURE_CODES`,
`isUpstreamBadGatewayFailureCode`), transient HTTP status helper
(`TRANSIENT_UPSTREAM_HTTP_STATUSES`, `isTransientUpstreamHttpStatus`),
and shared retryability policy (`isRetryableUpstreamFailure`). Transient
HTTP statuses (408, 425, 429, and 5xx) are checked before the permanent
`oauth_dynamic_client_registration_failed` fallback so rate-limited or
timed-out registration attempts remain retryable. Any unlisted
structured 502 still falls back to the transient outage path.
- Updated `connectToolAppSchema` in
`packages/shared/src/validators/tool-access.ts` so `resumeConnectionId`
works for generic `link` connections as well as gallery apps (still
requiring `galleryKey || link`), enabling the recovery path to resume a
saved generic MCP draft instead of creating a duplicate connection.
- **Server (`server/`)**:
- Updated `server/src/services/mcp-connection-failure.ts` so
`mcpDiscoveryHttpFailure` emits `{ code: "mcp_remote_http_error", status
}` in `HttpError` details.
- Updated `server/src/services/tool-access/catalog/failures.ts` so
`sanitizeHttpFailure` imports `UPSTREAM_MCP_OAUTH_FAILURE_CODES` from
`@paperclipai/shared` and preserves upstream MCP/OAuth failure codes
with HTTP 502 instead of collapsing them to `"paperclip_error"`.
- Updated `server/src/routes/tool-access.ts` so when `svc.startOAuth`
throws a non-manual-client `HttpError` after creating a `draft`
connection, `error.details` includes `connectionId:
result.connectionId`.
- Updated `server/src/services/tool-access.ts` (`connectGalleryApp`) so
resuming a draft via `resumeConnectionId` with a generic `link` enforces
that the draft is not a curated gallery app and that its stored MCP
endpoint matches the requested `link`.
- **UI (`ui/`)**:
- Updated `ui/src/api/errors.ts` so `isStructuredUpstreamBadGateway` and
`isRetryableUpstreamBadGateway` delegate to
`isUpstreamBadGatewayFailureCode` and `isRetryableUpstreamFailure` from
`@paperclipai/shared` (keeping unlisted structured 502s,
`ApiUnavailableError`, and `TRANSIENT_CODES` on the outage banner path,
and returning `retryable: false` for permanent upstream rejections vs
`retryable: true` for upstream 5xx, rate limits, timeouts, or temporary
outages).
- Updated `ui/src/pages/apps/generic-mcp-connect.ts` with
`"oauth_client"` focus, plain-English guidance for DCR (including
temporary rate-limit/timeout/5xx guidance with `focus: "none"` vs
permanent rejection guidance with `focus: "oauth_client"`), metadata,
redirect, token, and remote HTTP failures, plus pure
`genericGuidanceFormPatch` and `resolveGenericDraftResumeId` helpers.
- Updated `ui/src/features/connections/oauthFailureMessages.ts` to cover
`oauth_dynamic_client_registration_failed` (including transient HTTP
429/408/425/5xx responses), `oauth_dcr_response_invalid`, and
`oauth_metadata_failed`, extract `connectionId` in
`readOAuthApiErrorDetails`, and add `oauthStartFailureMessage`.
- Added `ui/src/features/connections/useGenericDraftResume.ts`
(`useGenericDraftResume` + `grantKindFromConnection`) and updated
`ui/src/features/connections/GenericMcpConnectStep.tsx`,
`ui/src/features/connections/ConnectionSetupFlow.tsx`, and
`ui/src/pages/tools/PasteConfigTab.tsx` to deduplicate guidance form
transitions via `applyGenericConnectGuidance`, preserve and resume the
failed generic draft connection ID across retries without creating
duplicates while starting a fresh draft if the URL, company, credential
ownership (`grantKind`), or dedicated agent changes, clear stale drafts
on `404` / `connection_setup_not_incomplete`, display Paperclip's
copyable callback URL (using `useCopyAction`) above Client ID and Client
secret when Browser sign-in expands, and remove the unused `ApiError`
import. No source file crossed the 1,000-line threshold
(`ConnectionSetupFlow.tsx` and `tool-access.ts` were already above 1,000
lines).
- **Tests**:
- Synchronized `tests/runner-e2e/source-sdk-public-inputs.json` for the
`@paperclipai/shared` public source graph.
- Added/updated regression tests in
`packages/shared/src/upstream-failure-codes.test.ts`,
`packages/shared/src/validators/tool-access.test.ts`,
`ui/src/api/errors.test.ts`,
`ui/src/pages/apps/generic-mcp-connect.test.ts`,
`ui/src/features/connections/oauthFailureMessages.test.ts`,
`ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx`,
`ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx`,
`server/src/services/tool-access/catalog/failures.test.ts`,
`server/src/services/__tests__/mcp-connection-failure.test.ts`, and
`server/src/__tests__/generic-mcp-connection.test.ts`.
## Verification
Ran on latest commit `9d088abf91`:
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/shared exec
vitest run src/upstream-failure-codes.test.ts
src/validators/tool-access.test.ts` — passed (2 files, 20 tests).
- `pnpm --filter @paperclipai/ui typecheck` — passed (0 errors).
- `pnpm --filter @paperclipai/ui exec vitest run src/api/errors.test.ts
src/pages/apps/generic-mcp-connect.test.ts
src/features/connections/oauthFailureMessages.test.ts
src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx
src/features/connections/ConnectionSetupFlow.oauth.test.ts` — passed (5
files, 140 tests).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`changed: false`, 582 inputs).
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — passed (13 tests).
Full GitHub CI & review gates on final head `9d088abf91` ([`ci` run
46468259760](https://github.com/paperclipai/paperclip/actions/runs/46468259760)):
- `ci / verify`, `ci / e2e` (all 16 shards), `ci / Typecheck + Release
Registry`, `ci / policy`, `ci / General tests` (20/20), `ci / Runner
support suite` (4/4), `ci / Verify Paperclip` (9/9), `ci / Verify
serialized server suites` (9/9), `ci / Sandbox profile`, `Superagent
Security Scan`, `Socket Security`, `Contributor trust`, `security/snyk`,
`commitperclip PR Review`, and `Greptile Review` (5/5, 0 unresolved
threads) all passed on `9d088abf91`.
Visual states covered via component and flow tests using existing design
tokens (`border-input`, `bg-muted/40`, `text-foreground`,
`text-muted-foreground`): initial generic MCP connect step, expanded
Browser sign-in with copyable Paperclip callback URL (`Copy` / `Copied`
/ `Copy failed`), inline guidance banner for DCR/metadata/credential
errors (including transient rate-limit/timeout/5xx copy), draft resume
on manual client retry, fresh draft creation on access ownership change,
and draft clearing on `404` / `connection_setup_not_incomplete`.
## Risks
- Low risk. Uncoded HTTP 502 responses, unlisted structured 502 codes,
proxy HTML `ApiUnavailableError` responses, and `tenant_app_unavailable`
/ `tenant_app_starting` responses still classify as `"transient"` and
still trigger the app-wide outage banner.
- Security: Untrusted upstream OAuth `error_description`, `error_uri`,
and response bodies remain blocked; only Paperclip-authored messages and
allowlisted RFC error codes drive UI copy. Generic draft resume enforces
route-level configure authorization
(`assertToolConnectionConfigureAccess`), rejects curated gallery drafts,
and requires a matching normalized server endpoint.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Google DeepMind Antigravity (Gemini-based coding agent via ACPX
runtime) with tool use and code execution.
## 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
---
packages/shared/src/index.ts | 1 +
.../shared/src/upstream-failure-codes.test.ts | 86 ++++
packages/shared/src/upstream-failure-codes.ts | 106 +++++
.../shared/src/validators/tool-access.test.ts | 5 +-
packages/shared/src/validators/tool-access.ts | 7 -
.../__tests__/generic-mcp-connection.test.ts | 61 +++
server/src/routes/tool-access.ts | 10 +-
.../__tests__/mcp-connection-failure.test.ts | 1 +
server/src/services/mcp-connection-failure.ts | 5 +-
server/src/services/tool-access.ts | 19 +
.../tool-access/catalog/failures.test.ts | 21 +
.../services/tool-access/catalog/failures.ts | 16 +-
.../runner-e2e/source-sdk-public-inputs.json | 8 +-
ui/src/api/errors.test.ts | 124 +++++-
ui/src/api/errors.ts | 38 +-
.../ConnectionSetupFlow.generic-mcp.test.tsx | 369 ++++++++++++++++++
.../connections/ConnectionSetupFlow.tsx | 117 ++++--
.../GenericMcpConnectStep.machine.test.tsx | 43 +-
.../connections/GenericMcpConnectStep.tsx | 33 +-
.../connections/oauthFailureMessages.test.ts | 105 +++++
.../connections/oauthFailureMessages.ts | 72 +++-
.../connections/useGenericDraftResume.ts | 90 +++++
ui/src/pages/apps/generic-mcp-connect.test.ts | 231 +++++++++++
ui/src/pages/apps/generic-mcp-connect.ts | 207 +++++++++-
ui/src/pages/tools/PasteConfigTab.tsx | 5 +-
25 files changed, 1719 insertions(+), 61 deletions(-)
create mode 100644 packages/shared/src/upstream-failure-codes.test.ts
create mode 100644 packages/shared/src/upstream-failure-codes.ts
create mode 100644 ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx
create mode 100644 ui/src/features/connections/oauthFailureMessages.test.ts
create mode 100644 ui/src/features/connections/useGenericDraftResume.ts
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 3ff15a1891c..38e1663cb2d 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -3171,3 +3171,4 @@ export type { TailscaleConnection, TailscaleDeviceLogin } from "./types/tailscal
export * from "./agent-setup-progress.js";
export { antigravitySwarmAvailable, antigravitySwarmWorkModeAllows, isAntigravityAgent, parseLeadingUserCommand, SWARM_REQUEST_MAX_CHARS, type LeadingUserCommand } from "./leading-user-command.js";
export * from "./cloud-inference.js";
+export * from "./upstream-failure-codes.js";
diff --git a/packages/shared/src/upstream-failure-codes.test.ts b/packages/shared/src/upstream-failure-codes.test.ts
new file mode 100644
index 00000000000..b4a12899b8d
--- /dev/null
+++ b/packages/shared/src/upstream-failure-codes.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from "vitest";
+import {
+ isRetryableUpstreamFailure,
+ isTransientUpstreamHttpStatus,
+ isUpstreamBadGatewayFailureCode,
+ NON_RETRYABLE_UPSTREAM_BAD_GATEWAY_CODES,
+ UPSTREAM_MCP_OAUTH_FAILURE_CODES,
+ UPSTREAM_REMOTE_HTTP_FAILURE_CODES,
+} from "./upstream-failure-codes.js";
+
+describe("upstream failure codes", () => {
+ it("recognizes allowlisted MCP, OAuth, and remote HTTP 502 codes only", () => {
+ for (const code of [...UPSTREAM_MCP_OAUTH_FAILURE_CODES, ...UPSTREAM_REMOTE_HTTP_FAILURE_CODES]) {
+ expect(isUpstreamBadGatewayFailureCode(code), code).toBe(true);
+ }
+ expect(isUpstreamBadGatewayFailureCode("paperclip_error")).toBe(false);
+ expect(isUpstreamBadGatewayFailureCode("tenant_app_unavailable")).toBe(false);
+ expect(isUpstreamBadGatewayFailureCode("proxy_bad_gateway")).toBe(false);
+ expect(isUpstreamBadGatewayFailureCode(null)).toBe(false);
+ expect(isUpstreamBadGatewayFailureCode(undefined)).toBe(false);
+ });
+
+ it("identifies transient upstream HTTP statuses", () => {
+ for (const status of [408, 425, 429, 500, 502, 503, 504]) {
+ expect(isTransientUpstreamHttpStatus(status), String(status)).toBe(true);
+ }
+ for (const status of [200, 400, 401, 403, 404, 422, null, undefined, Number.NaN]) {
+ expect(isTransientUpstreamHttpStatus(status), String(status)).toBe(false);
+ }
+ });
+
+ it("marks permanent upstream rejections as non-retryable", () => {
+ for (const code of NON_RETRYABLE_UPSTREAM_BAD_GATEWAY_CODES) {
+ expect(isRetryableUpstreamFailure(code), code).toBe(false);
+ }
+ expect(
+ isRetryableUpstreamFailure("oauth_dynamic_client_registration_failed", {
+ providerError: "invalid_redirect_uri",
+ status: 400,
+ }),
+ ).toBe(false);
+ expect(
+ isRetryableUpstreamFailure("oauth_dynamic_client_registration_failed"),
+ ).toBe(false);
+ expect(
+ isRetryableUpstreamFailure("mcp_remote_http_error", { status: 403 }),
+ ).toBe(false);
+ expect(
+ isRetryableUpstreamFailure("oauth_token_exchange_failed", { status: 400 }),
+ ).toBe(false);
+ });
+
+ it("marks upstream 5xx, rate limits, timeouts, and transient provider errors as retryable", () => {
+ expect(
+ isRetryableUpstreamFailure("oauth_dynamic_client_registration_failed", {
+ providerError: "temporarily_unavailable",
+ status: 400,
+ }),
+ ).toBe(true);
+ expect(
+ isRetryableUpstreamFailure("oauth_dynamic_client_registration_failed", {
+ providerError: "server_error",
+ status: 500,
+ }),
+ ).toBe(true);
+ expect(
+ isRetryableUpstreamFailure("oauth_dynamic_client_registration_failed", {
+ status: 503,
+ }),
+ ).toBe(true);
+ for (const status of [408, 425, 429]) {
+ expect(
+ isRetryableUpstreamFailure("oauth_dynamic_client_registration_failed", { status }),
+ `DCR HTTP ${status}`,
+ ).toBe(true);
+ }
+ expect(
+ isRetryableUpstreamFailure("mcp_remote_http_error", { status: 429 }),
+ ).toBe(true);
+ expect(
+ isRetryableUpstreamFailure("mcp_remote_http_error", { status: 502 }),
+ ).toBe(true);
+ expect(isRetryableUpstreamFailure("remote_http_response_timeout")).toBe(true);
+ expect(isRetryableUpstreamFailure("oauth_metadata_failed")).toBe(true);
+ });
+});
diff --git a/packages/shared/src/upstream-failure-codes.ts b/packages/shared/src/upstream-failure-codes.ts
new file mode 100644
index 00000000000..da13407180a
--- /dev/null
+++ b/packages/shared/src/upstream-failure-codes.ts
@@ -0,0 +1,106 @@
+/**
+ * Structured error codes emitted with HTTP 502 when a remote MCP server, OAuth
+ * authorization server, or remote HTTP target fails — rather than Paperclip
+ * itself being unavailable.
+ *
+ * Shared between the server failure sanitizer and the UI error classifier so
+ * both layers agree on which structured 502 responses are upstream failures
+ * versus Paperclip outages, and which of those failures are retryable.
+ */
+export const UPSTREAM_MCP_OAUTH_FAILURE_CODES = [
+ "mcp_remote_http_error",
+ "mcp_catalog_error",
+ "mcp_catalog_invalid",
+ "mcp_catalog_pagination",
+ "mcp_skills_list_invalid",
+ "oauth_dynamic_client_registration_failed",
+ "oauth_dcr_response_invalid",
+ "oauth_metadata_failed",
+ "oauth_redirect_rejected",
+ "oauth_redirect_limit",
+ "oauth_token_exchange_failed",
+ "oauth_access_token_missing",
+] as const;
+
+export type UpstreamMcpOAuthFailureCode =
+ (typeof UPSTREAM_MCP_OAUTH_FAILURE_CODES)[number];
+
+export const UPSTREAM_REMOTE_HTTP_FAILURE_CODES = [
+ "remote_http_dns_failed",
+ "remote_http_connect_failed",
+ "remote_http_response_timeout",
+] as const;
+
+export type UpstreamRemoteHttpFailureCode =
+ (typeof UPSTREAM_REMOTE_HTTP_FAILURE_CODES)[number];
+
+export const UPSTREAM_BAD_GATEWAY_FAILURE_CODES: ReadonlySet = new Set([
+ ...UPSTREAM_MCP_OAUTH_FAILURE_CODES,
+ ...UPSTREAM_REMOTE_HTTP_FAILURE_CODES,
+]);
+
+export const NON_RETRYABLE_UPSTREAM_BAD_GATEWAY_CODES: ReadonlySet = new Set([
+ "oauth_dcr_response_invalid",
+ "oauth_redirect_rejected",
+ "oauth_redirect_limit",
+ "mcp_catalog_invalid",
+ "mcp_catalog_pagination",
+ "mcp_skills_list_invalid",
+]);
+
+export const RETRYABLE_OAUTH_PROVIDER_ERRORS: ReadonlySet = new Set([
+ "server_error",
+ "temporarily_unavailable",
+]);
+
+export const TRANSIENT_UPSTREAM_HTTP_STATUSES: ReadonlySet = new Set([408, 425, 429]);
+
+export interface UpstreamFailureRetryContext {
+ providerError?: string | null;
+ status?: number | null;
+}
+
+export function isUpstreamBadGatewayFailureCode(
+ code: string | null | undefined,
+): boolean {
+ return typeof code === "string" && UPSTREAM_BAD_GATEWAY_FAILURE_CODES.has(code);
+}
+
+export function isTransientUpstreamHttpStatus(
+ status: number | null | undefined,
+): boolean {
+ return (
+ typeof status === "number"
+ && Number.isFinite(status)
+ && (status >= 500 || TRANSIENT_UPSTREAM_HTTP_STATUSES.has(status))
+ );
+}
+
+/**
+ * Decide whether a structured upstream HTTP 502 failure is likely transient (so
+ * retrying the same request later can succeed) versus a configuration, policy,
+ * or protocol rejection that requires changing inputs or provider settings.
+ */
+export function isRetryableUpstreamFailure(
+ codeOrCodes: string | readonly string[],
+ context?: UpstreamFailureRetryContext,
+): boolean {
+ const codes = (Array.isArray(codeOrCodes) ? codeOrCodes : [codeOrCodes])
+ .filter((code) => isUpstreamBadGatewayFailureCode(code));
+ if (codes.some((code) => NON_RETRYABLE_UPSTREAM_BAD_GATEWAY_CODES.has(code))) {
+ return false;
+ }
+ const providerError = typeof context?.providerError === "string"
+ ? context.providerError.trim() || null
+ : null;
+ const upstreamStatus = typeof context?.status === "number" && Number.isFinite(context.status)
+ ? context.status
+ : null;
+ if (providerError && RETRYABLE_OAUTH_PROVIDER_ERRORS.has(providerError)) return true;
+ if (isTransientUpstreamHttpStatus(upstreamStatus)) return true;
+ if (codes.includes("oauth_dynamic_client_registration_failed")) return false;
+ if (upstreamStatus !== null && upstreamStatus >= 400 && upstreamStatus < 500) {
+ return false;
+ }
+ return true;
+}
diff --git a/packages/shared/src/validators/tool-access.test.ts b/packages/shared/src/validators/tool-access.test.ts
index b5838320115..ed01e972998 100644
--- a/packages/shared/src/validators/tool-access.test.ts
+++ b/packages/shared/src/validators/tool-access.test.ts
@@ -167,7 +167,7 @@ describe("tool access validators", () => {
}).success).toBe(true);
});
- it("allows only curated app setup to resume an exact draft", () => {
+ it("allows curated and generic link setup to resume an exact draft", () => {
const resumeConnectionId = "11111111-1111-4111-8111-111111111111";
expect(connectToolAppSchema.safeParse({
galleryKey: "notion",
@@ -176,6 +176,9 @@ describe("tool access validators", () => {
expect(connectToolAppSchema.safeParse({
link: "https://mcp.example.test/mcp",
resumeConnectionId,
+ }).success).toBe(true);
+ expect(connectToolAppSchema.safeParse({
+ resumeConnectionId,
}).success).toBe(false);
});
diff --git a/packages/shared/src/validators/tool-access.ts b/packages/shared/src/validators/tool-access.ts
index 23d0b8959ef..f7ed5d9b279 100644
--- a/packages/shared/src/validators/tool-access.ts
+++ b/packages/shared/src/validators/tool-access.ts
@@ -523,13 +523,6 @@ export const connectToolAppSchema = z.object({
if (value.resumeConnectionId && value.reconnectConnectionId) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["reconnectConnectionId"], message: "Choose resume or reconnect, not both" });
}
- if (value.resumeConnectionId && !value.galleryKey) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["resumeConnectionId"],
- message: "Only gallery app setup can resume a draft connection",
- });
- }
const source = value.credentialSource ?? "paperclip_vault";
if (source === "vercel_connect") {
if (!value.vercelConnect) {
diff --git a/server/src/__tests__/generic-mcp-connection.test.ts b/server/src/__tests__/generic-mcp-connection.test.ts
index 79f784e7b32..122f182590c 100644
--- a/server/src/__tests__/generic-mcp-connection.test.ts
+++ b/server/src/__tests__/generic-mcp-connection.test.ts
@@ -2446,6 +2446,67 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
await expect(db.select().from(toolConnections)).resolves.toHaveLength(1);
});
+ it("returns the draft connectionId when DCR rejects the callback URL so manual client retry resumes without duplicating", async () => {
+ installMcpOAuthFixture({
+ auth: "oauth",
+ registrationFailure: {
+ status: 400,
+ body: { error: "invalid_redirect_uri", error_description: "Redirect URI not allowed" },
+ },
+ });
+ const company = await createCompany(db);
+ const app = createRouteApp(db);
+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", PUBLIC_BASE_URL);
+
+ const failed = await request(app)
+ .post(`/api/companies/${company.id}/tools/apps/connect`)
+ .send({ link: MCP_URL, name: "Fixture DCR rejected" })
+ .expect(502);
+
+ const draftConnectionId = failed.body?.details?.connectionId;
+ expect(draftConnectionId).toEqual(expect.any(String));
+ expect(failed.body).toMatchObject({
+ code: "oauth_dynamic_client_registration_failed",
+ details: {
+ code: "oauth_dynamic_client_registration_failed",
+ providerError: "invalid_redirect_uri",
+ status: 400,
+ connectionId: draftConnectionId,
+ },
+ });
+ await expect(db.select().from(toolConnections)).resolves.toHaveLength(1);
+
+ await request(app)
+ .post(`/api/companies/${company.id}/tools/apps/connect`)
+ .send({
+ link: "https://other.example.test/mcp",
+ name: "Fixture DCR rejected",
+ authMode: "oauth",
+ resumeConnectionId: draftConnectionId,
+ oauthClient: { clientId: "operator-client" },
+ })
+ .expect(400);
+
+ const resumed = await request(app)
+ .post(`/api/companies/${company.id}/tools/apps/connect`)
+ .send({
+ link: MCP_URL,
+ name: "Fixture DCR rejected",
+ authMode: "oauth",
+ resumeConnectionId: draftConnectionId,
+ oauthClient: { clientId: "operator-client", clientSecret: "operator-secret" },
+ })
+ .expect(201);
+
+ expect(resumed.body.connectionId).toBe(draftConnectionId);
+ expect(resumed.body.auth).toMatchObject({
+ kind: "oauth",
+ registrationSource: "manual",
+ startUrl: expect.any(String),
+ });
+ await expect(db.select().from(toolConnections)).resolves.toHaveLength(1);
+ });
+
it("uses preregistered client credentials without registering anything", async () => {
const fixture = installMcpOAuthFixture({ auth: "oauth", dcr: false });
const company = await createCompany(db);
diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts
index 494039bdca5..806a50829f8 100644
--- a/server/src/routes/tool-access.ts
+++ b/server/src/routes/tool-access.ts
@@ -1083,7 +1083,15 @@ function connectorEnrollmentPrincipal(req: Request): string {
// the wizard can ask for it rather than losing the draft.
const code = error instanceof HttpError ? String((error.details as { code?: unknown })?.code ?? "") : "";
if (code !== "oauth_manual_client_required" && code !== "oauth_manual_client_rebinding_required"
- && code !== "oauth_instance_client_endpoint_mismatch") throw error;
+ && code !== "oauth_instance_client_endpoint_mismatch") {
+ if (error instanceof HttpError && result.connection.status === "draft") {
+ const details = error.details && typeof error.details === "object" && !Array.isArray(error.details)
+ ? (error.details as Record)
+ : {};
+ error.details = { ...details, connectionId: result.connectionId };
+ }
+ throw error;
+ }
const reason = (error as HttpError).details as { reason?: unknown } | undefined;
result.auth.startUrl = null;
result.auth.manualClientRequired = true;
diff --git a/server/src/services/__tests__/mcp-connection-failure.test.ts b/server/src/services/__tests__/mcp-connection-failure.test.ts
index f6ff037a09b..7c7c147876d 100644
--- a/server/src/services/__tests__/mcp-connection-failure.test.ts
+++ b/server/src/services/__tests__/mcp-connection-failure.test.ts
@@ -54,6 +54,7 @@ describe("MCP outbound failure provenance", () => {
[405, "endpoint_not_found"], [429, "rate_limited"], [503, "remote_unavailable"],
])("classifies a remote HTTP %i response as %s across health-check wrapping", (status, reason) => {
const original = mcpDiscoveryHttpFailure(new Response(null, { status }), `Remote app returned HTTP ${status}`);
+ expect(original.details).toEqual({ code: "mcp_remote_http_error", status });
expect(mcpConnectionFailureReason(original)).toBe(reason);
const wrapped = retainMcpConnectionFailure(original, new HttpError(502, original.message));
expect(isExpectedMcpConnectionFailure(wrapped)).toBe(true);
diff --git a/server/src/services/mcp-connection-failure.ts b/server/src/services/mcp-connection-failure.ts
index b76265be31d..42c0d49790e 100644
--- a/server/src/services/mcp-connection-failure.ts
+++ b/server/src/services/mcp-connection-failure.ts
@@ -29,7 +29,10 @@ export async function withMcpConnectionFailure(request: () => Promise): Pr
/** Preserve the existing HTTP failure; classify only the actual remote status. */
export function mcpDiscoveryHttpFailure(response: Response, message: string): HttpError {
- return markMcpHttpResponseFailure(response, new HttpError(502, message, { status: response.status }));
+ return markMcpHttpResponseFailure(
+ response,
+ new HttpError(502, message, { code: "mcp_remote_http_error", status: response.status }),
+ );
}
/** Only an actual MCP response can attach this evidence to a protocol wrapper. */
diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts
index 736478c43c0..e387e5e2059 100644
--- a/server/src/services/tool-access.ts
+++ b/server/src/services/tool-access.ts
@@ -1912,6 +1912,25 @@ export function toolAccessService(
"The selected provider does not match this incomplete connection",
);
}
+ } else if (requestedResumeConnection && !galleryEntry && input.resumeConnectionId) {
+ const storedSource =
+ asRecord(requestedResumeConnection.config).sourceTemplateKey ??
+ asRecord(requestedResumeConnection.transportConfig).sourceTemplateKey ??
+ asRecord(existingApplication?.metadata).sourceTemplateKey ??
+ asRecord(existingApplication?.metadata).galleryKey ??
+ asRecord(existingApplication?.metadata).source;
+ if (typeof storedSource === "string" && getConnectableAppDefinition(storedSource)) {
+ throw badRequest(
+ "The selected provider does not match this incomplete connection",
+ );
+ }
+ const storedEndpoint = linkEndpoint(asRecord(requestedResumeConnection.config).url);
+ const requestedEndpoint = linkEndpoint(input.link);
+ if (storedEndpoint && requestedEndpoint && storedEndpoint !== requestedEndpoint) {
+ throw badRequest(
+ "The server URL does not match this incomplete connection",
+ );
+ }
}
// Reconnect is not a second identity decision. Removed connections retain
// their row precisely so the next credential can be attached to the same
diff --git a/server/src/services/tool-access/catalog/failures.test.ts b/server/src/services/tool-access/catalog/failures.test.ts
index c5ab32a2126..f88dc7024dc 100644
--- a/server/src/services/tool-access/catalog/failures.test.ts
+++ b/server/src/services/tool-access/catalog/failures.test.ts
@@ -20,4 +20,25 @@ describe("healthFailureHttpStatus", () => {
expect(failure).toMatchObject({ status: "degraded", code: "aws_unavailable" });
expect(healthFailureHttpStatus(failure)).toBe(502);
});
+
+ it("preserves upstream MCP and OAuth failure codes with 502 status", () => {
+ for (const code of [
+ "mcp_remote_http_error",
+ "mcp_catalog_error",
+ "mcp_catalog_invalid",
+ "mcp_catalog_pagination",
+ "mcp_skills_list_invalid",
+ "oauth_dynamic_client_registration_failed",
+ "oauth_dcr_response_invalid",
+ "oauth_metadata_failed",
+ "oauth_redirect_rejected",
+ "oauth_redirect_limit",
+ "oauth_token_exchange_failed",
+ "oauth_access_token_missing",
+ ]) {
+ const failure = sanitizeHttpFailure(new HttpError(502, "Upstream failure", { code }));
+ expect(failure).toEqual({ status: "error", message: "Upstream failure", code });
+ expect(healthFailureHttpStatus(failure)).toBe(502);
+ }
+ });
});
diff --git a/server/src/services/tool-access/catalog/failures.ts b/server/src/services/tool-access/catalog/failures.ts
index 6c1831ac33c..725150951ea 100644
--- a/server/src/services/tool-access/catalog/failures.ts
+++ b/server/src/services/tool-access/catalog/failures.ts
@@ -1,8 +1,15 @@
-import type { ToolConnectionHealthStatus } from "@paperclipai/shared";
+import {
+ UPSTREAM_MCP_OAUTH_FAILURE_CODES,
+ type ToolConnectionHealthStatus,
+} from "@paperclipai/shared";
import { HttpError, unprocessable } from "../../../errors.js";
import { mcpConnectionFailureReason, retainMcpConnectionFailure } from "../../mcp-connection-failure.js";
import type { ActorInfo } from "../types.js";
+const PRESERVED_UPSTREAM_FAILURE_CODES: ReadonlySet = new Set(
+ UPSTREAM_MCP_OAUTH_FAILURE_CODES,
+);
+
function asRecord(value: unknown): Record {
if (value && typeof value === "object" && !Array.isArray(value))
return value as Record;
@@ -141,6 +148,13 @@ export function sanitizeHttpFailure(error: unknown): {
code,
};
}
+ if (typeof code === "string" && PRESERVED_UPSTREAM_FAILURE_CODES.has(code)) {
+ return {
+ status: "error",
+ message: error.message,
+ code,
+ };
+ }
if (
code === "binding_missing" ||
code === "secret_deleted" ||
diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json
index ad1efd30ed0..d042caa8eba 100644
--- a/tests/runner-e2e/source-sdk-public-inputs.json
+++ b/tests/runner-e2e/source-sdk-public-inputs.json
@@ -279,7 +279,7 @@
"packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d",
"packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca",
"packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699",
- "packages/shared/src/index.ts": "3ff15a1891c5d35043a58f3b2af4dece970fc8e6",
+ "packages/shared/src/index.ts": "38e1663cb2d5129f47206c27381c9053acd53a26",
"packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca",
"packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075",
"packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9",
@@ -474,6 +474,8 @@
"packages/shared/src/types/workspace-readiness.ts": "c979f99c3dccb684028f8a6ab07660a018a4a3ea",
"packages/shared/src/types/workspace-runtime.ts": "00ab237577d3ea3a1fa946ce6ab6ef8b389b1739",
"packages/shared/src/types/workspace-source-verification.ts": "647f5c8817590629439813df5dc63750b316206d",
+ "packages/shared/src/upstream-failure-codes.test.ts": "b4a12899b8daa13b4a015945f21ead45a1f36a2a",
+ "packages/shared/src/upstream-failure-codes.ts": "da13407180aa18d5bb20c8dfc1d3b48538bd71d0",
"packages/shared/src/validators/access.test.ts": "0df0e096658a31c4f21462a992e38cf8bd7082b1",
"packages/shared/src/validators/access.ts": "efd12471a885dcdcae575dc73445f8bbbd06b889",
"packages/shared/src/validators/adapter-auth-session.ts": "14cffbd7281265bf3f059bcf1b97739ebe0e1f81",
@@ -554,8 +556,8 @@
"packages/shared/src/validators/task-workspace.ts": "b6b5813c6f57868f522d233e6d50ded19510180b",
"packages/shared/src/validators/teams-catalog.ts": "7bddf40c091a52aaa54e79de784bea5ae496f9aa",
"packages/shared/src/validators/text.ts": "74c430fe17cdcfd4b56dd08a4c57cd3d567670a8",
- "packages/shared/src/validators/tool-access.test.ts": "b5838320115946a936b256919a5bd3a2294c6070",
- "packages/shared/src/validators/tool-access.ts": "23d0b8959efdabd0fdb15e4309ea56ebdc321056",
+ "packages/shared/src/validators/tool-access.test.ts": "ed01e972998730e91c97b5086badf7131bd0264e",
+ "packages/shared/src/validators/tool-access.ts": "f7ed5d9b27910aca23789f2e111df4a3429ff627",
"packages/shared/src/validators/trust-policy.test.ts": "1fc4818984eb0e14f034d56ad147600224496d4e",
"packages/shared/src/validators/trust-policy.ts": "f16b002db940b06bd882d51df8b5712c576e1d7b",
"packages/shared/src/validators/voice-sessions.ts": "018a71f9ac544645041ac3cc9919e59c95fbe998",
diff --git a/ui/src/api/errors.test.ts b/ui/src/api/errors.test.ts
index 26f4238b8dd..9e0167a5873 100644
--- a/ui/src/api/errors.test.ts
+++ b/ui/src/api/errors.test.ts
@@ -8,6 +8,7 @@ import {
errorCodes,
isConnectivityError,
isRawErrorCode,
+ isTransientError,
parseRetryAfter,
type ErrorKind,
} from "./errors";
@@ -26,6 +27,7 @@ describe("classifyError", () => {
["425", apiError(425), "transient"],
["429", apiError(429, { error: "Too many requests" }), "transient"],
["502", apiError(502), "transient"],
+ ["502 without a structured code", apiError(502, { error: "Bad gateway" }), "transient"],
["503", apiError(503, { error: "Service unavailable" }), "transient"],
["504", apiError(504), "transient"],
["401", apiError(401, { error: "Unauthorized" }), "auth"],
@@ -46,10 +48,11 @@ describe("classifyError", () => {
expect(classifyError(error)).toBe(kind);
});
- it.each([200, 400, 403, 404, 409, 500])(
+ it.each([200, 400, 403, 404, 409, 500, 502])(
"treats the gateway's tenant_app_unavailable as transient in any status (%s)",
(status) => {
expect(classifyError(apiError(status, { error: "tenant_app_unavailable" }))).toBe("transient");
+ expect(classifyError(apiError(status, { code: "tenant_app_unavailable" }))).toBe("transient");
expect(classifyError(apiError(status, { error: "tenant_app_starting" }))).toBe("transient");
},
);
@@ -63,6 +66,44 @@ describe("classifyError", () => {
expect(classifyError(error)).toBe("transient");
});
+ it("does not classify a structured upstream MCP/OAuth 502 from Paperclip as a Paperclip outage", () => {
+ const dcrError = apiError(502, {
+ error: "The authorization server rejected Paperclip's callback URL.",
+ code: "oauth_dynamic_client_registration_failed",
+ details: {
+ code: "oauth_dynamic_client_registration_failed",
+ providerError: "invalid_redirect_uri",
+ status: 400,
+ },
+ });
+ const detailsOnlyError = apiError(502, {
+ error: "Remote app returned HTTP 500",
+ details: { code: "mcp_remote_http_error", status: 500 },
+ });
+
+ expect(classifyError(dcrError)).toBe("unknown");
+ expect(isTransientError(dcrError)).toBe(false);
+ expect(classifyError(detailsOnlyError)).toBe("unknown");
+ expect(isTransientError(detailsOnlyError)).toBe(false);
+ });
+
+ it("keeps non-upstream structured 502 codes on the transient outage path", () => {
+ const nonUpstream502 = apiError(502, {
+ error: "Cloud stack signing key is not configured",
+ code: "cloud_inference_auth_unconfigured",
+ details: { code: "cloud_inference_auth_unconfigured" },
+ });
+ const unknownCode502 = apiError(502, {
+ error: "Gateway backend failed",
+ details: { code: "internal_gateway_fault" },
+ });
+
+ expect(classifyError(nonUpstream502)).toBe("transient");
+ expect(isConnectivityError(nonUpstream502)).toBe(true);
+ expect(classifyError(unknownCode502)).toBe("transient");
+ expect(isConnectivityError(unknownCode502)).toBe(true);
+ });
+
it("classifies structurally, without the ApiError class", () => {
expect(classifyError({ status: 503, body: null })).toBe("transient");
expect(classifyError({ name: "AuthApiError", status: 401, code: null })).toBe("auth");
@@ -73,8 +114,21 @@ describe("isConnectivityError", () => {
it("is true for server-wide outages only", () => {
expect(isConnectivityError(new TypeError("Failed to fetch"))).toBe(true);
expect(isConnectivityError(new ApiUnavailableError(200))).toBe(true);
+ expect(isConnectivityError(new ApiUnavailableError(502))).toBe(true);
+ expect(isConnectivityError(apiError(502))).toBe(true);
+ expect(isConnectivityError(apiError(502, { error: "Bad gateway" }))).toBe(true);
+ expect(isConnectivityError(apiError(502, { code: "tenant_app_unavailable" }))).toBe(true);
+ expect(isConnectivityError(apiError(502, { code: "internal_gateway_fault" }))).toBe(true);
expect(isConnectivityError(apiError(503))).toBe(true);
expect(isConnectivityError(apiError(404, { error: "tenant_app_unavailable" }))).toBe(true);
+ expect(isConnectivityError(apiError(502, {
+ error: "The authorization server rejected Paperclip's callback URL.",
+ details: { code: "oauth_dynamic_client_registration_failed", providerError: "invalid_redirect_uri" },
+ }))).toBe(false);
+ expect(isConnectivityError(apiError(502, {
+ error: "Remote MCP server returned HTTP 500",
+ code: "mcp_catalog_error",
+ }))).toBe(false);
// Transient, but one route: left to query retry, not the app banner.
expect(isConnectivityError(apiError(429))).toBe(false);
expect(isConnectivityError(apiError(503, { code: "WORKER_UNAVAILABLE", message: "x" }))).toBe(false);
@@ -92,6 +146,7 @@ describe("describeError", () => {
apiError(200, { error: "tenant_app_starting" }),
apiError(404, { error: "issue_not_found" }),
apiError(500, { error: "internal_error" }),
+ apiError(502, { error: "oauth_dynamic_client_registration_failed", details: { code: "oauth_dynamic_client_registration_failed" } }),
apiError(503, { code: "WORKER_UNAVAILABLE", message: "WORKER_UNAVAILABLE" }),
new ApiError("tenant_app_unavailable", 503, { error: "tenant_app_unavailable" }),
];
@@ -114,6 +169,73 @@ describe("describeError", () => {
});
});
+ it("preserves Paperclip's message for structured upstream 502 errors and derives retryability accurately", () => {
+ const rejectedDcr = apiError(502, {
+ error: "The authorization server rejected Paperclip's callback URL.",
+ details: {
+ code: "oauth_dynamic_client_registration_failed",
+ providerError: "invalid_redirect_uri",
+ status: 400,
+ },
+ });
+ expect(describeError(rejectedDcr, { action: "connect this server" })).toEqual({
+ title: "Couldn't connect this server",
+ body: "The authorization server rejected Paperclip's callback URL.",
+ retryable: false,
+ });
+
+ const providerOutageDcr = apiError(502, {
+ error: "The authorization server failed during dynamic client registration.",
+ details: {
+ code: "oauth_dynamic_client_registration_failed",
+ providerError: "temporarily_unavailable",
+ status: 503,
+ },
+ });
+ expect(describeError(providerOutageDcr, { action: "connect this server" })).toEqual({
+ title: "Couldn't connect this server",
+ body: "The authorization server failed during dynamic client registration.",
+ retryable: true,
+ });
+
+ const rateLimitedDcr = apiError(502, {
+ error: "The authorization server rate-limited dynamic client registration.",
+ details: {
+ code: "oauth_dynamic_client_registration_failed",
+ status: 429,
+ },
+ });
+ expect(describeError(rateLimitedDcr, { action: "connect this server" })).toEqual({
+ title: "Couldn't connect this server",
+ body: "The authorization server rate-limited dynamic client registration.",
+ retryable: true,
+ });
+
+ const upstream5xx = apiError(502, {
+ error: "Remote app returned HTTP 500",
+ details: {
+ code: "mcp_remote_http_error",
+ status: 500,
+ },
+ });
+ expect(describeError(upstream5xx)).toMatchObject({
+ body: "Remote app returned HTTP 500",
+ retryable: true,
+ });
+
+ const upstream404 = apiError(502, {
+ error: "Remote app returned HTTP 404",
+ details: {
+ code: "mcp_remote_http_error",
+ status: 404,
+ },
+ });
+ expect(describeError(upstream404)).toMatchObject({
+ body: "Remote app returned HTTP 404",
+ retryable: false,
+ });
+ });
+
it("keeps a readable server message for client errors", () => {
expect(describeError(apiError(400, { error: "Title is required" }))).toEqual({
title: "Check your input",
diff --git a/ui/src/api/errors.ts b/ui/src/api/errors.ts
index a76be6093a9..a7df3a06123 100644
--- a/ui/src/api/errors.ts
+++ b/ui/src/api/errors.ts
@@ -12,6 +12,10 @@
* by hand-rolled fetches (health, uploads) classify the same way.
*/
+import {
+ isRetryableUpstreamFailure,
+ isUpstreamBadGatewayFailureCode,
+} from "@paperclipai/shared";
import { CancelledError } from "@tanstack/react-query";
export type ErrorKind =
@@ -170,6 +174,34 @@ export function errorCodes(err: unknown): string[] {
return [...new Set(codes.filter((code): code is string => code !== null))];
}
+function structuredApplicationCodes(err: unknown): string[] {
+ const body = record(record(err)?.body);
+ if (!body) return [];
+ const codes = [
+ stringField(body.code),
+ stringField(record(body.details)?.code),
+ ];
+ return [...new Set(codes.filter((code): code is string => code !== null))];
+}
+
+function isStructuredUpstreamBadGateway(err: unknown): boolean {
+ if (isApiUnavailableError(err) || errorStatus(err) !== 502) return false;
+ const codes = structuredApplicationCodes(err);
+ if (!codes.some((code) => isUpstreamBadGatewayFailureCode(code))) return false;
+ return !errorCodes(err).some((code) => TRANSIENT_CODES.has(code));
+}
+
+function isRetryableUpstreamBadGateway(err: unknown): boolean {
+ const details = record(record(record(err)?.body)?.details);
+ const upstreamStatus = typeof details?.status === "number" && Number.isFinite(details.status)
+ ? details.status
+ : null;
+ return isRetryableUpstreamFailure(structuredApplicationCodes(err), {
+ providerError: stringField(details?.providerError),
+ status: upstreamStatus,
+ });
+}
+
/**
* True for a machine code (`tenant_app_unavailable`, `WORKER_UNAVAILABLE`,
* `TIMEOUT`) rather than a sentence a person wrote. Single readable words such
@@ -226,6 +258,7 @@ export function classifyError(err: unknown): ErrorKind {
const status = errorStatus(err);
if (status === null) return "unknown";
+ if (isStructuredUpstreamBadGateway(err)) return "unknown";
if (TRANSIENT_STATUSES.has(status)) return "transient";
if (status === 401) return "auth";
if (status === 403) return "forbidden";
@@ -248,6 +281,7 @@ export function isTransientError(err: unknown): boolean {
export function isConnectivityError(err: unknown): boolean {
if (isApiUnavailableError(err) || isNetworkTypeError(err)) return true;
if (errorCodes(err).some((code) => CONNECTIVITY_CODES.has(code))) return true;
+ if (isStructuredUpstreamBadGateway(err)) return false;
const status = errorStatus(err);
if (status === null || !CONNECTIVITY_STATUSES.has(status)) return false;
// A plugin worker 503 is one route, not the server.
@@ -291,7 +325,9 @@ export function errorRetryAfterMs(err: unknown): number | null {
*/
export function describeError(err: unknown, options: DescribeErrorOptions = {}): ErrorDescription {
const kind = classifyError(err);
- const retryable = kind === "transient" || kind === "unknown";
+ const retryable = isStructuredUpstreamBadGateway(err)
+ ? isRetryableUpstreamBadGateway(err)
+ : (kind === "transient" || kind === "unknown");
const coded = errorCodes(err).map((code) => CODE_COPY[code]).find(Boolean);
const fallback = KIND_COPY[kind];
diff --git a/ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx b/ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx
new file mode 100644
index 00000000000..7535f1799e0
--- /dev/null
+++ b/ui/src/features/connections/ConnectionSetupFlow.generic-mcp.test.tsx
@@ -0,0 +1,369 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { ConnectToolAppResult, ToolConnection } from "@paperclipai/shared";
+import { ConnectionSetupFlow } from "./ConnectionSetupFlow";
+
+const fixture = vi.hoisted(() => ({
+ companyId: "company-1",
+ search: "",
+ params: {} as Record,
+ navigate: vi.fn(),
+ breadcrumbs: vi.fn(),
+ pushToast: vi.fn(),
+ listGallery: vi.fn(),
+ listApplications: vi.fn(),
+ listConnections: vi.fn(),
+ connectApp: vi.fn(),
+ startOAuth: vi.fn(),
+ putConnectionInstalls: vi.fn(),
+ listAgents: vi.fn(),
+}));
+
+vi.mock("@/context/CompanyContext", () => ({
+ useCompany: () => ({
+ selectedCompanyId: fixture.companyId,
+ selectedCompany: { id: fixture.companyId, name: "Acme", issuePrefix: "ACM" },
+ }),
+}));
+vi.mock("@/context/BreadcrumbContext", () => ({
+ useBreadcrumbs: () => ({ setBreadcrumbs: fixture.breadcrumbs }),
+}));
+vi.mock("@/context/ToastContext", () => ({
+ useToast: () => ({ pushToast: fixture.pushToast }),
+}));
+vi.mock("@/hooks/useCloudInstance", () => ({
+ useCloudInstance: () => false,
+}));
+vi.mock("@/hooks/useChatConnectorsEnabled", () => ({
+ useChatConnectorsEnabled: () => ({ enabled: false }),
+ chatProviderVisible: () => true,
+}));
+vi.mock("@/hooks/useMemoryConnectorsEnabled", () => ({
+ useMemoryConnectorsEnabled: () => ({ loaded: true, enabled: false }),
+}));
+vi.mock("@/hooks/useConnectorAvailability", () => ({
+ useConnectorAvailability: () => ({ loaded: true, failed: false, enabled: () => true }),
+}));
+vi.mock("@/lib/router", () => ({
+ Link: ({ to, children, ...props }: { to: string; children: React.ReactNode }) => (
+ {children}
+ ),
+ useNavigate: () => fixture.navigate,
+ useParams: () => fixture.params,
+ useSearchParams: () => [new URLSearchParams(fixture.search), vi.fn()],
+}));
+vi.mock("@/api/tools", () => ({
+ toolsApi: {
+ listGallery: (...args: unknown[]) => fixture.listGallery(...args),
+ listApplications: (...args: unknown[]) => fixture.listApplications(...args),
+ listConnections: (...args: unknown[]) => fixture.listConnections(...args),
+ connectApp: (...args: unknown[]) => fixture.connectApp(...args),
+ startOAuth: (...args: unknown[]) => fixture.startOAuth(...args),
+ putConnectionInstalls: (...args: unknown[]) => fixture.putConnectionInstalls(...args),
+ getConnection: vi.fn(),
+ getCloudConnectorEnrollment: vi.fn(),
+ startCloudConnectorEnrollment: vi.fn(),
+ },
+}));
+vi.mock("@/api/agents", () => ({
+ agentsApi: {
+ list: (...args: unknown[]) => fixture.listAgents(...args),
+ },
+}));
+vi.mock("@/api/connection-intents", () => ({
+ connectionIntentsApi: {
+ setPhase: vi.fn(),
+ setupOptions: vi.fn(),
+ },
+}));
+vi.mock("@/pages/apps/AppLogo", () => ({
+ AppLogo: () => null,
+}));
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+let container: HTMLDivElement;
+let root: Root;
+let queryClient: QueryClient;
+
+const CALLBACK_URL = "https://paperclip.example/api/tools/oauth/callback";
+const DREAMDATA_URL = "https://mcp.dreamdata.io/mcp";
+
+function draftConnection(
+ id: string,
+ credentialPolicy: ToolConnection["credentialPolicy"] = "shared",
+): ToolConnection {
+ return {
+ id,
+ companyId: "company-1",
+ applicationId: `app-${id}`,
+ name: "mcp.dreamdata.io/mcp",
+ status: "draft",
+ enabled: false,
+ authKind: "oauth",
+ transport: "mcp_remote",
+ credentialPolicy,
+ credentialSource: "paperclip_vault",
+ config: { url: DREAMDATA_URL },
+ transportConfig: {},
+ } as unknown as ToolConnection;
+}
+
+function oauthConnectResult(
+ id: string,
+ credentialPolicy: ToolConnection["credentialPolicy"] = "shared",
+ startUrl: string | null = null,
+): ConnectToolAppResult {
+ const connection = draftConnection(id, credentialPolicy);
+ return {
+ connectionId: id,
+ connection,
+ application: { id: `app-${id}`, name: "mcp.dreamdata.io/mcp" },
+ auth: {
+ kind: "oauth",
+ startUrl,
+ manualClientRequired: false,
+ },
+ actions: { readOnly: [], canMakeChanges: [] },
+ } as unknown as ConnectToolAppResult;
+}
+
+function dcrRejectedError(connectionId?: string) {
+ return Object.assign(new Error("The authorization server rejected Paperclip's callback URL."), {
+ status: 502,
+ body: {
+ error: "The authorization server rejected Paperclip's callback URL.",
+ details: {
+ code: "oauth_dynamic_client_registration_failed",
+ providerError: "invalid_redirect_uri",
+ status: 400,
+ ...(connectionId ? { connectionId } : {}),
+ },
+ },
+ });
+}
+
+async function settle() {
+ for (let i = 0; i < 8; i += 1) {
+ await act(async () => {
+ await new Promise((resolve) => window.setTimeout(resolve, 0));
+ });
+ }
+}
+
+async function renderFlow() {
+ await act(async () => {
+ root.render(
+
+
+ ,
+ );
+ });
+ await settle();
+}
+
+function findButton(label: string): HTMLButtonElement {
+ const button = [...container.querySelectorAll("button")].find(
+ (item) => item.textContent?.trim() === label,
+ );
+ if (!button) {
+ throw new Error(`Button "${label}" not found. Available: ${[...container.querySelectorAll("button")].map((b) => b.textContent?.trim()).join(", ")}`);
+ }
+ return button as HTMLButtonElement;
+}
+
+async function setInputValue(input: HTMLInputElement, value: string) {
+ const descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
+ await act(async () => {
+ descriptor?.set?.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+}
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ fixture.companyId = "company-1";
+ fixture.search = `link=${encodeURIComponent(DREAMDATA_URL)}`;
+ fixture.params = {};
+ fixture.listGallery.mockResolvedValue({
+ apps: [],
+ oauthCallbackUrl: CALLBACK_URL,
+ capabilities: { canCreateOrganizationGrant: true, canSetCompanyInstall: true },
+ });
+ fixture.listApplications.mockResolvedValue({ applications: [] });
+ fixture.listConnections.mockResolvedValue({ connections: [] });
+ fixture.listAgents.mockResolvedValue([]);
+ fixture.putConnectionInstalls.mockResolvedValue({});
+ vi.spyOn(window, "open").mockReturnValue({
+ close: vi.fn(),
+ closed: false,
+ location: { href: "" },
+ } as unknown as Window);
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ queryClient.clear();
+ container.remove();
+ vi.restoreAllMocks();
+});
+
+describe("ConnectionSetupFlow — generic MCP OAuth recovery and draft resume", () => {
+ it("reopens entry with callback URL and client fields after DCR rejection and resumes the saved draft on retry", async () => {
+ fixture.connectApp
+ .mockResolvedValueOnce(oauthConnectResult("conn-draft-1", "shared", null))
+ .mockResolvedValueOnce(oauthConnectResult("conn-draft-1", "shared", "https://authenticate.dreamdata.io/authorize"));
+ fixture.startOAuth.mockRejectedValueOnce(dcrRejectedError("conn-draft-1"));
+
+ await renderFlow();
+
+ await act(async () => {
+ findButton("Check link").click();
+ });
+ await settle();
+
+ expect(fixture.startOAuth).toHaveBeenCalledTimes(1);
+ expect(container.textContent).toContain("This server didn't allow Paperclip's callback URL");
+ expect(container.textContent).not.toContain("Paperclip is temporarily unavailable");
+ expect(container.textContent).toContain(CALLBACK_URL);
+
+ const clientIdInput = container.querySelector("#generic-mcp-client-id");
+ expect(clientIdInput, "expected manual OAuth client ID input to be visible").not.toBeNull();
+
+ await setInputValue(clientIdInput!, "dreamdata-client-1");
+ await act(async () => {
+ findButton("Check link").click();
+ });
+ await settle();
+
+ expect(fixture.connectApp).toHaveBeenCalledTimes(2);
+ expect(fixture.connectApp.mock.calls[1]).toEqual([
+ "company-1",
+ expect.objectContaining({
+ link: DREAMDATA_URL,
+ authMode: "oauth",
+ resumeConnectionId: "conn-draft-1",
+ oauthClient: { clientId: "dreamdata-client-1" },
+ }),
+ ]);
+ });
+
+ it("starts a fresh draft instead of resuming when the user changes credential ownership before retrying", async () => {
+ fixture.connectApp
+ .mockResolvedValueOnce(oauthConnectResult("conn-draft-org", "shared", null))
+ .mockResolvedValueOnce(oauthConnectResult("conn-draft-personal", "per_user", "https://authenticate.dreamdata.io/authorize"));
+ fixture.startOAuth.mockRejectedValueOnce(dcrRejectedError("conn-draft-org"));
+
+ await renderFlow();
+
+ await act(async () => {
+ findButton("Check link").click();
+ });
+ await settle();
+
+ expect(container.textContent).toContain("This server didn't allow Paperclip's callback URL");
+
+ // Expand access defaults and switch from "Any human in the organization" (organization) to "Just me" (user).
+ await act(async () => {
+ findButton("Change").click();
+ });
+ await settle();
+
+ const justMeOption = [...container.querySelectorAll('[role="radio"]')].find(
+ (item) => item.textContent?.includes("Just me"),
+ ) as HTMLElement | undefined;
+ expect(justMeOption, "expected personal access radio option").toBeDefined();
+ await act(async () => {
+ justMeOption!.click();
+ });
+ await settle();
+
+ const clientIdInput = container.querySelector("#generic-mcp-client-id")!;
+ await setInputValue(clientIdInput, "dreamdata-personal-client");
+ await act(async () => {
+ findButton("Check link").click();
+ });
+ await settle();
+
+ expect(fixture.connectApp).toHaveBeenCalledTimes(2);
+ const retryPayload = fixture.connectApp.mock.calls[1]?.[1] as Record;
+ expect(retryPayload.resumeConnectionId).toBeUndefined();
+ expect(retryPayload.grantKind).toBe("user");
+ expect(retryPayload.oauthClient).toEqual({ clientId: "dreamdata-personal-client" });
+ });
+
+ it("clears the saved draft after 404 or connection_setup_not_incomplete so the next retry starts fresh", async () => {
+ const staleNotIncompleteError = Object.assign(
+ new Error("Connection setup is no longer incomplete."),
+ {
+ status: 409,
+ body: {
+ error: "Connection setup is no longer incomplete.",
+ details: { code: "connection_setup_not_incomplete" },
+ },
+ },
+ );
+ const missingDraftError = Object.assign(new Error("Connection not found."), {
+ status: 404,
+ body: { error: "Connection not found." },
+ });
+
+ fixture.connectApp
+ .mockRejectedValueOnce(dcrRejectedError("conn-draft-stale-1"))
+ .mockRejectedValueOnce(staleNotIncompleteError)
+ .mockRejectedValueOnce(dcrRejectedError("conn-draft-stale-2"))
+ .mockRejectedValueOnce(missingDraftError)
+ .mockResolvedValueOnce(oauthConnectResult("conn-draft-fresh", "shared", "https://authenticate.dreamdata.io/authorize"));
+
+ await renderFlow();
+
+ // 1. Initial attempt fails DCR and records conn-draft-stale-1.
+ await act(async () => {
+ findButton("Check link").click();
+ });
+ await settle();
+
+ // 2. Retry sends resumeConnectionId: conn-draft-stale-1, receives connection_setup_not_incomplete, and clears it.
+ await act(async () => {
+ findButton("Check link").click();
+ });
+ await settle();
+ expect(fixture.connectApp.mock.calls[1]?.[1]).toEqual(
+ expect.objectContaining({ resumeConnectionId: "conn-draft-stale-1" }),
+ );
+
+ // 3. Next attempt starts fresh (no resumeConnectionId) and records conn-draft-stale-2.
+ await act(async () => {
+ findButton("Check link").click();
+ });
+ await settle();
+ expect((fixture.connectApp.mock.calls[2]?.[1] as Record).resumeConnectionId).toBeUndefined();
+
+ // 4. Retry sends resumeConnectionId: conn-draft-stale-2, receives 404, and clears it.
+ await act(async () => {
+ findButton("Check link").click();
+ });
+ await settle();
+ expect(fixture.connectApp.mock.calls[3]?.[1]).toEqual(
+ expect.objectContaining({ resumeConnectionId: "conn-draft-stale-2" }),
+ );
+
+ // 5. Final retry omits resumeConnectionId and succeeds with a fresh draft.
+ await act(async () => {
+ findButton("Check link").click();
+ });
+ await settle();
+ expect((fixture.connectApp.mock.calls[4]?.[1] as Record).resumeConnectionId).toBeUndefined();
+ });
+});
diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx
index 8167c13f048..87f9f1b2316 100644
--- a/ui/src/features/connections/ConnectionSetupFlow.tsx
+++ b/ui/src/features/connections/ConnectionSetupFlow.tsx
@@ -5,8 +5,10 @@ import {
allowlistedOAuthProviderError,
oauthCallbackErrorMessage,
oauthFailureMessage,
+ oauthStartFailureMessage,
readConnectionIntentOAuthFailureCode,
readConnectionIntentOAuthProviderError,
+ readOAuthApiErrorDetails,
} from "./oauthFailureMessages";
export {
oauthCallbackErrorMessage,
@@ -87,13 +89,12 @@ import { useToast } from "@/context/ToastContext";
import { useChatConnectorsEnabled, chatProviderVisible } from "@/hooks/useChatConnectorsEnabled";
import { queryKeys } from "@/lib/queryKeys";
import { RadioCardGroup } from "@/components/ui/radio-card";
-import { ApiError } from "@/api/client";
import { toolsApi } from "@/api/tools";
import { agentsApi } from "@/api/agents";
import { appCopyFor, credentialFieldLabel } from "@/lib/app-gallery-copy";
import { JsonSchemaForm, validateJsonSchemaForm, type JsonSchemaNode } from "@/components/JsonSchemaForm";
import { AgentMultiSelect, type AgentMultiSelectOption } from "@/components/AgentMultiSelect";
-import { describeError } from "@/api/errors";
+import { describeError, errorStatus } from "@/api/errors";
import { InlineBanner } from "@/components/InlineBanner";
import { useQueryView } from "@/components/QueryView";
import { Button } from "@/components/ui/button";
@@ -125,12 +126,17 @@ import {
endpointHost,
genericConnectGuidance,
genericConnectPayload,
+ genericGuidanceFormPatch,
newCustomHeaderRow,
oauthCallbackUrlForBrowser,
type CustomHeaderRow,
type GenericConnectGuidance,
type GenericMcpAuthMode,
} from "@/pages/apps/generic-mcp-connect";
+import {
+ grantKindFromConnection,
+ useGenericDraftResume,
+} from "./useGenericDraftResume";
import { autoExtendNotice, INSTALL_ALL_WARNING, installInfoNotice, installPayload } from "@/lib/tool-installs";
type Step = "gallery" | "key" | "success";
@@ -822,6 +828,7 @@ function StandardConnectionSetupFlow({
// A draft that sign-in already created, to be resumed with an operator's own
// OAuth client when automatic registration was refused.
const customerClientResumeRef = useRef(null);
+ const genericDraftResume = useGenericDraftResume({ reconnectConnectionId });
const hydratedResumeConnectionIdRef = useRef(null);
const [hydratedResumeConnectionId, setHydratedResumeConnectionId] = useState(null);
// Finishing a resumed unauthenticated/API-key draft activates that exact row.
@@ -864,11 +871,12 @@ function StandardConnectionSetupFlow({
setCancellingSignIn(false);
}
firstSignInDraftRef.current = null;
+ genericDraftResume.clear(connectionId);
setConnectResult((current) => current?.connectionId === connectionId ? null : current);
void queryClient.invalidateQueries({ queryKey: queryKeys.tools.connections(selectedCompanyId) });
void queryClient.invalidateQueries({ queryKey: queryKeys.tools.applications(selectedCompanyId) });
return true;
- }, [pushToast, queryClient, selectedCompanyId]);
+ }, [genericDraftResume, pushToast, queryClient, selectedCompanyId]);
useEffect(() => {
if (pendingOAuthLookupRef.current && pendingOAuthLookupRef.current.scope !== oauthLookupScope) {
cancelOAuthLookup();
@@ -1487,6 +1495,15 @@ function StandardConnectionSetupFlow({
: null;
const instructionsValid = !instructionValue || Boolean(instructionValue.text.trim());
+ const applyGenericConnectGuidance = useCallback((guidance: GenericConnectGuidance) => {
+ const patch = genericGuidanceFormPatch(guidance);
+ setLinkGuidance(patch.guidance);
+ setGenericOAuthPending(patch.genericOAuthPending);
+ if (patch.authMode !== undefined) setLinkAuthMode(patch.authMode);
+ if (patch.needsKey !== undefined) setLinkNeedsKey(patch.needsKey);
+ if (patch.advancedOpen !== undefined) setLinkAdvancedOpen(patch.advancedOpen);
+ }, []);
+
const oauthStartMutation = useMutation({
// Retry/reconnect reads identity from the durable connection. Provider is
// not identity: an organization Notion connection must stay organization-
@@ -1517,20 +1534,31 @@ function StandardConnectionSetupFlow({
});
},
onSuccess: (start) => void prepareAndOpenOAuth(start),
- onError: (error) => {
+ onError: (error, connection) => {
oauthPopupRef.current?.close();
oauthPopupRef.current = null;
- const details = error instanceof ApiError && error.body && typeof error.body === "object"
- ? (error.body as { details?: { code?: unknown } }).details
- : null;
- setOAuthPhase("error");
workspaceSelectionRef.current = null;
+ if (!entry && linkUrl) {
+ const { code, providerError, upstreamStatus, connectionId } = readOAuthApiErrorDetails(error);
+ const draftConnectionId = connectionId ?? (connection.status === "draft" ? connection.id : null);
+ genericDraftResume.remember(draftConnectionId, {
+ linkUrl,
+ companyId: selectedCompanyId,
+ grantKind: grantKindFromConnection(connection),
+ subjectAgentId: configuredAgentIdentity(connection) ?? ([...installAgentIds][0] ?? null),
+ });
+ const guidance = genericConnectGuidance(code, describeError(error).body, { providerError, upstreamStatus });
+ if (guidance.focus === "oauth_client") {
+ applyGenericConnectGuidance(guidance);
+ setOAuthPhase("entry");
+ setOAuthError(null);
+ onPhaseChange?.("needs_retry");
+ return;
+ }
+ }
+ setOAuthPhase("error");
onPhaseChange?.("needs_retry");
- setOAuthError(
- details?.code === "invalid_grant"
- ? "Your authorization expired or was revoked. Reconnect to continue."
- : describeError(error).body,
- );
+ setOAuthError(oauthStartFailureMessage(error, describeError(error).body));
},
});
const mutateOAuthStart = oauthStartMutation.mutate;
@@ -1569,6 +1597,7 @@ function StandardConnectionSetupFlow({
};
const effectiveGrantKind = fixedGrantKind ?? grantKind;
+ const effectiveSubjectAgentId = effectiveGrantKind === "agent" ? ([...installAgentIds][0] ?? null) : null;
// A dedicated agent identity is never "all agents": keep the picker on so
// the connect request can name its one agent.
useEffect(() => {
@@ -1577,6 +1606,7 @@ function StandardConnectionSetupFlow({
// A connected result (from the link probe or machine sign-in) goes straight to
// review with every discovered action enabled by default.
function acceptConnectedResult(result: ConnectToolAppResult) {
+ genericDraftResume.clear();
setLinkGuidance(null);
setConnectResult(result);
const defaults: Record = {};
@@ -1661,9 +1691,21 @@ function StandardConnectionSetupFlow({
genericPayload.name ?? defaultGenericMcpName(linkUrl) ?? "Custom app",
effectiveGrantKind,
);
+ const genericResumeId = genericDraftResume.resolve({
+ resumeConnectionId,
+ reconnectConnectionId,
+ linkUrl,
+ companyId: selectedCompanyId,
+ grantKind: effectiveGrantKind,
+ subjectAgentId: effectiveSubjectAgentId,
+ });
result = await toolsApi.connectApp(selectedCompanyId!, {
...genericPayload,
- ...(reconnectConnectionId ? { reconnectConnectionId } : {}),
+ ...(genericResumeId
+ ? { resumeConnectionId: genericResumeId }
+ : reconnectConnectionId
+ ? { reconnectConnectionId }
+ : {}),
// Zapier issues a credential-bearing URL, so its branded setup keeps
// the compact pasted-URL step. It is still a curated app, though: the
// gallery identity must reach the server or Browse can only see a
@@ -1700,13 +1742,21 @@ function StandardConnectionSetupFlow({
if (result.auth.manualClientRequired) {
oauthPopupRef.current?.close();
oauthPopupRef.current = null;
+ if (!entry && linkUrl && result.connection.status === "draft") {
+ genericDraftResume.remember(result.connectionId, {
+ linkUrl,
+ companyId: selectedCompanyId,
+ grantKind: grantKindFromConnection(result.connection),
+ subjectAgentId: configuredAgentIdentity(result.connection) ?? effectiveSubjectAgentId,
+ });
+ }
const guidance = genericConnectGuidance("oauth_manual_client_required", null);
- setLinkGuidance(result.auth.manualClientReason ? { ...guidance, body: result.auth.manualClientReason } : guidance);
- setLinkAuthMode("oauth");
- setLinkAdvancedOpen(true);
- setGenericOAuthPending(false);
+ applyGenericConnectGuidance(
+ result.auth.manualClientReason ? { ...guidance, body: result.auth.manualClientReason } : guidance,
+ );
return;
}
+ genericDraftResume.clear();
setOAuthPhase("starting");
setGenericOAuthPending(!entry);
const startUrl = result.auth.startUrl?.trim();
@@ -1726,34 +1776,30 @@ function StandardConnectionSetupFlow({
oauthPopupRef.current?.close();
oauthPopupRef.current = null;
if (awsRoleSetup.acceptError(error)) return;
- const details = error instanceof ApiError && error.body && typeof error.body === "object"
- ? (error.body as { details?: { code?: unknown } }).details
- : null;
if (entry?.slug === "google-workspace") workspaceSelectionRef.current = null;
if (automaticOAuthEntry) {
setOAuthPhase("error");
onPhaseChange?.("needs_retry");
- setOAuthError(
- details?.code === "invalid_grant"
- ? "Your authorization expired or was revoked. Reconnect to continue."
- : describeError(error).body,
- );
+ setOAuthError(oauthStartFailureMessage(error, describeError(error).body));
return;
}
// The generic URL path explains the specific corrective action inline,
// beside the fields the operator has to change. A toast can't do that, and
// for a pasted address "check your key" is usually the wrong advice.
if (!entry && linkUrl) {
- const code = typeof details?.code === "string" ? details.code : null;
- const guidance = genericConnectGuidance(code, describeError(error).body);
- setLinkGuidance(guidance);
- setGenericOAuthPending(false);
- if (guidance.focus === "credentials") {
- // The probe is the answer to "does it need a key?", so the field
- // appears now rather than being offered as a guess beforehand.
- setLinkNeedsKey(true);
- setLinkAdvancedOpen(true);
+ const { code, providerError, upstreamStatus, connectionId } = readOAuthApiErrorDetails(error);
+ if (errorStatus(error) === 404 || code === "connection_setup_not_incomplete") {
+ genericDraftResume.clear();
+ } else if (connectionId) {
+ genericDraftResume.remember(connectionId, {
+ linkUrl,
+ companyId: selectedCompanyId,
+ grantKind: effectiveGrantKind,
+ subjectAgentId: effectiveSubjectAgentId,
+ });
}
+ const guidance = genericConnectGuidance(code, describeError(error).body, { providerError, upstreamStatus });
+ applyGenericConnectGuidance(guidance);
return;
}
pushToast({
@@ -3007,6 +3053,7 @@ function StandardConnectionSetupFlow({
onOAuthClientIdChange={setLinkOAuthClientId}
oauthClientSecret={linkOAuthClientSecret}
onOAuthClientSecretChange={setLinkOAuthClientSecret}
+ callbackUrl={callbackUrlForSetup}
advancedOpen={linkAdvancedOpen}
onAdvancedOpenChange={setLinkAdvancedOpen}
guidance={linkGuidance}
diff --git a/ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx b/ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx
index 0103b16ff05..bae5616491a 100644
--- a/ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx
+++ b/ui/src/features/connections/GenericMcpConnectStep.machine.test.tsx
@@ -2,7 +2,7 @@
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { newCustomHeaderRow } from "@/pages/apps/generic-mcp-connect";
+import { genericConnectGuidance, newCustomHeaderRow } from "@/pages/apps/generic-mcp-connect";
import { GenericMcpConnectStep } from "./GenericMcpConnectStep";
import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils";
@@ -69,6 +69,47 @@ describe("Machine sign-in in the custom server step", () => {
});
});
+describe("Browser sign-in callback URL and client fields in the custom server step", () => {
+ let root: Root;
+ let container: HTMLDivElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ });
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ });
+
+ it("opens the callback URL and client fields when automatic sign-in registration fails", async () => {
+ const callbackUrl = "https://paperclip.example.test/api/tools/oauth/callback";
+ const guidance = genericConnectGuidance(
+ "oauth_dynamic_client_registration_failed",
+ "The authorization server rejected Paperclip's callback URL.",
+ { providerError: "invalid_redirect_uri", upstreamStatus: 400 },
+ );
+ await act(async () => {
+ root.render(
+ undefined}
+ authMode="oauth" onAuthModeChange={() => undefined} headers={[newCustomHeaderRow()]} onHeadersChange={() => undefined}
+ oauthClientId="" onOAuthClientIdChange={() => undefined} oauthClientSecret="" onOAuthClientSecretChange={() => undefined}
+ callbackUrl={callbackUrl}
+ advancedOpen onAdvancedOpenChange={() => undefined} guidance={guidance} submitting={false}
+ onBack={() => undefined} onConnect={() => undefined} machineSignIn={null}
+ />,
+ );
+ });
+ expect(container.textContent).toContain("Paperclip callback URL");
+ expect(container.textContent).toContain(callbackUrl);
+ expect(container.querySelector('button[aria-label="Copy callback URL"]')).not.toBeNull();
+ expect(container.querySelector("#generic-mcp-client-id")).not.toBeNull();
+ expect(container.querySelector("#generic-mcp-client-secret")).not.toBeNull();
+ });
+});
+
describe("Session replay in the custom server step", () => {
it("blocks the server link, which can carry an API key, from session replay", async () => {
const container = document.createElement("div");
diff --git a/ui/src/features/connections/GenericMcpConnectStep.tsx b/ui/src/features/connections/GenericMcpConnectStep.tsx
index e36d99de2b0..c1244bae8af 100644
--- a/ui/src/features/connections/GenericMcpConnectStep.tsx
+++ b/ui/src/features/connections/GenericMcpConnectStep.tsx
@@ -1,5 +1,5 @@
import { useState, type KeyboardEvent, type ReactNode } from "react";
-import { Loader2, Plus, X } from "lucide-react";
+import { Check, Copy, Loader2, Plus, X } from "lucide-react";
import type { AppDefinition, ConnectToolAppResult } from "@paperclipai/shared";
import { InlineBanner } from "@/components/InlineBanner";
import { Button } from "@/components/ui/button";
@@ -8,6 +8,7 @@ import { Input } from "@/components/ui/input";
import { RadioCard } from "@/components/ui/radio-card";
import { ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy";
import { redactUrlSecrets } from "@/lib/redact-url-secrets";
+import { useCopyAction } from "@/lib/use-copy-action";
import { cn } from "@/lib/utils";
import { AppLogo } from "@/pages/apps/AppLogo";
import { MachineSignInSetup } from "./MachineSignInSetup";
@@ -106,6 +107,7 @@ export function GenericMcpConnectStep({
onOAuthClientIdChange,
oauthClientSecret,
onOAuthClientSecretChange,
+ callbackUrl,
advancedOpen,
onAdvancedOpenChange,
guidance,
@@ -131,6 +133,7 @@ export function GenericMcpConnectStep({
onOAuthClientIdChange: (next: string) => void;
oauthClientSecret: string;
onOAuthClientSecretChange: (next: string) => void;
+ callbackUrl?: string | null;
advancedOpen: boolean;
onAdvancedOpenChange: (next: boolean) => void;
guidance: GenericConnectGuidance | null;
@@ -148,6 +151,7 @@ export function GenericMcpConnectStep({
const [clientFieldsOpen, setClientFieldsOpen] = useState(false);
// Machine sign-in runs its own setup and test, so it is a choice beside the modes, not one of them.
const [machineSelected, setMachineSelected] = useState(false);
+ const { copied: callbackCopied, failed: callbackCopyFailed, copy: copyCallbackUrl } = useCopyAction();
const machine = Boolean(machineSelected && machineSignIn);
const headerError = authMode === "custom_headers" ? customHeaderError(headers) : null;
const canSubmit = canSubmitGenericConnect({
@@ -169,6 +173,7 @@ export function GenericMcpConnectStep({
const showClientFields = clientFieldsOpen
|| oauthClientId.trim().length > 0
|| oauthClientSecret.trim().length > 0
+ || guidance?.focus === "oauth_client"
|| guidance?.focus === "credentials";
const updateHeader = (id: string, patch: Partial) => {
@@ -293,6 +298,32 @@ export function GenericMcpConnectStep({
Paperclip sets sign-in up on its own whenever the server allows it. Fill these in only when the
server’s docs tell you to register Paperclip yourself first.
+ {callbackUrl ? (
+
+
+
+
+ {callbackUrl}
+
+
+
+
+ Share this exact URL with the provider if it allowlists clients, or add it when registering your own app.
+
+
+ ) : null}