Skip to main content
Glama
Gmail Check MCP Server

Gmail Check MCP Server

by baddif

Gmail Check MCP Server

๐Ÿ”ง AI-Powered Gmail Integration for MCP (Model Context Protocol)

A comprehensive skill for checking Gmail emails with advanced filtering, caching, and AI agent integration. Supports both standalone operation and MCP server mode for use with Claude Desktop and other AI agents.

โœจ Features

  • ๐Ÿ” Smart Email Filtering - Filter by sender, subject (partial match), date range, and read status

  • ๐Ÿ“ง Full Content Download - Download email headers, body content, and metadata

  • ๐Ÿ’พ Intelligent Caching - 30-minute cache with hash-based deduplication

  • ๐Ÿค– MCP Compatible - Full Model Context Protocol support for AI agents

  • ๐ŸŒ Multi-Language - Supports Chinese and English interfaces

  • ๐Ÿ” Secure Auth - Gmail app password authentication

  • โšก High Performance - Optimized IMAP operations with connection reuse

Related MCP server: Gmail AutoAuth MCP Server

๐Ÿš€ Quick Start

# Clone and install
git clone https://github.com/baddif/mcp-server-gmail-check.git
cd mcp-server-gmail-check
bash install.sh

# Check installation
python3 version.py --info

Option 2: Manual Installation

# 1. Clone repository
git clone https://github.com/baddif/mcp-server-gmail-check.git
cd mcp-server-gmail-check

# 2. Install Python dependencies
pip3 install -r requirements.txt

# 3. Configure Gmail credentials
cp gmail_config_example.json gmail_config_local.json
# Edit gmail_config_local.json with your credentials

# 4. Test installation
python3 test_gmail_skill.py

# 5. Check version
python3 version.py --version

๐Ÿ”„ Version Control & Updates

Check Current Version

# Show version information
python3 version.py --info

# Show version string only
python3 version.py --version

# Check for available updates
python3 version.py --check-updates

# Get version data as JSON
python3 version.py --json

Automatic Updates

# Automatic update with backup
./update.sh

# Check for updates without applying
./update.sh --check

# Show update help
./update.sh --help

Manual Update Process

# 1. Backup your configuration
cp gmail_config_local.json gmail_config_backup.json

# 2. Check for uncommitted changes
git status

# 3. Pull latest changes
git pull origin main

# 4. Update dependencies
pip3 install -r requirements.txt --upgrade

# 5. Test installation
python3 mcp_server.py --test

# 6. Restore configuration if needed
# (your gmail_config_local.json is preserved automatically)

Version Information

  • Current Version: v1.1.0 (2026-02-12)

  • MCP Compatibility: 2024-11-05

  • Python Requirement: 3.7+

  • Update Method: Git-based with automatic dependency management

What's New in v1.1.0

  • โฑ๏ธ Enhanced Time Control: time_range_hours parameter for precise timing (1-720 hours)

  • ๐Ÿ’พ Cache Management: use_cache parameter for flexible cache control

  • ๐Ÿ”„ Version Control: Automatic update system with configuration backup

  • ๐Ÿ“š Improved Documentation: Comprehensive parameter guides and examples

See CHANGELOG.md for complete version history.

Running tests

The project uses pytest for tests. Most tests are unit tests and safe to run locally. Integration tests that contact live Gmail services are located under tests/integration/ and are gated behind the RUN_LIVE_TESTS environment variable to avoid accidental runs.

How to run integration (live) tests

  1. Create and activate the project's virtual environment (recommended):

source .venv/bin/activate

  1. Create a local credentials file at the repository root named gmail_config_local.json (this file is gitignored). Provide your Gmail username and an app password (recommended). Do not commit this file.

  2. Run the integration tests by enabling the gate:

export RUN_LIVE_TESTS=1 .venv/bin/python -m pytest tests/integration -q

If you only want to run a single integration test file, pass its path instead of the whole folder.

MCP integration tests and secure credentials

If you want to test the MCP server integration (starting the MCP server and calling it with a client), follow these steps.

  1. Provide credentials securely

  • Locally: create gmail_config_local.json in the repository root. This file is gitignored. Do not commit it.

  • In CI: store your credentials as secret variables (for example, GMAIL_USERNAME and GMAIL_APP_PASSWORD), and write them to gmail_config_local.json at job runtime before running tests.

Example gmail_config_local.json (do not commit):

{
  "username": "your_email@gmail.com",
  "app_password": "your_16_digit_app_password",
  "imap_server": "imap.gmail.com",
  "imap_port": 993
}
  1. Start the MCP server (in a separate shell):

source .venv/bin/activate
python -m mcp_server
  1. Run MCP integration tests (gated):

export RUN_LIVE_TESTS=1
.venv/bin/python -m pytest tests/integration -q

Security notes:

  • Never commit gmail_config_local.json or other secrets. Use CI secrets and write them to files at runtime.

  • Limit the scope of credentials used for CI by using a dedicated Gmail account with minimal permissions.

  • Rotate app passwords periodically.

Creating a local MCP inspector configuration

If you use an MCP inspector or local MCP client for development, you can create a local inspector config from the provided example:

  1. Copy the example file to create your local config:

cp mcp-inspector-config.example.json mcp-inspector-config.json

  1. Edit mcp-inspector-config.json and adjust the args or env.PYTHONPATH if necessary for your local setup. Prefer relative paths (e.g. ./mcp_server.py and .) so the config remains portable.

  2. The repository keeps mcp-inspector-config.example.json under version control; your local mcp-inspector-config.json is ignored by git to avoid committing machine-specific paths.

If you need a quick one-liner to create a local copy and open it in your default editor (macOS):

cp mcp-inspector-config.example.json mcp-inspector-config.json && open mcp-inspector-config.json

Backup & Recovery

The update script automatically backs up:

  • gmail_config_local.json - Your private Gmail credentials

  • claude_desktop_config.json - Claude Desktop configuration

  • Any custom configuration files

Backups are stored in timestamped folders: backup_YYYYMMDD_HHMMSS/

Update Troubleshooting

Update Script Fails

# Check Git repository status
git status

# Manual update
git fetch origin main
git pull origin main

Dependencies Issues

# Force reinstall dependencies
pip3 install -r requirements.txt --force-reinstall

# Check Python version
python3 --version

Configuration Lost

# Restore from backup (replace with your backup folder)
cp backup_20260212_143000/gmail_config_local.json .

โš™๏ธ Configuration

Gmail App Password Setup

  1. Enable 2-Factor Authentication on your Google account

  2. Generate App Password:

    • Go to Google Account Settings

    • Security โ†’ 2-Step Verification โ†’ App passwords

    • Select "Mail" and generate password

  3. Configure credentials in gmail_config_local.json:

{
    "username": "your_email@gmail.com",
    "password": "your_16_digit_app_password",
    "imap_server": "imap.gmail.com",
    "imap_port": 993
}

Configuration Files

  • gmail_config_example.json - Public template (safe to commit)

  • gmail_config_local.json - Your private config (gitignored)

๐Ÿ“– Usage Examples

Standalone Python Usage

from gmail_check_skill import GmailCheckSkill
from ldr_compat import ExecutionContext

# Initialize skill
skill = GmailCheckSkill()
ctx = ExecutionContext()

# Check recent emails
result = skill.execute(ctx, 
    sender_filter="notifications@github.com",
    max_emails=10,
    download_content=True
)

print(f"Found {len(result['data']['emails'])} emails")

MCP Server Integration

Start MCP Server

# Start MCP server for AI agent integration
python3 mcp_server.py

# Test MCP server
python3 mcp_server.py --test

Claude Desktop Integration

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "gmail-check": {
      "command": "python3",
      "args": ["/path/to/mcp-server-gmail-check/mcp_server.py"],
      "env": {
        "PYTHONPATH": "/path/to/mcp-server-gmail-check"
      }
    }
  }
}

Generic MCP Client

from mcp import ClientSession, StdioServerParameters

async def use_gmail_skill():
    server_params = StdioServerParameters(
        command="python3",
        args=["/path/to/mcp-server-gmail-check/mcp_server.py"]
    )
    
    async with ClientSession(server_params) as session:
        await session.initialize()
        
        # List available tools
        tools = await session.list_tools()
        
        # Check emails
        result = await session.call_tool("gmail_check", {
            "sender_filter": "important@company.com",
            "days_back": 7,
            "download_content": True
        })
        
        return result

๐Ÿ”ง Function Parameters

The Gmail Check MCP Server ๅฎŒๅ…จๆ”ฏๆŒๅ‚ๆ•ฐไผ ้€’๏ผไปฅไธ‹ๆ˜ฏๆ‰€ๆœ‰ๅฏ็”จๅ‚ๆ•ฐ๏ผš

๐Ÿ“‹ Complete Parameter List

Parameter

Type

Required

Default

Description

username

string

โœ… YES

-

Gmail username (email address)

app_password

string

โœ… YES

-

Gmail 16-digit app password

email_filters

object

โœ… YES

-

Email filters: {"sender": ["subject1", "subject2"]}

check_interval

integer

โŒ No

30

Check interval in minutes (1-1440)

background_mode

boolean

โŒ No

false

Continuous monitoring mode

max_emails

integer

โŒ No

100

Max emails per check (1-1000)

days_back

integer

โŒ No

1

Days to look back (1-30)

time_range_hours

integer

โŒ No

24

Time range in hours from current time (1-720, overrides days_back)

use_cache

boolean

โŒ No

true

Whether to use cache to avoid re-processing emails

๐ŸŽฏ Parameter Usage Examples

Basic Email Check

{
  "username": "your_email@gmail.com",
  "app_password": "your_16_digit_app_password",
  "email_filters": {
    "notifications@github.com": ["pull request", "issue"],
    "billing@aws.amazon.com": ["invoice", "bill"]
  },
  "max_emails": 20,
  "days_back": 3
}

Background Monitoring

{
  "username": "monitor@gmail.com", 
  "app_password": "monitoring_password",
  "email_filters": {
    "alerts@company.com": ["urgent", "critical", "error"],
    "support@service.com": ["ticket", "request"]
  },
  "background_mode": true,
  "check_interval": 15,
  "max_emails": 50,
  "days_back": 1
}

Comprehensive Scan

{
  "username": "admin@domain.com",
  "app_password": "admin_app_password", 
  "email_filters": {
    "security@bank.com": ["alert", "fraud"],
    "notifications@system.com": ["down", "maintenance"],
    "reports@analytics.com": ["weekly", "monthly"]
  },
  "max_emails": 200,
  "days_back": 7,
  "check_interval": 60
}

Precise Time Range Check

{
  "username": "monitor@company.com",
  "app_password": "precise_monitoring_pwd",
  "email_filters": {
    "alerts@system.com": ["critical", "error"]
  },
  "time_range_hours": 6,
  "use_cache": false,
  "max_emails": 50
}

Cache-Disabled Full Scan

{
  "username": "audit@company.com", 
  "app_password": "audit_app_password",
  "email_filters": {
    "compliance@bank.com": ["violation", "audit"],
    "security@company.com": ["breach", "incident"]
  },
  "time_range_hours": 72,
  "use_cache": false,
  "max_emails": 500
}

๐Ÿค– MCP Client Integration with Parameters

Direct JSON-RPC Call

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "gmail_check",
    "arguments": {
      "username": "user@gmail.com",
      "app_password": "your_app_password",
      "email_filters": {
        "important@company.com": ["urgent", "action required"]
      },
      "max_emails": 25,
      "days_back": 2
    }
  }
}

Python MCP Client

async def check_emails_with_params():
    server_params = StdioServerParameters(
        command="python3",
        args=["/path/to/mcp_server.py"]
    )
    
    async with ClientSession(server_params) as session:
        await session.initialize()
        
        # Call with custom parameters
        result = await session.call_tool("gmail_check", {
            "username": "your_email@gmail.com",
            "app_password": "your_app_password",
            "email_filters": {
                "github@notifications.com": ["mentioned", "review"],
                "alerts@system.com": ["critical", "down"]
            },
            "max_emails": 30,
            "days_back": 3,
            "background_mode": False
        })
        
        return result

Claude Desktop with Parameters

When using Claude Desktop, you can specify parameters in your conversation:

"Check my Gmail for:
- GitHub notifications about pull requests from last 2 days  
- System alerts containing 'critical' or 'error' from last week
- Maximum 50 emails
- Username: developer@company.com
- Use background mode for continuous monitoring"

โšก Quick Test Commands

# Test parameter validation
python3 test_mcp_parameters.py

# Simulate MCP client with parameters  
python3 demo_mcp_client.py

# Test real MCP server
echo '{"method":"tools/call","params":{"name":"gmail_check","arguments":{"username":"test@gmail.com","app_password":"test123","email_filters":{"test@example.com":["test"]}}}}' | python3 mcp_server.py

## ๐Ÿ—๏ธ Project Structure

mcp-server-gmail-check/ โ”œโ”€โ”€ ๐Ÿ“ง Core Implementation โ”‚ โ”œโ”€โ”€ gmail_check_skill.py # Main Gmail skill โ”‚ โ”œโ”€โ”€ mcp_server.py # MCP protocol server
โ”‚ โ””โ”€โ”€ ldr_compat.py # Framework compatibility โ”œโ”€โ”€ ๐Ÿงช Testing & Validation โ”‚ โ”œโ”€โ”€ test_gmail_skill.py # Comprehensive tests โ”‚ โ”œโ”€โ”€ test_mcp_parameters.py # Parameter validation tests โ”‚ โ””โ”€โ”€ test_mcp_server.py # MCP server tests โ”œโ”€โ”€ โš™๏ธ Configuration โ”‚ โ”œโ”€โ”€ gmail_config_example.json # Public template โ”‚ โ”œโ”€โ”€ gmail_config_local.json # Private config (gitignored) โ”‚ โ””โ”€โ”€ claude_desktop_config.json # Claude Desktop setup โ”œโ”€โ”€ ๐Ÿš€ Deployment & Updates โ”‚ โ”œโ”€โ”€ install.sh # One-click installation โ”‚ โ”œโ”€โ”€ update.sh # Automatic update script โ”‚ โ”œโ”€โ”€ version.py # Version management system โ”‚ โ”œโ”€โ”€ requirements.txt # Python dependencies โ”‚ โ””โ”€โ”€ .gitignore # Security exclusions โ””โ”€โ”€ ๐Ÿ“š Documentation โ”œโ”€โ”€ README.md # This file โ”œโ”€โ”€ CHANGELOG.md # Version history & updates โ”œโ”€โ”€ MCP_DEPLOYMENT.md # MCP integration guide โ””โ”€โ”€ SKILL_GENERATION_RULES.md # Development standards


## ๐Ÿ”’ Security Features

- โœ… **App Password Auth** - Uses Gmail app passwords, not main password
- โœ… **Config Isolation** - Private credentials separated from code
- โœ… **Git Security** - Sensitive files automatically gitignored
- โœ… **Input Validation** - All parameters validated and sanitized
- โœ… **Error Handling** - Secure error messages without credential leaks

## ๐Ÿš€ Performance Optimizations

- โšก **Connection Reuse** - Persistent IMAP connections
- ๐Ÿ’พ **Smart Caching** - 30-minute cache with hash-based deduplication  
- ๐Ÿ” **Efficient Search** - Server-side IMAP SEARCH commands
- ๐Ÿ“Š **Batch Processing** - Bulk email operations
- ๐Ÿงน **Memory Management** - Automatic cleanup and connection management

## ๐Ÿ” Troubleshooting

### Common Issues

**Authentication Failed**
```bash
# Check credentials
python3 -c "
import json
with open('gmail_config_local.json') as f:
    config = json.load(f)
print('Username:', config['username'])
print('Password length:', len(config['password']))
"

No Emails Found

  • Check date range with days_back parameter

  • Verify sender/subject filters are correct

  • Ensure Gmail IMAP is enabled

MCP Server Issues

# Test MCP server functionality
python3 mcp_server.py --test

# Check MCP configuration
echo '{"method":"initialize","params":{},"id":1}' | python3 mcp_server.py

Debug Mode

Enable detailed debugging:

import logging
logging.basicConfig(level=logging.DEBUG)

# Run with debug output
result = skill.execute(ctx, sender_filter="test@example.com")

๐Ÿค Contributing

  1. Fork the repository

  2. Create feature branch: git checkout -b feature/amazing-feature

  3. Follow coding standards in SKILL_GENERATION_RULES.md

  4. Add tests: Update test_gmail_skill.py

  5. Commit changes: git commit -m 'Add amazing feature'

  6. Push to branch: git push origin feature/amazing-feature

  7. Open Pull Request

๐Ÿ“‹ Development Standards

This project follows the AI-Powered Application Standards v2.0.0:

  • โœ… OpenAI Function Calling compatible

  • โœ… Model Context Protocol (MCP) support

  • โœ… Framework-agnostic design

  • โœ… Comprehensive error handling

  • โœ… Multi-language support

  • โœ… Security-first configuration

See SKILL_GENERATION_RULES.md for detailed development guidelines.

๐Ÿ“œ License

MIT License - see LICENSE file for details.

๐Ÿ“ž Support

  • ๐Ÿ› Bug Reports: GitHub Issues

  • ๐Ÿ’ก Feature Requests: GitHub Discussions

  • ๐Ÿ“– Documentation: See MCP_DEPLOYMENT.md for advanced setup

  • ๐Ÿ”„ Updates: Use ./update.sh for automatic updates or check CHANGELOG.md

  • ๐Ÿ“Š Version Info: Run python3 version.py --info for current version details

Getting Help

Before reporting issues, please:

  1. Check your version: python3 version.py --version

  2. Try updating: ./update.sh --check

  3. Review CHANGELOG.md for known issues

  4. Test basic functionality: python3 mcp_server.py --test

Include in bug reports:

  • Version information (python3 version.py --json)

  • Error messages and logs

  • Configuration (without credentials)

  • Steps to reproduce the issue


Made with โค๏ธ for the AI-powered future

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelogโ€ฆ

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables AI assistants to interact with Gmail accounts through IMAP/SMTP, supporting reading, sending, replying to emails, managing threads, downloading attachments, and searching with Gmail syntax using simple app password authentication.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to manage Gmail through natural language interactions, supporting email operations (send, read, search, draft), comprehensive attachment handling (send, receive, download), label management, filters, and batch operations with automatic OAuth2 authentication.
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables interaction with Gmail accounts via IMAP and SMTP, providing tools for searching emails, retrieving content, managing labels, and sending/forwarding emails through natural language.
      -
    • A
      license
      A
      quality
      B
      maintenance
      Enables AI agents to search, read, label, draft, and reversibly trash Gmail messages through the official Gmail API, with safe attachment handling and guardrails against prompt injection. Drafts can be sent only after explicit user confirmation for that exact draft, and nothing is permanently deleted.
      21
      1
      MIT