@aidalinfo/m365-mcp 0.1.0 → 0.3.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.
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Access-review snapshot of a tenant, its comparison with a previous one, and the signals a
3
+ * reviewer must look at. Pure functions: collection lives in collect.ts.
4
+ */
5
+ export const SNAPSHOT_SCHEMA = "m365-access-review/1";
6
+ const SERVICE_MAILBOXES = ["Shared", "Room", "Equipment"];
7
+ export function signals(s, opts) {
8
+ const now = opts.now ?? Date.parse(s.generatedAt);
9
+ const users = new Map(s.users.map((u) => [u.id, u]));
10
+ const label = (id) => {
11
+ const u = users.get(id);
12
+ return u ? `${u.displayName ?? "?"} <${u.upn ?? id}>` : id;
13
+ };
14
+ const ok = (...sections) => sections.filter((n) => !s.sections[n]?.ok);
15
+ const out = [];
16
+ const add = (code, title, deps, compute, extra) => {
17
+ const failed = ok(...deps);
18
+ out.push(failed.length ? { code, title, items: [], notEvaluated: `section(s) ${failed.join(", ")} failed` } : extra ? { code, title, items: [], notEvaluated: extra } : { code, title, items: compute() });
19
+ };
20
+ add("group_without_owner", "Microsoft 365 groups / teams without owner", ["groups"], () => s.groups.filter((g) => g.kind === "microsoft365" && g.owners.length === 0).map((g) => `${g.displayName} (${g.id})${g.isTeam ? " — team" : ""}`));
21
+ add("guest_owner", "Guests owning a group or team", ["users", "groups"], () => s.groups.flatMap((g) => g.owners.filter((o) => users.get(o)?.userType === "Guest").map((o) => `${label(o)} owns ${g.displayName} (${g.id})`)));
22
+ add("disabled_still_member", "Disabled accounts still member or owner of groups", ["users", "groups"], () => {
23
+ const where = new Map();
24
+ for (const g of s.groups)
25
+ for (const m of new Set([...g.members, ...g.owners]))
26
+ if (users.get(m)?.accountEnabled === false)
27
+ where.set(m, [...(where.get(m) ?? []), g.displayName ?? g.id]);
28
+ return [...where].map(([id, gs]) => `${label(id)} — in ${gs.length} group(s): ${gs.slice(0, 5).join(", ")}${gs.length > 5 ? "…" : ""}`);
29
+ });
30
+ add("disabled_licensed", "Disabled accounts still holding a licence", ["users"], () => s.users.filter((u) => u.accountEnabled === false && u.licenses.length && !SERVICE_MAILBOXES.includes(u.mailboxType ?? "")).map((u) => `${label(u.id)} — ${u.licenses.join(", ")}`));
31
+ add("inactive_accounts", `Enabled accounts without sign-in for ${opts.inactiveDays}+ days`, ["users"], () => s.users
32
+ .filter((u) => u.accountEnabled !== false && !SERVICE_MAILBOXES.includes(u.mailboxType ?? "") && u.lastSignIn !== undefined)
33
+ .filter((u) => !u.lastSignIn || now - Date.parse(u.lastSignIn) >= opts.inactiveDays * 86_400_000)
34
+ .filter((u) => !u.createdDateTime || now - Date.parse(u.createdDateTime) >= opts.inactiveDays * 86_400_000)
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);
38
+ add("admin_without_mfa", "Administrators without MFA registered", ["roles", "mfa"], () => {
39
+ const admins = new Map();
40
+ for (const r of s.roles)
41
+ if (r.principalType === "user")
42
+ admins.set(r.principalId, [...(admins.get(r.principalId) ?? []), r.role]);
43
+ return [...admins].filter(([id]) => users.get(id)?.mfaRegistered === false).map(([id, roles]) => `${label(id)} — ${roles.join(", ")}`);
44
+ });
45
+ add("guest_admin", "Guests holding an admin role", ["users", "roles"], () => s.roles.filter((r) => users.get(r.principalId)?.userType === "Guest").map((r) => `${label(r.principalId)} — ${r.role}`));
46
+ if (s.mailboxAccess) {
47
+ add("shared_mailbox_disabled_delegate", "Disabled accounts still holding rights on a shared mailbox", ["users", "mailboxAccess"], () => {
48
+ const byUpn = new Map(s.users.filter((u) => u.upn).map((u) => [u.upn.toLowerCase(), u]));
49
+ return s.mailboxAccess.flatMap((m) => m.grants.filter((g) => byUpn.get(g.split(": ")[1]?.toLowerCase() ?? "")?.accountEnabled === false).map((g) => `${m.mailbox} — ${g}`));
50
+ });
51
+ }
52
+ return out;
53
+ }
54
+ const setDiff = (a, b) => {
55
+ const sb = new Set(b);
56
+ return a.filter((x) => !sb.has(x));
57
+ };
58
+ export function diff(prev, cur) {
59
+ const users = new Map([...prev.users, ...cur.users].map((u) => [u.id, u]));
60
+ const label = (id) => {
61
+ const u = users.get(id);
62
+ return u ? `${u.displayName ?? "?"} <${u.upn ?? id}>` : id;
63
+ };
64
+ const pu = new Map(prev.users.map((u) => [u.id, u]));
65
+ const cu = new Map(cur.users.map((u) => [u.id, u]));
66
+ const out = [];
67
+ const push = (code, title, items) => out.push({ code, title, items });
68
+ push("users_created", "Accounts created", cur.users.filter((u) => !pu.has(u.id)).map((u) => `${label(u.id)}${u.userType === "Guest" ? " — GUEST" : ""}`));
69
+ push("users_deleted", "Accounts deleted", prev.users.filter((u) => !cu.has(u.id)).map((u) => label(u.id)));
70
+ push("guests_new", "New guests", cur.users.filter((u) => !pu.has(u.id) && u.userType === "Guest").map((u) => label(u.id)));
71
+ push("users_disabled", "Accounts disabled", cur.users.filter((u) => pu.get(u.id)?.accountEnabled === true && u.accountEnabled === false).map((u) => label(u.id)));
72
+ push("users_enabled", "Accounts re-enabled", cur.users.filter((u) => pu.get(u.id)?.accountEnabled === false && u.accountEnabled === true).map((u) => label(u.id)));
73
+ push("licenses_changed", "Licences assigned / removed", cur.users.flatMap((u) => {
74
+ const p = pu.get(u.id);
75
+ if (!p)
76
+ return [];
77
+ const added = setDiff(u.licenses, p.licenses);
78
+ const removed = setDiff(p.licenses, u.licenses);
79
+ return added.length || removed.length ? [`${label(u.id)}${added.length ? ` +${added.join(", +")}` : ""}${removed.length ? ` -${removed.join(", -")}` : ""}`] : [];
80
+ }));
81
+ const pg = new Map(prev.groups.map((g) => [g.id, g]));
82
+ const cg = new Map(cur.groups.map((g) => [g.id, g]));
83
+ push("groups_created", "Groups / teams created", cur.groups.filter((g) => !pg.has(g.id)).map((g) => `${g.displayName} (${g.kind}${g.isTeam ? ", team" : ""})`));
84
+ push("groups_deleted", "Groups / teams deleted", prev.groups.filter((g) => !cg.has(g.id)).map((g) => `${g.displayName} (${g.kind}${g.isTeam ? ", team" : ""})`));
85
+ const joined = [];
86
+ const left = [];
87
+ const ownersNew = [];
88
+ const ownersGone = [];
89
+ for (const g of cur.groups) {
90
+ const p = pg.get(g.id);
91
+ if (!p)
92
+ continue;
93
+ const name = `${g.displayName}${g.isTeam ? " (team)" : ""}`;
94
+ for (const m of setDiff(g.members, p.members))
95
+ joined.push(`${label(m)} → ${name}`);
96
+ for (const m of setDiff(p.members, g.members))
97
+ left.push(`${label(m)} ← ${name}`);
98
+ for (const o of setDiff(g.owners, p.owners))
99
+ ownersNew.push(`${label(o)} owns ${name}`);
100
+ for (const o of setDiff(p.owners, g.owners))
101
+ ownersGone.push(`${label(o)} no longer owns ${name}`);
102
+ }
103
+ const pc = new Map(prev.channels.map((c) => [c.channelId, c]));
104
+ for (const c of cur.channels) {
105
+ const p = pc.get(c.channelId);
106
+ const name = `${c.teamName ?? c.teamId} › ${c.displayName} (${c.membershipType} channel)`;
107
+ for (const m of setDiff(c.members, p?.members ?? []))
108
+ joined.push(`${label(m)} → ${name}`);
109
+ if (p)
110
+ for (const m of setDiff(p.members, c.members))
111
+ left.push(`${label(m)} ← ${name}`);
112
+ for (const o of setDiff(c.owners, p?.owners ?? []))
113
+ ownersNew.push(`${label(o)} owns ${name}`);
114
+ }
115
+ push("members_joined", "Entries in groups, teams and private/shared channels", joined);
116
+ push("members_left", "Exits from groups, teams and private/shared channels", left);
117
+ push("owners_new", "New owners", ownersNew);
118
+ push("owners_removed", "Owners removed", ownersGone);
119
+ const roleKey = (r) => `${r.roleId}|${r.principalId}|${r.scope}`;
120
+ const pr = new Set(prev.roles.map(roleKey));
121
+ const cr = new Set(cur.roles.map(roleKey));
122
+ push("admins_new", "New admin role assignments", cur.roles.filter((r) => !pr.has(roleKey(r))).map((r) => `${r.principalName ?? label(r.principalId)} — ${r.role}`));
123
+ push("admins_removed", "Admin role assignments removed", prev.roles.filter((r) => !cr.has(roleKey(r))).map((r) => `${r.principalName ?? label(r.principalId)} — ${r.role}`));
124
+ const pa = new Map(prev.applications.map((a) => [a.id, a]));
125
+ push("apps_new", "New applications", cur.applications.filter((a) => !pa.has(a.id) && (a.appPermissions.length || a.delegatedGrants.length || a.owner === "third party")).map((a) => `${a.displayName} (${a.owner})`));
126
+ push("app_consents_new", "New permissions consented to applications", cur.applications.flatMap((a) => {
127
+ const p = pa.get(a.id);
128
+ return [...setDiff(a.appPermissions, p?.appPermissions ?? []).map((x) => `${a.displayName}: application ${x}`), ...setDiff(a.delegatedGrants, p?.delegatedGrants ?? []).map((x) => `${a.displayName}: delegated ${x}`)];
129
+ }));
130
+ if (prev.mailboxAccess && cur.mailboxAccess) {
131
+ const key = (m) => m.grants.map((g) => `${m.mailbox} — ${g}`);
132
+ const before = prev.mailboxAccess.flatMap(key);
133
+ const after = cur.mailboxAccess.flatMap(key);
134
+ push("mailbox_access_new", "Shared-mailbox rights granted", setDiff(after, before));
135
+ push("mailbox_access_removed", "Shared-mailbox rights removed", setDiff(before, after));
136
+ }
137
+ return out;
138
+ }
139
+ /** Bounded text of a list of signals or diff entries. */
140
+ export function renderEntries(entries, max) {
141
+ return entries
142
+ .map((e) => {
143
+ const ne = e.notEvaluated;
144
+ if (ne)
145
+ return `- **${e.title}**: not evaluated — ${ne}`;
146
+ if (!e.items.length)
147
+ return `- ${e.title}: none`;
148
+ const shown = e.items.slice(0, max).map((i) => ` - ${i}`);
149
+ return `- **${e.title}: ${e.items.length}**\n${shown.join("\n")}${e.items.length > max ? `\n - … ${e.items.length - max} more in the snapshot file` : ""}`;
150
+ })
151
+ .join("\n");
152
+ }
@@ -0,0 +1,98 @@
1
+ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { z } from "zod";
4
+ import { M365Error } from "../errors.js";
5
+ import { collectSnapshot } from "../review/collect.js";
6
+ import { diff, renderEntries, signals, SNAPSHOT_SCHEMA } from "../review/model.js";
7
+ import { errorResult, jsonBlock, sizeText, textResult } from "./common.js";
8
+ const FILE_RE = /^m365-review-[0-9a-f-]{36}-[0-9TZ-]+\.json$/;
9
+ export const snapshotFileName = (s) => `m365-review-${s.tenantId}-${s.generatedAt.replace(/[:.]/g, "-")}.json`;
10
+ /** A previous snapshot of THIS tenant from M365_SNAPSHOT_DIR: by file name, or the most recent one. */
11
+ async function loadPrevious(dir, tenantId, which) {
12
+ let file;
13
+ if (which === "latest") {
14
+ const files = (await readdir(dir).catch(() => [])).filter((f) => FILE_RE.test(f) && f.startsWith(`m365-review-${tenantId}-`)).sort();
15
+ if (!files.length)
16
+ throw new M365Error("not_found", `not_found: no previous snapshot of this tenant in M365_SNAPSHOT_DIR — run once without compareWith first`);
17
+ file = files[files.length - 1];
18
+ }
19
+ else {
20
+ if (!FILE_RE.test(which))
21
+ throw new M365Error("invalid_request", "invalid_request: compareWith must be \"latest\" or a snapshot file name (m365-review-<tenant>-<date>.json), without any directory");
22
+ file = which;
23
+ }
24
+ let snapshot;
25
+ try {
26
+ snapshot = JSON.parse(await readFile(join(dir, file), "utf-8"));
27
+ }
28
+ catch (err) {
29
+ throw new M365Error("not_found", `not_found: cannot read snapshot ${file} (${err.code ?? "invalid JSON"})`);
30
+ }
31
+ if (snapshot?.schema !== SNAPSHOT_SCHEMA)
32
+ throw new M365Error("invalid_request", `invalid_request: ${file} is not a ${SNAPSHOT_SCHEMA} snapshot`);
33
+ if (snapshot.tenantId !== tenantId)
34
+ throw new M365Error("invalid_request", `invalid_request: ${file} belongs to another tenant`);
35
+ return { file, snapshot };
36
+ }
37
+ export function registerAccessReviewTools(server, ctx, serverVersion) {
38
+ server.tool("m365_access_review_snapshot", "Access review in one call: snapshot of the tenant (users, licences, last sign-in if P1, groups and teams with owners and members, private/shared channel members, admin roles, MFA, applications and consents, storage per account and site), the signals to review (group without owner, guest owner, disabled account still member or licensed, inactive accounts, shared mailbox licensed or able to sign in, admin without MFA) and, with compareWith, what changed since a previous snapshot. Writes a dated JSON file in M365_SNAPSHOT_DIR; returns a bounded summary. Long-running (hundreds of Graph calls).", {
39
+ compareWith: z
40
+ .string()
41
+ .max(200)
42
+ .optional()
43
+ .describe('"latest" = the most recent previous snapshot of this tenant in M365_SNAPSHOT_DIR, or a file name from a previous run'),
44
+ inactiveDays: z.number().int().min(7).max(3650).default(90).describe("Threshold of the inactive-accounts signal (default 90)"),
45
+ maxItems: z.number().int().min(1).max(100).default(20).describe("Items shown per signal / change in the response (the file holds everything)"),
46
+ }, async ({ compareWith, inactiveDays, maxItems }) => {
47
+ try {
48
+ const dir = ctx.config.snapshotDir;
49
+ if (compareWith && !dir)
50
+ throw new M365Error("invalid_request", "invalid_request: compareWith needs M365_SNAPSHOT_DIR (where previous snapshots are stored)");
51
+ const previous = compareWith && dir ? await loadPrevious(dir, ctx.config.tenantId, compareWith) : undefined;
52
+ const snap = await collectSnapshot(ctx, { serverVersion });
53
+ const sig = signals(snap, { inactiveDays });
54
+ const changes = previous ? diff(previous.snapshot, snap) : undefined;
55
+ let saved = "not saved — set M365_SNAPSHOT_DIR to keep snapshots and compare reviews";
56
+ if (dir) {
57
+ await mkdir(dir, { recursive: true, mode: 0o700 });
58
+ const file = snapshotFileName(snap);
59
+ // the file holds personal data (names, UPNs, memberships): owner-only
60
+ await writeFile(join(dir, file), JSON.stringify({ ...snap, review: { inactiveDays, comparedWith: previous?.file, signals: sig, changes } }, null, 2), { mode: 0o600, flag: "wx" });
61
+ saved = `${join(dir, file)} (compare later with compareWith: "${file}" or "latest")`;
62
+ }
63
+ const failed = Object.entries(snap.sections).filter(([, s]) => !s.ok);
64
+ const truncated = Object.entries(snap.sections).filter(([, s]) => s.truncated).map(([n]) => n);
65
+ const storage = snap.users.reduce((n, u) => n + (u.mailboxBytes ?? 0) + (u.oneDriveBytes ?? 0), 0) + snap.sites.reduce((n, s) => n + (s.storageBytes ?? 0), 0);
66
+ const features = snap.tenantFeatures;
67
+ const yn = (v) => (v === undefined ? "unknown" : v ? "yes" : "no");
68
+ const lines = [
69
+ `# Access review — tenant ${snap.tenantId} — ${snap.generatedAt}`,
70
+ "",
71
+ `Entra ID P1: ${yn(features.entraP1)} — P2: ${yn(features.entraP2)} — Intune: ${yn(features.intune)}`,
72
+ `Snapshot: ${saved}`,
73
+ "",
74
+ `## Inventory`,
75
+ `- Users: ${snap.users.length} (${snap.users.filter((u) => u.userType === "Guest").length} guests, ${snap.users.filter((u) => u.accountEnabled === false).length} disabled, ${snap.users.filter((u) => u.licenses.length).length} licensed)`,
76
+ `- Licences: ${snap.skus.map((s) => `${s.skuPartNumber} ${s.consumed}/${s.purchased}`).join(", ") || "none"}`,
77
+ `- Groups: ${snap.groups.length} (${snap.groups.filter((g) => g.kind === "microsoft365").length} Microsoft 365, ${snap.groups.filter((g) => g.isTeam).length} teams) — private/shared channels: ${snap.channels.length}`,
78
+ `- Admin role assignments: ${snap.roles.length} (${new Set(snap.roles.map((r) => r.principalId)).size} principals)`,
79
+ `- Applications reviewed: ${snap.applications.length}`,
80
+ snap.mailboxAccess ? `- Shared mailboxes reviewed: ${snap.mailboxAccess.length} (${snap.mailboxAccess.reduce((n, m) => n + m.grants.length, 0)} delegated rights)` : "",
81
+ `- Storage (mailboxes + OneDrive + sites): ${sizeText(storage)}${snap.reportsConcealed ? " — ⚠ report names concealed: storage and mailbox types are not matched to accounts" : ""}`,
82
+ failed.length ? `\n⚠ Sections NOT read (their signals are not evaluated):\n${failed.map(([n, s]) => `- ${n}: ${s.error}`).join("\n")}` : "",
83
+ truncated.length ? `\n⚠ Truncated sections (caps reached): ${truncated.join(", ")}` : "",
84
+ Object.entries(snap.sections).filter(([, s]) => s.note).map(([n, s]) => `- note ${n}: ${s.note}`).join("\n"),
85
+ "",
86
+ `## Signals to review`,
87
+ renderEntries(sig, maxItems),
88
+ changes ? `\n## Changes since ${previous.snapshot.generatedAt} (${previous.file})\n${renderEntries(changes, maxItems)}` : "\n_No comparison (pass compareWith: \"latest\" on the next review)._",
89
+ "",
90
+ jsonBlock({ signals: Object.fromEntries(sig.map((s) => [s.code, s.notEvaluated ? "not evaluated" : s.items.length])), ...(changes ? { changes: Object.fromEntries(changes.map((c) => [c.code, c.items.length])) } : {}) }),
91
+ ].filter((l) => l !== "");
92
+ return textResult(lines.join("\n"));
93
+ }
94
+ catch (err) {
95
+ return errorResult(err);
96
+ }
97
+ });
98
+ }
@@ -0,0 +1,101 @@
1
+ import { z } from "zod";
2
+ import { GUID_RE } from "../config.js";
3
+ import { M365Error } from "../errors.js";
4
+ import { collectAll, cursorParam, errorResult, formatParam, limitParam, listPage, odataString, or, renderList, searchText, textResult, } from "./common.js";
5
+ /** Tenants Microsoft publishes its first-party applications from. */
6
+ export const MICROSOFT_TENANTS = ["f8cdef31-a31e-4b4a-93e4-5f571e91255a", "72f988bf-86f1-41af-91ab-2d7cd011db47"];
7
+ const ADVANCED = { ConsistencyLevel: "eventual" };
8
+ const SP_FIELDS = "id,appId,displayName,servicePrincipalType,accountEnabled,appOwnerOrganizationId,publisherName,verifiedPublisher,tags,appRoleAssignmentRequired";
9
+ export const ownerOf = (sp, tenantId) => !sp.appOwnerOrganizationId ? "unknown" : sp.appOwnerOrganizationId.toLowerCase() === tenantId ? "this tenant" : MICROSOFT_TENANTS.includes(sp.appOwnerOrganizationId.toLowerCase()) ? "Microsoft" : "third party";
10
+ async function resolveServicePrincipal(ctx, input) {
11
+ if (GUID_RE.test(input)) {
12
+ try {
13
+ return (await ctx.graph.get(`/servicePrincipals/${input}`, { query: { $select: SP_FIELDS } })).data;
14
+ }
15
+ catch (err) {
16
+ if (!(err instanceof M365Error) || err.code !== "not_found")
17
+ throw err;
18
+ }
19
+ }
20
+ const filter = GUID_RE.test(input) ? `appId eq ${odataString(input)}` : `displayName eq ${odataString(input)}`;
21
+ const found = (await ctx.graph.get("/servicePrincipals", { query: { $filter: filter, $select: SP_FIELDS, $top: 5 } })).data?.value ?? [];
22
+ if (!found.length)
23
+ throw new M365Error("not_found", `not_found: no service principal matches "${input}"`);
24
+ if (found.length > 1)
25
+ throw new M365Error("ambiguous_target", `ambiguous_target: ${found.length} service principals match "${input}" — pass the object id: ${found.map((s) => `${s.displayName} (${s.id})`).join("; ")}`);
26
+ return found[0];
27
+ }
28
+ /** Application permission names of a resource (e.g. Microsoft Graph's appRoles), cached per call. */
29
+ export function roleResolver(ctx) {
30
+ const cache = new Map();
31
+ const sp = (id) => {
32
+ if (!cache.has(id))
33
+ cache.set(id, ctx.graph.get(`/servicePrincipals/${id}`, { query: { $select: "id,displayName,appRoles" } }).then((r) => r.data, () => undefined));
34
+ return cache.get(id);
35
+ };
36
+ return {
37
+ name: async (id) => (await sp(id))?.displayName ?? id,
38
+ role: async (resourceId, appRoleId) => (await sp(resourceId))?.appRoles?.find((r) => r.id === appRoleId)?.value ?? (appRoleId === "00000000-0000-0000-0000-000000000000" ? "default access" : appRoleId),
39
+ };
40
+ }
41
+ /** Application permissions granted to a service principal, with their names. */
42
+ export async function appPermissions(ctx, spId, resolver = roleResolver(ctx)) {
43
+ const { items, truncated } = await collectAll(ctx, `/servicePrincipals/${spId}/appRoleAssignments`, { $select: "id,resourceId,resourceDisplayName,appRoleId,createdDateTime" }, { max: 500 });
44
+ const out = await Promise.all(items.map(async (a) => ({ resource: a.resourceDisplayName ?? (await resolver.name(a.resourceId)), resourceId: a.resourceId, permission: await resolver.role(a.resourceId, a.appRoleId), grantedAt: a.createdDateTime })));
45
+ return { items: out, truncated };
46
+ }
47
+ export function registerApplicationTools(server, ctx) {
48
+ server.tool("m365_applications", "Enterprise applications (service principals) and what they were granted: view=enterprise_apps lists them (third party / this tenant / Microsoft); view=app_permissions shows the application permissions granted to one; view=delegated_grants lists delegated consents (admin or per user). Read-only — distinct from the entra-applications write family.", {
49
+ view: z.enum(["enterprise_apps", "app_permissions", "delegated_grants"]).default("enterprise_apps"),
50
+ servicePrincipal: z.string().min(1).max(256).optional().describe("app_permissions (required) / delegated_grants (optional): service principal object id, appId, or exact display name"),
51
+ owner: z.enum(["third_party", "this_tenant", "any"]).default("third_party").describe("enterprise_apps: who publishes the application (default: neither this tenant nor Microsoft)"),
52
+ search: searchText("enterprise_apps: prefix of the display name").optional(),
53
+ limit: limitParam,
54
+ cursor: cursorParam,
55
+ format: formatParam,
56
+ }, async ({ view, servicePrincipal, owner, search, limit, cursor, format }) => {
57
+ try {
58
+ const tenant = ctx.config.tenantId;
59
+ if (view === "enterprise_apps") {
60
+ const filters = ["tags/any(t:t eq 'WindowsAzureActiveDirectoryIntegratedApp')"];
61
+ if (search)
62
+ filters.push(`startswith(displayName,${odataString(search)})`);
63
+ if (owner === "this_tenant")
64
+ filters.push(`appOwnerOrganizationId eq ${tenant}`);
65
+ if (owner === "third_party")
66
+ filters.push([tenant, ...MICROSOFT_TENANTS].map((t) => `appOwnerOrganizationId ne ${t}`).join(" and "));
67
+ const page = await listPage(ctx, `m365_applications:apps:${owner}:${search ?? ""}`, { path: "/servicePrincipals", query: { $select: SP_FIELDS, $filter: filters.join(" and "), $count: "true" }, headers: ADVANCED }, limit, cursor);
68
+ return textResult(renderList(`Enterprise applications (${owner.replace("_", " ")})`, page, format, (s) => `${or(s.displayName)} (${s.id}, appId ${or(s.appId)}) — ${ownerOf(s, tenant)}${s.verifiedPublisher?.displayName ? ` — verified publisher ${s.verifiedPublisher.displayName}` : s.publisherName ? ` — publisher ${s.publisherName}` : ""}${s.accountEnabled === false ? " — DISABLED" : ""}${s.appRoleAssignmentRequired ? " — assignment required" : ""}`));
69
+ }
70
+ if (view === "app_permissions") {
71
+ if (!servicePrincipal)
72
+ throw new M365Error("invalid_request", "invalid_request: view=app_permissions needs servicePrincipal");
73
+ const sp = await resolveServicePrincipal(ctx, servicePrincipal);
74
+ const { items, truncated } = await appPermissions(ctx, sp.id);
75
+ const body = items.map((p) => `- ${p.resource}: **${p.permission}**${p.grantedAt ? ` — granted ${p.grantedAt}` : ""}`).join("\n");
76
+ return textResult(`# Application permissions of ${or(sp.displayName)} (${sp.id}) — ${ownerOf(sp, tenant)}\n\n${items.length ? body : "No application permission granted (the request succeeded)."}${truncated ? "\n\n⚠ truncated at 500" : ""}\n\nDelegated consents: m365_applications view=delegated_grants servicePrincipal=${sp.id}`);
77
+ }
78
+ const sp = servicePrincipal ? await resolveServicePrincipal(ctx, servicePrincipal) : undefined;
79
+ const resolver = roleResolver(ctx);
80
+ let page;
81
+ try {
82
+ page = await listPage(ctx, `m365_applications:grants:${sp?.id ?? ""}`, { path: "/oauth2PermissionGrants", query: { $filter: sp ? `clientId eq ${odataString(sp.id)}` : undefined }, supportsTop: false }, limit, cursor);
83
+ }
84
+ catch (err) {
85
+ if (err instanceof M365Error && err.code === "permission_missing") {
86
+ throw new M365Error("permission_missing", `permission_missing: delegated consents (GET /oauth2PermissionGrants) need DelegatedPermissionGrant.Read.All on the read identity — ${err.message}`, {
87
+ status: err.status,
88
+ requestId: err.requestId,
89
+ clientRequestId: err.clientRequestId,
90
+ });
91
+ }
92
+ throw err;
93
+ }
94
+ const named = await Promise.all(page.items.map(async (g) => ({ ...g, client: await resolver.name(g.clientId), resource: await resolver.name(g.resourceId) })));
95
+ return textResult(renderList(`Delegated permission grants${sp ? ` of ${or(sp.displayName)}` : ""}`, { ...page, items: named }, format, (g) => `${g.client} → ${g.resource}: ${(g.scope ?? "").trim().split(/\s+/).join(", ") || "—"} — ${g.consentType === "AllPrincipals" ? "ADMIN consent (all users)" : `user consent (${or(g.principalId)})`}`));
96
+ }
97
+ catch (err) {
98
+ return errorResult(err);
99
+ }
100
+ });
101
+ }
@@ -1,13 +1,16 @@
1
1
  import { toM365Error } from "../errors.js";
2
2
  import { FORBIDDEN_ROLES } from "../auth/token-provider.js";
3
- import { isWritePermission, permissionStatus, planStatus, TOOL_SPECS } from "../permissions.js";
4
- import { jsonBlock, textResult } from "./common.js";
3
+ import { extraStatus, isWritePermission, permissionStatus, planStatus, TOOL_SPECS } from "../permissions.js";
4
+ import { jsonBlock, tenantHas, textResult } from "./common.js";
5
5
  export const SERVER_INSTRUCTIONS = [
6
- "Microsoft 365 MCP over Microsoft Graph (v1.0): Entra ID users and groups, licences, Teams. Read-only unless M365_MODE=full.",
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.",
7
7
  "Start with m365_capabilities: it shows the mode, the tools registered and, for each, whether the Graph permission is present in the identity's token.",
8
8
  "Lists are paginated: pass the returned cursor to get the next page. A refused or unavailable API answers with an explicit error code (permission_missing, unsupported_by_tenant…), never an empty list.",
9
9
  "Writes ([WRITE] tools) are two-step: call once without confirmToken to get a preview and a token, then call again with the same arguments and the token. Get the user's explicit approval before the second call.",
10
- "Out of scope: Entra roles, applications and credentials, passwords, Conditional Access, permanent deletions, mail/chat/meeting/file content.",
10
+ "Helpdesk: m365_service_health first ('is it Microsoft?'), then the user/licence/group tools. Periodic access review: m365_access_review_snapshot (one call, compareWith: \"latest\").",
11
+ "Tools needing Entra ID P1/P2 or Intune answer unsupported_by_tenant on tenants without that licence — m365_capabilities shows which licences the tenant has.",
12
+ "Phase 2 (only if the audit identity is configured): m365_mailbox_permissions (who can use a shared mailbox), m365_activity_search (who deleted / shared a file — run m365_activity_collect regularly), m365_site_permissions (internal SharePoint rights).",
13
+ "Out of scope: writing Entra roles or Conditional Access, deletions, client secrets, private keys, programmatic consent, app-role-assignment/OAuth2-grant writes, passwords, mail/chat/meeting/file content.",
11
14
  ].join("\n");
12
15
  async function inspect(id) {
13
16
  const described = { ...id.describe(), role: id.role };
@@ -24,13 +27,14 @@ export function registerCapabilityTools(server, ctx) {
24
27
  server.tool("m365_capabilities", "Mode, tenant, the Entra identities in use (client id, auth method, certificate expiry — never a secret), the application permissions present in each token, and for every registered tool whether its permission is granted.", {}, async () => {
25
28
  const read = await inspect(ctx.identities.read);
26
29
  const write = ctx.identities.write ? await inspect(ctx.identities.write) : undefined;
30
+ const entra = ctx.identities.entra ? await inspect(ctx.identities.entra) : undefined;
27
31
  const warnings = [...ctx.config.warnings];
28
32
  if (read.ok) {
29
33
  const writes = read.roles.filter(isWritePermission);
30
34
  if (writes.length)
31
35
  warnings.push(`the READ identity holds write permissions (${writes.join(", ")}) — remove them to keep the identities separate`);
32
36
  }
33
- for (const id of [read, write]) {
37
+ for (const id of [read, write, entra]) {
34
38
  if (id?.ok) {
35
39
  const broad = id.roles.filter((r) => FORBIDDEN_ROLES.includes(r));
36
40
  if (broad.length)
@@ -40,22 +44,54 @@ export function registerCapabilityTools(server, ctx) {
40
44
  warnings.push(`the ${id.role} certificate expires in ${id.expiresInDays} day(s) — rotate it`);
41
45
  }
42
46
  }
47
+ const features = { "Entra ID P1": undefined, "Entra ID P2": undefined, Intune: undefined };
48
+ if (read.ok)
49
+ for (const f of Object.keys(features))
50
+ features[f] = await tenantHas(ctx, f);
51
+ // phase 2: one token per enabled API; the provider already enforced the exact role set
52
+ const apis = {};
53
+ for (const [api, p] of Object.entries(ctx.ext.providers))
54
+ if (p)
55
+ apis[api] = await inspect(p);
43
56
  const tools = TOOL_SPECS.filter((s) => ctx.registered.includes(s.tool)).map((s) => {
44
- const id = s.access === "write" ? write : read;
57
+ if (s.api) {
58
+ const a = apis[s.api];
59
+ return {
60
+ tool: s.tool,
61
+ access: s.access,
62
+ status: a?.ok ? "granted" : `${a?.error ?? "unknown"} (audit identity, ${s.api})`,
63
+ needs: s.permissions.join(" + "),
64
+ identity: `audit/${s.api}`,
65
+ requires: undefined,
66
+ parts: undefined,
67
+ };
68
+ }
69
+ const id = s.identity === "entra" ? entra : s.access === "write" ? write : read;
45
70
  let status = s.permissions.length === 0 ? "granted" : id?.ok ? permissionStatus(s, id.roles) : "unknown (no token)";
46
71
  // a write tool also needs, on the READ identity, the permissions its preview reads with
47
- if (s.planPermissions && status === "granted")
48
- status = read.ok ? (planStatus(s, read.roles) === "granted" ? "granted" : "missing on read identity (preview)") : "unknown (no read token)";
72
+ if (s.planPermissions && status === "granted") {
73
+ const preview = s.identity === "entra" ? entra : read;
74
+ status = preview?.ok ? (planStatus(s, preview.roles) === "granted" ? "granted" : `missing on ${s.identity === "entra" ? "entra" : "read"} identity (preview)`) : "unknown (no preview token)";
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)
78
+ status = `unsupported_by_tenant (needs ${s.requires})`;
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;
49
80
  return {
50
81
  tool: s.tool,
51
82
  access: s.access,
52
83
  status,
53
84
  needs: s.permissions.join(" + ") || "—",
54
- ...(s.planPermissions ? { previewNeedsOnRead: s.planPermissions.join(" + ") } : {}),
85
+ ...(s.requires ? { requires: s.requires } : {}),
86
+ ...(extras?.length ? { parts: extras } : {}),
87
+ ...(s.planPermissions ? { previewIdentity: s.identity === "entra" ? "entra" : "read", previewNeeds: s.planPermissions.join(" + ") } : {}),
55
88
  ...(s.rsc ? { rsc: s.rsc.join(", ") } : {}),
56
89
  };
57
90
  });
58
- const missing = tools.filter((t) => t.status !== "granted");
91
+ const missing = tools.filter((t) => t.status !== "granted" && !t.status.startsWith("unsupported_by_tenant"));
92
+ const unsupported = tools.filter((t) => t.status.startsWith("unsupported_by_tenant"));
93
+ const partial = tools.flatMap((t) => (t.parts ?? []).filter((p) => p.status !== "granted").map((p) => `${t.tool} › ${p.part}: ${p.status}${p.status === "missing" ? ` (${p.needs})` : ""}`));
94
+ const yn = (v) => (v === undefined ? "unknown" : v ? "yes" : "no");
59
95
  const killSwitch = ctx.killSwitchActive();
60
96
  const lines = [
61
97
  `# Microsoft 365 MCP — capabilities`,
@@ -64,10 +100,16 @@ export function registerCapabilityTools(server, ctx) {
64
100
  `Tenant: ${ctx.config.tenantId}`,
65
101
  killSwitch ? `⛔ Kill switch ACTIVE (${ctx.config.killSwitchFile}) — every write is refused` : "",
66
102
  `Sign-in audit tool: ${ctx.config.signInAudit ? "enabled" : "disabled (M365_ENABLE_SIGNIN_AUDIT)"}`,
103
+ `Entra applications family: ${ctx.config.writeFamilies.has("entra-applications") ? "enabled (owned objects only)" : "disabled (explicit M365_WRITE_FAMILIES opt-in required)"}`,
104
+ `Tenant licences: Entra ID P1 ${yn(features["Entra ID P1"])}, P2 ${yn(features["Entra ID P2"])}, Intune ${yn(features.Intune)}`,
105
+ `Audit identity (phase 2): ${ctx.config.audit ? `${ctx.config.audit.clientId} — features ${[...ctx.config.auditFeatures].join(", ")}` : "not configured (M365_AUDIT_APP_*)"}`,
106
+ `Access-review snapshots: ${ctx.config.snapshotDir ? ctx.config.snapshotDir : "not saved (M365_SNAPSHOT_DIR unset)"}`,
67
107
  `Registered tools: ${ctx.registered.length}`,
68
108
  missing.length ? `\n⚠ ${missing.length} tool(s) without their permission in the token: ${missing.map((t) => `${t.tool} (${t.needs})`).join("; ")}` : "\nAll registered tools have their permission.",
109
+ unsupported.length ? `ℹ ${unsupported.length} tool(s) unsupported by this tenant's licences: ${unsupported.map((t) => `${t.tool} (${t.requires})`).join("; ")}` : "",
110
+ partial.length ? `ℹ Partial: ${partial.join("; ")}` : "",
69
111
  warnings.length ? `\n## Warnings\n${warnings.map((w) => `- ${w}`).join("\n")}` : "",
70
112
  ].filter((l) => l !== "");
71
- return textResult(`${lines.join("\n")}\n\n## Identities\n${jsonBlock({ read, write: write ?? "not loaded (readonly mode)" })}\n\n## Tools\n${jsonBlock(tools)}`);
113
+ return textResult(`${lines.join("\n")}\n\n## Identities\n${jsonBlock({ read, write: write ?? "not loaded (readonly mode)", entra: entra ?? "not loaded (family disabled)", audit: Object.keys(apis).length ? apis : "not loaded (phase 2 disabled)" })}\n\n## Tools\n${jsonBlock(tools)}`);
72
114
  });
73
115
  }
@@ -78,7 +78,7 @@ export async function listPage(ctx, tool, first, limit, cursor) {
78
78
  else {
79
79
  url = ctx.graph.urlFor(first.path, { ...first.query, ...(first.supportsTop === false ? {} : { $top: limit }) });
80
80
  }
81
- const res = await ctx.graph.getUrl(url, { headers });
81
+ const res = await ctx.graph.getUrl(url, { headers, identity: first.identity });
82
82
  const value = Array.isArray(res.data?.value) ? res.data.value : [];
83
83
  const items = value.slice(offset, offset + limit);
84
84
  let nextCursor;
@@ -183,3 +183,79 @@ export class SkuCache {
183
183
  }
184
184
  }
185
185
  export const available = (s) => (s.prepaidUnits?.enabled ?? 0) - (s.consumedUnits ?? 0);
186
+ const FEATURE_PLANS = {
187
+ // AAD_PREMIUM = P1, AAD_PREMIUM_P2 = P2 (P2 includes P1)
188
+ "Entra ID P1": /^AAD_PREMIUM(_P2)?$/,
189
+ "Entra ID P2": /^AAD_PREMIUM_P2$/,
190
+ // INTUNE_A (Intune Plan 1), INTUNE_SMBIZ (Business Premium), INTUNE_EDU…
191
+ Intune: /^INTUNE_/,
192
+ };
193
+ /** true / false from the subscribed SKUs; undefined when they cannot be read (never guessed). */
194
+ export async function tenantHas(ctx, feature) {
195
+ const skus = await ctx.skus.list().catch(() => undefined);
196
+ if (!skus)
197
+ return undefined;
198
+ return skus.some((s) => s.capabilityStatus !== "Deleted" && (s.prepaidUnits?.enabled ?? 0) + (s.prepaidUnits?.warning ?? 0) > 0 && (s.servicePlans ?? []).some((p) => FEATURE_PLANS[feature].test(p.servicePlanName)));
199
+ }
200
+ /**
201
+ * A Graph refusal on an API that needs a premium licence becomes `unsupported_by_tenant` when the
202
+ * tenant really lacks it — so "you may not" (permission_missing) and "this tenant cannot" stay distinct.
203
+ */
204
+ export async function premiumError(ctx, err, feature, what) {
205
+ if (!(err instanceof M365Error))
206
+ return err;
207
+ if (err.code === "unsupported_by_tenant" || ((err.code === "permission_missing" || err.code === "invalid_request") && (await tenantHas(ctx, feature)) === false)) {
208
+ return new M365Error("unsupported_by_tenant", `unsupported_by_tenant: ${what} needs ${feature}, which this tenant does not have — ${err.message}`, {
209
+ status: err.status,
210
+ graphCode: err.graphCode,
211
+ requestId: err.requestId,
212
+ clientRequestId: err.clientRequestId,
213
+ });
214
+ }
215
+ return err;
216
+ }
217
+ /**
218
+ * Every item of a Graph collection, following nextLinks (host-checked), up to `max` items.
219
+ * For aggregate tools (snapshot, sharing links) that must not page through cursors.
220
+ */
221
+ export async function collectAll(ctx, path, query = {}, opts = {}) {
222
+ const max = opts.max ?? 5000;
223
+ const top = opts.top === false ? {} : { $top: opts.top ?? 999 };
224
+ let url = ctx.graph.urlFor(path, { ...query, ...top });
225
+ const items = [];
226
+ while (url) {
227
+ const res = await ctx.graph.getUrl(url, { headers: opts.headers });
228
+ items.push(...(Array.isArray(res.data?.value) ? res.data.value : []));
229
+ if (items.length >= max)
230
+ return { items: items.slice(0, max), truncated: items.length > max || Boolean(res.data?.["@odata.nextLink"]) };
231
+ const next = res.data?.["@odata.nextLink"];
232
+ url = next ? ctx.graph.assertGraphUrl(next).toString() : undefined;
233
+ }
234
+ return { items, truncated: false };
235
+ }
236
+ /** Run `fn` over `items` with at most `concurrency` calls in flight (keeps Graph throttling at bay). */
237
+ export async function mapLimit(items, concurrency, fn) {
238
+ const out = new Array(items.length);
239
+ let next = 0;
240
+ const worker = async () => {
241
+ while (next < items.length) {
242
+ const i = next++;
243
+ out[i] = await fn(items[i]);
244
+ }
245
+ };
246
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
247
+ return out;
248
+ }
249
+ /** Sizes always in bytes and in GB (10^9, as the Microsoft 365 admin center). */
250
+ export const sizeOf = (bytes) => bytes === undefined || bytes === null || Number.isNaN(bytes) ? undefined : { bytes, gb: Math.round((bytes / 1e9) * 100) / 100 };
251
+ export const sizeText = (bytes) => {
252
+ const s = sizeOf(bytes);
253
+ return s ? `${s.gb} GB (${s.bytes} B)` : "—";
254
+ };
255
+ /** Whole days since an ISO date, or undefined. */
256
+ export const daysSince = (iso, now = Date.now()) => {
257
+ if (!iso)
258
+ return undefined;
259
+ const t = Date.parse(iso);
260
+ return Number.isNaN(t) ? undefined : Math.floor((now - t) / 86_400_000);
261
+ };
@@ -0,0 +1,40 @@
1
+ import { z } from "zod";
2
+ import { cursorParam, daysSince, errorResult, formatParam, limitParam, listPage, odataString, or, premiumError, renderList, textResult } from "./common.js";
3
+ const DEVICE_FIELDS = "id,deviceName,operatingSystem,osVersion,complianceState,managementState,lastSyncDateTime,enrolledDateTime,userPrincipalName,userDisplayName,managedDeviceOwnerType,model,manufacturer,isEncrypted,jailBroken,azureADDeviceId";
4
+ export function registerDeviceTools(server, ctx) {
5
+ server.tool("m365_intune_devices", "Devices managed by Intune: compliance, OS, encryption, last contact, primary user. Needs an Intune licence (e.g. Business Premium) — otherwise unsupported_by_tenant.", {
6
+ complianceState: z.enum(["compliant", "noncompliant", "inGracePeriod", "unknown", "error", "conflict", "configManager"]).optional(),
7
+ operatingSystem: z.enum(["Windows", "iOS", "Android", "macOS"]).optional(),
8
+ user: z.string().max(256).optional().describe("Primary user's UPN (exact)"),
9
+ staleDays: z.number().int().min(1).max(3650).optional().describe("Only devices that have not synced for at least N days"),
10
+ ownerType: z.enum(["company", "personal"]).optional(),
11
+ limit: limitParam,
12
+ cursor: cursorParam,
13
+ format: formatParam,
14
+ }, async ({ complianceState, operatingSystem, user, staleDays, ownerType, limit, cursor, format }) => {
15
+ try {
16
+ const filters = [];
17
+ if (complianceState)
18
+ filters.push(`complianceState eq ${odataString(complianceState)}`);
19
+ if (operatingSystem)
20
+ filters.push(`operatingSystem eq ${odataString(operatingSystem)}`);
21
+ if (user)
22
+ filters.push(`userPrincipalName eq ${odataString(user.toLowerCase())}`);
23
+ if (staleDays)
24
+ filters.push(`lastSyncDateTime le ${new Date(Date.now() - staleDays * 86_400_000).toISOString()}`);
25
+ if (ownerType)
26
+ filters.push(`managedDeviceOwnerType eq ${odataString(ownerType)}`);
27
+ let page;
28
+ try {
29
+ page = await listPage(ctx, `m365_intune_devices:${filters.join(" and ")}`, { path: "/deviceManagement/managedDevices", query: { $select: DEVICE_FIELDS, $filter: filters.join(" and ") || undefined } }, limit, cursor);
30
+ }
31
+ catch (err) {
32
+ throw await premiumError(ctx, err, "Intune", "managed devices");
33
+ }
34
+ return textResult(renderList("Intune managed devices", page, format, (d) => `${or(d.deviceName)} — ${or(d.operatingSystem)} ${or(d.osVersion, "")} — ${d.complianceState === "compliant" ? "compliant" : `⚠ ${or(d.complianceState)}`} — ${d.isEncrypted ? "encrypted" : "NOT encrypted"}${d.jailBroken === "True" ? " — JAILBROKEN" : ""} — ${or(d.managedDeviceOwnerType)} — user ${or(d.userPrincipalName)} — last sync ${or(d.lastSyncDateTime)}${daysSince(d.lastSyncDateTime) !== undefined ? ` (${daysSince(d.lastSyncDateTime)} days)` : ""}`));
35
+ }
36
+ catch (err) {
37
+ return errorResult(err);
38
+ }
39
+ });
40
+ }