mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-19 07:42:38 +01:00
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>
This commit is contained in:
1 parent
7b1c01a8a8
commit
a29658b5b7
25 files changed
+2479
No files matched your search
@@ -0,0 +1,278 @@
|
||||
# Google Workspace REST tools
|
||||
|
||||
Paperclip's own implementation of the tools that Google's hosted Workspace MCP
|
||||
servers expose (for example `https://gmailmcp.googleapis.com/mcp/v1`), backed
|
||||
by Google's generally available REST APIs.
|
||||
|
||||
It lives in this one folder, `server/src/google-workspace-rest-tools/`, inside
|
||||
the server package. It is not a separate npm package, so nothing new is
|
||||
published.
|
||||
|
||||
This release has three Gmail tools: `get_message`, `search_threads` and
|
||||
`create_draft`. There is no send tool, and none may be added.
|
||||
|
||||
## Why this exists, and why it is temporary
|
||||
|
||||
Google's Workspace MCP servers are a Developer Preview and cannot be offered to
|
||||
the public. On 2026-11-17 the owner decided that Paperclip will launch on its
|
||||
own tools over the REST APIs. The tools are built so Paperclip can switch to
|
||||
Google's MCP servers later without a rewrite, and they live in this one folder
|
||||
so they can be deleted cleanly when that happens.
|
||||
|
||||
## Boundary rules
|
||||
|
||||
- **One entry point.** Other server code may import only `index.ts`.
|
||||
- **Isolated imports, enforced by `boundary.test.ts`.** Source files import
|
||||
only files in this folder, Node built-ins, `@modelcontextprotocol/sdk` and
|
||||
`zod` (both existing server dependencies). Test files and `fixtures/` may
|
||||
also import `vitest` and `@paperclipai/shared`. Nothing in this folder
|
||||
imports other server code. In this release nothing else in the server
|
||||
imports this folder; the test also checks that, and the switch PR relaxes
|
||||
that one check.
|
||||
- **Same tools as Google's MCP servers.** Same tool names, same input fields,
|
||||
same result shape. Names, field names, types and enums come from Google's
|
||||
published reference (Gmail:
|
||||
<https://developers.google.com/workspace/gmail/api/reference/mcp>, recorded
|
||||
2026-11-17). Where REST cannot match, the difference is listed below.
|
||||
- **Public surface is MCP only.** `index.ts` exports tool definitions (`Tool`),
|
||||
results (`CallToolResult`), an MCP server, and the MCP error thrown for token
|
||||
problems. No Google REST type is exported.
|
||||
- **Knows nothing about Paperclip.** No company, connection, grant, policy,
|
||||
audit, approval or screening code. Input is a service, a tool name,
|
||||
arguments and an access token. Output is an MCP result. Authorization, scope
|
||||
checks, approval, audit and injection screening stay with their current
|
||||
owners in the gateway.
|
||||
- **Stores nothing.** No tokens, no content, no cache. The access token is used
|
||||
for one call and dropped.
|
||||
- **One file calls Google.** `google-http.ts` is the only place that calls
|
||||
`googleapis.com`. It sets the bearer header, allows only listed hosts,
|
||||
bounds each request (20 s deadline, 20 MB response, including the body
|
||||
read), maps Google errors, and retries a read (GET) once after a network
|
||||
error or HTTP 502/503/504. **It never retries a write.** A write that fails
|
||||
after it was sent (network error, dropped connection, timeout, caller
|
||||
cancellation, HTTP 5xx, or a success answer that is too large or not JSON)
|
||||
says that the change may or may not have been made.
|
||||
- **One tool, one file.** Each tool in `gmail/` is a set of pure functions
|
||||
(arguments to REST request, REST response to MCP result) plus a short `run`
|
||||
that sequences them. The pure functions are unit tested without network.
|
||||
- **`server.ts` is thin MCP wiring:** `tools/list` and `tools/call`.
|
||||
- **The allowlist stays where it is.** `toolScopes` in
|
||||
`packages/shared/src/google-workspace-connectors.ts` is the single list of
|
||||
allowed Google tools. `allowlist.test.ts` fails if this folder implements a
|
||||
tool that is not on it, if a tool's read-only hint disagrees with the
|
||||
allowlist's write flag, or if a description names a tool this folder does
|
||||
not list.
|
||||
|
||||
### Errors
|
||||
|
||||
| Google answer | Result |
|
||||
| --- | --- |
|
||||
| 401 | Throws `GoogleWorkspaceAuthError` (`reason: "unauthenticated"`, JSON-RPC `data: { code: "unauthenticated", httpStatus: 401 }`) |
|
||||
| 403 with insufficient scope (`ACCESS_TOKEN_SCOPE_INSUFFICIENT`, `insufficientPermissions`, or `WWW-Authenticate: error="insufficient_scope"`) | Throws `GoogleWorkspaceAuthError` (`reason: "insufficient_scope"`, `data.code: "insufficient_scope"`, the value the gateway already recognizes) |
|
||||
| 403 API not enabled (`SERVICE_DISABLED`, `accessNotConfigured`) | Tool error result, without the project number |
|
||||
| Other 403, 404, 400, 429, 5xx, timeout, network failure | Tool error result (`isError: true`) with a short message |
|
||||
| Invalid arguments | Tool error result, no request sent |
|
||||
| Unknown tool | Throws `McpError` `InvalidParams` |
|
||||
|
||||
Token problems are thrown, not returned, so a caller can refresh the token or
|
||||
ask the user to reconnect exactly as it does for Google's MCP servers.
|
||||
|
||||
## How it plugs in (seam trace)
|
||||
|
||||
Traced on `origin/master` at `ca34aca777`.
|
||||
|
||||
### Today's dispatch path
|
||||
|
||||
1. **Tool name to target.** `googleWorkspaceToolTarget(name)` in
|
||||
`packages/shared/src/google-workspace-connectors.ts` turns `gmail__get_message`
|
||||
into `{ service, upstreamName, leaf, serverUrl, appSlug, requiredScopes, write }`.
|
||||
`serverUrl` comes from the closed `SERVICE_PROFILES` registry.
|
||||
2. **Discovery (`tools/list`).** `remoteTools()` in
|
||||
`server/src/services/tool-access/catalog/discovery.ts` (Google branch near
|
||||
line 130) lists each granted service by calling itself with
|
||||
`profile.serverUrl`, prefixes names with `googleWorkspaceToolName(service, …)`,
|
||||
and filters by the granted scopes. It speaks MCP over HTTP through
|
||||
`requestRemoteHttpEndpoint`, negotiating a protocol era per endpoint
|
||||
(`mcpEraKey`, saved on the connection by `saveMcpNegotiation` in
|
||||
`server/src/services/tool-access/mcp-protocol-config.ts`).
|
||||
3. **Call (`tools/call`).** `executeRemoteHttpTool()` in
|
||||
`server/src/services/tool-gateway.ts` (near line 7784) computes
|
||||
`workspaceTarget`, refuses a tool whose scopes are not granted
|
||||
(`oauth_insufficient_scope`), sets `endpoint = workspaceTarget.serverUrl`,
|
||||
builds headers with the user's `Authorization: Bearer <token>` from
|
||||
`resolveCredentialHeaders`, rechecks the grant before every dispatch, and
|
||||
posts JSON-RPC through `guardedRemoteHttpFetch`
|
||||
(`server/src/services/remote-http-fetch.ts`, behind
|
||||
`server/src/services/tool-access/remote-http.ts`). A 401 forces a token
|
||||
refresh and asks for an explicit retry; `isInsufficientConnectionScope`
|
||||
(`server/src/services/connection-permission-errors.ts`) maps a scope
|
||||
failure. The MCP result goes through `completeRemoteMcpCall` →
|
||||
`normalizeMcpToolResult`. Prompt-injection screening, audit and invocation
|
||||
records happen in the caller of `executeRemoteHttpTool`, so they apply to any
|
||||
result it returns.
|
||||
4. **MCP Tasks.** The background task path (near line 7578) also reads
|
||||
`workspaceTarget.serverUrl`. It only runs for calls a remote server turned
|
||||
into a task; REST calls never do.
|
||||
|
||||
The gateway speaks MCP `2026-07-28` (stateless) first, then the legacy
|
||||
handshake versions `2025-11-25`, `2025-06-18`, `2025-03-26` and `2024-11-05`
|
||||
(`server/src/services/mcp-http.ts`). The MCP SDK the server uses (1.31) speaks
|
||||
the legacy versions only, so over HTTP every new session would pay a failed
|
||||
modern probe plus an `initialize` round trip.
|
||||
|
||||
### Recommendation: call it in process
|
||||
|
||||
The code already runs in the server process, so the gateway calls
|
||||
`callGoogleWorkspaceRestTool()` and `listGoogleWorkspaceRestTools()` directly,
|
||||
the way it already runs other REST-backed tool sets (`restConnectorFor` in
|
||||
`server/src/services/connectors/rest-registry.ts` and
|
||||
`nativeProviderCatalogFor` in `server/src/services/native-provider-catalogs.ts`).
|
||||
No loopback or hosted MCP endpoint.
|
||||
|
||||
- **Speed.** Measured locally: about 13 µs of overhead per call with a stubbed
|
||||
fetch. The MCP SDK and zod are already loaded by the server, so there is no
|
||||
extra cold-start cost beyond this folder's own modules. An HTTP hop would
|
||||
add a connection, JSON-RPC framing, and the protocol probe and handshake
|
||||
above to every call. `tools/list` becomes a static list: no network, no token.
|
||||
- **Token handling.** The token stays in the server process and goes only to
|
||||
Google.
|
||||
- **Self-hosted and Cloud run the same code.** Nothing to deploy, configure or
|
||||
publish. A loopback endpoint would not work on authenticated public
|
||||
deployments: `allowPrivateRemoteEndpoints()` refuses loopback addresses there.
|
||||
- **Egress stays guarded.** The gateway passes its `guardedRemoteHttpFetch` as
|
||||
the `fetch` option, so calls to Google go through the same egress policy as
|
||||
today.
|
||||
- **Swap-back is unchanged.** Tool names, inputs and results are Google's, so
|
||||
the catalog, policies, approvals and audit records written under
|
||||
`paperclip_rest` stay valid under `google_mcp`.
|
||||
|
||||
`createGoogleWorkspaceRestServer()` (a standard MCP server that reads the token
|
||||
from the transport's auth info) stays available if an HTTP or stdio
|
||||
deployment is ever needed; the in-process path does not use it.
|
||||
|
||||
### The switch (follow-up PR, not this one)
|
||||
|
||||
One per-service setting in `packages/shared/src/google-workspace-connectors.ts`:
|
||||
|
||||
```ts
|
||||
export const GOOGLE_WORKSPACE_TOOL_TRANSPORT: Record<GoogleWorkspaceService, "google_mcp" | "paperclip_rest"> = {
|
||||
gmail: "paperclip_rest", drive: "google_mcp", /* … */
|
||||
};
|
||||
```
|
||||
|
||||
`googleWorkspaceToolTarget()` returns it as `transport`. Files the follow-up
|
||||
touches:
|
||||
|
||||
- `packages/shared/src/google-workspace-connectors.ts`: the setting above, and
|
||||
`transport` on the target.
|
||||
- One new server adapter outside this folder, for example
|
||||
`server/src/services/google-workspace-rest-dispatch.ts`, the only importer of
|
||||
`server/src/google-workspace-rest-tools/index.ts`. It strips `Bearer ` from
|
||||
the resolved `Authorization` header, passes the guarded fetch and the call's
|
||||
deadline signal, and maps `GoogleWorkspaceAuthError` to the gateway's existing
|
||||
outcomes (`unauthenticated` to the forced refresh plus
|
||||
`oauth_refreshed_retry_required`; `insufficient_scope` to
|
||||
`oauth_insufficient_scope`).
|
||||
- `server/src/services/tool-gateway.ts`, `executeRemoteHttpTool`: after the
|
||||
grant checks and before `endpoint` is chosen, when
|
||||
`workspaceTarget.transport === "paperclip_rest"`, recheck the grant (as
|
||||
`dispatchRemote` does), call the adapter, and return through
|
||||
`normalizeMcpToolResult(result, "mcp_http", false, sourceTemplateKey)`.
|
||||
- `server/src/services/tool-access/catalog/discovery.ts`, the Google branch of
|
||||
`remoteTools`: for a `paperclip_rest` service, use the adapter's static tool
|
||||
list instead of an HTTP `tools/list`.
|
||||
- `boundary.test.ts`: allow that one adapter as the only importer.
|
||||
|
||||
No dependency, workspace, Docker or release change is needed. Everything else
|
||||
(picker, scopes, grant checks, allowlist, approval, audit, injection
|
||||
screening, risk classification in `catalog/descriptors.ts`) only knows tool
|
||||
names and scopes and needs no change.
|
||||
|
||||
## Known differences from Google's MCP tools
|
||||
|
||||
- **Descriptions** are our own wording; names, fields, types, enums, required
|
||||
fields and annotations follow Google's reference. Until a tool lands here,
|
||||
descriptions do not mention it: Google's text points to `get_thread` and
|
||||
`list_labels`, ours points to `get_message` and does not name a label tool.
|
||||
A contract test against a recorded `tools/list` from Google's servers is
|
||||
planned once a listing is recorded on the enrolled internal account.
|
||||
- **Result envelope.** Results carry the object both as `structuredContent`
|
||||
and as JSON text. Google's exact envelope has not been recorded yet.
|
||||
- **`date`** is the UTC calendar date of Gmail's `internalDate`. Google does
|
||||
not say which time zone it uses.
|
||||
- **`sender` and recipients** are plain addresses parsed from the headers;
|
||||
display names are dropped. Bodies are decoded as UTF-8.
|
||||
- **Large bodies.** Gmail can store a body part separately and return only
|
||||
its `attachmentId`. With `FULL_CONTENT`, `get_message` reads those bytes
|
||||
(`users.messages.attachments.get`) before it answers. The first `text/plain`
|
||||
and first `text/html` body parts are found depth first through nested
|
||||
multiparts. If a body part cannot be read, the call returns a tool error that
|
||||
starts with "Could not read the full body of this message"; it never returns
|
||||
a result without the body. Google's reference does not say what its tool
|
||||
does here.
|
||||
- **Addresses** come from `gmail/address.ts`, a small single-pass tokenizer
|
||||
over RFC 5322 address lists. It tracks quoted strings with escapes, nested
|
||||
comments, angle brackets and square-bracket domain literals (so
|
||||
`ops@[IPv6:2001:db8::1]` stays whole), drops comments and display names,
|
||||
returns the members of groups without the group name, and returns nothing
|
||||
for an empty group such as `undisclosed-recipients:;`. Malformed input gives
|
||||
a best-effort list and never throws. Google's reference does not say how its
|
||||
tools parse these headers.
|
||||
- **`labelIds`** keeps user labels and the system labels Google lists (INBOX,
|
||||
SPAM, TRASH, UNREAD, STARRED, IMPORTANT, SENT, DRAFT, CHAT); category labels
|
||||
are dropped.
|
||||
- **`search_threads`** makes one `threads.list` call and then one
|
||||
`threads.get` per thread (10 at a time), so a 50-thread page is 51 requests.
|
||||
A thread deleted between the two calls is left out. `pageSize` above 50 is
|
||||
capped at 50. Drafts are excluded by adding `-in:draft` unless the query
|
||||
itself uses `in:draft`, `is:draft` or `in:anywhere` outside quoted text;
|
||||
`includeTrash` uses `includeSpamTrash` plus `-in:spam`, with the same rule
|
||||
for `in:spam`. When terms are added, the caller's query is wrapped in
|
||||
parentheses first. Google's reference documents the default exclusions but
|
||||
not how its tool applies them.
|
||||
- **`create_draft`**: for a reply, the draft is threaded (`threadId`,
|
||||
`In-Reply-To`, `References`) and an empty subject becomes `Re: <original>`,
|
||||
but the original message is not quoted under the new body as Google's tool
|
||||
does, and recipients are not filled in from the original: pass `to`. The
|
||||
result is built from the request and Google's `drafts.create` answer,
|
||||
without a second read; `date` is the creation date (UTC). Attachments are
|
||||
refused, as Google's tool currently does. Long subjects and recipient lists
|
||||
are folded onto continuation lines (RFC 5322); non-ASCII subjects and single
|
||||
words longer than 900 characters become RFC 2047 encoded-words. Google's
|
||||
reference sets no length limits.
|
||||
- **Errors** for Google failures are tool error results with our own short
|
||||
messages, not Google's raw error text (except for 400 and 403 messages,
|
||||
trimmed to one line).
|
||||
|
||||
## Open questions
|
||||
|
||||
- The Gmail allowlist in `toolScopes` names `get_draft`, `list_threads` and
|
||||
`search_messages`, which Google's published Gmail MCP reference does not list
|
||||
(it lists `create_draft`, `get_message`, `get_thread`, `label_message`,
|
||||
`label_thread`, `list_drafts`, `list_labels`, `search_threads`,
|
||||
`unlabel_message` and `unlabel_thread`). Those three have no Google schema to
|
||||
copy, so they would not survive a switch back to `google_mcp`.
|
||||
- Whether an OAuth client marked as an AI-powered agent may call the REST APIs.
|
||||
- Each Google Cloud project behind a connection needs the REST APIs enabled
|
||||
(Gmail now; Drive, Docs, Sheets, Slides and Calendar as their tools land).
|
||||
Without that, calls return the `api_disabled` tool error.
|
||||
- With `paperclip_rest`, `tools/list` no longer proves the token works. A live
|
||||
health check needs a cheap REST probe (for example Gmail `users.getProfile`).
|
||||
|
||||
## Removal procedure
|
||||
|
||||
1. Set every service in `GOOGLE_WORKSPACE_TOOL_TRANSPORT` to `google_mcp`.
|
||||
2. Delete this folder, `server/src/google-workspace-rest-tools/`.
|
||||
3. Delete the server adapter that imports it and its two call sites (gateway
|
||||
and discovery).
|
||||
4. Check that the build, typecheck and tests pass, then delete the setting
|
||||
itself if nothing else uses it.
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
cd server && npx vitest run src/google-workspace-rest-tools
|
||||
```
|
||||
|
||||
Test fixtures in `fixtures/` and `gmail/fixtures/` are synthetic, in the shape
|
||||
of Google's REST responses. They contain no real mail, addresses or IDs.
|
||||
@@ -0,0 +1,45 @@
|
||||
import { googleWorkspaceToolName, googleWorkspaceToolTarget } from "@paperclipai/shared";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { GOOGLE_WORKSPACE_REST_SERVICES, listGoogleWorkspaceRestTools } from "./tools.js";
|
||||
|
||||
describe("tool allowlist", () => {
|
||||
for (const service of GOOGLE_WORKSPACE_REST_SERVICES) {
|
||||
for (const tool of listGoogleWorkspaceRestTools(service)) {
|
||||
it(`${service} ${tool.name} is on the reviewed allowlist, with matching read/write intent`, () => {
|
||||
const target = googleWorkspaceToolTarget(googleWorkspaceToolName(service, tool.name));
|
||||
expect(target, `${tool.name} is not in toolScopes.${service}`).not.toBeNull();
|
||||
expect(target!.leaf).toBe(tool.name);
|
||||
expect(tool.annotations?.readOnlyHint).toBe(!target!.write);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
it("mentions only tools this package lists in any description", () => {
|
||||
for (const service of GOOGLE_WORKSPACE_REST_SERVICES) {
|
||||
const tools = listGoogleWorkspaceRestTools(service);
|
||||
const names = new Set(tools.map((tool) => tool.name));
|
||||
const descriptions: string[] = [];
|
||||
const collect = (value: unknown) => {
|
||||
if (Array.isArray(value)) value.forEach(collect);
|
||||
else if (value && typeof value === "object") {
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
if (key === "description" && typeof item === "string") descriptions.push(item);
|
||||
else collect(item);
|
||||
}
|
||||
}
|
||||
};
|
||||
tools.forEach(collect);
|
||||
const mentioned = descriptions.flatMap((text) => text.match(/\b[a-z]+(?:_[a-z]+)+\b(?!:)/g) ?? []);
|
||||
expect(mentioned.filter((name) => !names.has(name))).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it("implements no send tool", () => {
|
||||
const names = GOOGLE_WORKSPACE_REST_SERVICES.flatMap((service) => listGoogleWorkspaceRestTools(service).map((tool) => tool.name));
|
||||
expect(names.filter((name) => /send/i.test(name))).toEqual([]);
|
||||
});
|
||||
|
||||
it("implements the Gmail tools of this release", () => {
|
||||
expect(listGoogleWorkspaceRestTools("gmail").map((tool) => tool.name)).toEqual(["get_message", "search_threads", "create_draft"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { builtinModules } from "node:module";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const folder = path.dirname(fileURLToPath(import.meta.url));
|
||||
const serverSrc = path.dirname(folder);
|
||||
|
||||
function typescriptFiles(directory: string): string[] {
|
||||
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
||||
if (entry.name === "node_modules") return [];
|
||||
const full = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) return typescriptFiles(full);
|
||||
return entry.name.endsWith(".ts") ? [full] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function importSpecifiers(source: string): string[] {
|
||||
const patterns = [/\bfrom\s+["']([^"']+)["']/g, /\bimport\s*\(\s*["']([^"']+)["']\s*\)/g, /^\s*import\s+["']([^"']+)["']/gm];
|
||||
return patterns.flatMap((pattern) => [...source.matchAll(pattern)].map((match) => match[1]!));
|
||||
}
|
||||
|
||||
const builtins = new Set(builtinModules);
|
||||
const isBuiltin = (specifier: string) => specifier.startsWith("node:") || builtins.has(specifier);
|
||||
const isTestSupport = (file: string) => file.endsWith(".test.ts") || file.split(path.sep).includes("fixtures");
|
||||
|
||||
function disallowedImports(file: string): string[] {
|
||||
return importSpecifiers(readFileSync(file, "utf8")).filter((specifier) => {
|
||||
if (specifier.startsWith(".")) {
|
||||
const target = path.resolve(path.dirname(file), specifier);
|
||||
return !(target === folder || target.startsWith(`${folder}${path.sep}`));
|
||||
}
|
||||
if (isBuiltin(specifier)) return false;
|
||||
if (specifier === "@modelcontextprotocol/sdk" || specifier.startsWith("@modelcontextprotocol/sdk/")) return false;
|
||||
if (specifier === "zod") return false;
|
||||
if (isTestSupport(file) && (specifier === "vitest" || specifier === "@paperclipai/shared")) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
describe("google-workspace-rest-tools boundary", () => {
|
||||
it("imports only its own files, Node built-ins, the MCP SDK and zod", () => {
|
||||
const violations = typescriptFiles(folder)
|
||||
.map((file) => ({ file: path.relative(folder, file), imports: disallowedImports(file) }))
|
||||
.filter((entry) => entry.imports.length > 0);
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
it("is not imported by any other server code yet", () => {
|
||||
const importers = typescriptFiles(serverSrc)
|
||||
.filter((file) => !file.startsWith(`${folder}${path.sep}`))
|
||||
.filter((file) => importSpecifiers(readFileSync(file, "utf8")).some((specifier) => specifier.includes("google-workspace-rest-tools")))
|
||||
.map((file) => path.relative(serverSrc, file));
|
||||
expect(importers).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { McpError } from "@modelcontextprotocol/sdk/types.js";
|
||||
|
||||
export const GOOGLE_AUTH_ERROR_CODE = -32050;
|
||||
|
||||
export type GoogleAuthFailure = "unauthenticated" | "insufficient_scope";
|
||||
|
||||
export class GoogleWorkspaceAuthError extends McpError {
|
||||
readonly reason: GoogleAuthFailure;
|
||||
readonly httpStatus: 401 | 403;
|
||||
|
||||
constructor(reason: GoogleAuthFailure) {
|
||||
const httpStatus = reason === "unauthenticated" ? 401 : 403;
|
||||
super(
|
||||
GOOGLE_AUTH_ERROR_CODE,
|
||||
reason === "unauthenticated"
|
||||
? "Google did not accept the access token. Reconnect Google Workspace."
|
||||
: "Google Workspace has not granted the permission this action needs. Reconnect Google Workspace and allow it.",
|
||||
{ code: reason, httpStatus },
|
||||
);
|
||||
this.name = "GoogleWorkspaceAuthError";
|
||||
this.reason = reason;
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
}
|
||||
|
||||
export type GoogleToolErrorKind =
|
||||
| "invalid_argument"
|
||||
| "not_found"
|
||||
| "permission_denied"
|
||||
| "api_disabled"
|
||||
| "rate_limited"
|
||||
| "unavailable"
|
||||
| "timeout"
|
||||
| "network"
|
||||
| "invalid_response"
|
||||
| "unsupported"
|
||||
| "incomplete";
|
||||
|
||||
export class GoogleToolError extends Error {
|
||||
readonly kind: GoogleToolErrorKind;
|
||||
readonly httpStatus: number | null;
|
||||
|
||||
constructor(kind: GoogleToolErrorKind, message: string, httpStatus: number | null = null) {
|
||||
super(message);
|
||||
this.name = "GoogleToolError";
|
||||
this.kind = kind;
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { GoogleFetch } from "../google-http.js";
|
||||
|
||||
export interface RecordedCall {
|
||||
method: string;
|
||||
url: URL;
|
||||
headers: Record<string, string>;
|
||||
body: unknown;
|
||||
}
|
||||
|
||||
export type Route = (call: RecordedCall) => Response | Promise<Response>;
|
||||
|
||||
export function json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });
|
||||
}
|
||||
|
||||
export function fakeGoogle(route: Route): { fetch: GoogleFetch; calls: RecordedCall[] } {
|
||||
const calls: RecordedCall[] = [];
|
||||
const fetch: GoogleFetch = async (url, init) => {
|
||||
const call: RecordedCall = {
|
||||
method: init.method ?? "GET",
|
||||
url: new URL(url),
|
||||
headers: Object.fromEntries(new Headers(init.headers).entries()),
|
||||
body: typeof init.body === "string" ? JSON.parse(init.body) : undefined,
|
||||
};
|
||||
calls.push(call);
|
||||
return route(call);
|
||||
};
|
||||
return { fetch, calls };
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseAddressList } from "./address.js";
|
||||
|
||||
const cases: Array<[string, string | undefined, string[]]> = [
|
||||
["no header", undefined, []],
|
||||
["empty header", "", []],
|
||||
["plain address", "a@example.test", ["a@example.test"]],
|
||||
["display name with angle address", "Avery Example <avery@example.test>", ["avery@example.test"]],
|
||||
["quoted display name with a comma", "\"Doe, Drew\" <drew@example.test>", ["drew@example.test"]],
|
||||
["quoted display name with a colon", "\"Odd: name\" <d@example.test>", ["d@example.test"]],
|
||||
["quoted display name with an escaped quote", "\"Al \\\"Ace\\\" Ray\" <al@example.test>", ["al@example.test"]],
|
||||
["quoted local part with a space, bare", "\"john doe\"@example.test", ["\"john doe\"@example.test"]],
|
||||
["quoted local part with a space, in angle brackets", "John <\"john doe\"@example.test>", ["\"john doe\"@example.test"]],
|
||||
["quoted local part with an escaped quote, bare", "\"a\\\"b\"@example.test", ["\"a\\\"b\"@example.test"]],
|
||||
["quoted local part with an escaped quote, in angle brackets", "<\"a\\\"b\"@example.test>", ["\"a\\\"b\"@example.test"]],
|
||||
["quoted local part with an escaped backslash, bare", "\"a\\\\b c\"@example.test", ["\"a\\\\b c\"@example.test"]],
|
||||
["quoted local part with an escaped backslash, in angle brackets", "X <\"a\\\\b c\"@example.test>", ["\"a\\\\b c\"@example.test"]],
|
||||
["bare address with folding space around the at-sign", "a @ example.test", ["a@example.test"]],
|
||||
["trailing comment", "Avery <avery@example.test> (work)", ["avery@example.test"]],
|
||||
["nested comment", "blake@example.test (Blake, (home: desk))", ["blake@example.test"]],
|
||||
["comment with an escaped parenthesis", "c@example.test (a \\) b)", ["c@example.test"]],
|
||||
["group with two members", "Team: a@example.test, Bea <b@example.test>;", ["a@example.test", "b@example.test"]],
|
||||
["empty group", "undisclosed-recipients:;", []],
|
||||
["group then a mailbox", "Team: a@example.test;, c@example.test", ["a@example.test", "c@example.test"]],
|
||||
["IPv6 domain literal, bare", "ops@[IPv6:2001:db8::1]", ["ops@[IPv6:2001:db8::1]"]],
|
||||
["IPv6 domain literal, in angle brackets", "Ops <ops@[IPv6:2001:db8::1]>", ["ops@[IPv6:2001:db8::1]"]],
|
||||
["IPv6 domain literal inside a group", "Lab: ops@[IPv6:2001:db8::1];", ["ops@[IPv6:2001:db8::1]"]],
|
||||
["source route in angle brackets", "<@relay.example.test:e@example.test>", ["e@example.test"]],
|
||||
[
|
||||
"mixed list",
|
||||
"\"Doe, Drew\" <drew@example.test>, e@example.test (x), Team: f@example.test, \"G: H\" <g@example.test>;, ops@[IPv6:2001:db8::1]",
|
||||
["drew@example.test", "e@example.test", "f@example.test", "g@example.test", "ops@[IPv6:2001:db8::1]"],
|
||||
],
|
||||
["unclosed angle bracket", "Avery <avery@example.test", ["avery@example.test"]],
|
||||
["unclosed quote", "\"Avery <avery@example.test>", ["avery@example.test"]],
|
||||
["unclosed comment", "a@example.test (oops", ["a@example.test"]],
|
||||
["unclosed domain literal", "ops@[IPv6:2001:db8::1", ["ops@[IPv6:2001:db8::1"]],
|
||||
["stray separators", ",,;; ,", []],
|
||||
["name without an address", "Just A Name", []],
|
||||
];
|
||||
|
||||
describe("parseAddressList", () => {
|
||||
it.each(cases)("%s", (_name, header, expected) => {
|
||||
expect(parseAddressList(header)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("never throws on arbitrary input", () => {
|
||||
const alphabet = ["a", "@", ".", ",", ";", ":", "<", ">", "(", ")", "[", "]", "\"", "\\", " ", "é"];
|
||||
let seed = 7;
|
||||
for (let round = 0; round < 2000; round += 1) {
|
||||
let text = "";
|
||||
for (let index = 0; index < 24; index += 1) {
|
||||
seed = (seed * 1103515245 + 12345) % 2147483648;
|
||||
text += alphabet[seed % alphabet.length];
|
||||
}
|
||||
expect(() => parseAddressList(text)).not.toThrow();
|
||||
expect(Array.isArray(parseAddressList(text))).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
interface Mailbox {
|
||||
outside: string;
|
||||
angle: string;
|
||||
hasAngle: boolean;
|
||||
}
|
||||
|
||||
const emptyMailbox = (): Mailbox => ({ outside: "", angle: "", hasAngle: false });
|
||||
|
||||
function withoutRoute(angle: string): string {
|
||||
if (!angle.startsWith("@")) return angle;
|
||||
let bracket = false;
|
||||
for (let index = 0; index < angle.length; index += 1) {
|
||||
const char = angle[index];
|
||||
if (char === "[") bracket = true;
|
||||
else if (char === "]") bracket = false;
|
||||
else if (char === ":" && !bracket) return angle.slice(index + 1);
|
||||
}
|
||||
return angle;
|
||||
}
|
||||
|
||||
function withoutUnquotedSpace(text: string): string {
|
||||
let result = "";
|
||||
let quoted = false;
|
||||
let escaped = false;
|
||||
for (const char of text) {
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
result += char;
|
||||
continue;
|
||||
}
|
||||
if (quoted && char === "\\") {
|
||||
escaped = true;
|
||||
result += char;
|
||||
continue;
|
||||
}
|
||||
if (char === "\"") quoted = !quoted;
|
||||
if (!quoted && /\s/.test(char)) continue;
|
||||
result += char;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function mailboxAddress(mailbox: Mailbox): string | null {
|
||||
if (mailbox.hasAngle) {
|
||||
const address = withoutRoute(mailbox.angle.trim()).trim();
|
||||
return address.length > 0 ? address : null;
|
||||
}
|
||||
const address = withoutUnquotedSpace(mailbox.outside);
|
||||
const enclosed = /<([^<>]*@[^<>]*)>?/.exec(address);
|
||||
if (enclosed) return enclosed[1]!.trim();
|
||||
return address.includes("@") && !/[<>]/.test(address) ? address : null;
|
||||
}
|
||||
|
||||
export function parseAddressList(value: string | undefined): string[] {
|
||||
if (!value) return [];
|
||||
const addresses: string[] = [];
|
||||
let mailbox = emptyMailbox();
|
||||
let quoted = false;
|
||||
let comment = 0;
|
||||
let angle = false;
|
||||
let bracket = false;
|
||||
let escaped = false;
|
||||
|
||||
const append = (text: string) => {
|
||||
if (angle) mailbox.angle += text;
|
||||
else mailbox.outside += text;
|
||||
};
|
||||
const finish = () => {
|
||||
const address = mailboxAddress(mailbox);
|
||||
if (address) addresses.push(address);
|
||||
mailbox = emptyMailbox();
|
||||
};
|
||||
|
||||
for (const char of value) {
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
if (comment === 0) append(char);
|
||||
continue;
|
||||
}
|
||||
if (char === "\\" && (quoted || comment > 0 || bracket)) {
|
||||
escaped = true;
|
||||
if (comment === 0) append(char);
|
||||
continue;
|
||||
}
|
||||
if (comment > 0) {
|
||||
if (char === "(") comment += 1;
|
||||
else if (char === ")") comment -= 1;
|
||||
continue;
|
||||
}
|
||||
if (quoted) {
|
||||
append(char);
|
||||
if (char === "\"") quoted = false;
|
||||
continue;
|
||||
}
|
||||
if (bracket) {
|
||||
append(char);
|
||||
if (char === "]") bracket = false;
|
||||
continue;
|
||||
}
|
||||
if (char === "(") {
|
||||
comment = 1;
|
||||
append(" ");
|
||||
continue;
|
||||
}
|
||||
if (char === "\"") {
|
||||
quoted = true;
|
||||
append(char);
|
||||
continue;
|
||||
}
|
||||
if (char === "[") {
|
||||
bracket = true;
|
||||
append(char);
|
||||
continue;
|
||||
}
|
||||
if (angle) {
|
||||
if (char === ">") angle = false;
|
||||
else append(char);
|
||||
continue;
|
||||
}
|
||||
if (char === "<") {
|
||||
angle = true;
|
||||
mailbox.hasAngle = true;
|
||||
mailbox.angle = "";
|
||||
continue;
|
||||
}
|
||||
if (char === ":") {
|
||||
mailbox = emptyMailbox();
|
||||
continue;
|
||||
}
|
||||
if (char === "," || char === ";") {
|
||||
finish();
|
||||
continue;
|
||||
}
|
||||
append(char);
|
||||
}
|
||||
finish();
|
||||
return addresses;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createGoogleHttp } from "../google-http.js";
|
||||
import { fakeGoogle, json } from "../fixtures/fake-google.js";
|
||||
import { createDraft, createDraftRequest, createDraftResult, replyContext } from "./create-draft.js";
|
||||
import { CREATED_DRAFT, REPLY_ORIGINAL } from "./fixtures/gmail-rest.js";
|
||||
|
||||
function decodedRaw(request: ReturnType<typeof createDraftRequest>): string {
|
||||
const raw = (request.body as { message: { raw: string } }).message.raw;
|
||||
return Buffer.from(raw, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
function decodedParts(mime: string): string[] {
|
||||
return [...mime.matchAll(/Content-Transfer-Encoding: base64\r\n\r\n([A-Za-z0-9+/=\r\n]+)/g)]
|
||||
.map((match) => Buffer.from(match[1]!.replace(/\r\n/g, ""), "base64").toString("utf8"));
|
||||
}
|
||||
|
||||
describe("create_draft request", () => {
|
||||
it("creates a draft (never sends) with a plain-text body", () => {
|
||||
const request = createDraftRequest({ to: ["blake@example.test"], subject: "Hello", body: "Hi Blake" }, undefined, "b1");
|
||||
expect(request).toMatchObject({ method: "POST", host: "gmail.googleapis.com", path: "/gmail/v1/users/me/drafts" });
|
||||
const mime = decodedRaw(request);
|
||||
expect(mime).toContain("To: blake@example.test\r\n");
|
||||
expect(mime).toContain("Subject: Hello\r\n");
|
||||
expect(mime).toContain("Content-Type: text/plain; charset=\"UTF-8\"");
|
||||
expect(decodedParts(mime)).toEqual(["Hi Blake"]);
|
||||
expect((request.body as { message: Record<string, unknown> }).message).not.toHaveProperty("threadId");
|
||||
});
|
||||
|
||||
it("sends both bodies as multipart/alternative and encodes a non-ASCII subject", () => {
|
||||
const mime = decodedRaw(createDraftRequest({
|
||||
to: ["a@example.test"], cc: ["c@example.test"], bcc: ["d@example.test"],
|
||||
subject: "Plan für Q4", body: "plain", htmlBody: "<p>rich</p>",
|
||||
}, undefined, "b2"));
|
||||
expect(mime).toContain("Cc: c@example.test\r\n");
|
||||
expect(mime).toContain("Bcc: d@example.test\r\n");
|
||||
expect(mime).toContain(`Subject: =?UTF-8?B?${Buffer.from("Plan für Q4").toString("base64")}?=`);
|
||||
expect(mime).toContain("Content-Type: multipart/alternative; boundary=\"b2\"");
|
||||
expect(decodedParts(mime)).toEqual(["plain", "<p>rich</p>"]);
|
||||
});
|
||||
|
||||
it("folds a long non-ASCII subject into encoded-words of at most 75 characters", () => {
|
||||
const subject = "Résumé für das Quartal ".repeat(6).trim();
|
||||
const mime = decodedRaw(createDraftRequest({ to: ["a@example.test"], subject, body: "x" }, undefined, "b4"));
|
||||
const folded = /Subject: ((?:=\?UTF-8\?B\?[A-Za-z0-9+/=]+\?=(?:\r\n )?)+)\r\n/.exec(mime)![1]!;
|
||||
const words = folded.split("\r\n ");
|
||||
expect(words.length).toBeGreaterThan(1);
|
||||
for (const word of words) expect(word.length).toBeLessThanOrEqual(75);
|
||||
const decoded = words.map((word) => Buffer.from(word.slice(10, -2), "base64").toString("utf8")).join("");
|
||||
expect(decoded).toBe(subject);
|
||||
});
|
||||
|
||||
it("folds long ASCII subjects and long recipient lists to RFC 5322 line limits", () => {
|
||||
const subject = Array.from({ length: 140 }, (_, index) => `word${index}`).join(" ");
|
||||
const to = Array.from({ length: 100 }, (_, index) => `person.number${index}@example.test`);
|
||||
const mime = decodedRaw(createDraftRequest({ to, subject, body: "x" }, undefined, "b5"));
|
||||
const headerBlock = mime.slice(0, mime.indexOf("\r\n\r\n") + 2);
|
||||
for (const line of headerBlock.split("\r\n").slice(0, -1)) {
|
||||
expect(line.length).toBeLessThanOrEqual(78);
|
||||
expect(line.trim().length).toBeGreaterThan(0);
|
||||
}
|
||||
const unfolded = headerBlock.replace(/\r\n /g, " ");
|
||||
expect(unfolded).toContain(`Subject: ${subject}\r\n`);
|
||||
expect(unfolded).toContain(`To: ${to.join(", ")}\r\n`);
|
||||
});
|
||||
|
||||
it("encodes a single ASCII token too long for one line", () => {
|
||||
const subject = "x".repeat(990);
|
||||
const mime = decodedRaw(createDraftRequest({ subject }, undefined, "b6"));
|
||||
const headerBlock = mime.slice(0, mime.indexOf("\r\n\r\n") + 2);
|
||||
for (const line of headerBlock.split("\r\n")) expect(line.length).toBeLessThanOrEqual(78);
|
||||
const words = /Subject: ([\s\S]*?)\r\n(?! )/.exec(headerBlock)![1]!.split("\r\n ");
|
||||
expect(words.map((word) => Buffer.from(word.slice(10, -2), "base64").toString("utf8")).join("")).toBe(subject);
|
||||
});
|
||||
|
||||
it("threads a reply and defaults the subject to Re:", () => {
|
||||
const reply = replyContext(REPLY_ORIGINAL);
|
||||
expect(reply).toEqual({
|
||||
threadId: "18c0ffee00000000",
|
||||
inReplyTo: "<plan-1@mail.example.test>",
|
||||
references: "<kickoff-0@mail.example.test> <plan-1@mail.example.test>",
|
||||
subject: "Quarterly plan",
|
||||
});
|
||||
const request = createDraftRequest({ to: ["avery@example.test"], body: "Looks good" }, reply, "b3");
|
||||
expect((request.body as { message: Record<string, unknown> }).message.threadId).toBe("18c0ffee00000000");
|
||||
const mime = decodedRaw(request);
|
||||
expect(mime).toContain("Subject: Re: Quarterly plan\r\n");
|
||||
expect(mime).toContain("In-Reply-To: <plan-1@mail.example.test>\r\n");
|
||||
expect(mime).toContain("References: <kickoff-0@mail.example.test> <plan-1@mail.example.test>\r\n");
|
||||
});
|
||||
|
||||
it("drops malformed threading headers from the original message", () => {
|
||||
const reply = replyContext({ threadId: "t1", payload: { headers: [{ name: "Message-ID", value: "<a@b>\r\nBcc: x@example.test" }] } });
|
||||
expect(reply.inReplyTo).toBeUndefined();
|
||||
expect(reply.references).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("create_draft result", () => {
|
||||
it("returns Google's MCP Draft", () => {
|
||||
const input = { to: ["blake@example.test"], subject: "Hello", body: "Hi" };
|
||||
expect(createDraftResult(CREATED_DRAFT, input, undefined, new Date("2026-11-17T12:00:00Z")).structuredContent).toEqual({
|
||||
id: "r-1234567890123456789", subject: "Hello", threadId: "18c0ffee00000000",
|
||||
toRecipients: ["blake@example.test"], ccRecipients: [], bccRecipients: [], plaintextBody: "Hi", date: "2026-11-17",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("create_draft tool", () => {
|
||||
it("looks up the original for a reply, then makes exactly one drafts.create call", async () => {
|
||||
const { fetch, calls } = fakeGoogle(({ method }) => json(method === "GET" ? REPLY_ORIGINAL : CREATED_DRAFT));
|
||||
const result = await createDraft.call({ to: ["avery@example.test"], body: "Looks good", replyToMessageId: "18c0ffee00000001" },
|
||||
createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.isError).toBeUndefined();
|
||||
expect(calls.map((call) => `${call.method} ${call.url.pathname}`)).toEqual([
|
||||
"GET /gmail/v1/users/me/messages/18c0ffee00000001",
|
||||
"POST /gmail/v1/users/me/drafts",
|
||||
]);
|
||||
expect(calls.some((call) => call.url.pathname.includes("send"))).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects header injection and display-name recipients before calling Google", async () => {
|
||||
const { fetch, calls } = fakeGoogle(() => json(CREATED_DRAFT));
|
||||
const http = createGoogleHttp({ accessToken: "t", fetch });
|
||||
for (const args of [
|
||||
{ subject: "Hi\r\nBcc: x@example.test" },
|
||||
{ to: ["Blake <blake@example.test>"] },
|
||||
{ to: ["blake@example.test\r\nBcc: x@example.test"] },
|
||||
{ cc: ["a@example.test, b@example.test"] },
|
||||
{ replyToMessageId: "../send" },
|
||||
]) {
|
||||
const result = await createDraft.call(args, http);
|
||||
expect(result.isError).toBe(true);
|
||||
}
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("refuses attachments, as Google's tool does today", async () => {
|
||||
const { fetch, calls } = fakeGoogle(() => json(CREATED_DRAFT));
|
||||
const result = await createDraft.call({ to: ["a@example.test"], attachments: [{ content: "aGk=" }] }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result).toEqual({ isError: true, content: [{ type: "text", text: "Drafts with attachments are not supported yet." }] });
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("does not retry the write when Google fails", async () => {
|
||||
const { fetch, calls } = fakeGoogle(() => json({}, 503));
|
||||
const result = await createDraft.call({ to: ["a@example.test"] }, createGoogleHttp({ accessToken: "t", fetch, retryDelayMs: 0 }));
|
||||
expect(result.isError).toBe(true);
|
||||
expect(calls).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
import { GoogleToolError } from "../errors.js";
|
||||
import type { GoogleRequest } from "../google-http.js";
|
||||
import { compact, defineTool, structuredResult } from "../tool.js";
|
||||
import { gmailId, header, type GmailRestMessage } from "./message.js";
|
||||
import { buildDraftMime } from "./mime.js";
|
||||
|
||||
const plainEmail = z.string().regex(/^[^\s<>@,;"()\\]+@[^\s<>@,;"()\\]+\.[^\s<>@,;"()\\]+$/, "Must be a plain email address such as user@example.com");
|
||||
const addressList = z.array(plainEmail).max(100).optional();
|
||||
|
||||
const args = z.object({
|
||||
to: addressList,
|
||||
cc: addressList,
|
||||
bcc: addressList,
|
||||
subject: z.string().max(998).regex(/^[^\r\n]*$/, "Subject must be a single line").optional(),
|
||||
body: z.string().optional(),
|
||||
htmlBody: z.string().optional(),
|
||||
replyToMessageId: gmailId.optional(),
|
||||
attachments: z.array(z.object({
|
||||
id: z.string().optional(),
|
||||
filename: z.string().optional(),
|
||||
mimeType: z.string().optional(),
|
||||
content: z.string(),
|
||||
inline: z.boolean().optional(),
|
||||
})).optional(),
|
||||
});
|
||||
export type CreateDraftArgs = z.infer<typeof args>;
|
||||
|
||||
interface GmailRestDraft { id?: string; message?: { id?: string; threadId?: string } }
|
||||
|
||||
export interface ReplyContext {
|
||||
threadId?: string;
|
||||
inReplyTo?: string;
|
||||
references?: string;
|
||||
subject: string;
|
||||
}
|
||||
|
||||
const MESSAGE_ID_TOKEN = /^<[^<>\s]+>$/;
|
||||
|
||||
export function replyLookupRequest(messageId: string): GoogleRequest {
|
||||
return {
|
||||
method: "GET",
|
||||
host: "gmail.googleapis.com",
|
||||
path: `/gmail/v1/users/me/messages/${messageId}`,
|
||||
query: { format: "metadata", metadataHeaders: ["Message-ID", "References", "Subject"] },
|
||||
};
|
||||
}
|
||||
|
||||
export function replyContext(original: GmailRestMessage): ReplyContext {
|
||||
const messageId = header(original.payload, "Message-ID")?.trim();
|
||||
const inReplyTo = messageId && MESSAGE_ID_TOKEN.test(messageId) ? messageId : undefined;
|
||||
const references = [...(header(original.payload, "References") ?? "").split(/\s+/), inReplyTo ?? ""]
|
||||
.filter((token) => MESSAGE_ID_TOKEN.test(token));
|
||||
const subject = (header(original.payload, "Subject") ?? "").replace(/[\r\n]+/g, " ").trim();
|
||||
return {
|
||||
threadId: original.threadId,
|
||||
inReplyTo,
|
||||
references: references.length ? [...new Set(references)].join(" ") : undefined,
|
||||
subject,
|
||||
};
|
||||
}
|
||||
|
||||
export function draftSubject(input: CreateDraftArgs, reply?: ReplyContext): string {
|
||||
if (input.subject) return input.subject;
|
||||
if (!reply?.subject) return "";
|
||||
return /^re:/i.test(reply.subject) ? reply.subject : `Re: ${reply.subject}`;
|
||||
}
|
||||
|
||||
export function assertDraftSupported(input: CreateDraftArgs): void {
|
||||
if (input.attachments?.length) throw new GoogleToolError("unsupported", "Drafts with attachments are not supported yet.");
|
||||
}
|
||||
|
||||
export function createDraftRequest(input: CreateDraftArgs, reply: ReplyContext | undefined, boundary: string): GoogleRequest {
|
||||
const mime = buildDraftMime({
|
||||
to: input.to ?? [], cc: input.cc ?? [], bcc: input.bcc ?? [],
|
||||
subject: draftSubject(input, reply),
|
||||
body: input.body,
|
||||
htmlBody: input.htmlBody,
|
||||
inReplyTo: reply?.inReplyTo,
|
||||
references: reply?.references,
|
||||
boundary,
|
||||
});
|
||||
return {
|
||||
method: "POST",
|
||||
host: "gmail.googleapis.com",
|
||||
path: "/gmail/v1/users/me/drafts",
|
||||
body: { message: compact({ raw: Buffer.from(mime, "utf8").toString("base64url"), threadId: reply?.threadId }) },
|
||||
};
|
||||
}
|
||||
|
||||
export function createDraftResult(draft: GmailRestDraft, input: CreateDraftArgs, reply: ReplyContext | undefined, now: Date): CallToolResult {
|
||||
return structuredResult(compact({
|
||||
id: draft.id ?? "",
|
||||
subject: draftSubject(input, reply),
|
||||
threadId: draft.message?.threadId,
|
||||
toRecipients: input.to ?? [],
|
||||
ccRecipients: input.cc ?? [],
|
||||
bccRecipients: input.bcc ?? [],
|
||||
plaintextBody: input.body,
|
||||
date: now.toISOString().slice(0, 10),
|
||||
htmlBody: input.htmlBody,
|
||||
}));
|
||||
}
|
||||
|
||||
const recipients = (description: string) => ({ type: "array", items: { type: "string" }, description });
|
||||
|
||||
export const createDraft = defineTool({
|
||||
definition: {
|
||||
name: "create_draft",
|
||||
description: "Creates a draft email in the signed-in user's Gmail and returns it. It does not send. To draft a reply, pass the original message's ID as replyToMessageId. Attachments are not supported yet.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
to: recipients("Optional. To recipients, each a plain email address such as user@example.com. \"Name <email>\" is not supported."),
|
||||
cc: recipients("Optional. Cc recipients, each a plain email address."),
|
||||
bcc: recipients("Optional. Bcc recipients, each a plain email address."),
|
||||
subject: { type: "string", description: "Optional. The subject line. Empty when not given." },
|
||||
body: { type: "string", description: "Optional. The plain-text body. When htmlBody is also given, this is the plain-text alternative." },
|
||||
htmlBody: { type: "string", description: "The HTML body, used as the rich-text version." },
|
||||
replyToMessageId: { type: "string", description: "Optional. The ID of the message this draft replies to." },
|
||||
attachments: {
|
||||
type: "array",
|
||||
description: "Optional. Attachments, at most 25 MB in total. Not supported yet.",
|
||||
items: {
|
||||
type: "object",
|
||||
properties: {
|
||||
id: { type: "string", description: "Output only. An external attachment ID." },
|
||||
filename: { type: "string", description: "Optional. The file name shown to recipients." },
|
||||
mimeType: { type: "string", description: "Optional. IANA media type. Default application/octet-stream." },
|
||||
content: { type: "string", description: "Required. The base64-encoded content." },
|
||||
inline: { type: "boolean", description: "Optional. Show inline in the HTML body. Default false." },
|
||||
},
|
||||
required: ["content"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
outputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
id: { type: "string", description: "The draft ID." },
|
||||
subject: { type: "string", description: "The draft's subject line." },
|
||||
threadId: { type: "string", description: "The ID of the thread the draft belongs to." },
|
||||
toRecipients: recipients("To recipient email addresses."),
|
||||
ccRecipients: recipients("Cc recipient email addresses."),
|
||||
bccRecipients: recipients("Bcc recipient email addresses."),
|
||||
plaintextBody: { type: "string", description: "The plain-text body, if any." },
|
||||
date: { type: "string", description: "The draft date, ISO 8601 (YYYY-MM-DD)." },
|
||||
htmlBody: { type: "string", description: "The HTML body, if any." },
|
||||
},
|
||||
},
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
||||
},
|
||||
args,
|
||||
async run(input, http) {
|
||||
assertDraftSupported(input);
|
||||
const reply = input.replyToMessageId
|
||||
? replyContext(await http.send<GmailRestMessage>(replyLookupRequest(input.replyToMessageId)))
|
||||
: undefined;
|
||||
const draft = await http.send<GmailRestDraft>(createDraftRequest(input, reply, `paperclip-${randomBytes(12).toString("hex")}`));
|
||||
return createDraftResult(draft, input, reply, new Date());
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
const b64 = (text: string) => Buffer.from(text, "utf8").toString("base64url");
|
||||
|
||||
export const FULL_MESSAGE = {
|
||||
id: "18c0ffee00000001",
|
||||
threadId: "18c0ffee00000000",
|
||||
labelIds: ["INBOX", "UNREAD", "CATEGORY_PERSONAL", "Label_42"],
|
||||
snippet: "Here is the quarterly plan we discussed",
|
||||
internalDate: "1763337600000",
|
||||
sizeEstimate: 4096,
|
||||
historyId: "9001",
|
||||
payload: {
|
||||
partId: "",
|
||||
mimeType: "multipart/mixed",
|
||||
filename: "",
|
||||
headers: [
|
||||
{ name: "From", value: "\"Avery Example\" <avery@example.test>" },
|
||||
{ name: "To", value: "Blake <blake@example.test>, casey@example.test" },
|
||||
{ name: "Cc", value: "\"Doe, Drew\" <drew@example.test>" },
|
||||
{ name: "Subject", value: "Quarterly plan" },
|
||||
{ name: "Date", value: "Mon, 17 Nov 2025 00:00:00 +0000" },
|
||||
{ name: "Message-ID", value: "<plan-1@mail.example.test>" },
|
||||
],
|
||||
body: { size: 0 },
|
||||
parts: [
|
||||
{
|
||||
partId: "0",
|
||||
mimeType: "multipart/alternative",
|
||||
filename: "",
|
||||
headers: [{ name: "Content-Type", value: "multipart/alternative; boundary=\"alt\"" }],
|
||||
body: { size: 0 },
|
||||
parts: [
|
||||
{ partId: "0.0", mimeType: "text/plain", filename: "", headers: [], body: { size: 38, data: b64("Here is the quarterly plan we discussed.") } },
|
||||
{ partId: "0.1", mimeType: "text/html", filename: "", headers: [], body: { size: 45, data: b64("<p>Here is the <b>quarterly plan</b>.</p>") } },
|
||||
],
|
||||
},
|
||||
{
|
||||
partId: "1",
|
||||
mimeType: "application/pdf",
|
||||
filename: "plan.pdf",
|
||||
headers: [{ name: "Content-Disposition", value: "attachment; filename=\"plan.pdf\"" }],
|
||||
body: { attachmentId: "ANGjdJ_fake_attachment_1", size: 2048 },
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export const METADATA_MESSAGE = {
|
||||
id: "18c0ffee00000002",
|
||||
threadId: "18c0ffee00000000",
|
||||
labelIds: ["SENT", "CATEGORY_UPDATES"],
|
||||
snippet: "Thanks, looks good",
|
||||
internalDate: "1763424000000",
|
||||
payload: {
|
||||
mimeType: "text/plain",
|
||||
headers: [
|
||||
{ name: "From", value: "blake@example.test" },
|
||||
{ name: "To", value: "avery@example.test" },
|
||||
{ name: "Subject", value: "Re: Quarterly plan" },
|
||||
{ name: "Date", value: "Tue, 18 Nov 2025 00:00:00 +0000" },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export const THREAD_LIST = {
|
||||
threads: [
|
||||
{ id: "18c0ffee00000000", snippet: "Thanks, looks good", historyId: "9002" },
|
||||
{ id: "18c0ffee00000010", snippet: "Lunch?", historyId: "9003" },
|
||||
],
|
||||
nextPageToken: "page-2-token",
|
||||
resultSizeEstimate: 201,
|
||||
};
|
||||
|
||||
export const THREAD_ONE = {
|
||||
id: "18c0ffee00000000",
|
||||
historyId: "9002",
|
||||
messages: [{ ...FULL_MESSAGE, payload: { mimeType: "multipart/mixed", headers: FULL_MESSAGE.payload.headers } }, METADATA_MESSAGE],
|
||||
};
|
||||
|
||||
export const REPLY_ORIGINAL = {
|
||||
id: "18c0ffee00000001",
|
||||
threadId: "18c0ffee00000000",
|
||||
payload: {
|
||||
mimeType: "multipart/mixed",
|
||||
headers: [
|
||||
{ name: "Message-ID", value: "<plan-1@mail.example.test>" },
|
||||
{ name: "References", value: "<kickoff-0@mail.example.test>" },
|
||||
{ name: "Subject", value: "Quarterly plan" },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export const CREATED_DRAFT = {
|
||||
id: "r-1234567890123456789",
|
||||
message: { id: "18c0ffee00000099", threadId: "18c0ffee00000000", labelIds: ["DRAFT"] },
|
||||
};
|
||||
@@ -0,0 +1,147 @@
|
||||
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." }] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
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));
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { RestTool } from "../tool.js";
|
||||
import { createDraft } from "./create-draft.js";
|
||||
import { getMessage } from "./get-message.js";
|
||||
import { searchThreads } from "./search-threads.js";
|
||||
|
||||
export const GMAIL_TOOLS: readonly RestTool[] = [getMessage, searchThreads, createDraft];
|
||||
@@ -0,0 +1,163 @@
|
||||
import { z } from "zod";
|
||||
import { GoogleToolError } from "../errors.js";
|
||||
import type { GoogleRequest } from "../google-http.js";
|
||||
import { compact } from "../tool.js";
|
||||
import { parseAddressList } from "./address.js";
|
||||
|
||||
export interface GmailHeader { name?: string; value?: string }
|
||||
export interface GmailMessagePart {
|
||||
partId?: string;
|
||||
mimeType?: string;
|
||||
filename?: string;
|
||||
headers?: GmailHeader[];
|
||||
body?: { attachmentId?: string; size?: number; data?: string };
|
||||
parts?: GmailMessagePart[];
|
||||
}
|
||||
export interface GmailRestMessage {
|
||||
id?: string;
|
||||
threadId?: string;
|
||||
labelIds?: string[];
|
||||
snippet?: string;
|
||||
internalDate?: string;
|
||||
payload?: GmailMessagePart;
|
||||
}
|
||||
export interface GmailRestAttachment { size?: number; data?: string }
|
||||
|
||||
export type MessageDetail = "metadata_only" | "minimal" | "full";
|
||||
|
||||
export const SUMMARY_HEADERS = ["From", "To", "Cc", "Subject", "Date"] as const;
|
||||
|
||||
export interface McpGmailMessage extends Record<string, unknown> {
|
||||
id: string;
|
||||
snippet?: string;
|
||||
subject?: string;
|
||||
sender?: string;
|
||||
toRecipients?: string[];
|
||||
ccRecipients?: string[];
|
||||
date?: string;
|
||||
plaintextBody?: string;
|
||||
attachmentIds?: string[];
|
||||
htmlBody?: string;
|
||||
attachments?: Array<{ id: string; mimeType: string; filename: string }>;
|
||||
labelIds?: string[];
|
||||
}
|
||||
|
||||
const REPORTED_SYSTEM_LABELS = new Set(["INBOX", "SPAM", "TRASH", "UNREAD", "STARRED", "IMPORTANT", "SENT", "DRAFT", "CHAT"]);
|
||||
|
||||
export const gmailId = z.string().regex(/^[A-Za-z0-9_-]{1,256}$/, "Must be a Gmail ID");
|
||||
const ATTACHMENT_ID = /^[A-Za-z0-9_-]{1,4096}$/;
|
||||
|
||||
export function header(part: GmailMessagePart | undefined, name: string): string | undefined {
|
||||
const lower = name.toLowerCase();
|
||||
return part?.headers?.find((item) => item.name?.toLowerCase() === lower)?.value;
|
||||
}
|
||||
|
||||
export function isoDate(internalDate: string | undefined): string | undefined {
|
||||
if (!internalDate || !/^\d+$/.test(internalDate)) return undefined;
|
||||
const date = new Date(Number(internalDate));
|
||||
return Number.isNaN(date.getTime()) ? undefined : date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function decodeBase64Url(data: string): string {
|
||||
return Buffer.from(data, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
export function reportedLabelIds(labelIds: readonly string[] | undefined): string[] {
|
||||
return (labelIds ?? []).filter((id) => id.startsWith("Label_") || REPORTED_SYSTEM_LABELS.has(id));
|
||||
}
|
||||
|
||||
function isAttachment(part: GmailMessagePart): boolean {
|
||||
const disposition = header(part, "Content-Disposition") ?? "";
|
||||
return Boolean(part.filename) || /^\s*attachment\b/i.test(disposition);
|
||||
}
|
||||
|
||||
interface MessageParts {
|
||||
plain?: GmailMessagePart;
|
||||
html?: GmailMessagePart;
|
||||
attachments: Array<{ id: string; mimeType: string; filename: string }>;
|
||||
}
|
||||
|
||||
export function messageParts(payload: GmailMessagePart | undefined): MessageParts {
|
||||
const found: MessageParts = { attachments: [] };
|
||||
const visit = (part: GmailMessagePart) => {
|
||||
if (part.parts?.length) {
|
||||
for (const child of part.parts) visit(child);
|
||||
return;
|
||||
}
|
||||
if (isAttachment(part)) {
|
||||
if (part.body?.attachmentId) {
|
||||
found.attachments.push({
|
||||
id: part.body.attachmentId,
|
||||
mimeType: part.mimeType ?? "application/octet-stream",
|
||||
filename: part.filename ?? "",
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const mimeType = (part.mimeType ?? "").toLowerCase();
|
||||
const hasBody = part.body?.data !== undefined || Boolean(part.body?.attachmentId);
|
||||
if (!hasBody) return;
|
||||
if (mimeType === "text/plain" && !found.plain) found.plain = part;
|
||||
else if (mimeType === "text/html" && !found.html) found.html = part;
|
||||
};
|
||||
if (payload) visit(payload);
|
||||
return found;
|
||||
}
|
||||
|
||||
export function externalBodyIds(payload: GmailMessagePart | undefined): string[] {
|
||||
const { plain, html } = messageParts(payload);
|
||||
return [plain, html]
|
||||
.filter((part): part is GmailMessagePart => Boolean(part && part.body?.data === undefined && part.body?.attachmentId))
|
||||
.map((part) => part.body!.attachmentId!);
|
||||
}
|
||||
|
||||
export function bodyAttachmentRequest(messageId: string, attachmentId: string): GoogleRequest {
|
||||
if (!ATTACHMENT_ID.test(attachmentId)) throw new GoogleToolError("incomplete", "Gmail returned a message body this tool cannot read.");
|
||||
return {
|
||||
method: "GET",
|
||||
host: "gmail.googleapis.com",
|
||||
path: `/gmail/v1/users/me/messages/${messageId}/attachments/${attachmentId}`,
|
||||
};
|
||||
}
|
||||
|
||||
export interface MessageContent {
|
||||
plaintextBody?: string;
|
||||
htmlBody?: string;
|
||||
attachments: Array<{ id: string; mimeType: string; filename: string }>;
|
||||
}
|
||||
|
||||
export function messageContent(payload: GmailMessagePart | undefined, externalBodies: ReadonlyMap<string, string> = new Map()): MessageContent {
|
||||
const { plain, html, attachments } = messageParts(payload);
|
||||
const text = (part: GmailMessagePart | undefined): string | undefined => {
|
||||
if (!part) return undefined;
|
||||
if (part.body?.data !== undefined) return decodeBase64Url(part.body.data);
|
||||
const data = externalBodies.get(part.body?.attachmentId ?? "");
|
||||
if (data === undefined) throw new GoogleToolError("incomplete", "Could not read the full body of this message.");
|
||||
return decodeBase64Url(data);
|
||||
};
|
||||
return { plaintextBody: text(plain), htmlBody: text(html), attachments };
|
||||
}
|
||||
|
||||
export function toMcpMessage(
|
||||
message: GmailRestMessage,
|
||||
detail: MessageDetail,
|
||||
externalBodies?: ReadonlyMap<string, string>,
|
||||
): McpGmailMessage {
|
||||
const payload = message.payload;
|
||||
const withText = detail !== "metadata_only";
|
||||
const content = detail === "full" ? messageContent(payload, externalBodies) : undefined;
|
||||
return compact({
|
||||
id: message.id ?? "",
|
||||
snippet: withText ? message.snippet ?? "" : undefined,
|
||||
subject: withText ? header(payload, "Subject") ?? "" : undefined,
|
||||
sender: parseAddressList(header(payload, "From"))[0],
|
||||
toRecipients: parseAddressList(header(payload, "To")),
|
||||
ccRecipients: parseAddressList(header(payload, "Cc")),
|
||||
date: isoDate(message.internalDate),
|
||||
plaintextBody: content?.plaintextBody,
|
||||
htmlBody: content?.htmlBody,
|
||||
attachmentIds: content ? content.attachments.map((attachment) => attachment.id) : undefined,
|
||||
attachments: content?.attachments,
|
||||
labelIds: reportedLabelIds(message.labelIds),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
export interface DraftMime {
|
||||
to: readonly string[];
|
||||
cc: readonly string[];
|
||||
bcc: readonly string[];
|
||||
subject: string;
|
||||
body?: string;
|
||||
htmlBody?: string;
|
||||
inReplyTo?: string;
|
||||
references?: string;
|
||||
boundary: string;
|
||||
}
|
||||
|
||||
const CRLF = "\r\n";
|
||||
export const PREFERRED_LINE_LENGTH = 78;
|
||||
const MAX_ASCII_TOKEN = 900;
|
||||
const ENCODED_WORD_BYTES = 39;
|
||||
|
||||
function assertSingleLine(name: string, value: string): string {
|
||||
if (/[\r\n]/.test(value)) throw new Error(`${name} must be a single line`);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function foldHeader(name: string, tokens: readonly string[], separator: string): string {
|
||||
let line = `${name}:`;
|
||||
const lines: string[] = [];
|
||||
tokens.forEach((token, index) => {
|
||||
const piece = index === tokens.length - 1 ? token : `${token}${separator}`;
|
||||
if (piece.trim() !== "" && line.length + 1 + piece.length > PREFERRED_LINE_LENGTH && line.trim() !== `${name}:`) {
|
||||
lines.push(line);
|
||||
line = "";
|
||||
}
|
||||
line += ` ${piece}`;
|
||||
});
|
||||
lines.push(line);
|
||||
return lines.join(CRLF);
|
||||
}
|
||||
|
||||
function encodedWords(value: string): string[] {
|
||||
const words: string[] = [];
|
||||
let chunk = "";
|
||||
for (const char of value) {
|
||||
if (Buffer.byteLength(chunk + char, "utf8") > ENCODED_WORD_BYTES) {
|
||||
words.push(chunk);
|
||||
chunk = "";
|
||||
}
|
||||
chunk += char;
|
||||
}
|
||||
if (chunk) words.push(chunk);
|
||||
return words.map((word) => `=?UTF-8?B?${Buffer.from(word, "utf8").toString("base64")}?=`);
|
||||
}
|
||||
|
||||
export function subjectHeader(subject: string): string {
|
||||
assertSingleLine("Subject", subject);
|
||||
const words = subject.split(" ");
|
||||
const plain = /^[\x20-\x7e]*$/.test(subject) && words.every((word) => word.length <= MAX_ASCII_TOKEN);
|
||||
if (plain) {
|
||||
if (`Subject: ${subject}`.length <= PREFERRED_LINE_LENGTH) return `Subject: ${subject}`;
|
||||
return foldHeader("Subject", words, "");
|
||||
}
|
||||
return foldHeader("Subject", encodedWords(subject), "");
|
||||
}
|
||||
|
||||
function textPart(mimeType: "text/plain" | "text/html", text: string): string {
|
||||
const encoded = (Buffer.from(text, "utf8").toString("base64").match(/.{1,76}/g) ?? [""]).join(CRLF);
|
||||
return [`Content-Type: ${mimeType}; charset="UTF-8"`, "Content-Transfer-Encoding: base64", "", encoded].join(CRLF);
|
||||
}
|
||||
|
||||
export function buildDraftMime(input: DraftMime): string {
|
||||
assertSingleLine("Boundary", input.boundary);
|
||||
for (const address of [...input.to, ...input.cc, ...input.bcc]) assertSingleLine("Address", address);
|
||||
const headers = [
|
||||
"MIME-Version: 1.0",
|
||||
input.to.length ? foldHeader("To", input.to, ",") : null,
|
||||
input.cc.length ? foldHeader("Cc", input.cc, ",") : null,
|
||||
input.bcc.length ? foldHeader("Bcc", input.bcc, ",") : null,
|
||||
subjectHeader(input.subject),
|
||||
input.inReplyTo ? `In-Reply-To: ${assertSingleLine("In-Reply-To", input.inReplyTo)}` : null,
|
||||
input.references ? foldHeader("References", assertSingleLine("References", input.references).split(" "), "") : null,
|
||||
].filter((line): line is string => line !== null);
|
||||
|
||||
if (input.htmlBody !== undefined && input.body !== undefined) {
|
||||
return [
|
||||
...headers,
|
||||
`Content-Type: multipart/alternative; boundary="${input.boundary}"`,
|
||||
"",
|
||||
`--${input.boundary}`,
|
||||
textPart("text/plain", input.body),
|
||||
`--${input.boundary}`,
|
||||
textPart("text/html", input.htmlBody),
|
||||
`--${input.boundary}--`,
|
||||
"",
|
||||
].join(CRLF);
|
||||
}
|
||||
const part = input.htmlBody !== undefined ? textPart("text/html", input.htmlBody) : textPart("text/plain", input.body ?? "");
|
||||
return [...headers, part, ""].join(CRLF);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
const stringArray = (description: string) => ({ type: "array", items: { type: "string" }, description });
|
||||
|
||||
export const attachmentMetadataSchema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
id: { type: "string", description: "The attachment ID." },
|
||||
mimeType: { type: "string", description: "The attachment's MIME type." },
|
||||
filename: { type: "string", description: "The attachment's file name." },
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const messageSchema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
id: { type: "string", description: "The message ID." },
|
||||
snippet: { type: "string", description: "A short excerpt of the message body." },
|
||||
subject: { type: "string", description: "The subject header." },
|
||||
sender: { type: "string", description: "The sender's email address." },
|
||||
toRecipients: stringArray("To recipient email addresses."),
|
||||
ccRecipients: stringArray("Cc recipient email addresses."),
|
||||
date: { type: "string", description: "The message date, ISO 8601 (YYYY-MM-DD)." },
|
||||
plaintextBody: { type: "string", description: "The plain-text body. Only with FULL_CONTENT." },
|
||||
attachmentIds: stringArray("Attachment IDs. Only with FULL_CONTENT."),
|
||||
htmlBody: { type: "string", description: "The HTML body. Only with FULL_CONTENT." },
|
||||
attachments: { type: "array", items: attachmentMetadataSchema, description: "Attachments. Only with FULL_CONTENT." },
|
||||
labelIds: stringArray("User label IDs and the system labels INBOX, SPAM, TRASH, UNREAD, STARRED, IMPORTANT, SENT, DRAFT and CHAT."),
|
||||
},
|
||||
} as const;
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { GoogleWorkspaceAuthError } from "../errors.js";
|
||||
import { createGoogleHttp } from "../google-http.js";
|
||||
import { fakeGoogle, json } from "../fixtures/fake-google.js";
|
||||
import { THREAD_LIST, THREAD_ONE } from "./fixtures/gmail-rest.js";
|
||||
import { effectiveQuery, listThreadsRequest, searchThreads, searchThreadsResult } from "./search-threads.js";
|
||||
|
||||
describe("search_threads request", () => {
|
||||
it("excludes drafts unless the query asks for them", () => {
|
||||
expect(effectiveQuery({})).toBe("-in:draft");
|
||||
expect(effectiveQuery({ query: "from:avery@example.test" })).toBe("(from:avery@example.test) -in:draft");
|
||||
expect(effectiveQuery({ query: "from:a@example.test OR from:b@example.test" })).toBe("(from:a@example.test OR from:b@example.test) -in:draft");
|
||||
expect(effectiveQuery({ query: "in:draft subject:plan" })).toBe("in:draft subject:plan");
|
||||
expect(effectiveQuery({ query: "-in:draft is:unread" })).toBe("-in:draft is:unread");
|
||||
expect(effectiveQuery({ query: "in:anywhere plan" })).toBe("in:anywhere plan");
|
||||
});
|
||||
|
||||
it("ignores operator-looking text inside quotes", () => {
|
||||
expect(effectiveQuery({ query: "subject:\"go in:draft mode\"" })).toBe("(subject:\"go in:draft mode\") -in:draft");
|
||||
expect(effectiveQuery({ query: "\"in:spam\" report", includeTrash: true })).toBe("(\"in:spam\" report) -in:draft -in:spam");
|
||||
expect(effectiveQuery({ query: "\"quoted\" in:draft" })).toBe("\"quoted\" in:draft");
|
||||
});
|
||||
|
||||
it("adds trash but not spam for includeTrash", () => {
|
||||
expect(effectiveQuery({ includeTrash: true })).toBe("-in:draft -in:spam");
|
||||
expect(listThreadsRequest({ includeTrash: true }).query).toMatchObject({ includeSpamTrash: true });
|
||||
expect(listThreadsRequest({}).query?.includeSpamTrash).toBeUndefined();
|
||||
});
|
||||
|
||||
it("defaults the page size to 20 and caps it at 50", () => {
|
||||
expect(listThreadsRequest({}).query?.maxResults).toBe(20);
|
||||
expect(listThreadsRequest({ pageSize: 500 }).query?.maxResults).toBe(50);
|
||||
expect(listThreadsRequest({ pageSize: 5, pageToken: "page-2-token" }).query).toMatchObject({ maxResults: 5, pageToken: "page-2-token" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("search_threads result", () => {
|
||||
it("maps threads to Google's MCP SearchThreadsResponse", () => {
|
||||
const result = searchThreadsResult(THREAD_LIST, [THREAD_ONE, null], {});
|
||||
expect(result.structuredContent).toEqual({
|
||||
threads: [{
|
||||
id: "18c0ffee00000000",
|
||||
messages: [
|
||||
{
|
||||
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", labelIds: ["INBOX", "UNREAD", "Label_42"],
|
||||
},
|
||||
{
|
||||
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"],
|
||||
},
|
||||
],
|
||||
}],
|
||||
nextPageToken: "page-2-token",
|
||||
resultCountEstimate: "201",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves snippet and subject out of THREAD_VIEW_METADATA_ONLY", () => {
|
||||
const result = searchThreadsResult(THREAD_LIST, [THREAD_ONE], { view: "THREAD_VIEW_METADATA_ONLY" });
|
||||
const message = (result.structuredContent as { threads: Array<{ messages: Array<Record<string, unknown>> }> }).threads[0]!.messages[0]!;
|
||||
expect(message).not.toHaveProperty("snippet");
|
||||
expect(message).not.toHaveProperty("subject");
|
||||
expect(message.sender).toBe("avery@example.test");
|
||||
});
|
||||
|
||||
it("returns an empty page without nextPageToken", () => {
|
||||
expect(searchThreadsResult({ resultSizeEstimate: 0 }, [], {}).structuredContent).toEqual({ threads: [], resultCountEstimate: "0" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("search_threads tool", () => {
|
||||
it("lists, then reads each thread's metadata, skipping a thread deleted in between", async () => {
|
||||
const { fetch, calls } = fakeGoogle(({ url }) => {
|
||||
if (url.pathname.endsWith("/threads")) return json(THREAD_LIST);
|
||||
if (url.pathname.endsWith("/threads/18c0ffee00000000")) return json(THREAD_ONE);
|
||||
return json({ error: { code: 404 } }, 404);
|
||||
});
|
||||
const result = await searchThreads.call({ query: "plan" }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.isError).toBeUndefined();
|
||||
expect((result.structuredContent as { threads: unknown[] }).threads).toHaveLength(1);
|
||||
expect(calls.map((call) => `${call.method} ${call.url.pathname}`)).toEqual([
|
||||
"GET /gmail/v1/users/me/threads",
|
||||
"GET /gmail/v1/users/me/threads/18c0ffee00000000",
|
||||
"GET /gmail/v1/users/me/threads/18c0ffee00000010",
|
||||
]);
|
||||
expect(calls[1]!.url.searchParams.get("format")).toBe("metadata");
|
||||
});
|
||||
|
||||
it("surfaces an auth failure on a thread read instead of a partial page", async () => {
|
||||
const { fetch } = fakeGoogle(({ url }) => (url.pathname.endsWith("/threads") ? json(THREAD_LIST) : json({}, 401)));
|
||||
await expect(searchThreads.call({}, createGoogleHttp({ accessToken: "t", fetch }))).rejects.toBeInstanceOf(GoogleWorkspaceAuthError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
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 { compact, defineTool, structuredResult } from "../tool.js";
|
||||
import { SUMMARY_HEADERS, toMcpMessage, type GmailRestMessage, type McpGmailMessage, type MessageDetail } from "./message.js";
|
||||
import { messageSchema } from "./schemas.js";
|
||||
|
||||
const THREAD_VIEWS = ["THREAD_VIEW_UNSPECIFIED", "THREAD_VIEW_MINIMAL", "THREAD_VIEW_METADATA_ONLY"] as const;
|
||||
export const DEFAULT_PAGE_SIZE = 20;
|
||||
export const MAX_PAGE_SIZE = 50;
|
||||
const THREAD_FETCH_CONCURRENCY = 10;
|
||||
|
||||
const args = z.object({
|
||||
pageSize: z.number().int().positive().optional(),
|
||||
pageToken: z.string().max(2048).optional(),
|
||||
query: z.string().max(4096).optional(),
|
||||
includeTrash: z.boolean().optional(),
|
||||
view: z.enum(THREAD_VIEWS).optional(),
|
||||
});
|
||||
export type SearchThreadsArgs = z.infer<typeof args>;
|
||||
|
||||
interface GmailThreadList {
|
||||
threads?: Array<{ id?: string }>;
|
||||
nextPageToken?: string;
|
||||
resultSizeEstimate?: number;
|
||||
}
|
||||
interface GmailRestThread { id?: string; messages?: GmailRestMessage[] }
|
||||
|
||||
export function unquotedOperators(query: string): string {
|
||||
return query.replace(/"[^"]*"?/g, " ");
|
||||
}
|
||||
|
||||
export function effectiveQuery(input: SearchThreadsArgs): string {
|
||||
const query = (input.query ?? "").trim();
|
||||
const operators = unquotedOperators(query);
|
||||
const added: string[] = [];
|
||||
if (!/(^|[\s({])-?(in|is):(drafts?|anywhere)\b/i.test(operators)) added.push("-in:draft");
|
||||
if (input.includeTrash && !/(^|[\s({])-?(in|is):(spam|anywhere)\b/i.test(operators)) added.push("-in:spam");
|
||||
if (!query) return added.join(" ");
|
||||
if (added.length === 0) return query;
|
||||
return [`(${query})`, ...added].join(" ");
|
||||
}
|
||||
|
||||
export function threadDetail(view: SearchThreadsArgs["view"]): MessageDetail {
|
||||
return view === "THREAD_VIEW_METADATA_ONLY" ? "metadata_only" : "minimal";
|
||||
}
|
||||
|
||||
export function listThreadsRequest(input: SearchThreadsArgs): GoogleRequest {
|
||||
return {
|
||||
method: "GET",
|
||||
host: "gmail.googleapis.com",
|
||||
path: "/gmail/v1/users/me/threads",
|
||||
query: {
|
||||
q: effectiveQuery(input),
|
||||
maxResults: Math.min(input.pageSize ?? DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE),
|
||||
pageToken: input.pageToken || undefined,
|
||||
includeSpamTrash: input.includeTrash ? true : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function threadIds(list: GmailThreadList): string[] {
|
||||
return (list.threads ?? []).map((thread) => thread.id).filter((id): id is string => typeof id === "string" && /^[A-Za-z0-9_-]+$/.test(id));
|
||||
}
|
||||
|
||||
export function getThreadRequest(threadId: string): GoogleRequest {
|
||||
return {
|
||||
method: "GET",
|
||||
host: "gmail.googleapis.com",
|
||||
path: `/gmail/v1/users/me/threads/${threadId}`,
|
||||
query: { format: "metadata", metadataHeaders: SUMMARY_HEADERS },
|
||||
};
|
||||
}
|
||||
|
||||
export function searchThreadsResult(list: GmailThreadList, threads: Array<GmailRestThread | null>, input: SearchThreadsArgs): CallToolResult {
|
||||
const detail = threadDetail(input.view);
|
||||
const mapped = threads.filter((thread): thread is GmailRestThread => thread !== null).map((thread) => ({
|
||||
id: thread.id ?? "",
|
||||
messages: (thread.messages ?? []).map((message): McpGmailMessage => toMcpMessage(message, detail)),
|
||||
}));
|
||||
return structuredResult(compact({
|
||||
threads: mapped,
|
||||
nextPageToken: list.nextPageToken || undefined,
|
||||
resultCountEstimate: typeof list.resultSizeEstimate === "number" ? String(list.resultSizeEstimate) : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
async function readThreads(ids: string[], http: GoogleHttp): Promise<Array<GmailRestThread | null>> {
|
||||
const results: Array<GmailRestThread | null> = new Array(ids.length).fill(null);
|
||||
let next = 0;
|
||||
let failed = false;
|
||||
const worker = async () => {
|
||||
while (!failed && next < ids.length) {
|
||||
const index = next++;
|
||||
try {
|
||||
results[index] = await http.send<GmailRestThread>(getThreadRequest(ids[index]!));
|
||||
} catch (error) {
|
||||
if (error instanceof GoogleToolError && error.kind === "not_found") continue;
|
||||
failed = true;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.min(THREAD_FETCH_CONCURRENCY, ids.length) }, worker));
|
||||
return results;
|
||||
}
|
||||
|
||||
export const searchThreads = defineTool({
|
||||
definition: {
|
||||
name: "search_threads",
|
||||
description: "Lists the signed-in user's Gmail threads that match an optional Gmail search query, one page at a time. Returns thread IDs with message summaries, not full bodies; use get_message with a message ID for a full message. A thread matches when any of its messages matches.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
pageSize: { type: "integer", description: "Optional. Most threads to return. Default 20, maximum 50." },
|
||||
pageToken: { type: "string", description: "Optional. The nextPageToken from a previous call. Leave empty for the first page." },
|
||||
query: {
|
||||
type: "string",
|
||||
description: "Optional. A Gmail search query (for example `from:user@example.com newer_than:7d has:attachment`). Convert natural language to Gmail syntax first. `label:` takes label IDs, not display names. Without a query, all threads except spam and trash are listed. Drafts are excluded unless the query includes in:draft.",
|
||||
},
|
||||
includeTrash: { type: "boolean", description: "Optional. Include threads in Trash. Default false." },
|
||||
view: {
|
||||
type: "string",
|
||||
enum: [...THREAD_VIEWS],
|
||||
description: "Optional. THREAD_VIEW_MINIMAL (default) returns id, snippet, subject, sender, recipients, date and labels. THREAD_VIEW_METADATA_ONLY leaves out snippet and subject.",
|
||||
},
|
||||
},
|
||||
},
|
||||
outputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
threads: {
|
||||
type: "array",
|
||||
description: "Matching threads.",
|
||||
items: {
|
||||
type: "object",
|
||||
properties: {
|
||||
id: { type: "string", description: "The thread ID." },
|
||||
messages: { type: "array", items: messageSchema, description: "The thread's messages, oldest first." },
|
||||
},
|
||||
},
|
||||
},
|
||||
nextPageToken: { type: "string", description: "Pass as pageToken to get the next page. Present only when there are more results." },
|
||||
resultCountEstimate: { type: "string", description: "Estimated number of results; treat as a lower bound." },
|
||||
},
|
||||
},
|
||||
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
||||
},
|
||||
args,
|
||||
async run(input, http) {
|
||||
const list = await http.send<GmailThreadList>(listThreadsRequest(input));
|
||||
return searchThreadsResult(list, await readThreads(threadIds(list), http), input);
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { GoogleToolError, GoogleWorkspaceAuthError } from "./errors.js";
|
||||
import { fakeGoogle, json } from "./fixtures/fake-google.js";
|
||||
import { createGoogleHttp, googleRequestUrl, MAX_RESPONSE_BYTES, type GoogleRequest } from "./google-http.js";
|
||||
|
||||
const GET: GoogleRequest = { method: "GET", host: "gmail.googleapis.com", path: "/gmail/v1/users/me/labels" };
|
||||
const POST: GoogleRequest = { method: "POST", host: "gmail.googleapis.com", path: "/gmail/v1/users/me/drafts", body: { message: { raw: "eA" } } };
|
||||
|
||||
function client(route: Parameters<typeof fakeGoogle>[0], timeoutMs?: number) {
|
||||
const fake = fakeGoogle(route);
|
||||
return { http: createGoogleHttp({ accessToken: "test-token", fetch: fake.fetch, retryDelayMs: 0, timeoutMs }), calls: fake.calls };
|
||||
}
|
||||
|
||||
async function failure(promise: Promise<unknown>): Promise<unknown> {
|
||||
try {
|
||||
await promise;
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
throw new Error("expected a failure");
|
||||
}
|
||||
|
||||
describe("googleRequestUrl", () => {
|
||||
it("builds an https googleapis.com URL with repeated array parameters", () => {
|
||||
const url = new URL(googleRequestUrl({ ...GET, query: { format: "metadata", metadataHeaders: ["From", "To"], skip: undefined, max: 5 } }));
|
||||
expect(url.origin).toBe("https://gmail.googleapis.com");
|
||||
expect(url.searchParams.getAll("metadataHeaders")).toEqual(["From", "To"]);
|
||||
expect(url.searchParams.get("max")).toBe("5");
|
||||
expect(url.searchParams.has("skip")).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses hosts outside the allowlist and relative paths", () => {
|
||||
expect(() => googleRequestUrl({ ...GET, host: "evil.example.test" as never })).toThrow(/not allowed/);
|
||||
expect(() => googleRequestUrl({ ...GET, path: "//evil.example.test/x" })).toThrow(/absolute/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createGoogleHttp", () => {
|
||||
it("sends the bearer token and JSON body, and parses the JSON answer", async () => {
|
||||
const { http, calls } = client(() => json({ id: "r-1" }));
|
||||
await expect(http.send(POST)).resolves.toEqual({ id: "r-1" });
|
||||
expect(calls[0]!.headers.authorization).toBe("Bearer test-token");
|
||||
expect(calls[0]!.headers["content-type"]).toBe("application/json");
|
||||
expect(calls[0]!.body).toEqual({ message: { raw: "eA" } });
|
||||
});
|
||||
|
||||
it("maps 401 to an unauthenticated auth error", async () => {
|
||||
const { http } = client(() => json({ error: { code: 401, status: "UNAUTHENTICATED" } }, 401));
|
||||
const error = await failure(http.send(GET));
|
||||
expect(error).toBeInstanceOf(GoogleWorkspaceAuthError);
|
||||
expect((error as GoogleWorkspaceAuthError).reason).toBe("unauthenticated");
|
||||
expect((error as GoogleWorkspaceAuthError).data).toEqual({ code: "unauthenticated", httpStatus: 401 });
|
||||
});
|
||||
|
||||
it("maps 403 insufficient scope, from the body or the WWW-Authenticate header, to an insufficient_scope auth error", async () => {
|
||||
const fromBody = client(() => json({ error: { code: 403, status: "PERMISSION_DENIED", details: [{ reason: "ACCESS_TOKEN_SCOPE_INSUFFICIENT" }] } }, 403));
|
||||
const fromLegacyBody = client(() => json({ error: { code: 403, errors: [{ reason: "insufficientPermissions" }] } }, 403));
|
||||
const fromHeader = client(() => json({}, 403, { "www-authenticate": "Bearer error=\"insufficient_scope\", scope=\"x\"" }));
|
||||
for (const { http } of [fromBody, fromLegacyBody, fromHeader]) {
|
||||
const error = await failure(http.send(GET));
|
||||
expect(error).toBeInstanceOf(GoogleWorkspaceAuthError);
|
||||
expect((error as GoogleWorkspaceAuthError).reason).toBe("insufficient_scope");
|
||||
expect((error as GoogleWorkspaceAuthError).data).toEqual({ code: "insufficient_scope", httpStatus: 403 });
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps other 403s apart from scope errors", async () => {
|
||||
const disabled = await failure(client(() => json({ error: { code: 403, details: [{ reason: "SERVICE_DISABLED" }], message: "Gmail API has not been used in project 123" } }, 403)).http.send(GET));
|
||||
expect(disabled).toMatchObject({ kind: "api_disabled" });
|
||||
expect((disabled as Error).message).not.toContain("123");
|
||||
const denied = await failure(client(() => json({ error: { code: 403, message: "Delegation denied" } }, 403)).http.send(GET));
|
||||
expect(denied).toBeInstanceOf(GoogleToolError);
|
||||
expect(denied).toMatchObject({ kind: "permission_denied", message: "Delegation denied" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
[404, "not_found"],
|
||||
[400, "invalid_argument"],
|
||||
[429, "rate_limited"],
|
||||
[500, "unavailable"],
|
||||
])("maps HTTP %i to %s", async (status, kind) => {
|
||||
const error = await failure(client(() => json({ error: { code: status, message: "x" } }, status)).http.send(POST));
|
||||
expect(error).toMatchObject({ kind, httpStatus: status });
|
||||
});
|
||||
|
||||
it("retries a read once after 503, then succeeds", async () => {
|
||||
let count = 0;
|
||||
const { http, calls } = client(() => (count++ === 0 ? json({}, 503) : json({ labels: [] })));
|
||||
await expect(http.send(GET)).resolves.toEqual({ labels: [] });
|
||||
expect(calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("retries a read at most once", async () => {
|
||||
const { http, calls } = client(() => json({}, 503));
|
||||
expect(await failure(http.send(GET))).toMatchObject({ kind: "unavailable" });
|
||||
expect(calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("never retries a write, after a 503 or a network failure", async () => {
|
||||
const after503 = client(() => json({}, 503));
|
||||
expect(await failure(after503.http.send(POST))).toMatchObject({ kind: "unavailable" });
|
||||
expect(after503.calls).toHaveLength(1);
|
||||
|
||||
const afterNetwork = client(() => { throw new TypeError("fetch failed"); });
|
||||
expect(await failure(afterNetwork.http.send(POST))).toMatchObject({ kind: "network" });
|
||||
expect(afterNetwork.calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("warns that a failed write may have been applied, for network errors, 5xx and caller cancellation", async () => {
|
||||
const network = await failure(client(() => { throw new TypeError("fetch failed"); }).http.send(POST));
|
||||
expect((network as Error).message).toMatch(/may or may not have been made/);
|
||||
const unavailable = await failure(client(() => json({}, 503)).http.send(POST));
|
||||
expect((unavailable as Error).message).toMatch(/may or may not have been made/);
|
||||
|
||||
const controller = new AbortController();
|
||||
const cancelled = createGoogleHttp({
|
||||
accessToken: "test-token",
|
||||
signal: controller.signal,
|
||||
fetch: (_url, init) => new Promise((_resolve, reject) => {
|
||||
init.signal?.addEventListener("abort", () => reject(init.signal?.reason));
|
||||
controller.abort();
|
||||
}),
|
||||
});
|
||||
const error = await failure(cancelled.send(POST));
|
||||
expect(error).toMatchObject({ kind: "timeout" });
|
||||
expect((error as Error).message).toMatch(/may or may not have been made/);
|
||||
|
||||
const readFailure = await failure(client(() => { throw new TypeError("fetch failed"); }).http.send(GET));
|
||||
expect((readFailure as Error).message).not.toMatch(/may or may not/);
|
||||
});
|
||||
|
||||
it("warns that a write may have been applied when Google's success answer is unusable", async () => {
|
||||
const html = await failure(client(() => new Response("<html>ok</html>", { status: 200 })).http.send(POST));
|
||||
expect(html).toMatchObject({ kind: "invalid_response" });
|
||||
expect((html as Error).message).toMatch(/may or may not have been made/);
|
||||
|
||||
const oversized = await failure(client(() => new Response("{}", { headers: { "content-length": String(MAX_RESPONSE_BYTES + 1) } })).http.send(POST));
|
||||
expect(oversized).toMatchObject({ kind: "invalid_response" });
|
||||
expect((oversized as Error).message).toMatch(/may or may not have been made/);
|
||||
|
||||
const readHtml = await failure(client(() => new Response("<html>")).http.send(GET));
|
||||
expect((readHtml as Error).message).not.toMatch(/may or may not/);
|
||||
});
|
||||
|
||||
it("treats a connection that drops while the body streams like any network failure", async () => {
|
||||
const dropping = () => new Response(new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode("{\"partial\":"));
|
||||
controller.error(new TypeError("terminated"));
|
||||
},
|
||||
}), { status: 200 });
|
||||
|
||||
let reads = 0;
|
||||
const read = client(() => (reads++ === 0 ? dropping() : json({ ok: true })));
|
||||
await expect(read.http.send(GET)).resolves.toEqual({ ok: true });
|
||||
expect(read.calls).toHaveLength(2);
|
||||
|
||||
const write = client(() => dropping());
|
||||
const error = await failure(write.http.send(POST));
|
||||
expect(error).toBeInstanceOf(GoogleToolError);
|
||||
expect(error).toMatchObject({ kind: "network" });
|
||||
expect((error as Error).message).toMatch(/may or may not have been made/);
|
||||
expect(write.calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("retries a read once after a network failure", async () => {
|
||||
let count = 0;
|
||||
const { http, calls } = client(() => {
|
||||
if (count++ === 0) throw new TypeError("fetch failed");
|
||||
return json({ ok: true });
|
||||
});
|
||||
await expect(http.send(GET)).resolves.toEqual({ ok: true });
|
||||
expect(calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("stops a request at its deadline and says a write's outcome is unknown", async () => {
|
||||
let calls = 0;
|
||||
const slow = createGoogleHttp({
|
||||
accessToken: "test-token",
|
||||
retryDelayMs: 0,
|
||||
timeoutMs: 20,
|
||||
fetch: (_url, init) => new Promise((_resolve, reject) => {
|
||||
calls += 1;
|
||||
init.signal?.addEventListener("abort", () => reject(init.signal?.reason));
|
||||
}),
|
||||
});
|
||||
const error = await failure(slow.send(POST));
|
||||
expect(error).toMatchObject({ kind: "timeout" });
|
||||
expect((error as Error).message).toMatch(/may or may not/);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("sends nothing to a disallowed host, and does not treat it as a network failure", async () => {
|
||||
const { http, calls } = client(() => json({}));
|
||||
const error = await failure(http.send({ ...GET, host: "evil.example.test" as never }));
|
||||
expect(error).not.toBeInstanceOf(GoogleToolError);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("rejects an oversized response", async () => {
|
||||
const declared = client(() => new Response("{}", { headers: { "content-length": String(MAX_RESPONSE_BYTES + 1) } }));
|
||||
expect(await failure(declared.http.send(GET))).toMatchObject({ kind: "invalid_response" });
|
||||
});
|
||||
|
||||
it("rejects a non-JSON success body", async () => {
|
||||
expect(await failure(client(() => new Response("<html>")).http.send(GET))).toMatchObject({ kind: "invalid_response" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,229 @@
|
||||
import { GoogleToolError, GoogleWorkspaceAuthError } from "./errors.js";
|
||||
|
||||
export const GOOGLE_API_HOSTS = ["gmail.googleapis.com"] as const;
|
||||
export type GoogleApiHost = (typeof GOOGLE_API_HOSTS)[number];
|
||||
|
||||
export type QueryValue = string | number | boolean | readonly string[] | undefined;
|
||||
|
||||
export interface GoogleRequest {
|
||||
method: "GET" | "POST";
|
||||
host: GoogleApiHost;
|
||||
path: string;
|
||||
query?: Record<string, QueryValue>;
|
||||
body?: unknown;
|
||||
}
|
||||
|
||||
export type GoogleFetch = (url: string, init: RequestInit) => Promise<Response>;
|
||||
|
||||
export interface GoogleHttpOptions {
|
||||
accessToken: string;
|
||||
fetch?: GoogleFetch;
|
||||
signal?: AbortSignal;
|
||||
timeoutMs?: number;
|
||||
retryDelayMs?: number;
|
||||
}
|
||||
|
||||
export interface GoogleHttp {
|
||||
send<T = unknown>(request: GoogleRequest): Promise<T>;
|
||||
}
|
||||
|
||||
interface GoogleAnswer {
|
||||
status: number;
|
||||
headers: Headers;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_TIMEOUT_MS = 20_000;
|
||||
export const MAX_RESPONSE_BYTES = 20 * 1024 * 1024;
|
||||
const RETRYABLE_READ_STATUSES = new Set([502, 503, 504]);
|
||||
const DEFAULT_RETRY_DELAY_MS = 250;
|
||||
const MAX_ERROR_MESSAGE_LENGTH = 300;
|
||||
export const UNCERTAIN_WRITE = "The change may or may not have been made; check before trying again.";
|
||||
|
||||
export function googleRequestUrl(request: GoogleRequest): string {
|
||||
if (!GOOGLE_API_HOSTS.includes(request.host)) throw new Error(`Host is not allowed: ${request.host}`);
|
||||
if (!request.path.startsWith("/") || request.path.startsWith("//")) throw new Error("Request path must be absolute");
|
||||
const url = new URL(`https://${request.host}${request.path}`);
|
||||
for (const [key, value] of Object.entries(request.query ?? {})) {
|
||||
if (value === undefined) continue;
|
||||
if (Array.isArray(value)) for (const item of value) url.searchParams.append(key, item);
|
||||
else url.searchParams.set(key, String(value));
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function isWrite(request: GoogleRequest): boolean {
|
||||
return request.method !== "GET";
|
||||
}
|
||||
|
||||
function withWriteWarning(request: GoogleRequest, message: string): string {
|
||||
return isWrite(request) ? `${message} ${UNCERTAIN_WRITE}` : message;
|
||||
}
|
||||
|
||||
export function createGoogleHttp(options: GoogleHttpOptions): GoogleHttp {
|
||||
const doFetch = options.fetch ?? ((url, init) => fetch(url, init));
|
||||
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
|
||||
|
||||
async function attempt(request: GoogleRequest): Promise<GoogleAnswer> {
|
||||
const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(options.signal ? [options.signal] : [])]);
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: `Bearer ${options.accessToken}`,
|
||||
Accept: "application/json",
|
||||
};
|
||||
if (request.body !== undefined) headers["Content-Type"] = "application/json";
|
||||
const url = googleRequestUrl(request);
|
||||
try {
|
||||
const response = await doFetch(url, {
|
||||
method: request.method,
|
||||
headers,
|
||||
body: request.body === undefined ? undefined : JSON.stringify(request.body),
|
||||
signal,
|
||||
redirect: "error",
|
||||
});
|
||||
return { status: response.status, headers: response.headers, text: await readBounded(response) };
|
||||
} catch (error) {
|
||||
if (error instanceof GoogleToolError) {
|
||||
throw new GoogleToolError(error.kind, withWriteWarning(request, error.message), error.httpStatus);
|
||||
}
|
||||
if (options.signal?.aborted) throw new GoogleToolError("timeout", withWriteWarning(request, "The request was cancelled."));
|
||||
if (isAbort(error)) throw new GoogleToolError("timeout", withWriteWarning(request, "Google did not answer in time."));
|
||||
throw new GoogleToolError("network", withWriteWarning(request, "Could not reach Google."));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async send<T>(request: GoogleRequest): Promise<T> {
|
||||
let answer: GoogleAnswer;
|
||||
for (let tries = 0; ; tries += 1) {
|
||||
const mayRetry = !isWrite(request) && tries === 0;
|
||||
try {
|
||||
answer = await attempt(request);
|
||||
} catch (error) {
|
||||
if (mayRetry && error instanceof GoogleToolError && error.kind === "network") {
|
||||
await delay(retryDelayMs, options.signal);
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (mayRetry && RETRYABLE_READ_STATUSES.has(answer.status)) {
|
||||
await delay(retryDelayMs, options.signal);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (answer.status < 200 || answer.status >= 300) throw googleError(answer, answer.text, request);
|
||||
if (answer.text.length === 0) return {} as T;
|
||||
try {
|
||||
return JSON.parse(answer.text) as T;
|
||||
} catch {
|
||||
throw new GoogleToolError("invalid_response", withWriteWarning(request, "Google returned a response that is not JSON."), answer.status);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readBounded(response: Response): Promise<string> {
|
||||
const declared = Number(response.headers.get("content-length") ?? "0");
|
||||
if (declared > MAX_RESPONSE_BYTES) {
|
||||
await response.body?.cancel().catch(() => undefined);
|
||||
throw new GoogleToolError("invalid_response", "Google's response is too large.", response.status);
|
||||
}
|
||||
if (!response.body) return "";
|
||||
const reader = response.body.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
size += value.byteLength;
|
||||
if (size > MAX_RESPONSE_BYTES) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
throw new GoogleToolError("invalid_response", "Google's response is too large.", response.status);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks).toString("utf8");
|
||||
}
|
||||
|
||||
interface GoogleErrorBody {
|
||||
error?: {
|
||||
code?: number;
|
||||
message?: string;
|
||||
status?: string;
|
||||
errors?: Array<{ reason?: string }>;
|
||||
details?: Array<{ reason?: string }>;
|
||||
} | string;
|
||||
}
|
||||
|
||||
export function googleError(
|
||||
response: { status: number; headers: Pick<Headers, "get"> },
|
||||
text: string,
|
||||
request?: GoogleRequest,
|
||||
): Error {
|
||||
const status = response.status;
|
||||
let body: GoogleErrorBody = {};
|
||||
try {
|
||||
body = JSON.parse(text) as GoogleErrorBody;
|
||||
} catch {
|
||||
body = {};
|
||||
}
|
||||
const error = typeof body.error === "object" ? body.error : undefined;
|
||||
const reasons = new Set([
|
||||
...(error?.errors ?? []).map((item) => item.reason),
|
||||
...(error?.details ?? []).map((item) => item.reason),
|
||||
typeof body.error === "string" ? body.error : undefined,
|
||||
].filter((reason): reason is string => typeof reason === "string"));
|
||||
const authenticate = response.headers.get("www-authenticate") ?? "";
|
||||
|
||||
if (status === 401) return new GoogleWorkspaceAuthError("unauthenticated");
|
||||
if (status === 403 && (
|
||||
/\berror\s*=\s*"?insufficient_scope\b/i.test(authenticate)
|
||||
|| reasons.has("ACCESS_TOKEN_SCOPE_INSUFFICIENT")
|
||||
|| reasons.has("insufficientPermissions")
|
||||
|| reasons.has("insufficient_scope")
|
||||
)) return new GoogleWorkspaceAuthError("insufficient_scope");
|
||||
|
||||
const message = safeMessage(error?.message);
|
||||
if (status === 403 && (reasons.has("SERVICE_DISABLED") || reasons.has("accessNotConfigured"))) {
|
||||
return new GoogleToolError("api_disabled", "This Google API is not enabled for the Google Cloud project behind this connection.", status);
|
||||
}
|
||||
if (status === 429 || reasons.has("RATE_LIMIT_EXCEEDED") || reasons.has("rateLimitExceeded") || reasons.has("userRateLimitExceeded")) {
|
||||
return new GoogleToolError("rate_limited", "Google is rate limiting requests. Try again shortly.", status);
|
||||
}
|
||||
if (status === 403) return new GoogleToolError("permission_denied", message ?? "Google denied access to this item.", status);
|
||||
if (status === 404) return new GoogleToolError("not_found", "Google could not find that item.", status);
|
||||
if (status === 400 || status === 409 || status === 412 || status === 413) {
|
||||
return new GoogleToolError("invalid_argument", message ?? "Google rejected the request.", status);
|
||||
}
|
||||
if (status >= 500) {
|
||||
const unavailable = "Google is temporarily unavailable.";
|
||||
return new GoogleToolError("unavailable", request && isWrite(request) ? withWriteWarning(request, unavailable) : `${unavailable} Try again shortly.`, status);
|
||||
}
|
||||
return new GoogleToolError("invalid_response", message ?? `Google returned HTTP ${status}.`, status);
|
||||
}
|
||||
|
||||
function safeMessage(value: unknown): string | undefined {
|
||||
if (typeof value !== "string" || value.trim().length === 0) return undefined;
|
||||
const oneLine = value.replace(/\s+/g, " ").trim();
|
||||
return oneLine.length > MAX_ERROR_MESSAGE_LENGTH ? `${oneLine.slice(0, MAX_ERROR_MESSAGE_LENGTH)}…` : oneLine;
|
||||
}
|
||||
|
||||
function isAbort(error: unknown): boolean {
|
||||
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
||||
}
|
||||
|
||||
function delay(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
if (ms <= 0) return Promise.resolve();
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(new GoogleToolError("timeout", "The request was cancelled."));
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export {
|
||||
GOOGLE_WORKSPACE_REST_SERVICES,
|
||||
callGoogleWorkspaceRestTool,
|
||||
isGoogleWorkspaceRestService,
|
||||
listGoogleWorkspaceRestTools,
|
||||
type CallGoogleWorkspaceRestToolInput,
|
||||
type GoogleWorkspaceRestService,
|
||||
} from "./tools.js";
|
||||
export { createGoogleWorkspaceRestServer, type GoogleWorkspaceRestServerOptions } from "./server.js";
|
||||
export { GOOGLE_AUTH_ERROR_CODE, GoogleWorkspaceAuthError, type GoogleAuthFailure } from "./errors.js";
|
||||
export type { GoogleFetch } from "./google-http.js";
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import { McpError } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fakeGoogle, json } from "./fixtures/fake-google.js";
|
||||
import { FULL_MESSAGE } from "./gmail/fixtures/gmail-rest.js";
|
||||
import { GOOGLE_AUTH_ERROR_CODE, callGoogleWorkspaceRestTool, createGoogleWorkspaceRestServer, GoogleWorkspaceAuthError } from "./index.js";
|
||||
|
||||
async function connect(route: Parameters<typeof fakeGoogle>[0], token?: string) {
|
||||
const fake = fakeGoogle(route);
|
||||
const server = createGoogleWorkspaceRestServer("gmail", { fetch: fake.fetch });
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const send = clientTransport.send.bind(clientTransport);
|
||||
clientTransport.send = (message, options) => send(message, { ...options, ...(token ? { authInfo: { token, clientId: "test", scopes: [] } } : {}) });
|
||||
await server.connect(serverTransport);
|
||||
const client = new Client({ name: "test", version: "1" });
|
||||
await client.connect(clientTransport);
|
||||
return { client, calls: fake.calls };
|
||||
}
|
||||
|
||||
describe("MCP server", () => {
|
||||
it("lists the service's tools with input and output schemas", async () => {
|
||||
const { client } = await connect(() => json({}));
|
||||
const { tools } = await client.listTools();
|
||||
expect(tools.map((tool) => tool.name)).toEqual(["get_message", "search_threads", "create_draft"]);
|
||||
for (const tool of tools) {
|
||||
expect(tool.inputSchema.type).toBe("object");
|
||||
expect(tool.outputSchema?.type).toBe("object");
|
||||
}
|
||||
});
|
||||
|
||||
it("calls a tool with the bearer token from the transport", async () => {
|
||||
const { client, calls } = await connect(() => json(FULL_MESSAGE), "user-token");
|
||||
const result = await client.callTool({ name: "get_message", arguments: { messageId: FULL_MESSAGE.id } });
|
||||
expect(result.isError).toBeFalsy();
|
||||
expect((result.structuredContent as { subject: string }).subject).toBe("Quarterly plan");
|
||||
expect(calls[0]!.headers.authorization).toBe("Bearer user-token");
|
||||
});
|
||||
|
||||
it("answers a missing token and a refused token with a JSON-RPC auth error", async () => {
|
||||
const missing = await connect(() => json(FULL_MESSAGE));
|
||||
await expect(missing.client.callTool({ name: "get_message", arguments: { messageId: "x1" } }))
|
||||
.rejects.toMatchObject({ code: GOOGLE_AUTH_ERROR_CODE, data: { code: "unauthenticated", httpStatus: 401 } });
|
||||
|
||||
const scoped = await connect(() => json({ error: { details: [{ reason: "ACCESS_TOKEN_SCOPE_INSUFFICIENT" }] } }, 403), "narrow-token");
|
||||
const error = await scoped.client.callTool({ name: "get_message", arguments: { messageId: "x1" } }).catch((caught: unknown) => caught);
|
||||
expect(error).toBeInstanceOf(McpError);
|
||||
expect(error).toMatchObject({ code: GOOGLE_AUTH_ERROR_CODE, data: { code: "insufficient_scope", httpStatus: 403 } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("callGoogleWorkspaceRestTool", () => {
|
||||
it("is the in-process equivalent of tools/call", async () => {
|
||||
const { fetch } = fakeGoogle(() => json(FULL_MESSAGE));
|
||||
const result = await callGoogleWorkspaceRestTool({ service: "gmail", name: "get_message", arguments: { messageId: FULL_MESSAGE.id, messageFormat: "MINIMAL" }, accessToken: "t", fetch });
|
||||
expect(result.structuredContent).toMatchObject({ id: FULL_MESSAGE.id, subject: "Quarterly plan" });
|
||||
});
|
||||
|
||||
it("throws for an unknown tool and for a refused token", async () => {
|
||||
const { fetch } = fakeGoogle(() => json({}, 401));
|
||||
await expect(callGoogleWorkspaceRestTool({ service: "gmail", name: "send_message", accessToken: "t", fetch })).rejects.toThrow(/Unknown tool/);
|
||||
await expect(callGoogleWorkspaceRestTool({ service: "gmail", name: "get_message", arguments: { messageId: "x1" }, accessToken: "t", fetch }))
|
||||
.rejects.toBeInstanceOf(GoogleWorkspaceAuthError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
||||
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { GoogleWorkspaceAuthError } from "./errors.js";
|
||||
import type { GoogleFetch } from "./google-http.js";
|
||||
import { callGoogleWorkspaceRestTool, listGoogleWorkspaceRestTools, type GoogleWorkspaceRestService } from "./tools.js";
|
||||
|
||||
export interface GoogleWorkspaceRestServerOptions {
|
||||
fetch?: GoogleFetch;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export function createGoogleWorkspaceRestServer(service: GoogleWorkspaceRestService, options: GoogleWorkspaceRestServerOptions = {}): Server {
|
||||
const server = new Server(
|
||||
{ name: `paperclip-google-workspace-rest-${service}`, version: "0.1.0" },
|
||||
{ capabilities: { tools: {} } },
|
||||
);
|
||||
server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: listGoogleWorkspaceRestTools(service) }));
|
||||
server.setRequestHandler(CallToolRequestSchema, (request, extra) => {
|
||||
const accessToken = extra.authInfo?.token;
|
||||
if (!accessToken) throw new GoogleWorkspaceAuthError("unauthenticated");
|
||||
return callGoogleWorkspaceRestTool({
|
||||
service,
|
||||
name: request.params.name,
|
||||
arguments: request.params.arguments,
|
||||
accessToken,
|
||||
fetch: options.fetch,
|
||||
signal: extra.signal,
|
||||
timeoutMs: options.timeoutMs,
|
||||
});
|
||||
});
|
||||
return server;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
|
||||
import type { z } from "zod";
|
||||
import { GoogleToolError } from "./errors.js";
|
||||
import type { GoogleHttp } from "./google-http.js";
|
||||
|
||||
export interface RestToolSpec<Args> {
|
||||
definition: Tool;
|
||||
args: z.ZodType<Args>;
|
||||
run(args: Args, http: GoogleHttp): Promise<CallToolResult>;
|
||||
}
|
||||
|
||||
export interface RestTool {
|
||||
definition: Tool;
|
||||
call(rawArgs: unknown, http: GoogleHttp): Promise<CallToolResult>;
|
||||
}
|
||||
|
||||
export function defineTool<Args>(spec: RestToolSpec<Args>): RestTool {
|
||||
return {
|
||||
definition: spec.definition,
|
||||
async call(rawArgs, http) {
|
||||
const parsed = spec.args.safeParse(rawArgs ?? {});
|
||||
if (!parsed.success) {
|
||||
const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "arguments"}: ${issue.message}`).join("; ");
|
||||
return { isError: true, content: [{ type: "text", text: `Invalid arguments for ${spec.definition.name}: ${detail}` }] };
|
||||
}
|
||||
try {
|
||||
return await spec.run(parsed.data, http);
|
||||
} catch (error) {
|
||||
if (error instanceof GoogleToolError) return toolErrorResult(error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function structuredResult(value: Record<string, unknown>): CallToolResult {
|
||||
return { content: [{ type: "text", text: JSON.stringify(value) }], structuredContent: value };
|
||||
}
|
||||
|
||||
export function toolErrorResult(error: GoogleToolError): CallToolResult {
|
||||
return { isError: true, content: [{ type: "text", text: error.message }] };
|
||||
}
|
||||
|
||||
export function compact<T extends Record<string, unknown>>(value: T): T {
|
||||
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { GoogleWorkspaceAuthError } from "./errors.js";
|
||||
import { GMAIL_TOOLS } from "./gmail/index.js";
|
||||
import { createGoogleHttp, type GoogleFetch } from "./google-http.js";
|
||||
import type { RestTool } from "./tool.js";
|
||||
|
||||
export const GOOGLE_WORKSPACE_REST_SERVICES = ["gmail"] as const;
|
||||
export type GoogleWorkspaceRestService = (typeof GOOGLE_WORKSPACE_REST_SERVICES)[number];
|
||||
|
||||
const TOOLS: Record<GoogleWorkspaceRestService, readonly RestTool[]> = {
|
||||
gmail: GMAIL_TOOLS,
|
||||
};
|
||||
|
||||
export function isGoogleWorkspaceRestService(value: string): value is GoogleWorkspaceRestService {
|
||||
return (GOOGLE_WORKSPACE_REST_SERVICES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
export function listGoogleWorkspaceRestTools(service: GoogleWorkspaceRestService): Tool[] {
|
||||
return TOOLS[service].map((tool) => tool.definition);
|
||||
}
|
||||
|
||||
export interface CallGoogleWorkspaceRestToolInput {
|
||||
service: GoogleWorkspaceRestService;
|
||||
name: string;
|
||||
arguments?: Record<string, unknown>;
|
||||
accessToken: string;
|
||||
fetch?: GoogleFetch;
|
||||
signal?: AbortSignal;
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export async function callGoogleWorkspaceRestTool(input: CallGoogleWorkspaceRestToolInput): Promise<CallToolResult> {
|
||||
const tool = TOOLS[input.service].find((candidate) => candidate.definition.name === input.name);
|
||||
if (!tool) throw new McpError(ErrorCode.InvalidParams, `Unknown tool: ${input.name}`);
|
||||
if (!input.accessToken) throw new GoogleWorkspaceAuthError("unauthenticated");
|
||||
const http = createGoogleHttp({ accessToken: input.accessToken, fetch: input.fetch, signal: input.signal, timeoutMs: input.timeoutMs });
|
||||
return tool.call(input.arguments, http);
|
||||
}
|
||||
Reference in new issue
Block a user