Gmail MCP Server
Enables AI agents to interact with Gmail through a standardized MCP server interface, allowing for natural language email management and automation.
README
Gmail MCP AI Integration
An intelligent Gmail assistant powered by Azure OpenAI and the Model Context Protocol (MCP). This project enables AI agents to interact with Gmail through a standardized MCP server interface, allowing for natural language email management and automation.
Features
-
MCP Server for Gmail
- Search emails with natural language queries
- Read email content with full metadata
- Send emails with attachments
- Mark emails as read/unread
- Delete and trash management
- Label operations
- Draft management
-
AI Agent Integration
- Azure OpenAI-powered assistant using Agent Framework
- Natural language email understanding
- Context-aware responses
- Efficient inbox management
-
Authentication
- OAuth 2.0 Gmail authentication
- Environment variable support for Azure deployments
- Secure credential management
- Refresh token handling
Prerequisites
- Python 3.11 or higher
- Google Cloud account with Gmail API enabled
- Azure OpenAI Service (for agent functionality)
- Required OAuth 2.0 credentials from Google Cloud Console
Setup
1. Clone the repository
git clone <repository-url>
cd Gmail-MCP-AI-Integration
2. Set up Python environment
python -m venv venv
venv\Scripts\activate # On Windows
# source venv/bin/activate # On macOS/Linux
pip install -r requirements.txt
3. Configure Gmail API
Step-by-step guide to get Gmail API credentials:
-
Go to Google Cloud Console
-
Create or Select a Project
- Click the project dropdown at the top
- Click "New Project" or select existing project
- Enter a project name (e.g., "Gmail MCP Server")
- Click "Create"
-
Enable the Gmail API
- In the left sidebar, go to APIs & Services → Library
- Search for "Gmail API"
- Click on "Gmail API" in the results
- Click the Enable button
-
Configure OAuth Consent Screen (First-time setup)
- Go to APIs & Services → OAuth consent screen
- Select External user type
- Click Create
- Fill in required fields:
- App name: "Gmail MCP Server"
- User support email: Your email
- Developer contact: Your email
- Click Save and Continue
- On Scopes page, click Save and Continue
- On Test users page, add your Gmail address, click Save and Continue
-
Create OAuth 2.0 Credentials
- Go to APIs & Services → Credentials
- Click + Create Credentials → OAuth client ID
- Choose Application type: Desktop app
- Name it: "Gmail MCP Desktop Client"
- Click Create
- Click Download JSON (or click the download icon for your credential)
- Save the file as
credentials.json
-
Place credentials.json in your project
# Create credentials folder if it doesn't exist mkdir credentials # Move downloaded file to credentials/credentials.json # Windows: copy Downloads\credentials.json credentials\credentials.json # Linux/Mac: mv ~/Downloads/credentials.json credentials/credentials.json
Note: On first run, a browser window will open asking you to authorize the application. After authorization, a
token.jsonfile will be created automatically.
4. Configure Azure OpenAI (Optional, for AI Agent)
If you want to use the AI agent functionality, follow these steps to get Azure OpenAI credentials:
Step-by-step guide to get Azure OpenAI credentials:
-
Go to Azure Portal
- Sign in with your Microsoft account
- If you don't have an account, click "Create one" (Free account available)
-
Create Azure OpenAI Resource
- Click Create a resource (+ icon in top left)
- Search for "Azure OpenAI"
- Click Create → Azure OpenAI
- Fill in the required fields:
- Subscription: Select your Azure subscription
- Resource group: Create new or select existing (e.g., "gmail-mcp-rg")
- Region: Choose a region (e.g., "East US", "West Europe")
- Name: Enter a unique name (e.g., "gmail-mcp-openai")
- Pricing tier: Select Standard S0
- Click Review + Create → Create
- Wait for deployment (usually 1-2 minutes)
-
Get Endpoint and API Key
- After deployment, click Go to resource
- In the left menu, click Keys and Endpoint
- Copy these values:
- Endpoint: Should look like
https://your-resource.openai.azure.com/ - Key 1: Your API key (long string of characters)
- Endpoint: Should look like
-
Deploy a Model
- In the left menu, click Model deployments or go to Azure OpenAI Studio
- Click Create new deployment or Deploy model
- Select a model:
- gpt-4: Most capable, higher cost
- gpt-4-turbo: Fast and capable
- gpt-4.1-mini: Fast, cost-effective (recommended for testing)
- gpt-35-turbo: Fastest, lowest cost
- Give it a deployment name (e.g., "gpt-4-mini")
- Click Create
-
Create and configure .env file
# Copy the example file copy .env.example .envEdit
.envand add your Azure OpenAI credentials:AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/ AZURE_OPENAI_API_KEY=your_actual_api_key_here AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4-mini
Cost Note: Azure OpenAI is a paid service. Check Azure OpenAI Pricing for rates. New accounts get $200 free credit for 30 days.
5. Run the MCP Server
Start the Gmail MCP server:
python app/server.py
The server will:
- Authenticate with Gmail (browser window will open on first run)
- Start listening for MCP protocol messages via STDIO
- Log status messages to stderr
6. Test the Server
Use the provided test client:
python mcp_client.py
This will:
- Connect to the MCP server
- Test basic operations (search, read emails)
- Display results
Usage
Using the MCP Server
The server exposes the following MCP tools:
search_emails
Search for emails using Gmail query syntax.
{
"query": "from:someone@example.com",
"max_results": 10,
"include_spam_trash": false
}
get_email
Get detailed information about a specific email.
{
"message_id": "abc123..."
}
send_email
Send a new email with optional attachments.
{
"to": "recipient@example.com",
"subject": "Hello",
"body": "Message content",
"cc": "cc@example.com",
"bcc": "bcc@example.com",
"attachments": [{"filename": "doc.pdf", "content": "base64..."}]
}
mark_as_read / mark_as_unread
Change read status of emails.
{
"message_ids": ["id1", "id2"]
}
delete_email / trash_email / untrash_email
Manage email deletion and trash.
{
"message_id": "abc123..."
}
list_labels
Get all Gmail labels.
{}
add_label / remove_label
Manage email labels.
{
"message_ids": ["id1", "id2"],
"label_ids": ["Label_1"]
}
create_draft / list_drafts / send_draft / delete_draft
Manage email drafts.
Using with Claude Desktop
Add to your Claude Desktop config (claude_desktop_config.json):
{
"mcpServers": {
"gmail": {
"command": "python",
"args": ["C:/Projects/Gmail-MCP-AI-Integration/app/server.py"]
}
}
}
Then restart Claude Desktop. The Gmail tools will be available in conversations.
Using the AI Agent
Run the agent directly:
python app/agent.py
The agent uses Azure OpenAI and can interact with Gmail through the MCP protocol.
Project Structure
Gmail-MCP-AI-Integration/
├── app/
│ ├── __init__.py
│ ├── agent.py # AI agent using Agent Framework
│ ├── gmail_auth.py # OAuth 2.0 authentication
│ ├── gmail_client.py # Gmail API wrapper
│ └── server.py # MCP server implementation
├── credentials/
│ ├── credentials.json # OAuth credentials (not in repo)
│ └── token.json # Access token (auto-generated)
├── mcp_client.py # Test client for MCP protocol
├── test_*.py # Various test scripts
├── requirements.txt # Python dependencies
└── README.md # This file
Troubleshooting
Common Issues
❌ Authentication Failed
- Cause: Missing or invalid credentials.json
- Solution:
- Ensure credentials.json is in the credentials/ folder
- Verify it's for a Desktop application type
- Re-download from Google Cloud Console if needed
❌ "Access blocked: This app's request is invalid"
- Cause: Incorrect OAuth 2.0 setup
- Solution:
- Make sure you created a "Desktop application" credential type
- Check that Gmail API is enabled in your project
❌ Server Not Responding
- Cause: Server initialization failed
- Solution:
- Check stderr output for error messages
- Verify all dependencies are installed
- Ensure credentials are properly configured
❌ Token Expired
- Cause: Refresh token is invalid or expired
- Solution:
- Delete
credentials/token.json - Re-run the server to re-authenticate
- Delete
❌ ModuleNotFoundError
- Cause: Missing dependencies
- Solution:
pip install -r requirements.txt
Environment Variables for Azure Deployment
For production deployments (e.g., Azure), you can use environment variables:
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_REFRESH_TOKEN=your_refresh_token
The server will automatically detect and use these instead of file-based authentication.
Architecture
- MCP Protocol: Standardized interface for AI tools
- FastMCP: Framework for building MCP servers
- Gmail API: Official Google API for email operations
- Agent Framework: Azure's framework for building AI agents
- Azure OpenAI: LLM for natural language understanding
Security Notes
- Never commit
credentials.jsonortoken.jsonto version control - Use environment variables for production deployments
- Limit OAuth scopes to only what's needed
- Regularly review and rotate credentials
- Use Azure Key Vault for production secrets
Testing
Run the test suite:
# Test MCP protocol
python test_mcp_protocol.py
# Test server functionality
python test_server.py
# Test individual features
python test_functionality.py
Contributing
- Fork the repository
- Create feature branch (
git checkout -b feature/name) - Commit your changes (
git commit -am 'Add feature') - Push to the branch (
git push origin feature/name) - Create Pull Request
License
This project is provided as-is for educational and development purposes.
Acknowledgments
- Built with FastMCP framework
- Uses Agent Framework for Azure AI integration
- Powered by Gmail API
- Model Context Protocol by Anthropic
Resources
Support
For issues and questions:
- Check the Troubleshooting section
- Review test results in TEST_RESULTS.md
- Open an issue on GitHub
- Commit changes (
git commit -am 'Add feature') - Push branch (
git push origin feature/name) - Create Pull Request
License
[Your License Type] - 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 模型以安全和受控的方式获取实时的网络信息。