Gmail MCP Server
Enables AI assistants to interact with Gmail through OAuth2 authentication, allowing users to list, search, read emails, and create drafts with a safety-first design that prevents accidental sends by default.
README
📧 Gmail MCP Server
A powerful MCP (Model Context Protocol) server that enables AI assistants to interact with Gmail through OAuth2 authentication with safety-first design. Built with TypeScript and designed for seamless integration with Claude Desktop and other MCP-compatible clients.
📑 Table of Contents
- Features
- Prerequisites
- Installation
- Configuration
- Usage
- Available Tools
- Examples
- Troubleshooting
- Development
✨ Features
- 🛡️ Safety First - Draft-only mode by default prevents accidental email sends
- 📝 Smart Drafts - Create drafts for new emails and replies with custom content
- 📬 List Emails - Retrieve recent emails with advanced filtering options
- 📖 Get Email Details - Fetch complete email content including attachments info
- 🔍 Search Emails - Use Gmail's powerful search syntax to find specific emails
- ✉️ Send Emails - Direct sending (disabled by default, enable with caution)
- 🔐 Secure OAuth2 - Industry-standard authentication with refresh token support
- 🎯 Type-Safe - Full TypeScript implementation with strict typing
- 🚀 High Performance - Optimized with parallel processing and smart caching
📋 Prerequisites
Before you begin, ensure you have:
- Node.js 18.0 or higher
- npm or yarn package manager
- Google Account with Gmail enabled
- Google Cloud Console access
- Claude Desktop (optional, for integration)
📦 Installation
- Clone the repository:
git clone https://github.com/JaviEzpeleta/gmail-mcp-server.git
cd gmail-mcp-server
- Install dependencies:
npm install
- Create environment file:
cp .env.example .env
🛡️ Security Note: By default, direct email sending is disabled for safety. The server will create drafts instead, which you can review and send manually from Gmail.
⚙️ Configuration
1. Google Cloud Console Setup
-
Create or select a project:
- Go to Google Cloud Console
- Click on the project dropdown and select "New Project"
- Give your project a name (e.g., "Gmail MCP Server")
- Click "Create"
-
Enable Gmail API:
- In the sidebar, navigate to APIs & Services → Library
- Search for "Gmail API"
- Click on Gmail API from the results
- Click Enable
- Wait for the API to be enabled (usually takes a few seconds)
2. Create OAuth2 Credentials
-
Configure OAuth consent screen:
- Go to APIs & Services → OAuth consent screen
- Select "External" user type (unless you have a Google Workspace account)
- Fill in the required fields:
- App name: "Gmail MCP Server"
- User support email: Your email
- Developer contact: Your email
- Add scopes:
https://www.googleapis.com/auth/gmail.readonlyhttps://www.googleapis.com/auth/gmail.sendhttps://www.googleapis.com/auth/gmail.modify
- Add test users (important!):
- Add your Gmail address and any other accounts you want to use
- Save and continue through all steps
-
Create OAuth client:
- Go to APIs & Services → Credentials
- Click + CREATE CREDENTIALS → OAuth client ID
- Application type: Web application ⚠️ (NOT Desktop app)
- Name: "Gmail MCP Web Client"
- Configure Authorized redirect URIs:
- Click + ADD URI
- Add:
http://localhost:8765/oauth2callback(default port) - If you plan to use a custom port, add:
http://localhost:YOUR_PORT/oauth2callback
- Click Create
- Download the credentials (you'll see a download button or JSON option)
- Save the
client_idandclient_secretfrom the downloaded file
⚠️ Important: Desktop app type doesn't allow custom redirect URIs, but we need
localhost:PORT/oauth2callbackfor the OAuth flow to work. That's why we use Web application instead.
3. Generate Refresh Token
- Add credentials to .env:
GMAIL_CLIENT_ID=your_client_id_here
GMAIL_CLIENT_SECRET=your_client_secret_here
GMAIL_REFRESH_TOKEN=
# Security: Keep this false unless you need direct sending
GMAIL_ALLOW_DIRECT_SEND=false
# OAuth setup port (must match the redirect URI you configured above)
OAUTH_REDIRECT_PORT=8765
💡 Port Configuration: The
OAUTH_REDIRECT_PORTmust match the port you configured in the Google Cloud Console redirect URI. If you usedhttp://localhost:8765/oauth2callback, keep it as 8765. If you used a different port, update this value accordingly.
- Run the setup script:
npm run setup
# or
npm run dev src/get-refresh-token-desktop.ts
-
Authorize the application:
- A browser window will open automatically
- Sign in with your Google account
- Grant all requested permissions
- You'll be redirected to a success page
-
Save the refresh token:
- The terminal will display your refresh token
- Copy the complete
GMAIL_REFRESH_TOKENvalue - Add it to your
.envfile
🚀 Usage
Standalone Server
- Build the project:
npm run build
- Start the server:
npm start
The server will start and listen for MCP commands via stdio.
Claude Desktop Integration
- Build the project first:
npm run build
-
Locate Claude Desktop config:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json
- macOS:
-
Edit the configuration file:
{
"mcpServers": {
"gmail": {
"command": "node",
"args": ["/absolute/path/to/gmail-mcp-server/dist/index.js"],
"env": {
"GMAIL_CLIENT_ID": "your_client_id",
"GMAIL_CLIENT_SECRET": "your_client_secret",
"GMAIL_REFRESH_TOKEN": "your_refresh_token",
"GMAIL_ALLOW_DIRECT_SEND": "false"
}
}
}
}
-
Restart Claude Desktop
-
Verify the connection:
- Open Claude Desktop
- Look for the 🔌 icon indicating MCP connection
- Try: "List my recent emails"
🛠️ Available Tools
🛡️ Safety Notice: Tools marked with 🛡️ create drafts by default for your safety. Direct sending tools marked with 🚨 are disabled by default.
📬 list_emails
List recent emails with optional filtering.
Parameters:
maxResults(number, 1-100): Maximum emails to return (default: 10)query(string): Gmail search query (e.g., "is:unread")includeSpamTrash(boolean): Include SPAM/TRASH folders (default: false)
Example:
List my 5 most recent unread emails
📖 get_email_details
Get complete details and content of a specific email.
Parameters:
emailId(string, required): The email ID to retrieveformat(string): Level of detail - "full", "minimal", or "metadata" (default: "full")
Example:
Get the full content of email ID 18abc123def
🛡️ create_draft
Create an email draft with optional CC/BCC recipients (recommended for AI assistants).
Parameters:
to(string, required): Recipient email addresssubject(string, required): Email subjectbody(string, required): Email body (plain text or HTML)cc(string): CC recipients (comma-separated)bcc(string): BCC recipients (comma-separated)
Example:
Create a draft email to john@example.com with subject "Meeting Tomorrow" and body "Let's meet at 10 AM"
🚨 send_email (Disabled by Default)
Send an email directly with optional CC/BCC recipients.
⚠️ Security Warning: This tool is disabled by default. Set GMAIL_ALLOW_DIRECT_SEND=true to enable.
Parameters:
to(string, required): Recipient email addresssubject(string, required): Email subjectbody(string, required): Email body (plain text or HTML)cc(string): CC recipients (comma-separated)bcc(string): BCC recipients (comma-separated)
Example:
Send an email to john@example.com with subject "Meeting Tomorrow" and body "Let's meet at 10 AM"
🔍 search_emails
Search emails using Gmail's advanced search syntax.
Parameters:
query(string, required): Gmail search querymaxResults(number, 1-100): Maximum results (default: 10)includeSpamTrash(boolean): Include SPAM/TRASH (default: false)
Example Gmail search queries:
from:user@example.com- Emails from a specific sendersubject:"important meeting"- Emails with exact phrase in subjecthas:attachment- Emails with attachmentsis:unread- Unread emailsnewer_than:2d- Emails from last 2 dayslabel:work- Emails with specific label
🛡️ find_and_draft_reply
Find the latest email from a sender and create a draft reply with optional custom content.
Parameters:
senderName(string, required): Sender name or email addressreplyBody(string, optional): Custom reply content (template used if not provided)
Example:
Create a draft reply to the latest email from John Smith saying "Thanks for your message. I'll get back to you soon."
📚 Examples
Basic Usage Examples
List recent emails:
Show me my 10 most recent emails
Search for specific emails:
Search for emails from alice@example.com with attachments
Create a draft email:
Create a draft email to bob@example.com saying "Thanks for your help!"
Create a draft reply:
Draft a reply to the latest email from support@company.com
Advanced Usage Examples
Complex search:
Find all unread emails from the last week with "invoice" in the subject
Draft with CC:
Create a draft email to team@company.com with CC to manager@company.com about the project update
Get email details:
Show me the full content of the most recent email from my boss
🔧 Troubleshooting
Common Issues and Solutions
❌ Error: Missing required environment variables
Solution: Ensure all required environment variables are set in your .env file:
GMAIL_CLIENT_IDGMAIL_CLIENT_SECRETGMAIL_REFRESH_TOKENGMAIL_ALLOW_DIRECT_SEND(optional, defaults tofalse)OAUTH_REDIRECT_PORT(optional, defaults to8765)
❌ Error: redirect_uri_mismatch
Problem: OAuth setup fails with "The redirect URI in the request does not match the ones authorized for the OAuth client."
Solution:
- Go to Google Cloud Console → APIs & Services → Credentials
- Click on your OAuth client
- In "Authorized redirect URIs", ensure you have:
http://localhost:8765/oauth2callback - If using a custom port, add:
http://localhost:YOUR_PORT/oauth2callback - Make sure your
.envfile has the matchingOAUTH_REDIRECT_PORT=8765 - Important: OAuth client must be Web application type, not Desktop app
This error commonly occurs when following old documentation that suggests using "Desktop app" type, which doesn't support custom redirect URIs.
🛡️ Security: Direct email sending is disabled
This is normal and safe behavior. By default, the server creates drafts instead of sending emails directly.
Solutions:
- Recommended: Use
create_drafttool instead ofsend_email - Alternative: Set
GMAIL_ALLOW_DIRECT_SEND=truein your.envfile (not recommended for AI assistants)
❌ Error 403: access_denied
Solution:
- Go to Google Cloud Console → OAuth consent screen
- Add your email as a test user
- Re-run the token generation process
❌ Error: invalid_grant
Solution: Your refresh token has expired or is invalid
- Delete the old refresh token from
.env - Run
npm run setupagain - Complete the authorization flow
- Update
.envwith the new token
❌ Gmail API not enabled
Solution:
- Go to Google Cloud Console
- Navigate to APIs & Services → Library
- Search for "Gmail API"
- Click Enable
❌ Claude Desktop doesn't show the MCP server
Solution:
- Verify the config file path is correct
- Ensure all paths in the config are absolute paths
- Check that the built files exist in
dist/ - Restart Claude Desktop completely
- Check Claude Desktop logs for errors
❌ Rate limit exceeded
Solution:
- Gmail API has quotas (250 quota units per user per second)
- Implement exponential backoff for retries
- Reduce the number of parallel requests
🔒 Security Guidelines
Draft-First Approach
This server implements a safety-first design to prevent accidental email sends:
- Default behavior: Creates drafts that require manual review
- Protection:
send_emailtool is disabled by default - User control: Explicit environment variable required for direct sending
Recommended Usage
✅ Safe for AI assistants:
create_draft- Creates email draftsfind_and_draft_reply- Creates reply draftslist_emails,search_emails,get_email_details- Read-only operations
⚠️ Use with caution:
send_email- Only enable if you fully trust the AI assistant and understand the risks
Best Practices
- Keep
GMAIL_ALLOW_DIRECT_SEND=falseunless absolutely necessary - Review all drafts before sending manually from Gmail
- Test thoroughly in a safe environment before production use
- Monitor usage and check for unexpected behavior
🔨 Development
Available Scripts
# Development with hot reload
npm run dev
# Build TypeScript to JavaScript
npm run build
# Start production server
npm start
# Generate OAuth refresh token
npm run setup
# Run tests
npm test
# Lint code
npm run lint
Project Structure
gmail-mcp-server/
├── src/
│ ├── index.ts # Main server implementation
│ └── get-refresh-token-desktop.ts # OAuth setup utility
├── dist/ # Compiled JavaScript (generated)
├── examples/ # Usage examples
├── docs/ # Additional documentation
├── .env.example # Environment variables template
├── tsconfig.json # TypeScript configuration
├── package.json # Project dependencies
└── README.md # This file
Testing
Test the connection and basic functionality:
# Test Gmail connection
npm run dev test-gmail-connection.ts
# Test with MCP client
npm run dev test-list-emails.js
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Google Gmail API for email functionality
- Model Context Protocol for the MCP specification
- Anthropic for Claude and MCP development
📞 Support
For issues, questions, or suggestions:
- Open an issue on GitHub
- Check existing issues for solutions
- Read the Gmail API documentation
Made with ❤️ by Javi Ezpeleta
推荐服务器
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 模型以安全和受控的方式获取实时的网络信息。