@mcp-z/mcp-gmail 1.1.2 → 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/README.md +5 -1
- 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 +28 -18
- 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 +22 -12
- 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 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/messages-export-csv.ts"],"sourcesContent":["import { EmailContentTypeSchema, 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 { getFileUri, reserveFile, type ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\n\nimport { stringify } from 'csv-stringify/sync';\nimport { createWriteStream } from 'fs';\nimport { unlink } from 'fs/promises';\nimport { type gmail_v1, google } from 'googleapis';\nimport { z } from 'zod';\nimport { DEFAULT_PAGE_SIZE } from '../../constants.ts';\nimport { extractBodyFromPayload } from '../../email/parsing/html-processing.ts';\nimport { executeQuery as executeGmailQuery } from '../../email/querying/execute-query.ts';\nimport { GmailQueryParameterSchema, parseGmailQueryParameter } from '../../schemas/gmail-query-schema.ts';\nimport type { StorageExtra } from '../../types.ts';\n\nconst DEFAULT_MAX_ITEMS = 10000;\nconst MAX_EXPORT_ITEMS = 50000;\n\n/**\n * CSV row format based on EmailDetail\n * All fields are strings (empty string instead of undefined)\n * Includes additional CSV-specific fields: provider and labels\n */\ninterface CsvRow {\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\nconst inputSchema = z.object({\n query: GmailQueryParameterSchema.optional().describe('Structured query object or JSON string for filtering messages. Use query-syntax prompt for reference and rawGmailQuery for Gmail 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('gmail-messages.csv').describe('Output filename (default: gmail-messages.csv)'),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\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 outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Export Gmail 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 gmail-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) {\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('gmail.messages.export-csv starting streaming export', { path: fullPath, maxItems });\n\n try {\n const parsedQuery = parseGmailQueryParameter(query);\n\n logger.info('gmail.messages.export-csv called', {\n query: parsedQuery,\n maxItems,\n filename,\n accountId: extra.authContext.accountId,\n });\n\n const gmail = google.gmail({ version: 'v1', auth: 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: CsvRow[];\n metadata?: { nextPageToken?: string };\n } = await executeGmailQuery(\n parsedQuery,\n {\n client: gmail,\n logger,\n pageSize,\n ...(nextPageToken !== undefined && { pageToken: nextPageToken }),\n includeBody: true, // Always include body for CSV export\n },\n (full: unknown): CsvRow => {\n // Type-safe property access with guards\n const fullData = full as {\n id?: unknown;\n threadId?: unknown;\n snippet?: unknown;\n labelIds?: unknown[];\n payload?: { headers?: unknown[] };\n };\n\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\n const payload = fullData?.payload;\n // Cast to Schema$MessagePart for extractBodyFromPayload\n const body = payload ? extractBodyFromPayload(payload as gmail_v1.Schema$MessagePart, { contentType, excludeThreadHistory }) : '';\n\n const labelIds = Array.isArray(fullData?.labelIds) ? fullData.labelIds.map((id) => String(id ?? '')) : [];\n\n return {\n id: String(fullData?.id ?? ''),\n threadId: fullData?.threadId ? String(fullData.threadId) : '',\n from: headers?.From || '',\n to: headers?.To || '',\n cc: headers?.Cc || '',\n bcc: headers?.Bcc || '',\n subject: headers?.Subject || '',\n date: headers?.Date || '',\n snippet: fullData?.snippet ? String(fullData.snippet) : '',\n body,\n provider: 'gmail',\n labels: labelIds.join(';'),\n };\n }\n );\n\n // Type-safe CSV row mapping\n const csvRows = exec.items.map((row) => {\n return [row.id, row.threadId, row.from, row.to, row.cc, row.bcc, row.subject, row.date, row.snippet, row.body, row.provider, row.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('gmail.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('gmail.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 const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.messages.export-csv error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error exporting messages to CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'messages-export-csv',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","inputSchema","z","object","query","GmailQueryParameterSchema","optional","describe","maxItems","number","int","positive","max","default","filename","string","trim","min","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successBranchSchema","type","literal","uri","rowCount","truncated","boolean","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","storageContext","transport","resourceStoreUri","baseUrl","reservation","storedName","fullPath","parsedQuery","gmail","csvHeaders","writeStream","headerLine","totalRows","nextPageToken","started","exec","remainingItems","pageSize","csvRows","rowsContent","durationMs","error","_cleanupError","message","reserveFile","info","path","parseGmailQueryParameter","accountId","authContext","google","version","auth","createWriteStream","encoding","stringify","header","quoted","quote","escape","write","Date","now","Math","DEFAULT_PAGE_SIZE","executeGmailQuery","client","undefined","pageToken","includeBody","full","fullData","headersArray","Array","isArray","payload","headers","Object","fromEntries","map","h","String","name","value","body","extractBodyFromPayload","labelIds","id","threadId","from","From","to","To","cc","Cc","bcc","Bcc","subject","Subject","date","snippet","provider","labels","join","items","row","length","metadata","batchSize","hasMore","Boolean","Promise","resolve","reject","end","on","getFileUri","endpoint","content","text","JSON","structuredContent","unlink","debug","Error","McpError","ErrorCode","InternalError","stack"],"mappings":";;;;+BAsQA;;;e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U;;oBAGNrG,SAAiB;wBACrBV,MAAM;wBACNE,KAAAA;wBACAX,UAAU4B;wBACVhB,UAAUuB;wBACVtB,WAAAA;oBACF;oBAEA;;wBAAO;4BACL4G,OAAO;gCACL;oCACEhH,MAAM;oCACNiH,MAAMC,KAAKjE,SAAS,CAACvC;gCACvB;;4BAEFyG,mBAAmB;gCAAEzG,QAAAA;4BAAO;wBAC9B;;;oBACOyB;;;;;;;;;oBAGL;;wBAAMiF,IAAAA,gBAAM,EAAChG;;;oBAAb;oBACAP,OAAOwG,KAAK,CAAC,2CAA2C;wBAAE7E,MAAMpB;oBAAS;;;;;;oBAClEgB;oBACPvB,OAAOwG,KAAK,CAAC,+CAA+C;wBAAE7E,MAAMpB;oBAAS;;;;;;oBAGzEiB,UAAUF,AAAK,YAALA,OAAiBmF,SAAQnF,MAAME,OAAO,GAAGsC,OAAOxC;oBAChEtB,OAAOsB,KAAK,CAAC,mCAAmC;wBAAEA,OAAOE;oBAAQ;oBAEjE,MAAM,IAAIkF,eAAQ,CAACC,gBAAS,CAACC,aAAa,EAAE,AAAC,oCAA2C,OAARpF,UAAW;wBACzFqF,OAAOvF,AAAK,YAALA,OAAiBmF,SAAQnF,MAAMuF,KAAK,GAAG7D;oBAChD;;;;;;;IAEJ;;AAEe,SAASxF;IACtB,OAAO;QACLuG,MAAM;QACNpE,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/messages-export-csv.ts"],"sourcesContent":["import { EmailContentTypeSchema, 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 { getFileUri, ProtocolError, ProtocolErrorCode, reserveFile, type ToolModule } from '@mcp-z/server';\n\nimport { stringify } from 'csv-stringify/sync';\nimport { createWriteStream } from 'fs';\nimport { unlink } from 'fs/promises';\nimport { type gmail_v1, google } from 'googleapis';\nimport { z } from 'zod';\nimport { DEFAULT_PAGE_SIZE } from '../../constants.ts';\nimport { extractBodyFromPayload } from '../../email/parsing/html-processing.ts';\nimport { executeQuery as executeGmailQuery } from '../../email/querying/execute-query.ts';\nimport { GmailQueryParameterSchema, parseGmailQueryParameter } from '../../schemas/gmail-query-schema.ts';\nimport type { StorageExtra } from '../../types.ts';\n\nconst DEFAULT_MAX_ITEMS = 10000;\nconst MAX_EXPORT_ITEMS = 50000;\n\n/**\n * CSV row format based on EmailDetail\n * All fields are strings (empty string instead of undefined)\n * Includes additional CSV-specific fields: provider and labels\n */\ninterface CsvRow {\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\nconst inputSchema = z.object({\n query: GmailQueryParameterSchema.optional().describe('Structured query object or JSON string for filtering messages. Use query-syntax prompt for reference and rawGmailQuery for Gmail 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('gmail-messages.csv').describe('Output filename (default: gmail-messages.csv)'),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\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 outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Export Gmail 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 gmail-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) {\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('gmail.messages.export-csv starting streaming export', { path: fullPath, maxItems });\n\n try {\n const parsedQuery = parseGmailQueryParameter(query);\n\n logger.info('gmail.messages.export-csv called', {\n query: parsedQuery,\n maxItems,\n filename,\n accountId: extra.authContext.accountId,\n });\n\n const gmail = google.gmail({ version: 'v1', auth: 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: CsvRow[];\n metadata?: { nextPageToken?: string };\n } = await executeGmailQuery(\n parsedQuery,\n {\n client: gmail,\n logger,\n pageSize,\n ...(nextPageToken !== undefined && { pageToken: nextPageToken }),\n includeBody: true, // Always include body for CSV export\n },\n (full: unknown): CsvRow => {\n // Type-safe property access with guards\n const fullData = full as {\n id?: unknown;\n threadId?: unknown;\n snippet?: unknown;\n labelIds?: unknown[];\n payload?: { headers?: unknown[] };\n };\n\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\n const payload = fullData?.payload;\n // Cast to Schema$MessagePart for extractBodyFromPayload\n const body = payload ? extractBodyFromPayload(payload as gmail_v1.Schema$MessagePart, { contentType, excludeThreadHistory }) : '';\n\n const labelIds = Array.isArray(fullData?.labelIds) ? fullData.labelIds.map((id) => String(id ?? '')) : [];\n\n return {\n id: String(fullData?.id ?? ''),\n threadId: fullData?.threadId ? String(fullData.threadId) : '',\n from: headers?.From || '',\n to: headers?.To || '',\n cc: headers?.Cc || '',\n bcc: headers?.Bcc || '',\n subject: headers?.Subject || '',\n date: headers?.Date || '',\n snippet: fullData?.snippet ? String(fullData.snippet) : '',\n body,\n provider: 'gmail',\n labels: labelIds.join(';'),\n };\n }\n );\n\n // Type-safe CSV row mapping\n const csvRows = exec.items.map((row) => {\n return [row.id, row.threadId, row.from, row.to, row.cc, row.bcc, row.subject, row.date, row.snippet, row.body, row.provider, row.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('gmail.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('gmail.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 const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.messages.export-csv error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error exporting messages to CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'messages-export-csv',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","inputSchema","z","object","query","GmailQueryParameterSchema","optional","describe","maxItems","number","int","positive","max","default","filename","string","trim","min","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successBranchSchema","type","literal","uri","rowCount","truncated","boolean","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","storageContext","transport","resourceStoreUri","baseUrl","reservation","storedName","fullPath","parsedQuery","gmail","csvHeaders","writeStream","headerLine","totalRows","nextPageToken","started","exec","remainingItems","pageSize","csvRows","rowsContent","durationMs","error","_cleanupError","message","reserveFile","info","path","parseGmailQueryParameter","accountId","authContext","google","version","auth","createWriteStream","encoding","stringify","header","quoted","quote","escape","write","Date","now","Math","DEFAULT_PAGE_SIZE","executeGmailQuery","client","undefined","pageToken","includeBody","full","fullData","headersArray","Array","isArray","payload","headers","Object","fromEntries","map","h","String","name","value","body","extractBodyFromPayload","labelIds","id","threadId","from","From","to","To","cc","Cc","bcc","Bcc","subject","Subject","date","snippet","provider","labels","join","items","row","length","metadata","batchSize","hasMore","Boolean","Promise","resolve","reject","end","on","getFileUri","endpoint","content","text","JSON","structuredContent","unlink","debug","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BAqQA;;;eAAwBA;;;qBArQ2C;2BAE3C;sBAImE;oBAEjE;kBACQ;wBACX;0BACe;mBACpB;2BACgB;gCACK;8BACW;kCACkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAZpE,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAeR,IAAME,oBAAoB;AAC1B,IAAMC,mBAAmB;AAsBzB,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,6CAAyB,CAACC,QAAQ,GAAGC,QAAQ,CAAC;IACrDC,UAAUN,MAAC,CAACO,MAAM,GAAGC,GAAG,GAAGC,QAAQ,GAAGC,GAAG,CAACZ,kBAAkBa,OAAO,CAACd,mBAAmBQ,QAAQ,CAAC,AAAC,wCAAkEP,OAA3BD,mBAAkB,WAA0B,OAAjBC,kBAAiB;IACpLc,UAAUZ,MAAC,CAACa,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGJ,OAAO,CAAC,sBAAsBN,QAAQ,CAAC;IAC1EW,aAAaC,6BAAsB;IACnCC,sBAAsBC,iCAA0B;AAClD;AAEA,IAAMC,sBAAsBpB,MAA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
|
|
|
1
|
-
import { McpServer } from '@
|
|
1
|
+
import { McpServer } from '@mcp-z/server';
|
|
2
2
|
import type { RuntimeOverrides, ServerConfig } from '../types.js';
|
|
3
3
|
export declare function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
|
|
4
4
|
httpServer: import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
|
package/dist/cjs/setup/http.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { McpServer } from '@
|
|
1
|
+
import { McpServer } from '@mcp-z/server';
|
|
2
2
|
import type { RuntimeOverrides, ServerConfig } from '../types.js';
|
|
3
3
|
export declare function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
|
|
4
4
|
httpServer: import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
|
package/dist/cjs/setup/http.js
CHANGED
|
@@ -9,7 +9,6 @@ Object.defineProperty(exports, "createHTTPServer", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _server = require("@mcp-z/server");
|
|
12
|
-
var _mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
13
12
|
var _cors = /*#__PURE__*/ _interop_require_default(require("cors"));
|
|
14
13
|
var _express = /*#__PURE__*/ _interop_require_default(require("express"));
|
|
15
14
|
var _runtimets = require("./runtime.js");
|
|
@@ -172,7 +171,7 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
172
171
|
}
|
|
173
172
|
function createHTTPServer(config, overrides) {
|
|
174
173
|
return _async_to_generator(function() {
|
|
175
|
-
var runtime, modules, layers, composed, logger, port, tools, filteredTools, prompts, mcpServer, app,
|
|
174
|
+
var runtime, modules, layers, composed, logger, port, tools, filteredTools, prompts, mcpServer, app, publicUrl, _ref, close, httpServer, fileRouter;
|
|
176
175
|
return _ts_generator(this, function(_state) {
|
|
177
176
|
switch(_state.label){
|
|
178
177
|
case 0:
|
|
@@ -196,7 +195,7 @@ function createHTTPServer(config, overrides) {
|
|
|
196
195
|
}) // No file storage in DCR (public cloud responsibility)
|
|
197
196
|
: tools;
|
|
198
197
|
prompts = _to_consumable_array(composed.prompts).concat(_to_consumable_array(runtime.deps.oauthAdapters.accountPrompts));
|
|
199
|
-
mcpServer = new
|
|
198
|
+
mcpServer = new _server.McpServer({
|
|
200
199
|
name: config.name,
|
|
201
200
|
version: config.version
|
|
202
201
|
});
|
|
@@ -204,12 +203,34 @@ function createHTTPServer(config, overrides) {
|
|
|
204
203
|
(0, _server.registerResources)(mcpServer, composed.resources);
|
|
205
204
|
(0, _server.registerPrompts)(mcpServer, prompts);
|
|
206
205
|
app = (0, _express.default)();
|
|
207
|
-
app.use((0, _cors.default)());
|
|
208
206
|
app.use(_express.default.json({
|
|
209
207
|
limit: '10mb'
|
|
210
208
|
}));
|
|
209
|
+
// Must mount '/mcp' before any permissive app-level cors(), or that layer answers its
|
|
210
|
+
// preflight first; pass baseUrl's origin/host below or a public deployment 403s itself.
|
|
211
|
+
publicUrl = config.baseUrl ? new URL(config.baseUrl) : undefined;
|
|
212
|
+
logger.info("Starting ".concat(config.name, " MCP server (http)"));
|
|
213
|
+
return [
|
|
214
|
+
4,
|
|
215
|
+
(0, _server.connectHttp)(mcpServer, {
|
|
216
|
+
logger: logger,
|
|
217
|
+
app: app,
|
|
218
|
+
port: port,
|
|
219
|
+
allowedOrigins: publicUrl ? [
|
|
220
|
+
publicUrl.origin
|
|
221
|
+
] : undefined,
|
|
222
|
+
allowedHosts: publicUrl ? [
|
|
223
|
+
publicUrl.host
|
|
224
|
+
] : undefined
|
|
225
|
+
})
|
|
226
|
+
];
|
|
227
|
+
case 2:
|
|
228
|
+
_ref = _state.sent(), close = _ref.close, httpServer = _ref.httpServer;
|
|
229
|
+
// The loopback OAuth callback, the file-export download, and the DCR discovery/
|
|
230
|
+
// registration endpoints are all meant to be reached from a browser on another
|
|
231
|
+
// origin. Keep cors() for them, scoped to their own routes - never in front of '/mcp'.
|
|
211
232
|
if (runtime.deps.oauthAdapters.loopbackRouter) {
|
|
212
|
-
app.use('/', runtime.deps.oauthAdapters.loopbackRouter);
|
|
233
|
+
app.use('/', (0, _cors.default)(), runtime.deps.oauthAdapters.loopbackRouter);
|
|
213
234
|
logger.info('Mounted loopback OAuth callback router');
|
|
214
235
|
}
|
|
215
236
|
if (config.auth !== 'dcr') {
|
|
@@ -219,23 +240,12 @@ function createHTTPServer(config, overrides) {
|
|
|
219
240
|
contentType: 'text/csv',
|
|
220
241
|
contentDisposition: 'attachment'
|
|
221
242
|
});
|
|
222
|
-
app.use('/files', fileRouter);
|
|
243
|
+
app.use('/files', (0, _cors.default)(), fileRouter);
|
|
223
244
|
}
|
|
224
245
|
if (runtime.deps.oauthAdapters.dcrRouter) {
|
|
225
|
-
app.use('/', runtime.deps.oauthAdapters.dcrRouter);
|
|
246
|
+
app.use('/', (0, _cors.default)(), runtime.deps.oauthAdapters.dcrRouter);
|
|
226
247
|
logger.info('Mounted DCR router with OAuth endpoints');
|
|
227
248
|
}
|
|
228
|
-
logger.info("Starting ".concat(config.name, " MCP server (http)"));
|
|
229
|
-
return [
|
|
230
|
-
4,
|
|
231
|
-
(0, _server.connectHttp)(mcpServer, {
|
|
232
|
-
logger: logger,
|
|
233
|
-
app: app,
|
|
234
|
-
port: port
|
|
235
|
-
})
|
|
236
|
-
];
|
|
237
|
-
case 2:
|
|
238
|
-
_ref = _state.sent(), close = _ref.close, httpServer = _ref.httpServer;
|
|
239
249
|
logger.info('http transport ready');
|
|
240
250
|
return [
|
|
241
251
|
2,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/setup/http.ts"],"sourcesContent":["import { composeMiddleware, connectHttp, createFileServingRouter, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/setup/http.ts"],"sourcesContent":["import { composeMiddleware, connectHttp, createFileServingRouter, McpServer, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport cors from 'cors';\nimport express from 'express';\nimport type { RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createDefaultRuntime } from './runtime.ts';\n\nexport async function createHTTPServer(config: ServerConfig, overrides?: RuntimeOverrides) {\n const runtime = await createDefaultRuntime(config, overrides);\n const modules = runtime.createDomainModules();\n const layers = runtime.middlewareFactories.map((factory) => factory(runtime.deps));\n const composed = composeMiddleware(modules, layers);\n const logger = runtime.deps.logger;\n const port = config.transport.port;\n if (!port) throw new Error('Port is required for HTTP transport');\n\n const tools = [...composed.tools, ...runtime.deps.oauthAdapters.accountTools];\n const filteredTools =\n config.auth === 'dcr'\n ? tools.filter((tool) => tool.name !== 'messages-export-csv') // No file storage in DCR (public cloud responsibility)\n : tools;\n const prompts = [...composed.prompts, ...runtime.deps.oauthAdapters.accountPrompts];\n\n const mcpServer = new McpServer({ name: config.name, version: config.version });\n registerTools(mcpServer, filteredTools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n\n const app = express();\n app.use(express.json({ limit: '10mb' }));\n\n // Must mount '/mcp' before any permissive app-level cors(), or that layer answers its\n // preflight first; pass baseUrl's origin/host below or a public deployment 403s itself.\n const publicUrl = config.baseUrl ? new URL(config.baseUrl) : undefined;\n logger.info(`Starting ${config.name} MCP server (http)`);\n const { close, httpServer } = await connectHttp(mcpServer, {\n logger,\n app,\n port,\n allowedOrigins: publicUrl ? [publicUrl.origin] : undefined,\n allowedHosts: publicUrl ? [publicUrl.host] : undefined,\n });\n\n // The loopback OAuth callback, the file-export download, and the DCR discovery/\n // registration endpoints are all meant to be reached from a browser on another\n // origin. Keep cors() for them, scoped to their own routes - never in front of '/mcp'.\n if (runtime.deps.oauthAdapters.loopbackRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.loopbackRouter);\n logger.info('Mounted loopback OAuth callback router');\n }\n\n if (config.auth !== 'dcr') {\n const fileRouter = createFileServingRouter({ resourceStoreUri: config.resourceStoreUri }, { contentType: 'text/csv', contentDisposition: 'attachment' });\n app.use('/files', cors(), fileRouter);\n }\n\n if (runtime.deps.oauthAdapters.dcrRouter) {\n app.use('/', cors(), runtime.deps.oauthAdapters.dcrRouter);\n logger.info('Mounted DCR router with OAuth endpoints');\n }\n\n logger.info('http transport ready');\n\n return {\n httpServer,\n mcpServer,\n logger,\n close: async () => {\n await close();\n await runtime.close();\n },\n };\n}\n"],"names":["createHTTPServer","config","overrides","runtime","modules","layers","composed","logger","port","tools","filteredTools","prompts","mcpServer","app","publicUrl","close","httpServer","fileRouter","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","transport","Error","oauthAdapters","accountTools","auth","filter","tool","name","accountPrompts","McpServer","version","registerTools","registerResources","resources","registerPrompts","express","use","json","limit","baseUrl","URL","undefined","info","connectHttp","allowedOrigins","origin","allowedHosts","host","loopbackRouter","cors","createFileServingRouter","resourceStoreUri","contentType","contentDisposition","dcrRouter"],"mappings":";;;;+BAMsBA;;;eAAAA;;;sBANgH;2DACrH;8DACG;yBAEiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,SAAeA,iBAAiBC,MAAoB,EAAEC,SAA4B;;YACjFC,SACAC,SACAC,QACAC,UACAC,QACAC,MAGAC,OACAC,eAIAC,SAEAC,WAKAC,KAKAC,WAEwB,MAAtBC,OAAOC,YAiBPC;;;;oBA5CQ;;wBAAMC,IAAAA,+BAAoB,EAACjB,QAAQC;;;oBAA7CC,UAAU;oBACVC,UAAUD,QAAQgB,mBAAmB;oBACrCd,SAASF,QAAQiB,mBAAmB,CAACC,GAAG,CAAC,SAACC;+BAAYA,QAAQn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/C;;;oBAN8B,OAAA,eAAtB/B,QAAsB,KAAtBA,OAAOC,aAAe,KAAfA;oBAQf,gFAAgF;oBAChF,+EAA+E;oBAC/E,uFAAuF;oBACvF,IAAIb,QAAQoB,IAAI,CAACI,aAAa,CAAC0B,cAAc,EAAE;wBAC7CxC,IAAI4B,GAAG,CAAC,KAAKa,IAAAA,aAAI,KAAInD,QAAQoB,IAAI,CAACI,aAAa,CAAC0B,cAAc;wBAC9D9C,OAAOwC,IAAI,CAAC;oBACd;oBAEA,IAAI9C,OAAO4B,IAAI,KAAK,OAAO;wBACnBZ,aAAasC,IAAAA,+BAAuB,EAAC;4BAAEC,kBAAkBvD,OAAOuD,gBAAgB;wBAAC,GAAG;4BAAEC,aAAa;4BAAYC,oBAAoB;wBAAa;wBACtJ7C,IAAI4B,GAAG,CAAC,UAAUa,IAAAA,aAAI,KAAIrC;oBAC5B;oBAEA,IAAId,QAAQoB,IAAI,CAACI,aAAa,CAACgC,SAAS,EAAE;wBACxC9C,IAAI4B,GAAG,CAAC,KAAKa,IAAAA,aAAI,KAAInD,QAAQoB,IAAI,CAACI,aAAa,CAACgC,SAAS;wBACzDpD,OAAOwC,IAAI,CAAC;oBACd;oBAEAxC,OAAOwC,IAAI,CAAC;oBAEZ;;wBAAO;4BACL/B,YAAAA;4BACAJ,WAAAA;4BACAL,QAAAA;4BACAQ,OAAO,SAAPA;;;;;gDACE;;oDAAMA;;;gDAAN;gDACA;;oDAAMZ,QAAQY,KAAK;;;gDAAnB;;;;;;gCACF;;wBACF;;;;IACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { McpServer } from '@
|
|
1
|
+
import { McpServer } from '@mcp-z/server';
|
|
2
2
|
import type { RuntimeOverrides, ServerConfig } from '../types.js';
|
|
3
3
|
export declare function createStdioServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
|
|
4
4
|
mcpServer: McpServer;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { McpServer } from '@
|
|
1
|
+
import { McpServer } from '@mcp-z/server';
|
|
2
2
|
import type { RuntimeOverrides, ServerConfig } from '../types.js';
|
|
3
3
|
export declare function createStdioServer(config: ServerConfig, overrides?: RuntimeOverrides): Promise<{
|
|
4
4
|
mcpServer: McpServer;
|
package/dist/cjs/setup/stdio.js
CHANGED
|
@@ -9,7 +9,6 @@ Object.defineProperty(exports, "createStdioServer", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _server = require("@mcp-z/server");
|
|
12
|
-
var _mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
|
|
13
12
|
var _runtimets = require("./runtime.js");
|
|
14
13
|
function _array_like_to_array(arr, len) {
|
|
15
14
|
if (len == null || len > arr.length) len = arr.length;
|
|
@@ -187,7 +186,7 @@ function createStdioServer(config, overrides) {
|
|
|
187
186
|
}) // No file storage in DCR (public cloud responsibility)
|
|
188
187
|
: tools;
|
|
189
188
|
prompts = _to_consumable_array(composed.prompts).concat(_to_consumable_array(runtime.deps.oauthAdapters.accountPrompts));
|
|
190
|
-
mcpServer = new
|
|
189
|
+
mcpServer = new _server.McpServer({
|
|
191
190
|
name: config.name,
|
|
192
191
|
version: config.version
|
|
193
192
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/setup/stdio.ts"],"sourcesContent":["import { composeMiddleware, connectStdio, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/setup/stdio.ts"],"sourcesContent":["import { composeMiddleware, connectStdio, McpServer, registerPrompts, registerResources, registerTools } from '@mcp-z/server';\nimport type { RuntimeOverrides, ServerConfig } from '../types.ts';\nimport { createDefaultRuntime } from './runtime.ts';\n\nexport async function createStdioServer(config: ServerConfig, overrides?: RuntimeOverrides) {\n const runtime = await createDefaultRuntime(config, overrides);\n const modules = runtime.createDomainModules();\n const layers = runtime.middlewareFactories.map((factory) => factory(runtime.deps));\n const composed = composeMiddleware(modules, layers);\n const logger = runtime.deps.logger;\n\n const tools = [...composed.tools, ...runtime.deps.oauthAdapters.accountTools];\n const filteredTools =\n config.auth === 'dcr'\n ? tools.filter((tool) => tool.name !== 'messages-export-csv') // No file storage in DCR (public cloud responsibility)\n : tools;\n const prompts = [...composed.prompts, ...runtime.deps.oauthAdapters.accountPrompts];\n\n const mcpServer = new McpServer({ name: config.name, version: config.version });\n registerTools(mcpServer, filteredTools);\n registerResources(mcpServer, composed.resources);\n registerPrompts(mcpServer, prompts);\n\n logger.info(`Starting ${config.name} MCP server (stdio)`);\n const { close } = await connectStdio(mcpServer, { logger });\n logger.info('stdio transport ready');\n\n return {\n mcpServer,\n logger,\n close: async () => {\n await close();\n await runtime.close();\n },\n };\n}\n"],"names":["createStdioServer","config","overrides","runtime","modules","layers","composed","logger","tools","filteredTools","prompts","mcpServer","close","createDefaultRuntime","createDomainModules","middlewareFactories","map","factory","deps","composeMiddleware","oauthAdapters","accountTools","auth","filter","tool","name","accountPrompts","McpServer","version","registerTools","registerResources","resources","registerPrompts","info","connectStdio"],"mappings":";;;;+BAIsBA;;;eAAAA;;;sBAJwF;yBAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE9B,SAAeA,kBAAkBC,MAAoB,EAAEC,SAA4B;;YAClFC,SACAC,SACAC,QACAC,UACAC,QAEAC,OACAC,eAIAC,SAEAC,WAMEC;;;;oBAnBQ;;wBAAMC,IAAAA,+BAAoB,EAACZ,QAAQC;;;oBAA7CC,UAAU;oBACVC,UAAUD,QAAQW,mBAAmB;oBACrCT,SAASF,QAAQY,mBAAmB,CAACC,GAAG,CAAC,SAACC;+BAAYA,QAAQd,QAAQe,IAAI;;oBAC1EZ,WAAWa,IAAAA,yBAAiB,EAACf,SAASC;oBACtCE,SAASJ,QAAQe,IAAI,CAACX,MAAM;oBAE5BC,QAAQ,AAAC,qBAAGF,SAASE,KAAK,SAAE,qBAAGL,QAAQe,IAAI,CAACE,aAAa,CAACC,YAAY;oBACtEZ,gBACJR,OAAOqB,IAAI,KAAK,QACZd,MAAMe,MAAM,CAAC,SAACC;+BAASA,KAAKC,IAAI,KAAK;uBAAuB,uDAAuD;uBACnHjB;oBACAE,UAAU,AAAC,qBAAGJ,SAASI,OAAO,SAAE,qBAAGP,QAAQe,IAAI,CAACE,aAAa,CAACM,cAAc;oBAE5Ef,YAAY,IAAIgB,iBAAS,CAAC;wBAAEF,MAAMxB,OAAOwB,IAAI;wBAAEG,SAAS3B,OAAO2B,OAAO;oBAAC;oBAC7EC,IAAAA,qBAAa,EAAClB,WAAWF;oBACzBqB,IAAAA,yBAAiB,EAACnB,WAAWL,SAASyB,SAAS;oBAC/CC,IAAAA,uBAAe,EAACrB,WAAWD;oBAE3BH,OAAO0B,IAAI,CAAC,AAAC,YAAuB,OAAZhC,OAAOwB,IAAI,EAAC;oBAClB;;wBAAMS,IAAAA,oBAAY,EAACvB,WAAW;4BAAEJ,QAAAA;wBAAO;;;oBAAjDK,QAAU,cAAVA;oBACRL,OAAO0B,IAAI,CAAC;oBAEZ;;wBAAO;4BACLtB,WAAAA;4BACAJ,QAAAA;4BACAK,OAAO,SAAPA;;;;;gDACE;;oDAAMA;;;gDAAN;gDACA;;oDAAMT,QAAQS,KAAK;;;gDAAnB;;;;;;gCACF;;wBACF;;;;IACF"}
|
package/dist/esm/index.js
CHANGED
|
@@ -10,7 +10,7 @@ import * as _setup from './setup/index.js';
|
|
|
10
10
|
export { _setup as setup };
|
|
11
11
|
export * from './types.js';
|
|
12
12
|
export async function startServer(config) {
|
|
13
|
-
// createHTTPServer/createStdioServer pull in @
|
|
13
|
+
// createHTTPServer/createStdioServer pull in @mcp-z/server and every mcp/tools/*.ts
|
|
14
14
|
// (googleapis included); deferred so a --version/--help run never reaches them.
|
|
15
15
|
const { createHTTPServer } = await import('./setup/http.js');
|
|
16
16
|
const { createStdioServer } = await import('./setup/stdio.js');
|
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/index.ts"],"sourcesContent":["import { handleVersionHelp } from './setup/version-help.ts';\nimport type { ServerConfig } from './types.ts';\n\nexport { GOOGLE_SCOPE } from './constants.ts';\nexport * as mcp from './mcp/index.ts';\n// Export types and schemas for documentation\nexport type { Input as CategoriesListInput } from './mcp/tools/categories-list.ts';\nexport { inputSchema as CategoriesListInputSchema } from './mcp/tools/categories-list.ts';\nexport type { Input as LabelsListInput } from './mcp/tools/labels-list.ts';\nexport { inputSchema as LabelsListInputSchema } from './mcp/tools/labels-list.ts';\nexport * as schemas from './schemas/index.ts';\nexport * as setup from './setup/index.ts';\nexport * from './types.ts';\n\nexport async function startServer(config: ServerConfig): Promise<void> {\n // createHTTPServer/createStdioServer pull in @
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/index.ts"],"sourcesContent":["import { handleVersionHelp } from './setup/version-help.ts';\nimport type { ServerConfig } from './types.ts';\n\nexport { GOOGLE_SCOPE } from './constants.ts';\nexport * as mcp from './mcp/index.ts';\n// Export types and schemas for documentation\nexport type { Input as CategoriesListInput } from './mcp/tools/categories-list.ts';\nexport { inputSchema as CategoriesListInputSchema } from './mcp/tools/categories-list.ts';\nexport type { Input as LabelsListInput } from './mcp/tools/labels-list.ts';\nexport { inputSchema as LabelsListInputSchema } from './mcp/tools/labels-list.ts';\nexport * as schemas from './schemas/index.ts';\nexport * as setup from './setup/index.ts';\nexport * from './types.ts';\n\nexport async function startServer(config: ServerConfig): Promise<void> {\n // createHTTPServer/createStdioServer pull in @mcp-z/server and every mcp/tools/*.ts\n // (googleapis included); deferred so a --version/--help run never reaches them.\n const { createHTTPServer } = await import('./setup/http.ts');\n const { createStdioServer } = await import('./setup/stdio.ts');\n const { logger, close } = config.transport.type === 'stdio' ? await createStdioServer(config) : await createHTTPServer(config);\n\n process.on('SIGINT', async () => {\n await close();\n process.exit(0);\n });\n\n logger.info(`Server started with ${config.transport.type} transport`);\n await new Promise(() => {});\n}\n\nexport default async function main(): Promise<void> {\n // Check for help/version flags FIRST, before config parsing\n const versionHelpResult = handleVersionHelp(process.argv);\n if (versionHelpResult.handled) {\n console.log(versionHelpResult.output);\n process.exit(0);\n }\n\n // Only parse config if no help/version flags. config.ts's own heavy imports (@mcp-z/oauth-google,\n // @mcp-z/server) are deferred internally, so this static-looking call stays cheap until here.\n const { createConfig } = await import('./setup/config.ts');\n const config = createConfig();\n await startServer(config);\n}\n\nif (process.argv[1] === new URL(import.meta.url).pathname) {\n main();\n}\n"],"names":["handleVersionHelp","GOOGLE_SCOPE","mcp","inputSchema","CategoriesListInputSchema","LabelsListInputSchema","schemas","setup","startServer","config","createHTTPServer","createStdioServer","logger","close","transport","type","process","on","exit","info","Promise","main","versionHelpResult","argv","handled","console","log","output","createConfig","URL","url","pathname"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,0BAA0B;AAG5D,SAASC,YAAY,QAAQ,iBAAiB;AAC9C,sBAAqB,iBAAiB;AAAtC,SAAO,QAAKC,GAAG,GAAuB;AAGtC,SAASC,eAAeC,yBAAyB,QAAQ,iCAAiC;AAE1F,SAASD,eAAeE,qBAAqB,QAAQ,6BAA6B;AAClF,0BAAyB,qBAAqB;AAA9C,SAAO,YAAKC,OAAO,GAA2B;AAC9C,wBAAuB,mBAAmB;AAA1C,SAAO,UAAKC,KAAK,GAAyB;AAC1C,cAAc,aAAa;AAE3B,OAAO,eAAeC,YAAYC,MAAoB;IACpD,oFAAoF;IACpF,gFAAgF;IAChF,MAAM,EAAEC,gBAAgB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC1C,MAAM,EAAEC,iBAAiB,EAAE,GAAG,MAAM,MAAM,CAAC;IAC3C,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAE,GAAGJ,OAAOK,SAAS,CAACC,IAAI,KAAK,UAAU,MAAMJ,kBAAkBF,UAAU,MAAMC,iBAAiBD;IAEvHO,QAAQC,EAAE,CAAC,UAAU;QACnB,MAAMJ;QACNG,QAAQE,IAAI,CAAC;IACf;IAEAN,OAAOO,IAAI,CAAC,CAAC,oBAAoB,EAAEV,OAAOK,SAAS,CAACC,IAAI,CAAC,UAAU,CAAC;IACpE,MAAM,IAAIK,QAAQ,KAAO;AAC3B;AAEA,eAAe,eAAeC;IAC5B,4DAA4D;IAC5D,MAAMC,oBAAoBtB,kBAAkBgB,QAAQO,IAAI;IACxD,IAAID,kBAAkBE,OAAO,EAAE;QAC7BC,QAAQC,GAAG,CAACJ,kBAAkBK,MAAM;QACpCX,QAAQE,IAAI,CAAC;IACf;IAEA,kGAAkG;IAClG,8FAA8F;IAC9F,MAAM,EAAEU,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC;IACtC,MAAMnB,SAASmB;IACf,MAAMpB,YAAYC;AACpB;AAEA,IAAIO,QAAQO,IAAI,CAAC,EAAE,KAAK,IAAIM,IAAI,YAAYC,GAAG,EAAEC,QAAQ,EAAE;IACzDV;AACF"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
1
|
+
import type { ServerContext } from '@mcp-z/server';
|
|
3
2
|
import { z } from 'zod';
|
|
4
3
|
export default function createPrompt(): {
|
|
5
4
|
name: string;
|
|
@@ -12,7 +11,7 @@ export default function createPrompt(): {
|
|
|
12
11
|
};
|
|
13
12
|
handler: (args: {
|
|
14
13
|
[x: string]: unknown;
|
|
15
|
-
}, _extra:
|
|
14
|
+
}, _extra: ServerContext) => Promise<{
|
|
16
15
|
messages: ({
|
|
17
16
|
role: "system";
|
|
18
17
|
content: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/prompts/draft-email.ts"],"sourcesContent":["import type { PromptModule } from '@mcp-z/server';\nimport
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/prompts/draft-email.ts"],"sourcesContent":["import type { PromptModule, ServerContext } from '@mcp-z/server';\nimport { z } from 'zod';\n\nexport default function createPrompt() {\n const argsSchema = z.object({\n context: z.string().min(1).describe('Email context to draft response for'),\n tone: z.string().optional().describe('Email tone (default: professional)'),\n });\n\n const config = {\n description: 'Draft an email response',\n argsSchema: argsSchema.shape,\n };\n\n const handler = async (args: { [x: string]: unknown }, _extra: ServerContext) => {\n const { context, tone } = argsSchema.parse(args);\n return {\n messages: [\n { role: 'system' as const, content: { type: 'text' as const, text: 'You are an expert email assistant.' } },\n { role: 'user' as const, content: { type: 'text' as const, text: `Draft a ${tone || 'professional'} email:\\n\\n${context}` } },\n ],\n };\n };\n\n return {\n name: 'draft-email',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["z","createPrompt","argsSchema","object","context","string","min","describe","tone","optional","config","description","shape","handler","args","_extra","parse","messages","role","content","type","text","name"],"mappings":"AACA,SAASA,CAAC,QAAQ,MAAM;AAExB,eAAe,SAASC;IACtB,MAAMC,aAAaF,EAAEG,MAAM,CAAC;QAC1BC,SAASJ,EAAEK,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;QACpCC,MAAMR,EAAEK,MAAM,GAAGI,QAAQ,GAAGF,QAAQ,CAAC;IACvC;IAEA,MAAMG,SAAS;QACbC,aAAa;QACbT,YAAYA,WAAWU,KAAK;IAC9B;IAEA,MAAMC,UAAU,OAAOC,MAAgCC;QACrD,MAAM,EAAEX,OAAO,EAAEI,IAAI,EAAE,GAAGN,WAAWc,KAAK,CAACF;QAC3C,OAAO;YACLG,UAAU;gBACR;oBAAEC,MAAM;oBAAmBC,SAAS;wBAAEC,MAAM;wBAAiBC,MAAM;oBAAqC;gBAAE;gBAC1G;oBAAEH,MAAM;oBAAiBC,SAAS;wBAAEC,MAAM;wBAAiBC,MAAM,CAAC,QAAQ,EAAEb,QAAQ,eAAe,WAAW,EAAEJ,SAAS;oBAAC;gBAAE;aAC7H;QACH;IACF;IAEA,OAAO;QACLkB,MAAM;QACNZ;QACAG;IACF;AACF"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
1
|
+
import type { ServerContext } from '@mcp-z/server';
|
|
3
2
|
export default function createPrompt(): {
|
|
4
3
|
name: string;
|
|
5
4
|
config: {
|
|
@@ -7,7 +6,7 @@ export default function createPrompt(): {
|
|
|
7
6
|
};
|
|
8
7
|
handler: (_args: {
|
|
9
8
|
[x: string]: unknown;
|
|
10
|
-
}, _extra:
|
|
9
|
+
}, _extra: ServerContext) => Promise<{
|
|
11
10
|
messages: {
|
|
12
11
|
role: "user";
|
|
13
12
|
content: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule } from '@mcp-z/server';\
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule, ServerContext } from '@mcp-z/server';\n\nexport default function createPrompt() {\n const config = {\n description: 'Reference guide for Gmail query syntax',\n };\n\n const handler = async (_args: { [x: string]: unknown }, _extra: ServerContext) => {\n return {\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: `# Gmail Query Syntax Reference\n\n## Logical Operators\n- \\`$and\\`: Array of conditions that ALL must match\n- \\`$or\\`: Array of conditions where ANY must match\n- \\`$not\\`: Condition that must NOT match\n\n## Email Address Fields\n- \\`from\\`, \\`to\\`, \\`cc\\`, \\`bcc\\`: String or field operators\n\n## Content Fields\n- \\`subject\\`: Search subject line\n- \\`body\\`: Search message body\n- \\`text\\`: Search all text content\n- \\`fuzzyPhrase\\`: Approximate phrase matching (words appear together)\n\n## Boolean Flags\n- \\`hasAttachment\\`: true/false\n- \\`isRead\\`: true/false\n\n## Date Range\n\\`\\`\\`json\n{ \"date\": { \"$gte\": \"2024-01-01\", \"$lt\": \"2024-12-31\" } }\n\\`\\`\\`\n\n## Gmail-Specific\n- \\`categories\\`: primary, social, promotions, updates, forums\n- \\`label\\`: User labels (case-sensitive, use gmail-labels-list to discover)\n- \\`rawGmailQuery\\`: Escape hatch for advanced Gmail syntax\n\n## Field Operators (for multi-value fields)\n- \\`$any\\`: OR - matches if ANY value matches\n- \\`$all\\`: AND - matches if ALL values match\n- \\`$none\\`: NOT - matches if NONE match\n\n## Example Queries\n\\`\\`\\`json\n// Unread from specific sender\n{ \"from\": \"boss@company.com\", \"isRead\": false }\n\n// Recent with attachment\n{ \"hasAttachment\": true, \"date\": { \"$gte\": \"2024-01-01\" } }\n\n// Multiple senders\n{ \"from\": { \"$any\": [\"alice@example.com\", \"bob@example.com\"] } }\n\n// Complex: promotions OR social, unread\n{ \"$and\": [\n { \"categories\": { \"$any\": [\"promotions\", \"social\"] } },\n { \"isRead\": false }\n]}\n\\`\\`\\``,\n },\n },\n ],\n };\n };\n\n return {\n name: 'query-syntax',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","config","description","handler","_args","_extra","messages","role","content","type","text","name"],"mappings":"AAEA,eAAe,SAASA;IACtB,MAAMC,SAAS;QACbC,aAAa;IACf;IAEA,MAAMC,UAAU,OAAOC,OAAiCC;QACtD,OAAO;YACLC,UAAU;gBACR;oBACEC,MAAM;oBACNC,SAAS;wBACPC,MAAM;wBACNC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAmDb,CAAC;oBACG;gBACF;aACD;QACH;IACF;IAEA,OAAO;QACLC,MAAM;QACNV;QACAE;IACF;AACF"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import type { ReadResourceResult, ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
1
|
+
import type { ReadResourceResult, ServerContext } from '@mcp-z/server';
|
|
2
|
+
import { ResourceTemplate } from '@mcp-z/server';
|
|
4
3
|
export default function createResource(): {
|
|
5
4
|
name: string;
|
|
6
5
|
template: ResourceTemplate;
|
|
7
|
-
config: import("@modelcontextprotocol/
|
|
6
|
+
config: import("@modelcontextprotocol/server").ResourceMetadata & {
|
|
7
|
+
cacheHint?: import("@modelcontextprotocol/server").CacheHint;
|
|
8
|
+
};
|
|
8
9
|
handler: (uri: URL, variables: {
|
|
9
10
|
id: string;
|
|
10
|
-
}, extra:
|
|
11
|
+
}, extra: ServerContext) => Promise<ReadResourceResult>;
|
|
11
12
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ResourceTemplate } from '@
|
|
1
|
+
import { ResourceTemplate } from '@mcp-z/server';
|
|
2
2
|
import { google } from 'googleapis';
|
|
3
3
|
import { extractEmails, extractFrom } from '../../email/parsing/message-extraction.js';
|
|
4
4
|
import { toIsoUtc } from '../../lib/date-conversion.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/resources/email.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ResourceConfig, ResourceModule } from '@mcp-z/server';\nimport { ResourceTemplate } from '@
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/resources/email.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ReadResourceResult, ResourceConfig, ResourceModule, ServerContext } from '@mcp-z/server';\nimport { ResourceTemplate } from '@mcp-z/server';\nimport { type gmail_v1, google } from 'googleapis';\nimport { extractEmails, extractFrom } from '../../email/parsing/message-extraction.ts';\nimport { toIsoUtc } from '../../lib/date-conversion.ts';\n\nexport default function createResource() {\n const template = new ResourceTemplate('gmail://messages/{id}', {\n list: undefined,\n });\n const config: ResourceConfig = {\n description: 'Gmail message metadata (lightweight: id, subject, from, to, date)',\n mimeType: 'application/json',\n };\n\n const handler = async (uri: URL, variables: { id: string }, extra: ServerContext): Promise<ReadResourceResult> => {\n try {\n const { logger, authContext } = extra as unknown as EnrichedExtra;\n\n logger.info(variables, 'gmail-email resource fetch');\n\n const gmail = google.gmail({ version: 'v1', auth: authContext.auth });\n const response = await gmail.users.messages.get({\n userId: 'me',\n id: variables.id,\n format: 'metadata',\n metadataHeaders: ['From', 'To', 'Subject', 'Date'],\n });\n\n const fullData = response.data;\n if (!fullData) {\n throw new Error('Message not found');\n }\n\n // Extract headers\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\n const fromInfo = extractFrom(headersMap.From);\n const toStr = extractEmails(headersMap.To).join(', ');\n\n // Return lightweight metadata only (no body/snippet)\n const metadata = {\n id: fullData.id ?? variables.id,\n subject: headersMap.Subject ?? '',\n from: fromInfo?.address || headersMap.From,\n to: toStr,\n date: toIsoUtc(headersMap.Date) || headersMap.Date,\n };\n\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(metadata),\n },\n ],\n };\n } catch (e) {\n const { logger } = extra as unknown as EnrichedExtra;\n logger.error(e as Record<string, unknown>, 'gmail-email resource fetch failed');\n const error = e as { message?: unknown };\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({ error: String(error?.message ?? e) }),\n },\n ],\n };\n }\n };\n\n return {\n name: 'email',\n template,\n config,\n handler,\n } satisfies ResourceModule;\n}\n"],"names":["ResourceTemplate","google","extractEmails","extractFrom","toIsoUtc","createResource","template","list","undefined","config","description","mimeType","handler","uri","variables","extra","fullData","headersMap","logger","authContext","info","gmail","version","auth","response","users","messages","get","userId","id","format","metadataHeaders","data","Error","headers","payload","headersArray","Array","isArray","Object","fromEntries","map","h","header","String","name","value","fromInfo","From","toStr","To","join","metadata","subject","Subject","from","address","to","date","Date","contents","href","text","JSON","stringify","e","error","message"],"mappings":"AAEA,SAASA,gBAAgB,QAAQ,gBAAgB;AACjD,SAAwBC,MAAM,QAAQ,aAAa;AACnD,SAASC,aAAa,EAAEC,WAAW,QAAQ,4CAA4C;AACvF,SAASC,QAAQ,QAAQ,+BAA+B;AAExD,eAAe,SAASC;IACtB,MAAMC,WAAW,IAAIN,iBAAiB,yBAAyB;QAC7DO,MAAMC;IACR;IACA,MAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,MAAMC,UAAU,OAAOC,KAAUC,WAA2BC;QAC1D,IAAI;gBAiCIC,cACKC;gBAfKD;YAlBhB,MAAM,EAAEE,MAAM,EAAEC,WAAW,EAAE,GAAGJ;YAEhCG,OAAOE,IAAI,CAACN,WAAW;YAEvB,MAAMO,QAAQpB,OAAOoB,KAAK,CAAC;gBAAEC,SAAS;gBAAMC,MAAMJ,YAAYI,IAAI;YAAC;YACnE,MAAMC,WAAW,MAAMH,MAAMI,KAAK,CAACC,QAAQ,CAACC,GAAG,CAAC;gBAC9CC,QAAQ;gBACRC,IAAIf,UAAUe,EAAE;gBAChBC,QAAQ;gBACRC,iBAAiB;oBAAC;oBAAQ;oBAAM;oBAAW;iBAAO;YACpD;YAEA,MAAMf,WAAWQ,SAASQ,IAAI;YAC9B,IAAI,CAAChB,UAAU;gBACb,MAAM,IAAIiB,M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KC,SAAS,CAAC;4BAAEE,OAAOtB,eAAOsB,kBAAAA,4BAAAA,MAAOC,OAAO,uCAAIF;wBAAG;oBAC5D;iBACD;YACH;QACF;IACF;IAEA,OAAO;QACLpB,MAAM;QACNvC;QACAG;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
|
// Schema for individual category items
|
|
@@ -112,7 +112,7 @@ async function handler(_, extra) {
|
|
|
112
112
|
logger.error('gmail.categories.list error', {
|
|
113
113
|
error: message
|
|
114
114
|
});
|
|
115
|
-
throw new
|
|
115
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error listing categories: ${message}`, {
|
|
116
116
|
stack: error instanceof Error ? error.stack : undefined
|
|
117
117
|
});
|
|
118
118
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/categories-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/categories-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 category items\nconst CategorySchema = z.object({\n id: z.string().describe('Gmail category ID (e.g., CATEGORY_PERSONAL)'),\n name: z.string().describe('Human-readable category name'),\n description: z.string().describe('Description of what emails belong in this category'),\n});\n\n/**\n * Input schema for the categories-list tool (currently empty as this tool takes no parameters).\n */\nexport const inputSchema = z.object({});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n items: z.array(CategorySchema),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'List Gmail category labels (CATEGORY_*) with IDs and descriptions.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\n/**\n * Input parameters for the categories-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.categories.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 for CATEGORY_* system labels and map to our schema\n const categories = labels\n .filter((label) => label.id?.startsWith('CATEGORY_'))\n .map((label) => {\n const id = label.id as string;\n let name = label.name || id;\n let description = '';\n\n // Map known category types to user-friendly names and descriptions\n switch (id) {\n case 'CATEGORY_PERSONAL':\n name = 'Primary';\n description = 'Important emails from people you know';\n break;\n case 'CATEGORY_SOCIAL':\n name = 'Social';\n description = 'Social networks and social websites';\n break;\n case 'CATEGORY_PROMOTIONS':\n name = 'Promotions';\n description = 'Deals, offers, and marketing emails';\n break;\n case 'CATEGORY_UPDATES':\n name = 'Updates';\n description = 'Confirmations, receipts, bills, and statements';\n break;\n case 'CATEGORY_FORUMS':\n name = 'Forums';\n description = 'Online groups, discussion boards, mailing lists';\n break;\n default:\n // For any unknown CATEGORY_* labels, use the label name as-is\n name = label.name || id.replace('CATEGORY_', '');\n description = `Gmail category: ${name}`;\n }\n\n return {\n id,\n name,\n description,\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name)); // Sort alphabetically by name\n\n const durationMs = Date.now() - started;\n\n logger.info('gmail.categories.list results', { categoryCount: categories.length, totalLabels: labels.length });\n logger.info('gmail.categories.list metrics', { durationMs });\n\n const result: Output = {\n type: 'success' as const,\n items: categories,\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.categories.list error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error listing categories: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'categories-list',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","CategorySchema","object","id","string","describe","name","description","inputSchema","successBranchSchema","type","literal","items","array","outputSchema","discriminatedUnion","config","result","handler","_","extra","logger","info","gmail","version","auth","authContext","started","Date","now","response","users","labels","list","userId","data","categories","filter","label","startsWith","map","replace","sort","a","b","localeCompare","durationMs","categoryCount","length","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,uCAAuC;AACvC,MAAMC,iBAAiBD,EAAEE,MAAM,CAAC;IAC9BC,IAAIH,EAAEI,MAAM,GAAGC,QAAQ,CAAC;IACxBC,MAAMN,EAAEI,MAAM,GAAGC,QAAQ,CAAC;IAC1BE,aAAaP,EAAE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redBranchSchema } = 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 { ensureLabelId } from '../../labels/gmail-labels.js';
|
|
@@ -39,7 +39,7 @@ async function handler({ id, label }, extra) {
|
|
|
39
39
|
id,
|
|
40
40
|
label
|
|
41
41
|
});
|
|
42
|
-
throw new
|
|
42
|
+
throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id or label');
|
|
43
43
|
}
|
|
44
44
|
try {
|
|
45
45
|
const gmail = google.gmail({
|
|
@@ -87,7 +87,7 @@ async function handler({ id, label }, extra) {
|
|
|
87
87
|
logger.error('gmail.label.add error', {
|
|
88
88
|
error: message
|
|
89
89
|
});
|
|
90
|
-
throw new
|
|
90
|
+
throw new ProtocolError(ProtocolErrorCode.InternalError, `Error adding label to message: ${message}`, {
|
|
91
91
|
stack: error instanceof Error ? error.stack : undefined
|
|
92
92
|
});
|
|
93
93
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/label-add.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/label-add.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 { ensureLabelId } from '../../labels/gmail-labels.ts';\n\nconst inputSchema = z.object({\n id: z.coerce.string().trim().min(1).describe('Gmail message ID to add label to'),\n label: z.coerce.string().trim().min(1).describe('Label name or ID (use gmail-labels-list to discover available labels)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n item: z.object({\n id: z.string().describe('Message ID the label was added to'),\n label: z.string().describe('Label that was added'),\n }),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Add a label 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, label }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail.label.add called', { id, label });\n\n if (!id || !label) {\n logger.info('gmail.label.add missing parameters', { id, label });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id or label');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n\n const labelId = await ensureLabelId(gmail, 'me', label);\n await gmail.users.messages.modify({\n userId: 'me',\n id: id,\n requestBody: {\n addLabelIds: [labelId],\n },\n });\n\n logger.info('gmail.label.add success', { id, label });\n logger.info('gmail.label.add result (typed)', { id, label });\n\n const result: Output = {\n type: 'success' as const,\n item: { id, label },\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.add error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error adding label to message: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'label-add',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["schemas","AuthRequiredBranchSchema","ProtocolError","ProtocolErrorCode","google","z","ensureLabelId","inputSchema","object","id","coerce","string","trim","min","describe","label","successBranchSchema","type","literal","item","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","info","InvalidParams","gmail","version","auth","authContext","labelId","users","messages","modify","userId","requestBody","addLabelIds","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;AACxB,SAASC,aAAa,QAAQ,+BAA+B;AAE7D,MAAMC,cAAcF,EAAEG,MAAM,CAAC;IAC3BC,IAAIJ,EAAEK,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,OAAOV,EAAEK,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAClD;AAEA,wBAAwB;AACxB,MAAME,sBAAsBX,EAAEG,MAAM,CAAC;IACnCS,MAAMZ,EAAEa,OAAO,CAAC;IAChBC,MAAMd,EAAEG,MAAM,CAAC;QACbC,IAAIJ,EAAEM,MAAM,GAAGG,QAAQ,CAAC;QACxBC,OAAOV,EAAEM,MAAM,GAAGG,QAAQ,CAAC;IAC7B;AACF;AAEA,2CAA2C;AAC3C,MAAMM,eAAef,EAAEgB,kBAAkB,CAAC,QAAQ;IAACL;IAAqBf;CAAyB;AAEjG,MAAMqB,SAAS;IACbC,aAAa;IACbhB,aAAaA;IACba,cAAcf,EAAEG,MAAM,CAAC;QACrBgB,QAAQJ;IACV;AACF;AAKA,eAAeK,QAAQ,EAAEhB,EAAE,EAAEM,KAAK,EAAS,EAAEW,KAAoB;IAC/D,MAAMC,SAASD,MAAMC,MAAM;IAC3BA,OAAOC,IAAI,CAAC,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