@aidalinfo/m365-mcp 0.1.0 → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aidalinfo / Pulse myIT
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -6,11 +6,14 @@ licences, Microsoft Teams, and tenant information for diagnosis — with targete
6
6
  - **`readonly`** (default): read tools only. The write identity is **not even loaded**.
7
7
  - **`full`**: read tools **plus** targeted write tools (user attributes from an allowlist,
8
8
  enable/disable account, licences, group members, team members, channels, team settings),
9
- signed by a **separate Entra application**, per family (`M365_WRITE_FAMILIES`).
9
+ signed by a **separate Entra application**, per family (`M365_WRITE_FAMILIES`). The optional
10
+ `entra-applications` family is absent by default and uses a third dedicated identity.
10
11
 
11
- There is **no raw Graph request tool** (neither read nor write), no `beta` endpoint, and the v1
12
- deliberately leaves out: Entra roles, applications / service principals / credentials, password
13
- resets, permanent deletions, Conditional Access, and any mail / chat / meeting / file content.
12
+ There is **no raw Graph request tool** (neither read nor write) and no `beta` endpoint. Entra
13
+ application management is limited to allowlisted application/service-principal properties. Public
14
+ certificate metadata and federated identity credentials are read-only in v1. V1 has no certificate
15
+ or federated-credential write, deletion, client-secret creation/return, private-key handling,
16
+ programmatic consent, app-role-assignment or OAuth2-grant write.
14
17
 
15
18
  ```text
16
19
  Agent Pulse / Vulcain
@@ -22,11 +25,12 @@ Agent Pulse / Vulcain
22
25
  Microsoft Graph v1.0
23
26
  │
24
27
  ├── Entra app "m365-mcp-read" (every mode — read permissions only)
25
- └── Entra app "m365-mcp-write" (full mode only — write permissions only)
28
+ ├── Entra app "m365-mcp-write" (full mode only — general write permissions)
29
+ └── Entra app "m365-mcp-entra" (optional entra-applications family only)
26
30
  ```
27
31
 
28
32
  Do **not** reuse Pulse Chat's Microsoft SSO application, nor the application behind personal
29
- Outlook / calendar connectors: the two identities above are dedicated to this server.
33
+ Outlook / calendar connectors: these identities are dedicated to this server.
30
34
 
31
35
  ## Tools
32
36
 
@@ -88,10 +92,46 @@ Each error carries Microsoft's `request-id` (quote it to Microsoft support) and
88
92
  | `m365_team_channel_create` | `teams` | Standard channel | No-op if the name exists; never retried on 5xx (no duplicate) |
89
93
  | `m365_team_channel_update` | `teams` | Rename / describe a channel | General channel cannot be renamed |
90
94
  | `m365_team_settings_update` | `teams` | Allowlisted member / guest / messaging / fun settings | Strict schema |
95
+ | `m365_entra_applications` / `_application_info` | `entra-applications` | Typed application-registration inventory/details | Dedicated identity; response and nested collections bounded; certificate material reduced to public metadata |
96
+ | `m365_entra_service_principals` / `_service_principal_info` | `entra-applications` | Typed enterprise-application inventory/details | Dedicated identity; allowlisted fields only |
97
+ | `m365_entra_application_requested_permissions` / `_service_principal_effective_permissions` | `entra-applications` | Requested permissions and read-only inspection of effective app-role assignments / delegated grants | Effective delegated grants additionally require read-only `Directory.Read.All`; never grants consent or writes assignments/grants |
98
+ | `m365_entra_application_federated_credentials` | `entra-applications` | First 20 federated identity credentials | Application ownership is verified first; no external token or secret is read |
99
+ | `m365_entra_application_create` / `_update` | `entra-applications` | Idempotent application upsert by URL-safe `uniqueName`, or update allowlisted scalar properties | `requiredResourceAccess` is deliberately absent from write schemas; ownership by the dedicated identity; no delete, secret or private key |
100
+ | `m365_entra_service_principal_create` / `_update` | `entra-applications` | Idempotent service-principal upsert by `appId`, or update allowlisted scalar properties | Both the linked application and service principal must be owned; no role assignment or consent write |
91
101
 
92
102
  `m365_group_create` / `m365_team_create` are **not** in v1 (they would need `Group.ReadWrite.All`
93
103
  / `Team.Create`); add them later behind a dedicated flag if needed.
94
104
 
105
+ ### `entra-applications` bootstrap and ownership boundary
106
+
107
+ Create a third single-tenant app for this family and grant it exactly
108
+ `Application.ReadWrite.OwnedBy` and read-only `Directory.Read.All` (admin consent). Any additional
109
+ Graph application role is refused. Its client id must differ from the read and write
110
+ identities. The family is not enabled unless `entra-applications` is explicitly present in
111
+ `M365_WRITE_FAMILIES`, `M365_ENTRA_*` contains exactly one credential, and
112
+ `M365_WRITE_KILL_SWITCH_FILE` is configured.
113
+
114
+ `Application.ReadWrite.OwnedBy` does not ownership-filter tenant-wide list responses. Therefore every
115
+ mutation of an existing application re-reads `/owners` during preview and again immediately before
116
+ the Graph mutation. Application creation with `Application.ReadWrite.OwnedBy` establishes ownership for the calling service principal by Graph; the server verifies that ownership after creation without requiring a broader owner-write permission;
117
+ service-principal writes require both a linked, owned local application registration and ownership of
118
+ the service principal itself. For a newly created service principal, the server establishes the
119
+ dedicated identity as owner when Graph did not do so automatically, then verifies ownership.
120
+ Federated-credential reads also verify ownership before reading the collection.
121
+ The dedicated identity service principal itself must already exist in the tenant (normal after admin
122
+ consent); inability to resolve it uniquely stops the operation. Newly created objects can be
123
+ eventually consistent: post-write verification is retried only three times with bounded delays. For
124
+ this family verification is fail-closed: if the mutation may have succeeded but ownership or the
125
+ requested resulting state cannot be verified, the tool returns an error and the audit result is
126
+ `success_unverified`, never the misleading values `success` or `failed`.
127
+
128
+ Hard exclusions remain: no deletion tools, no client-secret creation or return, no private-key input
129
+ or output, no certificate or federated-credential write, no programmatic consent, no
130
+ `appRoleAssignment`/`oAuth2PermissionGrant` write, and no raw
131
+ Graph tool. `Application.ReadWrite.All`, `AppRoleAssignment.ReadWrite.All`,
132
+ `DelegatedPermissionGrant.ReadWrite.All` and `Directory.ReadWrite.All` are refused for the dedicated
133
+ identity even when `M365_ALLOW_BROAD_PERMISSIONS=true`.
134
+
95
135
  #### Two-step confirmation (every write tool)
96
136
 
97
137
  1. **Preview** — call the tool **without** `confirmToken`. Nothing is changed: the target is
@@ -110,14 +150,13 @@ nothing by itself. **Pulse Chat must still obtain an explicit, traced human appr
110
150
  second call**; pass its id as `approvalId` so the audit line can be correlated (it is recorded as
111
151
  `approvalRef: { id, verified: false }` — a free string is never treated as an authorisation).
112
152
 
113
- All reads done for a write (resolution, state before/after) use the **read** identity; only the
114
- mutation itself uses the write identity. The read identity therefore needs the permissions of the
115
- last column of the write matrix below — `m365_capabilities` reports a write tool as
116
- `missing on read identity (preview)` otherwise.
153
+ General write-family reads (resolution, state before/after) use the **read** identity and mutations
154
+ use the write identity. The `entra-applications` family instead uses its dedicated **entra** identity
155
+ for both its reads and its tightly scoped writes.
117
156
 
118
157
  #### Audit trail
119
158
 
120
- Every write attempt — `preview`, `success`, `noop`, `refused`, `failed` — produces one JSON line on
159
+ Every write attempt — `preview`, `success`, `success_unverified`, `noop`, `refused`, `failed` — produces one JSON line on
121
160
  **stderr** (stdout is the MCP transport) and, with `M365_AUDIT_LOG_FILE`, appended to that file
122
161
  (mode 0600):
123
162
 
@@ -191,6 +230,26 @@ Notes:
191
230
  attributes of `m365_user_update` (the `User-*` permissions cover only phones, mail or password
192
231
  profile). Drop the `users` family from `M365_WRITE_FAMILIES` if you do not need it.
193
232
 
233
+ ### Entra applications — dedicated entra identity (preview and execution)
234
+
235
+ This identity must contain exactly `Application.ReadWrite.OwnedBy` plus read-only
236
+ `Directory.Read.All`; `M365_ALLOW_BROAD_PERMISSIONS` never expands this exact allowlist.
237
+
238
+ | Tool | Access | Endpoint(s) |
239
+ |---|---|---|
240
+ | inventory, info, requested permissions | read | `GET /applications`, `GET /applications/{id}`, `GET /servicePrincipals` |
241
+ | effective permissions | read | bounded `GET /servicePrincipals/{id}/appRoleAssignments` and `GET /oauth2PermissionGrants`; output includes `truncated` |
242
+ | federated credentials | read | `GET /applications/{id}/federatedIdentityCredentials` (`$select` only; no `$top`) |
243
+ | application create/upsert | write | `PATCH /applications(uniqueName='{uniqueName}')` with `Prefer: create-if-missing` (no owners `/$ref` call) |
244
+ | application update | write | `PATCH /applications/{id}` |
245
+ | service-principal create/upsert | write | `PATCH /servicePrincipals(appId='{appId}')` with `Prefer: create-if-missing`; `POST /servicePrincipals/{id}/owners/$ref` only when ownership was not established automatically |
246
+ | service-principal update | write | `PATCH /servicePrincipals/{id}` |
247
+
248
+ V1 can read `requiredResourceAccess`, certificates and federated credentials, but exposes no write
249
+ field or endpoint for them. Scalar PATCH operations re-read the targeted fields immediately before
250
+ the request and preserve unrelated fields. This implementation does not claim atomic concurrency
251
+ control: a narrow residual last-writer-wins window remains and is documented explicitly.
252
+
194
253
  ### Refused by default
195
254
 
196
255
  The token provider **refuses** a token carrying any of: `Directory.ReadWrite.All`,
@@ -215,8 +274,9 @@ GUID: `common`, `organizations` or a domain name are refused — no implicit mul
215
274
  | `M365_READ_CERT_PATH` / `M365_READ_KEY_PATH` | — | **2nd choice** — PEM certificate (+ unencrypted private key, in the same file or `KEY_PATH`) |
216
275
  | `M365_READ_CLIENT_SECRET` | — | **Acceptance testing only** — warning printed at startup |
217
276
  | `M365_WRITE_*` | — | Same variables for the write application, **read only when `M365_MODE=full`** — missing ⇒ startup failure; same client id as read ⇒ startup failure |
218
- | `M365_WRITE_FAMILIES` | all | Comma list of `users`, `licenses`, `groups`, `teams` — or `none` |
219
- | `M365_WRITE_KILL_SWITCH_FILE` | — | While this file exists, every write is refused (checked at each call) |
277
+ | `M365_WRITE_FAMILIES` | `users,licenses,groups,teams` | Comma list; add `entra-applications` explicitly to enable that high-risk family, or use `none` |
278
+ | `M365_ENTRA_*` | — | Third dedicated identity, loaded only for `entra-applications`; same credential forms as read/write; client id must differ from both |
279
+ | `M365_WRITE_KILL_SWITCH_FILE` | — | While this file exists, every write is refused (checked at each call); configuration is mandatory when `entra-applications` is enabled |
220
280
  | `M365_AUDIT_LOG_FILE` | — | Also append the audit trail to this file |
221
281
  | `M365_AUDIT_TARGET_ID` | `id` | `id` or `hash` (keyed HMAC-SHA256 of the object id — a plain hash of a GUID would be reversible by anyone who can list the directory) |
222
282
  | `M365_AUDIT_HASH_KEY` | — | Required with `hash`: ≥ 16 characters, kept secret (redacted everywhere) |
@@ -248,11 +308,12 @@ claude mcp add m365 --scope user \
248
308
 
249
309
  ## Runbook — Entra identities
250
310
 
251
- ### 1. Create the two applications
311
+ ### 1. Create the applications
252
312
 
253
- Entra admin center → **Identity → Applications → App registrations → New registration**, twice:
254
- `m365-mcp-read` and `m365-mcp-write`, *Accounts in this organizational directory only* (single
255
- tenant), no redirect URI. Note each **Application (client) ID** and the **Directory (tenant) ID**.
313
+ Entra admin center → **Identity → Applications → App registrations → New registration**: create
314
+ `m365-mcp-read` and `m365-mcp-write`, plus `m365-mcp-entra` if the optional `entra-applications`
315
+ family is used. Choose *Accounts in this organizational directory only* (single tenant), with no
316
+ redirect URI. Note each **Application (client) ID** and the **Directory (tenant) ID**.
256
317
  Set **Owners** to named administrators (not a technical account) and, under *Enterprise
257
318
  applications → the app → Properties*, *Visible to users* = No.
258
319
 
package/dist/audit.js CHANGED
@@ -24,7 +24,13 @@ export class AuditLogger {
24
24
  tool: e.tool,
25
25
  mode: this.ctx.mode,
26
26
  tenant: this.ctx.tenant,
27
- identity: this.ctx.writeClientId ? { role: "write", clientId: this.ctx.writeClientId } : undefined,
27
+ identity: e.identity === "entra"
28
+ ? this.ctx.entraClientId
29
+ ? { role: "entra", clientId: this.ctx.entraClientId }
30
+ : undefined
31
+ : this.ctx.writeClientId
32
+ ? { role: "write", clientId: this.ctx.writeClientId }
33
+ : undefined,
28
34
  targetType: e.targetType,
29
35
  targetId,
30
36
  operation: e.operation,
@@ -16,9 +16,11 @@ export const FORBIDDEN_ROLES = [
16
16
  "RoleManagement.ReadWrite.Directory",
17
17
  "Application.ReadWrite.All",
18
18
  "AppRoleAssignment.ReadWrite.All",
19
+ "DelegatedPermissionGrant.ReadWrite.All",
19
20
  "Policy.ReadWrite.ConditionalAccess",
20
21
  "UserAuthenticationMethod.ReadWrite.All",
21
22
  ];
23
+ export const ENTRA_ALLOWED_ROLES = ["Application.ReadWrite.OwnedBy", "Directory.Read.All"];
22
24
  function decodeClaims(jwt) {
23
25
  const part = jwt.split(".")[1];
24
26
  if (!part)
@@ -125,7 +127,16 @@ export class TokenProvider {
125
127
  }
126
128
  const roles = Array.isArray(claims.roles) ? claims.roles.map(String).sort() : [];
127
129
  const forbidden = roles.filter((r) => FORBIDDEN_ROLES.includes(r));
128
- if (forbidden.length && !this.opts.allowBroadPermissions) {
130
+ if (this.role === "entra") {
131
+ const missing = ENTRA_ALLOWED_ROLES.filter((r) => !roles.includes(r));
132
+ if (missing.length)
133
+ throw new M365Error("permission_missing", `permission_missing: the entra identity must hold exactly ${ENTRA_ALLOWED_ROLES.join(", ")} (missing ${missing.join(", ")})`);
134
+ const extra = roles.filter((r) => !ENTRA_ALLOWED_ROLES.includes(r));
135
+ if (extra.length)
136
+ throw new M365Error("forbidden_permission", `forbidden_permission: the entra identity holds roles outside its exact allowlist: ${extra.join(", ")}`);
137
+ }
138
+ const hardForbidden = this.role === "entra" && forbidden.length > 0;
139
+ if (forbidden.length && (hardForbidden || !this.opts.allowBroadPermissions)) {
129
140
  throw new M365Error("forbidden_permission", `forbidden_permission: the ${this.role} application holds ${forbidden.join(", ")} — refused by policy. Remove these permissions from the Entra app (or set M365_ALLOW_BROAD_PERMISSIONS=true knowingly).`);
130
141
  }
131
142
  return { tenantId: tid, appId, roles, expiresAt: "" };
package/dist/config.js CHANGED
@@ -7,7 +7,9 @@
7
7
  * - the write identity (M365_WRITE_*) is read from the environment only when M365_MODE=full,
8
8
  * so revoking it removes the writes and keeps the read-only diagnostics.
9
9
  */
10
- export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams"];
10
+ import { isAbsolute } from "node:path";
11
+ export const WRITE_FAMILIES = ["users", "licenses", "groups", "teams", "entra-applications"];
12
+ export const DEFAULT_WRITE_FAMILIES = ["users", "licenses", "groups", "teams"];
11
13
  export class ConfigError extends Error {
12
14
  constructor(message) {
13
15
  super(message);
@@ -34,10 +36,10 @@ function parseBool(env, name) {
34
36
  throw new ConfigError(`${name} must be true or false — got "${v}"`);
35
37
  }
36
38
  function loadIdentity(env, role) {
37
- const p = role === "read" ? "M365_READ_" : "M365_WRITE_";
39
+ const p = role === "read" ? "M365_READ_" : role === "write" ? "M365_WRITE_" : "M365_ENTRA_";
38
40
  const clientId = get(env, `${p}CLIENT_ID`);
39
41
  if (!clientId)
40
- throw new ConfigError(`${p}CLIENT_ID is required${role === "write" ? " in full mode" : ""}`);
42
+ throw new ConfigError(`${p}CLIENT_ID is required${role === "write" ? " in full mode" : role === "entra" ? " when entra-applications is enabled" : ""}`);
41
43
  if (!GUID_RE.test(clientId))
42
44
  throw new ConfigError(`${p}CLIENT_ID must be an application (client) id GUID`);
43
45
  const tokenFile = get(env, `${p}FEDERATED_TOKEN_FILE`);
@@ -62,7 +64,7 @@ function loadIdentity(env, role) {
62
64
  }
63
65
  function parseFamilies(raw) {
64
66
  if (raw === undefined)
65
- return new Set(WRITE_FAMILIES);
67
+ return new Set(DEFAULT_WRITE_FAMILIES);
66
68
  if (raw === "none")
67
69
  return new Set();
68
70
  const out = new Set();
@@ -87,6 +89,16 @@ export function loadConfig(env) {
87
89
  if (write && write.clientId.toLowerCase() === read.clientId.toLowerCase()) {
88
90
  throw new ConfigError("M365_WRITE_CLIENT_ID must be a different Entra application than M365_READ_CLIENT_ID");
89
91
  }
92
+ const writeFamilies = mode === "full" ? parseFamilies(get(env, "M365_WRITE_FAMILIES")) : new Set();
93
+ const entra = writeFamilies.has("entra-applications") ? loadIdentity(env, "entra") : undefined;
94
+ const killSwitchFile = get(env, "M365_WRITE_KILL_SWITCH_FILE");
95
+ if (entra && !killSwitchFile)
96
+ throw new ConfigError("M365_WRITE_KILL_SWITCH_FILE is required when entra-applications is enabled");
97
+ if (entra && killSwitchFile && !isAbsolute(killSwitchFile))
98
+ throw new ConfigError("M365_WRITE_KILL_SWITCH_FILE must be an absolute path");
99
+ if (entra && [read.clientId, write?.clientId].filter(Boolean).some((id) => id.toLowerCase() === entra.clientId.toLowerCase())) {
100
+ throw new ConfigError("M365_ENTRA_CLIENT_ID must be a different Entra application than M365_READ_CLIENT_ID and M365_WRITE_CLIENT_ID");
101
+ }
90
102
  const auditTarget = get(env, "M365_AUDIT_TARGET_ID") ?? "id";
91
103
  if (auditTarget !== "id" && auditTarget !== "hash")
92
104
  throw new ConfigError(`M365_AUDIT_TARGET_ID must be "id" or "hash"`);
@@ -95,7 +107,7 @@ export function loadConfig(env) {
95
107
  throw new ConfigError("M365_AUDIT_TARGET_ID=hash needs M365_AUDIT_HASH_KEY (at least 16 characters, kept secret)");
96
108
  }
97
109
  const warnings = [];
98
- for (const id of [read, write]) {
110
+ for (const id of [read, write, entra]) {
99
111
  if (id?.auth.kind === "secret") {
100
112
  warnings.push(`⚠ the ${id.role} identity authenticates with a client secret — acceptable for temporary acceptance testing only; use workload identity federation or a certificate in production`);
101
113
  }
@@ -108,12 +120,13 @@ export function loadConfig(env) {
108
120
  tenantId: tenantId.toLowerCase(),
109
121
  read,
110
122
  write,
111
- writeFamilies: parseFamilies(get(env, "M365_WRITE_FAMILIES")),
123
+ entra,
124
+ writeFamilies,
112
125
  signInAudit: parseBool(env, "M365_ENABLE_SIGNIN_AUDIT"),
113
126
  auditLogFile: get(env, "M365_AUDIT_LOG_FILE"),
114
127
  auditTargetId: auditTarget,
115
128
  auditHashKey,
116
- killSwitchFile: get(env, "M365_WRITE_KILL_SWITCH_FILE"),
129
+ killSwitchFile,
117
130
  allowBroadPermissions,
118
131
  warnings,
119
132
  };
package/dist/context.js CHANGED
@@ -18,12 +18,14 @@ export function createContext(config, deps = {}) {
18
18
  const read = new TokenProvider(config.read, config.tenantId, tokenOpts, deps.credentials?.read);
19
19
  // the write identity is constructed only in full mode: in readonly mode no write credential is ever loaded
20
20
  const write = config.mode === "full" && config.write ? new TokenProvider(config.write, config.tenantId, tokenOpts, deps.credentials?.write) : undefined;
21
+ const entra = config.entra ? new TokenProvider(config.entra, config.tenantId, tokenOpts, deps.credentials?.entra) : undefined;
21
22
  if (config.mode === "full" && !write)
22
23
  throw new Error("M365_MODE=full requires the write identity (M365_WRITE_CLIENT_ID + a credential)");
23
24
  const killSwitchActive = () => Boolean(config.killSwitchFile && existsSync(config.killSwitchFile));
24
25
  const graph = new GraphClient({
25
26
  read,
26
27
  write,
28
+ entra,
27
29
  baseUrl: deps.graphBaseUrl,
28
30
  fetcher: deps.fetcher,
29
31
  sleep: deps.sleep,
@@ -37,13 +39,14 @@ export function createContext(config, deps = {}) {
37
39
  return {
38
40
  config,
39
41
  graph,
40
- identities: { read, write },
42
+ identities: { read, write, entra },
41
43
  cursors: new CursorStore(now),
42
44
  confirmations: new Confirmations(now),
43
45
  audit: new AuditLogger({
44
46
  mode: config.mode,
45
47
  tenant: config.tenantId,
46
48
  writeClientId: write?.clientId,
49
+ entraClientId: entra?.clientId,
47
50
  targetIdPolicy: config.auditTargetId,
48
51
  hashKey: config.auditHashKey,
49
52
  file: config.auditLogFile,
@@ -53,5 +56,6 @@ export function createContext(config, deps = {}) {
53
56
  skus: new SkuCache(graph, now),
54
57
  registered: [],
55
58
  killSwitchActive,
59
+ sleep: deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
56
60
  };
57
61
  }
@@ -57,6 +57,9 @@ export class GraphClient {
57
57
  get hasWrite() {
58
58
  return Boolean(this.opts.write);
59
59
  }
60
+ get hasEntra() {
61
+ return Boolean(this.opts.entra);
62
+ }
60
63
  /**
61
64
  * Accept a URL only if it is on the Graph host under the configured version — the guard applied
62
65
  * to every `@odata.nextLink` before it is followed, so pagination can never leave Graph.
@@ -95,6 +98,11 @@ export class GraphClient {
95
98
  throw new M365Error("refused", "refused: no write identity is loaded (M365_MODE=readonly)");
96
99
  return this.opts.write;
97
100
  }
101
+ if (role === "entra") {
102
+ if (!this.opts.entra)
103
+ throw new M365Error("refused", "refused: no dedicated entra-applications identity is loaded");
104
+ return this.opts.entra;
105
+ }
98
106
  return this.opts.read;
99
107
  }
100
108
  async send(method, url, opts) {
@@ -109,9 +117,14 @@ export class GraphClient {
109
117
  }
110
118
  const body = opts.body === undefined ? undefined : JSON.stringify(opts.body);
111
119
  for (let attempt = 0;; attempt++) {
112
- if (source.role === "write")
113
- this.opts.beforeWrite?.();
114
120
  const token = await source.getToken();
121
+ if (method !== "GET") {
122
+ if (source.role === "read")
123
+ throw new M365Error("refused", "refused: mutating Graph requests may not use the read identity");
124
+ // Last possible stop point: token acquisition may be slow, so the emergency switch is
125
+ // checked only after it completes and immediately before the network request.
126
+ this.opts.beforeWrite?.();
127
+ }
115
128
  let res;
116
129
  try {
117
130
  res = await this.fetcher(url, {
@@ -193,6 +193,17 @@ export const TOOL_SPECS = [
193
193
  permissions: ["TeamSettings.ReadWrite.All"],
194
194
  rsc: ["TeamSettings.ReadWrite.Group"],
195
195
  },
196
+ { tool: "m365_entra_applications", access: "read", identity: "entra", family: "entra-applications", endpoints: ["GET /applications"], permissions: ["Application.ReadWrite.OwnedBy"] },
197
+ { tool: "m365_entra_application_info", access: "read", identity: "entra", family: "entra-applications", endpoints: ["GET /applications/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
198
+ { tool: "m365_entra_service_principals", access: "read", identity: "entra", family: "entra-applications", endpoints: ["GET /servicePrincipals"], permissions: ["Application.ReadWrite.OwnedBy"] },
199
+ { tool: "m365_entra_service_principal_info", access: "read", identity: "entra", family: "entra-applications", endpoints: ["GET /servicePrincipals/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
200
+ { tool: "m365_entra_application_requested_permissions", access: "read", identity: "entra", family: "entra-applications", endpoints: ["GET /applications/{id}", "GET /servicePrincipals"], permissions: ["Application.ReadWrite.OwnedBy"] },
201
+ { tool: "m365_entra_service_principal_effective_permissions", access: "read", identity: "entra", family: "entra-applications", endpoints: ["GET /servicePrincipals/{id}/appRoleAssignments", "GET /oauth2PermissionGrants"], permissions: ["Application.ReadWrite.OwnedBy", "Directory.Read.All"], note: "Directory.Read.All is read-only here and is required to inspect delegated OAuth2 grants" },
202
+ { tool: "m365_entra_application_federated_credentials", access: "read", identity: "entra", family: "entra-applications", endpoints: ["GET /applications/{id}/federatedIdentityCredentials"], permissions: ["Application.ReadWrite.OwnedBy"] },
203
+ { tool: "m365_entra_application_create", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /applications(uniqueName='{uniqueName}') + Prefer: create-if-missing"], permissions: ["Application.ReadWrite.OwnedBy"] },
204
+ { tool: "m365_entra_application_update", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /applications/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
205
+ { tool: "m365_entra_service_principal_create", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /servicePrincipals(appId='{appId}') + Prefer: create-if-missing", "POST /servicePrincipals/{id}/owners/$ref when Graph did not establish ownership"], permissions: ["Application.ReadWrite.OwnedBy"] },
206
+ { tool: "m365_entra_service_principal_update", access: "write", identity: "entra", family: "entra-applications", planPermissions: ["Application.ReadWrite.OwnedBy"], endpoints: ["PATCH /servicePrincipals/{id}"], permissions: ["Application.ReadWrite.OwnedBy"] },
196
207
  ];
197
208
  export const specOf = (tool) => TOOL_SPECS.find((s) => s.tool === tool);
198
209
  /** Does this set of token roles satisfy the tool? RSC grants are invisible in the token: "unknown" then. */
package/dist/register.js CHANGED
@@ -8,6 +8,8 @@ import { registerUserWriteTools } from "./tools/users-write.js";
8
8
  import { registerLicenseWriteTools } from "./tools/licenses-write.js";
9
9
  import { registerGroupWriteTools } from "./tools/groups-write.js";
10
10
  import { registerTeamWriteTools } from "./tools/teams-write.js";
11
+ import { registerEntraApplicationReadTools } from "./tools/entra-applications.js";
12
+ import { registerEntraApplicationWriteTools } from "./tools/entra-applications-write.js";
11
13
  /**
12
14
  * Read tools always register. Write tools register only in full mode, with a write identity,
13
15
  * and per family (M365_WRITE_FAMILIES) — in readonly mode they do not exist at all.
@@ -45,6 +47,12 @@ export function registerTools(server, ctx) {
45
47
  registerGroupWriteTools(tracking, ctx);
46
48
  if (f.has("teams"))
47
49
  registerTeamWriteTools(tracking, ctx);
50
+ if (f.has("entra-applications")) {
51
+ if (!ctx.identities.entra || !ctx.graph.hasEntra)
52
+ throw new Error("entra-applications requires the dedicated identity (M365_ENTRA_*)");
53
+ registerEntraApplicationReadTools(tracking, ctx);
54
+ registerEntraApplicationWriteTools(tracking, ctx);
55
+ }
48
56
  }
49
57
  ctx.registered.splice(0, ctx.registered.length, ...names);
50
58
  return names;
@@ -3,11 +3,11 @@ import { FORBIDDEN_ROLES } from "../auth/token-provider.js";
3
3
  import { isWritePermission, permissionStatus, planStatus, TOOL_SPECS } from "../permissions.js";
4
4
  import { jsonBlock, textResult } from "./common.js";
5
5
  export const SERVER_INSTRUCTIONS = [
6
- "Microsoft 365 MCP over Microsoft Graph (v1.0): Entra ID users and groups, licences, Teams. Read-only unless M365_MODE=full.",
6
+ "Microsoft 365 MCP over Microsoft Graph (v1.0): Entra ID users, groups and explicitly enabled application management, licences, Teams. Read-only unless M365_MODE=full.",
7
7
  "Start with m365_capabilities: it shows the mode, the tools registered and, for each, whether the Graph permission is present in the identity's token.",
8
8
  "Lists are paginated: pass the returned cursor to get the next page. A refused or unavailable API answers with an explicit error code (permission_missing, unsupported_by_tenant…), never an empty list.",
9
9
  "Writes ([WRITE] tools) are two-step: call once without confirmToken to get a preview and a token, then call again with the same arguments and the token. Get the user's explicit approval before the second call.",
10
- "Out of scope: Entra roles, applications and credentials, passwords, Conditional Access, permanent deletions, mail/chat/meeting/file content.",
10
+ "Out of scope: Entra roles, deletions, client secrets, private keys, programmatic consent, app-role-assignment/OAuth2-grant writes, passwords, Conditional Access, mail/chat/meeting/file content.",
11
11
  ].join("\n");
12
12
  async function inspect(id) {
13
13
  const described = { ...id.describe(), role: id.role };
@@ -24,13 +24,14 @@ export function registerCapabilityTools(server, ctx) {
24
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
25
  const read = await inspect(ctx.identities.read);
26
26
  const write = ctx.identities.write ? await inspect(ctx.identities.write) : undefined;
27
+ const entra = ctx.identities.entra ? await inspect(ctx.identities.entra) : undefined;
27
28
  const warnings = [...ctx.config.warnings];
28
29
  if (read.ok) {
29
30
  const writes = read.roles.filter(isWritePermission);
30
31
  if (writes.length)
31
32
  warnings.push(`the READ identity holds write permissions (${writes.join(", ")}) — remove them to keep the identities separate`);
32
33
  }
33
- for (const id of [read, write]) {
34
+ for (const id of [read, write, entra]) {
34
35
  if (id?.ok) {
35
36
  const broad = id.roles.filter((r) => FORBIDDEN_ROLES.includes(r));
36
37
  if (broad.length)
@@ -41,17 +42,19 @@ export function registerCapabilityTools(server, ctx) {
41
42
  }
42
43
  }
43
44
  const tools = TOOL_SPECS.filter((s) => ctx.registered.includes(s.tool)).map((s) => {
44
- const id = s.access === "write" ? write : read;
45
+ const id = s.identity === "entra" ? entra : s.access === "write" ? write : read;
45
46
  let status = s.permissions.length === 0 ? "granted" : id?.ok ? permissionStatus(s, id.roles) : "unknown (no token)";
46
47
  // 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)";
48
+ if (s.planPermissions && status === "granted") {
49
+ const preview = s.identity === "entra" ? entra : read;
50
+ status = preview?.ok ? (planStatus(s, preview.roles) === "granted" ? "granted" : `missing on ${s.identity === "entra" ? "entra" : "read"} identity (preview)`) : "unknown (no preview token)";
51
+ }
49
52
  return {
50
53
  tool: s.tool,
51
54
  access: s.access,
52
55
  status,
53
56
  needs: s.permissions.join(" + ") || "—",
54
- ...(s.planPermissions ? { previewNeedsOnRead: s.planPermissions.join(" + ") } : {}),
57
+ ...(s.planPermissions ? { previewIdentity: s.identity === "entra" ? "entra" : "read", previewNeeds: s.planPermissions.join(" + ") } : {}),
55
58
  ...(s.rsc ? { rsc: s.rsc.join(", ") } : {}),
56
59
  };
57
60
  });
@@ -64,10 +67,11 @@ export function registerCapabilityTools(server, ctx) {
64
67
  `Tenant: ${ctx.config.tenantId}`,
65
68
  killSwitch ? `⛔ Kill switch ACTIVE (${ctx.config.killSwitchFile}) — every write is refused` : "",
66
69
  `Sign-in audit tool: ${ctx.config.signInAudit ? "enabled" : "disabled (M365_ENABLE_SIGNIN_AUDIT)"}`,
70
+ `Entra applications family: ${ctx.config.writeFamilies.has("entra-applications") ? "enabled (owned objects only)" : "disabled (explicit M365_WRITE_FAMILIES opt-in required)"}`,
67
71
  `Registered tools: ${ctx.registered.length}`,
68
72
  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
73
  warnings.length ? `\n## Warnings\n${warnings.map((w) => `- ${w}`).join("\n")}` : "",
70
74
  ].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)}`);
75
+ return textResult(`${lines.join("\n")}\n\n## Identities\n${jsonBlock({ read, write: write ?? "not loaded (readonly mode)", entra: entra ?? "not loaded (family disabled)" })}\n\n## Tools\n${jsonBlock(tools)}`);
72
76
  });
73
77
  }
@@ -78,7 +78,7 @@ export async function listPage(ctx, tool, first, limit, cursor) {
78
78
  else {
79
79
  url = ctx.graph.urlFor(first.path, { ...first.query, ...(first.supportsTop === false ? {} : { $top: limit }) });
80
80
  }
81
- const res = await ctx.graph.getUrl(url, { headers });
81
+ const res = await ctx.graph.getUrl(url, { headers, identity: first.identity });
82
82
  const value = Array.isArray(res.data?.value) ? res.data.value : [];
83
83
  const items = value.slice(offset, offset + limit);
84
84
  let nextCursor;
@@ -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
+ }
@@ -22,6 +22,7 @@ export const confirmParams = {
22
22
  */
23
23
  export async function runWrite(spec) {
24
24
  const { ctx, tool, approvalId } = spec;
25
+ const identity = spec.identity ?? "write";
25
26
  let plan;
26
27
  const requestIds = [];
27
28
  try {
@@ -32,11 +33,11 @@ export async function runWrite(spec) {
32
33
  const binding = { tool, targetId: plan.targetId, state: plan.before, plan: plan.change };
33
34
  const head = `Target: ${plan.targetType} ${plan.targetLabel} (${plan.targetId})\nOperation: ${plan.operation}`;
34
35
  if (plan.refuse) {
35
- ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "refused", errorCode: "refused", approvalId });
36
+ ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "refused", errorCode: "refused", approvalId, identity });
36
37
  return errorResult(new M365Error("refused", `refused: ${plan.refuse}`));
37
38
  }
38
39
  if (!spec.confirmToken) {
39
- ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "preview", approvalId });
40
+ ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "preview", approvalId, identity });
40
41
  if (plan.noop) {
41
42
  return textResult(`# Preview — ${tool}\n\n${head}\n\nNothing to do: ${plan.noop}\n\nCurrent state:\n${jsonBlock(plan.before)}`);
42
43
  }
@@ -51,18 +52,25 @@ export async function runWrite(spec) {
51
52
  throw new M365Error("refused", `refused: writes are disabled by the kill switch (${ctx.config.killSwitchFile} exists)`);
52
53
  }
53
54
  if (plan.noop) {
54
- ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "noop", approvalId });
55
+ ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "noop", approvalId, identity });
55
56
  return textResult(`# ${tool} — nothing to do\n\n${head}\n\n${plan.noop}\n\nState:\n${jsonBlock(plan.before)}`);
56
57
  }
57
58
  requestIds.push(...(await spec.execute(plan)));
58
59
  let afterText;
60
+ let result = "success";
59
61
  try {
60
62
  afterText = jsonBlock(await spec.after(plan));
61
63
  }
62
64
  catch (err) {
63
- afterText = `(could not re-read the target: ${toM365Error(err).code} — the change itself succeeded)`;
65
+ result = "success_unverified";
66
+ const verificationError = toM365Error(err);
67
+ afterText = `(could not re-read the target: ${verificationError.code} — the change succeeded but its resulting state is unverified)`;
68
+ ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result, errorCode: verificationError.code, graphRequestIds: requestIds, approvalId, identity });
69
+ if (spec.verificationRequired) {
70
+ return errorResult(new M365Error("transient", `transient: ${tool} changed the target but post-write verification failed; inspect the target before retrying`, { requestId: requestIds.filter(Boolean).at(-1) }));
71
+ }
64
72
  }
65
- ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result: "success", graphRequestIds: requestIds, approvalId });
73
+ ctx.audit.log({ tool, targetType: plan.targetType, targetId: plan.targetId, operation: plan.operation, result, graphRequestIds: requestIds, approvalId, identity });
66
74
  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
75
  }
68
76
  catch (err) {
@@ -79,6 +87,7 @@ export async function runWrite(spec) {
79
87
  errorCode: e.code,
80
88
  graphRequestIds: requestIds,
81
89
  approvalId,
90
+ identity,
82
91
  });
83
92
  return errorResult(e);
84
93
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aidalinfo/m365-mcp",
3
- "version": "0.1.0",
4
- "description": "Microsoft 365 MCP server over Microsoft Graph — Entra ID users & groups, licences, Teams. Read-only by default; full mode uses a separate Entra write identity with two-step confirmed, audited writes",
3
+ "version": "0.2.0",
4
+ "description": "Microsoft 365 MCP server over Microsoft Graph — Entra ID users, groups and applications, licences, Teams. Read-only by default; full mode uses separate scoped identities with two-step confirmed, audited writes",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "bin": {
@@ -9,7 +9,8 @@
9
9
  },
10
10
  "files": [
11
11
  "dist",
12
- "README.md"
12
+ "README.md",
13
+ "LICENSE"
13
14
  ],
14
15
  "publishConfig": {
15
16
  "access": "public"
@@ -43,8 +44,8 @@
43
44
  "smoke": "node smoke.mjs"
44
45
  },
45
46
  "dependencies": {
46
- "@modelcontextprotocol/sdk": "^1.27.0",
47
- "zod": "^4.4.3"
47
+ "@modelcontextprotocol/sdk": "^1.32.0",
48
+ "zod": "^4.6.5"
48
49
  },
49
50
  "devDependencies": {
50
51
  "@jest/globals": "^30.3.0",