ms-365-mcp-server

repository·main·Indexed 21 days ago

https://github.com/softeria/ms-365-mcp-server

A Model Context Protocol (MCP) server that provides an interface for LLMs to interact with Microsoft 365 and Office services, including Outlook, Teams, SharePoint, and OneDrive, via the Microsoft Graph API. It features over 300 tools, support for both personal and organization account modes, and an experimental TOON output format to reduce token usage. The server supports Global and China (21Vianet) cloud environments and can be deployed to Azure Container Apps.

Tokens
19.6K
Snippets
46
Records
80
Agent score
71%

What's inside ms-365-mcp-server

  1. Overview of ms-365-mcp-server

    main
    The ms-365-mcp-server is a Model Context Protocol (MCP) server that enables interaction with Microsoft 365 and Microsoft Office services via the Microsoft Graph API. It provides over 300 tools for managing services like Outlook, Teams, SharePoint, and OneDrive.
  2. Pin a specific account for headless deployments

    main

    In headless stdio environments, you can pin the local MSAL cache to a specific Microsoft account to ensure the server always uses the correct identity. This collapses the server into single-account mode (the account parameter is not advertised).

    Pinning Methods

    • By Username: Use --expected-username <username> (case-insensitive).
    • By Home Account ID: Use --expected-home-account-id <homeAccountId> (exact match). Use npx @softeria/ms-365-mcp-server --list-accounts to find this ID.

    Implementation via Environment Variables

    You can also use:

    • MS365_MCP_EXPECTED_USERNAME
    • MS365_MCP_EXPECTED_HOME_ACCOUNT_ID

    Note: CLI flags take precedence over environment variables.

    Important Constraints

    • Bootstrap Process: If the expected account is not in the cache, startup will fail. You must run --login with the pin set first to populate the cache.
    • Cleanup: Use --logout to clear all accounts or --remove-account <id> for specific cleanup.
    # Pin by username
    MS365_MCP_EXPECTED_USERNAME=work@company.com npx @softeria/ms-365-mcp-server --login
    
    # Pin by exact homeAccountId
    npx @softeria/ms-365-mcp-server --expected-home-account-id <homeAccountId> --login
  3. How Azure Key Vault authentication works

    main

    The Key Vault integration utilizes DefaultAzureCredential from the Azure Identity SDK. It attempts authentication using the following methods in order:

    1. Environment variables: AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID.
    2. Managed Identity: Recommended for Azure Container Apps.
    3. Azure CLI credentials: Used for local development.
    4. Visual Studio Code credentials.
    5. Azure PowerShell credentials.

    Note: The @azure/identity and @azure/keyvault-secrets packages are optional dependencies and are only loaded if MS365_MCP_KEYVAULT_URL is configured.

  4. Switch between Personal and Organization Account modes

    main

    The server distinguishes between personal and organization account tools:

    1. Personal Account Tools (Default): Includes Email (Outlook), Calendar, OneDrive Files, Excel, OneNote, To Do Tasks, Planner, Contacts, User Profile, and Search.
    2. Organization Account Tools: Includes Teams & Chats, Online Meetings, Transcripts & Recordings, Attendance Reports, SharePoint Sites & Lists, Shared Mailboxes & Calendars, User Management, Presence, and Virtual Events. Requires the --org-mode flag.

    To enable organization features in Claude Desktop, use the --org-mode argument:

    {
      "mcpServers": {
        "ms365": {
          "command": "npx",
          "args": ["-y", "@softeria/ms-365-mcp-server", "--org-mode"]
        }
      }
    }
  5. Configure audit logging for compliance

    main

    The server includes a structured audit log enabled by default to provide a "who accessed what, when" trail for GDPR, HIPAA, PIPEDA, or SOC 2 compliance.

    • Output: Every tool invocation emits one JSON line to stderr and to ~/.ms-365-mcp-server/logs/audit.log (mode 0o600).
    • Log Schema: { event, request_id, user_principal_name, tool, http_method, status, duration_ms, target_resource?, error_type?, error_code? }.
    • Privacy: To prevent PII leakage, the log only records the target_resource (type and ID) for Graph tools. It never records path parameters, query values, tool parameters, returned content, or full Graph response bodies. Error messages are reduced to error_type and error_code.
    • Disable Logging: Set MS365_MCP_AUDIT_LOG=false to opt-out.
  6. Manage multiple Microsoft accounts

    main

    A single server instance can serve multiple accounts. When multiple accounts are logged in, the server injects an account parameter into every tool call, allowing you to specify which account to use.

    Workflow

    1. Login multiple accounts: Run npx @softeria/ms-365-mcp-server --login for each account you wish to add.
    2. List accounts: Use npx @softeria/ms-365-mcp-server --list-accounts to see configured accounts.
    3. Specify account in tool calls: Pass the email address or MSAL homeAccountId in the account argument.

    Account Selection Behavior

    • Single account: The server auto-selects the account; no account parameter is needed.
    • Multiple accounts (no parameter): The server uses the default account or returns an error listing available accounts.
    • Parameter values: Accepts email addresses (e.g., user@outlook.com) or MSAL homeAccountId.
    // Example tool call specifying an account
    {
      "tool": "list-mail-messages",
      "arguments": {
        "account": "work@company.com"
      }
    }
  7. Configure Microsoft Graph resilience and timeouts

    main

    The server manages Microsoft Graph reliability through several mechanisms:

    • Timeouts: Every call has a fetch timeout. Configure this via MS365_MCP_GRAPH_TIMEOUT_MS (default: 100000 ms).
    • Retries: The server uses retry-with-backoff (default 3 retries) for 429, 503, 504, and network errors. It uses full-jitter exponential backoff and honors the Retry-After header.
      • 429 errors are retried on all methods.
      • 503, 504, and network errors are only retried for idempotent methods.
    • Circuit Breaker: A process-wide circuit breaker opens after 5 consecutive failures and stays open for 30 seconds.
      • Configure threshold via MS365_MCP_GRAPH_CIRCUIT_THRESHOLD.
      • Configure cooldown via MS365_MCP_GRAPH_CIRCUIT_COOLDOWN_MS.
      • Disable the breaker for trusted automation using MS365_MCP_GRAPH_CIRCUIT_DISABLED=true.
  8. Supported Microsoft Cloud Environments

    main

    The server supports two primary cloud environments. By default, it uses the Global environment. To use the China (21Vianet) environment, you must configure the appropriate endpoints.

    CloudDescriptionAuth EndpointGraph API Endpoint
    Global (default)International Microsoft 365login.microsoftonline.comgraph.microsoft.com
    China (21Vianet)Microsoft 365 operated by 21Vianetlogin.chinacloudapi.cnmicrosoftgraph.chinacloudapi.cn
  9. How the External Auth-Cache Command works

    main

    In headless local-MSAL deployments, you can replace the built-in storage with a provider-neutral external command via MS365_MCP_AUTH_CACHE_COMMAND. The server invokes this executable with specific subcommands and keys.

    Protocol v1 Requirements:

    • load <key>: Reads no stdin. Exit 0 with {"found":true,"value":"<value>"} if present, or {"found":false} if missing.
    • save <key>: Receives {"value":"<value>"} on stdin. Must exit 0 only after the value is durably committed.
    • delete <key>: Reads no stdin. Exits 0 regardless of whether the key existed.
    • Keys: The <key> will be either token-cache or selected-account.

    Important Notes:

    • The value must be a real executable path, not a shell command string.
    • Wrappers should handle payloads of at least 256 KB.
    • Any non-zero exit is treated as a storage error.
    • The server does not fall back to other storage methods if this command is set.
    $MS365_MCP_AUTH_CACHE_COMMAND load token-cache
    $MS365_MCP_AUTH_CACHE_COMMAND save token-cache
    $MS365_MCP_AUTH_CACHE_COMMAND delete token-cache
    $MS365_MCP_AUTH_CACHE_COMMAND load selected-account
    $MS365_MCP_AUTH_CACHE_COMMAND save selected-account
    $MS365_MCP_AUTH_CACHE_COMMAND delete selected-account
  10. Post-deployment configuration for Azure Container Apps

    main

    After the initial deployment, you must perform these steps to make the server functional:

    1. Update Entra ID Redirect URI: Retrieve your Container App FQDN (e.g., ms365mcp-app.<suffix>.<region>.azurecontainerapps.io) and add https://<fqdn>/oauth/callback to your app registration's Authentication -> Redirect URIs.
    2. Redeploy with Public Base URL: Run the deployment script again with the -PublicBaseUrl flag so the server advertises the correct URL in OAuth metadata:
      ./deploy.ps1 ... -PublicBaseUrl 'https://<fqdn>'
    3. Verify Installation (Smoke Test):
      • Check OAuth metadata: curl https://<fqdn>/.well-known/oauth-authorization-server (expect 200 OK).
      • Check MCP endpoint: curl -i https://<fqdn>/mcp (expect 401 Unauthorized).
    # Example of redeploying to set the base URL
    ./deploy.ps1 -ResourceGroup 'rg-ms365mcp' -BaseName 'ms365mcp' -PublicBaseUrl 'https://ms365mcp-app.eastus.azurecontainerapps.io'
  11. Access Shared Mailboxes

    main

    To interact with shared mailboxes, ensure the following requirements are met:

    1. Enable Organization Mode: Use the --org-mode flag.
    2. Delegated Permissions: The application must have Mail.Read.Shared or Mail.Send.Shared scopes.
    3. Exchange Permissions: The signed-in user must have been granted explicit access to the shared mailbox by an admin.
    4. Usage: Provide the shared mailbox's email address as the user-id parameter in the relevant shared mailbox tools.

    Discovery: Use the list-users tool to find available shared mailboxes in your organization.

    Example Tool Call: list-shared-mailbox-messages with user-id set to shared-mailbox@company.com.

  12. Configure TOON output format for efficient LLM usage

    main

    The server supports an experimental TOON (Token-Oriented Object Notation) format designed to reduce LLM token usage by 30-60% for uniform array data (e.g., lists of emails or files).

    You can enable TOON format using one of the following methods:

    Via CLI flag:

    npx @softeria/ms-365-mcp-server --toon

    Via Claude Desktop configuration:

    {
      "mcpServers": {
        "ms365": {
          "command": "npx",
          "args": ["-y", "@softeria/ms-365-mcp-server", "--toon"]
        }
      }
    }

    Via environment variable:

    MS365_MCP_OUTPUT_FORMAT=toon npx @softeria/ms-365-mcp-server