Outlook MCP Server
MCP server for Microsoft Outlook / Microsoft Graph mail operations. It supports delegated access (per-user tokens, Graph /me/... paths) and application access (daemon or gateway-issued tokens, /users/{mailbox}/... paths, plus optional client-credentials token acquisition via environment variables).
Features
- Read tools:
get_email,get_thread(by GraphconversationId; sorted byreceivedDateTimein the server to avoid GraphInefficientFilteron$filter+$orderby),search_emails(KQL + optional read/date filters),list_inbox(optional folder, unread, received date filters),list_folders,get_attachments(metadata only),get_attachment_content(downloads one attachment as native multimodal content for the model to look at — anImageContentblock for images by default, anEmbeddedResourceblob otherwise;as_resource=trueforcesEmbeddedResourceeven for images, withmimeTypedeliberately masked as generic binary since MCP clients render animage/*mimeType inline and truncate the response before the base64 reaches the model as text; attachments overMAX_MULTIMODAL_ATTACHMENT_BYTES, default 8MB, return a metadata-only error instead),list_master_categories,list_message_rules - AI tools (MCP sampling):
categorize_email(read-only — does not change Outlook),extract_email_data— fall back if the client does not support sampling - Write tools (optional):
send_email,send_draft_email,create_draft(compact response by default),delete_draft(drafts only; refuses non-drafts; Graph DELETE does not purge, Exchange keeps the item recoverable, normally in Deleted Items per mailbox retention),create_mail_folder,move_email(compact response by default),move_emailsandset_messages_categories(Graph$batch, throttling-aware),mark_as_read,create_reply_draft,set_message_categories,create_message_rule/update_message_rule/delete_message_rule(Inbox rules),create_master_category/delete_master_category,apply_llm_category_to_email(classify via sampling then PATCH categories — needs successful sampling +ENABLE_WRITE_OPERATIONS=true),save_attachment_to_path(writes an attachment directly to local disk — the reliable way to save one, since routing bytes through a tool response hits context/token limits and image content gets rendered/truncated by MCP clients before the base64 is usable) — disabled unlessENABLE_WRITE_OPERATIONS=true. Many production setups keep writes off and send mail from a separate service; enable writes only when you intend this process to call Graph send/category APIs directly (or, forsave_attachment_to_path, to write to the local filesystem). Category updates requireMail.ReadWrite(added automatically to OAuth scopes when writes are enabled). Seecategorize_emailvsapply_llm_category_to_emailvsset_message_categoriesbelow.create_draftaccepts optionalcc_addressesandbcc_addresses(validated, de-duplicated per list, at most 500 recipients in total withto_addresses). For group reminders put all participants inbcc_addressesso they don't see each other; a BCC-only draft is allowed. Validation errors never echo addresses. By default (compact=true) the success response is{ok, id, webLink, isDraft, to_count, cc_count, bcc_count}plus theattachmentssummary when files were attached — counts only, no recipients, subject or body;compact=falsereturns the Graph message (recipients and body included) asmessage, plus the counts.to_countis the raw length ofto_addresses(not validated or de-duplicated). Graph error messages on failure paths may echo request details.send_email,create_draft, andcreate_reply_draftaccept an optionalattachmentslist ({"filename", "content_type", "content_base64", "file_path", "is_inline"}per file — exactly one ofcontent_base64/file_path). Preferfile_path: the server reads the file itself from local disk, so the calling model just passes a short path instead of transcribing the whole file as base64 text — for anything beyond a trivial file, having the model generate that content character-by-character as a tool argument is slow and error-prone (one wrong token corrupts the file).filenamedefaults to the path's basename whenfile_pathis used. Small files (≤3MB) attach inline; larger files (up to Graph's ~150MB ceiling) go through a chunked upload session — forsend_emailthis means a transparent draft-then-send fallback (used_draft_path: truein the response) since Graph's one-shotsendMailhas no message id to attach large files to before sending. Per-call limits (MAX_ATTACHMENT_COUNT,MAX_ATTACHMENT_UPLOAD_BYTES) are configurable.
- Transports:
stdio(local tools and IDE integrations) andstreamable-http(HTTP MCP behind a reverse proxy or in containers) - Auth:
X-Graph-Token(delegated or application JWT); optionalX-Graph-Mailbox/GRAPH_APPLICATION_MAILBOXfor application mode;GRAPH_AUTH_MODE=application+ app registration env for client_credentials; optional OAuth (/oauth/login+X-OAuth-Session, oroutlook-mcp-oauth-device+GRAPH_OAUTH_TOKEN_CACHE_PATH); orGRAPH_DEV_TOKENfor local dev. See Token handling below.
categorize_email vs apply_llm_category_to_email vs set_message_categories
| Tool | Updates Outlook? | Notes |
|---|---|---|
categorize_email |
No (read-only) | Runs MCP sampling and returns classification JSON in the tool result. The mailbox is unchanged. |
apply_llm_category_to_email |
Yes, when writes work | Same classification as above, then PATCHes message.categories with a single label from your configured list (see CLASSIFICATION_CATEGORIES). Requires ENABLE_WRITE_OPERATIONS=true, delegated Mail.ReadWrite, and successful sampling — if sampling fails, the message is not updated. |
set_message_categories |
Yes, when writes work | You supply the category strings; replaces the message’s entire categories list. No LLM. Same writes flag and Mail.ReadWrite as above. |
Debugging “category not visible in Outlook”: Inspect the raw MCP tool JSON, not only the assistant’s summary (agents may paraphrase success incorrectly). For apply_llm_category_to_email, a real success includes "ok": true and "categories". If you see write_disabled, set ENABLE_WRITE_OPERATIONS=true and restart. If classification_failed / sampling_error, MCP sampling did not produce valid JSON — fix the client or use set_message_categories after categorize_email. If http_error with 403, the token likely lacks Mail.ReadWrite — re-consent. Message ids with +, /, or = are percent-encoded in Graph URL paths (graph_client.py); without encoding, PATCH can target the wrong resource or fail silently. categorize_email alone never writes. Use list_master_categories to see names/colors defined for the mailbox.
Requirements
- Python 3.12+
- Delegated tokens: Graph delegated permissions on the token (typical
scp):Mail.Read(andoffline_accessif using refresh tokens) for most read toolsMailboxSettings.Readforlist_master_categories(Outlook master category list). Without it, that tool returns HTTP 403 from Graph.Mail.Sendforsend_email/create_draftwhenENABLE_WRITE_OPERATIONS=trueMail.ReadWriteforset_message_categoriesandapply_llm_category_to_emailwhenENABLE_WRITE_OPERATIONS=true(OAuth scope list adds it alongsideMail.Sendwhen writes are enabled)MailboxSettings.ReadWritefor Inbox rules (list_message_rulesalso works withMailboxSettings.Read) and forcreate_master_category/delete_master_category. Not added automatically — put it inGRAPH_OAUTH_SCOPESyourself (see Inbox rules and master categories).
- Application tokens (client credentials or gateway-issued app JWT): use application permissions in Entra ID (e.g.
Mail.Read,Mail.Send,Mail.ReadWriteas Application roles — admin consent). The server calls/users/{mailbox}/...; you must supply the mailbox viaX-Graph-Mailbox(Streamable HTTP) orGRAPH_APPLICATION_MAILBOX(stdio / default).
Search: search_emails expects a KQL string (mailbox search, eventual consistency). Optional read_filter (any, read, unread) and received_on / received_after / received_before (UTC dates, YYYY-MM-DD) are combined into the query; the tool returns effective_query.
Mail folders, list_inbox, and create_mail_folder
list_folders— Lists mail folders (id,displayName, item counts). Use returnedidvalues when a tool requires a folder id, or rely on name resolution below.list_inbox— Lists messages in a folder (default: Inbox). Specify the folder withfolder_id(Graph id or well-known name such asinbox,sentitems,drafts,archive) orfolder_name(case-insensitivedisplayName; resolved via Graph). Do not set bothfolder_idandfolder_name. Optionalunread_only, andreceived_on(single UTC calendar day) orreceived_after/received_before(OData datetimes). If name resolution finds no folder or more than one match, the tool returnsfolder_not_foundorfolder_ambiguous.create_mail_folder(requiresENABLE_WRITE_OPERATIONS=true) — Creates a folder at the mailbox root or under a parent. Parent may beparent_folder_idorparent_folder_name(same resolution rules aslist_inbox); do not set both. Successful responses may includeresolved_parent_folder_idwhenparent_folder_namewas used.
Folder references for move_email, move_emails and a rule's moveToFolder / copyToFolder accept any of: a Graph folder id, a well-known name (archive, deleteditems, junkemail, inbox, …), a unique display name, or a path such as Auto/DMARC (first segment: a well-known name or a unique display name anywhere in the tree; each next segment: a direct child). Ids are recognised by shape (long base64, no spaces), so a path containing / is not confused with an id that happens to contain one.
Name resolution walks the visible folder tree (root mailFolders, then childFolders per folder) with a bounded number of Graph requests. For unusual trees or duplicate display names, use list_folders and pass explicit ids.
Install from PyPI (uvx)
After the package is published to PyPI (outlook-multi-tenant-mcp), run the server without cloning the repo. You need uv installed locally.
uvx outlook-multi-tenant-mcp
Pin a release:
uvx outlook-multi-tenant-mcp==0.3.0
The same wheel also installs the outlook-mcp-server command (same entry point) for older docs and scripts.
OAuth device-code helper (stdio-friendly MSAL cache; same PyPI package):
uvx outlook-mcp-oauth-device
Set the same environment variables as in a dev checkout (see Configuration and .env.example). uvx uses stdio MCP by default. For Streamable HTTP with X-Graph-Token, run the server as a process or container and point clients at the HTTP MCP URL instead of uvx.
Install (development, uv)
cd outlook-mcp-server
uv sync --extra dev
If you prefer pip/venv, pip install -e ".[dev]" still works.
Configuration
See .env.example. Important variables:
| Variable | Description |
|---|---|
MCP_TRANSPORT |
stdio (default) or streamable-http |
MCP_HOST / MCP_PORT |
Bind address for Streamable HTTP (default 127.0.0.1:8000; use 0.0.0.0 in containers) |
MCP_STATELESS_HTTP |
true for stateless Streamable HTTP (better behind LB; sampling may be limited) |
GRAPH_DEV_TOKEN |
Optional static token for local testing (never production); may be delegated or application JWT — same classification rules as X-Graph-Token |
GRAPH_AUTH_MODE |
delegated (default) or application. In application, with no bearer, the server acquires a token via client_credentials using the GRAPH_APPLICATION_* and tenant vars below |
GRAPH_TENANT_ID |
Tenant for application token endpoint (falls back to GRAPH_OAUTH_TENANT if unset) |
GRAPH_APPLICATION_CLIENT_ID / GRAPH_APPLICATION_CLIENT_SECRET |
Entra app for client_credentials (store secret in Key Vault / env in production) |
GRAPH_APPLICATION_MAILBOX |
Default mailbox (UPN or object id) for /users/... when X-Graph-Mailbox is not sent (required for application mode without that header) |
GRAPH_ALLOW_CLIENT_SECRET_HEADER |
true allows X-Graph-Client-Secret on HTTP requests (dev only; default false) |
GRAPH_OAUTH_* |
See OAuth below (GRAPH_OAUTH_ENABLED, CLIENT_ID, optional CLIENT_SECRET, TENANT, REDIRECT_URI, SCOPES, TOKEN_CACHE_PATH) |
ENABLE_WRITE_OPERATIONS |
true to enable write tools (send_email, send_draft_email, create_draft, delete_draft, create_mail_folder, move_email, move_emails, mark_as_read, create_reply_draft, set_message_categories, set_messages_categories, apply_llm_category_to_email, create_message_rule, update_message_rule, delete_message_rule, create_master_category, delete_master_category, save_attachment_to_path; adds Mail.Send and Mail.ReadWrite to default OAuth scopes when using OAuth — not MailboxSettings.ReadWrite, list that in GRAPH_OAUTH_SCOPES) |
MAX_ATTACHMENT_COUNT |
Max attachments accepted per send_email / create_draft / create_reply_draft call (default 10) |
MAX_ATTACHMENT_UPLOAD_BYTES |
Max decoded size for a single outgoing attachment (default 157286400, ~150MB — Graph's practical ceiling for chunked upload sessions) |
MAX_MULTIMODAL_ATTACHMENT_BYTES |
Max decoded size get_attachment_content will inline as an ImageContent/EmbeddedResource block (default 8388608, 8MB — base64 inflates ~33% and becomes LLM context; larger attachments get a metadata-only response instead) |
CLASSIFICATION_CATEGORIES |
Comma-separated labels for categorize_email / apply_llm_category_to_email (MCP sampling + validation). Default is a built-in multi-category list; override for your own taxonomy. UNCLASSIFIED is always allowed even if omitted from the list. |
PII_REDACTION_ENABLED |
true to run Microsoft Presidio on email JSON before MCP sampling (categorize_email, extract_email_data); requires optional install pip install ".[pii]" and python -m spacy download en_core_web_lg |
PII_REDACTION_STRATEGY |
pseudonymize (default), hash, or remove |
PII_ENTITIES |
Comma-separated Presidio detector types (default in .env.example). Cyrillic-heavy paragraphs skip PERSON and LOCATION (English NER false positives); emails/phones/cards still run. |
PII_RESPONSE_LEVEL |
full (default), minimal (omit body_content only — not privacy-safe; from / body_preview stay), or redacted (minimal + Presidio on remaining fields when [pii] works; otherwise deterministic email scrub + masked display names). Use Python 3.12+ with uv sync --extra pii and python -m spacy download en_core_web_lg for full Presidio behaviour. |
Privacy / PII: Optional Microsoft Presidio integration (PII_REDACTION_ENABLED, PII_REDACTION_STRATEGY, PII_ENTITIES, PII_RESPONSE_LEVEL) can redact or minimize sensitive spans in tool payloads—especially before MCP sampling. Install the [pii] extra and an English spaCy model when using Presidio (see Configuration and Security below). Tune settings for your compliance needs; do not rely on defaults alone for regulated data without review.
Run
stdio (default):
MCP_TRANSPORT=stdio uv run outlook-mcp-server
# or: MCP_TRANSPORT=stdio uv run python -m outlook_mcp.server
Streamable HTTP (MCP endpoint default path /mcp, health GET /health):
MCP_TRANSPORT=streamable-http MCP_HOST=0.0.0.0 MCP_PORT=8000 uv run outlook-mcp-server
Point an MCP client at http://<host>:8000/mcp (Streamable HTTP).
Server instructions
The instructions string returned to MCP clients at initialize is generated at startup from the tools that
are actually registered, so it never describes a tool the deployment removed (MCP_ENABLED_TOOLS,
MCP_DISABLED_TOOLS, missing prerequisites). It is short plain text: what the server is, KQL examples for
search_emails, thread checks before calling a message unanswered, create_draft / create_reply_draft /
delete_draft caveats, folder-name resolution, attachment tool behaviour, and, when no send tool is registered,
a line telling the model to prepare drafts instead.
Set MCP_INSTRUCTIONS_APPEND to add deployment-specific hints (for example naming conventions) without changing
the package. The text is appended as-is after the generated lines, truncated to 4000 characters, and is not logged.
MCP Inspector
Use the official MCP Inspector to connect to this server and try tools in the browser.
1. STDIO (Inspector starts the server for you) — simplest for a quick local run. From the directory that contains the outlook-mcp-server folder (if you cloned the repo with that layout), run:
npx @modelcontextprotocol/inspector \
uv \
--directory outlook-mcp-server \
run \
outlook-mcp-server
From PyPI (no local clone; requires the package on PyPI and uvx on PATH):
npx @modelcontextprotocol/inspector uvx outlook-multi-tenant-mcp
The CLI prints a local URL (often with an MCP_PROXY_AUTH_TOKEN query parameter). Open it in the browser. In the UI, choose the STDIO transport if it is not already selected.
- Graph auth: STDIO requests usually have no HTTP headers, so use
GRAPH_DEV_TOKENin.env(see.env.example) orGRAPH_OAUTH_TOKEN_CACHE_PATHafteroutlook-mcp-oauth-deviceinstead ofX-Graph-Token. - If the Inspector shows a session token for its proxy, use the full URL it prints or set
DANGEROUSLY_OMIT_AUTH=trueonly for trusted local debugging (see Inspector docs).
2. Streamable HTTP (you start the server separately) — use this to test X-Graph-Token, X-OAuth-Session, or OAuth in a way that matches HTTP clients.
Terminal A — run the MCP HTTP server (see Streamable HTTP above), e.g.:
cd outlook-mcp-server
MCP_TRANSPORT=streamable-http MCP_HOST=127.0.0.1 MCP_PORT=8000 uv run outlook-mcp-server
Confirm GET http://127.0.0.1:8000/health returns JSON.
Terminal B — start the Inspector (or open an already-running Inspector UI):
npx @modelcontextprotocol/inspector
In the Inspector sidebar:
- Transport:
Streamable HTTP - URL:
http://127.0.0.1:8000/mcp(adjust host/port if needed) - Custom headers: add
X-Graph-Token(your delegated JWT) orX-OAuth-Session(afterGET /oauth/loginwhen OAuth is enabled). Turn the toggle ON for each header you add — disabled headers are not sent.
Without a running HTTP server on that URL, the Inspector shows connection refused.
MCP Inspector with Entra ID Application (client) ID and client secret
The Inspector does not store your Microsoft app secret. You put the Application (client) ID and client secret (from Entra ID → App registrations → your app → Overview / Certificates & secrets) in the environment of the MCP server process, then connect the Inspector with Streamable HTTP only.
Map Entra portal names to env vars
| Entra ID (Azure portal) | Environment variable (server) |
|---|---|
| Application (client) ID | GRAPH_OAUTH_CLIENT_ID (browser OAuth) or GRAPH_APPLICATION_CLIENT_ID (app-only Graph) |
| Client secret (Certificates & secrets → Value) | GRAPH_OAUTH_CLIENT_SECRET or GRAPH_APPLICATION_CLIENT_SECRET |
| Directory (tenant) ID | Use as GRAPH_OAUTH_TENANT or GRAPH_TENANT_ID (single-tenant app) |
Path A — Delegated user (browser sign-in, Graph /me/...)
Use this when the signed-in user’s mailbox is the one you want to read.
- Register an app in Entra ID with delegated Graph permissions (
Mail.Read,offline_access; add others per Requirements above). For a confidential web client, create a client secret under Certificates & secrets. - Under Authentication, add a Web redirect URI that matches
GRAPH_OAUTH_REDIRECT_URI(default in.env.example:http://127.0.0.1:8000/oauth/callback). - Start the server with OAuth enabled, streamable-http, and your IDs filled in (example; adjust paths and secrets — never commit real values):
cd outlook-mcp-server
export GRAPH_OAUTH_ENABLED=true
export MCP_TRANSPORT=streamable-http
export MCP_HOST=127.0.0.1
export MCP_PORT=8000
# Application (client) ID and client secret from Entra
export GRAPH_OAUTH_CLIENT_ID="your-application-client-id"
export GRAPH_OAUTH_CLIENT_SECRET="your-client-secret-value"
export GRAPH_OAUTH_TENANT="common" # or your tenant GUID / domain
export GRAPH_OAUTH_REDIRECT_URI="http://127.0.0.1:8000/oauth/callback"
uv run outlook-mcp-server
- In a browser, open
http://127.0.0.1:8000/oauth/login, sign in, and complete consent. - On the success page, copy the
X-OAuth-Sessionvalue. - In MCP Inspector: Transport → Streamable HTTP, URL →
http://127.0.0.1:8000/mcp, Custom headers → addX-OAuth-Sessionwith that value (toggle on). Do not put the client secret in Inspector headers.
Path B — Application permissions (client credentials, Graph /users/{mailbox}/...)
Use this for daemon-style access to a specific mailbox (no user browser login on each run).
- Register an app in Entra ID with Application permissions for Graph (e.g.
Mail.Read; addMail.Send/Mail.ReadWriteonly if you enable writes). Grant admin consent. - Create a client secret under Certificates & secrets. Note Application (client) ID and Directory (tenant) ID on Overview.
- Start the server in application mode (example):
cd outlook-mcp-server
export MCP_TRANSPORT=streamable-http
export MCP_HOST=127.0.0.1
export MCP_PORT=8000
export GRAPH_AUTH_MODE=application
export GRAPH_TENANT_ID="your-tenant-id"
export GRAPH_APPLICATION_CLIENT_ID="your-application-client-id"
export GRAPH_APPLICATION_CLIENT_SECRET="your-client-secret-value"
export GRAPH_APPLICATION_MAILBOX="shared-mailbox@yourtenant.com"
uv run outlook-mcp-server
- In MCP Inspector, connect to
http://127.0.0.1:8000/mcpwith noX-Graph-Tokenrequired if the mailbox is set viaGRAPH_APPLICATION_MAILBOX. To target another mailbox for a single session, add custom headerX-Graph-Mailbox(and optionalX-Graph-Auth-Mode: application) instead of changing env.
Security: Keep client secrets in env, a secret manager, or your shell only for local tests — not in the Inspector UI, not in git. Optional dev-only header X-Graph-Client-Secret exists only when GRAPH_ALLOW_CLIENT_SECRET_HEADER=true; leave it false outside trusted local debugging.
Sampling / AI tools in the Inspector
Tools categorize_email, extract_email_data, and apply_llm_category_to_email call the MCP host via sampling/createMessage. The client must return assistant text that contains one JSON object matching the system prompt for that call.
- MCP Inspector (manual sampling): When the UI asks you to complete sampling, you must paste a valid JSON object (not an empty reply and not conversational prose alone). The classification prompt expects fields such as
email_id,category,confidence,intent,reasoning,extracted_data, andescalation, as described in the system prompt shown in the sampling request. An empty or non-JSON reply leads to errors likeNo JSON object foundorEmpty model response from MCP sampling. - Automated clients (e.g. langgraph-mcp-tester with a
sampling_callbackthat calls an LLM, optionally with JSON response format) handle this without manual paste. - If sampling fails, those tools return
sampling: false(or an error forapply_llm_category_to_email) plushinttext and the full message JSON from Microsoft Graph (email), including rawbody_contentwhen the message is HTML. That payload is intentional: it lets you or an upstream model classify the message outside MCP sampling. It is not the same as the truncated, HTML-stripped text sent inside the sampling prompt.
Troubleshooting: If a tool is missing from the Inspector list, disconnect and reconnect after upgrading. Some Inspector versions drop tools whose input schema uses anyOf / nullable types; list_master_categories uses a plain integer top (default 500, Graph $top) so its schema matches tools like list_inbox. Confirm the running server is this repo: cd outlook-mcp-server && uv run python -c "from outlook_mcp.server import mcp_app; print([t.name for t in mcp_app._tool_manager.list_tools()])".
MCP clients (Cursor, Claude Code, GitHub Copilot, Codex)
IDE and agent integrations change between versions—use each product’s current docs for file paths and JSON/TOML schema. The stable pattern for stdio + PyPI is:
- command:
uvx - args:
["outlook-multi-tenant-mcp"](optional version pin:["outlook-multi-tenant-mcp==0.3.0"]) - env: Graph-related variables from
.env.example(e.g.GRAPH_DEV_TOKEN,MCP_TRANSPORT,ENABLE_WRITE_OPERATIONS). Never commit real tokens; use env injection or secret stores.
From a git checkout instead of PyPI, use command uv and args like ["run", "outlook-mcp-server"] with working directory set to outlook-mcp-server (if the client supports cwd). Alternatively ["run", "outlook-multi-tenant-mcp"] after uv sync in that directory.
Cursor
See the Cursor Model Context Protocol docs. Register a stdio server with uvx / outlook-multi-tenant-mcp and set env for auth.
Example shape (field names may differ by Cursor version):
{
"mcpServers": {
"outlook-mcp": {
"command": "uvx",
"args": ["outlook-multi-tenant-mcp"],
"env": {
"MCP_TRANSPORT": "stdio"
}
}
}
}
Add GRAPH_DEV_TOKEN or GRAPH_OAUTH_TOKEN_CACHE_PATH under env as needed.
Claude Code
See MCP in Claude Code. Add a stdio server using the same uvx + outlook-multi-tenant-mcp entrypoint and environment variables as above.
GitHub Copilot (VS Code)
See Use MCP servers in VS Code. Configure a stdio server with command uvx, args ["outlook-multi-tenant-mcp"], and env for Microsoft Graph auth.
OpenAI Codex (CLI / IDE)
Codex reads MCP settings from ~/.codex/config.toml. See Model Context Protocol – Codex and the configuration reference.
Example (syntax per your Codex version):
[mcp_servers.outlook-mcp]
command = "uvx"
args = ["outlook-multi-tenant-mcp"]
env = { MCP_TRANSPORT = "stdio" }
Set GRAPH_DEV_TOKEN (or other vars) in the process environment before starting Codex if you prefer not to store secrets in the file.
Docker
docker build -t outlook-mcp-server .
docker run --rm -p 8000:8000 \
-e GRAPH_DEV_TOKEN="..." \
outlook-mcp-server
Token handling
Resolution order (first match wins):
X-Graph-Token— Bearer access token.expis checked before calling Graph. If the token is classified as application (non-empty JWTrolesclaim, orX-Graph-Auth-Mode: application), the server uses/users/{mailbox}/...and requiresX-Graph-MailboxorGRAPH_APPLICATION_MAILBOX. If classified as delegated (e.g.scppresent, orX-Graph-Auth-Mode: delegated), the server uses/me/....X-OAuth-Session— opaque session id after browser OAuth (requiresGRAPH_OAUTH_ENABLED=trueand streamable-http; delegated cache →/me).GRAPH_OAUTH_TOKEN_CACHE_PATH— MSAL delegated token cache (e.g. afteroutlook-mcp-oauth-device). Works with stdio or HTTP →/me.GRAPH_DEV_TOKEN— static token for local testing; same delegated vs application rules asX-Graph-Token.GRAPH_AUTH_MODE=application(orX-Graph-Auth-Mode: application) with no bearer — acquire token via MSAL client_credentials (GRAPH_APPLICATION_CLIENT_ID, secret, tenant), then/users/{mailbox}/...with mailbox from header orGRAPH_APPLICATION_MAILBOX.
Expired token: Tools return a JSON payload with code: ERR_GRAPH_TOKEN_EXPIRED.
Missing mailbox (application mode): Tools return code: ERR_GRAPH_MAILBOX_MISSING when an application token is used without X-Graph-Mailbox or GRAPH_APPLICATION_MAILBOX.
Logging: Never log tokens, session ids, or email bodies in production.
Multi-tenancy and auth isolation
Graph identity is resolved on every tool call from the MCP request context (there is no process-wide “current user” token reused across callers).
| Source | Isolation | Multi-tenant hosting |
|---|---|---|
X-Graph-Token (+ optional X-Graph-Mailbox / X-Graph-Auth-Mode) |
Per HTTP request | For delegated: forward a distinct user token per end user. For application: you may forward a short-lived app access token and a mailbox header per tenant/user; never put the app client secret in headers in production. |
X-OAuth-Session + in-memory store |
Per opaque session id (returned after /oauth/login) |
Users do not share one bucket; isolation breaks only if the same session id is sent for different users (misconfiguration, leak, or proxy stripping/overwriting headers). In-memory sessions are single-process and are lost on restart; multiple replicas need a shared session store (not built in today). |
GRAPH_OAUTH_TOKEN_CACHE_PATH |
One MSAL cache file for the process | The server uses the first account in that cache. Do not use one shared cache path for many tenants on one server. |
GRAPH_DEV_TOKEN or no per-request headers (e.g. some stdio clients) |
Whole process | One Microsoft identity per server process for those code paths. |
Recommendations
- For many users on one MCP host, prefer
X-Graph-Token(upstream holds delegated tokens) orX-OAuth-Sessionwith one session id per user. For application hosting, prefer passing app access tokens +X-Graph-Mailboxper logical mailbox, or run one process per mailbox withGRAPH_APPLICATION_MAILBOX. - Avoid a shared
GRAPH_OAUTH_TOKEN_CACHE_PATHacross tenants in one process. - The
mcp_appsingleton is one server instance, not one user—separation is entirely in how tokens are resolved per request.
OAuth (browser, streamable-http)
For a single-process server (default; not multiple replicas without a shared session store):
- Register an app in Entra ID with delegated Graph permissions (
Mail.Read,offline_access; addMail.SendandMail.ReadWriteif writes are enabled (category updates needMail.ReadWrite); addMailboxSettings.Readif you uselist_master_categories, orMailboxSettings.ReadWritefor Inbox rules / creating master categories). Allow personal Microsoft accounts and/or organizational accounts as needed. - Add a web redirect URI matching
GRAPH_OAUTH_REDIRECT_URI(e.g.http://127.0.0.1:8000/oauth/callback). - Set
GRAPH_OAUTH_ENABLED=true,GRAPH_OAUTH_CLIENT_ID, optionalGRAPH_OAUTH_CLIENT_SECRET(confidential app), andGRAPH_OAUTH_TENANT(common,organizations,consumers, or a tenant id). - Run streamable-http, open
http://<host>:<port>/oauth/login, complete sign-in. - Copy the
X-OAuth-Sessionvalue from the success page into MCP Inspector Custom Headers (toggle on).
Sessions live in memory only: restart the server → sign in again. MCP_STATELESS_HTTP=true across multiple instances is not compatible with in-memory OAuth sessions without a shared store (future work).
OAuth (device code, stdio-friendly)
cd outlook-mcp-server
# Set GRAPH_OAUTH_CLIENT_ID (and TENANT if needed) in .env or the environment
uv run outlook-mcp-oauth-device
Follow the browser/device instructions. Then set GRAPH_OAUTH_TOKEN_CACHE_PATH to the printed cache path (or rely on the default under ~/.cache/outlook-mcp/) when running outlook-mcp-server. The server will refresh tokens silently when possible.
Obtaining a Graph token without built-in OAuth
- Your own OAuth client — Any flow that yields a delegated Graph access token with the right
scpworks withX-Graph-Token.
Graph Explorer (quick tests, personal or work account)
Graph Explorer runs in the browser and obtains a delegated token for the account you sign in with. It is useful for manual checks (MCP Inspector, X-Graph-Token, or short-lived GRAPH_DEV_TOKEN). Tokens expire quickly; rotate them as needed and never commit tokens to git.
Personal Microsoft account (e.g. @outlook.com, @hotmail.com, @live.com):
- Open Graph Explorer and choose Sign in (use your personal account).
- Open Modify permissions (or the permissions panel) and consent to the Graph permissions this server needs for the APIs you will call — at minimum
Mail.Readfor mail tools; addMail.SendandMail.ReadWriteif you test writes (including message categories); addMailboxSettings.Readif you uselist_master_categories. Accept the consent prompt for your account. - Run a simple request to confirm mail access works, for example
GET https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$top=1. - Open the Access token tab (or the token preview in the UI), copy the access token string.
- Pass it to the MCP server as
X-Graph-Token(Streamable HTTP custom header, toggle on in MCP Inspector) or setGRAPH_DEV_TOKENfor local stdio-only runs.
If consent or the request fails, confirm the signed-in user is the mailbox you expect and that the selected permissions match the operation (personal tenants have no “admin consent” step for your own account beyond the prompt shown in Graph Explorer).
Cloud application mode (managed identity)
Run the server unattended (for example in Azure Container Apps) with no stored secrets: it reads mail with application permissions, authenticates to Microsoft Graph and Azure Blob Storage with a user-assigned managed identity, and can be narrowed to a handful of read-oriented tools.
Prerequisites: a user-assigned managed identity attached to the host; the Graph application role
Mail.Read (and Mail.ReadWrite only if you enable write tools) granted to that identity, ideally
restricted to specific mailboxes with an Exchange Online application access policy; and, for attachment
storage, the Storage Blob Data Contributor role on the target container.
| Variable | Description |
|---|---|
GRAPH_AUTH_MODE |
Must be application for managed identity. |
GRAPH_APPLICATION_CREDENTIAL |
client_secret (default) or managed_identity. With managed_identity the token comes from the host identity endpoint (IDENTITY_ENDPOINT / IDENTITY_HEADER, set by Azure). Tool calls return configuration_error if GRAPH_AUTH_MODE is not application. |
AZURE_CLIENT_ID |
Client id of the user-assigned managed identity. |
GRAPH_APPLICATION_MAILBOX |
Default mailbox when no X-Graph-Mailbox header is sent. |
GRAPH_ALLOWED_MAILBOXES |
Comma-separated mailboxes (case-insensitive) application mode may access; anything else returns mailbox_not_allowed. Required (non-empty) whenever GRAPH_APPLICATION_CREDENTIAL=managed_identity (header trust does not matter); optional with client_secret (multi-mailbox use). |
GRAPH_TRUST_REQUEST_HEADERS |
Default true. Set false behind a gateway or in a public deployment: X-Graph-Token, X-OAuth-Session, X-Graph-Auth-Mode and X-Graph-Client-Secret are then ignored. X-Graph-Mailbox is still honoured, so pair this with an allowlist. |
MCP_ENABLED_TOOLS |
Comma-separated allowlist of tool names; empty = every tool the configuration allows. Unknown names are a startup error. |
MCP_DISABLED_TOOLS |
Comma-separated tools to remove; applied last and always wins. Unknown names are a startup error. |
ENABLE_WRITE_OPERATIONS |
Must be true for save_attachment_to_storage (and other write tools). Listing a write tool in MCP_ENABLED_TOOLS while this is false is a startup error. |
ATTACHMENT_STORAGE |
azure_blob enables save_attachment_to_storage; empty (default) disables it. |
ATTACHMENT_BLOB_CONTAINER_URL |
https://<account>.blob.core.windows.net/<container>. |
ATTACHMENT_ALLOWED_PREFIXES |
Comma-separated key prefixes the tool may write under (matched on whole path segments); empty = any key. |
ATTACHMENT_TEXT_MAX_BYTES |
Largest attachment (PDF or text) get_attachment_text will download (default 15000000). |
ATTACHMENT_TEXT_MAX_PAGES |
Pages extracted per PDF (default 200); beyond it the result is marked truncated. |
ATTACHMENT_TEXT_TIMEOUT_SECONDS |
Wall-clock bound for extraction (default 30); on timeout the result is unreadable. |
MCP_INSTRUCTIONS_APPEND |
Optional text appended to the generated server instructions (see "Server instructions"); truncated to 4000 characters, never logged. |
LOG_LEVEL |
DEBUG, INFO, WARNING, ERROR or CRITICAL, applied to the root and outlook_mcp loggers at startup. Empty (default) leaves logging unchanged. Use WARNING in production. |
Fail-closed rules: managed_identity requires GRAPH_AUTH_MODE=application and a non-empty
GRAPH_ALLOWED_MAILBOXES (whatever GRAPH_TRUST_REQUEST_HEADERS is). client_secret is unchanged: without an
allowlist it can serve any mailbox the app registration is granted. Errors are returned as
mailbox_not_allowed, managed_identity_error or configuration_error payloads.
Example (a read-only deployment; sending is excluded):
MCP_TRANSPORT=streamable-http
MCP_HOST=0.0.0.0
GRAPH_AUTH_MODE=application
GRAPH_APPLICATION_CREDENTIAL=managed_identity
AZURE_CLIENT_ID=00000000-0000-0000-0000-000000000000
GRAPH_TRUST_REQUEST_HEADERS=false
GRAPH_ALLOWED_MAILBOXES=billing@contoso.com
GRAPH_APPLICATION_MAILBOX=billing@contoso.com
ENABLE_WRITE_OPERATIONS=true
MCP_DISABLED_TOOLS=send_email,send_draft_email
ATTACHMENT_STORAGE=azure_blob
ATTACHMENT_BLOB_CONTAINER_URL=https://contosostorage.blob.core.windows.net/attachments
ATTACHMENT_ALLOWED_PREFIXES=Contracts/
LOG_LEVEL=WARNING
Sending can be excluded with MCP_DISABLED_TOOLS (as above); disabled tools are not registered, so a
client cannot call them even though ENABLE_WRITE_OPERATIONS=true.
save_attachment_to_storage
Writes one message attachment to the configured private blob container using the managed identity (no
keys). The result {"ok": true, "queued": true, ...} means the write was queued, not that it is
delivered or visible yet. Writing to a key that is still pending overwrites it. Nothing about the key, file
name or content is logged. It requires GRAPH_TRUST_REQUEST_HEADERS=false: the storage write uses the
server's own identity, so the Graph identity must be the server's own too (otherwise any caller with a
header token could make the server write to its storage). With trusted headers it returns
configuration_error. The key is the blob name (/ separates folders) and is validated:
- Unicode is normalized to NFC; names are kept as given otherwise (Cyrillic and spaces are fine).
- Refused: an absolute key (leading
/),..or.segments, backslashes, empty segments (//), control, format and bidirectional-override characters, characters that fold to/or.under NFKC (confusables), a leading or trailing space in any segment, a segment ending in.(so a folder namedLtd.is refused; useLtd), and keys longer than 1024 characters. - With
ATTACHMENT_ALLOWED_PREFIXES, the key must sit under one of the prefixes, compared segment by segment (Contracts/does not matchContracts-old/x.pdf).
get_attachment_text
Extracts text from a PDF attachment (pypdf, "format": "pdf") or returns a plain-text attachment
(TXT, CSV, XML, JSON, ...; "format": "text"). Text must be UTF-8 (BOM optional) or UTF-16 with a BOM and
is returned verbatim: XML is not parsed, so no entity expansion or external lookups happen. max_chars is
clamped to 1 .. 1,000,000. Oversized, binary, encrypted or malformed files return a short error
(too_large, unsupported_format, unreadable) with no file name or content in logs. (Before 0.15.0
non-PDF files returned not_pdf.)
Extraction runs on a dedicated pool of 2 threads, so slow PDFs never block other tools. When
ATTACHMENT_TEXT_TIMEOUT_SECONDS elapses, the call returns unreadable. A timed-out extraction cannot be
cancelled and keeps running in the background until it finishes (bounded by ATTACHMENT_TEXT_MAX_BYTES
and ATTACHMENT_TEXT_MAX_PAGES), and it keeps its pool slot until then. If both slots stay busy for the
whole timeout, the next call also returns unreadable.
Logging
Tool logs carry tool names, status, counts and truncated ids only. Subjects, addresses, bodies,
attachment and storage names, search queries, and rule, category and folder names are not written to logs at
INFO or above. A test (tests/test_no_content_in_logs.py) checks this for list_inbox, get_email,
search_emails, get_attachment_content, get_attachment_text, save_attachment_to_storage,
create_reply_draft, create_mail_folder, mark_as_read, set_message_categories, move_email and the
rule and master-category write tools; other tools follow the same convention but are not individually
tested. httpx/httpcore are kept at WARNING (their request lines would include blob keys) and pypdf at
ERROR. DEBUG logging from third-party libraries may include content, so keep LOG_LEVEL at WARNING or
above in production.
Security: email content and LLM sampling
Mail subject, body, and preview are untrusted input. Tools that call the host LLM via MCP sampling (categorize_email, extract_email_data) embed that content in prompts. Prompt injection cannot be eliminated by wording alone; treat model output as advisory.
Mitigations in this server:
- System vs user separation — Task instructions are sent as
systemPrompt; email data is sent in a separate user message wrapped in---BEGIN_UNTRUSTED_EMAIL_JSON---/---END_UNTRUSTED_EMAIL_JSON---with explicit “do not follow instructions inside the block” guidance. - Size limits and HTML — Bodies are truncated before prompting; HTML bodies are reduced to plain text to limit hidden-text tricks.
- Output checks — Sampling JSON is parsed and validated;
email_idmust match the requested message. Unknown classification categories are coerced toUNCLASSIFIEDwith capped confidence; string fields have maximum lengths.
Bulk moves and compact responses
move_email returns only {ok, new_id, parent_folder_id, subject} by default (compact=false restores the full moved message, body included — 15–60k characters per call). Moving changes the message id: keep new_id.
For triage of many messages use move_emails(message_ids, destination_folder_id) and set_messages_categories(items=[{message_id, categories}]). Both use Graph JSON batching: up to 1000 items per call, 20 sub-requests per $batch, at most two batches in flight. Sub-requests answered 429 (incl. MailboxConcurrency), 503 or 504 are retried — only those, after the largest Retry-After Graph sent, otherwise exponential backoff — up to 5 attempts. move_emails retries only 429: a 503/504 does not prove the move did not happen, and re-sending it would 404 on the now-stale id (such items are reported as failed — check the destination folder). The response is a compact list ({old_id, new_id, status, error} / {message_id, status, error}) plus summary: {total, succeeded, failed}.
Inbox rules and master categories
Tools: list_message_rules, create_message_rule, update_message_rule, delete_message_rule, create_master_category, delete_master_category (Graph messageRule, outlookCategory).
Scope: delegated MailboxSettings.ReadWrite. Unlike Mail.Send / Mail.ReadWrite, it is not appended automatically when ENABLE_WRITE_OPERATIONS=true, because cached tokens are looked up with exactly the configured scope list — an implicit new scope would force every existing install to sign in again. To enable:
- Entra ID → your app → API permissions → add delegated
MailboxSettings.ReadWrite. GRAPH_OAUTH_SCOPES=Mail.Read MailboxSettings.ReadWrite(plus anything else you already use).- Sign in again with the same
GRAPH_OAUTH_TOKEN_CACHE_PATHthe server uses (outlook-mcp-oauth-device), so the device login and the server request the same scope list.
Without it Graph returns 403; the tool response then includes a hint naming the missing scope.
Rule conditions / actions use Graph's messageRulePredicates / messageRuleActions names. Conveniences: string-list predicates (subjectContains, senderContains, …) accept a single string; fromAddresses / sentToAddresses / forwardTo / redirectTo accept plain email strings; moveToFolder / copyToFolder accept any folder reference (see above) and are resolved to an id before the rule is created. Unknown keys are rejected locally with the list of valid ones; Graph's own 400s come back with graph_code / graph_message.
Example — file DMARC aggregate reports and stop processing further rules:
{
"display_name": "DMARC reports",
"sequence": 1,
"conditions": {
"fromAddresses": ["noreply-dmarc-support@google.com", "dmarcreport@microsoft.com"],
"subjectContains": ["Report domain:"]
},
"actions": {
"moveToFolder": "Auto/DMARC",
"assignCategories": ["DMARC"],
"markAsRead": true,
"stopProcessingRules": true
}
}
Switch it off later with update_message_rule(rule_id=..., is_enabled=false).
Master categories: create_master_category(display_name, color) — color is preset0…preset24, none, or a color name (Red, DarkBlue, …; full table in the tool description). Graph cannot rename a master category (only its color is mutable): create a new one and delete the old.
Operational: Do not drive high-risk actions (payments, irreversible sends, ERP writes) solely from LLM classification or extraction without human review or rules. Do not log full email bodies or prompts in production.
Tests
uv run pytest
References
- PyPI:
outlook-multi-tenant-mcp - uv tool install /
uvx— run the published package without a clone - MCP Inspector — browser UI to connect to this server over STDIO or Streamable HTTP
- Graph Explorer — try APIs and copy a delegated access token for manual tests
- Microsoft Graph Mail API overview
- Use the $search query parameter (mailbox / KQL)
- List masterCategories
- messageRule resource
- JSON batching and Outlook throttling limits
Metadata
Release files for outlook-multi-tenant-mcp 0.15.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| outlook_multi_tenant_mcp-0.15.0.tar.gz | 190.6 kB | Without provenance | Details for outlook_multi_tenant_mcp-0.15.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| outlook_multi_tenant_mcp-0.15.0-py3-none-any.whl | Python 3 | none | any | Details for outlook_multi_tenant_mcp-0.15.0-py3-none-any.whl |
Total release size: 314.1 kB
Release files / outlook_multi_tenant_mcp-0.15.0.tar.gz
| Download URL | outlook_multi_tenant_mcp-0.15.0.tar.gz |
|---|---|
| Size | 190.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
784a10ed96828c925178a09694b165ab5ecbc434ff6d6930731cda67db12b9cb
|
|
BLAKE2b-256 checksum How to use checksums |
d669ade68ddf03047f7c25b7b08d416ac98168a2af16024fb4a8175e7c9ff3b2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / outlook_multi_tenant_mcp-0.15.0-py3-none-any.whl
| Download URL | outlook_multi_tenant_mcp-0.15.0-py3-none-any.whl |
|---|---|
| Size | 123.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e49f43b0e9382be4b92e9ce8e8d92d9d2df9c1225c610e30180916537fabd6db
|
|
BLAKE2b-256 checksum How to use checksums |
360e5052cccba5a54f2948f6496623b8794db68daac693619b3fa95553539b4f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for outlook-multi-tenant-mcp 0.15.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.