From 4401962e69b2cb076ad41ac149dfe48f12297de8 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:44:03 -0600 Subject: [PATCH] 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 --- doc/connections/GOOGLE-WORKSPACE.md | 25 +- doc/memory/google-connector-memory.md | 118 ++++- ...7-google-workspace-production-checklist.md | 35 +- .../src/google-workspace-connectors.test.ts | 8 +- .../shared/src/google-workspace-connectors.ts | 4 +- .../google-workspace-mcp-transport.test.ts | 430 ++++++++++++++++++ .../google-workspace-rest-transport.test.ts | 27 +- .../__tests__/tool-gateway-service.test.ts | 2 +- .../src/google-workspace-rest-tools/README.md | 98 +++- .../argument-guards.test.ts | 71 +++ .../argument-guards.ts | 96 ++++ .../src/google-workspace-rest-tools/index.ts | 6 + .../src/google-workspace-rest-tools/tool.ts | 17 +- .../connectors/paperclip-defined-tools.ts | 13 +- .../google-workspace-rest-dispatch.test.ts | 33 +- .../google-workspace-rest-dispatch.ts | 36 +- .../tool-access/catalog/publication.ts | 5 +- server/src/services/tool-gateway.ts | 40 +- .../runner-e2e/source-sdk-public-inputs.json | 4 +- 19 files changed, 988 insertions(+), 80 deletions(-) create mode 100644 server/src/__tests__/google-workspace-mcp-transport.test.ts create mode 100644 server/src/google-workspace-rest-tools/argument-guards.test.ts create mode 100644 server/src/google-workspace-rest-tools/argument-guards.ts diff --git a/doc/connections/GOOGLE-WORKSPACE.md b/doc/connections/GOOGLE-WORKSPACE.md index 251b02b534a..692104c28cd 100644 --- a/doc/connections/GOOGLE-WORKSPACE.md +++ b/doc/connections/GOOGLE-WORKSPACE.md @@ -58,8 +58,12 @@ supported. They are not automatically merged, upgraded or reauthorized. The Shee robot-account method remains separate because it uses explicitly shared files, not the user's Google OAuth identity. -Google's hosted Workspace MCP servers are Developer Preview services. The app -endpoints remain separate. Paperclip namespaces actions by service and routes them +Google made its hosted Workspace MCP servers generally available on +2026-11-24. Its Workspace AI Tools Addendum +() requires a tool that is, or is +driven by, an AI agent to use them instead of the REST APIs, and Google's MCP +servers reject an OAuth client that is not marked "Use this client for an +AI-powered agent" in the Google Console. The app endpoints remain separate. Paperclip namespaces actions by service and routes them to a closed endpoint registry using the combined grant. It does not create child connections or send provider tokens through Paperclip ID. @@ -68,10 +72,19 @@ Each service has a tool transport, set in `GOOGLE_WORKSPACE_TOOL_TRANSPORT` to Google's hosted MCP server for that service. `paperclip_rest` runs Paperclip's own tools over Google's REST APIs, in the server process (`server/src/google-workspace-rest-tools/`), with the same tool names, inputs -and results. Gmail, Drive, Docs, Sheets, Slides and Calendar run on -`paperclip_rest` (since 2026-11-23), so the combined connection lists all 36 -allowlisted actions for a full read and write grant. Chat, People and Search, -which new setup does not offer, stay on `google_mcp`. A service can move to +and results. Every service runs on `google_mcp` (since 2026-11-24; Gmail, +Drive, Docs, Sheets, Slides and Calendar ran on `paperclip_rest` from +2026-11-23 to 2026-11-24). `paperclip_rest` stays as the fallback. The +combined connection lists the allowlisted actions that Google's servers list +and the grant covers, at most 36 for a full read and write grant. Before a call +goes to Google's MCP server, the gateway applies the REST tools' argument checks +that need no request to Google: unknown arguments, one file ID per argument, +the closed list of Docs and Slides edit kinds, and, for a Calendar delete, a +read of the event that refuses a whole recurring series. A confirmation question +from Google's server goes to a person on the task's question card. When a +connection saved on `paperclip_rest` is refreshed on `google_mcp`, Google's +definitions replace Paperclip's without holding any action for review, and Off +and Ask first stay. A service can move to `paperclip_rest` only when Paperclip implements every tool on its allowlist; a test enforces that. Actions of a service on `paperclip_rest` are Paperclip's own definitions. Agents receive them at once, also for a connection saved diff --git a/doc/memory/google-connector-memory.md b/doc/memory/google-connector-memory.md index 546bd7e9a09..53b283f7bd5 100644 --- a/doc/memory/google-connector-memory.md +++ b/doc/memory/google-connector-memory.md @@ -12,14 +12,14 @@ Related: [production checklist](../plans/2026-11-17-google-workspace-production- [code-fix plan](../plans/2026-11-17-google-workspace-code-fixes.md), [connector doc](../connections/GOOGLE-WORKSPACE.md). -Last updated: November 23, 2026 (evening). +Last updated: November 24, 2026. ## Decisions | Date | Decision | Detail | | --- | --- | --- | | Nov 17 | **Owner for everything is Dotta** | Submission, security, privacy and release. | -| Nov 17 | **Launch on our own tools over Google's REST APIs** | Google's hosted Workspace MCP servers are still Developer Preview and cannot be offered to the public. We build our own tool set for agents that have this connector. | +| Nov 17 | **Launch on our own tools over Google's REST APIs** | Replaced on Nov 24 (see below). Google's hosted Workspace MCP servers were still Developer Preview and could not be offered to the public. We built our own tool set for agents that have this connector. | | Nov 17 | **The REST tool set must be swappable for Google's MCP later** | Same tool names, inputs and results as Google's MCP tools, so switching back is a change of endpoint, not a rewrite. | | Nov 17 | **The REST tool set lives in its own folder** | Nothing Google-REST-specific leaks into shared code; removing it later means deleting the folder and flipping one registration. Follow the boundary-discipline principle and `rules/module-boundaries.mdc`. | | Nov 17 | **No new npm packages** | The REST tool set is a folder inside the server, `server/src/google-workspace-rest-tools/`, not a new package. The server is published, so a new package in its dependencies would also have to be published. | @@ -40,7 +40,7 @@ Last updated: November 23, 2026 (evening). | Nov 17 | **Deleting a whole recurring series is refused** | Same rule as the `delete_event` decision above. | | Nov 17 | **A service is switched to REST only after a live test on the staging tester** | One service at a time. | | Nov 17 | **The gateway sets the REST result size limit** | The REST tools enforce the number the gateway passes: the gateway's MCP response limit less framing, 999,885 bytes. A result Google's MCP server could deliver is also delivered over REST. See the folder README's "Result size". | -| Nov 23 | **All six launch services switched to REST now** | Gmail, Drive, Docs, Sheets, Slides and Calendar are `paperclip_rest`. This replaces the Nov 17 "one service at a time after a live test" rule: live testing happens on the staging tester right after the switch deploys, and problems are fixed forward. Chat, People and Search stay on `google_mcp`. | +| Nov 23 | **All six launch services switched to REST now** | Replaced on Nov 24 (see below). Gmail, Drive, Docs, Sheets, Slides and Calendar were `paperclip_rest`. This replaces the Nov 17 "one service at a time after a live test" rule: live testing happens on the staging tester right after the switch deploys, and problems are fixed forward. Chat, People and Search stay on `google_mcp`. | | Nov 23 | **Write actions default to "Allowed"** | No approval step by default, including actions labelled destructive. Operators can still set Ask first per action. | | Nov 23 | **Images by public web address are allowed in Docs and Slides** | `insertInlineImage`, `replaceImage`, `createImage` and `replaceAllShapesWithImage` may use any public link. Links to Drive or Docs files stay refused (Nov 17 rule). Accepted risk: Google, not Paperclip, fetches the address, and Paperclip's own requests still go only to the allowed Google hosts. What remains is that an agent could put data in the address it chooses. Owner decision; do not restrict it. | | Nov 23 | **Unconfirmed Google revocation is retried by the app, not Cloud** | When access must end and Google cannot be reached or confirm, the app keeps the token in `google_pending_revocations` and retries (1 minute up to 6 hours backoff, 30-day hard stop). Cloud still never stores provider tokens. Company deletion and a Cloud-removed instance queue the same way. The broker lets a removed instance sign a Google revoke (Cloud broker change, November 23). See [connector doc](../connections/GOOGLE-WORKSPACE.md), "Pending revocation". | @@ -49,6 +49,9 @@ Last updated: November 23, 2026 (evening). | Nov 23 | **Security lab: TAC Security (recommended, not yet engaged)** | Google's discounted Tier 2 partner. Plan about $2,000 for year one including a retest. Confirm with a quote; Google assigns the tier. | | Nov 23 | **A tool refuses an argument it does not know** | All 36 tools fail before any request to Google and name the accepted arguments. Found live: `list_threads` ignored a filter and returned unfiltered mail. | | Nov 23 | **A cancelled or abandoned first sign-in leaves no connection** | Cancel removes the draft; a closed tab leaves a hidden draft that the next attempt reuses. Applies to every sign-in connector. | +| Nov 24 | **Back to Google's MCP servers for all six services, before the demo video and the submission** | Gmail, Drive, Docs, Sheets, Slides and Calendar are `google_mcp` again. Reason: Google's Workspace AI Tools Addendum (published Nov 24, see "Google AI Tools Addendum") says a tool that is, or is driven by, an AI agent must use a Google MCP and not the REST APIs, and forbids hiding that classification. Google made its Workspace MCP servers generally available the same day. | +| Nov 24 | **The REST tool set stays as the fallback** | `server/src/google-workspace-rest-tools/` and the `GOOGLE_WORKSPACE_TOOL_TRANSPORT` switch stay in the code. Do not delete them. The REST argument checks that need no request to Google also run before each call to Google's MCP servers. | +| Nov 24 | **Every OAuth client that calls Google's MCP servers is an agent client** | Google's MCP servers reject an OAuth client that is not marked "Use this client for an AI-powered agent" in the Google Console. The coordinator changes the Console setting; there is no code for it. | | Nov 24 | **The service picker shows no explanatory text, only the privacy policy link** | Owner decision. This removes the in-product data-use disclosure added on Nov 17 ([#21998](https://github.com/paperclipai/paperclip/pull/21998)). Risk noted by the coordinator: Google's user data policy may expect an in-product disclosure before consent; if a reviewer asks, restore a short statement above the link. | ## What has shipped @@ -68,26 +71,64 @@ Last updated: November 23, 2026 (evening). | [#22027](https://github.com/paperclipai/paperclip/pull/22027) | Six Sheets tools in the REST tool set (Sheets 6 of 6). | `c366a606b1` | | [#22029](https://github.com/paperclipai/paperclip/pull/22029) | Docs and Slides tools in the REST tool set (Docs 2 of 2, Slides 2 of 2). Also marks Calendar `update_event` destructive. | `f61b919701` | | [#22028](https://github.com/paperclipai/paperclip/pull/22028) | Eight Drive tools in the REST tool set (Drive 8 of 8). Also limits the Gmail host to its API path prefix (before, any path was accepted there) and requires a path prefix for every allowed host. | `ceaf574421` | +| [#22815](https://github.com/paperclipai/paperclip/pull/22815) | All six services back on Google's MCP servers (Nov 24). The REST argument checks that need no request to Google run before each MCP call. A refresh that replaces saved REST definitions holds nothing for review. REST tools stay as the fallback. | Squash merge of this PR | -The REST tool set covers all 36 actions, and all six services are switched to it. +The REST tool set covers all 36 actions. All six services ran on it from Nov 23 to Nov 24 and are back on Google's MCP servers since Nov 24; the REST tool set is the fallback. ### REST tools status | Service | Implemented | Switched on | | --- | --- | --- | -| Gmail | 9 of 9 | Yes (Nov 23) | -| Calendar | 9 of 9 | Yes (Nov 23) | -| Drive | 8 of 8 | Yes (Nov 23) | -| Docs | 2 of 2 | Yes (Nov 23) | -| Sheets | 6 of 6 | Yes (Nov 23) | -| Slides | 2 of 2 | Yes (Nov 23) | +| Gmail | 9 of 9 | No. On REST Nov 23 to Nov 24 | +| Calendar | 9 of 9 | No. On REST Nov 23 to Nov 24 | +| Drive | 8 of 8 | No. On REST Nov 23 to Nov 24 | +| Docs | 2 of 2 | No. On REST Nov 23 to Nov 24 | +| Sheets | 6 of 6 | No. On REST Nov 23 to Nov 24 | +| Slides | 2 of 2 | No. On REST Nov 23 to Nov 24 | "Switched on" means the service is `paperclip_rest` in -`GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Chat, People and Search stay `google_mcp`. +`GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Since Nov 24 every service is +`google_mcp`. + +### On Google's MCP servers (since Nov 24) + +What Paperclip still does before it sends a call to Google's MCP server: + +- Offers only the actions on the allowlist (`toolScopes` in + `packages/shared/src/google-workspace-connectors.ts`) that the grant + covers. A tool that Google's server lists and the allowlist does not (Gmail + send, Drive delete or sharing, Gmail archive, Chat, People, Search) never + reaches an agent. +- Refuses an argument that the action's saved schema does not list (top + level always; inside an object only when the schema closes that object). +- Requires one file ID (no link, no list) in `fileId`, `parentId`, + `documentId`, `spreadsheetId` and `presentationId`. +- Docs and Slides edits: the closed list of request kinds, including the + refusal of kinds that read another file and of images from Drive or Docs + links. +- `delete_event`: reads the event first with Google's `get_event` and refuses + a whole recurring series. If that read does not return the event, nothing + is deleted. +- Off, Ask first, approval, readable action names, audit, invocation records + and prompt-injection screening run as on REST. +- A confirmation question from Google (MCP elicitation) goes on the task's + question card for a person. Skipping it sends "decline"; until it is + answered, the call stops again and nothing is changed. + +What only the REST tools did, and does not happen on MCP: + +- `requiredRevisionId` being mandatory for Docs and Slides edits. +- A connection whose catalog was saved on REST keeps the REST definitions + for agents until its next catalog refresh. The refresh saves Google's + definitions and does not hold those actions for review. Gmail + `get_draft`, `list_threads` and `search_messages` are not in Google's + published reference; if Google's server does not list them, the refresh + removes them. ### Known differences from Google's tools From the folder README (`server/src/google-workspace-rest-tools/README.md`). +They apply only while a service is on the REST fallback. | Service | Difference | | --- | --- | @@ -106,8 +147,12 @@ From the folder README (`server/src/google-workspace-rest-tools/README.md`). reviewers and nobody has signed in with it yet. Only the owner holds it. This test also decides whether the reviewer's `member` role can add a Google connection or must be raised. -- **Disconnect and "Delete data" on the REST build.** Verified on the - earlier build only. +- **Live test on Google's MCP servers.** The switch back (Nov 24) is tested + with fakes only. On the staging tester: mark the client as an agent client, + enable the six MCP APIs, then run all 36 actions, one Google confirmation + answered and one declined, disconnect and "Delete data". +- **Retention after disconnect (owner decision).** See "Google AI Tools + Addendum". - **Company deletion race.** A late activity entry can fail a company delete with a foreign-key error (seen once in CI on Nov 23). A fix is in review. @@ -137,16 +182,18 @@ From the folder README (`server/src/google-workspace-rest-tools/README.md`). ## Next steps -1. Owner signs in as the reviewer on the staging tester; then test connect, +1. Mark the OAuth clients as agent clients in the Google Console and test + the MCP build live on the staging tester (see "Still open"). +2. Owner signs in as the reviewer on the staging tester; then test connect, an agent task, disconnect and "Delete data" as the reviewer. -2. Deploy to production on the owner's go: app first, then broker. The +3. Deploy to production on the owner's go: app first, then broker. The production GitHub Environment already has the reviewer login switch set to on (November 23), so no action is needed there. Without that switch, a production deploy would turn the production tester's reviewer login off. -3. Get a quote from the security lab. -4. Record the demo video and prepare the reply to Google. -5. Update the Console declaration to the 14 when submitting. +4. Get a quote from the security lab. +5. Record the demo video and prepare the reply to Google. +6. Update the Console declaration to the 14 when submitting. ## Environments @@ -168,7 +215,8 @@ Staging tester state (November 23): releases, which is why its build changed without a deploy. - **On the separate Google app.** That app is External, In Production, with the six REST APIs enabled and the staging broker callback on its one web - client. The consent screen names the app by its domain and shows one + client. For the MCP build it also needs the six Workspace MCP APIs enabled + and its client marked as an agent client (not done as of Nov 24). The consent screen names the app by its domain and shows one unticked box per permission. The staging environment lists the tester's stack for the alternate client, for the Workspace group only. - Never set the alternate stack list before its client secret exists: the @@ -179,7 +227,8 @@ Staging tester state (November 23): wrong review code is refused. Sign-in with the real review code is not tested (see "Still open"). -Passed live on the tester, on REST against real Google (November 23): +Passed live on the tester, on the REST build against real Google (November 23; +the MCP build is not tested live yet): - All 36 actions: Gmail (search, read, labels, drafts, list with a filter, create and read a draft), Drive (create, search, metadata, read, copy, @@ -197,7 +246,8 @@ Passed live on the tester, on REST against real Google (November 23): - Cancelling a sign-in leaves one connection and nothing needing attention. - Review, Permissions and Activity show readable action names and no ids. -Checked on the build before the REST switch only (test again on REST): +Checked on the MCP build before the REST switch only (test again on the +current MCP build): - Disconnect ends access at Google (the account's linked-apps list lost the entry), and reconnect works. @@ -229,8 +279,30 @@ the reviewers only through the review channel. separate-project request. - Verification is of the original production app; the new app only gives reviewers a way in. -- With the REST transport, each project needs the Gmail, Drive, Docs, Sheets, - Slides and Calendar APIs enabled, not the MCP APIs. +- On Google's MCP servers (since Nov 24), each project needs the Gmail, + Drive, Docs, Sheets, Slides and Calendar MCP APIs enabled, and each OAuth + client that calls them marked "Use this client for an AI-powered agent". + Keep the REST APIs enabled too, for the fallback. + +## Google AI Tools Addendum + +Published November 24, 2026 with the general availability of Google's +Workspace MCP servers: . + +- A tool that is, or is driven by, an AI agent must use a Google MCP, not the + REST APIs. Hiding that classification is forbidden. This is why all six + services are back on Google's MCP servers. +- Google's MCP servers reject an OAuth client that is not marked "Use this + client for an AI-powered agent". +- **February 1, 2027:** technical enforcement starts. +- **April 1, 2027:** paid tier for the Gmail, Drive and Calendar MCP servers, + billed from the first request. +- **Free tier:** 5,000 requests per day per project per product. +- **Open, owner decision needed:** the addendum forbids keeping Google user + data after the user disconnects. Paperclip keeps task and run content + (see "Where Google content is kept") until the user runs "Delete data" or + deletes the task or company. Disconnect alone does not delete it. Do not + change this until the owner decides. ## Scopes diff --git a/doc/plans/2026-11-17-google-workspace-production-checklist.md b/doc/plans/2026-11-17-google-workspace-production-checklist.md index 9fed8d06fc2..36d0e491758 100644 --- a/doc/plans/2026-11-17-google-workspace-production-checklist.md +++ b/doc/plans/2026-11-17-google-workspace-production-checklist.md @@ -31,8 +31,11 @@ demo. Decisions and the details behind them are kept in the [working memory](../memory/google-connector-memory.md). -- [x] **Launch transport** (Nov 17): our own tools over Google's REST APIs, - built so we can switch to Google's MCP servers later. +- [x] **Launch transport** (Nov 24): Google's hosted MCP servers for Gmail, + Drive, Docs, Sheets, Slides and Calendar, because Google's Workspace AI + Tools Addendum requires a Google MCP for a tool that is or is driven by + an AI agent. Paperclip's REST tool set stays in the code as the + fallback. This replaces the Nov 17 decision to launch on REST. - [x] **Owner** (Nov 17): Dotta owns submission, security, privacy and release. - [x] **Engineering test instance** (Nov 17): create `googletester.staging.paperclip.app`. @@ -41,15 +44,20 @@ Decisions and the details behind them are kept in the - [ ] Privacy policy edits approved. - [ ] Security lab and budget. (Nov 23: TAC Security recommended; quote and budget not confirmed) -- [ ] Email the Developer Preview team asking for permission to offer the MCP - integration publicly (optional now, still cheap). +- [x] Permission to offer the MCP integration publicly: not needed. Google + made the Workspace MCP servers generally available on November 24. ## 1. Baseline (needs the Google project owner's sign-in) - [ ] Verification Center: is the case pending, waiting on us, or closed? - [ ] Record the scopes declared in the Console and compare with the 14. -- [ ] Every OAuth client that calls Workspace MCP is marked as an AI-agent - client; note any that missed the November cutoff and need replacing. +- [ ] Every OAuth client that calls Workspace MCP is marked "Use this client + for an AI-powered agent" in the Google Console (Google's MCP servers + reject other clients). Note any that missed the November cutoff and need + replacing. Required before the switch back to MCP works on the staging + tester and in production. +- [ ] The six Workspace MCP APIs are enabled in each Google project that + calls them (the REST APIs stay enabled for the fallback). - [ ] Separate QA project is External and In Production, with user count noted. - [ ] Reviewer callback URL is registered on the QA client. - [ ] Branding preflight: homepage, privacy policy on the app domain and on the @@ -78,8 +86,9 @@ Decisions and the details behind them are kept in the - [x] Prompt-injection screening confirmed on every Google tool result (Nov 17, [#21999](https://github.com/paperclipai/paperclip/pull/21999)). - [ ] Disconnecting the last Google connection revokes the grant at Google. - Seen at Google on November 23 on the build before the REST switch. - Test it again on the REST build before this is ticked. + Seen at Google on November 23 on the MCP build before the REST switch. + Revocation does not depend on the transport; test it again on the + current MCP build before this is ticked. - [x] Retention and deletion of Google content in tasks, runs and files audited (Nov 17, [#22010](https://github.com/paperclipai/paperclip/pull/22010) store inventory; summary in the working memory's "Where Google content @@ -103,6 +112,16 @@ Decisions and the details behind them are kept in the passed against Google after two fixes ([#22706](https://github.com/paperclipai/paperclip/pull/22706), [#22714](https://github.com/paperclipai/paperclip/pull/22714)). +- [x] All six services switched back to Google's MCP servers (Nov 24), with + the REST argument checks that need no request to Google applied before + each MCP call, and Google's confirmation questions routed to the task's + question card. Tested with fakes only. +- [ ] The six services tested live on Google's MCP servers on the staging + tester: all 36 actions, the agent-client OAuth setting, and one + confirmation question from Google answered and one declined. +- [ ] Owner decision: the AI Tools Addendum forbids keeping Google user data + after the user disconnects. Paperclip keeps task and run content until + "Delete data". See the working memory's "Google AI Tools Addendum". - [ ] Scopes identical in the picker, the server, the Cloud broker and the Google Console. - [x] `googletester.staging.paperclip.app` created (Nov 18). diff --git a/packages/shared/src/google-workspace-connectors.test.ts b/packages/shared/src/google-workspace-connectors.test.ts index 26316900a50..b9948b508bc 100644 --- a/packages/shared/src/google-workspace-connectors.test.ts +++ b/packages/shared/src/google-workspace-connectors.test.ts @@ -172,13 +172,13 @@ describe("combined Google Workspace consent", () => { expect(isGoogleWorkspaceToolGranted("gmail__send_message", profiles["workspace.all"].scopes)).toBe(false); }); - it("runs the six launch services on Paperclip's REST tools, keeps the others on Google's MCP servers, and reports the transport on each target", () => { + it("runs every service on Google's MCP servers, as the AI Tools Addendum requires, and reports the transport on each target", () => { expect(Object.keys(GOOGLE_WORKSPACE_TOOL_TRANSPORT).sort()).toEqual(Object.keys(GOOGLE_WORKSPACE_SERVICES).sort()); expect(GOOGLE_WORKSPACE_TOOL_TRANSPORT).toEqual({ - gmail: "paperclip_rest", drive: "paperclip_rest", docs: "paperclip_rest", sheets: "paperclip_rest", - slides: "paperclip_rest", calendar: "paperclip_rest", chat: "google_mcp", people: "google_mcp", search: "google_mcp", + gmail: "google_mcp", drive: "google_mcp", docs: "google_mcp", sheets: "google_mcp", + slides: "google_mcp", calendar: "google_mcp", chat: "google_mcp", people: "google_mcp", search: "google_mcp", }); - expect(googleWorkspaceToolTarget("gmail__get_message")?.transport).toBe("paperclip_rest"); + expect(googleWorkspaceToolTarget("gmail__get_message")?.transport).toBe("google_mcp"); expect(googleWorkspaceToolTarget("chat__list_messages")?.transport).toBe("google_mcp"); expect(googleWorkspaceServiceToolNames("docs")).toEqual(["read_doc", "update_doc"]); }); diff --git a/packages/shared/src/google-workspace-connectors.ts b/packages/shared/src/google-workspace-connectors.ts index 88d942d1e66..270fbd40c0f 100644 --- a/packages/shared/src/google-workspace-connectors.ts +++ b/packages/shared/src/google-workspace-connectors.ts @@ -136,8 +136,8 @@ export type GoogleWorkspaceService = keyof typeof GOOGLE_WORKSPACE_SERVICES; export type GoogleWorkspaceToolTransport = "google_mcp" | "paperclip_rest"; export const GOOGLE_WORKSPACE_TOOL_TRANSPORT: Record = { - gmail: "paperclip_rest", drive: "paperclip_rest", docs: "paperclip_rest", sheets: "paperclip_rest", - slides: "paperclip_rest", calendar: "paperclip_rest", chat: "google_mcp", + gmail: "google_mcp", drive: "google_mcp", docs: "google_mcp", sheets: "google_mcp", + slides: "google_mcp", calendar: "google_mcp", chat: "google_mcp", people: "google_mcp", search: "google_mcp", }; diff --git a/server/src/__tests__/google-workspace-mcp-transport.test.ts b/server/src/__tests__/google-workspace-mcp-transport.test.ts new file mode 100644 index 00000000000..2e55d43f3a7 --- /dev/null +++ b/server/src/__tests__/google-workspace-mcp-transport.test.ts @@ -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(); + 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 = { + "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> = { + 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 } + +function fakeGoogle(options: { confirm?: Confirmation } = {}) { + const requests: Recorded[] = []; + const replies: Array> = []; + const waiting = new Map) => 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 => { + 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).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({ + async start(controller) { + const askId = `ask-${++asks}`; + const reply = new Promise>((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; + let database: Awaited>; + 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" }); + }); +}); diff --git a/server/src/__tests__/google-workspace-rest-transport.test.ts b/server/src/__tests__/google-workspace-rest-transport.test.ts index c603cbe9fc7..202fe66f3e1 100644 --- a/server/src/__tests__/google-workspace-rest-transport.test.ts +++ b/server/src/__tests__/google-workspace-rest-transport.test.ts @@ -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> = { }, 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; let database: Awaited>; const savedTransport = { ...GOOGLE_WORKSPACE_TOOL_TRANSPORT }; + const REST_TRANSPORT: Record = { + ...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); diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index 4aeadc56de2..396392a861d 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -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\""), }); }); diff --git a/server/src/google-workspace-rest-tools/README.md b/server/src/google-workspace-rest-tools/README.md index 9e40a4468c8..1b483bc9a05 100644 --- a/server/src/google-workspace-rest-tools/README.md +++ b/server/src/google-workspace-rest-tools/README.md @@ -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 +(): 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 diff --git a/server/src/google-workspace-rest-tools/argument-guards.test.ts b/server/src/google-workspace-rest-tools/argument-guards.test.ts new file mode 100644 index 00000000000..f08eab3f60a --- /dev/null +++ b/server/src/google-workspace-rest-tools/argument-guards.test.ts @@ -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."); + }); +}); diff --git a/server/src/google-workspace-rest-tools/argument-guards.ts b/server/src/google-workspace-rest-tools/argument-guards.ts new file mode 100644 index 00000000000..5dfb4f54e5e --- /dev/null +++ b/server/src/google-workspace-rest-tools/argument-guards.ts @@ -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> = { + drive: ["fileId", "parentId"], + docs: ["documentId"], + sheets: ["spreadsheetId"], + slides: ["presentationId"], +}; +const REQUEST_KINDS: Partial>>> = { + docs: { update_doc: DOCS_REQUEST_KINDS }, + slides: { update_presentation: SLIDES_REQUEST_KINDS }, +}; + +const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); + +function closedAtTopOrDeclared(schema: JsonSchemaNode, path: string): schema is JsonSchemaNode & { properties: Record } { + 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>, 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 | 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; +} diff --git a/server/src/google-workspace-rest-tools/index.ts b/server/src/google-workspace-rest-tools/index.ts index b6c772612f5..3d694701662 100644 --- a/server/src/google-workspace-rest-tools/index.ts +++ b/server/src/google-workspace-rest-tools/index.ts @@ -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"; diff --git a/server/src/google-workspace-rest-tools/tool.ts b/server/src/google-workspace-rest-tools/tool.ts index 96d8bd64e6e..54e9faa43e9 100644 --- a/server/src/google-workspace-rest-tools/tool.ts +++ b/server/src/google-workspace-rest-tools/tool.ts @@ -60,7 +60,7 @@ export function defineTool(spec: RestToolSpec): RestTool { }; } -type JsonSchemaNode = Record; +export type JsonSchemaNode = Record; const isRecord = (value: unknown): value is Record => 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 }; + +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; } diff --git a/server/src/services/connectors/paperclip-defined-tools.ts b/server/src/services/connectors/paperclip-defined-tools.ts index e8dca24d85d..b4a948341e8 100644 --- a/server/src/services/connectors/paperclip-defined-tools.ts +++ b/server/src/services/connectors/paperclip-defined-tools.ts @@ -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 }; 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; diff --git a/server/src/services/google-workspace-rest-dispatch.test.ts b/server/src/services/google-workspace-rest-dispatch.test.ts index 05af29aa319..884ba3d1c0a 100644 --- a/server/src/services/google-workspace-rest-dispatch.test.ts +++ b/server/src/services/google-workspace-rest-dispatch.test.ts @@ -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) => ({ 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(); + }); +}); diff --git a/server/src/services/google-workspace-rest-dispatch.ts b/server/src/services/google-workspace-rest-dispatch.ts index 1876809efe5..8b888852e2b 100644 --- a/server/src/services/google-workspace-rest-dispatch.ts +++ b/server/src/services/google-workspace-rest-dispatch.ts @@ -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) => Promise; +} + +export async function googleWorkspaceMcpPreflightRefusal(input: GoogleWorkspaceMcpPreflight): Promise { + 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; + 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 { diff --git a/server/src/services/tool-access/catalog/publication.ts b/server/src/services/tool-access/catalog/publication.ts index d2ea419ff96..35dede36fb1 100644 --- a/server/src/services/tool-access/catalog/publication.ts +++ b/server/src/services/tool-access/catalog/publication.ts @@ -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); diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 1d5d0bd89f2..9e191b4371c 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -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, + ms: number, + invocationId: string, + callerHeaders: ExecuteGatewayToolInput["callerHeaders"], + signals: { run?: AbortSignal; caller?: AbortSignal }, + ): Promise { + 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; diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index bef1cc66288..75d6e3bac23 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -270,8 +270,8 @@ "packages/shared/src/gitignore-runtime.test.ts": "e334ab0eca8faeab5807171983ec9102a3f1c734", "packages/shared/src/google-sign-in-deployment.test.ts": "7f0ee05e9adaec48ed71c67e2b0e8364b0d1bdb2", "packages/shared/src/google-sign-in-deployment.ts": "2e4e4cc3c24347642e20c91186581e1dce81d740", - "packages/shared/src/google-workspace-connectors.test.ts": "26316900a50e5ab384e0dcf9c45a2bb4abc0830d", - "packages/shared/src/google-workspace-connectors.ts": "88d942d1e66d7facc68cf8645f665cdc80c8c005", + "packages/shared/src/google-workspace-connectors.test.ts": "b9948b508bcb7a27c0dcea974edee314164686e5", + "packages/shared/src/google-workspace-connectors.ts": "270fbd40c0f96e8f4140c880a2c36a3150d4b9aa", "packages/shared/src/google-workspace-setup-links.test.ts": "d86428b26e74e54ab2902d1a14c0f06f562de775", "packages/shared/src/grok-bot.ts": "9de68f00e7926c397729ff62bf8e277f5a41c525", "packages/shared/src/heartbeat-inbox.ts": "227dc89705c20460ca02194091cb162e11503186",