@aidalinfo/m365-mcp 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +373 -0
- package/dist/audit.js +52 -0
- package/dist/auth/credentials.js +120 -0
- package/dist/auth/token-provider.js +133 -0
- package/dist/config.js +120 -0
- package/dist/confirm.js +74 -0
- package/dist/context.js +57 -0
- package/dist/errors.js +98 -0
- package/dist/graph-client.js +168 -0
- package/dist/http.js +3 -0
- package/dist/index.js +28 -0
- package/dist/pagination.js +42 -0
- package/dist/permissions.js +212 -0
- package/dist/redact.js +76 -0
- package/dist/register.js +51 -0
- package/dist/tools/capabilities.js +73 -0
- package/dist/tools/common.js +185 -0
- package/dist/tools/groups-write.js +93 -0
- package/dist/tools/groups.js +110 -0
- package/dist/tools/licenses-write.js +129 -0
- package/dist/tools/licenses.js +59 -0
- package/dist/tools/organization.js +32 -0
- package/dist/tools/teams-write.js +264 -0
- package/dist/tools/teams.js +71 -0
- package/dist/tools/users-write.js +82 -0
- package/dist/tools/users.js +136 -0
- package/dist/tools/write-flow.js +87 -0
- package/package.json +56 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { M365Error } from "../errors.js";
|
|
2
|
+
import { groupParam, resolveGroup, resolveUser, userParam } from "./common.js";
|
|
3
|
+
import { groupKind } from "./groups.js";
|
|
4
|
+
import { confirmParams, rid, runWrite } from "./write-flow.js";
|
|
5
|
+
const GROUP_GUARD_FIELDS = "id,displayName,mailEnabled,securityEnabled,groupTypes,isAssignableToRole,onPremisesSyncEnabled,resourceProvisioningOptions";
|
|
6
|
+
/** Why this group's membership must not be changed here, if it must not. */
|
|
7
|
+
export function membershipGuard(g) {
|
|
8
|
+
const types = g.groupTypes ?? [];
|
|
9
|
+
if (types.includes("DynamicMembership"))
|
|
10
|
+
return "dynamic group — membership is computed from its rule, change the user's attributes instead";
|
|
11
|
+
if (g.onPremisesSyncEnabled)
|
|
12
|
+
return "group synced from on-premises AD — change it in Active Directory";
|
|
13
|
+
if (g.isAssignableToRole)
|
|
14
|
+
return "role-assignable group — membership grants Entra roles, out of scope for this server";
|
|
15
|
+
if (g.resourceProvisioningOptions?.includes("Team"))
|
|
16
|
+
return "this group backs a team — use m365_team_member_add / m365_team_member_remove (they protect owners and archived teams)";
|
|
17
|
+
if (g.mailEnabled && !types.includes("Unified"))
|
|
18
|
+
return "distribution list / mail-enabled security group — managed in Exchange Online, not through Graph";
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
/** Direct membership of `memberId` in `groupId` (advanced query, so the answer is exact on id). */
|
|
22
|
+
async function isMember(ctx, groupId, memberId) {
|
|
23
|
+
const res = await ctx.graph.get(`/groups/${groupId}/members`, {
|
|
24
|
+
query: { $filter: `id eq '${memberId}'`, $select: "id", $count: "true" },
|
|
25
|
+
headers: { ConsistencyLevel: "eventual" },
|
|
26
|
+
});
|
|
27
|
+
return (res.data?.value ?? []).some((m) => m.id === memberId);
|
|
28
|
+
}
|
|
29
|
+
async function planMembership(ctx, group, user, adding) {
|
|
30
|
+
const g = (await resolveGroup(ctx, group, GROUP_GUARD_FIELDS));
|
|
31
|
+
const u = await resolveUser(ctx, user, "id,displayName,userPrincipalName");
|
|
32
|
+
const member = await isMember(ctx, g.id, u.id);
|
|
33
|
+
return {
|
|
34
|
+
targetType: "group",
|
|
35
|
+
targetId: g.id,
|
|
36
|
+
targetLabel: `${g.displayName ?? ""} [${groupKind(g)}]`,
|
|
37
|
+
operation: adding ? "add_member" : "remove_member",
|
|
38
|
+
before: { member },
|
|
39
|
+
change: { [adding ? "add" : "remove"]: { id: u.id, displayName: u.displayName, userPrincipalName: u.userPrincipalName } },
|
|
40
|
+
refuse: membershipGuard(g),
|
|
41
|
+
noop: member === adding ? `${u.userPrincipalName ?? u.id} is ${adding ? "already a member" : "not a member"}` : undefined,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const memberIdOf = (plan) => {
|
|
45
|
+
const c = plan.change;
|
|
46
|
+
return (c.add ?? c.remove).id;
|
|
47
|
+
};
|
|
48
|
+
export function registerGroupWriteTools(server, ctx) {
|
|
49
|
+
server.tool("m365_group_member_add", "[WRITE] Add a user to a Microsoft 365 or security group (direct membership). Refuses dynamic, AD-synced, role-assignable and Exchange-managed groups. Idempotent. Two steps: preview then execute with the returned token.", { group: groupParam, user: userParam, ...confirmParams }, async ({ group, user, confirmToken, approvalId }) => runWrite({
|
|
50
|
+
tool: "m365_group_member_add",
|
|
51
|
+
ctx,
|
|
52
|
+
confirmToken,
|
|
53
|
+
approvalId,
|
|
54
|
+
plan: () => planMembership(ctx, group, user, true),
|
|
55
|
+
execute: async (plan) => {
|
|
56
|
+
const memberId = memberIdOf(plan);
|
|
57
|
+
try {
|
|
58
|
+
const res = await ctx.graph.request("POST", `/groups/${plan.targetId}/members/$ref`, {
|
|
59
|
+
identity: "write",
|
|
60
|
+
idempotent: true,
|
|
61
|
+
body: { "@odata.id": `${ctx.graph.base.toString()}/directoryObjects/${memberId}` },
|
|
62
|
+
});
|
|
63
|
+
return [rid(res)];
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
// added concurrently (or replication lag on the pre-check): the target state is reached
|
|
67
|
+
if (err instanceof M365Error && err.code === "conflict")
|
|
68
|
+
return [err.requestId ?? ""];
|
|
69
|
+
throw err;
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
after: async (plan) => ({ member: await isMember(ctx, plan.targetId, memberIdOf(plan)) }),
|
|
73
|
+
}));
|
|
74
|
+
server.tool("m365_group_member_remove", "[WRITE] Remove a user from a group (direct membership). Same guards as m365_group_member_add. Idempotent. Two steps: preview then execute with the returned token.", { group: groupParam, user: userParam, ...confirmParams }, async ({ group, user, confirmToken, approvalId }) => runWrite({
|
|
75
|
+
tool: "m365_group_member_remove",
|
|
76
|
+
ctx,
|
|
77
|
+
confirmToken,
|
|
78
|
+
approvalId,
|
|
79
|
+
plan: () => planMembership(ctx, group, user, false),
|
|
80
|
+
execute: async (plan) => {
|
|
81
|
+
try {
|
|
82
|
+
const res = await ctx.graph.request("DELETE", `/groups/${plan.targetId}/members/${memberIdOf(plan)}/$ref`, { identity: "write" });
|
|
83
|
+
return [rid(res)];
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
if (err instanceof M365Error && err.code === "not_found")
|
|
87
|
+
return [err.requestId ?? ""];
|
|
88
|
+
throw err;
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
after: async (plan) => ({ member: await isMember(ctx, plan.targetId, memberIdOf(plan)) }),
|
|
92
|
+
}));
|
|
93
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { cursorParam, errorResult, fieldsParam, formatParam, groupParam, jsonBlock, limitParam, listPage, odataString, or, renderList, resolveGroup, searchText, selectFields, textResult, } from "./common.js";
|
|
3
|
+
export const GROUP_FIELDS = [
|
|
4
|
+
"id",
|
|
5
|
+
"displayName",
|
|
6
|
+
"description",
|
|
7
|
+
"mail",
|
|
8
|
+
"mailNickname",
|
|
9
|
+
"mailEnabled",
|
|
10
|
+
"securityEnabled",
|
|
11
|
+
"groupTypes",
|
|
12
|
+
"visibility",
|
|
13
|
+
"membershipRule",
|
|
14
|
+
"membershipRuleProcessingState",
|
|
15
|
+
"isAssignableToRole",
|
|
16
|
+
"onPremisesSyncEnabled",
|
|
17
|
+
"createdDateTime",
|
|
18
|
+
"resourceProvisioningOptions",
|
|
19
|
+
];
|
|
20
|
+
const GROUP_DEFAULT = ["id", "displayName", "mail", "mailEnabled", "securityEnabled", "groupTypes", "isAssignableToRole", "onPremisesSyncEnabled", "resourceProvisioningOptions"];
|
|
21
|
+
const ADVANCED = { ConsistencyLevel: "eventual" };
|
|
22
|
+
const TYPE_FILTERS = {
|
|
23
|
+
microsoft365: "groupTypes/any(c:c eq 'Unified')",
|
|
24
|
+
security: "securityEnabled eq true and mailEnabled eq false",
|
|
25
|
+
mailEnabledSecurity: "securityEnabled eq true and mailEnabled eq true",
|
|
26
|
+
distribution: "mailEnabled eq true and securityEnabled eq false",
|
|
27
|
+
dynamic: "groupTypes/any(c:c eq 'DynamicMembership')",
|
|
28
|
+
team: "resourceProvisioningOptions/Any(x:x eq 'Team')",
|
|
29
|
+
};
|
|
30
|
+
export function groupKind(g) {
|
|
31
|
+
const types = g.groupTypes ?? [];
|
|
32
|
+
const kind = types.includes("Unified")
|
|
33
|
+
? "Microsoft 365"
|
|
34
|
+
: g.mailEnabled && g.securityEnabled
|
|
35
|
+
? "mail-enabled security"
|
|
36
|
+
: g.mailEnabled
|
|
37
|
+
? "distribution list"
|
|
38
|
+
: "security";
|
|
39
|
+
const flags = [
|
|
40
|
+
types.includes("DynamicMembership") ? "dynamic" : "",
|
|
41
|
+
g.resourceProvisioningOptions?.includes("Team") ? "team" : "",
|
|
42
|
+
g.isAssignableToRole ? "role-assignable" : "",
|
|
43
|
+
g.onPremisesSyncEnabled ? "synced from AD" : "",
|
|
44
|
+
].filter(Boolean);
|
|
45
|
+
return `${kind}${flags.length ? ` (${flags.join(", ")})` : ""}`;
|
|
46
|
+
}
|
|
47
|
+
const memberLine = (m) => `${or(m.displayName)}${m.userPrincipalName ? ` <${m.userPrincipalName}>` : ""} (${m.id}) — ${String(m["@odata.type"] ?? "").replace("#microsoft.graph.", "") || "object"}`;
|
|
48
|
+
export function registerGroupTools(server, ctx) {
|
|
49
|
+
server.tool("m365_groups", "List Entra ID groups (paginated, bounded): Microsoft 365, security, distribution, dynamic, team-enabled. Structured filters only.", {
|
|
50
|
+
search: searchText("Prefix matched against displayName, mail and mailNickname").optional(),
|
|
51
|
+
type: z.enum(Object.keys(TYPE_FILTERS)).optional().describe("Group kind"),
|
|
52
|
+
fields: fieldsParam(GROUP_FIELDS),
|
|
53
|
+
limit: limitParam,
|
|
54
|
+
cursor: cursorParam,
|
|
55
|
+
format: formatParam,
|
|
56
|
+
}, async ({ search, type, fields, limit, cursor, format }) => {
|
|
57
|
+
try {
|
|
58
|
+
const filters = [];
|
|
59
|
+
if (search) {
|
|
60
|
+
const q = odataString(search);
|
|
61
|
+
filters.push(`(startswith(displayName,${q}) or startswith(mail,${q}) or startswith(mailNickname,${q}))`);
|
|
62
|
+
}
|
|
63
|
+
if (type)
|
|
64
|
+
filters.push(TYPE_FILTERS[type]);
|
|
65
|
+
const page = await listPage(ctx, "m365_groups", {
|
|
66
|
+
path: "/groups",
|
|
67
|
+
query: { $select: selectFields(GROUP_FIELDS, GROUP_DEFAULT, fields), $filter: filters.join(" and ") || undefined, $count: "true" },
|
|
68
|
+
headers: ADVANCED,
|
|
69
|
+
}, limit, cursor);
|
|
70
|
+
return textResult(renderList("Groups", page, format, (g) => `${or(g.displayName)}${g.mail ? ` <${g.mail}>` : ""} (${g.id}) — ${groupKind(g)}`));
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
return errorResult(err);
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
server.tool("m365_group_info", "One group in detail: kind, membership rule (dynamic), sync origin, member count and owners (first 20).", { group: groupParam }, async ({ group }) => {
|
|
77
|
+
try {
|
|
78
|
+
const g = (await resolveGroup(ctx, group, GROUP_FIELDS.join(",")));
|
|
79
|
+
const [count, owners] = await Promise.all([
|
|
80
|
+
ctx.graph.get(`/groups/${g.id}/members/$count`, { headers: { ...ADVANCED, Accept: "text/plain" } }).then((r) => Number(r.data), () => undefined),
|
|
81
|
+
ctx.graph
|
|
82
|
+
.get(`/groups/${g.id}/owners`, { query: { $select: "id,displayName,userPrincipalName", $top: 20 } })
|
|
83
|
+
.then((r) => r.data?.value ?? []),
|
|
84
|
+
]);
|
|
85
|
+
const ownerLines = owners.map((o) => `- ${memberLine(o)}`).join("\n") || "none";
|
|
86
|
+
return textResult(`# ${or(g.displayName)} (${g.id})\n\nKind: ${groupKind(g)}\nMembers: ${count ?? "unknown"}\n${g.membershipRule ? `Membership rule: ${g.membershipRule}\n` : ""}\n## Owners\n${ownerLines}\n\n${jsonBlock(g)}`);
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
return errorResult(err);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
server.tool("m365_group_members", "Members of a group (paginated): users, devices, nested groups, service principals. transitive=true flattens nested groups.", {
|
|
93
|
+
group: groupParam,
|
|
94
|
+
transitive: z.boolean().default(false).describe("Include members of nested groups"),
|
|
95
|
+
limit: limitParam,
|
|
96
|
+
cursor: cursorParam,
|
|
97
|
+
format: formatParam,
|
|
98
|
+
}, async ({ group, transitive, limit, cursor, format }) => {
|
|
99
|
+
try {
|
|
100
|
+
const g = await resolveGroup(ctx, group, "id,displayName");
|
|
101
|
+
// the cursor is bound to this group: a cursor of another group is refused, not silently mislabelled
|
|
102
|
+
const tool = `m365_group_members:${transitive ? "transitive" : "direct"}:${g.id}`;
|
|
103
|
+
const page = await listPage(ctx, tool, { path: `/groups/${g.id}/${transitive ? "transitiveMembers" : "members"}`, query: { $select: "id,displayName,userPrincipalName,mail,userType,accountEnabled" } }, limit, cursor);
|
|
104
|
+
return textResult(renderList(`Members of ${or(g.displayName, group)}`, page, format, memberLine));
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
return errorResult(err);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { M365Error } from "../errors.js";
|
|
3
|
+
import { GUID_RE } from "../config.js";
|
|
4
|
+
import { available, resolveUser, userParam } from "./common.js";
|
|
5
|
+
import { confirmParams, rid, runWrite } from "./write-flow.js";
|
|
6
|
+
const skuRef = z.string().min(1).max(128).describe("skuPartNumber (e.g. ENTERPRISEPACK) or skuId — see m365_subscribed_skus");
|
|
7
|
+
async function licenceState(ctx, user) {
|
|
8
|
+
const u = await resolveUser(ctx, user, "id,displayName,userPrincipalName,usageLocation,assignedLicenses,licenseAssignmentStates");
|
|
9
|
+
const states = u.licenseAssignmentStates ?? [];
|
|
10
|
+
const bySku = new Map();
|
|
11
|
+
for (const s of states) {
|
|
12
|
+
const a = bySku.get(s.skuId) ?? { skuId: s.skuId, direct: false, inheritedFrom: [], disabledPlans: [] };
|
|
13
|
+
if (s.assignedByGroup)
|
|
14
|
+
a.inheritedFrom.push(s.assignedByGroup);
|
|
15
|
+
else {
|
|
16
|
+
a.direct = true;
|
|
17
|
+
a.disabledPlans = [...(s.disabledPlans ?? [])].sort();
|
|
18
|
+
}
|
|
19
|
+
bySku.set(s.skuId, a);
|
|
20
|
+
}
|
|
21
|
+
for (const a of bySku.values())
|
|
22
|
+
a.inheritedFrom.sort();
|
|
23
|
+
return { user: u, usageLocation: u.usageLocation ?? null, licences: [...bySku.values()].sort((a, b) => a.skuId.localeCompare(b.skuId)) };
|
|
24
|
+
}
|
|
25
|
+
export function registerLicenseWriteTools(server, ctx) {
|
|
26
|
+
server.tool("m365_user_assign_licenses", "[WRITE] Assign and/or remove licences of a user in one call. Checks free units, usageLocation and group-inherited licences (which must be removed from the group instead). Idempotent. Two steps: preview then execute with the returned token.", {
|
|
27
|
+
user: userParam,
|
|
28
|
+
add: z
|
|
29
|
+
.array(z
|
|
30
|
+
.object({
|
|
31
|
+
sku: skuRef,
|
|
32
|
+
disabledPlans: z.array(z.string().min(1).max(128)).max(50).optional().describe("Service plans to disable (servicePlanName or id) — see m365_subscribed_skus includeServicePlans"),
|
|
33
|
+
})
|
|
34
|
+
.strict())
|
|
35
|
+
.max(10)
|
|
36
|
+
.default([]),
|
|
37
|
+
remove: z.array(skuRef).max(10).default([]),
|
|
38
|
+
...confirmParams,
|
|
39
|
+
}, async ({ user, add, remove, confirmToken, approvalId }) => runWrite({
|
|
40
|
+
tool: "m365_user_assign_licenses",
|
|
41
|
+
ctx,
|
|
42
|
+
confirmToken,
|
|
43
|
+
approvalId,
|
|
44
|
+
plan: async () => {
|
|
45
|
+
const state = await licenceState(ctx, user);
|
|
46
|
+
const { user: u, licences } = state;
|
|
47
|
+
const current = new Map(licences.map((l) => [l.skuId, l]));
|
|
48
|
+
const addLicenses = [];
|
|
49
|
+
const removeLicenses = [];
|
|
50
|
+
const skipped = [];
|
|
51
|
+
let refuse;
|
|
52
|
+
// resolve every SKU first, so a contradictory request is refused before any idempotence shortcut
|
|
53
|
+
const toAdd = await Promise.all(add.map(async (a) => ({ a, sku: await ctx.skus.resolve(a.sku) })));
|
|
54
|
+
// by GUID: no name lookup, so the bound plan never depends on a cache hit
|
|
55
|
+
const toRemove = await Promise.all(remove.map(async (r) => (GUID_RE.test(r) ? { skuId: r.toLowerCase(), skuPartNumber: r.toLowerCase() } : await ctx.skus.resolve(r))));
|
|
56
|
+
const both = toRemove.filter((r) => toAdd.some(({ sku }) => sku.skuId.toLowerCase() === r.skuId.toLowerCase()));
|
|
57
|
+
if (both.length)
|
|
58
|
+
throw new M365Error("invalid_request", `invalid_request: ${both.map((s) => s.skuPartNumber).join(", ")} both added and removed`);
|
|
59
|
+
for (const { a, sku } of toAdd) {
|
|
60
|
+
const disabledPlans = (a.disabledPlans ?? [])
|
|
61
|
+
.map((p) => {
|
|
62
|
+
const plan = sku.servicePlans?.find((sp) => sp.servicePlanId.toLowerCase() === p.toLowerCase() || sp.servicePlanName.toLowerCase() === p.toLowerCase());
|
|
63
|
+
if (!plan)
|
|
64
|
+
throw new M365Error("invalid_request", `invalid_request: ${sku.skuPartNumber} has no service plan "${p}"`);
|
|
65
|
+
return plan.servicePlanId;
|
|
66
|
+
})
|
|
67
|
+
.sort();
|
|
68
|
+
const cur = current.get(sku.skuId);
|
|
69
|
+
if (cur?.direct && JSON.stringify(cur.disabledPlans) === JSON.stringify(disabledPlans)) {
|
|
70
|
+
skipped.push(`${sku.skuPartNumber} already assigned directly`);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
// a user already holding the SKU (directly or through a group) does not consume another unit
|
|
74
|
+
if (!cur && available(sku) <= 0) {
|
|
75
|
+
throw new M365Error("license_unavailable", `license_unavailable: no free ${sku.skuPartNumber} unit (purchased ${sku.prepaidUnits?.enabled ?? 0}, consumed ${sku.consumedUnits ?? 0})`);
|
|
76
|
+
}
|
|
77
|
+
if (sku.capabilityStatus && sku.capabilityStatus !== "Enabled" && !cur) {
|
|
78
|
+
throw new M365Error("license_unavailable", `license_unavailable: ${sku.skuPartNumber} is ${sku.capabilityStatus}`);
|
|
79
|
+
}
|
|
80
|
+
addLicenses.push({ skuId: sku.skuId, sku: sku.skuPartNumber, disabledPlans });
|
|
81
|
+
}
|
|
82
|
+
for (const sku of toRemove) {
|
|
83
|
+
const cur = current.get(sku.skuId);
|
|
84
|
+
if (!cur) {
|
|
85
|
+
skipped.push(`${sku.skuPartNumber} not assigned`);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (!cur.direct) {
|
|
89
|
+
refuse = `${sku.skuPartNumber} is inherited from group(s) ${cur.inheritedFrom.join(", ")} — remove the user from the group (or the licence from the group) instead`;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (cur.inheritedFrom.length)
|
|
93
|
+
skipped.push(`${sku.skuPartNumber}: the direct assignment is removed but the licence stays through group(s) ${cur.inheritedFrom.join(", ")}`);
|
|
94
|
+
removeLicenses.push({ skuId: sku.skuId, sku: sku.skuPartNumber });
|
|
95
|
+
}
|
|
96
|
+
if (addLicenses.length && !state.usageLocation) {
|
|
97
|
+
refuse = "the user has no usageLocation — set it first with m365_user_update (changes.usageLocation, e.g. FR)";
|
|
98
|
+
}
|
|
99
|
+
if (!add.length && !remove.length)
|
|
100
|
+
refuse = "nothing to add or remove";
|
|
101
|
+
return {
|
|
102
|
+
targetType: "user",
|
|
103
|
+
targetId: u.id,
|
|
104
|
+
targetLabel: `${u.displayName ?? ""} <${u.userPrincipalName ?? ""}>`,
|
|
105
|
+
operation: "assign_licenses",
|
|
106
|
+
before: { usageLocation: state.usageLocation, licences },
|
|
107
|
+
change: { addLicenses, removeLicenses, notes: skipped },
|
|
108
|
+
refuse,
|
|
109
|
+
noop: !addLicenses.length && !removeLicenses.length ? skipped.join("; ") || "nothing to change" : undefined,
|
|
110
|
+
};
|
|
111
|
+
},
|
|
112
|
+
execute: async (plan) => {
|
|
113
|
+
const change = plan.change;
|
|
114
|
+
const res = await ctx.graph.request("POST", `/users/${plan.targetId}/assignLicense`, {
|
|
115
|
+
identity: "write",
|
|
116
|
+
idempotent: true, // assignLicense sets a target state: safe to retry
|
|
117
|
+
body: {
|
|
118
|
+
addLicenses: change.addLicenses.map((a) => ({ skuId: a.skuId, disabledPlans: a.disabledPlans })),
|
|
119
|
+
removeLicenses: change.removeLicenses.map((r) => r.skuId),
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
return [rid(res)];
|
|
123
|
+
},
|
|
124
|
+
after: async (plan) => {
|
|
125
|
+
const s = await licenceState(ctx, plan.targetId);
|
|
126
|
+
return { usageLocation: s.usageLocation, licences: s.licences };
|
|
127
|
+
},
|
|
128
|
+
}));
|
|
129
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { available, errorResult, jsonBlock, or, resolveUser, textResult, userParam } from "./common.js";
|
|
3
|
+
export function registerLicenseTools(server, ctx) {
|
|
4
|
+
server.tool("m365_subscribed_skus", "Licences the tenant subscribes to: units purchased (enabled), consumed, available, suspended, in warning — per SKU. Use before assigning a licence.", {
|
|
5
|
+
sku: z.string().max(128).optional().describe("Only this SKU (skuPartNumber, e.g. ENTERPRISEPACK, or skuId)"),
|
|
6
|
+
includeServicePlans: z.boolean().default(false).describe("Also list the service plans of each SKU"),
|
|
7
|
+
}, async ({ sku, includeServicePlans }) => {
|
|
8
|
+
try {
|
|
9
|
+
const skus = sku ? [await ctx.skus.resolve(sku)] : await ctx.skus.list(true);
|
|
10
|
+
if (!skus.length)
|
|
11
|
+
return textResult("# Subscribed SKUs\n\nThe tenant has no subscription (the request succeeded).");
|
|
12
|
+
const lines = skus.map((s) => {
|
|
13
|
+
const p = s.prepaidUnits ?? {};
|
|
14
|
+
const free = available(s);
|
|
15
|
+
const flags = [p.suspended ? `${p.suspended} suspended` : "", p.warning ? `${p.warning} in warning` : "", p.lockedOut ? `${p.lockedOut} locked out` : ""].filter(Boolean);
|
|
16
|
+
return `- **${s.skuPartNumber}** (${s.skuId}) — ${or(s.capabilityStatus)}, ${or(s.appliesTo)} — purchased ${p.enabled ?? 0}, consumed ${s.consumedUnits ?? 0}, available ${free}${free <= 0 ? " ⚠ none left" : ""}${flags.length ? ` — ${flags.join(", ")}` : ""}`;
|
|
17
|
+
});
|
|
18
|
+
const detail = includeServicePlans
|
|
19
|
+
? `\n\n${jsonBlock(skus.map((s) => ({ skuPartNumber: s.skuPartNumber, servicePlans: (s.servicePlans ?? []).map((sp) => ({ id: sp.servicePlanId, name: sp.servicePlanName, appliesTo: sp.appliesTo })) })))}`
|
|
20
|
+
: "";
|
|
21
|
+
return textResult(`# Subscribed SKUs (${skus.length})\n\n${lines.join("\n")}${detail}`);
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
return errorResult(err);
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
server.tool("m365_license_assignments", "Licences of one user: each SKU with how it is assigned (direct or inherited from a group — inherited ones cannot be removed on the user), its state and error, disabled plans, and the capability status of each assigned service plan.", { user: userParam, includeServicePlans: z.boolean().default(false).describe("List each assigned service plan and its capability status (from the user's assignedPlans)") }, async ({ user, includeServicePlans }) => {
|
|
28
|
+
try {
|
|
29
|
+
const u = await resolveUser(ctx, user, "id,displayName,userPrincipalName,usageLocation,assignedLicenses,licenseAssignmentStates");
|
|
30
|
+
const states = u.licenseAssignmentStates ?? [];
|
|
31
|
+
const lines = await Promise.all(states.map(async (s) => {
|
|
32
|
+
const how = s.assignedByGroup ? `inherited from group ${s.assignedByGroup}` : "direct";
|
|
33
|
+
const err = s.error && s.error !== "None" ? ` — ERROR ${s.error}` : "";
|
|
34
|
+
const disabled = s.disabledPlans?.length ? ` — ${s.disabledPlans.length} plan(s) disabled` : "";
|
|
35
|
+
return `- ${await ctx.skus.name(s.skuId)} (${s.skuId}) — ${how} — ${or(s.state)}${err}${disabled}`;
|
|
36
|
+
}));
|
|
37
|
+
let plans = "";
|
|
38
|
+
if (includeServicePlans) {
|
|
39
|
+
// GET /users/{id}/licenseDetails supports delegated permissions only; with app-only identities
|
|
40
|
+
// the per-plan state comes from the user's assignedPlans, named through /subscribedSkus.
|
|
41
|
+
const res = await ctx.graph.get(`/users/${u.id}`, { query: { $select: "id,assignedPlans" } });
|
|
42
|
+
const skus = await ctx.skus.list().catch(() => []);
|
|
43
|
+
const planName = new Map(skus.flatMap((s) => (s.servicePlans ?? []).map((sp) => [sp.servicePlanId, `${sp.servicePlanName} (${s.skuPartNumber})`])));
|
|
44
|
+
const assigned = (res.data?.assignedPlans ?? []).map((p) => ({
|
|
45
|
+
servicePlan: planName.get(p.servicePlanId) ?? p.servicePlanId,
|
|
46
|
+
service: p.service,
|
|
47
|
+
capabilityStatus: p.capabilityStatus,
|
|
48
|
+
assignedDateTime: p.assignedDateTime,
|
|
49
|
+
}));
|
|
50
|
+
plans = `\n\n## Service plans (assignedPlans)\n${jsonBlock(assigned)}`;
|
|
51
|
+
}
|
|
52
|
+
const loc = u.usageLocation ? `usageLocation ${u.usageLocation}` : "⚠ no usageLocation — licences cannot be assigned until it is set";
|
|
53
|
+
return textResult(`# Licences of ${or(u.displayName)} <${or(u.userPrincipalName)}> (${u.id})\n\n${loc}\n\n${lines.join("\n") || "No licence assigned."}${plans}`);
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
return errorResult(err);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { errorResult, jsonBlock, or, textResult } from "./common.js";
|
|
2
|
+
/** Allowlisted organisation fields: identity, domains and sync — no contact e-mails or phone numbers. */
|
|
3
|
+
const ORG_FIELDS = [
|
|
4
|
+
"id",
|
|
5
|
+
"displayName",
|
|
6
|
+
"tenantType",
|
|
7
|
+
"countryLetterCode",
|
|
8
|
+
"preferredLanguage",
|
|
9
|
+
"createdDateTime",
|
|
10
|
+
"verifiedDomains",
|
|
11
|
+
"onPremisesSyncEnabled",
|
|
12
|
+
"onPremisesLastSyncDateTime",
|
|
13
|
+
];
|
|
14
|
+
export function registerOrganizationTools(server, ctx) {
|
|
15
|
+
server.tool("m365_organization", "Tenant overview for diagnosis: name, type, country, verified domains (default, initial, capabilities), Entra Connect sync state.", {}, async () => {
|
|
16
|
+
try {
|
|
17
|
+
const res = await ctx.graph.get("/organization", { query: { $select: ORG_FIELDS.join(",") } });
|
|
18
|
+
const org = res.data?.value?.[0];
|
|
19
|
+
if (!org)
|
|
20
|
+
return errorResult(new Error("Graph returned no organization object"));
|
|
21
|
+
const domains = (org.verifiedDomains ?? [])
|
|
22
|
+
.map((d) => `- ${d.name}${d.isDefault ? " (default)" : ""}${d.isInitial ? " (initial)" : ""} — ${or(d.type)}, ${or(d.capabilities)}`)
|
|
23
|
+
.join("\n");
|
|
24
|
+
const sync = org.onPremisesSyncEnabled ? `enabled, last sync ${or(org.onPremisesLastSyncDateTime)}` : "not enabled (cloud-only)";
|
|
25
|
+
return textResult(`# ${or(org.displayName)}\n\nTenant id: ${org.id}\nType: ${or(org.tenantType)} — country ${or(org.countryLetterCode)} — created ${or(org.createdDateTime)}\n` +
|
|
26
|
+
`Entra Connect sync: ${sync}\n\n## Verified domains\n${domains || "none"}\n\n${jsonBlock(org)}`);
|
|
27
|
+
}
|
|
28
|
+
catch (err) {
|
|
29
|
+
return errorResult(err);
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|