@softeria/ms-365-mcp-server 0.172.0 → 0.174.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
@@ -155,7 +155,7 @@ The `--list-permissions` JSON includes:
155
155
 
156
156
  ### Allowed Scopes
157
157
 
158
- By default, MSAL requests the scopes implied by the enabled tools, and the tool surface is controlled by `--enabled-tools`, `--preset`, `--org-mode`, and `--read-only`.
158
+ By default, MSAL requests the scopes implied by the enabled tools, and the tool surface is controlled by `--enabled-tools`, `--enabled-tools-file`, `--preset`, `--org-mode`, and `--read-only`.
159
159
 
160
160
  Enterprise and headless deployments can add a scope boundary with `--allowed-scopes` or `MS365_MCP_ALLOWED_SCOPES`. When configured, the server first computes the normal tool surface, then hides Graph tools whose required scopes are not covered by the allowlist. OAuth metadata and login flows request only the effective permissions for the tools that remain enabled.
161
161
 
@@ -166,6 +166,19 @@ npx @softeria/ms-365-mcp-server \
166
166
  --allowed-scopes 'User.Read Mail.Read Files.Read'
167
167
  ```
168
168
 
169
+ For longer filters, put one regex per line in a file and pass `--enabled-tools-file` / `ENABLED_TOOLS_FILE`. Blank lines and whole-line `#` comments are dropped; the rest are joined with `|`, so the file is equivalent to `--enabled-tools=line1|line2|…`:
170
+
171
+ ```text
172
+ # tools.txt
173
+ ^list-mail-messages$
174
+ ^get-mail-message$
175
+ drive|download-bytes
176
+ ```
177
+
178
+ ```bash
179
+ npx @softeria/ms-365-mcp-server --org-mode --enabled-tools-file ./tools.txt
180
+ ```
181
+
169
182
  CLI value takes precedence over `MS365_MCP_ALLOWED_SCOPES`; if neither is set, the default tool-derived scope behavior is unchanged. Supplying an empty value fails at startup so deployments do not accidentally fall back to a wider tool surface.
170
183
 
171
184
  Scope coverage is hierarchy-aware: for example, `Mail.ReadWrite` covers tools that require `Mail.Read`, and `Files.ReadWrite.All` covers tools that require `Files.Read`.
@@ -636,6 +649,8 @@ npx @softeria/ms-365-mcp-server --list-presets # See all available presets
636
649
 
637
650
  Available presets: `mail`, `calendar`, `files`, `personal`, `work`, `excel`, `contacts`, `tasks`, `onenote`, `search`, `users`, `outlook`, `onedrive`, `teams`, `teams-write`, `all`
638
651
 
652
+ See **[PRESETS.md](PRESETS.md)** for the full list of tools each preset unlocks (regenerated on `npm run generate`).
653
+
639
654
  Each endpoint in `endpoints.json` declares which presets it belongs to via a `presets` array, so every preset is an exact tool-name allow-list that never over-matches across apps (e.g. `mail` does not include shared-mailbox tools; those are in `work`). The universal binary reader `download-bytes` is included in every preset except `teams-write`, so whatever an app returns (a file, an attachment, a photo, a recording) can always be fetched; `get-download-url` (a pre-authenticated URL for drive/SharePoint files) rides with the drive-backed presets, and joins every other preset (bar `teams-write`) when HTTP mode runs with `--enable-attachment-urls`. So a preset that can find a file can always read its bytes.
640
655
 
641
656
  The `outlook`, `onedrive` and `teams` presets are app-scoped: they expose exactly one Microsoft app. Use these for "expose exactly one app" deployments:
@@ -664,6 +679,31 @@ npx @softeria/ms-365-mcp-server --discovery
664
679
 
665
680
  Keeps the initial context small and cuts token usage, especially useful for long sessions or cost-sensitive setups (e.g. Open WebUI running against a paid API).
666
681
 
682
+ ### Hybrid discovery with direct tools
683
+
684
+ Keep the full enabled catalogue discoverable while exposing frequent operations directly:
685
+
686
+ ```bash
687
+ npx @softeria/ms-365-mcp-server --org-mode --discovery \
688
+ --eager-tools list-mail-messages,get-calendar-view,download-bytes
689
+ ```
690
+
691
+ `--eager-tools` accepts comma-separated **exact** Graph or utility tool names,
692
+ not a regular expression or preset. `MS365_MCP_EAGER_TOOLS` is the environment
693
+ fallback; the CLI wins. The option requires `--discovery`. Empty entries and
694
+ unknown names fail startup. Duplicate names are registered once.
695
+
696
+ Direct tools use the same schemas, annotations and execution handlers as normal
697
+ mode. They also remain searchable and executable through discovery. Existing
698
+ `--preset`, `--enabled-tools`, `--allowed-scopes`, `--read-only`, organization-mode
699
+ and transport restrictions apply first: an eager selection cannot enable a
700
+ filtered-out tool or add permissions. Recognized but unavailable tools are
701
+ omitted with a startup log message. HTTP still excludes server-local file tools.
702
+
703
+ Select a small set: exposing many generated Graph schemas can consume substantial
704
+ model context. This option does not shrink individual schemas. Without
705
+ `--eager-tools`, discovery and normal registration behave as before.
706
+
667
707
  ## CLI Options
668
708
 
669
709
  The following options can be used when running ms-365-mcp-server directly from the command line:
@@ -672,7 +712,7 @@ The following options can be used when running ms-365-mcp-server directly from t
672
712
  --login Login using device code flow
673
713
  --logout Log out and clear saved credentials
674
714
  --verify-login Verify login without starting the server
675
- --list-permissions List required Graph API permissions and exit (respects --org-mode, --preset, --enabled-tools, --allowed-scopes)
715
+ --list-permissions List required Graph API permissions and exit (respects --org-mode, --preset, --enabled-tools, --enabled-tools-file, --allowed-scopes)
676
716
  --org-mode Enable organization/work mode from start (includes Teams, SharePoint, etc.)
677
717
  --work-mode Alias for --org-mode
678
718
  --force-work-scopes Backwards compatibility alias for --org-mode (deprecated)
@@ -715,6 +755,9 @@ When running as an MCP server, the following options can be used:
715
755
  (requires --attachment-port; see "Splitting the attachment listener")
716
756
  --no-dynamic-registration Disable OAuth Dynamic Client Registration (enabled by default in HTTP mode)
717
757
  --enabled-tools <pattern> Filter tools using regex pattern (e.g., "excel|contact" to enable Excel and Contact tools)
758
+ --enabled-tools-file <path> Filter tools using a file with one regex per line (same as --enabled-tools;
759
+ blank lines and whole-line # comments ignored). Overrides --enabled-tools;
760
+ overridden by --preset. Equivalent env var: ENABLED_TOOLS_FILE
718
761
  --preset <names> Use preset tool categories (comma-separated). See "Tool Presets" section above
719
762
  --list-presets List all available presets and exit
720
763
  --toon (experimental) Enable TOON output format for 30-60% token reduction
@@ -728,6 +771,7 @@ Environment variables:
728
771
 
729
772
  - `READ_ONLY=true|1`: Alternative to --read-only flag
730
773
  - `ENABLED_TOOLS`: Filter tools using a regex pattern (alternative to --enabled-tools flag)
774
+ - `ENABLED_TOOLS_FILE`: Path to a file with one regex per line (alternative to --enabled-tools-file). Blank lines and whole-line `#` comments are dropped, then lines are joined with `|` (same as `ENABLED_TOOLS=line1|line2|…`). Layering (later wins): `--enabled-tools` → `--enabled-tools-file` → `--preset` → `ENABLED_TOOLS` → `ENABLED_TOOLS_FILE`
731
775
  - `MS365_MCP_ORG_MODE=true|1`: Enable organization/work mode (alternative to --org-mode flag)
732
776
  - `MS365_MCP_FORCE_WORK_SCOPES=true|1`: Backwards compatibility for MS365_MCP_ORG_MODE
733
777
  - `MS365_MCP_OUTPUT_FORMAT=toon`: Enable TOON output format (alternative to --toon flag)
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env npx tsx
2
+ /**
3
+ * Writes PRESETS.md from the live preset → tool mapping in tool-categories.ts.
4
+ * Invoked by `npm run generate`.
5
+ */
6
+ import { writeFileSync } from 'fs';
7
+ import path from 'path';
8
+ import { fileURLToPath } from 'url';
9
+ import prettier from 'prettier';
10
+ import { getToolsForPreset, listPresets } from '../src/tool-categories.js';
11
+
12
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
+ const rootDir = path.resolve(__dirname, '..');
14
+ const outFile = path.join(rootDir, 'PRESETS.md');
15
+
16
+ export async function renderPresetsMarkdown(): Promise<string> {
17
+ const catalog = listPresets().map((preset) => ({
18
+ ...preset,
19
+ tools: getToolsForPreset(preset.name),
20
+ }));
21
+ const lines: string[] = [
22
+ '# Tool Presets',
23
+ '',
24
+ '> Generated by `bin/generate-presets-md.ts`. Do not edit by hand; regenerated on `npm run generate`.',
25
+ '',
26
+ '',
27
+ '## Summary',
28
+ '',
29
+ '| Preset | Tools | Org mode | Description |',
30
+ '| ------ | ----: | -------- | ----------- |',
31
+ ];
32
+
33
+ for (const entry of catalog) {
34
+ const org = entry.requiresOrgMode ? 'required' : '';
35
+ const desc = entry.description.replace(/\|/g, '\\|');
36
+ lines.push(`| \`${entry.name}\` | ${entry.tools.length} | ${org} | ${desc} |`);
37
+ }
38
+
39
+ lines.push('');
40
+
41
+ for (const entry of catalog) {
42
+ lines.push(`## \`${entry.name}\``);
43
+ lines.push('');
44
+ lines.push(entry.description);
45
+ if (entry.requiresOrgMode) {
46
+ lines.push('');
47
+ lines.push('Requires `--org-mode`.');
48
+ }
49
+ lines.push('');
50
+ lines.push(`Tools (${entry.tools.length}):`);
51
+ lines.push('');
52
+ for (const tool of entry.tools) {
53
+ lines.push(`- \`${tool}\``);
54
+ }
55
+ lines.push('');
56
+ }
57
+
58
+ // Format here so PRESETS.md matches `prettier --check` and the staleness test.
59
+ return prettier.format(lines.join('\n'), { filepath: outFile });
60
+ }
61
+
62
+ async function main(): Promise<void> {
63
+ const presets = listPresets();
64
+ writeFileSync(outFile, await renderPresetsMarkdown(), 'utf8');
65
+ console.log(`Wrote ${path.relative(rootDir, outFile)} (${presets.length} presets)`);
66
+ }
67
+
68
+ const isDirectRun =
69
+ process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
70
+
71
+ if (isDirectRun) {
72
+ main().catch((error) => {
73
+ console.error(error);
74
+ process.exit(1);
75
+ });
76
+ }
package/dist/cli.js CHANGED
@@ -2,6 +2,7 @@ import { Command, Option } from "commander";
2
2
  import { readFileSync } from "fs";
3
3
  import path from "path";
4
4
  import { fileURLToPath } from "url";
5
+ import { readEnabledToolsFromFile } from "./lib/enabled-tools-file.js";
5
6
  import { assertSignoffMarkersVisible } from "./lib/message-signoff.js";
6
7
  import { assertUploadDirsAbsolute } from "./lib/upload-dirs.js";
7
8
  import { getCombinedPresetPattern, listPresets, presetRequiresOrgMode } from "./tool-categories.js";
@@ -40,6 +41,9 @@ program.name("ms-365-mcp-server").description("Microsoft 365 MCP Server").versio
40
41
  ).option(
41
42
  "--enabled-tools <pattern>",
42
43
  'Filter tools using regex pattern (e.g., "excel|contact" to enable Excel and Contact tools)'
44
+ ).option(
45
+ "--enabled-tools-file <path>",
46
+ "Filter tools using a file with one regex per line (same semantics as --enabled-tools; blank lines and whole-line # comments ignored). Overrides --enabled-tools; overridden by --preset. Equivalent env var: ENABLED_TOOLS_FILE."
43
47
  ).option(
44
48
  "--allowed-scopes <scopes>",
45
49
  "Limit exposed tools to Graph scopes covered by this whitespace-separated allowlist"
@@ -55,7 +59,10 @@ program.name("ms-365-mcp-server").description("Microsoft 365 MCP Server").versio
55
59
  ).option("--list-presets", "List all available presets and exit").option("--list-permissions", "List all required Graph API permissions and exit").option(
56
60
  "--org-mode",
57
61
  "Enable organization/work mode from start (includes Teams, SharePoint, etc.)"
58
- ).option("--work-mode", "Alias for --org-mode").option("--force-work-scopes", "Backwards compatibility alias for --org-mode (deprecated)").option("--toon", "(experimental) Enable TOON output format for 30-60% token reduction").option("--discovery", "Enable runtime tool discovery and loading (experimental feature)").option(
62
+ ).option("--work-mode", "Alias for --org-mode").option("--force-work-scopes", "Backwards compatibility alias for --org-mode (deprecated)").option("--toon", "(experimental) Enable TOON output format for 30-60% token reduction").option(
63
+ "--eager-tools <names>",
64
+ "With --discovery, also expose these comma-separated exact Graph or utility tool names directly. All enabled tools remain discoverable. Env: MS365_MCP_EAGER_TOOLS."
65
+ ).option("--discovery", "Enable runtime tool discovery and loading (experimental feature)").option(
59
66
  "--cloud <type>",
60
67
  "Microsoft cloud environment: global (default), china (21Vianet) or gcc-high (US Government GCC High)"
61
68
  ).option(
@@ -114,6 +121,23 @@ function parseArgs() {
114
121
  console.log(JSON.stringify({ presets }, null, 2));
115
122
  process.exit(0);
116
123
  }
124
+ if (typeof options.enabledToolsFile === "string") {
125
+ try {
126
+ options.enabledTools = readEnabledToolsFromFile(options.enabledToolsFile);
127
+ } catch (error) {
128
+ console.error(`Error: ${error.message}`);
129
+ process.exit(1);
130
+ }
131
+ }
132
+ delete options.enabledToolsFile;
133
+ const eagerValue = options.eagerTools ?? process.env.MS365_MCP_EAGER_TOOLS;
134
+ if (eagerValue !== void 0) {
135
+ if (!options.discovery) throw new Error("--eager-tools requires --discovery");
136
+ const names = String(eagerValue).split(",").map((name) => name.trim());
137
+ if (names.some((name) => name === ""))
138
+ throw new Error("--eager-tools requires non-empty exact tool names");
139
+ options.eagerTools = [...new Set(names)];
140
+ }
117
141
  if (options.preset) {
118
142
  const presetNames = options.preset.split(",").map((p) => p.trim());
119
143
  try {
@@ -137,6 +161,14 @@ function parseArgs() {
137
161
  if (process.env.ENABLED_TOOLS) {
138
162
  options.enabledTools = process.env.ENABLED_TOOLS;
139
163
  }
164
+ if (process.env.ENABLED_TOOLS_FILE) {
165
+ try {
166
+ options.enabledTools = readEnabledToolsFromFile(process.env.ENABLED_TOOLS_FILE);
167
+ } catch (error) {
168
+ console.error(`Error: ${error.message}`);
169
+ process.exit(1);
170
+ }
171
+ }
140
172
  if (options.allowedScopes === void 0 && process.env.MS365_MCP_ALLOWED_SCOPES !== void 0) {
141
173
  options.allowedScopes = process.env.MS365_MCP_ALLOWED_SCOPES;
142
174
  }
@@ -2310,6 +2310,87 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2310
2310
  };
2311
2311
  }
2312
2312
  }
2313
+ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, options) {
2314
+ const { authManager, multiAccount = false, accountNames = [] } = options;
2315
+ const userFields = parseUserFields(options.userFields);
2316
+ const paramSchema = {};
2317
+ if (tool.parameters && tool.parameters.length > 0) {
2318
+ for (const param of tool.parameters) {
2319
+ if (param.type === "Query") {
2320
+ const schema = queryParameterSchema(param.name, param.schema || z.any(), endpointConfig);
2321
+ if (schema) paramSchema[param.name] = schema;
2322
+ continue;
2323
+ }
2324
+ paramSchema[param.name] = param.type === "Body" && param.schema ? lenientBodySchema(param.schema) : param.schema || z.any();
2325
+ }
2326
+ }
2327
+ const pathParamMatches = tool.path.matchAll(/:([a-zA-Z]+)/g);
2328
+ for (const match of pathParamMatches) {
2329
+ const pathParamName = match[1];
2330
+ if (!(pathParamName in paramSchema)) {
2331
+ paramSchema[pathParamName] = z.string().describe(describePathParam(pathParamName));
2332
+ }
2333
+ }
2334
+ if (endpointConfig?.acceptType && paramSchema["Accept"] === void 0) {
2335
+ paramSchema["Accept"] = z.string().describe(getAcceptParamDescription(endpointConfig.acceptType)).optional();
2336
+ }
2337
+ if (endpointConfig?.blobOutput && paramSchema["fileName"] === void 0) {
2338
+ paramSchema["fileName"] = z.string().describe(
2339
+ "Name of the file, used as the last segment of the returned resource URI when the server runs with blob output. Optional."
2340
+ ).optional();
2341
+ }
2342
+ if (isFetchAllPagesApplicable(tool)) {
2343
+ const maxPages = getMaxPages();
2344
+ paramSchema["fetchAllPages"] = z.boolean().describe(getFetchAllPagesParamDescription(maxPages, endpointConfig)).optional();
2345
+ }
2346
+ if (endpointConfig?.nameFilter) {
2347
+ paramSchema["name"] = z.string().describe(MEMBER_NAME_PARAM_DESCRIPTION).optional();
2348
+ }
2349
+ if (isSkiptokenApplicable(tool, Object.keys(paramSchema), endpointConfig)) {
2350
+ paramSchema["skiptoken"] = z.string().describe(SKIPTOKEN_PARAM_DESCRIPTION).optional();
2351
+ }
2352
+ if (multiAccount) {
2353
+ paramSchema["account"] = z.string().describe(getAccountParamDescription(accountNames)).optional();
2354
+ }
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();
2357
+ const destructive = isDestructiveOperation(tool.method, endpointConfig);
2358
+ if (destructive) {
2359
+ paramSchema["confirm"] = z.boolean().describe(CONFIRM_PARAM_DESCRIPTION).optional();
2360
+ }
2361
+ if (endpointConfig?.supportsTimezone) {
2362
+ paramSchema["timezone"] = z.string().describe(TIMEZONE_PARAM_DESCRIPTION).optional();
2363
+ }
2364
+ if (endpointConfig?.supportsExpandExtendedProperties) {
2365
+ paramSchema["expandExtendedProperties"] = z.boolean().describe(EXPAND_EXTENDED_PROPERTIES_PARAM_DESCRIPTION).optional();
2366
+ }
2367
+ let toolDescription = withApiVersionPrefix(
2368
+ (endpointConfig?.descriptionOverride ?? tool.description) || `Execute ${tool.method.toUpperCase()} request to ${tool.path}`,
2369
+ endpointConfig
2370
+ );
2371
+ if (endpointConfig?.llmTip) {
2372
+ toolDescription += `
2373
+
2374
+ \u{1F4A1} TIP: ${endpointConfig.llmTip}`;
2375
+ }
2376
+ const isReadOnlyTool = tool.method.toUpperCase() === "GET" || endpointConfig?.readOnly === true;
2377
+ server.registerTool(
2378
+ tool.alias,
2379
+ {
2380
+ title: tool.alias,
2381
+ description: toolDescription,
2382
+ inputSchema: z.object(paramSchema).passthrough(),
2383
+ annotations: {
2384
+ title: tool.alias,
2385
+ readOnlyHint: isReadOnlyTool,
2386
+ destructiveHint: destructive,
2387
+ openWorldHint: true
2388
+ // All tools call Microsoft Graph API
2389
+ }
2390
+ },
2391
+ async (params) => executeGraphTool(tool, endpointConfig, graphClient, params, authManager, userFields)
2392
+ );
2393
+ }
2313
2394
  function registerGraphTools(server, graphClient, options = {}) {
2314
2395
  const {
2315
2396
  readOnly = false,
@@ -2373,84 +2454,8 @@ function registerGraphTools(server, graphClient, options = {}) {
2373
2454
  skippedCount++;
2374
2455
  continue;
2375
2456
  }
2376
- const paramSchema = {};
2377
- if (tool.parameters && tool.parameters.length > 0) {
2378
- for (const param of tool.parameters) {
2379
- if (param.type === "Query") {
2380
- const schema = queryParameterSchema(param.name, param.schema || z.any(), endpointConfig);
2381
- if (schema) paramSchema[param.name] = schema;
2382
- continue;
2383
- }
2384
- paramSchema[param.name] = param.type === "Body" && param.schema ? lenientBodySchema(param.schema) : param.schema || z.any();
2385
- }
2386
- }
2387
- const pathParamMatches = tool.path.matchAll(/:([a-zA-Z]+)/g);
2388
- for (const match of pathParamMatches) {
2389
- const pathParamName = match[1];
2390
- if (!(pathParamName in paramSchema)) {
2391
- paramSchema[pathParamName] = z.string().describe(describePathParam(pathParamName));
2392
- }
2393
- }
2394
- if (endpointConfig?.acceptType && paramSchema["Accept"] === void 0) {
2395
- paramSchema["Accept"] = z.string().describe(getAcceptParamDescription(endpointConfig.acceptType)).optional();
2396
- }
2397
- if (endpointConfig?.blobOutput && paramSchema["fileName"] === void 0) {
2398
- paramSchema["fileName"] = z.string().describe(
2399
- "Name of the file, used as the last segment of the returned resource URI when the server runs with blob output. Optional."
2400
- ).optional();
2401
- }
2402
- if (isFetchAllPagesApplicable(tool)) {
2403
- const maxPages = getMaxPages();
2404
- paramSchema["fetchAllPages"] = z.boolean().describe(getFetchAllPagesParamDescription(maxPages, endpointConfig)).optional();
2405
- }
2406
- if (endpointConfig?.nameFilter) {
2407
- paramSchema["name"] = z.string().describe(MEMBER_NAME_PARAM_DESCRIPTION).optional();
2408
- }
2409
- if (isSkiptokenApplicable(tool, Object.keys(paramSchema), endpointConfig)) {
2410
- paramSchema["skiptoken"] = z.string().describe(SKIPTOKEN_PARAM_DESCRIPTION).optional();
2411
- }
2412
- if (multiAccount) {
2413
- paramSchema["account"] = z.string().describe(getAccountParamDescription(accountNames)).optional();
2414
- }
2415
- paramSchema["includeHeaders"] = z.boolean().describe("Include response headers (including ETag) in the response metadata").optional();
2416
- paramSchema["excludeResponse"] = z.boolean().describe("Exclude the full response body and only return success or failure indication").optional();
2417
- const destructive = isDestructiveOperation(tool.method, endpointConfig);
2418
- if (destructive) {
2419
- paramSchema["confirm"] = z.boolean().describe(CONFIRM_PARAM_DESCRIPTION).optional();
2420
- }
2421
- if (endpointConfig?.supportsTimezone) {
2422
- paramSchema["timezone"] = z.string().describe(TIMEZONE_PARAM_DESCRIPTION).optional();
2423
- }
2424
- if (endpointConfig?.supportsExpandExtendedProperties) {
2425
- paramSchema["expandExtendedProperties"] = z.boolean().describe(EXPAND_EXTENDED_PROPERTIES_PARAM_DESCRIPTION).optional();
2426
- }
2427
- let toolDescription = withApiVersionPrefix(
2428
- (endpointConfig?.descriptionOverride ?? tool.description) || `Execute ${tool.method.toUpperCase()} request to ${tool.path}`,
2429
- endpointConfig
2430
- );
2431
- if (endpointConfig?.llmTip) {
2432
- toolDescription += `
2433
-
2434
- \u{1F4A1} TIP: ${endpointConfig.llmTip}`;
2435
- }
2436
- const isReadOnlyTool = tool.method.toUpperCase() === "GET" || endpointConfig?.readOnly === true;
2437
2457
  try {
2438
- server.registerTool(
2439
- tool.alias,
2440
- {
2441
- title: tool.alias,
2442
- description: toolDescription,
2443
- inputSchema: z.object(paramSchema).passthrough(),
2444
- annotations: {
2445
- title: tool.alias,
2446
- readOnlyHint: isReadOnlyTool,
2447
- destructiveHint: destructive,
2448
- openWorldHint: true
2449
- // All tools call Microsoft Graph API
2450
- }
2451
- },
2452
- async (params) => executeGraphTool(tool, endpointConfig, graphClient, params, authManager, userFields)
2453
- );
2458
+ registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, options);
2454
2459
  registeredCount++;
2455
2460
  } catch (error) {
2456
2461
  logger.error(`Failed to register tool ${tool.alias}: ${error.message}`);
@@ -2604,6 +2609,13 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
2604
2609
  httpMode = false,
2605
2610
  userFields: userFieldsValue
2606
2611
  } = options;
2612
+ const eagerNames = new Set(options.eagerTools ?? []);
2613
+ const knownNames = /* @__PURE__ */ new Set([
2614
+ ...allEndpoints.map((t) => t.alias),
2615
+ ...UTILITY_TOOLS.map((t) => t.name)
2616
+ ]);
2617
+ const unknown = [...eagerNames].filter((name) => !knownNames.has(name));
2618
+ if (unknown.length > 0) throw new Error(`Unknown eager tool names: ${unknown.join(", ")}`);
2607
2619
  const userFields = parseUserFields(userFieldsValue);
2608
2620
  let enabledToolsRegex;
2609
2621
  if (enabledTools) {
@@ -2643,6 +2655,29 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
2643
2655
  if (enabledToolsRegex && !enabledToolsRegex.test(u.name)) return false;
2644
2656
  return true;
2645
2657
  });
2658
+ for (const name of eagerNames) {
2659
+ try {
2660
+ const entry = toolsRegistry.get(name);
2661
+ if (entry) {
2662
+ registerGraphToolWithMcp(server, entry.tool, entry.config, graphClient, options);
2663
+ continue;
2664
+ }
2665
+ const utility = utilityTools.find((tool) => tool.name === name);
2666
+ if (utility) {
2667
+ registerUtilityToolWithMcp(server, utility, {
2668
+ graphClient,
2669
+ authManager,
2670
+ multiAccount,
2671
+ accountNames,
2672
+ userFields
2673
+ });
2674
+ continue;
2675
+ }
2676
+ logger.info(`Eager tool ${name} is unavailable under the current filters or transport`);
2677
+ } catch (error) {
2678
+ logger.error(`Failed to register eager tool ${name}: ${error.message}`);
2679
+ }
2680
+ }
2646
2681
  const searchIndex = buildDiscoverySearchIndex(toolsRegistry, utilityTools);
2647
2682
  const totalCount = toolsRegistry.size + utilityTools.length;
2648
2683
  logger.info(
@@ -0,0 +1,19 @@
1
+ import { readFileSync } from "node:fs";
2
+ function parseEnabledToolsFileContent(content) {
3
+ return content.split(/\r?\n/).map((line) => line.trim()).filter((line) => !line.startsWith("#")).filter((line) => line.length > 0).join("|");
4
+ }
5
+ function readEnabledToolsFromFile(filePath) {
6
+ let content;
7
+ try {
8
+ content = readFileSync(filePath, "utf8");
9
+ } catch (error) {
10
+ throw new Error(
11
+ `could not read enabled tools file ${JSON.stringify(filePath)}: ${error.message}`
12
+ );
13
+ }
14
+ return parseEnabledToolsFileContent(content);
15
+ }
16
+ export {
17
+ parseEnabledToolsFileContent,
18
+ readEnabledToolsFromFile
19
+ };
@@ -19,7 +19,8 @@ const DISCOVERY_MODE_INSTRUCTIONS_ADDON = "DISCOVERY MODE ADD-ON: Graph is reach
19
19
  function buildMcpServerInstructions(opts) {
20
20
  const general = buildGeneralMcpInstructions(opts);
21
21
  if (!opts.discovery) return general;
22
- return `${general} ${DISCOVERY_MODE_INSTRUCTIONS_ADDON}`;
22
+ const eager = opts.eagerTools?.length ? " HYBRID MODE: Tools published directly may be called immediately using their schemas. Use discovery for other operations; directly published tools also remain available through discovery." : "";
23
+ return `${general} ${DISCOVERY_MODE_INSTRUCTIONS_ADDON}${eager}`;
23
24
  }
24
25
  export {
25
26
  buildMcpServerInstructions
package/dist/server.js CHANGED
@@ -179,6 +179,7 @@ class MicrosoftGraphServer {
179
179
  {
180
180
  instructions: buildMcpServerInstructions({
181
181
  discovery: Boolean(this.options.discovery),
182
+ eagerTools: this.options.eagerTools,
182
183
  orgMode: Boolean(this.options.orgMode),
183
184
  readOnly: Boolean(this.options.readOnly),
184
185
  multiAccount: this.multiAccount
@@ -191,6 +192,7 @@ class MicrosoftGraphServer {
191
192
  }
192
193
  const registrationOptions = {
193
194
  readOnly: this.options.readOnly,
195
+ eagerTools: this.options.eagerTools,
194
196
  enabledTools: this.options.enabledTools,
195
197
  orgMode: this.options.orgMode,
196
198
  authManager: this.authManager,
@@ -76,19 +76,28 @@ for (const [tool, presets] of Object.entries(SCOPED_UTILITY_TOOLS)) {
76
76
  }
77
77
  }
78
78
  }
79
- function presetPattern(preset) {
79
+ function getToolsForPreset(preset) {
80
+ if (preset === "all") {
81
+ const endpointNames2 = [...new Set(endpointEntries.map((e) => e.toolName))];
82
+ const utilityNames = [...UNIVERSAL_UTILITY_TOOLS, ...Object.keys(SCOPED_UTILITY_TOOLS)];
83
+ return [.../* @__PURE__ */ new Set([...endpointNames2, ...utilityNames])].sort();
84
+ }
80
85
  const endpointNames = [
81
86
  ...new Set(endpointEntries.filter((e) => e.presets?.includes(preset)).map((e) => e.toolName))
82
87
  ];
83
88
  if (endpointNames.length === 0) {
84
89
  throw new Error(`Preset "${preset}" matches no endpoints in endpoints.json`);
85
90
  }
86
- const names = [
87
- ...endpointNames,
88
- ...PRESET_META[preset]?.omitUniversalUtilities ? [] : UNIVERSAL_UTILITY_TOOLS,
89
- ...Object.entries(SCOPED_UTILITY_TOOLS).filter(([, presets]) => presets.includes(preset)).map(([name]) => name)
90
- ];
91
- return new RegExp(`^(?:${names.join("|")})$`);
91
+ return [
92
+ .../* @__PURE__ */ new Set([
93
+ ...endpointNames,
94
+ ...PRESET_META[preset]?.omitUniversalUtilities ? [] : UNIVERSAL_UTILITY_TOOLS,
95
+ ...Object.entries(SCOPED_UTILITY_TOOLS).filter(([, presets]) => presets.includes(preset)).map(([name]) => name)
96
+ ])
97
+ ].sort();
98
+ }
99
+ function presetPattern(preset) {
100
+ return new RegExp(`^(?:${getToolsForPreset(preset).join("|")})$`);
92
101
  }
93
102
  const TOOL_CATEGORIES = {
94
103
  ...Object.fromEntries(
@@ -123,7 +132,7 @@ function listPresets() {
123
132
  name: category.name,
124
133
  description: category.description,
125
134
  requiresOrgMode: category.requiresOrgMode
126
- }));
135
+ })).sort((a, b) => a.name.localeCompare(b.name));
127
136
  }
128
137
  function presetRequiresOrgMode(preset) {
129
138
  const category = TOOL_CATEGORIES[preset];
@@ -132,6 +141,7 @@ function presetRequiresOrgMode(preset) {
132
141
  export {
133
142
  TOOL_CATEGORIES,
134
143
  getCombinedPresetPattern,
144
+ getToolsForPreset,
135
145
  listPresets,
136
146
  presetRequiresOrgMode
137
147
  };
@@ -228,7 +228,7 @@ The client automatically discovers OAuth endpoints and opens a browser for authe
228
228
  - **Admin consent**: grant tenant-wide consent to avoid per-user consent prompts
229
229
  - **Managed identity**: use managed identity for Key Vault access (no secrets in environment variables)
230
230
  - **Read-only mode**: use `--read-only` to disable all write operations (send, delete, update, create)
231
- - **Tool filtering**: use `--enabled-tools <regex>` or `--preset <names>` to restrict available tools
231
+ - **Tool filtering**: use `--enabled-tools <regex>`, `--enabled-tools-file <path>` (one regex per line), or `--preset <names>` to restrict available tools
232
232
  - **CORS**: configure `MS365_MCP_CORS_ORIGIN` to restrict allowed origins (defaults to `http://localhost:3000`); set explicitly when clients run on a different origin
233
233
  - **Disable Dynamic Client Registration**: when only a known client talks to the server, set `MS365_MCP_DISABLE_DCR=true` (or pass `--no-dynamic-registration`) to close the anonymous `/register` endpoint
234
234
  - **Structured audit log**: enabled by default. Every tool invocation that reaches Microsoft Graph emits one JSON line on stderr (captured by the container platform's log collector) and to `~/.ms-365-mcp-server/logs/audit.log` (mode `0o600`, or under `MS365_MCP_LOG_DIR` when set) with `{ event, request_id, user_principal_name, tool, http_method, http_status?, status, duration_ms, recipient_count?, recipient_domains?, recipient_domains_truncated?, graph_batch_subrequest_count?, graph_batch_http_status_counts?, graph_batch_error_code_counts?, result_count?, result_has_more?, response_bytes?, target_resource?, error_type?, error_code? }`. A few refusals short-circuit before that and emit nothing: a confirm-gate rejection, an `account` param that contradicts the bearer identity, and a failure to resolve an account token. Policy-blocked tool attempts emit `event: "tool.denied"` with `status: "denied"`, `reason` (`allowed_scopes` or `tool_allowlist`), and `missing_scopes` when applicable. When an audited generated Microsoft Graph tool targets a derivable resource through an ID-like path parameter such as `{message-id}` or `{driveItem-id}`, `target_resource` is `{ type, id }`, where `id` is the Graph path up to that resource ID. Later path parameters such as `{path}`, query values, returned content, and Graph response bodies are NEVER recorded, and error messages are reduced to `error_type` / `error_code` so upstream library errors do not leak token fragments or query-string PII. Response _metadata_ is recorded — `result_count`, `result_has_more` and `response_bytes` describe how much came back so that a bulk read is distinguishable from an ordinary one; none of them reveals any of its content. Two things derived from tool parameters **are** recorded, both deliberately. First, `target_resource.id` substitutes ID-like path parameters into the resource path, so a tool on `/users/{user-id}/...` records whatever identifier the caller passed, which may be a full email address. Second, a request whose body carries `toRecipients` / `ccRecipients` / `bccRecipients` / `attendees` / `recipients`, at any casing and several levels down, including inside a `graph-batch` sub-request, records `recipient_count`, the number of entries in those arrays, and `recipient_domains`, the **domain part only** of their addresses and only where it parses as a plain hostname, never the local part and never a subject or message body. An entry that names someone without an address (a `driveRecipient` given as `alias` or `objectId`) counts but contributes no domain. It keys on body shape rather than on the endpoint, so it covers sends, forwards, invites and file shares but equally draft creation and edits, event updates and `findMeetingTimes`, and it reads high rather than low: an attached message's own recipients are counted too. `recipient_domains` holds at most 50 **distinct domains**, alphabetically, and sets `recipient_domains_truncated: true` when there were more; `recipient_count` is unaffected by the cap. All three are absent when the body carries no recipient array at all. A request that fails after reaching Graph still records recipients, since a timeout is not proof of non-delivery. Gaps remain, so absence proves nothing: a draft composed outside this server and sent by id, the original thread's recipients on a reply (Graph resolves those server-side), and a body nesting recipients deeper than the walker descends. This describes the structured audit log only; the operational logger is separate and does log tool parameters. Forms the "who accessed what, when" trail required for GDPR / HIPAA / PIPEDA / SOC 2 audit. Opt-out: `MS365_MCP_AUDIT_LOG=false`
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.172.0",
4
+ "version": "0.174.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",
@@ -9,7 +9,7 @@
9
9
  "ms-365-mcp-server": "dist/index.js"
10
10
  },
11
11
  "scripts": {
12
- "generate": "node bin/generate-graph-client.mjs",
12
+ "generate": "node bin/generate-graph-client.mjs && tsx bin/generate-presets-md.ts",
13
13
  "build": "tsup",
14
14
  "test": "vitest run",
15
15
  "test:watch": "vitest",
@@ -35,7 +35,7 @@
35
35
  "access": "public"
36
36
  },
37
37
  "dependencies": {
38
- "@azure/msal-node": "^5.2.2",
38
+ "@azure/msal-node": "^7.1.1",
39
39
  "@modelcontextprotocol/sdk": "^1.29.0",
40
40
  "@toon-format/toon": "^2.3.1",
41
41
  "commander": "^11.1.0",