Gmail MCP Server
Provides tools for managing Gmail inboxes through the Gmail API, including inbox triage, email search, thread summarization, downloading emails and attachments, drafting replies, label management, sending emails, archiving, deleting, and unsubscribing. Supports read-only mode and human-in-the-loop approval for write operations.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
Gmail MCP Server
An MCP (Model Context Protocol) server that enables Claude to manage Gmail inboxes through natural conversation. Ask Claude to triage your inbox, search emails, send messages, and more.
Features
16 Gmail Tools - Full inbox management via conversational AI
Read-Only Mode - Run with
READ_ONLY=truefor safe cross-project use (9 tools, single OAuth scope)Human-in-the-Loop Security - All write operations require explicit approval
Encrypted Token Storage - AES-256-GCM encryption for OAuth tokens at rest
Rate Limiting - Token bucket protection (100 req/min default)
Multiple Transports - stdio (local), HTTP/SSE (remote deployments)
Related MCP server: Gmail MCP Server
Quick Start
Prerequisites
Python 3.11+
Google Cloud project with Gmail API enabled
1. Install
git clone https://github.com/your-org/gmail-mcp-server.git
cd gmail-mcp-server
poetry install2. Google OAuth Setup
Go to Google Cloud Console
Create OAuth 2.0 Client ID with type "Desktop app" (required for local server flow)
Enable Gmail API in your project
Note your Client ID and Client Secret
3. Environment Variables
export GOOGLE_CLIENT_ID="your-client-id.apps.googleusercontent.com"
export GOOGLE_CLIENT_SECRET="your-client-secret"
export TOKEN_ENCRYPTION_KEY=$(openssl rand -hex 32)4. Add to Claude Code
Create or update .mcp.json in your project root:
{
"mcpServers": {
"gmail": {
"command": "poetry",
"args": ["run", "python", "-m", "gmail_mcp"],
"cwd": "/path/to/gmail-mcp-server",
"env": {
"GOOGLE_CLIENT_ID": "${GOOGLE_CLIENT_ID}",
"GOOGLE_CLIENT_SECRET": "${GOOGLE_CLIENT_SECRET}",
"TOKEN_ENCRYPTION_KEY": "${TOKEN_ENCRYPTION_KEY}"
}
}
}
}5. Verify Connection
Restart Claude Code, then run /mcp to verify the Gmail server is connected.
Configuration
Required Environment Variables
Variable | Description |
| OAuth 2.0 Client ID from Google Cloud Console |
| OAuth 2.0 Client Secret |
| 64-character hex string (256-bit AES key) |
Optional Environment Variables
Variable | Default | Description |
|
| Read-only mode — only |
|
| Transport mode: |
|
| HTTP server port (for http/sse transport) |
|
| OAuth callback port (fallback: 3001, 3002) |
|
| Logging level (DEBUG, INFO, WARNING, ERROR) |
|
| Max requests per minute per user |
|
| Approval expiration (5 min default) |
|
| Custom token storage location |
Transport Modes
Mode | Use Case |
| Local development with Claude Code/Desktop |
| Remote deployments (Replit, Docker) |
| Stateless deployments |
Read-Only Mode
Set READ_ONLY=true for safe, read-only Gmail access — ideal for a global MCP config shared across all projects.
What changes:
Full Mode (default) | Read-Only Mode | |
OAuth scopes | 4 scopes (readonly, modify, compose, labels) | 1 scope ( |
Tools registered | 16 (3 auth + 7 read + 6 write) | 9 (3 auth + 6 read) |
Write tools visible | Yes (with HITL approval) | No — Claude can't see them |
Consent screen | 4 checkboxes | 1 checkbox |
Global read-only config (~/.claude/.mcp.json):
{
"mcpServers": {
"gmail": {
"command": "gmail-mcp",
"args": [],
"env": {
"GOOGLE_CLIENT_ID": "${GOOGLE_CLIENT_ID}",
"GOOGLE_CLIENT_SECRET": "${GOOGLE_CLIENT_SECRET}",
"TOKEN_ENCRYPTION_KEY": "${TOKEN_ENCRYPTION_KEY}",
"READ_ONLY": "true"
}
}
}
}To override in a specific project (e.g., for full access), add a project-level .mcp.json without READ_ONLY or set it to "false".
Note: Switching between modes requires re-authentication (gmail_login) since Google doesn't upgrade scopes on existing tokens.
User Guide
Authentication Tools
Tool | Purpose |
| Sign in via Google OAuth (opens browser) |
| Sign out and clear stored tokens |
| Check if authenticated |
Example prompts:
"Sign me into Gmail"
"Am I logged into Gmail?"
"Sign out of Gmail"
Read Operations
These tools read data without modifying your inbox. No approval required.
Tool | Description | Read-Only |
| Categorize emails by urgency (urgent, social, newsletter, other) | Yes |
| Search using Gmail query syntax | Yes |
| Get full thread content for summarization | Yes |
| Get context for composing a reply | Yes |
| Natural language inbox queries | Yes |
| Download email as .eml, HTML, and attachments | Yes |
| Add or remove labels from messages | No* |
*gmail_apply_labels requires gmail.modify scope and is excluded in read-only mode.
Example prompts:
"Triage my inbox"
"Show me unread emails from today"
"Search for emails from boss@company.com"
"Find emails with attachments from last week"
"Summarize this email thread"
"Help me reply to this email"
"Add the 'Important' label to these messages"Gmail Query Syntax (for gmail_search):
from:sender@example.com- From specific senderto:recipient@example.com- To specific recipientsubject:keyword- Subject contains keywordafter:2024/01/01- After datehas:attachment- Has attachmentsis:unread- Unread messageslabel:important- Specific label
Write Operations (HITL Required)
All write operations use Human-in-the-Loop approval:
Tool returns a preview +
approval_idClaude shows you the preview and asks for confirmation
You approve, tool executes with the
approval_id
Tool | Description |
| Compose and send emails |
| Remove from inbox (keeps in All Mail) |
| Move to trash (deleted after 30 days) |
| Extract unsubscribe link from newsletters |
| Create a new label |
| Rename, delete, or update label visibility |
Example prompts:
"Send an email to john@example.com about the meeting tomorrow"
"Archive all newsletters from this week"
"Delete these promotional emails"
"Help me unsubscribe from this newsletter"
"Create a label called 'Projects'"
"Rename the 'Old' label to 'Archive'"Approval Flow Example:
You: "Send an email to john@example.com about the meeting"
Claude: "I'll compose this email for you:
To: john@example.com
Subject: Meeting Tomorrow
Body: Hi John, I wanted to confirm our meeting tomorrow at 2pm...
Would you like me to send this?"
You: "Yes, send it"
Claude: "Email sent successfully!"How It Works
Architecture
┌──────────┐ ┌─────────┐ ┌─────────────────┐ ┌───────────┐
│ User │ <──> │ Claude │ <──> │ Gmail MCP Server│ <──> │ Gmail API │
└──────────┘ └─────────┘ └─────────────────┘ └───────────┘
│ │
│ ┌─────┴─────┐
MCP Protocol │ Encrypted │
(JSON-RPC) │ Tokens │
└───────────┘Security Model
Layer | Protection |
HITL Approval | All write operations require explicit user confirmation |
Token Encryption | AES-256-GCM with unique IV per token |
Rate Limiting | Token bucket algorithm prevents API quota exhaustion |
Audit Logging | JSON-formatted logs to stderr for all operations |
Input Validation | Pydantic schemas validate all tool parameters |
HITL Two-Step Flow
# Step 1: No approval_id → Return preview
{
"status": "pending_approval",
"approval_id": "uuid-here",
"expires_at": "2024-01-01T12:05:00Z",
"preview": { "to": "...", "subject": "...", "body": "..." },
"message": "ACTION NOT TAKEN. Please review and confirm."
}
# Step 2: With approval_id → Execute
{
"status": "success",
"data": { "message_id": "..." }
}Approvals expire after 5 minutes (configurable via HITL_TIMEOUT_MS).
Project Structure
gmail_mcp/
├── __main__.py # Entry point, transport selection
├── server.py # FastMCP server, tool registration
├── tools/
│ ├── auth/ # gmail_login, gmail_logout, gmail_get_auth_status
│ ├── read/ # 6 read-only tools
│ └── write/ # 6 HITL-protected write tools
├── auth/
│ ├── oauth.py # Google OAuth flow (local server)
│ ├── tokens.py # AES-256-GCM encryption
│ └── storage.py # Encrypted file storage
├── gmail/
│ ├── client.py # Authenticated Gmail API client
│ ├── messages.py # Message operations
│ ├── threads.py # Thread operations
│ └── labels.py # Label management
├── hitl/
│ ├── manager.py # Approval lifecycle
│ └── models.py # Pydantic models
├── middleware/
│ ├── rate_limiter.py # Token bucket rate limiting
│ ├── audit_logger.py # JSON logging to stderr
│ └── validator.py # Input validation
└── schemas/
└── tools.py # Tool parameter modelsTroubleshooting
Port Already in Use
OSError: [Errno 48] Address already in useThe OAuth callback server tries ports 3000, 3001, 3002 in sequence. To use a different port:
export OAUTH_PORT=4000Browser Doesn't Open
If running in a headless environment (SSH, Docker):
Copy the URL from the logs and open manually
Or pre-authenticate locally and copy the token file to the server
"Loopback Flow Has Been Blocked" (Error 400)
Your OAuth client type is incorrect. Google blocks loopback redirects for non-desktop apps.
Fix: In Google Cloud Console:
Delete the existing OAuth client
Create new OAuth 2.0 Client ID with type "Desktop app"
Update your environment variables with new credentials
Token Storage Errors
Ensure
~/.gmail-mcp/tokens/exists and is writableVerify
TOKEN_ENCRYPTION_KEYis exactly 64 hex charactersIf key changed, delete old token files and re-authenticate
State Mismatch Error
CSRF protection triggered. Don't reuse browser tabs from old auth attempts. Restart the login flow.
Authentication Fails Silently
Check logs with LOG_LEVEL=DEBUG:
LOG_LEVEL=DEBUG python -m gmail_mcpDevelopment
Setup
poetry install
poetry shellRun Tests
pytest --covCode Quality
ruff check . && ruff format . && mypy .Run Server Locally
# stdio transport (default)
python -m gmail_mcp
# HTTP transport
TRANSPORT=http python -m gmail_mcpKnown Limitations
Single-User Mode - Currently operates with
user_id="default". For multi-account, run separate server instances with differentTOKEN_STORAGE_PATH.No Device Flow - Gmail scopes are "restricted" and cannot use device flow. Local server flow requires a browser.
Headless Deployments - Require workarounds:
Pre-authenticate locally, copy token file to server
Use Google Workspace service account with domain-wide delegation
License
MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Connect any IMAP/SMTP mailbox to Claude & ChatGPT: search, read, sort, draft. Sends only with OK.
Connect any mailbox to Claude, ChatGPT & AI: read, send, reply, schedule & search emails.
Your mailboxes in ChatGPT and Claude: Gmail, iCloud, Fastmail, any IMAP. Passwords stay yours.
Connect Gmail, iCloud Mail, Outlook, Yahoo Mail, Fastmail and other IMAP inboxes to ChatGPT, Claude and compatible AI assistants. Find emails by meaning across languages with semantic search. Ask AI to find customer conversations, summarize deadlines and draft follow-ups. Give a sales rep access to a shared outreach inbox or bring email into a compatible CRM. Share an iCloud custom-domain inbox with teammates without their own Apple ID or iCloud+ plan. Search results may be incomplete or stale; separate permissions control mail actions.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI-powered inbox management with natural language commands through Claude Desktop. Supports sending, reading, searching, organizing emails, and managing labels using Gmail API with automatic authentication.8MIT
- FlicenseAqualityCmaintenanceEnables Claude to read, search, send, and manage Gmail messages and threads through natural language.13-
- FlicenseNot gradedqualityDmaintenanceEnables Claude to read and manage your Gmail account, including listing, searching, sending, drafting, replying to, archiving, labeling, and trashing emails via the Gmail API.-
- AlicenseAqualityBmaintenanceEnables Claude.ai and Claude Code to read and write a single Gmail mailbox, including search, drafts, sending, and label management.21MIT