@aidalinfo/m365-mcp 0.3.0 → 0.3.1

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
@@ -52,7 +52,7 @@ Outlook / calendar connectors: these identities are dedicated to this server.
52
52
  | `m365_team_channels` | Channels (standard / private / shared) with ids |
53
53
  | `m365_team_members` | Members with role (owner / member / guest) and membership id |
54
54
  | `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 |
55
- | `m365_usage_reports` | Storage per mailbox / OneDrive / SharePoint site (bytes **and** GB), mailbox type (`Recipient Type`: User, **Shared**, Room…), last activity per service — filters `search`, `recipientType`, `inactiveDays`, sort by size. Concealed (anonymised) names are detected and flagged |
55
+ | `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 |
56
56
  | `m365_service_health` | Service state, open incidents / advisories, message center — "is it us or Microsoft?" |
57
57
  | `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 |
58
58
  | `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 |
@@ -249,7 +249,7 @@ permissions, granted per team instead of tenant-wide, work too but do not appear
249
249
  | `m365_team_channels` | `GET /teams/{id}/channels` | `Channel.ReadBasic.All` | `ChannelSettings.Read.All`, `Directory.Read.All` | `ChannelSettings.Read.Group` | — | — |
250
250
  | `m365_team_members` | `GET /teams/{id}/members` | `TeamMember.Read.All` | `TeamMember.ReadWrite.All`, `Directory.Read.All` | `TeamMember.Read.Group` | — | — |
251
251
  | `m365_channel_members` | `GET /teams/{id}/channels/{channelId}/members` | `ChannelMember.Read.All` | `ChannelMember.ReadWrite.All`, `Directory.Read.All` | `ChannelMember.Read.Group` | — | — |
252
- | `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` | — | — | — | — |
252
+ | `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` | — |
253
253
  | `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` | — |
254
254
  | `m365_sites` | `GET /sites/getAllSites`<br>`GET /sites?search=… (fallback: search=*)` | `Sites.Read.All` | `Sites.ReadWrite.All`, `Sites.FullControl.All` | — | — | — |
255
255
  | `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` | — | — | — |
@@ -261,7 +261,7 @@ permissions, granted per team instead of tenant-wide, work too but do not appear
261
261
  | `m365_applications` | `GET /servicePrincipals`<br>`GET /servicePrincipals/{id}/appRoleAssignments`<br>`GET /oauth2PermissionGrants (view=delegated_grants)` | `Application.Read.All` | `Directory.Read.All` | — | view=delegated_grants: `DelegatedPermissionGrant.Read.All` | — |
262
262
  | `m365_conditional_access` | `GET /identity/conditionalAccess/policies`<br>`GET /policies/identitySecurityDefaultsEnforcementPolicy` | `Policy.Read.All` | — | — | Conditional Access policies: `Policy.Read.All` (Entra ID P1) | — |
263
263
  | `m365_intune_devices` | `GET /deviceManagement/managedDevices` | `DeviceManagementManagedDevices.Read.All` | — | — | — | Intune |
264
- | `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)<br>delegated consents: `DelegatedPermissionGrant.Read.All` | — |
264
+ | `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)<br>delegated consents: `DelegatedPermissionGrant.Read.All`<br>mailbox types (shared-mailbox signals) — or the exchange feature: `MailboxSettings.Read` | — |
265
265
  | `m365_audit_signins` | `GET /auditLogs/signIns` | `AuditLog.Read.All` | — | — | — | — |
266
266
 
267
267
  Notes:
@@ -269,7 +269,7 @@ Notes:
269
269
  - `m365_group_members` — without User.Read.All, user members come back with their id only
270
270
  - `m365_team_info` — if the member/guest/messaging/fun settings come back empty, add TeamSettings.Read.All
271
271
  - `m365_channel_members` — private and shared channels have their own members, absent from m365_team_members
272
- - `m365_usage_reports` — 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
272
+ - `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
273
273
  - `m365_sharing_links` — bounded walk (depth ≤ 3, ≤ 200 items, target folder required); link URLs are never returned
274
274
  - `m365_user_auth_methods` — method types only — phone numbers, e-mails and keys are never returned
275
275
  - `m365_directory_audit` — retention 7 days without Entra ID P1, 30 days with; modified property values are never returned
@@ -485,7 +485,8 @@ Full read set for every read tool (0.3.0): `User.Read.All`, `GroupMember.Read.Al
485
485
  `TeamSettings.Read.All`, `Channel.ReadBasic.All`, `ChannelMember.Read.All`, `Reports.Read.All`,
486
486
  `Sites.Read.All`, `RoleManagement.Read.Directory` (or `.All`), `AuditLog.Read.All`,
487
487
  `UserAuthenticationMethod.Read.All`, `Application.Read.All`, `DelegatedPermissionGrant.Read.All`,
488
- `Policy.Read.All`, `ServiceHealth.Read.All`, `ServiceMessage.Read.All`, and
488
+ `Policy.Read.All`, `ServiceHealth.Read.All`, `ServiceMessage.Read.All`, `MailboxSettings.Read` (mailbox type
489
+ only — the server reads `mailboxSettings/userPurpose` and nothing else), and
489
490
  `DeviceManagementManagedDevices.Read.All` on Intune tenants. All are read-only.
490
491
 
491
492
  ### 3. Grant admin consent
@@ -0,0 +1,57 @@
1
+ import { M365Error } from "./errors.js";
2
+ import { mapLimit } from "./tools/common.js";
3
+ const FROM_EXCHANGE = { UserMailbox: "User", SharedMailbox: "Shared", RoomMailbox: "Room", EquipmentMailbox: "Equipment", LinkedMailbox: "Linked" };
4
+ const FROM_PURPOSE = { user: "User", shared: "Shared", room: "Room", equipment: "Equipment", linked: "Linked", others: "Others" };
5
+ const TTL_MS = 10 * 60_000;
6
+ const MAX_LOOKUPS = 2000;
7
+ const cache = new WeakMap();
8
+ export async function mailboxTypes(ctx, upns) {
9
+ const wanted = [...new Set(upns.map((u) => u.toLowerCase()).filter((u) => u.includes("@")))];
10
+ const key = wanted.sort().join(",");
11
+ const hit = cache.get(ctx);
12
+ if (hit && hit.key === key && Date.now() - hit.at < TTL_MS)
13
+ return hit.value;
14
+ let value;
15
+ if (ctx.ext.exchange) {
16
+ const { items } = await ctx.ext.exchange.invoke("Get-Mailbox", { ResultSize: 1000 });
17
+ const types = new Map();
18
+ for (const m of items) {
19
+ const t = FROM_EXCHANGE[m.RecipientTypeDetails ?? ""] ?? "Others";
20
+ for (const a of [m.UserPrincipalName, m.PrimarySmtpAddress])
21
+ if (a)
22
+ types.set(a.toLowerCase(), t);
23
+ }
24
+ value = { types, source: "exchange", unresolved: wanted.filter((u) => !types.has(u)) };
25
+ }
26
+ else {
27
+ if (wanted.length > MAX_LOOKUPS)
28
+ throw new M365Error("invalid_request", `invalid_request: ${wanted.length} mailboxes — mailbox types are resolved one by one through Graph above ${MAX_LOOKUPS}: enable the exchange feature (phase 2)`);
29
+ const types = new Map();
30
+ const unresolved = [];
31
+ let denied;
32
+ await mapLimit(wanted, 4, async (upn) => {
33
+ if (denied)
34
+ return;
35
+ try {
36
+ const r = await ctx.graph.get(`/users/${encodeURIComponent(upn)}/mailboxSettings/userPurpose`);
37
+ const t = FROM_PURPOSE[String(r.data?.value ?? "").toLowerCase()];
38
+ if (t)
39
+ types.set(upn, t);
40
+ else
41
+ unresolved.push(upn);
42
+ }
43
+ catch (err) {
44
+ if (err instanceof M365Error && (err.code === "permission_missing" || err.code === "auth_failed"))
45
+ denied = err;
46
+ else
47
+ unresolved.push(upn); // no mailbox / inactive / on-premises: this one only
48
+ }
49
+ });
50
+ if (denied) {
51
+ throw new M365Error("permission_missing", `permission_missing: the mailbox type (shared, room…) is not in the Graph usage report; reading it needs MailboxSettings.Read on the read identity, or the exchange feature of the audit identity — ${denied.message}`, { status: denied.status, requestId: denied.requestId, clientRequestId: denied.clientRequestId });
52
+ }
53
+ value = { types, source: "graph mailboxSettings", unresolved };
54
+ }
55
+ cache.set(ctx, { at: Date.now(), key, value });
56
+ return value;
57
+ }
@@ -109,7 +109,8 @@ export const TOOL_SPECS = [
109
109
  "GET /reports/getOffice365ActiveUserDetail(period=…)",
110
110
  ],
111
111
  permissions: ["Reports.Read.All"],
112
- note: "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",
112
+ extras: [{ part: "mailbox type (recipientType / withMailboxType) — or the exchange feature of the audit identity", permissions: ["MailboxSettings.Read"] }],
113
+ note: "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",
113
114
  },
114
115
  {
115
116
  tool: "m365_service_health",
@@ -212,6 +213,7 @@ export const TOOL_SPECS = [
212
213
  extras: [
213
214
  { part: "last sign-in + tenant MFA report", permissions: ["AuditLog.Read.All"], requires: "Entra ID P1" },
214
215
  { part: "delegated consents", permissions: ["DelegatedPermissionGrant.Read.All"] },
216
+ { part: "mailbox types (shared-mailbox signals) — or the exchange feature", permissions: ["MailboxSettings.Read"] },
215
217
  ],
216
218
  note: "writes a dated JSON file (0600) in M365_SNAPSHOT_DIR; a section that cannot be read is reported, never left empty",
217
219
  },
@@ -1,5 +1,6 @@
1
1
  import { toM365Error } from "../errors.js";
2
2
  import { fetchUsageReport } from "../reports.js";
3
+ import { mailboxTypes } from "../mailbox-types.js";
3
4
  import { appPermissions, MICROSOFT_TENANTS, ownerOf, roleResolver } from "../tools/applications.js";
4
5
  import { collectAll, mapLimit, tenantHas } from "../tools/common.js";
5
6
  import { isMfaMethod, principalType, roleAssignments, roleNames, userMethods } from "../tools/security.js";
@@ -47,7 +48,7 @@ export async function collectSnapshot(ctx, opts = {}) {
47
48
  });
48
49
  const users = (rawUsers?.items ?? []).map((u) => {
49
50
  const a = u.signInActivity ?? {};
50
- const last = [a.lastSignInDateTime, a.lastNonInteractiveSignInDateTime].filter(Boolean).sort().pop() ?? null;
51
+ const last = [a.lastSignInDateTime, a.lastNonInteractiveSignInDateTime, a.lastSuccessfulSignInDateTime].filter(Boolean).sort().pop() ?? null;
51
52
  return {
52
53
  id: u.id,
53
54
  upn: u.userPrincipalName,
@@ -171,20 +172,37 @@ export async function collectSnapshot(ctx, opts = {}) {
171
172
  a.delegatedGrants.sort();
172
173
  return { list: [...apps.values()], truncated, note };
173
174
  }))?.list ?? [];
174
- // storage and mailbox types from the usage reports
175
+ // storage from the usage reports; mailbox types from Exchange or mailboxSettings (not in the Graph CSV)
175
176
  let concealed = false;
177
+ const mailboxUpns = [];
176
178
  await section(sections, "mailboxes", async () => {
177
179
  const r = await fetchUsageReport(ctx.graph, "mailbox", "D7");
178
180
  concealed ||= r.concealed;
179
181
  for (const row of r.rows) {
180
182
  const u = row.upn ? byUpn.get(row.upn.toLowerCase()) : undefined;
181
183
  if (u && !row.isDeleted) {
182
- u.mailboxType = row.recipientType;
183
184
  u.mailboxBytes = row.storageUsedBytes;
185
+ if (row.recipientType)
186
+ u.mailboxType = row.recipientType;
187
+ mailboxUpns.push(u.upn);
184
188
  }
185
189
  }
186
190
  return { note: r.concealed ? "names concealed in reports" : undefined };
187
191
  });
192
+ await section(sections, "mailboxTypes", async () => {
193
+ if (!sections.mailboxes?.ok)
194
+ throw new Error("mailbox usage report not read");
195
+ if (concealed)
196
+ throw new Error("report names are concealed — mailboxes cannot be matched to accounts");
197
+ const mt = await mailboxTypes(ctx, mailboxUpns);
198
+ for (const upn of mailboxUpns) {
199
+ const u = byUpn.get(upn.toLowerCase());
200
+ const t = mt.types.get(upn.toLowerCase());
201
+ if (u && t)
202
+ u.mailboxType = t;
203
+ }
204
+ return { note: `from ${mt.source}${mt.unresolved.length ? `, ${mt.unresolved.length} of unknown type` : ""}` };
205
+ });
188
206
  await section(sections, "onedrive", async () => {
189
207
  const r = await fetchUsageReport(ctx.graph, "onedrive", "D7");
190
208
  concealed ||= r.concealed;
@@ -33,8 +33,8 @@ export function signals(s, opts) {
33
33
  .filter((u) => !u.lastSignIn || now - Date.parse(u.lastSignIn) >= opts.inactiveDays * 86_400_000)
34
34
  .filter((u) => !u.createdDateTime || now - Date.parse(u.createdDateTime) >= opts.inactiveDays * 86_400_000)
35
35
  .map((u) => `${label(u.id)} — last sign-in ${u.lastSignIn ?? "never"}${u.userType === "Guest" ? " — guest" : ""}`), s.users.every((u) => u.lastSignIn === undefined) ? `sign-in activity unavailable (${s.tenantFeatures.entraP1 === false ? "no Entra ID P1" : "section signInActivity failed"})` : undefined);
36
- add("shared_mailbox_licensed", "Shared mailboxes holding a licence", ["users", "mailboxes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.licenses.length).map((u) => `${label(u.id)} — ${u.licenses.join(", ")} (needed only above 50 GB or with an archive)`), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
37
- add("shared_mailbox_signin_enabled", "Shared mailboxes whose account can sign in", ["users", "mailboxes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.accountEnabled !== false).map((u) => label(u.id)), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
36
+ add("shared_mailbox_licensed", "Shared mailboxes holding a licence", ["users", "mailboxes", "mailboxTypes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.licenses.length).map((u) => `${label(u.id)} — ${u.licenses.join(", ")} (needed only above 50 GB or with an archive)`), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
37
+ add("shared_mailbox_signin_enabled", "Shared mailboxes whose account can sign in", ["users", "mailboxes", "mailboxTypes"], () => s.users.filter((u) => u.mailboxType === "Shared" && u.accountEnabled !== false).map((u) => label(u.id)), s.reportsConcealed ? "usage report names are concealed — mailbox types cannot be matched to accounts" : undefined);
38
38
  add("admin_without_mfa", "Administrators without MFA registered", ["roles", "mfa"], () => {
39
39
  const admins = new Map();
40
40
  for (const r of s.roles)
@@ -73,8 +73,8 @@ export function registerCapabilityTools(server, ctx) {
73
73
  const preview = s.identity === "entra" ? entra : read;
74
74
  status = preview?.ok ? (planStatus(s, preview.roles) === "granted" ? "granted" : `missing on ${s.identity === "entra" ? "entra" : "read"} identity (preview)`) : "unknown (no preview token)";
75
75
  }
76
- // granted in the token, but the tenant lacks the licence the API needs
77
- if (s.requires && status === "granted" && features[s.requires] === false)
76
+ // the tenant lacks the licence the API needs: that is the answer, whether or not the permission is in the token
77
+ if (s.requires && (status === "granted" || status === "missing") && features[s.requires] === false)
78
78
  status = `unsupported_by_tenant (needs ${s.requires})`;
79
79
  const extras = s.extras && id?.ok ? extraStatus(s, id.roles).map((e) => ({ ...e, status: e.status === "granted" && e.requires && features[e.requires] === false ? `unsupported_by_tenant (needs ${e.requires})` : e.status })) : undefined;
80
80
  return {
@@ -187,8 +187,9 @@ const FEATURE_PLANS = {
187
187
  // AAD_PREMIUM = P1, AAD_PREMIUM_P2 = P2 (P2 includes P1)
188
188
  "Entra ID P1": /^AAD_PREMIUM(_P2)?$/,
189
189
  "Entra ID P2": /^AAD_PREMIUM_P2$/,
190
- // INTUNE_A (Intune Plan 1), INTUNE_SMBIZ (Business Premium), INTUNE_EDU…
191
- Intune: /^INTUNE_/,
190
+ // INTUNE_A (Intune Plan 1), INTUNE_SMBIZ (Business Premium), INTUNE_EDU… — but NOT INTUNE_O365, the basic
191
+ // "Mobile Device Management for Office 365" of Business Basic/Standard, which has no managedDevices API
192
+ Intune: /^INTUNE_(?!O365$)/,
192
193
  };
193
194
  /** true / false from the subscribed SKUs; undefined when they cannot be read (never guessed). */
194
195
  export async function tenantHas(ctx, feature) {
@@ -1,4 +1,6 @@
1
1
  import { z } from "zod";
2
+ import { M365Error } from "../errors.js";
3
+ import { mailboxTypes } from "../mailbox-types.js";
2
4
  import { CONCEALED_WARNING, fetchUsageReport, REPORTS } from "../reports.js";
3
5
  import { cursorParam, errorResult, formatParam, jsonBlock, limitParam, listPage, odataString, or, pageFooter, renderList, searchText, sizeOf, sizeText, textResult, } from "./common.js";
4
6
  const KINDS = Object.keys(REPORTS);
@@ -33,20 +35,21 @@ function rowLine(kind, r) {
33
35
  }
34
36
  export function registerReportTools(server, ctx) {
35
37
  server.tool("m365_usage_reports", "Microsoft 365 usage reports (CSV from Graph, parsed): storage per mailbox / OneDrive / SharePoint site in bytes and GB, mailbox type (User, Shared, Room…), last activity per service. Concealed (anonymised) names are detected and flagged.", {
36
- report: z.enum(KINDS).describe("mailbox = Exchange mailboxes (storage, Recipient Type = shared/room); onedrive = OneDrive accounts; sharepoint = SharePoint sites; active_users = last activity per service and assigned products"),
38
+ report: z.enum(KINDS).describe("mailbox = Exchange mailboxes (storage; type shared/room with withMailboxType or recipientType); onedrive = OneDrive accounts; sharepoint = SharePoint sites; active_users = last activity per service and assigned products"),
37
39
  period: z.enum(["D7", "D30", "D90", "D180"]).default("D7").describe("Report period (activity window); storage is the latest value"),
38
40
  search: searchText("Case-insensitive substring of the UPN, display name or site URL").optional(),
39
- recipientType: z.enum(["User", "Shared", "Room", "Equipment", "Others"]).optional().describe("mailbox report only: only this mailbox type"),
41
+ recipientType: z.enum(["User", "Shared", "Room", "Equipment", "Others"]).optional().describe("mailbox report only: only this mailbox type (resolved through Exchange or MailboxSettings.Read — the Graph CSV has no type column)"),
42
+ withMailboxType: z.boolean().default(false).describe("mailbox report only: also show each mailbox's type (one Graph call per mailbox without the exchange feature)"),
40
43
  inactiveDays: z.number().int().min(1).max(3650).optional().describe("Only rows without activity for at least this many days (or never)"),
41
44
  sort: z.enum(["storage", "lastActivity", "name"]).default("storage").describe("storage = largest first; lastActivity = oldest first"),
42
45
  includeDeleted: z.boolean().default(false),
43
46
  limit: limitParam,
44
47
  cursor: cursorParam,
45
48
  format: formatParam,
46
- }, async ({ report, period, search, recipientType, inactiveDays, sort, includeDeleted, limit, cursor, format }) => {
49
+ }, async ({ report, period, search, recipientType, withMailboxType, inactiveDays, sort, includeDeleted, limit, cursor, format }) => {
47
50
  try {
48
51
  // the cursor is bound to the whole query: another filter cannot reuse it
49
- const tool = `m365_usage_reports:${JSON.stringify([report, period, search ?? "", recipientType ?? "", inactiveDays ?? 0, sort, includeDeleted])}`;
52
+ const tool = `m365_usage_reports:${JSON.stringify([report, period, search ?? "", recipientType ?? "", withMailboxType, inactiveDays ?? 0, sort, includeDeleted])}`;
50
53
  const offset = cursor ? ctx.cursors.get(tool, cursor).offset : 0;
51
54
  const r = await fetchUsageReport(ctx.graph, report, period);
52
55
  const now = Date.now();
@@ -54,6 +57,16 @@ export function registerReportTools(server, ctx) {
54
57
  let rows = r.rows.filter((x) => includeDeleted || !x.isDeleted);
55
58
  if (q)
56
59
  rows = rows.filter((x) => [x.upn, x.displayName, x.siteUrl].some((v) => v?.toLowerCase().includes(q)));
60
+ let typeNote = "";
61
+ if (report === "mailbox" && (recipientType || withMailboxType) && !rows.every((x) => x.recipientType)) {
62
+ // the Graph CSV has no Recipient Type column: resolve it, or fail explicitly
63
+ if (r.concealed)
64
+ throw new M365Error("unsupported_by_tenant", `unsupported_by_tenant: mailbox types cannot be matched while report names are concealed — ${CONCEALED_WARNING}`);
65
+ const mt = await mailboxTypes(ctx, rows.map((x) => x.upn ?? ""));
66
+ for (const x of rows)
67
+ x.recipientType ??= mt.types.get((x.upn ?? "").toLowerCase());
68
+ typeNote = `Mailbox types from ${mt.source}${mt.unresolved.length ? ` — ⚠ ${mt.unresolved.length} mailbox(es) of unknown type, not matched by recipientType: ${mt.unresolved.slice(0, 5).join(", ")}${mt.unresolved.length > 5 ? "…" : ""}` : ""}\n`;
69
+ }
57
70
  if (recipientType)
58
71
  rows = rows.filter((x) => (recipientType === "Others" ? !["User", "Shared", "Room", "Equipment"].includes(x.recipientType ?? "") : x.recipientType === recipientType));
59
72
  if (inactiveDays)
@@ -75,6 +88,7 @@ export function registerReportTools(server, ctx) {
75
88
  `# ${REPORTS[report].title} (${period}${r.refreshDate ? `, data of ${r.refreshDate}` : ""})`,
76
89
  "",
77
90
  r.concealed ? `${CONCEALED_WARNING}\n` : "",
91
+ typeNote,
78
92
  report === "active_users" ? `${rows.length} row(s)` : `${rows.length} row(s) — total storage of the matching rows: ${sizeText(total)}`,
79
93
  "",
80
94
  ].join("\n");
@@ -151,7 +151,7 @@ export function registerSecurityTools(server, ctx) {
151
151
  }
152
152
  });
153
153
  server.tool("m365_user_activity", "Last sign-in of each account (interactive and non-interactive) to find dormant accounts to disable. Needs Entra ID P1 (signInActivity) — otherwise unsupported_by_tenant.", {
154
- inactiveDays: z.number().int().min(1).max(3650).optional().describe("Only accounts whose last sign-in is older than N days (accounts that never signed in are listed only without this filter)"),
154
+ inactiveDays: z.number().int().min(1).max(3650).optional().describe("Only accounts whose latest sign-in — interactive, non-interactive or successful — is older than N days (accounts that never signed in interactively are listed only without this filter)"),
155
155
  accountEnabled: z.boolean().optional().describe("Applied to the returned page (signInActivity filters cannot be combined server-side)"),
156
156
  userType: z.enum(["Member", "Guest"]).optional().describe("Applied to the returned page"),
157
157
  limit: limitParam,
@@ -173,12 +173,20 @@ export function registerSecurityTools(server, ctx) {
173
173
  catch (err) {
174
174
  throw await premiumError(ctx, err, "Entra ID P1", "signInActivity");
175
175
  }
176
- const shown = page.items.filter((u) => (accountEnabled === undefined || u.accountEnabled === accountEnabled) && (!userType || u.userType === userType));
176
+ // latest of interactive, non-interactive and last successful sign-in. Graph filters on the interactive
177
+ // date only: an account signing in non-interactively (Outlook, Teams tokens…) is active and is removed here
177
178
  const last = (u) => {
178
179
  const a = u.signInActivity ?? {};
179
- return [a.lastSignInDateTime, a.lastNonInteractiveSignInDateTime].filter(Boolean).sort().pop();
180
+ return [a.lastSignInDateTime, a.lastNonInteractiveSignInDateTime, a.lastSuccessfulSignInDateTime].filter(Boolean).sort().pop();
180
181
  };
181
- const local = shown.length !== page.items.length ? `\n\n_${page.items.length - shown.length} account(s) of this page hidden by accountEnabled/userType._` : "";
182
+ const activeRecently = (u) => Boolean(before && last(u) && last(u) > before);
183
+ const shown = page.items.filter((u) => !activeRecently(u) && (accountEnabled === undefined || u.accountEnabled === accountEnabled) && (!userType || u.userType === userType));
184
+ const hiddenActive = page.items.filter(activeRecently).length;
185
+ const hiddenOther = page.items.length - shown.length - hiddenActive;
186
+ const local = [
187
+ hiddenActive ? `${hiddenActive} account(s) of this page hidden: no interactive sign-in for ${inactiveDays} days, but a more recent non-interactive sign-in (still in use).` : "",
188
+ hiddenOther ? `${hiddenOther} account(s) of this page hidden by accountEnabled/userType.` : "",
189
+ ].filter(Boolean).map((l) => `\n\n_${l}_`).join("");
182
190
  return textResult(renderList(`Account activity${inactiveDays ? ` (inactive ≥ ${inactiveDays} days)` : ""}`, { ...page, items: shown }, format, (u) => {
183
191
  const l = last(u);
184
192
  const d = daysSince(l);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aidalinfo/m365-mcp",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
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. 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",