@mcp-z/mcp-gmail 1.1.3 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/mcp/prompts/draft-email.d.cts +2 -3
- package/dist/cjs/mcp/prompts/draft-email.d.ts +2 -3
- package/dist/cjs/mcp/prompts/draft-email.js.map +1 -1
- package/dist/cjs/mcp/prompts/query-syntax.d.cts +2 -3
- package/dist/cjs/mcp/prompts/query-syntax.d.ts +2 -3
- package/dist/cjs/mcp/prompts/query-syntax.js.map +1 -1
- package/dist/cjs/mcp/resources/email.d.cts +6 -5
- package/dist/cjs/mcp/resources/email.d.ts +6 -5
- package/dist/cjs/mcp/resources/email.js +2 -2
- package/dist/cjs/mcp/resources/email.js.map +1 -1
- package/dist/cjs/mcp/tools/categories-list.js +2 -2
- package/dist/cjs/mcp/tools/categories-list.js.map +1 -1
- package/dist/cjs/mcp/tools/label-add.js +3 -3
- package/dist/cjs/mcp/tools/label-add.js.map +1 -1
- package/dist/cjs/mcp/tools/label-delete.js +6 -6
- package/dist/cjs/mcp/tools/label-delete.js.map +1 -1
- package/dist/cjs/mcp/tools/labels-list.d.cts +3 -3
- package/dist/cjs/mcp/tools/labels-list.d.ts +3 -3
- package/dist/cjs/mcp/tools/labels-list.js +2 -2
- package/dist/cjs/mcp/tools/labels-list.js.map +1 -1
- package/dist/cjs/mcp/tools/message-get.js +3 -4
- package/dist/cjs/mcp/tools/message-get.js.map +1 -1
- package/dist/cjs/mcp/tools/message-mark-read.js +3 -3
- package/dist/cjs/mcp/tools/message-mark-read.js.map +1 -1
- package/dist/cjs/mcp/tools/message-move-to-trash.js +6 -6
- package/dist/cjs/mcp/tools/message-move-to-trash.js.map +1 -1
- package/dist/cjs/mcp/tools/message-respond.js +4 -4
- package/dist/cjs/mcp/tools/message-respond.js.map +1 -1
- package/dist/cjs/mcp/tools/message-search.js +2 -3
- package/dist/cjs/mcp/tools/message-search.js.map +1 -1
- package/dist/cjs/mcp/tools/message-send.js +3 -3
- package/dist/cjs/mcp/tools/message-send.js.map +1 -1
- package/dist/cjs/mcp/tools/messages-export-csv.js +1 -2
- package/dist/cjs/mcp/tools/messages-export-csv.js.map +1 -1
- package/dist/cjs/setup/http.d.cts +1 -1
- package/dist/cjs/setup/http.d.ts +1 -1
- package/dist/cjs/setup/http.js +1 -2
- package/dist/cjs/setup/http.js.map +1 -1
- package/dist/cjs/setup/stdio.d.cts +1 -1
- package/dist/cjs/setup/stdio.d.ts +1 -1
- package/dist/cjs/setup/stdio.js +1 -2
- package/dist/cjs/setup/stdio.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/mcp/prompts/draft-email.d.ts +2 -3
- package/dist/esm/mcp/prompts/draft-email.js.map +1 -1
- package/dist/esm/mcp/prompts/query-syntax.d.ts +2 -3
- package/dist/esm/mcp/prompts/query-syntax.js.map +1 -1
- package/dist/esm/mcp/resources/email.d.ts +6 -5
- package/dist/esm/mcp/resources/email.js +1 -1
- package/dist/esm/mcp/resources/email.js.map +1 -1
- package/dist/esm/mcp/tools/categories-list.js +2 -2
- package/dist/esm/mcp/tools/categories-list.js.map +1 -1
- package/dist/esm/mcp/tools/label-add.js +3 -3
- package/dist/esm/mcp/tools/label-add.js.map +1 -1
- package/dist/esm/mcp/tools/label-delete.js +6 -6
- package/dist/esm/mcp/tools/label-delete.js.map +1 -1
- package/dist/esm/mcp/tools/labels-list.d.ts +3 -3
- package/dist/esm/mcp/tools/labels-list.js +2 -2
- package/dist/esm/mcp/tools/labels-list.js.map +1 -1
- package/dist/esm/mcp/tools/message-get.js +4 -5
- package/dist/esm/mcp/tools/message-get.js.map +1 -1
- package/dist/esm/mcp/tools/message-mark-read.js +3 -3
- package/dist/esm/mcp/tools/message-mark-read.js.map +1 -1
- package/dist/esm/mcp/tools/message-move-to-trash.js +6 -6
- package/dist/esm/mcp/tools/message-move-to-trash.js.map +1 -1
- package/dist/esm/mcp/tools/message-respond.js +4 -4
- package/dist/esm/mcp/tools/message-respond.js.map +1 -1
- package/dist/esm/mcp/tools/message-search.js +2 -2
- package/dist/esm/mcp/tools/message-search.js.map +1 -1
- package/dist/esm/mcp/tools/message-send.js +3 -3
- package/dist/esm/mcp/tools/message-send.js.map +1 -1
- package/dist/esm/mcp/tools/messages-export-csv.js +2 -3
- package/dist/esm/mcp/tools/messages-export-csv.js.map +1 -1
- package/dist/esm/setup/http.d.ts +1 -1
- package/dist/esm/setup/http.js +1 -2
- package/dist/esm/setup/http.js.map +1 -1
- package/dist/esm/setup/stdio.d.ts +1 -1
- package/dist/esm/setup/stdio.js +1 -2
- package/dist/esm/setup/stdio.js.map +1 -1
- package/package.json +7 -7
|
@@ -11,7 +11,6 @@ Object.defineProperty(exports, "default", {
|
|
|
11
11
|
var _email = require("@mcp-z/email");
|
|
12
12
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
13
13
|
var _server = require("@mcp-z/server");
|
|
14
|
-
var _types = require("@modelcontextprotocol/sdk/types.js");
|
|
15
14
|
var _googleapis = require("googleapis");
|
|
16
15
|
var _zod = require("zod");
|
|
17
16
|
var _messageextractionts = require("../../email/parsing/message-extraction.js");
|
|
@@ -198,7 +197,7 @@ function handler(_0, _1) {
|
|
|
198
197
|
4
|
|
199
198
|
]);
|
|
200
199
|
if (!id) {
|
|
201
|
-
throw new
|
|
200
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'Missing id');
|
|
202
201
|
}
|
|
203
202
|
gmail = _googleapis.google.gmail({
|
|
204
203
|
version: 'v1',
|
|
@@ -224,7 +223,7 @@ function handler(_0, _1) {
|
|
|
224
223
|
response = _state.sent();
|
|
225
224
|
fullData = response.data;
|
|
226
225
|
if (!fullData) {
|
|
227
|
-
throw new
|
|
226
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidRequest, 'Message not found');
|
|
228
227
|
}
|
|
229
228
|
// Build full message data with type guards
|
|
230
229
|
headers = fullData === null || fullData === void 0 ? void 0 : (_fullData_payload = fullData.payload) === null || _fullData_payload === void 0 ? void 0 : _fullData_payload.headers;
|
|
@@ -292,7 +291,7 @@ function handler(_0, _1) {
|
|
|
292
291
|
logger.error('gmail.message.get error', {
|
|
293
292
|
error: message
|
|
294
293
|
});
|
|
295
|
-
throw new
|
|
294
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error getting message: ".concat(message), {
|
|
296
295
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
297
296
|
});
|
|
298
297
|
case 4:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-get.ts"],"sourcesContent":["import { EMAIL_COMMON_PATTERNS, EMAIL_FIELD_DESCRIPTIONS, EMAIL_FIELDS, EmailContentTypeSchema, type EmailDetail, EmailDetailSchema, ExcludeThreadHistorySchema } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { createFieldsSchema, filterFields, parseFields, type ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { type gmail_v1, google } from 'googleapis';\nimport { z } from 'zod';\nimport { extractBodyFromPayload, extractEmails, extractFrom } from '../../email/parsing/message-extraction.ts';\nimport { toIsoUtc } from '../../lib/date-conversion.ts';\n\nconst inputSchema = z.object({\n id: z.coerce.string().trim().min(1).describe('Gmail message ID to retrieve'),\n fields: createFieldsSchema({\n availableFields: EMAIL_FIELDS,\n fieldDescriptions: EMAIL_FIELD_DESCRIPTIONS,\n commonPatterns: EMAIL_COMMON_PATTERNS,\n resourceName: 'email message',\n }),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n item: EmailDetailSchema,\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Get a Gmail message by ID with flexible field selection',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, fields, contentType, excludeThreadHistory }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n\n const requestedFields = parseFields(fields, EMAIL_FIELDS);\n\n logger.info('gmail.message.get called', { id: Boolean(id), fields: fields || 'all' });\n\n try {\n if (!id) {\n throw new McpError(ErrorCode.InvalidParams, 'Missing id');\n }\n\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n const response = await gmail.users.messages.get({\n userId: 'me',\n id: id,\n format: 'full',\n metadataHeaders: ['From', 'To', 'Cc', 'Bcc', 'Subject', 'Date'],\n });\n const fullData = response.data;\n if (!fullData) {\n throw new McpError(ErrorCode.InvalidRequest, 'Message not found');\n }\n\n // Build full message data with type guards\n const headers = fullData?.payload?.headers;\n const headersArray = Array.isArray(headers) ? headers : [];\n const headersMap: Record<string, string> = Object.fromEntries(\n headersArray.map((h: unknown) => {\n const header = h as gmail_v1.Schema$MessagePartHeader;\n return [String(header.name ?? ''), String(header.value ?? '')];\n })\n );\n const fromInfo = extractFrom(headersMap.From);\n const toStr = extractEmails(headersMap.To).join(', ');\n const ccStr = extractEmails(headersMap.Cc).join(', ');\n const bccStr = extractEmails(headersMap.Bcc).join(', ');\n const messagePayload = fullData?.payload;\n const bodyContent = messagePayload ? extractBodyFromPayload(messagePayload, { contentType, excludeThreadHistory }) : '';\n const payload: Partial<EmailDetail> = {\n id: fullData.id ?? undefined,\n threadId: fullData.threadId ?? undefined,\n date: toIsoUtc(headersMap.Date) || headersMap.Date,\n from: fromInfo?.address || headersMap.From,\n fromName: fromInfo?.name,\n to: toStr,\n cc: ccStr,\n bcc: bccStr,\n subject: headersMap.Subject ?? '',\n snippet: fullData.snippet ?? undefined,\n body: bodyContent,\n bodyContentType: contentType,\n };\n\n // Filter based on requested fields\n const filteredPayload = filterFields(payload, requestedFields);\n\n logger.info('gmail.message.get result', { id: fullData.id, subject: payload.subject, from: payload.from, fields: fields || 'all' });\n\n const result: Output = {\n type: 'success' as const,\n item: filteredPayload,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.message.get error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error getting message: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-get',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","coerce","string","trim","min","describe","fields","createFieldsSchema","availableFields","EMAIL_FIELDS","fieldDescriptions","EMAIL_FIELD_DESCRIPTIONS","commonPatterns","EMAIL_COMMON_PATTERNS","resourceName","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successBranchSchema","type","literal","item","EmailDetailSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","requestedFields","fullData","headersMap","gmail","response","headers","headersArray","fromInfo","toStr","ccStr","bccStr","messagePayload","bodyContent","payload","filteredPayload","error","message","parseFields","info","Boolean","McpError","ErrorCode","InvalidParams","google","version","auth","authContext","users","messages","get","userId","format","metadataHeaders","data","InvalidRequest","Array","isArray","Object","fromEntries","map","h","header","String","name","value","extractFrom","From","extractEmails","To","join","Cc","Bcc","extractBodyFromPayload","undefined","threadId","date","toIsoUtc","Date","from","address","fromName","to","cc","bcc","subject","Subject","snippet","body","bodyContentType","filterFields","content","text","JSON","stringify","structuredContent","Error","InternalError","stack"],"mappings":";;;;+BAgIA;;;eA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SAAiB;wBACrBR,MAAM;wBACNE,MAAMwB;oBACR;oBAEA;;wBAAO;4BACLwD,OAAO;gCACL;oCACElF,MAAM;oCACNmF,MAAMC,KAAKC,SAAS,CAAC7E;gCACvB;;4BAEF8E,mBAAmB;gCAAE9E,QAAAA;4BAAO;wBAC9B;;;oBACOmB;oBACDC,UAAUD,AAAK,YAALA,OAAiB4D,SAAQ5D,MAAMC,OAAO,GAAG0B,OAAO3B;oBAChEhB,OAAOgB,KAAK,CAAC,2BAA2B;wBAAEA,OAAOC;oBAAQ;oBAEzD,MAAM,IAAII,eAAQ,CAACC,gBAAS,CAACuD,aAAa,EAAE,AAAC,0BAAiC,OAAR5D,UAAW;wBAC/E6D,OAAO9D,AAAK,YAALA,OAAiB4D,SAAQ5D,MAAM8D,KAAK,GAAGxB;oBAChD;;;;;;;IAEJ;;AAEe,SAAS3F;IACtB,OAAO;QACLiF,MAAM;QACNjD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-get.ts"],"sourcesContent":["import { EMAIL_COMMON_PATTERNS, EMAIL_FIELD_DESCRIPTIONS, EMAIL_FIELDS, EmailContentTypeSchema, type EmailDetail, EmailDetailSchema, ExcludeThreadHistorySchema } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { createFieldsSchema, filterFields, ProtocolError, ProtocolErrorCode, parseFields, type ToolModule } from '@mcp-z/server';\nimport { type gmail_v1, google } from 'googleapis';\nimport { z } from 'zod';\nimport { extractBodyFromPayload, extractEmails, extractFrom } from '../../email/parsing/message-extraction.ts';\nimport { toIsoUtc } from '../../lib/date-conversion.ts';\n\nconst inputSchema = z.object({\n id: z.coerce.string().trim().min(1).describe('Gmail message ID to retrieve'),\n fields: createFieldsSchema({\n availableFields: EMAIL_FIELDS,\n fieldDescriptions: EMAIL_FIELD_DESCRIPTIONS,\n commonPatterns: EMAIL_COMMON_PATTERNS,\n resourceName: 'email message',\n }),\n contentType: EmailContentTypeSchema,\n excludeThreadHistory: ExcludeThreadHistorySchema,\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n item: EmailDetailSchema,\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Get a Gmail message by ID with flexible field selection',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, fields, contentType, excludeThreadHistory }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n\n const requestedFields = parseFields(fields, EMAIL_FIELDS);\n\n logger.info('gmail.message.get called', { id: Boolean(id), fields: fields || 'all' });\n\n try {\n if (!id) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id');\n }\n\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n const response = await gmail.users.messages.get({\n userId: 'me',\n id: id,\n format: 'full',\n metadataHeaders: ['From', 'To', 'Cc', 'Bcc', 'Subject', 'Date'],\n });\n const fullData = response.data;\n if (!fullData) {\n throw new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Message not found');\n }\n\n // Build full message data with type guards\n const headers = fullData?.payload?.headers;\n const headersArray = Array.isArray(headers) ? headers : [];\n const headersMap: Record<string, string> = Object.fromEntries(\n headersArray.map((h: unknown) => {\n const header = h as gmail_v1.Schema$MessagePartHeader;\n return [String(header.name ?? ''), String(header.value ?? '')];\n })\n );\n const fromInfo = extractFrom(headersMap.From);\n const toStr = extractEmails(headersMap.To).join(', ');\n const ccStr = extractEmails(headersMap.Cc).join(', ');\n const bccStr = extractEmails(headersMap.Bcc).join(', ');\n const messagePayload = fullData?.payload;\n const bodyContent = messagePayload ? extractBodyFromPayload(messagePayload, { contentType, excludeThreadHistory }) : '';\n const payload: Partial<EmailDetail> = {\n id: fullData.id ?? undefined,\n threadId: fullData.threadId ?? undefined,\n date: toIsoUtc(headersMap.Date) || headersMap.Date,\n from: fromInfo?.address || headersMap.From,\n fromName: fromInfo?.name,\n to: toStr,\n cc: ccStr,\n bcc: bccStr,\n subject: headersMap.Subject ?? '',\n snippet: fullData.snippet ?? undefined,\n body: bodyContent,\n bodyContentType: contentType,\n };\n\n // Filter based on requested fields\n const filteredPayload = filterFields(payload, requestedFields);\n\n logger.info('gmail.message.get result', { id: fullData.id, subject: payload.subject, from: payload.from, fields: fields || 'all' });\n\n const result: Output = {\n type: 'success' as const,\n item: filteredPayload,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.message.get error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error getting message: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-get',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","coerce","string","trim","min","describe","fields","createFieldsSchema","availableFields","EMAIL_FIELDS","fieldDescriptions","EMAIL_FIELD_DESCRIPTIONS","commonPatterns","EMAIL_COMMON_PATTERNS","resourceName","contentType","EmailContentTypeSchema","excludeThreadHistory","ExcludeThreadHistorySchema","successBranchSchema","type","literal","item","EmailDetailSchema","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","requestedFields","fullData","headersMap","gmail","response","headers","headersArray","fromInfo","toStr","ccStr","bccStr","messagePayload","bodyContent","payload","filteredPayload","error","message","parseFields","info","Boolean","ProtocolError","ProtocolErrorCode","InvalidParams","google","version","auth","authContext","users","messages","get","userId","format","metadataHeaders","data","InvalidRequest","Array","isArray","Object","fromEntries","map","h","header","String","name","value","extractFrom","From","extractEmails","To","join","Cc","Bcc","extractBodyFromPayload","undefined","threadId","date","toIsoUtc","Date","from","address","fromName","to","cc","bcc","subject","Subject","snippet","body","bodyContentType","filterFields","content","text","JSON","stringify","structuredContent","Error","InternalError","stack"],"mappings":";;;;+BA+HA;;;eAAwBA;;;qBA/H+I;2BAE/I;sBAIyF;0BAC3E;mBACpB;mCACiD;gCAC1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AANzB,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIF,MAAC,CAACG,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,QAAQC,IAAAA,0BAAkB,EAAC;QACzBC,iBAAiBC,mBAAY;QAC7BC,mBAAmBC,+BAAwB;QAC3CC,gBAAgBC,4BAAqB;QACrCC,cAAc;IAChB;IACAC,aAAaC,6BAAsB;IACnCC,sBAAsBC,iCAA0B;AAClD;AAEA,wBAAwB;AACxB,IAAMC,sBAAsBrB,MAAC,CAACC,MAAM,CAAC;IACnCqB,MAAMtB,MAAC,CAACuB,OAAO,CAAC;IAChBC,MAAMC,wBAAiB;AACzB;AAEA,2CAA2C;AAC3C,IAAMC,eAAe1B,MAAC,CAAC2B,kBAAkB,CAAC,QAAQ;IAACN;IAAqBxB;CAAyB;AAEjG,IAAM+B,SAAS;IACbC,aAAa;IACb9B,aAAaA;IACb2B,cAAc1B,MAAC,CAACC,MAAM,CAAC;QACrB6B,QAAQJ;IACV;AACF;AAKA,SAAeK;wCAAQ,KAAwD,EAAEC,KAAoB;YAA5E9B,IAAIM,QAAQS,aAAaE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+B,kBAAkBuD,IAAAA,oBAAY,EAACxD,SAASb;oBAE9CD,OAAOmB,IAAI,CAAC,4BAA4B;wBAAElD,IAAIiC,SAASjC,EAAE;wBAAEgG,SAASnD,QAAQmD,OAAO;wBAAEN,MAAM7C,QAAQ6C,IAAI;wBAAEpF,QAAQA,UAAU;oBAAM;oBAE3HsB,SAAiB;wBACrBR,MAAM;wBACNE,MAAMwB;oBACR;oBAEA;;wBAAO;4BACLwD,OAAO;gCACL;oCACElF,MAAM;oCACNmF,MAAMC,KAAKC,SAAS,CAAC7E;gCACvB;;4BAEF8E,mBAAmB;gCAAE9E,QAAAA;4BAAO;wBAC9B;;;oBACOmB;oBACDC,UAAUD,AAAK,YAALA,OAAiB4D,SAAQ5D,MAAMC,OAAO,GAAG0B,OAAO3B;oBAChEhB,OAAOgB,KAAK,CAAC,2BAA2B;wBAAEA,OAAOC;oBAAQ;oBAEzD,MAAM,IAAII,qBAAa,CAACC,yBAAiB,CAACuD,aAAa,EAAE,AAAC,0BAAiC,OAAR5D,UAAW;wBAC5F6D,OAAO9D,AAAK,YAALA,OAAiB4D,SAAQ5D,MAAM8D,KAAK,GAAGxB;oBAChD;;;;;;;IAEJ;;AAEe,SAAS3F;IACtB,OAAO;QACLiF,MAAM;QACNjD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -9,7 +9,7 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
-
var
|
|
12
|
+
var _server = require("@mcp-z/server");
|
|
13
13
|
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
15
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
@@ -174,7 +174,7 @@ function handler(_0, _1) {
|
|
|
174
174
|
id: Boolean(id)
|
|
175
175
|
});
|
|
176
176
|
if (!id) {
|
|
177
|
-
throw new
|
|
177
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'Missing id');
|
|
178
178
|
}
|
|
179
179
|
_state.label = 1;
|
|
180
180
|
case 1:
|
|
@@ -229,7 +229,7 @@ function handler(_0, _1) {
|
|
|
229
229
|
logger.error('gmail-message-mark-read error', {
|
|
230
230
|
error: message
|
|
231
231
|
});
|
|
232
|
-
throw new
|
|
232
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error marking message as read: ".concat(message), {
|
|
233
233
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
234
234
|
});
|
|
235
235
|
case 4:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-mark-read.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport {
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-mark-read.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\n\nconst inputSchema = z.object({\n id: z.coerce.string().trim().min(1).describe('Gmail message ID to mark as read'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n id: z.string().describe('Message ID that was marked as read'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Mark a Gmail message as read',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail-message-mark-read called', { id: Boolean(id) });\n\n if (!id) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n await gmail.users.messages.modify({\n userId: 'me',\n id: id,\n requestBody: {\n removeLabelIds: ['UNREAD'],\n },\n });\n\n logger.info('gmail-message-mark-read success', { id });\n\n const result: Output = {\n type: 'success' as const,\n id,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail-message-mark-read error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error marking message as read: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-mark-read',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","coerce","string","trim","min","describe","successBranchSchema","type","literal","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","gmail","error","message","info","Boolean","ProtocolError","ProtocolErrorCode","InvalidParams","google","version","auth","authContext","users","messages","modify","userId","requestBody","removeLabelIds","content","text","JSON","stringify","structuredContent","Error","String","InternalError","stack","undefined","name"],"mappings":";;;;+BA4EA;;;eAAwBA;;;2BA3EA;sBAKyB;0BAC1B;mBACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AALlB,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAOR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,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gCAAE1B,QAAAA;4BAAO;wBAC9B;;;oBACOK;oBACDC,UAAUD,AAAK,YAALA,OAAiBsB,SAAQtB,MAAMC,OAAO,GAAGsB,OAAOvB;oBAChEF,OAAOE,KAAK,CAAC,iCAAiC;wBAAEA,OAAOC;oBAAQ;oBAE/D,MAAM,IAAIG,qBAAa,CAACC,yBAAiB,CAACmB,aAAa,EAAE,AAAC,kCAAyC,OAARvB,UAAW;wBACpGwB,OAAOzB,AAAK,YAALA,OAAiBsB,SAAQtB,MAAMyB,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASlD;IACtB,OAAO;QACLmD,MAAM;QACNlC,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -9,7 +9,7 @@ Object.defineProperty(exports, "default", {
|
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
12
|
-
var
|
|
12
|
+
var _server = require("@mcp-z/server");
|
|
13
13
|
var _googleapis = require("googleapis");
|
|
14
14
|
var _zod = require("zod");
|
|
15
15
|
var _constantsts = require("../../constants.js");
|
|
@@ -233,11 +233,11 @@ function handler(_0, _1) {
|
|
|
233
233
|
count: ids.length
|
|
234
234
|
});
|
|
235
235
|
if (!ids || ids.length === 0) {
|
|
236
|
-
throw new
|
|
236
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'Missing ids');
|
|
237
237
|
}
|
|
238
238
|
// Validate batch size to prevent memory exhaustion
|
|
239
239
|
if (ids.length > _constantsts.MAX_BATCH_SIZE) {
|
|
240
|
-
throw new
|
|
240
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, "Batch size ".concat(ids.length, " exceeds maximum allowed size of ").concat(_constantsts.MAX_BATCH_SIZE));
|
|
241
241
|
}
|
|
242
242
|
// Validate and sanitize IDs
|
|
243
243
|
validatedIds = [];
|
|
@@ -273,10 +273,10 @@ function handler(_0, _1) {
|
|
|
273
273
|
}
|
|
274
274
|
}
|
|
275
275
|
if (invalidIds.length > 0) {
|
|
276
|
-
throw new
|
|
276
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, "Found ".concat(invalidIds.length, " invalid IDs: ").concat(invalidIds.join(', ')));
|
|
277
277
|
}
|
|
278
278
|
if (validatedIds.length === 0) {
|
|
279
|
-
throw new
|
|
279
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'No valid IDs found after validation');
|
|
280
280
|
}
|
|
281
281
|
_state.label = 1;
|
|
282
282
|
case 1:
|
|
@@ -433,7 +433,7 @@ function handler(_0, _1) {
|
|
|
433
433
|
logger.error('gmail-message-move-to-trash error', {
|
|
434
434
|
error: message
|
|
435
435
|
});
|
|
436
|
-
throw new
|
|
436
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error moving messages to trash: ".concat(message), {
|
|
437
437
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
438
438
|
});
|
|
439
439
|
case 7:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-move-to-trash.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).describe('Gmail message IDs to move to trash'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n totalRequested: z.number().describe('Total number of messages requested to trash'),\n successCount: z.number().describe('Number of messages successfully moved to trash'),\n failureCount: z.number().describe('Number of messages that failed to move'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Message ID'),\n success: z.boolean().describe('Whether the operation succeeded'),\n error: z.string().optional().describe('Error message if operation failed'),\n })\n )\n .describe('Individual results for each message'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Move Gmail messages to trash (recoverable).',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ ids }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail-message-move-to-trash called', { count: ids.length });\n\n if (!ids || ids.length === 0) {\n throw new McpError(ErrorCode.InvalidParams, 'Missing ids');\n }\n\n // Validate batch size to prevent memory exhaustion\n if (ids.length > MAX_BATCH_SIZE) {\n throw new McpError(ErrorCode.InvalidParams, `Batch size ${ids.length} exceeds maximum allowed size of ${MAX_BATCH_SIZE}`);\n }\n\n // Validate and sanitize IDs\n const validatedIds: string[] = [];\n const invalidIds: string[] = [];\n\n for (const id of ids) {\n const trimmedId = id.trim();\n if (!trimmedId) {\n invalidIds.push(id);\n continue;\n }\n // Basic Gmail message ID validation - should not contain certain characters\n if (trimmedId.includes('/') || trimmedId.includes('\\\\') || trimmedId.includes('<') || trimmedId.includes('>')) {\n invalidIds.push(id);\n continue;\n }\n validatedIds.push(trimmedId);\n }\n\n if (invalidIds.length > 0) {\n throw new McpError(ErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs: ${invalidIds.join(', ')}`);\n }\n\n if (validatedIds.length === 0) {\n throw new McpError(ErrorCode.InvalidParams, 'No valid IDs found after validation');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n // Process operations in chunks to prevent memory exhaustion\n const allResults: Array<{ id: string; success: boolean; error?: string }> = [];\n\n for (let i = 0; i < validatedIds.length; i += CHUNK_SIZE) {\n const chunk = validatedIds.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(validatedIds.length / CHUNK_SIZE) });\n\n const chunkResults = await Promise.allSettled(\n chunk.map(async (id) => {\n await gmail.users.messages.trash({\n userId: 'me',\n id: id,\n });\n return { id, success: true };\n })\n );\n\n // Process chunk results\n const processedChunkResults = chunkResults.map((result, chunkIndex) => {\n const id = chunk[chunkIndex];\n if (!id) {\n throw new Error(`Chunk index ${chunkIndex} is out of bounds for chunk of size ${chunk.length}`);\n }\n if (result.status === 'fulfilled') {\n return { id, success: true };\n }\n\n // Extract error message more robustly\n let errorMessage = 'Unknown error';\n if (result.reason) {\n if (typeof result.reason === 'string') {\n errorMessage = result.reason;\n } else if (result.reason instanceof Error) {\n errorMessage = result.reason.message;\n } else if (result.reason && typeof result.reason === 'object' && 'message' in result.reason) {\n errorMessage = String(result.reason.message);\n } else if (result.reason && typeof result.reason === 'object' && 'error' in result.reason) {\n errorMessage = String(result.reason.error);\n } else {\n errorMessage = String(result.reason);\n }\n }\n\n return { id, success: false, error: errorMessage };\n });\n\n allResults.push(...processedChunkResults);\n }\n\n const successCount = allResults.filter((r) => r.success).length;\n const failureCount = allResults.filter((r) => !r.success).length;\n\n logger.info('gmail-message-move-to-trash completed', {\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(validatedIds.length / CHUNK_SIZE),\n });\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n results: allResults,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail-message-move-to-trash error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error moving messages to trash: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-move-to-trash',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","ids","array","coerce","string","trim","min","describe","successBranchSchema","type","literal","totalRequested","number","successCount","failureCount","results","id","success","boolean","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","validatedIds","invalidIds","trimmedId","gmail","allResults","i","message","info","count","length","McpError","ErrorCode","InvalidParams","MAX_BATCH_SIZE","push","includes","join","chunk","chunkResults","processedChunkResults","slice","CHUNK_SIZE","chunkIndex","chunkSize","totalChunks","Math","ceil","Promise","allSettled","map","users","messages","trash","userId","Error","status","errorMessage","reason","String","google","version","auth","authContext","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","name"],"mappings":";;;;+BA2KA;;;eAAwBA;;;2BA1KA;qBAKY;0BACb;mBACL;2BACyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN3C,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,KAAKF,MAAC,CAACG,KAAK,CAACH,MAAC,CAACI,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAChE;AAEA,IAAMC,sBAAsBT,MAAC,CAACC,MAAM,CAAC;IACnCS,MAAMV,MAAC,CAACW,OAAO,CAAC;IAChBC,gBAAgBZ,MAAC,CAACa,MAAM,GAAGL,QAAQ,CAAC;IACpCM,cAAcd,MAAC,CAACa,MAAM,GAAGL,QAAQ,CAAC;IAClCO,cAAcf,MAAC,CAACa,MAAM,GAAGL,QAAQ,CAAC;IA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ourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).describe('Gmail message IDs to move to trash'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n totalRequested: z.number().describe('Total number of messages requested to trash'),\n successCount: z.number().describe('Number of messages successfully moved to trash'),\n failureCount: z.number().describe('Number of messages that failed to move'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Message ID'),\n success: z.boolean().describe('Whether the operation succeeded'),\n error: z.string().optional().describe('Error message if operation failed'),\n })\n )\n .describe('Individual results for each message'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Move Gmail messages to trash (recoverable).',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ ids }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail-message-move-to-trash called', { count: ids.length });\n\n if (!ids || ids.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing ids');\n }\n\n // Validate batch size to prevent memory exhaustion\n if (ids.length > MAX_BATCH_SIZE) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Batch size ${ids.length} exceeds maximum allowed size of ${MAX_BATCH_SIZE}`);\n }\n\n // Validate and sanitize IDs\n const validatedIds: string[] = [];\n const invalidIds: string[] = [];\n\n for (const id of ids) {\n const trimmedId = id.trim();\n if (!trimmedId) {\n invalidIds.push(id);\n continue;\n }\n // Basic Gmail message ID validation - should not contain certain characters\n if (trimmedId.includes('/') || trimmedId.includes('\\\\') || trimmedId.includes('<') || trimmedId.includes('>')) {\n invalidIds.push(id);\n continue;\n }\n validatedIds.push(trimmedId);\n }\n\n if (invalidIds.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs: ${invalidIds.join(', ')}`);\n }\n\n if (validatedIds.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'No valid IDs found after validation');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n // Process operations in chunks to prevent memory exhaustion\n const allResults: Array<{ id: string; success: boolean; error?: string }> = [];\n\n for (let i = 0; i < validatedIds.length; i += CHUNK_SIZE) {\n const chunk = validatedIds.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(validatedIds.length / CHUNK_SIZE) });\n\n const chunkResults = await Promise.allSettled(\n chunk.map(async (id) => {\n await gmail.users.messages.trash({\n userId: 'me',\n id: id,\n });\n return { id, success: true };\n })\n );\n\n // Process chunk results\n const processedChunkResults = chunkResults.map((result, chunkIndex) => {\n const id = chunk[chunkIndex];\n if (!id) {\n throw new Error(`Chunk index ${chunkIndex} is out of bounds for chunk of size ${chunk.length}`);\n }\n if (result.status === 'fulfilled') {\n return { id, success: true };\n }\n\n // Extract error message more robustly\n let errorMessage = 'Unknown error';\n if (result.reason) {\n if (typeof result.reason === 'string') {\n errorMessage = result.reason;\n } else if (result.reason instanceof Error) {\n errorMessage = result.reason.message;\n } else if (result.reason && typeof result.reason === 'object' && 'message' in result.reason) {\n errorMessage = String(result.reason.message);\n } else if (result.reason && typeof result.reason === 'object' && 'error' in result.reason) {\n errorMessage = String(result.reason.error);\n } else {\n errorMessage = String(result.reason);\n }\n }\n\n return { id, success: false, error: errorMessage };\n });\n\n allResults.push(...processedChunkResults);\n }\n\n const successCount = allResults.filter((r) => r.success).length;\n const failureCount = allResults.filter((r) => !r.success).length;\n\n logger.info('gmail-message-move-to-trash completed', {\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(validatedIds.length / CHUNK_SIZE),\n });\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n results: allResults,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail-message-move-to-trash error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error moving messages to trash: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'message-move-to-trash',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","ids","array","coerce","string","trim","min","describe","successBranchSchema","type","literal","totalRequested","number","successCount","failureCount","results","id","success","boolean","error","optional","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","validatedIds","invalidIds","trimmedId","gmail","allResults","i","message","info","count","length","ProtocolError","ProtocolErrorCode","InvalidParams","MAX_BATCH_SIZE","push","includes","join","chunk","chunkResults","processedChunkResults","slice","CHUNK_SIZE","chunkIndex","chunkSize","totalChunks","Math","ceil","Promise","allSettled","map","users","messages","trash","userId","Error","status","errorMessage","reason","String","google","version","auth","authContext","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined","name"],"mappings":";;;;+BA2KA;;;eAAwBA;;;2BA1KA;sBAKyB;0BAC1B;mBACL;2BACyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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BAAmB;gCAAEtD,QAAAA;4BAAO;wBAC9B;;;oBACON;oBACDgB,UAAUhB,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAMgB,OAAO,GAAGgC,OAAOhD;oBAChES,OAAOT,KAAK,CAAC,qCAAqC;wBAAEA,OAAOgB;oBAAQ;oBAEnE,MAAM,IAAII,qBAAa,CAACC,yBAAiB,CAACwC,aAAa,EAAE,AAAC,mCAA0C,OAAR7C,UAAW;wBACrG8C,OAAO9D,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAM8D,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASvF;IACtB,OAAO;QACLwF,MAAM;QACN5D,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -10,7 +10,7 @@ Object.defineProperty(exports, "default", {
|
|
|
10
10
|
});
|
|
11
11
|
var _email = require("@mcp-z/email");
|
|
12
12
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
13
|
-
var
|
|
13
|
+
var _server = require("@mcp-z/server");
|
|
14
14
|
var _googleapis = require("googleapis");
|
|
15
15
|
var _zod = require("zod");
|
|
16
16
|
var _headersutilsts = require("../../email/parsing/headers-utils.js");
|
|
@@ -202,7 +202,7 @@ function handler(_0, _1) {
|
|
|
202
202
|
id = param.id, body = param.body, contentType = param.contentType;
|
|
203
203
|
logger = extra.logger;
|
|
204
204
|
if (!id || !body) {
|
|
205
|
-
throw new
|
|
205
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'Missing id or body');
|
|
206
206
|
}
|
|
207
207
|
logger.info('gmail.message.respond called', {
|
|
208
208
|
id: id,
|
|
@@ -259,7 +259,7 @@ function handler(_0, _1) {
|
|
|
259
259
|
logger.error('gmail.message.respond fetch error', {
|
|
260
260
|
error: message
|
|
261
261
|
});
|
|
262
|
-
throw new
|
|
262
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error fetching message metadata: ".concat(message), {
|
|
263
263
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
264
264
|
});
|
|
265
265
|
case 5:
|
|
@@ -340,7 +340,7 @@ function handler(_0, _1) {
|
|
|
340
340
|
logger.error('gmail.message.respond error', {
|
|
341
341
|
error: message1
|
|
342
342
|
});
|
|
343
|
-
throw new
|
|
343
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error responding to message: ".concat(message1), {
|
|
344
344
|
stack: _instanceof(error1, Error) ? error1.stack : undefined
|
|
345
345
|
});
|
|
346
346
|
case 8:
|
|
@@ -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 { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\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 McpError(ErrorCode.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 McpError(ErrorCode.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 McpError(ErrorCode.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","McpError","ErrorCode","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;qBAKY;0BACb;mBACL;8BACY;gCACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAPvB,IAAM,AAAEC,2BAA6BC,oBAAO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AG;oBAE/CgB,SAAiB;wBACrBN,MAAM;wBACNV,IAAAA;oBACF;oBAEA;;wBAAO;4BACLoF,OAAO;gCACL;oCACE1E,MAAM;oCACN2E,MAAMC,KAAKC,SAAS,CAACvE;gCACvB;;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,eAAQ,CAACC,gBAAS,CAACgB,aAAa,EAAE,AAAC,gCAAuC,OAAR/B,WAAW;wBACrFgC,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';\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":";;;;+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AAA,qBAAAA,+BAAAA,SAAUkB,QAAQ,IAAGiB,OAAOnC,SAASkB,QAAQ,IAAIoB;oBAClE;;wBAAMrC,MAAM0B,KAAK,CAACC,QAAQ,CAACgC,IAAI,CAAC;4BAC9B9B,QAAQ;4BACR+B,aAAa;gCACX5C,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;4BACLoF,OAAO;gCACL;oCACE1E,MAAM;oCACN2E,MAAMC,KAAKC,SAAS,CAACvE;gCACvB;;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"}
|
|
@@ -8,10 +8,9 @@ Object.defineProperty(exports, "default", {
|
|
|
8
8
|
return createTool;
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
|
-
var
|
|
11
|
+
var _server = require("@mcp-z/server");
|
|
12
12
|
var _email = require("@mcp-z/email");
|
|
13
13
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
14
|
-
var _server = require("@mcp-z/server");
|
|
15
14
|
var _googleapis = require("googleapis");
|
|
16
15
|
var _zod = require("zod");
|
|
17
16
|
var _constantsts = require("../../constants.js");
|
|
@@ -378,7 +377,7 @@ function handler(_0, _1) {
|
|
|
378
377
|
logger.error('gmail.message.search error', {
|
|
379
378
|
error: message
|
|
380
379
|
});
|
|
381
|
-
throw new
|
|
380
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error searching messages: ".concat(message), {
|
|
382
381
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
383
382
|
});
|
|
384
383
|
case 4:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/message-search.ts"],"sourcesContent":["import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\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 McpError(ErrorCode.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","McpError","ErrorCode","InternalError","stack"],"mappings":";;;;+BA+KA;;;eAAwBA;;;qBA/KY;qBAGmI;2BAE/I;sBAIoH;0BACtG;mBACpB;2BAC+B;gCACV;8BACW;kCACkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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BAAEA,OAAOC;oBAAQ;oBAE5D,MAAM,IAAIuD,eAAQ,CAACC,gBAAS,CAACC,aAAa,EAAE,AAAC,6BAAoC,OAARzD,UAAW;wBAClF0D,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 { 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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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OC;oBAAQ;oBAE5D,MAAM,IAAIuD,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,6BAAoC,OAARzD,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"}
|
|
@@ -10,7 +10,7 @@ Object.defineProperty(exports, "default", {
|
|
|
10
10
|
});
|
|
11
11
|
var _email = require("@mcp-z/email");
|
|
12
12
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
13
|
-
var
|
|
13
|
+
var _server = require("@mcp-z/server");
|
|
14
14
|
var _googleapis = require("googleapis");
|
|
15
15
|
var _zod = require("zod");
|
|
16
16
|
var _rfc822builderts = require("../../email/composition/rfc822-builder.js");
|
|
@@ -186,7 +186,7 @@ function handler(params, extra) {
|
|
|
186
186
|
contentType: contentType
|
|
187
187
|
});
|
|
188
188
|
if (!to) {
|
|
189
|
-
throw new
|
|
189
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'Missing required field: to');
|
|
190
190
|
}
|
|
191
191
|
_state.label = 1;
|
|
192
192
|
case 1:
|
|
@@ -263,7 +263,7 @@ function handler(params, extra) {
|
|
|
263
263
|
logger.error('gmail.message.send error', {
|
|
264
264
|
error: message
|
|
265
265
|
});
|
|
266
|
-
throw new
|
|
266
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error sending message: ".concat(message), {
|
|
267
267
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
268
268
|
});
|
|
269
269
|
case 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 {
|
|
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":";;;;+BAuGA;;;eAAwBA;;;qBAvGyE;2BAEzE;sBAKyB;0BAC1B;mBACL;+BACkB;gCACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAPvB,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIC,IAAAA,kCAA2B,EAAC,MAAM;IACtCC,IAAID,IAAAA,kCAA2B,EAAC,MAAM;IACtCE,KAAKF,IAAAA,kCAA2B,EAAC,OAAO;IACxCG,SAASN,MAAC,CAACO,MAAM,GAAGC,QAAQ,CAAC,mBAAmBC,OAAO,CAAC;IACxDC,MAAMV,MAAC,CAACO,MAAM,GAAGI,IAAI,GAAGC,GAAG,CAAC,GAAGJ,QAAQ,CAAC;IACxCK,aAAaC,+BAAwB;AACvC;AAEA,wBAAwB;AACxB,IAAMC,sBAAsBf,MAAC,CAACC,MAAM,CAAC;IACnCe,MAAMhB,MAAC,CAACiB,OAAO,CAAC;IAChBC,MAAMC,IAAAA,gCAAyB,EAAC;AAClC;AAEA,2CAA2C;AAC3C,IAAMC,eAAepB,MAAC,CAACqB,kBAAkB,CAAC,QAAQ;IAACN;IAAqBlB;CAAyB;AAEjG,IAAMyB,SAAS;IACbC,aAAa;IACbxB,aAAaA;IACbqB,cAAcpB,MAAC,CAACC,MAAM,CAAC;QACrBuB,QAAQJ;IACV;AACF;AAKA,SAAeK,QAAQC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EiB,IAAIrB;oBAAU;oBAChEP,OAAOW,IAAI,CAAC,qCAAqC;wBAAErC,IAAAA;wBAAII,SAAAA;wBAAS6B,WAAAA;oBAAU;oBAEpEC,kBAAkB,AAACqB,CAAAA,MAAMC,OAAO,CAACxD,MAAMA,GAAGyD,MAAM,GAAG,CAAA,IAAMvD,CAAAA,KAAMqD,MAAMC,OAAO,CAACtD,MAAMA,GAAGuD,MAAM,GAAG,IAAK,CAAA,IAAMtD,CAAAA,MAAOoD,MAAMC,OAAO,CAACrD,OAAOA,IAAIsD,MAAM,GAAG,IAAK,CAAA;oBACxJnC,SAAiB;wBACrBR,MAAM;wBACNE,MAAM;4BACJsC,IAAIrB;4BACJyB,QAAQ,IAAIC,OAAOC,WAAW;4BAC9BC,gBAAgB3B;4BAChB4B,SAAS,AAAC,0CAAmD,OAAV7B;wBACrD;oBACF;oBAEA;;wBAAO;4BACL8B,OAAO;gCACL;oCACEjD,MAAM;oCACNkD,MAAMC,KAAKC,SAAS,CAAC5C;gCACvB;;4BAEF6C,mBAAmB;gCAAE7C,QAAAA;4BAAO;wBAC9B;;;oBACOa;oBACDC,UAAUD,AAAK,YAALA,OAAiBiC,SAAQjC,MAAMC,OAAO,GAAGiC,OAAOlC;oBAChET,OAAOS,KAAK,CAAC,4BAA4B;wBAAEA,OAAOC;oBAAQ;oBAE1D,MAAM,IAAIE,qBAAa,CAACC,yBAAiB,CAAC+B,aAAa,EAAE,AAAC,0BAAiC,OAARlC,UAAW;wBAC5FmC,OAAOpC,AAAK,YAALA,OAAiBiC,SAAQjC,MAAMoC,KAAK,GAAG9B;oBAChD;;;;;;;IAEJ;;AAEe,SAAS/C;IACtB,OAAO;QACL8E,MAAM;QACNpD,QAAAA;QACAG,SAAAA;IACF;AACF"}
|
|
@@ -11,7 +11,6 @@ Object.defineProperty(exports, "default", {
|
|
|
11
11
|
var _email = require("@mcp-z/email");
|
|
12
12
|
var _oauthgoogle = require("@mcp-z/oauth-google");
|
|
13
13
|
var _server = require("@mcp-z/server");
|
|
14
|
-
var _types = require("@modelcontextprotocol/sdk/types.js");
|
|
15
14
|
var _sync = require("csv-stringify/sync");
|
|
16
15
|
var _fs = require("fs");
|
|
17
16
|
var _promises = require("fs/promises");
|
|
@@ -503,7 +502,7 @@ var config = {
|
|
|
503
502
|
logger.error('gmail.messages.export-csv error', {
|
|
504
503
|
error: message
|
|
505
504
|
});
|
|
506
|
-
throw new
|
|
505
|
+
throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error exporting messages to CSV: ".concat(message), {
|
|
507
506
|
stack: _instanceof(error, Error) ? error.stack : undefined
|
|
508
507
|
});
|
|
509
508
|
case 12:
|