Gmail检查MCP服务器
🔧 基于人工智能的Gmail MCP集成(模型上下文协议)
通过高级过滤、缓存和AI代理集成检查Gmail电子邮件的综合技能。支持独立操作和MCP服务器模式,可与Claude Desktop和其他AI代理一起使用。
✨ 特性
- 🔍 智能电子邮件过滤 -按发件人、主题(部分匹配)、日期范围和读取状态筛选
- 📧 完整内容下载 -下载电子邮件标题、正文内容和元数据
- 💾 智能高速缓存 -具有基于哈希的重复数据消除的30分钟缓存
- 🤖 MCP兼容 -AI代理的完整模型上下文协议支持
- 🌐 多语言 -支持中英文界面
- 🔐 安全认证 -Gmail应用程序密码验证
- ⚡ 高性能 -通过连接重用优化IMAP操作
🚀 快速开始
选项1:一键安装(推荐)
# 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选项2:手动安装
# 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🔄 版本控制和更新
检查当前版本
# 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 update with backup
./update.sh
# Check for updates without applying
./update.sh --check
# Show update help
./update.sh --help手动更新流程
# 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)版本信息
- 当前版本:v1.1.0(2026-02-12)
- MCP兼容性: 2024-11-05
- Python要求: 3.7+
- 更新方法:基于Git的自动依赖管理
v1.1.0的新增功能
- ⏱️ 增强的时间控制:
time_range_hours精确计时参数(1-720小时) - 💾 缓存管理:
use_cache灵活缓存控制参数 - 🔄 版本控制:带配置备份的自动更新系统
- 📚 改进文档:全面的参数指南和示例
看 更改日志.md 查看完整的版本历史记录。
运行测试
该项目使用pytest进行测试。大多数测试都是单元测试,可以在本地安全运行。联系实时Gmail服务的集成测试位于 tests/integration/ 并被关在后面 RUN_LIVE_TESTS 环境变量,以避免意外运行。
如何运行集成(实时)测试
- 创建并激活项目的虚拟环境(推荐):
source.ven/bin/activate
- 在存储库根目录下创建名为的本地凭据文件
gmail_config_local.json(此文件被忽略)。提供您的Gmail用户名和应用程序密码(推荐)。不要提交此文件。
- 通过启用门来运行集成测试:
导出RUN_LIVE_TESTS=1 .venv/bin/python-m pytest测试/集成-q
如果只想运行单个集成测试文件,请传递其路径,而不是整个文件夹。
MCP集成测试和安全证书
如果要测试MCP服务器集成(启动MCP服务器并用客户端调用它),请执行以下步骤。
- 安全地提供凭据
- 本地:创建
gmail_config_local.json在存储库根目录中。这个文件是无效的。不要承诺。 - 在CI中:将凭据存储为秘密变量(例如,GMAIL_USERNAME和GMAIL_APP_PASSWORD),并将其写入
gmail_config_local.json在运行测试之前的作业运行时。
示例 gmail_config_local.json (不承诺):
{
"username": "your_email@gmail.com",
"app_password": "your_16_digit_app_password",
"imap_server": "imap.gmail.com",
"imap_port": 993
}- 启动MCP服务器(在单独的shell中):
source .venv/bin/activate
python -m mcp_server- 运行MCP集成测试(门控):
export RUN_LIVE_TESTS=1
.venv/bin/python -m pytest tests/integration -q安全注意事项:
- 永不承诺
gmail_config_local.json或其他秘密。使用CI机密并在运行时将其写入文件。 - 通过使用具有最小权限的专用Gmail帐户来限制用于CI的凭据范围。
- 定期轮换应用程序密码。
创建本地MCP检查器配置
如果您使用MCP检查器或本地MCP客户端进行开发,您可以从提供的示例中创建本地检查器配置:
- 复制示例文件以创建本地配置:
cp-mcp-inspector-config.example.json mcp-inspector-config.json
- 编辑
mcp-inspector-config.json并调整args或env.PYTHONPATH如果您的本地设置需要。更喜欢相对路径(例如。./mcp_server.py和.)因此配置仍然是可移植的。
- 存储库保存
mcp-inspector-config.example.json在版本控制下;您所在的地区mcp-inspector-config.json被git忽略,以避免提交特定于机器的路径。
如果你需要一个快速的单行命令来创建本地副本并在默认编辑器(macOS)中打开它:
cp mcp-inspector-config.example.json mcp-inspector-config.json && open mcp-inspector-config.json备份和恢复
更新脚本会自动备份:
gmail_config_local.json-您的私人Gmail凭据claude_desktop_config.json-Claude桌面配置- 任何自定义配置文件
备份存储在带时间戳的文件夹中: backup_YYYYMMDD_HHMMSS/
更新故障排除
更新脚本失败
# Check Git repository status
git status
# Manual update
git fetch origin main
git pull origin main依赖关系问题
# Force reinstall dependencies
pip3 install -r requirements.txt --force-reinstall
# Check Python version
python3 --version配置丢失
# Restore from backup (replace with your backup folder)
cp backup_20260212_143000/gmail_config_local.json .⚙️ 配置
Gmail应用程序密码设置
- 启用双因素身份验证 在您的Google帐户上
- 生成应用程序密码:
- 首选 Google帐号设置 - 安全→ 2-步骤验证→ 应用密码 - 选择“邮件”并生成密码
- 配置凭据 在
gmail_config_local.json:
{
"username": "your_email@gmail.com",
"password": "your_16_digit_app_password",
"imap_server": "imap.gmail.com",
"imap_port": 993
}配置文件
gmail_config_example.json-公共模板(提交安全)gmail_config_local.json-您的私有配置(gitignored)
📖 用法示例
独立Python用法
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服务器集成
启动MCP服务器
# Start MCP server for AI agent integration
python3 mcp_server.py
# Test MCP server
python3 mcp_server.py --testClaude桌面集成
添加到您的 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"
}
}
}
}通用MCP客户端
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🔧 功能参数
Gmail检查MCP服务器 完全支持参数传递!以下是所有可用参数:
📋 完整参数列表
| 参数 | 类型 | 必填 | 默认 | 说明 |
|---|---|---|---|---|
username | string | ✅ 是 | - | Gmail用户名(电子邮件地址) |
app_password | string | ✅ 是 | - | Gmail 16位应用程序密码 |
email_filters | 对象 | ✅ 是 | - | 电子邮件过滤器: {"sender": ["subject1", "subject2"]} |
check_interval | 整数 | ❌ 否 | 30 | 检查间隔(分钟)(1-1440) |
background_mode | boolean | ❌ 否 | 错误 | 连续监控模式 |
max_emails | 整数 | ❌ 否 | 100 | 每张支票的最大电子邮件数(1-1000) |
days_back | 整数 | ❌ 否 | 1 | 需要回顾的天数(1-30) |
time_range_hours | 整数 | ❌ 否 | 24 | 从当前时间开始的时间范围(小时)(1-720,覆盖days_back) |
use_cache | boolean | ❌ 否 | true | 是否使用缓存来避免重新处理电子邮件 |
🎯 参数使用示例
基本电子邮件检查
{
"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
}本底监测
{
"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
}全面扫描
{
"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
}精确时间范围检查
{
"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
}缓存已禁用完全扫描
{
"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客户端与参数集成
直接JSON-RPC调用
{
"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客户端
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桌面
使用Claude Desktop时,您可以在对话中指定参数:
"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"⚡ 快速测试命令
# 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服务器gmail检查/ ├── 📧 核心实施 │ ├── gmail_check_skill.py#gmail主要技巧 │ ├── mcp_server.py#mcp协议服务器\ │ └── ldr_compat.py#框架兼容性 ├── 🧪 测试与验证 │ ├── test_gmail_skill.py#综合测试 │ ├── test_mcp_parameters.py#参数验证测试 │ └── test_mcp_server.py#mcp服务器测试 ├── ⚙️ 配置 │ ├── gmail_configure_example.json#公共模板 │ ├── gmail_config \_local.json#私有配置(gitignored) │ └── claude_desktop_config.json#克劳德桌面设置 ├── 🚀 部署和更新 │ ├── install.sh#一键安装 │ ├── update.sh#自动更新脚本 │ ├── version.py#版本管理系统 │ ├── requirements.txt#Python依赖项 │ └── .gitignore#安全排除 └── 📚 文档 ├── README.md#此文件 ├── CHANGELOG.md#版本历史和更新 ├── MCP_DEPLOYMENT.md#MCP集成指南 └── 技能_生成_规则.md#开发标准
## 🔒 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**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'])) "
**未找到电子邮件**
- 检查日期范围 `days_back` 参数
- 验证发件人/主题筛选器是否正确
- 确保Gmail IMAP已启用
**MCP服务器问题**
Test MCP server functionality
python3 mcp_server.py --test
Check MCP configuration
echo '{"method":"initialize","params":{},"id":1}' | python3 mcp_server.py
### 调试模式
启用详细调试:
import logging logging.basicConfig(level=logging.DEBUG)
Run with debug output
result = skill.execute(ctx, sender_filter="test@example.com")
## 🤝 贡献
1. **分叉存储库**
1. **创建特征分支**: `git checkout -b feature/amazing-feature`
1. **遵循编码标准** 在 `SKILL_GENERATION_RULES.md`
1. **添加测试**:更新 `test_gmail_skill.py`
1. **提交更改**: `git commit -m 'Add amazing feature'`
1. **推送到分支**: `git push origin feature/amazing-feature`
1. **打开拉取请求**
## 📋 开发标准
该项目遵循 **人工智能应用标准v2.0.0**:
- ✅ OpenAI函数调用兼容
- ✅ 模型上下文协议(MCP)支持
- ✅ 框架无关设计
- ✅ 全面的错误处理
- ✅ 多语言支持
- ✅ 安全第一配置
看 `SKILL_GENERATION_RULES.md` 详细的开发指南。
## 📜 许可证
MIT许可证-请参阅 [许可证](LICENSE) 文件以获取详细信息。
## 🔗 相关项目
- [模型上下文协议](https://modelcontextprotocol.io/) -MCP规范
- [克劳德桌面](https://claude.ai/desktop) -支持MCP的AI助手
- [OpenAI函数调用](https://platform.openai.com/docs/guides/function-calling) -函数调用标准
## 📞 支持
- 🐛 **错误报告**:
- 💡 **功能请求**:
- 📖 **文档**:参见 `MCP_DEPLOYMENT.md` 用于高级设置
- 🔄 **更新**:使用 `./update.sh` 用于自动更新或检查 `CHANGELOG.md`
- 📊 **版本信息**:运行 `python3 version.py --info` 有关当前版本的详细信息
### 获取帮助
**在报告问题之前,请:**
1. 检查您的版本: `python3 version.py --version`
1. 尝试更新: `./update.sh --check`
1. 审查 [更改日志.md](CHANGELOG.md) 对于已知问题
1. 测试基本功能: `python3 mcp_server.py --test`
**在错误报告中包括:**
- 版本信息(`python3 version.py --json`)
- 错误消息和日志
- 配置(无凭据)
- 重现问题的步骤
______________________________________________________________________
**制作❤️ 面向人工智能驱动的未来**