### Azure Key Vault Setup Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Provides a step-by-step guide to setting up Azure Key Vault for storing MS365 MCP Server secrets and configuring the server to use them. ```bash # Create Key Vault az keyvault create --name my-mcp-vault --resource-group my-rg # Add secrets az keyvault secret set --vault-name my-mcp-vault --name ms365-mcp-client-id --value "app-client-id" az keyvault secret set --vault-name my-mcp-vault --name ms365-mcp-tenant-id --value "app-tenant-id" # Grant access (managed identity in Container Apps) PRINCIPAL_ID=$(az containerapp show --name my-app --resource-group my-rg --query identity.principalId -o tsv) az keyvault set-policy --name my-mcp-vault --object-id $PRINCIPAL_ID --secret-permissions get list # Configure server MS365_MCP_KEYVAULT_URL=https://my-mcp-vault.vault.azure.net npx @softeria/ms-365-mcp-server ``` -------------------------------- ### Quick Test Setup for Open WebUI Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Sets up Open WebUI and the MCP server for a quick test. This includes running Open WebUI in Docker and starting the MCP server in HTTP mode. ```bash docker run -d -p 8080:8080 \ -e WEBUI_AUTH=false \ -e OPENAI_API_KEY \ ghcr.io/open-webui/open-webui:main npx @softeria/ms-365-mcp-server --http ``` -------------------------------- ### Start MicrosoftGraphServer Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/entry-point.md Starts the MCP server, connecting it to either stdio or an Express HTTP server depending on the configured transport. ```typescript await server.start(); ``` -------------------------------- ### MicrosoftGraphServer Start Method Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Starts the MCP server on the configured transport (stdio or HTTP). ```typescript async start(): Promise ``` -------------------------------- ### Multi-Account Routing Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Example JSON payload demonstrating how to specify a particular account for a tool call when multiple Microsoft accounts are cached. ```json { "name": "list-mail-messages", "arguments": { "account": "work@company.com", "$top": 10 } } ``` -------------------------------- ### Initialize MicrosoftGraphServer Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Example of calling the initialize method on a MicrosoftGraphServer instance. ```typescript await server.initialize('0.1.0'); ``` -------------------------------- ### Instantiate MicrosoftGraphServer Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Example of creating a new instance of the MicrosoftGraphServer class. ```typescript const server = new MicrosoftGraphServer(authManager, args); ``` -------------------------------- ### Start HTTP Server on All Interfaces and Specific Port Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Starts the MS-365 MCP Server using an HTTP transport, binding to all interfaces on a specified port. ```bash npx @softeria/ms-365-mcp-server --http :3000 ``` -------------------------------- ### MCP Server Startup Sequence Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Illustrates the typical startup sequence for the MCP server, including argument parsing, AuthManager creation, server initialization, and starting the server. ```typescript // 1. Parse CLI arguments const args = parseArgs(); // 2. Create AuthManager const authManager = await AuthManager.create(effectiveScopes, {...}); await authManager.loadTokenCache(); // 3. Create and initialize server const server = new MicrosoftGraphServer(authManager, args); await server.initialize(version); // 4. Start listening await server.start(); ``` -------------------------------- ### Initialize GraphClient Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/graph-client.md Instantiate the GraphClient with authentication manager, secrets, and desired output format. This is typically done in the server setup. ```typescript const graphClient = new GraphClient( authManager, secrets, outputFormat // 'json' or 'toon' ); ``` -------------------------------- ### Start HTTP Server on Specific Host and Port Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Starts the MS-365 MCP Server using an HTTP transport, binding to a specific host and port. ```bash npx @softeria/ms-365-mcp-server --http localhost:3000 ``` -------------------------------- ### MicrosoftGraphServer Lifecycle Methods Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Details the constructor and lifecycle methods for initializing and starting the MicrosoftGraphServer. ```APIDOC ## Class: MicrosoftGraphServer ### Constructor Initializes server with authentication manager and command options. ```typescript constructor(authManager: AuthManager, options?: CommandOptions) ``` #### Parameters - **authManager** (`AuthManager`) - Required - Authenticated AuthManager instance - **options** (`CommandOptions`) - Optional - CLI options from `parseArgs()` **Example**: ```typescript const server = new MicrosoftGraphServer(authManager, args); ``` ### `initialize` Method Prepares server for startup: loads secrets, detects multi-account mode, initializes GraphClient. ```typescript async initialize(version: string): Promise ``` #### Parameters - **version** (`string`) - Server version (e.g., "1.0.0") **Throws**: Error if secrets cannot be loaded or configuration is invalid **Behavior**: Loads app secrets, detects multi-account mode, caches account names, initializes GraphClient, validates OBO flow, and creates MCP server with tools if not using HTTP. **Example**: ```typescript await server.initialize('0.1.0'); ``` ### `start` Method Starts the server on configured transport (stdio or HTTP). ```typescript async start(): Promise ``` **Throws**: Error if transport fails to start **Behavior**: Connects to stdin/stdout for Stdio Transport or starts an Express.js server for HTTP Transport, registering OAuth endpoints and requiring Bearer token authentication. **Example**: ```typescript await server.start(); ``` ``` -------------------------------- ### Start MCP Server with HTTP and Port Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Starts the MS 365 MCP Server in HTTP mode on a specified port, enabling OAuth capabilities and endpoints for MCP clients. ```bash npx @softeria/ms-365-mcp-server --http 3000 ``` -------------------------------- ### Use Multiple Presets Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Combine multiple presets by separating them with a comma. This example enables tools for both Outlook and contacts. ```bash npx @sosoria/ms-365-mcp-server --preset outlook,contacts ``` -------------------------------- ### Start HTTP Server on a Specific Port Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Starts the MS-365 MCP Server using an HTTP transport on all available interfaces, listening on the specified port. ```bash npx @softeria/ms-365-mcp-server --http 8080 ``` -------------------------------- ### TOON Output Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/README.md Experimental Token-Oriented Object Notation (TOON) for reduced token usage. Offers 30-60% token reduction. ```text value[1]{id,subject}: "123",Meeting ``` -------------------------------- ### Start HTTP Server on Default Port Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Starts the MS-365 MCP Server using an HTTP transport on all available interfaces and the default port (3000). ```bash npx @softeria/ms-365-mcp-server --http ``` -------------------------------- ### Local Development Setup Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Adds an MCP tool for local development using the project's source code. Ensure you run 'npm run build' after code changes. ```bash # From the project directory claude mcp add ms -- npx tsx src/index.ts --org-mode ``` -------------------------------- ### Example GraphClient Workflow Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/graph-client.md A complete workflow demonstrating how to create a GraphClient, make a request to retrieve messages, and process the response, including error handling. ```typescript // 1. Create client const graphClient = new GraphClient(authManager, secrets, 'json'); // 2. Make request const response = await graphClient.graphRequest('/me/messages', { method: 'GET' }); // 3. Process response if (response.isError) { console.error('Error:', response.content[0].text); } else { const data = JSON.parse(response.content[0].text); console.log(`Found ${data.value.length} messages`); } ``` -------------------------------- ### EndpointConfig Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/types.md An example JSON object illustrating the structure of an EndpointConfig. Shows how to define a Graph API endpoint for listing mail messages. ```json { "pathPattern": "/me/messages", "method": "get", "toolName": "list-mail-messages", "presets": ["mail", "outlook", "personal"], "scopes": ["Mail.Read"], "llmTip": "Use $select to limit fields..." } ``` -------------------------------- ### Complete OAuth Flow Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md This comprehensive bash script illustrates the full OAuth 2.0 authorization code flow for the MS 365 MCP Server, including client registration, PKCE generation, authorization, and token exchange. ```bash # 1. Client registers RESULT=$(curl -s -X POST http://localhost:3000/register \ -H "Content-Type: application/json" \ -d '{ "client_name": "My Client", "redirect_uris": ["http://localhost:6274/callback"] }') CLIENT_ID=$(echo $RESULT | jq -r .client_id) # 2. Client generates PKCE pair VERIFIER=$(openssl rand -base64 32 | tr -d "=\n" | cut -c1-128) CHALLENGE=$(echo -n "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr -d "=\n") # 3. Client initiates authorization AUTH_URL="http://localhost:3000/authorize?client_id=$CLIENT_ID&redirect_uri=http://localhost:6274/callback&state=xyz&code_challenge=$CHALLENGE&code_challenge_method=S256&scope=Mail.Read%20Calendars.Read" # User visits AUTH_URL, logs in, returns with code # 4. Client exchanges code for token TOKEN=$(curl -s -X POST http://localhost:3000/token \ -H "Content-Type: application/json" \ -d "{ \"grant_type\": \"authorization_code\", \"code\": \"$CODE_FROM_REDIRECT\", \"redirect_uri\": \"http://localhost:6274/callback\", \"code_verifier\": \"$VERIFIER\" }") ACCESS_TOKEN=$(echo $TOKEN | jq -r .access_token) # 5. Client calls /mcp with token curl -s -X POST http://localhost:3000/mcp \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "list-mail-messages", "arguments": {"$top": 10} }, "id": 1 }' | jq . ``` -------------------------------- ### JSON Output Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/README.md Standard JSON output format with pretty-printing. This is the default output format. ```json {"value": [{"id": "123", "subject": "Meeting"}]} ``` -------------------------------- ### ScopeDiagnostics Example Usage Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/types.md An example demonstrating the usage of `buildAllowedScopeDiagnostics` and the structure of the returned ScopeDiagnostics object. Shows how to analyze scopes based on CLI options. ```typescript const diag = buildAllowedScopeDiagnostics({ orgMode: false, allowedScopes: 'Mail.Read' }); // Returns: // { // permissions: ['Mail.Read'], // toolPermissions: ['Mail.Read', 'Mail.ReadWrite', 'Calendars.Read', ...], // disabledTools: [ // { toolName: 'send-mail', requiredScopes: ['Mail.Send'], missingScopes: ['Mail.Send'] } // ], // missingAllowedScopesForTools: ['Mail.Send', 'Calendars.Read', ...] // } ``` -------------------------------- ### Example Output for --list-permissions Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/entry-point.md Shows the JSON output structure when the `--list-permissions` flag is used, detailing the server's operational mode, read-only status, scope filters, and permission diagnostics. ```json { "mode": "org", "readOnly": false, "filter": "mail", "permissions": ["Mail.Read", "Mail.ReadWrite", "User.Read"], "toolPermissions": ["Mail.Read", "Mail.ReadWrite", "Calendars.Read", ...], "allowedScopes": ["Mail.Read", "Mail.ReadWrite"], "disabledTools": [ { "toolName": "list-calendar-events", "requiredScopes": ["Calendars.Read"], "missingScopes": ["Calendars.Read"] } ], "missingAllowedScopesForTools": ["Calendars.Read"], "extraAllowedScopesNotUsedByTools": [] } ``` -------------------------------- ### Example JSON Response Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/graph-client.md Illustrates the structure of a standard JSON response from the GraphClient, including an array of items. ```json { "value": [ { "id": "123", "displayName": "Meeting", "start": "2026-06-07T10:00:00Z" } ] } ``` -------------------------------- ### Example TOON Response Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/graph-client.md Shows the compact TOON (Token-Oriented Object Notation) format for GraphClient responses, offering token reduction. ```text value[1]{"id","displayName","start"}: "123",Meeting,2026-06-07T10:00:00Z ``` -------------------------------- ### Example: Effective Scopes Calculation Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/entry-point.md Illustrates how different CLI flags like `--org-mode`, `--preset`, `--allowed-scopes`, and `--read-only` influence the final set of effective authentication scopes. ```text --org-mode + --preset mail → Mail.Read, Mail.ReadWrite, User.Read, offline_access --allowed-scopes 'Mail.Read' → only Mail.Read (Mail.ReadWrite filtered) --read-only → excludes Mail.Send, Mail.ReadWrite, etc. ``` -------------------------------- ### Specify Account in Tool Call Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Example of how to specify a particular account for a tool call by including the 'account' parameter in the request. ```json { "tool": "list-mail-messages", "arguments": { "account": "work@company.com" } } ``` -------------------------------- ### CLI Flag Precedence Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/README.md Demonstrates how CLI flags take precedence over environment variables for configuration. Use CLI flags for the highest precedence settings. ```bash # CLI flag takes precedence npx @softeria/ms-365-mcp-server --org-mode # Enables org mode MS365_MCP_ORG_MODE=false ... # (ignored; CLI wins) # Env var used if CLI not set MS365_MCP_ORG_MODE=true npx @softeria/ms-365-mcp-server ``` -------------------------------- ### Initiate Device Code Flow Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/auth-manager.md Starts the device code flow for interactive authentication. Use this when a browser is not available or preferred. ```typescript async acquireTokenByDeviceCode(hack?: (message: string) => void): Promise ``` ```typescript const token = await authManager.acquireTokenByDeviceCode(); console.log('Token acquired:', token); ``` -------------------------------- ### Dynamic Client Registration Request Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Example request body for dynamically registering an OAuth client via the /register endpoint. ```json { "client_name": "My MCP Client", "redirect_uris": ["http://localhost:6274/callback"], "response_types": ["code"], "grant_types": ["authorization_code", "refresh_token"], "token_endpoint_auth_method": "none" } ``` -------------------------------- ### Package.json Bin Entry for CLI Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/entry-point.md Defines the 'ms-365-mcp-server' command in the package.json 'bin' field, allowing it to be run via npx or as a globally installed command. ```json { "bin": { "ms-365-mcp-server": "dist/index.js" } } ``` -------------------------------- ### Account Pinning via Environment Variable Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/README.md Configure the server to start only if a specific Microsoft account is cached. Prevents silent fallback to an incorrect user. ```bash MS365_MCP_EXPECTED_USERNAME=automation@company.com npx @softeria/ms-365-mcp-server ``` -------------------------------- ### Pin Minimum Replicas for Container App Source: https://github.com/softeria/ms-365-mcp-server/blob/main/examples/azure-container-apps/README.md Configures the minimum and maximum number of replicas for a container app to eliminate cold starts and manage scaling. ```bash az containerapp update -n -app -g --min-replicas 1 --max-replicas 5 ``` -------------------------------- ### PKCE Flow Setup for MCP Client Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md This bash snippet demonstrates how an MCP client can generate a PKCE verifier and challenge pair. These are used to enhance the security of the OAuth 2.0 authorization code flow. ```bash # Client generates PKCE pair code_verifier=$(openssl rand -base64 32 | tr -d "=\n" | cut -c1-128) code_challenge=$(echo -n "$code_verifier" | openssl dgst -sha256 -binary | base64 | tr -d "=\n") ``` -------------------------------- ### TOON Output Format Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md This is an experimental TOON (Token-Oriented Object Notation) output format, designed for efficient LLM token usage. It is beneficial for uniform array data and cost-sensitive applications. ```text value[1]{id,displayName,mail,jobTitle}: "1",Alice Johnson,alice@example.com,Software Engineer ``` -------------------------------- ### cURL Example: Token Refresh Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md This cURL command demonstrates how to refresh an access token using the /token endpoint with a JSON payload. ```bash curl -X POST http://localhost:3000/token \ -H "Content-Type: application/json" \ -d '{ "grant_type": "refresh_token", "refresh_token": "0.AVAAu..." }' | jq . ``` -------------------------------- ### MCP Protocol Request - Tool Call Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md An example of an MCP protocol request for calling a tool. This demonstrates the structure for sending tool execution requests to the server. ```JSON { "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "list-mail-messages", "arguments": { "$top": 10 } }, "id": 1 } ``` -------------------------------- ### OPTIONS Request Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md This curl command demonstrates an OPTIONS request to the /mcp endpoint, showing the expected HTTP 200 OK response and CORS headers. It's used for preflight requests in CORS. ```bash curl -X OPTIONS http://localhost:3000/mcp -v # HTTP/1.1 200 OK # Access-Control-Allow-Origin: http://localhost:3000 # ... ``` -------------------------------- ### Dynamic Client Registration Response Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Example successful response (HTTP 201) for the /register endpoint, containing details of the newly registered OAuth client. ```json { "client_id": "mcp-client-1234567890", "client_id_issued_at": 1234567890, "redirect_uris": ["http://localhost:6274/callback"], "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"], "token_endpoint_auth_method": "none", "client_name": "My MCP Client" } ``` -------------------------------- ### Standard OAuth Authorization Flow with cURL Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md Initiate the standard OAuth 2.0 authorization code flow using cURL. This example demonstrates passing required parameters like redirect_uri and state. ```bash curl -G "http://localhost:3000/authorize" \ -d "client_id=mcp-client-123" \ -d "redirect_uri=http://localhost:6274/callback" \ -d "scope=Mail.Read Calendars.Read" \ -d "state=xyz" \ -d "response_type=code" # Redirects to: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?... ``` -------------------------------- ### Entry Point and Startup Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/README.md Details the main executable (`src/index.ts`), CLI argument parsing, secrets management, error handling, and early-exit commands. ```APIDOC ## Entry Point and Startup ### Description Covers the main executable file (`src/index.ts`) which orchestrates the server's startup sequence. It includes functionality for parsing command-line arguments, managing secrets, handling errors, and supporting early-exit commands such as `--login`, `--logout`, and `--list-accounts`. The documentation also outlines the different initialization phases the server undergoes. ### Features - Main executable (`src/index.ts`) - CLI argument parsing - Secrets management - Error handling - Early-exit commands: `--login`, `--logout`, `--list-accounts` - Initialization phases ``` -------------------------------- ### Deploy MS365 MCP Server in Production with Docker Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Run the MS365 MCP Server in a Docker container for production deployment. This example sets Azure Key Vault and public URL environment variables, and configures HTTP listening. ```bash docker run \ -e MS365_MCP_KEYVAULT_URL=https://my-vault.vault.azure.net \ -e MS365_MCP_PUBLIC_URL=https://mcp.company.com \ ms-365-mcp-server:latest \ --http 0.0.0.0:3000 \ --org-mode ``` -------------------------------- ### MCP Protocol (HTTP GET) Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md Handles MCP protocol communication using HTTP GET requests. ```APIDOC ## GET /mcp ### Description MCP protocol communication (HTTP GET). ### Method GET ### Endpoint /mcp ### Auth Required Bearer token ``` -------------------------------- ### MicrosoftGraphServer Initialize Method Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Prepares the server for startup by loading secrets, detecting multi-account mode, and initializing the GraphClient. ```typescript async initialize(version: string): Promise ``` -------------------------------- ### OAuth Error Response Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md An example of an error response from the OAuth token endpoint, detailing the error type and description. ```json { "error": "invalid_grant", "error_description": "AADSTS65001: User or admin has not consented to use the application...", "error_codes": [65001] } ``` -------------------------------- ### List Available Presets Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Execute the --list-presets command to display all available preset tool categories and exit the server. This is useful for understanding configuration options. ```bash npx @softeria/ms-365-mcp-server --list-presets ``` -------------------------------- ### Login First Account (Device Code Flow) Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Initiates the device code flow for logging in the first Microsoft account. Follow the on-screen prompts to authenticate. ```bash # Login first account (device code flow) npx @softeria/ms-365-mcp-server --login # Follow the device code prompt, sign in as personal@outlook.com ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/softeria/ms-365-mcp-server/blob/main/docs/deployment.md Builds the Docker image for the ms-365-mcp-server and runs it with environment variables for configuration. Ensure to replace placeholders with your actual values. ```bash # Build the image docker build -t ms-365-mcp-server . # Run with environment variables docker run -p 3000:3000 \ -e MS365_MCP_CLIENT_ID=your-client-id \ -e MS365_MCP_TENANT_ID=your-tenant-id \ -e MS365_MCP_CLIENT_SECRET=your-secret \ -e MS365_MCP_ORG_MODE=true \ ms-365-mcp-server \ --http 3000 --org-mode ``` -------------------------------- ### getUseInteractiveAuth Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/auth-manager.md Gets the current interactive auth setting. ```APIDOC ## getUseInteractiveAuth ### Description Gets current interactive auth setting. ### Method ``` (): boolean ``` ``` -------------------------------- ### Migrate from --base-url to --public-url Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Demonstrates the transition from the deprecated `--base-url` CLI option to the recommended `--public-url` for specifying the server's public-facing URL. ```bash # Old (still works for compatibility) npx @softeria/ms-365-mcp-server --base-url https://mcp.example.com # New npx @softeria/ms-365-mcp-server --public-url https://mcp.example.com ``` -------------------------------- ### Use Mail Tool Preset Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Load only the mail-related tools to reduce initial connection overhead. Use `--list-presets` to see all available presets. ```bash npx @softeria/ms-365-mcp-server --preset mail npx @softeria/ms-365-mcp-server --list-presets # See all available presets ``` -------------------------------- ### Get Cloud Endpoints Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/utilities.md Returns OAuth and Graph API endpoints for a specified cloud environment (Global or China). ```typescript function getCloudEndpoints(cloudType: CloudType): { authority: string; // OAuth authority URL graphApi: string; // Graph API base URL } ``` ```typescript const endpoints = getCloudEndpoints('global'); // { authority: 'https://login.microsoftonline.com', graphApi: 'https://graph.microsoft.com' } ``` -------------------------------- ### Login Second Account (Device Code Flow) Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Initiates the device code flow for logging in a second Microsoft account. Follow the on-screen prompts to authenticate. ```bash # Login second account npx @softeria/ms-365-mcp-server --login # Follow the device code prompt, sign in as work@company.com ``` -------------------------------- ### Configuration Options Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/README.md Details available CLI options, environment variables, Azure Key Vault integration, token storage paths, and OAuth server configuration. ```APIDOC ## Configuration Options ### Description This section provides a comprehensive overview of the configuration options for the MS-365 MCP Server. It details the available command-line interface (CLI) options with their descriptions, the precedence of environment variables, and how to integrate with Azure Key Vault for secure secret management. It also covers token storage paths and OAuth server configuration, including example configurations for common scenarios. ### Topics - CLI options - Environment variables and precedence - Azure Key Vault integration - Token storage paths - OAuth server configuration - Example configurations ``` -------------------------------- ### graphRequest Method Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/graph-client.md Handles Graph API requests and formats the response into the MCP Tool result structure. ```typescript async graphRequest( endpoint: string, options?: GraphRequestOptions ): Promise ``` ```typescript const response = await graphClient.graphRequest('/me/messages', { method: 'GET' }); console.log(response.content[0].text); // JSON string ``` -------------------------------- ### Create MCP Server Instance Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Creates and initializes an McpServer instance, registering authentication, Graph, or discovery tools based on configuration. ```typescript private createMcpServer(): McpServer ``` -------------------------------- ### OAuth Authorization Endpoint Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md Initiates the OAuth authorization flow with a challenge. This endpoint is used by the client to start the authorization process. ```APIDOC ## GET /authorize ### Description Initiates the OAuth authorization flow by providing a challenge to the client. The client then uses this challenge to generate a code verifier. ### Method GET ### Endpoint /authorize ### Parameters #### Query Parameters - **redirect_uri** (string) - Required - The URI to redirect to after authorization. - **state** (string) - Required - An opaque value used to maintain state between the request and callback. - **code_challenge** (string) - Required - The challenge generated by the client for PKCE. - **code_challenge_method** (string) - Required - The method used to generate the code challenge (e.g., S256). ``` -------------------------------- ### Run Server with BYOT Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Provide a pre-existing OAuth token to bypass interactive authentication flows. Token refresh is not handled by the server. ```bash MS365_MCP_OAUTH_TOKEN=your_oauth_token npx @softeria/ms-365-mcp-server ``` -------------------------------- ### Create and Initialize MicrosoftGraphServer Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/entry-point.md Instantiates the MicrosoftGraphServer, loads secrets, detects multi-account mode, initializes the GraphClient, and validates OBO configuration if enabled. ```typescript const server = new MicrosoftGraphServer(authManager, args); await server.initialize(version); ``` -------------------------------- ### Enable Dynamic Tool Discovery Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Activate experimental dynamic tool discovery with the --discovery flag. This loads tools on demand, which is beneficial for cost-sensitive applications or long sessions. ```bash npx @softeria/ms-365-mcp-server --discovery ``` -------------------------------- ### Error Handling during Startup Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/entry-point.md Wraps the main application logic in a try-catch block to log any startup errors and exit the process with a status code of 1. ```typescript try { await main(); } catch (error) { const message = error instanceof Error ? error.message : String(error); logger.error(`Startup error: ${message}`); console.error(message); process.exit(1); } ``` -------------------------------- ### MCP Protocol Endpoints Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md Provides endpoints for the MCP protocol, supporting tool invocation and discovery via both GET and POST requests. ```APIDOC ## GET /mcp and POST /mcp ### Description MCP protocol endpoints for tool invocation and discovery. Both GET and POST methods are supported for compatibility. ### Method GET, POST ### Endpoint /mcp ### Parameters #### Request Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Content-Type** (string) - Required for POST - `application/json`. - **mcp-protocol-version** (string) - Optional - Specifies the MCP protocol version. ### Request Body (POST) - **jsonrpc** (string) - Required - The JSON-RPC version, typically "2.0". - **method** (string) - Required - The method to invoke (e.g., `tools/call`). - **params** (object) - Required - Parameters for the method. - **name** (string) - Required - The name of the tool or method to call. - **arguments** (object) - Optional - Arguments for the tool/method. - **id** (integer or string) - Required - The request ID. ### Response #### Success Response (200 OK) - **jsonrpc** (string) - The JSON-RPC version, typically "2.0". - **result** (object) - The result of the method execution. - **content** (array) - An array of content items returned by the tool. - **type** (string) - The type of content (e.g., `text`). - **text** (string) - The actual content, often a JSON string. - **id** (integer or string) - The request ID. ### Response Example ```json { "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "[{"id":"123","subject":"Meeting"}]" } ] }, "id": 1 } ``` ``` -------------------------------- ### Get Selected Account ID Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/auth-manager.md Retrieves the MSAL homeAccountId of the currently selected account. Returns null if no account is currently selected. ```typescript getSelectedAccountId(): string | null ``` ```typescript const selectedId = authManager.getSelectedAccountId(); ``` -------------------------------- ### Configure and Use Logger Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/utilities.md Demonstrates how to configure and use the Winston-based logger. Logs can be set to different levels (error, warn, info, http, debug, verbose) and output to a file or console. ```typescript import logger from './logger.js'; logger.info('Message', { key: 'value' }); logger.error('Error message', error); logger.debug('Debug only at debug level'); ``` -------------------------------- ### makeRequest Method Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/graph-client.md Performs a low-level HTTP request to the Microsoft Graph API, including token injection and response parsing. ```typescript async makeRequest( endpoint: string, options?: GraphRequestOptions ): Promise ``` ```typescript const messages = await graphClient.makeRequest('/me/messages', { method: 'GET' }); ``` -------------------------------- ### Get Default Client ID Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/utilities.md Returns the built-in Azure app client ID for a given cloud type. Used when MS365_MCP_CLIENT_ID is not configured. ```typescript function getDefaultClientId(cloudType: CloudType): string ``` -------------------------------- ### Server Command-Line Options Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Use these flags to configure the MS365 MCP server's behavior, such as logging verbosity, transport mode, and authentication settings. ```bash -v Enable verbose logging --read-only Start server in read-only mode, disabling write operations --http [port] Use Streamable HTTP transport instead of stdio (optionally specify port, default: 3000) Starts Express.js server with MCP endpoint at /mcp --enable-auth-tools Enable login/logout tools when using HTTP mode (disabled by default in HTTP mode) --no-dynamic-registration Disable OAuth Dynamic Client Registration (enabled by default in HTTP mode) --enabled-tools Filter tools using regex pattern (e.g., "excel|contact" to enable Excel and Contact tools) --preset Use preset tool categories (comma-separated). See "Tool Presets" section above --list-presets List all available presets and exit --toon (experimental) Enable TOON output format for 30-60% token reduction --discovery Dynamic tool discovery: loads tools on demand to reduce initial token usage (see "Dynamic Tool Discovery" above) --public-url Public base URL for OAuth when behind a reverse proxy (see Open WebUI section and docs/deployment.md) ``` -------------------------------- ### Initiate Interactive Browser Flow Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/auth-manager.md Starts an interactive OAuth flow using the system browser. This is suitable for typical web application authentication scenarios. ```typescript async acquireTokenInteractive(hack?: (message: string) => void): Promise ``` ```typescript const token = await authManager.acquireTokenInteractive(); ``` -------------------------------- ### Test Current Authentication Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Verifies the current authentication status without starting the server. Returns success or failure along with user details if authenticated. ```bash npx @softeria/ms-365-mcp-server --verify-login ``` -------------------------------- ### MicrosoftGraphServer Constructor Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md Initializes the server with an authentication manager and optional command-line options. ```typescript constructor(authManager: AuthManager, options?: CommandOptions) ``` -------------------------------- ### buildBM25Index Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/utilities.md Creates a searchable BM25 index from a list of tools, where each tool has a name and description. ```APIDOC ## buildBM25Index ### Description Creates a searchable index from a list of tools. ### Module `src/lib/bm25.ts` ### Function Signature ```typescript function buildBM25Index(tools: Array<{ name: string; description: string; }>): BM25Index ``` ### Parameters #### Path Parameters - **tools** (Array<{ name: string; description: string; }>) - Required - An array of tool objects, each with a name and description. ### Returns - **BM25Index** - The generated BM25 index. ``` -------------------------------- ### getSharedBreaker Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/utilities.md Gets or creates a shared circuit breaker instance for the server. This breaker tracks failures across all requests to implement circuit breaking logic. ```APIDOC ## getSharedBreaker ### Description Gets or creates shared circuit breaker. ### Method ```typescript function getSharedBreaker(): CircuitBreaker ``` ### Response #### Success Response - (CircuitBreaker) - The shared circuit breaker instance. ### Behavior - One breaker per server instance - Tracks failures across all requests - Opens after N consecutive failures - Reopens after timeout (half-open state) ### Configuration - Failure threshold: 5 consecutive errors - Recovery timeout: 60 seconds ``` -------------------------------- ### MicrosoftGraphServer Class Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/README.md Implements the MCP server, handling initialization, startup, and communication through stdio or HTTP transports. Manages tool registration and multi-account mode detection. ```APIDOC ## MicrosoftGraphServer Class ### Description This class is the core implementation of the MCP server. It manages the server's initialization, startup sequence, and communication protocols. The server supports two primary transports: standard input/output (stdio) and HTTP. It also handles the registration of tools and their schemas, and detects when the server is operating in multi-account mode. ### Features - Initialization and startup - Transports: stdio and HTTP - Tool registration and schemas - Multi-account mode detection ``` -------------------------------- ### Local Development Configuration Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Manual configuration for Claude Desktop to connect to the MS 365 MCP server for local development. Requires building the project first. ```json { "mcpServers": { "ms365": { "command": "node", "args": ["/absolute/path/to/ms-365-mcp-server/dist/index.js", "--org-mode"] } } } ``` -------------------------------- ### CORS Response Headers Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md These are example response headers for CORS requests, indicating allowed origins, methods, and headers. They are crucial for enabling cross-domain communication. ```text Access-Control-Allow-Origin: Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, mcp-protocol-version ``` -------------------------------- ### cURL Example: Authorization Code Exchange Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md This cURL command demonstrates how to perform an authorization code exchange with the /token endpoint using JSON payload. ```bash curl -X POST http://localhost:3000/token \ -H "Content-Type: application/json" \ -d '{ "grant_type": "authorization_code", "code": "M.R3_BAY...", "redirect_uri": "http://localhost:6274/callback", "code_verifier": "..." }' | jq . ``` -------------------------------- ### Import Version from './version.js' Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/entry-point.md Imports the version string from the local version file, used for server initialization and metadata. ```typescript import { version } from './version.js'; ``` -------------------------------- ### Get Shared Circuit Breaker Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/utilities.md Retrieves or creates a shared circuit breaker instance for the server. It tracks failures and opens/reopens based on configured thresholds and timeouts. ```typescript function getSharedBreaker(): CircuitBreaker ``` -------------------------------- ### Get Current Account Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/auth-manager.md Retrieves the currently active account. It prioritizes configured accounts, then previously selected accounts, and finally the first available cached account. ```typescript async getCurrentAccount(): Promise ``` ```typescript const account = await authManager.getCurrentAccount(); console.log(`Using account: ${account?.username}`); ``` -------------------------------- ### CLI Login for Device Code Flow Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Initiates the Device Code Flow for authentication via the command line. Follow the provided URL and code prompt in your terminal. ```bash npx @softeria/ms-365-mcp-server --login ``` -------------------------------- ### Configure Limited Tool Scope for Cost Efficiency Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Run the MS365 MCP Server with a limited set of tools and scopes to reduce costs. This configuration uses the 'mail' preset, specifies allowed scopes, and enables TOON format and dynamic discovery. ```bash npx @softeria/ms-365-mcp-server \ --preset mail \ --allowed-scopes 'Mail.Read User.Read' \ --toon \ --discovery ``` -------------------------------- ### TypeScript Error Message Check Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/README.md Demonstrates how to check for specific error types by inspecting the message string. Useful for handling scope or permission-related issues. ```typescript if (error.message.includes('scope') || error.message.includes('permission')) { // Handle scope error } ``` -------------------------------- ### Run Verification Script Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md Execute this command to ensure all code quality requirements are met before contributing. ```bash npm run verify ``` -------------------------------- ### TypeScript Error Handling Example Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/README.md Standard JavaScript Error objects are thrown for all error conditions. Error detection is performed by inspecting the error message content. ```typescript throw new Error('Microsoft Graph API error: 403 Forbidden - Insufficient permissions') ``` -------------------------------- ### Enable TOON Format via Claude Desktop Configuration Source: https://github.com/softeria/ms-365-mcp-server/blob/main/README.md To enable the TOON format within Claude Desktop, configure the 'mcpServers' setting in your JSON configuration file. ```json { "mcpServers": { "ms365": { "command": "npx", "args": ["-y", "@softeria/ms-365-mcp-server", "--toon"] } } } ``` -------------------------------- ### Get Active Resources Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/utilities.md Returns a list of currently open handles and timers. This is used in crash logs to help diagnose issues related to hanging connections or processes. ```typescript function getActiveResources(): unknown[] ``` -------------------------------- ### Create Azure Container App Source: https://github.com/softeria/ms-365-mcp-server/blob/main/docs/deployment.md Creates an Azure Container App to host the ms-365-mcp-server. It configures environment variables, ingress, and specifies the command to run the application. ```bash az containerapp create \ --name mcp-server \ --resource-group your-rg \ --environment your-cae \ --image yourregistry.azurecr.io/ms365-mcp-server:latest \ --target-port 3000 \ --ingress external \ --min-replicas 1 \ --max-replicas 3 \ --cpu 0.5 --memory 1Gi \ --system-assigned \ --env-vars \ "MS365_MCP_KEYVAULT_URL=https://your-keyvault.vault.azure.net" \ "MS365_MCP_ORG_MODE=true" \ "MS365_MCP_PUBLIC_URL=https://mcp.example.com" \ --command "node" "dist/index.js" "--http" "3000" "--org-mode" ``` -------------------------------- ### GET /authorize Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md Initiates the OAuth 2.0 authorization code flow. This endpoint supports two-leg PKCE and handles various parameters for redirecting to the Microsoft authorization server. ```APIDOC ## GET /authorize ### Description Initiates the OAuth 2.0 authorization code flow. This endpoint implements two-leg PKCE, allowing MCP clients with their own PKCE implementations to interoperate with Microsoft OAuth. It validates redirect URIs, handles PKCE challenges, and manages scopes before redirecting to the Microsoft authorization server. ### Method GET ### Endpoint /authorize ### Parameters #### Query Parameters - **client_id** (string) - Optional - OAuth client ID (ignored by the server; server uses its own). - **redirect_uri** (string) - Required - The callback URL, which must be validated against an allowlist. - **scope** (string) - Optional - Space-separated scopes, which are merged with default scopes. - **state** (string) - Required - A CSRF token used for PKCE matching and stored for validation. - **response_type** (string) - Optional - Specifies the desired response type, typically `"code"`. - **response_mode** (string) - Optional - The delivery mode for the response. - **code_challenge** (string) - Optional - The PKCE code challenge provided by the client. - **code_challenge_method** (string) - Optional - The PKCE method used (usually `"S256"`). - **login_hint** (string) - Optional - A hint for the login identifier, forwarded to Microsoft. - **domain_hint** (string) - Optional - A hint for the domain, forwarded to Microsoft. - **prompt** (string) - Optional - Specifies the prompt behavior, forwarded to Microsoft. ### Response #### Success Response (302 Redirect) - **Location** (header) - The URL to redirect to, typically pointing to Microsoft's authorization endpoint. #### Response Example ``` Location: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?... ``` ### Error Responses - **400 `invalid_request`**: Returned if the `redirect_uri` is not allowed (fails CWE-601 check). - **503 `server_busy`**: Returned if the PKCE store capacity is exceeded (more than 1000 pending authorizations). ``` -------------------------------- ### Get Token for Specific Account Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/auth-manager.md Use `getTokenForAccount` to fetch an access token for a particular user, identified by their username or MSAL homeAccountId. This is useful when managing multiple accounts. ```typescript async getTokenForAccount(identifier: string): Promise ``` ```typescript const userToken = await authManager.getTokenForAccount('user@example.com'); ``` -------------------------------- ### Run MS365 MCP Server (Personal Account) Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/configuration.md Execute the MS365 MCP Server using npx for personal account usage. This command defaults to the device code flow and loads personal tools like email, calendar, and OneDrive. ```bash npx @softeria/ms-365-mcp-server ``` -------------------------------- ### Get Access Token Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/auth-manager.md Call `getToken` to retrieve an access token. It will attempt a silent refresh if the cached token is expired. Ensure a valid token is obtained before proceeding. ```typescript async getToken(forceRefresh?: boolean): Promise ``` ```typescript const token = await authManager.getToken(); if (!token) throw new Error('No valid token'); ``` -------------------------------- ### MCP Protocol Response - Tool Result Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/mcp-server.md An example of an MCP protocol response containing the result of a tool call. This shows the structure for receiving tool execution results. ```JSON { "jsonrpc": "2.0", "result": { "content": [ { "type": "text", "text": "[{\"id\":\"123\",\"subject\":\"Meeting\"}]" } ] }, "id": 1 } ``` -------------------------------- ### Health Check Endpoint Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/endpoints.md A simple GET request to the root path '/' provides a health check for the server. The expected response is a 200 OK status with a confirmation message. ```bash curl http://localhost:3000/ ``` ```text Microsoft 365 MCP Server is running ``` -------------------------------- ### GraphClient Constructor Source: https://github.com/softeria/ms-365-mcp-server/blob/main/_autodocs/api-reference/graph-client.md Initializes the GraphClient with authentication manager, application secrets, and an optional output format. ```APIDOC ## GraphClient Constructor ### Description Initializes GraphClient with authentication and output format configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```typescript constructor( authManager: AuthManager, secrets: AppSecrets, outputFormat?: 'json' | 'toon' ) ``` ### Parameters Table | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | authManager | `AuthManager` | — | AuthManager instance for token acquisition | | secrets | `AppSecrets` | — | Application secrets (clientId, tenantId, cloudType) | | outputFormat | `'json' | 'toon'` | `'json'` | Response format: JSON or TOON (Token-Oriented Object Notation) | ### Example ```typescript const graphClient = new GraphClient(authManager, secrets, 'json'); ``` ```