@softeria/ms-365-mcp-server 0.182.2 → 0.182.3

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/.gitattributes ADDED
@@ -0,0 +1 @@
1
+ * text=auto eol=lf
package/README.md CHANGED
@@ -883,7 +883,7 @@ Environment variables:
883
883
  - `MS365_MCP_GRAPH_BASE_URL=<url>`: Send Graph API requests to this base URL instead of the cloud's `graph.microsoft.com` (e.g. `http://127.0.0.1:10255/tenant-a/graph` for an egress proxy that originates TLS itself). Absolute http(s) URL without query or fragment; a path prefix is kept, so requests go to `<url>/v1.0/...`. The login authority and the On-Behalf-Of token resource are unchanged. Two things bypass it: `get-download-url` returns Graph's pre-authenticated SharePoint URL, and the `302` from `/content` points straight at SharePoint, so whoever follows either connects to SharePoint directly; if you control egress, allow those SharePoint hosts or disable those tools. Not read from `.env`
884
884
  - `LOG_LEVEL`: Set logging level (default: 'info')
885
885
  - `SILENT=true|1`: Disable console output
886
- - `MS365_MCP_REDACT_PII=false|0`: Disable scrubbing of JWTs, Bearer headers, OAuth token fields, and email addresses from log messages (default: enabled). The server handles live Graph bearer tokens, so redaction is on unless you opt out for fully verbose local debugging.
886
+ - `MS365_MCP_REDACT_PII=false|0`: Disable scrubbing of JWTs, Bearer headers, OAuth token fields, and email addresses from log messages, and log tool parameters, request bodies, URLs, error messages and crash dumps in full instead of by shape only (default: enabled). The server handles live Graph bearer tokens, so redaction is on unless you opt out for fully verbose local debugging.
887
887
  - `MS365_MCP_CLIENT_ID`: Custom Azure app client ID (defaults to built-in app)
888
888
  - `MS365_MCP_TENANT_ID`: Custom tenant ID (defaults to 'common' for multi-tenant). **Personal Microsoft accounts should set this to `consumers`** - as of June 2026, refresh tokens issued via the default 'common' authority are rejected at the first refresh, so sessions die roughly an hour after login
889
889
  - `MS365_MCP_OAUTH_TOKEN`: Pre-existing OAuth token for Microsoft Graph API (BYOT method)
@@ -0,0 +1,153 @@
1
+ import { afterEach, beforeEach, describe, it, expect } from "vitest";
2
+ import {
3
+ describeShape,
4
+ describeText,
5
+ describeUrl,
6
+ describeError,
7
+ describeStack,
8
+ serializedSize,
9
+ summarizeError
10
+ } from "../lib/log-safe.js";
11
+ import { dumpError } from "../crash-logging.js";
12
+ import { GraphApiError } from "../graph-client.js";
13
+ const SECRET = "SENTINEL-the quarterly numbers are bad, do not forward";
14
+ describe("log-safe", () => {
15
+ it("describes parameters by shape, never by value", () => {
16
+ const out = describeShape({
17
+ top: 10,
18
+ filter: `subject eq '${SECRET}'`,
19
+ search: `"${SECRET}"`,
20
+ body: { subject: SECRET, body: { contentType: "html", content: SECRET } },
21
+ messageIds: [SECRET, SECRET],
22
+ confirm: true,
23
+ skiptoken: null
24
+ });
25
+ expect(out).not.toContain(SECRET);
26
+ expect(out).toContain("top: 10");
27
+ expect(out).toContain(`filter: string(${SECRET.length + 13})`);
28
+ expect(out).toContain("body: object(2 keys)");
29
+ expect(out).toContain("messageIds: array(2)");
30
+ expect(out).toContain("confirm: true");
31
+ expect(out).toContain("skiptoken: null");
32
+ });
33
+ it("counts keys that are not on the known list instead of naming them", () => {
34
+ const out = describeShape({ [SECRET]: "x", top: 1, [`${SECRET}-2`]: 2 });
35
+ expect(out).toBe("{top: 1, +2 other}");
36
+ });
37
+ it("describes a string or array at the top level without its content", () => {
38
+ expect(describeShape(SECRET)).toBe(`string(${SECRET.length})`);
39
+ expect(describeShape([SECRET])).toBe("array(1)");
40
+ });
41
+ it("masks every path segment that is not a fixed Graph word", () => {
42
+ expect(describeUrl(`/me/drive/root:/${SECRET}.txt:/content`)).toBe(
43
+ "/me/drive/root:/{\u2026}/content"
44
+ );
45
+ expect(describeUrl("/me/messages/AAMkAGVj-abc=/attachments/ATT1/$value")).toBe(
46
+ "/me/messages/{\u2026}/attachments/{\u2026}/$value"
47
+ );
48
+ expect(describeUrl(`/users/${SECRET}@contoso.com/mailFolders/inbox/messages`)).toBe(
49
+ "/users/{\u2026}/mailFolders/inbox/messages"
50
+ );
51
+ });
52
+ it("drops the query string and lists only $-prefixed OData names", () => {
53
+ const url = `https://graph.microsoft.com/v1.0/me/messages?$search=%22${encodeURIComponent(SECRET)}%22&$top=5&${encodeURIComponent(SECRET)}=x`;
54
+ const out = describeUrl(url);
55
+ expect(out).not.toContain(SECRET);
56
+ expect(out).not.toContain(encodeURIComponent(SECRET));
57
+ expect(out).toBe(
58
+ "https://graph.microsoft.com/v1.0/me/messages [query: $search, $top, +1 other]"
59
+ );
60
+ expect(describeUrl("/me/messages")).toBe("/me/messages");
61
+ });
62
+ it("never throws on malformed input", () => {
63
+ expect(describeUrl("/me/messages?%malformed=x&%E0%A4%A=y")).toBe(
64
+ "/me/messages [query: +2 other]"
65
+ );
66
+ expect(describeUrl("")).toBe("");
67
+ expect(describeUrl(`http://${SECRET}/me`)).toBe("{origin}/me");
68
+ expect(describeUrl(void 0)).toBe("undefined");
69
+ });
70
+ it("describes a Graph error by status and code, never by message", () => {
71
+ const err = new GraphApiError(`Invalid filter clause: ${SECRET}`, 400, "BadRequest");
72
+ expect(describeError(err)).toBe("GraphApiError status=400 code=BadRequest");
73
+ });
74
+ it("shows only known error names, HTTP statuses and short codes", () => {
75
+ const named = new Error(`connect failed while sending ${SECRET}`);
76
+ named.name = SECRET;
77
+ expect(describeError(Object.assign(named, { code: SECRET, status: 999 }))).toBe(
78
+ `Error code=unlisted(${SECRET.length})`
79
+ );
80
+ expect(describeError(Object.assign(new Error("x"), { code: 7000215 }))).toBe(
81
+ "Error code=7000215"
82
+ );
83
+ expect(describeError(Object.assign(new Error("x"), { code: "ECONNRESET", status: 502 }))).toBe(
84
+ "Error status=502 code=ECONNRESET"
85
+ );
86
+ expect(describeError(SECRET)).toBe("non-error(string)");
87
+ });
88
+ it("keeps stack frames but not the message line", () => {
89
+ const frames = describeStack(new Error(`boom ${SECRET}`));
90
+ expect(frames.length).toBeGreaterThan(0);
91
+ for (const f of frames) {
92
+ expect(f.startsWith("at ")).toBe(true);
93
+ expect(f).not.toContain(SECRET);
94
+ }
95
+ expect(describeStack("x")).toEqual([]);
96
+ });
97
+ it("reports a serialized size without the content", () => {
98
+ expect(serializedSize({ a: "bc" })).toBe(Buffer.byteLength('{"a":"bc"}'));
99
+ const cyclic = {};
100
+ cyclic.self = cyclic;
101
+ expect(serializedSize(cyclic)).toBe(-1);
102
+ });
103
+ it("describes free text by length", () => {
104
+ expect(describeText(SECRET)).toBe(`(${SECRET.length} chars)`);
105
+ });
106
+ });
107
+ describe("log-safe with MS365_MCP_REDACT_PII=false", () => {
108
+ const prev = process.env.MS365_MCP_REDACT_PII;
109
+ beforeEach(() => {
110
+ process.env.MS365_MCP_REDACT_PII = "false";
111
+ });
112
+ afterEach(() => {
113
+ if (prev === void 0) delete process.env.MS365_MCP_REDACT_PII;
114
+ else process.env.MS365_MCP_REDACT_PII = prev;
115
+ });
116
+ it("logs values, URLs and free text in full", () => {
117
+ const params = { filter: `subject eq '${SECRET}'`, [SECRET]: 1 };
118
+ expect(describeShape(params)).toBe(JSON.stringify(params));
119
+ const cyclic = {};
120
+ cyclic.self = cyclic;
121
+ expect(describeShape(cyclic)).toBe("[unserializable: TypeError]");
122
+ const url = `/me/drive/root:/${SECRET}.txt:/content?$search=${SECRET}`;
123
+ expect(describeUrl(url)).toBe(url);
124
+ expect(describeText(SECRET)).toBe(SECRET);
125
+ });
126
+ it("logs the real error name, code and message", () => {
127
+ const err = new GraphApiError(
128
+ `Insufficient privileges: ${SECRET}`,
129
+ 403,
130
+ "Authorization_RequestDenied"
131
+ );
132
+ expect(describeError(err)).toBe(
133
+ `GraphApiError status=403 code=Authorization_RequestDenied: Insufficient privileges: ${SECRET}`
134
+ );
135
+ expect(describeError(SECRET)).toBe(JSON.stringify(SECRET));
136
+ });
137
+ it("keeps the self-test summary short, since /health returns it", () => {
138
+ const err = Object.assign(new Error(`connect ${SECRET}`), { code: "ECONNREFUSED" });
139
+ expect(summarizeError(err)).toBe("Error code=ECONNREFUSED");
140
+ });
141
+ it("dumps a crash with message, properties and cause", () => {
142
+ const crash = Object.assign(new Error(`boom ${SECRET}`), {
143
+ response: { body: SECRET },
144
+ cause: new Error(`inner ${SECRET}`)
145
+ });
146
+ expect(dumpError(crash)).toMatchObject({
147
+ name: "Error",
148
+ message: `boom ${SECRET}`,
149
+ properties: { response: { body: SECRET } },
150
+ cause: { message: `inner ${SECRET}` }
151
+ });
152
+ });
153
+ });
package/dist/app-mode.js CHANGED
@@ -210,6 +210,7 @@ class AppTokenClient {
210
210
  export {
211
211
  APP_MODE_WARNING,
212
212
  AppTokenClient,
213
+ NON_TENANT_AUTHORITIES,
213
214
  assertAppModeOptions,
214
215
  describeAppToken,
215
216
  loadCertificateCredential,
@@ -1,6 +1,7 @@
1
1
  import { Readable } from "node:stream";
2
2
  import { pipeline } from "node:stream/promises";
3
3
  import logger from "./logger.js";
4
+ import { describeError, describeUrl } from "./lib/log-safe.js";
4
5
  import {
5
6
  isPlainGraphPath,
6
7
  TICKET_PARAM
@@ -105,7 +106,7 @@ function createAttachmentHandler(deps) {
105
106
  stream = await graphClient.downloadStream(ticket.target, { accessToken });
106
107
  } catch (error) {
107
108
  logger.error(
108
- `Attachment redemption failed for ${ticket.target}: ${error.message}`
109
+ `Attachment redemption failed for ${describeUrl(ticket.target)}: ${describeError(error)}`
109
110
  );
110
111
  res.status(502).type("text/plain").send("Upstream fetch failed");
111
112
  return;
@@ -128,7 +129,9 @@ function createAttachmentHandler(deps) {
128
129
  try {
129
130
  await pipeline(Readable.fromWeb(stream.body), res);
130
131
  } catch (error) {
131
- logger.error(`Attachment stream aborted for ${ticket.target}: ${error.message}`);
132
+ logger.error(
133
+ `Attachment stream aborted for ${describeUrl(ticket.target)}: ${describeError(error)}`
134
+ );
132
135
  res.destroy();
133
136
  }
134
137
  };
@@ -179,7 +182,9 @@ function createAttachmentUploadHandler(deps) {
179
182
  accessToken = ticket.kind === "request-token" ? ticket.accessToken : await deps.authManager.getTokenForAccount(ticket.accountName);
180
183
  if (!accessToken) throw new Error("No access token for this ticket");
181
184
  } catch (error) {
182
- logger.error(`Attachment upload failed for ${ticket.target}: ${error.message}`);
185
+ logger.error(
186
+ `Attachment upload failed for ${describeUrl(ticket.target)}: ${describeError(error)}`
187
+ );
183
188
  res.status(502).type("text/plain").send("Upstream upload failed");
184
189
  return;
185
190
  }
@@ -233,7 +238,9 @@ function createAttachmentUploadHandler(deps) {
233
238
  ...ticket.contentId ? { contentId: ticket.contentId } : {}
234
239
  });
235
240
  } catch (error) {
236
- logger.error(`Attachment upload failed for ${ticket.target}: ${error.message}`);
241
+ logger.error(
242
+ `Attachment upload failed for ${describeUrl(ticket.target)}: ${describeError(error)}`
243
+ );
237
244
  if (!res.headersSent) res.status(502).type("text/plain").send("Upstream upload failed");
238
245
  }
239
246
  };
package/dist/audit-log.js CHANGED
@@ -35,6 +35,8 @@ const auditLogger = winston.createLogger({
35
35
  stderrLevels: ["info"],
36
36
  silent: process.env.SILENT === "true" || process.env.SILENT === "1" || process.env.VITEST === "true"
37
37
  }),
38
+ // Not bounded like the diagnostic logs: this is the audit trail, so when old
39
+ // records go is up to the operator.
38
40
  new winston.transports.File({
39
41
  filename: auditLogPath,
40
42
  options: { flags: "a", mode: FILE_MODE }
package/dist/auth.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AuthError, PublicClientApplication } from "@azure/msal-node";
2
2
  import logger from "./logger.js";
3
+ import { describeText } from "./lib/log-safe.js";
3
4
  import { readFileSync } from "fs";
4
5
  import { fileURLToPath } from "url";
5
6
  import path from "path";
@@ -974,7 +975,9 @@ class AuthManager {
974
975
  };
975
976
  } else {
976
977
  const errorText = await response.text();
977
- logger.error(`Graph API user data fetch failed: ${response.status} - ${errorText}`);
978
+ logger.error(
979
+ `Graph API user data fetch failed: ${response.status} ${describeText(errorText)}`
980
+ );
978
981
  return {
979
982
  success: false,
980
983
  message: `Login successful but Graph API access failed: ${response.status}`
@@ -1,28 +1,42 @@
1
+ import { redactionEnabled } from "./lib/log-redactor.js";
2
+ import { describeError, describeStack } from "./lib/log-safe.js";
1
3
  function dumpError(reason, depth = 0) {
2
4
  if (depth > 5) {
3
5
  return { truncated: true };
4
6
  }
7
+ if (!redactionEnabled()) return fullDump(reason, depth);
5
8
  if (reason instanceof Error) {
6
9
  const dump = {
7
- name: reason.name,
8
- constructor: reason.constructor?.name,
9
- message: reason.message,
10
- stack: reason.stack
10
+ summary: describeError(reason),
11
+ stack: describeStack(reason)
11
12
  };
12
- const properties = {};
13
- for (const key of Object.getOwnPropertyNames(reason)) {
14
- if (key === "name" || key === "message" || key === "stack" || key === "cause") continue;
15
- properties[key] = reason[key];
16
- }
17
- if (Object.keys(properties).length > 0) {
18
- dump.properties = properties;
19
- }
20
13
  if ("cause" in reason && reason.cause !== void 0) {
21
14
  dump.cause = dumpError(reason.cause, depth + 1);
22
15
  }
23
16
  return dump;
24
17
  }
25
- return { type: typeof reason, value: reason };
18
+ return { type: typeof reason };
19
+ }
20
+ function fullDump(reason, depth) {
21
+ if (!(reason instanceof Error)) return { type: typeof reason, value: reason };
22
+ const dump = {
23
+ name: reason.name,
24
+ constructor: reason.constructor?.name,
25
+ message: reason.message,
26
+ stack: reason.stack
27
+ };
28
+ const properties = {};
29
+ for (const key of Object.getOwnPropertyNames(reason)) {
30
+ if (key === "name" || key === "message" || key === "stack" || key === "cause") continue;
31
+ properties[key] = reason[key];
32
+ }
33
+ if (Object.keys(properties).length > 0) {
34
+ dump.properties = properties;
35
+ }
36
+ if ("cause" in reason && reason.cause !== void 0) {
37
+ dump.cause = dumpError(reason.cause, depth + 1);
38
+ }
39
+ return dump;
26
40
  }
27
41
  function getActiveResources() {
28
42
  const fn = process.getActiveResourcesInfo;
@@ -1,4 +1,5 @@
1
1
  import logger from "./logger.js";
2
+ import { describeError, describeShape, describeUrl } from "./lib/log-safe.js";
2
3
  import { encode as toonEncode } from "@toon-format/toon";
3
4
  import { getGraphBaseUrl } from "./cloud-config.js";
4
5
  import { getRequestTokens } from "./request-context.js";
@@ -246,7 +247,7 @@ class GraphClient {
246
247
  }
247
248
  return { data: result, metadata };
248
249
  } catch (error) {
249
- logger.error("Microsoft Graph API request failed:", error);
250
+ logger.error(`Microsoft Graph API request failed: ${describeError(error)}`);
250
251
  throw error;
251
252
  }
252
253
  }
@@ -340,7 +341,7 @@ class GraphClient {
340
341
  httpStatus: response.status
341
342
  };
342
343
  } catch (error) {
343
- logger.error("Microsoft Graph file download failed:", error);
344
+ logger.error(`Microsoft Graph file download failed: ${describeError(error)}`);
344
345
  throw error;
345
346
  } finally {
346
347
  await fileHandle.close().catch(() => void 0);
@@ -404,7 +405,7 @@ class GraphClient {
404
405
  async performRequest(endpoint, accessToken, options) {
405
406
  const apiVersion = options.apiVersion || "v1.0";
406
407
  const url = `${getGraphBaseUrl(this.secrets.cloudType)}/${apiVersion}${endpoint}`;
407
- logger.info(`[GRAPH CLIENT] Final URL being sent to Microsoft: ${url}`);
408
+ logger.info(`[GRAPH CLIENT] Request ${options.method || "GET"} ${describeUrl(url)}`);
408
409
  const method = options.method || "GET";
409
410
  const signedBody = applyMessageSignoffToRequest(method, endpoint, options.body);
410
411
  const body = applyBatchContentType(method, endpoint, signedBody);
@@ -448,7 +449,7 @@ class GraphClient {
448
449
  try {
449
450
  const { accessToken: _redacted, ...safeOptions } = options;
450
451
  logger.info(
451
- `Calling ${endpoint} with options: ${JSON.stringify(safeOptions)}${_redacted ? " [accessToken=REDACTED]" : ""}`
452
+ `Calling ${describeUrl(endpoint)} [${options.method || "GET"}] with options: ${describeShape(safeOptions)}${_redacted ? " [accessToken=REDACTED]" : ""}`
452
453
  );
453
454
  const { data, metadata } = await this.makeRequestWithMetadata(endpoint, options);
454
455
  const outputFormat = options.forceJsonOutput ? "json" : this.outputFormat;
@@ -458,7 +459,7 @@ class GraphClient {
458
459
  metadata
459
460
  );
460
461
  } catch (error) {
461
- logger.error(`Error in Graph API request: ${error}`);
462
+ logger.error(`Error in Graph API request: ${describeError(error)}`);
462
463
  const metadata = error instanceof GraphApiError ? definedMetadata({
463
464
  http_status: error.httpStatus,
464
465
  error_code: error.graphErrorCode
@@ -92,6 +92,13 @@ import {
92
92
  userFieldEnforcement
93
93
  } from "./lib/user-field-policy.js";
94
94
  import logger from "./logger.js";
95
+ import {
96
+ describeError,
97
+ describeShape,
98
+ describeText,
99
+ describeUrl,
100
+ serializedSize
101
+ } from "./lib/log-safe.js";
95
102
  import { getRequestTokens } from "./request-context.js";
96
103
  import { TOOL_CATEGORIES } from "./tool-categories.js";
97
104
  const __filename = fileURLToPath(import.meta.url);
@@ -309,7 +316,9 @@ function normalizeSearchQueryParam(queryParams, path2, toolAlias) {
309
316
  if (inner === "") return noSearchableText();
310
317
  const normalized = `"${inner}"`;
311
318
  if (normalized !== raw) {
312
- logger.info(`Auto-corrected parameter '$search': normalized KQL quoting to ${normalized}`);
319
+ logger.info(
320
+ `Auto-corrected parameter '$search': normalized KQL quoting ${describeText(normalized)}`
321
+ );
313
322
  queryParams["$search"] = normalized;
314
323
  }
315
324
  }
@@ -1904,11 +1913,7 @@ function hasOwn(obj, key) {
1904
1913
  return Object.prototype.hasOwnProperty.call(obj, key);
1905
1914
  }
1906
1915
  function describeParamsForLog(params) {
1907
- try {
1908
- return JSON.stringify(params);
1909
- } catch (error) {
1910
- return `[unserializable: ${error instanceof Error ? error.name : "unknown error"}]`;
1911
- }
1916
+ return describeShape(params);
1912
1917
  }
1913
1918
  function escapeIfStringLiteral(template, names, value) {
1914
1919
  const quoted = names.some((n) => template.includes(`'{${n}}'`) || template.includes(`':${n}'`));
@@ -2111,7 +2116,7 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2111
2116
  }
2112
2117
  } else if (paramName === "body") {
2113
2118
  body = paramValue;
2114
- logger.info(`Set body param: ${JSON.stringify(body)}`);
2119
+ logger.info(`Set body param: ${describeShape(body)} (${serializedSize(body)} bytes)`);
2115
2120
  } else if (path2.includes(`:${paramName}`) || path2.includes(`{${paramName}}`) || path2.includes(`:${camelCaseParamName}`) || path2.includes(`{${camelCaseParamName}}`)) {
2116
2121
  const encodedValue = encodeURIComponent(
2117
2122
  escapeIfStringLiteral(tool.path, [paramName, camelCaseParamName], paramValue)
@@ -2127,7 +2132,9 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2127
2132
  }
2128
2133
  } else if (isOdataParam) {
2129
2134
  queryParams[fixedParamName] = `${paramValue}`;
2130
- logger.info(`OData param fallback: forwarded ${fixedParamName}=${paramValue}`);
2135
+ logger.info(
2136
+ `OData param fallback: forwarded ${fixedParamName} ${describeText(String(paramValue))}`
2137
+ );
2131
2138
  } else if (bodyShape && (hasOwn(bodyShape, paramName) || hasOwn(bodyShape, camelCaseParamName)) && !READ_ONLY_BODY_FIELDS.has(hasOwn(bodyShape, paramName) ? paramName : camelCaseParamName)) {
2132
2139
  const fieldName = hasOwn(bodyShape, paramName) ? paramName : camelCaseParamName;
2133
2140
  strayBodyFields[fieldName] = paramValue;
@@ -2135,7 +2142,9 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2135
2142
  `Body field fallback: merging top-level param '${fieldName}' into request body`
2136
2143
  );
2137
2144
  } else {
2138
- logger.warn(`Dropping unrecognized parameter '${paramName}' for tool ${tool.alias}`);
2145
+ logger.warn(
2146
+ `Dropping unrecognized parameter ${describeText(paramName)} for tool ${tool.alias}`
2147
+ );
2139
2148
  }
2140
2149
  }
2141
2150
  if (!isUnalteredGraphPath(path2)) {
@@ -2333,7 +2342,7 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2333
2342
  });
2334
2343
  const { accessToken: _redacted, ...safeOptions } = options;
2335
2344
  logger.info(
2336
- `Making graph request to ${path2} with options: ${JSON.stringify(safeOptions)}${_redacted ? " [accessToken=REDACTED]" : ""}`
2345
+ `Making graph request to ${describeUrl(path2)} [${options.method || "GET"}] with options: ${describeShape(safeOptions)}${_redacted ? " [accessToken=REDACTED]" : ""}`
2337
2346
  );
2338
2347
  const fetchAllPages = params.fetchAllPages === true;
2339
2348
  const paginationEnabled = paginationAllowed();
@@ -2389,7 +2398,7 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2389
2398
  const maxItems = positiveIntFromEnv("MS365_MCP_MAX_ITEMS", DEFAULT_MAX_ITEMS);
2390
2399
  let deltaLink = combinedResponse["@odata.deltaLink"];
2391
2400
  while (nextLink && pageCount < maxPages && allItems.length < maxItems) {
2392
- logger.info(`Fetching page ${pageCount + 1} from: ${nextLink}`);
2401
+ logger.info(`Fetching page ${pageCount + 1} from: ${describeUrl(nextLink)}`);
2393
2402
  const url = new URL(nextLink);
2394
2403
  const nextPath = url.pathname.replace(/^\/(v1\.0|beta)/, "") + url.search;
2395
2404
  const nextOptions = { ...options };
@@ -2450,7 +2459,7 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2450
2459
  }
2451
2460
  }
2452
2461
  } catch (e) {
2453
- logger.error(`Error during pagination: ${e}`);
2462
+ logger.error(`Error during pagination: ${describeError(e)}`);
2454
2463
  }
2455
2464
  if (combinedResponse !== void 0) {
2456
2465
  const merged = applyMemberFilter(
@@ -2495,7 +2504,9 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2495
2504
  logger.info(`Response contains ${jsonResponse.value.length} items`);
2496
2505
  }
2497
2506
  if (jsonResponse["@odata.nextLink"]) {
2498
- logger.info(`Response has pagination nextLink: ${jsonResponse["@odata.nextLink"]}`);
2507
+ logger.info(
2508
+ `Response has pagination nextLink: ${describeUrl(jsonResponse["@odata.nextLink"])}`
2509
+ );
2499
2510
  }
2500
2511
  } catch {
2501
2512
  }
@@ -2522,7 +2533,7 @@ async function executeGraphTool(tool, config, graphClient, params, authManager,
2522
2533
  };
2523
2534
  } catch (error) {
2524
2535
  const err = error;
2525
- logger.error(`Error in tool ${tool.alias}: ${error.message}`);
2536
+ logger.error(`Error in tool ${tool.alias}: ${describeError(error)}`);
2526
2537
  auditLog({
2527
2538
  event: "tool.call",
2528
2539
  request_id: requestId,
@@ -0,0 +1,99 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import winston from "winston";
4
+ const Transport = winston.Transport;
5
+ const MIN_BYTES = 1024;
6
+ class BoundedFileTransport extends Transport {
7
+ constructor(opts) {
8
+ super(opts);
9
+ this.stopped = false;
10
+ this.filename = opts.filename;
11
+ this.maxBytes = Math.max(MIN_BYTES, opts.maxBytes);
12
+ this.maxFiles = Math.max(1, opts.maxFiles);
13
+ this.mode = opts.mode ?? 384;
14
+ fs.mkdirSync(path.dirname(this.filename), { recursive: true, mode: 448 });
15
+ this.size = this.currentSize();
16
+ }
17
+ currentSize() {
18
+ try {
19
+ return fs.statSync(this.filename).size;
20
+ } catch {
21
+ return 0;
22
+ }
23
+ }
24
+ rotated(n) {
25
+ return `${this.filename}.${n}`;
26
+ }
27
+ /**
28
+ * `<name>.<maxFiles-1>` is removed, every older file shifts up, the live file
29
+ * becomes `.1`. Returns false when the live file could neither be moved aside
30
+ * nor cut to zero.
31
+ */
32
+ rotate() {
33
+ try {
34
+ fs.rmSync(this.rotated(this.maxFiles - 1), { force: true });
35
+ for (let n = this.maxFiles - 2; n >= 1; n--) {
36
+ if (fs.existsSync(this.rotated(n))) fs.renameSync(this.rotated(n), this.rotated(n + 1));
37
+ }
38
+ } catch {
39
+ }
40
+ try {
41
+ if (this.maxFiles > 1 && fs.existsSync(this.filename)) {
42
+ fs.renameSync(this.filename, this.rotated(1));
43
+ } else {
44
+ fs.rmSync(this.filename, { force: true });
45
+ }
46
+ } catch {
47
+ try {
48
+ fs.truncateSync(this.filename, 0);
49
+ } catch {
50
+ this.size = this.currentSize();
51
+ return false;
52
+ }
53
+ }
54
+ this.size = this.currentSize();
55
+ return true;
56
+ }
57
+ /** A single record never exceeds the file bound; the excess is replaced by a note. */
58
+ fit(line) {
59
+ const bytes = Buffer.byteLength(line);
60
+ if (bytes <= this.maxBytes) return line;
61
+ const note = ` \u2026[${bytes - this.maxBytes} bytes dropped]
62
+ `;
63
+ const room = Math.max(0, this.maxBytes - Buffer.byteLength(note));
64
+ const head = Buffer.from(line).subarray(0, room).toString("utf8").replace(/�+$/, "");
65
+ return `${head}${note}`;
66
+ }
67
+ log(info, callback) {
68
+ setImmediate(() => this.emit("logged", info));
69
+ if (this.stopped) {
70
+ callback();
71
+ return;
72
+ }
73
+ const line = this.fit(`${String(info[/* @__PURE__ */ Symbol.for("message")] ?? "")}
74
+ `);
75
+ const bytes = Buffer.byteLength(line);
76
+ if (this.size + bytes > this.maxBytes && !this.rotate()) {
77
+ this.stopped = true;
78
+ console.error(
79
+ `[ms365-mcp] log file ${path.basename(this.filename)} cannot be bounded; writing stopped`
80
+ );
81
+ callback();
82
+ return;
83
+ }
84
+ if (this.size + bytes > this.maxBytes) {
85
+ this.stopped = true;
86
+ callback();
87
+ return;
88
+ }
89
+ try {
90
+ fs.appendFileSync(this.filename, line, { mode: this.mode, flag: "a" });
91
+ this.size += bytes;
92
+ } catch {
93
+ }
94
+ callback();
95
+ }
96
+ }
97
+ export {
98
+ BoundedFileTransport
99
+ };
@@ -0,0 +1,12 @@
1
+ function boundedInt(name, fallback) {
2
+ const raw = process.env[name];
3
+ if (raw === void 0 || raw === "") return fallback;
4
+ const n = Number(raw);
5
+ return Number.isInteger(n) && n > 0 ? n : fallback;
6
+ }
7
+ const LOG_MAX_BYTES = boundedInt("MS365_MCP_LOG_MAX_BYTES", 10 * 1024 * 1024);
8
+ const LOG_MAX_FILES = boundedInt("MS365_MCP_LOG_MAX_FILES", 5);
9
+ export {
10
+ LOG_MAX_BYTES,
11
+ LOG_MAX_FILES
12
+ };
@@ -0,0 +1,405 @@
1
+ import { redactionEnabled } from "./log-redactor.js";
2
+ const MAX_LISTED = 40;
3
+ const KNOWN_PARAM_NAMES = /* @__PURE__ */ new Set([
4
+ "top",
5
+ "skip",
6
+ "skiptoken",
7
+ "search",
8
+ "filter",
9
+ "count",
10
+ "orderby",
11
+ "select",
12
+ "expand",
13
+ "fetchAllPages",
14
+ "includeHeaders",
15
+ "excludeResponse",
16
+ "includeHiddenMessages",
17
+ "confirm",
18
+ "timezone",
19
+ "expandExtendedProperties",
20
+ "body",
21
+ "rawResponse",
22
+ "blobOutput",
23
+ "forceJsonOutput",
24
+ "method",
25
+ "apiVersion",
26
+ "queryParams",
27
+ "headers",
28
+ "accessToken",
29
+ "maxChars",
30
+ "maxPages",
31
+ "maxItems",
32
+ "messageId",
33
+ "messageIds",
34
+ "mailFolderId",
35
+ "folderId",
36
+ "eventId",
37
+ "calendarId",
38
+ "contactId",
39
+ "contactFolderId",
40
+ "attachmentId",
41
+ "driveId",
42
+ "driveItemId",
43
+ "itemId",
44
+ "siteId",
45
+ "listId",
46
+ "userId",
47
+ "teamId",
48
+ "channelId",
49
+ "chatId",
50
+ "planId",
51
+ "taskId",
52
+ "bucketId",
53
+ "notebookId",
54
+ "sectionId",
55
+ "pageId",
56
+ "subscriptionId",
57
+ "target",
58
+ "name",
59
+ "contentType",
60
+ "If-Match",
61
+ "Prefer",
62
+ "outputFormat",
63
+ "skipEncoding"
64
+ ]);
65
+ const KNOWN_PATH_SEGMENTS = /* @__PURE__ */ new Set([
66
+ "v1.0",
67
+ "beta",
68
+ "me",
69
+ "users",
70
+ "messages",
71
+ "mailFolders",
72
+ "childFolders",
73
+ "attachments",
74
+ "events",
75
+ "calendar",
76
+ "calendars",
77
+ "calendarView",
78
+ "calendarGroups",
79
+ "instances",
80
+ "contacts",
81
+ "contactFolders",
82
+ "drive",
83
+ "drives",
84
+ "items",
85
+ "root",
86
+ "children",
87
+ "content",
88
+ "thumbnails",
89
+ "delta",
90
+ "search",
91
+ "sites",
92
+ "lists",
93
+ "columns",
94
+ "contentTypes",
95
+ "teams",
96
+ "channels",
97
+ "chats",
98
+ "members",
99
+ "tabs",
100
+ "planner",
101
+ "plans",
102
+ "buckets",
103
+ "tasks",
104
+ "todo",
105
+ "onenote",
106
+ "notebooks",
107
+ "sections",
108
+ "pages",
109
+ "people",
110
+ "photo",
111
+ "mailboxSettings",
112
+ "subscriptions",
113
+ "outlook",
114
+ "masterCategories",
115
+ "inbox",
116
+ "drafts",
117
+ "sentitems",
118
+ "deleteditems",
119
+ "archive",
120
+ "junkemail",
121
+ "sendMail",
122
+ "reply",
123
+ "replyAll",
124
+ "forward",
125
+ "move",
126
+ "copy",
127
+ "send",
128
+ "createReply",
129
+ "createReplyAll",
130
+ "createForward",
131
+ "accept",
132
+ "decline",
133
+ "tentativelyAccept",
134
+ "cancel",
135
+ "getSchedule",
136
+ "findMeetingTimes",
137
+ "createUploadSession",
138
+ "invite",
139
+ "permissions",
140
+ "joinedTeams",
141
+ "memberOf",
142
+ "getMemberGroups",
143
+ "extensions",
144
+ "organization",
145
+ "reminderView",
146
+ "workbook",
147
+ "worksheets",
148
+ "tables",
149
+ "range",
150
+ "usedRange",
151
+ "presence",
152
+ "onlineMeetings",
153
+ "$batch",
154
+ "$value",
155
+ "$count",
156
+ "$ref"
157
+ ]);
158
+ const KNOWN_ERROR_CODES = /* @__PURE__ */ new Set([
159
+ "BadRequest",
160
+ "Unauthorized",
161
+ "Forbidden",
162
+ "NotFound",
163
+ "Conflict",
164
+ "TooManyRequests",
165
+ "ServiceUnavailable",
166
+ "InternalServerError",
167
+ "InvalidAuthenticationToken",
168
+ "InvalidRequest",
169
+ "ResourceNotFound",
170
+ "itemNotFound",
171
+ "invalidRequest",
172
+ "accessDenied",
173
+ "generalException",
174
+ "serviceNotAvailable",
175
+ "activityLimitReached",
176
+ "quotaLimitReached",
177
+ "unauthenticated",
178
+ "notAllowed",
179
+ "notSupported",
180
+ "nameAlreadyExists",
181
+ "invalidRange",
182
+ "malwareDetected",
183
+ "resyncRequired",
184
+ "SearchWithFilter",
185
+ "InefficientFilter",
186
+ "RequestBroker--ParseUri",
187
+ "ErrorAccessDenied",
188
+ "ErrorItemNotFound",
189
+ "ErrorInvalidIdMalformed",
190
+ "ErrorInvalidMailboxItemId",
191
+ "ErrorInvalidRequest",
192
+ "ErrorInvalidUser",
193
+ "ErrorInvalidRecipients",
194
+ "ErrorSendAsDenied",
195
+ "ErrorPropertyValidationFailure",
196
+ "ErrorInvalidPropertyRequest",
197
+ "ErrorMessageSizeExceeded",
198
+ "ErrorQuotaExceeded",
199
+ "ErrorMailboxNotEnabledForRESTAPI",
200
+ "MailboxNotEnabledForRESTAPI",
201
+ "ErrorInvalidOperation",
202
+ "ErrorObjectTypeChanged",
203
+ "ErrorIrresolvableConflict",
204
+ "ErrorInternalServerError",
205
+ "ErrorTimeoutExpired",
206
+ "ErrorServerBusy",
207
+ "ApplicationThrottled",
208
+ "MailboxConcurrency",
209
+ "ErrorInvalidAttachmentId",
210
+ "ErrorAttachmentSizeLimitExceeded",
211
+ "ErrorCalendarMeetingRequestIsOutOfDate",
212
+ "ErrorCalendarIsOrganizer",
213
+ "ErrorCalendarIsNotOrganizer",
214
+ "ErrorOccurrenceCrossingBoundary",
215
+ "ErrorSchemaValidation",
216
+ "ErrorInvalidPropertySet",
217
+ "invalid_grant",
218
+ "invalid_client",
219
+ "invalid_request",
220
+ "invalid_scope",
221
+ "unauthorized_client",
222
+ "interaction_required",
223
+ "consent_required",
224
+ "login_required",
225
+ "access_denied",
226
+ "temporarily_unavailable",
227
+ "ECONNRESET",
228
+ "ECONNREFUSED",
229
+ "ETIMEDOUT",
230
+ "ENOTFOUND",
231
+ "EAI_AGAIN",
232
+ "EPIPE",
233
+ "EHOSTUNREACH",
234
+ "ENETUNREACH",
235
+ "ERR_NETWORK",
236
+ "ERR_SOCKET_TIMEOUT",
237
+ "UND_ERR_CONNECT_TIMEOUT",
238
+ "UND_ERR_HEADERS_TIMEOUT",
239
+ "UND_ERR_BODY_TIMEOUT",
240
+ "UND_ERR_SOCKET",
241
+ "ABORT_ERR",
242
+ "ERR_FR_TOO_MANY_REDIRECTS"
243
+ ]);
244
+ function describeValue(value) {
245
+ if (value === null) return "null";
246
+ if (value === void 0) return "undefined";
247
+ if (typeof value === "string") return `string(${value.length})`;
248
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
249
+ if (typeof value === "boolean") return String(value);
250
+ if (Array.isArray(value)) return `array(${value.length})`;
251
+ if (typeof value === "object") return `object(${Object.keys(value).length} keys)`;
252
+ return typeof value;
253
+ }
254
+ function describeShape(value) {
255
+ if (!redactionEnabled()) return stringify(value);
256
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
257
+ return describeValue(value);
258
+ }
259
+ const entries = Object.entries(value);
260
+ const shown = [];
261
+ let other = 0;
262
+ for (const [k, v] of entries) {
263
+ if (KNOWN_PARAM_NAMES.has(k) && shown.length < MAX_LISTED)
264
+ shown.push(`${k}: ${describeValue(v)}`);
265
+ else other += 1;
266
+ }
267
+ if (other > 0) shown.push(`+${other} other`);
268
+ return `{${shown.join(", ")}}`;
269
+ }
270
+ function describeText(value) {
271
+ return redactionEnabled() ? `(${value.length} chars)` : value;
272
+ }
273
+ function stringify(value) {
274
+ try {
275
+ return JSON.stringify(value) ?? String(value);
276
+ } catch (error) {
277
+ return `[unserializable: ${error instanceof Error ? error.name : "unknown error"}]`;
278
+ }
279
+ }
280
+ function serializedSize(value) {
281
+ try {
282
+ return Buffer.byteLength(JSON.stringify(value) ?? "");
283
+ } catch {
284
+ return -1;
285
+ }
286
+ }
287
+ function describeUrl(url) {
288
+ if (typeof url !== "string") return typeof url;
289
+ if (!redactionEnabled()) return url;
290
+ let origin = "";
291
+ let rest = url;
292
+ const schemeEnd = url.indexOf("://");
293
+ if (schemeEnd > 0) {
294
+ const pathStart = url.indexOf("/", schemeEnd + 3);
295
+ origin = pathStart === -1 ? url : url.slice(0, pathStart);
296
+ rest = pathStart === -1 ? "" : url.slice(pathStart);
297
+ }
298
+ const q = rest.indexOf("?");
299
+ const pathPart = q === -1 ? rest : rest.slice(0, q);
300
+ const queryPart = q === -1 ? "" : rest.slice(q + 1);
301
+ const segments = pathPart.split("/").map((s) => {
302
+ if (s === "") return "";
303
+ const bare = s.endsWith(":") ? s.slice(0, -1) : s;
304
+ return KNOWN_PATH_SEGMENTS.has(bare) ? s : "{\u2026}";
305
+ });
306
+ let out = `${/^https?:\/\/[A-Za-z0-9.-]+(:\d+)?$/.test(origin) ? origin : origin ? "{origin}" : ""}${segments.join("/")}`;
307
+ if (queryPart) {
308
+ const names = [];
309
+ let other = 0;
310
+ for (const part of queryPart.split("&")) {
311
+ const name = part.split("=")[0];
312
+ if (!name) continue;
313
+ if (KNOWN_QUERY_NAMES.has(name)) {
314
+ if (!names.includes(name)) names.push(name);
315
+ } else other += 1;
316
+ }
317
+ const list = names.join(", ") + (other ? `${names.length ? ", " : ""}+${other} other` : "");
318
+ out += ` [query: ${list}]`;
319
+ }
320
+ return out;
321
+ }
322
+ const KNOWN_QUERY_NAMES = /* @__PURE__ */ new Set([
323
+ "$select",
324
+ "$filter",
325
+ "$search",
326
+ "$top",
327
+ "$skip",
328
+ "$skiptoken",
329
+ "$orderby",
330
+ "$count",
331
+ "$expand",
332
+ "$format",
333
+ "$deltatoken",
334
+ "$ref",
335
+ "$value",
336
+ "$batch",
337
+ "$metadata"
338
+ ]);
339
+ const KNOWN_ERROR_NAMES = /* @__PURE__ */ new Set([
340
+ "Error",
341
+ "TypeError",
342
+ "RangeError",
343
+ "SyntaxError",
344
+ "AbortError",
345
+ "TimeoutError",
346
+ "GraphApiError",
347
+ "OAuthUpstreamError",
348
+ "FetchError",
349
+ "AggregateError",
350
+ "DOMException",
351
+ "TicketStoreFullError",
352
+ "ClientAuthError",
353
+ "ServerError",
354
+ "InteractionRequiredAuthError",
355
+ "AuthError",
356
+ "BrowserAuthError"
357
+ ]);
358
+ function describeError(error) {
359
+ return errorText(error, !redactionEnabled());
360
+ }
361
+ function summarizeError(error) {
362
+ return errorText(error, false);
363
+ }
364
+ function errorText(error, full) {
365
+ if (!(error instanceof Error)) return full ? stringify(error) : `non-error(${typeof error})`;
366
+ const e = error;
367
+ const parts = [full || KNOWN_ERROR_NAMES.has(e.name) ? e.name || "Error" : "Error"];
368
+ const status = [e.httpStatus, e.status].find(
369
+ (s) => Number.isInteger(s) && s >= 100 && s <= 599
370
+ );
371
+ if (status !== void 0) parts.push(`status=${status}`);
372
+ const code = [e.graphErrorCode, e.code, e.errorCode].find((c) => c !== void 0 && c !== null);
373
+ if (typeof code === "number" && Number.isInteger(code)) parts.push(`code=${code}`);
374
+ else if (typeof code === "string") {
375
+ parts.push(
376
+ full || KNOWN_ERROR_CODES.has(code) ? `code=${code}` : `code=unlisted(${code.length})`
377
+ );
378
+ }
379
+ const summary = parts.join(" ");
380
+ return full && e.message ? `${summary}: ${e.message}` : summary;
381
+ }
382
+ const FRAME = /^at (?:[\w$.<>[\] ]+ \()?(?:node:[\w/]+|file:\/\/\S+|[A-Za-z]:\\\S+|\/\S+):\d+:\d+\)?$/;
383
+ function describeStack(error) {
384
+ if (!(error instanceof Error) || typeof error.stack !== "string") return [];
385
+ let tail = error.stack;
386
+ const message = typeof error.message === "string" ? error.message : "";
387
+ if (message.length > 0) {
388
+ const at = tail.indexOf(message);
389
+ if (at === -1) return [];
390
+ tail = tail.slice(at + message.length);
391
+ } else {
392
+ const nl = tail.indexOf("\n");
393
+ tail = nl === -1 ? "" : tail.slice(nl);
394
+ }
395
+ return tail.split("\n").map((l) => l.trim()).filter((l) => FRAME.test(l)).slice(0, 20);
396
+ }
397
+ export {
398
+ describeError,
399
+ describeShape,
400
+ describeStack,
401
+ describeText,
402
+ describeUrl,
403
+ serializedSize,
404
+ summarizeError
405
+ };
@@ -1,4 +1,5 @@
1
1
  import logger from "../logger.js";
2
+ import { describeText, summarizeError } from "./log-safe.js";
2
3
  import { getCloudEndpoints } from "../cloud-config.js";
3
4
  function buildResourceMetadataUrl(req, publicUrl) {
4
5
  if (publicUrl) {
@@ -166,9 +167,104 @@ function unwrapToken(result, failureMessage) {
166
167
  });
167
168
  throw new OAuthUpstreamError(result.status, result.raw, result.parsed);
168
169
  }
169
- logger.error(`${failureMessage}: ${result.raw}`);
170
+ logger.error(
171
+ `${failureMessage}: HTTP ${result.status}, unparsed body ${describeText(result.raw)}`
172
+ );
170
173
  throw new Error(`${failureMessage}: ${result.raw}`);
171
174
  }
175
+ const SELF_TEST_TIMEOUT_MS = 15e3;
176
+ const SAFE_CODE = /^[A-Za-z0-9_.-]{1,64}$/;
177
+ async function checkClientCredentials(clientId, clientSecret, tenantId, cloudType = "global", timeoutMs = SELF_TEST_TIMEOUT_MS) {
178
+ const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
179
+ const cloudEndpoints = getCloudEndpoints(cloudType);
180
+ const graphBase = cloudEndpoints.graphApi.replace(/\/$/, "");
181
+ const params = new URLSearchParams({
182
+ grant_type: "client_credentials",
183
+ client_id: clientId,
184
+ client_secret: clientSecret,
185
+ scope: `${graphBase}/.default`
186
+ });
187
+ const controller = new AbortController();
188
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
189
+ try {
190
+ const response = await fetch(`${cloudEndpoints.authority}/${tenantId}/oauth2/v2.0/token`, {
191
+ method: "POST",
192
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
193
+ body: params,
194
+ signal: controller.signal
195
+ });
196
+ const raw = await response.text();
197
+ let json = null;
198
+ try {
199
+ json = JSON.parse(raw);
200
+ } catch {
201
+ json = null;
202
+ }
203
+ const obj = json && typeof json === "object" ? json : null;
204
+ if (response.ok) {
205
+ if (obj && typeof obj.access_token === "string" && obj.access_token.length > 0) {
206
+ return { ok: true, verdict: "accepted", checkedAt, status: response.status };
207
+ }
208
+ return {
209
+ ok: false,
210
+ verdict: "malformed",
211
+ checkedAt,
212
+ status: response.status,
213
+ detail: `HTTP ${response.status} without a token (${raw.length} chars)`
214
+ };
215
+ }
216
+ if (obj && typeof obj.error === "string" && SAFE_CODE.test(obj.error)) {
217
+ const codes = Array.isArray(obj.error_codes) ? obj.error_codes.filter((c) => Number.isInteger(c)) : [];
218
+ const corr = typeof obj.correlation_id === "string" && /^[A-Za-z0-9-]{1,64}$/.test(obj.correlation_id) ? obj.correlation_id : void 0;
219
+ return {
220
+ ok: false,
221
+ verdict: "rejected",
222
+ checkedAt,
223
+ status: response.status,
224
+ error: obj.error,
225
+ error_codes: codes,
226
+ correlation_id: corr
227
+ };
228
+ }
229
+ return {
230
+ ok: false,
231
+ verdict: "malformed",
232
+ checkedAt,
233
+ status: response.status,
234
+ detail: `HTTP ${response.status}, unparsed response (${raw.length} chars)`
235
+ };
236
+ } catch (error) {
237
+ const timedOut = controller.signal.aborted;
238
+ return {
239
+ ok: false,
240
+ verdict: "unavailable",
241
+ checkedAt,
242
+ detail: timedOut ? `no answer within ${timeoutMs} ms` : `request failed: ${summarizeError(error)}`
243
+ };
244
+ } finally {
245
+ clearTimeout(timer);
246
+ }
247
+ }
248
+ function credentialCheckMessage(c, tenantId) {
249
+ const codes = (c.error_codes ?? []).join(", ");
250
+ const ref = `${c.error ?? "none"}, error_codes [${codes}], correlation_id ${c.correlation_id ?? "none"}`;
251
+ switch (c.verdict) {
252
+ case "accepted":
253
+ return `Startup self-test: Microsoft accepted the client id and secret for tenant ${tenantId}. (App credentials only; not a test of user sign-in or Graph access.)`;
254
+ case "rejected":
255
+ if (c.error_codes?.includes(7000215)) {
256
+ return `Startup self-test FAILED: Microsoft rejected the client secret as not a current secret value of this app (${ref}). Sign-ins will fail until the secret value is corrected and the revision restarted.`;
257
+ }
258
+ if (c.error_codes?.includes(7000222)) {
259
+ return `Startup self-test FAILED: the client secret has expired (${ref}). Sign-ins will fail until a new secret is created, stored, and the revision restarted.`;
260
+ }
261
+ return `Startup self-test FAILED: Microsoft rejected the app credentials (${ref}). Look the code up in the troubleshooting table; this says nothing about the secret value.`;
262
+ case "unavailable":
263
+ return `Startup self-test could not be completed (${c.detail ?? "unknown"}); the credentials were not judged. Check network access to the Microsoft login endpoint.`;
264
+ default:
265
+ return `Startup self-test inconclusive: ${c.detail ?? "unexpected answer"}; the credentials were not judged.`;
266
+ }
267
+ }
172
268
  async function exchangeCodeForToken(code, redirectUri, clientId, clientSecret, tenantId = "common", codeVerifier, cloudType = "global", scope) {
173
269
  const cloudEndpoints = getCloudEndpoints(cloudType);
174
270
  const params = new URLSearchParams({
@@ -210,6 +306,8 @@ async function refreshAccessToken(refreshToken, clientId, clientSecret, tenantId
210
306
  export {
211
307
  OAuthUpstreamError,
212
308
  buildWwwAuthenticate,
309
+ checkClientCredentials,
310
+ credentialCheckMessage,
213
311
  exchangeCodeForToken,
214
312
  microsoftBearerTokenAuthMiddleware,
215
313
  refreshAccessToken,
package/dist/logger.js CHANGED
@@ -4,6 +4,8 @@ import { fileURLToPath } from "url";
4
4
  import fs from "fs";
5
5
  import os from "os";
6
6
  import { redactionEnabled, redactSensitive } from "./lib/log-redactor.js";
7
+ import { LOG_MAX_BYTES, LOG_MAX_FILES } from "./lib/log-limits.js";
8
+ import { BoundedFileTransport } from "./lib/bounded-file-transport.js";
7
9
  const redactFormat = winston.format((info) => {
8
10
  if (!redactionEnabled()) return info;
9
11
  if (typeof info.message === "string") {
@@ -46,14 +48,19 @@ const logger = winston.createLogger({
46
48
  })
47
49
  ),
48
50
  transports: [
49
- new winston.transports.File({
51
+ // Bounded files: each rotates at LOG_MAX_BYTES, LOG_MAX_FILES kept (see log-limits).
52
+ new BoundedFileTransport({
50
53
  filename: errorLogPath,
51
54
  level: "error",
52
- options: { flags: "a", mode: FILE_MODE }
55
+ maxBytes: LOG_MAX_BYTES,
56
+ maxFiles: LOG_MAX_FILES,
57
+ mode: FILE_MODE
53
58
  }),
54
- new winston.transports.File({
59
+ new BoundedFileTransport({
55
60
  filename: serverLogPath,
56
- options: { flags: "a", mode: FILE_MODE }
61
+ maxBytes: LOG_MAX_BYTES,
62
+ maxFiles: LOG_MAX_FILES,
63
+ mode: FILE_MODE
57
64
  })
58
65
  ]
59
66
  });
package/dist/server.js CHANGED
@@ -8,6 +8,7 @@ import rateLimit from "express-rate-limit";
8
8
  import helmet from "helmet";
9
9
  import crypto from "node:crypto";
10
10
  import { isIP, isIPv6 } from "node:net";
11
+ import { NON_TENANT_AUTHORITIES } from "./app-mode.js";
11
12
  import { createAttachmentHandler, createAttachmentUploadHandler } from "./attachment-route.js";
12
13
  import { registerAuthTools } from "./auth-tools.js";
13
14
  import {
@@ -32,10 +33,13 @@ import {
32
33
  buildWwwAuthenticate,
33
34
  OAuthUpstreamError,
34
35
  refreshAccessToken,
35
- toOAuthErrorResponse
36
+ toOAuthErrorResponse,
37
+ checkClientCredentials,
38
+ credentialCheckMessage
36
39
  } from "./lib/microsoft-auth.js";
37
40
  import { isAllowedRedirectUri, parseAllowlist } from "./lib/redirect-uri-validation.js";
38
41
  import logger, { enableConsoleLogging } from "./logger.js";
42
+ import { version } from "./version.js";
39
43
  import { buildMcpServerInstructions } from "./mcp-instructions.js";
40
44
  import { installToolSchemaRefNormalization } from "./normalize-tool-schema.js";
41
45
  import { MicrosoftOAuthProvider } from "./oauth-provider.js";
@@ -161,6 +165,7 @@ function statelessPkceSecret(env = process.env) {
161
165
  }
162
166
  class MicrosoftGraphServer {
163
167
  constructor(authManager, options = {}) {
168
+ this.credentialCheck = null;
164
169
  this.version = "0.0.0";
165
170
  this.multiAccount = false;
166
171
  this.accountNames = [];
@@ -259,9 +264,9 @@ class MicrosoftGraphServer {
259
264
  if (!this.options.obo || !this.secrets?.clientId) return void 0;
260
265
  return `${this.secrets.clientId}/access_as_user offline_access`;
261
266
  }
262
- async initialize(version) {
267
+ async initialize(version2) {
263
268
  this.secrets = this.authManager.getAppSecrets?.() ?? await getSecrets();
264
- this.version = version;
269
+ this.version = version2;
265
270
  const accountRoutingAvailable = (!this.options.http || this.options.trustProxyAuth) && !this.authManager.isOAuthModeEnabled();
266
271
  if (accountRoutingAvailable) {
267
272
  try {
@@ -466,7 +471,7 @@ class MicrosoftGraphServer {
466
471
  if (this.options.enableDynamicRegistration) {
467
472
  app.post("/register", async (req, res) => {
468
473
  const body = req.body;
469
- logger.info("Client registration request", { body });
474
+ logger.info("Client registration request", { keys: Object.keys(body ?? {}) });
470
475
  const clientId = `mcp-client-${Date.now()}`;
471
476
  res.status(201).json({
472
477
  client_id: clientId,
@@ -603,7 +608,7 @@ class MicrosoftGraphServer {
603
608
  return;
604
609
  }
605
610
  if (!body.grant_type) {
606
- logger.error("Token endpoint: grant_type is missing", { body });
611
+ logger.error("Token endpoint: grant_type is missing", { keys: Object.keys(body) });
607
612
  res.status(400).json({
608
613
  error: "invalid_request",
609
614
  error_description: "grant_type parameter is required"
@@ -832,6 +837,15 @@ class MicrosoftGraphServer {
832
837
  app.get("/", (req, res) => {
833
838
  res.send("Microsoft 365 MCP Server is running");
834
839
  });
840
+ app.get("/health", (req, res) => {
841
+ res.json({
842
+ status: "ok",
843
+ version,
844
+ // Startup app-credential check: did Microsoft accept the client id and secret.
845
+ // Not a test of user sign-in, On-Behalf-Of exchange, Graph access or Claude.
846
+ credentialCheck: this.credentialCheck ?? { ok: null, verdict: "not run" }
847
+ });
848
+ });
835
849
  const mcpBound = await this.listen(app, port, host);
836
850
  const mcp = describeBoundAddress(mcpBound);
837
851
  logger.info(`Server listening on ${mcp.label}`);
@@ -840,6 +854,25 @@ class MicrosoftGraphServer {
840
854
  logger.info(
841
855
  ` - OAuth discovery: http://${mcp.authority}/.well-known/oauth-authorization-server`
842
856
  );
857
+ if (this.oboClient && this.secrets?.clientSecret && process.env.VITEST !== "true") {
858
+ const tenantId = this.secrets.tenantId;
859
+ if (!tenantId || NON_TENANT_AUTHORITIES.has(tenantId.toLowerCase())) {
860
+ logger.warn("Startup self-test skipped: MS365_MCP_TENANT_ID is not a tenant id");
861
+ } else {
862
+ this.credentialCheck = await checkClientCredentials(
863
+ this.secrets.clientId,
864
+ this.secrets.clientSecret,
865
+ this.secrets.tenantId,
866
+ this.secrets.cloudType
867
+ );
868
+ const c = this.credentialCheck;
869
+ const line = credentialCheckMessage(c, this.secrets.tenantId);
870
+ if (c.verdict === "accepted") logger.info(line);
871
+ else if (c.verdict === "rejected") logger.error(line);
872
+ else logger.warn(line);
873
+ console.error(`[ms365-mcp] ${line}`);
874
+ }
875
+ }
843
876
  if (attachmentApp && attachmentPort !== null) {
844
877
  let attachmentBound;
845
878
  try {
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.182.2",
4
+ "version": "0.182.3",
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",