@softeria/ms-365-mcp-server 0.178.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
@@ -842,6 +842,7 @@ Environment variables:
842
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`
843
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.
844
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.
845
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).
846
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.
847
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.
@@ -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);
@@ -0,0 +1,200 @@
1
+ import { z } from "zod";
2
+ import {
3
+ normalizeToolSchemaRefs,
4
+ tidyToolJsonSchema,
5
+ toolInputJsonSchema
6
+ } from "../normalize-tool-schema.js";
7
+ import { positiveIntFromEnv } from "./param-descriptions.js";
8
+ const CONNECTOR_DEFINITION_BUDGET = 1048576;
9
+ const DEFAULT_TOOL_DEFINITION_BUDGET = 4096;
10
+ function getToolDefinitionBudget() {
11
+ const raw = process.env.MS365_MCP_TOOL_DEFINITION_BUDGET;
12
+ if (raw === void 0 || raw === "") return void 0;
13
+ return positiveIntFromEnv("MS365_MCP_TOOL_DEFINITION_BUDGET", DEFAULT_TOOL_DEFINITION_BUDGET);
14
+ }
15
+ const PRUNE_STRATEGIES = [
16
+ { maxDepth: 4, describeDepth: 2 },
17
+ { maxDepth: 3, describeDepth: 2 },
18
+ { maxDepth: 2, describeDepth: 2 },
19
+ { maxDepth: 1, describeDepth: 2 },
20
+ { maxDepth: 1, describeDepth: 1 },
21
+ { maxDepth: 1, describeDepth: 0 },
22
+ { maxDepth: 0, describeDepth: 0 }
23
+ ];
24
+ function withDescription(rebuilt, original, keepDescription) {
25
+ const description = original.description;
26
+ return description && keepDescription ? rebuilt.describe(description) : rebuilt;
27
+ }
28
+ function collapsedKind(schema) {
29
+ const unwrapped = unwrapContainer(schema);
30
+ if (unwrapped instanceof z.ZodArray) return "array";
31
+ if (unwrapped instanceof z.ZodObject || unwrapped instanceof z.ZodRecord) return "object";
32
+ if (unwrapped instanceof z.ZodUnion) {
33
+ const kinds = new Set(unwrapped.options.map(collapsedKind));
34
+ return kinds.size === 1 ? [...kinds][0] : "other";
35
+ }
36
+ return "other";
37
+ }
38
+ function collapse(schema, keepDescription) {
39
+ switch (collapsedKind(schema)) {
40
+ case "array":
41
+ return withDescription(z.array(z.any()), schema, keepDescription);
42
+ case "object":
43
+ return withDescription(z.record(z.string(), z.any()), schema, keepDescription);
44
+ default:
45
+ return withDescription(z.any(), schema, keepDescription);
46
+ }
47
+ }
48
+ function unwrapContainer(schema) {
49
+ let current = schema;
50
+ for (let i = 0; i < 10; i++) {
51
+ if (current instanceof z.ZodOptional || current instanceof z.ZodNullable) {
52
+ current = current.unwrap();
53
+ continue;
54
+ }
55
+ if (current instanceof z.ZodLazy) {
56
+ current = current.unwrap();
57
+ continue;
58
+ }
59
+ if (current instanceof z.ZodDefault) {
60
+ current = current.def.innerType;
61
+ continue;
62
+ }
63
+ return current;
64
+ }
65
+ return current;
66
+ }
67
+ function pruneSchemaDepth(schema, maxDepth, describeDepth = Number.POSITIVE_INFINITY) {
68
+ const keepDescription = describeDepth > 0;
69
+ if (schema instanceof z.ZodOptional) {
70
+ return pruneSchemaDepth(schema.unwrap(), maxDepth, describeDepth).optional();
71
+ }
72
+ if (schema instanceof z.ZodNullable) {
73
+ return pruneSchemaDepth(schema.unwrap(), maxDepth, describeDepth).nullable();
74
+ }
75
+ if (schema instanceof z.ZodDefault) {
76
+ return pruneSchemaDepth(schema.def.innerType, maxDepth, describeDepth).default(
77
+ schema.def.defaultValue
78
+ );
79
+ }
80
+ if (schema instanceof z.ZodLazy) {
81
+ return pruneSchemaDepth(schema.unwrap(), maxDepth, describeDepth);
82
+ }
83
+ if (maxDepth <= 0) return collapse(schema, keepDescription);
84
+ if (schema instanceof z.ZodObject) {
85
+ const shape = schema.shape;
86
+ const pruned = {};
87
+ for (const [key, value] of Object.entries(shape)) {
88
+ pruned[key] = pruneSchemaDepth(value, maxDepth - 1, describeDepth - 1);
89
+ }
90
+ return withDescription(z.object(pruned).loose(), schema, keepDescription);
91
+ }
92
+ if (schema instanceof z.ZodArray) {
93
+ return withDescription(
94
+ z.array(pruneSchemaDepth(schema.element, maxDepth - 1, describeDepth - 1)),
95
+ schema,
96
+ keepDescription
97
+ );
98
+ }
99
+ if (schema instanceof z.ZodRecord) {
100
+ return withDescription(
101
+ z.record(
102
+ schema.keyType,
103
+ pruneSchemaDepth(schema.valueType, maxDepth - 1, describeDepth - 1)
104
+ ),
105
+ schema,
106
+ keepDescription
107
+ );
108
+ }
109
+ if (schema instanceof z.ZodUnion) {
110
+ const options = schema.options.map(
111
+ (option) => pruneSchemaDepth(option, maxDepth, describeDepth)
112
+ );
113
+ return withDescription(
114
+ z.union(options),
115
+ schema,
116
+ keepDescription
117
+ );
118
+ }
119
+ if (!keepDescription && schema.description) {
120
+ return collapseScalarDescription(schema);
121
+ }
122
+ return schema;
123
+ }
124
+ function collapseScalarDescription(schema) {
125
+ if (schema instanceof z.ZodString) return z.string();
126
+ if (schema instanceof z.ZodNumber) return z.number();
127
+ if (schema instanceof z.ZodBoolean) return z.boolean();
128
+ if (schema instanceof z.ZodEnum) return z.enum(schema.options);
129
+ return schema;
130
+ }
131
+ function serveToolInputSchema(paramSchema) {
132
+ return serveInputSchema(z.object(paramSchema).loose());
133
+ }
134
+ function serveInputSchema(schema) {
135
+ const served = normalizeToolSchemaRefs(toolInputJsonSchema(schema));
136
+ tidyToolJsonSchema(served);
137
+ return served;
138
+ }
139
+ function measureToolDefinitionBytes(paramSchema) {
140
+ return measureInputSchemaBytes(z.object(paramSchema).loose());
141
+ }
142
+ function measureInputSchemaBytes(schema) {
143
+ return Buffer.byteLength(JSON.stringify(serveInputSchema(schema)), "utf8");
144
+ }
145
+ const fitCache = /* @__PURE__ */ new Map();
146
+ function clearToolDefinitionBudgetCache() {
147
+ fitCache.clear();
148
+ }
149
+ function fitToolDefinitionToBudget(paramSchema, bodyParamNames, budget = DEFAULT_TOOL_DEFINITION_BUDGET, cacheKey) {
150
+ if (cacheKey !== void 0) {
151
+ const cached = fitCache.get(cacheKey);
152
+ if (cached) return cached;
153
+ }
154
+ const result = fitUncached(paramSchema, bodyParamNames, budget);
155
+ if (cacheKey !== void 0) fitCache.set(cacheKey, result);
156
+ return result;
157
+ }
158
+ function fitUncached(paramSchema, bodyParamNames, budget) {
159
+ const bytesBefore = measureToolDefinitionBytes(paramSchema);
160
+ if (bytesBefore <= budget || bodyParamNames.length === 0) {
161
+ return {
162
+ paramSchema,
163
+ appliedStrategy: null,
164
+ bytesBefore,
165
+ bytesAfter: bytesBefore,
166
+ bodyWentOpaque: false
167
+ };
168
+ }
169
+ let best = null;
170
+ for (const strategy of PRUNE_STRATEGIES) {
171
+ const candidate = { ...paramSchema };
172
+ for (const bodyName of bodyParamNames) {
173
+ const original = paramSchema[bodyName];
174
+ if (original)
175
+ candidate[bodyName] = pruneSchemaDepth(original, strategy.maxDepth, strategy.describeDepth);
176
+ }
177
+ const bytesAfter = measureToolDefinitionBytes(candidate);
178
+ best = {
179
+ paramSchema: candidate,
180
+ appliedStrategy: strategy,
181
+ bytesBefore,
182
+ bytesAfter,
183
+ bodyWentOpaque: strategy.maxDepth === 0
184
+ };
185
+ if (bytesAfter <= budget) return best;
186
+ }
187
+ return best;
188
+ }
189
+ export {
190
+ CONNECTOR_DEFINITION_BUDGET,
191
+ DEFAULT_TOOL_DEFINITION_BUDGET,
192
+ clearToolDefinitionBudgetCache,
193
+ fitToolDefinitionToBudget,
194
+ getToolDefinitionBudget,
195
+ measureInputSchemaBytes,
196
+ measureToolDefinitionBytes,
197
+ pruneSchemaDepth,
198
+ serveInputSchema,
199
+ serveToolInputSchema
200
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@softeria/ms-365-mcp-server",
3
3
  "mcpName": "io.github.Softeria/ms-365-mcp-server",
4
- "version": "0.178.0",
4
+ "version": "0.179.0",
5
5
  "description": " A Model Context Protocol (MCP) server for interacting with Microsoft 365 and Office services through the Graph API",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",