@mindstone/mcp-server-google-workspace 0.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 (514) hide show
  1. package/LICENSE +97 -0
  2. package/README.md +71 -0
  3. package/SECURITY.md +38 -0
  4. package/dist/__fixtures__/accounts.d.ts +47 -0
  5. package/dist/__fixtures__/accounts.d.ts.map +1 -0
  6. package/dist/__fixtures__/accounts.js +56 -0
  7. package/dist/__fixtures__/accounts.js.map +1 -0
  8. package/dist/api/handler.d.ts +16 -0
  9. package/dist/api/handler.d.ts.map +1 -0
  10. package/dist/api/handler.js +68 -0
  11. package/dist/api/handler.js.map +1 -0
  12. package/dist/api/request.d.ts +13 -0
  13. package/dist/api/request.d.ts.map +1 -0
  14. package/dist/api/request.js +111 -0
  15. package/dist/api/request.js.map +1 -0
  16. package/dist/api/validators/endpoint.d.ts +8 -0
  17. package/dist/api/validators/endpoint.d.ts.map +1 -0
  18. package/dist/api/validators/endpoint.js +115 -0
  19. package/dist/api/validators/endpoint.js.map +1 -0
  20. package/dist/api/validators/parameter.d.ts +12 -0
  21. package/dist/api/validators/parameter.d.ts.map +1 -0
  22. package/dist/api/validators/parameter.js +155 -0
  23. package/dist/api/validators/parameter.js.map +1 -0
  24. package/dist/index.d.ts +3 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +28 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/modules/accounts/index.d.ts +12 -0
  29. package/dist/modules/accounts/index.d.ts.map +1 -0
  30. package/dist/modules/accounts/index.js +41 -0
  31. package/dist/modules/accounts/index.js.map +1 -0
  32. package/dist/modules/accounts/manager.d.ts +40 -0
  33. package/dist/modules/accounts/manager.d.ts.map +1 -0
  34. package/dist/modules/accounts/manager.js +359 -0
  35. package/dist/modules/accounts/manager.js.map +1 -0
  36. package/dist/modules/accounts/oauth.d.ts +36 -0
  37. package/dist/modules/accounts/oauth.d.ts.map +1 -0
  38. package/dist/modules/accounts/oauth.js +112 -0
  39. package/dist/modules/accounts/oauth.js.map +1 -0
  40. package/dist/modules/accounts/token.d.ts +32 -0
  41. package/dist/modules/accounts/token.d.ts.map +1 -0
  42. package/dist/modules/accounts/token.js +305 -0
  43. package/dist/modules/accounts/token.js.map +1 -0
  44. package/dist/modules/accounts/types.d.ts +47 -0
  45. package/dist/modules/accounts/types.d.ts.map +1 -0
  46. package/dist/modules/accounts/types.js +16 -0
  47. package/dist/modules/accounts/types.js.map +1 -0
  48. package/dist/modules/accounts/unauthorized.d.ts +3 -0
  49. package/dist/modules/accounts/unauthorized.d.ts.map +1 -0
  50. package/dist/modules/accounts/unauthorized.js +44 -0
  51. package/dist/modules/accounts/unauthorized.js.map +1 -0
  52. package/dist/modules/attachments/cleanup-service.d.ts +44 -0
  53. package/dist/modules/attachments/cleanup-service.d.ts.map +1 -0
  54. package/dist/modules/attachments/cleanup-service.js +118 -0
  55. package/dist/modules/attachments/cleanup-service.js.map +1 -0
  56. package/dist/modules/attachments/index-service.d.ts +57 -0
  57. package/dist/modules/attachments/index-service.d.ts.map +1 -0
  58. package/dist/modules/attachments/index-service.js +110 -0
  59. package/dist/modules/attachments/index-service.js.map +1 -0
  60. package/dist/modules/attachments/response-transformer.d.ts +28 -0
  61. package/dist/modules/attachments/response-transformer.d.ts.map +1 -0
  62. package/dist/modules/attachments/response-transformer.js +64 -0
  63. package/dist/modules/attachments/response-transformer.js.map +1 -0
  64. package/dist/modules/attachments/service.d.ts +47 -0
  65. package/dist/modules/attachments/service.d.ts.map +1 -0
  66. package/dist/modules/attachments/service.js +362 -0
  67. package/dist/modules/attachments/service.js.map +1 -0
  68. package/dist/modules/attachments/transformer.d.ts +28 -0
  69. package/dist/modules/attachments/transformer.d.ts.map +1 -0
  70. package/dist/modules/attachments/transformer.js +31 -0
  71. package/dist/modules/attachments/transformer.js.map +1 -0
  72. package/dist/modules/attachments/types.d.ts +33 -0
  73. package/dist/modules/attachments/types.d.ts.map +1 -0
  74. package/dist/modules/attachments/types.js +9 -0
  75. package/dist/modules/attachments/types.js.map +1 -0
  76. package/dist/modules/calendar/index.d.ts +48 -0
  77. package/dist/modules/calendar/index.d.ts.map +1 -0
  78. package/dist/modules/calendar/index.js +61 -0
  79. package/dist/modules/calendar/index.js.map +1 -0
  80. package/dist/modules/calendar/scopes.d.ts +17 -0
  81. package/dist/modules/calendar/scopes.d.ts.map +1 -0
  82. package/dist/modules/calendar/scopes.js +39 -0
  83. package/dist/modules/calendar/scopes.js.map +1 -0
  84. package/dist/modules/calendar/service.d.ts +75 -0
  85. package/dist/modules/calendar/service.d.ts.map +1 -0
  86. package/dist/modules/calendar/service.js +705 -0
  87. package/dist/modules/calendar/service.js.map +1 -0
  88. package/dist/modules/calendar/types.d.ts +154 -0
  89. package/dist/modules/calendar/types.d.ts.map +1 -0
  90. package/dist/modules/calendar/types.js +11 -0
  91. package/dist/modules/calendar/types.js.map +1 -0
  92. package/dist/modules/comments/index.d.ts +12 -0
  93. package/dist/modules/comments/index.d.ts.map +1 -0
  94. package/dist/modules/comments/index.js +23 -0
  95. package/dist/modules/comments/index.js.map +1 -0
  96. package/dist/modules/comments/service.d.ts +39 -0
  97. package/dist/modules/comments/service.d.ts.map +1 -0
  98. package/dist/modules/comments/service.js +227 -0
  99. package/dist/modules/comments/service.js.map +1 -0
  100. package/dist/modules/comments/types.d.ts +67 -0
  101. package/dist/modules/comments/types.d.ts.map +1 -0
  102. package/dist/modules/comments/types.js +2 -0
  103. package/dist/modules/comments/types.js.map +1 -0
  104. package/dist/modules/contacts/index.d.ts +12 -0
  105. package/dist/modules/contacts/index.d.ts.map +1 -0
  106. package/dist/modules/contacts/index.js +18 -0
  107. package/dist/modules/contacts/index.js.map +1 -0
  108. package/dist/modules/contacts/scopes.d.ts +4 -0
  109. package/dist/modules/contacts/scopes.d.ts.map +1 -0
  110. package/dist/modules/contacts/scopes.js +11 -0
  111. package/dist/modules/contacts/scopes.js.map +1 -0
  112. package/dist/modules/contacts/types.d.ts +55 -0
  113. package/dist/modules/contacts/types.d.ts.map +1 -0
  114. package/dist/modules/contacts/types.js +14 -0
  115. package/dist/modules/contacts/types.js.map +1 -0
  116. package/dist/modules/docs/formatters.d.ts +30 -0
  117. package/dist/modules/docs/formatters.d.ts.map +1 -0
  118. package/dist/modules/docs/formatters.js +76 -0
  119. package/dist/modules/docs/formatters.js.map +1 -0
  120. package/dist/modules/docs/index.d.ts +9 -0
  121. package/dist/modules/docs/index.d.ts.map +1 -0
  122. package/dist/modules/docs/index.js +23 -0
  123. package/dist/modules/docs/index.js.map +1 -0
  124. package/dist/modules/docs/scopes.d.ts +17 -0
  125. package/dist/modules/docs/scopes.d.ts.map +1 -0
  126. package/dist/modules/docs/scopes.js +39 -0
  127. package/dist/modules/docs/scopes.js.map +1 -0
  128. package/dist/modules/docs/service.d.ts +58 -0
  129. package/dist/modules/docs/service.d.ts.map +1 -0
  130. package/dist/modules/docs/service.js +421 -0
  131. package/dist/modules/docs/service.js.map +1 -0
  132. package/dist/modules/docs/types.d.ts +75 -0
  133. package/dist/modules/docs/types.d.ts.map +1 -0
  134. package/dist/modules/docs/types.js +2 -0
  135. package/dist/modules/docs/types.js.map +1 -0
  136. package/dist/modules/drive/index.d.ts +9 -0
  137. package/dist/modules/drive/index.d.ts.map +1 -0
  138. package/dist/modules/drive/index.js +28 -0
  139. package/dist/modules/drive/index.js.map +1 -0
  140. package/dist/modules/drive/scopes.d.ts +19 -0
  141. package/dist/modules/drive/scopes.d.ts.map +1 -0
  142. package/dist/modules/drive/scopes.js +44 -0
  143. package/dist/modules/drive/scopes.js.map +1 -0
  144. package/dist/modules/drive/service.d.ts +33 -0
  145. package/dist/modules/drive/service.d.ts.map +1 -0
  146. package/dist/modules/drive/service.js +467 -0
  147. package/dist/modules/drive/service.js.map +1 -0
  148. package/dist/modules/drive/types.d.ts +55 -0
  149. package/dist/modules/drive/types.d.ts.map +1 -0
  150. package/dist/modules/drive/types.js +2 -0
  151. package/dist/modules/drive/types.js.map +1 -0
  152. package/dist/modules/forms/index.d.ts +13 -0
  153. package/dist/modules/forms/index.d.ts.map +1 -0
  154. package/dist/modules/forms/index.js +24 -0
  155. package/dist/modules/forms/index.js.map +1 -0
  156. package/dist/modules/forms/scopes.d.ts +21 -0
  157. package/dist/modules/forms/scopes.d.ts.map +1 -0
  158. package/dist/modules/forms/scopes.js +36 -0
  159. package/dist/modules/forms/scopes.js.map +1 -0
  160. package/dist/modules/forms/service.d.ts +52 -0
  161. package/dist/modules/forms/service.d.ts.map +1 -0
  162. package/dist/modules/forms/service.js +284 -0
  163. package/dist/modules/forms/service.js.map +1 -0
  164. package/dist/modules/forms/types.d.ts +399 -0
  165. package/dist/modules/forms/types.d.ts.map +1 -0
  166. package/dist/modules/forms/types.js +6 -0
  167. package/dist/modules/forms/types.js.map +1 -0
  168. package/dist/modules/gmail/constants.d.ts +69 -0
  169. package/dist/modules/gmail/constants.d.ts.map +1 -0
  170. package/dist/modules/gmail/constants.js +100 -0
  171. package/dist/modules/gmail/constants.js.map +1 -0
  172. package/dist/modules/gmail/index.d.ts +7 -0
  173. package/dist/modules/gmail/index.d.ts.map +1 -0
  174. package/dist/modules/gmail/index.js +16 -0
  175. package/dist/modules/gmail/index.js.map +1 -0
  176. package/dist/modules/gmail/scopes.d.ts +17 -0
  177. package/dist/modules/gmail/scopes.d.ts.map +1 -0
  178. package/dist/modules/gmail/scopes.js +39 -0
  179. package/dist/modules/gmail/scopes.js.map +1 -0
  180. package/dist/modules/gmail/service.d.ts +2 -0
  181. package/dist/modules/gmail/service.d.ts.map +1 -0
  182. package/dist/modules/gmail/service.js +2 -0
  183. package/dist/modules/gmail/service.js.map +1 -0
  184. package/dist/modules/gmail/services/attachment.d.ts +41 -0
  185. package/dist/modules/gmail/services/attachment.d.ts.map +1 -0
  186. package/dist/modules/gmail/services/attachment.js +143 -0
  187. package/dist/modules/gmail/services/attachment.js.map +1 -0
  188. package/dist/modules/gmail/services/base.d.ts +79 -0
  189. package/dist/modules/gmail/services/base.d.ts.map +1 -0
  190. package/dist/modules/gmail/services/base.js +124 -0
  191. package/dist/modules/gmail/services/base.js.map +1 -0
  192. package/dist/modules/gmail/services/draft.d.ts +104 -0
  193. package/dist/modules/gmail/services/draft.d.ts.map +1 -0
  194. package/dist/modules/gmail/services/draft.js +239 -0
  195. package/dist/modules/gmail/services/draft.js.map +1 -0
  196. package/dist/modules/gmail/services/email.d.ts +82 -0
  197. package/dist/modules/gmail/services/email.d.ts.map +1 -0
  198. package/dist/modules/gmail/services/email.js +462 -0
  199. package/dist/modules/gmail/services/email.js.map +1 -0
  200. package/dist/modules/gmail/services/label.d.ts +62 -0
  201. package/dist/modules/gmail/services/label.d.ts.map +1 -0
  202. package/dist/modules/gmail/services/label.js +501 -0
  203. package/dist/modules/gmail/services/label.js.map +1 -0
  204. package/dist/modules/gmail/services/mime-builder.d.ts +26 -0
  205. package/dist/modules/gmail/services/mime-builder.d.ts.map +1 -0
  206. package/dist/modules/gmail/services/mime-builder.js +83 -0
  207. package/dist/modules/gmail/services/mime-builder.js.map +1 -0
  208. package/dist/modules/gmail/services/search.d.ts +8 -0
  209. package/dist/modules/gmail/services/search.d.ts.map +1 -0
  210. package/dist/modules/gmail/services/search.js +76 -0
  211. package/dist/modules/gmail/services/search.js.map +1 -0
  212. package/dist/modules/gmail/services/settings.d.ts +14 -0
  213. package/dist/modules/gmail/services/settings.d.ts.map +1 -0
  214. package/dist/modules/gmail/services/settings.js +104 -0
  215. package/dist/modules/gmail/services/settings.js.map +1 -0
  216. package/dist/modules/gmail/types.d.ts +279 -0
  217. package/dist/modules/gmail/types.d.ts.map +1 -0
  218. package/dist/modules/gmail/types.js +11 -0
  219. package/dist/modules/gmail/types.js.map +1 -0
  220. package/dist/modules/sheets/a1Utils.d.ts +20 -0
  221. package/dist/modules/sheets/a1Utils.d.ts.map +1 -0
  222. package/dist/modules/sheets/a1Utils.js +252 -0
  223. package/dist/modules/sheets/a1Utils.js.map +1 -0
  224. package/dist/modules/sheets/cellShape.d.ts +48 -0
  225. package/dist/modules/sheets/cellShape.d.ts.map +1 -0
  226. package/dist/modules/sheets/cellShape.js +418 -0
  227. package/dist/modules/sheets/cellShape.js.map +1 -0
  228. package/dist/modules/sheets/errorRewriter.d.ts +6 -0
  229. package/dist/modules/sheets/errorRewriter.d.ts.map +1 -0
  230. package/dist/modules/sheets/errorRewriter.js +120 -0
  231. package/dist/modules/sheets/errorRewriter.js.map +1 -0
  232. package/dist/modules/sheets/formatters.d.ts +54 -0
  233. package/dist/modules/sheets/formatters.d.ts.map +1 -0
  234. package/dist/modules/sheets/formatters.js +270 -0
  235. package/dist/modules/sheets/formatters.js.map +1 -0
  236. package/dist/modules/sheets/index.d.ts +9 -0
  237. package/dist/modules/sheets/index.d.ts.map +1 -0
  238. package/dist/modules/sheets/index.js +23 -0
  239. package/dist/modules/sheets/index.js.map +1 -0
  240. package/dist/modules/sheets/scopes.d.ts +17 -0
  241. package/dist/modules/sheets/scopes.d.ts.map +1 -0
  242. package/dist/modules/sheets/scopes.js +39 -0
  243. package/dist/modules/sheets/scopes.js.map +1 -0
  244. package/dist/modules/sheets/service.d.ts +102 -0
  245. package/dist/modules/sheets/service.d.ts.map +1 -0
  246. package/dist/modules/sheets/service.js +1650 -0
  247. package/dist/modules/sheets/service.js.map +1 -0
  248. package/dist/modules/sheets/types.d.ts +271 -0
  249. package/dist/modules/sheets/types.d.ts.map +1 -0
  250. package/dist/modules/sheets/types.js +2 -0
  251. package/dist/modules/sheets/types.js.map +1 -0
  252. package/dist/modules/sheets/writeGuards.d.ts +31 -0
  253. package/dist/modules/sheets/writeGuards.d.ts.map +1 -0
  254. package/dist/modules/sheets/writeGuards.js +254 -0
  255. package/dist/modules/sheets/writeGuards.js.map +1 -0
  256. package/dist/modules/slides/formatters.d.ts +35 -0
  257. package/dist/modules/slides/formatters.d.ts.map +1 -0
  258. package/dist/modules/slides/formatters.js +96 -0
  259. package/dist/modules/slides/formatters.js.map +1 -0
  260. package/dist/modules/slides/index.d.ts +9 -0
  261. package/dist/modules/slides/index.d.ts.map +1 -0
  262. package/dist/modules/slides/index.js +23 -0
  263. package/dist/modules/slides/index.js.map +1 -0
  264. package/dist/modules/slides/scopes.d.ts +17 -0
  265. package/dist/modules/slides/scopes.d.ts.map +1 -0
  266. package/dist/modules/slides/scopes.js +39 -0
  267. package/dist/modules/slides/scopes.js.map +1 -0
  268. package/dist/modules/slides/service.d.ts +67 -0
  269. package/dist/modules/slides/service.d.ts.map +1 -0
  270. package/dist/modules/slides/service.js +394 -0
  271. package/dist/modules/slides/service.js.map +1 -0
  272. package/dist/modules/slides/types.d.ts +63 -0
  273. package/dist/modules/slides/types.d.ts.map +1 -0
  274. package/dist/modules/slides/types.js +2 -0
  275. package/dist/modules/slides/types.js.map +1 -0
  276. package/dist/modules/tasks/index.d.ts +13 -0
  277. package/dist/modules/tasks/index.d.ts.map +1 -0
  278. package/dist/modules/tasks/index.js +24 -0
  279. package/dist/modules/tasks/index.js.map +1 -0
  280. package/dist/modules/tasks/scopes.d.ts +18 -0
  281. package/dist/modules/tasks/scopes.d.ts.map +1 -0
  282. package/dist/modules/tasks/scopes.js +28 -0
  283. package/dist/modules/tasks/scopes.js.map +1 -0
  284. package/dist/modules/tasks/service.d.ts +72 -0
  285. package/dist/modules/tasks/service.d.ts.map +1 -0
  286. package/dist/modules/tasks/service.js +319 -0
  287. package/dist/modules/tasks/service.js.map +1 -0
  288. package/dist/modules/tasks/types.d.ts +118 -0
  289. package/dist/modules/tasks/types.d.ts.map +1 -0
  290. package/dist/modules/tasks/types.js +6 -0
  291. package/dist/modules/tasks/types.js.map +1 -0
  292. package/dist/modules/tools/registry.d.ts +28 -0
  293. package/dist/modules/tools/registry.d.ts.map +1 -0
  294. package/dist/modules/tools/registry.js +229 -0
  295. package/dist/modules/tools/registry.js.map +1 -0
  296. package/dist/modules/tools/scope-registry.d.ts +31 -0
  297. package/dist/modules/tools/scope-registry.d.ts.map +1 -0
  298. package/dist/modules/tools/scope-registry.js +52 -0
  299. package/dist/modules/tools/scope-registry.js.map +1 -0
  300. package/dist/oauth/client.d.ts +15 -0
  301. package/dist/oauth/client.d.ts.map +1 -0
  302. package/dist/oauth/client.js +136 -0
  303. package/dist/oauth/client.js.map +1 -0
  304. package/dist/resources/compose-email-template.d.ts +2 -0
  305. package/dist/resources/compose-email-template.d.ts.map +1 -0
  306. package/dist/resources/compose-email-template.js +711 -0
  307. package/dist/resources/compose-email-template.js.map +1 -0
  308. package/dist/scripts/health-check.d.ts +3 -0
  309. package/dist/scripts/health-check.d.ts.map +1 -0
  310. package/dist/scripts/health-check.js +22 -0
  311. package/dist/scripts/health-check.js.map +1 -0
  312. package/dist/scripts/setup-environment.d.ts +3 -0
  313. package/dist/scripts/setup-environment.d.ts.map +1 -0
  314. package/dist/scripts/setup-environment.js +91 -0
  315. package/dist/scripts/setup-environment.js.map +1 -0
  316. package/dist/scripts/setup-google-env.d.ts +3 -0
  317. package/dist/scripts/setup-google-env.d.ts.map +1 -0
  318. package/dist/scripts/setup-google-env.js +78 -0
  319. package/dist/scripts/setup-google-env.js.map +1 -0
  320. package/dist/services/base/BaseGoogleService.d.ts +52 -0
  321. package/dist/services/base/BaseGoogleService.d.ts.map +1 -0
  322. package/dist/services/base/BaseGoogleService.js +155 -0
  323. package/dist/services/base/BaseGoogleService.js.map +1 -0
  324. package/dist/services/calendar/index.d.ts +27 -0
  325. package/dist/services/calendar/index.d.ts.map +1 -0
  326. package/dist/services/calendar/index.js +146 -0
  327. package/dist/services/calendar/index.js.map +1 -0
  328. package/dist/services/contacts/index.d.ts +40 -0
  329. package/dist/services/contacts/index.d.ts.map +1 -0
  330. package/dist/services/contacts/index.js +137 -0
  331. package/dist/services/contacts/index.js.map +1 -0
  332. package/dist/services/docs/index.d.ts +4 -0
  333. package/dist/services/docs/index.d.ts.map +1 -0
  334. package/dist/services/docs/index.js +6 -0
  335. package/dist/services/docs/index.js.map +1 -0
  336. package/dist/services/drive/index.d.ts +4 -0
  337. package/dist/services/drive/index.d.ts.map +1 -0
  338. package/dist/services/drive/index.js +6 -0
  339. package/dist/services/drive/index.js.map +1 -0
  340. package/dist/services/gmail/index.d.ts +39 -0
  341. package/dist/services/gmail/index.d.ts.map +1 -0
  342. package/dist/services/gmail/index.js +337 -0
  343. package/dist/services/gmail/index.js.map +1 -0
  344. package/dist/services/sheets/index.d.ts +4 -0
  345. package/dist/services/sheets/index.d.ts.map +1 -0
  346. package/dist/services/sheets/index.js +6 -0
  347. package/dist/services/sheets/index.js.map +1 -0
  348. package/dist/services/slides/index.d.ts +4 -0
  349. package/dist/services/slides/index.d.ts.map +1 -0
  350. package/dist/services/slides/index.js +6 -0
  351. package/dist/services/slides/index.js.map +1 -0
  352. package/dist/tools/account-handlers.d.ts +28 -0
  353. package/dist/tools/account-handlers.d.ts.map +1 -0
  354. package/dist/tools/account-handlers.js +105 -0
  355. package/dist/tools/account-handlers.js.map +1 -0
  356. package/dist/tools/arg-aliases.d.ts +6 -0
  357. package/dist/tools/arg-aliases.d.ts.map +1 -0
  358. package/dist/tools/arg-aliases.js +22 -0
  359. package/dist/tools/arg-aliases.js.map +1 -0
  360. package/dist/tools/calendar-handlers.d.ts +83 -0
  361. package/dist/tools/calendar-handlers.d.ts.map +1 -0
  362. package/dist/tools/calendar-handlers.js +658 -0
  363. package/dist/tools/calendar-handlers.js.map +1 -0
  364. package/dist/tools/comments-handlers.d.ts +59 -0
  365. package/dist/tools/comments-handlers.d.ts.map +1 -0
  366. package/dist/tools/comments-handlers.js +138 -0
  367. package/dist/tools/comments-handlers.js.map +1 -0
  368. package/dist/tools/contacts-handlers.d.ts +36 -0
  369. package/dist/tools/contacts-handlers.d.ts.map +1 -0
  370. package/dist/tools/contacts-handlers.js +128 -0
  371. package/dist/tools/contacts-handlers.js.map +1 -0
  372. package/dist/tools/definitions/account.d.ts +3 -0
  373. package/dist/tools/definitions/account.d.ts.map +1 -0
  374. package/dist/tools/definitions/account.js +77 -0
  375. package/dist/tools/definitions/account.js.map +1 -0
  376. package/dist/tools/definitions/calendar.d.ts +3 -0
  377. package/dist/tools/definitions/calendar.d.ts.map +1 -0
  378. package/dist/tools/definitions/calendar.js +565 -0
  379. package/dist/tools/definitions/calendar.js.map +1 -0
  380. package/dist/tools/definitions/comments.d.ts +3 -0
  381. package/dist/tools/definitions/comments.d.ts.map +1 -0
  382. package/dist/tools/definitions/comments.js +207 -0
  383. package/dist/tools/definitions/comments.js.map +1 -0
  384. package/dist/tools/definitions/contacts.d.ts +3 -0
  385. package/dist/tools/definitions/contacts.d.ts.map +1 -0
  386. package/dist/tools/definitions/contacts.js +93 -0
  387. package/dist/tools/definitions/contacts.js.map +1 -0
  388. package/dist/tools/definitions/destructive-overrides.json +106 -0
  389. package/dist/tools/definitions/docs.d.ts +3 -0
  390. package/dist/tools/definitions/docs.d.ts.map +1 -0
  391. package/dist/tools/definitions/docs.js +416 -0
  392. package/dist/tools/definitions/docs.js.map +1 -0
  393. package/dist/tools/definitions/drive.d.ts +3 -0
  394. package/dist/tools/definitions/drive.d.ts.map +1 -0
  395. package/dist/tools/definitions/drive.js +587 -0
  396. package/dist/tools/definitions/drive.js.map +1 -0
  397. package/dist/tools/definitions/forms.d.ts +14 -0
  398. package/dist/tools/definitions/forms.d.ts.map +1 -0
  399. package/dist/tools/definitions/forms.js +189 -0
  400. package/dist/tools/definitions/forms.js.map +1 -0
  401. package/dist/tools/definitions/gmail.d.ts +3 -0
  402. package/dist/tools/definitions/gmail.d.ts.map +1 -0
  403. package/dist/tools/definitions/gmail.js +962 -0
  404. package/dist/tools/definitions/gmail.js.map +1 -0
  405. package/dist/tools/definitions/index.d.ts +33 -0
  406. package/dist/tools/definitions/index.d.ts.map +1 -0
  407. package/dist/tools/definitions/index.js +77 -0
  408. package/dist/tools/definitions/index.js.map +1 -0
  409. package/dist/tools/definitions/labels.d.ts +3 -0
  410. package/dist/tools/definitions/labels.d.ts.map +1 -0
  411. package/dist/tools/definitions/labels.js +662 -0
  412. package/dist/tools/definitions/labels.js.map +1 -0
  413. package/dist/tools/definitions/open-world-overrides.json +106 -0
  414. package/dist/tools/definitions/sheets.d.ts +3 -0
  415. package/dist/tools/definitions/sheets.d.ts.map +1 -0
  416. package/dist/tools/definitions/sheets.js +833 -0
  417. package/dist/tools/definitions/sheets.js.map +1 -0
  418. package/dist/tools/definitions/slides.d.ts +3 -0
  419. package/dist/tools/definitions/slides.d.ts.map +1 -0
  420. package/dist/tools/definitions/slides.js +383 -0
  421. package/dist/tools/definitions/slides.js.map +1 -0
  422. package/dist/tools/definitions/tasks.d.ts +11 -0
  423. package/dist/tools/definitions/tasks.d.ts.map +1 -0
  424. package/dist/tools/definitions/tasks.js +259 -0
  425. package/dist/tools/definitions/tasks.js.map +1 -0
  426. package/dist/tools/definitions.d.ts +8 -0
  427. package/dist/tools/definitions.d.ts.map +1 -0
  428. package/dist/tools/definitions.js +9 -0
  429. package/dist/tools/definitions.js.map +1 -0
  430. package/dist/tools/docs-handlers.d.ts +96 -0
  431. package/dist/tools/docs-handlers.d.ts.map +1 -0
  432. package/dist/tools/docs-handlers.js +250 -0
  433. package/dist/tools/docs-handlers.js.map +1 -0
  434. package/dist/tools/drive-handlers.d.ts +95 -0
  435. package/dist/tools/drive-handlers.d.ts.map +1 -0
  436. package/dist/tools/drive-handlers.js +506 -0
  437. package/dist/tools/drive-handlers.js.map +1 -0
  438. package/dist/tools/forms-handlers.d.ts +72 -0
  439. package/dist/tools/forms-handlers.d.ts.map +1 -0
  440. package/dist/tools/forms-handlers.js +435 -0
  441. package/dist/tools/forms-handlers.js.map +1 -0
  442. package/dist/tools/gmail-handlers.d.ts +320 -0
  443. package/dist/tools/gmail-handlers.d.ts.map +1 -0
  444. package/dist/tools/gmail-handlers.js +1040 -0
  445. package/dist/tools/gmail-handlers.js.map +1 -0
  446. package/dist/tools/param-normalizer.d.ts +2 -0
  447. package/dist/tools/param-normalizer.d.ts.map +1 -0
  448. package/dist/tools/param-normalizer.js +96 -0
  449. package/dist/tools/param-normalizer.js.map +1 -0
  450. package/dist/tools/server.d.ts +14 -0
  451. package/dist/tools/server.d.ts.map +1 -0
  452. package/dist/tools/server.js +733 -0
  453. package/dist/tools/server.js.map +1 -0
  454. package/dist/tools/sheets-handlers.d.ts +230 -0
  455. package/dist/tools/sheets-handlers.d.ts.map +1 -0
  456. package/dist/tools/sheets-handlers.js +589 -0
  457. package/dist/tools/sheets-handlers.js.map +1 -0
  458. package/dist/tools/slides-handlers.d.ts +90 -0
  459. package/dist/tools/slides-handlers.d.ts.map +1 -0
  460. package/dist/tools/slides-handlers.js +281 -0
  461. package/dist/tools/slides-handlers.js.map +1 -0
  462. package/dist/tools/tasks-handlers.d.ts +85 -0
  463. package/dist/tools/tasks-handlers.d.ts.map +1 -0
  464. package/dist/tools/tasks-handlers.js +265 -0
  465. package/dist/tools/tasks-handlers.js.map +1 -0
  466. package/dist/tools/type-guards.d.ts +491 -0
  467. package/dist/tools/type-guards.d.ts.map +1 -0
  468. package/dist/tools/type-guards.js +1325 -0
  469. package/dist/tools/type-guards.js.map +1 -0
  470. package/dist/tools/types.d.ts +298 -0
  471. package/dist/tools/types.d.ts.map +1 -0
  472. package/dist/tools/types.js +2 -0
  473. package/dist/tools/types.js.map +1 -0
  474. package/dist/types.d.ts +70 -0
  475. package/dist/types.d.ts.map +1 -0
  476. package/dist/types.js +12 -0
  477. package/dist/types.js.map +1 -0
  478. package/dist/utils/atomicCredentialWrite.d.ts +5 -0
  479. package/dist/utils/atomicCredentialWrite.d.ts.map +1 -0
  480. package/dist/utils/atomicCredentialWrite.js +120 -0
  481. package/dist/utils/atomicCredentialWrite.js.map +1 -0
  482. package/dist/utils/emfileRetry.d.ts +3 -0
  483. package/dist/utils/emfileRetry.d.ts.map +1 -0
  484. package/dist/utils/emfileRetry.js +24 -0
  485. package/dist/utils/emfileRetry.js.map +1 -0
  486. package/dist/utils/logger.d.ts +8 -0
  487. package/dist/utils/logger.d.ts.map +1 -0
  488. package/dist/utils/logger.js +67 -0
  489. package/dist/utils/logger.js.map +1 -0
  490. package/dist/utils/request-timeout.d.ts +5 -0
  491. package/dist/utils/request-timeout.d.ts.map +1 -0
  492. package/dist/utils/request-timeout.js +27 -0
  493. package/dist/utils/request-timeout.js.map +1 -0
  494. package/dist/utils/safe-filename.d.ts +2 -0
  495. package/dist/utils/safe-filename.d.ts.map +1 -0
  496. package/dist/utils/safe-filename.js +24 -0
  497. package/dist/utils/safe-filename.js.map +1 -0
  498. package/dist/utils/scope-hierarchy.d.ts +35 -0
  499. package/dist/utils/scope-hierarchy.d.ts.map +1 -0
  500. package/dist/utils/scope-hierarchy.js +123 -0
  501. package/dist/utils/scope-hierarchy.js.map +1 -0
  502. package/dist/utils/service-initializer.d.ts +12 -0
  503. package/dist/utils/service-initializer.d.ts.map +1 -0
  504. package/dist/utils/service-initializer.js +87 -0
  505. package/dist/utils/service-initializer.js.map +1 -0
  506. package/dist/utils/untrusted-content.d.ts +3 -0
  507. package/dist/utils/untrusted-content.d.ts.map +1 -0
  508. package/dist/utils/untrusted-content.js +20 -0
  509. package/dist/utils/untrusted-content.js.map +1 -0
  510. package/dist/utils/workspace.d.ts +43 -0
  511. package/dist/utils/workspace.d.ts.map +1 -0
  512. package/dist/utils/workspace.js +98 -0
  513. package/dist/utils/workspace.js.map +1 -0
  514. package/package.json +61 -0
@@ -0,0 +1,1040 @@
1
+ import { getGmailService } from '../modules/gmail/index.js';
2
+ import { getAccountManager, validateEmail, resolveEmail } from '../modules/accounts/index.js';
3
+ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
4
+ import { GmailError } from '../modules/gmail/types.js';
5
+ import { AttachmentService } from '../modules/attachments/service.js';
6
+ import { ATTACHMENT_FOLDERS } from '../modules/attachments/types.js';
7
+ import { lstatSync, readFileSync, realpathSync, statSync } from 'fs';
8
+ import path from 'path';
9
+ import { wrapUntrustedContent, wrapUntrustedJsonStrings } from '../utils/untrusted-content.js';
10
+ // Singleton instances
11
+ let gmailService;
12
+ let accountManager;
13
+ let attachmentService;
14
+ /**
15
+ * Initialize required services
16
+ */
17
+ async function initializeServices() {
18
+ if (!gmailService) {
19
+ gmailService = getGmailService();
20
+ await gmailService.initialize();
21
+ }
22
+ if (!accountManager) {
23
+ accountManager = getAccountManager();
24
+ }
25
+ if (!attachmentService) {
26
+ attachmentService = AttachmentService.getInstance();
27
+ }
28
+ }
29
+ async function resolveReplyThreading(email, replyToMessageId) {
30
+ try {
31
+ const originalMessage = await gmailService.getMessage(email, replyToMessageId);
32
+ if (!originalMessage) {
33
+ console.warn(`[gmail-handlers] Could not fetch message ${replyToMessageId} for threading — draft will be unthreaded`);
34
+ return {};
35
+ }
36
+ const result = { threadId: originalMessage.threadId };
37
+ const messageIdHeader = originalMessage.headers?.find((h) => h.name.toLowerCase() === 'message-id');
38
+ if (messageIdHeader) {
39
+ result.inReplyTo = messageIdHeader.value;
40
+ }
41
+ const referencesHeader = originalMessage.headers?.find((h) => h.name.toLowerCase() === 'references');
42
+ const existingRefs = referencesHeader?.value?.split(/\s+/).filter(Boolean) || [];
43
+ if (result.inReplyTo) {
44
+ const allRefs = [...existingRefs, result.inReplyTo];
45
+ // Keep the first and last refs to preserve thread origin and immediate parent
46
+ const MAX_REFS = 50;
47
+ result.references = allRefs.length > MAX_REFS
48
+ ? [allRefs[0], ...allRefs.slice(-(MAX_REFS - 1))]
49
+ : allRefs;
50
+ }
51
+ else if (existingRefs.length > 0) {
52
+ result.references = existingRefs;
53
+ }
54
+ return result;
55
+ }
56
+ catch (error) {
57
+ console.warn(`[gmail-handlers] Failed to resolve threading for ${replyToMessageId}:`, error instanceof Error ? error.message : error);
58
+ return {};
59
+ }
60
+ }
61
+ const MIME_TYPES = {
62
+ '.pdf': 'application/pdf',
63
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
64
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
65
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
66
+ '.doc': 'application/msword',
67
+ '.xls': 'application/vnd.ms-excel',
68
+ '.ppt': 'application/vnd.ms-powerpoint',
69
+ '.csv': 'text/csv',
70
+ '.txt': 'text/plain',
71
+ '.html': 'text/html',
72
+ '.json': 'application/json',
73
+ '.png': 'image/png',
74
+ '.jpg': 'image/jpeg',
75
+ '.jpeg': 'image/jpeg',
76
+ '.gif': 'image/gif',
77
+ '.svg': 'image/svg+xml',
78
+ '.zip': 'application/zip',
79
+ };
80
+ function isPathInsideDirectory(candidatePath, rootPath) {
81
+ return candidatePath === rootPath || candidatePath.startsWith(`${rootPath}${path.sep}`);
82
+ }
83
+ function getAttachmentWorkspaceRoot() {
84
+ const workspaceBase = process.env.MCP_WORKSPACE_PATH || process.env.WORKSPACE_BASE_PATH;
85
+ if (!workspaceBase) {
86
+ throw new McpError(ErrorCode.InvalidParams, 'Attachment paths require MCP_WORKSPACE_PATH to be set to the workspace root.');
87
+ }
88
+ const rootPath = path.resolve(workspaceBase);
89
+ const rootStats = lstatSync(rootPath);
90
+ if (rootStats.isSymbolicLink() || !rootStats.isDirectory()) {
91
+ throw new McpError(ErrorCode.InvalidParams, 'MCP_WORKSPACE_PATH must point to a real workspace directory, not a symlink or file.');
92
+ }
93
+ return realpathSync.native(rootPath);
94
+ }
95
+ /** @internal Exported for tests. */
96
+ export function resolveAttachmentFromPath(filePath) {
97
+ const rootRealpath = getAttachmentWorkspaceRoot();
98
+ const candidatePath = path.resolve(filePath);
99
+ const candidateStats = lstatSync(candidatePath);
100
+ if (candidateStats.isSymbolicLink()) {
101
+ throw new McpError(ErrorCode.InvalidParams, 'Attachment path must not be a symbolic link.');
102
+ }
103
+ const candidateRealpath = realpathSync.native(candidatePath);
104
+ if (!isPathInsideDirectory(candidateRealpath, rootRealpath)) {
105
+ throw new McpError(ErrorCode.InvalidParams, `Attachment path must be within the workspace directory. Got: ${filePath}`);
106
+ }
107
+ const stats = statSync(candidateRealpath);
108
+ const content = readFileSync(candidateRealpath);
109
+ const ext = path.extname(candidateRealpath).toLowerCase();
110
+ return {
111
+ content: content.toString('base64'),
112
+ name: path.basename(candidateRealpath),
113
+ mimeType: MIME_TYPES[ext] || 'application/octet-stream',
114
+ size: stats.size,
115
+ };
116
+ }
117
+ function processOutgoingAttachments(attachments) {
118
+ return attachments?.map(attachment => {
119
+ if (attachment.path && !attachment.content) {
120
+ const resolved = resolveAttachmentFromPath(attachment.path);
121
+ return {
122
+ id: attachment.id || resolved.name,
123
+ name: attachment.name || resolved.name,
124
+ mimeType: attachment.mimeType || resolved.mimeType,
125
+ size: attachment.size || resolved.size,
126
+ content: resolved.content,
127
+ };
128
+ }
129
+ if (!attachment.content) {
130
+ throw new McpError(ErrorCode.InvalidParams, `Attachment requires either "content" (base64) or "path" (local file): ${attachment.name || 'unnamed'}`);
131
+ }
132
+ if (!attachment.name) {
133
+ throw new McpError(ErrorCode.InvalidParams, 'Attachment with "content" (base64) also requires "name" (filename).');
134
+ }
135
+ const contentBytes = Buffer.from(attachment.content, 'base64');
136
+ return {
137
+ id: attachment.id || attachment.name,
138
+ name: attachment.name,
139
+ mimeType: attachment.mimeType || 'application/octet-stream',
140
+ size: attachment.size || contentBytes.length,
141
+ content: attachment.content,
142
+ };
143
+ });
144
+ }
145
+ function readAliasedString(args, canonicalKey, legacyKey) {
146
+ const value = args[canonicalKey] ?? args[legacyKey];
147
+ return typeof value === 'string' ? value : undefined;
148
+ }
149
+ function readAliasedNumber(args, canonicalKey, legacyKey) {
150
+ const value = args[canonicalKey] ?? args[legacyKey];
151
+ return typeof value === 'number' ? value : undefined;
152
+ }
153
+ function readAliasedBoolean(args, canonicalKey, legacyKey) {
154
+ const value = args[canonicalKey] ?? args[legacyKey];
155
+ return typeof value === 'boolean' ? value : undefined;
156
+ }
157
+ function readAliasedStringArray(args, canonicalKey, legacyKey) {
158
+ const value = args[canonicalKey] ?? args[legacyKey];
159
+ return Array.isArray(value) && value.every(item => typeof item === 'string')
160
+ ? value
161
+ : undefined;
162
+ }
163
+ /** @internal Exported for testing only. */
164
+ export function formatEmailsAsText(result) {
165
+ const { emails, resultSummary } = result;
166
+ if (emails.length === 0) {
167
+ return 'No emails found matching your search criteria.';
168
+ }
169
+ const lines = [];
170
+ lines.push(`Found ${resultSummary.returned} email${resultSummary.returned !== 1 ? 's' : ''}${resultSummary.hasMore ? ` (more available)` : ''}:\n`);
171
+ emails.forEach((email, i) => {
172
+ const isUnread = email.labelIds?.includes('UNREAD');
173
+ const labels = email.labelIds?.filter(l => l !== 'UNREAD' && l !== 'INBOX').join(', ') || '';
174
+ const attachmentNote = email.hasAttachment ? ' [has attachments]' : '';
175
+ lines.push(`${i + 1}. **${email.subject || '(no subject)'}**${isUnread ? ' [UNREAD]' : ''}${attachmentNote}`);
176
+ lines.push(` From: ${email.from}`);
177
+ lines.push(` Date: ${email.date}`);
178
+ if (email.snippet) {
179
+ lines.push(` Preview: "${email.snippet.substring(0, 150)}${email.snippet.length > 150 ? '...' : ''}"`);
180
+ }
181
+ if (email.attachments && email.attachments.length > 0) {
182
+ const attachmentList = email.attachments.map(a => a.name).join(', ');
183
+ lines.push(` Attachments: ${attachmentList}`);
184
+ }
185
+ lines.push(` [id: ${email.id}, thread: ${email.threadId}${labels ? `, labels: ${labels}` : ''}]`);
186
+ lines.push('');
187
+ });
188
+ if (result.nextPageToken) {
189
+ lines.push(`More results available. Use pageToken: "${result.nextPageToken}" to continue.`);
190
+ }
191
+ return wrapUntrustedContent(lines.join('\n'), 'google-workspace:gmail:search');
192
+ }
193
+ const ANSI_ESCAPE_SEQUENCE_PATTERN = /\x1b\[[0-?]*[ -/]*[@-~]/g;
194
+ const HTML_TAG_PATTERN = /<[^>]*>/g;
195
+ function truncateText(value, maxChars) {
196
+ if (value.length <= maxChars)
197
+ return value;
198
+ return `${value.slice(0, Math.max(0, maxChars - 1))}…`;
199
+ }
200
+ function sanitizeViewSummaryPart(value) {
201
+ return value
202
+ .replace(ANSI_ESCAPE_SEQUENCE_PATTERN, '')
203
+ .replace(HTML_TAG_PATTERN, '')
204
+ .trim();
205
+ }
206
+ function normalizeDraftData(data) {
207
+ if (!data) {
208
+ return undefined;
209
+ }
210
+ return {
211
+ to: data.to,
212
+ subject: data.subject,
213
+ body: data.body,
214
+ cc: data.cc,
215
+ bcc: data.bcc,
216
+ isHtml: data.is_html ?? data.isHtml,
217
+ attachments: data.attachments,
218
+ replyToMessageId: data.reply_to_message_id ?? data.replyToMessageId,
219
+ threadId: data.thread_id ?? data.threadId,
220
+ inReplyTo: data.in_reply_to ?? data.inReplyTo,
221
+ references: data.references,
222
+ };
223
+ }
224
+ export async function handleComposeWorkspaceEmail(params) {
225
+ await initializeServices();
226
+ const email = await resolveEmail(params);
227
+ const to = Array.isArray(params.to) ? params.to : [];
228
+ const cc = Array.isArray(params.cc) ? params.cc : [];
229
+ const bcc = Array.isArray(params.bcc) ? params.bcc : [];
230
+ const subject = typeof params.subject === 'string' ? params.subject : '';
231
+ const body = typeof params.body === 'string' ? params.body : '';
232
+ const recipientSummary = to.length > 0 ? to.join(', ') : '(no recipients)';
233
+ const fallbackSubject = truncateText(subject, 256);
234
+ const fallbackBody = truncateText(body, 5_000);
235
+ const viewSummaryRecipient = truncateText(sanitizeViewSummaryPart(recipientSummary), 120);
236
+ const viewSummarySubject = truncateText(sanitizeViewSummaryPart(subject), 120);
237
+ const viewSummary = truncateText(`Email draft to ${viewSummaryRecipient || '(no recipients)'} — subject "${viewSummarySubject}".`, 280);
238
+ const draftData = { to, cc, bcc, subject, body, email };
239
+ return {
240
+ text: `Drafting email to ${recipientSummary} with subject "${subject}"\n\n${JSON.stringify(draftData)}\n\n[View: ui://google-workspace/compose-email]`,
241
+ _meta: {
242
+ ui: {
243
+ resourceUri: 'ui://google-workspace/compose-email',
244
+ presentation: 'primary',
245
+ viewSummary,
246
+ viewRoleLabel: 'Editable email draft',
247
+ structuredFallback: {
248
+ kind: 'email-draft',
249
+ payload: { to, cc, bcc, subject: fallbackSubject, body: fallbackBody }
250
+ }
251
+ }
252
+ },
253
+ structuredContent: draftData
254
+ };
255
+ }
256
+ export async function handleSearchWorkspaceEmails(params) {
257
+ await initializeServices();
258
+ // Resolve email - uses instance account if not provided, validates if provided
259
+ const email = await resolveEmail(params);
260
+ const rawParams = params;
261
+ const hasAttachment = readAliasedBoolean(rawParams, 'has_attachment', 'hasAttachment');
262
+ const isUnread = readAliasedBoolean(rawParams, 'is_unread', 'isUnread');
263
+ const pageToken = readAliasedString(rawParams, 'page_token', 'pageToken');
264
+ const includeBody = readAliasedBoolean(rawParams, 'include_body', 'includeBody');
265
+ const messageIds = readAliasedStringArray(rawParams, 'message_ids', 'messageIds');
266
+ // Merge flat parameters with legacy nested parameters (flat takes precedence)
267
+ // This provides backwards compatibility while supporting the new flat schema
268
+ const mergedSearch = {
269
+ // Start with legacy nested search params
270
+ ...params.search,
271
+ // Flat params override nested (preferred API)
272
+ ...(params.from !== undefined && { from: params.from }),
273
+ ...(params.to !== undefined && { to: params.to }),
274
+ ...(params.subject !== undefined && { subject: params.subject }),
275
+ ...(params.after !== undefined && { after: params.after }),
276
+ ...(params.before !== undefined && { before: params.before }),
277
+ ...(hasAttachment !== undefined && { hasAttachment }),
278
+ ...(isUnread !== undefined && { isUnread }),
279
+ ...(params.labels !== undefined && { labels: params.labels }),
280
+ };
281
+ // Handle query param: maps to search.content, AND-ed with other filters
282
+ // Also accept 'q' as alias for 'query' (common LLM pattern)
283
+ const queryParam = params.query || params.q;
284
+ if (queryParam) {
285
+ if (mergedSearch.content) {
286
+ // AND the query with existing content
287
+ mergedSearch.content = `(${mergedSearch.content}) (${queryParam})`;
288
+ }
289
+ else {
290
+ mergedSearch.content = queryParam;
291
+ }
292
+ }
293
+ // Merge options (snake_case canonical, flat params take precedence)
294
+ const mergedOptions = {
295
+ ...params.options,
296
+ ...(params.max_results !== undefined && { maxResults: params.max_results }),
297
+ ...(pageToken !== undefined && { pageToken }),
298
+ ...(includeBody !== undefined && { includeBody }),
299
+ };
300
+ // Also accept backwards-compatible aliases: maxResults (camelCase), limit
301
+ const unknownParams = params;
302
+ if ('maxResults' in unknownParams && mergedOptions.maxResults === undefined) {
303
+ mergedOptions.maxResults = unknownParams.maxResults;
304
+ }
305
+ if ('limit' in unknownParams && mergedOptions.maxResults === undefined) {
306
+ mergedOptions.maxResults = unknownParams.limit;
307
+ }
308
+ const search = mergedSearch;
309
+ const options = mergedOptions;
310
+ // Normalize search.from - if it's a partial name (no @), convert to content query
311
+ // This helps when LLMs pass names like "Solena" instead of full email addresses
312
+ let normalizedSearch = { ...search };
313
+ if (search.from && !search.content) {
314
+ const fromValues = Array.isArray(search.from) ? search.from : [search.from];
315
+ const hasPartialName = fromValues.some(f => !f.includes('@'));
316
+ if (hasPartialName) {
317
+ // Convert partial names to content query for better matching
318
+ // Gmail's from: operator works with partial matches, but content search is more flexible
319
+ const fromQuery = fromValues.map(f => `from:${f}`).join(' OR ');
320
+ normalizedSearch = {
321
+ ...search,
322
+ from: undefined,
323
+ content: search.content ? `(${search.content}) AND (${fromQuery})` : fromQuery
324
+ };
325
+ }
326
+ }
327
+ const returnJson = readAliasedBoolean(rawParams, 'return_json', 'returnJson') ?? false;
328
+ return accountManager.withTokenRenewal(email, async () => {
329
+ try {
330
+ const result = await gmailService.getEmails({ email, search: normalizedSearch, options, messageIds });
331
+ // Return formatted text by default, JSON only when explicitly requested
332
+ if (returnJson) {
333
+ return wrapUntrustedJsonStrings(result, 'google-workspace:gmail:search');
334
+ }
335
+ return formatEmailsAsText(result);
336
+ }
337
+ catch (error) {
338
+ throw new McpError(ErrorCode.InternalError, `Failed to search emails: ${error instanceof Error ? error.message : 'Unknown error'}`);
339
+ }
340
+ });
341
+ }
342
+ // Format thread as human-readable text
343
+ const DEFAULT_FULL_BODY_TAIL = 2;
344
+ export function formatThreadAsText(result, offset = 0, includeFullBodies = false) {
345
+ const { threadId, messagesCount, hasMore, nextOffset, messages } = result;
346
+ if (messages.length === 0) {
347
+ if (offset > 0) {
348
+ return wrapUntrustedContent(`Thread ${threadId} has no more messages beyond offset ${offset} (${messagesCount} total).`, `google-workspace:gmail:thread/${threadId}`);
349
+ }
350
+ return wrapUntrustedContent(`Thread ${threadId} is empty.`, `google-workspace:gmail:thread/${threadId}`);
351
+ }
352
+ // Get subject from first message
353
+ const subject = messages[0]?.subject || '(no subject)';
354
+ const lines = [];
355
+ lines.push(`**Thread: ${subject}**`);
356
+ lines.push(`[threadId: ${threadId}, ${messagesCount} message${messagesCount !== 1 ? 's' : ''}]\n`);
357
+ const fullBodyThreshold = includeFullBodies ? -Infinity : messages.length - DEFAULT_FULL_BODY_TAIL;
358
+ let abbreviatedCount = 0;
359
+ messages.forEach((msg, i) => {
360
+ lines.push(`--- Message ${offset + i + 1} of ${messagesCount} ---`);
361
+ lines.push(`From: ${msg.from}`);
362
+ lines.push(`To: ${msg.to.join(', ')}`);
363
+ lines.push(`Date: ${msg.date}`);
364
+ lines.push(`[id: ${msg.id}]`);
365
+ const showFullBody = i >= fullBodyThreshold;
366
+ if (showFullBody && msg.body?.text) {
367
+ const bodyText = msg.body.text.length > 2000
368
+ ? msg.body.text.substring(0, 2000) + '\n...[truncated]'
369
+ : msg.body.text;
370
+ lines.push(`\n${bodyText}`);
371
+ }
372
+ else if (msg.snippet) {
373
+ lines.push(`\nPreview: "${msg.snippet}"`);
374
+ if (!showFullBody)
375
+ abbreviatedCount += 1;
376
+ }
377
+ if (msg.attachments && msg.attachments.length > 0) {
378
+ const attachmentList = msg.attachments.map(a => {
379
+ const sizeStr = a.size >= 1024 * 1024
380
+ ? `${(a.size / (1024 * 1024)).toFixed(1)} MB`
381
+ : a.size >= 1024
382
+ ? `${(a.size / 1024).toFixed(0)} KB`
383
+ : `${a.size} B`;
384
+ return `${a.filename} (${sizeStr})`;
385
+ }).join(', ');
386
+ lines.push(` 📎 Attachments: ${attachmentList}`);
387
+ }
388
+ lines.push('');
389
+ });
390
+ if (abbreviatedCount > 0) {
391
+ lines.push(`(${abbreviatedCount} earlier message${abbreviatedCount === 1 ? '' : 's'} abbreviated to preview only. Pass include_full_bodies: true to fetch full content.)`);
392
+ }
393
+ if (hasMore && nextOffset !== undefined) {
394
+ lines.push(`More messages available. Use offset: ${nextOffset} to continue.`);
395
+ }
396
+ return wrapUntrustedContent(lines.join('\n'), `google-workspace:gmail:thread/${threadId}`);
397
+ }
398
+ export async function handleGetWorkspaceEmailThread(params) {
399
+ await initializeServices();
400
+ const rawParams = params;
401
+ const threadId = readAliasedString(rawParams, 'thread_id', 'threadId');
402
+ const maxMessages = readAliasedNumber(rawParams, 'max_messages', 'maxMessages') ?? 50;
403
+ const offset = typeof params.offset === 'number' ? params.offset : 0;
404
+ const includeBody = readAliasedBoolean(rawParams, 'include_body', 'includeBody') ?? true;
405
+ const includeFullBodies = readAliasedBoolean(rawParams, 'include_full_bodies', 'includeFullBodies') ?? false;
406
+ const returnJson = readAliasedBoolean(rawParams, 'return_json', 'returnJson') ?? false;
407
+ // Resolve email - uses instance account if not provided, validates if provided
408
+ const email = await resolveEmail(params);
409
+ if (!threadId) {
410
+ throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter: "thread_id" (from search results or a message). ' +
411
+ 'Example: { "email": "user@example.com", "thread_id": "thread123" }');
412
+ }
413
+ return accountManager.withTokenRenewal(email, async () => {
414
+ try {
415
+ const result = await gmailService.getThread(email, threadId, { maxMessages, offset, includeBody });
416
+ if (returnJson) {
417
+ // JSON path: when full bodies aren't requested, strip body content from
418
+ // every message except the last 2 so long threads stay token-cheap.
419
+ // Snippet field is preserved so callers can still see what was elided.
420
+ if (includeBody && !includeFullBodies && result.messages.length > DEFAULT_FULL_BODY_TAIL) {
421
+ const tailStart = result.messages.length - DEFAULT_FULL_BODY_TAIL;
422
+ return wrapUntrustedJsonStrings({
423
+ ...result,
424
+ bodies_abbreviated: tailStart,
425
+ messages: result.messages.map((m, i) => i < tailStart ? { ...m, body: undefined } : m),
426
+ }, `google-workspace:gmail:thread/${threadId}`);
427
+ }
428
+ return wrapUntrustedJsonStrings(result, `google-workspace:gmail:thread/${threadId}`);
429
+ }
430
+ return formatThreadAsText(result, offset, includeFullBodies);
431
+ }
432
+ catch (error) {
433
+ throw new McpError(ErrorCode.InternalError, `Failed to get thread: ${error instanceof Error ? error.message : 'Unknown error'}`);
434
+ }
435
+ });
436
+ }
437
+ export async function handleSendWorkspaceEmail(params) {
438
+ await initializeServices();
439
+ const { to, subject, body, cc, bcc, attachments } = params;
440
+ const rawParams = params;
441
+ const isHtml = readAliasedBoolean(rawParams, 'is_html', 'isHtml');
442
+ const replyToMessageId = readAliasedString(rawParams, 'reply_to_message_id', 'replyToMessageId');
443
+ // Resolve email - uses instance account if not provided, validates if provided
444
+ const email = await resolveEmail(params);
445
+ // Catch common parameter mistakes
446
+ const unknownParams = rawParams;
447
+ // Catch 'recipient'/'recipients' instead of 'to'
448
+ if ('recipient' in unknownParams || 'recipients' in unknownParams) {
449
+ const passedRecipient = unknownParams.recipient || unknownParams.recipients;
450
+ throw new McpError(ErrorCode.InvalidParams, `Invalid parameter: '${unknownParams.recipient ? 'recipient' : 'recipients'}' is not supported. Use 'to' instead. ` +
451
+ `Example: { "email": "sender@example.com", "to": ${JSON.stringify(Array.isArray(passedRecipient) ? passedRecipient : [passedRecipient])}, "subject": "...", "body": "..." }`);
452
+ }
453
+ // Catch 'message'/'content'/'text' instead of 'body'
454
+ if ('message' in unknownParams || 'content' in unknownParams || 'text' in unknownParams) {
455
+ const paramName = 'message' in unknownParams ? 'message' : ('content' in unknownParams ? 'content' : 'text');
456
+ throw new McpError(ErrorCode.InvalidParams, `Invalid parameter: '${paramName}' is not supported. Use 'body' instead. ` +
457
+ `Example: { "email": "sender@example.com", "to": ["recipient@example.com"], "subject": "...", "body": "Your message here" }`);
458
+ }
459
+ // Catch 'html' instead of 'is_html'
460
+ if ('html' in unknownParams) {
461
+ throw new McpError(ErrorCode.InvalidParams, `Invalid parameter: 'html' is not supported. Use 'is_html' (boolean) instead. ` +
462
+ `Example: { "email": "...", "to": [...], "subject": "...", "body": "<html>...</html>", "is_html": true }`);
463
+ }
464
+ // Catch 'from' instead of 'email'
465
+ if ('from' in unknownParams) {
466
+ throw new McpError(ErrorCode.InvalidParams, `Invalid parameter: 'from' is not supported. Use 'email' for the sender address. ` +
467
+ `Example: { "email": "${unknownParams.from}", "to": [...], "subject": "...", "body": "..." }`);
468
+ }
469
+ if (!to || !Array.isArray(to) || to.length === 0) {
470
+ throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter: "to" (array of recipient email addresses). ' +
471
+ 'Example: { "email": "sender@example.com", "to": ["recipient@example.com"], "subject": "Hello", "body": "Message content" }');
472
+ }
473
+ if (!subject) {
474
+ throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter: "subject" (email subject line). ' +
475
+ 'Example: { "email": "sender@example.com", "to": ["recipient@example.com"], "subject": "Meeting Tomorrow", "body": "..." }');
476
+ }
477
+ if (!body) {
478
+ throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter: "body" (email content). ' +
479
+ 'Example: { "email": "...", "to": [...], "subject": "...", "body": "Your message here" }. ' +
480
+ 'For HTML emails, set "is_html": true');
481
+ }
482
+ to.forEach(validateEmail);
483
+ if (cc)
484
+ cc.forEach(validateEmail);
485
+ if (bcc)
486
+ bcc.forEach(validateEmail);
487
+ return accountManager.withTokenRenewal(email, async () => {
488
+ try {
489
+ const threading = replyToMessageId
490
+ ? await resolveReplyThreading(email, replyToMessageId)
491
+ : {};
492
+ const emailParams = {
493
+ email,
494
+ to,
495
+ subject,
496
+ body,
497
+ cc,
498
+ bcc,
499
+ isHtml,
500
+ threadId: threading.threadId,
501
+ inReplyTo: threading.inReplyTo,
502
+ references: threading.references,
503
+ attachments: processOutgoingAttachments(attachments)
504
+ };
505
+ return await gmailService.sendEmail(emailParams);
506
+ }
507
+ catch (error) {
508
+ const details = error instanceof GmailError && error.details
509
+ ? `${error.message}: ${error.details}`
510
+ : error instanceof Error
511
+ ? error.message
512
+ : 'Unknown error';
513
+ throw new McpError(ErrorCode.InternalError, `Failed to send email: ${details}`);
514
+ }
515
+ });
516
+ }
517
+ export async function handleGetWorkspaceGmailSettings(params) {
518
+ await initializeServices();
519
+ // Resolve email - uses instance account if not provided, validates if provided
520
+ const email = await resolveEmail(params);
521
+ return accountManager.withTokenRenewal(email, async () => {
522
+ try {
523
+ return await gmailService.getWorkspaceGmailSettings({ email });
524
+ }
525
+ catch (error) {
526
+ throw new McpError(ErrorCode.InternalError, `Failed to get Gmail settings: ${error instanceof Error ? error.message : 'Unknown error'}`);
527
+ }
528
+ });
529
+ }
530
+ export async function handleManageWorkspaceDraft(params) {
531
+ await initializeServices();
532
+ const rawParams = params;
533
+ const action = params.action;
534
+ const draftId = readAliasedString(rawParams, 'draft_id', 'draftId');
535
+ const data = normalizeDraftData(params.data);
536
+ // Resolve email - uses instance account if not provided, validates if provided
537
+ const email = await resolveEmail(params);
538
+ if (!action) {
539
+ throw new McpError(ErrorCode.InvalidParams, 'Action is required');
540
+ }
541
+ return accountManager.withTokenRenewal(email, async () => {
542
+ try {
543
+ // Resolve reply threading headers if replyToMessageId is provided
544
+ const threading = data?.replyToMessageId
545
+ ? await resolveReplyThreading(email, data.replyToMessageId)
546
+ : {};
547
+ switch (action) {
548
+ case 'create':
549
+ if (!data) {
550
+ throw new McpError(ErrorCode.InvalidParams, 'Draft data is required for create action');
551
+ }
552
+ if (data.to)
553
+ data.to.forEach(validateEmail);
554
+ if (data.cc)
555
+ data.cc.forEach(validateEmail);
556
+ if (data.bcc)
557
+ data.bcc.forEach(validateEmail);
558
+ {
559
+ // Destructure replyToMessageId out so it doesn't leak to the service
560
+ const { replyToMessageId: _, ...draftData } = data;
561
+ return await gmailService.manageDraft({
562
+ email,
563
+ action: 'create',
564
+ data: {
565
+ ...draftData,
566
+ threadId: data.threadId ?? threading.threadId,
567
+ inReplyTo: data.inReplyTo ?? threading.inReplyTo,
568
+ references: data.references ?? threading.references,
569
+ attachments: processOutgoingAttachments(data.attachments)
570
+ }
571
+ });
572
+ }
573
+ case 'read':
574
+ return await gmailService.manageDraft({
575
+ email,
576
+ action: 'read',
577
+ draftId
578
+ });
579
+ case 'update':
580
+ if (!draftId || !data) {
581
+ throw new McpError(ErrorCode.InvalidParams, 'Draft ID and data are required for update action');
582
+ }
583
+ if (data.to)
584
+ data.to.forEach(validateEmail);
585
+ if (data.cc)
586
+ data.cc.forEach(validateEmail);
587
+ if (data.bcc)
588
+ data.bcc.forEach(validateEmail);
589
+ {
590
+ const { replyToMessageId: _, ...draftData } = data;
591
+ return await gmailService.manageDraft({
592
+ email,
593
+ action: 'update',
594
+ draftId,
595
+ data: {
596
+ ...draftData,
597
+ threadId: data.threadId ?? threading.threadId,
598
+ inReplyTo: data.inReplyTo ?? threading.inReplyTo,
599
+ references: data.references ?? threading.references,
600
+ attachments: processOutgoingAttachments(data.attachments)
601
+ }
602
+ });
603
+ }
604
+ case 'delete':
605
+ if (!draftId) {
606
+ throw new McpError(ErrorCode.InvalidParams, 'Draft ID is required for delete action');
607
+ }
608
+ return await gmailService.manageDraft({
609
+ email,
610
+ action: 'delete',
611
+ draftId
612
+ });
613
+ case 'send':
614
+ if (!draftId) {
615
+ throw new McpError(ErrorCode.InvalidParams, 'Draft ID is required for send action');
616
+ }
617
+ return await gmailService.manageDraft({
618
+ email,
619
+ action: 'send',
620
+ draftId
621
+ });
622
+ default:
623
+ throw new McpError(ErrorCode.InvalidParams, 'Invalid action. Supported actions are: create, read, update, delete, send');
624
+ }
625
+ }
626
+ catch (error) {
627
+ throw new McpError(ErrorCode.InternalError, `Failed to manage draft: ${error instanceof Error ? error.message : 'Unknown error'}`);
628
+ }
629
+ });
630
+ }
631
+ export async function handleManageWorkspaceLabel(params) {
632
+ await initializeServices();
633
+ const rawParams = params;
634
+ // Resolve email - uses instance account if not provided, validates if provided
635
+ const email = await resolveEmail(params);
636
+ const labelId = readAliasedString(rawParams, 'label_id', 'labelId');
637
+ const rawData = (rawParams.data ?? {});
638
+ const messageListVisibility = readAliasedString(rawParams, 'message_list_visibility', 'messageListVisibility')
639
+ ?? (typeof rawData.messageListVisibility === 'string' ? rawData.messageListVisibility : undefined);
640
+ const labelListVisibility = readAliasedString(rawParams, 'label_list_visibility', 'labelListVisibility')
641
+ ?? (typeof rawData.labelListVisibility === 'string' ? rawData.labelListVisibility : undefined);
642
+ const data = {
643
+ ...(typeof rawData.name === 'string' ? { name: rawData.name } : {}),
644
+ ...(messageListVisibility ? { messageListVisibility: messageListVisibility } : {}),
645
+ ...(labelListVisibility ? { labelListVisibility: labelListVisibility } : {}),
646
+ ...(typeof rawData.color === 'object' && rawData.color !== null ? { color: rawData.color } : {}),
647
+ };
648
+ return accountManager.withTokenRenewal(email, async () => {
649
+ try {
650
+ return await gmailService.manageLabel({
651
+ action: params.action,
652
+ email,
653
+ ...(labelId ? { labelId } : {}),
654
+ ...(Object.keys(data).length > 0 ? { data } : {}),
655
+ });
656
+ }
657
+ catch (error) {
658
+ throw new McpError(ErrorCode.InternalError, `Failed to manage label: ${error instanceof Error ? error.message : 'Unknown error'}`);
659
+ }
660
+ });
661
+ }
662
+ export async function handleManageWorkspaceLabelAssignment(params) {
663
+ await initializeServices();
664
+ const rawParams = params;
665
+ // Resolve email - uses instance account if not provided, validates if provided
666
+ const email = await resolveEmail(params);
667
+ const messageId = readAliasedString(rawParams, 'message_id', 'messageId');
668
+ const labelIds = readAliasedStringArray(rawParams, 'label_ids', 'labelIds');
669
+ return accountManager.withTokenRenewal(email, async () => {
670
+ try {
671
+ await gmailService.manageLabelAssignment({
672
+ action: params.action,
673
+ email,
674
+ messageId: messageId,
675
+ labelIds: labelIds,
676
+ });
677
+ return {
678
+ content: [{
679
+ type: 'text',
680
+ text: JSON.stringify({ success: true })
681
+ }]
682
+ };
683
+ }
684
+ catch (error) {
685
+ throw new McpError(ErrorCode.InternalError, `Failed to manage label assignment: ${error instanceof Error ? error.message : 'Unknown error'}`);
686
+ }
687
+ });
688
+ }
689
+ export async function handleManageWorkspaceAttachment(params) {
690
+ await initializeServices();
691
+ const rawParams = params;
692
+ const { action, source, filename, content } = params;
693
+ const messageId = readAliasedString(rawParams, 'message_id', 'messageId');
694
+ const mimeType = readAliasedString(rawParams, 'mime_type', 'mimeType');
695
+ // Resolve email - uses instance account if not provided, validates if provided
696
+ const email = await resolveEmail(params);
697
+ // Validate all required parameters
698
+ if (!action || !source || !messageId || !filename) {
699
+ throw new McpError(ErrorCode.InvalidRequest, 'Invalid attachment management parameters. Required: action, source, message_id, filename');
700
+ }
701
+ return accountManager.withTokenRenewal(email, async () => {
702
+ try {
703
+ // Get shared attachment service instance
704
+ if (!attachmentService) {
705
+ attachmentService = AttachmentService.getInstance();
706
+ await attachmentService.initialize(email);
707
+ }
708
+ // Determine parent folder based on source
709
+ const parentFolder = source === 'email' ?
710
+ ATTACHMENT_FOLDERS.EMAIL :
711
+ ATTACHMENT_FOLDERS.CALENDAR;
712
+ switch (action) {
713
+ case 'download': {
714
+ // Check local storage first (handles files uploaded via upload_workspace_attachment)
715
+ const localResult = await attachmentService.findAttachmentByFilename(email, filename, parentFolder);
716
+ if (localResult.success) {
717
+ return {
718
+ success: true,
719
+ attachment: localResult.attachment
720
+ };
721
+ }
722
+ // Fall back to Gmail API for real Gmail attachments
723
+ const gmailAttachment = await gmailService.getAttachment(email, messageId, filename);
724
+ if (!gmailAttachment || !gmailAttachment.content) {
725
+ throw new McpError(ErrorCode.InvalidRequest, 'Attachment not found or content missing');
726
+ }
727
+ // Process and save the attachment locally
728
+ const result = await attachmentService.processAttachment(email, {
729
+ content: gmailAttachment.content,
730
+ metadata: {
731
+ name: gmailAttachment.name || `attachment_${Date.now()}`,
732
+ mimeType: gmailAttachment.mimeType || 'application/octet-stream',
733
+ size: gmailAttachment.size || 0
734
+ }
735
+ }, parentFolder);
736
+ if (!result.success) {
737
+ throw new McpError(ErrorCode.InternalError, `Failed to save attachment: ${result.error}`);
738
+ }
739
+ return {
740
+ success: true,
741
+ attachment: result.attachment
742
+ };
743
+ }
744
+ case 'upload': {
745
+ if (!content) {
746
+ throw new McpError(ErrorCode.InvalidParams, 'File content is required for upload');
747
+ }
748
+ // Process attachment using provided filename and mimeType
749
+ const result = await attachmentService.processAttachment(email, {
750
+ content,
751
+ metadata: {
752
+ name: filename,
753
+ mimeType: mimeType || 'application/octet-stream',
754
+ }
755
+ }, parentFolder);
756
+ if (!result.success) {
757
+ throw new McpError(ErrorCode.InternalError, `Failed to upload attachment: ${result.error}`);
758
+ }
759
+ return {
760
+ success: true,
761
+ attachment: result.attachment
762
+ };
763
+ }
764
+ case 'delete': {
765
+ // Delete attachment by scanning local storage for matching filename
766
+ // The attachment must have been previously downloaded to local storage
767
+ const result = await attachmentService.deleteAttachmentByFilename(email, filename, parentFolder);
768
+ if (!result.success) {
769
+ throw new McpError(ErrorCode.InvalidRequest, result.error || 'Failed to delete attachment');
770
+ }
771
+ return {
772
+ success: true,
773
+ attachment: result.attachment
774
+ };
775
+ }
776
+ default:
777
+ throw new McpError(ErrorCode.InvalidParams, 'Invalid action. Supported actions are: download, upload, delete');
778
+ }
779
+ }
780
+ catch (error) {
781
+ if (error instanceof McpError) {
782
+ throw error;
783
+ }
784
+ throw new McpError(ErrorCode.InternalError, `Failed to manage attachment: ${error instanceof Error ? error.message : 'Unknown error'}`);
785
+ }
786
+ });
787
+ }
788
+ export async function handleManageWorkspaceLabelFilter(params) {
789
+ await initializeServices();
790
+ const rawParams = params;
791
+ // Resolve email - uses instance account if not provided, validates if provided
792
+ const email = await resolveEmail(params);
793
+ const filterId = readAliasedString(rawParams, 'filter_id', 'filterId');
794
+ const labelId = readAliasedString(rawParams, 'label_id', 'labelId');
795
+ const data = typeof rawParams.data === 'object' && rawParams.data !== null
796
+ ? rawParams.data
797
+ : undefined;
798
+ return accountManager.withTokenRenewal(email, async () => {
799
+ try {
800
+ return await gmailService.manageLabelFilter({
801
+ action: params.action,
802
+ email,
803
+ ...(filterId ? { filterId } : {}),
804
+ ...(labelId ? { labelId } : {}),
805
+ ...(data ? { data } : {}),
806
+ });
807
+ }
808
+ catch (error) {
809
+ throw new McpError(ErrorCode.InternalError, `Failed to manage label filter: ${error instanceof Error ? error.message : 'Unknown error'}`);
810
+ }
811
+ });
812
+ }
813
+ // --- Individual Draft Operation Handlers ---
814
+ // These delegate to handleManageWorkspaceDraft with the appropriate action.
815
+ export async function handleListWorkspaceDrafts(params) {
816
+ return handleManageWorkspaceDraft({ ...params, action: 'read' });
817
+ }
818
+ export async function handleGetWorkspaceDraft(params) {
819
+ return handleManageWorkspaceDraft({ ...params, action: 'read' });
820
+ }
821
+ export async function handleCreateWorkspaceDraft(params) {
822
+ const { email, ...data } = params;
823
+ return handleManageWorkspaceDraft({ email: email, action: 'create', data: data });
824
+ }
825
+ export async function handleUpdateWorkspaceDraft(params) {
826
+ const email = params.email;
827
+ const draftId = readAliasedString(params, 'draft_id', 'draftId');
828
+ const { draft_id: _draftIdSnake, draftId: _draftIdCamel, ...data } = params;
829
+ return handleManageWorkspaceDraft({ email, action: 'update', draftId, data: data });
830
+ }
831
+ export async function handleDeleteWorkspaceDraft(params) {
832
+ const draftId = readAliasedString(params, 'draft_id', 'draftId');
833
+ return handleManageWorkspaceDraft({ ...params, draftId, action: 'delete' });
834
+ }
835
+ export async function handleSendWorkspaceDraft(params) {
836
+ const draftId = readAliasedString(params, 'draft_id', 'draftId');
837
+ return handleManageWorkspaceDraft({ ...params, draftId, action: 'send' });
838
+ }
839
+ // --- Individual Attachment Operation Handlers ---
840
+ // These delegate to handleManageWorkspaceAttachment with the appropriate action.
841
+ export async function handleDownloadWorkspaceAttachment(params) {
842
+ const messageId = readAliasedString(params, 'message_id', 'messageId');
843
+ return handleManageWorkspaceAttachment({ ...params, messageId: messageId, action: 'download' });
844
+ }
845
+ export async function handleUploadWorkspaceAttachment(params) {
846
+ const rawParams = params;
847
+ const messageId = readAliasedString(rawParams, 'message_id', 'messageId');
848
+ const mimeType = readAliasedString(rawParams, 'mime_type', 'mimeType');
849
+ return handleManageWorkspaceAttachment({ ...params, messageId: messageId, mimeType, action: 'upload' });
850
+ }
851
+ export async function handleDeleteWorkspaceAttachment(params) {
852
+ const messageId = readAliasedString(params, 'message_id', 'messageId');
853
+ return handleManageWorkspaceAttachment({ ...params, messageId: messageId, action: 'delete' });
854
+ }
855
+ // --- Individual Label Operation Handlers ---
856
+ // These delegate to handleManageWorkspaceLabel with the appropriate action.
857
+ export async function handleListWorkspaceLabels(params) {
858
+ return handleManageWorkspaceLabel({ action: 'read', email: params.email || '' });
859
+ }
860
+ export async function handleGetWorkspaceLabel(params) {
861
+ const labelId = readAliasedString(params, 'label_id', 'labelId');
862
+ return handleManageWorkspaceLabel({ action: 'read', email: params.email || '', labelId });
863
+ }
864
+ export async function handleCreateWorkspaceLabel(params) {
865
+ const { email, message_list_visibility, messageListVisibility, label_list_visibility, labelListVisibility, ...rest } = params;
866
+ return handleManageWorkspaceLabel({
867
+ action: 'create',
868
+ email: email || '',
869
+ ...rest,
870
+ ...(message_list_visibility !== undefined || messageListVisibility !== undefined
871
+ ? { messageListVisibility: (message_list_visibility ?? messageListVisibility) }
872
+ : {}),
873
+ ...(label_list_visibility !== undefined || labelListVisibility !== undefined
874
+ ? { labelListVisibility: (label_list_visibility ?? labelListVisibility) }
875
+ : {}),
876
+ });
877
+ }
878
+ export async function handleUpdateWorkspaceLabel(params) {
879
+ const labelId = readAliasedString(params, 'label_id', 'labelId');
880
+ const { email, label_id: _labelIdSnake, labelId: _labelIdCamel, message_list_visibility, messageListVisibility, label_list_visibility, labelListVisibility, ...rest } = params;
881
+ return handleManageWorkspaceLabel({
882
+ action: 'update',
883
+ email: email || '',
884
+ labelId,
885
+ ...rest,
886
+ ...(message_list_visibility !== undefined || messageListVisibility !== undefined
887
+ ? { messageListVisibility: (message_list_visibility ?? messageListVisibility) }
888
+ : {}),
889
+ ...(label_list_visibility !== undefined || labelListVisibility !== undefined
890
+ ? { labelListVisibility: (label_list_visibility ?? labelListVisibility) }
891
+ : {}),
892
+ });
893
+ }
894
+ export async function handleDeleteWorkspaceLabel(params) {
895
+ const labelId = readAliasedString(params, 'label_id', 'labelId');
896
+ return handleManageWorkspaceLabel({ action: 'delete', email: params.email || '', labelId });
897
+ }
898
+ // --- Individual Label Filter Operation Handlers ---
899
+ // These delegate to handleManageWorkspaceLabelFilter with the appropriate action.
900
+ export async function handleListWorkspaceLabelFilters(params) {
901
+ const labelId = readAliasedString(params, 'label_id', 'labelId');
902
+ return handleManageWorkspaceLabelFilter({ action: 'read', email: params.email || '', ...(labelId ? { labelId } : {}) });
903
+ }
904
+ export async function handleCreateWorkspaceLabelFilter(params) {
905
+ const labelId = readAliasedString(params, 'label_id', 'labelId');
906
+ const { email, data } = params;
907
+ return handleManageWorkspaceLabelFilter({ action: 'create', email: email || '', labelId, data });
908
+ }
909
+ export async function handleUpdateWorkspaceLabelFilter(params) {
910
+ const filterId = readAliasedString(params, 'filter_id', 'filterId');
911
+ const labelId = readAliasedString(params, 'label_id', 'labelId');
912
+ const { email, data } = params;
913
+ return handleManageWorkspaceLabelFilter({ action: 'update', email: email || '', filterId, labelId, data });
914
+ }
915
+ export async function handleDeleteWorkspaceLabelFilter(params) {
916
+ const filterId = readAliasedString(params, 'filter_id', 'filterId');
917
+ return handleManageWorkspaceLabelFilter({ action: 'delete', email: params.email || '', filterId });
918
+ }
919
+ /**
920
+ * Resolves messageId / messageIds into a single array.
921
+ * At least one must be present.
922
+ */
923
+ function resolveMessageIds(params) {
924
+ const ids = [];
925
+ if (params.message_id ?? params.messageId)
926
+ ids.push((params.message_id ?? params.messageId));
927
+ if (params.message_ids ?? params.messageIds)
928
+ ids.push(...(params.message_ids ?? params.messageIds));
929
+ if (ids.length === 0) {
930
+ throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter: provide "message_id" (string) or "message_ids" (string array). ' +
931
+ 'Example: { "message_id": "18c5a2b3d4e5f6g7" } or { "message_ids": ["id1", "id2"] }');
932
+ }
933
+ return ids;
934
+ }
935
+ export async function handleArchiveWorkspaceEmail(params) {
936
+ await initializeServices();
937
+ const email = await resolveEmail(params);
938
+ const ids = resolveMessageIds(params);
939
+ return accountManager.withTokenRenewal(email, async () => {
940
+ try {
941
+ for (const messageId of ids) {
942
+ await gmailService.manageLabelAssignment({
943
+ email,
944
+ messageId,
945
+ action: 'remove',
946
+ labelIds: ['INBOX'],
947
+ });
948
+ }
949
+ return ids.length === 1
950
+ ? `Message ${ids[0]} archived successfully.`
951
+ : `${ids.length} messages archived successfully.`;
952
+ }
953
+ catch (error) {
954
+ throw new McpError(ErrorCode.InternalError, `Failed to archive email: ${error instanceof Error ? error.message : 'Unknown error'}`);
955
+ }
956
+ });
957
+ }
958
+ export async function handleTrashWorkspaceEmail(params) {
959
+ await initializeServices();
960
+ const email = await resolveEmail(params);
961
+ const ids = resolveMessageIds(params);
962
+ return accountManager.withTokenRenewal(email, async () => {
963
+ try {
964
+ for (const messageId of ids) {
965
+ await gmailService.trashMessage(email, messageId);
966
+ }
967
+ return ids.length === 1
968
+ ? `Message ${ids[0]} moved to trash.`
969
+ : `${ids.length} messages moved to trash.`;
970
+ }
971
+ catch (error) {
972
+ throw new McpError(ErrorCode.InternalError, `Failed to trash email: ${error instanceof Error ? error.message : 'Unknown error'}`);
973
+ }
974
+ });
975
+ }
976
+ export async function handleUntrashWorkspaceEmail(params) {
977
+ await initializeServices();
978
+ const email = await resolveEmail(params);
979
+ const ids = resolveMessageIds(params);
980
+ return accountManager.withTokenRenewal(email, async () => {
981
+ try {
982
+ for (const messageId of ids) {
983
+ await gmailService.untrashMessage(email, messageId);
984
+ }
985
+ return ids.length === 1
986
+ ? `Message ${ids[0]} restored from trash.`
987
+ : `${ids.length} messages restored from trash.`;
988
+ }
989
+ catch (error) {
990
+ throw new McpError(ErrorCode.InternalError, `Failed to untrash email: ${error instanceof Error ? error.message : 'Unknown error'}`);
991
+ }
992
+ });
993
+ }
994
+ export async function handleMarkWorkspaceEmailRead(params) {
995
+ await initializeServices();
996
+ const email = await resolveEmail(params);
997
+ const ids = resolveMessageIds(params);
998
+ return accountManager.withTokenRenewal(email, async () => {
999
+ try {
1000
+ for (const messageId of ids) {
1001
+ await gmailService.manageLabelAssignment({
1002
+ email,
1003
+ messageId,
1004
+ action: 'remove',
1005
+ labelIds: ['UNREAD'],
1006
+ });
1007
+ }
1008
+ return ids.length === 1
1009
+ ? `Message ${ids[0]} marked as read.`
1010
+ : `${ids.length} messages marked as read.`;
1011
+ }
1012
+ catch (error) {
1013
+ throw new McpError(ErrorCode.InternalError, `Failed to mark email as read: ${error instanceof Error ? error.message : 'Unknown error'}`);
1014
+ }
1015
+ });
1016
+ }
1017
+ export async function handleMarkWorkspaceEmailUnread(params) {
1018
+ await initializeServices();
1019
+ const email = await resolveEmail(params);
1020
+ const ids = resolveMessageIds(params);
1021
+ return accountManager.withTokenRenewal(email, async () => {
1022
+ try {
1023
+ for (const messageId of ids) {
1024
+ await gmailService.manageLabelAssignment({
1025
+ email,
1026
+ messageId,
1027
+ action: 'add',
1028
+ labelIds: ['UNREAD'],
1029
+ });
1030
+ }
1031
+ return ids.length === 1
1032
+ ? `Message ${ids[0]} marked as unread.`
1033
+ : `${ids.length} messages marked as unread.`;
1034
+ }
1035
+ catch (error) {
1036
+ throw new McpError(ErrorCode.InternalError, `Failed to mark email as unread: ${error instanceof Error ? error.message : 'Unknown error'}`);
1037
+ }
1038
+ });
1039
+ }
1040
+ //# sourceMappingURL=gmail-handlers.js.map