@softeria/ms-365-mcp-server 0.182.1 → 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.
@@ -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.1",
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",
@@ -1334,7 +1334,7 @@
1334
1334
  {
1335
1335
  "pathPattern": "/sites/{site-id}/onenote/sectionGroups/{sectionGroup-id}/sectionGroups",
1336
1336
  "method": "get",
1337
- "toolName": "list-sharepoint-site-onenote-section-group-section-groups",
1337
+ "toolName": "list-sharepoint-site-onenote-child-section-groups",
1338
1338
  "presets": ["onenote", "work"],
1339
1339
  "workScopes": ["Notes.Read.All"]
1340
1340
  },