@mcp-z/mcp-gmail 1.1.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/cjs/index.js.map +1 -1
  2. package/dist/cjs/lib/google-auth.d.cts +9 -0
  3. package/dist/cjs/lib/google-auth.d.ts +9 -0
  4. package/dist/cjs/lib/google-auth.js +16 -0
  5. package/dist/cjs/lib/google-auth.js.map +1 -0
  6. package/dist/cjs/mcp/prompts/draft-email.d.cts +2 -3
  7. package/dist/cjs/mcp/prompts/draft-email.d.ts +2 -3
  8. package/dist/cjs/mcp/prompts/draft-email.js.map +1 -1
  9. package/dist/cjs/mcp/prompts/query-syntax.d.cts +2 -3
  10. package/dist/cjs/mcp/prompts/query-syntax.d.ts +2 -3
  11. package/dist/cjs/mcp/prompts/query-syntax.js.map +1 -1
  12. package/dist/cjs/mcp/resources/email.d.cts +6 -5
  13. package/dist/cjs/mcp/resources/email.d.ts +6 -5
  14. package/dist/cjs/mcp/resources/email.js +4 -3
  15. package/dist/cjs/mcp/resources/email.js.map +1 -1
  16. package/dist/cjs/mcp/tools/categories-list.js +4 -3
  17. package/dist/cjs/mcp/tools/categories-list.js.map +1 -1
  18. package/dist/cjs/mcp/tools/label-add.js +5 -4
  19. package/dist/cjs/mcp/tools/label-add.js.map +1 -1
  20. package/dist/cjs/mcp/tools/label-delete.js +8 -7
  21. package/dist/cjs/mcp/tools/label-delete.js.map +1 -1
  22. package/dist/cjs/mcp/tools/labels-list.d.cts +3 -3
  23. package/dist/cjs/mcp/tools/labels-list.d.ts +3 -3
  24. package/dist/cjs/mcp/tools/labels-list.js +4 -3
  25. package/dist/cjs/mcp/tools/labels-list.js.map +1 -1
  26. package/dist/cjs/mcp/tools/message-get.js +5 -5
  27. package/dist/cjs/mcp/tools/message-get.js.map +1 -1
  28. package/dist/cjs/mcp/tools/message-mark-read.js +5 -4
  29. package/dist/cjs/mcp/tools/message-mark-read.js.map +1 -1
  30. package/dist/cjs/mcp/tools/message-move-to-trash.js +8 -7
  31. package/dist/cjs/mcp/tools/message-move-to-trash.js.map +1 -1
  32. package/dist/cjs/mcp/tools/message-respond.js +6 -5
  33. package/dist/cjs/mcp/tools/message-respond.js.map +1 -1
  34. package/dist/cjs/mcp/tools/message-search.js +4 -4
  35. package/dist/cjs/mcp/tools/message-search.js.map +1 -1
  36. package/dist/cjs/mcp/tools/message-send.js +5 -4
  37. package/dist/cjs/mcp/tools/message-send.js.map +1 -1
  38. package/dist/cjs/mcp/tools/messages-export-csv.js +3 -3
  39. package/dist/cjs/mcp/tools/messages-export-csv.js.map +1 -1
  40. package/dist/cjs/setup/http.d.cts +1 -1
  41. package/dist/cjs/setup/http.d.ts +1 -1
  42. package/dist/cjs/setup/http.js +1 -2
  43. package/dist/cjs/setup/http.js.map +1 -1
  44. package/dist/cjs/setup/stdio.d.cts +1 -1
  45. package/dist/cjs/setup/stdio.d.ts +1 -1
  46. package/dist/cjs/setup/stdio.js +1 -2
  47. package/dist/cjs/setup/stdio.js.map +1 -1
  48. package/dist/esm/index.js +1 -1
  49. package/dist/esm/index.js.map +1 -1
  50. package/dist/esm/lib/google-auth.d.ts +9 -0
  51. package/dist/esm/lib/google-auth.js +11 -0
  52. package/dist/esm/lib/google-auth.js.map +1 -0
  53. package/dist/esm/mcp/prompts/draft-email.d.ts +2 -3
  54. package/dist/esm/mcp/prompts/draft-email.js.map +1 -1
  55. package/dist/esm/mcp/prompts/query-syntax.d.ts +2 -3
  56. package/dist/esm/mcp/prompts/query-syntax.js.map +1 -1
  57. package/dist/esm/mcp/resources/email.d.ts +6 -5
  58. package/dist/esm/mcp/resources/email.js +3 -2
  59. package/dist/esm/mcp/resources/email.js.map +1 -1
  60. package/dist/esm/mcp/tools/categories-list.js +4 -3
  61. package/dist/esm/mcp/tools/categories-list.js.map +1 -1
  62. package/dist/esm/mcp/tools/label-add.js +5 -4
  63. package/dist/esm/mcp/tools/label-add.js.map +1 -1
  64. package/dist/esm/mcp/tools/label-delete.js +8 -7
  65. package/dist/esm/mcp/tools/label-delete.js.map +1 -1
  66. package/dist/esm/mcp/tools/labels-list.d.ts +3 -3
  67. package/dist/esm/mcp/tools/labels-list.js +4 -3
  68. package/dist/esm/mcp/tools/labels-list.js.map +1 -1
  69. package/dist/esm/mcp/tools/message-get.js +6 -6
  70. package/dist/esm/mcp/tools/message-get.js.map +1 -1
  71. package/dist/esm/mcp/tools/message-mark-read.js +5 -4
  72. package/dist/esm/mcp/tools/message-mark-read.js.map +1 -1
  73. package/dist/esm/mcp/tools/message-move-to-trash.js +8 -7
  74. package/dist/esm/mcp/tools/message-move-to-trash.js.map +1 -1
  75. package/dist/esm/mcp/tools/message-respond.js +6 -5
  76. package/dist/esm/mcp/tools/message-respond.js.map +1 -1
  77. package/dist/esm/mcp/tools/message-search.js +4 -3
  78. package/dist/esm/mcp/tools/message-search.js.map +1 -1
  79. package/dist/esm/mcp/tools/message-send.js +5 -4
  80. package/dist/esm/mcp/tools/message-send.js.map +1 -1
  81. package/dist/esm/mcp/tools/messages-export-csv.js +4 -4
  82. package/dist/esm/mcp/tools/messages-export-csv.js.map +1 -1
  83. package/dist/esm/setup/http.d.ts +1 -1
  84. package/dist/esm/setup/http.js +1 -2
  85. package/dist/esm/setup/http.js.map +1 -1
  86. package/dist/esm/setup/stdio.d.ts +1 -1
  87. package/dist/esm/setup/stdio.js +1 -2
  88. package/dist/esm/setup/stdio.js.map +1 -1
  89. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/index.ts"],"sourcesContent":["import { handleVersionHelp } from './setup/version-help.ts';\nimport type { ServerConfig } from './types.ts';\n\nexport { GOOGLE_SCOPE } from './constants.ts';\nexport * as mcp from './mcp/index.ts';\n// Export types and schemas for documentation\nexport type { Input as CategoriesListInput } from './mcp/tools/categories-list.ts';\nexport { inputSchema as CategoriesListInputSchema } from './mcp/tools/categories-list.ts';\nexport type { Input as LabelsListInput } from './mcp/tools/labels-list.ts';\nexport { inputSchema as LabelsListInputSchema } from './mcp/tools/labels-list.ts';\nexport * as schemas from './schemas/index.ts';\nexport * as setup from './setup/index.ts';\nexport * from './types.ts';\n\nexport async function startServer(config: ServerConfig): Promise<void> {\n // createHTTPServer/createStdioServer pull in @modelcontextprotocol/sdk and every mcp/tools/*.ts\n // (googleapis included); deferred so a --version/--help run never reaches them.\n const { createHTTPServer } = await import('./setup/http.ts');\n const { createStdioServer } = await import('./setup/stdio.ts');\n const { logger, close } = config.transport.type === 'stdio' ? await createStdioServer(config) : await createHTTPServer(config);\n\n process.on('SIGINT', async () => {\n await close();\n process.exit(0);\n });\n\n logger.info(`Server started with ${config.transport.type} transport`);\n await new Promise(() => {});\n}\n\nexport default async function main(): Promise<void> {\n // Check for help/version flags FIRST, before config parsing\n const versionHelpResult = handleVersionHelp(process.argv);\n if (versionHelpResult.handled) {\n console.log(versionHelpResult.output);\n process.exit(0);\n }\n\n // Only parse config if no help/version flags. config.ts's own heavy imports (@mcp-z/oauth-google,\n // @mcp-z/server) are deferred internally, so this static-looking call stays cheap until here.\n const { createConfig } = await import('./setup/config.ts');\n const config = createConfig();\n await startServer(config);\n}\n\nif (process.argv[1] === new URL(import.meta.url).pathname) {\n main();\n}\n"],"names":["CategoriesListInputSchema","inputSchema","GOOGLE_SCOPE","LabelsListInputSchema","main","mcp","schemas","setup","startServer","config","createHTTPServer","createStdioServer","logger","close","transport","type","process","on","exit","info","Promise","versionHelpResult","createConfig","handleVersionHelp","argv","handled","console","log","output","URL","pathname"],"mappings":";;;;;;;;;;;QAOwBA;eAAfC,6BAAW;;QAJXC;eAAAA,yBAAY;;QAMGC;eAAfF,yBAAW;;QAqBpB;eAA8BG;;QA1BlBC;;;QAMAC;;;QACAC;;;QAGUC;eAAAA;;;6BAdY;2BAGL;+DACR;gCAGoC;4BAEJ;gEAC5B;gEACF;qBACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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EAAE;IACzD1B;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/index.ts"],"sourcesContent":["import { handleVersionHelp } from './setup/version-help.ts';\nimport type { ServerConfig } from './types.ts';\n\nexport { GOOGLE_SCOPE } from './constants.ts';\nexport * as mcp from './mcp/index.ts';\n// Export types and schemas for documentation\nexport type { Input as CategoriesListInput } from './mcp/tools/categories-list.ts';\nexport { inputSchema as CategoriesListInputSchema } from './mcp/tools/categories-list.ts';\nexport type { Input as LabelsListInput } from './mcp/tools/labels-list.ts';\nexport { inputSchema as LabelsListInputSchema } from './mcp/tools/labels-list.ts';\nexport * as schemas from './schemas/index.ts';\nexport * as setup from './setup/index.ts';\nexport * from './types.ts';\n\nexport async function startServer(config: ServerConfig): Promise<void> {\n // createHTTPServer/createStdioServer pull in @mcp-z/server and every mcp/tools/*.ts\n // (googleapis included); deferred so a --version/--help run never reaches them.\n const { createHTTPServer } = await import('./setup/http.ts');\n const { createStdioServer } = await import('./setup/stdio.ts');\n const { logger, close } = config.transport.type === 'stdio' ? await createStdioServer(config) : await createHTTPServer(config);\n\n process.on('SIGINT', async () => {\n await close();\n process.exit(0);\n });\n\n logger.info(`Server started with ${config.transport.type} transport`);\n await new Promise(() => {});\n}\n\nexport default async function main(): Promise<void> {\n // Check for help/version flags FIRST, before config parsing\n const versionHelpResult = handleVersionHelp(process.argv);\n if (versionHelpResult.handled) {\n console.log(versionHelpResult.output);\n process.exit(0);\n }\n\n // Only parse config if no help/version flags. config.ts's own heavy imports (@mcp-z/oauth-google,\n // @mcp-z/server) are deferred internally, so this static-looking call stays cheap until here.\n const { createConfig } = await import('./setup/config.ts');\n const config = createConfig();\n await startServer(config);\n}\n\nif (process.argv[1] === new URL(import.meta.url).pathname) {\n main();\n}\n"],"names":["CategoriesListInputSchema","inputSchema","GOOGLE_SCOPE","LabelsListInputSchema","main","mcp","schemas","setup","startServer","config","createHTTPServer","createStdioServer","logger","close","transport","type","process","on","exit","info","Promise","versionHelpResult","createConfig","handleVersionHelp","argv","handled","console","log","output","URL","pathname"],"mappings":";;;;;;;;;;;QAOwBA;eAAfC,6BAAW;;QAJXC;eAAAA,yBAAY;;QAMGC;eAAfF,yBAAW;;QAqBpB;eAA8BG;;QA1BlBC;;;QAMAC;;;QACAC;;;QAGUC;eAAAA;;;6BAdY;2BAGL;+DACR;gCAGoC;4BAEJ;gEAC5B;gEACF;qBACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEP,SAAeA,YAAYC,MAAoB;;YAG5CC,kBACAC,mBACkBF,MAAlBG,QAAQC;;;;oBAFa;;wBAAM;2EAAA,QAAO;;;;oBAAlCH,mBAAqB,cAArBA;oBACsB;;wBAAM;2EAAA,QAAO;;;;oBAAnCC,oBAAsB,cAAtBA;yBACkBF,CAAAA,OAAOK,SAAS,CAACC,IAAI,KAAK,OAAM,GAAhCN;;;;oBAAoC;;wBAAME,kBAAkBF;;;2BAAxB;;;;;;oBAAkC;;wBAAMC,iBAAiBD;;;2BAAvB;;;oBAAtEA,aAAlBG,SAAkBH,KAAlBG,QAAQC,QAAUJ,KAAVI;oBAEhBG,QAAQC,EAAE,CAAC,UAAU;;;;;wCACnB;;4CAAMJ;;;wCAAN;wCACAG,QAAQE,IAAI,CAAC;;;;;;wBACf;;oBAEAN,OAAOO,IAAI,CAAC,AAAC,uBAA4C,OAAtBV,OAAOK,SAAS,CAACC,IAAI,EAAC;oBACzD;;wBAAM,IAAIK,QAAQ,YAAO;;;oBAAzB;;;;;;IACF;;AAEe,SAAehB;;YAEtBiB,mBAQEC,cACFb;;;;oBAVN,4DAA4D;oBACtDY,oBAAoBE,IAAAA,gCAAiB,EAACP,QAAQQ,IAAI;oBACxD,IAAIH,kBAAkBI,OAAO,EAAE;wBAC7BC,QAAQC,GAAG,CAACN,kBAAkBO,MAAM;wBACpCZ,QAAQE,IAAI,CAAC;oBACf;oBAIyB;;wBAAM;2EAAA,QAAO;;;;oBAA9BI,eAAiB,cAAjBA;oBACFb,SAASa;oBACf;;wBAAMd,YAAYC;;;oBAAlB;;;;;;IACF;;AAEA,IAAIO,QAAQQ,IAAI,CAAC,EAAE,KAAK,IAAIK,IAAI,qDAAiBC,QAAQ,EAAE;IACzD1B;AACF"}
@@ -0,0 +1,9 @@
1
+ import { type GoogleAuthProvider } from '@mcp-z/oauth-google';
2
+ /**
3
+ * A Google API client bound to this request's token provider.
4
+ *
5
+ * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client
6
+ * is built here, from this package's own `googleapis`. That keeps one copy of
7
+ * `google-auth-library` in the tree by construction rather than by matching pins.
8
+ */
9
+ export declare function googleAuth(auth: GoogleAuthProvider): import("google-auth-library").OAuth2Client;
@@ -0,0 +1,9 @@
1
+ import { type GoogleAuthProvider } from '@mcp-z/oauth-google';
2
+ /**
3
+ * A Google API client bound to this request's token provider.
4
+ *
5
+ * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client
6
+ * is built here, from this package's own `googleapis`. That keeps one copy of
7
+ * `google-auth-library` in the tree by construction rather than by matching pins.
8
+ */
9
+ export declare function googleAuth(auth: GoogleAuthProvider): import("google-auth-library").OAuth2Client;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "googleAuth", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return googleAuth;
9
+ }
10
+ });
11
+ var _oauthgoogle = require("@mcp-z/oauth-google");
12
+ var _googleapis = require("googleapis");
13
+ function googleAuth(auth) {
14
+ return (0, _oauthgoogle.attachTokenProvider)(new _googleapis.google.auth.OAuth2(), auth);
15
+ }
16
+ /* CJS INTEROP */ if (exports.__esModule && exports.default) { try { Object.defineProperty(exports.default, '__esModule', { value: true }); for (var key in exports) { exports.default[key] = exports[key]; } } catch (_) {}; module.exports = exports.default; }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/lib/google-auth.ts"],"sourcesContent":["import { attachTokenProvider, type GoogleAuthProvider } from '@mcp-z/oauth-google';\nimport { google } from 'googleapis';\n\n/**\n * A Google API client bound to this request's token provider.\n *\n * `@mcp-z/oauth-google` mints tokens and depends on no Google SDK, so the client\n * is built here, from this package's own `googleapis`. That keeps one copy of\n * `google-auth-library` in the tree by construction rather than by matching pins.\n */\nexport function googleAuth(auth: GoogleAuthProvider) {\n return attachTokenProvider(new google.auth.OAuth2(), auth);\n}\n"],"names":["googleAuth","auth","attachTokenProvider","google","OAuth2"],"mappings":";;;;+BAUgBA;;;eAAAA;;;2BAV6C;0BACtC;AAShB,SAASA,WAAWC,IAAwB;IACjD,OAAOC,IAAAA,gCAAmB,EAAC,IAAIC,kBAAM,CAACF,IAAI,CAACG,MAAM,IAAIH;AACvD"}
@@ -1,5 +1,4 @@
1
- import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
2
- import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
1
+ import type { ServerContext } from '@mcp-z/server';
3
2
  import { z } from 'zod';
4
3
  export default function createPrompt(): {
5
4
  name: string;
@@ -12,7 +11,7 @@ export default function createPrompt(): {
12
11
  };
13
12
  handler: (args: {
14
13
  [x: string]: unknown;
15
- }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => Promise<{
14
+ }, _extra: ServerContext) => Promise<{
16
15
  messages: ({
17
16
  role: "system";
18
17
  content: {
@@ -1,5 +1,4 @@
1
- import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
2
- import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
1
+ import type { ServerContext } from '@mcp-z/server';
3
2
  import { z } from 'zod';
4
3
  export default function createPrompt(): {
5
4
  name: string;
@@ -12,7 +11,7 @@ export default function createPrompt(): {
12
11
  };
13
12
  handler: (args: {
14
13
  [x: string]: unknown;
15
- }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => Promise<{
14
+ }, _extra: ServerContext) => Promise<{
16
15
  messages: ({
17
16
  role: "system";
18
17
  content: {
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/prompts/draft-email.ts"],"sourcesContent":["import type { PromptModule } from '@mcp-z/server';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\n\nexport default function createPrompt() {\n const argsSchema = z.object({\n context: z.string().min(1).describe('Email context to draft response for'),\n tone: z.string().optional().describe('Email tone (default: professional)'),\n });\n\n const config = {\n description: 'Draft an email response',\n argsSchema: argsSchema.shape,\n };\n\n const handler = async (args: { [x: string]: unknown }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => {\n const { context, tone } = argsSchema.parse(args);\n return {\n messages: [\n { role: 'system' as const, content: { type: 'text' as const, text: 'You are an expert email assistant.' } },\n { role: 'user' as const, content: { type: 'text' as const, text: `Draft a ${tone || 'professional'} email:\\n\\n${context}` } },\n ],\n };\n };\n\n return {\n name: 'draft-email',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","argsSchema","z","object","context","string","min","describe","tone","optional","config","description","shape","handler","args","_extra","parse","messages","role","content","type","text","name"],"mappings":";;;;+BAKA;;;eAAwBA;;;mBAFN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,SAASA;IACtB,IAAMC,aAAaC,MAAC,CAACC,MAAM,CAAC;QAC1BC,SAASF,MAAC,CAACG,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;QACpCC,MAAMN,MAAC,CAACG,MAAM,GAAGI,QAAQ,GAAGF,QAAQ,CAAC;IACvC;IAEA,IAAMG,SAAS;QACbC,aAAa;QACbV,YAAYA,WAAWW,KAAK;IAC9B;IAEA,IAAMC,UAAU,iBAAOC,MAAgCC;;gBAC3Bd,mBAAlBG,SAASI;;gBAASP,oBAAAA,WAAWe,KAAK,CAACF,OAAnCV,UAAkBH,kBAAlBG,SAASI,OAASP,kBAATO;gBACjB;;oBAAO;wBACLS,QAAQ;4BACN;gCAAEC,MAAM;gCAAmBC,SAAS;oCAAEC,MAAM;oCAAiBC,MAAM;gCAAqC;4BAAE;4BAC1G;gCAAEH,MAAM;gCAAiBC,SAAS;oCAAEC,MAAM;oCAAiBC,MAAM,AAAC,WAA8CjB,OAApCI,QAAQ,gBAAe,eAAqB,OAARJ;gCAAU;4BAAE;;oBAEhI;;;QACF;;IAEA,OAAO;QACLkB,MAAM;QACNZ,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/prompts/draft-email.ts"],"sourcesContent":["import type { PromptModule, ServerContext } from '@mcp-z/server';\nimport { z } from 'zod';\n\nexport default function createPrompt() {\n const argsSchema = z.object({\n context: z.string().min(1).describe('Email context to draft response for'),\n tone: z.string().optional().describe('Email tone (default: professional)'),\n });\n\n const config = {\n description: 'Draft an email response',\n argsSchema: argsSchema.shape,\n };\n\n const handler = async (args: { [x: string]: unknown }, _extra: ServerContext) => {\n const { context, tone } = argsSchema.parse(args);\n return {\n messages: [\n { role: 'system' as const, content: { type: 'text' as const, text: 'You are an expert email assistant.' } },\n { role: 'user' as const, content: { type: 'text' as const, text: `Draft a ${tone || 'professional'} email:\\n\\n${context}` } },\n ],\n };\n };\n\n return {\n name: 'draft-email',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","argsSchema","z","object","context","string","min","describe","tone","optional","config","description","shape","handler","args","_extra","parse","messages","role","content","type","text","name"],"mappings":";;;;+BAGA;;;eAAwBA;;;mBAFN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,SAASA;IACtB,IAAMC,aAAaC,MAAC,CAACC,MAAM,CAAC;QAC1BC,SAASF,MAAC,CAACG,MAAM,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;QACpCC,MAAMN,MAAC,CAACG,MAAM,GAAGI,QAAQ,GAAGF,QAAQ,CAAC;IACvC;IAEA,IAAMG,SAAS;QACbC,aAAa;QACbV,YAAYA,WAAWW,KAAK;IAC9B;IAEA,IAAMC,UAAU,iBAAOC,MAAgCC;;gBAC3Bd,mBAAlBG,SAASI;;gBAASP,oBAAAA,WAAWe,KAAK,CAACF,OAAnCV,UAAkBH,kBAAlBG,SAASI,OAASP,kBAATO;gBACjB;;oBAAO;wBACLS,QAAQ;4BACN;gCAAEC,MAAM;gCAAmBC,SAAS;oCAAEC,MAAM;oCAAiBC,MAAM;gCAAqC;4BAAE;4BAC1G;gCAAEH,MAAM;gCAAiBC,SAAS;oCAAEC,MAAM;oCAAiBC,MAAM,AAAC,WAA8CjB,OAApCI,QAAQ,gBAAe,eAAqB,OAARJ;gCAAU;4BAAE;;oBAEhI;;;QACF;;IAEA,OAAO;QACLkB,MAAM;QACNZ,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -1,5 +1,4 @@
1
- import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
2
- import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
1
+ import type { ServerContext } from '@mcp-z/server';
3
2
  export default function createPrompt(): {
4
3
  name: string;
5
4
  config: {
@@ -7,7 +6,7 @@ export default function createPrompt(): {
7
6
  };
8
7
  handler: (_args: {
9
8
  [x: string]: unknown;
10
- }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => Promise<{
9
+ }, _extra: ServerContext) => Promise<{
11
10
  messages: {
12
11
  role: "user";
13
12
  content: {
@@ -1,5 +1,4 @@
1
- import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
2
- import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
1
+ import type { ServerContext } from '@mcp-z/server';
3
2
  export default function createPrompt(): {
4
3
  name: string;
5
4
  config: {
@@ -7,7 +6,7 @@ export default function createPrompt(): {
7
6
  };
8
7
  handler: (_args: {
9
8
  [x: string]: unknown;
10
- }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => Promise<{
9
+ }, _extra: ServerContext) => Promise<{
11
10
  messages: {
12
11
  role: "user";
13
12
  content: {
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule } from '@mcp-z/server';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\n\nexport default function createPrompt() {\n const config = {\n description: 'Reference guide for Gmail query syntax',\n };\n\n const handler = async (_args: { [x: string]: unknown }, _extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => {\n return {\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: `# Gmail Query Syntax Reference\n\n## Logical Operators\n- \\`$and\\`: Array of conditions that ALL must match\n- \\`$or\\`: Array of conditions where ANY must match\n- \\`$not\\`: Condition that must NOT match\n\n## Email Address Fields\n- \\`from\\`, \\`to\\`, \\`cc\\`, \\`bcc\\`: String or field operators\n\n## Content Fields\n- \\`subject\\`: Search subject line\n- \\`body\\`: Search message body\n- \\`text\\`: Search all text content\n- \\`fuzzyPhrase\\`: Approximate phrase matching (words appear together)\n\n## Boolean Flags\n- \\`hasAttachment\\`: true/false\n- \\`isRead\\`: true/false\n\n## Date Range\n\\`\\`\\`json\n{ \"date\": { \"$gte\": \"2024-01-01\", \"$lt\": \"2024-12-31\" } }\n\\`\\`\\`\n\n## Gmail-Specific\n- \\`categories\\`: primary, social, promotions, updates, forums\n- \\`label\\`: User labels (case-sensitive, use gmail-labels-list to discover)\n- \\`rawGmailQuery\\`: Escape hatch for advanced Gmail syntax\n\n## Field Operators (for multi-value fields)\n- \\`$any\\`: OR - matches if ANY value matches\n- \\`$all\\`: AND - matches if ALL values match\n- \\`$none\\`: NOT - matches if NONE match\n\n## Example Queries\n\\`\\`\\`json\n// Unread from specific sender\n{ \"from\": \"boss@company.com\", \"isRead\": false }\n\n// Recent with attachment\n{ \"hasAttachment\": true, \"date\": { \"$gte\": \"2024-01-01\" } }\n\n// Multiple senders\n{ \"from\": { \"$any\": [\"alice@example.com\", \"bob@example.com\"] } }\n\n// Complex: promotions OR social, unread\n{ \"$and\": [\n { \"categories\": { \"$any\": [\"promotions\", \"social\"] } },\n { \"isRead\": false }\n]}\n\\`\\`\\``,\n },\n },\n ],\n };\n };\n\n return {\n name: 'query-syntax',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","config","description","handler","_args","_extra","messages","role","content","type","text","name"],"mappings":";;;;+BAIA;;;eAAwBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAT,SAASA;IACtB,IAAMC,SAAS;QACbC,aAAa;IACf;IAEA,IAAMC,UAAU,iBAAOC,OAAiCC;;;gBACtD;;oBAAO;wBACLC,QAAQ;4BACN;gCACEC,MAAM;gCACNC,SAAS;oCACPC,MAAM;oCACNC,MAAM;gCAoDR;4BACF;;oBAEJ;;;QACF;;IAEA,OAAO;QACLC,MAAM;QACNV,QAAAA;QACAE,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/prompts/query-syntax.ts"],"sourcesContent":["import type { PromptModule, ServerContext } from '@mcp-z/server';\n\nexport default function createPrompt() {\n const config = {\n description: 'Reference guide for Gmail query syntax',\n };\n\n const handler = async (_args: { [x: string]: unknown }, _extra: ServerContext) => {\n return {\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: `# Gmail Query Syntax Reference\n\n## Logical Operators\n- \\`$and\\`: Array of conditions that ALL must match\n- \\`$or\\`: Array of conditions where ANY must match\n- \\`$not\\`: Condition that must NOT match\n\n## Email Address Fields\n- \\`from\\`, \\`to\\`, \\`cc\\`, \\`bcc\\`: String or field operators\n\n## Content Fields\n- \\`subject\\`: Search subject line\n- \\`body\\`: Search message body\n- \\`text\\`: Search all text content\n- \\`fuzzyPhrase\\`: Approximate phrase matching (words appear together)\n\n## Boolean Flags\n- \\`hasAttachment\\`: true/false\n- \\`isRead\\`: true/false\n\n## Date Range\n\\`\\`\\`json\n{ \"date\": { \"$gte\": \"2024-01-01\", \"$lt\": \"2024-12-31\" } }\n\\`\\`\\`\n\n## Gmail-Specific\n- \\`categories\\`: primary, social, promotions, updates, forums\n- \\`label\\`: User labels (case-sensitive, use gmail-labels-list to discover)\n- \\`rawGmailQuery\\`: Escape hatch for advanced Gmail syntax\n\n## Field Operators (for multi-value fields)\n- \\`$any\\`: OR - matches if ANY value matches\n- \\`$all\\`: AND - matches if ALL values match\n- \\`$none\\`: NOT - matches if NONE match\n\n## Example Queries\n\\`\\`\\`json\n// Unread from specific sender\n{ \"from\": \"boss@company.com\", \"isRead\": false }\n\n// Recent with attachment\n{ \"hasAttachment\": true, \"date\": { \"$gte\": \"2024-01-01\" } }\n\n// Multiple senders\n{ \"from\": { \"$any\": [\"alice@example.com\", \"bob@example.com\"] } }\n\n// Complex: promotions OR social, unread\n{ \"$and\": [\n { \"categories\": { \"$any\": [\"promotions\", \"social\"] } },\n { \"isRead\": false }\n]}\n\\`\\`\\``,\n },\n },\n ],\n };\n };\n\n return {\n name: 'query-syntax',\n config,\n handler,\n } satisfies PromptModule;\n}\n"],"names":["createPrompt","config","description","handler","_args","_extra","messages","role","content","type","text","name"],"mappings":";;;;+BAEA;;;eAAwBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAT,SAASA;IACtB,IAAMC,SAAS;QACbC,aAAa;IACf;IAEA,IAAMC,UAAU,iBAAOC,OAAiCC;;;gBACtD;;oBAAO;wBACLC,QAAQ;4BACN;gCACEC,MAAM;gCACNC,SAAS;oCACPC,MAAM;oCACNC,MAAM;gCAoDR;4BACF;;oBAEJ;;;QACF;;IAEA,OAAO;QACLC,MAAM;QACNV,QAAAA;QACAE,SAAAA;IACF;AACF"}
@@ -1,11 +1,12 @@
1
- import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
3
- import type { ReadResourceResult, ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
1
+ import type { ReadResourceResult, ServerContext } from '@mcp-z/server';
2
+ import { ResourceTemplate } from '@mcp-z/server';
4
3
  export default function createResource(): {
5
4
  name: string;
6
5
  template: ResourceTemplate;
7
- config: import("@modelcontextprotocol/sdk/server/mcp.js").ResourceMetadata;
6
+ config: import("@modelcontextprotocol/server").ResourceMetadata & {
7
+ cacheHint?: import("@modelcontextprotocol/server").CacheHint;
8
+ };
8
9
  handler: (uri: URL, variables: {
9
10
  id: string;
10
- }, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => Promise<ReadResourceResult>;
11
+ }, extra: ServerContext) => Promise<ReadResourceResult>;
11
12
  };
@@ -1,11 +1,12 @@
1
- import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
3
- import type { ReadResourceResult, ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';
1
+ import type { ReadResourceResult, ServerContext } from '@mcp-z/server';
2
+ import { ResourceTemplate } from '@mcp-z/server';
4
3
  export default function createResource(): {
5
4
  name: string;
6
5
  template: ResourceTemplate;
7
- config: import("@modelcontextprotocol/sdk/server/mcp.js").ResourceMetadata;
6
+ config: import("@modelcontextprotocol/server").ResourceMetadata & {
7
+ cacheHint?: import("@modelcontextprotocol/server").CacheHint;
8
+ };
8
9
  handler: (uri: URL, variables: {
9
10
  id: string;
10
- }, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => Promise<ReadResourceResult>;
11
+ }, extra: ServerContext) => Promise<ReadResourceResult>;
11
12
  };
@@ -8,10 +8,11 @@ Object.defineProperty(exports, "default", {
8
8
  return createResource;
9
9
  }
10
10
  });
11
- var _mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
11
+ var _server = require("@mcp-z/server");
12
12
  var _googleapis = require("googleapis");
13
13
  var _messageextractionts = require("../../email/parsing/message-extraction.js");
14
14
  var _dateconversionts = require("../../lib/date-conversion.js");
15
+ var _googleauthts = require("../../lib/google-auth.js");
15
16
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
16
17
  try {
17
18
  var info = gen[key](arg);
@@ -138,7 +139,7 @@ function _ts_generator(thisArg, body) {
138
139
  }
139
140
  }
140
141
  function createResource() {
141
- var template = new _mcp.ResourceTemplate('gmail://messages/{id}', {
142
+ var template = new _server.ResourceTemplate('gmail://messages/{id}', {
142
143
  list: undefined
143
144
  });
144
145
  var config = {
@@ -161,7 +162,7 @@ function createResource() {
161
162
  logger.info(variables, 'gmail-email resource fetch');
162
163
  gmail = _googleapis.google.gmail({
163
164
  version: 'v1',
164
- auth: authContext.auth
165
+ auth: (0, _googleauthts.googleAuth)(authContext.auth)
165
166
  });
166
167
  return [
167
168
  4,
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/resources/email.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ResourceConfig, ResourceModule } from '@mcp-z/server';\nimport { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { ReadResourceResult, ServerNotification, ServerRequest } from '@modelcontextprotocol/sdk/types.js';\nimport { type gmail_v1, google } from 'googleapis';\nimport { extractEmails, extractFrom } from '../../email/parsing/message-extraction.ts';\nimport { toIsoUtc } from '../../lib/date-conversion.ts';\n\nexport default function createResource() {\n const template = new ResourceTemplate('gmail://messages/{id}', {\n list: undefined,\n });\n const config: ResourceConfig = {\n description: 'Gmail message metadata (lightweight: id, subject, from, to, date)',\n mimeType: 'application/json',\n };\n\n const handler = async (uri: URL, variables: { id: string }, extra: RequestHandlerExtra<ServerRequest, ServerNotification>): Promise<ReadResourceResult> => {\n try {\n const { logger, authContext } = extra as unknown as EnrichedExtra;\n\n logger.info(variables, 'gmail-email resource fetch');\n\n const gmail = google.gmail({ version: 'v1', auth: authContext.auth });\n const response = await gmail.users.messages.get({\n userId: 'me',\n id: variables.id,\n format: 'metadata',\n metadataHeaders: ['From', 'To', 'Subject', 'Date'],\n });\n\n const fullData = response.data;\n if (!fullData) {\n throw new Error('Message not found');\n }\n\n // Extract headers\n const headers = fullData?.payload?.headers;\n const headersArray = Array.isArray(headers) ? headers : [];\n const headersMap: Record<string, string> = Object.fromEntries(\n headersArray.map((h: unknown) => {\n const header = h as gmail_v1.Schema$MessagePartHeader;\n return [String(header.name ?? ''), String(header.value ?? '')];\n })\n );\n\n const fromInfo = extractFrom(headersMap.From);\n const toStr = extractEmails(headersMap.To).join(', ');\n\n // Return lightweight metadata only (no body/snippet)\n const metadata = {\n id: fullData.id ?? variables.id,\n subject: headersMap.Subject ?? '',\n from: fromInfo?.address || headersMap.From,\n to: toStr,\n date: toIsoUtc(headersMap.Date) || headersMap.Date,\n };\n\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(metadata),\n },\n ],\n };\n } catch (e) {\n const { logger } = extra as unknown as EnrichedExtra;\n logger.error(e as Record<string, unknown>, 'gmail-email resource fetch failed');\n const error = e as { message?: unknown };\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({ error: String(error?.message ?? e) }),\n },\n ],\n };\n }\n };\n\n return {\n name: 'email',\n template,\n config,\n handler,\n } satisfies ResourceModule;\n}\n"],"names":["createResource","template","ResourceTemplate","list","undefined","config","description","mimeType","handler","uri","variables","extra","fullData","headersMap","logger","authContext","gmail","response","headers","headersArray","fromInfo","toStr","metadata","e","error","info","google","version","auth","users","messages","get","userId","id","format","metadataHeaders","data","Error","payload","Array","isArray","Object","fromEntries","map","h","header","String","name","value","extractFrom","From","extractEmails","To","join","subject","Subject","from","address","to","date","toIsoUtc","Date","contents","href","text","JSON","stringify","message"],"mappings":";;;;+BASA;;;eAAwBA;;;mBAPS;0BAGK;mCACK;gCAClB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEV,SAASA;IACtB,IAAMC,WAAW,IAAIC,qBAAgB,CAAC,yBAAyB;QAC7DC,MAAMC;IACR;IACA,IAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,IAAMC,UAAU,iBAAOC,KAAUC,WAA2BC;;gBAkClDC,cACKC,qBAfKD,mBAlBRE,QAAQC,aAIVC,OACAC,UAOA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B1C,iCAAAA,sBAAsB;4BAC/B2C,MAAMpC,CAAAA,qBAAAA,+BAAAA,SAAUqC,OAAO,KAAI5C,WAAWqC,IAAI;4BAC1CQ,IAAIrC;4BACJsC,MAAMC,IAAAA,0BAAQ,EAAC/C,WAAWgD,IAAI,KAAKhD,WAAWgD,IAAI;wBACpD;wBAEA;;4BAAO;gCACLC,QAAQ;oCACN;wCACErD,KAAKA,IAAIsD,IAAI;wCACbxD,UAAU;wCACVyD,MAAMC,KAAKC,SAAS,CAAC5C;oCACvB;;4BAEJ;;;wBACOC;wBACCT,UAAWH,MAAXG;wBACRA,QAAOU,KAAK,CAACD,GAA8B;wBACrCC,QAAQD;wBACd;;4BAAO;gCACLuC,QAAQ;oCACN;wCACErD,KAAKA,IAAIsD,IAAI;wCACbxD,UAAU;wCACVyD,MAAMC,KAAKC,SAAS,CAAC;4CAAE1C,OAAOsB,eAAOtB,kBAAAA,4BAAAA,MAAO2C,OAAO,uCAAI5C;wCAAG;oCAC5D;;4BAEJ;;;;;;;;QAEJ;;IAEA,OAAO;QACLwB,MAAM;QACN9C,UAAAA;QACAI,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/resources/email.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport type { ReadResourceResult, ResourceConfig, ResourceModule, ServerContext } from '@mcp-z/server';\nimport { ResourceTemplate } from '@mcp-z/server';\nimport { type gmail_v1, google } from 'googleapis';\nimport { extractEmails, extractFrom } from '../../email/parsing/message-extraction.ts';\nimport { toIsoUtc } from '../../lib/date-conversion.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nexport default function createResource() {\n const template = new ResourceTemplate('gmail://messages/{id}', {\n list: undefined,\n });\n const config: ResourceConfig = {\n description: 'Gmail message metadata (lightweight: id, subject, from, to, date)',\n mimeType: 'application/json',\n };\n\n const handler = async (uri: URL, variables: { id: string }, extra: ServerContext): Promise<ReadResourceResult> => {\n try {\n const { logger, authContext } = extra as unknown as EnrichedExtra;\n\n logger.info(variables, 'gmail-email resource fetch');\n\n const gmail = google.gmail({ version: 'v1', auth: googleAuth(authContext.auth) });\n const response = await gmail.users.messages.get({\n userId: 'me',\n id: variables.id,\n format: 'metadata',\n metadataHeaders: ['From', 'To', 'Subject', 'Date'],\n });\n\n const fullData = response.data;\n if (!fullData) {\n throw new Error('Message not found');\n }\n\n // Extract headers\n const headers = fullData?.payload?.headers;\n const headersArray = Array.isArray(headers) ? headers : [];\n const headersMap: Record<string, string> = Object.fromEntries(\n headersArray.map((h: unknown) => {\n const header = h as gmail_v1.Schema$MessagePartHeader;\n return [String(header.name ?? ''), String(header.value ?? '')];\n })\n );\n\n const fromInfo = extractFrom(headersMap.From);\n const toStr = extractEmails(headersMap.To).join(', ');\n\n // Return lightweight metadata only (no body/snippet)\n const metadata = {\n id: fullData.id ?? variables.id,\n subject: headersMap.Subject ?? '',\n from: fromInfo?.address || headersMap.From,\n to: toStr,\n date: toIsoUtc(headersMap.Date) || headersMap.Date,\n };\n\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify(metadata),\n },\n ],\n };\n } catch (e) {\n const { logger } = extra as unknown as EnrichedExtra;\n logger.error(e as Record<string, unknown>, 'gmail-email resource fetch failed');\n const error = e as { message?: unknown };\n return {\n contents: [\n {\n uri: uri.href,\n mimeType: 'application/json',\n text: JSON.stringify({ error: String(error?.message ?? e) }),\n },\n ],\n };\n }\n };\n\n return {\n name: 'email',\n template,\n config,\n handler,\n } satisfies ResourceModule;\n}\n"],"names":["createResource","template","ResourceTemplate","list","undefined","config","description","mimeType","handler","uri","variables","extra","fullData","headersMap","logger","authContext","gmail","response","headers","headersArray","fromInfo","toStr","metadata","e","error","info","google","version","auth","googleAuth","users","messages","get","userId","id","format","metadataHeaders","data","Error","payload","Array","isArray","Object","fromEntries","map","h","header","String","name","value","extractFrom","From","extractEmails","To","join","subject","Subject","from","address","to","date","toIsoUtc","Date","contents","href","text","JSON","stringify","message"],"mappings":";;;;+BAQA;;;eAAwBA;;;sBANS;0BACK;mCACK;gCAClB;4BACE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEZ,SAASA;IACtB,IAAMC,WAAW,IAAIC,wBAAgB,CAAC,yBAAyB;QAC7DC,MAAMC;IACR;IACA,IAAMC,SAAyB;QAC7BC,aAAa;QACbC,UAAU;IACZ;IAEA,IAAMC,UAAU,iBAAOC,KAAUC,WAA2BC;;gBAkClDC,cACKC,qBAfKD,mBAlBRE,QAAQC,aAIVC,OACAC,UAOAL,UAMAM,SACAC,cACAN,YAOAO,UACAC,OAGAC,UAiBCC,SACCT,SAEFU;;;;;;;;;;wBAnDEV,SAAwBH,MAAxBG,QAAQC,cAAgBJ,MAAhBI;wBAEhBD,OAAOW,IAAI,CAACf,WAAW;wBAEjBM,QAAQU,kBAAM,CAACV,KAAK,CAAC;4BAAEW,SAAS;4BAAMC,MAAMC,IAAAA,wBAAU,EAACd,YAAYa,IAAI;wBAAE;wBAC9D;;4BAAMZ,MAAMc,KAAK,CAACC,QAAQ,CAACC,GAAG,CAAC;gCAC9CC,QAAQ;gCACRC,IAAIxB,UAAUwB,EAAE;gCAChBC,QAAQ;gCACRC,eAAe;oCAAG;oCAAQ;oCAAM;oCAAW;;4BAC7C;;;wBALMnB,WAAW;wBAOXL,WAAWK,SAASoB,IAAI;wBAC9B,IAAI,CAACzB,UAAU;4BACb,MAAM,IAAI0B,MAAM;wBAClB;wBAEA,kBAAkB;wBACZpB,UAAUN,qBAAAA,gCAAAA,oBAAAA,SAAU2B,OAAO,cAAjB3B,wCAAAA,kBAAmBM,OAAO;wBACpCC,eAAeqB,MAAMC,OAAO,CAACvB,WAAWA;wBACxCL,aAAqC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,SAAAA;IACF;AACF"}
@@ -17,9 +17,10 @@ _export(exports, {
17
17
  }
18
18
  });
19
19
  var _oauthgoogle = require("@mcp-z/oauth-google");
20
- var _types = require("@modelcontextprotocol/sdk/types.js");
20
+ var _server = require("@mcp-z/server");
21
21
  var _googleapis = require("googleapis");
22
22
  var _zod = require("zod");
23
+ var _googleauthts = require("../../lib/google-auth.js");
23
24
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
24
25
  try {
25
26
  var info = gen[key](arg);
@@ -194,7 +195,7 @@ function handler(_, extra) {
194
195
  ]);
195
196
  gmail = _googleapis.google.gmail({
196
197
  version: 'v1',
197
- auth: extra.authContext.auth
198
+ auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
198
199
  });
199
200
  started = Date.now();
200
201
  return [
@@ -281,7 +282,7 @@ function handler(_, extra) {
281
282
  logger.error('gmail.categories.list error', {
282
283
  error: message
283
284
  });
284
- throw new _types.McpError(_types.ErrorCode.InternalError, "Error listing categories: ".concat(message), {
285
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error listing categories: ".concat(message), {
285
286
  stack: _instanceof(error, Error) ? error.stack : undefined
286
287
  });
287
288
  case 4:
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/categories-list.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\n\n// Schema for individual category items\nconst CategorySchema = z.object({\n id: z.string().describe('Gmail category ID (e.g., CATEGORY_PERSONAL)'),\n name: z.string().describe('Human-readable category name'),\n description: z.string().describe('Description of what emails belong in this category'),\n});\n\n/**\n * Input schema for the categories-list tool (currently empty as this tool takes no parameters).\n */\nexport const inputSchema = z.object({});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n items: z.array(CategorySchema),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'List Gmail category labels (CATEGORY_*) with IDs and descriptions.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\n/**\n * Input parameters for the categories-list tool.\n */\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler(_: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail.categories.list called');\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n const started = Date.now();\n\n // Fetch all labels from Gmail API\n const response = await gmail.users.labels.list({ userId: 'me' });\n const labels = response.data.labels || [];\n\n // Filter for CATEGORY_* system labels and map to our schema\n const categories = labels\n .filter((label) => label.id?.startsWith('CATEGORY_'))\n .map((label) => {\n const id = label.id as string;\n let name = label.name || id;\n let description = '';\n\n // Map known category types to user-friendly names and descriptions\n switch (id) {\n case 'CATEGORY_PERSONAL':\n name = 'Primary';\n description = 'Important emails from people you know';\n break;\n case 'CATEGORY_SOCIAL':\n name = 'Social';\n description = 'Social networks and social websites';\n break;\n case 'CATEGORY_PROMOTIONS':\n name = 'Promotions';\n description = 'Deals, offers, and marketing emails';\n break;\n case 'CATEGORY_UPDATES':\n name = 'Updates';\n description = 'Confirmations, receipts, bills, and statements';\n break;\n case 'CATEGORY_FORUMS':\n name = 'Forums';\n description = 'Online groups, discussion boards, mailing lists';\n break;\n default:\n // For any unknown CATEGORY_* labels, use the label name as-is\n name = label.name || id.replace('CATEGORY_', '');\n description = `Gmail category: ${name}`;\n }\n\n return {\n id,\n name,\n description,\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name)); // Sort alphabetically by name\n\n const durationMs = Date.now() - started;\n\n logger.info('gmail.categories.list results', { categoryCount: categories.length, totalLabels: labels.length });\n logger.info('gmail.categories.list metrics', { durationMs });\n\n const result: Output = {\n type: 'success' as const,\n items: categories,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.categories.list error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error listing categories: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'categories-list',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","inputSchema","AuthRequiredBranchSchema","schemas","CategorySchema","z","object","id","string","describe","name","description","successBranchSchema","type","literal","items","array","outputSchema","discriminatedUnion","config","result","handler","_","extra","logger","gmail","started","response","labels","categories","durationMs","error","message","info","google","version","auth","authContext","Date","now","users","list","userId","data","filter","label","startsWith","map","replace","sort","a","b","localeCompare","categoryCount","length","totalLabels","content","text","JSON","stringify","structuredContent","Error","String","McpError","ErrorCode","InternalError","stack","undefined"],"mappings":";;;;;;;;;;;QAkIA;eAAwBA;;QA9GXC;eAAAA;;;2BAnBW;qBAKY;0BACb;mBACL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AALlB,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAOR,uCAAuC;AACvC,IAAME,iBAAiBC,MAAC,CAACC,MAAM,CAAC;IAC9BC,IAAIF,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IACxBC,MAAML,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;IAC1BE,aAAaN,MAAC,CAACG,MAAM,GAAGC,QAAQ,CAAC;AACnC;AAKO,IAAMR,cAAcI,MAAC,CAACC,MAAM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":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/categories-list.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\n// Schema for individual category items\nconst CategorySchema = z.object({\n id: z.string().describe('Gmail category ID (e.g., CATEGORY_PERSONAL)'),\n name: z.string().describe('Human-readable category name'),\n description: z.string().describe('Description of what emails belong in this category'),\n});\n\n/**\n * Input schema for the categories-list tool (currently empty as this tool takes no parameters).\n */\nexport const inputSchema = z.object({});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n items: z.array(CategorySchema),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'List Gmail category labels (CATEGORY_*) with IDs and descriptions.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\n/**\n * Input parameters for the categories-list tool.\n */\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler(_: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail.categories.list called');\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: googleAuth(extra.authContext.auth) });\n const started = Date.now();\n\n // Fetch all labels from Gmail API\n const response = await gmail.users.labels.list({ userId: 'me' });\n const labels = response.data.labels || [];\n\n // Filter for CATEGORY_* system labels and map to our schema\n const categories = labels\n .filter((label) => label.id?.startsWith('CATEGORY_'))\n .map((label) => {\n const id = label.id as string;\n let name = label.name || id;\n let description = '';\n\n // Map known category types to user-friendly names and descriptions\n switch (id) {\n case 'CATEGORY_PERSONAL':\n name = 'Primary';\n description = 'Important emails from people you know';\n break;\n case 'CATEGORY_SOCIAL':\n name = 'Social';\n description = 'Social networks and social websites';\n break;\n case 'CATEGORY_PROMOTIONS':\n name = 'Promotions';\n description = 'Deals, offers, and marketing emails';\n break;\n case 'CATEGORY_UPDATES':\n name = 'Updates';\n description = 'Confirmations, receipts, bills, and statements';\n break;\n case 'CATEGORY_FORUMS':\n name = 'Forums';\n description = 'Online groups, discussion boards, mailing lists';\n break;\n default:\n // For any unknown CATEGORY_* labels, use the label name as-is\n name = label.name || id.replace('CATEGORY_', '');\n description = `Gmail category: ${name}`;\n }\n\n return {\n id,\n name,\n description,\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name)); // Sort alphabetically by name\n\n const durationMs = Date.now() - started;\n\n logger.info('gmail.categories.list results', { categoryCount: categories.length, totalLabels: labels.length });\n logger.info('gmail.categories.list metrics', { durationMs });\n\n const result: Output = {\n type: 'success' as const,\n items: categories,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.categories.list error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error listing categories: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'categories-list',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","inputSchema","AuthRequiredBranchSchema","schemas","CategorySchema","z","object","id","string","describe","name","description","successBranchSchema","type","literal","items","array","outputSchema","discriminatedUnion","config","result","handler","_","extra","logger","gmail","started","response","labels","categories","durationMs","error","message","info","google","version","auth","googleAuth","authContext","Date","now","users","list","userId","data","filter","label","startsWith","map","replace","sort","a","b","localeCompare","categoryCount","length","totalLabels","content","text","JSON","stringify","structuredContent","Error","String","ProtocolError","ProtocolErrorCode","InternalError","stack","undefined"],"mappings":";;;;;;;;;;;QAmIA;eAAwBA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ACL4B,OAAO;gCACL;oCACE5C,MAAM;oCACN6C,MAAMC,KAAKC,SAAS,CAACxC;gCACvB;;4BAEFyC,mBAAmB;gCAAEzC,QAAAA;4BAAO;wBAC9B;;;oBACOW;oBACDC,UAAUD,AAAK,YAALA,OAAiB+B,SAAQ/B,MAAMC,OAAO,GAAG+B,OAAOhC;oBAChEP,OAAOO,KAAK,CAAC,+BAA+B;wBAAEA,OAAOC;oBAAQ;oBAE7D,MAAM,IAAIgC,qBAAa,CAACC,yBAAiB,CAACC,aAAa,EAAE,AAAC,6BAAoC,OAARlC,UAAW;wBAC/FmC,OAAOpC,AAAK,YAALA,OAAiB+B,SAAQ/B,MAAMoC,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASpE;IACtB,OAAO;QACLU,MAAM;QACNS,QAAAA;QACAE,SAAAA;IACF;AACF"}
@@ -9,10 +9,11 @@ Object.defineProperty(exports, "default", {
9
9
  }
10
10
  });
11
11
  var _oauthgoogle = require("@mcp-z/oauth-google");
12
- var _types = require("@modelcontextprotocol/sdk/types.js");
12
+ var _server = require("@mcp-z/server");
13
13
  var _googleapis = require("googleapis");
14
14
  var _zod = require("zod");
15
15
  var _gmaillabelsts = require("../../labels/gmail-labels.js");
16
+ var _googleauthts = require("../../lib/google-auth.js");
16
17
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
17
18
  try {
18
19
  var info = gen[key](arg);
@@ -186,7 +187,7 @@ function handler(_0, _1) {
186
187
  id: id,
187
188
  label: label
188
189
  });
189
- throw new _types.McpError(_types.ErrorCode.InvalidParams, 'Missing id or label');
190
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'Missing id or label');
190
191
  }
191
192
  _state.label = 1;
192
193
  case 1:
@@ -198,7 +199,7 @@ function handler(_0, _1) {
198
199
  ]);
199
200
  gmail = _googleapis.google.gmail({
200
201
  version: 'v1',
201
- auth: extra.authContext.auth
202
+ auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
202
203
  });
203
204
  return [
204
205
  4,
@@ -255,7 +256,7 @@ function handler(_0, _1) {
255
256
  logger.error('gmail.label.add error', {
256
257
  error: message
257
258
  });
258
- throw new _types.McpError(_types.ErrorCode.InternalError, "Error adding label to message: ".concat(message), {
259
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error adding label to message: ".concat(message), {
259
260
  stack: _instanceof(error, Error) ? error.stack : undefined
260
261
  });
261
262
  case 5:
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/label-add.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { ensureLabelId } from '../../labels/gmail-labels.ts';\n\nconst inputSchema = z.object({\n id: z.coerce.string().trim().min(1).describe('Gmail message ID to add label to'),\n label: z.coerce.string().trim().min(1).describe('Label name or ID (use gmail-labels-list to discover available labels)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n item: z.object({\n id: z.string().describe('Message ID the label was added to'),\n label: z.string().describe('Label that was added'),\n }),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Add a label to a Gmail message',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, label }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail.label.add called', { id, label });\n\n if (!id || !label) {\n logger.info('gmail.label.add missing parameters', { id, label });\n throw new McpError(ErrorCode.InvalidParams, 'Missing id or label');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n\n const labelId = await ensureLabelId(gmail, 'me', label);\n await gmail.users.messages.modify({\n userId: 'me',\n id: id,\n requestBody: {\n addLabelIds: [labelId],\n },\n });\n\n logger.info('gmail.label.add success', { id, label });\n logger.info('gmail.label.add result (typed)', { id, label });\n\n const result: Output = {\n type: 'success' as const,\n item: { id, label },\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.label.add error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error adding label to message: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'label-add',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","coerce","string","trim","min","describe","label","successBranchSchema","type","literal","item","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","gmail","labelId","error","message","info","McpError","ErrorCode","InvalidParams","google","version","auth","authContext","ensureLabelId","users","messages","modify","userId","requestBody","addLabelIds","content","text","JSON","stringify","structuredContent","Error","String","InternalError","stack","undefined","name"],"mappings":";;;;+BAuFA;;;eAAwBA;;;2BAtFA;qBAKY;0BACb;mBACL;6BACY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAN9B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AAQR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,IAAIF,MAAC,CAACG,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;IAC7CC,OA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AC;4BAChCC,QAAQ;4BACRnC,IAAIA;4BACJoC,aAAa;gCACXC,WAAW;oCAAGjB;;4BAChB;wBACF;;;oBANA;oBAQAF,OAAOK,IAAI,CAAC,2BAA2B;wBAAEvB,IAAAA;wBAAIM,OAAAA;oBAAM;oBACnDY,OAAOK,IAAI,CAAC,kCAAkC;wBAAEvB,IAAAA;wBAAIM,OAAAA;oBAAM;oBAEpDS,SAAiB;wBACrBP,MAAM;wBACNE,MAAM;4BAAEV,IAAAA;4BAAIM,OAAAA;wBAAM;oBACpB;oBAEA;;wBAAO;4BACLgC,OAAO;gCACL;oCACE9B,MAAM;oCACN+B,MAAMC,KAAKC,SAAS,CAAC1B;gCACvB;;4BAEF2B,mBAAmB;gCAAE3B,QAAAA;4BAAO;wBAC9B;;;oBACOM;oBACDC,UAAUD,AAAK,YAALA,OAAiBsB,SAAQtB,MAAMC,OAAO,GAAGsB,OAAOvB;oBAChEH,OAAOG,KAAK,CAAC,yBAAyB;wBAAEA,OAAOC;oBAAQ;oBAEvD,MAAM,IAAIE,eAAQ,CAACC,gBAAS,CAACoB,aAAa,EAAE,AAAC,kCAAyC,OAARvB,UAAW;wBACvFwB,OAAOzB,AAAK,YAALA,OAAiBsB,SAAQtB,MAAMyB,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASrD;IACtB,OAAO;QACLsD,MAAM;QACNnC,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/label-add.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { ensureLabelId } from '../../labels/gmail-labels.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nconst inputSchema = z.object({\n id: z.coerce.string().trim().min(1).describe('Gmail message ID to add label to'),\n label: z.coerce.string().trim().min(1).describe('Label name or ID (use gmail-labels-list to discover available labels)'),\n});\n\n// Success branch schema\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n item: z.object({\n id: z.string().describe('Message ID the label was added to'),\n label: z.string().describe('Label that was added'),\n }),\n});\n\n// Output schema with auth_required support\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Add a label to a Gmail message',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ id, label }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail.label.add called', { id, label });\n\n if (!id || !label) {\n logger.info('gmail.label.add missing parameters', { id, label });\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing id or label');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: googleAuth(extra.authContext.auth) });\n\n const labelId = await ensureLabelId(gmail, 'me', label);\n await gmail.users.messages.modify({\n userId: 'me',\n id: id,\n requestBody: {\n addLabelIds: [labelId],\n },\n });\n\n logger.info('gmail.label.add success', { id, label });\n logger.info('gmail.label.add result (typed)', { id, label });\n\n const result: Output = {\n type: 'success' as const,\n item: { id, label },\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail.label.add error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error adding label to message: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'label-add',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["createTool","AuthRequiredBranchSchema","schemas","inputSchema","z","object","id","coerce","string","trim","min","describe","label","successBranchSchema","type","literal","item","outputSchema","discriminatedUnion","config","description","result","handler","extra","logger","gmail","labelId","error","message","info","ProtocolError","ProtocolErrorCode","InvalidParams","google","version","auth","googleAuth","authContext","ensureLabelId","users","messages","modify","userId","requestBody","addLabelIds","content","text","JSON","stringify","structuredContent","Error","String","InternalError","stack","undefined","name"],"mappings":";;;;+BAwFA;;;eAAwBA;;;2BAvFA;sBAKyB;0BAC1B;mBACL;6BACY;4BACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAP3B,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,OAAOR,MAAC,CAACG,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAClD;AAEA,wBAAwB;AACxB,IAAME,sBAAsBT,MAAC,CAACC,MAAM,CAAC;IACnCS,MAAMV,MAAC,CAACW,OAAO,CAAC;IAChBC,MAAMZ,MAAC,CAACC,MAAM,CAAC;QACbC,IAAIF,MAAC,CAACI,MAAM,GAAGG,QAAQ,CAAC;QACxBC,OAAOR,MAAC,CAACI,MAAM,GAAGG,QAAQ,CAAC;IAC7B;AACF;AAEA,2CAA2C;AAC3C,IAAMM,eAAeb,MAAC,CAACc,kBAAkB,CAAC,QAAQ;IAACL;IAAqBZ;CAAyB;AAEjG,IAAMkB,SAAS;IACbC,aAAa;IACbjB,aAAaA;IACbc,cAAcb,MAAC,CAACC,MAAM,CAAC;QACrBgB,QAAQJ;IACV;AACF;AAKA,SAAeK;wC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,GAAGuB,OAAOxB;oBAChEH,OAAOG,KAAK,CAAC,yBAAyB;wBAAEA,OAAOC;oBAAQ;oBAEvD,MAAM,IAAIE,qBAAa,CAACC,yBAAiB,CAACqB,aAAa,EAAE,AAAC,kCAAyC,OAARxB,UAAW;wBACpGyB,OAAO1B,AAAK,YAALA,OAAiBuB,SAAQvB,MAAM0B,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAStD;IACtB,OAAO;QACLuD,MAAM;QACNpC,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -9,10 +9,11 @@ Object.defineProperty(exports, "default", {
9
9
  }
10
10
  });
11
11
  var _oauthgoogle = require("@mcp-z/oauth-google");
12
- var _types = require("@modelcontextprotocol/sdk/types.js");
12
+ var _server = require("@mcp-z/server");
13
13
  var _googleapis = require("googleapis");
14
14
  var _zod = require("zod");
15
15
  var _constantsts = require("../../constants.js");
16
+ var _googleauthts = require("../../lib/google-auth.js");
16
17
  function _array_like_to_array(arr, len) {
17
18
  if (len == null || len > arr.length) len = arr.length;
18
19
  for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
@@ -233,11 +234,11 @@ function handler(_0, _1) {
233
234
  count: ids.length
234
235
  });
235
236
  if (!ids || ids.length === 0) {
236
- throw new _types.McpError(_types.ErrorCode.InvalidParams, 'Missing ids');
237
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'Missing ids');
237
238
  }
238
239
  // Validate batch size to prevent memory exhaustion
239
240
  if (ids.length > _constantsts.MAX_BATCH_SIZE) {
240
- throw new _types.McpError(_types.ErrorCode.InvalidParams, "Batch size ".concat(ids.length, " exceeds maximum allowed size of ").concat(_constantsts.MAX_BATCH_SIZE));
241
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, "Batch size ".concat(ids.length, " exceeds maximum allowed size of ").concat(_constantsts.MAX_BATCH_SIZE));
241
242
  }
242
243
  // Validate and sanitize IDs
243
244
  validatedIds = [];
@@ -273,10 +274,10 @@ function handler(_0, _1) {
273
274
  }
274
275
  }
275
276
  if (invalidIds.length > 0) {
276
- throw new _types.McpError(_types.ErrorCode.InvalidParams, "Found ".concat(invalidIds.length, " invalid IDs: ").concat(invalidIds.join(', ')));
277
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, "Found ".concat(invalidIds.length, " invalid IDs: ").concat(invalidIds.join(', ')));
277
278
  }
278
279
  if (validatedIds.length === 0) {
279
- throw new _types.McpError(_types.ErrorCode.InvalidParams, 'No valid IDs found after validation');
280
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InvalidParams, 'No valid IDs found after validation');
280
281
  }
281
282
  _state.label = 1;
282
283
  case 1:
@@ -380,7 +381,7 @@ function handler(_0, _1) {
380
381
  };
381
382
  gmail = _googleapis.google.gmail({
382
383
  version: 'v1',
383
- auth: extra.authContext.auth
384
+ auth: (0, _googleauthts.googleAuth)(extra.authContext.auth)
384
385
  });
385
386
  return [
386
387
  4,
@@ -459,7 +460,7 @@ function handler(_0, _1) {
459
460
  logger.error('gmail-label-delete error', {
460
461
  error: message
461
462
  });
462
- throw new _types.McpError(_types.ErrorCode.InternalError, "Error deleting labels: ".concat(message), {
463
+ throw new _server.ProtocolError(_server.ProtocolErrorCode.InternalError, "Error deleting labels: ".concat(message), {
463
464
  stack: _instanceof(error, Error) ? error.stack : undefined
464
465
  });
465
466
  case 8:
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/label-delete.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).describe('Gmail label IDs to delete'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n totalRequested: z.number().describe('Total number of labels requested to delete'),\n successCount: z.number().describe('Number of labels successfully deleted'),\n failureCount: z.number().describe('Number of labels that failed to delete'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Label ID'),\n success: z.boolean().describe('Whether the operation succeeded'),\n error: z.string().optional().describe('Error message if operation failed'),\n })\n )\n .describe('Individual results for each label'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Delete Gmail labels permanently (irreversible). System labels (INBOX, SENT, etc.) cannot be deleted.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ ids }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail-label-delete called', { count: ids.length });\n\n if (!ids || ids.length === 0) {\n throw new McpError(ErrorCode.InvalidParams, 'Missing ids');\n }\n\n // Validate batch size to prevent memory exhaustion\n if (ids.length > MAX_BATCH_SIZE) {\n throw new McpError(ErrorCode.InvalidParams, `Batch size ${ids.length} exceeds maximum allowed size of ${MAX_BATCH_SIZE}`);\n }\n\n // Validate and sanitize IDs\n const validatedIds: string[] = [];\n const invalidIds: string[] = [];\n\n for (const id of ids) {\n const trimmedId = id.trim();\n if (!trimmedId) {\n invalidIds.push(id);\n continue;\n }\n // Basic Gmail label ID validation - should not contain certain characters\n if (trimmedId.includes('/') || trimmedId.includes('\\\\') || trimmedId.includes('<') || trimmedId.includes('>')) {\n invalidIds.push(id);\n continue;\n }\n validatedIds.push(trimmedId);\n }\n\n if (invalidIds.length > 0) {\n throw new McpError(ErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs: ${invalidIds.join(', ')}`);\n }\n\n if (validatedIds.length === 0) {\n throw new McpError(ErrorCode.InvalidParams, 'No valid IDs found after validation');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: extra.authContext.auth });\n // Get all labels first to check for system labels\n const labelsResponse = await gmail.users.labels.list({ userId: 'me' });\n const allLabels = labelsResponse.data.labels || [];\n const labelMap = new Map(allLabels.map((label) => [label.id || '', label]));\n\n // Process deletions in chunks to prevent memory exhaustion\n const allResults: Array<{ id: string; success: boolean; error?: string }> = [];\n\n for (let i = 0; i < validatedIds.length; i += CHUNK_SIZE) {\n const chunk = validatedIds.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(validatedIds.length / CHUNK_SIZE) });\n\n const chunkResults = await Promise.allSettled(\n chunk.map(async (id) => {\n const label = labelMap.get(id);\n\n // Check if label exists\n if (!label) {\n throw new Error(`Label not found: ${id}`);\n }\n\n // Check if it's a system label\n if (label.type === 'system') {\n throw new Error(`Cannot delete system label: ${label.name} (${id})`);\n }\n\n // Delete the label\n await gmail.users.labels.delete({\n userId: 'me',\n id: id,\n });\n return { id, success: true };\n })\n );\n\n // Process chunk results\n const processedChunkResults = chunkResults.map((result, chunkIndex) => {\n const id = chunk[chunkIndex];\n if (!id) {\n throw new Error(`Chunk index ${chunkIndex} is out of bounds for chunk of size ${chunk.length}`);\n }\n if (result.status === 'fulfilled') {\n return { id, success: true };\n }\n\n // Extract error message more robustly\n let errorMessage = 'Unknown error';\n if (result.reason) {\n if (typeof result.reason === 'string') {\n errorMessage = result.reason;\n } else if (result.reason instanceof Error) {\n errorMessage = result.reason.message;\n } else if (result.reason && typeof result.reason === 'object' && 'message' in result.reason) {\n errorMessage = String(result.reason.message);\n } else if (result.reason && typeof result.reason === 'object' && 'error' in result.reason) {\n errorMessage = String(result.reason.error);\n } else {\n errorMessage = String(result.reason);\n }\n }\n\n return { id, success: false, error: errorMessage };\n });\n\n allResults.push(...processedChunkResults);\n }\n\n const successCount = allResults.filter((r) => r.success).length;\n const failureCount = allResults.filter((r) => !r.success).length;\n\n logger.info('gmail-label-delete completed', {\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(validatedIds.length / CHUNK_SIZE),\n });\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n results: allResults,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail-label-delete error', { error: message });\n\n throw new McpError(ErrorCode.InternalError, `Error deleting labels: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'label-delete',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["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","labelsResponse","allLabels","labelMap","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","label","get","Error","name","users","labels","delete","userId","status","errorMessage","reason","String","google","version","auth","authContext","list","data","Map","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined"],"mappings":";;;;+BA6LA;;;eAAwBA;;;2BA5LA;qBAKY;0BACb;mBACL;2BACyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;oBAAGJ,KAAKgB,uBAAU;;;;;;oBA2DlDxC,eAAeuB,WAAW6C,MAAM,CAAC,SAACC;+BAAMA,EAAEjE,OAAO;uBAAEwB,MAAM;oBACzD3B,eAAesB,WAAW6C,MAAM,CAAC,SAACC;+BAAM,CAACA,EAAEjE,OAAO;uBAAEwB,MAAM;oBAEhEb,OAAOW,IAAI,CAAC,gCAAgC;wBAC1C5B,gBAAgBkB,aAAaY,MAAM;wBACnC5B,cAAAA;wBACAC,cAAAA;wBACAqE,iBAAiB1B,KAAKC,IAAI,CAAC7B,aAAaY,MAAM,GAAGY,uBAAU;oBAC7D;oBAEM5B,SAAiB;wBACrBhB,MAAM;wBACNE,gBAAgBkB,aAAaY,MAAM;wBACnC5B,cAAAA;wBACAC,cAAAA;wBACAC,SAASqB;oBACX;oBAEA;;wBAAO;4BACLgD,OAAO;gCACL;oCACE3E,MAAM;oCACN4E,MAAMC,KAAKC,SAAS,CAAC9D;gCACvB;;4BAEF+D,mBAAmB;gCAAE/D,QAAAA;4BAAO;wBAC9B;;;oBACON;oBACDmB,UAAUnB,AAAK,YAALA,OAAiB6C,SAAQ7C,MAAMmB,OAAO,GAAGmC,OAAOtD;oBAChES,OAAOT,KAAK,CAAC,4BAA4B;wBAAEA,OAAOmB;oBAAQ;oBAE1D,MAAM,IAAII,eAAQ,CAACC,gBAAS,CAAC8C,aAAa,EAAE,AAAC,0BAAiC,OAARnD,UAAW;wBAC/EoD,OAAOvE,AAAK,YAALA,OAAiB6C,SAAQ7C,MAAMuE,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAAShG;IACtB,OAAO;QACLsE,MAAM;QACN1C,QAAAA;QACAG,SAAAA;IACF;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/mcp-gmail/src/mcp/tools/label-delete.ts"],"sourcesContent":["import type { EnrichedExtra } from '@mcp-z/oauth-google';\nimport { schemas } from '@mcp-z/oauth-google';\n\nconst { AuthRequiredBranchSchema } = schemas;\n\nimport type { ToolModule } from '@mcp-z/server';\nimport { ProtocolError, ProtocolErrorCode } from '@mcp-z/server';\nimport { google } from 'googleapis';\nimport { z } from 'zod';\nimport { CHUNK_SIZE, MAX_BATCH_SIZE } from '../../constants.ts';\nimport { googleAuth } from '../../lib/google-auth.ts';\n\nconst inputSchema = z.object({\n ids: z.array(z.coerce.string().trim().min(1)).min(1).describe('Gmail label IDs to delete'),\n});\n\nconst successBranchSchema = z.object({\n type: z.literal('success'),\n totalRequested: z.number().describe('Total number of labels requested to delete'),\n successCount: z.number().describe('Number of labels successfully deleted'),\n failureCount: z.number().describe('Number of labels that failed to delete'),\n results: z\n .array(\n z.object({\n id: z.string().describe('Label ID'),\n success: z.boolean().describe('Whether the operation succeeded'),\n error: z.string().optional().describe('Error message if operation failed'),\n })\n )\n .describe('Individual results for each label'),\n});\n\nconst outputSchema = z.discriminatedUnion('type', [successBranchSchema, AuthRequiredBranchSchema]);\n\nconst config = {\n description: 'Delete Gmail labels permanently (irreversible). System labels (INBOX, SENT, etc.) cannot be deleted.',\n inputSchema: inputSchema,\n outputSchema: z.object({\n result: outputSchema,\n }),\n} as const;\n\nexport type Input = z.infer<typeof inputSchema>;\nexport type Output = z.infer<typeof outputSchema>;\n\nasync function handler({ ids }: Input, extra: EnrichedExtra) {\n const logger = extra.logger;\n logger.info('gmail-label-delete called', { count: ids.length });\n\n if (!ids || ids.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Missing ids');\n }\n\n // Validate batch size to prevent memory exhaustion\n if (ids.length > MAX_BATCH_SIZE) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Batch size ${ids.length} exceeds maximum allowed size of ${MAX_BATCH_SIZE}`);\n }\n\n // Validate and sanitize IDs\n const validatedIds: string[] = [];\n const invalidIds: string[] = [];\n\n for (const id of ids) {\n const trimmedId = id.trim();\n if (!trimmedId) {\n invalidIds.push(id);\n continue;\n }\n // Basic Gmail label ID validation - should not contain certain characters\n if (trimmedId.includes('/') || trimmedId.includes('\\\\') || trimmedId.includes('<') || trimmedId.includes('>')) {\n invalidIds.push(id);\n continue;\n }\n validatedIds.push(trimmedId);\n }\n\n if (invalidIds.length > 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Found ${invalidIds.length} invalid IDs: ${invalidIds.join(', ')}`);\n }\n\n if (validatedIds.length === 0) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'No valid IDs found after validation');\n }\n\n try {\n const gmail = google.gmail({ version: 'v1', auth: googleAuth(extra.authContext.auth) });\n // Get all labels first to check for system labels\n const labelsResponse = await gmail.users.labels.list({ userId: 'me' });\n const allLabels = labelsResponse.data.labels || [];\n const labelMap = new Map(allLabels.map((label) => [label.id || '', label]));\n\n // Process deletions in chunks to prevent memory exhaustion\n const allResults: Array<{ id: string; success: boolean; error?: string }> = [];\n\n for (let i = 0; i < validatedIds.length; i += CHUNK_SIZE) {\n const chunk = validatedIds.slice(i, i + CHUNK_SIZE);\n logger.info('Processing chunk', { chunkIndex: i / CHUNK_SIZE + 1, chunkSize: chunk.length, totalChunks: Math.ceil(validatedIds.length / CHUNK_SIZE) });\n\n const chunkResults = await Promise.allSettled(\n chunk.map(async (id) => {\n const label = labelMap.get(id);\n\n // Check if label exists\n if (!label) {\n throw new Error(`Label not found: ${id}`);\n }\n\n // Check if it's a system label\n if (label.type === 'system') {\n throw new Error(`Cannot delete system label: ${label.name} (${id})`);\n }\n\n // Delete the label\n await gmail.users.labels.delete({\n userId: 'me',\n id: id,\n });\n return { id, success: true };\n })\n );\n\n // Process chunk results\n const processedChunkResults = chunkResults.map((result, chunkIndex) => {\n const id = chunk[chunkIndex];\n if (!id) {\n throw new Error(`Chunk index ${chunkIndex} is out of bounds for chunk of size ${chunk.length}`);\n }\n if (result.status === 'fulfilled') {\n return { id, success: true };\n }\n\n // Extract error message more robustly\n let errorMessage = 'Unknown error';\n if (result.reason) {\n if (typeof result.reason === 'string') {\n errorMessage = result.reason;\n } else if (result.reason instanceof Error) {\n errorMessage = result.reason.message;\n } else if (result.reason && typeof result.reason === 'object' && 'message' in result.reason) {\n errorMessage = String(result.reason.message);\n } else if (result.reason && typeof result.reason === 'object' && 'error' in result.reason) {\n errorMessage = String(result.reason.error);\n } else {\n errorMessage = String(result.reason);\n }\n }\n\n return { id, success: false, error: errorMessage };\n });\n\n allResults.push(...processedChunkResults);\n }\n\n const successCount = allResults.filter((r) => r.success).length;\n const failureCount = allResults.filter((r) => !r.success).length;\n\n logger.info('gmail-label-delete completed', {\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n chunksProcessed: Math.ceil(validatedIds.length / CHUNK_SIZE),\n });\n\n const result: Output = {\n type: 'success' as const,\n totalRequested: validatedIds.length,\n successCount,\n failureCount,\n results: allResults,\n };\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(result),\n },\n ],\n structuredContent: { result },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error('gmail-label-delete error', { error: message });\n\n throw new ProtocolError(ProtocolErrorCode.InternalError, `Error deleting labels: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n });\n }\n}\n\nexport default function createTool() {\n return {\n name: 'label-delete',\n config,\n handler,\n } satisfies ToolModule;\n}\n"],"names":["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","labelsResponse","allLabels","labelMap","allResults","i","message","info","count","length","ProtocolError","ProtocolErrorCode","InvalidParams","MAX_BATCH_SIZE","push","includes","join","chunk","chunkResults","processedChunkResults","slice","CHUNK_SIZE","chunkIndex","chunkSize","totalChunks","Math","ceil","Promise","allSettled","map","label","get","Error","name","users","labels","delete","userId","status","errorMessage","reason","String","google","version","auth","googleAuth","authContext","list","data","Map","filter","r","chunksProcessed","content","text","JSON","stringify","structuredContent","InternalError","stack","undefined"],"mappings":";;;;+BA8LA;;;eAAwBA;;;2BA7LA;sBAKyB;0BAC1B;mBACL;2BACyB;4BAChB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAP3B,IAAM,AAAEC,2BAA6BC,oBAAO,CAApCD;AASR,IAAME,cAAcC,MAAC,CAACC,MAAM,CAAC;IAC3BC,KAAKF,MAAC,CAACG,KAAK,CAACH,MAAC,CAACI,MAAM,CAACC,MAAM,GAAGC,IAAI,GAAGC,GAAG,CAAC,IAAIA,GAAG,CAAC,GAAGC,QAAQ,CAAC;AAChE;AAEA,IAAMC,sBAAsBT,MAAC,CAACC,MAAM,CAAC;IACnCS,MAAMV,MAAC,CAACW,OAAO,CAAC;IAChBC,gBAAgBZ,MAAC,CAACa,MAAM,GAAGL,QAAQ,CAAC;IACpCM,cAAcd,MAAC,CAACa,MAAM,GAAGL,QAAQ,CAAC;IAClCO,cAAcf,MAAC,CAACa,MAAM,GAAGL,QAAQ,CAAC;IAClCQ,SAAShB,MAAC,CACPG,KAAK,CACJH,MAAC,CAACC,MAAM,CAAC;QACPgB,IAAIjB,MAAC,CAACK,MAAM,GAAGG,QAAQ,CAAC;QACxBU,SAASlB,MAAC,CAACmB,OAAO,GAAGX,QAAQ,CAAC;QAC9BY,OAAOpB,MAAC,CAACK,MAAM,GAAGgB,QAAQ,GAAGb,QAAQ,CAAC;IACxC,IAEDA,QAAQ,CAAC;AACd;AAEA,IAAMc,eAAetB,MAAC,CAACuB,kBAAkB,CAAC,QAAQ;IAACd;IAAqBZ;CAAyB;AAEjG,IAAM2B,SAAS;IACbC,aAAa;IACb1B,aAAaA;IACbuB,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K,YAALA,OAAiB6C,SAAQ7C,MAAMwE,KAAK,GAAGC;oBAChD;;;;;;;IAEJ;;AAEe,SAASjG;IACtB,OAAO;QACLsE,MAAM;QACN1C,QAAAA;QACAG,SAAAA;IACF;AACF"}
@@ -10,8 +10,8 @@ declare const outputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
10
10
  id: z.ZodString;
11
11
  name: z.ZodString;
12
12
  type: z.ZodEnum<{
13
- user: "user";
14
13
  system: "system";
14
+ user: "user";
15
15
  }>;
16
16
  visibility: z.ZodEnum<{
17
17
  labelShow: "labelShow";
@@ -41,7 +41,7 @@ declare function handler(_: Input, extra: EnrichedExtra): Promise<{
41
41
  items: {
42
42
  id: string;
43
43
  name: string;
44
- type: "user" | "system";
44
+ type: "system" | "user";
45
45
  visibility: "labelShow" | "labelHide" | "labelShowIfUnread";
46
46
  }[];
47
47
  };
@@ -59,8 +59,8 @@ export default function createTool(): {
59
59
  id: z.ZodString;
60
60
  name: z.ZodString;
61
61
  type: z.ZodEnum<{
62
- user: "user";
63
62
  system: "system";
63
+ user: "user";
64
64
  }>;
65
65
  visibility: z.ZodEnum<{
66
66
  labelShow: "labelShow";