@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,264 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { M365Error } from "../errors.js";
|
|
3
|
+
import { odataString, resolveTeamId, resolveUser, teamParam, userParam } from "./common.js";
|
|
4
|
+
import { CHANNEL_FIELDS, memberRole } from "./teams.js";
|
|
5
|
+
import { confirmParams, rid, runWrite } from "./write-flow.js";
|
|
6
|
+
async function getTeam(ctx, team, select = "id,displayName,isArchived") {
|
|
7
|
+
const { id } = await resolveTeamId(ctx, team);
|
|
8
|
+
return (await ctx.graph.get(`/teams/${id}`, { query: { $select: select } })).data;
|
|
9
|
+
}
|
|
10
|
+
async function findMembership(ctx, teamId, userId) {
|
|
11
|
+
const res = await ctx.graph.get(`/teams/${teamId}/members`, {
|
|
12
|
+
query: { $filter: `(microsoft.graph.aadUserConversationMember/userId eq ${odataString(userId)})`, $select: "id,userId,displayName,email,roles" },
|
|
13
|
+
});
|
|
14
|
+
return (res.data?.value ?? []).find((m) => m.userId === userId);
|
|
15
|
+
}
|
|
16
|
+
const membershipState = (m) => ({ member: Boolean(m), role: m ? memberRole(m) : null });
|
|
17
|
+
async function listChannels(ctx, teamId) {
|
|
18
|
+
return (await ctx.graph.get(`/teams/${teamId}/channels`, { query: { $select: CHANNEL_FIELDS } })).data?.value ?? [];
|
|
19
|
+
}
|
|
20
|
+
/** Teams channel name rules: ≤ 50 chars, none of ~ # % & * { } + / \ : < > ? | ' " , no "..", no leading "_" or ".", no trailing ".". */
|
|
21
|
+
const CHANNEL_NAME = z
|
|
22
|
+
.string()
|
|
23
|
+
.trim()
|
|
24
|
+
.min(1)
|
|
25
|
+
.max(50)
|
|
26
|
+
.regex(/^[^~#%&*{}+/\\:<>?|'",]+$/, "characters ~ # % & * { } + / \\ : < > ? | ' \" , are not allowed by Teams")
|
|
27
|
+
.refine((n) => !n.includes("..") && !/^[_.]/.test(n) && !n.endsWith("."), 'no "..", no leading "_" or ".", no trailing "."');
|
|
28
|
+
const bool = z.boolean();
|
|
29
|
+
/** Team settings this server may change. Strict: an unlisted setting is rejected. */
|
|
30
|
+
export const TEAM_SETTINGS = z
|
|
31
|
+
.object({
|
|
32
|
+
memberSettings: z
|
|
33
|
+
.object({
|
|
34
|
+
allowCreateUpdateChannels: bool,
|
|
35
|
+
allowCreatePrivateChannels: bool,
|
|
36
|
+
allowDeleteChannels: bool,
|
|
37
|
+
allowAddRemoveApps: bool,
|
|
38
|
+
allowCreateUpdateRemoveTabs: bool,
|
|
39
|
+
allowCreateUpdateRemoveConnectors: bool,
|
|
40
|
+
})
|
|
41
|
+
.partial()
|
|
42
|
+
.strict(),
|
|
43
|
+
guestSettings: z.object({ allowCreateUpdateChannels: bool, allowDeleteChannels: bool }).partial().strict(),
|
|
44
|
+
messagingSettings: z
|
|
45
|
+
.object({
|
|
46
|
+
allowUserEditMessages: bool,
|
|
47
|
+
allowUserDeleteMessages: bool,
|
|
48
|
+
allowOwnerDeleteMessages: bool,
|
|
49
|
+
allowTeamMentions: bool,
|
|
50
|
+
allowChannelMentions: bool,
|
|
51
|
+
})
|
|
52
|
+
.partial()
|
|
53
|
+
.strict(),
|
|
54
|
+
funSettings: z
|
|
55
|
+
.object({ allowGiphy: bool, giphyContentRating: z.enum(["moderate", "strict"]), allowStickersAndMemes: bool, allowCustomMemes: bool })
|
|
56
|
+
.partial()
|
|
57
|
+
.strict(),
|
|
58
|
+
})
|
|
59
|
+
.partial()
|
|
60
|
+
.strict();
|
|
61
|
+
export function registerTeamWriteTools(server, ctx) {
|
|
62
|
+
server.tool("m365_team_member_add", "[WRITE] Add a user to a team as member (owner role is out of scope). Refuses archived teams. Idempotent. Two steps: preview then execute with the returned token.", { team: teamParam, user: userParam, ...confirmParams }, async ({ team, user, confirmToken, approvalId }) => runWrite({
|
|
63
|
+
tool: "m365_team_member_add",
|
|
64
|
+
ctx,
|
|
65
|
+
confirmToken,
|
|
66
|
+
approvalId,
|
|
67
|
+
plan: async () => {
|
|
68
|
+
const t = await getTeam(ctx, team);
|
|
69
|
+
const u = await resolveUser(ctx, user, "id,displayName,userPrincipalName,accountEnabled");
|
|
70
|
+
const m = await findMembership(ctx, t.id, u.id);
|
|
71
|
+
return {
|
|
72
|
+
targetType: "team",
|
|
73
|
+
targetId: t.id,
|
|
74
|
+
targetLabel: t.displayName ?? t.id,
|
|
75
|
+
operation: "add_team_member",
|
|
76
|
+
before: membershipState(m),
|
|
77
|
+
change: { add: { userId: u.id, userPrincipalName: u.userPrincipalName, role: "member" } },
|
|
78
|
+
refuse: t.isArchived ? "the team is archived" : u.accountEnabled === false ? "the user account is disabled" : undefined,
|
|
79
|
+
noop: m ? `${u.userPrincipalName} is already in the team (${memberRole(m)})` : undefined,
|
|
80
|
+
};
|
|
81
|
+
},
|
|
82
|
+
execute: async (plan) => {
|
|
83
|
+
const { userId } = plan.change.add;
|
|
84
|
+
try {
|
|
85
|
+
const res = await ctx.graph.request("POST", `/teams/${plan.targetId}/members`, {
|
|
86
|
+
identity: "write",
|
|
87
|
+
idempotent: true,
|
|
88
|
+
body: {
|
|
89
|
+
"@odata.type": "#microsoft.graph.aadUserConversationMember",
|
|
90
|
+
roles: [],
|
|
91
|
+
"user@odata.bind": `${ctx.graph.base.toString()}/users('${userId}')`,
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
return [rid(res)];
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
if (err instanceof M365Error && err.code === "conflict")
|
|
98
|
+
return [err.requestId ?? ""];
|
|
99
|
+
throw err;
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
after: async (plan) => membershipState(await findMembership(ctx, plan.targetId, plan.change.add.userId)),
|
|
103
|
+
}));
|
|
104
|
+
server.tool("m365_team_member_remove", "[WRITE] Remove a member or guest from a team. Owners are refused. Idempotent. Two steps: preview then execute with the returned token.", { team: teamParam, user: userParam, ...confirmParams }, async ({ team, user, confirmToken, approvalId }) => runWrite({
|
|
105
|
+
tool: "m365_team_member_remove",
|
|
106
|
+
ctx,
|
|
107
|
+
confirmToken,
|
|
108
|
+
approvalId,
|
|
109
|
+
plan: async () => {
|
|
110
|
+
const t = await getTeam(ctx, team);
|
|
111
|
+
const u = await resolveUser(ctx, user, "id,displayName,userPrincipalName");
|
|
112
|
+
const m = await findMembership(ctx, t.id, u.id);
|
|
113
|
+
return {
|
|
114
|
+
targetType: "team",
|
|
115
|
+
targetId: t.id,
|
|
116
|
+
targetLabel: t.displayName ?? t.id,
|
|
117
|
+
operation: "remove_team_member",
|
|
118
|
+
before: membershipState(m),
|
|
119
|
+
change: { remove: { userId: u.id, userPrincipalName: u.userPrincipalName, membershipId: m?.id ?? null } },
|
|
120
|
+
refuse: t.isArchived ? "the team is archived" : m && memberRole(m) === "owner" ? "the user is an owner of the team — owner changes are out of scope" : undefined,
|
|
121
|
+
noop: m ? undefined : `${u.userPrincipalName} is not in the team`,
|
|
122
|
+
};
|
|
123
|
+
},
|
|
124
|
+
execute: async (plan) => {
|
|
125
|
+
const { membershipId } = plan.change.remove;
|
|
126
|
+
try {
|
|
127
|
+
return [rid(await ctx.graph.request("DELETE", `/teams/${plan.targetId}/members/${encodeURIComponent(membershipId)}`, { identity: "write" }))];
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
if (err instanceof M365Error && err.code === "not_found")
|
|
131
|
+
return [err.requestId ?? ""];
|
|
132
|
+
throw err;
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
after: async (plan) => membershipState(await findMembership(ctx, plan.targetId, plan.change.remove.userId)),
|
|
136
|
+
}));
|
|
137
|
+
server.tool("m365_team_channel_create", "[WRITE] Create a standard channel in a team. No-op if a channel with the same name exists. Two steps: preview then execute with the returned token.", {
|
|
138
|
+
team: teamParam,
|
|
139
|
+
displayName: CHANNEL_NAME,
|
|
140
|
+
description: z.string().max(1024).optional(),
|
|
141
|
+
...confirmParams,
|
|
142
|
+
}, async ({ team, displayName, description, confirmToken, approvalId }) => runWrite({
|
|
143
|
+
tool: "m365_team_channel_create",
|
|
144
|
+
ctx,
|
|
145
|
+
confirmToken,
|
|
146
|
+
approvalId,
|
|
147
|
+
plan: async () => {
|
|
148
|
+
const t = await getTeam(ctx, team);
|
|
149
|
+
const channels = await listChannels(ctx, t.id);
|
|
150
|
+
const existing = channels.find((c) => c.displayName?.toLowerCase() === displayName.toLowerCase());
|
|
151
|
+
return {
|
|
152
|
+
targetType: "team",
|
|
153
|
+
targetId: t.id,
|
|
154
|
+
targetLabel: t.displayName ?? t.id,
|
|
155
|
+
operation: "create_channel",
|
|
156
|
+
before: { channels: channels.map((c) => c.displayName).sort() },
|
|
157
|
+
change: { displayName, ...(description !== undefined ? { description } : {}), membershipType: "standard" },
|
|
158
|
+
refuse: t.isArchived ? "the team is archived" : undefined,
|
|
159
|
+
noop: existing ? `a channel "${existing.displayName}" already exists (${existing.id})` : undefined,
|
|
160
|
+
};
|
|
161
|
+
},
|
|
162
|
+
// POST is not idempotent: not retried on 5xx (a retry could create a duplicate)
|
|
163
|
+
execute: async (plan) => [rid(await ctx.graph.request("POST", `/teams/${plan.targetId}/channels`, { identity: "write", body: plan.change }))],
|
|
164
|
+
after: async (plan) => {
|
|
165
|
+
const channels = await listChannels(ctx, plan.targetId);
|
|
166
|
+
const c = channels.find((ch) => ch.displayName?.toLowerCase() === displayName.toLowerCase());
|
|
167
|
+
return { channels: channels.map((ch) => ch.displayName).sort(), created: c ? { id: c.id, displayName: c.displayName } : null };
|
|
168
|
+
},
|
|
169
|
+
}));
|
|
170
|
+
server.tool("m365_team_channel_update", "[WRITE] Rename a channel or change its description. The General channel cannot be renamed. Two steps: preview then execute with the returned token.", {
|
|
171
|
+
team: teamParam,
|
|
172
|
+
channelId: z.string().min(1).max(256).regex(/^[\w:@.-]+$/).describe("Channel id from m365_team_channels"),
|
|
173
|
+
displayName: CHANNEL_NAME.optional(),
|
|
174
|
+
description: z.string().max(1024).optional(),
|
|
175
|
+
...confirmParams,
|
|
176
|
+
}, async ({ team, channelId, displayName, description, confirmToken, approvalId }) => runWrite({
|
|
177
|
+
tool: "m365_team_channel_update",
|
|
178
|
+
ctx,
|
|
179
|
+
confirmToken,
|
|
180
|
+
approvalId,
|
|
181
|
+
plan: async () => {
|
|
182
|
+
const t = await getTeam(ctx, team);
|
|
183
|
+
const path = `/teams/${t.id}/channels/${encodeURIComponent(channelId)}`;
|
|
184
|
+
const [c, primary] = await Promise.all([
|
|
185
|
+
ctx.graph.get(path, { query: { $select: CHANNEL_FIELDS } }).then((r) => r.data),
|
|
186
|
+
ctx.graph.get(`/teams/${t.id}/primaryChannel`, { query: { $select: "id" } }).then((r) => r.data),
|
|
187
|
+
]);
|
|
188
|
+
const before = { displayName: c.displayName ?? null, description: c.description ?? null };
|
|
189
|
+
const diff = {};
|
|
190
|
+
if (displayName !== undefined && displayName !== before.displayName)
|
|
191
|
+
diff.displayName = displayName;
|
|
192
|
+
if (description !== undefined && description !== before.description)
|
|
193
|
+
diff.description = description;
|
|
194
|
+
return {
|
|
195
|
+
targetType: "channel",
|
|
196
|
+
targetId: `${t.id}/${c.id}`,
|
|
197
|
+
targetLabel: `${t.displayName ?? t.id} › ${c.displayName ?? c.id}`,
|
|
198
|
+
operation: "update_channel",
|
|
199
|
+
before,
|
|
200
|
+
change: diff,
|
|
201
|
+
refuse: displayName === undefined && description === undefined
|
|
202
|
+
? "nothing to change"
|
|
203
|
+
: t.isArchived
|
|
204
|
+
? "the team is archived"
|
|
205
|
+
: diff.displayName && primary.id === c.id
|
|
206
|
+
? "the General channel cannot be renamed"
|
|
207
|
+
: undefined,
|
|
208
|
+
noop: Object.keys(diff).length === 0 ? "the channel already has these values" : undefined,
|
|
209
|
+
};
|
|
210
|
+
},
|
|
211
|
+
execute: async (plan) => {
|
|
212
|
+
const [teamId, ...rest] = plan.targetId.split("/");
|
|
213
|
+
return [rid(await ctx.graph.request("PATCH", `/teams/${teamId}/channels/${encodeURIComponent(rest.join("/"))}`, { identity: "write", body: plan.change }))];
|
|
214
|
+
},
|
|
215
|
+
after: async (plan) => {
|
|
216
|
+
const [teamId, ...rest] = plan.targetId.split("/");
|
|
217
|
+
const c = (await ctx.graph.get(`/teams/${teamId}/channels/${encodeURIComponent(rest.join("/"))}`, { query: { $select: CHANNEL_FIELDS } })).data;
|
|
218
|
+
return { displayName: c.displayName ?? null, description: c.description ?? null };
|
|
219
|
+
},
|
|
220
|
+
}));
|
|
221
|
+
server.tool("m365_team_settings_update", "[WRITE] Change allowlisted team settings (member, guest, messaging and fun settings). Two steps: preview then execute with the returned token.", { team: teamParam, settings: TEAM_SETTINGS.describe("Only the listed settings; unknown keys are rejected"), ...confirmParams }, async ({ team, settings, confirmToken, approvalId }) => runWrite({
|
|
222
|
+
tool: "m365_team_settings_update",
|
|
223
|
+
ctx,
|
|
224
|
+
confirmToken,
|
|
225
|
+
approvalId,
|
|
226
|
+
plan: async () => {
|
|
227
|
+
const t = await getTeam(ctx, team, "id,displayName,isArchived,memberSettings,guestSettings,messagingSettings,funSettings");
|
|
228
|
+
const before = {};
|
|
229
|
+
const diff = {};
|
|
230
|
+
for (const [section, values] of Object.entries(settings)) {
|
|
231
|
+
const current = t[section];
|
|
232
|
+
if (!current || typeof current !== "object") {
|
|
233
|
+
// without TeamSettings.Read.All Graph omits the settings: never compare against guessed nulls
|
|
234
|
+
throw new M365Error("permission_missing", `permission_missing: ${section} of the team is not readable — grant TeamSettings.Read.All to the read identity`);
|
|
235
|
+
}
|
|
236
|
+
for (const [k, v] of Object.entries(values ?? {})) {
|
|
237
|
+
(before[section] ??= {})[k] = current[k] ?? null;
|
|
238
|
+
if (current[k] !== v)
|
|
239
|
+
(diff[section] ??= {})[k] = v;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
targetType: "team",
|
|
244
|
+
targetId: t.id,
|
|
245
|
+
targetLabel: t.displayName ?? t.id,
|
|
246
|
+
operation: "update_team_settings",
|
|
247
|
+
before,
|
|
248
|
+
change: diff,
|
|
249
|
+
refuse: Object.keys(before).length === 0 ? "no setting to change" : t.isArchived ? "the team is archived" : undefined,
|
|
250
|
+
noop: Object.keys(diff).length === 0 ? "every setting already has the requested value" : undefined,
|
|
251
|
+
};
|
|
252
|
+
},
|
|
253
|
+
execute: async (plan) => [rid(await ctx.graph.request("PATCH", `/teams/${plan.targetId}`, { identity: "write", body: plan.change }))],
|
|
254
|
+
after: async (plan) => {
|
|
255
|
+
const t = await getTeam(ctx, plan.targetId, "id,memberSettings,guestSettings,messagingSettings,funSettings");
|
|
256
|
+
const out = {};
|
|
257
|
+
for (const [section, values] of Object.entries(plan.before)) {
|
|
258
|
+
for (const k of Object.keys(values))
|
|
259
|
+
(out[section] ??= {})[k] = t[section]?.[k] ?? null;
|
|
260
|
+
}
|
|
261
|
+
return out;
|
|
262
|
+
},
|
|
263
|
+
}));
|
|
264
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { cursorParam, errorResult, formatParam, jsonBlock, limitParam, listPage, odataString, or, renderList, resolveTeamId, searchText, teamParam, textResult, } from "./common.js";
|
|
3
|
+
export const TEAM_FIELDS = "id,displayName,description,visibility,isArchived,classification,specialization,createdDateTime,webUrl,memberSettings,guestSettings,messagingSettings,funSettings";
|
|
4
|
+
export const CHANNEL_FIELDS = "id,displayName,description,membershipType,createdDateTime";
|
|
5
|
+
export const memberRole = (m) => (m.roles?.includes("owner") ? "owner" : m.roles?.includes("guest") ? "guest" : "member");
|
|
6
|
+
export function registerTeamTools(server, ctx) {
|
|
7
|
+
server.tool("m365_teams", "List Microsoft Teams teams of the tenant (paginated, bounded).", {
|
|
8
|
+
search: searchText("Prefix of the team displayName").optional(),
|
|
9
|
+
limit: limitParam,
|
|
10
|
+
cursor: cursorParam,
|
|
11
|
+
format: formatParam,
|
|
12
|
+
}, async ({ search, limit, cursor, format }) => {
|
|
13
|
+
try {
|
|
14
|
+
const page = await listPage(ctx, "m365_teams", { path: "/teams", query: { $select: "id,displayName,description,visibility", $filter: search ? `startswith(displayName,${odataString(search)})` : undefined } }, limit, cursor);
|
|
15
|
+
return textResult(renderList("Teams", page, format, (t) => `${or(t.displayName)} (${t.id}) — ${or(t.visibility)}${t.description ? ` — ${t.description.slice(0, 80)}` : ""}`));
|
|
16
|
+
}
|
|
17
|
+
catch (err) {
|
|
18
|
+
return errorResult(err);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
server.tool("m365_team_info", "One team: visibility, archive state, and its member / guest / messaging / fun settings.", { team: teamParam }, async ({ team }) => {
|
|
22
|
+
try {
|
|
23
|
+
const { id } = await resolveTeamId(ctx, team);
|
|
24
|
+
const t = (await ctx.graph.get(`/teams/${id}`, { query: { $select: TEAM_FIELDS } })).data;
|
|
25
|
+
return textResult(`# ${or(t.displayName)} (${t.id})\n\nVisibility: ${or(t.visibility)} — ${t.isArchived ? "ARCHIVED" : "active"}\n\n${jsonBlock(t)}`);
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
return errorResult(err);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
server.tool("m365_team_channels", "Channels of a team: standard, private and shared, with their ids (needed by m365_team_channel_update).", {
|
|
32
|
+
team: teamParam,
|
|
33
|
+
membershipType: z.enum(["standard", "private", "shared"]).optional(),
|
|
34
|
+
limit: limitParam,
|
|
35
|
+
cursor: cursorParam,
|
|
36
|
+
format: formatParam,
|
|
37
|
+
}, async ({ team, membershipType, limit, cursor, format }) => {
|
|
38
|
+
try {
|
|
39
|
+
const { id } = await resolveTeamId(ctx, team);
|
|
40
|
+
const page = await listPage(ctx, `m365_team_channels:${id}`, {
|
|
41
|
+
path: `/teams/${id}/channels`,
|
|
42
|
+
query: { $select: CHANNEL_FIELDS, $filter: membershipType ? `membershipType eq ${odataString(membershipType)}` : undefined },
|
|
43
|
+
supportsTop: false,
|
|
44
|
+
}, limit, cursor);
|
|
45
|
+
return textResult(renderList(`Channels of team ${id}`, page, format, (c) => `${or(c.displayName)} (${c.id}) — ${or(c.membershipType)}${c.description ? ` — ${c.description.slice(0, 80)}` : ""}`));
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
return errorResult(err);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
server.tool("m365_team_members", "Members of a team with their role (owner, member, guest) and membership id.", {
|
|
52
|
+
team: teamParam,
|
|
53
|
+
role: z.enum(["owner", "guest"]).optional().describe("Only owners, or only guests"),
|
|
54
|
+
limit: limitParam,
|
|
55
|
+
cursor: cursorParam,
|
|
56
|
+
format: formatParam,
|
|
57
|
+
}, async ({ team, role, limit, cursor, format }) => {
|
|
58
|
+
try {
|
|
59
|
+
const { id } = await resolveTeamId(ctx, team);
|
|
60
|
+
const page = await listPage(ctx, `m365_team_members:${id}`, {
|
|
61
|
+
path: `/teams/${id}/members`,
|
|
62
|
+
query: { $select: "id,userId,displayName,email,roles", $filter: role ? `roles/any(r:r eq ${odataString(role)})` : undefined },
|
|
63
|
+
supportsTop: false,
|
|
64
|
+
}, limit, cursor);
|
|
65
|
+
return textResult(renderList(`Members of team ${id}`, page, format, (m) => `${or(m.displayName)} <${or(m.email)}> — ${memberRole(m)} — userId ${or(m.userId)} — membershipId ${m.id}`));
|
|
66
|
+
}
|
|
67
|
+
catch (err) {
|
|
68
|
+
return errorResult(err);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { resolveUser, userParam } from "./common.js";
|
|
3
|
+
import { confirmParams, rid, runWrite } from "./write-flow.js";
|
|
4
|
+
/**
|
|
5
|
+
* Attributes m365_user_update may change. Identity (UPN, mail, proxy addresses), credentials,
|
|
6
|
+
* account state (own tool), on-premises attributes and anything role-related are not here:
|
|
7
|
+
* the schema is strict, so an unlisted key is rejected, not ignored.
|
|
8
|
+
*/
|
|
9
|
+
const text = (max) => z.string().trim().min(1).max(max);
|
|
10
|
+
export const UPDATABLE_USER_ATTRIBUTES = z
|
|
11
|
+
.object({
|
|
12
|
+
displayName: text(256),
|
|
13
|
+
givenName: text(64),
|
|
14
|
+
surname: text(64),
|
|
15
|
+
jobTitle: text(128),
|
|
16
|
+
department: text(64),
|
|
17
|
+
officeLocation: text(128),
|
|
18
|
+
companyName: text(64),
|
|
19
|
+
city: text(128),
|
|
20
|
+
country: text(128),
|
|
21
|
+
usageLocation: z.string().regex(/^[A-Z]{2}$/, "two-letter ISO 3166 country code, upper case").describe("Required before assigning licences"),
|
|
22
|
+
preferredLanguage: z.string().regex(/^[a-z]{2,3}(-[A-Z]{2})?$/, "ISO 639-1 language, e.g. fr-FR"),
|
|
23
|
+
})
|
|
24
|
+
.partial()
|
|
25
|
+
.strict();
|
|
26
|
+
export const UPDATABLE_KEYS = Object.keys(UPDATABLE_USER_ATTRIBUTES.shape);
|
|
27
|
+
export function registerUserWriteTools(server, ctx) {
|
|
28
|
+
server.tool("m365_user_update", `[WRITE] Update allowlisted attributes of a user (${UPDATABLE_KEYS.join(", ")}). Two steps: preview (no confirmToken) then execute with the returned token.`, {
|
|
29
|
+
user: userParam,
|
|
30
|
+
changes: UPDATABLE_USER_ATTRIBUTES.describe(`Attributes to set — only: ${UPDATABLE_KEYS.join(", ")}`),
|
|
31
|
+
...confirmParams,
|
|
32
|
+
}, async ({ user, changes, confirmToken, approvalId }) => runWrite({
|
|
33
|
+
tool: "m365_user_update",
|
|
34
|
+
ctx,
|
|
35
|
+
confirmToken,
|
|
36
|
+
approvalId,
|
|
37
|
+
plan: async () => {
|
|
38
|
+
const keys = Object.keys(changes);
|
|
39
|
+
const u = await resolveUser(ctx, user, ["id", "displayName", "userPrincipalName", ...UPDATABLE_KEYS].join(","));
|
|
40
|
+
const before = Object.fromEntries(UPDATABLE_KEYS.map((k) => [k, u[k] ?? null]));
|
|
41
|
+
const diff = Object.fromEntries(Object.entries(changes).filter(([k, v]) => before[k] !== v));
|
|
42
|
+
return {
|
|
43
|
+
targetType: "user",
|
|
44
|
+
targetId: u.id,
|
|
45
|
+
targetLabel: `${u.displayName ?? ""} <${u.userPrincipalName ?? ""}>`,
|
|
46
|
+
operation: "update_attributes",
|
|
47
|
+
before,
|
|
48
|
+
change: diff,
|
|
49
|
+
refuse: keys.length === 0 ? "no attribute to change" : undefined,
|
|
50
|
+
noop: keys.length && Object.keys(diff).length === 0 ? "every attribute already has the requested value" : undefined,
|
|
51
|
+
};
|
|
52
|
+
},
|
|
53
|
+
execute: async (plan) => [rid(await ctx.graph.request("PATCH", `/users/${plan.targetId}`, { body: plan.change, identity: "write" }))],
|
|
54
|
+
after: async (plan) => {
|
|
55
|
+
const u = await resolveUser(ctx, plan.targetId, ["id", "userPrincipalName", "displayName", ...UPDATABLE_KEYS].join(","));
|
|
56
|
+
return Object.fromEntries(UPDATABLE_KEYS.map((k) => [k, u[k] ?? null]));
|
|
57
|
+
},
|
|
58
|
+
}));
|
|
59
|
+
server.tool("m365_user_set_account_enabled", "[WRITE] Enable or disable a user account (sign-in blocked when disabled; nothing is deleted). Two steps: preview then execute with the returned token.", { user: userParam, enabled: z.boolean().describe("true = enable sign-in, false = block sign-in"), ...confirmParams }, async ({ user, enabled, confirmToken, approvalId }) => runWrite({
|
|
60
|
+
tool: "m365_user_set_account_enabled",
|
|
61
|
+
ctx,
|
|
62
|
+
confirmToken,
|
|
63
|
+
approvalId,
|
|
64
|
+
plan: async () => {
|
|
65
|
+
const u = await resolveUser(ctx, user, "id,displayName,userPrincipalName,accountEnabled,userType");
|
|
66
|
+
return {
|
|
67
|
+
targetType: "user",
|
|
68
|
+
targetId: u.id,
|
|
69
|
+
targetLabel: `${u.displayName ?? ""} <${u.userPrincipalName ?? ""}>`,
|
|
70
|
+
operation: enabled ? "enable_account" : "disable_account",
|
|
71
|
+
before: { accountEnabled: u.accountEnabled ?? null },
|
|
72
|
+
change: { accountEnabled: enabled },
|
|
73
|
+
noop: u.accountEnabled === enabled ? `the account is already ${enabled ? "enabled" : "disabled"}` : undefined,
|
|
74
|
+
};
|
|
75
|
+
},
|
|
76
|
+
execute: async (plan) => [rid(await ctx.graph.request("PATCH", `/users/${plan.targetId}`, { body: { accountEnabled: enabled }, identity: "write" }))],
|
|
77
|
+
after: async (plan) => {
|
|
78
|
+
const u = await resolveUser(ctx, plan.targetId, "id,accountEnabled");
|
|
79
|
+
return { accountEnabled: u.accountEnabled ?? null };
|
|
80
|
+
},
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { GUID_RE } from "../config.js";
|
|
3
|
+
import { M365Error } from "../errors.js";
|
|
4
|
+
import { cursorParam, errorResult, fieldsParam, formatParam, jsonBlock, limitParam, listPage, odataString, or, renderList, resolveUser, searchText, selectFields, textResult, userParam, } from "./common.js";
|
|
5
|
+
/**
|
|
6
|
+
* User attributes this server may return. Credentials, authentication methods, sign-in activity,
|
|
7
|
+
* personal phone numbers, alternate e-mails and on-premises identifiers are deliberately absent.
|
|
8
|
+
*/
|
|
9
|
+
export const USER_FIELDS = [
|
|
10
|
+
"id",
|
|
11
|
+
"displayName",
|
|
12
|
+
"userPrincipalName",
|
|
13
|
+
"mail",
|
|
14
|
+
"accountEnabled",
|
|
15
|
+
"userType",
|
|
16
|
+
"givenName",
|
|
17
|
+
"surname",
|
|
18
|
+
"jobTitle",
|
|
19
|
+
"department",
|
|
20
|
+
"officeLocation",
|
|
21
|
+
"companyName",
|
|
22
|
+
"city",
|
|
23
|
+
"country",
|
|
24
|
+
"usageLocation",
|
|
25
|
+
"preferredLanguage",
|
|
26
|
+
"createdDateTime",
|
|
27
|
+
"onPremisesSyncEnabled",
|
|
28
|
+
"assignedLicenses",
|
|
29
|
+
];
|
|
30
|
+
const USER_DEFAULT = ["id", "displayName", "userPrincipalName", "mail", "accountEnabled", "userType", "jobTitle", "department", "usageLocation", "assignedLicenses"];
|
|
31
|
+
const ADVANCED = { ConsistencyLevel: "eventual" };
|
|
32
|
+
async function licenceNames(ctx, users) {
|
|
33
|
+
const ids = new Set(users.flatMap((u) => (u.assignedLicenses ?? []).map((l) => l.skuId)));
|
|
34
|
+
const out = new Map();
|
|
35
|
+
for (const id of ids)
|
|
36
|
+
out.set(id, await ctx.skus.name(id));
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
export function userLine(u, names) {
|
|
40
|
+
const lic = u.assignedLicenses ? ` — licences: ${u.assignedLicenses.map((l) => names?.get(l.skuId) ?? l.skuId).join(", ") || "none"}` : "";
|
|
41
|
+
const state = u.accountEnabled === undefined ? "" : u.accountEnabled ? " — enabled" : " — DISABLED";
|
|
42
|
+
const role = [u.jobTitle, u.department].filter(Boolean).join(", ");
|
|
43
|
+
return `${or(u.displayName)} <${or(u.userPrincipalName)}> (${u.id})${state}${u.userType ? ` — ${u.userType}` : ""}${role ? ` — ${role}` : ""}${lic}`;
|
|
44
|
+
}
|
|
45
|
+
export function registerUserTools(server, ctx) {
|
|
46
|
+
server.tool("m365_users", "List Entra ID users (paginated, bounded). Filters are structured — no free-form OData. Returns account state, type and licences.", {
|
|
47
|
+
search: searchText("Prefix matched against displayName, userPrincipalName and mail").optional(),
|
|
48
|
+
accountEnabled: z.boolean().optional().describe("true = enabled accounts only, false = disabled only"),
|
|
49
|
+
userType: z.enum(["Member", "Guest"]).optional(),
|
|
50
|
+
department: searchText("Exact department").optional(),
|
|
51
|
+
licensed: z.boolean().optional().describe("true = with at least one licence, false = without any"),
|
|
52
|
+
skuId: z.string().regex(GUID_RE).optional().describe("Only users holding this licence (skuId from m365_subscribed_skus)"),
|
|
53
|
+
fields: fieldsParam(USER_FIELDS),
|
|
54
|
+
limit: limitParam,
|
|
55
|
+
cursor: cursorParam,
|
|
56
|
+
format: formatParam,
|
|
57
|
+
}, async ({ search, accountEnabled, userType, department, licensed, skuId, fields, limit, cursor, format }) => {
|
|
58
|
+
try {
|
|
59
|
+
const filters = [];
|
|
60
|
+
if (search) {
|
|
61
|
+
const q = odataString(search);
|
|
62
|
+
filters.push(`(startswith(displayName,${q}) or startswith(userPrincipalName,${q}) or startswith(mail,${q}))`);
|
|
63
|
+
}
|
|
64
|
+
if (accountEnabled !== undefined)
|
|
65
|
+
filters.push(`accountEnabled eq ${accountEnabled}`);
|
|
66
|
+
if (userType)
|
|
67
|
+
filters.push(`userType eq ${odataString(userType)}`);
|
|
68
|
+
if (department)
|
|
69
|
+
filters.push(`department eq ${odataString(department)}`);
|
|
70
|
+
if (licensed !== undefined)
|
|
71
|
+
filters.push(`assignedLicenses/$count ${licensed ? "ne" : "eq"} 0`);
|
|
72
|
+
if (skuId)
|
|
73
|
+
filters.push(`assignedLicenses/any(x:x/skuId eq ${skuId.toLowerCase()})`);
|
|
74
|
+
const page = await listPage(ctx, "m365_users", {
|
|
75
|
+
path: "/users",
|
|
76
|
+
query: { $select: selectFields(USER_FIELDS, USER_DEFAULT, fields), $filter: filters.join(" and ") || undefined, $count: "true" },
|
|
77
|
+
headers: ADVANCED,
|
|
78
|
+
}, limit, cursor);
|
|
79
|
+
const names = await licenceNames(ctx, page.items);
|
|
80
|
+
return textResult(renderList("Users", page, format, (u) => userLine(u, names)));
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
return errorResult(err);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
server.tool("m365_user_info", "One user in detail: allowlisted attributes, account state, licences with their names and how each is assigned (direct or inherited from a group).", { user: userParam }, async ({ user }) => {
|
|
87
|
+
try {
|
|
88
|
+
const u = await resolveUser(ctx, user, [...USER_FIELDS, "licenseAssignmentStates"].join(","));
|
|
89
|
+
const states = u.licenseAssignmentStates ?? [];
|
|
90
|
+
const lic = await Promise.all(states.map(async (s) => `- ${await ctx.skus.name(s.skuId)} — ${s.assignedByGroup ? `inherited from group ${s.assignedByGroup}` : "direct"} — ${or(s.state)}${s.error && s.error !== "None" ? ` (error: ${s.error})` : ""}`));
|
|
91
|
+
const { licenseAssignmentStates: _drop, ...attrs } = u;
|
|
92
|
+
return textResult(`# ${userLine(u)}\n\n## Licences\n${lic.join("\n") || "none"}\n\n${jsonBlock(attrs)}`);
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
return errorResult(err);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/** Sign-in logs — registered only when M365_ENABLE_SIGNIN_AUDIT=true. */
|
|
100
|
+
export function registerSignInTools(server, ctx) {
|
|
101
|
+
const SIGNIN_FIELDS = "id,createdDateTime,userPrincipalName,userId,appDisplayName,ipAddress,clientAppUsed,isInteractive,conditionalAccessStatus,riskLevelDuringSignIn,status,location";
|
|
102
|
+
server.tool("m365_audit_signins", "Entra ID sign-in logs (paginated, at most 30 days back). Needs AuditLog.Read.All and an Entra ID P1/P2 tenant — otherwise answers unsupported_by_tenant, never an empty list.", {
|
|
103
|
+
user: z.string().max(256).optional().describe("userPrincipalName (exact) or user id"),
|
|
104
|
+
sinceHours: z.number().int().min(1).max(720).default(24).describe("How far back, in hours (default 24, max 720 = 30 days)"),
|
|
105
|
+
status: z.enum(["success", "failure"]).optional(),
|
|
106
|
+
limit: limitParam,
|
|
107
|
+
cursor: cursorParam,
|
|
108
|
+
format: formatParam,
|
|
109
|
+
}, async ({ user, sinceHours, status, limit, cursor, format }) => {
|
|
110
|
+
try {
|
|
111
|
+
const since = new Date(Date.now() - sinceHours * 3600_000).toISOString();
|
|
112
|
+
const filters = [`createdDateTime ge ${since}`];
|
|
113
|
+
if (user)
|
|
114
|
+
filters.push(GUID_RE.test(user) ? `userId eq ${odataString(user)}` : `userPrincipalName eq ${odataString(user.toLowerCase())}`);
|
|
115
|
+
if (status)
|
|
116
|
+
filters.push(`status/errorCode ${status === "success" ? "eq" : "ne"} 0`);
|
|
117
|
+
const page = await listPage(ctx, "m365_audit_signins", { path: "/auditLogs/signIns", query: { $select: SIGNIN_FIELDS, $filter: filters.join(" and ") } }, limit, cursor);
|
|
118
|
+
return textResult(renderList(`Sign-ins (last ${sinceHours} h)`, page, format, (s) => {
|
|
119
|
+
const st = s.status?.errorCode === 0 ? "success" : `FAILURE ${s.status?.errorCode ?? "?"}${s.status?.failureReason ? ` (${s.status.failureReason})` : ""}`;
|
|
120
|
+
const loc = [s.location?.city, s.location?.countryOrRegion].filter(Boolean).join(", ");
|
|
121
|
+
return `${or(s.createdDateTime)} — ${or(s.userPrincipalName)} → ${or(s.appDisplayName)} — ${st} — ${or(s.ipAddress)}${loc ? ` (${loc})` : ""} — CA: ${or(s.conditionalAccessStatus)}`;
|
|
122
|
+
}));
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
if (err instanceof M365Error && err.code === "permission_missing" && /premium|license/i.test(err.message)) {
|
|
126
|
+
return errorResult(new M365Error("unsupported_by_tenant", `unsupported_by_tenant: sign-in logs need Entra ID P1/P2 — ${err.message}`, {
|
|
127
|
+
status: err.status,
|
|
128
|
+
graphCode: err.graphCode,
|
|
129
|
+
requestId: err.requestId,
|
|
130
|
+
clientRequestId: err.clientRequestId,
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
return errorResult(err);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { errorResult, M365Error, toM365Error } from "../errors.js";
|
|
3
|
+
import { jsonBlock, textResult } from "./common.js";
|
|
4
|
+
/** Params shared by every write tool. */
|
|
5
|
+
export const confirmParams = {
|
|
6
|
+
confirmToken: z
|
|
7
|
+
.string()
|
|
8
|
+
.max(200)
|
|
9
|
+
.optional()
|
|
10
|
+
.describe("Omit for the preview (nothing is changed: the target is resolved, the planned change computed and a confirmToken returned). " +
|
|
11
|
+
"Then call again with the SAME arguments and this token to execute. Refused if the target or its state changed in between."),
|
|
12
|
+
approvalId: z
|
|
13
|
+
.string()
|
|
14
|
+
.regex(/^[\w.:-]{1,128}$/)
|
|
15
|
+
.optional()
|
|
16
|
+
.describe("Pulse Chat approval id, recorded in the audit trail for correlation (not an authorisation)."),
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* The single path every write goes through:
|
|
20
|
+
* kill switch → plan (resolve target, refuse ambiguity, guards) → preview + token, or
|
|
21
|
+
* verify token against the *current* state → no-op or execute → re-read → audit.
|
|
22
|
+
*/
|
|
23
|
+
export async function runWrite(spec) {
|
|
24
|
+
const { ctx, tool, approvalId } = spec;
|
|
25
|
+
let plan;
|
|
26
|
+
const requestIds = [];
|
|
27
|
+
try {
|
|
28
|
+
if (ctx.killSwitchActive()) {
|
|
29
|
+
throw new M365Error("refused", `refused: writes are disabled by the kill switch (${ctx.config.killSwitchFile} exists)`);
|
|
30
|
+
}
|
|
31
|
+
plan = await spec.plan();
|
|
32
|
+
const binding = { tool, targetId: plan.targetId, state: plan.before, plan: plan.change };
|
|
33
|
+
const head = `Target: ${plan.targetType} ${plan.targetLabel} (${plan.targetId})\nOperation: ${plan.operation}`;
|
|
34
|
+
if (plan.refuse) {
|
|
35
|
+
ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "refused", errorCode: "refused", approvalId });
|
|
36
|
+
return errorResult(new M365Error("refused", `refused: ${plan.refuse}`));
|
|
37
|
+
}
|
|
38
|
+
if (!spec.confirmToken) {
|
|
39
|
+
ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "preview", approvalId });
|
|
40
|
+
if (plan.noop) {
|
|
41
|
+
return textResult(`# Preview — ${tool}\n\n${head}\n\nNothing to do: ${plan.noop}\n\nCurrent state:\n${jsonBlock(plan.before)}`);
|
|
42
|
+
}
|
|
43
|
+
const { token, expiresAt } = ctx.confirmations.issue(binding);
|
|
44
|
+
return textResult(`# Preview — ${tool} (nothing changed yet)\n\n${head}\n\nCurrent state:\n${jsonBlock(plan.before)}\n\nPlanned change:\n${jsonBlock(plan.change)}\n\n` +
|
|
45
|
+
`To execute: call ${tool} again with the same arguments and confirmToken: "${token}" (valid until ${expiresAt}, single use).`);
|
|
46
|
+
}
|
|
47
|
+
ctx.confirmations.verify(spec.confirmToken, binding);
|
|
48
|
+
// re-checked after the confirmation (the switch may have been set since the preview); the Graph
|
|
49
|
+
// client checks it once more right before each mutating request
|
|
50
|
+
if (ctx.killSwitchActive()) {
|
|
51
|
+
throw new M365Error("refused", `refused: writes are disabled by the kill switch (${ctx.config.killSwitchFile} exists)`);
|
|
52
|
+
}
|
|
53
|
+
if (plan.noop) {
|
|
54
|
+
ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "noop", approvalId });
|
|
55
|
+
return textResult(`# ${tool} — nothing to do\n\n${head}\n\n${plan.noop}\n\nState:\n${jsonBlock(plan.before)}`);
|
|
56
|
+
}
|
|
57
|
+
requestIds.push(...(await spec.execute(plan)));
|
|
58
|
+
let afterText;
|
|
59
|
+
try {
|
|
60
|
+
afterText = jsonBlock(await spec.after(plan));
|
|
61
|
+
}
|
|
62
|
+
catch (err) {
|
|
63
|
+
afterText = `(could not re-read the target: ${toM365Error(err).code} — the change itself succeeded)`;
|
|
64
|
+
}
|
|
65
|
+
ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "success", graphRequestIds: requestIds, approvalId });
|
|
66
|
+
return textResult(`# ${tool} — done\n\n${head}\n\nBefore:\n${jsonBlock(plan.before)}\n\nAfter:\n${afterText}\n\nGraph request-id: ${requestIds.filter(Boolean).join(", ") || "—"}`);
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
const e = toM365Error(err);
|
|
70
|
+
if (e.requestId)
|
|
71
|
+
requestIds.push(e.requestId);
|
|
72
|
+
const result = e.code === "refused" || e.code === "confirmation_invalid" || e.code === "ambiguous_target" ? "refused" : "failed";
|
|
73
|
+
ctx.audit.log({
|
|
74
|
+
tool,
|
|
75
|
+
targetType: plan?.targetType ?? "unknown",
|
|
76
|
+
targetId: plan?.targetId,
|
|
77
|
+
operation: plan?.operation ?? tool,
|
|
78
|
+
result,
|
|
79
|
+
errorCode: e.code,
|
|
80
|
+
graphRequestIds: requestIds,
|
|
81
|
+
approvalId,
|
|
82
|
+
});
|
|
83
|
+
return errorResult(e);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** Request id of a Graph result, for `execute` to return. */
|
|
87
|
+
export const rid = (r) => r.requestId ?? "";
|