@miguelarios/email-mcp 0.14.0 → 0.16.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,247 @@ 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
+ * Returns a function that turns header address lists into plain addresses,
99
+ * dropping every address the account owns and any address an earlier call
100
+ * already emitted.
101
+ *
102
+ * Seeding the set with our own addresses drops them and de-duplicates in one
103
+ * pass: an address already "placed" is never emitted again.
104
+ */
105
+ function addressPicker(ownAddresses) {
106
+ const placed = new Set(ownAddresses.map(addressKey));
107
+ return (addresses) => {
108
+ const out = [];
109
+ for (const entry of addresses ?? []) {
110
+ const address = entry?.address?.trim();
111
+ if (!address)
112
+ continue;
113
+ const key = addressKey(address);
114
+ if (placed.has(key))
115
+ continue;
116
+ placed.add(key);
117
+ out.push(address);
118
+ }
119
+ return out;
120
+ };
121
+ }
122
+ /**
123
+ * The original's author, as far as replies are concerned. RFC 5322 §3.6.2:
124
+ * Reply-To is precisely the author's statement of where replies belong, so it
125
+ * replaces From rather than joining it.
126
+ */
127
+ function replyAuthors(original) {
128
+ return original.replyTo?.length ? original.replyTo : [original.from];
129
+ }
130
+ /**
131
+ * Works out who a plain reply goes to when the caller names nobody: the
132
+ * original's author.
133
+ *
134
+ * When that author is this account — a follow-up to a message read back out of
135
+ * Sent — the reply goes to the original's To instead, as a mail client does,
136
+ * since a reply addressed to ourselves is never what was meant.
137
+ */
138
+ function deriveReplyRecipients(original, ownAddresses) {
139
+ const take = addressPicker(ownAddresses);
140
+ const authors = take(replyAuthors(original));
141
+ return authors.length > 0 ? authors : take(original.to);
142
+ }
143
+ /**
144
+ * Works out who a reply-all goes to, from the message being replied to.
145
+ *
146
+ * Every address the account owns is dropped, so the sender is not copied back
147
+ * to themselves, and an address that appears twice across the headers is kept
148
+ * once — at the strongest position it held, since To outranks Cc.
149
+ */
150
+ function deriveReplyAllRecipients(original, ownAddresses) {
151
+ const take = addressPicker(ownAddresses);
152
+ const to = [...take(replyAuthors(original)), ...take(original.to)];
153
+ const cc = take(original.cc);
154
+ // A received message never carries Bcc; one read back out of Sent or Drafts
155
+ // does, and dropping it there would quietly narrow the thread.
156
+ const bcc = take(original.bcc);
157
+ // Everything on To was ours. Rather than send a message with an empty To
158
+ // header, promote the Cc list — which is what a mail client does.
159
+ if (to.length === 0 && cc.length > 0) {
160
+ return { to: cc, cc: [], bcc };
161
+ }
162
+ return { to, cc, bcc };
163
+ }
164
+ /**
165
+ * "On <date>, <name> <address> wrote:" — the line every mail client puts above
166
+ * a quote. The date clause is dropped rather than left empty when the original
167
+ * carries no Date header.
168
+ */
169
+ function attributionLine(original) {
170
+ const { name, address } = original.from ?? {};
171
+ const who = name && address ? `${name} <${address}>` : (address ?? name ?? "an unknown sender");
172
+ return original.date ? `On ${original.date}, ${who} wrote:` : `${who} wrote:`;
173
+ }
174
+ /**
175
+ * Prefixes each line with a quote marker, per RFC 3676 §4.5: a line that is
176
+ * already quoted gains a level rather than a space, so nesting depth survives
177
+ * a round trip through this function. A blank line becomes a bare ">" instead
178
+ * of "> " so the quote carries no trailing whitespace.
179
+ */
180
+ function quoteTextBody(body) {
181
+ return body
182
+ .replace(/\r\n/g, "\n")
183
+ .replace(/\s+$/, "")
184
+ .split("\n")
185
+ .map((line) => (line.startsWith(">") ? `>${line}` : line === "" ? ">" : `> ${line}`))
186
+ .join("\n");
187
+ }
188
+ function escapeHtml(value) {
189
+ return value
190
+ .replace(/&/g, "&amp;")
191
+ .replace(/</g, "&lt;")
192
+ .replace(/>/g, "&gt;")
193
+ .replace(/"/g, "&quot;");
194
+ }
195
+ /**
196
+ * The quoted original, in whichever body formats the reply itself uses.
197
+ *
198
+ * A reply's text and HTML parts must say the same thing, so each is quoted
199
+ * from the original's matching part where there is one and converted where
200
+ * there is not: HTML becomes markdown for the text quote, and text is escaped
201
+ * into the HTML quote. Conversion failure yields no quote for that part rather
202
+ * than failing the send — an unquoted reply still delivers.
203
+ */
204
+ async function quoteOriginalBodies(original, want) {
205
+ const attribution = attributionLine(original);
206
+ const quoted = {};
207
+ if (want.text) {
208
+ let source = original.textBody;
209
+ if (source === undefined && original.htmlBody) {
210
+ try {
211
+ source = await htmlToMarkdown(original.htmlBody);
212
+ }
213
+ catch {
214
+ source = undefined;
215
+ }
216
+ }
217
+ if (source?.trim()) {
218
+ quoted.text = `${attribution}\n\n${quoteTextBody(source)}`;
219
+ }
220
+ }
221
+ if (want.html) {
222
+ // The original's markup is sanitised before it goes back out. Quoting it
223
+ // verbatim would re-send the sender's script, style, tracking pixels and
224
+ // document wrapper under our own From, to every recipient of the reply —
225
+ // the text path escapes for the same reason.
226
+ const quotedHtml = original.htmlBody ? sanitizeEmailHtml(original.htmlBody).trim() : "";
227
+ const source = quotedHtml ||
228
+ (original.textBody?.trim()
229
+ ? `<pre style="white-space:pre-wrap;font-family:inherit">${escapeHtml(original.textBody)}</pre>`
230
+ : undefined);
231
+ if (source) {
232
+ const style = "margin:0 0 0 0.8ex;border-left:2px solid #ccc;padding-left:1ex";
233
+ quoted.html = `<p>${escapeHtml(attribution)}</p><blockquote type="cite" style="${style}">${source}</blockquote>`;
234
+ }
235
+ }
236
+ return quoted;
237
+ }
238
+ /** "Name <address>", or the bare address when there is no display name. */
239
+ function formatAddress(entry) {
240
+ return entry.name ? `${entry.name} <${entry.address}>` : entry.address;
241
+ }
242
+ /**
243
+ * The header block every mail client writes above a forwarded message. Lines
244
+ * the original does not have are omitted rather than left blank, so a message
245
+ * with no Cc does not claim an empty one.
246
+ */
247
+ function forwardedHeaderLines(original) {
248
+ const lines = [`From: ${formatAddress(original.from)}`];
249
+ if (original.date)
250
+ lines.push(`Date: ${original.date}`);
251
+ if (original.subject)
252
+ lines.push(`Subject: ${original.subject}`);
253
+ if (original.to?.length)
254
+ lines.push(`To: ${original.to.map(formatAddress).join(", ")}`);
255
+ if (original.cc?.length)
256
+ lines.push(`Cc: ${original.cc.map(formatAddress).join(", ")}`);
257
+ return lines;
258
+ }
259
+ const FORWARD_SEPARATOR = "---------- Forwarded message ----------";
260
+ /**
261
+ * Builds the forwarded body in both formats.
262
+ *
263
+ * The text part is authoritative — every message can carry one — while the
264
+ * HTML part is emitted only when the original had HTML to preserve, since
265
+ * inventing markup for a plain-text original gains the recipient nothing.
266
+ */
267
+ async function buildForwardedBodies(original, note) {
268
+ const headerLines = forwardedHeaderLines(original);
269
+ let textOriginal = original.textBody;
270
+ if (textOriginal === undefined && original.htmlBody) {
271
+ try {
272
+ textOriginal = await htmlToMarkdown(original.htmlBody);
273
+ }
274
+ catch {
275
+ textOriginal = undefined;
276
+ }
277
+ }
278
+ const textParts = [FORWARD_SEPARATOR, ...headerLines, "", textOriginal ?? ""];
279
+ const text = [...(note ? [note, ""] : []), ...textParts].join("\n").replace(/\s+$/, "");
280
+ let html;
281
+ if (original.htmlBody) {
282
+ const headerHtml = headerLines.map((line) => escapeHtml(line)).join("<br>");
283
+ // The note's own line breaks have to survive into the HTML part, or a
284
+ // multi-line covering note renders as one run-on paragraph while the text
285
+ // part keeps its shape — and the two parts would no longer say the same
286
+ // thing, which is the whole point of emitting both.
287
+ const noteHtml = note ? `<p>${escapeHtml(note).replace(/\r?\n/g, "<br>")}</p>` : "";
288
+ const blockHtml = `<p>${escapeHtml(FORWARD_SEPARATOR)}<br>${headerHtml}</p>`;
289
+ html = `${noteHtml}${blockHtml}${original.htmlBody}`;
290
+ }
291
+ return { text, html };
292
+ }
293
+ /**
294
+ * The last mile shared by send_email and forward_email: compose the message,
295
+ * then either APPEND it to Drafts or put it on the wire and file a copy in
296
+ * Sent. Both callers reach it having already passed their confirmation gate.
297
+ */
298
+ async function deliver({ imap, smtp }, messageOptions, saveToDrafts) {
299
+ if (saveToDrafts) {
300
+ // Draft mode: keep Bcc in the saved message so a later send_draft can
301
+ // still deliver to it — the header is stripped at send time.
302
+ const rawMessage = await smtp.composeRawMessage(messageOptions, { keepBcc: true });
303
+ const draftsFolder = await imap.getSpecialUseFolder("\\Drafts");
304
+ const appendResult = await imap.appendMessage(draftsFolder, rawMessage, ["\\Draft", "\\Seen"]);
305
+ return structured({
306
+ status: "draft",
307
+ uid: appendResult.uid,
308
+ folder: draftsFolder,
309
+ });
310
+ }
311
+ // Send mode: SMTP send + APPEND to Sent (Bcc stripped per RFC 2822 default)
312
+ const rawMessage = await smtp.composeRawMessage(messageOptions);
313
+ const envelope = {
314
+ from: smtp.config.smtp.user,
315
+ to: [...messageOptions.to, ...(messageOptions.cc || []), ...(messageOptions.bcc || [])],
316
+ };
317
+ const sendResult = await smtp.sendRawMessage(rawMessage, envelope);
318
+ let sentFolderPath = "Sent";
319
+ if (!smtp.config.autoSent) {
320
+ try {
321
+ sentFolderPath = await imap.getSpecialUseFolder("\\Sent");
322
+ await imap.appendMessage(sentFolderPath, rawMessage, ["\\Seen"]);
323
+ }
324
+ catch (appendError) {
325
+ console.error("[email-mcp] Failed to copy to Sent folder:", appendError);
326
+ }
327
+ }
328
+ return structured({
329
+ status: "sent",
330
+ messageId: sendResult.messageId,
331
+ folder: sentFolderPath,
332
+ });
333
+ }
93
334
  /** Runs a handler body, converting anything thrown into a tool execution error. */
94
335
  async function run(body) {
95
336
  try {
@@ -117,7 +358,7 @@ export const EMAIL_TOOLS = [
117
358
  {
118
359
  name: "search_emails",
119
360
  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).",
361
+ 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
362
  annotations: READ_ONLY,
122
363
  inputSchema: {
123
364
  type: "object",
@@ -256,10 +497,66 @@ export const EMAIL_TOOLS = [
256
497
  return structured(email);
257
498
  }),
258
499
  },
500
+ {
501
+ name: "get_thread",
502
+ title: "Get Thread",
503
+ 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.",
504
+ annotations: READ_ONLY,
505
+ inputSchema: {
506
+ type: "object",
507
+ properties: {
508
+ folder: {
509
+ type: "string",
510
+ description: "IMAP folder holding the message to start from. Defaults to INBOX.",
511
+ },
512
+ uid: {
513
+ type: "number",
514
+ description: "UID of any message in the thread — the root or any reply.",
515
+ },
516
+ folders: {
517
+ type: "array",
518
+ items: { type: "string" },
519
+ 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.",
520
+ },
521
+ },
522
+ required: ["uid"],
523
+ },
524
+ outputSchema: threadResultSchema,
525
+ handler: (args, { imap }) => run(async () => {
526
+ const folder = args.folder || "INBOX";
527
+ let folders;
528
+ if (args.folders !== undefined) {
529
+ if (!Array.isArray(args.folders) || args.folders.length === 0) {
530
+ return invalid("folders must be a non-empty array of folder paths");
531
+ }
532
+ folders = args.folders;
533
+ }
534
+ else {
535
+ // Sent by default: a conversation with your own replies missing from
536
+ // it is not the conversation. An account with no resolvable Sent
537
+ // folder simply gets the one folder.
538
+ folders = [folder];
539
+ try {
540
+ const sent = await imap.getSpecialUseFolder("\\Sent");
541
+ if (sent !== folder)
542
+ folders.push(sent);
543
+ }
544
+ catch {
545
+ // No Sent folder to add.
546
+ }
547
+ }
548
+ const thread = await imap.fetchThread(folder, args.uid, folders);
549
+ return structured({
550
+ rootMessageId: thread.rootMessageId,
551
+ count: thread.messages.length,
552
+ messages: thread.messages,
553
+ });
554
+ }),
555
+ },
259
556
  {
260
557
  name: "send_email",
261
558
  title: "Send Email",
262
- 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.",
559
+ 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, sets correct In-Reply-To/References headers and Re: subject prefix automatically, and addresses the reply to the original's sender unless to is given. 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.",
263
560
  annotations: {
264
561
  readOnlyHint: false,
265
562
  destructiveHint: false,
@@ -272,10 +569,18 @@ export const EMAIL_TOOLS = [
272
569
  to: {
273
570
  type: "array",
274
571
  items: { type: "string" },
275
- description: "Recipient email addresses.",
572
+ description: "Recipient email addresses. Required for a new email. When replying (replyToUid set) and omitted, defaults to the original's Reply-To (or its From) — or, with replyAll, to everyone on the original. Giving it explicitly overrides the derived list.",
573
+ },
574
+ cc: {
575
+ type: "array",
576
+ items: { type: "string" },
577
+ description: "CC email addresses. Under replyAll, omitting this derives the CC list from the original; giving it overrides that list.",
578
+ },
579
+ bcc: {
580
+ type: "array",
581
+ items: { type: "string" },
582
+ description: "BCC email addresses. Under replyAll, omitting this carries over the original's BCC when there is one to carry — see replyAll.",
276
583
  },
277
- cc: { type: "array", items: { type: "string" }, description: "CC email addresses." },
278
- bcc: { type: "array", items: { type: "string" }, description: "BCC email addresses." },
279
584
  subject: {
280
585
  type: "string",
281
586
  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.",
@@ -315,6 +620,14 @@ export const EMAIL_TOOLS = [
315
620
  type: "string",
316
621
  description: "IMAP folder containing the email referenced by replyToUid. Defaults to INBOX.",
317
622
  },
623
+ replyAll: {
624
+ type: "boolean",
625
+ 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.",
626
+ },
627
+ quoteOriginal: {
628
+ type: "boolean",
629
+ 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.",
630
+ },
318
631
  saveToDrafts: {
319
632
  type: "boolean",
320
633
  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.",
@@ -328,18 +641,22 @@ export const EMAIL_TOOLS = [
328
641
  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.",
329
642
  },
330
643
  },
331
- required: ["to"],
332
644
  },
333
645
  outputSchema: sendResultSchema,
334
646
  handler: async (args, { imap, smtp }, ctx) => {
335
- const to = Array.isArray(args.to) ? args.to : [args.to];
336
- const cc = args.cc == null ? undefined : Array.isArray(args.cc) ? args.cc : [args.cc];
337
- const bcc = args.bcc == null ? undefined : Array.isArray(args.bcc) ? args.bcc : [args.bcc];
647
+ const list = (value) => value == null ? undefined : Array.isArray(value) ? value : [value];
648
+ let to = list(args.to);
649
+ let cc = list(args.cc);
650
+ let bcc = list(args.bcc);
338
651
  const saveToDrafts = args.saveToDrafts || false;
652
+ const replyAll = args.replyAll || false;
339
653
  // Validation: subject required when not replying
340
654
  if (!args.subject && !args.replyToUid) {
341
655
  return invalid("subject is required when not replying to an existing email");
342
656
  }
657
+ if (replyAll && args.replyToUid === undefined) {
658
+ return invalid("replyAll requires replyToUid — there is no thread to reply to without it");
659
+ }
343
660
  // Attachments are resolved before the gate, not inside the handler body.
344
661
  // Every failure here is the request being wrong, and a confirmation spent
345
662
  // on a send that was never going to happen is worse than no confirmation:
@@ -362,6 +679,46 @@ export const EMAIL_TOOLS = [
362
679
  // pattern for them and would label plain caller error INTERNAL_ERROR.
363
680
  return invalid(err instanceof Error ? err.message : String(err));
364
681
  }
682
+ // The original is fetched before the gate, not inside the handler body,
683
+ // because under replyAll it is what decides the recipients — and a
684
+ // confirmation that cannot name who the mail is going to is not a
685
+ // confirmation. The cost is one extra FETCH per confirmation round trip.
686
+ let original;
687
+ if (args.replyToUid !== undefined) {
688
+ try {
689
+ original = await imap.fetchEmail(args.replyToFolder || "INBOX", args.replyToUid);
690
+ }
691
+ catch (err) {
692
+ return toolError(err);
693
+ }
694
+ }
695
+ if (replyAll && original) {
696
+ const derived = deriveReplyAllRecipients(original, smtp.ownAddresses());
697
+ // Per field, not all-or-nothing: an explicit `to` with a derived `cc`
698
+ // is a real request ("reply to everyone, but send it to Ada").
699
+ to ??= derived.to;
700
+ cc ??= derived.cc;
701
+ if (derived.bcc.length > 0)
702
+ bcc ??= derived.bcc;
703
+ // Checked on the effective recipients, after the overrides — not on
704
+ // the derived ones before them. A caller who supplied `to` has named
705
+ // someone, and the derivation finding only this account is then not a
706
+ // problem to refuse over.
707
+ if (to.length === 0 && (cc?.length ?? 0) === 0) {
708
+ return invalid("replyAll found no recipients other than this account — reply to the original's sender explicitly instead");
709
+ }
710
+ }
711
+ else if (original && to === undefined) {
712
+ // A plain reply goes back to whoever wrote the original. Only an absent
713
+ // `to` is filled in: an explicit empty list is the caller's own word.
714
+ to = deriveReplyRecipients(original, smtp.ownAddresses());
715
+ if (to.length === 0) {
716
+ return invalid("the original has no sender other than this account to reply to — pass to explicitly");
717
+ }
718
+ }
719
+ if (!to || to.length === 0) {
720
+ return invalid("to is required — pass recipient addresses, or set replyToUid to reply to the original's sender");
721
+ }
365
722
  // Saving a draft is reversible; actually putting mail on the wire is not.
366
723
  if (!saveToDrafts) {
367
724
  const recipients = [...to, ...(cc ?? []), ...(bcc ?? [])].join(", ");
@@ -370,13 +727,13 @@ export const EMAIL_TOOLS = [
370
727
  return gate.result;
371
728
  }
372
729
  return run(async () => {
373
- const replyToFolder = args.replyToFolder || "INBOX";
374
730
  let subject = args.subject;
375
- // Threading: fetch original email for reply context
731
+ // Threading, from the original already fetched above.
376
732
  let inReplyTo;
377
733
  let references;
378
- if (args.replyToUid) {
379
- const original = await imap.fetchEmail(replyToFolder, args.replyToUid);
734
+ let text = args.text;
735
+ let html = args.html;
736
+ if (original) {
380
737
  inReplyTo = original.messageId;
381
738
  references = [...(original.references || [])];
382
739
  if (original.messageId && !references.includes(original.messageId)) {
@@ -386,6 +743,24 @@ export const EMAIL_TOOLS = [
386
743
  const origSubject = original.subject || "";
387
744
  subject = origSubject.startsWith("Re:") ? origSubject : `Re: ${origSubject}`;
388
745
  }
746
+ if (args.quoteOriginal !== false) {
747
+ try {
748
+ // A reply with neither body is still a reply, and the quote is
749
+ // the only thing it can carry — so an empty reply quotes as text.
750
+ const quoted = await quoteOriginalBodies(original, {
751
+ text: text !== undefined || html === undefined,
752
+ html: html !== undefined,
753
+ });
754
+ if (quoted.text)
755
+ text = text ? `${text}\n\n${quoted.text}` : quoted.text;
756
+ if (quoted.html)
757
+ html = html ? `${html}\n${quoted.html}` : quoted.html;
758
+ }
759
+ catch {
760
+ // A quote is a courtesy, not the message. Whatever went wrong
761
+ // building it, the reply the caller wrote still goes out.
762
+ }
763
+ }
389
764
  }
390
765
  // Compose RFC 822 message
391
766
  const from = smtp.formatFromHeader(smtp.resolveFromAddress(args.from), args.fromName);
@@ -395,50 +770,118 @@ export const EMAIL_TOOLS = [
395
770
  cc,
396
771
  bcc,
397
772
  subject: subject,
398
- text: args.text,
399
- html: args.html,
773
+ text,
774
+ html,
400
775
  attachments: args.attachments === undefined ? undefined : attachments,
401
776
  inReplyTo,
402
777
  references,
403
778
  };
404
- if (saveToDrafts) {
405
- // Draft mode: keep Bcc in the saved message so a later send_draft
406
- // can still deliver to it — the header is stripped at send time.
407
- const rawMessage = await smtp.composeRawMessage(messageOptions, { keepBcc: true });
408
- // APPEND to Drafts folder
409
- const draftsFolder = await imap.getSpecialUseFolder("\\Drafts");
410
- const appendResult = await imap.appendMessage(draftsFolder, rawMessage, [
411
- "\\Draft",
412
- "\\Seen",
413
- ]);
414
- return structured({
415
- status: "draft",
416
- uid: appendResult.uid,
417
- folder: draftsFolder,
418
- });
419
- }
420
- // Send mode: SMTP send + APPEND to Sent (Bcc stripped per RFC 2822 default)
421
- const rawMessage = await smtp.composeRawMessage(messageOptions);
422
- const envelope = {
423
- from: smtp.config.smtp.user,
424
- to: [...to, ...(cc || []), ...(bcc || [])],
425
- };
426
- const sendResult = await smtp.sendRawMessage(rawMessage, envelope);
427
- let sentFolderPath = "Sent";
428
- if (!smtp.config.autoSent) {
429
- try {
430
- sentFolderPath = await imap.getSpecialUseFolder("\\Sent");
431
- await imap.appendMessage(sentFolderPath, rawMessage, ["\\Seen"]);
432
- }
433
- catch (appendError) {
434
- console.error("[email-mcp] Failed to copy to Sent folder:", appendError);
779
+ return deliver({ imap, smtp }, messageOptions, saveToDrafts);
780
+ });
781
+ },
782
+ },
783
+ {
784
+ name: "forward_email",
785
+ title: "Forward Email",
786
+ 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.",
787
+ annotations: {
788
+ readOnlyHint: false,
789
+ destructiveHint: false,
790
+ idempotentHint: false,
791
+ openWorldHint: true,
792
+ },
793
+ inputSchema: {
794
+ type: "object",
795
+ properties: {
796
+ folder: {
797
+ type: "string",
798
+ description: "IMAP folder containing the message to forward. Defaults to INBOX.",
799
+ },
800
+ uid: { type: "number", description: "UID of the message to forward." },
801
+ to: { type: "array", items: { type: "string" }, description: "Recipient addresses." },
802
+ cc: { type: "array", items: { type: "string" }, description: "CC addresses." },
803
+ bcc: { type: "array", items: { type: "string" }, description: "BCC addresses." },
804
+ note: {
805
+ type: "string",
806
+ description: "Optional text placed above the forwarded message, where a covering note goes.",
807
+ },
808
+ subject: {
809
+ type: "string",
810
+ description: "Subject line. Defaults to 'Fwd: <original subject>', and is not prefixed again when the original is already a forward.",
811
+ },
812
+ includeAttachments: {
813
+ type: "boolean",
814
+ 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.",
815
+ },
816
+ saveToDrafts: {
817
+ type: "boolean",
818
+ description: "Save the forward to Drafts instead of sending it, so it can be edited in a mail client first. Defaults to false.",
819
+ },
820
+ from: {
821
+ type: "string",
822
+ description: "Optional visible From address. Must be SMTP_USER or listed in SMTP_ALLOWED_FROM; anything else is rejected.",
823
+ },
824
+ fromName: {
825
+ type: "string",
826
+ description: "Optional visible display name for the From header.",
827
+ },
828
+ },
829
+ required: ["uid", "to"],
830
+ },
831
+ outputSchema: sendResultSchema,
832
+ handler: async (args, services, ctx) => {
833
+ const { imap, smtp } = services;
834
+ const list = (value) => value == null ? undefined : Array.isArray(value) ? value : [value];
835
+ const to = list(args.to) ?? [];
836
+ const cc = list(args.cc);
837
+ const bcc = list(args.bcc);
838
+ const saveToDrafts = args.saveToDrafts || false;
839
+ if (to.length === 0) {
840
+ return invalid("to must be a non-empty array of recipient addresses");
841
+ }
842
+ // The original is read before the gate: its subject is what the
843
+ // confirmation names, and a UID that does not exist should fail as a
844
+ // lookup error rather than after the user has agreed to send it.
845
+ let original;
846
+ try {
847
+ original = await imap.fetchEmail(args.folder || "INBOX", args.uid);
848
+ }
849
+ catch (err) {
850
+ return toolError(err);
851
+ }
852
+ const subject = args.subject ??
853
+ (/^fwd:/i.test(original.subject || "")
854
+ ? original.subject
855
+ : `Fwd: ${original.subject || ""}`);
856
+ if (!saveToDrafts) {
857
+ const recipients = [...to, ...(cc ?? []), ...(bcc ?? [])].join(", ");
858
+ const gate = confirmDestructive(ctx, "confirm_forward_email", `Forward "${original.subject || "(no subject)"}" to ${recipients}? This cannot be undone.`);
859
+ if (gate.status === "interrupt")
860
+ return gate.result;
861
+ }
862
+ return run(async () => {
863
+ const { text, html } = await buildForwardedBodies(original, args.note);
864
+ // Attachments go IMAP → SMTP without passing through a tool result, so
865
+ // the EMAIL_MAX_INLINE_BYTES ceiling — which exists to keep payloads
866
+ // out of the model's context — deliberately does not apply here.
867
+ // includeAttachments: false is the control for a large message.
868
+ let attachments;
869
+ if (args.includeAttachments !== false && original.attachments.length > 0) {
870
+ attachments = [];
871
+ for (const att of original.attachments) {
872
+ const fetched = await imap.downloadAttachment(args.folder || "INBOX", args.uid, att.partId);
873
+ attachments.push({
874
+ filename: fetched.filename,
875
+ contentType: fetched.contentType,
876
+ content: fetched.content,
877
+ });
435
878
  }
436
879
  }
437
- return structured({
438
- status: "sent",
439
- messageId: sendResult.messageId,
440
- folder: sentFolderPath,
441
- });
880
+ const from = smtp.formatFromHeader(smtp.resolveFromAddress(args.from), args.fromName);
881
+ // No In-Reply-To or References: a forward starts its own thread. Adding
882
+ // them would file it under the original conversation in the recipient's
883
+ // client, which is not what forwarding to a new audience means.
884
+ return deliver(services, { from, to, cc, bcc, subject, text, html, attachments }, saveToDrafts);
442
885
  });
443
886
  },
444
887
  },
@@ -474,6 +917,50 @@ export const EMAIL_TOOLS = [
474
917
  });
475
918
  }),
476
919
  },
920
+ {
921
+ name: "copy_email",
922
+ title: "Copy Email",
923
+ 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.",
924
+ annotations: {
925
+ readOnlyHint: false,
926
+ destructiveHint: false,
927
+ // Not idempotent: a second call adds a second copy rather than doing
928
+ // nothing, since each COPY allocates a fresh UID in the destination.
929
+ idempotentHint: false,
930
+ openWorldHint: true,
931
+ },
932
+ inputSchema: {
933
+ type: "object",
934
+ properties: {
935
+ folder: { type: "string", description: "Source IMAP folder. Defaults to INBOX." },
936
+ uids: UIDS_PROP("UIDs of emails to copy. They remain in the source folder."),
937
+ destination: {
938
+ type: "string",
939
+ description: "Destination folder path. It must already exist — create_folder first if not.",
940
+ },
941
+ },
942
+ required: ["uids", "destination"],
943
+ },
944
+ outputSchema: copyResultSchema,
945
+ handler: (args, { imap }) => run(async () => {
946
+ if (!Array.isArray(args.uids) || args.uids.length === 0) {
947
+ return invalid("uids must be a non-empty array of message UIDs");
948
+ }
949
+ const folder = args.folder || "INBOX";
950
+ // A self-copy is legal IMAP and duplicates every message in place,
951
+ // which is never what a caller reaching for "copy to a folder" wants.
952
+ if (folder === args.destination) {
953
+ return invalid(`destination is the source folder (${folder}) — this would duplicate the messages in place`);
954
+ }
955
+ const copied = await imap.copyEmails(folder, args.uids, args.destination);
956
+ return structured({
957
+ status: "copied",
958
+ uids: args.uids,
959
+ destination: args.destination,
960
+ ...(copied ? { copied } : {}),
961
+ });
962
+ }),
963
+ },
477
964
  {
478
965
  name: "mark_email",
479
966
  title: "Mark Email",
@@ -592,6 +1079,104 @@ export const EMAIL_TOOLS = [
592
1079
  return structured({ status: "created", path: args.path });
593
1080
  }),
594
1081
  },
1082
+ {
1083
+ name: "rename_folder",
1084
+ title: "Rename Folder",
1085
+ 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.",
1086
+ annotations: {
1087
+ readOnlyHint: false,
1088
+ destructiveHint: false,
1089
+ // Not idempotent: the second call finds nothing at the old path and fails.
1090
+ idempotentHint: false,
1091
+ openWorldHint: true,
1092
+ },
1093
+ inputSchema: {
1094
+ type: "object",
1095
+ properties: {
1096
+ path: {
1097
+ type: "string",
1098
+ description: "Existing folder path to rename (e.g., 'Projects/Work').",
1099
+ },
1100
+ newPath: {
1101
+ type: "string",
1102
+ 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.",
1103
+ },
1104
+ },
1105
+ required: ["path", "newPath"],
1106
+ },
1107
+ outputSchema: renameFolderResultSchema,
1108
+ handler: (args, { imap }) => run(async () => {
1109
+ // Checked before connecting: a blank path is a RENAME the server would
1110
+ // answer with a protocol error naming neither argument, and IMAP has no
1111
+ // way to express "rename to nothing".
1112
+ const path = typeof args.path === "string" ? args.path.trim() : "";
1113
+ const newPath = typeof args.newPath === "string" ? args.newPath.trim() : "";
1114
+ if (!path)
1115
+ return invalid("path must be a non-empty folder path");
1116
+ if (!newPath)
1117
+ return invalid("newPath must be a non-empty folder path");
1118
+ if (path === newPath) {
1119
+ return invalid(`newPath is already the folder's path: ${path}`);
1120
+ }
1121
+ const renamed = await imap.renameFolder(path, newPath);
1122
+ return structured({ status: "renamed", ...renamed });
1123
+ }),
1124
+ },
1125
+ {
1126
+ name: "delete_folder",
1127
+ title: "Delete Folder",
1128
+ 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.",
1129
+ annotations: {
1130
+ readOnlyHint: false,
1131
+ destructiveHint: true,
1132
+ // A second call finds nothing to delete and fails, but the account ends
1133
+ // up in the same state either way.
1134
+ idempotentHint: true,
1135
+ openWorldHint: true,
1136
+ },
1137
+ inputSchema: {
1138
+ type: "object",
1139
+ properties: {
1140
+ path: { type: "string", description: "Folder path to delete (e.g., 'Projects/Work')." },
1141
+ },
1142
+ required: ["path"],
1143
+ },
1144
+ outputSchema: deleteFolderResultSchema,
1145
+ handler: async (args, { imap }, ctx) => {
1146
+ const path = typeof args.path === "string" ? args.path.trim() : "";
1147
+ if (!path)
1148
+ return invalid("path must be a non-empty folder path");
1149
+ // RFC 3501 §6.3.4 makes deleting INBOX an error, and a server's reply to
1150
+ // it is a bare NO. Rejecting here spends no confirmation on a request
1151
+ // that was never going to succeed.
1152
+ if (path.toUpperCase() === "INBOX") {
1153
+ return invalid("INBOX cannot be deleted — IMAP reserves it");
1154
+ }
1155
+ // STATUS before the gate so the prompt says what is actually at stake:
1156
+ // "delete Projects/Work" and "delete Projects/Work and its 412 messages"
1157
+ // are different decisions. A folder the server will not count is still
1158
+ // worth confirming, so a failure here is not fatal — the delete itself
1159
+ // raises the real error.
1160
+ let messages;
1161
+ try {
1162
+ messages = (await imap.getFolderStatus(path)).total;
1163
+ }
1164
+ catch {
1165
+ messages = undefined;
1166
+ }
1167
+ 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.`);
1168
+ if (gate.status === "interrupt")
1169
+ return gate.result;
1170
+ return run(async () => {
1171
+ await imap.deleteFolder(path);
1172
+ return structured({
1173
+ status: "deleted",
1174
+ path,
1175
+ ...(messages === undefined ? {} : { messages }),
1176
+ });
1177
+ });
1178
+ },
1179
+ },
595
1180
  {
596
1181
  name: "download_attachment",
597
1182
  title: "Download Attachment",