@mcp-z/mcp-gmail 2.0.0 → 2.1.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/lib/google-auth.d.cts +9 -0
- package/dist/cjs/lib/google-auth.d.ts +9 -0
- package/dist/cjs/lib/google-auth.js +16 -0
- package/dist/cjs/lib/google-auth.js.map +1 -0
- package/dist/cjs/mcp/resources/email.js +2 -1
- package/dist/cjs/mcp/resources/email.js.map +1 -1
- package/dist/cjs/mcp/tools/categories-list.js +2 -1
- package/dist/cjs/mcp/tools/categories-list.js.map +1 -1
- package/dist/cjs/mcp/tools/label-add.js +2 -1
- package/dist/cjs/mcp/tools/label-add.js.map +1 -1
- package/dist/cjs/mcp/tools/label-delete.js +2 -1
- package/dist/cjs/mcp/tools/label-delete.js.map +1 -1
- package/dist/cjs/mcp/tools/labels-list.js +2 -1
- package/dist/cjs/mcp/tools/labels-list.js.map +1 -1
- package/dist/cjs/mcp/tools/message-get.js +2 -1
- package/dist/cjs/mcp/tools/message-get.js.map +1 -1
- package/dist/cjs/mcp/tools/message-mark-read.js +2 -1
- package/dist/cjs/mcp/tools/message-mark-read.js.map +1 -1
- package/dist/cjs/mcp/tools/message-move-to-trash.js +2 -1
- package/dist/cjs/mcp/tools/message-move-to-trash.js.map +1 -1
- package/dist/cjs/mcp/tools/message-respond.js +2 -1
- package/dist/cjs/mcp/tools/message-respond.js.map +1 -1
- package/dist/cjs/mcp/tools/message-search.js +2 -1
- package/dist/cjs/mcp/tools/message-search.js.map +1 -1
- package/dist/cjs/mcp/tools/message-send.js +2 -1
- package/dist/cjs/mcp/tools/message-send.js.map +1 -1
- package/dist/cjs/mcp/tools/messages-export-csv.js +2 -1
- package/dist/cjs/mcp/tools/messages-export-csv.js.map +1 -1
- package/dist/esm/lib/google-auth.d.ts +9 -0
- package/dist/esm/lib/google-auth.js +11 -0
- package/dist/esm/lib/google-auth.js.map +1 -0
- package/dist/esm/mcp/resources/email.js +2 -1
- package/dist/esm/mcp/resources/email.js.map +1 -1
- package/dist/esm/mcp/tools/categories-list.js +2 -1
- package/dist/esm/mcp/tools/categories-list.js.map +1 -1
- package/dist/esm/mcp/tools/label-add.js +2 -1
- package/dist/esm/mcp/tools/label-add.js.map +1 -1
- package/dist/esm/mcp/tools/label-delete.js +2 -1
- package/dist/esm/mcp/tools/label-delete.js.map +1 -1
- package/dist/esm/mcp/tools/labels-list.js +2 -1
- package/dist/esm/mcp/tools/labels-list.js.map +1 -1
- package/dist/esm/mcp/tools/message-get.js +2 -1
- package/dist/esm/mcp/tools/message-get.js.map +1 -1
- package/dist/esm/mcp/tools/message-mark-read.js +2 -1
- package/dist/esm/mcp/tools/message-mark-read.js.map +1 -1
- package/dist/esm/mcp/tools/message-move-to-trash.js +2 -1
- package/dist/esm/mcp/tools/message-move-to-trash.js.map +1 -1
- package/dist/esm/mcp/tools/message-respond.js +2 -1
- package/dist/esm/mcp/tools/message-respond.js.map +1 -1
- package/dist/esm/mcp/tools/message-search.js +2 -1
- package/dist/esm/mcp/tools/message-search.js.map +1 -1
- package/dist/esm/mcp/tools/message-send.js +2 -1
- package/dist/esm/mcp/tools/message-send.js.map +1 -1
- package/dist/esm/mcp/tools/messages-export-csv.js +2 -1
- package/dist/esm/mcp/tools/messages-export-csv.js.map +1 -1
- package/package.json +3 -3
|
@@ -15,6 +15,7 @@ var _googleapis = require("googleapis");
|
|
|
15
15
|
var _zod = require("zod");
|
|
16
16
|
var _headersutilsts = require("../../email/parsing/headers-utils.js");
|
|
17
17
|
var _base64encodingts = require("../../lib/base64-encoding.js");
|
|
18
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
18
19
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
19
20
|
try {
|
|
20
21
|
var info = gen[key](arg);
|
|
@@ -218,7 +219,7 @@ function handler(_0, _1) {
|
|
|
218
219
|
]);
|
|
219
220
|
gmail = _googleapis.google.gmail({
|
|
220
221
|
version: 'v1',
|
|
221
|
-
auth: extra.authContext.auth
|
|
222
|
+
auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
|
|
222
223
|
});
|
|
223
224
|
_state.label = 2;
|
|
224
225
|
case 2:
|
|
@@ -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 { 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":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","coerce","string","trim","min","describe","body","contentType","ComposeContentTypeSchema","successBranchSchema","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","replyToHdr","headers","fullData","gmail","full","response","error","message","headersArray","fromHdr","toAddr","subject","messageIdHeader","references","replySubject","inReplyTo","refs","mimeType","lines","raw","threadId","ProtocolError","ProtocolErrorCode","InvalidParams","info","google","version","auth","authContext","users","messages","get","userId","format","metadataHeaders","data","Error","String","InternalError","stack","undefined","Array","isArray","payload","Object","fromEntries","map","h","header","name","value","From","from","extractEmails","Subject","References","test","startsWith","filter","Boolean","join","b64url","send","requestBody","content","text","JSON","stringify","structuredContent"],"mappings":";;;;+BA6HA;;;eAAwBA;;;qBA7HiB;2BAEjB;sBAKyB;0BAC1B;mBACL;8BACY;gCACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAPvB,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIF,MAAC,CAACG,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC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ACvB;;4BAEFwE,mBAAmB;gCAAExE,QAAAA;4BAAO;wBAC9B;;;oBACOU;oBACDC,WAAUD,AAAK,YAALA,QAAiB8B,SAAQ9B,OAAMC,OAAO,GAAG8B,OAAO/B;oBAChEP,OAAOO,KAAK,CAAC,+BAA+B;wBAAEA,OAAOC;oBAAQ;oBAE7D,MAAM,IAAIc,qBAAa,CAACC,yBAAiB,CAACgB,aAAa,EAAE,AAAC,gCAAuC,OAAR/B,WAAW;wBAClGgC,OAAOjC,AAAK,YAALA,QAAiB8B,SAAQ9B,OAAMiC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASlE;IACtB,OAAO;QACL2E,MAAM;QACNvD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
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';\nimport { googleAuth } from '../../lib/google-auth.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: googleAuth(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":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","coerce","string","trim","min","describe","body","contentType","ComposeContentTypeSchema","successBranchSchema","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","replyToHdr","headers","fullData","gmail","full","response","error","message","headersArray","fromHdr","toAddr","subject","messageIdHeader","references","replySubject","inReplyTo","refs","mimeType","lines","raw","threadId","ProtocolError","ProtocolErrorCode","InvalidParams","info","google","version","auth","googleAuth","authContext","users","messages","get","userId","format","metadataHeaders","data","Error","String","InternalError","stack","undefined","Array","isArray","payload","Object","fromEntries","map","h","header","name","value","From","from","extractEmails","Subject","References","test","startsWith","filter","Boolean","join","b64url","send","requestBody","content","text","JSON","stringify","structuredContent"],"mappings":";;;;+BA8HA;;;eAAwBA;;;qBA9HiB;2BAEjB;sBAKyB;0BAC1B;mBACL;8BACY;gCACP;4BACI;;;;;;;;;;;;;;;;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AIqB;oBAClE;;wBAAMtC,MAAM2B,KAAK,CAACC,QAAQ,CAACgC,IAAI,CAAC;4BAC9B9B,QAAQ;4BACR+B,aAAa;gCACX7C,KAAKA;+BACDC,YAAY;gCAAEA,UAAAA;4BAAS;wBAE/B;;;oBANA;oBAQArB,OAAOyB,IAAI,CAAC,oCAAoC;wBAAE5C,IAAAA;oBAAG;oBAE/CgB,SAAiB;wBACrBN,MAAM;wBACNV,IAAAA;oBACF;oBAEA;;wBAAO;4BACLqF,OAAO;gCACL;oCACE3E,MAAM;oCACN4E,MAAMC,KAAKC,SAAS,CAACxE;gCACvB;;4BAEFyE,mBAAmB;gCAAEzE,QAAAA;4BAAO;wBAC9B;;;oBACOU;oBACDC,WAAUD,AAAK,YAALA,QAAiB+B,SAAQ/B,OAAMC,OAAO,GAAG+B,OAAOhC;oBAChEP,OAAOO,KAAK,CAAC,+BAA+B;wBAAEA,OAAOC;oBAAQ;oBAE7D,MAAM,IAAIc,qBAAa,CAACC,yBAAiB,CAACiB,aAAa,EAAE,AAAC,gCAAuC,OAARhC,WAAW;wBAClGiC,OAAOlC,AAAK,YAALA,QAAiB+B,SAAQ/B,OAAMkC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASnE;IACtB,OAAO;QACL4E,MAAM;QACNxD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -16,6 +16,7 @@ var _zod = require("zod");
|
|
|
16
16
|
var _constantsts = require("../../constants.js");
|
|
17
17
|
var _htmlprocessingts = require("../../email/parsing/html-processing.js");
|
|
18
18
|
var _executequeryts = require("../../email/querying/execute-query.js");
|
|
19
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
19
20
|
var _gmailqueryschemats = require("../../schemas/gmail-query-schema.js");
|
|
20
21
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
21
22
|
try {
|
|
@@ -272,7 +273,7 @@ function handler(_0, _1) {
|
|
|
272
273
|
});
|
|
273
274
|
gmail = _googleapis.google.gmail({
|
|
274
275
|
version: 'v1',
|
|
275
|
-
auth: extra.authContext.auth
|
|
276
|
+
auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
|
|
276
277
|
});
|
|
277
278
|
started = Date.now();
|
|
278
279
|
return [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-search.ts"],"sourcesContent":["import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\n/** Gmail message search using middleware-based auth pattern */\n\nimport { 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, createPaginationSchema, createShapeSchema, filterFields, parseFields, type ToolModule, toColumnarFormat } from '@mcp-z/server';\nimport { type gmail_v1, google } from 'googleapis';\nimport { z } from 'zod';\nimport { DEFAULT_PAGE_SIZE, MAX_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';\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 fields: createFieldsSchema({\n availableFields: EMAIL_FIELDS,\n fieldDescriptions: EMAIL_FIELD_DESCRIPTIONS,\n commonPatterns: EMAIL_COMMON_PATTERNS,\n resourceName: 'email message',\n }),\n ...createPaginationSchema({ defaultPageSize: DEFAULT_PAGE_SIZE, maxPageSize: MAX_PAGE_SIZE, provider: 'gmail' }).shape,\n shape: createShapeSchema(),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(EmailDetailSchema).describe('Matching email messages'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search Gmail messages using structured query objects with flexible field selection.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ query, pageSize = DEFAULT_PAGE_SIZE, pageToken, fields, shape = 'arrays', contentType = 'text', excludeThreadHistory = false }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseGmailQueryParameter(query);\n const requestedFields = parseFields(fields, EMAIL_FIELDS);\n const includeBody = requestedFields === 'all' || requestedFields.has('body');\n\n logger.info('gmail.message.search called', {\n query: parsedQuery,\n pageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields,\n includeBody,\n accountId: extra.authContext.accountId, // Available from middleware\n });\n\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n\n const started = Date.now();\n\n const exec = await executeGmailQuery(\n parsedQuery,\n {\n client: gmail,\n logger,\n pageSize,\n ...(pageToken !== undefined && { pageToken }),\n includeBody,\n },\n (full: unknown) => {\n // Type-safe property access with guards\n const fullData = full as gmail_v1.Schema$Message;\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 gmail_v1.Schema$MessagePartHeader;\n return [String(header.name ?? ''), String(header.value ?? '')];\n })\n );\n\n const mapped: Partial<EmailDetail> = {\n id: String(fullData?.id ?? ''),\n threadId: fullData?.threadId ? String(fullData.threadId) : undefined,\n from: headers?.From,\n to: headers?.To,\n subject: headers?.Subject,\n date: headers?.Date,\n snippet: fullData?.snippet ? String(fullData.snippet) : undefined,\n };\n\n if (includeBody) {\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 if (body) {\n mapped.body = body;\n mapped.bodyContentType = contentType;\n }\n }\n return mapped;\n }\n );\n\n const items = exec.items;\n const metadata = exec.metadata;\n const durationMs = Date.now() - started;\n\n // Type-safe field filtering\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('gmail.message.search results', { query, pageSize, resultCount: filteredItems.length, fields: fields || 'all' });\n logger.info('gmail.message.search metrics', { durationMs, metadata });\n\n // Type-safe metadata access\n const metadataObj = metadata as { nextPageToken?: string } | undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, EMAIL_FIELDS),\n ...(metadataObj?.nextPageToken && { nextPageToken: metadataObj.nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n ...(metadataObj?.nextPageToken && { nextPageToken: metadataObj.nextPageToken }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.message.search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching messages: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","GmailQueryParameterSchema","optional","describe","fields","createFieldsSchema","availableFields","EMAIL_FIELDS","fieldDescriptions","EMAIL_FIELD_DESCRIPTIONS","commonPatterns","EMAIL_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","DEFAULT_PAGE_SIZE","maxPageSize","MAX_PAGE_SIZE","provider","shape","createShapeSchema","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successObjectsBranchSchema","type","literal","items","array","EmailDetailSchema","nextPageToken","string","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","description","result","handler","extra","pageSize","pageToken","logger","parsedQuery","requestedFields","includeBody","gmail","started","exec","metadata","durationMs","filteredItems","metadataObj","error","message","parseGmailQueryParameter","parseFields","has","info","undefined","accountId","authContext","google","version","auth","Date","now","executeGmailQuery","client","full","fullData","headersArray","Array","isArray","payload","headers","Object","fromEntries","map","h","header","String","name","value","mapped","id","threadId","from","From","to","To","subject","Subject","date","snippet","body","extractBodyFromPayload","bodyContentType","item","filterFields","resultCount","length","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BA+KA;;;eAAwBA;;;sBA/KyB;qBAGsH;2BAE/I;0BAKc;mBACpB;2BAC+B;gCACV;8BACW;kCACkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARpE,IAAM,AAAEC,2BAA6BC,o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D,UAAW;wBAC/F0D,OAAO3D,AAAK,YAALA,OAAiBuD,SAAQvD,MAAM2D,KAAK,GAAGrD;oBAChD;;;;;;;IAEJ;;AAEe,SAASrE;IACtB,OAAO;QACL4F,MAAM;QACN/C,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-search.ts"],"sourcesContent":["import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\n/** Gmail message search using middleware-based auth pattern */\n\nimport { 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, createPaginationSchema, createShapeSchema, filterFields, parseFields, type ToolModule, toColumnarFormat } from '@mcp-z/server';\nimport { type gmail_v1, google } from 'googleapis';\nimport { z } from 'zod';\nimport { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from '../../constants.ts';\nimport { extractBodyFromPayload } from '../../email/parsing/html-processing.ts';\nimport { executeQuery as executeGmailQuery } from '../../email/querying/execute-query.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\nimport { GmailQueryParameterSchema, parseGmailQueryParameter } from '../../schemas/gmail-query-schema.ts';\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 fields: createFieldsSchema({\n availableFields: EMAIL_FIELDS,\n fieldDescriptions: EMAIL_FIELD_DESCRIPTIONS,\n commonPatterns: EMAIL_COMMON_PATTERNS,\n resourceName: 'email message',\n }),\n ...createPaginationSchema({ defaultPageSize: DEFAULT_PAGE_SIZE, maxPageSize: MAX_PAGE_SIZE, provider: 'gmail' }).shape,\n shape: createShapeSchema(),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schemas for different shapes\nconst successObjectsBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('objects'),\n items: z.array(EmailDetailSchema).describe('Matching email messages'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\nconst successArraysBranchSchema = z.object({\n type: z.literal('success'),\n shape: z.literal('arrays'),\n columns: z.array(z.string()).describe('Column names in canonical order'),\n rows: z.array(z.array(z.unknown())).describe('Row data matching column order'),\n nextPageToken: z.string().optional().describe('Token for fetching next page of results'),\n});\n\n// Output schema with auth_required support\n// Using z.union instead of discriminatedUnion since we have two success branches with different shapes\nconst outputSchema = z.union([successObjectsBranchSchema, successArraysBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Search Gmail messages using structured query objects with flexible field selection.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ query, pageSize = DEFAULT_PAGE_SIZE, pageToken, fields, shape = 'arrays', contentType = 'text', excludeThreadHistory = false }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n\n try {\n const parsedQuery = parseGmailQueryParameter(query);\n const requestedFields = parseFields(fields, EMAIL_FIELDS);\n const includeBody = requestedFields === 'all' || requestedFields.has('body');\n\n logger.info('gmail.message.search called', {\n query: parsedQuery,\n pageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields,\n includeBody,\n accountId: extra.authContext.accountId, // Available from middleware\n });\n\n const gmail = google.gmail({ version: 'v1', auth: googleAuth(extra.authContext.auth) });\n\n const started = Date.now();\n\n const exec = await executeGmailQuery(\n parsedQuery,\n {\n client: gmail,\n logger,\n pageSize,\n ...(pageToken !== undefined && { pageToken }),\n includeBody,\n },\n (full: unknown) => {\n // Type-safe property access with guards\n const fullData = full as gmail_v1.Schema$Message;\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 gmail_v1.Schema$MessagePartHeader;\n return [String(header.name ?? ''), String(header.value ?? '')];\n })\n );\n\n const mapped: Partial<EmailDetail> = {\n id: String(fullData?.id ?? ''),\n threadId: fullData?.threadId ? String(fullData.threadId) : undefined,\n from: headers?.From,\n to: headers?.To,\n subject: headers?.Subject,\n date: headers?.Date,\n snippet: fullData?.snippet ? String(fullData.snippet) : undefined,\n };\n\n if (includeBody) {\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 if (body) {\n mapped.body = body;\n mapped.bodyContentType = contentType;\n }\n }\n return mapped;\n }\n );\n\n const items = exec.items;\n const metadata = exec.metadata;\n const durationMs = Date.now() - started;\n\n // Type-safe field filtering\n const filteredItems = items.map((item) => filterFields(item, requestedFields));\n\n logger.info('gmail.message.search results', { query, pageSize, resultCount: filteredItems.length, fields: fields || 'all' });\n logger.info('gmail.message.search metrics', { durationMs, metadata });\n\n // Type-safe metadata access\n const metadataObj = metadata as { nextPageToken?: string } | undefined;\n\n // Build result based on shape\n const result: Output =\n shape === 'arrays'\n ? {\n type: 'success' as const,\n shape: 'arrays' as const,\n ...toColumnarFormat(filteredItems, requestedFields, EMAIL_FIELDS),\n ...(metadataObj?.nextPageToken && { nextPageToken: metadataObj.nextPageToken }),\n }\n : {\n type: 'success' as const,\n shape: 'objects' as const,\n items: filteredItems,\n ...(metadataObj?.nextPageToken && { nextPageToken: metadataObj.nextPageToken }),\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.message.search error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error searching messages: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-search',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","query","GmailQueryParameterSchema","optional","describe","fields","createFieldsSchema","availableFields","EMAIL_FIELDS","fieldDescriptions","EMAIL_FIELD_DESCRIPTIONS","commonPatterns","EMAIL_COMMON_PATTERNS","resourceName","createPaginationSchema","defaultPageSize","DEFAULT_PAGE_SIZE","maxPageSize","MAX_PAGE_SIZE","provider","shape","createShapeSchema","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successObjectsBranchSchema","type","literal","items","array","EmailDetailSchema","nextPageToken","string","successArraysBranchSchema","columns","rows","unknown","outputSchema","union","config","description","result","handler","extra","pageSize","pageToken","logger","parsedQuery","requestedFields","includeBody","gmail","started","exec","metadata","durationMs","filteredItems","metadataObj","error","message","parseGmailQueryParameter","parseFields","has","info","undefined","accountId","authContext","google","version","auth","googleAuth","Date","now","executeGmailQuery","client","full","fullData","headersArray","Array","isArray","payload","headers","Object","fromEntries","map","h","header","String","name","value","mapped","id","threadId","from","From","to","To","subject","Subject","date","snippet","body","extractBodyFromPayload","bodyContentType","item","filterFields","resultCount","length","toColumnarFormat","content","text","JSON","stringify","structuredContent","Error","ProtocolError","ProtocolErrorCode","InternalError","stack"],"mappings":";;;;+BAgLA;;;eAAwBA;;;sBAhLyB;qBAGsH;2BAE/I;0BAKc;mBACpB;2BAC+B;gCACV;8BACW;4BACvB;kCACyC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AM,IAAIwD,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,6BAAoC,OAAR1D,UAAW;wBAC/F2D,OAAO5D,AAAK,YAALA,OAAiBwD,SAAQxD,MAAM4D,KAAK,GAAGtD;oBAChD;;;;;;;IAEJ;;AAEe,SAASrE;IACtB,OAAO;QACL6F,MAAM;QACNhD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -15,6 +15,7 @@ var _googleapis = require("googleapis");
|
|
|
15
15
|
var _zod = require("zod");
|
|
16
16
|
var _rfc822builderts = require("../../email/composition/rfc822-builder.js");
|
|
17
17
|
var _base64encodingts = require("../../lib/base64-encoding.js");
|
|
18
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
18
19
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
19
20
|
try {
|
|
20
21
|
var info = gen[key](arg);
|
|
@@ -210,7 +211,7 @@ function handler(params, extra) {
|
|
|
210
211
|
encodedMessage = (0, _base64encodingts.b64url)(raw);
|
|
211
212
|
gmail = _googleapis.google.gmail({
|
|
212
213
|
version: 'v1',
|
|
213
|
-
auth: extra.authContext.auth
|
|
214
|
+
auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
|
|
214
215
|
});
|
|
215
216
|
return [
|
|
216
217
|
4,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-send.ts"],"sourcesContent":["import { ComposeContentTypeSchema, createEmailRecipientsSchema, createMessageResultSchema } 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 { buildRfc822FromArgs } from '../../email/composition/rfc822-builder.ts';\nimport { b64url } from '../../lib/base64-encoding.ts';\n\nconst inputSchema = z.object({\n to: createEmailRecipientsSchema('to', true),\n cc: createEmailRecipientsSchema('cc', false),\n bcc: createEmailRecipientsSchema('bcc', false),\n subject: z.string().describe('Message subject').default(''),\n body: z.string().trim().min(1).describe('Email body content (plain text or HTML)'),\n contentType: ComposeContentTypeSchema,\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n item: createMessageResultSchema('gmail'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Send an email message through Gmail',\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(params: Input, extra: EnrichedExtra) {\n const { to, cc, bcc, subject, body, contentType } = params;\n const logger = extra.logger;\n logger.info('gmail.message.send called', { to, subject, contentType });\n\n if (!to) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing required field: to');\n }\n\n try {\n // Build RFC822 message - only include optional headers when defined to satisfy\n // exactOptionalPropertyTypes (avoid passing `undefined` into optional props)\n const msgArgs: { to: string; cc?: string; bcc?: string; subject?: string; body: string; contentType: 'text' | 'html' } = { to, body, contentType };\n if (cc !== undefined) msgArgs.cc = cc;\n if (bcc !== undefined) msgArgs.bcc = bcc;\n if (subject !== undefined) msgArgs.subject = subject;\n\n const raw = buildRfc822FromArgs(msgArgs);\n const encodedMessage = b64url(raw);\n\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n\n const sendRes = await gmail.users.messages.send({\n userId: 'me',\n requestBody: { raw: encodedMessage },\n });\n const sendData = sendRes.data;\n const messageId = sendData.id || 'unknown';\n logger.info('Gmail: sent message successfully', { id: messageId });\n logger.info('gmail.message.send result (typed)', { to, subject, messageId });\n\n const totalRecipients = (Array.isArray(to) ? to.length : 1) + (cc ? (Array.isArray(cc) ? cc.length : 1) : 0) + (bcc ? (Array.isArray(bcc) ? bcc.length : 1) : 0);\n const result: Output = {\n type: 'success' as const,\n item: {\n id: messageId,\n sentAt: new Date().toISOString(),\n recipientCount: totalRecipients,\n webLink: `https://mail.google.com/mail/u/0/#sent/${messageId}`,\n },\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.send error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error sending message: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-send',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","to","createEmailRecipientsSchema","cc","bcc","subject","string","describe","default","body","trim","min","contentType","ComposeContentTypeSchema","successBranchSchema","type","literal","item","createMessageResultSchema","outputSchema","discriminatedUnion","config","description","result","handler","params","extra","logger","msgArgs","raw","encodedMessage","gmail","sendRes","sendData","messageId","totalRecipients","error","message","info","ProtocolError","ProtocolErrorCode","InvalidParams","undefined","buildRfc822FromArgs","b64url","google","version","auth","authContext","users","messages","send","userId","requestBody","data","id","Array","isArray","length","sentAt","Date","toISOString","recipientCount","webLink","content","text","JSON","stringify","structuredContent","Error","String","InternalError","stack","name"],"mappings":";;;;+
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-send.ts"],"sourcesContent":["import { ComposeContentTypeSchema, createEmailRecipientsSchema, createMessageResultSchema } 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 { buildRfc822FromArgs } from '../../email/composition/rfc822-builder.ts';\nimport { b64url } from '../../lib/base64-encoding.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nconst inputSchema = z.object({\n to: createEmailRecipientsSchema('to', true),\n cc: createEmailRecipientsSchema('cc', false),\n bcc: createEmailRecipientsSchema('bcc', false),\n subject: z.string().describe('Message subject').default(''),\n body: z.string().trim().min(1).describe('Email body content (plain text or HTML)'),\n contentType: ComposeContentTypeSchema,\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n item: createMessageResultSchema('gmail'),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Send an email message through Gmail',\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(params: Input, extra: EnrichedExtra) {\n const { to, cc, bcc, subject, body, contentType } = params;\n const logger = extra.logger;\n logger.info('gmail.message.send called', { to, subject, contentType });\n\n if (!to) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing required field: to');\n }\n\n try {\n // Build RFC822 message - only include optional headers when defined to satisfy\n // exactOptionalPropertyTypes (avoid passing `undefined` into optional props)\n const msgArgs: { to: string; cc?: string; bcc?: string; subject?: string; body: string; contentType: 'text' | 'html' } = { to, body, contentType };\n if (cc !== undefined) msgArgs.cc = cc;\n if (bcc !== undefined) msgArgs.bcc = bcc;\n if (subject !== undefined) msgArgs.subject = subject;\n\n const raw = buildRfc822FromArgs(msgArgs);\n const encodedMessage = b64url(raw);\n\n const gmail = google.gmail({ version: 'v1', auth: googleAuth(extra.authContext.auth) });\n\n const sendRes = await gmail.users.messages.send({\n userId: 'me',\n requestBody: { raw: encodedMessage },\n });\n const sendData = sendRes.data;\n const messageId = sendData.id || 'unknown';\n logger.info('Gmail: sent message successfully', { id: messageId });\n logger.info('gmail.message.send result (typed)', { to, subject, messageId });\n\n const totalRecipients = (Array.isArray(to) ? to.length : 1) + (cc ? (Array.isArray(cc) ? cc.length : 1) : 0) + (bcc ? (Array.isArray(bcc) ? bcc.length : 1) : 0);\n const result: Output = {\n type: 'success' as const,\n item: {\n id: messageId,\n sentAt: new Date().toISOString(),\n recipientCount: totalRecipients,\n webLink: `https://mail.google.com/mail/u/0/#sent/${messageId}`,\n },\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.send error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error sending message: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-send',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","to","createEmailRecipientsSchema","cc","bcc","subject","string","describe","default","body","trim","min","contentType","ComposeContentTypeSchema","successBranchSchema","type","literal","item","createMessageResultSchema","outputSchema","discriminatedUnion","config","description","result","handler","params","extra","logger","msgArgs","raw","encodedMessage","gmail","sendRes","sendData","messageId","totalRecipients","error","message","info","ProtocolError","ProtocolErrorCode","InvalidParams","undefined","buildRfc822FromArgs","b64url","google","version","auth","googleAuth","authContext","users","messages","send","userId","requestBody","data","id","Array","isArray","length","sentAt","Date","toISOString","recipientCount","webLink","content","text","JSON","stringify","structuredContent","Error","String","InternalError","stack","name"],"mappings":";;;;+BAwGA;;;eAAwBA;;;qBAxGyE;2BAEzE;sBAKyB;0BAC1B;mBACL;+BACkB;gCACb;4BACI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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SAAiB;wBACrBR,MAAM;wBACNE,MAAM;4BACJuC,IAAItB;4BACJ0B,QAAQ,IAAIC,OAAOC,WAAW;4BAC9BC,gBAAgB5B;4BAChB6B,SAAS,AAAC,0CAAmD,OAAV9B;wBACrD;oBACF;oBAEA;;wBAAO;4BACL+B,OAAO;gCACL;oCACElD,MAAM;oCACNmD,MAAMC,KAAKC,SAAS,CAAC7C;gCACvB;;4BAEF8C,mBAAmB;gCAAE9C,QAAAA;4BAAO;wBAC9B;;;oBACOa;oBACDC,UAAUD,AAAK,YAALA,OAAiBkC,SAAQlC,MAAMC,OAAO,GAAGkC,OAAOnC;oBAChET,OAAOS,KAAK,CAAC,4BAA4B;wBAAEA,OAAOC;oBAAQ;oBAE1D,MAAM,IAAIE,qBAAa,CAACC,yBAAiB,CAACgC,aAAa,EAAE,AAAC,0BAAiC,OAARnC,UAAW;wBAC5FoC,OAAOrC,AAAK,YAALA,OAAiBkC,SAAQlC,MAAMqC,KAAK,GAAG/B;oBAChD;;;;;;;IAEJ;;AAEe,SAAS/C;IACtB,OAAO;QACL+E,MAAM;QACNrD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -19,6 +19,7 @@ var _zod = require("zod");
|
|
|
19
19
|
var _constantsts = require("../../constants.js");
|
|
20
20
|
var _htmlprocessingts = require("../../email/parsing/html-processing.js");
|
|
21
21
|
var _executequeryts = require("../../email/querying/execute-query.js");
|
|
22
|
+
var _googleauthts = require("../../lib/google-auth.js");
|
|
22
23
|
var _gmailqueryschemats = require("../../schemas/gmail-query-schema.js");
|
|
23
24
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
24
25
|
try {
|
|
@@ -277,7 +278,7 @@ var config = {
|
|
|
277
278
|
});
|
|
278
279
|
gmail = _googleapis.google.gmail({
|
|
279
280
|
version: 'v1',
|
|
280
|
-
auth: extra.authContext.auth
|
|
281
|
+
auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
|
|
281
282
|
});
|
|
282
283
|
// Create CSV headers (all email fields)
|
|
283
284
|
csvHeaders = [
|
|
@@ -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, 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,CA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BAAS;;;;;;oBAGzEiB,UAAUF,AAAK,YAALA,OAAiBmF,SAAQnF,MAAME,OAAO,GAAGsC,OAAOxC;oBAChEtB,OAAOsB,KAAK,CAAC,mCAAmC;wBAAEA,OAAOE;oBAAQ;oBAEjE,MAAM,IAAIkF,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,oCAA2C,OAARpF,UAAW;wBACtGqF,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 { googleAuth } from '../../lib/google-auth.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: googleAuth(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","googleAuth","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":";;;;+BAsQA;;;eAAwBA;;;qBAtQ2C;2BAE3C;sBAImE;oBAEjE;kBACQ;wB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ACNE,KAAAA;wBACAX,UAAU4B;wBACVhB,UAAUuB;wBACVtB,WAAAA;oBACF;oBAEA;;wBAAO;4BACL6G,OAAO;gCACL;oCACEjH,MAAM;oCACNkH,MAAMC,KAAKjE,SAAS,CAACxC;gCACvB;;4BAEF0G,mBAAmB;gCAAE1G,QAAAA;4BAAO;wBAC9B;;;oBACOyB;;;;;;;;;oBAGL;;wBAAMkF,IAAAA,gBAAM,EAACjG;;;oBAAb;oBACAP,OAAOyG,KAAK,CAAC,2CAA2C;wBAAE9E,MAAMpB;oBAAS;;;;;;oBAClEgB;oBACPvB,OAAOyG,KAAK,CAAC,+CAA+C;wBAAE9E,MAAMpB;oBAAS;;;;;;oBAGzEiB,UAAUF,AAAK,YAALA,OAAiBoF,SAAQpF,MAAME,OAAO,GAAGuC,OAAOzC;oBAChEtB,OAAOsB,KAAK,CAAC,mCAAmC;wBAAEA,OAAOE;oBAAQ;oBAEjE,MAAM,IAAImF,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,oCAA2C,OAARrF,UAAW;wBACtGsF,OAAOxF,AAAK,YAALA,OAAiBoF,SAAQpF,MAAMwF,KAAK,GAAG7D;oBAChD;;;;;;;IAEJ;;AAEe,SAASzF;IACtB,OAAO;QACLwG,MAAM;QACNrE,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type GoogleAuthProvider } from '@mcp-z/oauth-google';
|
|
2
|
+
/**
|
|
3
|
+
* A Google API client bound to this request's token provider.
|
|
4
|
+
*
|
|
5
|
+
* `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client
|
|
6
|
+
* is built here, from this package's own `googleapis`. That keeps one copy of
|
|
7
|
+
* `google-auth-library` in the tree by construction rather than by matching pins.
|
|
8
|
+
*/
|
|
9
|
+
export declare function googleAuth(auth: GoogleAuthProvider): import("google-auth-library").OAuth2Client;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { attachTokenProvider } from '@mcp-z/oauth-google';
|
|
2
|
+
import { google } from 'googleapis';
|
|
3
|
+
/**
|
|
4
|
+
* A Google API client bound to this request's token provider.
|
|
5
|
+
*
|
|
6
|
+
* `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client
|
|
7
|
+
* is built here, from this package's own `googleapis`. That keeps one copy of
|
|
8
|
+
* `google-auth-library` in the tree by construction rather than by matching pins.
|
|
9
|
+
*/ export function googleAuth(auth) {
|
|
10
|
+
return attachTokenProvider(new google.auth.OAuth2(), auth);
|
|
11
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/lib/google-auth.ts"],"sourcesContent":["import { attachTokenProvider, type GoogleAuthProvider } from '@mcp-z/oauth-google';\nimport { google } from 'googleapis';\n\n/**\n * A Google API client bound to this request's token provider.\n *\n * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client\n * is built here, from this package's own `googleapis`. That keeps one copy of\n * `google-auth-library` in the tree by construction rather than by matching pins.\n */\nexport function googleAuth(auth: GoogleAuthProvider) {\n return attachTokenProvider(new google.auth.OAuth2(), auth);\n}\n"],"names":["attachTokenProvider","google","googleAuth","auth","OAuth2"],"mappings":"AAAA,SAASA,mBAAmB,QAAiC,sBAAsB;AACnF,SAASC,MAAM,QAAQ,aAAa;AAEpC;;;;;;CAMC,GACD,OAAO,SAASC,WAAWC,IAAwB;IACjD,OAAOH,oBAAoB,IAAIC,OAAOE,IAAI,CAACC,MAAM,IAAID;AACvD"}
|
|
@@ -2,6 +2,7 @@ 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';
|
|
5
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
5
6
|
export default function createResource() {
|
|
6
7
|
const template = new ResourceTemplate('gmail://messages/{id}', {
|
|
7
8
|
list: undefined
|
|
@@ -18,7 +19,7 @@ export default function createResource() {
|
|
|
18
19
|
logger.info(variables, 'gmail-email resource fetch');
|
|
19
20
|
const gmail = google.gmail({
|
|
20
21
|
version: 'v1',
|
|
21
|
-
auth: authContext.auth
|
|
22
|
+
auth: googleAuth(authContext.auth)
|
|
22
23
|
});
|
|
23
24
|
const response = await gmail.users.messages.get({
|
|
24
25
|
userId: 'me',
|
|
@@ -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 { 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;
|
|
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';\nimport { googleAuth } from '../../lib/google-auth.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: googleAuth(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","googleAuth","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;AACxD,SAASC,UAAU,QAAQ,2BAA2B;AAEtD,eAAe,SAASC;IACtB,MAAMC,WAAW,IAAIP,iBAAiB,yBAAyB;QAC7DQ,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,QAAQrB,OAAOqB,KAAK,CAAC;gBAAEC,SAAS;gBAAMC,MAAMnB,WAAWe,YAAYI,IAAI;YAAE;YAC/E,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,MAAM;YAClB;YAE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C;4BAAEE,OAAOtB,eAAOsB,kBAAAA,4BAAAA,MAAOC,OAAO,uCAAIF;wBAAG;oBAC5D;iBACD;YACH;QACF;IACF;IAEA,OAAO;QACLpB,MAAM;QACNvC;QACAG;QACAG;IACF;AACF"}
|
|
@@ -3,6 +3,7 @@ const { AuthRequiredBranchSchema } = schemas;
|
|
|
3
3
|
import { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';
|
|
4
4
|
import { google } from 'googleapis';
|
|
5
5
|
import { z } from 'zod';
|
|
6
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
6
7
|
// Schema for individual category items
|
|
7
8
|
const CategorySchema = z.object({
|
|
8
9
|
id: z.string().describe('Gmail category ID (e.g., CATEGORY_PERSONAL)'),
|
|
@@ -35,7 +36,7 @@ async function handler(_, extra) {
|
|
|
35
36
|
try {
|
|
36
37
|
const gmail = google.gmail({
|
|
37
38
|
version: 'v1',
|
|
38
|
-
auth: extra.authContext.auth
|
|
39
|
+
auth: googleAuth(extra.authContext.auth)
|
|
39
40
|
});
|
|
40
41
|
const started = Date.now();
|
|
41
42
|
// Fetch all labels from Gmail API
|
|
@@ -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 { 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;
|
|
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';\nimport { googleAuth } from '../../lib/google-auth.ts';\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: googleAuth(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","googleAuth","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;AACxB,SAASC,UAAU,QAAQ,2BAA2B;AAEtD,uCAAuC;AACvC,MAAMC,iBAAiBF,EAAEG,MAAM,CAAC;IAC9BC,IAAIJ,EAAEK,MAAM,GAAGC,QAAQ,CAAC;IACxBC,MAAMP,EAAEK,MAAM,GAAGC,QAAQ,CAA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cp-z/server';
|
|
|
4
4
|
import { google } from 'googleapis';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { ensureLabelId } from '../../labels/gmail-labels.js';
|
|
7
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
7
8
|
const inputSchema = z.object({
|
|
8
9
|
id: z.coerce.string().trim().min(1).describe('Gmail message ID to add label to'),
|
|
9
10
|
label: z.coerce.string().trim().min(1).describe('Label name or ID (use gmail-labels-list to discover available labels)')
|
|
@@ -44,7 +45,7 @@ async function handler({ id, label }, extra) {
|
|
|
44
45
|
try {
|
|
45
46
|
const gmail = google.gmail({
|
|
46
47
|
version: 'v1',
|
|
47
|
-
auth: extra.authContext.auth
|
|
48
|
+
auth: googleAuth(extra.authContext.auth)
|
|
48
49
|
});
|
|
49
50
|
const labelId = await ensureLabelId(gmail, 'me', label);
|
|
50
51
|
await gmail.users.messages.modify({
|
|
@@ -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 { 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;
|
|
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';\nimport { googleAuth } from '../../lib/google-auth.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: googleAuth(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","googleAuth","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;AAC7D,SAASC,UAAU,QAAQ,2BAA2B;AAEtD,MAAMC,cAAcH,EAAEI,MAAM,CAAC;IAC3BC,IAAIL,EAAEM,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,OAAOX,EAAEM,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAClD;AAEA,wBAAwB;AACxB,MAAME,sBAAsBZ,E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ExB,MAAM;oBACNyB,MAAMC,KAAKC,SAAS,CAACpB;gBACvB;aACD;YACDqB,mBAAmB;gBAAErB;YAAO;QAC9B;IACF,EAAE,OAAOsB,OAAO;QACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGE,OAAOH;QAChEnB,OAAOmB,KAAK,CAAC,yBAAyB;YAAEA,OAAOC;QAAQ;QAEvD,MAAM,IAAI9C,cAAcC,kBAAkBgD,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"}
|
|
@@ -4,6 +4,7 @@ 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';
|
|
7
|
+
import { googleAuth } from '../../lib/google-auth.js';
|
|
7
8
|
const inputSchema = z.object({
|
|
8
9
|
ids: z.array(z.coerce.string().trim().min(1)).min(1).describe('Gmail label IDs to delete')
|
|
9
10
|
});
|
|
@@ -66,7 +67,7 @@ async function handler({ ids }, extra) {
|
|
|
66
67
|
try {
|
|
67
68
|
const gmail = google.gmail({
|
|
68
69
|
version: 'v1',
|
|
69
|
-
auth: extra.authContext.auth
|
|
70
|
+
auth: googleAuth(extra.authContext.auth)
|
|
70
71
|
});
|
|
71
72
|
// Get all labels first to check for system labels
|
|
72
73
|
const labelsResponse = await gmail.users.labels.list({
|