Gmail MCP Server
Provides comprehensive Gmail functionality, allowing users to list, search, read, and delete emails, send messages with or without attachments, manage labels, handle conversation threads, and access account statistics.
Click on "Deploy 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 Server search for emails from john@example.com about the project"
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
A Model Context Protocol (MCP) server that provides comprehensive Gmail functionality through FastMCP. This server enables AI assistants like Claude to interact with Gmail accounts, manage emails, send messages, and perform various Gmail operations using OAuth2 authentication via Nango.
Features
Core Gmail Operations
Message Management: List, search, read, and delete emails
Send Emails: Send messages with or without attachments
Message Actions: Mark messages as read, manage labels
Advanced Search: Filter by sender, subject, date, attachments, read status
Account Statistics: Get Gmail account overview and metrics
Thread Support: Handle Gmail conversation threads
Attachment Support: Send emails with file attachments
Authentication & Security
OAuth2 Integration: Secure authentication via Nango
Token Management: Automatic token refresh and validation
Multi-account Support: Handle multiple Gmail accounts
Secure Credential Storage: Environment-based configuration
Related MCP server: Gmail MCP Server
Prerequisites
Python 3.13+
Gmail account with API access enabled
Google Cloud Project with Gmail API enabled
Nango account for OAuth2 management (optional but recommended)
Installation
Clone or create the project structure:
mkdir gmail-mcp-server
cd gmail-mcp-serverCreate a virtual environment:
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activateInstall dependencies:
pip install -e .Configuration
Environment Variables
Create a .env file in the project root:
# Nango Configuration (Recommended)
NANGO_BASE_URL=https://api.nango.dev
NANGO_SECRET_KEY=your_nango_secret_key
NANGO_CONNECTION_ID=your_NANGO_CONNECTION_ID
NANGO_INTEGRATION_ID=google
# Alternative: Direct Google OAuth (if not using Nango)
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GOOGLE_REFRESH_TOKEN=your_refresh_tokenGoogle Cloud Setup
Create a Google Cloud Project:
Go to Google Cloud Console
Create a new project or select existing one
Enable Gmail API:
Navigate to "APIs & Services" > "Library"
Search for "Gmail API" and enable it
Create OAuth2 Credentials:
Go to "APIs & Services" > "Credentials"
Click "Create Credentials" > "OAuth 2.0 Client IDs"
Choose "Desktop application" or "Web application"
Note the Client ID and Client Secret
Configure OAuth Scopes:
Add the following scopes:
https://www.googleapis.com/auth/gmail.readonlyhttps://www.googleapis.com/auth/gmail.sendhttps://www.googleapis.com/auth/gmail.modify
Nango Setup (Recommended)
Create Nango Account: Sign up at nango.dev
Create Google Integration: Set up Google OAuth2 integration
Configure Connection: Create a connection for your Gmail account
Get Credentials: Note your connection ID and provider config key
Claude Desktop Configuration
Add this configuration to your Claude Desktop config file:
Location:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
With Nango
{
"mcpServers": {
"gmail": {
"command": "uvx",
"args": ["git+https://github.com/ampcome-mcps/gmail-mcp.git"],
"env": {
"NANGO_BASE_URL": "https://api.nango.dev",
"NANGO_SECRET_KEY": "your_nango_secret_key",
"NANGO_CONNECTION_ID": "your_nango_connection_id",
"NANGO_INTEGRATION_ID": "google-mail"
}
}
}
}Notes:
On Windows, use backslashes in paths:
C:\\path\\to\\your\\gmail-mcp-server\\main.pyFor virtual environment on Windows:
.venv\\Scripts\\python.exeReplace placeholder values with your actual credentials
Available Tools
The MCP server provides the following tools for Claude:
Message Operations
gmail_list_messages- List Gmail messages with optional search querygmail_get_message- Get details of a specific messagegmail_search_messages- Advanced search with multiple criteriagmail_send_message- Send a new email messagegmail_send_message_with_attachment- Send email with file attachment
Message Management
gmail_mark_as_read- Mark messages as readgmail_delete_messages- Delete messages permanently
Account Information
gmail_get_stats- Get Gmail account statistics and overview
Usage Examples
Once configured with Claude, you can use natural language commands like:
Basic Operations
"Show me my latest 10 emails"
"Search for emails from john@example.com sent this week"
"Get the full content of message ID xyz123"
"Send an email to sarah@example.com with subject 'Meeting Tomorrow'"
Advanced Operations
"Find all unread emails with attachments from the last 7 days"
"Mark all emails from newsletter@company.com as read"
"Delete the email with ID abc456"
"Send a report to my manager with the quarterly-report.pdf attachment"
"Show me my Gmail account statistics"
Search Capabilities
"Find emails about 'project alpha' from last month"
"Show unread emails from important@client.com"
"List emails with attachments sent after 2024/01/01"
Project Structure
gmail-mcp-server/
├── main.py # FastMCP server implementation
├── gmail_auth.py # Gmail OAuth2 authentication
├── gmail_operations.py # Gmail client operations
├── pyproject.toml # Project configuration
├── .env # Environment variables (create from template)
├── .env.example # Environment template
├── README.md # This file
├── uv.lock # Dependency lock file
└── .gitignore # Git ignore rulesRunning the Server
With Claude Desktop
The server automatically starts when Claude Desktop loads the configuration.
Standalone Testing
For development and testing:
python main.pyTool Specifications
gmail_list_messages
# Parameters:
- query: str = "" # Gmail search query
- max_results: int = 10 # Max messages (1-100)
# Returns:
{
"success": bool,
"count": int,
"messages": [
{
"id": "message_id",
"from": "sender@example.com",
"subject": "Email subject",
"date": "2024-01-01",
"snippet": "Preview text...",
"is_unread": bool
}
]
}gmail_search_messages
# Parameters:
- sender: str = None # Filter by sender
- subject: str = None # Filter by subject
- after_date: str = None # After date (YYYY/MM/DD)
- before_date: str = None # Before date (YYYY/MM/DD)
- has_attachment: bool = False # Filter with attachments
- is_unread: bool = False # Filter unread only
- max_results: int = 20 # Max results (1-100)gmail_send_message
# Parameters:
- to: str # Recipient email (required)
- subject: str # Email subject (required)
- body: str # Email content (required)
- cc: str = "" # CC recipients
- bcc: str = "" # BCC recipients
# Returns:
{
"success": bool,
"message_id": "sent_message_id",
"to": "recipient@example.com",
"subject": "Email subject"
}Development
Key Components
main.py: FastMCP server with tool definitions
gmail_auth.py: OAuth2 authentication handling
gmail_operations.py: Gmail API client wrapper
Nango Integration: Secure credential management
Adding New Features
Add Gmail Operation: Extend
GmailClientclass ingmail_operations.pyDefine MCP Tool: Add
@mcp.tool()decorator inmain.pyAdd Validation: Include parameter validation and error handling
Update Documentation: Add usage examples and tool specifications
Dependencies
google-api-python-client- Official Google API clientgoogle-auth- Google authentication librarymcp[cli]- Model Context Protocol frameworkpython-dotenv- Environment variable managementpydantic- Data validationrequests- HTTP client for Nango integration
Troubleshooting
Common Issues
Authentication Errors:
Verify Nango credentials are correct
Check Gmail API is enabled in Google Cloud
Ensure OAuth scopes are properly configured
Permission Errors:
Verify OAuth2 scopes include required permissions
Check if Gmail account has necessary access
Message Not Found:
Ensure message IDs are valid Gmail message IDs
Check if messages haven't been deleted
Rate Limiting:
Gmail API has quotas and rate limits
Implement retry logic for production use
Debug Mode
Enable debug logging by setting environment variable:
export GMAIL_MCP_DEBUG=trueTesting Nango Connection
# Test script to verify Nango setup
from gmail_auth import get_connection_credentials
try:
result = get_connection_credentials("your_connection_id", "google")
print("Nango connection successful:", result.keys())
except Exception as e:
print("Nango connection failed:", e)Security Considerations
Environment Variables: Never commit
.envfiles with credentialsToken Storage: Tokens are handled securely by Nango
API Quotas: Monitor Gmail API usage to avoid quota exhaustion
Scope Limitations: Use minimal required OAuth scopes
Access Control: Limit MCP server access to authorized clients
Performance Optimization
Batch Operations: Use batch requests when possible
Caching: Implement message caching for frequently accessed data
Pagination: Handle large result sets with proper pagination
Connection Pooling: Reuse HTTP connections for API calls
Error Handling
The server implements comprehensive error handling:
Validation Errors: Parameter validation with descriptive messages
API Errors: Gmail API error handling and retry logic
Authentication Errors: Token refresh and re-authentication
Network Errors: Connection timeout and retry mechanisms
Contributing
Fork the repository
Create a feature branch (
git checkout -b feature/amazing-feature)Make your changes and add tests
Commit your changes (
git commit -m 'Add amazing feature')Push to the branch (
git push origin feature/amazing-feature)Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For support and questions:
Check the troubleshooting section
Review Gmail API documentation: Gmail API Guide
Open an issue in the project repository
Check Nango documentation: Nango Docs
Acknowledgments
FastMCP: Simplified MCP server implementation
Google API Python Client: Official Gmail API integration
Nango: OAuth2 authentication management
Model Context Protocol: Standard for AI tool integration
Available Tools
8 toolsgmail_delete_messagesC
Delete Gmail messages.
Args: message_ids: List of message IDs to delete
Returns: Dictionary with operation result
Inputs: message_ids (required).
gmail_get_messageC
Get details of a specific Gmail message.
Args: message_id: Gmail message ID
Returns: Dictionary with message details or error
Inputs: message_id (required).
gmail_get_statsC
Get Gmail account statistics.
Args: include_unread: Include unread message count
Returns: Dictionary with account statistics
Inputs: include_unread.
gmail_list_messagesB
List Gmail messages with optional search query.
Args: query: Gmail search query (e.g., 'from:sender@example.com', 'is:unread') max_results: Maximum number of messages to return (1-100)
Returns: Dictionary with success status and message data
Inputs: query, max_results.
gmail_mark_as_readB
Mark Gmail messages as read.
Args: message_ids: List of message IDs to mark as read
Returns: Dictionary with operation result
Inputs: message_ids (required).
gmail_search_messagesB
Search Gmail messages with specific criteria.
Args: sender: Filter by sender email subject: Filter by subject keywords after_date: Filter messages after date (YYYY/MM/DD format) before_date: Filter messages before date (YYYY/MM/DD format) has_attachment: Filter messages with attachments is_unread: Filter unread messages max_results: Maximum number of messages to return (1-100)
Returns: Dictionary with search results
Inputs: sender, subject, is_unread, after_date, +3 more.
gmail_send_messageB
Send a Gmail message.
Args: to: Recipient email address subject: Email subject body: Email body content cc: CC recipients (comma-separated) bcc: BCC recipients (comma-separated)
Returns: Dictionary with send result
Inputs: to (required), body (required), subject (required), cc, +1 more.
gmail_send_message_with_attachmentB
Send Gmail message with attachment.
Args: to: Recipient email address subject: Email subject body: Email body content file_path: Path to file to attach cc: CC recipients (comma-separated)
Returns: Dictionary with send result
Inputs: to (required), body (required), subject (required), file_path (required), +1 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
There is overlap between gmail_list_messages and gmail_search_messages, as both retrieve messages with filtering, though search offers more specific criteria. Similarly, gmail_send_message and gmail_send_message_with_attachment are nearly identical except for the attachment parameter. This could cause agent confusion.
All tool names follow a consistent 'gmail_verb_noun' pattern in snake_case. Every name clearly indicates the action and resource, e.g., gmail_list_messages, gmail_get_message, gmail_send_message.
With 8 tools, the server covers essential Gmail operations without being overwhelming. The count is well-scoped for a focused MCP server, providing a balanced set of capabilities.
The tool set covers core email operations: send, receive, list, search, mark read, delete, and stats. Missing features like label management and draft handling are minor gaps, but the current surface supports primary workflows effectively.
Maintenance
Related MCP Connectors
Email infrastructure for AI agents — send, receive, search, and reply to email over MCP.
Manage Gmail end-to-end: search, read, send, draft, label, and organize threads. Automate workflow…
Your agent needs a mailbox of its own — to receive, thread, draft and send, with attachments, without borrowing your personal inbox or your company's SMTP. **What you can ask for** • "Create an inbox for this agent and tell me its address." • "Read the new messages in this thread and draft a reply." • "Send this message with the attachment and wait for the response." • "Search this inbox for everything from that domain." • "Show delivery metrics and the events on this inbox." **How to use it** Point any MCP client at https://mcp.aisa.one/mail/mcp and sign in with OAuth — there is no key to create or paste. 49 tools: create and delete inboxes, list and read messages, raw message bodies, attachments, threads, drafts and draft attachments, send and reply, message search, inbox events, metrics, and list entries — reads and writes. **Why this rather than the source** A real inbox an agent owns, rather than an SMTP credential it borrows from a human. **It is also a door to the rest** The same login reaches 26 sources and 580+ operations. Find the contact elsewhere in the catalogue, then write to them from here — without adding a second server. **What it costs** Finding and inspecting an operation is free. Running one is billed per call at API prices, with no seat and no monthly minimum, and every call takes max_price_usd so an agent cannot overspend by accident. **Where else it reaches** https://mcp.aisa.one/sales/mcp finds the person to write to.
Email for AI agents: read, search and send from your Gmail, Outlook, Yahoo, iCloud or IMAP inbox.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to read, search, organize, and draft emails in Gmail inboxes with support for multiple accounts, OAuth authentication, and 26 comprehensive tools for email management.283 npm3MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to manage Gmail accounts through natural language for tasks like sending, reading, searching, and organizing emails. It supports advanced features including draft management, label operations, and batch actions via secure OAuth 2.0 authentication.MIT
- AlicenseAqualityDmaintenanceEnables AI agents to search, read, send, and organize Gmail emails via MCP protocol.22132 npm2MIT
- FlicenseNot gradedqualityDmaintenanceFull Gmail control for any MCP-compatible AI agent. Exposes ~40 tools for reading, composing, labeling, filtering, threading, and account management.-