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
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.