@softeria/ms-365-mcp-server 0.177.0 → 0.179.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -589,10 +589,28 @@ MS365_MCP_CLIENT_SECRET=<secret> \
589
589
  npx @softeria/ms-365-mcp-server --app-mode --read-only
590
590
  ```
591
591
 
592
- - Use your own app registration with **application** permissions and admin consent. Use either
593
- `MS365_MCP_CLIENT_SECRET` or `MS365_MCP_CLIENT_CERTIFICATE_PATH` (a PEM file with the certificate and its
594
- unencrypted private key), not both. `MS365_MCP_TENANT_ID` must be a real tenant, not `common`.
595
- - Tokens come from client credentials and are renewed automatically. Nothing is cached on disk.
592
+ - Use your own app registration with **application** permissions and admin consent, and set exactly one
593
+ credential:
594
+ - `MS365_MCP_CLIENT_SECRET`
595
+ - `MS365_MCP_CLIENT_CERTIFICATE_PATH`: a PEM file with the certificate and its unencrypted private key
596
+ - `MS365_MCP_FEDERATED_TOKEN_FILE`: a token from an identity provider the app trusts through
597
+ [workload identity federation](https://learn.microsoft.com/en-us/entra/workload-id/workload-identity-federation),
598
+ read again on every token request. On AKS set it to `$AZURE_FEDERATED_TOKEN_FILE`, which Kubernetes
599
+ keeps fresh. A GitHub Actions OIDC token is valid for 5 minutes, so writing it to a file once only
600
+ covers the first Graph token (about an hour) unless something rewrites the file. If Entra answers
601
+ `AADSTS700213`, set the federated credential's subject to the one quoted in the error (GitHub's
602
+ subject can include the owner and repo ids).
603
+
604
+ `MS365_MCP_TENANT_ID` must be a real tenant, not `common`.
605
+
606
+ - On an Azure host (App Service, Container Apps, VM, ...) set `MS365_MCP_MANAGED_IDENTITY=system`, or the
607
+ client id of a user-assigned identity, instead. No app registration, tenant id or secret is needed, and
608
+ Key Vault (`MS365_MCP_KEYVAULT_URL`) is not read. Graph
609
+ application permissions for a managed identity can't be granted in the portal;
610
+ [assign them with PowerShell or the Graph API](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/how-to-assign-app-role-managed-identity).
611
+ On Azure Container Instances, give the container one kind of identity: with both a system- and a
612
+ user-assigned identity, the system-assigned token request fails there.
613
+ - Tokens are renewed automatically. Nothing is cached on disk.
596
614
  - Only tools that work with application permissions are offered: the `/users/{user-id}` mail and calendar
597
615
  tools (pass a UPN or object id as `user-id`), users and groups, OneDrive/SharePoint drives and lists, Planner,
598
616
  Teams reads, presence, places and subscriptions. `/me` tools, Excel, OneNote and sending Teams chat or channel
@@ -818,10 +836,13 @@ Environment variables:
818
836
  - `MS365_MCP_FORCE_WORK_SCOPES=true|1`: Backwards compatibility for MS365_MCP_ORG_MODE
819
837
  - `MS365_MCP_APP_MODE=true|1`: Enable app mode (alternative to --app-mode flag)
820
838
  - `MS365_MCP_CLIENT_CERTIFICATE_PATH=<path>`: PEM file with a certificate and its unencrypted private key, used instead of `MS365_MCP_CLIENT_SECRET` in app mode
839
+ - `MS365_MCP_FEDERATED_TOKEN_FILE=<path>`: Federated token (workload identity federation), used instead of a secret or certificate in app mode
840
+ - `MS365_MCP_MANAGED_IDENTITY=system|<client id>`: Use the host's managed identity in app mode, instead of an app registration
821
841
  - `MS365_MCP_OUTPUT_FORMAT=toon`: Enable TOON output format (alternative to --toon flag)
822
842
  - `MS365_MCP_MAX_TOP=<n>`: Hard cap for Graph `$top` / `top` on list requests (positive integer). When the model passes a larger value, the server clamps it to `n` so responses stay smaller. Example: `MS365_MCP_MAX_TOP=15`
823
843
  - `MS365_MCP_MAX_PAGES=<n>`: Maximum number of pages followed when a tool is called with `fetchAllPages: true` (positive integer, default `100`). Bounds memory and latency for large result sets.
824
844
  - `MS365_MCP_MAX_ITEMS=<n>`: Maximum number of items accumulated when `fetchAllPages: true` (positive integer, default `10000`). Pagination stops and the response is truncated once this many items are collected.
845
+ - `MS365_MCP_TOOL_DEFINITION_BUDGET=<bytes>`: Opt in to trimming oversized request-body schemas so every tool fits a hosted connector's tool-definition budget (1 048 576 bytes of input schema per connector, admitted alphabetically — a tool that no longer fits is silently skipped). `4096` keeps a full org surface at ~78 % of that budget. Only bodies above the ration are trimmed, nested descriptions before structure, field names last. Unset (default): nothing is trimmed; the server still logs the total input-schema bytes served and, in HTTP mode, warns when the surface exceeds the connector budget.
825
846
  - `MS365_MCP_ALLOW_PAGINATION=0|false|no`: Disable multi-page following entirely. When set, the `fetchAllPages` parameter is not advertised on tools, and any request that still passes it returns only the first page (default: pagination enabled).
826
847
  - `MS365_MCP_BLOB_OUTPUT=true|1`: File download tools (`download-bytes`, `get-mail-message-mime`, `get-shared-mailbox-message-mime`, `get-mail-attachment-content`, `get-shared-mailbox-attachment-content`) answer a short JSON text block (`name`, `contentType`, `size`) and an MCP `EmbeddedResource` with `BlobResourceContents` (`uri`, `mimeType`, `blob`) instead of base64 JSON in text. The `uri`'s last segment is the optional `fileName` argument. Default: off. Alternative to the --blob-output flag.
827
848
  - `MS365_MCP_BLOB_MAX_BYTES=<n>`: With blob output on, the largest file a download tool reads (positive integer, default `5242880`). The server stops reading past it and answers an error naming the limit.
@@ -7,54 +7,127 @@ import { writeFileSync } from 'fs';
7
7
  import path from 'path';
8
8
  import { fileURLToPath } from 'url';
9
9
  import prettier from 'prettier';
10
- import { getToolsForPreset, listPresets } from '../src/tool-categories.js';
10
+ import { resolveAuthScopes } from '../src/auth.js';
11
+ import { buildToolsRegistry, isUtilityToolAvailable, UTILITY_TOOLS } from '../src/graph-tools.js';
12
+ import { getCombinedPresetPattern, listPresets } from '../src/tool-categories.js';
11
13
 
12
14
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
15
  const rootDir = path.resolve(__dirname, '..');
14
16
  const outFile = path.join(rootDir, 'PRESETS.md');
15
17
 
18
+ type Mode = 'full' | 'read-only';
19
+
20
+ function modeLabel(mode: Mode): string {
21
+ return mode === 'full' ? 'full' : 'read only';
22
+ }
23
+
24
+ function sectionAnchor(preset: string, mode: Mode): string {
25
+ return `${preset}-${mode}`;
26
+ }
27
+
28
+ /**
29
+ * Tools the server would expose for `--preset X` [--read-only], using the same
30
+ * Graph registry filters as runtime. Always pass orgMode so work-scoped tools that
31
+ * belong to a personal preset (e.g. SharePoint OneNote under `onenote`) are listed.
32
+ * httpMode=false keeps stdioOnly utilities in the catalog. Strip `enabled` so
33
+ * process opt-in (e.g. MS365_MCP_UPLOAD_DIRS) does not shrink the documented set.
34
+ */
35
+ function toolsForMode(preset: string, mode: Mode): string[] {
36
+ const readOnly = mode === 'read-only';
37
+ const enabledToolsRegex = new RegExp(getCombinedPresetPattern([preset]));
38
+ const graphTools = [...buildToolsRegistry(readOnly, true, enabledToolsRegex).keys()];
39
+ const utilityTools = UTILITY_TOOLS.filter(
40
+ (u) =>
41
+ isUtilityToolAvailable(
42
+ { ...u, enabled: undefined },
43
+ { readOnly, httpMode: false, scopeMode: 'org' }
44
+ ) && enabledToolsRegex.test(u.name)
45
+ ).map((u) => u.name);
46
+ return [...new Set([...graphTools, ...utilityTools])].sort();
47
+ }
48
+
49
+ function scopesForMode(preset: string, mode: Mode): string[] {
50
+ return resolveAuthScopes({
51
+ enabledTools: getCombinedPresetPattern([preset]),
52
+ readOnly: mode === 'read-only',
53
+ orgMode: true,
54
+ });
55
+ }
56
+
57
+ function pushBulletList(lines: string[], heading: string, items: string[]): void {
58
+ lines.push(`${heading} (${items.length}):`);
59
+ lines.push('');
60
+ for (const item of items) {
61
+ lines.push(`- \`${item}\``);
62
+ }
63
+ lines.push('');
64
+ }
65
+
16
66
  export async function renderPresetsMarkdown(): Promise<string> {
17
- const catalog = listPresets().map((preset) => ({
18
- ...preset,
19
- tools: getToolsForPreset(preset.name),
20
- }));
67
+ const catalog = listPresets().map((preset) => {
68
+ const fullTools = toolsForMode(preset.name, 'full');
69
+ const readOnlyTools = toolsForMode(preset.name, 'read-only');
70
+ return {
71
+ ...preset,
72
+ variants: [
73
+ {
74
+ mode: 'full' as const,
75
+ tools: fullTools,
76
+ scopes: scopesForMode(preset.name, 'full'),
77
+ },
78
+ {
79
+ mode: 'read-only' as const,
80
+ tools: readOnlyTools,
81
+ scopes: scopesForMode(preset.name, 'read-only'),
82
+ },
83
+ ],
84
+ };
85
+ });
86
+
21
87
  const lines: string[] = [
22
88
  '# Tool Presets',
23
89
  '',
24
90
  '> Generated by `bin/generate-presets-md.ts`. Do not edit by hand; regenerated on `npm run generate`.',
25
91
  '',
92
+ 'Tool and scope lists assume `--org-mode`; without it, personal accounts get fewer tools and scopes.',
26
93
  '',
27
94
  '## Summary',
28
95
  '',
29
- '| Preset | Tools | Org mode | Description |',
30
- '| ------ | ----: | -------- | ----------- |',
96
+ '| Preset | Mode | Tools | Scopes | Org mode | Description |',
97
+ '| ------ | ---- | ----: | -----: | -------- | ----------- |',
31
98
  ];
32
99
 
33
100
  for (const entry of catalog) {
34
- const org = entry.requiresOrgMode ? 'required' : '';
101
+ const org = entry.requiresOrgMode ? 'required' : '-';
35
102
  const desc = entry.description.replace(/\|/g, '\\|');
103
+ const modeCell = entry.variants
104
+ .map((v) => `[${modeLabel(v.mode)}](#${sectionAnchor(entry.name, v.mode)})`)
105
+ .join('<br>');
106
+ const toolsCell = entry.variants.map((v) => String(v.tools.length)).join('<br>');
107
+ const scopesCell = entry.variants.map((v) => String(v.scopes.length)).join('<br>');
108
+ // Same org-mode flag for both variants; still stacked so the row lines up with Mode/Tools.
109
+ const orgCell = entry.variants.map(() => org).join('<br>');
36
110
  lines.push(
37
- `| [\`${entry.name}\`](#${entry.name}) | ${entry.tools.length} | ${org} | ${desc} |`
111
+ `| \`${entry.name}\` | ${modeCell} | ${toolsCell} | ${scopesCell} | ${orgCell} | ${desc} |`
38
112
  );
39
113
  }
40
114
 
41
115
  lines.push('');
42
116
 
43
117
  for (const entry of catalog) {
44
- lines.push(`## \`${entry.name}\``);
45
- lines.push('');
46
- lines.push(entry.description);
47
- if (entry.requiresOrgMode) {
118
+ for (const variant of entry.variants) {
119
+ const label = modeLabel(variant.mode);
120
+ lines.push(`## \`${entry.name}\` ${label}`);
48
121
  lines.push('');
49
- lines.push('Requires `--org-mode`.');
50
- }
51
- lines.push('');
52
- lines.push(`Tools (${entry.tools.length}):`);
53
- lines.push('');
54
- for (const tool of entry.tools) {
55
- lines.push(`- \`${tool}\``);
122
+ lines.push(entry.description);
123
+ if (entry.requiresOrgMode) {
124
+ lines.push('');
125
+ lines.push('Requires `--org-mode`.');
126
+ }
127
+ lines.push('');
128
+ pushBulletList(lines, 'Tools', variant.tools);
129
+ pushBulletList(lines, 'Scopes', variant.scopes);
56
130
  }
57
- lines.push('');
58
131
  }
59
132
 
60
133
  // Format here so PRESETS.md matches `prettier --check` and the staleness test.
package/dist/app-mode.js CHANGED
@@ -1,8 +1,11 @@
1
- import { ConfidentialClientApplication } from "@azure/msal-node";
1
+ import {
2
+ ConfidentialClientApplication,
3
+ ManagedIdentityApplication
4
+ } from "@azure/msal-node";
2
5
  import { X509Certificate } from "crypto";
3
6
  import { readFileSync } from "fs";
4
7
  import logger from "./logger.js";
5
- import { getCloudEndpoints, getDefaultClientId } from "./cloud-config.js";
8
+ import { getCloudEndpoints, getDefaultClientId, parseCloudType } from "./cloud-config.js";
6
9
  const APP_MODE_WARNING = "Warning: app mode (--app-mode) uses application permissions with no signed-in user. Whatever the app registration is granted applies to the whole tenant (every mailbox, calendar, site), and anyone who can call this server acts with it. Grant the fewest permissions you can, and scope mailbox access with RBAC for Applications in Exchange Online.";
7
10
  const NON_TENANT_AUTHORITIES = /* @__PURE__ */ new Set(["common", "organizations", "consumers"]);
8
11
  const LOCAL_ACCOUNT_FLAGS = [
@@ -84,8 +87,82 @@ function describeAppToken(token) {
84
87
  roles: Array.isArray(claims.roles) ? claims.roles : []
85
88
  };
86
89
  }
90
+ function readFederatedToken(tokenPath) {
91
+ let token;
92
+ try {
93
+ token = readFileSync(tokenPath, "utf8").trim();
94
+ } catch (error) {
95
+ throw new Error(
96
+ `Cannot read MS365_MCP_FEDERATED_TOKEN_FILE (${tokenPath}): ${error.message}`
97
+ );
98
+ }
99
+ if (!token) {
100
+ throw new Error(`MS365_MCP_FEDERATED_TOKEN_FILE (${tokenPath}) is empty.`);
101
+ }
102
+ return token;
103
+ }
104
+ const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
105
+ function parseManagedIdentity(value) {
106
+ const trimmed = value.trim();
107
+ if (["system", "true", "1"].includes(trimmed.toLowerCase())) return {};
108
+ if (GUID.test(trimmed)) return { userAssignedClientId: trimmed };
109
+ throw new Error(
110
+ `MS365_MCP_MANAGED_IDENTITY must be 'system' or the client id of a user-assigned identity, not '${trimmed}'.`
111
+ );
112
+ }
113
+ function managedIdentityFromEnv() {
114
+ const value = process.env.MS365_MCP_MANAGED_IDENTITY?.trim();
115
+ return value && !["false", "0"].includes(value.toLowerCase()) ? value : void 0;
116
+ }
117
+ function credentialEnvFromProcess() {
118
+ return {
119
+ certPath: process.env.MS365_MCP_CLIENT_CERTIFICATE_PATH || void 0,
120
+ federatedTokenFile: process.env.MS365_MCP_FEDERATED_TOKEN_FILE || void 0,
121
+ managedIdentity: managedIdentityFromEnv()
122
+ };
123
+ }
124
+ function usesManagedIdentity() {
125
+ return managedIdentityFromEnv() !== void 0;
126
+ }
127
+ function managedIdentitySecrets() {
128
+ return {
129
+ clientId: process.env.MS365_MCP_CLIENT_ID || "",
130
+ tenantId: process.env.MS365_MCP_TENANT_ID || "common",
131
+ clientSecret: process.env.MS365_MCP_CLIENT_SECRET,
132
+ cloudType: parseCloudType(process.env.MS365_MCP_CLOUD_TYPE)
133
+ };
134
+ }
135
+ const CREDENTIAL_OPTIONS = "MS365_MCP_CLIENT_SECRET, MS365_MCP_CLIENT_CERTIFICATE_PATH, MS365_MCP_FEDERATED_TOKEN_FILE or MS365_MCP_MANAGED_IDENTITY";
87
136
  class AppTokenClient {
88
- constructor(secrets, certPath = process.env.MS365_MCP_CLIENT_CERTIFICATE_PATH) {
137
+ constructor(secrets, env = credentialEnvFromProcess()) {
138
+ const set = [
139
+ secrets.clientSecret && "a client secret (MS365_MCP_CLIENT_SECRET, .env or Key Vault)",
140
+ env.certPath && "MS365_MCP_CLIENT_CERTIFICATE_PATH",
141
+ env.federatedTokenFile && "MS365_MCP_FEDERATED_TOKEN_FILE",
142
+ env.managedIdentity && "MS365_MCP_MANAGED_IDENTITY"
143
+ ].filter((name) => Boolean(name));
144
+ if (set.length === 0) {
145
+ throw new Error(`--app-mode needs one of ${CREDENTIAL_OPTIONS}.`);
146
+ }
147
+ if (set.length > 1) {
148
+ throw new Error(`Set only one credential for --app-mode, not ${set.join(" and ")}.`);
149
+ }
150
+ const cloudEndpoints = getCloudEndpoints(secrets.cloudType);
151
+ const graphResource = cloudEndpoints.graphApi.replace(/\/$/, "");
152
+ if (env.managedIdentity) {
153
+ const managedIdentityIdParams = parseManagedIdentity(env.managedIdentity);
154
+ if (secrets.clientId) {
155
+ logger.warn(
156
+ "App mode: MS365_MCP_CLIENT_ID is ignored with a managed identity. For a user-assigned identity, put its client id in MS365_MCP_MANAGED_IDENTITY."
157
+ );
158
+ }
159
+ const mia = new ManagedIdentityApplication({ managedIdentityIdParams });
160
+ this.acquire = () => mia.acquireToken({ resource: graphResource });
161
+ logger.info(
162
+ `App mode: managed identity (${managedIdentityIdParams.userAssignedClientId ? `user-assigned ${managedIdentityIdParams.userAssignedClientId}` : "system-assigned"})`
163
+ );
164
+ return;
165
+ }
89
166
  const tenantId = secrets.tenantId?.trim();
90
167
  if (!tenantId || NON_TENANT_AUTHORITIES.has(tenantId.toLowerCase())) {
91
168
  throw new Error(
@@ -97,33 +174,35 @@ class AppTokenClient {
97
174
  "--app-mode needs MS365_MCP_CLIENT_ID set to your own app registration; the built-in app has no application permissions."
98
175
  );
99
176
  }
100
- if (certPath && secrets.clientSecret) {
101
- throw new Error(
102
- "Set MS365_MCP_CLIENT_SECRET or MS365_MCP_CLIENT_CERTIFICATE_PATH for --app-mode, not both."
103
- );
177
+ let credential;
178
+ let label;
179
+ if (env.certPath) {
180
+ credential = { clientCertificate: loadCertificateCredential(env.certPath) };
181
+ label = "a certificate";
182
+ } else if (env.federatedTokenFile) {
183
+ const tokenFile = env.federatedTokenFile;
184
+ readFederatedToken(tokenFile);
185
+ credential = { clientAssertion: async () => readFederatedToken(tokenFile) };
186
+ label = "a federated token";
187
+ } else {
188
+ credential = { clientSecret: secrets.clientSecret };
189
+ label = "a client secret";
104
190
  }
105
- if (!certPath && !secrets.clientSecret) {
106
- throw new Error(
107
- "--app-mode needs MS365_MCP_CLIENT_SECRET or MS365_MCP_CLIENT_CERTIFICATE_PATH for your own app registration."
108
- );
109
- }
110
- const cloudEndpoints = getCloudEndpoints(secrets.cloudType);
111
- this.cca = new ConfidentialClientApplication({
191
+ const cca = new ConfidentialClientApplication({
112
192
  auth: {
113
193
  clientId: secrets.clientId,
114
194
  authority: `${cloudEndpoints.authority}/${tenantId}`,
115
- ...certPath ? { clientCertificate: loadCertificateCredential(certPath) } : { clientSecret: secrets.clientSecret }
195
+ ...credential
116
196
  }
117
197
  });
118
- this.scopes = [`${cloudEndpoints.graphApi.replace(/\/$/, "")}/.default`];
119
- logger.info(
120
- `App mode: client credentials with a ${certPath ? "certificate" : "client secret"} for tenant ${tenantId}`
121
- );
198
+ const scopes = [`${graphResource}/.default`];
199
+ this.acquire = () => cca.acquireTokenByClientCredential({ scopes });
200
+ logger.info(`App mode: client credentials with ${label} for tenant ${tenantId}`);
122
201
  }
123
202
  async getToken() {
124
- const result = await this.cca.acquireTokenByClientCredential({ scopes: this.scopes });
203
+ const result = await this.acquire();
125
204
  if (!result?.accessToken) {
126
- throw new Error("Client credentials token request returned no access token");
205
+ throw new Error("App token request returned no access token");
127
206
  }
128
207
  return result.accessToken;
129
208
  }
@@ -133,5 +212,9 @@ export {
133
212
  AppTokenClient,
134
213
  assertAppModeOptions,
135
214
  describeAppToken,
136
- loadCertificateCredential
215
+ loadCertificateCredential,
216
+ managedIdentitySecrets,
217
+ parseManagedIdentity,
218
+ readFederatedToken,
219
+ usesManagedIdentity
137
220
  };
package/dist/auth.js CHANGED
@@ -4,7 +4,12 @@ import { readFileSync } from "fs";
4
4
  import { fileURLToPath } from "url";
5
5
  import path from "path";
6
6
  import { getSecrets } from "./secrets.js";
7
- import { AppTokenClient, describeAppToken } from "./app-mode.js";
7
+ import {
8
+ AppTokenClient,
9
+ describeAppToken,
10
+ managedIdentitySecrets,
11
+ usesManagedIdentity
12
+ } from "./app-mode.js";
8
13
  import { getCloudEndpoints, getDefaultClientId, getGraphBaseUrl } from "./cloud-config.js";
9
14
  import {
10
15
  dedupeRefreshTokens
@@ -462,6 +467,7 @@ function consumersAuthorityHint(error, account, authority) {
462
467
  class AuthManager {
463
468
  constructor(config, scopes = [], expectedAccount, storage) {
464
469
  this.appClient = null;
470
+ this.appSecrets = null;
465
471
  logger.info(`And scopes are ${scopes.join(", ")}`, scopes);
466
472
  this.scopes = scopes;
467
473
  this.storage = storage ?? new DefaultTokenCacheStorage();
@@ -491,18 +497,26 @@ class AuthManager {
491
497
  * Uses Key Vault if MS365_MCP_KEYVAULT_URL is set, otherwise environment variables.
492
498
  */
493
499
  static async create(scopes = [], expectedAccount, options = {}) {
494
- const secrets = await getSecrets();
495
- const config = createMsalConfig(secrets);
500
+ const managedIdentity = Boolean(options.appMode) && usesManagedIdentity();
501
+ const secrets = managedIdentity ? managedIdentitySecrets() : await getSecrets();
502
+ const config = createMsalConfig(
503
+ managedIdentity && !secrets.clientId ? { ...secrets, clientId: "00000000-0000-0000-0000-000000000000" } : secrets
504
+ );
496
505
  const storage = options.storage ?? await createTokenCacheStorage({ allowCommandStorage: false, logProvider: true });
497
506
  const authManager = new AuthManager(config, scopes, expectedAccount, storage);
498
507
  if (options.appMode) {
499
508
  authManager.appClient = new AppTokenClient(secrets);
509
+ authManager.appSecrets = secrets;
500
510
  }
501
511
  return authManager;
502
512
  }
503
513
  isAppMode() {
504
514
  return this.appClient !== null;
505
515
  }
516
+ /** The secrets app mode was set up with, so the server does not load them a second way. */
517
+ getAppSecrets() {
518
+ return this.appSecrets;
519
+ }
506
520
  async loadTokenCache() {
507
521
  try {
508
522
  const cacheRaw = await this.storage.load("token-cache");
package/dist/cli.js CHANGED
@@ -61,7 +61,7 @@ program.name("ms-365-mcp-server").description("Microsoft 365 MCP Server").versio
61
61
  "Enable organization/work mode from start (includes Teams, SharePoint, etc.)"
62
62
  ).option("--work-mode", "Alias for --org-mode").option(
63
63
  "--app-mode",
64
- "Use application permissions (client credentials) with no signed-in user. stdio only. Needs your own app registration, MS365_MCP_TENANT_ID, and MS365_MCP_CLIENT_SECRET or MS365_MCP_CLIENT_CERTIFICATE_PATH. Only tools that work with application permissions are offered."
64
+ "Use application permissions with no signed-in user. stdio only. Needs one credential: MS365_MCP_CLIENT_SECRET, MS365_MCP_CLIENT_CERTIFICATE_PATH or MS365_MCP_FEDERATED_TOKEN_FILE (with your own app registration and MS365_MCP_TENANT_ID), or MS365_MCP_MANAGED_IDENTITY on an Azure host. Only tools that work with application permissions are offered."
65
65
  ).option("--force-work-scopes", "Backwards compatibility alias for --org-mode (deprecated)").option("--toon", "(experimental) Enable TOON output format for 30-60% token reduction").option(
66
66
  "--eager-tools <names>",
67
67
  "With --discovery, also expose these comma-separated exact Graph or utility tool names directly. All enabled tools remain discoverable. Env: MS365_MCP_EAGER_TOOLS."
@@ -27,6 +27,13 @@ import {
27
27
  TicketStoreFullError
28
28
  } from "./lib/attachment-tickets.js";
29
29
  import { buildBM25Index, scoreQuery, tokenize } from "./lib/bm25.js";
30
+ import {
31
+ CONNECTOR_DEFINITION_BUDGET,
32
+ DEFAULT_TOOL_DEFINITION_BUDGET,
33
+ fitToolDefinitionToBudget,
34
+ getToolDefinitionBudget,
35
+ measureInputSchemaBytes
36
+ } from "./lib/body-schema-budget.js";
30
37
  import { isDestructiveOperation } from "./lib/destructive-ops.js";
31
38
  import {
32
39
  CONFIRM_PARAM_DESCRIPTION,
@@ -2327,10 +2334,11 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2327
2334
  };
2328
2335
  }
2329
2336
  }
2330
- function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, options) {
2337
+ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, options, budget) {
2331
2338
  const { authManager, multiAccount = false, accountNames = [] } = options;
2332
2339
  const userFields = parseUserFields(options.userFields);
2333
2340
  const paramSchema = {};
2341
+ const bodyParamNames = [];
2334
2342
  if (tool.parameters && tool.parameters.length > 0) {
2335
2343
  for (const param of tool.parameters) {
2336
2344
  if (param.type === "Query") {
@@ -2338,7 +2346,12 @@ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, opt
2338
2346
  if (schema) paramSchema[param.name] = schema;
2339
2347
  continue;
2340
2348
  }
2341
- paramSchema[param.name] = param.type === "Body" && param.schema ? lenientBodySchema(param.schema) : param.schema || z.any();
2349
+ if (param.type === "Body" && param.schema) {
2350
+ paramSchema[param.name] = lenientBodySchema(param.schema);
2351
+ bodyParamNames.push(param.name);
2352
+ } else {
2353
+ paramSchema[param.name] = param.schema || z.any();
2354
+ }
2342
2355
  }
2343
2356
  }
2344
2357
  const pathParamMatches = tool.path.matchAll(/:([a-zA-Z]+)/g);
@@ -2391,12 +2404,18 @@ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, opt
2391
2404
  \u{1F4A1} TIP: ${endpointConfig.llmTip}`;
2392
2405
  }
2393
2406
  const isReadOnlyTool = tool.method.toUpperCase() === "GET" || endpointConfig?.readOnly === true;
2407
+ const fit = budget ? fitToolDefinitionToBudget(
2408
+ paramSchema,
2409
+ bodyParamNames,
2410
+ budget.definitionBudget ?? Number.POSITIVE_INFINITY,
2411
+ `${budget.schemaFingerprint}|${tool.alias}`
2412
+ ) : void 0;
2394
2413
  server.registerTool(
2395
2414
  tool.alias,
2396
2415
  {
2397
2416
  title: tool.alias,
2398
2417
  description: toolDescription,
2399
- inputSchema: z.object(paramSchema).loose(),
2418
+ inputSchema: z.object(fit?.paramSchema ?? paramSchema).loose(),
2400
2419
  annotations: {
2401
2420
  title: tool.alias,
2402
2421
  readOnlyHint: isReadOnlyTool,
@@ -2407,6 +2426,7 @@ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, opt
2407
2426
  },
2408
2427
  async (params) => executeGraphTool(tool, endpointConfig, graphClient, params, authManager, userFields)
2409
2428
  );
2429
+ return fit;
2410
2430
  }
2411
2431
  function registerGraphTools(server, graphClient, options = {}) {
2412
2432
  const {
@@ -2444,6 +2464,18 @@ function registerGraphTools(server, graphClient, options = {}) {
2444
2464
  allowedScopesValue,
2445
2465
  httpMode
2446
2466
  });
2467
+ let servedSchemaBytes = 0;
2468
+ const definitionBudget = getToolDefinitionBudget();
2469
+ const budgetContext = {
2470
+ definitionBudget,
2471
+ schemaFingerprint: [
2472
+ definitionBudget ?? "unrationed",
2473
+ multiAccount ? accountNames.join("\0") : "",
2474
+ paginationAllowed(),
2475
+ getMaxPages()
2476
+ ].join("|")
2477
+ };
2478
+ const prunedForBudget = [];
2447
2479
  for (const tool of allEndpoints) {
2448
2480
  const endpointConfig = endpointsData.find((e) => e.toolName === tool.alias);
2449
2481
  if (!isEndpointInScopeMode(endpointConfig, scopeMode)) {
@@ -2474,7 +2506,27 @@ function registerGraphTools(server, graphClient, options = {}) {
2474
2506
  continue;
2475
2507
  }
2476
2508
  try {
2477
- registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, options);
2509
+ const fit = registerGraphToolWithMcp(
2510
+ server,
2511
+ tool,
2512
+ endpointConfig,
2513
+ graphClient,
2514
+ options,
2515
+ budgetContext
2516
+ );
2517
+ if (fit) {
2518
+ servedSchemaBytes += fit.bytesAfter;
2519
+ if (fit.appliedStrategy !== null) {
2520
+ prunedForBudget.push({
2521
+ toolName: tool.alias,
2522
+ depth: fit.appliedStrategy.maxDepth,
2523
+ describeDepth: fit.appliedStrategy.describeDepth,
2524
+ bytesBefore: fit.bytesBefore,
2525
+ bytesAfter: fit.bytesAfter,
2526
+ bodyWentOpaque: fit.bodyWentOpaque
2527
+ });
2528
+ }
2529
+ }
2478
2530
  registeredCount++;
2479
2531
  } catch (error) {
2480
2532
  logger.error(`Failed to register tool ${tool.alias}: ${error.message}`);
@@ -2500,6 +2552,7 @@ function registerGraphTools(server, graphClient, options = {}) {
2500
2552
  if (!isUtilityToolAvailable(utility, { readOnly, httpMode, scopeMode })) continue;
2501
2553
  if (enabledToolsRegex && !enabledToolsRegex.test(utility.name)) continue;
2502
2554
  try {
2555
+ servedSchemaBytes += measureInputSchemaBytes(z.object(utility.buildSchema(utilityCtx)));
2503
2556
  registerUtilityToolWithMcp(server, utility, utilityCtx);
2504
2557
  registeredCount++;
2505
2558
  } catch (error) {
@@ -2507,12 +2560,57 @@ function registerGraphTools(server, graphClient, options = {}) {
2507
2560
  failedCount++;
2508
2561
  }
2509
2562
  }
2563
+ const surfaceKey = [
2564
+ budgetContext.schemaFingerprint,
2565
+ readOnly,
2566
+ scopeMode,
2567
+ enabledToolsPattern ?? "",
2568
+ allowedScopesValue ?? "",
2569
+ httpMode
2570
+ ].join("|");
2571
+ if (!budgetSummaryLogged.has(surfaceKey)) {
2572
+ budgetSummaryLogged.add(surfaceKey);
2573
+ logBudgetSummary(servedSchemaBytes, prunedForBudget, definitionBudget, httpMode);
2574
+ }
2510
2575
  logger.info(
2511
2576
  `Tool registration complete: ${registeredCount} registered, ${skippedCount} skipped, ${failedCount} failed`
2512
2577
  );
2513
2578
  installDeniedToolAuditHandler(server, deniedTools);
2514
2579
  return registeredCount;
2515
2580
  }
2581
+ const budgetSummaryLogged = /* @__PURE__ */ new Set();
2582
+ function logBudgetSummary(servedSchemaBytes, prunedForBudget, budget, httpMode) {
2583
+ const connectorShare = (servedSchemaBytes / CONNECTOR_DEFINITION_BUDGET * 100).toFixed(1);
2584
+ logger.info(
2585
+ `Tool input schemas total ${servedSchemaBytes} bytes as served by tools/list, ${connectorShare}% of the ${CONNECTOR_DEFINITION_BUDGET}-byte budget of a hosted connector`
2586
+ );
2587
+ if (httpMode && servedSchemaBytes > CONNECTOR_DEFINITION_BUDGET) {
2588
+ const remedy = budget === void 0 ? `Set MS365_MCP_TOOL_DEFINITION_BUDGET=${DEFAULT_TOOL_DEFINITION_BUDGET} to trim oversized request bodies, use --discovery, narrow --enabled-tools, or split the surface across two connectors.` : `Lower MS365_MCP_TOOL_DEFINITION_BUDGET, use --discovery, narrow --enabled-tools, or split the surface across two connectors.`;
2589
+ logger.warn(
2590
+ `Served tool schemas exceed the ${CONNECTOR_DEFINITION_BUDGET}-byte budget of a hosted connector by ${servedSchemaBytes - CONNECTOR_DEFINITION_BUDGET} bytes. Such a connector admits tools alphabetically, so the tail of the alphabet will be silently omitted. ` + remedy
2591
+ );
2592
+ }
2593
+ if (budget !== void 0 && prunedForBudget.length > 0) {
2594
+ const saved = prunedForBudget.reduce((n, p) => n + (p.bytesBefore - p.bytesAfter), 0);
2595
+ const stillOver = prunedForBudget.filter((p) => p.bytesAfter > budget);
2596
+ logger.info(
2597
+ `Body schemas trimmed on ${prunedForBudget.length} tools to fit the ${budget}-byte definition budget, saving ${saved} bytes: ` + prunedForBudget.map(
2598
+ (p) => `${p.toolName}(d${p.depth}/desc${p.describeDepth} ${p.bytesBefore}->${p.bytesAfter})`
2599
+ ).join(", ")
2600
+ );
2601
+ const opaque = prunedForBudget.filter((p) => p.bodyWentOpaque);
2602
+ if (opaque.length > 0) {
2603
+ logger.warn(
2604
+ `${opaque.length} tools had their body collapsed to an open object, so callers see no field names: ` + opaque.map((p) => p.toolName).join(", ") + `. Raise MS365_MCP_TOOL_DEFINITION_BUDGET to keep their schemas.`
2605
+ );
2606
+ }
2607
+ if (stillOver.length > 0) {
2608
+ logger.warn(
2609
+ `${stillOver.length} tools remain above the ${budget}-byte ration at minimum depth and spend more of the connector budget than planned: ` + stillOver.map((p) => `${p.toolName}(${p.bytesAfter})`).join(", ")
2610
+ );
2611
+ }
2612
+ }
2613
+ }
2516
2614
  function buildToolsRegistry(readOnly, mode, enabledToolsRegex, allowedScopesValue, disabledByAllowedScopes = []) {
2517
2615
  const toolsMap = /* @__PURE__ */ new Map();
2518
2616
  const allowedScopes = parseAllowedScopes(allowedScopesValue);
@@ -2884,6 +2982,7 @@ export {
2884
2982
  buildToolsRegistry,
2885
2983
  filterMembersByName,
2886
2984
  isDestructiveOperation,
2985
+ isUtilityToolAvailable,
2887
2986
  registerDiscoveryTools,
2888
2987
  registerGraphTools,
2889
2988
  rewriteMentionShorthand,