@mcp-z/mcp-outlook 2.4.0 → 2.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/cjs/constants.d.cts +1 -0
- package/dist/cjs/constants.d.ts +1 -0
- package/dist/cjs/constants.js +4 -0
- package/dist/cjs/constants.js.map +1 -1
- package/dist/cjs/email/querying/query-builder.d.cts +2 -2
- package/dist/cjs/email/querying/query-builder.d.ts +2 -2
- package/dist/cjs/email/querying/query-builder.js +35 -28
- package/dist/cjs/email/querying/query-builder.js.map +1 -1
- package/dist/cjs/lib/create-store.js +1 -1
- package/dist/cjs/lib/create-store.js.map +1 -1
- package/dist/cjs/mcp/tools/label-delete.d.cts +11 -1
- package/dist/cjs/mcp/tools/label-delete.d.ts +11 -1
- package/dist/cjs/mcp/tools/label-delete.js +32 -4
- package/dist/cjs/mcp/tools/label-delete.js.map +1 -1
- package/dist/cjs/mcp/tools/message-search.js +1 -0
- package/dist/cjs/mcp/tools/message-search.js.map +1 -1
- package/dist/cjs/mcp/tools/messages-export-csv.js +1 -0
- package/dist/cjs/mcp/tools/messages-export-csv.js.map +1 -1
- package/dist/cjs/schemas/outlook-query-schema.d.cts +7 -0
- package/dist/cjs/schemas/outlook-query-schema.d.ts +7 -0
- package/dist/cjs/schemas/outlook-query-schema.js +116 -3
- package/dist/cjs/schemas/outlook-query-schema.js.map +1 -1
- package/dist/cjs/setup/config.d.cts +2 -6
- package/dist/cjs/setup/config.d.ts +2 -6
- package/dist/cjs/setup/config.js +22 -0
- package/dist/cjs/setup/config.js.map +1 -1
- package/dist/cjs/setup/http.js +2 -1
- package/dist/cjs/setup/http.js.map +1 -1
- package/dist/cjs/setup/oauth-microsoft.d.cts +6 -1
- package/dist/cjs/setup/oauth-microsoft.d.ts +6 -1
- package/dist/cjs/setup/oauth-microsoft.js +5 -1
- package/dist/cjs/setup/oauth-microsoft.js.map +1 -1
- package/dist/cjs/setup/runtime.d.cts +1 -1
- package/dist/cjs/setup/runtime.d.ts +1 -1
- package/dist/cjs/setup/runtime.js +11 -6
- package/dist/cjs/setup/runtime.js.map +1 -1
- package/dist/cjs/setup/version-help.js +1 -1
- package/dist/cjs/setup/version-help.js.map +1 -1
- package/dist/esm/constants.d.ts +1 -0
- package/dist/esm/constants.js +2 -0
- package/dist/esm/constants.js.map +1 -1
- package/dist/esm/email/querying/query-builder.d.ts +2 -2
- package/dist/esm/email/querying/query-builder.js +16 -20
- package/dist/esm/email/querying/query-builder.js.map +1 -1
- package/dist/esm/lib/create-store.js +1 -1
- package/dist/esm/lib/create-store.js.map +1 -1
- package/dist/esm/mcp/tools/label-delete.d.ts +11 -1
- package/dist/esm/mcp/tools/label-delete.js +21 -0
- package/dist/esm/mcp/tools/label-delete.js.map +1 -1
- package/dist/esm/mcp/tools/message-search.js +2 -1
- package/dist/esm/mcp/tools/message-search.js.map +1 -1
- package/dist/esm/mcp/tools/messages-export-csv.js +2 -1
- package/dist/esm/mcp/tools/messages-export-csv.js.map +1 -1
- package/dist/esm/schemas/outlook-query-schema.d.ts +7 -0
- package/dist/esm/schemas/outlook-query-schema.js +12 -3
- package/dist/esm/schemas/outlook-query-schema.js.map +1 -1
- package/dist/esm/setup/config.d.ts +2 -6
- package/dist/esm/setup/config.js +24 -6
- package/dist/esm/setup/config.js.map +1 -1
- package/dist/esm/setup/http.js +2 -1
- package/dist/esm/setup/http.js.map +1 -1
- package/dist/esm/setup/oauth-microsoft.d.ts +6 -1
- package/dist/esm/setup/oauth-microsoft.js +6 -2
- package/dist/esm/setup/oauth-microsoft.js.map +1 -1
- package/dist/esm/setup/runtime.d.ts +1 -1
- package/dist/esm/setup/runtime.js +11 -5
- package/dist/esm/setup/runtime.js.map +1 -1
- package/dist/esm/setup/version-help.js +3 -7
- package/dist/esm/setup/version-help.js.map +1 -1
- package/package.json +10 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/mcp/tools/message-search.ts"],"sourcesContent":["import { EMAIL_COMMON_PATTERNS, EMAIL_FIELD_DESCRIPTIONS, EMAIL_FIELDS, EmailContentTypeSchema, type EmailDetail, EmailDetailSchema, 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, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, type ToolModule, toColumnarFormat } from '@mcp-z/server';\nimport { Client } from '@microsoft/microsoft-graph-client';\nimport type * as MicrosoftGraph from '@microsoft/microsoft-graph-types';\nimport { z } from 'zod';\nimport { needsBody } from '../../email/querying/client-filter.ts';\nimport { executeQuery as executeOutlookQuery } from '../../email/querying/execute-query.ts';\nimport { OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.ts';\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 fields: createFieldsSchema({\n availableFields: EMAIL_FIELDS,\n fieldDescriptions: EMAIL_FIELD_DESCRIPTIONS,\n commonPatterns: EMAIL_COMMON_PATTERNS,\n resourceName: 'email message',\n }),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 500,\n provider: 'outlook',\n }).shape,\n shape: createShapeSchema(),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(EmailDetailSchema).describe('Matching email messages'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search Outlook messages using structured query objects with flexible field selection.',\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\nasync function handler({ query, pageSize = 50, pageToken, fields, shape = 'arrays', contentType, excludeThreadHistory }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseOutlookQueryParameter(query);\n const requestedFields = parseFields(fields, EMAIL_FIELDS);\n const needsBodyContent = needsBody(parsedQuery);\n const includeBody = requestedFields === 'all' || requestedFields.has('body') || needsBodyContent;\n\n logger.info('outlook.search called with', {\n query: parsedQuery,\n pageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n includeBody,\n });\n\n const graph = Client.initWithMiddleware({\n authProvider: extra.authContext.auth,\n });\n const started = Date.now();\n const exec = await executeOutlookQuery(\n graph,\n parsedQuery,\n {\n logger,\n pageSize,\n ...(pageToken ? { pageToken } : {}),\n includeBody,\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)\n .filter(Boolean)\n .join(', ')\n : undefined;\n const cc = Array.isArray(message?.ccRecipients)\n ? message.ccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address)\n .filter(Boolean)\n .join(', ')\n : undefined;\n const bcc = Array.isArray(message?.bccRecipients)\n ? message.bccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address)\n .filter(Boolean)\n .join(', ')\n : undefined;\n const fromAddr = message?.from?.emailAddress?.address ?? null;\n const fromName = message?.from?.emailAddress?.name ?? null;\n // Process body based on contentType and excludeThreadHistory options\n let bodyContent: string | undefined;\n if (includeBody && message?.body?.content) {\n const isHtml = message.body.contentType?.toLowerCase() === 'html';\n bodyContent = message.body.content;\n\n if (isHtml && excludeThreadHistory) {\n bodyContent = extractCurrentMessageFromHtml(bodyContent);\n }\n\n if (isHtml && contentType === 'text') {\n bodyContent = excludeThreadHistory ? extractCurrentMessageFromHtmlToText(bodyContent) : extractCurrentMessageFromHtmlToText(message.body.content);\n }\n }\n\n const mapped: Partial<EmailDetail> = {\n id: message?.id ?? undefined,\n subject: message?.subject ?? undefined,\n from: fromAddr ?? undefined,\n fromName: fromName ?? undefined,\n to,\n cc,\n bcc,\n date: message?.receivedDateTime ?? undefined,\n snippet: message?.bodyPreview ?? undefined,\n ...(bodyContent && { body: bodyContent, bodyContentType: contentType }),\n };\n return mapped;\n }\n );\n const durationMs = Date.now() - started;\n\n const filteredItems = exec.items.map((item) => filterFields(item, requestedFields));\n logger.info('outlook.message.search returning', {\n query,\n pageSize,\n itemsLength: filteredItems.length,\n fields: fields || 'all',\n });\n logger.info('outlook.message.search metrics', {\n durationMs,\n metadata: exec.metadata,\n });\n\n // Type-safe metadata access\n const metadataObj = exec.metadata as { nextPageToken?: string } | undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, EMAIL_FIELDS),\n ...(metadataObj?.nextPageToken && { nextPageToken: metadataObj.nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n ...(metadataObj?.nextPageToken && { nextPageToken: metadataObj.nextPageToken }),\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 if (error instanceof ProtocolError) throw error;\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('outlook.message.search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching messages: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","OutlookQueryParameterSchema","optional","describe","fields","createFieldsSchema","availableFields","EMAIL_FIELDS","fieldDescriptions","EMAIL_FIELD_DESCRIPTIONS","commonPatterns","EMAIL_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successObjectsBranchSchema","type","literal","items","array","EmailDetailSchema","nextPageToken","string","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","description","result","handler","extra","pageSize","pageToken","logger","parsedQuery","requestedFields","needsBodyContent","includeBody","graph","started","exec","durationMs","filteredItems","metadataObj","error","message","parseOutlookQueryParameter","parseFields","needsBody","has","info","undefined","Client","initWithMiddleware","authProvider","authContext","auth","Date","now","executeOutlookQuery","limit","m","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","fromName","name","bodyContent","body","content","isHtml","toLowerCase","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","mapped","id","subject","date","receivedDateTime","snippet","bodyPreview","bodyContentType","item","filterFields","itemsLength","length","metadata","toColumnarFormat","text","JSON","stringify","structuredContent","ProtocolError","Error","String","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BAwMA;;;eAAwBA;;;qBAxMmN;8BAEnN;sBAI2K;oCAC5K;mBAEL;8BACQ;8BAC0B;oCACoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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LiG,MAAM;QACNtD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/mcp/tools/message-search.ts"],"sourcesContent":["import { EMAIL_COMMON_PATTERNS, EMAIL_FIELD_DESCRIPTIONS, EMAIL_FIELDS, EmailContentTypeSchema, type EmailDetail, EmailDetailSchema, 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, createFieldsSchema, createPaginationSchema, createShapeSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, type ToolModule, toColumnarFormat } from '@mcp-z/server';\nimport { Client } from '@microsoft/microsoft-graph-client';\nimport type * as MicrosoftGraph from '@microsoft/microsoft-graph-types';\nimport { z } from 'zod';\nimport { needsBody } from '../../email/querying/client-filter.ts';\nimport { executeQuery as executeOutlookQuery } from '../../email/querying/execute-query.ts';\nimport { InvalidQueryError, OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.ts';\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 fields: createFieldsSchema({\n availableFields: EMAIL_FIELDS,\n fieldDescriptions: EMAIL_FIELD_DESCRIPTIONS,\n commonPatterns: EMAIL_COMMON_PATTERNS,\n resourceName: 'email message',\n }),\n ...createPaginationSchema({\n defaultPageSize: 50,\n maxPageSize: 500,\n provider: 'outlook',\n }).shape,\n shape: createShapeSchema(),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(EmailDetailSchema).describe('Matching email messages'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search Outlook messages using structured query objects with flexible field selection.',\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\nasync function handler({ query, pageSize = 50, pageToken, fields, shape = 'arrays', contentType, excludeThreadHistory }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseOutlookQueryParameter(query);\n const requestedFields = parseFields(fields, EMAIL_FIELDS);\n const needsBodyContent = needsBody(parsedQuery);\n const includeBody = requestedFields === 'all' || requestedFields.has('body') || needsBodyContent;\n\n logger.info('outlook.search called with', {\n query: parsedQuery,\n pageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields: fields || 'all',\n includeBody,\n });\n\n const graph = Client.initWithMiddleware({\n authProvider: extra.authContext.auth,\n });\n const started = Date.now();\n const exec = await executeOutlookQuery(\n graph,\n parsedQuery,\n {\n logger,\n pageSize,\n ...(pageToken ? { pageToken } : {}),\n includeBody,\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)\n .filter(Boolean)\n .join(', ')\n : undefined;\n const cc = Array.isArray(message?.ccRecipients)\n ? message.ccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address)\n .filter(Boolean)\n .join(', ')\n : undefined;\n const bcc = Array.isArray(message?.bccRecipients)\n ? message.bccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address)\n .filter(Boolean)\n .join(', ')\n : undefined;\n const fromAddr = message?.from?.emailAddress?.address ?? null;\n const fromName = message?.from?.emailAddress?.name ?? null;\n // Process body based on contentType and excludeThreadHistory options\n let bodyContent: string | undefined;\n if (includeBody && message?.body?.content) {\n const isHtml = message.body.contentType?.toLowerCase() === 'html';\n bodyContent = message.body.content;\n\n if (isHtml && excludeThreadHistory) {\n bodyContent = extractCurrentMessageFromHtml(bodyContent);\n }\n\n if (isHtml && contentType === 'text') {\n bodyContent = excludeThreadHistory ? extractCurrentMessageFromHtmlToText(bodyContent) : extractCurrentMessageFromHtmlToText(message.body.content);\n }\n }\n\n const mapped: Partial<EmailDetail> = {\n id: message?.id ?? undefined,\n subject: message?.subject ?? undefined,\n from: fromAddr ?? undefined,\n fromName: fromName ?? undefined,\n to,\n cc,\n bcc,\n date: message?.receivedDateTime ?? undefined,\n snippet: message?.bodyPreview ?? undefined,\n ...(bodyContent && { body: bodyContent, bodyContentType: contentType }),\n };\n return mapped;\n }\n );\n const durationMs = Date.now() - started;\n\n const filteredItems = exec.items.map((item) => filterFields(item, requestedFields));\n logger.info('outlook.message.search returning', {\n query,\n pageSize,\n itemsLength: filteredItems.length,\n fields: fields || 'all',\n });\n logger.info('outlook.message.search metrics', {\n durationMs,\n metadata: exec.metadata,\n });\n\n // Type-safe metadata access\n const metadataObj = exec.metadata as { nextPageToken?: string } | undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, EMAIL_FIELDS),\n ...(metadataObj?.nextPageToken && { nextPageToken: metadataObj.nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n ...(metadataObj?.nextPageToken && { nextPageToken: metadataObj.nextPageToken }),\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 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.message.search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching messages: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","OutlookQueryParameterSchema","optional","describe","fields","createFieldsSchema","availableFields","EMAIL_FIELDS","fieldDescriptions","EMAIL_FIELD_DESCRIPTIONS","commonPatterns","EMAIL_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","maxPageSize","provider","shape","createShapeSchema","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successObjectsBranchSchema","type","literal","items","array","EmailDetailSchema","nextPageToken","string","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","description","result","handler","extra","pageSize","pageToken","logger","parsedQuery","requestedFields","needsBodyContent","includeBody","graph","started","exec","durationMs","filteredItems","metadataObj","error","message","parseOutlookQueryParameter","parseFields","needsBody","has","info","undefined","Client","initWithMiddleware","authProvider","authContext","auth","Date","now","executeOutlookQuery","limit","m","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","fromName","name","bodyContent","body","content","isHtml","toLowerCase","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","mapped","id","subject","date","receivedDateTime","snippet","bodyPreview","bodyContentType","item","filterFields","itemsLength","length","metadata","toColumnarFormat","text","JSON","stringify","structuredContent","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AQlE,MAAMC,OAAO,GAAGkE,OAAOnE;oBAChEX,OAAOW,KAAK,CAAC,gCAAgC;wBAAEA,OAAOC;oBAAQ;oBAE9D,MAAM,IAAI6D,qBAAa,CAACE,yBAAiB,CAACI,aAAa,EAAE,AAAC,6BAAoC,OAARnE,UAAW;wBAC/FoE,OAAOrE,AAAK,YAALA,OAAiBkE,SAAQlE,MAAMqE,KAAK,GAAG9D;oBAChD;;;;;;;IAEJ;;AAEe,SAASpE;IACtB,OAAO;QACLiG,MAAM;QACNtD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -509,6 +509,7 @@ var config = {
|
|
|
509
509
|
];
|
|
510
510
|
case 11:
|
|
511
511
|
if (_instanceof(error, _server.ProtocolError)) throw error;
|
|
512
|
+
if (_instanceof(error, _outlookqueryschemats.InvalidQueryError)) throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, error.message);
|
|
512
513
|
message = _instanceof(error, Error) ? error.message : String(error);
|
|
513
514
|
logger.error('outlook.messages.export-csv error', {
|
|
514
515
|
error: message
|
|
@@ -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 { 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\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","Error","ProtocolErrorCode","InternalError","stack","name"],"mappings":"AAAA,oGAAoG;;;;+BAiRpG;;;eAAwBA;;;qBA/Q+G;8BAE/G;sBAIwF;oCACzF;oBAEG;kBACQ;wBACX;mBACL;8BACkC;oCACoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAVxE,IAAM,AAAEC,2BAA6BC,uBAAO,CAApCD;AAaR,IAAME,oBAAoB;AAC1B,IAAMC,oBAAoB;AAC1B,IAAMC,mBAAmB;AAEzB,IAAMC,qBAAqBC,MAAC,CAACC,MAAM,CAAC;IAClCC,KAAKF,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IACzBC,UAAUL,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IAC9BE,UAAUN,MAAC,CAACO,MAAM,GAAGH,QAAQ,CAAC;I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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;;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,gBAAM,EAAChG;;;oBAAb;oBACAP,OAAOwG,KAAK,CAAC,2CAA2C;wBAAE7E,MAAMpB;oBAAS;;;;;;oBAClEgB;oBACPvB,OAAOwG,KAAK,CAAC,+CAA+C;wBAAE7E,MAAMpB;oBAAS;;;;;;oBAG/E,IAAIe,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,5 +1,12 @@
|
|
|
1
1
|
import { type BaseEmailQueryFields, type FieldOperator } from '@mcp-z/email';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
+
/**
|
|
4
|
+
* The caller's query is invalid (unparseable JSON, a shape the schema rejects, or an unknown category).
|
|
5
|
+
* Tools report it as an invalid-parameters error rather than an internal error.
|
|
6
|
+
*/
|
|
7
|
+
export declare class InvalidQueryError extends Error {
|
|
8
|
+
constructor(message: string);
|
|
9
|
+
}
|
|
3
10
|
/**
|
|
4
11
|
* Outlook system category values.
|
|
5
12
|
* These are the built-in category types that Outlook recognizes.
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { type BaseEmailQueryFields, type FieldOperator } from '@mcp-z/email';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
+
/**
|
|
4
|
+
* The caller's query is invalid (unparseable JSON, a shape the schema rejects, or an unknown category).
|
|
5
|
+
* Tools report it as an invalid-parameters error rather than an internal error.
|
|
6
|
+
*/
|
|
7
|
+
export declare class InvalidQueryError extends Error {
|
|
8
|
+
constructor(message: string);
|
|
9
|
+
}
|
|
3
10
|
/**
|
|
4
11
|
* Outlook system category values.
|
|
5
12
|
* These are the built-in category types that Outlook recognizes.
|
|
@@ -9,6 +9,9 @@ function _export(target, all) {
|
|
|
9
9
|
});
|
|
10
10
|
}
|
|
11
11
|
_export(exports, {
|
|
12
|
+
get InvalidQueryError () {
|
|
13
|
+
return InvalidQueryError;
|
|
14
|
+
},
|
|
12
15
|
get OutlookQueryParameterSchema () {
|
|
13
16
|
return OutlookQueryParameterSchema;
|
|
14
17
|
},
|
|
@@ -24,6 +27,33 @@ _export(exports, {
|
|
|
24
27
|
});
|
|
25
28
|
var _email = require("@mcp-z/email");
|
|
26
29
|
var _zod = require("zod");
|
|
30
|
+
function _assert_this_initialized(self) {
|
|
31
|
+
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
|
|
32
|
+
return self;
|
|
33
|
+
}
|
|
34
|
+
function _call_super(_this, derived, args) {
|
|
35
|
+
derived = _get_prototype_of(derived);
|
|
36
|
+
return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
|
|
37
|
+
}
|
|
38
|
+
function _class_call_check(instance, Constructor) {
|
|
39
|
+
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
|
|
40
|
+
}
|
|
41
|
+
function _construct(Parent, args, Class) {
|
|
42
|
+
if (_is_native_reflect_construct()) _construct = Reflect.construct;
|
|
43
|
+
else {
|
|
44
|
+
_construct = function construct(Parent, args, Class) {
|
|
45
|
+
var a = [
|
|
46
|
+
null
|
|
47
|
+
];
|
|
48
|
+
a.push.apply(a, args);
|
|
49
|
+
var Constructor = Function.bind.apply(Parent, a);
|
|
50
|
+
var instance = new Constructor();
|
|
51
|
+
if (Class) _set_prototype_of(instance, Class.prototype);
|
|
52
|
+
return instance;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
return _construct.apply(null, arguments);
|
|
56
|
+
}
|
|
27
57
|
function _define_property(obj, key, value) {
|
|
28
58
|
if (key in obj) {
|
|
29
59
|
Object.defineProperty(obj, key, {
|
|
@@ -35,12 +65,42 @@ function _define_property(obj, key, value) {
|
|
|
35
65
|
} else obj[key] = value;
|
|
36
66
|
return obj;
|
|
37
67
|
}
|
|
68
|
+
function _get_prototype_of(o) {
|
|
69
|
+
_get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
|
|
70
|
+
return o.__proto__ || Object.getPrototypeOf(o);
|
|
71
|
+
};
|
|
72
|
+
return _get_prototype_of(o);
|
|
73
|
+
}
|
|
74
|
+
function _inherits(subClass, superClass) {
|
|
75
|
+
if (typeof superClass !== "function" && superClass !== null) {
|
|
76
|
+
throw new TypeError("Super expression must either be null or a function");
|
|
77
|
+
}
|
|
78
|
+
subClass.prototype = Object.create(superClass && superClass.prototype, {
|
|
79
|
+
constructor: {
|
|
80
|
+
value: subClass,
|
|
81
|
+
writable: true,
|
|
82
|
+
configurable: true
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
if (superClass) _set_prototype_of(subClass, superClass);
|
|
86
|
+
}
|
|
38
87
|
function _instanceof(left, right) {
|
|
39
88
|
"@swc/helpers - instanceof";
|
|
40
89
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
41
90
|
return !!right[Symbol.hasInstance](left);
|
|
42
91
|
} else return left instanceof right;
|
|
43
92
|
}
|
|
93
|
+
function _is_native_function(fn) {
|
|
94
|
+
return Function.toString.call(fn).indexOf("[native code]") !== -1;
|
|
95
|
+
}
|
|
96
|
+
function _is_native_reflect_construct() {
|
|
97
|
+
try {
|
|
98
|
+
var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
|
|
99
|
+
} catch (_) {}
|
|
100
|
+
return (_is_native_reflect_construct = function() {
|
|
101
|
+
return !!result;
|
|
102
|
+
})();
|
|
103
|
+
}
|
|
44
104
|
function _object_spread(target) {
|
|
45
105
|
for(var i = 1; i < arguments.length; i++){
|
|
46
106
|
var source = arguments[i] != null ? arguments[i] : {};
|
|
@@ -79,6 +139,59 @@ function _object_spread_props(target, source) {
|
|
|
79
139
|
}
|
|
80
140
|
return target;
|
|
81
141
|
}
|
|
142
|
+
function _possible_constructor_return(self, call) {
|
|
143
|
+
if (call && (_type_of(call) === "object" || typeof call === "function")) return call;
|
|
144
|
+
return _assert_this_initialized(self);
|
|
145
|
+
}
|
|
146
|
+
function _set_prototype_of(o, p) {
|
|
147
|
+
_set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
|
|
148
|
+
o.__proto__ = p;
|
|
149
|
+
return o;
|
|
150
|
+
};
|
|
151
|
+
return _set_prototype_of(o, p);
|
|
152
|
+
}
|
|
153
|
+
function _type_of(obj) {
|
|
154
|
+
"@swc/helpers - typeof";
|
|
155
|
+
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
|
|
156
|
+
}
|
|
157
|
+
function _wrap_native_super(Class) {
|
|
158
|
+
var _cache = typeof Map === "function" ? new Map() : undefined;
|
|
159
|
+
_wrap_native_super = function(Class) {
|
|
160
|
+
if (Class === null || !_is_native_function(Class)) return Class;
|
|
161
|
+
if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
|
|
162
|
+
if (typeof _cache !== "undefined") {
|
|
163
|
+
if (_cache.has(Class)) return _cache.get(Class);
|
|
164
|
+
_cache.set(Class, Wrapper);
|
|
165
|
+
}
|
|
166
|
+
function Wrapper() {
|
|
167
|
+
return _construct(Class, arguments, _get_prototype_of(this).constructor);
|
|
168
|
+
}
|
|
169
|
+
Wrapper.prototype = Object.create(Class.prototype, {
|
|
170
|
+
constructor: {
|
|
171
|
+
value: Wrapper,
|
|
172
|
+
enumerable: false,
|
|
173
|
+
writable: true,
|
|
174
|
+
configurable: true
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
return _set_prototype_of(Wrapper, Class);
|
|
178
|
+
};
|
|
179
|
+
return _wrap_native_super(Class);
|
|
180
|
+
}
|
|
181
|
+
var InvalidQueryError = /*#__PURE__*/ function(Error1) {
|
|
182
|
+
"use strict";
|
|
183
|
+
_inherits(InvalidQueryError, Error1);
|
|
184
|
+
function InvalidQueryError(message) {
|
|
185
|
+
_class_call_check(this, InvalidQueryError);
|
|
186
|
+
var _this;
|
|
187
|
+
_this = _call_super(this, InvalidQueryError, [
|
|
188
|
+
message
|
|
189
|
+
]);
|
|
190
|
+
_this.name = 'InvalidQueryError';
|
|
191
|
+
return _this;
|
|
192
|
+
}
|
|
193
|
+
return InvalidQueryError;
|
|
194
|
+
}(_wrap_native_super(Error));
|
|
82
195
|
var OutlookSystemCategorySchema = _zod.z.enum([
|
|
83
196
|
'work',
|
|
84
197
|
'personal',
|
|
@@ -144,7 +257,7 @@ function parseOutlookQueryParameter(input) {
|
|
|
144
257
|
}
|
|
145
258
|
var validated = OutlookQuerySchema.safeParse(input);
|
|
146
259
|
if (!validated.success) {
|
|
147
|
-
throw new
|
|
260
|
+
throw new InvalidQueryError("Invalid query JSON: ".concat(validated.error.message, '. Use {"kqlQuery":"<query>"} for KQL syntax.'));
|
|
148
261
|
}
|
|
149
262
|
return validated.data;
|
|
150
263
|
}
|
|
@@ -152,7 +265,7 @@ function parseOutlookQueryString(value) {
|
|
|
152
265
|
var raw = safeJsonParse(value, 'kqlQuery');
|
|
153
266
|
var validated = OutlookQuerySchema.safeParse(raw);
|
|
154
267
|
if (!validated.success) {
|
|
155
|
-
throw new
|
|
268
|
+
throw new InvalidQueryError("Invalid query JSON: ".concat(validated.error.message, '. Use {"kqlQuery":"<query>"} for KQL syntax.'));
|
|
156
269
|
}
|
|
157
270
|
return validated.data;
|
|
158
271
|
}
|
|
@@ -161,7 +274,7 @@ function safeJsonParse(value, rawField) {
|
|
|
161
274
|
return JSON.parse(value);
|
|
162
275
|
} catch (error) {
|
|
163
276
|
var message = _instanceof(error, Error) ? error.message : 'Invalid JSON';
|
|
164
|
-
throw new
|
|
277
|
+
throw new InvalidQueryError("Query must be valid JSON. ".concat(message, '. Wrap KQL syntax in {"').concat(rawField, '":"<query>"} if needed.'));
|
|
165
278
|
}
|
|
166
279
|
}
|
|
167
280
|
/* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/schemas/outlook-query-schema.ts"],"sourcesContent":["import { type BaseEmailQueryFields, baseEmailQueryFields, type FieldOperator, FieldOperatorSchema } from '@mcp-z/email';\nimport { z } from 'zod';\n\n/**\n * Outlook system category values.\n * These are the built-in category types that Outlook recognizes.\n * Note: This is distinct from OutlookCategory (user-created category objects with id/displayName/color).\n */\nexport type OutlookSystemCategory = 'work' | 'personal' | 'family' | 'travel' | 'important' | 'urgent';\n\n/** Zod schema for validating OutlookSystemCategory values */\nexport const OutlookSystemCategorySchema = z.enum(['work', 'personal', 'family', 'travel', 'important', 'urgent']);\n\n/**\n * Outlook-specific query schema with recursive operators and Outlook features.\n *\n * Includes Microsoft Graph/Outlook-specific features:\n * - exactPhrase: Strict exact phrase matching via KQL $search parameter\n * - categories: Outlook system categories (work, personal, family, travel, important, urgent)\n * - label: User-created Outlook categories (case-sensitive, discovered via outlook-categories-list)\n * - importance: Message importance level (high, normal, low)\n * - kqlQuery: Escape hatch for advanced KQL (Keyword Query Language) syntax\n *\n * Plus all base fields from baseEmailQueryFields:\n * - Email addresses: from, to, cc, bcc (support string or field operators)\n * - Content: subject, body, text\n * - Flags: hasAttachment, isRead\n * - Date range: date { $gte, $lt }\n * - Logical operators: $and, $or, $not (recursive)\n *\n * Note: Cast through unknown to work around Zod's lazy schema type inference issue\n * with exactOptionalPropertyTypes. The runtime schema is correct; this cast ensures\n * TypeScript sees the strict OutlookQuery type everywhere the schema is used.\n */\nexport const OutlookQuerySchema = z.lazy(() =>\n z\n .object({\n // Logical operators for combining conditions (recursive)\n $and: z.array(OutlookQuerySchema).optional().describe('Array of conditions that must ALL match'),\n $or: z.array(OutlookQuerySchema).optional().describe('Array of conditions where ANY must match'),\n $not: OutlookQuerySchema.optional().describe('Nested condition that must NOT match'),\n\n // Spread base email query fields (from, to, subject, body, etc.)\n ...baseEmailQueryFields,\n\n // Outlook-specific features\n\n // Exact phrase matching - KQL strict search with double quotes\n exactPhrase: z.string().min(1).optional().describe('Exact phrase matching - words must appear together in exact order (strict matching). Outlook uses KQL.'),\n\n // Outlook system categories with field operator support\n categories: z\n .union([\n OutlookSystemCategorySchema,\n z\n .object({\n $any: z.array(OutlookSystemCategorySchema).optional(),\n $all: z.array(OutlookSystemCategorySchema).optional(),\n $none: z.array(OutlookSystemCategorySchema).optional(),\n })\n .strict(),\n ])\n .optional()\n .describe('Filter by Outlook system categories (work, personal, family, travel, important, urgent)'),\n\n // User-created categories\n label: z\n .union([z.string().min(1), FieldOperatorSchema])\n .optional()\n .describe('Filter by user-created categories (case-sensitive). Use outlook-categories-list to see available categories'),\n\n // Message importance level - Outlook-specific property\n importance: z.enum(['high', 'normal', 'low']).optional().describe('Filter by message importance level (high, normal, low)'),\n\n // Raw KQL query string - escape hatch for advanced syntax\n kqlQuery: z.string().min(1).optional().describe('Raw KQL (Keyword Query Language) syntax for advanced use cases. Bypasses schema validation - use sparingly.'),\n })\n .strict()\n) as unknown as z.ZodType<OutlookQuery>;\n\nconst OutlookQueryStringSchema = z\n .string()\n .min(1)\n .transform((value, ctx) => {\n try {\n return parseOutlookQueryString(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Invalid query input';\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message,\n });\n return z.NEVER;\n }\n });\n\nexport const OutlookQueryParameterSchema = z.union([OutlookQuerySchema, OutlookQueryStringSchema]) as z.ZodType<OutlookQuery | string>;\nexport type OutlookQueryParameter = z.infer<typeof OutlookQueryParameterSchema>;\n\nexport function parseOutlookQueryParameter(input: OutlookQuery | string | undefined): OutlookQuery | undefined {\n if (input === undefined) return undefined;\n if (typeof input === 'string') {\n return parseOutlookQueryString(input);\n }\n const validated = OutlookQuerySchema.safeParse(input);\n if (!validated.success) {\n throw new
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/schemas/outlook-query-schema.ts"],"sourcesContent":["import { type BaseEmailQueryFields, baseEmailQueryFields, type FieldOperator, FieldOperatorSchema } from '@mcp-z/email';\nimport { z } from 'zod';\n\n/**\n * The caller's query is invalid (unparseable JSON, a shape the schema rejects, or an unknown category).\n * Tools report it as an invalid-parameters error rather than an internal error.\n */\nexport class InvalidQueryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'InvalidQueryError';\n }\n}\n\n/**\n * Outlook system category values.\n * These are the built-in category types that Outlook recognizes.\n * Note: This is distinct from OutlookCategory (user-created category objects with id/displayName/color).\n */\nexport type OutlookSystemCategory = 'work' | 'personal' | 'family' | 'travel' | 'important' | 'urgent';\n\n/** Zod schema for validating OutlookSystemCategory values */\nexport const OutlookSystemCategorySchema = z.enum(['work', 'personal', 'family', 'travel', 'important', 'urgent']);\n\n/**\n * Outlook-specific query schema with recursive operators and Outlook features.\n *\n * Includes Microsoft Graph/Outlook-specific features:\n * - exactPhrase: Strict exact phrase matching via KQL $search parameter\n * - categories: Outlook system categories (work, personal, family, travel, important, urgent)\n * - label: User-created Outlook categories (case-sensitive, discovered via outlook-categories-list)\n * - importance: Message importance level (high, normal, low)\n * - kqlQuery: Escape hatch for advanced KQL (Keyword Query Language) syntax\n *\n * Plus all base fields from baseEmailQueryFields:\n * - Email addresses: from, to, cc, bcc (support string or field operators)\n * - Content: subject, body, text\n * - Flags: hasAttachment, isRead\n * - Date range: date { $gte, $lt }\n * - Logical operators: $and, $or, $not (recursive)\n *\n * Note: Cast through unknown to work around Zod's lazy schema type inference issue\n * with exactOptionalPropertyTypes. The runtime schema is correct; this cast ensures\n * TypeScript sees the strict OutlookQuery type everywhere the schema is used.\n */\nexport const OutlookQuerySchema = z.lazy(() =>\n z\n .object({\n // Logical operators for combining conditions (recursive)\n $and: z.array(OutlookQuerySchema).optional().describe('Array of conditions that must ALL match'),\n $or: z.array(OutlookQuerySchema).optional().describe('Array of conditions where ANY must match'),\n $not: OutlookQuerySchema.optional().describe('Nested condition that must NOT match'),\n\n // Spread base email query fields (from, to, subject, body, etc.)\n ...baseEmailQueryFields,\n\n // Outlook-specific features\n\n // Exact phrase matching - KQL strict search with double quotes\n exactPhrase: z.string().min(1).optional().describe('Exact phrase matching - words must appear together in exact order (strict matching). Outlook uses KQL.'),\n\n // Outlook system categories with field operator support\n categories: z\n .union([\n OutlookSystemCategorySchema,\n z\n .object({\n $any: z.array(OutlookSystemCategorySchema).optional(),\n $all: z.array(OutlookSystemCategorySchema).optional(),\n $none: z.array(OutlookSystemCategorySchema).optional(),\n })\n .strict(),\n ])\n .optional()\n .describe('Filter by Outlook system categories (work, personal, family, travel, important, urgent)'),\n\n // User-created categories\n label: z\n .union([z.string().min(1), FieldOperatorSchema])\n .optional()\n .describe('Filter by user-created categories (case-sensitive). Use outlook-categories-list to see available categories'),\n\n // Message importance level - Outlook-specific property\n importance: z.enum(['high', 'normal', 'low']).optional().describe('Filter by message importance level (high, normal, low)'),\n\n // Raw KQL query string - escape hatch for advanced syntax\n kqlQuery: z.string().min(1).optional().describe('Raw KQL (Keyword Query Language) syntax for advanced use cases. Bypasses schema validation - use sparingly.'),\n })\n .strict()\n) as unknown as z.ZodType<OutlookQuery>;\n\nconst OutlookQueryStringSchema = z\n .string()\n .min(1)\n .transform((value, ctx) => {\n try {\n return parseOutlookQueryString(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Invalid query input';\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message,\n });\n return z.NEVER;\n }\n });\n\nexport const OutlookQueryParameterSchema = z.union([OutlookQuerySchema, OutlookQueryStringSchema]) as z.ZodType<OutlookQuery | string>;\nexport type OutlookQueryParameter = z.infer<typeof OutlookQueryParameterSchema>;\n\nexport function parseOutlookQueryParameter(input: OutlookQuery | string | undefined): OutlookQuery | undefined {\n if (input === undefined) return undefined;\n if (typeof input === 'string') {\n return parseOutlookQueryString(input);\n }\n const validated = OutlookQuerySchema.safeParse(input);\n if (!validated.success) {\n throw new InvalidQueryError(`Invalid query JSON: ${validated.error.message}. Use {\"kqlQuery\":\"<query>\"} for KQL syntax.`);\n }\n return validated.data;\n}\n\nfunction parseOutlookQueryString(value: string): OutlookQuery {\n const raw = safeJsonParse(value, 'kqlQuery');\n const validated = OutlookQuerySchema.safeParse(raw);\n if (!validated.success) {\n throw new InvalidQueryError(`Invalid query JSON: ${validated.error.message}. Use {\"kqlQuery\":\"<query>\"} for KQL syntax.`);\n }\n return validated.data;\n}\n\nfunction safeJsonParse(value: string, rawField: 'kqlQuery'): unknown {\n try {\n return JSON.parse(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Invalid JSON';\n throw new InvalidQueryError(`Query must be valid JSON. ${message}. Wrap KQL syntax in {\"${rawField}\":\"<query>\"} if needed.`);\n }\n}\n\nexport type OutlookQuery = BaseEmailQueryFields & {\n $and?: OutlookQuery[];\n $or?: OutlookQuery[];\n $not?: OutlookQuery;\n exactPhrase?: string;\n categories?:\n | OutlookSystemCategory\n | {\n $any?: OutlookSystemCategory[];\n $all?: OutlookSystemCategory[];\n $none?: OutlookSystemCategory[];\n };\n label?: string | FieldOperator;\n importance?: 'high' | 'normal' | 'low';\n kqlQuery?: string;\n};\n"],"names":["InvalidQueryError","OutlookQueryParameterSchema","OutlookQuerySchema","OutlookSystemCategorySchema","parseOutlookQueryParameter","message","name","Error","z","enum","lazy","object","$and","array","optional","describe","$or","$not","baseEmailQueryFields","exactPhrase","string","min","categories","union","$any","$all","$none","strict","label","FieldOperatorSchema","importance","kqlQuery","OutlookQueryStringSchema","transform","value","ctx","parseOutlookQueryString","error","addIssue","code","ZodIssueCode","custom","NEVER","input","undefined","validated","safeParse","success","data","raw","safeJsonParse","rawField","JSON","parse"],"mappings":";;;;;;;;;;;QAOaA;eAAAA;;QAoGAC;eAAAA;;QA9DAC;eAAAA;;QAvBAC;eAAAA;;QAwFGC;eAAAA;;;qBA9GyF;mBACvF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMX,IAAA,AAAMJ,kCAAN;;cAAMA;aAAAA,kBACCK,OAAe;gCADhBL;;gBAET,kBAFSA;YAEHK;;QACN,MAAKC,IAAI,GAAG;;;WAHHN;qBAA0BO;AAehC,IAAMJ,8BAA8BK,MAAC,CAACC,IAAI,CAAC;IAAC;IAAQ;IAAY;IAAU;IAAU;IAAa;CAAS;AAuB1G,IAAMP,qBAAqBM,MAAC,CAACE,IAAI,CAAC;WACvCF,MAAC,CACEG,MAAM,CAAC;QACN,yDAAyD;QACzDC,MAAMJ,MAAC,CAACK,KAAK,CAACX,oBAAoBY,QAAQ,GAAGC,QAAQ,CAAC;QACtDC,KAAKR,MAAC,CAACK,KAAK,CAACX,oBAAoBY,QAAQ,GAAGC,QAAQ,CAAC;QACrDE,MAAMf,mBAAmBY,QAAQ,GAAGC,QAAQ,CAAC;OAG1CG,2BAAoB;QAEvB,4BAA4B;QAE5B,+DAA+D;QAC/DC,aAAaX,MAAC,CAACY,MAAM,GAAGC,GAAG,CAAC,GAAGP,QAAQ,GAAGC,QAAQ,CAAC;QAEnD,wDAAwD;Q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;QAC7B,OAAOP,wBAAwBO;IACjC;IACA,IAAME,YAAY3C,mBAAmB4C,SAAS,CAACH;IAC/C,IAAI,CAACE,UAAUE,OAAO,EAAE;QACtB,MAAM,IAAI/C,kBAAkB,AAAC,uBAA8C,OAAxB6C,UAAUR,KAAK,CAAChC,OAAO,EAAC;IAC7E;IACA,OAAOwC,UAAUG,IAAI;AACvB;AAEA,SAASZ,wBAAwBF,KAAa;IAC5C,IAAMe,MAAMC,cAAchB,OAAO;IACjC,IAAMW,YAAY3C,mBAAmB4C,SAAS,CAACG;IAC/C,IAAI,CAACJ,UAAUE,OAAO,EAAE;QACtB,MAAM,IAAI/C,kBAAkB,AAAC,uBAA8C,OAAxB6C,UAAUR,KAAK,CAAChC,OAAO,EAAC;IAC7E;IACA,OAAOwC,UAAUG,IAAI;AACvB;AAEA,SAASE,cAAchB,KAAa,EAAEiB,QAAoB;IACxD,IAAI;QACF,OAAOC,KAAKC,KAAK,CAACnB;IACpB,EAAE,OAAOG,OAAO;QACd,IAAMhC,UAAUgC,AAAK,YAALA,OAAiB9B,SAAQ8B,MAAMhC,OAAO,GAAG;QACzD,MAAM,IAAIL,kBAAkB,AAAC,6BAA6DmD,OAAjC9C,SAAQ,2BAAkC,OAAT8C,UAAS;IACrG;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-
|
|
12
|
-
* - --dcr-verify-url=<url> External verification endpoint (required for external mode)
|
|
13
|
-
* - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)
|
|
11
|
+
* - --dcr-store-uri=<uri> DCR client storage URI (default: .mcp-z/dcr.json)
|
|
14
12
|
* - --port=<port> Enable HTTP transport on specified port
|
|
15
13
|
* - --stdio Enable stdio transport (default if no port)
|
|
16
14
|
* - --log-level=<level> Logging level (default: info)
|
|
17
|
-
* - --resource-store-uri=<uri> Resource store URI for CSV file storage (default:
|
|
15
|
+
* - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: .mcp-z/mcp-outlook/files beside the nearest .mcp.json, else ~/.mcp-z/mcp-outlook/files)
|
|
18
16
|
* - --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)
|
|
19
17
|
*
|
|
20
18
|
* Environment Variables:
|
|
@@ -23,8 +21,6 @@ import type { ServerConfig } from '../types.js';
|
|
|
23
21
|
* - MS_CLIENT_SECRET OAuth client secret (optional)
|
|
24
22
|
* - AUTH_MODE Default authentication mode (optional)
|
|
25
23
|
* - HEADLESS Disable browser auto-open (optional)
|
|
26
|
-
* - DCR_MODE DCR mode (optional, same format as --dcr-mode)
|
|
27
|
-
* - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)
|
|
28
24
|
* - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)
|
|
29
25
|
* - TOKEN_STORE_URI Token storage URI (optional)
|
|
30
26
|
* - PORT Default HTTP port (optional)
|
|
@@ -8,13 +8,11 @@ import type { ServerConfig } from '../types.js';
|
|
|
8
8
|
* - --headless Disable browser auto-open, return auth URL instead
|
|
9
9
|
* - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)
|
|
10
10
|
* - --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)
|
|
11
|
-
* - --dcr-
|
|
12
|
-
* - --dcr-verify-url=<url> External verification endpoint (required for external mode)
|
|
13
|
-
* - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)
|
|
11
|
+
* - --dcr-store-uri=<uri> DCR client storage URI (default: .mcp-z/dcr.json)
|
|
14
12
|
* - --port=<port> Enable HTTP transport on specified port
|
|
15
13
|
* - --stdio Enable stdio transport (default if no port)
|
|
16
14
|
* - --log-level=<level> Logging level (default: info)
|
|
17
|
-
* - --resource-store-uri=<uri> Resource store URI for CSV file storage (default:
|
|
15
|
+
* - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: .mcp-z/mcp-outlook/files beside the nearest .mcp.json, else ~/.mcp-z/mcp-outlook/files)
|
|
18
16
|
* - --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)
|
|
19
17
|
*
|
|
20
18
|
* Environment Variables:
|
|
@@ -23,8 +21,6 @@ import type { ServerConfig } from '../types.js';
|
|
|
23
21
|
* - MS_CLIENT_SECRET OAuth client secret (optional)
|
|
24
22
|
* - AUTH_MODE Default authentication mode (optional)
|
|
25
23
|
* - HEADLESS Disable browser auto-open (optional)
|
|
26
|
-
* - DCR_MODE DCR mode (optional, same format as --dcr-mode)
|
|
27
|
-
* - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)
|
|
28
24
|
* - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)
|
|
29
25
|
* - TOKEN_STORE_URI Token storage URI (optional)
|
|
30
26
|
* - PORT Default HTTP port (optional)
|
package/dist/cjs/setup/config.js
CHANGED
|
@@ -117,6 +117,7 @@ function parseConfig(args, env) {
|
|
|
117
117
|
var mcpServer = _require('@mcp-z/server');
|
|
118
118
|
var transportConfig = mcpServer.parseConfig(args, env);
|
|
119
119
|
var oauthConfig = oauthMicrosoft.parseConfig(args, env);
|
|
120
|
+
if (oauthConfig.auth === 'dcr') rejectExternalDcr(args, env);
|
|
120
121
|
// Parse DCR configuration if DCR mode is enabled
|
|
121
122
|
var dcrConfig = oauthConfig.auth === 'dcr' ? oauthMicrosoft.parseDcrConfig(args, env, _constantsts.MS_SCOPE) : undefined;
|
|
122
123
|
// Parse application-level config (LOG_LEVEL, RESOURCE_STORE_URI, BASE_URL)
|
|
@@ -191,6 +192,27 @@ function createConfig() {
|
|
|
191
192
|
throw new Error("".concat(error.message, "\n").concat(mcpServer.formatServerEnvSearch(envResult)));
|
|
192
193
|
}
|
|
193
194
|
}
|
|
195
|
+
// With --auth=dcr the server always runs its own sign-in endpoints; the external-mode settings never had an effect, so they are refused rather than ignored there. Other auth modes never read them.
|
|
196
|
+
function rejectExternalDcr(args, env) {
|
|
197
|
+
var values = (0, _util.parseArgs)({
|
|
198
|
+
args: args,
|
|
199
|
+
options: {
|
|
200
|
+
'dcr-mode': {
|
|
201
|
+
type: 'string'
|
|
202
|
+
},
|
|
203
|
+
'dcr-verify-url': {
|
|
204
|
+
type: 'string'
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
strict: false,
|
|
208
|
+
allowPositionals: true
|
|
209
|
+
}).values;
|
|
210
|
+
var mode = (typeof values['dcr-mode'] === 'string' ? values['dcr-mode'] : undefined) || env.DCR_MODE;
|
|
211
|
+
if (mode === 'external') throw new Error('external DCR mode is not supported: the server runs its own sign-in endpoints (use --dcr-mode=self-hosted or leave it unset)');
|
|
212
|
+
if (mode && mode !== 'self-hosted') throw new Error('Invalid DCR mode "'.concat(mode, '": only self-hosted is supported'));
|
|
213
|
+
var verifyUrl = typeof values['dcr-verify-url'] === 'string' ? values['dcr-verify-url'] : env.DCR_VERIFY_URL;
|
|
214
|
+
if (verifyUrl) throw new Error('--dcr-verify-url / DCR_VERIFY_URL is not supported: the server runs its own sign-in endpoints and verifies tokens itself');
|
|
215
|
+
}
|
|
194
216
|
function normalizeResourceStoreUri(resourceStoreUri) {
|
|
195
217
|
var filePrefix = 'file://';
|
|
196
218
|
if (resourceStoreUri.startsWith(filePrefix)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/config.ts"],"sourcesContent":["import { fileURLToPath, pathToFileURL } from 'node:url';\nimport type * as OAuthMicrosoft from '@mcp-z/oauth-microsoft';\nimport type * as McpServer from '@mcp-z/server';\nimport { Module } from 'module';\nimport { homedir } from 'os';\nimport * as path from 'path';\nimport { parseArgs } from 'util';\nimport { MS_SCOPE } from '../constants.ts';\nimport type { ServerConfig } from '../types.ts';\nimport { readPkg } from './version-help.ts';\n\nconst pkg = readPkg();\nconst SERVER_NAME = pkg.name.replace(/^@[^/]+\\//, '');\n\n// @mcp-z/oauth-microsoft and @mcp-z/server are requireable at the >=20 floor; deferred so\n// --version/--help (handled via version-help.ts, never this file) load neither package.\nconst _require = typeof require === 'undefined' ? Module.createRequire(import.meta.url) : require;\n\n/**\n * Parse Outlook server configuration from CLI arguments and environment.\n *\n * CLI Arguments (all optional):\n * - --auth=<mode> Authentication mode (default: loopback-oauth)\n * Modes: loopback-oauth, device-code, dcr\n * - --headless Disable browser auto-open, return auth URL instead\n * - --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n * - --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)\n * - --dcr-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)\n * - --dcr-verify-url=<url> External verification endpoint (required for external mode)\n * - --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)\n * - --port=<port> Enable HTTP transport on specified port\n * - --stdio Enable stdio transport (default if no port)\n * - --log-level=<level> Logging level (default: info)\n * - --resource-store-uri=<uri> Resource store URI for CSV file storage (default: file://~/.mcp-z/mcp-outlook/files)\n * - --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)\n *\n * Environment Variables:\n * - MS_CLIENT_ID OAuth client ID (REQUIRED)\n * - MS_TENANT_ID Microsoft tenant ID (REQUIRED)\n * - MS_CLIENT_SECRET OAuth client secret (optional)\n * - AUTH_MODE Default authentication mode (optional)\n * - HEADLESS Disable browser auto-open (optional)\n * - DCR_MODE DCR mode (optional, same format as --dcr-mode)\n * - DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)\n * - DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n * - TOKEN_STORE_URI Token storage URI (optional)\n * - PORT Default HTTP port (optional)\n * - LOG_LEVEL Default logging level (optional)\n * - RESOURCE_STORE_URI Resource store URI (optional, file://)\n * - BASE_URL Base URL for HTTP file serving (optional)\n *\n * OAuth Scopes (from constants.ts):\n * openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite\n */\nexport function parseConfig(args: string[], env: Record<string, string | undefined>): ServerConfig {\n const oauthMicrosoft = _require('@mcp-z/oauth-microsoft') as typeof OAuthMicrosoft;\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n\n const transportConfig = mcpServer.parseConfig(args, env);\n const oauthConfig = oauthMicrosoft.parseConfig(args, env);\n\n // Parse DCR configuration if DCR mode is enabled\n const dcrConfig = oauthConfig.auth === 'dcr' ? oauthMicrosoft.parseDcrConfig(args, env, MS_SCOPE) : undefined;\n\n // Parse application-level config (LOG_LEVEL, RESOURCE_STORE_URI, BASE_URL)\n const { values } = parseArgs({\n args,\n options: {\n 'log-level': { type: 'string' },\n 'base-url': { type: 'string' },\n 'resource-store-uri': { type: 'string' },\n },\n strict: false, // Allow other arguments\n allowPositionals: true,\n });\n\n const name = SERVER_NAME;\n // Parse repository URL from package.json, stripping git+ prefix and .git suffix\n const rawRepoUrl = typeof pkg.repository === 'object' ? pkg.repository.url : pkg.repository;\n const repositoryUrl = rawRepoUrl?.replace(/^git\\+/, '').replace(/\\.git$/, '') ?? `https://github.com/mcp-z/${name}`;\n const baseDir = resolveBaseDir();\n const cliLogLevel = typeof values['log-level'] === 'string' ? values['log-level'] : undefined;\n const envLogLevel = env.LOG_LEVEL;\n const logLevel = cliLogLevel ?? envLogLevel ?? 'info';\n\n // Parse file storage configuration\n const cliResourceStoreUri = typeof values['resource-store-uri'] === 'string' ? values['resource-store-uri'] : undefined;\n const envResourceStoreUri = env.RESOURCE_STORE_URI;\n const defaultResourceStorePath = path.join(baseDir, name, 'files');\n const resourceStoreUri = normalizeResourceStoreUri(cliResourceStoreUri ?? envResourceStoreUri ?? defaultResourceStorePath);\n\n const cliBaseUrl = typeof values['base-url'] === 'string' ? values['base-url'] : undefined;\n const envBaseUrl = env.BASE_URL;\n const baseUrl = cliBaseUrl ?? envBaseUrl;\n\n // Combine configs\n const result: ServerConfig = {\n ...oauthConfig, // Includes clientId, auth, headless, redirectUri\n transport: transportConfig.transport,\n logLevel,\n baseDir,\n name,\n version: pkg.version,\n repositoryUrl,\n resourceStoreUri,\n };\n if (baseUrl !== undefined) result.baseUrl = baseUrl;\n if (dcrConfig !== undefined) result.dcrConfig = dcrConfig;\n return result;\n}\n\n/** The server's data directory: `.mcp-z` beside the nearest .mcp.json (searched from cwd up to home), else in the home directory. */\nfunction resolveBaseDir(): string {\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n try {\n const configPath = mcpServer.findConfigPath({ config: '.mcp.json', cwd: process.cwd(), stopDir: homedir() });\n return path.join(path.dirname(configPath), '.mcp-z');\n } catch {\n return path.join(homedir(), '.mcp-z');\n }\n}\n\n/**\n * Build production configuration from process globals.\n * Entry point for production server.\n */\nexport function createConfig(): ServerConfig {\n const mcpServer = _require('@mcp-z/server') as typeof McpServer;\n const envResult = mcpServer.loadServerEnv({ name: SERVER_NAME, baseDir: resolveBaseDir() });\n try {\n return parseConfig(process.argv, process.env);\n } catch (error) {\n throw new Error(`${(error as Error).message}\\n${mcpServer.formatServerEnvSearch(envResult)}`);\n }\n}\n\nfunction normalizeResourceStoreUri(resourceStoreUri: string): string {\n const filePrefix = 'file://';\n if (resourceStoreUri.startsWith(filePrefix)) {\n const rawPath = resourceStoreUri.slice(filePrefix.length);\n const filePath = rawPath.startsWith('~') ? rawPath.replace(/^~/, homedir()) : rawPath.startsWith('/') ? fileURLToPath(resourceStoreUri) : rawPath;\n return pathToFileURL(path.resolve(filePath)).href;\n }\n\n if (resourceStoreUri.includes('://')) return resourceStoreUri;\n\n const expandedPath = resourceStoreUri.startsWith('~') ? resourceStoreUri.replace(/^~/, homedir()) : resourceStoreUri;\n return pathToFileURL(path.resolve(expandedPath)).href;\n}\n"],"names":["createConfig","parseConfig","pkg","readPkg","SERVER_NAME","name","replace","_require","require","Module","createRequire","args","env","cliLogLevel","cliResourceStoreUri","oauthMicrosoft","mcpServer","transportConfig","oauthConfig","dcrConfig","auth","parseDcrConfig","MS_SCOPE","undefined","values","parseArgs","options","type","strict","allowPositionals","rawRepoUrl","repository","url","repositoryUrl","baseDir","resolveBaseDir","envLogLevel","LOG_LEVEL","logLevel","envResourceStoreUri","RESOURCE_STORE_URI","defaultResourceStorePath","path","join","resourceStoreUri","normalizeResourceStoreUri","cliBaseUrl","envBaseUrl","BASE_URL","baseUrl","result","transport","version","configPath","findConfigPath","config","cwd","process","stopDir","homedir","dirname","envResult","loadServerEnv","argv","error","Error","message","formatServerEnvSearch","filePrefix","startsWith","rawPath","slice","length","filePath","fileURLToPath","pathToFileURL","resolve","href","includes","expandedPath"],"mappings":";;;;;;;;;;;QA8HgBA;eAAAA;;QAxEAC;eAAAA;;;uBAtD6B;sBAGtB;kBACC;4DACF;oBACI;2BACD;6BAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAExB,IAAMC,MAAMC,IAAAA,sBAAO;AACnB,IAAMC,cAAcF,IAAIG,IAAI,CAACC,OAAO,CAAC,aAAa;AAElD,0FAA0F;AAC1F,wFAAwF;AACxF,IAAMC,WAAW,OAAOC,YAAY,cAAcC,cAAM,CAACC,aAAa,CAAC,uDAAmBF;AAsCnF,SAASP,YAAYU,IAAc,EAAEC,GAAuC;cA6BhEC,OAMkCC;IAlCnD,IAAMC,iBAAiBR,SAAS;IAChC,IAAMS,YAAYT,SAAS;IAE3B,IAAMU,kBAAkBD,UAAUf,WAAW,CAACU,MAAMC;IACpD,IAAMM,cAAcH,eAAed,WAAW,CAACU,MAAMC;IAErD,iDAAiD;IACjD,IAAMO,YAAYD,YAAYE,IAAI,KAAK,QAAQL,eAAeM,cAAc,CAACV,MAAMC,KAAKU,qBAAQ,IAAIC;IAEpG,2EAA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B;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,IAAMC,iBAAiBR,SAAS;IAChC,IAAMS,YAAYT,SAAS;IAE3B,IAAMU,kBAAkBD,UAAUf,WAAW,CAACU,MAAMC;IACpD,IAAMM,cAAcH,eAAed,WAAW,CAACU,MAAMC;IAErD,IAAIM,YAAYC,IAAI,KAAK,OAAOC,kBAAkBT,MAAMC;IAExD,iDAAiD;IACjD,IAAMS,YAAYH,YAAYC,IAAI,KAAK,QAAQJ,eAAeO,cAAc,CAACX,MAAMC,KAAKW,qBAAQ,IAAIC;IAEpG,2EAA2E;IAC3E,IAAM,AAAEC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