Skip to main content
Glama
gmails-reader

gmails-reader

by ruliana
README.md
# gmails-reader

A remote [MCP](https://modelcontextprotocol.io) server on Cloudflare Workers that searches and reads **several personal Gmail accounts** from one connector in Claude or ChatGPT.

- **Read-only.** Google access uses only the `gmail.readonly` scope. Nothing can send, delete or modify mail.
- **Invite-only, private per user.** Only Google accounts listed in the `ALLOWED_EMAILS` secret can connect (you and a few friends). Each user sees only the Gmail accounts *they* linked, never anyone else's. Nothing about the users is in the code; it all comes from secrets.
- **Many Gmail accounts per user.** Signing in links your own inbox. The `link_account` tool gives you a one-time link for any other `@gmail.com` account; authorize it and it becomes searchable for you. Two users can link the same Gmail (e.g. a family account) independently.
- **Gmail advanced search across all accounts.** From, to, subject, words, exact phrase, exclusions, date ranges, relative age, size, attachments, labels, folders, categories, read/starred state, or raw Gmail syntax.
- **Storage.** Google refresh tokens are AES-256-GCM encrypted (key derived from `APP_SECRET`) in a D1 database on your Cloudflare account. MCP client tokens live in Workers KV, hashed, via [`workers-oauth-provider`](https://github.com/cloudflare/workers-oauth-provider).

## Tools

| Tool | What it does |
| --- | --- |
| `search_emails` | Structured Gmail advanced search across all linked accounts (or some). Returns summaries newest first, with paging per account. |
| `get_message` | One email: headers, plain-text body (HTML converted), attachment list. |
| `get_thread` | A whole conversation. |
| `get_attachment_text` | Content of a text attachment (txt, csv, json, html, ics…). |
| `list_labels` | Labels of an account, for the `label` filter. |
| `list_accounts` | Linked accounts and their status. |
| `link_account` | Takes a Gmail address; returns a one-time URL (15 min) to authorize it, or re-link one marked `needs_relink`. |
| `unlink_account` | Remove one of your linked accounts (revokes the Google token unless another user still links that Gmail). |
| `search`, `fetch` | Simple query + fetch-by-id pair that ChatGPT connectors and deep research expect. |

`search_emails` fields: `query` (raw Gmail syntax), `from`, `to`, `cc`, `bcc`, `subject`, `has_words`, `exact_phrase`, `doesnt_have`, `after`, `before` (YYYY-MM-DD), `newer_than`, `older_than` (`7d`, `3m`, `1y`), `has_attachment`, `filename`, `has` (drive, document, spreadsheet, …), `label`, `in` (inbox, sent, anywhere, …), `is` (unread, starred, important, …), `category`, `larger`, `smaller`, `list`, `deliveredto`, `rfc822msgid`, plus `accounts`, `max_results`, `page_tokens`, `include_spam_trash`.

## Setup

You need a Cloudflare account (the free plan works), a Google account, and Node.js 20+. It takes about 20 minutes.

### 1. Deploy to Cloudflare

Easiest: fork or push this repository to GitHub, add the two Cloudflare secrets described in [Continuous deployment](#continuous-deployment), then run **Actions → CI → Run workflow** on `main`. The deploy job creates the KV namespace (`gmails-reader-oauth`) and the D1 database (`gmails-reader`) on first run, applies migrations and deploys.

Or from your machine:

```sh
git clone https://github.com/ruliana/gmails-reader.git
cd gmails-reader
npm install
npx wrangler login
npx wrangler kv namespace create gmails-reader-oauth   # put its id in wrangler.jsonc (don't commit it)
npx wrangler d1 create gmails-reader                   # put its database_id in wrangler.jsonc (don't commit it)
npm run db:migrate
npx wrangler deploy
```

The deploy prints your Worker URL, e.g. `https://gmails-reader.<your-subdomain>.workers.dev`. Below it is called `BASE_URL`. (If you put the Worker on a custom domain, use that domain everywhere instead.)

### 2. Create the Google OAuth app

In the [Google Cloud console](https://console.cloud.google.com/):

1. **Create a project** (any name).
2. **Enable the Gmail API:** APIs & Services → Library → "Gmail API" → Enable.
3. **Google Auth Platform → Branding:** app name (anything, e.g. "My Gmail reader"), your email as support and developer contact. Save.
4. **Audience:** user type **External**. Then click **Publish app** so the status is **In production**. Do *not* submit for verification.
   - Why: in *Testing*, Google expires refresh tokens after 7 days, so every account would need re-linking weekly. In *In production* without verification, tokens don't have that limit; the cost is an "unverified app" warning at sign-in and a cap of 100 users, fine for you and a few friends (the cap counts every Google account that ever authorizes, linked ones included).
5. **Data access → Add or remove scopes:** add `openid`, `.../auth/userinfo.email` and `https://www.googleapis.com/auth/gmail.readonly`. Save.
6. **Clients → Create client:** type **Web application**. Under *Authorized redirect URIs* add exactly:
   - `BASE_URL/callback` (user sign-in)
   - `BASE_URL/link/callback` (linking Gmail accounts)
7. Copy the **Client ID** and **Client secret**.

When you sign in you will see "Google hasn't verified this app". Click **Advanced → Go to … (unsafe)**, and on the next screen keep the Gmail permission **ticked** (if it's unticked the link is refused).

### 3. Set the secrets and deploy

```sh
npx wrangler secret put GOOGLE_CLIENT_ID       # from step 2.7
npx wrangler secret put GOOGLE_CLIENT_SECRET   # from step 2.7
npx wrangler secret put ALLOWED_EMAILS         # who may use the server, e.g. you@gmail.com,friend@gmail.com
openssl rand -base64 48                        # generate a value for the next one
npx wrangler secret put APP_SECRET             # at least 32 characters; keep a copy somewhere safe
npx wrangler deploy
```

Opening `BASE_URL` in a browser should now show a one-line page. If a secret is missing it says which.

`APP_SECRET` encrypts the stored Google tokens. If you change or lose it, every Gmail account must be linked again.

### 4. Connect your assistant

The MCP endpoint is **`BASE_URL/mcp`** (streamable HTTP, OAuth). Both clients discover the OAuth endpoints and register themselves automatically; you don't enter a client ID or secret.

- **Claude** (claude.ai, desktop, mobile): Settings → Connectors → **Add custom connector** → URL `BASE_URL/mcp` → Connect.
- **ChatGPT:** Settings → Apps & Connectors → Advanced settings → enable **Developer mode**, then **Create** a connector with URL `BASE_URL/mcp` and authentication **OAuth**.

(Menu names in both apps change often; look for "custom connector" or "developer mode" if these moved.)

Connecting shows a short consent page on your Worker (**Allow**), then Google sign-in. Sign in with an address from `ALLOWED_EMAILS` and keep the Gmail permission ticked; anyone else is refused. That sign-in identifies you on every later connection and also links your own Gmail (read-only), so it's searchable right away. The connection stays valid as long as it's used at least once every 30 days.

### 5. Link Gmail accounts

Ask the assistant: *"Link my other Gmail, someone@gmail.com"*. It calls `link_account` with that address and shows you a URL. Open it, click **Continue with Google**, and authorize that account. It's now readable by you (only). Repeat as often as you like.

To add or remove a friend, update the `ALLOWED_EMAILS` secret. Removal takes effect on their next request.

Then try: *"Find emails from my bank in all accounts since 2024-01-01 with PDF attachments."*

## Things to know

- **Re-linking.** Google can still revoke a token: changing that Google account's password revokes Gmail tokens, as does removing access at [myaccount.google.com/permissions](https://myaccount.google.com/permissions) or 6 months without use. The account then shows `needs_relink`; call `link_account` again.
- **Limits.** Searches use Gmail's batch API (about 3 requests per account per search), so the Workers free plan (50 outbound requests per invocation) handles roughly 10–15 accounts per search.
- **Personal Gmail only.** Only `@gmail.com` / `@googlemail.com` accounts can be linked.
- **Consent per MCP client.** A new client (or a new browser) gets the Allow/Deny page before Google sign-in. This prevents another app from silently obtaining access through your Google session.

## Continuous deployment

`.github/workflows/ci.yml` runs typecheck and tests on every pull request. When they pass, it squash-merges the PR, deletes its branch, applies D1 migrations and deploys `main` to Cloudflare. A push to `main` also deploys. There is no staging: merged means live.

One-time setup in GitHub → the repository → **Settings**:

1. **Secrets and variables → Actions → Secrets:**
   - `CLOUDFLARE_API_TOKEN`: create at [dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens) from the **Edit Cloudflare Workers** template, and add the permission **Account → D1 → Edit**.
   - `CLOUDFLARE_ACCOUNT_ID`: shown by `npx wrangler whoami`, or on the Workers overview page.
2. Nothing else: the deploy job finds the KV namespace `gmails-reader-oauth` and D1 database `gmails-reader` by name and creates them if missing. (Optional: repository variables `KV_NAMESPACE_ID` / `D1_DATABASE_ID` override the lookup.)
3. **Actions → General → Workflow permissions:** leave as is; the workflow requests the write access it needs per job.

The Worker's own secrets (`GOOGLE_CLIENT_ID`, etc.) stay in Cloudflare (`wrangler secret put`); a deploy doesn't touch them.

Limits:

- Only PRs from branches in this repository auto-merge. PRs from forks run the checks but never merge or deploy.
- Draft PRs don't merge until marked ready.

## Development

```sh
cp .dev.vars.example .dev.vars   # fill in test values
npm run db:migrate:local
npm run dev                       # http://localhost:8787 (add http://localhost:8787/callback and /link/callback to the Google client to sign in locally)
npm test
npm run typecheck
```

Code map: `src/index.ts` (routing, OAuth provider), `src/auth.ts` (user sign-in, allowlist), `src/link.ts` (linking Gmail accounts), `src/mcp.ts` (tools), `src/query.ts` (search fields → Gmail query), `src/gmail.ts` (Gmail API and MIME parsing), `src/store.ts` (D1, token refresh), `src/crypto.ts`.