uhbarp-gmail-mcp-server
Version:
Gmail MCP Server for managing Gmail through natural language interactions with full OAuth2 authentication support
320 lines (249 loc) • 8.99 kB
Markdown
# Gmail MCP Server
A Model Context Protocol (MCP) server implementation for Gmail integration in Claude Desktop with comprehensive OAuth2 authentication support. This server enables AI assistants to manage Gmail through natural language interactions.
## ✨ Features
### 📧 Email Management
- **Send emails** with HTML/text content, attachments, and international character support
- **Read email messages** with advanced MIME structure handling and content extraction
- **Search emails** with complex criteria (sender, date range, Gmail search syntax)
- **List emails** in inbox, sent, or custom labels with detailed information
- **Download attachments** with full metadata and content retrieval
- **Email organization** with read/unread marking and label management
### 🏷️ Label & Organization
- **Complete label management** - create, update, delete, and list all Gmail labels
- **Move emails** between labels and folders efficiently
- **Batch operations** for managing multiple emails simultaneously
- **Advanced filtering** with Gmail's powerful search syntax support
### 🔐 Authentication & Security
- **Flexible authentication modes**: Single-user and multi-user support
- **OAuth2 integration** with auto browser launch and manual link options
- **Secure token management** with automatic refresh and local storage
- **User isolation** in multi-user mode for privacy and security
### ⚡ Performance & Usability
- **Batch operations** for efficient bulk email management
- **One-time authentication** with persistent session storage
- **Clickable authentication links** for manual control
- **Comprehensive error handling** and user-friendly messages
## 🚀 Quick Start
### Using npx (Recommended)
```bash
# Set up Gmail API credentials first
npx gmail-mcp-server --setup-auth
# Start the server
npx gmail-mcp-server
```
### Using with Claude Desktop
1. **Configure your credentials** (choose one method):
**Option A: Environment Variables**
```bash
export GMAIL_CLIENT_ID="your_client_id"
export GMAIL_CLIENT_SECRET="your_client_secret"
```
**Option B: Setup Command**
```bash
npx gmail-mcp-server --setup-auth
```
2. **Add to Claude Desktop config** (`~/Library/Application Support/Claude/claude_desktop_config.json`):
```json
{
"mcpServers": {
"gmail": {
"command": "npx",
"args": ["gmail-mcp-server"],
"env": {
"GMAIL_CLIENT_ID": "your_client_id",
"GMAIL_CLIENT_SECRET": "your_client_secret"
}
}
}
}
```
3. **Start using Gmail features**:
- "Help me authenticate with Gmail"
- "Send an email to john@example.com about tomorrow's meeting"
- "Show me unread emails from this week"
- "Search for emails with attachments from my boss"
## 🔧 Available Tools
### 📧 Email Management (8 tools)
- **`send_email`** - Send emails with HTML content, attachments, and international character support
- **`read_email`** - Read email messages with advanced MIME structure handling
- **`search_emails`** - Search emails with various criteria (sender, subject, date range, Gmail syntax)
- **`list_emails`** - List emails in inbox, sent, or custom labels/folders
- **`get_attachment`** - Download and retrieve email attachments
- **`mark_email`** - Mark emails as read or unread
- **`move_email`** - Move emails to different labels/folders
- **`delete_email`** - Permanently delete email messages
### 🏷️ Label Management (4 tools)
- **`get_labels`** - List all Gmail labels (system and user-defined)
- **`create_label`** - Create new Gmail labels/folders
- **`update_label`** - Update existing label names or visibility
- **`delete_label`** - Delete Gmail labels
### ⚡ Batch Operations (3 tools)
- **`batch_mark_read`** - Mark multiple emails as read in one operation
- **`batch_move_emails`** - Move multiple emails to a label in one operation
- **`batch_delete_emails`** - Delete multiple emails in one operation
### 🔐 Authentication Tools (4 tools)
- **`quick_authenticate`** - One-time authentication with auto browser launch (single-user mode)
- **`get_auth_link`** - Get clickable authentication link for manual control (single-user mode)
- **`authenticate_user`** - Start authentication flow for new users (multi-user mode)
- **`get_my_session_info`** - View your own session information (multi-user mode)
**Total: 19 tools** (15 Gmail operations + 4 authentication tools)
## 🛠️ Installation & Setup
### Global Installation
```bash
npm install -g gmail-mcp-server
```
### Manual Installation
```bash
# Clone and build
git clone <repository-url>
cd gmail-mcp-server
npm install
npm run build
# Set up authentication
node dist/index.js --setup-auth
# Start server
node dist/index.js
```
## 🔑 Authentication Setup
### Step 1: Google Cloud Console Setup
1. Go to [Google Cloud Console](https://console.developers.google.com/)
2. Create a new project or select existing project
3. Enable the Gmail API:
- Navigate to "APIs & Services" > "Library"
- Search for "Gmail API" and enable it
4. Create OAuth 2.0 credentials:
- Go to "APIs & Services" > "Credentials"
- Click "Create Credentials" > "OAuth 2.0 Client ID"
- Choose "Desktop application" or "Web application"
- Add redirect URI: `http://localhost:3000/oauth2callback`
5. Download the credentials JSON file
### Step 2: Configure Credentials
**Method 1: Environment Variables (Recommended)**
```bash
export GMAIL_CLIENT_ID="your_client_id_here"
export GMAIL_CLIENT_SECRET="your_client_secret_here"
```
**Method 2: Credentials File**
```bash
# Save your downloaded JSON file as:
~/.gmail-mcp/credentials.json
```
### Step 3: Authentication Modes
**Single-User Mode (Personal Use)**
```bash
gmail-mcp-server
# Use quick_authenticate or get_auth_link tools
```
**Multi-User Mode (Teams/Shared)**
```bash
gmail-mcp-server --multi-user
# Use authenticate_user tool for each user
```
## 📖 Usage Examples
### Sending Emails
```javascript
{
"tool": "send_email",
"arguments": {
"to": ["colleague@company.com"],
"subject": "Project Update",
"html": "<h2>Status Report</h2><p>The project is <b>on track</b>!</p>",
"attachments": [{
"filename": "report.pdf",
"content": "base64_encoded_content",
"contentType": "application/pdf"
}]
}
}
```
### Advanced Email Search
```javascript
{
"tool": "search_emails",
"arguments": {
"from": "boss@company.com",
"after": "2024/01/01",
"hasAttachment": true,
"query": "is:unread has:attachment",
"maxResults": 20
}
}
```
### Batch Operations
```javascript
{
"tool": "batch_move_emails",
"arguments": {
"messageIds": ["msg1", "msg2", "msg3"],
"labelId": "INBOX",
"removeLabelIds": ["UNREAD"]
}
}
```
## 🎯 Command Line Options
- `--setup-auth` - Configure Gmail API credentials
- `--reset-auth` - Clear stored authentication tokens
- `--multi-user` - Enable multi-user authentication mode
- `--debug` - Enable detailed debug logging
- `--help` - Show help information
## 🔒 Security & Privacy
- **Local token storage** in `~/.gmail-mcp/token.json`
- **User isolation** in multi-user mode prevents cross-user data access
- **OAuth2 compliance** with secure token refresh
- **No external data transmission** - all data stays local
- **Configurable scopes** for minimal required permissions
## 📊 Logging & Debugging
Debug logs are written to: `/tmp/gmail-mcp-server.log`
Enable debug mode:
```bash
gmail-mcp-server --debug
```
## 🚨 Troubleshooting
### Common Issues
**"Gmail credentials not configured"**
- Set environment variables or run `--setup-auth`
- Ensure credentials file exists at correct path
**"Access blocked" during OAuth**
- Add your email as test user in Google Cloud Console
- Or publish your OAuth app for production use
**Authentication timeout**
- Use `--reset-auth` to clear old tokens
- Check that redirect URI matches console settings
**Permission errors**
- Verify Gmail API is enabled in Google Cloud Console
- Ensure all required OAuth scopes are granted
### Reset Authentication
```bash
gmail-mcp-server --reset-auth
```
## 🔧 Development
### Local Development
```bash
npm run dev
```
### Build Project
```bash
npm run build
```
### Version Management
```bash
# Bump patch version (1.0.0 → 1.0.1)
npm run version-bump
# Bump minor version (1.0.0 → 1.1.0)
npm run version-bump minor
# Bump major version (1.0.0 → 2.0.0)
npm run version-bump major
```
## 📋 Requirements
- **Node.js**: >=18.0.0
- **Gmail account** with API access
- **Google Cloud Project** with Gmail API enabled
## 📄 License
MIT License - see LICENSE file for details.
## 🤝 Contributing
Contributions welcome! Please check our issues and contributing guidelines.
## 🆘 Support
For issues and questions:
1. Check troubleshooting section above
2. Review debug logs in `/tmp/gmail-mcp-server.log`
3. Open an issue with relevant log information