msexchange-mcp
Version:
MCP server for Microsoft Exchange/Outlook email operations via Microsoft Graph API
374 lines (289 loc) • 12.8 kB
Markdown
# Exchange MCP Server
[](https://www.npmjs.com/package/msexchange-mcp)
[](https://opensource.org/licenses/MIT)
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
1. Azure AD App Registration with the following API permissions:
- `Mail.ReadWrite`
- `Mail.Send`
- `User.Read`
2. Node.js 18+ installed (compatible with Node.js v23+)
## Installation
### Install from npm
```bash
npm install -g msexchange-mcp
```
### Install from source
1. Clone the repository
2. Install dependencies:
```bash
npm install
```
## Setup
1. Copy `.env.example` to `.env` and fill in your Azure AD credentials:
```bash
cp .env.example .env
```
Or create the file manually with:
```env
AZURE_AD_CLIENT_ID=your-client-id
AZURE_AD_TENANT_ID=your-tenant-id
```
2. Configure your email accounts by creating `accounts.json`:
**For npm installation:**
```bash
# 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": "user1@yourdomain.com",
"displayName": "User One"
}
]
}
EOF
```
**For source installation:**
Edit `src/config/accounts.json` with your account details.
3. If installing from source, build the project:
```bash
npm run build
```
## Azure Key Vault Integration (Optional)
To enable persistent refresh tokens (so you don't have to re-authenticate every hour):
1. **Create Azure Key Vault** (if you don't have one):
```bash
az keyvault create \
--name your-keyvault-name \
--resource-group your-resource-group \
--location your-location
```
2. **Grant yourself access**:
```bash
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}
```
3. **Configure Key Vault** in `.env.keyvault`:
```env
AZURE_KEY_VAULT_URI=https://your-keyvault-name.vault.azure.net/
```
4. **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):
```bash
msexchange-mcp
```
Or with HTTP transport:
```bash
msexchange-mcp --transport httpStream
```
### Integrating 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
1. First, ensure you have your Azure credentials in a `.env` file in your current directory:
```env
AZURE_AD_CLIENT_ID=your-client-id
AZURE_AD_TENANT_ID=your-tenant-id
```
2. Load the credentials and add the server to Claude Code:
```bash
# 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 -y` to 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:
```bash
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-mcp
```
### Verification
After adding the server, verify it's installed:
```bash
claude mcp list
```
You 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:
```bash
npm run dev
```
## Smart Search Guide
### Using the New Smart Email Search
The `smart_email_search` tool automatically handles common search issues:
```bash
# Search with years (automatically handled)
msexchange-mcp smart_email_search --query "tax documents 2024" --user_id user@domain.com
# Search with sender and date range
msexchange-mcp smart_email_search \
--query "invoices from accounting" \
--sender "accounting@company.com" \
--date_start "2025-01-01" \
--date_end "2025-01-31"
# Search with relevance ranking
msexchange-mcp smart_email_search \
--query "project proposal budget" \
--sort "relevance" \
--limit 10
```
### Search Strategy Examples
1. **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
2. **Email-based Searches**:
- Automatically uses sender filtering for accuracy
- Combines with content search when needed
3. **Complex Queries**:
- Automatic fallback strategies
- Smart sanitization of problematic characters
- Clear feedback about search strategy used
## Known Limitations
### Microsoft Graph API Restrictions
1. **Search and OrderBy Incompatibility**: When using the `search` parameter in email queries, the `orderBy` parameter is not supported. This is a limitation of the Microsoft Graph API. The server will automatically ignore `orderBy` when `search` is used.
2. **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.
3. **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
4. **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).
5. **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.
6. **Search Character Restrictions**: The Microsoft Graph API's `$search` parameter doesn't support numbers and some special characters. The smart search tools automatically handle this by converting to filter expressions or sanitizing queries.
7. **Recipient Filtering**: The `toRecipients` filter 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 `smart_email_search` or the new `find_conversation` tool which automatically handle problematic characters.
### Token Limit Exceeded
1. Use `query_emails` with `include_body=false`
2. Use `get_email_content` to fetch individual emails
3. Reduce the `limit` parameter
### Can't Find Emails to/from Someone
Use `find_conversation` tool:
```bash
msexchange-mcp find_conversation \
--with_person "florian" \
--about "insurance"
```
### Need to Handle Different Names
Use aliases:
```bash
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
### 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 person
- `get_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_search` tool 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
- **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_draft` tool
- Added attachments parameter to `send_email` tool
- New `add_attachment_to_draft` tool 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
- **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_search` tool 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](https://github.com/olivierdebeufderijcker/exchange-mcp/issues).
## License
MIT