@aidalinfo/m365-mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,373 @@
1
+ # @aidalinfo/m365-mcp
2
+
3
+ MCP server for **Microsoft 365** through **Microsoft Graph v1.0**: Entra ID users and groups,
4
+ licences, Microsoft Teams, and tenant information for diagnosis — with targeted, audited writes.
5
+
6
+ - **`readonly`** (default): read tools only. The write identity is **not even loaded**.
7
+ - **`full`**: read tools **plus** targeted write tools (user attributes from an allowlist,
8
+ enable/disable account, licences, group members, team members, channels, team settings),
9
+ signed by a **separate Entra application**, per family (`M365_WRITE_FAMILIES`).
10
+
11
+ There is **no raw Graph request tool** (neither read nor write), no `beta` endpoint, and the v1
12
+ deliberately leaves out: Entra roles, applications / service principals / credentials, password
13
+ resets, permanent deletions, Conditional Access, and any mail / chat / meeting / file content.
14
+
15
+ ```text
16
+ Agent Pulse / Vulcain
17
+ │ MCP (stdio)
18
+ ▼
19
+ @aidalinfo/m365-mcp ── allowlisted, validated tools ── two-step writes ── audit (JSON lines)
20
+ │ client credentials (federation → certificate → secret)
21
+ ▼
22
+ Microsoft Graph v1.0
23
+ │
24
+ ├── Entra app "m365-mcp-read" (every mode — read permissions only)
25
+ └── Entra app "m365-mcp-write" (full mode only — write permissions only)
26
+ ```
27
+
28
+ Do **not** reuse Pulse Chat's Microsoft SSO application, nor the application behind personal
29
+ Outlook / calendar connectors: the two identities above are dedicated to this server.
30
+
31
+ ## Tools
32
+
33
+ ### Read (every mode)
34
+
35
+ | Tool | What |
36
+ |---|---|
37
+ | `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.** |
38
+ | `m365_organization` | Tenant name/type/country, verified domains, Entra Connect sync state |
39
+ | `m365_users` | Users, paginated — filters: `search` (prefix of name/UPN/mail), `accountEnabled`, `userType`, `department`, `licensed`, `skuId`; `fields` from an allowlist |
40
+ | `m365_user_info` | One user: allowlisted attributes, licences with names and direct/group assignment |
41
+ | `m365_subscribed_skus` | Licences purchased, consumed, available, suspended, in warning (+ service plans) |
42
+ | `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) |
43
+ | `m365_groups` / `m365_group_info` / `m365_group_members` | Groups (by kind: Microsoft 365, security, distribution, dynamic, team), details + owners + count, members (direct or transitive) |
44
+ | `m365_teams` / `m365_team_info` | Teams, and one team's settings (member, guest, messaging, fun) |
45
+ | `m365_team_channels` | Channels (standard / private / shared) with ids |
46
+ | `m365_team_members` | Members with role (owner / member / guest) and membership id |
47
+ | `m365_audit_signins` | Sign-in logs — **only with `M365_ENABLE_SIGNIN_AUDIT=true`**, needs Entra ID P1/P2 |
48
+
49
+ Every list tool takes `limit` (default 25, **server maximum 100**), an opaque `cursor` for the
50
+ next page, structured filters (no free-form OData; strings are escaped server-side) and
51
+ `format: summary | json`. Selected fields come from a server-side allowlist: credentials,
52
+ authentication methods, personal phone numbers, alternate e-mails and on-premises identifiers are
53
+ never requested.
54
+
55
+ HTTP redirects are **never followed** (`redirect: "error"`, Graph and token endpoint): only
56
+ validated Graph URLs are called, and a 307 could otherwise replay a mutation elsewhere.
57
+
58
+ Cursors are **server-side**: the caller holds a random id, never a URL, so pagination cannot be
59
+ pointed at another resource; every `@odata.nextLink` is checked to stay on
60
+ `https://graph.microsoft.com/v1.0/` before it is followed. A cursor is bound to its tool (and to
61
+ the group / team for member and channel lists) and expires after 30 minutes.
62
+
63
+ A refused or unavailable API never looks like an empty list — the tool answers an explicit error:
64
+
65
+ | Code | Meaning |
66
+ |---|---|
67
+ | `permission_missing` | 403 — the application lacks the Graph permission (or admin consent), see `m365_capabilities` |
68
+ | `unsupported_by_tenant` | The tenant cannot serve this (no Entra P1 for sign-ins, no Teams licence…) |
69
+ | `license_unavailable` | No free unit, SKU not enabled, or a licence prerequisite (usage location, plan dependency) |
70
+ | `not_found` / `ambiguous_target` | Nothing matches / several objects match a name — pass the id |
71
+ | `conflict` | Already exists, concurrent change, precondition failed |
72
+ | `throttled` / `transient` | 429 after the bounded retries (with `Retry-After`) / 5xx, timeout, network |
73
+ | `auth_failed` / `tenant_mismatch` / `forbidden_permission` | Token refused / token for another tenant or app / token carries a permission refused by policy |
74
+ | `refused` / `confirmation_invalid` | A guard refused the write / the confirmation token is expired, reused, or the state changed |
75
+
76
+ Each error carries Microsoft's `request-id` (quote it to Microsoft support) and the
77
+ `client-request-id` the server sent. The raw Graph body is never returned.
78
+
79
+ ### Write (`M365_MODE=full`, per family)
80
+
81
+ | Tool | Family | What | Guards |
82
+ |---|---|---|---|
83
+ | `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** |
84
+ | `m365_user_set_account_enabled` | `users` | Enable / disable sign-in (nothing is deleted) | — |
85
+ | `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 |
86
+ | `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) |
87
+ | `m365_team_member_add` / `_remove` | `teams` | Team membership, role **member** only | Refuses archived teams, disabled accounts, and removing an **owner** |
88
+ | `m365_team_channel_create` | `teams` | Standard channel | No-op if the name exists; never retried on 5xx (no duplicate) |
89
+ | `m365_team_channel_update` | `teams` | Rename / describe a channel | General channel cannot be renamed |
90
+ | `m365_team_settings_update` | `teams` | Allowlisted member / guest / messaging / fun settings | Strict schema |
91
+
92
+ `m365_group_create` / `m365_team_create` are **not** in v1 (they would need `Group.ReadWrite.All`
93
+ / `Team.Create`); add them later behind a dedicated flag if needed.
94
+
95
+ #### Two-step confirmation (every write tool)
96
+
97
+ 1. **Preview** — call the tool **without** `confirmToken`. Nothing is changed: the target is
98
+ resolved (ambiguous names are refused with the candidates), the guards run, and the answer
99
+ shows the target, its current state, the planned change and a `confirmToken`
100
+ (valid 5 minutes, single use — replay protection is keyed by the MAC and only the canonical
101
+ token spelling is accepted). If the target is already in the requested state the preview
102
+ says *Nothing to do* and issues no token (idempotence).
103
+ 2. **Execute** — call again with the **same arguments** and the token. The server re-reads the
104
+ target and refuses (`confirmation_invalid`) if the tool, target, state or requested change
105
+ differs from the preview. Then it writes with the **write identity**, re-reads the target, and
106
+ answers *before* / *after* plus the Graph `request-id`.
107
+
108
+ The token is an HMAC under a per-process key: unforgeable, but it carries no secret and grants
109
+ nothing by itself. **Pulse Chat must still obtain an explicit, traced human approval before the
110
+ second call**; pass its id as `approvalId` so the audit line can be correlated (it is recorded as
111
+ `approvalRef: { id, verified: false }` — a free string is never treated as an authorisation).
112
+
113
+ All reads done for a write (resolution, state before/after) use the **read** identity; only the
114
+ mutation itself uses the write identity. The read identity therefore needs the permissions of the
115
+ last column of the write matrix below — `m365_capabilities` reports a write tool as
116
+ `missing on read identity (preview)` otherwise.
117
+
118
+ #### Audit trail
119
+
120
+ Every write attempt — `preview`, `success`, `noop`, `refused`, `failed` — produces one JSON line on
121
+ **stderr** (stdout is the MCP transport) and, with `M365_AUDIT_LOG_FILE`, appended to that file
122
+ (mode 0600):
123
+
124
+ ```json
125
+ {"timestamp":"2026-10-02T09:14:03.120Z","tool":"m365_user_assign_licenses","mode":"full",
126
+ "tenant":"<tenant-guid>","identity":{"role":"write","clientId":"<write-app-guid>"},
127
+ "targetType":"user","targetId":"<object-id, or hmac:… with M365_AUDIT_TARGET_ID=hash>",
128
+ "operation":"assign_licenses","graphRequestId":"<request-id>","result":"success",
129
+ "approvalRef":{"id":"pulse-approval-42","verified":false}}
130
+ ```
131
+
132
+ Failures add `errorCode`. Tokens, secrets and assertions are never logged (every line goes
133
+ through the central redaction).
134
+
135
+ ## Microsoft Graph permissions
136
+
137
+ Application permissions (app-only), **least privileged first**. `m365_capabilities` compares this
138
+ matrix with the `roles` actually present in each token. Teams **resource-specific consent** (RSC)
139
+ permissions, granted per team instead of tenant-wide, work too but do not appear in the token —
140
+ `m365_capabilities` then reports `rsc-or-missing`.
141
+
142
+ ### Read — read identity
143
+
144
+ | Tool | Endpoint(s) | Minimal application permission | Also accepted (broader) | Teams RSC |
145
+ |---|---|---|---|---|
146
+ | `m365_capabilities` | `(token claims only)` | — | — | — |
147
+ | `m365_organization` | `GET /organization` | `Organization.Read.All` | `Directory.Read.All` | — |
148
+ | `m365_users` | `GET /users` | `User.Read.All` | `Directory.Read.All` | — |
149
+ | `m365_user_info` | `GET /users/{id}`<br>`GET /subscribedSkus (licence names)` | `User.Read.All` | `Directory.Read.All` | — |
150
+ | `m365_subscribed_skus` | `GET /subscribedSkus` | `LicenseAssignment.Read.All` | `Organization.Read.All`, `Directory.Read.All` | — |
151
+ | `m365_license_assignments` | `GET /users/{id}?$select=licenseAssignmentStates,assignedPlans`<br>`GET /subscribedSkus (plan names)` | `User.Read.All` | `Directory.Read.All` | — |
152
+ | `m365_groups` | `GET /groups` | `GroupMember.Read.All` | `Group.Read.All`, `Directory.Read.All` | — |
153
+ | `m365_group_info` | `GET /groups/{id}`<br>`GET /groups/{id}/members/$count`<br>`GET /groups/{id}/owners` | `GroupMember.Read.All` | `Group.Read.All`, `Directory.Read.All` | — |
154
+ | `m365_group_members` | `GET /groups/{id}/members` | `GroupMember.Read.All` + `User.Read.All` | `Directory.Read.All` | — |
155
+ | `m365_teams` | `GET /teams` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `Directory.Read.All` | — |
156
+ | `m365_team_info` | `GET /teams/{id}` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `TeamSettings.ReadWrite.All`, `Directory.Read.All` | `TeamSettings.Read.Group` |
157
+ | `m365_team_channels` | `GET /teams/{id}/channels` | `Channel.ReadBasic.All` | `ChannelSettings.Read.All`, `Directory.Read.All` | `ChannelSettings.Read.Group` |
158
+ | `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `TeamMember.ReadWrite.All`, `Directory.Read.All` | `TeamMember.Read.Group` |
159
+ | `m365_audit_signins` | `GET /auditLogs/signIns` | `AuditLog.Read.All` | — | — |
160
+
161
+ Notes:
162
+ - `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
163
+ - `m365_group_members` — without User.Read.All, user members come back with their id only
164
+ - `m365_team_info` — if the member/guest/messaging/fun settings come back empty, add TeamSettings.Read.All
165
+ - `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
166
+
167
+ ### Write — write identity (M365_MODE=full)
168
+
169
+ | Tool | Family | Endpoint(s) | Write identity — minimal permission | Also accepted (broader) | Teams RSC | Read identity — needed by the preview |
170
+ |---|---|---|---|---|---|---|
171
+ | `m365_user_update` | users | `PATCH /users/{id}` | `User.ReadWrite.All` | — | — | `User.Read.All` |
172
+ | `m365_user_set_account_enabled` | users | `PATCH /users/{id} (accountEnabled)` | `User.EnableDisableAccount.All` + `User.Read.All` | `User.ReadWrite.All` | — | `User.Read.All` |
173
+ | `m365_user_assign_licenses` | licenses | `POST /users/{id}/assignLicense` | `LicenseAssignment.ReadWrite.All` | `User.ReadWrite.All` | — | `User.Read.All` + `LicenseAssignment.Read.All` |
174
+ | `m365_group_member_add` | groups | `POST /groups/{id}/members/$ref` | `GroupMember.ReadWrite.All` | `Group.ReadWrite.All` | — | `GroupMember.Read.All` + `User.Read.All` |
175
+ | `m365_group_member_remove` | groups | `DELETE /groups/{id}/members/{memberId}/$ref` | `GroupMember.ReadWrite.All` | `Group.ReadWrite.All` | — | `GroupMember.Read.All` + `User.Read.All` |
176
+ | `m365_team_member_add` | teams | `POST /teams/{id}/members` | `TeamMember.ReadWriteNonOwnerRole.All` | `TeamMember.ReadWrite.All` | — | `Team.ReadBasic.All` + `TeamMember.Read.All` + `User.Read.All` |
177
+ | `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` |
178
+ | `m365_team_channel_create` | teams | `POST /teams/{id}/channels` | `Channel.Create` | — | `Channel.Create.Group` | `Team.ReadBasic.All` + `Channel.ReadBasic.All` |
179
+ | `m365_team_channel_update` | teams | `PATCH /teams/{id}/channels/{channelId}` | `ChannelSettings.ReadWrite.All` | — | `ChannelSettings.ReadWrite.Group` | `Team.ReadBasic.All` + `Channel.ReadBasic.All` |
180
+ | `m365_team_settings_update` | teams | `PATCH /teams/{id}` | `TeamSettings.ReadWrite.All` | — | `TeamSettings.ReadWrite.Group` | `TeamSettings.Read.All` |
181
+
182
+ Notes:
183
+ - `m365_user_update` — allowlisted attributes only; users holding an admin role additionally require a privileged Entra role and are refused by Graph (permission_missing)
184
+ - `m365_user_set_account_enabled` — Microsoft requires User.Read.All together with User.EnableDisableAccount.All
185
+ - `m365_group_member_add` — role-assignable groups are refused (would need RoleManagement.ReadWrite.Directory)
186
+ - `m365_team_member_add` — members only — owner role is out of scope in v1
187
+ - `m365_team_member_remove` — owners are refused
188
+ - `m365_team_channel_create` — standard channels only
189
+
190
+ **`User.ReadWrite.All`** is the narrowest application permission Graph offers for the profile
191
+ attributes of `m365_user_update` (the `User-*` permissions cover only phones, mail or password
192
+ profile). Drop the `users` family from `M365_WRITE_FAMILIES` if you do not need it.
193
+
194
+ ### Refused by default
195
+
196
+ The token provider **refuses** a token carrying any of: `Directory.ReadWrite.All`,
197
+ `RoleManagement.ReadWrite.Directory`, `Application.ReadWrite.All`, `AppRoleAssignment.ReadWrite.All`,
198
+ `Policy.ReadWrite.ConditionalAccess`, `UserAuthenticationMethod.ReadWrite.All` (`forbidden_permission`).
199
+ `M365_ALLOW_BROAD_PERMISSIONS=true` lifts this knowingly — do not. Never give a technical user the
200
+ Global Administrator role for this server: it uses application permissions only.
201
+ `m365_capabilities` also warns when the **read** identity holds any write permission.
202
+
203
+ Every token is also checked for `tid` = `M365_TENANT_ID`, `appid` = the configured client id and
204
+ `aud` = Microsoft Graph (`tenant_mismatch` / `auth_failed` otherwise). `M365_TENANT_ID` must be a
205
+ GUID: `common`, `organizations` or a domain name are refused — no implicit multi-tenant authority.
206
+
207
+ ## Environment
208
+
209
+ | Variable | Default | Meaning |
210
+ |---|---|---|
211
+ | `M365_MODE` | `readonly` | `readonly` or `full`; any other value is a startup error |
212
+ | `M365_TENANT_ID` | — | Tenant GUID (required) |
213
+ | `M365_READ_CLIENT_ID` | — | Read application (client) id (required) |
214
+ | `M365_READ_FEDERATED_TOKEN_FILE` | — | **1st choice** — file with the platform's OIDC token (workload identity federation), re-read at each token request |
215
+ | `M365_READ_CERT_PATH` / `M365_READ_KEY_PATH` | — | **2nd choice** — PEM certificate (+ unencrypted private key, in the same file or `KEY_PATH`) |
216
+ | `M365_READ_CLIENT_SECRET` | — | **Acceptance testing only** — warning printed at startup |
217
+ | `M365_WRITE_*` | — | Same variables for the write application, **read only when `M365_MODE=full`** — missing ⇒ startup failure; same client id as read ⇒ startup failure |
218
+ | `M365_WRITE_FAMILIES` | all | Comma list of `users`, `licenses`, `groups`, `teams` — or `none` |
219
+ | `M365_WRITE_KILL_SWITCH_FILE` | — | While this file exists, every write is refused (checked at each call) |
220
+ | `M365_AUDIT_LOG_FILE` | — | Also append the audit trail to this file |
221
+ | `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) |
222
+ | `M365_AUDIT_HASH_KEY` | — | Required with `hash`: ≥ 16 characters, kept secret (redacted everywhere) |
223
+ | `M365_ENABLE_SIGNIN_AUDIT` | `false` | Register `m365_audit_signins` |
224
+ | `M365_ALLOW_BROAD_PERMISSIONS` | `false` | Accept tokens with the refused permissions above |
225
+
226
+ Exactly one credential per identity: several ⇒ startup error. Tokens are cached **in memory only**
227
+ (renewed 5 min before expiry) — there is no MSAL / token cache on disk. The Graph base URL is not
228
+ configurable from the environment (tests inject it), and only `v1.0` is used.
229
+
230
+ ## Register
231
+
232
+ ```bash
233
+ # readonly, certificate (recommended outside a federated platform)
234
+ claude mcp add m365 --scope user \
235
+ -e M365_TENANT_ID=<tenant-guid> \
236
+ -e M365_READ_CLIENT_ID=<read-app-guid> -e M365_READ_CERT_PATH=/etc/m365-mcp/read.pem \
237
+ -- npx -y @aidalinfo/m365-mcp
238
+
239
+ # full, workload identity federation (e.g. Kubernetes service account token)
240
+ claude mcp add m365 --scope user \
241
+ -e M365_MODE=full -e M365_TENANT_ID=<tenant-guid> \
242
+ -e M365_READ_CLIENT_ID=<read-app-guid> -e M365_READ_FEDERATED_TOKEN_FILE=/var/run/secrets/tokens/m365-read \
243
+ -e M365_WRITE_CLIENT_ID=<write-app-guid> -e M365_WRITE_FEDERATED_TOKEN_FILE=/var/run/secrets/tokens/m365-write \
244
+ -e M365_WRITE_FAMILIES=groups,teams -e M365_WRITE_KILL_SWITCH_FILE=/run/m365-mcp/STOP \
245
+ -e M365_AUDIT_LOG_FILE=/var/log/m365-mcp/audit.jsonl \
246
+ -- npx -y @aidalinfo/m365-mcp
247
+ ```
248
+
249
+ ## Runbook — Entra identities
250
+
251
+ ### 1. Create the two applications
252
+
253
+ Entra admin center → **Identity → Applications → App registrations → New registration**, twice:
254
+ `m365-mcp-read` and `m365-mcp-write`, *Accounts in this organizational directory only* (single
255
+ tenant), no redirect URI. Note each **Application (client) ID** and the **Directory (tenant) ID**.
256
+ Set **Owners** to named administrators (not a technical account) and, under *Enterprise
257
+ applications → the app → Properties*, *Visible to users* = No.
258
+
259
+ ### 2. Add the permissions
260
+
261
+ *API permissions → Add a permission → Microsoft Graph → **Application permissions***, from the
262
+ matrix above — read permissions on `m365-mcp-read` only, write permissions on `m365-mcp-write`
263
+ only (plus `User.Read.All` there if you use `m365_user_set_account_enabled`). Remove the default
264
+ delegated `User.Read`, which is useless here. Nothing from the *Refused by default* list.
265
+
266
+ ### 3. Grant admin consent
267
+
268
+ *API permissions → **Grant admin consent for <tenant>*** (Privileged Role Administrator or Global
269
+ Administrator, as a human, once). Each line must show *Granted*. Equivalent check in Graph
270
+ Explorer / PowerShell: `GET /servicePrincipals(appId='<client-id>')/appRoleAssignments`.
271
+
272
+ ### 4. Give each app a credential
273
+
274
+ - **Workload identity federation (preferred)** — *Certificates & secrets → Federated credentials →
275
+ Add*: choose the scenario (Kubernetes: issuer = cluster OIDC issuer URL, subject =
276
+ `system:serviceaccount:<namespace>:<service-account>`; GitHub Actions; or *Other issuer*),
277
+ audience `api://AzureADTokenExchange`. Mount the projected token with that audience and point
278
+ `M365_*_FEDERATED_TOKEN_FILE` at it. No secret exists anywhere.
279
+ - **Certificate** — generate the key where it will live and upload only the public part:
280
+ ```bash
281
+ openssl req -x509 -newkey rsa:3072 -sha256 -days 365 -nodes \
282
+ -keyout m365-mcp-read.key -out m365-mcp-read.crt -subj "/CN=m365-mcp-read"
283
+ cat m365-mcp-read.crt m365-mcp-read.key > /etc/m365-mcp/read.pem && chmod 600 /etc/m365-mcp/read.pem
284
+ ```
285
+ *Certificates & secrets → Certificates → Upload* `m365-mcp-read.crt`. The server signs a PS256
286
+ client assertion with the `x5t#S256` thumbprint; `m365_capabilities` shows the thumbprint and the
287
+ days left (warning under 30).
288
+ - **Client secret** — only for a temporary acceptance environment, shortest expiry, deleted after.
289
+
290
+ Never commit `.env`, `.pem`, `.key`, `.pfx` or token files (the package `.gitignore` covers them).
291
+
292
+ ### 5. Verify the roles actually present in the token — without showing it
293
+
294
+ Run the server and call **`m365_capabilities`**: it decodes the token **inside the server** and
295
+ returns only the `roles` claim, the tenant, the application id and the expiry, plus the per-tool
296
+ status. Nothing else is needed; never paste a token into a website to decode it.
297
+
298
+ ### 6. Rotation
299
+
300
+ - Certificate: upload the new certificate to the app (both coexist), deploy the new PEM, restart,
301
+ check the thumbprint in `m365_capabilities`, then delete the old certificate in Entra.
302
+ - Federation: nothing to rotate (the platform refreshes the token); review the subject/issuer when
303
+ the namespace or service account changes.
304
+ - Secret: create the new one, deploy, restart, delete the old one — and plan the move to a
305
+ certificate.
306
+
307
+ ### 7. Revocation and emergency stop
308
+
309
+ From fastest to most definitive:
310
+
311
+ 1. **Kill switch** — `touch "$M365_WRITE_KILL_SWITCH_FILE"`: every write is refused at once, no
312
+ restart; reads keep working. The file is checked before the preview, again after the
313
+ confirmation token is validated, and once more right before each mutating Graph request.
314
+ `rm` it to resume.
315
+ 2. **Back to readonly** — set `M365_MODE=readonly` (or `M365_WRITE_FAMILIES=none`) and restart: the
316
+ write identity is no longer loaded and the write tools disappear.
317
+ 3. **Disable the write app in Entra** — *Enterprise applications → m365-mcp-write → Properties →
318
+ Enabled for users to sign in? = No* (or delete its credentials / federated credentials, or revoke
319
+ the admin consent): no new write token can be issued tenant-wide, whatever runs where. Existing
320
+ tokens expire within their lifetime (≈ 1 h).
321
+
322
+ The read identity is independent: revoking the write app keeps the diagnostics.
323
+
324
+ ## Smoke test (real tenant)
325
+
326
+ Copy `.env.example` to `.env`, fill it, build (`npm run build`), then:
327
+
328
+ ```bash
329
+ node smoke.mjs # read identity: capabilities, organization, 5 users, SKUs, groups, Teams
330
+ node smoke.mjs --write # write identity, on dedicated acceptance objects only
331
+ ```
332
+
333
+ `--write` requires `M365_MODE=full`, `M365_SMOKE_USER` and at least one of `M365_SMOKE_GROUP`,
334
+ `M365_SMOKE_TEAM`, `M365_SMOKE_SKU`. **Create dedicated acceptance objects** (user, security group,
335
+ team, a spare licence) whose names contain `M365_SMOKE_MARKER` (default `recette`); the script
336
+ refuses to confirm any write whose target does not. It adds then removes the user in the group and
337
+ the team, assigns then removes the licence — the tenant ends as it started — exercising preview,
338
+ confirmation and idempotence. Both modes finish by checking that **no secret value, private key,
339
+ federated token or JWT** appears in the server's stderr or in any MCP response (exit 1 otherwise).
340
+
341
+ ## Progressive rollout
342
+
343
+ 1. Deploy in `readonly`; run `node smoke.mjs`; review `m365_capabilities` (no missing permission,
344
+ no write permission on the read app).
345
+ 2. Check the real tenant inventory (users, SKUs, groups, Teams).
346
+ 3. Create the acceptance user / group / team / spare licence.
347
+ 4. Enable `full` **on the acceptance environment only**; run `node smoke.mjs --write`.
348
+ 5. Validate the audit trail and the Pulse Chat approval workflow (`approvalId` correlation).
349
+ 6. Enable in production only the validated families (`M365_WRITE_FAMILIES`), with the kill switch
350
+ path configured.
351
+
352
+ ## Development
353
+
354
+ ```bash
355
+ npm run build -w @aidalinfo/m365-mcp
356
+ npm test -w @aidalinfo/m365-mcp # build + type-check of tests + jest (no tenant needed)
357
+ ```
358
+
359
+ Tests run against a fake Microsoft (token endpoint + Graph) and cover: configuration validation,
360
+ mode and family gating, `full` without write identity, pagination / caps / cursors, `Retry-After`
361
+ and bounded retries, Graph error normalisation, redaction of secrets and tokens, allowlists, ambiguous
362
+ targets, preview/confirmation bound to target and state, idempotence of members and licences,
363
+ `request-id` propagation, `@odata.nextLink` host pinning, certificate assertion signature, and the
364
+ compiled server started over MCP stdio.
365
+
366
+ ## Validation status
367
+
368
+ - Unit and contract tests: passing, without tenant access.
369
+ - To confirm on a real tenant (Graph behaviours not testable offline): the advanced query
370
+ `GET /groups/{id}/members?$filter=id eq '…'` used for the membership pre-check, `GET /teams?$filter=displayName eq …`
371
+ used to resolve a team by name, and the team settings returned by `GET /teams/{id}` with the read permissions above.
372
+ - **Not yet validated against a real tenant** — run the smoke tests (read, then write on acceptance
373
+ objects) before enabling writes in production, as per the rollout above.
package/dist/audit.js ADDED
@@ -0,0 +1,52 @@
1
+ import { createHmac } from "node:crypto";
2
+ import { appendFileSync } from "node:fs";
3
+ import { redact } from "./redact.js";
4
+ /**
5
+ * Structured audit trail of every write attempt (preview, success, no-op, refusal, failure),
6
+ * one JSON object per line on stderr and, optionally, appended to M365_AUDIT_LOG_FILE.
7
+ *
8
+ * `approvalId` is recorded as `approvalRef` with `verified: false`: it correlates the entry with
9
+ * the Pulse Chat approval, it is not an authorisation (anyone calling the tool can type a string).
10
+ */
11
+ export class AuditLogger {
12
+ ctx;
13
+ entries = [];
14
+ constructor(ctx) {
15
+ this.ctx = ctx;
16
+ }
17
+ log(e) {
18
+ const targetId = e.targetId && this.ctx.targetIdPolicy === "hash"
19
+ ? `hmac:${createHmac("sha256", this.ctx.hashKey ?? "").update(e.targetId).digest("hex").slice(0, 32)}`
20
+ : e.targetId;
21
+ const ids = e.graphRequestIds?.filter(Boolean) ?? [];
22
+ const entry = redact({
23
+ timestamp: (this.ctx.now ?? (() => new Date()))().toISOString(),
24
+ tool: e.tool,
25
+ mode: this.ctx.mode,
26
+ tenant: this.ctx.tenant,
27
+ identity: this.ctx.writeClientId ? { role: "write", clientId: this.ctx.writeClientId } : undefined,
28
+ targetType: e.targetType,
29
+ targetId,
30
+ operation: e.operation,
31
+ graphRequestId: ids.at(-1),
32
+ graphRequestIds: ids.length > 1 ? ids : undefined,
33
+ result: e.result,
34
+ errorCode: e.errorCode,
35
+ approvalRef: e.approvalId ? { id: e.approvalId, verified: false } : undefined,
36
+ });
37
+ const line = JSON.stringify(entry);
38
+ (this.ctx.sink ?? ((l) => process.stderr.write(`${l}\n`)))(line);
39
+ if (this.ctx.file) {
40
+ try {
41
+ appendFileSync(this.ctx.file, `${line}\n`, { mode: 0o600 });
42
+ }
43
+ catch (err) {
44
+ process.stderr.write(`⚠ audit log file not writable (${err.code ?? "error"}) — entry kept on stderr only\n`);
45
+ }
46
+ }
47
+ this.entries.push(entry);
48
+ if (this.entries.length > 200)
49
+ this.entries.shift();
50
+ return entry;
51
+ }
52
+ }
@@ -0,0 +1,120 @@
1
+ import { createHash, createPrivateKey, randomUUID, sign, constants, X509Certificate } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
3
+ import { ConfigError } from "../config.js";
4
+ import { registerSecret } from "../redact.js";
5
+ const JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
6
+ const b64url = (b) => Buffer.from(b).toString("base64url");
7
+ /** Workload identity federation: the platform writes a short-lived OIDC token to a file; re-read at each request. */
8
+ class FederatedCredential {
9
+ tokenFile;
10
+ kind = "federated";
11
+ constructor(tokenFile) {
12
+ this.tokenFile = tokenFile;
13
+ }
14
+ describe() {
15
+ return { method: "workload identity federation", tokenFile: this.tokenFile };
16
+ }
17
+ formFields() {
18
+ let assertion;
19
+ try {
20
+ assertion = readFileSync(this.tokenFile, "utf-8").trim();
21
+ }
22
+ catch (err) {
23
+ throw new ConfigError(`cannot read the federated token file ${this.tokenFile}: ${err.code ?? "error"}`);
24
+ }
25
+ if (!assertion)
26
+ throw new ConfigError(`the federated token file ${this.tokenFile} is empty`);
27
+ registerSecret(assertion);
28
+ return { client_assertion_type: JWT_BEARER, client_assertion: assertion };
29
+ }
30
+ }
31
+ /**
32
+ * Certificate: signs a client assertion (PS256, `x5t#S256` header) with the private key,
33
+ * as documented for Microsoft identity platform certificate credentials.
34
+ */
35
+ class CertificateCredential {
36
+ clientId;
37
+ now;
38
+ kind = "certificate";
39
+ key;
40
+ thumbprint;
41
+ cert;
42
+ constructor(clientId, certPath, keyPath, now) {
43
+ this.clientId = clientId;
44
+ this.now = now;
45
+ const certPem = readPem(certPath, "certificate");
46
+ const keyPem = keyPath ? readPem(keyPath, "private key") : certPem;
47
+ const certBlock = certPem.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/);
48
+ if (!certBlock)
49
+ throw new ConfigError(`no PEM certificate found in ${certPath}`);
50
+ try {
51
+ this.cert = new X509Certificate(certBlock[0]);
52
+ this.key = createPrivateKey(keyPem);
53
+ }
54
+ catch {
55
+ throw new ConfigError(`unreadable certificate or private key (${keyPath ?? certPath}) — expected PEM, unencrypted private key`);
56
+ }
57
+ if (!this.cert.checkPrivateKey(this.key))
58
+ throw new ConfigError("the private key does not match the certificate");
59
+ this.thumbprint = b64url(createHash("sha256").update(this.cert.raw).digest());
60
+ }
61
+ describe() {
62
+ const notAfter = new Date(this.cert.validTo);
63
+ return {
64
+ method: "certificate",
65
+ thumbprintSha256: this.thumbprint,
66
+ subject: this.cert.subject.replace(/\n/g, ", "),
67
+ notAfter: notAfter.toISOString(),
68
+ expiresInDays: Math.floor((notAfter.getTime() - this.now()) / 86_400_000),
69
+ };
70
+ }
71
+ formFields(audience) {
72
+ const now = Math.floor(this.now() / 1000);
73
+ const header = { alg: "PS256", typ: "JWT", "x5t#S256": this.thumbprint };
74
+ const payload = { aud: audience, iss: this.clientId, sub: this.clientId, jti: randomUUID(), nbf: now, iat: now, exp: now + 600 };
75
+ const input = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;
76
+ const sig = sign("sha256", Buffer.from(input), {
77
+ key: this.key,
78
+ padding: constants.RSA_PKCS1_PSS_PADDING,
79
+ saltLength: constants.RSA_PSS_SALTLEN_DIGEST,
80
+ });
81
+ const assertion = `${input}.${b64url(sig)}`;
82
+ return { client_assertion_type: JWT_BEARER, client_assertion: assertion };
83
+ }
84
+ }
85
+ class SecretCredential {
86
+ secret;
87
+ kind = "secret";
88
+ constructor(secret) {
89
+ this.secret = secret;
90
+ registerSecret(secret);
91
+ }
92
+ describe() {
93
+ return { method: "client secret", warning: "acceptance testing only — use federation or a certificate in production" };
94
+ }
95
+ formFields() {
96
+ return { client_secret: this.secret };
97
+ }
98
+ }
99
+ function readPem(path, what) {
100
+ try {
101
+ const pem = readFileSync(path, "utf-8");
102
+ // the key itself is masked by the PEM pattern of redact; register it too in case it leaks un-armoured
103
+ for (const m of pem.matchAll(/-----BEGIN [A-Z ]*PRIVATE KEY-----([\s\S]+?)-----END/g))
104
+ registerSecret(m[1].replace(/\s+/g, ""));
105
+ return pem;
106
+ }
107
+ catch (err) {
108
+ throw new ConfigError(`cannot read the ${what} file ${path}: ${err.code ?? "error"}`);
109
+ }
110
+ }
111
+ export function createCredential(id, now = Date.now) {
112
+ switch (id.auth.kind) {
113
+ case "federated":
114
+ return new FederatedCredential(id.auth.tokenFile);
115
+ case "certificate":
116
+ return new CertificateCredential(id.clientId, id.auth.certPath, id.auth.keyPath, now);
117
+ case "secret":
118
+ return new SecretCredential(id.auth.secret);
119
+ }
120
+ }