@kbzowski/mcp-inbox 0.3.2 → 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/README.md +25 -214
- package/dist/app.js +784 -376
- package/dist/cache/queries.d.ts +33 -4
- package/dist/cache/schema.d.ts +24 -2
- package/dist/cache/sync.d.ts +24 -7
- package/dist/config/env.d.ts +15 -27
- package/dist/imap/client.d.ts +9 -1
- package/dist/imap/mime-builder.d.ts +12 -0
- package/dist/imap/search.d.ts +6 -0
- package/dist/index.js +0 -1
- package/dist/migrations/20260804112339_fantastic_miss_america/migration.sql +1 -0
- package/dist/migrations/20260804112339_fantastic_miss_america/snapshot.json +310 -0
- package/dist/tools/compose-schema.d.ts +14 -0
- package/dist/tools/drafts/create-draft.d.ts +5 -0
- package/dist/tools/drafts/get-draft.d.ts +1 -1
- package/dist/tools/drafts/list-drafts.d.ts +1 -1
- package/dist/tools/drafts/update-draft.d.ts +5 -0
- package/dist/tools/emails/flags.d.ts +15 -0
- package/dist/tools/emails/get-email.d.ts +1 -1
- package/dist/tools/emails/list-emails.d.ts +1 -1
- package/dist/tools/emails/search-emails.d.ts +3 -1
- package/dist/tools/emails/set-flags.d.ts +13 -0
- package/dist/tools/emails/shared.d.ts +25 -27
- package/dist/tools/send/forward.d.ts +7 -1
- package/dist/tools/send/reply.d.ts +14 -1
- package/dist/tools/send/send-email.d.ts +5 -0
- package/package.json +14 -13
- package/dist/app.js.map +0 -7
- package/dist/index.js.map +0 -7
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
573
|
+
var log3 = createLogger("mcp-inbox:imap");
|
|
412
574
|
async function createImapConnection(config) {
|
|
413
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
680
|
+
log3.warn("error during IMAP logout", {
|
|
501
681
|
msg: err instanceof Error ? err.message : String(err)
|
|
502
682
|
});
|
|
503
683
|
}
|
|
@@ -505,107 +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 listEmailsByFolder(db, 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
|
-
let rows = db.select().from(emails).where(and(...conditions)).orderBy(desc(emails.date), desc(emails.uid)).limit(opts.limit ?? 100).offset(opts.offset ?? 0).all();
|
|
552
|
-
if (opts.unseenOnly) {
|
|
553
|
-
rows = rows.filter((r) => !r.flags.includes("\\Seen"));
|
|
554
|
-
}
|
|
555
|
-
return rows;
|
|
556
|
-
}
|
|
557
|
-
function countEmailsInFolder(db, folder) {
|
|
558
|
-
const row = db.select({ n: sql`count(*)` }).from(emails).where(eq(emails.folder, folder)).get();
|
|
559
|
-
return row?.n ?? 0;
|
|
560
|
-
}
|
|
561
|
-
function setEmailFlags(db, folder, uid, flags) {
|
|
562
|
-
db.update(emails).set({ flags }).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
|
|
563
|
-
}
|
|
564
|
-
function mutateEmailFlagsForUids(db, folder, uids, mutate) {
|
|
565
|
-
if (uids.length === 0) return;
|
|
566
|
-
db.transaction((tx) => {
|
|
567
|
-
const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, uids))).all();
|
|
568
|
-
for (const row of rows) {
|
|
569
|
-
const next = mutate(row.flags);
|
|
570
|
-
if (flagsEqual(row.flags, next)) continue;
|
|
571
|
-
tx.update(emails).set({ flags: next }).where(and(eq(emails.folder, folder), eq(emails.uid, row.uid))).run();
|
|
572
|
-
}
|
|
573
|
-
});
|
|
574
|
-
}
|
|
575
|
-
function flagsEqual(a, b) {
|
|
576
|
-
if (a.length !== b.length) return false;
|
|
577
|
-
const setB = new Set(b);
|
|
578
|
-
for (const f of a) if (!setB.has(f)) return false;
|
|
579
|
-
return true;
|
|
580
|
-
}
|
|
581
|
-
function deleteEmailsByFolder(db, folder) {
|
|
582
|
-
db.delete(emails).where(eq(emails.folder, folder)).run();
|
|
583
|
-
}
|
|
584
|
-
function deleteEmail(db, folder, uid) {
|
|
585
|
-
db.delete(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
|
|
586
|
-
}
|
|
587
|
-
function deleteEmailsByUids(db, folder, uids) {
|
|
588
|
-
if (uids.length === 0) return;
|
|
589
|
-
db.delete(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, uids))).run();
|
|
590
|
-
}
|
|
591
|
-
function getEmailBody(db, folder, uid) {
|
|
592
|
-
const row = db.select({
|
|
593
|
-
bodyText: emails.bodyText,
|
|
594
|
-
bodyHtml: emails.bodyHtml,
|
|
595
|
-
bodyCachedAt: emails.bodyCachedAt
|
|
596
|
-
}).from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
|
|
597
|
-
return row;
|
|
598
|
-
}
|
|
599
|
-
function setEmailBody(db, folder, uid, body, nowMs) {
|
|
600
|
-
db.update(emails).set({
|
|
601
|
-
bodyText: body.text,
|
|
602
|
-
bodyHtml: body.html,
|
|
603
|
-
bodyCachedAt: nowMs
|
|
604
|
-
}).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
|
|
605
|
-
}
|
|
606
|
-
|
|
607
688
|
// src/cache/sync.ts
|
|
608
|
-
var
|
|
689
|
+
var log4 = createLogger("mcp-inbox:sync");
|
|
690
|
+
var ENVELOPE_FLUSH_SIZE = 500;
|
|
609
691
|
async function syncFolder(ctx, folderPath) {
|
|
610
692
|
const started = Date.now();
|
|
611
693
|
const lock = await ctx.imap.getMailboxLock(folderPath);
|
|
@@ -617,7 +699,7 @@ async function syncFolder(ctx, folderPath) {
|
|
|
617
699
|
const cached = getFolder(ctx.db, folderPath);
|
|
618
700
|
const uidValidityChanged = cached !== void 0 && cached.uidValidity !== Number(box.uidValidity);
|
|
619
701
|
if (uidValidityChanged) {
|
|
620
|
-
|
|
702
|
+
log4.warn("UIDVALIDITY changed - wiping folder cache", {
|
|
621
703
|
folder: folderPath,
|
|
622
704
|
cached: cached?.uidValidity,
|
|
623
705
|
server: Number(box.uidValidity)
|
|
@@ -635,7 +717,7 @@ async function syncFolder(ctx, folderPath) {
|
|
|
635
717
|
lastSyncedAt: Date.now()
|
|
636
718
|
});
|
|
637
719
|
const durationMs = Date.now() - started;
|
|
638
|
-
|
|
720
|
+
log4.info("folder synced", { folder: folderPath, syncType, fetched, durationMs });
|
|
639
721
|
return { folder: folderPath, syncType, fetched, durationMs };
|
|
640
722
|
} catch (err) {
|
|
641
723
|
throw mapImapError(err);
|
|
@@ -643,45 +725,72 @@ async function syncFolder(ctx, folderPath) {
|
|
|
643
725
|
lock.release();
|
|
644
726
|
}
|
|
645
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
|
+
}
|
|
646
740
|
async function runSync(ctx, folderPath, box, cached, uidValidityChanged) {
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
}
|
|
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;
|
|
651
750
|
const serverModseq = box.highestModseq !== void 0 ? Number(box.highestModseq) : null;
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
}
|
|
656
|
-
const fetched2 = await fetchAndStoreRange(ctx, folderPath, "1:*", BigInt(cached.highestModseq));
|
|
657
|
-
return { syncType: "incremental", fetched: fetched2 };
|
|
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));
|
|
658
754
|
}
|
|
659
|
-
|
|
660
|
-
|
|
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 };
|
|
661
760
|
}
|
|
662
|
-
async function
|
|
761
|
+
async function fetchEnvelopes(ctx, folderPath, uids) {
|
|
663
762
|
const now = Date.now();
|
|
664
763
|
let count = 0;
|
|
665
|
-
const options = changedSince !== void 0 ? { uid: true, changedSince } : { uid: true };
|
|
666
764
|
const iterator = ctx.imap.fetch(
|
|
667
|
-
|
|
668
|
-
{
|
|
669
|
-
|
|
670
|
-
flags: true,
|
|
671
|
-
internalDate: true,
|
|
672
|
-
bodyStructure: true
|
|
673
|
-
},
|
|
674
|
-
options
|
|
765
|
+
uids,
|
|
766
|
+
{ envelope: true, flags: true, internalDate: true, bodyStructure: true },
|
|
767
|
+
{ uid: true }
|
|
675
768
|
);
|
|
769
|
+
const buffer = [];
|
|
676
770
|
for await (const msg of iterator) {
|
|
677
771
|
const insert = messageToInsert(folderPath, msg, now);
|
|
678
772
|
if (insert) {
|
|
679
|
-
|
|
773
|
+
buffer.push(insert);
|
|
680
774
|
count++;
|
|
775
|
+
if (buffer.length >= ENVELOPE_FLUSH_SIZE) {
|
|
776
|
+
upsertEmails(ctx.db, buffer);
|
|
777
|
+
buffer.length = 0;
|
|
778
|
+
}
|
|
681
779
|
}
|
|
682
780
|
}
|
|
781
|
+
upsertEmails(ctx.db, buffer);
|
|
683
782
|
return count;
|
|
684
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
|
+
}
|
|
685
794
|
function messageToInsert(folderPath, msg, cachedAt) {
|
|
686
795
|
if (typeof msg.uid !== "number") return null;
|
|
687
796
|
const env = msg.envelope;
|
|
@@ -714,7 +823,7 @@ function hasAttachments(structure) {
|
|
|
714
823
|
}
|
|
715
824
|
|
|
716
825
|
// src/cache/idle.ts
|
|
717
|
-
var
|
|
826
|
+
var log5 = createLogger("mcp-inbox:idle");
|
|
718
827
|
var IdleManager = class {
|
|
719
828
|
#opts;
|
|
720
829
|
#subscriptions = [];
|
|
@@ -730,7 +839,7 @@ var IdleManager = class {
|
|
|
730
839
|
const sub = await this.#watchFolder(folder);
|
|
731
840
|
this.#subscriptions.push(sub);
|
|
732
841
|
} catch (err) {
|
|
733
|
-
|
|
842
|
+
log5.error("failed to open IDLE for folder", {
|
|
734
843
|
folder,
|
|
735
844
|
msg: err instanceof Error ? err.message : String(err)
|
|
736
845
|
});
|
|
@@ -748,13 +857,13 @@ var IdleManager = class {
|
|
|
748
857
|
async #watchFolder(folder) {
|
|
749
858
|
const imap = await createImapConnection(this.#opts.imap);
|
|
750
859
|
await imap.mailboxOpen(folder);
|
|
751
|
-
|
|
860
|
+
log5.info("watching folder", { folder });
|
|
752
861
|
const onExists = (e) => {
|
|
753
|
-
|
|
862
|
+
log5.debug("exists event", { folder: e.path, count: e.count, prevCount: e.prevCount });
|
|
754
863
|
void this.#handleExists(folder, imap);
|
|
755
864
|
};
|
|
756
865
|
const onFlags = (e) => {
|
|
757
|
-
|
|
866
|
+
log5.debug("flags event", { folder: e.path, uid: e.uid, flags: Array.from(e.flags) });
|
|
758
867
|
if (e.uid !== void 0) {
|
|
759
868
|
setEmailFlags(this.#opts.db, folder, e.uid, Array.from(e.flags));
|
|
760
869
|
} else {
|
|
@@ -762,7 +871,7 @@ var IdleManager = class {
|
|
|
762
871
|
}
|
|
763
872
|
};
|
|
764
873
|
const onExpunge = (e) => {
|
|
765
|
-
|
|
874
|
+
log5.debug("expunge event", { folder: e.path, uid: e.uid, seq: e.seq });
|
|
766
875
|
if (e.uid !== void 0) {
|
|
767
876
|
deleteEmail(this.#opts.db, folder, e.uid);
|
|
768
877
|
} else {
|
|
@@ -781,7 +890,7 @@ var IdleManager = class {
|
|
|
781
890
|
try {
|
|
782
891
|
await imap.logout();
|
|
783
892
|
} catch (err) {
|
|
784
|
-
|
|
893
|
+
log5.warn("error closing IDLE connection", {
|
|
785
894
|
folder,
|
|
786
895
|
msg: err instanceof Error ? err.message : String(err)
|
|
787
896
|
});
|
|
@@ -793,7 +902,7 @@ var IdleManager = class {
|
|
|
793
902
|
try {
|
|
794
903
|
await syncFolder({ db: this.#opts.db, imap }, folder);
|
|
795
904
|
} catch (err) {
|
|
796
|
-
|
|
905
|
+
log5.error("exists sync failed", {
|
|
797
906
|
folder,
|
|
798
907
|
msg: err instanceof Error ? err.message : String(err)
|
|
799
908
|
});
|
|
@@ -803,7 +912,7 @@ var IdleManager = class {
|
|
|
803
912
|
try {
|
|
804
913
|
await syncFolder({ db: this.#opts.db, imap }, folder);
|
|
805
914
|
} catch (err) {
|
|
806
|
-
|
|
915
|
+
log5.error("resync failed", {
|
|
807
916
|
folder,
|
|
808
917
|
msg: err instanceof Error ? err.message : String(err)
|
|
809
918
|
});
|
|
@@ -813,7 +922,7 @@ var IdleManager = class {
|
|
|
813
922
|
|
|
814
923
|
// src/smtp/client.ts
|
|
815
924
|
import nodemailer from "nodemailer";
|
|
816
|
-
var
|
|
925
|
+
var log6 = createLogger("mcp-inbox:smtp");
|
|
817
926
|
var SmtpClient = class {
|
|
818
927
|
#config;
|
|
819
928
|
#transporter = null;
|
|
@@ -826,7 +935,7 @@ var SmtpClient = class {
|
|
|
826
935
|
throw new Error("SmtpClient has been closed");
|
|
827
936
|
}
|
|
828
937
|
if (this.#transporter) return this.#transporter;
|
|
829
|
-
|
|
938
|
+
log6.info("creating SMTP transporter", {
|
|
830
939
|
host: this.#config.host,
|
|
831
940
|
port: this.#config.port,
|
|
832
941
|
secure: this.#config.secure
|
|
@@ -881,8 +990,100 @@ import {
|
|
|
881
990
|
ListToolsRequestSchema
|
|
882
991
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
883
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
|
+
|
|
884
1085
|
// src/tools/registry.ts
|
|
885
|
-
import { z as
|
|
1086
|
+
import { z as z23 } from "zod";
|
|
886
1087
|
|
|
887
1088
|
// src/tools/folders/list-folders.ts
|
|
888
1089
|
import { z as z2 } from "zod";
|
|
@@ -1013,7 +1214,7 @@ var NAME_CANDIDATES = {
|
|
|
1013
1214
|
};
|
|
1014
1215
|
|
|
1015
1216
|
// src/tools/emails/shared.ts
|
|
1016
|
-
async function syncIfStale(ctx, folder, maxStalenessSec) {
|
|
1217
|
+
async function syncIfStale(ctx, folder, maxStalenessSec = ctx.cacheConfig.defaultStalenessSec) {
|
|
1017
1218
|
const cached = getFolder(ctx.db, folder);
|
|
1018
1219
|
const ageMs = cached ? ctx.now() - cached.lastSyncedAt : Infinity;
|
|
1019
1220
|
const stale = ageMs >= maxStalenessSec * 1e3;
|
|
@@ -1025,7 +1226,7 @@ async function syncIfStale(ctx, folder, maxStalenessSec) {
|
|
|
1025
1226
|
}
|
|
1026
1227
|
function readEnvelopes(ctx, folder, opts) {
|
|
1027
1228
|
const rows = listEmailsByFolder(ctx.db, folder, opts);
|
|
1028
|
-
const total = countEmailsInFolder(ctx.db, folder);
|
|
1229
|
+
const total = countEmailsInFolder(ctx.db, folder, opts);
|
|
1029
1230
|
const offset = opts.offset ?? 0;
|
|
1030
1231
|
const limit = opts.limit ?? 100;
|
|
1031
1232
|
const hasMore = offset + rows.length < total;
|
|
@@ -1034,8 +1235,7 @@ function readEnvelopes(ctx, folder, opts) {
|
|
|
1034
1235
|
async function resolveSpecialFolder(ctx, attr, explicitOverride) {
|
|
1035
1236
|
if (explicitOverride) return explicitOverride;
|
|
1036
1237
|
try {
|
|
1037
|
-
const
|
|
1038
|
-
const list = await imap.list();
|
|
1238
|
+
const list = await ctx.imap.folderList();
|
|
1039
1239
|
const path = findSpecialFolder(list, attr);
|
|
1040
1240
|
if (!path) {
|
|
1041
1241
|
throw new ImapError(
|
|
@@ -1049,7 +1249,7 @@ async function resolveSpecialFolder(ctx, attr, explicitOverride) {
|
|
|
1049
1249
|
throw mapImapError(err);
|
|
1050
1250
|
}
|
|
1051
1251
|
}
|
|
1052
|
-
async function
|
|
1252
|
+
async function fetchRawSource(ctx, folder, uid) {
|
|
1053
1253
|
const imap = await ctx.imap.connection();
|
|
1054
1254
|
const lock = await imap.getMailboxLock(folder);
|
|
1055
1255
|
try {
|
|
@@ -1060,19 +1260,7 @@ async function ensureBodyCached(ctx, folder, uid) {
|
|
|
1060
1260
|
`Message with UID ${String(uid)} was not found in ${folder}. It may have been moved or deleted.`
|
|
1061
1261
|
);
|
|
1062
1262
|
}
|
|
1063
|
-
|
|
1064
|
-
const bodyText = parsed.text ?? null;
|
|
1065
|
-
const bodyHtml = typeof parsed.html === "string" ? parsed.html : null;
|
|
1066
|
-
const cached = getEmailBody(ctx.db, folder, uid);
|
|
1067
|
-
if (cached?.bodyCachedAt == null) {
|
|
1068
|
-
setEmailBody(ctx.db, folder, uid, { text: bodyText, html: bodyHtml }, ctx.now());
|
|
1069
|
-
}
|
|
1070
|
-
const attachments = (parsed.attachments ?? []).map((a) => ({
|
|
1071
|
-
filename: a.filename ?? null,
|
|
1072
|
-
content_type: a.contentType ?? "application/octet-stream",
|
|
1073
|
-
size_bytes: typeof a.size === "number" ? a.size : 0
|
|
1074
|
-
}));
|
|
1075
|
-
return { bodyText, bodyHtml, attachments };
|
|
1263
|
+
return msg.source;
|
|
1076
1264
|
} catch (err) {
|
|
1077
1265
|
if (err instanceof ImapError) throw err;
|
|
1078
1266
|
throw mapImapError(err);
|
|
@@ -1080,6 +1268,37 @@ async function ensureBodyCached(ctx, folder, uid) {
|
|
|
1080
1268
|
lock.release();
|
|
1081
1269
|
}
|
|
1082
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
|
+
}
|
|
1083
1302
|
async function ensureEnvelopeCached(ctx, folder, uid, maxStalenessSec) {
|
|
1084
1303
|
const existing = getEmail(ctx.db, folder, uid);
|
|
1085
1304
|
if (existing !== void 0) {
|
|
@@ -1120,8 +1339,8 @@ var Input2 = z3.object({
|
|
|
1120
1339
|
unseen_only: z3.boolean().default(false),
|
|
1121
1340
|
since_date: z3.string().date().optional().describe("YYYY-MM-DD. Only return emails received on or after this date."),
|
|
1122
1341
|
before_date: z3.string().date().optional().describe("YYYY-MM-DD. Only return emails received strictly before this date."),
|
|
1123
|
-
max_staleness_seconds: z3.number().int().min(0).
|
|
1124
|
-
"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."
|
|
1125
1344
|
),
|
|
1126
1345
|
response_format: z3.enum(["markdown", "json"]).default("markdown")
|
|
1127
1346
|
});
|
|
@@ -1171,7 +1390,9 @@ var Input3 = z4.object({
|
|
|
1171
1390
|
uid: z4.number().int().positive().describe(
|
|
1172
1391
|
"IMAP UID of the message. UIDs are folder-scoped - a UID from INBOX cannot be reused with the Sent folder."
|
|
1173
1392
|
),
|
|
1174
|
-
max_staleness_seconds: z4.number().int().min(0).
|
|
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
|
+
),
|
|
1175
1396
|
response_format: z4.enum(["markdown", "json"]).default("markdown")
|
|
1176
1397
|
});
|
|
1177
1398
|
var getEmailTool = defineTool({
|
|
@@ -1245,6 +1466,8 @@ function buildImapSearch(c) {
|
|
|
1245
1466
|
if (c.since) q.since = c.since;
|
|
1246
1467
|
if (c.before) q.before = c.before;
|
|
1247
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;
|
|
1248
1471
|
if (c.larger_than_bytes !== void 0) q.larger = c.larger_than_bytes;
|
|
1249
1472
|
if (c.smaller_than_bytes !== void 0) q.smaller = c.smaller_than_bytes;
|
|
1250
1473
|
if (c.or !== void 0 && c.or.length > 0) q.or = c.or.map(buildImapSearch);
|
|
@@ -1263,6 +1486,8 @@ var Criteria = z5.lazy(
|
|
|
1263
1486
|
to: z5.string().min(1).optional(),
|
|
1264
1487
|
body: z5.string().min(1).optional(),
|
|
1265
1488
|
unseen: z5.boolean().optional(),
|
|
1489
|
+
flagged: z5.boolean().optional(),
|
|
1490
|
+
answered: z5.boolean().optional(),
|
|
1266
1491
|
since: z5.coerce.date().optional(),
|
|
1267
1492
|
before: z5.coerce.date().optional(),
|
|
1268
1493
|
larger_than_bytes: z5.number().int().positive().optional(),
|
|
@@ -1278,6 +1503,8 @@ var Input4 = z5.object({
|
|
|
1278
1503
|
to: z5.string().min(1).optional(),
|
|
1279
1504
|
body: z5.string().min(1).optional(),
|
|
1280
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."),
|
|
1281
1508
|
since_date: z5.string().date().optional(),
|
|
1282
1509
|
before_date: z5.string().date().optional(),
|
|
1283
1510
|
larger_than_bytes: z5.number().int().positive().optional().describe("Only match messages larger than this many bytes."),
|
|
@@ -1289,10 +1516,26 @@ var Input4 = z5.object({
|
|
|
1289
1516
|
'Sub-criteria that must NOT match. Useful for excluding auto-generated mail, e.g. `{not: {from: "noreply"}}`.'
|
|
1290
1517
|
),
|
|
1291
1518
|
limit: z5.number().int().min(1).max(100).default(20),
|
|
1292
|
-
max_staleness_seconds: z5.number().int().min(0).
|
|
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
|
+
),
|
|
1293
1522
|
response_format: z5.enum(["markdown", "json"]).default("markdown")
|
|
1294
1523
|
}).refine(
|
|
1295
|
-
(v) =>
|
|
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),
|
|
1296
1539
|
{ message: "At least one search criterion must be provided." }
|
|
1297
1540
|
);
|
|
1298
1541
|
var searchEmailsTool = defineTool({
|
|
@@ -1313,6 +1556,8 @@ var searchEmailsTool = defineTool({
|
|
|
1313
1556
|
...args.to !== void 0 && { to: args.to },
|
|
1314
1557
|
...args.body !== void 0 && { body: args.body },
|
|
1315
1558
|
...args.unseen !== void 0 && { unseen: args.unseen },
|
|
1559
|
+
...args.flagged !== void 0 && { flagged: args.flagged },
|
|
1560
|
+
...args.answered !== void 0 && { answered: args.answered },
|
|
1316
1561
|
...args.since_date !== void 0 && { since: new Date(args.since_date) },
|
|
1317
1562
|
...args.before_date !== void 0 && { before: new Date(args.before_date) },
|
|
1318
1563
|
...args.larger_than_bytes !== void 0 && { larger_than_bytes: args.larger_than_bytes },
|
|
@@ -1325,20 +1570,39 @@ var searchEmailsTool = defineTool({
|
|
|
1325
1570
|
let matchingUids;
|
|
1326
1571
|
const imap = await ctx.imap.connection();
|
|
1327
1572
|
const lock = await imap.getMailboxLock(args.folder);
|
|
1573
|
+
let topUids;
|
|
1574
|
+
let cached;
|
|
1575
|
+
let missingUids;
|
|
1328
1576
|
try {
|
|
1329
1577
|
const result = await imap.search(criteria, { uid: true });
|
|
1330
1578
|
matchingUids = Array.isArray(result) ? result : [];
|
|
1579
|
+
topUids = matchingUids.toReversed().slice(0, args.limit);
|
|
1580
|
+
cached = getEmailsByUids(ctx.db, args.folder, topUids);
|
|
1581
|
+
missingUids = topUids.filter((uid) => !cached.has(uid));
|
|
1582
|
+
if (missingUids.length > 0) {
|
|
1583
|
+
const cachedAt = ctx.now();
|
|
1584
|
+
const fetched = [];
|
|
1585
|
+
for await (const msg of imap.fetch(
|
|
1586
|
+
missingUids,
|
|
1587
|
+
{ envelope: true, flags: true, internalDate: true, bodyStructure: true },
|
|
1588
|
+
{ uid: true }
|
|
1589
|
+
)) {
|
|
1590
|
+
const insert = messageToInsert(args.folder, msg, cachedAt);
|
|
1591
|
+
if (insert) fetched.push(insert);
|
|
1592
|
+
}
|
|
1593
|
+
upsertEmails(ctx.db, fetched);
|
|
1594
|
+
}
|
|
1331
1595
|
} catch (err) {
|
|
1332
1596
|
lock.release();
|
|
1333
1597
|
throw mapImapError(err);
|
|
1334
1598
|
}
|
|
1335
1599
|
lock.release();
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
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
|
+
}
|
|
1341
1604
|
}
|
|
1605
|
+
const rows = topUids.map((uid) => cached.get(uid)).filter((r) => r !== void 0);
|
|
1342
1606
|
const structured = {
|
|
1343
1607
|
folder: args.folder,
|
|
1344
1608
|
total_matches: matchingUids.length,
|
|
@@ -1350,6 +1614,8 @@ var searchEmailsTool = defineTool({
|
|
|
1350
1614
|
to: args.to ?? null,
|
|
1351
1615
|
body: args.body ?? null,
|
|
1352
1616
|
unseen: args.unseen ?? null,
|
|
1617
|
+
flagged: args.flagged ?? null,
|
|
1618
|
+
answered: args.answered ?? null,
|
|
1353
1619
|
since_date: args.since_date ?? null,
|
|
1354
1620
|
before_date: args.before_date ?? null
|
|
1355
1621
|
}
|
|
@@ -1364,30 +1630,47 @@ var searchEmailsTool = defineTool({
|
|
|
1364
1630
|
|
|
1365
1631
|
// src/tools/emails/mark-read.ts
|
|
1366
1632
|
import { z as z6 } from "zod";
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
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 ?? [];
|
|
1372
1638
|
const imap = await ctx.imap.connection();
|
|
1373
1639
|
const lock = await imap.getMailboxLock(folder);
|
|
1640
|
+
let ok = true;
|
|
1374
1641
|
try {
|
|
1375
|
-
if (
|
|
1376
|
-
await imap.messageFlagsAdd(
|
|
1377
|
-
}
|
|
1378
|
-
|
|
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;
|
|
1379
1647
|
}
|
|
1380
1648
|
} catch (err) {
|
|
1381
1649
|
throw mapImapError(err);
|
|
1382
1650
|
} finally {
|
|
1383
1651
|
lock.release();
|
|
1384
1652
|
}
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
const
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
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
|
+
);
|
|
1391
1674
|
}
|
|
1392
1675
|
var markReadTool = defineTool({
|
|
1393
1676
|
name: "imap_mark_read",
|
|
@@ -1444,25 +1727,12 @@ var Input6 = z7.object({
|
|
|
1444
1727
|
"UIDs of messages to flip. Max 500 per call - chunk your own list for larger batches."
|
|
1445
1728
|
)
|
|
1446
1729
|
});
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
try {
|
|
1451
|
-
if (want === "add") {
|
|
1452
|
-
await imap.messageFlagsAdd(uids, ["\\Seen"], { uid: true });
|
|
1453
|
-
} else {
|
|
1454
|
-
await imap.messageFlagsRemove(uids, ["\\Seen"], { uid: true });
|
|
1455
|
-
}
|
|
1456
|
-
} catch (err) {
|
|
1457
|
-
throw mapImapError(err);
|
|
1458
|
-
} finally {
|
|
1459
|
-
lock.release();
|
|
1460
|
-
}
|
|
1461
|
-
mutateEmailFlagsForUids(
|
|
1462
|
-
ctx.db,
|
|
1730
|
+
function updateSeenFlagBulk(ctx, folder, uids, want) {
|
|
1731
|
+
return applyFlags(
|
|
1732
|
+
ctx,
|
|
1463
1733
|
folder,
|
|
1464
1734
|
uids,
|
|
1465
|
-
|
|
1735
|
+
want === "add" ? { add: ["\\Seen"] } : { remove: ["\\Seen"] }
|
|
1466
1736
|
);
|
|
1467
1737
|
}
|
|
1468
1738
|
var markReadMultipleTool = defineTool({
|
|
@@ -1522,12 +1792,64 @@ var markUnreadMultipleTool = defineTool({
|
|
|
1522
1792
|
}
|
|
1523
1793
|
});
|
|
1524
1794
|
|
|
1525
|
-
// src/tools/emails/
|
|
1795
|
+
// src/tools/emails/set-flags.ts
|
|
1526
1796
|
import { z as z8 } from "zod";
|
|
1797
|
+
var Flag = z8.enum(["\\Flagged", "\\Answered"]);
|
|
1527
1798
|
var Input7 = z8.object({
|
|
1528
|
-
folder: z8.string().min(1).describe("
|
|
1529
|
-
|
|
1530
|
-
|
|
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(
|
|
1531
1853
|
"Target folder path. Use imap_list_folders to discover valid destinations. Must exist on the server."
|
|
1532
1854
|
)
|
|
1533
1855
|
});
|
|
@@ -1541,7 +1863,7 @@ var moveToFolderTool = defineTool({
|
|
|
1541
1863
|
idempotentHint: false,
|
|
1542
1864
|
openWorldHint: true
|
|
1543
1865
|
},
|
|
1544
|
-
inputSchema:
|
|
1866
|
+
inputSchema: Input8,
|
|
1545
1867
|
handler: async (args, ctx) => {
|
|
1546
1868
|
const imap = await ctx.imap.connection();
|
|
1547
1869
|
const lock = await imap.getMailboxLock(args.folder);
|
|
@@ -1579,11 +1901,11 @@ var moveToFolderTool = defineTool({
|
|
|
1579
1901
|
});
|
|
1580
1902
|
|
|
1581
1903
|
// src/tools/emails/move-multiple.ts
|
|
1582
|
-
import { z as
|
|
1583
|
-
var
|
|
1584
|
-
folder:
|
|
1585
|
-
uids:
|
|
1586
|
-
destination:
|
|
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.")
|
|
1587
1909
|
});
|
|
1588
1910
|
var moveMultipleTool = defineTool({
|
|
1589
1911
|
name: "imap_move_multiple",
|
|
@@ -1594,7 +1916,7 @@ var moveMultipleTool = defineTool({
|
|
|
1594
1916
|
idempotentHint: false,
|
|
1595
1917
|
openWorldHint: true
|
|
1596
1918
|
},
|
|
1597
|
-
inputSchema:
|
|
1919
|
+
inputSchema: Input9,
|
|
1598
1920
|
handler: async (args, ctx) => {
|
|
1599
1921
|
const imap = await ctx.imap.connection();
|
|
1600
1922
|
const lock = await imap.getMailboxLock(args.folder);
|
|
@@ -1631,11 +1953,11 @@ var moveMultipleTool = defineTool({
|
|
|
1631
1953
|
});
|
|
1632
1954
|
|
|
1633
1955
|
// src/tools/emails/delete-email.ts
|
|
1634
|
-
import { z as
|
|
1635
|
-
var
|
|
1636
|
-
folder:
|
|
1637
|
-
uid:
|
|
1638
|
-
hard_delete:
|
|
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(
|
|
1639
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."
|
|
1640
1962
|
)
|
|
1641
1963
|
});
|
|
@@ -1648,7 +1970,7 @@ var deleteEmailTool = defineTool({
|
|
|
1648
1970
|
idempotentHint: false,
|
|
1649
1971
|
openWorldHint: true
|
|
1650
1972
|
},
|
|
1651
|
-
inputSchema:
|
|
1973
|
+
inputSchema: Input10,
|
|
1652
1974
|
handler: async (args, ctx) => {
|
|
1653
1975
|
const imap = await ctx.imap.connection();
|
|
1654
1976
|
if (args.hard_delete) {
|
|
@@ -1716,11 +2038,11 @@ var deleteEmailTool = defineTool({
|
|
|
1716
2038
|
});
|
|
1717
2039
|
|
|
1718
2040
|
// src/tools/emails/delete-multiple.ts
|
|
1719
|
-
import { z as
|
|
1720
|
-
var
|
|
1721
|
-
folder:
|
|
1722
|
-
uids:
|
|
1723
|
-
hard_delete:
|
|
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(
|
|
1724
2046
|
"When false (default), messages move to the server Trash and can be recovered. When true, they are permanently expunged."
|
|
1725
2047
|
)
|
|
1726
2048
|
});
|
|
@@ -1733,7 +2055,7 @@ var deleteMultipleTool = defineTool({
|
|
|
1733
2055
|
idempotentHint: false,
|
|
1734
2056
|
openWorldHint: true
|
|
1735
2057
|
},
|
|
1736
|
-
inputSchema:
|
|
2058
|
+
inputSchema: Input11,
|
|
1737
2059
|
handler: async (args, ctx) => {
|
|
1738
2060
|
const imap = await ctx.imap.connection();
|
|
1739
2061
|
if (args.hard_delete) {
|
|
@@ -1803,15 +2125,17 @@ var deleteMultipleTool = defineTool({
|
|
|
1803
2125
|
});
|
|
1804
2126
|
|
|
1805
2127
|
// src/tools/drafts/list-drafts.ts
|
|
1806
|
-
import { z as
|
|
1807
|
-
var
|
|
1808
|
-
folder:
|
|
2128
|
+
import { z as z13 } from "zod";
|
|
2129
|
+
var Input12 = z13.object({
|
|
2130
|
+
folder: z13.string().min(1).optional().describe(
|
|
1809
2131
|
"Optional explicit Drafts folder path. If omitted, mcp-inbox auto-detects via RFC 6154 SPECIAL-USE."
|
|
1810
2132
|
),
|
|
1811
|
-
limit:
|
|
1812
|
-
offset:
|
|
1813
|
-
max_staleness_seconds:
|
|
1814
|
-
|
|
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")
|
|
1815
2139
|
});
|
|
1816
2140
|
var listDraftsTool = defineTool({
|
|
1817
2141
|
name: "imap_list_drafts",
|
|
@@ -1822,7 +2146,7 @@ var listDraftsTool = defineTool({
|
|
|
1822
2146
|
idempotentHint: true,
|
|
1823
2147
|
openWorldHint: true
|
|
1824
2148
|
},
|
|
1825
|
-
inputSchema:
|
|
2149
|
+
inputSchema: Input12,
|
|
1826
2150
|
handler: async (args, ctx) => {
|
|
1827
2151
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
1828
2152
|
const didSync = await syncIfStale(ctx, folder, args.max_staleness_seconds);
|
|
@@ -1849,12 +2173,14 @@ ${formatEmailListMarkdown(rows)}`;
|
|
|
1849
2173
|
});
|
|
1850
2174
|
|
|
1851
2175
|
// src/tools/drafts/get-draft.ts
|
|
1852
|
-
import { z as
|
|
1853
|
-
var
|
|
1854
|
-
uid:
|
|
1855
|
-
folder:
|
|
1856
|
-
max_staleness_seconds:
|
|
1857
|
-
|
|
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")
|
|
1858
2184
|
});
|
|
1859
2185
|
var getDraftTool = defineTool({
|
|
1860
2186
|
name: "imap_get_draft",
|
|
@@ -1865,7 +2191,7 @@ var getDraftTool = defineTool({
|
|
|
1865
2191
|
idempotentHint: true,
|
|
1866
2192
|
openWorldHint: true
|
|
1867
2193
|
},
|
|
1868
|
-
inputSchema:
|
|
2194
|
+
inputSchema: Input13,
|
|
1869
2195
|
handler: async (args, ctx) => {
|
|
1870
2196
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
1871
2197
|
const envelope = await ensureEnvelopeCached(ctx, folder, args.uid, args.max_staleness_seconds);
|
|
@@ -1900,7 +2226,7 @@ function formatDraftMarkdown(d) {
|
|
|
1900
2226
|
}
|
|
1901
2227
|
|
|
1902
2228
|
// src/tools/drafts/create-draft.ts
|
|
1903
|
-
import { z as
|
|
2229
|
+
import { z as z16 } from "zod";
|
|
1904
2230
|
|
|
1905
2231
|
// src/imap/mime-builder.ts
|
|
1906
2232
|
import MailComposer from "nodemailer/lib/mail-composer/index.js";
|
|
@@ -1915,26 +2241,47 @@ async function buildRawMessage(input) {
|
|
|
1915
2241
|
...input.html !== void 0 && { html: input.html },
|
|
1916
2242
|
...input.inReplyTo !== void 0 && { inReplyTo: input.inReplyTo },
|
|
1917
2243
|
...input.references !== void 0 && { references: input.references },
|
|
1918
|
-
...input.headers !== void 0 && { headers: input.headers }
|
|
2244
|
+
...input.headers !== void 0 && { headers: input.headers },
|
|
2245
|
+
...input.attachments !== void 0 && { attachments: input.attachments }
|
|
1919
2246
|
};
|
|
1920
2247
|
const composer = new MailComposer(options);
|
|
1921
2248
|
const message = composer.compile();
|
|
1922
2249
|
return await message.build();
|
|
1923
2250
|
}
|
|
1924
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
|
+
|
|
1925
2272
|
// src/tools/drafts/create-draft.ts
|
|
1926
|
-
var
|
|
1927
|
-
var Input13 = z14.object({
|
|
2273
|
+
var Input14 = z16.object({
|
|
1928
2274
|
to: AddressList.describe("Recipient email address or array of addresses."),
|
|
1929
|
-
subject:
|
|
1930
|
-
body:
|
|
1931
|
-
html:
|
|
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)."),
|
|
1932
2278
|
cc: AddressList.optional(),
|
|
1933
2279
|
bcc: AddressList.optional(),
|
|
1934
|
-
from:
|
|
2280
|
+
from: z16.string().min(1).optional().describe(
|
|
1935
2281
|
"Sender address. Defaults to IMAP_USER. Some providers reject mismatched From headers."
|
|
1936
2282
|
),
|
|
1937
|
-
folder:
|
|
2283
|
+
folder: z16.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted."),
|
|
2284
|
+
attachments: AttachmentList
|
|
1938
2285
|
});
|
|
1939
2286
|
var createDraftTool = defineTool({
|
|
1940
2287
|
name: "imap_create_draft",
|
|
@@ -1945,9 +2292,10 @@ var createDraftTool = defineTool({
|
|
|
1945
2292
|
idempotentHint: false,
|
|
1946
2293
|
openWorldHint: true
|
|
1947
2294
|
},
|
|
1948
|
-
inputSchema:
|
|
2295
|
+
inputSchema: Input14,
|
|
1949
2296
|
handler: async (args, ctx) => {
|
|
1950
2297
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
2298
|
+
const attachments = toMessageAttachments(args.attachments);
|
|
1951
2299
|
const raw = await buildRawMessage({
|
|
1952
2300
|
from: args.from ?? ctx.defaults.fromAddress,
|
|
1953
2301
|
to: args.to,
|
|
@@ -1955,7 +2303,8 @@ var createDraftTool = defineTool({
|
|
|
1955
2303
|
...args.cc !== void 0 && { cc: args.cc },
|
|
1956
2304
|
...args.bcc !== void 0 && { bcc: args.bcc },
|
|
1957
2305
|
...args.body !== void 0 && { text: args.body },
|
|
1958
|
-
...args.html !== void 0 && { html: args.html }
|
|
2306
|
+
...args.html !== void 0 && { html: args.html },
|
|
2307
|
+
...attachments !== void 0 && { attachments }
|
|
1959
2308
|
});
|
|
1960
2309
|
const imap = await ctx.imap.connection();
|
|
1961
2310
|
let uid;
|
|
@@ -1985,18 +2334,18 @@ var createDraftTool = defineTool({
|
|
|
1985
2334
|
});
|
|
1986
2335
|
|
|
1987
2336
|
// src/tools/drafts/update-draft.ts
|
|
1988
|
-
import { z as
|
|
1989
|
-
var
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
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
|
|
2000
2349
|
});
|
|
2001
2350
|
var updateDraftTool = defineTool({
|
|
2002
2351
|
name: "imap_update_draft",
|
|
@@ -2008,9 +2357,10 @@ var updateDraftTool = defineTool({
|
|
|
2008
2357
|
idempotentHint: false,
|
|
2009
2358
|
openWorldHint: true
|
|
2010
2359
|
},
|
|
2011
|
-
inputSchema:
|
|
2360
|
+
inputSchema: Input15,
|
|
2012
2361
|
handler: async (args, ctx) => {
|
|
2013
2362
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
2363
|
+
const attachments = toMessageAttachments(args.attachments);
|
|
2014
2364
|
const raw = await buildRawMessage({
|
|
2015
2365
|
from: args.from ?? ctx.defaults.fromAddress,
|
|
2016
2366
|
to: args.to,
|
|
@@ -2018,7 +2368,8 @@ var updateDraftTool = defineTool({
|
|
|
2018
2368
|
...args.cc !== void 0 && { cc: args.cc },
|
|
2019
2369
|
...args.bcc !== void 0 && { bcc: args.bcc },
|
|
2020
2370
|
...args.body !== void 0 && { text: args.body },
|
|
2021
|
-
...args.html !== void 0 && { html: args.html }
|
|
2371
|
+
...args.html !== void 0 && { html: args.html },
|
|
2372
|
+
...attachments !== void 0 && { attachments }
|
|
2022
2373
|
});
|
|
2023
2374
|
const imap = await ctx.imap.connection();
|
|
2024
2375
|
let newUid;
|
|
@@ -2080,7 +2431,7 @@ var updateDraftTool = defineTool({
|
|
|
2080
2431
|
});
|
|
2081
2432
|
|
|
2082
2433
|
// src/tools/send/send-email.ts
|
|
2083
|
-
import { z as
|
|
2434
|
+
import { z as z18 } from "zod";
|
|
2084
2435
|
|
|
2085
2436
|
// src/tools/send/shared.ts
|
|
2086
2437
|
function normalizeAddrs(value) {
|
|
@@ -2122,28 +2473,28 @@ function flattenCompose(args) {
|
|
|
2122
2473
|
}
|
|
2123
2474
|
|
|
2124
2475
|
// src/tools/send/send-email.ts
|
|
2125
|
-
var
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
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(
|
|
2134
2484
|
"Sender address. Defaults to IMAP_USER. Providers like Gmail and Fastmail reject mismatched From unless the address is a verified alias."
|
|
2135
|
-
)
|
|
2485
|
+
),
|
|
2486
|
+
attachments: AttachmentList
|
|
2136
2487
|
});
|
|
2137
2488
|
var sendEmailTool = defineTool({
|
|
2138
2489
|
name: "imap_send_email",
|
|
2139
|
-
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,
|
|
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.",
|
|
2140
2491
|
annotations: {
|
|
2141
2492
|
readOnlyHint: false,
|
|
2142
2493
|
destructiveHint: true,
|
|
2143
2494
|
idempotentHint: false,
|
|
2144
2495
|
openWorldHint: true
|
|
2145
2496
|
},
|
|
2146
|
-
inputSchema:
|
|
2497
|
+
inputSchema: Input16,
|
|
2147
2498
|
handler: async (args, ctx) => {
|
|
2148
2499
|
const compose = flattenCompose({
|
|
2149
2500
|
...args.from !== void 0 && { from: args.from },
|
|
@@ -2152,6 +2503,7 @@ var sendEmailTool = defineTool({
|
|
|
2152
2503
|
...args.bcc !== void 0 && { bcc: args.bcc }
|
|
2153
2504
|
});
|
|
2154
2505
|
const fromAddress = compose.fromOrDefault(ctx.defaults.fromAddress);
|
|
2506
|
+
const attachments = toMessageAttachments(args.attachments);
|
|
2155
2507
|
const raw = await buildRawMessage({
|
|
2156
2508
|
from: fromAddress,
|
|
2157
2509
|
to: args.to,
|
|
@@ -2159,7 +2511,8 @@ var sendEmailTool = defineTool({
|
|
|
2159
2511
|
...args.cc !== void 0 && { cc: args.cc },
|
|
2160
2512
|
...args.bcc !== void 0 && { bcc: args.bcc },
|
|
2161
2513
|
...args.body !== void 0 && { text: args.body },
|
|
2162
|
-
...args.html !== void 0 && { html: args.html }
|
|
2514
|
+
...args.html !== void 0 && { html: args.html },
|
|
2515
|
+
...attachments !== void 0 && { attachments }
|
|
2163
2516
|
});
|
|
2164
2517
|
const envelope = {
|
|
2165
2518
|
from: fromAddress,
|
|
@@ -2190,11 +2543,11 @@ var sendEmailTool = defineTool({
|
|
|
2190
2543
|
});
|
|
2191
2544
|
|
|
2192
2545
|
// src/tools/send/send-draft.ts
|
|
2193
|
-
import { z as
|
|
2546
|
+
import { z as z19 } from "zod";
|
|
2194
2547
|
import { simpleParser as simpleParser2 } from "mailparser";
|
|
2195
|
-
var
|
|
2196
|
-
uid:
|
|
2197
|
-
folder:
|
|
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.")
|
|
2198
2551
|
});
|
|
2199
2552
|
var sendDraftTool = defineTool({
|
|
2200
2553
|
name: "imap_send_draft",
|
|
@@ -2205,7 +2558,7 @@ var sendDraftTool = defineTool({
|
|
|
2205
2558
|
idempotentHint: false,
|
|
2206
2559
|
openWorldHint: true
|
|
2207
2560
|
},
|
|
2208
|
-
inputSchema:
|
|
2561
|
+
inputSchema: Input17,
|
|
2209
2562
|
handler: async (args, ctx) => {
|
|
2210
2563
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
2211
2564
|
const imap = await ctx.imap.connection();
|
|
@@ -2283,8 +2636,7 @@ var sendDraftTool = defineTool({
|
|
|
2283
2636
|
});
|
|
2284
2637
|
function firstAddress(field) {
|
|
2285
2638
|
if (!field) return null;
|
|
2286
|
-
const
|
|
2287
|
-
const single = Array.isArray(obj) ? obj[0] : obj;
|
|
2639
|
+
const single = Array.isArray(field) ? field[0] : field;
|
|
2288
2640
|
if (!single) return null;
|
|
2289
2641
|
if (typeof single.address === "string") return single.address;
|
|
2290
2642
|
const fromValue = single.value?.[0]?.address;
|
|
@@ -2292,8 +2644,7 @@ function firstAddress(field) {
|
|
|
2292
2644
|
}
|
|
2293
2645
|
function addressList(field) {
|
|
2294
2646
|
if (!field) return [];
|
|
2295
|
-
const
|
|
2296
|
-
const arr = Array.isArray(obj) ? obj : [obj];
|
|
2647
|
+
const arr = Array.isArray(field) ? field : [field];
|
|
2297
2648
|
const out = [];
|
|
2298
2649
|
for (const entry of arr) {
|
|
2299
2650
|
if (typeof entry.address === "string") {
|
|
@@ -2307,20 +2658,25 @@ function addressList(field) {
|
|
|
2307
2658
|
}
|
|
2308
2659
|
|
|
2309
2660
|
// src/tools/send/reply.ts
|
|
2310
|
-
import { z as
|
|
2311
|
-
var
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
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(
|
|
2320
2670
|
"When true, CC the original To + Cc recipients (minus the sender). When false, reply only to the original From."
|
|
2321
2671
|
),
|
|
2322
|
-
from:
|
|
2323
|
-
max_staleness_seconds:
|
|
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
|
+
)
|
|
2324
2680
|
});
|
|
2325
2681
|
var replyTool = defineTool({
|
|
2326
2682
|
name: "imap_reply",
|
|
@@ -2331,7 +2687,7 @@ var replyTool = defineTool({
|
|
|
2331
2687
|
idempotentHint: false,
|
|
2332
2688
|
openWorldHint: true
|
|
2333
2689
|
},
|
|
2334
|
-
inputSchema:
|
|
2690
|
+
inputSchema: Input18,
|
|
2335
2691
|
handler: async (args, ctx) => {
|
|
2336
2692
|
const original = await ensureEnvelopeCached(
|
|
2337
2693
|
ctx,
|
|
@@ -2347,7 +2703,11 @@ var replyTool = defineTool({
|
|
|
2347
2703
|
const bcc = args.bcc !== void 0 ? flattenCompose({ to: "_", bcc: args.bcc }).bcc : [];
|
|
2348
2704
|
const from = args.from ?? ctx.defaults.fromAddress;
|
|
2349
2705
|
const subject = prefixSubject(original.subject ?? "", "Re: ");
|
|
2350
|
-
const references =
|
|
2706
|
+
const references = mergeReferences(
|
|
2707
|
+
await fetchReferencesHeader(ctx, args.folder, args.uid),
|
|
2708
|
+
parsedEnvelope.messageId
|
|
2709
|
+
);
|
|
2710
|
+
const attachments = toMessageAttachments(args.attachments);
|
|
2351
2711
|
const raw = await buildRawMessage({
|
|
2352
2712
|
from,
|
|
2353
2713
|
to,
|
|
@@ -2359,7 +2719,8 @@ var replyTool = defineTool({
|
|
|
2359
2719
|
...parsedEnvelope.messageId !== void 0 && {
|
|
2360
2720
|
inReplyTo: parsedEnvelope.messageId
|
|
2361
2721
|
},
|
|
2362
|
-
...references.length > 0 && { references }
|
|
2722
|
+
...references.length > 0 && { references },
|
|
2723
|
+
...attachments !== void 0 && { attachments }
|
|
2363
2724
|
});
|
|
2364
2725
|
const envelope = {
|
|
2365
2726
|
from,
|
|
@@ -2368,11 +2729,26 @@ var replyTool = defineTool({
|
|
|
2368
2729
|
...bcc.length > 0 && { bcc }
|
|
2369
2730
|
};
|
|
2370
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(", ")}` : ""}.`;
|
|
2371
2747
|
return {
|
|
2372
2748
|
content: [
|
|
2373
2749
|
{
|
|
2374
2750
|
type: "text",
|
|
2375
|
-
text:
|
|
2751
|
+
text: markAnsweredError !== null ? `${summary} Warning: could not mark the original as answered: ${markAnsweredError}` : summary
|
|
2376
2752
|
}
|
|
2377
2753
|
],
|
|
2378
2754
|
structuredContent: {
|
|
@@ -2385,7 +2761,9 @@ var replyTool = defineTool({
|
|
|
2385
2761
|
references,
|
|
2386
2762
|
message_id: result.messageId,
|
|
2387
2763
|
sent_folder: result.sentFolder,
|
|
2388
|
-
sent_save_error: result.sentSaveError
|
|
2764
|
+
sent_save_error: result.sentSaveError,
|
|
2765
|
+
original_marked_answered: originalMarkedAnswered,
|
|
2766
|
+
mark_answered_error: markAnsweredError
|
|
2389
2767
|
}
|
|
2390
2768
|
};
|
|
2391
2769
|
}
|
|
@@ -2405,10 +2783,29 @@ function prefixSubject(subject, prefix) {
|
|
|
2405
2783
|
const trimmed = subject.trim();
|
|
2406
2784
|
return trimmed.toLowerCase().startsWith(prefix.toLowerCase().trim()) ? trimmed : `${prefix}${trimmed}`;
|
|
2407
2785
|
}
|
|
2408
|
-
function
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
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))];
|
|
2412
2809
|
}
|
|
2413
2810
|
function dedupeAddrs(addrs, exclude) {
|
|
2414
2811
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -2423,30 +2820,34 @@ function dedupeAddrs(addrs, exclude) {
|
|
|
2423
2820
|
}
|
|
2424
2821
|
|
|
2425
2822
|
// src/tools/send/forward.ts
|
|
2426
|
-
import { z as
|
|
2427
|
-
var
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
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(
|
|
2433
2829
|
'Optional prefix body (e.g. "FYI, thought you should see this."). Quoted original follows.'
|
|
2434
2830
|
),
|
|
2435
|
-
cc:
|
|
2436
|
-
bcc:
|
|
2437
|
-
from:
|
|
2438
|
-
max_staleness_seconds:
|
|
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
|
+
)
|
|
2439
2840
|
});
|
|
2440
2841
|
var forwardTool = defineTool({
|
|
2441
2842
|
name: "imap_forward",
|
|
2442
|
-
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.',
|
|
2443
2844
|
annotations: {
|
|
2444
2845
|
readOnlyHint: false,
|
|
2445
2846
|
destructiveHint: true,
|
|
2446
2847
|
idempotentHint: false,
|
|
2447
2848
|
openWorldHint: true
|
|
2448
2849
|
},
|
|
2449
|
-
inputSchema:
|
|
2850
|
+
inputSchema: Input19,
|
|
2450
2851
|
handler: async (args, ctx) => {
|
|
2451
2852
|
const original = await ensureEnvelopeCached(
|
|
2452
2853
|
ctx,
|
|
@@ -2454,7 +2855,7 @@ var forwardTool = defineTool({
|
|
|
2454
2855
|
args.uid,
|
|
2455
2856
|
args.max_staleness_seconds
|
|
2456
2857
|
);
|
|
2457
|
-
const body = await
|
|
2858
|
+
const { body, source } = await ensureBodyAndSource(ctx, args.folder, args.uid);
|
|
2458
2859
|
const compose = flattenCompose({
|
|
2459
2860
|
...args.from !== void 0 && { from: args.from },
|
|
2460
2861
|
to: args.to,
|
|
@@ -2484,7 +2885,16 @@ Subject: ${original.subject ?? ""}
|
|
|
2484
2885
|
text: forwardedText,
|
|
2485
2886
|
...body.bodyHtml !== null && {
|
|
2486
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
|
|
2487
|
-
}
|
|
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
|
+
]
|
|
2488
2898
|
});
|
|
2489
2899
|
const envelope = {
|
|
2490
2900
|
from,
|
|
@@ -2508,6 +2918,7 @@ Subject: ${original.subject ?? ""}
|
|
|
2508
2918
|
subject,
|
|
2509
2919
|
forwarded_from_folder: args.folder,
|
|
2510
2920
|
forwarded_uid: args.uid,
|
|
2921
|
+
original_attached: true,
|
|
2511
2922
|
message_id: result.messageId,
|
|
2512
2923
|
sent_folder: result.sentFolder,
|
|
2513
2924
|
sent_save_error: result.sentSaveError
|
|
@@ -2519,21 +2930,25 @@ function prefixSubject2(subject, prefix) {
|
|
|
2519
2930
|
const trimmed = subject.trim();
|
|
2520
2931
|
return trimmed.toLowerCase().startsWith(prefix.toLowerCase().trim()) ? trimmed : `${prefix}${trimmed}`;
|
|
2521
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
|
+
}
|
|
2522
2937
|
function escapeHtml(s) {
|
|
2523
2938
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2524
2939
|
}
|
|
2525
2940
|
|
|
2526
2941
|
// src/tools/attachments/get-attachment.ts
|
|
2527
|
-
import { z as
|
|
2942
|
+
import { z as z22 } from "zod";
|
|
2528
2943
|
import { simpleParser as simpleParser3 } from "mailparser";
|
|
2529
|
-
var
|
|
2530
|
-
folder:
|
|
2531
|
-
uid:
|
|
2532
|
-
filename:
|
|
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(
|
|
2533
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."
|
|
2534
2949
|
),
|
|
2535
|
-
part_id:
|
|
2536
|
-
max_inline_mb:
|
|
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(
|
|
2537
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."
|
|
2538
2953
|
)
|
|
2539
2954
|
}).refine((v) => v.filename !== void 0 || v.part_id !== void 0, {
|
|
@@ -2548,7 +2963,7 @@ var getAttachmentTool = defineTool({
|
|
|
2548
2963
|
idempotentHint: true,
|
|
2549
2964
|
openWorldHint: true
|
|
2550
2965
|
},
|
|
2551
|
-
inputSchema:
|
|
2966
|
+
inputSchema: Input20,
|
|
2552
2967
|
handler: async (args, ctx) => {
|
|
2553
2968
|
const imap = await ctx.imap.connection();
|
|
2554
2969
|
const lock = await imap.getMailboxLock(args.folder);
|
|
@@ -2629,36 +3044,19 @@ var getAttachmentTool = defineTool({
|
|
|
2629
3044
|
}
|
|
2630
3045
|
});
|
|
2631
3046
|
function findAttachmentPart(structure, selector) {
|
|
2632
|
-
const
|
|
2633
|
-
while (
|
|
2634
|
-
const node =
|
|
3047
|
+
const queue = [structure];
|
|
3048
|
+
while (queue.length > 0) {
|
|
3049
|
+
const node = queue.shift();
|
|
2635
3050
|
if (!node) continue;
|
|
2636
|
-
if (node.childNodes) {
|
|
2637
|
-
for (const child of node.childNodes) stack.push(child);
|
|
2638
|
-
continue;
|
|
2639
|
-
}
|
|
2640
3051
|
const partId = node.part;
|
|
2641
|
-
if (!partId) continue;
|
|
2642
3052
|
const nodeFilename = node.dispositionParameters?.filename ?? node.parameters?.name;
|
|
2643
|
-
if (
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
filename: nodeFilename,
|
|
2648
|
-
contentType: node.type,
|
|
2649
|
-
size: node.size
|
|
2650
|
-
};
|
|
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 };
|
|
2651
3057
|
}
|
|
2652
|
-
continue;
|
|
2653
|
-
}
|
|
2654
|
-
if (selector.filename !== void 0 && nodeFilename === selector.filename) {
|
|
2655
|
-
return {
|
|
2656
|
-
partId,
|
|
2657
|
-
filename: nodeFilename,
|
|
2658
|
-
contentType: node.type,
|
|
2659
|
-
size: node.size
|
|
2660
|
-
};
|
|
2661
3058
|
}
|
|
3059
|
+
if (node.childNodes) queue.push(...node.childNodes);
|
|
2662
3060
|
}
|
|
2663
3061
|
return null;
|
|
2664
3062
|
}
|
|
@@ -2686,6 +3084,7 @@ var tools = [
|
|
|
2686
3084
|
// Write (flag + move + delete)
|
|
2687
3085
|
markReadTool,
|
|
2688
3086
|
markUnreadTool,
|
|
3087
|
+
setFlagsTool,
|
|
2689
3088
|
moveToFolderTool,
|
|
2690
3089
|
deleteEmailTool,
|
|
2691
3090
|
// Bulk variants of the same (one IMAP round-trip for N UIDs)
|
|
@@ -2716,7 +3115,7 @@ function listToolEntries() {
|
|
|
2716
3115
|
// this setting, such types become `{}` (matches anything) in the
|
|
2717
3116
|
// exposed inputSchema, and the real validation still happens on
|
|
2718
3117
|
// the Zod side inside the CallTool dispatcher.
|
|
2719
|
-
inputSchema:
|
|
3118
|
+
inputSchema: z23.toJSONSchema(t.inputSchema, {
|
|
2720
3119
|
target: "draft-7",
|
|
2721
3120
|
unrepresentable: "any"
|
|
2722
3121
|
}),
|
|
@@ -2725,12 +3124,12 @@ function listToolEntries() {
|
|
|
2725
3124
|
}
|
|
2726
3125
|
|
|
2727
3126
|
// src/server.ts
|
|
2728
|
-
var
|
|
3127
|
+
var log7 = createLogger("mcp-inbox:server");
|
|
2729
3128
|
function createMcpServer(ctx) {
|
|
2730
3129
|
const server = new Server(
|
|
2731
3130
|
{
|
|
2732
3131
|
name: "mcp-inbox",
|
|
2733
|
-
version:
|
|
3132
|
+
version: package_default.version
|
|
2734
3133
|
},
|
|
2735
3134
|
{
|
|
2736
3135
|
capabilities: {
|
|
@@ -2745,27 +3144,27 @@ function createMcpServer(ctx) {
|
|
|
2745
3144
|
const toolName = request.params.name;
|
|
2746
3145
|
const tool = findTool(toolName);
|
|
2747
3146
|
if (!tool) {
|
|
2748
|
-
|
|
3147
|
+
log7.warn("unknown tool", { tool: toolName });
|
|
2749
3148
|
return errorResult(`Unknown tool: ${toolName}`);
|
|
2750
3149
|
}
|
|
2751
3150
|
const parsed = tool.inputSchema.safeParse(request.params.arguments ?? {});
|
|
2752
3151
|
if (!parsed.success) {
|
|
2753
3152
|
const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
|
|
2754
|
-
|
|
3153
|
+
log7.warn("invalid tool args", { tool: toolName, issues });
|
|
2755
3154
|
return errorResult(`Invalid arguments for ${toolName}: ${issues}`);
|
|
2756
3155
|
}
|
|
2757
3156
|
try {
|
|
2758
3157
|
return await tool.handler(parsed.data, ctx);
|
|
2759
3158
|
} catch (err) {
|
|
2760
3159
|
if (isMcpInboxError(err)) {
|
|
2761
|
-
|
|
3160
|
+
log7.warn("tool returned mcp-inbox error", {
|
|
2762
3161
|
tool: toolName,
|
|
2763
3162
|
code: err.code,
|
|
2764
3163
|
msg: err.userMessage
|
|
2765
3164
|
});
|
|
2766
3165
|
return errorResult(err.userMessage);
|
|
2767
3166
|
}
|
|
2768
|
-
|
|
3167
|
+
log7.error("tool handler threw", {
|
|
2769
3168
|
tool: toolName,
|
|
2770
3169
|
msg: err instanceof Error ? err.message : String(err)
|
|
2771
3170
|
});
|
|
@@ -2774,7 +3173,7 @@ function createMcpServer(ctx) {
|
|
|
2774
3173
|
});
|
|
2775
3174
|
server.onerror = (err) => {
|
|
2776
3175
|
const meta = isMcpInboxError(err) ? { code: err.code, msg: err.userMessage } : { msg: err instanceof Error ? err.message : String(err) };
|
|
2777
|
-
|
|
3176
|
+
log7.error("mcp server error", meta);
|
|
2778
3177
|
};
|
|
2779
3178
|
return server;
|
|
2780
3179
|
}
|
|
@@ -2801,12 +3200,22 @@ try {
|
|
|
2801
3200
|
configureLogger({ debug: config.debug, level: "info" });
|
|
2802
3201
|
rootLogger.info("booting mcp-inbox", {
|
|
2803
3202
|
imapHost: config.imap.host,
|
|
2804
|
-
cacheEnabled: config.cache.enabled,
|
|
2805
3203
|
cacheDir: config.cache.dir,
|
|
3204
|
+
cacheStalenessSec: config.cache.defaultStalenessSec,
|
|
2806
3205
|
idleEnabled: config.idle.enabled,
|
|
2807
3206
|
idleFolders: config.idle.folders
|
|
2808
3207
|
});
|
|
2809
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
|
+
}
|
|
2810
3219
|
const imapClient = new ImapClient(config.imap);
|
|
2811
3220
|
const smtpClient = new SmtpClient(config.smtp);
|
|
2812
3221
|
const ctx = {
|
|
@@ -2885,4 +3294,3 @@ try {
|
|
|
2885
3294
|
}
|
|
2886
3295
|
process.exit(1);
|
|
2887
3296
|
}
|
|
2888
|
-
//# sourceMappingURL=app.js.map
|