fix(mcp): stop masking upstream MCP and OAuth 502 errors as Paperclip outages (#23295)

## 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 <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-30 14:20:23 -06:00
1 parent 3621d7204d
commit a1b9eed57d
25 files changed
+1719 -61

No files matched your search

+1
View File
@@ -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";
@@ -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);
});
});
@@ -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<string> = new Set([
...UPSTREAM_MCP_OAUTH_FAILURE_CODES,
...UPSTREAM_REMOTE_HTTP_FAILURE_CODES,
]);
export const NON_RETRYABLE_UPSTREAM_BAD_GATEWAY_CODES: ReadonlySet<string> = 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<string> = new Set([
"server_error",
"temporarily_unavailable",
]);
export const TRANSIENT_UPSTREAM_HTTP_STATUSES: ReadonlySet<number> = 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;
}
@@ -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);
});
@@ -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) {
@@ -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);
+9 -1
View File
@@ -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<string, unknown>)
: {};
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;
@@ -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);
@@ -29,7 +29,10 @@ export async function withMcpConnectionFailure<T>(request: () => Promise<T>): 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. */
+19
View File
@@ -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
@@ -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);
}
});
});
@@ -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<string> = new Set(
UPSTREAM_MCP_OAUTH_FAILURE_CODES,
);
function asRecord(value: unknown): Record<string, unknown> {
if (value && typeof value === "object" && !Array.isArray(value))
return value as Record<string, unknown>;
@@ -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" ||
@@ -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",
+123 -1
View File
@@ -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",
+37 -1
View File
@@ -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];
@@ -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<string, string | undefined>,
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 }) => (
<a href={to} {...props}>{children}</a>
),
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(
<QueryClientProvider client={queryClient}>
<ConnectionSetupFlow host="page" />
</QueryClientProvider>,
);
});
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<HTMLInputElement>("#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<HTMLInputElement>("#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<string, unknown>;
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<string, unknown>).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<string, unknown>).resumeConnectionId).toBeUndefined();
});
});
@@ -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<string | null>(null);
const genericDraftResume = useGenericDraftResume({ reconnectConnectionId });
const hydratedResumeConnectionIdRef = useRef<string | null>(null);
const [hydratedResumeConnectionId, setHydratedResumeConnectionId] = useState<string | null>(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<string, boolean> = {};
@@ -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}
@@ -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(
<GenericMcpConnectStep
link="https://mcp.example/mcp" name="" needsKey={false} keyValue="" onKeyChange={() => 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");
@@ -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<CustomHeaderRow>) => {
@@ -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.
</p>
{callbackUrl ? (
<div>
<label className="text-sm font-medium text-foreground">Paperclip callback URL</label>
<div className="mt-2 flex min-w-0 flex-col gap-2 sm:flex-row">
<div
title={callbackUrl}
className="min-h-10 min-w-0 flex-1 rounded-md border border-input bg-muted/40 px-3 py-2 font-mono text-xs leading-tight text-foreground break-all"
>
{callbackUrl}
</div>
<Button
type="button"
variant="outline"
className="shrink-0"
aria-label="Copy callback URL"
onClick={() => void copyCallbackUrl(callbackUrl)}
>
{callbackCopied ? <Check className="mr-2 h-4 w-4" aria-hidden="true" /> : <Copy className="mr-2 h-4 w-4" aria-hidden="true" />}
{callbackCopied ? "Copied" : callbackCopyFailed ? "Copy failed" : "Copy"}
</Button>
</div>
<p className="mt-2 text-xs text-muted-foreground">
Share this exact URL with the provider if it allowlists clients, or add it when registering your own app.
</p>
</div>
) : null}
<div className="grid gap-4 sm:grid-cols-2">
<div>
<label className="text-sm font-medium text-foreground" htmlFor="generic-mcp-client-id">
@@ -0,0 +1,105 @@
import { describe, expect, it } from "vitest";
import {
oauthFailureMessage,
oauthStartFailureMessage,
readOAuthApiErrorDetails,
} from "./oauthFailureMessages";
describe("oauthFailureMessage for dynamic client registration and metadata failures", () => {
it("explains callback URL rejection during automatic sign-in setup", () => {
const message = oauthFailureMessage("oauth_dynamic_client_registration_failed", "invalid_redirect_uri");
expect(message).toMatch(/callback URL/i);
expect(message).toMatch(/allowlist/i);
expect(message).toMatch(/client ID/i);
});
it("explains generic dynamic client registration failure without exposing raw codes", () => {
const message = oauthFailureMessage("oauth_dynamic_client_registration_failed", null);
expect(message).toMatch(/automatic sign-in setup/i);
expect(message).toMatch(/client ID/i);
expect(message).not.toContain("oauth_");
});
it("explains rate limits and temporary upstream statuses during automatic sign-in setup", () => {
const rateLimited = oauthFailureMessage("oauth_dynamic_client_registration_failed", null, 429);
expect(rateLimited).toMatch(/rate-limited/i);
expect(rateLimited).toMatch(/try again/i);
expect(rateLimited).not.toMatch(/client ID/i);
const temporaryError = oauthFailureMessage("oauth_dynamic_client_registration_failed", null, 503);
expect(temporaryError).toMatch(/temporary error/i);
expect(temporaryError).toMatch(/try again/i);
expect(temporaryError).not.toMatch(/client ID/i);
});
it("explains invalid DCR response and OAuth metadata failures", () => {
expect(oauthFailureMessage("oauth_dcr_response_invalid")).toMatch(/invalid response/i);
expect(oauthFailureMessage("oauth_metadata_failed")).toMatch(/sign-in settings/i);
});
});
describe("readOAuthApiErrorDetails", () => {
it("extracts code, allowlisted providerError, upstreamStatus, and connectionId from HttpError details", () => {
expect(readOAuthApiErrorDetails({
body: {
error: "The authorization server rejected Paperclip's callback URL.",
details: {
code: "oauth_dynamic_client_registration_failed",
providerError: "invalid_redirect_uri",
status: 400,
connectionId: " conn-draft-1 ",
},
},
})).toEqual({
code: "oauth_dynamic_client_registration_failed",
providerError: "invalid_redirect_uri",
upstreamStatus: 400,
connectionId: "conn-draft-1",
});
});
it("falls back to top-level body.code and drops non-allowlisted provider errors", () => {
expect(readOAuthApiErrorDetails({
body: {
code: "mcp_catalog_error",
details: { providerError: "untrusted_raw_text", connectionId: " " },
},
})).toEqual({
code: "mcp_catalog_error",
providerError: null,
upstreamStatus: null,
connectionId: null,
});
});
});
describe("oauthStartFailureMessage", () => {
it("formats DCR start failures with actionable guidance and preserves invalid_grant and fallback", () => {
const dcrError = {
body: {
error: "The authorization server rejected Paperclip's callback URL.",
details: {
code: "oauth_dynamic_client_registration_failed",
providerError: "invalid_redirect_uri",
status: 400,
},
},
};
const rateLimitedDcrError = {
body: {
error: "The authorization server failed during client registration.",
details: {
code: "oauth_dynamic_client_registration_failed",
status: 429,
},
},
};
expect(oauthStartFailureMessage(dcrError, "fallback")).toMatch(/callback URL/i);
expect(oauthStartFailureMessage(dcrError, "fallback")).toMatch(/allowlist/i);
expect(oauthStartFailureMessage(rateLimitedDcrError, "fallback")).toMatch(/rate-limited/i);
expect(oauthStartFailureMessage({ body: { details: { code: "invalid_grant" } } }, "fallback"))
.toBe("Your authorization expired or was revoked. Reconnect to continue.");
expect(oauthStartFailureMessage({ body: { details: { code: "other" } } }, "Server message"))
.toBe("Server message");
});
});
@@ -1,3 +1,5 @@
import { isTransientUpstreamHttpStatus } from "@paperclipai/shared";
const DEFAULT_OAUTH_FAILURE_MESSAGE = "Authorization did not complete. Try again when you’re ready.";
const OAUTH_PROVIDER_ERROR_COPY = new Map<string, string>([
@@ -20,6 +22,13 @@ const OAUTH_PROVIDER_ERROR_COPY = new Map<string, string>([
["login_required", "The provider requires you to sign in first. Try connecting again."],
]);
export interface OAuthApiErrorDetails {
code: string | null;
providerError: string | null;
upstreamStatus: number | null;
connectionId: string | null;
}
export function allowlistedOAuthProviderError(value: unknown): string | null {
if (typeof value !== "string") return null;
if (value === "access_denied" || OAUTH_PROVIDER_ERROR_COPY.has(value)) return value;
@@ -37,8 +46,42 @@ export function readConnectionIntentOAuthProviderError(data: unknown): string |
return allowlistedOAuthProviderError((data as { providerError?: unknown }).providerError);
}
export function oauthFailureMessage(code: string | null, providerError?: string | null): string {
export function readOAuthApiErrorDetails(error: unknown): OAuthApiErrorDetails {
if (!error || typeof error !== "object") {
return { code: null, providerError: null, upstreamStatus: null, connectionId: null };
}
const body = (error as { body?: unknown }).body;
if (!body || typeof body !== "object" || Array.isArray(body)) {
return { code: null, providerError: null, upstreamStatus: null, connectionId: null };
}
const record = body as { code?: unknown; details?: unknown };
const details = record.details && typeof record.details === "object" && !Array.isArray(record.details)
? (record.details as { code?: unknown; providerError?: unknown; status?: unknown; connectionId?: unknown })
: null;
const code = typeof details?.code === "string"
? details.code
: typeof record.code === "string"
? record.code
: null;
const providerError = allowlistedOAuthProviderError(details?.providerError);
const upstreamStatus = typeof details?.status === "number" && Number.isFinite(details.status)
? details.status
: null;
const connectionId = typeof details?.connectionId === "string" && details.connectionId.trim()
? details.connectionId.trim()
: null;
return { code, providerError, upstreamStatus, connectionId };
}
export function oauthFailureMessage(
code: string | null,
providerError?: string | null,
upstreamStatus?: number | null,
): string {
const safeProviderError = allowlistedOAuthProviderError(providerError);
if (code === "oauth_dynamic_client_registration_failed" && safeProviderError === "invalid_redirect_uri") {
return "The provider rejected Paperclip’s callback URL during automatic sign-in setup. Ask the provider to allowlist Paperclip’s callback URL, or use your own OAuth client ID.";
}
if (safeProviderError && safeProviderError !== "access_denied") {
const providerCopy = OAUTH_PROVIDER_ERROR_COPY.get(safeProviderError);
if (providerCopy) return providerCopy;
@@ -51,6 +94,18 @@ export function oauthFailureMessage(code: string | null, providerError?: string
return "Sign-in finished in a different Paperclip session. Stay signed in to Paperclip in this browser and try again.";
case "oauth_redirect_origin_unsupported":
return "Sign-in returned to a different Paperclip address than the one you started from. Open Paperclip at its usual address and try again.";
case "oauth_dynamic_client_registration_failed":
if (upstreamStatus === 429) {
return "The provider rate-limited automatic sign-in setup. Wait a moment and try again.";
}
if (isTransientUpstreamHttpStatus(upstreamStatus)) {
return "The provider reported a temporary error during automatic sign-in setup. Try again shortly.";
}
return "The provider refused Paperclip’s automatic sign-in setup. Ask the provider to allowlist Paperclip’s callback URL, or use your own OAuth client ID.";
case "oauth_dcr_response_invalid":
return "The provider returned an invalid response during automatic sign-in setup. Try again or use your own OAuth client ID.";
case "oauth_metadata_failed":
return "Paperclip couldn’t read the provider’s sign-in settings. Confirm the server address or try again shortly.";
case "oauth_token_exchange_failed":
case "oauth_token_endpoint_rejected":
case "oauth_access_token_missing":
@@ -67,6 +122,21 @@ export function oauthFailureMessage(code: string | null, providerError?: string
}
}
export function oauthStartFailureMessage(error: unknown, fallback: string): string {
const { code, providerError, upstreamStatus } = readOAuthApiErrorDetails(error);
if (code === "invalid_grant") {
return "Your authorization expired or was revoked. Reconnect to continue.";
}
if (
code === "oauth_dynamic_client_registration_failed"
|| code === "oauth_dcr_response_invalid"
|| code === "oauth_metadata_failed"
) {
return oauthFailureMessage(code, providerError, upstreamStatus);
}
return fallback;
}
export function oauthCallbackErrorMessage(
outcome: string | null,
code: string | null,
@@ -0,0 +1,90 @@
import { useCallback, useMemo, useRef } from "react";
import type { ConnectionGrantKind, ToolConnection } from "@paperclipai/shared";
import {
resolveGenericDraftResumeId,
type GenericDraftResumeState,
} from "@/pages/apps/generic-mcp-connect";
export interface GenericDraftContext {
linkUrl: string;
companyId: string | null;
grantKind: ConnectionGrantKind;
subjectAgentId: string | null;
}
export interface GenericDraftResumeController {
remember: (connectionId: string | null | undefined, context: GenericDraftContext) => void;
clear: (connectionId?: string) => void;
resolve: (
input: GenericDraftContext & {
resumeConnectionId: string | null;
reconnectConnectionId: string | null;
},
) => string | null;
}
export function grantKindFromConnection(
connection: Pick<ToolConnection, "credentialPolicy">,
): ConnectionGrantKind {
if (connection.credentialPolicy === "per_user") return "user";
if (connection.credentialPolicy === "per_agent") return "agent";
return "organization";
}
/**
* Tracks a generic MCP draft created on an earlier attempt so retrying after
* an OAuth registration rejection reuses that draft instead of creating a
* duplicate numbered connection, while starting a fresh draft if the URL,
* company, or credential ownership changes.
*/
export function useGenericDraftResume(options: {
reconnectConnectionId: string | null;
}): GenericDraftResumeController {
const savedDraftRef = useRef<GenericDraftResumeState | null>(null);
const { reconnectConnectionId } = options;
const remember = useCallback(
(connectionId: string | null | undefined, context: GenericDraftContext) => {
const trimmedUrl = context.linkUrl.trim();
if (!connectionId || reconnectConnectionId || !context.companyId || !trimmedUrl) return;
savedDraftRef.current = {
connectionId,
linkUrl: trimmedUrl,
companyId: context.companyId,
grantKind: context.grantKind,
subjectAgentId: context.grantKind === "agent" ? context.subjectAgentId : null,
};
},
[reconnectConnectionId],
);
const clear = useCallback((connectionId?: string) => {
if (!connectionId || savedDraftRef.current?.connectionId === connectionId) {
savedDraftRef.current = null;
}
}, []);
const resolve = useCallback(
(
input: GenericDraftContext & {
resumeConnectionId: string | null;
reconnectConnectionId: string | null;
},
) =>
resolveGenericDraftResumeId({
resumeConnectionId: input.resumeConnectionId,
reconnectConnectionId: input.reconnectConnectionId,
savedDraft: savedDraftRef.current,
linkUrl: input.linkUrl,
companyId: input.companyId,
grantKind: input.grantKind,
subjectAgentId: input.subjectAgentId,
}),
[],
);
return useMemo(
() => ({ remember, clear, resolve }),
[remember, clear, resolve],
);
}
@@ -6,8 +6,10 @@ import {
endpointHost,
genericConnectGuidance,
genericConnectPayload,
genericGuidanceFormPatch,
newCustomHeaderRow,
oauthCallbackUrlForBrowser,
resolveGenericDraftResumeId,
type GenericConnectDraft,
} from "./generic-mcp-connect";
@@ -86,6 +88,13 @@ describe("genericConnectGuidance", () => {
"mcp_remote_url_invalid",
"remote_http_private_endpoint",
"remote_http_dns_failed",
"remote_http_connect_failed",
"remote_http_response_timeout",
"oauth_metadata_failed",
"oauth_redirect_rejected",
"oauth_redirect_limit",
"mcp_remote_http_error",
"mcp_catalog_error",
"runtime_error",
]) {
expect(genericConnectGuidance(code, null).focus, code).toBe("url");
@@ -98,6 +107,92 @@ describe("genericConnectGuidance", () => {
expect(guidance.body).toContain("key or headers its docs list below");
});
it("explains callback URL rejection during automatic sign-in setup and focuses browser sign-in client fields", () => {
const guidance = genericConnectGuidance(
"oauth_dynamic_client_registration_failed",
"The authorization server rejected Paperclip's callback URL.",
{ providerError: "invalid_redirect_uri", upstreamStatus: 400 },
);
expect(guidance.focus).toBe("oauth_client");
expect(guidance.title).toContain("callback URL");
expect(guidance.body).toContain("allowlist");
expect(guidance.body).toContain("client ID");
});
it("handles other DCR provider errors, transient HTTP statuses, and manual client codes clearly", () => {
const metadataRejected = genericConnectGuidance(
"oauth_dynamic_client_registration_failed",
"The authorization server rejected Paperclip's registration metadata.",
{ providerError: "invalid_client_metadata", upstreamStatus: 400 },
);
expect(metadataRejected.focus).toBe("oauth_client");
expect(metadataRejected.body).toContain("callback URL below");
const accessDenied = genericConnectGuidance(
"oauth_dynamic_client_registration_failed",
"The authorization server refused dynamic client registration.",
{ providerError: "access_denied", upstreamStatus: 403 },
);
expect(accessDenied.focus).toBe("oauth_client");
expect(accessDenied.body).toContain("client ID");
const providerOutage = genericConnectGuidance(
"oauth_dynamic_client_registration_failed",
"The authorization server failed during client registration.",
{ providerError: "server_error", upstreamStatus: 500 },
);
expect(providerOutage.focus).toBe("none");
expect(providerOutage.title).toContain("sign-in service");
const upstream5xx = genericConnectGuidance(
"oauth_dynamic_client_registration_failed",
"The authorization server failed during client registration.",
{ upstreamStatus: 503 },
);
expect(upstream5xx.focus).toBe("none");
const rateLimited = genericConnectGuidance(
"oauth_dynamic_client_registration_failed",
"The authorization server rate-limited client registration.",
{ upstreamStatus: 429 },
);
expect(rateLimited.focus).toBe("none");
expect(rateLimited.title).toContain("rate-limiting");
expect(rateLimited.body).toContain("Wait a moment and try again");
for (const status of [408, 425]) {
const transient4xx = genericConnectGuidance(
"oauth_dynamic_client_registration_failed",
"The authorization server failed during client registration.",
{ upstreamStatus: status },
);
expect(transient4xx.focus, String(status)).toBe("none");
expect(transient4xx.body, String(status)).toContain("Try again shortly");
}
const generic4xx = genericConnectGuidance(
"oauth_dynamic_client_registration_failed",
"The authorization server rejected client registration.",
{ upstreamStatus: 403 },
);
expect(generic4xx.focus).toBe("oauth_client");
for (const code of [
"oauth_dcr_response_invalid",
"oauth_dcr_not_supported",
"oauth_dcr_client_auth_unsupported",
"oauth_client_registration_unavailable",
"oauth_manual_client_required",
"oauth_manual_client_rebinding_required",
]) {
expect(genericConnectGuidance(code, null).focus, code).toBe("oauth_client");
}
expect(genericConnectGuidance("oauth_pkce_s256_required", null).focus).toBe("credentials");
expect(genericConnectGuidance("oauth_token_exchange_failed", null).focus).toBe("none");
expect(genericConnectGuidance("oauth_access_token_missing", null).focus).toBe("none");
});
it("points at the deployment when Paperclip itself has no public HTTPS address", () => {
expect(genericConnectGuidance("oauth_redirect_origin_unsupported", null).focus).toBe("deployment");
});
@@ -123,6 +218,142 @@ describe("genericConnectGuidance", () => {
});
});
describe("genericGuidanceFormPatch", () => {
it("expands Browser sign-in and disables bearer key mode for oauth_client guidance", () => {
const guidance = genericConnectGuidance(
"oauth_dynamic_client_registration_failed",
null,
{ providerError: "invalid_redirect_uri", upstreamStatus: 400 },
);
expect(genericGuidanceFormPatch(guidance)).toEqual({
guidance,
genericOAuthPending: false,
authMode: "oauth",
needsKey: false,
advancedOpen: true,
});
});
it("reveals the key field for credentials guidance and leaves form controls untouched otherwise", () => {
const credGuidance = genericConnectGuidance("oauth_challenge", null);
expect(genericGuidanceFormPatch(credGuidance)).toEqual({
guidance: credGuidance,
genericOAuthPending: false,
needsKey: true,
advancedOpen: true,
});
const urlGuidance = genericConnectGuidance("oauth_metadata_failed", null);
expect(genericGuidanceFormPatch(urlGuidance)).toEqual({
guidance: urlGuidance,
genericOAuthPending: false,
});
});
});
describe("resolveGenericDraftResumeId", () => {
const savedDraft = {
connectionId: "conn-draft-1",
linkUrl: "https://mcp.dreamdata.io/mcp",
companyId: "company-1",
grantKind: "user" as const,
subjectAgentId: null,
};
it("resumes the saved draft when retrying the same URL, company, and access choice", () => {
expect(resolveGenericDraftResumeId({
resumeConnectionId: null,
reconnectConnectionId: null,
savedDraft,
linkUrl: " https://mcp.dreamdata.io/mcp ",
companyId: "company-1",
grantKind: "user",
subjectAgentId: null,
})).toBe("conn-draft-1");
});
it("starts a fresh draft when credential ownership or dedicated agent changes", () => {
expect(resolveGenericDraftResumeId({
resumeConnectionId: null,
reconnectConnectionId: null,
savedDraft,
linkUrl: "https://mcp.dreamdata.io/mcp",
companyId: "company-1",
grantKind: "organization",
subjectAgentId: null,
})).toBeNull();
const agentDraft = {
connectionId: "conn-agent-draft",
linkUrl: "https://mcp.dreamdata.io/mcp",
companyId: "company-1",
grantKind: "agent" as const,
subjectAgentId: "agent-1",
};
expect(resolveGenericDraftResumeId({
resumeConnectionId: null,
reconnectConnectionId: null,
savedDraft: agentDraft,
linkUrl: "https://mcp.dreamdata.io/mcp",
companyId: "company-1",
grantKind: "agent",
subjectAgentId: "agent-1",
})).toBe("conn-agent-draft");
expect(resolveGenericDraftResumeId({
resumeConnectionId: null,
reconnectConnectionId: null,
savedDraft: agentDraft,
linkUrl: "https://mcp.dreamdata.io/mcp",
companyId: "company-1",
grantKind: "agent",
subjectAgentId: "agent-2",
})).toBeNull();
});
it("prefers an explicit resumeConnectionId and skips draft resume during reconnects or URL/company changes", () => {
expect(resolveGenericDraftResumeId({
resumeConnectionId: "conn-route-resume",
reconnectConnectionId: null,
savedDraft,
linkUrl: "https://mcp.dreamdata.io/mcp",
companyId: "company-1",
grantKind: "organization",
subjectAgentId: null,
})).toBe("conn-route-resume");
expect(resolveGenericDraftResumeId({
resumeConnectionId: null,
reconnectConnectionId: "conn-active-1",
savedDraft,
linkUrl: "https://mcp.dreamdata.io/mcp",
companyId: "company-1",
grantKind: "user",
subjectAgentId: null,
})).toBeNull();
expect(resolveGenericDraftResumeId({
resumeConnectionId: null,
reconnectConnectionId: null,
savedDraft,
linkUrl: "https://mcp.other.io/mcp",
companyId: "company-1",
grantKind: "user",
subjectAgentId: null,
})).toBeNull();
expect(resolveGenericDraftResumeId({
resumeConnectionId: null,
reconnectConnectionId: null,
savedDraft,
linkUrl: "https://mcp.dreamdata.io/mcp",
companyId: "company-2",
grantKind: "user",
subjectAgentId: null,
})).toBeNull();
});
});
describe("customHeaderError", () => {
it("accepts a filled row and ignores a blank one", () => {
expect(customHeaderError([
+203 -4
View File
@@ -1,5 +1,11 @@
import { checkMcpRemoteHeaderName, checkMcpRemoteHeaderValue, mcpRemoteHeaderRejectionMessage, paperclipPeerFromMcpUrl } from "@paperclipai/shared";
import type { GenericMcpAuthMode } from "@paperclipai/shared";
import {
checkMcpRemoteHeaderName,
checkMcpRemoteHeaderValue,
isTransientUpstreamHttpStatus,
mcpRemoteHeaderRejectionMessage,
paperclipPeerFromMcpUrl,
} from "@paperclipai/shared";
import type { ConnectionGrantKind, GenericMcpAuthMode } from "@paperclipai/shared";
/**
* Logic behind the guided "Connect your own MCP server" flow (PAP-17087).
@@ -84,7 +90,7 @@ export function defaultGenericMcpName(url: string): string | null {
* this to decide whether to reopen the URL field or the credential section, rather
* than leaving them to guess which of the two was wrong.
*/
export type GenericConnectFocus = "url" | "credentials" | "deployment" | "none";
export type GenericConnectFocus = "url" | "credentials" | "oauth_client" | "deployment" | "none";
export interface GenericConnectGuidance {
title: string;
@@ -92,6 +98,145 @@ export interface GenericConnectGuidance {
focus: GenericConnectFocus;
}
export interface GenericConnectFailureDetails {
providerError?: string | null;
upstreamStatus?: number | null;
}
export interface GenericGuidanceFormPatch {
guidance: GenericConnectGuidance;
genericOAuthPending: false;
authMode?: GenericMcpAuthMode;
needsKey?: boolean;
advancedOpen?: boolean;
}
export function genericGuidanceFormPatch(
guidance: GenericConnectGuidance,
): GenericGuidanceFormPatch {
if (guidance.focus === "oauth_client") {
return {
guidance,
genericOAuthPending: false,
authMode: "oauth",
needsKey: false,
advancedOpen: true,
};
}
if (guidance.focus === "credentials") {
return {
guidance,
genericOAuthPending: false,
needsKey: true,
advancedOpen: true,
};
}
return {
guidance,
genericOAuthPending: false,
};
}
export interface GenericDraftResumeState {
connectionId: string;
linkUrl: string;
companyId: string;
grantKind: ConnectionGrantKind;
subjectAgentId: string | null;
}
/**
* Resolve the draft connection to resume when submitting a generic MCP connect
* request. Preserving a draft created on an earlier attempt (for example when
* automatic OAuth registration was rejected and the operator enters a manual
* client ID) prevents creating a duplicate numbered connection, while starting
* a fresh draft whenever the server URL, company, or credential ownership
* (`grantKind` / dedicated agent) changes so the server never silently keeps
* an outdated access policy.
*/
export function resolveGenericDraftResumeId(input: {
resumeConnectionId: string | null;
reconnectConnectionId: string | null;
savedDraft: GenericDraftResumeState | null;
linkUrl: string;
companyId: string | null;
grantKind: ConnectionGrantKind;
subjectAgentId?: string | null;
}): string | null {
if (input.resumeConnectionId) return input.resumeConnectionId;
if (input.reconnectConnectionId) return null;
if (!input.savedDraft || !input.companyId) return null;
const requestedSubjectAgentId = input.grantKind === "agent" ? (input.subjectAgentId ?? null) : null;
if (
input.savedDraft.companyId !== input.companyId
|| input.savedDraft.linkUrl !== input.linkUrl.trim()
|| input.savedDraft.grantKind !== input.grantKind
|| input.savedDraft.subjectAgentId !== requestedSubjectAgentId
) {
return null;
}
return input.savedDraft.connectionId;
}
function dynamicClientRegistrationGuidance(
details?: GenericConnectFailureDetails,
): GenericConnectGuidance {
const providerError = details?.providerError ?? null;
const upstreamStatus = details?.upstreamStatus ?? null;
if (providerError === "invalid_redirect_uri") {
return {
title: "This server didn't allow Paperclip's callback URL",
body: "The server rejected Paperclip's callback URL during automatic sign-in setup. Some servers only allow approved clients or require registering an app first. Ask the provider to allowlist the callback URL below, or enter your own client ID under Browser sign-in.",
focus: "oauth_client",
};
}
if (
providerError === "invalid_client_metadata"
|| providerError === "invalid_software_statement"
|| providerError === "unapproved_software_statement"
) {
return {
title: "This server rejected automatic sign-in setup",
body: "The server rejected Paperclip's automatic sign-in registration details. Register Paperclip in the provider's settings using the callback URL below, then enter your client ID under Browser sign-in.",
focus: "oauth_client",
};
}
if (
providerError === "access_denied"
|| providerError === "unauthorized_client"
|| providerError === "invalid_client"
) {
return {
title: "This server refused automatic sign-in setup",
body: "The server did not allow Paperclip to register itself automatically. Register Paperclip in the provider's settings using the callback URL below, or enter your own client ID under Browser sign-in.",
focus: "oauth_client",
};
}
if (
providerError === "server_error"
|| providerError === "temporarily_unavailable"
|| isTransientUpstreamHttpStatus(upstreamStatus)
) {
if (upstreamStatus === 429) {
return {
title: "The server is rate-limiting sign-in setup",
body: "The server asked Paperclip to slow down while setting up sign-in. Wait a moment and try again.",
focus: "none",
};
}
return {
title: "The server's sign-in service had an error",
body: "The server's sign-in endpoint reported a temporary error while setting up sign-in. Try again shortly, or contact the provider if it keeps happening.",
focus: "none",
};
}
return {
title: "This server rejected automatic sign-in setup",
body: "The server wouldn't let Paperclip register itself automatically. Ask the provider to allowlist the callback URL below, or enter your own client ID under Browser sign-in.",
focus: "oauth_client",
};
}
/**
* Turn an API failure into the specific corrective action the plan asks for:
* invalid, unsafe, unreachable, or "needs a credential we could not discover".
@@ -102,6 +247,7 @@ export interface GenericConnectGuidance {
export function genericConnectGuidance(
code: string | null | undefined,
message: string | null | undefined,
details?: GenericConnectFailureDetails,
): GenericConnectGuidance {
const fallback = message?.trim() || "Paperclip couldn't connect to that address. Check it and try again.";
switch (code) {
@@ -124,6 +270,13 @@ export function genericConnectGuidance(
body: "The address didn't resolve. Check the spelling, or confirm the server is published on the internet.",
focus: "url",
};
case "remote_http_connect_failed":
case "remote_http_response_timeout":
return {
title: "We couldn't reach that server",
body: fallback,
focus: "url",
};
case "mcp_header_rejected":
return {
title: "Paperclip can't send that header",
@@ -142,13 +295,59 @@ export function genericConnectGuidance(
body: "It asked us to authenticate but didn't offer a sign-in Paperclip can complete on its own. Add the key or headers its docs list below.",
focus: "credentials",
};
case "oauth_dynamic_client_registration_failed":
return dynamicClientRegistrationGuidance(details);
case "oauth_dcr_response_invalid":
return {
title: "The server returned invalid sign-in setup data",
body: "The server answered Paperclip's automatic sign-in setup with an unusable response. Register Paperclip in the provider's settings using the callback URL below, then enter your client ID under Browser sign-in.",
focus: "oauth_client",
};
case "oauth_dcr_not_supported":
case "oauth_dcr_client_auth_unsupported":
case "oauth_client_registration_unavailable":
case "oauth_manual_client_required":
case "oauth_manual_client_rebinding_required":
return {
title: "This server needs sign-in details you create yourself",
body: "Register Paperclip in the provider's settings, then add the client ID and secret it gives you below.",
body: "Register Paperclip in the provider's settings using the callback URL below, then add the client ID and secret it gives you under Browser sign-in.",
focus: "oauth_client",
};
case "oauth_pkce_s256_required":
return {
title: "This server's sign-in isn't compatible with Paperclip",
body: "The server doesn't advertise the security option Paperclip requires for browser sign-in. Check whether it supports a key or custom headers instead.",
focus: "credentials",
};
case "oauth_metadata_failed":
return {
title: "We couldn't read this server's sign-in settings",
body: "The server asked for browser sign-in, but its sign-in configuration endpoint failed or returned invalid data. Confirm the server address, or check with the provider.",
focus: "url",
};
case "oauth_redirect_rejected":
case "oauth_redirect_limit":
return {
title: "The server's sign-in redirect couldn't be followed",
body: fallback,
focus: "url",
};
case "oauth_token_exchange_failed":
case "oauth_access_token_missing":
return {
title: "The server didn't finish granting access",
body: "Sign-in reached the server, but it didn't return an access token Paperclip could use. Try again, or check that your account allows this app.",
focus: "none",
};
case "mcp_remote_http_error":
case "mcp_catalog_error":
case "mcp_catalog_invalid":
case "mcp_catalog_pagination":
return {
title: "The remote server returned an error",
body: fallback,
focus: "url",
};
case "oauth_redirect_origin_unsupported":
case "oauth_redirect_uri_invalid":
return {
+2 -3
View File
@@ -26,6 +26,7 @@ import { endpointHost } from "@/pages/apps/generic-mcp-connect";
import { withoutUnavailableActions } from "@/pages/apps/app-detail/action-permissions";
import { McpConfigHelpDialog } from "./McpConfigHelpDialog";
import { describeError } from "@/api/errors";
import { oauthStartFailureMessage } from "@/features/connections/oauthFailureMessages";
const SAMPLE_CONFIG = `{
"mcpServers": {
@@ -180,9 +181,7 @@ export function PasteConfigTab({ companyId }: { companyId: string }) {
onError: (error) => {
authorization.cancel();
setOAuthPhase("error");
setOAuthError(
describeError(error).body,
);
setOAuthError(oauthStartFailureMessage(error, describeError(error).body));
},
});