@mcp-z/mcp-gmail 1.1.3 → 2.0.0
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/dist/cjs/index.js.map +1 -1
- package/dist/cjs/mcp/prompts/draft-email.d.cts +2 -3
- package/dist/cjs/mcp/prompts/draft-email.d.ts +2 -3
- package/dist/cjs/mcp/prompts/draft-email.js.map +1 -1
- package/dist/cjs/mcp/prompts/query-syntax.d.cts +2 -3
- package/dist/cjs/mcp/prompts/query-syntax.d.ts +2 -3
- package/dist/cjs/mcp/prompts/query-syntax.js.map +1 -1
- package/dist/cjs/mcp/resources/email.d.cts +6 -5
- package/dist/cjs/mcp/resources/email.d.ts +6 -5
- package/dist/cjs/mcp/resources/email.js +2 -2
- package/dist/cjs/mcp/resources/email.js.map +1 -1
- package/dist/cjs/mcp/tools/categories-list.js +2 -2
- package/dist/cjs/mcp/tools/categories-list.js.map +1 -1
- package/dist/cjs/mcp/tools/label-add.js +3 -3
- package/dist/cjs/mcp/tools/label-add.js.map +1 -1
- package/dist/cjs/mcp/tools/label-delete.js +6 -6
- package/dist/cjs/mcp/tools/label-delete.js.map +1 -1
- package/dist/cjs/mcp/tools/labels-list.d.cts +3 -3
- package/dist/cjs/mcp/tools/labels-list.d.ts +3 -3
- package/dist/cjs/mcp/tools/labels-list.js +2 -2
- package/dist/cjs/mcp/tools/labels-list.js.map +1 -1
- package/dist/cjs/mcp/tools/message-get.js +3 -4
- package/dist/cjs/mcp/tools/message-get.js.map +1 -1
- package/dist/cjs/mcp/tools/message-mark-read.js +3 -3
- package/dist/cjs/mcp/tools/message-mark-read.js.map +1 -1
- package/dist/cjs/mcp/tools/message-move-to-trash.js +6 -6
- package/dist/cjs/mcp/tools/message-move-to-trash.js.map +1 -1
- package/dist/cjs/mcp/tools/message-respond.js +4 -4
- package/dist/cjs/mcp/tools/message-respond.js.map +1 -1
- package/dist/cjs/mcp/tools/message-search.js +2 -3
- package/dist/cjs/mcp/tools/message-search.js.map +1 -1
- package/dist/cjs/mcp/tools/message-send.js +3 -3
- package/dist/cjs/mcp/tools/message-send.js.map +1 -1
- package/dist/cjs/mcp/tools/messages-export-csv.js +1 -2
- package/dist/cjs/mcp/tools/messages-export-csv.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 -2
- package/dist/cjs/setup/http.js.map +1 -1
- package/dist/cjs/setup/stdio.d.cts +1 -1
- package/dist/cjs/setup/stdio.d.ts +1 -1
- package/dist/cjs/setup/stdio.js +1 -2
- package/dist/cjs/setup/stdio.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/mcp/prompts/draft-email.d.ts +2 -3
- package/dist/esm/mcp/prompts/draft-email.js.map +1 -1
- package/dist/esm/mcp/prompts/query-syntax.d.ts +2 -3
- package/dist/esm/mcp/prompts/query-syntax.js.map +1 -1
- package/dist/esm/mcp/resources/email.d.ts +6 -5
- package/dist/esm/mcp/resources/email.js +1 -1
- package/dist/esm/mcp/resources/email.js.map +1 -1
- package/dist/esm/mcp/tools/categories-list.js +2 -2
- package/dist/esm/mcp/tools/categories-list.js.map +1 -1
- package/dist/esm/mcp/tools/label-add.js +3 -3
- package/dist/esm/mcp/tools/label-add.js.map +1 -1
- package/dist/esm/mcp/tools/label-delete.js +6 -6
- package/dist/esm/mcp/tools/label-delete.js.map +1 -1
- package/dist/esm/mcp/tools/labels-list.d.ts +3 -3
- package/dist/esm/mcp/tools/labels-list.js +2 -2
- package/dist/esm/mcp/tools/labels-list.js.map +1 -1
- package/dist/esm/mcp/tools/message-get.js +4 -5
- package/dist/esm/mcp/tools/message-get.js.map +1 -1
- package/dist/esm/mcp/tools/message-mark-read.js +3 -3
- package/dist/esm/mcp/tools/message-mark-read.js.map +1 -1
- package/dist/esm/mcp/tools/message-move-to-trash.js +6 -6
- package/dist/esm/mcp/tools/message-move-to-trash.js.map +1 -1
- package/dist/esm/mcp/tools/message-respond.js +4 -4
- package/dist/esm/mcp/tools/message-respond.js.map +1 -1
- package/dist/esm/mcp/tools/message-search.js +2 -2
- package/dist/esm/mcp/tools/message-search.js.map +1 -1
- package/dist/esm/mcp/tools/message-send.js +3 -3
- package/dist/esm/mcp/tools/message-send.js.map +1 -1
- package/dist/esm/mcp/tools/messages-export-csv.js +2 -3
- package/dist/esm/mcp/tools/messages-export-csv.js.map +1 -1
- package/dist/esm/setup/http.d.ts +1 -1
- package/dist/esm/setup/http.js +1 -2
- package/dist/esm/setup/http.js.map +1 -1
- package/dist/esm/setup/stdio.d.ts +1 -1
- package/dist/esm/setup/stdio.js +1 -2
- package/dist/esm/setup/stdio.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/label-delete.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).describe('Gmail label IDs to delete'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n totalRequested: z.number().describe('Total number of labels requested to delete'),\n successCount: z.number().describe('Number of labels successfully deleted'),\n failureCount: z.number().describe('Number of labels that failed to delete'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Label 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 label'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Delete Gmail labels permanently (irreversible). System labels (INBOX, SENT, etc.) cannot be deleted.',\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) {\n const logger = extra.logger;\n logger.info('gmail-label-delete called', { count: ids.length });\n\n if (!ids || ids.length === 0) {\n throw new McpError(ErrorCode.InvalidParams, 'Missing ids');\n }\n\n // Validate batch size to prevent memory exhaustion\n if (ids.length > MAX_BATCH_SIZE) {\n throw new McpError(ErrorCode.InvalidParams, `Batch size ${ids.length} exceeds maximum allowed size of ${MAX_BATCH_SIZE}`);\n }\n\n // Validate and sanitize IDs\n const validatedIds: string[] = [];\n const invalidIds: string[] = [];\n\n for (const id of ids) {\n const trimmedId = id.trim();\n if (!trimmedId) {\n invalidIds.push(id);\n continue;\n }\n // Basic Gmail label ID validation - should not contain certain characters\n if (trimmedId.includes('/') || trimmedId.includes('\\\\') || trimmedId.includes('<') || trimmedId.includes('>')) {\n invalidIds.push(id);\n continue;\n }\n validatedIds.push(trimmedId);\n }\n\n if (invalidIds.length > 0) {\n throw new McpError(ErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs: ${invalidIds.join(', ')}`);\n }\n\n if (validatedIds.length === 0) {\n throw new McpError(ErrorCode.InvalidParams, 'No valid IDs found after validation');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n // Get all labels first to check for system labels\n const labelsResponse = await gmail.users.labels.list({ userId: 'me' });\n const allLabels = labelsResponse.data.labels || [];\n const labelMap = new Map(allLabels.map((label) => [label.id || '', label]));\n\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 < validatedIds.length; i += CHUNK_SIZE) {\n const chunk = validatedIds.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(validatedIds.length / CHUNK_SIZE) });\n\n const chunkResults = await Promise.allSettled(\n chunk.map(async (id) => {\n const label = labelMap.get(id);\n\n // Check if label exists\n if (!label) {\n throw new Error(`Label not found: ${id}`);\n }\n\n // Check if it's a system label\n if (label.type === 'system') {\n throw new Error(`Cannot delete system label: ${label.name} (${id})`);\n }\n\n // Delete the label\n await gmail.users.labels.delete({\n userId: 'me',\n id: id,\n });\n return { id, success: true };\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 logger.info('gmail-label-delete completed', {\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(validatedIds.length / CHUNK_SIZE),\n });\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n results: allResults,\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('gmail-label-delete error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error deleting labels: ${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","ErrorCode","McpError","google","z","CHUNK_SIZE","MAX_BATCH_SIZE","inputSchema","object","ids","array","coerce","string","trim","min","describe","successBranchSchema","type","literal","totalRequested","number","successCount","failureCount","results","id","success","boolean","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","count","length","InvalidParams","validatedIds","invalidIds","trimmedId","push","includes","join","gmail","version","auth","authContext","labelsResponse","users","labels","list","userId","allLabels","data","labelMap","Map","map","label","allResults","i","chunk","slice","chunkIndex","chunkSize","totalChunks","Math","ceil","chunkResults","Promise","allSettled","get","Error","name","delete","processedChunkResults","status","errorMessage","reason","message","String","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AACzE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,EAAEC,cAAc,QAAQ,qBAAqB;AAEhE,MAAMC,cAAcH,EAAEI,MAAM,CAAC;IAC3BC,KAAKL,EAAEM,KAAK,CAACN,EAAEO,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAChE;AAEA,MAAMC,sBAAsBZ,EAAEI,MAAM,CAAC;IACnCS,MAAMb,EAAEc,OAAO,CAAC;IAChBC,gBAAgBf,EAAEgB,MAAM,GAAGL,QAAQ,CAAC;IACpCM,cAAcjB,EAAEgB,MAAM,GAAGL,QAAQ,CAAC;IAClCO,cAAclB,E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cp-z/mcp-gmail/src/mcp/tools/label-delete.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).describe('Gmail label IDs to delete'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n totalRequested: z.number().describe('Total number of labels requested to delete'),\n successCount: z.number().describe('Number of labels successfully deleted'),\n failureCount: z.number().describe('Number of labels that failed to delete'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Label 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 label'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Delete Gmail labels permanently (irreversible). System labels (INBOX, SENT, etc.) cannot be deleted.',\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) {\n const logger = extra.logger;\n logger.info('gmail-label-delete called', { count: ids.length });\n\n if (!ids || ids.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing ids');\n }\n\n // Validate batch size to prevent memory exhaustion\n if (ids.length > MAX_BATCH_SIZE) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Batch size ${ids.length} exceeds maximum allowed size of ${MAX_BATCH_SIZE}`);\n }\n\n // Validate and sanitize IDs\n const validatedIds: string[] = [];\n const invalidIds: string[] = [];\n\n for (const id of ids) {\n const trimmedId = id.trim();\n if (!trimmedId) {\n invalidIds.push(id);\n continue;\n }\n // Basic Gmail label ID validation - should not contain certain characters\n if (trimmedId.includes('/') || trimmedId.includes('\\\\') || trimmedId.includes('<') || trimmedId.includes('>')) {\n invalidIds.push(id);\n continue;\n }\n validatedIds.push(trimmedId);\n }\n\n if (invalidIds.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs: ${invalidIds.join(', ')}`);\n }\n\n if (validatedIds.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'No valid IDs found after validation');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n // Get all labels first to check for system labels\n const labelsResponse = await gmail.users.labels.list({ userId: 'me' });\n const allLabels = labelsResponse.data.labels || [];\n const labelMap = new Map(allLabels.map((label) => [label.id || '', label]));\n\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 < validatedIds.length; i += CHUNK_SIZE) {\n const chunk = validatedIds.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(validatedIds.length / CHUNK_SIZE) });\n\n const chunkResults = await Promise.allSettled(\n chunk.map(async (id) => {\n const label = labelMap.get(id);\n\n // Check if label exists\n if (!label) {\n throw new Error(`Label not found: ${id}`);\n }\n\n // Check if it's a system label\n if (label.type === 'system') {\n throw new Error(`Cannot delete system label: ${label.name} (${id})`);\n }\n\n // Delete the label\n await gmail.users.labels.delete({\n userId: 'me',\n id: id,\n });\n return { id, success: true };\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 logger.info('gmail-label-delete completed', {\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(validatedIds.length / CHUNK_SIZE),\n });\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n results: allResults,\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('gmail-label-delete error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error deleting labels: ${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","google","z","CHUNK_SIZE","MAX_BATCH_SIZE","inputSchema","object","ids","array","coerce","string","trim","min","describe","successBranchSchema","type","literal","totalRequested","number","successCount","failureCount","results","id","success","boolean","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","count","length","InvalidParams","validatedIds","invalidIds","trimmedId","push","includes","join","gmail","version","auth","authContext","labelsResponse","users","labels","list","userId","allLabels","data","labelMap","Map","map","label","allResults","i","chunk","slice","chunkIndex","chunkSize","totalChunks","Math","ceil","chunkResults","Promise","allSettled","get","Error","name","delete","processedChunkResults","status","errorMessage","reason","message","String","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,EAAEC,cAAc,QAAQ,qBAAqB;AAEhE,MAAMC,cAAcH,EAAEI,MAAM,CAAC;IAC3BC,KAAKL,EAAEM,KAAK,CAACN,EAAEO,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAChE;AAEA,MAAMC,sBAAsBZ,EAAEI,MAAM,CAAC;IACnCS,MAAMb,EAAEc,OAAO,CAAC;IAChBC,gBAAgBf,EAAEgB,MAAM,GAAGL,QAAQ,CAAC;IACpCM,cAAcjB,EAAEgB,MAAM,GAAGL,QAAQ,CAAC;IAClCO,cAAclB,EAAEgB,MAAM,GAAGL,QAAQ,CAAC;IAClCQ,SAASnB,EACNM,KAAK,CACJN,EAAEI,MAAM,CAAC;QACPgB,IAAIpB,EAAEQ,MAAM,GAAGG,QAAQ,CAAC;QACxBU,SAASrB,EAAEsB,OAAO,GAAGX,QAAQ,CAAC;QAC9BY,OAAOvB,EAAEQ,MAAM,GAAGgB,QAAQ,GAAGb,QAAQ,CAAC;IACxC,IAEDA,QAAQ,CAAC;AACd;AAEA,MAAMc,eAAezB,EAAE0B,kBAAkB,CAAC,QAAQ;IAACd;IAAqBhB;CAAyB;AAEjG,MAAM+B,SAAS;IACbC,aAAa;IACbzB,aAAaA;IACbsB,cAAczB,EAAEI,MAAM,CAAC;QACrByB,QAAQJ;IACV;AACF;AAKA,eAAeK,QAAQ,EAAEzB,GAA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,MAAM;YACnClB;YACAC;YACAgE,iBAAiBjB,KAAKC,IAAI,CAAC7B,aAAaF,MAAM,GAAGlC;QACnD;QAEA,MAAM4B,SAAiB;YACrBhB,MAAM;YACNE,gBAAgBsB,aAAaF,MAAM;YACnClB;YACAC;YACAC,SAASuC;QACX;QAEA,OAAO;YACLyB,SAAS;gBACP;oBACEtE,MAAM;oBACNuE,MAAMC,KAAKC,SAAS,CAACzD;gBACvB;aACD;YACD0D,mBAAmB;gBAAE1D;YAAO;QAC9B;IACF,EAAE,OAAON,OAAO;QACd,MAAMuD,UAAUvD,iBAAiBgD,QAAQhD,MAAMuD,OAAO,GAAGC,OAAOxD;QAChES,OAAOT,KAAK,CAAC,4BAA4B;YAAEA,OAAOuD;QAAQ;QAE1D,MAAM,IAAIjF,cAAcC,kBAAkB0F,aAAa,EAAE,CAAC,uBAAuB,EAAEV,SAAS,EAAE;YAC5FW,OAAOlE,iBAAiBgD,QAAQhD,MAAMkE,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLnB,MAAM;QACN7C;QACAG;IACF;AACF"}
|
|
@@ -10,8 +10,8 @@ declare const outputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
10
10
|
id: z.ZodString;
|
|
11
11
|
name: z.ZodString;
|
|
12
12
|
type: z.ZodEnum<{
|
|
13
|
-
user: "user";
|
|
14
13
|
system: "system";
|
|
14
|
+
user: "user";
|
|
15
15
|
}>;
|
|
16
16
|
visibility: z.ZodEnum<{
|
|
17
17
|
labelShow: "labelShow";
|
|
@@ -41,7 +41,7 @@ declare function handler(_: Input, extra: EnrichedExtra): Promise<{
|
|
|
41
41
|
items: {
|
|
42
42
|
id: string;
|
|
43
43
|
name: string;
|
|
44
|
-
type: "
|
|
44
|
+
type: "system" | "user";
|
|
45
45
|
visibility: "labelShow" | "labelHide" | "labelShowIfUnread";
|
|
46
46
|
}[];
|
|
47
47
|
};
|
|
@@ -59,8 +59,8 @@ export default function createTool(): {
|
|
|
59
59
|
id: z.ZodString;
|
|
60
60
|
name: z.ZodString;
|
|
61
61
|
type: z.ZodEnum<{
|
|
62
|
-
user: "user";
|
|
63
62
|
system: "system";
|
|
63
|
+
user: "user";
|
|
64
64
|
}>;
|
|
65
65
|
visibility: z.ZodEnum<{
|
|
66
66
|
labelShow: "labelShow";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { schemas } from '@mcp-z/oauth-google';
|
|
2
2
|
const { AuthRequiredBranchSchema } = schemas;
|
|
3
|
-
import {
|
|
3
|
+
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
4
4
|
import { google } from 'googleapis';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
// Schema for individual label items
|
|
@@ -110,7 +110,7 @@ async function handler(_, extra) {
|
|
|
110
110
|
logger.error('gmail.labels.list error', {
|
|
111
111
|
error: message
|
|
112
112
|
});
|
|
113
|
-
throw new
|
|
113
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error listing labels: ${message}`, {
|
|
114
114
|
stack: error instanceof Error ? error.stack : undefined
|
|
115
115
|
});
|
|
116
116
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/labels-list.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport {
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/labels-list.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\n\n// Schema for individual label items\nconst LabelSchema = z.object({\n id: z.string().describe('Gmail label ID'),\n name: z.string().describe('Label name for use in queries (case-sensitive)'),\n type: z.enum(['user', 'system']).describe('Whether this is a user-created or system label'),\n visibility: z.enum(['labelShow', 'labelHide', 'labelShowIfUnread']).describe('Label visibility in Gmail UI'),\n});\n\n/**\n * Input schema for the labels-list tool (currently empty as this tool takes no parameters).\n */\nexport const inputSchema = z.object({});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n items: z.array(LabelSchema),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'List Gmail labels for label: query syntax. Case-sensitive.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\n/**\n * Input parameters for the labels-list tool.\n */\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler(_: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail.labels.list called');\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n const started = Date.now();\n\n // Fetch all labels from Gmail API\n const response = await gmail.users.labels.list({ userId: 'me' });\n const labels = response.data.labels || [];\n\n // Filter out CATEGORY_* labels (handled by categories tool) and map to our schema\n const availableLabels = labels\n .filter((label) => {\n // Exclude CATEGORY_* labels as they're handled by the categories tool\n return !label.id?.startsWith('CATEGORY_');\n })\n .map((label) => {\n const id = label.id as string;\n const name = label.name || id;\n\n // Determine label type\n const type: 'user' | 'system' = label.type === 'user' ? 'user' : 'system';\n\n // Map label visibility\n let visibility: 'labelShow' | 'labelHide' | 'labelShowIfUnread' = 'labelShow';\n if (label.labelListVisibility === 'labelHide') {\n visibility = 'labelHide';\n } else if (label.labelListVisibility === 'labelShowIfUnread') {\n visibility = 'labelShowIfUnread';\n }\n\n return {\n id,\n name,\n type,\n visibility,\n };\n })\n .sort((a, b) => {\n // Sort user labels first, then system labels, both alphabetically\n if (a.type !== b.type) {\n return a.type === 'user' ? -1 : 1;\n }\n // Use simple ASCII comparison for consistent, case-sensitive sorting\n return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;\n });\n\n const durationMs = Date.now() - started;\n\n logger.info('gmail.labels.list results', {\n labelCount: availableLabels.length,\n userLabels: availableLabels.filter((l) => l.type === 'user').length,\n systemLabels: availableLabels.filter((l) => l.type === 'system').length,\n totalLabels: labels.length,\n });\n logger.info('gmail.labels.list metrics', { durationMs });\n\n const result: Output = {\n type: 'success' as const,\n items: availableLabels,\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('gmail.labels.list error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error listing labels: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'labels-list',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","LabelSchema","object","id","string","describe","name","type","enum","visibility","inputSchema","successBranchSchema","literal","items","array","outputSchema","discriminatedUnion","config","description","result","handler","_","extra","logger","info","gmail","version","auth","authContext","started","Date","now","response","users","labels","list","userId","data","availableLabels","filter","label","startsWith","map","labelListVisibility","sort","a","b","durationMs","labelCount","length","userLabels","l","systemLabels","totalLabels","content","text","JSON","stringify","structuredContent","error","message","Error","String","InternalError","stack","undefined","createTool"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AAExB,oCAAoC;AACpC,MAAMC,cA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QAC9B;IACF,EAAE,OAAOwC,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGE,OAAOH;QAChEpC,OAAOoC,KAAK,CAAC,2BAA2B;YAAEA,OAAOC;QAAQ;QAEzD,MAAM,IAAI/D,cAAcC,kBAAkBiE,aAAa,EAAE,CAAC,sBAAsB,EAAEH,SAAS,EAAE;YAC3FI,OAAOL,iBAAiBE,QAAQF,MAAMK,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACL5D,MAAM;QACNW;QACAG;IACF;AACF"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { EMAIL_COMMON_PATTERNS, EMAIL_FIELD_DESCRIPTIONS, EMAIL_FIELDS, EmailContentTypeSchema, EmailDetailSchema, ExcludeThreadHistorySchema } from '@mcp-z/email';
|
|
2
2
|
import { schemas } from '@mcp-z/oauth-google';
|
|
3
3
|
const { AuthRequiredBranchSchema } = schemas;
|
|
4
|
-
import { createFieldsSchema, filterFields, parseFields } from '@mcp-z/server';
|
|
5
|
-
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
+
import { createFieldsSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields } from '@mcp-z/server';
|
|
6
5
|
import { google } from 'googleapis';
|
|
7
6
|
import { z } from 'zod';
|
|
8
7
|
import { extractBodyFromPayload, extractEmails, extractFrom } from '../../email/parsing/message-extraction.js';
|
|
@@ -46,7 +45,7 @@ async function handler({ id, fields, contentType, excludeThreadHistory }, extra)
|
|
|
46
45
|
var _fullData_id, _fullData_threadId, _headersMap_Subject, _fullData_snippet;
|
|
47
46
|
var _fullData_payload;
|
|
48
47
|
if (!id) {
|
|
49
|
-
throw new
|
|
48
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id');
|
|
50
49
|
}
|
|
51
50
|
const gmail = google.gmail({
|
|
52
51
|
version: 'v1',
|
|
@@ -67,7 +66,7 @@ async function handler({ id, fields, contentType, excludeThreadHistory }, extra)
|
|
|
67
66
|
});
|
|
68
67
|
const fullData = response.data;
|
|
69
68
|
if (!fullData) {
|
|
70
|
-
throw new
|
|
69
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Message not found');
|
|
71
70
|
}
|
|
72
71
|
// Build full message data with type guards
|
|
73
72
|
const headers = fullData === null || fullData === void 0 ? void 0 : (_fullData_payload = fullData.payload) === null || _fullData_payload === void 0 ? void 0 : _fullData_payload.headers;
|
|
@@ -131,7 +130,7 @@ async function handler({ id, fields, contentType, excludeThreadHistory }, extra)
|
|
|
131
130
|
logger.error('gmail.message.get error', {
|
|
132
131
|
error: message
|
|
133
132
|
});
|
|
134
|
-
throw new
|
|
133
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting message: ${message}`, {
|
|
135
134
|
stack: error instanceof Error ? error.stack : undefined
|
|
136
135
|
});
|
|
137
136
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-get.ts"],"sourcesContent":["import { EMAIL_COMMON_PATTERNS, EMAIL_FIELD_DESCRIPTIONS, EMAIL_FIELDS, EmailContentTypeSchema, type EmailDetail, EmailDetailSchema, ExcludeThreadHistorySchema } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { createFieldsSchema, filterFields, parseFields, type ToolModule } from '@mcp-z/server';\nimport {
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-get.ts"],"sourcesContent":["import { EMAIL_COMMON_PATTERNS, EMAIL_FIELD_DESCRIPTIONS, EMAIL_FIELDS, EmailContentTypeSchema, type EmailDetail, EmailDetailSchema, ExcludeThreadHistorySchema } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { createFieldsSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, type ToolModule } from '@mcp-z/server';\nimport { type gmail_v1, google } from 'googleapis';\nimport { z } from 'zod';\nimport { extractBodyFromPayload, extractEmails, extractFrom } from '../../email/parsing/message-extraction.ts';\nimport { toIsoUtc } from '../../lib/date-conversion.ts';\n\nconst inputSchema = z.object({\n id: z.coerce.string().trim().min(1).describe('Gmail message ID to retrieve'),\n fields: createFieldsSchema({\n availableFields: EMAIL_FIELDS,\n fieldDescriptions: EMAIL_FIELD_DESCRIPTIONS,\n commonPatterns: EMAIL_COMMON_PATTERNS,\n resourceName: 'email message',\n }),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n item: EmailDetailSchema,\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Get a Gmail message by ID 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({ id, fields, contentType, excludeThreadHistory }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n\n const requestedFields = parseFields(fields, EMAIL_FIELDS);\n\n logger.info('gmail.message.get called', { id: Boolean(id), fields: fields || 'all' });\n\n try {\n if (!id) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id');\n }\n\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n const response = await gmail.users.messages.get({\n userId: 'me',\n id: id,\n format: 'full',\n metadataHeaders: ['From', 'To', 'Cc', 'Bcc', 'Subject', 'Date'],\n });\n const fullData = response.data;\n if (!fullData) {\n throw new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Message not found');\n }\n\n // Build full message data with type guards\n const headers = fullData?.payload?.headers;\n const headersArray = Array.isArray(headers) ? headers : [];\n const headersMap: Record<string, string> = Object.fromEntries(\n headersArray.map((h: unknown) => {\n const header = h as gmail_v1.Schema$MessagePartHeader;\n return [String(header.name ?? ''), String(header.value ?? '')];\n })\n );\n const fromInfo = extractFrom(headersMap.From);\n const toStr = extractEmails(headersMap.To).join(', ');\n const ccStr = extractEmails(headersMap.Cc).join(', ');\n const bccStr = extractEmails(headersMap.Bcc).join(', ');\n const messagePayload = fullData?.payload;\n const bodyContent = messagePayload ? extractBodyFromPayload(messagePayload, { contentType, excludeThreadHistory }) : '';\n const payload: Partial<EmailDetail> = {\n id: fullData.id ?? undefined,\n threadId: fullData.threadId ?? undefined,\n date: toIsoUtc(headersMap.Date) || headersMap.Date,\n from: fromInfo?.address || headersMap.From,\n fromName: fromInfo?.name,\n to: toStr,\n cc: ccStr,\n bcc: bccStr,\n subject: headersMap.Subject ?? '',\n snippet: fullData.snippet ?? undefined,\n body: bodyContent,\n bodyContentType: contentType,\n };\n\n // Filter based on requested fields\n const filteredPayload = filterFields(payload, requestedFields);\n\n logger.info('gmail.message.get result', { id: fullData.id, subject: payload.subject, from: payload.from, fields: fields || 'all' });\n\n const result: Output = {\n type: 'success' as const,\n item: filteredPayload,\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('gmail.message.get error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting message: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-get',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["EMAIL_COMMON_PATTERNS","EMAIL_FIELD_DESCRIPTIONS","EMAIL_FIELDS","EmailContentTypeSchema","EmailDetailSchema","ExcludeThreadHistorySchema","schemas","AuthRequiredBranchSchema","createFieldsSchema","filterFields","ProtocolError","ProtocolErrorCode","parseFields","google","z","extractBodyFromPayload","extractEmails","extractFrom","toIsoUtc","inputSchema","object","id","coerce","string","trim","min","describe","fields","availableFields","fieldDescriptions","commonPatterns","resourceName","contentType","excludeThreadHistory","successBranchSchema","type","literal","item","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","requestedFields","info","Boolean","fullData","headersMap","InvalidParams","gmail","version","auth","authContext","response","users","messages","get","userId","format","metadataHeaders","data","InvalidRequest","headers","payload","headersArray","Array","isArray","Object","fromEntries","map","h","header","String","name","value","fromInfo","From","toStr","To","join","ccStr","Cc","bccStr","Bcc","messagePayload","bodyContent","undefined","threadId","date","Date","from","address","fromName","to","cc","bcc","subject","Subject","snippet","body","bodyContentType","filteredPayload","content","text","JSON","stringify","structuredContent","error","message","Error","InternalError","stack","createTool"],"mappings":"AAAA,SAASA,qBAAqB,EAAEC,wBAAwB,EAAEC,YAAY,EAAEC,sBAAsB,EAAoBC,iBAAiB,EAAEC,0BAA0B,QAAQ,eAAe;AAEtL,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAErC,SAASE,kBAAkB,EAAEC,YAAY,EAAEC,aAAa,EAAEC,iBAAiB,EAAEC,WAAW,QAAyB,gBAAgB;AACjI,SAAwBC,MAAM,QAAQ,aAAa;AACnD,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,sBAAsB,EAAEC,aAAa,EAAEC,WAAW,QAAQ,4CAA4C;AAC/G,SAASC,QAAQ,QAAQ,+BAA+B;AAExD,MAAMC,cAAcL,EAAEM,MAAM,CAAC;IAC3BC,IAAIP,EAAEQ,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,QAAQnB,mBAAmB;QACzBoB,iBAAiB1B;QACjB2B,mBAA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BmD,OAAO,GAAEpD,oBAAAA,SAASoD,OAAO,cAAhBpD,+BAAAA,oBAAoBwC;YAC7Ba,MAAMd;YACNe,iBAAiBvE;QACnB;QAEA,mCAAmC;QACnC,MAAMwE,kBAAkB/F,aAAayD,SAASpB;QAE9CD,OAAOE,IAAI,CAAC,4BAA4B;YAAE1B,IAAI4B,SAAS5B,EAAE;YAAE8E,SAASjC,QAAQiC,OAAO;YAAEN,MAAM3B,QAAQ2B,IAAI;YAAElE,QAAQA,UAAU;QAAM;QAEjI,MAAMe,SAAiB;YACrBP,MAAM;YACNE,MAAMmE;QACR;QAEA,OAAO;YACLC,SAAS;gBACP;oBACEtE,MAAM;oBACNuE,MAAMC,KAAKC,SAAS,CAAClE;gBACvB;aACD;YACDmE,mBAAmB;gBAAEnE;YAAO;QAC9B;IACF,EAAE,OAAOoE,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGpC,OAAOmC;QAChEjE,OAAOiE,KAAK,CAAC,2BAA2B;YAAEA,OAAOC;QAAQ;QAEzD,MAAM,IAAIrG,cAAcC,kBAAkBsG,aAAa,EAAE,CAAC,uBAAuB,EAAEF,SAAS,EAAE;YAC5FG,OAAOJ,iBAAiBE,QAAQF,MAAMI,KAAK,GAAGzB;QAChD;IACF;AACF;AAEA,eAAe,SAAS0B;IACtB,OAAO;QACLvC,MAAM;QACNpC;QACAG;IACF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { schemas } from '@mcp-z/oauth-google';
|
|
2
2
|
const { AuthRequiredBranchSchema } = schemas;
|
|
3
|
-
import {
|
|
3
|
+
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
4
4
|
import { google } from 'googleapis';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
const inputSchema = z.object({
|
|
@@ -27,7 +27,7 @@ async function handler({ id }, extra) {
|
|
|
27
27
|
id: Boolean(id)
|
|
28
28
|
});
|
|
29
29
|
if (!id) {
|
|
30
|
-
throw new
|
|
30
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id');
|
|
31
31
|
}
|
|
32
32
|
try {
|
|
33
33
|
const gmail = google.gmail({
|
|
@@ -66,7 +66,7 @@ async function handler({ id }, extra) {
|
|
|
66
66
|
logger.error('gmail-message-mark-read error', {
|
|
67
67
|
error: message
|
|
68
68
|
});
|
|
69
|
-
throw new
|
|
69
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error marking message as read: ${message}`, {
|
|
70
70
|
stack: error instanceof Error ? error.stack : undefined
|
|
71
71
|
});
|
|
72
72
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-mark-read.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport {
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-mark-read.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\n\nconst inputSchema = z.object({\n id: z.coerce.string().trim().min(1).describe('Gmail message ID to mark as read'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: z.string().describe('Message ID that was marked as read'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Mark a Gmail message as read',\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({ id }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail-message-mark-read called', { id: Boolean(id) });\n\n if (!id) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n await gmail.users.messages.modify({\n userId: 'me',\n id: id,\n requestBody: {\n removeLabelIds: ['UNREAD'],\n },\n });\n\n logger.info('gmail-message-mark-read success', { id });\n\n const result: Output = {\n type: 'success' as const,\n id,\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('gmail-message-mark-read error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error marking message as read: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-mark-read',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","inputSchema","object","id","coerce","string","trim","min","describe","successBranchSchema","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","Boolean","InvalidParams","gmail","version","auth","authContext","users","messages","modify","userId","requestBody","removeLabelIds","content","text","JSON","stringify","structuredContent","error","message","Error","String","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AAExB,MAAMC,cAAcD,EAAEE,MAAM,CAAC;IAC3BC,IAAIH,EAAEI,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GA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1C,cAAcC,kBAAkB4C,aAAa,EAAE,CAAC,+BAA+B,EAAEH,SAAS,EAAE;YACpGI,OAAOL,iBAAiBE,QAAQF,MAAMK,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNhC;QACAG;IACF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { schemas } from '@mcp-z/oauth-google';
|
|
2
2
|
const { AuthRequiredBranchSchema } = schemas;
|
|
3
|
-
import {
|
|
3
|
+
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
4
4
|
import { google } from 'googleapis';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.js';
|
|
@@ -35,11 +35,11 @@ async function handler({ ids }, extra) {
|
|
|
35
35
|
count: ids.length
|
|
36
36
|
});
|
|
37
37
|
if (!ids || ids.length === 0) {
|
|
38
|
-
throw new
|
|
38
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing ids');
|
|
39
39
|
}
|
|
40
40
|
// Validate batch size to prevent memory exhaustion
|
|
41
41
|
if (ids.length > MAX_BATCH_SIZE) {
|
|
42
|
-
throw new
|
|
42
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Batch size ${ids.length} exceeds maximum allowed size of ${MAX_BATCH_SIZE}`);
|
|
43
43
|
}
|
|
44
44
|
// Validate and sanitize IDs
|
|
45
45
|
const validatedIds = [];
|
|
@@ -58,10 +58,10 @@ async function handler({ ids }, extra) {
|
|
|
58
58
|
validatedIds.push(trimmedId);
|
|
59
59
|
}
|
|
60
60
|
if (invalidIds.length > 0) {
|
|
61
|
-
throw new
|
|
61
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs: ${invalidIds.join(', ')}`);
|
|
62
62
|
}
|
|
63
63
|
if (validatedIds.length === 0) {
|
|
64
|
-
throw new
|
|
64
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'No valid IDs found after validation');
|
|
65
65
|
}
|
|
66
66
|
try {
|
|
67
67
|
const gmail = google.gmail({
|
|
@@ -153,7 +153,7 @@ async function handler({ ids }, extra) {
|
|
|
153
153
|
logger.error('gmail-message-move-to-trash error', {
|
|
154
154
|
error: message
|
|
155
155
|
});
|
|
156
|
-
throw new
|
|
156
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving messages to trash: ${message}`, {
|
|
157
157
|
stack: error instanceof Error ? error.stack : undefined
|
|
158
158
|
});
|
|
159
159
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-move-to-trash.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).describe('Gmail message IDs to move to trash'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n totalRequested: z.number().describe('Total number of messages requested to trash'),\n successCount: z.number().describe('Number of messages successfully moved to trash'),\n failureCount: z.number().describe('Number of messages that failed to move'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Message 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 message'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Move Gmail messages to trash (recoverable).',\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) {\n const logger = extra.logger;\n logger.info('gmail-message-move-to-trash called', { count: ids.length });\n\n if (!ids || ids.length === 0) {\n throw new McpError(ErrorCode.InvalidParams, 'Missing ids');\n }\n\n // Validate batch size to prevent memory exhaustion\n if (ids.length > MAX_BATCH_SIZE) {\n throw new McpError(ErrorCode.InvalidParams, `Batch size ${ids.length} exceeds maximum allowed size of ${MAX_BATCH_SIZE}`);\n }\n\n // Validate and sanitize IDs\n const validatedIds: string[] = [];\n const invalidIds: string[] = [];\n\n for (const id of ids) {\n const trimmedId = id.trim();\n if (!trimmedId) {\n invalidIds.push(id);\n continue;\n }\n // Basic Gmail message ID validation - should not contain certain characters\n if (trimmedId.includes('/') || trimmedId.includes('\\\\') || trimmedId.includes('<') || trimmedId.includes('>')) {\n invalidIds.push(id);\n continue;\n }\n validatedIds.push(trimmedId);\n }\n\n if (invalidIds.length > 0) {\n throw new McpError(ErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs: ${invalidIds.join(', ')}`);\n }\n\n if (validatedIds.length === 0) {\n throw new McpError(ErrorCode.InvalidParams, 'No valid IDs found after validation');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n // Process operations in chunks to prevent memory exhaustion\n const allResults: Array<{ id: string; success: boolean; error?: string }> = [];\n\n for (let i = 0; i < validatedIds.length; i += CHUNK_SIZE) {\n const chunk = validatedIds.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(validatedIds.length / CHUNK_SIZE) });\n\n const chunkResults = await Promise.allSettled(\n chunk.map(async (id) => {\n await gmail.users.messages.trash({\n userId: 'me',\n id: id,\n });\n return { id, success: true };\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 logger.info('gmail-message-move-to-trash completed', {\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(validatedIds.length / CHUNK_SIZE),\n });\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n results: allResults,\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('gmail-message-move-to-trash error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error moving messages to trash: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-move-to-trash',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ErrorCode","McpError","google","z","CHUNK_SIZE","MAX_BATCH_SIZE","inputSchema","object","ids","array","coerce","string","trim","min","describe","successBranchSchema","type","literal","totalRequested","number","successCount","failureCount","results","id","success","boolean","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","count","length","InvalidParams","validatedIds","invalidIds","trimmedId","push","includes","join","gmail","version","auth","authContext","allResults","i","chunk","slice","chunkIndex","chunkSize","totalChunks","Math","ceil","chunkResults","Promise","allSettled","map","users","messages","trash","userId","processedChunkResults","Error","status","errorMessage","reason","message","String","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","createTool","name"],"mappings":"AACA,SAASA,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,SAAS,EAAEC,QAAQ,QAAQ,qCAAqC;AACzE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,UAAU,EAAEC,cAAc,QAAQ,qBAAqB;AAEhE,MAAMC,cAAcH,EAAEI,MAAM,CAAC;IAC3BC,KAAKL,EAAEM,KAAK,CAACN,EAAEO,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAChE;AAEA,MAAMC,sBAAsBZ,EAAEI,MAAM,CAAC;IACnCS,MAAMb,EAAEc,OAAO,CAAC;IAChBC,gBAAgBf,EAAEgB,MAAM,GAAGL,QAAQ,CAAC;IACpCM,cAAcjB,EAAEgB,MAAM,GAAGL,QAAQ,CAAC;IAClCO,cAAclB,EAAEgB,MAAM,GAAGL,QAAQ,CAAC;IAClCQ,SAASnB,EACNM,KAAK,CACJN,EAAEI,MAAM,CAAC;QACPgB,IAAIpB,EAAEQ,MAAM,GAAGG,QAAQ,CAAC;QACxBU,SAASrB,EAAEsB,OAAO,GAAGX,QAAQ,CAAC;QAC9BY,OAAOvB,EAAEQ,MAAM,GAAGgB,QAAQ,GAAGb,QAAQ,CAAC;IACxC,IAEDA,QAAQ,CAAC;AACd;AAEA,MAAMc,eAAezB,EAAE0B,kBAAkB,CAAC,QAAQ;IAACd;IAAqBhB;CAAyB;AAEjG,MAAM+B,SAAS;IACbC,aAAa;IACbzB,aAAaA;IACb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AAS,EAAE;YACxFW,OAAOzD,iBAAiB0C,QAAQ1C,MAAMyD,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASC;IACtB,OAAO;QACLC,MAAM;QACNxD;QACAG;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-move-to-trash.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).describe('Gmail message IDs to move to trash'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n totalRequested: z.number().describe('Total number of messages requested to trash'),\n successCount: z.number().describe('Number of messages successfully moved to trash'),\n failureCount: z.number().describe('Number of messages that failed to move'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Message 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 message'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Move Gmail messages to trash (recoverable).',\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) {\n const logger = extra.logger;\n logger.info('gmail-message-move-to-trash called', { count: ids.length });\n\n if (!ids || ids.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing ids');\n }\n\n // Validate batch size to prevent memory exhaustion\n if (ids.length > MAX_BATCH_SIZE) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Batch size ${ids.length} exceeds maximum allowed size of ${MAX_BATCH_SIZE}`);\n }\n\n // Validate and sanitize IDs\n const validatedIds: string[] = [];\n const invalidIds: string[] = [];\n\n for (const id of ids) {\n const trimmedId = id.trim();\n if (!trimmedId) {\n invalidIds.push(id);\n continue;\n }\n // Basic Gmail message ID validation - should not contain certain characters\n if (trimmedId.includes('/') || trimmedId.includes('\\\\') || trimmedId.includes('<') || trimmedId.includes('>')) {\n invalidIds.push(id);\n continue;\n }\n validatedIds.push(trimmedId);\n }\n\n if (invalidIds.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs: ${invalidIds.join(', ')}`);\n }\n\n if (validatedIds.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'No valid IDs found after validation');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n // Process operations in chunks to prevent memory exhaustion\n const allResults: Array<{ id: string; success: boolean; error?: string }> = [];\n\n for (let i = 0; i < validatedIds.length; i += CHUNK_SIZE) {\n const chunk = validatedIds.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(validatedIds.length / CHUNK_SIZE) });\n\n const chunkResults = await Promise.allSettled(\n chunk.map(async (id) => {\n await gmail.users.messages.trash({\n userId: 'me',\n id: id,\n });\n return { id, success: true };\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 logger.info('gmail-message-move-to-trash completed', {\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(validatedIds.length / CHUNK_SIZE),\n });\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n results: allResults,\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('gmail-message-move-to-trash error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving messages to trash: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-move-to-trash',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","CHUNK_SIZE","MAX_BATCH_SIZE","inputSchema","object","ids","array","coerce","string","trim","min","describe","successBranchSchema","type","literal","totalRequested","number","successCount","failureCount","results","id","success","boolean","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","count","length","InvalidParams","validatedIds","invalidIds","trimmedId","push","includes","join","gmail","version","auth","authContext","allResults","i","chunk","slice","chunkIndex","chunkSize","totalChunks","Math","ceil","chunkResults","Promise","allSettled","map","users","messages","trash","userId","processedChunkResults","Error","status","errorMessage","reason","message","String","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","und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|
1
1
|
import { ComposeContentTypeSchema } from '@mcp-z/email';
|
|
2
2
|
import { schemas } from '@mcp-z/oauth-google';
|
|
3
3
|
const { AuthRequiredBranchSchema } = schemas;
|
|
4
|
-
import {
|
|
4
|
+
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
5
5
|
import { google } from 'googleapis';
|
|
6
6
|
import { z } from 'zod';
|
|
7
7
|
import { extractEmails } from '../../email/parsing/headers-utils.js';
|
|
@@ -29,7 +29,7 @@ const config = {
|
|
|
29
29
|
async function handler({ id, body, contentType }, extra) {
|
|
30
30
|
const logger = extra.logger;
|
|
31
31
|
if (!id || !body) {
|
|
32
|
-
throw new
|
|
32
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id or body');
|
|
33
33
|
}
|
|
34
34
|
logger.info('gmail.message.respond called', {
|
|
35
35
|
id,
|
|
@@ -65,7 +65,7 @@ async function handler({ id, body, contentType }, extra) {
|
|
|
65
65
|
logger.error('gmail.message.respond fetch error', {
|
|
66
66
|
error: message
|
|
67
67
|
});
|
|
68
|
-
throw new
|
|
68
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error fetching message metadata: ${message}`, {
|
|
69
69
|
stack: error instanceof Error ? error.stack : undefined
|
|
70
70
|
});
|
|
71
71
|
}
|
|
@@ -138,7 +138,7 @@ async function handler({ id, body, contentType }, extra) {
|
|
|
138
138
|
logger.error('gmail.message.respond error', {
|
|
139
139
|
error: message
|
|
140
140
|
});
|
|
141
|
-
throw new
|
|
141
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error responding to message: ${message}`, {
|
|
142
142
|
stack: error instanceof Error ? error.stack : undefined
|
|
143
143
|
});
|
|
144
144
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-respond.ts"],"sourcesContent":["import { ComposeContentTypeSchema } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport {
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-respond.ts"],"sourcesContent":["import { ComposeContentTypeSchema } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { extractEmails } from '../../email/parsing/headers-utils.ts';\nimport { b64url } from '../../lib/base64-encoding.ts';\n\nconst inputSchema = z.object({\n id: z.coerce.string().trim().min(1).describe('Gmail message ID to reply to'),\n body: z.coerce.string().trim().min(1).describe('Reply body content (plain text or HTML)'),\n contentType: ComposeContentTypeSchema,\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: z.string().describe('Original message ID that was replied to'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Send a reply to a Gmail message',\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({ id, body, contentType }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n\n if (!id || !body) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id or body');\n }\n\n logger.info('gmail.message.respond called', { id, contentType });\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n\n let full: unknown;\n try {\n const response = await gmail.users.messages.get({\n userId: 'me',\n id: id,\n format: 'metadata',\n metadataHeaders: ['From', 'To', 'Reply-To', 'Subject', 'Message-ID', 'References', 'In-Reply-To', 'Date'],\n });\n full = response.data;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.message.respond fetch error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error fetching message metadata: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n\n // Type-safe header extraction\n const fullData = full as { payload?: { headers?: unknown[] }; threadId?: unknown };\n const headersArray = Array.isArray(fullData?.payload?.headers) ? fullData.payload.headers : [];\n const headers = Object.fromEntries(\n headersArray.map((h: unknown) => {\n const header = h as { name?: unknown; value?: unknown };\n return [String(header.name ?? ''), String(header.value ?? '')];\n })\n );\n const fromHdr = headers.From || headers.from;\n const replyToHdr = headers['Reply-To'] || headers['reply-to'];\n const toAddr = (replyToHdr ? extractEmails(replyToHdr)[0] : extractEmails(fromHdr)[0]) ?? '';\n const subject = (headers.Subject || headers.subject) ?? '';\n const messageIdHeader = headers['Message-ID'] || headers['Message-Id'] || headers['message-id'];\n const references = (headers.References || headers.references) ?? '';\n const replySubject = /^re:/i.test(subject) ? subject : `Re: ${subject}`;\n const inReplyTo = messageIdHeader?.startsWith('<') ? messageIdHeader : messageIdHeader ? `<${messageIdHeader}>` : undefined;\n const refs = [references, inReplyTo].filter(Boolean).join(' ').trim();\n const mimeType = contentType === 'html' ? 'text/html' : 'text/plain';\n const lines = [`To: ${toAddr}`, `Subject: ${replySubject}`, `In-Reply-To: ${inReplyTo ?? ''}`, `References: ${refs}`, 'MIME-Version: 1.0', `Content-Type: ${mimeType}; charset=UTF-8`, '', body].join('\\r\\n');\n const raw = b64url(lines);\n\n // Prepare request body with conditional threadId for exactOptionalPropertyTypes\n const threadId = fullData?.threadId ? String(fullData.threadId) : undefined;\n await gmail.users.messages.send({\n userId: 'me',\n requestBody: {\n raw: raw,\n ...(threadId && { threadId }),\n },\n });\n\n logger.info('gmail.message.respond sent reply', { id });\n\n const result: Output = {\n type: 'success' as const,\n id,\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('gmail.message.respond error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error responding to message: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-respond',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["ComposeContentTypeSchema","schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","extractEmails","b64url","inputSchema","object","id","coerce","string","trim","min","describe","body","contentType","successBranchSchema","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","InvalidParams","info","replyToHdr","headers","fullData","gmail","version","auth","authContext","full","response","users","messages","get","userId","format","metadataHeaders","data","error","message","Error","String","InternalError","stack","undefined","headersArray","Array","isArray","payload","Object","fromEntries","map","h","header","name","value","fromHdr","From","from","toAddr","subject","Subject","messageIdHeader","references","References","replySubject","test","inReplyTo","startsWith","refs","filter","Boolean","join","mimeType","lines","raw","threadId","send","requestBody","content","text","JSON","stringify","structuredContent","createTool"],"mappings":"AAAA,SAASA,wBAAwB,QAAQ,eAAe;AAExD,SAASC,OAAO,QAAQ,sBAAsB;AAE9C,MAAM,EAAEC,wBAAwB,EAAE,GAAGD;AAGrC,SAASE,aAAa,EAAEC,iBAAiB,QAAQ,gBAAgB;AACjE,SAASC,MAAM,QAAQ,aAAa;AACpC,SAASC,CAAC,QAAQ,MAAM;AACxB,SAASC,aAAa,QAAQ,uCAAuC;AACrE,SAASC,MAAM,QAAQ,+BAA+B;AAEtD,MAAMC,cAAcH,EAAEI,MAAM,CAAC;IAC3BC,IAAIL,EAAEM,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,MAAMX,EAAEM,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CA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iBE,QAAQF,MAAMK,KAAK,GAAGC;QAChD;IACF;AACF;AAEA,eAAe,SAASwC;IACtB,OAAO;QACL9B,MAAM;QACNxC;QACAG;IACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
2
2
|
/** Gmail message search using middleware-based auth pattern */ import { EMAIL_COMMON_PATTERNS, EMAIL_FIELD_DESCRIPTIONS, EMAIL_FIELDS, EmailContentTypeSchema, EmailDetailSchema, ExcludeThreadHistorySchema } from '@mcp-z/email';
|
|
3
3
|
import { schemas } from '@mcp-z/oauth-google';
|
|
4
4
|
const { AuthRequiredBranchSchema } = schemas;
|
|
@@ -167,7 +167,7 @@ async function handler({ query, pageSize = DEFAULT_PAGE_SIZE, pageToken, fields,
|
|
|
167
167
|
logger.error('gmail.message.search error', {
|
|
168
168
|
error: message
|
|
169
169
|
});
|
|
170
|
-
throw new
|
|
170
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching messages: ${message}`, {
|
|
171
171
|
stack: error instanceof Error ? error.stack : undefined
|
|
172
172
|
});
|
|
173
173
|
}
|