npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@aidalinfo/m365-mcp

v0.6.2

Published

Microsoft 365 MCP server over Microsoft Graph — Entra ID users, groups and applications, licences, Teams, SharePoint, usage reports, service health, roles, MFA, audit, access review, shared mailbox delegation (Exchange Online). Read-only by default; full

Readme

@aidalinfo/m365-mcp

MCP server for Microsoft 365 through Microsoft Graph v1.0: Entra ID users and groups, licences, Microsoft Teams, SharePoint, usage reports, service health, admin roles, MFA, applications and consents, audit logs, Conditional Access, Intune — for helpdesk support and a periodic access review (one-call snapshot compared with the previous one) — with targeted, audited writes.

  • readonly (default): read tools only. The write identity is not even loaded.
  • full: read tools plus targeted write tools (user attributes from an allowlist, enable/disable account, licences, group members, team members, channels, team settings), signed by a separate Entra application, per family (M365_WRITE_FAMILIES). The optional entra-applications family is absent by default and uses a third dedicated identity; the optional exchange-delegation family (Full Access / Send As on shared mailboxes) is absent by default and uses its own Exchange Online identity.

There is no raw Graph request tool (neither read nor write) and no beta endpoint. Entra application management is limited to allowlisted application/service-principal properties. Public certificate metadata and federated identity credentials are read-only in v1. V1 has no certificate or federated-credential write, deletion, client-secret creation/return, private-key handling, programmatic consent, app-role-assignment or OAuth2-grant write.

Agent Pulse / Vulcain
        │  MCP (stdio)
        ▼
@aidalinfo/m365-mcp ── allowlisted, validated tools ── two-step writes ── audit (JSON lines)
        │  client credentials (federation → certificate → secret)
        ▼
Microsoft Graph v1.0
        │
        ├── Entra app "m365-mcp-read"   (every mode — read permissions only)
        ├── Entra app "m365-mcp-write"  (full mode only — general write permissions)
        └── Entra app "m365-mcp-entra"  (optional entra-applications family only)

Exchange Online (InvokeCommand)
        └── Entra app "m365-mcp-exchange" (optional exchange-delegation family only — no Graph token)

Do not reuse Pulse Chat's Microsoft SSO application, nor the application behind personal Outlook / calendar connectors: these identities are dedicated to this server.

Tools

Read (every mode)

| Tool | What | |---|---| | m365_capabilities | Mode, tenant, identities (client id, auth method, certificate thumbprint & expiry), application permissions found in each token, and per tool whether its permission is granted. Start here. | | m365_organization | Tenant name/type/country, verified domains, Entra Connect sync state | | m365_users | Users, paginated — filters: search (prefix of name/UPN/mail), accountEnabled, userType, department, licensed, skuId; fields from an allowlist | | m365_user_info | One user: allowlisted attributes, licences with names and direct/group assignment | | m365_subscribed_skus | Licences purchased, consumed, available, suspended, in warning (+ service plans) | | m365_license_assignments | Licences of a user: direct vs inherited, state/errors, disabled plans, capability status of each assigned service plan (from assignedPlans — licenseDetails is delegated-only and not used) | | m365_groups / m365_group_info / m365_group_members | Groups (by kind: Microsoft 365, security, distribution, dynamic, team), details + owners + count, members (direct or transitive) | | m365_teams / m365_team_info | Teams, and one team's settings (member, guest, messaging, fun) | | m365_team_channels | Channels (standard / private / shared) with ids | | m365_team_members | Members with role (owner / member / guest) and membership id | | m365_channel_members | Members of a channel — private and shared channels have their own members, absent from the team's; shared channels show the external tenant | | m365_usage_reports | Storage per mailbox / OneDrive / SharePoint site (bytes and GB), mailbox type (User, Shared, Room… — the Graph CSV has no type column: resolved through MailboxSettings.Read or the phase-2 exchange feature, otherwise an explicit permission_missing), last activity per service — filters search, recipientType, withMailboxType, inactiveDays, sort by size. Concealed (anonymised) names are detected and flagged | | m365_service_health | Service state, open incidents / advisories, message center — "is it us or Microsoft?" | | m365_sites / m365_site_info | Every SharePoint site (with or without Teams); one site's libraries with size / quota and its linked Microsoft 365 group | | m365_sharing_links | Sharing links and external grants on one folder (bounded walk: depth ≤ 3, ≤ 200 items) — flags anonymous links, links without expiry, external people; link URLs are never returned | | m365_directory_roles | Who is admin of what (active assignments with principal and scope); view=eligible = PIM (Entra ID P2) | | m365_user_auth_methods | MFA methods of a user (types only — never a phone number or key); without user, the tenant MFA registration report (Entra ID P1) | | m365_user_activity | Last sign-in of each account, dormant accounts (inactiveDays) — Entra ID P1 | | m365_directory_audit | Who changed what in the directory (users, groups, roles, licences, apps) — 7 days of history without P1, 30 with; property values never returned | | m365_applications | Enterprise applications (third party / own), application permissions granted to one, delegated consents (DelegatedPermissionGrant.Read.All) | | m365_conditional_access | Conditional Access policies (Entra ID P1) and security defaults | | m365_intune_devices | Intune managed devices: compliance, encryption, last sync, primary user — Intune licence | | m365_access_review_snapshot | Access review in one call — see below | | m365_audit_signins | Sign-in logs — only with M365_ENABLE_SIGNIN_AUDIT=true, needs Entra ID P1/P2 |

Tools that need a premium licence

| Licence | Tools (or parts) | Without it | |---|---|---| | Entra ID P1 (Business Premium, E3/E5, standalone) | m365_user_activity, m365_user_auth_methods tenant view, m365_conditional_access policies, m365_audit_signins; in the snapshot: last sign-in and the tenant MFA report | unsupported_by_tenant (the snapshot falls back to the admins' own methods for MFA and marks inactivity as not evaluated) | | Entra ID P2 | m365_directory_roles view=eligible (PIM) | unsupported_by_tenant (see PIM control unavailable below) | | Intune (Business Premium, EMS) | m365_intune_devices | unsupported_by_tenant |

The tools stay registered on every tenant. m365_capabilities reads the tenant's service plans (AAD_PREMIUM, AAD_PREMIUM_P2, INTUNE_*) and reports such tools as unsupported_by_tenant (needs …) rather than as a missing permission. m365_directory_audit works without P1, with 7 days of retention.

Access review — m365_access_review_snapshot

One call (hundreds of Graph calls, at most 4 in flight) produces the full picture of the tenant: users (state, type, licences, last sign-in with P1, MFA), subscribed licences, every group and team with owners and members, members of private and shared channels, admin roles, enterprise applications with their application permissions and delegated consents, storage per account and per site.

  • Output: a dated JSON file m365-review-<tenant>-<timestamp>.json in M365_SNAPSHOT_DIR (mode 0600: it holds names and memberships), plus a bounded summary (maxItems per list).
  • Comparison: compareWith: "latest" (or a file name from that directory — never a path) lists accounts created / deleted / disabled / re-enabled, new guests, entries and exits of groups, teams and private channels, new and removed owners, new and removed admins, licences reassigned, new applications and newly consented permissions. Each change depends on named sections in both snapshots (users; users + skus for licences; groups; groups + channels for entries, exits and new owners; roles; applications): one of them not read on either side makes that change NOT compared — with the reason — never a list of accounts, groups or admins "created" or "deleted". Only exception, channels: without it (typically ChannelMember.Read.All missing) the entries, exits and new owners of groups and teams are still compared; the private/shared channels are left out, named (as read in the other snapshot), and the change is ⚠ partial. Without groups they stay NOT compared. A truncated list (10 000 accounts, 2 000 groups, 2 000 role assignments, 300 applications) creates or deletes nothing for the objects present on one side only, and the change is ⚠ partial; a group or private channel whose members were cut is left out of entries and exits and named; delegated consents not read leave the delegated grants out. The summary says how many changes were NOT compared, which is never no change.
  • Signals: Microsoft 365 group or team without owner, guest owner, disabled account still member or licensed, account inactive for 90+ days (inactiveDays), shared mailbox holding a licence or able to sign in, admin without MFA, guest admin.
  • A section that cannot be read (missing permission, licence) is listed under Sections NOT read and its signals are not evaluated — never reported as "none".

Every list tool takes limit (default 25, server maximum 100), an opaque cursor for the next page, structured filters (no free-form OData; strings are escaped server-side) and format: summary | json. Selected fields come from a server-side allowlist: credentials, authentication methods, personal phone numbers, alternate e-mails and on-premises identifiers are never requested.

HTTP redirects are never followed (redirect: "error", Graph and token endpoint): only validated Graph URLs are called, and a 307 could otherwise replay a mutation elsewhere. Single exception, GET only: usage reports answer 302 to a pre-authenticated CSV download URL. That URL must be https on a Microsoft reports host (*.office.com, *.office.net, *.office365.com, *.microsoft.com); it is fetched without the Graph token, with redirects refused, and never returned to the caller.

Cursors are server-side: the caller holds a random id, never a URL, so pagination cannot be pointed at another resource; every @odata.nextLink is checked to stay on https://graph.microsoft.com/v1.0/ before it is followed. A cursor is bound to its tool (and to the group / team for member and channel lists) and expires after 30 minutes.

A refused or unavailable API never looks like an empty list — the tool answers an explicit error:

| Code | Meaning | |---|---| | permission_missing | 403 — the application lacks the Graph permission (or admin consent), see m365_capabilities | | rbac_denied | Exchange accepted the token but its own role model refused: the identity's Exchange role group does not hold the cmdlet / parameter, or Exchange knows no role for the application. Fix the role group — never a broader admin role (README → Exchange mailbox audit) | | unsupported_by_tenant | The tenant cannot serve this (no Entra P1 for sign-ins, no Teams licence…) | | license_unavailable | No free unit, SKU not enabled, or a licence prerequisite (usage location, plan dependency) | | not_found / ambiguous_target | Nothing matches / several objects match a name — pass the id | | conflict | Already exists, concurrent change, precondition failed | | throttled / transient | 429 after the bounded retries (with Retry-After) / 5xx, timeout, network | | service_error | Microsoft answered a 4xx that only carries one of its own internal exceptions (e.g. UnknownError / CultureNotFoundException on the PIM API). The result is unknown: it proves neither a missing licence, nor a missing permission, nor an empty list | | auth_failed / tenant_mismatch / forbidden_permission | Token refused / token for another tenant or app / token carries a permission refused by policy | | refused / confirmation_invalid | A guard refused the write / the confirmation token is expired, reused, or the state changed |

PIM control unavailable. m365_directory_roles view=eligible concludes to a missing Entra ID P2 licence only when Graph says so or refuses while the subscribed SKUs carry no AAD_PREMIUM_P2 plan. The PIM back end has also been seen answering HTTP 400 UnknownError / CultureNotFoundException ("Culture is not supported … * is an invalid culture identifier"): that is reported as service_error with the status, Graph's code and the request ids. It says nothing about the licence, the eligible roles or the application's rights — report the PIM control as not performed, never as "no eligible role", and do not add permissions or roles to work around it. Node's fetch sends Accept-Language: * when no language is set, so the server names Accept-Language: en-US on this PIM request only (no other Graph call, no retry); whether * was the cause on the affected tenant has not been confirmed there.

Each error carries Microsoft's request-id (quote it to Microsoft support) and the client-request-id the server sent. The raw Graph body is never returned.

Write (M365_MODE=full, per family)

| Tool | Family | What | Guards | |---|---|---|---| | m365_user_update | users | Set allowlisted attributes: displayName, givenName, surname, jobTitle, department, officeLocation, companyName, city, country, usageLocation, preferredLanguage | Strict schema: any other key (UPN, mail, password, accountEnabled, on-prem…) is rejected | | m365_user_set_account_enabled | users | Enable / disable sign-in (nothing is deleted) | — | | m365_user_assign_licenses | licenses | Add and/or remove licences in one call, optional disabled plans (by name or id) | Free units checked, usageLocation required, group-inherited licences cannot be removed on the user | | m365_group_member_add / _remove | groups | Direct membership of a user | Refuses dynamic, AD-synced, role-assignable, Exchange-managed (distribution / mail-enabled security) and team-backed groups (use the team tools, which protect owners and archived teams) | | m365_team_member_add / _remove | teams | Team membership, role member only | Refuses archived teams, disabled accounts, and removing an owner | | m365_team_channel_create | teams | Standard channel | No-op if the name exists; never retried on 5xx (no duplicate) | | m365_team_channel_update | teams | Rename / describe a channel | General channel cannot be renamed | | m365_team_settings_update | teams | Allowlisted member / guest / messaging / fun settings | Strict schema | | m365_entra_applications / _application_info | entra-applications | Typed application-registration inventory/details; _info adds the OAuth configuration: spa.redirectUris, web.redirectUris (+ homePageUrl, logoutUrl, implicit grant), identifierUris, public scope metadata | Dedicated identity; response and nested collections bounded (50 URIs per list, 20 scopes, oauthTruncated when cut); certificate material reduced to public metadata; no secret, no pre-authorization detail | | m365_entra_service_principals / _service_principal_info | entra-applications | Typed enterprise-application inventory/details | Dedicated identity; allowlisted fields only | | m365_entra_application_requested_permissions / _service_principal_effective_permissions | entra-applications | Requested permissions and read-only inspection of effective app-role assignments / delegated grants | Effective delegated grants additionally require read-only Directory.Read.All; never grants consent or writes assignments/grants | | m365_entra_application_federated_credentials | entra-applications | First 20 federated identity credentials | Application ownership is verified first; no external token or secret is read | | m365_entra_application_create / _update | entra-applications | Idempotent application upsert by URL-safe uniqueName, or update allowlisted scalar properties | requiredResourceAccess is deliberately absent from write schemas; ownership by the dedicated identity; no delete, secret or private key | | m365_entra_application_redirect_uris | entra-applications | Add / remove SPA or Web redirect URIs (platform: spa or web, changes: { add, remove }) | Owned application only; targeted edit: other URIs and the other platform are preserved (the Web platform is sent back whole, homePageUrl, logoutUrl, implicit grant kept); https only, http://localhost / 127.0.0.1 / [::1] only with allowLocalhost: true; wildcards, fragments, query strings, userinfo, percent-encoding, dot segments, IP literals, non-ASCII / bidi / control characters and normalized duplicates (case of scheme/host, default port, trailing /) refused before any write; SAML-indexed redirectUriSettings refused | | m365_entra_application_identifier_uris | entra-applications | Add / remove identifier URIs (Application ID URI) | Exactly api://<appId of this application> or https on a DNS name (verified domain enforced by Entra); removing the last one while scopes are enabled is refused | | m365_entra_application_oauth2_scope_upsert | entra-applications | Create or update one delegated scope (api.oauth2PermissionScopes) keyed by its value | Stable id (existing id kept, otherwise derived from appId + value); other scopes, preAuthorizedApplications and API settings sent back unchanged; strict schema (no id, secret or consent field), bounded texts without control / bidi characters, reserved OIDC values refused; no deletion (isEnabled: false disables); never creates a consent or an OAuth2 permission grant | | m365_entra_service_principal_create / _update | entra-applications | Idempotent service-principal upsert by appId, or update allowlisted scalar properties | Both the linked application and service principal must be owned; no role assignment or consent write | | m365_mailbox_delegation_add / _remove | exchange-delegation | Give / remove a user's Full Access (with autoMapping, default true) or Send As on a shared mailbox; the preview lists who already holds the right | Shared mailboxes only (personal, room and equipment refused); guests and disabled accounts refused on add; explicit grants only (group-inherited rights untouched); dedicated identity, kill switch mandatory |

m365_group_create / m365_team_create are not in v1 (they would need Group.ReadWrite.All / Team.Create); add them later behind a dedicated flag if needed.

entra-applications bootstrap and ownership boundary

Create a third single-tenant app for this family and grant it exactly Application.ReadWrite.OwnedBy and read-only Directory.Read.All (admin consent). Any additional Graph application role is refused. Its client id must differ from the read and write identities. The family is not enabled unless entra-applications is explicitly present in M365_WRITE_FAMILIES, M365_ENTRA_* contains exactly one credential, and M365_WRITE_KILL_SWITCH_FILE is configured.

Application.ReadWrite.OwnedBy does not ownership-filter tenant-wide list responses. Therefore every mutation of an existing application re-reads /owners during preview and again immediately before the Graph mutation. Application creation with Application.ReadWrite.OwnedBy establishes ownership for the calling service principal by Graph; the server verifies that ownership after creation without requiring a broader owner-write permission; service-principal writes require both a linked, owned local application registration and ownership of the service principal itself. For a newly created service principal, the server establishes the dedicated identity as owner when Graph did not do so automatically, then verifies ownership. Federated-credential reads also verify ownership before reading the collection. The dedicated identity service principal itself must already exist in the tenant (normal after admin consent); inability to resolve it uniquely stops the operation. Newly created objects can be eventually consistent: post-write verification is retried only three times with bounded delays. For this family verification is fail-closed: if the mutation may have succeeded but ownership or the requested resulting state cannot be verified, the tool returns an error and the audit result is success_unverified, never the misleading values success or failed.

Hard exclusions remain: no deletion tools, no client-secret creation or return, no private-key input or output, no certificate or federated-credential write, no programmatic consent, no appRoleAssignment/oAuth2PermissionGrant write, and no raw Graph tool. Application.ReadWrite.All, AppRoleAssignment.ReadWrite.All, DelegatedPermissionGrant.ReadWrite.All and Directory.ReadWrite.All are refused for the dedicated identity even when M365_ALLOW_BROAD_PERMISSIONS=true.

exchange-delegation — shared mailbox Full Access / Send As

Graph has no API for mailbox permissions: this family calls Exchange Online through the same InvokeCommand endpoint as m365_mailbox_permissions (the one the ExchangeOnlineManagement v3 module uses), with a dedicated identity m365-mcp-exchange — or, since 0.4.1, the write application m365-mcp-write itself. It is registered only when exchange-delegation is explicitly listed in M365_WRITE_FAMILIES (full mode), with exactly one certificate or federated credential in M365_EXCHANGE_* (a client secret is a startup error), a client id different from the read, entra and audit identities, and M365_WRITE_KILL_SWITCH_FILE configured.

Reusing the write application (M365_EXCHANGE_CLIENT_ID = M365_WRITE_CLIENT_ID) is accepted: add Exchange.ManageAsApp to m365-mcp-write and give its enterprise app the scoped role group below. No Entra administrator role is needed (and one would be refused). The Exchange token is a separate token (Exchange audience) still checked for exactly Exchange.ManageAsApp; the Graph token of the app is unaffected. M365_EXCHANGE_* still needs its own certificate or federated file (it may be the same certificate as the write identity). Trade-off, shown as a startup warning: one compromised write credential also reaches shared-mailbox delegation.

| Lock | Where | |---|---| | Closed cmdlet list: Get-Mailbox, Get-MailboxPermission, Get-RecipientPermission, Add-/Remove-MailboxPermission (AccessRights FullAccess, InheritanceType All only), Add-/Remove-RecipientPermission (AccessRights SendAs only); closed, validated parameters | server | | Shared mailbox only, no guest / disabled trustee, no self-delegation, preview bound to the current holders | server | | Token: Exchange audience, exactly Exchange.ManageAsApp, never a Graph token; refused if the app holds a write-capable directory role (Exchange Administrator…) | server | | Kill switch checked before the preview, after the confirmation, and right before the cmdlet | server | | Custom role reduced to the seven cmdlets, write scope limited to shared mailboxes — even a bypass of the server cannot touch a personal mailbox | Exchange |

Send on behalf (Set-Mailbox -GrantSendOnBehalfTo), folder permissions, personal mailboxes and groups as trustees are deliberately out of scope.

Runbook (Exchange Online PowerShell, as an Exchange administrator):

  1. Entra: create the single-tenant app m365-mcp-exchange, certificate credential (or federation), no Graph permission; API permissions → APIs my organization uses → Office 365 Exchange Online → Application → Exchange.ManageAsApp, admin consent. Never assign it an Entra directory role.
  2. Exchange:
    New-ServicePrincipal -AppId <appId> -ObjectId <enterprise-app-object-id> -DisplayName m365-mcp-exchange
    # role reduced to the delegation cmdlets (check where Add-RecipientPermission lives: Get-ManagementRoleEntry "*\Add-RecipientPermission")
    New-ManagementRole -Parent "Mail Recipients" -Name "m365-mcp mailbox delegation"
    $keep = "Get-Mailbox","Get-MailboxPermission","Add-MailboxPermission","Remove-MailboxPermission","Get-RecipientPermission","Add-RecipientPermission","Remove-RecipientPermission"
    Get-ManagementRoleEntry "m365-mcp mailbox delegation\*" | Where-Object { $_.Name -notin $keep } | Remove-ManagementRoleEntry -Confirm:$false
    # write scope: shared mailboxes only
    New-ManagementScope -Name "m365-mcp shared mailboxes" -RecipientRestrictionFilter "RecipientTypeDetails -eq 'SharedMailbox'"
    New-RoleGroup -Name "m365-mcp-exchange (delegation)" -Roles "m365-mcp mailbox delegation" -CustomRecipientWriteScope "m365-mcp shared mailboxes"
    Add-RoleGroupMember -Identity "m365-mcp-exchange (delegation)" -Member <enterprise-app-object-id>
    If a cmdlet is missing from the derived role, derive a second role from the role that holds it and reduce it the same way — never assign Mail Recipients or Organization Management as is.
  3. Configure M365_MODE=full, M365_WRITE_FAMILIES=…,exchange-delegation, M365_EXCHANGE_CLIENT_ID, M365_EXCHANGE_CERT_PATH (or _FEDERATED_TOKEN_FILE), M365_WRITE_KILL_SWITCH_FILE (and M365_EXCHANGE_ORGANIZATION, else resolved from Graph).
  4. Verify with m365_capabilities (Exchange delegation family: enabled, exchange identity with Exchange.ManageAsApp), then on an acceptance shared mailbox: preview, confirm, remove.
  5. Revoke: drop the family from M365_WRITE_FAMILIES, disable the enterprise app, remove the role group.

Two-step confirmation (every write tool)

  1. Preview — call the tool without confirmToken. Nothing is changed: the target is resolved (ambiguous names are refused with the candidates), the guards run, and the answer shows the target, its current state, the planned change and a confirmToken (valid 5 minutes, single use — replay protection is keyed by the MAC and only the canonical token spelling is accepted). If the target is already in the requested state the preview says Nothing to do and issues no token (idempotence).
  2. Execute — call again with the same arguments and the token. The server re-reads the target and refuses (confirmation_invalid) if the tool, target, state or requested change differs from the preview. Then it writes with the write identity, re-reads the target, and answers before / after plus the Graph request-id.

The token is an HMAC under a per-process key: unforgeable, but it carries no secret and grants nothing by itself. Pulse Chat must still obtain an explicit, traced human approval before the second call; pass its id as approvalId so the audit line can be correlated (it is recorded as approvalRef: { id, verified: false } — a free string is never treated as an authorisation).

General write-family reads (resolution, state before/after) use the read identity and mutations use the write identity. The entra-applications family instead uses its dedicated entra identity for both its reads and its tightly scoped writes.

Audit trail

Every write attempt — preview, success, success_unverified, noop, refused, failed — produces one JSON line on stderr (stdout is the MCP transport) and, with M365_AUDIT_LOG_FILE, appended to that file (mode 0600):

{"timestamp":"2026-10-02T09:14:03.120Z","tool":"m365_user_assign_licenses","mode":"full",
 "tenant":"<tenant-guid>","identity":{"role":"write","clientId":"<write-app-guid>"},
 "targetType":"user","targetId":"<object-id, or hmac:… with M365_AUDIT_TARGET_ID=hash>",
 "operation":"assign_licenses","graphRequestId":"<request-id>","result":"success",
 "approvalRef":{"id":"pulse-approval-42","verified":false}}

Failures add errorCode. Tokens, secrets and assertions are never logged (every line goes through the central redaction).

Microsoft Graph permissions

Application permissions (app-only), least privileged first. m365_capabilities compares this matrix with the roles actually present in each token. Teams resource-specific consent (RSC) permissions, granted per team instead of tenant-wide, work too but do not appear in the token — m365_capabilities then reports rsc-or-missing.

Read — read identity

| Tool | Endpoint(s) | Minimal application permission | Also accepted (broader) | Teams RSC | Parts needing more | Tenant licence | |---|---|---|---|---|---|---| | m365_capabilities | (token claims only) | — | — | — | — | — | | m365_organization | GET /organization | Organization.Read.All | Directory.Read.All | — | — | — | | m365_users | GET /users | User.Read.All | Directory.Read.All | — | — | — | | m365_user_info | GET /users/{id}GET /subscribedSkus (licence names) | User.Read.All | Directory.Read.All | — | — | — | | m365_subscribed_skus | GET /subscribedSkus | LicenseAssignment.Read.All | Organization.Read.All, Directory.Read.All | — | — | — | | m365_license_assignments | GET /users/{id}?$select=licenseAssignmentStates,assignedPlansGET /subscribedSkus (plan names) | User.Read.All | Directory.Read.All | — | — | — | | m365_groups | GET /groups | GroupMember.Read.All | Group.Read.All, Directory.Read.All | — | — | — | | m365_group_info | GET /groups/{id}GET /groups/{id}/members/$countGET /groups/{id}/owners | GroupMember.Read.All | Group.Read.All, Directory.Read.All | — | — | — | | m365_group_members | GET /groups/{id}/members | GroupMember.Read.All + User.Read.All | Directory.Read.All | — | — | — | | m365_teams | GET /teams | Team.ReadBasic.All | TeamSettings.Read.All, Directory.Read.All | — | — | — | | m365_team_info | GET /teams/{id} | Team.ReadBasic.All | TeamSettings.Read.All, Directory.Read.All | TeamSettings.Read.Group | — | — | | m365_team_channels | GET /teams/{id}/channels | Channel.ReadBasic.All | ChannelSettings.Read.All, Directory.Read.All | ChannelSettings.Read.Group | — | — | | m365_team_members | GET /teams/{id}/members | TeamMember.Read.All | Directory.Read.All | TeamMember.Read.Group | — | — | | m365_channel_members | GET /teams/{id}/channels/{channelId}/members | ChannelMember.Read.All | Directory.Read.All | ChannelMember.Read.Group | — | — | | m365_usage_reports | GET /reports/getMailboxUsageDetail(period='D7')GET /reports/getOneDriveUsageAccountDetail(period=…)GET /reports/getSharePointSiteUsageDetail(period=…)GET /reports/getOffice365ActiveUserDetail(period=…) | Reports.Read.All | — | — | mailbox type (recipientType / withMailboxType) — or the exchange feature of the audit identity: MailboxSettings.Read | — | | m365_service_health | GET /admin/serviceAnnouncement/healthOverviewsGET /admin/serviceAnnouncement/issuesGET /admin/serviceAnnouncement/messages | ServiceHealth.Read.All | — | — | view=messages (message center): ServiceMessage.Read.All | — | | m365_sites | GET /sites/getAllSitesGET /sites?search=… (fallback: search=*) | Sites.Read.All | — | — | — | — | | m365_site_info | GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/rootGET /sites/{id}/drives | Sites.Read.All | — | — | — | — | | m365_sharing_links | GET /drives/{driveId}/root:/{path}:GET /drives/{driveId}/items/{itemId}/childrenGET /drives/{driveId}/items/{itemId}/permissions | Sites.Read.All | Files.Read.All | — | — | — | | m365_directory_roles | GET /roleManagement/directory/roleAssignments?$expand=principalGET /roleManagement/directory/roleDefinitionsGET /roleManagement/directory/roleEligibilityScheduleInstances (view=eligible) | RoleManagement.Read.Directory | RoleManagement.Read.All, Directory.Read.All | — | view=eligible (PIM): RoleManagement.Read.Directory (Entra ID P2) | — | | m365_user_auth_methods | GET /users/{id}/authentication/methodsGET /reports/authenticationMethods/userRegistrationDetails (tenant view) | UserAuthenticationMethod.Read.All | — | — | tenant view (without user): AuditLog.Read.All (Entra ID P1) | — | | m365_user_activity | GET /users?$select=…,signInActivity | AuditLog.Read.All + User.Read.All | — | — | — | Entra ID P1 | | m365_directory_audit | GET /auditLogs/directoryAudits | AuditLog.Read.All | — | — | — | — | | m365_applications | GET /servicePrincipalsGET /servicePrincipals/{id}/appRoleAssignmentsGET /oauth2PermissionGrants (view=delegated_grants) | Application.Read.All | Directory.Read.All | — | view=delegated_grants: DelegatedPermissionGrant.Read.All | — | | m365_conditional_access | GET /identity/conditionalAccess/policiesGET /policies/identitySecurityDefaultsEnforcementPolicy | Policy.Read.All | — | — | Conditional Access policies: Policy.Read.All (Entra ID P1) | — | | m365_intune_devices | GET /deviceManagement/managedDevices | DeviceManagementManagedDevices.Read.All | — | — | — | Intune | | m365_access_review_snapshot | (aggregate) the endpoints of the users, groups, channel members, roles, MFA, applications and usage-report tools | User.Read.All + GroupMember.Read.All + LicenseAssignment.Read.All + ChannelMember.Read.All + Channel.ReadBasic.All + RoleManagement.Read.Directory + UserAuthenticationMethod.Read.All + Application.Read.All + Reports.Read.All | — | — | last sign-in + tenant MFA report: AuditLog.Read.All (Entra ID P1)delegated consents: DelegatedPermissionGrant.Read.Allmailbox types (shared-mailbox signals) — or the exchange feature: MailboxSettings.Read | — | | m365_audit_signins | GET /auditLogs/signIns | AuditLog.Read.All | — | — | — | — |

Notes:

  • m365_license_assignments — licenseAssignmentStates and assignedPlans are user properties, hence User.Read.All. GET /users/{id}/licenseDetails is not used: it supports delegated permissions only
  • m365_group_members — without User.Read.All, user members come back with their id only
  • m365_team_info — if the member/guest/messaging/fun settings come back empty, add TeamSettings.Read.All
  • m365_channel_members — private and shared channels have their own members, absent from m365_team_members
  • m365_usage_reports — the Graph CSV has no Recipient Type column: mailbox types come from GET /users/{upn}/mailboxSettings/userPurpose (MailboxSettings.Read, that property only) or Exchange Get-Mailbox. CSV through a 302 to a pre-authenticated Microsoft download URL (fetched without the Graph token, never returned). Concealed names (admin center → Reports setting) are detected and flagged
  • m365_sharing_links — bounded walk (depth ≤ 3, ≤ 200 items, target folder required); link URLs are never returned
  • m365_user_auth_methods — method types only — phone numbers, e-mails and keys are never returned
  • m365_directory_audit — retention 7 days without Entra ID P1, 30 days with; modified property values are never returned
  • m365_applications — read identity; distinct from the entra-applications write family
  • m365_conditional_access — without Entra ID P1 the policies part answers unsupported_by_tenant and the security defaults are still read
  • m365_access_review_snapshot — writes a dated JSON file (0600) in M365_SNAPSHOT_DIR; a section that cannot be read is reported, never left empty
  • m365_audit_signins — registered only with M365_ENABLE_SIGNIN_AUDIT=true; needs Entra ID P1/P2 (else unsupported_by_tenant). Microsoft documents Directory.Read.All alongside AuditLog.Read.All for this API — add it if Graph answers 403

Phase 2 tools (audit identity, APIs outside Graph): see Phase 2 below.

Write — write identity (M365_MODE=full)

| Tool | Family | Endpoint(s) | Write identity — minimal permission | Also accepted (broader) | Teams RSC | Read identity — needed by the preview | |---|---|---|---|---|---|---| | m365_user_update | users | PATCH /users/{id} | User.ReadWrite.All | — | — | User.Read.All | | m365_user_set_account_enabled | users | PATCH /users/{id} (accountEnabled) | User.EnableDisableAccount.All + User.Read.All | User.ReadWrite.All | — | User.Read.All | | m365_user_assign_licenses | licenses | POST /users/{id}/assignLicense | LicenseAssignment.ReadWrite.All | User.ReadWrite.All | — | User.Read.All + LicenseAssignment.Read.All | | m365_group_member_add | groups | POST /groups/{id}/members/$ref | GroupMember.ReadWrite.All | Group.ReadWrite.All | — | GroupMember.Read.All + User.Read.All | | m365_group_member_remove | groups | DELETE /groups/{id}/members/{memberId}/$ref | GroupMember.ReadWrite.All | Group.ReadWrite.All | — | GroupMember.Read.All + User.Read.All | | m365_team_member_add | teams | POST /teams/{id}/members | TeamMember.ReadWriteNonOwnerRole.All | TeamMember.ReadWrite.All | — | Team.ReadBasic.All + TeamMember.Read.All + User.Read.All | | m365_team_member_remove | teams | DELETE /teams/{id}/members/{membershipId} | TeamMember.ReadWriteNonOwnerRole.All | TeamMember.ReadWrite.All | — | Team.ReadBasic.All + TeamMember.Read.All + User.Read.All | | m365_team_channel_create | teams | POST /teams/{id}/channels | Channel.Create | — | Channel.Create.Group | Team.ReadBasic.All + Channel.ReadBasic.All | | m365_team_channel_update | teams | PATCH /teams/{id}/channels/{channelId} | ChannelSettings.ReadWrite.All | — | ChannelSettings.ReadWrite.Group | Team.ReadBasic.All + Channel.ReadBasic.All | | m365_team_settings_update | teams | PATCH /teams/{id} | TeamSettings.ReadWrite.All | — | TeamSettings.ReadWrite.Group | TeamSettings.Read.All |

Notes:

  • m365_user_update — allowlisted attributes only; users holding an admin role additionally require a privileged Entra role and are refused by Graph (permission_missing)
  • m365_user_set_account_enabled — Microsoft requires User.Read.All together with User.EnableDisableAccount.All
  • m365_group_member_add — role-assignable groups are refused (would need RoleManagement.ReadWrite.Directory)
  • m365_team_member_add — members only — owner role is out of scope in v1
  • m365_team_member_remove — owners are refused
  • m365_team_channel_create — standard channels only

User.ReadWrite.All is the narrowest application permission Graph offers for the profile attributes of m365_user_update (the User-* permissions cover only phones, mail or password profile). Drop the users family from M365_WRITE_FAMILIES if you do not need it.

Entra applications — dedicated entra identity (preview and execution)

This identity must contain exactly Application.ReadWrite.OwnedBy plus read-only Directory.Read.All; M365_ALLOW_BROAD_PERMISSIONS never expands this exact allowlist.

| Tool | Access | Endpoint(s) | |---|---|---| | inventory, info, requested permissions | read | GET /applications, GET /applications/{id}, GET /servicePrincipals | | effective permissions | read | bounded GET /servicePrincipals/{id}/appRoleAssignments and GET /oauth2PermissionGrants; output includes truncated | | federated credentials | read | GET /applications/{id}/federatedIdentityCredentials ($select only; no $top) | | application create/upsert | write | PATCH /applications(uniqueName='{uniqueName}') with Prefer: create-if-missing (no owners /$ref call) | | application update | write | PATCH /applications/{id} | | redirect URIs | write | PATCH /applications/{id} with spa or web only | | identifier URIs | write | PATCH /applications/{id} with identifierUris only | | delegated scope upsert | write | PATCH /applications/{id} with api only (no /oauth2PermissionGrants, no /appRoleAssignments) | | service-principal create/upsert | write | PATCH /servicePrincipals(appId='{appId}') with Prefer: create-if-missing; POST /servicePrincipals/{id}/owners/$ref only when ownership was not established automatically | | service-principal update | write | PATCH /servicePrincipals/{id} |

V1 can read requiredResourceAccess, certificates and federated credentials, but exposes no write field or endpoint for them. Redirect URIs, identifier URIs and delegated scopes are written by the three OAuth tools only: the preview binds the whole list (or the whole scope collection and API settings), the execution re-reads it with ownership right before the PATCH and refuses (confirmation_invalid) if it moved, and the post-write re-read must show exactly the expected state — otherwise the call fails as transient (changed the target but post-write verification failed): inspect the application before retrying. Client secrets, private keys, admin consent, grants and application deletion stay out of scope. Scalar PATCH operations re-read the targeted fields immediately before the request and preserve unrelated fields. This implementation does not claim atomic concurrency control: a narrow residual last-writer-wins window remains and is documented explicitly.

Read identity: read permissions only

The token provider refuses (forbidden_permission) a read-identity token carrying any permission that is not a read, before any Graph call. One classification (classifyPermission in src/permissions.ts) is shared by the token provider and m365_capabilities:

  • read — <Resource>.Read or <Resource>.ReadBasic, optionally followed by plain scope segments (User.Read.All, RoleManagement.Read.Directory, MailboxSettings.Read). Every permission of the read matrix above has this shape and is accepted;
  • write — a segment after the resource names a write verb (ReadWrite, FullControl, EnableDisable, Create, Manage, Send, Invite, Selected…): User.ReadWrite.All, GroupMember.ReadWrite.All, LicenseAssignment.ReadWrite.All, User.EnableDisableAccount.All, Sites.FullControl.All, Sites.ReadWrite.All, the broad permissions below…;
  • unknown — any other shape (Calls.JoinGroupCall.All…): fail-closed, treated as a write.

The error names every refused permission (writes and unrecognised ones separately), never a token or a secret. M365_ALLOW_BROAD_PERMISSIONS does not apply to the read identity, and there is no compatibility switch: remove the permission from the read Entra app (the server never changes Entra permissions or consents itself) and give writes to the separate write identity (M365_WRITE_CLIENT_ID, M365_MODE=full). Since 0.5.3 the read tools no longer list write permissions (Sites.ReadWrite.All, Sites.FullControl.All, TeamSettings.ReadWrite.All, TeamMember.ReadWrite.All, ChannelMember.ReadWrite.All) as "also accepted".

Refused by default (write identity)

The token provider refuses a write-identity token carrying any of: Directory.ReadWrite.All, RoleManagement.ReadWrite.Directory, Application.ReadWrite.All, AppRoleAssignment.ReadWrite.All, Policy.ReadWrite.ConditionalAccess, UserAuthenticationMethod.ReadWrite.All (forbidden_permission). M365_ALLOW_BROAD_PERMISSIONS=true lifts this knowingly for the write identity only — do not. It never lifts the read-identity check above, nor the exact allowlist of the entra identity. Never give a technical user the Global Administrator role for this server: it uses application permissions only.

Every token is also checked for tid = M365_TENANT_ID, appid = the configured client id and aud = Microsoft Graph (tenant_mismatch / auth_failed otherwise). M365_TENANT_ID must be a GUID: common, organizations or a domain name are refused — no implicit multi-tenant authority.

Phase 2 — APIs outside Microsoft Graph (opt-in)

Three helpdesk / review questions have no Graph v1.0 answer. They are served by a fourth, dedicated identity (m365-mcp-audit), each API enabled separately with M365_AUDIT_APP_FEATURES. Without M365_AUDIT_APP_CLIENT_ID none of these tools exists.

| Tool | Feature | API | Permission on that API | What | |---|---|---|---|---| | m365_mailbox_permissions | exchange | Exchange Online InvokeCommand | Exchange.ManageAsApp + read-only Exchange role | Full Access, Send As, Send on behalf of a mailbox, or of every shared mailbox — explicit grants only; a right Exchange refused to read is NOT EVALUATED, never "none" | | m365_activity_collect | activity | Office 365 Management Activity | ActivityFeed.Read | Collects the unified audit log (SharePoint/OneDrive, Exchange, Entra, Teams) into a local store | | m365_activity_search | activity | (local store) | ActivityFeed.Read | "Who deleted / shared / downloaded this file? who changed these rights?" over up to 180 days | | m365_site_permissions | sharepoint | SharePoint REST /_api | Sites.Selected + per-site fullcontrol | Site admins, Owners / Members / Visitors and their members, Everyone claims, external users, libraries with broken inheritance |

With exchange, m365_access_review_snapshot also records the rights on every shared mailbox, raises disabled account still delegate of a shared mailbox, and its comparison lists rights granted and removed.

Security model

| Risk | Control | |---|---| | One identity reaching three APIs | Separate Entra app with no Graph permission (the server never even asks for a Graph token for it); one token per API, each checked for tenant, application, audience and an exact role set — any extra role ⇒ forbidden_permission, before any call | | Weak credential | Certificate or workload identity federation only — a client secret is a startup error (and SharePoint refuses secret-based app-only tokens anyway) | | Token sent elsewhere | Each API client is pinned to one origin (outlook.office365.com, manage.office.com, M365_SHAREPOINT_HOST) and a closed list of method + path, checked before the token is attached; encoded separators (%2f, %5c, %2e, %25), malformed encodings and OData @ aliases are refused; nextLink, NextPageUri and audit blob URIs from Microsoft are re-checked; redirects are refused; answers are capped in size and pages in number | | Exchange: InvokeCommand runs any cmdlet the role allows | Server side: three cmdlets only (Get-Mailbox, Get-MailboxPermission, Get-RecipientPermission), closed parameter list, validated values. Tenant side: a read-only role, so even a bypass cannot write. A token whose wids claim shows a write-capable directory role (Global, Exchange, SharePoint, User… Administrator) is refused; a custom Exchange role group is invisible in the token — keep it view-only | | Exchange: endpoint not publicly documented | It is the endpoint of the official ExchangeOnlineManagement v3 module; the documented Exchange Online Admin API (preview) covers only Send on behalf and folder permissions, not Full Access / Send As. Validate on the tenant; switch when Microsoft publishes these cmdlets | | SharePoint: reading role assignments needs full control | Sites.Selected + fullcontrol granted site by site on the reviewed sites only; Sites.FullControl.All is refused unless M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL=true (warning at startup). The client only sends GET to seven /_api/web… paths | | Audit data = personal data | Only allowlisted fields are stored: actor, operation, object / file / site, target, result, IP — the object id only for SharePoint / OneDrive / Entra / Exchange admin records (for mail items, Teams, Forms… it can carry titles). Never mail subjects, items, message bodies, modified values or cmdlet parameter values (names only). Store 0700/0600, purged after M365_ACTIVITY_RETENTION_DAYS (default 180) | | ActivityFeed.ReadDlp (DLP matches contain sensitive content) | Refused — not in the role set | | Starting audit subscriptions is a configuration change | Off by default: the route is not even allowlisted unless M365_ACTIVITY_START_SUBSCRIPTIONS=true; when allowed it is written to the audit trail and stopped by the kill switch (M365_WRITE_KILL_SWITCH_FILE) | | "No result" vs "not collected" | m365_activity_search says when the period precedes the store, or when the last collection is older than Microsoft's 7-day retention. A content type cut by the per-run blob budget (shared between types) is not marked collected | | Audit data used as prompt injection | Search output is labelled as recorded data; records past the retention are never returned, even before the purge |

Why not Graph auditLogQuery for 180 days? Microsoft moved it back from v1.0 to beta in 2025 and it is still unreliable there; this server never calls Graph beta. The Management Activity API keeps content 7 days, so schedule m365_activity_collect daily (a Claude routine, a cron calling the MCP, or the smoke script): history builds up to the retention. Unified audit must be enabled in Purview.

Runbook — the audit identity

  1. Create the Entra app m365-mcp-audit (single tenant), certificate credential (or federation). Give it no Microsoft Graph permission.
  2. exchange: API permissions → APIs my organization uses → Office 365 Exchange Online → Application → Exchange.ManageAsApp, admin consent. Then a view-only Exchange role group holding exactly the three Get-* cmdlets the server sends, and no Entra directory role — the full procedure, its checks and the acceptance are in Exchange mailbox audit. Never Exchange Administrator, Organization Management or Global Administrator; Global Reader is accepted but broader than needed (m365_capabilities warns).
  3. activity: Office 365 Management APIs → Application → ActivityFeed.Read only (not ActivityFeed.ReadDlp), admin consent. Check that auditing is on (Purview → Audit). Start the subscriptions once: M365_ACTIVITY_START_SUBSCRIPTIONS=true + m365_activity_collect startMissingSubscriptions=true, then set the flag back to false.
  4. sharepoint: SharePoint → Application → Sites.Selected, admin consent. Then grant full control on each site to review (with an admin's own Graph access, not this server):
    POST https://graph.microsoft.com/v1.0/sites/{site-id}/permissions
    { "roles": ["fullcontrol"], "grantedToIdentities": [{ "application": { "id": "<appId>", "displayName": "m365-mcp-audit" } }] }
    Revoke with DELETE /sites/{site-id}/permissions/{permission-id}.
  5. Configure M365_AUDIT_APP_CLIENT_ID, M365_AUDIT_APP_CERT_PATH (or _FEDERATED_TOKEN_FILE), M365_AUDIT_APP_FEATURES, and per feature M365_ACTIVITY_DIR, M365_SHAREPOINT_HOST.
  6. Verify with m365_capabilities: the audit block shows one token per API with its exact role.
  7. Revoke: remove the feature from M365_AUDIT_APP_FEATURES (tools disappear), or disable the enterprise app in Entra (no token anywhere), and remove the role group / site grants.

Exchange mailbox audit only (read-only)

Who can use a shared mailbox — Full Access, Send As, Send on behalf — for a connection that stays in M365_MODE=readonly (the Athéna connection, #152). This path adds exactly one tool, m365_mailbox_permissions, and the shared-mailbox rights of m365_access_review_snapshot. It never enables exchange-delegation, a write family, the activity or sharepoint features, Mail.Read, full_access_as_app, Sites.FullControl.All, nor an Entra administrator role, and it reads no message content.

Nothing here authorises a change. Creating the identity, the admin consent, the Exchange role group and the acceptance run on a test mailbox each need their own explicit approval; this section only says how to do them and how to check them.

What the server guarantees (unit-tested, no tenant needed)

  • Readonly + M365_AUDIT_APP_FEATURES=exchange: the readonly tools plus m365_mailbox_permissions, nothing else — M365_WRITE_* / M365_EXCHANGE_* present in the environment are not even read.
  • The audit identity only ever sends Get-Mailbox (Identity, RecipientTypeDetails, ResultSize), Get-MailboxPermission (Identity), Get-RecipientPermission (Identity, AccessRights=SendAs), with validated values; any other cmdlet or parameter is refused before a token is even requested.
  • Its Exchange token must hold exactly Exchange.ManageAsApp (an extra role ⇒ forbidden_permission) and no write-capable directory role (wids); it never gets a Graph token.
  • Listing the tools and m365_capabilities make no Exchange call; a call refused by the server (invalid mailbox, cmdlet outside the list) sends nothing to Microsoft. Only the read itself does.
  • An absence of collection is never an empty list: see Reading the answers below.

1. Prepare the identity (under a separate approval)

  1. Entra: the single-tenant app m365-mcp-audit, certificate credential (or workload identity federation — a client secret is a startup error), no Microsoft Graph permission.
  2. API permissions → APIs my organization uses → Office 365 Exchange Online → Application → Exchange.ManageAsApp, then admin consent. Assign no Entra directory role.
  3. Exchange Online PowerShell, as an Exchange administrator — a custom role reduced to the three Get-* cmdlets, in a dedicated role group:
    New-ServicePrincipal -AppId <appId> -ObjectId <enterprise-app-object-id> -DisplayName m365-mcp-audit
    New-ManagementRole -Parent "Mail Recipients" -Name "m365-mcp mailbox audit (read)"
    $keep = "Get-Mailbox","Get-MailboxPermission","Get-RecipientPermission"
    Get-ManagementRoleEntry "m365-mcp mailbox audit (read)\*" | Where-Object { $_.Name -notin $keep } | Remove-ManagementRoleEntry -Confirm:$false
    New-RoleGroup -Name "m365-mcp-audit (read)" -Roles "m365-mcp mailbox audit (read)"
    Add-RoleGroupMember -Identity "m365-mcp-audit (read)" -Member <enterprise-app-object-id>
    The parent only provides the cmdlets: the custom role keeps the three Get-* entries, so the identity cannot change anything even if the server were bypassed. Do not remove parameters below what the server sends (list above).

2. Verify the principal and the RBAC (read-only cmdlets)

Get-ServicePrincipal -Identity <appId> | Format-List DisplayName,AppId,ObjectId              # registered in Exchange
Get-RoleGroupMember "m365-mcp-audit (read)"                                                  # the application is a member
(Get-RoleGroup "m365-mcp-audit (read)").Roles                                                # only the custom role
Get-ManagementRoleEntry "m365-mcp mailbox audit (read)\*" | Format-Table Name,Parameters     # exactly the three cmdlets
Get-ManagementRoleEntry "m365-mcp mailbox audit (read)\*" | Where-Object { $_.Name -notlike "Get-*" }   # must return nothing

Expected: the three entries, with at least Identity, RecipientTypeDetails, ResultSize on Get-Mailbox, Identity on Get-MailboxPermission, Identity, AccessRights on Get-RecipientPermission; the application in no other role group, and with no Entra directory role. Then m365_capabilities must show Mode: readonly, Exchange delegation family: disabled, Exchange mailbox audit (read-only): enabled — the server sends only … and m365_mailbox_permissions granted (the token holds exactly Exchange.ManageAsApp).

On rbac_denied, add only the missing Get-* entry to the custom role (Add-ManagementRoleEntry "m365-mcp mailbox audit (read)\<cmdlet>"). Never answer it with Exchange Administrator, Organization Management, Global Administrator, Global Reader, full_access_as_app or Mail.Read: the error is precise enough to fix the role group.

3. Configure the connection

M365_MODE=readonly
M365_AUDIT_APP_CLIENT_ID=<appId>
M365_AUDIT_APP_CERT_PATH=/etc/m365-mcp/audit.pem      # or M365_AUDIT_APP_FEDERATED_TOKEN_FILE
M365_AUDIT_APP_FEATURES=exchange                      # exchange only: no activity, no sharepoint
M365_EXCHANGE_ORGANIZATION=<tenant>.onmicrosoft.com   # else read from Graph

No M365_WRITE_*, M365_EXCHANGE_CLIENT_ID (that is the delegation identity), M365_ACTIVITY_* or M365_SHAREPOINT_*. Only this connection's environment changes: the read identity, the other connections and the snapshots already in M365_SNAPSHOT_DIR are untouched (same schema; a snapshot taken without the exchange feature is compared as not evaluated, never as "rights removed").

4. Acceptance on the authorised test mailbox (under the approval)

  1. Prerequisite: a test shared mailbox named in the approval, holding at least one explicit grant of each right (Full Access, Send As, Send on behalf) — set up by an administrator, not by this server.
  2. The administrator's reference, in Exchange Online PowerShell:
    $m = Get-Mailbox -Identity <test-mailbox>
    [pscustomobject]@{
      mailbox      = [string]$m.PrimarySmtpAddress
      fullAccess   = @(Get-MailboxPermission -Identity $m.Identity | Where-Object { -not $_.IsInherited -and -not $_.Deny -and $_.AccessRights -match 'FullAccess' -and [string]$_.User -notmatch '^(NT AUTHORITY\\|S-1-5-)' } | ForEach-Object { [string]$_.User })
      sendAs       = @(Get-RecipientPermission -Identity $m.Identity -AccessRights SendAs | Where-Object { -not $_.IsInherited -and $_.AccessControlType -eq 'Allow' -and [string]$_.Trustee -notmatch '^(NT AUTHORITY\\|S-1-5-)' } | ForEach-Object { [string]$_.Trustee })
      sendOnBehalf = @($m.GrantSendOnBehalfTo | ForEach-Object { [string]$_ })
    } | ConvertTo-Json | Set-Content -Encoding utf8 reference.json
  3. The server, through the compiled MCP over stdio — only that mailbox is read:
    M365_SMOKE_MAILBOX=<test-mailbox> M365_SMOKE_EXCHANGE_REFERENCE=./reference.json node smoke.mjs --exchange-audit
    It refuses to start unless M365_AUDIT_APP_FEATURES=exchange exactly, forces M365_MODE=readonly and passes no write / entra / delegation identity to the server. It checks: no [WRITE], activity, SharePoint or delegation tool; mode readonly and delegation family disabled in m365_capabilities; the exact token role; the three rights read (none NOT EVALUATED) with one grant each; the same trustees as the reference, right by right (case-insensitive). It ends with the secret / JWT leak check.
  4. Keep the report with the acceptance records (it names the test mailbox's trustees). A difference in trustee format (display name vs UPN, alias) is a finding to record, not a reason to widen a role.

Reading the answers

| You see | Meaning | Next step | |---|---|---| | No m365_mailbox_permissions; m365_capabilities: Exchange mailbox audit (read-only): not configured; review: Not covered by this configuration — mailboxAccess | Identity / feature not configured | Steps 1–3, if approved | | auth_failed: … could not get a exchange token | The token endpoint refused the credential (certificate, federation, consent) | Check the credential and the consent | | permission_missing … needs exactly Exchange.ManageAsApp on exchange | The app lacks Exchange.ManageAsApp (or its consent) — no Exchange call was made | Step 1.2 | | forbidden_permission | The token carries another role, or a write-capable directory role | Remove it | | auth_failed (exchange HTTP 401 …) | Exchange refused a valid token: consent not propagated, or principal not registered | Wait, then New-ServicePrincipal (step 1.3) | | rbac_denied … Exchange knows no role for this application | Principal registered without role group | Add-RoleGroupMember (step 1.3) | | rbac_denied … does not let this identity run <cmdlet> (<parameters>) | The role group lacks that cmdlet or parameter | Add that Get-* entry only (step 2) | | not_found … Exchange has no object "<x>" | No such mailbox (or outside the role's read scope) | Check the address | | - Send As: ⚠ NOT EVALUATED — <reason> and ⚠ INCOMPLETE | That right could not be read; the others were | Its holders are unknown — never report "nobody" | | - Full Access: none (no explicit grant) | Read: Exchange returned no explicit grant | See the limits below | | ⚠ Mailbox list truncated: … ResultSize 1000 | Connector limit: Exchange stopped at 1000 mailboxes | Mailboxes beyond it are not reviewed | | ⚠ Permission list truncated (server page budget) / ⚠ truncated | Pagination budget (20 pages) reached | That right is partial | | Review: not evaluated — section(s) mailboxAccess failed / not configured, or ⚠ partial — … | Section not read, or read in part | The signal / change is not concluded | | Changes: NOT compared — previous snapshot: section users failed (…) | That section was not read in one of the two reviews | Nothing is known of those changes — never report deletions or creations; compare with another snapshot | | Changes: ⚠ partial — private/shared channels NOT compared — … section channels failed (…); N channel(s) left out, as read in the … snapshot: … | Channel members not read in one of the two reviews (ChannelMember.Read.All) | The group and team entries, exits and new owners listed are real; nothing is known of the named channels |

Limits (stated in every answer)

Explicit grants only. Inherited entries, Deny entries and system principals (NT AUTHORITY\…, S-1-5-…) are not listed — they are counted under Not shown. A trustee that is a group gives access to its members, who are not expanded. Effective (transitive) rights are therefore not evaluated: this is no exhaustive proof of who can open a mailbox — a separate piece of work if needed. Send on behalf comes from the GrantSendOnBehalfTo property of Get-Mailbox; if Exchange does not return it, the right is NOT EVALUATED. The review reads at most 300 shared mailboxes (flagged when cut).

Rollback

Remove exchange from M365_AUDIT_APP_FEATURES (or the whole M365_AUDIT_APP_* block) and restart: the tool disappears and the review says not configured. Tenant side, under approval: Remove-RoleGroupMember / Remove-RoleGroup "m365-mcp-audit (read)", Remove-ManagementRole, Remove-ServicePrincipal, then disable or delete the enterprise app.

Environment

| Variable | Default | Meaning | |---|---|---| | M365_MODE | readonly | readonly or full; any other value is a startup error | | M365_TENANT_ID | — | Tenant GUID (required) | | M365_READ_CLIENT_ID | — | Read application (client) id (required) | | M365_READ_FEDERATED_TOKEN_FILE | — | 1st choice — file with the platform's OIDC token (workload identity federation), re-read at each token request | | M365_READ_CERT_PATH / M365_READ_KEY_PATH | — | 2nd choice — PEM certificate (+ unencrypted private key, in the same file or KEY_PATH) | | M365_READ_CLIENT_SECRET | — | Acceptance testing only — warning printed at startup | | M365_WRITE_* | — | Same variables for the write application, read only when M365_MODE=full — missing ⇒ startup failure; same client id as read ⇒ startup failure | | M365_WRITE_FAMILIES | users,licenses,groups,teams | Comma list; add entra-applications or exchange-delegation explicitly to enable those families, or use none | | M365_ENTRA_* | — | Third dedicated identity, loaded only for entra-applications; same credential forms as read/write; client id must differ from both | | M365_EXCHANGE_* | — | Exchange Online identity, loaded only for exchange-delegation (full mode); certificate or federated token file only — a secret is refused; client id must differ from read, entra and audit (it may be the write one) | | M365_WRITE_KILL_SWITCH_FILE | — | While this file exists, every write is refused (checked at each call); absolute path, mandatory when entra-applications or exchange-delegation is enabled | | M365_AUDIT_LOG_FILE | — | Also append the audit trail to this file | | M365_AUDIT_TARGET_ID | id | id or hash (keyed HMAC-SHA256 of the object id — a plain hash of a GUID would be reversible by anyone who can list the directory) | | M365_AUDIT_HASH_KEY | — | Required with hash: ≥ 16 characters, kept secret (redacted everywhere) | | M365_ENABLE_SIGNIN_AUDIT | false | Register m365_audit_signins | | M365_AUDIT_APP_CLIENT_ID | — | Phase 2: dedicated audit identity (certificate M365_AUDIT_APP_CERT_PATH/_KEY_PATH or M365_AUDIT_APP_FEDERATED_TOKEN_FILE; a secret is refused) | | M365_AUDIT_APP_FEATURES | — | Required with the identity: comma list of exchange, activity, sharepoint | | M365_EXCHANGE_ORGANIZATION | from Graph | Initial domain (contoso.onmicrosoft.com) used to route Exchange calls (audit and delegation identities) | | M365_ACTIVITY_DIR | — | Required by activity: absolute directory of the collected audit records (0700/0600) | | M365_ACTIVITY_RETENTION_DAYS | 180 | Collected records older than this are purged (7–3650) | | M365_ACTIVITY_START_SUBSCRIPTIONS | false | Allow m365_activity_collect to start missing subscriptions | | M365_SHAREPOINT_HOST | — | Required by sharepoint: <tenant>.sharepoint.com, the only host its token goes to | | `M365_SHAREPOIN