gmail-reader-mcp 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +84 -2
  3. package/dist/auth.d.ts +36 -0
  4. package/dist/auth.js +328 -0
  5. package/dist/files.d.ts +8 -0
  6. package/dist/files.js +32 -0
  7. package/dist/format.d.ts +10 -0
  8. package/dist/format.js +53 -0
  9. package/dist/mail.d.ts +80 -0
  10. package/dist/mail.js +265 -0
  11. package/dist/mcp-server.d.ts +2 -0
  12. package/dist/mcp-server.js +37 -0
  13. package/dist/text.d.ts +8 -0
  14. package/dist/text.js +70 -0
  15. package/dist/tools/authenticate/definition.d.ts +8 -0
  16. package/dist/tools/authenticate/definition.js +19 -0
  17. package/dist/tools/authenticate/index.d.ts +2 -0
  18. package/dist/tools/authenticate/index.js +10 -0
  19. package/dist/tools/authenticate/key.d.ts +1 -0
  20. package/dist/tools/authenticate/key.js +4 -0
  21. package/dist/tools/authenticate/schema.d.ts +3 -0
  22. package/dist/tools/authenticate/schema.js +5 -0
  23. package/dist/tools/download-attachment/definition.d.ts +8 -0
  24. package/dist/tools/download-attachment/definition.js +20 -0
  25. package/dist/tools/download-attachment/index.d.ts +2 -0
  26. package/dist/tools/download-attachment/index.js +10 -0
  27. package/dist/tools/download-attachment/key.d.ts +1 -0
  28. package/dist/tools/download-attachment/key.js +4 -0
  29. package/dist/tools/download-attachment/schema.d.ts +7 -0
  30. package/dist/tools/download-attachment/schema.js +14 -0
  31. package/dist/tools/download-attachments/definition.d.ts +8 -0
  32. package/dist/tools/download-attachments/definition.js +50 -0
  33. package/dist/tools/download-attachments/index.d.ts +2 -0
  34. package/dist/tools/download-attachments/index.js +10 -0
  35. package/dist/tools/download-attachments/key.d.ts +1 -0
  36. package/dist/tools/download-attachments/key.js +4 -0
  37. package/dist/tools/download-attachments/schema.d.ts +8 -0
  38. package/dist/tools/download-attachments/schema.js +20 -0
  39. package/dist/tools/get-email/definition.d.ts +8 -0
  40. package/dist/tools/get-email/definition.js +10 -0
  41. package/dist/tools/get-email/index.d.ts +2 -0
  42. package/dist/tools/get-email/index.js +10 -0
  43. package/dist/tools/get-email/key.d.ts +1 -0
  44. package/dist/tools/get-email/key.js +4 -0
  45. package/dist/tools/get-email/schema.d.ts +5 -0
  46. package/dist/tools/get-email/schema.js +9 -0
  47. package/dist/tools/get-emails/definition.d.ts +8 -0
  48. package/dist/tools/get-emails/definition.js +16 -0
  49. package/dist/tools/get-emails/index.d.ts +2 -0
  50. package/dist/tools/get-emails/index.js +10 -0
  51. package/dist/tools/get-emails/key.d.ts +1 -0
  52. package/dist/tools/get-emails/key.js +4 -0
  53. package/dist/tools/get-emails/schema.d.ts +5 -0
  54. package/dist/tools/get-emails/schema.js +11 -0
  55. package/dist/tools/get-thread/definition.d.ts +8 -0
  56. package/dist/tools/get-thread/definition.js +15 -0
  57. package/dist/tools/get-thread/index.d.ts +2 -0
  58. package/dist/tools/get-thread/index.js +10 -0
  59. package/dist/tools/get-thread/key.d.ts +1 -0
  60. package/dist/tools/get-thread/key.js +4 -0
  61. package/dist/tools/get-thread/schema.d.ts +5 -0
  62. package/dist/tools/get-thread/schema.js +9 -0
  63. package/dist/tools/index.d.ts +2 -0
  64. package/dist/tools/index.js +27 -0
  65. package/dist/tools/list-attachments/definition.d.ts +8 -0
  66. package/dist/tools/list-attachments/definition.js +13 -0
  67. package/dist/tools/list-attachments/index.d.ts +2 -0
  68. package/dist/tools/list-attachments/index.js +10 -0
  69. package/dist/tools/list-attachments/key.d.ts +1 -0
  70. package/dist/tools/list-attachments/key.js +4 -0
  71. package/dist/tools/list-attachments/schema.d.ts +5 -0
  72. package/dist/tools/list-attachments/schema.js +9 -0
  73. package/dist/tools/list-emails/definition.d.ts +10 -0
  74. package/dist/tools/list-emails/definition.js +25 -0
  75. package/dist/tools/list-emails/index.d.ts +2 -0
  76. package/dist/tools/list-emails/index.js +10 -0
  77. package/dist/tools/list-emails/key.d.ts +1 -0
  78. package/dist/tools/list-emails/key.js +4 -0
  79. package/dist/tools/list-emails/schema.d.ts +8 -0
  80. package/dist/tools/list-emails/schema.js +27 -0
  81. package/dist/tools/list-labels/definition.d.ts +8 -0
  82. package/dist/tools/list-labels/definition.js +14 -0
  83. package/dist/tools/list-labels/index.d.ts +2 -0
  84. package/dist/tools/list-labels/index.js +10 -0
  85. package/dist/tools/list-labels/key.d.ts +1 -0
  86. package/dist/tools/list-labels/key.js +4 -0
  87. package/dist/tools/list-labels/schema.d.ts +3 -0
  88. package/dist/tools/list-labels/schema.js +5 -0
  89. package/dist/tools/search-emails/definition.d.ts +8 -0
  90. package/dist/tools/search-emails/definition.js +17 -0
  91. package/dist/tools/search-emails/index.d.ts +2 -0
  92. package/dist/tools/search-emails/index.js +10 -0
  93. package/dist/tools/search-emails/key.d.ts +1 -0
  94. package/dist/tools/search-emails/key.js +4 -0
  95. package/dist/tools/search-emails/schema.d.ts +8 -0
  96. package/dist/tools/search-emails/schema.js +27 -0
  97. package/dist/tools/sign-out/definition.d.ts +8 -0
  98. package/dist/tools/sign-out/definition.js +17 -0
  99. package/dist/tools/sign-out/index.d.ts +2 -0
  100. package/dist/tools/sign-out/index.js +10 -0
  101. package/dist/tools/sign-out/key.d.ts +1 -0
  102. package/dist/tools/sign-out/key.js +4 -0
  103. package/dist/tools/sign-out/schema.d.ts +3 -0
  104. package/dist/tools/sign-out/schema.js +5 -0
  105. package/dist/tools/wrap.d.ts +13 -0
  106. package/dist/tools/wrap.js +44 -0
  107. package/package.json +56 -4
package/dist/mail.js ADDED
@@ -0,0 +1,265 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.attachmentsOf = attachmentsOf;
4
+ exports.listEmails = listEmails;
5
+ exports.getEmail = getEmail;
6
+ exports.getEmails = getEmails;
7
+ exports.getThread = getThread;
8
+ exports.listLabels = listLabels;
9
+ exports.getMessage = getMessage;
10
+ exports.listAttachments = listAttachments;
11
+ exports.downloadAttachment = downloadAttachment;
12
+ const gmail_1 = require("@googleapis/gmail");
13
+ const auth_1 = require("./auth");
14
+ const text_1 = require("./text");
15
+ // Gmail's per-user quota is 250 units/s and messages.get costs 5 units, so
16
+ // ~10 concurrent fetches keeps large batches well under the limit.
17
+ const CONCURRENCY = 10;
18
+ // Partial response for list views: headers + part tree (to detect
19
+ // attachments) without any body data.
20
+ const PART_TREE = 'partId,mimeType,filename,headers,body/attachmentId,body/size';
21
+ const SUMMARY_FIELDS = `id,threadId,labelIds,snippet,internalDate,` +
22
+ `payload(${PART_TREE},parts(${PART_TREE},parts(${PART_TREE},parts(${PART_TREE}))))`;
23
+ async function client() {
24
+ return (0, gmail_1.gmail)({ version: 'v1', auth: await (0, auth_1.getAuthClient)() });
25
+ }
26
+ async function mapLimit(items, limit, fn) {
27
+ const results = new Array(items.length);
28
+ let next = 0;
29
+ const worker = async () => {
30
+ while (next < items.length) {
31
+ const i = next++;
32
+ results[i] = await fn(items[i]);
33
+ }
34
+ };
35
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
36
+ return results;
37
+ }
38
+ function header(part, name) {
39
+ const lower = name.toLowerCase();
40
+ return (part?.headers?.find((h) => h.name?.toLowerCase() === lower)?.value ?? '');
41
+ }
42
+ function* walkParts(part) {
43
+ if (!part)
44
+ return;
45
+ yield part;
46
+ for (const child of part.parts ?? [])
47
+ yield* walkParts(child);
48
+ }
49
+ function isAttachmentPart(p) {
50
+ return (!!p.filename || (!!p.body?.attachmentId && !p.mimeType?.startsWith('text/')));
51
+ }
52
+ function toAttachmentInfo(p) {
53
+ const disposition = header(p, 'Content-Disposition').toLowerCase();
54
+ return {
55
+ partId: p.partId ?? '',
56
+ filename: p.filename || `part-${p.partId}`,
57
+ mimeType: p.mimeType ?? 'application/octet-stream',
58
+ size: p.body?.size ?? 0,
59
+ isInline: disposition.startsWith('inline') ||
60
+ (!disposition && !!header(p, 'Content-ID')),
61
+ };
62
+ }
63
+ function attachmentsOf(message) {
64
+ return [...walkParts(message.payload ?? undefined)]
65
+ .filter(isAttachmentPart)
66
+ .map(toAttachmentInfo);
67
+ }
68
+ function internalDateIso(m) {
69
+ return m.internalDate
70
+ ? new Date(Number(m.internalDate)).toISOString()
71
+ : header(m.payload, 'Date');
72
+ }
73
+ function toSummary(m) {
74
+ return {
75
+ id: m.id ?? '',
76
+ threadId: m.threadId ?? '',
77
+ subject: header(m.payload, 'Subject') || '(no subject)',
78
+ from: header(m.payload, 'From'),
79
+ to: header(m.payload, 'To'),
80
+ date: internalDateIso(m),
81
+ unread: m.labelIds?.includes('UNREAD') ?? false,
82
+ labels: m.labelIds ?? [],
83
+ hasAttachments: attachmentsOf(m).some((a) => !a.isInline),
84
+ // Snippets come HTML-escaped from the API.
85
+ snippet: (0, text_1.htmlToText)(m.snippet ?? ''),
86
+ };
87
+ }
88
+ async function listEmails(options = {}) {
89
+ const g = await client();
90
+ const res = await g.users.messages.list({
91
+ userId: 'me',
92
+ q: options.query || undefined,
93
+ labelIds: options.labelIds?.length ? options.labelIds : undefined,
94
+ maxResults: options.maxResults ?? 10,
95
+ pageToken: options.pageToken || undefined,
96
+ includeSpamTrash: options.includeSpamTrash ?? false,
97
+ });
98
+ const ids = (res.data.messages ?? []).map((m) => m.id).filter(Boolean);
99
+ const emails = await mapLimit(ids, CONCURRENCY, async (id) => {
100
+ const r = await g.users.messages.get({
101
+ userId: 'me',
102
+ id,
103
+ format: 'full',
104
+ fields: SUMMARY_FIELDS,
105
+ });
106
+ return toSummary(r.data);
107
+ });
108
+ return {
109
+ emails,
110
+ nextPageToken: res.data.nextPageToken ?? undefined,
111
+ resultSizeEstimate: res.data.resultSizeEstimate ?? undefined,
112
+ };
113
+ }
114
+ function charsetOf(part) {
115
+ const m = /charset\s*=\s*"?([^";\s]+)"?/i.exec(header(part, 'Content-Type'));
116
+ return m?.[1] ?? 'utf-8';
117
+ }
118
+ function decodeText(buf, charset) {
119
+ try {
120
+ return new TextDecoder(charset).decode(buf);
121
+ }
122
+ catch {
123
+ return buf.toString('utf8');
124
+ }
125
+ }
126
+ async function partText(g, messageId, part) {
127
+ // Large text parts come back as an attachment reference instead of data.
128
+ let data = part.body?.data;
129
+ if (!data && part.body?.attachmentId) {
130
+ const r = await g.users.messages.attachments.get({
131
+ userId: 'me',
132
+ messageId,
133
+ id: part.body.attachmentId,
134
+ });
135
+ data = r.data.data;
136
+ }
137
+ return data ? decodeText((0, text_1.decodeBase64Url)(data), charsetOf(part)) : '';
138
+ }
139
+ /** First non-attachment part of the given MIME type, depth-first. */
140
+ function findBodyPart(root, mimeType) {
141
+ for (const p of walkParts(root)) {
142
+ if (p.mimeType === mimeType && !p.filename)
143
+ return p;
144
+ }
145
+ return undefined;
146
+ }
147
+ async function toDetail(g, m) {
148
+ const plain = findBodyPart(m.payload, 'text/plain');
149
+ const html = findBodyPart(m.payload, 'text/html');
150
+ let body = '';
151
+ let bodyFormat = 'none';
152
+ if (plain) {
153
+ body = (await partText(g, m.id, plain)).trim();
154
+ bodyFormat = 'text';
155
+ }
156
+ // Some senders ship an empty text/plain alongside the real HTML body.
157
+ if (!body && html) {
158
+ body = (0, text_1.htmlToText)(await partText(g, m.id, html));
159
+ bodyFormat = 'html-converted';
160
+ }
161
+ return {
162
+ ...toSummary(m),
163
+ cc: header(m.payload, 'Cc'),
164
+ replyTo: header(m.payload, 'Reply-To'),
165
+ headerDate: header(m.payload, 'Date'),
166
+ body,
167
+ bodyFormat,
168
+ attachments: attachmentsOf(m),
169
+ };
170
+ }
171
+ async function getFullMessage(g, id) {
172
+ const r = await g.users.messages.get({ userId: 'me', id, format: 'full' });
173
+ return r.data;
174
+ }
175
+ async function getEmail(id) {
176
+ const g = await client();
177
+ return toDetail(g, await getFullMessage(g, id));
178
+ }
179
+ async function getEmails(ids) {
180
+ const g = await client();
181
+ return mapLimit(ids, CONCURRENCY, async (id) => {
182
+ try {
183
+ return {
184
+ ok: true,
185
+ email: await toDetail(g, await getFullMessage(g, id)),
186
+ };
187
+ }
188
+ catch (err) {
189
+ const e = err;
190
+ return {
191
+ ok: false,
192
+ id,
193
+ error: `${e.status ? `HTTP ${e.status}: ` : ''}${e.message ?? String(err)}`,
194
+ };
195
+ }
196
+ });
197
+ }
198
+ async function getThread(id) {
199
+ const g = await client();
200
+ const r = await g.users.threads.get({ userId: 'me', id, format: 'full' });
201
+ const messages = r.data.messages ?? [];
202
+ return mapLimit(messages, CONCURRENCY, (m) => toDetail(g, m));
203
+ }
204
+ async function listLabels() {
205
+ const g = await client();
206
+ const res = await g.users.labels.list({ userId: 'me' });
207
+ // labels.list omits counts; labels.get includes them.
208
+ const labels = await mapLimit(res.data.labels ?? [], CONCURRENCY, async (l) => (await g.users.labels.get({ userId: 'me', id: l.id })).data);
209
+ return labels
210
+ .map((l) => ({
211
+ id: l.id ?? '',
212
+ name: l.name ?? '',
213
+ type: l.type ?? '',
214
+ messagesTotal: l.messagesTotal ?? 0,
215
+ messagesUnread: l.messagesUnread ?? 0,
216
+ threadsTotal: l.threadsTotal ?? 0,
217
+ threadsUnread: l.threadsUnread ?? 0,
218
+ }))
219
+ .sort((a, b) =>
220
+ // System labels first, then user labels alphabetically.
221
+ Number(a.type === 'user') - Number(b.type === 'user') ||
222
+ a.name.localeCompare(b.name));
223
+ }
224
+ /**
225
+ * Gmail attachment IDs change on every fetch, so they are useless as
226
+ * handles across tool calls. Attachments are addressed by MIME part ID
227
+ * instead (stable for a given message), and the current attachment ID is
228
+ * resolved at download time.
229
+ */
230
+ async function getMessage(messageId) {
231
+ return getFullMessage(await client(), messageId);
232
+ }
233
+ async function listAttachments(messageId) {
234
+ return attachmentsOf(await getMessage(messageId));
235
+ }
236
+ /**
237
+ * Downloads one attachment by part ID. Pass `message` (fetched with
238
+ * getMessage) to avoid re-fetching it when downloading several parts.
239
+ */
240
+ async function downloadAttachment(messageId, partId, message) {
241
+ const g = await client();
242
+ const m = message ?? (await getFullMessage(g, messageId));
243
+ const part = [...walkParts(m.payload ?? undefined)].find((p) => p.partId === partId);
244
+ if (!part) {
245
+ throw new Error(`No part ${partId} in message ${messageId}. Re-run list_attachments to get current part IDs.`);
246
+ }
247
+ // Small parts carry their data inline; larger ones need a separate fetch.
248
+ let data = part.body?.data;
249
+ if (!data && part.body?.attachmentId) {
250
+ const r = await g.users.messages.attachments.get({
251
+ userId: 'me',
252
+ messageId,
253
+ id: part.body.attachmentId,
254
+ });
255
+ data = r.data.data;
256
+ }
257
+ if (!data)
258
+ throw new Error(`Part ${partId} has no downloadable content.`);
259
+ const info = toAttachmentInfo(part);
260
+ return {
261
+ filename: info.filename,
262
+ mimeType: info.mimeType,
263
+ data: (0, text_1.decodeBase64Url)(data),
264
+ };
265
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const mcp_js_1 = require("@modelcontextprotocol/sdk/server/mcp.js");
5
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
6
+ const dotenv_1 = require("dotenv");
7
+ const auth_js_1 = require("./auth.js");
8
+ const index_js_1 = require("./tools/index.js");
9
+ // Load a local .env (development). quiet: dotenv must never write to stdout,
10
+ // which carries the MCP protocol.
11
+ (0, dotenv_1.config)({ quiet: true });
12
+ // Pull version from package.json so it stays in sync with published releases.
13
+ // Resolves to the project root from both dist/ (build) and src/ (tsx dev).
14
+ const { version } = require('../package.json');
15
+ async function main() {
16
+ // Fail fast with a readable message instead of a confusing OAuth error on
17
+ // the first tool call.
18
+ (0, auth_js_1.getConfig)();
19
+ const server = new mcp_js_1.McpServer({
20
+ name: 'gmail-reader',
21
+ version,
22
+ });
23
+ (0, index_js_1.registerAllTools)(server);
24
+ const transport = new stdio_js_1.StdioServerTransport();
25
+ await server.connect(transport);
26
+ // When the client disconnects, stdin ends — but a pending sign-in listener
27
+ // can keep the event loop alive for up to 10 minutes, leaving an orphaned
28
+ // process. Give in-flight responses a moment to flush, then exit.
29
+ // unref() lets the process exit sooner naturally if the loop drains.
30
+ process.stdin.on('end', () => {
31
+ setTimeout(() => process.exit(0), 5_000).unref();
32
+ });
33
+ }
34
+ main().catch((err) => {
35
+ console.error(err instanceof Error ? err.message : err);
36
+ process.exit(1);
37
+ });
package/dist/text.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Lightweight HTML-to-text for email bodies that have no text/plain part.
3
+ * Keeps paragraph/line structure and link targets; not a full renderer.
4
+ */
5
+ export declare function htmlToText(html: string): string;
6
+ /** Gmail returns part bodies as base64url. */
7
+ export declare function decodeBase64Url(data: string): Buffer;
8
+ export declare function formatSize(bytes: number): string;
package/dist/text.js ADDED
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.htmlToText = htmlToText;
4
+ exports.decodeBase64Url = decodeBase64Url;
5
+ exports.formatSize = formatSize;
6
+ const NAMED_ENTITIES = {
7
+ amp: '&',
8
+ lt: '<',
9
+ gt: '>',
10
+ quot: '"',
11
+ apos: "'",
12
+ nbsp: ' ',
13
+ copy: '©',
14
+ reg: '®',
15
+ hellip: '…',
16
+ mdash: '—',
17
+ ndash: '–',
18
+ lsquo: '‘',
19
+ rsquo: '’',
20
+ ldquo: '“',
21
+ rdquo: '”',
22
+ bull: '•',
23
+ euro: '€',
24
+ };
25
+ function decodeEntities(s) {
26
+ return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (match, ent) => {
27
+ if (ent[0] === '#') {
28
+ const code = ent[1].toLowerCase() === 'x'
29
+ ? parseInt(ent.slice(2), 16)
30
+ : parseInt(ent.slice(1), 10);
31
+ return Number.isFinite(code) && code <= 0x10ffff
32
+ ? String.fromCodePoint(code)
33
+ : match;
34
+ }
35
+ return NAMED_ENTITIES[ent.toLowerCase()] ?? match;
36
+ });
37
+ }
38
+ /**
39
+ * Lightweight HTML-to-text for email bodies that have no text/plain part.
40
+ * Keeps paragraph/line structure and link targets; not a full renderer.
41
+ */
42
+ function htmlToText(html) {
43
+ return (decodeEntities(html
44
+ .replace(/<(head|style|script|title)[^>]*>[\s\S]*?<\/\1>/gi, '')
45
+ .replace(/<!--[\s\S]*?-->/g, '')
46
+ .replace(/<a\b[^>]*href\s*=\s*["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi, (_m, href, label) => {
47
+ const text = label.replace(/<[^>]+>/g, '').trim();
48
+ return href.startsWith('mailto:') || !text || text === href
49
+ ? text || href
50
+ : `${text} (${href})`;
51
+ })
52
+ .replace(/<br\s*\/?>/gi, '\n')
53
+ .replace(/<li\b[^>]*>/gi, '\n• ')
54
+ .replace(/<\/(p|div|tr|h[1-6]|li|ul|ol|table|blockquote)>/gi, '\n')
55
+ .replace(/<(td|th)\b[^>]*>/gi, ' ')
56
+ .replace(/<[^>]+>/g, ''))
57
+ // Invisible characters marketing emails use to pad the preview text.
58
+ .replace(/[\u034f\u00ad\u200b-\u200d\u2060\ufeff]/g, '')
59
+ .replace(/[ \t\u00a0]+/g, ' ')
60
+ .replace(/ *\n */g, '\n')
61
+ .replace(/\n{3,}/g, '\n\n')
62
+ .trim());
63
+ }
64
+ /** Gmail returns part bodies as base64url. */
65
+ function decodeBase64Url(data) {
66
+ return Buffer.from(data, 'base64url');
67
+ }
68
+ function formatSize(bytes) {
69
+ return `${(bytes / 1024).toFixed(1)} KB`;
70
+ }
@@ -0,0 +1,8 @@
1
+ import type { Input } from './schema.js';
2
+ export declare const description = "Sign in to the Google account used by the other tools. Returns a Google sign-in URL: show it to the user and ask them to open it in a browser on this machine and grant read-only Gmail access. Run this when other tools report that authentication is required. Safe to call anytime \u2014 reports the current account if already signed in.";
3
+ export declare function handler(_input: Input): Promise<{
4
+ content: {
5
+ type: "text";
6
+ text: string;
7
+ }[];
8
+ }>;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.description = void 0;
4
+ exports.handler = handler;
5
+ const auth_js_1 = require("../../auth.js");
6
+ const format_js_1 = require("../../format.js");
7
+ exports.description = 'Sign in to the Google account used by the other tools. Returns a Google sign-in URL: show it to the user and ask them to open it in a browser on this machine and grant read-only Gmail access. Run this when other tools report that authentication is required. Safe to call anytime — reports the current account if already signed in.';
8
+ async function handler(_input) {
9
+ const account = await (0, auth_js_1.getSignedInAccount)();
10
+ if (account) {
11
+ return (0, format_js_1.text)(`Already signed in as ${account}. Other tools are ready to use.`);
12
+ }
13
+ const url = await (0, auth_js_1.startLoopbackAuth)();
14
+ return (0, format_js_1.text)(`Open this URL to sign in to Google and grant read-only Gmail access:\n${url}\n\n` +
15
+ 'Show the URL to the user and ask them to open it in a browser on this ' +
16
+ 'computer (the sign-in redirects to a temporary local listener, valid for ' +
17
+ '10 minutes). Once they see "Signed in", retry the original request — no ' +
18
+ 'need to run this tool again.');
19
+ }
@@ -0,0 +1,2 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ export declare function register(server: McpServer): void;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.register = register;
4
+ const wrap_js_1 = require("../wrap.js");
5
+ const definition_js_1 = require("./definition.js");
6
+ const key_js_1 = require("./key.js");
7
+ const schema_js_1 = require("./schema.js");
8
+ function register(server) {
9
+ server.registerTool(key_js_1.KEY, { description: definition_js_1.description, inputSchema: schema_js_1.schema }, (0, wrap_js_1.wrapHandler)(definition_js_1.handler));
10
+ }
@@ -0,0 +1 @@
1
+ export declare const KEY = "authenticate";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KEY = void 0;
4
+ exports.KEY = 'authenticate';
@@ -0,0 +1,3 @@
1
+ import { z } from 'zod';
2
+ export declare const schema: z.ZodObject<{}, z.core.$strip>;
3
+ export type Input = z.infer<typeof schema>;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.schema = void 0;
4
+ const zod_1 = require("zod");
5
+ exports.schema = zod_1.z.object({});
@@ -0,0 +1,8 @@
1
+ import type { Input } from './schema.js';
2
+ export declare const description = "Download a specific email attachment and save it to disk. Use list_attachments (or get_email) first to get the part ID. To save several (or all) attachments from an email in one call, use download_attachments instead. Returns the full path where the file was saved.";
3
+ export declare function handler({ messageId, partId, saveTo }: Input): Promise<{
4
+ content: {
5
+ type: "text";
6
+ text: string;
7
+ }[];
8
+ }>;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.description = void 0;
4
+ exports.handler = handler;
5
+ const fs_1 = require("fs");
6
+ const os_1 = require("os");
7
+ const path_1 = require("path");
8
+ const files_js_1 = require("../../files.js");
9
+ const format_js_1 = require("../../format.js");
10
+ const mail_js_1 = require("../../mail.js");
11
+ const text_js_1 = require("../../text.js");
12
+ exports.description = 'Download a specific email attachment and save it to disk. Use list_attachments (or get_email) first to get the part ID. To save several (or all) attachments from an email in one call, use download_attachments instead. Returns the full path where the file was saved.';
13
+ async function handler({ messageId, partId, saveTo }) {
14
+ const att = await (0, mail_js_1.downloadAttachment)(messageId, partId);
15
+ const dir = saveTo ?? (0, path_1.join)((0, os_1.homedir)(), 'Downloads');
16
+ (0, fs_1.mkdirSync)(dir, { recursive: true });
17
+ const filePath = (0, files_js_1.uniquePath)(dir, (0, files_js_1.sanitizeFilename)(att.filename));
18
+ (0, fs_1.writeFileSync)(filePath, att.data, { flag: 'wx' });
19
+ return (0, format_js_1.text)(`Saved: ${filePath}\nSize: ${(0, text_js_1.formatSize)(att.data.length)}\nType: ${att.mimeType}`);
20
+ }
@@ -0,0 +1,2 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ export declare function register(server: McpServer): void;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.register = register;
4
+ const wrap_js_1 = require("../wrap.js");
5
+ const definition_js_1 = require("./definition.js");
6
+ const key_js_1 = require("./key.js");
7
+ const schema_js_1 = require("./schema.js");
8
+ function register(server) {
9
+ server.registerTool(key_js_1.KEY, { description: definition_js_1.description, inputSchema: schema_js_1.schema }, (0, wrap_js_1.wrapHandler)(definition_js_1.handler));
10
+ }
@@ -0,0 +1 @@
1
+ export declare const KEY = "download_attachment";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KEY = void 0;
4
+ exports.KEY = 'download_attachment';
@@ -0,0 +1,7 @@
1
+ import { z } from 'zod';
2
+ export declare const schema: z.ZodObject<{
3
+ messageId: z.ZodString;
4
+ partId: z.ZodString;
5
+ saveTo: z.ZodOptional<z.ZodString>;
6
+ }, z.core.$strip>;
7
+ export type Input = z.infer<typeof schema>;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.schema = void 0;
4
+ const zod_1 = require("zod");
5
+ exports.schema = zod_1.z.object({
6
+ messageId: zod_1.z.string().describe('The email message ID'),
7
+ partId: zod_1.z
8
+ .string()
9
+ .describe('The attachment part ID (from list_attachments or get_email)'),
10
+ saveTo: zod_1.z
11
+ .string()
12
+ .optional()
13
+ .describe('Directory path to save the file. Defaults to user Downloads folder (e.g. C:\\Users\\username\\Downloads)'),
14
+ });
@@ -0,0 +1,8 @@
1
+ import type { Input } from './schema.js';
2
+ export declare const description = "Download multiple attachments from an email in a single call and save them to disk. Omit partIds to download all file attachments. Returns the saved path for each file.";
3
+ export declare function handler({ messageId, partIds, saveTo, includeInline, }: Input): Promise<{
4
+ content: {
5
+ type: "text";
6
+ text: string;
7
+ }[];
8
+ }>;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.description = void 0;
4
+ exports.handler = handler;
5
+ const fs_1 = require("fs");
6
+ const os_1 = require("os");
7
+ const path_1 = require("path");
8
+ const files_js_1 = require("../../files.js");
9
+ const format_js_1 = require("../../format.js");
10
+ const mail_js_1 = require("../../mail.js");
11
+ const text_js_1 = require("../../text.js");
12
+ exports.description = 'Download multiple attachments from an email in a single call and save them to disk. Omit partIds to download all file attachments. Returns the saved path for each file.';
13
+ async function handler({ messageId, partIds, saveTo, includeInline, }) {
14
+ // Fetch the message once and reuse it for every part.
15
+ const message = await (0, mail_js_1.getMessage)(messageId);
16
+ const all = (0, mail_js_1.attachmentsOf)(message);
17
+ const lines = [];
18
+ let targets;
19
+ if (partIds?.length) {
20
+ const known = new Set(all.map((a) => a.partId));
21
+ for (const id of partIds) {
22
+ if (!known.has(id))
23
+ lines.push(`Not found: attachment part ${id}`);
24
+ }
25
+ targets = all.filter((a) => partIds.includes(a.partId));
26
+ }
27
+ else {
28
+ targets = all.filter((a) => includeInline || !a.isInline);
29
+ }
30
+ if (targets.length === 0) {
31
+ lines.push('No attachments to download.');
32
+ return (0, format_js_1.text)(lines.join('\n'));
33
+ }
34
+ const dir = saveTo ?? (0, path_1.join)((0, os_1.homedir)(), 'Downloads');
35
+ (0, fs_1.mkdirSync)(dir, { recursive: true });
36
+ // Sequential on purpose: uniquePath checks disk, so parallel downloads of
37
+ // same-named attachments could race into the same target path.
38
+ for (const a of targets) {
39
+ try {
40
+ const att = await (0, mail_js_1.downloadAttachment)(messageId, a.partId, message);
41
+ const filePath = (0, files_js_1.uniquePath)(dir, (0, files_js_1.sanitizeFilename)(att.filename));
42
+ (0, fs_1.writeFileSync)(filePath, att.data, { flag: 'wx' });
43
+ lines.push(`Saved: ${filePath} (${(0, text_js_1.formatSize)(att.data.length)})`);
44
+ }
45
+ catch (err) {
46
+ lines.push(`Failed: ${a.filename} — ${err instanceof Error ? err.message : String(err)}`);
47
+ }
48
+ }
49
+ return (0, format_js_1.text)(lines.join('\n'));
50
+ }
@@ -0,0 +1,2 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ export declare function register(server: McpServer): void;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.register = register;
4
+ const wrap_js_1 = require("../wrap.js");
5
+ const definition_js_1 = require("./definition.js");
6
+ const key_js_1 = require("./key.js");
7
+ const schema_js_1 = require("./schema.js");
8
+ function register(server) {
9
+ server.registerTool(key_js_1.KEY, { description: definition_js_1.description, inputSchema: schema_js_1.schema }, (0, wrap_js_1.wrapHandler)(definition_js_1.handler));
10
+ }
@@ -0,0 +1 @@
1
+ export declare const KEY = "download_attachments";
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KEY = void 0;
4
+ exports.KEY = 'download_attachments';
@@ -0,0 +1,8 @@
1
+ import { z } from 'zod';
2
+ export declare const schema: z.ZodObject<{
3
+ messageId: z.ZodString;
4
+ partIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
5
+ saveTo: z.ZodOptional<z.ZodString>;
6
+ includeInline: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
7
+ }, z.core.$strip>;
8
+ export type Input = z.infer<typeof schema>;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.schema = void 0;
4
+ const zod_1 = require("zod");
5
+ exports.schema = zod_1.z.object({
6
+ messageId: zod_1.z.string().describe('The email message ID'),
7
+ partIds: zod_1.z
8
+ .array(zod_1.z.string())
9
+ .optional()
10
+ .describe('Specific attachment part IDs to download (from list_attachments). Omit to download ALL file attachments of the message.'),
11
+ saveTo: zod_1.z
12
+ .string()
13
+ .optional()
14
+ .describe('Directory path to save the files. Defaults to user Downloads folder (e.g. C:\\Users\\username\\Downloads)'),
15
+ includeInline: zod_1.z
16
+ .boolean()
17
+ .optional()
18
+ .default(false)
19
+ .describe('When downloading all attachments, also include inline ones (embedded images, signatures). Default false.'),
20
+ });