diff --git a/doc/connections/GOOGLE-WORKSPACE.md b/doc/connections/GOOGLE-WORKSPACE.md index ee64fd1b2fa..c6ceef68b63 100644 --- a/doc/connections/GOOGLE-WORKSPACE.md +++ b/doc/connections/GOOGLE-WORKSPACE.md @@ -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 diff --git a/doc/memory/google-connector-memory.md b/doc/memory/google-connector-memory.md index 4cb85ab50d0..dafe7633f3b 100644 --- a/doc/memory/google-connector-memory.md +++ b/doc/memory/google-connector-memory.md @@ -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. diff --git a/packages/shared/src/google-workspace-connectors.test.ts b/packages/shared/src/google-workspace-connectors.test.ts index 0021bf50e20..26316900a50 100644 --- a/packages/shared/src/google-workspace-connectors.test.ts +++ b/packages/shared/src/google-workspace-connectors.test.ts @@ -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"]); }); diff --git a/packages/shared/src/google-workspace-connectors.ts b/packages/shared/src/google-workspace-connectors.ts index 270fbd40c0f..88d942d1e66 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: "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", }; diff --git a/server/src/__tests__/google-workspace-injection-screening.test.ts b/server/src/__tests__/google-workspace-injection-screening.test.ts index 3a7cb32e5da..a4c61a2364e 100644 --- a/server/src/__tests__/google-workspace-injection-screening.test.ts +++ b/server/src/__tests__/google-workspace-injection-screening.test.ts @@ -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; let database: Awaited>; let home: string; + const savedTransport = { ...GOOGLE_WORKSPACE_TOOL_TRANSPORT }; beforeAll(async () => { + for (const service of Object.keys(GOOGLE_WORKSPACE_TOOL_TRANSPORT) as Array) 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 }); diff --git a/server/src/__tests__/google-workspace-rest-transport.test.ts b/server/src/__tests__/google-workspace-rest-transport.test.ts index c800dddc13f..590ddfbc08b 100644 --- a/server/src/__tests__/google-workspace-rest-transport.test.ts +++ b/server/src/__tests__/google-workspace-rest-transport.test.ts @@ -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 = { "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> = { + 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 | undefined) | undefined; + let restOverride: ((url: URL, init: RequestInit) => Response | Promise | undefined) | undefined; let messageBody = BENIGN_BODY; let mcpCallOverride: ((init: RequestInit) => Promise | 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((_resolve, reject) => { + f.setGoogle((url, init) => url.pathname.includes("/messages/") ? new Promise((_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]> = [ + ["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]> = [ + ["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>) => f.gmailRequests.map((request) => request.path); + const restPaths = (f: Awaited>) => 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"); diff --git a/server/src/__tests__/helpers/google-workspace-transport.ts b/server/src/__tests__/helpers/google-workspace-transport.ts new file mode 100644 index 00000000000..6e0768e6b19 --- /dev/null +++ b/server/src/__tests__/helpers/google-workspace-transport.ts @@ -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); + }); +} diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index dad5e4c1922..15dd9b5afaa 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -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()}`; diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index b7b61a5f4f0..bfa25a92f46 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -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); diff --git a/server/src/google-workspace-rest-tools/README.md b/server/src/google-workspace-rest-tools/README.md index b84398a501b..11d2d43bf14 100644 --- a/server/src/google-workspace-rest-tools/README.md +++ b/server/src/google-workspace-rest-tools/README.md @@ -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 diff --git a/server/src/services/connectors/paperclip-defined-tools.ts b/server/src/services/connectors/paperclip-defined-tools.ts new file mode 100644 index 00000000000..673c5d4c408 --- /dev/null +++ b/server/src/services/connectors/paperclip-defined-tools.ts @@ -0,0 +1,16 @@ +import { googleWorkspaceRestToolDefinition, type GoogleWorkspaceRestToolDefinition } from "../google-workspace-rest-dispatch.js"; + +export type PaperclipDefinedTool = GoogleWorkspaceRestToolDefinition; + +type Connection = { config: Record }; + +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; +} diff --git a/server/src/services/google-workspace-rest-dispatch.test.ts b/server/src/services/google-workspace-rest-dispatch.test.ts index 1052ab144d0..05af29aa319 100644 --- a/server/src/services/google-workspace-rest-dispatch.test.ts +++ b/server/src/services/google-workspace-rest-dispatch.test.ts @@ -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; diff --git a/server/src/services/google-workspace-rest-dispatch.ts b/server/src/services/google-workspace-rest-dispatch.ts index 535224f969c..1876809efe5 100644 --- a/server/src/services/google-workspace-rest-dispatch.ts +++ b/server/src/services/google-workspace-rest-dispatch.ts @@ -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; + outputSchema: Record | null; + annotations: Record; +} + +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, diff --git a/server/src/services/tool-access/catalog/publication.ts b/server/src/services/tool-access/catalog/publication.ts index 2483655153b..d2ea419ff96 100644 --- a/server/src/services/tool-access/catalog/publication.ts +++ b/server/src/services/tool-access/catalog/publication.ts @@ -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 = []; let quarantinedCount = 0; + const releasedNames = new Set(); 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; })); } diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 508fca57d1d..b241730ae23 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -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, diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index f5711f2796e..ba205a897b5 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -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",