@softeria/ms-365-mcp-server 0.176.1 → 0.178.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/PRESETS.md +1200 -39
- package/README.md +61 -0
- package/SECURITY.md +9 -0
- package/bin/generate-presets-md.ts +94 -21
- package/dist/app-mode.js +220 -0
- package/dist/auth.js +82 -14
- package/dist/cli.js +10 -1
- package/dist/endpoints.json +250 -41
- package/dist/graph-client.js +8 -2
- package/dist/graph-tools.js +33 -24
- package/dist/index.js +18 -3
- package/dist/mcp-instructions.js +4 -0
- package/dist/server.js +4 -2
- package/dist/tool-categories.js +0 -1
- package/package.json +1 -1
- package/src/endpoints.json +250 -41
package/README.md
CHANGED
|
@@ -570,6 +570,61 @@ 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, and set exactly one
|
|
593
|
+
credential:
|
|
594
|
+
- `MS365_MCP_CLIENT_SECRET`
|
|
595
|
+
- `MS365_MCP_CLIENT_CERTIFICATE_PATH`: a PEM file with the certificate and its unencrypted private key
|
|
596
|
+
- `MS365_MCP_FEDERATED_TOKEN_FILE`: a token from an identity provider the app trusts through
|
|
597
|
+
[workload identity federation](https://learn.microsoft.com/en-us/entra/workload-id/workload-identity-federation),
|
|
598
|
+
read again on every token request. On AKS set it to `$AZURE_FEDERATED_TOKEN_FILE`, which Kubernetes
|
|
599
|
+
keeps fresh. A GitHub Actions OIDC token is valid for 5 minutes, so writing it to a file once only
|
|
600
|
+
covers the first Graph token (about an hour) unless something rewrites the file. If Entra answers
|
|
601
|
+
`AADSTS700213`, set the federated credential's subject to the one quoted in the error (GitHub's
|
|
602
|
+
subject can include the owner and repo ids).
|
|
603
|
+
|
|
604
|
+
`MS365_MCP_TENANT_ID` must be a real tenant, not `common`.
|
|
605
|
+
|
|
606
|
+
- On an Azure host (App Service, Container Apps, VM, ...) set `MS365_MCP_MANAGED_IDENTITY=system`, or the
|
|
607
|
+
client id of a user-assigned identity, instead. No app registration, tenant id or secret is needed, and
|
|
608
|
+
Key Vault (`MS365_MCP_KEYVAULT_URL`) is not read. Graph
|
|
609
|
+
application permissions for a managed identity can't be granted in the portal;
|
|
610
|
+
[assign them with PowerShell or the Graph API](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/how-to-assign-app-role-managed-identity).
|
|
611
|
+
On Azure Container Instances, give the container one kind of identity: with both a system- and a
|
|
612
|
+
user-assigned identity, the system-assigned token request fails there.
|
|
613
|
+
- Tokens are renewed automatically. Nothing is cached on disk.
|
|
614
|
+
- Only tools that work with application permissions are offered: the `/users/{user-id}` mail and calendar
|
|
615
|
+
tools (pass a UPN or object id as `user-id`), users and groups, OneDrive/SharePoint drives and lists, Planner,
|
|
616
|
+
Teams reads, presence, places and subscriptions. `/me` tools, Excel, OneNote and sending Teams chat or channel
|
|
617
|
+
messages are not available, because Graph does not support them with application permissions.
|
|
618
|
+
- `--list-permissions --app-mode` lists the application permissions the offered tools use. `--allowed-scopes`,
|
|
619
|
+
`--enabled-tools`, `--preset` and `--read-only` narrow the surface as usual.
|
|
620
|
+
- `--verify-login --app-mode` gets a token and shows the app id, tenant and granted roles (Exchange RBAC
|
|
621
|
+
grants do not show up there).
|
|
622
|
+
- The `mail`, `calendar` and `outlook` presets are built from `/me` tools and leave little in app mode; the
|
|
623
|
+
`/users/{user-id}` mail and calendar tools are in `work`.
|
|
624
|
+
- stdio only. It refuses `--http`, `--obo`, `--extra-scopes`, `MS365_MCP_OAUTH_TOKEN` and the
|
|
625
|
+
login/account options.
|
|
626
|
+
- Webinar tools also need an application access policy assigned to the organizer.
|
|
627
|
+
|
|
573
628
|
> **Note**: HTTP mode requires authentication. For unauthenticated testing, use stdio mode with device code flow.
|
|
574
629
|
>
|
|
575
630
|
> **Authentication Tools**: In HTTP mode, login/logout tools are disabled by default since OAuth handles authentication.
|
|
@@ -745,6 +800,8 @@ When running as an MCP server, the following options can be used:
|
|
|
745
800
|
which reads files from those directories.
|
|
746
801
|
Refused unless --http binds a loopback host with no --public-url and no
|
|
747
802
|
--trust-proxy-auth
|
|
803
|
+
--app-mode Use application permissions (client credentials) with no signed-in user. stdio only
|
|
804
|
+
(see "App Mode" under Authentication)
|
|
748
805
|
--enable-auth-tools Enable login/logout tools when using HTTP mode (disabled by default in HTTP mode)
|
|
749
806
|
--enable-attachment-urls Let get-download-url mint a server-served URL for byte resources Graph
|
|
750
807
|
exposes no pre-authenticated URL for (see "Server-Minted Attachment URLs").
|
|
@@ -777,6 +834,10 @@ Environment variables:
|
|
|
777
834
|
- `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
835
|
- `MS365_MCP_ORG_MODE=true|1`: Enable organization/work mode (alternative to --org-mode flag)
|
|
779
836
|
- `MS365_MCP_FORCE_WORK_SCOPES=true|1`: Backwards compatibility for MS365_MCP_ORG_MODE
|
|
837
|
+
- `MS365_MCP_APP_MODE=true|1`: Enable app mode (alternative to --app-mode flag)
|
|
838
|
+
- `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
|
|
839
|
+
- `MS365_MCP_FEDERATED_TOKEN_FILE=<path>`: Federated token (workload identity federation), used instead of a secret or certificate in app mode
|
|
840
|
+
- `MS365_MCP_MANAGED_IDENTITY=system|<client id>`: Use the host's managed identity in app mode, instead of an app registration
|
|
780
841
|
- `MS365_MCP_OUTPUT_FORMAT=toon`: Enable TOON output format (alternative to --toon flag)
|
|
781
842
|
- `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
843
|
- `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
|
|
@@ -7,54 +7,127 @@ import { writeFileSync } from 'fs';
|
|
|
7
7
|
import path from 'path';
|
|
8
8
|
import { fileURLToPath } from 'url';
|
|
9
9
|
import prettier from 'prettier';
|
|
10
|
-
import {
|
|
10
|
+
import { resolveAuthScopes } from '../src/auth.js';
|
|
11
|
+
import { buildToolsRegistry, isUtilityToolAvailable, UTILITY_TOOLS } from '../src/graph-tools.js';
|
|
12
|
+
import { getCombinedPresetPattern, listPresets } from '../src/tool-categories.js';
|
|
11
13
|
|
|
12
14
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
13
15
|
const rootDir = path.resolve(__dirname, '..');
|
|
14
16
|
const outFile = path.join(rootDir, 'PRESETS.md');
|
|
15
17
|
|
|
18
|
+
type Mode = 'full' | 'read-only';
|
|
19
|
+
|
|
20
|
+
function modeLabel(mode: Mode): string {
|
|
21
|
+
return mode === 'full' ? 'full' : 'read only';
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function sectionAnchor(preset: string, mode: Mode): string {
|
|
25
|
+
return `${preset}-${mode}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Tools the server would expose for `--preset X` [--read-only], using the same
|
|
30
|
+
* Graph registry filters as runtime. Always pass orgMode so work-scoped tools that
|
|
31
|
+
* belong to a personal preset (e.g. SharePoint OneNote under `onenote`) are listed.
|
|
32
|
+
* httpMode=false keeps stdioOnly utilities in the catalog. Strip `enabled` so
|
|
33
|
+
* process opt-in (e.g. MS365_MCP_UPLOAD_DIRS) does not shrink the documented set.
|
|
34
|
+
*/
|
|
35
|
+
function toolsForMode(preset: string, mode: Mode): string[] {
|
|
36
|
+
const readOnly = mode === 'read-only';
|
|
37
|
+
const enabledToolsRegex = new RegExp(getCombinedPresetPattern([preset]));
|
|
38
|
+
const graphTools = [...buildToolsRegistry(readOnly, true, enabledToolsRegex).keys()];
|
|
39
|
+
const utilityTools = UTILITY_TOOLS.filter(
|
|
40
|
+
(u) =>
|
|
41
|
+
isUtilityToolAvailable(
|
|
42
|
+
{ ...u, enabled: undefined },
|
|
43
|
+
{ readOnly, httpMode: false, scopeMode: 'org' }
|
|
44
|
+
) && enabledToolsRegex.test(u.name)
|
|
45
|
+
).map((u) => u.name);
|
|
46
|
+
return [...new Set([...graphTools, ...utilityTools])].sort();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function scopesForMode(preset: string, mode: Mode): string[] {
|
|
50
|
+
return resolveAuthScopes({
|
|
51
|
+
enabledTools: getCombinedPresetPattern([preset]),
|
|
52
|
+
readOnly: mode === 'read-only',
|
|
53
|
+
orgMode: true,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function pushBulletList(lines: string[], heading: string, items: string[]): void {
|
|
58
|
+
lines.push(`${heading} (${items.length}):`);
|
|
59
|
+
lines.push('');
|
|
60
|
+
for (const item of items) {
|
|
61
|
+
lines.push(`- \`${item}\``);
|
|
62
|
+
}
|
|
63
|
+
lines.push('');
|
|
64
|
+
}
|
|
65
|
+
|
|
16
66
|
export async function renderPresetsMarkdown(): Promise<string> {
|
|
17
|
-
const catalog = listPresets().map((preset) =>
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
67
|
+
const catalog = listPresets().map((preset) => {
|
|
68
|
+
const fullTools = toolsForMode(preset.name, 'full');
|
|
69
|
+
const readOnlyTools = toolsForMode(preset.name, 'read-only');
|
|
70
|
+
return {
|
|
71
|
+
...preset,
|
|
72
|
+
variants: [
|
|
73
|
+
{
|
|
74
|
+
mode: 'full' as const,
|
|
75
|
+
tools: fullTools,
|
|
76
|
+
scopes: scopesForMode(preset.name, 'full'),
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
mode: 'read-only' as const,
|
|
80
|
+
tools: readOnlyTools,
|
|
81
|
+
scopes: scopesForMode(preset.name, 'read-only'),
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
};
|
|
85
|
+
});
|
|
86
|
+
|
|
21
87
|
const lines: string[] = [
|
|
22
88
|
'# Tool Presets',
|
|
23
89
|
'',
|
|
24
90
|
'> Generated by `bin/generate-presets-md.ts`. Do not edit by hand; regenerated on `npm run generate`.',
|
|
25
91
|
'',
|
|
92
|
+
'Tool and scope lists assume `--org-mode`; without it, personal accounts get fewer tools and scopes.',
|
|
26
93
|
'',
|
|
27
94
|
'## Summary',
|
|
28
95
|
'',
|
|
29
|
-
'| Preset | Tools | Org mode | Description |',
|
|
30
|
-
'| ------ | ----: | -------- | ----------- |',
|
|
96
|
+
'| Preset | Mode | Tools | Scopes | Org mode | Description |',
|
|
97
|
+
'| ------ | ---- | ----: | -----: | -------- | ----------- |',
|
|
31
98
|
];
|
|
32
99
|
|
|
33
100
|
for (const entry of catalog) {
|
|
34
|
-
const org = entry.requiresOrgMode ? 'required' : '';
|
|
101
|
+
const org = entry.requiresOrgMode ? 'required' : '-';
|
|
35
102
|
const desc = entry.description.replace(/\|/g, '\\|');
|
|
103
|
+
const modeCell = entry.variants
|
|
104
|
+
.map((v) => `[${modeLabel(v.mode)}](#${sectionAnchor(entry.name, v.mode)})`)
|
|
105
|
+
.join('<br>');
|
|
106
|
+
const toolsCell = entry.variants.map((v) => String(v.tools.length)).join('<br>');
|
|
107
|
+
const scopesCell = entry.variants.map((v) => String(v.scopes.length)).join('<br>');
|
|
108
|
+
// Same org-mode flag for both variants; still stacked so the row lines up with Mode/Tools.
|
|
109
|
+
const orgCell = entry.variants.map(() => org).join('<br>');
|
|
36
110
|
lines.push(
|
|
37
|
-
`|
|
|
111
|
+
`| \`${entry.name}\` | ${modeCell} | ${toolsCell} | ${scopesCell} | ${orgCell} | ${desc} |`
|
|
38
112
|
);
|
|
39
113
|
}
|
|
40
114
|
|
|
41
115
|
lines.push('');
|
|
42
116
|
|
|
43
117
|
for (const entry of catalog) {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (entry.requiresOrgMode) {
|
|
118
|
+
for (const variant of entry.variants) {
|
|
119
|
+
const label = modeLabel(variant.mode);
|
|
120
|
+
lines.push(`## \`${entry.name}\` ${label}`);
|
|
48
121
|
lines.push('');
|
|
49
|
-
lines.push(
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
lines.
|
|
122
|
+
lines.push(entry.description);
|
|
123
|
+
if (entry.requiresOrgMode) {
|
|
124
|
+
lines.push('');
|
|
125
|
+
lines.push('Requires `--org-mode`.');
|
|
126
|
+
}
|
|
127
|
+
lines.push('');
|
|
128
|
+
pushBulletList(lines, 'Tools', variant.tools);
|
|
129
|
+
pushBulletList(lines, 'Scopes', variant.scopes);
|
|
56
130
|
}
|
|
57
|
-
lines.push('');
|
|
58
131
|
}
|
|
59
132
|
|
|
60
133
|
// Format here so PRESETS.md matches `prettier --check` and the staleness test.
|
package/dist/app-mode.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ConfidentialClientApplication,
|
|
3
|
+
ManagedIdentityApplication
|
|
4
|
+
} from "@azure/msal-node";
|
|
5
|
+
import { X509Certificate } from "crypto";
|
|
6
|
+
import { readFileSync } from "fs";
|
|
7
|
+
import logger from "./logger.js";
|
|
8
|
+
import { getCloudEndpoints, getDefaultClientId, parseCloudType } from "./cloud-config.js";
|
|
9
|
+
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.";
|
|
10
|
+
const NON_TENANT_AUTHORITIES = /* @__PURE__ */ new Set(["common", "organizations", "consumers"]);
|
|
11
|
+
const LOCAL_ACCOUNT_FLAGS = [
|
|
12
|
+
["login", "--login"],
|
|
13
|
+
["logout", "--logout"],
|
|
14
|
+
["listAccounts", "--list-accounts"],
|
|
15
|
+
["selectAccount", "--select-account"],
|
|
16
|
+
["removeAccount", "--remove-account"],
|
|
17
|
+
["authBrowser", "--auth-browser"],
|
|
18
|
+
["expectedUsername", "--expected-username"],
|
|
19
|
+
["expectedHomeAccountId", "--expected-home-account-id"]
|
|
20
|
+
];
|
|
21
|
+
function assertAppModeOptions(options) {
|
|
22
|
+
const conflicts = [];
|
|
23
|
+
if (options.http) conflicts.push("--http");
|
|
24
|
+
if (options.obo) conflicts.push("--obo");
|
|
25
|
+
if (options.trustProxyAuth) conflicts.push("--trust-proxy-auth");
|
|
26
|
+
if (options.extraScopes !== void 0) conflicts.push("--extra-scopes");
|
|
27
|
+
for (const [key, flag] of LOCAL_ACCOUNT_FLAGS) {
|
|
28
|
+
if (options[key]) conflicts.push(flag);
|
|
29
|
+
}
|
|
30
|
+
if (process.env.MS365_MCP_OAUTH_TOKEN) conflicts.push("MS365_MCP_OAUTH_TOKEN");
|
|
31
|
+
if (conflicts.length > 0) {
|
|
32
|
+
throw new Error(
|
|
33
|
+
`--app-mode cannot be combined with ${conflicts.join(", ")}. App mode is stdio only and uses the app registration itself, with no signed-in user.`
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function pemBlock(pem, label) {
|
|
38
|
+
const match = pem.match(
|
|
39
|
+
new RegExp(`-----BEGIN (${label.source})-----[\\s\\S]+?-----END \\1-----`)
|
|
40
|
+
);
|
|
41
|
+
return match?.[0];
|
|
42
|
+
}
|
|
43
|
+
function loadCertificateCredential(certPath) {
|
|
44
|
+
let pem;
|
|
45
|
+
try {
|
|
46
|
+
pem = readFileSync(certPath, "utf8");
|
|
47
|
+
} catch (error) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
`Cannot read MS365_MCP_CLIENT_CERTIFICATE_PATH (${certPath}): ${error.message}`
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
if (pemBlock(pem, /ENCRYPTED PRIVATE KEY/)) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
"MS365_MCP_CLIENT_CERTIFICATE_PATH holds an encrypted private key; decrypt it first (openssl pkey -in key.pem -out plain.pem)."
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
const certificate = pemBlock(pem, /CERTIFICATE/);
|
|
58
|
+
const privateKey = pemBlock(pem, /(?:RSA |EC )?PRIVATE KEY/);
|
|
59
|
+
if (!certificate || !privateKey) {
|
|
60
|
+
throw new Error(
|
|
61
|
+
"MS365_MCP_CLIENT_CERTIFICATE_PATH must be a PEM file with both the certificate and its private key."
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
const thumbprintSha256 = new X509Certificate(certificate).fingerprint256.replace(/:/g, "");
|
|
65
|
+
return { thumbprintSha256, privateKey };
|
|
66
|
+
}
|
|
67
|
+
function isBuiltInClientId(secrets) {
|
|
68
|
+
try {
|
|
69
|
+
return secrets.clientId === getDefaultClientId(secrets.cloudType);
|
|
70
|
+
} catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function decodeTokenClaims(token) {
|
|
75
|
+
try {
|
|
76
|
+
const payload = token.split(".")[1] ?? "";
|
|
77
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
78
|
+
} catch {
|
|
79
|
+
return {};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function describeAppToken(token) {
|
|
83
|
+
const claims = decodeTokenClaims(token);
|
|
84
|
+
return {
|
|
85
|
+
appId: claims.appid ?? claims.azp,
|
|
86
|
+
tenantId: claims.tid,
|
|
87
|
+
roles: Array.isArray(claims.roles) ? claims.roles : []
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function readFederatedToken(tokenPath) {
|
|
91
|
+
let token;
|
|
92
|
+
try {
|
|
93
|
+
token = readFileSync(tokenPath, "utf8").trim();
|
|
94
|
+
} catch (error) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`Cannot read MS365_MCP_FEDERATED_TOKEN_FILE (${tokenPath}): ${error.message}`
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
if (!token) {
|
|
100
|
+
throw new Error(`MS365_MCP_FEDERATED_TOKEN_FILE (${tokenPath}) is empty.`);
|
|
101
|
+
}
|
|
102
|
+
return token;
|
|
103
|
+
}
|
|
104
|
+
const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
105
|
+
function parseManagedIdentity(value) {
|
|
106
|
+
const trimmed = value.trim();
|
|
107
|
+
if (["system", "true", "1"].includes(trimmed.toLowerCase())) return {};
|
|
108
|
+
if (GUID.test(trimmed)) return { userAssignedClientId: trimmed };
|
|
109
|
+
throw new Error(
|
|
110
|
+
`MS365_MCP_MANAGED_IDENTITY must be 'system' or the client id of a user-assigned identity, not '${trimmed}'.`
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
function managedIdentityFromEnv() {
|
|
114
|
+
const value = process.env.MS365_MCP_MANAGED_IDENTITY?.trim();
|
|
115
|
+
return value && !["false", "0"].includes(value.toLowerCase()) ? value : void 0;
|
|
116
|
+
}
|
|
117
|
+
function credentialEnvFromProcess() {
|
|
118
|
+
return {
|
|
119
|
+
certPath: process.env.MS365_MCP_CLIENT_CERTIFICATE_PATH || void 0,
|
|
120
|
+
federatedTokenFile: process.env.MS365_MCP_FEDERATED_TOKEN_FILE || void 0,
|
|
121
|
+
managedIdentity: managedIdentityFromEnv()
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function usesManagedIdentity() {
|
|
125
|
+
return managedIdentityFromEnv() !== void 0;
|
|
126
|
+
}
|
|
127
|
+
function managedIdentitySecrets() {
|
|
128
|
+
return {
|
|
129
|
+
clientId: process.env.MS365_MCP_CLIENT_ID || "",
|
|
130
|
+
tenantId: process.env.MS365_MCP_TENANT_ID || "common",
|
|
131
|
+
clientSecret: process.env.MS365_MCP_CLIENT_SECRET,
|
|
132
|
+
cloudType: parseCloudType(process.env.MS365_MCP_CLOUD_TYPE)
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
const CREDENTIAL_OPTIONS = "MS365_MCP_CLIENT_SECRET, MS365_MCP_CLIENT_CERTIFICATE_PATH, MS365_MCP_FEDERATED_TOKEN_FILE or MS365_MCP_MANAGED_IDENTITY";
|
|
136
|
+
class AppTokenClient {
|
|
137
|
+
constructor(secrets, env = credentialEnvFromProcess()) {
|
|
138
|
+
const set = [
|
|
139
|
+
secrets.clientSecret && "a client secret (MS365_MCP_CLIENT_SECRET, .env or Key Vault)",
|
|
140
|
+
env.certPath && "MS365_MCP_CLIENT_CERTIFICATE_PATH",
|
|
141
|
+
env.federatedTokenFile && "MS365_MCP_FEDERATED_TOKEN_FILE",
|
|
142
|
+
env.managedIdentity && "MS365_MCP_MANAGED_IDENTITY"
|
|
143
|
+
].filter((name) => Boolean(name));
|
|
144
|
+
if (set.length === 0) {
|
|
145
|
+
throw new Error(`--app-mode needs one of ${CREDENTIAL_OPTIONS}.`);
|
|
146
|
+
}
|
|
147
|
+
if (set.length > 1) {
|
|
148
|
+
throw new Error(`Set only one credential for --app-mode, not ${set.join(" and ")}.`);
|
|
149
|
+
}
|
|
150
|
+
const cloudEndpoints = getCloudEndpoints(secrets.cloudType);
|
|
151
|
+
const graphResource = cloudEndpoints.graphApi.replace(/\/$/, "");
|
|
152
|
+
if (env.managedIdentity) {
|
|
153
|
+
const managedIdentityIdParams = parseManagedIdentity(env.managedIdentity);
|
|
154
|
+
if (secrets.clientId) {
|
|
155
|
+
logger.warn(
|
|
156
|
+
"App mode: MS365_MCP_CLIENT_ID is ignored with a managed identity. For a user-assigned identity, put its client id in MS365_MCP_MANAGED_IDENTITY."
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
const mia = new ManagedIdentityApplication({ managedIdentityIdParams });
|
|
160
|
+
this.acquire = () => mia.acquireToken({ resource: graphResource });
|
|
161
|
+
logger.info(
|
|
162
|
+
`App mode: managed identity (${managedIdentityIdParams.userAssignedClientId ? `user-assigned ${managedIdentityIdParams.userAssignedClientId}` : "system-assigned"})`
|
|
163
|
+
);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const tenantId = secrets.tenantId?.trim();
|
|
167
|
+
if (!tenantId || NON_TENANT_AUTHORITIES.has(tenantId.toLowerCase())) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
`--app-mode needs MS365_MCP_TENANT_ID set to your tenant id or domain, not '${tenantId || "common"}'.`
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
if (isBuiltInClientId(secrets)) {
|
|
173
|
+
throw new Error(
|
|
174
|
+
"--app-mode needs MS365_MCP_CLIENT_ID set to your own app registration; the built-in app has no application permissions."
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
let credential;
|
|
178
|
+
let label;
|
|
179
|
+
if (env.certPath) {
|
|
180
|
+
credential = { clientCertificate: loadCertificateCredential(env.certPath) };
|
|
181
|
+
label = "a certificate";
|
|
182
|
+
} else if (env.federatedTokenFile) {
|
|
183
|
+
const tokenFile = env.federatedTokenFile;
|
|
184
|
+
readFederatedToken(tokenFile);
|
|
185
|
+
credential = { clientAssertion: async () => readFederatedToken(tokenFile) };
|
|
186
|
+
label = "a federated token";
|
|
187
|
+
} else {
|
|
188
|
+
credential = { clientSecret: secrets.clientSecret };
|
|
189
|
+
label = "a client secret";
|
|
190
|
+
}
|
|
191
|
+
const cca = new ConfidentialClientApplication({
|
|
192
|
+
auth: {
|
|
193
|
+
clientId: secrets.clientId,
|
|
194
|
+
authority: `${cloudEndpoints.authority}/${tenantId}`,
|
|
195
|
+
...credential
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
const scopes = [`${graphResource}/.default`];
|
|
199
|
+
this.acquire = () => cca.acquireTokenByClientCredential({ scopes });
|
|
200
|
+
logger.info(`App mode: client credentials with ${label} for tenant ${tenantId}`);
|
|
201
|
+
}
|
|
202
|
+
async getToken() {
|
|
203
|
+
const result = await this.acquire();
|
|
204
|
+
if (!result?.accessToken) {
|
|
205
|
+
throw new Error("App token request returned no access token");
|
|
206
|
+
}
|
|
207
|
+
return result.accessToken;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
export {
|
|
211
|
+
APP_MODE_WARNING,
|
|
212
|
+
AppTokenClient,
|
|
213
|
+
assertAppModeOptions,
|
|
214
|
+
describeAppToken,
|
|
215
|
+
loadCertificateCredential,
|
|
216
|
+
managedIdentitySecrets,
|
|
217
|
+
parseManagedIdentity,
|
|
218
|
+
readFederatedToken,
|
|
219
|
+
usesManagedIdentity
|
|
220
|
+
};
|
package/dist/auth.js
CHANGED
|
@@ -4,6 +4,12 @@ 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 {
|
|
8
|
+
AppTokenClient,
|
|
9
|
+
describeAppToken,
|
|
10
|
+
managedIdentitySecrets,
|
|
11
|
+
usesManagedIdentity
|
|
12
|
+
} from "./app-mode.js";
|
|
7
13
|
import { getCloudEndpoints, getDefaultClientId, getGraphBaseUrl } from "./cloud-config.js";
|
|
8
14
|
import {
|
|
9
15
|
dedupeRefreshTokens
|
|
@@ -164,6 +170,21 @@ const SCOPE_HIERARCHY = {
|
|
|
164
170
|
"Tasks.ReadWrite": ["Tasks.Read"],
|
|
165
171
|
"Contacts.ReadWrite": ["Contacts.Read"]
|
|
166
172
|
};
|
|
173
|
+
function toScopeMode(mode = false) {
|
|
174
|
+
if (mode === true) return "org";
|
|
175
|
+
if (mode === false) return "personal";
|
|
176
|
+
return mode;
|
|
177
|
+
}
|
|
178
|
+
function scopeModeFor(options) {
|
|
179
|
+
if (options.appMode) return "app";
|
|
180
|
+
return options.orgMode ? "org" : "personal";
|
|
181
|
+
}
|
|
182
|
+
function isEndpointInScopeMode(endpoint, mode = false) {
|
|
183
|
+
const scopeMode = toScopeMode(mode);
|
|
184
|
+
if (scopeMode === "app") return endpoint?.appScopes !== void 0;
|
|
185
|
+
if (scopeMode === "personal" && endpoint && !endpoint.scopes && endpoint.workScopes) return false;
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
167
188
|
function parseAllowedScopes(value) {
|
|
168
189
|
if (value === void 0) {
|
|
169
190
|
return void 0;
|
|
@@ -190,8 +211,12 @@ function getEndpointScopeGroups(endpoint, includeWorkAccountScopes = false) {
|
|
|
190
211
|
if (!endpoint) {
|
|
191
212
|
return [];
|
|
192
213
|
}
|
|
214
|
+
const mode = toScopeMode(includeWorkAccountScopes);
|
|
215
|
+
if (mode === "app") {
|
|
216
|
+
return toScopeGroups(endpoint.appScopes);
|
|
217
|
+
}
|
|
193
218
|
const groups = [...toScopeGroups(endpoint.scopes)];
|
|
194
|
-
if (
|
|
219
|
+
if (mode === "org") {
|
|
195
220
|
groups.push(...toScopeGroups(endpoint.workScopes));
|
|
196
221
|
}
|
|
197
222
|
return groups;
|
|
@@ -261,7 +286,7 @@ function buildScopesFromEndpoints(includeWorkAccountScopes = false, enabledTools
|
|
|
261
286
|
if (enabledToolsRegex && !enabledToolsRegex.test(endpoint.toolName)) {
|
|
262
287
|
return;
|
|
263
288
|
}
|
|
264
|
-
if (!
|
|
289
|
+
if (!isEndpointInScopeMode(endpoint, includeWorkAccountScopes)) {
|
|
265
290
|
return;
|
|
266
291
|
}
|
|
267
292
|
getEndpointLoginScopes(endpoint, includeWorkAccountScopes).forEach(
|
|
@@ -327,10 +352,7 @@ function endpointMatchesNormalToolSurface(endpoint, includeWorkAccountScopes, en
|
|
|
327
352
|
if (enabledToolsRegex && !enabledToolsRegex.test(endpoint.toolName)) {
|
|
328
353
|
return false;
|
|
329
354
|
}
|
|
330
|
-
|
|
331
|
-
return false;
|
|
332
|
-
}
|
|
333
|
-
return true;
|
|
355
|
+
return isEndpointInScopeMode(endpoint, includeWorkAccountScopes);
|
|
334
356
|
}
|
|
335
357
|
function buildAllowedScopeDiagnostics(options = {}) {
|
|
336
358
|
const allowedScopes = parseAllowedScopes(options.allowedScopes);
|
|
@@ -348,18 +370,19 @@ function buildAllowedScopeDiagnostics(options = {}) {
|
|
|
348
370
|
const effectiveToolScopes = /* @__PURE__ */ new Set();
|
|
349
371
|
const effectiveToolScopesAllGroups = /* @__PURE__ */ new Set();
|
|
350
372
|
const disabledTools = [];
|
|
373
|
+
const mode = scopeModeFor(options);
|
|
351
374
|
for (const endpoint of endpoints.default) {
|
|
352
375
|
if (!endpointMatchesNormalToolSurface(
|
|
353
376
|
endpoint,
|
|
354
|
-
|
|
377
|
+
mode,
|
|
355
378
|
enabledToolsRegex,
|
|
356
379
|
Boolean(options.readOnly)
|
|
357
380
|
)) {
|
|
358
381
|
continue;
|
|
359
382
|
}
|
|
360
|
-
const scopeGroups = getEndpointScopeGroups(endpoint,
|
|
361
|
-
const loginScopes = getEndpointLoginScopes(endpoint,
|
|
362
|
-
const allScopes = getEndpointRequiredScopes(endpoint,
|
|
383
|
+
const scopeGroups = getEndpointScopeGroups(endpoint, mode);
|
|
384
|
+
const loginScopes = getEndpointLoginScopes(endpoint, mode);
|
|
385
|
+
const allScopes = getEndpointRequiredScopes(endpoint, mode);
|
|
363
386
|
loginScopes.forEach((scope) => normalToolScopes.add(scope));
|
|
364
387
|
const missingScopes = getMissingAllowedScopesForGroups(scopeGroups, allowedScopes);
|
|
365
388
|
if (missingScopes.length > 0) {
|
|
@@ -443,6 +466,8 @@ function consumersAuthorityHint(error, account, authority) {
|
|
|
443
466
|
}
|
|
444
467
|
class AuthManager {
|
|
445
468
|
constructor(config, scopes = [], expectedAccount, storage) {
|
|
469
|
+
this.appClient = null;
|
|
470
|
+
this.appSecrets = null;
|
|
446
471
|
logger.info(`And scopes are ${scopes.join(", ")}`, scopes);
|
|
447
472
|
this.scopes = scopes;
|
|
448
473
|
this.storage = storage ?? new DefaultTokenCacheStorage();
|
|
@@ -472,10 +497,25 @@ class AuthManager {
|
|
|
472
497
|
* Uses Key Vault if MS365_MCP_KEYVAULT_URL is set, otherwise environment variables.
|
|
473
498
|
*/
|
|
474
499
|
static async create(scopes = [], expectedAccount, options = {}) {
|
|
475
|
-
const
|
|
476
|
-
const
|
|
500
|
+
const managedIdentity = Boolean(options.appMode) && usesManagedIdentity();
|
|
501
|
+
const secrets = managedIdentity ? managedIdentitySecrets() : await getSecrets();
|
|
502
|
+
const config = createMsalConfig(
|
|
503
|
+
managedIdentity && !secrets.clientId ? { ...secrets, clientId: "00000000-0000-0000-0000-000000000000" } : secrets
|
|
504
|
+
);
|
|
477
505
|
const storage = options.storage ?? await createTokenCacheStorage({ allowCommandStorage: false, logProvider: true });
|
|
478
|
-
|
|
506
|
+
const authManager = new AuthManager(config, scopes, expectedAccount, storage);
|
|
507
|
+
if (options.appMode) {
|
|
508
|
+
authManager.appClient = new AppTokenClient(secrets);
|
|
509
|
+
authManager.appSecrets = secrets;
|
|
510
|
+
}
|
|
511
|
+
return authManager;
|
|
512
|
+
}
|
|
513
|
+
isAppMode() {
|
|
514
|
+
return this.appClient !== null;
|
|
515
|
+
}
|
|
516
|
+
/** The secrets app mode was set up with, so the server does not load them a second way. */
|
|
517
|
+
getAppSecrets() {
|
|
518
|
+
return this.appSecrets;
|
|
479
519
|
}
|
|
480
520
|
async loadTokenCache() {
|
|
481
521
|
try {
|
|
@@ -749,6 +789,9 @@ class AuthManager {
|
|
|
749
789
|
this.isOAuthMode = true;
|
|
750
790
|
}
|
|
751
791
|
async getToken(forceRefresh = false) {
|
|
792
|
+
if (this.appClient) {
|
|
793
|
+
return this.appClient.getToken();
|
|
794
|
+
}
|
|
752
795
|
if (this.isOAuthMode && this.oauthToken) {
|
|
753
796
|
return this.oauthToken;
|
|
754
797
|
}
|
|
@@ -893,6 +936,9 @@ class AuthManager {
|
|
|
893
936
|
return this.selectedAccountId === null || this.selectedAccountId === this.loginPersistence.homeAccountId;
|
|
894
937
|
}
|
|
895
938
|
async testLogin() {
|
|
939
|
+
if (this.appClient) {
|
|
940
|
+
return this.testAppLogin(this.appClient);
|
|
941
|
+
}
|
|
896
942
|
try {
|
|
897
943
|
logger.info("Testing login...");
|
|
898
944
|
if (this.loginPersistence && this.loginPersistenceAppliesToCurrentAccount()) {
|
|
@@ -949,6 +995,18 @@ class AuthManager {
|
|
|
949
995
|
};
|
|
950
996
|
}
|
|
951
997
|
}
|
|
998
|
+
// No /me for an app token: report the roles claim instead. It is empty for an app that only
|
|
999
|
+
// has Exchange RBAC for Applications grants, so an empty one is a hint, not a failure.
|
|
1000
|
+
async testAppLogin(appClient) {
|
|
1001
|
+
try {
|
|
1002
|
+
const appData = describeAppToken(await appClient.getToken());
|
|
1003
|
+
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.";
|
|
1004
|
+
return { success: true, message, appData };
|
|
1005
|
+
} catch (error) {
|
|
1006
|
+
logger.error(`App token request failed: ${describeAuthError(error)}`);
|
|
1007
|
+
return { success: false, message: `App token request failed: ${error.message}` };
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
952
1010
|
async logout() {
|
|
953
1011
|
try {
|
|
954
1012
|
const accounts = await this.msalApp.getTokenCache().getAllAccounts();
|
|
@@ -1045,7 +1103,7 @@ class AuthManager {
|
|
|
1045
1103
|
* Used to decide whether to inject the `account` parameter into tool schemas.
|
|
1046
1104
|
*/
|
|
1047
1105
|
async isMultiAccount() {
|
|
1048
|
-
if (this.hasExpectedAccount()) {
|
|
1106
|
+
if (this.appClient || this.hasExpectedAccount()) {
|
|
1049
1107
|
return false;
|
|
1050
1108
|
}
|
|
1051
1109
|
const accounts = await this.msalApp.getTokenCache().getAllAccounts();
|
|
@@ -1064,6 +1122,14 @@ class AuthManager {
|
|
|
1064
1122
|
* @returns The access token string.
|
|
1065
1123
|
*/
|
|
1066
1124
|
async getTokenForAccount(identifier) {
|
|
1125
|
+
if (this.appClient) {
|
|
1126
|
+
if (identifier) {
|
|
1127
|
+
throw new Error(
|
|
1128
|
+
`Cannot switch to account '${identifier}': the server is in app mode and has no signed-in accounts.`
|
|
1129
|
+
);
|
|
1130
|
+
}
|
|
1131
|
+
return this.appClient.getToken();
|
|
1132
|
+
}
|
|
1067
1133
|
if (this.isOAuthMode && this.oauthToken) {
|
|
1068
1134
|
if (identifier) {
|
|
1069
1135
|
throw new Error(
|
|
@@ -1140,10 +1206,12 @@ export {
|
|
|
1140
1206
|
getMissingAllowedScopesForGroups,
|
|
1141
1207
|
getSelectedAccountPath,
|
|
1142
1208
|
getTokenCachePath,
|
|
1209
|
+
isEndpointInScopeMode,
|
|
1143
1210
|
parseAllowedScopes,
|
|
1144
1211
|
pickNewest,
|
|
1145
1212
|
resetRefreshTokenWarningsForTests,
|
|
1146
1213
|
resolveAuthScopes,
|
|
1214
|
+
scopeModeFor,
|
|
1147
1215
|
unwrapCache,
|
|
1148
1216
|
wrapCache
|
|
1149
1217
|
};
|