npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

msexchange-mcp

v1.10.11

Published

MCP server for Microsoft Exchange/Outlook email operations via Microsoft Graph API

Readme

Exchange MCP Server

npm version License: 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

npm install -g msexchange-mcp

Install from source

  1. Clone the repository
  2. Install dependencies:
    npm install

Setup

  1. Copy .env.example to .env and fill in your Azure AD credentials:

    cp .env.example .env

    Or 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-secret
  2. Configure 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"
        }
      ]
    }
    EOF

    For source installation: Edit src/config/accounts.json with your account details.

  3. 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:

  1. Add a client secret to your Azure AD app registration
  2. Set the client secret in your .env file:
    AZURE_AD_CLIENT_SECRET=your-client-secret
  3. Grant admin consent for required permissions in Azure AD
  4. 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):

  1. Create Azure Key Vault (if you don't have one):

    az keyvault create \
      --name your-keyvault-name \
      --resource-group your-resource-group \
      --location your-location
  2. Grant 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}
  3. Configure Key Vault in .env.keyvault:

    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):

msexchange-mcp

Or with HTTP transport:

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:

    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:

    # 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:

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:

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:

npm run dev

Tool Evaluation Harness

Run the token-aware evaluation scenarios (live mode hits Microsoft Graph):

npm exec tsx scripts/evaluate-mail-search.ts

Generate deterministic telemetry using mock fixtures:

MAIL_SEARCH_EVAL_MODE=mock npm exec tsx scripts/evaluate-mail-search.ts

Each 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 3

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 mail.search_context tool automatically sanitizes or falls back to filter expressions when needed.

  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 mail.search_context or the find_conversation tool which automatically handle problematic characters.

Token Limit Exceeded

  1. Call mail.search_context with response_format=ids or omit bodies
  2. Use get_email_content to fetch individual emails
  3. Reduce the limit parameter or paginate with offset

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 namespaced mail.search_context tool 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 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.

License

MIT