@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":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","Client","z","CHUNK_SIZE","MAX_BATCH_SIZE","BatchResultSchema","object","totalRequested","number","describe","successCount","failureCount","results","array","id","string","success","boolean","error","optional","inputSchema","ids","coerce","trim","min","max","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","count","length","invalidIds","includes","push","InvalidParams","join","graph","initWithMiddleware","authProvider","authContext","auth","allResults","i","chunk","slice","chunkIndex","chunkSize","totalChunks","Math","ceil","chunkResults","api","encodeURIComponent","delete","status","value","reason","processedChunkResults","map","Error","errorMessage","message","String","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,yBAAyB;AAEjD,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAA8BE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACtF,SAASC,MAAM,QAAQ,oCAAoC;AAC3D,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,EAAEC,cAAc,QAAQ,qBAAqB;AAEhE,MAAMC,oBAAoBH,EAAEI,MAAM,CAAC;IACjCC,gBAAgBL,EAAEM,MAAM,GAAGC,QAAQ,CAAC;IACpCC,cAAcR,EAAEM,MAAM,GAAGC,QAAQ,CAAC;IAClCE,cAAcT,EAAEM,MAAM,GAAGC,QAAQ,CAAC;IAClCG,SAASV,EACNW,KAAK,CACJX,EAAEI,MAAM,CAAC;QACPQ,IAAIZ,EAAEa,MAAM,GAAGN,QAAQ,CAAC;QACxBO,SAASd,EAAEe,OAAO,GAAGR,QAAQ,CAAC;QAC9BS,OAAOhB,EAAEa,MAAM,GAAGI,QAAQ,GAAGV,QAAQ,CAAC;IACxC,IAEDA,QAAQ,CAAC;AACd;AAEA,MAAMW,cAAclB,EAAEI,MAAM,CAAC;IAC3Be,KAAK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,OAAOnB,KAAK,CAAC,8BAA8B;YAAEA,OAAOqD;QAAQ;QAE5D,MAAM,IAAIxE,cAAcC,kBAAkBiF,aAAa,EAAE,CAAC,2BAA2B,EAAEV,SAAS,EAAE;YAChGW,OAAOhE,iBAAiBmD,QAAQnD,MAAMgE,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNrD;QACAG;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":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","Client","z","CHUNK_SIZE","MAX_BATCH_SIZE","BatchResultSchema","object","totalRequested","number","describe","successCount","failureCount","results","array","id","string","success","boolean","error","optional","inputSchema","ids","coerce","trim","min","max","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","allFailedError","length","some","r","failures","map","InternalError","join","handler","extra","logger","info","count","invalidIds","includes","push","InvalidParams","graph","initWithMiddleware","authProvider","authContext","auth","allResults","i","chunk","slice","chunkIndex","chunkSize","totalChunks","Math","ceil","chunkResults","api","encodeURIComponent","delete","status","value","reason","processedChunkResults","Error","errorMessage","message","String","filter","failed","chunksProcessed","content","text","JSON","stringify","structuredContent","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,yBAAyB;AAEjD,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAA8BE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACtF,SAASC,MAAM,QAAQ,oCAAoC;AAC3D,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,EAAEC,cAAc,QAAQ,qBAAqB;AAEhE,MAAMC,oBAAoBH,EAAEI,MAAM,CAAC;IACjCC,gBAAgBL,EAAEM,MAAM,GAAGC,QAAQ,CAAC;IACpCC,cAAcR,EAAEM,MAAM,GAAGC,QAAQ,CAAC;IAClCE,cAAcT,EAAEM,MAAM,GAAGC,QAAQ,CAAC;IAClCG,SAASV,EACNW,KAAK,CACJX,EAAEI,MAAM,CAAC;QACPQ,IAAIZ,EAAEa,MAAM,GAAGN,QAAQ,CAAC;QACxBO,SAASd,EAAEe,OAAO,GAAGR,QAAQ,CAAC;QAC9BS,OAAOhB,EAAEa,MAAM,GAAGI,QAAQ,GAAGV,QAAQ,CAAC;IACxC,IAEDA,QAAQ,CAAC;AACd;AAEA,MAAMW,cAAclB,EAAEI,MAAM,CAAC;IAC3Be,KAAKnB,EAAEW,K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,eAAesB;QAC9B,IAAIsB,QAAQ;YACVlC,OAAO3B,KAAK,CAAC,2CAA2C;gBAAEX,gBAAgBc,IAAIe,MAAM;YAAC;YACrF,MAAM2C;QACR;QAEA,MAAM7C,SAAiB;YACrBN,MAAM;YACNrB,gBAAgBc,IAAIe,MAAM;YAC1B1B;YACAC;YACAC,SAAS6C;QACX;QAEAZ,OAAOC,IAAI,CAAC,kCAAkC;YAC5CvC,gBAAgBc,IAAIe,MAAM;YAC1B1B;YACAC;YACAqE,iBAAiBhB,KAAKC,IAAI,CAAC5C,IAAIe,MAAM,GAAGjC;QAC1C;QAEA,OAAO;YACL8E,SAAS;gBACP;oBACErD,MAAM;oBACNsD,MAAMC,KAAKC,SAAS,CAAClD;gBACvB;aACD;YACDmD,mBAAmB;gBAAEnD;YAAO;QAC9B;IACF,EAAE,OAAOhB,OAAO;QACd,IAAIA,iBAAiBnB,eAAe,MAAMmB;QAC1C,MAAM0D,UAAU1D,iBAAiBwD,QAAQxD,MAAM0D,OAAO,GAAGC,OAAO3D;QAChE2B,OAAO3B,KAAK,CAAC,8BAA8B;YAAEA,OAAO0D;QAAQ;QAE5D,MAAM,IAAI7E,cAAcC,kBAAkByC,aAAa,EAAE,CAAC,2BAA2B,EAAEmC,SAAS,EAAE;YAChGU,OAAOpE,iBAAiBwD,QAAQxD,MAAMoE,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNzD;QACAW;IACF;AACF"}
|
|
@@ -6,7 +6,7 @@ import { Client } from '@microsoft/microsoft-graph-client';
|
|
|
6
6
|
import { z } from 'zod';
|
|
7
7
|
import { needsBody } from '../../email/querying/client-filter.js';
|
|
8
8
|
import { executeQuery as executeOutlookQuery } from '../../email/querying/execute-query.js';
|
|
9
|
-
import { OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.js';
|
|
9
|
+
import { InvalidQueryError, OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.js';
|
|
10
10
|
const inputSchema = z.object({
|
|
11
11
|
query: OutlookQueryParameterSchema.optional().describe('Structured query object or JSON string for filtering messages. Use query-syntax prompt for reference and kqlQuery for KQL syntax.'),
|
|
12
12
|
fields: createFieldsSchema({
|
|
@@ -169,6 +169,7 @@ async function handler({ query, pageSize = 50, pageToken, fields, shape = 'array
|
|
|
169
169
|
};
|
|
170
170
|
} catch (error) {
|
|
171
171
|
if (error instanceof ProtocolError) throw error;
|
|
172
|
+
if (error instanceof InvalidQueryError) throw new ProtocolError(ProtocolErrorCode.InvalidParams, error.message);
|
|
172
173
|
const message = error instanceof Error ? error.message : String(error);
|
|
173
174
|
logger.error('outlook.message.search error', {
|
|
174
175
|
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":["EMAIL_COMMON_PATTERNS","EMAIL_FIELD_DESCRIPTIONS","EMAIL_FIELDS","EmailContentTypeSchema","EmailDetailSchema","ExcludeThreadHistorySchema","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","schemas","AuthRequiredBranchSchema","createFieldsSchema","createPaginationSchema","createShapeSchema","filterFields","ProtocolError","ProtocolErrorCode","parseFields","toColumnarFormat","Client","z","needsBody","executeQuery","executeOutlookQuery","OutlookQueryParameterSchema","parseOutlookQueryParameter","inputSchema","object","query","optional","describe","fields","availableFields","fieldDescriptions","commonPatterns","resourceName","defaultPageSize","maxPageSize","provider","shape","contentType","excludeThreadHistory","successObjectsBranchSchema","type","literal","items","array","nextPageToken","string","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","description","result","handler","pageSize","pageToken","extra","logger","parsedQuery","requestedFields","needsBodyContent","includeBody","has","info","undefined","graph","initWithMiddleware","authProvider","authContext","auth","started","Date","now","exec","limit","m","message","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","fromName","name","bodyContent","body","content","isHtml","toLowerCase","mapped","id","subject","date","receivedDateTime","snippet","bodyPreview","bodyContentType","durationMs","filteredItems","item","itemsLength","length","metadata","metadataObj","text","JSON","stringify","structuredContent","error","Error","String","InternalError","stack","createTool"],"mappings":"AAAA,SAASA,qBAAqB,EAAEC,wBAAwB,EAAEC,YAAY,EAAEC,sBAAsB,EAAoBC,iBAAiB,EAAEC,0BAA0B,EAAEC,6BAA6B,EAAEC,mCAAmC,QAAQ,eAAe;AAE1P,SAASC,OAAO,QAAQ,yBAAyB;AAEjD,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,kBAAkB,EAAEC,sBAAsB,EAAEC,iBAAiB,EAAEC,YAAY,EAAEC,aAAa,EAAEC,iBAAiB,EAAEC,WAAW,EAAmBC,gBAAgB,QAAQ,gBAAgB;AACnN,SAASC,MAAM,QAAQ,oCAAoC;AAE3D,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,SAAS,QAAQ,wCAAwC;AAClE,SAASC,gBAAgBC,mBAAmB,QAAQ,wCAAwC;AAC5F,SAASC,2BAA2B,EAAEC,0BAA0B,QAAQ,wCAAwC;AAEhH,MAAMC,cAAcN,EAAEO,MAAM,CAAC;IAC3BC,OAAOJ,4BAA4BK,QAAQ,GAAGC,QAAQ,CAAC;IACvDC,QAAQpB,mBAAmB;QACzBqB,iBAAiB7B;QACjB8B,mBAAmB/B;QACnBgC,gBAAgBjC;QAChBkC,cAAc;IAChB;IACA,GAAGvB,uBAAuB;QACxBwB,iBAAiB;QACjBC,aAAa;QACb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E/C,SAAS,EAAE;YAC/FgD,OAAOJ,iBAAiBC,QAAQD,MAAMI,KAAK,GAAG5D;QAChD;IACF;AACF;AAEA,eAAe,SAAS6D;IACtB,OAAO;QACL9B,MAAM;QACN7C;QACAG;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":["EMAIL_COMMON_PATTERNS","EMAIL_FIELD_DESCRIPTIONS","EMAIL_FIELDS","EmailContentTypeSchema","EmailDetailSchema","ExcludeThreadHistorySchema","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","schemas","AuthRequiredBranchSchema","createFieldsSchema","createPaginationSchema","createShapeSchema","filterFields","ProtocolError","ProtocolErrorCode","parseFields","toColumnarFormat","Client","z","needsBody","executeQuery","executeOutlookQuery","InvalidQueryError","OutlookQueryParameterSchema","parseOutlookQueryParameter","inputSchema","object","query","optional","describe","fields","availableFields","fieldDescriptions","commonPatterns","resourceName","defaultPageSize","maxPageSize","provider","shape","contentType","excludeThreadHistory","successObjectsBranchSchema","type","literal","items","array","nextPageToken","string","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","description","result","handler","pageSize","pageToken","extra","logger","parsedQuery","requestedFields","needsBodyContent","includeBody","has","info","undefined","graph","initWithMiddleware","authProvider","authContext","auth","started","Date","now","exec","limit","m","message","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","fromName","name","bodyContent","body","content","isHtml","toLowerCase","mapped","id","subject","date","receivedDateTime","snippet","bodyPreview","bodyContentType","durationMs","filteredItems","item","itemsLength","length","metadata","metadataObj","text","JSON","stringify","structuredContent","error","InvalidParams","Error","String","InternalError","stack","createTool"],"mappings":"AAAA,SAASA,qBAAqB,EAAEC,wBAAwB,EAAEC,YAAY,EAAEC,sBAAsB,EAAoBC,iBAAiB,EAAEC,0BAA0B,EAAEC,6BAA6B,EAAEC,mCAAmC,QAAQ,eAAe;AAE1P,SAASC,OAAO,QAAQ,yBAAyB;AAEjD,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,kBAAkB,EAAEC,sBAAsB,EAAEC,iBAAiB,EAAEC,YAAY,EAAEC,aAAa,EAAEC,iBAAiB,EAAEC,WAAW,EAAmBC,gBAAgB,QAAQ,gBAAgB;AACnN,SAASC,MAAM,QAAQ,oCAAoC;AAE3D,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,SAAS,QAAQ,wCAAwC;AAClE,SAASC,gBAAgBC,mBAAmB,QAAQ,wCAAwC;AAC5F,SAASC,iBAAiB,EAAEC,2BAA2B,EAAEC,0BAA0B,QAAQ,wCAAwC;AAEnI,MAAMC,cAAcP,EAAEQ,MAAM,CAAC;IAC3BC,OAAOJ,4BAA4BK,QAAQ,GAAGC,QAAQ,CAAC;IACvDC,QAAQrB,mBAAmB;QACzBsB,iBAAiB9B;QACjB+B,mBAAmBhC;QACnBiC,gBAAgBlC;QAChBmC,cAAc;IAChB;IACA,GAAGxB,uBAAuB;QACxByB,iBAAiB;QACjBC,aAAa;QACbC,UAAU;IACZ,GAAGC,KAAK;IACRA,OAAO3B;IACP4B,aAAarC;IACbsC,sBAAsBpC;AACxB;AAEA,8CAA8C;AAC9C,MAAMqC,6BAA6BvB,EAAEQ,MAAM,CAAC;IAC1CgB,MAAMxB,EAAEyB,OAAO,CAAC;IAChBL,OAAOpB,EAAEyB,OAAO,CAAC;IACjBC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AAM;QACN7C;QACAG;IACF;AACF"}
|
|
@@ -8,7 +8,7 @@ import { createWriteStream } from 'fs';
|
|
|
8
8
|
import { unlink } from 'fs/promises';
|
|
9
9
|
import { z } from 'zod';
|
|
10
10
|
import { executeQuery as executeOutlookQuery } from '../../email/querying/execute-query.js';
|
|
11
|
-
import { OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.js';
|
|
11
|
+
import { InvalidQueryError, OutlookQueryParameterSchema, parseOutlookQueryParameter } from '../../schemas/outlook-query-schema.js';
|
|
12
12
|
const DEFAULT_PAGE_SIZE = 50;
|
|
13
13
|
const DEFAULT_MAX_ITEMS = 10000;
|
|
14
14
|
const MAX_EXPORT_ITEMS = 50000;
|
|
@@ -256,6 +256,7 @@ const config = {
|
|
|
256
256
|
});
|
|
257
257
|
}
|
|
258
258
|
if (error instanceof ProtocolError) throw error;
|
|
259
|
+
if (error instanceof InvalidQueryError) throw new ProtocolError(ProtocolErrorCode.InvalidParams, error.message);
|
|
259
260
|
const message = error instanceof Error ? error.message : String(error);
|
|
260
261
|
logger.error('outlook.messages.export-csv error', {
|
|
261
262
|
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":["EmailContentTypeSchema","ExcludeThreadHistorySchema","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","schemas","AuthRequiredBranchSchema","getFileUri","ProtocolError","ProtocolErrorCode","reserveFile","Client","stringify","createWriteStream","unlink","z","executeQuery","executeOutlookQuery","OutlookQueryParameterSchema","parseOutlookQueryParameter","DEFAULT_PAGE_SIZE","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","ExportResultSchema","object","uri","string","describe","filename","rowCount","number","truncated","boolean","inputSchema","query","optional","maxItems","int","positive","max","default","trim","min","contentType","excludeThreadHistory","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","storageContext","transport","resourceStoreUri","baseUrl","reservation","storedName","fullPath","info","path","parsedQuery","accountId","authContext","graph","initWithMiddleware","authProvider","auth","csvHeaders","writeStream","encoding","headerLine","header","quoted","quote","escape","write","totalRows","nextPageToken","started","Date","now","exec","remainingItems","pageSize","Math","undefined","pageToken","includeBody","limit","m","message","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","categories","body","content","isHtml","toLowerCase","id","String","threadId","conversationId","subject","date","receivedDateTime","snippet","bodyPreview","provider","labels","csvRows","items","item","length","rowsContent","metadata","batchSize","hasMore","Promise","resolve","reject","end","on","durationMs","endpoint","text","JSON","structuredContent","error","debug","_cleanupError","Error","InternalError","stack","createTool","name"],"mappings":"AAAA,oGAAoG,GAEpG,SAASA,sBAAsB,EAAEC,0BAA0B,EAAEC,6BAA6B,EAAEC,mCAAmC,QAAQ,eAAe;AAEtJ,SAASC,OAAO,QAAQ,yBAAyB;AAEjD,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,UAAU,EAAEC,aAAa,EAAEC,iBAAiB,EAAEC,WAAW,QAAyB,gBAAgB;AAChI,SAASC,MAAM,QAAQ,oCAAoC;AAE3D,SAASC,SAAS,QAAQ,qBAAqB;AAC/C,SAASC,iBAAiB,QAAQ,KAAK;AACvC,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,gBAAgBC,mBAAmB,QAAQ,wCAAwC;AAC5F,SAASC,2BAA2B,EAAEC,0BAA0B,QAAQ,wCAAwC;AAGhH,MAAMC,oBAAoB;AAC1B,MAAMC,oBAAoB;AAC1B,MAAMC,mBAAmB;AAEz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ACP;oBACErE,MAAM;oBACNkG,MAAMC,KAAKtI,SAAS,CAACyC;gBACvB;aACD;YACD8F,mBAAmB;gBAAE9F;YAAO;QAC9B;IACF,EAAE,OAAO+F,OAAO;QACd,+CAA+C;QAC/C,IAAI;YACF,MAAMtI,OAAOiD;YACbP,OAAO6F,KAAK,CAAC,2CAA2C;gBAAEpF,MAAMF;YAAS;QAC3E,EAAE,OAAOuF,eAAe;YACtB9F,OAAO6F,KAAK,CAAC,+CAA+C;gBAAEpF,MAAMF;YAAS;QAC/E;QAEA,IAAIqF,iBAAiB5I,eAAe,MAAM4I;QAE1C,MAAMpD,UAAUoD,iBAAiBG,QAAQH,MAAMpD,OAAO,GAAGwB,OAAO4B;QAChE5F,OAAO4F,KAAK,CAAC,qCAAqC;YAAEA,OAAOpD;QAAQ;QAEnE,MAAM,IAAIxF,cAAcC,kBAAkB+I,aAAa,EAAE,CAAC,iCAAiC,EAAExD,SAAS,EAAE;YACtGyD,OAAOL,iBAAiBG,QAAQH,MAAMK,KAAK,GAAG9D;QAChD;IACF;AACF;AAEA,eAAe,SAAS+D;IACtB,OAAO;QACLC,MAAM;QACNxG;QACAG;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":["EmailContentTypeSchema","ExcludeThreadHistorySchema","extractCurrentMessageFromHtml","extractCurrentMessageFromHtmlToText","schemas","AuthRequiredBranchSchema","getFileUri","ProtocolError","ProtocolErrorCode","reserveFile","Client","stringify","createWriteStream","unlink","z","executeQuery","executeOutlookQuery","InvalidQueryError","OutlookQueryParameterSchema","parseOutlookQueryParameter","DEFAULT_PAGE_SIZE","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","ExportResultSchema","object","uri","string","describe","filename","rowCount","number","truncated","boolean","inputSchema","query","optional","maxItems","int","positive","max","default","trim","min","contentType","excludeThreadHistory","successBranchSchema","extend","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","storageContext","transport","resourceStoreUri","baseUrl","reservation","storedName","fullPath","info","path","parsedQuery","accountId","authContext","graph","initWithMiddleware","authProvider","auth","csvHeaders","writeStream","encoding","headerLine","header","quoted","quote","escape","write","totalRows","nextPageToken","started","Date","now","exec","remainingItems","pageSize","Math","undefined","pageToken","includeBody","limit","m","message","to","Array","isArray","toRecipients","map","r","emailAddress","address","filter","Boolean","join","cc","ccRecipients","bcc","bccRecipients","fromAddr","from","categories","body","content","isHtml","toLowerCase","id","String","threadId","conversationId","subject","date","receivedDateTime","snippet","bodyPreview","provider","labels","csvRows","items","item","length","rowsContent","metadata","batchSize","hasMore","Promise","resolve","reject","end","on","durationMs","endpoint","text","JSON","structuredContent","error","debug","_cleanupError","InvalidParams","Error","InternalError","stack","createTool","name"],"mappings":"AAAA,oGAAoG,GAEpG,SAASA,sBAAsB,EAAEC,0BAA0B,EAAEC,6BAA6B,EAAEC,mCAAmC,QAAQ,eAAe;AAEtJ,SAASC,OAAO,QAAQ,yBAAyB;AAEjD,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAA8BE,UAAU,EAAEC,aAAa,EAAEC,iBAAiB,EAAEC,WAAW,QAAyB,gBAAgB;AAChI,SAASC,MAAM,QAAQ,oCAAoC;AAE3D,SAASC,SAAS,QAAQ,qBAAqB;AAC/C,SAASC,iBAAiB,QAAQ,KAAK;AACvC,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,gBAAgBC,mBAAmB,QAAQ,wCAAwC;AAC5F,SAASC,iBAAiB,EAAEC,2BAA2B,EAAEC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MAAM3F,SAAiB;YACrBN,MAAM;YACNtB;YACAG,UAAUkC;YACVjC,UAAUqD;YACVnD;QACF;QAEA,OAAO;YACLqF,SAAS;gBACP;oBACErE,MAAM;oBACNkG,MAAMC,KAAKvI,SAAS,CAAC0C;gBACvB;aACD;YACD8F,mBAAmB;gBAAE9F;YAAO;QAC9B;IACF,EAAE,OAAO+F,OAAO;QACd,+CAA+C;QAC/C,IAAI;YACF,MAAMvI,OAAOkD;YACbP,OAAO6F,KAAK,CAAC,2CAA2C;gBAAEpF,MAAMF;YAAS;QAC3E,EAAE,OAAOuF,eAAe;YACtB9F,OAAO6F,KAAK,CAAC,+CAA+C;gBAAEpF,MAAMF;YAAS;QAC/E;QAEA,IAAIqF,iBAAiB7I,eAAe,MAAM6I;QAC1C,IAAIA,iBAAiBnI,mBAAmB,MAAM,IAAIV,cAAcC,kBAAkB+I,aAAa,EAAEH,MAAMpD,OAAO;QAE9G,MAAMA,UAAUoD,iBAAiBI,QAAQJ,MAAMpD,OAAO,GAAGwB,OAAO4B;QAChE5F,OAAO4F,KAAK,CAAC,qCAAqC;YAAEA,OAAOpD;QAAQ;QAEnE,MAAM,IAAIzF,cAAcC,kBAAkBiJ,aAAa,EAAE,CAAC,iCAAiC,EAAEzD,SAAS,EAAE;YACtG0D,OAAON,iBAAiBI,QAAQJ,MAAMM,KAAK,GAAG/D;QAChD;IACF;AACF;AAEA,eAAe,SAASgE;IACtB,OAAO;QACLC,MAAM;QACNzG;QACAG;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,14 @@
|
|
|
1
1
|
import { baseEmailQueryFields, FieldOperatorSchema } 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
|
+
*/ export class InvalidQueryError extends Error {
|
|
7
|
+
constructor(message){
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'InvalidQueryError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
3
12
|
/** Zod schema for validating OutlookSystemCategory values */ export const OutlookSystemCategorySchema = z.enum([
|
|
4
13
|
'work',
|
|
5
14
|
'personal',
|
|
@@ -84,7 +93,7 @@ export function parseOutlookQueryParameter(input) {
|
|
|
84
93
|
}
|
|
85
94
|
const validated = OutlookQuerySchema.safeParse(input);
|
|
86
95
|
if (!validated.success) {
|
|
87
|
-
throw new
|
|
96
|
+
throw new InvalidQueryError(`Invalid query JSON: ${validated.error.message}. Use {"kqlQuery":"<query>"} for KQL syntax.`);
|
|
88
97
|
}
|
|
89
98
|
return validated.data;
|
|
90
99
|
}
|
|
@@ -92,7 +101,7 @@ function parseOutlookQueryString(value) {
|
|
|
92
101
|
const raw = safeJsonParse(value, 'kqlQuery');
|
|
93
102
|
const validated = OutlookQuerySchema.safeParse(raw);
|
|
94
103
|
if (!validated.success) {
|
|
95
|
-
throw new
|
|
104
|
+
throw new InvalidQueryError(`Invalid query JSON: ${validated.error.message}. Use {"kqlQuery":"<query>"} for KQL syntax.`);
|
|
96
105
|
}
|
|
97
106
|
return validated.data;
|
|
98
107
|
}
|
|
@@ -101,6 +110,6 @@ function safeJsonParse(value, rawField) {
|
|
|
101
110
|
return JSON.parse(value);
|
|
102
111
|
} catch (error) {
|
|
103
112
|
const message = error instanceof Error ? error.message : 'Invalid JSON';
|
|
104
|
-
throw new
|
|
113
|
+
throw new InvalidQueryError(`Query must be valid JSON. ${message}. Wrap KQL syntax in {"${rawField}":"<query>"} if needed.`);
|
|
105
114
|
}
|
|
106
115
|
}
|
|
@@ -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":["baseEmailQueryFields","FieldOperatorSchema","z","InvalidQueryError","Error","message","name","OutlookSystemCategorySchema","enum","OutlookQuerySchema","lazy","object","$and","array","optional","describe","$or","$not","exactPhrase","string","min","categories","union","$any","$all","$none","strict","label","importance","kqlQuery","OutlookQueryStringSchema","transform","value","ctx","parseOutlookQueryString","error","addIssue","code","ZodIssueCode","custom","NEVER","OutlookQueryParameterSchema","parseOutlookQueryParameter","input","undefined","validated","safeParse","success","data","raw","safeJsonParse","rawField","JSON","parse"],"mappings":"AAAA,SAAoCA,oBAAoB,EAAsBC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AAOwC,UAAUG,IAAI;AACvB;AAEA,SAASE,cAAclB,KAAa,EAAEmB,QAAoB;IACxD,IAAI;QACF,OAAOC,KAAKC,KAAK,CAACrB;IACpB,EAAE,OAAOG,OAAO;QACd,MAAM9B,UAAU8B,iBAAiB/B,QAAQ+B,MAAM9B,OAAO,GAAG;QACzD,MAAM,IAAIF,kBAAkB,CAAC,0BAA0B,EAAEE,QAAQ,uBAAuB,EAAE8C,SAAS,uBAAuB,CAAC;IAC7H;AACF"}
|
package/dist/esm/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
|
}>;
|
|
@@ -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;
|
|
@@ -22,14 +22,14 @@ export function createLogger(config) {
|
|
|
22
22
|
sync: false
|
|
23
23
|
}) : pino.destination(1));
|
|
24
24
|
}
|
|
25
|
-
export async function createTokenStore(baseDir) {
|
|
25
|
+
export async function createTokenStore(baseDir, logger) {
|
|
26
26
|
const tokenStoreUri = process.env.TOKEN_STORE_URI || pathToFileURL(path.join(baseDir, 'tokens.json')).href;
|
|
27
|
-
return createStore(tokenStoreUri);
|
|
27
|
+
return createStore(tokenStoreUri, logger);
|
|
28
28
|
}
|
|
29
|
-
export async function createDcrStore(baseDir, required) {
|
|
29
|
+
export async function createDcrStore(baseDir, required, logger) {
|
|
30
30
|
if (!required) return undefined;
|
|
31
31
|
const dcrStoreUri = process.env.DCR_STORE_URI || pathToFileURL(path.join(baseDir, 'dcr.json')).href;
|
|
32
|
-
return createStore(dcrStoreUri);
|
|
32
|
+
return createStore(dcrStoreUri, logger);
|
|
33
33
|
}
|
|
34
34
|
export function createAuthLayer(authMiddleware) {
|
|
35
35
|
return {
|
|
@@ -84,9 +84,9 @@ export async function createDefaultRuntime(config, overrides) {
|
|
|
84
84
|
if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');
|
|
85
85
|
const logger = createLogger(config);
|
|
86
86
|
validateStorageConfig(config, logger);
|
|
87
|
-
const tokenStore = await createTokenStore(config.baseDir);
|
|
87
|
+
const tokenStore = await createTokenStore(config.baseDir, logger);
|
|
88
88
|
const baseUrl = (_config_baseUrl = config.baseUrl) !== null && _config_baseUrl !== void 0 ? _config_baseUrl : config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined;
|
|
89
|
-
const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr');
|
|
89
|
+
const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr', logger);
|
|
90
90
|
const oauthAdapters = await createOAuthAdapters(config, {
|
|
91
91
|
logger,
|
|
92
92
|
tokenStore,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/runtime.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url';\nimport { sanitizeForLoggingFormatter } from '@mcp-z/oauth';\nimport type { Logger, MiddlewareLayer } from '@mcp-z/server';\nimport { createLoggingMiddleware } from '@mcp-z/server';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport pino from 'pino';\nimport createStore from '../lib/create-store.ts';\nimport * as mcp from '../mcp/index.ts';\nimport type { CommonRuntime, RuntimeDeps, RuntimeOverrides, ServerConfig, StorageContext } from '../types.ts';\nimport { createOAuthAdapters, type OAuthAdapters } from './oauth-microsoft.ts';\n\nexport function createLogger(config: ServerConfig): Logger {\n const hasStdio = config.transport.type === 'stdio';\n const logsPath = path.join(config.baseDir, 'logs', `${config.name}.log`);\n if (hasStdio) fs.mkdirSync(path.dirname(logsPath), { recursive: true });\n return pino({ level: config.logLevel ?? 'info', formatters: sanitizeForLoggingFormatter() }, hasStdio ? pino.destination({ dest: logsPath, sync: false }) : pino.destination(1));\n}\n\nexport async function createTokenStore(baseDir: string) {\n const tokenStoreUri = process.env.TOKEN_STORE_URI || pathToFileURL(path.join(baseDir, 'tokens.json')).href;\n return createStore<unknown>(tokenStoreUri);\n}\n\nexport async function createDcrStore(baseDir: string, required: boolean) {\n if (!required) return undefined;\n const dcrStoreUri = process.env.DCR_STORE_URI || pathToFileURL(path.join(baseDir, 'dcr.json')).href;\n return createStore<unknown>(dcrStoreUri);\n}\n\nexport function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer {\n return {\n withTool: authMiddleware.withToolAuth,\n withResource: authMiddleware.withResourceAuth,\n withPrompt: authMiddleware.withPromptAuth,\n };\n}\n\nexport function createLoggingLayer(logger: Logger): MiddlewareLayer {\n const logging = createLoggingMiddleware({ logger });\n return {\n withTool: logging.withToolLogging,\n withResource: logging.withResourceLogging,\n withPrompt: logging.withPromptLogging,\n };\n}\n\nexport function createStorageLayer(storageContext: StorageContext): MiddlewareLayer {\n const wrapAtPosition = <T extends { name: string; handler: unknown; [key: string]: unknown }>(module: T, extraPosition: number): T => {\n const originalHandler = module.handler as (...args: unknown[]) => Promise<unknown>;\n\n const wrappedHandler = async (...allArgs: unknown[]) => {\n const extra = allArgs[extraPosition];\n (extra as { storageContext?: StorageContext }).storageContext = storageContext;\n return await originalHandler(...allArgs);\n };\n\n return {\n ...module,\n handler: wrappedHandler,\n } as T;\n };\n\n return {\n withTool: <T extends { name: string; config: unknown; handler: unknown }>(module: T): T => wrapAtPosition(module, 1) as T,\n };\n}\n\nexport function validateStorageConfig(config: ServerConfig, logger: Logger) {\n if (config.auth === 'dcr') {\n if (config.resourceStoreUri) {\n logger.warn('DCR mode does not support file storage; resourceStoreUri will be ignored.');\n }\n return;\n }\n if (!config.resourceStoreUri) {\n throw new Error('outlook-messages-export-csv: Server configuration missing resourceStoreUri.');\n }\n if (config.transport.type === 'http' && !config.baseUrl && !config.transport.port) {\n throw new Error('outlook-messages-export-csv: HTTP transport requires either baseUrl in server config or port in transport config. This is a server configuration error - please provide --base-url or --port.');\n }\n}\n\nexport async function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime> {\n if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');\n\n const logger = createLogger(config);\n validateStorageConfig(config, logger);\n const tokenStore = await createTokenStore(config.baseDir);\n const baseUrl = config.baseUrl ?? (config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined);\n const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr');\n const oauthAdapters = await createOAuthAdapters(config, { logger, tokenStore, dcrStore }, baseUrl);\n const deps: RuntimeDeps = { config, logger, tokenStore, oauthAdapters, baseUrl };\n const createDomainModules =\n overrides?.createDomainModules ??\n (() => ({\n tools: Object.values(mcp.toolFactories).map((factory) => factory()),\n resources: Object.values(mcp.resourceFactories).map((factory) => factory()),\n prompts: Object.values(mcp.promptFactories).map((factory) => factory()),\n }));\n const middlewareFactories = overrides?.middlewareFactories ?? [() => createAuthLayer(oauthAdapters.middleware), () => createLoggingLayer(logger), ...(config.auth === 'dcr' ? [] : [() => createStorageLayer({ resourceStoreUri: config.resourceStoreUri, baseUrl: config.baseUrl, transport: config.transport })])];\n\n return {\n deps,\n middlewareFactories,\n createDomainModules,\n close: async () => {},\n };\n}\n"],"names":["pathToFileURL","sanitizeForLoggingFormatter","createLoggingMiddleware","fs","path","pino","createStore","mcp","createOAuthAdapters","createLogger","config","hasStdio","transport","type","logsPath","join","baseDir","name","mkdirSync","dirname","recursive","level","logLevel","formatters","destination","dest","sync","createTokenStore","tokenStoreUri","process","env","TOKEN_STORE_URI","href","createDcrStore","required","undefined","dcrStoreUri","DCR_STORE_URI","createAuthLayer","authMiddleware","withTool","withToolAuth","withResource","withResourceAuth","withPrompt","withPromptAuth","createLoggingLayer","
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/runtime.ts"],"sourcesContent":["import { pathToFileURL } from 'node:url';\nimport { sanitizeForLoggingFormatter } from '@mcp-z/oauth';\nimport type { Logger, MiddlewareLayer } from '@mcp-z/server';\nimport { createLoggingMiddleware } from '@mcp-z/server';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport pino from 'pino';\nimport createStore from '../lib/create-store.ts';\nimport * as mcp from '../mcp/index.ts';\nimport type { CommonRuntime, RuntimeDeps, RuntimeOverrides, ServerConfig, StorageContext } from '../types.ts';\nimport { createOAuthAdapters, type OAuthAdapters } from './oauth-microsoft.ts';\n\nexport function createLogger(config: ServerConfig): Logger {\n const hasStdio = config.transport.type === 'stdio';\n const logsPath = path.join(config.baseDir, 'logs', `${config.name}.log`);\n if (hasStdio) fs.mkdirSync(path.dirname(logsPath), { recursive: true });\n return pino({ level: config.logLevel ?? 'info', formatters: sanitizeForLoggingFormatter() }, hasStdio ? pino.destination({ dest: logsPath, sync: false }) : pino.destination(1));\n}\n\nexport async function createTokenStore(baseDir: string, logger: Logger) {\n const tokenStoreUri = process.env.TOKEN_STORE_URI || pathToFileURL(path.join(baseDir, 'tokens.json')).href;\n return createStore<unknown>(tokenStoreUri, logger);\n}\n\nexport async function createDcrStore(baseDir: string, required: boolean, logger: Logger) {\n if (!required) return undefined;\n const dcrStoreUri = process.env.DCR_STORE_URI || pathToFileURL(path.join(baseDir, 'dcr.json')).href;\n return createStore<unknown>(dcrStoreUri, logger);\n}\n\nexport function createAuthLayer(authMiddleware: OAuthAdapters['middleware']): MiddlewareLayer {\n return {\n withTool: authMiddleware.withToolAuth,\n withResource: authMiddleware.withResourceAuth,\n withPrompt: authMiddleware.withPromptAuth,\n };\n}\n\nexport function createLoggingLayer(logger: Logger): MiddlewareLayer {\n const logging = createLoggingMiddleware({ logger });\n return {\n withTool: logging.withToolLogging,\n withResource: logging.withResourceLogging,\n withPrompt: logging.withPromptLogging,\n };\n}\n\nexport function createStorageLayer(storageContext: StorageContext): MiddlewareLayer {\n const wrapAtPosition = <T extends { name: string; handler: unknown; [key: string]: unknown }>(module: T, extraPosition: number): T => {\n const originalHandler = module.handler as (...args: unknown[]) => Promise<unknown>;\n\n const wrappedHandler = async (...allArgs: unknown[]) => {\n const extra = allArgs[extraPosition];\n (extra as { storageContext?: StorageContext }).storageContext = storageContext;\n return await originalHandler(...allArgs);\n };\n\n return {\n ...module,\n handler: wrappedHandler,\n } as T;\n };\n\n return {\n withTool: <T extends { name: string; config: unknown; handler: unknown }>(module: T): T => wrapAtPosition(module, 1) as T,\n };\n}\n\nexport function validateStorageConfig(config: ServerConfig, logger: Logger) {\n if (config.auth === 'dcr') {\n if (config.resourceStoreUri) {\n logger.warn('DCR mode does not support file storage; resourceStoreUri will be ignored.');\n }\n return;\n }\n if (!config.resourceStoreUri) {\n throw new Error('outlook-messages-export-csv: Server configuration missing resourceStoreUri.');\n }\n if (config.transport.type === 'http' && !config.baseUrl && !config.transport.port) {\n throw new Error('outlook-messages-export-csv: HTTP transport requires either baseUrl in server config or port in transport config. This is a server configuration error - please provide --base-url or --port.');\n }\n}\n\nexport async function createDefaultRuntime(config: ServerConfig, overrides?: RuntimeOverrides): Promise<CommonRuntime> {\n if (config.auth === 'dcr' && config.transport.type !== 'http') throw new Error('DCR mode requires an HTTP transport');\n\n const logger = createLogger(config);\n validateStorageConfig(config, logger);\n const tokenStore = await createTokenStore(config.baseDir, logger);\n const baseUrl = config.baseUrl ?? (config.transport.type === 'http' && config.transport.port ? `http://localhost:${config.transport.port}` : undefined);\n const dcrStore = await createDcrStore(config.baseDir, config.auth === 'dcr', logger);\n const oauthAdapters = await createOAuthAdapters(config, { logger, tokenStore, dcrStore }, baseUrl);\n const deps: RuntimeDeps = { config, logger, tokenStore, oauthAdapters, baseUrl };\n const createDomainModules =\n overrides?.createDomainModules ??\n (() => ({\n tools: Object.values(mcp.toolFactories).map((factory) => factory()),\n resources: Object.values(mcp.resourceFactories).map((factory) => factory()),\n prompts: Object.values(mcp.promptFactories).map((factory) => factory()),\n }));\n const middlewareFactories = overrides?.middlewareFactories ?? [() => createAuthLayer(oauthAdapters.middleware), () => createLoggingLayer(logger), ...(config.auth === 'dcr' ? [] : [() => createStorageLayer({ resourceStoreUri: config.resourceStoreUri, baseUrl: config.baseUrl, transport: config.transport })])];\n\n return {\n deps,\n middlewareFactories,\n createDomainModules,\n close: async () => {},\n };\n}\n"],"names":["pathToFileURL","sanitizeForLoggingFormatter","createLoggingMiddleware","fs","path","pino","createStore","mcp","createOAuthAdapters","createLogger","config","hasStdio","transport","type","logsPath","join","baseDir","name","mkdirSync","dirname","recursive","level","logLevel","formatters","destination","dest","sync","createTokenStore","logger","tokenStoreUri","process","env","TOKEN_STORE_URI","href","createDcrStore","required","undefined","dcrStoreUri","DCR_STORE_URI","createAuthLayer","authMiddleware","withTool","withToolAuth","withResource","withResourceAuth","withPrompt","withPromptAuth","createLoggingLayer","logging","withToolLogging","withResourceLogging","withPromptLogging","createStorageLayer","storageContext","wrapAtPosition","module","extraPosition","originalHandler","handler","wrappedHandler","allArgs","extra","validateStorageConfig","auth","resourceStoreUri","warn","Error","baseUrl","port","createDefaultRuntime","overrides","tokenStore","dcrStore","oauthAdapters","deps","createDomainModules","tools","Object","values","toolFactories","map","factory","resources","resourceFactories","prompts","promptFactories","middlewareFactories","middleware","close"],"mappings":"AAAA,SAASA,aAAa,QAAQ,WAAW;AACzC,SAASC,2BAA2B,QAAQ,eAAe;AAE3D,SAASC,uBAAuB,QAAQ,gBAAgB;AACxD,YAAYC,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAC7B,OAAOC,UAAU,OAAO;AACxB,OAAOC,iBAAiB,yBAAyB;AACjD,YAAYC,SAAS,kBAAkB;AAEvC,SAASC,mBAAmB,QAA4B,uBAAuB;AAE/E,OAAO,SAASC,aAAaC,MAAoB;QAI1BA;IAHrB,MAAMC,WAAWD,OAAOE,SAAS,CAACC,IAAI,KAAK;IAC3C,MAAMC,WAAWV,KAAKW,IAAI,CAACL,OAAOM,OAAO,EAAE,QAAQ,GAAGN,OAAOO,IAAI,CAAC,IAAI,CAAC;IACvE,IAAIN,UAAUR,GAAGe,SAAS,CAACd,KAAKe,OAAO,CAACL,WAAW;QAAEM,WAAW;IAAK;IACrE,OAAOf,KAAK;QAAEgB,KAAK,GAAEX,mBAAAA,OAAOY,QAAQ,cAAfZ,8BAAAA,mBAAmB;QAAQa,YAAYtB;IAA8B,GAAGU,WAAWN,KAAKmB,WAAW,CAAC;QAAEC,MAAMX;QAAUY,MAAM;IAAM,KAAKrB,KAAKmB,WAAW,CAAC;AAC/K;AAEA,OAAO,eAAeG,iBAAiBX,OAAe,EAAEY,MAAc;IACpE,MAAMC,gBAAgBC,QAAQC,GAAG,CAACC,eAAe,IAAIhC,cAAcI,KAAKW,IAAI,CAACC,SAAS,gBAAgBiB,IAAI;IAC1G,OAAO3B,YAAqBuB,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gB,mBAAmB,yCAAI;QAAC,IAAM/C,gBAAgBkC,cAAcc,UAAU;QAAG,IAAMxC,mBAAmBnB;WAAalB,OAAOqD,IAAI,KAAK,QAAQ,EAAE,GAAG;YAAC,IAAMX,mBAAmB;oBAAEY,kBAAkBtD,OAAOsD,gBAAgB;oBAAEG,SAASzD,OAAOyD,OAAO;oBAAEvD,WAAWF,OAAOE,SAAS;gBAAC;SAAG;KAAE;IAEpT,OAAO;QACL8D;QACAY;QACAX;QACAa,OAAO,WAAa;IACtB;AACF"}
|
|
@@ -55,7 +55,7 @@ Storage Backends:
|
|
|
55
55
|
TOKEN_STORE_URI and DCR_STORE_URI accept any keyv-registry protocol.
|
|
56
56
|
file:// (the default) and memory:// work out of the box. Any other backend
|
|
57
57
|
needs its adapter installed alongside this server:
|
|
58
|
-
npm install -g @keyv/redis
|
|
58
|
+
npm install -g @keyv/redis@6
|
|
59
59
|
TOKEN_STORE_URI=redis://localhost:6379 mcp-outlook
|
|
60
60
|
|
|
61
61
|
OAuth Scopes:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/version-help.ts"],"sourcesContent":["import * as fs from 'fs';\nimport moduleRoot from 'module-root-sync';\nimport * as path from 'path';\nimport * as url from 'url';\nimport { parseArgs } from 'util';\n\n// Kept dependency-free (fs/path/url/module-root-sync only) so `--version`/`--help`\n// resolve nothing beyond Node startup: config.ts's parseConfig pulls in @mcp-z/oauth-microsoft\n// and @mcp-z/server, which this path must not touch.\nconst pkg = JSON.parse(fs.readFileSync(path.join(moduleRoot(url.fileURLToPath(import.meta.url)), 'package.json'), 'utf-8'));\n\nconst HELP_TEXT = `\nUsage: mcp-outlook [options]\n\nMCP server for Outlook/Microsoft email management with OAuth authentication.\n\nOptions:\n --version Show version number\n --help Show this help message\n --auth=<mode> Authentication mode (default: loopback-oauth)\n Modes: loopback-oauth, device-code, dcr\n --headless Disable browser auto-open, return auth URL instead\n --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)\n --dcr-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)\n --dcr-verify-url=<url> External verification endpoint (required for external mode)\n --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)\n --port=<port> Enable HTTP transport on specified port\n --stdio Enable stdio transport (default if no port)\n --log-level=<level> Logging level (default: info)\n --resource-store-uri=<uri> Resource store URI for CSV file storage (default: file://~/.mcp-z/mcp-outlook/files)\n --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)\n\nEnvironment Variables:\n MS_CLIENT_ID OAuth client ID (REQUIRED)\n MS_TENANT_ID Microsoft tenant ID (REQUIRED)\n MS_CLIENT_SECRET OAuth client secret (optional)\n AUTH_MODE Default authentication mode (optional)\n HEADLESS Disable browser auto-open (optional)\n DCR_MODE DCR mode (optional, same format as --dcr-mode)\n DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)\n DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n TOKEN_STORE_URI Token storage URI (optional)\n PORT Default HTTP port (optional)\n LOG_LEVEL Default logging level (optional)\n RESOURCE_STORE_URI Resource store URI (optional, file://)\n BASE_URL Base URL for HTTP file serving (optional)\n\nConfiguration Files:\n Variables may also be set in the first of these files that exists:\n 1. .mcp-z/mcp-outlook/.env beside the nearest .mcp.json (else ~/.mcp-z/mcp-outlook/.env)\n 2. ~/.config/mcp-z/mcp-outlook/.env (~ is your home directory, on every OS)\n Values already in the environment, including .mcp.json \"env\", take precedence.\n On macOS and Linux the file must be private (chmod 600), or the server will not start.\n\nStorage Backends:\n TOKEN_STORE_URI and DCR_STORE_URI accept any keyv-registry protocol.\n file:// (the default) and memory:// work out of the box. Any other backend\n needs its adapter installed alongside this server:\n npm install -g @keyv/redis\n TOKEN_STORE_URI=redis://localhost:6379 mcp-outlook\n\nOAuth Scopes:\n openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite\n\nExamples:\n mcp-outlook # Use default settings\n mcp-outlook --auth=device-code # Use device code auth\n mcp-outlook --port=3000 # HTTP transport on port 3000\n mcp-outlook --tenant-id=xxx # Set tenant ID\n mcp-outlook --resource-store-uri=file:///tmp/emails # Custom resource store URI\n MS_CLIENT_ID=xxx mcp-outlook # Set client ID via env var\n`.trim();\n\n/** Package metadata read from package.json, resolved relative to this file. */\nexport function readPkg(): { name: string; version: string; repository?: string | { url?: string } } {\n return pkg;\n}\n\n/**\n * Handle --version/--help flags before config parsing.\n * These must work without requiring any configuration or heavy dependency.\n */\nexport function handleVersionHelp(args: string[]): { handled: boolean; output?: string } {\n const { values } = parseArgs({\n args,\n options: {\n version: { type: 'boolean', short: 'v' },\n help: { type: 'boolean', short: 'h' },\n },\n strict: false,\n allowPositionals: true,\n });\n\n if (values.version) return { handled: true, output: pkg.version };\n if (values.help) return { handled: true, output: HELP_TEXT };\n return { handled: false };\n}\n"],"names":["fs","moduleRoot","path","url","parseArgs","pkg","JSON","parse","readFileSync","join","fileURLToPath","HELP_TEXT","trim","readPkg","handleVersionHelp","args","values","options","version","type","short","help","strict","allowPositionals","handled","output"],"mappings":"AAAA,YAAYA,QAAQ,KAAK;AACzB,OAAOC,gBAAgB,mBAAmB;AAC1C,YAAYC,UAAU,OAAO;AAC7B,YAAYC,SAAS,MAAM;AAC3B,SAASC,SAAS,QAAQ,OAAO;AAEjC,mFAAmF;AACnF,+FAA+F;AAC/F,qDAAqD;AACrD,MAAMC,MAAMC,KAAKC,KAAK,CAACP,GAAGQ,YAAY,CAACN,KAAKO,IAAI,CAACR,WAAWE,IAAIO,aAAa,CAAC,YAAYP,GAAG,IAAI,iBAAiB;AAElH,MAAMQ,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DnB,CAAC,CAACC,IAAI;AAEN,6EAA6E,GAC7E,OAAO,SAASC;IACd,OAAOR;AACT;AAEA;;;CAGC,GACD,OAAO,SAASS,kBAAkBC,IAAc;IAC9C,MAAM,EAAEC,MAAM,EAAE,GAAGZ,UAAU;QAC3BW;QACAE,SAAS;YACPC,SAAS;gBAAEC,MAAM;gBAAWC,OAAO;YAAI;YACvCC,MAAM;gBAAEF,MAAM;gBAAWC,OAAO;YAAI;QACtC;QACAE,QAAQ;QACRC,kBAAkB;IACpB;IAEA,IAAIP,OAAOE,OAAO,EAAE,OAAO;QAAEM,SAAS;QAAMC,QAAQpB,IAAIa,OAAO;IAAC;IAChE,IAAIF,OAAOK,IAAI,EAAE,OAAO;QAAEG,SAAS;QAAMC,QAAQd;IAAU;IAC3D,OAAO;QAAEa,SAAS;IAAM;AAC1B"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/open-source/ai/mcp-z/mcp-outlook/src/setup/version-help.ts"],"sourcesContent":["import * as fs from 'fs';\nimport moduleRoot from 'module-root-sync';\nimport * as path from 'path';\nimport * as url from 'url';\nimport { parseArgs } from 'util';\n\n// Kept dependency-free (fs/path/url/module-root-sync only) so `--version`/`--help`\n// resolve nothing beyond Node startup: config.ts's parseConfig pulls in @mcp-z/oauth-microsoft\n// and @mcp-z/server, which this path must not touch.\nconst pkg = JSON.parse(fs.readFileSync(path.join(moduleRoot(url.fileURLToPath(import.meta.url)), 'package.json'), 'utf-8'));\n\nconst HELP_TEXT = `\nUsage: mcp-outlook [options]\n\nMCP server for Outlook/Microsoft email management with OAuth authentication.\n\nOptions:\n --version Show version number\n --help Show this help message\n --auth=<mode> Authentication mode (default: loopback-oauth)\n Modes: loopback-oauth, device-code, dcr\n --headless Disable browser auto-open, return auth URL instead\n --redirect-uri=<uri> OAuth redirect URI (default: ephemeral loopback)\n --tenant-id=<id> Microsoft tenant ID (overrides MS_TENANT_ID env var)\n --dcr-mode=<mode> DCR mode (self-hosted or external, default: self-hosted)\n --dcr-verify-url=<url> External verification endpoint (required for external mode)\n --dcr-store-uri=<uri> DCR client storage URI (required for self-hosted mode)\n --port=<port> Enable HTTP transport on specified port\n --stdio Enable stdio transport (default if no port)\n --log-level=<level> Logging level (default: info)\n --resource-store-uri=<uri> Resource store URI for CSV file storage (default: file://~/.mcp-z/mcp-outlook/files)\n --base-url=<url> Base URL for HTTP file serving (default: http://localhost for HTTP transports)\n\nEnvironment Variables:\n MS_CLIENT_ID OAuth client ID (REQUIRED)\n MS_TENANT_ID Microsoft tenant ID (REQUIRED)\n MS_CLIENT_SECRET OAuth client secret (optional)\n AUTH_MODE Default authentication mode (optional)\n HEADLESS Disable browser auto-open (optional)\n DCR_MODE DCR mode (optional, same format as --dcr-mode)\n DCR_VERIFY_URL External verification URL (optional, same as --dcr-verify-url)\n DCR_STORE_URI DCR storage URI (optional, same as --dcr-store-uri)\n TOKEN_STORE_URI Token storage URI (optional)\n PORT Default HTTP port (optional)\n LOG_LEVEL Default logging level (optional)\n RESOURCE_STORE_URI Resource store URI (optional, file://)\n BASE_URL Base URL for HTTP file serving (optional)\n\nConfiguration Files:\n Variables may also be set in the first of these files that exists:\n 1. .mcp-z/mcp-outlook/.env beside the nearest .mcp.json (else ~/.mcp-z/mcp-outlook/.env)\n 2. ~/.config/mcp-z/mcp-outlook/.env (~ is your home directory, on every OS)\n Values already in the environment, including .mcp.json \"env\", take precedence.\n On macOS and Linux the file must be private (chmod 600), or the server will not start.\n\nStorage Backends:\n TOKEN_STORE_URI and DCR_STORE_URI accept any keyv-registry protocol.\n file:// (the default) and memory:// work out of the box. Any other backend\n needs its adapter installed alongside this server:\n npm install -g @keyv/redis@6\n TOKEN_STORE_URI=redis://localhost:6379 mcp-outlook\n\nOAuth Scopes:\n openid profile offline_access https://graph.microsoft.com/User.Read https://graph.microsoft.com/Mail.ReadWrite https://graph.microsoft.com/Mail.Send https://graph.microsoft.com/MailboxSettings.ReadWrite\n\nExamples:\n mcp-outlook # Use default settings\n mcp-outlook --auth=device-code # Use device code auth\n mcp-outlook --port=3000 # HTTP transport on port 3000\n mcp-outlook --tenant-id=xxx # Set tenant ID\n mcp-outlook --resource-store-uri=file:///tmp/emails # Custom resource store URI\n MS_CLIENT_ID=xxx mcp-outlook # Set client ID via env var\n`.trim();\n\n/** Package metadata read from package.json, resolved relative to this file. */\nexport function readPkg(): { name: string; version: string; repository?: string | { url?: string } } {\n return pkg;\n}\n\n/**\n * Handle --version/--help flags before config parsing.\n * These must work without requiring any configuration or heavy dependency.\n */\nexport function handleVersionHelp(args: string[]): { handled: boolean; output?: string } {\n const { values } = parseArgs({\n args,\n options: {\n version: { type: 'boolean', short: 'v' },\n help: { type: 'boolean', short: 'h' },\n },\n strict: false,\n allowPositionals: true,\n });\n\n if (values.version) return { handled: true, output: pkg.version };\n if (values.help) return { handled: true, output: HELP_TEXT };\n return { handled: false };\n}\n"],"names":["fs","moduleRoot","path","url","parseArgs","pkg","JSON","parse","readFileSync","join","fileURLToPath","HELP_TEXT","trim","readPkg","handleVersionHelp","args","values","options","version","type","short","help","strict","allowPositionals","handled","output"],"mappings":"AAAA,YAAYA,QAAQ,KAAK;AACzB,OAAOC,gBAAgB,mBAAmB;AAC1C,YAAYC,UAAU,OAAO;AAC7B,YAAYC,SAAS,MAAM;AAC3B,SAASC,SAAS,QAAQ,OAAO;AAEjC,mFAAmF;AACnF,+FAA+F;AAC/F,qDAAqD;AACrD,MAAMC,MAAMC,KAAKC,KAAK,CAACP,GAAGQ,YAAY,CAACN,KAAKO,IAAI,CAACR,WAAWE,IAAIO,aAAa,CAAC,YAAYP,GAAG,IAAI,iBAAiB;AAElH,MAAMQ,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DnB,CAAC,CAACC,IAAI;AAEN,6EAA6E,GAC7E,OAAO,SAASC;IACd,OAAOR;AACT;AAEA;;;CAGC,GACD,OAAO,SAASS,kBAAkBC,IAAc;IAC9C,MAAM,EAAEC,MAAM,EAAE,GAAGZ,UAAU;QAC3BW;QACAE,SAAS;YACPC,SAAS;gBAAEC,MAAM;gBAAWC,OAAO;YAAI;YACvCC,MAAM;gBAAEF,MAAM;gBAAWC,OAAO;YAAI;QACtC;QACAE,QAAQ;QACRC,kBAAkB;IACpB;IAEA,IAAIP,OAAOE,OAAO,EAAE,OAAO;QAAEM,SAAS;QAAMC,QAAQpB,IAAIa,OAAO;IAAC;IAChE,IAAIF,OAAOK,IAAI,EAAE,OAAO;QAAEG,SAAS;QAAMC,QAAQd;IAAU;IAC3D,OAAO;QAAEa,SAAS;IAAM;AAC1B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcp-z/mcp-outlook",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.4.1",
|
|
4
4
|
"description": "MCP server for Outlook integration with OAuth authentication, message search, and batch operations",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"outlook",
|
|
@@ -71,8 +71,8 @@
|
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
73
|
"@mcp-z/email": "^1.0.0",
|
|
74
|
-
"@mcp-z/oauth": "^2.
|
|
75
|
-
"@mcp-z/oauth-microsoft": "^2.
|
|
74
|
+
"@mcp-z/oauth": "^2.2.0",
|
|
75
|
+
"@mcp-z/oauth-microsoft": "^2.4.0",
|
|
76
76
|
"@mcp-z/server": "^2.3.0",
|
|
77
77
|
"@microsoft/microsoft-graph-client": "^3.0.0",
|
|
78
78
|
"@microsoft/microsoft-graph-types": "^2.0.0",
|
|
@@ -80,21 +80,21 @@
|
|
|
80
80
|
"csv-stringify": "^6.0.0",
|
|
81
81
|
"express": "^5.0.0",
|
|
82
82
|
"keyv-file": "5.3.3",
|
|
83
|
-
"keyv-registry": "^
|
|
83
|
+
"keyv-registry": "^3.0.0",
|
|
84
84
|
"module-root-sync": "^2.0.0",
|
|
85
85
|
"pino": "^10.0.0",
|
|
86
86
|
"zod": "^4.2.0"
|
|
87
87
|
},
|
|
88
88
|
"devDependencies": {
|
|
89
|
-
"@mcp-z/client": "^2.
|
|
89
|
+
"@mcp-z/client": "^2.5.0",
|
|
90
90
|
"@modelcontextprotocol/sdk": "^1.10.0",
|
|
91
91
|
"@types/cors": "^2.8.19",
|
|
92
92
|
"@types/express": "^5.0.6",
|
|
93
93
|
"@types/mocha": "^10.0.10",
|
|
94
|
-
"@types/node": "^
|
|
94
|
+
"@types/node": "^22",
|
|
95
95
|
"fs-remove-compat": "^1.0.4",
|
|
96
96
|
"get-port": "5.1.1",
|
|
97
|
-
"keyv": "^
|
|
97
|
+
"keyv": "^6.1.0",
|
|
98
98
|
"node-version-use": "^2.4.7",
|
|
99
99
|
"portable-env": "^1.4.0",
|
|
100
100
|
"ts-dev-stack": "^1.22.1",
|