Files
PaperClipAI/server/src/google-workspace-rest-tools/gmail/get-message.ts
T
DottaandClaude Opus 5.5 a29658b5b7 feat(google-workspace): REST-backed Gmail tools in server/src/google-workspace-rest-tools (#22000)
## 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>
2026-11-17 08:13:01 -06:00

94 lines
3.5 KiB
TypeScript

import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { GoogleToolError } from "../errors.js";
import type { GoogleHttp, GoogleRequest } from "../google-http.js";
import { defineTool, structuredResult } from "../tool.js";
import {
bodyAttachmentRequest,
externalBodyIds,
gmailId,
SUMMARY_HEADERS,
toMcpMessage,
type GmailRestAttachment,
type GmailRestMessage,
type MessageDetail,
} from "./message.js";
import { messageSchema } from "./schemas.js";
const MESSAGE_FORMATS = ["MESSAGE_FORMAT_UNSPECIFIED", "MINIMAL", "FULL_CONTENT", "METADATA_ONLY"] as const;
const args = z.object({
messageId: gmailId,
messageFormat: z.enum(MESSAGE_FORMATS).optional(),
});
export type GetMessageArgs = z.infer<typeof args>;
export function messageDetail(format: GetMessageArgs["messageFormat"]): MessageDetail {
if (format === "MINIMAL") return "minimal";
if (format === "METADATA_ONLY") return "metadata_only";
return "full";
}
export function getMessageRequest(input: GetMessageArgs): GoogleRequest {
const detail = messageDetail(input.messageFormat);
return {
method: "GET",
host: "gmail.googleapis.com",
path: `/gmail/v1/users/me/messages/${input.messageId}`,
query: detail === "full" ? { format: "full" } : { format: "metadata", metadataHeaders: SUMMARY_HEADERS },
};
}
export function getMessageResult(
message: GmailRestMessage,
input: GetMessageArgs,
externalBodies?: ReadonlyMap<string, string>,
): CallToolResult {
return structuredResult(toMcpMessage(message, messageDetail(input.messageFormat), externalBodies));
}
async function readExternalBodies(message: GmailRestMessage, input: GetMessageArgs, http: GoogleHttp): Promise<Map<string, string>> {
const bodies = new Map<string, string>();
if (messageDetail(input.messageFormat) !== "full") return bodies;
for (const attachmentId of externalBodyIds(message.payload)) {
let answer: GmailRestAttachment;
try {
answer = await http.send<GmailRestAttachment>(bodyAttachmentRequest(input.messageId, attachmentId));
} catch (error) {
if (error instanceof GoogleToolError) {
throw new GoogleToolError("incomplete", `Could not read the full body of this message. ${error.message}`, error.httpStatus);
}
throw error;
}
if (typeof answer.data !== "string") throw new GoogleToolError("incomplete", "Could not read the full body of this message.");
bodies.set(attachmentId, answer.data);
}
return bodies;
}
export const getMessage = defineTool({
definition: {
name: "get_message",
description: "Gets one email message from the signed-in user's Gmail by message ID.",
inputSchema: {
type: "object",
properties: {
messageId: { type: "string", description: "Required. The ID of the message to get." },
messageFormat: {
type: "string",
enum: [...MESSAGE_FORMATS],
description: "Optional. How much of the message to return. MINIMAL: snippet and the Subject, From, To, Cc and Date headers. FULL_CONTENT (default): MINIMAL plus the body and attachments. METADATA_ONLY: no subject, snippet, body or attachment names.",
},
},
required: ["messageId"],
},
outputSchema: messageSchema,
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
},
args,
async run(input, http) {
const message = await http.send<GmailRestMessage>(getMessageRequest(input));
return getMessageResult(message, input, await readExternalBodies(message, input, http));
},
});