@mcp-z/mcp-outlook 2.4.1 → 2.4.3

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.
Files changed (78) hide show
  1. package/README.md +5 -1
  2. package/dist/cjs/constants.d.cts +1 -0
  3. package/dist/cjs/constants.d.ts +1 -0
  4. package/dist/cjs/constants.js +4 -0
  5. package/dist/cjs/constants.js.map +1 -1
  6. package/dist/cjs/email/querying/next-link.d.cts +5 -0
  7. package/dist/cjs/email/querying/next-link.d.ts +5 -0
  8. package/dist/cjs/email/querying/next-link.js +30 -0
  9. package/dist/cjs/email/querying/next-link.js.map +1 -0
  10. package/dist/cjs/email/querying/pagination-token.d.cts +3 -4
  11. package/dist/cjs/email/querying/pagination-token.d.ts +3 -4
  12. package/dist/cjs/email/querying/pagination-token.js +71 -49
  13. package/dist/cjs/email/querying/pagination-token.js.map +1 -1
  14. package/dist/cjs/email/querying/paging-decisions.d.cts +14 -0
  15. package/dist/cjs/email/querying/paging-decisions.d.ts +14 -0
  16. package/dist/cjs/email/querying/paging-decisions.js +91 -0
  17. package/dist/cjs/email/querying/paging-decisions.js.map +1 -0
  18. package/dist/cjs/email/querying/search-execution.js +130 -88
  19. package/dist/cjs/email/querying/search-execution.js.map +1 -1
  20. package/dist/cjs/lib/create-store.js +1 -1
  21. package/dist/cjs/lib/create-store.js.map +1 -1
  22. package/dist/cjs/mcp/tools/message-search.d.cts +1 -1
  23. package/dist/cjs/mcp/tools/message-search.d.ts +1 -1
  24. package/dist/cjs/mcp/tools/message-search.js +1 -1
  25. package/dist/cjs/mcp/tools/message-search.js.map +1 -1
  26. package/dist/cjs/mcp/tools/messages-export-csv.js +10 -6
  27. package/dist/cjs/mcp/tools/messages-export-csv.js.map +1 -1
  28. package/dist/cjs/setup/config.d.cts +2 -6
  29. package/dist/cjs/setup/config.d.ts +2 -6
  30. package/dist/cjs/setup/config.js +22 -0
  31. package/dist/cjs/setup/config.js.map +1 -1
  32. package/dist/cjs/setup/http.js +2 -1
  33. package/dist/cjs/setup/http.js.map +1 -1
  34. package/dist/cjs/setup/oauth-microsoft.d.cts +6 -1
  35. package/dist/cjs/setup/oauth-microsoft.d.ts +6 -1
  36. package/dist/cjs/setup/oauth-microsoft.js +5 -1
  37. package/dist/cjs/setup/oauth-microsoft.js.map +1 -1
  38. package/dist/cjs/setup/runtime.d.cts +1 -1
  39. package/dist/cjs/setup/runtime.d.ts +1 -1
  40. package/dist/cjs/setup/runtime.js +11 -6
  41. package/dist/cjs/setup/runtime.js.map +1 -1
  42. package/dist/cjs/setup/version-help.js +1 -1
  43. package/dist/cjs/setup/version-help.js.map +1 -1
  44. package/dist/esm/constants.d.ts +1 -0
  45. package/dist/esm/constants.js +2 -0
  46. package/dist/esm/constants.js.map +1 -1
  47. package/dist/esm/email/querying/next-link.d.ts +5 -0
  48. package/dist/esm/email/querying/next-link.js +22 -0
  49. package/dist/esm/email/querying/next-link.js.map +1 -0
  50. package/dist/esm/email/querying/pagination-token.d.ts +3 -4
  51. package/dist/esm/email/querying/pagination-token.js +22 -44
  52. package/dist/esm/email/querying/pagination-token.js.map +1 -1
  53. package/dist/esm/email/querying/paging-decisions.d.ts +14 -0
  54. package/dist/esm/email/querying/paging-decisions.js +21 -0
  55. package/dist/esm/email/querying/paging-decisions.js.map +1 -0
  56. package/dist/esm/email/querying/search-execution.js +82 -77
  57. package/dist/esm/email/querying/search-execution.js.map +1 -1
  58. package/dist/esm/lib/create-store.js +1 -1
  59. package/dist/esm/lib/create-store.js.map +1 -1
  60. package/dist/esm/mcp/tools/message-search.d.ts +1 -1
  61. package/dist/esm/mcp/tools/message-search.js +1 -1
  62. package/dist/esm/mcp/tools/message-search.js.map +1 -1
  63. package/dist/esm/mcp/tools/messages-export-csv.js +10 -6
  64. package/dist/esm/mcp/tools/messages-export-csv.js.map +1 -1
  65. package/dist/esm/setup/config.d.ts +2 -6
  66. package/dist/esm/setup/config.js +24 -6
  67. package/dist/esm/setup/config.js.map +1 -1
  68. package/dist/esm/setup/http.js +2 -1
  69. package/dist/esm/setup/http.js.map +1 -1
  70. package/dist/esm/setup/oauth-microsoft.d.ts +6 -1
  71. package/dist/esm/setup/oauth-microsoft.js +6 -2
  72. package/dist/esm/setup/oauth-microsoft.js.map +1 -1
  73. package/dist/esm/setup/runtime.d.ts +1 -1
  74. package/dist/esm/setup/runtime.js +11 -5
  75. package/dist/esm/setup/runtime.js.map +1 -1
  76. package/dist/esm/setup/version-help.js +3 -7
  77. package/dist/esm/setup/version-help.js.map +1 -1
  78. package/package.json +10 -4
@@ -17,6 +17,7 @@ var _fs = require("fs");
17
17
  var _promises = require("fs/promises");
18
18
  var _zod = require("zod");
19
19
  var _executequeryts = require("../../email/querying/execute-query.js");
20
+ var _pagingdecisionsts = require("../../email/querying/paging-decisions.js");
20
21
  var _outlookqueryschemats = require("../../schemas/outlook-query-schema.js");
21
22
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
22
23
  try {
@@ -242,7 +243,7 @@ var config = {
242
243
  * - NO RETRIES (fail fast on error)
243
244
  */ function handler(_0, _1) {
244
245
  return _async_to_generator(function(param, extra) {
245
- var query, maxItems, filename, contentType, excludeThreadHistory, logger, storageContext, transport, resourceStoreUri, baseUrl, reservation, storedName, fullPath, parsedQuery, graph, csvHeaders, writeStream, headerLine, totalRows, nextPageToken, started, _exec_metadata, remainingItems, pageSize, exec, csvRows, rowsContent, durationMs, truncated, uri, result, error, _cleanupError, message;
246
+ var query, maxItems, filename, contentType, excludeThreadHistory, logger, storageContext, transport, resourceStoreUri, baseUrl, reservation, storedName, fullPath, parsedQuery, graph, csvHeaders, writeStream, headerLine, totalRows, nextPageToken, truncated, started, _exec_metadata, _exec_metadata1, remainingItems, pageSize, exec, cut, csvRows, rowsContent, durationMs, uri, result, error, _cleanupError, message;
246
247
  return _ts_generator(this, function(_state) {
247
248
  switch(_state.label){
248
249
  case 0:
@@ -312,6 +313,7 @@ var config = {
312
313
  // Internal pagination loop - append to CSV with each batch
313
314
  // NO RETRIES: If any error occurs, fail the whole operation and clean up
314
315
  totalRows = 0;
316
+ truncated = false;
315
317
  started = Date.now();
316
318
  _state.label = 3;
317
319
  case 3:
@@ -381,7 +383,10 @@ var config = {
381
383
  ];
382
384
  case 4:
383
385
  exec = _state.sent();
384
- csvRows = exec.items.map(function(item) {
386
+ // The next-page link fixes $top at the first page's size, so a batch can hold more than is still wanted
387
+ cut = (0, _pagingdecisionsts.cutToMaxItems)(exec.items, totalRows, maxItems, Boolean((_exec_metadata = exec.metadata) === null || _exec_metadata === void 0 ? void 0 : _exec_metadata.nextPageToken));
388
+ truncated = cut.truncated;
389
+ csvRows = cut.rows.map(function(item) {
385
390
  return [
386
391
  item.id,
387
392
  item.threadId,
@@ -407,10 +412,10 @@ var config = {
407
412
  });
408
413
  writeStream.write(rowsContent);
409
414
  }
410
- totalRows += exec.items.length;
411
- nextPageToken = (_exec_metadata = exec.metadata) === null || _exec_metadata === void 0 ? void 0 : _exec_metadata.nextPageToken;
415
+ totalRows += cut.rows.length;
416
+ nextPageToken = (_exec_metadata1 = exec.metadata) === null || _exec_metadata1 === void 0 ? void 0 : _exec_metadata1.nextPageToken;
412
417
  logger.info('outlook.messages.export-csv batch written', {
413
- batchSize: exec.items.length,
418
+ batchSize: cut.rows.length,
414
419
  totalRows: totalRows,
415
420
  hasMore: Boolean(nextPageToken)
416
421
  });
@@ -439,7 +444,6 @@ var config = {
439
444
  case 6:
440
445
  _state.sent();
441
446
  durationMs = Date.now() - started;
442
- truncated = totalRows >= maxItems && Boolean(nextPageToken);
443
447
  logger.info('outlook.messages.export-csv completed', {
444
448
  rowCount: totalRows,
445
449
  truncated: truncated,
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/mcp/tools/messages-export-csv.ts"],"sourcesContent":["/** Outlook message CSV export tool - streams results to file without loading all data into context */\n\nimport { EmailContentTypeSchema, ExcludeThreadHistorySchema, extractCurrentMessageFromHtml, extractCurrentMessageFromHtmlToText } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-microsoft';\nimport { schemas } from '@mcp-z/oauth-microsoft';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, getFileUri, ProtocolError, ProtocolErrorCode, reserveFile, type ToolModule } from '@mcp-z/server';\nimport { Client } from '@microsoft/microsoft-graph-client';\nimport type * as MicrosoftGraph from '@microsoft/microsoft-graph-types';\nimport { stringify } from 'csv-stringify/sync';\nimport { createWriteStream } from 'fs';\nimport { unlink } from 'fs/promises';\nimport { z } from 'zod';\nimport { executeQuery as executeOutlookQuery } from '../../email/querying/execute-query.ts';\nimport { InvalidQueryError, OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.ts';\nimport type { StorageExtra } from '../../types.ts';\n\nconst DEFAULT_PAGE_SIZE = 50;\nconst DEFAULT_MAX_ITEMS = 10000;\nconst MAX_EXPORT_ITEMS = 50000;\n\nconst ExportResultSchema = z.object({\n uri: z.string().describe('File URI (file:// or http://)'),\n filename: z.string().describe('Stored filename'),\n rowCount: z.number().describe('Number of messages exported'),\n truncated: z.boolean().describe('Whether export was truncated at maxItems'),\n});\n\nconst inputSchema = z.object({\n query: OutlookQueryParameterSchema.optional().describe('Structured query object or JSON string for filtering messages. Use query-syntax prompt for reference and kqlQuery for KQL syntax.'),\n maxItems: z.number().int().positive().max(MAX_EXPORT_ITEMS).default(DEFAULT_MAX_ITEMS).describe(`Maximum messages to export (default: ${DEFAULT_MAX_ITEMS}, max: ${MAX_EXPORT_ITEMS})`),\n filename: z.string().trim().min(1).default('outlook-messages.csv').describe('Output filename (default: outlook-messages.csv)'),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schema\nconst successBranchSchema = ExportResultSchema.extend({\n type: z.literal('success'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Export Outlook messages to CSV with streaming pagination. Returns file URI. Use query-syntax prompt for query reference.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n/**\n * Handler for outlook-messages-export-csv tool\n *\n * CRITICAL: Streaming implementation per user requirements\n * - Generate UUID upfront\n * - Write CSV header immediately\n * - Append rows as batches arrive\n * - Delete partial file on error\n * - NO RETRIES (fail fast on error)\n */\nasync function handler({ query, maxItems, filename, contentType, excludeThreadHistory }: Input, extra: EnrichedExtra & StorageExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n const { storageContext } = extra;\n const { transport, resourceStoreUri, baseUrl } = storageContext;\n\n // Reserve file location for streaming write (creates directory, generates ID, formats filename)\n const reservation = await reserveFile(filename, {\n resourceStoreUri,\n });\n const { storedName, fullPath } = reservation;\n\n logger.info('outlook.messages.export-csv starting streaming export', { path: fullPath, maxItems });\n\n try {\n const parsedQuery = parseOutlookQueryParameter(query);\n\n logger.info('outlook.messages.export-csv called', {\n query: parsedQuery,\n maxItems,\n filename,\n accountId: extra.authContext.accountId,\n });\n\n const graph = Client.initWithMiddleware({ authProvider: extra.authContext.auth });\n\n // Create CSV headers (all email fields)\n const csvHeaders = ['id', 'threadId', 'from', 'to', 'cc', 'bcc', 'subject', 'date', 'snippet', 'body', 'provider', 'labels'];\n\n // Create write stream and write headers immediately\n const writeStream = createWriteStream(fullPath, { encoding: 'utf-8' });\n const headerLine = stringify([csvHeaders], { header: false, quoted: true, quote: '\"', escape: '\"' });\n writeStream.write(headerLine);\n\n // Internal pagination loop - append to CSV with each batch\n // NO RETRIES: If any error occurs, fail the whole operation and clean up\n let totalRows = 0;\n let nextPageToken: string | undefined;\n const started = Date.now();\n\n while (totalRows < maxItems) {\n const remainingItems = maxItems - totalRows;\n const pageSize = Math.min(remainingItems, DEFAULT_PAGE_SIZE);\n\n const exec: {\n items: Array<{\n id: string;\n threadId?: string;\n from: string;\n to: string;\n cc: string;\n bcc: string;\n subject: string;\n date: string;\n snippet: string;\n body: string;\n provider: string;\n labels: string;\n }>;\n metadata?: { nextPageToken?: string };\n } = await executeOutlookQuery(\n graph,\n parsedQuery,\n {\n logger,\n pageSize,\n ...(nextPageToken !== undefined && { pageToken: nextPageToken }),\n includeBody: true, // Always include body for CSV export\n limit: pageSize,\n },\n (m: unknown) => {\n const message = m as MicrosoftGraph.Message;\n const to = Array.isArray(message?.toRecipients)\n ? message.toRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const cc = Array.isArray(message?.ccRecipients)\n ? message.ccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const bcc = Array.isArray(message?.bccRecipients)\n ? message.bccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const fromAddr = message?.from?.emailAddress?.address ?? (message?.from as { address?: string })?.address ?? '';\n const categories = Array.isArray(message?.categories) ? message.categories.join(';') : '';\n\n // Process body based on contentType and excludeThreadHistory options\n let body = message?.body?.content ?? '';\n const isHtml = message?.body?.contentType?.toLowerCase() === 'html';\n\n if (isHtml && excludeThreadHistory) {\n body = extractCurrentMessageFromHtml(body);\n }\n\n if (isHtml && contentType === 'text') {\n body = excludeThreadHistory ? extractCurrentMessageFromHtmlToText(body) : extractCurrentMessageFromHtmlToText(message?.body?.content ?? '');\n }\n\n return {\n id: String(message?.id ?? ''),\n threadId: message?.conversationId ? String(message.conversationId) : '',\n from: fromAddr,\n to,\n cc,\n bcc,\n subject: message?.subject ?? '',\n date: message?.receivedDateTime ?? '',\n snippet: message?.bodyPreview ?? '',\n body,\n provider: 'outlook' as const,\n labels: categories,\n };\n }\n );\n\n const csvRows = exec.items.map((item) => {\n return [item.id, item.threadId, item.from, item.to, item.cc, item.bcc, item.subject, item.date, item.snippet, item.body, item.provider, item.labels];\n });\n\n // Append rows to CSV file immediately\n if (csvRows.length > 0) {\n const rowsContent = stringify(csvRows, { header: false, quoted: true, quote: '\"', escape: '\"' });\n writeStream.write(rowsContent);\n }\n\n totalRows += exec.items.length;\n nextPageToken = exec.metadata?.nextPageToken;\n\n logger.info('outlook.messages.export-csv batch written', {\n batchSize: exec.items.length,\n totalRows,\n hasMore: Boolean(nextPageToken),\n });\n\n // Exit if no more results or reached maxItems\n if (!nextPageToken || exec.items.length === 0) {\n break;\n }\n }\n\n // Close write stream\n await new Promise<void>((resolve, reject) => {\n writeStream.end(() => resolve());\n writeStream.on('error', reject);\n });\n\n const durationMs = Date.now() - started;\n const truncated = totalRows >= maxItems && Boolean(nextPageToken);\n\n logger.info('outlook.messages.export-csv completed', {\n rowCount: totalRows,\n truncated,\n durationMs,\n filename: storedName,\n });\n\n // Generate URI based on transport type (stdio: file://, HTTP: http://)\n const uri = getFileUri(storedName, transport, {\n resourceStoreUri,\n ...(baseUrl && { baseUrl }),\n endpoint: '/files',\n });\n\n const result: Output = {\n type: 'success' as const,\n uri,\n filename: storedName,\n rowCount: totalRows,\n truncated,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n // CRITICAL: Clean up partial CSV file on error\n try {\n await unlink(fullPath);\n logger.debug('Cleaned up partial CSV file after error', { path: fullPath });\n } catch (_cleanupError) {\n logger.debug('Could not clean up CSV file (may not exist)', { path: fullPath });\n }\n\n if (error instanceof ProtocolError) throw error;\n if (error instanceof InvalidQueryError) throw new ProtocolError(ProtocolErrorCode.InvalidParams, error.message);\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('outlook.messages.export-csv error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error exporting messages to CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'messages-export-csv',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","DEFAULT_PAGE_SIZE","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","ExportResultSchema","z","object","uri","string","describe","filename","rowCount","number","truncated","boolean","inputSchema","query","OutlookQueryParameterSchema","optional","maxItems","int","positive","max","default","trim","min","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","storageContext","transport","resourceStoreUri","baseUrl","reservation","storedName","fullPath","parsedQuery","graph","csvHeaders","writeStream","headerLine","totalRows","nextPageToken","started","exec","remainingItems","pageSize","csvRows","rowsContent","durationMs","error","_cleanupError","message","reserveFile","info","path","parseOutlookQueryParameter","accountId","authContext","Client","initWithMiddleware","authProvider","auth","createWriteStream","encoding","stringify","header","quoted","quote","escape","write","Date","now","Math","executeOutlookQuery","undefined","pageToken","includeBody","limit","m","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","categories","body","content","isHtml","toLowerCase","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","id","String","threadId","conversationId","subject","date","receivedDateTime","snippet","bodyPreview","provider","labels","items","item","length","metadata","batchSize","hasMore","Promise","resolve","reject","end","on","getFileUri","endpoint","text","JSON","structuredContent","unlink","debug","ProtocolError","InvalidQueryError","ProtocolErrorCode","InvalidParams","Error","InternalError","stack","name"],"mappings":"AAAA,oGAAoG;;;;+BAkRpG;;;eAAwBA;;;qBAhR+G;8BAE/G;sBAIwF;oCACzF;oBAEG;kBACQ;wBACX;mBACL;8BACkC;oCACuC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,AAAK,YAALA,OAAiBmF,qBAAa,GAAE,MAAMnF;oBAC1C,IAAIA,AAAK,YAALA,OAAiBoF,uCAAiB,GAAE,MAAM,IAAID,qBAAa,CAACE,yBAAiB,CAACC,aAAa,EAAEtF,MAAME,OAAO;oBAExGA,UAAUF,AAAK,YAALA,OAAiBuF,SAAQvF,MAAME,OAAO,GAAGqD,OAAOvD;oBAChEtB,OAAOsB,KAAK,CAAC,qCAAqC;wBAAEA,OAAOE;oBAAQ;oBAEnE,MAAM,IAAIiF,qBAAa,CAACE,yBAAiB,CAACG,aAAa,EAAE,AAAC,oCAA2C,OAARtF,UAAW;wBACtGuF,OAAOzF,AAAK,YAALA,OAAiBuF,SAAQvF,MAAMyF,KAAK,GAAGhE;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1F;IACtB,OAAO;QACL2J,MAAM;QACNrH,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/mcp/tools/messages-export-csv.ts"],"sourcesContent":["/** Outlook message CSV export tool - streams results to file without loading all data into context */\n\nimport { EmailContentTypeSchema, ExcludeThreadHistorySchema, extractCurrentMessageFromHtml, extractCurrentMessageFromHtmlToText } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-microsoft';\nimport { schemas } from '@mcp-z/oauth-microsoft';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, getFileUri, ProtocolError, ProtocolErrorCode, reserveFile, type ToolModule } from '@mcp-z/server';\nimport { Client } from '@microsoft/microsoft-graph-client';\nimport type * as MicrosoftGraph from '@microsoft/microsoft-graph-types';\nimport { stringify } from 'csv-stringify/sync';\nimport { createWriteStream } from 'fs';\nimport { unlink } from 'fs/promises';\nimport { z } from 'zod';\nimport { executeQuery as executeOutlookQuery } from '../../email/querying/execute-query.ts';\nimport { cutToMaxItems } from '../../email/querying/paging-decisions.ts';\nimport { InvalidQueryError, OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.ts';\nimport type { StorageExtra } from '../../types.ts';\n\nconst DEFAULT_PAGE_SIZE = 50;\nconst DEFAULT_MAX_ITEMS = 10000;\nconst MAX_EXPORT_ITEMS = 50000;\n\nconst ExportResultSchema = z.object({\n uri: z.string().describe('File URI (file:// or http://)'),\n filename: z.string().describe('Stored filename'),\n rowCount: z.number().describe('Number of messages exported'),\n truncated: z.boolean().describe('Whether export was truncated at maxItems'),\n});\n\nconst inputSchema = z.object({\n query: OutlookQueryParameterSchema.optional().describe('Structured query object or JSON string for filtering messages. Use query-syntax prompt for reference and kqlQuery for KQL syntax.'),\n maxItems: z.number().int().positive().max(MAX_EXPORT_ITEMS).default(DEFAULT_MAX_ITEMS).describe(`Maximum messages to export (default: ${DEFAULT_MAX_ITEMS}, max: ${MAX_EXPORT_ITEMS})`),\n filename: z.string().trim().min(1).default('outlook-messages.csv').describe('Output filename (default: outlook-messages.csv)'),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schema\nconst successBranchSchema = ExportResultSchema.extend({\n type: z.literal('success'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Export Outlook messages to CSV with streaming pagination. Returns file URI. Use query-syntax prompt for query reference.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n/**\n * Handler for outlook-messages-export-csv tool\n *\n * CRITICAL: Streaming implementation per user requirements\n * - Generate UUID upfront\n * - Write CSV header immediately\n * - Append rows as batches arrive\n * - Delete partial file on error\n * - NO RETRIES (fail fast on error)\n */\nasync function handler({ query, maxItems, filename, contentType, excludeThreadHistory }: Input, extra: EnrichedExtra & StorageExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n const { storageContext } = extra;\n const { transport, resourceStoreUri, baseUrl } = storageContext;\n\n // Reserve file location for streaming write (creates directory, generates ID, formats filename)\n const reservation = await reserveFile(filename, {\n resourceStoreUri,\n });\n const { storedName, fullPath } = reservation;\n\n logger.info('outlook.messages.export-csv starting streaming export', { path: fullPath, maxItems });\n\n try {\n const parsedQuery = parseOutlookQueryParameter(query);\n\n logger.info('outlook.messages.export-csv called', {\n query: parsedQuery,\n maxItems,\n filename,\n accountId: extra.authContext.accountId,\n });\n\n const graph = Client.initWithMiddleware({ authProvider: extra.authContext.auth });\n\n // Create CSV headers (all email fields)\n const csvHeaders = ['id', 'threadId', 'from', 'to', 'cc', 'bcc', 'subject', 'date', 'snippet', 'body', 'provider', 'labels'];\n\n // Create write stream and write headers immediately\n const writeStream = createWriteStream(fullPath, { encoding: 'utf-8' });\n const headerLine = stringify([csvHeaders], { header: false, quoted: true, quote: '\"', escape: '\"' });\n writeStream.write(headerLine);\n\n // Internal pagination loop - append to CSV with each batch\n // NO RETRIES: If any error occurs, fail the whole operation and clean up\n let totalRows = 0;\n let nextPageToken: string | undefined;\n let truncated = false;\n const started = Date.now();\n\n while (totalRows < maxItems) {\n const remainingItems = maxItems - totalRows;\n const pageSize = Math.min(remainingItems, DEFAULT_PAGE_SIZE);\n\n const exec: {\n items: Array<{\n id: string;\n threadId?: string;\n from: string;\n to: string;\n cc: string;\n bcc: string;\n subject: string;\n date: string;\n snippet: string;\n body: string;\n provider: string;\n labels: string;\n }>;\n metadata?: { nextPageToken?: string };\n } = await executeOutlookQuery(\n graph,\n parsedQuery,\n {\n logger,\n pageSize,\n ...(nextPageToken !== undefined && { pageToken: nextPageToken }),\n includeBody: true, // Always include body for CSV export\n limit: pageSize,\n },\n (m: unknown) => {\n const message = m as MicrosoftGraph.Message;\n const to = Array.isArray(message?.toRecipients)\n ? message.toRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const cc = Array.isArray(message?.ccRecipients)\n ? message.ccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const bcc = Array.isArray(message?.bccRecipients)\n ? message.bccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const fromAddr = message?.from?.emailAddress?.address ?? (message?.from as { address?: string })?.address ?? '';\n const categories = Array.isArray(message?.categories) ? message.categories.join(';') : '';\n\n // Process body based on contentType and excludeThreadHistory options\n let body = message?.body?.content ?? '';\n const isHtml = message?.body?.contentType?.toLowerCase() === 'html';\n\n if (isHtml && excludeThreadHistory) {\n body = extractCurrentMessageFromHtml(body);\n }\n\n if (isHtml && contentType === 'text') {\n body = excludeThreadHistory ? extractCurrentMessageFromHtmlToText(body) : extractCurrentMessageFromHtmlToText(message?.body?.content ?? '');\n }\n\n return {\n id: String(message?.id ?? ''),\n threadId: message?.conversationId ? String(message.conversationId) : '',\n from: fromAddr,\n to,\n cc,\n bcc,\n subject: message?.subject ?? '',\n date: message?.receivedDateTime ?? '',\n snippet: message?.bodyPreview ?? '',\n body,\n provider: 'outlook' as const,\n labels: categories,\n };\n }\n );\n\n // The next-page link fixes $top at the first page's size, so a batch can hold more than is still wanted\n const cut = cutToMaxItems(exec.items, totalRows, maxItems, Boolean(exec.metadata?.nextPageToken));\n truncated = cut.truncated;\n\n const csvRows = cut.rows.map((item) => {\n return [item.id, item.threadId, item.from, item.to, item.cc, item.bcc, item.subject, item.date, item.snippet, item.body, item.provider, item.labels];\n });\n\n // Append rows to CSV file immediately\n if (csvRows.length > 0) {\n const rowsContent = stringify(csvRows, { header: false, quoted: true, quote: '\"', escape: '\"' });\n writeStream.write(rowsContent);\n }\n\n totalRows += cut.rows.length;\n nextPageToken = exec.metadata?.nextPageToken;\n\n logger.info('outlook.messages.export-csv batch written', {\n batchSize: cut.rows.length,\n totalRows,\n hasMore: Boolean(nextPageToken),\n });\n\n // Exit if no more results or reached maxItems\n if (!nextPageToken || exec.items.length === 0) {\n break;\n }\n }\n\n // Close write stream\n await new Promise<void>((resolve, reject) => {\n writeStream.end(() => resolve());\n writeStream.on('error', reject);\n });\n\n const durationMs = Date.now() - started;\n\n logger.info('outlook.messages.export-csv completed', {\n rowCount: totalRows,\n truncated,\n durationMs,\n filename: storedName,\n });\n\n // Generate URI based on transport type (stdio: file://, HTTP: http://)\n const uri = getFileUri(storedName, transport, {\n resourceStoreUri,\n ...(baseUrl && { baseUrl }),\n endpoint: '/files',\n });\n\n const result: Output = {\n type: 'success' as const,\n uri,\n filename: storedName,\n rowCount: totalRows,\n truncated,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n // CRITICAL: Clean up partial CSV file on error\n try {\n await unlink(fullPath);\n logger.debug('Cleaned up partial CSV file after error', { path: fullPath });\n } catch (_cleanupError) {\n logger.debug('Could not clean up CSV file (may not exist)', { path: fullPath });\n }\n\n if (error instanceof ProtocolError) throw error;\n if (error instanceof InvalidQueryError) throw new ProtocolError(ProtocolErrorCode.InvalidParams, error.message);\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('outlook.messages.export-csv error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error exporting messages to CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'messages-export-csv',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","DEFAULT_PAGE_SIZE","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","ExportResultSchema","z","object","uri","string","describe","filename","rowCount","number","truncated","boolean","inputSchema","query","OutlookQueryParameterSchema","optional","maxItems","int","positive","max","default","trim","min","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","storageContext","transport","resourceStoreUri","baseUrl","reservation","storedName","fullPath","parsedQuery","graph","csvHeaders","writeStream","headerLine","totalRows","nextPageToken","started","exec","remainingItems","pageSize","cut","csvRows","rowsContent","durationMs","error","_cleanupError","message","reserveFile","info","path","parseOutlookQueryParameter","accountId","authContext","Client","initWithMiddleware","authProvider","auth","createWriteStream","encoding","stringify","header","quoted","quote","escape","write","Date","now","Math","executeOutlookQuery","undefined","pageToken","includeBody","limit","m","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","categories","body","content","isHtml","toLowerCase","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","id","String","threadId","conversationId","subject","date","receivedDateTime","snippet","bodyPreview","provider","labels","cutToMaxItems","items","metadata","rows","item","length","batchSize","hasMore","Promise","resolve","reject","end","on","getFileUri","endpoint","text","JSON","structuredContent","unlink","debug","ProtocolError","InvalidQueryError","ProtocolErrorCode","InvalidParams","Error","InternalError","stack","name"],"mappings":"AAAA,oGAAoG;;;;+BAuRpG;;;eAAwBA;;;qBArR+G;8BAE/G;sBAIwF;oCACzF;oBAEG;kBACQ;wBACX;mBACL;8BACkC;iCACtB;oCAC6D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAX3F,IAAM,AAAEC,2BAA6BC,uBAAO,CAApCD;AAcR,IAAME,oBAAoB;AAC1B,IAAMC,oBAAoB;AAC1B,IAAMC,mBAAmB;AAEzB,IAAMC,qBAAqBC,MAAC,CAACC,MAAM,CAAC;IAClCC,KAAKF,MAAC,CAACG,MAAM,G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Aa,EAAExF,MAAME,OAAO;oBAExGA,UAAUF,AAAK,YAALA,OAAiByF,SAAQzF,MAAME,OAAO,GAAGqD,OAAOvD;oBAChEvB,OAAOuB,KAAK,CAAC,qCAAqC;wBAAEA,OAAOE;oBAAQ;oBAEnE,MAAM,IAAImF,qBAAa,CAACE,yBAAiB,CAACG,aAAa,EAAE,AAAC,oCAA2C,OAARxF,UAAW;wBACtGyF,OAAO3F,AAAK,YAALA,OAAiByF,SAAQzF,MAAM2F,KAAK,GAAGlE;oBAChD;;;;;;;IAEJ;;AAEe,SAAS3F;IACtB,OAAO;QACL8J,MAAM;QACNxH,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -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-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)
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: file://~/.mcp-z/mcp-outlook/files)
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-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)
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: file://~/.mcp-z/mcp-outlook/files)
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)
@@ -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,CAACC,OAAO,CAAC,aAAa;AAElD,0FAA0F;AAC1F,wFAAwF;AACxF,IAAMC,WAAW,OAAOC,YAAY,cAAcC,cAAM,CAACC,aA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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,YAAY,cAAcC,cAAM,CAACC,aAAa,CAAC,uDAAmBF;AAkCnF,SAASP,YAAYU,IAAc,EAAEC,GAAuC;cA+BhEC,OAMkCC;IApCnD,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,sBAAa,EAACrC,MAAKsC,OAAO,CAACG,eAAeF,IAAI;AACvD"}
@@ -230,7 +230,8 @@ function createHTTPServer(config, overrides) {
230
230
  ] : undefined,
231
231
  allowedHosts: publicUrl ? [
232
232
  publicUrl.host
233
- ] : undefined
233
+ ] : undefined,
234
+ bearerAuth: runtime.deps.oauthAdapters.bearerAuth
234
235
  })
235
236
  ];
236
237
  case 2:
@@ -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;;;s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5B;oBAEA,IAAId,QAAQoB,IAAI,CAACI,aAAa,CAACmC,SAAS,EAAE;wBACxCjD,IAAI+B,GAAG,CAAC,KAAKa,IAAAA,aAAI,KAAItD,QAAQoB,IAAI,CAACI,aAAa,CAACmC,SAAS;wBACzDvD,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
+ {"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,cAA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d;oBAEA,IAAIjD,OAAO4B,IAAI,KAAK,OAAO;wBACnBZ,aAAa0C,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,QAMAH,eACAC,iBAGAG;;YA3IEZ,SAAiCF,KAAjCE,QAAQC,aAAyBH,KAAzBG,YAAYC,WAAaJ,KAAbI;YACtBC,oBAAoB;gBACxBU,SAAShB,OAAOiB,IAAI;gBACpBC,UAAUlB,OAAOkB,QAAQ;gBACzBC,cAAcnB,OAAOmB,YAAY;gBACjCC,OAAOC,qBAAQ;gBACfC,UAAUtB,OAAOsB,QAAQ;gBACzBC,MAAMvB,OAAOuB,IAAI;gBACjBC,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,OAAO;gBAClCE,UAAUZ,kBAAkBY,QAAQ;gBACpCC,cAAcb,kBAAkBa,YAAY;gBAC5CC,OAAOd,kBAAkBc,KAAK;gBAC9BE,UAAUhB,kBAAkBgB,QAAQ;gBACpCE,UAAUlB,kBAAkBkB,QAAQ;gBACpCrB,QAAAA;gBACAC,YAAAA;eACIE,kBAAkBmB,WAAW,KAAKG,aAAa;gBAAEH,aAAanB,kBAAkBmB,WAAW;YAAC;YAGlG,gEAAgE;YAC1Df,eAAmCH;YAEzC,yDAAyD;YACnDE,cAAkEF,QAAQgC,cAAc;YAE9F,sCAAsC;YAChCzB,SAASgC,oBAAa,CAACC,cAAc,CAAC;gBAC1C/B,SAASV,kBAAkBU,OAAO;gBAClCkB,OAAO9B;gBACPD,QAAAA;gBACAoB,MAAMb;YACR;YACMC,gBAA6BG,OAAOkC,KAAK;YACzCpC,kBAAiCE,OAAOmC,OAAO;YACrD9C,OAAO0B,KAAK,CAAC,uCAAuC;gBAAEb,SAASV,kBAAkBU,OAAO;YAAC;YAEnFD,iBAAiBT,kBAAkBmB,WAAW,GAAGyB,IAAAA,4CAA4B,EAAC3C,WAAWqB;YAE/F;;gBAAO;oBAAErB,SAAAA;oBAASE,YAAYA;oBAA8BC,aAAAA;oBAAaC,cAAAA;oBAAcC,gBAAAA;oBAAgBG,gBAAAA;gBAAe;;;IACxH"}
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, 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDlB,SAAeA,oBAAoBC,MAAoB,EAAEC,IAAsB,EAAEC,OAAgB;;YAC9FC,QAAQC,YAAYC,UACtBC,mBAYFC,SAyBIC,WAaAC,YAGAC,aAUAC,cACAC,gBAwBAC,oBAYAJ,aAGAC,cAMAC,eACAC,iBAuBFF,cAGAD,aAGAK,QAMAH,eACAC,iBAGAG;;YAtJEZ,SAAiCF,KAAjCE,QAA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BAAe;;;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: false
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 || (0, _nodeurl.pathToFileURL)(_path.join(baseDir, 'tokens.json')).href;
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 || (0, _nodeurl.pathToFileURL)(_path.join(baseDir, 'dcr.json')).href;
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();