mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call Google Workspace through Google's MCP servers. Paperclip
checks the arguments before it sends a call (#22815, #22706)
> - The Paperclip Runner wrapper for assigned tools sends the agent only
a stable code. It does not send the provider's free text (#22723)
> - Paperclip's own refusals had no code. Google's errors had no code.
So the agent saw only `assigned_tool_error: The connected tool reported
an error.`
> - The agent did not know which argument to remove, or that it must
delete one occurrence. It retried blindly and stopped
> - This pull request gives each Paperclip refusal a stable code and
sends its Paperclip-written text. It gives each Google error a stable
code from Google's status. It records the code on the failed call event
> - The benefit is that the agent can fix its call, and an admin can see
why a call failed
## Linked Issues or Issue Description
Refs #22815
Refs #22723
Refs #22842
**What happened?**
On the staging tester (build 1b4ebec), a Workspace Tester agent on
OpenCode + DeepSeek on the native runtime ran a QA task. Three Calendar
calls returned only `assigned_tool_error: The connected tool reported an
error.`:
1. `list_calendars` with an extra argument `bogus: 1`. Paperclip refused
it before dispatch (`dispatched: false`).
2. `delete_event` with a recurring series ID. Paperclip refused it
before dispatch (`dispatched: false`).
3. `respond_to_event` "accepted" on an event that the user organises.
Google returned an error. The agent retried blindly and stopped. The
failed call event had an empty `errorCode` and `errorMessage`.
**What did you expect to happen?**
1. The agent sees `unknown_argument:` and the refusal text that names
the unknown argument and lists the accepted arguments.
2. The agent sees `recurring_series_delete_refused:` and the text that
tells it to pass one occurrence.
3. The agent sees a stable code from Google's structured error, for
example `google_permission_denied`. The failed call event records this
code.
**Steps to reproduce**
1. Connect Google Workspace on Google's MCP servers and give an agent on
the Paperclip Runner access.
2. Call Calendar `list_calendars` with `{ "bogus": 1 }`.
3. Call Calendar `delete_event` with the ID of a recurring series.
4. Call Calendar `respond_to_event` on an event that Google refuses.
5. Each call returns only `assigned_tool_error: The connected tool
reported an error.`
## What Changed
- `argument-guards.ts`: each refusal now returns `{ code, message }`.
The codes are `unknown_argument`, `invalid_arguments`,
`invalid_file_id`, `request_kind_refused`,
`recurring_series_delete_refused` and `delete_target_unverified`.
- `tool-gateway.ts`: a Google MCP preflight refusal returns
`errorDetails` with the code and the Paperclip text (`paperclipRefusal`)
beside the result. Only Paperclip code sets this field, so a provider
result cannot forge it. A Google MCP error result gets `errorDetails`
from the new `googleWorkspaceMcpErrorDetails`. The three tool error
throw sites use these details first.
- `google-workspace-rest-dispatch.ts`: `googleWorkspaceMcpErrorDetails`
finds Google's HTTP status (`error.code`, a status name such as
`PERMISSION_DENIED` mapped to its canonical HTTP status, or `HTTP 403`
in the text). It gives the status and Google's error body to the REST
tools' `googleError`, so there is one Google classification. The code is
`google_<kind>`, for example `google_permission_denied`,
`google_invalid_argument`, `google_not_found`, `google_unavailable`, or
`google_unauthenticated` / `google_insufficient_scope`. Otherwise the
code is `google_error`. `google_rate_limited` is retryable.
`google_unavailable` is retryable only for a read action: a write can
already be applied when Google reports a server error. Google's text
never becomes a code.
- `assigned-mcp-tools.ts`: `toolReportedError` sends `paperclipRefusal`
text after the code, bounded to 2,000 characters. Without it, the
message stays `<code>: The connected tool reported an error.` (#22723
rule).
- Every failed call event writer (`tool_call_events`, `call_failed`:
agent call, approved action, connection test, plugin tool) now records
`errorCode` (the tool code, else the reason code) and `errorMessage`
through one helper. The 30-day Google Technical Information sweep from
#22842 already clears `tool_call_events.error_message` for Google
connections. The invocation row is unchanged (`errorCode: tool_error`,
`errorMessage`: the text).
- README of the Google Workspace tools: the codes and what the agent
sees.
Why Google's text stays out: #22723 sends only a stable code because
provider text is untrusted. It can carry prompt injection or internal
details. This reasoning applies to Google's text, so this change keeps
it. In a test, an injection-style Google error message was blocked by
the result screen, which shows that this text is a real risk.
Paperclip's refusal text is trusted: Paperclip wrote it. It echoes only
the argument names that the agent sent and the argument names from the
tool's schema, which the agent already has.
## Verification
- Red/green: the first three new tests in
`server/src/__tests__/google-workspace-mcp-transport.test.ts` ("what an
agent on the Paperclip Runner sees when a call fails") use the fake
Google MCP server and the native-runtime assigned tool path
(`buildPaperclipRuntimeMcpServers` + `createAssignedMcpTools`). With the
gateway and wrapper changes reverted, all three fail. With the changes,
all three pass:
- `list_calendars { bogus: 1 }` → `unknown_argument: Invalid arguments
for list_calendars: unknown argument "bogus". Accepted arguments:
pageSize, pageToken. Nothing was sent to Google.` Event `errorCode:
unknown_argument`, `dispatched: false`, nothing sent to Google.
- `delete_event` on a series → `recurring_series_delete_refused: This ID
is a whole recurring series. … Pass one occurrence's ID (from
list_events). Nothing was deleted.` Event `errorCode:
recurring_series_delete_refused`, `dispatched: false`.
- `respond_to_event` with a Google 403 `PERMISSION_DENIED` →
`google_permission_denied: The connected tool reported an error.` with
no Google text. Event `errorCode: google_permission_denied`,
`errorMessage`: Google's text.
- A fourth test approves an Ask first `respond_to_event` that Google
refuses. The failed call event has `errorCode: google_permission_denied`
and Google's text.
- Unit tests: guard codes (`argument-guards.test.ts`),
`googleWorkspaceMcpErrorDetails` classification, 5xx retry for reads
only, and its free-text refusal
(`google-workspace-rest-dispatch.test.ts`), refusal text only from the
gateway detail and bounded (`assigned-mcp-tools.test.ts`).
- Focused run: `npx vitest run` on the tool gateway, tool gateway
service, content deletion, Google connection removal, Google Workspace
tools, dispatch, assigned tools and MCP transport tests: 63 files, 1,925
tests passed.
- `pnpm exec tsc --noEmit -p server/tsconfig.json`: passed.
- `pnpm verify`: exit 2 (the README is a broad input). Required CI
covers the rest.
## Risks
- Low. The change touches only connected tool errors. Approval,
revocation and gateway failures are unchanged.
- A failed call event now records `errorMessage` for every connection,
not only Google. The invocation row and the audit event already hold
this text. For Google connections, the 30-day sweep clears it.
- `errorCode` on the call event holds a short code such as
`google_permission_denied`, not Google text. The sweep does not clear
it, as on the invocation row.
- The ACPX runner feedback (Rust) keeps only the leading code from a
failed tool result. Harnesses on that path now see the stable code (for
example `unknown_argument`) but not the refusal text. OpenCode on the
native runtime sees the full text. A runner change is out of scope.
- A JSON-RPC protocol error from Google (not a tool error result) keeps
its current path (`remote_mcp_error`).
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code, 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
- [ ] 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>
242 lines
10 KiB
TypeScript
242 lines
10 KiB
TypeScript
import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
|
|
import {
|
|
GOOGLE_WORKSPACE_TOOL_TRANSPORT,
|
|
googleWorkspaceServiceToolNames,
|
|
googleWorkspaceToolName,
|
|
googleWorkspaceToolTarget,
|
|
googleWorkspaceToolTitle,
|
|
type GoogleWorkspaceService,
|
|
type GoogleWorkspaceToolTransport,
|
|
} from "@paperclipai/shared";
|
|
import {
|
|
GOOGLE_WORKSPACE_REST_SHIPPED_SCHEMA_HASHES,
|
|
GoogleToolError,
|
|
GoogleWorkspaceAuthError,
|
|
callGoogleWorkspaceRestTool,
|
|
googleCalendarSeriesRefusal,
|
|
googleError,
|
|
googleWorkspaceArgumentRefusal,
|
|
isGoogleWorkspaceRestService,
|
|
listGoogleWorkspaceRestTools,
|
|
probeGoogleWorkspaceRestService,
|
|
type GoogleAuthFailure,
|
|
type GoogleFetch,
|
|
type GoogleWorkspaceRefusal,
|
|
type GoogleWorkspaceRestService,
|
|
} from "../google-workspace-rest-tools/index.js";
|
|
|
|
export type GoogleWorkspaceRestAuthFailure = GoogleAuthFailure;
|
|
export type { GoogleWorkspaceRefusal };
|
|
|
|
export interface GoogleWorkspaceRestContext {
|
|
service: GoogleWorkspaceService;
|
|
credentialHeaders: Record<string, string>;
|
|
fetch: GoogleFetch;
|
|
signal?: AbortSignal;
|
|
}
|
|
|
|
export type GoogleWorkspaceRestCallOutcome =
|
|
| { ok: true; result: CallToolResult }
|
|
| { ok: false; authFailure: GoogleWorkspaceRestAuthFailure };
|
|
|
|
export type GoogleWorkspaceRestProbeOutcome =
|
|
| { ok: true }
|
|
| { ok: false; authFailure: "unauthenticated" | null; message: string };
|
|
|
|
export function googleWorkspaceRestAuditEndpoint(service: GoogleWorkspaceService): string {
|
|
return `paperclip-rest:google-workspace/${service}`;
|
|
}
|
|
|
|
export function listGoogleWorkspaceRest(service: GoogleWorkspaceService): Tool[] {
|
|
return listGoogleWorkspaceRestTools(restService(service));
|
|
}
|
|
|
|
export interface GoogleWorkspaceRestToolDefinition {
|
|
name: string;
|
|
title: string | null;
|
|
description: string | null;
|
|
inputSchema: Record<string, unknown>;
|
|
outputSchema: Record<string, unknown> | null;
|
|
annotations: Record<string, unknown>;
|
|
}
|
|
|
|
export function googleWorkspaceRestToolDefinition(toolName: string): GoogleWorkspaceRestToolDefinition | null {
|
|
return googleWorkspaceTransport(toolName) === "paperclip_rest" ? googleWorkspaceRestFallbackDefinition(toolName) : null;
|
|
}
|
|
|
|
export function googleWorkspaceRestFallbackDefinition(toolName: string): GoogleWorkspaceRestToolDefinition | null {
|
|
const target = googleWorkspaceToolTarget(toolName);
|
|
if (!target || !isGoogleWorkspaceRestService(target.service)) return null;
|
|
const tool = listGoogleWorkspaceRestTools(target.service).find((candidate) => candidate.name === target.leaf);
|
|
return tool ? {
|
|
name: tool.name,
|
|
title: googleWorkspaceCatalogToolTitle("google-workspace", toolName, tool.title),
|
|
description: tool.description ?? null,
|
|
inputSchema: { ...tool.inputSchema },
|
|
outputSchema: tool.outputSchema ? { ...tool.outputSchema } : null,
|
|
annotations: { ...tool.annotations },
|
|
} : null;
|
|
}
|
|
|
|
export function googleWorkspaceRestShippedSchemaHashes(toolName: string): readonly string[] {
|
|
const target = googleWorkspaceToolTarget(toolName);
|
|
return target ? GOOGLE_WORKSPACE_REST_SHIPPED_SCHEMA_HASHES[`${target.service}__${target.leaf}`] ?? [] : [];
|
|
}
|
|
|
|
function googleWorkspaceTransport(toolName: string): GoogleWorkspaceToolTransport | null {
|
|
return googleWorkspaceToolTarget(toolName)?.transport ?? null;
|
|
}
|
|
|
|
export function googleWorkspaceCatalogToolTitle(
|
|
sourceTemplateKey: unknown,
|
|
name: string,
|
|
title: string | null | undefined,
|
|
): string | null {
|
|
if (sourceTemplateKey !== "google-workspace") return title ?? null;
|
|
const target = googleWorkspaceToolTarget(name);
|
|
const restTitle = target && isGoogleWorkspaceRestService(target.service)
|
|
? listGoogleWorkspaceRestTools(target.service).find((tool) => tool.name === target.leaf)?.title
|
|
: undefined;
|
|
return googleWorkspaceToolTitle(name, restTitle ?? title);
|
|
}
|
|
|
|
export interface GoogleWorkspaceMcpPreflight {
|
|
toolName: string;
|
|
arguments: unknown;
|
|
inputSchema: unknown;
|
|
callTool: (toolName: string, args: Record<string, unknown>) => Promise<unknown | null>;
|
|
}
|
|
|
|
export async function googleWorkspaceMcpPreflightRefusal(input: GoogleWorkspaceMcpPreflight): Promise<GoogleWorkspaceRefusal | null> {
|
|
const target = googleWorkspaceToolTarget(input.toolName);
|
|
if (!target || !isGoogleWorkspaceRestService(target.service)) return null;
|
|
const refusal = googleWorkspaceArgumentRefusal({ service: target.service, toolName: target.leaf, arguments: input.arguments, inputSchema: input.inputSchema });
|
|
if (refusal || target.service !== "calendar" || target.leaf !== "delete_event") return refusal;
|
|
const args = (input.arguments ?? {}) as Record<string, unknown>;
|
|
const lookup = Object.fromEntries(["calendarId", "eventId"].filter((key) => args[key] !== undefined).map((key) => [key, args[key]]));
|
|
const result = await input.callTool(googleWorkspaceToolName("calendar", "get_event"), lookup);
|
|
const record = (result && typeof result === "object" ? result : {}) as { content?: unknown; data?: { isError?: unknown; structuredContent?: unknown } };
|
|
return googleCalendarSeriesRefusal({
|
|
isError: record.data?.isError === true,
|
|
structuredContent: record.data?.structuredContent ?? null,
|
|
text: typeof record.content === "string" ? record.content : null,
|
|
});
|
|
}
|
|
|
|
const GOOGLE_STATUS_HTTP: Readonly<Record<string, number>> = {
|
|
INVALID_ARGUMENT: 400, FAILED_PRECONDITION: 400, OUT_OF_RANGE: 400, UNAUTHENTICATED: 401, PERMISSION_DENIED: 403, NOT_FOUND: 404,
|
|
ABORTED: 409, ALREADY_EXISTS: 409, RESOURCE_EXHAUSTED: 429, CANCELLED: 499, DATA_LOSS: 500, UNKNOWN: 500, INTERNAL: 500,
|
|
NOT_IMPLEMENTED: 501, UNAVAILABLE: 503, DEADLINE_EXCEEDED: 504,
|
|
};
|
|
const GOOGLE_STATUS_TEXT = new RegExp(`\\b(${Object.keys(GOOGLE_STATUS_HTTP).join("|")})\\b`);
|
|
const GOOGLE_HTTP_STATUS_TEXT = /\b(?:HTTP|status|code)\b["']?\s*[:=]?\s*([45]\d\d)\b/i;
|
|
|
|
function isObject(value: unknown): value is Record<string, unknown> {
|
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
}
|
|
|
|
function parseJson(text: string): unknown {
|
|
try {
|
|
return JSON.parse(text);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function httpStatusOf(error: Record<string, unknown>): number | null {
|
|
if (typeof error.code === "number" && error.code >= 400 && error.code < 600) return error.code;
|
|
return typeof error.status === "string" ? GOOGLE_STATUS_HTTP[error.status] ?? null : null;
|
|
}
|
|
|
|
function googleErrorOf(value: unknown): { status: number; body: string } | null {
|
|
if (!isObject(value)) return null;
|
|
const error = isObject(value.error) ? value.error : value;
|
|
const status = httpStatusOf(error);
|
|
return status === null ? null : { status, body: JSON.stringify({ error }) };
|
|
}
|
|
|
|
function googleErrorInText(text: string): { status: number; body: string } | null {
|
|
const structured = googleErrorOf(parseJson(text));
|
|
if (structured) return structured;
|
|
const named = GOOGLE_STATUS_TEXT.exec(text)?.[1];
|
|
const status = named ? GOOGLE_STATUS_HTTP[named] : Number(GOOGLE_HTTP_STATUS_TEXT.exec(text)?.[1]);
|
|
return status && status >= 400 && status < 600 ? { status, body: "" } : null;
|
|
}
|
|
|
|
export function googleWorkspaceMcpErrorDetails(result: unknown, options: { readOnly: boolean }): { toolCode: string; retryable?: true } {
|
|
const record = isObject(result) ? result : {};
|
|
const texts = Array.isArray(record.content)
|
|
? record.content.flatMap((item) => isObject(item) && typeof item.text === "string" ? [item.text] : [])
|
|
: [];
|
|
const found = googleErrorOf(record.structuredContent) ?? texts.map(googleErrorInText).find(Boolean) ?? null;
|
|
if (!found) return { toolCode: "google_error" };
|
|
const error = googleError({ status: found.status, headers: new Headers() }, found.body);
|
|
if (error instanceof GoogleWorkspaceAuthError) return { toolCode: `google_${error.reason}` };
|
|
if (!(error instanceof GoogleToolError)) return { toolCode: "google_error" };
|
|
const retryable = error.kind === "rate_limited" || (error.kind === "unavailable" && options.readOnly);
|
|
return { toolCode: `google_${error.kind}`, ...(retryable ? { retryable: true as const } : {}) };
|
|
}
|
|
|
|
export async function callGoogleWorkspaceRest(
|
|
input: GoogleWorkspaceRestContext & { toolName: string; arguments: unknown; maxResultBytes: number },
|
|
): Promise<GoogleWorkspaceRestCallOutcome> {
|
|
try {
|
|
const result = await callGoogleWorkspaceRestTool({
|
|
service: restService(input.service),
|
|
name: input.toolName,
|
|
arguments: input.arguments as Record<string, unknown> | undefined,
|
|
accessToken: bearerToken(input.credentialHeaders),
|
|
fetch: input.fetch,
|
|
signal: input.signal,
|
|
maxResultBytes: input.maxResultBytes,
|
|
});
|
|
return { ok: true, result };
|
|
} catch (error) {
|
|
if (error instanceof GoogleWorkspaceAuthError) return { ok: false, authFailure: error.reason };
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function probeGoogleWorkspaceRest(
|
|
input: GoogleWorkspaceRestContext & { grantedScopes: readonly string[] },
|
|
): Promise<GoogleWorkspaceRestProbeOutcome> {
|
|
try {
|
|
const probe = await probeGoogleWorkspaceRestService({
|
|
service: restService(input.service),
|
|
accessToken: bearerToken(input.credentialHeaders),
|
|
grantedScopes: input.grantedScopes,
|
|
fetch: input.fetch,
|
|
signal: input.signal,
|
|
});
|
|
return probe.ok ? { ok: true } : { ok: false, authFailure: null, message: probe.message };
|
|
} catch (error) {
|
|
if (error instanceof GoogleWorkspaceAuthError && error.reason === "unauthenticated") {
|
|
return { ok: false, authFailure: "unauthenticated", message: error.message };
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export function googleWorkspaceRestTransportGaps(
|
|
transport: Readonly<Record<GoogleWorkspaceService, GoogleWorkspaceToolTransport>> = GOOGLE_WORKSPACE_TOOL_TRANSPORT,
|
|
): Array<{ service: GoogleWorkspaceService; missing: string[] }> {
|
|
return (Object.keys(transport) as GoogleWorkspaceService[])
|
|
.filter((service) => transport[service] === "paperclip_rest")
|
|
.map((service) => {
|
|
const implemented = new Set(isGoogleWorkspaceRestService(service)
|
|
? listGoogleWorkspaceRestTools(service).map((tool) => tool.name) : []);
|
|
return { service, missing: googleWorkspaceServiceToolNames(service).filter((name) => !implemented.has(name)) };
|
|
})
|
|
.filter((gap) => gap.missing.length > 0);
|
|
}
|
|
|
|
function restService(service: GoogleWorkspaceService): GoogleWorkspaceRestService {
|
|
if (!isGoogleWorkspaceRestService(service)) throw new Error(`Google Workspace ${service} has no Paperclip REST tools`);
|
|
return service;
|
|
}
|
|
|
|
function bearerToken(headers: Record<string, string>): string {
|
|
const value = Object.entries(headers).find(([name]) => name.toLowerCase() === "authorization")?.[1] ?? "";
|
|
return value.replace(/^Bearer\s+/i, "").trim();
|
|
}
|