Provides comprehensive email management capabilities including intelligent categorization, advanced search and filtering, archiving and export (MBOX, JSON, CSV), automated cleanup policies, and detailed analytics for Gmail accounts through the Gmail API.
Integrates with Google Cloud Platform for OAuth2 authentication and Gmail API access, enabling secure email operations through Google Cloud credentials.
Gmail MCP Server
A comprehensive Model Context Protocol (MCP) server that integrates with Gmail API to provide intelligent email management capabilities. Features advanced email categorization, search, archiving, deletion, and automated cleanup with 25+ MCP tools for complete email lifecycle management.
๐ Key Features
๐ง Intelligent Email Management
AI-Powered Categorization: Automatically categorize emails by importance (high/medium/low) using advanced analysis
Smart Search & Filtering: Advanced search with multiple criteria, saved searches, and filter combinations
Real-time Processing: Background job processing for long-running operations with progress tracking
๐๏ธ Archive & Export System
Smart Archiving: Archive emails based on rules with multiple export formats (MBOX, JSON, CSV)
Automated Rules Engine: Create and manage automatic archiving rules with scheduling
Restore Capability: Restore previously archived emails with full metadata
๐งน Advanced Cleanup Automation
Policy-Based Cleanup: 13+ cleanup tools with configurable policies for automated email management
Access Pattern Tracking: Track email access patterns for intelligent cleanup decisions
Safety-First Design: Dry-run options, confirmation steps, and rollback capabilities
๐ Analytics & Monitoring
Comprehensive Statistics: Detailed email usage analytics by category, year, size, and more
System Health Monitoring: Real-time metrics, performance tracking, and system health reports
Cleanup Recommendations: AI-driven recommendations for optimal email management
๐ Security & Safety
OAuth2 Authentication: Secure Gmail API integration with encrypted token storage
Multi-layered Safety: Confirmation prompts, dry-run modes, and maximum deletion limits
Audit Logging: Complete operation logging and error tracking
๐ Table of Contents
๐ Quick Start
Prerequisites
Node.js 18+ and npm
Google Cloud Platform account with Gmail API enabled
OAuth2 credentials (Client ID and Client Secret)
Automated Setup
First Run
๐ฆ Installation
Method 1: Quick Setup (Recommended)
The setup script will guide you through:
๐ Setting up Google Cloud credentials
๐ Creating necessary directories
โ๏ธ Configuring environment variables
๐ง Initial configuration
Method 2: Manual Setup
Set up Google Cloud credentials:
Go to Google Cloud Console
Create project or select existing
Enable Gmail API
Create OAuth2 credentials (Desktop application)
Download
credentials.jsonto project root
Configure environment:
cp .env.example .env # Edit .env with your settingsCreate directories:
mkdir -p data logs archivesInstall and build:
npm install npm run build
๐ง Configuration
MCP Client Setup
For Claude Desktop:
For other MCP clients:
Environment Configuration
Key environment variables in .env:
๐ ๏ธ MCP Tools Reference
The Gmail MCP Server provides 25+ specialized tools organized into logical categories for comprehensive email management. Each tool includes safety features, parameter validation, and detailed error handling.
๐ Authentication Tools
authenticate
Initiates OAuth2 authentication flow with Gmail API.
Parameters:
scopes(array, optional): Additional OAuth scopes beyond Gmail read/write
Returns: Authentication status and user email
๐ง Email Management Tools
list_emails
List emails with comprehensive filtering and pagination.
Parameters:
category(string): Filter by importance level (high|medium|low)year(number): Filter by specific yearsize_min(number): Minimum size in bytessize_max(number): Maximum size in bytesarchived(boolean): Include archived emailshas_attachments(boolean): Filter by attachment presencelabels(array): Filter by Gmail labelsquery(string): Custom Gmail query stringlimit(number, default: 50): Maximum resultsoffset(number, default: 0): Skip first N results
get_email_details
Retrieve complete email content and metadata.
Parameters:
id(string, required): Gmail message ID
Returns: Full email object with headers, body, attachments
categorize_emails
Analyze and categorize emails by importance using AI algorithms.
Parameters:
year(number, required): Year to categorizeforce_refresh(boolean): Re-analyze already categorized emails
Returns: Categorization job status and statistics
๐ Search & Filter Tools
search_emails
Advanced multi-criteria email search with intelligent filtering.
Parameters:
query(string): Text search querycategory(string): Importance filter (high|medium|low)year_range(object): Date range withstartand/orendyearsize_range(object): Size range withminand/ormaxbytessender(string): Filter by sender email addresshas_attachments(boolean): Attachment presence filterarchived(boolean): Include archived emailslimit(number, default: 50): Maximum results
save_search
Save search criteria for quick reuse.
Parameters:
name(string, required): Name for saved searchcriteria(object, required): Search criteria to save
list_saved_searches
Retrieve all saved search queries.
Parameters: None
Returns: Array of saved searches with usage statistics
๐ Archive & Export Tools
archive_emails
Archive emails using multiple methods and formats.
Parameters:
search_criteria(object): Email selection criteriacategory(string): Archive by importance levelyear(number): Archive emails from specific yearolder_than_days(number): Archive emails older than N daysmethod(string, required): Archive method (gmail|export)export_format(string): Format when exporting (mbox|json)export_path(string): Custom export destinationdry_run(boolean, default: false): Preview mode
restore_emails
Restore emails from previous archives.
Parameters:
archive_id(string): Specific archive to restore fromemail_ids(array): Individual email IDs to restorerestore_labels(array): Labels to apply to restored emails
create_archive_rule
Create automated archiving rules with scheduling.
Parameters:
name(string, required): Descriptive rule namecriteria(object, required): Archiving conditionsaction(object, required): Archive method and formatschedule(string): Execution frequency (daily|weekly|monthly)
list_archive_rules
View all configured archive rules and their status.
Parameters:
active_only(boolean, default: false): Show only enabled rules
export_emails
Export emails to external formats with cloud upload support.
Parameters:
search_criteria(object): Email selection filtersformat(string, required): Export format (mbox|json|csv)include_attachments(boolean, default: false): Include attachmentsoutput_path(string): Local output pathcloud_upload(object): Cloud storage configuration
๐๏ธ Delete & Cleanup Tools
delete_emails
Safely delete emails with comprehensive safety checks.
โ ๏ธ Safety Note: Always use dry_run: true first to preview deletions
Parameters:
search_criteria(object): Email selection filterscategory(string): Delete by importance levelyear(number): Delete from specific yearsize_threshold(number): Delete emails larger than N bytesskip_archived(boolean, default: true): Skip archived emailsdry_run(boolean, default: false): Preview modemax_count(number, default: 10): Safety limit
empty_trash
Permanently delete all emails in Gmail trash folder.
โ ๏ธ Destructive Operation: This permanently deletes emails
Parameters:
dry_run(boolean, default: false): Preview modemax_count(number, default: 10): Safety limit
trigger_cleanup
Execute manual cleanup using specific policies.
Parameters:
policy_id(string, required): Cleanup policy to executedry_run(boolean, default: false): Preview modemax_emails(number): Processing limitforce(boolean, default: false): Execute even if policy disabled
get_cleanup_status
Monitor cleanup automation system status.
Parameters: None
Returns: System status, active jobs, and health metrics
get_system_health
Get comprehensive system health and performance metrics.
Parameters: None
Returns: Performance metrics, storage usage, and system status
create_cleanup_policy
Create advanced cleanup policies with detailed criteria.
Parameters:
name(string, required): Policy nameenabled(boolean, default: true): Policy statuspriority(number, default: 50): Execution priority (0-100)criteria(object, required): Cleanup conditionsaction(object, required): Action to takesafety(object, required): Safety configurationschedule(object): Optional scheduling
update_cleanup_policy
Modify existing cleanup policy configuration.
Parameters:
policy_id(string, required): Policy to updateupdates(object, required): Changes to apply
list_cleanup_policies
View all cleanup policies and their configurations.
Parameters:
active_only(boolean, default: false): Show only enabled policies
delete_cleanup_policy
Remove a cleanup policy permanently.
Parameters:
policy_id(string, required): Policy to delete
create_cleanup_schedule
Schedule automatic cleanup policy execution.
Parameters:
name(string, required): Schedule nametype(string, required): Schedule type (daily|weekly|monthly|interval|cron)expression(string, required): Schedule expressionpolicy_id(string, required): Policy to scheduleenabled(boolean, default: true): Schedule status
update_cleanup_automation_config
Update global cleanup automation settings.
Parameters:
config(object, required): Configuration updates
get_cleanup_metrics
Retrieve cleanup system analytics and performance data.
Parameters:
hours(number, default: 24): History window in hours
get_cleanup_recommendations
Get AI-powered cleanup policy recommendations.
Parameters: None
Returns: Recommended policies based on email analysis
๐ Statistics & Analytics Tools
get_email_stats
Comprehensive email usage statistics and analytics.
Parameters:
group_by(string): Grouping method (year|category|label|all)year(number): Filter by specific year
Returns: Detailed statistics by categories, years, sizes, and storage
โ๏ธ Job Management Tools
list_jobs
View all background jobs with filtering options.
Parameters:
limit(number, default: 50): Maximum resultsoffset(number, default: 0): Skip first N jobsstatus(string): Filter by status (pending|running|completed|failed)job_type(string): Filter by job type
get_job_status
Get detailed status of a specific background job.
Parameters:
id(string, required): Job ID to query
Returns: Job details, progress, and results
cancel_job
Cancel a running background job.
Parameters:
id(string, required): Job ID to cancel
Example Workflows
Initial Setup
Clean Up Old Emails
Automated Cleanup Setup
Development
Project Structure
Running in Development
Testing with MCP Inspector
Testing
The project includes comprehensive test suites to ensure reliability and correctness of all features.
Running Tests
Integration Tests
Delete Email Tests
The delete functionality has extensive integration tests covering all scenarios:
For detailed information about delete email testing, see Delete Email Testing Documentation.
Test Structure
Writing Tests
Follow the existing test patterns
Use descriptive test names
Mock external dependencies
Test both success and error cases
Maintain test coverage above 80%
Security
OAuth2 tokens are encrypted at rest
All bulk operations require confirmation
Audit logging for all operations
Rate limiting implemented for Gmail API
Access pattern tracking for security monitoring
Troubleshooting
Authentication Issues
Ensure credentials.json is in the correct location
Check that Gmail API is enabled in GCP
Verify redirect URI matches your configuration
Performance
First categorization may take time for large mailboxes
Use pagination for large result sets
Enable caching in production
License
MIT
Contributing
Contributions are welcome! Please read our contributing guidelines before submitting PRs.
๐๏ธ Architecture Overview
The Gmail MCP Server follows a modular, layered architecture designed for scalability, maintainability, and extensibility.
Core Architecture
Project Structure
Key Design Patterns
๐ง Modular Architecture: Each component has a single responsibility
๐ญ Factory Pattern: Tool creation and configuration management
๐ฆ Repository Pattern: Data access abstraction
๐ Observer Pattern: Event-driven cleanup automation
๐ก๏ธ Strategy Pattern: Multiple categorization algorithms
โก Caching Strategy: Multi-level caching for performance
Data Flow
Authentication: OAuth2 flow with secure token storage
Email Fetching: Batch processing with Gmail API rate limiting
Categorization: Multi-analyzer pipeline with ML-like scoring
Search: Indexed search with complex filter combinations
Operations: Safe execution with dry-run and confirmation steps
๐ง Development & Contributing
Development Setup
Development Workflow
๐ Feature Development
# Create feature branch git checkout -b feature/new-tool-name # Make changes # Add tests # Update documentation # Test thoroughly npm test npm run build๐งช Testing Strategy
Unit Tests: Individual component testing
Integration Tests: End-to-end workflow testing
Performance Tests: Load and stress testing
Manual Testing: MCP Inspector validation
๐ Documentation
Update README.md for new tools
Add JSDoc comments for public APIs
Include usage examples
Update architecture diagrams
Adding New MCP Tools
Create Tool Definition
// src/tools/definitions/my-category.tools.ts export const myToolConfigs: ToolConfig[] = [ { name: 'my_new_tool', description: 'Description of what the tool does', category: 'my_category', parameters: { required_param: ParameterTypes.string('Required parameter'), optional_param: ParameterTypes.boolean('Optional parameter', false) }, required: ['required_param'] } ];Implement Tool Handler
// src/tools/handlers/my-tool.handler.ts export async function handleMyNewTool(args: MyToolArgs): Promise<MyToolResult> { // Implementation }Register Tool
// src/tools/definitions/index.ts import { myToolConfigs } from './my-category.tools.js'; export function registerAllTools() { myToolConfigs.forEach(config => { toolRegistry.registerTool(ToolBuilder.fromConfig(config), config.category); }); }Add Tests
// tests/unit/tools/my-tool.test.ts describe('my_new_tool', () => { it('should handle valid input', async () => { // Test implementation }); });
Code Quality Standards
๐ TypeScript: Strict type checking with comprehensive interfaces
๐ ESLint: Code style and quality enforcement
๐ฏ Testing: >80% test coverage requirement
๐ Documentation: JSDoc for all public APIs
๐ Security: Input validation and sanitization
โก Performance: Efficient algorithms and caching
Architecture Guidelines
๐๏ธ Separation of Concerns: Each module has a single responsibility
๐ Dependency Injection: Loose coupling between components
๐ Scalability: Designed for large email datasets
๐ก๏ธ Error Handling: Comprehensive error handling and logging
๐ Async Operations: Non-blocking I/O with proper resource cleanup
Contributing Guidelines
๐ฏ Issues & Feature Requests
Use issue templates
Provide detailed descriptions
Include use cases and examples
๐ป Pull Requests
Follow PR template
Include tests and documentation
Ensure CI passes
Request reviews
๐ Code Review Checklist
โ Tests pass and coverage maintained
โ Documentation updated
โ Type safety maintained
โ Security considerations addressed
โ Performance implications considered
Extension Points
The server is designed for extensibility:
๐ง Custom Tools: Add domain-specific tools
๐ง Analyzers: Implement custom categorization algorithms
๐ Exporters: Add new export formats
๐ Search Providers: Integrate external search engines
โ๏ธ Storage Backends: Add cloud storage providers
๐ Example Workflows
๐ Initial Setup & Email Organization
๐งน Advanced Cleanup Workflow
๐ค Automated Cleanup Policy Setup
๐ Advanced Search & Analysis
๐ Analytics & Monitoring
๐ Security & Safety
๐ก๏ธ Authentication & Authorization
OAuth2 Flow: Secure Google OAuth2 implementation
Token Encryption: All tokens encrypted at rest using AES-256
Scope Limitation: Minimal required Gmail API scopes
Token Rotation: Automatic token refresh and rotation
Session Management: Secure session handling with expiration
๐ Data Protection
Local Storage: Encrypted SQLite database for metadata
No Email Content Storage: Only metadata stored locally
Audit Logging: Comprehensive operation logging
Data Isolation: User data completely isolated
Secure Communication: HTTPS/TLS for all API communications
โ ๏ธ Safety Mechanisms
Dry Run Mode: All destructive operations support preview mode
Confirmation Prompts: Multi-step confirmation for bulk operations
Safety Limits: Configurable maximum deletion/modification limits
Backup Integration: Automatic backup before major operations
Rollback Capability: Ability to restore from archives
๐จ Risk Mitigation
Rate Limiting: Gmail API rate limit compliance
Error Handling: Comprehensive error recovery
Validation: Input sanitization and validation
Monitoring: Real-time operation monitoring
Alerts: Automatic alerts for critical issues
๐ Security Best Practices
โ Troubleshooting
๐ Authentication Issues
Problem: Authentication failed or Invalid credentials
Problem: Token expired errors
๐ง Email Processing Issues
Problem: Categorization taking too long
Problem: Search results incomplete
๐๏ธ Deletion & Cleanup Issues
Problem: Deletion failed or Cleanup stuck
Problem: Archives not restoring
โก Performance Issues
Problem: Slow search or categorization
Problem: High memory usage
๐ Database Issues
Problem: Database locked or SQLite errors
๐ง Development Issues
Problem: MCP Inspector not working
Problem: TypeScript compilation errors
๐ Getting Help
๐ Documentation: Check
docs/directory for detailed guides๐ Issues: Create detailed issue reports on GitHub
๐ฌ Discussions: Join community discussions
๐ Debugging: Enable debug logging:
LOG_LEVEL=debug
๐จ Emergency Procedures
If you accidentally delete important emails:
Check Gmail Trash folder first
Use
restore_emailsif archivedCheck local database for metadata
Contact Gmail support for account recovery
If system is unresponsive:
Cancel all running jobs:
cancel_jobRestart server:
npm startCheck system health:
get_system_healthClear caches if needed:
rm -rf data/cache/
๐ License
MIT License - see LICENSE file for details.
๐ค Contributing
We welcome contributions! Please see our Contributing Guidelines for details on:
๐ Bug reports and feature requests
๐ป Code contributions and pull requests
๐ Documentation improvements
๐งช Testing and quality assurance
๐ Community support and discussions
โญ Star this project if you find it useful!
To run the test suite efficiently, always set the environment variable NODE_ENV=test before running tests. This enables fast mode, which:
Skips artificial delays (e.g., between batches)
Reduces logging output for cleaner and faster test runs
Uses smaller data sets in most tests for speed (except explicit performance tests)
Example:
Or with jest directly:
CI/CD:
Your CI pipeline should always set NODE_ENV=test to ensure the fastest possible test execution.