@softeria/ms-365-mcp-server 0.190.4 → 0.191.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/__tests__/graph-tools.test.js +25 -11
- package/dist/app-mode.js +1 -0
- package/dist/auth-tools.js +47 -38
- package/dist/auth.js +19 -2
- package/dist/cli.js +2 -2
- package/dist/generated/hack.js +1 -0
- package/dist/graph-client.js +6 -1
- package/dist/graph-tools.js +82 -49
- package/dist/lib/attachment-tickets.js +1 -1
- package/dist/lib/body-schema-budget.js +27 -1
- package/dist/lib/bounded-file-transport.js +6 -1
- package/dist/lib/client-metadata.js +18 -5
- package/dist/lib/graph-resilience.js +4 -3
- package/dist/lib/microsoft-auth.js +4 -0
- package/dist/normalize-tool-schema.js +0 -38
- package/dist/obo-client.js +2 -0
- package/dist/secrets.js +1 -0
- package/dist/server.js +129 -53
- package/dist/token-cache-storage.js +4 -5
- package/docs/deployment.md +11 -3
- package/eslint.config.js +17 -0
- package/package.json +5 -3
- package/tsup.config.ts +3 -2
- package/dist/oauth-provider.js +0 -51
- package/test-calendar-fix.js +0 -62
- package/test-real-calendar.js +0 -96
|
@@ -9,6 +9,7 @@ const CIMD_MIN_TTL_MS = 6e4;
|
|
|
9
9
|
const CIMD_MAX_TTL_MS = 24 * 60 * 6e4;
|
|
10
10
|
const CIMD_MAX_CACHE_ENTRIES = 500;
|
|
11
11
|
const CIMD_MAX_IN_FLIGHT = 20;
|
|
12
|
+
const CIMD_RETRY_AFTER_SECONDS = 30;
|
|
12
13
|
class ClientMetadataError extends Error {
|
|
13
14
|
constructor(message, transient = false) {
|
|
14
15
|
super(message);
|
|
@@ -255,9 +256,11 @@ function redirectUriMatches(requested, registered) {
|
|
|
255
256
|
}
|
|
256
257
|
const CIMD_MAX_STALE_MS = 24 * 60 * 6e4;
|
|
257
258
|
class ClientMetadataResolver {
|
|
259
|
+
cache = /* @__PURE__ */ new Map();
|
|
260
|
+
inFlight = /* @__PURE__ */ new Map();
|
|
261
|
+
fetcher;
|
|
262
|
+
now;
|
|
258
263
|
constructor(options = {}) {
|
|
259
|
-
this.cache = /* @__PURE__ */ new Map();
|
|
260
|
-
this.inFlight = /* @__PURE__ */ new Map();
|
|
261
264
|
this.fetcher = options.fetcher ?? fetchDocument;
|
|
262
265
|
this.now = options.now ?? Date.now;
|
|
263
266
|
}
|
|
@@ -274,7 +277,10 @@ class ClientMetadataResolver {
|
|
|
274
277
|
if (!pending) {
|
|
275
278
|
if (this.inFlight.size >= CIMD_MAX_IN_FLIGHT) {
|
|
276
279
|
if (stale) return stale;
|
|
277
|
-
throw new ClientMetadataError(
|
|
280
|
+
throw new ClientMetadataError(
|
|
281
|
+
"too many client metadata lookups in progress, try again",
|
|
282
|
+
true
|
|
283
|
+
);
|
|
278
284
|
}
|
|
279
285
|
pending = this.load(url, clientId).finally(() => this.inFlight.delete(clientId));
|
|
280
286
|
this.inFlight.set(clientId, pending);
|
|
@@ -338,8 +344,14 @@ async function checkAuthorizeClient(params) {
|
|
|
338
344
|
try {
|
|
339
345
|
metadata = await resolver.resolve(clientId);
|
|
340
346
|
} catch (err) {
|
|
341
|
-
|
|
342
|
-
|
|
347
|
+
if (!(err instanceof ClientMetadataError)) {
|
|
348
|
+
return { ok: false, error: "invalid_client", description: "client metadata error" };
|
|
349
|
+
}
|
|
350
|
+
return {
|
|
351
|
+
ok: false,
|
|
352
|
+
error: err.transient ? "temporarily_unavailable" : "invalid_client",
|
|
353
|
+
description: err.message
|
|
354
|
+
};
|
|
343
355
|
}
|
|
344
356
|
if (!redirectUriMatches(redirectUri, metadata.redirect_uris)) {
|
|
345
357
|
return {
|
|
@@ -358,6 +370,7 @@ export {
|
|
|
358
370
|
CIMD_MAX_STALE_MS,
|
|
359
371
|
CIMD_MAX_TTL_MS,
|
|
360
372
|
CIMD_MIN_TTL_MS,
|
|
373
|
+
CIMD_RETRY_AFTER_SECONDS,
|
|
361
374
|
CIMD_TIMEOUT_MS,
|
|
362
375
|
ClientMetadataError,
|
|
363
376
|
ClientMetadataResolver,
|
|
@@ -21,11 +21,12 @@ function loadResilienceConfig() {
|
|
|
21
21
|
};
|
|
22
22
|
}
|
|
23
23
|
class CircuitOpenError extends Error {
|
|
24
|
+
code = "circuit_open";
|
|
25
|
+
cooldownMs;
|
|
24
26
|
constructor(cooldownMs) {
|
|
25
27
|
super(
|
|
26
28
|
`Graph circuit breaker is open (cooldown ${cooldownMs} ms). Upstream has failed repeatedly; refusing to flood it.`
|
|
27
29
|
);
|
|
28
|
-
this.code = "circuit_open";
|
|
29
30
|
this.name = "CircuitOpenError";
|
|
30
31
|
this.cooldownMs = cooldownMs;
|
|
31
32
|
}
|
|
@@ -36,9 +37,9 @@ class CircuitBreaker {
|
|
|
36
37
|
this.cooldownMs = cooldownMs;
|
|
37
38
|
this.disabled = disabled;
|
|
38
39
|
this.now = now;
|
|
39
|
-
this.failures = 0;
|
|
40
|
-
this.openedAt = null;
|
|
41
40
|
}
|
|
41
|
+
failures = 0;
|
|
42
|
+
openedAt = null;
|
|
42
43
|
/**
|
|
43
44
|
* @returns the time-remaining (in ms) before the circuit can be probed,
|
|
44
45
|
* or `null` if the circuit is closed and the call should proceed.
|
|
@@ -27,6 +27,7 @@ function isJwtExpired(token) {
|
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
const DISCOVERY_METHODS = /* @__PURE__ */ new Set([
|
|
30
|
+
"server/discover",
|
|
30
31
|
"initialize",
|
|
31
32
|
"notifications/initialized",
|
|
32
33
|
"tools/list",
|
|
@@ -79,6 +80,9 @@ const microsoftBearerTokenAuthMiddleware = (opts = {}) => (req, res, next) => {
|
|
|
79
80
|
next();
|
|
80
81
|
};
|
|
81
82
|
class OAuthUpstreamError extends Error {
|
|
83
|
+
status;
|
|
84
|
+
body;
|
|
85
|
+
raw;
|
|
82
86
|
constructor(status, raw, body) {
|
|
83
87
|
const suffix = body.error_description ? ` - ${body.error_description}` : "";
|
|
84
88
|
super(`OAuth upstream error: ${body.error}${suffix}`);
|
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
2
1
|
import { z } from "zod";
|
|
3
|
-
import logger from "./logger.js";
|
|
4
2
|
function dropZodOnlyChecks(node) {
|
|
5
3
|
if (!node || typeof node !== "object") return;
|
|
6
4
|
if (Array.isArray(node)) {
|
|
@@ -351,43 +349,7 @@ function normalizeToolSchemaRefs(schema) {
|
|
|
351
349
|
const inlined = inlineExcept(leavesOnly);
|
|
352
350
|
return JSON.stringify(inlined).length <= limit ? inlined : hoisted;
|
|
353
351
|
}
|
|
354
|
-
function installToolSchemaRefNormalization(server) {
|
|
355
|
-
const lowLevel = server.server;
|
|
356
|
-
const handlers = lowLevel._requestHandlers;
|
|
357
|
-
const original = handlers?.get("tools/list");
|
|
358
|
-
if (!original) {
|
|
359
|
-
logger.warn("Skipping tool-schema $ref normalization: tools/list handler not found");
|
|
360
|
-
return;
|
|
361
|
-
}
|
|
362
|
-
const registered = server._registeredTools;
|
|
363
|
-
lowLevel.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
|
|
364
|
-
for (const [name, tool] of Object.entries(registered ?? {})) {
|
|
365
|
-
if (tool.inputSchema instanceof z.core.$ZodObject) useOwnConversion(name, tool.inputSchema);
|
|
366
|
-
}
|
|
367
|
-
const result = await original(request, extra);
|
|
368
|
-
for (const tool of result.tools ?? []) {
|
|
369
|
-
if (tool.inputSchema && typeof tool.inputSchema === "object") {
|
|
370
|
-
tool.inputSchema = normalizeToolSchemaRefs(tool.inputSchema);
|
|
371
|
-
tidyToolJsonSchema(tool.inputSchema);
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
return result;
|
|
375
|
-
});
|
|
376
|
-
}
|
|
377
|
-
function useOwnConversion(name, schema) {
|
|
378
|
-
const internals = schema._zod;
|
|
379
|
-
if (internals.toJSONSchema) return;
|
|
380
|
-
internals.toJSONSchema = () => {
|
|
381
|
-
try {
|
|
382
|
-
return toolInputJsonSchema(schema);
|
|
383
|
-
} catch (error) {
|
|
384
|
-
logger.warn(`Could not convert the input schema of ${name}: ${error}`);
|
|
385
|
-
return void 0;
|
|
386
|
-
}
|
|
387
|
-
};
|
|
388
|
-
}
|
|
389
352
|
export {
|
|
390
|
-
installToolSchemaRefNormalization,
|
|
391
353
|
normalizeToolSchemaRefs,
|
|
392
354
|
tidyToolJsonSchema,
|
|
393
355
|
toolInputJsonSchema,
|
package/dist/obo-client.js
CHANGED
|
@@ -2,6 +2,8 @@ import { ConfidentialClientApplication } from "@azure/msal-node";
|
|
|
2
2
|
import logger from "./logger.js";
|
|
3
3
|
import { getCloudEndpoints } from "./cloud-config.js";
|
|
4
4
|
class OboClient {
|
|
5
|
+
cca;
|
|
6
|
+
graphScopes;
|
|
5
7
|
constructor(secrets) {
|
|
6
8
|
if (!secrets.clientSecret) {
|
|
7
9
|
throw new Error(
|
package/dist/secrets.js
CHANGED
package/dist/server.js
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import {
|
|
2
|
+
hostHeaderValidation,
|
|
3
|
+
NodeStreamableHTTPServerTransport,
|
|
4
|
+
toNodeHandler,
|
|
5
|
+
toWebRequest
|
|
6
|
+
} from "@modelcontextprotocol/node";
|
|
7
|
+
import {
|
|
8
|
+
createMcpHandler,
|
|
9
|
+
isLegacyRequest,
|
|
10
|
+
McpServer
|
|
11
|
+
} from "@modelcontextprotocol/server";
|
|
12
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
6
13
|
import express from "express";
|
|
7
14
|
import rateLimit from "express-rate-limit";
|
|
8
15
|
import helmet from "helmet";
|
|
@@ -40,6 +47,7 @@ import {
|
|
|
40
47
|
import { isAllowedRedirectUri, parseAllowlist } from "./lib/redirect-uri-validation.js";
|
|
41
48
|
import {
|
|
42
49
|
checkAuthorizeClient,
|
|
50
|
+
CIMD_RETRY_AFTER_SECONDS,
|
|
43
51
|
clientIdHost,
|
|
44
52
|
ClientMetadataResolver,
|
|
45
53
|
DCR_DISABLED_HINT
|
|
@@ -47,8 +55,6 @@ import {
|
|
|
47
55
|
import logger, { enableConsoleLogging } from "./logger.js";
|
|
48
56
|
import { version } from "./version.js";
|
|
49
57
|
import { buildMcpServerInstructions } from "./mcp-instructions.js";
|
|
50
|
-
import { installToolSchemaRefNormalization } from "./normalize-tool-schema.js";
|
|
51
|
-
import { MicrosoftOAuthProvider } from "./oauth-provider.js";
|
|
52
58
|
import OboClient from "./obo-client.js";
|
|
53
59
|
import { isRejectedAssertion, oboAllowlistRefusal, readOboAllowlist } from "./lib/obo-access.js";
|
|
54
60
|
import { requestContext } from "./request-context.js";
|
|
@@ -170,28 +176,39 @@ function statelessPkceSecret(env = process.env) {
|
|
|
170
176
|
return secret;
|
|
171
177
|
}
|
|
172
178
|
class MicrosoftGraphServer {
|
|
179
|
+
authManager;
|
|
180
|
+
options;
|
|
181
|
+
graphClient;
|
|
182
|
+
server;
|
|
183
|
+
secrets;
|
|
184
|
+
oboClient;
|
|
185
|
+
credentialCheck = null;
|
|
186
|
+
version = "0.0.0";
|
|
187
|
+
multiAccount = false;
|
|
188
|
+
accountNames = [];
|
|
189
|
+
/**
|
|
190
|
+
* Every HTTP listener `start()` opened, so `stop()` can close every one.
|
|
191
|
+
*
|
|
192
|
+
* A list rather than a field because `--attachment-port` makes it two, and an
|
|
193
|
+
* untracked listener cannot be closed at all: it holds the event loop open
|
|
194
|
+
* for the life of the process. One that is only *usually* two is worse than
|
|
195
|
+
* either, so nothing here special-cases the count.
|
|
196
|
+
*/
|
|
197
|
+
httpServers = [];
|
|
198
|
+
// The 2026-07-28 leg of /mcp, built once in start() so stop() can close it
|
|
199
|
+
mcpHandler = null;
|
|
200
|
+
stdioHandle = null;
|
|
201
|
+
// Two-leg PKCE: stores client's code_challenge and server's code_verifier, keyed by OAuth state
|
|
202
|
+
pkceStore = /* @__PURE__ */ new Map();
|
|
203
|
+
// Set in start() for HTTP mode; replaces pkceStore when present.
|
|
204
|
+
pkceSecret;
|
|
205
|
+
reportedUnavailableEagerTools = /* @__PURE__ */ new Set();
|
|
206
|
+
reportUnavailableEagerTool = (name) => {
|
|
207
|
+
if (this.reportedUnavailableEagerTools.has(name)) return;
|
|
208
|
+
this.reportedUnavailableEagerTools.add(name);
|
|
209
|
+
logger.info(`Eager tool ${name} is unavailable under the current filters or transport`);
|
|
210
|
+
};
|
|
173
211
|
constructor(authManager, options = {}) {
|
|
174
|
-
this.credentialCheck = null;
|
|
175
|
-
this.version = "0.0.0";
|
|
176
|
-
this.multiAccount = false;
|
|
177
|
-
this.accountNames = [];
|
|
178
|
-
/**
|
|
179
|
-
* Every HTTP listener `start()` opened, so `stop()` can close every one.
|
|
180
|
-
*
|
|
181
|
-
* A list rather than a field because `--attachment-port` makes it two, and an
|
|
182
|
-
* untracked listener cannot be closed at all: it holds the event loop open
|
|
183
|
-
* for the life of the process. One that is only *usually* two is worse than
|
|
184
|
-
* either, so nothing here special-cases the count.
|
|
185
|
-
*/
|
|
186
|
-
this.httpServers = [];
|
|
187
|
-
// Two-leg PKCE: stores client's code_challenge and server's code_verifier, keyed by OAuth state
|
|
188
|
-
this.pkceStore = /* @__PURE__ */ new Map();
|
|
189
|
-
this.reportedUnavailableEagerTools = /* @__PURE__ */ new Set();
|
|
190
|
-
this.reportUnavailableEagerTool = (name) => {
|
|
191
|
-
if (this.reportedUnavailableEagerTools.has(name)) return;
|
|
192
|
-
this.reportedUnavailableEagerTools.add(name);
|
|
193
|
-
logger.info(`Eager tool ${name} is unavailable under the current filters or transport`);
|
|
194
|
-
};
|
|
195
212
|
if (options.eagerTools?.length) validateEagerToolNames(options.eagerTools);
|
|
196
213
|
this.authManager = authManager;
|
|
197
214
|
this.options = options;
|
|
@@ -209,6 +226,7 @@ class MicrosoftGraphServer {
|
|
|
209
226
|
return Boolean(this.options.http) && !this.options.httpLocalFileTools;
|
|
210
227
|
}
|
|
211
228
|
createMcpServer() {
|
|
229
|
+
const mcpApps = Boolean(this.options.enableMcpApps && !this.options.toon);
|
|
212
230
|
const server = new McpServer(
|
|
213
231
|
{
|
|
214
232
|
name: "Microsoft365MCP",
|
|
@@ -224,7 +242,12 @@ class MicrosoftGraphServer {
|
|
|
224
242
|
multiAccount: this.multiAccount,
|
|
225
243
|
attachmentUrlsEnabled: Boolean(this.options.http && this.options.enableAttachmentUrls)
|
|
226
244
|
}),
|
|
227
|
-
maxToolInputElements: MAX_TOOL_INPUT_ELEMENTS
|
|
245
|
+
maxToolInputElements: MAX_TOOL_INPUT_ELEMENTS,
|
|
246
|
+
// The tool set is fixed for the life of a server, so no list ever changes
|
|
247
|
+
capabilities: {
|
|
248
|
+
tools: { listChanged: false },
|
|
249
|
+
...mcpApps && { resources: { listChanged: false } }
|
|
250
|
+
}
|
|
228
251
|
}
|
|
229
252
|
);
|
|
230
253
|
const shouldRegisterAuthTools = !this.options.appMode && (!this.options.http || this.options.enableAuthTools);
|
|
@@ -250,15 +273,13 @@ class MicrosoftGraphServer {
|
|
|
250
273
|
allowedScopes: this.options.allowedScopes,
|
|
251
274
|
httpMode: this.hidesStdioOnlyTools(),
|
|
252
275
|
userFields: this.options.userFields,
|
|
253
|
-
|
|
254
|
-
mcpApps: Boolean(this.options.enableMcpApps && !this.options.toon)
|
|
276
|
+
mcpApps
|
|
255
277
|
};
|
|
256
278
|
if (this.options.discovery) {
|
|
257
279
|
registerDiscoveryTools(server, this.graphClient, registrationOptions);
|
|
258
280
|
} else {
|
|
259
281
|
registerGraphTools(server, this.graphClient, registrationOptions);
|
|
260
282
|
}
|
|
261
|
-
installToolSchemaRefNormalization(server);
|
|
262
283
|
return server;
|
|
263
284
|
}
|
|
264
285
|
/**
|
|
@@ -390,7 +411,10 @@ class MicrosoftGraphServer {
|
|
|
390
411
|
}
|
|
391
412
|
const app = express();
|
|
392
413
|
if (this.isLoopbackOnlyHttp()) {
|
|
393
|
-
|
|
414
|
+
const hostGuard = hostHeaderValidation(LOOPBACK_HOSTNAMES);
|
|
415
|
+
app.use((req, res, next) => {
|
|
416
|
+
if (hostGuard(req, res)) next();
|
|
417
|
+
});
|
|
394
418
|
app.use(loopbackOriginValidation());
|
|
395
419
|
}
|
|
396
420
|
const trustProxyEnv = process.env.MS365_MCP_TRUST_PROXY_HOPS;
|
|
@@ -416,7 +440,7 @@ class MicrosoftGraphServer {
|
|
|
416
440
|
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
|
|
417
441
|
res.header(
|
|
418
442
|
"Access-Control-Allow-Headers",
|
|
419
|
-
"Origin, X-Requested-With, Content-Type, Accept, Authorization, mcp-protocol-version"
|
|
443
|
+
"Origin, X-Requested-With, Content-Type, Accept, Authorization, mcp-protocol-version, mcp-method, mcp-name"
|
|
420
444
|
);
|
|
421
445
|
if (req.method === "OPTIONS") {
|
|
422
446
|
res.sendStatus(200);
|
|
@@ -443,9 +467,21 @@ class MicrosoftGraphServer {
|
|
|
443
467
|
app.use("/register", authLimiter);
|
|
444
468
|
app.use("/mcp", mcpLimiter);
|
|
445
469
|
}
|
|
446
|
-
const oauthProvider = new MicrosoftOAuthProvider(this.authManager, this.secrets);
|
|
447
470
|
const publicUrlRaw = this.options.publicUrl || process.env.MS365_MCP_PUBLIC_URL || this.options.baseUrl || process.env.MS365_MCP_BASE_URL || null;
|
|
448
471
|
const publicBase = publicUrlRaw ? new URL(publicUrlRaw).href.replace(/\/$/, "") : null;
|
|
472
|
+
if (publicUrlRaw) {
|
|
473
|
+
const parsed = new URL(publicUrlRaw);
|
|
474
|
+
if (!["http:", "https:"].includes(parsed.protocol) || parsed.search || parsed.hash) {
|
|
475
|
+
throw new Error(
|
|
476
|
+
`Public URL ${publicUrlRaw} must be an http(s) URL without a query or fragment`
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
if (parsed.protocol === "http:" && !isLoopbackHost(parsed.hostname)) {
|
|
480
|
+
logger.warn(
|
|
481
|
+
`Public URL ${parsed.origin} is http:// on a non-loopback host. Newer MCP clients refuse an http token endpoint and cannot sign in; serve it over https.`
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
449
485
|
const cimdEnabled = this.options.clientMetadataDocuments !== false;
|
|
450
486
|
app.get("/.well-known/oauth-authorization-server", async (req, res) => {
|
|
451
487
|
const protocol = req.secure ? "https" : "http";
|
|
@@ -546,7 +582,9 @@ class MicrosoftGraphServer {
|
|
|
546
582
|
error: clientCheck.error,
|
|
547
583
|
reason: clientCheck.description
|
|
548
584
|
});
|
|
549
|
-
|
|
585
|
+
const unavailable = clientCheck.error === "temporarily_unavailable";
|
|
586
|
+
if (unavailable) res.set("Retry-After", String(CIMD_RETRY_AFTER_SECONDS));
|
|
587
|
+
res.status(unavailable ? 503 : 400).json({
|
|
550
588
|
error: clientCheck.error,
|
|
551
589
|
error_description: clientCheck.description
|
|
552
590
|
});
|
|
@@ -749,12 +787,6 @@ class MicrosoftGraphServer {
|
|
|
749
787
|
res.status(status).json(body);
|
|
750
788
|
}
|
|
751
789
|
});
|
|
752
|
-
app.use(
|
|
753
|
-
mcpAuthRouter({
|
|
754
|
-
provider: oauthProvider,
|
|
755
|
-
issuerUrl: new URL(publicBase ?? `http://localhost:${port}`)
|
|
756
|
-
})
|
|
757
|
-
);
|
|
758
790
|
const oboAllowlist = this.oboClient ? readOboAllowlist() : null;
|
|
759
791
|
if (oboAllowlist && (oboAllowlist.tenants.size > 0 || oboAllowlist.users.size > 0)) {
|
|
760
792
|
logger.info(
|
|
@@ -766,6 +798,23 @@ class MicrosoftGraphServer {
|
|
|
766
798
|
allowUnauthenticatedDiscovery: this.options.allowUnauthenticatedDiscovery,
|
|
767
799
|
publicUrl: publicBase
|
|
768
800
|
});
|
|
801
|
+
const onMcpError = (error) => {
|
|
802
|
+
if (error.message.startsWith("Rejected inbound request")) {
|
|
803
|
+
logger.debug(`MCP request refused: ${error.message}`);
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
logger.error("MCP request error", { error: dumpError(error) });
|
|
807
|
+
};
|
|
808
|
+
const mcpHandler = createMcpHandler(() => this.createMcpServer(), {
|
|
809
|
+
legacy: "reject",
|
|
810
|
+
maxRequestBodySize: MAX_REQUEST_BODY_BYTES,
|
|
811
|
+
onerror: onMcpError
|
|
812
|
+
});
|
|
813
|
+
this.mcpHandler = mcpHandler;
|
|
814
|
+
const serveModernMcp = toNodeHandler(mcpHandler, {
|
|
815
|
+
maxRequestBodySize: MAX_REQUEST_BODY_BYTES,
|
|
816
|
+
onerror: onMcpError
|
|
817
|
+
});
|
|
769
818
|
app.get("/mcp", (req, res) => {
|
|
770
819
|
res.status(405).json({
|
|
771
820
|
jsonrpc: "2.0",
|
|
@@ -781,8 +830,20 @@ class MicrosoftGraphServer {
|
|
|
781
830
|
mcpAuth,
|
|
782
831
|
async (req, res) => {
|
|
783
832
|
const handler = async () => {
|
|
833
|
+
const body = req.body;
|
|
834
|
+
if (body !== void 0) {
|
|
835
|
+
const probe = await toWebRequest(req, body, {
|
|
836
|
+
maxRequestBodySize: MAX_REQUEST_BODY_BYTES
|
|
837
|
+
});
|
|
838
|
+
if (!await isLegacyRequest(probe, body, {
|
|
839
|
+
maxRequestBodySize: MAX_REQUEST_BODY_BYTES
|
|
840
|
+
})) {
|
|
841
|
+
await serveModernMcp(req, res, body);
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
784
845
|
const server = this.createMcpServer();
|
|
785
|
-
const transport = new
|
|
846
|
+
const transport = new NodeStreamableHTTPServerTransport({
|
|
786
847
|
sessionIdGenerator: void 0,
|
|
787
848
|
// Stateless mode
|
|
788
849
|
enableJsonResponse: true,
|
|
@@ -790,11 +851,13 @@ class MicrosoftGraphServer {
|
|
|
790
851
|
maxRequestBodySize: MAX_REQUEST_BODY_BYTES
|
|
791
852
|
});
|
|
792
853
|
res.on("close", () => {
|
|
793
|
-
transport.close()
|
|
794
|
-
|
|
854
|
+
void transport.close().catch(() => {
|
|
855
|
+
});
|
|
856
|
+
void server.close().catch(() => {
|
|
857
|
+
});
|
|
795
858
|
});
|
|
796
859
|
await server.connect(transport);
|
|
797
|
-
await transport.handleRequest(req, res,
|
|
860
|
+
await transport.handleRequest(req, res, body);
|
|
798
861
|
};
|
|
799
862
|
try {
|
|
800
863
|
if (req.microsoftAuth) {
|
|
@@ -942,12 +1005,19 @@ class MicrosoftGraphServer {
|
|
|
942
1005
|
}
|
|
943
1006
|
}
|
|
944
1007
|
} else {
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
1008
|
+
this.stdioHandle = serveStdio(
|
|
1009
|
+
() => {
|
|
1010
|
+
const server = this.server ?? this.createMcpServer();
|
|
1011
|
+
this.server = null;
|
|
1012
|
+
return server;
|
|
1013
|
+
},
|
|
1014
|
+
{
|
|
1015
|
+
onerror: (error) => {
|
|
1016
|
+
logger.error("Stdio transport error", { error: dumpError(error) });
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
);
|
|
1020
|
+
logger.info("Serving MCP over stdio");
|
|
951
1021
|
}
|
|
952
1022
|
}
|
|
953
1023
|
/**
|
|
@@ -1017,11 +1087,17 @@ class MicrosoftGraphServer {
|
|
|
1017
1087
|
async stop() {
|
|
1018
1088
|
const servers = this.httpServers.splice(0);
|
|
1019
1089
|
configureAttachmentMinting(null);
|
|
1090
|
+
const stdioHandle = this.stdioHandle;
|
|
1091
|
+
this.stdioHandle = null;
|
|
1092
|
+
await stdioHandle?.close();
|
|
1093
|
+
const mcpHandler = this.mcpHandler;
|
|
1094
|
+
this.mcpHandler = null;
|
|
1095
|
+
await mcpHandler?.close();
|
|
1020
1096
|
await Promise.all(
|
|
1021
1097
|
servers.map(
|
|
1022
1098
|
(server) => new Promise((resolve) => {
|
|
1023
1099
|
server.close(() => resolve());
|
|
1024
|
-
server.
|
|
1100
|
+
server.closeAllConnections();
|
|
1025
1101
|
})
|
|
1026
1102
|
)
|
|
1027
1103
|
);
|
|
@@ -444,10 +444,8 @@ async function assertOverwritable(key, cachePath) {
|
|
|
444
444
|
throw new Error(`Refusing to overwrite the unreadable auth cache at ${cachePath}`);
|
|
445
445
|
}
|
|
446
446
|
class DefaultTokenCacheStorage {
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
this.failClosed = false;
|
|
450
|
-
}
|
|
447
|
+
description = "default (encrypted file)";
|
|
448
|
+
failClosed = false;
|
|
451
449
|
async load(key) {
|
|
452
450
|
assertValidKey(key);
|
|
453
451
|
migrateLegacyPaths();
|
|
@@ -508,9 +506,10 @@ class CommandTokenCacheStorage {
|
|
|
508
506
|
this.commandPath = commandPath;
|
|
509
507
|
this.timeoutMs = timeoutMs;
|
|
510
508
|
this.spawnCommand = spawnCommand;
|
|
511
|
-
this.failClosed = true;
|
|
512
509
|
this.description = `command (${path.basename(commandPath)})`;
|
|
513
510
|
}
|
|
511
|
+
description;
|
|
512
|
+
failClosed = true;
|
|
514
513
|
async load(key) {
|
|
515
514
|
assertValidKey(key);
|
|
516
515
|
const result = await this.invoke("load", key);
|
package/docs/deployment.md
CHANGED
|
@@ -18,6 +18,10 @@ MCP Clients (Claude Desktop, Claude Code, Open WebUI, ...)
|
|
|
18
18
|
Microsoft Graph API
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
+
Requires Node.js 20 or newer.
|
|
22
|
+
|
|
23
|
+
`/mcp` serves both protocol eras on the same URL: MCP 2026-07-28 clients (which open with `server/discover`) and 2025-era clients (which open with `initialize`). Nothing needs configuring for either.
|
|
24
|
+
|
|
21
25
|
## Headless stdio auth-cache storage
|
|
22
26
|
|
|
23
27
|
Production HTTP deployments are stateless: normal Graph requests carry a per-user bearer token, including On-Behalf-Of (`--obo`) deployments, and the server does not store MSAL token state for those requests.
|
|
@@ -186,7 +190,7 @@ The list should mirror the redirect URIs registered on your Azure AD app registr
|
|
|
186
190
|
|
|
187
191
|
## Reverse Proxy / Custom Domain
|
|
188
192
|
|
|
189
|
-
When running behind a reverse proxy, set `MS365_MCP_PUBLIC_URL` so that the OAuth
|
|
193
|
+
When running behind a reverse proxy, set `MS365_MCP_PUBLIC_URL` so that the OAuth URLs the server advertises are resolvable from outside the server's network:
|
|
190
194
|
|
|
191
195
|
```bash
|
|
192
196
|
# Via environment variable
|
|
@@ -196,7 +200,11 @@ MS365_MCP_PUBLIC_URL=https://mcp.example.com
|
|
|
196
200
|
--public-url https://mcp.example.com
|
|
197
201
|
```
|
|
198
202
|
|
|
199
|
-
|
|
203
|
+
Every advertised URL (`issuer`, `authorization_endpoint`, `token_endpoint`, `registration_endpoint`, `resource`, `authorization_servers`) uses this URL, path included, so a server hosted under a sub-path works. A client that reaches the server over an internal network (e.g. another container on the same Docker network) must still be able to reach the public URL, since it calls `/token` there.
|
|
204
|
+
|
|
205
|
+
The proxy must pass the `MCP-Protocol-Version`, `Mcp-Method` and `Mcp-Name` request headers through to `/mcp`. MCP 2026-07-28 clients send them on every request, and the server answers `400` when they are missing; 2025-era clients do not need them.
|
|
206
|
+
|
|
207
|
+
Use an `https://` public URL. Newer MCP clients refuse an `http://` token endpoint, so the server logs a warning at startup when the public URL is `http://` on a host other than localhost.
|
|
200
208
|
|
|
201
209
|
## Client Configuration
|
|
202
210
|
|
|
@@ -233,7 +241,7 @@ The client automatically discovers OAuth endpoints and opens a browser for authe
|
|
|
233
241
|
- **Read-only mode**: use `--read-only` to disable all write operations (send, delete, update, create)
|
|
234
242
|
- **Tool filtering**: use `--enabled-tools <regex>`, `--enabled-tools-file <path>` (one regex per line), or `--preset <names>` to restrict available tools
|
|
235
243
|
- **CORS**: configure `MS365_MCP_CORS_ORIGIN` to restrict allowed origins (defaults to `http://localhost:3000`); set explicitly when clients run on a different origin
|
|
236
|
-
- **Client registration**: clients identify themselves with Client ID Metadata Documents (CIMD): the `client_id` is an https URL, the server fetches the document there and only redirects to a `redirect_uri` it lists. This follows the MCP spec; it is not a security boundary, since a `client_id` that is not an https URL skips it and the server always sends its own client ID to Entra, whose reply URLs are what really limit where codes go. The fetch only goes to public addresses, follows no redirects and is capped at 5 KiB and 5 s; documents are cached per their `Cache-Control` (5 minutes by default), and an expired one is still used for up to 24 hours while a refetch fails for a passing reason (unreachable host, timeout, 5xx, 429) or every lookup slot is busy; a final answer (a 404, an invalid document) drops it at once. The fetch connects directly and does not use `HTTPS_PROXY`, so it needs direct outbound HTTPS to
|
|
244
|
+
- **Client registration**: clients identify themselves with Client ID Metadata Documents (CIMD): the `client_id` is an https URL, the server fetches the document there and only redirects to a `redirect_uri` it lists. This follows the MCP spec; it is not a security boundary, since a `client_id` that is not an https URL skips it and the server always sends its own client ID to Entra, whose reply URLs are what really limit where codes go. The fetch only goes to public addresses, follows no redirects and is capped at 5 KiB and 5 s; documents are cached per their `Cache-Control` (5 minutes by default), and an expired one is still used for up to 24 hours while a refetch fails for a passing reason (unreachable host, timeout, 5xx, 429) or every lookup slot is busy; a final answer (a 404, an invalid document) drops it at once. With no usable copy, `/authorize` answers a passing failure with 503 `temporarily_unavailable` and `Retry-After`, and a final one with 400 `invalid_client`. The fetch resolves the client's host over DNS itself, so `/etc/hosts` entries do not apply. It connects directly and does not use `HTTPS_PROXY`, so it needs direct outbound HTTPS to that host (`claude.ai` for Claude). Without that, turn CIMD off with `--no-client-metadata-documents` (or `MS365_MCP_DISABLE_CIMD=true`) and turn DCR on: Claude then falls back to DCR. Dynamic Client Registration is off by default, since the MCP spec deprecated it; `/register` then answers with how to turn it on. Turn it on with `--enable-dynamic-registration` or `MS365_MCP_ENABLE_DCR=true` for DCR-only clients such as Open WebUI; `MS365_MCP_DISABLE_DCR=true` (or `--no-dynamic-registration`) keeps it off regardless. Other `client_id` values (a static one, or one issued by DCR earlier) are accepted at `/authorize` as before
|
|
237
245
|
- **Structured audit log**: enabled by default. Every tool invocation that reaches Microsoft Graph emits one JSON line on stderr (captured by the container platform's log collector) and to `~/.ms-365-mcp-server/logs/audit.log` (mode `0o600`, or under `MS365_MCP_LOG_DIR` when set) with `{ event, request_id, user_principal_name, tool, http_method, http_status?, status, duration_ms, recipient_count?, recipient_domains?, recipient_domains_truncated?, graph_batch_subrequest_count?, graph_batch_http_status_counts?, graph_batch_error_code_counts?, result_count?, result_has_more?, response_bytes?, target_resource?, error_type?, error_code? }`. A few refusals short-circuit before that and emit nothing: a confirm-gate rejection, an `account` param that contradicts the bearer identity, and a failure to resolve an account token. Policy-blocked tool attempts emit `event: "tool.denied"` with `status: "denied"`, `reason` (`allowed_scopes` or `tool_allowlist`), and `missing_scopes` when applicable. When an audited generated Microsoft Graph tool targets a derivable resource through an ID-like path parameter such as `{message-id}` or `{driveItem-id}`, `target_resource` is `{ type, id }`, where `id` is the Graph path up to that resource ID. Later path parameters such as `{path}`, query values, returned content, and Graph response bodies are NEVER recorded, and error messages are reduced to `error_type` / `error_code` so upstream library errors do not leak token fragments or query-string PII. Response _metadata_ is recorded — `result_count`, `result_has_more` and `response_bytes` describe how much came back so that a bulk read is distinguishable from an ordinary one; none of them reveals any of its content. Two things derived from tool parameters **are** recorded, both deliberately. First, `target_resource.id` substitutes ID-like path parameters into the resource path, so a tool on `/users/{user-id}/...` records whatever identifier the caller passed, which may be a full email address. Second, a request whose body carries `toRecipients` / `ccRecipients` / `bccRecipients` / `attendees` / `recipients`, at any casing and several levels down, including inside a `graph-batch` sub-request, records `recipient_count`, the number of entries in those arrays, and `recipient_domains`, the **domain part only** of their addresses and only where it parses as a plain hostname, never the local part and never a subject or message body. An entry that names someone without an address (a `driveRecipient` given as `alias` or `objectId`) counts but contributes no domain. It keys on body shape rather than on the endpoint, so it covers sends, forwards, invites and file shares but equally draft creation and edits, event updates and `findMeetingTimes`, and it reads high rather than low: an attached message's own recipients are counted too. `recipient_domains` holds at most 50 **distinct domains**, alphabetically, and sets `recipient_domains_truncated: true` when there were more; `recipient_count` is unaffected by the cap. All three are absent when the body carries no recipient array at all. A request that fails after reaching Graph still records recipients, since a timeout is not proof of non-delivery. Gaps remain, so absence proves nothing: a draft composed outside this server and sent by id, the original thread's recipients on a reply (Graph resolves those server-side), and a body nesting recipients deeper than the walker descends. This describes the structured audit log only; the operational logger is separate and does log tool parameters. Forms the "who accessed what, when" trail required for GDPR / HIPAA / PIPEDA / SOC 2 audit. Opt-out: `MS365_MCP_AUDIT_LOG=false`
|
|
238
246
|
- **Graph resilience**: every call to Microsoft Graph is wrapped with a fetch timeout (default 100 s via `MS365_MCP_GRAPH_TIMEOUT_MS`), retry-with-backoff on 429 / 503 / 504 / network errors (default 3 retries, full-jitter exponential backoff, honours `Retry-After`; 503 / 504 / network errors only retried for idempotent methods, 429 retried on all methods), and a process-wide circuit breaker that opens after 5 consecutive failures and cools down for 30 s (`MS365_MCP_GRAPH_CIRCUIT_THRESHOLD` / `MS365_MCP_GRAPH_CIRCUIT_COOLDOWN_MS`). Disable the breaker for trusted automation: `MS365_MCP_GRAPH_CIRCUIT_DISABLED=true`
|
|
239
247
|
- **Confirm gate on destructive tools**: opt-in, **off by default**. Enable with `MS365_MCP_REQUIRE_CONFIRM=true`. When on, destructive tools (POST except `readOnly`, PATCH, PUT, DELETE — `delete-mail-message`, `send-mail`, `update-event`, etc.) return `{ "error": "confirmation_required" }` until the caller re-invokes them with `"confirm": true`. Mitigates accidental writes when an LLM misroutes a request or follows an injected instruction. Shipped opt-in so it is a non-breaking, additive layer that can coexist with client-side elicitation prompts (MCP Elicitation API) where the client supports them.
|
package/eslint.config.js
CHANGED
|
@@ -3,6 +3,15 @@ import globals from 'globals';
|
|
|
3
3
|
import tseslint from '@typescript-eslint/eslint-plugin';
|
|
4
4
|
import tsparser from '@typescript-eslint/parser';
|
|
5
5
|
|
|
6
|
+
const SDK_V1 = {
|
|
7
|
+
group: ['@modelcontextprotocol/sdk', '@modelcontextprotocol/sdk/*'],
|
|
8
|
+
message: 'SDK v1 is gone, use the v2 packages.',
|
|
9
|
+
};
|
|
10
|
+
const CLIENT = {
|
|
11
|
+
group: ['@modelcontextprotocol/client', '@modelcontextprotocol/client/*'],
|
|
12
|
+
message: 'The client package is a devDependency, for tests only.',
|
|
13
|
+
};
|
|
14
|
+
|
|
6
15
|
export default [
|
|
7
16
|
js.configs.recommended,
|
|
8
17
|
{
|
|
@@ -28,6 +37,14 @@ export default [
|
|
|
28
37
|
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
|
|
29
38
|
'@typescript-eslint/no-explicit-any': 'warn',
|
|
30
39
|
'no-console': 'off',
|
|
40
|
+
'no-restricted-imports': ['error', { patterns: [SDK_V1] }],
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
// The client package is a devDependency, for tests only
|
|
45
|
+
files: ['src/**/*.ts'],
|
|
46
|
+
rules: {
|
|
47
|
+
'no-restricted-imports': ['error', { patterns: [SDK_V1, CLIENT] }],
|
|
31
48
|
},
|
|
32
49
|
},
|
|
33
50
|
{
|
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.
|
|
4
|
+
"version": "0.191.0",
|
|
5
5
|
"description": " A Model Context Protocol (MCP) server for interacting with Microsoft 365 and Office services through the Graph API",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "dist/index.js",
|
|
@@ -36,7 +36,8 @@
|
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
38
|
"@azure/msal-node": "^7.1.1",
|
|
39
|
-
"@modelcontextprotocol/
|
|
39
|
+
"@modelcontextprotocol/node": "^2.1.2",
|
|
40
|
+
"@modelcontextprotocol/server": "^2.4.0",
|
|
40
41
|
"@toon-format/toon": "^2.3.1",
|
|
41
42
|
"commander": "^11.1.0",
|
|
42
43
|
"dotenv": "^17.0.1",
|
|
@@ -55,6 +56,7 @@
|
|
|
55
56
|
"keytar": "^7.9.0"
|
|
56
57
|
},
|
|
57
58
|
"devDependencies": {
|
|
59
|
+
"@modelcontextprotocol/client": "^2.4.0",
|
|
58
60
|
"@redocly/cli": "^2.11.1",
|
|
59
61
|
"@semantic-release/exec": "^7.1.0",
|
|
60
62
|
"@semantic-release/git": "^10.0.1",
|
|
@@ -75,7 +77,7 @@
|
|
|
75
77
|
"vitest": "^4.1.8"
|
|
76
78
|
},
|
|
77
79
|
"engines": {
|
|
78
|
-
"node": ">=
|
|
80
|
+
"node": ">=20"
|
|
79
81
|
},
|
|
80
82
|
"repository": {
|
|
81
83
|
"type": "git",
|
package/tsup.config.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { defineConfig } from 'tsup';
|
|
|
3
3
|
export default defineConfig({
|
|
4
4
|
entry: ['src/**/*.ts', 'src/endpoints.json', 'src/apps/*.html', 'src/apps/*.js'],
|
|
5
5
|
format: ['esm'],
|
|
6
|
-
target: '
|
|
6
|
+
target: 'es2022',
|
|
7
7
|
outDir: 'dist',
|
|
8
8
|
clean: true,
|
|
9
9
|
bundle: false,
|
|
@@ -21,7 +21,8 @@ export default defineConfig({
|
|
|
21
21
|
noExternal: [],
|
|
22
22
|
external: [
|
|
23
23
|
'@azure/msal-node',
|
|
24
|
-
'@modelcontextprotocol/
|
|
24
|
+
'@modelcontextprotocol/node',
|
|
25
|
+
'@modelcontextprotocol/server',
|
|
25
26
|
'commander',
|
|
26
27
|
'dotenv',
|
|
27
28
|
'express',
|