Content
# MCP Email Server
A comprehensive Model Context Protocol (MCP) server for unified email management, supporting both Gmail and IMAP accounts.
## 🚀 Features
- **MCP Protocol Support**: Streaming HTTP MCP server
- **Gmail Integration**: OAuth2-based Gmail API access with automatic token management
- **IMAP Support**: Secure IMAP connections to various email providers
- **Unified Interface**: Single MCP interface for all email accounts with auto-discovery
- **Account Management**: Centralized settings and connection testing
- **Robust Error Handling**: Comprehensive timeout and error management with detailed user guidance
- **Security**: Encrypted password storage for IMAP accounts
- **Cross-Account Search**: Simultaneous search across all configured accounts
## 📋 Available MCP Tools
### 🔄 Integrated Tools (Automatic Account Type Detection)
| Tool | Description | Parameters |
|--------|-------------|----------|
| `list_emails` | Retrieve email list from any account (automatic type detection) | `account_name`, `limit?`, `folder?`, `unread_only?` |
| `search_emails` | Search emails in any account (automatic type detection) | `account_name`, `query`, `limit?` |
| `search_all_emails` | Cross-search all Gmail and IMAP accounts | `query`, `accounts?`, `limit?`, `sortBy?` |
| `get_email_detail` | Retrieve detailed email information from any account | `account_name`, `email_id` |
| `archive_email` | Archive an email in any account (automatic type detection) | `account_name`, `email_id`, `remove_unread?` |
| `send_email` | Send an email from any account (automatic type detection) | `account_name`, `to`, `subject`, `text/html`, `cc?`, `bcc?`, `attachments?` |
### 🔧 Administration Tools
| Tool | Description | Parameters |
|--------|-------------|----------|
| `list_accounts` | List configured email accounts with status | None |
| `test_connection` | Test connection to a specific account | `account_name` |
| `get_account_stats` | Retrieve comprehensive statistics for all accounts | None |
## 🛠️ Available Scripts
Located in the `scripts/` directory:
### 📧 Authentication and Setup
| Script | Purpose | Usage |
|-----------|------|----------|
| `gmail-desktop-auth.mjs` | Gmail OAuth2 authentication setup | `npx tsx scripts/gmail-desktop-auth.mjs [ACCOUNT_NAME]` |
| `cleanup-env-tokens.mjs` | Clean up and standardize environment variables | `npx tsx scripts/cleanup-env-tokens.mjs` |
| `setup-xserver.mjs` | Interactive IMAP account setup for XServer | `npx tsx scripts/setup-xserver.mjs` |
| `encrypt-password.ts` | Encrypt IMAP account password | `npx tsx scripts/encrypt-password.ts [PASSWORD]` |
### 🖥️ Server Management
| Script | Purpose | Usage |
|-----------|------|----------|
| `server.sh` | MCP Email Server management (start/stop/restart/status) | `./scripts/server.sh {start\|stop\|restart\|status\|logs\|health}` |
| `monitor-health.ts` | Comprehensive health check with authentication status diagnosis | `npm run health:check` |
| `test-search-all.sh` | Test cross-account search functionality | `./scripts/test-search-all.sh` |
## ⚙️ Installation and Setup
### 1. Installation
```bash
git clone <repository-url>
cd mcp-email-server
npm install
```
### 2. Environment Setup
```bash
# Copy sample environment file
cp .env.example .env
# Edit settings
nano .env
```
### 3. Required Environment Variables
```bash
# Mandatory - encryption key for password storage
EMAIL_ENCRYPTION_KEY=your-unique-32-character-encryption-key
# Gmail OAuth2 settings (if using Gmail)
GMAIL_CLIENT_ID=your-gmail-client-id
GMAIL_CLIENT_SECRET=your-gmail-client-secret
GMAIL_REDIRECT_URI=urn:ietf:wg:oauth:2.0:oob
# Gmail account token (obtained via OAuth script)
GMAIL_REFRESH_TOKEN_accountname=your-refresh-token
# IMAP account settings (if using IMAP)
IMAP_HOST_accountname=mail.example.com
IMAP_USER_accountname=user@example.com
IMAP_PASSWORD_accountname=encrypted-password-here
IMAP_PORT_accountname=993
IMAP_TLS_accountname=true
```
### 4. Account Setup
#### Gmail Account
```bash
# Configure Gmail OAuth2 credentials in .env file, then:
node scripts/gmail-desktop-auth.mjs ACCOUNT_NAME
# Restart server to apply settings:
./scripts/server.sh restart
```
#### IMAP Account
```bash
# Interactive IMAP setup (recommended):
node scripts/setup-xserver.mjs
# Or manually encrypt password:
npx tsx scripts/encrypt-password.ts "your-password"
```
### 5. Server Startup and Verification
```bash
# Start server (using LaunchAgent)
./scripts/server.sh start
# Check server status
./scripts/server.sh status
# Comprehensive health check (recommended)
./scripts/server.sh health
# or
npm run health:check
# Full test suite
npm test
```
## 🔧 MCP Configuration
### Cursor MCP Setup (Recommended)
Add to Cursor MCP configuration file (`~/.cursor/mcp.json`):
```json
{
"mcpServers": {
"mcp-email-server": {
"url": "http://localhost:3456/mcp",
"transport": "http"
}
}
}
```
**Caution:** Do not expose server without authentication.
## 🖥️ Server and Testing
Located in the `bin/` directory:
| Script | Purpose | Usage |
|-----------|------|----------|
| `run-streaming-email-server.ts` | Start production MCP server | `npx tsx bin/run-streaming-email-server.ts` |
※ `run-stdio-email-server.ts` is deprecated
#### MacOS Persistent Startup
As a streaming HTTP server, keep the server running at all times. On macOS, create a LaunchAgent plist file:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>localhost.mcp-email-server</string>
<key>Program</key>
<string>/PATH/TO/tsx</string>
<key>ProgramArguments</key>
<array>
<string>/PATH/TO/.nvm/versions/node/v23.7.0/bin/tsx</string>
<string>/PATH/TO/mcp-email-server/bin/run-streaming-email-server.ts</string>
</array>
<key>WorkingDirectory</key>
<string>/PATH/TO/src/git/mcp-email-server</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardOutPath</key>
<string>/PATH/TO/Library/Logs/mcp-email-server.log</string>
<key>StandardErrorPath</key>
<string>/PATH/TO/Library/Logs/mcp-email-server-error.log</string>
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/PATH/TO/NODE/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>NODE_PATH</key>
<string>/PATH/TO/NODE/lib/node_modules</string>
</dict>
</dict>
</plist>
```
- Start server with LaunchAgent
```bash
launchctl load ~/Library/LaunchAgents/localhost.mcp-email-server.plist
```
Other test scripts are located in the `scripts/` directory:
| Script | Purpose | Usage |
|-----------|------|----------|
| `quick-test.ts` | Quick connection and response test | `npx tsx scripts/quick-test.ts` |
| `monitor-health.ts` | Comprehensive health monitoring | `npx tsx scripts/monitor-health.ts` |
| `decrypt-test.ts` | Password decryption function test | `npx tsx scripts/decrypt-test.ts` |
## 💡 MCP Tool Usage Examples
### Account Management
```javascript
// List all configured accounts
mcp_mcp-email-server_list_accounts()
// Test connection to a specific account
mcp_mcp-email-server_test_connection("business_gmail")
// Retrieve comprehensive statistics for all accounts
mcp_mcp-email-server_get_account_stats()
```
### Email Operations
```javascript
// Cross-search all accounts
mcp_mcp-email-server_search_all_emails({
query: "invoice",
accounts: "ALL",
limit: 20,
sortBy: "date"
})
// Retrieve email list from a specific account
mcp_mcp-email-server_list_emails({
account_name: "business_gmail",
limit: 10,
unread_only: true
})
// Send an email (automatic account type detection)
mcp_mcp-email-server_send_email({
account_name: "business_gmail",
to: "recipient@example.com",
subject: "Meeting Schedule",
text: "Let's schedule a meeting for next week.",
cc: "manager@example.com"
})
// Archive an email
mcp_mcp-email-server_archive_email({
account_name: "business_gmail",
email_id: "email_id_here"
})
```
## 🧪 Testing
This project includes comprehensive tests designed to work with any account settings:
```bash
# Full test suite
npm test
# Specific test categories
npm run test:core # Core functionality tests
npm run test:integration # Integration tests
npm run test:imap-timeout # IMAP timeout prevention tests
# Health monitoring
npm run health:check # Comprehensive health check
npm run test:quick # Quick connection test
```
### Test Requirements
- **Minimum setup**: At least one Gmail or one IMAP account configured
- **Full coverage**: Complete testing requires both Gmail and IMAP accounts
- Tests automatically detect and adapt to account settings
## 🔐 Security Features
### Password Encryption
- All IMAP passwords are encrypted with AES-256-GCM
- Unique encryption key required for each installation
- Randomized initialization vectors for security
### OAuth2 Security
- Gmail access uses OAuth2 with refresh token rotation
- Plain text credentials are not stored
- Automatic token updates
### Best Practices
- Environment variable isolation
- Do not include credentials in version control
- Regular token rotation recommended
- Minimal permission scopes requested
## 🛠️ Architecture
### Core Components
- **MCP Protocol Handler**: JSON-RPC 2.0 compliant request processing
- **Account Manager**: Centralized account settings and discovery
- **Gmail Handler**: OAuth2-authenticated Gmail API operations
- **IMAP Handler**: Secure IMAP protocol implementation with connection pooling
- **Unified Interface**: Automatic account type detection and routing
### Error Handling
- Comprehensive error responses compliant with MCP
- Detailed user guidance for common issues
- Automatic retry mechanisms for transient failures
- Graceful degradation for partial service availability
## 📊 Current Status
### ✅ Fully Operational (100% Success Rate)
CLI and MCP environment tools tested and validated:
- **Account Management**: 100% success rate across all account types
- **Email Operations**: Complete CRUD operations supported
- **Cross-Account Search**: Integrated search across Gmail and IMAP
- **Connection Testing**: Robust connectivity validation
- **Error Handling**: Comprehensive error recovery and user guidance
### 🎯 Performance Metrics
- **Response Time**: Under 5 seconds for most operations
- **Timeout Prevention**: 100% success rate in timeout tests
- **Account Detection**: Automatic detection of 7/7 configured accounts
- **Error Recovery**: Graceful handling of network and authentication issues
## 🔧 Troubleshooting
For detailed troubleshooting, see **[doc/re-auth.md](doc/re-auth.md)**.
### Common Issues and Resolution Flows
#### 1. Authentication Error Diagnosis and Resolution
```bash
# Run health check
npm run health:check
# Address issues based on error patterns
# Pattern A: Gmail authentication error
node scripts/gmail-desktop-auth.mjs ACCOUNT_NAME
./scripts/server.sh restart
# Pattern B: Server restart required
./scripts/server.sh restart
# Pattern C: IMAP authentication error
npx tsx scripts/decrypt-test.ts
```
#### 2. Server Management
```bash
# Check server status
./scripts/server.sh status
# Restart server (required after authentication)
./scripts/server.sh restart
# View logs
./scripts/server.sh logs
./scripts/server.sh logs error
```
#### 3. Detailed Diagnostics
```bash
# Cross-account search test
./scripts/test-search-all.sh
# Individual account test
curl -X POST http://localhost:3456/mcp \
-H "Content-Type: application/json" \
-d '{"method":"tools/call","params":{"name":"test_connection","arguments":{"account_name":"ACCOUNT_NAME"}}}'
```
### Preventive Maintenance
```bash
# Regular health checks (recommended: daily)
./scripts/server.sh health
# Regular restarts (recommended: weekly)
./scripts/server.sh restart
```
### Debug Mode
```bash
# Start server with detailed logs
DEBUG=1 npx tsx bin/run-streaming-email-server.ts
# Run in development mode
NODE_ENV=development npx tsx bin/run-streaming-email-server.ts
```
## 📈 Future Enhancements
- Additional email provider support
- Advanced filtering and search options
- Email template management
- Bulk operation support
- Calendar integration for meeting emails
## 🤝 Contributing
1. Fork repository
2. Create feature branch
3. Add comprehensive tests
4. Ensure all tests pass
5. Submit pull request
## 📄 License
MIT License - see LICENSE file for details.
## 🆘 Support
For issues or questions:
1. Check **[doc/re-auth.md](doc/re-auth.md)** workflow for AI-assisted troubleshooting
2. Diagnose issues with health check: `./scripts/server.sh health`
3. Utilize server management tools: `./scripts/server.sh --help`
4. Review debug logs: `./scripts/server.sh logs`
5. Create issue with detailed error information and configuration details
### 🤖 AI-Assisted Support
This project includes AI (Claude, ChatGPT, etc.)-assisted diagnostic and resolution workflows:
- **Automated diagnosis**: Automatic issue classification with `npm run health:check`
- **Step-by-step resolution**: Pattern-based guidance
- **Preventive maintenance**: Recommended regular maintenance tasks
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
No recommendations available