Files
PaperClipAI/server/src/google-workspace-rest-tools/argument-guards.ts
T
DottaandClaude Opus 5.5 f1dd9288d1 fix(google-workspace): show agents Paperclip's refusal text and a stable Google error code (#22881)
## 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>
2026-11-24 23:46:35 -06:00

102 lines
4.9 KiB
TypeScript

import { assertRequestKinds, type RequestKindRules } from "./documents-shared.js";
import { DOCS_REQUEST_KINDS } from "./docs/request-kinds.js";
import { GoogleToolError } from "./errors.js";
import { SLIDES_REQUEST_KINDS } from "./slides/request-kinds.js";
import { unknownArgumentProblems, type JsonSchemaNode } from "./tool.js";
import type { GoogleWorkspaceRestService } from "./tools.js";
const FILE_ID = /^[A-Za-z0-9_-]{1,256}$/;
const FILE_ID_ARGUMENTS: Partial<Record<GoogleWorkspaceRestService, readonly string[]>> = {
drive: ["fileId", "parentId"],
docs: ["documentId"],
sheets: ["spreadsheetId"],
slides: ["presentationId"],
};
const REQUEST_KINDS: Partial<Record<GoogleWorkspaceRestService, Partial<Record<string, RequestKindRules>>>> = {
docs: { update_doc: DOCS_REQUEST_KINDS },
slides: { update_presentation: SLIDES_REQUEST_KINDS },
};
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
function closedAtTopOrDeclared(schema: JsonSchemaNode, path: string): schema is JsonSchemaNode & { properties: Record<string, JsonSchemaNode> } {
if (!isRecord(schema.properties)) return false;
return schema.additionalProperties === false || (path === "" && schema.additionalProperties === undefined);
}
export interface GoogleWorkspaceArgumentCheck {
service: GoogleWorkspaceRestService;
toolName: string;
arguments: unknown;
inputSchema: unknown;
}
export interface GoogleWorkspaceRefusal {
code: string;
message: string;
}
export function googleWorkspaceArgumentRefusal(check: GoogleWorkspaceArgumentCheck): GoogleWorkspaceRefusal | null {
const args = check.arguments ?? {};
if (!isRecord(args)) return refusal("invalid_arguments", check.toolName, "arguments must be an object.");
const schema = isRecord(check.inputSchema) && check.inputSchema.additionalProperties === false && !isRecord(check.inputSchema.properties)
? { ...check.inputSchema, properties: {} } : check.inputSchema;
const unknown = unknownArgumentProblems(args, schema, "", closedAtTopOrDeclared);
if (unknown.length > 0) return refusal("unknown_argument", check.toolName, unknown.join(" "));
for (const name of FILE_ID_ARGUMENTS[check.service] ?? []) {
const value = args[name];
if (value !== undefined && (typeof value !== "string" || !FILE_ID.test(value))) {
return refusal("invalid_file_id", check.toolName, `${name} must be one Google file ID (letters, digits, - and _), not a link or a list.`);
}
}
const rules = REQUEST_KINDS[check.service]?.[check.toolName];
if (rules && args.requests !== undefined) {
const requests = args.requests;
if (!Array.isArray(requests) || requests.some((request) => !isRecord(request) || Object.keys(request).length !== 1)) {
return refusal("request_kind_refused", check.toolName, "requests must be a list in which each request names exactly one kind of update, such as insertText.");
}
try {
assertRequestKinds(requests as Array<Record<string, unknown>>, rules);
} catch (error) {
if (error instanceof GoogleToolError) return refusal("request_kind_refused", check.toolName, error.message);
throw error;
}
}
return null;
}
function refusal(code: string, toolName: string, detail: string): GoogleWorkspaceRefusal {
return { code, message: `Invalid arguments for ${toolName}: ${detail} Nothing was sent to Google.` };
}
export interface GoogleCalendarEventRead {
isError: boolean;
structuredContent: unknown;
text: string | null;
}
const SERIES_REFUSAL: GoogleWorkspaceRefusal = { code: "recurring_series_delete_refused", message: "This ID is a whole recurring series. This tool deletes single events or single occurrences only. Pass one occurrence's ID (from list_events). Nothing was deleted." };
function eventFrom(read: GoogleCalendarEventRead): Record<string, unknown> | null {
const structured = isRecord(read.structuredContent) ? read.structuredContent : null;
let candidate: unknown = structured;
if (!structured && read.text) {
try {
candidate = JSON.parse(read.text);
} catch {
return null;
}
}
if (!isRecord(candidate)) return null;
return isRecord(candidate.event) ? candidate.event : candidate;
}
export function googleCalendarSeriesRefusal(read: GoogleCalendarEventRead): GoogleWorkspaceRefusal | null {
const event = read.isError ? null : eventFrom(read);
if (!event || (event.id === undefined && event.eventId === undefined && event.start === undefined)) {
return { code: "delete_target_unverified", message: "Paperclip reads an event before it deletes it, to make sure the ID is not a whole recurring series, and that read did not return the event. Check the eventId and calendarId with get_event. Nothing was deleted." };
}
const recurrence = event.recurrence;
return Array.isArray(recurrence) && recurrence.length > 0 && !event.recurringEventId ? SERIES_REFUSAL : null;
}