mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
feat(google-workspace): run Gmail, Drive, Docs, Sheets, Slides and Calendar on Paperclip's REST tools (#22634)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The built-in Google Workspace connector gives agents Gmail, Drive, Docs, Sheets, Slides and Calendar actions through one connection > - Google's hosted Workspace MCP servers are a Developer Preview, so Paperclip cannot offer them to the public > - Paperclip has its own REST tool set for all 36 allowlisted actions, but every service still sent its calls to Google's MCP servers > - The owner decided on 2026-11-23 to launch all six services on REST now and to live-test on the staging tester after deploy > - This pull request switches the six services to `paperclip_rest` and fixes what the switch breaks > - The benefit is that the connector no longer depends on Developer Preview servers, and agents get all 36 actions, including the two Gmail actions Google's live server did not offer ## Linked Issues or Issue Description Refs #22016 (the transport switch), #22000, #22014, #22017, #22027, #22028, #22029 (the REST tool set). **Subsystem affected** Built-in Google Workspace connector (`google-workspace`, `workspace.all`): transport setting, catalog publication, tests and docs. **Problem or motivation** All six launch services used Google's hosted MCP servers. These servers are a Developer Preview and are not available to the public. Google's live Gmail MCP server also did not offer `gmail__list_threads` and `gmail__search_messages`. **Proposed solution** Set Gmail, Drive, Docs, Sheets, Slides and Calendar to `paperclip_rest` in `GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Keep Chat, People and Search on `google_mcp`. Fix the catalog refresh so that an existing connection keeps its actions active after the switch. **Alternatives considered** Switch one service at a time after a live test (the Nov 17 rule). The owner replaced this rule on Nov 23: switch all six now and fix forward. **Roadmap alignment** This is the planned launch step for the Google Workspace connector. It does not overlap other core work. ## What Changed - `packages/shared/src/google-workspace-connectors.ts`: set `gmail`, `drive`, `docs`, `sheets`, `slides` and `calendar` to `paperclip_rest`. `chat`, `people` and `search` stay `google_mcp`. - Connections saved before the switch keep Google's MCP definitions in their catalog. Two changes make them work with no user action: - New resolver `paperclipDefinedTool(connection, toolName)` in `server/src/services/connectors/paperclip-defined-tools.ts` (typed result). It is the one place that says which tools are Paperclip-defined; for a `google-workspace` connection it calls `googleWorkspaceRestToolDefinition` in the dispatch adapter, which returns the REST definition when the service is on `paperclip_rest`. - `server/src/services/tool-gateway.ts`: when the gateway lists a connection's tools, it takes the input schema, output schema, description and annotations of a Paperclip-defined tool from the resolver, not from the saved row. Routing and the advertised definition read the same transport setting in the same process. This is an in-memory lookup, so it adds no request to the turn start. Example: an agent gets the REST `docs__update_doc` schema, where `writeControl.requiredRevisionId` is required, not Google's schema, where it is optional. - `server/src/services/tool-access/catalog/publication.ts`: catalog publication asks the same resolver. It never holds a Paperclip-defined action for review, and it clears the review hold (`quarantined`, `pending_review`) of an action held only because a remote definition changed. Clearing the hold does not count the action as new, so it is never added to the profile: Off stays Off and Ask first stays, also for a held action. Only actions the connection never had (Gmail `list_threads` and `search_messages`) get the default for new actions. Before this fix, a refresh after the switch put every action of an existing managed connection into `pending_review` (10 of 10 in the regression test). - `server/src/__tests__/google-workspace-rest-transport.test.ts`: the fake Google now answers the Docs, Sheets and Slides REST hosts and the Drive and Calendar paths. New tests: - The transport map has exactly the six launch services on `paperclip_rest`. - A full read and write grant lists exactly the 36 allowlisted actions (with `gmail__list_threads` and `gmail__search_messages`) and sends no MCP request. A read-only grant lists the 23 read actions. Gmail, Drive and Calendar group grants list exactly their actions. - One read and one write per service run through the real `executeTool` path on REST with the default policy (no approval request). Each call records the invocation and the `call_completed` event with the connection ID (the "Delete data" bookkeeping keys), and audits the protocol `Google Workspace REST` with the service endpoint. - Injected instructions in Docs, Sheets, Slides, Drive and Calendar REST results are blocked. - An existing connection discovered over MCP keeps its actions active after the switch and can call the new Gmail actions. - Migration without refresh: a connection saved with Google's MCP schemas (`update_doc` with `writeControl` optional) advertises the REST schemas after the switch with no refresh, and `read_doc` then `update_doc` with the revision succeed over REST. - The first refresh after the switch releases an action held for `pending_review`, keeps an Off action unlisted and keeps Ask first (`approval_required`). - An action that is both Off and held stays Off, and one that is both Ask first and held stays Ask first, after the switch and after two refreshes. - The MCP-path test pins Gmail and Docs to `google_mcp` explicitly. - `server/src/__tests__/helpers/google-workspace-transport.ts`: new helper `useGoogleMcpTransport()`. Tests whose fixtures act as Google's MCP servers use it (`tool-access-service`, `tool-gateway-service`) or pin the transport in `beforeAll` (`google-workspace-injection-screening`). These tests still cover the MCP path, which stays available for Chat, People, Search and a switch back. - `packages/shared/src/google-workspace-connectors.test.ts`: assert the new transport map. - Docs: `doc/connections/GOOGLE-WORKSPACE.md` and the REST folder `README.md` say that the six services run on REST. `doc/memory/google-connector-memory.md` has three dated Nov 23 decisions (all six switched to REST, writes default to Allowed, image-by-URL inserts allowed), and the two items are removed from "Still open". ## Verification - Red: after the flip, 50 tests failed in four files because their fixtures act as Google's MCP servers. These are fixture assumptions, not product bugs. - Red: without the gateway change, the migration test gets Google's saved schema; without the publication change, the held action stays `quarantined`; without excluding released rows from the new-action default, the Off and held action comes back. All green with the fixes. - Red: the new test "keeps an existing connection's actions usable when its services move from Google's MCP servers to REST" failed before the `publication.ts` fix: 10 catalog entries were `quarantined` with `pending_review`. Green after the fix. - `cd server && npx vitest run src/__tests__/google-workspace-rest-transport.test.ts src/__tests__/google-workspace-injection-screening.test.ts src/__tests__/tool-gateway-service.test.ts src/__tests__/tool-access-service.test.ts src/services/google-workspace-rest-dispatch.test.ts src/google-workspace-rest-tools`: with `connection-management.integration.test.ts` added: 60 files, 2232 tests pass. `google-workspace-rest-transport.test.ts`: 52 tests pass. - `cd packages/shared && npx vitest run src/google-workspace-connectors.test.ts`: 14 tests pass. - `npx tsc -p server/tsconfig.json --noEmit`: no errors. - Trace of a read (`gmail__get_message`) and a write (`gmail__create_draft`) through `executeTool` in `server/src/services/tool-gateway.ts`: policy decision and invocation record (13723, 13731), approval gate (13820), `call_allowed` audit (13885), dispatch to `executeRemoteHttpTool` (13915), prompt-injection screening of the result (13964), `call_completed` event and audit (14022, 14044), failure audit (14187). In `executeRemoteHttpTool` the grant scope check (8172) runs before the REST branch (8276), which rechecks the current grant and returns before any MCP session, MCP Task or elicitation code. The REST adapter (`google-workspace-rest-dispatch.ts`) calls `google-http.ts` only through the gateway's guarded fetch. - Not verified: calls against real Google. The live test on the staging tester runs after deploy. ## Risks - Real Google answers can differ from the fixtures. The REST tools are not yet run against real Google. The live test on the staging tester runs after this deploys, and problems are fixed forward. - The OAuth client on the staging tester is marked for AI agents and was only used through MCP. If Google refuses REST calls from that client, all six services fail on the tester until the client changes. - Existing connections keep their stored MCP schemas until a catalog refresh, but agents receive the REST definitions at once. The stored risk level of the four update actions stays `write` until that refresh, then becomes `destructive`. The two new Gmail actions appear after a refresh. - Input differences between Google's MCP schemas and the REST tools are listed in the REST folder `README.md` ("Input differences an agent meets after a switch"). Agents receive the REST schemas, so these differences are visible to them. No `tools/list` from Google's servers is recorded, so the check uses Google's published references. - Accepted risk (owner decision, 2026-11-23): Docs and Slides edits may insert an image from any public web address. Google, not Paperclip, fetches the address, and Paperclip's own requests still go only to the allowed Google hosts. The residual risk is that an agent could put data in the address it chooses. Links to Drive or Docs files stay refused. - Update actions (`update_doc`, `update_presentation`, `update_spreadsheet`, `update_event`) are labelled destructive on REST, as decided on Nov 17. This does not add an approval step: write actions stay Allowed by default. - A switch back to `google_mcp` stays possible with a one-line change. The MCP path tests still run. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e856a607ed
commit
b865dd112b
16 files changed
+500
-90
No files matched your search
@@ -68,9 +68,20 @@ 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. Every service is on `google_mcp` today. A service can move to
|
||||
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
|
||||
`paperclip_rest` only when Paperclip implements every tool on its allowlist; a
|
||||
test enforces that. On either transport, the same grant scope checks, approvals,
|
||||
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
|
||||
before the switch, and the next catalog refresh saves them without holding
|
||||
any for review. That refresh also clears the review hold of held actions,
|
||||
without enabling them: actions turned Off stay Off and Ask first settings
|
||||
stay, also for a held action. Only the two Gmail actions the connection never
|
||||
had get the default for new actions. The setting applies only to the combined `google-workspace`
|
||||
connection; saved individual product connections (for example the Gmail app)
|
||||
still call Google's MCP servers directly. On either transport, the same grant scope checks, approvals,
|
||||
audit, token refresh and reconnection, prompt-injection screening, cancellation
|
||||
and experimental-feature gate apply. On `paperclip_rest`, discovery and health
|
||||
checks prove the token with one cheap REST read per service that the granted
|
||||
|
||||
@@ -12,7 +12,7 @@ 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 18, 2026.
|
||||
Last updated: November 23, 2026.
|
||||
|
||||
## Decisions
|
||||
|
||||
@@ -40,6 +40,9 @@ Last updated: November 18, 2026.
|
||||
| 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 | **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. |
|
||||
|
||||
## What has shipped
|
||||
|
||||
@@ -59,21 +62,21 @@ Last updated: November 18, 2026.
|
||||
| [#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` |
|
||||
|
||||
The REST tool set now covers all 36 actions. No service is switched to it.
|
||||
The REST tool set covers all 36 actions, and all six services are switched to it.
|
||||
|
||||
### REST tools status
|
||||
|
||||
| Service | Implemented | Switched on |
|
||||
| --- | --- | --- |
|
||||
| Gmail | 9 of 9 | No |
|
||||
| Calendar | 9 of 9 | No |
|
||||
| Drive | 8 of 8 | No |
|
||||
| Docs | 2 of 2 | No |
|
||||
| Sheets | 6 of 6 | No |
|
||||
| Slides | 2 of 2 | No |
|
||||
| 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) |
|
||||
|
||||
"Switched on" means the service is `paperclip_rest` in
|
||||
`GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Today every service is `google_mcp`.
|
||||
`GOOGLE_WORKSPACE_TOOL_TRANSPORT`. Chat, People and Search stay `google_mcp`.
|
||||
|
||||
### Known differences from Google's tools
|
||||
|
||||
@@ -91,11 +94,6 @@ From the folder README (`server/src/google-workspace-rest-tools/README.md`).
|
||||
|
||||
## Still open
|
||||
|
||||
- **Images by public web address in Docs and Slides.** An edit may insert an
|
||||
image from any public link, and Google then fetches that address. The
|
||||
address is chosen by the agent, so it can carry data out (a leak path).
|
||||
Allowed today. Recommendation: refuse it before Docs or Slides is switched
|
||||
to REST.
|
||||
- **What we send to the reviewers.** Not decided: the new staging tester or
|
||||
something else. Whatever it is must use the separate Google app (below).
|
||||
- **Reviewer login on staging.** The broker now allows the scoped reviewer
|
||||
@@ -103,8 +101,9 @@ From the folder README (`server/src/google-workspace-rest-tools/README.md`).
|
||||
broker change is needed.
|
||||
- **AI-agent client and REST.** Whether an OAuth client marked for AI agents
|
||||
may call the REST APIs rather than MCP. The tester's client is marked for
|
||||
AI agents and is wired, but it has only been used through MCP. Check on the
|
||||
tester before any service is switched to REST.
|
||||
AI agents and is wired, but it has only been used through MCP. The services
|
||||
are switched (Nov 23); this is the first thing the live test on the tester
|
||||
answers.
|
||||
- **Three Gmail tools are inferred.** Google's MCP reference does not list
|
||||
`get_draft`, `list_threads` and `search_messages`; their schemas copy the
|
||||
sibling tools (#22014).
|
||||
@@ -129,11 +128,11 @@ From the folder README (`server/src/google-workspace-rest-tools/README.md`).
|
||||
waits for Dotta.
|
||||
2. Confirm the consent screen on the staging tester with a fresh Google
|
||||
account, and set the reviewer login secret.
|
||||
3. Finish live acceptance on the staging tester.
|
||||
4. Switch services to REST one at a time, each after its live test.
|
||||
5. Revoke at Google when the last connection is removed.
|
||||
6. Security scans.
|
||||
7. Request revocation at Google when a company with Google connections is
|
||||
3. Live-test all six services on REST on the staging tester and fix forward
|
||||
(switched Nov 23).
|
||||
4. Revoke at Google when the last connection is removed.
|
||||
5. Security scans.
|
||||
6. Request revocation at Google when a company with Google connections is
|
||||
deleted.
|
||||
|
||||
## Environments
|
||||
@@ -180,7 +179,8 @@ Found while testing:
|
||||
tester; `gmail__list_threads` and `gmail__search_messages` were missing.
|
||||
`gmail__get_draft` was offered live even though Google's published
|
||||
reference does not list it, so the reference and the live server differ.
|
||||
- Write actions default to "Allowed" with no approval step. Dotta to decide.
|
||||
- Write actions default to "Allowed" with no approval step. Decided Nov 23:
|
||||
keep it (see "Decisions").
|
||||
- The connection audit page shows internal tool names and raw ids.
|
||||
- The REST tools have not been run against real Google yet.
|
||||
|
||||
|
||||
@@ -172,10 +172,14 @@ describe("combined Google Workspace consent", () => {
|
||||
expect(isGoogleWorkspaceToolGranted("gmail__send_message", profiles["workspace.all"].scopes)).toBe(false);
|
||||
});
|
||||
|
||||
it("sends every service to Google's MCP servers by default and reports the transport on each target", () => {
|
||||
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", () => {
|
||||
expect(Object.keys(GOOGLE_WORKSPACE_TOOL_TRANSPORT).sort()).toEqual(Object.keys(GOOGLE_WORKSPACE_SERVICES).sort());
|
||||
expect(new Set(Object.values(GOOGLE_WORKSPACE_TOOL_TRANSPORT))).toEqual(new Set(["google_mcp"]));
|
||||
expect(googleWorkspaceToolTarget("gmail__get_message")?.transport).toBe("google_mcp");
|
||||
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",
|
||||
});
|
||||
expect(googleWorkspaceToolTarget("gmail__get_message")?.transport).toBe("paperclip_rest");
|
||||
expect(googleWorkspaceToolTarget("chat__list_messages")?.transport).toBe("google_mcp");
|
||||
expect(googleWorkspaceServiceToolNames("docs")).toEqual(["read_doc", "update_doc"]);
|
||||
});
|
||||
|
||||
|
||||
@@ -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<GoogleWorkspaceService, GoogleWorkspaceToolTransport> = {
|
||||
gmail: "google_mcp", drive: "google_mcp", docs: "google_mcp", sheets: "google_mcp",
|
||||
slides: "google_mcp", calendar: "google_mcp", chat: "google_mcp",
|
||||
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",
|
||||
};
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { createDb, companies, companyMemberships, agents, issues, heartbeatRuns, toolApplications, toolConnections, connectionGrants,
|
||||
toolCatalogEntries, toolConnectionInstalls, toolPolicies, toolInvocations, toolActionRequests, toolProfiles, toolProfileEntries,
|
||||
promptInjectionInvocations } from "@paperclipai/db";
|
||||
import { PROMPT_INJECTION_DEFAULT_MODEL } from "@paperclipai/shared";
|
||||
import { GOOGLE_WORKSPACE_TOOL_TRANSPORT, PROMPT_INJECTION_DEFAULT_MODEL } from "@paperclipai/shared";
|
||||
import { createToolGatewayService } from "../services/tool-gateway.js";
|
||||
import { mcpGatewayProtocolRoutes } from "../routes/tool-gateway.js";
|
||||
import { initializeRunIdentity } from "../services/run-identity.js";
|
||||
@@ -37,11 +37,13 @@ function googleResult(body: string) {
|
||||
}
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
(support.supported ? describe : describe.skip)("Google Workspace results pass the prompt-injection guard", () => {
|
||||
(support.supported ? describe : describe.skip)("Google Workspace results from Google's MCP servers pass the prompt-injection guard", () => {
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let home: string;
|
||||
const savedTransport = { ...GOOGLE_WORKSPACE_TOOL_TRANSPORT };
|
||||
beforeAll(async () => {
|
||||
for (const service of Object.keys(GOOGLE_WORKSPACE_TOOL_TRANSPORT) as Array<keyof typeof GOOGLE_WORKSPACE_TOOL_TRANSPORT>) GOOGLE_WORKSPACE_TOOL_TRANSPORT[service] = "google_mcp";
|
||||
home = await realpath(await mkdtemp(path.join(os.tmpdir(), "paperclip-google-guard-")));
|
||||
vi.stubEnv("PAPERCLIP_HOME", home);
|
||||
database = await startEmbeddedPostgresTestDatabase("paperclip-google-guard-db-");
|
||||
@@ -49,6 +51,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
await instanceSettingsService(db).updateExperimental({ enableGoogleWorkspaceConnector: true });
|
||||
}, 90_000);
|
||||
afterAll(async () => {
|
||||
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, savedTransport);
|
||||
await database?.cleanup();
|
||||
vi.unstubAllEnvs();
|
||||
if (home) await rm(home, { recursive: true, force: true });
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents, companies, companyMemberships, connectionGrants, createDb, heartbeatRuns, issues,
|
||||
toolAccessAuditEvents, toolActionRequests, toolInvocations,
|
||||
toolAccessAuditEvents, toolActionRequests, toolCallEvents, toolCatalogEntries, toolInvocations,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
GOOGLE_WORKSPACE_DEFAULT_SELECTION, GOOGLE_WORKSPACE_TOOL_TRANSPORT, googleWorkspaceServiceToolNames,
|
||||
@@ -50,9 +50,43 @@ function gmailMessage(body: string) {
|
||||
};
|
||||
}
|
||||
|
||||
const REST_HOSTS = new Set(["gmail.googleapis.com", "www.googleapis.com", "docs.googleapis.com", "sheets.googleapis.com", "slides.googleapis.com"]);
|
||||
|
||||
function googleDocument(text: string) {
|
||||
return {
|
||||
documentId: "doc1", title: "Plan", revisionId: "rev-1",
|
||||
tabs: [{ tabProperties: { tabId: "t.0", title: "Tab 1", index: 0 }, documentTab: { body: { content: [
|
||||
{ endIndex: 1, sectionBreak: {} },
|
||||
{ startIndex: 1, endIndex: text.length + 2, paragraph: { elements: [{ startIndex: 1, endIndex: text.length + 2, textRun: { content: `${text}\n` } }] } },
|
||||
] } } }],
|
||||
};
|
||||
}
|
||||
|
||||
const MCP_TOOLS: Record<string, string[]> = {
|
||||
"gmailmcp.googleapis.com": ["get_message", "search_threads", "create_draft"],
|
||||
"docsmcp.googleapis.com": ["read_doc"],
|
||||
"docsmcp.googleapis.com": ["read_doc", "update_doc"],
|
||||
};
|
||||
|
||||
const GOOGLE_MCP_SCHEMAS: Record<string, Record<string, unknown>> = {
|
||||
read_doc: {
|
||||
type: "object",
|
||||
properties: { documentId: { type: "string" }, commentsIncluded: { type: "boolean" } },
|
||||
required: ["documentId"],
|
||||
},
|
||||
update_doc: {
|
||||
type: "object",
|
||||
properties: {
|
||||
documentId: { type: "string" },
|
||||
requests: { type: "array", items: { type: "object" } },
|
||||
writeControl: { type: "object", properties: { requiredRevisionId: { type: "string" }, targetRevisionId: { type: "string" } } },
|
||||
},
|
||||
required: ["documentId", "requests"],
|
||||
},
|
||||
get_message: {
|
||||
type: "object",
|
||||
properties: { messageId: { type: "string" }, messageFormat: { type: "string", enum: ["MINIMAL", "FULL_CONTENT", "METADATA_ONLY"] } },
|
||||
required: ["messageId"],
|
||||
},
|
||||
};
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
@@ -81,7 +115,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
GOOGLE_WORKSPACE_TOOL_TRANSPORT[service] = transport;
|
||||
}
|
||||
|
||||
async function connectWorkspace(options: { permissions?: string[]; askFirst?: string[] } = {}) {
|
||||
async function connectWorkspace(options: { permissions?: string[]; askFirst?: string[]; off?: string[] } = {}) {
|
||||
const permissions = (options.permissions ?? ["gmail.readonly", "gmail.compose", "documents.readonly"]).map(scope);
|
||||
const [company] = await db.insert(companies).values({ name: `Google REST ${randomUUID()}`, issuePrefix: `GR${randomUUID().slice(0, 6).toUpperCase()}` }).returning();
|
||||
const userId = `google-rest-${randomUUID()}`;
|
||||
@@ -105,18 +139,33 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
revoke: vi.fn(async () => undefined),
|
||||
} as unknown as PaperclipCloudConnector;
|
||||
|
||||
const gmailRequests: Array<{ method: string; path: string; authorization: string | null; signal: AbortSignal | null }> = [];
|
||||
const restRequests: Array<{ method: string; host: string; path: string; authorization: string | null; signal: AbortSignal | null }> = [];
|
||||
const mcpRequests: string[] = [];
|
||||
let gmailOverride: ((url: URL, init: RequestInit) => Response | Promise<Response> | undefined) | undefined;
|
||||
let restOverride: ((url: URL, init: RequestInit) => Response | Promise<Response> | undefined) | undefined;
|
||||
let messageBody = BENIGN_BODY;
|
||||
let mcpCallOverride: ((init: RequestInit) => Promise<Response> | undefined) | undefined;
|
||||
const remoteHttpRequest = vi.fn(async (href: string, init: RequestInit) => {
|
||||
const url = new URL(href);
|
||||
if (url.hostname === "gmail.googleapis.com" || url.hostname === "www.googleapis.com") {
|
||||
gmailRequests.push({ method: init.method ?? "GET", path: url.pathname, authorization: new Headers(init.headers).get("authorization"), signal: init.signal ?? null });
|
||||
const overridden = await gmailOverride?.(url, init);
|
||||
if (REST_HOSTS.has(url.hostname)) {
|
||||
restRequests.push({ method: init.method ?? "GET", host: url.hostname, path: url.pathname, authorization: new Headers(init.headers).get("authorization"), signal: init.signal ?? null });
|
||||
const overridden = await restOverride?.(url, init);
|
||||
if (overridden) return overridden;
|
||||
if (url.pathname === "/calendar/v3/users/me/calendarList") return Response.json({ items: [{ id: "primary" }] });
|
||||
if (url.pathname === "/calendar/v3/users/me/calendarList") return Response.json({ items: [{ id: "primary", summary: "Team" }] });
|
||||
if (url.pathname === "/calendar/v3/calendars/primary/events" && init.method === "POST") {
|
||||
return Response.json({ id: "event1", status: "confirmed", summary: "Planning", start: { dateTime: "2026-11-24T10:00:00Z" }, end: { dateTime: "2026-11-24T10:30:00Z" } });
|
||||
}
|
||||
if (url.pathname === "/drive/v3/about") return Response.json({ kind: "drive#about" });
|
||||
if (url.pathname === "/gmail/v1/users/me/threads") return Response.json({ threads: [], resultSizeEstimate: 0 });
|
||||
if (url.pathname === "/drive/v3/files/file1") return Response.json({ id: "file1", name: "Plan", mimeType: "text/plain" });
|
||||
if (/^(\/upload)?\/drive\/v3\/files$/.test(url.pathname) && init.method === "POST") return Response.json({ id: "file2", name: "Notes", mimeType: "application/vnd.google-apps.folder" });
|
||||
if (url.pathname === "/v1/documents/doc1") return Response.json(googleDocument(BENIGN_BODY));
|
||||
if (url.pathname === "/v1/documents/doc1:batchUpdate") return Response.json({ documentId: "doc1", replies: [{}], writeControl: { requiredRevisionId: "rev-2" } });
|
||||
if (url.pathname.startsWith("/v4/spreadsheets/sheet1/values/") && init.method === "PUT") {
|
||||
return Response.json({ spreadsheetId: "sheet1", updatedRange: "Sheet1!A1:B1", updatedRows: 1, updatedColumns: 2, updatedCells: 2 });
|
||||
}
|
||||
if (url.pathname.startsWith("/v4/spreadsheets/sheet1/values/")) return Response.json({ range: "Sheet1!A1:B1", majorDimension: "ROWS", values: [["Owner", "Sam"]] });
|
||||
if (url.pathname === "/v1/presentations/deck1:batchUpdate") return Response.json({ presentationId: "deck1", replies: [{}], writeControl: { requiredRevisionId: "rev-2" } });
|
||||
if (url.pathname === "/v1/presentations/deck1") return Response.json({ presentationId: "deck1", title: "Deck", revisionId: "rev-1", slides: [] });
|
||||
if (url.pathname === "/calendar/v3/calendars/primary/events") return Response.json({ items: [] });
|
||||
if (url.pathname === "/calendar/v3/freeBusy") return Response.json({ calendars: { primary: { busy: [] } } });
|
||||
if (url.pathname === "/gmail/v1/users/me/profile") return Response.json({ emailAddress: "owner@example.test", messagesTotal: 1 });
|
||||
@@ -132,7 +181,9 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
const result = body.method === "initialize"
|
||||
? { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "google-fixture", version: "1" } }
|
||||
: body.method === "tools/list"
|
||||
? { tools: (MCP_TOOLS[url.hostname] ?? []).map((name) => ({ name, inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint: name !== "create_draft" } })) }
|
||||
? { tools: (MCP_TOOLS[url.hostname] ?? []).map((name) => ({ name, description: `Google's ${name}.`,
|
||||
inputSchema: GOOGLE_MCP_SCHEMAS[name] ?? { type: "object", properties: {} },
|
||||
annotations: { readOnlyHint: name !== "create_draft" && name !== "update_doc" } })) }
|
||||
: { content: [{ type: "text", text: "ok from Google MCP" }] };
|
||||
return Response.json({ jsonrpc: "2.0", id: body.id, result });
|
||||
});
|
||||
@@ -154,7 +205,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: `Inbox ${randomUUID()}`, role: "engineer",
|
||||
adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning();
|
||||
await service.finishGalleryAppConnection(company!.id, connected.connectionId, {
|
||||
enabledCatalogEntryIds: completed.catalog.map((entry) => entry.id),
|
||||
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);
|
||||
@@ -177,20 +228,22 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
eq(connectionGrants.connectionId, connected.connectionId), eq(connectionGrants.status, "active"))))[0];
|
||||
return {
|
||||
company: company!, actor, agent: agent!, service, gateway, session, connector, connectionId: connected.connectionId, catalog: completed.catalog,
|
||||
gmailRequests, mcpRequests, remoteHttpRequest, toolNamed, call, grant,
|
||||
setGmail: (override: typeof gmailOverride) => { gmailOverride = override; },
|
||||
restRequests, mcpRequests, remoteHttpRequest, toolNamed, call, grant,
|
||||
setGoogle: (override: typeof restOverride) => { restOverride = override; },
|
||||
setMessageBody: (body: string) => { messageBody = body; },
|
||||
setMcpCall: (override: typeof mcpCallOverride) => { mcpCallOverride = override; },
|
||||
invocations: () => db.select().from(toolInvocations).where(eq(toolInvocations.companyId, company!.id)),
|
||||
};
|
||||
}
|
||||
|
||||
describe("with the default transport map", () => {
|
||||
it("sends every Google call to Google's MCP servers and never calls the REST adapter", async () => {
|
||||
describe("with a service switched back to google_mcp", () => {
|
||||
it("sends that service's calls to Google's MCP server and never calls the REST adapter", async () => {
|
||||
useTransport("gmail", "google_mcp");
|
||||
useTransport("docs", "google_mcp");
|
||||
const f = await connectWorkspace();
|
||||
await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" });
|
||||
expect(f.mcpRequests).toContain("gmailmcp.googleapis.com tools/call get_message");
|
||||
expect(f.gmailRequests).toEqual([]);
|
||||
expect(f.restRequests).toEqual([]);
|
||||
expect(restDispatch.callGoogleWorkspaceRest).not.toHaveBeenCalled();
|
||||
expect(restDispatch.probeGoogleWorkspaceRest).not.toHaveBeenCalled();
|
||||
expect(restDispatch.listGoogleWorkspaceRest).not.toHaveBeenCalled();
|
||||
@@ -203,9 +256,8 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
const f = await connectWorkspace();
|
||||
expect(f.catalog.map((entry) => entry.toolName).sort()).toEqual(gmailCatalog(true));
|
||||
expect(f.catalog.find((entry) => entry.toolName === "gmail__create_draft")?.riskLevel).toBe("write");
|
||||
expect(f.mcpRequests.some((request) => request.startsWith("gmailmcp."))).toBe(false);
|
||||
expect(f.mcpRequests).toContain("docsmcp.googleapis.com tools/list");
|
||||
expect(f.gmailRequests).toEqual([expect.objectContaining({ method: "GET", path: "/gmail/v1/users/me/profile", authorization: "Bearer workspace-access-1" })]);
|
||||
expect(f.mcpRequests).toEqual([]);
|
||||
expect(f.restRequests).toEqual([expect.objectContaining({ method: "GET", path: "/gmail/v1/users/me/profile", authorization: "Bearer workspace-access-1" })]);
|
||||
|
||||
const readOnly = await connectWorkspace({ permissions: ["gmail.readonly", "documents.readonly"] });
|
||||
expect(readOnly.catalog.map((entry) => entry.toolName).sort()).toEqual(gmailCatalog(false));
|
||||
@@ -214,11 +266,11 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
it("runs a Gmail read in process with the caller's token, screens it, and audits it", async () => {
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace();
|
||||
f.gmailRequests.length = 0;
|
||||
f.restRequests.length = 0;
|
||||
const result = await f.call("gmail__get_message", { messageId: "msg1" });
|
||||
expect(result.status).toBe("completed");
|
||||
expect(JSON.stringify(result.result)).toContain("Lunch is moved to Thursday");
|
||||
expect(f.gmailRequests).toEqual([expect.objectContaining({ method: "GET", path: "/gmail/v1/users/me/messages/msg1", authorization: "Bearer workspace-access-1" })]);
|
||||
expect(f.restRequests).toEqual([expect.objectContaining({ method: "GET", path: "/gmail/v1/users/me/messages/msg1", authorization: "Bearer workspace-access-1" })]);
|
||||
expect(f.mcpRequests.some((request) => request.includes("tools/call"))).toBe(false);
|
||||
expect(restDispatch.callGoogleWorkspaceRest).toHaveBeenCalledOnce();
|
||||
const [invocation] = await f.invocations();
|
||||
@@ -232,14 +284,14 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
it("asks for approval before creating a draft and creates it over REST once approved", async () => {
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace({ askFirst: ["gmail__create_draft"] });
|
||||
f.gmailRequests.length = 0;
|
||||
f.restRequests.length = 0;
|
||||
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.gmailRequests).toEqual([]);
|
||||
expect(f.restRequests).toEqual([]);
|
||||
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.gmailRequests).toEqual([expect.objectContaining({ method: "POST", path: "/gmail/v1/users/me/drafts" })]);
|
||||
expect(f.restRequests).toEqual([expect.objectContaining({ method: "POST", path: "/gmail/v1/users/me/drafts" })]);
|
||||
const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, action!.invocationId));
|
||||
expect(invocation).toMatchObject({ status: "succeeded" });
|
||||
expect(JSON.stringify(invocation!.resultSummary)).toContain("draft1");
|
||||
@@ -248,7 +300,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
it("refuses a tool the grant does not cover, and rechecks consent before every dispatch", async () => {
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace();
|
||||
f.gmailRequests.length = 0;
|
||||
f.restRequests.length = 0;
|
||||
const tool = await f.toolNamed("gmail__get_message");
|
||||
const grant = await f.grant();
|
||||
const narrowTo = (permissions: string[]) => db.update(connectionGrants)
|
||||
@@ -261,14 +313,14 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
await narrowTo(["documents.readonly"]);
|
||||
await expect(f.gateway.executeTool({ sessionToken: f.session.token, tool: tool.name, parameters: { messageId: "msg1" } }))
|
||||
.rejects.toMatchObject({ reasonCode: "oauth_insufficient_scope" });
|
||||
expect(f.gmailRequests).toEqual([]);
|
||||
expect(f.restRequests).toEqual([]);
|
||||
expect(restDispatch.callGoogleWorkspaceRest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("maps Google's insufficient-scope answer to the gateway's scope error", async () => {
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace();
|
||||
f.setGmail((url) => url.pathname.includes("/messages/")
|
||||
f.setGoogle((url) => url.pathname.includes("/messages/")
|
||||
? Response.json({ error: { code: 403, status: "PERMISSION_DENIED", errors: [{ reason: "insufficientPermissions" }] } }, { status: 403 })
|
||||
: undefined);
|
||||
await expect(f.call("gmail__get_message", { messageId: "msg1" })).rejects.toMatchObject({ status: 403, reasonCode: "oauth_insufficient_scope" });
|
||||
@@ -277,20 +329,20 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
it("refreshes the token after Google rejects it, never replays the call, and the explicit retry uses the new token", async () => {
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace();
|
||||
f.gmailRequests.length = 0;
|
||||
f.restRequests.length = 0;
|
||||
let rejectNext = true;
|
||||
f.setGmail((url) => {
|
||||
f.setGoogle((url) => {
|
||||
if (!url.pathname.includes("/messages/") || !rejectNext) return undefined;
|
||||
rejectNext = false;
|
||||
return Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 });
|
||||
});
|
||||
const refreshesBefore = vi.mocked(f.connector.refresh).mock.calls.length;
|
||||
await expect(f.call("gmail__get_message", { messageId: "msg1" })).rejects.toMatchObject({ status: 409, reasonCode: "oauth_refreshed_retry_required" });
|
||||
expect(f.gmailRequests).toHaveLength(1);
|
||||
expect(f.restRequests).toHaveLength(1);
|
||||
expect(vi.mocked(f.connector.refresh).mock.calls.length).toBeGreaterThan(refreshesBefore);
|
||||
await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" });
|
||||
expect(f.gmailRequests).toHaveLength(2);
|
||||
expect(f.gmailRequests[1]!.authorization).not.toBe(f.gmailRequests[0]!.authorization);
|
||||
expect(f.restRequests).toHaveLength(2);
|
||||
expect(f.restRequests[1]!.authorization).not.toBe(f.restRequests[0]!.authorization);
|
||||
});
|
||||
|
||||
it("blocks an injected email before the agent sees it", async () => {
|
||||
@@ -330,12 +382,12 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace();
|
||||
f.setMessageBody(`${BENIGN_BODY}\n`.repeat(Math.ceil(520_000 / (BENIGN_BODY.length + 1))));
|
||||
f.gmailRequests.length = 0;
|
||||
f.restRequests.length = 0;
|
||||
await expect(f.call("gmail__get_message", { messageId: "msg1" })).rejects.toMatchObject({
|
||||
status: 502, reasonCode: "tool_error",
|
||||
message: expect.stringMatching(new RegExp(`more than the ${GOOGLE_WORKSPACE_REST_MAX_RESULT_BYTES.toLocaleString("en-US")} bytes this tool can return, so it was not returned\\. Read it with messageFormat METADATA_ONLY or MINIMAL`)),
|
||||
});
|
||||
expect(f.gmailRequests).toHaveLength(1);
|
||||
expect(f.restRequests).toHaveLength(1);
|
||||
expect(vi.mocked(restDispatch.callGoogleWorkspaceRest).mock.calls[0]![0].maxResultBytes).toBe(GOOGLE_WORKSPACE_REST_MAX_RESULT_BYTES);
|
||||
});
|
||||
|
||||
@@ -343,7 +395,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace();
|
||||
let observed: AbortSignal | undefined;
|
||||
f.setGmail((url, init) => url.pathname.includes("/messages/") ? new Promise<Response>((_resolve, reject) => {
|
||||
f.setGoogle((url, init) => url.pathname.includes("/messages/") ? new Promise<Response>((_resolve, reject) => {
|
||||
observed = init.signal ?? undefined;
|
||||
init.signal?.addEventListener("abort", () => reject(init.signal!.reason), { once: true });
|
||||
}) : undefined);
|
||||
@@ -355,17 +407,17 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace();
|
||||
const tool = await f.toolNamed("gmail__get_message");
|
||||
f.gmailRequests.length = 0;
|
||||
f.restRequests.length = 0;
|
||||
await instanceSettingsService(db).updateExperimental({ enableGoogleWorkspaceConnector: false });
|
||||
await expect(f.gateway.executeTool({ sessionToken: f.session.token, tool: tool.name, parameters: { messageId: "msg1" } })).rejects.toBeTruthy();
|
||||
await expect(f.service.refreshCatalog(f.connectionId, f.actor)).rejects.toBeTruthy();
|
||||
expect(f.gmailRequests).toEqual([]);
|
||||
expect(f.restRequests).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps other services usable when the Gmail probe fails, and restores Gmail once it passes", async () => {
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace();
|
||||
f.setGmail((url) => url.pathname.endsWith("/profile") ? Response.json({ error: { code: 403, errors: [{ reason: "accessNotConfigured" }] } }, { status: 403 }) : undefined);
|
||||
f.setGoogle((url) => url.pathname.endsWith("/profile") ? Response.json({ error: { code: 403, errors: [{ reason: "accessNotConfigured" }] } }, { status: 403 }) : undefined);
|
||||
const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor);
|
||||
expect(refreshed.connection).toMatchObject({ healthStatus: "ok", healthMessage: expect.stringContaining("gmail") });
|
||||
expect(refreshed.catalog.map((entry) => entry.toolName)).toEqual(["docs__read_doc"]);
|
||||
@@ -374,7 +426,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
const events = await db.select().from(toolAccessAuditEvents).where(eq(toolAccessAuditEvents.connectionId, f.connectionId));
|
||||
expect(events).toContainEqual(expect.objectContaining({ reasonCode: "google_workspace_service_unavailable", details: { service: "gmail" } }));
|
||||
await expect(f.call("docs__read_doc", { documentId: "doc1" })).resolves.toMatchObject({ status: "completed" });
|
||||
f.setGmail(undefined);
|
||||
f.setGoogle(undefined);
|
||||
const recovered = await f.service.refreshCatalog(f.connectionId, f.actor);
|
||||
expect(recovered.catalog.map((entry) => entry.toolName).sort()).toEqual(gmailCatalog(true));
|
||||
});
|
||||
@@ -383,7 +435,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace();
|
||||
const refreshesBefore = vi.mocked(f.connector.refresh).mock.calls.length;
|
||||
f.setGmail(() => Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 }));
|
||||
f.setGoogle(() => Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 }));
|
||||
await expect(f.service.refreshCatalog(f.connectionId, f.actor)).rejects.toMatchObject({ details: { code: "oauth_reauthorization_required" } });
|
||||
expect(vi.mocked(f.connector.refresh).mock.calls.length).toBeGreaterThan(refreshesBefore);
|
||||
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connectionId));
|
||||
@@ -399,7 +451,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
it("warns that a timed-out draft may already exist, in the error, the invocation and the audit", async () => {
|
||||
useTransport("gmail", transport);
|
||||
const f = await connectWorkspace();
|
||||
f.setGmail((url, init) => url.pathname.endsWith("/drafts") ? hang(init) : undefined);
|
||||
f.setGoogle((url, init) => url.pathname.endsWith("/drafts") ? hang(init) : undefined);
|
||||
f.setMcpCall((init) => JSON.parse(String(init.body)).params?.name === "create_draft" ? hang(init) : undefined);
|
||||
await expect(f.call("gmail__create_draft", { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." }, { timeoutMs: 100 }))
|
||||
.rejects.toMatchObject({ status: 504, reasonCode: "tool_timeout", message: expect.stringContaining(UNCERTAIN) });
|
||||
@@ -413,16 +465,216 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
it("returns the uncertain-write warning from an approved REST draft whose request was lost", async () => {
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace({ askFirst: ["gmail__create_draft"] });
|
||||
f.setGmail((url) => url.pathname.endsWith("/drafts") ? Promise.reject(new TypeError("socket hang up")) : undefined);
|
||||
f.setGoogle((url) => url.pathname.endsWith("/drafts") ? Promise.reject(new TypeError("socket hang up")) : undefined);
|
||||
await expect(f.call("gmail__create_draft", { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." }))
|
||||
.rejects.toMatchObject({ reasonCode: "approval_required" });
|
||||
const [action] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, f.company.id));
|
||||
const approved = await f.gateway.approveActionRequest({ companyId: f.company.id, actionRequestId: action!.id, actor: { userId: f.actor.actorId } });
|
||||
expect(JSON.stringify(approved)).toContain("may or may not have been made");
|
||||
});
|
||||
describe("the six launch services on paperclip_rest", () => {
|
||||
const LAUNCH_SERVICES = ["gmail", "drive", "docs", "sheets", "slides", "calendar"] as const;
|
||||
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 = (services: readonly GoogleWorkspaceService[], keep: (name: string) => boolean = () => true) =>
|
||||
services.flatMap((service) => googleWorkspaceServiceToolNames(service).map((name) => `${service}__${name}`)).filter(keep).sort();
|
||||
const names = (catalog: Array<{ toolName: string }>) => catalog.map((entry) => entry.toolName).sort();
|
||||
const REVISION = { requiredRevisionId: "rev-1" };
|
||||
const READS: Array<[string, Record<string, unknown>, string]> = [
|
||||
["gmail__get_message", { messageId: "msg1" }, "gmail.googleapis.com GET /gmail/v1/users/me/messages/msg1"],
|
||||
["drive__get_file_metadata", { fileId: "file1" }, "www.googleapis.com GET /drive/v3/files/file1"],
|
||||
["docs__read_doc", { documentId: "doc1" }, "docs.googleapis.com GET /v1/documents/doc1"],
|
||||
["sheets__get_values", { spreadsheetId: "sheet1", range: "Sheet1!A1:B1" }, "sheets.googleapis.com GET /v4/spreadsheets/sheet1/values/Sheet1!A1%3AB1"],
|
||||
["slides__read_presentation", { presentationId: "deck1" }, "slides.googleapis.com GET /v1/presentations/deck1"],
|
||||
["calendar__list_calendars", {}, "www.googleapis.com GET /calendar/v3/users/me/calendarList"],
|
||||
];
|
||||
const WRITES: Array<[string, Record<string, unknown>, string]> = [
|
||||
["gmail__create_draft", { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." }, "gmail.googleapis.com POST /gmail/v1/users/me/drafts"],
|
||||
["drive__create_file", { title: "Notes", mimeType: "application/vnd.google-apps.folder" }, "www.googleapis.com POST /drive/v3/files"],
|
||||
["docs__update_doc", { documentId: "doc1", requests: [{ insertText: { text: "Hi", location: { index: 1 } } }], writeControl: REVISION }, "docs.googleapis.com POST /v1/documents/doc1:batchUpdate"],
|
||||
["sheets__update_values", { spreadsheetId: "sheet1", range: "Sheet1!A1:B1", values: [["Owner", "Sam"]] }, "sheets.googleapis.com PUT /v4/spreadsheets/sheet1/values/Sheet1!A1%3AB1"],
|
||||
["slides__update_presentation", { presentationId: "deck1", requests: [{ createSlide: {} }], writeControl: REVISION }, "slides.googleapis.com POST /v1/presentations/deck1:batchUpdate"],
|
||||
["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", () => {
|
||||
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" });
|
||||
});
|
||||
|
||||
it("lists all 36 allowlisted actions for a full read & write grant without contacting a Google MCP server", async () => {
|
||||
const f = await connectWorkspace({ permissions: DEFAULT_PERMISSIONS });
|
||||
expect(names(f.catalog)).toEqual(allowlisted(LAUNCH_SERVICES));
|
||||
expect(f.catalog).toHaveLength(36);
|
||||
expect(names(f.catalog)).toEqual(expect.arrayContaining(["gmail__list_threads", "gmail__search_messages"]));
|
||||
expect(f.mcpRequests).toEqual([]);
|
||||
expect(f.restRequests.map((request) => `${request.host} ${request.path}`).sort()).toEqual([
|
||||
"gmail.googleapis.com /gmail/v1/users/me/profile", "www.googleapis.com /calendar/v3/users/me/calendarList", "www.googleapis.com /drive/v3/about",
|
||||
]);
|
||||
expect((await f.gateway.listToolsForSession(f.session.token)).filter((tool) => tool.connectionId === f.connectionId)).toHaveLength(36);
|
||||
});
|
||||
|
||||
it("lists only the read actions for a read-only grant", async () => {
|
||||
const f = await connectWorkspace({ permissions: READ_ONLY_PERMISSIONS });
|
||||
const writes = new Set(WRITES.map(([name]) => name).concat("calendar__update_event", "calendar__delete_event", "calendar__respond_to_event",
|
||||
"drive__copy_file", "sheets__update_spreadsheet", "sheets__update_formulas", "sheets__insert_dimension"));
|
||||
expect(names(f.catalog)).toEqual(allowlisted(LAUNCH_SERVICES, (name) => !writes.has(name)));
|
||||
expect(f.catalog).toHaveLength(23);
|
||||
expect(f.catalog.every((entry) => entry.riskLevel === "read")).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Gmail read & write", ["gmail.readonly", "gmail.compose"], allowlisted(["gmail"])],
|
||||
["Drive read only", ["drive.readonly", "documents.readonly", "spreadsheets.readonly", "presentations.readonly"],
|
||||
allowlisted(["drive", "docs", "sheets", "slides"], (name) => /__(read|get|list|search|download)/.test(name))],
|
||||
["Drive read & write", ["drive.readonly", "drive.file", "documents.readonly", "documents", "spreadsheets.readonly", "spreadsheets", "presentations.readonly", "presentations"],
|
||||
allowlisted(["drive", "docs", "sheets", "slides"])],
|
||||
["Calendar read & write", ["calendar.calendarlist.readonly", "calendar.events", "calendar.events.freebusy"], allowlisted(["calendar"])],
|
||||
])("lists exactly the %s group's actions", async (_label, permissions, expected) => {
|
||||
const f = await connectWorkspace({ permissions });
|
||||
expect(names(f.catalog)).toEqual(expected);
|
||||
expect(f.mcpRequests).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([...READS, ...WRITES])("runs %s through executeTool over REST, with the default Allowed policy, and audits it", async (name, parameters, request) => {
|
||||
const f = await connectWorkspace({ permissions: DEFAULT_PERMISSIONS });
|
||||
f.restRequests.length = 0;
|
||||
const result = await f.call(name, parameters);
|
||||
expect(result.status).toBe("completed");
|
||||
expect(f.restRequests.map((sent) => `${sent.host} ${sent.method} ${sent.path}`)).toEqual([request.replace(/\?.*$/, "")]);
|
||||
expect(f.restRequests[0]!.authorization).toBe("Bearer workspace-access-1");
|
||||
expect(f.mcpRequests).toEqual([]);
|
||||
expect(restDispatch.callGoogleWorkspaceRest).toHaveBeenCalledWith(expect.objectContaining({ service: name.split("__")[0], toolName: name.split("__")[1] }));
|
||||
await expect(db.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, f.company.id))).resolves.toEqual([]);
|
||||
const [invocation] = await f.invocations();
|
||||
expect(invocation).toMatchObject({ status: "succeeded", errorCode: null, connectionId: f.connectionId });
|
||||
const events = await db.select().from(toolCallEvents).where(eq(toolCallEvents.invocationId, invocation!.id));
|
||||
expect(events.filter((event) => event.eventType === "call_completed")).toEqual([expect.objectContaining({ connectionId: f.connectionId })]);
|
||||
const audit = await db.select().from(toolAccessAuditEvents).where(and(eq(toolAccessAuditEvents.companyId, f.company.id), eq(toolAccessAuditEvents.action, "call_completed")));
|
||||
expect(audit).toHaveLength(1);
|
||||
expect(JSON.stringify(audit[0])).toContain("Google Workspace REST");
|
||||
expect(JSON.stringify(audit[0])).toContain(`paperclip-rest:google-workspace/${name.split("__")[0]}`);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["docs__read_doc", { documentId: "doc1" }, (url: URL) => url.pathname === "/v1/documents/doc1" ? Response.json(googleDocument(INJECTED_BODY)) : undefined],
|
||||
["sheets__get_values", { spreadsheetId: "sheet1", range: "Sheet1!A1:B1" },
|
||||
(url: URL) => url.hostname === "sheets.googleapis.com" ? Response.json({ range: "Sheet1!A1:B1", majorDimension: "ROWS", values: [[INJECTED_BODY]] }) : undefined],
|
||||
["slides__read_presentation", { presentationId: "deck1" }, (url: URL) => url.pathname === "/v1/presentations/deck1"
|
||||
? Response.json({ presentationId: "deck1", title: INJECTED_BODY, revisionId: "rev-1", slides: [] }) : undefined],
|
||||
["drive__get_file_metadata", { fileId: "file1" }, (url: URL) => url.pathname === "/drive/v3/files/file1"
|
||||
? Response.json({ id: "file1", name: "Plan", mimeType: "text/plain", description: INJECTED_BODY }) : undefined],
|
||||
["calendar__list_calendars", {}, (url: URL) => url.pathname === "/calendar/v3/users/me/calendarList"
|
||||
? Response.json({ items: [{ id: "primary", summary: "Team", description: INJECTED_BODY }] }) : undefined],
|
||||
] as const)("blocks injected instructions returned by %s over REST", async (name, parameters, answer) => {
|
||||
const f = await connectWorkspace({ permissions: DEFAULT_PERMISSIONS });
|
||||
f.setGoogle(answer);
|
||||
await expect(f.call(name, parameters)).rejects.toMatchObject({ status: 422, reasonCode: "prompt_injection_blocked" });
|
||||
const [invocation] = await f.invocations();
|
||||
expect(invocation).toMatchObject({ status: "failed", errorCode: "prompt_injection_blocked" });
|
||||
expect(JSON.stringify(invocation)).not.toContain("ignore all previous instructions");
|
||||
});
|
||||
|
||||
it("keeps an existing connection's actions usable when its services move from Google's MCP servers to REST", async () => {
|
||||
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);
|
||||
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([]);
|
||||
f.restRequests.length = 0;
|
||||
await expect(f.call("gmail__list_threads", { labelIds: ["INBOX"] })).resolves.toMatchObject({ status: "completed" });
|
||||
await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" });
|
||||
expect(f.restRequests.map((request) => request.path)).toContain("/gmail/v1/users/me/messages/msg1");
|
||||
});
|
||||
|
||||
it("advertises the REST definitions to agents for a connection saved with Google's MCP schemas, with no refresh, and the edit succeeds", async () => {
|
||||
for (const service of LAUNCH_SERVICES) useTransport(service, "google_mcp");
|
||||
const f = await connectWorkspace({ permissions: ["gmail.readonly", "documents.readonly", "documents"] });
|
||||
const saved = f.catalog.find((entry) => entry.toolName === "docs__update_doc")!;
|
||||
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);
|
||||
f.restRequests.length = 0;
|
||||
const refreshesBefore = f.mcpRequests.length;
|
||||
|
||||
const update = await f.toolNamed("docs__update_doc");
|
||||
const restDefinition = restDispatch.listGoogleWorkspaceRest("docs").find((tool) => tool.name === "update_doc")!;
|
||||
expect(update.parametersSchema).toEqual(restDefinition.inputSchema);
|
||||
expect((update.parametersSchema as { required: string[] }).required).toContain("writeControl");
|
||||
expect(update.description).toBe(restDefinition.description);
|
||||
expect(update.displayName).toBe("Docs: Edit a document");
|
||||
expect(update.description).toContain("requiredRevisionId");
|
||||
const read = await f.toolNamed("docs__read_doc");
|
||||
expect(read.parametersSchema).toEqual(restDispatch.listGoogleWorkspaceRest("docs").find((tool) => tool.name === "read_doc")!.inputSchema);
|
||||
|
||||
const document = await f.call("docs__read_doc", { documentId: "doc1" });
|
||||
expect(JSON.stringify(document.result)).toContain("rev-1");
|
||||
await expect(f.call("docs__update_doc", { documentId: "doc1", requests: [{ insertText: { text: "Hi", location: { index: 1 } } }],
|
||||
writeControl: { requiredRevisionId: "rev-1" } })).resolves.toMatchObject({ status: "completed" });
|
||||
expect(f.restRequests.map((request) => `${request.method} ${request.path}`)).toEqual(["GET /v1/documents/doc1", "POST /v1/documents/doc1:batchUpdate"]);
|
||||
expect(f.mcpRequests).toHaveLength(refreshesBefore);
|
||||
});
|
||||
|
||||
it("on the first refresh after the switch, releases actions held for review and keeps Off and Ask first", async () => {
|
||||
for (const service of LAUNCH_SERVICES) useTransport(service, "google_mcp");
|
||||
const f = await connectWorkspace({ off: ["gmail__search_threads"], askFirst: ["gmail__create_draft"] });
|
||||
const held = f.catalog.find((entry) => entry.toolName === "gmail__get_message")!;
|
||||
await db.update(toolCatalogEntries).set({ status: "quarantined", quarantineReason: "pending_review", quarantinedAt: new Date() })
|
||||
.where(eq(toolCatalogEntries.id, held.id));
|
||||
const listed = async () => (await f.gateway.listToolsForSession(f.session.token))
|
||||
.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);
|
||||
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([]);
|
||||
const after = await listed();
|
||||
expect(after).toContain("gmail__get_message");
|
||||
expect(after).not.toContain("gmail__search_threads");
|
||||
await expect(f.call("gmail__get_message", { messageId: "msg1" })).resolves.toMatchObject({ status: "completed" });
|
||||
await expect(f.call("gmail__create_draft", { to: ["sam@example.test"], subject: "Thursday", body: "Thursday works." }))
|
||||
.rejects.toMatchObject({ reasonCode: "approval_required" });
|
||||
});
|
||||
|
||||
it("keeps an action that is both Off and held for review Off, and one that is both Ask first and held for review Ask first", async () => {
|
||||
for (const service of LAUNCH_SERVICES) useTransport(service, "google_mcp");
|
||||
const f = await connectWorkspace({ off: ["gmail__get_message"], askFirst: ["gmail__create_draft"] });
|
||||
const held = f.catalog.filter((entry) => entry.toolName === "gmail__get_message" || entry.toolName === "gmail__create_draft").map((entry) => entry.id);
|
||||
expect(held).toHaveLength(2);
|
||||
await db.update(toolCatalogEntries).set({ status: "quarantined", quarantineReason: "pending_review", quarantinedAt: new Date() })
|
||||
.where(inArray(toolCatalogEntries.id, held));
|
||||
const listed = async () => (await f.gateway.listToolsForSession(f.session.token))
|
||||
.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);
|
||||
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);
|
||||
expect(refreshed.catalog.filter((entry) => held.includes(entry.id))).toEqual([
|
||||
expect.objectContaining({ status: "active" }), expect.objectContaining({ status: "active" }),
|
||||
]);
|
||||
const after = await listed();
|
||||
expect(after).not.toContain("gmail__get_message");
|
||||
expect(after).toContain("gmail__create_draft");
|
||||
expect(after).toEqual(expect.arrayContaining(["gmail__list_threads", "gmail__search_messages"]));
|
||||
await expect(f.call("gmail__create_draft", draft)).rejects.toMatchObject({ reasonCode: "approval_required" });
|
||||
}
|
||||
expect(f.restRequests.filter((request) => request.path.endsWith("/drafts") || request.path.endsWith("/messages/msg1"))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("probing only with what the grant allows", () => {
|
||||
const calendarTools = (catalog: Array<{ toolName: string }>) => catalog.map((entry) => entry.toolName).filter((name) => name.startsWith("calendar__")).sort();
|
||||
const restPaths = (f: Awaited<ReturnType<typeof connectWorkspace>>) => f.gmailRequests.map((request) => request.path);
|
||||
const restPaths = (f: Awaited<ReturnType<typeof connectWorkspace>>) => f.restRequests.map((request) => request.path);
|
||||
|
||||
it.each([
|
||||
[["calendar.events"], "/calendar/v3/calendars/primary/events",
|
||||
@@ -442,13 +694,13 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
useTransport("gmail", "paperclip_rest");
|
||||
const f = await connectWorkspace({ permissions: ["gmail.compose", "documents.readonly"] });
|
||||
expect(f.catalog.map((entry) => entry.toolName).sort()).toEqual(["docs__read_doc", "gmail__create_draft"]);
|
||||
expect(f.gmailRequests).toEqual([]);
|
||||
expect(f.restRequests).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a service whose probe answers with insufficient scope", async () => {
|
||||
useTransport("calendar", "paperclip_rest");
|
||||
const f = await connectWorkspace({ permissions: ["calendar.calendarlist.readonly", "calendar.events", "documents.readonly"] });
|
||||
f.setGmail((url) => url.pathname.startsWith("/calendar/") ? Response.json({ error: { code: 403, errors: [{ reason: "insufficientPermissions" }] } }, { status: 403 }) : undefined);
|
||||
f.setGoogle((url) => url.pathname.startsWith("/calendar/") ? Response.json({ error: { code: 403, errors: [{ reason: "insufficientPermissions" }] } }, { status: 403 }) : undefined);
|
||||
const refreshed = await f.service.refreshCatalog(f.connectionId, f.actor);
|
||||
expect(refreshed.connection.healthMessage ?? "").not.toContain("calendar");
|
||||
expect(calendarTools(refreshed.catalog)).toContain("calendar__list_calendars");
|
||||
@@ -458,7 +710,7 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
it("drops nothing but asks for reconnection when Google rejects a revoked Calendar token", async () => {
|
||||
useTransport("calendar", "paperclip_rest");
|
||||
const f = await connectWorkspace({ permissions: ["calendar.events", "documents.readonly"] });
|
||||
f.setGmail((url) => url.pathname.startsWith("/calendar/") ? Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 }) : undefined);
|
||||
f.setGoogle((url) => url.pathname.startsWith("/calendar/") ? Response.json({ error: { code: 401, status: "UNAUTHENTICATED" } }, { status: 401 }) : undefined);
|
||||
await expect(f.service.refreshCatalog(f.connectionId, f.actor)).rejects.toMatchObject({ details: { code: "oauth_reauthorization_required" } });
|
||||
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, f.connectionId));
|
||||
expect(grant!.status).toBe("needs_reauthorization");
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { onTestFinished } from "vitest";
|
||||
import { GOOGLE_WORKSPACE_TOOL_TRANSPORT, type GoogleWorkspaceService } from "@paperclipai/shared";
|
||||
|
||||
export function useGoogleMcpTransport() {
|
||||
const saved = { ...GOOGLE_WORKSPACE_TOOL_TRANSPORT };
|
||||
for (const service of Object.keys(saved) as GoogleWorkspaceService[]) GOOGLE_WORKSPACE_TOOL_TRANSPORT[service] = "google_mcp";
|
||||
onTestFinished(() => {
|
||||
Object.assign(GOOGLE_WORKSPACE_TOOL_TRANSPORT, saved);
|
||||
});
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
@@ -79,6 +80,7 @@ import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { useGoogleMcpTransport } from "./helpers/google-workspace-transport.js";
|
||||
import {
|
||||
classifyRisk,
|
||||
normalizeConnectionMethodConfig,
|
||||
@@ -2999,6 +3001,7 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
["with", ["calendar.calendarlist.readonly", "calendar.events", "calendar.events.freebusy"]],
|
||||
["without", ["calendar.calendarlist.readonly", "calendar.events"]],
|
||||
] as const)("asks for free/busy with read and write Calendar and keeps Calendar working %s it", async (_label, granted) => {
|
||||
useGoogleMcpTransport();
|
||||
const company = await createCompany(db);
|
||||
const userId = `workspace-calendar-${randomUUID()}`;
|
||||
await grantBoardUser(db, company.id, userId, [], "owner");
|
||||
@@ -8846,6 +8849,7 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
});
|
||||
|
||||
it.each(["user", "organization"] as const)("builds one Workspace catalog from actual partial consent for a %s grant", async (grantKind) => {
|
||||
useGoogleMcpTransport();
|
||||
const company = await createCompany(db);
|
||||
const userId = `workspace-member-${randomUUID()}`;
|
||||
await grantBoardUser(db, company.id, userId, [], "owner");
|
||||
@@ -8884,6 +8888,7 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
});
|
||||
|
||||
describe("combined Workspace service isolation and refresh consent", () => {
|
||||
beforeEach(() => useGoogleMcpTransport());
|
||||
async function connectWorkspace(mode: "managed" | "customer", permissions = ["documents.readonly", "gmail.readonly"]) {
|
||||
const company = await createCompany(db);
|
||||
const userId = `workspace-refresh-${randomUUID()}`;
|
||||
|
||||
@@ -69,6 +69,7 @@ import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { useGoogleMcpTransport } from "./helpers/google-workspace-transport.js";
|
||||
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
||||
@@ -3308,6 +3309,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
["people__get_user_profile", "userinfo.profile", "people"],
|
||||
["search__search_corpus", null, "workspacemcp"],
|
||||
] as const)("routes %s and denies cached actions after consent changes", async (toolName, permission, host) => {
|
||||
useGoogleMcpTransport();
|
||||
const { company, agent, run } = await createRunFixture(db);
|
||||
await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: "board", status: "active", membershipRole: "owner" });
|
||||
const { connection, catalogEntry } = await createRemoteMcpToolFixture(db, company.id);
|
||||
|
||||
@@ -113,9 +113,10 @@ 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`:
|
||||
|
||||
- `google_mcp` (every service today): calls go to Google's hosted MCP server
|
||||
for that service, exactly as before this folder existed.
|
||||
- `paperclip_rest`: calls go to this folder.
|
||||
- `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.
|
||||
|
||||
`googleWorkspaceToolTarget(name)` returns the setting as `transport`. It is a
|
||||
plain constant: no environment variable, instance setting or database row.
|
||||
@@ -242,6 +243,60 @@ result and 0.24 ms for a 700 KB one.
|
||||
`google-workspace-rest-dispatch.test.ts`, fails while any service set to
|
||||
`paperclip_rest` is missing an allowlisted tool, so a partial flip cannot ship.
|
||||
|
||||
### Connections saved before a switch
|
||||
|
||||
A connection keeps the tool definitions its last catalog refresh saved. After
|
||||
a service switches to `paperclip_rest`, the saved definitions of an existing
|
||||
connection are still Google's MCP definitions. Two things keep such a
|
||||
connection working with no user action:
|
||||
|
||||
- **Agents see this folder's definitions at once.** When the gateway lists a
|
||||
connection's tools for an agent, it takes the input schema, output schema,
|
||||
description and annotations of a `paperclip_rest` tool from this folder, not
|
||||
from the saved row. It asks `paperclipDefinedTool` in
|
||||
`server/src/services/connectors/paperclip-defined-tools.ts`, which calls
|
||||
`googleWorkspaceRestToolDefinition` in the adapter.
|
||||
Routing and the advertised definition read the same transport setting in
|
||||
the same process, so an agent never gets Google's MCP schema for a call that
|
||||
goes to REST. This is an in-memory lookup: no request and no refresh before
|
||||
the turn starts.
|
||||
- **The next catalog refresh saves this folder's definitions.** Catalog
|
||||
publication asks the same `paperclipDefinedTool`. It never holds such an
|
||||
action for review, and it clears the review hold (`quarantined`,
|
||||
`pending_review`) of an action held only because a remote definition
|
||||
changed. Clearing the hold does not count the action as new, so it does not
|
||||
add the action to the connection's profile: an action a person turned Off
|
||||
(left out of the profile) stays Off, also when it was held, and an Ask first
|
||||
policy stays in force. Only actions the connection never had (Gmail
|
||||
`list_threads` and `search_messages`) get the connection's default for new
|
||||
actions.
|
||||
|
||||
The saved risk level of an action changes only on that refresh. Until then,
|
||||
`docs__update_doc`, `slides__update_presentation`, `sheets__update_spreadsheet`
|
||||
and `calendar__update_event` keep the level saved from Google's MCP
|
||||
definition (`write`); after it they are `destructive`. Write actions are
|
||||
Allowed by default at either level.
|
||||
|
||||
### Input differences an agent meets after a switch
|
||||
|
||||
Checked against Google's published MCP references, since no `tools/list`
|
||||
from Google's servers is recorded yet. These are the cases where a call that
|
||||
Google's saved schema allowed is refused by this folder; each is also stated
|
||||
in the tool's own description and schema, which agents now receive:
|
||||
|
||||
| Tool | Google's schema | This folder |
|
||||
| --- | --- | --- |
|
||||
| `docs__update_doc`, `slides__update_presentation` | `writeControl` optional; `targetRevisionId` allowed | `writeControl.requiredRevisionId` required (read the document first); `targetRevisionId` refused |
|
||||
| `docs__update_doc`, `slides__update_presentation` | any request kind | closed list of request kinds; kinds that read another file refused |
|
||||
| `sheets__update_spreadsheet` | `writeControl` allowed | `writeControl` refused (no revision check in Sheets REST) |
|
||||
| `sheets__get_spreadsheet` | `commentsIncluded: true` allowed | refused (not in the Sheets API) |
|
||||
| `sheets__insert_dimension` | `DIMENSION_UNSPECIFIED` in the enum | refused |
|
||||
| `calendar__delete_event` | a recurring series ID deletes the series | refused; pass one occurrence |
|
||||
| `gmail__create_draft` | attachments | refused, as Google's tool does today |
|
||||
| `drive__search_files` | full MCP query language and `orderBy` | terms without a Drive `q` equivalent refused; `orderBy` limited |
|
||||
|
||||
Each refusal is a tool error that says what to do, and nothing is changed.
|
||||
|
||||
## Known differences from Google's MCP tools
|
||||
|
||||
- **Descriptions** are our own wording; names, fields, types, enums, required
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { googleWorkspaceRestToolDefinition, type GoogleWorkspaceRestToolDefinition } from "../google-workspace-rest-dispatch.js";
|
||||
|
||||
export type PaperclipDefinedTool = GoogleWorkspaceRestToolDefinition;
|
||||
|
||||
type Connection = { config: Record<string, unknown> };
|
||||
|
||||
const PAPERCLIP_DEFINED_TOOL_SOURCES: ReadonlyArray<{
|
||||
matches: (connection: Connection) => boolean;
|
||||
definition: (toolName: string) => PaperclipDefinedTool | null;
|
||||
}> = [
|
||||
{ matches: (connection) => connection.config.sourceTemplateKey === "google-workspace", definition: googleWorkspaceRestToolDefinition },
|
||||
];
|
||||
|
||||
export function paperclipDefinedTool(connection: Connection, toolName: string): PaperclipDefinedTool | null {
|
||||
return PAPERCLIP_DEFINED_TOOL_SOURCES.find((source) => source.matches(connection))?.definition(toolName) ?? null;
|
||||
}
|
||||
@@ -2,8 +2,10 @@ import { GOOGLE_WORKSPACE_TOOL_TRANSPORT, googleWorkspaceServiceToolNames } from
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
callGoogleWorkspaceRest,
|
||||
googleWorkspaceRestToolDefinition,
|
||||
googleWorkspaceCatalogToolTitle,
|
||||
googleWorkspaceRestTransportGaps,
|
||||
listGoogleWorkspaceRest,
|
||||
probeGoogleWorkspaceRest,
|
||||
} from "./google-workspace-rest-dispatch.js";
|
||||
|
||||
@@ -23,6 +25,25 @@ 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 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 });
|
||||
expect(googleWorkspaceRestToolDefinition("docs__update_doc")?.inputSchema.required).toContain("writeControl");
|
||||
expect(googleWorkspaceRestToolDefinition("chat__list_messages")).toBeNull();
|
||||
expect(googleWorkspaceRestToolDefinition("gmail__send_message")).toBeNull();
|
||||
expect(googleWorkspaceRestToolDefinition("update_doc")).toBeNull();
|
||||
const saved = GOOGLE_WORKSPACE_TOOL_TRANSPORT.docs;
|
||||
GOOGLE_WORKSPACE_TOOL_TRANSPORT.docs = "google_mcp";
|
||||
try {
|
||||
expect(googleWorkspaceRestToolDefinition("docs__update_doc")).toBeNull();
|
||||
} finally {
|
||||
GOOGLE_WORKSPACE_TOOL_TRANSPORT.docs = saved;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("googleWorkspaceCatalogToolTitle", () => {
|
||||
const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
|
||||
|
||||
|
||||
@@ -43,6 +43,29 @@ export function listGoogleWorkspaceRest(service: GoogleWorkspaceService): Tool[]
|
||||
return listGoogleWorkspaceRestTools(restService(service));
|
||||
}
|
||||
|
||||
export interface GoogleWorkspaceRestToolDefinition {
|
||||
name: string;
|
||||
title: string | null;
|
||||
description: string | null;
|
||||
inputSchema: Record<string, unknown>;
|
||||
outputSchema: Record<string, unknown> | null;
|
||||
annotations: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function googleWorkspaceRestToolDefinition(toolName: string): GoogleWorkspaceRestToolDefinition | null {
|
||||
const target = googleWorkspaceToolTarget(toolName);
|
||||
if (!target || target.transport !== "paperclip_rest" || !isGoogleWorkspaceRestService(target.service)) return null;
|
||||
const tool = listGoogleWorkspaceRestTools(target.service).find((candidate) => candidate.name === target.leaf);
|
||||
return tool ? {
|
||||
name: tool.name,
|
||||
title: googleWorkspaceCatalogToolTitle("google-workspace", toolName, tool.title),
|
||||
description: tool.description ?? null,
|
||||
inputSchema: { ...tool.inputSchema },
|
||||
outputSchema: tool.outputSchema ? { ...tool.outputSchema } : null,
|
||||
annotations: { ...tool.annotations },
|
||||
} : null;
|
||||
}
|
||||
|
||||
export function googleWorkspaceCatalogToolTitle(
|
||||
sourceTemplateKey: unknown,
|
||||
name: string,
|
||||
|
||||
@@ -12,6 +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 { googleWorkspaceToolTarget, googleWorkspaceGrantedScopes, isGoogleWorkspaceToolGranted } from "@paperclipai/shared";
|
||||
import { retainMcpConnectionFailure } from "../../mcp-connection-failure.js";
|
||||
import { isRemoteMcpConnectorMethod } from "@paperclipai/shared";
|
||||
@@ -185,6 +186,7 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection
|
||||
}
|
||||
const catalogValues: Array<typeof toolCatalogEntries.$inferInsert> = [];
|
||||
let quarantinedCount = 0;
|
||||
const releasedNames = new Set<string>();
|
||||
const sourceTemplateKey =
|
||||
typeof asRecord(connection.config).sourceTemplateKey === "string"
|
||||
? String(asRecord(connection.config).sourceTemplateKey)
|
||||
@@ -232,8 +234,11 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection
|
||||
const changed =
|
||||
existing &&
|
||||
(existing.versionHash !== hash || existing.schemaHash !== schemaHash);
|
||||
const paperclipDefined = paperclipDefinedTool(connection, descriptor.name) !== null;
|
||||
if (paperclipDefined && existing?.status === "quarantined") releasedNames.add(descriptor.name);
|
||||
const shouldQuarantine =
|
||||
quarantineOnRefresh &&
|
||||
!paperclipDefined &&
|
||||
(!existing || changed) &&
|
||||
existing?.status !== "disabled" &&
|
||||
(!safeDefault || riskLevel !== "read" || nativeProvider);
|
||||
@@ -247,7 +252,7 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection
|
||||
? "quarantined"
|
||||
: existing?.status === "disabled" && existing.quarantineReason !== "mcp_tool_removed"
|
||||
? "disabled"
|
||||
: quarantineOnRefresh && existing?.status === "quarantined"
|
||||
: quarantineOnRefresh && existing?.status === "quarantined" && !paperclipDefined
|
||||
? "quarantined"
|
||||
: "active";
|
||||
if (shouldQuarantine && !providerPermanentlyBlocked) quarantinedCount += 1;
|
||||
@@ -285,7 +290,7 @@ export function createToolCatalogPublication(db: Db, { now, audit, getConnection
|
||||
versionHash: sql`excluded.version_hash`, schemaHash: sql`excluded.schema_hash`, lastSeenAt: sql`excluded.last_seen_at`,
|
||||
quarantinedAt: sql`excluded.quarantined_at`, quarantineReason: sql`excluded.quarantine_reason`, updatedAt: sql`excluded.updated_at`,
|
||||
} }).returning();
|
||||
for (const row of rows) if (!existingNonQuarantinedNames.has(row.name)) newCatalogEntryIds.add(row.id);
|
||||
for (const row of rows) if (!existingNonQuarantinedNames.has(row.name) && !releasedNames.has(row.name)) newCatalogEntryIds.add(row.id);
|
||||
return rows;
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notificatio
|
||||
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 { paperclipDefinedTool } from "./connectors/paperclip-defined-tools.js";
|
||||
import { composeConnectionInstructions } from "./connection-instructions.js";
|
||||
import { googleWorkspaceToolTarget, googleWorkspaceGrantedScopes, isGoogleWorkspaceToolGranted } from "@paperclipai/shared";
|
||||
import { isInsufficientConnectionScope, INSUFFICIENT_CONNECTION_SCOPE_MESSAGE } from "./connection-permission-errors.js";
|
||||
@@ -2019,13 +2020,15 @@ export function createToolGatewayService(
|
||||
...(baseNameCounts.get(baseName)! > 1 ? [catalogEntry.id] : []),
|
||||
]);
|
||||
const applicationKey = application.applicationKey ?? null;
|
||||
const currentDefinition = paperclipDefinedTool(connection, catalogEntry.toolName);
|
||||
const inputSchema = projectedConnectionToolInputSchema(
|
||||
connection,
|
||||
catalogEntry.inputSchema ?? {},
|
||||
currentDefinition?.inputSchema ?? catalogEntry.inputSchema ?? {},
|
||||
catalogEntry.toolName,
|
||||
);
|
||||
const outputSchema = catalogEntry.outputSchema ?? null;
|
||||
const annotations = catalogEntry.annotations ?? {};
|
||||
const outputSchema = currentDefinition?.outputSchema ?? catalogEntry.outputSchema ?? null;
|
||||
const annotations = currentDefinition?.annotations ?? catalogEntry.annotations ?? {};
|
||||
const description = currentDefinition?.description ?? catalogEntry.description;
|
||||
const risk = riskFromCatalogEntry(catalogEntry);
|
||||
const onDemandTools = readOnDemandToolsEnabled(connection);
|
||||
const providerMetadata: ConnectedMcpGatewayMetadata = {
|
||||
@@ -2052,12 +2055,12 @@ export function createToolGatewayService(
|
||||
};
|
||||
return {
|
||||
name: gatewayToolName,
|
||||
displayName: googleWorkspaceCatalogToolTitle(connection.config.sourceTemplateKey, catalogEntry.toolName, catalogEntry.title) ?? catalogEntry.toolName,
|
||||
displayName: currentDefinition?.title ?? googleWorkspaceCatalogToolTitle(connection.config.sourceTemplateKey, catalogEntry.toolName, catalogEntry.title) ?? catalogEntry.toolName,
|
||||
description:
|
||||
gmailArchiveToolDescription(
|
||||
connection,
|
||||
catalogEntry.toolName,
|
||||
googleChatToolDescription(connection, catalogEntry.toolName, catalogEntry.description),
|
||||
googleChatToolDescription(connection, catalogEntry.toolName, description),
|
||||
) ??
|
||||
`Connected MCP tool ${catalogEntry.toolName} from ${connection.name}.`,
|
||||
parametersSchema: inputSchema,
|
||||
|
||||
@@ -267,8 +267,8 @@
|
||||
"packages/shared/src/github-connectors.ts": "b8448b1eddac9a9d1308b94e4d136c761cbd4a00",
|
||||
"packages/shared/src/github-skill-repository.ts": "b00a9963472723bcb7fcd433aae442f75d7a138b",
|
||||
"packages/shared/src/gitignore-runtime.test.ts": "e334ab0eca8faeab5807171983ec9102a3f1c734",
|
||||
"packages/shared/src/google-workspace-connectors.test.ts": "0021bf50e20076e9862b13e97f84e0e5bf5d5b35",
|
||||
"packages/shared/src/google-workspace-connectors.ts": "270fbd40c0f96e8f4140c880a2c36a3150d4b9aa",
|
||||
"packages/shared/src/google-workspace-connectors.test.ts": "26316900a50e5ab384e0dcf9c45a2bb4abc0830d",
|
||||
"packages/shared/src/google-workspace-connectors.ts": "88d942d1e66d7facc68cf8645f665cdc80c8c005",
|
||||
"packages/shared/src/grok-bot.ts": "9de68f00e7926c397729ff62bf8e277f5a41c525",
|
||||
"packages/shared/src/heartbeat-inbox.ts": "227dc89705c20460ca02194091cb162e11503186",
|
||||
"packages/shared/src/home-paths.test.ts": "81235c17c376224e1be3abd3f034a8400f079c66",
|
||||
|
||||
Reference in new issue
Block a user