@mcp-z/mcp-gmail 1.0.0 → 1.0.2

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.
Files changed (139) hide show
  1. package/README.md +33 -3
  2. package/bin/server.js +1 -1
  3. package/dist/cjs/constants.js.map +1 -1
  4. package/dist/cjs/email/composition/rfc822-builder.js.map +1 -1
  5. package/dist/cjs/email/messages/fetch-message.js +7 -7
  6. package/dist/cjs/email/messages/fetch-message.js.map +1 -1
  7. package/dist/cjs/email/messages/messages.js +10 -10
  8. package/dist/cjs/email/messages/messages.js.map +1 -1
  9. package/dist/cjs/email/parsing/header-parsing.js +3 -3
  10. package/dist/cjs/email/parsing/header-parsing.js.map +1 -1
  11. package/dist/cjs/email/parsing/headers-utils.js.map +1 -1
  12. package/dist/cjs/email/parsing/html-processing.js.map +1 -1
  13. package/dist/cjs/email/parsing/message-extraction.js +5 -5
  14. package/dist/cjs/email/parsing/message-extraction.js.map +1 -1
  15. package/dist/cjs/email/querying/execute-query.js +2 -2
  16. package/dist/cjs/email/querying/execute-query.js.map +1 -1
  17. package/dist/cjs/email/querying/pagination.js.map +1 -1
  18. package/dist/cjs/email/querying/query-builder.js.map +1 -1
  19. package/dist/cjs/email/querying/search-execution.js +4 -4
  20. package/dist/cjs/email/querying/search-execution.js.map +1 -1
  21. package/dist/cjs/index.d.cts +4 -0
  22. package/dist/cjs/index.d.ts +4 -0
  23. package/dist/cjs/index.js +21 -13
  24. package/dist/cjs/index.js.map +1 -1
  25. package/dist/cjs/labels/gmail-labels.js.map +1 -1
  26. package/dist/cjs/lib/base64-encoding.js.map +1 -1
  27. package/dist/cjs/lib/create-store.js.map +1 -1
  28. package/dist/cjs/lib/date-conversion.js.map +1 -1
  29. package/dist/cjs/lib/messages-to-row.js.map +1 -1
  30. package/dist/cjs/mcp/index.js +6 -6
  31. package/dist/cjs/mcp/index.js.map +1 -1
  32. package/dist/cjs/mcp/prompts/draft-email.js.map +1 -1
  33. package/dist/cjs/mcp/prompts/index.js +4 -4
  34. package/dist/cjs/mcp/prompts/index.js.map +1 -1
  35. package/dist/cjs/mcp/prompts/query-syntax.js.map +1 -1
  36. package/dist/cjs/mcp/resources/email.js +5 -5
  37. package/dist/cjs/mcp/resources/email.js.map +1 -1
  38. package/dist/cjs/mcp/resources/index.js +2 -2
  39. package/dist/cjs/mcp/resources/index.js.map +1 -1
  40. package/dist/cjs/mcp/tools/categories-list.d.cts +8 -2
  41. package/dist/cjs/mcp/tools/categories-list.d.ts +8 -2
  42. package/dist/cjs/mcp/tools/categories-list.js +12 -4
  43. package/dist/cjs/mcp/tools/categories-list.js.map +1 -1
  44. package/dist/cjs/mcp/tools/index.js +22 -22
  45. package/dist/cjs/mcp/tools/index.js.map +1 -1
  46. package/dist/cjs/mcp/tools/label-add.js +2 -2
  47. package/dist/cjs/mcp/tools/label-add.js.map +1 -1
  48. package/dist/cjs/mcp/tools/label-delete.js.map +1 -1
  49. package/dist/cjs/mcp/tools/labels-list.d.cts +8 -2
  50. package/dist/cjs/mcp/tools/labels-list.d.ts +8 -2
  51. package/dist/cjs/mcp/tools/labels-list.js +12 -4
  52. package/dist/cjs/mcp/tools/labels-list.js.map +1 -1
  53. package/dist/cjs/mcp/tools/message-get.js +8 -8
  54. package/dist/cjs/mcp/tools/message-get.js.map +1 -1
  55. package/dist/cjs/mcp/tools/message-mark-read.js.map +1 -1
  56. package/dist/cjs/mcp/tools/message-move-to-trash.js.map +1 -1
  57. package/dist/cjs/mcp/tools/message-respond.js +4 -4
  58. package/dist/cjs/mcp/tools/message-respond.js.map +1 -1
  59. package/dist/cjs/mcp/tools/message-search.js +6 -6
  60. package/dist/cjs/mcp/tools/message-search.js.map +1 -1
  61. package/dist/cjs/mcp/tools/message-send.js +4 -4
  62. package/dist/cjs/mcp/tools/message-send.js.map +1 -1
  63. package/dist/cjs/mcp/tools/messages-export-csv.js +6 -6
  64. package/dist/cjs/mcp/tools/messages-export-csv.js.map +1 -1
  65. package/dist/cjs/schemas/gmail-query-schema.js.map +1 -1
  66. package/dist/cjs/schemas/index.js.map +1 -1
  67. package/dist/cjs/setup/config.js +11 -1
  68. package/dist/cjs/setup/config.js.map +1 -1
  69. package/dist/cjs/setup/http.js +6 -2
  70. package/dist/cjs/setup/http.js.map +1 -1
  71. package/dist/cjs/setup/index.d.cts +1 -0
  72. package/dist/cjs/setup/index.d.ts +1 -0
  73. package/dist/cjs/setup/index.js +9 -9
  74. package/dist/cjs/setup/index.js.map +1 -1
  75. package/dist/cjs/setup/oauth-google.d.cts +3 -2
  76. package/dist/cjs/setup/oauth-google.d.ts +3 -2
  77. package/dist/cjs/setup/oauth-google.js +15 -12
  78. package/dist/cjs/setup/oauth-google.js.map +1 -1
  79. package/dist/cjs/setup/runtime.js +9 -9
  80. package/dist/cjs/setup/runtime.js.map +1 -1
  81. package/dist/cjs/setup/stdio.js +2 -2
  82. package/dist/cjs/setup/stdio.js.map +1 -1
  83. package/dist/esm/constants.js.map +1 -1
  84. package/dist/esm/email/composition/rfc822-builder.js.map +1 -1
  85. package/dist/esm/email/messages/fetch-message.js.map +1 -1
  86. package/dist/esm/email/messages/messages.js.map +1 -1
  87. package/dist/esm/email/parsing/header-parsing.js.map +1 -1
  88. package/dist/esm/email/parsing/headers-utils.js.map +1 -1
  89. package/dist/esm/email/parsing/html-processing.js.map +1 -1
  90. package/dist/esm/email/parsing/message-extraction.js.map +1 -1
  91. package/dist/esm/email/querying/execute-query.js.map +1 -1
  92. package/dist/esm/email/querying/pagination.js.map +1 -1
  93. package/dist/esm/email/querying/query-builder.js.map +1 -1
  94. package/dist/esm/email/querying/search-execution.js.map +1 -1
  95. package/dist/esm/index.d.ts +4 -0
  96. package/dist/esm/index.js +2 -0
  97. package/dist/esm/index.js.map +1 -1
  98. package/dist/esm/labels/gmail-labels.js.map +1 -1
  99. package/dist/esm/lib/base64-encoding.js.map +1 -1
  100. package/dist/esm/lib/create-store.js.map +1 -1
  101. package/dist/esm/lib/date-conversion.js.map +1 -1
  102. package/dist/esm/lib/messages-to-row.js.map +1 -1
  103. package/dist/esm/mcp/index.js.map +1 -1
  104. package/dist/esm/mcp/prompts/draft-email.js.map +1 -1
  105. package/dist/esm/mcp/prompts/index.js.map +1 -1
  106. package/dist/esm/mcp/prompts/query-syntax.js.map +1 -1
  107. package/dist/esm/mcp/resources/email.js.map +1 -1
  108. package/dist/esm/mcp/resources/index.js.map +1 -1
  109. package/dist/esm/mcp/tools/categories-list.d.ts +8 -2
  110. package/dist/esm/mcp/tools/categories-list.js +4 -2
  111. package/dist/esm/mcp/tools/categories-list.js.map +1 -1
  112. package/dist/esm/mcp/tools/index.js.map +1 -1
  113. package/dist/esm/mcp/tools/label-add.js.map +1 -1
  114. package/dist/esm/mcp/tools/label-delete.js.map +1 -1
  115. package/dist/esm/mcp/tools/labels-list.d.ts +8 -2
  116. package/dist/esm/mcp/tools/labels-list.js +4 -2
  117. package/dist/esm/mcp/tools/labels-list.js.map +1 -1
  118. package/dist/esm/mcp/tools/message-get.js.map +1 -1
  119. package/dist/esm/mcp/tools/message-mark-read.js.map +1 -1
  120. package/dist/esm/mcp/tools/message-move-to-trash.js.map +1 -1
  121. package/dist/esm/mcp/tools/message-respond.js.map +1 -1
  122. package/dist/esm/mcp/tools/message-search.js.map +1 -1
  123. package/dist/esm/mcp/tools/message-send.js.map +1 -1
  124. package/dist/esm/mcp/tools/messages-export-csv.js.map +1 -1
  125. package/dist/esm/schemas/gmail-query-schema.js.map +1 -1
  126. package/dist/esm/schemas/index.js.map +1 -1
  127. package/dist/esm/setup/config.js +12 -2
  128. package/dist/esm/setup/config.js.map +1 -1
  129. package/dist/esm/setup/http.js +4 -0
  130. package/dist/esm/setup/http.js.map +1 -1
  131. package/dist/esm/setup/index.d.ts +1 -0
  132. package/dist/esm/setup/index.js.map +1 -1
  133. package/dist/esm/setup/oauth-google.d.ts +3 -2
  134. package/dist/esm/setup/oauth-google.js +8 -11
  135. package/dist/esm/setup/oauth-google.js.map +1 -1
  136. package/dist/esm/setup/runtime.js.map +1 -1
  137. package/dist/esm/setup/stdio.js.map +1 -1
  138. package/dist/esm/types.js.map +1 -1
  139. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/servers/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 { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\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 McpError(ErrorCode.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 McpError(ErrorCode.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","McpError","ErrorCode","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;qBAKY;0BACb;mBACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AALlB,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAOR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIF,MAAC,CAACG,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAC/C;AAEA,IAAMC,sBAAsBR,MAAC,CAACC,MAAM,CAAC;IACnCQ,MAAMT,MAAC,CAACU,OAAO,CAAC;IAChBR,IAAIF,MAAC,CAACI,MAAM,GAAGG,QAAQ,CAAC;AAC1B;AAEA,IAAMI,eAAeX,MAAC,CAACY,kBAAkB,CAAC,QAAQ;IAACJ;IAAqBX;CAAyB;AAEjG,IAAMgB,SAAS;IACbC,aAAa;IACbf,aAAaA;IACbY,cAAcX,MAAC,CAACC,MAAM,CAAC;QACrBc,QAAQJ;IACV;AACF;AAKA,SAAeK;wCAAQ,KAAa,EAAEC,KAAoB;YAAjCf,IACjBgB,QAQEC,OAWAJ,QAcCK,OACDC;;;;oBAnCenB,KAAF,MAAEA;oBACjBgB,SAASD,MAAMC,MAAM;oBAC3BA,OAAOI,IAAI,CAAC,kCAAkC;wBAAEpB,IAAIqB,QAAQrB;oBAAI;oBAEhE,IAAI,CAACA,IAAI;wBACP,MAAM,IAAIsB,eAAQ,CAACC,gBAAS,CAACC,aAAa,EAAE;oBAC9C;;;;;;;;;oBAGQP,QAAQQ,kBAAM,CAACR,KAAK,CAAC;wBAAES,SAAS;wBAAMC,MAAMZ,MAAMa,WAAW,CAACD,IAAI;oBAAC;oBACzE;;wBAAMV,MAAMY,KAAK,CAACC,QAAQ,CAACC,MAAM,CAAC;4BAChCC,QAAQ;4BACRhC,IAAIA;4BACJiC,aAAa;gCACXC,cAAc;oCAAG;;4BACnB;wBACF;;;oBANA;oBAQAlB,OAAOI,IAAI,CAAC,mCAAmC;wBAAEpB,IAAAA;oBAAG;oBAE9Ca,SAAiB;wBACrBN,MAAM;wBACNP,IAAAA;oBACF;oBAEA;;wBAAO;4BACLmC,OAAO;gCACL;oCACE5B,MAAM;oCACN6B,MAAMC,KAAKC,SAAS,CAACzB;gCACvB;;4BAEF0B,mBAAmB;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,eAAQ,CAACC,gBAAS,CAACmB,aAAa,EAAE,AAAC,kCAAyC,OAARvB,UAAW;wBACvFwB,OAAOzB,AAAK,YAALA,OAAiBsB,SAAQtB,MAAMyB,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASlD;IACtB,OAAO;QACLmD,MAAM;QACNlC,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/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 { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\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 McpError(ErrorCode.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 McpError(ErrorCode.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","McpError","ErrorCode","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;qBAKY;0BACb;mBACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AALlB,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAOR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIF,MAAC,CAACG,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAC/C;AAEA,IAAMC,sBAAsBR,MAAC,CAACC,MAAM,CAAC;IACnCQ,MAAMT,MAAC,CAACU,OAAO,CAAC;IAChBR,IAAIF,MAAC,CAACI,MAAM,GAAGG,QAAQ,CAAC;AAC1B;AAEA,IAAMI,eAAeX,MAAC,CAACY,kBAAkB,CAAC,QAAQ;IAACJ;IAAqBX;CAAyB;AAEjG,IAAMgB,SAAS;IACbC,aAAa;IACbf,aAAaA;IACbY,cAAcX,MAAC,CAACC,MAAM,CAAC;QACrBc,QAAQJ;IACV;AACF;AAKA,SAAeK;wCAAQ,KAAa,EAAEC,KAAoB;YAAjCf,IACjBgB,QAQEC,OAWAJ,QAcCK,OACDC;;;;oBAnCenB,KAAF,MAAEA;oBACjBgB,SAASD,MAAMC,MAAM;oBAC3BA,OAAOI,IAAI,CAAC,kCAAkC;wBAAEpB,IAAIqB,QAAQrB;oBAAI;oBAEhE,IAAI,CAACA,IAAI;wBACP,MAAM,IAAIsB,eAAQ,CAACC,gBAAS,CAACC,aAAa,EAAE;oBAC9C;;;;;;;;;oBAGQP,QAAQQ,kBAAM,CAACR,KAAK,CAAC;wBAAES,SAAS;wBAAMC,MAAMZ,MAAMa,WAAW,CAACD,IAAI;oBAAC;oBACzE;;wBAAMV,MAAMY,KAAK,CAACC,QAAQ,CAACC,MAAM,CAAC;4BAChCC,QAAQ;4BACRhC,IAAIA;4BACJiC,aAAa;gCACXC,cAAc;oCAAG;;4BACnB;wBACF;;;oBANA;oBAQAlB,OAAOI,IAAI,CAAC,mCAAmC;wBAAEpB,IAAAA;oBAAG;oBAE9Ca,SAAiB;wBACrBN,MAAM;wBACNP,IAAAA;oBACF;oBAEA;;wBAAO;4BACLmC,OAAO;gCACL;oCACE5B,MAAM;oCACN6B,MAAMC,KAAKC,SAAS,CAACzB;gCACvB;;4BAEF0B,mBAAmB;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,eAAQ,CAACC,gBAAS,CAACmB,aAAa,EAAE,AAAC,kCAAyC,OAARvB,UAAW;wBACvFwB,OAAOzB,AAAK,YAALA,OAAiBsB,SAAQtB,MAAMyB,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASlD;IACtB,OAAO;QACLmD,MAAM;QACNlC,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/servers/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,Q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wBACxF8C,OAAO9D,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAM8D,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASvF;IACtB,OAAO;QACLwF,MAAM;QACN5D,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/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;;;eAAwB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,MAAM;wBACNE,gBAAgBkB,aAAaS,MAAM;wBACnCzB,cAAAA;wBACAC,cAAAA;wBACAC,SAASkB;oBACX;oBAEA;;wBAAO;4BACL0C,OAAO;gCACL;oCACElE,MAAM;oCACNmE,MAAMC,KAAKC,SAAS,CAACrD;gCACvB;;4BAEFsD,mBAAmB;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,eAAQ,CAACC,gBAAS,CAACwC,aAAa,EAAE,AAAC,mCAA0C,OAAR7C,UAAW;wBACxF8C,OAAO9D,AAAK,YAALA,OAAiB4C,SAAQ5C,MAAM8D,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASvF;IACtB,OAAO;QACLwF,MAAM;QACN5D,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -13,8 +13,8 @@ var _oauthgoogle = require("@mcp-z/oauth-google");
13
13
  var _types = require("@modelcontextprotocol/sdk/types.js");
14
14
  var _googleapis = require("googleapis");
15
15
  var _zod = require("zod");
16
- var _headersutils = require("../../email/parsing/headers-utils.js");
17
- var _base64encoding = require("../../lib/base64-encoding.js");
16
+ var _headersutilsts = require("../../email/parsing/headers-utils.js");
17
+ var _base64encodingts = require("../../lib/base64-encoding.js");
18
18
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
19
19
  try {
20
20
  var info = gen[key](arg);
@@ -282,7 +282,7 @@ function handler(_0, _1) {
282
282
  }));
283
283
  fromHdr = headers.From || headers.from;
284
284
  replyToHdr = headers['Reply-To'] || headers['reply-to'];
285
- toAddr = (_ref = replyToHdr ? (0, _headersutils.extractEmails)(replyToHdr)[0] : (0, _headersutils.extractEmails)(fromHdr)[0]) !== null && _ref !== void 0 ? _ref : '';
285
+ toAddr = (_ref = replyToHdr ? (0, _headersutilsts.extractEmails)(replyToHdr)[0] : (0, _headersutilsts.extractEmails)(fromHdr)[0]) !== null && _ref !== void 0 ? _ref : '';
286
286
  subject = (_ref1 = headers.Subject || headers.subject) !== null && _ref1 !== void 0 ? _ref1 : '';
287
287
  messageIdHeader = headers['Message-ID'] || headers['Message-Id'] || headers['message-id'];
288
288
  references = (_ref2 = headers.References || headers.references) !== null && _ref2 !== void 0 ? _ref2 : '';
@@ -303,7 +303,7 @@ function handler(_0, _1) {
303
303
  '',
304
304
  body
305
305
  ].join('\r\n');
306
- raw = (0, _base64encoding.b64url)(lines);
306
+ raw = (0, _base64encodingts.b64url)(lines);
307
307
  // Prepare request body with conditional threadId for exactOptionalPropertyTypes
308
308
  threadId = (fullData === null || fullData === void 0 ? void 0 : fullData.threadId) ? String(fullData.threadId) : undefined;
309
309
  return [
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/servers/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.js';\nimport { b64url } from '../../lib/base64-encoding.js';\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;4BACY;8BACP;;;;;;;;;;;;;;;;;;;;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rC,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,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/Projects/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,CAApCD;AASR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIF,MAAC,CAACG,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,MAAMR,MAAC,CAACG,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC/CE,aAAaC,+BAAwB;AACvC;AAEA,IAAMC,sBAAsBX,MAAC,CAACC,MAAM,CAAC;IACnCW,MAAMZ,MAAC,CAACa,OAAO,CAAC;IAChBX,IAAIF,MAAC,CAACI,MAAM,GAAGG,QAAQ,CAAC;AAC1B;AAEA,IAAMO,eAAed,MAAC,CAACe,kBAAkB,CAAC,QAAQ;IAACJ;IAAqBd;CAAyB;AAEjG,IAAMmB,SAAS;IACbC,aAAa;IACblB,aAAaA;IACbe,cAAcd,MAAC,CAACC,MAAM,CAAC;QACrBiB,QAAQJ;IACV;AACF;AAKA,SAAeK;wCAAQ,KAAgC,EAAEC,KAAoB;YAApDlB,IAAIM,MAAMC,aAC3BY,QAwCYC,MACCC,OAEGA,OAZeC,mBAtB7BC,OAEFC,MAEIC,UAOCC,OACDC,SASFL,UACAM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AAmB,OAALC;wBAAQ;wBAAsB,iBAAyB,OAATC,UAAS;wBAAkB;wBAAI/B;sBAAM0E,IAAI,CAAC;oBAChMzC,MAAM0C,IAAAA,wBAAM,EAAC3C;oBAEnB,gFAAgF;oBAC1EE,WAAWlB,CAAAA,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,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"}
@@ -15,9 +15,9 @@ var _server = require("@mcp-z/server");
15
15
  var _googleapis = require("googleapis");
16
16
  var _zod = require("zod");
17
17
  var _constantsts = require("../../constants.js");
18
- var _htmlprocessing = require("../../email/parsing/html-processing.js");
19
- var _executequery = require("../../email/querying/execute-query.js");
20
- var _gmailqueryschema = require("../../schemas/gmail-query-schema.js");
18
+ var _htmlprocessingts = require("../../email/parsing/html-processing.js");
19
+ var _executequeryts = require("../../email/querying/execute-query.js");
20
+ var _gmailqueryschemats = require("../../schemas/gmail-query-schema.js");
21
21
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
22
22
  try {
23
23
  var info = gen[key](arg);
@@ -207,7 +207,7 @@ function _ts_generator(thisArg, body) {
207
207
  }
208
208
  var AuthRequiredBranchSchema = _oauthgoogle.schemas.AuthRequiredBranchSchema;
209
209
  var inputSchema = _zod.z.object(_object_spread_props(_object_spread({
210
- query: _gmailqueryschema.GmailQuerySchema.optional().describe('Structured query object for filtering messages. Use query-syntax prompt for reference.'),
210
+ query: _gmailqueryschemats.GmailQuerySchema.optional().describe('Structured query object for filtering messages. Use query-syntax prompt for reference.'),
211
211
  fields: (0, _server.createFieldsSchema)({
212
212
  availableFields: _email.EMAIL_FIELDS,
213
213
  fieldDescriptions: _email.EMAIL_FIELD_DESCRIPTIONS,
@@ -284,7 +284,7 @@ function handler(_0, _1) {
284
284
  started = Date.now();
285
285
  return [
286
286
  4,
287
- (0, _executequery.executeQuery)(query, _object_spread_props(_object_spread({
287
+ (0, _executequeryts.executeQuery)(query, _object_spread_props(_object_spread({
288
288
  client: gmail,
289
289
  logger: logger,
290
290
  pageSize: pageSize
@@ -318,7 +318,7 @@ function handler(_0, _1) {
318
318
  if (includeBody) {
319
319
  var payload = fullData === null || fullData === void 0 ? void 0 : fullData.payload;
320
320
  // Cast to Schema$MessagePart for extractBodyFromPayload
321
- var body = payload ? (0, _htmlprocessing.extractBodyFromPayload)(payload, {
321
+ var body = payload ? (0, _htmlprocessingts.extractBodyFromPayload)(payload, {
322
322
  contentType: contentType,
323
323
  excludeThreadHistory: excludeThreadHistory
324
324
  }) : '';
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/servers/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.js';\nimport { executeQuery as executeGmailQuery } from '../../email/querying/execute-query.js';\nimport { GmailQuerySchema } from '../../schemas/gmail-query-schema.js';\n\nconst inputSchema = z.object({\n query: GmailQuerySchema.optional().describe('Structured query object for filtering messages. Use query-syntax prompt for reference.'),\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 const requestedFields = parseFields(fields, EMAIL_FIELDS);\n const includeBody = requestedFields === 'all' || requestedFields.has('body');\n\n logger.info('gmail.message.search called', {\n query,\n pageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields,\n includeBody,\n accountId: extra.authContext.accountId, // Available from middleware\n });\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n\n const started = Date.now();\n\n const exec = await executeGmailQuery(\n query,\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","GmailQuerySchema","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","requestedFields","includeBody","gmail","started","exec","metadata","durationMs","filteredItems","metadataObj","error","message","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":";;;;+BA8KA;;;eAAwBA;;;qBA9KY;qBAGmI;2BAE/I;sBAIoH;0BACtG;mBACpB;2BAC+B;8BACV;4BACW;gCACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,kCAAgB,CAACC,QAAQ,GAAGC,QAAQ,CAAC;IAC5CC,QAAQC,IAAAA,0BAAkB,EAAC;QACzBC,iBAAiBC,mBAAY;QAC7BC,mBAAmBC,+BAAwB;QAC3CC,gBAAgBC,4BAAqB;QACrCC,cAAc;IAChB;GACGC,IAAAA,8BAAsB,EAAC;IAAEC,iBAAiBC,8BAAiB;IAAEC,aAAaC,0BAAa;IAAEC,UAAU;AAAQ,GAAGC,KAAK;IACtHA,OAAOC,IAAAA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C;wBAAEP,YAAAA;wBAAYD,UAAAA;oBAAS;oBAEnE,4BAA4B;oBACtBG,cAAcH;oBAEpB,8BAA8B;oBACxBX,SACJtB,UAAU,WACN;wBACEO,MAAM;wBACNP,OAAO;uBACJqF,IAAAA,wBAAgB,EAAClD,eAAeP,iBAAiBxC,mBAAY,GAC5DgD,CAAAA,wBAAAA,kCAAAA,YAAaxB,aAAa,KAAI;wBAAEA,eAAewB,YAAYxB,aAAa;oBAAC,KAE/E;wBACEL,MAAM;wBACNP,OAAO;wBACPS,OAAO0B;uBACHC,CAAAA,wBAAAA,kCAAAA,YAAaxB,aAAa,KAAI;wBAAEA,eAAewB,YAAYxB,aAAa;oBAAC;oBAGrF;;wBAAO;4BACL0E,OAAO;gCACL;oCACE/E,MAAM;oCACNgF,MAAMC,KAAKC,SAAS,CAACnE;gCACvB;;4BAEFoE,mBAAmB;gCAAEpE,QAAAA;4BAAO;wBAC9B;;;oBACOe;oBACDC,UAAUD,AAAK,YAALA,OAAiBsD,SAAQtD,MAAMC,OAAO,GAAG0B,OAAO3B;oBAChEV,OAAOU,KAAK,CAAC,8BAA8B;wBAAEA,OAAOC;oBAAQ;oBAE5D,MAAM,IAAIsD,eAAQ,CAACC,gBAAS,CAACC,aAAa,EAAE,AAAC,6BAAoC,OAARxD,UAAW;wBAClFyD,OAAO1D,AAAK,YAALA,OAAiBsD,SAAQtD,MAAM0D,KAAK,GAAGrD;oBAChD;;;;;;;IAEJ;;AAEe,SAASnE;IACtB,OAAO;QACL0F,MAAM;QACN7C,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/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 { GmailQuerySchema } from '../../schemas/gmail-query-schema.ts';\n\nconst inputSchema = z.object({\n query: GmailQuerySchema.optional().describe('Structured query object for filtering messages. Use query-syntax prompt for reference.'),\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 const requestedFields = parseFields(fields, EMAIL_FIELDS);\n const includeBody = requestedFields === 'all' || requestedFields.has('body');\n\n logger.info('gmail.message.search called', {\n query,\n pageSize,\n pageToken: pageToken ? '[provided]' : undefined,\n fields,\n includeBody,\n accountId: extra.authContext.accountId, // Available from middleware\n });\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n\n const started = Date.now();\n\n const exec = await executeGmailQuery(\n query,\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","GmailQuerySchema","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","requestedFields","includeBody","gmail","started","exec","metadata","durationMs","filteredItems","metadataObj","error","message","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":";;;;+BA8KA;;;eAAwBA;;;qBA9KY;qBAGmI;2BAE/I;sBAIoH;0BACtG;mBACpB;2BAC+B;gCACV;8BACW;kCACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AARjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAUR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,oCAAgB,CAACC,QAAQ,GAAGC,QAAQ,CAAC;IAC5CC,QAAQC,IAAAA,0BAAkB,EAAC;QACzBC,iBAAiBC,mBAAY;QAC7BC,mBAAmBC,+BAAwB;QAC3CC,gBAAgBC,4BAAqB;QACrCC,cAAc;IAChB;GACGC,IAAAA,8BAAsB,EAAC;IAAEC,iBAAiBC,8BAAiB;IAAEC,aAAaC,0BAAa;IAAEC,UAAU;AAAQ,GAAGC,KAAK;IACtHA,OAAOC,IAAAA,yBAAiB;IACxBC,aAAaC,6BAAsB;IACnCC,sBAAsBC,iCAA0B;;AAGlD,8CAA8C;AAC9C,IAAMC,6BAA6B3B,MAAC,CAACC,MAAM,CAAC;IAC1C2B,MAAM5B,MAAC,CAAC6B,OAAO,CAAC;IAChBR,OAAOrB,MAAC,CA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mBAAY,GAC5DgD,CAAAA,wBAAAA,kCAAAA,YAAaxB,aAAa,KAAI;wBAAEA,eAAewB,YAAYxB,aAAa;oBAAC,KAE/E;wBACEL,MAAM;wBACNP,OAAO;wBACPS,OAAO0B;uBACHC,CAAAA,wBAAAA,kCAAAA,YAAaxB,aAAa,KAAI;wBAAEA,eAAewB,YAAYxB,aAAa;oBAAC;oBAGrF;;wBAAO;4BACL0E,OAAO;gCACL;oCACE/E,MAAM;oCACNgF,MAAMC,KAAKC,SAAS,CAACnE;gCACvB;;4BAEFoE,mBAAmB;gCAAEpE,QAAAA;4BAAO;wBAC9B;;;oBACOe;oBACDC,UAAUD,AAAK,YAALA,OAAiBsD,SAAQtD,MAAMC,OAAO,GAAG0B,OAAO3B;oBAChEV,OAAOU,KAAK,CAAC,8BAA8B;wBAAEA,OAAOC;oBAAQ;oBAE5D,MAAM,IAAIsD,eAAQ,CAACC,gBAAS,CAACC,aAAa,EAAE,AAAC,6BAAoC,OAARxD,UAAW;wBAClFyD,OAAO1D,AAAK,YAALA,OAAiBsD,SAAQtD,MAAM0D,KAAK,GAAGrD;oBAChD;;;;;;;IAEJ;;AAEe,SAASnE;IACtB,OAAO;QACL0F,MAAM;QACN7C,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -13,8 +13,8 @@ var _oauthgoogle = require("@mcp-z/oauth-google");
13
13
  var _types = require("@modelcontextprotocol/sdk/types.js");
14
14
  var _googleapis = require("googleapis");
15
15
  var _zod = require("zod");
16
- var _rfc822builder = require("../../email/composition/rfc822-builder.js");
17
- var _base64encoding = require("../../lib/base64-encoding.js");
16
+ var _rfc822builderts = require("../../email/composition/rfc822-builder.js");
17
+ var _base64encodingts = require("../../lib/base64-encoding.js");
18
18
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
19
19
  try {
20
20
  var info = gen[key](arg);
@@ -210,8 +210,8 @@ function handler(params, extra) {
210
210
  if (cc !== undefined) msgArgs.cc = cc;
211
211
  if (bcc !== undefined) msgArgs.bcc = bcc;
212
212
  if (subject !== undefined) msgArgs.subject = subject;
213
- raw = (0, _rfc822builder.buildRfc822FromArgs)(msgArgs);
214
- encodedMessage = (0, _base64encoding.b64url)(raw);
213
+ raw = (0, _rfc822builderts.buildRfc822FromArgs)(msgArgs);
214
+ encodedMessage = (0, _base64encodingts.b64url)(raw);
215
215
  gmail = _googleapis.google.gmail({
216
216
  version: 'v1',
217
217
  auth: extra.authContext.auth
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/servers/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 { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { buildRfc822FromArgs } from '../../email/composition/rfc822-builder.js';\nimport { b64url } from '../../lib/base64-encoding.js';\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 McpError(ErrorCode.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 McpError(ErrorCode.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","McpError","ErrorCode","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;qBAKY;0BACb;mBACL;6BACkB;8BACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,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["/Users/kevin/Dev/Projects/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 { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\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 McpError(ErrorCode.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 McpError(ErrorCode.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","McpError","ErrorCode","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","structured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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,eAAQ,CAACC,gBAAS,CAAC+B,aAAa,EAAE,AAAC,0BAAiC,OAARlC,UAAW;wBAC/EmC,OAAOpC,AAAK,YAALA,OAAiBiC,SAAQjC,MAAMoC,KAAK,GAAG9B;oBAChD;;;;;;;IAEJ;;AAEe,SAAS/C;IACtB,OAAO;QACL8E,MAAM;QACNpD,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -18,9 +18,9 @@ var _promises = require("fs/promises");
18
18
  var _googleapis = require("googleapis");
19
19
  var _zod = require("zod");
20
20
  var _constantsts = require("../../constants.js");
21
- var _htmlprocessing = require("../../email/parsing/html-processing.js");
22
- var _executequery = require("../../email/querying/execute-query.js");
23
- var _gmailqueryschema = require("../../schemas/gmail-query-schema.js");
21
+ var _htmlprocessingts = require("../../email/parsing/html-processing.js");
22
+ var _executequeryts = require("../../email/querying/execute-query.js");
23
+ var _gmailqueryschemats = require("../../schemas/gmail-query-schema.js");
24
24
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
25
25
  try {
26
26
  var info = gen[key](arg);
@@ -212,7 +212,7 @@ var AuthRequiredBranchSchema = _oauthgoogle.schemas.AuthRequiredBranchSchema;
212
212
  var DEFAULT_MAX_ITEMS = 10000;
213
213
  var MAX_EXPORT_ITEMS = 50000;
214
214
  var inputSchema = _zod.z.object({
215
- query: _gmailqueryschema.GmailQuerySchema.optional().describe('Structured query object for filtering messages. Use query-syntax prompt for reference.'),
215
+ query: _gmailqueryschemats.GmailQuerySchema.optional().describe('Structured query object for filtering messages. Use query-syntax prompt for reference.'),
216
216
  maxItems: _zod.z.number().int().positive().max(MAX_EXPORT_ITEMS).default(DEFAULT_MAX_ITEMS).describe("Maximum messages to export (default: ".concat(DEFAULT_MAX_ITEMS, ", max: ").concat(MAX_EXPORT_ITEMS, ")")),
217
217
  filename: _zod.z.string().trim().min(1).default('gmail-messages.csv').describe('Output filename (default: gmail-messages.csv)'),
218
218
  contentType: _email.EmailContentTypeSchema,
@@ -328,7 +328,7 @@ var config = {
328
328
  pageSize = Math.min(remainingItems, _constantsts.DEFAULT_PAGE_SIZE);
329
329
  return [
330
330
  4,
331
- (0, _executequery.executeQuery)(query, _object_spread_props(_object_spread({
331
+ (0, _executequeryts.executeQuery)(query, _object_spread_props(_object_spread({
332
332
  client: gmail,
333
333
  logger: logger,
334
334
  pageSize: pageSize
@@ -352,7 +352,7 @@ var config = {
352
352
  }));
353
353
  var payload = fullData === null || fullData === void 0 ? void 0 : fullData.payload;
354
354
  // Cast to Schema$MessagePart for extractBodyFromPayload
355
- var body = payload ? (0, _htmlprocessing.extractBodyFromPayload)(payload, {
355
+ var body = payload ? (0, _htmlprocessingts.extractBodyFromPayload)(payload, {
356
356
  contentType: contentType,
357
357
  excludeThreadHistory: excludeThreadHistory
358
358
  }) : '';
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/servers/mcp-gmail/src/mcp/tools/messages-export-csv.ts"],"sourcesContent":["import { EmailContentTypeSchema, ExcludeThreadHistorySchema } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { getFileUri, reserveFile, type ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\n\nimport { stringify } from 'csv-stringify/sync';\nimport { createWriteStream } from 'fs';\nimport { unlink } from 'fs/promises';\nimport { type gmail_v1, google } from 'googleapis';\nimport { z } from 'zod';\nimport { DEFAULT_PAGE_SIZE } from '../../constants.ts';\nimport { extractBodyFromPayload } from '../../email/parsing/html-processing.js';\nimport { executeQuery as executeGmailQuery } from '../../email/querying/execute-query.js';\nimport { GmailQuerySchema } from '../../schemas/gmail-query-schema.js';\nimport type { StorageExtra } from '../../types.js';\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: GmailQuerySchema.optional().describe('Structured query object for filtering messages. Use query-syntax prompt for reference.'),\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, storageDir, baseUrl } = storageContext;\n\n logger.info('gmail.messages.export-csv called', {\n query,\n maxItems,\n filename,\n accountId: extra.authContext.accountId,\n });\n\n // Reserve file location for streaming write (creates directory, generates ID, formats filename)\n const reservation = await reserveFile(filename, {\n storageDir,\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 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 query,\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 storageDir,\n ...(baseUrl && { baseUrl }),\n endpoint: '/files',\n });\n\n const result: Output = {\n type: 'success' as const,\n uri,\n filename: storedName,\n rowCount: totalRows,\n truncated,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n // CRITICAL: Clean up partial CSV file on error\n try {\n await unlink(fullPath);\n logger.debug('Cleaned up partial CSV file after error', { path: fullPath });\n } catch (_cleanupError) {\n logger.debug('Could not clean up CSV file (may not exist)', { path: fullPath });\n }\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.messages.export-csv error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error exporting messages to CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'messages-export-csv',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","inputSchema","z","object","query","GmailQuerySchema","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","storageDir","baseUrl","reservation","storedName","fullPath","gmail","csvHeaders","writeStream","headerLine","totalRows","nextPageToken","started","exec","remainingItems","pageSize","csvRows","rowsContent","durationMs","error","_cleanupError","message","info","accountId","authContext","reserveFile","path","google","version","auth","createWriteStream","encoding","stringify","header","quoted","quote","escape","write","Date","now","Math","DEFAULT_PAGE_SIZE","executeGmailQuery","client","undefined","pageToken","includeBody","full","fullData","headersArray","Array","isArray","payload","headers","Object","fromEntries","map","h","String","name","value","body","extractBodyFromPayload","labelIds","id","threadId","from","From","to","To","cc","Cc","bcc","Bcc","subject","Subject","date","snippet","provider","labels","join","items","row","length","metadata","batchSize","hasMore","Boolean","Promise","resolve","reject","end","on","getFileUri","endpoint","content","text","JSON","structuredContent","unlink","debug","Error","McpError","ErrorCode","InternalError","stack"],"mappings":";;;;+BAoQA;;;eAAwBA;;;qBApQ2C;2BAE3C;sBAIiC;qBACrB;oBAEV;kBACQ;wBACX;0BACe;mBACpB;2BACgB;8BACK;4BACW;gCACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAbjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAgBR,IAAME,oBAAoB;AAC1B,IAAMC,mBAAmB;AAsBzB,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,kCAAgB,CAACC,QAAQ,GAAGC,QAAQ,CAAC;IAC5CC,UAAUN,MAAC,CAACO,MAAM,GAAGC,GAAG,GAAGC,QAAQ,GAAGC,GAAG,CAACZ,kBAAkBa,OAAO,CAACd,mBAAmBQ,QAAQ,CAAC,AAAC,wCAAkEP,OAA3BD,mBAAkB,WAA0B,OAAjBC,kBAAiB;IACpLc,UAAUZ,MAAC,CA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,SAAStF;IACtB,OAAO;QACLqG,MAAM;QACNlE,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-gmail/src/mcp/tools/messages-export-csv.ts"],"sourcesContent":["import { EmailContentTypeSchema, ExcludeThreadHistorySchema } from '@mcp-z/email';\nimport type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport { getFileUri, reserveFile, type ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\n\nimport { stringify } from 'csv-stringify/sync';\nimport { createWriteStream } from 'fs';\nimport { unlink } from 'fs/promises';\nimport { type gmail_v1, google } from 'googleapis';\nimport { z } from 'zod';\nimport { DEFAULT_PAGE_SIZE } from '../../constants.ts';\nimport { extractBodyFromPayload } from '../../email/parsing/html-processing.ts';\nimport { executeQuery as executeGmailQuery } from '../../email/querying/execute-query.ts';\nimport { GmailQuerySchema } 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: GmailQuerySchema.optional().describe('Structured query object for filtering messages. Use query-syntax prompt for reference.'),\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, storageDir, baseUrl } = storageContext;\n\n logger.info('gmail.messages.export-csv called', {\n query,\n maxItems,\n filename,\n accountId: extra.authContext.accountId,\n });\n\n // Reserve file location for streaming write (creates directory, generates ID, formats filename)\n const reservation = await reserveFile(filename, {\n storageDir,\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 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 query,\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 storageDir,\n ...(baseUrl && { baseUrl }),\n endpoint: '/files',\n });\n\n const result: Output = {\n type: 'success' as const,\n uri,\n filename: storedName,\n rowCount: totalRows,\n truncated,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n // CRITICAL: Clean up partial CSV file on error\n try {\n await unlink(fullPath);\n logger.debug('Cleaned up partial CSV file after error', { path: fullPath });\n } catch (_cleanupError) {\n logger.debug('Could not clean up CSV file (may not exist)', { path: fullPath });\n }\n\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.messages.export-csv error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error exporting messages to CSV: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'messages-export-csv',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","DEFAULT_MAX_ITEMS","MAX_EXPORT_ITEMS","inputSchema","z","object","query","GmailQuerySchema","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","storageDir","baseUrl","reservation","storedName","fullPath","gmail","csvHeaders","writeStream","headerLine","totalRows","nextPageToken","started","exec","remainingItems","pageSize","csvRows","rowsContent","durationMs","error","_cleanupError","message","info","accountId","authContext","reserveFile","path","google","version","auth","createWriteStream","encoding","stringify","header","quoted","quote","escape","write","Date","now","Math","DEFAULT_PAGE_SIZE","executeGmailQuery","client","undefined","pageToken","includeBody","full","fullData","headersArray","Array","isArray","payload","headers","Object","fromEntries","map","h","String","name","value","body","extractBodyFromPayload","labelIds","id","threadId","from","From","to","To","cc","Cc","bcc","Bcc","subject","Subject","date","snippet","provider","labels","join","items","row","length","metadata","batchSize","hasMore","Boolean","Promise","resolve","reject","end","on","getFileUri","endpoint","content","text","JSON","structuredContent","unlink","debug","Error","McpError","ErrorCode","InternalError","stack"],"mappings":";;;;+BAoQA;;;eAAwBA;;;qBApQ2C;2BAE3C;sBAIiC;qBACrB;oBAEV;kBACQ;wBACX;0BACe;mBACpB;2BACgB;gCACK;8BACW;kCACjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAbjC,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAgBR,IAAME,oBAAoB;AAC1B,IAAMC,mBAAmB;AAsBzB,IAAMC,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,OAAOC,oCAAgB,CAACC,QAAQ,GAAGC,QAAQ,CAAC;IAC5CC,UAAUN,MAAC,CAACO,MAAM,GAAGC,GAAG,GAAGC,QAAQ,GAAG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ACC,aAAa,EAAE,AAAC,oCAA2C,OAARnF,UAAW;wBACzFoF,OAAOtF,AAAK,YAALA,OAAiBkF,SAAQlF,MAAMsF,KAAK,GAAG7D;oBAChD;;;;;;;IAEJ;;AAEe,SAAStF;IACtB,OAAO;QACLqG,MAAM;QACNlE,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/servers/mcp-gmail/src/schemas/gmail-query-schema.ts"],"sourcesContent":["import { type BaseEmailQueryFields, baseEmailQueryFields, type FieldOperator, FieldOperatorSchema } from '@mcp-z/email';\nimport { z } from 'zod';\n\n/**\n * Gmail-specific query schema with recursive operators and Gmail features.\n *\n * Includes Gmail-specific features:\n * - fuzzyPhrase: Approximate phrase matching (Gmail's quoted string behavior with relevance ranking)\n * - categories: Gmail system categories (primary, social, promotions, updates, forums)\n * - label: User-created Gmail labels (case-sensitive, discovered via gmail-labels-list)\n * - rawGmailQuery: Escape hatch for advanced Gmail query syntax\n *\n * Plus all base fields from baseEmailQueryFields:\n * - Email addresses: from, to, cc, bcc (support string or field operators)\n * - Content: subject, body, text\n * - Flags: hasAttachment, isRead\n * - Date range: date { $gte, $lt }\n * - Logical operators: $and, $or, $not (recursive)\n *\n * Note: Cast through unknown to work around Zod's lazy schema type inference issue\n * with exactOptionalPropertyTypes. The runtime schema is correct; this cast ensures\n * TypeScript sees the strict GmailQuery type everywhere the schema is used.\n */\nexport const GmailQuerySchema = z.lazy(() =>\n z\n .object({\n // Logical operators for combining conditions (recursive)\n $and: z.array(GmailQuerySchema).optional().describe('Array of conditions that must ALL match'),\n $or: z.array(GmailQuerySchema).optional().describe('Array of conditions where ANY must match'),\n $not: GmailQuerySchema.optional().describe('Nested condition that must NOT match'),\n\n // Spread base email query fields (from, to, subject, body, etc.)\n ...baseEmailQueryFields,\n\n // Gmail-specific features\n\n // Fuzzy phrase matching - Gmail's approximate search using quoted strings\n fuzzyPhrase: z.string().min(1).optional().describe('Fuzzy phrase matching - words should appear together (approximate matching). Gmail uses relevance-based matching.'),\n\n // Gmail system categories with field operator support\n categories: z\n .union([\n z.enum(['primary', 'social', 'promotions', 'updates', 'forums']),\n z\n .object({\n $any: z.array(z.enum(['primary', 'social', 'promotions', 'updates', 'forums'])).optional(),\n $all: z.array(z.enum(['primary', 'social', 'promotions', 'updates', 'forums'])).optional(),\n $none: z.array(z.enum(['primary', 'social', 'promotions', 'updates', 'forums'])).optional(),\n })\n .strict(),\n ])\n .optional()\n .describe('Filter by Gmail system categories (primary, social, promotions, updates, forums)'),\n\n // User-created labels\n label: z\n .union([z.string().min(1), FieldOperatorSchema])\n .optional()\n .describe('Filter by user-created labels (case-sensitive). Use gmail-labels-list to see available labels'),\n\n // Raw Gmail query string - escape hatch for advanced syntax\n rawGmailQuery: z.string().min(1).optional().describe('Raw Gmail query syntax for advanced use cases. Bypasses schema validation - use sparingly.'),\n })\n .strict()\n) as unknown as z.ZodType<GmailQuery>;\n\nexport type GmailQuery = BaseEmailQueryFields & {\n $and?: GmailQuery[];\n $or?: GmailQuery[];\n $not?: GmailQuery;\n fuzzyPhrase?: string;\n categories?:\n | 'primary'\n | 'social'\n | 'promotions'\n | 'updates'\n | 'forums'\n | {\n $any?: ('primary' | 'social' | 'promotions' | 'updates' | 'forums')[];\n $all?: ('primary' | 'social' | 'promotions' | 'updates' | 'forums')[];\n $none?: ('primary' | 'social' | 'promotions' | 'updates' | 'forums')[];\n };\n label?: string | FieldOperator;\n rawGmailQuery?: string;\n};\n"],"names":["GmailQuerySchema","z","lazy","object","$and","array","optional","describe","$or","$not","baseEmailQueryFields","fuzzyPhrase","string","min","categories","union","enum","$any","$all","$none","strict","label","FieldOperatorSchema","rawGmailQuery"],"mappings":";;;;+BAuBaA;;;eAAAA;;;qBAvB4F;mBACvF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBX,IAAMA,mBAAmBC,MAAC,CAACC,IAAI,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AAC;QAEtDa,MAAM"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-gmail/src/schemas/gmail-query-schema.ts"],"sourcesContent":["import { type BaseEmailQueryFields, baseEmailQueryFields, type FieldOperator, FieldOperatorSchema } from '@mcp-z/email';\nimport { z } from 'zod';\n\n/**\n * Gmail-specific query schema with recursive operators and Gmail features.\n *\n * Includes Gmail-specific features:\n * - fuzzyPhrase: Approximate phrase matching (Gmail's quoted string behavior with relevance ranking)\n * - categories: Gmail system categories (primary, social, promotions, updates, forums)\n * - label: User-created Gmail labels (case-sensitive, discovered via gmail-labels-list)\n * - rawGmailQuery: Escape hatch for advanced Gmail query syntax\n *\n * Plus all base fields from baseEmailQueryFields:\n * - Email addresses: from, to, cc, bcc (support string or field operators)\n * - Content: subject, body, text\n * - Flags: hasAttachment, isRead\n * - Date range: date { $gte, $lt }\n * - Logical operators: $and, $or, $not (recursive)\n *\n * Note: Cast through unknown to work around Zod's lazy schema type inference issue\n * with exactOptionalPropertyTypes. The runtime schema is correct; this cast ensures\n * TypeScript sees the strict GmailQuery type everywhere the schema is used.\n */\nexport const GmailQuerySchema = z.lazy(() =>\n z\n .object({\n // Logical operators for combining conditions (recursive)\n $and: z.array(GmailQuerySchema).optional().describe('Array of conditions that must ALL match'),\n $or: z.array(GmailQuerySchema).optional().describe('Array of conditions where ANY must match'),\n $not: GmailQuerySchema.optional().describe('Nested condition that must NOT match'),\n\n // Spread base email query fields (from, to, subject, body, etc.)\n ...baseEmailQueryFields,\n\n // Gmail-specific features\n\n // Fuzzy phrase matching - Gmail's approximate search using quoted strings\n fuzzyPhrase: z.string().min(1).optional().describe('Fuzzy phrase matching - words should appear together (approximate matching). Gmail uses relevance-based matching.'),\n\n // Gmail system categories with field operator support\n categories: z\n .union([\n z.enum(['primary', 'social', 'promotions', 'updates', 'forums']),\n z\n .object({\n $any: z.array(z.enum(['primary', 'social', 'promotions', 'updates', 'forums'])).optional(),\n $all: z.array(z.enum(['primary', 'social', 'promotions', 'updates', 'forums'])).optional(),\n $none: z.array(z.enum(['primary', 'social', 'promotions', 'updates', 'forums'])).optional(),\n })\n .strict(),\n ])\n .optional()\n .describe('Filter by Gmail system categories (primary, social, promotions, updates, forums)'),\n\n // User-created labels\n label: z\n .union([z.string().min(1), FieldOperatorSchema])\n .optional()\n .describe('Filter by user-created labels (case-sensitive). Use gmail-labels-list to see available labels'),\n\n // Raw Gmail query string - escape hatch for advanced syntax\n rawGmailQuery: z.string().min(1).optional().describe('Raw Gmail query syntax for advanced use cases. Bypasses schema validation - use sparingly.'),\n })\n .strict()\n) as unknown as z.ZodType<GmailQuery>;\n\nexport type GmailQuery = BaseEmailQueryFields & {\n $and?: GmailQuery[];\n $or?: GmailQuery[];\n $not?: GmailQuery;\n fuzzyPhrase?: string;\n categories?:\n | 'primary'\n | 'social'\n | 'promotions'\n | 'updates'\n | 'forums'\n | {\n $any?: ('primary' | 'social' | 'promotions' | 'updates' | 'forums')[];\n $all?: ('primary' | 'social' | 'promotions' | 'updates' | 'forums')[];\n $none?: ('primary' | 'social' | 'promotions' | 'updates' | 'forums')[];\n };\n label?: string | FieldOperator;\n rawGmailQuery?: string;\n};\n"],"names":["GmailQuerySchema","z","lazy","object","$and","array","optional","describe","$or","$not","baseEmailQueryFields","fuzzyPhrase","string","min","categories","union","enum","$any","$all","$none","strict","label","FieldOperatorSchema","rawGmailQuery"],"mappings":";;;;+BAuBaA;;;eAAAA;;;qBAvB4F;mBACvF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBX,IAAMA,mBAAmBC,MAAC,CAACC,IAAI,CAAC;WACrCD,MAAC,CACEE,MAAM,CAAC;QACN,yDAAyD;QACzDC,MAAMH,MAAC,CAACI,KAAK,CAACL,kBAAkBM,QAAQ,GAAGC,QAAQ,CAAC;QACpDC,KAAKP,MAAC,CAACI,KAAK,CAACL,kBAAkBM,QAAQ,GAAGC,QAAQ,CAAC;QACnDE,MAAMT,iBAAiBM,QAAQ,GAAGC,QAAQ,CAAC;OAGxCG,2BAAoB;QAEvB,0BAA0B;QAE1B,0EAA0E;QAC1EC,aAAaV,MAAC,CAACW,MAAM,GAAGC,GAAG,CAAC,GAAGP,QAAQ,GAAGC,QAAQ,CAAC;QAEnD,sDAAsD;QACtDO,YAAYb,MAAC,CACVc,KAAK,CAAC;YACLd,MAAC,CAACe,IAAI,CAAC;gBAAC;gBAAW;gBAAU;gBAAc;gBAAW;aAAS;YAC/Df,MAAC,CACEE,MAAM,CAAC;gBACNc,MAAMhB,MAAC,CAACI,KAAK,CAACJ,MAAC,CAACe,IAAI,CAAC;oBAAC;oBAAW;oBAAU;oBAAc;oBAAW;iBAAS,GAAGV,QAAQ;gBACxFY,MAAMjB,MAAC,CAACI,KAAK,CAACJ,MAAC,CAACe,IAAI,CAAC;oBAAC;oBAAW;oBAAU;oBAAc;oBAAW;iBAAS,GAAGV,QAAQ;gBACxFa,OAAOlB,MAAC,CAACI,KAAK,CAACJ,MAAC,CAACe,IAAI,CAAC;oBAAC;oBAAW;oBAAU;oBAAc;oBAAW;iBAAS,GAAGV,QAAQ;YAC3F,GACCc,MAAM;SACV,EACAd,QAAQ,GACRC,QAAQ,CAAC;QAEZ,sBAAsB;QACtBc,OAAOpB,MAAC,CACLc,KAAK,CAAC;YAACd,MAAC,CAACW,MAAM,GAAGC,GAAG,CAAC;YAAIS,0BAAmB;SAAC,EAC9ChB,QAAQ,GACRC,QAAQ,CAAC;QAEZ,4DAA4D;QAC5DgB,eAAetB,MAAC,CAACW,MAAM,GAAGC,GAAG,CAAC,GAAGP,QAAQ,GAAGC,QAAQ,CAAC;QAEtDa,MAAM"}
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/Projects/ai/mcp-z/servers/mcp-gmail/src/schemas/index.ts"],"sourcesContent":["export * from './gmail-query-schema.js';\n"],"names":[],"mappings":";;;;qBAAc"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/mcp-gmail/src/schemas/index.ts"],"sourcesContent":["export * from './gmail-query-schema.ts';\n"],"names":[],"mappings":";;;;qBAAc"}
@@ -184,7 +184,17 @@ function parseConfig(args, env) {
184
184
  // Parse repository URL from package.json, stripping git+ prefix and .git suffix
185
185
  var rawRepoUrl = _type_of(pkg.repository) === 'object' ? pkg.repository.url : pkg.repository;
186
186
  var repositoryUrl = (_ref = rawRepoUrl === null || rawRepoUrl === void 0 ? void 0 : rawRepoUrl.replace(/^git\+/, '').replace(/\.git$/, '')) !== null && _ref !== void 0 ? _ref : "https://github.com/mcp-z/".concat(name);
187
- var rootDir = process.cwd() === '/' ? (0, _os.homedir)() : process.cwd();
187
+ var rootDir = (0, _os.homedir)();
188
+ try {
189
+ var configPath = (0, _server.findConfigPath)({
190
+ config: '.mcp.json',
191
+ cwd: process.cwd(),
192
+ stopDir: (0, _os.homedir)()
193
+ });
194
+ rootDir = _path.dirname(configPath);
195
+ } catch (unused) {
196
+ rootDir = (0, _os.homedir)();
197
+ }
188
198
  var baseDir = _path.join(rootDir, '.mcp-z');
189
199
  var cliLogLevel = typeof values['log-level'] === 'string' ? values['log-level'] : undefined;
190
200
  var envLogLevel = env.LOG_LEVEL;