@mcp-z/mcp-outlook 2.4.2 → 2.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/cjs/email/querying/next-link.d.cts +5 -0
  2. package/dist/cjs/email/querying/next-link.d.ts +5 -0
  3. package/dist/cjs/email/querying/next-link.js +30 -0
  4. package/dist/cjs/email/querying/next-link.js.map +1 -0
  5. package/dist/cjs/email/querying/pagination-token.d.cts +3 -4
  6. package/dist/cjs/email/querying/pagination-token.d.ts +3 -4
  7. package/dist/cjs/email/querying/pagination-token.js +71 -49
  8. package/dist/cjs/email/querying/pagination-token.js.map +1 -1
  9. package/dist/cjs/email/querying/paging-decisions.d.cts +14 -0
  10. package/dist/cjs/email/querying/paging-decisions.d.ts +14 -0
  11. package/dist/cjs/email/querying/paging-decisions.js +91 -0
  12. package/dist/cjs/email/querying/paging-decisions.js.map +1 -0
  13. package/dist/cjs/email/querying/search-execution.js +130 -88
  14. package/dist/cjs/email/querying/search-execution.js.map +1 -1
  15. package/dist/cjs/mcp/tools/message-search.d.cts +1 -1
  16. package/dist/cjs/mcp/tools/message-search.d.ts +1 -1
  17. package/dist/cjs/mcp/tools/message-search.js +1 -1
  18. package/dist/cjs/mcp/tools/message-search.js.map +1 -1
  19. package/dist/cjs/mcp/tools/messages-export-csv.js +10 -6
  20. package/dist/cjs/mcp/tools/messages-export-csv.js.map +1 -1
  21. package/dist/esm/email/querying/next-link.d.ts +5 -0
  22. package/dist/esm/email/querying/next-link.js +22 -0
  23. package/dist/esm/email/querying/next-link.js.map +1 -0
  24. package/dist/esm/email/querying/pagination-token.d.ts +3 -4
  25. package/dist/esm/email/querying/pagination-token.js +22 -44
  26. package/dist/esm/email/querying/pagination-token.js.map +1 -1
  27. package/dist/esm/email/querying/paging-decisions.d.ts +14 -0
  28. package/dist/esm/email/querying/paging-decisions.js +21 -0
  29. package/dist/esm/email/querying/paging-decisions.js.map +1 -0
  30. package/dist/esm/email/querying/search-execution.js +82 -77
  31. package/dist/esm/email/querying/search-execution.js.map +1 -1
  32. package/dist/esm/mcp/tools/message-search.d.ts +1 -1
  33. package/dist/esm/mcp/tools/message-search.js +1 -1
  34. package/dist/esm/mcp/tools/message-search.js.map +1 -1
  35. package/dist/esm/mcp/tools/messages-export-csv.js +10 -6
  36. package/dist/esm/mcp/tools/messages-export-csv.js.map +1 -1
  37. package/package.json +1 -1
@@ -17,6 +17,7 @@ var _fs = require("fs");
17
17
  var _promises = require("fs/promises");
18
18
  var _zod = require("zod");
19
19
  var _executequeryts = require("../../email/querying/execute-query.js");
20
+ var _pagingdecisionsts = require("../../email/querying/paging-decisions.js");
20
21
  var _outlookqueryschemats = require("../../schemas/outlook-query-schema.js");
21
22
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
22
23
  try {
@@ -242,7 +243,7 @@ var config = {
242
243
  * - NO RETRIES (fail fast on error)
243
244
  */ function handler(_0, _1) {
244
245
  return _async_to_generator(function(param, extra) {
245
- var query, maxItems, filename, contentType, excludeThreadHistory, logger, storageContext, transport, resourceStoreUri, baseUrl, reservation, storedName, fullPath, parsedQuery, graph, csvHeaders, writeStream, headerLine, totalRows, nextPageToken, started, _exec_metadata, remainingItems, pageSize, exec, csvRows, rowsContent, durationMs, truncated, uri, result, error, _cleanupError, message;
246
+ var query, maxItems, filename, contentType, excludeThreadHistory, logger, storageContext, transport, resourceStoreUri, baseUrl, reservation, storedName, fullPath, parsedQuery, graph, csvHeaders, writeStream, headerLine, totalRows, nextPageToken, truncated, started, _exec_metadata, _exec_metadata1, remainingItems, pageSize, exec, cut, csvRows, rowsContent, durationMs, uri, result, error, _cleanupError, message;
246
247
  return _ts_generator(this, function(_state) {
247
248
  switch(_state.label){
248
249
  case 0:
@@ -312,6 +313,7 @@ var config = {
312
313
  // Internal pagination loop - append to CSV with each batch
313
314
  // NO RETRIES: If any error occurs, fail the whole operation and clean up
314
315
  totalRows = 0;
316
+ truncated = false;
315
317
  started = Date.now();
316
318
  _state.label = 3;
317
319
  case 3:
@@ -381,7 +383,10 @@ var config = {
381
383
  ];
382
384
  case 4:
383
385
  exec = _state.sent();
384
- csvRows = exec.items.map(function(item) {
386
+ // The next-page link fixes $top at the first page's size, so a batch can hold more than is still wanted
387
+ cut = (0, _pagingdecisionsts.cutToMaxItems)(exec.items, totalRows, maxItems, Boolean((_exec_metadata = exec.metadata) === null || _exec_metadata === void 0 ? void 0 : _exec_metadata.nextPageToken));
388
+ truncated = cut.truncated;
389
+ csvRows = cut.rows.map(function(item) {
385
390
  return [
386
391
  item.id,
387
392
  item.threadId,
@@ -407,10 +412,10 @@ var config = {
407
412
  });
408
413
  writeStream.write(rowsContent);
409
414
  }
410
- totalRows += exec.items.length;
411
- nextPageToken = (_exec_metadata = exec.metadata) === null || _exec_metadata === void 0 ? void 0 : _exec_metadata.nextPageToken;
415
+ totalRows += cut.rows.length;
416
+ nextPageToken = (_exec_metadata1 = exec.metadata) === null || _exec_metadata1 === void 0 ? void 0 : _exec_metadata1.nextPageToken;
412
417
  logger.info('outlook.messages.export-csv batch written', {
413
- batchSize: exec.items.length,
418
+ batchSize: cut.rows.length,
414
419
  totalRows: totalRows,
415
420
  hasMore: Boolean(nextPageToken)
416
421
  });
@@ -439,7 +444,6 @@ var config = {
439
444
  case 6:
440
445
  _state.sent();
441
446
  durationMs = Date.now() - started;
442
- truncated = totalRows >= maxItems && Boolean(nextPageToken);
443
447
  logger.info('outlook.messages.export-csv completed', {
444
448
  rowCount: totalRows,
445
449
  truncated: truncated,
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/mcp/tools/messages-export-csv.ts"],"sourcesContent":["/** Outlook message CSV export tool - streams results to file without loading all data into context */\n\nimport { EmailContentTypeSchema, ExcludeThreadHistorySchema, extractCurrentMessageFromHtml, extractCurrentMessageFromHtmlToText } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-microsoft';\nimport { schemas } from '@mcp-z/oauth-microsoft';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, getFileUri, ProtocolError, ProtocolErrorCode, reserveFile, type ToolModule } from '@mcp-z/server';\nimport { Client } from '@microsoft/microsoft-graph-client';\nimport type * as MicrosoftGraph from '@microsoft/microsoft-graph-types';\nimport { stringify } from 'csv-stringify/sync';\nimport { createWriteStream } from 'fs';\nimport { unlink } from 'fs/promises';\nimport { z } from 'zod';\nimport { executeQuery as executeOutlookQuery } from '../../email/querying/execute-query.ts';\nimport { InvalidQueryError, OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.ts';\nimport type { StorageExtra } from '../../types.ts';\n\nconst DEFAULT_PAGE_SIZE = 50;\nconst DEFAULT_MAX_ITEMS = 10000;\nconst MAX_EXPORT_ITEMS = 50000;\n\nconst ExportResultSchema = z.object({\n uri: z.string().describe('File URI (file:// or http://)'),\n filename: z.string().describe('Stored filename'),\n rowCount: z.number().describe('Number of messages exported'),\n truncated: z.boolean().describe('Whether export was truncated at maxItems'),\n});\n\nconst inputSchema = z.object({\n query: OutlookQueryParameterSchema.optional().describe('Structured query object or JSON string for filtering messages. Use query-syntax prompt for reference and kqlQuery for KQL syntax.'),\n maxItems: z.number().int().positive().max(MAX_EXPORT_ITEMS).default(DEFAULT_MAX_ITEMS).describe(`Maximum messages to export (default: ${DEFAULT_MAX_ITEMS}, max: ${MAX_EXPORT_ITEMS})`),\n filename: z.string().trim().min(1).default('outlook-messages.csv').describe('Output filename (default: outlook-messages.csv)'),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schema\nconst successBranchSchema = ExportResultSchema.extend({\n type: z.literal('success'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Export Outlook messages to CSV with streaming pagination. Returns file URI. Use query-syntax prompt for query reference.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n/**\n * Handler for outlook-messages-export-csv tool\n *\n * CRITICAL: Streaming implementation per user requirements\n * - Generate UUID upfront\n * - Write CSV header immediately\n * - Append rows as batches arrive\n * - Delete partial file on error\n * - NO RETRIES (fail fast on error)\n */\nasync function handler({ query, maxItems, filename, contentType, excludeThreadHistory }: Input, extra: EnrichedExtra & StorageExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n const { storageContext } = extra;\n const { transport, resourceStoreUri, baseUrl } = storageContext;\n\n // Reserve file location for streaming write (creates directory, generates ID, formats filename)\n const reservation = await reserveFile(filename, {\n resourceStoreUri,\n });\n const { storedName, fullPath } = reservation;\n\n logger.info('outlook.messages.export-csv starting streaming export', { path: fullPath, maxItems });\n\n try {\n const parsedQuery = parseOutlookQueryParameter(query);\n\n logger.info('outlook.messages.export-csv called', {\n query: parsedQuery,\n maxItems,\n filename,\n accountId: extra.authContext.accountId,\n });\n\n const graph = Client.initWithMiddleware({ authProvider: extra.authContext.auth });\n\n // Create CSV headers (all email fields)\n const csvHeaders = ['id', 'threadId', 'from', 'to', 'cc', 'bcc', 'subject', 'date', 'snippet', 'body', 'provider', 'labels'];\n\n // Create write stream and write headers immediately\n const writeStream = createWriteStream(fullPath, { encoding: 'utf-8' });\n const headerLine = stringify([csvHeaders], { header: false, quoted: true, quote: '\"', escape: '\"' });\n writeStream.write(headerLine);\n\n // Internal pagination loop - append to CSV with each batch\n // NO RETRIES: If any error occurs, fail the whole operation and clean up\n let totalRows = 0;\n let nextPageToken: string | undefined;\n const started = Date.now();\n\n while (totalRows < maxItems) {\n const remainingItems = maxItems - totalRows;\n const pageSize = Math.min(remainingItems, DEFAULT_PAGE_SIZE);\n\n const exec: {\n items: Array<{\n id: string;\n threadId?: string;\n from: string;\n to: string;\n cc: string;\n bcc: string;\n subject: string;\n date: string;\n snippet: string;\n body: string;\n provider: string;\n labels: string;\n }>;\n metadata?: { nextPageToken?: string };\n } = await executeOutlookQuery(\n graph,\n parsedQuery,\n {\n logger,\n pageSize,\n ...(nextPageToken !== undefined && { pageToken: nextPageToken }),\n includeBody: true, // Always include body for CSV export\n limit: pageSize,\n },\n (m: unknown) => {\n const message = m as MicrosoftGraph.Message;\n const to = Array.isArray(message?.toRecipients)\n ? message.toRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const cc = Array.isArray(message?.ccRecipients)\n ? message.ccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const bcc = Array.isArray(message?.bccRecipients)\n ? message.bccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const fromAddr = message?.from?.emailAddress?.address ?? (message?.from as { address?: string })?.address ?? '';\n const categories = Array.isArray(message?.categories) ? message.categories.join(';') : '';\n\n // Process body based on contentType and excludeThreadHistory options\n let body = message?.body?.content ?? '';\n const isHtml = message?.body?.contentType?.toLowerCase() === 'html';\n\n if (isHtml && excludeThreadHistory) {\n body = extractCurrentMessageFromHtml(body);\n }\n\n if (isHtml && contentType === 'text') {\n body = excludeThreadHistory ? extractCurrentMessageFromHtmlToText(body) : extractCurrentMessageFromHtmlToText(message?.body?.content ?? '');\n }\n\n return {\n id: String(message?.id ?? ''),\n threadId: message?.conversationId ? String(message.conversationId) : '',\n from: fromAddr,\n to,\n cc,\n bcc,\n subject: message?.subject ?? '',\n date: message?.receivedDateTime ?? '',\n snippet: message?.bodyPreview ?? '',\n body,\n provider: 'outlook' as const,\n labels: categories,\n };\n }\n );\n\n const csvRows = exec.items.map((item) => {\n return [item.id, item.threadId, item.from, item.to, item.cc, item.bcc, item.subject, item.date, item.snippet, item.body, item.provider, item.labels];\n });\n\n // Append rows to CSV file immediately\n if (csvRows.length > 0) {\n const rowsContent = stringify(csvRows, { header: false, quoted: true, quote: '\"', escape: '\"' });\n writeStream.write(rowsContent);\n }\n\n totalRows += exec.items.length;\n nextPageToken = exec.metadata?.nextPageToken;\n\n logger.info('outlook.messages.export-csv batch written', {\n batchSize: exec.items.length,\n totalRows,\n hasMore: Boolean(nextPageToken),\n });\n\n // Exit if no more results or reached maxItems\n if (!nextPageToken || exec.items.length === 0) {\n break;\n }\n }\n\n // Close write stream\n await new Promise<void>((resolve, reject) => {\n writeStream.end(() => resolve());\n writeStream.on('error', reject);\n });\n\n const durationMs = Date.now() - started;\n const truncated = totalRows >= maxItems && Boolean(nextPageToken);\n\n logger.info('outlook.messages.export-csv completed', {\n rowCount: totalRows,\n truncated,\n durationMs,\n filename: storedName,\n });\n\n // Generate URI based on transport type (stdio: file://, HTTP: http://)\n const uri = getFileUri(storedName, transport, {\n resourceStoreUri,\n ...(baseUrl && { baseUrl }),\n endpoint: '/files',\n });\n\n const result: Output = {\n type: 'success' as const,\n uri,\n filename: storedName,\n rowCount: totalRows,\n truncated,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n // CRITICAL: Clean up partial CSV file on error\n try {\n await unlink(fullPath);\n logger.debug('Cleaned up partial CSV file after error', { path: fullPath });\n } catch (_cleanupError) {\n logger.debug('Could not clean up CSV file (may not exist)', { path: fullPath });\n }\n\n if (error instanceof ProtocolError) throw error;\n if (error instanceof InvalidQueryError) throw new ProtocolError(ProtocolErrorCode.InvalidParams, error.message);\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('outlook.messages.export-csv error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error exporting messages to CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'messages-export-csv',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","DEFAULT_PAGE_SIZE","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","ExportResultSchema","z","object","uri","string","describe","filename","rowCount","number","truncated","boolean","inputSchema","query","OutlookQueryParameterSchema","optional","maxItems","int","positive","max","default","trim","min","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","storageContext","transport","resourceStoreUri","baseUrl","reservation","storedName","fullPath","parsedQuery","graph","csvHeaders","writeStream","headerLine","totalRows","nextPageToken","started","exec","remainingItems","pageSize","csvRows","rowsContent","durationMs","error","_cleanupError","message","reserveFile","info","path","parseOutlookQueryParameter","accountId","authContext","Client","initWithMiddleware","authProvider","auth","createWriteStream","encoding","stringify","header","quoted","quote","escape","write","Date","now","Math","executeOutlookQuery","undefined","pageToken","includeBody","limit","m","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","categories","body","content","isHtml","toLowerCase","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","id","String","threadId","conversationId","subject","date","receivedDateTime","snippet","bodyPreview","provider","labels","items","item","length","metadata","batchSize","hasMore","Promise","resolve","reject","end","on","getFileUri","endpoint","text","JSON","structuredContent","unlink","debug","ProtocolError","InvalidQueryError","ProtocolErrorCode","InvalidParams","Error","InternalError","stack","name"],"mappings":"AAAA,oGAAoG;;;;+BAkRpG;;;eAAwBA;;;qBAhR+G;8BAE/G;sBAIwF;oCACzF;oBAEG;kBACQ;wBACX;mBACL;8BACkC;oCACuC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAiBoF,uCAAiB,GAAE,MAAM,IAAID,qBAAa,CAACE,yBAAiB,CAACC,aAAa,EAAEtF,MAAME,OAAO;oBAExGA,UAAUF,AAAK,YAALA,OAAiBuF,SAAQvF,MAAME,OAAO,GAAGqD,OAAOvD;oBAChEtB,OAAOsB,KAAK,CAAC,qCAAqC;wBAAEA,OAAOE;oBAAQ;oBAEnE,MAAM,IAAIiF,qBAAa,CAACE,yBAAiB,CAACG,aAAa,EAAE,AAAC,oCAA2C,OAARtF,UAAW;wBACtGuF,OAAOzF,AAAK,YAALA,OAAiBuF,SAAQvF,MAAMyF,KAAK,GAAGhE;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1F;IACtB,OAAO;QACL2J,MAAM;QACNrH,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/mcp/tools/messages-export-csv.ts"],"sourcesContent":["/** Outlook message CSV export tool - streams results to file without loading all data into context */\n\nimport { EmailContentTypeSchema, ExcludeThreadHistorySchema, extractCurrentMessageFromHtml, extractCurrentMessageFromHtmlToText } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-microsoft';\nimport { schemas } from '@mcp-z/oauth-microsoft';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { type CallToolResult, getFileUri, ProtocolError, ProtocolErrorCode, reserveFile, type ToolModule } from '@mcp-z/server';\nimport { Client } from '@microsoft/microsoft-graph-client';\nimport type * as MicrosoftGraph from '@microsoft/microsoft-graph-types';\nimport { stringify } from 'csv-stringify/sync';\nimport { createWriteStream } from 'fs';\nimport { unlink } from 'fs/promises';\nimport { z } from 'zod';\nimport { executeQuery as executeOutlookQuery } from '../../email/querying/execute-query.ts';\nimport { cutToMaxItems } from '../../email/querying/paging-decisions.ts';\nimport { InvalidQueryError, OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.ts';\nimport type { StorageExtra } from '../../types.ts';\n\nconst DEFAULT_PAGE_SIZE = 50;\nconst DEFAULT_MAX_ITEMS = 10000;\nconst MAX_EXPORT_ITEMS = 50000;\n\nconst ExportResultSchema = z.object({\n uri: z.string().describe('File URI (file:// or http://)'),\n filename: z.string().describe('Stored filename'),\n rowCount: z.number().describe('Number of messages exported'),\n truncated: z.boolean().describe('Whether export was truncated at maxItems'),\n});\n\nconst inputSchema = z.object({\n query: OutlookQueryParameterSchema.optional().describe('Structured query object or JSON string for filtering messages. Use query-syntax prompt for reference and kqlQuery for KQL syntax.'),\n maxItems: z.number().int().positive().max(MAX_EXPORT_ITEMS).default(DEFAULT_MAX_ITEMS).describe(`Maximum messages to export (default: ${DEFAULT_MAX_ITEMS}, max: ${MAX_EXPORT_ITEMS})`),\n filename: z.string().trim().min(1).default('outlook-messages.csv').describe('Output filename (default: outlook-messages.csv)'),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schema\nconst successBranchSchema = ExportResultSchema.extend({\n type: z.literal('success'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Export Outlook messages to CSV with streaming pagination. Returns file URI. Use query-syntax prompt for query reference.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\n/**\n * Handler for outlook-messages-export-csv tool\n *\n * CRITICAL: Streaming implementation per user requirements\n * - Generate UUID upfront\n * - Write CSV header immediately\n * - Append rows as batches arrive\n * - Delete partial file on error\n * - NO RETRIES (fail fast on error)\n */\nasync function handler({ query, maxItems, filename, contentType, excludeThreadHistory }: Input, extra: EnrichedExtra & StorageExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n const { storageContext } = extra;\n const { transport, resourceStoreUri, baseUrl } = storageContext;\n\n // Reserve file location for streaming write (creates directory, generates ID, formats filename)\n const reservation = await reserveFile(filename, {\n resourceStoreUri,\n });\n const { storedName, fullPath } = reservation;\n\n logger.info('outlook.messages.export-csv starting streaming export', { path: fullPath, maxItems });\n\n try {\n const parsedQuery = parseOutlookQueryParameter(query);\n\n logger.info('outlook.messages.export-csv called', {\n query: parsedQuery,\n maxItems,\n filename,\n accountId: extra.authContext.accountId,\n });\n\n const graph = Client.initWithMiddleware({ authProvider: extra.authContext.auth });\n\n // Create CSV headers (all email fields)\n const csvHeaders = ['id', 'threadId', 'from', 'to', 'cc', 'bcc', 'subject', 'date', 'snippet', 'body', 'provider', 'labels'];\n\n // Create write stream and write headers immediately\n const writeStream = createWriteStream(fullPath, { encoding: 'utf-8' });\n const headerLine = stringify([csvHeaders], { header: false, quoted: true, quote: '\"', escape: '\"' });\n writeStream.write(headerLine);\n\n // Internal pagination loop - append to CSV with each batch\n // NO RETRIES: If any error occurs, fail the whole operation and clean up\n let totalRows = 0;\n let nextPageToken: string | undefined;\n let truncated = false;\n const started = Date.now();\n\n while (totalRows < maxItems) {\n const remainingItems = maxItems - totalRows;\n const pageSize = Math.min(remainingItems, DEFAULT_PAGE_SIZE);\n\n const exec: {\n items: Array<{\n id: string;\n threadId?: string;\n from: string;\n to: string;\n cc: string;\n bcc: string;\n subject: string;\n date: string;\n snippet: string;\n body: string;\n provider: string;\n labels: string;\n }>;\n metadata?: { nextPageToken?: string };\n } = await executeOutlookQuery(\n graph,\n parsedQuery,\n {\n logger,\n pageSize,\n ...(nextPageToken !== undefined && { pageToken: nextPageToken }),\n includeBody: true, // Always include body for CSV export\n limit: pageSize,\n },\n (m: unknown) => {\n const message = m as MicrosoftGraph.Message;\n const to = Array.isArray(message?.toRecipients)\n ? message.toRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const cc = Array.isArray(message?.ccRecipients)\n ? message.ccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const bcc = Array.isArray(message?.bccRecipients)\n ? message.bccRecipients\n .map((r: MicrosoftGraph.Recipient) => r?.emailAddress?.address ?? (r as { address?: string })?.address)\n .filter(Boolean)\n .join(', ')\n : '';\n const fromAddr = message?.from?.emailAddress?.address ?? (message?.from as { address?: string })?.address ?? '';\n const categories = Array.isArray(message?.categories) ? message.categories.join(';') : '';\n\n // Process body based on contentType and excludeThreadHistory options\n let body = message?.body?.content ?? '';\n const isHtml = message?.body?.contentType?.toLowerCase() === 'html';\n\n if (isHtml && excludeThreadHistory) {\n body = extractCurrentMessageFromHtml(body);\n }\n\n if (isHtml && contentType === 'text') {\n body = excludeThreadHistory ? extractCurrentMessageFromHtmlToText(body) : extractCurrentMessageFromHtmlToText(message?.body?.content ?? '');\n }\n\n return {\n id: String(message?.id ?? ''),\n threadId: message?.conversationId ? String(message.conversationId) : '',\n from: fromAddr,\n to,\n cc,\n bcc,\n subject: message?.subject ?? '',\n date: message?.receivedDateTime ?? '',\n snippet: message?.bodyPreview ?? '',\n body,\n provider: 'outlook' as const,\n labels: categories,\n };\n }\n );\n\n // The next-page link fixes $top at the first page's size, so a batch can hold more than is still wanted\n const cut = cutToMaxItems(exec.items, totalRows, maxItems, Boolean(exec.metadata?.nextPageToken));\n truncated = cut.truncated;\n\n const csvRows = cut.rows.map((item) => {\n return [item.id, item.threadId, item.from, item.to, item.cc, item.bcc, item.subject, item.date, item.snippet, item.body, item.provider, item.labels];\n });\n\n // Append rows to CSV file immediately\n if (csvRows.length > 0) {\n const rowsContent = stringify(csvRows, { header: false, quoted: true, quote: '\"', escape: '\"' });\n writeStream.write(rowsContent);\n }\n\n totalRows += cut.rows.length;\n nextPageToken = exec.metadata?.nextPageToken;\n\n logger.info('outlook.messages.export-csv batch written', {\n batchSize: cut.rows.length,\n totalRows,\n hasMore: Boolean(nextPageToken),\n });\n\n // Exit if no more results or reached maxItems\n if (!nextPageToken || exec.items.length === 0) {\n break;\n }\n }\n\n // Close write stream\n await new Promise<void>((resolve, reject) => {\n writeStream.end(() => resolve());\n writeStream.on('error', reject);\n });\n\n const durationMs = Date.now() - started;\n\n logger.info('outlook.messages.export-csv completed', {\n rowCount: totalRows,\n truncated,\n durationMs,\n filename: storedName,\n });\n\n // Generate URI based on transport type (stdio: file://, HTTP: http://)\n const uri = getFileUri(storedName, transport, {\n resourceStoreUri,\n ...(baseUrl && { baseUrl }),\n endpoint: '/files',\n });\n\n const result: Output = {\n type: 'success' as const,\n uri,\n filename: storedName,\n rowCount: totalRows,\n truncated,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n // CRITICAL: Clean up partial CSV file on error\n try {\n await unlink(fullPath);\n logger.debug('Cleaned up partial CSV file after error', { path: fullPath });\n } catch (_cleanupError) {\n logger.debug('Could not clean up CSV file (may not exist)', { path: fullPath });\n }\n\n if (error instanceof ProtocolError) throw error;\n if (error instanceof InvalidQueryError) throw new ProtocolError(ProtocolErrorCode.InvalidParams, error.message);\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('outlook.messages.export-csv error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error exporting messages to CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'messages-export-csv',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","DEFAULT_PAGE_SIZE","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","ExportResultSchema","z","object","uri","string","describe","filename","rowCount","number","truncated","boolean","inputSchema","query","OutlookQueryParameterSchema","optional","maxItems","int","positive","max","default","trim","min","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","storageContext","transport","resourceStoreUri","baseUrl","reservation","storedName","fullPath","parsedQuery","graph","csvHeaders","writeStream","headerLine","totalRows","nextPageToken","started","exec","remainingItems","pageSize","cut","csvRows","rowsContent","durationMs","error","_cleanupError","message","reserveFile","info","path","parseOutlookQueryParameter","accountId","authContext","Client","initWithMiddleware","authProvider","auth","createWriteStream","encoding","stringify","header","quoted","quote","escape","write","Date","now","Math","executeOutlookQuery","undefined","pageToken","includeBody","limit","m","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","categories","body","content","isHtml","toLowerCase","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","id","String","threadId","conversationId","subject","date","receivedDateTime","snippet","bodyPreview","provider","labels","cutToMaxItems","items","metadata","rows","item","length","batchSize","hasMore","Promise","resolve","reject","end","on","getFileUri","endpoint","text","JSON","structuredContent","unlink","debug","ProtocolError","InvalidQueryError","ProtocolErrorCode","InvalidParams","Error","InternalError","stack","name"],"mappings":"AAAA,oGAAoG;;;;+BAuRpG;;;eAAwBA;;;qBArR+G;8BAE/G;sBAIwF;oCACzF;oBAEG;kBACQ;wBACX;mBACL;8BACkC;iCACtB;oCAC6D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAX3F,IAAM,AAAEC,2BAA6BC,uBAAO,CAApCD;AAcR,IAAME,oBAAoB;AAC1B,IAAMC,oBAAoB;AAC1B,IAAMC,mBAAmB;AAEzB,IAAMC,qBAAqBC,MAAC,CAACC,MAAM,CAAC;IAClCC,KAAKF,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IACzBC,UAAUL,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;I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OAAO,GAAGqD,OAAOvD;oBAChEvB,OAAOuB,KAAK,CAAC,qCAAqC;wBAAEA,OAAOE;oBAAQ;oBAEnE,MAAM,IAAImF,qBAAa,CAACE,yBAAiB,CAACG,aAAa,EAAE,AAAC,oCAA2C,OAARxF,UAAW;wBACtGyF,OAAO3F,AAAK,YAALA,OAAiByF,SAAQzF,MAAM2F,KAAK,GAAGlE;oBAChD;;;;;;;IAEJ;;AAEe,SAAS3F;IACtB,OAAO;QACL8J,MAAM;QACNxH,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Check an `@odata.nextLink` and return its path and query after the version (`/me/messages?...`),
3
+ * as the URL parser writes them. Microsoft says to follow the whole link and not to rebuild it, so nothing is decoded or reordered.
4
+ */
5
+ export declare function checkNextLink(link: string): string;
@@ -0,0 +1,22 @@
1
+ import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
2
+ const GRAPH_HOST = 'graph.microsoft.com';
3
+ const GRAPH_VERSION_PATH = '/v1.0';
4
+ const MESSAGES_PATH = `${GRAPH_VERSION_PATH}/me/messages`;
5
+ function refuse(reason) {
6
+ throw new ProtocolError(ProtocolErrorCode.InternalError, `Microsoft Graph returned a next-page link that cannot be followed (${reason}); results would be incomplete`);
7
+ }
8
+ /**
9
+ * Check an `@odata.nextLink` and return its path and query after the version (`/me/messages?...`),
10
+ * as the URL parser writes them. Microsoft says to follow the whole link and not to rebuild it, so nothing is decoded or reordered.
11
+ */ export function checkNextLink(link) {
12
+ let url;
13
+ try {
14
+ url = new URL(link);
15
+ } catch {
16
+ return refuse('not a URL');
17
+ }
18
+ if (url.protocol !== 'https:') return refuse(`scheme ${url.protocol.slice(0, -1)}`);
19
+ if (url.host !== GRAPH_HOST) return refuse(`host ${url.host}`);
20
+ if (url.pathname !== MESSAGES_PATH) return refuse(`path ${url.pathname}`);
21
+ return url.pathname.slice(GRAPH_VERSION_PATH.length) + url.search;
22
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/email/querying/next-link.ts"],"sourcesContent":["import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\n\nconst GRAPH_HOST = 'graph.microsoft.com';\nconst GRAPH_VERSION_PATH = '/v1.0';\nconst MESSAGES_PATH = `${GRAPH_VERSION_PATH}/me/messages`;\n\nfunction refuse(reason: string): never {\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Microsoft Graph returned a next-page link that cannot be followed (${reason}); results would be incomplete`);\n}\n\n/**\n * Check an `@odata.nextLink` and return its path and query after the version (`/me/messages?...`),\n * as the URL parser writes them. Microsoft says to follow the whole link and not to rebuild it, so nothing is decoded or reordered.\n */\nexport function checkNextLink(link: string): string {\n let url: URL;\n try {\n url = new URL(link);\n } catch {\n return refuse('not a URL');\n }\n if (url.protocol !== 'https:') return refuse(`scheme ${url.protocol.slice(0, -1)}`);\n if (url.host !== GRAPH_HOST) return refuse(`host ${url.host}`);\n if (url.pathname !== MESSAGES_PATH) return refuse(`path ${url.pathname}`);\n return url.pathname.slice(GRAPH_VERSION_PATH.length) + url.search;\n}\n"],"names":["ProtocolError","ProtocolErrorCode","GRAPH_HOST","GRAPH_VERSION_PATH","MESSAGES_PATH","refuse","reason","InternalError","checkNextLink","link","url","URL","protocol","slice","host","pathname","length","search"],"mappings":"AAAA,SAASA,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AAEjE,MAAMC,aAAa;AACnB,MAAMC,qBAAqB;AAC3B,MAAMC,gBAAgB,GAAGD,mBAAmB,YAAY,CAAC;AAEzD,SAASE,OAAOC,MAAc;IAC5B,MAAM,IAAIN,cAAcC,kBAAkBM,aAAa,EAAE,CAAC,mEAAmE,EAAED,OAAO,8BAA8B,CAAC;AACvK;AAEA;;;CAGC,GACD,OAAO,SAASE,cAAcC,IAAY;IACxC,IAAIC;IACJ,IAAI;QACFA,MAAM,IAAIC,IAAIF;IAChB,EAAE,OAAM;QACN,OAAOJ,OAAO;IAChB;IACA,IAAIK,IAAIE,QAAQ,KAAK,UAAU,OAAOP,OAAO,CAAC,OAAO,EAAEK,IAAIE,QAAQ,CAACC,KAAK,CAAC,GAAG,CAAC,IAAI;IAClF,IAAIH,IAAII,IAAI,KAAKZ,YAAY,OAAOG,OAAO,CAAC,KAAK,EAAEK,IAAII,IAAI,EAAE;IAC7D,IAAIJ,IAAIK,QAAQ,KAAKX,eAAe,OAAOC,OAAO,CAAC,KAAK,EAAEK,IAAIK,QAAQ,EAAE;IACxE,OAAOL,IAAIK,QAAQ,CAACF,KAAK,CAACV,mBAAmBa,MAAM,IAAIN,IAAIO,MAAM;AACnE"}
@@ -1,12 +1,11 @@
1
- export declare const FIRST_PAGE_SKIP_TOKEN = "__mcp_outlook_first_page__";
2
1
  export interface DecodeNextPageTokenResult {
3
- skipToken?: string;
2
+ /** Path and query of the Graph next-page link that fetches the page, absent for the first page. */
3
+ link?: string;
4
4
  offset: number;
5
5
  mode?: string;
6
- legacy: boolean;
7
6
  }
8
7
  export declare function encodeNextPageToken(params: {
9
- skipToken?: string;
8
+ link?: string;
10
9
  offset: number;
11
10
  mode?: string;
12
11
  }): string;
@@ -1,59 +1,37 @@
1
1
  import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
2
- const PREFIX = 'v2:';
3
- export const FIRST_PAGE_SKIP_TOKEN = '__mcp_outlook_first_page__';
2
+ const PREFIX = 'v3:';
4
3
  export function encodeNextPageToken(params) {
5
- var _params_skipToken;
6
- const sanitizedOffset = Math.max(0, Math.trunc(params.offset));
7
4
  const payload = {
8
- v: 2,
9
- skipToken: (_params_skipToken = params.skipToken) !== null && _params_skipToken !== void 0 ? _params_skipToken : FIRST_PAGE_SKIP_TOKEN,
10
- offset: sanitizedOffset
5
+ v: 3,
6
+ offset: Math.max(0, Math.trunc(params.offset))
11
7
  };
12
- if (typeof params.mode === 'string' && params.mode.length > 0) {
13
- payload.mode = params.mode;
14
- }
15
- const serialized = JSON.stringify(payload);
16
- return `${PREFIX}${base64UrlEncode(serialized)}`;
8
+ if (params.link) payload.link = params.link;
9
+ if (typeof params.mode === 'string' && params.mode.length > 0) payload.mode = params.mode;
10
+ return `${PREFIX}${Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')}`;
17
11
  }
18
12
  export function decodeNextPageToken(token) {
19
- if (!token) {
20
- return {
21
- offset: 0,
22
- legacy: true
23
- };
24
- }
13
+ if (!token) return {
14
+ offset: 0
15
+ };
25
16
  if (!token.startsWith(PREFIX)) {
26
- return {
27
- skipToken: token,
28
- offset: 0,
29
- legacy: true
30
- };
17
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'pageToken was issued by an earlier mcp-outlook version and cannot be used; repeat the search without pageToken');
31
18
  }
32
- const encoded = token.slice(PREFIX.length);
33
19
  try {
34
- const decodedJson = base64UrlDecode(encoded);
35
- const parsed = JSON.parse(decodedJson);
36
- if (parsed.v !== 2) throw new Error('unsupported token version');
37
- const skipTokenRaw = parsed.skipToken;
38
- const offsetRaw = parsed.offset;
39
- if (typeof skipTokenRaw !== 'string' || skipTokenRaw.trim() === '') throw new Error('missing skipToken');
40
- if (typeof offsetRaw !== 'number' || !Number.isInteger(offsetRaw) || offsetRaw < 0) throw new Error('invalid offset');
20
+ const parsed = JSON.parse(Buffer.from(token.slice(PREFIX.length), 'base64url').toString('utf8'));
21
+ if (parsed.v !== 3) throw new Error('unsupported token version');
22
+ const { link, offset, mode } = parsed;
23
+ if (link !== undefined && (typeof link !== 'string' || link === '')) throw new Error('invalid link');
24
+ if (typeof offset !== 'number' || !Number.isInteger(offset) || offset < 0) throw new Error('invalid offset');
41
25
  return {
42
- skipToken: skipTokenRaw === FIRST_PAGE_SKIP_TOKEN ? undefined : skipTokenRaw,
43
- offset: offsetRaw,
44
- mode: typeof parsed.mode === 'string' ? parsed.mode : undefined,
45
- legacy: false
26
+ ...typeof link === 'string' && {
27
+ link
28
+ },
29
+ offset,
30
+ ...typeof mode === 'string' && {
31
+ mode
32
+ }
46
33
  };
47
34
  } catch {
48
35
  throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid pageToken');
49
36
  }
50
37
  }
51
- function base64UrlEncode(value) {
52
- return Buffer.from(value, 'utf8').toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
53
- }
54
- function base64UrlDecode(value) {
55
- const padded = value.replace(/-/g, '+').replace(/_/g, '/');
56
- const padLength = (4 - padded.length % 4) % 4;
57
- const normalized = padded + '='.repeat(padLength);
58
- return Buffer.from(normalized, 'base64').toString('utf8');
59
- }
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/email/querying/pagination-token.ts"],"sourcesContent":["import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\n\nconst PREFIX = 'v2:';\nexport const FIRST_PAGE_SKIP_TOKEN = '__mcp_outlook_first_page__';\n\ninterface V2Payload {\n v: 2;\n skipToken: string;\n offset: number;\n mode?: string;\n}\n\nexport interface DecodeNextPageTokenResult {\n skipToken?: string;\n offset: number;\n mode?: string;\n legacy: boolean;\n}\n\nexport function encodeNextPageToken(params: { skipToken?: string; offset: number; mode?: string }): string {\n const sanitizedOffset = Math.max(0, Math.trunc(params.offset));\n const payload: V2Payload = {\n v: 2,\n skipToken: params.skipToken ?? FIRST_PAGE_SKIP_TOKEN,\n offset: sanitizedOffset,\n };\n if (typeof params.mode === 'string' && params.mode.length > 0) {\n payload.mode = params.mode;\n }\n const serialized = JSON.stringify(payload);\n return `${PREFIX}${base64UrlEncode(serialized)}`;\n}\n\nexport function decodeNextPageToken(token: string | undefined): DecodeNextPageTokenResult {\n if (!token) {\n return { offset: 0, legacy: true };\n }\n\n if (!token.startsWith(PREFIX)) {\n return { skipToken: token, offset: 0, legacy: true };\n }\n\n const encoded = token.slice(PREFIX.length);\n try {\n const decodedJson = base64UrlDecode(encoded);\n const parsed = JSON.parse(decodedJson) as Record<string, unknown>;\n if (parsed.v !== 2) throw new Error('unsupported token version');\n const skipTokenRaw = parsed.skipToken;\n const offsetRaw = parsed.offset;\n if (typeof skipTokenRaw !== 'string' || skipTokenRaw.trim() === '') throw new Error('missing skipToken');\n if (typeof offsetRaw !== 'number' || !Number.isInteger(offsetRaw) || offsetRaw < 0) throw new Error('invalid offset');\n\n return {\n skipToken: skipTokenRaw === FIRST_PAGE_SKIP_TOKEN ? undefined : skipTokenRaw,\n offset: offsetRaw,\n mode: typeof parsed.mode === 'string' ? parsed.mode : undefined,\n legacy: false,\n };\n } catch {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid pageToken');\n }\n}\n\nfunction base64UrlEncode(value: string): string {\n return Buffer.from(value, 'utf8').toString('base64').replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction base64UrlDecode(value: string): string {\n const padded = value.replace(/-/g, '+').replace(/_/g, '/');\n const padLength = (4 - (padded.length % 4)) % 4;\n const normalized = padded + '='.repeat(padLength);\n return Buffer.from(normalized, 'base64').toString('utf8');\n}\n"],"names":["ProtocolError","ProtocolErrorCode","PREFIX","FIRST_PAGE_SKIP_TOKEN","encodeNextPageToken","params","sanitizedOffset","Math","max","trunc","offset","payload","v","skipToken","mode","length","serialized","JSON","stringify","base64UrlEncode","decodeNextPageToken","token","legacy","startsWith","encoded","slice","decodedJson","base64UrlDecode","parsed","parse","Error","skipTokenRaw","offsetRaw","trim","Number","isInteger","undefined","InvalidParams","value","Buffer","from","toString","replace","padded","padLength","normalized","repeat"],"mappings":"AAAA,SAASA,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AAEjE,MAAMC,SAAS;AACf,OAAO,MAAMC,wBAAwB,6BAA6B;AAgBlE,OAAO,SAASC,oBAAoBC,MAA6D;QAIlFA;IAHb,MAAMC,kBAAkBC,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACJ,OAAOK,MAAM;IAC5D,MAAMC,UAAqB;QACzBC,GAAG;QACHC,SAAS,GAAER,oB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C,OAAOC,IAAI,CAACF,OAAO,QAAQG,QAAQ,CAAC,UAAUC,OAAO,CAAC,OAAO,KAAKA,OAAO,CAAC,OAAO,KAAKA,OAAO,CAAC,OAAO;AAC9G;AAEA,SAASf,gBAAgBW,KAAa;IACpC,MAAMK,SAASL,MAAMI,OAAO,CAAC,MAAM,KAAKA,OAAO,CAAC,MAAM;IACtD,MAAME,YAAY,AAAC,CAAA,IAAKD,OAAO5B,MAAM,GAAG,CAAC,IAAK;IAC9C,MAAM8B,aAAaF,SAAS,IAAIG,MAAM,CAACF;IACvC,OAAOL,OAAOC,IAAI,CAACK,YAAY,UAAUJ,QAAQ,CAAC;AACpD"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/email/querying/pagination-token.ts"],"sourcesContent":["import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\n\nconst PREFIX = 'v3:';\n\ninterface V3Payload {\n v: 3;\n link?: string;\n offset: number;\n mode?: string;\n}\n\nexport interface DecodeNextPageTokenResult {\n /** Path and query of the Graph next-page link that fetches the page, absent for the first page. */\n link?: string;\n offset: number;\n mode?: string;\n}\n\nexport function encodeNextPageToken(params: { link?: string; offset: number; mode?: string }): string {\n const payload: V3Payload = { v: 3, offset: Math.max(0, Math.trunc(params.offset)) };\n if (params.link) payload.link = params.link;\n if (typeof params.mode === 'string' && params.mode.length > 0) payload.mode = params.mode;\n return `${PREFIX}${Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')}`;\n}\n\nexport function decodeNextPageToken(token: string | undefined): DecodeNextPageTokenResult {\n if (!token) return { offset: 0 };\n\n if (!token.startsWith(PREFIX)) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'pageToken was issued by an earlier mcp-outlook version and cannot be used; repeat the search without pageToken');\n }\n\n try {\n const parsed = JSON.parse(Buffer.from(token.slice(PREFIX.length), 'base64url').toString('utf8')) as Record<string, unknown>;\n if (parsed.v !== 3) throw new Error('unsupported token version');\n const { link, offset, mode } = parsed;\n if (link !== undefined && (typeof link !== 'string' || link === '')) throw new Error('invalid link');\n if (typeof offset !== 'number' || !Number.isInteger(offset) || offset < 0) throw new Error('invalid offset');\n return {\n ...(typeof link === 'string' && { link }),\n offset,\n ...(typeof mode === 'string' && { mode }),\n };\n } catch {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid pageToken');\n }\n}\n"],"names":["ProtocolError","ProtocolErrorCode","PREFIX","encodeNextPageToken","params","payload","v","offset","Math","max","trunc","link","mode","length","Buffer","from","JSON","stringify","toString","decodeNextPageToken","token","startsWith","InvalidParams","parsed","parse","slice","Error","undefined","Number","isInteger"],"mappings":"AAAA,SAASA,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AAEjE,MAAMC,SAAS;AAgBf,OAAO,SAASC,oBAAoBC,MAAwD;IAC1F,MAAMC,UAAqB;QAAEC,GAAG;QAAGC,QAAQC,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACN,OAAOG,MAAM;IAAG;IAClF,IAAIH,OAAOO,IAAI,EAAEN,QAAQM,IAAI,GAAGP,OAAOO,IAAI;IAC3C,IAAI,OAAOP,OAAOQ,IAAI,KAAK,YAAYR,OAAOQ,IAAI,CAACC,MAAM,GAAG,GAAGR,QAAQO,IAAI,GAAGR,OAAOQ,IAAI;IACzF,OAAO,GAAGV,SAASY,OAAOC,IAAI,CAACC,KAAKC,SAAS,CAACZ,UAAU,QAAQa,QAAQ,CAAC,cAAc;AACzF;AAEA,OAAO,SAASC,oBAAoBC,KAAyB;IAC3D,IAAI,CAACA,OAAO,OAAO;QAAEb,QAAQ;IAAE;IAE/B,IAAI,CAACa,MAAMC,UAAU,CAACnB,SAAS;QAC7B,MAAM,IAAIF,cAAcC,kBAAkBqB,aAAa,EAAE;IAC3D;IAEA,IAAI;QACF,MAAMC,SAASP,KAAKQ,KAAK,CAACV,OAAOC,IAAI,CAACK,MAAMK,KAAK,CAACvB,OAAOW,MAAM,GAAG,aAAaK,QAAQ,CAAC;QACxF,IAAIK,OAAOjB,CAAC,KAAK,GAAG,MAAM,IAAIoB,MAAM;QACpC,MAAM,EAAEf,IAAI,EAAEJ,MAAM,EAAEK,IAAI,EAAE,GAAGW;QAC/B,IAAIZ,SAASgB,aAAc,CAAA,OAAOhB,SAAS,YAAYA,SAAS,EAAC,GAAI,MAAM,IAAIe,MAAM;QACrF,IAAI,OAAOnB,WAAW,YAAY,CAACqB,OAAOC,SAAS,CAACtB,WAAWA,SAAS,GAAG,MAAM,IAAImB,MAAM;QAC3F,OAAO;YACL,GAAI,OAAOf,SAAS,YAAY;gBAAEA;YAAK,CAAC;YACxCJ;YACA,GAAI,OAAOK,SAAS,YAAY;gBAAEA;YAAK,CAAC;QAC1C;IACF,EAAE,OAAM;QACN,MAAM,IAAIZ,cAAcC,kBAAkBqB,aAAa,EAAE;IAC3D;AACF"}
@@ -0,0 +1,14 @@
1
+ /** Token that resumes inside the page fetched by `link`, one message past the last one taken. */
2
+ export declare function midPageToken(params: {
3
+ link?: string;
4
+ pageStart: number;
5
+ index: number;
6
+ mode: 'search' | 'filter';
7
+ }): string;
8
+ /** Which collection a page token resumes: a fallback-filter token resumes the filter collection, anything else the search. */
9
+ export declare function resumeCollection(mode: string | undefined): 'search' | 'filter';
10
+ /** Cut a batch to what still fits under maxItems; truncated when rows were cut or a link remains at the limit. */
11
+ export declare function cutToMaxItems<T>(rows: T[], taken: number, maxItems: number, hasMore: boolean): {
12
+ rows: T[];
13
+ truncated: boolean;
14
+ };
@@ -0,0 +1,21 @@
1
+ import { encodeNextPageToken } from './pagination-token.js';
2
+ /** Token that resumes inside the page fetched by `link`, one message past the last one taken. */ export function midPageToken(params) {
3
+ return encodeNextPageToken({
4
+ ...params.link && {
5
+ link: params.link
6
+ },
7
+ offset: params.pageStart + params.index + 1,
8
+ mode: params.mode
9
+ });
10
+ }
11
+ /** Which collection a page token resumes: a fallback-filter token resumes the filter collection, anything else the search. */ export function resumeCollection(mode) {
12
+ return mode === 'filter' ? 'filter' : 'search';
13
+ }
14
+ /** Cut a batch to what still fits under maxItems; truncated when rows were cut or a link remains at the limit. */ export function cutToMaxItems(rows, taken, maxItems, hasMore) {
15
+ const kept = rows.slice(0, Math.max(0, maxItems - taken));
16
+ const truncated = kept.length < rows.length || taken + kept.length >= maxItems && hasMore;
17
+ return {
18
+ rows: kept,
19
+ truncated
20
+ };
21
+ }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/email/querying/paging-decisions.ts"],"sourcesContent":["import { encodeNextPageToken } from './pagination-token.ts';\n\n/** Token that resumes inside the page fetched by `link`, one message past the last one taken. */\nexport function midPageToken(params: { link?: string; pageStart: number; index: number; mode: 'search' | 'filter' }): string {\n return encodeNextPageToken({ ...(params.link && { link: params.link }), offset: params.pageStart + params.index + 1, mode: params.mode });\n}\n\n/** Which collection a page token resumes: a fallback-filter token resumes the filter collection, anything else the search. */\nexport function resumeCollection(mode: string | undefined): 'search' | 'filter' {\n return mode === 'filter' ? 'filter' : 'search';\n}\n\n/** Cut a batch to what still fits under maxItems; truncated when rows were cut or a link remains at the limit. */\nexport function cutToMaxItems<T>(rows: T[], taken: number, maxItems: number, hasMore: boolean): { rows: T[]; truncated: boolean } {\n const kept = rows.slice(0, Math.max(0, maxItems - taken));\n const truncated = kept.length < rows.length || (taken + kept.length >= maxItems && hasMore);\n return { rows: kept, truncated };\n}\n"],"names":["encodeNextPageToken","midPageToken","params","link","offset","pageStart","index","mode","resumeCollection","cutToMaxItems","rows","taken","maxItems","hasMore","kept","slice","Math","max","truncated","length"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,wBAAwB;AAE5D,+FAA+F,GAC/F,OAAO,SAASC,aAAaC,MAAsF;IACjH,OAAOF,oBAAoB;QAAE,GAAIE,OAAOC,IAAI,IAAI;YAAEA,MAAMD,OAAOC,IAAI;QAAC,CAAC;QAAGC,QAAQF,OAAOG,SAAS,GAAGH,OAAOI,KAAK,GAAG;QAAGC,MAAML,OAAOK,IAAI;IAAC;AACzI;AAEA,4HAA4H,GAC5H,OAAO,SAASC,iBAAiBD,IAAwB;IACvD,OAAOA,SAAS,WAAW,WAAW;AACxC;AAEA,gHAAgH,GAChH,OAAO,SAASE,cAAiBC,IAAS,EAAEC,KAAa,EAAEC,QAAgB,EAAEC,OAAgB;IAC3F,MAAMC,OAAOJ,KAAKK,KAAK,CAAC,GAAGC,KAAKC,GAAG,CAAC,GAAGL,WAAWD;IAClD,MAAMO,YAAYJ,KAAKK,MAAM,GAAGT,KAAKS,MAAM,IAAKR,QAAQG,KAAKK,MAAM,IAAIP,YAAYC;IACnF,OAAO;QAAEH,MAAMI;QAAMI;IAAU;AACjC"}