agentleFS
knowledgeislandsknowledgeislands/mcp-m365/AGENTS.md

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.

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
  1. Very specific:

    Use Bun (>= 1.3) for installation, development, and tests.

    line 5
  2. Very specific:

    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 …

    line 17
  3. Very specific:

    Destructive tools expose dry_run (default true): Every DESTRUCTIVE_REMOTE tool (m365_email_message_delete, …

    line 78
  4. Very specific:

    ensureAuthenticated() is the auth gate: Every Graph-calling handler must await ensureAuthenticated() first — it returns the access token …

    line 80

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

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 (NOT bun test — the latter invokes Bun's own runner instead of vitest).
  • Bun auto-loads .env.${NODE_ENV} from the CWD; Node needs the explicit process.loadEnvFile() call inside loadConfig() in src/config/index.ts. The try/catch swallows the TypeError Bun raises (no process.loadEnvFile), so the same code works under both.
  • NODE_ENV is set to development only by server:*:dev and ki:server:mcp:inspect. Claude Desktop doesn't set it, so .env.* is ignored in production — MCP_M365_CLIENT_ID / MCP_M365_CLIENT_SECRET must come from the Claude Desktop config env block.

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 plain Config value. There is no module-level config singleton — nothing reads process.env at import time. Genuinely static, non-env constants (server name/version, GRAPH_API_ENDPOINT, the $select field lists, page-size defaults, M365_DEFAULT_SCOPES, AccessLevel/AuditLogMode types + 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 threads Config into the access gate, the shared token storage (initTokenStorage(config)), and tool registration. Startup logging reads from config. The stdio boundary is the SDK's serveStdio(createServer, { legacy: 'serve' }) on the modern 2026-07-28 profile: createServer is a per-connection factory, so the McpServer instance, the access gate wrapped around it, and the seven register*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 uses config.auth.
  • src/tools/ — MCP tool definitions, one index.ts per <service> (auth, calendar, email, folder, onedrive, rules). These are thin: each server.registerTool(...) call declares the zod inputSchema (+ outputSchema where the tool returns structuredContent), the annotation preset, and a handler imported from main/. There is no logic and no non-index.ts file under src/tools/ — everything else moved to main/. All tools/**/index.ts are coverage-excluded.
  • src/main/ — the real implementation, grouped by concern, each with an index.ts re-export and surfaced via the package exports map: main/email/, main/folder/, main/calendar/, main/onedrive/, main/rules/, main/triage/ (the m365_* handlers), plus main/graph-client/index.ts (the Microsoft Graph HTTP layer), main/auth/index.ts (legacy-shaped token persistence with public MSAL acquisition/refresh, the config-injected createTokenStorage(cfg) factory, and ensureAuthenticated), and main/auth/handlers.ts (m365_about / m365_auth_start / m365_auth_status). main/ functions take their config slice (or the specific primitive) and contain no console.* — they return data; the tool layer maps it to an envelope and only mcp-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 whole Config, so they stay MCP-agnostic. Like main/, these return data rather than print — the one sanctioned exception is audit-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 the m365_auth_start flow.

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 → read
  • destructiveHint: true → destructive
  • explicit readOnlyHint: false AND destructiveHint: 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.

  1. 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 a null return; an unconfigured OAuth client surfaces as a thrown error from exchangeCodeForTokens/refreshAccessToken). m365_auth_status returns presence + scope + expiry only. Any future error surfacing must carry only safe fields (error.code, error.message) and never token contents.
  2. Token persistence is atomic and 0600. _saveTokensToFile() writes to <path>.tmp.<pid>.<rand> then fs.rename into place; both temp and final files use mode: 0o600. Refresh and exchange flows both go through _saveTokensToFile inside 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.
  3. Refresh deduplication. _refreshPromise ensures concurrent getValidAccessToken() 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.
  4. All Zod schemas are .strict() with bounded numerics. Already true; new schemas must continue this — e.g. count is z.number().int().positive().max(50) for calendar/onedrive listings, .max(1000) for email; sequence (rule ordering) is .min(0).max(10000).
  5. Destructive tools expose dry_run (default true). Every DESTRUCTIVE_REMOTE tool (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 passes dry_run: false.
  6. OneDrive caller-supplied paths must go through sanitizeOneDrivePath() in src/utils/odata-helpers.ts before interpolation into me/drive/root:/... endpoints. It strips outer slashes, splits on /, rejects :/\/empty/./.. segments, and encodeURIComponents each remaining segment. Never interpolate raw paths.
  7. ensureAuthenticated() is the auth gate. Every Graph-calling handler must await ensureAuthenticated() first — it returns the access token (refreshing if needed). Bypassing it (e.g. reading tokenStorage.tokens directly) risks expired tokens AND ignores the refresh-dedup machinery.
  8. 401 hint surfaces remediation. errMessage() in src/utils/errors.ts appends AUTH_HINT on 401 (or matching message keywords): the browser sign-in route through the callback server's /auth page first, then m365_auth_start qualified by the write access level it needs. Handlers with no usable token return AUTH_REQUIRED_MESSAGE, built from the same hint. New tools must use errorResult(action, err) so this contract holds.
  9. No shell-string interpolation. This server doesn't shell out. If a future tool needs to, use execFile with an argv array.
  10. If a future tool writes Graph response bytes to disk, add a configurable download root (e.g. MCP_M365_DOWNLOAD_PATH, default ~/Downloads) and validate outputPath via a two-layer (lexical + realpath) helper, mirroring assertOutputPathWithinDownloadRoot() in mcp-gmail. Today, m365_onedrive_item_download returns a pre-authenticated URL rather than writing bytes.
  11. Full URLs are host-pinned before the Bearer token is attached (SSRF — workspace standard §13.5). callGraphAPI only ever receives a full URL via an @odata.nextLink echoed 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 is https: and the host is exactly graph.microsoft.com (derived from GRAPH_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.

  1. 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.
  2. 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 — lexical resolve then realpath — because the knowledge base symlinks Pillars/* 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.
  3. 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 findMessage re-verifies before any mutation — and a move reissues the id again, which is why applyOne threads the new one into the actions that follow.
  4. Calls are batch-bounded and resumable, never long-running. maxActions caps mutations per call and the result reports remaining; 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_at per entry plus a sweep.started_at marker on the file. remaining must count what is outstanding in the current sweep and reach zero when the sweep completes — a remaining derived from total - batchSize is a constant and makes the documented polling loop non-terminating.
  5. 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) and broad-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-collision comment on the rule, not by weakening the check.
  6. Cross-message lookups are lazy and resolved before matching. thread:filed and move:@thread need 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 tests thread:, so a rule file without one makes no extra call and routes exactly as before. forwarded-to: follows the same pattern: searchForwards and attachmentNames are cached per call, the pure forwardCandidates filter 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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.