@aidalinfo/m365-mcp 0.5.0 → 0.6.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.
@@ -1,15 +1,58 @@
1
1
  import { z } from "zod";
2
2
  import { M365Error } from "../errors.js";
3
- import { asList, fullAccess, sendAs } from "../external/exchange.js";
3
+ import { MAILBOX_LIMITS, MAILBOX_RIGHTS, readMailboxAccess } from "../external/exchange.js";
4
4
  import { CATEGORIES, CONTENT_TYPES } from "../external/activity.js";
5
5
  import { isEveryone, isExternalLogin, principalKind, sitePath } from "../external/sharepoint.js";
6
6
  import { cursorParam, errorResult, formatParam, jsonBlock, limitParam, mapLimit, or, pageFooter, searchText, textResult } from "./common.js";
7
7
  const mailboxParam = z.string().min(3).max(256).describe("Mailbox e-mail address / UPN (or object id)");
8
+ /** Mailboxes Get-Mailbox lists in one call (Exchange's ResultSize): reaching it is reported as a possible cut. */
9
+ const MAILBOX_LIST_SIZE = 1000;
10
+ const RIGHT_LABEL = { FullAccess: "Full Access", SendAs: "Send As", SendOnBehalf: "Send on behalf" };
11
+ const rightText = (r) => (r.evaluated ? `${r.trustees.join(", ") || "none (no explicit grant)"}${r.truncated ? " ⚠ truncated" : ""}` : `⚠ NOT EVALUATED — ${r.reason}`);
12
+ /** "Not shown: Full Access 1 inherited, 1 system" — the entries the explicit-grant view leaves out. */
13
+ function notShown(a) {
14
+ const parts = MAILBOX_RIGHTS.flatMap((k) => {
15
+ const r = a.rights[k];
16
+ if (!r.evaluated || !r.hidden)
17
+ return [];
18
+ const h = r.hidden;
19
+ const bits = [h.inherited ? `${h.inherited} inherited` : "", h.deny ? `${h.deny} deny` : "", h.system ? `${h.system} system` : ""].filter(Boolean);
20
+ return bits.length ? [`${RIGHT_LABEL[k]} ${bits.join(", ")}`] : [];
21
+ });
22
+ return parts.length ? `\n- Not shown: ${parts.join("; ")}` : "";
23
+ }
24
+ /** JSON row: a right not evaluated is null (unknown), never [] (no explicit grant). */
25
+ function jsonRow(a) {
26
+ const field = { FullAccess: "fullAccess", SendAs: "sendAs", SendOnBehalf: "sendOnBehalf" };
27
+ const out = { mailbox: a.mailbox, displayName: a.displayName, type: a.type };
28
+ const notEvaluated = {};
29
+ const hidden = {};
30
+ const truncated = [];
31
+ for (const k of MAILBOX_RIGHTS) {
32
+ const r = a.rights[k];
33
+ out[field[k]] = r.evaluated ? r.trustees : null;
34
+ if (!r.evaluated)
35
+ notEvaluated[field[k]] = r.reason;
36
+ else {
37
+ if (r.hidden && (r.hidden.inherited || r.hidden.deny || r.hidden.system))
38
+ hidden[field[k]] = r.hidden;
39
+ if (r.truncated)
40
+ truncated.push(field[k]);
41
+ }
42
+ }
43
+ if (Object.keys(notEvaluated).length)
44
+ out.notEvaluated = notEvaluated;
45
+ if (Object.keys(hidden).length)
46
+ out.notShown = hidden;
47
+ if (truncated.length)
48
+ out.truncated = truncated;
49
+ return out;
50
+ }
8
51
  /** Phase 2 tools: registered only for the audit-identity features enabled in M365_AUDIT_APP_FEATURES. */
9
52
  export function registerPhase2Tools(server, ctx) {
10
53
  const { exchange, activity, sharepoint } = ctx.ext;
11
54
  if (exchange) {
12
- server.tool("m365_mailbox_permissions", "Who can use a mailbox: Full Access, Send As and Send on behalf (explicit grants only; system and inherited entries hidden). Without `mailbox`, every shared mailbox (paginated). Exchange Online, read-only role.", {
55
+ server.tool("m365_mailbox_permissions", "Who can use a mailbox: Full Access, Send As and Send on behalf — explicit grants only (inherited, deny and system entries are counted, not listed; group trustees are not expanded; effective rights are not evaluated). Without `mailbox`, every shared mailbox (paginated). A right Exchange refused to read (RBAC) is marked NOT EVALUATED, never 'none'. Exchange Online, read-only role, Get-* cmdlets only.", {
13
56
  mailbox: mailboxParam.optional(),
14
57
  type: z.enum(["SharedMailbox", "RoomMailbox", "EquipmentMailbox", "UserMailbox"]).default("SharedMailbox").describe("Without mailbox: which mailboxes to review"),
15
58
  limit: z.number().int().min(1).max(50).default(10).describe("Mailboxes per page (each costs 3 Exchange calls; max 50)"),
@@ -21,7 +64,7 @@ export function registerPhase2Tools(server, ctx) {
21
64
  let mailboxes;
22
65
  let offset = 0;
23
66
  let total;
24
- let truncated = false;
67
+ let cut;
25
68
  if (mailbox) {
26
69
  mailboxes = (await exchange.invoke("Get-Mailbox", { Identity: mailbox })).items;
27
70
  if (!mailboxes.length)
@@ -29,32 +72,44 @@ export function registerPhase2Tools(server, ctx) {
29
72
  }
30
73
  else {
31
74
  offset = cursor ? ctx.cursors.get(tool, cursor).offset : 0;
32
- const all = await exchange.invoke("Get-Mailbox", { RecipientTypeDetails: type, ResultSize: 1000 });
33
- truncated = all.truncated;
75
+ const all = await exchange.invoke("Get-Mailbox", { RecipientTypeDetails: type, ResultSize: MAILBOX_LIST_SIZE });
76
+ if (all.truncated) {
77
+ cut =
78
+ all.truncatedBy === "resultSize"
79
+ ? `⚠ Mailbox list truncated: Exchange returned ${all.items.length} mailboxes, the connector's limit (ResultSize ${MAILBOX_LIST_SIZE}) — any mailbox beyond it is NOT reviewed (unknown, not "no grant").`
80
+ : `⚠ Mailbox list truncated after the server's page budget (${all.items.length} mailboxes read) — any mailbox beyond it is NOT reviewed.`;
81
+ }
34
82
  const sorted = all.items.sort((a, b) => String(a.PrimarySmtpAddress).localeCompare(String(b.PrimarySmtpAddress)));
35
83
  total = sorted.length;
36
84
  mailboxes = sorted.slice(offset, offset + limit);
37
85
  }
38
- const rows = await mapLimit(mailboxes, 3, async (m) => {
39
- const id = m.PrimarySmtpAddress ?? m.UserPrincipalName ?? m.ExternalDirectoryObjectId;
40
- // query by object id when known: Exchange's own addresses may hold characters our input check refuses
41
- const key = m.ExternalDirectoryObjectId || id;
42
- const [fa, sa] = await Promise.all([exchange.invoke("Get-MailboxPermission", { Identity: key }), exchange.invoke("Get-RecipientPermission", { Identity: key, AccessRights: "SendAs" })]);
43
- return { mailbox: id, displayName: m.DisplayName, type: m.RecipientTypeDetails, fullAccess: fullAccess(fa.items), sendAs: sendAs(sa.items), sendOnBehalf: asList(m.GrantSendOnBehalfTo) };
44
- });
86
+ const rows = await mapLimit(mailboxes, 3, (m) => readMailboxAccess(exchange, m));
45
87
  const page = {
46
88
  items: rows,
47
89
  count: total,
48
90
  nextCursor: !mailbox && total !== undefined && offset + limit < total ? ctx.cursors.put(tool, "exchange:mailboxes", offset + limit) : undefined,
49
91
  };
50
92
  if (!rows.length)
51
- return textResult(`# Mailbox permissions (${type})\n\nNo ${type} in the organization (the request succeeded).`);
93
+ return textResult(`# Mailbox permissions (${type})\n\nNo ${type} in the organization (the request succeeded).${cut ? `\n\n${cut}` : ""}`);
94
+ const missing = MAILBOX_RIGHTS.flatMap((k) => {
95
+ const failed = rows.filter((r) => !r.rights[k].evaluated);
96
+ const first = failed[0]?.rights[k];
97
+ return failed.length && first && !first.evaluated ? [`${RIGHT_LABEL[k]} NOT evaluated on ${failed.length} of ${rows.length} mailbox(es) — ${first.reason}`] : [];
98
+ });
99
+ const nothing = rows.every((r) => MAILBOX_RIGHTS.every((k) => !r.rights[k].evaluated));
100
+ const cutRights = rows.filter((r) => MAILBOX_RIGHTS.some((k) => { const x = r.rights[k]; return x.evaluated && x.truncated; })).map((r) => r.mailbox);
101
+ const warnings = [
102
+ missing.length ? `⚠ INCOMPLETE — ${missing.join("\n⚠ INCOMPLETE — ")}` : "",
103
+ cutRights.length ? `⚠ Permission list truncated (server page budget) on: ${cutRights.join(", ")}` : "",
104
+ cut ?? "",
105
+ ].filter(Boolean);
52
106
  const body = format === "json"
53
- ? jsonBlock(rows)
107
+ ? jsonBlock(rows.map(jsonRow))
54
108
  : rows
55
- .map((r) => `## ${or(r.displayName)} <${r.mailbox}> — ${or(r.type)}\n- Full Access: ${r.fullAccess.join(", ") || "nobody"}\n- Send As: ${r.sendAs.join(", ") || "nobody"}\n- Send on behalf: ${r.sendOnBehalf.join(", ") || "nobody"}`)
109
+ .map((r) => `## ${or(r.displayName)} <${r.mailbox}> — ${or(r.type)}\n${MAILBOX_RIGHTS.map((k) => `- ${RIGHT_LABEL[k]}: ${rightText(r.rights[k])}`).join("\n")}${notShown(r)}`)
56
110
  .join("\n\n");
57
- return textResult(`# Mailbox permissions${mailbox ? "" : ` — ${type}`}${truncated ? " ⚠ list truncated" : ""}\n\n${body}${mailbox ? "" : pageFooter(page, rows.length)}`);
111
+ const text = `# Mailbox permissions${mailbox ? ` — ${mailbox}` : ` — ${type}`}\n\n${warnings.length ? `${warnings.join("\n")}\n\n` : ""}${body}\n\n_${MAILBOX_LIMITS}_${mailbox ? "" : pageFooter(page, rows.length)}`;
112
+ return { ...textResult(text), ...(nothing ? { isError: true } : {}) };
58
113
  }
59
114
  catch (err) {
60
115
  return errorResult(err);
@@ -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.6.0",
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",