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
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.