@mcp-z/mcp-outlook 2.4.1 → 2.4.2
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 +5 -1
- package/dist/cjs/constants.d.cts +1 -0
- package/dist/cjs/constants.d.ts +1 -0
- package/dist/cjs/constants.js +4 -0
- package/dist/cjs/constants.js.map +1 -1
- package/dist/cjs/lib/create-store.js +1 -1
- package/dist/cjs/lib/create-store.js.map +1 -1
- package/dist/cjs/setup/config.d.cts +2 -6
- package/dist/cjs/setup/config.d.ts +2 -6
- package/dist/cjs/setup/config.js +22 -0
- package/dist/cjs/setup/config.js.map +1 -1
- package/dist/cjs/setup/http.js +2 -1
- package/dist/cjs/setup/http.js.map +1 -1
- package/dist/cjs/setup/oauth-microsoft.d.cts +6 -1
- package/dist/cjs/setup/oauth-microsoft.d.ts +6 -1
- package/dist/cjs/setup/oauth-microsoft.js +5 -1
- package/dist/cjs/setup/oauth-microsoft.js.map +1 -1
- package/dist/cjs/setup/runtime.d.cts +1 -1
- package/dist/cjs/setup/runtime.d.ts +1 -1
- package/dist/cjs/setup/runtime.js +11 -6
- package/dist/cjs/setup/runtime.js.map +1 -1
- package/dist/cjs/setup/version-help.js +1 -1
- package/dist/cjs/setup/version-help.js.map +1 -1
- package/dist/esm/constants.d.ts +1 -0
- package/dist/esm/constants.js +2 -0
- package/dist/esm/constants.js.map +1 -1
- package/dist/esm/lib/create-store.js +1 -1
- package/dist/esm/lib/create-store.js.map +1 -1
- package/dist/esm/setup/config.d.ts +2 -6
- package/dist/esm/setup/config.js +24 -6
- package/dist/esm/setup/config.js.map +1 -1
- package/dist/esm/setup/http.js +2 -1
- package/dist/esm/setup/http.js.map +1 -1
- package/dist/esm/setup/oauth-microsoft.d.ts +6 -1
- package/dist/esm/setup/oauth-microsoft.js +6 -2
- package/dist/esm/setup/oauth-microsoft.js.map +1 -1
- package/dist/esm/setup/runtime.d.ts +1 -1
- package/dist/esm/setup/runtime.js +11 -5
- package/dist/esm/setup/runtime.js.map +1 -1
- package/dist/esm/setup/version-help.js +3 -7
- package/dist/esm/setup/version-help.js.map +1 -1
- package/package.json +10 -4
package/README.md
CHANGED
|
@@ -173,6 +173,10 @@ HTTP only. Requires a public base URL. CSV export and `/files` are disabled in D
|
|
|
173
173
|
}
|
|
174
174
|
```
|
|
175
175
|
|
|
176
|
+
In `--auth=dcr` mode, every request to `/mcp` needs a bearer token issued by the server's own `/oauth/register` and `/oauth/authorize` flow; a request without a valid one gets 401 with a `WWW-Authenticate` challenge that points clients to it.
|
|
177
|
+
|
|
178
|
+
In `--auth=dcr` mode, `/oauth/register` accepts anonymous registrations with no limit, and stored registrations do not expire. If you expose the server to the internet, limit that endpoint in your reverse proxy.
|
|
179
|
+
|
|
176
180
|
## How to use
|
|
177
181
|
|
|
178
182
|
```bash
|
|
@@ -214,7 +218,7 @@ See [`server.json`](https://github.com/mcp-z/mcp-outlook/blob/master/server.json
|
|
|
214
218
|
|
|
215
219
|
OAuth tokens (`TOKEN_STORE_URI`) and DCR registrations (`DCR_STORE_URI`) are stored through [keyv-registry](https://www.npmjs.com/package/keyv-registry), which picks an adapter from the URI protocol.
|
|
216
220
|
|
|
217
|
-
`file://`
|
|
221
|
+
The default is a JSON file under `~/.mcp-z/` (`file+shared://`), written under a lock so several mcp-z servers and the cli can share `.mcp-z/tokens.json` without undoing each other's sign-ins; upgrade them together, because an older one still rewrites the whole file. `file://` (keyv-file) and `memory://` also work with no extra setup.
|
|
218
222
|
|
|
219
223
|
Any other backend needs its adapter installed alongside this server. Adapters are resolved with `require()`, so a globally installed server finds a globally installed adapter:
|
|
220
224
|
|
package/dist/cjs/constants.d.cts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* rather than externally configured since this server knows its own requirements.
|
|
6
6
|
*/
|
|
7
7
|
export declare const MS_SCOPE = "openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite";
|
|
8
|
+
export declare const SHARED_FILE_PROTOCOL = "file+shared:";
|
|
8
9
|
export declare const CHUNK_SIZE = 10;
|
|
9
10
|
export declare const MAX_BATCH_SIZE = 500;
|
|
10
11
|
export declare const MAX_PAGE_SIZE = 1000;
|
package/dist/cjs/constants.d.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* rather than externally configured since this server knows its own requirements.
|
|
6
6
|
*/
|
|
7
7
|
export declare const MS_SCOPE = "openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite";
|
|
8
|
+
export declare const SHARED_FILE_PROTOCOL = "file+shared:";
|
|
8
9
|
export declare const CHUNK_SIZE = 10;
|
|
9
10
|
export declare const MAX_BATCH_SIZE = 500;
|
|
10
11
|
export declare const MAX_PAGE_SIZE = 1000;
|
package/dist/cjs/constants.js
CHANGED
|
@@ -25,10 +25,14 @@ _export(exports, {
|
|
|
25
25
|
},
|
|
26
26
|
get MS_SCOPE () {
|
|
27
27
|
return MS_SCOPE;
|
|
28
|
+
},
|
|
29
|
+
get SHARED_FILE_PROTOCOL () {
|
|
30
|
+
return SHARED_FILE_PROTOCOL;
|
|
28
31
|
}
|
|
29
32
|
});
|
|
30
33
|
var _email = require("@mcp-z/email");
|
|
31
34
|
var MS_SCOPE = 'openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite';
|
|
35
|
+
var SHARED_FILE_PROTOCOL = 'file+shared:';
|
|
32
36
|
var CHUNK_SIZE = _email.EMAIL_CHUNK_SIZE;
|
|
33
37
|
var MAX_BATCH_SIZE = _email.EMAIL_MAX_BATCH_SIZE;
|
|
34
38
|
var MAX_PAGE_SIZE = 1000; // Maximum number of items per page
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/constants.ts"],"sourcesContent":["/**\n * Outlook MCP Server Constants\n *\n * These scopes are required for Microsoft Outlook functionality and are hardcoded\n * rather than externally configured since this server knows its own requirements.\n */\n\nimport { EMAIL_CHUNK_SIZE, EMAIL_MAX_BATCH_SIZE } from '@mcp-z/email';\n\n// Microsoft OAuth scopes required for Outlook operations\nexport const MS_SCOPE = 'openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite';\n\n// Batch processing configuration (from shared email constants)\nexport const CHUNK_SIZE = EMAIL_CHUNK_SIZE;\nexport const MAX_BATCH_SIZE = EMAIL_MAX_BATCH_SIZE;\n\n// Pagination configuration\nexport const MAX_PAGE_SIZE = 1000; // Maximum number of items per page\n"],"names":["CHUNK_SIZE","MAX_BATCH_SIZE","MAX_PAGE_SIZE","MS_SCOPE","EMAIL_CHUNK_SIZE","EMAIL_MAX_BATCH_SIZE"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/constants.ts"],"sourcesContent":["/**\n * Outlook MCP Server Constants\n *\n * These scopes are required for Microsoft Outlook functionality and are hardcoded\n * rather than externally configured since this server knows its own requirements.\n */\n\nimport { EMAIL_CHUNK_SIZE, EMAIL_MAX_BATCH_SIZE } from '@mcp-z/email';\n\n// Microsoft OAuth scopes required for Outlook operations\nexport const MS_SCOPE = 'openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite';\n\n// Default token and DCR stores: a JSON file several processes can share\nexport const SHARED_FILE_PROTOCOL = 'file+shared:';\n\n// Batch processing configuration (from shared email constants)\nexport const CHUNK_SIZE = EMAIL_CHUNK_SIZE;\nexport const MAX_BATCH_SIZE = EMAIL_MAX_BATCH_SIZE;\n\n// Pagination configuration\nexport const MAX_PAGE_SIZE = 1000; // Maximum number of items per page\n"],"names":["CHUNK_SIZE","MAX_BATCH_SIZE","MAX_PAGE_SIZE","MS_SCOPE","SHARED_FILE_PROTOCOL","EMAIL_CHUNK_SIZE","EMAIL_MAX_BATCH_SIZE"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;QAWYA;eAAAA;;QACAC;eAAAA;;QAGAC;eAAAA;;QAVAC;eAAAA;;QAGAC;eAAAA;;;qBAN0C;AAGhD,IAAMD,WAAW;AAGjB,IAAMC,uBAAuB;AAG7B,IAAMJ,aAAaK,uBAAgB;AACnC,IAAMJ,iBAAiBK,2BAAoB;AAG3C,IAAMJ,gBAAgB,MAAM,mCAAmC"}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", {
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
|
-
Object.defineProperty(exports, // keyv-file is a direct dependency so
|
|
5
|
+
Object.defineProperty(exports, // keyv-file is a direct dependency so explicit file:// URIs resolve; keyv-registry
|
|
6
6
|
// loads adapters with require() rather than depending on any of them itself.
|
|
7
7
|
"default", {
|
|
8
8
|
enumerable: true,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/lib/create-store.ts"],"sourcesContent":["import type { Logger } from '@mcp-z/server';\nimport type Keyv from 'keyv';\nimport keyvRegistry, { migrateKeyv5Keys } from 'keyv-registry';\n\n// keyv-file is a direct dependency so
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/lib/create-store.ts"],"sourcesContent":["import type { Logger } from '@mcp-z/server';\nimport type Keyv from 'keyv';\nimport keyvRegistry, { migrateKeyv5Keys } from 'keyv-registry';\n\n// keyv-file is a direct dependency so explicit file:// URIs resolve; keyv-registry\n// loads adapters with require() rather than depending on any of them itself.\n\nexport default async function createStore<T>(uri: string, logger: Logger): Promise<Keyv<T>> {\n const store = await keyvRegistry<T>(uri);\n // Name only the protocol: the URI can hold a password.\n if (!store) throw new Error(`Failed to create store for protocol: ${uri.split(':')[0]}:`);\n // Saved sign-ins written by keyv 5 sit under old keys; move them once. The URI is never logged.\n try {\n const moved = await migrateKeyv5Keys(store as Keyv);\n if (moved > 0) logger.info(`Moved ${moved} saved sign-in entries to the keyv 6 format`);\n } catch (error) {\n // Keep the migration error as the one reported, even if closing the store fails too.\n await store.disconnect().catch(() => {});\n throw error;\n }\n return store;\n}\n"],"names":["createStore","uri","logger","store","moved","error","keyvRegistry","Error","split","migrateKeyv5Keys","info","disconnect","catch"],"mappings":";;;;+BAIA,mFAAmF;AACnF,6EAA6E;AAE7E;;;eAA8BA;;;oEALiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKhC,SAAeA,YAAeC,GAAW,EAAEC,MAAc;;YAChEC,OAKEC,OAECC;;;;oBAPK;;wBAAMC,IAAAA,qBAAY,EAAIL;;;oBAA9BE,QAAQ;oBACd,uDAAuD;oBACvD,IAAI,CAACA,OAAO,MAAM,IAAII,MAAM,AAAC,wCAAyD,OAAlBN,IAAIO,KAAK,CAAC,IAAI,CAAC,EAAE,EAAC;;;;;;;;;oBAGtE;;wBAAMC,IAAAA,8BAAgB,EAACN;;;oBAA/BC,QAAQ;oBACd,IAAIA,QAAQ,GAAGF,OAAOQ,IAAI,CAAC,AAAC,SAAc,OAANN,OAAM;;;;;;oBACnCC;oBACP,qFAAqF;oBACrF;;wBAAMF,MAAMQ,UAAU,GAAGC,KAAK,CAAC,YAAO;;;oBAAtC;oBACA,MAAMP;;oBAER;;wBAAOF;;;;IACT"}
|
|
@@ -8,13 +8,11 @@ import type { ServerConfig } from '../types.js';
|
|
|
8
8
|
* - --headless Disable browser auto-open, return auth URL instead
|
|
9
9
|
* - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)
|
|
10
10
|
* - --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)
|
|
11
|
-
* - --dcr-
|
|
12
|
-
* - --dcr-verify-url=<url> External verification endpoint (required for external mode)
|
|
13
|
-
* - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)
|
|
11
|
+
* - --dcr-store-uri=<uri> DCR client storage URI (default: .mcp-z/dcr.json)
|
|
14
12
|
* - --port=<port> Enable HTTP transport on specified port
|
|
15
13
|
* - --stdio Enable stdio transport (default if no port)
|
|
16
14
|
* - --log-level=<level> Logging level (default: info)
|
|
17
|
-
* - --resource-store-uri=<uri> Resource store URI for CSV file storage (default:
|
|
15
|
+
* - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: .mcp-z/mcp-outlook/files beside the nearest .mcp.json, else ~/.mcp-z/mcp-outlook/files)
|
|
18
16
|
* - --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)
|
|
19
17
|
*
|
|
20
18
|
* Environment Variables:
|
|
@@ -23,8 +21,6 @@ import type { ServerConfig } from '../types.js';
|
|
|
23
21
|
* - MS_CLIENT_SECRET OAuth client secret (optional)
|
|
24
22
|
* - AUTH_MODE Default authentication mode (optional)
|
|
25
23
|
* - HEADLESS Disable browser auto-open (optional)
|
|
26
|
-
* - DCR_MODE DCR mode (optional, same format as --dcr-mode)
|
|
27
|
-
* - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)
|
|
28
24
|
* - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)
|
|
29
25
|
* - TOKEN_STORE_URI Token storage URI (optional)
|
|
30
26
|
* - PORT Default HTTP port (optional)
|
|
@@ -8,13 +8,11 @@ import type { ServerConfig } from '../types.js';
|
|
|
8
8
|
* - --headless Disable browser auto-open, return auth URL instead
|
|
9
9
|
* - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)
|
|
10
10
|
* - --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)
|
|
11
|
-
* - --dcr-
|
|
12
|
-
* - --dcr-verify-url=<url> External verification endpoint (required for external mode)
|
|
13
|
-
* - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)
|
|
11
|
+
* - --dcr-store-uri=<uri> DCR client storage URI (default: .mcp-z/dcr.json)
|
|
14
12
|
* - --port=<port> Enable HTTP transport on specified port
|
|
15
13
|
* - --stdio Enable stdio transport (default if no port)
|
|
16
14
|
* - --log-level=<level> Logging level (default: info)
|
|
17
|
-
* - --resource-store-uri=<uri> Resource store URI for CSV file storage (default:
|
|
15
|
+
* - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: .mcp-z/mcp-outlook/files beside the nearest .mcp.json, else ~/.mcp-z/mcp-outlook/files)
|
|
18
16
|
* - --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)
|
|
19
17
|
*
|
|
20
18
|
* Environment Variables:
|
|
@@ -23,8 +21,6 @@ import type { ServerConfig } from '../types.js';
|
|
|
23
21
|
* - MS_CLIENT_SECRET OAuth client secret (optional)
|
|
24
22
|
* - AUTH_MODE Default authentication mode (optional)
|
|
25
23
|
* - HEADLESS Disable browser auto-open (optional)
|
|
26
|
-
* - DCR_MODE DCR mode (optional, same format as --dcr-mode)
|
|
27
|
-
* - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)
|
|
28
24
|
* - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)
|
|
29
25
|
* - TOKEN_STORE_URI Token storage URI (optional)
|
|
30
26
|
* - PORT Default HTTP port (optional)
|
package/dist/cjs/setup/config.js
CHANGED
|
@@ -117,6 +117,7 @@ function parseConfig(args, env) {
|
|
|
117
117
|
var mcpServer = _require('@mcp-z/server');
|
|
118
118
|
var transportConfig = mcpServer.parseConfig(args, env);
|
|
119
119
|
var oauthConfig = oauthMicrosoft.parseConfig(args, env);
|
|
120
|
+
if (oauthConfig.auth === 'dcr') rejectExternalDcr(args, env);
|
|
120
121
|
// Parse DCR configuration if DCR mode is enabled
|
|
121
122
|
var dcrConfig = oauthConfig.auth === 'dcr' ? oauthMicrosoft.parseDcrConfig(args, env, _constantsts.MS_SCOPE) : undefined;
|
|
122
123
|
// Parse application-level config (LOG_LEVEL, RESOURCE_STORE_URI, BASE_URL)
|
|
@@ -191,6 +192,27 @@ function createConfig() {
|
|
|
191
192
|
throw new Error("".concat(error.message, "\n").concat(mcpServer.formatServerEnvSearch(envResult)));
|
|
192
193
|
}
|
|
193
194
|
}
|
|
195
|
+
// With --auth=dcr the server always runs its own sign-in endpoints; the external-mode settings never had an effect, so they are refused rather than ignored there. Other auth modes never read them.
|
|
196
|
+
function rejectExternalDcr(args, env) {
|
|
197
|
+
var values = (0, _util.parseArgs)({
|
|
198
|
+
args: args,
|
|
199
|
+
options: {
|
|
200
|
+
'dcr-mode': {
|
|
201
|
+
type: 'string'
|
|
202
|
+
},
|
|
203
|
+
'dcr-verify-url': {
|
|
204
|
+
type: 'string'
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
strict: false,
|
|
208
|
+
allowPositionals: true
|
|
209
|
+
}).values;
|
|
210
|
+
var mode = (typeof values['dcr-mode'] === 'string' ? values['dcr-mode'] : undefined) || env.DCR_MODE;
|
|
211
|
+
if (mode === 'external') throw new Error('external DCR mode is not supported: the server runs its own sign-in endpoints (use --dcr-mode=self-hosted or leave it unset)');
|
|
212
|
+
if (mode && mode !== 'self-hosted') throw new Error('Invalid DCR mode "'.concat(mode, '": only self-hosted is supported'));
|
|
213
|
+
var verifyUrl = typeof values['dcr-verify-url'] === 'string' ? values['dcr-verify-url'] : env.DCR_VERIFY_URL;
|
|
214
|
+
if (verifyUrl) throw new Error('--dcr-verify-url / DCR_VERIFY_URL is not supported: the server runs its own sign-in endpoints and verifies tokens itself');
|
|
215
|
+
}
|
|
194
216
|
function normalizeResourceStoreUri(resourceStoreUri) {
|
|
195
217
|
var filePrefix = 'file://';
|
|
196
218
|
if (resourceStoreUri.startsWith(filePrefix)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/config.ts"],"sourcesContent":["import { fileURLToPath, pathToFileURL } from 'node:url';\nimport type * as OAuthMicrosoft from '@mcp-z/oauth-microsoft';\nimport type * as McpServer from '@mcp-z/server';\nimport { Module } from 'module';\nimport { homedir } from 'os';\nimport * as path from 'path';\nimport { parseArgs } from 'util';\nimport { MS_SCOPE } from '../constants.ts';\nimport type { ServerConfig } from '../types.ts';\nimport { readPkg } from './version-help.ts';\n\nconst pkg = readPkg();\nconst SERVER_NAME = pkg.name.replace(/^@[^/]+\\//, '');\n\n// @mcp-z/oauth-microsoft and @mcp-z/server are requireable at the >=20 floor; deferred so\n// --version/--help (handled via version-help.ts, never this file) load neither package.\nconst _require = typeof require === 'undefined' ? Module.createRequire(import.meta.url) : require;\n\n/**\n * Parse Outlook server configuration from CLI arguments and environment.\n *\n * CLI Arguments (all optional):\n * - --auth=<mode> Authentication mode (default: loopback-oauth)\n * Modes: loopback-oauth, device-code, dcr\n * - --headless Disable browser auto-open, return auth URL instead\n * - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n * - --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)\n * - --dcr-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)\n * - --dcr-verify-url=<url> External verification endpoint (required for external mode)\n * - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)\n * - --port=<port> Enable HTTP transport on specified port\n * - --stdio Enable stdio transport (default if no port)\n * - --log-level=<level> Logging level (default: info)\n * - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: file://~/.mcp-z/mcp-outlook/files)\n * - --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)\n *\n * Environment Variables:\n * - MS_CLIENT_ID OAuth client ID (REQUIRED)\n * - MS_TENANT_ID Microsoft tenant ID (REQUIRED)\n * - MS_CLIENT_SECRET OAuth client secret (optional)\n * - AUTH_MODE Default authentication mode (optional)\n * - HEADLESS Disable browser auto-open (optional)\n * - DCR_MODE DCR mode (optional, same format as --dcr-mode)\n * - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)\n * - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n * - TOKEN_STORE_URI Token storage URI (optional)\n * - PORT Default HTTP port (optional)\n * - LOG_LEVEL Default logging level (optional)\n * - RESOURCE_STORE_URI Resource store URI (optional, file://)\n * - BASE_URL Base URL for HTTP file serving (optional)\n *\n * OAuth Scopes (from constants.ts):\n * openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite\n */\nexport function parseConfig(args: string[], env: Record<string, string | undefined>): ServerConfig {\n const oauthMicrosoft = _require('@mcp-z/oauth-microsoft') as typeof OAuthMicrosoft;\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n\n const transportConfig = mcpServer.parseConfig(args, env);\n const oauthConfig = oauthMicrosoft.parseConfig(args, env);\n\n // Parse DCR configuration if DCR mode is enabled\n const dcrConfig = oauthConfig.auth === 'dcr' ? oauthMicrosoft.parseDcrConfig(args, env, MS_SCOPE) : undefined;\n\n // Parse application-level config (LOG_LEVEL, RESOURCE_STORE_URI, BASE_URL)\n const { values } = parseArgs({\n args,\n options: {\n 'log-level': { type: 'string' },\n 'base-url': { type: 'string' },\n 'resource-store-uri': { type: 'string' },\n },\n strict: false, // Allow other arguments\n allowPositionals: true,\n });\n\n const name = SERVER_NAME;\n // Parse repository URL from package.json, stripping git+ prefix and .git suffix\n const rawRepoUrl = typeof pkg.repository === 'object' ? pkg.repository.url : pkg.repository;\n const repositoryUrl = rawRepoUrl?.replace(/^git\\+/, '').replace(/\\.git$/, '') ?? `https://github.com/mcp-z/${name}`;\n const baseDir = resolveBaseDir();\n const cliLogLevel = typeof values['log-level'] === 'string' ? values['log-level'] : undefined;\n const envLogLevel = env.LOG_LEVEL;\n const logLevel = cliLogLevel ?? envLogLevel ?? 'info';\n\n // Parse file storage configuration\n const cliResourceStoreUri = typeof values['resource-store-uri'] === 'string' ? values['resource-store-uri'] : undefined;\n const envResourceStoreUri = env.RESOURCE_STORE_URI;\n const defaultResourceStorePath = path.join(baseDir, name, 'files');\n const resourceStoreUri = normalizeResourceStoreUri(cliResourceStoreUri ?? envResourceStoreUri ?? defaultResourceStorePath);\n\n const cliBaseUrl = typeof values['base-url'] === 'string' ? values['base-url'] : undefined;\n const envBaseUrl = env.BASE_URL;\n const baseUrl = cliBaseUrl ?? envBaseUrl;\n\n // Combine configs\n const result: ServerConfig = {\n ...oauthConfig, // Includes clientId, auth, headless, redirectUri\n transport: transportConfig.transport,\n logLevel,\n baseDir,\n name,\n version: pkg.version,\n repositoryUrl,\n resourceStoreUri,\n };\n if (baseUrl !== undefined) result.baseUrl = baseUrl;\n if (dcrConfig !== undefined) result.dcrConfig = dcrConfig;\n return result;\n}\n\n/** The server's data directory: `.mcp-z` beside the nearest .mcp.json (searched from cwd up to home), else in the home directory. */\nfunction resolveBaseDir(): string {\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n try {\n const configPath = mcpServer.findConfigPath({ config: '.mcp.json', cwd: process.cwd(), stopDir: homedir() });\n return path.join(path.dirname(configPath), '.mcp-z');\n } catch {\n return path.join(homedir(), '.mcp-z');\n }\n}\n\n/**\n * Build production configuration from process globals.\n * Entry point for production server.\n */\nexport function createConfig(): ServerConfig {\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n const envResult = mcpServer.loadServerEnv({ name: SERVER_NAME, baseDir: resolveBaseDir() });\n try {\n return parseConfig(process.argv, process.env);\n } catch (error) {\n throw new Error(`${(error as Error).message}\\n${mcpServer.formatServerEnvSearch(envResult)}`);\n }\n}\n\nfunction normalizeResourceStoreUri(resourceStoreUri: string): string {\n const filePrefix = 'file://';\n if (resourceStoreUri.startsWith(filePrefix)) {\n const rawPath = resourceStoreUri.slice(filePrefix.length);\n const filePath = rawPath.startsWith('~') ? rawPath.replace(/^~/, homedir()) : rawPath.startsWith('/') ? fileURLToPath(resourceStoreUri) : rawPath;\n return pathToFileURL(path.resolve(filePath)).href;\n }\n\n if (resourceStoreUri.includes('://')) return resourceStoreUri;\n\n const expandedPath = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, homedir()) : resourceStoreUri;\n return pathToFileURL(path.resolve(expandedPath)).href;\n}\n"],"names":["createConfig","parseConfig","pkg","readPkg","SERVER_NAME","name","replace","_require","require","Module","createRequire","args","env","cliLogLevel","cliResourceStoreUri","oauthMicrosoft","mcpServer","transportConfig","oauthConfig","dcrConfig","auth","parseDcrConfig","MS_SCOPE","undefined","values","parseArgs","options","type","strict","allowPositionals","rawRepoUrl","repository","url","repositoryUrl","baseDir","resolveBaseDir","envLogLevel","LOG_LEVEL","logLevel","envResourceStoreUri","RESOURCE_STORE_URI","defaultResourceStorePath","path","join","resourceStoreUri","normalizeResourceStoreUri","cliBaseUrl","envBaseUrl","BASE_URL","baseUrl","result","transport","version","configPath","findConfigPath","config","cwd","process","stopDir","homedir","dirname","envResult","loadServerEnv","argv","error","Error","message","formatServerEnvSearch","filePrefix","startsWith","rawPath","slice","length","filePath","fileURLToPath","pathToFileURL","resolve","href","includes","expandedPath"],"mappings":";;;;;;;;;;;QA8HgBA;eAAAA;;QAxEAC;eAAAA;;;uBAtD6B;sBAGtB;kBACC;4DACF;oBACI;2BACD;6BAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,IAAMC,MAAMC,IAAAA,sBAAO;AACnB,IAAMC,cAAcF,IAAIG,IAAI,CA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AG;IAC9C,EAAE,OAAOoD,OAAO;QACd,MAAM,IAAIC,MAAM,AAAC,GAA+BjD,OAA7B,AAACgD,MAAgBE,OAAO,EAAC,MAA+C,OAA3ClD,UAAUmD,qBAAqB,CAACN;IAClF;AACF;AAEA,SAAShB,0BAA0BD,gBAAwB;IACzD,IAAMwB,aAAa;IACnB,IAAIxB,iBAAiByB,UAAU,CAACD,aAAa;QAC3C,IAAME,UAAU1B,iBAAiB2B,KAAK,CAACH,WAAWI,MAAM;QACxD,IAAMC,WAAWH,QAAQD,UAAU,CAAC,OAAOC,QAAQhE,OAAO,CAAC,MAAMqD,IAAAA,WAAO,OAAMW,QAAQD,UAAU,CAAC,OAAOK,IAAAA,sBAAa,EAAC9B,oBAAoB0B;QAC1I,OAAOK,IAAAA,sBAAa,EAACjC,MAAKkC,OAAO,CAACH,WAAWI,IAAI;IACnD;IAEA,IAAIjC,iBAAiBkC,QAAQ,CAAC,QAAQ,OAAOlC;IAE7C,IAAMmC,eAAenC,iBAAiByB,UAAU,CAAC,OAAOzB,iBAAiBtC,OAAO,CAAC,MAAMqD,IAAAA,WAAO,OAAMf;IACpG,OAAO+B,IAAAA,sBAAa,EAACjC,MAAKkC,OAAO,CAACG,eAAeF,IAAI;AACvD"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/config.ts"],"sourcesContent":["import { fileURLToPath, pathToFileURL } from 'node:url';\nimport type * as OAuthMicrosoft from '@mcp-z/oauth-microsoft';\nimport type * as McpServer from '@mcp-z/server';\nimport { Module } from 'module';\nimport { homedir } from 'os';\nimport * as path from 'path';\nimport { parseArgs } from 'util';\nimport { MS_SCOPE } from '../constants.ts';\nimport type { ServerConfig } from '../types.ts';\nimport { readPkg } from './version-help.ts';\n\nconst pkg = readPkg();\nconst SERVER_NAME = pkg.name.replace(/^@[^/]+\\//, '');\n\n// @mcp-z/oauth-microsoft and @mcp-z/server are requireable at the >=20 floor; deferred so\n// --version/--help (handled via version-help.ts, never this file) load neither package.\nconst _require = typeof require === 'undefined' ? Module.createRequire(import.meta.url) : require;\n\n/**\n * Parse Outlook server configuration from CLI arguments and environment.\n *\n * CLI Arguments (all optional):\n * - --auth=<mode> Authentication mode (default: loopback-oauth)\n * Modes: loopback-oauth, device-code, dcr\n * - --headless Disable browser auto-open, return auth URL instead\n * - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n * - --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)\n * - --dcr-store-uri=<uri> DCR client storage URI (default: .mcp-z/dcr.json)\n * - --port=<port> Enable HTTP transport on specified port\n * - --stdio Enable stdio transport (default if no port)\n * - --log-level=<level> Logging level (default: info)\n * - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: .mcp-z/mcp-outlook/files beside the nearest .mcp.json, else ~/.mcp-z/mcp-outlook/files)\n * - --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)\n *\n * Environment Variables:\n * - MS_CLIENT_ID OAuth client ID (REQUIRED)\n * - MS_TENANT_ID Microsoft tenant ID (REQUIRED)\n * - MS_CLIENT_SECRET OAuth client secret (optional)\n * - AUTH_MODE Default authentication mode (optional)\n * - HEADLESS Disable browser auto-open (optional)\n * - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n * - TOKEN_STORE_URI Token storage URI (optional)\n * - PORT Default HTTP port (optional)\n * - LOG_LEVEL Default logging level (optional)\n * - RESOURCE_STORE_URI Resource store URI (optional, file://)\n * - BASE_URL Base URL for HTTP file serving (optional)\n *\n * OAuth Scopes (from constants.ts):\n * openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite\n */\nexport function parseConfig(args: string[], env: Record<string, string | undefined>): ServerConfig {\n const oauthMicrosoft = _require('@mcp-z/oauth-microsoft') as typeof OAuthMicrosoft;\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n\n const transportConfig = mcpServer.parseConfig(args, env);\n const oauthConfig = oauthMicrosoft.parseConfig(args, env);\n\n if (oauthConfig.auth === 'dcr') rejectExternalDcr(args, env);\n\n // Parse DCR configuration if DCR mode is enabled\n const dcrConfig = oauthConfig.auth === 'dcr' ? oauthMicrosoft.parseDcrConfig(args, env, MS_SCOPE) : undefined;\n\n // Parse application-level config (LOG_LEVEL, RESOURCE_STORE_URI, BASE_URL)\n const { values } = parseArgs({\n args,\n options: {\n 'log-level': { type: 'string' },\n 'base-url': { type: 'string' },\n 'resource-store-uri': { type: 'string' },\n },\n strict: false, // Allow other arguments\n allowPositionals: true,\n });\n\n const name = SERVER_NAME;\n // Parse repository URL from package.json, stripping git+ prefix and .git suffix\n const rawRepoUrl = typeof pkg.repository === 'object' ? pkg.repository.url : pkg.repository;\n const repositoryUrl = rawRepoUrl?.replace(/^git\\+/, '').replace(/\\.git$/, '') ?? `https://github.com/mcp-z/${name}`;\n const baseDir = resolveBaseDir();\n const cliLogLevel = typeof values['log-level'] === 'string' ? values['log-level'] : undefined;\n const envLogLevel = env.LOG_LEVEL;\n const logLevel = cliLogLevel ?? envLogLevel ?? 'info';\n\n // Parse file storage configuration\n const cliResourceStoreUri = typeof values['resource-store-uri'] === 'string' ? values['resource-store-uri'] : undefined;\n const envResourceStoreUri = env.RESOURCE_STORE_URI;\n const defaultResourceStorePath = path.join(baseDir, name, 'files');\n const resourceStoreUri = normalizeResourceStoreUri(cliResourceStoreUri ?? envResourceStoreUri ?? defaultResourceStorePath);\n\n const cliBaseUrl = typeof values['base-url'] === 'string' ? values['base-url'] : undefined;\n const envBaseUrl = env.BASE_URL;\n const baseUrl = cliBaseUrl ?? envBaseUrl;\n\n // Combine configs\n const result: ServerConfig = {\n ...oauthConfig, // Includes clientId, auth, headless, redirectUri\n transport: transportConfig.transport,\n logLevel,\n baseDir,\n name,\n version: pkg.version,\n repositoryUrl,\n resourceStoreUri,\n };\n if (baseUrl !== undefined) result.baseUrl = baseUrl;\n if (dcrConfig !== undefined) result.dcrConfig = dcrConfig;\n return result;\n}\n\n/** The server's data directory: `.mcp-z` beside the nearest .mcp.json (searched from cwd up to home), else in the home directory. */\nfunction resolveBaseDir(): string {\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n try {\n const configPath = mcpServer.findConfigPath({ config: '.mcp.json', cwd: process.cwd(), stopDir: homedir() });\n return path.join(path.dirname(configPath), '.mcp-z');\n } catch {\n return path.join(homedir(), '.mcp-z');\n }\n}\n\n/**\n * Build production configuration from process globals.\n * Entry point for production server.\n */\nexport function createConfig(): ServerConfig {\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n const envResult = mcpServer.loadServerEnv({ name: SERVER_NAME, baseDir: resolveBaseDir() });\n try {\n return parseConfig(process.argv, process.env);\n } catch (error) {\n throw new Error(`${(error as Error).message}\\n${mcpServer.formatServerEnvSearch(envResult)}`);\n }\n}\n\n// With --auth=dcr the server always runs its own sign-in endpoints; the external-mode settings never had an effect, so they are refused rather than ignored there. Other auth modes never read them.\nfunction rejectExternalDcr(args: string[], env: Record<string, string | undefined>): void {\n const { values } = parseArgs({ args, options: { 'dcr-mode': { type: 'string' }, 'dcr-verify-url': { type: 'string' } }, strict: false, allowPositionals: true });\n const mode = (typeof values['dcr-mode'] === 'string' ? values['dcr-mode'] : undefined) || env.DCR_MODE;\n if (mode === 'external') throw new Error('external DCR mode is not supported: the server runs its own sign-in endpoints (use --dcr-mode=self-hosted or leave it unset)');\n if (mode && mode !== 'self-hosted') throw new Error(`Invalid DCR mode \"${mode}\": only self-hosted is supported`);\n const verifyUrl = typeof values['dcr-verify-url'] === 'string' ? values['dcr-verify-url'] : env.DCR_VERIFY_URL;\n if (verifyUrl) throw new Error('--dcr-verify-url / DCR_VERIFY_URL is not supported: the server runs its own sign-in endpoints and verifies tokens itself');\n}\n\nfunction normalizeResourceStoreUri(resourceStoreUri: string): string {\n const filePrefix = 'file://';\n if (resourceStoreUri.startsWith(filePrefix)) {\n const rawPath = resourceStoreUri.slice(filePrefix.length);\n const filePath = rawPath.startsWith('~') ? rawPath.replace(/^~/, homedir()) : rawPath.startsWith('/') ? fileURLToPath(resourceStoreUri) : rawPath;\n return pathToFileURL(path.resolve(filePath)).href;\n }\n\n if (resourceStoreUri.includes('://')) return resourceStoreUri;\n\n const expandedPath = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, homedir()) : resourceStoreUri;\n return pathToFileURL(path.resolve(expandedPath)).href;\n}\n"],"names":["createConfig","parseConfig","pkg","readPkg","SERVER_NAME","name","replace","_require","require","Module","createRequire","args","env","cliLogLevel","cliResourceStoreUri","oauthMicrosoft","mcpServer","transportConfig","oauthConfig","auth","rejectExternalDcr","dcrConfig","parseDcrConfig","MS_SCOPE","undefined","values","parseArgs","options","type","strict","allowPositionals","rawRepoUrl","repository","url","repositoryUrl","baseDir","resolveBaseDir","envLogLevel","LOG_LEVEL","logLevel","envResourceStoreUri","RESOURCE_STORE_URI","defaultResourceStorePath","path","join","resourceStoreUri","normalizeResourceStoreUri","cliBaseUrl","envBaseUrl","BASE_URL","baseUrl","result","transport","version","configPath","findConfigPath","config","cwd","process","stopDir","homedir","dirname","envResult","loadServerEnv","argv","error","Error","message","formatServerEnvSearch","mode","DCR_MODE","verifyUrl","DCR_VERIFY_URL","filePrefix","startsWith","rawPath","slice","length","filePath","fileURLToPath","pathToFileURL","resolve","href","includes","expandedPath"],"mappings":";;;;;;;;;;;QA4HgBA;eAAAA;;QA1EAC;eAAAA;;;uBAlD6B;sBAGtB;kBACC;4DACF;oBACI;2BACD;6BAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,IAAMC,MAAMC,IAAAA,sBAAO;AACnB,IAAMC,cAAcF,IAAIG,IAAI,CAACC,OAAO,CAAC,aAAa;AAElD,0FAA0F;AAC1F,wFAAwF;AACxF,IAAMC,WAAW,OAAOC,Y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C,eAAevC,iBAAiB6B,UAAU,CAAC,OAAO7B,iBAAiBvC,OAAO,CAAC,MAAMsD,IAAAA,WAAO,OAAMf;IACpG,OAAOmC,IAAAA,sBAAa,EAACrC,MAAKsC,OAAO,CAACG,eAAeF,IAAI;AACvD"}
|
package/dist/cjs/setup/http.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/http.ts"],"sourcesContent":["import { composeMiddleware, connectHttp, createFileServingRouter, defaultCacheHints, McpServer, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport cors from 'cors';\nimport express from 'express';\nimport type { RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createDefaultRuntime } from './runtime.ts';\n\nexport async function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides) {\n const runtime = await createDefaultRuntime(config, overrides);\n const modules = runtime.createDomainModules();\n const layers = runtime.middlewareFactories.map((factory) => factory(runtime.deps));\n const composed = composeMiddleware(modules, layers);\n const logger = runtime.deps.logger;\n const port = config.transport.port;\n if (!port) throw new Error('Port is required for HTTP transport');\n\n const tools = [...composed.tools, ...runtime.deps.oauthAdapters.accountTools];\n const filteredTools =\n config.auth === 'dcr'\n ? tools.filter((tool) => tool.name !== 'messages-export-csv') // No file storage in DCR (public cloud responsibility)\n : tools;\n const prompts = [...composed.prompts, ...runtime.deps.oauthAdapters.accountPrompts];\n\n // Built per request (HTTP) and per connection (stdio), not shared. The SDK caches the\n // negotiated protocol revision on the McpServer instance - its own docs say a negotiated\n // session never re-routes a method onto the other era - so one shared instance pins itself\n // to whichever revision reaches it first and answers the other with -32601.\n const buildServer = () => {\n const mcpServer = new McpServer({ name: config.name, version: config.version }, { cacheHints: defaultCacheHints });\n registerTools(mcpServer, filteredTools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n return mcpServer;\n };\n\n const app = express();\n app.use(express.json({ limit: '10mb' }));\n\n // Must mount '/mcp' before any permissive app-level cors(), or that layer answers its\n // preflight first; pass baseUrl's origin/host below or a public deployment 403s itself.\n const publicUrl = config.baseUrl ? new URL(config.baseUrl) : undefined;\n logger.info(`Starting ${config.name} MCP server (http)`);\n const { close, httpServer } = await connectHttp(buildServer, {\n logger,\n app,\n port,\n allowedOrigins: publicUrl ? [publicUrl.origin] : undefined,\n allowedHosts: publicUrl ? [publicUrl.host] : undefined,\n });\n\n // The loopback OAuth callback, the file-export download, and the DCR discovery/\n // registration endpoints are all meant to be reached from a browser on another\n // origin. Keep cors() for them, scoped to their own routes - never in front of '/mcp'.\n if (runtime.deps.oauthAdapters.loopbackRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.loopbackRouter);\n logger.info('Mounted loopback OAuth callback router');\n }\n\n if (config.auth !== 'dcr') {\n const fileRouter = createFileServingRouter({ resourceStoreUri: config.resourceStoreUri }, { contentType: 'text/csv', contentDisposition: 'attachment' });\n app.use('/files', cors(), fileRouter);\n }\n\n if (runtime.deps.oauthAdapters.dcrRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.dcrRouter);\n logger.info('Mounted DCR router with OAuth endpoints');\n }\n\n logger.info('http transport ready');\n\n return {\n httpServer,\n logger,\n close: async () => {\n await close();\n await runtime.close();\n },\n };\n}\n"],"names":["createHTTPServer","config","overrides","runtime","modules","layers","composed","logger","port","tools","filteredTools","prompts","buildServer","app","publicUrl","close","httpServer","fileRouter","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","transport","Error","oauthAdapters","accountTools","auth","filter","tool","name","accountPrompts","mcpServer","McpServer","version","cacheHints","defaultCacheHints","registerTools","registerResources","resources","registerPrompts","express","use","json","limit","baseUrl","URL","undefined","info","connectHttp","allowedOrigins","origin","allowedHosts","host","loopbackRouter","cors","createFileServingRouter","resourceStoreUri","contentType","contentDisposition","dcrRouter"],"mappings":";;;;+BAMsBA;;;eAAAA;;;sBANmI;2DACxI;8DACG;yBAEiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,SAAeA,iBAAiBC,MAAoB,EAAEC,SAA4B;;YACjFC,SACAC,SACAC,QACAC,UACAC,QACAC,MAGAC,OACAC,eAIAC,SAMAC,aAQAC,KAKAC,WAEwB,MAAtBC,OAAOC,
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/http.ts"],"sourcesContent":["import { composeMiddleware, connectHttp, createFileServingRouter, defaultCacheHints, McpServer, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport cors from 'cors';\nimport express from 'express';\nimport type { RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createDefaultRuntime } from './runtime.ts';\n\nexport async function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides) {\n const runtime = await createDefaultRuntime(config, overrides);\n const modules = runtime.createDomainModules();\n const layers = runtime.middlewareFactories.map((factory) => factory(runtime.deps));\n const composed = composeMiddleware(modules, layers);\n const logger = runtime.deps.logger;\n const port = config.transport.port;\n if (!port) throw new Error('Port is required for HTTP transport');\n\n const tools = [...composed.tools, ...runtime.deps.oauthAdapters.accountTools];\n const filteredTools =\n config.auth === 'dcr'\n ? tools.filter((tool) => tool.name !== 'messages-export-csv') // No file storage in DCR (public cloud responsibility)\n : tools;\n const prompts = [...composed.prompts, ...runtime.deps.oauthAdapters.accountPrompts];\n\n // Built per request (HTTP) and per connection (stdio), not shared. The SDK caches the\n // negotiated protocol revision on the McpServer instance - its own docs say a negotiated\n // session never re-routes a method onto the other era - so one shared instance pins itself\n // to whichever revision reaches it first and answers the other with -32601.\n const buildServer = () => {\n const mcpServer = new McpServer({ name: config.name, version: config.version }, { cacheHints: defaultCacheHints });\n registerTools(mcpServer, filteredTools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n return mcpServer;\n };\n\n const app = express();\n app.use(express.json({ limit: '10mb' }));\n\n // Must mount '/mcp' before any permissive app-level cors(), or that layer answers its\n // preflight first; pass baseUrl's origin/host below or a public deployment 403s itself.\n const publicUrl = config.baseUrl ? new URL(config.baseUrl) : undefined;\n logger.info(`Starting ${config.name} MCP server (http)`);\n const { close, httpServer } = await connectHttp(buildServer, {\n logger,\n app,\n port,\n allowedOrigins: publicUrl ? [publicUrl.origin] : undefined,\n allowedHosts: publicUrl ? [publicUrl.host] : undefined,\n bearerAuth: runtime.deps.oauthAdapters.bearerAuth,\n });\n\n // The loopback OAuth callback, the file-export download, and the DCR discovery/\n // registration endpoints are all meant to be reached from a browser on another\n // origin. Keep cors() for them, scoped to their own routes - never in front of '/mcp'.\n if (runtime.deps.oauthAdapters.loopbackRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.loopbackRouter);\n logger.info('Mounted loopback OAuth callback router');\n }\n\n if (config.auth !== 'dcr') {\n const fileRouter = createFileServingRouter({ resourceStoreUri: config.resourceStoreUri }, { contentType: 'text/csv', contentDisposition: 'attachment' });\n app.use('/files', cors(), fileRouter);\n }\n\n if (runtime.deps.oauthAdapters.dcrRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.dcrRouter);\n logger.info('Mounted DCR router with OAuth endpoints');\n }\n\n logger.info('http transport ready');\n\n return {\n httpServer,\n logger,\n close: async () => {\n await close();\n await runtime.close();\n },\n };\n}\n"],"names":["createHTTPServer","config","overrides","runtime","modules","layers","composed","logger","port","tools","filteredTools","prompts","buildServer","app","publicUrl","close","httpServer","fileRouter","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","transport","Error","oauthAdapters","accountTools","auth","filter","tool","name","accountPrompts","mcpServer","McpServer","version","cacheHints","defaultCacheHints","registerTools","registerResources","resources","registerPrompts","express","use","json","limit","baseUrl","URL","undefined","info","connectHttp","allowedOrigins","origin","allowedHosts","host","bearerAuth","loopbackRouter","cors","createFileServingRouter","resourceStoreUri","contentType","contentDisposition","dcrRouter"],"mappings":";;;;+BAMsBA;;;eAAAA;;;sBANmI;2DACxI;8DACG;yBAEiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,SAAeA,iBAAiBC,MAAoB,EAAEC,SAA4B;;YACjFC,SACAC,SACAC,QACAC,UACAC,QACAC,MAGAC,OACAC,eAIAC,SAMAC,aAQAC,KAKAC,WAEwB,MAAtBC,OAAOC,YAkBPC;;;;oBApDQ;;wBAAMC,IAAAA,+BAAoB,EAACjB,QAAQC;;;oBAA7CC,UAAU;oBACVC,UAAUD,QAAQgB,mBAAmB;oBACrCd,SAASF,QAAQiB,mBAAmB,CAACC,GAAG,CAAC,SAACC;+BAAYA,QAAQnB,QAAQoB,IAAI;;oBAC1EjB,WAAWkB,IAAAA,yBAAiB,EAACpB,SAASC;oBACtCE,SAASJ,QAAQoB,IAAI,CAAChB,MAAM;oBAC5BC,OAAOP,OAAOwB,SAAS,CAACjB,IAAI;oBAClC,IAAI,CAACA,MAAM,MAAM,IAAIkB,MAAM;oBAErBjB,QAAQ,AAAC,qBAAGH,SAASG,KAAK,SAAE,qBAAGN,QAAQoB,IAAI,CAACI,aAAa,CAACC,YAAY;oBACtElB,gBACJT,OAAO4B,IAAI,KAAK,QACZpB,MAAMqB,MAAM,CAAC,SAACC;+BAASA,KAAKC,IAAI,KAAK;uBAAuB,uDAAuD;uBACnHvB;oBACAE,UAAU,AAAC,qBAAGL,SAASK,OAAO,SAAE,qBAAGR,QAAQoB,IAAI,CAACI,aAAa,CAACM,cAAc;oBAElF,sFAAsF;oBACtF,yFAAyF;oBACzF,2FAA2F;oBAC3F,4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0C,IAAAA,+BAAuB,EAAC;4BAAEC,kBAAkB3D,OAAO2D,gBAAgB;wBAAC,GAAG;4BAAEC,aAAa;4BAAYC,oBAAoB;wBAAa;wBACtJjD,IAAI+B,GAAG,CAAC,UAAUc,IAAAA,aAAI,KAAIzC;oBAC5B;oBAEA,IAAId,QAAQoB,IAAI,CAACI,aAAa,CAACoC,SAAS,EAAE;wBACxClD,IAAI+B,GAAG,CAAC,KAAKc,IAAAA,aAAI,KAAIvD,QAAQoB,IAAI,CAACI,aAAa,CAACoC,SAAS;wBACzDxD,OAAO2C,IAAI,CAAC;oBACd;oBAEA3C,OAAO2C,IAAI,CAAC;oBAEZ;;wBAAO;4BACLlC,YAAAA;4BACAT,QAAAA;4BACAQ,OAAO,SAAPA;;;;;gDACE;;oDAAMA;;;gDAAN;gDACA;;oDAAMZ,QAAQY,KAAK;;;gDAAnB;;;;;;gCACF;;wBACF;;;;IACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AccountAuthProvider } from '@mcp-z/oauth';
|
|
2
|
-
import { DcrOAuthProvider, DeviceCodeProvider, LoopbackOAuthProvider } from '@mcp-z/oauth-microsoft';
|
|
2
|
+
import { DcrOAuthProvider, DcrTokenVerifier, DeviceCodeProvider, LoopbackOAuthProvider } from '@mcp-z/oauth-microsoft';
|
|
3
3
|
import type { Logger, PromptModule, ToolModule } from '@mcp-z/server';
|
|
4
4
|
import type { Router } from 'express';
|
|
5
5
|
import type { Keyv } from 'keyv';
|
|
@@ -38,6 +38,11 @@ export interface OAuthAdapters {
|
|
|
38
38
|
accountTools: ToolModule[];
|
|
39
39
|
accountPrompts: PromptModule[];
|
|
40
40
|
dcrRouter?: Router;
|
|
41
|
+
/** Bearer gate for '/mcp' in DCR mode: every request is verified against this server's /oauth/verify. */
|
|
42
|
+
bearerAuth?: {
|
|
43
|
+
verifier: DcrTokenVerifier;
|
|
44
|
+
resourceMetadataUrl: string;
|
|
45
|
+
};
|
|
41
46
|
loopbackRouter?: Router;
|
|
42
47
|
}
|
|
43
48
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AccountAuthProvider } from '@mcp-z/oauth';
|
|
2
|
-
import { DcrOAuthProvider, DeviceCodeProvider, LoopbackOAuthProvider } from '@mcp-z/oauth-microsoft';
|
|
2
|
+
import { DcrOAuthProvider, DcrTokenVerifier, DeviceCodeProvider, LoopbackOAuthProvider } from '@mcp-z/oauth-microsoft';
|
|
3
3
|
import type { Logger, PromptModule, ToolModule } from '@mcp-z/server';
|
|
4
4
|
import type { Router } from 'express';
|
|
5
5
|
import type { Keyv } from 'keyv';
|
|
@@ -38,6 +38,11 @@ export interface OAuthAdapters {
|
|
|
38
38
|
accountTools: ToolModule[];
|
|
39
39
|
accountPrompts: PromptModule[];
|
|
40
40
|
dcrRouter?: Router;
|
|
41
|
+
/** Bearer gate for '/mcp' in DCR mode: every request is verified against this server's /oauth/verify. */
|
|
42
|
+
bearerAuth?: {
|
|
43
|
+
verifier: DcrTokenVerifier;
|
|
44
|
+
resourceMetadataUrl: string;
|
|
45
|
+
};
|
|
41
46
|
loopbackRouter?: Router;
|
|
42
47
|
}
|
|
43
48
|
/**
|
|
@@ -265,7 +265,11 @@ function createOAuthAdapters(config, deps, baseUrl) {
|
|
|
265
265
|
authAdapter: authAdapter,
|
|
266
266
|
accountTools: accountTools,
|
|
267
267
|
accountPrompts: accountPrompts,
|
|
268
|
-
dcrRouter: dcrRouter
|
|
268
|
+
dcrRouter: dcrRouter,
|
|
269
|
+
bearerAuth: {
|
|
270
|
+
verifier: new _oauthmicrosoft.DcrTokenVerifier("".concat(oauthStaticConfig.baseUrl, "/oauth/verify")),
|
|
271
|
+
resourceMetadataUrl: "".concat(oauthStaticConfig.baseUrl, "/.well-known/oauth-protected-resource/mcp")
|
|
272
|
+
}
|
|
269
273
|
}
|
|
270
274
|
];
|
|
271
275
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/oauth-microsoft.ts"],"sourcesContent":["import { type AccountAuthProvider, AccountServer } from '@mcp-z/oauth';\nimport { createDcrRouter, createLoopbackCallbackRouter, DcrOAuthProvider, DeviceCodeProvider, LoopbackOAuthProvider } from '@mcp-z/oauth-microsoft';\nimport type { Logger, PromptModule, ToolModule } from '@mcp-z/server';\nimport type { Router } from 'express';\nimport type { Keyv } from 'keyv';\nimport { MS_SCOPE } from '../constants.ts';\nimport type { ServerConfig } from '../types.ts';\n\n/**\n * Outlook OAuth runtime dependencies\n *\n * Contains the required dependencies for OAuth functionality including logger,\n * token storage, and optional DCR store.\n */\nexport interface OAuthRuntimeDeps {\n logger: Logger;\n tokenStore: Keyv<unknown>;\n dcrStore?: Keyv<unknown>;\n}\n\n/**\n * Auth middleware wrapper with withToolAuth/withResourceAuth/withPromptAuth methods\n *\n * Provides authentication middleware methods for tools, resources, and prompts.\n */\nexport interface AuthMiddleware {\n withToolAuth<T extends ToolModule>(module: T): T;\n withResourceAuth<T>(module: T): T;\n withPromptAuth<T>(module: T): T;\n}\n\n/**\n * Result of OAuth adapter creation\n *\n * Contains the primary OAuth adapter, middleware, auth adapter,\n * account tools, prompts, and optional routers.\n */\nexport interface OAuthAdapters {\n primary: LoopbackOAuthProvider | DeviceCodeProvider | DcrOAuthProvider;\n middleware: AuthMiddleware;\n authAdapter: AccountAuthProvider;\n accountTools: ToolModule[];\n accountPrompts: PromptModule[];\n dcrRouter?: Router; // DCR OAuth endpoints (only for dcr mode)\n loopbackRouter?: Router;\n}\n\n/**\n * Create Outlook OAuth adapters based on transport configuration\n *\n * Returns primary adapter, pre-configured middleware, auth email provider,\n * and pre-selected account tools based on auth mode.\n * @param config - Outlook server configuration\n * @param deps - Runtime dependencies (logger, tokenStore, etc.)\n * @returns OAuth adapters with pre-configured middleware and account tools\n */\nexport async function createOAuthAdapters(config: ServerConfig, deps: OAuthRuntimeDeps, baseUrl?: string): Promise<OAuthAdapters> {\n const { logger, tokenStore, dcrStore } = deps;\n const oauthStaticConfig = {\n service: config.name,\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n scope: MS_SCOPE,\n tenantId: config.tenantId,\n auth: config.auth,\n headless: config.headless,\n redirectUri: config.transport.type === 'stdio' ? undefined : config.redirectUri,\n ...(baseUrl && { baseUrl }),\n };\n\n let primary: LoopbackOAuthProvider | DeviceCodeProvider | DcrOAuthProvider;\n\n // DCR mode - Dynamic Client Registration with HTTP-only support\n if (oauthStaticConfig.auth === 'dcr') {\n logger.debug('Creating DCR provider', { service: oauthStaticConfig.service });\n\n // DCR requires dcrStore and baseUrl\n if (!dcrStore) {\n throw new Error('DCR mode requires dcrStore to be configured');\n }\n if (!oauthStaticConfig.baseUrl) {\n throw new Error('DCR mode requires baseUrl to be configured');\n }\n\n // Create DcrOAuthProvider (stateless provider that receives tokens from verification context)\n primary = new DcrOAuthProvider({\n clientId: oauthStaticConfig.clientId,\n ...(oauthStaticConfig.clientSecret && { clientSecret: oauthStaticConfig.clientSecret }),\n tenantId: oauthStaticConfig.tenantId,\n scope: oauthStaticConfig.scope,\n verifyEndpoint: `${oauthStaticConfig.baseUrl}/oauth/verify`,\n logger,\n });\n\n // Create DCR OAuth router with authorization server endpoints\n const dcrRouter = createDcrRouter({\n store: dcrStore,\n issuerUrl: oauthStaticConfig.baseUrl,\n baseUrl: oauthStaticConfig.baseUrl,\n scopesSupported: oauthStaticConfig.scope.split(' '), // Convert space-separated scope to array\n clientConfig: {\n clientId: oauthStaticConfig.clientId,\n ...(oauthStaticConfig.clientSecret && { clientSecret: oauthStaticConfig.clientSecret }),\n tenantId: oauthStaticConfig.tenantId,\n },\n });\n\n // DCR uses bearer token authentication with middleware validation\n const middleware = primary.authMiddleware();\n\n // Create auth email provider (stateless, no token storage)\n const authAdapter: AccountAuthProvider = {\n getAccessToken: () => {\n throw new Error('DCR mode does not support getAccessToken - tokens are provided via bearer auth');\n },\n getUserEmail: () => {\n throw new Error('DCR mode does not support getUserEmail - tokens are provided via bearer auth');\n },\n };\n\n // No account management tools for DCR (multi-user management at client registration level)\n const accountTools: ToolModule[] = [];\n const accountPrompts: PromptModule[] = [];\n\n logger.info('DCR provider created for Outlook', {\n service: oauthStaticConfig.service,\n baseUrl: oauthStaticConfig.baseUrl,\n });\n\n return { primary, middleware: middleware as AuthMiddleware, authAdapter, accountTools, accountPrompts, dcrRouter };\n }\n\n // Device code mode - similar to service accounts (single static identity)\n if (oauthStaticConfig.auth === 'device-code') {\n logger.debug('Creating device code provider', { service: oauthStaticConfig.service });\n const deviceCodeProvider = new DeviceCodeProvider({\n service: oauthStaticConfig.service,\n clientId: oauthStaticConfig.clientId,\n tenantId: oauthStaticConfig.tenantId,\n scope: oauthStaticConfig.scope,\n logger,\n tokenStore,\n headless: oauthStaticConfig.headless,\n });\n primary = deviceCodeProvider;\n\n // Device code uses single-user middleware (no account management needed)\n const middleware = deviceCodeProvider.authMiddleware();\n\n // Create auth email provider\n const authAdapter: AccountAuthProvider = {\n getAccessToken: (accountId) => deviceCodeProvider.getAccessToken(accountId),\n getUserEmail: (accountId) => deviceCodeProvider.getUserEmail(accountId),\n };\n\n // No account management tools for device code (like service accounts)\n const accountTools: ToolModule[] = [];\n const accountPrompts: PromptModule[] = [];\n\n logger.info('Device code provider created for Outlook', {\n service: oauthStaticConfig.service,\n });\n\n return { primary, middleware: middleware as AuthMiddleware, authAdapter, accountTools, accountPrompts };\n }\n\n // Always create primary adapter for file-based OAuth (loopback mode)\n primary = new LoopbackOAuthProvider({\n service: oauthStaticConfig.service,\n clientId: oauthStaticConfig.clientId,\n clientSecret: oauthStaticConfig.clientSecret,\n scope: oauthStaticConfig.scope,\n tenantId: oauthStaticConfig.tenantId,\n headless: oauthStaticConfig.headless,\n logger,\n tokenStore,\n ...(oauthStaticConfig.redirectUri !== undefined && { redirectUri: oauthStaticConfig.redirectUri }),\n });\n\n // Create auth email provider (used by account management tools)\n const authAdapter: AccountAuthProvider = primary;\n\n // Select middleware AND account tools based on auth mode\n const middleware: ReturnType<LoopbackOAuthProvider['authMiddleware']> = primary.authMiddleware();\n\n // Loopback OAuth - multi-account mode\n const result = AccountServer.createLoopback({\n service: oauthStaticConfig.service,\n store: tokenStore,\n logger,\n auth: authAdapter,\n });\n const accountTools: ToolModule[] = result.tools as ToolModule[];\n const accountPrompts: PromptModule[] = result.prompts as PromptModule[];\n logger.debug('Loopback OAuth (multi-account mode)', { service: oauthStaticConfig.service });\n\n const loopbackRouter = oauthStaticConfig.redirectUri ? createLoopbackCallbackRouter(primary) : undefined;\n\n return { primary, middleware: middleware as AuthMiddleware, authAdapter, accountTools, accountPrompts, loopbackRouter };\n}\n"],"names":["createOAuthAdapters","config","deps","baseUrl","logger","tokenStore","dcrStore","oauthStaticConfig","primary","dcrRouter","middleware","authAdapter","accountTools","accountPrompts","deviceCodeProvider","result","loopbackRouter","service","name","clientId","clientSecret","scope","MS_SCOPE","tenantId","auth","headless","redirectUri","transport","type","undefined","debug","Error","DcrOAuthProvider","verifyEndpoint","createDcrRouter","store","issuerUrl","scopesSupported","split","clientConfig","authMiddleware","getAccessToken","getUserEmail","info","DeviceCodeProvider","accountId","LoopbackOAuthProvider","AccountServer","createLoopback","tools","prompts","createLoopbackCallbackRouter"],"mappings":";;;;+BAwDsBA;;;eAAAA;;;qBAxDkC;8BACmE;2BAIlG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDlB,SAAeA,oBAAoBC,MAAoB,EAAEC,IAAsB,EAAEC,OAAgB;;YAC9FC,QAAQC,YAAYC,UACtBC,mBAYFC,SAyBIC,WAaAC,YAGAC,aAUAC,cACAC,gBAaAC,oBAYAJ,aAGAC,cAMAC,eACAC,iBAuBFF,cAGAD,aAGAK,QAMA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esContent":["import { type AccountAuthProvider, AccountServer } from '@mcp-z/oauth';\nimport { createDcrRouter, createLoopbackCallbackRouter, DcrOAuthProvider, DcrTokenVerifier, DeviceCodeProvider, LoopbackOAuthProvider } from '@mcp-z/oauth-microsoft';\nimport type { Logger, PromptModule, ToolModule } from '@mcp-z/server';\nimport type { Router } from 'express';\nimport type { Keyv } from 'keyv';\nimport { MS_SCOPE } from '../constants.ts';\nimport type { ServerConfig } from '../types.ts';\n\n/**\n * Outlook OAuth runtime dependencies\n *\n * Contains the required dependencies for OAuth functionality including logger,\n * token storage, and optional DCR store.\n */\nexport interface OAuthRuntimeDeps {\n logger: Logger;\n tokenStore: Keyv<unknown>;\n dcrStore?: Keyv<unknown>;\n}\n\n/**\n * Auth middleware wrapper with withToolAuth/withResourceAuth/withPromptAuth methods\n *\n * Provides authentication middleware methods for tools, resources, and prompts.\n */\nexport interface AuthMiddleware {\n withToolAuth<T extends ToolModule>(module: T): T;\n withResourceAuth<T>(module: T): T;\n withPromptAuth<T>(module: T): T;\n}\n\n/**\n * Result of OAuth adapter creation\n *\n * Contains the primary OAuth adapter, middleware, auth adapter,\n * account tools, prompts, and optional routers.\n */\nexport interface OAuthAdapters {\n primary: LoopbackOAuthProvider | DeviceCodeProvider | DcrOAuthProvider;\n middleware: AuthMiddleware;\n authAdapter: AccountAuthProvider;\n accountTools: ToolModule[];\n accountPrompts: PromptModule[];\n dcrRouter?: Router; // DCR OAuth endpoints (only for dcr mode)\n /** Bearer gate for '/mcp' in DCR mode: every request is verified against this server's /oauth/verify. */\n bearerAuth?: { verifier: DcrTokenVerifier; resourceMetadataUrl: string };\n loopbackRouter?: Router;\n}\n\n/**\n * Create Outlook OAuth adapters based on transport configuration\n *\n * Returns primary adapter, pre-configured middleware, auth email provider,\n * and pre-selected account tools based on auth mode.\n * @param config - Outlook server configuration\n * @param deps - Runtime dependencies (logger, tokenStore, etc.)\n * @returns OAuth adapters with pre-configured middleware and account tools\n */\nexport async function createOAuthAdapters(config: ServerConfig, deps: OAuthRuntimeDeps, baseUrl?: string): Promise<OAuthAdapters> {\n const { logger, tokenStore, dcrStore } = deps;\n const oauthStaticConfig = {\n service: config.name,\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n scope: MS_SCOPE,\n tenantId: config.tenantId,\n auth: config.auth,\n headless: config.headless,\n redirectUri: config.transport.type === 'stdio' ? undefined : config.redirectUri,\n ...(baseUrl && { baseUrl }),\n };\n\n let primary: LoopbackOAuthProvider | DeviceCodeProvider | DcrOAuthProvider;\n\n // DCR mode - Dynamic Client Registration with HTTP-only support\n if (oauthStaticConfig.auth === 'dcr') {\n logger.debug('Creating DCR provider', { service: oauthStaticConfig.service });\n\n // DCR requires dcrStore and baseUrl\n if (!dcrStore) {\n throw new Error('DCR mode requires dcrStore to be configured');\n }\n if (!oauthStaticConfig.baseUrl) {\n throw new Error('DCR mode requires baseUrl to be configured');\n }\n\n // Create DcrOAuthProvider (stateless provider that receives tokens from verification context)\n primary = new DcrOAuthProvider({\n clientId: oauthStaticConfig.clientId,\n ...(oauthStaticConfig.clientSecret && { clientSecret: oauthStaticConfig.clientSecret }),\n tenantId: oauthStaticConfig.tenantId,\n scope: oauthStaticConfig.scope,\n verifyEndpoint: `${oauthStaticConfig.baseUrl}/oauth/verify`,\n logger,\n });\n\n // Create DCR OAuth router with authorization server endpoints\n const dcrRouter = createDcrRouter({\n store: dcrStore,\n issuerUrl: oauthStaticConfig.baseUrl,\n baseUrl: oauthStaticConfig.baseUrl,\n scopesSupported: oauthStaticConfig.scope.split(' '), // Convert space-separated scope to array\n clientConfig: {\n clientId: oauthStaticConfig.clientId,\n ...(oauthStaticConfig.clientSecret && { clientSecret: oauthStaticConfig.clientSecret }),\n tenantId: oauthStaticConfig.tenantId,\n },\n });\n\n // DCR uses bearer token authentication with middleware validation\n const middleware = primary.authMiddleware();\n\n // Create auth email provider (stateless, no token storage)\n const authAdapter: AccountAuthProvider = {\n getAccessToken: () => {\n throw new Error('DCR mode does not support getAccessToken - tokens are provided via bearer auth');\n },\n getUserEmail: () => {\n throw new Error('DCR mode does not support getUserEmail - tokens are provided via bearer auth');\n },\n };\n\n // No account management tools for DCR (multi-user management at client registration level)\n const accountTools: ToolModule[] = [];\n const accountPrompts: PromptModule[] = [];\n\n logger.info('DCR provider created for Outlook', {\n service: oauthStaticConfig.service,\n baseUrl: oauthStaticConfig.baseUrl,\n });\n\n return {\n primary,\n middleware: middleware as AuthMiddleware,\n authAdapter,\n accountTools,\n accountPrompts,\n dcrRouter,\n bearerAuth: {\n verifier: new DcrTokenVerifier(`${oauthStaticConfig.baseUrl}/oauth/verify`),\n resourceMetadataUrl: `${oauthStaticConfig.baseUrl}/.well-known/oauth-protected-resource/mcp`,\n },\n };\n }\n\n // Device code mode - similar to service accounts (single static identity)\n if (oauthStaticConfig.auth === 'device-code') {\n logger.debug('Creating device code provider', { service: oauthStaticConfig.service });\n const deviceCodeProvider = new DeviceCodeProvider({\n service: oauthStaticConfig.service,\n clientId: oauthStaticConfig.clientId,\n tenantId: oauthStaticConfig.tenantId,\n scope: oauthStaticConfig.scope,\n logger,\n tokenStore,\n headless: oauthStaticConfig.headless,\n });\n primary = deviceCodeProvider;\n\n // Device code uses single-user middleware (no account management needed)\n const middleware = deviceCodeProvider.authMiddleware();\n\n // Create auth email provider\n const authAdapter: AccountAuthProvider = {\n getAccessToken: (accountId) => deviceCodeProvider.getAccessToken(accountId),\n getUserEmail: (accountId) => deviceCodeProvider.getUserEmail(accountId),\n };\n\n // No account management tools for device code (like service accounts)\n const accountTools: ToolModule[] = [];\n const accountPrompts: PromptModule[] = [];\n\n logger.info('Device code provider created for Outlook', {\n service: oauthStaticConfig.service,\n });\n\n return { primary, middleware: middleware as AuthMiddleware, authAdapter, accountTools, accountPrompts };\n }\n\n // Always create primary adapter for file-based OAuth (loopback mode)\n primary = new LoopbackOAuthProvider({\n service: oauthStaticConfig.service,\n clientId: oauthStaticConfig.clientId,\n clientSecret: oauthStaticConfig.clientSecret,\n scope: oauthStaticConfig.scope,\n tenantId: oauthStaticConfig.tenantId,\n headless: oauthStaticConfig.headless,\n logger,\n tokenStore,\n ...(oauthStaticConfig.redirectUri !== undefined && { redirectUri: oauthStaticConfig.redirectUri }),\n });\n\n // Create auth email provider (used by account management tools)\n const authAdapter: AccountAuthProvider = primary;\n\n // Select middleware AND account tools based on auth mode\n const middleware: ReturnType<LoopbackOAuthProvider['authMiddleware']> = primary.authMiddleware();\n\n // Loopback OAuth - multi-account mode\n const result = AccountServer.createLoopback({\n service: oauthStaticConfig.service,\n store: tokenStore,\n logger,\n auth: authAdapter,\n });\n const accountTools: ToolModule[] = result.tools as ToolModule[];\n const accountPrompts: PromptModule[] = result.prompts as PromptModule[];\n logger.debug('Loopback OAuth (multi-account mode)', { service: oauthStaticConfig.service });\n\n const loopbackRouter = oauthStaticConfig.redirectUri ? createLoopbackCallbackRouter(primary) : undefined;\n\n return { primary, middleware: middleware as AuthMiddleware, authAdapter, accountTools, accountPrompts, loopbackRouter };\n}\n"],"names":["createOAuthAdapters","config","deps","baseUrl","logger","tokenStore","dcrStore","oauthStaticConfig","primary","dcrRouter","middleware","authAdapter","accountTools","accountPrompts","deviceCodeProvider","result","loopbackRouter","service","name","clientId","clientSecret","scope","MS_SCOPE","tenantId","auth","headless","redirectUri","transport","type","undefined","debug","Error","DcrOAuthProvider","verifyEndpoint","createDcrRouter","store","issuerUrl","scopesSupported","split","clientConfig","authMiddleware","getAccessToken","getUserEmail","info","bearerAuth","verifier","DcrTokenVerifier","resourceMetadataUrl","DeviceCodeProvider","accountId","LoopbackOAuthProvider","AccountServer","createLoopback","tools","prompts","createLoopbackCallbackRouter"],"mappings":";;;;+BA0DsBA;;;eAAAA;;;qBA1DkC;8BACqF;2BAIpH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,KAAK;YACzCxC,kBAAiCE,OAAOuC,OAAO;YACrDlD,OAAO0B,KAAK,CAAC,uCAAuC;gBAAEb,SAASV,kBAAkBU,OAAO;YAAC;YAEnFD,iBAAiBT,kBAAkBmB,WAAW,GAAG6B,IAAAA,4CAA4B,EAAC/C,WAAWqB;YAE/F;;gBAAO;oBAAErB,SAAAA;oBAASE,YAAYA;oBAA8BC,aAAAA;oBAAaC,cAAAA;oBAAcC,gBAAAA;oBAAgBG,gBAAAA;gBAAe;;;IACxH"}
|
|
@@ -3,7 +3,7 @@ import type { CommonRuntime, RuntimeOverrides, ServerConfig, StorageContext } fr
|
|
|
3
3
|
import { type OAuthAdapters } from './oauth-microsoft.js';
|
|
4
4
|
export declare function createLogger(config: ServerConfig): Logger;
|
|
5
5
|
export declare function createTokenStore(baseDir: string, logger: Logger): Promise<import("keyv").Keyv<unknown>>;
|
|
6
|
-
export declare function createDcrStore(baseDir: string, required: boolean, logger: Logger): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
6
|
+
export declare function createDcrStore(baseDir: string, required: boolean, logger: Logger, storeUri?: string): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
7
7
|
export declare function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer;
|
|
8
8
|
export declare function createLoggingLayer(logger: Logger): MiddlewareLayer;
|
|
9
9
|
export declare function createStorageLayer(storageContext: StorageContext): MiddlewareLayer;
|
|
@@ -3,7 +3,7 @@ import type { CommonRuntime, RuntimeOverrides, ServerConfig, StorageContext } fr
|
|
|
3
3
|
import { type OAuthAdapters } from './oauth-microsoft.js';
|
|
4
4
|
export declare function createLogger(config: ServerConfig): Logger;
|
|
5
5
|
export declare function createTokenStore(baseDir: string, logger: Logger): Promise<import("keyv").Keyv<unknown>>;
|
|
6
|
-
export declare function createDcrStore(baseDir: string, required: boolean, logger: Logger): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
6
|
+
export declare function createDcrStore(baseDir: string, required: boolean, logger: Logger, storeUri?: string): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
7
7
|
export declare function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer;
|
|
8
8
|
export declare function createLoggingLayer(logger: Logger): MiddlewareLayer;
|
|
9
9
|
export declare function createStorageLayer(storageContext: StorageContext): MiddlewareLayer;
|
|
@@ -40,6 +40,7 @@ var _server = require("@mcp-z/server");
|
|
|
40
40
|
var _fs = /*#__PURE__*/ _interop_require_wildcard(require("fs"));
|
|
41
41
|
var _path = /*#__PURE__*/ _interop_require_wildcard(require("path"));
|
|
42
42
|
var _pino = /*#__PURE__*/ _interop_require_default(require("pino"));
|
|
43
|
+
var _constantsts = require("../constants.js");
|
|
43
44
|
var _createstorets = /*#__PURE__*/ _interop_require_default(require("../lib/create-store.js"));
|
|
44
45
|
var _indexts = /*#__PURE__*/ _interop_require_wildcard(require("../mcp/index.js"));
|
|
45
46
|
var _oauthmicrosoftts = require("./oauth-microsoft.js");
|
|
@@ -291,14 +292,18 @@ function createLogger(config) {
|
|
|
291
292
|
formatters: (0, _oauth.sanitizeForLoggingFormatter)()
|
|
292
293
|
}, hasStdio ? _pino.default.destination({
|
|
293
294
|
dest: logsPath,
|
|
294
|
-
sync:
|
|
295
|
+
sync: true
|
|
295
296
|
}) : _pino.default.destination(1));
|
|
296
297
|
}
|
|
298
|
+
// Several mcp-z processes share these files, so the default store merges each write under a lock.
|
|
299
|
+
function sharedFileUri(file) {
|
|
300
|
+
return (0, _nodeurl.pathToFileURL)(file).href.replace(/^file:/, _constantsts.SHARED_FILE_PROTOCOL);
|
|
301
|
+
}
|
|
297
302
|
function createTokenStore(baseDir, logger) {
|
|
298
303
|
return _async_to_generator(function() {
|
|
299
304
|
var tokenStoreUri;
|
|
300
305
|
return _ts_generator(this, function(_state) {
|
|
301
|
-
tokenStoreUri = process.env.TOKEN_STORE_URI || (
|
|
306
|
+
tokenStoreUri = process.env.TOKEN_STORE_URI || sharedFileUri(_path.join(baseDir, 'tokens.json'));
|
|
302
307
|
return [
|
|
303
308
|
2,
|
|
304
309
|
(0, _createstorets.default)(tokenStoreUri, logger)
|
|
@@ -306,7 +311,7 @@ function createTokenStore(baseDir, logger) {
|
|
|
306
311
|
});
|
|
307
312
|
})();
|
|
308
313
|
}
|
|
309
|
-
function createDcrStore(baseDir, required, logger) {
|
|
314
|
+
function createDcrStore(baseDir, required, logger, storeUri) {
|
|
310
315
|
return _async_to_generator(function() {
|
|
311
316
|
var dcrStoreUri;
|
|
312
317
|
return _ts_generator(this, function(_state) {
|
|
@@ -314,7 +319,7 @@ function createDcrStore(baseDir, required, logger) {
|
|
|
314
319
|
2,
|
|
315
320
|
undefined
|
|
316
321
|
];
|
|
317
|
-
dcrStoreUri = process.env.DCR_STORE_URI || (
|
|
322
|
+
dcrStoreUri = storeUri || process.env.DCR_STORE_URI || sharedFileUri(_path.join(baseDir, 'dcr.json'));
|
|
318
323
|
return [
|
|
319
324
|
2,
|
|
320
325
|
(0, _createstorets.default)(dcrStoreUri, logger)
|
|
@@ -392,7 +397,7 @@ function validateStorageConfig(config, logger) {
|
|
|
392
397
|
}
|
|
393
398
|
function createDefaultRuntime(config, overrides) {
|
|
394
399
|
return _async_to_generator(function() {
|
|
395
|
-
var _config_baseUrl, _ref, _ref1, logger, tokenStore, baseUrl, dcrStore, oauthAdapters, deps, createDomainModules, middlewareFactories;
|
|
400
|
+
var _config_baseUrl, _ref, _ref1, _config_dcrConfig, logger, tokenStore, baseUrl, dcrStore, oauthAdapters, deps, createDomainModules, middlewareFactories;
|
|
396
401
|
return _ts_generator(this, function(_state) {
|
|
397
402
|
switch(_state.label){
|
|
398
403
|
case 0:
|
|
@@ -408,7 +413,7 @@ function createDefaultRuntime(config, overrides) {
|
|
|
408
413
|
baseUrl = (_config_baseUrl = config.baseUrl) !== null && _config_baseUrl !== void 0 ? _config_baseUrl : config.transport.type === 'http' && config.transport.port ? "http://localhost:".concat(config.transport.port) : undefined;
|
|
409
414
|
return [
|
|
410
415
|
4,
|
|
411
|
-
createDcrStore(config.baseDir, config.auth === 'dcr', logger)
|
|
416
|
+
createDcrStore(config.baseDir, config.auth === 'dcr', logger, (_config_dcrConfig = config.dcrConfig) === null || _config_dcrConfig === void 0 ? void 0 : _config_dcrConfig.storeUri)
|
|
412
417
|
];
|
|
413
418
|
case 2:
|
|
414
419
|
dcrStore = _state.sent();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/runtime.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url';\nimport { sanitizeForLoggingFormatter } from '@mcp-z/oauth';\nimport type { Logger, MiddlewareLayer } from '@mcp-z/server';\nimport { createLoggingMiddleware } from '@mcp-z/server';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport pino from 'pino';\nimport createStore from '../lib/create-store.ts';\nimport * as mcp from '../mcp/index.ts';\nimport type { CommonRuntime, RuntimeDeps, RuntimeOverrides, ServerConfig, StorageContext } from '../types.ts';\nimport { createOAuthAdapters, type OAuthAdapters } from './oauth-microsoft.ts';\n\nexport function createLogger(config: ServerConfig): Logger {\n const hasStdio = config.transport.type === 'stdio';\n const logsPath = path.join(config.baseDir, 'logs', `${config.name}.log`);\n if (hasStdio) fs.mkdirSync(path.dirname(logsPath), { recursive: true });\n return pino({ level: config.logLevel ?? 'info', formatters: sanitizeForLoggingFormatter() }, hasStdio ? pino.destination({ dest: logsPath, sync: false }) : pino.destination(1));\n}\n\nexport async function createTokenStore(baseDir: string, logger: Logger) {\n const tokenStoreUri = process.env.TOKEN_STORE_URI || pathToFileURL(path.join(baseDir, 'tokens.json')).href;\n return createStore<unknown>(tokenStoreUri, logger);\n}\n\nexport async function createDcrStore(baseDir: string, required: boolean, logger: Logger) {\n if (!required) return undefined;\n const dcrStoreUri = process.env.DCR_STORE_URI || pathToFileURL(path.join(baseDir, 'dcr.json')).href;\n return createStore<unknown>(dcrStoreUri, logger);\n}\n\nexport function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer {\n return {\n withTool: authMiddleware.withToolAuth,\n withResource: authMiddleware.withResourceAuth,\n withPrompt: authMiddleware.withPromptAuth,\n };\n}\n\nexport function createLoggingLayer(logger: Logger): MiddlewareLayer {\n const logging = createLoggingMiddleware({ logger });\n return {\n withTool: logging.withToolLogging,\n withResource: logging.withResourceLogging,\n withPrompt: logging.withPromptLogging,\n };\n}\n\nexport function createStorageLayer(storageContext: StorageContext): MiddlewareLayer {\n const wrapAtPosition = <T extends { name: string; handler: unknown; [key: string]: unknown }>(module: T, extraPosition: number): T => {\n const originalHandler = module.handler as (...args: unknown[]) => Promise<unknown>;\n\n const wrappedHandler = async (...allArgs: unknown[]) => {\n const extra = allArgs[extraPosition];\n (extra as { storageContext?: StorageContext }).storageContext = storageContext;\n return await originalHandler(...allArgs);\n };\n\n return {\n ...module,\n handler: wrappedHandler,\n } as T;\n };\n\n return {\n withTool: <T extends { name: string; config: unknown; handler: unknown }>(module: T): T => wrapAtPosition(module, 1) as T,\n };\n}\n\nexport function validateStorageConfig(config: ServerConfig, logger: Logger) {\n if (config.auth === 'dcr') {\n if (config.resourceStoreUri) {\n logger.warn('DCR mode does not support file storage; resourceStoreUri will be ignored.');\n }\n return;\n }\n if (!config.resourceStoreUri) {\n throw new Error('outlook-messages-export-csv: Server configuration missing resourceStoreUri.');\n }\n if (config.transport.type === 'http' && !config.baseUrl && !config.transport.port) {\n throw new Error('outlook-messages-export-csv: HTTP transport requires either baseUrl in server config or port in transport config. This is a server configuration error - please provide --base-url or --port.');\n }\n}\n\nexport async function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime> {\n if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');\n\n const logger = createLogger(config);\n validateStorageConfig(config, logger);\n const tokenStore = await createTokenStore(config.baseDir, logger);\n const baseUrl = config.baseUrl ?? (config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined);\n const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr', logger);\n const oauthAdapters = await createOAuthAdapters(config, { logger, tokenStore, dcrStore }, baseUrl);\n const deps: RuntimeDeps = { config, logger, tokenStore, oauthAdapters, baseUrl };\n const createDomainModules =\n overrides?.createDomainModules ??\n (() => ({\n tools: Object.values(mcp.toolFactories).map((factory) => factory()),\n resources: Object.values(mcp.resourceFactories).map((factory) => factory()),\n prompts: Object.values(mcp.promptFactories).map((factory) => factory()),\n }));\n const middlewareFactories = overrides?.middlewareFactories ?? [() => createAuthLayer(oauthAdapters.middleware), () => createLoggingLayer(logger), ...(config.auth === 'dcr' ? [] : [() => createStorageLayer({ resourceStoreUri: config.resourceStoreUri, baseUrl: config.baseUrl, transport: config.transport })])];\n\n return {\n deps,\n middlewareFactories,\n createDomainModules,\n close: async () => {},\n };\n}\n"],"names":["createAuthLayer","createDcrStore","createDefaultRuntime","createLogger","createLoggingLayer","createStorageLayer","createTokenStore","validateStorageConfig","config","hasStdio","transport","type","logsPath","path","join","baseDir","name","fs","mkdirSync","dirname","recursive","pino","level","logLevel","formatters","sanitizeForLoggingFormatter","destination","dest","sync","logger","tokenStoreUri","process","env","TOKEN_STORE_URI","pathToFileURL","href","createStore","required","dcrStoreUri","undefined","DCR_STORE_URI","authMiddleware","withTool","withToolAuth","withResource","withResourceAuth","withPrompt","withPromptAuth","logging","createLoggingMiddleware","withToolLogging","withResourceLogging","withPromptLogging","storageContext","wrapAtPosition","module","extraPosition","originalHandler","handler","wrappedHandler","allArgs","extra","auth","resourceStoreUri","warn","Error","baseUrl","port","overrides","tokenStore","dcrStore","oauthAdapters","deps","createDomainModules","middlewareFactories","createOAuthAdapters","tools","Object","values","mcp","toolFactories","map","factory","resources","resourceFactories","prompts","promptFactories","middleware","close"],"mappings":";;;;;;;;;;;QA8BgBA;eAAAA;;QANMC;eAAAA;;QA2DAC;eAAAA;;QAvENC;eAAAA;;QA0BAC;eAAAA;;QASAC;eAAAA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AIO,eAAe,EAAEL,GAAG,CAAC,SAACC;uCAAYA;;wBAC/D;;oBACIR,+BAAsBN,sBAAAA,gCAAAA,UAAWM,mBAAmB,yCAAI;wBAAC;mCAAM1E,gBAAgBuE,cAAcgB,UAAU;;wBAAG;mCAAMnF,mBAAmByB;;sBAA3E,OAAoF,qBAAIrB,OAAOsD,IAAI,KAAK;wBAAc;mCAAMzD,mBAAmB;gCAAE0D,kBAAkBvD,OAAOuD,gBAAgB;gCAAEG,SAAS1D,OAAO0D,OAAO;gCAAExD,WAAWF,OAAOE,SAAS;4BAAC;;;oBAE/S;;wBAAO;4BACL8D,MAAAA;4BACAE,qBAAAA;4BACAD,qBAAAA;4BACAe,OAAO,SAAPA;;;;;;;gCAAoB;;wBACtB;;;;IACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/runtime.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url';\nimport { sanitizeForLoggingFormatter } from '@mcp-z/oauth';\nimport type { Logger, MiddlewareLayer } from '@mcp-z/server';\nimport { createLoggingMiddleware } from '@mcp-z/server';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport pino from 'pino';\nimport { SHARED_FILE_PROTOCOL } from '../constants.ts';\nimport createStore from '../lib/create-store.ts';\nimport * as mcp from '../mcp/index.ts';\nimport type { CommonRuntime, RuntimeDeps, RuntimeOverrides, ServerConfig, StorageContext } from '../types.ts';\nimport { createOAuthAdapters, type OAuthAdapters } from './oauth-microsoft.ts';\n\nexport function createLogger(config: ServerConfig): Logger {\n const hasStdio = config.transport.type === 'stdio';\n const logsPath = path.join(config.baseDir, 'logs', `${config.name}.log`);\n if (hasStdio) fs.mkdirSync(path.dirname(logsPath), { recursive: true });\n return pino({ level: config.logLevel ?? 'info', formatters: sanitizeForLoggingFormatter() }, hasStdio ? pino.destination({ dest: logsPath, sync: true }) : pino.destination(1));\n}\n\n// Several mcp-z processes share these files, so the default store merges each write under a lock.\nfunction sharedFileUri(file: string): string {\n return pathToFileURL(file).href.replace(/^file:/, SHARED_FILE_PROTOCOL);\n}\n\nexport async function createTokenStore(baseDir: string, logger: Logger) {\n const tokenStoreUri = process.env.TOKEN_STORE_URI || sharedFileUri(path.join(baseDir, 'tokens.json'));\n return createStore<unknown>(tokenStoreUri, logger);\n}\n\nexport async function createDcrStore(baseDir: string, required: boolean, logger: Logger, storeUri?: string) {\n if (!required) return undefined;\n const dcrStoreUri = storeUri || process.env.DCR_STORE_URI || sharedFileUri(path.join(baseDir, 'dcr.json'));\n return createStore<unknown>(dcrStoreUri, logger);\n}\n\nexport function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer {\n return {\n withTool: authMiddleware.withToolAuth,\n withResource: authMiddleware.withResourceAuth,\n withPrompt: authMiddleware.withPromptAuth,\n };\n}\n\nexport function createLoggingLayer(logger: Logger): MiddlewareLayer {\n const logging = createLoggingMiddleware({ logger });\n return {\n withTool: logging.withToolLogging,\n withResource: logging.withResourceLogging,\n withPrompt: logging.withPromptLogging,\n };\n}\n\nexport function createStorageLayer(storageContext: StorageContext): MiddlewareLayer {\n const wrapAtPosition = <T extends { name: string; handler: unknown; [key: string]: unknown }>(module: T, extraPosition: number): T => {\n const originalHandler = module.handler as (...args: unknown[]) => Promise<unknown>;\n\n const wrappedHandler = async (...allArgs: unknown[]) => {\n const extra = allArgs[extraPosition];\n (extra as { storageContext?: StorageContext }).storageContext = storageContext;\n return await originalHandler(...allArgs);\n };\n\n return {\n ...module,\n handler: wrappedHandler,\n } as T;\n };\n\n return {\n withTool: <T extends { name: string; config: unknown; handler: unknown }>(module: T): T => wrapAtPosition(module, 1) as T,\n };\n}\n\nexport function validateStorageConfig(config: ServerConfig, logger: Logger) {\n if (config.auth === 'dcr') {\n if (config.resourceStoreUri) {\n logger.warn('DCR mode does not support file storage; resourceStoreUri will be ignored.');\n }\n return;\n }\n if (!config.resourceStoreUri) {\n throw new Error('outlook-messages-export-csv: Server configuration missing resourceStoreUri.');\n }\n if (config.transport.type === 'http' && !config.baseUrl && !config.transport.port) {\n throw new Error('outlook-messages-export-csv: HTTP transport requires either baseUrl in server config or port in transport config. This is a server configuration error - please provide --base-url or --port.');\n }\n}\n\nexport async function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime> {\n if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');\n\n const logger = createLogger(config);\n validateStorageConfig(config, logger);\n const tokenStore = await createTokenStore(config.baseDir, logger);\n const baseUrl = config.baseUrl ?? (config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined);\n const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr', logger, config.dcrConfig?.storeUri);\n const oauthAdapters = await createOAuthAdapters(config, { logger, tokenStore, dcrStore }, baseUrl);\n const deps: RuntimeDeps = { config, logger, tokenStore, oauthAdapters, baseUrl };\n const createDomainModules =\n overrides?.createDomainModules ??\n (() => ({\n tools: Object.values(mcp.toolFactories).map((factory) => factory()),\n resources: Object.values(mcp.resourceFactories).map((factory) => factory()),\n prompts: Object.values(mcp.promptFactories).map((factory) => factory()),\n }));\n const middlewareFactories = overrides?.middlewareFactories ?? [() => createAuthLayer(oauthAdapters.middleware), () => createLoggingLayer(logger), ...(config.auth === 'dcr' ? [] : [() => createStorageLayer({ resourceStoreUri: config.resourceStoreUri, baseUrl: config.baseUrl, transport: config.transport })])];\n\n return {\n deps,\n middlewareFactories,\n createDomainModules,\n close: async () => {},\n };\n}\n"],"names":["createAuthLayer","createDcrStore","createDefaultRuntime","createLogger","createLoggingLayer","createStorageLayer","createTokenStore","validateStorageConfig","config","hasStdio","transport","type","logsPath","path","join","baseDir","name","fs","mkdirSync","dirname","recursive","pino","level","logLevel","formatters","sanitizeForLoggingFormatter","destination","dest","sync","sharedFileUri","file","pathToFileURL","href","replace","SHARED_FILE_PROTOCOL","logger","tokenStoreUri","process","env","TOKEN_STORE_URI","createStore","required","storeUri","dcrStoreUri","undefined","DCR_STORE_URI","authMiddleware","withTool","withToolAuth","withResource","withResourceAuth","withPrompt","withPromptAuth","logging","createLoggingMiddleware","withToolLogging","withResourceLogging","withPromptLogging","storageContext","wrapAtPosition","module","extraPosition","originalHandler","handler","wrappedHandler","allArgs","extra","auth","resourceStoreUri","warn","Error","baseUrl","port","overrides","tokenStore","dcrStore","oauthAdapters","deps","createDomainModules","middlewareFactories","dcrConfig","createOAuthAdapters","tools","Object","values","mcp","toolFactories","map","factory","resources","resourceFactories","prompts","promptFactories","middleware","close"],"mappings":";;;;;;;;;;;QAoCgBA;eAAAA;;QANMC;eAAAA;;QA2DAC;eAAAA;;QA5ENC;eAAAA;;QA+BAC;eAAAA;;QASAC;eAAAA;;QA5BMC;eAAAA;;QAiDNC;eAAAA;;;uBA1Ec;qBACc;sBAEJ;0DACpB;4DACE;2DACL;2BACoB;oEACb;+DACH;gCAEmC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEjD,SAASJ,aAAaK,MAAoB;QAI1BA;IAHrB,IAAMC,WAAWD,OAAOE,SAAS,CAACC,IAAI,KAAK;IAC3C,IAAMC,WAAWC,MAAKC,IAAI,CAACN,OAAOO,OAAO,EAAE,QAAQ,AAAC,GAAc,OAAZP,OAAOQ,IAAI,EAAC;IAClE,IAAIP,UAAUQ,IAAGC,SAAS,CAACL,MAAKM,OAAO,CAACP,WAAW;QAAEQ,WAAW;IAAK;IACrE,OAAOC,IAAAA,aAAI,EAAC;QAAEC,KAAK,GAAEd,mBAAAA,OAAOe,QAAQ,cAAff,8BAAAA,mBAA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@mcp-z/oauth-microsoft
|
|
61
61
|
// and @mcp-z/server, which this path must not touch.
|
|
62
62
|
var pkg = JSON.parse(_fs.readFileSync(_path.join((0, _modulerootsync.default)(_url.fileURLToPath(require("url").pathToFileURL(__filename).toString())), 'package.json'), 'utf-8'));
|
|
63
|
-
var HELP_TEXT = '\nUsage: mcp-outlook [options]\n\nMCP server for Outlook/Microsoft email management with OAuth authentication.\n\nOptions:\n --version Show version number\n --help Show this help message\n --auth=<mode> Authentication mode (default: loopback-oauth)\n Modes: loopback-oauth, device-code, dcr\n --headless Disable browser auto-open, return auth URL instead\n --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)\n --dcr-
|
|
63
|
+
var HELP_TEXT = '\nUsage: mcp-outlook [options]\n\nMCP server for Outlook/Microsoft email management with OAuth authentication.\n\nOptions:\n --version Show version number\n --help Show this help message\n --auth=<mode> Authentication mode (default: loopback-oauth)\n Modes: loopback-oauth, device-code, dcr\n --headless Disable browser auto-open, return auth URL instead\n --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)\n --dcr-store-uri=<uri> DCR client storage URI (default: .mcp-z/dcr.json)\n --port=<port> Enable HTTP transport on specified port\n --stdio Enable stdio transport (default if no port)\n --log-level=<level> Logging level (default: info)\n --resource-store-uri=<uri> Resource store URI for CSV file storage (default: .mcp-z/mcp-outlook/files beside the nearest .mcp.json, else ~/.mcp-z/mcp-outlook/files)\n --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)\n\nEnvironment Variables:\n MS_CLIENT_ID OAuth client ID (REQUIRED)\n MS_TENANT_ID Microsoft tenant ID (REQUIRED)\n MS_CLIENT_SECRET OAuth client secret (optional)\n AUTH_MODE Default authentication mode (optional)\n HEADLESS Disable browser auto-open (optional)\n DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n TOKEN_STORE_URI Token storage URI (optional)\n PORT Default HTTP port (optional)\n LOG_LEVEL Default logging level (optional)\n RESOURCE_STORE_URI Resource store URI (optional, file://)\n BASE_URL Base URL for HTTP file serving (optional)\n\nConfiguration Files:\n Variables may also be set in the first of these files that exists:\n 1. .mcp-z/mcp-outlook/.env beside the nearest .mcp.json (else ~/.mcp-z/mcp-outlook/.env)\n 2. ~/.config/mcp-z/mcp-outlook/.env (~ is your home directory, on every OS)\n Values already in the environment, including .mcp.json "env", take precedence.\n On macOS and Linux the file must be private (chmod 600), or the server will not start.\n\nStorage Backends:\n TOKEN_STORE_URI and DCR_STORE_URI accept any keyv-registry protocol.\n file+shared:// (the default), file:// and memory:// work out of the box. Any other backend\n needs its adapter installed alongside this server:\n npm install -g @keyv/redis@6\n TOKEN_STORE_URI=redis://localhost:6379 mcp-outlook\n\nOAuth Scopes:\n openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite\n\nExamples:\n mcp-outlook # Use default settings\n mcp-outlook --auth=device-code # Use device code auth\n mcp-outlook --port=3000 # HTTP transport on port 3000\n mcp-outlook --tenant-id=xxx # Set tenant ID\n mcp-outlook --resource-store-uri=file:///tmp/emails # Custom resource store URI\n MS_CLIENT_ID=xxx mcp-outlook # Set client ID via env var\n'.trim();
|
|
64
64
|
function readPkg() {
|
|
65
65
|
return pkg;
|
|
66
66
|
}
|