@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.
- package/LICENSE +21 -0
- package/README.md +279 -37
- package/dist/audit.js +11 -1
- package/dist/auth/token-provider.js +79 -3
- package/dist/config.js +77 -7
- package/dist/confirm.js +1 -1
- package/dist/context.js +48 -2
- package/dist/errors.js +1 -1
- package/dist/external/activity.js +253 -0
- package/dist/external/client.js +140 -0
- package/dist/external/exchange.js +104 -0
- package/dist/external/sharepoint.js +79 -0
- package/dist/graph-client.js +108 -4
- package/dist/index.js +1 -1
- package/dist/permissions.js +189 -1
- package/dist/register.js +23 -1
- package/dist/reports.js +138 -0
- package/dist/review/collect.js +238 -0
- package/dist/review/model.js +152 -0
- package/dist/tools/access-review.js +98 -0
- package/dist/tools/applications.js +101 -0
- package/dist/tools/capabilities.js +53 -11
- package/dist/tools/common.js +77 -1
- package/dist/tools/devices.js +40 -0
- package/dist/tools/entra-applications-write.js +193 -0
- package/dist/tools/entra-applications.js +239 -0
- package/dist/tools/phase2.js +235 -0
- package/dist/tools/reports.js +151 -0
- package/dist/tools/security.js +275 -0
- package/dist/tools/sites.js +231 -0
- package/dist/tools/teams-write.js +2 -1
- package/dist/tools/teams.js +39 -1
- package/dist/tools/write-flow.js +25 -6
- package/package.json +10 -6
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { M365Error } from "../errors.js";
|
|
3
|
+
import { applicationParam, assertOwned, assertServicePrincipalOwned, resolveApplication, resolveServicePrincipal, safeApplication, safeServicePrincipal, } from "./entra-applications.js";
|
|
4
|
+
import { confirmParams, rid, runWrite } from "./write-flow.js";
|
|
5
|
+
const appChangesSchema = z.object({
|
|
6
|
+
displayName: z.string().min(1).max(120).optional(),
|
|
7
|
+
description: z.string().max(1024).nullable().optional(),
|
|
8
|
+
notes: z.string().max(1024).nullable().optional(),
|
|
9
|
+
tags: z.array(z.string().min(1).max(128)).max(20).optional(),
|
|
10
|
+
}).strict().refine((value) => Object.keys(value).length > 0, "at least one allowlisted property is required");
|
|
11
|
+
const spChangesSchema = z.object({
|
|
12
|
+
displayName: z.string().min(1).max(120).optional(),
|
|
13
|
+
description: z.string().max(1024).nullable().optional(),
|
|
14
|
+
accountEnabled: z.boolean().optional(),
|
|
15
|
+
notificationEmailAddresses: z.array(z.string().email()).max(10).optional(),
|
|
16
|
+
preferredSingleSignOnMode: z.enum(["password", "saml", "notSupported", "oidc"]).nullable().optional(),
|
|
17
|
+
tags: z.array(z.string().min(1).max(128)).max(20).optional(),
|
|
18
|
+
}).strict().refine((value) => Object.keys(value).length > 0, "at least one allowlisted property is required");
|
|
19
|
+
const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
|
|
20
|
+
const fields = (record, keys) => Object.fromEntries(keys.map((key) => [key, record[key] ?? null]));
|
|
21
|
+
const delta = (record, changes) => Object.fromEntries(Object.entries(changes).filter(([key, value]) => !same(record[key] ?? null, value)));
|
|
22
|
+
const matches = (record, changes) => Object.entries(changes).every(([key, value]) => same(record[key] ?? null, value));
|
|
23
|
+
const alternate = (kind, key, value) => `/${kind}(${key}='${value}')`;
|
|
24
|
+
async function optionalGet(read) {
|
|
25
|
+
try {
|
|
26
|
+
return (await read()).data;
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error instanceof M365Error && error.code === "not_found")
|
|
30
|
+
return undefined;
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
async function ownedApplication(ctx, input, select = "id,appId,displayName") {
|
|
35
|
+
const app = await resolveApplication(ctx, input, select);
|
|
36
|
+
await assertOwned(ctx, app);
|
|
37
|
+
return app;
|
|
38
|
+
}
|
|
39
|
+
async function boundedAfter(ctx, read, ready) {
|
|
40
|
+
let last = new M365Error("transient", "transient: post-write verification did not observe the requested state");
|
|
41
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
42
|
+
try {
|
|
43
|
+
const value = await read();
|
|
44
|
+
if (ready(value))
|
|
45
|
+
return value;
|
|
46
|
+
last = new M365Error("transient", "transient: Graph returned stale state during bounded post-write verification");
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (!(error instanceof M365Error) || !["not_found", "transient", "refused"].includes(error.code))
|
|
50
|
+
throw error;
|
|
51
|
+
last = error.code === "refused" ? new M365Error("transient", "transient: post-write ownership verification failed") : error;
|
|
52
|
+
}
|
|
53
|
+
if (attempt < 2)
|
|
54
|
+
await ctx.sleep(250 * (attempt + 1));
|
|
55
|
+
}
|
|
56
|
+
throw last;
|
|
57
|
+
}
|
|
58
|
+
export function registerEntraApplicationWriteTools(server, ctx) {
|
|
59
|
+
server.tool("m365_entra_application_create", "[WRITE] Idempotently upsert a single-tenant Entra application by uniqueName. Ownership is verified. No requested permissions or credentials are written.", {
|
|
60
|
+
uniqueName: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$/, "uniqueName must be URL-safe"),
|
|
61
|
+
displayName: z.string().min(1).max(120),
|
|
62
|
+
signInAudience: z.literal("AzureADMyOrg").default("AzureADMyOrg"),
|
|
63
|
+
description: z.string().max(1024).optional(),
|
|
64
|
+
...confirmParams,
|
|
65
|
+
}, async ({ uniqueName, displayName, signInAudience, description, confirmToken, approvalId }) => {
|
|
66
|
+
const body = { displayName, signInAudience, ...(description === undefined ? {} : { description }) };
|
|
67
|
+
const path = alternate("applications", "uniqueName", uniqueName);
|
|
68
|
+
return runWrite({
|
|
69
|
+
tool: "m365_entra_application_create", ctx, identity: "entra", confirmToken, approvalId, verificationRequired: true,
|
|
70
|
+
plan: async () => {
|
|
71
|
+
const existing = await optionalGet(() => ctx.graph.get(path, { identity: "entra", query: { $select: "id,appId,uniqueName,displayName,signInAudience,description" } }));
|
|
72
|
+
if (existing)
|
|
73
|
+
await assertOwned(ctx, existing);
|
|
74
|
+
const change = existing ? delta(existing, body) : body;
|
|
75
|
+
return {
|
|
76
|
+
targetType: "application", targetId: uniqueName, targetLabel: displayName, operation: "upsert_application",
|
|
77
|
+
before: existing ? { exists: true, state: fields(existing, Object.keys(body)) } : { exists: false },
|
|
78
|
+
change,
|
|
79
|
+
...(existing && Object.keys(change).length === 0 ? { noop: "application already matches" } : {}),
|
|
80
|
+
};
|
|
81
|
+
},
|
|
82
|
+
execute: async (plan) => {
|
|
83
|
+
const current = await optionalGet(() => ctx.graph.get(path, { identity: "entra", query: { $select: "id,appId,uniqueName,displayName,signInAudience,description" } }));
|
|
84
|
+
const before = plan.before;
|
|
85
|
+
if (before.exists !== Boolean(current) || (current && !same(fields(current, Object.keys(body)), before.state)))
|
|
86
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: application state changed after confirmation");
|
|
87
|
+
if (current)
|
|
88
|
+
await assertOwned(ctx, current);
|
|
89
|
+
return [rid(await ctx.graph.request("PATCH", path, { identity: "entra", headers: { Prefer: "create-if-missing" }, body: plan.change }))];
|
|
90
|
+
},
|
|
91
|
+
after: async () => safeApplication(await boundedAfter(ctx, async () => {
|
|
92
|
+
const app = (await ctx.graph.get(path, { identity: "entra", query: { $select: "id,appId,uniqueName,displayName,signInAudience,description" } })).data;
|
|
93
|
+
await assertOwned(ctx, app);
|
|
94
|
+
return app;
|
|
95
|
+
}, (app) => matches(app, body))),
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
server.tool("m365_entra_application_update", "[WRITE] Update allowlisted application scalar properties. Requested permissions and credentials are read-only in v1.", { application: applicationParam, changes: appChangesSchema, ...confirmParams }, async ({ application, changes, confirmToken, approvalId }) => runWrite({
|
|
99
|
+
tool: "m365_entra_application_update", ctx, identity: "entra", confirmToken, approvalId, verificationRequired: true,
|
|
100
|
+
plan: async () => {
|
|
101
|
+
const keys = Object.keys(changes);
|
|
102
|
+
const app = await ownedApplication(ctx, application, `id,appId,displayName,${keys.join(",")}`);
|
|
103
|
+
const change = delta(app, changes);
|
|
104
|
+
return { targetType: "application", targetId: app.id, targetLabel: app.displayName ?? app.id, operation: "update_application", before: { fields: fields(app, keys) }, change, ...(Object.keys(change).length ? {} : { noop: "all requested application properties already match" }) };
|
|
105
|
+
},
|
|
106
|
+
execute: async (plan) => {
|
|
107
|
+
const keys = Object.keys(changes);
|
|
108
|
+
const app = await resolveApplication(ctx, plan.targetId, `id,appId,displayName,${keys.join(",")}`);
|
|
109
|
+
await assertOwned(ctx, app);
|
|
110
|
+
if (!same(fields(app, keys), plan.before.fields))
|
|
111
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: targeted application fields changed after confirmation");
|
|
112
|
+
return [rid(await ctx.graph.request("PATCH", `/applications/${plan.targetId}`, { identity: "entra", body: plan.change }))];
|
|
113
|
+
},
|
|
114
|
+
after: async (plan) => safeApplication(await boundedAfter(ctx, () => resolveApplication(ctx, plan.targetId, `id,appId,displayName,${Object.keys(changes).join(",")}`), (app) => matches(app, plan.change))),
|
|
115
|
+
}));
|
|
116
|
+
server.tool("m365_entra_service_principal_create", "[WRITE] Idempotently upsert a service principal by appId for an owned application. The service principal itself must be owned after creation.", { application: applicationParam, accountEnabled: z.boolean().default(true), ...confirmParams }, async ({ application, accountEnabled, confirmToken, approvalId }) => runWrite({
|
|
117
|
+
tool: "m365_entra_service_principal_create", ctx, identity: "entra", confirmToken, approvalId, verificationRequired: true,
|
|
118
|
+
plan: async () => {
|
|
119
|
+
const app = await ownedApplication(ctx, application);
|
|
120
|
+
if (!app.appId)
|
|
121
|
+
throw new M365Error("refused", "refused: application has no appId");
|
|
122
|
+
const ownerServicePrincipalId = await assertOwned(ctx, app);
|
|
123
|
+
const path = alternate("servicePrincipals", "appId", app.appId);
|
|
124
|
+
const existing = await optionalGet(() => ctx.graph.get(path, { identity: "entra", query: { $select: "id,appId,displayName,accountEnabled" } }));
|
|
125
|
+
if (existing)
|
|
126
|
+
await assertServicePrincipalOwned(ctx, existing);
|
|
127
|
+
const desired = { appId: app.appId, accountEnabled };
|
|
128
|
+
return {
|
|
129
|
+
targetType: "servicePrincipal", targetId: app.appId, targetLabel: app.displayName ?? app.id, operation: "upsert_service_principal",
|
|
130
|
+
before: { applicationObjectId: app.id, ownerServicePrincipalId, existing: existing ? fields(existing, ["appId", "accountEnabled"]) : null },
|
|
131
|
+
change: desired,
|
|
132
|
+
...(existing && matches(existing, desired) ? { noop: "service principal already matches" } : {}),
|
|
133
|
+
};
|
|
134
|
+
},
|
|
135
|
+
execute: async (plan) => {
|
|
136
|
+
const before = plan.before;
|
|
137
|
+
await assertOwned(ctx, await resolveApplication(ctx, before.applicationObjectId));
|
|
138
|
+
const path = alternate("servicePrincipals", "appId", plan.targetId);
|
|
139
|
+
const current = await optionalGet(() => ctx.graph.get(path, { identity: "entra", query: { $select: "id,appId,accountEnabled" } }));
|
|
140
|
+
if (current)
|
|
141
|
+
await assertServicePrincipalOwned(ctx, current);
|
|
142
|
+
if (!same(current ? fields(current, ["appId", "accountEnabled"]) : null, before.existing))
|
|
143
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: service principal state changed after confirmation");
|
|
144
|
+
const requestIds = [rid(await ctx.graph.request("PATCH", path, { identity: "entra", headers: { Prefer: "create-if-missing" }, body: plan.change }))];
|
|
145
|
+
if (!current) {
|
|
146
|
+
const created = await boundedAfter(ctx, async () => (await ctx.graph.get(path, { identity: "entra", query: { $select: "id,appId,displayName,accountEnabled" } })).data, () => true);
|
|
147
|
+
try {
|
|
148
|
+
await assertServicePrincipalOwned(ctx, created);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
if (!(error instanceof M365Error) || error.code !== "refused")
|
|
152
|
+
throw error;
|
|
153
|
+
requestIds.push(rid(await ctx.graph.request("POST", `/servicePrincipals/${created.id}/owners/$ref`, { identity: "entra", body: { "@odata.id": `${ctx.graph.base.origin}${ctx.graph.base.pathname}/directoryObjects/${before.ownerServicePrincipalId}` } })));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return requestIds;
|
|
157
|
+
},
|
|
158
|
+
after: async (plan) => safeServicePrincipal(await boundedAfter(ctx, async () => {
|
|
159
|
+
const sp = (await ctx.graph.get(alternate("servicePrincipals", "appId", plan.targetId), { identity: "entra", query: { $select: "id,appId,displayName,accountEnabled" } })).data;
|
|
160
|
+
await assertServicePrincipalOwned(ctx, sp);
|
|
161
|
+
return sp;
|
|
162
|
+
}, (sp) => matches(sp, plan.change))),
|
|
163
|
+
}));
|
|
164
|
+
server.tool("m365_entra_service_principal_update", "[WRITE] Update allowlisted service-principal scalar properties only. Both the linked application and service principal must be owned.", { servicePrincipal: z.string().min(1).max(256), changes: spChangesSchema, ...confirmParams }, async ({ servicePrincipal, changes, confirmToken, approvalId }) => runWrite({
|
|
165
|
+
tool: "m365_entra_service_principal_update", ctx, identity: "entra", confirmToken, approvalId, verificationRequired: true,
|
|
166
|
+
plan: async () => {
|
|
167
|
+
const keys = Object.keys(changes);
|
|
168
|
+
const sp = await resolveServicePrincipal(ctx, servicePrincipal, `id,appId,displayName,${keys.join(",")}`);
|
|
169
|
+
await assertServicePrincipalOwned(ctx, sp);
|
|
170
|
+
const apps = await ctx.graph.get("/applications", { identity: "entra", query: { $filter: `appId eq '${sp.appId}'`, $select: "id,appId,displayName", $top: 2 } });
|
|
171
|
+
const app = apps.data.value?.[0];
|
|
172
|
+
if (!app)
|
|
173
|
+
throw new M365Error("refused", "refused: service principal has no local application registration");
|
|
174
|
+
await assertOwned(ctx, app);
|
|
175
|
+
const change = delta(sp, changes);
|
|
176
|
+
return { targetType: "servicePrincipal", targetId: sp.id, targetLabel: sp.displayName ?? sp.id, operation: "update_service_principal", before: { applicationObjectId: app.id, fields: fields(sp, keys) }, change, ...(Object.keys(change).length ? {} : { noop: "all requested service-principal properties already match" }) };
|
|
177
|
+
},
|
|
178
|
+
execute: async (plan) => {
|
|
179
|
+
const keys = Object.keys(changes);
|
|
180
|
+
await assertOwned(ctx, await resolveApplication(ctx, plan.before.applicationObjectId));
|
|
181
|
+
const sp = await resolveServicePrincipal(ctx, plan.targetId, `id,appId,displayName,${keys.join(",")}`);
|
|
182
|
+
await assertServicePrincipalOwned(ctx, sp);
|
|
183
|
+
if (!same(fields(sp, keys), plan.before.fields))
|
|
184
|
+
throw new M365Error("confirmation_invalid", "confirmation_invalid: targeted service-principal fields changed after confirmation");
|
|
185
|
+
return [rid(await ctx.graph.request("PATCH", `/servicePrincipals/${plan.targetId}`, { identity: "entra", body: plan.change }))];
|
|
186
|
+
},
|
|
187
|
+
after: async (plan) => safeServicePrincipal(await boundedAfter(ctx, async () => {
|
|
188
|
+
const sp = await resolveServicePrincipal(ctx, plan.targetId, `id,appId,displayName,${Object.keys(changes).join(",")}`);
|
|
189
|
+
await assertServicePrincipalOwned(ctx, sp);
|
|
190
|
+
return sp;
|
|
191
|
+
}, (sp) => matches(sp, plan.change))),
|
|
192
|
+
}));
|
|
193
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { GUID_RE } from "../config.js";
|
|
3
|
+
import { M365Error } from "../errors.js";
|
|
4
|
+
import { cursorParam, errorResult, formatParam, jsonBlock, limitParam, listPage, odataString, or, renderList, searchText, textResult, } from "./common.js";
|
|
5
|
+
export const APPLICATION_SELECT = "id,appId,uniqueName,displayName,description,signInAudience,publisherDomain,createdDateTime,disabledByMicrosoftStatus,notes,tags,requiredResourceAccess,keyCredentials";
|
|
6
|
+
export const SERVICE_PRINCIPAL_SELECT = "id,appId,displayName,description,servicePrincipalType,accountEnabled,appOwnerOrganizationId,homepage,loginUrl,notificationEmailAddresses,preferredSingleSignOnMode,tags,keyCredentials";
|
|
7
|
+
const APPLICATION_LIST_SELECT = "id,appId,displayName,description,signInAudience,publisherDomain,createdDateTime,disabledByMicrosoftStatus,tags";
|
|
8
|
+
const SERVICE_PRINCIPAL_LIST_SELECT = "id,appId,displayName,description,servicePrincipalType,accountEnabled,appOwnerOrganizationId,homepage,loginUrl,preferredSingleSignOnMode,tags";
|
|
9
|
+
const MAX_NESTED = 20;
|
|
10
|
+
const ADVANCED = { ConsistencyLevel: "eventual" };
|
|
11
|
+
export const applicationParam = z.string().min(1).max(256).describe("Application object id, application/client id, or exact display name");
|
|
12
|
+
export const servicePrincipalParam = z.string().min(1).max(256).describe("Service principal object id, application/client id, or exact display name");
|
|
13
|
+
const safeKeys = (keys) => (keys ?? []).slice(0, MAX_NESTED).map(({ keyId, displayName, startDateTime, endDateTime, type, usage, customKeyIdentifier }) => ({
|
|
14
|
+
keyId,
|
|
15
|
+
displayName,
|
|
16
|
+
startDateTime,
|
|
17
|
+
endDateTime,
|
|
18
|
+
type,
|
|
19
|
+
usage,
|
|
20
|
+
customKeyIdentifier,
|
|
21
|
+
}));
|
|
22
|
+
export const safeApplication = (a) => ({
|
|
23
|
+
id: a.id,
|
|
24
|
+
appId: a.appId,
|
|
25
|
+
uniqueName: a.uniqueName,
|
|
26
|
+
displayName: a.displayName,
|
|
27
|
+
description: a.description,
|
|
28
|
+
signInAudience: a.signInAudience,
|
|
29
|
+
publisherDomain: a.publisherDomain,
|
|
30
|
+
createdDateTime: a.createdDateTime,
|
|
31
|
+
disabledByMicrosoftStatus: a.disabledByMicrosoftStatus,
|
|
32
|
+
notes: a.notes,
|
|
33
|
+
tags: Array.isArray(a.tags) ? a.tags.slice(0, MAX_NESTED) : a.tags,
|
|
34
|
+
requiredResourceAccess: (a.requiredResourceAccess ?? []).slice(0, MAX_NESTED).map((r) => ({ ...r, resourceAccess: (r.resourceAccess ?? []).slice(0, MAX_NESTED) })),
|
|
35
|
+
keyCredentials: safeKeys(a.keyCredentials),
|
|
36
|
+
});
|
|
37
|
+
export const safeServicePrincipal = (s) => ({
|
|
38
|
+
id: s.id,
|
|
39
|
+
appId: s.appId,
|
|
40
|
+
displayName: s.displayName,
|
|
41
|
+
description: s.description,
|
|
42
|
+
servicePrincipalType: s.servicePrincipalType,
|
|
43
|
+
accountEnabled: s.accountEnabled,
|
|
44
|
+
appOwnerOrganizationId: s.appOwnerOrganizationId,
|
|
45
|
+
homepage: s.homepage,
|
|
46
|
+
loginUrl: s.loginUrl,
|
|
47
|
+
notificationEmailAddresses: Array.isArray(s.notificationEmailAddresses) ? s.notificationEmailAddresses.slice(0, MAX_NESTED) : s.notificationEmailAddresses,
|
|
48
|
+
preferredSingleSignOnMode: s.preferredSingleSignOnMode,
|
|
49
|
+
tags: Array.isArray(s.tags) ? s.tags.slice(0, MAX_NESTED) : s.tags,
|
|
50
|
+
keyCredentials: safeKeys(s.keyCredentials),
|
|
51
|
+
});
|
|
52
|
+
async function unique(ctx, path, input, select) {
|
|
53
|
+
const filters = GUID_RE.test(input) ? [`appId eq ${odataString(input)}`] : [`displayName eq ${odataString(input)}`];
|
|
54
|
+
for (const filter of filters) {
|
|
55
|
+
const r = await ctx.graph.get(path, { identity: "entra", query: { $filter: filter, $select: select, $top: 5 }, headers: ADVANCED });
|
|
56
|
+
const found = r.data.value ?? [];
|
|
57
|
+
if (found.length === 1)
|
|
58
|
+
return found[0];
|
|
59
|
+
if (found.length > 1)
|
|
60
|
+
throw new M365Error("ambiguous_target", `ambiguous_target: several objects match ${input}; pass the object id`);
|
|
61
|
+
}
|
|
62
|
+
throw new M365Error("not_found", `not_found: no object matches ${input}`);
|
|
63
|
+
}
|
|
64
|
+
export async function resolveApplication(ctx, input, select = APPLICATION_SELECT) {
|
|
65
|
+
if (GUID_RE.test(input)) {
|
|
66
|
+
try {
|
|
67
|
+
return (await ctx.graph.get(`/applications/${input}`, { identity: "entra", query: { $select: select } })).data;
|
|
68
|
+
}
|
|
69
|
+
catch (e) {
|
|
70
|
+
if (!(e instanceof M365Error) || e.code !== "not_found")
|
|
71
|
+
throw e;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return unique(ctx, "/applications", input, select);
|
|
75
|
+
}
|
|
76
|
+
export async function resolveServicePrincipal(ctx, input, select = SERVICE_PRINCIPAL_SELECT) {
|
|
77
|
+
if (GUID_RE.test(input)) {
|
|
78
|
+
try {
|
|
79
|
+
return (await ctx.graph.get(`/servicePrincipals/${input}`, { identity: "entra", query: { $select: select } })).data;
|
|
80
|
+
}
|
|
81
|
+
catch (e) {
|
|
82
|
+
if (!(e instanceof M365Error) || e.code !== "not_found")
|
|
83
|
+
throw e;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return unique(ctx, "/servicePrincipals", input, select);
|
|
87
|
+
}
|
|
88
|
+
async function ownerServicePrincipal(ctx) {
|
|
89
|
+
const appId = ctx.identities.entra?.clientId;
|
|
90
|
+
if (!appId)
|
|
91
|
+
throw new M365Error("refused", "refused: dedicated entra-applications identity is not loaded");
|
|
92
|
+
const r = await ctx.graph.get("/servicePrincipals", { identity: "entra", query: { $filter: `appId eq '${appId}'`, $select: "id,appId", $top: 2 } });
|
|
93
|
+
const found = r.data.value ?? [];
|
|
94
|
+
if (found.length !== 1)
|
|
95
|
+
throw new M365Error("refused", "refused: cannot uniquely resolve the dedicated identity service principal for ownership checks");
|
|
96
|
+
return found[0];
|
|
97
|
+
}
|
|
98
|
+
async function assertObjectOwned(ctx, kind, objectId) {
|
|
99
|
+
const owner = await ownerServicePrincipal(ctx);
|
|
100
|
+
let url = ctx.graph.urlFor(`/${kind}/${objectId}/owners`, { $select: "id,appId", $top: 100 });
|
|
101
|
+
let owned = false;
|
|
102
|
+
for (let page = 0; page < 5 && url; page++) {
|
|
103
|
+
const r = await ctx.graph.getUrl(url, { identity: "entra" });
|
|
104
|
+
owned ||= (r.data.value ?? []).some((x) => x.id === owner.id || x.appId?.toLowerCase() === ctx.identities.entra?.clientId.toLowerCase());
|
|
105
|
+
url = r.data["@odata.nextLink"] ? ctx.graph.assertGraphUrl(r.data["@odata.nextLink"]).toString() : "";
|
|
106
|
+
}
|
|
107
|
+
if (!owned)
|
|
108
|
+
throw new M365Error("refused", `refused: ${kind === "applications" ? "application" : "service principal"} ${objectId} is not owned by the dedicated entra-applications identity`);
|
|
109
|
+
return owner.id;
|
|
110
|
+
}
|
|
111
|
+
export async function assertOwned(ctx, app) {
|
|
112
|
+
return assertObjectOwned(ctx, "applications", app.id);
|
|
113
|
+
}
|
|
114
|
+
export async function assertServicePrincipalOwned(ctx, sp) {
|
|
115
|
+
return assertObjectOwned(ctx, "servicePrincipals", sp.id);
|
|
116
|
+
}
|
|
117
|
+
async function resourcePrincipal(ctx, appId) {
|
|
118
|
+
const r = await ctx.graph.get("/servicePrincipals", {
|
|
119
|
+
identity: "entra",
|
|
120
|
+
query: { $filter: `appId eq ${odataString(appId)}`, $select: "id,appId,displayName,appRoles,oauth2PermissionScopes", $top: 2 },
|
|
121
|
+
});
|
|
122
|
+
return r.data.value?.[0];
|
|
123
|
+
}
|
|
124
|
+
export async function requestedPermissions(ctx, app) {
|
|
125
|
+
const out = [];
|
|
126
|
+
const resources = app.requiredResourceAccess ?? [];
|
|
127
|
+
let total = 0;
|
|
128
|
+
for (const resource of resources) {
|
|
129
|
+
const sp = await resourcePrincipal(ctx, resource.resourceAppId);
|
|
130
|
+
for (const access of resource.resourceAccess ?? []) {
|
|
131
|
+
total++;
|
|
132
|
+
if (out.length >= MAX_NESTED)
|
|
133
|
+
continue;
|
|
134
|
+
const definitions = access.type === "Role" ? sp?.appRoles : sp?.oauth2PermissionScopes;
|
|
135
|
+
const def = definitions?.find((d) => d.id.toLowerCase() === access.id.toLowerCase());
|
|
136
|
+
out.push({ resourceAppId: resource.resourceAppId, resource: sp?.displayName, id: access.id, type: access.type === "Role" ? "application" : "delegated", value: def?.value, displayName: def?.displayName });
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return { items: out, truncated: total > MAX_NESTED, limit: MAX_NESTED };
|
|
140
|
+
}
|
|
141
|
+
async function boundedCollection(ctx, path, query) {
|
|
142
|
+
const items = [];
|
|
143
|
+
let url = ctx.graph.urlFor(path, query);
|
|
144
|
+
for (let page = 0; page < 5 && url; page++) {
|
|
145
|
+
const r = await ctx.graph.getUrl(url, { identity: "entra" });
|
|
146
|
+
items.push(...(r.data.value ?? []));
|
|
147
|
+
const next = r.data["@odata.nextLink"];
|
|
148
|
+
if (items.length > MAX_NESTED)
|
|
149
|
+
return { items: items.slice(0, MAX_NESTED + 1), truncated: true };
|
|
150
|
+
if (!next)
|
|
151
|
+
return { items, truncated: false };
|
|
152
|
+
url = ctx.graph.assertGraphUrl(next).toString();
|
|
153
|
+
}
|
|
154
|
+
return { items, truncated: Boolean(url) };
|
|
155
|
+
}
|
|
156
|
+
export function registerEntraApplicationReadTools(server, ctx) {
|
|
157
|
+
server.tool("m365_entra_applications", "List Entra application registrations through the dedicated entra-applications identity (bounded and allowlisted).", {
|
|
158
|
+
search: searchText("Prefix matched against displayName").optional(), limit: limitParam, cursor: cursorParam, format: formatParam,
|
|
159
|
+
}, async ({ search, limit, cursor, format }) => {
|
|
160
|
+
try {
|
|
161
|
+
const page = await listPage(ctx, "m365_entra_applications", { path: "/applications", identity: "entra", headers: ADVANCED, query: { $select: APPLICATION_LIST_SELECT, $filter: search ? `startswith(displayName,${odataString(search)})` : undefined, $count: "true" } }, limit, cursor);
|
|
162
|
+
const safe = { ...page, items: page.items.map(safeApplication) };
|
|
163
|
+
return textResult(renderList("Entra applications", safe, format, (a) => `${or(a.displayName)} (${a.id}) — appId ${or(a.appId)}`));
|
|
164
|
+
}
|
|
165
|
+
catch (e) {
|
|
166
|
+
return errorResult(e);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
server.tool("m365_entra_application_info", "One Entra application registration, with safe public certificate metadata; no secrets or private key material.", { application: applicationParam }, async ({ application }) => {
|
|
170
|
+
try {
|
|
171
|
+
return textResult(`# Entra application\n\n${jsonBlock(safeApplication(await resolveApplication(ctx, application)))}`);
|
|
172
|
+
}
|
|
173
|
+
catch (e) {
|
|
174
|
+
return errorResult(e);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
server.tool("m365_entra_service_principals", "List enterprise application service principals (bounded and allowlisted).", {
|
|
178
|
+
search: searchText("Prefix matched against displayName").optional(), limit: limitParam, cursor: cursorParam, format: formatParam,
|
|
179
|
+
}, async ({ search, limit, cursor, format }) => {
|
|
180
|
+
try {
|
|
181
|
+
const page = await listPage(ctx, "m365_entra_service_principals", { path: "/servicePrincipals", identity: "entra", headers: ADVANCED, query: { $select: SERVICE_PRINCIPAL_LIST_SELECT, $filter: search ? `startswith(displayName,${odataString(search)})` : undefined, $count: "true" } }, limit, cursor);
|
|
182
|
+
const safe = { ...page, items: page.items.map(safeServicePrincipal) };
|
|
183
|
+
return textResult(renderList("Entra service principals", safe, format, (s) => `${or(s.displayName)} (${s.id}) — appId ${or(s.appId)}`));
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
return errorResult(e);
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
server.tool("m365_entra_service_principal_info", "One enterprise application service principal with allowlisted properties.", { servicePrincipal: servicePrincipalParam }, async ({ servicePrincipal }) => {
|
|
190
|
+
try {
|
|
191
|
+
return textResult(`# Entra service principal\n\n${jsonBlock(safeServicePrincipal(await resolveServicePrincipal(ctx, servicePrincipal)))}`);
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
return errorResult(e);
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
server.tool("m365_entra_application_requested_permissions", "Requested application/delegated permissions from requiredResourceAccess, resolved to resource and permission names.", { application: applicationParam }, async ({ application }) => {
|
|
198
|
+
try {
|
|
199
|
+
const app = await resolveApplication(ctx, application, "id,appId,displayName,requiredResourceAccess");
|
|
200
|
+
return textResult(`# Requested permissions — ${or(app.displayName)}\n\n${jsonBlock(await requestedPermissions(ctx, app))}`);
|
|
201
|
+
}
|
|
202
|
+
catch (e) {
|
|
203
|
+
return errorResult(e);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
server.tool("m365_entra_service_principal_effective_permissions", "Read effective application role assignments and delegated OAuth2 permission grants. This never grants consent or writes assignments.", { servicePrincipal: servicePrincipalParam }, async ({ servicePrincipal }) => {
|
|
207
|
+
try {
|
|
208
|
+
const sp = await resolveServicePrincipal(ctx, servicePrincipal, "id,appId,displayName");
|
|
209
|
+
const [roles, grants] = await Promise.all([
|
|
210
|
+
boundedCollection(ctx, `/servicePrincipals/${sp.id}/appRoleAssignments`, { $select: "id,resourceId,appRoleId" }),
|
|
211
|
+
boundedCollection(ctx, "/oauth2PermissionGrants", { $filter: `clientId eq ${odataString(sp.id)}`, $select: "id,clientId,resourceId,scope,consentType,principalId" }),
|
|
212
|
+
]);
|
|
213
|
+
const resourceIds = [...new Set([...roles.items.map((x) => x.resourceId), ...grants.items.map((x) => x.resourceId)])].slice(0, MAX_NESTED);
|
|
214
|
+
const resources = new Map();
|
|
215
|
+
for (const id of resourceIds)
|
|
216
|
+
resources.set(id, (await ctx.graph.get(`/servicePrincipals/${id}`, { identity: "entra", query: { $select: "id,displayName,appRoles,oauth2PermissionScopes" } })).data);
|
|
217
|
+
const effective = [
|
|
218
|
+
...roles.items.map((x) => { const r = resources.get(x.resourceId); const d = r?.appRoles?.find((p) => p.id === x.appRoleId); return { type: "application", resource: r?.displayName, resourceId: x.resourceId, id: x.appRoleId, value: d?.value, displayName: d?.displayName }; }),
|
|
219
|
+
...grants.items.flatMap((x) => (x.scope ?? "").split(/\s+/).filter(Boolean).map((scope) => ({ type: "delegated", resource: resources.get(x.resourceId)?.displayName, resourceId: x.resourceId, value: scope, consentType: x.consentType, principalId: x.principalId }))),
|
|
220
|
+
];
|
|
221
|
+
const truncated = roles.truncated || grants.truncated || effective.length > MAX_NESTED;
|
|
222
|
+
return textResult(`# Effective permissions — ${or(sp.displayName)}\n\n${jsonBlock({ items: effective.slice(0, MAX_NESTED), truncated, limit: MAX_NESTED })}`);
|
|
223
|
+
}
|
|
224
|
+
catch (e) {
|
|
225
|
+
return errorResult(e);
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
server.tool("m365_entra_application_federated_credentials", "List federated identity credentials for one owned application (first 20; no tokens or secrets).", { application: applicationParam }, async ({ application }) => {
|
|
229
|
+
try {
|
|
230
|
+
const app = await resolveApplication(ctx, application, "id,displayName");
|
|
231
|
+
await assertOwned(ctx, app);
|
|
232
|
+
const credentials = await boundedCollection(ctx, `/applications/${app.id}/federatedIdentityCredentials`, { $select: "id,name,issuer,subject,audiences,description" });
|
|
233
|
+
return textResult(`# Federated identity credentials — ${or(app.displayName)}\n\n${jsonBlock({ items: credentials.items.slice(0, MAX_NESTED), truncated: credentials.truncated || credentials.items.length > MAX_NESTED, limit: MAX_NESTED })}`);
|
|
234
|
+
}
|
|
235
|
+
catch (e) {
|
|
236
|
+
return errorResult(e);
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
}
|