@softeria/ms-365-mcp-server 0.184.1 → 0.185.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 +11 -5
- package/dist/cli.js +10 -8
- package/dist/lib/client-metadata.js +375 -0
- package/dist/server.js +57 -16
- package/docs/deployment.md +10 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -412,10 +412,10 @@ integration method.
|
|
|
412
412
|
|
|
413
413
|
Open WebUI supports MCP servers via HTTP transport with OAuth 2.1.
|
|
414
414
|
|
|
415
|
-
1. Start the server with HTTP mode:
|
|
415
|
+
1. Start the server with HTTP mode and Dynamic Client Registration on (Open WebUI needs it):
|
|
416
416
|
|
|
417
417
|
```bash
|
|
418
|
-
npx @softeria/ms-365-mcp-server --http
|
|
418
|
+
npx @softeria/ms-365-mcp-server --http --enable-dynamic-registration
|
|
419
419
|
```
|
|
420
420
|
|
|
421
421
|
2. In Open WebUI, go to **Admin Settings → Tools** (`/admin/settings/tools`) → **Add Connection**:
|
|
@@ -425,7 +425,7 @@ Open WebUI supports MCP servers via HTTP transport with OAuth 2.1.
|
|
|
425
425
|
|
|
426
426
|
3. Click **Register Client**.
|
|
427
427
|
|
|
428
|
-
> **Note**:
|
|
428
|
+
> **Note**: In HTTP mode clients identify themselves with [Client ID Metadata Documents](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration#client-id-metadata-documents), which is on by default (`--no-client-metadata-documents` turns it off for servers without direct outbound HTTPS). Dynamic Client Registration is deprecated by the MCP spec and off by default; turn it on with `--enable-dynamic-registration` (or `MS365_MCP_ENABLE_DCR=true`) for clients that only support DCR, such as Open WebUI. If using a custom Azure Entra app, the platform type for your redirect URI depends on whether the app has a client secret: with a secret use "Web", without one use "Mobile and desktop applications" (never "Single-page application").
|
|
429
429
|
|
|
430
430
|
**Quick test setup** using the default Azure app (ID `ms-365` and `localhost:8080` are pre-configured):
|
|
431
431
|
|
|
@@ -435,7 +435,7 @@ docker run -d -p 8080:8080 \
|
|
|
435
435
|
-e OPENAI_API_KEY \
|
|
436
436
|
ghcr.io/open-webui/open-webui:main
|
|
437
437
|
|
|
438
|
-
npx @softeria/ms-365-mcp-server --http
|
|
438
|
+
npx @softeria/ms-365-mcp-server --http --enable-dynamic-registration
|
|
439
439
|
```
|
|
440
440
|
|
|
441
441
|
Then add connection with URL `http://localhost:3000/mcp` and ID `ms-365`.
|
|
@@ -832,7 +832,13 @@ When running as an MCP server, the following options can be used:
|
|
|
832
832
|
--http bound, which with a wildcard --http leaves BOTH ports on every
|
|
833
833
|
interface and so isolates nothing — set this to make the split real
|
|
834
834
|
(requires --attachment-port; see "Splitting the attachment listener")
|
|
835
|
-
--
|
|
835
|
+
--enable-dynamic-registration Turn on OAuth Dynamic Client Registration in HTTP mode (off by default; needed by
|
|
836
|
+
DCR-only clients such as Open WebUI). Equivalent env var: MS365_MCP_ENABLE_DCR=true
|
|
837
|
+
--no-dynamic-registration Keep Dynamic Client Registration off even if it is turned on elsewhere.
|
|
838
|
+
Equivalent env var: MS365_MCP_DISABLE_DCR=true
|
|
839
|
+
--no-client-metadata-documents Turn off Client ID Metadata Documents in HTTP mode, for servers that cannot
|
|
840
|
+
reach the client's host directly; turn on DCR too so Claude can fall back to it.
|
|
841
|
+
Equivalent env var: MS365_MCP_DISABLE_CIMD=true
|
|
836
842
|
--enabled-tools <pattern> Filter tools using regex pattern (e.g., "excel|contact" to enable Excel and Contact tools)
|
|
837
843
|
--enabled-tools-file <path> Filter tools using a file with one regex per line (same as --enabled-tools;
|
|
838
844
|
blank lines and whole-line # comments ignored). Overrides --enabled-tools;
|
package/dist/cli.js
CHANGED
|
@@ -70,10 +70,13 @@ program.name("ms-365-mcp-server").description("Microsoft 365 MCP Server").versio
|
|
|
70
70
|
"Microsoft cloud environment: global (default), china (21Vianet) or gcc-high (US Government GCC High)"
|
|
71
71
|
).option(
|
|
72
72
|
"--enable-dynamic-registration",
|
|
73
|
-
"
|
|
73
|
+
"Turn on OAuth Dynamic Client Registration in HTTP mode (off by default; the MCP spec deprecated it in favour of Client ID Metadata Documents). Needed by clients that only support DCR, such as Open WebUI. Equivalent env var: MS365_MCP_ENABLE_DCR=true."
|
|
74
74
|
).option(
|
|
75
75
|
"--no-dynamic-registration",
|
|
76
|
-
"
|
|
76
|
+
"Keep OAuth Dynamic Client Registration off, even when --enable-dynamic-registration or MS365_MCP_ENABLE_DCR is set. Equivalent env var: MS365_MCP_DISABLE_DCR=true."
|
|
77
|
+
).option(
|
|
78
|
+
"--no-client-metadata-documents",
|
|
79
|
+
"Turn off OAuth Client ID Metadata Documents in HTTP mode: they are no longer advertised, and https client_ids are passed through like any other. For servers that cannot reach the client's host directly (proxy-only or allowlisted egress); Claude then falls back to Dynamic Client Registration, so turn that on too. Equivalent env var: MS365_MCP_DISABLE_CIMD=true."
|
|
77
80
|
).option(
|
|
78
81
|
"--auth-browser",
|
|
79
82
|
"Use browser-based interactive OAuth flow instead of device code for stdio mode. Opens system browser with localhost callback for seamless sign-in."
|
|
@@ -260,12 +263,11 @@ function parseArgs() {
|
|
|
260
263
|
options.toon = true;
|
|
261
264
|
}
|
|
262
265
|
if (options.http) {
|
|
263
|
-
const
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
}
|
|
266
|
+
const envFlag = (name) => process.env[name] === "true" || process.env[name] === "1";
|
|
267
|
+
const forcedOff = options.dynamicRegistration === false || envFlag("MS365_MCP_DISABLE_DCR");
|
|
268
|
+
const turnedOn = options.enableDynamicRegistration === true || envFlag("MS365_MCP_ENABLE_DCR");
|
|
269
|
+
options.enableDynamicRegistration = turnedOn && !forcedOff;
|
|
270
|
+
if (envFlag("MS365_MCP_DISABLE_CIMD")) options.clientMetadataDocuments = false;
|
|
269
271
|
}
|
|
270
272
|
if (process.env.MS365_MCP_OBO === "true" || process.env.MS365_MCP_OBO === "1") {
|
|
271
273
|
options.obo = true;
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
import dns from "node:dns";
|
|
2
|
+
import https from "node:https";
|
|
3
|
+
import net from "node:net";
|
|
4
|
+
import { isLoopbackHost } from "./redirect-uri-validation.js";
|
|
5
|
+
const CIMD_MAX_BYTES = 5 * 1024;
|
|
6
|
+
const CIMD_TIMEOUT_MS = 5e3;
|
|
7
|
+
const CIMD_DEFAULT_TTL_MS = 5 * 6e4;
|
|
8
|
+
const CIMD_MIN_TTL_MS = 6e4;
|
|
9
|
+
const CIMD_MAX_TTL_MS = 24 * 60 * 6e4;
|
|
10
|
+
const CIMD_MAX_CACHE_ENTRIES = 500;
|
|
11
|
+
const CIMD_MAX_IN_FLIGHT = 20;
|
|
12
|
+
class ClientMetadataError extends Error {
|
|
13
|
+
constructor(message, transient = false) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.transient = transient;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function clientIdHost(clientId) {
|
|
19
|
+
try {
|
|
20
|
+
return new URL(clientId).host;
|
|
21
|
+
} catch {
|
|
22
|
+
return void 0;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function looksLikeCimdClientId(clientId) {
|
|
26
|
+
return clientId.toLowerCase().startsWith("https://");
|
|
27
|
+
}
|
|
28
|
+
function parseCimdClientId(clientId) {
|
|
29
|
+
let url;
|
|
30
|
+
try {
|
|
31
|
+
url = new URL(clientId);
|
|
32
|
+
} catch {
|
|
33
|
+
throw new ClientMetadataError("client_id is not a valid URL");
|
|
34
|
+
}
|
|
35
|
+
if (url.protocol !== "https:") throw new ClientMetadataError("client_id must use https");
|
|
36
|
+
if (url.username || url.password) {
|
|
37
|
+
throw new ClientMetadataError("client_id must not contain credentials");
|
|
38
|
+
}
|
|
39
|
+
if (url.hash || clientId.includes("#")) {
|
|
40
|
+
throw new ClientMetadataError("client_id must not contain a fragment");
|
|
41
|
+
}
|
|
42
|
+
if (url.pathname === "/" || url.pathname === "") {
|
|
43
|
+
throw new ClientMetadataError("client_id must contain a path");
|
|
44
|
+
}
|
|
45
|
+
if (url.href !== clientId) {
|
|
46
|
+
throw new ClientMetadataError("client_id must be a normalized URL");
|
|
47
|
+
}
|
|
48
|
+
if (net.isIP(url.hostname.replace(/^\[|\]$/g, "")) && !isPublicAddress(url.hostname)) {
|
|
49
|
+
throw new ClientMetadataError("client_id host is not a public address");
|
|
50
|
+
}
|
|
51
|
+
return url;
|
|
52
|
+
}
|
|
53
|
+
const blockedV4 = new net.BlockList();
|
|
54
|
+
for (const [prefix, bits] of [
|
|
55
|
+
["0.0.0.0", 8],
|
|
56
|
+
["10.0.0.0", 8],
|
|
57
|
+
["100.64.0.0", 10],
|
|
58
|
+
["127.0.0.0", 8],
|
|
59
|
+
["169.254.0.0", 16],
|
|
60
|
+
["172.16.0.0", 12],
|
|
61
|
+
["192.0.0.0", 24],
|
|
62
|
+
["192.0.2.0", 24],
|
|
63
|
+
["192.88.99.0", 24],
|
|
64
|
+
["192.168.0.0", 16],
|
|
65
|
+
["198.18.0.0", 15],
|
|
66
|
+
["198.51.100.0", 24],
|
|
67
|
+
["203.0.113.0", 24],
|
|
68
|
+
["224.0.0.0", 4],
|
|
69
|
+
["240.0.0.0", 4]
|
|
70
|
+
]) {
|
|
71
|
+
blockedV4.addSubnet(prefix, bits, "ipv4");
|
|
72
|
+
}
|
|
73
|
+
const globalV6 = new net.BlockList();
|
|
74
|
+
globalV6.addSubnet("2000::", 3, "ipv6");
|
|
75
|
+
const blockedV6 = new net.BlockList();
|
|
76
|
+
for (const [prefix, bits] of [
|
|
77
|
+
["2001::", 23],
|
|
78
|
+
["2001:db8::", 32],
|
|
79
|
+
["2002::", 16],
|
|
80
|
+
// 6to4
|
|
81
|
+
["3fff::", 20]
|
|
82
|
+
// documentation
|
|
83
|
+
]) {
|
|
84
|
+
blockedV6.addSubnet(prefix, bits, "ipv6");
|
|
85
|
+
}
|
|
86
|
+
function isPublicAddress(address) {
|
|
87
|
+
const ip = address.replace(/^\[|\]$/g, "");
|
|
88
|
+
const family = net.isIP(ip);
|
|
89
|
+
if (family === 4) return !blockedV4.check(ip, "ipv4");
|
|
90
|
+
if (family !== 6) return false;
|
|
91
|
+
const canonical = new URL(`http://[${ip}]/`).hostname.slice(1, -1);
|
|
92
|
+
const mapped = /^(?:::ffff|64:ff9b:):([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(canonical);
|
|
93
|
+
if (mapped) {
|
|
94
|
+
const hi = parseInt(mapped[1], 16);
|
|
95
|
+
const lo = parseInt(mapped[2], 16);
|
|
96
|
+
return isPublicAddress(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`);
|
|
97
|
+
}
|
|
98
|
+
return globalV6.check(canonical, "ipv6") && !blockedV6.check(canonical, "ipv6");
|
|
99
|
+
}
|
|
100
|
+
async function resolvePublic(hostname) {
|
|
101
|
+
if (/(^|\.)localhost\.?$/i.test(hostname)) {
|
|
102
|
+
throw new ClientMetadataError("client_id host does not resolve to a public address");
|
|
103
|
+
}
|
|
104
|
+
const resolver = new dns.promises.Resolver({ timeout: CIMD_TIMEOUT_MS / 2, tries: 1 });
|
|
105
|
+
const [v4, v6] = await Promise.allSettled([
|
|
106
|
+
resolver.resolve4(hostname),
|
|
107
|
+
resolver.resolve6(hostname)
|
|
108
|
+
]);
|
|
109
|
+
const list = [
|
|
110
|
+
...v4.status === "fulfilled" ? v4.value.map((address) => ({ address, family: 4 })) : [],
|
|
111
|
+
...v6.status === "fulfilled" ? v6.value.map((address) => ({ address, family: 6 })) : []
|
|
112
|
+
];
|
|
113
|
+
if (list.length === 0) {
|
|
114
|
+
throw v4.status === "rejected" ? v4.reason : new Error(`no addresses for ${hostname}`);
|
|
115
|
+
}
|
|
116
|
+
return list;
|
|
117
|
+
}
|
|
118
|
+
const publicOnlyLookup = (hostname, options, callback) => {
|
|
119
|
+
resolvePublic(hostname).then(
|
|
120
|
+
(all) => {
|
|
121
|
+
const list = options.family ? all.filter((a) => a.family === options.family) : all;
|
|
122
|
+
if (list.length === 0 || all.some((a) => !isPublicAddress(a.address))) {
|
|
123
|
+
const error = new ClientMetadataError(
|
|
124
|
+
"client_id host does not resolve to a public address"
|
|
125
|
+
);
|
|
126
|
+
callback(error, "", 4);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (options.all) {
|
|
130
|
+
callback(null, list);
|
|
131
|
+
} else {
|
|
132
|
+
callback(null, list[0].address, list[0].family);
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
(err) => callback(err, "", 4)
|
|
136
|
+
);
|
|
137
|
+
};
|
|
138
|
+
const fetchDocument = (url) => new Promise((resolve, reject) => {
|
|
139
|
+
const literal = url.hostname.replace(/^\[|\]$/g, "");
|
|
140
|
+
if (net.isIP(literal) && !isPublicAddress(literal)) {
|
|
141
|
+
reject(new ClientMetadataError("client_id host is not a public address"));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const req = https.get(
|
|
145
|
+
url,
|
|
146
|
+
{
|
|
147
|
+
agent: false,
|
|
148
|
+
lookup: publicOnlyLookup,
|
|
149
|
+
headers: { accept: "application/json" },
|
|
150
|
+
timeout: CIMD_TIMEOUT_MS
|
|
151
|
+
},
|
|
152
|
+
(res) => {
|
|
153
|
+
if (res.statusCode !== 200) {
|
|
154
|
+
clearTimeout(deadline);
|
|
155
|
+
resolve({ status: res.statusCode ?? 0, body: "" });
|
|
156
|
+
req.destroy();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const chunks = [];
|
|
160
|
+
let size = 0;
|
|
161
|
+
let tooLarge = false;
|
|
162
|
+
res.on("data", (chunk) => {
|
|
163
|
+
if (tooLarge) return;
|
|
164
|
+
size += chunk.length;
|
|
165
|
+
if (size > CIMD_MAX_BYTES) {
|
|
166
|
+
tooLarge = true;
|
|
167
|
+
clearTimeout(deadline);
|
|
168
|
+
reject(new ClientMetadataError("client metadata document is too large"));
|
|
169
|
+
req.destroy();
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
chunks.push(chunk);
|
|
173
|
+
});
|
|
174
|
+
res.on("end", () => {
|
|
175
|
+
if (tooLarge) return;
|
|
176
|
+
clearTimeout(deadline);
|
|
177
|
+
resolve({
|
|
178
|
+
status: res.statusCode ?? 0,
|
|
179
|
+
body: Buffer.concat(chunks).toString("utf8"),
|
|
180
|
+
cacheControl: res.headers["cache-control"]
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
res.on("error", (err) => {
|
|
184
|
+
clearTimeout(deadline);
|
|
185
|
+
reject(err);
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
);
|
|
189
|
+
const deadline = setTimeout(
|
|
190
|
+
() => req.destroy(new ClientMetadataError("client metadata fetch timed out", true)),
|
|
191
|
+
CIMD_TIMEOUT_MS
|
|
192
|
+
);
|
|
193
|
+
req.on(
|
|
194
|
+
"timeout",
|
|
195
|
+
() => req.destroy(new ClientMetadataError("client metadata fetch timed out", true))
|
|
196
|
+
);
|
|
197
|
+
req.on("error", (err) => {
|
|
198
|
+
clearTimeout(deadline);
|
|
199
|
+
reject(err);
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
function validateClientMetadata(raw, clientId) {
|
|
203
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
204
|
+
throw new ClientMetadataError("client metadata document is not a JSON object");
|
|
205
|
+
}
|
|
206
|
+
const doc = raw;
|
|
207
|
+
if (doc.client_id !== clientId) {
|
|
208
|
+
throw new ClientMetadataError("client metadata client_id does not match the URL");
|
|
209
|
+
}
|
|
210
|
+
if (typeof doc.client_name !== "string" || doc.client_name.trim() === "") {
|
|
211
|
+
throw new ClientMetadataError("client metadata is missing client_name");
|
|
212
|
+
}
|
|
213
|
+
if (!Array.isArray(doc.redirect_uris) || doc.redirect_uris.length === 0 || !doc.redirect_uris.every((u) => typeof u === "string")) {
|
|
214
|
+
throw new ClientMetadataError("client metadata is missing redirect_uris");
|
|
215
|
+
}
|
|
216
|
+
if (doc.token_endpoint_auth_method !== void 0 && doc.token_endpoint_auth_method !== "none") {
|
|
217
|
+
throw new ClientMetadataError("client metadata token_endpoint_auth_method must be none");
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
client_id: clientId,
|
|
221
|
+
client_name: doc.client_name,
|
|
222
|
+
redirect_uris: doc.redirect_uris
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function cacheTtlMs(cacheControl) {
|
|
226
|
+
if (!cacheControl) return CIMD_DEFAULT_TTL_MS;
|
|
227
|
+
const directives = cacheControl.toLowerCase();
|
|
228
|
+
if (/(^|[\s,])(no-store|no-cache)\b/.test(directives)) return 0;
|
|
229
|
+
const maxAge = /(^|[\s,])max-age="?(\d+)"?/.exec(directives);
|
|
230
|
+
if (!maxAge) return CIMD_DEFAULT_TTL_MS;
|
|
231
|
+
const ms = Number(maxAge[2]) * 1e3;
|
|
232
|
+
if (ms === 0) return 0;
|
|
233
|
+
return Math.min(CIMD_MAX_TTL_MS, Math.max(CIMD_MIN_TTL_MS, ms));
|
|
234
|
+
}
|
|
235
|
+
function redirectUriMatches(requested, registered) {
|
|
236
|
+
if (registered.includes(requested)) return true;
|
|
237
|
+
let req;
|
|
238
|
+
try {
|
|
239
|
+
req = new URL(requested);
|
|
240
|
+
} catch {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
if (req.protocol !== "http:" || !isLoopbackHost(req.hostname)) return false;
|
|
244
|
+
return registered.some((candidate) => {
|
|
245
|
+
let reg;
|
|
246
|
+
try {
|
|
247
|
+
reg = new URL(candidate);
|
|
248
|
+
} catch {
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
if (reg.protocol !== "http:" || !isLoopbackHost(reg.hostname)) return false;
|
|
252
|
+
reg.port = req.port;
|
|
253
|
+
return reg.href === requested;
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
const CIMD_MAX_STALE_MS = 24 * 60 * 6e4;
|
|
257
|
+
class ClientMetadataResolver {
|
|
258
|
+
constructor(options = {}) {
|
|
259
|
+
this.cache = /* @__PURE__ */ new Map();
|
|
260
|
+
this.inFlight = /* @__PURE__ */ new Map();
|
|
261
|
+
this.fetcher = options.fetcher ?? fetchDocument;
|
|
262
|
+
this.now = options.now ?? Date.now;
|
|
263
|
+
}
|
|
264
|
+
async resolve(clientId) {
|
|
265
|
+
const url = parseCimdClientId(clientId);
|
|
266
|
+
const cached = this.cache.get(clientId);
|
|
267
|
+
if (cached) {
|
|
268
|
+
this.cache.delete(clientId);
|
|
269
|
+
this.cache.set(clientId, cached);
|
|
270
|
+
if (cached.expiresAt > this.now()) return cached.metadata;
|
|
271
|
+
}
|
|
272
|
+
const stale = cached && cached.expiresAt + CIMD_MAX_STALE_MS > this.now() ? cached.metadata : void 0;
|
|
273
|
+
let pending = this.inFlight.get(clientId);
|
|
274
|
+
if (!pending) {
|
|
275
|
+
if (this.inFlight.size >= CIMD_MAX_IN_FLIGHT) {
|
|
276
|
+
if (stale) return stale;
|
|
277
|
+
throw new ClientMetadataError("too many client metadata lookups in progress, try again");
|
|
278
|
+
}
|
|
279
|
+
pending = this.load(url, clientId).finally(() => this.inFlight.delete(clientId));
|
|
280
|
+
this.inFlight.set(clientId, pending);
|
|
281
|
+
}
|
|
282
|
+
if (!stale) return pending;
|
|
283
|
+
return pending.catch((err) => {
|
|
284
|
+
if (err instanceof ClientMetadataError && err.transient) return stale;
|
|
285
|
+
throw err;
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
async load(url, clientId) {
|
|
289
|
+
try {
|
|
290
|
+
return await this.fetchAndCache(url, clientId);
|
|
291
|
+
} catch (err) {
|
|
292
|
+
if (!(err instanceof ClientMetadataError && err.transient)) this.cache.delete(clientId);
|
|
293
|
+
throw err;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
async fetchAndCache(url, clientId) {
|
|
297
|
+
let fetched;
|
|
298
|
+
try {
|
|
299
|
+
fetched = await this.fetcher(url);
|
|
300
|
+
} catch (err) {
|
|
301
|
+
if (err instanceof ClientMetadataError) throw err;
|
|
302
|
+
throw new ClientMetadataError("client metadata document could not be fetched", true);
|
|
303
|
+
}
|
|
304
|
+
if (fetched.status !== 200) {
|
|
305
|
+
throw new ClientMetadataError(
|
|
306
|
+
"client metadata document could not be fetched (it must answer 200; redirects are not followed)",
|
|
307
|
+
fetched.status >= 500 || fetched.status === 429
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
let raw;
|
|
311
|
+
try {
|
|
312
|
+
raw = JSON.parse(fetched.body);
|
|
313
|
+
} catch {
|
|
314
|
+
throw new ClientMetadataError("client metadata document is not valid JSON");
|
|
315
|
+
}
|
|
316
|
+
const metadata = validateClientMetadata(raw, clientId);
|
|
317
|
+
const ttl = cacheTtlMs(fetched.cacheControl);
|
|
318
|
+
this.cache.delete(clientId);
|
|
319
|
+
if (ttl > 0) {
|
|
320
|
+
while (this.cache.size >= CIMD_MAX_CACHE_ENTRIES) {
|
|
321
|
+
const oldest = this.cache.keys().next().value;
|
|
322
|
+
if (oldest === void 0) break;
|
|
323
|
+
this.cache.delete(oldest);
|
|
324
|
+
}
|
|
325
|
+
this.cache.set(clientId, { metadata, expiresAt: this.now() + ttl });
|
|
326
|
+
}
|
|
327
|
+
return metadata;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const DCR_DISABLED_HINT = "Dynamic Client Registration is off on this server. Use a client that supports Client ID Metadata Documents, or start the server with --enable-dynamic-registration (or MS365_MCP_ENABLE_DCR=true).";
|
|
331
|
+
async function checkAuthorizeClient(params) {
|
|
332
|
+
const { clientId, redirectUri, resolver } = params;
|
|
333
|
+
if (!clientId || !looksLikeCimdClientId(clientId)) return { ok: true };
|
|
334
|
+
if (!redirectUri) {
|
|
335
|
+
return { ok: false, error: "invalid_request", description: "redirect_uri is required" };
|
|
336
|
+
}
|
|
337
|
+
let metadata;
|
|
338
|
+
try {
|
|
339
|
+
metadata = await resolver.resolve(clientId);
|
|
340
|
+
} catch (err) {
|
|
341
|
+
const reason = err instanceof ClientMetadataError ? err.message : "client metadata error";
|
|
342
|
+
return { ok: false, error: "invalid_client", description: reason };
|
|
343
|
+
}
|
|
344
|
+
if (!redirectUriMatches(redirectUri, metadata.redirect_uris)) {
|
|
345
|
+
return {
|
|
346
|
+
ok: false,
|
|
347
|
+
error: "invalid_request",
|
|
348
|
+
description: "redirect_uri is not listed in the client metadata document"
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
return { ok: true, clientName: metadata.client_name };
|
|
352
|
+
}
|
|
353
|
+
export {
|
|
354
|
+
CIMD_DEFAULT_TTL_MS,
|
|
355
|
+
CIMD_MAX_BYTES,
|
|
356
|
+
CIMD_MAX_CACHE_ENTRIES,
|
|
357
|
+
CIMD_MAX_IN_FLIGHT,
|
|
358
|
+
CIMD_MAX_STALE_MS,
|
|
359
|
+
CIMD_MAX_TTL_MS,
|
|
360
|
+
CIMD_MIN_TTL_MS,
|
|
361
|
+
CIMD_TIMEOUT_MS,
|
|
362
|
+
ClientMetadataError,
|
|
363
|
+
ClientMetadataResolver,
|
|
364
|
+
DCR_DISABLED_HINT,
|
|
365
|
+
cacheTtlMs,
|
|
366
|
+
checkAuthorizeClient,
|
|
367
|
+
clientIdHost,
|
|
368
|
+
fetchDocument,
|
|
369
|
+
isPublicAddress,
|
|
370
|
+
looksLikeCimdClientId,
|
|
371
|
+
parseCimdClientId,
|
|
372
|
+
publicOnlyLookup,
|
|
373
|
+
redirectUriMatches,
|
|
374
|
+
validateClientMetadata
|
|
375
|
+
};
|
package/dist/server.js
CHANGED
|
@@ -38,6 +38,12 @@ import {
|
|
|
38
38
|
credentialCheckMessage
|
|
39
39
|
} from "./lib/microsoft-auth.js";
|
|
40
40
|
import { isAllowedRedirectUri, parseAllowlist } from "./lib/redirect-uri-validation.js";
|
|
41
|
+
import {
|
|
42
|
+
checkAuthorizeClient,
|
|
43
|
+
clientIdHost,
|
|
44
|
+
ClientMetadataResolver,
|
|
45
|
+
DCR_DISABLED_HINT
|
|
46
|
+
} from "./lib/client-metadata.js";
|
|
41
47
|
import logger, { enableConsoleLogging } from "./logger.js";
|
|
42
48
|
import { version } from "./version.js";
|
|
43
49
|
import { buildMcpServerInstructions } from "./mcp-instructions.js";
|
|
@@ -394,8 +400,9 @@ class MicrosoftGraphServer {
|
|
|
394
400
|
hsts: { maxAge: 31536e3, includeSubDomains: true, preload: true }
|
|
395
401
|
})
|
|
396
402
|
);
|
|
397
|
-
|
|
398
|
-
app.use(express.
|
|
403
|
+
const unlessAttachmentRoute = (parser) => (req, res, next) => req.path.toLowerCase().replace(/\/$/, "") === ATTACHMENT_ROUTE ? next() : parser(req, res, next);
|
|
404
|
+
app.use(unlessAttachmentRoute(express.json({ limit: MAX_REQUEST_BODY_BYTES })));
|
|
405
|
+
app.use(unlessAttachmentRoute(express.urlencoded({ extended: true })));
|
|
399
406
|
const corsOrigin = process.env.MS365_MCP_CORS_ORIGIN || "http://localhost:3000";
|
|
400
407
|
app.use((req, res, next) => {
|
|
401
408
|
res.header("Access-Control-Allow-Origin", corsOrigin);
|
|
@@ -432,6 +439,7 @@ class MicrosoftGraphServer {
|
|
|
432
439
|
const oauthProvider = new MicrosoftOAuthProvider(this.authManager, this.secrets);
|
|
433
440
|
const publicUrlRaw = this.options.publicUrl || process.env.MS365_MCP_PUBLIC_URL || this.options.baseUrl || process.env.MS365_MCP_BASE_URL || null;
|
|
434
441
|
const publicBase = publicUrlRaw ? new URL(publicUrlRaw).href.replace(/\/$/, "") : null;
|
|
442
|
+
const cimdEnabled = this.options.clientMetadataDocuments !== false;
|
|
435
443
|
app.get("/.well-known/oauth-authorization-server", async (req, res) => {
|
|
436
444
|
const protocol = req.secure ? "https" : "http";
|
|
437
445
|
const requestOrigin = `${protocol}://${req.get("host")}`;
|
|
@@ -451,6 +459,7 @@ class MicrosoftGraphServer {
|
|
|
451
459
|
if (this.options.enableDynamicRegistration) {
|
|
452
460
|
metadata.registration_endpoint = `${browserBase}/register`;
|
|
453
461
|
}
|
|
462
|
+
if (cimdEnabled) metadata.client_id_metadata_document_supported = true;
|
|
454
463
|
res.json(metadata);
|
|
455
464
|
});
|
|
456
465
|
const protectedResourcesHandler = async (req, res) => {
|
|
@@ -468,22 +477,31 @@ class MicrosoftGraphServer {
|
|
|
468
477
|
};
|
|
469
478
|
app.get("/.well-known/oauth-protected-resource", protectedResourcesHandler);
|
|
470
479
|
app.get("/.well-known/oauth-protected-resource/*path", protectedResourcesHandler);
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
res.status(
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
redirect_uris: body.redirect_uris || [],
|
|
480
|
-
grant_types: body.grant_types || ["authorization_code", "refresh_token"],
|
|
481
|
-
response_types: body.response_types || ["code"],
|
|
482
|
-
token_endpoint_auth_method: body.token_endpoint_auth_method || "none",
|
|
483
|
-
client_name: body.client_name || "MCP Client"
|
|
480
|
+
app.post("/register", async (req, res) => {
|
|
481
|
+
if (!this.options.enableDynamicRegistration) {
|
|
482
|
+
logger.warn(
|
|
483
|
+
`Client tried Dynamic Client Registration while it is off. ${DCR_DISABLED_HINT}`
|
|
484
|
+
);
|
|
485
|
+
res.status(400).json({
|
|
486
|
+
error: "invalid_client_metadata",
|
|
487
|
+
error_description: DCR_DISABLED_HINT
|
|
484
488
|
});
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
const body = req.body ?? {};
|
|
492
|
+
logger.info("Client registration request", { keys: Object.keys(body) });
|
|
493
|
+
const clientId = `mcp-client-${Date.now()}`;
|
|
494
|
+
res.status(201).json({
|
|
495
|
+
client_id: clientId,
|
|
496
|
+
client_id_issued_at: Math.floor(Date.now() / 1e3),
|
|
497
|
+
redirect_uris: body.redirect_uris || [],
|
|
498
|
+
grant_types: body.grant_types || ["authorization_code", "refresh_token"],
|
|
499
|
+
response_types: body.response_types || ["code"],
|
|
500
|
+
token_endpoint_auth_method: body.token_endpoint_auth_method || "none",
|
|
501
|
+
client_name: body.client_name || "MCP Client"
|
|
485
502
|
});
|
|
486
|
-
}
|
|
503
|
+
});
|
|
504
|
+
const clientMetadataResolver = new ClientMetadataResolver();
|
|
487
505
|
app.get("/authorize", async (req, res) => {
|
|
488
506
|
const url = new URL(req.url, `${req.protocol}://${req.get("host")}`);
|
|
489
507
|
const tenantId = this.secrets?.tenantId || "common";
|
|
@@ -509,6 +527,29 @@ class MicrosoftGraphServer {
|
|
|
509
527
|
return;
|
|
510
528
|
}
|
|
511
529
|
}
|
|
530
|
+
const requestedClientId = url.searchParams.get("client_id");
|
|
531
|
+
const clientCheck = cimdEnabled ? await checkAuthorizeClient({
|
|
532
|
+
clientId: requestedClientId,
|
|
533
|
+
redirectUri: redirectUriParam,
|
|
534
|
+
resolver: clientMetadataResolver
|
|
535
|
+
}) : { ok: true };
|
|
536
|
+
if (!clientCheck.ok) {
|
|
537
|
+
logger.warn("Rejected /authorize request for CIMD client", {
|
|
538
|
+
client_id_host: requestedClientId ? clientIdHost(requestedClientId) : void 0,
|
|
539
|
+
error: clientCheck.error,
|
|
540
|
+
reason: clientCheck.description
|
|
541
|
+
});
|
|
542
|
+
res.status(400).json({
|
|
543
|
+
error: clientCheck.error,
|
|
544
|
+
error_description: clientCheck.description
|
|
545
|
+
});
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (clientCheck.clientName) {
|
|
549
|
+
logger.info("Authorize for CIMD client", {
|
|
550
|
+
client_name: clientCheck.clientName.slice(0, 100)
|
|
551
|
+
});
|
|
552
|
+
}
|
|
512
553
|
const allowedParams = [
|
|
513
554
|
"response_type",
|
|
514
555
|
"redirect_uri",
|
package/docs/deployment.md
CHANGED
|
@@ -233,19 +233,19 @@ The client automatically discovers OAuth endpoints and opens a browser for authe
|
|
|
233
233
|
- **Read-only mode**: use `--read-only` to disable all write operations (send, delete, update, create)
|
|
234
234
|
- **Tool filtering**: use `--enabled-tools <regex>`, `--enabled-tools-file <path>` (one regex per line), or `--preset <names>` to restrict available tools
|
|
235
235
|
- **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
|
-
- **
|
|
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 the client's 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
237
|
- **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
238
|
- **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
239
|
- **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.
|
|
240
240
|
|
|
241
241
|
## Exposed Endpoints
|
|
242
242
|
|
|
243
|
-
| Path | Method | Description
|
|
244
|
-
| ----------------------------------------- | -------- |
|
|
245
|
-
| `/` | GET | Health check
|
|
246
|
-
| `/mcp` | GET/POST | MCP protocol endpoint
|
|
247
|
-
| `/authorize` | GET | OAuth — redirect to Microsoft
|
|
248
|
-
| `/token` | POST | OAuth — code exchange / refresh
|
|
249
|
-
| `/register` | POST | OAuth — dynamic registration
|
|
250
|
-
| `/.well-known/oauth-authorization-server` | GET | OAuth server metadata
|
|
251
|
-
| `/.well-known/oauth-protected-resource` | GET | Protected resource metadata
|
|
243
|
+
| Path | Method | Description | Auth Required |
|
|
244
|
+
| ----------------------------------------- | -------- | ------------------------------------- | ------------- |
|
|
245
|
+
| `/` | GET | Health check | No |
|
|
246
|
+
| `/mcp` | GET/POST | MCP protocol endpoint | Bearer token |
|
|
247
|
+
| `/authorize` | GET | OAuth — redirect to Microsoft | No |
|
|
248
|
+
| `/token` | POST | OAuth — code exchange / refresh | No |
|
|
249
|
+
| `/register` | POST | OAuth — dynamic registration (opt-in) | No |
|
|
250
|
+
| `/.well-known/oauth-authorization-server` | GET | OAuth server metadata | No |
|
|
251
|
+
| `/.well-known/oauth-protected-resource` | GET | Protected resource metadata | No |
|
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.185.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",
|