Gmail MCP Server
Provides tools for managing Gmail emails, including search, send, draft management, label operations, and marking read/unread.
Integrates with Google Cloud for OAuth authentication and accessing the Gmail API.
Provides database integration for storing and retrieving customer information, orders, and inventory.
Uses Azure OpenAI to generate intelligent responses for automated email replies with human approval workflow.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Gmail MCP Serverfind emails from last week about project updates"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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
Related MCP server: Gmail MCP Server
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-server2. Set Up Python Environment
python -m venv myenv
# On Windows
myenv\Scripts\activate
# On macOS/Linux
source myenv/bin/activate
pip install -r requirements.txt3. 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-token5. Initial Authentication
Run the MCP server for the first time to authenticate:
python -m app.serverThis will:
Open your browser for Google OAuth
Ask you to grant Gmail permissions
Save credentials to
credentials/token.jsonToken will auto-refresh when needed
Usage
MCP Server Mode
Start the MCP server to expose Gmail tools:
python -m app.serverThe 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.pyFeatures:
Monitors inbox every 30 seconds (configurable)
Generates AI responses using Azure OpenAI
Web UI at
http://localhost:9000/approvals.htmlApprovals 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.pyThis 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 fileAvailable 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.jsonexistsDelete
credentials/token.jsonand re-authenticateCheck OAuth consent screen configuration
❌ 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.jsonKeep
.envfile secure and out of version controlUse 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.ps1Azure App Service
# Deploy to Azure App Service
.\deploy-appservice.ps1Azure Container Apps
# Deploy to Container Apps
.\deploy-azure.ps1See 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 resultTesting
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
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/TechVest-Global/Gmail-MCP-server'
If you have feedback or need assistance with the MCP directory API, please join our Discord server