@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/dist/index.js ADDED
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { loadConfig } from "./config.js";
6
+ import { createContext } from "./context.js";
7
+ import { registerTools } from "./register.js";
8
+ import { SERVER_INSTRUCTIONS } from "./tools/capabilities.js";
9
+ import { redactString } from "./redact.js";
10
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
11
+ // stdout is the MCP transport: everything human-readable goes to stderr, redacted.
12
+ const log = (msg) => process.stderr.write(`${redactString(msg)}\n`);
13
+ try {
14
+ const config = loadConfig(process.env);
15
+ const ctx = createContext(config);
16
+ const server = new McpServer({ name: "m365", version: pkg.version }, { instructions: SERVER_INSTRUCTIONS });
17
+ const tools = registerTools(server, ctx);
18
+ for (const w of config.warnings)
19
+ log(w);
20
+ await server.connect(new StdioServerTransport());
21
+ const auth = (k) => k ?? "—";
22
+ log(`m365-mcp v${pkg.version} ready (mode: ${config.mode}, tenant: ${config.tenantId}, read: ${config.read.clientId} [${config.read.auth.kind}], ` +
23
+ `write: ${config.write ? `${config.write.clientId} [${auth(config.write.auth.kind)}], families: ${[...config.writeFamilies].join(",") || "none"}` : "not loaded"}, tools: ${tools.length})`);
24
+ }
25
+ catch (err) {
26
+ log(`m365-mcp: ${err instanceof Error ? err.message : String(err)}`);
27
+ process.exit(1);
28
+ }
@@ -0,0 +1,42 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { M365Error } from "./errors.js";
3
+ /** Default and server-side maximum page size of every list tool. */
4
+ export const DEFAULT_LIMIT = 25;
5
+ export const MAX_LIMIT = 100;
6
+ const TTL_MS = 30 * 60_000;
7
+ const MAX_ENTRIES = 1000;
8
+ /**
9
+ * Opaque, server-side pagination cursors. The caller only ever holds a random id: it never sees
10
+ * nor supplies a URL, so a cursor cannot be turned into a request to another resource or host.
11
+ * A cursor is bound to the tool that issued it.
12
+ */
13
+ export class CursorStore {
14
+ now;
15
+ entries = new Map();
16
+ constructor(now = Date.now) {
17
+ this.now = now;
18
+ }
19
+ put(tool, url, offset = 0, headers) {
20
+ this.evict();
21
+ const id = randomBytes(12).toString("base64url");
22
+ this.entries.set(id, { tool, url, offset, headers, at: this.now() });
23
+ return id;
24
+ }
25
+ get(tool, id) {
26
+ const e = this.entries.get(id);
27
+ if (!e || this.now() - e.at > TTL_MS) {
28
+ throw new M365Error("invalid_request", "invalid_request: unknown or expired cursor — restart the listing without cursor");
29
+ }
30
+ if (e.tool !== tool)
31
+ throw new M365Error("invalid_request", `invalid_request: this cursor belongs to ${e.tool}, not ${tool}`);
32
+ return { url: e.url, offset: e.offset, headers: e.headers };
33
+ }
34
+ evict() {
35
+ const now = this.now();
36
+ for (const [id, e] of this.entries)
37
+ if (now - e.at > TTL_MS)
38
+ this.entries.delete(id);
39
+ while (this.entries.size >= MAX_ENTRIES)
40
+ this.entries.delete(this.entries.keys().next().value);
41
+ }
42
+ }
@@ -0,0 +1,212 @@
1
+ export const TOOL_SPECS = [
2
+ { tool: "m365_capabilities", access: "read", endpoints: ["(token claims only)"], permissions: [] },
3
+ {
4
+ tool: "m365_organization",
5
+ access: "read",
6
+ endpoints: ["GET /organization"],
7
+ permissions: ["Organization.Read.All"],
8
+ alternatives: ["Directory.Read.All"],
9
+ },
10
+ {
11
+ tool: "m365_users",
12
+ access: "read",
13
+ endpoints: ["GET /users"],
14
+ permissions: ["User.Read.All"],
15
+ alternatives: ["Directory.Read.All"],
16
+ },
17
+ {
18
+ tool: "m365_user_info",
19
+ access: "read",
20
+ endpoints: ["GET /users/{id}", "GET /subscribedSkus (licence names)"],
21
+ permissions: ["User.Read.All"],
22
+ alternatives: ["Directory.Read.All"],
23
+ },
24
+ {
25
+ tool: "m365_subscribed_skus",
26
+ access: "read",
27
+ endpoints: ["GET /subscribedSkus"],
28
+ permissions: ["LicenseAssignment.Read.All"],
29
+ alternatives: ["Organization.Read.All", "Directory.Read.All"],
30
+ },
31
+ {
32
+ tool: "m365_license_assignments",
33
+ access: "read",
34
+ endpoints: ["GET /users/{id}?$select=licenseAssignmentStates,assignedPlans", "GET /subscribedSkus (plan names)"],
35
+ permissions: ["User.Read.All"],
36
+ alternatives: ["Directory.Read.All"],
37
+ note: "licenseAssignmentStates and assignedPlans are user properties, hence User.Read.All. GET /users/{id}/licenseDetails is not used: it supports delegated permissions only",
38
+ },
39
+ {
40
+ tool: "m365_groups",
41
+ access: "read",
42
+ endpoints: ["GET /groups"],
43
+ permissions: ["GroupMember.Read.All"],
44
+ alternatives: ["Group.Read.All", "Directory.Read.All"],
45
+ },
46
+ {
47
+ tool: "m365_group_info",
48
+ access: "read",
49
+ endpoints: ["GET /groups/{id}", "GET /groups/{id}/members/$count", "GET /groups/{id}/owners"],
50
+ permissions: ["GroupMember.Read.All"],
51
+ alternatives: ["Group.Read.All", "Directory.Read.All"],
52
+ },
53
+ {
54
+ tool: "m365_group_members",
55
+ access: "read",
56
+ endpoints: ["GET /groups/{id}/members"],
57
+ permissions: ["GroupMember.Read.All", "User.Read.All"],
58
+ alternatives: ["Directory.Read.All"],
59
+ note: "without User.Read.All, user members come back with their id only",
60
+ },
61
+ {
62
+ tool: "m365_teams",
63
+ access: "read",
64
+ endpoints: ["GET /teams"],
65
+ permissions: ["Team.ReadBasic.All"],
66
+ alternatives: ["TeamSettings.Read.All", "Directory.Read.All"],
67
+ },
68
+ {
69
+ tool: "m365_team_info",
70
+ access: "read",
71
+ endpoints: ["GET /teams/{id}"],
72
+ permissions: ["Team.ReadBasic.All"],
73
+ alternatives: ["TeamSettings.Read.All", "TeamSettings.ReadWrite.All", "Directory.Read.All"],
74
+ rsc: ["TeamSettings.Read.Group"],
75
+ note: "if the member/guest/messaging/fun settings come back empty, add TeamSettings.Read.All",
76
+ },
77
+ {
78
+ tool: "m365_team_channels",
79
+ access: "read",
80
+ endpoints: ["GET /teams/{id}/channels"],
81
+ permissions: ["Channel.ReadBasic.All"],
82
+ alternatives: ["ChannelSettings.Read.All", "Directory.Read.All"],
83
+ rsc: ["ChannelSettings.Read.Group"],
84
+ },
85
+ {
86
+ tool: "m365_team_members",
87
+ access: "read",
88
+ endpoints: ["GET /teams/{id}/members"],
89
+ permissions: ["TeamMember.Read.All"],
90
+ alternatives: ["TeamMember.ReadWrite.All", "Directory.Read.All"],
91
+ rsc: ["TeamMember.Read.Group"],
92
+ },
93
+ {
94
+ tool: "m365_audit_signins",
95
+ access: "read",
96
+ endpoints: ["GET /auditLogs/signIns"],
97
+ permissions: ["AuditLog.Read.All"],
98
+ note: "registered only with M365_ENABLE_SIGNIN_AUDIT=true; needs Entra ID P1/P2 (else unsupported_by_tenant). Microsoft documents Directory.Read.All alongside AuditLog.Read.All for this API — add it if Graph answers 403",
99
+ },
100
+ // ---- writes (write identity, M365_MODE=full)
101
+ {
102
+ tool: "m365_user_update",
103
+ access: "write",
104
+ planPermissions: ["User.Read.All"],
105
+ family: "users",
106
+ endpoints: ["PATCH /users/{id}"],
107
+ permissions: ["User.ReadWrite.All"],
108
+ note: "allowlisted attributes only; users holding an admin role additionally require a privileged Entra role and are refused by Graph (permission_missing)",
109
+ },
110
+ {
111
+ tool: "m365_user_set_account_enabled",
112
+ access: "write",
113
+ planPermissions: ["User.Read.All"],
114
+ family: "users",
115
+ endpoints: ["PATCH /users/{id} (accountEnabled)"],
116
+ permissions: ["User.EnableDisableAccount.All", "User.Read.All"],
117
+ alternatives: ["User.ReadWrite.All"],
118
+ note: "Microsoft requires User.Read.All together with User.EnableDisableAccount.All",
119
+ },
120
+ {
121
+ tool: "m365_user_assign_licenses",
122
+ access: "write",
123
+ planPermissions: ["User.Read.All", "LicenseAssignment.Read.All"],
124
+ family: "licenses",
125
+ endpoints: ["POST /users/{id}/assignLicense"],
126
+ permissions: ["LicenseAssignment.ReadWrite.All"],
127
+ alternatives: ["User.ReadWrite.All"],
128
+ },
129
+ {
130
+ tool: "m365_group_member_add",
131
+ access: "write",
132
+ planPermissions: ["GroupMember.Read.All", "User.Read.All"],
133
+ family: "groups",
134
+ endpoints: ["POST /groups/{id}/members/$ref"],
135
+ permissions: ["GroupMember.ReadWrite.All"],
136
+ alternatives: ["Group.ReadWrite.All"],
137
+ note: "role-assignable groups are refused (would need RoleManagement.ReadWrite.Directory)",
138
+ },
139
+ {
140
+ tool: "m365_group_member_remove",
141
+ access: "write",
142
+ planPermissions: ["GroupMember.Read.All", "User.Read.All"],
143
+ family: "groups",
144
+ endpoints: ["DELETE /groups/{id}/members/{memberId}/$ref"],
145
+ permissions: ["GroupMember.ReadWrite.All"],
146
+ alternatives: ["Group.ReadWrite.All"],
147
+ },
148
+ {
149
+ tool: "m365_team_member_add",
150
+ access: "write",
151
+ planPermissions: ["Team.ReadBasic.All", "TeamMember.Read.All", "User.Read.All"],
152
+ family: "teams",
153
+ endpoints: ["POST /teams/{id}/members"],
154
+ permissions: ["TeamMember.ReadWriteNonOwnerRole.All"],
155
+ alternatives: ["TeamMember.ReadWrite.All"],
156
+ note: "members only — owner role is out of scope in v1",
157
+ },
158
+ {
159
+ tool: "m365_team_member_remove",
160
+ access: "write",
161
+ planPermissions: ["Team.ReadBasic.All", "TeamMember.Read.All", "User.Read.All"],
162
+ family: "teams",
163
+ endpoints: ["DELETE /teams/{id}/members/{membershipId}"],
164
+ permissions: ["TeamMember.ReadWriteNonOwnerRole.All"],
165
+ alternatives: ["TeamMember.ReadWrite.All"],
166
+ note: "owners are refused",
167
+ },
168
+ {
169
+ tool: "m365_team_channel_create",
170
+ access: "write",
171
+ planPermissions: ["Team.ReadBasic.All", "Channel.ReadBasic.All"],
172
+ family: "teams",
173
+ endpoints: ["POST /teams/{id}/channels"],
174
+ permissions: ["Channel.Create"],
175
+ rsc: ["Channel.Create.Group"],
176
+ note: "standard channels only",
177
+ },
178
+ {
179
+ tool: "m365_team_channel_update",
180
+ access: "write",
181
+ planPermissions: ["Team.ReadBasic.All", "Channel.ReadBasic.All"],
182
+ family: "teams",
183
+ endpoints: ["PATCH /teams/{id}/channels/{channelId}"],
184
+ permissions: ["ChannelSettings.ReadWrite.All"],
185
+ rsc: ["ChannelSettings.ReadWrite.Group"],
186
+ },
187
+ {
188
+ tool: "m365_team_settings_update",
189
+ access: "write",
190
+ planPermissions: ["TeamSettings.Read.All"],
191
+ family: "teams",
192
+ endpoints: ["PATCH /teams/{id}"],
193
+ permissions: ["TeamSettings.ReadWrite.All"],
194
+ rsc: ["TeamSettings.ReadWrite.Group"],
195
+ },
196
+ ];
197
+ export const specOf = (tool) => TOOL_SPECS.find((s) => s.tool === tool);
198
+ /** Does this set of token roles satisfy the tool? RSC grants are invisible in the token: "unknown" then. */
199
+ export function permissionStatus(spec, roles) {
200
+ const has = new Set(roles);
201
+ if (spec.permissions.every((p) => has.has(p)))
202
+ return "granted";
203
+ if (spec.alternatives?.some((p) => has.has(p)))
204
+ return "granted";
205
+ return spec.rsc?.length ? "rsc-or-missing" : "missing";
206
+ }
207
+ /** Read-identity side of a write tool: are its preview permissions present? */
208
+ export function planStatus(spec, readRoles) {
209
+ return (spec.planPermissions ?? []).every((p) => readRoles.includes(p) || readRoles.includes("Directory.Read.All")) ? "granted" : "missing";
210
+ }
211
+ /** A permission whose name says it writes. The read identity should hold none of these. */
212
+ export const isWritePermission = (p) => /ReadWrite|EnableDisable|\.Create$|\.Create\./.test(p);
package/dist/redact.js ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Centralised redaction, applied before anything leaves the server: every JSON block a tool
3
+ * returns, every error message, and every audit/log line goes through `redact`.
4
+ *
5
+ * Two layers:
6
+ * - keys: a field whose name looks like a credential is replaced whatever its value;
7
+ * - strings: JWTs (Graph tokens, client assertions), "Bearer …" headers, secret-looking
8
+ * form/query parameters and signed URLs are masked wherever they appear in free text.
9
+ * Values registered with `registerSecret` (the configured client secrets, the certificate key)
10
+ * are also masked verbatim, so a secret echoed back by an error can never get out.
11
+ */
12
+ export const REDACTED = "[REDACTED]";
13
+ const SENSITIVE_KEY_PATTERNS = [
14
+ /pass(word|phrase)/i, // password, passwordProfile, passwordCredentials
15
+ /secret/i, // client_secret, secretText
16
+ /assertion/i, // client_assertion
17
+ /private[-_]?key/i,
18
+ /api[-_]?key/i,
19
+ /credential/i, // keyCredentials, passwordCredentials
20
+ /^authorization$/i,
21
+ /^cookie$/i,
22
+ /(token)$/i, // access_token, refresh_token, id_token, skipToken…
23
+ ];
24
+ /** Fields that end like a sensitive one but are not secrets. */
25
+ const SAFE_KEYS = new Set(["tokenType"]);
26
+ export function isSensitiveKey(key) {
27
+ if (SAFE_KEYS.has(key))
28
+ return false;
29
+ return SENSITIVE_KEY_PATTERNS.some((re) => re.test(key));
30
+ }
31
+ const STRING_PATTERNS = [
32
+ // JWT / JWS (three base64url segments, header starting with {" → "eyJ")
33
+ [/eyJ[\w-]{5,}\.[\w-]{5,}\.[\w-]*/g, "[REDACTED_JWT]"],
34
+ [/\b(Bearer|Basic)\s+[\w.~+/=-]{8,}/gi, "$1 [REDACTED]"],
35
+ // form / query parameters carrying credentials
36
+ [/\b(client_secret|client_assertion|access_token|refresh_token|id_token|assertion|code|password)=[^&\s"']+/gi, "$1=[REDACTED]"],
37
+ // signed URLs (SAS, pre-signed): keep the path, drop the query
38
+ [/(https?:\/\/[^\s?#"']+)\?[^\s"']*\b(sig|signature|x-amz-signature|token|se|sv)=[^\s"']*/gi, "$1?[REDACTED]"],
39
+ // PEM blocks
40
+ [/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/g, "[REDACTED_PEM]"],
41
+ ];
42
+ const secrets = new Set();
43
+ /** Mask this exact value wherever it appears from now on (ignored when too short to be meaningful). */
44
+ export function registerSecret(value) {
45
+ if (value && value.length >= 8)
46
+ secrets.add(value);
47
+ }
48
+ export function redactString(s) {
49
+ let out = s;
50
+ for (const secret of secrets)
51
+ if (out.includes(secret))
52
+ out = out.split(secret).join(REDACTED);
53
+ for (const [re, repl] of STRING_PATTERNS)
54
+ out = out.replace(re, repl);
55
+ return out;
56
+ }
57
+ /** Deep copy of `value` with sensitive fields and secret-looking strings masked. */
58
+ export function redact(value) {
59
+ return walk(value, 0);
60
+ }
61
+ function walk(value, depth) {
62
+ if (depth > 64)
63
+ return REDACTED; // pathological nesting: refuse rather than risk a leak
64
+ if (typeof value === "string")
65
+ return redactString(value);
66
+ if (Array.isArray(value))
67
+ return value.map((v) => walk(v, depth + 1));
68
+ if (value && typeof value === "object") {
69
+ const out = {};
70
+ for (const [k, v] of Object.entries(value)) {
71
+ out[k] = isSensitiveKey(k) && v !== null && v !== undefined && v !== "" ? REDACTED : walk(v, depth + 1);
72
+ }
73
+ return out;
74
+ }
75
+ return value;
76
+ }
@@ -0,0 +1,51 @@
1
+ import { registerCapabilityTools } from "./tools/capabilities.js";
2
+ import { registerOrganizationTools } from "./tools/organization.js";
3
+ import { registerSignInTools, registerUserTools } from "./tools/users.js";
4
+ import { registerLicenseTools } from "./tools/licenses.js";
5
+ import { registerGroupTools } from "./tools/groups.js";
6
+ import { registerTeamTools } from "./tools/teams.js";
7
+ import { registerUserWriteTools } from "./tools/users-write.js";
8
+ import { registerLicenseWriteTools } from "./tools/licenses-write.js";
9
+ import { registerGroupWriteTools } from "./tools/groups-write.js";
10
+ import { registerTeamWriteTools } from "./tools/teams-write.js";
11
+ /**
12
+ * Read tools always register. Write tools register only in full mode, with a write identity,
13
+ * and per family (M365_WRITE_FAMILIES) — in readonly mode they do not exist at all.
14
+ */
15
+ export function registerTools(server, ctx) {
16
+ const names = [];
17
+ const tracking = new Proxy(server, {
18
+ get(target, prop, receiver) {
19
+ if (prop === "tool") {
20
+ return (name, ...rest) => {
21
+ names.push(name);
22
+ return target.tool.call(target, name, ...rest);
23
+ };
24
+ }
25
+ return Reflect.get(target, prop, receiver);
26
+ },
27
+ });
28
+ registerCapabilityTools(tracking, ctx);
29
+ registerOrganizationTools(tracking, ctx);
30
+ registerUserTools(tracking, ctx);
31
+ registerLicenseTools(tracking, ctx);
32
+ registerGroupTools(tracking, ctx);
33
+ registerTeamTools(tracking, ctx);
34
+ if (ctx.config.signInAudit)
35
+ registerSignInTools(tracking, ctx);
36
+ if (ctx.config.mode === "full") {
37
+ if (!ctx.identities.write || !ctx.graph.hasWrite)
38
+ throw new Error("full mode requires the write identity (M365_WRITE_*)");
39
+ const f = ctx.config.writeFamilies;
40
+ if (f.has("users"))
41
+ registerUserWriteTools(tracking, ctx);
42
+ if (f.has("licenses"))
43
+ registerLicenseWriteTools(tracking, ctx);
44
+ if (f.has("groups"))
45
+ registerGroupWriteTools(tracking, ctx);
46
+ if (f.has("teams"))
47
+ registerTeamWriteTools(tracking, ctx);
48
+ }
49
+ ctx.registered.splice(0, ctx.registered.length, ...names);
50
+ return names;
51
+ }
@@ -0,0 +1,73 @@
1
+ import { toM365Error } from "../errors.js";
2
+ import { FORBIDDEN_ROLES } from "../auth/token-provider.js";
3
+ import { isWritePermission, permissionStatus, planStatus, TOOL_SPECS } from "../permissions.js";
4
+ import { jsonBlock, textResult } from "./common.js";
5
+ export const SERVER_INSTRUCTIONS = [
6
+ "Microsoft 365 MCP over Microsoft Graph (v1.0): Entra ID users and groups, licences, Teams. Read-only unless M365_MODE=full.",
7
+ "Start with m365_capabilities: it shows the mode, the tools registered and, for each, whether the Graph permission is present in the identity's token.",
8
+ "Lists are paginated: pass the returned cursor to get the next page. A refused or unavailable API answers with an explicit error code (permission_missing, unsupported_by_tenant…), never an empty list.",
9
+ "Writes ([WRITE] tools) are two-step: call once without confirmToken to get a preview and a token, then call again with the same arguments and the token. Get the user's explicit approval before the second call.",
10
+ "Out of scope: Entra roles, applications and credentials, passwords, Conditional Access, permanent deletions, mail/chat/meeting/file content.",
11
+ ].join("\n");
12
+ async function inspect(id) {
13
+ const described = { ...id.describe(), role: id.role };
14
+ try {
15
+ const info = await id.info();
16
+ return { ...described, ok: true, tenantId: info.tenantId, roles: info.roles, tokenExpiresAt: info.expiresAt };
17
+ }
18
+ catch (err) {
19
+ const e = toM365Error(err);
20
+ return { ...described, ok: false, roles: [], error: e.code, message: e.message };
21
+ }
22
+ }
23
+ export function registerCapabilityTools(server, ctx) {
24
+ server.tool("m365_capabilities", "Mode, tenant, the Entra identities in use (client id, auth method, certificate expiry — never a secret), the application permissions present in each token, and for every registered tool whether its permission is granted.", {}, async () => {
25
+ const read = await inspect(ctx.identities.read);
26
+ const write = ctx.identities.write ? await inspect(ctx.identities.write) : undefined;
27
+ const warnings = [...ctx.config.warnings];
28
+ if (read.ok) {
29
+ const writes = read.roles.filter(isWritePermission);
30
+ if (writes.length)
31
+ warnings.push(`the READ identity holds write permissions (${writes.join(", ")}) — remove them to keep the identities separate`);
32
+ }
33
+ for (const id of [read, write]) {
34
+ if (id?.ok) {
35
+ const broad = id.roles.filter((r) => FORBIDDEN_ROLES.includes(r));
36
+ if (broad.length)
37
+ warnings.push(`the ${id.role} identity holds ${broad.join(", ")}`);
38
+ }
39
+ if (id && typeof id.expiresInDays === "number" && id.expiresInDays < 30) {
40
+ warnings.push(`the ${id.role} certificate expires in ${id.expiresInDays} day(s) — rotate it`);
41
+ }
42
+ }
43
+ const tools = TOOL_SPECS.filter((s) => ctx.registered.includes(s.tool)).map((s) => {
44
+ const id = s.access === "write" ? write : read;
45
+ let status = s.permissions.length === 0 ? "granted" : id?.ok ? permissionStatus(s, id.roles) : "unknown (no token)";
46
+ // a write tool also needs, on the READ identity, the permissions its preview reads with
47
+ if (s.planPermissions && status === "granted")
48
+ status = read.ok ? (planStatus(s, read.roles) === "granted" ? "granted" : "missing on read identity (preview)") : "unknown (no read token)";
49
+ return {
50
+ tool: s.tool,
51
+ access: s.access,
52
+ status,
53
+ needs: s.permissions.join(" + ") || "—",
54
+ ...(s.planPermissions ? { previewNeedsOnRead: s.planPermissions.join(" + ") } : {}),
55
+ ...(s.rsc ? { rsc: s.rsc.join(", ") } : {}),
56
+ };
57
+ });
58
+ const missing = tools.filter((t) => t.status !== "granted");
59
+ const killSwitch = ctx.killSwitchActive();
60
+ const lines = [
61
+ `# Microsoft 365 MCP — capabilities`,
62
+ ``,
63
+ `Mode: **${ctx.config.mode}**${ctx.config.mode === "full" ? ` — write families: ${[...ctx.config.writeFamilies].join(", ") || "none"}` : ""}`,
64
+ `Tenant: ${ctx.config.tenantId}`,
65
+ killSwitch ? `⛔ Kill switch ACTIVE (${ctx.config.killSwitchFile}) — every write is refused` : "",
66
+ `Sign-in audit tool: ${ctx.config.signInAudit ? "enabled" : "disabled (M365_ENABLE_SIGNIN_AUDIT)"}`,
67
+ `Registered tools: ${ctx.registered.length}`,
68
+ missing.length ? `\n⚠ ${missing.length} tool(s) without their permission in the token: ${missing.map((t) => `${t.tool} (${t.needs})`).join("; ")}` : "\nAll registered tools have their permission.",
69
+ warnings.length ? `\n## Warnings\n${warnings.map((w) => `- ${w}`).join("\n")}` : "",
70
+ ].filter((l) => l !== "");
71
+ return textResult(`${lines.join("\n")}\n\n## Identities\n${jsonBlock({ read, write: write ?? "not loaded (readonly mode)" })}\n\n## Tools\n${jsonBlock(tools)}`);
72
+ });
73
+ }
@@ -0,0 +1,185 @@
1
+ import { z } from "zod";
2
+ import { GUID_RE } from "../config.js";
3
+ import { M365Error } from "../errors.js";
4
+ import { DEFAULT_LIMIT, MAX_LIMIT } from "../pagination.js";
5
+ import { redact } from "../redact.js";
6
+ export { errorResult } from "../errors.js";
7
+ export function textResult(text) {
8
+ return { content: [{ type: "text", text }] };
9
+ }
10
+ /** Every JSON block a tool returns goes through here, so redaction happens in one place. */
11
+ export const jsonBlock = (data) => "```json\n" + JSON.stringify(redact(data), null, 2) + "\n```";
12
+ // ---- shared parameters
13
+ export const limitParam = z
14
+ .number()
15
+ .int()
16
+ .min(1)
17
+ .max(MAX_LIMIT)
18
+ .default(DEFAULT_LIMIT)
19
+ .describe(`Items per page (default ${DEFAULT_LIMIT}, server maximum ${MAX_LIMIT})`);
20
+ export const cursorParam = z
21
+ .string()
22
+ .regex(/^[\w-]{8,64}$/)
23
+ .optional()
24
+ .describe("Opaque cursor returned by the previous page (same tool). Omit for the first page.");
25
+ export const formatParam = z
26
+ .enum(["summary", "json"])
27
+ .default("summary")
28
+ .describe("summary = one readable line per item; json = the bounded, allowlisted fields as JSON");
29
+ /** Free text used inside an OData string literal: bounded, printable, quotes escaped by `odataString`. */
30
+ export const searchText = (what) => z
31
+ .string()
32
+ .min(1)
33
+ .max(120)
34
+ .regex(/^[^\u0000-\u001f\u007f]+$/, "control characters are not allowed")
35
+ .describe(what);
36
+ export const odataString = (s) => `'${s.replace(/'/g, "''")}'`;
37
+ export const userParam = z
38
+ .string()
39
+ .min(1)
40
+ .max(256)
41
+ .describe("User object id (GUID) or userPrincipalName (e.g. alice@contoso.com). An exact displayName is accepted if unique.");
42
+ export const groupParam = z
43
+ .string()
44
+ .min(1)
45
+ .max(256)
46
+ .describe("Group object id (GUID), or exact displayName / mailNickname if unique");
47
+ export const teamParam = z
48
+ .string()
49
+ .min(1)
50
+ .max(256)
51
+ .describe("Team id (= its Microsoft 365 group id, GUID), or exact team displayName if unique");
52
+ /** $select from a server-side allowlist: the caller may narrow it, never widen it. */
53
+ export function selectFields(allowed, defaults, requested) {
54
+ if (!requested?.length)
55
+ return defaults.join(",");
56
+ const bad = requested.filter((f) => !allowed.includes(f));
57
+ if (bad.length)
58
+ throw new M365Error("invalid_request", `invalid_request: field(s) not allowed: ${bad.join(", ")} — allowed: ${allowed.join(", ")}`);
59
+ return [...new Set(["id", ...requested])].join(",");
60
+ }
61
+ export const fieldsParam = (allowed) => z
62
+ .array(z.enum(allowed))
63
+ .max(allowed.length)
64
+ .optional()
65
+ .describe(`Restrict the returned fields (allowlist: ${allowed.join(", ")})`);
66
+ /**
67
+ * One page of a Graph collection. The first page is built from `path` + `query` (with $top when
68
+ * the endpoint supports it); later pages come from a server-side cursor. Endpoints that ignore
69
+ * $top are sliced locally and resumed at the right offset, so nothing is skipped.
70
+ */
71
+ export async function listPage(ctx, tool, first, limit, cursor) {
72
+ let url;
73
+ let offset = 0;
74
+ let headers = first.headers;
75
+ if (cursor) {
76
+ ({ url, offset, headers } = ctx.cursors.get(tool, cursor));
77
+ }
78
+ else {
79
+ url = ctx.graph.urlFor(first.path, { ...first.query, ...(first.supportsTop === false ? {} : { $top: limit }) });
80
+ }
81
+ const res = await ctx.graph.getUrl(url, { headers });
82
+ const value = Array.isArray(res.data?.value) ? res.data.value : [];
83
+ const items = value.slice(offset, offset + limit);
84
+ let nextCursor;
85
+ if (offset + limit < value.length) {
86
+ nextCursor = ctx.cursors.put(tool, url, offset + limit, headers);
87
+ }
88
+ else if (res.data?.["@odata.nextLink"]) {
89
+ const next = ctx.graph.assertGraphUrl(res.data["@odata.nextLink"]).toString();
90
+ nextCursor = ctx.cursors.put(tool, next, 0, headers);
91
+ }
92
+ return { items, nextCursor, count: res.data?.["@odata.count"], requestId: res.requestId };
93
+ }
94
+ export function pageFooter(page, shown) {
95
+ const total = page.count !== undefined ? ` of ${page.count}` : "";
96
+ return page.nextCursor
97
+ ? `\n\n_${shown}${total} shown — more available: call again with cursor: "${page.nextCursor}"._`
98
+ : `\n\n_${shown}${total} shown — end of list._`;
99
+ }
100
+ export function renderList(title, page, format, line) {
101
+ if (!page.items.length && !page.nextCursor)
102
+ return `# ${title}\n\nNo item matches (the request succeeded; this is a genuinely empty result).`;
103
+ const body = format === "json" ? jsonBlock(page.items) : page.items.map((i) => `- ${line(i)}`).join("\n");
104
+ return `# ${title}\n\n${body}${pageFooter(page, page.items.length)}`;
105
+ }
106
+ export const or = (v, d = "—") => (v === undefined || v === null || v === "" ? d : String(v));
107
+ // ---- target resolution (refuses ambiguous names)
108
+ const ADVANCED = { ConsistencyLevel: "eventual" };
109
+ async function uniqueByFilter(ctx, kind, path, filter, select, label, input) {
110
+ const res = await ctx.graph.get(path, { query: { $filter: filter, $select: select, $top: 5, $count: "true" }, headers: ADVANCED });
111
+ const found = res.data?.value ?? [];
112
+ if (found.length === 0)
113
+ throw new M365Error("not_found", `not_found: no ${kind} matches "${input}"`);
114
+ if (found.length > 1) {
115
+ throw new M365Error("ambiguous_target", `ambiguous_target: ${found.length}${found.length === 5 ? "+" : ""} ${kind}s match "${input}" — pass the object id instead: ${found.map(label).join("; ")}`);
116
+ }
117
+ return found[0];
118
+ }
119
+ export async function resolveUser(ctx, input, select) {
120
+ const sel = select.includes("userPrincipalName") ? select : `${select},userPrincipalName,displayName`;
121
+ if (GUID_RE.test(input) || input.includes("@")) {
122
+ return (await ctx.graph.get(`/users/${encodeURIComponent(input)}`, { query: { $select: sel } })).data;
123
+ }
124
+ return uniqueByFilter(ctx, "user", "/users", `displayName eq ${odataString(input)}`, sel, (u) => `${u.displayName} <${u.userPrincipalName}> (${u.id})`, input);
125
+ }
126
+ export async function resolveGroup(ctx, input, select) {
127
+ if (GUID_RE.test(input))
128
+ return (await ctx.graph.get(`/groups/${input}`, { query: { $select: select } })).data;
129
+ return uniqueByFilter(ctx, "group", "/groups", `displayName eq ${odataString(input)} or mailNickname eq ${odataString(input)}`, select, (g) => `${g.displayName} (${g.id})`, input);
130
+ }
131
+ /** A team is a Microsoft 365 group with a team: resolve by id, or by exact displayName among teams. */
132
+ export async function resolveTeamId(ctx, input) {
133
+ if (GUID_RE.test(input))
134
+ return { id: input.toLowerCase() };
135
+ const res = await ctx.graph.get("/teams", {
136
+ query: { $filter: `displayName eq ${odataString(input)}`, $select: "id,displayName", $top: 5 },
137
+ });
138
+ const found = res.data?.value ?? [];
139
+ if (found.length === 0)
140
+ throw new M365Error("not_found", `not_found: no team named "${input}"`);
141
+ if (found.length > 1) {
142
+ throw new M365Error("ambiguous_target", `ambiguous_target: ${found.length} teams are named "${input}" — pass the team id: ${found.map((t) => t.id).join(", ")}`);
143
+ }
144
+ return found[0];
145
+ }
146
+ const SKU_TTL_MS = 5 * 60_000;
147
+ /** /subscribedSkus, cached briefly: used to name licences and to check free units before assigning. */
148
+ export class SkuCache {
149
+ graph;
150
+ now;
151
+ cached;
152
+ constructor(graph, now = Date.now) {
153
+ this.graph = graph;
154
+ this.now = now;
155
+ }
156
+ list(fresh = false) {
157
+ if (!fresh && this.cached && this.now() - this.cached.at < SKU_TTL_MS)
158
+ return this.cached.p;
159
+ const p = this.graph.get("/subscribedSkus").then((r) => r.data?.value ?? []);
160
+ this.cached = { at: this.now(), p };
161
+ p.catch(() => {
162
+ if (this.cached?.p === p)
163
+ this.cached = undefined; // never drop a newer, valid entry
164
+ });
165
+ return p;
166
+ }
167
+ async name(skuId) {
168
+ const skus = await this.list().catch(() => []);
169
+ return skus.find((s) => s.skuId === skuId)?.skuPartNumber ?? skuId;
170
+ }
171
+ /** SKU by skuId (GUID) or skuPartNumber (case-insensitive), from fresh data. */
172
+ async resolve(input, fresh = true) {
173
+ const skus = await this.list(fresh);
174
+ const found = GUID_RE.test(input)
175
+ ? skus.filter((s) => s.skuId.toLowerCase() === input.toLowerCase())
176
+ : skus.filter((s) => s.skuPartNumber.toLowerCase() === input.toLowerCase());
177
+ if (found.length === 0) {
178
+ throw new M365Error("not_found", `not_found: the tenant has no subscription "${input}" — see m365_subscribed_skus (${skus.map((s) => s.skuPartNumber).join(", ") || "none"})`);
179
+ }
180
+ if (found.length > 1)
181
+ throw new M365Error("ambiguous_target", `ambiguous_target: several SKUs match "${input}" — pass the skuId`);
182
+ return found[0];
183
+ }
184
+ }
185
+ export const available = (s) => (s.prepaidUnits?.enabled ?? 0) - (s.consumedUnits ?? 0);