Gmail MCP Server
Enables AI-powered email management through Gmail, including search, send, drafts, labels, and an intelligent agent with human approval workflow and optional customer database integration.
README
Gmail MCP Server
An intelligent Gmail automation system using Model Context Protocol (MCP) for AI-powered email management, automated responses, and customer database integration. Features include email search, draft management, label operations, and an intelligent agent that can auto-respond to emails with human approval workflow.
Features
🔧 MCP Server Tools
- Email Search - Query emails using Gmail search syntax
- Email Details - Get full email content, attachments, and metadata
- Send Emails - Send plain text or HTML emails with attachments
- Draft Management - Create, list, update, and send drafts
- Label Operations - Create, list, and manage Gmail labels
- Mark as Read/Unread - Update email read status
🤖 AI Agent Capabilities
- Automated Email Monitoring - Continuously monitors inbox for new emails
- Intelligent Response Generation - Uses Azure OpenAI to generate contextual responses
- Human-in-the-Loop Approval - All AI responses require human approval before sending
- Confidence-Based Routing - Low confidence responses automatically require approval
- Customer Database Integration - Query and update customer/order data from MySQL
- Web-Based Approval UI - Friendly interface for reviewing and approving responses
📊 Database Integration
- MySQL Customer Management - Store and retrieve customer information
- Order Tracking - Manage customer orders and history
- AI-Powered Queries - Agent can search customers, add orders, check inventory
Prerequisites
- Python 3.11 or higher
- Google Cloud Project with Gmail API enabled
- Azure OpenAI Service (for AI agent features)
- MySQL Database (optional, for customer database features)
- Node.js (optional, for MCP client testing)
Setup
1. Clone the Repository
git clone https://github.com/TechVest-Global/Gmail-MCP-server.git
cd Gmail-MCP-server
2. Set Up Python Environment
python -m venv myenv
# On Windows
myenv\Scripts\activate
# On macOS/Linux
source myenv/bin/activate
pip install -r requirements.txt
3. Configure Google Cloud & Gmail API
3.1 Create Google Cloud Project
- Go to Google Cloud Console
- Create a new project or select existing one
- Enable Gmail API:
- Go to APIs & Services → Library
- Search for "Gmail API"
- Click Enable
3.2 Create OAuth 2.0 Credentials
- Go to APIs & Services → Credentials
- Click Create Credentials → OAuth client ID
- Configure OAuth consent screen if prompted:
- User type: External (for testing)
- Add your email as test user
- Select Desktop app as application type
- Download the credentials JSON file
- Save as
credentials/credentials.json
3.3 Required Gmail API Scopes
The following scopes are configured by default:
https://www.googleapis.com/auth/gmail.readonly- Read emailshttps://www.googleapis.com/auth/gmail.send- Send emailshttps://www.googleapis.com/auth/gmail.modify- Modify emails (mark read/unread)https://www.googleapis.com/auth/gmail.labels- Manage labels
4. Configure Environment Variables (Optional)
For AI agent and database features, create a .env file:
# Azure OpenAI Configuration (for AI Agent)
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_API_KEY=your-api-key
AZURE_OPENAI_DEPLOYMENT=gpt-4o-mini
# MySQL Database Configuration (optional)
MYSQL_HOST=your-mysql-server.mysql.database.azure.com
MYSQL_USER=your-username
MYSQL_PASSWORD=your-password
MYSQL_DATABASE=your-database
MYSQL_PORT=3306
MYSQL_SSL_DISABLED=false
# Agent Configuration
MONITOR_INTERVAL=30
CONFIDENCE_THRESHOLD=0.8
AGENT_PORT=9000
# Google OAuth (alternative to file-based auth)
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
GOOGLE_REFRESH_TOKEN=your-refresh-token
5. Initial Authentication
Run the MCP server for the first time to authenticate:
python -m app.server
This will:
- Open your browser for Google OAuth
- Ask you to grant Gmail permissions
- Save credentials to
credentials/token.json - Token will auto-refresh when needed
Usage
MCP Server Mode
Start the MCP server to expose Gmail tools:
python -m app.server
The server communicates via stdio using the Model Context Protocol. Connect to it using an MCP client like Claude Desktop, Cline, or custom applications.
Example MCP Client Configuration (Claude Desktop)
Edit ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"gmail": {
"command": "python",
"args": ["-m", "app.server"],
"cwd": "C:/Projects/Gmail-MCP-server",
"env": {}
}
}
}
AI Agent Mode
Start the automated email responder with approval workflow:
python agent_server.py
Features:
- Monitors inbox every 30 seconds (configurable)
- Generates AI responses using Azure OpenAI
- Web UI at
http://localhost:9000/approvals.html - Approvals API at
http://localhost:9000/approvals
Agent Endpoints
GET /health- Health checkGET /approvals- List pending approvalsPOST /approvals/{message_id}/approve- Approve and send responsePOST /approvals/{message_id}/reject- Reject proposed response
Standalone Agent with Database
Run the agent with full customer database integration:
python agent.py
This includes:
- All email monitoring features
- Customer database tools (add, search, update customers)
- Order management (create, track orders)
- Inventory checks
Project Structure
Gmail-MCP-server/
├── app/
│ ├── server.py # Main MCP server
│ ├── gmail_auth.py # OAuth authentication handler
│ ├── gmail_client.py # Gmail API wrapper
│ ├── monitor.py # Email monitoring logic
│ └── approval_store.py # Approval workflow storage
├── agent.py # AI agent with database integration
├── agent_server.py # FastAPI server for agent
├── database.py # MySQL database integration
├── email_responder.py # Email auto-responder logic
├── credentials/
│ ├── credentials.json # Google OAuth client credentials
│ └── token.json # Auto-generated access token
├── chat-ui/ # Web UI for approvals
│ ├── index.html
│ ├── approvals.html
│ └── app.js
├── requirements.txt # Python dependencies
└── README.md # This file
Available MCP Tools
search_emails
Search for emails using Gmail query syntax.
{
"query": "from:example@gmail.com is:unread",
"max_results": 10,
"include_spam_trash": false
}
get_email_details
Get complete email details including body and attachments.
{
"message_id": "18c2f3a1b2e4d5f6"
}
send_email
Send an email (plain text or HTML).
{
"to": "recipient@example.com",
"subject": "Hello",
"body": "Email content",
"html": false,
"cc": "cc@example.com",
"bcc": "bcc@example.com"
}
create_draft
Create an email draft.
{
"to": "recipient@example.com",
"subject": "Draft Subject",
"body": "Draft content"
}
list_labels
Get all Gmail labels.
{}
mark_as_read / mark_as_unread
Update email read status.
{
"message_id": "18c2f3a1b2e4d5f6"
}
Troubleshooting
Common Issues
❌ Authentication Error
- Cause: Missing or invalid credentials
- Solution:
- Ensure
credentials/credentials.jsonexists - Delete
credentials/token.jsonand re-authenticate - Check OAuth consent screen configuration
- Ensure
❌ Gmail API Not Enabled
- Cause: Gmail API not enabled in Google Cloud
- Solution: Go to Google Cloud Console → APIs & Services → Enable Gmail API
❌ Token Refresh Failed
- Cause: Expired refresh token or revoked access
- Solution: Delete
credentials/token.jsonand re-authenticate
❌ ModuleNotFoundError
- Cause: Missing dependencies
- Solution:
pip install -r requirements.txt
❌ Database Connection Error
- Cause: MySQL credentials not configured or server unreachable
- Solution: Check
.envfile for correct MySQL credentials
❌ Azure OpenAI Error
- Cause: Invalid Azure OpenAI endpoint or API key
- Solution: Verify credentials in
.envand ensure deployment name is correct
Logging and Debugging
- MCP server logs to stderr for debugging
- Agent server logs to stdout
- Check terminal output for detailed error messages
- Use
--verboseflag for detailed logging (if implemented)
Architecture
- MCP Protocol: FastMCP framework for tool exposure
- Gmail API: Google API Python client for Gmail operations
- AI Agent: Agent Framework with Azure OpenAI integration
- Web Framework: FastAPI for REST endpoints and SSE
- Database: PyMySQL for MySQL connectivity
- Authentication: OAuth 2.0 with automatic token refresh
Security Notes
- Never commit
credentials/credentials.jsonorcredentials/token.json - Keep
.envfile secure and out of version control - Use environment variables for production deployments
- Regularly rotate API keys and credentials
- Review Gmail API scopes and use minimum required permissions
- Enable 2FA on Google account for additional security
Azure Deployment
This project includes Azure deployment configurations:
Azure Functions
# Deploy to Azure Functions
.\deploy-functions.ps1
Azure App Service
# Deploy to Azure App Service
.\deploy-appservice.ps1
Azure Container Apps
# Deploy to Container Apps
.\deploy-azure.ps1
See deployment guides:
Development
Adding New MCP Tools
Add tools in app/server.py:
@mcp.tool()
async def your_new_tool(param: str) -> str:
"""Tool description"""
# Implementation
return result
Testing
Run tests:
pytest tests/
Code Style
Follow PEP 8 guidelines:
black .
Contributing
- Fork the repository
- Create feature branch (
git checkout -b feature/your-feature) - Commit changes (
git commit -am 'Add new feature') - Push to branch (
git push origin feature/your-feature) - Create Pull Request
License
MIT License - See LICENSE file for details
推荐服务器
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 模型以安全和受控的方式获取实时的网络信息。