mcp-m365
AGENTS.md0 starsChanged 3 days agoMITView on GitHub
Use Bun (>= 1.3) for installation, development, and tests; use bun run test, never bun test. The published dist/ servers run under Node (>= 22). Keep NODE_ENV=development confined to development and inspector commands; production configuration comes from the host environment. Keep configuration injectable: no module-level environment reads or configuration singleton. The MCP and OAuth servers each load configuration once and pass the smallest required slice into registration or implementation functions. Tool modules validate and adapt MCP envelopes only; implementation belongs…
- Reads credentials
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 32,671 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repositoryOne other file it gives its agents.
- CLAUDE.mdCLAUDE.md
The file
We split this AGENTS.md into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 5
Use Bun (>= 1.3) for installation, development, and tests.
- Very specific: line 17
Run bunx tsc --noEmit, bun run test, bun run test:coverage, bun run build, bun run ki:test:smoke, and the relevant focused ki repo audit …
- Very specific: line 78
Destructive tools expose
dry_run(defaulttrue): Every DESTRUCTIVE_REMOTE tool (m365_email_message_delete, … - Very specific: line 80
ensureAuthenticated()is the auth gate: Every Graph-calling handler must await ensureAuthenticated() first — it returns the access token …
≈ “Common” is an estimate: at least 1 in 5 of the 41,581 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
Runtime
Use Bun (>= 1.3) for installation, development, and tests; use bun run test, never bun test. The published dist/ servers run under Node (>= 22). Keep NODE_ENV=development confined to development and inspector commands; production configuration comes from the host environment.
MCP architecture
Keep configuration injectable: no module-level environment reads or configuration singleton. The MCP and OAuth servers each load configuration once and pass the smallest required slice into registration or implementation functions. Tool modules validate and adapt MCP envelopes only; implementation belongs in src/main/. Register every tool through the annotation-driven access gate with an explicit annotation preset.
OAuth and data safety
Never log or return access or refresh tokens. Preserve atomic 0600 token storage, exact single-use OAuth state validation, strict provider and redirect validation, bounded attachment handling, and header-injection guards. Mutating tools expose safe defaults and tests use isolated fixtures rather than real Microsoft 365 accounts, mailboxes, calendars, drives, or token stores.
Verification
Run bunx tsc --noEmit, bun run test, bun run test:coverage, bun run build, bun run ki:test:smoke, and the relevant focused ki repo audit commands. Live OAuth and Microsoft Graph operations require explicit authority.
Repository-specific implementation guidance follows. User-facing setup and tool documentation live in README.md and docs/guides/.
Bun vs Node
This project uses Bun (≥ 1.3) for install and dev scripts, but the compiled dist/ runs under Node (≥ 22) — that's what Claude Desktop launches.
bun run test(NOTbun test— the latter invokes Bun's own runner instead of vitest).- Bun auto-loads
.env.${NODE_ENV}from the CWD; Node needs the explicitprocess.loadEnvFile()call insideloadConfig()in src/config/index.ts. The try/catch swallows theTypeErrorBun raises (noprocess.loadEnvFile), so the same code works under both. NODE_ENVis set todevelopmentonly byserver:*:devandki:server:mcp:inspect. Claude Desktop doesn't set it, so.env.*is ignored in production —MCP_M365_CLIENT_ID/MCP_M365_CLIENT_SECRETmust come from the Claude Desktop configenvblock.
Run bun run with no args for the full script list. bun run ki:test:smoke boots the server over stdio and asserts the wire-level tool surface matches EXPECTED_TOOLS in scripts/smoke.ts — keep that list in sync when adding or removing tools. It also asserts the live protocol profile: modern era, negotiated 2026-07-28, a complete server/discover envelope, a real tools/call round trip, argument rejection, and that a deliberately legacy client still sees the identical surface. Source audit deliberately does not require a local discovery literal, so this script is the only place those claims are proved.
Architecture Invariants
Project layout & config injection (the workspace MCP shape)
This is the canonical layout we roll out across the MCPs:
- src/config/index.ts —
loadConfig(env?) → Config. Reads env (optionally hydrated from.env.${NODE_ENV}) into a plainConfigvalue. There is no module-level config singleton — nothing readsprocess.envat import time. Genuinely static, non-env constants (server name/version,GRAPH_API_ENDPOINT, the$selectfield lists, page-size defaults,M365_DEFAULT_SCOPES,AccessLevel/AuditLogModetypes + rank tables) stay as plain module exports — they read no env and never differ per run. - src/mcp-server/index.ts — the stdio MCP wrapper. Calls
loadConfig()once, then threadsConfiginto the access gate, the shared token storage (initTokenStorage(config)), and tool registration. Startup logging reads fromconfig. The stdio boundary is the SDK'sserveStdio(createServer, { legacy: 'serve' })on the modern 2026-07-28 profile:createServeris a per-connection factory, so theMcpServerinstance, the access gate wrapped around it, and the sevenregister*Tools(...)calls all belong to one connection. Connection-independent state (config, token storage, the Graph and triage contexts) stays at module scope above the factory — rebuilding token storage per connection would fragment the refresh path.legacy: 'serve'is a deliberate retention while the fleet migrates, not an oversight. - src/auth-server/index.ts — the OAuth callback server, a second top-level entry. Also calls
loadConfig()once at boot and usesconfig.auth. - src/tools/ — MCP tool definitions, one
index.tsper<service>(auth,calendar,email,folder,onedrive,rules). These are thin: eachserver.registerTool(...)call declares the zodinputSchema(+outputSchemawhere the tool returnsstructuredContent), the annotation preset, and a handler imported frommain/. There is no logic and no non-index.tsfile undersrc/tools/— everything else moved tomain/. Alltools/**/index.tsare coverage-excluded. - src/main/ — the real implementation, grouped by concern, each with an
index.tsre-export and surfaced via the packageexportsmap:main/email/,main/folder/,main/calendar/,main/onedrive/,main/rules/,main/triage/(them365_*handlers), plusmain/graph-client/index.ts(the Microsoft Graph HTTP layer),main/auth/index.ts(legacy-shaped token persistence with public MSAL acquisition/refresh, the config-injectedcreateTokenStorage(cfg)factory, andensureAuthenticated), andmain/auth/handlers.ts(m365_about/m365_auth_start/m365_auth_status).main/functions take their config slice (or the specific primitive) and contain noconsole.*— they return data; the tool layer maps it to an envelope and onlymcp-server/stderr prints. Concern modules are unit-tested to 100% on all four coverage metrics. - src/utils/ — cross-MCP reusable helpers; keep in sync with sibling repos. These take the specific config primitive/slice they need (
makeAccessGatedRegister(server, accessLevel, audit),withAuditLog(auditConfig, …)), not the wholeConfig, so they stay MCP-agnostic. Likemain/, these return data rather than print — the one sanctioned exception isaudit-log.ts, which writes a single stderr line if (and only if) writing the audit log itself fails, since a broken log must never abort a tool call.
To use the code from a script: const cfg = loadConfig(); const ts = createTokenStorage(cfg).
This dependency direction is enforced, not just described: .dependency-cruiser.ts states each boundary as a named rule and src/boundaries.test.ts cruises the source graph and proves every rule still rejects a deliberate crossing. The checker runs from its own install root, tooling/depcruise, because dependency-cruiser needs a TypeScript below 7.
Two processes
mcp-m365— the stdio MCP server (entry:dist/mcp-server/index.js).mcp-m365-auth— long-running OAuth callback server on:3333(entry:dist/auth-server/index.js). Must be up to complete them365_auth_startflow.
Token persistence is repository-owned in src/main/auth/index.ts; src/main/auth/msal.ts uses pinned MSAL public acquisition APIs and its supported network transport. The existing legacy JSON remains authoritative, and a fresh transient MSAL client never serializes its cache. Both writers share bounded cross-process locking and reload inside the lock before acquisition; refresh retains the in-process single-flight promise. createTokenStorage(cfg) and makeEnsureAuthenticated(storage) remain config-injected factories with no module-level token singleton.
Naming convention
Tool names follow the canonical workspace scheme <app>_<resource>_<action> (snake case) with <app> = m365. In this repo the <resource> is compound — a <service>_<thing> pair with <service> ∈ {email, calendar, onedrive} — so a full name reads as m365_email_message_get, m365_calendar_event_create, m365_onedrive_item_upload. Plural resource for collection ops (m365_email_messages_list), singular for single-item ops (m365_email_message_get). The auth/metadata tools (m365_about, m365_auth_start, m365_auth_status) drop the resource segment.
Access-level gate — driven by annotations, not names
src/utils/access-level.ts makeAccessGatedRegister(server, accessLevel, audit) decides at startup whether to register each tool, based on config.annotations:
readOnlyHint: true→readdestructiveHint: true→destructive- explicit
readOnlyHint: falseANDdestructiveHint: false→write(non-destructive Graph mutation) - anything else (unannotated / partially annotated) →
destructive(fail-safe)
A tool registers when its derived level is at or below MCP_M365_ACCESS_LEVEL (default: read). Levels nest: read registers only readers; write adds non-destructive mutations like m365_email_message_send and m365_calendar_event_create; destructive adds delete/overwrite. New tools MUST set annotations to one of the presets in src/utils/annotations.ts — READ_ONLY/READ_ONLY_REMOTE for pure reads; WRITE_REMOTE/WRITE_IDEMPOTENT_REMOTE for non-destructive Graph mutations; DESTRUCTIVE_REMOTE for deletes whose end state is the same however often they run; DESTRUCTIVE_ONESHOT_REMOTE where a repeat does more work rather than converging (the batch-bounded routing passes, which process the next batch on each call). Annotations must be honest about what the tool does — m365_auth_start is WRITE_REMOTE (not READ_ONLY_REMOTE) because it persists tokens to disk; misrepresenting it would silently classify it as read under the gate. Do not bypass the proxy.
Security Requirements
This server holds OAuth refresh tokens that grant Outlook read/write/send, Calendar read/write, and OneDrive read/write across the user's tenant. Token leakage = mailbox + drive compromise. Destructive Graph operations cannot be undone via Graph itself. New tools and changes to existing tools MUST preserve every invariant below.
- Tokens are never logged. src/main/auth/index.ts does not print at all — as a
main/layer it returns/throws data rather than logging (a missing/unreadable token cache is reported by anullreturn; an unconfigured OAuth client surfaces as a thrown error fromexchangeCodeForTokens/refreshAccessToken).m365_auth_statusreturns presence + scope + expiry only. Any future error surfacing must carry only safe fields (error.code,error.message) and never token contents. - Token persistence is atomic and
0600._saveTokensToFile()writes to<path>.tmp.<pid>.<rand>thenfs.renameinto place; both temp and final files usemode: 0o600. Refresh and exchange flows both go through_saveTokensToFileinside the shared token-operation lock — keep it that way. A failed acquisition or save preserves the prior on-disk file; publish in-memory tokens only after the atomic rename succeeds. - Refresh deduplication.
_refreshPromiseensures concurrentgetValidAccessToken()callers share a single refresh request. New auth code must preserve the dedupe — without it a burst of tool calls would race for token persistence. - All Zod schemas are
.strict()with bounded numerics. Already true; new schemas must continue this — e.g.countisz.number().int().positive().max(50)for calendar/onedrive listings,.max(1000)for email;sequence(rule ordering) is.min(0).max(10000). - Destructive tools expose
dry_run(defaulttrue). EveryDESTRUCTIVE_REMOTEtool (m365_email_message_delete,m365_calendar_event_{delete,cancel,decline},m365_email_folder_delete,m365_onedrive_item_delete) returns a[dry_run] would …preview by default and only mutates when the caller passesdry_run: false. - OneDrive caller-supplied paths must go through
sanitizeOneDrivePath()in src/utils/odata-helpers.ts before interpolation intome/drive/root:/...endpoints. It strips outer slashes, splits on/, rejects:/\/empty/./..segments, andencodeURIComponents each remaining segment. Never interpolate raw paths. ensureAuthenticated()is the auth gate. Every Graph-calling handler mustawait ensureAuthenticated()first — it returns the access token (refreshing if needed). Bypassing it (e.g. readingtokenStorage.tokensdirectly) risks expired tokens AND ignores the refresh-dedup machinery.- 401 hint surfaces remediation.
errMessage()in src/utils/errors.ts appendsAUTH_HINTon 401 (or matching message keywords): the browser sign-in route through the callback server's/authpage first, thenm365_auth_startqualified by thewriteaccess level it needs. Handlers with no usable token returnAUTH_REQUIRED_MESSAGE, built from the same hint. New tools must useerrorResult(action, err)so this contract holds. - No shell-string interpolation. This server doesn't shell out. If a future tool needs to, use
execFilewith an argv array. - If a future tool writes Graph response bytes to disk, add a configurable download root (e.g.
MCP_M365_DOWNLOAD_PATH, default~/Downloads) and validateoutputPathvia a two-layer (lexical + realpath) helper, mirroringassertOutputPathWithinDownloadRoot()in mcp-gmail. Today,m365_onedrive_item_downloadreturns a pre-authenticated URL rather than writing bytes. - Full URLs are host-pinned before the Bearer token is attached (SSRF — workspace standard §13.5).
callGraphAPIonly ever receives a full URL via an@odata.nextLinkechoed back in a prior Graph response; that value is server-controlled and treated as untrusted.assertGraphUrl()in src/main/graph-client/index.ts asserts the scheme ishttps:and the host is exactlygraph.microsoft.com(derived fromGRAPH_API_ENDPOINT) before the token is sent, so a forged/tampered nextLink can never exfiltrate the access token to another origin. Never bypass it when following pagination.
Atomic-write, mode-0600, refresh-dedup, and nextLink host-pin tests live in src/main/auth/index.test.ts and src/main/graph-client/index.test.ts; the redacted m365_auth_status summary is tested in src/main/auth/handlers.test.ts.
Tool registration call sites
Each <service> registers its tools in src/tools/<service>/index.ts (auth, calendar, email, folder, onedrive, rules, triage). To survey the surface, grep "registerTool" src/tools/*/index.ts. README's Available Tools tabulates them with purposes.
Email routing engine (main/triage/)
A deterministic replacement for LLM-interpreted email triage: rules are data, the engine is code. Six things about it are load-bearing and easy to break.
- The server holds no rule state. Rules either arrive as a string in the call or are read at call time from a path; either way the caller's rule file is canonical and is re-read every time. Do not add server-side rule storage or caching.
- Every filesystem path goes through
assertWithinRoots(). Rules and tracking paths may be supplied per call, so the allowlist in src/utils/paths.ts is the only thing standing between a tool argument and arbitrary file access. It is deliberately two-layer — lexicalresolvethenrealpath— because the knowledge base symlinksPillars/*into a separate repository, and a lexical-only check is defeated by a symlink inside a root pointing out of it. Never read or write an engine path that has not been through it. - Message identity is subject + sender + received timestamp, never the Graph id. Graph reissues ids on folder moves, so an id is a cache hint that
findMessagere-verifies before any mutation — and amovereissues the id again, which is whyapplyOnethreads the new one into the actions that follow. - Calls are batch-bounded and resumable, never long-running.
maxActionscaps mutations per call and the result reportsremaining; the caller loops. For the triage and aged passes progress is implicit — classification moves a message out of the folder being scanned, so a re-run finds less work. The drift scan has no such natural progress (it re-reads the same cache), so it carries an explicit sweep cursor:scanned_atper entry plus asweep.started_atmarker on the file.remainingmust count what is outstanding in the current sweep and reach zero when the sweep completes — aremainingderived fromtotal - batchSizeis a constant and makes the documented polling loop non-terminating. - Ordering is the whole specification. The list is flat and first-match-wins, so the two lint checks that matter are
shadowed-rule(a rule that can never fire) andbroad-rule-collision(a content-agnostic rule sitting above the specific rules it will swallow — the class of bug that sent project calendar invites to the action folder). A reviewed collision is silenced with a# lint:allow-collisioncomment on the rule, not by weakening the check. - Cross-message lookups are lazy and resolved before matching.
thread:filedandmove:@threadneed another message's folder, which is Graph I/O, so the run layer looks the conversation up (listConversation, cached per call) and writes the answer onto the record as plain data; the pure lookups.ts decides which folders count as filed from the rule file itself. A lookup happens only for a message whose lookup-free classification lands at or below the first rule that teststhread:, so a rule file without one makes no extra call and routes exactly as before.forwarded-to:follows the same pattern:searchForwardsandattachmentNamesare cached per call, the pureforwardCandidatesfilter decides, and the search runs only for an address in a group whose other terms already hold at or above the current match, so the aged pass does not search for every message. Keep any future cross-message predicate on the same pattern.
Categories follow the same rule: category: reads the categories Graph already returns with the message, so it needs no lookup. Category names are provider-free and compared case-insensitively, and the optional ```categories block holds names only — a key = value line there is reserved for a provider setting such as a Gmail label prefix, so keep it refused until that setting exists. hold is the one action that claims a message without acting on it: it must never reach applyActions, count towards maxActions, or be tracked.
parser.ts, matcher.ts, lint.ts, folders.ts and lookups.ts are pure — no clock, no Graph, no I/O (age: takes an injected now). Keep them that way: semantics.test.ts pins the behaviour classes the Phase 3 replay found against exactly the code that runs live, and that only holds while classification is a pure function. Its fixture, fixtures/routing/example-rules.md, is synthetic, on reserved domains, and never a copy of a real rule file; a real file is validated in place with the m365_email_routing_lint tool.
MCP spec conformance
This server targets MCP spec revision 2025-11-25 (the latest released revision; see the workspace MCP standard §12–13). Tool-execution errors are returned as isError: true envelopes via errorResult (never thrown), and structured output is paired with an outputSchema (below).
RFC 8707 resource/aud audience validation is deliberately N/A here. That requirement (spec §13 item 7, AUTH 2025-11-25) governs a server acting as a remote HTTP OAuth resource server — validating that an inbound bearer token's audience is itself. This server is an OAuth client of Microsoft Graph, runs over stdio, and obtains its own tokens via the loopback consent flow: no caller-supplied bearer ever crosses the client↔server boundary, so there is nothing to audience-validate. The live token-passthrough defence is that we never accept or forward a caller-supplied token (we only use tokens issued to ourselves for Graph). This goes live only if the server is ever deployed as a remote resource server. Likewise, Client ID Metadata Documents (§13 item 8) apply only to an authorization-server role we do not occupy.
Structured output (spec §12)
Tools that emit structuredContent — message list/search, folder list, and attachment list/get — pair it with a matching outputSchema at registration. The schema and emitted object use the same Zod result schema in their implementation and registration. Message and folder listings retain permissive Graph-item shapes; attachment results use strict metadata and file shapes so no extra bytes slip into a metadata list. The handlers also keep a serialized-text content block. A new tool that returns structuredContent MUST declare its outputSchema from the same Zod schema.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

