@miguelarios/email-mcp 0.10.0 → 0.12.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.
@@ -1,8 +1,9 @@
1
1
  import { realpathSync } from "node:fs";
2
2
  import { resolve, sep } from "node:path";
3
- import { toPimError } from "@miguelarios/pim-core";
3
+ import { confirmDestructive, fail, structured, toolError, } from "@miguelarios/pim-core/mcp";
4
4
  import { simpleParser } from "mailparser";
5
5
  import { htmlToMarkdown } from "../htmlToMarkdown.js";
6
+ import { attachmentSchema, createFolderResultSchema, deleteResultSchema, emailFullSchema, folderListSchema, folderStatusSchema, markResultSchema, moveResultSchema, rawEmailSchema, searchResultSchema, sendResultSchema, } from "./emailSchemas.js";
6
7
  function assertAttachmentPathAllowed(p) {
7
8
  const allowedRoot = process.env.EMAIL_ATTACHMENT_DIR;
8
9
  if (!allowedRoot) {
@@ -14,18 +15,39 @@ function assertAttachmentPathAllowed(p) {
14
15
  throw new Error(`attachment path is outside EMAIL_ATTACHMENT_DIR: ${p}`);
15
16
  }
16
17
  }
18
+ /** Runs a handler body, converting anything thrown into a tool execution error. */
19
+ async function run(body) {
20
+ try {
21
+ return await body();
22
+ }
23
+ catch (err) {
24
+ return toolError(err);
25
+ }
26
+ }
27
+ function invalid(message) {
28
+ return fail("INVALID_INPUT", message);
29
+ }
30
+ const FOLDER_PROP = {
31
+ type: "string",
32
+ description: "IMAP folder. Defaults to INBOX.",
33
+ };
34
+ const UIDS_PROP = (description) => ({ type: "array", items: { type: "number" }, description });
35
+ const READ_ONLY = {
36
+ readOnlyHint: true,
37
+ destructiveHint: false,
38
+ idempotentHint: true,
39
+ openWorldHint: true,
40
+ };
17
41
  export const EMAIL_TOOLS = [
18
42
  {
19
43
  name: "search_emails",
44
+ title: "Search Emails",
20
45
  description: "Search and list emails in a folder. Returns email summaries with configurable sorting (default: date descending). All filters combine with AND logic. Use the dedicated fields (subject, from, to, etc.) for most searches. Note: for result sets >1000, non-date sort fields are approximate (sorted within page only).",
21
- annotations: { readOnlyHint: true },
46
+ annotations: READ_ONLY,
22
47
  inputSchema: {
23
48
  type: "object",
24
49
  properties: {
25
- folder: {
26
- type: "string",
27
- description: 'IMAP folder path. Defaults to "INBOX".',
28
- },
50
+ folder: { type: "string", description: 'IMAP folder path. Defaults to "INBOX".' },
29
51
  subject: {
30
52
  type: "string",
31
53
  description: "Search subject line. Multiple words are ANDed. Use -term to exclude. Use quotes for exact phrase: '\"weekly report\"'.",
@@ -38,14 +60,8 @@ export const EMAIL_TOOLS = [
38
60
  type: "string",
39
61
  description: "Match recipient name or email address (substring match).",
40
62
  },
41
- cc: {
42
- type: "string",
43
- description: "Match CC recipient (substring match).",
44
- },
45
- bcc: {
46
- type: "string",
47
- description: "Match BCC recipient (substring match).",
48
- },
63
+ cc: { type: "string", description: "Match CC recipient (substring match)." },
64
+ bcc: { type: "string", description: "Match BCC recipient (substring match)." },
49
65
  body: {
50
66
  type: "string",
51
67
  description: "Search body text. Multiple words are ANDed. Use -term to exclude. Use quotes for exact phrase: '\"project update\"'.",
@@ -54,35 +70,17 @@ export const EMAIL_TOOLS = [
54
70
  type: "string",
55
71
  description: 'Search all message content (headers + body, IMAP TEXT). Multiple words are ANDed. Use quotes for exact phrase. Use -term for exclusion. Examples: "budget", "report -draft", \'"quarterly report"\'.',
56
72
  },
57
- since: {
58
- type: "string",
59
- description: "Emails on or after this date (YYYY-MM-DD).",
60
- },
61
- before: {
62
- type: "string",
63
- description: "Emails before this date (YYYY-MM-DD).",
64
- },
65
- unread: {
66
- type: "boolean",
67
- description: "Filter by unread status.",
68
- },
69
- flagged: {
70
- type: "boolean",
71
- description: "Filter by flagged/starred status.",
72
- },
73
- hasAttachment: {
74
- type: "boolean",
75
- description: "Filter for emails with attachments.",
76
- },
73
+ since: { type: "string", description: "Emails on or after this date (YYYY-MM-DD)." },
74
+ before: { type: "string", description: "Emails before this date (YYYY-MM-DD)." },
75
+ unread: { type: "boolean", description: "Filter by unread status." },
76
+ flagged: { type: "boolean", description: "Filter by flagged/starred status." },
77
+ hasAttachment: { type: "boolean", description: "Filter for emails with attachments." },
77
78
  tags: {
78
79
  type: "array",
79
80
  items: { type: "string" },
80
81
  description: "Filter by IMAP keyword flags.",
81
82
  },
82
- limit: {
83
- type: "number",
84
- description: "Max results to return. Defaults to 50.",
85
- },
83
+ limit: { type: "number", description: "Max results to return. Defaults to 50." },
86
84
  offset: {
87
85
  type: "number",
88
86
  description: "Number of results to skip for pagination. Defaults to 0.",
@@ -99,11 +97,37 @@ export const EMAIL_TOOLS = [
99
97
  },
100
98
  },
101
99
  },
100
+ outputSchema: searchResultSchema,
101
+ handler: (args, { imap }) => run(async () => {
102
+ const searchParams = {
103
+ hasWords: args.hasWords,
104
+ body: args.body,
105
+ from: args.from,
106
+ to: args.to,
107
+ cc: args.cc,
108
+ bcc: args.bcc,
109
+ subject: args.subject,
110
+ since: args.since,
111
+ before: args.before,
112
+ unread: args.unread,
113
+ flagged: args.flagged,
114
+ hasAttachment: args.hasAttachment,
115
+ tags: args.tags,
116
+ };
117
+ const emails = await imap.searchEmails(args.folder || "INBOX", searchParams, {
118
+ limit: args.limit || 50,
119
+ offset: args.offset || 0,
120
+ sortBy: args.sortBy ?? "date",
121
+ sortOrder: args.sortOrder ?? "desc",
122
+ });
123
+ return structured({ emails, count: emails.length });
124
+ }),
102
125
  },
103
126
  {
104
127
  name: "get_email",
105
- description: "Fetch a full email by UID including headers, body, and attachment metadata. Returns body as markdown by default for token efficiency. Use format='html' or format='text' for raw content.",
106
- annotations: { readOnlyHint: true },
128
+ title: "Get Email",
129
+ description: "Fetch a full email by UID including headers, body, and attachment metadata. Calendar invitations (text/calendar parts, even inline ones without a filename) are surfaced in calendarParts with their iTIP method and decoded iCalendar content. Returns body as markdown by default for token efficiency. Use format='html' or format='text' for raw content.",
130
+ annotations: READ_ONLY,
107
131
  inputSchema: {
108
132
  type: "object",
109
133
  properties: {
@@ -111,10 +135,7 @@ export const EMAIL_TOOLS = [
111
135
  type: "string",
112
136
  description: "IMAP folder containing the email. Defaults to INBOX.",
113
137
  },
114
- uid: {
115
- type: "number",
116
- description: "The UID of the email to fetch.",
117
- },
138
+ uid: { type: "number", description: "The UID of the email to fetch." },
118
139
  format: {
119
140
  type: "string",
120
141
  enum: ["markdown", "html", "text"],
@@ -123,10 +144,44 @@ export const EMAIL_TOOLS = [
123
144
  },
124
145
  required: ["uid"],
125
146
  },
147
+ outputSchema: emailFullSchema,
148
+ handler: (args, { imap }) => run(async () => {
149
+ const format = args.format || "markdown";
150
+ const email = await imap.fetchEmail(args.folder || "INBOX", args.uid);
151
+ if (format === "markdown") {
152
+ try {
153
+ if (email.htmlBody) {
154
+ email.markdownBody = await htmlToMarkdown(email.htmlBody);
155
+ }
156
+ else if (email.textBody) {
157
+ email.markdownBody = email.textBody;
158
+ }
159
+ delete email.htmlBody;
160
+ delete email.textBody;
161
+ }
162
+ catch {
163
+ // Conversion failed — fall back to returning raw bodies unchanged
164
+ }
165
+ }
166
+ else if (format === "text") {
167
+ delete email.htmlBody;
168
+ }
169
+ else if (format === "html") {
170
+ delete email.textBody;
171
+ }
172
+ return structured(email);
173
+ }),
126
174
  },
127
175
  {
128
176
  name: "send_email",
129
- description: "Compose and send an email, or save it as a draft. Supports replies with automatic threading — when replyToUid is provided, the tool fetches the original email and sets correct In-Reply-To/References headers and Re: subject prefix automatically. Set saveToDrafts to true to save to the Drafts folder instead of sending. Sent emails are automatically copied to the Sent folder.",
177
+ title: "Send Email",
178
+ description: "Compose and send an email, or save it as a draft. Supports replies with automatic threading — when replyToUid is provided, the tool fetches the original email and sets correct In-Reply-To/References headers and Re: subject prefix automatically. Set saveToDrafts to true to save to the Drafts folder instead of sending. Sending (but not saving a draft) asks the user to confirm first. Sent emails are automatically copied to the Sent folder.",
179
+ annotations: {
180
+ readOnlyHint: false,
181
+ destructiveHint: false,
182
+ idempotentHint: false,
183
+ openWorldHint: true,
184
+ },
130
185
  inputSchema: {
131
186
  type: "object",
132
187
  properties: {
@@ -135,28 +190,14 @@ export const EMAIL_TOOLS = [
135
190
  items: { type: "string" },
136
191
  description: "Recipient email addresses.",
137
192
  },
138
- cc: {
139
- type: "array",
140
- items: { type: "string" },
141
- description: "CC email addresses.",
142
- },
143
- bcc: {
144
- type: "array",
145
- items: { type: "string" },
146
- description: "BCC email addresses.",
147
- },
193
+ cc: { type: "array", items: { type: "string" }, description: "CC email addresses." },
194
+ bcc: { type: "array", items: { type: "string" }, description: "BCC email addresses." },
148
195
  subject: {
149
196
  type: "string",
150
197
  description: "Email subject line. Required for new emails. When replyToUid is set and subject is omitted, automatically uses 'Re: <original subject>'. When provided explicitly, used as-is.",
151
198
  },
152
- text: {
153
- type: "string",
154
- description: "Plain text body.",
155
- },
156
- html: {
157
- type: "string",
158
- description: "HTML body.",
159
- },
199
+ text: { type: "string", description: "Plain text body." },
200
+ html: { type: "string", description: "HTML body." },
160
201
  attachments: {
161
202
  type: "array",
162
203
  items: {
@@ -167,10 +208,7 @@ export const EMAIL_TOOLS = [
167
208
  type: "string",
168
209
  description: "File path to attach. Disabled unless the server has EMAIL_ATTACHMENT_DIR set to an allowed directory; the resolved path must be inside it. Use content instead if unavailable.",
169
210
  },
170
- content: {
171
- type: "string",
172
- description: "String content to attach.",
173
- },
211
+ content: { type: "string", description: "String content to attach." },
174
212
  },
175
213
  required: ["filename"],
176
214
  },
@@ -188,48 +226,158 @@ export const EMAIL_TOOLS = [
188
226
  type: "boolean",
189
227
  description: "When true, saves the composed email to the Drafts folder instead of sending it. The draft will appear in any email client and can be edited there. Defaults to false.",
190
228
  },
229
+ from: {
230
+ type: "string",
231
+ description: "Optional visible From address. Must be SMTP_USER or listed in the server's SMTP_ALLOWED_FROM allowlist; anything else is rejected. SMTP envelope delivery still uses the account sender, so an address on a different domain than SMTP_USER may fail DMARC at the recipient.",
232
+ },
233
+ fromName: {
234
+ type: "string",
235
+ description: "Optional visible display name for the From header. Useful when multiple agents share one allowed sender address. Changes only the display name, never the address.",
236
+ },
191
237
  },
192
238
  required: ["to"],
193
239
  },
240
+ outputSchema: sendResultSchema,
241
+ handler: async (args, { imap, smtp }, ctx) => {
242
+ const to = Array.isArray(args.to) ? args.to : [args.to];
243
+ const cc = args.cc == null ? undefined : Array.isArray(args.cc) ? args.cc : [args.cc];
244
+ const bcc = args.bcc == null ? undefined : Array.isArray(args.bcc) ? args.bcc : [args.bcc];
245
+ const saveToDrafts = args.saveToDrafts || false;
246
+ // Validation: subject required when not replying
247
+ if (!args.subject && !args.replyToUid) {
248
+ return invalid("subject is required when not replying to an existing email");
249
+ }
250
+ // Saving a draft is reversible; actually putting mail on the wire is not.
251
+ if (!saveToDrafts) {
252
+ const recipients = [...to, ...(cc ?? []), ...(bcc ?? [])].join(", ");
253
+ const gate = confirmDestructive(ctx, "confirm_send_email", `Send this email to ${recipients}${args.subject ? ` with subject "${args.subject}"` : ""}? This cannot be undone.`);
254
+ if (gate.status === "interrupt")
255
+ return gate.result;
256
+ }
257
+ return run(async () => {
258
+ for (const att of args.attachments ?? []) {
259
+ if (att.path)
260
+ assertAttachmentPathAllowed(att.path);
261
+ }
262
+ const replyToFolder = args.replyToFolder || "INBOX";
263
+ let subject = args.subject;
264
+ // Threading: fetch original email for reply context
265
+ let inReplyTo;
266
+ let references;
267
+ if (args.replyToUid) {
268
+ const original = await imap.fetchEmail(replyToFolder, args.replyToUid);
269
+ inReplyTo = original.messageId;
270
+ references = [...(original.references || [])];
271
+ if (original.messageId && !references.includes(original.messageId)) {
272
+ references.push(original.messageId);
273
+ }
274
+ if (!subject) {
275
+ const origSubject = original.subject || "";
276
+ subject = origSubject.startsWith("Re:") ? origSubject : `Re: ${origSubject}`;
277
+ }
278
+ }
279
+ // Compose RFC 822 message
280
+ const from = smtp.formatFromHeader(smtp.resolveFromAddress(args.from), args.fromName);
281
+ const messageOptions = {
282
+ from,
283
+ to,
284
+ cc,
285
+ bcc,
286
+ subject: subject,
287
+ text: args.text,
288
+ html: args.html,
289
+ attachments: args.attachments,
290
+ inReplyTo,
291
+ references,
292
+ };
293
+ if (saveToDrafts) {
294
+ // Draft mode: keep Bcc in the saved message so a later send_draft
295
+ // can still deliver to it — the header is stripped at send time.
296
+ const rawMessage = await smtp.composeRawMessage(messageOptions, { keepBcc: true });
297
+ // APPEND to Drafts folder
298
+ const draftsFolder = await imap.getSpecialUseFolder("\\Drafts");
299
+ const appendResult = await imap.appendMessage(draftsFolder, rawMessage, [
300
+ "\\Draft",
301
+ "\\Seen",
302
+ ]);
303
+ return structured({
304
+ status: "draft",
305
+ uid: appendResult.uid,
306
+ folder: draftsFolder,
307
+ });
308
+ }
309
+ // Send mode: SMTP send + APPEND to Sent (Bcc stripped per RFC 2822 default)
310
+ const rawMessage = await smtp.composeRawMessage(messageOptions);
311
+ const envelope = {
312
+ from: smtp.config.smtp.user,
313
+ to: [...to, ...(cc || []), ...(bcc || [])],
314
+ };
315
+ const sendResult = await smtp.sendRawMessage(rawMessage, envelope);
316
+ let sentFolderPath = "Sent";
317
+ if (!smtp.config.autoSent) {
318
+ try {
319
+ sentFolderPath = await imap.getSpecialUseFolder("\\Sent");
320
+ await imap.appendMessage(sentFolderPath, rawMessage, ["\\Seen"]);
321
+ }
322
+ catch (appendError) {
323
+ console.error("[email-mcp] Failed to copy to Sent folder:", appendError);
324
+ }
325
+ }
326
+ return structured({
327
+ status: "sent",
328
+ messageId: sendResult.messageId,
329
+ folder: sentFolderPath,
330
+ });
331
+ });
332
+ },
194
333
  },
195
334
  {
196
335
  name: "move_email",
336
+ title: "Move Email",
197
337
  description: "Move one or more emails to a different IMAP folder.",
338
+ annotations: {
339
+ readOnlyHint: false,
340
+ destructiveHint: false,
341
+ idempotentHint: true,
342
+ openWorldHint: true,
343
+ },
198
344
  inputSchema: {
199
345
  type: "object",
200
346
  properties: {
201
- folder: {
202
- type: "string",
203
- description: "Source IMAP folder. Defaults to INBOX.",
204
- },
205
- uids: {
206
- type: "array",
207
- items: { type: "number" },
208
- description: "UIDs of emails to move.",
209
- },
210
- destination: {
211
- type: "string",
212
- description: "Destination folder path.",
213
- },
347
+ folder: { type: "string", description: "Source IMAP folder. Defaults to INBOX." },
348
+ uids: UIDS_PROP("UIDs of emails to move."),
349
+ destination: { type: "string", description: "Destination folder path." },
214
350
  },
215
351
  required: ["uids", "destination"],
216
352
  },
353
+ outputSchema: moveResultSchema,
354
+ handler: (args, { imap }) => run(async () => {
355
+ if (!Array.isArray(args.uids) || args.uids.length === 0) {
356
+ return invalid("uids must be a non-empty array of message UIDs");
357
+ }
358
+ await imap.moveEmails(args.folder || "INBOX", args.uids, args.destination);
359
+ return structured({
360
+ status: "moved",
361
+ uids: args.uids,
362
+ destination: args.destination,
363
+ });
364
+ }),
217
365
  },
218
366
  {
219
367
  name: "mark_email",
368
+ title: "Mark Email",
220
369
  description: 'Set or unset flags on one or more emails. Common flags: "\\Seen" (read), "\\Flagged" (starred).',
370
+ annotations: {
371
+ readOnlyHint: false,
372
+ destructiveHint: false,
373
+ idempotentHint: true,
374
+ openWorldHint: true,
375
+ },
221
376
  inputSchema: {
222
377
  type: "object",
223
378
  properties: {
224
- folder: {
225
- type: "string",
226
- description: "IMAP folder. Defaults to INBOX.",
227
- },
228
- uids: {
229
- type: "array",
230
- items: { type: "number" },
231
- description: "UIDs of emails to modify.",
232
- },
379
+ folder: FOLDER_PROP,
380
+ uids: UIDS_PROP("UIDs of emails to modify."),
233
381
  flags: {
234
382
  type: "array",
235
383
  items: { type: "string" },
@@ -243,23 +391,36 @@ export const EMAIL_TOOLS = [
243
391
  },
244
392
  required: ["uids", "flags"],
245
393
  },
394
+ outputSchema: markResultSchema,
395
+ handler: (args, { imap }) => run(async () => {
396
+ if (!Array.isArray(args.uids) || args.uids.length === 0) {
397
+ return invalid("uids must be a non-empty array of message UIDs");
398
+ }
399
+ const action = args.action || "add";
400
+ await imap.markEmails(args.folder || "INBOX", args.uids, args.flags, action);
401
+ return structured({
402
+ status: "updated",
403
+ uids: args.uids,
404
+ flags: args.flags,
405
+ action,
406
+ });
407
+ }),
246
408
  },
247
409
  {
248
410
  name: "delete_email",
249
- description: "Delete one or more emails. Moves to Trash by default, or permanently deletes if specified.",
250
- annotations: { destructiveHint: true },
411
+ title: "Delete Email",
412
+ description: "Delete one or more emails. Moves to Trash by default, or permanently deletes if specified. A permanent delete asks the user to confirm first.",
413
+ annotations: {
414
+ readOnlyHint: false,
415
+ destructiveHint: true,
416
+ idempotentHint: true,
417
+ openWorldHint: true,
418
+ },
251
419
  inputSchema: {
252
420
  type: "object",
253
421
  properties: {
254
- folder: {
255
- type: "string",
256
- description: "IMAP folder. Defaults to INBOX.",
257
- },
258
- uids: {
259
- type: "array",
260
- items: { type: "number" },
261
- description: "UIDs of emails to delete.",
262
- },
422
+ folder: FOLDER_PROP,
423
+ uids: UIDS_PROP("UIDs of emails to delete."),
263
424
  permanent: {
264
425
  type: "boolean",
265
426
  description: "If true, permanently delete instead of moving to Trash. Defaults to false.",
@@ -267,45 +428,69 @@ export const EMAIL_TOOLS = [
267
428
  },
268
429
  required: ["uids"],
269
430
  },
431
+ outputSchema: deleteResultSchema,
432
+ handler: async (args, { imap }, ctx) => {
433
+ if (!Array.isArray(args.uids) || args.uids.length === 0) {
434
+ return invalid("uids must be a non-empty array of message UIDs");
435
+ }
436
+ const permanent = args.permanent || false;
437
+ // A Trash move is recoverable; an expunge is not.
438
+ if (permanent) {
439
+ const gate = confirmDestructive(ctx, "confirm_delete_email", `Permanently delete ${args.uids.length} email(s) from ${args.folder || "INBOX"}? They cannot be recovered.`);
440
+ if (gate.status === "interrupt")
441
+ return gate.result;
442
+ }
443
+ return run(async () => {
444
+ await imap.deleteEmails(args.folder || "INBOX", args.uids, permanent);
445
+ return structured({
446
+ status: permanent ? "permanently_deleted" : "moved_to_trash",
447
+ uids: args.uids,
448
+ });
449
+ });
450
+ },
270
451
  },
271
452
  {
272
453
  name: "list_folders",
454
+ title: "List Folders",
273
455
  description: "List all IMAP folders with their paths and special-use flags (Inbox, Sent, Trash, etc.).",
274
- annotations: { readOnlyHint: true },
275
- inputSchema: {
276
- type: "object",
277
- properties: {},
278
- },
456
+ annotations: READ_ONLY,
457
+ inputSchema: { type: "object", properties: {} },
458
+ outputSchema: folderListSchema,
459
+ handler: (_args, { imap }) => run(async () => structured({ folders: await imap.listFolders() })),
279
460
  },
280
461
  {
281
462
  name: "create_folder",
463
+ title: "Create Folder",
282
464
  description: "Create a new IMAP folder.",
465
+ annotations: {
466
+ readOnlyHint: false,
467
+ destructiveHint: false,
468
+ idempotentHint: false,
469
+ openWorldHint: true,
470
+ },
283
471
  inputSchema: {
284
472
  type: "object",
285
473
  properties: {
286
- path: {
287
- type: "string",
288
- description: "Folder path to create (e.g., 'Projects/Work').",
289
- },
474
+ path: { type: "string", description: "Folder path to create (e.g., 'Projects/Work')." },
290
475
  },
291
476
  required: ["path"],
292
477
  },
478
+ outputSchema: createFolderResultSchema,
479
+ handler: (args, { imap }) => run(async () => {
480
+ await imap.createFolder(args.path);
481
+ return structured({ status: "created", path: args.path });
482
+ }),
293
483
  },
294
484
  {
295
485
  name: "download_attachment",
296
- description: "Download a specific attachment from an email. Returns the attachment content as base64.",
297
- annotations: { readOnlyHint: true },
486
+ title: "Download Attachment",
487
+ description: "Download a specific attachment from an email. Returns the bytes as an embedded binary resource; structured output carries the filename, content type and size.",
488
+ annotations: READ_ONLY,
298
489
  inputSchema: {
299
490
  type: "object",
300
491
  properties: {
301
- folder: {
302
- type: "string",
303
- description: "IMAP folder. Defaults to INBOX.",
304
- },
305
- uid: {
306
- type: "number",
307
- description: "UID of the email containing the attachment.",
308
- },
492
+ folder: FOLDER_PROP,
493
+ uid: { type: "number", description: "UID of the email containing the attachment." },
309
494
  partId: {
310
495
  type: "string",
311
496
  description: "MIME part ID of the attachment (from get_email attachment metadata).",
@@ -313,50 +498,94 @@ export const EMAIL_TOOLS = [
313
498
  },
314
499
  required: ["uid", "partId"],
315
500
  },
501
+ outputSchema: attachmentSchema,
502
+ handler: (args, { imap }) => run(async () => {
503
+ const folder = args.folder || "INBOX";
504
+ const attachment = await imap.downloadAttachment(folder, args.uid, args.partId);
505
+ return {
506
+ // The bytes ride in the resource block only — repeating the base64 in
507
+ // structuredContent would double the response for large attachments.
508
+ // Same reasoning as get_email_raw below.
509
+ content: [
510
+ {
511
+ type: "resource",
512
+ resource: {
513
+ uri: `imap://${encodeURIComponent(folder)}/${args.uid}/${encodeURIComponent(args.partId)}`,
514
+ mimeType: attachment.contentType,
515
+ blob: attachment.content.toString("base64"),
516
+ },
517
+ },
518
+ ],
519
+ structuredContent: {
520
+ filename: attachment.filename,
521
+ contentType: attachment.contentType,
522
+ size: attachment.size,
523
+ },
524
+ };
525
+ }),
316
526
  },
317
527
  {
318
528
  name: "get_email_raw",
319
- description: "Export an email as raw .eml (RFC 822 source). Useful for archival or forwarding.",
320
- annotations: { readOnlyHint: true },
529
+ title: "Get Raw Email",
530
+ description: "Export an email as raw .eml (RFC 822 source). Useful for archival or forwarding. The source is returned as an embedded message/rfc822 resource.",
531
+ annotations: READ_ONLY,
321
532
  inputSchema: {
322
533
  type: "object",
323
534
  properties: {
324
- folder: {
325
- type: "string",
326
- description: "IMAP folder. Defaults to INBOX.",
327
- },
328
- uid: {
329
- type: "number",
330
- description: "UID of the email to export.",
331
- },
535
+ folder: FOLDER_PROP,
536
+ uid: { type: "number", description: "UID of the email to export." },
332
537
  },
333
538
  required: ["uid"],
334
539
  },
540
+ outputSchema: rawEmailSchema,
541
+ handler: (args, { imap }) => run(async () => {
542
+ const folder = args.folder || "INBOX";
543
+ const raw = await imap.fetchRawEmail(folder, args.uid);
544
+ return {
545
+ // The source rides in the resource block rather than being repeated
546
+ // in both `content` and `structuredContent` — .eml payloads are large.
547
+ content: [
548
+ {
549
+ type: "resource",
550
+ resource: {
551
+ uri: `imap://${encodeURIComponent(folder)}/${args.uid}.eml`,
552
+ mimeType: "message/rfc822",
553
+ text: raw,
554
+ },
555
+ },
556
+ ],
557
+ structuredContent: { uid: args.uid, folder, size: raw.length },
558
+ };
559
+ }),
335
560
  },
336
561
  {
337
562
  name: "get_folder_status",
563
+ title: "Get Folder Status",
338
564
  description: "Get total and unread message counts for a folder via IMAP STATUS (single round-trip, no payload).",
339
- annotations: { readOnlyHint: true },
565
+ annotations: READ_ONLY,
340
566
  inputSchema: {
341
567
  type: "object",
342
568
  properties: {
343
- folder: {
344
- type: "string",
345
- description: "IMAP folder path. Defaults to INBOX.",
346
- },
569
+ folder: { type: "string", description: "IMAP folder path. Defaults to INBOX." },
347
570
  },
348
571
  },
572
+ outputSchema: folderStatusSchema,
573
+ handler: (args, { imap }) => run(async () => structured(await imap.getFolderStatus(args.folder || "INBOX"))),
349
574
  },
350
575
  {
351
576
  name: "send_draft",
352
- description: "Send an existing email draft from the Drafts folder. Fetches the draft's raw RFC 822 source, sends it via SMTP, copies it to the Sent folder, and removes it from Drafts. The draft must already exist — use send_email with saveToDrafts: true to create one.",
577
+ title: "Send Draft",
578
+ description: "Send an existing email draft from the Drafts folder. Fetches the draft's raw RFC 822 source, sends it via SMTP, copies it to the Sent folder, and removes it from Drafts. Asks the user to confirm before sending. The draft must already exist — use send_email with saveToDrafts: true to create one.",
579
+ annotations: {
580
+ readOnlyHint: false,
581
+ destructiveHint: false,
582
+ idempotentHint: false,
583
+ openWorldHint: true,
584
+ },
353
585
  inputSchema: {
354
586
  type: "object",
355
587
  properties: {
356
- uid: {
357
- type: "number",
358
- description: "UID of the draft email in the Drafts folder.",
359
- },
588
+ uid: { type: "number", description: "UID of the draft email in the Drafts folder." },
360
589
  folder: {
361
590
  type: "string",
362
591
  description: "IMAP folder containing the draft. Defaults to the server's Drafts folder.",
@@ -364,227 +593,15 @@ export const EMAIL_TOOLS = [
364
593
  },
365
594
  required: ["uid"],
366
595
  },
367
- },
368
- ];
369
- export async function handleEmailTool(name, args, imapService, smtpService) {
370
- try {
371
- const folder = args.folder || "INBOX";
372
- switch (name) {
373
- case "search_emails": {
374
- const searchParams = {
375
- hasWords: args.hasWords,
376
- body: args.body,
377
- from: args.from,
378
- to: args.to,
379
- cc: args.cc,
380
- bcc: args.bcc,
381
- subject: args.subject,
382
- since: args.since,
383
- before: args.before,
384
- unread: args.unread,
385
- flagged: args.flagged,
386
- hasAttachment: args.hasAttachment,
387
- tags: args.tags,
388
- };
389
- const limit = args.limit || 50;
390
- const offset = args.offset || 0;
391
- const sortBy = args.sortBy ?? "date";
392
- const sortOrder = args.sortOrder ?? "desc";
393
- const emails = await imapService.searchEmails(folder, searchParams, {
394
- limit,
395
- offset,
396
- sortBy: sortBy,
397
- sortOrder: sortOrder,
398
- });
399
- return ok(JSON.stringify(emails, null, 2));
400
- }
401
- case "get_email": {
402
- const uid = args.uid;
403
- const format = args.format || "markdown";
404
- const email = await imapService.fetchEmail(folder, uid);
405
- if (format === "markdown") {
406
- try {
407
- if (email.htmlBody) {
408
- email.markdownBody = await htmlToMarkdown(email.htmlBody);
409
- }
410
- else if (email.textBody) {
411
- email.markdownBody = email.textBody;
412
- }
413
- delete email.htmlBody;
414
- delete email.textBody;
415
- }
416
- catch {
417
- // Conversion failed — fall back to returning raw bodies unchanged
418
- }
419
- }
420
- else if (format === "text") {
421
- delete email.htmlBody;
422
- }
423
- else if (format === "html") {
424
- delete email.textBody;
425
- }
426
- return ok(JSON.stringify(email, null, 2));
427
- }
428
- case "send_email": {
429
- const to = Array.isArray(args.to) ? args.to : [args.to];
430
- const cc = args.cc == null
431
- ? undefined
432
- : Array.isArray(args.cc)
433
- ? args.cc
434
- : [args.cc];
435
- const bcc = args.bcc == null
436
- ? undefined
437
- : Array.isArray(args.bcc)
438
- ? args.bcc
439
- : [args.bcc];
440
- const text = args.text;
441
- const html = args.html;
442
- const attachments = args.attachments;
443
- for (const att of attachments ?? []) {
444
- if (att.path)
445
- assertAttachmentPathAllowed(att.path);
446
- }
447
- const replyToUid = args.replyToUid;
448
- const replyToFolder = args.replyToFolder || "INBOX";
449
- const saveToDrafts = args.saveToDrafts || false;
450
- let subject = args.subject;
451
- // Validation: subject required when not replying
452
- if (!subject && !replyToUid) {
453
- return error("subject is required when not replying to an existing email");
454
- }
455
- // Threading: fetch original email for reply context
456
- let inReplyTo;
457
- let references;
458
- if (replyToUid) {
459
- const original = await imapService.fetchEmail(replyToFolder, replyToUid);
460
- inReplyTo = original.messageId;
461
- references = [...(original.references || [])];
462
- if (original.messageId && !references.includes(original.messageId)) {
463
- references.push(original.messageId);
464
- }
465
- if (!subject) {
466
- const origSubject = original.subject || "";
467
- subject = origSubject.startsWith("Re:") ? origSubject : `Re: ${origSubject}`;
468
- }
469
- }
470
- // Compose RFC 822 message
471
- const from = smtpService.config.fromName
472
- ? `"${smtpService.config.fromName}" <${smtpService.config.smtp.user}>`
473
- : smtpService.config.smtp.user;
474
- const messageOptions = {
475
- from,
476
- to,
477
- cc,
478
- bcc,
479
- subject: subject,
480
- text,
481
- html,
482
- attachments,
483
- inReplyTo,
484
- references,
485
- };
486
- if (saveToDrafts) {
487
- // Draft mode: keep Bcc in the saved message so a later send_draft
488
- // can still deliver to it — the header is stripped at send time.
489
- const rawMessage = await smtpService.composeRawMessage(messageOptions, {
490
- keepBcc: true,
491
- });
492
- // APPEND to Drafts folder
493
- const draftsFolder = await imapService.getSpecialUseFolder("\\Drafts");
494
- const appendResult = await imapService.appendMessage(draftsFolder, rawMessage, [
495
- "\\Draft",
496
- "\\Seen",
497
- ]);
498
- return ok(JSON.stringify({ status: "draft", uid: appendResult.uid, folder: draftsFolder }));
499
- }
500
- // Send mode: SMTP send + APPEND to Sent (Bcc stripped per RFC 2822 default)
501
- const rawMessage = await smtpService.composeRawMessage(messageOptions);
502
- const envelope = {
503
- from: smtpService.config.smtp.user,
504
- to: [...to, ...(cc || []), ...(bcc || [])],
505
- };
506
- const sendResult = await smtpService.sendRawMessage(rawMessage, envelope);
507
- let sentFolderPath = "Sent";
508
- if (!smtpService.config.autoSent) {
509
- try {
510
- sentFolderPath = await imapService.getSpecialUseFolder("\\Sent");
511
- await imapService.appendMessage(sentFolderPath, rawMessage, ["\\Seen"]);
512
- }
513
- catch (appendError) {
514
- console.error("[email-mcp] Failed to copy to Sent folder:", appendError);
515
- }
516
- }
517
- return ok(JSON.stringify({
518
- status: "sent",
519
- messageId: sendResult.messageId,
520
- folder: sentFolderPath,
521
- }));
522
- }
523
- case "move_email": {
524
- const uids = args.uids;
525
- if (!Array.isArray(uids) || uids.length === 0) {
526
- return error("uids must be a non-empty array of message UIDs");
527
- }
528
- const destination = args.destination;
529
- await imapService.moveEmails(folder, uids, destination);
530
- return ok(JSON.stringify({ status: "moved", uids, destination }));
531
- }
532
- case "mark_email": {
533
- const uids = args.uids;
534
- if (!Array.isArray(uids) || uids.length === 0) {
535
- return error("uids must be a non-empty array of message UIDs");
536
- }
537
- const flags = args.flags;
538
- const action = args.action || "add";
539
- await imapService.markEmails(folder, uids, flags, action);
540
- return ok(JSON.stringify({ status: "updated", uids, flags, action }));
541
- }
542
- case "delete_email": {
543
- const uids = args.uids;
544
- if (!Array.isArray(uids) || uids.length === 0) {
545
- return error("uids must be a non-empty array of message UIDs");
546
- }
547
- const permanent = args.permanent || false;
548
- await imapService.deleteEmails(folder, uids, permanent);
549
- return ok(JSON.stringify({
550
- status: permanent ? "permanently_deleted" : "moved_to_trash",
551
- uids,
552
- }));
553
- }
554
- case "list_folders": {
555
- const folders = await imapService.listFolders();
556
- return ok(JSON.stringify(folders, null, 2));
557
- }
558
- case "create_folder": {
559
- const path = args.path;
560
- await imapService.createFolder(path);
561
- return ok(JSON.stringify({ status: "created", path }));
562
- }
563
- case "download_attachment": {
564
- const uid = args.uid;
565
- const partId = args.partId;
566
- const attachment = await imapService.downloadAttachment(folder, uid, partId);
567
- return ok(JSON.stringify({
568
- filename: attachment.filename,
569
- contentType: attachment.contentType,
570
- size: attachment.size,
571
- content: attachment.content.toString("base64"),
572
- }));
573
- }
574
- case "get_email_raw": {
575
- const uid = args.uid;
576
- const raw = await imapService.fetchRawEmail(folder, uid);
577
- return ok(raw);
578
- }
579
- case "get_folder_status": {
580
- const status = await imapService.getFolderStatus(folder);
581
- return ok(JSON.stringify(status));
582
- }
583
- case "send_draft": {
584
- const uid = args.uid;
585
- const draftFolder = args.folder || (await imapService.getSpecialUseFolder("\\Drafts"));
596
+ outputSchema: sendResultSchema,
597
+ handler: async (args, { imap, smtp }, ctx) => {
598
+ const gate = confirmDestructive(ctx, "confirm_send_draft", `Send draft ${args.uid}? Once sent it cannot be recalled.`);
599
+ if (gate.status === "interrupt")
600
+ return gate.result;
601
+ return run(async () => {
602
+ const draftFolder = args.folder || (await imap.getSpecialUseFolder("\\Drafts"));
586
603
  // Fetch raw source
587
- const rawSource = await imapService.fetchRawSource(draftFolder, uid);
604
+ const rawSource = await imap.fetchRawSource(draftFolder, args.uid);
588
605
  // Parse headers for SMTP envelope
589
606
  const parsed = await simpleParser(rawSource);
590
607
  const toAddrs = (Array.isArray(parsed.to) ? parsed.to : parsed.to ? [parsed.to] : [])
@@ -601,7 +618,7 @@ export async function handleEmailTool(name, args, imapService, smtpService) {
601
618
  .filter((a) => !!a);
602
619
  const allRecipients = [...toAddrs, ...ccAddrs, ...bccAddrs];
603
620
  if (allRecipients.length === 0) {
604
- return error("Draft has no recipients — cannot send");
621
+ return invalid("Draft has no recipients — cannot send");
605
622
  }
606
623
  // Send via SMTP. The envelope still carries bccAddrs (via
607
624
  // allRecipients) so the MTA delivers to them, but the Bcc header
@@ -609,44 +626,32 @@ export async function handleEmailTool(name, args, imapService, smtpService) {
609
626
  // transmitted copy while keeping rawSource intact for the Sent
610
627
  // folder append below (so the sender keeps a record of who was bcc'd).
611
628
  const envelope = {
612
- from: smtpService.config.smtp.user,
629
+ from: smtp.config.smtp.user,
613
630
  to: allRecipients,
614
631
  };
615
- const sendResult = await smtpService.sendRawMessage(stripBccHeader(rawSource), envelope);
632
+ const sendResult = await smtp.sendRawMessage(stripBccHeader(rawSource), envelope);
616
633
  // Copy to Sent
617
634
  let sentFolderPath = "Sent";
618
- if (!smtpService.config.autoSent) {
635
+ if (!smtp.config.autoSent) {
619
636
  try {
620
- sentFolderPath = await imapService.getSpecialUseFolder("\\Sent");
621
- await imapService.appendMessage(sentFolderPath, rawSource, ["\\Seen"]);
637
+ sentFolderPath = await imap.getSpecialUseFolder("\\Sent");
638
+ await imap.appendMessage(sentFolderPath, rawSource, ["\\Seen"]);
622
639
  }
623
640
  catch (appendError) {
624
641
  console.error("[email-mcp] Failed to copy to Sent folder:", appendError);
625
642
  }
626
643
  }
627
644
  // Delete draft (permanently — not move to Trash)
628
- await imapService.deleteEmails(draftFolder, [uid], true);
629
- return ok(JSON.stringify({
645
+ await imap.deleteEmails(draftFolder, [args.uid], true);
646
+ return structured({
630
647
  status: "sent",
631
648
  messageId: sendResult.messageId,
632
649
  folder: sentFolderPath,
633
- }));
634
- }
635
- default:
636
- return error(`Unknown tool: ${name}`);
637
- }
638
- }
639
- catch (err) {
640
- const pimError = toPimError(err instanceof Error ? err : new Error(String(err)));
641
- return error(`${pimError.message}${pimError.isRetryable ? " (retryable)" : ""}`);
642
- }
643
- }
644
- function ok(text) {
645
- return { content: [{ type: "text", text }] };
646
- }
647
- function error(text) {
648
- return { content: [{ type: "text", text }], isError: true };
649
- }
650
+ });
651
+ });
652
+ },
653
+ },
654
+ ];
650
655
  function stripBccHeader(raw) {
651
656
  const str = raw.toString("latin1");
652
657
  const sep = str.indexOf("\r\n\r\n");