feat(google-workspace): run the six launch services on Google's MCP servers again (#22815)

Gmail, Drive, Docs, Sheets, Slides and Calendar go back to google_mcp because of Google's Workspace AI Tools Addendum; the REST tool set stays as the fallback. The REST argument checks that need no request to Google run before each MCP call, a Calendar delete reads the event first and refuses a recurring series, and a refresh that replaces saved REST definitions holds nothing for review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-24 14:44:03 -06:00
1 parent 71ff1c8600
commit 4401962e69
19 files changed
+988 -80

No files matched your search

@@ -0,0 +1,430 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agents, companies, companyMemberships, createDb, heartbeatRuns, issues, issueThreadInteractions,
toolAccessAuditEvents, toolActionRequests, toolCatalogEntries, toolInvocations,
} from "@paperclipai/db";
import {
GOOGLE_WORKSPACE_DEFAULT_SELECTION, GOOGLE_WORKSPACE_TOOL_TRANSPORT, googleWorkspaceServiceToolNames,
type GoogleWorkspaceService, type GoogleWorkspaceToolTransport,
} from "@paperclipai/shared";
import * as restDispatch from "../services/google-workspace-rest-dispatch.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import { forgetMcpHttpSessions, MCP_MODERN_PROTOCOL_VERSION } from "../services/mcp-http.js";
import { toolAccessService } from "../services/tool-access.js";
import { createToolGatewayService } from "../services/tool-gateway.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { initializeRunIdentity } from "../services/run-identity.js";
import type { PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
vi.mock("../services/google-sign-in-availability.js", () => ({ paperclipGoogleSignInAvailable: () => true }));
vi.mock("../services/google-workspace-rest-dispatch.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../services/google-workspace-rest-dispatch.js")>();
return {
...actual,
callGoogleWorkspaceRest: vi.fn(actual.callGoogleWorkspaceRest),
probeGoogleWorkspaceRest: vi.fn(actual.probeGoogleWorkspaceRest),
};
});
const scope = (value: string) => `https://www.googleapis.com/auth/${value}`;
const LAUNCH_SERVICES = ["gmail", "drive", "docs", "sheets", "slides", "calendar"] as const;
const HOSTS: Record<(typeof LAUNCH_SERVICES)[number], string> = {
gmail: "gmailmcp.googleapis.com", drive: "drivemcp.googleapis.com", docs: "docsmcp.googleapis.com",
sheets: "sheetsmcp.googleapis.com", slides: "slidesmcp.googleapis.com", calendar: "calendarmcp.googleapis.com",
};
const FORBIDDEN: Record<string, string[]> = {
"gmailmcp.googleapis.com": ["send_message", "send_draft", "unlabel_thread", "modify_labels", "trash_message"],
"drivemcp.googleapis.com": ["delete_file", "trash_file", "share_file", "update_permissions"],
"calendarmcp.googleapis.com": ["delete_calendar"],
"docsmcp.googleapis.com": ["delete_doc"],
};
const SCHEMAS: Record<string, Record<string, unknown>> = {
get_message: { type: "object", properties: { messageId: { type: "string" }, messageFormat: { type: "string" } }, required: ["messageId"] },
list_threads: { type: "object", properties: { pageSize: { type: "integer" }, pageToken: { type: "string" }, query: { type: "string" }, labelIds: { type: "array", items: { type: "string" } } } },
create_draft: { type: "object", properties: { to: { type: "array", items: { type: "string" } }, subject: { type: "string" }, body: { type: "string" } } },
get_file_metadata: { type: "object", properties: { fileId: { type: "string" } }, required: ["fileId"] },
update_doc: {
type: "object",
properties: {
documentId: { type: "string" },
requests: { type: "array", items: { type: "object" } },
writeControl: { type: "object", additionalProperties: false, properties: { requiredRevisionId: { type: "string" }, targetRevisionId: { type: "string" } } },
},
required: ["documentId", "requests"],
},
update_presentation: { type: "object", properties: { presentationId: { type: "string" }, requests: { type: "array", items: { type: "object" } } } },
};
const DEFAULT_PERMISSIONS = ["gmail.readonly", "gmail.compose", "drive.readonly", "drive.file", "documents.readonly", "documents",
"spreadsheets.readonly", "spreadsheets", "presentations.readonly", "presentations", "calendar.calendarlist.readonly", "calendar.events",
"calendar.events.freebusy"];
const READ_ONLY_PERMISSIONS = ["gmail.readonly", "drive.readonly", "documents.readonly", "spreadsheets.readonly", "presentations.readonly",
"calendar.calendarlist.readonly", "calendar.events.freebusy", "calendar.events.readonly"];
const allowlisted = (keep: (name: string) => boolean = () => true) => LAUNCH_SERVICES
.flatMap((service) => googleWorkspaceServiceToolNames(service).map((name) => `${service}__${name}`)).filter(keep).sort();
const names = (catalog: Array<{ toolName: string }>) => catalog.map((entry) => entry.toolName).sort();
type Confirmation = "none" | "legacy" | "modern";
interface Recorded { host: string; method: string; name?: string; body: Record<string, any> }
function fakeGoogle(options: { confirm?: Confirmation } = {}) {
const requests: Recorded[] = [];
const replies: Array<Record<string, any>> = [];
const waiting = new Map<string, (reply: Record<string, any>) => void>();
const restHosts: string[] = [];
let sessions = 0;
let asks = 0;
const sse = (message: unknown) => new TextEncoder().encode(`data: ${JSON.stringify(message)}\n\n`);
const confirmation = { message: "Apply 2 edits to the document \"Plan\"?", requestedSchema: { type: "object", properties: {} } };
const outcome = (accepted: boolean) => accepted
? { content: [{ type: "text", text: "Applied 2 edits." }] }
: { isError: true, content: [{ type: "text", text: "The user did not confirm the edit. Nothing was changed." }] };
const handle = async (href: string, init: RequestInit): Promise<Response> => {
const url = new URL(href);
if (!url.hostname.endsWith("mcp.googleapis.com")) {
restHosts.push(`${url.hostname}${url.pathname}`);
if (url.pathname === "/gmail/v1/users/me/profile") return Response.json({ emailAddress: "owner@example.test" });
if (url.pathname === "/gmail/v1/users/me/messages/msg1") {
return Response.json({ id: "msg1", threadId: "t1", payload: { mimeType: "text/plain", headers: [], body: { size: 2, data: "aGk" } } });
}
return Response.json({ error: { code: 404, message: "Not found" } }, { status: 404 });
}
const body = JSON.parse(String(init.body));
const headers = new Headers(init.headers);
requests.push({ host: url.hostname, method: body.method ?? "(reply)", name: body.params?.name, body });
if (body.method === "server/discover" && options.confirm === "modern") {
return Response.json({ jsonrpc: "2.0", id: body.id, result: { supportedVersions: [MCP_MODERN_PROTOCOL_VERSION], capabilities: { tools: {} } } });
}
if (body.method === "initialize") {
return Response.json({ jsonrpc: "2.0", id: body.id, result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "google-fixture", version: "1" } } },
{ headers: { "Mcp-Session-Id": `google-${++sessions}` } });
}
if (options.confirm === "legacy" && !headers.get("mcp-session-id")) {
return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32000, message: "Bad Request: No valid session ID provided" } }, { status: 400 });
}
if (body.method === "notifications/initialized") return new Response(null, { status: 202 });
if (!body.method && body.id) {
replies.push(body);
waiting.get(String(body.id))?.(body);
return new Response(null, { status: 202 });
}
if (body.method === "tools/list") {
const service = (Object.keys(HOSTS) as Array<keyof typeof HOSTS>).find((key) => HOSTS[key] === url.hostname)!;
const tools = [...googleWorkspaceServiceToolNames(service), ...(FORBIDDEN[url.hostname] ?? [])].map((name) => ({
name, description: `Google's ${name}.`, inputSchema: SCHEMAS[name] ?? { type: "object" },
annotations: { readOnlyHint: /^(get|list|search|read|download|suggest)_/.test(name) },
}));
return Response.json({ jsonrpc: "2.0", id: body.id, result: { tools } });
}
if (body.method !== "tools/call") return Response.json({ jsonrpc: "2.0", id: body.id, error: { code: -32601, message: "Method not found" } });
const asksConfirmation = body.params.name === "update_doc" && options.confirm && options.confirm !== "none";
if (asksConfirmation && options.confirm === "modern") {
const answer = body.params.inputResponses?.confirm;
if (!answer) {
return Response.json({ jsonrpc: "2.0", id: body.id, result: { resultType: "input_required", requestState: "edit-1",
inputRequests: { confirm: { method: "elicitation/create", params: { mode: "form", ...confirmation } } } } });
}
return Response.json({ jsonrpc: "2.0", id: body.id, result: outcome(answer.action === "accept") });
}
if (asksConfirmation) {
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
const askId = `ask-${++asks}`;
const reply = new Promise<Record<string, any>>((resolve) => waiting.set(askId, resolve));
controller.enqueue(sse({ jsonrpc: "2.0", id: askId, method: "elicitation/create", params: confirmation }));
const answer = await reply;
controller.enqueue(sse({ jsonrpc: "2.0", id: body.id, result: outcome(answer.result?.action === "accept") }));
controller.close();
},
});
return new Response(stream, { headers: { "content-type": "text/event-stream" } });
}
if (body.params.name === "get_event") {
const eventId = String(body.params.arguments?.eventId ?? "");
if (eventId === "missing") return Response.json({ jsonrpc: "2.0", id: body.id, result: { isError: true, content: [{ type: "text", text: "Not found" }] } });
const event = eventId === "series1" ? { id: eventId, summary: "Standup", recurrence: ["RRULE:FREQ=WEEKLY"] }
: eventId.startsWith("series1_") ? { id: eventId, summary: "Standup", recurringEventId: "series1" }
: { id: eventId, summary: "Lunch" };
return Response.json({ jsonrpc: "2.0", id: body.id, result: { content: [{ type: "text", text: JSON.stringify(event) }], structuredContent: event } });
}
return Response.json({ jsonrpc: "2.0", id: body.id, result: { content: [{ type: "text", text: `ok from Google MCP ${body.params.name}` }] } });
};
return {
handle, requests, replies, restHosts,
calls: () => requests.filter((request) => request.method === "tools/call").map((request) => `${request.host} ${request.name}`),
edits: () => replies.filter((reply) => reply.result?.action === "accept").length,
};
}
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("Google Workspace tools on Google's MCP servers", () => {
let db: ReturnType<typeof createDb>;
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
const savedTransport = { ...GOOGLE_WORKSPACE_TOOL_TRANSPORT };
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-google-mcp-transport-");
db = createDb(database.connectionString);
await instanceSettingsService(db).updateExperimental({ enableGoogleWorkspaceConnector: true });
}, 90_000);
afterAll(async () => {
await database?.cleanup();
});
afterEach(() => {
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport);
vi.mocked(restDispatch.callGoogleWorkspaceRest).mockClear();
vi.mocked(restDispatch.probeGoogleWorkspaceRest).mockClear();
});
function useTransport(transport: GoogleWorkspaceToolTransport) {
for (const service of LAUNCH_SERVICES) GOOGLE_WORKSPACE_TOOL_TRANSPORT[service as GoogleWorkspaceService] = transport;
}
async function connectWorkspace(options: { permissions?: string[]; askFirst?: string[]; off?: string[]; confirm?: Confirmation } = {}) {
const google = fakeGoogle({ confirm: options.confirm });
const permissions = (options.permissions ?? DEFAULT_PERMISSIONS).map(scope);
const [company] = await db.insert(companies).values({ name: `Google MCP ${randomUUID()}`, issuePrefix: `GM${randomUUID().slice(0, 6).toUpperCase()}` }).returning();
const userId = `google-mcp-${randomUUID()}`;
await db.insert(companyMemberships).values({ companyId: company!.id, principalType: "user", principalId: userId, status: "active", membershipRole: "owner" });
const actor = { actorType: "user" as const, actorId: userId };
const credentials = () => ({
v: 1 as const, accessToken: "workspace-access", refreshToken: "workspace-refresh", tokenType: "Bearer",
accessTokenExpiresAt: new Date(Date.now() + 86_400_000).toISOString(), refreshTokenExpiresAt: null, scopes: permissions,
subject: userId, companyId: company!.id, instanceId: "test-instance", environment: "development" as const,
provider: "google" as const, profile: "workspace.all" as const,
});
const connector = {
getCapabilities: vi.fn(async () => ["workspace.all"]),
startAuthorization: vi.fn(async ({ returnState }: { returnState: string }) => ({
authorizationUrl: `https://accounts.google.com/o/oauth2/v2/auth?state=${encodeURIComponent(returnState)}`,
expiresAt: new Date(Date.now() + 600_000).toISOString(),
})),
claim: vi.fn(async () => credentials()),
refresh: vi.fn(async () => credentials()),
revoke: vi.fn(async () => undefined),
} as unknown as PaperclipCloudConnector;
const remoteHttpRequest = vi.fn(google.handle);
const service = toolAccessService(db, {
paperclipCloudConnector: connector,
remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }],
remoteHttpRequest,
});
const connected = await service.connectGalleryApp(company!.id, {
galleryKey: "google-workspace", grantKind: "organization", connectionMethodKey: "paperclip-workspace",
}, actor);
const started = await service.startOAuth(company!.id, connected.connectionId, {
redirectUri: "https://paperclip.example/api/tools/oauth/cloud-connector/callback", actor, workspaceServices: GOOGLE_WORKSPACE_DEFAULT_SELECTION,
});
const completed = await service.completePaperclipCloudConnectorCallback({
state: new URL(started.authorizationUrl).searchParams.get("state")!, claimId: "fixture", actor,
});
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: `Workspace ${randomUUID()}`, role: "engineer",
adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning();
await service.finishGalleryAppConnection(company!.id, connected.connectionId, {
enabledCatalogEntryIds: completed.catalog.filter((entry) => !options.off?.includes(entry.toolName)).map((entry) => entry.id),
askFirstCatalogEntryIds: completed.catalog.filter((entry) => options.askFirst?.includes(entry.toolName)).map((entry) => entry.id),
access: { agentIds: [agent!.id] },
}, actor);
const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Tidy the plan", status: "in_progress", assigneeAgentId: agent!.id }).returning();
const [run] = await db.insert(heartbeatRuns).values({ companyId: company!.id, agentId: agent!.id, invocationSource: "assignment",
status: "running", contextSnapshot: { issueId: issue!.id } }).returning();
await initializeRunIdentity(db, { companyId: company!.id, runId: run!.id, issueId: issue!.id, responsibleUserId: null, cause: "company_default" });
const gateway = createToolGatewayService(db, { toolActionSigningSecret: "google-mcp-signing", remoteHttpRequest, oauthGrantRefresher: service.refreshOAuthGrantCredentials });
const session = await gateway.createSession({ companyId: company!.id, agentId: agent!.id, runId: run!.id });
const listed = async () => (await gateway.listToolsForSession(session.token)).filter((tool) => tool.connectionId === connected.connectionId);
const toolNamed = async (name: string) => {
const tool = (await listed()).find((item) => item.upstreamToolName === name);
expect(tool, name).toBeTruthy();
return tool!;
};
const call = async (name: string, parameters: unknown) =>
gateway.executeTool({ sessionToken: session.token, tool: (await toolNamed(name)).name, parameters, timeoutMs: 5_000 });
const interactions = issueThreadInteractionService(db);
return {
company: company!, actor, agent: agent!, issue: issue!, service, gateway, connectionId: connected.connectionId, catalog: completed.catalog,
google, listed, toolNamed, call,
cards: () => db.select().from(issueThreadInteractions)
.where(and(eq(issueThreadInteractions.companyId, company!.id), eq(issueThreadInteractions.issueId, issue!.id))),
skip: (cardId: string) => interactions.skipInteraction({ id: issue!.id, companyId: company!.id }, cardId, {}, { userId }),
confirm: (cardId: string) => interactions.answerQuestions({ id: issue!.id, companyId: company!.id }, cardId,
{ answers: [{ questionId: "continue", optionIds: ["continue"] }] }, { userId }),
invocations: () => db.select().from(toolInvocations).where(eq(toolInvocations.companyId, company!.id)),
audit: (action: string) => db.select().from(toolAccessAuditEvents).where(and(eq(toolAccessAuditEvents.companyId, company!.id), eq(toolAccessAuditEvents.action, action))),
};
}
it("ships Gmail, Drive, Docs, Sheets, Slides and Calendar on Google's MCP servers", () => {
expect(Object.fromEntries(LAUNCH_SERVICES.map((service) => [service, GOOGLE_WORKSPACE_TOOL_TRANSPORT[service]])))
.toEqual(Object.fromEntries(LAUNCH_SERVICES.map((service) => [service, "google_mcp"])));
});
it("offers agents only the allowlisted actions, whatever Google's servers list", async () => {
const f = await connectWorkspace();
expect(names(f.catalog.filter((entry) => entry.status === "active"))).toEqual(allowlisted());
const offered = (await f.listed()).map((tool) => tool.upstreamToolName ?? "").sort();
expect(offered).toEqual(allowlisted());
for (const forbidden of Object.values(FORBIDDEN).flat()) expect(offered.some((name) => name.endsWith(`__${forbidden}`))).toBe(false);
expect(offered.some((name) => /^(chat|people|search)__/.test(name))).toBe(false);
expect(f.google.calls()).toEqual([]);
expect(f.google.restHosts).toEqual([]);
expect(restDispatch.probeGoogleWorkspaceRest).not.toHaveBeenCalled();
});
it("discovers a read-only grant with tools/list only, from the granted services, and offers only reads", async () => {
const f = await connectWorkspace({ permissions: READ_ONLY_PERMISSIONS });
const writes = new Set(["gmail__create_draft", "drive__create_file", "drive__copy_file", "docs__update_doc", "sheets__update_spreadsheet",
"sheets__update_values", "sheets__update_formulas", "sheets__insert_dimension", "slides__update_presentation",
"calendar__create_event", "calendar__update_event", "calendar__delete_event", "calendar__respond_to_event"]);
expect(names(f.catalog)).toEqual(allowlisted((name) => !writes.has(name)));
expect(f.catalog.every((entry) => entry.riskLevel === "read")).toBe(true);
const listing = new Set(["server/discover", "initialize", "notifications/initialized", "tools/list"]);
expect(f.google.requests.filter((request) => !listing.has(request.method))).toEqual([]);
expect(f.google.calls()).toEqual([]);
const gmailOnly = await connectWorkspace({ permissions: ["gmail.readonly"] });
expect(new Set(gmailOnly.google.requests.map((request) => request.host))).toEqual(new Set(["gmailmcp.googleapis.com"]));
expect(gmailOnly.google.calls()).toEqual([]);
});
it("keeps readable action names, Off, Ask first and the activity log for MCP calls", async () => {
const f = await connectWorkspace({ askFirst: ["gmail__create_draft"], off: ["gmail__search_threads"] });
const read = await f.toolNamed("gmail__get_message");
expect(read.displayName).toBe("Gmail: Read a message");
expect(f.catalog.find((entry) => entry.toolName === "docs__update_doc")?.title).toBe("Docs: Edit a document");
expect((await f.listed()).map((tool) => tool.upstreamToolName)).not.toContain("gmail__search_threads");
await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" });
expect(f.google.calls()).toEqual(["gmailmcp.googleapis.com get_message"]);
const [completed] = await f.audit("call_completed");
expect(JSON.stringify(completed)).toContain("https://gmailmcp.googleapis.com/mcp/v1");
expect(JSON.stringify(completed)).not.toContain("workspace-access");
const draft = { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." };
await expect(f.call("gmail__create_draft", draft)).rejects.toMatchObject({ reasonCode: "approval_required" });
expect(f.google.calls()).toEqual(["gmailmcp.googleapis.com get_message"]);
const [action] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, f.company.id));
await expect(f.gateway.approveActionRequest({ companyId: f.company.id, actionRequestId: action!.id, actor: { userId: f.actor.actorId } }))
.resolves.toMatchObject({ status: "executed" });
expect(f.google.calls()).toEqual(["gmailmcp.googleapis.com get_message", "gmailmcp.googleapis.com create_draft"]);
expect(restDispatch.callGoogleWorkspaceRest).not.toHaveBeenCalled();
});
describe("argument checks before anything is sent to Google", () => {
it.each([
["an argument the tool does not list", "gmail__list_threads", { q: "subject:marker-123" }, "unknown argument \"q\". Accepted arguments: query, labelIds, pageSize, pageToken."],
["an unknown field in a closed structured argument", "docs__update_doc",
{ documentId: "doc1", requests: [{ insertText: { text: "Hi", location: { index: 1 } } }], writeControl: { revision: "r1" } }, "unknown argument \"revision\" in writeControl."],
["a list of Drive file IDs", "drive__get_file_metadata", { fileId: "file1,file2" }, "fileId must be one Google file ID"],
["a Drive link in place of a file ID", "drive__get_file_metadata", { fileId: "https://drive.google.com/file/d/file1/view" }, "fileId must be one Google file ID"],
["a Docs edit that reads another file", "docs__update_doc",
{ documentId: "doc1", requests: [{ insertRichLink: { uri: "https://docs.google.com/document/d/other", location: { index: 1 } } }] }, "insertRichLink inserts a smart chip"],
["a Docs image from a Drive link", "docs__update_doc",
{ documentId: "doc1", requests: [{ insertInlineImage: { uri: "https://drive.google.com/uc?id=secret", location: { index: 1 } } }] }, "takes its picture from a Google Drive or Docs link"],
["a Docs request kind not on the closed list", "docs__update_doc",
{ documentId: "doc1", requests: [{ futureKind: {} }] }, "futureKind is not a request kind this tool accepts"],
["a Slides import from another presentation", "slides__update_presentation",
{ presentationId: "deck1", requests: [{ importSlides: { presentationId: "other" } }] }, "importSlides copies slides from another presentation"],
])("refuses %s", async (_label, tool, parameters, reason) => {
const f = await connectWorkspace();
await expect(f.call(tool, parameters)).rejects.toMatchObject({ status: 502, reasonCode: "tool_error", message: expect.stringContaining(reason) });
expect(f.google.calls()).toEqual([]);
const failed = (await f.invocations()).filter((invocation) => invocation.status === "failed");
expect(failed).toEqual([expect.objectContaining({ errorCode: "tool_error", errorMessage: expect.stringContaining("Nothing was sent to Google.") })]);
const audit = await f.audit("call_failed");
expect(audit).toHaveLength(1);
expect(JSON.stringify(audit[0])).toContain("\"dispatched\":false");
});
it("reads the event first and refuses to delete a whole recurring series", async () => {
const f = await connectWorkspace();
await expect(f.call("calendar__delete_event", { calendarId: "primary", eventId: "series1" })).rejects.toMatchObject({
status: 502, reasonCode: "tool_error", message: expect.stringContaining("This ID is a whole recurring series"),
});
await expect(f.call("calendar__delete_event", { calendarId: "primary", eventId: "missing" })).rejects.toMatchObject({
status: 502, reasonCode: "tool_error", message: expect.stringContaining("Nothing was deleted."),
});
expect(f.google.calls()).toEqual(["calendarmcp.googleapis.com get_event", "calendarmcp.googleapis.com get_event"]);
const audit = await f.audit("call_failed");
expect(audit).toHaveLength(2);
expect(JSON.stringify(audit)).toContain("\"dispatched\":false");
await expect(f.call("calendar__delete_event", { calendarId: "primary", eventId: "series1_20261124T100000Z" })).resolves.toMatchObject({ status: "completed" });
await expect(f.call("calendar__delete_event", { eventId: "lunch1" })).resolves.toMatchObject({ status: "completed" });
expect(f.google.calls().slice(2)).toEqual(["calendarmcp.googleapis.com get_event", "calendarmcp.googleapis.com delete_event",
"calendarmcp.googleapis.com get_event", "calendarmcp.googleapis.com delete_event"]);
expect(f.google.requests.filter((request) => request.name === "get_event").map((request) => request.body.params.arguments))
.toEqual([{ calendarId: "primary", eventId: "series1" }, { calendarId: "primary", eventId: "missing" },
{ calendarId: "primary", eventId: "series1_20261124T100000Z" }, { eventId: "lunch1" }]);
});
it("sends a valid edit and a public image link unchanged", async () => {
const f = await connectWorkspace();
const edit = { documentId: "doc1", requests: [{ insertInlineImage: { uri: "https://example.test/logo.png", location: { index: 1 } } }],
writeControl: { requiredRevisionId: "rev-1" } };
await expect(f.call("docs__update_doc", edit)).resolves.toMatchObject({ status: "completed" });
await expect(f.call("drive__get_file_metadata", { fileId: "file_1-A" })).resolves.toMatchObject({ status: "completed" });
expect(f.google.calls()).toEqual(["docsmcp.googleapis.com update_doc", "drivemcp.googleapis.com get_file_metadata"]);
expect(f.google.requests.find((request) => request.name === "update_doc")!.body.params.arguments).toEqual(edit);
});
});
describe.each(["legacy", "modern"] as const)("a confirmation Google's %s server asks for", (confirm) => {
const edit = { documentId: "doc1", requests: [{ insertText: { text: "Hi", location: { index: 1 } } }, { insertText: { text: "There", location: { index: 3 } } }] };
it("reaches a person on a question card, and a declined confirmation fails cleanly with nothing changed", async () => {
const f = await connectWorkspace({ confirm });
await expect(f.call("docs__update_doc", edit)).rejects.toMatchObject({ reasonCode: "elicitation_required" });
const [card] = await f.cards();
expect(card).toMatchObject({ kind: "ask_user_questions", status: "pending", requestedResolverPolicy: "human_only" });
expect(card!.payload).toMatchObject({ questionSet: { description: "Apply 2 edits to the document \"Plan\"?" } });
expect(f.google.edits()).toBe(0);
await expect(f.call("docs__update_doc", edit)).rejects.toMatchObject({ reasonCode: "elicitation_required" });
expect(await f.cards()).toHaveLength(1);
expect(f.google.edits()).toBe(0);
await f.skip(card!.id);
await expect(f.call("docs__update_doc", edit)).rejects.toMatchObject({ status: 502, reasonCode: "tool_error",
message: expect.stringContaining("did not confirm the edit") });
expect(f.google.edits()).toBe(0);
const responses = confirm === "legacy"
? f.google.replies.map((reply) => reply.result.action)
: f.google.requests.filter((request) => request.body.params?.inputResponses).map((request) => request.body.params.inputResponses.confirm.action);
expect(responses.at(-1)).toBe("decline");
expect(responses).not.toContain("accept");
});
it("completes the edit once the person confirms", async () => {
const f = await connectWorkspace({ confirm });
await expect(f.call("docs__update_doc", edit)).rejects.toMatchObject({ reasonCode: "elicitation_required" });
const [card] = await f.cards();
await f.confirm(card!.id);
await expect(f.call("docs__update_doc", edit)).resolves.toMatchObject({ status: "completed" });
});
});
it("moves a connection saved on REST back to Google's MCP servers with no action held for review, keeping Off and Ask first", async () => {
useTransport("paperclip_rest");
const f = await connectWorkspace({ permissions: ["gmail.readonly", "gmail.compose", "documents.readonly"],
off: ["gmail__search_threads"], askFirst: ["gmail__create_draft"] });
expect(f.google.restHosts).toContain("gmail.googleapis.com/gmail/v1/users/me/profile");
useTransport("google_mcp");
forgetMcpHttpSessions(f.connectionId);
const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor);
expect(refreshed.catalog.filter((entry) => entry.status !== "active")).toEqual([]);
const saved = await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.connectionId, f.connectionId));
expect(saved.find((entry) => entry.toolName === "gmail__get_message")?.inputSchema).toEqual(SCHEMAS.get_message);
const offered = (await f.listed()).map((tool) => tool.upstreamToolName);
expect(offered).toContain("gmail__get_message");
expect(offered).not.toContain("gmail__search_threads");
await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" });
expect(f.google.calls()).toEqual(["gmailmcp.googleapis.com get_message"]);
await expect(f.call("gmail__create_draft", { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." }))
.rejects.toMatchObject({ reasonCode: "approval_required" });
});
});
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { and, eq, inArray } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import {
agents, companies, companyMemberships, connectionGrants, createDb, heartbeatRuns, issues,
toolAccessAuditEvents, toolActionRequests, toolCallEvents, toolCatalogEntries, toolInvocations,
@@ -84,6 +84,10 @@ const GOOGLE_MCP_SCHEMAS: Record<string, Record<string, unknown>> = {
},
required: ["documentId", "requests"],
},
create_draft: {
type: "object",
properties: { to: { type: "array", items: { type: "string" } }, subject: { type: "string" }, body: { type: "string" } },
},
get_message: {
type: "object",
properties: { messageId: { type: "string" }, messageFormat: { type: "string", enum: ["MINIMAL", "FULL_CONTENT", "METADATA_ONLY"] } },
@@ -96,6 +100,14 @@ const support = await getEmbeddedPostgresTestSupport();
let db: ReturnType<typeof createDb>;
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
const savedTransport = { ...GOOGLE_WORKSPACE_TOOL_TRANSPORT };
const REST_TRANSPORT: Record<GoogleWorkspaceService, GoogleWorkspaceToolTransport> = {
...savedTransport, gmail: "paperclip_rest", drive: "paperclip_rest", docs: "paperclip_rest",
sheets: "paperclip_rest", slides: "paperclip_rest", calendar: "paperclip_rest",
};
beforeEach(() => {
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, REST_TRANSPORT);
});
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-google-rest-transport-");
@@ -503,10 +515,11 @@ const support = await getEmbeddedPostgresTestSupport();
["calendar__create_event", { summary: "Planning", startTime: "2026-11-24T10:00:00Z", endTime: "2026-11-24T10:30:00Z", timeZone: "UTC" }, "www.googleapis.com POST /calendar/v3/calendars/primary/events"],
];
it("puts exactly the six launch services on paperclip_rest and leaves the rest on google_mcp", () => {
it("ships every service on google_mcp, and the REST fallback still covers the six launch services", () => {
expect(Object.values(savedTransport).every((transport) => transport === "google_mcp")).toBe(true);
expect(Object.entries(GOOGLE_WORKSPACE_TOOL_TRANSPORT).filter(([, transport]) => transport === "paperclip_rest").map(([service]) => service).sort())
.toEqual([...LAUNCH_SERVICES].sort());
expect(GOOGLE_WORKSPACE_TOOL_TRANSPORT).toMatchObject({ chat: "google_mcp", people: "google_mcp", search: "google_mcp" });
expect(restDispatch.googleWorkspaceRestTransportGaps(REST_TRANSPORT)).toEqual([]);
});
it("lists all 36 allowlisted actions for a full read & write grant without contacting a Google MCP server", async () => {
@@ -586,7 +599,7 @@ const support = await getEmbeddedPostgresTestSupport();
for (const service of LAUNCH_SERVICES) useTransport(service, "google_mcp");
const f = await connectWorkspace();
expect(names(f.catalog)).toEqual(["docs__read_doc", "gmail__create_draft", "gmail__get_message", "gmail__search_threads"]);
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport);
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, REST_TRANSPORT);
const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor);
expect(names(refreshed.catalog)).toEqual(gmailCatalog(true));
expect(refreshed.catalog.filter((entry) => entry.status !== "active")).toEqual([]);
@@ -603,7 +616,7 @@ const support = await getEmbeddedPostgresTestSupport();
expect(saved.inputSchema).toEqual(GOOGLE_MCP_SCHEMAS.update_doc);
const before = await f.toolNamed("docs__update_doc");
expect(before.parametersSchema).toMatchObject({ required: ["documentId", "requests"] });
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport);
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, REST_TRANSPORT);
f.restRequests.length = 0;
const refreshesBefore = f.mcpRequests.length;
@@ -667,7 +680,7 @@ const support = await getEmbeddedPostgresTestSupport();
.filter((tool) => tool.connectionId === f.connectionId).map((tool) => tool.upstreamToolName).sort();
expect(await listed()).toEqual(["docs__read_doc", "gmail__create_draft"]);
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport);
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, REST_TRANSPORT);
const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor);
expect(refreshed.catalog.find((entry) => entry.toolName === "gmail__get_message")).toMatchObject({ status: "active", quarantineReason: null });
expect(refreshed.catalog.filter((entry) => entry.status !== "active")).toEqual([]);
@@ -690,7 +703,7 @@ const support = await getEmbeddedPostgresTestSupport();
.filter((tool) => tool.connectionId === f.connectionId).map((tool) => tool.upstreamToolName).sort();
const draft = { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." };
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport);
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, REST_TRANSPORT);
expect(await listed()).toEqual(["docs__read_doc", "gmail__search_threads"]);
for (let refresh = 0; refresh < 2; refresh += 1) {
const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor);
@@ -3458,7 +3458,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
parameters: {},
})).rejects.toMatchObject({
reasonCode: "tool_error",
message: expect.stringContaining("enroll the signed-in Workspace account and this OAuth client's Google Cloud project"),
message: expect.stringContaining("accept only an OAuth client marked \"Use this client for an AI-powered agent\""),
});
});
@@ -17,13 +17,22 @@ all eight allowlisted Drive tools (see "Drive tools" below), both Docs tools
and both Slides tools (see "Docs and Slides tools" below), and all six
allowlisted Sheets tools (see "Sheets tools" below).
## Why this exists, and why it is temporary
## Why this exists, and why it is the fallback now
Google's Workspace MCP servers are a Developer Preview and cannot be offered to
the public. On 2026-11-17 the owner decided that Paperclip will launch on its
own tools over the REST APIs. The tools are built so Paperclip can switch to
Google's MCP servers later without a rewrite, and they live in this one folder
so they can be deleted cleanly when that happens.
On 2026-11-17 Google's Workspace MCP servers were a Developer Preview and could
not be offered to the public, so the owner decided that Paperclip would launch
on its own tools over the REST APIs. All six services ran on this folder from
2026-11-23 to 2026-11-24.
On 2026-11-24 Google made its Workspace MCP servers generally available and
published the Workspace AI Tools Addendum
(<https://workspace.google.com/terms/ai-tools>): a tool that is, or is driven
by, an AI agent must use a Google MCP, not the REST APIs. The owner decided the
same day to switch all six services back to Google's MCP servers. This folder
and the switch stay in the code as the fallback; do not delete them.
`argument-guards.ts` is the one part of this folder that also runs on the
`google_mcp` path (see "Argument checks on Google's MCP path").
## Boundary rules
@@ -155,10 +164,12 @@ deployment is ever needed; the gateway does not use it.
One setting per service, `GOOGLE_WORKSPACE_TOOL_TRANSPORT` in
`packages/shared/src/google-workspace-connectors.ts`:
- `paperclip_rest`: calls go to this folder. Gmail, Drive, Docs, Sheets,
Slides and Calendar use it since 2026-11-23.
- `google_mcp`: calls go to Google's hosted MCP server for that service.
Chat, People and Search use it; they are not offered for new setup.
Every service uses it since 2026-11-24. Chat, People and Search are not
offered for new setup.
- `paperclip_rest`: calls go to this folder. Gmail, Drive, Docs, Sheets,
Slides and Calendar used it from 2026-11-23 to 2026-11-24. It is the
fallback.
`googleWorkspaceToolTarget(name)` returns the setting as `transport`. It is a
plain constant: no environment variable, instance setting or database row.
@@ -219,6 +230,49 @@ plain constant: no environment variable, instance setting or database row.
the others stay usable. Health checks use the same branch.
MCP Tasks, MCP resources and elicitation only exist on the `google_mcp` path.
Google's MCP servers ask a person to confirm some actions (MCP elicitation).
The gateway puts the question on the task's question card, as for any MCP
server (`server/src/services/mcp-elicitation.ts`); skipping the card sends
"decline". `server/src/__tests__/google-workspace-mcp-transport.test.ts`
covers this with a fake Google server, for a server that asks over a session
stream and for a stateless one.
### Argument checks on Google's MCP path
Before the gateway sends a call to Google's MCP server for Gmail, Drive,
Docs, Sheets, Slides or Calendar, it runs `googleWorkspaceArgumentRefusal`
(`argument-guards.ts`, through `googleWorkspaceMcpPreflightRefusal` in the
adapter). A refusal is a tool error that ends with "Nothing was sent to
Google.", recorded and audited like a REST refusal. It checks only what an
argument shows, with no request to Google:
- An argument that the action's saved schema does not list. The top level is
always checked; a nested object only when its schema has
`additionalProperties: false`. A schema with `additionalProperties` open at
the top level, or with neither `properties` nor `additionalProperties:
false`, is not checked.
- `fileId` and `parentId` (Drive), `documentId`, `spreadsheetId` and
`presentationId` must each be one file ID: no link, no list.
- Docs `update_doc` and Slides `update_presentation`: each request names
exactly one kind, and the kind is on the closed list in
`docs/request-kinds.ts` or `slides/request-kinds.ts` (so kinds that read
another file, and images from Drive or Docs links, are refused).
For Calendar `delete_event`, `googleWorkspaceMcpPreflightRefusal` in the
adapter first reads the event with the connection's own `calendar__get_event`
(only `calendarId` and `eventId`), through a callback the gateway passes, and
gives the answer to `googleCalendarSeriesRefusal`. The gateway only looks up
and runs that action, with the grant and scope checks, inside the delete's
own deadline. The read action's Off or Ask first setting does not apply: the
read is part of a delete that the policy already allowed, and its answer never
reaches the agent. The REST `delete_event` makes the same read. A whole recurring series is
refused, as on REST. If the read does not return the event, nothing is
deleted.
The REST tools' other checks describe a REST limit or a stricter REST rule, so
they do not run on MCP: mandatory `requiredRevisionId`, the Sheets comment and
data-source refusals, the result size budget, and the Drive search query
rules.
Measured with a stubbed fetch, the adapter adds about 15 µs per call. A full
`gmail__get_message` through `executeTool` (policy, records, screening) took a
@@ -274,6 +328,20 @@ that JSON escapes, and non-ASCII characters, count more):
The check costs one `JSON.stringify` of the result: about 5 µs for a 4 KB
result and 0.24 ms for a 700 KB one.
### Connections saved on REST, after the switch back
A connection whose catalog was refreshed while its services were on
`paperclip_rest` has this folder's definitions saved. After the switch back,
agents see those saved definitions until the next catalog refresh, and the
argument checks use them. That refresh saves Google's definitions. It does not
hold an action for review when the saved row is this folder's definition
(`formerPaperclipDefinedTool` in
`server/src/services/connectors/paperclip-defined-tools.ts` and the hold rule
in `server/src/services/tool-access/catalog/publication.ts`), and it keeps Off
and Ask first. An action that Google's server does not list (for example Gmail
`get_draft`, `list_threads` or `search_messages`, if Google does not have
them) is removed by that refresh.
### Flipping a service
1. Implement every tool in that service's allowlist (`toolScopes` in the
@@ -1176,9 +1244,10 @@ says `false`.
## Open questions
- Whether an OAuth client marked as an AI-powered agent may call the REST APIs.
The AI Tools Addendum says an agent must use a Google MCP, so the fallback
is for an outage or a Google problem, not for normal use.
- Each Google Cloud project behind a connection needs the REST APIs enabled
(Gmail now; Drive, Docs, Sheets, Slides and Calendar as their tools land).
Without that, calls return the `api_disabled` tool error.
for the fallback. Without that, calls return the `api_disabled` tool error.
- `freeBusy.query` does not accept `calendar.events`, and the read & write
Calendar selection grants `calendar.calendarlist.readonly` and
`calendar.events` only (the `calendar.events` → `calendar.events.freebusy`
@@ -1193,7 +1262,12 @@ says `false`.
## Removal procedure
1. Set every service in `GOOGLE_WORKSPACE_TOOL_TRANSPORT` to `google_mcp`.
The owner decided on 2026-11-24 to keep this folder as the fallback. Remove it
only on a new decision.
1. Check that every service in `GOOGLE_WORKSPACE_TOOL_TRANSPORT` is
`google_mcp`. Move `argument-guards.ts` and the request-kind lists it uses
out of this folder first, because the MCP path uses them.
2. Delete this folder, `server/src/google-workspace-rest-tools/`.
3. Delete `server/src/services/google-workspace-rest-dispatch.ts` and its
test, and the two call sites: the `paperclip_rest` branch in
@@ -0,0 +1,71 @@
import { describe, expect, it } from "vitest";
import { googleCalendarSeriesRefusal, googleWorkspaceArgumentRefusal } from "./argument-guards.js";
const schema = {
type: "object",
properties: {
fileId: { type: "string" },
options: { type: "object", properties: { fields: { type: "string" } } },
closed: { type: "object", additionalProperties: false, properties: { fields: { type: "string" } } },
},
};
describe("googleWorkspaceArgumentRefusal", () => {
it("refuses an unknown top-level argument and names the accepted ones", () => {
expect(googleWorkspaceArgumentRefusal({ service: "drive", toolName: "get_file_metadata", arguments: { fileId: "f1", fields: "*" }, inputSchema: schema }))
.toBe("Invalid arguments for get_file_metadata: unknown argument \"fields\". Accepted arguments: fileId, options, closed. Nothing was sent to Google.");
});
it("checks a nested object only when its schema closes it", () => {
expect(googleWorkspaceArgumentRefusal({ service: "drive", toolName: "get_file_metadata", arguments: { fileId: "f1", options: { extra: 1 } }, inputSchema: schema })).toBeNull();
expect(googleWorkspaceArgumentRefusal({ service: "drive", toolName: "get_file_metadata", arguments: { fileId: "f1", closed: { extra: 1 } }, inputSchema: schema }))
.toContain("unknown argument \"extra\" in closed.");
});
it("checks a closed object below an open one", () => {
const nested = { type: "object", properties: { options: { type: "object", properties: {
filter: { type: "object", additionalProperties: false, properties: { label: { type: "string" } } },
} } } };
expect(googleWorkspaceArgumentRefusal({ service: "gmail", toolName: "list_threads", arguments: { options: { other: 1, filter: { label: "a", color: "red" } } }, inputSchema: nested }))
.toBe("Invalid arguments for list_threads: unknown argument \"color\" in options.filter. Accepted in options.filter: label. Nothing was sent to Google.");
});
it("refuses every argument for a closed schema that lists none", () => {
expect(googleWorkspaceArgumentRefusal({ service: "calendar", toolName: "list_calendars", arguments: { pageSize: 5 }, inputSchema: { type: "object", additionalProperties: false } }))
.toBe("Invalid arguments for list_calendars: unknown argument \"pageSize\". Accepted arguments: none. Nothing was sent to Google.");
});
it("leaves a schema that allows more arguments, or lists none, to the server", () => {
expect(googleWorkspaceArgumentRefusal({ service: "gmail", toolName: "get_message", arguments: { any: 1 }, inputSchema: { type: "object", properties: {}, additionalProperties: true } })).toBeNull();
expect(googleWorkspaceArgumentRefusal({ service: "gmail", toolName: "get_message", arguments: { any: 1 }, inputSchema: { type: "object" } })).toBeNull();
});
it("requires one file ID for Drive, Docs, Sheets and Slides, and leaves Gmail and Calendar IDs alone", () => {
expect(googleWorkspaceArgumentRefusal({ service: "sheets", toolName: "get_values", arguments: { spreadsheetId: "a b" }, inputSchema: {} }))
.toContain("spreadsheetId must be one Google file ID");
expect(googleWorkspaceArgumentRefusal({ service: "calendar", toolName: "get_event", arguments: { eventId: "a b" }, inputSchema: {} })).toBeNull();
});
it("refuses Slides and Docs requests outside the closed lists, and requests with more than one kind", () => {
expect(googleWorkspaceArgumentRefusal({ service: "slides", toolName: "update_presentation",
arguments: { presentationId: "p1", requests: [{ createVideo: { source: "DRIVE", id: "v1" } }] }, inputSchema: {} }))
.toContain("a DRIVE video is another file");
expect(googleWorkspaceArgumentRefusal({ service: "docs", toolName: "update_doc",
arguments: { documentId: "d1", requests: [{ insertText: {}, deleteContentRange: {} }] }, inputSchema: {} }))
.toContain("each request names exactly one kind of update");
expect(googleWorkspaceArgumentRefusal({ service: "docs", toolName: "update_doc",
arguments: { documentId: "d1", requests: [{ insertText: { text: "Hi", location: { index: 1 } } }] }, inputSchema: {} })).toBeNull();
});
});
describe("googleCalendarSeriesRefusal", () => {
it("refuses a series, allows an occurrence or a single event, and refuses when the read shows no event", () => {
const read = (event: unknown, text: string | null = null) => ({ isError: false, structuredContent: event, text });
expect(googleCalendarSeriesRefusal(read({ id: "s1", recurrence: ["RRULE:FREQ=DAILY"] }))).toContain("whole recurring series");
expect(googleCalendarSeriesRefusal(read(null, JSON.stringify({ event: { id: "s1", recurrence: ["RRULE:FREQ=DAILY"] } })))).toContain("whole recurring series");
expect(googleCalendarSeriesRefusal(read({ id: "s1_20261124", recurrence: ["RRULE:FREQ=DAILY"], recurringEventId: "s1" }))).toBeNull();
expect(googleCalendarSeriesRefusal(read({ id: "e1", summary: "Lunch" }))).toBeNull();
expect(googleCalendarSeriesRefusal(read(null, "Event: Lunch"))).toContain("Nothing was deleted.");
expect(googleCalendarSeriesRefusal({ isError: true, structuredContent: { id: "e1" }, text: null })).toContain("Nothing was deleted.");
});
});
@@ -0,0 +1,96 @@
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 function googleWorkspaceArgumentRefusal(check: GoogleWorkspaceArgumentCheck): string | null {
const args = check.arguments ?? {};
if (!isRecord(args)) return refusal(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(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(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(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(check.toolName, error.message);
throw error;
}
}
return null;
}
function refusal(toolName: string, detail: string): string {
return `Invalid arguments for ${toolName}: ${detail} Nothing was sent to Google.`;
}
export interface GoogleCalendarEventRead {
isError: boolean;
structuredContent: unknown;
text: string | null;
}
const SERIES_REFUSAL = "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): string | null {
const event = read.isError ? null : eventFrom(read);
if (!event || (event.id === undefined && event.eventId === undefined && event.start === undefined)) {
return "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;
}
@@ -14,3 +14,9 @@ export {
export { createGoogleWorkspaceRestServer, type GoogleWorkspaceRestServerOptions } from "./server.js";
export { GOOGLE_AUTH_ERROR_CODE, GoogleWorkspaceAuthError, type GoogleAuthFailure } from "./errors.js";
export type { GoogleFetch } from "./google-http.js";
export {
googleCalendarSeriesRefusal,
googleWorkspaceArgumentRefusal,
type GoogleCalendarEventRead,
type GoogleWorkspaceArgumentCheck,
} from "./argument-guards.js";
+10 -7
View File
@@ -60,7 +60,7 @@ export function defineTool<Args>(spec: RestToolSpec<Args>): RestTool {
};
}
type JsonSchemaNode = Record<string, unknown>;
export type JsonSchemaNode = Record<string, unknown>;
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -98,14 +98,17 @@ export function closedObjectSchema(schema: unknown): unknown {
return copy;
}
function unknownArgumentProblems(value: unknown, schema: unknown, path: string): string[] {
export type ClosedObjectTest = (schema: JsonSchemaNode, path: string) => schema is JsonSchemaNode & { properties: Record<string, JsonSchemaNode> };
export function unknownArgumentProblems(value: unknown, schema: unknown, path: string, closed: ClosedObjectTest = isClosedObjectSchema): string[] {
if (!isRecord(schema)) return [];
if (Array.isArray(value)) {
return isRecord(schema.items) ? value.flatMap((item, index) => unknownArgumentProblems(item, schema.items, `${path}[${index}]`)) : [];
return isRecord(schema.items) ? value.flatMap((item, index) => unknownArgumentProblems(item, schema.items, `${path}[${index}]`, closed)) : [];
}
if (!isRecord(value) || !isClosedObjectSchema(schema)) return [];
const accepted = Object.keys(schema.properties);
const unknown = Object.keys(value).filter((key) => value[key] !== undefined && !Object.hasOwn(schema.properties, key));
if (!isRecord(value) || !isRecord(schema.properties)) return [];
const properties = schema.properties;
const accepted = Object.keys(properties);
const unknown = closed(schema, path) ? Object.keys(value).filter((key) => value[key] !== undefined && !Object.hasOwn(properties, key)) : [];
const problems: string[] = [];
if (unknown.length > 0) {
const names = unknown.map((key) => JSON.stringify(key)).join(", ");
@@ -114,7 +117,7 @@ function unknownArgumentProblems(value: unknown, schema: unknown, path: string):
problems.push(`unknown ${unknown.length === 1 ? "argument" : "arguments"} ${names}${where}. ${path ? `Accepted in ${path}` : "Accepted arguments"}: ${list}.`);
}
for (const key of accepted) {
if (value[key] !== undefined) problems.push(...unknownArgumentProblems(value[key], schema.properties[key], path ? `${path}.${key}` : key));
if (value[key] !== undefined) problems.push(...unknownArgumentProblems(value[key], properties[key], path ? `${path}.${key}` : key, closed));
}
return problems;
}
@@ -1,4 +1,4 @@
import { googleWorkspaceRestToolDefinition } from "../google-workspace-rest-dispatch.js";
import { googleWorkspaceRestFallbackDefinition, googleWorkspaceRestToolDefinition } from "../google-workspace-rest-dispatch.js";
import type { toolConnections } from "@paperclipai/db";
import { pluginConnectionMethod, pluginConnectionToolDefinition } from "../plugin-connector-runtime.js";
import { shouldQuarantineNewEntries } from "../tool-access/catalog/descriptors.js";
@@ -17,14 +17,23 @@ type Connection = { config: Record<string, unknown> };
const PAPERCLIP_DEFINED_TOOL_SOURCES: ReadonlyArray<{
matches: (connection: Connection) => boolean;
definition: (toolName: string) => PaperclipDefinedToolDefinition | null;
formerDefinition: (toolName: string) => PaperclipDefinedToolDefinition | null;
}> = [
{ matches: (connection) => connection.config.sourceTemplateKey === "google-workspace", definition: googleWorkspaceRestToolDefinition },
{
matches: (connection) => connection.config.sourceTemplateKey === "google-workspace",
definition: googleWorkspaceRestToolDefinition,
formerDefinition: googleWorkspaceRestFallbackDefinition,
},
];
export function paperclipDefinedTool(connection: Connection, toolName: string): PaperclipDefinedToolDefinition | null {
return PAPERCLIP_DEFINED_TOOL_SOURCES.find((source) => source.matches(connection))?.definition(toolName) ?? null;
}
export function formerPaperclipDefinedTool(connection: Connection, toolName: string): PaperclipDefinedToolDefinition | null {
return PAPERCLIP_DEFINED_TOOL_SOURCES.find((source) => source.matches(connection))?.formerDefinition(toolName) ?? null;
}
export function currentConnectionToolDefinition(connection: typeof toolConnections.$inferSelect, toolName: string): PaperclipDefinedToolDefinition | null {
const trusted = paperclipDefinedTool(connection, toolName);
if (trusted) return trusted;
@@ -1,9 +1,10 @@
import { GOOGLE_WORKSPACE_TOOL_TRANSPORT, googleWorkspaceServiceToolNames } from "@paperclipai/shared";
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import {
callGoogleWorkspaceRest,
googleWorkspaceRestToolDefinition,
googleWorkspaceCatalogToolTitle,
googleWorkspaceMcpPreflightRefusal,
googleWorkspaceRestTransportGaps,
listGoogleWorkspaceRest,
probeGoogleWorkspaceRest,
@@ -12,6 +13,8 @@ import {
describe("Google Workspace REST transport eligibility", () => {
it("switches no service to paperclip_rest unless the REST tools cover its whole allowlist", () => {
expect(googleWorkspaceRestTransportGaps()).toEqual([]);
expect(googleWorkspaceRestTransportGaps({ ...GOOGLE_WORKSPACE_TOOL_TRANSPORT, gmail: "paperclip_rest", drive: "paperclip_rest",
docs: "paperclip_rest", sheets: "paperclip_rest", slides: "paperclip_rest", calendar: "paperclip_rest" })).toEqual([]);
});
it("finds Gmail and Calendar fully implemented and Chat not", () => {
@@ -27,6 +30,9 @@ describe("Google Workspace REST transport eligibility", () => {
describe("googleWorkspaceRestToolDefinition", () => {
it("returns this folder's definition for a tool of a service on paperclip_rest, and nothing otherwise", () => {
const savedDocs = GOOGLE_WORKSPACE_TOOL_TRANSPORT.docs;
GOOGLE_WORKSPACE_TOOL_TRANSPORT.docs = "paperclip_rest";
onTestFinished(() => { GOOGLE_WORKSPACE_TOOL_TRANSPORT.docs = savedDocs; });
const rest = listGoogleWorkspaceRest("docs").find((tool) => tool.name === "update_doc")!;
expect(googleWorkspaceRestToolDefinition("docs__update_doc")).toEqual({ name: rest.name, title: "Docs: Edit a document", description: rest.description,
inputSchema: rest.inputSchema, outputSchema: rest.outputSchema, annotations: rest.annotations });
@@ -134,3 +140,28 @@ describe("probeGoogleWorkspaceRest", () => {
await expect(probe(403, { error: { errors: [{ reason: "accessNotConfigured" }] } })).resolves.toMatchObject({ ok: false, authFailure: null });
});
});
describe("googleWorkspaceMcpPreflightRefusal", () => {
const eventResult = (event: Record<string, unknown>) => ({ content: JSON.stringify(event), data: { isError: false, structuredContent: event } });
it("reads the event through the gateway's callback before a Calendar delete, and refuses a recurring series", async () => {
const callTool = vi.fn(async () => eventResult({ id: "s1", recurrence: ["RRULE:FREQ=WEEKLY"] }));
await expect(googleWorkspaceMcpPreflightRefusal({ toolName: "calendar__delete_event", arguments: { calendarId: "primary", eventId: "s1", sendUpdates: "none" },
inputSchema: {}, callTool })).resolves.toContain("whole recurring series");
expect(callTool).toHaveBeenCalledWith("calendar__get_event", { calendarId: "primary", eventId: "s1" });
});
it("passes one occurrence, refuses when the callback has no event, and reads nothing for other tools", async () => {
await expect(googleWorkspaceMcpPreflightRefusal({ toolName: "calendar__delete_event", arguments: { eventId: "s1_20261124" }, inputSchema: {},
callTool: async () => eventResult({ id: "s1_20261124", recurringEventId: "s1" }) })).resolves.toBeNull();
await expect(googleWorkspaceMcpPreflightRefusal({ toolName: "calendar__delete_event", arguments: { eventId: "e1" }, inputSchema: {},
callTool: async () => null })).resolves.toContain("Nothing was deleted.");
const callTool = vi.fn(async () => null);
await expect(googleWorkspaceMcpPreflightRefusal({ toolName: "calendar__update_event", arguments: { eventId: "e1" }, inputSchema: {}, callTool })).resolves.toBeNull();
await expect(googleWorkspaceMcpPreflightRefusal({ toolName: "drive__get_file_metadata", arguments: { fileId: "a,b" }, inputSchema: {}, callTool }))
.resolves.toContain("fileId must be one Google file ID");
await expect(googleWorkspaceMcpPreflightRefusal({ toolName: "chat__list_messages", arguments: { anything: 1 }, inputSchema: { type: "object", properties: {} }, callTool }))
.resolves.toBeNull();
expect(callTool).not.toHaveBeenCalled();
});
});
@@ -2,6 +2,7 @@ import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
import {
GOOGLE_WORKSPACE_TOOL_TRANSPORT,
googleWorkspaceServiceToolNames,
googleWorkspaceToolName,
googleWorkspaceToolTarget,
googleWorkspaceToolTitle,
type GoogleWorkspaceService,
@@ -10,6 +11,8 @@ import {
import {
GoogleWorkspaceAuthError,
callGoogleWorkspaceRestTool,
googleCalendarSeriesRefusal,
googleWorkspaceArgumentRefusal,
isGoogleWorkspaceRestService,
listGoogleWorkspaceRestTools,
probeGoogleWorkspaceRestService,
@@ -53,8 +56,12 @@ export interface GoogleWorkspaceRestToolDefinition {
}
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 || target.transport !== "paperclip_rest" || !isGoogleWorkspaceRestService(target.service)) return null;
if (!target || !isGoogleWorkspaceRestService(target.service)) return null;
const tool = listGoogleWorkspaceRestTools(target.service).find((candidate) => candidate.name === target.leaf);
return tool ? {
name: tool.name,
@@ -66,6 +73,10 @@ export function googleWorkspaceRestToolDefinition(toolName: string): GoogleWorks
} : null;
}
function googleWorkspaceTransport(toolName: string): GoogleWorkspaceToolTransport | null {
return googleWorkspaceToolTarget(toolName)?.transport ?? null;
}
export function googleWorkspaceCatalogToolTitle(
sourceTemplateKey: unknown,
name: string,
@@ -79,6 +90,29 @@ export function googleWorkspaceCatalogToolTitle(
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<string | 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,
});
}
export async function callGoogleWorkspaceRest(
input: GoogleWorkspaceRestContext & { toolName: string; arguments: unknown; maxResultBytes: number },
): Promise<GoogleWorkspaceRestCallOutcome> {
@@ -12,7 +12,7 @@ import { connectionMethodForConnection } from "../connection-methods.js";
import { stableHash, descriptorHash } from "../../tool-catalog-hash.js";
import { nativeProviderCatalogFor } from "../../native-provider-catalogs.js";
import { restConnectorFor } from "../../connectors/rest-registry.js";
import { paperclipDefinedTool } from "../../connectors/paperclip-defined-tools.js";
import { formerPaperclipDefinedTool, paperclipDefinedTool } from "../../connectors/paperclip-defined-tools.js";
import { googleWorkspaceToolTarget, googleWorkspaceGrantedScopes, isGoogleWorkspaceToolGranted } from "@paperclipai/shared";
import { retainMcpConnectionFailure } from "../../mcp-connection-failure.js";
import { isRemoteMcpConnectorMethod } from "@paperclipai/shared";
@@ -236,9 +236,12 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection
(existing.versionHash !== hash || existing.schemaHash !== schemaHash);
const paperclipDefined = paperclipDefinedTool(connection, descriptor.name) !== null;
if (paperclipDefined && existing?.status === "quarantined") releasedNames.add(descriptor.name);
const former = !paperclipDefined && existing ? formerPaperclipDefinedTool(connection, descriptor.name) : null;
const leavingPaperclipDefinition = Boolean(former && existing && stableHash(former.inputSchema) === existing.schemaHash);
const shouldQuarantine =
quarantineOnRefresh &&
!paperclipDefined &&
!leavingPaperclipDefinition &&
(!existing || changed) &&
existing?.status !== "disabled" &&
(!safeDefault || riskLevel !== "read" || nativeProvider);
+37 -3
View File
@@ -33,7 +33,9 @@ import { connectionManagementService, type ConnectionManagementContext } from ".
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { measureToolDiscovery, measureRunPhase, recordConnectionCatalogCounts } from "./execution-preparation-timing.js";
import { nativeProviderCatalogFor } from "./native-provider-catalogs.js";
import { callGoogleWorkspaceRest, googleWorkspaceCatalogToolTitle, googleWorkspaceRestAuditEndpoint } from "./google-workspace-rest-dispatch.js";
import {
callGoogleWorkspaceRest, googleWorkspaceCatalogToolTitle, googleWorkspaceMcpPreflightRefusal, googleWorkspaceRestAuditEndpoint,
} from "./google-workspace-rest-dispatch.js";
import { currentConnectionToolDefinition } from "./connectors/paperclip-defined-tools.js";
import { composeConnectionInstructions } from "./connection-instructions.js";
import { googleWorkspaceToolTarget, googleWorkspaceGrantedScopes, isGoogleWorkspaceToolGranted } from "@paperclipai/shared";
@@ -644,7 +646,7 @@ type RemoteHttpExecutionAudit = {
mcpMethod?: "tools/call";
requestId: string;
upstreamToolName: string;
dispatched: true;
dispatched: boolean;
};
response?: {
httpStatus: number;
@@ -7518,7 +7520,7 @@ export function createToolGatewayService(
sourceTemplateKey?.startsWith("google-") === true) &&
/caller does not have permission/i.test(providerContent);
const content = googleWorkspacePermissionDenied
? "Google rejected this call. Google Workspace MCP is a Developer Preview: enroll the signed-in Workspace account and this OAuth client's Google Cloud project in Google's Developer Preview Program, wait for Google's registration confirmation, then reconnect and try again."
? "Google rejected this call. Google's Workspace MCP servers accept only an OAuth client marked \"Use this client for an AI-powered agent\" in the Google Cloud console, from a project with the service's MCP API enabled. Ask the admin who set up the Google connection to check both, then reconnect and try again."
: providerContent;
const normalized = {
content,
@@ -8253,6 +8255,26 @@ export function createToolGatewayService(
}, { owner });
}
async function callConnectionToolForCheck(
session: ToolGatewaySession,
tool: ToolGatewayDescriptor,
connectionId: string,
toolName: string,
parameters: Record<string, unknown>,
ms: number,
invocationId: string,
callerHeaders: ExecuteGatewayToolInput["callerHeaders"],
signals: { run?: AbortSignal; caller?: AbortSignal },
): Promise<unknown | null> {
const [entry] = await db.select({ id: toolCatalogEntries.id }).from(toolCatalogEntries).where(and(
eq(toolCatalogEntries.companyId, session.companyId), eq(toolCatalogEntries.connectionId, connectionId),
eq(toolCatalogEntries.toolName, toolName), eq(toolCatalogEntries.status, "active"),
)).limit(1);
if (!entry) return null;
return (await executeRemoteHttpTool(session, { ...tool, catalogEntryId: entry.id }, parameters, ms, invocationId, callerHeaders, false,
{ run: signals.run, caller: signals.caller })).result;
}
async function executeRemoteHttpTool(
session: ToolGatewaySession,
tool: ToolGatewayDescriptor,
@@ -8347,6 +8369,7 @@ export function createToolGatewayService(
},
};
const controller = new AbortController();
const deadlineAt = Date.now() + ms;
const timer = setTimeout(() => controller.abort(), ms);
timer.unref?.();
const progressReporter = toolCallProgressReporterFor(session, tool, invocationId);
@@ -8417,6 +8440,17 @@ export function createToolGatewayService(
{ connectionId: connection.id, catalogEntryId: entry.id, execution },
);
};
if (workspaceTarget?.transport === "google_mcp") {
const refusal = await googleWorkspaceMcpPreflightRefusal({
toolName: entry.toolName, arguments: parameters, inputSchema: entry.inputSchema,
callTool: (toolName, args) => callConnectionToolForCheck(session, tool, connection.id, toolName, args,
Math.max(1, deadlineAt - Date.now()), invocationId, callerHeaders, { run: taskSignals.run, caller: taskSignals.caller }),
});
if (refusal) {
execution.request.dispatched = false;
return { result: normalizeMcpToolResult({ isError: true, content: [{ type: "text", text: refusal }] }, "mcp_http", false, sourceTemplateKey), headerSummary, execution };
}
}
if (workspaceTarget?.transport === "paperclip_rest") {
execution.request.protocol = "Google Workspace REST";
delete execution.request.mcpMethod;