Manage emails using Gmail and IMAP protocols. Requires external configuration for credentials and settings.
Gmail と IMAP をサポートするメール管理用MCPサーバー
プロジェクトルートに.env
ファイルを作成して環境変数を設定します:
# .env.exampleをコピーして設定
cp .env.example .env
# Gmail APIタイムアウト(デフォルト: 60000ms = 60秒)
GMAIL_TIMEOUT_MS=60000
# IMAP接続タイムアウト(デフォルト: 30000ms = 30秒)
IMAP_CONNECTION_TIMEOUT_MS=30000
# IMAP操作タイムアウト(デフォルト: 60000ms = 60秒)
IMAP_OPERATION_TIMEOUT_MS=60000
# 統合検索タイムアウト(デフォルト: 25000ms = 25秒)
SEARCH_ALL_TIMEOUT_MS=25000
MCP公式仕様では、具体的なタイムアウト時間は規定されておらず、実装者が適切な値を設定することが期待されています:
本実装では、MCP仕様に準拠した適切なタイムアウト値を設定し、環境変数による柔軟な調整を可能にしています。
MCPサーバーは詳細なGmail認証エラーメッセージを提供し、問題解決のための具体的な手順を案内します。
Gmail認証エラー: リフレッシュトークンが無効または期限切れです。
❌ アカウント: kentaroh7
🔧 解決方法: 以下のコマンドでトークンを再生成してください:
node scripts/gmail-desktop-auth.mjs kentaroh7
📝 詳細: OAuth 2.0 リフレッシュトークンが無効、期限切れ、または取り消されています。
Gmail接続エラー: ネットワークタイムアウトが発生しました。
❌ アカウント: kentaroh7
🔧 解決方法:
1. ネットワーク接続を確認してください
2. ファイアウォール設定を確認してください
3. しばらく時間をおいて再試行してください
Gmail API制限エラー: APIクォータ制限に達しました。
❌ アカウント: kentaroh7
🔧 解決方法:
1. しばらく時間をおいて再試行してください
2. 複数のリクエストを短時間で送信しないでください
3. Google Cloud Consoleでクォータ制限を確認してください
Gmail権限エラー: APIアクセス権限が不足しています。
❌ アカウント: kentaroh7
🔧 解決方法:
1. Google Cloud ConsoleでGmail APIが有効化されているか確認
2. OAuth同意画面でスコープが正しく設定されているか確認
3. 以下のコマンドで認証をやり直してください:
node scripts/gmail-desktop-auth.mjs kentaroh7
CLI環境とMCP環境の両方で完璧に動作するツール:
list_accounts
- 設定済みメールアカウントの一覧表示get_account_stats
- 包括的なアカウント統計情報search_all_emails
- GmailとIMAPアカウント横断検索list_imap_emails
- IMAPアカウントからのメール一覧get_imap_unread_count
- IMAPアカウントの未読数取得search_imap_emails
- IMAPアカウント内メール検索get_imap_email_detail
- IMAP詳細メール情報取得MCP仕様準拠の適切なタイムアウト設定により、以下のGmailツールも安定動作:
list_emails
(Gmail) - Gmail メール一覧取得get_unread_count
(Gmail) - Gmail 未読数取得推奨: 包括的なGmail+IMAP検索機能には search_all_emails
を使用してください。
getProfile
による即座の接続テストGMAIL_TIMEOUT_MS
で設定可能(デフォルト60秒)resultSizeEstimate
使用このプロジェクトのテストは、特定の環境やアカウントに依存しない汎用的な設計になっています:
.env
設定から利用可能なアカウントを自動検出テスト実行には以下の設定が必要です:
.env
ファイルでの適切な環境変数設定設定が不足している場合、テストは以下のメッセージで失敗します:
テスト実行には最低1つのGmailアカウントまたは1つのIMAPアカウントの設定が必要です。.envファイルを確認してください。
# 全テストスイートの実行
npm test
# タイムアウト防止テストの実行
npm run test:imap-timeout
# シンプルIMAPテストの実行
npm run test:simple-imap
# 包括的ヘルスチェックの実行
npm run health:check
テスト実行時に以下のような環境チェックメッセージが表示されます:
テスト環境チェック: 完全なテスト環境: Gmail 4アカウント, IMAP 3アカウント
テスト環境チェック: Gmailアカウントのみでテスト実行: 2アカウント
テスト環境チェック: IMAPアカウントのみでテスト実行: 1アカウント
search_all_emails
を使用get_account_stats
を使用list_accounts
を使用サーバーは関心の分離を明確にした設計を使用:
このアーキテクチャにより、MCP制約内で最高のユーザーエクスペリエンスを提供しながら、信頼性、パフォーマンス、保守性を確保しています。
ビルドされたJavaScriptファイル(dist/index.js
)を使用すると、以下の問題が発生する可能性があります:
/
)で起動される.env
ファイル参照が失敗TypeScript直接実行を使用することで、これらの問題を完全に解決できます:
{
"mcpServers": {
"mcp-email-server": {
"command": "npx",
"args": ["tsx", "src/index.ts"],
"cwd": "/path/to/mcp-email-server", // 重要: 作業ディレクトリの指定
"env": {
"EMAIL_ENCRYPTION_KEY": "your-encryption-key"
}
}
}
}
import.meta.url
を使用した確実なファイルパス取得.env
ファイルを読み込みcwd
設定により確実なプロジェクトルート参照アカウント認識の問題の多くは、暗号化キーの不一致が原因です:
# .envファイルの暗号化キー確認
grep EMAIL_ENCRYPTION_KEY .env
# CursorのMCP設定の暗号化キー確認
cat ~/.cursor/mcp.json | grep EMAIL_ENCRYPTION_KEY
両方のキーが完全に一致している必要があります。
TypeScript直接実行には以下が必要です:
# tsx の確認・インストール
npx tsx --version || npm install tsx
# 必要なTypeScript依存関係
npm install @types/node typescript
git clone <repository-url>
cd mcp-email-server
npm install
環境変数ファイルをコピーして設定します:
cp .env.example .env
.env
ファイルを編集して、あなたの設定を追加してください。
# クイックテスト(推奨)
npm run test:quick
# 包括的ヘルスチェック
npm run health:check
TypeScript直接実行に必要なパッケージを確認・インストール:
# tsx の確認・インストール
npx tsx --version || npm install tsx
# TypeScript関連の依存関係確認
npm install @types/node typescript
CursorのMCP設定ファイル(~/.cursor/mcp.json
)にサーバーを追加します。
推奨設定(TypeScript直接実行):
{
"mcpServers": {
"mcp-email-server": {
"command": "npx",
"args": ["tsx", "src/index.ts"],
"cwd": "/your/path/to/mcp-email-server",
"env": {
"EMAIL_ENCRYPTION_KEY": "your-unique-encryption-key"
}
}
}
}
~/.cursor/mcp.json
%USERPROFILE%\.cursor\mcp.json
CursorのMCP設定ファイルに以下を追加:
{
"mcpServers": {
"mcp-email-server": {
"command": "npx",
"args": ["tsx", "src/index.ts"],
"cwd": "/path/to/mcp-email-server",
"env": {
"EMAIL_ENCRYPTION_KEY": "your-unique-encryption-key-here",
"NODE_ENV": "development",
"DEBUG": "false"
}
}
}
}
⚠️ 注意: ビルドされたJavaScriptファイルでは.env読み込みに問題がある場合があります。TypeScript直接実行を推奨。
{
"mcpServers": {
"mcp-email-server": {
"command": "node",
"args": ["dist/index.js"],
"cwd": "/path/to/mcp-email-server",
"env": {
"EMAIL_ENCRYPTION_KEY": "your-unique-encryption-key-here",
"NODE_ENV": "development",
"DEBUG": "false"
}
}
}
}
{
"mcpServers": {
"mcp-email-server": {
"command": "npx",
"args": ["tsx", "src/index.ts"],
"cwd": "/Users/your-username/path/to/mcp-email-server",
"env": {
"EMAIL_ENCRYPTION_KEY": "mcp-email-server-development-key-2025"
}
}
}
}
{
"mcpServers": {
"mcp-email-server": {
"command": "npx",
"args": ["tsx", "src/index.ts"],
"cwd": "/Users/your-username/path/to/mcp-email-server",
"env": {
"EMAIL_ENCRYPTION_KEY": "your-strong-encryption-key",
"NODE_ENV": "production",
"DEBUG": "false",
"GMAIL_TIMEOUT_MS": "60000",
"IMAP_CONNECTION_TIMEOUT_MS": "30000",
"IMAP_OPERATION_TIMEOUT_MS": "60000",
"EMAIL_DEFAULT_TIMEZONE": "Asia/Tokyo"
}
}
}
}
パスの確認:
pwd
# /Users/your-username/path/to/mcp-email-server
ビルド確認:
ls -la dist/index.js
# -rw-r--r-- 1 user staff 3200 Dec 29 10:00 dist/index.js
MCP設定ファイル編集:
# macOS/Linux
nano ~/.cursor/mcp.json
# Windows
notepad %USERPROFILE%\.cursor\mcp.json
Cursor再起動: 設定反映のためCursorを再起動
動作確認: MCPツールが利用可能になったことを確認
npx tsx src/index.ts
を推奨(ビルド不要、確実な.env読み込み)EMAIL_ENCRYPTION_KEY
のみnpm install tsx
でインストール)プロジェクトパスの確認:
# プロジェクトディレクトリの確認
ls -la /path/to/mcp-email-server/src/index.ts
Node.js/tsx確認:
node --version # v18.0.0以上が必要
npx tsx --version # tsxがインストールされているか確認
手動テスト(推奨):
cd /path/to/mcp-email-server
npx tsx src/index.ts
環境変数確認:
# .envファイルの存在確認
ls -la .env
# 暗号化キーの設定確認
cat .env | grep EMAIL_ENCRYPTION_KEY
.env not found
: 作業ディレクトリ(cwd)が正しく設定されていないtsx command not found
: npm install tsx
またはnpm install -g tsx
でインストールCannot find module
: TypeScript/tsxパッケージの依存関係問題Encryption key required
: EMAIL_ENCRYPTION_KEY
環境変数を設定Cursor上でMCPツールが正常に利用できるか確認:
以下のコマンドでMCPサーバーの基本機能をテスト:
// アカウント一覧の確認
mcp_mcp-email-server_list_accounts()
// アカウント統計の確認
mcp_mcp-email-server_get_account_stats()
// 存在しないアカウントでのエラーハンドリング確認
mcp_mcp-email-server_test_connection("nonexistent_account")
期待される結果:
{
"mcpServers": {
"mcp-email-server": {
"command": "npx",
"args": ["tsx", "src/index.ts"],
"cwd": "/Users/username/projects/mcp-email-server",
"env": {
"EMAIL_ENCRYPTION_KEY": "personal-gmail-mcp-2025"
}
}
}
}
{
"mcpServers": {
"mcp-email-server": {
"command": "npx",
"args": ["tsx", "src/index.ts"],
"cwd": "/Users/username/projects/mcp-email-server",
"env": {
"EMAIL_ENCRYPTION_KEY": "business-email-mcp-secure-key-2025",
"NODE_ENV": "production",
"GMAIL_TIMEOUT_MS": "45000",
"IMAP_CONNECTION_TIMEOUT_MS": "20000",
"EMAIL_DEFAULT_TIMEZONE": "Asia/Tokyo"
}
}
}
}
メールアカウントを設定した後の実用的な使用例:
// 全アカウントからキーワード検索
mcp_mcp-email-server_search_all_emails({
query: "請求書",
limit: 20,
accounts: "ALL"
})
// 全アカウントの状態確認
mcp_mcp-email-server_list_accounts()
// 特定アカウントの接続テスト
mcp_mcp-email-server_test_connection("business_gmail")
// 全アカウントの統計情報
mcp_mcp-email-server_get_account_stats()
暗号化キー管理:
MCP設定ファイル:
.cursor/mcp.json
は通常バージョン管理対象外権限最小化:
## Configuration
### Environment Variables
Create a `.env` file with the following configuration:
```bash
# Encryption key for password storage (change this!)
EMAIL_ENCRYPTION_KEY=your-secret-encryption-key-here
# Gmail OAuth2 Configuration
GMAIL_CLIENT_ID=your-gmail-client-id
GMAIL_CLIENT_SECRET=your-gmail-client-secret
GMAIL_REDIRECT_URI=http://localhost:3000/oauth2callback
# Gmail Account Tokens (obtain via OAuth2 flow)
GMAIL_ACCESS_TOKEN_account1=your-access-token
GMAIL_REFRESH_TOKEN_account1=your-refresh-token
# Additional Gmail accounts
GMAIL_ACCESS_TOKEN_account2=your-access-token-2
GMAIL_REFRESH_TOKEN_account2=your-refresh-token-2
# IMAP Account Configuration
IMAP_HOST_myimap=imap.example.com
IMAP_PORT_myimap=993
IMAP_SECURE_myimap=true
IMAP_USER_myimap=user@example.com
IMAP_PASSWORD_myimap=encrypted_password_here
# XServer Account Configuration (simplified setup)
XSERVER_DOMAIN_mydomain=mydomain.com
XSERVER_USERNAME_mydomain=username
XSERVER_PASSWORD_mydomain=encrypted_password_here
# Gmail APIタイムアウト(デフォルト: 60000ms = 60秒)
GMAIL_TIMEOUT_MS=60000
# IMAP接続タイムアウト(デフォルト: 30000ms = 30秒)
IMAP_CONNECTION_TIMEOUT_MS=30000
# IMAP操作タイムアウト(デフォルト: 60000ms = 60秒)
IMAP_OPERATION_TIMEOUT_MS=60000
# タイムゾーン設定(優先順位:TZ > EMAIL_DEFAULT_TIMEZONE > システム検出 > Asia/Tokyo)
EMAIL_DEFAULT_TIMEZONE=Asia/Tokyo
Google Cloud プロジェクトの作成:
OAuth2の設定:
アクセストークンの取得:
tools/refresh-gmail-tokens.js
スクリプトで自動化されたトークン管理が可能です:
# 全Gmailアカウントの状態確認
node tools/refresh-gmail-tokens.js --check-all
# 特定アカウントのトークン更新
node tools/refresh-gmail-tokens.js <アカウント名>
# 対話式モード
node tools/refresh-gmail-tokens.js
トークン状態の確認:
node tools/refresh-gmail-tokens.js --check-all
出力例:
📊 チェック結果:
✅ 有効: 4/4
❌ 無効: 0/4
期限切れトークンの更新:
node tools/refresh-gmail-tokens.js kentaroh7
新規アカウント追加:
node tools/refresh-gmail-tokens.js
# オプション3を選択: "新規アカウント追加"
invalid_grant
などのOAuth2エラーを識別invalid_grant
エラーが表示された場合:
🔄 再認証が必要なアカウント:
- kentaroh7
- kabucoh
再認証するには: node tools/refresh-gmail-tokens.js <account_name>
提案されたコマンドを実行してトークンを更新してください。
Standard IMAP Server:
IMAP_HOST_myaccount=imap.provider.com
IMAP_PORT_myaccount=993
IMAP_SECURE_myaccount=true
IMAP_USER_myaccount=user@provider.com
IMAP_PASSWORD_myaccount=encrypted_password
XServer (Japanese hosting):
XSERVER_DOMAIN_mydomain=example.com
XSERVER_USERNAME_mydomain=username
XSERVER_PASSWORD_mydomain=encrypted_password
Use the crypto utility to encrypt passwords:
node -e "
const crypto = require('./dist/crypto');
const encrypted = crypto.encrypt('your-password', process.env.EMAIL_ENCRYPTION_KEY);
console.log('Encrypted password:', encrypted);
"
日時指定時のタイムゾーン解釈は以下の優先順位で決定されます:
1640995200
(秒単位)2024-01-01T10:00:00+09:00
, 2024-01-01T01:00:00Z
2024-01-01T10:00:00
(デフォルトタイムゾーンで解釈)2024/01/01
(Gmail API形式)2024/01/01 10:00:00
(デフォルトタイムゾーンで解釈)# システム全体のタイムゾーン設定(最優先)
export TZ=America/New_York
# または、メール専用のタイムゾーン設定
EMAIL_DEFAULT_TIMEZONE=Europe/London
// 異なるタイムゾーンでの検索例
{
"tool": "search_emails",
"arguments": {
"query": "meeting",
"date_after": "2024-01-01T09:00:00+09:00", // JST指定
"date_before": "2024-01-01T18:00:00Z" // UTC指定
}
}
list_accounts
: List all configured accounts with statustest_connection
: Test connection to specific accountsearch_all_emails
: Search across all Gmail/IMAP accountsget_account_stats
: Get statistics for all accountssend_email
: Send emails from Gmail or IMAP accounts (auto-detects account type)archive_email
: Archive emails (Gmail) or move to archive folder (IMAP)list_emails
: List emails from Gmail accountsearch_emails
: Search emails in Gmail accountget_email_detail
: Get detailed email contentget_unread_count
: Get unread email countlist_imap_emails
: List emails from IMAP accountsearch_imap_emails
: Search emails in IMAP accountget_imap_email_detail
: Get detailed email content from IMAPget_imap_unread_count
: Get unread count from IMAP# Run all tests
npm test
# Run timeout prevention tests
npm run test:imap-timeout
# Run health check
npm run health:check
# Test specific IMAP account
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_imap_emails","arguments":{"account_name":"your_account","limit":1}}}' | npx tsx run-email-server.ts
# Test with timeout
gtimeout 10s bash -c 'echo "..." | npx tsx run-email-server.ts && echo "COMMAND_COMPLETED"'
// Search across all accounts
{
"tool": "search_all_emails",
"arguments": {
"query": "invoice",
"accounts": "ALL",
"limit": 10,
"sortBy": "date"
}
}
// List all accounts and their status
{
"tool": "list_accounts",
"arguments": {}
}
// Test specific account connection
{
"tool": "test_connection",
"arguments": {
"account_name": "myaccount"
}
}
// Get comprehensive account statistics
{
"tool": "get_account_stats",
"arguments": {}
}
// Send simple email
{
"tool": "send_email",
"arguments": {
"account_name": "business_gmail",
"to": "recipient@example.com",
"subject": "Meeting Schedule",
"text": "Hi, let's schedule our meeting for next week."
}
}
// Send HTML email with CC/BCC
{
"tool": "send_email",
"arguments": {
"account_name": "business_gmail",
"to": ["recipient1@example.com", "recipient2@example.com"],
"cc": "manager@example.com",
"bcc": "archive@example.com",
"subject": "Project Update",
"html": "<h1>Project Status</h1><p>Current progress: <strong>80%</strong></p>",
"text": "Project Status\nCurrent progress: 80%"
}
}
// Reply to existing email
{
"tool": "send_email",
"arguments": {
"account_name": "business_gmail",
"to": "original_sender@example.com",
"subject": "Re: Original Subject",
"text": "Thank you for your message. I'll get back to you soon.",
"in_reply_to": "original-message-id@gmail.com",
"references": ["thread-ref-1@gmail.com", "thread-ref-2@gmail.com"]
}
}
// Archive single email
{
"tool": "archive_email",
"arguments": {
"account_name": "business_gmail",
"email_id": "email_id_here"
}
}
// Archive multiple emails
{
"tool": "archive_email",
"arguments": {
"account_name": "business_gmail",
"email_id": ["email_id_1", "email_id_2", "email_id_3"]
}
}
npm run build
# Test Gmail connection
node test_gmail.js
# Test IMAP connection
node test_imap.js
# Test complete integration
node test-connection.js
npm run dev
Gmail Authentication Errors:
IMAP Connection Failures:
Password Decryption Errors:
MCP Connection Issues:
Set debug environment variables:
DEBUG=1 npm start
Check application logs for detailed error information:
tail -f logs/mcp-email-server.log
MIT License - see LICENSE file for details.
For issues and questions:
An IMAP Model Context Protocol (MCP) server to expose IMAP operations as tools for AI assistants.
BGG MCP enables AI tools to interact with the BoardGameGeek API.
Query live Gmail data using LLMs via CData's read-only MCP server.
Simple MCP Server to enable a human-in-the-loop workflow in tools like Cline and Cursor.
Enables room-based messaging between multiple agents.
integrates with Bluesky API to query and search feeds and posts.
Send push notifications via the Pushinator service. Requires an API token from your Pushinator account.
An AI voice toolkit with TTS, voice cloning, and video translation, now available as an MCP server for smarter agent integration.
A headless server to get and send emails via the Gmail API, requiring Google API credentials at runtime.
The official ElevenLabs MCP server