Files
PaperClipAI/server/src/services/tool-access/catalog/failures.ts
T
DottaandClaude Opus 5.5 1fa6d71171 fix(connections): clear run answer copies and show reconnect state when Google access ends (#22937)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use Google Workspace through a connection, and Paperclip
saves what they read in runs and tool-call records
> - Google's Workspace AI Tools Addendum says Paperclip must keep no
user data from a connection after access ends. #22836 and #22842 delete
this content when access ends.
> - A live test found two gaps. The run record still holds the run's
final answer and its evidence (a Drive link, text from a Drive file).
And after a person removes Paperclip at their Google Account, the
connection still shows as healthy and agents still get its tools.
> - This pull request clears the answer and evidence copies in the run
record, and puts the connection in the existing "sign in again" state
when no grant on it is active.
> - The benefit is that no Google data stays in run records after
deletion, and people and agents see that the connection must be signed
in again.

## Linked Issues or Issue Description

Refs #22836

**What happened?**

1. After `tool_connection.content_deleted`, `GET
/api/heartbeat-runs/:id` still returned Google data. The data was in
`resultJson.nativeResult.evidence[].ref`, `verification[].detail` and
`commandOrCheck`, `completionClaim.criteria[].evidenceRefs[]`, and in
`runnerProfileJson.sessionCheckpoint` (`semanticResult` and
`terminalTurns[].fingerprint`, a 1.3 to 1.9 KB copy of the result).
2. After a person removed Paperclip at their Google Account, the next
Google call failed with `oauth_reauthorization_required` and the
deletion started with reason `provider_access_ended`. But the connection
status stayed `active` with healthy status, and agents were still
offered its 34 tools.

**What did you expect to happen?**

1. The deletion clears the run's answer and evidence copies the same way
it clears the transcript. The run keeps its status, ids, counts and
hashes, so the run page still shows.
2. The connection shows that it needs a new sign-in, and agents do not
get its tools until someone reconnects.

**Steps to reproduce**

1. Connect Google Workspace and let an agent run that reads a Drive file
and reports a link as evidence.
2. Remove the connection (or remove Paperclip at the Google Account and
let the next Google call fail).
3. Wait for `tool_connection.content_deleted`.
4. Open `GET /api/heartbeat-runs/:id` for that run. See the Drive link
in `resultJson.nativeResult` and in
`runnerProfileJson.sessionCheckpoint`.
5. For case 2, open the connection. See status `active` and health `ok`.
List the agent's tools. See the Google tools.

## What Changed

- `content-cleaning.ts`: add `withoutRunAnswers`. In every
`paperclip.run_result.v1` object in `result_json` (`nativeResult`,
`acceptedResult`, `semanticResult.result`), each free-text string
becomes the fixed text "Removed because the connection data was
deleted.", so the result still passes `validatePrpStructuredRunResult`.
Structural fields stay (schema, disposition, status, scope, reason
codes, Paperclip ids, booleans and numbers). Agent-chosen
`idempotencyKey` values become `sha256:` hashes.
- `content-cleaning.ts`: add `withoutCheckpointAnswers`. It cleans the
persisted checkpoint (`PersistedNativeSession`): `semanticResult` and
`governedWait.result` the same way, `governedWait.sourceEvent.payload`
free text, and each `terminalTurns[]` fingerprint becomes its `sha256:`
hash. The recovery hash is updated when it matched.
- Each store gets its own mark: `result_json.answerCopiesDeletedAt` and
`sessionCheckpoint.contentDeletedAt`. A run in scope whose result or
checkpoint lacks its mark is cleaned again. This fixes runs cleaned by
an older build and a checkpoint rewritten later.
- `paperclip-control-plane-port.ts`: a checkpoint written for a run
whose result has `contentDeletedAt` is cleaned before it is saved
(`checkpointProfileForRun`).
- `withoutResultText` no longer blanks fields inside a run result;
`withoutRunAnswers` owns those.
- `withoutFreeText` moves from `run-copies.ts` to `content-cleaning.ts`;
`native_run_results` gets the same treatment.
- The task text stays: `contextSnapshot.paperclipIssue.description` and
`runnerProfileJson.nativeExecutionInput.task` are the user's text, not
Google data.
- `grant-refresh.ts`: when a refresh marks a grant
`needs_reauthorization` and no grant on the connection is still active,
the connection gets the needs-attention state: health `error`, last
error `oauth_reauthorization_required`, message "Access to this app
ended. Reconnect to continue." The check and the write run under a row
lock on the connection, so a reconnect that finishes at the same time is
not overwritten. This applies to the Paperclip Cloud broker path and to
the direct token path for personal grants. Status and the enabled flag
do not change, so the app list shows "Needs attention" (not "Paused"),
and a reconnect keeps the chosen tools.
- `tool-gateway.ts`: agents are not offered a connection's tools (tool
list, tool search, and the prompt guidance for usable connections) while
the connection has a `needs_reauthorization` grant and no active grant.
An action that a person already approved still finds its tool and waits
for the new sign-in, as before.
- Plain copy: "OAuth authorization expired/has expired" becomes "Access
to this app ended. Reconnect to continue." in `connection-refresh.ts`,
`grant-refresh.ts`, `catalog/failures.ts` and `oauth/client.ts`.
- UI (`Connections.tsx`, `Browse.tsx`): the removal message and dialog
count a connection as "available to agents" only when agents are offered
its tools: it is on, it is not waiting for a new sign-in, and it is
healthy, personal or a plugin. New helper
`isConnectionAvailableToAgents` in `connection-identity.ts`.
- Docs: the inventory and access-end notes in
`doc/memory/google-connector-memory.md`, and the help page
`docs/guides/board-operator/deleting-connection-data.md`.

## Verification

- Red/green:
`server/src/__tests__/tool-connection-content-deletion.test.ts`,
"removes the run's final answer and evidence from its result and session
checkpoint, and keeps the task text". It failed before the fix (the
Drive link and quoted text stayed in `nativeResult`) and passes after.
It also checks that a run cleaned by an older build is cleaned again,
that the task text stays, that `hasAcceptedSemanticResult` is still
true, and that the recovery hash matches the new checkpoint.
- Red/green:
`server/src/__tests__/google-managed-connection-removal.test.ts`, "shows
a user/organization connection needs signing in again and stops offering
its tools after Google access ends". Before the fix, health stayed `ok`.
After the fix, health is `error`, the agent's tool list for the
connection is empty, and after a reconnect health is `ok` and the tool
comes back.
- The deletion test checks that the fixture result is valid and that the
cleaned `nativeResult` and checkpoint `semanticResult` still pass
`validatePrpStructuredRunResult`. It rewrites a dirty checkpoint on a
cleaned run and checks that the next deletion cleans it, and checks
`checkpointProfileForRun`. It uses the persisted checkpoint shape
(`semanticResult` is the run result, plus `governedWait`). A second
phase stores a legacy run (no `answerCopiesDeletedAt` mark) whose only
remaining text is `nativeResult.evidence[].ref` and the checkpoint
copies, with hashed fingerprints and blank summaries. The new selection
rule cleans it.
- `tool-access-oauth-protocol.integration.test.ts` still passes: an
approved action waits for sign-in and runs after reconnect. Its fixture
now also restores the health fields when it restores the connection by
hand.
- `ui/src/pages/apps/connection-identity.test.ts`: the new helper does
not count a connection that needs attention.
- Agents in the needs-attention state: the provider-ended test lists the
agent's tools before (1), after Google access ends (0) and after
reconnect (1). So agents are not offered the actions of a connection in
that state.
- On the final code: deletion, removal and OAuth protocol files 77/77;
`paperclip-control-plane-port.test.ts` 108/108; deletion and
reauthorization cases in `tool-access-service.test.ts` 9/9; UI helper
test 12/12. Server and UI typecheck pass.
- `tsc --noEmit` for `server`: pass.
- `pnpm verify`: see the comment below for the result.

## Risks

- Medium-low. The tool gateway now hides a connection's tools from
discovery when it has a `needs_reauthorization` grant and no active
grant. Before, a personal (`per_user`) connection in that state still
listed its tools, and each call failed. Execution of an already approved
action is not changed. Connections with no grants, or with one active
grant, do not change.
- Health `error` is set for any provider whose last active grant needs a
new sign-in, not only Google. This is the same state a direct token
refresh already uses.
- No schema change and no migration.
- Not covered: the encrypted controller checkpoint rows
(`native_runner_checkpoints`). The harness backup expiration removes
them. This is recorded in the memory doc.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code
with tool use (shell, file edits, test runs).

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:31:28 -06:00

214 lines
8.8 KiB
TypeScript

import 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";
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 function unsupportedToolConnectionTransport() {
return unprocessable(
"This connection has no supported tool integration. Add a supported account or MCP connection from Connectors.",
{ 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 (
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);
}