@miguelarios/email-mcp 0.13.0 → 0.15.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.
@@ -2,9 +2,9 @@ import { realpathSync } from "node:fs";
2
2
  import { resolve, sep } from "node:path";
3
3
  import { confirmDestructive, fail, structured, toolError, } from "@miguelarios/pim-core/mcp";
4
4
  import { simpleParser } from "mailparser";
5
- import { htmlToMarkdown } from "../htmlToMarkdown.js";
5
+ import { htmlToMarkdown, sanitizeEmailHtml } from "../htmlToMarkdown.js";
6
6
  import { attachmentUri, rawEmailUri } from "../resources/imapResources.js";
7
- import { attachmentSchema, createFolderResultSchema, deleteResultSchema, emailFullSchema, folderListSchema, folderStatusSchema, markResultSchema, moveResultSchema, rawEmailSchema, searchResultSchema, sendResultSchema, } from "./emailSchemas.js";
7
+ import { attachmentSchema, copyResultSchema, createFolderResultSchema, deleteFolderResultSchema, deleteResultSchema, emailFullSchema, folderListSchema, folderStatusSchema, markResultSchema, moveResultSchema, rawEmailSchema, renameFolderResultSchema, searchResultSchema, sendResultSchema, threadResultSchema, } from "./emailSchemas.js";
8
8
  /**
9
9
  * Bytes above which a payload comes back as a resource link rather than inline
10
10
  * base64.
@@ -90,6 +90,220 @@ function assertAttachmentPathAllowed(p) {
90
90
  throw new Error(`attachment path is outside EMAIL_ATTACHMENT_DIR: ${p}`);
91
91
  }
92
92
  }
93
+ /** Lower-cased and trimmed, for comparing and de-duplicating addresses. */
94
+ function addressKey(address) {
95
+ return address.trim().toLowerCase();
96
+ }
97
+ /**
98
+ * Works out who a reply-all goes to, from the message being replied to.
99
+ *
100
+ * Every address the account owns is dropped, so the sender is not copied back
101
+ * to themselves, and an address that appears twice across the headers is kept
102
+ * once — at the strongest position it held, since To outranks Cc.
103
+ */
104
+ function deriveReplyAllRecipients(original, ownAddresses) {
105
+ // Seeding `placed` with our own addresses drops them and de-duplicates in
106
+ // one pass: an address already "placed" is never emitted again.
107
+ const placed = new Set(ownAddresses.map(addressKey));
108
+ const take = (addresses) => {
109
+ const out = [];
110
+ for (const entry of addresses ?? []) {
111
+ const address = entry?.address?.trim();
112
+ if (!address)
113
+ continue;
114
+ const key = addressKey(address);
115
+ if (placed.has(key))
116
+ continue;
117
+ placed.add(key);
118
+ out.push(address);
119
+ }
120
+ return out;
121
+ };
122
+ // RFC 5322 §3.6.2: Reply-To is precisely the author's statement of where
123
+ // replies belong, so it replaces From rather than joining it.
124
+ const authors = original.replyTo?.length ? original.replyTo : [original.from];
125
+ const to = [...take(authors), ...take(original.to)];
126
+ const cc = take(original.cc);
127
+ // A received message never carries Bcc; one read back out of Sent or Drafts
128
+ // does, and dropping it there would quietly narrow the thread.
129
+ const bcc = take(original.bcc);
130
+ // Everything on To was ours. Rather than send a message with an empty To
131
+ // header, promote the Cc list — which is what a mail client does.
132
+ if (to.length === 0 && cc.length > 0) {
133
+ return { to: cc, cc: [], bcc };
134
+ }
135
+ return { to, cc, bcc };
136
+ }
137
+ /**
138
+ * "On <date>, <name> <address> wrote:" — the line every mail client puts above
139
+ * a quote. The date clause is dropped rather than left empty when the original
140
+ * carries no Date header.
141
+ */
142
+ function attributionLine(original) {
143
+ const { name, address } = original.from ?? {};
144
+ const who = name && address ? `${name} <${address}>` : (address ?? name ?? "an unknown sender");
145
+ return original.date ? `On ${original.date}, ${who} wrote:` : `${who} wrote:`;
146
+ }
147
+ /**
148
+ * Prefixes each line with a quote marker, per RFC 3676 §4.5: a line that is
149
+ * already quoted gains a level rather than a space, so nesting depth survives
150
+ * a round trip through this function. A blank line becomes a bare ">" instead
151
+ * of "> " so the quote carries no trailing whitespace.
152
+ */
153
+ function quoteTextBody(body) {
154
+ return body
155
+ .replace(/\r\n/g, "\n")
156
+ .replace(/\s+$/, "")
157
+ .split("\n")
158
+ .map((line) => (line.startsWith(">") ? `>${line}` : line === "" ? ">" : `> ${line}`))
159
+ .join("\n");
160
+ }
161
+ function escapeHtml(value) {
162
+ return value
163
+ .replace(/&/g, "&amp;")
164
+ .replace(/</g, "&lt;")
165
+ .replace(/>/g, "&gt;")
166
+ .replace(/"/g, "&quot;");
167
+ }
168
+ /**
169
+ * The quoted original, in whichever body formats the reply itself uses.
170
+ *
171
+ * A reply's text and HTML parts must say the same thing, so each is quoted
172
+ * from the original's matching part where there is one and converted where
173
+ * there is not: HTML becomes markdown for the text quote, and text is escaped
174
+ * into the HTML quote. Conversion failure yields no quote for that part rather
175
+ * than failing the send — an unquoted reply still delivers.
176
+ */
177
+ async function quoteOriginalBodies(original, want) {
178
+ const attribution = attributionLine(original);
179
+ const quoted = {};
180
+ if (want.text) {
181
+ let source = original.textBody;
182
+ if (source === undefined && original.htmlBody) {
183
+ try {
184
+ source = await htmlToMarkdown(original.htmlBody);
185
+ }
186
+ catch {
187
+ source = undefined;
188
+ }
189
+ }
190
+ if (source?.trim()) {
191
+ quoted.text = `${attribution}\n\n${quoteTextBody(source)}`;
192
+ }
193
+ }
194
+ if (want.html) {
195
+ // The original's markup is sanitised before it goes back out. Quoting it
196
+ // verbatim would re-send the sender's script, style, tracking pixels and
197
+ // document wrapper under our own From, to every recipient of the reply —
198
+ // the text path escapes for the same reason.
199
+ const quotedHtml = original.htmlBody ? sanitizeEmailHtml(original.htmlBody).trim() : "";
200
+ const source = quotedHtml ||
201
+ (original.textBody?.trim()
202
+ ? `<pre style="white-space:pre-wrap;font-family:inherit">${escapeHtml(original.textBody)}</pre>`
203
+ : undefined);
204
+ if (source) {
205
+ const style = "margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex";
206
+ quoted.html = `<p>${escapeHtml(attribution)}</p><blockquote type="cite" style="${style}">${source}</blockquote>`;
207
+ }
208
+ }
209
+ return quoted;
210
+ }
211
+ /** "Name <address>", or the bare address when there is no display name. */
212
+ function formatAddress(entry) {
213
+ return entry.name ? `${entry.name} <${entry.address}>` : entry.address;
214
+ }
215
+ /**
216
+ * The header block every mail client writes above a forwarded message. Lines
217
+ * the original does not have are omitted rather than left blank, so a message
218
+ * with no Cc does not claim an empty one.
219
+ */
220
+ function forwardedHeaderLines(original) {
221
+ const lines = [`From: ${formatAddress(original.from)}`];
222
+ if (original.date)
223
+ lines.push(`Date: ${original.date}`);
224
+ if (original.subject)
225
+ lines.push(`Subject: ${original.subject}`);
226
+ if (original.to?.length)
227
+ lines.push(`To: ${original.to.map(formatAddress).join(", ")}`);
228
+ if (original.cc?.length)
229
+ lines.push(`Cc: ${original.cc.map(formatAddress).join(", ")}`);
230
+ return lines;
231
+ }
232
+ const FORWARD_SEPARATOR = "---------- Forwarded message ----------";
233
+ /**
234
+ * Builds the forwarded body in both formats.
235
+ *
236
+ * The text part is authoritative — every message can carry one — while the
237
+ * HTML part is emitted only when the original had HTML to preserve, since
238
+ * inventing markup for a plain-text original gains the recipient nothing.
239
+ */
240
+ async function buildForwardedBodies(original, note) {
241
+ const headerLines = forwardedHeaderLines(original);
242
+ let textOriginal = original.textBody;
243
+ if (textOriginal === undefined && original.htmlBody) {
244
+ try {
245
+ textOriginal = await htmlToMarkdown(original.htmlBody);
246
+ }
247
+ catch {
248
+ textOriginal = undefined;
249
+ }
250
+ }
251
+ const textParts = [FORWARD_SEPARATOR, ...headerLines, "", textOriginal ?? ""];
252
+ const text = [...(note ? [note, ""] : []), ...textParts].join("\n").replace(/\s+$/, "");
253
+ let html;
254
+ if (original.htmlBody) {
255
+ const headerHtml = headerLines.map((line) => escapeHtml(line)).join("<br>");
256
+ // The note's own line breaks have to survive into the HTML part, or a
257
+ // multi-line covering note renders as one run-on paragraph while the text
258
+ // part keeps its shape — and the two parts would no longer say the same
259
+ // thing, which is the whole point of emitting both.
260
+ const noteHtml = note ? `<p>${escapeHtml(note).replace(/\r?\n/g, "<br>")}</p>` : "";
261
+ const blockHtml = `<p>${escapeHtml(FORWARD_SEPARATOR)}<br>${headerHtml}</p>`;
262
+ html = `${noteHtml}${blockHtml}${original.htmlBody}`;
263
+ }
264
+ return { text, html };
265
+ }
266
+ /**
267
+ * The last mile shared by send_email and forward_email: compose the message,
268
+ * then either APPEND it to Drafts or put it on the wire and file a copy in
269
+ * Sent. Both callers reach it having already passed their confirmation gate.
270
+ */
271
+ async function deliver({ imap, smtp }, messageOptions, saveToDrafts) {
272
+ if (saveToDrafts) {
273
+ // Draft mode: keep Bcc in the saved message so a later send_draft can
274
+ // still deliver to it — the header is stripped at send time.
275
+ const rawMessage = await smtp.composeRawMessage(messageOptions, { keepBcc: true });
276
+ const draftsFolder = await imap.getSpecialUseFolder("\\Drafts");
277
+ const appendResult = await imap.appendMessage(draftsFolder, rawMessage, ["\\Draft", "\\Seen"]);
278
+ return structured({
279
+ status: "draft",
280
+ uid: appendResult.uid,
281
+ folder: draftsFolder,
282
+ });
283
+ }
284
+ // Send mode: SMTP send + APPEND to Sent (Bcc stripped per RFC 2822 default)
285
+ const rawMessage = await smtp.composeRawMessage(messageOptions);
286
+ const envelope = {
287
+ from: smtp.config.smtp.user,
288
+ to: [...messageOptions.to, ...(messageOptions.cc || []), ...(messageOptions.bcc || [])],
289
+ };
290
+ const sendResult = await smtp.sendRawMessage(rawMessage, envelope);
291
+ let sentFolderPath = "Sent";
292
+ if (!smtp.config.autoSent) {
293
+ try {
294
+ sentFolderPath = await imap.getSpecialUseFolder("\\Sent");
295
+ await imap.appendMessage(sentFolderPath, rawMessage, ["\\Seen"]);
296
+ }
297
+ catch (appendError) {
298
+ console.error("[email-mcp] Failed to copy to Sent folder:", appendError);
299
+ }
300
+ }
301
+ return structured({
302
+ status: "sent",
303
+ messageId: sendResult.messageId,
304
+ folder: sentFolderPath,
305
+ });
306
+ }
93
307
  /** Runs a handler body, converting anything thrown into a tool execution error. */
94
308
  async function run(body) {
95
309
  try {
@@ -117,7 +331,7 @@ export const EMAIL_TOOLS = [
117
331
  {
118
332
  name: "search_emails",
119
333
  title: "Search Emails",
120
- 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).",
334
+ 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. Sorting uses the server's native SORT command where the server supports it, which makes pagination exact at any size; where it does not, the result set is sorted here instead and for >1000 results a non-date sort is approximate (ordered within the page only).",
121
335
  annotations: READ_ONLY,
122
336
  inputSchema: {
123
337
  type: "object",
@@ -147,9 +361,18 @@ export const EMAIL_TOOLS = [
147
361
  },
148
362
  since: { type: "string", description: "Emails on or after this date (YYYY-MM-DD)." },
149
363
  before: { type: "string", description: "Emails before this date (YYYY-MM-DD)." },
150
- unread: { type: "boolean", description: "Filter by unread status." },
151
- flagged: { type: "boolean", description: "Filter by flagged/starred status." },
152
- hasAttachment: { type: "boolean", description: "Filter for emails with attachments." },
364
+ unread: {
365
+ type: "boolean",
366
+ description: 'Filter by unread status. true matches unread only, false matches read only. Omit to match both — do not send false to mean "any".',
367
+ },
368
+ flagged: {
369
+ type: "boolean",
370
+ description: 'Filter by flagged/starred status. true matches flagged only, false matches unflagged only. Omit to match both — do not send false to mean "any".',
371
+ },
372
+ hasAttachment: {
373
+ type: "boolean",
374
+ description: "true matches emails with attachments. false is not a filter (IMAP cannot express it) and matches both. Omit to match both.",
375
+ },
153
376
  tags: {
154
377
  type: "array",
155
378
  items: { type: "string" },
@@ -247,6 +470,62 @@ export const EMAIL_TOOLS = [
247
470
  return structured(email);
248
471
  }),
249
472
  },
473
+ {
474
+ name: "get_thread",
475
+ title: "Get Thread",
476
+ description: "Fetch the whole conversation a message belongs to, oldest first. Given any message in a thread, this follows its References chain back to the root and finds everything that cites it — or uses the server's own thread id where the server keeps one. By default it looks in the message's folder and the account's Sent folder, so your own replies are part of the conversation rather than missing from it; pass folders to search elsewhere. Returns summaries, not bodies — use get_email for the text of any one message.",
477
+ annotations: READ_ONLY,
478
+ inputSchema: {
479
+ type: "object",
480
+ properties: {
481
+ folder: {
482
+ type: "string",
483
+ description: "IMAP folder holding the message to start from. Defaults to INBOX.",
484
+ },
485
+ uid: {
486
+ type: "number",
487
+ description: "UID of any message in the thread — the root or any reply.",
488
+ },
489
+ folders: {
490
+ type: "array",
491
+ items: { type: "string" },
492
+ description: "Folders to search for thread members. Defaults to the message's folder plus the account's Sent folder. Pass this to search an archive as well; a folder that cannot be opened is skipped rather than failing the call.",
493
+ },
494
+ },
495
+ required: ["uid"],
496
+ },
497
+ outputSchema: threadResultSchema,
498
+ handler: (args, { imap }) => run(async () => {
499
+ const folder = args.folder || "INBOX";
500
+ let folders;
501
+ if (args.folders !== undefined) {
502
+ if (!Array.isArray(args.folders) || args.folders.length === 0) {
503
+ return invalid("folders must be a non-empty array of folder paths");
504
+ }
505
+ folders = args.folders;
506
+ }
507
+ else {
508
+ // Sent by default: a conversation with your own replies missing from
509
+ // it is not the conversation. An account with no resolvable Sent
510
+ // folder simply gets the one folder.
511
+ folders = [folder];
512
+ try {
513
+ const sent = await imap.getSpecialUseFolder("\\Sent");
514
+ if (sent !== folder)
515
+ folders.push(sent);
516
+ }
517
+ catch {
518
+ // No Sent folder to add.
519
+ }
520
+ }
521
+ const thread = await imap.fetchThread(folder, args.uid, folders);
522
+ return structured({
523
+ rootMessageId: thread.rootMessageId,
524
+ count: thread.messages.length,
525
+ messages: thread.messages,
526
+ });
527
+ }),
528
+ },
250
529
  {
251
530
  name: "send_email",
252
531
  title: "Send Email",
@@ -263,10 +542,18 @@ export const EMAIL_TOOLS = [
263
542
  to: {
264
543
  type: "array",
265
544
  items: { type: "string" },
266
- description: "Recipient email addresses.",
545
+ description: "Recipient email addresses. Required unless replyAll is set, which derives them from the message being replied to. Giving it explicitly overrides the derived list.",
546
+ },
547
+ cc: {
548
+ type: "array",
549
+ items: { type: "string" },
550
+ description: "CC email addresses. Under replyAll, omitting this derives the CC list from the original; giving it overrides that list.",
551
+ },
552
+ bcc: {
553
+ type: "array",
554
+ items: { type: "string" },
555
+ description: "BCC email addresses. Under replyAll, omitting this carries over the original's BCC when there is one to carry — see replyAll.",
267
556
  },
268
- cc: { type: "array", items: { type: "string" }, description: "CC email addresses." },
269
- bcc: { type: "array", items: { type: "string" }, description: "BCC email addresses." },
270
557
  subject: {
271
558
  type: "string",
272
559
  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.",
@@ -306,6 +593,14 @@ export const EMAIL_TOOLS = [
306
593
  type: "string",
307
594
  description: "IMAP folder containing the email referenced by replyToUid. Defaults to INBOX.",
308
595
  },
596
+ replyAll: {
597
+ type: "boolean",
598
+ description: "Reply to everyone on the original rather than only its sender. Requires replyToUid. To becomes the original's Reply-To (or its From) plus its To; CC becomes the original's CC; addresses this account owns are dropped so the reply is not sent back to the sender. When the original itself carries a BCC — which happens only for a message this account sent, read back from Sent or Drafts — those recipients are carried over too, and remain blind. An explicit to, cc or bcc overrides the corresponding derived list. Defaults to false.",
599
+ },
600
+ quoteOriginal: {
601
+ type: "boolean",
602
+ description: "When replying (replyToUid set), append the conventional quoted original below the new body: an 'On <date>, <sender> wrote:' attribution line, then the original as '>'-prefixed text or an HTML blockquote, matching whichever of text/html the reply uses. Defaults to true. Set false for a reply with no quote.",
603
+ },
309
604
  saveToDrafts: {
310
605
  type: "boolean",
311
606
  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.",
@@ -319,18 +614,22 @@ export const EMAIL_TOOLS = [
319
614
  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.",
320
615
  },
321
616
  },
322
- required: ["to"],
323
617
  },
324
618
  outputSchema: sendResultSchema,
325
619
  handler: async (args, { imap, smtp }, ctx) => {
326
- const to = Array.isArray(args.to) ? args.to : [args.to];
327
- const cc = args.cc == null ? undefined : Array.isArray(args.cc) ? args.cc : [args.cc];
328
- const bcc = args.bcc == null ? undefined : Array.isArray(args.bcc) ? args.bcc : [args.bcc];
620
+ const list = (value) => value == null ? undefined : Array.isArray(value) ? value : [value];
621
+ let to = list(args.to);
622
+ let cc = list(args.cc);
623
+ let bcc = list(args.bcc);
329
624
  const saveToDrafts = args.saveToDrafts || false;
625
+ const replyAll = args.replyAll || false;
330
626
  // Validation: subject required when not replying
331
627
  if (!args.subject && !args.replyToUid) {
332
628
  return invalid("subject is required when not replying to an existing email");
333
629
  }
630
+ if (replyAll && args.replyToUid === undefined) {
631
+ return invalid("replyAll requires replyToUid — there is no thread to reply to without it");
632
+ }
334
633
  // Attachments are resolved before the gate, not inside the handler body.
335
634
  // Every failure here is the request being wrong, and a confirmation spent
336
635
  // on a send that was never going to happen is worse than no confirmation:
@@ -353,6 +652,38 @@ export const EMAIL_TOOLS = [
353
652
  // pattern for them and would label plain caller error INTERNAL_ERROR.
354
653
  return invalid(err instanceof Error ? err.message : String(err));
355
654
  }
655
+ // The original is fetched before the gate, not inside the handler body,
656
+ // because under replyAll it is what decides the recipients — and a
657
+ // confirmation that cannot name who the mail is going to is not a
658
+ // confirmation. The cost is one extra FETCH per confirmation round trip.
659
+ let original;
660
+ if (args.replyToUid !== undefined) {
661
+ try {
662
+ original = await imap.fetchEmail(args.replyToFolder || "INBOX", args.replyToUid);
663
+ }
664
+ catch (err) {
665
+ return toolError(err);
666
+ }
667
+ }
668
+ if (replyAll && original) {
669
+ const derived = deriveReplyAllRecipients(original, smtp.ownAddresses());
670
+ // Per field, not all-or-nothing: an explicit `to` with a derived `cc`
671
+ // is a real request ("reply to everyone, but send it to Ada").
672
+ to ??= derived.to;
673
+ cc ??= derived.cc;
674
+ if (derived.bcc.length > 0)
675
+ bcc ??= derived.bcc;
676
+ // Checked on the effective recipients, after the overrides — not on
677
+ // the derived ones before them. A caller who supplied `to` has named
678
+ // someone, and the derivation finding only this account is then not a
679
+ // problem to refuse over.
680
+ if (to.length === 0 && (cc?.length ?? 0) === 0) {
681
+ return invalid("replyAll found no recipients other than this account — reply to the original's sender explicitly instead");
682
+ }
683
+ }
684
+ if (!to || to.length === 0) {
685
+ return invalid("to is required — pass recipient addresses, or set replyAll with replyToUid to derive them");
686
+ }
356
687
  // Saving a draft is reversible; actually putting mail on the wire is not.
357
688
  if (!saveToDrafts) {
358
689
  const recipients = [...to, ...(cc ?? []), ...(bcc ?? [])].join(", ");
@@ -361,13 +692,13 @@ export const EMAIL_TOOLS = [
361
692
  return gate.result;
362
693
  }
363
694
  return run(async () => {
364
- const replyToFolder = args.replyToFolder || "INBOX";
365
695
  let subject = args.subject;
366
- // Threading: fetch original email for reply context
696
+ // Threading, from the original already fetched above.
367
697
  let inReplyTo;
368
698
  let references;
369
- if (args.replyToUid) {
370
- const original = await imap.fetchEmail(replyToFolder, args.replyToUid);
699
+ let text = args.text;
700
+ let html = args.html;
701
+ if (original) {
371
702
  inReplyTo = original.messageId;
372
703
  references = [...(original.references || [])];
373
704
  if (original.messageId && !references.includes(original.messageId)) {
@@ -377,6 +708,24 @@ export const EMAIL_TOOLS = [
377
708
  const origSubject = original.subject || "";
378
709
  subject = origSubject.startsWith("Re:") ? origSubject : `Re: ${origSubject}`;
379
710
  }
711
+ if (args.quoteOriginal !== false) {
712
+ try {
713
+ // A reply with neither body is still a reply, and the quote is
714
+ // the only thing it can carry — so an empty reply quotes as text.
715
+ const quoted = await quoteOriginalBodies(original, {
716
+ text: text !== undefined || html === undefined,
717
+ html: html !== undefined,
718
+ });
719
+ if (quoted.text)
720
+ text = text ? `${text}\n\n${quoted.text}` : quoted.text;
721
+ if (quoted.html)
722
+ html = html ? `${html}\n${quoted.html}` : quoted.html;
723
+ }
724
+ catch {
725
+ // A quote is a courtesy, not the message. Whatever went wrong
726
+ // building it, the reply the caller wrote still goes out.
727
+ }
728
+ }
380
729
  }
381
730
  // Compose RFC 822 message
382
731
  const from = smtp.formatFromHeader(smtp.resolveFromAddress(args.from), args.fromName);
@@ -386,50 +735,118 @@ export const EMAIL_TOOLS = [
386
735
  cc,
387
736
  bcc,
388
737
  subject: subject,
389
- text: args.text,
390
- html: args.html,
738
+ text,
739
+ html,
391
740
  attachments: args.attachments === undefined ? undefined : attachments,
392
741
  inReplyTo,
393
742
  references,
394
743
  };
395
- if (saveToDrafts) {
396
- // Draft mode: keep Bcc in the saved message so a later send_draft
397
- // can still deliver to it — the header is stripped at send time.
398
- const rawMessage = await smtp.composeRawMessage(messageOptions, { keepBcc: true });
399
- // APPEND to Drafts folder
400
- const draftsFolder = await imap.getSpecialUseFolder("\\Drafts");
401
- const appendResult = await imap.appendMessage(draftsFolder, rawMessage, [
402
- "\\Draft",
403
- "\\Seen",
404
- ]);
405
- return structured({
406
- status: "draft",
407
- uid: appendResult.uid,
408
- folder: draftsFolder,
409
- });
410
- }
411
- // Send mode: SMTP send + APPEND to Sent (Bcc stripped per RFC 2822 default)
412
- const rawMessage = await smtp.composeRawMessage(messageOptions);
413
- const envelope = {
414
- from: smtp.config.smtp.user,
415
- to: [...to, ...(cc || []), ...(bcc || [])],
416
- };
417
- const sendResult = await smtp.sendRawMessage(rawMessage, envelope);
418
- let sentFolderPath = "Sent";
419
- if (!smtp.config.autoSent) {
420
- try {
421
- sentFolderPath = await imap.getSpecialUseFolder("\\Sent");
422
- await imap.appendMessage(sentFolderPath, rawMessage, ["\\Seen"]);
423
- }
424
- catch (appendError) {
425
- console.error("[email-mcp] Failed to copy to Sent folder:", appendError);
744
+ return deliver({ imap, smtp }, messageOptions, saveToDrafts);
745
+ });
746
+ },
747
+ },
748
+ {
749
+ name: "forward_email",
750
+ title: "Forward Email",
751
+ description: "Forward an existing message to new recipients, with an optional note above it. The body is reproduced under a '---------- Forwarded message ----------' header block naming the original's From, Date, Subject, To and Cc, and the original's attachments are re-attached unless includeAttachments is false. The subject becomes 'Fwd: <original subject>' unless given explicitly. A forward starts a new thread rather than joining the original's. Sending (but not saving a draft) asks the user to confirm first.",
752
+ annotations: {
753
+ readOnlyHint: false,
754
+ destructiveHint: false,
755
+ idempotentHint: false,
756
+ openWorldHint: true,
757
+ },
758
+ inputSchema: {
759
+ type: "object",
760
+ properties: {
761
+ folder: {
762
+ type: "string",
763
+ description: "IMAP folder containing the message to forward. Defaults to INBOX.",
764
+ },
765
+ uid: { type: "number", description: "UID of the message to forward." },
766
+ to: { type: "array", items: { type: "string" }, description: "Recipient addresses." },
767
+ cc: { type: "array", items: { type: "string" }, description: "CC addresses." },
768
+ bcc: { type: "array", items: { type: "string" }, description: "BCC addresses." },
769
+ note: {
770
+ type: "string",
771
+ description: "Optional text placed above the forwarded message, where a covering note goes.",
772
+ },
773
+ subject: {
774
+ type: "string",
775
+ description: "Subject line. Defaults to 'Fwd: <original subject>', and is not prefixed again when the original is already a forward.",
776
+ },
777
+ includeAttachments: {
778
+ type: "boolean",
779
+ description: "Re-attach the original's attachments. Defaults to true. Set false to forward the text alone — worth doing for a message with large attachments, since the bytes are pulled from IMAP and pushed back out over SMTP.",
780
+ },
781
+ saveToDrafts: {
782
+ type: "boolean",
783
+ description: "Save the forward to Drafts instead of sending it, so it can be edited in a mail client first. Defaults to false.",
784
+ },
785
+ from: {
786
+ type: "string",
787
+ description: "Optional visible From address. Must be SMTP_USER or listed in SMTP_ALLOWED_FROM; anything else is rejected.",
788
+ },
789
+ fromName: {
790
+ type: "string",
791
+ description: "Optional visible display name for the From header.",
792
+ },
793
+ },
794
+ required: ["uid", "to"],
795
+ },
796
+ outputSchema: sendResultSchema,
797
+ handler: async (args, services, ctx) => {
798
+ const { imap, smtp } = services;
799
+ const list = (value) => value == null ? undefined : Array.isArray(value) ? value : [value];
800
+ const to = list(args.to) ?? [];
801
+ const cc = list(args.cc);
802
+ const bcc = list(args.bcc);
803
+ const saveToDrafts = args.saveToDrafts || false;
804
+ if (to.length === 0) {
805
+ return invalid("to must be a non-empty array of recipient addresses");
806
+ }
807
+ // The original is read before the gate: its subject is what the
808
+ // confirmation names, and a UID that does not exist should fail as a
809
+ // lookup error rather than after the user has agreed to send it.
810
+ let original;
811
+ try {
812
+ original = await imap.fetchEmail(args.folder || "INBOX", args.uid);
813
+ }
814
+ catch (err) {
815
+ return toolError(err);
816
+ }
817
+ const subject = args.subject ??
818
+ (/^fwd:/i.test(original.subject || "")
819
+ ? original.subject
820
+ : `Fwd: ${original.subject || ""}`);
821
+ if (!saveToDrafts) {
822
+ const recipients = [...to, ...(cc ?? []), ...(bcc ?? [])].join(", ");
823
+ const gate = confirmDestructive(ctx, "confirm_forward_email", `Forward "${original.subject || "(no subject)"}" to ${recipients}? This cannot be undone.`);
824
+ if (gate.status === "interrupt")
825
+ return gate.result;
826
+ }
827
+ return run(async () => {
828
+ const { text, html } = await buildForwardedBodies(original, args.note);
829
+ // Attachments go IMAP → SMTP without passing through a tool result, so
830
+ // the EMAIL_MAX_INLINE_BYTES ceiling — which exists to keep payloads
831
+ // out of the model's context — deliberately does not apply here.
832
+ // includeAttachments: false is the control for a large message.
833
+ let attachments;
834
+ if (args.includeAttachments !== false && original.attachments.length > 0) {
835
+ attachments = [];
836
+ for (const att of original.attachments) {
837
+ const fetched = await imap.downloadAttachment(args.folder || "INBOX", args.uid, att.partId);
838
+ attachments.push({
839
+ filename: fetched.filename,
840
+ contentType: fetched.contentType,
841
+ content: fetched.content,
842
+ });
426
843
  }
427
844
  }
428
- return structured({
429
- status: "sent",
430
- messageId: sendResult.messageId,
431
- folder: sentFolderPath,
432
- });
845
+ const from = smtp.formatFromHeader(smtp.resolveFromAddress(args.from), args.fromName);
846
+ // No In-Reply-To or References: a forward starts its own thread. Adding
847
+ // them would file it under the original conversation in the recipient's
848
+ // client, which is not what forwarding to a new audience means.
849
+ return deliver(services, { from, to, cc, bcc, subject, text, html, attachments }, saveToDrafts);
433
850
  });
434
851
  },
435
852
  },
@@ -465,6 +882,50 @@ export const EMAIL_TOOLS = [
465
882
  });
466
883
  }),
467
884
  },
885
+ {
886
+ name: "copy_email",
887
+ title: "Copy Email",
888
+ description: "Copy one or more emails into another IMAP folder, leaving the originals where they are. Use move_email to relocate them instead. When the server supports UIDPLUS, the result pairs each source UID with the UID its copy took in the destination; otherwise only the source UIDs come back, and the copy still happened.",
889
+ annotations: {
890
+ readOnlyHint: false,
891
+ destructiveHint: false,
892
+ // Not idempotent: a second call adds a second copy rather than doing
893
+ // nothing, since each COPY allocates a fresh UID in the destination.
894
+ idempotentHint: false,
895
+ openWorldHint: true,
896
+ },
897
+ inputSchema: {
898
+ type: "object",
899
+ properties: {
900
+ folder: { type: "string", description: "Source IMAP folder. Defaults to INBOX." },
901
+ uids: UIDS_PROP("UIDs of emails to copy. They remain in the source folder."),
902
+ destination: {
903
+ type: "string",
904
+ description: "Destination folder path. It must already exist — create_folder first if not.",
905
+ },
906
+ },
907
+ required: ["uids", "destination"],
908
+ },
909
+ outputSchema: copyResultSchema,
910
+ handler: (args, { imap }) => run(async () => {
911
+ if (!Array.isArray(args.uids) || args.uids.length === 0) {
912
+ return invalid("uids must be a non-empty array of message UIDs");
913
+ }
914
+ const folder = args.folder || "INBOX";
915
+ // A self-copy is legal IMAP and duplicates every message in place,
916
+ // which is never what a caller reaching for "copy to a folder" wants.
917
+ if (folder === args.destination) {
918
+ return invalid(`destination is the source folder (${folder}) — this would duplicate the messages in place`);
919
+ }
920
+ const copied = await imap.copyEmails(folder, args.uids, args.destination);
921
+ return structured({
922
+ status: "copied",
923
+ uids: args.uids,
924
+ destination: args.destination,
925
+ ...(copied ? { copied } : {}),
926
+ });
927
+ }),
928
+ },
468
929
  {
469
930
  name: "mark_email",
470
931
  title: "Mark Email",
@@ -583,6 +1044,104 @@ export const EMAIL_TOOLS = [
583
1044
  return structured({ status: "created", path: args.path });
584
1045
  }),
585
1046
  },
1047
+ {
1048
+ name: "rename_folder",
1049
+ title: "Rename Folder",
1050
+ description: "Rename an IMAP folder, or move it in the hierarchy by giving a newPath under a different parent. Child folders move with it. Renaming INBOX is special-cased by IMAP: the server moves INBOX's messages into the new folder and leaves an empty INBOX behind, and INBOX's children do not follow. The server may normalise the path it reports back, so use the returned newPath rather than assuming the requested one.",
1051
+ annotations: {
1052
+ readOnlyHint: false,
1053
+ destructiveHint: false,
1054
+ // Not idempotent: the second call finds nothing at the old path and fails.
1055
+ idempotentHint: false,
1056
+ openWorldHint: true,
1057
+ },
1058
+ inputSchema: {
1059
+ type: "object",
1060
+ properties: {
1061
+ path: {
1062
+ type: "string",
1063
+ description: "Existing folder path to rename (e.g., 'Projects/Work').",
1064
+ },
1065
+ newPath: {
1066
+ type: "string",
1067
+ description: "New folder path. A path under a different parent moves the folder there, creating the parent only if the server does so implicitly — call create_folder first if it does not.",
1068
+ },
1069
+ },
1070
+ required: ["path", "newPath"],
1071
+ },
1072
+ outputSchema: renameFolderResultSchema,
1073
+ handler: (args, { imap }) => run(async () => {
1074
+ // Checked before connecting: a blank path is a RENAME the server would
1075
+ // answer with a protocol error naming neither argument, and IMAP has no
1076
+ // way to express "rename to nothing".
1077
+ const path = typeof args.path === "string" ? args.path.trim() : "";
1078
+ const newPath = typeof args.newPath === "string" ? args.newPath.trim() : "";
1079
+ if (!path)
1080
+ return invalid("path must be a non-empty folder path");
1081
+ if (!newPath)
1082
+ return invalid("newPath must be a non-empty folder path");
1083
+ if (path === newPath) {
1084
+ return invalid(`newPath is already the folder's path: ${path}`);
1085
+ }
1086
+ const renamed = await imap.renameFolder(path, newPath);
1087
+ return structured({ status: "renamed", ...renamed });
1088
+ }),
1089
+ },
1090
+ {
1091
+ name: "delete_folder",
1092
+ title: "Delete Folder",
1093
+ description: "Delete an IMAP folder and every message in it. This is irreversible — the messages are not moved to Trash — so the tool asks the user to confirm first, naming the folder and how many messages it holds. INBOX cannot be deleted. Whether a folder with sub-folders can be deleted is up to the server; many refuse, so delete or move the children first.",
1094
+ annotations: {
1095
+ readOnlyHint: false,
1096
+ destructiveHint: true,
1097
+ // A second call finds nothing to delete and fails, but the account ends
1098
+ // up in the same state either way.
1099
+ idempotentHint: true,
1100
+ openWorldHint: true,
1101
+ },
1102
+ inputSchema: {
1103
+ type: "object",
1104
+ properties: {
1105
+ path: { type: "string", description: "Folder path to delete (e.g., 'Projects/Work')." },
1106
+ },
1107
+ required: ["path"],
1108
+ },
1109
+ outputSchema: deleteFolderResultSchema,
1110
+ handler: async (args, { imap }, ctx) => {
1111
+ const path = typeof args.path === "string" ? args.path.trim() : "";
1112
+ if (!path)
1113
+ return invalid("path must be a non-empty folder path");
1114
+ // RFC 3501 §6.3.4 makes deleting INBOX an error, and a server's reply to
1115
+ // it is a bare NO. Rejecting here spends no confirmation on a request
1116
+ // that was never going to succeed.
1117
+ if (path.toUpperCase() === "INBOX") {
1118
+ return invalid("INBOX cannot be deleted — IMAP reserves it");
1119
+ }
1120
+ // STATUS before the gate so the prompt says what is actually at stake:
1121
+ // "delete Projects/Work" and "delete Projects/Work and its 412 messages"
1122
+ // are different decisions. A folder the server will not count is still
1123
+ // worth confirming, so a failure here is not fatal — the delete itself
1124
+ // raises the real error.
1125
+ let messages;
1126
+ try {
1127
+ messages = (await imap.getFolderStatus(path)).total;
1128
+ }
1129
+ catch {
1130
+ messages = undefined;
1131
+ }
1132
+ const gate = confirmDestructive(ctx, "confirm_delete_folder", `Delete the folder ${path}${messages === undefined ? "" : ` and the ${messages} message(s) in it`}? This cannot be undone — the messages do not go to Trash.`);
1133
+ if (gate.status === "interrupt")
1134
+ return gate.result;
1135
+ return run(async () => {
1136
+ await imap.deleteFolder(path);
1137
+ return structured({
1138
+ status: "deleted",
1139
+ path,
1140
+ ...(messages === undefined ? {} : { messages }),
1141
+ });
1142
+ });
1143
+ },
1144
+ },
586
1145
  {
587
1146
  name: "download_attachment",
588
1147
  title: "Download Attachment",