@mcp-z/mcp-outlook 2.3.1 → 2.4.1
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 +4 -2
- 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 +36 -29
- package/dist/cjs/email/querying/query-builder.js.map +1 -1
- package/dist/cjs/lib/create-store.d.cts +2 -1
- package/dist/cjs/lib/create-store.d.ts +2 -1
- package/dist/cjs/lib/create-store.js +62 -6
- 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 +33 -5
- package/dist/cjs/mcp/tools/label-delete.js.map +1 -1
- package/dist/cjs/mcp/tools/message-move-to-trash.js +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/http.d.cts +1 -1
- package/dist/cjs/setup/http.d.ts +1 -1
- package/dist/cjs/setup/http.js +1 -1
- package/dist/cjs/setup/runtime.d.cts +2 -2
- package/dist/cjs/setup/runtime.d.ts +2 -2
- package/dist/cjs/setup/runtime.js +7 -7
- package/dist/cjs/setup/runtime.js.map +1 -1
- package/dist/cjs/setup/stdio.js +1 -1
- package/dist/cjs/setup/version-help.js +1 -1
- package/dist/cjs/setup/version-help.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.d.ts +2 -1
- package/dist/esm/lib/create-store.js +13 -3
- 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/http.d.ts +1 -1
- package/dist/esm/setup/runtime.d.ts +2 -2
- package/dist/esm/setup/runtime.js +6 -6
- package/dist/esm/setup/runtime.js.map +1 -1
- package/dist/esm/setup/version-help.js +1 -1
- package/dist/esm/setup/version-help.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/mcp/tools/label-delete.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-microsoft';\nimport { schemas } from '@mcp-z/oauth-microsoft';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { Client } from '@microsoft/microsoft-graph-client';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\n\nconst BatchResultSchema = z.object({\n totalRequested: z.number().describe('Total number of categories requested to delete'),\n successCount: z.number().describe('Number of categories successfully deleted'),\n failureCount: z.number().describe('Number of categories that failed to delete'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Category ID'),\n success: z.boolean().describe('Whether the operation succeeded'),\n error: z.string().optional().describe('Error message if operation failed'),\n })\n )\n .describe('Individual results for each category'),\n});\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).max(MAX_BATCH_SIZE).describe('Outlook category IDs to delete'),\n});\n\n// Success branch schema\nconst successBranchSchema = BatchResultSchema.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: 'Delete Outlook categories permanently (irreversible). Categories organize messages by color and name.',\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({ ids }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('outlook-label-delete called', { count: ids.length });\n\n // Validate IDs for Outlook-specific constraints\n // Note: Schema already validates non-empty, trimmed strings with min/max length\n // This check enforces business rule: Outlook category IDs cannot contain path separators or angle brackets\n const invalidIds: string[] = [];\n for (const id of ids) {\n if (id.includes('/') || id.includes('\\\\') || id.includes('<') || id.includes('>')) {\n invalidIds.push(id);\n }\n }\n\n if (invalidIds.length > 0) {\n logger.info('outlook-label-delete found invalid ids', { invalidIds, count: invalidIds.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs (contain invalid characters): ${invalidIds.join(', ')}`);\n }\n\n try {\n const graph = Client.initWithMiddleware({ authProvider: extra.authContext.auth });\n // Process deletions in chunks to prevent memory exhaustion\n const allResults: Array<{ id: string; success: boolean; error?: string }> = [];\n\n for (let i = 0; i < ids.length; i += CHUNK_SIZE) {\n const chunk = ids.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(ids.length / CHUNK_SIZE) });\n\n // Delete categories sequentially to avoid API lock conflicts\n const chunkResults: Array<{ status: string; value?: unknown; reason?: unknown }> = [];\n for (const id of chunk) {\n try {\n await graph.api(`/me/outlook/masterCategories/${encodeURIComponent(id)}`).delete();\n chunkResults.push({ status: 'fulfilled', value: { id, success: true } });\n } catch (error) {\n chunkResults.push({ status: 'rejected', reason: error });\n }\n }\n\n // Process chunk results\n const processedChunkResults = chunkResults.map((result, chunkIndex) => {\n const id = chunk[chunkIndex];\n if (!id) {\n throw new Error(`Chunk index ${chunkIndex} is out of bounds for chunk of size ${chunk.length}`);\n }\n if (result.status === 'fulfilled') {\n return { id, success: true };\n }\n\n // Extract error message more robustly\n let errorMessage = 'Unknown error';\n if (result.reason) {\n if (typeof result.reason === 'string') {\n errorMessage = result.reason;\n } else if (result.reason instanceof Error) {\n errorMessage = result.reason.message;\n } else if (result.reason && typeof result.reason === 'object' && 'message' in result.reason) {\n errorMessage = String(result.reason.message);\n } else if (result.reason && typeof result.reason === 'object' && 'error' in result.reason) {\n errorMessage = String(result.reason.error);\n } else {\n errorMessage = String(result.reason);\n }\n }\n\n return { id, success: false, error: errorMessage };\n });\n\n allResults.push(...processedChunkResults);\n }\n\n const successCount = allResults.filter((r) => r.success).length;\n const failureCount = allResults.filter((r) => !r.success).length;\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: ids.length,\n successCount,\n failureCount,\n results: allResults,\n };\n\n logger.info('outlook-label-delete completed', {\n totalRequested: ids.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(ids.length / CHUNK_SIZE),\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 const message = error instanceof Error ? error.message : String(error);\n logger.error('outlook-label-delete error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error deleting categories: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'label-delete',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","BatchResultSchema","z","object","totalRequested","number","describe","successCount","failureCount","results","array","id","string","success","boolean","error","optional","inputSchema","ids","coerce","trim","min","max","MAX_BATCH_SIZE","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","invalidIds","graph","allResults","i","message","info","count","length","includes","push","ProtocolError","ProtocolErrorCode","InvalidParams","join","chunk","chunkResults","processedChunkResults","slice","CHUNK_SIZE","chunkIndex","chunkSize","totalChunks","Math","ceil","api","encodeURIComponent","delete","status","value","reason","map","Error","errorMessage","String","Client","initWithMiddleware","authProvider","authContext","auth","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","name"],"mappings":";;;;+BA6JA;;;eAAwBA;;;8BA5JA;sBAK8C;oCAC/C;mBACL;2BACyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3C,IAAM,AAAEC,2BAA6BC,uBAAO,CAApCD;AAQR,IAAME,oBAAoBC,MAAC,CAACC,MAAM,CAAC;IACjCC,gBAAgBF,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IACpCC,cAAcL,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IAClCE,cAAcN,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IAClCG,SAASP,MAAC,CACPQ,KAAK,CACJR,MAAC,CAACC,MAAM,CAAC;QACPQ,IAAIT,MAAC,CAACU,MAAM,GAAGN,QAAQ,CAAC;QACxBO,SAASX,MAAC,CAACY,OAAO,GAAGR,QAAQ,CAAC;QAC9BS,OAAOb,MAAC,CAAC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,MAAM,AAAD;;;;;;;;;;;;oBAAGJ,KAAKe,uBAAU;;;;;;oBA+CzC/C,eAAe+B,WAAWqC,MAAM,CAAC,SAACC;+BAAMA,EAAE/D,OAAO;uBAAE8B,MAAM;oBACzDnC,eAAe8B,WAAWqC,MAAM,CAAC,SAACC;+BAAM,CAACA,EAAE/D,OAAO;uBAAE8B,MAAM;oBAE1DX,SAAiB;wBACrBN,MAAM;wBACNtB,gBAAgBc,IAAIyB,MAAM;wBAC1BpC,cAAAA;wBACAC,cAAAA;wBACAC,SAAS6B;oBACX;oBAEAH,OAAOM,IAAI,CAAC,kCAAkC;wBAC5CrC,gBAAgBc,IAAIyB,MAAM;wBAC1BpC,cAAAA;wBACAC,cAAAA;wBACAqE,iBAAiBnB,KAAKC,IAAI,CAACzC,IAAIyB,MAAM,GAAGW,uBAAU;oBACpD;oBAEA;;wBAAO;4BACLwB,OAAO;gCACL;oCACEpD,MAAM;oCACNqD,MAAMC,KAAKC,SAAS,CAACjD;gCACvB;;4BAEFkD,mBAAmB;gCAAElD,QAAAA;4BAAO;wBAC9B;;;oBACOjB;oBACDyB,UAAUzB,AAAK,YAALA,OAAiBoD,SAAQpD,MAAMyB,OAAO,GAAG6B,OAAOtD;oBAChEoB,OAAOpB,KAAK,CAAC,8BAA8B;wBAAEA,OAAOyB;oBAAQ;oBAE5D,MAAM,IAAIM,qBAAa,CAACC,yBAAiB,CAACoC,aAAa,EAAE,AAAC,8BAAqC,OAAR3C,UAAW;wBAChG4C,OAAOrE,AAAK,YAALA,OAAiBoD,SAAQpD,MAAMqE,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASvF;IACtB,OAAO;QACLwF,MAAM;QACNxD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/mcp/tools/label-delete.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-microsoft';\nimport { schemas } from '@mcp-z/oauth-microsoft';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { type CallToolResult, ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { Client } from '@microsoft/microsoft-graph-client';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\n\nconst BatchResultSchema = z.object({\n totalRequested: z.number().describe('Total number of categories requested to delete'),\n successCount: z.number().describe('Number of categories successfully deleted'),\n failureCount: z.number().describe('Number of categories that failed to delete'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Category ID'),\n success: z.boolean().describe('Whether the operation succeeded'),\n error: z.string().optional().describe('Error message if operation failed'),\n })\n )\n .describe('Individual results for each category'),\n});\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).max(MAX_BATCH_SIZE).describe('Outlook category IDs to delete'),\n});\n\n// Success branch schema\nconst successBranchSchema = BatchResultSchema.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: 'Delete Outlook categories permanently (irreversible). Categories organize messages by color and name.',\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\ntype DeleteResult = { id: string; success: boolean; error?: string };\n\n/**\n * An all-failed batch is an error, not a result: returns the error to throw when every delete failed, otherwise null.\n * A partly failed batch keeps the success shape with failureCount and per-id errors.\n */\nexport function allFailedError(results: DeleteResult[]): ProtocolError | null {\n if (results.length === 0 || results.some((r) => r.success)) return null;\n const failures = results.map((r) => `${r.id}: ${r.error ?? 'Unknown error'}`);\n return new ProtocolError(ProtocolErrorCode.InternalError, `Failed to delete all ${results.length} categories. ${failures.join('; ')}`, { results });\n}\n\nasync function handler({ ids }: Input, extra: EnrichedExtra): Promise<CallToolResult> {\n const logger = extra.logger;\n logger.info('outlook-label-delete called', { count: ids.length });\n\n // Validate IDs for Outlook-specific constraints\n // Note: Schema already validates non-empty, trimmed strings with min/max length\n // This check enforces business rule: Outlook category IDs cannot contain path separators or angle brackets\n const invalidIds: string[] = [];\n for (const id of ids) {\n if (id.includes('/') || id.includes('\\\\') || id.includes('<') || id.includes('>')) {\n invalidIds.push(id);\n }\n }\n\n if (invalidIds.length > 0) {\n logger.info('outlook-label-delete found invalid ids', { invalidIds, count: invalidIds.length });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs (contain invalid characters): ${invalidIds.join(', ')}`);\n }\n\n try {\n const graph = Client.initWithMiddleware({ authProvider: extra.authContext.auth });\n // Process deletions in chunks to prevent memory exhaustion\n const allResults: DeleteResult[] = [];\n\n for (let i = 0; i < ids.length; i += CHUNK_SIZE) {\n const chunk = ids.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(ids.length / CHUNK_SIZE) });\n\n // Delete categories sequentially to avoid API lock conflicts\n const chunkResults: Array<{ status: string; value?: unknown; reason?: unknown }> = [];\n for (const id of chunk) {\n try {\n await graph.api(`/me/outlook/masterCategories/${encodeURIComponent(id)}`).delete();\n chunkResults.push({ status: 'fulfilled', value: { id, success: true } });\n } catch (error) {\n chunkResults.push({ status: 'rejected', reason: error });\n }\n }\n\n // Process chunk results\n const processedChunkResults = chunkResults.map((result, chunkIndex) => {\n const id = chunk[chunkIndex];\n if (!id) {\n throw new Error(`Chunk index ${chunkIndex} is out of bounds for chunk of size ${chunk.length}`);\n }\n if (result.status === 'fulfilled') {\n return { id, success: true };\n }\n\n // Extract error message more robustly\n let errorMessage = 'Unknown error';\n if (result.reason) {\n if (typeof result.reason === 'string') {\n errorMessage = result.reason;\n } else if (result.reason instanceof Error) {\n errorMessage = result.reason.message;\n } else if (result.reason && typeof result.reason === 'object' && 'message' in result.reason) {\n errorMessage = String(result.reason.message);\n } else if (result.reason && typeof result.reason === 'object' && 'error' in result.reason) {\n errorMessage = String(result.reason.error);\n } else {\n errorMessage = String(result.reason);\n }\n }\n\n return { id, success: false, error: errorMessage };\n });\n\n allResults.push(...processedChunkResults);\n }\n\n const successCount = allResults.filter((r) => r.success).length;\n const failureCount = allResults.filter((r) => !r.success).length;\n\n const failed = allFailedError(allResults);\n if (failed) {\n logger.error('outlook-label-delete all deletes failed', { totalRequested: ids.length });\n throw failed;\n }\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: ids.length,\n successCount,\n failureCount,\n results: allResults,\n };\n\n logger.info('outlook-label-delete completed', {\n totalRequested: ids.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(ids.length / CHUNK_SIZE),\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 const message = error instanceof Error ? error.message : String(error);\n logger.error('outlook-label-delete error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error deleting categories: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'label-delete',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["allFailedError","createTool","AuthRequiredBranchSchema","schemas","BatchResultSchema","z","object","totalRequested","number","describe","successCount","failureCount","results","array","id","string","success","boolean","error","optional","inputSchema","ids","coerce","trim","min","max","MAX_BATCH_SIZE","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","length","some","r","failures","map","ProtocolError","ProtocolErrorCode","InternalError","join","handler","extra","logger","invalidIds","graph","allResults","i","failed","message","info","count","includes","push","InvalidParams","chunk","chunkResults","processedChunkResults","slice","CHUNK_SIZE","chunkIndex","chunkSize","totalChunks","Math","ceil","api","encodeURIComponent","delete","status","value","reason","Error","errorMessage","String","Client","initWithMiddleware","authProvider","authContext","auth","filter","chunksProcessed","content","text","JSON","stringify","structuredContent","stack","undefined","name"],"mappings":";;;;;;;;;;;QAuDgBA;eAAAA;;QAyHhB;eAAwBC;;;8BA/KA;sBAK8C;oCAC/C;mBACL;2BACyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3C,IAAM,AAAEC,2BAA6BC,uBAAO,CAApCD;AAQR,IAAME,oBAAoBC,MAAC,CAACC,MAAM,CAAC;IACjCC,gBAAgBF,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IACpCC,cAAcL,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IAClCE,cAAcN,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IAClCG,SAASP,MAAC,CACPQ,KAAK,CACJR,MAAC,CAACC,MAAM,CAAC;QACPQ,IAAIT,MAAC,CAACU,MAAM,GAAGN,QAAQ,CAAC;QACxBO,SAASX,MAAC,CAACY,OAAO,GAAGR,QAAQ,CAAC;QAC9BS,OAAOb,MAAC,CAACU,MAAM,GAAGI,QAAQ,GAAGV,QAAQ,CAAC;IACxC,IAEDA,QAAQ,CAAC;AACd;AAEA,IAAMW,cAAcf,MAAC,CAACC,MAAM,CAAC;IAC3Be,KAAKhB,MAAC,CAACQ,KAAK,CAACR,MAAC,CAACiB,MAAM,CAACP,MAAM,GAAGQ,IAAI,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,GAAG,CAACC,2BAAc,EAAEjB,QAAQ,CAAC;AACpF;AAEA,wBAAwB;AACxB,IAAMkB,sBAAsBvB,kBAAkBwB,MAAM,CAAC;IACnDC,MAAMxB,MAAC,CAACyB,OAAO,CAAC;AAClB;AA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,YAALA,OAAiByD,SAAQzD,MAAMwE,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1F;IACtB,OAAO;QACL2F,MAAM;QACN3D,QAAAA;QACAY,SAAAA;IACF;AACF"}
|
|
@@ -192,7 +192,7 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
192
192
|
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
193
193
|
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
194
194
|
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
195
|
-
if (n === "Map" || n === "Set") return Array.from(
|
|
195
|
+
if (n === "Map" || n === "Set") return Array.from(o);
|
|
196
196
|
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
197
197
|
}
|
|
198
198
|
var AuthRequiredBranchSchema = _oauthmicrosoft.schemas.AuthRequiredBranchSchema;
|
|
@@ -379,6 +379,7 @@ function handler(_0, _1) {
|
|
|
379
379
|
case 3:
|
|
380
380
|
error = _state.sent();
|
|
381
381
|
if (_instanceof(error, _server.ProtocolError)) throw error;
|
|
382
|
+
if (_instanceof(error, _outlookqueryschemats.InvalidQueryError)) throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, error.message);
|
|
382
383
|
message = _instanceof(error, Error) ? error.message : String(error);
|
|
383
384
|
logger.error('outlook.message.search error', {
|
|
384
385
|
error: message
|
|
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARxE,IAAM,AAAEC,2BAA6BC,uBAAO,CAApCD;AAUR,IAAME,cAAcC,MAAC,CAACC,MAAM,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EA,4BAA4B;oBACtBzD,cAAcH,KAAK4D,QAAQ;oBAEjC,8BAA8B;oBACxBxE,SACJtB,UAAU,WACN;wBACEO,MAAM;wBACNP,OAAO;uBACJ+F,IAAAA,wBAAgB,EAAC3D,eAAeP,iBAAiBvC,mBAAY,GAC5D+C,CAAAA,wBAAAA,kCAAAA,YAAazB,aAAa,KAAI;wBAAEA,eAAeyB,YAAYzB,aAAa;oBAAC,KAE/E;wBACEL,MAAM;wBACNP,OAAO;wBACPS,OAAO2B;uBACHC,CAAAA,wBAAAA,kCAAAA,YAAazB,aAAa,KAAI;wBAAEA,eAAeyB,YAAYzB,aAAa;oBAAC;oBAGrF;;wBAAO;4BACLiE,OAAO;gCACL;oCACEtE,MAAM;oCACNyF,MAAMC,KAAKC,SAAS,CAAC5E;gCACvB;;4BAEF6E,mBAAmB;gCAAE7E,QAAAA;4BAAO;wBAC9B;;;oBACOgB;oBACP,IAAIA,AAAK,YAALA,OAAiB8D,qBAAa,GAAE,MAAM9D;oBAEpCC,UAAUD,AAAK,YAALA,OAAiB+D,SAAQ/D,MAAMC,OAAO,GAAG+D,OAAOhE;oBAChEX,OAAOW,KAAK,CAAC,gCAAgC;wBAAEA,OAAOC;oBAAQ;oBAE9D,MAAM,IAAI6D,qBAAa,CAACG,yBAAiB,CAACC,aAAa,EAAE,AAAC,6BAAoC,OAARjE,UAAW;wBAC/FkE,OAAOnE,AAAK,YAALA,OAAiB+D,SAAQ/D,MAAMmE,KAAK,GAAG5D;oBAChD;;;;;;;IAEJ;;AAEe,SAASpE;IACtB,OAAO;QACLiG,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","ProtocolError","InvalidQueryError","ProtocolErrorCode","InvalidParams","Error","String","InternalError","stack"],"mappings":";;;;+BAyMA;;;eAAwBA;;;qBAzMmN;8BAEnN;sBAI2K;oCAC5K;mBAEL;8BACQ;8BAC0B;oCACuC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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BAChD;;;;;;;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;IAC9BI,WAAWR,MAAC,CAACS,OAAO,GAAGL,QAAQ,CAAC;AAClC;AAEA,IAAMM,cAAcV,MAAC,CAACC,MAAM,CAAC;IAC3BU,OAAOC,iDAA2B,CAACC,QAAQ,GAAGT,QAAQ,CAAC;IACvDU,UAAUd,MAAC,CAACO,MAAM,GAAGQ,GAAG,GAAGC,QAAQ,GAAGC,GAAG,CAACnB,kBAAkBoB,OAAO,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;wBAAEA,SAAAA;oBAAQ;wBACzB+F,UAAU;;oBAGNtG,SAAiB;wBACrBN,MAAM;wBACNzB,KAAAA;wBACAG,UAAUqC;wBACVpC,UAAU2C;wBACVzC,WAAAA;oBACF;oBAEA;;wBAAO;4BACLmG,OAAO;gCACL;oCACEhF,MAAM;oCACN6G,MAAMC,KAAKhE,SAAS,CAACxC;gCACvB;;4BAEFyG,mBAAmB;gCAAEzG,QAAAA;4BAAO;wBAC9B;;;oBACOyB;;;;;;;;;oBAGL;;wBAAMiF,IAAAA,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;oBAEpCE,UAAUF,AAAK,YAALA,OAAiBoF,SAAQpF,MAAME,OAAO,GAAGqD,OAAOvD;oBAChEtB,OAAOsB,KAAK,CAAC,qCAAqC;wBAAEA,OAAOE;oBAAQ;oBAEnE,MAAM,IAAIiF,qBAAa,CAACE,yBAAiB,CAACC,aAAa,EAAE,AAAC,oCAA2C,OAARpF,UAAW;wBACtGqF,OAAOvF,AAAK,YAALA,OAAiBoF,SAAQpF,MAAMuF,KAAK,GAAG9D;oBAChD;;;;;;;IAEJ;;AAEe,SAAS1F;IACtB,OAAO;QACLyJ,MAAM;QACNnH,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 { 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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AiBoF,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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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"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { RuntimeOverrides, ServerConfig } from '../types.js';
|
|
2
2
|
export declare function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
|
|
3
|
-
httpServer: import("
|
|
3
|
+
httpServer: import("http").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>;
|
|
4
4
|
logger: import("@mcp-z/server").Logger;
|
|
5
5
|
close: () => Promise<void>;
|
|
6
6
|
}>;
|
package/dist/cjs/setup/http.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { RuntimeOverrides, ServerConfig } from '../types.js';
|
|
2
2
|
export declare function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
|
|
3
|
-
httpServer: import("
|
|
3
|
+
httpServer: import("http").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>;
|
|
4
4
|
logger: import("@mcp-z/server").Logger;
|
|
5
5
|
close: () => Promise<void>;
|
|
6
6
|
}>;
|
package/dist/cjs/setup/http.js
CHANGED
|
@@ -166,7 +166,7 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
166
166
|
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
167
167
|
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
168
168
|
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
169
|
-
if (n === "Map" || n === "Set") return Array.from(
|
|
169
|
+
if (n === "Map" || n === "Set") return Array.from(o);
|
|
170
170
|
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
171
171
|
}
|
|
172
172
|
function createHTTPServer(config, overrides) {
|
|
@@ -2,8 +2,8 @@ import type { Logger, MiddlewareLayer } from '@mcp-z/server';
|
|
|
2
2
|
import type { CommonRuntime, RuntimeOverrides, ServerConfig, StorageContext } from '../types.js';
|
|
3
3
|
import { type OAuthAdapters } from './oauth-microsoft.js';
|
|
4
4
|
export declare function createLogger(config: ServerConfig): Logger;
|
|
5
|
-
export declare function createTokenStore(baseDir: string): Promise<import("keyv").Keyv<unknown>>;
|
|
6
|
-
export declare function createDcrStore(baseDir: string, required: boolean): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
5
|
+
export declare function createTokenStore(baseDir: string, logger: Logger): Promise<import("keyv").Keyv<unknown>>;
|
|
6
|
+
export declare function createDcrStore(baseDir: string, required: boolean, logger: Logger): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
7
7
|
export declare function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer;
|
|
8
8
|
export declare function createLoggingLayer(logger: Logger): MiddlewareLayer;
|
|
9
9
|
export declare function createStorageLayer(storageContext: StorageContext): MiddlewareLayer;
|
|
@@ -2,8 +2,8 @@ import type { Logger, MiddlewareLayer } from '@mcp-z/server';
|
|
|
2
2
|
import type { CommonRuntime, RuntimeOverrides, ServerConfig, StorageContext } from '../types.js';
|
|
3
3
|
import { type OAuthAdapters } from './oauth-microsoft.js';
|
|
4
4
|
export declare function createLogger(config: ServerConfig): Logger;
|
|
5
|
-
export declare function createTokenStore(baseDir: string): Promise<import("keyv").Keyv<unknown>>;
|
|
6
|
-
export declare function createDcrStore(baseDir: string, required: boolean): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
5
|
+
export declare function createTokenStore(baseDir: string, logger: Logger): Promise<import("keyv").Keyv<unknown>>;
|
|
6
|
+
export declare function createDcrStore(baseDir: string, required: boolean, logger: Logger): Promise<import("keyv").Keyv<unknown> | undefined>;
|
|
7
7
|
export declare function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer;
|
|
8
8
|
export declare function createLoggingLayer(logger: Logger): MiddlewareLayer;
|
|
9
9
|
export declare function createStorageLayer(storageContext: StorageContext): MiddlewareLayer;
|