@softeria/ms-365-mcp-server 0.190.5 → 0.191.1

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
@@ -23,8 +23,7 @@ To route Graph traffic through a proxy of your own (one that terminates the clie
23
23
 
24
24
  ## Prerequisites
25
25
 
26
- - Node.js >= 20 (recommended)
27
- - Node.js 14+ may work with dependency warnings
26
+ - Node.js >= 20
28
27
 
29
28
  ## Features
30
29
 
@@ -850,7 +849,8 @@ When running as an MCP server, the following options can be used:
850
849
  Starts Express.js server with MCP endpoint at /mcp. Bound to a loopback host
851
850
  (e.g. --http 127.0.0.1:3000 or --http [::1]:3000) with no --public-url, it
852
851
  rejects requests whose Host or Origin is not localhost (not applied to the
853
- --attachment-port listener)
852
+ --attachment-port listener). Serves both MCP 2026-07-28 clients and 2025-era
853
+ clients on the same /mcp endpoint
854
854
  --http-local-file-tools Register download-bytes-to-file over HTTP. Anyone who can reach the port
855
855
  can write files as the server's user (without a valid token, only an empty
856
856
  file that is removed again), so enable it only on a single-user machine.
@@ -131,12 +131,6 @@ function createMockServer() {
131
131
  };
132
132
  return {
133
133
  server: lowLevelServer,
134
- tool: vi.fn(
135
- (name, description, schema, annotations, handler) => {
136
- tools.set(name, { description, schema, handler });
137
- installDefaultToolCallHandler();
138
- }
139
- ),
140
134
  registerTool: vi.fn(
141
135
  (name, config, handler) => {
142
136
  tools.set(name, {
@@ -3185,7 +3179,17 @@ describe("graph-tools", () => {
3185
3179
  },
3186
3180
  {}
3187
3181
  )
3188
- ).rejects.toThrow(/not found/);
3182
+ ).resolves.toMatchObject({
3183
+ isError: true,
3184
+ content: [
3185
+ {
3186
+ type: "text",
3187
+ text: expect.stringMatching(
3188
+ /^Tool get-drive-item is not available in this server configuration: .*Files\.Read/
3189
+ )
3190
+ }
3191
+ ]
3192
+ });
3189
3193
  expect(auditLogMock).toHaveBeenCalledWith(
3190
3194
  expect.objectContaining({
3191
3195
  event: "tool.denied",
@@ -3315,7 +3319,17 @@ describe("graph-tools", () => {
3315
3319
  },
3316
3320
  {}
3317
3321
  )
3318
- ).rejects.toThrow(/not found/);
3322
+ ).resolves.toMatchObject({
3323
+ isError: true,
3324
+ content: [
3325
+ {
3326
+ type: "text",
3327
+ text: expect.stringMatching(
3328
+ /^Tool get-drive-item is not available in this server configuration: .*Files\.Read/
3329
+ )
3330
+ }
3331
+ ]
3332
+ });
3319
3333
  expect(auditLogMock).toHaveBeenCalledWith(
3320
3334
  expect.objectContaining({
3321
3335
  event: "tool.denied",
@@ -3524,8 +3538,8 @@ describe("graph-tools", () => {
3524
3538
  const server = createMockServer();
3525
3539
  const { registerGraphTools } = await loadModule();
3526
3540
  registerGraphTools(server, {}, { readOnly: true });
3527
- const call = server.tool.mock.calls.find((c) => c[0] === "download-bytes-to-file");
3528
- expect(call?.[3]).toEqual({
3541
+ const call = server.registerTool.mock.calls.find((c) => c[0] === "download-bytes-to-file");
3542
+ expect(call?.[1].annotations).toEqual({
3529
3543
  title: "download-bytes-to-file",
3530
3544
  readOnlyHint: false,
3531
3545
  destructiveHint: false,
@@ -3540,7 +3554,7 @@ describe("graph-tools", () => {
3540
3554
  const server = createMockServer();
3541
3555
  const { registerGraphTools } = await loadModule();
3542
3556
  registerGraphTools(server, {}, {});
3543
- const withHint = server.tool.mock.calls.filter((c) => "destructiveHint" in c[3]).map((c) => c[0]);
3557
+ const withHint = server.registerTool.mock.calls.filter((c) => "destructiveHint" in (c[1].annotations ?? {})).map((c) => c[0]);
3544
3558
  expect(withHint).toEqual(["download-bytes-to-file"]);
3545
3559
  });
3546
3560
  });
package/dist/app-mode.js CHANGED
@@ -134,6 +134,7 @@ function managedIdentitySecrets() {
134
134
  }
135
135
  const CREDENTIAL_OPTIONS = "MS365_MCP_CLIENT_SECRET, MS365_MCP_CLIENT_CERTIFICATE_PATH, MS365_MCP_FEDERATED_TOKEN_FILE or MS365_MCP_MANAGED_IDENTITY";
136
136
  class AppTokenClient {
137
+ acquire;
137
138
  constructor(secrets, env = credentialEnvFromProcess()) {
138
139
  const set = [
139
140
  secrets.clientSecret && "a client secret (MS365_MCP_CLIENT_SECRET, .env or Key Vault)",
@@ -1,12 +1,7 @@
1
1
  import { z } from "zod";
2
+ import { withServedInputSchema } from "./lib/body-schema-budget.js";
2
3
  import logger from "./logger.js";
3
4
  import { getRequestTokens } from "./request-context.js";
4
- function readOnlyHintOf(args) {
5
- const annotations = args.find(
6
- (arg) => typeof arg === "object" && arg !== null && "readOnlyHint" in arg
7
- );
8
- return annotations?.readOnlyHint === true;
9
- }
10
5
  function registerAuthTools(mcpServer, authManager, options = {}) {
11
6
  let enabledToolsRegex;
12
7
  if (options.enabledTools) {
@@ -15,20 +10,24 @@ function registerAuthTools(mcpServer, authManager, options = {}) {
15
10
  } catch {
16
11
  }
17
12
  }
18
- const server = {
19
- tool: ((name, ...args) => {
20
- if (options.readOnly && !readOnlyHintOf(args)) return void 0;
21
- if (enabledToolsRegex && !enabledToolsRegex.test(name)) return void 0;
22
- return mcpServer.tool.call(mcpServer, name, ...args);
23
- })
13
+ const register = (name, config, cb) => {
14
+ if (options.readOnly && config.annotations.readOnlyHint !== true) return;
15
+ if (enabledToolsRegex && !enabledToolsRegex.test(name)) return;
16
+ mcpServer.registerTool(
17
+ name,
18
+ { ...config, inputSchema: withServedInputSchema(config.inputSchema, name) },
19
+ cb
20
+ );
24
21
  };
25
- server.tool(
22
+ register(
26
23
  "login",
27
- "Authenticate with Microsoft account",
28
24
  {
29
- force: z.boolean().default(false).describe("Force a new login even if already logged in")
25
+ description: "Authenticate with Microsoft account",
26
+ inputSchema: z.object({
27
+ force: z.boolean().default(false).describe("Force a new login even if already logged in")
28
+ }),
29
+ annotations: { title: "login", readOnlyHint: false, openWorldHint: false }
30
30
  },
31
- { title: "login", readOnlyHint: false, openWorldHint: false },
32
31
  async ({ force }) => {
33
32
  try {
34
33
  if (!force) {
@@ -91,11 +90,13 @@ function registerAuthTools(mcpServer, authManager, options = {}) {
91
90
  }
92
91
  }
93
92
  );
94
- server.tool(
93
+ register(
95
94
  "logout",
96
- "Log out from Microsoft account",
97
- {},
98
- { title: "logout", readOnlyHint: false, openWorldHint: false },
95
+ {
96
+ description: "Log out from Microsoft account",
97
+ inputSchema: z.object({}),
98
+ annotations: { title: "logout", readOnlyHint: false, openWorldHint: false }
99
+ },
99
100
  async () => {
100
101
  try {
101
102
  await authManager.logout();
@@ -119,11 +120,13 @@ function registerAuthTools(mcpServer, authManager, options = {}) {
119
120
  }
120
121
  }
121
122
  );
122
- server.tool(
123
+ register(
123
124
  "verify-login",
124
- "Check current Microsoft authentication status",
125
- {},
126
- { title: "verify-login", readOnlyHint: true, openWorldHint: false },
125
+ {
126
+ description: "Check current Microsoft authentication status",
127
+ inputSchema: z.object({}),
128
+ annotations: { title: "verify-login", readOnlyHint: true, openWorldHint: false }
129
+ },
127
130
  async () => {
128
131
  let testResult;
129
132
  try {
@@ -144,14 +147,16 @@ function registerAuthTools(mcpServer, authManager, options = {}) {
144
147
  };
145
148
  }
146
149
  );
147
- server.tool(
150
+ register(
148
151
  "list-accounts",
149
- "List all Microsoft accounts configured in this server. Use this to discover available account emails before making tool calls. Reflects accounts added mid-session via --login.",
150
- {},
151
152
  {
152
- title: "list-accounts",
153
- readOnlyHint: true,
154
- openWorldHint: false
153
+ description: "List all Microsoft accounts configured in this server. Use this to discover available account emails before making tool calls. Reflects accounts added mid-session via --login.",
154
+ inputSchema: z.object({}),
155
+ annotations: {
156
+ title: "list-accounts",
157
+ readOnlyHint: true,
158
+ openWorldHint: false
159
+ }
155
160
  },
156
161
  async () => {
157
162
  try {
@@ -191,13 +196,15 @@ function registerAuthTools(mcpServer, authManager, options = {}) {
191
196
  }
192
197
  }
193
198
  );
194
- server.tool(
199
+ register(
195
200
  "select-account",
196
- "Select a Microsoft account as the default. Accepts email address (e.g. user@outlook.com) or account ID. Use list-accounts to discover available accounts.",
197
201
  {
198
- account: z.string().describe("Email address or account ID of the account to select")
202
+ description: "Select a Microsoft account as the default. Accepts email address (e.g. user@outlook.com) or account ID. Use list-accounts to discover available accounts.",
203
+ inputSchema: z.object({
204
+ account: z.string().describe("Email address or account ID of the account to select")
205
+ }),
206
+ annotations: { title: "select-account", readOnlyHint: false, openWorldHint: false }
199
207
  },
200
- { title: "select-account", readOnlyHint: false, openWorldHint: false },
201
208
  async ({ account }) => {
202
209
  try {
203
210
  await authManager.selectAccount(account);
@@ -224,13 +231,15 @@ function registerAuthTools(mcpServer, authManager, options = {}) {
224
231
  }
225
232
  }
226
233
  );
227
- server.tool(
234
+ register(
228
235
  "remove-account",
229
- "Remove a Microsoft account from the cache. Accepts email address (e.g. user@outlook.com) or account ID. Use list-accounts to discover available accounts.",
230
236
  {
231
- account: z.string().describe("Email address or account ID of the account to remove")
237
+ description: "Remove a Microsoft account from the cache. Accepts email address (e.g. user@outlook.com) or account ID. Use list-accounts to discover available accounts.",
238
+ inputSchema: z.object({
239
+ account: z.string().describe("Email address or account ID of the account to remove")
240
+ }),
241
+ annotations: { title: "remove-account", readOnlyHint: false, openWorldHint: false }
232
242
  },
233
- { title: "remove-account", readOnlyHint: false, openWorldHint: false },
234
243
  async ({ account }) => {
235
244
  try {
236
245
  const success = await authManager.removeAccount(account);
package/dist/auth.js CHANGED
@@ -466,9 +466,26 @@ function consumersAuthorityHint(error, account, authority) {
466
466
  return null;
467
467
  }
468
468
  class AuthManager {
469
+ config;
470
+ scopes;
471
+ msalApp;
472
+ accessToken;
473
+ tokenExpiry;
474
+ oauthToken;
475
+ isOAuthMode;
476
+ selectedAccountId;
477
+ useInteractiveAuth;
478
+ expectedUsername;
479
+ expectedHomeAccountId;
480
+ storage;
481
+ /**
482
+ * A sign-in this process could not confirm reached the cache, plus which account it was
483
+ * about - with several cached, one account's failure must not answer for another (#648).
484
+ */
485
+ loginPersistence;
486
+ appClient = null;
487
+ appSecrets = null;
469
488
  constructor(config, scopes = [], expectedAccount, storage) {
470
- this.appClient = null;
471
- this.appSecrets = null;
472
489
  logger.info(`And scopes are ${scopes.join(", ")}`, scopes);
473
490
  this.scopes = scopes;
474
491
  this.storage = storage ?? new DefaultTokenCacheStorage();
package/dist/cli.js CHANGED
@@ -97,7 +97,7 @@ program.name("ms-365-mcp-server").description("Microsoft 365 MCP Server").versio
97
97
  "File download tools (get-mail-message-mime, get-shared-mailbox-message-mime, get-mail-attachment-content, get-shared-mailbox-attachment-content) answer an MCP EmbeddedResource with the file instead of base64 JSON in a text block. Off by default."
98
98
  ).option(
99
99
  "--allow-unauthenticated-discovery",
100
- "In HTTP mode, allow MCP discovery requests (initialize, tools/list, prompts/list, resources/list, ping) without a bearer token, so a gateway can enumerate the tool catalog before any user has authenticated. Non-discovery requests (e.g. tools/call) still require a token. Off by default."
100
+ "In HTTP mode, allow MCP discovery requests (server/discover, initialize, tools/list, prompts/list, resources/list, ping) without a bearer token, so a gateway can enumerate the tool catalog before any user has authenticated. Non-discovery requests (e.g. tools/call) still require a token. Off by default."
101
101
  ).option(
102
102
  "--enable-mcp-apps",
103
103
  "(experimental) Show an interactive MCP Apps view for the tools that have one, in hosts that support MCP Apps: a OneDrive/SharePoint file browser for folder listings, and a mail draft view with a Send button for the draft tools. Other hosts ignore it. No effect with --toon. Equivalent env var: MS365_MCP_ENABLE_MCP_APPS=true."
@@ -8,6 +8,7 @@ function isPathParamStub(param) {
8
8
  return typeof description === "string" && /^Path parameter: /.test(description);
9
9
  }
10
10
  class Zodios {
11
+ endpoints;
11
12
  constructor(baseUrlOrEndpoints, endpoints, options) {
12
13
  if (typeof baseUrlOrEndpoints === "string") {
13
14
  throw new Error("No such hack");
@@ -51,6 +51,8 @@ function graphInnerErrorCodes(errorText) {
51
51
  return codes;
52
52
  }
53
53
  class GraphApiError extends Error {
54
+ httpStatus;
55
+ graphErrorCode;
54
56
  constructor(message, httpStatus, graphErrorCode) {
55
57
  super(message);
56
58
  this.name = "GraphApiError";
@@ -166,8 +168,11 @@ function toBlobResponse(data, blob) {
166
168
  };
167
169
  }
168
170
  class GraphClient {
171
+ authManager;
172
+ secrets;
173
+ outputFormat = "json";
174
+ orgMode;
169
175
  constructor(authManager, secrets, outputFormat = "json", options = {}) {
170
- this.outputFormat = "json";
171
176
  this.authManager = authManager;
172
177
  this.secrets = secrets;
173
178
  this.outputFormat = outputFormat;
@@ -1,4 +1,3 @@
1
- import { CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
2
1
  import { randomUUID } from "crypto";
3
2
  import { readFileSync } from "fs";
4
3
  import { access } from "fs/promises";
@@ -36,7 +35,8 @@ import {
36
35
  DEFAULT_TOOL_DEFINITION_BUDGET,
37
36
  fitToolDefinitionToBudget,
38
37
  getToolDefinitionBudget,
39
- measureInputSchemaBytes
38
+ measureInputSchemaBytes,
39
+ withServedInputSchema
40
40
  } from "./lib/body-schema-budget.js";
41
41
  import { isDestructiveOperation } from "./lib/destructive-ops.js";
42
42
  import {
@@ -545,7 +545,7 @@ function rewriteMentionShorthand(body) {
545
545
  let error;
546
546
  const rewritten = content.replace(SHORTHAND_AT, (tag, userId, name) => {
547
547
  if (!AAD_GUID.test(userId)) {
548
- error ?? (error = `Mention user-id "${userId}" is not an Entra object id (GUID). Use the userId from list-team-members or list-chat-members.`);
548
+ error ??= `Mention user-id "${userId}" is not an Entra object id (GUID). Use the userId from list-team-members or list-chat-members.`;
549
549
  return tag;
550
550
  }
551
551
  const id = nextId++;
@@ -708,22 +708,34 @@ function auditToolDenied(policy, params = {}) {
708
708
  ...targetResource ? { target_resource: targetResource } : {}
709
709
  });
710
710
  }
711
+ function deniedToolResult(policy) {
712
+ const why = policy.reason === "allowed_scopes" ? `it needs scopes this server does not allow (${(policy.missingScopes ?? []).join(", ")})` : "it is not in the enabled tool list";
713
+ return {
714
+ content: [
715
+ {
716
+ type: "text",
717
+ text: `Tool ${policy.toolName} is not available in this server configuration: ${why}.`
718
+ }
719
+ ],
720
+ isError: true
721
+ };
722
+ }
711
723
  function installDeniedToolAuditHandler(server, deniedTools) {
712
724
  if (deniedTools.size === 0) return;
713
725
  const lowLevel = server.server;
714
726
  const handlers = lowLevel._requestHandlers;
715
727
  const original = handlers?.get("tools/call");
716
728
  if (!original) {
717
- logger.warn("Skipping denied-tool audit hook: tools/call handler not found");
718
- return;
729
+ throw new Error("Cannot install the denied-tool audit hook: tools/call handler not found");
719
730
  }
720
- lowLevel.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
731
+ lowLevel.setRequestHandler("tools/call", async (request, ctx) => {
721
732
  const policy = deniedTools.get(request.params.name);
722
733
  if (policy) {
723
734
  const params = request.params.arguments && typeof request.params.arguments === "object" ? request.params.arguments : {};
724
735
  auditToolDenied(policy, params);
736
+ return deniedToolResult(policy);
725
737
  }
726
- return original(request, extra);
738
+ return await original(request, ctx);
727
739
  });
728
740
  }
729
741
  async function checkAccountParamInBearerMode(accountParam, authManager) {
@@ -1931,16 +1943,18 @@ const UTILITY_TOOLS = [
1931
1943
  })
1932
1944
  }
1933
1945
  ];
1934
- function registerUtilityToolWithMcp(server, utility, ctx) {
1935
- server.tool(
1946
+ function registerUtilityToolWithMcp(server, utility, ctx, inputSchema = z.object(utility.buildSchema(ctx))) {
1947
+ server.registerTool(
1936
1948
  utility.name,
1937
- utility.description,
1938
- utility.buildSchema(ctx),
1939
1949
  {
1940
- title: utility.name,
1941
- readOnlyHint: utility.readOnlyHint ?? true,
1942
- ...utility.destructiveHint !== void 0 ? { destructiveHint: utility.destructiveHint } : {},
1943
- openWorldHint: utility.openWorldHint ?? true
1950
+ description: utility.description,
1951
+ inputSchema: withServedInputSchema(inputSchema, utility.name),
1952
+ annotations: {
1953
+ title: utility.name,
1954
+ readOnlyHint: utility.readOnlyHint ?? true,
1955
+ ...utility.destructiveHint !== void 0 ? { destructiveHint: utility.destructiveHint } : {},
1956
+ openWorldHint: utility.openWorldHint ?? true
1957
+ }
1944
1958
  },
1945
1959
  async (params) => executeUtilityTool(utility, ctx, params)
1946
1960
  );
@@ -2069,6 +2083,13 @@ function rawValueAddsSegments(template, names, value) {
2069
2083
  const isTail = names.some((n) => template.endsWith(`/{${n}}`) || template.endsWith(`/:${n}`));
2070
2084
  return isTail ? value.includes(":") : value.includes("/");
2071
2085
  }
2086
+ function fillPathParam(path2, names, value) {
2087
+ for (const name of new Set(names)) {
2088
+ const colonForm = new RegExp(`:${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9])`);
2089
+ path2 = path2.replace(`{${name}}`, () => value).replace(colonForm, () => value);
2090
+ }
2091
+ return path2;
2092
+ }
2072
2093
  function invalidPathParameter(message) {
2073
2094
  return {
2074
2095
  content: [
@@ -2229,7 +2250,7 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2229
2250
  /%3D/g,
2230
2251
  "="
2231
2252
  );
2232
- path2 = path2.replace(`{${paramName}}`, () => encodedValue).replace(`:${paramName}`, () => encodedValue).replace(`{${camelCaseParamName}}`, () => encodedValue).replace(`:${camelCaseParamName}`, () => encodedValue);
2253
+ path2 = fillPathParam(path2, names, encodedValue);
2233
2254
  break;
2234
2255
  }
2235
2256
  case "Query":
@@ -2270,7 +2291,7 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2270
2291
  const encodedValue = encodeURIComponent(
2271
2292
  escapeIfStringLiteral(tool.path, [paramName, camelCaseParamName], paramValue)
2272
2293
  ).replace(/%3D/g, "=");
2273
- path2 = path2.replace(`{${paramName}}`, () => encodedValue).replace(`:${paramName}`, () => encodedValue).replace(`{${camelCaseParamName}}`, () => encodedValue).replace(`:${camelCaseParamName}`, () => encodedValue);
2294
+ path2 = fillPathParam(path2, [paramName, camelCaseParamName], encodedValue);
2274
2295
  logger.info(`Path param fallback: replaced :${camelCaseParamName} with encoded value`);
2275
2296
  } else if (paramName.toLowerCase() === "accept" && config?.acceptType) {
2276
2297
  if (paramValue !== "" && paramValue != null) {
@@ -2818,7 +2839,10 @@ function registerGraphToolWithMcp(server, tool, endpointConfig, graphClient, opt
2818
2839
  {
2819
2840
  title: tool.alias,
2820
2841
  description: toolDescription,
2821
- inputSchema: z.object(fit?.paramSchema ?? paramSchema).loose(),
2842
+ inputSchema: withServedInputSchema(
2843
+ z.object(fit?.paramSchema ?? paramSchema).loose(),
2844
+ tool.alias
2845
+ ),
2822
2846
  annotations: {
2823
2847
  title: tool.alias,
2824
2848
  readOnlyHint: isReadOnlyTool,
@@ -2972,8 +2996,9 @@ function registerGraphTools(server, graphClient, options = {}) {
2972
2996
  if (!isUtilityToolAvailable(utility, { readOnly, httpMode, scopeMode })) continue;
2973
2997
  if (enabledToolsRegex && !enabledToolsRegex.test(utility.name)) continue;
2974
2998
  try {
2975
- servedSchemaBytes += measureInputSchemaBytes(z.object(utility.buildSchema(utilityCtx)));
2976
- registerUtilityToolWithMcp(server, utility, utilityCtx);
2999
+ const inputSchema = z.object(utility.buildSchema(utilityCtx));
3000
+ servedSchemaBytes += measureInputSchemaBytes(inputSchema);
3001
+ registerUtilityToolWithMcp(server, utility, utilityCtx, inputSchema);
2977
3002
  registeredCount++;
2978
3003
  } catch (error) {
2979
3004
  logger.error(`Failed to register tool ${utility.name}: ${error.message}`);
@@ -3259,20 +3284,25 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
3259
3284
  }
3260
3285
  return null;
3261
3286
  };
3262
- server.tool(
3287
+ server.registerTool(
3263
3288
  "search-tools",
3264
- `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.`,
3265
3289
  {
3266
- query: z.string().optional().describe(
3267
- 'Natural-language query. Tokenized and BM25-ranked. E.g. "send email", "download photo", "list unread messages".'
3290
+ description: `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.`,
3291
+ inputSchema: withServedInputSchema(
3292
+ z.object({
3293
+ query: z.string().optional().describe(
3294
+ 'Natural-language query. Tokenized and BM25-ranked. E.g. "send email", "download photo", "list unread messages".'
3295
+ ),
3296
+ category: z.string().optional().describe(`Optional pre-filter by category: ${categoryNames}`),
3297
+ limit: z.number().optional().describe("Maximum results (default: 10, max: 50)")
3298
+ }),
3299
+ "search-tools"
3268
3300
  ),
3269
- category: z.string().optional().describe(`Optional pre-filter by category: ${categoryNames}`),
3270
- limit: z.number().optional().describe("Maximum results (default: 10, max: 50)")
3271
- },
3272
- {
3273
- title: "search-tools",
3274
- readOnlyHint: true,
3275
- openWorldHint: true
3301
+ annotations: {
3302
+ title: "search-tools",
3303
+ readOnlyHint: true,
3304
+ openWorldHint: true
3305
+ }
3276
3306
  },
3277
3307
  async ({ query, category, limit = 10 }) => {
3278
3308
  const maxLimit = Math.min(Math.max(limit, 1), 50);
@@ -3307,16 +3337,21 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
3307
3337
  };
3308
3338
  }
3309
3339
  );
3310
- server.tool(
3340
+ server.registerTool(
3311
3341
  "get-tool-schema",
3312
- "Returns the full parameter schema (name, placement, required, JSON Schema) for a tool discovered via search-tools. Call this before execute-tool so you know what parameters to pass and what enum values are valid.",
3313
3342
  {
3314
- tool_name: z.string().describe('Exact tool name from search-tools (e.g. "send-mail")')
3315
- },
3316
- {
3317
- title: "get-tool-schema",
3318
- readOnlyHint: true,
3319
- openWorldHint: false
3343
+ description: "Returns the full parameter schema (name, placement, required, JSON Schema) for a tool discovered via search-tools. Call this before execute-tool so you know what parameters to pass and what enum values are valid.",
3344
+ inputSchema: withServedInputSchema(
3345
+ z.object({
3346
+ tool_name: z.string().describe('Exact tool name from search-tools (e.g. "send-mail")')
3347
+ }),
3348
+ "get-tool-schema"
3349
+ ),
3350
+ annotations: {
3351
+ title: "get-tool-schema",
3352
+ readOnlyHint: true,
3353
+ openWorldHint: false
3354
+ }
3320
3355
  },
3321
3356
  async ({ tool_name }) => {
3322
3357
  const entry = toolsRegistry.get(tool_name);
@@ -3347,20 +3382,25 @@ function registerDiscoveryTools(server, graphClient, options = {}) {
3347
3382
  };
3348
3383
  }
3349
3384
  );
3350
- server.tool(
3385
+ server.registerTool(
3351
3386
  "execute-tool",
3352
- "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.",
3353
3387
  {
3354
- tool_name: z.string().describe('Name of the tool to execute (e.g., "list-mail-messages")'),
3355
- parameters: z.record(z.string(), z.any()).optional().describe(
3356
- 'Parameters shaped per get-tool-schema. Path/query/header params go at the top level; request bodies go under "body".'
3357
- )
3358
- },
3359
- {
3360
- title: "execute-tool",
3361
- readOnlyHint: false,
3362
- destructiveHint: true,
3363
- openWorldHint: true
3388
+ description: "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.",
3389
+ inputSchema: withServedInputSchema(
3390
+ z.object({
3391
+ tool_name: z.string().describe('Name of the tool to execute (e.g., "list-mail-messages")'),
3392
+ parameters: z.record(z.string(), z.any()).optional().describe(
3393
+ 'Parameters shaped per get-tool-schema. Path/query/header params go at the top level; request bodies go under "body".'
3394
+ )
3395
+ }),
3396
+ "execute-tool"
3397
+ ),
3398
+ annotations: {
3399
+ title: "execute-tool",
3400
+ readOnlyHint: false,
3401
+ destructiveHint: true,
3402
+ openWorldHint: true
3403
+ }
3364
3404
  },
3365
3405
  async ({ tool_name, parameters = {} }) => {
3366
3406
  const toolData = toolsRegistry.get(tool_name);
@@ -46,8 +46,8 @@ class TicketStoreFullError extends Error {
46
46
  class AttachmentTicketStore {
47
47
  constructor(ttlSeconds) {
48
48
  this.ttlSeconds = ttlSeconds;
49
- this.tickets = /* @__PURE__ */ new Map();
50
49
  }
50
+ tickets = /* @__PURE__ */ new Map();
51
51
  /** Drop every expired ticket. Called before each mint and each redemption. */
52
52
  sweep(nowMs) {
53
53
  for (const [id, ticket] of this.tickets) {
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import logger from "../logger.js";
2
3
  import {
3
4
  normalizeToolSchemaRefs,
4
5
  tidyToolJsonSchema,
@@ -136,6 +137,30 @@ function serveInputSchema(schema) {
136
137
  tidyToolJsonSchema(served);
137
138
  return served;
138
139
  }
140
+ function withServedInputSchema(schema, toolName) {
141
+ const standard = schema["~standard"];
142
+ let served;
143
+ const json = (options) => {
144
+ if (served) return served;
145
+ try {
146
+ served = deepFreeze(serveInputSchema(schema));
147
+ return served;
148
+ } catch (error) {
149
+ logger.warn(`Could not convert the input schema of ${toolName}: ${error}`);
150
+ served = standard.jsonSchema.input(options);
151
+ return served;
152
+ }
153
+ };
154
+ schema["~standard"] = { ...standard, jsonSchema: { input: json, output: json } };
155
+ return schema;
156
+ }
157
+ function deepFreeze(value) {
158
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
159
+ Object.freeze(value);
160
+ for (const child of Object.values(value)) deepFreeze(child);
161
+ }
162
+ return value;
163
+ }
139
164
  function measureToolDefinitionBytes(paramSchema) {
140
165
  return measureInputSchemaBytes(z.object(paramSchema).loose());
141
166
  }
@@ -196,5 +221,6 @@ export {
196
221
  measureToolDefinitionBytes,
197
222
  pruneSchemaDepth,
198
223
  serveInputSchema,
199
- serveToolInputSchema
224
+ serveToolInputSchema,
225
+ withServedInputSchema
200
226
  };
@@ -4,9 +4,14 @@ import winston from "winston";
4
4
  const Transport = winston.Transport;
5
5
  const MIN_BYTES = 1024;
6
6
  class BoundedFileTransport extends Transport {
7
+ filename;
8
+ maxBytes;
9
+ maxFiles;
10
+ mode;
11
+ size;
12
+ stopped = false;
7
13
  constructor(opts) {
8
14
  super(opts);
9
- this.stopped = false;
10
15
  this.filename = opts.filename;
11
16
  this.maxBytes = Math.max(MIN_BYTES, opts.maxBytes);
12
17
  this.maxFiles = Math.max(1, opts.maxFiles);
@@ -256,9 +256,11 @@ function redirectUriMatches(requested, registered) {
256
256
  }
257
257
  const CIMD_MAX_STALE_MS = 24 * 60 * 6e4;
258
258
  class ClientMetadataResolver {
259
+ cache = /* @__PURE__ */ new Map();
260
+ inFlight = /* @__PURE__ */ new Map();
261
+ fetcher;
262
+ now;
259
263
  constructor(options = {}) {
260
- this.cache = /* @__PURE__ */ new Map();
261
- this.inFlight = /* @__PURE__ */ new Map();
262
264
  this.fetcher = options.fetcher ?? fetchDocument;
263
265
  this.now = options.now ?? Date.now;
264
266
  }