Files
PaperClipAI/server/src/services/tool-access/catalog/failures.ts
T
DottaandPaperclip a1b9eed57d 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>
2026-11-30 14:20:23 -06:00

231 lines
9.3 KiB
TypeScript

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>;
return {};
}
/**
* Did this error come from the OAuth endpoint gate (PAP-17099)? Such a refusal
* is Paperclip's own decision about an unsafe address, so it must keep its code
* and its 422 instead of being folded into a generic upstream failure.
*/
export function isOAuthEndpointRejection(error: unknown): boolean {
if (!(error instanceof HttpError)) return false;
const code = asRecord(error.details).code;
return typeof code === "string" && code.endsWith("_endpoint_rejected");
}
/** A caller without an agent grant has not tested the connection's credential. */
export function isCallerAuthorizationFailure(error: unknown, actor?: ActorInfo): boolean {
return actor?.actorType === "agent" && error instanceof HttpError
&& asRecord(error.details).code === "agent_authorization_required";
}
export function healthFailureHttpStatus(failure: {
status: ToolConnectionHealthStatus;
code: string;
}): number {
if (failure.status === "missing_secret") return 422;
if (failure.code === "oauth_challenge") return 422;
if (failure.code === "oauth_refresh_missing") return 422;
if (failure.code === "oauth_reauthorization_required") return 422;
if (failure.code === "oauth_insufficient_scope") return 422;
if (failure.code === "slack_mcp_access_disabled") return 422;
if (failure.code === "user_authorization_required") return 422;
if (failure.code === "agent_authorization_required" || failure.code === "agent_authorization_ambiguous") return 422;
if (failure.code === "github_installation_required") return 422;
if (failure.code === "composio_broker_retired") return 422;
if (failure.code === "tool_connection_transport_unsupported") return 422;
if (failure.code === "cognee_access_unverified" || failure.code === "memory_api_key_rejected") return 422;
if (failure.code.endsWith("_endpoint_rejected")) return 422;
if (isAwsConfigurationFailureCode(failure.code)) return 422;
return 502;
}
function isAwsConfigurationFailureCode(code: string): boolean {
return code.startsWith("aws_") && code !== "aws_unavailable";
}
export const UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE =
"This connection has no supported tool integration. Add a supported account or MCP connection from Connectors.";
export function unsupportedToolConnectionTransport() {
return unprocessable(
UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE,
{ code: "tool_connection_transport_unsupported" },
);
}
export function sanitizeHttpFailure(error: unknown): {
status: ToolConnectionHealthStatus;
message: string;
code: string;
} {
if (error instanceof HttpError) {
const code = asRecord(error.details).code;
if (code === "cognee_access_unverified" || code === "memory_api_key_rejected") {
return { status: "error", message: error.message, code };
}
if (code === "grant_credential_invalid" || code === "oauth_insufficient_scope") {
return { status: code === "grant_credential_invalid" ? "missing_secret" : "degraded", message: error.message, code };
}
if (code === "slack_mcp_access_disabled" || code === "google_workspace_services_unavailable") {
return { status: "error", message: error.message, code };
}
if (code === "user_authorization_required" || code === "agent_authorization_required"
|| code === "agent_authorization_ambiguous" || code === "github_installation_required") {
return { status: "error", message: error.message, code };
}
if (code === "tool_connection_transport_unsupported") {
return { status: "error", message: error.message, code };
}
if (code === "composio_broker_retired") {
return { status: "error", message: error.message, code };
}
if (typeof code === "string" && code.startsWith("remote_http_")) {
return { status: "error", message: error.message, code };
}
if (isOAuthEndpointRejection(error)) {
return { status: "error", message: error.message, code: String(code) };
}
if (code === "oauth_challenge") {
return {
status: "error",
message: "This app needs you to sign in.",
code: "oauth_challenge",
};
}
if (code === "oauth_refresh_missing") {
return {
status: "failed",
message: "OAuth credentials have expired and need to be reconnected.",
code: "oauth_refresh_missing",
};
}
if (code === "oauth_reauthorization_required") {
return {
status: "error",
message: "Access to this app ended. Reconnect to continue.",
code: "oauth_reauthorization_required",
};
}
if (typeof code === "string" && isAwsConfigurationFailureCode(code)) {
return { status: "error", message: error.message, code };
}
if (code === "aws_unavailable") return { status: "degraded", message: error.message, code };
if (typeof code === "string" && code.startsWith("vercel_connect_")) {
return {
status:
code === "vercel_connect_unavailable" ||
code === "vercel_connect_auth_failed" ||
code === "vercel_connect_installation_required"
? "degraded"
: "error",
message: error.message,
code,
};
}
if (
code === "oauth_refresh_in_progress" ||
code === "oauth_refresh_superseded" ||
code === "oauth_refresh_outcome_unknown"
) {
return {
status: "error",
message: error.message,
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" ||
code === "secret_inactive" ||
code === "version_missing"
) {
return {
status: "missing_secret",
message: "A configured credential secret could not be resolved.",
code: String(code),
};
}
if (error.status === 404 && /secret/i.test(error.message)) {
return {
status: "missing_secret",
message: "A configured credential secret could not be resolved.",
code: "secret_missing",
};
}
return { status: "error", message: error.message, code: "paperclip_error" };
}
if (error instanceof Error) {
return {
status: "error",
message: error.message.slice(0, 240),
code: "runtime_error",
};
}
return {
status: "error",
message: "Connection check failed.",
code: "runtime_error",
};
}
const UNREACHABLE_SERVER_REASONS: Readonly<Record<string, string>> = {
connection_refused: "nothing accepted the connection",
dns_failure: "its host name did not resolve",
network_unreachable: "its network address could not be reached",
connection_reset: "the connection was dropped",
connection_timeout: "it did not answer in time",
tls_failure: "its TLS certificate was not accepted",
};
/**
* For an agent, a check that could not reach the MCP server is final until the
* person fixes the URL or the server. Say so, so the agent hands it back instead
* of retrying or contacting other network addresses as a workaround.
*/
export function unreachableServerRemediation(
source: unknown,
actor?: Pick<ActorInfo, "actorType">,
): { remediation: string } | Record<string, never> {
if (actor?.actorType !== "agent") return {};
const reason = mcpConnectionFailureReason(source);
const detail = reason ? UNREACHABLE_SERVER_REASONS[reason] : undefined;
if (!detail) return {};
return {
remediation: `Paperclip could not reach this MCP server at its saved URL: ${detail}. This result is final until the person fixes it: they must correct the URL, or start the server or make it reachable from Paperclip, and then check it again. Retrying now will not connect it, and you must not contact other hosts, ports or network addresses yourself as a workaround. Reply now: tell the person the server could not be reached and what they need to fix, do not say it is connected, and link [Open Connectors](/<prefix>/apps), with this conversation's company prefix as <prefix>, where they can fix or remove the connection or set it up again.`,
};
}
/**
* Every Google Workspace service failed. Carry the first classified cause onto
* the aggregate so an unreachable server still gets the final remediation
* instead of a bare "retry".
*/
export function googleWorkspaceServicesUnavailable(services: readonly string[], causes: readonly unknown[]): HttpError {
const error = new HttpError(502, `Google services unavailable: ${services.join(", ")}. Retry refreshing actions.`,
{ code: "google_workspace_services_unavailable" });
const cause = causes.find((candidate) => mcpConnectionFailureReason(candidate) !== null);
return cause === undefined ? error : retainMcpConnectionFailure(cause, error);
}