@softeria/ms-365-mcp-server 0.176.0 → 0.177.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 +41 -0
- package/SECURITY.md +9 -0
- package/bin/modules/generate-mcp-tools.mjs +24 -1
- package/dist/__tests__/graph-tools.test.js +4 -4
- package/dist/app-mode.js +137 -0
- package/dist/auth.js +66 -12
- package/dist/cli.js +10 -1
- package/dist/endpoints.json +250 -41
- package/dist/generated/client-beta.js +50 -50
- package/dist/generated/client.js +503 -503
- package/dist/graph-client.js +8 -2
- package/dist/graph-tools.js +66 -49
- package/dist/index.js +18 -3
- package/dist/lib/tool-schema.js +39 -12
- package/dist/mcp-instructions.js +4 -0
- package/dist/normalize-tool-schema.js +170 -1
- package/dist/server.js +3 -1
- package/package.json +2 -3
- package/src/endpoints.json +250 -41
package/README.md
CHANGED
|
@@ -570,6 +570,43 @@ This method:
|
|
|
570
570
|
- Use your pre-existing OAuth token for Microsoft Graph API requests
|
|
571
571
|
- Does not handle token refresh (token lifecycle management is your responsibility)
|
|
572
572
|
|
|
573
|
+
#### 4. App Mode (application permissions, no signed-in user)
|
|
574
|
+
|
|
575
|
+
> **Warning**: application permissions apply to the whole tenant. `Mail.Read` granted to the app reads every
|
|
576
|
+
> mailbox, `Files.ReadWrite.All` writes every OneDrive and site, and whoever can call this server acts with
|
|
577
|
+
> them. Grant the fewest permissions you can. To limit which mailboxes and calendars it reaches, grant the
|
|
578
|
+
> mail and calendar permissions with
|
|
579
|
+
> [RBAC for Applications in Exchange Online](https://learn.microsoft.com/en-us/exchange/permissions-exo/application-rbac)
|
|
580
|
+
> **instead of** in Microsoft Entra: the two add up, so an Entra `Mail.Read` grant left in place still reaches
|
|
581
|
+
> every mailbox. SharePoint sites can be narrowed with `Sites.Selected`.
|
|
582
|
+
|
|
583
|
+
For unattended agents that act as the app registration itself (client credentials):
|
|
584
|
+
|
|
585
|
+
```bash
|
|
586
|
+
MS365_MCP_CLIENT_ID=<your app id> \
|
|
587
|
+
MS365_MCP_TENANT_ID=<your tenant id or domain> \
|
|
588
|
+
MS365_MCP_CLIENT_SECRET=<secret> \
|
|
589
|
+
npx @softeria/ms-365-mcp-server --app-mode --read-only
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
- Use your own app registration with **application** permissions and admin consent. Use either
|
|
593
|
+
`MS365_MCP_CLIENT_SECRET` or `MS365_MCP_CLIENT_CERTIFICATE_PATH` (a PEM file with the certificate and its
|
|
594
|
+
unencrypted private key), not both. `MS365_MCP_TENANT_ID` must be a real tenant, not `common`.
|
|
595
|
+
- Tokens come from client credentials and are renewed automatically. Nothing is cached on disk.
|
|
596
|
+
- Only tools that work with application permissions are offered: the `/users/{user-id}` mail and calendar
|
|
597
|
+
tools (pass a UPN or object id as `user-id`), users and groups, OneDrive/SharePoint drives and lists, Planner,
|
|
598
|
+
Teams reads, presence, places and subscriptions. `/me` tools, Excel, OneNote and sending Teams chat or channel
|
|
599
|
+
messages are not available, because Graph does not support them with application permissions.
|
|
600
|
+
- `--list-permissions --app-mode` lists the application permissions the offered tools use. `--allowed-scopes`,
|
|
601
|
+
`--enabled-tools`, `--preset` and `--read-only` narrow the surface as usual.
|
|
602
|
+
- `--verify-login --app-mode` gets a token and shows the app id, tenant and granted roles (Exchange RBAC
|
|
603
|
+
grants do not show up there).
|
|
604
|
+
- The `mail`, `calendar` and `outlook` presets are built from `/me` tools and leave little in app mode; the
|
|
605
|
+
`/users/{user-id}` mail and calendar tools are in `work`.
|
|
606
|
+
- stdio only. It refuses `--http`, `--obo`, `--extra-scopes`, `MS365_MCP_OAUTH_TOKEN` and the
|
|
607
|
+
login/account options.
|
|
608
|
+
- Webinar tools also need an application access policy assigned to the organizer.
|
|
609
|
+
|
|
573
610
|
> **Note**: HTTP mode requires authentication. For unauthenticated testing, use stdio mode with device code flow.
|
|
574
611
|
>
|
|
575
612
|
> **Authentication Tools**: In HTTP mode, login/logout tools are disabled by default since OAuth handles authentication.
|
|
@@ -745,6 +782,8 @@ When running as an MCP server, the following options can be used:
|
|
|
745
782
|
which reads files from those directories.
|
|
746
783
|
Refused unless --http binds a loopback host with no --public-url and no
|
|
747
784
|
--trust-proxy-auth
|
|
785
|
+
--app-mode Use application permissions (client credentials) with no signed-in user. stdio only
|
|
786
|
+
(see "App Mode" under Authentication)
|
|
748
787
|
--enable-auth-tools Enable login/logout tools when using HTTP mode (disabled by default in HTTP mode)
|
|
749
788
|
--enable-attachment-urls Let get-download-url mint a server-served URL for byte resources Graph
|
|
750
789
|
exposes no pre-authenticated URL for (see "Server-Minted Attachment URLs").
|
|
@@ -777,6 +816,8 @@ Environment variables:
|
|
|
777
816
|
- `ENABLED_TOOLS_FILE`: Path to a file with one regex per line (alternative to --enabled-tools-file). Blank lines and whole-line `#` comments are dropped, then lines are joined with `|` (same as `ENABLED_TOOLS=line1|line2|…`). Layering (later wins): `--enabled-tools` → `--enabled-tools-file` → `--preset` → `ENABLED_TOOLS` → `ENABLED_TOOLS_FILE`
|
|
778
817
|
- `MS365_MCP_ORG_MODE=true|1`: Enable organization/work mode (alternative to --org-mode flag)
|
|
779
818
|
- `MS365_MCP_FORCE_WORK_SCOPES=true|1`: Backwards compatibility for MS365_MCP_ORG_MODE
|
|
819
|
+
- `MS365_MCP_APP_MODE=true|1`: Enable app mode (alternative to --app-mode flag)
|
|
820
|
+
- `MS365_MCP_CLIENT_CERTIFICATE_PATH=<path>`: PEM file with a certificate and its unencrypted private key, used instead of `MS365_MCP_CLIENT_SECRET` in app mode
|
|
780
821
|
- `MS365_MCP_OUTPUT_FORMAT=toon`: Enable TOON output format (alternative to --toon flag)
|
|
781
822
|
- `MS365_MCP_MAX_TOP=<n>`: Hard cap for Graph `$top` / `top` on list requests (positive integer). When the model passes a larger value, the server clamps it to `n` so responses stay smaller. Example: `MS365_MCP_MAX_TOP=15`
|
|
782
823
|
- `MS365_MCP_MAX_PAGES=<n>`: Maximum number of pages followed when a tool is called with `fetchAllPages: true` (positive integer, default `100`). Bounds memory and latency for large result sets.
|
package/SECURITY.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Security Policy
|
|
2
2
|
|
|
3
|
+
## Security Maintainer
|
|
4
|
+
|
|
5
|
+
Security for this project is handled by
|
|
6
|
+
[Eirik Brandtzæg](https://github.com/eirikb) (eirikb@eirikb.no), the
|
|
7
|
+
project's main developer. He triages reports, fixes them and publishes the
|
|
8
|
+
advisories.
|
|
9
|
+
|
|
10
|
+
Published advisories: [Security Advisories](https://github.com/Softeria/ms-365-mcp-server/security/advisories)
|
|
11
|
+
|
|
3
12
|
## Reporting a Vulnerability
|
|
4
13
|
|
|
5
14
|
If you discover a security vulnerability in this project, please report it
|
|
@@ -13,6 +13,29 @@ export function fixFunctionStylePaths(clientCode) {
|
|
|
13
13
|
return clientCode.replace(/(path:\s*)'(\/[^']*\([^)]*=':[\w]+'[^)]*\)[^']*)'/g, '$1`$2`');
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* openapi-zod-client emits zod 3 code. Rewrites the parts zod 4 rejects or treats differently:
|
|
18
|
+
* - `.strict()` and `.passthrough()` become `.loose()`, so unknown Graph properties pass
|
|
19
|
+
* through (#248).
|
|
20
|
+
* - one-argument `z.record(x)` gets the string key schema zod 4 requires.
|
|
21
|
+
* - `.uuid()` becomes `.guid()`; zod 4's `.uuid()` checks RFC variant bits that Microsoft
|
|
22
|
+
* ids such as skuId do not always have.
|
|
23
|
+
* - `.default(x)` becomes `.meta({ default: x })`. Every default sits in an optional field,
|
|
24
|
+
* where zod 3 left a missing value missing and zod 4 fills it in - SaveToSentItems: false
|
|
25
|
+
* on every send-mail. The JSON Schema still shows the default.
|
|
26
|
+
*/
|
|
27
|
+
export function toZod4(clientCode) {
|
|
28
|
+
const code = clientCode
|
|
29
|
+
.replace(/\.(strict|passthrough)\(\)/g, '.loose()')
|
|
30
|
+
.replace(/z\.record\((?!z\.string\(\),)/g, 'z.record(z.string(), ')
|
|
31
|
+
.replace(/\.uuid\(\)/g, '.guid()')
|
|
32
|
+
.replace(/\.default\(([^()]*)\)/g, '.meta({ default: $1 })');
|
|
33
|
+
// A default the rewrite missed would quietly be sent to Graph again
|
|
34
|
+
const missed = code.match(/\.default\(.*/);
|
|
35
|
+
if (missed) throw new Error(`toZod4 could not rewrite ${missed[0].slice(0, 80)}`);
|
|
36
|
+
return code;
|
|
37
|
+
}
|
|
38
|
+
|
|
16
39
|
export function generateMcpTools(openapiTrimmedFile, clientFilePath) {
|
|
17
40
|
try {
|
|
18
41
|
console.log(
|
|
@@ -37,7 +60,7 @@ export function generateMcpTools(openapiTrimmedFile, clientFilePath) {
|
|
|
37
60
|
let clientCode = fs.readFileSync(clientFilePath, 'utf-8');
|
|
38
61
|
clientCode = clientCode.replace(/'@zodios\/core';/, "'./hack.js';");
|
|
39
62
|
|
|
40
|
-
clientCode = clientCode
|
|
63
|
+
clientCode = toZod4(clientCode);
|
|
41
64
|
|
|
42
65
|
console.log('Stripping unused errors arrays from endpoint definitions...');
|
|
43
66
|
// I didn't make up this crazy regex myself; you know who did. It seems works though.
|
|
@@ -285,7 +285,7 @@ describe("graph-tools", () => {
|
|
|
285
285
|
method: "post",
|
|
286
286
|
path: "/$batch",
|
|
287
287
|
alias: "graph-batch",
|
|
288
|
-
parameters: [{ name: "body", type: "Body", schema: z.object({}).
|
|
288
|
+
parameters: [{ name: "body", type: "Body", schema: z.object({}).loose() }]
|
|
289
289
|
});
|
|
290
290
|
const config = makeConfig({
|
|
291
291
|
pathPattern: "/$batch",
|
|
@@ -572,7 +572,7 @@ describe("graph-tools", () => {
|
|
|
572
572
|
method: "post",
|
|
573
573
|
path: "/me/messages",
|
|
574
574
|
alias: "create-draft-email",
|
|
575
|
-
parameters: [{ name: "body", type: "Body", schema: z.object({}).
|
|
575
|
+
parameters: [{ name: "body", type: "Body", schema: z.object({}).loose() }]
|
|
576
576
|
});
|
|
577
577
|
const config = makeConfig({
|
|
578
578
|
pathPattern: "/me/messages",
|
|
@@ -695,7 +695,7 @@ describe("graph-tools", () => {
|
|
|
695
695
|
{
|
|
696
696
|
name: "body",
|
|
697
697
|
type: "Body",
|
|
698
|
-
schema: z.object({ message: z.object({}).
|
|
698
|
+
schema: z.object({ message: z.object({}).loose() })
|
|
699
699
|
}
|
|
700
700
|
]
|
|
701
701
|
})
|
|
@@ -4300,7 +4300,7 @@ describe("graph-tools", () => {
|
|
|
4300
4300
|
alias,
|
|
4301
4301
|
method,
|
|
4302
4302
|
path: "/chats/{chat-id}/messages",
|
|
4303
|
-
parameters: [{ name: "body", type: "Body", schema: z.object({}).
|
|
4303
|
+
parameters: [{ name: "body", type: "Body", schema: z.object({}).loose() }]
|
|
4304
4304
|
})
|
|
4305
4305
|
);
|
|
4306
4306
|
mockEndpointsJson = [
|
package/dist/app-mode.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { ConfidentialClientApplication } from "@azure/msal-node";
|
|
2
|
+
import { X509Certificate } from "crypto";
|
|
3
|
+
import { readFileSync } from "fs";
|
|
4
|
+
import logger from "./logger.js";
|
|
5
|
+
import { getCloudEndpoints, getDefaultClientId } from "./cloud-config.js";
|
|
6
|
+
const APP_MODE_WARNING = "Warning: app mode (--app-mode) uses application permissions with no signed-in user. Whatever the app registration is granted applies to the whole tenant (every mailbox, calendar, site), and anyone who can call this server acts with it. Grant the fewest permissions you can, and scope mailbox access with RBAC for Applications in Exchange Online.";
|
|
7
|
+
const NON_TENANT_AUTHORITIES = /* @__PURE__ */ new Set(["common", "organizations", "consumers"]);
|
|
8
|
+
const LOCAL_ACCOUNT_FLAGS = [
|
|
9
|
+
["login", "--login"],
|
|
10
|
+
["logout", "--logout"],
|
|
11
|
+
["listAccounts", "--list-accounts"],
|
|
12
|
+
["selectAccount", "--select-account"],
|
|
13
|
+
["removeAccount", "--remove-account"],
|
|
14
|
+
["authBrowser", "--auth-browser"],
|
|
15
|
+
["expectedUsername", "--expected-username"],
|
|
16
|
+
["expectedHomeAccountId", "--expected-home-account-id"]
|
|
17
|
+
];
|
|
18
|
+
function assertAppModeOptions(options) {
|
|
19
|
+
const conflicts = [];
|
|
20
|
+
if (options.http) conflicts.push("--http");
|
|
21
|
+
if (options.obo) conflicts.push("--obo");
|
|
22
|
+
if (options.trustProxyAuth) conflicts.push("--trust-proxy-auth");
|
|
23
|
+
if (options.extraScopes !== void 0) conflicts.push("--extra-scopes");
|
|
24
|
+
for (const [key, flag] of LOCAL_ACCOUNT_FLAGS) {
|
|
25
|
+
if (options[key]) conflicts.push(flag);
|
|
26
|
+
}
|
|
27
|
+
if (process.env.MS365_MCP_OAUTH_TOKEN) conflicts.push("MS365_MCP_OAUTH_TOKEN");
|
|
28
|
+
if (conflicts.length > 0) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
`--app-mode cannot be combined with ${conflicts.join(", ")}. App mode is stdio only and uses the app registration itself, with no signed-in user.`
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function pemBlock(pem, label) {
|
|
35
|
+
const match = pem.match(
|
|
36
|
+
new RegExp(`-----BEGIN (${label.source})-----[\\s\\S]+?-----END \\1-----`)
|
|
37
|
+
);
|
|
38
|
+
return match?.[0];
|
|
39
|
+
}
|
|
40
|
+
function loadCertificateCredential(certPath) {
|
|
41
|
+
let pem;
|
|
42
|
+
try {
|
|
43
|
+
pem = readFileSync(certPath, "utf8");
|
|
44
|
+
} catch (error) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
`Cannot read MS365_MCP_CLIENT_CERTIFICATE_PATH (${certPath}): ${error.message}`
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
if (pemBlock(pem, /ENCRYPTED PRIVATE KEY/)) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
"MS365_MCP_CLIENT_CERTIFICATE_PATH holds an encrypted private key; decrypt it first (openssl pkey -in key.pem -out plain.pem)."
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
const certificate = pemBlock(pem, /CERTIFICATE/);
|
|
55
|
+
const privateKey = pemBlock(pem, /(?:RSA |EC )?PRIVATE KEY/);
|
|
56
|
+
if (!certificate || !privateKey) {
|
|
57
|
+
throw new Error(
|
|
58
|
+
"MS365_MCP_CLIENT_CERTIFICATE_PATH must be a PEM file with both the certificate and its private key."
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
const thumbprintSha256 = new X509Certificate(certificate).fingerprint256.replace(/:/g, "");
|
|
62
|
+
return { thumbprintSha256, privateKey };
|
|
63
|
+
}
|
|
64
|
+
function isBuiltInClientId(secrets) {
|
|
65
|
+
try {
|
|
66
|
+
return secrets.clientId === getDefaultClientId(secrets.cloudType);
|
|
67
|
+
} catch {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function decodeTokenClaims(token) {
|
|
72
|
+
try {
|
|
73
|
+
const payload = token.split(".")[1] ?? "";
|
|
74
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
75
|
+
} catch {
|
|
76
|
+
return {};
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function describeAppToken(token) {
|
|
80
|
+
const claims = decodeTokenClaims(token);
|
|
81
|
+
return {
|
|
82
|
+
appId: claims.appid ?? claims.azp,
|
|
83
|
+
tenantId: claims.tid,
|
|
84
|
+
roles: Array.isArray(claims.roles) ? claims.roles : []
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
class AppTokenClient {
|
|
88
|
+
constructor(secrets, certPath = process.env.MS365_MCP_CLIENT_CERTIFICATE_PATH) {
|
|
89
|
+
const tenantId = secrets.tenantId?.trim();
|
|
90
|
+
if (!tenantId || NON_TENANT_AUTHORITIES.has(tenantId.toLowerCase())) {
|
|
91
|
+
throw new Error(
|
|
92
|
+
`--app-mode needs MS365_MCP_TENANT_ID set to your tenant id or domain, not '${tenantId || "common"}'.`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
if (isBuiltInClientId(secrets)) {
|
|
96
|
+
throw new Error(
|
|
97
|
+
"--app-mode needs MS365_MCP_CLIENT_ID set to your own app registration; the built-in app has no application permissions."
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
if (certPath && secrets.clientSecret) {
|
|
101
|
+
throw new Error(
|
|
102
|
+
"Set MS365_MCP_CLIENT_SECRET or MS365_MCP_CLIENT_CERTIFICATE_PATH for --app-mode, not both."
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
if (!certPath && !secrets.clientSecret) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
"--app-mode needs MS365_MCP_CLIENT_SECRET or MS365_MCP_CLIENT_CERTIFICATE_PATH for your own app registration."
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
const cloudEndpoints = getCloudEndpoints(secrets.cloudType);
|
|
111
|
+
this.cca = new ConfidentialClientApplication({
|
|
112
|
+
auth: {
|
|
113
|
+
clientId: secrets.clientId,
|
|
114
|
+
authority: `${cloudEndpoints.authority}/${tenantId}`,
|
|
115
|
+
...certPath ? { clientCertificate: loadCertificateCredential(certPath) } : { clientSecret: secrets.clientSecret }
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
this.scopes = [`${cloudEndpoints.graphApi.replace(/\/$/, "")}/.default`];
|
|
119
|
+
logger.info(
|
|
120
|
+
`App mode: client credentials with a ${certPath ? "certificate" : "client secret"} for tenant ${tenantId}`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
async getToken() {
|
|
124
|
+
const result = await this.cca.acquireTokenByClientCredential({ scopes: this.scopes });
|
|
125
|
+
if (!result?.accessToken) {
|
|
126
|
+
throw new Error("Client credentials token request returned no access token");
|
|
127
|
+
}
|
|
128
|
+
return result.accessToken;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
export {
|
|
132
|
+
APP_MODE_WARNING,
|
|
133
|
+
AppTokenClient,
|
|
134
|
+
assertAppModeOptions,
|
|
135
|
+
describeAppToken,
|
|
136
|
+
loadCertificateCredential
|
|
137
|
+
};
|
package/dist/auth.js
CHANGED
|
@@ -4,6 +4,7 @@ import { readFileSync } from "fs";
|
|
|
4
4
|
import { fileURLToPath } from "url";
|
|
5
5
|
import path from "path";
|
|
6
6
|
import { getSecrets } from "./secrets.js";
|
|
7
|
+
import { AppTokenClient, describeAppToken } from "./app-mode.js";
|
|
7
8
|
import { getCloudEndpoints, getDefaultClientId, getGraphBaseUrl } from "./cloud-config.js";
|
|
8
9
|
import {
|
|
9
10
|
dedupeRefreshTokens
|
|
@@ -164,6 +165,21 @@ const SCOPE_HIERARCHY = {
|
|
|
164
165
|
"Tasks.ReadWrite": ["Tasks.Read"],
|
|
165
166
|
"Contacts.ReadWrite": ["Contacts.Read"]
|
|
166
167
|
};
|
|
168
|
+
function toScopeMode(mode = false) {
|
|
169
|
+
if (mode === true) return "org";
|
|
170
|
+
if (mode === false) return "personal";
|
|
171
|
+
return mode;
|
|
172
|
+
}
|
|
173
|
+
function scopeModeFor(options) {
|
|
174
|
+
if (options.appMode) return "app";
|
|
175
|
+
return options.orgMode ? "org" : "personal";
|
|
176
|
+
}
|
|
177
|
+
function isEndpointInScopeMode(endpoint, mode = false) {
|
|
178
|
+
const scopeMode = toScopeMode(mode);
|
|
179
|
+
if (scopeMode === "app") return endpoint?.appScopes !== void 0;
|
|
180
|
+
if (scopeMode === "personal" && endpoint && !endpoint.scopes && endpoint.workScopes) return false;
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
167
183
|
function parseAllowedScopes(value) {
|
|
168
184
|
if (value === void 0) {
|
|
169
185
|
return void 0;
|
|
@@ -190,8 +206,12 @@ function getEndpointScopeGroups(endpoint, includeWorkAccountScopes = false) {
|
|
|
190
206
|
if (!endpoint) {
|
|
191
207
|
return [];
|
|
192
208
|
}
|
|
209
|
+
const mode = toScopeMode(includeWorkAccountScopes);
|
|
210
|
+
if (mode === "app") {
|
|
211
|
+
return toScopeGroups(endpoint.appScopes);
|
|
212
|
+
}
|
|
193
213
|
const groups = [...toScopeGroups(endpoint.scopes)];
|
|
194
|
-
if (
|
|
214
|
+
if (mode === "org") {
|
|
195
215
|
groups.push(...toScopeGroups(endpoint.workScopes));
|
|
196
216
|
}
|
|
197
217
|
return groups;
|
|
@@ -261,7 +281,7 @@ function buildScopesFromEndpoints(includeWorkAccountScopes = false, enabledTools
|
|
|
261
281
|
if (enabledToolsRegex && !enabledToolsRegex.test(endpoint.toolName)) {
|
|
262
282
|
return;
|
|
263
283
|
}
|
|
264
|
-
if (!
|
|
284
|
+
if (!isEndpointInScopeMode(endpoint, includeWorkAccountScopes)) {
|
|
265
285
|
return;
|
|
266
286
|
}
|
|
267
287
|
getEndpointLoginScopes(endpoint, includeWorkAccountScopes).forEach(
|
|
@@ -327,10 +347,7 @@ function endpointMatchesNormalToolSurface(endpoint, includeWorkAccountScopes, en
|
|
|
327
347
|
if (enabledToolsRegex && !enabledToolsRegex.test(endpoint.toolName)) {
|
|
328
348
|
return false;
|
|
329
349
|
}
|
|
330
|
-
|
|
331
|
-
return false;
|
|
332
|
-
}
|
|
333
|
-
return true;
|
|
350
|
+
return isEndpointInScopeMode(endpoint, includeWorkAccountScopes);
|
|
334
351
|
}
|
|
335
352
|
function buildAllowedScopeDiagnostics(options = {}) {
|
|
336
353
|
const allowedScopes = parseAllowedScopes(options.allowedScopes);
|
|
@@ -348,18 +365,19 @@ function buildAllowedScopeDiagnostics(options = {}) {
|
|
|
348
365
|
const effectiveToolScopes = /* @__PURE__ */ new Set();
|
|
349
366
|
const effectiveToolScopesAllGroups = /* @__PURE__ */ new Set();
|
|
350
367
|
const disabledTools = [];
|
|
368
|
+
const mode = scopeModeFor(options);
|
|
351
369
|
for (const endpoint of endpoints.default) {
|
|
352
370
|
if (!endpointMatchesNormalToolSurface(
|
|
353
371
|
endpoint,
|
|
354
|
-
|
|
372
|
+
mode,
|
|
355
373
|
enabledToolsRegex,
|
|
356
374
|
Boolean(options.readOnly)
|
|
357
375
|
)) {
|
|
358
376
|
continue;
|
|
359
377
|
}
|
|
360
|
-
const scopeGroups = getEndpointScopeGroups(endpoint,
|
|
361
|
-
const loginScopes = getEndpointLoginScopes(endpoint,
|
|
362
|
-
const allScopes = getEndpointRequiredScopes(endpoint,
|
|
378
|
+
const scopeGroups = getEndpointScopeGroups(endpoint, mode);
|
|
379
|
+
const loginScopes = getEndpointLoginScopes(endpoint, mode);
|
|
380
|
+
const allScopes = getEndpointRequiredScopes(endpoint, mode);
|
|
363
381
|
loginScopes.forEach((scope) => normalToolScopes.add(scope));
|
|
364
382
|
const missingScopes = getMissingAllowedScopesForGroups(scopeGroups, allowedScopes);
|
|
365
383
|
if (missingScopes.length > 0) {
|
|
@@ -443,6 +461,7 @@ function consumersAuthorityHint(error, account, authority) {
|
|
|
443
461
|
}
|
|
444
462
|
class AuthManager {
|
|
445
463
|
constructor(config, scopes = [], expectedAccount, storage) {
|
|
464
|
+
this.appClient = null;
|
|
446
465
|
logger.info(`And scopes are ${scopes.join(", ")}`, scopes);
|
|
447
466
|
this.scopes = scopes;
|
|
448
467
|
this.storage = storage ?? new DefaultTokenCacheStorage();
|
|
@@ -475,7 +494,14 @@ class AuthManager {
|
|
|
475
494
|
const secrets = await getSecrets();
|
|
476
495
|
const config = createMsalConfig(secrets);
|
|
477
496
|
const storage = options.storage ?? await createTokenCacheStorage({ allowCommandStorage: false, logProvider: true });
|
|
478
|
-
|
|
497
|
+
const authManager = new AuthManager(config, scopes, expectedAccount, storage);
|
|
498
|
+
if (options.appMode) {
|
|
499
|
+
authManager.appClient = new AppTokenClient(secrets);
|
|
500
|
+
}
|
|
501
|
+
return authManager;
|
|
502
|
+
}
|
|
503
|
+
isAppMode() {
|
|
504
|
+
return this.appClient !== null;
|
|
479
505
|
}
|
|
480
506
|
async loadTokenCache() {
|
|
481
507
|
try {
|
|
@@ -749,6 +775,9 @@ class AuthManager {
|
|
|
749
775
|
this.isOAuthMode = true;
|
|
750
776
|
}
|
|
751
777
|
async getToken(forceRefresh = false) {
|
|
778
|
+
if (this.appClient) {
|
|
779
|
+
return this.appClient.getToken();
|
|
780
|
+
}
|
|
752
781
|
if (this.isOAuthMode && this.oauthToken) {
|
|
753
782
|
return this.oauthToken;
|
|
754
783
|
}
|
|
@@ -893,6 +922,9 @@ class AuthManager {
|
|
|
893
922
|
return this.selectedAccountId === null || this.selectedAccountId === this.loginPersistence.homeAccountId;
|
|
894
923
|
}
|
|
895
924
|
async testLogin() {
|
|
925
|
+
if (this.appClient) {
|
|
926
|
+
return this.testAppLogin(this.appClient);
|
|
927
|
+
}
|
|
896
928
|
try {
|
|
897
929
|
logger.info("Testing login...");
|
|
898
930
|
if (this.loginPersistence && this.loginPersistenceAppliesToCurrentAccount()) {
|
|
@@ -949,6 +981,18 @@ class AuthManager {
|
|
|
949
981
|
};
|
|
950
982
|
}
|
|
951
983
|
}
|
|
984
|
+
// No /me for an app token: report the roles claim instead. It is empty for an app that only
|
|
985
|
+
// has Exchange RBAC for Applications grants, so an empty one is a hint, not a failure.
|
|
986
|
+
async testAppLogin(appClient) {
|
|
987
|
+
try {
|
|
988
|
+
const appData = describeAppToken(await appClient.getToken());
|
|
989
|
+
const message = appData.roles.length > 0 ? "App token acquired" : "App token acquired, but it carries no Microsoft Entra application permissions. Fine if access comes only from Exchange RBAC for Applications; otherwise grant permissions and admin consent.";
|
|
990
|
+
return { success: true, message, appData };
|
|
991
|
+
} catch (error) {
|
|
992
|
+
logger.error(`App token request failed: ${describeAuthError(error)}`);
|
|
993
|
+
return { success: false, message: `App token request failed: ${error.message}` };
|
|
994
|
+
}
|
|
995
|
+
}
|
|
952
996
|
async logout() {
|
|
953
997
|
try {
|
|
954
998
|
const accounts = await this.msalApp.getTokenCache().getAllAccounts();
|
|
@@ -1045,7 +1089,7 @@ class AuthManager {
|
|
|
1045
1089
|
* Used to decide whether to inject the `account` parameter into tool schemas.
|
|
1046
1090
|
*/
|
|
1047
1091
|
async isMultiAccount() {
|
|
1048
|
-
if (this.hasExpectedAccount()) {
|
|
1092
|
+
if (this.appClient || this.hasExpectedAccount()) {
|
|
1049
1093
|
return false;
|
|
1050
1094
|
}
|
|
1051
1095
|
const accounts = await this.msalApp.getTokenCache().getAllAccounts();
|
|
@@ -1064,6 +1108,14 @@ class AuthManager {
|
|
|
1064
1108
|
* @returns The access token string.
|
|
1065
1109
|
*/
|
|
1066
1110
|
async getTokenForAccount(identifier) {
|
|
1111
|
+
if (this.appClient) {
|
|
1112
|
+
if (identifier) {
|
|
1113
|
+
throw new Error(
|
|
1114
|
+
`Cannot switch to account '${identifier}': the server is in app mode and has no signed-in accounts.`
|
|
1115
|
+
);
|
|
1116
|
+
}
|
|
1117
|
+
return this.appClient.getToken();
|
|
1118
|
+
}
|
|
1067
1119
|
if (this.isOAuthMode && this.oauthToken) {
|
|
1068
1120
|
if (identifier) {
|
|
1069
1121
|
throw new Error(
|
|
@@ -1140,10 +1192,12 @@ export {
|
|
|
1140
1192
|
getMissingAllowedScopesForGroups,
|
|
1141
1193
|
getSelectedAccountPath,
|
|
1142
1194
|
getTokenCachePath,
|
|
1195
|
+
isEndpointInScopeMode,
|
|
1143
1196
|
parseAllowedScopes,
|
|
1144
1197
|
pickNewest,
|
|
1145
1198
|
resetRefreshTokenWarningsForTests,
|
|
1146
1199
|
resolveAuthScopes,
|
|
1200
|
+
scopeModeFor,
|
|
1147
1201
|
unwrapCache,
|
|
1148
1202
|
wrapCache
|
|
1149
1203
|
};
|
package/dist/cli.js
CHANGED
|
@@ -59,7 +59,10 @@ program.name("ms-365-mcp-server").description("Microsoft 365 MCP Server").versio
|
|
|
59
59
|
).option("--list-presets", "List all available presets and exit").option("--list-permissions", "List all required Graph API permissions and exit").option(
|
|
60
60
|
"--org-mode",
|
|
61
61
|
"Enable organization/work mode from start (includes Teams, SharePoint, etc.)"
|
|
62
|
-
).option("--work-mode", "Alias for --org-mode").option(
|
|
62
|
+
).option("--work-mode", "Alias for --org-mode").option(
|
|
63
|
+
"--app-mode",
|
|
64
|
+
"Use application permissions (client credentials) with no signed-in user. stdio only. Needs your own app registration, MS365_MCP_TENANT_ID, and MS365_MCP_CLIENT_SECRET or MS365_MCP_CLIENT_CERTIFICATE_PATH. Only tools that work with application permissions are offered."
|
|
65
|
+
).option("--force-work-scopes", "Backwards compatibility alias for --org-mode (deprecated)").option("--toon", "(experimental) Enable TOON output format for 30-60% token reduction").option(
|
|
63
66
|
"--eager-tools <names>",
|
|
64
67
|
"With --discovery, also expose these comma-separated exact Graph or utility tool names directly. All enabled tools remain discoverable. Env: MS365_MCP_EAGER_TOOLS."
|
|
65
68
|
).option("--discovery", "Enable runtime tool discovery and loading (experimental feature)").option(
|
|
@@ -138,6 +141,12 @@ function parseArgs() {
|
|
|
138
141
|
throw new Error("--eager-tools requires non-empty exact tool names");
|
|
139
142
|
options.eagerTools = [...new Set(names)];
|
|
140
143
|
}
|
|
144
|
+
if (process.env.MS365_MCP_APP_MODE === "true" || process.env.MS365_MCP_APP_MODE === "1") {
|
|
145
|
+
options.appMode = true;
|
|
146
|
+
}
|
|
147
|
+
if (options.appMode) {
|
|
148
|
+
options.orgMode = true;
|
|
149
|
+
}
|
|
141
150
|
if (options.preset) {
|
|
142
151
|
const presetNames = options.preset.split(",").map((p) => p.trim());
|
|
143
152
|
try {
|