Files
PaperClipAI/server/src/services/google-workspace-rest-dispatch.ts
T
DottaandPaperclip 1299d1d776 fix(google-workspace): keep approved tools active when only Paperclip's display title changed (#22980)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use Google Workspace through a connection whose catalog rows
store each action's definition, and a catalog refresh holds a changed
definition for review
> - #22630 replaced each launch Google Workspace action's discovered
title with Paperclip's own readable display label (for example, `Gmail:
Read a message`), and #22874 exempted transitions from Paperclip's
shipped REST schemas back to Google's MCP servers
> - Catalog publication still hashes `descriptor.title` into
`versionHash`, so refreshing a Google Workspace MCP connection whose
rows were saved before #22630 (with a `null` title or Google's raw
title, including after the 30-day technical-information strip) or after
a local display-title copy edit quarantines every approved Gmail and
Workspace action even though Google changed nothing
> - This pull request recognizes Paperclip-authored display titles for
the six REST-defined Google Workspace services and skips quarantine when
`schemaHash` is unchanged and `versionHash` matches the exact discovered
description, input schema, annotations, and risk level under the
previously saved or raw upstream title
> - The benefit is that catalog refreshes keep approved Gmail and Google
Workspace tools working without false review holds, while upstream
description, schema, annotation, risk-level, and non-Paperclip title
mutations still quarantine for review

## Linked Issues or Issue Description

Refs #22630
Refs #22874

**What happened?**

Refreshing a managed Google Workspace connection (`POST
/api/tool-connections/:id/catalog/refresh` or the automatic 15-minute
`listCatalog` refresh) puts previously approved Gmail and Workspace read
actions into `quarantined` (`pending_review`) when the saved catalog
rows carry a `null` title, Google's raw title (pre-#22630 MCP
connections, including rows stripped by the 30-day Google Technical
Information sweep), or an earlier Paperclip display title. Because
`discovery.ts` substitutes Paperclip's local display title
(`googleWorkspaceCatalogToolTitle`) before `publication.ts` computes
`descriptorHash`, `existing.versionHash !== hash` fires even when
Google's upstream definition did not change at all.

**Expected behavior**

Catalog refresh keeps already-approved Google Workspace actions `active`
(preserving `reviewedAt`, `reviewedByUserId`, Off, and Ask first
settings) when only Paperclip's own display title changed, while still
quarantining any upstream change to `description`, `inputSchema`,
`annotations`, `riskLevel`, or any title change on tools whose title is
provider-controlled. Already-quarantined rows stay held for human
review.

**Steps to reproduce**

1. Connect Google Workspace on Google's MCP servers with Gmail
permissions enabled and approve all read actions.
2. Have saved catalog rows from before #22630 (where `title` is `null`
or Google's raw title such as `"Get Message"` and `versionHash` was
computed with that title), or from an earlier Paperclip display title.
3. Run `refreshCatalog` against Google's MCP server returning the exact
same `description`, `inputSchema`, `annotations`, and `riskLevel`.
4. Observe that all 9 Gmail actions move to `status: "quarantined"`
(`quarantineReason: "pending_review"`) and disappear from agent
sessions.

**Paperclip version or commit**

`2d065677959b585065ff3fec8718156a4cf6f41d`

## What Changed

- `server/src/services/google-workspace-rest-dispatch.ts`: added
`googleWorkspacePaperclipToolTitle(toolName)` returning Paperclip's
static display title only for the six REST-defined Google Workspace
services (`gmail`, `drive`, `docs`, `sheets`, `slides`, `calendar`), and
reused it in `googleWorkspaceCatalogToolTitle`.
- `server/src/services/connectors/paperclip-defined-tools.ts`: exposed
`paperclipAuthoredToolTitle(connection, toolName)` on the narrow
connector contract so `publication.ts` stays connector-agnostic.
- `server/src/services/tool-access/catalog/descriptors.ts` &
`discovery.ts`: carried the raw upstream title as an in-memory-only
`upstreamTitle` field on `McpToolDescriptor` when Google Workspace
discovery replaces `title` with Paperclip's local display title (needed
when the 30-day Google Technical Information sweep has cleared
`existing.title` to `null`).
- `server/src/services/tool-access/catalog/publication.ts`: skipped
quarantine when `existing.schemaHash === schemaHash`,
`paperclipAuthoredToolTitle` equals `descriptor.title` (non-null), and
`descriptorHash` with `existing.title ?? null` or
`descriptor.upstreamTitle ?? null` matches `existing.versionHash`.
Already-quarantined rows remain quarantined, and any change to
`description`, `inputSchema`, `annotations`, `riskLevel`, or
non-Paperclip titles still quarantines.
- `server/src/__tests__/google-workspace-mcp-transport.test.ts`,
`server/src/services/google-workspace-rest-dispatch.test.ts`, and
`server/src/__tests__/connector-tool-policy.test.ts`: added
embedded-Postgres and unit regression tests covering all four
Paperclip-title-only refresh cases, plus security negative tests
confirming description/annotation/schema mutations on Gmail and upstream
title mutations on non-Paperclip connectors still quarantine.

## Verification

- Red before fix (on base `2d065677959b585065ff3fec8718156a4cf6f41d`):
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/google-workspace-mcp-transport.test.ts -t "keeps approved
Gmail read tools active on refresh when only Paperclip|still quarantines
approved Gmail read tools when Google mutates"` -> `4 failed | 1 passed`
(`AssertionError: expected 9 to be +0` quarantined on all 4 title-only
cases).
- Green after fix:
- `pnpm --filter @paperclipai/server exec vitest run
src/services/google-workspace-rest-dispatch.test.ts
src/__tests__/google-workspace-mcp-transport.test.ts
src/__tests__/connector-tool-policy.test.ts` -> **3 files, 77 passed
(77)** (including 34/34 embedded-Postgres Google Workspace MCP transport
tests, 21/21 REST dispatch tests, and 22/22 connector policy tests).
- `pnpm --filter @paperclipai/server exec vitest run
src/google-workspace-rest-tools/boundary.test.ts` -> **1 file, 2 passed
(2)**.
- `pnpm --filter @paperclipai/server typecheck` -> **PASS** (all 7
server typecheck layers).
- `node scripts/check-test-budget.mjs --files
server/src/services/google-workspace-rest-dispatch.test.ts
server/src/__tests__/google-workspace-mcp-transport.test.ts
server/src/__tests__/connector-tool-policy.test.ts` -> **PASS** (`110
nightly suites validated, 3 test file(s) checked`).
- `pnpm verify --base 2d06567795
--explain` selected 1947/2301 test files (>50); focused affected suites
and server typecheck ran locally while sharded PR CI supplies broad
coverage.

## Risks

- Low risk. No schema migration, no API contract change, and no
relaxation of security boundaries.
- Only tools whose displayed title is unconditionally replaced by
Paperclip's static `googleWorkspacePaperclipToolTitle` (the 36 launch
Google Workspace tools) can match `paperclipTitleOnlyChange`, and only
when SHA-256 proves `name`, `description`, `inputSchema`, `annotations`,
and `riskLevel` are all identical to the saved row.
- Already-quarantined rows (including pre-#22874 switch holds) remain
held for human review, matching #22874's safety invariant.

## Model Used

- Google Gemini (Antigravity agentic coding assistant) with tool use,
shell execution, and embedded-Postgres integration testing.

## 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

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:32:39 -06:00

246 lines
11 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 googleWorkspacePaperclipToolTitle(toolName: string): string | null {
const target = googleWorkspaceToolTarget(toolName);
const restTitle = target && isGoogleWorkspaceRestService(target.service)
? listGoogleWorkspaceRestTools(target.service).find((tool) => tool.name === target.leaf)?.title
: undefined;
return restTitle ? googleWorkspaceToolTitle(toolName, restTitle) : null;
}
export function googleWorkspaceCatalogToolTitle(
sourceTemplateKey: unknown,
name: string,
title: string | null | undefined,
): string | null {
if (sourceTemplateKey !== "google-workspace") return title ?? null;
return googleWorkspacePaperclipToolTitle(name) ?? googleWorkspaceToolTitle(name, 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();
}