Skip to main content
Glama
gmail-mcp-server

gmail-mcp-server

by flt-sudo

gmail-mcp-server

CI

Case study and the rest of my work: flt-sudo.github.io

MCP server that manages multiple Gmail accounts under one Google OAuth client, with per-call account routing and cross-account search.

  • 12 tools, all prefixed gmail_: account management (add / list / remove), read (search / thread / message / labels), write (send / reply / draft / labels / trash)

  • Every inbox tool takes an optional account (email or alias); gmail_search_threads also accepts account: "all" to fan out across every stored account and merge results by date

  • Per-account access levels chosen at add time: readonly, modify (the default), or send. Tools that need more access than an account has refuse with a clear message instead of a raw Google 403

  • Tokens live in ~/.config/gmail-mcp/accounts.json (file 0600 in a 0700 directory, refresh tokens only — no access tokens are persisted)

  • Runs over stdio for a local client, or over Streamable HTTP with bearer-token auth for a hosted setup

  • Unit tests, protocol checks on both transports, and a secret scan run in CI on every push

Requirements

  • Node.js ≥ 18

  • A Google Cloud OAuth client (Desktop app) — see below

Related MCP server: gmail-mcp

Google Cloud setup (one-time)

  1. Go to Google Cloud Console and create (or pick) a project.

  2. Enable the Gmail API: APIs & Services → Library → search "Gmail API" → Enable.

  3. Configure the OAuth consent screen (APIs & Services → OAuth consent screen):

    • User type: External is fine for personal accounts.

    • Fill in the required app name / support email fields.

    • Publishing status: set to "In production." This matters: in Testing mode, Google expires refresh tokens after 7 days, so you would have to re-authenticate every account weekly. In production status, tokens persist.

    • You do not need Google's app verification for personal use. During consent you'll see an "unverified app" warning — click Advanced → Go to (app name). This is expected and acceptable for a private tool.

  4. Create the OAuth client: APIs & Services → Credentials → Create Credentials → OAuth client ID → Application type: Desktop app.

  5. Copy the client ID and client secret and provide them to the server one of two ways:

    Option A — environment variables (e.g. in your MCP client config):

    GMAIL_MCP_CLIENT_ID=xxxxx.apps.googleusercontent.com
    GMAIL_MCP_CLIENT_SECRET=GOCSPX-xxxxx

    Option B — config file at ~/.config/gmail-mcp/client.json:

    { "client_id": "xxxxx.apps.googleusercontent.com", "client_secret": "GOCSPX-xxxxx" }

If credentials are missing, tools return an error pointing back at this section — the server itself never crashes over it.

Install & build

npm install
npm run build

The server binary is dist/index.js (stdio transport; all logging goes to stderr).

Hooking it up to Claude

Claude Code (~/.claude.json, or per-project .mcp.json) / Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "gmail": {
      "command": "node",
      "args": ["/absolute/path/to/gmail-mcp-server/dist/index.js"],
      "env": {
        "GMAIL_MCP_CLIENT_ID": "xxxxx.apps.googleusercontent.com",
        "GMAIL_MCP_CLIENT_SECRET": "GOCSPX-xxxxx"
      }
    }
  }
}

(Omit the env block if you use ~/.config/gmail-mcp/client.json.)

With Claude Code you can also add it from the CLI:

claude mcp add gmail -- node /absolute/path/to/gmail-mcp-server/dist/index.js

Running over HTTP (hosted)

node dist/index.js --http serves MCP over Streamable HTTP at /mcp, stateless, with a /healthz endpoint.

Env var

Default

Purpose

GMAIL_MCP_HTTP_TOKEN

required

Bearer token clients must send. At least 32 characters; the server refuses to start without it. Generate with openssl rand -hex 32.

GMAIL_MCP_HTTP_HOST

127.0.0.1

Interface to bind. Use 0.0.0.0 only behind a reverse proxy.

GMAIL_MCP_HTTP_PORT

3333

Port.

Requests without the right Authorization: Bearer … header get 401. The token check is constant-time.

Docker:

docker build -t gmail-mcp-server .
docker run -d -p 127.0.0.1:3333:3333 \
  -e GMAIL_MCP_HTTP_TOKEN="$(openssl rand -hex 32)" \
  -e GMAIL_MCP_CLIENT_ID=... -e GMAIL_MCP_CLIENT_SECRET=... \
  -v gmail-mcp-data:/data gmail-mcp-server

Tokens are stored under /data/.config/gmail-mcp/ in the volume.

Adding accounts on a hosted server. The consent flow opens a browser on the machine running the server, so it does not work remotely. Add accounts on your own machine with node scripts/add-account.mjs [--readonly | --send] [--alias name], then copy ~/.config/gmail-mcp/accounts.json into the volume.

Before exposing it to the internet:

  • Terminate TLS in front of it with Caddy, nginx, or a platform load balancer. Never send the bearer token over plain HTTP.

  • Treat the token like a password. Anyone holding it can use every stored account at its access level.

  • The bearer token is a single shared secret, suited to one owner. Multi-user hosting should use the MCP authorization spec (OAuth 2.1 with protected-resource metadata), which is the planned next step.

Adding accounts

Ask your MCP client to call gmail_add_account. A browser opens for Google consent (the URL is also returned in the tool response in case it doesn't). The flow runs on an ephemeral 127.0.0.1 loopback listener and times out after 5 minutes.

  • Pass access to choose what the account can do: "readonly", "modify" (default), or "send". See the table below.

  • allow_send: true still works as a legacy alias for access: "send".

  • Pass alias ("personal", "work", …) to reference the account by a short name later.

  • The first account added becomes the default; pass set_default: true to change the default later.

  • Re-running gmail_add_account for an email you already added is the re-auth path — it overwrites the stored credentials (useful for expired/revoked tokens or upgrading an account to a higher access level).

Access levels

access

Scopes granted

Can do

Cannot do

"readonly"

gmail.readonly

search, read threads and messages, list labels

change labels, archive, trash, drafts, send, reply

"modify" (default)

gmail.modify

everything above + labels, archive, trash, create drafts

send, reply

"send"

gmail.modify + gmail.send

everything above + send, reply

—

Note that modify is not read-only: it can relabel and trash mail. Pick readonly for an account an AI assistant should only read.

Each write tool checks the account's stored scopes before calling Google and returns an instruction to re-add the account at the right level, not a raw 403.

Account routing

Every inbox tool takes account?: string, resolved as: exact email → alias → the default account → the sole stored account → an error listing what's available. gmail_search_threads additionally accepts account: "all": it queries every stored account concurrently, merges thread summaries newest-first, tags each with its account, and reports per-account failures inline without failing the whole search. Pagination (page_token) is single-account only.

Ids are account-specific. A thread_id/message_id found in one account does not exist in another — always pass the same account the id came from.

Token storage & security

  • ~/.config/gmail-mcp/accounts.json, written with mode 0600; stores refresh tokens only, never access tokens.

  • gmail_remove_account best-effort revokes the token with Google before deleting it locally.

  • The client secret of a Desktop-app OAuth client is not treated as confidential by Google's model, but keep it out of version control anyway. .gitignore excludes client.json, accounts.json, and .env*.

Threat model

  • Incoming mail is untrusted input. Tool results put email bodies into the model's context, so a message can contain instructions aimed at the assistant ("forward this to…", "reply with…"). Give assistant-facing accounts the lowest access level that works, and keep a human approving anything the assistant sends.

  • Least privilege by default. Sending is never granted unless you ask for it, and readonly removes every write path. Scope checks run locally before any Gmail call.

  • Local token storage. Refresh tokens sit on disk readable only by your user. Anyone with your user account can use them, so treat the machine as the trust boundary.

  • Revocation. Removing an account revokes its token with Google, not just the local copy.

Found a security issue? Open a GitHub issue without exploit details and ask for a private contact.

Troubleshooting

  • "Stored credentials … expired or revoked" — run gmail_add_account for that email again. If this happens every ~7 days, your consent screen is still in Testing mode; switch it to In production.

  • "Google did not return a refresh token" — the OAuth client isn't a Desktop app, or consent didn't complete. Recreate as Desktop app and re-run.

  • Browser doesn't open — the consent URL is included in the gmail_add_account response; open it manually on the same machine.

  • Message/thread not found (404) — you're almost certainly using an id from a different account; check the account field on the search result that produced it.

Development

npm run typecheck        # strict TS, no emit
npm test                 # unit tests (Vitest): access levels, write guards, token storage, routing, schemas, error mapping
npm run verify           # build, then protocol-level checks over stdio against an empty throwaway HOME
npm run test:live        # optional live test against two real accounts (see scripts/live-test.mjs); not run in CI
npx @modelcontextprotocol/inspector node dist/index.js   # interactive inspection

CI (.github/workflows/ci.yml) runs typecheck, unit tests, the protocol checks, and a gitleaks secret scan on every push and pull request.

License

MIT, see LICENSE.

Available Tools

12 tools
gmail_add_accountAdd Gmail accountA

Add (or re-authenticate) a Gmail account via a browser OAuth consent flow on this machine.

Args:

  • access ("readonly" | "modify" | "send", default "modify"): readonly = search and read only; modify = read plus labels, trash, drafts; send = modify plus send and reply.

  • allow_send (boolean, legacy): same as access "send"; ignored when access is set.

  • alias (string, optional): short name usable anywhere an 'account' parameter is accepted.

  • set_default (boolean, default false): make this the default account. The first account added is always the default.

Returns: the authenticated email address and granted scopes. A browser window opens for consent; if it does not, the consent URL is included in the response for manual opening. Re-adding an existing email overwrites its stored credentials (this is the re-auth path).

Examples:

  • {"access": "readonly"} — add a read-only account

  • {} — add an account that can read, label, trash, and draft, but not send

  • {"access": "send", "alias": "work", "set_default": true}

Error Handling: returns an actionable error if OAuth client credentials are missing (see README setup), if the user denies consent, or if the flow times out (5 minutes).

Inputs: alias, access, allow_send, set_default.

gmail_create_draftCreate Gmail draftA

Create a plain-text draft (saved to the account's Drafts folder; nothing is sent). Works without the send scope; needs access "modify" or "send" (gmail.modify).

Args:

  • to (string[], required), cc (string[], optional), bcc (string[], optional): recipient addresses.

  • subject (string, required), body (string, required): plain text.

  • account (string, optional): email or alias. Omit for the default account.

Returns: the draft id, its message id, and the account it was created in.

Examples:

  • {"to": ["alice@example.com"], "subject": "Draft: proposal", "body": "First pass..."}

  • {"to": ["b@x.com"], "subject": "Hi", "body": "...", "account": "personal"}

Error Handling: expired credentials return a re-auth instruction naming the account.

Inputs: to (required), body (required), subject (required), cc, +2 more.

gmail_get_messageGet Gmail messageA
Read-onlyIdempotent

Fetch a single message with full body text and attachment metadata.

Args:

  • message_id (string, required): Gmail message id. Message ids are ACCOUNT-SPECIFIC — pass the same 'account' the id came from.

  • account (string, optional): email or alias. Omit for the default account.

  • response_format: 'markdown' (default) or 'json'.

Returns: normalized message (from/to/cc, date, subject, labels, body text) plus attachment metadata (filename, mimeType, size, attachment_id). Attachment CONTENT download is not supported in v1.

Examples:

  • {"message_id": "18c2f5a7b3d9e1f0"}

  • {"message_id": "18c2f5a7b3d9e1f0", "account": "personal", "response_format": "json"}

Error Handling: a 404 usually means the id belongs to a different account.

Inputs: message_id (required), account, response_format.

gmail_get_threadGet Gmail threadA
Read-onlyIdempotent

Fetch a full thread — every message with normalized headers and body text.

Args:

  • thread_id (string, required): from gmail_search_threads. Thread ids are ACCOUNT-SPECIFIC — pass the same 'account' the id came from.

  • account (string, optional): email or alias. Omit for the default account.

  • response_format: 'markdown' (default) or 'json'.

Returns: all messages in the thread (from/to/cc, date, subject, labels, body text, attachment metadata). Long threads are truncated to fit the response limit, with a note saying how many messages were shown; use gmail_get_message for a specific message's full content.

Examples:

  • {"thread_id": "18c2f5a7b3d9e1f0"}

  • {"thread_id": "18c2f5a7b3d9e1f0", "account": "work", "response_format": "json"}

Error Handling: a 404 usually means the id belongs to a DIFFERENT account — check the 'account' field on the search result that produced the id.

Inputs: thread_id (required), account, response_format.

gmail_list_accountsList Gmail accountsA
Read-onlyIdempotent

List every stored Gmail account: email, alias, access level (read-only, read+modify, or read+modify+send), whether it is the default, and when it was added. Tokens are never exposed.

Args: none.

Returns: one line per account, or a note that no accounts are configured.

Examples:

  • {} — list all accounts

Error Handling: returns an error only if the local accounts file is unreadable or corrupt.

Inputs: no named parameters.

gmail_list_labelsList Gmail labelsA
Read-onlyIdempotent

List every label in an account — system labels (INBOX, UNREAD, STARRED, SPAM, TRASH, ...) and user labels — with their ids. gmail_modify_labels operates on label IDS, so call this first to translate names to ids.

Args:

  • account (string, optional): email or alias. Omit for the default account.

  • response_format: 'markdown' (default) or 'json'.

Returns: label name, id, and type (system/user) for every label.

Examples:

  • {}

  • {"account": "work", "response_format": "json"}

Error Handling: expired credentials return a re-auth instruction naming the account.

Inputs: account, response_format.

gmail_modify_labelsModify Gmail labelsA
Idempotent

Add and/or remove labels on one message or one whole thread. This is also how you archive and mark read/unread:

  • Archive: remove_label_ids: ["INBOX"]

  • Mark read: remove_label_ids: ["UNREAD"] · Mark unread: add_label_ids: ["UNREAD"]

  • Star: add_label_ids: ["STARRED"]

Args:

  • message_id OR thread_id (exactly one, required): target. Ids are account-specific.

  • add_label_ids (string[], optional), remove_label_ids (string[], optional): label IDS, not names — call gmail_list_labels to translate. At least one of the two is required.

  • account (string, optional): email or alias. Omit for the default account.

Returns: confirmation with the resulting label set (message) or affected thread id.

Examples:

  • {"message_id": "18c2...", "remove_label_ids": ["UNREAD"]}

  • {"thread_id": "18c2...", "add_label_ids": ["STARRED"], "remove_label_ids": ["INBOX"], "account": "work"}

Error Handling: unknown label ids return a Gmail error — list labels first. A 404 usually means the id belongs to a different account.

Inputs: no named parameters.

gmail_remove_accountRemove Gmail accountA
DestructiveIdempotent

Remove a stored Gmail account by email or alias. Best-effort revokes the refresh token with Google, then deletes the local entry. If the removed account was the default, another stored account becomes the default (or the default is cleared).

Args:

  • account (string, required): email or alias to remove.

Returns: confirmation, including whether remote revocation succeeded and the new default account, if any.

Examples:

Error Handling: removing an unknown account returns an error listing available accounts. Revocation failures are ignored (the local entry is still deleted), making this safe to repeat.

Inputs: account (required).

gmail_reply_to_threadReply to Gmail threadA

Reply to an existing thread from the account that owns it, with correct In-Reply-To/References threading headers. REQUIRES the account to have been added with access: "send".

Args:

  • thread_id (string, required): the thread to reply within (account-specific — use the same account the id came from).

  • body (string, required): plain-text reply body.

  • reply_all (boolean, default false): false replies only to the last message's sender (or Reply-To); true also includes everyone on that message's To/Cc lines (minus this account).

  • account (string, optional): email or alias. Omit for the default account.

Returns: confirmation echoing the sending account, recipients, and the new message id + thread id.

Examples:

  • {"thread_id": "18c2f5a7b3d9e1f0", "body": "Sounds good — Thursday works."}

  • {"thread_id": "18c2f5a7b3d9e1f0", "body": "Looping everyone in.", "reply_all": true, "account": "work"}

Error Handling: accounts without send access get a re-add instruction. A 404 usually means the thread id belongs to a different account.

Inputs: body (required), thread_id (required), account, reply_all.

gmail_search_threadsSearch Gmail threadsA
Read-onlyIdempotent

Search threads with full Gmail search syntax, in one account or across all stored accounts.

Args:

  • query (string, required): Gmail search syntax. Examples: 'from:alice@example.com is:unread', 'newer_than:7d', 'has:attachment subject:"invoice"', 'to:me label:starred'.

  • account (string, optional): email or alias to search; the literal 'all' fans out to every stored account concurrently, merges results by date (newest first), and tags each thread with its account. Omit for the default account.

  • max_results (1–50, default 10): per-account cap.

  • page_token (optional): continue a previous single-account search. NOT supported with account:'all' — in that mode each account instead reports has_more; narrow the query or search one account to paginate.

  • response_format: 'markdown' (default) or 'json'.

Returns: thread-level summaries only (thread_id, account, participants, date, subject, snippet, message_count) — never full bodies. Use gmail_get_thread with the thread_id AND the same account to read a thread.

Examples:

  • {"query": "is:unread newer_than:2d"}

  • {"query": "subject:"invoice" has:attachment", "account": "all", "max_results": 20}

Error Handling: in 'all' mode, per-account failures are reported inline without failing the whole call. Expired credentials return a re-auth instruction naming the affected account.

Inputs: query (required), account, page_token, max_results, +1 more.

gmail_send_messageSend Gmail messageA

Send a new plain-text email from one of the stored accounts. REQUIRES the account to have been added with access: "send".

Args:

  • to (string[], required), cc (string[], optional), bcc (string[], optional): recipient addresses.

  • subject (string, required), body (string, required): plain text (v1 — no HTML, no attachments).

  • account (string, optional): email or alias to send FROM. Omit for the default account.

Returns: confirmation echoing the sending account, recipients, and the new message and thread ids.

Examples:

  • {"to": ["alice@example.com"], "subject": "Meeting notes", "body": "Attached below..."}

  • {"to": ["a@x.com"], "cc": ["b@x.com"], "subject": "Hi", "body": "...", "account": "work"}

Error Handling: if the account was added read-only, this returns an instruction to re-add it with access: "send" (use gmail_create_draft instead if the account should not send).

Inputs: to (required), body (required), subject (required), cc, +2 more.

gmail_trash_messageTrash Gmail message or threadA
DestructiveIdempotent

Move one message or one whole thread to Trash. RECOVERABLE — Gmail keeps trashed mail for ~30 days and it can be restored from the Trash folder; nothing is permanently deleted by this tool.

Args:

  • message_id OR thread_id (exactly one, required): target. Ids are account-specific.

  • account (string, optional): email or alias. Omit for the default account.

Returns: confirmation of what was trashed and in which account.

Examples:

  • {"message_id": "18c2f5a7b3d9e1f0"}

  • {"thread_id": "18c2f5a7b3d9e1f0", "account": "personal"}

Error Handling: a 404 usually means the id belongs to a different account — check the 'account' field on the search result that produced the id.

Inputs: no named parameters.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.6/5.0

    Scored across 12 tools

    Disambiguation5/5

    Every tool targets a distinct action-resource pair: account management, search/read, send/reply/draft, labels, and trash are cleanly separated. Even similar tools like get_message and get_thread are clearly scoped by resource type, and list_labels explicitly feeds modify_labels without overlap.

    Naming Consistency5/5

    All tools use the consistent gmail_verb_noun pattern with snake_case, making the action and target predictable. Minor variation like reply_to_thread instead of reply_thread does not break the overall convention.

    Tool Count5/5

    Twelve tools is well-scoped for a Gmail server: account lifecycle, search/read, send/reply/draft, labels, and trash each get focused coverage without redundancy. The count is solidly within the ideal range.

    Completeness4/5

    Core Gmail workflows are well covered: search, read, send, reply, draft, label modification, trash, and multi-account management. Minor gaps exist—no attachment content download, no draft editing/deletion, and no label create/delete—but these are workable and do not leave the main workflows dead-ended.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Connect multiple Gmail accounts to any MCP client, enabling search, read, draft, send, label, and organize mail across unlimited accounts with local-only OAuth token storage.
      22
      9
      MIT
    • F
      license
      Not graded
      quality
      B
      maintenance
      Enables interacting with multiple Gmail accounts through a single MCP server, supporting search, labels, drafts, and thread management with per-account OAuth.
      1
      -
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables simultaneous management of multiple Gmail accounts through MCP, allowing per-account reads and writes with verified labels and parallel search across all mailboxes.
      MIT