@aidalinfo/m365-mcp 0.5.0 → 0.5.3

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 CHANGED
@@ -76,7 +76,7 @@ Outlook / calendar connectors: these identities are dedicated to this server.
76
76
  | Licence | Tools (or parts) | Without it |
77
77
  |---|---|---|
78
78
  | **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*) |
79
- | **Entra ID P2** | `m365_directory_roles view=eligible` (PIM) | `unsupported_by_tenant` |
79
+ | **Entra ID P2** | `m365_directory_roles view=eligible` (PIM) | `unsupported_by_tenant` (see *PIM control unavailable* below) |
80
80
  | **Intune** (Business Premium, EMS) | `m365_intune_devices` | `unsupported_by_tenant` |
81
81
 
82
82
  The tools stay registered on every tenant. `m365_capabilities` reads the tenant's service plans
@@ -132,9 +132,20 @@ A refused or unavailable API never looks like an empty list — the tool answers
132
132
  | `not_found` / `ambiguous_target` | Nothing matches / several objects match a name — pass the id |
133
133
  | `conflict` | Already exists, concurrent change, precondition failed |
134
134
  | `throttled` / `transient` | 429 after the bounded retries (with `Retry-After`) / 5xx, timeout, network |
135
+ | `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 |
135
136
  | `auth_failed` / `tenant_mismatch` / `forbidden_permission` | Token refused / token for another tenant or app / token carries a permission refused by policy |
136
137
  | `refused` / `confirmation_invalid` | A guard refused the write / the confirmation token is expired, reused, or the state changed |
137
138
 
139
+ **PIM control unavailable.** `m365_directory_roles view=eligible` concludes to a missing Entra ID P2
140
+ licence only when Graph says so or refuses while the subscribed SKUs carry no `AAD_PREMIUM_P2` plan. The
141
+ PIM back end has also been seen answering HTTP 400 `UnknownError` / `CultureNotFoundException` ("Culture
142
+ is not supported … `*` is an invalid culture identifier"): that is reported as `service_error` with the
143
+ status, Graph's code and the request ids. It says nothing about the licence, the eligible roles or the
144
+ application's rights — report the PIM control as *not performed*, never as "no eligible role", and do
145
+ not add permissions or roles to work around it. Node's `fetch` sends `Accept-Language: *` when no
146
+ language is set, so the server names `Accept-Language: en-US` on this PIM request only (no other Graph
147
+ call, no retry); whether `*` was the cause on the affected tenant has not been confirmed there.
148
+
138
149
  Each error carries Microsoft's `request-id` (quote it to Microsoft support) and the
139
150
  `client-request-id` the server sent. The raw Graph body is never returned.
140
151
 
@@ -309,15 +320,15 @@ permissions, granted per team instead of tenant-wide, work too but do not appear
309
320
  | `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` | — | — | — |
310
321
  | `m365_group_members` | `GET /groups/{id}/members` | `GroupMember.Read.All` + `User.Read.All` | `Directory.Read.All` | — | — | — |
311
322
  | `m365_teams` | `GET /teams` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `Directory.Read.All` | — | — | — |
312
- | `m365_team_info` | `GET /teams/{id}` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `TeamSettings.ReadWrite.All`, `Directory.Read.All` | `TeamSettings.Read.Group` | — | — |
323
+ | `m365_team_info` | `GET /teams/{id}` | `Team.ReadBasic.All` | `TeamSettings.Read.All`, `Directory.Read.All` | `TeamSettings.Read.Group` | — | — |
313
324
  | `m365_team_channels` | `GET /teams/{id}/channels` | `Channel.ReadBasic.All` | `ChannelSettings.Read.All`, `Directory.Read.All` | `ChannelSettings.Read.Group` | — | — |
314
- | `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `TeamMember.ReadWrite.All`, `Directory.Read.All` | `TeamMember.Read.Group` | — | — |
315
- | `m365_channel_members` | `GET /teams/{id}/channels/{channelId}/members` | `ChannelMember.Read.All` | `ChannelMember.ReadWrite.All`, `Directory.Read.All` | `ChannelMember.Read.Group` | — | — |
325
+ | `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `Directory.Read.All` | `TeamMember.Read.Group` | — | — |
326
+ | `m365_channel_members` | `GET /teams/{id}/channels/{channelId}/members` | `ChannelMember.Read.All` | `Directory.Read.All` | `ChannelMember.Read.Group` | — | — |
316
327
  | `m365_usage_reports` | `GET /reports/getMailboxUsageDetail(period='D7')`<br>`GET /reports/getOneDriveUsageAccountDetail(period=…)`<br>`GET /reports/getSharePointSiteUsageDetail(period=…)`<br>`GET /reports/getOffice365ActiveUserDetail(period=…)` | `Reports.Read.All` | — | — | mailbox type (recipientType / withMailboxType) — or the exchange feature of the audit identity: `MailboxSettings.Read` | — |
317
328
  | `m365_service_health` | `GET /admin/serviceAnnouncement/healthOverviews`<br>`GET /admin/serviceAnnouncement/issues`<br>`GET /admin/serviceAnnouncement/messages` | `ServiceHealth.Read.All` | — | — | view=messages (message center): `ServiceMessage.Read.All` | — |
318
- | `m365_sites` | `GET /sites/getAllSites`<br>`GET /sites?search=… (fallback: search=*)` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Sites.FullControl.All` | — | — | — |
319
- | `m365_site_info` | `GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root`<br>`GET /sites/{id}/drives` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Sites.FullControl.All` | — | — | — |
320
- | `m365_sharing_links` | `GET /drives/{driveId}/root:/{path}:`<br>`GET /drives/{driveId}/items/{itemId}/children`<br>`GET /drives/{driveId}/items/{itemId}/permissions` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Files.Read.All` | — | — | — |
329
+ | `m365_sites` | `GET /sites/getAllSites`<br>`GET /sites?search=… (fallback: search=*)` | `Sites.Read.All` | — | — | — | — |
330
+ | `m365_site_info` | `GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root`<br>`GET /sites/{id}/drives` | `Sites.Read.All` | — | — | — | — |
331
+ | `m365_sharing_links` | `GET /drives/{driveId}/root:/{path}:`<br>`GET /drives/{driveId}/items/{itemId}/children`<br>`GET /drives/{driveId}/items/{itemId}/permissions` | `Sites.Read.All` | `Files.Read.All` | — | — | — |
321
332
  | `m365_directory_roles` | `GET /roleManagement/directory/roleAssignments?$expand=principal`<br>`GET /roleManagement/directory/roleDefinitions`<br>`GET /roleManagement/directory/roleEligibilityScheduleInstances (view=eligible)` | `RoleManagement.Read.Directory` | `RoleManagement.Read.All`, `Directory.Read.All` | — | view=eligible (PIM): `RoleManagement.Read.Directory` (Entra ID P2) | — |
322
333
  | `m365_user_auth_methods` | `GET /users/{id}/authentication/methods`<br>`GET /reports/authenticationMethods/userRegistrationDetails (tenant view)` | `UserAuthenticationMethod.Read.All` | — | — | tenant view (without user): `AuditLog.Read.All` (Entra ID P1) | — |
323
334
  | `m365_user_activity` | `GET /users?$select=…,signInActivity` | `AuditLog.Read.All` + `User.Read.All` | — | — | — | Entra ID P1 |
@@ -400,14 +411,37 @@ grants and application deletion stay out of scope. Scalar PATCH operations re-re
400
411
  the request and preserve unrelated fields. This implementation does not claim atomic concurrency
401
412
  control: a narrow residual last-writer-wins window remains and is documented explicitly.
402
413
 
403
- ### Refused by default
414
+ ### Read identity: read permissions only
415
+
416
+ The token provider **refuses** (`forbidden_permission`) a read-identity token carrying any
417
+ permission that is not a read, before any Graph call. One classification (`classifyPermission` in
418
+ `src/permissions.ts`) is shared by the token provider and `m365_capabilities`:
419
+
420
+ - **read** — `<Resource>.Read` or `<Resource>.ReadBasic`, optionally followed by plain scope segments
421
+ (`User.Read.All`, `RoleManagement.Read.Directory`, `MailboxSettings.Read`). Every permission of the
422
+ read matrix above has this shape and is accepted;
423
+ - **write** — a segment after the resource names a write verb (`ReadWrite`, `FullControl`,
424
+ `EnableDisable`, `Create`, `Manage`, `Send`, `Invite`, `Selected`…): `User.ReadWrite.All`,
425
+ `GroupMember.ReadWrite.All`, `LicenseAssignment.ReadWrite.All`, `User.EnableDisableAccount.All`,
426
+ `Sites.FullControl.All`, `Sites.ReadWrite.All`, the broad permissions below…;
427
+ - **unknown** — any other shape (`Calls.JoinGroupCall.All`…): **fail-closed**, treated as a write.
428
+
429
+ The error names every refused permission (writes and unrecognised ones separately), never a token
430
+ or a secret. `M365_ALLOW_BROAD_PERMISSIONS` **does not apply** to the read identity, and there is no
431
+ compatibility switch: remove the permission from the read Entra app (the server never changes Entra
432
+ permissions or consents itself) and give writes to the separate write identity (`M365_WRITE_CLIENT_ID`,
433
+ `M365_MODE=full`). Since 0.5.3 the read tools no longer list write permissions (`Sites.ReadWrite.All`,
434
+ `Sites.FullControl.All`, `TeamSettings.ReadWrite.All`, `TeamMember.ReadWrite.All`,
435
+ `ChannelMember.ReadWrite.All`) as "also accepted".
404
436
 
405
- The token provider **refuses** a token carrying any of: `Directory.ReadWrite.All`,
437
+ ### Refused by default (write identity)
438
+
439
+ The token provider **refuses** a write-identity token carrying any of: `Directory.ReadWrite.All`,
406
440
  `RoleManagement.ReadWrite.Directory`, `Application.ReadWrite.All`, `AppRoleAssignment.ReadWrite.All`,
407
441
  `Policy.ReadWrite.ConditionalAccess`, `UserAuthenticationMethod.ReadWrite.All` (`forbidden_permission`).
408
- `M365_ALLOW_BROAD_PERMISSIONS=true` lifts this knowingly — do not. Never give a technical user the
409
- Global Administrator role for this server: it uses application permissions only.
410
- `m365_capabilities` also warns when the **read** identity holds any write permission.
442
+ `M365_ALLOW_BROAD_PERMISSIONS=true` lifts this knowingly for the write identity only — do not. It
443
+ never lifts the read-identity check above, nor the exact allowlist of the entra identity. Never give
444
+ a technical user the Global Administrator role for this server: it uses application permissions only.
411
445
 
412
446
  Every token is also checked for `tid` = `M365_TENANT_ID`, `appid` = the configured client id and
413
447
  `aud` = Microsoft Graph (`tenant_mismatch` / `auth_failed` otherwise). `M365_TENANT_ID` must be a
@@ -511,7 +545,7 @@ or the smoke script): history builds up to the retention. Unified audit must be
511
545
  | `M365_SHAREPOINT_HOST` | — | Required by `sharepoint`: `<tenant>.sharepoint.com`, the only host its token goes to |
512
546
  | `M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL` | `false` | Accept `Sites.FullControl.All` instead of `Sites.Selected` — discouraged |
513
547
  | `M365_SNAPSHOT_DIR` | — | Absolute directory where `m365_access_review_snapshot` writes its dated JSON files (`0600`) and finds the previous ones; unset ⇒ the review is answered but not saved, and `compareWith` is refused |
514
- | `M365_ALLOW_BROAD_PERMISSIONS` | `false` | Accept tokens with the refused permissions above |
548
+ | `M365_ALLOW_BROAD_PERMISSIONS` | `false` | Accept write-identity tokens with the refused permissions above (never the read identity) |
515
549
 
516
550
  Exactly one credential per identity: several ⇒ startup error. Tokens are cached **in memory only**
517
551
  (renewed 5 min before expiry) — there is no MSAL / token cache on disk. The Graph base URL is not
@@ -684,6 +718,17 @@ snapshot, signals and comparison end to end.
684
718
 
685
719
  ## Validation status
686
720
 
721
+ - 0.5.3 (#138): the read identity refuses every write or unrecognised Graph permission
722
+ (`User.ReadWrite.All`, `Sites.FullControl.All`…), even with `M365_ALLOW_BROAD_PERMISSIONS=true`,
723
+ with one shared classification (`classifyPermission`). Unit tests passing; a read app holding a
724
+ write permission now fails with `forbidden_permission` instead of a warning in `m365_capabilities`.
725
+
726
+ - 0.5.2: a 4xx that only carries an internal Microsoft exception (`UnknownError` /
727
+ `CultureNotFoundException` on the PIM API) is `service_error`, no longer `unsupported_by_tenant`;
728
+ a missing licence is not asserted when the subscribed SKUs show it. Unit tests passing on fixtures;
729
+ **to validate on the affected tenant**: whether `Accept-Language: en-US` on the PIM request removes
730
+ the HTTP 400 (the origin of the `*` culture is not established).
731
+
687
732
  - 0.4.2: a connection dropped while the answer is read (Node's `terminated`) is retried like a failed
688
733
  request, then reported as `transient` with the HTTP status and the Microsoft request-id — it used to
689
734
  surface as `unexpected: terminated`, which hid whether Exchange or the network had refused.
@@ -1,5 +1,6 @@
1
1
  import { M365Error } from "../errors.js";
2
2
  import { defaultFetcher, DEFAULT_TIMEOUT_MS } from "../http.js";
3
+ import { classifyPermission, notReadPermissions } from "../permissions.js";
3
4
  import { registerSecret } from "../redact.js";
4
5
  import { createCredential } from "./credentials.js";
5
6
  export const DEFAULT_AUTHORITY = "https://login.microsoftonline.com";
@@ -8,8 +9,10 @@ const GRAPH_AUDIENCES = new Set(["https://graph.microsoft.com", "https://graph.m
8
9
  /** Renew this long before expiry, so a token never expires mid-request. */
9
10
  const EXPIRY_MARGIN_MS = 5 * 60_000;
10
11
  /**
11
- * Application permissions refused by default: they would let the MCP rewrite the directory,
12
- * assign Entra roles or mint credentials — outside the v1 scope. Override: M365_ALLOW_BROAD_PERMISSIONS.
12
+ * Application permissions refused by default on the write identity: they would let the MCP rewrite
13
+ * the directory, assign Entra roles or mint credentials — outside the v1 scope. Override:
14
+ * M365_ALLOW_BROAD_PERMISSIONS (write identity only). The read identity refuses every permission
15
+ * that is not a read (classifyPermission), whatever this flag says.
13
16
  */
14
17
  export const FORBIDDEN_ROLES = [
15
18
  "Directory.ReadWrite.All",
@@ -203,6 +206,16 @@ export class TokenProvider {
203
206
  if (extra.length)
204
207
  throw new M365Error("forbidden_permission", `forbidden_permission: the entra identity holds roles outside its exact allowlist: ${extra.join(", ")}`);
205
208
  }
209
+ if (this.role === "read") {
210
+ // fail-closed: writes and unrecognised permissions alike; M365_ALLOW_BROAD_PERMISSIONS does not apply here
211
+ const refused = notReadPermissions(roles);
212
+ if (refused.length) {
213
+ const writes = refused.filter((r) => classifyPermission(r) === "write");
214
+ const unknown = refused.filter((r) => classifyPermission(r) === "unknown");
215
+ const held = [writes.length ? `write permission(s) ${writes.join(", ")}` : "", unknown.length ? `unrecognised permission(s) ${unknown.join(", ")} (treated as write)` : ""].filter(Boolean).join(" and ");
216
+ throw new M365Error("forbidden_permission", `forbidden_permission: the read identity holds ${held} — it must hold read permissions only. Remove them from the read Entra app; writes belong to the separate write identity (M365_WRITE_CLIENT_ID, M365_MODE=full). M365_ALLOW_BROAD_PERMISSIONS does not apply to the read identity.`);
217
+ }
218
+ }
206
219
  const hardForbidden = this.role === "entra" && forbidden.length > 0;
207
220
  if (forbidden.length && (hardForbidden || !this.opts.allowBroadPermissions)) {
208
221
  throw new M365Error("forbidden_permission", `forbidden_permission: the ${this.role} application holds ${forbidden.join(", ")} — refused by policy. Remove these permissions from the Entra app (or set M365_ALLOW_BROAD_PERMISSIONS=true knowingly).`);
package/dist/config.js CHANGED
@@ -180,7 +180,7 @@ export function loadConfig(env) {
180
180
  warnings.push("⚠ M365_SHAREPOINT_ALLOW_FULLCONTROL_ALL=true — the audit identity may hold Sites.FullControl.All (tenant-wide full control of SharePoint); prefer Sites.Selected with per-site grants");
181
181
  const activityStartSubscriptions = parseBool(env, "M365_ACTIVITY_START_SUBSCRIPTIONS");
182
182
  if (allowBroadPermissions)
183
- warnings.push("⚠ M365_ALLOW_BROAD_PERMISSIONS=true — tokens with directory-wide write permissions are accepted");
183
+ warnings.push("⚠ M365_ALLOW_BROAD_PERMISSIONS=true — write-identity tokens with directory-wide write permissions are accepted (the read identity still refuses every write permission)");
184
184
  return {
185
185
  mode,
186
186
  tenantId: tenantId.toLowerCase(),
package/dist/errors.js CHANGED
@@ -36,6 +36,15 @@ function graphErrorBody(text) {
36
36
  }
37
37
  /** Graph codes and messages that say "this tenant cannot do it" rather than "you may not". */
38
38
  const UNSUPPORTED = /NonPremiumTenant|B2CTenant|RequestFromUnsupportedUserRole|NotSupported|not supported|not licensed|no license|requires a license|MailboxNotEnabled|not applicable to target tenant|PremiumLicense|premium license/i;
39
+ /**
40
+ * A 4xx whose only content is an internal exception of the Microsoft service (the PIM back end answers
41
+ * HTTP 400 UnknownError / CultureNotFoundException, "Culture is not supported … * is an invalid culture
42
+ * identifier"). It is neither a licence, a permission nor a data statement, and is tested before
43
+ * UNSUPPORTED: the bare words "not supported" in such a message say nothing about the tenant.
44
+ */
45
+ const SERVICE_FAULT = /CultureNotFound|invalid culture identifier|culture is not supported/i;
46
+ const DOTNET_EXCEPTION = /\b[A-Z]\w*Exception\b/;
47
+ const isServiceFault = (graphCode, hay) => SERVICE_FAULT.test(hay) || (graphCode === "UnknownError" && DOTNET_EXCEPTION.test(hay));
39
48
  const LICENSE = /available licenses|CountViolation|LicenseLimit|insufficient.*licen|MutuallyExclusiveViolation|DependsOnViolation|usage ?location/i;
40
49
  const CONFLICT = /already exist|Request_MultipleObjectsWithSameKeyValue|ObjectConflict|PreconditionFailed|conflict/i;
41
50
  /**
@@ -56,6 +65,8 @@ export function fromGraphResponse(status, bodyText, ids = {}) {
56
65
  code = "not_found";
57
66
  else if (status === 409 || status === 412)
58
67
  code = "conflict";
68
+ else if (isServiceFault(graphCode, hay))
69
+ code = "service_error";
59
70
  else if (UNSUPPORTED.test(hay))
60
71
  code = "unsupported_by_tenant";
61
72
  else if (LICENSE.test(hay))
@@ -67,7 +78,11 @@ export function fromGraphResponse(status, bodyText, ids = {}) {
67
78
  else
68
79
  code = "invalid_request";
69
80
  const short = (message ?? "").replace(/\s+/g, " ").slice(0, MAX_MESSAGE);
70
- const hint = code === "permission_missing" ? " — check the application permissions with m365_capabilities (admin consent granted?)" : "";
81
+ const hint = code === "permission_missing"
82
+ ? " — check the application permissions with m365_capabilities (admin consent granted?)"
83
+ : code === "service_error"
84
+ ? " — Microsoft failed on this request with an internal exception: the result is unknown (not an empty list), and this says nothing about the tenant's licences or the application's permissions. Quote the request-id to Microsoft support"
85
+ : "";
71
86
  return new M365Error(code, `${code} (HTTP ${status}${graphCode ? ` ${graphCode}` : ""})${short ? `: ${short}` : ""}${hint}`, {
72
87
  status,
73
88
  graphCode,
@@ -11,7 +11,7 @@ export const MAX_RETRY_AFTER_S = 30;
11
11
  const BACKOFF_BASE_MS = 1000;
12
12
  const BACKOFF_MAX_MS = 10_000;
13
13
  /** Request headers a tool may add; everything else is set by the client. */
14
- const ALLOWED_EXTRA_HEADERS = new Set(["ConsistencyLevel", "Prefer", "Accept"]);
14
+ const ALLOWED_EXTRA_HEADERS = new Set(["ConsistencyLevel", "Prefer", "Accept", "Accept-Language"]);
15
15
  /** Hosts Microsoft serves usage-report CSV downloads from (reports.office.com and its regional variants). */
16
16
  const REPORT_HOST = /^([a-z0-9-]+\.)*(office\.com|office\.net|office365\.com|microsoft\.com)$/i;
17
17
  const FORBIDDEN_PATH = /\.\.|[?#\\\s]|:\/\/|%2e|%2f|%5c/i;
@@ -70,7 +70,7 @@ export const TOOL_SPECS = [
70
70
  access: "read",
71
71
  endpoints: ["GET /teams/{id}"],
72
72
  permissions: ["Team.ReadBasic.All"],
73
- alternatives: ["TeamSettings.Read.All", "TeamSettings.ReadWrite.All", "Directory.Read.All"],
73
+ alternatives: ["TeamSettings.Read.All", "Directory.Read.All"],
74
74
  rsc: ["TeamSettings.Read.Group"],
75
75
  note: "if the member/guest/messaging/fun settings come back empty, add TeamSettings.Read.All",
76
76
  },
@@ -87,7 +87,7 @@ export const TOOL_SPECS = [
87
87
  access: "read",
88
88
  endpoints: ["GET /teams/{id}/members"],
89
89
  permissions: ["TeamMember.Read.All"],
90
- alternatives: ["TeamMember.ReadWrite.All", "Directory.Read.All"],
90
+ alternatives: ["Directory.Read.All"],
91
91
  rsc: ["TeamMember.Read.Group"],
92
92
  },
93
93
  {
@@ -95,7 +95,7 @@ export const TOOL_SPECS = [
95
95
  access: "read",
96
96
  endpoints: ["GET /teams/{id}/channels/{channelId}/members"],
97
97
  permissions: ["ChannelMember.Read.All"],
98
- alternatives: ["ChannelMember.ReadWrite.All", "Directory.Read.All"],
98
+ alternatives: ["Directory.Read.All"],
99
99
  rsc: ["ChannelMember.Read.Group"],
100
100
  note: "private and shared channels have their own members, absent from m365_team_members",
101
101
  },
@@ -124,21 +124,19 @@ export const TOOL_SPECS = [
124
124
  access: "read",
125
125
  endpoints: ["GET /sites/getAllSites", "GET /sites?search=… (fallback: search=*)"],
126
126
  permissions: ["Sites.Read.All"],
127
- alternatives: ["Sites.ReadWrite.All", "Sites.FullControl.All"],
128
127
  },
129
128
  {
130
129
  tool: "m365_site_info",
131
130
  access: "read",
132
131
  endpoints: ["GET /sites/{id} | /sites/{host}:/{path}: | /groups/{id}/sites/root", "GET /sites/{id}/drives"],
133
132
  permissions: ["Sites.Read.All"],
134
- alternatives: ["Sites.ReadWrite.All", "Sites.FullControl.All"],
135
133
  },
136
134
  {
137
135
  tool: "m365_sharing_links",
138
136
  access: "read",
139
137
  endpoints: ["GET /drives/{driveId}/root:/{path}:", "GET /drives/{driveId}/items/{itemId}/children", "GET /drives/{driveId}/items/{itemId}/permissions"],
140
138
  permissions: ["Sites.Read.All"],
141
- alternatives: ["Sites.ReadWrite.All", "Files.Read.All"],
139
+ alternatives: ["Files.Read.All"],
142
140
  note: "bounded walk (depth ≤ 3, ≤ 200 items, target folder required); link URLs are never returned",
143
141
  },
144
142
  {
@@ -420,5 +418,14 @@ export function permissionStatus(spec, roles) {
420
418
  export function planStatus(spec, readRoles) {
421
419
  return (spec.planPermissions ?? []).every((p) => readRoles.includes(p) || readRoles.includes("Directory.Read.All")) ? "granted" : "missing";
422
420
  }
423
- /** A permission whose name says it writes. The read identity should hold none of these. */
424
- export const isWritePermission = (p) => /ReadWrite|EnableDisable|\.Create$|\.Create\./.test(p);
421
+ const WRITE_VERB = /Write|FullControl|Enable|Disable|Create|Manage|Send|Delete|Invite|Export|Import|Revoke|Update|Assign|Selected|Migrate|Restore|Purge|Remove|Add|Accept|Execute|Action|Impersonat/;
422
+ export function classifyPermission(p) {
423
+ const [resource, ...rest] = p.split(".");
424
+ if (!resource || !/^[A-Za-z0-9-]+$/.test(resource) || !rest.length || !rest.every((s) => /^[A-Za-z0-9]+$/.test(s)))
425
+ return "unknown";
426
+ if (rest.some((s) => WRITE_VERB.test(s)))
427
+ return "write";
428
+ return rest[0] === "Read" || rest[0] === "ReadBasic" ? "read" : "unknown";
429
+ }
430
+ /** Permissions the read identity may not hold: writes and, fail-closed, anything not recognised as a read. */
431
+ export const notReadPermissions = (roles) => roles.filter((p) => classifyPermission(p) !== "read");
@@ -1,6 +1,6 @@
1
1
  import { toM365Error } from "../errors.js";
2
2
  import { FORBIDDEN_ROLES } from "../auth/token-provider.js";
3
- import { extraStatus, isWritePermission, permissionStatus, planStatus, TOOL_SPECS } from "../permissions.js";
3
+ import { extraStatus, permissionStatus, planStatus, TOOL_SPECS } from "../permissions.js";
4
4
  import { jsonBlock, tenantHas, textResult } from "./common.js";
5
5
  export const SERVER_INSTRUCTIONS = [
6
6
  "Microsoft 365 MCP over Microsoft Graph (v1.0): Entra ID users, groups and explicitly enabled application management, licences, Teams, SharePoint sites, usage reports, service health, admin roles, MFA, applications and consents, audit logs, Conditional Access, Intune devices. Read-only unless M365_MODE=full.",
@@ -31,11 +31,6 @@ export function registerCapabilityTools(server, ctx) {
31
31
  const entra = ctx.identities.entra ? await inspect(ctx.identities.entra) : undefined;
32
32
  const exchange = ctx.identities.exchange ? await inspect(ctx.identities.exchange) : undefined;
33
33
  const warnings = [...ctx.config.warnings];
34
- if (read.ok) {
35
- const writes = read.roles.filter(isWritePermission);
36
- if (writes.length)
37
- warnings.push(`the READ identity holds write permissions (${writes.join(", ")}) — remove them to keep the identities separate`);
38
- }
39
34
  for (const id of [read, write, entra, exchange]) {
40
35
  if (id?.ok) {
41
36
  const broad = id.roles.filter((r) => FORBIDDEN_ROLES.includes(r));
@@ -201,19 +201,24 @@ export async function tenantHas(ctx, feature) {
201
201
  /**
202
202
  * A Graph refusal on an API that needs a premium licence becomes `unsupported_by_tenant` when the
203
203
  * tenant really lacks it — so "you may not" (permission_missing) and "this tenant cannot" stay distinct.
204
+ * The missing licence is only asserted when the subscribed SKUs do not contradict it; a `service_error`
205
+ * (internal exception of the Microsoft service) is never turned into a licence statement.
204
206
  */
205
207
  export async function premiumError(ctx, err, feature, what) {
206
208
  if (!(err instanceof M365Error))
207
209
  return err;
208
- if (err.code === "unsupported_by_tenant" || ((err.code === "permission_missing" || err.code === "invalid_request") && (await tenantHas(ctx, feature)) === false)) {
209
- return new M365Error("unsupported_by_tenant", `unsupported_by_tenant: ${what} needs ${feature}, which this tenant does not have — ${err.message}`, {
210
- status: err.status,
211
- graphCode: err.graphCode,
212
- requestId: err.requestId,
213
- clientRequestId: err.clientRequestId,
214
- });
215
- }
216
- return err;
210
+ if (err.code !== "unsupported_by_tenant" && err.code !== "permission_missing" && err.code !== "invalid_request")
211
+ return err;
212
+ const has = await tenantHas(ctx, feature);
213
+ // Graph says "unsupported" but the tenant holds the licence: keep Graph's own words, do not invent a missing licence
214
+ if (err.code === "unsupported_by_tenant" ? has === true : has !== false)
215
+ return err;
216
+ return new M365Error("unsupported_by_tenant", `unsupported_by_tenant: ${what} needs ${feature}, which this tenant does not have — ${err.message}`, {
217
+ status: err.status,
218
+ graphCode: err.graphCode,
219
+ requestId: err.requestId,
220
+ clientRequestId: err.clientRequestId,
221
+ });
217
222
  }
218
223
  /**
219
224
  * Every item of a Graph collection, following nextLinks (host-checked), up to `max` items.
@@ -64,6 +64,13 @@ const safeAudit = (a) => ({
64
64
  modifiedProperties: (t.modifiedProperties ?? []).map((p) => p.displayName).filter(Boolean).slice(0, 20),
65
65
  })),
66
66
  });
67
+ /**
68
+ * Node's fetch adds `Accept-Language: *` when the caller sets none (Fetch standard), and the PIM back end
69
+ * has answered HTTP 400 CultureNotFoundException "* is an invalid culture identifier" (#140). A real
70
+ * culture is therefore named on the PIM request only — not on every Graph call, and without any retry.
71
+ * Whether `*` was the cause on the tenant is not established: a failure still surfaces as `service_error`.
72
+ */
73
+ const PIM_HEADERS = { "Accept-Language": "en-US" };
67
74
  export function registerSecurityTools(server, ctx) {
68
75
  server.tool("m365_directory_roles", "Who is administrator of what: active Entra role assignments (Global, Exchange, SharePoint, User administrator…) with the principal (user, group, service principal) and scope. view=eligible lists PIM-eligible assignments (Entra ID P2).", {
69
76
  view: z.enum(["active", "eligible"]).default("active"),
@@ -92,7 +99,7 @@ export function registerSecurityTools(server, ctx) {
92
99
  const path = view === "active" ? "/roleManagement/directory/roleAssignments" : "/roleManagement/directory/roleEligibilityScheduleInstances";
93
100
  let page;
94
101
  try {
95
- page = await listPage(ctx, `m365_directory_roles:${view}:${role ?? ""}:${principalId ?? ""}`, { path, query: { $expand: "principal", $filter: filters.join(" and ") || undefined }, supportsTop: false }, limit, cursor);
102
+ page = await listPage(ctx, `m365_directory_roles:${view}:${role ?? ""}:${principalId ?? ""}`, { path, query: { $expand: "principal", $filter: filters.join(" and ") || undefined }, supportsTop: false, headers: view === "eligible" ? PIM_HEADERS : undefined }, limit, cursor);
96
103
  }
97
104
  catch (err) {
98
105
  throw view === "eligible" ? await premiumError(ctx, err, "Entra ID P2", "PIM eligible role assignments") : err;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aidalinfo/m365-mcp",
3
- "version": "0.5.0",
3
+ "version": "0.5.3",
4
4
  "description": "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 mode uses separate scoped identities with two-step confirmed, audited writes",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",