@kbzowski/mcp-inbox 0.4.0 → 0.5.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.
package/dist/app.js CHANGED
@@ -37,11 +37,9 @@ var EnvSchema = z.object({
37
37
  SMTP_USER: z.string().min(1).optional(),
38
38
  SMTP_PASSWORD: z.string().min(1).optional(),
39
39
  // Cache
40
- IMAP_CACHE_ENABLED: BooleanString.default(true),
41
40
  IMAP_CACHE_DIR: z.string().min(1).optional(),
42
- IMAP_CACHE_BODY_INLINE: BooleanString.default(false),
43
41
  IMAP_CACHE_DEFAULT_STALENESS_SEC: z.coerce.number().int().min(0).default(60),
44
- IMAP_CACHE_RETAIN_DAYS: z.coerce.number().int().min(0).default(365),
42
+ IMAP_CACHE_BODY_RETAIN_DAYS: z.coerce.number().int().min(0).default(180),
45
43
  // IDLE
46
44
  IMAP_IDLE_ENABLED: BooleanString.default(true),
47
45
  IMAP_IDLE_FOLDERS: CsvList.default(["INBOX"]),
@@ -65,11 +63,9 @@ var EnvSchema = z.object({
65
63
  password: raw.SMTP_PASSWORD ?? raw.IMAP_PASSWORD
66
64
  },
67
65
  cache: {
68
- enabled: raw.IMAP_CACHE_ENABLED,
69
66
  dir: raw.IMAP_CACHE_DIR ?? defaultCacheDir(),
70
- eagerBodyCache: raw.IMAP_CACHE_BODY_INLINE,
71
67
  defaultStalenessSec: raw.IMAP_CACHE_DEFAULT_STALENESS_SEC,
72
- retainDays: raw.IMAP_CACHE_RETAIN_DAYS
68
+ bodyRetainDays: raw.IMAP_CACHE_BODY_RETAIN_DAYS
73
69
  },
74
70
  idle: {
75
71
  enabled: raw.IMAP_IDLE_ENABLED,
@@ -152,10 +148,12 @@ var emails = sqliteTable(
152
148
  hasAttachments: integer("has_attachments", { mode: "boolean" }).notNull().default(false),
153
149
  /** Full parsed envelope as JSON, for detail-view tools. */
154
150
  envelopeJson: text("envelope_json").notNull(),
155
- /** Plain-text body, nullable - fetched on demand unless IMAP_CACHE_BODY_INLINE=true. */
151
+ /** Plain-text body, nullable - fetched on first read of the message. */
156
152
  bodyText: text("body_text"),
157
153
  /** HTML body, nullable. Can be large; keep lazy by default. */
158
154
  bodyHtml: text("body_html"),
155
+ /** Attachment metadata, written with the body in the same fetch. */
156
+ attachmentsJson: text("attachments_json", { mode: "json" }).$type(),
159
157
  /** Per-message MODSEQ (RFC 7162). Used for CONDSTORE incremental sync. */
160
158
  modseq: integer("modseq"),
161
159
  /** Epoch ms of envelope cache write. */
@@ -217,7 +215,7 @@ var LoggerContext = class {
217
215
  emit(level, namespace, msg, meta) {
218
216
  if (!this.shouldEmit(level, namespace)) return;
219
217
  const entry = {
220
- ...meta ?? {},
218
+ ...meta,
221
219
  ts: (/* @__PURE__ */ new Date()).toISOString(),
222
220
  level,
223
221
  ns: namespace,
@@ -315,6 +313,170 @@ function diagnoseOpenError(path, err) {
315
313
  return `Could not open cache database at ${path}. ${hint}`;
316
314
  }
317
315
 
316
+ // src/cache/queries.ts
317
+ import { and, desc, eq, gte, inArray, lt, sql } from "drizzle-orm";
318
+ var log2 = createLogger("mcp-inbox:cache");
319
+ function upsertFolder(db, row) {
320
+ db.insert(folders).values(row).onConflictDoUpdate({
321
+ target: folders.name,
322
+ set: {
323
+ delimiter: row.delimiter,
324
+ specialUse: row.specialUse ?? null,
325
+ uidValidity: row.uidValidity,
326
+ uidNext: row.uidNext ?? null,
327
+ highestModseq: row.highestModseq ?? null,
328
+ lastSyncedAt: row.lastSyncedAt
329
+ }
330
+ }).run();
331
+ }
332
+ function getFolder(db, name) {
333
+ return db.select().from(folders).where(eq(folders.name, name)).get();
334
+ }
335
+ function upsertEmail(db, row) {
336
+ db.insert(emails).values(row).onConflictDoUpdate({
337
+ target: [emails.folder, emails.uid],
338
+ set: {
339
+ messageId: row.messageId ?? null,
340
+ subject: row.subject ?? null,
341
+ fromAddr: row.fromAddr ?? null,
342
+ toAddrs: row.toAddrs ?? null,
343
+ ccAddrs: row.ccAddrs ?? null,
344
+ date: row.date ?? null,
345
+ flags: row.flags,
346
+ hasAttachments: row.hasAttachments ?? false,
347
+ envelopeJson: row.envelopeJson,
348
+ modseq: row.modseq ?? null,
349
+ cachedAt: row.cachedAt
350
+ }
351
+ }).run();
352
+ }
353
+ function upsertEmails(db, rows) {
354
+ if (rows.length === 0) return;
355
+ db.transaction((tx) => {
356
+ for (const row of rows) upsertEmail(tx, row);
357
+ });
358
+ }
359
+ function getEmail(db, folder, uid) {
360
+ return db.select().from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
361
+ }
362
+ function getEmailsByUids(db, folder, uids) {
363
+ const out = /* @__PURE__ */ new Map();
364
+ if (uids.length === 0) return out;
365
+ inBatches(uids, (batch) => {
366
+ const rows = db.select().from(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, batch))).all();
367
+ for (const row of rows) out.set(row.uid, row);
368
+ });
369
+ return out;
370
+ }
371
+ function buildFolderConditions(folder, opts) {
372
+ const conditions = [eq(emails.folder, folder)];
373
+ if (opts.sinceMs !== void 0) conditions.push(gte(emails.date, opts.sinceMs));
374
+ if (opts.beforeMs !== void 0) conditions.push(lt(emails.date, opts.beforeMs));
375
+ if (opts.unseenOnly) {
376
+ conditions.push(
377
+ sql`NOT EXISTS (SELECT 1 FROM json_each(${emails.flags}) WHERE value = ${"\\Seen"})`
378
+ );
379
+ }
380
+ return conditions;
381
+ }
382
+ function listEmailsByFolder(db, folder, opts = {}) {
383
+ const conditions = buildFolderConditions(folder, opts);
384
+ return db.select().from(emails).where(and(...conditions)).orderBy(desc(emails.date), desc(emails.uid)).limit(opts.limit ?? 100).offset(opts.offset ?? 0).all();
385
+ }
386
+ function countEmailsInFolder(db, folder, opts = {}) {
387
+ const conditions = buildFolderConditions(folder, opts);
388
+ const row = db.select({ n: sql`count(*)` }).from(emails).where(and(...conditions)).get();
389
+ return row?.n ?? 0;
390
+ }
391
+ function listCachedUidsForFolder(db, folder) {
392
+ const rows = db.select({ uid: emails.uid }).from(emails).where(eq(emails.folder, folder)).all();
393
+ return rows.map((r) => r.uid);
394
+ }
395
+ function setEmailFlags(db, folder, uid, flags) {
396
+ db.update(emails).set({ flags }).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
397
+ }
398
+ var UID_BATCH = 1e4;
399
+ function inBatches(items, run) {
400
+ for (let i = 0; i < items.length; i += UID_BATCH) {
401
+ run(items.slice(i, i + UID_BATCH));
402
+ }
403
+ }
404
+ function setFlagsForUids(db, folder, next) {
405
+ if (next.size === 0) return;
406
+ const uids = [...next.keys()];
407
+ db.transaction((tx) => {
408
+ inBatches(uids, (batch) => {
409
+ const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, batch))).all();
410
+ for (const row of rows) {
411
+ const flags = next.get(row.uid);
412
+ if (!flags || flagsEqual(row.flags, flags)) continue;
413
+ tx.update(emails).set({ flags }).where(and(eq(emails.folder, folder), eq(emails.uid, row.uid))).run();
414
+ }
415
+ });
416
+ });
417
+ }
418
+ function mutateEmailFlagsForUids(db, folder, uids, mutate) {
419
+ if (uids.length === 0) return;
420
+ db.transaction((tx) => {
421
+ inBatches(uids, (batch) => {
422
+ const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, batch))).all();
423
+ for (const row of rows) {
424
+ const next = mutate(row.flags);
425
+ if (flagsEqual(row.flags, next)) continue;
426
+ tx.update(emails).set({ flags: next }).where(and(eq(emails.folder, folder), eq(emails.uid, row.uid))).run();
427
+ }
428
+ });
429
+ });
430
+ }
431
+ function flagsEqual(a, b) {
432
+ if (a.length !== b.length) return false;
433
+ const setB = new Set(b);
434
+ for (const f of a) if (!setB.has(f)) return false;
435
+ return true;
436
+ }
437
+ function deleteEmailsByFolder(db, folder) {
438
+ db.delete(emails).where(eq(emails.folder, folder)).run();
439
+ }
440
+ function deleteEmail(db, folder, uid) {
441
+ db.delete(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
442
+ }
443
+ function deleteEmailsByUids(db, folder, uids) {
444
+ if (uids.length === 0) return;
445
+ inBatches(uids, (batch) => {
446
+ db.delete(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, batch))).run();
447
+ });
448
+ }
449
+ function pruneBodiesBefore(db, cutoffMs) {
450
+ const stale = db.select({ n: sql`count(*)` }).from(emails).where(lt(emails.bodyCachedAt, cutoffMs)).get();
451
+ const count = stale?.n ?? 0;
452
+ if (count === 0) return 0;
453
+ db.update(emails).set({ bodyText: null, bodyHtml: null, attachmentsJson: null, bodyCachedAt: null }).where(lt(emails.bodyCachedAt, cutoffMs)).run();
454
+ return count;
455
+ }
456
+ function getEmailBody(db, folder, uid) {
457
+ const row = db.select({
458
+ bodyText: emails.bodyText,
459
+ bodyHtml: emails.bodyHtml,
460
+ attachments: emails.attachmentsJson,
461
+ bodyCachedAt: emails.bodyCachedAt
462
+ }).from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
463
+ return row;
464
+ }
465
+ function setEmailBody(db, folder, uid, body, nowMs) {
466
+ const existing = db.select({ uid: emails.uid }).from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
467
+ if (!existing) {
468
+ log2.warn("cannot cache body, envelope row missing", { folder, uid });
469
+ return false;
470
+ }
471
+ db.update(emails).set({
472
+ bodyText: body.text,
473
+ bodyHtml: body.html,
474
+ attachmentsJson: body.attachments ?? [],
475
+ bodyCachedAt: nowMs
476
+ }).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
477
+ return true;
478
+ }
479
+
318
480
  // src/imap/client.ts
319
481
  import { ImapFlow } from "imapflow";
320
482
 
@@ -408,9 +570,9 @@ function isMcpInboxError(err) {
408
570
  }
409
571
 
410
572
  // src/imap/client.ts
411
- var log2 = createLogger("mcp-inbox:imap");
573
+ var log3 = createLogger("mcp-inbox:imap");
412
574
  async function createImapConnection(config) {
413
- log2.info("opening IMAP connection", {
575
+ log3.info("opening IMAP connection", {
414
576
  host: config.host,
415
577
  port: config.port,
416
578
  tls: config.tls
@@ -431,7 +593,7 @@ async function createImapConnection(config) {
431
593
  greetingTimeout: config.authTimeoutMs
432
594
  });
433
595
  flow.on("error", (err) => {
434
- log2.error("IMAP connection error", {
596
+ log3.error("IMAP connection error", {
435
597
  msg: err instanceof Error ? err.message : String(err)
436
598
  });
437
599
  });
@@ -440,7 +602,7 @@ async function createImapConnection(config) {
440
602
  } catch (err) {
441
603
  throw mapImapError(err);
442
604
  }
443
- log2.info("IMAP connection ready");
605
+ log3.info("IMAP connection ready");
444
606
  return flow;
445
607
  }
446
608
  var ImapClient = class {
@@ -448,6 +610,7 @@ var ImapClient = class {
448
610
  #flow = null;
449
611
  #connecting = null;
450
612
  #closed = false;
613
+ #folderList = null;
451
614
  constructor(config) {
452
615
  this.#config = config;
453
616
  }
@@ -473,11 +636,28 @@ var ImapClient = class {
473
636
  this.#connecting = null;
474
637
  }
475
638
  }
639
+ /**
640
+ * The mailbox list, cached for `maxAgeMs`. Resolving \Drafts / \Sent /
641
+ * \Trash needs it on every send, draft and delete, and a LIST is a network
642
+ * round-trip whose answer almost never changes. A newly created folder
643
+ * shows up within the window; `imap_list_folders` bypasses this entirely,
644
+ * so an explicit "what folders do I have" is always current.
645
+ */
646
+ async folderList(maxAgeMs = 6e4) {
647
+ const cached = this.#folderList;
648
+ if (cached && Date.now() - cached.at < maxAgeMs) {
649
+ return cached.rows;
650
+ }
651
+ const flow = await this.connection();
652
+ const rows = await flow.list();
653
+ this.#folderList = { at: Date.now(), rows };
654
+ return rows;
655
+ }
476
656
  async #openConnection() {
477
657
  const flow = await createImapConnection(this.#config);
478
658
  flow.on("close", () => {
479
659
  if (!this.#closed) {
480
- log2.warn("IMAP connection closed unexpectedly");
660
+ log3.warn("IMAP connection closed unexpectedly");
481
661
  }
482
662
  if (this.#flow === flow) {
483
663
  this.#flow = null;
@@ -497,7 +677,7 @@ var ImapClient = class {
497
677
  try {
498
678
  await flow.logout();
499
679
  } catch (err) {
500
- log2.warn("error during IMAP logout", {
680
+ log3.warn("error during IMAP logout", {
501
681
  msg: err instanceof Error ? err.message : String(err)
502
682
  });
503
683
  }
@@ -505,117 +685,9 @@ var ImapClient = class {
505
685
  }
506
686
  };
507
687
 
508
- // src/cache/queries.ts
509
- import { and, desc, eq, gte, inArray, lt, sql } from "drizzle-orm";
510
- function upsertFolder(db, row) {
511
- db.insert(folders).values(row).onConflictDoUpdate({
512
- target: folders.name,
513
- set: {
514
- delimiter: row.delimiter,
515
- specialUse: row.specialUse ?? null,
516
- uidValidity: row.uidValidity,
517
- uidNext: row.uidNext ?? null,
518
- highestModseq: row.highestModseq ?? null,
519
- lastSyncedAt: row.lastSyncedAt
520
- }
521
- }).run();
522
- }
523
- function getFolder(db, name) {
524
- return db.select().from(folders).where(eq(folders.name, name)).get();
525
- }
526
- function upsertEmail(db, row) {
527
- db.insert(emails).values(row).onConflictDoUpdate({
528
- target: [emails.folder, emails.uid],
529
- set: {
530
- messageId: row.messageId ?? null,
531
- subject: row.subject ?? null,
532
- fromAddr: row.fromAddr ?? null,
533
- toAddrs: row.toAddrs ?? null,
534
- ccAddrs: row.ccAddrs ?? null,
535
- date: row.date ?? null,
536
- flags: row.flags,
537
- hasAttachments: row.hasAttachments ?? false,
538
- envelopeJson: row.envelopeJson,
539
- modseq: row.modseq ?? null,
540
- cachedAt: row.cachedAt
541
- }
542
- }).run();
543
- }
544
- function getEmail(db, folder, uid) {
545
- return db.select().from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
546
- }
547
- function buildFolderConditions(folder, opts) {
548
- const conditions = [eq(emails.folder, folder)];
549
- if (opts.sinceMs !== void 0) conditions.push(gte(emails.date, opts.sinceMs));
550
- if (opts.beforeMs !== void 0) conditions.push(lt(emails.date, opts.beforeMs));
551
- if (opts.unseenOnly) {
552
- conditions.push(
553
- sql`NOT EXISTS (SELECT 1 FROM json_each(${emails.flags}) WHERE value = ${"\\Seen"})`
554
- );
555
- }
556
- return conditions;
557
- }
558
- function listEmailsByFolder(db, folder, opts = {}) {
559
- const conditions = buildFolderConditions(folder, opts);
560
- return db.select().from(emails).where(and(...conditions)).orderBy(desc(emails.date), desc(emails.uid)).limit(opts.limit ?? 100).offset(opts.offset ?? 0).all();
561
- }
562
- function countEmailsInFolder(db, folder, opts = {}) {
563
- const conditions = buildFolderConditions(folder, opts);
564
- const row = db.select({ n: sql`count(*)` }).from(emails).where(and(...conditions)).get();
565
- return row?.n ?? 0;
566
- }
567
- function listCachedUidsForFolder(db, folder) {
568
- const rows = db.select({ uid: emails.uid }).from(emails).where(eq(emails.folder, folder)).all();
569
- return rows.map((r) => r.uid);
570
- }
571
- function setEmailFlags(db, folder, uid, flags) {
572
- db.update(emails).set({ flags }).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
573
- }
574
- function mutateEmailFlagsForUids(db, folder, uids, mutate) {
575
- if (uids.length === 0) return;
576
- db.transaction((tx) => {
577
- const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, uids))).all();
578
- for (const row of rows) {
579
- const next = mutate(row.flags);
580
- if (flagsEqual(row.flags, next)) continue;
581
- tx.update(emails).set({ flags: next }).where(and(eq(emails.folder, folder), eq(emails.uid, row.uid))).run();
582
- }
583
- });
584
- }
585
- function flagsEqual(a, b) {
586
- if (a.length !== b.length) return false;
587
- const setB = new Set(b);
588
- for (const f of a) if (!setB.has(f)) return false;
589
- return true;
590
- }
591
- function deleteEmailsByFolder(db, folder) {
592
- db.delete(emails).where(eq(emails.folder, folder)).run();
593
- }
594
- function deleteEmail(db, folder, uid) {
595
- db.delete(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
596
- }
597
- function deleteEmailsByUids(db, folder, uids) {
598
- if (uids.length === 0) return;
599
- db.delete(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, uids))).run();
600
- }
601
- function getEmailBody(db, folder, uid) {
602
- const row = db.select({
603
- bodyText: emails.bodyText,
604
- bodyHtml: emails.bodyHtml,
605
- bodyCachedAt: emails.bodyCachedAt
606
- }).from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
607
- return row;
608
- }
609
- function setEmailBody(db, folder, uid, body, nowMs) {
610
- db.update(emails).set({
611
- bodyText: body.text,
612
- bodyHtml: body.html,
613
- bodyCachedAt: nowMs
614
- }).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
615
- }
616
-
617
688
  // src/cache/sync.ts
618
- var log3 = createLogger("mcp-inbox:sync");
689
+ var log4 = createLogger("mcp-inbox:sync");
690
+ var ENVELOPE_FLUSH_SIZE = 500;
619
691
  async function syncFolder(ctx, folderPath) {
620
692
  const started = Date.now();
621
693
  const lock = await ctx.imap.getMailboxLock(folderPath);
@@ -627,7 +699,7 @@ async function syncFolder(ctx, folderPath) {
627
699
  const cached = getFolder(ctx.db, folderPath);
628
700
  const uidValidityChanged = cached !== void 0 && cached.uidValidity !== Number(box.uidValidity);
629
701
  if (uidValidityChanged) {
630
- log3.warn("UIDVALIDITY changed - wiping folder cache", {
702
+ log4.warn("UIDVALIDITY changed - wiping folder cache", {
631
703
  folder: folderPath,
632
704
  cached: cached?.uidValidity,
633
705
  server: Number(box.uidValidity)
@@ -645,7 +717,7 @@ async function syncFolder(ctx, folderPath) {
645
717
  lastSyncedAt: Date.now()
646
718
  });
647
719
  const durationMs = Date.now() - started;
648
- log3.info("folder synced", { folder: folderPath, syncType, fetched, durationMs });
720
+ log4.info("folder synced", { folder: folderPath, syncType, fetched, durationMs });
649
721
  return { folder: folderPath, syncType, fetched, durationMs };
650
722
  } catch (err) {
651
723
  throw mapImapError(err);
@@ -653,54 +725,72 @@ async function syncFolder(ctx, folderPath) {
653
725
  lock.release();
654
726
  }
655
727
  }
728
+ function diffUids(cached, server) {
729
+ const cachedSet = new Set(cached);
730
+ const serverSet = new Set(server);
731
+ return {
732
+ missing: server.filter((uid) => !cachedSet.has(uid)),
733
+ ghosts: cached.filter((uid) => !serverSet.has(uid))
734
+ };
735
+ }
736
+ function changedSinceFor(serverModseq, cachedModseq) {
737
+ if (serverModseq === null) return null;
738
+ return cachedModseq ?? null;
739
+ }
656
740
  async function runSync(ctx, folderPath, box, cached, uidValidityChanged) {
657
- if (!cached || uidValidityChanged) {
658
- const fetched2 = await fetchAndStoreRange(ctx, folderPath, "1:*");
659
- return { syncType: "full", fetched: fetched2 };
660
- }
741
+ const coldStart = !cached || uidValidityChanged;
742
+ const searchResult = await ctx.imap.search({ all: true }, { uid: true });
743
+ const serverUids = Array.isArray(searchResult) ? searchResult : [];
744
+ const { missing, ghosts } = diffUids(listCachedUidsForFolder(ctx.db, folderPath), serverUids);
745
+ if (ghosts.length > 0) {
746
+ deleteEmailsByUids(ctx.db, folderPath, ghosts);
747
+ log4.info("evicted ghost UIDs", { folder: folderPath, removed: ghosts.length });
748
+ }
749
+ const fetched = missing.length > 0 ? await fetchEnvelopes(ctx, folderPath, missing) : 0;
661
750
  const serverModseq = box.highestModseq !== void 0 ? Number(box.highestModseq) : null;
662
- if (serverModseq !== null && cached.highestModseq !== null && cached.highestModseq !== void 0) {
663
- const fetched2 = serverModseq === cached.highestModseq ? 0 : await fetchAndStoreRange(ctx, folderPath, "1:*", BigInt(cached.highestModseq));
664
- await reconcileUids(ctx, folderPath);
665
- return { syncType: serverModseq === cached.highestModseq ? "skipped" : "incremental", fetched: fetched2 };
666
- }
667
- const fetched = await fetchAndStoreRange(ctx, folderPath, "1:*");
668
- await reconcileUids(ctx, folderPath);
669
- return { syncType: "full", fetched };
670
- }
671
- async function reconcileUids(ctx, folderPath) {
672
- const cachedUids = listCachedUidsForFolder(ctx.db, folderPath);
673
- if (cachedUids.length === 0) return;
674
- const result = await ctx.imap.search({ all: true }, { uid: true });
675
- const serverUids = new Set(Array.isArray(result) ? result : []);
676
- const ghosts = cachedUids.filter((uid) => !serverUids.has(uid));
677
- if (ghosts.length === 0) return;
678
- deleteEmailsByUids(ctx.db, folderPath, ghosts);
679
- log3.info("reconciled ghost UIDs", { folder: folderPath, removed: ghosts.length });
680
- }
681
- async function fetchAndStoreRange(ctx, folderPath, range, changedSince) {
751
+ const flagsUnchanged = serverModseq !== null && cached?.highestModseq != null && serverModseq === cached.highestModseq;
752
+ if (!flagsUnchanged && serverUids.length > missing.length) {
753
+ await refreshFlags(ctx, folderPath, changedSinceFor(serverModseq, cached?.highestModseq));
754
+ }
755
+ if (coldStart) return { syncType: "full", fetched };
756
+ if (fetched === 0 && ghosts.length === 0 && flagsUnchanged) {
757
+ return { syncType: "skipped", fetched: 0 };
758
+ }
759
+ return { syncType: "incremental", fetched };
760
+ }
761
+ async function fetchEnvelopes(ctx, folderPath, uids) {
682
762
  const now = Date.now();
683
763
  let count = 0;
684
- const options = changedSince !== void 0 ? { uid: true, changedSince } : { uid: true };
685
764
  const iterator = ctx.imap.fetch(
686
- range,
687
- {
688
- envelope: true,
689
- flags: true,
690
- internalDate: true,
691
- bodyStructure: true
692
- },
693
- options
765
+ uids,
766
+ { envelope: true, flags: true, internalDate: true, bodyStructure: true },
767
+ { uid: true }
694
768
  );
769
+ const buffer = [];
695
770
  for await (const msg of iterator) {
696
771
  const insert = messageToInsert(folderPath, msg, now);
697
772
  if (insert) {
698
- upsertEmail(ctx.db, insert);
773
+ buffer.push(insert);
699
774
  count++;
775
+ if (buffer.length >= ENVELOPE_FLUSH_SIZE) {
776
+ upsertEmails(ctx.db, buffer);
777
+ buffer.length = 0;
778
+ }
700
779
  }
701
780
  }
781
+ upsertEmails(ctx.db, buffer);
702
782
  return count;
703
783
  }
784
+ async function refreshFlags(ctx, folderPath, cachedModseq) {
785
+ const options = cachedModseq !== null ? { uid: true, changedSince: BigInt(cachedModseq) } : { uid: true };
786
+ const next = /* @__PURE__ */ new Map();
787
+ for await (const msg of ctx.imap.fetch("1:*", { flags: true }, options)) {
788
+ if (typeof msg.uid === "number" && msg.flags) {
789
+ next.set(msg.uid, Array.from(msg.flags));
790
+ }
791
+ }
792
+ setFlagsForUids(ctx.db, folderPath, next);
793
+ }
704
794
  function messageToInsert(folderPath, msg, cachedAt) {
705
795
  if (typeof msg.uid !== "number") return null;
706
796
  const env = msg.envelope;
@@ -733,7 +823,7 @@ function hasAttachments(structure) {
733
823
  }
734
824
 
735
825
  // src/cache/idle.ts
736
- var log4 = createLogger("mcp-inbox:idle");
826
+ var log5 = createLogger("mcp-inbox:idle");
737
827
  var IdleManager = class {
738
828
  #opts;
739
829
  #subscriptions = [];
@@ -749,7 +839,7 @@ var IdleManager = class {
749
839
  const sub = await this.#watchFolder(folder);
750
840
  this.#subscriptions.push(sub);
751
841
  } catch (err) {
752
- log4.error("failed to open IDLE for folder", {
842
+ log5.error("failed to open IDLE for folder", {
753
843
  folder,
754
844
  msg: err instanceof Error ? err.message : String(err)
755
845
  });
@@ -767,13 +857,13 @@ var IdleManager = class {
767
857
  async #watchFolder(folder) {
768
858
  const imap = await createImapConnection(this.#opts.imap);
769
859
  await imap.mailboxOpen(folder);
770
- log4.info("watching folder", { folder });
860
+ log5.info("watching folder", { folder });
771
861
  const onExists = (e) => {
772
- log4.debug("exists event", { folder: e.path, count: e.count, prevCount: e.prevCount });
862
+ log5.debug("exists event", { folder: e.path, count: e.count, prevCount: e.prevCount });
773
863
  void this.#handleExists(folder, imap);
774
864
  };
775
865
  const onFlags = (e) => {
776
- log4.debug("flags event", { folder: e.path, uid: e.uid, flags: Array.from(e.flags) });
866
+ log5.debug("flags event", { folder: e.path, uid: e.uid, flags: Array.from(e.flags) });
777
867
  if (e.uid !== void 0) {
778
868
  setEmailFlags(this.#opts.db, folder, e.uid, Array.from(e.flags));
779
869
  } else {
@@ -781,7 +871,7 @@ var IdleManager = class {
781
871
  }
782
872
  };
783
873
  const onExpunge = (e) => {
784
- log4.debug("expunge event", { folder: e.path, uid: e.uid, seq: e.seq });
874
+ log5.debug("expunge event", { folder: e.path, uid: e.uid, seq: e.seq });
785
875
  if (e.uid !== void 0) {
786
876
  deleteEmail(this.#opts.db, folder, e.uid);
787
877
  } else {
@@ -800,7 +890,7 @@ var IdleManager = class {
800
890
  try {
801
891
  await imap.logout();
802
892
  } catch (err) {
803
- log4.warn("error closing IDLE connection", {
893
+ log5.warn("error closing IDLE connection", {
804
894
  folder,
805
895
  msg: err instanceof Error ? err.message : String(err)
806
896
  });
@@ -812,7 +902,7 @@ var IdleManager = class {
812
902
  try {
813
903
  await syncFolder({ db: this.#opts.db, imap }, folder);
814
904
  } catch (err) {
815
- log4.error("exists sync failed", {
905
+ log5.error("exists sync failed", {
816
906
  folder,
817
907
  msg: err instanceof Error ? err.message : String(err)
818
908
  });
@@ -822,7 +912,7 @@ var IdleManager = class {
822
912
  try {
823
913
  await syncFolder({ db: this.#opts.db, imap }, folder);
824
914
  } catch (err) {
825
- log4.error("resync failed", {
915
+ log5.error("resync failed", {
826
916
  folder,
827
917
  msg: err instanceof Error ? err.message : String(err)
828
918
  });
@@ -832,7 +922,7 @@ var IdleManager = class {
832
922
 
833
923
  // src/smtp/client.ts
834
924
  import nodemailer from "nodemailer";
835
- var log5 = createLogger("mcp-inbox:smtp");
925
+ var log6 = createLogger("mcp-inbox:smtp");
836
926
  var SmtpClient = class {
837
927
  #config;
838
928
  #transporter = null;
@@ -845,7 +935,7 @@ var SmtpClient = class {
845
935
  throw new Error("SmtpClient has been closed");
846
936
  }
847
937
  if (this.#transporter) return this.#transporter;
848
- log5.info("creating SMTP transporter", {
938
+ log6.info("creating SMTP transporter", {
849
939
  host: this.#config.host,
850
940
  port: this.#config.port,
851
941
  secure: this.#config.secure
@@ -900,8 +990,100 @@ import {
900
990
  ListToolsRequestSchema
901
991
  } from "@modelcontextprotocol/sdk/types.js";
902
992
 
993
+ // package.json
994
+ var package_default = {
995
+ name: "@kbzowski/mcp-inbox",
996
+ version: "0.5.0",
997
+ description: "MCP server exposing IMAP/SMTP email over a fast local cache. Read, search, compose, and manage email from any IMAP provider with near-instant response times via background sync and IDLE push.",
998
+ type: "module",
999
+ main: "./dist/index.js",
1000
+ types: "./dist/index.d.ts",
1001
+ bin: {
1002
+ "mcp-inbox": "./dist/index.js"
1003
+ },
1004
+ files: [
1005
+ "dist",
1006
+ "LICENSE",
1007
+ "README.md"
1008
+ ],
1009
+ keywords: [
1010
+ "mcp",
1011
+ "mcp-server",
1012
+ "model-context-protocol",
1013
+ "claude",
1014
+ "anthropic",
1015
+ "email",
1016
+ "imap",
1017
+ "smtp",
1018
+ "mail",
1019
+ "inbox",
1020
+ "gmail",
1021
+ "outlook",
1022
+ "fastmail",
1023
+ "ai-tools",
1024
+ "llm-tools"
1025
+ ],
1026
+ author: "Krzysztof Bzowski",
1027
+ license: "MIT",
1028
+ homepage: "https://github.com/kbzowski/mcp-inbox#readme",
1029
+ repository: {
1030
+ type: "git",
1031
+ url: "git+https://github.com/kbzowski/mcp-inbox.git"
1032
+ },
1033
+ bugs: {
1034
+ url: "https://github.com/kbzowski/mcp-inbox/issues"
1035
+ },
1036
+ engines: {
1037
+ node: ">=24.0.0"
1038
+ },
1039
+ publishConfig: {
1040
+ access: "public",
1041
+ provenance: true
1042
+ },
1043
+ scripts: {
1044
+ build: "node scripts/build.mjs && tsc -p tsconfig.build.json",
1045
+ dev: "tsx src/index.ts",
1046
+ test: "vitest run",
1047
+ "test:watch": "vitest",
1048
+ "test:integration": "vitest run --config vitest.integration.config.ts",
1049
+ typecheck: "tsc --noEmit",
1050
+ lint: "oxlint src tests --type-aware",
1051
+ "lint:fix": "oxlint src tests --type-aware --fix",
1052
+ format: "oxfmt .",
1053
+ "format:check": "oxfmt --check .",
1054
+ "db:generate": "drizzle-kit generate",
1055
+ prepare: "lefthook install",
1056
+ prepublishOnly: "npm run typecheck && npm run lint && npm run test && npm run build",
1057
+ release: "changeset publish"
1058
+ },
1059
+ dependencies: {
1060
+ "@modelcontextprotocol/sdk": "^1.20.0",
1061
+ "drizzle-orm": "1.0.0-beta.22",
1062
+ imapflow: "^1.3.2",
1063
+ mailparser: "^3.7.2",
1064
+ nodemailer: "^9.0.4",
1065
+ zod: "^4.0.0"
1066
+ },
1067
+ devDependencies: {
1068
+ "@changesets/cli": "^2.27.10",
1069
+ "@types/mailparser": "^3.4.5",
1070
+ "@types/node": "^26.1.2",
1071
+ "@types/nodemailer": "^8.0.0",
1072
+ "drizzle-kit": "1.0.0-beta.22",
1073
+ esbuild: "^0.28.0",
1074
+ lefthook: "^2.1.6",
1075
+ oxfmt: "^0.62.0",
1076
+ oxlint: "^1.77.0",
1077
+ "oxlint-tsgolint": "^7.0.2001",
1078
+ testcontainers: "^12.1.0",
1079
+ tsx: "^4.19.0",
1080
+ typescript: "^7.0.2",
1081
+ vitest: "^4.0.0"
1082
+ }
1083
+ };
1084
+
903
1085
  // src/tools/registry.ts
904
- import { z as z21 } from "zod";
1086
+ import { z as z23 } from "zod";
905
1087
 
906
1088
  // src/tools/folders/list-folders.ts
907
1089
  import { z as z2 } from "zod";
@@ -1032,7 +1214,7 @@ var NAME_CANDIDATES = {
1032
1214
  };
1033
1215
 
1034
1216
  // src/tools/emails/shared.ts
1035
- async function syncIfStale(ctx, folder, maxStalenessSec) {
1217
+ async function syncIfStale(ctx, folder, maxStalenessSec = ctx.cacheConfig.defaultStalenessSec) {
1036
1218
  const cached = getFolder(ctx.db, folder);
1037
1219
  const ageMs = cached ? ctx.now() - cached.lastSyncedAt : Infinity;
1038
1220
  const stale = ageMs >= maxStalenessSec * 1e3;
@@ -1053,8 +1235,7 @@ function readEnvelopes(ctx, folder, opts) {
1053
1235
  async function resolveSpecialFolder(ctx, attr, explicitOverride) {
1054
1236
  if (explicitOverride) return explicitOverride;
1055
1237
  try {
1056
- const imap = await ctx.imap.connection();
1057
- const list = await imap.list();
1238
+ const list = await ctx.imap.folderList();
1058
1239
  const path = findSpecialFolder(list, attr);
1059
1240
  if (!path) {
1060
1241
  throw new ImapError(
@@ -1068,7 +1249,7 @@ async function resolveSpecialFolder(ctx, attr, explicitOverride) {
1068
1249
  throw mapImapError(err);
1069
1250
  }
1070
1251
  }
1071
- async function ensureBodyCached(ctx, folder, uid) {
1252
+ async function fetchRawSource(ctx, folder, uid) {
1072
1253
  const imap = await ctx.imap.connection();
1073
1254
  const lock = await imap.getMailboxLock(folder);
1074
1255
  try {
@@ -1079,19 +1260,7 @@ async function ensureBodyCached(ctx, folder, uid) {
1079
1260
  `Message with UID ${String(uid)} was not found in ${folder}. It may have been moved or deleted.`
1080
1261
  );
1081
1262
  }
1082
- const parsed = await simpleParser(msg.source);
1083
- const bodyText = parsed.text ?? null;
1084
- const bodyHtml = typeof parsed.html === "string" ? parsed.html : null;
1085
- const cached = getEmailBody(ctx.db, folder, uid);
1086
- if (cached?.bodyCachedAt == null) {
1087
- setEmailBody(ctx.db, folder, uid, { text: bodyText, html: bodyHtml }, ctx.now());
1088
- }
1089
- const attachments = (parsed.attachments ?? []).map((a) => ({
1090
- filename: a.filename ?? null,
1091
- content_type: a.contentType ?? "application/octet-stream",
1092
- size_bytes: typeof a.size === "number" ? a.size : 0
1093
- }));
1094
- return { bodyText, bodyHtml, attachments };
1263
+ return msg.source;
1095
1264
  } catch (err) {
1096
1265
  if (err instanceof ImapError) throw err;
1097
1266
  throw mapImapError(err);
@@ -1099,6 +1268,37 @@ async function ensureBodyCached(ctx, folder, uid) {
1099
1268
  lock.release();
1100
1269
  }
1101
1270
  }
1271
+ async function cacheParsedBody(ctx, folder, uid, source) {
1272
+ const parsed = await simpleParser(source);
1273
+ const bodyText = parsed.text ?? null;
1274
+ const bodyHtml = typeof parsed.html === "string" ? parsed.html : null;
1275
+ const attachments = (parsed.attachments ?? []).map((a) => ({
1276
+ filename: a.filename ?? null,
1277
+ content_type: a.contentType ?? "application/octet-stream",
1278
+ size_bytes: typeof a.size === "number" ? a.size : 0
1279
+ }));
1280
+ setEmailBody(ctx.db, folder, uid, { text: bodyText, html: bodyHtml, attachments }, ctx.now());
1281
+ return { bodyText, bodyHtml, attachments };
1282
+ }
1283
+ function readCachedBody(ctx, folder, uid) {
1284
+ const cached = getEmailBody(ctx.db, folder, uid);
1285
+ if (cached?.bodyCachedAt == null) return void 0;
1286
+ return {
1287
+ bodyText: cached.bodyText,
1288
+ bodyHtml: cached.bodyHtml,
1289
+ attachments: cached.attachments ?? []
1290
+ };
1291
+ }
1292
+ async function ensureBodyCached(ctx, folder, uid) {
1293
+ const cached = readCachedBody(ctx, folder, uid);
1294
+ if (cached) return cached;
1295
+ return await cacheParsedBody(ctx, folder, uid, await fetchRawSource(ctx, folder, uid));
1296
+ }
1297
+ async function ensureBodyAndSource(ctx, folder, uid) {
1298
+ const source = await fetchRawSource(ctx, folder, uid);
1299
+ const cached = readCachedBody(ctx, folder, uid);
1300
+ return { body: cached ?? await cacheParsedBody(ctx, folder, uid, source), source };
1301
+ }
1102
1302
  async function ensureEnvelopeCached(ctx, folder, uid, maxStalenessSec) {
1103
1303
  const existing = getEmail(ctx.db, folder, uid);
1104
1304
  if (existing !== void 0) {
@@ -1139,8 +1339,8 @@ var Input2 = z3.object({
1139
1339
  unseen_only: z3.boolean().default(false),
1140
1340
  since_date: z3.string().date().optional().describe("YYYY-MM-DD. Only return emails received on or after this date."),
1141
1341
  before_date: z3.string().date().optional().describe("YYYY-MM-DD. Only return emails received strictly before this date."),
1142
- max_staleness_seconds: z3.number().int().min(0).default(60).describe(
1143
- "Serve from cache if the folder was synced within this many seconds. Pass 0 to force a fresh sync."
1342
+ max_staleness_seconds: z3.number().int().min(0).optional().describe(
1343
+ "Serve from cache if the folder was synced within this many seconds. Pass 0 to force a fresh sync. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
1144
1344
  ),
1145
1345
  response_format: z3.enum(["markdown", "json"]).default("markdown")
1146
1346
  });
@@ -1190,7 +1390,9 @@ var Input3 = z4.object({
1190
1390
  uid: z4.number().int().positive().describe(
1191
1391
  "IMAP UID of the message. UIDs are folder-scoped - a UID from INBOX cannot be reused with the Sent folder."
1192
1392
  ),
1193
- max_staleness_seconds: z4.number().int().min(0).default(60),
1393
+ max_staleness_seconds: z4.number().int().min(0).optional().describe(
1394
+ "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
1395
+ ),
1194
1396
  response_format: z4.enum(["markdown", "json"]).default("markdown")
1195
1397
  });
1196
1398
  var getEmailTool = defineTool({
@@ -1264,6 +1466,8 @@ function buildImapSearch(c) {
1264
1466
  if (c.since) q.since = c.since;
1265
1467
  if (c.before) q.before = c.before;
1266
1468
  if (c.unseen === true) q.seen = false;
1469
+ if (c.flagged !== void 0) q.flagged = c.flagged;
1470
+ if (c.answered !== void 0) q.answered = c.answered;
1267
1471
  if (c.larger_than_bytes !== void 0) q.larger = c.larger_than_bytes;
1268
1472
  if (c.smaller_than_bytes !== void 0) q.smaller = c.smaller_than_bytes;
1269
1473
  if (c.or !== void 0 && c.or.length > 0) q.or = c.or.map(buildImapSearch);
@@ -1282,6 +1486,8 @@ var Criteria = z5.lazy(
1282
1486
  to: z5.string().min(1).optional(),
1283
1487
  body: z5.string().min(1).optional(),
1284
1488
  unseen: z5.boolean().optional(),
1489
+ flagged: z5.boolean().optional(),
1490
+ answered: z5.boolean().optional(),
1285
1491
  since: z5.coerce.date().optional(),
1286
1492
  before: z5.coerce.date().optional(),
1287
1493
  larger_than_bytes: z5.number().int().positive().optional(),
@@ -1297,6 +1503,8 @@ var Input4 = z5.object({
1297
1503
  to: z5.string().min(1).optional(),
1298
1504
  body: z5.string().min(1).optional(),
1299
1505
  unseen: z5.boolean().optional(),
1506
+ flagged: z5.boolean().optional().describe("true = starred only, false = unstarred only, omit for no filter."),
1507
+ answered: z5.boolean().optional().describe("true = replied-to only, false = not-replied-to only, omit for no filter."),
1300
1508
  since_date: z5.string().date().optional(),
1301
1509
  before_date: z5.string().date().optional(),
1302
1510
  larger_than_bytes: z5.number().int().positive().optional().describe("Only match messages larger than this many bytes."),
@@ -1308,10 +1516,26 @@ var Input4 = z5.object({
1308
1516
  'Sub-criteria that must NOT match. Useful for excluding auto-generated mail, e.g. `{not: {from: "noreply"}}`.'
1309
1517
  ),
1310
1518
  limit: z5.number().int().min(1).max(100).default(20),
1311
- max_staleness_seconds: z5.number().int().min(0).default(60),
1519
+ max_staleness_seconds: z5.number().int().min(0).optional().describe(
1520
+ "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
1521
+ ),
1312
1522
  response_format: z5.enum(["markdown", "json"]).default("markdown")
1313
1523
  }).refine(
1314
- (v) => v.subject ?? v.from ?? v.to ?? v.body ?? v.unseen ?? v.since_date ?? v.before_date ?? v.larger_than_bytes ?? v.smaller_than_bytes ?? v.or ?? v.not,
1524
+ (v) => [
1525
+ v.subject,
1526
+ v.from,
1527
+ v.to,
1528
+ v.body,
1529
+ v.unseen,
1530
+ v.flagged,
1531
+ v.answered,
1532
+ v.since_date,
1533
+ v.before_date,
1534
+ v.larger_than_bytes,
1535
+ v.smaller_than_bytes,
1536
+ v.or,
1537
+ v.not
1538
+ ].some((c) => c !== void 0),
1315
1539
  { message: "At least one search criterion must be provided." }
1316
1540
  );
1317
1541
  var searchEmailsTool = defineTool({
@@ -1332,6 +1556,8 @@ var searchEmailsTool = defineTool({
1332
1556
  ...args.to !== void 0 && { to: args.to },
1333
1557
  ...args.body !== void 0 && { body: args.body },
1334
1558
  ...args.unseen !== void 0 && { unseen: args.unseen },
1559
+ ...args.flagged !== void 0 && { flagged: args.flagged },
1560
+ ...args.answered !== void 0 && { answered: args.answered },
1335
1561
  ...args.since_date !== void 0 && { since: new Date(args.since_date) },
1336
1562
  ...args.before_date !== void 0 && { before: new Date(args.before_date) },
1337
1563
  ...args.larger_than_bytes !== void 0 && { larger_than_bytes: args.larger_than_bytes },
@@ -1345,32 +1571,38 @@ var searchEmailsTool = defineTool({
1345
1571
  const imap = await ctx.imap.connection();
1346
1572
  const lock = await imap.getMailboxLock(args.folder);
1347
1573
  let topUids;
1574
+ let cached;
1575
+ let missingUids;
1348
1576
  try {
1349
1577
  const result = await imap.search(criteria, { uid: true });
1350
1578
  matchingUids = Array.isArray(result) ? result : [];
1351
- topUids = [...matchingUids].reverse().slice(0, args.limit);
1352
- const missingUids = topUids.filter((uid) => getEmail(ctx.db, args.folder, uid) === void 0);
1579
+ topUids = matchingUids.toReversed().slice(0, args.limit);
1580
+ cached = getEmailsByUids(ctx.db, args.folder, topUids);
1581
+ missingUids = topUids.filter((uid) => !cached.has(uid));
1353
1582
  if (missingUids.length > 0) {
1354
1583
  const cachedAt = ctx.now();
1584
+ const fetched = [];
1355
1585
  for await (const msg of imap.fetch(
1356
1586
  missingUids,
1357
1587
  { envelope: true, flags: true, internalDate: true, bodyStructure: true },
1358
1588
  { uid: true }
1359
1589
  )) {
1360
1590
  const insert = messageToInsert(args.folder, msg, cachedAt);
1361
- if (insert) upsertEmail(ctx.db, insert);
1591
+ if (insert) fetched.push(insert);
1362
1592
  }
1593
+ upsertEmails(ctx.db, fetched);
1363
1594
  }
1364
1595
  } catch (err) {
1365
1596
  lock.release();
1366
1597
  throw mapImapError(err);
1367
1598
  }
1368
1599
  lock.release();
1369
- const rows = [];
1370
- for (const uid of topUids) {
1371
- const row = getEmail(ctx.db, args.folder, uid);
1372
- if (row) rows.push(row);
1600
+ if (missingUids.length > 0) {
1601
+ for (const [uid, row] of getEmailsByUids(ctx.db, args.folder, missingUids)) {
1602
+ cached.set(uid, row);
1603
+ }
1373
1604
  }
1605
+ const rows = topUids.map((uid) => cached.get(uid)).filter((r) => r !== void 0);
1374
1606
  const structured = {
1375
1607
  folder: args.folder,
1376
1608
  total_matches: matchingUids.length,
@@ -1382,6 +1614,8 @@ var searchEmailsTool = defineTool({
1382
1614
  to: args.to ?? null,
1383
1615
  body: args.body ?? null,
1384
1616
  unseen: args.unseen ?? null,
1617
+ flagged: args.flagged ?? null,
1618
+ answered: args.answered ?? null,
1385
1619
  since_date: args.since_date ?? null,
1386
1620
  before_date: args.before_date ?? null
1387
1621
  }
@@ -1396,30 +1630,47 @@ var searchEmailsTool = defineTool({
1396
1630
 
1397
1631
  // src/tools/emails/mark-read.ts
1398
1632
  import { z as z6 } from "zod";
1399
- var Input5 = z6.object({
1400
- folder: z6.string().min(1).describe("Folder containing the message."),
1401
- uid: z6.number().int().positive().describe("IMAP UID of the message. UIDs are folder-scoped.")
1402
- });
1403
- async function updateSeenFlag(ctx, folder, uid, want) {
1633
+
1634
+ // src/tools/emails/flags.ts
1635
+ async function applyFlags(ctx, folder, uids, change) {
1636
+ const add = change.add ?? [];
1637
+ const remove = change.remove ?? [];
1404
1638
  const imap = await ctx.imap.connection();
1405
1639
  const lock = await imap.getMailboxLock(folder);
1640
+ let ok = true;
1406
1641
  try {
1407
- if (want === "add") {
1408
- await imap.messageFlagsAdd(String(uid), ["\\Seen"], { uid: true });
1409
- } else {
1410
- await imap.messageFlagsRemove(String(uid), ["\\Seen"], { uid: true });
1642
+ if (add.length > 0) {
1643
+ ok = await imap.messageFlagsAdd(uids, add, { uid: true });
1644
+ }
1645
+ if (remove.length > 0) {
1646
+ ok = await imap.messageFlagsRemove(uids, remove, { uid: true }) && ok;
1411
1647
  }
1412
1648
  } catch (err) {
1413
1649
  throw mapImapError(err);
1414
1650
  } finally {
1415
1651
  lock.release();
1416
1652
  }
1417
- const cached = getEmail(ctx.db, folder, uid);
1418
- if (!cached) return;
1419
- const next = want === "add" ? cached.flags.includes("\\Seen") ? cached.flags : [...cached.flags, "\\Seen"] : cached.flags.filter((f) => f !== "\\Seen");
1420
- if (next !== cached.flags) {
1421
- setEmailFlags(ctx.db, folder, uid, next);
1422
- }
1653
+ if (!ok) return false;
1654
+ const addSet = new Set(add);
1655
+ const removeSet = new Set(remove);
1656
+ mutateEmailFlagsForUids(ctx.db, folder, uids, (flags) => [
1657
+ .../* @__PURE__ */ new Set([...flags.filter((f) => !removeSet.has(f)), ...addSet])
1658
+ ]);
1659
+ return true;
1660
+ }
1661
+
1662
+ // src/tools/emails/mark-read.ts
1663
+ var Input5 = z6.object({
1664
+ folder: z6.string().min(1).describe("Folder containing the message."),
1665
+ uid: z6.number().int().positive().describe("IMAP UID of the message. UIDs are folder-scoped.")
1666
+ });
1667
+ function updateSeenFlag(ctx, folder, uid, want) {
1668
+ return applyFlags(
1669
+ ctx,
1670
+ folder,
1671
+ [uid],
1672
+ want === "add" ? { add: ["\\Seen"] } : { remove: ["\\Seen"] }
1673
+ );
1423
1674
  }
1424
1675
  var markReadTool = defineTool({
1425
1676
  name: "imap_mark_read",
@@ -1476,25 +1727,12 @@ var Input6 = z7.object({
1476
1727
  "UIDs of messages to flip. Max 500 per call - chunk your own list for larger batches."
1477
1728
  )
1478
1729
  });
1479
- async function updateSeenFlagBulk(ctx, folder, uids, want) {
1480
- const imap = await ctx.imap.connection();
1481
- const lock = await imap.getMailboxLock(folder);
1482
- try {
1483
- if (want === "add") {
1484
- await imap.messageFlagsAdd(uids, ["\\Seen"], { uid: true });
1485
- } else {
1486
- await imap.messageFlagsRemove(uids, ["\\Seen"], { uid: true });
1487
- }
1488
- } catch (err) {
1489
- throw mapImapError(err);
1490
- } finally {
1491
- lock.release();
1492
- }
1493
- mutateEmailFlagsForUids(
1494
- ctx.db,
1730
+ function updateSeenFlagBulk(ctx, folder, uids, want) {
1731
+ return applyFlags(
1732
+ ctx,
1495
1733
  folder,
1496
1734
  uids,
1497
- (flags) => want === "add" ? flags.includes("\\Seen") ? flags : [...flags, "\\Seen"] : flags.filter((f) => f !== "\\Seen")
1735
+ want === "add" ? { add: ["\\Seen"] } : { remove: ["\\Seen"] }
1498
1736
  );
1499
1737
  }
1500
1738
  var markReadMultipleTool = defineTool({
@@ -1554,12 +1792,64 @@ var markUnreadMultipleTool = defineTool({
1554
1792
  }
1555
1793
  });
1556
1794
 
1557
- // src/tools/emails/move-to-folder.ts
1795
+ // src/tools/emails/set-flags.ts
1558
1796
  import { z as z8 } from "zod";
1797
+ var Flag = z8.enum(["\\Flagged", "\\Answered"]);
1559
1798
  var Input7 = z8.object({
1560
- folder: z8.string().min(1).describe("Current folder of the message."),
1561
- uid: z8.number().int().positive().describe("IMAP UID of the message to move."),
1562
- destination: z8.string().min(1).describe(
1799
+ folder: z8.string().min(1).describe("Folder containing the messages."),
1800
+ uids: z8.array(z8.number().int().positive()).min(1).max(500).describe("UIDs to change. Max 500 per call - chunk your own list for larger batches."),
1801
+ add: z8.array(Flag).optional().describe("Flags to set. \\Flagged is the star / follow-up marker in mail clients."),
1802
+ remove: z8.array(Flag).optional().describe("Flags to clear.")
1803
+ }).refine((v) => (v.add?.length ?? 0) > 0 || (v.remove?.length ?? 0) > 0, {
1804
+ message: "Provide at least one flag in `add` or `remove`."
1805
+ }).refine((v) => !v.add?.some((f) => v.remove?.includes(f)), {
1806
+ message: "A flag cannot appear in both `add` and `remove`."
1807
+ });
1808
+ var setFlagsTool = defineTool({
1809
+ name: "imap_set_flags",
1810
+ description: 'Star, unstar, or mark messages as answered. Use \\Flagged for "star this" and "flag for follow-up" - it is the same marker mail clients show as a star. Read the flags back with imap_list_emails, or find them with imap_search_emails using `flagged` / `answered`. Read/unread has its own tools (imap_mark_read); deleting has imap_delete_email.',
1811
+ annotations: {
1812
+ readOnlyHint: false,
1813
+ destructiveHint: false,
1814
+ idempotentHint: true,
1815
+ openWorldHint: true
1816
+ },
1817
+ inputSchema: Input7,
1818
+ handler: async (args, ctx) => {
1819
+ const change = {
1820
+ ...args.add !== void 0 && { add: args.add },
1821
+ ...args.remove !== void 0 && { remove: args.remove }
1822
+ };
1823
+ const applied = await applyFlags(ctx, args.folder, args.uids, change);
1824
+ const parts = [
1825
+ args.add?.length ? `added ${args.add.join(", ")}` : null,
1826
+ args.remove?.length ? `removed ${args.remove.join(", ")}` : null
1827
+ ].filter((p) => p !== null);
1828
+ return {
1829
+ content: [
1830
+ {
1831
+ type: "text",
1832
+ text: applied ? `Updated ${String(args.uids.length)} message(s) in ${args.folder}: ${parts.join(" and ")}.` : `Server reported no change for ${String(args.uids.length)} message(s) in ${args.folder}. The UIDs may no longer exist, or the mailbox is read-only.`
1833
+ }
1834
+ ],
1835
+ structuredContent: {
1836
+ folder: args.folder,
1837
+ uids: args.uids,
1838
+ count: args.uids.length,
1839
+ added: args.add ?? [],
1840
+ removed: args.remove ?? [],
1841
+ applied
1842
+ }
1843
+ };
1844
+ }
1845
+ });
1846
+
1847
+ // src/tools/emails/move-to-folder.ts
1848
+ import { z as z9 } from "zod";
1849
+ var Input8 = z9.object({
1850
+ folder: z9.string().min(1).describe("Current folder of the message."),
1851
+ uid: z9.number().int().positive().describe("IMAP UID of the message to move."),
1852
+ destination: z9.string().min(1).describe(
1563
1853
  "Target folder path. Use imap_list_folders to discover valid destinations. Must exist on the server."
1564
1854
  )
1565
1855
  });
@@ -1573,7 +1863,7 @@ var moveToFolderTool = defineTool({
1573
1863
  idempotentHint: false,
1574
1864
  openWorldHint: true
1575
1865
  },
1576
- inputSchema: Input7,
1866
+ inputSchema: Input8,
1577
1867
  handler: async (args, ctx) => {
1578
1868
  const imap = await ctx.imap.connection();
1579
1869
  const lock = await imap.getMailboxLock(args.folder);
@@ -1611,11 +1901,11 @@ var moveToFolderTool = defineTool({
1611
1901
  });
1612
1902
 
1613
1903
  // src/tools/emails/move-multiple.ts
1614
- import { z as z9 } from "zod";
1615
- var Input8 = z9.object({
1616
- folder: z9.string().min(1).describe("Current folder of the messages."),
1617
- uids: z9.array(z9.number().int().positive()).min(1).max(500).describe("UIDs to move. Max 500 per call."),
1618
- destination: z9.string().min(1).describe("Target folder. Must exist on the server.")
1904
+ import { z as z10 } from "zod";
1905
+ var Input9 = z10.object({
1906
+ folder: z10.string().min(1).describe("Current folder of the messages."),
1907
+ uids: z10.array(z10.number().int().positive()).min(1).max(500).describe("UIDs to move. Max 500 per call."),
1908
+ destination: z10.string().min(1).describe("Target folder. Must exist on the server.")
1619
1909
  });
1620
1910
  var moveMultipleTool = defineTool({
1621
1911
  name: "imap_move_multiple",
@@ -1626,7 +1916,7 @@ var moveMultipleTool = defineTool({
1626
1916
  idempotentHint: false,
1627
1917
  openWorldHint: true
1628
1918
  },
1629
- inputSchema: Input8,
1919
+ inputSchema: Input9,
1630
1920
  handler: async (args, ctx) => {
1631
1921
  const imap = await ctx.imap.connection();
1632
1922
  const lock = await imap.getMailboxLock(args.folder);
@@ -1663,11 +1953,11 @@ var moveMultipleTool = defineTool({
1663
1953
  });
1664
1954
 
1665
1955
  // src/tools/emails/delete-email.ts
1666
- import { z as z10 } from "zod";
1667
- var Input9 = z10.object({
1668
- folder: z10.string().min(1).describe("Folder containing the message to delete."),
1669
- uid: z10.number().int().positive().describe("IMAP UID of the message to delete."),
1670
- hard_delete: z10.boolean().default(false).describe(
1956
+ import { z as z11 } from "zod";
1957
+ var Input10 = z11.object({
1958
+ folder: z11.string().min(1).describe("Folder containing the message to delete."),
1959
+ uid: z11.number().int().positive().describe("IMAP UID of the message to delete."),
1960
+ hard_delete: z11.boolean().default(false).describe(
1671
1961
  "When false (default), the message is moved to the Trash folder and can be recovered by the user. When true, the message is permanently expunged from the server."
1672
1962
  )
1673
1963
  });
@@ -1680,7 +1970,7 @@ var deleteEmailTool = defineTool({
1680
1970
  idempotentHint: false,
1681
1971
  openWorldHint: true
1682
1972
  },
1683
- inputSchema: Input9,
1973
+ inputSchema: Input10,
1684
1974
  handler: async (args, ctx) => {
1685
1975
  const imap = await ctx.imap.connection();
1686
1976
  if (args.hard_delete) {
@@ -1748,11 +2038,11 @@ var deleteEmailTool = defineTool({
1748
2038
  });
1749
2039
 
1750
2040
  // src/tools/emails/delete-multiple.ts
1751
- import { z as z11 } from "zod";
1752
- var Input10 = z11.object({
1753
- folder: z11.string().min(1).describe("Folder containing the messages to delete."),
1754
- uids: z11.array(z11.number().int().positive()).min(1).max(500).describe("UIDs to delete. Max 500 per call."),
1755
- hard_delete: z11.boolean().default(false).describe(
2041
+ import { z as z12 } from "zod";
2042
+ var Input11 = z12.object({
2043
+ folder: z12.string().min(1).describe("Folder containing the messages to delete."),
2044
+ uids: z12.array(z12.number().int().positive()).min(1).max(500).describe("UIDs to delete. Max 500 per call."),
2045
+ hard_delete: z12.boolean().default(false).describe(
1756
2046
  "When false (default), messages move to the server Trash and can be recovered. When true, they are permanently expunged."
1757
2047
  )
1758
2048
  });
@@ -1765,7 +2055,7 @@ var deleteMultipleTool = defineTool({
1765
2055
  idempotentHint: false,
1766
2056
  openWorldHint: true
1767
2057
  },
1768
- inputSchema: Input10,
2058
+ inputSchema: Input11,
1769
2059
  handler: async (args, ctx) => {
1770
2060
  const imap = await ctx.imap.connection();
1771
2061
  if (args.hard_delete) {
@@ -1835,15 +2125,17 @@ var deleteMultipleTool = defineTool({
1835
2125
  });
1836
2126
 
1837
2127
  // src/tools/drafts/list-drafts.ts
1838
- import { z as z12 } from "zod";
1839
- var Input11 = z12.object({
1840
- folder: z12.string().min(1).optional().describe(
2128
+ import { z as z13 } from "zod";
2129
+ var Input12 = z13.object({
2130
+ folder: z13.string().min(1).optional().describe(
1841
2131
  "Optional explicit Drafts folder path. If omitted, mcp-inbox auto-detects via RFC 6154 SPECIAL-USE."
1842
2132
  ),
1843
- limit: z12.number().int().min(1).max(100).default(20),
1844
- offset: z12.number().int().min(0).default(0),
1845
- max_staleness_seconds: z12.number().int().min(0).default(60),
1846
- response_format: z12.enum(["markdown", "json"]).default("markdown")
2133
+ limit: z13.number().int().min(1).max(100).default(20),
2134
+ offset: z13.number().int().min(0).default(0),
2135
+ max_staleness_seconds: z13.number().int().min(0).optional().describe(
2136
+ "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2137
+ ),
2138
+ response_format: z13.enum(["markdown", "json"]).default("markdown")
1847
2139
  });
1848
2140
  var listDraftsTool = defineTool({
1849
2141
  name: "imap_list_drafts",
@@ -1854,7 +2146,7 @@ var listDraftsTool = defineTool({
1854
2146
  idempotentHint: true,
1855
2147
  openWorldHint: true
1856
2148
  },
1857
- inputSchema: Input11,
2149
+ inputSchema: Input12,
1858
2150
  handler: async (args, ctx) => {
1859
2151
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
1860
2152
  const didSync = await syncIfStale(ctx, folder, args.max_staleness_seconds);
@@ -1881,12 +2173,14 @@ ${formatEmailListMarkdown(rows)}`;
1881
2173
  });
1882
2174
 
1883
2175
  // src/tools/drafts/get-draft.ts
1884
- import { z as z13 } from "zod";
1885
- var Input12 = z13.object({
1886
- uid: z13.number().int().positive().describe("IMAP UID of the draft in the Drafts folder. Use imap_list_drafts to discover UIDs."),
1887
- folder: z13.string().min(1).optional().describe("Optional explicit Drafts folder path. Auto-detected from SPECIAL-USE when omitted."),
1888
- max_staleness_seconds: z13.number().int().min(0).default(60),
1889
- response_format: z13.enum(["markdown", "json"]).default("markdown")
2176
+ import { z as z14 } from "zod";
2177
+ var Input13 = z14.object({
2178
+ uid: z14.number().int().positive().describe("IMAP UID of the draft in the Drafts folder. Use imap_list_drafts to discover UIDs."),
2179
+ folder: z14.string().min(1).optional().describe("Optional explicit Drafts folder path. Auto-detected from SPECIAL-USE when omitted."),
2180
+ max_staleness_seconds: z14.number().int().min(0).optional().describe(
2181
+ "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2182
+ ),
2183
+ response_format: z14.enum(["markdown", "json"]).default("markdown")
1890
2184
  });
1891
2185
  var getDraftTool = defineTool({
1892
2186
  name: "imap_get_draft",
@@ -1897,7 +2191,7 @@ var getDraftTool = defineTool({
1897
2191
  idempotentHint: true,
1898
2192
  openWorldHint: true
1899
2193
  },
1900
- inputSchema: Input12,
2194
+ inputSchema: Input13,
1901
2195
  handler: async (args, ctx) => {
1902
2196
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
1903
2197
  const envelope = await ensureEnvelopeCached(ctx, folder, args.uid, args.max_staleness_seconds);
@@ -1932,7 +2226,7 @@ function formatDraftMarkdown(d) {
1932
2226
  }
1933
2227
 
1934
2228
  // src/tools/drafts/create-draft.ts
1935
- import { z as z14 } from "zod";
2229
+ import { z as z16 } from "zod";
1936
2230
 
1937
2231
  // src/imap/mime-builder.ts
1938
2232
  import MailComposer from "nodemailer/lib/mail-composer/index.js";
@@ -1947,26 +2241,47 @@ async function buildRawMessage(input) {
1947
2241
  ...input.html !== void 0 && { html: input.html },
1948
2242
  ...input.inReplyTo !== void 0 && { inReplyTo: input.inReplyTo },
1949
2243
  ...input.references !== void 0 && { references: input.references },
1950
- ...input.headers !== void 0 && { headers: input.headers }
2244
+ ...input.headers !== void 0 && { headers: input.headers },
2245
+ ...input.attachments !== void 0 && { attachments: input.attachments }
1951
2246
  };
1952
2247
  const composer = new MailComposer(options);
1953
2248
  const message = composer.compile();
1954
2249
  return await message.build();
1955
2250
  }
1956
2251
 
2252
+ // src/tools/compose-schema.ts
2253
+ import { z as z15 } from "zod";
2254
+ var AddressList = z15.union([z15.string().min(1), z15.array(z15.string().min(1)).min(1)]);
2255
+ var AttachmentInput = z15.object({
2256
+ filename: z15.string().min(1).describe('Name the recipient sees, e.g. "invoice.pdf".'),
2257
+ content_base64: z15.base64().describe(
2258
+ "Base64-encoded file bytes. These pass through the model context, so a 2 MB PDF costs roughly 2.7M characters - prefer imap_forward when relaying a file you did not create."
2259
+ ),
2260
+ content_type: z15.string().min(1).optional().describe("MIME type. Omit to let the type be derived from `filename`.")
2261
+ });
2262
+ var AttachmentList = z15.array(AttachmentInput).optional();
2263
+ function toMessageAttachments(input) {
2264
+ if (input === void 0) return void 0;
2265
+ return input.map((a) => ({
2266
+ filename: a.filename,
2267
+ content: Buffer.from(a.content_base64, "base64"),
2268
+ ...a.content_type !== void 0 && { contentType: a.content_type }
2269
+ }));
2270
+ }
2271
+
1957
2272
  // src/tools/drafts/create-draft.ts
1958
- var AddressList = z14.union([z14.string().min(1), z14.array(z14.string().min(1)).min(1)]);
1959
- var Input13 = z14.object({
2273
+ var Input14 = z16.object({
1960
2274
  to: AddressList.describe("Recipient email address or array of addresses."),
1961
- subject: z14.string(),
1962
- body: z14.string().optional().describe("Plain-text body."),
1963
- html: z14.string().optional().describe("HTML body (combined with text via multipart/alternative)."),
2275
+ subject: z16.string(),
2276
+ body: z16.string().optional().describe("Plain-text body."),
2277
+ html: z16.string().optional().describe("HTML body (combined with text via multipart/alternative)."),
1964
2278
  cc: AddressList.optional(),
1965
2279
  bcc: AddressList.optional(),
1966
- from: z14.string().min(1).optional().describe(
2280
+ from: z16.string().min(1).optional().describe(
1967
2281
  "Sender address. Defaults to IMAP_USER. Some providers reject mismatched From headers."
1968
2282
  ),
1969
- folder: z14.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted.")
2283
+ folder: z16.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted."),
2284
+ attachments: AttachmentList
1970
2285
  });
1971
2286
  var createDraftTool = defineTool({
1972
2287
  name: "imap_create_draft",
@@ -1977,9 +2292,10 @@ var createDraftTool = defineTool({
1977
2292
  idempotentHint: false,
1978
2293
  openWorldHint: true
1979
2294
  },
1980
- inputSchema: Input13,
2295
+ inputSchema: Input14,
1981
2296
  handler: async (args, ctx) => {
1982
2297
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2298
+ const attachments = toMessageAttachments(args.attachments);
1983
2299
  const raw = await buildRawMessage({
1984
2300
  from: args.from ?? ctx.defaults.fromAddress,
1985
2301
  to: args.to,
@@ -1987,7 +2303,8 @@ var createDraftTool = defineTool({
1987
2303
  ...args.cc !== void 0 && { cc: args.cc },
1988
2304
  ...args.bcc !== void 0 && { bcc: args.bcc },
1989
2305
  ...args.body !== void 0 && { text: args.body },
1990
- ...args.html !== void 0 && { html: args.html }
2306
+ ...args.html !== void 0 && { html: args.html },
2307
+ ...attachments !== void 0 && { attachments }
1991
2308
  });
1992
2309
  const imap = await ctx.imap.connection();
1993
2310
  let uid;
@@ -2017,18 +2334,18 @@ var createDraftTool = defineTool({
2017
2334
  });
2018
2335
 
2019
2336
  // src/tools/drafts/update-draft.ts
2020
- import { z as z15 } from "zod";
2021
- var AddressList2 = z15.union([z15.string().min(1), z15.array(z15.string().min(1)).min(1)]);
2022
- var Input14 = z15.object({
2023
- uid: z15.number().int().positive().describe("UID of the existing draft to replace. Use imap_list_drafts to find it."),
2024
- to: AddressList2,
2025
- subject: z15.string(),
2026
- body: z15.string().optional(),
2027
- html: z15.string().optional(),
2028
- cc: AddressList2.optional(),
2029
- bcc: AddressList2.optional(),
2030
- from: z15.string().min(1).optional(),
2031
- folder: z15.string().min(1).optional()
2337
+ import { z as z17 } from "zod";
2338
+ var Input15 = z17.object({
2339
+ uid: z17.number().int().positive().describe("UID of the existing draft to replace. Use imap_list_drafts to find it."),
2340
+ to: AddressList,
2341
+ subject: z17.string(),
2342
+ body: z17.string().optional(),
2343
+ html: z17.string().optional(),
2344
+ cc: AddressList.optional(),
2345
+ bcc: AddressList.optional(),
2346
+ from: z17.string().min(1).optional(),
2347
+ folder: z17.string().min(1).optional(),
2348
+ attachments: AttachmentList
2032
2349
  });
2033
2350
  var updateDraftTool = defineTool({
2034
2351
  name: "imap_update_draft",
@@ -2040,9 +2357,10 @@ var updateDraftTool = defineTool({
2040
2357
  idempotentHint: false,
2041
2358
  openWorldHint: true
2042
2359
  },
2043
- inputSchema: Input14,
2360
+ inputSchema: Input15,
2044
2361
  handler: async (args, ctx) => {
2045
2362
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2363
+ const attachments = toMessageAttachments(args.attachments);
2046
2364
  const raw = await buildRawMessage({
2047
2365
  from: args.from ?? ctx.defaults.fromAddress,
2048
2366
  to: args.to,
@@ -2050,7 +2368,8 @@ var updateDraftTool = defineTool({
2050
2368
  ...args.cc !== void 0 && { cc: args.cc },
2051
2369
  ...args.bcc !== void 0 && { bcc: args.bcc },
2052
2370
  ...args.body !== void 0 && { text: args.body },
2053
- ...args.html !== void 0 && { html: args.html }
2371
+ ...args.html !== void 0 && { html: args.html },
2372
+ ...attachments !== void 0 && { attachments }
2054
2373
  });
2055
2374
  const imap = await ctx.imap.connection();
2056
2375
  let newUid;
@@ -2112,7 +2431,7 @@ var updateDraftTool = defineTool({
2112
2431
  });
2113
2432
 
2114
2433
  // src/tools/send/send-email.ts
2115
- import { z as z16 } from "zod";
2434
+ import { z as z18 } from "zod";
2116
2435
 
2117
2436
  // src/tools/send/shared.ts
2118
2437
  function normalizeAddrs(value) {
@@ -2154,28 +2473,28 @@ function flattenCompose(args) {
2154
2473
  }
2155
2474
 
2156
2475
  // src/tools/send/send-email.ts
2157
- var AddressList3 = z16.union([z16.string().min(1), z16.array(z16.string().min(1)).min(1)]);
2158
- var Input15 = z16.object({
2159
- to: AddressList3.describe("Recipient email address or array of addresses."),
2160
- subject: z16.string(),
2161
- body: z16.string().optional().describe("Plain-text body."),
2162
- html: z16.string().optional().describe("HTML body (sent as multipart/alternative with text)."),
2163
- cc: AddressList3.optional(),
2164
- bcc: AddressList3.optional(),
2165
- from: z16.string().min(1).optional().describe(
2476
+ var Input16 = z18.object({
2477
+ to: AddressList.describe("Recipient email address or array of addresses."),
2478
+ subject: z18.string(),
2479
+ body: z18.string().optional().describe("Plain-text body."),
2480
+ html: z18.string().optional().describe("HTML body (sent as multipart/alternative with text)."),
2481
+ cc: AddressList.optional(),
2482
+ bcc: AddressList.optional(),
2483
+ from: z18.string().min(1).optional().describe(
2166
2484
  "Sender address. Defaults to IMAP_USER. Providers like Gmail and Fastmail reject mismatched From unless the address is a verified alias."
2167
- )
2485
+ ),
2486
+ attachments: AttachmentList
2168
2487
  });
2169
2488
  var sendEmailTool = defineTool({
2170
2489
  name: "imap_send_email",
2171
- description: "Send an email via SMTP and append a copy to the Sent folder so it appears in the user mail client. Non-ASCII subjects, multipart text+HTML bodies, and international recipient lists all work through nodemailer's RFC 2822 builder.",
2490
+ description: "Send an email via SMTP and append a copy to the Sent folder so it appears in the user mail client. Non-ASCII subjects, multipart text+HTML bodies, international recipient lists, and base64 attachments all work through nodemailer's RFC 2822 builder.",
2172
2491
  annotations: {
2173
2492
  readOnlyHint: false,
2174
2493
  destructiveHint: true,
2175
2494
  idempotentHint: false,
2176
2495
  openWorldHint: true
2177
2496
  },
2178
- inputSchema: Input15,
2497
+ inputSchema: Input16,
2179
2498
  handler: async (args, ctx) => {
2180
2499
  const compose = flattenCompose({
2181
2500
  ...args.from !== void 0 && { from: args.from },
@@ -2184,6 +2503,7 @@ var sendEmailTool = defineTool({
2184
2503
  ...args.bcc !== void 0 && { bcc: args.bcc }
2185
2504
  });
2186
2505
  const fromAddress = compose.fromOrDefault(ctx.defaults.fromAddress);
2506
+ const attachments = toMessageAttachments(args.attachments);
2187
2507
  const raw = await buildRawMessage({
2188
2508
  from: fromAddress,
2189
2509
  to: args.to,
@@ -2191,7 +2511,8 @@ var sendEmailTool = defineTool({
2191
2511
  ...args.cc !== void 0 && { cc: args.cc },
2192
2512
  ...args.bcc !== void 0 && { bcc: args.bcc },
2193
2513
  ...args.body !== void 0 && { text: args.body },
2194
- ...args.html !== void 0 && { html: args.html }
2514
+ ...args.html !== void 0 && { html: args.html },
2515
+ ...attachments !== void 0 && { attachments }
2195
2516
  });
2196
2517
  const envelope = {
2197
2518
  from: fromAddress,
@@ -2222,11 +2543,11 @@ var sendEmailTool = defineTool({
2222
2543
  });
2223
2544
 
2224
2545
  // src/tools/send/send-draft.ts
2225
- import { z as z17 } from "zod";
2546
+ import { z as z19 } from "zod";
2226
2547
  import { simpleParser as simpleParser2 } from "mailparser";
2227
- var Input16 = z17.object({
2228
- uid: z17.number().int().positive().describe("UID of the draft to send."),
2229
- folder: z17.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted.")
2548
+ var Input17 = z19.object({
2549
+ uid: z19.number().int().positive().describe("UID of the draft to send."),
2550
+ folder: z19.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted.")
2230
2551
  });
2231
2552
  var sendDraftTool = defineTool({
2232
2553
  name: "imap_send_draft",
@@ -2237,7 +2558,7 @@ var sendDraftTool = defineTool({
2237
2558
  idempotentHint: false,
2238
2559
  openWorldHint: true
2239
2560
  },
2240
- inputSchema: Input16,
2561
+ inputSchema: Input17,
2241
2562
  handler: async (args, ctx) => {
2242
2563
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2243
2564
  const imap = await ctx.imap.connection();
@@ -2315,8 +2636,7 @@ var sendDraftTool = defineTool({
2315
2636
  });
2316
2637
  function firstAddress(field) {
2317
2638
  if (!field) return null;
2318
- const obj = field;
2319
- const single = Array.isArray(obj) ? obj[0] : obj;
2639
+ const single = Array.isArray(field) ? field[0] : field;
2320
2640
  if (!single) return null;
2321
2641
  if (typeof single.address === "string") return single.address;
2322
2642
  const fromValue = single.value?.[0]?.address;
@@ -2324,8 +2644,7 @@ function firstAddress(field) {
2324
2644
  }
2325
2645
  function addressList(field) {
2326
2646
  if (!field) return [];
2327
- const obj = field;
2328
- const arr = Array.isArray(obj) ? obj : [obj];
2647
+ const arr = Array.isArray(field) ? field : [field];
2329
2648
  const out = [];
2330
2649
  for (const entry of arr) {
2331
2650
  if (typeof entry.address === "string") {
@@ -2339,20 +2658,25 @@ function addressList(field) {
2339
2658
  }
2340
2659
 
2341
2660
  // src/tools/send/reply.ts
2342
- import { z as z18 } from "zod";
2343
- var AddressList4 = z18.union([z18.string().min(1), z18.array(z18.string().min(1)).min(1)]);
2344
- var Input17 = z18.object({
2345
- folder: z18.string().min(1).describe("Folder of the original message."),
2346
- uid: z18.number().int().positive().describe("UID of the message being replied to."),
2347
- body: z18.string().optional(),
2348
- html: z18.string().optional(),
2349
- cc: AddressList4.optional(),
2350
- bcc: AddressList4.optional(),
2351
- reply_all: z18.boolean().default(false).describe(
2661
+ import { z as z20 } from "zod";
2662
+ var Input18 = z20.object({
2663
+ folder: z20.string().min(1).describe("Folder of the original message."),
2664
+ uid: z20.number().int().positive().describe("UID of the message being replied to."),
2665
+ body: z20.string().optional(),
2666
+ html: z20.string().optional(),
2667
+ cc: AddressList.optional(),
2668
+ bcc: AddressList.optional(),
2669
+ reply_all: z20.boolean().default(false).describe(
2352
2670
  "When true, CC the original To + Cc recipients (minus the sender). When false, reply only to the original From."
2353
2671
  ),
2354
- from: z18.string().min(1).optional(),
2355
- max_staleness_seconds: z18.number().int().min(0).default(60)
2672
+ from: z20.string().min(1).optional(),
2673
+ max_staleness_seconds: z20.number().int().min(0).optional().describe(
2674
+ "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2675
+ ),
2676
+ attachments: AttachmentList,
2677
+ mark_answered: z20.boolean().default(true).describe(
2678
+ "Set \\Answered on the original after sending, so the thread shows as replied in the user mail client. Never fails the send - problems are reported in mark_answered_error."
2679
+ )
2356
2680
  });
2357
2681
  var replyTool = defineTool({
2358
2682
  name: "imap_reply",
@@ -2363,7 +2687,7 @@ var replyTool = defineTool({
2363
2687
  idempotentHint: false,
2364
2688
  openWorldHint: true
2365
2689
  },
2366
- inputSchema: Input17,
2690
+ inputSchema: Input18,
2367
2691
  handler: async (args, ctx) => {
2368
2692
  const original = await ensureEnvelopeCached(
2369
2693
  ctx,
@@ -2379,7 +2703,11 @@ var replyTool = defineTool({
2379
2703
  const bcc = args.bcc !== void 0 ? flattenCompose({ to: "_", bcc: args.bcc }).bcc : [];
2380
2704
  const from = args.from ?? ctx.defaults.fromAddress;
2381
2705
  const subject = prefixSubject(original.subject ?? "", "Re: ");
2382
- const references = buildReferences(parsedEnvelope);
2706
+ const references = mergeReferences(
2707
+ await fetchReferencesHeader(ctx, args.folder, args.uid),
2708
+ parsedEnvelope.messageId
2709
+ );
2710
+ const attachments = toMessageAttachments(args.attachments);
2383
2711
  const raw = await buildRawMessage({
2384
2712
  from,
2385
2713
  to,
@@ -2391,7 +2719,8 @@ var replyTool = defineTool({
2391
2719
  ...parsedEnvelope.messageId !== void 0 && {
2392
2720
  inReplyTo: parsedEnvelope.messageId
2393
2721
  },
2394
- ...references.length > 0 && { references }
2722
+ ...references.length > 0 && { references },
2723
+ ...attachments !== void 0 && { attachments }
2395
2724
  });
2396
2725
  const envelope = {
2397
2726
  from,
@@ -2400,11 +2729,26 @@ var replyTool = defineTool({
2400
2729
  ...bcc.length > 0 && { bcc }
2401
2730
  };
2402
2731
  const result = await sendRawAndAppendSent(ctx, raw, envelope);
2732
+ let originalMarkedAnswered = false;
2733
+ let markAnsweredError = null;
2734
+ if (args.mark_answered) {
2735
+ try {
2736
+ originalMarkedAnswered = await applyFlags(ctx, args.folder, [args.uid], {
2737
+ add: ["\\Answered"]
2738
+ });
2739
+ if (!originalMarkedAnswered) {
2740
+ markAnsweredError = `Server did not apply \\Answered to UID ${String(args.uid)} in ${args.folder}.`;
2741
+ }
2742
+ } catch (err) {
2743
+ markAnsweredError = err instanceof Error ? err.message : String(err);
2744
+ }
2745
+ }
2746
+ const summary = `Replied to "${original.subject ?? "(no subject)"}" (UID ${String(args.uid)}). Sent to ${to.join(", ")}${cc.length > 0 ? `, cc: ${cc.join(", ")}` : ""}.`;
2403
2747
  return {
2404
2748
  content: [
2405
2749
  {
2406
2750
  type: "text",
2407
- text: `Replied to "${original.subject ?? "(no subject)"}" (UID ${String(args.uid)}). Sent to ${to.join(", ")}${cc.length > 0 ? `, cc: ${cc.join(", ")}` : ""}.`
2751
+ text: markAnsweredError !== null ? `${summary} Warning: could not mark the original as answered: ${markAnsweredError}` : summary
2408
2752
  }
2409
2753
  ],
2410
2754
  structuredContent: {
@@ -2417,7 +2761,9 @@ var replyTool = defineTool({
2417
2761
  references,
2418
2762
  message_id: result.messageId,
2419
2763
  sent_folder: result.sentFolder,
2420
- sent_save_error: result.sentSaveError
2764
+ sent_save_error: result.sentSaveError,
2765
+ original_marked_answered: originalMarkedAnswered,
2766
+ mark_answered_error: markAnsweredError
2421
2767
  }
2422
2768
  };
2423
2769
  }
@@ -2437,10 +2783,29 @@ function prefixSubject(subject, prefix) {
2437
2783
  const trimmed = subject.trim();
2438
2784
  return trimmed.toLowerCase().startsWith(prefix.toLowerCase().trim()) ? trimmed : `${prefix}${trimmed}`;
2439
2785
  }
2440
- function buildReferences(env) {
2441
- const refs = [];
2442
- if (env.messageId) refs.push(env.messageId);
2443
- return refs;
2786
+ async function fetchReferencesHeader(ctx, folder, uid) {
2787
+ try {
2788
+ const imap = await ctx.imap.connection();
2789
+ const lock = await imap.getMailboxLock(folder);
2790
+ try {
2791
+ const msg = await imap.fetchOne(String(uid), { headers: ["references"] }, { uid: true });
2792
+ return msg && msg.headers ? msg.headers.toString("utf8") : null;
2793
+ } finally {
2794
+ lock.release();
2795
+ }
2796
+ } catch {
2797
+ return null;
2798
+ }
2799
+ }
2800
+ var REFERENCES_CAP = 20;
2801
+ function mergeReferences(headerValue, parentMessageId, cap = REFERENCES_CAP) {
2802
+ const existing = headerValue?.match(/<[^<>]+>/g) ?? [];
2803
+ const refs = [...existing];
2804
+ if (parentMessageId !== void 0 && !refs.includes(parentMessageId)) {
2805
+ refs.push(parentMessageId);
2806
+ }
2807
+ if (refs.length <= cap) return refs;
2808
+ return [refs[0], ...refs.slice(refs.length - (cap - 1))];
2444
2809
  }
2445
2810
  function dedupeAddrs(addrs, exclude) {
2446
2811
  const seen = /* @__PURE__ */ new Set();
@@ -2455,30 +2820,34 @@ function dedupeAddrs(addrs, exclude) {
2455
2820
  }
2456
2821
 
2457
2822
  // src/tools/send/forward.ts
2458
- import { z as z19 } from "zod";
2459
- var AddressList5 = z19.union([z19.string().min(1), z19.array(z19.string().min(1)).min(1)]);
2460
- var Input18 = z19.object({
2461
- folder: z19.string().min(1).describe("Folder of the original message."),
2462
- uid: z19.number().int().positive().describe("UID of the message to forward."),
2463
- to: AddressList5.describe("Recipient(s) to forward to."),
2464
- body: z19.string().optional().describe(
2823
+ import { z as z21 } from "zod";
2824
+ var Input19 = z21.object({
2825
+ folder: z21.string().min(1).describe("Folder of the original message."),
2826
+ uid: z21.number().int().positive().describe("UID of the message to forward."),
2827
+ to: AddressList.describe("Recipient(s) to forward to."),
2828
+ body: z21.string().optional().describe(
2465
2829
  'Optional prefix body (e.g. "FYI, thought you should see this."). Quoted original follows.'
2466
2830
  ),
2467
- cc: AddressList5.optional(),
2468
- bcc: AddressList5.optional(),
2469
- from: z19.string().min(1).optional(),
2470
- max_staleness_seconds: z19.number().int().min(0).default(60)
2831
+ cc: AddressList.optional(),
2832
+ bcc: AddressList.optional(),
2833
+ from: z21.string().min(1).optional(),
2834
+ max_staleness_seconds: z21.number().int().min(0).optional().describe(
2835
+ "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2836
+ ),
2837
+ attachments: AttachmentList.describe(
2838
+ "Extra files to add. The original message is always attached on top of these."
2839
+ )
2471
2840
  });
2472
2841
  var forwardTool = defineTool({
2473
2842
  name: "imap_forward",
2474
- description: 'Forward an existing message to new recipients. Subject gets a "Fwd: " prefix. The forwarded message is quoted inline with a standard "Begin forwarded message" header. Optional `body` is prepended above the quote.',
2843
+ description: 'Forward an existing message to new recipients. Subject gets a "Fwd: " prefix. The forwarded message is quoted inline with a standard "Begin forwarded message" header, and the untouched original is attached as a .eml file so attachments, signatures and DKIM survive. Optional `body` is prepended above the quote.',
2475
2844
  annotations: {
2476
2845
  readOnlyHint: false,
2477
2846
  destructiveHint: true,
2478
2847
  idempotentHint: false,
2479
2848
  openWorldHint: true
2480
2849
  },
2481
- inputSchema: Input18,
2850
+ inputSchema: Input19,
2482
2851
  handler: async (args, ctx) => {
2483
2852
  const original = await ensureEnvelopeCached(
2484
2853
  ctx,
@@ -2486,7 +2855,7 @@ var forwardTool = defineTool({
2486
2855
  args.uid,
2487
2856
  args.max_staleness_seconds
2488
2857
  );
2489
- const body = await ensureBodyCached(ctx, args.folder, args.uid);
2858
+ const { body, source } = await ensureBodyAndSource(ctx, args.folder, args.uid);
2490
2859
  const compose = flattenCompose({
2491
2860
  ...args.from !== void 0 && { from: args.from },
2492
2861
  to: args.to,
@@ -2516,7 +2885,16 @@ Subject: ${original.subject ?? ""}
2516
2885
  text: forwardedText,
2517
2886
  ...body.bodyHtml !== null && {
2518
2887
  html: (args.body ? `<p>${escapeHtml(args.body)}</p>` : "") + `<hr /><p><b>---------- Forwarded message ----------</b><br /><b>From:</b> ${escapeHtml(originalFrom)}<br /><b>Date:</b> ${escapeHtml(originalDate)}<br /><b>Subject:</b> ${escapeHtml(original.subject ?? "")}<br />` + (originalTo ? `<b>To:</b> ${escapeHtml(originalTo)}<br />` : "") + "</p>" + body.bodyHtml
2519
- }
2888
+ },
2889
+ attachments: [
2890
+ {
2891
+ filename: emlFilename(original.subject),
2892
+ content: source,
2893
+ contentType: "message/rfc822",
2894
+ contentDisposition: "attachment"
2895
+ },
2896
+ ...toMessageAttachments(args.attachments) ?? []
2897
+ ]
2520
2898
  });
2521
2899
  const envelope = {
2522
2900
  from,
@@ -2540,6 +2918,7 @@ Subject: ${original.subject ?? ""}
2540
2918
  subject,
2541
2919
  forwarded_from_folder: args.folder,
2542
2920
  forwarded_uid: args.uid,
2921
+ original_attached: true,
2543
2922
  message_id: result.messageId,
2544
2923
  sent_folder: result.sentFolder,
2545
2924
  sent_save_error: result.sentSaveError
@@ -2551,21 +2930,25 @@ function prefixSubject2(subject, prefix) {
2551
2930
  const trimmed = subject.trim();
2552
2931
  return trimmed.toLowerCase().startsWith(prefix.toLowerCase().trim()) ? trimmed : `${prefix}${trimmed}`;
2553
2932
  }
2933
+ function emlFilename(subject) {
2934
+ const safe = (subject ?? "").replace(new RegExp("\\p{Cc}", "gu"), " ").replace(/[<>:"/\\|?*]/g, "").replace(/\s+/g, " ").trim().slice(0, 80).trim();
2935
+ return `${safe === "" ? "forwarded-message" : safe}.eml`;
2936
+ }
2554
2937
  function escapeHtml(s) {
2555
2938
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2556
2939
  }
2557
2940
 
2558
2941
  // src/tools/attachments/get-attachment.ts
2559
- import { z as z20 } from "zod";
2942
+ import { z as z22 } from "zod";
2560
2943
  import { simpleParser as simpleParser3 } from "mailparser";
2561
- var Input19 = z20.object({
2562
- folder: z20.string().min(1).describe("Folder containing the message."),
2563
- uid: z20.number().int().positive().describe("IMAP UID of the message."),
2564
- filename: z20.string().min(1).optional().describe(
2944
+ var Input20 = z22.object({
2945
+ folder: z22.string().min(1).describe("Folder containing the message."),
2946
+ uid: z22.number().int().positive().describe("IMAP UID of the message."),
2947
+ filename: z22.string().min(1).optional().describe(
2565
2948
  "Filename of the attachment to fetch. First match wins if the message has multiple attachments with the same name - use part_id to disambiguate."
2566
2949
  ),
2567
- part_id: z20.string().min(1).optional().describe('MIME part ID (e.g. "1.2"). Use when multiple parts share a filename.'),
2568
- max_inline_mb: z20.number().int().min(1).max(50).default(5).describe(
2950
+ part_id: z22.string().min(1).optional().describe('MIME part ID (e.g. "1.2"). Use when multiple parts share a filename.'),
2951
+ max_inline_mb: z22.number().int().min(1).max(50).default(5).describe(
2569
2952
  "Maximum attachment size to return inline, in MB. Attachments larger than this are rejected with a clear error. Cap exists to avoid blowing up MCP response size."
2570
2953
  )
2571
2954
  }).refine((v) => v.filename !== void 0 || v.part_id !== void 0, {
@@ -2580,7 +2963,7 @@ var getAttachmentTool = defineTool({
2580
2963
  idempotentHint: true,
2581
2964
  openWorldHint: true
2582
2965
  },
2583
- inputSchema: Input19,
2966
+ inputSchema: Input20,
2584
2967
  handler: async (args, ctx) => {
2585
2968
  const imap = await ctx.imap.connection();
2586
2969
  const lock = await imap.getMailboxLock(args.folder);
@@ -2661,36 +3044,19 @@ var getAttachmentTool = defineTool({
2661
3044
  }
2662
3045
  });
2663
3046
  function findAttachmentPart(structure, selector) {
2664
- const stack = [structure];
2665
- while (stack.length > 0) {
2666
- const node = stack.pop();
3047
+ const queue = [structure];
3048
+ while (queue.length > 0) {
3049
+ const node = queue.shift();
2667
3050
  if (!node) continue;
2668
- if (node.childNodes) {
2669
- for (const child of node.childNodes) stack.push(child);
2670
- continue;
2671
- }
2672
3051
  const partId = node.part;
2673
- if (!partId) continue;
2674
3052
  const nodeFilename = node.dispositionParameters?.filename ?? node.parameters?.name;
2675
- if (selector.part_id !== void 0) {
2676
- if (partId === selector.part_id) {
2677
- return {
2678
- partId,
2679
- filename: nodeFilename,
2680
- contentType: node.type,
2681
- size: node.size
2682
- };
3053
+ if (partId !== void 0) {
3054
+ const matches = selector.part_id !== void 0 ? partId === selector.part_id : selector.filename !== void 0 && nodeFilename === selector.filename;
3055
+ if (matches) {
3056
+ return { partId, filename: nodeFilename, contentType: node.type, size: node.size };
2683
3057
  }
2684
- continue;
2685
- }
2686
- if (selector.filename !== void 0 && nodeFilename === selector.filename) {
2687
- return {
2688
- partId,
2689
- filename: nodeFilename,
2690
- contentType: node.type,
2691
- size: node.size
2692
- };
2693
3058
  }
3059
+ if (node.childNodes) queue.push(...node.childNodes);
2694
3060
  }
2695
3061
  return null;
2696
3062
  }
@@ -2718,6 +3084,7 @@ var tools = [
2718
3084
  // Write (flag + move + delete)
2719
3085
  markReadTool,
2720
3086
  markUnreadTool,
3087
+ setFlagsTool,
2721
3088
  moveToFolderTool,
2722
3089
  deleteEmailTool,
2723
3090
  // Bulk variants of the same (one IMAP round-trip for N UIDs)
@@ -2748,7 +3115,7 @@ function listToolEntries() {
2748
3115
  // this setting, such types become `{}` (matches anything) in the
2749
3116
  // exposed inputSchema, and the real validation still happens on
2750
3117
  // the Zod side inside the CallTool dispatcher.
2751
- inputSchema: z21.toJSONSchema(t.inputSchema, {
3118
+ inputSchema: z23.toJSONSchema(t.inputSchema, {
2752
3119
  target: "draft-7",
2753
3120
  unrepresentable: "any"
2754
3121
  }),
@@ -2757,12 +3124,12 @@ function listToolEntries() {
2757
3124
  }
2758
3125
 
2759
3126
  // src/server.ts
2760
- var log6 = createLogger("mcp-inbox:server");
3127
+ var log7 = createLogger("mcp-inbox:server");
2761
3128
  function createMcpServer(ctx) {
2762
3129
  const server = new Server(
2763
3130
  {
2764
3131
  name: "mcp-inbox",
2765
- version: "0.1.0"
3132
+ version: package_default.version
2766
3133
  },
2767
3134
  {
2768
3135
  capabilities: {
@@ -2777,27 +3144,27 @@ function createMcpServer(ctx) {
2777
3144
  const toolName = request.params.name;
2778
3145
  const tool = findTool(toolName);
2779
3146
  if (!tool) {
2780
- log6.warn("unknown tool", { tool: toolName });
3147
+ log7.warn("unknown tool", { tool: toolName });
2781
3148
  return errorResult(`Unknown tool: ${toolName}`);
2782
3149
  }
2783
3150
  const parsed = tool.inputSchema.safeParse(request.params.arguments ?? {});
2784
3151
  if (!parsed.success) {
2785
3152
  const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
2786
- log6.warn("invalid tool args", { tool: toolName, issues });
3153
+ log7.warn("invalid tool args", { tool: toolName, issues });
2787
3154
  return errorResult(`Invalid arguments for ${toolName}: ${issues}`);
2788
3155
  }
2789
3156
  try {
2790
3157
  return await tool.handler(parsed.data, ctx);
2791
3158
  } catch (err) {
2792
3159
  if (isMcpInboxError(err)) {
2793
- log6.warn("tool returned mcp-inbox error", {
3160
+ log7.warn("tool returned mcp-inbox error", {
2794
3161
  tool: toolName,
2795
3162
  code: err.code,
2796
3163
  msg: err.userMessage
2797
3164
  });
2798
3165
  return errorResult(err.userMessage);
2799
3166
  }
2800
- log6.error("tool handler threw", {
3167
+ log7.error("tool handler threw", {
2801
3168
  tool: toolName,
2802
3169
  msg: err instanceof Error ? err.message : String(err)
2803
3170
  });
@@ -2806,7 +3173,7 @@ function createMcpServer(ctx) {
2806
3173
  });
2807
3174
  server.onerror = (err) => {
2808
3175
  const meta = isMcpInboxError(err) ? { code: err.code, msg: err.userMessage } : { msg: err instanceof Error ? err.message : String(err) };
2809
- log6.error("mcp server error", meta);
3176
+ log7.error("mcp server error", meta);
2810
3177
  };
2811
3178
  return server;
2812
3179
  }
@@ -2833,12 +3200,22 @@ try {
2833
3200
  configureLogger({ debug: config.debug, level: "info" });
2834
3201
  rootLogger.info("booting mcp-inbox", {
2835
3202
  imapHost: config.imap.host,
2836
- cacheEnabled: config.cache.enabled,
2837
3203
  cacheDir: config.cache.dir,
3204
+ cacheStalenessSec: config.cache.defaultStalenessSec,
2838
3205
  idleEnabled: config.idle.enabled,
2839
3206
  idleFolders: config.idle.folders
2840
3207
  });
2841
3208
  const cache = openCache(join2(config.cache.dir, "cache.db"), DEFAULT_MIGRATIONS_FOLDER);
3209
+ if (config.cache.bodyRetainDays > 0) {
3210
+ const cutoff = Date.now() - config.cache.bodyRetainDays * 864e5;
3211
+ const pruned = pruneBodiesBefore(cache.db, cutoff);
3212
+ if (pruned > 0) {
3213
+ rootLogger.info("pruned stale message bodies", {
3214
+ rows: pruned,
3215
+ retainDays: config.cache.bodyRetainDays
3216
+ });
3217
+ }
3218
+ }
2842
3219
  const imapClient = new ImapClient(config.imap);
2843
3220
  const smtpClient = new SmtpClient(config.smtp);
2844
3221
  const ctx = {
@@ -2917,4 +3294,3 @@ try {
2917
3294
  }
2918
3295
  process.exit(1);
2919
3296
  }
2920
- //# sourceMappingURL=app.js.map