@softeria/ms-365-mcp-server 0.176.0 → 0.177.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.
@@ -259,7 +259,7 @@ class GraphClient {
259
259
  const errorText = await response.text();
260
260
  if (errorText.includes("scope") || errorText.includes("permission")) {
261
261
  throw new Error(
262
- `Microsoft Graph API scope error: ${response.status} ${response.statusText} - ${errorText}. This tool requires organization mode. Please restart with --org-mode flag.`
262
+ `Microsoft Graph API scope error: ${response.status} ${response.statusText} - ${errorText}. ${this.scopeErrorHint()}`
263
263
  );
264
264
  }
265
265
  throw new Error(
@@ -327,13 +327,19 @@ class GraphClient {
327
327
  }
328
328
  }
329
329
  }
330
+ scopeErrorHint() {
331
+ if (this.authManager.isAppMode?.()) {
332
+ return "Grant one of these as an application permission to your app registration (with admin consent), or for mail and calendars through Exchange RBAC for Applications.";
333
+ }
334
+ return "This tool requires organization mode. Please restart with --org-mode flag.";
335
+ }
330
336
  async createGraphApiError(response) {
331
337
  const errorText = await response.text();
332
338
  const graphErrorCode = extractGraphErrorCode(errorText);
333
339
  const isPermissionOrScopeError = errorText.includes("scope") || errorText.includes("permission");
334
340
  if (response.status === 403 && isPermissionOrScopeError) {
335
341
  return new GraphApiError(
336
- `Microsoft Graph API scope error: ${response.status} ${response.statusText} - ${errorText}. This tool requires organization mode. Please restart with --org-mode flag.`,
342
+ `Microsoft Graph API scope error: ${response.status} ${response.statusText} - ${errorText}. ${this.scopeErrorHint()}`,
337
343
  response.status,
338
344
  graphErrorCode
339
345
  );
@@ -10,7 +10,9 @@ import { deriveTargetResource } from "./audit-target-resource.js";
10
10
  import {
11
11
  getEndpointScopeGroups,
12
12
  getMissingAllowedScopesForGroups,
13
- parseAllowedScopes
13
+ isEndpointInScopeMode,
14
+ parseAllowedScopes,
15
+ scopeModeFor
14
16
  } from "./auth.js";
15
17
  import { api as betaApi } from "./generated/client-beta.js";
16
18
  import { api } from "./generated/client.js";
@@ -521,6 +523,13 @@ async function executeUtilityTool(utility, ctx, params) {
521
523
  throw error;
522
524
  }
523
525
  }
526
+ function isUtilityToolAvailable(utility, options) {
527
+ if (options.readOnly && !utility.readOnlyHint) return false;
528
+ if (options.httpMode && utility.stdioOnly) return false;
529
+ if (options.scopeMode === "app" && utility.meOnly) return false;
530
+ if (utility.enabled && !utility.enabled()) return false;
531
+ return true;
532
+ }
524
533
  function formatDisabledToolsForLog(disabledTools) {
525
534
  const shown = disabledTools.slice(0, 20).map((tool) => `${tool.toolName} (missing: ${tool.missingScopes.join(", ")})`);
526
535
  const suffix = disabledTools.length > shown.length ? `, ... +${disabledTools.length - shown.length} more` : "";
@@ -539,7 +548,7 @@ function collectDeniedToolPolicies(options) {
539
548
  const allowedScopes = parseAllowedScopes(options.allowedScopesValue);
540
549
  for (const tool of allEndpoints) {
541
550
  const endpointConfig = endpointsData.find((e) => e.toolName === tool.alias);
542
- if (!options.orgMode && endpointConfig && !endpointConfig.scopes && endpointConfig.workScopes) {
551
+ if (!isEndpointInScopeMode(endpointConfig, options.scopeMode)) {
543
552
  continue;
544
553
  }
545
554
  const method = tool.method.toUpperCase();
@@ -554,7 +563,7 @@ function collectDeniedToolPolicies(options) {
554
563
  continue;
555
564
  }
556
565
  const missingScopes = allowedScopes !== void 0 && !endpointConfig ? ["endpoint scope metadata"] : getMissingAllowedScopesForGroups(
557
- getEndpointScopeGroups(endpointConfig, options.orgMode),
566
+ getEndpointScopeGroups(endpointConfig, options.scopeMode),
558
567
  allowedScopes
559
568
  );
560
569
  if (missingScopes.length > 0) {
@@ -565,9 +574,7 @@ function collectDeniedToolPolicies(options) {
565
574
  }
566
575
  }
567
576
  for (const utility of UTILITY_TOOLS) {
568
- if (options.readOnly && !utility.readOnlyHint) continue;
569
- if (options.httpMode && utility.stdioOnly) continue;
570
- if (utility.enabled && !utility.enabled()) continue;
577
+ if (!isUtilityToolAvailable(utility, options)) continue;
571
578
  if (options.enabledToolsRegex && !options.enabledToolsRegex.test(utility.name)) {
572
579
  deniedTools.set(utility.name, {
573
580
  toolName: utility.name,
@@ -624,7 +631,7 @@ const UPLOAD_CONTENT_ID_ERROR = 'contentId may hold letters, digits, ".", "_", "
624
631
  const contentIdSchema = z.string().optional().describe(
625
632
  'Attach inline under this Content-ID instead of as a regular attachment, so the HTML body can show the file with <img src="cid:<contentId>">, e.g. a picture in an email signature. Letters, digits, ".", "_", "@", "-".'
626
633
  );
627
- const UPLOAD_TARGET_ERROR = "target must be the attachments collection of a draft message or an event: /me/messages/{message-id}/attachments or /me/events/{event-id}/attachments.";
634
+ const UPLOAD_TARGET_ERROR = "target must be the attachments collection of a draft message or an event: /me/messages/{message-id}/attachments or /me/events/{event-id}/attachments (or /users/{user-id}/... for another mailbox).";
628
635
  function uploadError(message) {
629
636
  return { content: [{ type: "text", text: JSON.stringify({ error: message }) }], isError: true };
630
637
  }
@@ -786,7 +793,7 @@ const UTILITY_TOOLS = [
786
793
  buildSchema: (ctx) => {
787
794
  const schema = {
788
795
  target: z.string().describe(
789
- "Attachments collection of a draft message or an event, e.g. /me/messages/{message-id}/attachments or /me/events/{event-id}/attachments."
796
+ "Attachments collection of a draft message or an event, e.g. /me/messages/{message-id}/attachments, /me/events/{event-id}/attachments, or /users/{user-id}/messages/{message-id}/attachments for another mailbox."
790
797
  ),
791
798
  name: z.string().describe("Attachment file name as the recipient will see it, e.g. report.pdf"),
792
799
  contentType: z.string().optional().describe(
@@ -834,7 +841,7 @@ const UTILITY_TOOLS = [
834
841
  buildSchema: (ctx) => {
835
842
  const schema = {
836
843
  target: z.string().describe(
837
- "Attachments collection of a draft message or an event, e.g. /me/messages/{message-id}/attachments or /me/events/{event-id}/attachments."
844
+ "Attachments collection of a draft message or an event, e.g. /me/messages/{message-id}/attachments, /me/events/{event-id}/attachments, or /users/{user-id}/messages/{message-id}/attachments for another mailbox."
838
845
  ),
839
846
  filePath: z.string().describe(
840
847
  "Absolute path of the file on the server's filesystem, e.g. /Users/me/documents/invitation.pdf. Must be inside a directory the server allows uploads from."
@@ -969,6 +976,7 @@ const UTILITY_TOOLS = [
969
976
  },
970
977
  {
971
978
  name: "read-mail-text",
979
+ meOnly: true,
972
980
  method: "GET",
973
981
  path: "tool:read-mail-text",
974
982
  searchKeywords: "triage inbox skim many emails at once without quoted history signature footer tracking links",
@@ -1112,9 +1120,9 @@ const UTILITY_TOOLS = [
1112
1120
  target: z.string().describe(
1113
1121
  'Relative Microsoft Graph path starting with "/". Common paths: /drives/{drive-id}/items/{driveItem-id}/content (drive file content); /me/messages/{message-id}/attachments/{attachment-id}/$value (mail attachment, list-mail-attachments returns the IDs); /me/photo/$value or /users/{user-id}/photo/$value (profile photo); /chats/{chat-id}/messages/{chatMessage-id}/hostedContents/{chatMessageHostedContent-id}/$value (Teams chat hosted content, list-chat-message-hosted-contents returns the IDs); /teams/{team-id}/channels/{channel-id}/messages/{chatMessage-id}/hostedContents/{chatMessageHostedContent-id}/$value (Teams channel hosted content). For meeting recordings, use get-meeting-recording-content where available; Microsoft Graph returns authenticated recording bytes, not a pre-authenticated download URL.'
1114
1122
  ),
1115
- fileName: z.string().describe(
1123
+ fileName: z.string().optional().describe(
1116
1124
  "Name of the file, used as the last segment of the returned resource URI when the server runs with blob output. Optional."
1117
- ).optional()
1125
+ )
1118
1126
  };
1119
1127
  if (ctx.multiAccount) {
1120
1128
  schema["account"] = z.string().optional().describe(
@@ -1595,14 +1603,23 @@ function bodySchemaShape(schema) {
1595
1603
  if (current instanceof z.ZodObject) {
1596
1604
  return current.shape;
1597
1605
  }
1598
- const def = current._def;
1599
- current = def?.innerType ?? def?.schema ?? def?.getter?.();
1606
+ const def = current.def;
1607
+ current = def.innerType ?? def.in ?? def.getter?.();
1600
1608
  }
1601
1609
  return null;
1602
1610
  }
1611
+ const lenientBodySchemas = /* @__PURE__ */ new WeakMap();
1603
1612
  function lenientBodySchema(schema) {
1613
+ let lenient = lenientBodySchemas.get(schema);
1614
+ if (!lenient) {
1615
+ lenient = buildLenientBodySchema(schema);
1616
+ lenientBodySchemas.set(schema, lenient);
1617
+ }
1618
+ return lenient;
1619
+ }
1620
+ function buildLenientBodySchema(schema) {
1604
1621
  if (schema instanceof z.ZodObject) {
1605
- return schema.passthrough();
1622
+ return schema.loose();
1606
1623
  }
1607
1624
  if (schema instanceof z.ZodOptional) {
1608
1625
  return lenientBodySchema(schema.unwrap()).optional();
@@ -1611,7 +1628,7 @@ function lenientBodySchema(schema) {
1611
1628
  return lenientBodySchema(schema.unwrap()).nullable();
1612
1629
  }
1613
1630
  if (schema instanceof z.ZodLazy) {
1614
- return z.lazy(() => lenientBodySchema(schema.schema));
1631
+ return z.lazy(() => lenientBodySchema(schema.unwrap()));
1615
1632
  }
1616
1633
  return schema;
1617
1634
  }
@@ -2332,37 +2349,37 @@ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, opt
2332
2349
  }
2333
2350
  }
2334
2351
  if (endpointConfig?.acceptType && paramSchema["Accept"] === void 0) {
2335
- paramSchema["Accept"] = z.string().describe(getAcceptParamDescription(endpointConfig.acceptType)).optional();
2352
+ paramSchema["Accept"] = z.string().optional().describe(getAcceptParamDescription(endpointConfig.acceptType));
2336
2353
  }
2337
2354
  if (endpointConfig?.blobOutput && paramSchema["fileName"] === void 0) {
2338
- paramSchema["fileName"] = z.string().describe(
2355
+ paramSchema["fileName"] = z.string().optional().describe(
2339
2356
  "Name of the file, used as the last segment of the returned resource URI when the server runs with blob output. Optional."
2340
- ).optional();
2357
+ );
2341
2358
  }
2342
2359
  if (isFetchAllPagesApplicable(tool)) {
2343
2360
  const maxPages = getMaxPages();
2344
- paramSchema["fetchAllPages"] = z.boolean().describe(getFetchAllPagesParamDescription(maxPages, endpointConfig)).optional();
2361
+ paramSchema["fetchAllPages"] = z.boolean().optional().describe(getFetchAllPagesParamDescription(maxPages, endpointConfig));
2345
2362
  }
2346
2363
  if (endpointConfig?.nameFilter) {
2347
- paramSchema["name"] = z.string().describe(MEMBER_NAME_PARAM_DESCRIPTION).optional();
2364
+ paramSchema["name"] = z.string().optional().describe(MEMBER_NAME_PARAM_DESCRIPTION);
2348
2365
  }
2349
2366
  if (isSkiptokenApplicable(tool, Object.keys(paramSchema), endpointConfig)) {
2350
- paramSchema["skiptoken"] = z.string().describe(SKIPTOKEN_PARAM_DESCRIPTION).optional();
2367
+ paramSchema["skiptoken"] = z.string().optional().describe(SKIPTOKEN_PARAM_DESCRIPTION);
2351
2368
  }
2352
2369
  if (multiAccount) {
2353
- paramSchema["account"] = z.string().describe(getAccountParamDescription(accountNames)).optional();
2370
+ paramSchema["account"] = z.string().optional().describe(getAccountParamDescription(accountNames));
2354
2371
  }
2355
- paramSchema["includeHeaders"] = z.boolean().describe("Include response headers (including ETag) in the response metadata").optional();
2356
- paramSchema["excludeResponse"] = z.boolean().describe("Exclude the full response body and only return success or failure indication").optional();
2372
+ paramSchema["includeHeaders"] = z.boolean().optional().describe("Include response headers (including ETag) in the response metadata");
2373
+ paramSchema["excludeResponse"] = z.boolean().optional().describe("Exclude the full response body and only return success or failure indication");
2357
2374
  const destructive = isDestructiveOperation(tool.method, endpointConfig);
2358
2375
  if (destructive) {
2359
- paramSchema["confirm"] = z.boolean().describe(CONFIRM_PARAM_DESCRIPTION).optional();
2376
+ paramSchema["confirm"] = z.boolean().optional().describe(CONFIRM_PARAM_DESCRIPTION);
2360
2377
  }
2361
2378
  if (endpointConfig?.supportsTimezone) {
2362
- paramSchema["timezone"] = z.string().describe(TIMEZONE_PARAM_DESCRIPTION).optional();
2379
+ paramSchema["timezone"] = z.string().optional().describe(TIMEZONE_PARAM_DESCRIPTION);
2363
2380
  }
2364
2381
  if (endpointConfig?.supportsExpandExtendedProperties) {
2365
- paramSchema["expandExtendedProperties"] = z.boolean().describe(EXPAND_EXTENDED_PROPERTIES_PARAM_DESCRIPTION).optional();
2382
+ paramSchema["expandExtendedProperties"] = z.boolean().optional().describe(EXPAND_EXTENDED_PROPERTIES_PARAM_DESCRIPTION);
2366
2383
  }
2367
2384
  let toolDescription = withApiVersionPrefix(
2368
2385
  (endpointConfig?.descriptionOverride ?? tool.description) || `Execute ${tool.method.toUpperCase()} request to ${tool.path}`,
@@ -2379,7 +2396,7 @@ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, opt
2379
2396
  {
2380
2397
  title: tool.alias,
2381
2398
  description: toolDescription,
2382
- inputSchema: z.object(paramSchema).passthrough(),
2399
+ inputSchema: z.object(paramSchema).loose(),
2383
2400
  annotations: {
2384
2401
  title: tool.alias,
2385
2402
  readOnlyHint: isReadOnlyTool,
@@ -2396,6 +2413,7 @@ function registerGraphTools(server, graphClient, options = {}) {
2396
2413
  readOnly = false,
2397
2414
  enabledTools: enabledToolsPattern,
2398
2415
  orgMode = false,
2416
+ appMode = false,
2399
2417
  authManager,
2400
2418
  multiAccount = false,
2401
2419
  accountNames = [],
@@ -2418,17 +2436,18 @@ function registerGraphTools(server, graphClient, options = {}) {
2418
2436
  let failedCount = 0;
2419
2437
  const allowedScopes = parseAllowedScopes(allowedScopesValue);
2420
2438
  const disabledByAllowedScopes = [];
2439
+ const scopeMode = scopeModeFor({ orgMode, appMode });
2421
2440
  const deniedTools = collectDeniedToolPolicies({
2422
2441
  readOnly,
2423
- orgMode,
2442
+ scopeMode,
2424
2443
  enabledToolsRegex,
2425
2444
  allowedScopesValue,
2426
2445
  httpMode
2427
2446
  });
2428
2447
  for (const tool of allEndpoints) {
2429
2448
  const endpointConfig = endpointsData.find((e) => e.toolName === tool.alias);
2430
- if (!orgMode && endpointConfig && !endpointConfig.scopes && endpointConfig.workScopes) {
2431
- logger.info(`Skipping work account tool ${tool.alias} - not in org mode`);
2449
+ if (!isEndpointInScopeMode(endpointConfig, scopeMode)) {
2450
+ logger.info(`Skipping tool ${tool.alias} - not available in ${scopeMode} mode`);
2432
2451
  skippedCount++;
2433
2452
  continue;
2434
2453
  }
@@ -2446,7 +2465,7 @@ function registerGraphTools(server, graphClient, options = {}) {
2446
2465
  continue;
2447
2466
  }
2448
2467
  const missingScopes = allowedScopes !== void 0 && !endpointConfig ? ["endpoint scope metadata"] : getMissingAllowedScopesForGroups(
2449
- getEndpointScopeGroups(endpointConfig, orgMode),
2468
+ getEndpointScopeGroups(endpointConfig, scopeMode),
2450
2469
  allowedScopes
2451
2470
  );
2452
2471
  if (missingScopes.length > 0) {
@@ -2478,9 +2497,7 @@ function registerGraphTools(server, graphClient, options = {}) {
2478
2497
  userFields
2479
2498
  };
2480
2499
  for (const utility of UTILITY_TOOLS) {
2481
- if (readOnly && !utility.readOnlyHint) continue;
2482
- if (httpMode && utility.stdioOnly) continue;
2483
- if (utility.enabled && !utility.enabled()) continue;
2500
+ if (!isUtilityToolAvailable(utility, { readOnly, httpMode, scopeMode })) continue;
2484
2501
  if (enabledToolsRegex && !enabledToolsRegex.test(utility.name)) continue;
2485
2502
  try {
2486
2503
  registerUtilityToolWithMcp(server, utility, utilityCtx);
@@ -2496,12 +2513,12 @@ function registerGraphTools(server, graphClient, options = {}) {
2496
2513
  installDeniedToolAuditHandler(server, deniedTools);
2497
2514
  return registeredCount;
2498
2515
  }
2499
- function buildToolsRegistry(readOnly, orgMode, enabledToolsRegex, allowedScopesValue, disabledByAllowedScopes = []) {
2516
+ function buildToolsRegistry(readOnly, mode, enabledToolsRegex, allowedScopesValue, disabledByAllowedScopes = []) {
2500
2517
  const toolsMap = /* @__PURE__ */ new Map();
2501
2518
  const allowedScopes = parseAllowedScopes(allowedScopesValue);
2502
2519
  for (const tool of allEndpoints) {
2503
2520
  const endpointConfig = endpointsData.find((e) => e.toolName === tool.alias);
2504
- if (!orgMode && endpointConfig && !endpointConfig.scopes && endpointConfig.workScopes) {
2521
+ if (!isEndpointInScopeMode(endpointConfig, mode)) {
2505
2522
  continue;
2506
2523
  }
2507
2524
  const method = tool.method.toUpperCase();
@@ -2514,7 +2531,7 @@ function buildToolsRegistry(readOnly, orgMode, enabledToolsRegex, allowedScopesV
2514
2531
  continue;
2515
2532
  }
2516
2533
  const missingScopes = allowedScopes !== void 0 && !endpointConfig ? ["endpoint scope metadata"] : getMissingAllowedScopesForGroups(
2517
- getEndpointScopeGroups(endpointConfig, orgMode),
2534
+ getEndpointScopeGroups(endpointConfig, mode),
2518
2535
  allowedScopes
2519
2536
  );
2520
2537
  if (missingScopes.length > 0) {
@@ -2610,6 +2627,7 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
2610
2627
  readOnly = false,
2611
2628
  enabledTools,
2612
2629
  orgMode = false,
2630
+ appMode = false,
2613
2631
  authManager,
2614
2632
  multiAccount = false,
2615
2633
  accountNames = [],
@@ -2632,16 +2650,17 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
2632
2650
  }
2633
2651
  }
2634
2652
  const disabledByAllowedScopes = [];
2653
+ const scopeMode = scopeModeFor({ orgMode, appMode });
2635
2654
  const deniedTools = collectDeniedToolPolicies({
2636
2655
  readOnly,
2637
- orgMode,
2656
+ scopeMode,
2638
2657
  enabledToolsRegex,
2639
2658
  allowedScopesValue,
2640
2659
  httpMode
2641
2660
  });
2642
2661
  const toolsRegistry = buildToolsRegistry(
2643
2662
  readOnly,
2644
- orgMode,
2663
+ scopeMode,
2645
2664
  enabledToolsRegex,
2646
2665
  allowedScopesValue,
2647
2666
  disabledByAllowedScopes
@@ -2652,9 +2671,7 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
2652
2671
  );
2653
2672
  }
2654
2673
  const utilityTools = UTILITY_TOOLS.filter((u) => {
2655
- if (readOnly && !u.readOnlyHint) return false;
2656
- if (httpMode && u.stdioOnly) return false;
2657
- if (u.enabled && !u.enabled()) return false;
2674
+ if (!isUtilityToolAvailable(u, { readOnly, httpMode, scopeMode })) return false;
2658
2675
  if (enabledToolsRegex && !enabledToolsRegex.test(u.name)) return false;
2659
2676
  return true;
2660
2677
  });
@@ -2726,11 +2743,11 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
2726
2743
  "search-tools",
2727
2744
  `Search through ${totalCount} tools (${toolsRegistry.size} Microsoft Graph API operations + ${utilityTools.length} server utilities like download-bytes). Ranks results by BM25 over tool name, llmTip, description, and path. After picking a tool, call get-tool-schema for parameters, then execute-tool.`,
2728
2745
  {
2729
- query: z.string().describe(
2746
+ query: z.string().optional().describe(
2730
2747
  'Natural-language query. Tokenized and BM25-ranked. E.g. "send email", "download photo", "list unread messages".'
2731
- ).optional(),
2732
- category: z.string().describe(`Optional pre-filter by category: ${categoryNames}`).optional(),
2733
- limit: z.number().describe("Maximum results (default: 10, max: 50)").optional()
2748
+ ),
2749
+ category: z.string().optional().describe(`Optional pre-filter by category: ${categoryNames}`),
2750
+ limit: z.number().optional().describe("Maximum results (default: 10, max: 50)")
2734
2751
  },
2735
2752
  {
2736
2753
  title: "search-tools",
@@ -2815,9 +2832,9 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
2815
2832
  "Execute a Microsoft Graph API tool by name. Workflow: search-tools \u2192 get-tool-schema \u2192 execute-tool. Call get-tool-schema first for any tool you have not seen before \u2014 passing the wrong shape to parameters will fail validation or return a Graph 400. For list endpoints, prefer modest $top plus $select.",
2816
2833
  {
2817
2834
  tool_name: z.string().describe('Name of the tool to execute (e.g., "list-mail-messages")'),
2818
- parameters: z.record(z.any()).describe(
2835
+ parameters: z.record(z.string(), z.any()).optional().describe(
2819
2836
  'Parameters shaped per get-tool-schema. Path/query/header params go at the top level; request bodies go under "body".'
2820
- ).optional()
2837
+ )
2821
2838
  },
2822
2839
  {
2823
2840
  title: "execute-tool",
package/dist/index.js CHANGED
@@ -12,6 +12,8 @@ import {
12
12
  import { createTokenCacheStorage } from "./token-cache-storage.js";
13
13
  import { dumpError, getActiveResources } from "./crash-logging.js";
14
14
  import { version } from "./version.js";
15
+ import { APP_MODE_WARNING, assertAppModeOptions } from "./app-mode.js";
16
+ import { buildToolsRegistry } from "./graph-tools.js";
15
17
  process.on("unhandledRejection", (reason) => {
16
18
  const dump = {
17
19
  kind: "unhandledRejection",
@@ -35,6 +37,9 @@ async function main() {
35
37
  try {
36
38
  loadEnvFile();
37
39
  const args = parseArgs();
40
+ if (args.appMode) {
41
+ assertAppModeOptions(args);
42
+ }
38
43
  const includeWorkScopes = args.orgMode || false;
39
44
  if (includeWorkScopes) {
40
45
  logger.info("Organization mode enabled - including work account scopes");
@@ -43,7 +48,7 @@ async function main() {
43
48
  const effectiveScopes = resolveAuthScopes(args);
44
49
  if (args.listPermissions) {
45
50
  const diagnostics = buildAllowedScopeDiagnostics(args);
46
- const mode = includeWorkScopes ? "org" : "personal";
51
+ const mode = args.appMode ? "app" : includeWorkScopes ? "org" : "personal";
47
52
  const filter = args.enabledTools ? args.enabledTools : void 0;
48
53
  if (diagnostics.disabledTools.length > 0) {
49
54
  console.error(
@@ -64,7 +69,17 @@ async function main() {
64
69
  );
65
70
  process.exit(0);
66
71
  }
67
- const useLocalAuthStorage = shouldUseLocalAuthStorage(args);
72
+ if (args.appMode) {
73
+ logger.warn(APP_MODE_WARNING);
74
+ console.error(APP_MODE_WARNING);
75
+ const filter = args.enabledTools ? new RegExp(args.enabledTools, "i") : void 0;
76
+ if (buildToolsRegistry(Boolean(args.readOnly), "app", filter, args.allowedScopes).size === 0) {
77
+ const empty = "Warning: no Microsoft Graph tools are left in app mode with these filters. App mode only has the /users/{user-id}, directory, files, sites and Teams tools (see --preset work).";
78
+ logger.warn(empty);
79
+ console.error(empty);
80
+ }
81
+ }
82
+ const useLocalAuthStorage = !args.appMode && shouldUseLocalAuthStorage(args);
68
83
  const storage = await createTokenCacheStorage({
69
84
  allowCommandStorage: useLocalAuthStorage,
70
85
  logProvider: useLocalAuthStorage
@@ -75,7 +90,7 @@ async function main() {
75
90
  expectedUsername: args.expectedUsername,
76
91
  expectedHomeAccountId: args.expectedHomeAccountId
77
92
  },
78
- { storage }
93
+ { storage, appMode: args.appMode }
79
94
  );
80
95
  if (useLocalAuthStorage) {
81
96
  await authManager.loadTokenCache();
@@ -1,5 +1,6 @@
1
- import { zodToJsonSchema } from "zod-to-json-schema";
1
+ import { z } from "zod";
2
2
  import { queryParameterSchema } from "./query-parameter-schema.js";
3
+ import { tidyToolJsonSchema, zodToToolJsonSchema } from "../normalize-tool-schema.js";
3
4
  import { isDestructiveOperation } from "./destructive-ops.js";
4
5
  import {
5
6
  isFetchAllPagesApplicable,
@@ -15,27 +16,53 @@ import {
15
16
  MEMBER_NAME_PARAM_DESCRIPTION
16
17
  } from "./param-descriptions.js";
17
18
  function unwrapOptional(schema) {
18
- const def = schema._def;
19
- const typeName = def?.typeName;
20
- if (typeName === "ZodOptional" || typeName === "ZodDefault" || typeName === "ZodNullable") {
21
- return { inner: def.innerType, optional: true };
19
+ if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault || schema instanceof z.ZodNullable) {
20
+ return { inner: schema.unwrap(), optional: true };
22
21
  }
23
22
  return { inner: schema, optional: false };
24
23
  }
24
+ function toParamJsonSchema(schema) {
25
+ const json = zodToToolJsonSchema(schema, "inline");
26
+ delete json.$schema;
27
+ const definitions = json.definitions ?? {};
28
+ delete json.definitions;
29
+ const expanded = expandRecursion(json, definitions, /* @__PURE__ */ new Set());
30
+ tidyToolJsonSchema(expanded);
31
+ return expanded;
32
+ }
33
+ function expandRecursion(node, definitions, expanding) {
34
+ if (!node || typeof node !== "object") return node;
35
+ if (Array.isArray(node)) return node.map((item) => expandRecursion(item, definitions, expanding));
36
+ const { $ref, ...rest } = node;
37
+ const siblings = {};
38
+ for (const [key, value] of Object.entries(rest)) {
39
+ siblings[key] = expandRecursion(value, definitions, expanding);
40
+ }
41
+ if (typeof $ref !== "string") return siblings;
42
+ const name = $ref.startsWith("#/definitions/") ? $ref.slice("#/definitions/".length) : null;
43
+ if (name === null || expanding.has(name) || !Object.prototype.hasOwnProperty.call(definitions, name)) {
44
+ return siblings;
45
+ }
46
+ const target = expandRecursion(
47
+ definitions[name],
48
+ definitions,
49
+ /* @__PURE__ */ new Set([...expanding, name])
50
+ );
51
+ return { ...target, ...siblings };
52
+ }
25
53
  function describeToolSchema(tool, config, ctx = {}) {
26
54
  const params = (tool.parameters ?? []).flatMap((p) => {
27
55
  const effectiveSchema = p.type === "Query" ? queryParameterSchema(p.name, p.schema, config) : p.schema;
28
56
  if (!effectiveSchema) return [];
29
57
  const { inner, optional } = unwrapOptional(effectiveSchema);
30
58
  const isPath = p.type === "Path";
31
- const jsonSchema = zodToJsonSchema(inner, { target: "jsonSchema7", $refStrategy: "none" });
32
- const { $schema: _s, ...schema } = jsonSchema;
59
+ const schema = toParamJsonSchema(inner);
33
60
  return [
34
61
  {
35
62
  name: p.name,
36
63
  in: p.type,
37
64
  required: isPath || !optional,
38
- description: effectiveSchema.description ?? p.description,
65
+ description: effectiveSchema.description ?? inner.description ?? p.description,
39
66
  schema
40
67
  }
41
68
  ];
@@ -130,13 +157,12 @@ function describeUtilityToolSchema(utility, ctx) {
130
157
  const schemaMap = utility.buildSchema(ctx);
131
158
  const params = Object.entries(schemaMap).map(([name, zodSchema]) => {
132
159
  const { inner, optional } = unwrapOptional(zodSchema);
133
- const jsonSchema = zodToJsonSchema(inner, { target: "jsonSchema7", $refStrategy: "none" });
134
- const { $schema: _s, ...schema } = jsonSchema;
160
+ const schema = toParamJsonSchema(inner);
135
161
  return {
136
162
  name,
137
163
  in: "Query",
138
164
  required: !optional,
139
- description: zodSchema.description,
165
+ description: zodSchema.description ?? inner.description,
140
166
  schema
141
167
  };
142
168
  });
@@ -150,5 +176,6 @@ function describeUtilityToolSchema(utility, ctx) {
150
176
  }
151
177
  export {
152
178
  describeToolSchema,
153
- describeUtilityToolSchema
179
+ describeUtilityToolSchema,
180
+ toParamJsonSchema
154
181
  };
@@ -8,6 +8,10 @@ function buildGeneralMcpInstructions(opts) {
8
8
  "Teams chat and channel messages: prefer HTML contentType in the body; plain text is often mangled by Graph.",
9
9
  "Files / binary content: for large drive/SharePoint file content, prefer get-download-url to resolve a pre-authenticated URL for out-of-band download. Use download-bytes for authenticated byte reads such as mail attachments, profile photos, Teams hosted content, and meeting recordings. In stdio mode (or HTTP with --http-local-file-tools), download-bytes-to-file writes those same authenticated bytes straight to a local absolute path instead of returning base64. For large mail attachments and meeting recordings that is one out-of-band option; get-download-url is the other, on a server running with --enable-attachment-urls. These tools take relative Microsoft Graph paths, not absolute URLs. For uploads, upload-file-content takes a base64 string body (Graph allows 250MB, but the whole string passes through the agent context and a truncated one is written without error); use create-upload-session for anything but small files."
10
10
  ];
11
+ if (opts.appMode)
12
+ parts.push(
13
+ "App mode: there is no signed-in user, so /me paths do not work. Name the user in /users/{user-id} paths with a UPN or object id."
14
+ );
11
15
  if (opts.readOnly) parts.push("This server is read-only; write operations are disabled.");
12
16
  if (opts.multiAccount)
13
17
  parts.push("Multiple accounts: pass the account parameter when required (see list-accounts).");