Gmail MCP Server
Enables AI assistants to read, search, organize, and draft emails in Gmail inboxes with support for multiple accounts, OAuth authentication, and 26 comprehensive tools for email management.
README
Gmail MCP Server
An MCP (Model Context Protocol) server that exposes Gmail tools via Streamable HTTP transport. Enables AI assistants to read, search, organize, and draft emails in your Gmail inbox.
Quickstart
git clone https://github.com/shcallaway/gmail-mcp-server.git
cd gmail-mcp-server
# Generate secrets and create .env
npm run bin:generate-secrets
# Edit .env to add your Google OAuth credentials
# Start the server
npm run docker:up
Server runs at http://localhost:3000. Connect your Gmail at /oauth/start.
Features
- 26 Gmail tools for comprehensive inbox management
- Multi-inbox support: Connect multiple Gmail accounts per user
- Two-layer OAuth: MCP-level JWT authentication + Google OAuth for Gmail access
- Secure token storage: SQLite with AES-256-GCM encryption for refresh tokens
- Streamable HTTP transport: Stateless mode for easy deployment
- Automatic token refresh: Proactive refresh 5 minutes before expiry
Requirements
- Node.js >= 20.0.0
- Google Cloud project with Gmail API enabled
- OAuth 2.0 credentials (Web application type)
Google Cloud Setup
-
Create a project at console.cloud.google.com
-
Enable the Gmail API
- Go to APIs & Services → Library
- Search for "Gmail API" and enable it
-
Configure OAuth consent screen
- Go to APIs & Services → OAuth consent screen
- Choose "External" user type
- Fill in app name and support email
- Add scopes:
gmail.readonly,gmail.labels,gmail.modify,gmail.compose - Add your email as a test user
-
Create OAuth credentials
- Go to APIs & Services → Credentials
- Click "Create Credentials" → "OAuth client ID"
- Choose "Web application"
- Add authorized redirect URI:
http://localhost:3000/oauth/callback - Copy the Client ID and Client Secret
-
Add to .env
GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com GOOGLE_CLIENT_SECRET=your-client-secret OAUTH_REDIRECT_URI=http://localhost:3000/oauth/callback
Installation
git clone <repository-url>
cd gmail-mcp
npm install
npm run build
Configuration
Copy .env.example to .env and configure:
cp .env.example .env
Required Environment Variables
| Variable | Description |
|---|---|
PORT |
Server port (default: 3000) |
BASE_URL |
Public URL of the server |
GOOGLE_CLIENT_ID |
Google OAuth client ID |
GOOGLE_CLIENT_SECRET |
Google OAuth client secret |
OAUTH_REDIRECT_URI |
OAuth callback URL (e.g., http://localhost:3000/oauth/callback) |
TOKEN_ENCRYPTION_KEY |
32-byte key for encrypting stored tokens |
JWT_SECRET |
Secret for signing MCP-level JWTs |
Optional Variables
| Variable | Description |
|---|---|
DB_URL |
SQLite database path (default: ./data/gmail-mcp.db) |
ALLOWED_ORIGINS |
Comma-separated CORS origins |
Generating Secrets
# Generate and optionally save to .env
./bin/generate-secrets.sh
# Or use npm
npm run bin:generate-secrets
Running the Server
# Production
npm run build
npm start
# Development (with hot reload)
npm run dev
Docker
The easiest way to deploy anywhere:
npm run docker:up # Start the server
npm run docker:down # Stop the server
npm run docker:logs # Tail logs
npm run docker:restart # Restart container
npm run docker:build # Rebuild image
The SQLite database persists in ./data/ via volume mount.
The server exposes:
POST /mcp- MCP protocol endpointGET /healthz- Health checkGET /oauth/start- Initiate Gmail OAuth flowGET /oauth/callback- OAuth callback handlerGET /.well-known/oauth-protected-resource- OAuth discovery
Available Tools
All tools accept an optional email parameter to target a specific connected account. If omitted, the default account is used.
Authentication & Accounts
| Tool | Description |
|---|---|
gmail.status |
Check connection status and list connected accounts |
gmail.authorize |
Initiate OAuth flow to connect Gmail |
gmail.listAccounts |
List all connected Gmail accounts |
gmail.setDefaultAccount |
Set which account is used by default |
gmail.removeAccount |
Disconnect a Gmail account |
Reading Messages
| Tool | Description |
|---|---|
gmail.searchMessages |
Search using Gmail query syntax |
gmail.getMessage |
Get a single message by ID |
gmail.listThreads |
List conversation threads |
gmail.getThread |
Get all messages in a thread |
gmail.getAttachmentMetadata |
Get attachment info (filename, size, MIME type) |
Labels
| Tool | Description | Scope Required |
|---|---|---|
gmail.listLabels |
List all labels with counts | - |
gmail.getLabelInfo |
Get label details | - |
gmail.addLabels |
Add labels to messages/threads | gmail.labels |
gmail.removeLabels |
Remove labels from messages/threads | gmail.labels |
gmail.createLabel |
Create a custom label | gmail.labels |
Message Organization
| Tool | Description | Scope Required |
|---|---|---|
gmail.archiveMessages |
Archive messages/threads (thread-aware by default) | gmail.modify |
gmail.unarchiveMessages |
Move back to inbox (thread-aware by default) | gmail.modify |
gmail.markAsRead |
Mark as read | gmail.labels |
gmail.markAsUnread |
Mark as unread | gmail.labels |
gmail.starMessages |
Add star | gmail.labels |
gmail.unstarMessages |
Remove star | gmail.labels |
Thread-Aware Archiving: By default,
archiveMessagesandunarchiveMessageswill archive the entire thread when given amessageId. This ensures conversations leave your inbox. SetarchiveEntireThread: falseto archive individual messages only.
Drafts
| Tool | Description | Scope Required |
|---|---|---|
gmail.createDraft |
Create a new draft | gmail.compose |
gmail.listDrafts |
List all drafts | - |
gmail.getDraft |
Get draft content | - |
gmail.updateDraft |
Update existing draft | gmail.compose |
gmail.deleteDraft |
Delete a draft | gmail.compose |
OAuth Scopes
Request scopes when calling gmail.authorize:
| Scope | Permissions |
|---|---|
gmail.readonly |
Read messages, threads, labels |
gmail.labels |
Manage labels, star, mark read/unread |
gmail.modify |
Archive/unarchive messages and threads |
gmail.compose |
Create, update, and delete drafts |
Example:
{
"scopes": ["gmail.readonly", "gmail.modify", "gmail.compose"]
}
Multi-Inbox Support
Users can connect multiple Gmail accounts. The first connected account becomes the default.
Connecting Additional Accounts
Call gmail.authorize again to connect another Gmail account. Each account can have different scopes.
Targeting Specific Accounts
All tools accept an optional email parameter:
{
"query": "is:unread",
"email": "work@example.com"
}
If email is omitted, the default account is used.
Managing Accounts
// List all connected accounts
{ "tool": "gmail.listAccounts" }
// Change default account
{ "tool": "gmail.setDefaultAccount", "email": "work@example.com" }
// Disconnect an account
{ "tool": "gmail.removeAccount", "email": "old@example.com" }
Architecture
MCP Client → Fastify HTTP (/mcp) → MCP Server → Gmail Client → Google APIs
↓
Token Store (SQLite) ← encrypted credentials
Key Components
src/index.ts- Entry pointsrc/config.ts- Zod-validated configurationsrc/http/server.ts- Fastify HTTP serversrc/mcp/server.ts- MCP server with all toolssrc/gmail/client.ts- Gmail API wrapper with token refreshsrc/auth/mcpOAuth.ts- MCP-level JWT authenticationsrc/auth/googleOAuth.ts- Google OAuth flow with PKCEsrc/store/sqlite.ts- SQLite token storage with encryption (composite key for multi-account)
Development
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Type checking
npm run typecheck
# Linting
npm run lint
# Run single test file
npx vitest run tests/unit/crypto.test.ts
Claude Code Integration
Install MCP Server
Add the Gmail MCP server to your Claude Code configuration:
npm run bin:cc-install-mcp-server
This adds the server to ~/.claude.json. Make sure the server is running first.
Install Subagents
Install custom Claude Code subagents for enhanced Gmail workflows:
npm run bin:cc-install-subagents
This installs 12 specialized Gmail agents that provide intelligent email management capabilities.
Available Subagents
| Agent | Description | Example Prompt |
|---|---|---|
| gmail-inbox-explorer | Analyzes inbox structure, labels, and activity | "Explore my Gmail inbox" |
| gmail-email-triage | Prioritizes unread emails by urgency | "Help me triage my inbox" |
| gmail-email-summarizer | Summarizes emails matching search criteria | "Summarize emails from John this week" |
| gmail-draft-composer | Helps write professional email drafts | "Help me write an email to my boss" |
| gmail-inbox-cleanup | Archives old emails and reduces clutter | "Clean up my inbox" |
| gmail-follow-up-finder | Finds emails needing response or follow-up | "What emails need follow-up?" |
| gmail-action-item-extractor | Extracts tasks and deadlines from emails | "What action items are in my emails?" |
| gmail-project-email-collector | Gathers all emails about a project/topic | "Find all emails about the redesign project" |
| gmail-newsletter-manager | Manages newsletter subscriptions | "What newsletters am I subscribed to?" |
| gmail-contact-insights | Analyzes communication with a contact | "Show my email history with sarah@company.com" |
| gmail-multi-inbox-dashboard | Unified view across multiple accounts | "Overview of all my email accounts" |
| gmail-email-reply-drafter | Drafts contextual replies to threads | "Help me reply to the project deadline email" |
Example Usage
Ask Claude Code naturally and it will automatically use the appropriate agent:
"I have 50 unread emails, what needs my attention first?"
→ Uses gmail-email-triage
"Summarize the email thread about Q4 planning"
→ Uses gmail-email-summarizer
"Help me write a follow-up email to the client"
→ Uses gmail-draft-composer
"What tasks are buried in my recent emails?"
→ Uses gmail-action-item-extractor
Error Handling
The server uses JSON-RPC error codes:
| Code | Type | Description |
|---|---|---|
-32001 |
NOT_AUTHORIZED |
User not authenticated, token revoked, or insufficient scope |
-32602 |
INVALID_ARGUMENT |
Invalid input parameters or account not found |
-32000 |
GMAIL_API_ERROR |
Gmail API error or rate limit |
When invalid_grant is returned from Google (token revoked), stored tokens are cleared and the user must re-authorize.
Security
- Refresh tokens encrypted with AES-256-GCM before storage
- MCP-level JWTs (HS256) with 1-hour lifetime
- Google OAuth with PKCE support
- CSRF protection via state parameter
License
MIT
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。