@chinchillaenterprises/mcp-gmail
v4.0.0
Published
Modular Gmail MCP server with multi-account support and standardized tool naming
Readme
MCP Gmail Server
A Model Context Protocol (MCP) server that provides read-only access to Gmail messages. This server enables searching, reading, and organizing Gmail messages with support for labels, threads, attachments, and batch operations.
Features
Mailbox Operations
- List messages with pagination and filtering
- Get full message content including headers and body
- Search messages using Gmail's powerful query syntax
- List all labels/folders in the account
Message Details
- List message attachments with metadata
- Get full email threads (conversations)
- List conversation threads with pagination
Filters & Organization
- Search by label - Filter messages by specific labels
- Search by date range - Find messages within date ranges
- Get unread counts - Statistics for unread messages
Batch Operations
- Batch get messages - Retrieve up to 100 messages in parallel for better performance
Installation
Install the server using Claude Code:
# Install with user scope for global availability
claude mcp add gmail -s user \
-e GMAIL_CLIENT_ID=your-client-id \
-e GMAIL_CLIENT_SECRET=your-client-secret \
-e GMAIL_REFRESH_TOKEN=your-refresh-token \
-- npx @chinchillaenterprises/mcp-gmail
# Or install with project scope for team sharing
claude mcp add gmail -s project \
-e GMAIL_CLIENT_ID=your-client-id \
-e GMAIL_CLIENT_SECRET=your-client-secret \
-e GMAIL_REFRESH_TOKEN=your-refresh-token \
-- npx @chinchillaenterprises/mcp-gmailAuthentication Setup
This server uses OAuth2 for authentication. You'll need three credentials:
- Client ID: Your OAuth2 client ID
- Client Secret: Your OAuth2 client secret
- Refresh Token: A long-lived token for accessing Gmail
Step-by-Step OAuth Setup
1. Create a Google Cloud Project
- Go to Google Cloud Console
- Create a new project or select an existing one
- Enable the Gmail API:
- Go to "APIs & Services" → "Library"
- Search for "Gmail API"
- Click on it and press "Enable"
2. Create OAuth2 Credentials
- Go to "APIs & Services" → "Credentials"
- Click "Create Credentials" → "OAuth client ID"
- Configure consent screen if prompted:
- Choose "External" (or "Internal" for Google Workspace)
- Fill in required fields
- Add your email to test users
- For Application type, choose "Desktop app"
- Name it (e.g., "MCP Gmail")
- Click "Create"
- Save your Client ID and Client Secret
3. Get a Refresh Token
Option A: Use the provided helper script
- Save this script as
get-gmail-token.js:
const { google } = require('googleapis');
const http = require('http');
const url = require('url');
const open = require('open');
const CLIENT_ID = 'YOUR_CLIENT_ID';
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
const REDIRECT_URI = 'http://localhost:3000/oauth2callback';
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
async function getRefreshToken() {
const oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
const authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
prompt: 'consent'
});
console.log('Opening browser for authorization...');
open(authUrl);
const server = http.createServer(async (req, res) => {
const queryObject = url.parse(req.url, true).query;
if (queryObject.code) {
const { tokens } = await oauth2Client.getToken(queryObject.code);
console.log('\nREFRESH TOKEN:', tokens.refresh_token);
res.end('Success! Check your terminal for the refresh token.');
process.exit(0);
}
});
server.listen(3000);
}
getRefreshToken();- Install dependencies and run:
npm install googleapis open
node get-gmail-token.jsOption B: Use OAuth Playground
- Go to OAuth 2.0 Playground
- Click settings (gear icon) → Use your own OAuth credentials
- Enter your Client ID and Secret
- Select "Gmail API v1" →
https://www.googleapis.com/auth/gmail.readonly - Authorize and exchange for tokens
- Copy the Refresh Token
Environment Variables
Set your credentials:
export GMAIL_CLIENT_ID="your-client-id"
export GMAIL_CLIENT_SECRET="your-client-secret"
export GMAIL_REFRESH_TOKEN="your-refresh-token"Available Tools
Mailbox Operations
gmail_list_messages
List messages with various filters and pagination.
Parameters:
maxResults(optional): Maximum messages to return (1-500, default: 100)pageToken(optional): Token for paginationlabelIds(optional): Array of label IDs to filter byq(optional): Gmail search queryincludeSpamTrash(optional): Include SPAM and TRASH messages (default: false)
Example:
{
"maxResults": 50,
"labelIds": ["INBOX"],
"q": "is:unread"
}gmail_get_message
Get complete message content including headers and body.
Parameters:
messageId(required): The message IDformat(optional): Format - "minimal", "full", "raw", "metadata" (default: "full")
Returns: Message with headers, body (text and HTML), labels, and metadata.
gmail_search_messages
Search messages using Gmail's query syntax.
Parameters:
query(required): Gmail search querymaxResults(optional): Maximum results (1-500, default: 100)pageToken(optional): Pagination tokenincludeSpamTrash(optional): Include SPAM/TRASH (default: false)
Example queries:
from:[email protected]is:unread subject:"Important"has:attachment larger:5Mafter:2024/1/1 before:2024/12/31
gmail_list_labels
List all labels/folders in the Gmail account.
No parameters required.
Returns: Array of labels with IDs, names, and types (system/user).
Message Details
gmail_get_attachments
List all attachments in a message.
Parameters:
messageId(required): The message ID
Returns: Array of attachments with filename, MIME type, size, and attachment ID.
gmail_get_thread
Get a complete email thread (conversation).
Parameters:
threadId(required): The thread IDformat(optional): Format for messages - "minimal", "full", "metadata" (default: "full")
Returns: Thread with all messages in the conversation.
gmail_list_threads
List conversation threads.
Parameters:
maxResults(optional): Maximum threads (1-500, default: 100)pageToken(optional): Pagination tokenlabelIds(optional): Filter by label IDsq(optional): Gmail search queryincludeSpamTrash(optional): Include SPAM/TRASH (default: false)
Filters & Organization
gmail_search_by_label
Get messages filtered by a specific label.
Parameters:
labelId(required): Label ID to filter bymaxResults(optional): Maximum results (1-500, default: 100)pageToken(optional): Pagination token
gmail_search_by_date
Search messages within date ranges.
Parameters:
after(required): Start date (YYYY/MM/DD)before(optional): End date (YYYY/MM/DD)maxResults(optional): Maximum results (1-500, default: 100)pageToken(optional): Pagination tokenadditionalQuery(optional): Additional search criteria
Example:
{
"after": "2024/06/01",
"before": "2024/06/30",
"additionalQuery": "from:[email protected]"
}gmail_get_unread_count
Get unread message statistics.
Parameters:
labelIds(optional): Count unread in specific labels (default: ["INBOX"])
Returns: Total unread count and breakdown by label.
Batch Operations
gmail_batch_get_messages
Retrieve multiple messages efficiently in parallel.
Parameters:
messageIds(required): Array of message IDs (max 100)format(optional): Format for all messages - "minimal", "full", "metadata" (default: "full")
Benefits:
- Much faster than individual requests
- Reduces API quota usage
- Returns all messages in one response
Usage Examples
Basic Email Search
// Search for unread emails from a specific sender
{
"tool": "gmail_search_messages",
"args": {
"query": "from:[email protected] is:unread",
"maxResults": 20
}
}
// Get the full content of a message
{
"tool": "gmail_get_message",
"args": {
"messageId": "18f5c3a2b8e9d6f1"
}
}Working with Labels
// List all labels
{
"tool": "gmail_list_labels"
}
// Get messages in a specific label
{
"tool": "gmail_search_by_label",
"args": {
"labelId": "Label_123",
"maxResults": 50
}
}Date-Based Searches
// Get emails from last week
{
"tool": "gmail_search_by_date",
"args": {
"after": "2024/06/15",
"before": "2024/06/22",
"additionalQuery": "has:attachment"
}
}Thread Management
// Get a complete conversation
{
"tool": "gmail_get_thread",
"args": {
"threadId": "18f5c3a2b8e9d6f1"
}
}Batch Operations
// Get multiple messages at once
{
"tool": "gmail_batch_get_messages",
"args": {
"messageIds": ["msg1", "msg2", "msg3", "msg4", "msg5"],
"format": "full"
}
}Gmail Query Syntax Reference
Common search operators:
from:[email protected]- From specific senderto:[email protected]- To specific recipientsubject:keyword- Subject contains keywordis:unread- Unread messagesis:important- Marked as importanthas:attachment- Has attachmentslarger:5M- Larger than 5MBsmaller:1M- Smaller than 1MBafter:2024/1/1- After datebefore:2024/12/31- Before datelabel:work- Has specific labelin:inbox- In inboxin:sent- In sent mailin:drafts- In draftsin:spam- In spamin:trash- In trash
Combine with AND/OR:
from:[email protected] AND is:unreadsubject:"Project Update" OR subject:"Status Report"has:attachment -from:[email protected](NOT from)
Error Handling
The server provides detailed error messages:
- Authentication errors: Invalid or expired tokens
- Permission errors: Missing OAuth scopes
- Not found errors: Invalid message/thread IDs
- Rate limiting: Automatic retry recommendations
- Validation errors: Invalid parameters
Rate Limiting
Gmail API quotas:
- Per-user rate limit: 250 quota units per user per second
- Daily quota: 1 billion quota units per day
The server handles rate limiting gracefully and provides clear error messages when limits are exceeded.
Testing
Local Development Testing
# 1. Install dependencies
cd mcp-gmail
npm install
# 2. Build the server
npm run build
# 3. Set your credentials
export GMAIL_CLIENT_ID="your-client-id"
export GMAIL_CLIENT_SECRET="your-client-secret"
export GMAIL_REFRESH_TOKEN="your-refresh-token"
# 4. Add server locally for testing
claude mcp add gmail-test -s user -- node $(pwd)/dist/index.js
# 5. Start Claude and test
claude
# Try: "Search my Gmail for unread messages"Limitations (v1.0.0)
This is a read-only server. The following operations are not supported:
- Sending emails
- Modifying messages (mark as read, delete, etc.)
- Creating or modifying labels
- Managing drafts
- Changing message labels
These write operations may be added in future versions.
Security Considerations
- Refresh tokens never expire unless explicitly revoked
- Store credentials securely - anyone with these tokens can read the Gmail account
- Use minimal scopes - this server only requests
gmail.readonly - Revoke access at myaccount.google.com/permissions if needed
Development
Prerequisites
- Node.js 18+
- TypeScript
- Google Cloud project with Gmail API enabled
Setup
git clone <repository>
cd mcp-gmail
npm install
npm run buildBuilding
npm run build # Build once
npm run dev # Build and watch for changesContributing
- Follow the existing code structure and patterns
- Add comprehensive error handling for new features
- Update this README with new tools and examples
- Test thoroughly with real Gmail data
- Follow the ChillMCP conventions for consistency
License
MIT License - see LICENSE file for details.
Note: This MCP server provides read-only access to Gmail. Always ensure you're using appropriate OAuth scopes and following Google's API usage policies.
