mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 04:54:00 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use Google Workspace through the built-in Google Workspace connector > - Today the connector sends each tool call to Google's hosted Workspace MCP servers > - Those servers are a Developer Preview, so we cannot offer them to the public > - The owner decided to launch on our own tools over Google's GA REST APIs, with the same tool names, inputs and results, in one folder that we can delete later > - This pull request adds that folder inside the server, with its first three Gmail tools, and a written trace of where it will plug in > - The benefit is a public-ready Gmail path that we can switch back to Google's MCP servers with one setting, with no new package to publish ## Linked Issues or Issue Description Refs #21996 (plan and working memory for the Google Workspace connector, section 9) Refs #15412 (an earlier community Gmail REST MCP server; this code follows Google's MCP tool contract instead) **Subsystem affected** Connections: the Google Workspace connector and the tool gateway. **Problem or motivation** Google's Workspace MCP servers are a Developer Preview. We cannot launch the Google Workspace connector to the public on them. **Proposed solution** Add `server/src/google-workspace-rest-tools/`. It exposes the same tools as Google's MCP servers over the GA REST APIs. It knows nothing about Paperclip. A later pull request selects it per service with one switch. **Alternatives considered** A separate npm package (it would have to be published, because the server is published) and a loopback or hosted HTTP MCP endpoint. The README explains why an in-process call is better: speed, token handling, and the egress guard, which refuses loopback addresses on public deployments. ## What Changed - New folder `server/src/google-workspace-rest-tools/` inside the existing server package. No new npm package, no new dependency, no workspace, Docker, lockfile or release change. Every changed file is in this folder. - `index.ts` is the only entry point. `boundary.test.ts` enforces that the folder imports only its own files, Node built-ins, `@modelcontextprotocol/sdk` and `zod` (both existing server dependencies; tests may also import `vitest` and `@paperclipai/shared`), and that no other server code imports the folder yet. - `google-http.ts` is the only code that calls `googleapis.com`. It sets the bearer header, allows only listed hosts, has a 20 s deadline and a 20 MB response limit, and retries a read once. It never retries a write. Every write that fails after it is sent says that the change may or may not have been made. - Token errors are thrown as `GoogleWorkspaceAuthError` (an `McpError`). 401 gives `unauthenticated`. 403 insufficient scope gives `insufficient_scope`, the code the gateway already recognizes. Other Google errors become tool error results. - Gmail tools `get_message`, `search_threads` and `create_draft`. Names, fields, types and enums follow Google's Gmail MCP reference. `create_draft` calls only `drafts.create`. There is no send tool. - `get_message` reads bodies that Gmail stores as attachments, and returns an explicit error, never a body-less `FULL_CONTENT` result. Address lists are parsed by a single-pass RFC 5322 tokenizer (`gmail/address.ts`, table-driven tests including IPv6 domain literals and malformed input); quoted search text and long draft headers are handled. - `server.ts`: a thin MCP server (`tools/list`, `tools/call`). `callGoogleWorkspaceRestTool()` is the in-process equivalent. - `allowlist.test.ts` fails if a tool is not in `toolScopes` in `packages/shared/src/google-workspace-connectors.ts`, if its read-only hint disagrees with the allowlist, or if a description names a tool the folder does not list. - `README.md`: purpose, boundary rules, the dispatch trace, the recommended in-process seam and the files the switch PR touches, known differences from Google's tools, and the removal procedure (delete the folder, set the switch to `google_mcp`). - No code comments. Explanations are in the README. ## Verification - `cd server && npx vitest run src/google-workspace-rest-tools`: 8 files, 98 tests pass. Tests use synthetic REST fixtures and a fake fetch. No network. - Each review fix has a test that fails on the revision before it (10 tests red on `d65b51d245`, 3 more red on `5d7d52ec86`). The boundary test fails when a probe file in the folder imports `../errors.js`. - `tsc --noEmit` with the server's `tsconfig.json` settings over the folder passes. - `pnpm check:module-boundaries` passes. - `pnpm verify` exits 2 because a new file under `server/src` is a broad input. Required CI supplies the broad coverage. - Local timing probe with a stubbed fetch: about 13 µs overhead per call. ## Risks - Low risk. Nothing imports the folder yet, so runtime behavior does not change. - The tool descriptions are our own wording. A contract test against a recorded `tools/list` from Google's servers comes in a later pull request. - The allowlist names three Gmail tools (`get_draft`, `list_threads`, `search_messages`) that Google's published Gmail MCP reference does not list. The README flags this. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, web fetch of Google's public reference pages). ## 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 - [x] All Paperclip CI gates are green - [x] 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>
148 lines
7.1 KiB
TypeScript
148 lines
7.1 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
import { createGoogleHttp } from "../google-http.js";
|
|
import { fakeGoogle, json } from "../fixtures/fake-google.js";
|
|
import { FULL_MESSAGE, METADATA_MESSAGE } from "./fixtures/gmail-rest.js";
|
|
import { getMessage, getMessageRequest, getMessageResult } from "./get-message.js";
|
|
|
|
describe("get_message request", () => {
|
|
it("reads the full message by default and for FULL_CONTENT", () => {
|
|
for (const messageFormat of [undefined, "FULL_CONTENT", "MESSAGE_FORMAT_UNSPECIFIED"] as const) {
|
|
expect(getMessageRequest({ messageId: "18c0ffee00000001", messageFormat })).toEqual({
|
|
method: "GET", host: "gmail.googleapis.com", path: "/gmail/v1/users/me/messages/18c0ffee00000001", query: { format: "full" },
|
|
});
|
|
}
|
|
});
|
|
|
|
it("reads only summary headers for MINIMAL and METADATA_ONLY", () => {
|
|
for (const messageFormat of ["MINIMAL", "METADATA_ONLY"] as const) {
|
|
expect(getMessageRequest({ messageId: "abc", messageFormat }).query).toEqual({
|
|
format: "metadata", metadataHeaders: ["From", "To", "Cc", "Subject", "Date"],
|
|
});
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("get_message result", () => {
|
|
it("maps a full message to Google's MCP Message", () => {
|
|
const result = getMessageResult(FULL_MESSAGE, { messageId: FULL_MESSAGE.id });
|
|
expect(result.structuredContent).toEqual({
|
|
id: "18c0ffee00000001",
|
|
snippet: "Here is the quarterly plan we discussed",
|
|
subject: "Quarterly plan",
|
|
sender: "avery@example.test",
|
|
toRecipients: ["blake@example.test", "casey@example.test"],
|
|
ccRecipients: ["drew@example.test"],
|
|
date: "2025-11-17",
|
|
plaintextBody: "Here is the quarterly plan we discussed.",
|
|
htmlBody: "<p>Here is the <b>quarterly plan</b>.</p>",
|
|
attachmentIds: ["ANGjdJ_fake_attachment_1"],
|
|
attachments: [{ id: "ANGjdJ_fake_attachment_1", mimeType: "application/pdf", filename: "plan.pdf" }],
|
|
labelIds: ["INBOX", "UNREAD", "Label_42"],
|
|
});
|
|
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual(result.structuredContent);
|
|
});
|
|
|
|
it("leaves bodies out of MINIMAL and subject and snippet out of METADATA_ONLY", () => {
|
|
const minimal = getMessageResult(METADATA_MESSAGE, { messageId: METADATA_MESSAGE.id, messageFormat: "MINIMAL" }).structuredContent;
|
|
expect(minimal).toEqual({
|
|
id: "18c0ffee00000002", snippet: "Thanks, looks good", subject: "Re: Quarterly plan", sender: "blake@example.test",
|
|
toRecipients: ["avery@example.test"], ccRecipients: [], date: "2025-11-18", labelIds: ["SENT"],
|
|
});
|
|
const metadata = getMessageResult(METADATA_MESSAGE, { messageId: METADATA_MESSAGE.id, messageFormat: "METADATA_ONLY" }).structuredContent;
|
|
expect(metadata).not.toHaveProperty("subject");
|
|
expect(metadata).not.toHaveProperty("snippet");
|
|
expect(metadata).not.toHaveProperty("plaintextBody");
|
|
});
|
|
|
|
it("reads the first plain and HTML bodies from nested multiparts", () => {
|
|
const b64 = (text: string) => Buffer.from(text, "utf8").toString("base64url");
|
|
const nested = {
|
|
id: "n1",
|
|
payload: {
|
|
mimeType: "multipart/mixed",
|
|
parts: [{
|
|
mimeType: "multipart/related",
|
|
parts: [{
|
|
mimeType: "multipart/alternative",
|
|
parts: [
|
|
{ mimeType: "text/plain", body: { data: b64("plain ü") } },
|
|
{ mimeType: "text/html", body: { data: b64("<p>html</p>") } },
|
|
],
|
|
}, { mimeType: "image/png", filename: "logo.png", headers: [{ name: "Content-Disposition", value: "inline" }], body: { attachmentId: "img1" } }],
|
|
}, { mimeType: "text/plain", filename: "notes.txt", body: { attachmentId: "att2" } }],
|
|
},
|
|
};
|
|
expect(getMessageResult(nested, { messageId: "n1" }).structuredContent).toMatchObject({
|
|
plaintextBody: "plain ü",
|
|
htmlBody: "<p>html</p>",
|
|
attachmentIds: ["img1", "att2"],
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("get_message with a body Gmail stores separately", () => {
|
|
const large = "A long body line.\n".repeat(5000);
|
|
const message = {
|
|
id: "big1",
|
|
snippet: "A long body line.",
|
|
payload: {
|
|
mimeType: "multipart/alternative",
|
|
headers: [{ name: "Subject", value: "Large" }],
|
|
parts: [
|
|
{ mimeType: "text/plain", body: { size: large.length, attachmentId: "ANGjdJ_body_plain" } },
|
|
{ mimeType: "text/html", body: { size: 12, data: Buffer.from("<p>short</p>").toString("base64url") } },
|
|
],
|
|
},
|
|
};
|
|
|
|
it("fetches the body bytes before returning FULL_CONTENT", async () => {
|
|
const { fetch, calls } = fakeGoogle(({ url }) => (url.pathname.includes("/attachments/")
|
|
? json({ size: large.length, data: Buffer.from(large).toString("base64url") })
|
|
: json(message)));
|
|
const result = await getMessage.call({ messageId: "big1" }, createGoogleHttp({ accessToken: "t", fetch }));
|
|
expect(result.isError).toBeUndefined();
|
|
expect((result.structuredContent as { plaintextBody: string }).plaintextBody).toBe(large);
|
|
expect((result.structuredContent as { htmlBody: string }).htmlBody).toBe("<p>short</p>");
|
|
expect(calls.map((call) => call.url.pathname)).toEqual([
|
|
"/gmail/v1/users/me/messages/big1",
|
|
"/gmail/v1/users/me/messages/big1/attachments/ANGjdJ_body_plain",
|
|
]);
|
|
});
|
|
|
|
it("does not fetch body bytes for MINIMAL", async () => {
|
|
const { fetch, calls } = fakeGoogle(() => json(message));
|
|
await getMessage.call({ messageId: "big1", messageFormat: "MINIMAL" }, createGoogleHttp({ accessToken: "t", fetch }));
|
|
expect(calls).toHaveLength(1);
|
|
});
|
|
|
|
it("returns an explicit error, never a body-less success, when the body cannot be read", async () => {
|
|
const { fetch } = fakeGoogle(({ url }) => (url.pathname.includes("/attachments/") ? json({ error: { code: 500 } }, 500) : json(message)));
|
|
const result = await getMessage.call({ messageId: "big1" }, createGoogleHttp({ accessToken: "t", fetch, retryDelayMs: 0 }));
|
|
expect(result.isError).toBe(true);
|
|
expect(result.structuredContent).toBeUndefined();
|
|
expect((result.content[0] as { text: string }).text).toMatch(/^Could not read the full body of this message/);
|
|
});
|
|
|
|
it("refuses to map a separately stored body that was not fetched", () => {
|
|
expect(() => getMessageResult(message, { messageId: "big1" })).toThrow(/full body/);
|
|
});
|
|
});
|
|
|
|
describe("get_message tool", () => {
|
|
it("rejects message IDs that could change the request path", async () => {
|
|
const { fetch, calls } = fakeGoogle(() => json(FULL_MESSAGE));
|
|
const http = createGoogleHttp({ accessToken: "t", fetch });
|
|
for (const messageId of ["..", "a/b", "a?b", ""]) {
|
|
const result = await getMessage.call({ messageId }, http);
|
|
expect(result.isError).toBe(true);
|
|
}
|
|
expect(calls).toHaveLength(0);
|
|
});
|
|
|
|
it("returns a tool error result when the message is missing", async () => {
|
|
const { fetch } = fakeGoogle(() => json({ error: { code: 404, message: "Requested entity was not found." } }, 404));
|
|
const result = await getMessage.call({ messageId: "missing1" }, createGoogleHttp({ accessToken: "t", fetch }));
|
|
expect(result).toEqual({ isError: true, content: [{ type: "text", text: "Google could not find that item." }] });
|
|
});
|
|
});
|