msexchange-mcp
v1.10.11
Published
MCP server for Microsoft Exchange/Outlook email operations via Microsoft Graph API
Maintainers
Readme
Exchange MCP Server
A FastMCP server for Microsoft Exchange/Outlook email operations via Microsoft Graph API.
Features
- 🤖 Smart Email Search - Automatically handles numbers, dates, and complex queries
- 🔍 Natural language search with automatic query optimization
- 📧 Multiple search strategies with automatic fallback
- 🎯 Relevance-based result ranking
- 📅 Date range filtering support
- 📎 Enhanced attachment information in search results
- 📁 List and manage email folders
- 🏷️ Add/remove email categories (labels)
- 📤 Send emails and create drafts with attachments
- 🔄 Move emails between folders
- ✅ Mark emails as read/unread
- 💬 Reply to and forward emails
- 🗑️ Delete emails
- 📋 Mail rules management
- 👥 Support for multiple email accounts
- 🔐 Azure Key Vault Integration - Persistent refresh tokens (no more hourly re-authentication!)
Prerequisites
Azure AD App Registration with the following API permissions:
Mail.ReadWriteMail.SendUser.Read
Node.js 18+ installed (compatible with Node.js v23+)
Installation
Install from npm
npm install -g msexchange-mcpInstall from source
- Clone the repository
- Install dependencies:
npm install
Setup
Copy
.env.exampleto.envand fill in your Azure AD credentials:cp .env.example .envOr create the file manually with:
AZURE_AD_CLIENT_ID=your-client-id AZURE_AD_TENANT_ID=your-tenant-id # Optional: For app-only authentication (no user interaction required) AZURE_AD_CLIENT_SECRET=your-client-secretConfigure your email accounts by creating
accounts.json:For npm installation:
# Create config directory in your home folder mkdir -p ~/.config/msexchange-mcp # Create accounts configuration cat > ~/.config/msexchange-mcp/accounts.json << 'EOF' { "accounts": [ { "id": "user1", "email": "[email protected]", "displayName": "User One" } ] } EOFFor source installation: Edit
src/config/accounts.jsonwith your account details.If installing from source, build the project:
npm run build
Authentication Methods
Client Credentials Flow (Recommended for Automation)
New in v1.10.7! Use app-only authentication without any user interaction:
- Add a client secret to your Azure AD app registration
- Set the client secret in your
.envfile:AZURE_AD_CLIENT_SECRET=your-client-secret - Grant admin consent for required permissions in Azure AD
- The MCP will now authenticate automatically without device code prompts!
Device Code Flow (Default)
If no client secret is provided, the MCP uses device code flow which requires:
- Manual authentication via browser every ~1 hour
- Entering a device code at https://microsoft.com/devicelogin
Azure Key Vault Integration (Optional)
To enable persistent refresh tokens (so you don't have to re-authenticate every hour):
Create Azure Key Vault (if you don't have one):
az keyvault create \ --name your-keyvault-name \ --resource-group your-resource-group \ --location your-locationGrant yourself access:
az role assignment create \ --role "Key Vault Secrets Officer" \ --assignee $(az ad signed-in-user show --query id -o tsv) \ --scope /subscriptions/{subscription-id}/resourceGroups/{rg}/providers/Microsoft.KeyVault/vaults/{vault-name}Configure Key Vault in
.env.keyvault:AZURE_KEY_VAULT_URI=https://your-keyvault-name.vault.azure.net/Authentication: The MCP will use your Azure CLI credentials (or Managed Identity if deployed) to access Key Vault automatically.
With Key Vault enabled, your refresh tokens will persist across restarts, eliminating the need for hourly re-authentication!
Usage
Run as MCP Server
Start the server in stdio mode (for use with Claude Code or other MCP clients):
msexchange-mcpOr with HTTP transport:
msexchange-mcp --transport httpStreamIntegrating with Claude Code
To give Claude Code the ability to manage your email, you need to register this server with it. After installing the package globally, you can use the claude command-line tool to add the server.
Quick Setup
First, ensure you have your Azure credentials in a
.envfile in your current directory:AZURE_AD_CLIENT_ID=your-client-id AZURE_AD_TENANT_ID=your-tenant-idLoad the credentials and add the server to Claude Code:
# Load credentials from .env file set -a; source .env; set +a # Add the server to Claude Code claude mcp add exchange-server --scope user \ -e AZURE_AD_CLIENT_ID=$AZURE_AD_CLIENT_ID \ -e AZURE_AD_TENANT_ID=$AZURE_AD_TENANT_ID \ -- npx -y msexchange-mcp
This command:
- Uses
npx -yto automatically download and run the latest version from npm - Passes your Azure credentials securely to the server
- Makes the server available across all your Claude Code sessions
Alternative: Project-Specific Installation
If you prefer to add the server only for a specific project, use --scope local instead:
claude mcp add exchange-server --scope local \
-e AZURE_AD_CLIENT_ID=$AZURE_AD_CLIENT_ID \
-e AZURE_AD_TENANT_ID=$AZURE_AD_TENANT_ID \
-- npx -y msexchange-mcpVerification
After adding the server, verify it's installed:
claude mcp listYou should see exchange-server in the list. You can now start a Claude Code session and use the email tools:
> list my email accounts
Claude will initiate the authentication flow if it's your first time using the tool.
Development
Run in development mode with auto-reload:
npm run devTool Evaluation Harness
Run the token-aware evaluation scenarios (live mode hits Microsoft Graph):
npm exec tsx scripts/evaluate-mail-search.tsGenerate deterministic telemetry using mock fixtures:
MAIL_SEARCH_EVAL_MODE=mock npm exec tsx scripts/evaluate-mail-search.tsEach execution writes a JSON snapshot to logs/evaluations/, including latency, token estimates, and suggestions per scenario.
Mail Search Guide
Using mail_search_context
The mail_search_context tool replaces the previous collection of search tools and keeps responses token-aware:
# Concise summaries (default response_format)
msexchange-mcp mail_search_context --account [email protected] --query "tax documents 2024"
# Lightweight IDs for follow-up actions
msexchange-mcp mail_search_context \
--account [email protected] \
--query "invoices from accounting" \
--response_format ids \
--limit 20
# Detailed payload with sanitized bodies
msexchange-mcp mail_search_context \
--account [email protected] \
--query "project proposal budget" \
--response_format detailed \
--include_body true \
--limit 3Search Strategy Examples
Queries with Numbers (e.g., "invoice 2024"):
- Automatically converted to filter expressions
- Numbers are extracted and searched in subject/body
- No more "character '2' is not valid" errors
Email-based Searches:
- Automatically uses sender filtering for accuracy
- Combines with content search when needed
Complex Queries:
- Automatic fallback strategies
- Smart sanitization of problematic characters
- Clear feedback about search strategy used
Known Limitations
Microsoft Graph API Restrictions
Search and OrderBy Incompatibility: When using the
searchparameter in email queries, theorderByparameter is not supported. This is a limitation of the Microsoft Graph API. The server will automatically ignoreorderBywhensearchis used.Complex Filter Expressions: Some complex filter expressions may not work with
orderBy. If you encounter an error about "restriction or sort order is too complex", the server will automatically retry the query without sorting.Token Limits: When querying emails with full body content, the server automatically limits results to prevent exceeding token limits:
- With body content: Maximum 5 emails per query
- Without body content: Maximum 100 emails per query
- Use the batch query tools for larger requests
Attachment Size: Direct attachment handling is limited to files under 4MB. The tools will validate attachment size and provide clear error messages. Larger attachments require upload sessions (not yet implemented).
Attachment Encoding: All attachments must be provided as Base64 encoded strings. The tools handle MIME type detection automatically but you can specify custom content types.
Search Character Restrictions: The Microsoft Graph API's
$searchparameter doesn't support numbers and some special characters. Themail.search_contexttool automatically sanitizes or falls back to filter expressions when needed.Recipient Filtering: The
toRecipientsfilter uses lambda syntax which can fail with "invalid nodes" errors. The improved tools automatically handle this with fallback strategies.
Troubleshooting Common Issues
"Character 'X' is not valid" Errors
Use mail.search_context or the find_conversation tool which automatically handle problematic characters.
Token Limit Exceeded
- Call
mail.search_contextwithresponse_format=idsor omit bodies - Use
get_email_contentto fetch individual emails - Reduce the
limitparameter or paginate withoffset
Can't Find Emails to/from Someone
Use find_conversation tool:
msexchange-mcp find_conversation \
--with_person "florian" \
--about "insurance"Need to Handle Different Names
Use aliases:
msexchange-mcp find_conversation \
--with_person "Doss" \
--aliases '{"Doss": ["Mads", "Mads Schwartz"]}'Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Changelog
Unreleased
- Replaced legacy search tools (
query_emails,simple_email_search,smart_email_search,query_emails_batch,query_emails_summary,unified_email_search) with the namespacedmail.search_contexttool featuring response_format guardrails and structured payloads.
v1.7.0 (2025-01-16)
- Advanced Query Improvements:
- Fixed "to" parameter filter errors with improved recipient handling
- Automatic token limit recovery with progressive content loading
- Fuzzy name and alias matching support
- Improved error handling for complex filter expressions
- New Tools:
find_conversation- Find all emails between you and another personget_email_content- Fetch individual emails with token-efficient options
- Enhanced Features:
- Better handling of partial email addresses and names
- Automatic fallback strategies for problematic queries
- Support for name aliases (e.g., "Doss" = "Mads")
- Conversation grouping and threading support
v1.6.0 (2025-01-16)
- Major Search Improvements:
- New
smart_email_searchtool that automatically handles problematic queries - Automatic detection and conversion of queries with numbers (e.g., "2024")
- Search query sanitization to remove invalid characters
- Intelligent fallback from search to filter when needed
- Relevance-based result ranking with keyword scoring
- New
- Enhanced Search Features:
- Date range filtering in simple_email_search
- Attachment information in email summaries
- Better error messages with actionable suggestions
- Automatic handling of "character X is not valid" errors
- UX Improvements:
- Clear search strategy logging for transparency
- Detection of years, emails, and keywords in queries
- Smart suggestions when searches fail
- Automatic query optimization behind the scenes
v1.5.0 (2025-01-16)
- Attachment Support Enhancements:
- Added attachments parameter to
create_drafttool - Added attachments parameter to
send_emailtool - New
add_attachment_to_drafttool for adding attachments to existing drafts - Base64 encoding support for all file types
- Automatic MIME type detection with fallback
- 4MB size limit validation with helpful error messages
- Added attachments parameter to
- Improved Response Formats:
- Enhanced JSON responses for draft and email operations
- Added attachment count and status information
v1.4.0 (2025-01-15)
- Major Query Improvements:
- Added intelligent query builder with automatic optimization
- New
simple_email_searchtool for natural language queries - Automatic fallback strategies for complex queries
- Smart filter simplification to handle Graph API limitations
- Post-search filtering for enhanced accuracy
- Enhanced Error Handling:
- Better error messages with actionable suggestions
- Automatic query strategy selection based on complexity
- Graceful degradation for unsupported query combinations
- Performance Optimizations:
- Improved token limit management
- Smarter field selection based on query needs
- Query strategy logging for transparency
v1.3.1 (2025-01-15)
- Fixed Microsoft Graph API restrictions with search and orderBy parameters
- Added automatic fallback when "restriction or sort order is too complex" errors occur
- Improved error handling and user feedback for API limitations
- Added comprehensive tests for query error handling
v1.3.0 (2025-01-15)
- Added comprehensive folder and mail rules management
- Implemented automatic token refresh and proactive token management
- Improved rate limiting and retry logic
v1.0.1 (2025-01-15)
- Fixed Node.js v23 compatibility issue with JSON imports
- Replaced
assert { type: 'json' }syntax with a version-agnostic approach
v1.0.0 (2025-01-15)
- Initial release with full Exchange/Outlook email functionality
- Support for all major email operations via Microsoft Graph API
Support
For issues and feature requests, please use the GitHub issue tracker.
License
MIT
