@kbzowski/mcp-inbox 0.2.0 → 0.3.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/index.js CHANGED
@@ -1,2891 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __mcpCreateRequire } from 'node:module';
3
3
  globalThis.require = globalThis.require ?? __mcpCreateRequire(import.meta.url);
4
- var __defProp = Object.defineProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
4
 
10
- // src/index.ts
11
- import { join as join2 } from "node:path";
12
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
-
14
- // src/config/env.ts
15
- import { z } from "zod";
16
- import { homedir, platform } from "node:os";
17
- import { join } from "node:path";
18
- var BooleanString = z.enum(["true", "false"]).transform((v) => v === "true");
19
- var CsvList = z.string().transform(
20
- (s) => s.split(",").map((v) => v.trim()).filter((v) => v.length > 0)
21
- );
22
- var EnvSchema = z.object({
23
- // Required IMAP
24
- IMAP_USER: z.string().min(1, "IMAP_USER is required"),
25
- IMAP_PASSWORD: z.string().min(1, "IMAP_PASSWORD is required"),
26
- IMAP_HOST: z.string().min(1, "IMAP_HOST is required"),
27
- // Optional IMAP
28
- IMAP_PORT: z.coerce.number().int().min(1).max(65535).default(993),
29
- IMAP_TLS: BooleanString.default(true),
30
- IMAP_TLS_REJECT_UNAUTHORIZED: BooleanString.default(true),
31
- IMAP_AUTH_TIMEOUT_MS: z.coerce.number().int().positive().default(1e4),
32
- // SMTP (optional; defaulted in transform below)
33
- // `.min(1)` prevents empty-string envs (e.g. `SMTP_HOST=`) from slipping
34
- // through and defeating the `??` fallback in the transform.
35
- SMTP_HOST: z.string().min(1).optional(),
36
- SMTP_PORT: z.coerce.number().int().min(1).max(65535).default(465),
37
- SMTP_SECURE: BooleanString.default(true),
38
- SMTP_USER: z.string().min(1).optional(),
39
- SMTP_PASSWORD: z.string().min(1).optional(),
40
- // Cache
41
- IMAP_CACHE_ENABLED: BooleanString.default(true),
42
- IMAP_CACHE_DIR: z.string().min(1).optional(),
43
- IMAP_CACHE_BODY_INLINE: BooleanString.default(false),
44
- IMAP_CACHE_DEFAULT_STALENESS_SEC: z.coerce.number().int().min(0).default(60),
45
- IMAP_CACHE_RETAIN_DAYS: z.coerce.number().int().min(0).default(365),
46
- // IDLE
47
- IMAP_IDLE_ENABLED: BooleanString.default(true),
48
- IMAP_IDLE_FOLDERS: CsvList.default(["INBOX"]),
49
- // Debug
50
- DEBUG: z.string().optional()
51
- }).transform((raw) => ({
52
- imap: {
53
- user: raw.IMAP_USER,
54
- password: raw.IMAP_PASSWORD,
55
- host: raw.IMAP_HOST,
56
- port: raw.IMAP_PORT,
57
- tls: raw.IMAP_TLS,
58
- tlsRejectUnauthorized: raw.IMAP_TLS_REJECT_UNAUTHORIZED,
59
- authTimeoutMs: raw.IMAP_AUTH_TIMEOUT_MS
60
- },
61
- smtp: {
62
- host: raw.SMTP_HOST ?? raw.IMAP_HOST,
63
- port: raw.SMTP_PORT,
64
- secure: raw.SMTP_SECURE,
65
- user: raw.SMTP_USER ?? raw.IMAP_USER,
66
- password: raw.SMTP_PASSWORD ?? raw.IMAP_PASSWORD
67
- },
68
- cache: {
69
- enabled: raw.IMAP_CACHE_ENABLED,
70
- dir: raw.IMAP_CACHE_DIR ?? defaultCacheDir(),
71
- eagerBodyCache: raw.IMAP_CACHE_BODY_INLINE,
72
- defaultStalenessSec: raw.IMAP_CACHE_DEFAULT_STALENESS_SEC,
73
- retainDays: raw.IMAP_CACHE_RETAIN_DAYS
74
- },
75
- idle: {
76
- enabled: raw.IMAP_IDLE_ENABLED,
77
- folders: raw.IMAP_IDLE_FOLDERS
78
- },
79
- debug: raw.DEBUG ?? ""
80
- }));
81
- function defaultCacheDir() {
82
- if (platform() === "win32") {
83
- const local = process.env.LOCALAPPDATA;
84
- const base2 = local && local.length > 0 ? local : join(homedir(), "AppData", "Local");
85
- return join(base2, "mcp-inbox", "Cache");
86
- }
87
- const xdg = process.env.XDG_CACHE_HOME;
88
- const base = xdg && xdg.length > 0 ? xdg : join(homedir(), ".cache");
89
- return join(base, "mcp-inbox");
90
- }
91
- function loadConfig(env = process.env) {
92
- const scrubbed = {};
93
- for (const [key, value] of Object.entries(env)) {
94
- scrubbed[key] = value === "" ? void 0 : value;
95
- }
96
- const parsed = EnvSchema.safeParse(scrubbed);
97
- if (!parsed.success) {
98
- const issues = parsed.error.issues.map((i) => ` - ${i.path.join(".") || "(root)"}: ${i.message}`).join("\n");
99
- throw new Error(`Invalid configuration:
100
- ${issues}`);
101
- }
102
- return parsed.data;
103
- }
104
-
105
- // src/cache/db.ts
106
- import Database from "better-sqlite3";
107
- import { mkdirSync } from "node:fs";
108
- import { dirname } from "node:path";
109
- import { fileURLToPath } from "node:url";
110
- import { drizzle } from "drizzle-orm/better-sqlite3";
111
- import { migrate } from "drizzle-orm/better-sqlite3/migrator";
112
-
113
- // src/cache/schema.ts
114
- var schema_exports = {};
115
- __export(schema_exports, {
116
- emails: () => emails,
117
- folders: () => folders
118
- });
119
- import { sqliteTable, text, integer, primaryKey, index } from "drizzle-orm/sqlite-core";
120
- var folders = sqliteTable("folders", {
121
- /** Full mailbox path as returned by IMAP LIST (e.g. "INBOX", "[Gmail]/Sent Mail"). */
122
- name: text("name").primaryKey(),
123
- /** Delimiter the server uses - usually "." (Dovecot) or "/" (Gmail). */
124
- delimiter: text("delimiter").notNull(),
125
- /** RFC 6154 attribute ("\\Drafts", "\\Sent", etc.) or null. */
126
- specialUse: text("special_use"),
127
- /** UIDVALIDITY from SELECT response. If this changes, wipe the cache. */
128
- uidValidity: integer("uid_validity").notNull(),
129
- /** Next UID the server will assign. Used for new-message detection. */
130
- uidNext: integer("uid_next"),
131
- /** HIGHESTMODSEQ from CONDSTORE. NULL if the server doesn't support it. */
132
- highestModseq: integer("highest_modseq"),
133
- /** Epoch milliseconds of the last successful sync completion. */
134
- lastSyncedAt: integer("last_synced_at").notNull()
135
- });
136
- var emails = sqliteTable(
137
- "emails",
138
- {
139
- folder: text("folder").notNull(),
140
- uid: integer("uid").notNull(),
141
- /** RFC 5322 Message-ID header (with angle brackets). Enables cross-folder dedup. */
142
- messageId: text("message_id"),
143
- subject: text("subject"),
144
- fromAddr: text("from_addr"),
145
- /** JSON array of recipient email strings. */
146
- toAddrs: text("to_addrs", { mode: "json" }).$type(),
147
- ccAddrs: text("cc_addrs", { mode: "json" }).$type(),
148
- /** INTERNALDATE in epoch ms. */
149
- date: integer("date"),
150
- /** JSON array of IMAP flags ("\\Seen", "\\Flagged", etc.). */
151
- flags: text("flags", { mode: "json" }).$type().notNull(),
152
- /** Whether any MIME part is an attachment. Indexed for "has-attachment" filters. */
153
- hasAttachments: integer("has_attachments", { mode: "boolean" }).notNull().default(false),
154
- /** Full parsed envelope as JSON, for detail-view tools. */
155
- envelopeJson: text("envelope_json").notNull(),
156
- /** Plain-text body, nullable - fetched on demand unless IMAP_CACHE_BODY_INLINE=true. */
157
- bodyText: text("body_text"),
158
- /** HTML body, nullable. Can be large; keep lazy by default. */
159
- bodyHtml: text("body_html"),
160
- /** Per-message MODSEQ (RFC 7162). Used for CONDSTORE incremental sync. */
161
- modseq: integer("modseq"),
162
- /** Epoch ms of envelope cache write. */
163
- cachedAt: integer("cached_at").notNull(),
164
- /** Epoch ms of body cache write (NULL if body not yet fetched). */
165
- bodyCachedAt: integer("body_cached_at")
166
- },
167
- (t) => [
168
- primaryKey({ columns: [t.folder, t.uid] }),
169
- index("idx_emails_date").on(t.folder, t.date),
170
- index("idx_emails_message_id").on(t.messageId)
171
- ]
172
- );
173
-
174
- // src/errors/types.ts
175
- var McpInboxError = class extends Error {
176
- code;
177
- userMessage;
178
- constructor(code, userMessage, cause) {
179
- super(userMessage, cause !== void 0 ? { cause } : void 0);
180
- this.name = new.target.name;
181
- this.code = code;
182
- this.userMessage = userMessage;
183
- Error.captureStackTrace(this, new.target);
184
- }
185
- };
186
- var ImapError = class extends McpInboxError {
187
- };
188
- var SmtpError = class extends McpInboxError {
189
- };
190
- var CacheError = class extends McpInboxError {
191
- };
192
- var ToolInputError = class extends McpInboxError {
193
- constructor(userMessage, cause) {
194
- super("TOOL_INVALID_INPUT", userMessage, cause);
195
- }
196
- };
197
-
198
- // src/utils/logger.ts
199
- var LEVEL_WEIGHT = {
200
- debug: 10,
201
- info: 20,
202
- warn: 30,
203
- error: 40
204
- };
205
- var LoggerContext = class {
206
- // JS hard-private - consumers of the published package cannot poke at these
207
- // from plain JS. TS `private` would be compile-time only.
208
- #enabledNamespaces = [];
209
- #minLevel = "info";
210
- configure(opts) {
211
- this.#enabledNamespaces = parseNamespaces(opts.debug ?? "");
212
- this.#minLevel = opts.level ?? "info";
213
- }
214
- shouldEmit(level, namespace) {
215
- if (LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[this.#minLevel]) return true;
216
- return this.#enabledNamespaces.some((re) => re.test(namespace));
217
- }
218
- emit(level, namespace, msg, meta) {
219
- if (!this.shouldEmit(level, namespace)) return;
220
- const entry = {
221
- ...meta ?? {},
222
- ts: (/* @__PURE__ */ new Date()).toISOString(),
223
- level,
224
- ns: namespace,
225
- msg
226
- };
227
- process.stderr.write(JSON.stringify(entry) + "\n");
228
- }
229
- logger(namespace) {
230
- return {
231
- debug: (msg, meta) => this.emit("debug", namespace, msg, meta),
232
- info: (msg, meta) => this.emit("info", namespace, msg, meta),
233
- warn: (msg, meta) => this.emit("warn", namespace, msg, meta),
234
- error: (msg, meta) => this.emit("error", namespace, msg, meta),
235
- child: (sub) => this.logger(`${namespace}:${sub}`)
236
- };
237
- }
238
- };
239
- function parseNamespaces(spec) {
240
- return spec.split(",").map((s) => s.trim()).filter((s) => s.length > 0).map((pattern) => {
241
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
242
- return new RegExp(`^${escaped}$`);
243
- });
244
- }
245
- var defaultContext = new LoggerContext();
246
- function configureLogger(opts) {
247
- defaultContext.configure(opts);
248
- }
249
- function createLogger(namespace, context = defaultContext) {
250
- return context.logger(namespace);
251
- }
252
- var rootLogger = createLogger("mcp-inbox");
253
-
254
- // src/cache/db.ts
255
- var DEFAULT_MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url));
256
- var log = createLogger("mcp-inbox:cache");
257
- function openCache(path, migrationsFolder) {
258
- if (path !== ":memory:") {
259
- try {
260
- mkdirSync(dirname(path), { recursive: true });
261
- } catch (err) {
262
- throw new CacheError("CACHE_IO_FAILED", diagnoseOpenError(path, err), err);
263
- }
264
- }
265
- let sqlite;
266
- try {
267
- sqlite = new Database(path);
268
- } catch (err) {
269
- throw new CacheError("CACHE_IO_FAILED", diagnoseOpenError(path, err), err);
270
- }
271
- sqlite.pragma("journal_mode = WAL");
272
- sqlite.pragma("foreign_keys = ON");
273
- sqlite.pragma("synchronous = NORMAL");
274
- const db = drizzle(sqlite, { schema: schema_exports });
275
- if (migrationsFolder) {
276
- try {
277
- migrate(db, { migrationsFolder });
278
- log.info("cache migrations applied", { migrationsFolder });
279
- } catch (err) {
280
- sqlite.close();
281
- throw new CacheError(
282
- "CACHE_SCHEMA_MISMATCH",
283
- "Failed to apply cache migrations. If the cache was created by a newer version, remove it and let mcp-inbox rebuild.",
284
- err
285
- );
286
- }
287
- }
288
- return {
289
- db,
290
- close: () => {
291
- try {
292
- sqlite.close();
293
- } catch (err) {
294
- log.warn("error closing cache db", {
295
- msg: err instanceof Error ? err.message : String(err)
296
- });
297
- }
298
- }
299
- };
300
- }
301
- function diagnoseOpenError(path, err) {
302
- const msg = err instanceof Error ? err.message : String(err);
303
- const code = err && typeof err === "object" && "code" in err ? String(err.code) : void 0;
304
- let hint;
305
- if (/cannot find module|invalid elf|was compiled against|node_modules[\\/]better-sqlite3/i.test(msg)) {
306
- hint = "The better-sqlite3 native binding failed to load. Try:\n npm rebuild better-sqlite3\nor reinstall: npm install -g @kbzowski/mcp-inbox --force";
307
- } else if (code === "EACCES" || code === "EPERM" || /permission denied|operation not permitted/i.test(msg)) {
308
- hint = "Permission denied. Check that IMAP_CACHE_DIR is writable by the current user.";
309
- } else if (code === "EBUSY" || /database is locked|SQLITE_BUSY|locked/i.test(msg)) {
310
- hint = "The cache file is locked, probably by another mcp-inbox instance (Claude Desktop + Claude Code both launching the server, for example). Close the other client or point this one at a different IMAP_CACHE_DIR.";
311
- } else if (code === "ENOENT") {
312
- hint = "Path not found. IMAP_CACHE_DIR or one of its parents may not exist and could not be created.";
313
- } else if (/disk i\/o|disk full|ENOSPC/i.test(msg) || code === "ENOSPC") {
314
- hint = "Disk I/O error (out of space, or the volume was disconnected).";
315
- } else {
316
- hint = `Underlying error: ${msg}`;
317
- }
318
- return `Could not open cache database at ${path}. ${hint}`;
319
- }
320
-
321
- // src/imap/client.ts
322
- import { ImapFlow } from "imapflow";
323
-
324
- // src/errors/mapper.ts
325
- function mapImapError(err) {
326
- if (err instanceof ImapError) return err;
327
- const message = errorMessage(err);
328
- const code = errorCode(err);
329
- const lower = message.toLowerCase();
330
- if (code === "ENOTFOUND" || lower.includes("getaddrinfo")) {
331
- return new ImapError(
332
- "IMAP_HOST_UNREACHABLE",
333
- "Cannot resolve the IMAP host. Verify IMAP_HOST is spelled correctly.",
334
- err
335
- );
336
- }
337
- if (code === "ECONNREFUSED") {
338
- return new ImapError(
339
- "IMAP_CONNECTION_REFUSED",
340
- "Connection refused by the IMAP server. Check IMAP_PORT (993 for TLS, 143 for STARTTLS).",
341
- err
342
- );
343
- }
344
- if (code === "ETIMEDOUT" || lower.includes("timeout")) {
345
- return new ImapError(
346
- "IMAP_TIMEOUT",
347
- "The IMAP server did not respond in time. Check your network or increase IMAP_AUTH_TIMEOUT_MS.",
348
- err
349
- );
350
- }
351
- if (code === "AUTHENTICATIONFAILED" || code === "EAUTH" || lower.includes("invalid credentials") || lower.includes("authentication failed") || lower.includes("auth failed") || lower.includes("login failed")) {
352
- return new ImapError(
353
- "IMAP_AUTH_FAILED",
354
- "IMAP authentication failed. For Gmail/Outlook use an app password, not your account password. Gmail app passwords: https://myaccount.google.com/apppasswords",
355
- err
356
- );
357
- }
358
- if (lower.includes("mailbox does not exist") || lower.includes("doesn't exist")) {
359
- return new ImapError(
360
- "IMAP_FOLDER_NOT_FOUND",
361
- "Folder not found on the server. Run imap_list_folders to see available folders.",
362
- err
363
- );
364
- }
365
- if (lower.includes("uidvalidity")) {
366
- return new ImapError(
367
- "IMAP_UIDVALIDITY_CHANGED",
368
- "The folder was rebuilt on the server; cached UIDs are no longer valid. The cache will resync automatically - retry the operation.",
369
- err
370
- );
371
- }
372
- return new ImapError("IMAP_UNKNOWN", "IMAP operation failed. See server logs for details.", err);
373
- }
374
- function mapSmtpError(err) {
375
- if (err instanceof SmtpError) return err;
376
- const message = errorMessage(err);
377
- const code = errorCode(err);
378
- const lower = message.toLowerCase();
379
- if (code === "EAUTH" || lower.includes("invalid login") || lower.includes("authentication failed") || lower.includes("auth failed")) {
380
- return new SmtpError(
381
- "SMTP_AUTH_FAILED",
382
- "SMTP authentication failed. If you set SMTP_USER/SMTP_PASSWORD, verify them; otherwise the IMAP credentials are reused.",
383
- err
384
- );
385
- }
386
- if (code === "ECONNECTION" || code === "ECONNREFUSED" || code === "ETIMEDOUT" || code === "EENVELOPE" || lower.includes("cannot connect") || lower.includes("could not connect") || lower.includes("connection refused")) {
387
- return new SmtpError(
388
- "SMTP_SEND_FAILED",
389
- "Could not connect to the SMTP server. Check SMTP_HOST / SMTP_PORT. Outlook requires SMTP_PORT=587 and SMTP_SECURE=false.",
390
- err
391
- );
392
- }
393
- return new SmtpError("SMTP_UNKNOWN", "SMTP send failed. See server logs for details.", err);
394
- }
395
- function errorMessage(err) {
396
- if (err instanceof Error) return err.message;
397
- if (typeof err === "string") return err;
398
- if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
399
- return err.message;
400
- }
401
- return String(err);
402
- }
403
- function errorCode(err) {
404
- if (err && typeof err === "object" && "code" in err && typeof err.code === "string") {
405
- return err.code;
406
- }
407
- return void 0;
408
- }
409
- function isMcpInboxError(err) {
410
- return err instanceof McpInboxError;
411
- }
412
-
413
- // src/imap/client.ts
414
- var log2 = createLogger("mcp-inbox:imap");
415
- async function createImapConnection(config) {
416
- log2.info("opening IMAP connection", {
417
- host: config.host,
418
- port: config.port,
419
- tls: config.tls
420
- });
421
- const flow = new ImapFlow({
422
- host: config.host,
423
- port: config.port,
424
- secure: config.tls,
425
- auth: {
426
- user: config.user,
427
- pass: config.password
428
- },
429
- ...config.tls && !config.tlsRejectUnauthorized ? { tls: { rejectUnauthorized: false } } : {},
430
- // We own the logger; mute ImapFlow's built-in console logger.
431
- logger: false,
432
- // Our own timeout policy.
433
- connectionTimeout: config.authTimeoutMs,
434
- greetingTimeout: config.authTimeoutMs
435
- });
436
- flow.on("error", (err) => {
437
- log2.error("IMAP connection error", {
438
- msg: err instanceof Error ? err.message : String(err)
439
- });
440
- });
441
- try {
442
- await flow.connect();
443
- } catch (err) {
444
- throw mapImapError(err);
445
- }
446
- log2.info("IMAP connection ready");
447
- return flow;
448
- }
449
- var ImapClient = class {
450
- #config;
451
- #flow = null;
452
- #connecting = null;
453
- #closed = false;
454
- constructor(config) {
455
- this.#config = config;
456
- }
457
- /**
458
- * Returns an authenticated ImapFlow instance, connecting if necessary.
459
- * Multiple concurrent callers share the same in-flight connection attempt.
460
- */
461
- async connection() {
462
- if (this.#closed) {
463
- throw new Error("ImapClient has been closed");
464
- }
465
- if (this.#flow?.usable) {
466
- return this.#flow;
467
- }
468
- if (this.#connecting) {
469
- return this.#connecting;
470
- }
471
- this.#connecting = this.#openConnection();
472
- try {
473
- this.#flow = await this.#connecting;
474
- return this.#flow;
475
- } finally {
476
- this.#connecting = null;
477
- }
478
- }
479
- async #openConnection() {
480
- const flow = await createImapConnection(this.#config);
481
- flow.on("close", () => {
482
- if (!this.#closed) {
483
- log2.warn("IMAP connection closed unexpectedly");
484
- }
485
- if (this.#flow === flow) {
486
- this.#flow = null;
487
- }
488
- });
489
- return flow;
490
- }
491
- /**
492
- * Cleanly close the connection. Safe to call multiple times.
493
- */
494
- async close() {
495
- if (this.#closed) return;
496
- this.#closed = true;
497
- const flow = this.#flow;
498
- this.#flow = null;
499
- if (flow?.usable) {
500
- try {
501
- await flow.logout();
502
- } catch (err) {
503
- log2.warn("error during IMAP logout", {
504
- msg: err instanceof Error ? err.message : String(err)
505
- });
506
- }
507
- }
508
- }
509
- };
510
-
511
- // src/cache/queries.ts
512
- import { and, desc, eq, gte, inArray, lt, sql } from "drizzle-orm";
513
- function upsertFolder(db, row) {
514
- db.insert(folders).values(row).onConflictDoUpdate({
515
- target: folders.name,
516
- set: {
517
- delimiter: row.delimiter,
518
- specialUse: row.specialUse ?? null,
519
- uidValidity: row.uidValidity,
520
- uidNext: row.uidNext ?? null,
521
- highestModseq: row.highestModseq ?? null,
522
- lastSyncedAt: row.lastSyncedAt
523
- }
524
- }).run();
525
- }
526
- function getFolder(db, name) {
527
- return db.select().from(folders).where(eq(folders.name, name)).get();
528
- }
529
- function upsertEmail(db, row) {
530
- db.insert(emails).values(row).onConflictDoUpdate({
531
- target: [emails.folder, emails.uid],
532
- set: {
533
- messageId: row.messageId ?? null,
534
- subject: row.subject ?? null,
535
- fromAddr: row.fromAddr ?? null,
536
- toAddrs: row.toAddrs ?? null,
537
- ccAddrs: row.ccAddrs ?? null,
538
- date: row.date ?? null,
539
- flags: row.flags,
540
- hasAttachments: row.hasAttachments ?? false,
541
- envelopeJson: row.envelopeJson,
542
- modseq: row.modseq ?? null,
543
- cachedAt: row.cachedAt
544
- }
545
- }).run();
546
- }
547
- function getEmail(db, folder, uid) {
548
- return db.select().from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
549
- }
550
- function listEmailsByFolder(db, folder, opts = {}) {
551
- const conditions = [eq(emails.folder, folder)];
552
- if (opts.sinceMs !== void 0) conditions.push(gte(emails.date, opts.sinceMs));
553
- if (opts.beforeMs !== void 0) conditions.push(lt(emails.date, opts.beforeMs));
554
- 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();
555
- if (opts.unseenOnly) {
556
- rows = rows.filter((r) => !r.flags.includes("\\Seen"));
557
- }
558
- return rows;
559
- }
560
- function countEmailsInFolder(db, folder) {
561
- const row = db.select({ n: sql`count(*)` }).from(emails).where(eq(emails.folder, folder)).get();
562
- return row?.n ?? 0;
563
- }
564
- function setEmailFlags(db, folder, uid, flags) {
565
- db.update(emails).set({ flags }).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
566
- }
567
- function mutateEmailFlagsForUids(db, folder, uids, mutate) {
568
- if (uids.length === 0) return;
569
- db.transaction((tx) => {
570
- const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, uids))).all();
571
- for (const row of rows) {
572
- const next = mutate(row.flags);
573
- if (flagsEqual(row.flags, next)) continue;
574
- tx.update(emails).set({ flags: next }).where(and(eq(emails.folder, folder), eq(emails.uid, row.uid))).run();
575
- }
576
- });
577
- }
578
- function flagsEqual(a, b) {
579
- if (a.length !== b.length) return false;
580
- const setB = new Set(b);
581
- for (const f of a) if (!setB.has(f)) return false;
582
- return true;
583
- }
584
- function deleteEmailsByFolder(db, folder) {
585
- db.delete(emails).where(eq(emails.folder, folder)).run();
586
- }
587
- function deleteEmail(db, folder, uid) {
588
- db.delete(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
589
- }
590
- function deleteEmailsByUids(db, folder, uids) {
591
- if (uids.length === 0) return;
592
- db.delete(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, uids))).run();
593
- }
594
- function getEmailBody(db, folder, uid) {
595
- const row = db.select({
596
- bodyText: emails.bodyText,
597
- bodyHtml: emails.bodyHtml,
598
- bodyCachedAt: emails.bodyCachedAt
599
- }).from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
600
- return row;
601
- }
602
- function setEmailBody(db, folder, uid, body, nowMs) {
603
- db.update(emails).set({
604
- bodyText: body.text,
605
- bodyHtml: body.html,
606
- bodyCachedAt: nowMs
607
- }).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
608
- }
609
-
610
- // src/cache/sync.ts
611
- var log3 = createLogger("mcp-inbox:sync");
612
- async function syncFolder(ctx, folderPath) {
613
- const started = Date.now();
614
- const lock = await ctx.imap.getMailboxLock(folderPath);
615
- try {
616
- const box = ctx.imap.mailbox;
617
- if (!box || typeof box === "boolean") {
618
- throw new Error("mailbox unexpectedly closed after getMailboxLock");
619
- }
620
- const cached = getFolder(ctx.db, folderPath);
621
- const uidValidityChanged = cached !== void 0 && cached.uidValidity !== Number(box.uidValidity);
622
- if (uidValidityChanged) {
623
- log3.warn("UIDVALIDITY changed - wiping folder cache", {
624
- folder: folderPath,
625
- cached: cached?.uidValidity,
626
- server: Number(box.uidValidity)
627
- });
628
- deleteEmailsByFolder(ctx.db, folderPath);
629
- }
630
- const { syncType, fetched } = await runSync(ctx, folderPath, box, cached, uidValidityChanged);
631
- upsertFolder(ctx.db, {
632
- name: folderPath,
633
- delimiter: box.delimiter ?? "/",
634
- specialUse: box.specialUse ?? null,
635
- uidValidity: Number(box.uidValidity),
636
- uidNext: box.uidNext !== void 0 ? Number(box.uidNext) : null,
637
- highestModseq: box.highestModseq !== void 0 ? Number(box.highestModseq) : null,
638
- lastSyncedAt: Date.now()
639
- });
640
- const durationMs = Date.now() - started;
641
- log3.info("folder synced", { folder: folderPath, syncType, fetched, durationMs });
642
- return { folder: folderPath, syncType, fetched, durationMs };
643
- } catch (err) {
644
- throw mapImapError(err);
645
- } finally {
646
- lock.release();
647
- }
648
- }
649
- async function runSync(ctx, folderPath, box, cached, uidValidityChanged) {
650
- if (!cached || uidValidityChanged) {
651
- const fetched2 = await fetchAndStoreRange(ctx, folderPath, "1:*");
652
- return { syncType: "full", fetched: fetched2 };
653
- }
654
- const serverModseq = box.highestModseq !== void 0 ? Number(box.highestModseq) : null;
655
- if (serverModseq !== null && cached.highestModseq !== null && cached.highestModseq !== void 0) {
656
- if (serverModseq === cached.highestModseq) {
657
- return { syncType: "skipped", fetched: 0 };
658
- }
659
- const fetched2 = await fetchAndStoreRange(ctx, folderPath, "1:*", BigInt(cached.highestModseq));
660
- return { syncType: "incremental", fetched: fetched2 };
661
- }
662
- const fetched = await fetchAndStoreRange(ctx, folderPath, "1:*");
663
- return { syncType: "full", fetched };
664
- }
665
- async function fetchAndStoreRange(ctx, folderPath, range, changedSince) {
666
- const now = Date.now();
667
- let count = 0;
668
- const options = changedSince !== void 0 ? { uid: true, changedSince } : { uid: true };
669
- const iterator = ctx.imap.fetch(
670
- range,
671
- {
672
- envelope: true,
673
- flags: true,
674
- internalDate: true,
675
- bodyStructure: true
676
- },
677
- options
678
- );
679
- for await (const msg of iterator) {
680
- const insert = messageToInsert(folderPath, msg, now);
681
- if (insert) {
682
- upsertEmail(ctx.db, insert);
683
- count++;
684
- }
685
- }
686
- return count;
687
- }
688
- function messageToInsert(folderPath, msg, cachedAt) {
689
- if (typeof msg.uid !== "number") return null;
690
- const env = msg.envelope;
691
- const date = env?.date ?? msg.internalDate;
692
- const flags = msg.flags ? Array.from(msg.flags) : [];
693
- return {
694
- folder: folderPath,
695
- uid: msg.uid,
696
- messageId: env?.messageId ?? null,
697
- subject: env?.subject ?? null,
698
- fromAddr: env?.from?.[0]?.address ?? null,
699
- toAddrs: env?.to?.map((a) => a.address ?? "").filter((a) => a.length > 0) ?? null,
700
- ccAddrs: env?.cc?.map((a) => a.address ?? "").filter((a) => a.length > 0) ?? null,
701
- date: date instanceof Date ? date.getTime() : null,
702
- flags,
703
- hasAttachments: hasAttachments(msg.bodyStructure),
704
- envelopeJson: JSON.stringify(env ?? {}),
705
- modseq: msg.modseq !== void 0 ? Number(msg.modseq) : null,
706
- cachedAt
707
- };
708
- }
709
- function hasAttachments(structure) {
710
- if (!structure) return false;
711
- if (structure.disposition?.toLowerCase() === "attachment") return true;
712
- if (structure.dispositionParameters?.filename) return true;
713
- if (structure.childNodes) {
714
- return structure.childNodes.some(hasAttachments);
715
- }
716
- return false;
717
- }
718
-
719
- // src/cache/idle.ts
720
- var log4 = createLogger("mcp-inbox:idle");
721
- var IdleManager = class {
722
- #opts;
723
- #subscriptions = [];
724
- #stopped = false;
725
- constructor(opts) {
726
- this.#opts = opts;
727
- }
728
- /** Open a watching connection per configured folder. Idempotent. */
729
- async start() {
730
- if (this.#subscriptions.length > 0 || this.#stopped) return;
731
- for (const folder of this.#opts.folders) {
732
- try {
733
- const sub = await this.#watchFolder(folder);
734
- this.#subscriptions.push(sub);
735
- } catch (err) {
736
- log4.error("failed to open IDLE for folder", {
737
- folder,
738
- msg: err instanceof Error ? err.message : String(err)
739
- });
740
- }
741
- }
742
- }
743
- /** Release every watching connection. Idempotent. */
744
- async stop() {
745
- if (this.#stopped) return;
746
- this.#stopped = true;
747
- const subs = this.#subscriptions;
748
- this.#subscriptions = [];
749
- await Promise.all(subs.map((s) => s.stop()));
750
- }
751
- async #watchFolder(folder) {
752
- const imap = await createImapConnection(this.#opts.imap);
753
- await imap.mailboxOpen(folder);
754
- log4.info("watching folder", { folder });
755
- const onExists = (e) => {
756
- log4.debug("exists event", { folder: e.path, count: e.count, prevCount: e.prevCount });
757
- void this.#handleExists(folder, imap);
758
- };
759
- const onFlags = (e) => {
760
- log4.debug("flags event", { folder: e.path, uid: e.uid, flags: Array.from(e.flags) });
761
- if (e.uid !== void 0) {
762
- setEmailFlags(this.#opts.db, folder, e.uid, Array.from(e.flags));
763
- } else {
764
- void this.#resyncFolder(folder, imap);
765
- }
766
- };
767
- const onExpunge = (e) => {
768
- log4.debug("expunge event", { folder: e.path, uid: e.uid, seq: e.seq });
769
- if (e.uid !== void 0) {
770
- deleteEmail(this.#opts.db, folder, e.uid);
771
- } else {
772
- void this.#resyncFolder(folder, imap);
773
- }
774
- };
775
- imap.on("exists", onExists);
776
- imap.on("flags", onFlags);
777
- imap.on("expunge", onExpunge);
778
- return {
779
- folder,
780
- stop: async () => {
781
- imap.off("exists", onExists);
782
- imap.off("flags", onFlags);
783
- imap.off("expunge", onExpunge);
784
- try {
785
- await imap.logout();
786
- } catch (err) {
787
- log4.warn("error closing IDLE connection", {
788
- folder,
789
- msg: err instanceof Error ? err.message : String(err)
790
- });
791
- }
792
- }
793
- };
794
- }
795
- async #handleExists(folder, imap) {
796
- try {
797
- await syncFolder({ db: this.#opts.db, imap }, folder);
798
- } catch (err) {
799
- log4.error("exists sync failed", {
800
- folder,
801
- msg: err instanceof Error ? err.message : String(err)
802
- });
803
- }
804
- }
805
- async #resyncFolder(folder, imap) {
806
- try {
807
- await syncFolder({ db: this.#opts.db, imap }, folder);
808
- } catch (err) {
809
- log4.error("resync failed", {
810
- folder,
811
- msg: err instanceof Error ? err.message : String(err)
812
- });
813
- }
814
- }
815
- };
816
-
817
- // src/smtp/client.ts
818
- import nodemailer from "nodemailer";
819
- var log5 = createLogger("mcp-inbox:smtp");
820
- var SmtpClient = class {
821
- #config;
822
- #transporter = null;
823
- #closed = false;
824
- constructor(config) {
825
- this.#config = config;
826
- }
827
- transporter() {
828
- if (this.#closed) {
829
- throw new Error("SmtpClient has been closed");
830
- }
831
- if (this.#transporter) return this.#transporter;
832
- log5.info("creating SMTP transporter", {
833
- host: this.#config.host,
834
- port: this.#config.port,
835
- secure: this.#config.secure
836
- });
837
- this.#transporter = nodemailer.createTransport({
838
- host: this.#config.host,
839
- port: this.#config.port,
840
- secure: this.#config.secure,
841
- auth: {
842
- user: this.#config.user,
843
- pass: this.#config.password
844
- }
845
- });
846
- return this.#transporter;
847
- }
848
- /**
849
- * Send a pre-built raw RFC 2822 message. Uses the explicit envelope
850
- * to avoid relying on header parsing - the envelope from/to are
851
- * what actually drive SMTP delivery.
852
- */
853
- async sendRaw(raw, envelope) {
854
- try {
855
- const info = await this.transporter().sendMail({
856
- envelope: {
857
- from: envelope.from,
858
- to: envelope.to
859
- },
860
- raw
861
- });
862
- return {
863
- messageId: info.messageId ?? null,
864
- response: info.response ?? ""
865
- };
866
- } catch (err) {
867
- throw mapSmtpError(err);
868
- }
869
- }
870
- close() {
871
- if (this.#closed) return;
872
- this.#closed = true;
873
- try {
874
- this.#transporter?.close();
875
- } catch {
876
- }
877
- }
878
- };
879
-
880
- // src/server.ts
881
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
882
- import {
883
- CallToolRequestSchema,
884
- ListToolsRequestSchema
885
- } from "@modelcontextprotocol/sdk/types.js";
886
-
887
- // src/tools/registry.ts
888
- import { z as z21 } from "zod";
889
-
890
- // src/tools/folders/list-folders.ts
891
- import { z as z2 } from "zod";
892
-
893
- // src/tools/define-tool.ts
894
- function defineTool(def) {
895
- return def;
896
- }
897
-
898
- // src/formatters/markdown.ts
899
- function formatFoldersMarkdown(folders2) {
900
- if (folders2.length === 0) return "_No folders._";
901
- const lines = ["| Path | Delimiter | Special-use |", "|---|---|---|"];
902
- for (const f of folders2) {
903
- lines.push(`| \`${f.path}\` | \`${f.delimiter}\` | ${f.specialUse ?? "-"} |`);
904
- }
905
- return lines.join("\n");
906
- }
907
- function formatEmailListMarkdown(emails2) {
908
- if (emails2.length === 0) return "_No emails match._";
909
- const lines = [
910
- "| # | Flags | From | Subject | Date | UID |",
911
- "|---|---|---|---|---|---|"
912
- ];
913
- emails2.forEach((e, i) => {
914
- const date = e.date ? new Date(e.date).toISOString().slice(0, 16).replace("T", " ") : "";
915
- const unseen = !e.flags.includes("\\Seen");
916
- const flagMarks = (unseen ? "UNSEEN " : "") + (e.flags.includes("\\Flagged") ? "\u2605 " : "") + (e.hasAttachments ? "\u{1F4CE}" : "");
917
- const subject = (e.subject ?? "").replace(/\|/g, "\\|");
918
- const from = (e.fromAddr ?? "").replace(/\|/g, "\\|");
919
- const row = `| ${i + 1} | ${flagMarks.trim()} | ${from} | ${subject} | ${date} | ${e.uid} |`;
920
- lines.push(unseen ? `**${row}**` : row);
921
- });
922
- return lines.join("\n");
923
- }
924
-
925
- // src/tools/folders/list-folders.ts
926
- var Input = z2.object({
927
- response_format: z2.enum(["markdown", "json"]).default("markdown")
928
- });
929
- var listFoldersTool = defineTool({
930
- name: "imap_list_folders",
931
- description: "List every folder/mailbox in the account. Returns each folder's path, path delimiter, and RFC 6154 special-use attribute (\\Drafts, \\Sent, \\Trash, \\Junk) where the server advertises one. Use this to discover folder names for other tools that accept a `folder` argument.",
932
- annotations: {
933
- readOnlyHint: true,
934
- destructiveHint: false,
935
- idempotentHint: true,
936
- openWorldHint: true
937
- },
938
- inputSchema: Input,
939
- handler: async (args, ctx) => {
940
- let folders2;
941
- try {
942
- const imap = await ctx.imap.connection();
943
- folders2 = await imap.list();
944
- } catch (err) {
945
- throw mapImapError(err);
946
- }
947
- const summaries = folders2.map((f) => ({
948
- path: f.path,
949
- delimiter: f.delimiter,
950
- specialUse: f.specialUse ?? null,
951
- flags: Array.from(f.flags)
952
- }));
953
- const text2 = args.response_format === "json" ? JSON.stringify({ folders: summaries }, null, 2) : formatFoldersMarkdown(summaries);
954
- return {
955
- content: [{ type: "text", text: text2 }],
956
- structuredContent: { folders: summaries }
957
- };
958
- }
959
- });
960
-
961
- // src/tools/emails/list-emails.ts
962
- import { z as z3 } from "zod";
963
-
964
- // src/tools/emails/shared.ts
965
- import { simpleParser } from "mailparser";
966
-
967
- // src/imap/folders.ts
968
- function findSpecialFolder(folders2, attr) {
969
- const bySpecial = folders2.find((f) => f.specialUse === attr);
970
- if (bySpecial) return bySpecial.path;
971
- const candidates = NAME_CANDIDATES[attr];
972
- const pathSet = new Set(folders2.map((f) => f.path));
973
- for (const candidate of candidates) {
974
- if (pathSet.has(candidate)) return candidate;
975
- }
976
- return void 0;
977
- }
978
- var NAME_CANDIDATES = {
979
- "\\Drafts": [
980
- "Drafts",
981
- "Draft",
982
- "INBOX.Drafts",
983
- "INBOX/Drafts",
984
- "[Gmail]/Drafts",
985
- "[Google Mail]/Drafts"
986
- ],
987
- "\\Sent": [
988
- "Sent",
989
- "Sent Items",
990
- "Sent Mail",
991
- "INBOX.Sent",
992
- "INBOX/Sent",
993
- "[Gmail]/Sent Mail",
994
- "[Google Mail]/Sent Mail"
995
- ],
996
- "\\Trash": [
997
- "Trash",
998
- "Deleted",
999
- "Deleted Items",
1000
- "INBOX.Trash",
1001
- "INBOX/Trash",
1002
- "[Gmail]/Trash",
1003
- "[Google Mail]/Trash"
1004
- ],
1005
- "\\Junk": [
1006
- "Junk",
1007
- "Junk Email",
1008
- "Spam",
1009
- "INBOX.Junk",
1010
- "INBOX/Junk",
1011
- "[Gmail]/Spam",
1012
- "[Google Mail]/Spam"
1013
- ],
1014
- "\\All": ["Archive", "All Mail", "[Gmail]/All Mail", "[Google Mail]/All Mail"],
1015
- "\\Flagged": ["Starred", "Flagged", "[Gmail]/Starred", "[Google Mail]/Starred"]
1016
- };
1017
-
1018
- // src/tools/emails/shared.ts
1019
- async function syncIfStale(ctx, folder, maxStalenessSec) {
1020
- const cached = getFolder(ctx.db, folder);
1021
- const ageMs = cached ? ctx.now() - cached.lastSyncedAt : Infinity;
1022
- const stale = ageMs >= maxStalenessSec * 1e3;
1023
- if (stale) {
1024
- const imap = await ctx.imap.connection();
1025
- await syncFolder({ db: ctx.db, imap }, folder);
1026
- }
1027
- return stale;
1028
- }
1029
- function readEnvelopes(ctx, folder, opts) {
1030
- const rows = listEmailsByFolder(ctx.db, folder, opts);
1031
- const total = countEmailsInFolder(ctx.db, folder);
1032
- const offset = opts.offset ?? 0;
1033
- const limit = opts.limit ?? 100;
1034
- const hasMore = offset + rows.length < total;
1035
- return { rows, total, hasMore, nextOffset: hasMore ? offset + limit : null };
1036
- }
1037
- async function resolveSpecialFolder(ctx, attr, explicitOverride) {
1038
- if (explicitOverride) return explicitOverride;
1039
- try {
1040
- const imap = await ctx.imap.connection();
1041
- const list = await imap.list();
1042
- const path = findSpecialFolder(list, attr);
1043
- if (!path) {
1044
- throw new ImapError(
1045
- "IMAP_FOLDER_NOT_FOUND",
1046
- `No folder matches ${attr} on this server. Pass an explicit \`folder\` to override, or run imap_list_folders to find the right name.`
1047
- );
1048
- }
1049
- return path;
1050
- } catch (err) {
1051
- if (err instanceof ImapError) throw err;
1052
- throw mapImapError(err);
1053
- }
1054
- }
1055
- async function ensureBodyCached(ctx, folder, uid) {
1056
- const imap = await ctx.imap.connection();
1057
- const lock = await imap.getMailboxLock(folder);
1058
- try {
1059
- const msg = await imap.fetchOne(String(uid), { source: true }, { uid: true });
1060
- if (!msg || msg.source === void 0) {
1061
- throw new ImapError(
1062
- "IMAP_MESSAGE_NOT_FOUND",
1063
- `Message with UID ${String(uid)} was not found in ${folder}. It may have been moved or deleted.`
1064
- );
1065
- }
1066
- const parsed = await simpleParser(msg.source);
1067
- const bodyText = parsed.text ?? null;
1068
- const bodyHtml = typeof parsed.html === "string" ? parsed.html : null;
1069
- const cached = getEmailBody(ctx.db, folder, uid);
1070
- if (cached?.bodyCachedAt == null) {
1071
- setEmailBody(ctx.db, folder, uid, { text: bodyText, html: bodyHtml }, ctx.now());
1072
- }
1073
- const attachments = (parsed.attachments ?? []).map((a) => ({
1074
- filename: a.filename ?? null,
1075
- content_type: a.contentType ?? "application/octet-stream",
1076
- size_bytes: typeof a.size === "number" ? a.size : 0
1077
- }));
1078
- return { bodyText, bodyHtml, attachments };
1079
- } catch (err) {
1080
- if (err instanceof ImapError) throw err;
1081
- throw mapImapError(err);
1082
- } finally {
1083
- lock.release();
1084
- }
1085
- }
1086
- async function ensureEnvelopeCached(ctx, folder, uid, maxStalenessSec) {
1087
- const existing = getEmail(ctx.db, folder, uid);
1088
- if (existing !== void 0) {
1089
- await syncIfStale(ctx, folder, maxStalenessSec);
1090
- } else {
1091
- await syncIfStale(ctx, folder, 0);
1092
- }
1093
- const row = getEmail(ctx.db, folder, uid);
1094
- if (!row) {
1095
- throw new ImapError(
1096
- "IMAP_MESSAGE_NOT_FOUND",
1097
- `No message with UID ${String(uid)} in folder ${folder}.`
1098
- );
1099
- }
1100
- return row;
1101
- }
1102
- function projectEmailSummary(e) {
1103
- return {
1104
- uid: e.uid,
1105
- folder: e.folder,
1106
- message_id: e.messageId,
1107
- subject: e.subject,
1108
- from: e.fromAddr,
1109
- to: e.toAddrs,
1110
- cc: e.ccAddrs,
1111
- date: e.date !== null ? new Date(e.date).toISOString() : null,
1112
- flags: e.flags,
1113
- has_attachments: e.hasAttachments,
1114
- unseen: !e.flags.includes("\\Seen")
1115
- };
1116
- }
1117
-
1118
- // src/tools/emails/list-emails.ts
1119
- var Input2 = z3.object({
1120
- folder: z3.string().min(1).default("INBOX").describe("Folder path to list. Use imap_list_folders to discover paths."),
1121
- limit: z3.number().int().min(1).max(100).default(20),
1122
- offset: z3.number().int().min(0).default(0),
1123
- unseen_only: z3.boolean().default(false),
1124
- since_date: z3.string().date().optional().describe("YYYY-MM-DD. Only return emails received on or after this date."),
1125
- before_date: z3.string().date().optional().describe("YYYY-MM-DD. Only return emails received strictly before this date."),
1126
- max_staleness_seconds: z3.number().int().min(0).default(60).describe(
1127
- "Serve from cache if the folder was synced within this many seconds. Pass 0 to force a fresh sync."
1128
- ),
1129
- response_format: z3.enum(["markdown", "json"]).default("markdown")
1130
- });
1131
- var listEmailsTool = defineTool({
1132
- name: "imap_list_emails",
1133
- description: "List emails in a folder, newest first. Pagination via `limit` + `offset`; filter by unseen, since_date, before_date. Cache-aware: serves from local SQLite when the folder was synced recently, falls through to an incremental IMAP sync otherwise.",
1134
- annotations: {
1135
- readOnlyHint: true,
1136
- destructiveHint: false,
1137
- idempotentHint: true,
1138
- openWorldHint: true
1139
- },
1140
- inputSchema: Input2,
1141
- handler: async (args, ctx) => {
1142
- const didSync = await syncIfStale(ctx, args.folder, args.max_staleness_seconds);
1143
- const { rows, total, hasMore, nextOffset } = readEnvelopes(ctx, args.folder, {
1144
- limit: args.limit,
1145
- offset: args.offset,
1146
- unseenOnly: args.unseen_only,
1147
- ...args.since_date !== void 0 && {
1148
- sinceMs: new Date(args.since_date).getTime()
1149
- },
1150
- ...args.before_date !== void 0 && {
1151
- beforeMs: new Date(args.before_date).getTime()
1152
- }
1153
- });
1154
- const structured = {
1155
- folder: args.folder,
1156
- emails: rows.map(projectEmailSummary),
1157
- total_count: total,
1158
- has_more: hasMore,
1159
- next_offset: nextOffset,
1160
- served_from: didSync ? "sync" : "cache"
1161
- };
1162
- const text2 = args.response_format === "json" ? JSON.stringify(structured, null, 2) : formatEmailListMarkdown(rows);
1163
- return {
1164
- content: [{ type: "text", text: text2 }],
1165
- structuredContent: structured
1166
- };
1167
- }
1168
- });
1169
-
1170
- // src/tools/emails/get-email.ts
1171
- import { z as z4 } from "zod";
1172
- var Input3 = z4.object({
1173
- folder: z4.string().min(1).describe("Folder containing the message."),
1174
- uid: z4.number().int().positive().describe(
1175
- "IMAP UID of the message. UIDs are folder-scoped - a UID from INBOX cannot be reused with the Sent folder."
1176
- ),
1177
- max_staleness_seconds: z4.number().int().min(0).default(60),
1178
- response_format: z4.enum(["markdown", "json"]).default("markdown")
1179
- });
1180
- var getEmailTool = defineTool({
1181
- name: "imap_get_email",
1182
- description: "Fetch the full content of a single email: headers, plain-text body, HTML body, and attachment metadata (filename, content type, size). Attachment bytes are NOT downloaded or stored locally - the user can open them in their mail client. Use imap_list_emails or imap_search_emails to discover UIDs first.",
1183
- annotations: {
1184
- readOnlyHint: true,
1185
- destructiveHint: false,
1186
- idempotentHint: true,
1187
- openWorldHint: true
1188
- },
1189
- inputSchema: Input3,
1190
- handler: async (args, ctx) => {
1191
- const envelope = await ensureEnvelopeCached(
1192
- ctx,
1193
- args.folder,
1194
- args.uid,
1195
- args.max_staleness_seconds
1196
- );
1197
- const body = await ensureBodyCached(ctx, args.folder, args.uid);
1198
- const structured = {
1199
- ...projectEmailSummary(envelope),
1200
- body_text: body.bodyText,
1201
- body_html: body.bodyHtml,
1202
- attachments: body.attachments
1203
- };
1204
- const text2 = args.response_format === "json" ? JSON.stringify(structured, null, 2) : formatEmailDetail(structured);
1205
- return {
1206
- content: [{ type: "text", text: text2 }],
1207
- structuredContent: structured
1208
- };
1209
- }
1210
- });
1211
- function formatEmailDetail(e) {
1212
- const lines = [];
1213
- lines.push(`**Subject:** ${e.subject ?? "(no subject)"}`);
1214
- lines.push(`**From:** ${e.from ?? "(unknown)"}`);
1215
- lines.push(`**To:** ${(e.to ?? []).join(", ")}`);
1216
- if (e.cc && e.cc.length > 0) lines.push(`**Cc:** ${e.cc.join(", ")}`);
1217
- if (e.date) lines.push(`**Date:** ${e.date}`);
1218
- lines.push(`**Flags:** ${e.flags.length > 0 ? e.flags.join(", ") : "(none)"}`);
1219
- if (e.attachments.length > 0) {
1220
- lines.push(`**Attachments (${String(e.attachments.length)}):**`);
1221
- for (const a of e.attachments) {
1222
- lines.push(
1223
- ` - ${a.filename ?? "(unnamed)"} (${a.content_type}, ${String(a.size_bytes)} bytes)`
1224
- );
1225
- }
1226
- }
1227
- lines.push("", "---", "");
1228
- if (e.body_text && e.body_text.trim().length > 0) {
1229
- lines.push(e.body_text.trim());
1230
- } else if (e.body_html) {
1231
- lines.push("_(HTML-only message; fetch with response_format=json to read the HTML.)_");
1232
- } else {
1233
- lines.push("_(no body)_");
1234
- }
1235
- return lines.join("\n");
1236
- }
1237
-
1238
- // src/tools/emails/search-emails.ts
1239
- import { z as z5 } from "zod";
1240
-
1241
- // src/imap/search.ts
1242
- function buildImapSearch(c) {
1243
- const q = {};
1244
- if (c.subject) q.subject = c.subject;
1245
- if (c.from) q.from = c.from;
1246
- if (c.to) q.to = c.to;
1247
- if (c.body) q.body = c.body;
1248
- if (c.since) q.since = c.since;
1249
- if (c.before) q.before = c.before;
1250
- if (c.unseen === true) q.seen = false;
1251
- if (c.larger_than_bytes !== void 0) q.larger = c.larger_than_bytes;
1252
- if (c.smaller_than_bytes !== void 0) q.smaller = c.smaller_than_bytes;
1253
- if (c.or !== void 0 && c.or.length > 0) q.or = c.or.map(buildImapSearch);
1254
- if (c.not !== void 0) q.not = buildImapSearch(c.not);
1255
- if (Object.keys(q).length === 0) {
1256
- q.all = true;
1257
- }
1258
- return q;
1259
- }
1260
-
1261
- // src/tools/emails/search-emails.ts
1262
- var Criteria = z5.lazy(
1263
- () => z5.object({
1264
- subject: z5.string().min(1).optional(),
1265
- from: z5.string().min(1).optional(),
1266
- to: z5.string().min(1).optional(),
1267
- body: z5.string().min(1).optional(),
1268
- unseen: z5.boolean().optional(),
1269
- since: z5.coerce.date().optional(),
1270
- before: z5.coerce.date().optional(),
1271
- larger_than_bytes: z5.number().int().positive().optional(),
1272
- smaller_than_bytes: z5.number().int().positive().optional(),
1273
- or: z5.array(Criteria).min(2).optional(),
1274
- not: Criteria.optional()
1275
- })
1276
- );
1277
- var Input4 = z5.object({
1278
- folder: z5.string().min(1).default("INBOX"),
1279
- subject: z5.string().min(1).optional(),
1280
- from: z5.string().min(1).optional(),
1281
- to: z5.string().min(1).optional(),
1282
- body: z5.string().min(1).optional(),
1283
- unseen: z5.boolean().optional(),
1284
- since_date: z5.string().date().optional(),
1285
- before_date: z5.string().date().optional(),
1286
- larger_than_bytes: z5.number().int().positive().optional().describe("Only match messages larger than this many bytes."),
1287
- smaller_than_bytes: z5.number().int().positive().optional().describe("Only match messages smaller than this many bytes."),
1288
- or: z5.array(Criteria).min(2).optional().describe(
1289
- 'Array of >=2 sub-criteria; at least one must match. Combines as AND with top-level fields: `{subject: "X", or: [{from: "a"}, {from: "b"}]}` means `subject=X AND (from=a OR from=b)`.'
1290
- ),
1291
- not: Criteria.optional().describe(
1292
- 'Sub-criteria that must NOT match. Useful for excluding auto-generated mail, e.g. `{not: {from: "noreply"}}`.'
1293
- ),
1294
- limit: z5.number().int().min(1).max(100).default(20),
1295
- max_staleness_seconds: z5.number().int().min(0).default(60),
1296
- response_format: z5.enum(["markdown", "json"]).default("markdown")
1297
- }).refine(
1298
- (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,
1299
- { message: "At least one search criterion must be provided." }
1300
- );
1301
- var searchEmailsTool = defineTool({
1302
- name: "imap_search_emails",
1303
- description: 'Search a folder for messages matching subject/from/to/body text, flag, date window, or size. Supports boolean combinators: `or: [...]` for "any of these match", `not: {...}` for exclusion. Runs IMAP SEARCH on the server (body text search is server-side), then returns cached envelopes for the matching UIDs. Results are newest-first.',
1304
- annotations: {
1305
- readOnlyHint: true,
1306
- destructiveHint: false,
1307
- idempotentHint: true,
1308
- openWorldHint: true
1309
- },
1310
- inputSchema: Input4,
1311
- handler: async (args, ctx) => {
1312
- await syncIfStale(ctx, args.folder, args.max_staleness_seconds);
1313
- const criteria = buildImapSearch({
1314
- ...args.subject !== void 0 && { subject: args.subject },
1315
- ...args.from !== void 0 && { from: args.from },
1316
- ...args.to !== void 0 && { to: args.to },
1317
- ...args.body !== void 0 && { body: args.body },
1318
- ...args.unseen !== void 0 && { unseen: args.unseen },
1319
- ...args.since_date !== void 0 && { since: new Date(args.since_date) },
1320
- ...args.before_date !== void 0 && { before: new Date(args.before_date) },
1321
- ...args.larger_than_bytes !== void 0 && { larger_than_bytes: args.larger_than_bytes },
1322
- ...args.smaller_than_bytes !== void 0 && {
1323
- smaller_than_bytes: args.smaller_than_bytes
1324
- },
1325
- ...args.or !== void 0 && { or: args.or },
1326
- ...args.not !== void 0 && { not: args.not }
1327
- });
1328
- let matchingUids;
1329
- const imap = await ctx.imap.connection();
1330
- const lock = await imap.getMailboxLock(args.folder);
1331
- try {
1332
- const result = await imap.search(criteria, { uid: true });
1333
- matchingUids = Array.isArray(result) ? result : [];
1334
- } catch (err) {
1335
- lock.release();
1336
- throw mapImapError(err);
1337
- }
1338
- lock.release();
1339
- const topUids = [...matchingUids].reverse().slice(0, args.limit);
1340
- const rows = [];
1341
- for (const uid of topUids) {
1342
- const row = getEmail(ctx.db, args.folder, uid);
1343
- if (row) rows.push(row);
1344
- }
1345
- const structured = {
1346
- folder: args.folder,
1347
- total_matches: matchingUids.length,
1348
- returned: rows.length,
1349
- emails: rows.map(projectEmailSummary),
1350
- criteria: {
1351
- subject: args.subject ?? null,
1352
- from: args.from ?? null,
1353
- to: args.to ?? null,
1354
- body: args.body ?? null,
1355
- unseen: args.unseen ?? null,
1356
- since_date: args.since_date ?? null,
1357
- before_date: args.before_date ?? null
1358
- }
1359
- };
1360
- const text2 = args.response_format === "json" ? JSON.stringify(structured, null, 2) : formatEmailListMarkdown(rows);
1361
- return {
1362
- content: [{ type: "text", text: text2 }],
1363
- structuredContent: structured
1364
- };
1365
- }
1366
- });
1367
-
1368
- // src/tools/emails/mark-read.ts
1369
- import { z as z6 } from "zod";
1370
- var Input5 = z6.object({
1371
- folder: z6.string().min(1).describe("Folder containing the message."),
1372
- uid: z6.number().int().positive().describe("IMAP UID of the message. UIDs are folder-scoped.")
1373
- });
1374
- async function updateSeenFlag(ctx, folder, uid, want) {
1375
- const imap = await ctx.imap.connection();
1376
- const lock = await imap.getMailboxLock(folder);
1377
- try {
1378
- if (want === "add") {
1379
- await imap.messageFlagsAdd(String(uid), ["\\Seen"], { uid: true });
1380
- } else {
1381
- await imap.messageFlagsRemove(String(uid), ["\\Seen"], { uid: true });
1382
- }
1383
- } catch (err) {
1384
- throw mapImapError(err);
1385
- } finally {
1386
- lock.release();
1387
- }
1388
- const cached = getEmail(ctx.db, folder, uid);
1389
- if (!cached) return;
1390
- const next = want === "add" ? cached.flags.includes("\\Seen") ? cached.flags : [...cached.flags, "\\Seen"] : cached.flags.filter((f) => f !== "\\Seen");
1391
- if (next !== cached.flags) {
1392
- setEmailFlags(ctx.db, folder, uid, next);
1393
- }
1394
- }
1395
- var markReadTool = defineTool({
1396
- name: "imap_mark_read",
1397
- description: "Mark a message as read by adding the IMAP \\Seen flag. Idempotent - already-read messages are unchanged.",
1398
- annotations: {
1399
- readOnlyHint: false,
1400
- destructiveHint: false,
1401
- idempotentHint: true,
1402
- openWorldHint: true
1403
- },
1404
- inputSchema: Input5,
1405
- handler: async (args, ctx) => {
1406
- await updateSeenFlag(ctx, args.folder, args.uid, "add");
1407
- return {
1408
- content: [
1409
- {
1410
- type: "text",
1411
- text: `Marked UID ${String(args.uid)} in ${args.folder} as read.`
1412
- }
1413
- ],
1414
- structuredContent: { folder: args.folder, uid: args.uid, seen: true }
1415
- };
5
+ // src/utils/suppress-sqlite-warning.ts
6
+ var originalEmitWarning = process.emitWarning.bind(process);
7
+ process.emitWarning = ((...args) => {
8
+ const [warning, typeOrOpts] = args;
9
+ const name = typeof typeOrOpts === "string" ? typeOrOpts : typeOrOpts?.type;
10
+ const text = typeof warning === "string" ? warning : warning?.message ?? "";
11
+ if (name === "ExperimentalWarning" && /SQLite is an experimental feature/i.test(text)) {
12
+ return;
1416
13
  }
14
+ return originalEmitWarning(...args);
1417
15
  });
1418
- var markUnreadTool = defineTool({
1419
- name: "imap_mark_unread",
1420
- description: "Mark a message as unread by removing the IMAP \\Seen flag. Idempotent - already-unread messages are unchanged.",
1421
- annotations: {
1422
- readOnlyHint: false,
1423
- destructiveHint: false,
1424
- idempotentHint: true,
1425
- openWorldHint: true
1426
- },
1427
- inputSchema: Input5,
1428
- handler: async (args, ctx) => {
1429
- await updateSeenFlag(ctx, args.folder, args.uid, "remove");
1430
- return {
1431
- content: [
1432
- {
1433
- type: "text",
1434
- text: `Marked UID ${String(args.uid)} in ${args.folder} as unread.`
1435
- }
1436
- ],
1437
- structuredContent: { folder: args.folder, uid: args.uid, seen: false }
1438
- };
1439
- }
1440
- });
1441
-
1442
- // src/tools/emails/mark-read-multiple.ts
1443
- import { z as z7 } from "zod";
1444
- var Input6 = z7.object({
1445
- folder: z7.string().min(1).describe("Folder containing the messages."),
1446
- uids: z7.array(z7.number().int().positive()).min(1).max(500).describe(
1447
- "UIDs of messages to flip. Max 500 per call - chunk your own list for larger batches."
1448
- )
1449
- });
1450
- async function updateSeenFlagBulk(ctx, folder, uids, want) {
1451
- const imap = await ctx.imap.connection();
1452
- const lock = await imap.getMailboxLock(folder);
1453
- try {
1454
- if (want === "add") {
1455
- await imap.messageFlagsAdd(uids, ["\\Seen"], { uid: true });
1456
- } else {
1457
- await imap.messageFlagsRemove(uids, ["\\Seen"], { uid: true });
1458
- }
1459
- } catch (err) {
1460
- throw mapImapError(err);
1461
- } finally {
1462
- lock.release();
1463
- }
1464
- mutateEmailFlagsForUids(
1465
- ctx.db,
1466
- folder,
1467
- uids,
1468
- (flags) => want === "add" ? flags.includes("\\Seen") ? flags : [...flags, "\\Seen"] : flags.filter((f) => f !== "\\Seen")
1469
- );
16
+ for (const listener of process.listeners("warning")) {
17
+ process.removeListener("warning", listener);
1470
18
  }
1471
- var markReadMultipleTool = defineTool({
1472
- name: "imap_mark_read_multiple",
1473
- description: "Mark multiple messages as read in a single IMAP round-trip. Idempotent - already-read UIDs are unchanged. Use this when you have a concrete list of UIDs (e.g. from a search) instead of calling imap_mark_read N times.",
1474
- annotations: {
1475
- readOnlyHint: false,
1476
- destructiveHint: false,
1477
- idempotentHint: true,
1478
- openWorldHint: true
1479
- },
1480
- inputSchema: Input6,
1481
- handler: async (args, ctx) => {
1482
- await updateSeenFlagBulk(ctx, args.folder, args.uids, "add");
1483
- return {
1484
- content: [
1485
- {
1486
- type: "text",
1487
- text: `Marked ${String(args.uids.length)} message(s) as read in ${args.folder}.`
1488
- }
1489
- ],
1490
- structuredContent: {
1491
- folder: args.folder,
1492
- uids: args.uids,
1493
- count: args.uids.length,
1494
- seen: true
1495
- }
1496
- };
1497
- }
1498
- });
1499
- var markUnreadMultipleTool = defineTool({
1500
- name: "imap_mark_unread_multiple",
1501
- description: "Mark multiple messages as unread in a single IMAP round-trip. Idempotent.",
1502
- annotations: {
1503
- readOnlyHint: false,
1504
- destructiveHint: false,
1505
- idempotentHint: true,
1506
- openWorldHint: true
1507
- },
1508
- inputSchema: Input6,
1509
- handler: async (args, ctx) => {
1510
- await updateSeenFlagBulk(ctx, args.folder, args.uids, "remove");
1511
- return {
1512
- content: [
1513
- {
1514
- type: "text",
1515
- text: `Marked ${String(args.uids.length)} message(s) as unread in ${args.folder}.`
1516
- }
1517
- ],
1518
- structuredContent: {
1519
- folder: args.folder,
1520
- uids: args.uids,
1521
- count: args.uids.length,
1522
- seen: false
1523
- }
1524
- };
1525
- }
1526
- });
1527
-
1528
- // src/tools/emails/move-to-folder.ts
1529
- import { z as z8 } from "zod";
1530
- var Input7 = z8.object({
1531
- folder: z8.string().min(1).describe("Current folder of the message."),
1532
- uid: z8.number().int().positive().describe("IMAP UID of the message to move."),
1533
- destination: z8.string().min(1).describe(
1534
- "Target folder path. Use imap_list_folders to discover valid destinations. Must exist on the server."
1535
- )
1536
- });
1537
- var moveToFolderTool = defineTool({
1538
- name: "imap_move_to_folder",
1539
- description: "Move a message from one folder to another. Uses IMAP MOVE (RFC 6851) when the server supports it, falling back to COPY + EXPUNGE. The cached row in the source folder is removed on success; the destination folder will pick up the moved message on its next sync.",
1540
- annotations: {
1541
- readOnlyHint: false,
1542
- // Destructive: changes where the message lives. Reversible by moving back.
1543
- destructiveHint: true,
1544
- idempotentHint: false,
1545
- openWorldHint: true
1546
- },
1547
- inputSchema: Input7,
1548
- handler: async (args, ctx) => {
1549
- const imap = await ctx.imap.connection();
1550
- const lock = await imap.getMailboxLock(args.folder);
1551
- try {
1552
- const result = await imap.messageMove(String(args.uid), args.destination, {
1553
- uid: true
1554
- });
1555
- if (!result) {
1556
- throw mapImapError(
1557
- new Error(
1558
- `Server rejected the move from ${args.folder} to ${args.destination}. Verify the destination folder exists.`
1559
- )
1560
- );
1561
- }
1562
- } catch (err) {
1563
- throw mapImapError(err);
1564
- } finally {
1565
- lock.release();
1566
- }
1567
- deleteEmail(ctx.db, args.folder, args.uid);
1568
- return {
1569
- content: [
1570
- {
1571
- type: "text",
1572
- text: `Moved UID ${String(args.uid)} from ${args.folder} to ${args.destination}.`
1573
- }
1574
- ],
1575
- structuredContent: {
1576
- folder: args.folder,
1577
- uid: args.uid,
1578
- destination: args.destination
1579
- }
1580
- };
1581
- }
1582
- });
1583
-
1584
- // src/tools/emails/move-multiple.ts
1585
- import { z as z9 } from "zod";
1586
- var Input8 = z9.object({
1587
- folder: z9.string().min(1).describe("Current folder of the messages."),
1588
- uids: z9.array(z9.number().int().positive()).min(1).max(500).describe("UIDs to move. Max 500 per call."),
1589
- destination: z9.string().min(1).describe("Target folder. Must exist on the server.")
1590
- });
1591
- var moveMultipleTool = defineTool({
1592
- name: "imap_move_multiple",
1593
- description: "Move multiple messages to another folder in a single IMAP round-trip. Uses IMAP MOVE when the server supports it, otherwise ImapFlow falls back to COPY + EXPUNGE transparently.",
1594
- annotations: {
1595
- readOnlyHint: false,
1596
- destructiveHint: true,
1597
- idempotentHint: false,
1598
- openWorldHint: true
1599
- },
1600
- inputSchema: Input8,
1601
- handler: async (args, ctx) => {
1602
- const imap = await ctx.imap.connection();
1603
- const lock = await imap.getMailboxLock(args.folder);
1604
- try {
1605
- const ok = await imap.messageMove(args.uids, args.destination, { uid: true });
1606
- if (!ok) {
1607
- throw new ImapError(
1608
- "IMAP_UNKNOWN",
1609
- `Server rejected the move from ${args.folder} to ${args.destination}. Verify the destination folder exists.`
1610
- );
1611
- }
1612
- } catch (err) {
1613
- if (err instanceof ImapError) throw err;
1614
- throw mapImapError(err);
1615
- } finally {
1616
- lock.release();
1617
- }
1618
- deleteEmailsByUids(ctx.db, args.folder, args.uids);
1619
- return {
1620
- content: [
1621
- {
1622
- type: "text",
1623
- text: `Moved ${String(args.uids.length)} message(s) from ${args.folder} to ${args.destination}.`
1624
- }
1625
- ],
1626
- structuredContent: {
1627
- folder: args.folder,
1628
- uids: args.uids,
1629
- count: args.uids.length,
1630
- destination: args.destination
1631
- }
1632
- };
1633
- }
1634
- });
1635
-
1636
- // src/tools/emails/delete-email.ts
1637
- import { z as z10 } from "zod";
1638
- var Input9 = z10.object({
1639
- folder: z10.string().min(1).describe("Folder containing the message to delete."),
1640
- uid: z10.number().int().positive().describe("IMAP UID of the message to delete."),
1641
- hard_delete: z10.boolean().default(false).describe(
1642
- "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."
1643
- )
1644
- });
1645
- var deleteEmailTool = defineTool({
1646
- name: "imap_delete_email",
1647
- description: "Delete a message. Default behavior (`hard_delete=false`) moves the message to the server-side Trash (\\Trash SPECIAL-USE) so the user can recover it. Set `hard_delete=true` to permanently expunge - this cannot be undone.",
1648
- annotations: {
1649
- readOnlyHint: false,
1650
- destructiveHint: true,
1651
- idempotentHint: false,
1652
- openWorldHint: true
1653
- },
1654
- inputSchema: Input9,
1655
- handler: async (args, ctx) => {
1656
- const imap = await ctx.imap.connection();
1657
- if (args.hard_delete) {
1658
- const lock2 = await imap.getMailboxLock(args.folder);
1659
- try {
1660
- await imap.messageDelete(String(args.uid), { uid: true });
1661
- } catch (err) {
1662
- throw mapImapError(err);
1663
- } finally {
1664
- lock2.release();
1665
- }
1666
- deleteEmail(ctx.db, args.folder, args.uid);
1667
- return {
1668
- content: [
1669
- {
1670
- type: "text",
1671
- text: `Permanently deleted UID ${String(args.uid)} from ${args.folder}.`
1672
- }
1673
- ],
1674
- structuredContent: {
1675
- folder: args.folder,
1676
- uid: args.uid,
1677
- action: "hard_delete"
1678
- }
1679
- };
1680
- }
1681
- const trashFolder = await resolveSpecialFolder(ctx, "\\Trash");
1682
- if (trashFolder === args.folder) {
1683
- throw new ImapError(
1684
- "IMAP_UNKNOWN",
1685
- `Message is already in the Trash folder (${args.folder}). Use hard_delete=true to permanently expunge.`
1686
- );
1687
- }
1688
- const lock = await imap.getMailboxLock(args.folder);
1689
- try {
1690
- const ok = await imap.messageMove(String(args.uid), trashFolder, { uid: true });
1691
- if (!ok) {
1692
- throw new ImapError(
1693
- "IMAP_UNKNOWN",
1694
- `Server rejected the move from ${args.folder} to ${trashFolder}.`
1695
- );
1696
- }
1697
- } catch (err) {
1698
- if (err instanceof ImapError) throw err;
1699
- throw mapImapError(err);
1700
- } finally {
1701
- lock.release();
1702
- }
1703
- deleteEmail(ctx.db, args.folder, args.uid);
1704
- return {
1705
- content: [
1706
- {
1707
- type: "text",
1708
- text: `Moved UID ${String(args.uid)} from ${args.folder} to ${trashFolder} (Trash).`
1709
- }
1710
- ],
1711
- structuredContent: {
1712
- folder: args.folder,
1713
- uid: args.uid,
1714
- action: "moved_to_trash",
1715
- trash_folder: trashFolder
1716
- }
1717
- };
1718
- }
1719
- });
1720
-
1721
- // src/tools/emails/delete-multiple.ts
1722
- import { z as z11 } from "zod";
1723
- var Input10 = z11.object({
1724
- folder: z11.string().min(1).describe("Folder containing the messages to delete."),
1725
- uids: z11.array(z11.number().int().positive()).min(1).max(500).describe("UIDs to delete. Max 500 per call."),
1726
- hard_delete: z11.boolean().default(false).describe(
1727
- "When false (default), messages move to the server Trash and can be recovered. When true, they are permanently expunged."
1728
- )
1729
- });
1730
- var deleteMultipleTool = defineTool({
1731
- name: "imap_delete_multiple",
1732
- description: "Delete multiple messages in a single IMAP round-trip. Default soft-deletes (moves to \\Trash); `hard_delete=true` permanently expunges. Mirrors imap_delete_email's per-UID semantics but handles a whole batch at once.",
1733
- annotations: {
1734
- readOnlyHint: false,
1735
- destructiveHint: true,
1736
- idempotentHint: false,
1737
- openWorldHint: true
1738
- },
1739
- inputSchema: Input10,
1740
- handler: async (args, ctx) => {
1741
- const imap = await ctx.imap.connection();
1742
- if (args.hard_delete) {
1743
- const lock2 = await imap.getMailboxLock(args.folder);
1744
- try {
1745
- await imap.messageDelete(args.uids, { uid: true });
1746
- } catch (err) {
1747
- throw mapImapError(err);
1748
- } finally {
1749
- lock2.release();
1750
- }
1751
- deleteEmailsByUids(ctx.db, args.folder, args.uids);
1752
- return {
1753
- content: [
1754
- {
1755
- type: "text",
1756
- text: `Permanently deleted ${String(args.uids.length)} message(s) from ${args.folder}.`
1757
- }
1758
- ],
1759
- structuredContent: {
1760
- folder: args.folder,
1761
- uids: args.uids,
1762
- count: args.uids.length,
1763
- action: "hard_delete"
1764
- }
1765
- };
1766
- }
1767
- const trashFolder = await resolveSpecialFolder(ctx, "\\Trash");
1768
- if (trashFolder === args.folder) {
1769
- throw new ImapError(
1770
- "IMAP_UNKNOWN",
1771
- `Messages are already in the Trash folder (${args.folder}). Use hard_delete=true to permanently expunge.`
1772
- );
1773
- }
1774
- const lock = await imap.getMailboxLock(args.folder);
1775
- try {
1776
- const ok = await imap.messageMove(args.uids, trashFolder, { uid: true });
1777
- if (!ok) {
1778
- throw new ImapError(
1779
- "IMAP_UNKNOWN",
1780
- `Server rejected the move from ${args.folder} to ${trashFolder}.`
1781
- );
1782
- }
1783
- } catch (err) {
1784
- if (err instanceof ImapError) throw err;
1785
- throw mapImapError(err);
1786
- } finally {
1787
- lock.release();
1788
- }
1789
- deleteEmailsByUids(ctx.db, args.folder, args.uids);
1790
- return {
1791
- content: [
1792
- {
1793
- type: "text",
1794
- text: `Moved ${String(args.uids.length)} message(s) from ${args.folder} to ${trashFolder} (Trash).`
1795
- }
1796
- ],
1797
- structuredContent: {
1798
- folder: args.folder,
1799
- uids: args.uids,
1800
- count: args.uids.length,
1801
- action: "moved_to_trash",
1802
- trash_folder: trashFolder
1803
- }
1804
- };
1805
- }
1806
- });
1807
-
1808
- // src/tools/drafts/list-drafts.ts
1809
- import { z as z12 } from "zod";
1810
- var Input11 = z12.object({
1811
- folder: z12.string().min(1).optional().describe(
1812
- "Optional explicit Drafts folder path. If omitted, mcp-inbox auto-detects via RFC 6154 SPECIAL-USE."
1813
- ),
1814
- limit: z12.number().int().min(1).max(100).default(20),
1815
- offset: z12.number().int().min(0).default(0),
1816
- max_staleness_seconds: z12.number().int().min(0).default(60),
1817
- response_format: z12.enum(["markdown", "json"]).default("markdown")
1818
- });
1819
- var listDraftsTool = defineTool({
1820
- name: "imap_list_drafts",
1821
- description: "List drafts from the server-advertised Drafts folder (\\Drafts SPECIAL-USE). Auto-detects the folder path across Gmail ([Gmail]/Drafts), Outlook, Fastmail, and others. Pass an explicit `folder` only if the server does not advertise SPECIAL-USE.",
1822
- annotations: {
1823
- readOnlyHint: true,
1824
- destructiveHint: false,
1825
- idempotentHint: true,
1826
- openWorldHint: true
1827
- },
1828
- inputSchema: Input11,
1829
- handler: async (args, ctx) => {
1830
- const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
1831
- const didSync = await syncIfStale(ctx, folder, args.max_staleness_seconds);
1832
- const { rows, total, hasMore, nextOffset } = readEnvelopes(ctx, folder, {
1833
- limit: args.limit,
1834
- offset: args.offset
1835
- });
1836
- const structured = {
1837
- folder,
1838
- drafts: rows.map(projectEmailSummary),
1839
- total_count: total,
1840
- has_more: hasMore,
1841
- next_offset: nextOffset,
1842
- served_from: didSync ? "sync" : "cache"
1843
- };
1844
- const text2 = args.response_format === "json" ? JSON.stringify(structured, null, 2) : `**Drafts folder:** \`${folder}\`
1845
-
1846
- ${formatEmailListMarkdown(rows)}`;
1847
- return {
1848
- content: [{ type: "text", text: text2 }],
1849
- structuredContent: structured
1850
- };
1851
- }
1852
- });
1853
-
1854
- // src/tools/drafts/get-draft.ts
1855
- import { z as z13 } from "zod";
1856
- var Input12 = z13.object({
1857
- uid: z13.number().int().positive().describe("IMAP UID of the draft in the Drafts folder. Use imap_list_drafts to discover UIDs."),
1858
- folder: z13.string().min(1).optional().describe("Optional explicit Drafts folder path. Auto-detected from SPECIAL-USE when omitted."),
1859
- max_staleness_seconds: z13.number().int().min(0).default(60),
1860
- response_format: z13.enum(["markdown", "json"]).default("markdown")
1861
- });
1862
- var getDraftTool = defineTool({
1863
- name: "imap_get_draft",
1864
- description: "Fetch the full content of a draft (headers, text, HTML, attachment metadata) by UID. Auto-resolves the Drafts folder via RFC 6154 SPECIAL-USE.",
1865
- annotations: {
1866
- readOnlyHint: true,
1867
- destructiveHint: false,
1868
- idempotentHint: true,
1869
- openWorldHint: true
1870
- },
1871
- inputSchema: Input12,
1872
- handler: async (args, ctx) => {
1873
- const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
1874
- const envelope = await ensureEnvelopeCached(ctx, folder, args.uid, args.max_staleness_seconds);
1875
- const body = await ensureBodyCached(ctx, folder, args.uid);
1876
- const structured = {
1877
- ...projectEmailSummary(envelope),
1878
- body_text: body.bodyText,
1879
- body_html: body.bodyHtml
1880
- };
1881
- const text2 = args.response_format === "json" ? JSON.stringify(structured, null, 2) : formatDraftMarkdown(structured);
1882
- return {
1883
- content: [{ type: "text", text: text2 }],
1884
- structuredContent: structured
1885
- };
1886
- }
1887
- });
1888
- function formatDraftMarkdown(d) {
1889
- const lines = [];
1890
- lines.push(`**Subject:** ${d.subject ?? "(no subject)"}`);
1891
- lines.push(`**To:** ${(d.to ?? []).join(", ") || "(not set)"}`);
1892
- if (d.cc && d.cc.length > 0) lines.push(`**Cc:** ${d.cc.join(", ")}`);
1893
- if (d.date) lines.push(`**Last modified:** ${d.date}`);
1894
- lines.push("", "---", "");
1895
- if (d.body_text && d.body_text.trim().length > 0) {
1896
- lines.push(d.body_text.trim());
1897
- } else if (d.body_html) {
1898
- lines.push("_(HTML-only draft; use response_format=json for the HTML.)_");
1899
- } else {
1900
- lines.push("_(empty body)_");
1901
- }
1902
- return lines.join("\n");
1903
- }
1904
-
1905
- // src/tools/drafts/create-draft.ts
1906
- import { z as z14 } from "zod";
1907
-
1908
- // src/imap/mime-builder.ts
1909
- import MailComposer from "nodemailer/lib/mail-composer/index.js";
1910
- async function buildRawMessage(input) {
1911
- const options = {
1912
- from: input.from,
1913
- to: input.to,
1914
- subject: input.subject,
1915
- ...input.cc !== void 0 && { cc: input.cc },
1916
- ...input.bcc !== void 0 && { bcc: input.bcc },
1917
- ...input.text !== void 0 && { text: input.text },
1918
- ...input.html !== void 0 && { html: input.html },
1919
- ...input.inReplyTo !== void 0 && { inReplyTo: input.inReplyTo },
1920
- ...input.references !== void 0 && { references: input.references },
1921
- ...input.headers !== void 0 && { headers: input.headers }
1922
- };
1923
- const composer = new MailComposer(options);
1924
- const message = composer.compile();
1925
- return await message.build();
1926
- }
1927
-
1928
- // src/tools/drafts/create-draft.ts
1929
- var AddressList = z14.union([z14.string().min(1), z14.array(z14.string().min(1)).min(1)]);
1930
- var Input13 = z14.object({
1931
- to: AddressList.describe("Recipient email address or array of addresses."),
1932
- subject: z14.string(),
1933
- body: z14.string().optional().describe("Plain-text body."),
1934
- html: z14.string().optional().describe("HTML body (combined with text via multipart/alternative)."),
1935
- cc: AddressList.optional(),
1936
- bcc: AddressList.optional(),
1937
- from: z14.string().min(1).optional().describe(
1938
- "Sender address. Defaults to IMAP_USER. Some providers reject mismatched From headers."
1939
- ),
1940
- folder: z14.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted.")
1941
- });
1942
- var createDraftTool = defineTool({
1943
- name: "imap_create_draft",
1944
- description: "Create a new draft email in the Drafts folder. The message is built with nodemailer (RFC 2822 compliant; handles non-ASCII subjects, long bodies, multipart) and appended to the folder via IMAP APPEND with the \\Draft flag.",
1945
- annotations: {
1946
- readOnlyHint: false,
1947
- destructiveHint: false,
1948
- idempotentHint: false,
1949
- openWorldHint: true
1950
- },
1951
- inputSchema: Input13,
1952
- handler: async (args, ctx) => {
1953
- const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
1954
- const raw = await buildRawMessage({
1955
- from: args.from ?? ctx.defaults.fromAddress,
1956
- to: args.to,
1957
- subject: args.subject,
1958
- ...args.cc !== void 0 && { cc: args.cc },
1959
- ...args.bcc !== void 0 && { bcc: args.bcc },
1960
- ...args.body !== void 0 && { text: args.body },
1961
- ...args.html !== void 0 && { html: args.html }
1962
- });
1963
- const imap = await ctx.imap.connection();
1964
- let uid;
1965
- try {
1966
- const result = await imap.append(folder, raw, ["\\Draft"]);
1967
- if (!result) {
1968
- throw new ImapError("IMAP_UNKNOWN", `Server did not accept the draft APPEND to ${folder}.`);
1969
- }
1970
- uid = result.uid;
1971
- } catch (err) {
1972
- if (err instanceof ImapError) throw err;
1973
- throw mapImapError(err);
1974
- }
1975
- return {
1976
- content: [
1977
- {
1978
- type: "text",
1979
- text: uid !== void 0 ? `Draft created in ${folder} (UID ${String(uid)}).` : `Draft created in ${folder} (server did not return a UID - call imap_list_drafts to locate it).`
1980
- }
1981
- ],
1982
- structuredContent: {
1983
- folder,
1984
- uid: uid ?? null
1985
- }
1986
- };
1987
- }
1988
- });
1989
-
1990
- // src/tools/drafts/update-draft.ts
1991
- import { z as z15 } from "zod";
1992
- var AddressList2 = z15.union([z15.string().min(1), z15.array(z15.string().min(1)).min(1)]);
1993
- var Input14 = z15.object({
1994
- uid: z15.number().int().positive().describe("UID of the existing draft to replace. Use imap_list_drafts to find it."),
1995
- to: AddressList2,
1996
- subject: z15.string(),
1997
- body: z15.string().optional(),
1998
- html: z15.string().optional(),
1999
- cc: AddressList2.optional(),
2000
- bcc: AddressList2.optional(),
2001
- from: z15.string().min(1).optional(),
2002
- folder: z15.string().min(1).optional()
2003
- });
2004
- var updateDraftTool = defineTool({
2005
- name: "imap_update_draft",
2006
- description: "Replace an existing draft. Implemented as append-then-delete: the new draft is written to the server first, and only on success is the old UID deleted. A failure in the middle leaves the user's draft intact rather than destroying it.",
2007
- annotations: {
2008
- readOnlyHint: false,
2009
- // Replaces user-visible state but never loses it - leaning non-destructive.
2010
- destructiveHint: false,
2011
- idempotentHint: false,
2012
- openWorldHint: true
2013
- },
2014
- inputSchema: Input14,
2015
- handler: async (args, ctx) => {
2016
- const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2017
- const raw = await buildRawMessage({
2018
- from: args.from ?? ctx.defaults.fromAddress,
2019
- to: args.to,
2020
- subject: args.subject,
2021
- ...args.cc !== void 0 && { cc: args.cc },
2022
- ...args.bcc !== void 0 && { bcc: args.bcc },
2023
- ...args.body !== void 0 && { text: args.body },
2024
- ...args.html !== void 0 && { html: args.html }
2025
- });
2026
- const imap = await ctx.imap.connection();
2027
- let newUid;
2028
- try {
2029
- const appended = await imap.append(folder, raw, ["\\Draft"]);
2030
- if (!appended) {
2031
- throw new ImapError(
2032
- "IMAP_UNKNOWN",
2033
- `Server did not accept the new draft APPEND to ${folder}. Old draft untouched.`
2034
- );
2035
- }
2036
- newUid = appended.uid;
2037
- } catch (err) {
2038
- if (err instanceof ImapError) throw err;
2039
- throw mapImapError(err);
2040
- }
2041
- const lock = await imap.getMailboxLock(folder);
2042
- let deletedOld = true;
2043
- try {
2044
- await imap.messageDelete(String(args.uid), { uid: true });
2045
- } catch (err) {
2046
- deletedOld = false;
2047
- return {
2048
- content: [
2049
- {
2050
- type: "text",
2051
- text: `Warning: created new draft UID ${String(newUid ?? "unknown")} in ${folder}, but failed to delete old UID ${String(args.uid)}: ${err instanceof Error ? err.message : String(err)}. Both drafts currently exist; you may want to clean up manually.`
2052
- }
2053
- ],
2054
- structuredContent: {
2055
- folder,
2056
- new_uid: newUid ?? null,
2057
- old_uid: args.uid,
2058
- old_deleted: false
2059
- },
2060
- isError: false
2061
- };
2062
- } finally {
2063
- lock.release();
2064
- }
2065
- if (deletedOld) {
2066
- deleteEmail(ctx.db, folder, args.uid);
2067
- }
2068
- return {
2069
- content: [
2070
- {
2071
- type: "text",
2072
- text: `Replaced draft UID ${String(args.uid)} with new UID ${String(newUid ?? "unknown")} in ${folder}.`
2073
- }
2074
- ],
2075
- structuredContent: {
2076
- folder,
2077
- new_uid: newUid ?? null,
2078
- old_uid: args.uid,
2079
- old_deleted: true
2080
- }
2081
- };
2082
- }
2083
- });
2084
-
2085
- // src/tools/send/send-email.ts
2086
- import { z as z16 } from "zod";
2087
-
2088
- // src/tools/send/shared.ts
2089
- function normalizeAddrs(value) {
2090
- if (value === void 0) return [];
2091
- return Array.isArray(value) ? value : [value];
2092
- }
2093
- async function sendRawAndAppendSent(ctx, raw, envelope) {
2094
- const envelopeTo = [...envelope.to, ...envelope.cc ?? [], ...envelope.bcc ?? []];
2095
- if (envelopeTo.length === 0) {
2096
- throw new ToolInputError("Cannot send: no recipients (to/cc/bcc all empty).");
2097
- }
2098
- const sendInfo = await ctx.smtp.sendRaw(raw, {
2099
- from: envelope.from,
2100
- to: envelopeTo
2101
- });
2102
- let sentFolder = null;
2103
- let sentSaveError = null;
2104
- try {
2105
- sentFolder = await resolveSpecialFolder(ctx, "\\Sent");
2106
- const imap = await ctx.imap.connection();
2107
- await imap.append(sentFolder, raw, ["\\Seen"]);
2108
- } catch (err) {
2109
- sentSaveError = err instanceof Error ? err.message : String(err);
2110
- sentFolder = null;
2111
- }
2112
- return {
2113
- messageId: sendInfo.messageId,
2114
- sentFolder,
2115
- sentSaveError
2116
- };
2117
- }
2118
- function flattenCompose(args) {
2119
- return {
2120
- fromOrDefault: (d) => args.from ?? d,
2121
- to: normalizeAddrs(args.to),
2122
- cc: normalizeAddrs(args.cc),
2123
- bcc: normalizeAddrs(args.bcc)
2124
- };
2125
- }
2126
-
2127
- // src/tools/send/send-email.ts
2128
- var AddressList3 = z16.union([z16.string().min(1), z16.array(z16.string().min(1)).min(1)]);
2129
- var Input15 = z16.object({
2130
- to: AddressList3.describe("Recipient email address or array of addresses."),
2131
- subject: z16.string(),
2132
- body: z16.string().optional().describe("Plain-text body."),
2133
- html: z16.string().optional().describe("HTML body (sent as multipart/alternative with text)."),
2134
- cc: AddressList3.optional(),
2135
- bcc: AddressList3.optional(),
2136
- from: z16.string().min(1).optional().describe(
2137
- "Sender address. Defaults to IMAP_USER. Providers like Gmail and Fastmail reject mismatched From unless the address is a verified alias."
2138
- )
2139
- });
2140
- var sendEmailTool = defineTool({
2141
- name: "imap_send_email",
2142
- 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.",
2143
- annotations: {
2144
- readOnlyHint: false,
2145
- destructiveHint: true,
2146
- idempotentHint: false,
2147
- openWorldHint: true
2148
- },
2149
- inputSchema: Input15,
2150
- handler: async (args, ctx) => {
2151
- const compose = flattenCompose({
2152
- ...args.from !== void 0 && { from: args.from },
2153
- to: args.to,
2154
- ...args.cc !== void 0 && { cc: args.cc },
2155
- ...args.bcc !== void 0 && { bcc: args.bcc }
2156
- });
2157
- const fromAddress = compose.fromOrDefault(ctx.defaults.fromAddress);
2158
- const raw = await buildRawMessage({
2159
- from: fromAddress,
2160
- to: args.to,
2161
- subject: args.subject,
2162
- ...args.cc !== void 0 && { cc: args.cc },
2163
- ...args.bcc !== void 0 && { bcc: args.bcc },
2164
- ...args.body !== void 0 && { text: args.body },
2165
- ...args.html !== void 0 && { html: args.html }
2166
- });
2167
- const envelope = {
2168
- from: fromAddress,
2169
- to: compose.to,
2170
- ...compose.cc.length > 0 && { cc: compose.cc },
2171
- ...compose.bcc.length > 0 && { bcc: compose.bcc }
2172
- };
2173
- const result = await sendRawAndAppendSent(ctx, raw, envelope);
2174
- const summary = [
2175
- `Sent to ${compose.to.join(", ")}${compose.cc.length > 0 ? ` (cc: ${compose.cc.join(", ")})` : ""}.`,
2176
- result.messageId ? `Message-ID: ${result.messageId}` : null,
2177
- result.sentFolder ? `Saved copy to ${result.sentFolder}.` : result.sentSaveError ? `Warning: could not save to Sent folder: ${result.sentSaveError}` : null
2178
- ].filter((l) => l !== null).join(" ");
2179
- return {
2180
- content: [{ type: "text", text: summary }],
2181
- structuredContent: {
2182
- from: fromAddress,
2183
- to: compose.to,
2184
- cc: compose.cc,
2185
- bcc: compose.bcc,
2186
- subject: args.subject,
2187
- message_id: result.messageId,
2188
- sent_folder: result.sentFolder,
2189
- sent_save_error: result.sentSaveError
2190
- }
2191
- };
2192
- }
2193
- });
2194
-
2195
- // src/tools/send/send-draft.ts
2196
- import { z as z17 } from "zod";
2197
- import { simpleParser as simpleParser2 } from "mailparser";
2198
- var Input16 = z17.object({
2199
- uid: z17.number().int().positive().describe("UID of the draft to send."),
2200
- folder: z17.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted.")
2201
- });
2202
- var sendDraftTool = defineTool({
2203
- name: "imap_send_draft",
2204
- description: "Send an existing draft as-is. Fetches the raw RFC 2822 source from the Drafts folder, pushes it through SMTP, appends a copy to the Sent folder, then deletes the draft. Any attachments and non-ASCII content are preserved exactly because the original source is used.",
2205
- annotations: {
2206
- readOnlyHint: false,
2207
- destructiveHint: true,
2208
- idempotentHint: false,
2209
- openWorldHint: true
2210
- },
2211
- inputSchema: Input16,
2212
- handler: async (args, ctx) => {
2213
- const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2214
- const imap = await ctx.imap.connection();
2215
- const lock = await imap.getMailboxLock(folder);
2216
- let rawSource;
2217
- let envelopeFrom;
2218
- let envelopeTo;
2219
- try {
2220
- const msg = await imap.fetchOne(
2221
- String(args.uid),
2222
- { source: true, envelope: true },
2223
- { uid: true }
2224
- );
2225
- if (!msg || msg.source === void 0) {
2226
- throw new ImapError(
2227
- "IMAP_MESSAGE_NOT_FOUND",
2228
- `Draft with UID ${String(args.uid)} not found in ${folder}.`
2229
- );
2230
- }
2231
- rawSource = msg.source;
2232
- const parsed = await simpleParser2(rawSource);
2233
- envelopeFrom = firstAddress(parsed.from) ?? ctx.defaults.fromAddress;
2234
- envelopeTo = [
2235
- ...addressList(parsed.to),
2236
- ...addressList(parsed.cc),
2237
- ...addressList(parsed.bcc)
2238
- ];
2239
- if (envelopeTo.length === 0) {
2240
- throw new ToolInputError(
2241
- `Draft UID ${String(args.uid)} has no recipients. Update the draft before sending.`
2242
- );
2243
- }
2244
- } catch (err) {
2245
- lock.release();
2246
- if (err instanceof ImapError || err instanceof ToolInputError) throw err;
2247
- throw mapImapError(err);
2248
- }
2249
- lock.release();
2250
- const result = await sendRawAndAppendSent(ctx, rawSource, {
2251
- from: envelopeFrom,
2252
- to: envelopeTo
2253
- });
2254
- let draftDeleted = true;
2255
- let draftDeleteError = null;
2256
- const imap2 = await ctx.imap.connection();
2257
- const lock2 = await imap2.getMailboxLock(folder);
2258
- try {
2259
- await imap2.messageDelete(String(args.uid), { uid: true });
2260
- deleteEmail(ctx.db, folder, args.uid);
2261
- } catch (err) {
2262
- draftDeleted = false;
2263
- draftDeleteError = err instanceof Error ? err.message : String(err);
2264
- } finally {
2265
- lock2.release();
2266
- }
2267
- const summary = [
2268
- `Sent draft (UID ${String(args.uid)}) to ${envelopeTo.join(", ")}.`,
2269
- result.messageId ? `Message-ID: ${result.messageId}` : null,
2270
- result.sentFolder ? `Saved to ${result.sentFolder}.` : `Warning: Sent-folder save failed: ${result.sentSaveError ?? "unknown error"}.`,
2271
- draftDeleted ? `Removed draft from ${folder}.` : `Warning: draft still in ${folder}: ${draftDeleteError ?? "unknown error"}.`
2272
- ].filter((l) => l !== null).join(" ");
2273
- return {
2274
- content: [{ type: "text", text: summary }],
2275
- structuredContent: {
2276
- drafts_folder: folder,
2277
- sent_uid: args.uid,
2278
- message_id: result.messageId,
2279
- sent_folder: result.sentFolder,
2280
- sent_save_error: result.sentSaveError,
2281
- draft_deleted: draftDeleted,
2282
- draft_delete_error: draftDeleteError
2283
- }
2284
- };
2285
- }
2286
- });
2287
- function firstAddress(field) {
2288
- if (!field) return null;
2289
- const obj = field;
2290
- const single = Array.isArray(obj) ? obj[0] : obj;
2291
- if (!single) return null;
2292
- if (typeof single.address === "string") return single.address;
2293
- const fromValue = single.value?.[0]?.address;
2294
- return typeof fromValue === "string" ? fromValue : null;
2295
- }
2296
- function addressList(field) {
2297
- if (!field) return [];
2298
- const obj = field;
2299
- const arr = Array.isArray(obj) ? obj : [obj];
2300
- const out = [];
2301
- for (const entry of arr) {
2302
- if (typeof entry.address === "string") {
2303
- out.push(entry.address);
2304
- }
2305
- for (const v of entry.value ?? []) {
2306
- if (typeof v.address === "string") out.push(v.address);
2307
- }
2308
- }
2309
- return Array.from(new Set(out));
2310
- }
2311
-
2312
- // src/tools/send/reply.ts
2313
- import { z as z18 } from "zod";
2314
- var AddressList4 = z18.union([z18.string().min(1), z18.array(z18.string().min(1)).min(1)]);
2315
- var Input17 = z18.object({
2316
- folder: z18.string().min(1).describe("Folder of the original message."),
2317
- uid: z18.number().int().positive().describe("UID of the message being replied to."),
2318
- body: z18.string().optional(),
2319
- html: z18.string().optional(),
2320
- cc: AddressList4.optional(),
2321
- bcc: AddressList4.optional(),
2322
- reply_all: z18.boolean().default(false).describe(
2323
- "When true, CC the original To + Cc recipients (minus the sender). When false, reply only to the original From."
2324
- ),
2325
- from: z18.string().min(1).optional(),
2326
- max_staleness_seconds: z18.number().int().min(0).default(60)
2327
- });
2328
- var replyTool = defineTool({
2329
- name: "imap_reply",
2330
- description: 'Reply to an existing message. Preserves threading headers (In-Reply-To, References) so the reply shows up in the same conversation. Subject gets a "Re: " prefix if not already present. `reply_all` toggles whether to CC the original To+Cc list.',
2331
- annotations: {
2332
- readOnlyHint: false,
2333
- destructiveHint: true,
2334
- idempotentHint: false,
2335
- openWorldHint: true
2336
- },
2337
- inputSchema: Input17,
2338
- handler: async (args, ctx) => {
2339
- const original = await ensureEnvelopeCached(
2340
- ctx,
2341
- args.folder,
2342
- args.uid,
2343
- args.max_staleness_seconds
2344
- );
2345
- const parsedEnvelope = JSON.parse(original.envelopeJson);
2346
- const to = original.fromAddr !== null ? [original.fromAddr] : [];
2347
- const autoCc = args.reply_all ? buildReplyAllCc(parsedEnvelope, ctx.defaults.fromAddress) : [];
2348
- const explicitCc = args.cc !== void 0 ? flattenCompose({ to: "_", cc: args.cc }).cc : [];
2349
- const cc = dedupeAddrs([...autoCc, ...explicitCc], new Set(to));
2350
- const bcc = args.bcc !== void 0 ? flattenCompose({ to: "_", bcc: args.bcc }).bcc : [];
2351
- const from = args.from ?? ctx.defaults.fromAddress;
2352
- const subject = prefixSubject(original.subject ?? "", "Re: ");
2353
- const references = buildReferences(parsedEnvelope);
2354
- const raw = await buildRawMessage({
2355
- from,
2356
- to,
2357
- ...cc.length > 0 && { cc },
2358
- ...bcc.length > 0 && { bcc },
2359
- subject,
2360
- ...args.body !== void 0 && { text: args.body },
2361
- ...args.html !== void 0 && { html: args.html },
2362
- ...parsedEnvelope.messageId !== void 0 && {
2363
- inReplyTo: parsedEnvelope.messageId
2364
- },
2365
- ...references.length > 0 && { references }
2366
- });
2367
- const envelope = {
2368
- from,
2369
- to,
2370
- ...cc.length > 0 && { cc },
2371
- ...bcc.length > 0 && { bcc }
2372
- };
2373
- const result = await sendRawAndAppendSent(ctx, raw, envelope);
2374
- return {
2375
- content: [
2376
- {
2377
- type: "text",
2378
- text: `Replied to "${original.subject ?? "(no subject)"}" (UID ${String(args.uid)}). Sent to ${to.join(", ")}${cc.length > 0 ? `, cc: ${cc.join(", ")}` : ""}.`
2379
- }
2380
- ],
2381
- structuredContent: {
2382
- from,
2383
- to,
2384
- cc,
2385
- bcc,
2386
- subject,
2387
- in_reply_to: parsedEnvelope.messageId ?? null,
2388
- references,
2389
- message_id: result.messageId,
2390
- sent_folder: result.sentFolder,
2391
- sent_save_error: result.sentSaveError
2392
- }
2393
- };
2394
- }
2395
- });
2396
- function buildReplyAllCc(env, excludeSelf) {
2397
- const out = [];
2398
- for (const pool of [env.to ?? [], env.cc ?? []]) {
2399
- for (const entry of pool) {
2400
- if (entry.address && entry.address.toLowerCase() !== excludeSelf.toLowerCase()) {
2401
- out.push(entry.address);
2402
- }
2403
- }
2404
- }
2405
- return out;
2406
- }
2407
- function prefixSubject(subject, prefix) {
2408
- const trimmed = subject.trim();
2409
- return trimmed.toLowerCase().startsWith(prefix.toLowerCase().trim()) ? trimmed : `${prefix}${trimmed}`;
2410
- }
2411
- function buildReferences(env) {
2412
- const refs = [];
2413
- if (env.messageId) refs.push(env.messageId);
2414
- return refs;
2415
- }
2416
- function dedupeAddrs(addrs, exclude) {
2417
- const seen = /* @__PURE__ */ new Set();
2418
- const out = [];
2419
- for (const a of addrs) {
2420
- const key = a.toLowerCase();
2421
- if (seen.has(key) || exclude.has(a) || exclude.has(key)) continue;
2422
- seen.add(key);
2423
- out.push(a);
2424
- }
2425
- return out;
2426
- }
2427
-
2428
- // src/tools/send/forward.ts
2429
- import { z as z19 } from "zod";
2430
- var AddressList5 = z19.union([z19.string().min(1), z19.array(z19.string().min(1)).min(1)]);
2431
- var Input18 = z19.object({
2432
- folder: z19.string().min(1).describe("Folder of the original message."),
2433
- uid: z19.number().int().positive().describe("UID of the message to forward."),
2434
- to: AddressList5.describe("Recipient(s) to forward to."),
2435
- body: z19.string().optional().describe(
2436
- 'Optional prefix body (e.g. "FYI, thought you should see this."). Quoted original follows.'
2437
- ),
2438
- cc: AddressList5.optional(),
2439
- bcc: AddressList5.optional(),
2440
- from: z19.string().min(1).optional(),
2441
- max_staleness_seconds: z19.number().int().min(0).default(60)
2442
- });
2443
- var forwardTool = defineTool({
2444
- name: "imap_forward",
2445
- 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.',
2446
- annotations: {
2447
- readOnlyHint: false,
2448
- destructiveHint: true,
2449
- idempotentHint: false,
2450
- openWorldHint: true
2451
- },
2452
- inputSchema: Input18,
2453
- handler: async (args, ctx) => {
2454
- const original = await ensureEnvelopeCached(
2455
- ctx,
2456
- args.folder,
2457
- args.uid,
2458
- args.max_staleness_seconds
2459
- );
2460
- const body = await ensureBodyCached(ctx, args.folder, args.uid);
2461
- const compose = flattenCompose({
2462
- ...args.from !== void 0 && { from: args.from },
2463
- to: args.to,
2464
- ...args.cc !== void 0 && { cc: args.cc },
2465
- ...args.bcc !== void 0 && { bcc: args.bcc }
2466
- });
2467
- const from = compose.fromOrDefault(ctx.defaults.fromAddress);
2468
- const subject = prefixSubject2(original.subject ?? "", "Fwd: ");
2469
- const originalDate = original.date !== null ? new Date(original.date).toUTCString() : "unknown";
2470
- const originalFrom = original.fromAddr ?? "(unknown sender)";
2471
- const originalTo = (original.toAddrs ?? []).join(", ");
2472
- const quotedHeader = `---------- Forwarded message ----------
2473
- From: ${originalFrom}
2474
- Date: ${originalDate}
2475
- Subject: ${original.subject ?? ""}
2476
- ` + (originalTo ? `To: ${originalTo}
2477
- ` : "") + "\n";
2478
- const forwardedText = (args.body ? `${args.body}
2479
-
2480
- ` : "") + quotedHeader + (body.bodyText ?? "(no text body)");
2481
- const raw = await buildRawMessage({
2482
- from,
2483
- to: args.to,
2484
- ...args.cc !== void 0 && { cc: args.cc },
2485
- ...args.bcc !== void 0 && { bcc: args.bcc },
2486
- subject,
2487
- text: forwardedText,
2488
- ...body.bodyHtml !== null && {
2489
- 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
2490
- }
2491
- });
2492
- const envelope = {
2493
- from,
2494
- to: compose.to,
2495
- ...compose.cc.length > 0 && { cc: compose.cc },
2496
- ...compose.bcc.length > 0 && { bcc: compose.bcc }
2497
- };
2498
- const result = await sendRawAndAppendSent(ctx, raw, envelope);
2499
- return {
2500
- content: [
2501
- {
2502
- type: "text",
2503
- text: `Forwarded "${original.subject ?? "(no subject)"}" to ${compose.to.join(", ")}.`
2504
- }
2505
- ],
2506
- structuredContent: {
2507
- from,
2508
- to: compose.to,
2509
- cc: compose.cc,
2510
- bcc: compose.bcc,
2511
- subject,
2512
- forwarded_from_folder: args.folder,
2513
- forwarded_uid: args.uid,
2514
- message_id: result.messageId,
2515
- sent_folder: result.sentFolder,
2516
- sent_save_error: result.sentSaveError
2517
- }
2518
- };
2519
- }
2520
- });
2521
- function prefixSubject2(subject, prefix) {
2522
- const trimmed = subject.trim();
2523
- return trimmed.toLowerCase().startsWith(prefix.toLowerCase().trim()) ? trimmed : `${prefix}${trimmed}`;
2524
- }
2525
- function escapeHtml(s) {
2526
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2527
- }
2528
-
2529
- // src/tools/attachments/get-attachment.ts
2530
- import { z as z20 } from "zod";
2531
- import { simpleParser as simpleParser3 } from "mailparser";
2532
- var Input19 = z20.object({
2533
- folder: z20.string().min(1).describe("Folder containing the message."),
2534
- uid: z20.number().int().positive().describe("IMAP UID of the message."),
2535
- filename: z20.string().min(1).optional().describe(
2536
- "Filename of the attachment to fetch. First match wins if the message has multiple attachments with the same name - use part_id to disambiguate."
2537
- ),
2538
- part_id: z20.string().min(1).optional().describe('MIME part ID (e.g. "1.2"). Use when multiple parts share a filename.'),
2539
- max_inline_mb: z20.number().int().min(1).max(50).default(5).describe(
2540
- "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."
2541
- )
2542
- }).refine((v) => v.filename !== void 0 || v.part_id !== void 0, {
2543
- message: "Either filename or part_id must be provided."
2544
- });
2545
- var getAttachmentTool = defineTool({
2546
- name: "imap_get_attachment",
2547
- description: 'Download an attachment as base64 bytes, inline in the response. Nothing is written to disk - bytes live in memory for one response and are gone afterward. Meant for ad-hoc "read the content of this attachment" workflows; the cap (max_inline_mb, default 5 MB) prevents runaway response sizes. For just "does this email have an attachment", use imap_get_email - it surfaces filename / content-type / size without any download.',
2548
- annotations: {
2549
- readOnlyHint: true,
2550
- destructiveHint: false,
2551
- idempotentHint: true,
2552
- openWorldHint: true
2553
- },
2554
- inputSchema: Input19,
2555
- handler: async (args, ctx) => {
2556
- const imap = await ctx.imap.connection();
2557
- const lock = await imap.getMailboxLock(args.folder);
2558
- let source;
2559
- let structure;
2560
- try {
2561
- const msg = await imap.fetchOne(
2562
- String(args.uid),
2563
- { source: true, bodyStructure: true },
2564
- { uid: true }
2565
- );
2566
- if (!msg || msg.source === void 0) {
2567
- throw new ImapError(
2568
- "IMAP_MESSAGE_NOT_FOUND",
2569
- `No message with UID ${String(args.uid)} in ${args.folder}.`
2570
- );
2571
- }
2572
- source = msg.source;
2573
- structure = msg.bodyStructure;
2574
- } catch (err) {
2575
- lock.release();
2576
- if (err instanceof ImapError) throw err;
2577
- throw mapImapError(err);
2578
- }
2579
- lock.release();
2580
- const capBytes = args.max_inline_mb * 1024 * 1024;
2581
- if (structure) {
2582
- const selector = {
2583
- ...args.filename !== void 0 && { filename: args.filename },
2584
- ...args.part_id !== void 0 && { part_id: args.part_id }
2585
- };
2586
- const structMatch = findAttachmentPart(structure, selector);
2587
- if (structMatch?.size !== void 0 && structMatch.size > capBytes * 1.5) {
2588
- throw new CacheError(
2589
- "ATTACHMENT_TOO_LARGE",
2590
- `Attachment "${structMatch.filename ?? structMatch.partId}" is ~${String(structMatch.size)} bytes; max_inline_mb=${String(args.max_inline_mb)} allows up to ${String(capBytes)} bytes. Raise max_inline_mb (up to 50) or open in your mail client.`
2591
- );
2592
- }
2593
- }
2594
- const parsed = await simpleParser3(source);
2595
- const attachment = pickAttachment(parsed.attachments ?? [], {
2596
- ...args.filename !== void 0 && { filename: args.filename },
2597
- ...args.part_id !== void 0 && { partId: args.part_id }
2598
- });
2599
- if (!attachment) {
2600
- throw new ImapError(
2601
- "ATTACHMENT_NOT_FOUND",
2602
- args.part_id !== void 0 ? `No attachment at part ${args.part_id} in UID ${String(args.uid)}.` : `No attachment named "${String(args.filename)}" in UID ${String(args.uid)}.`
2603
- );
2604
- }
2605
- const bytes = attachment.content;
2606
- if (bytes.length > capBytes) {
2607
- throw new CacheError(
2608
- "ATTACHMENT_TOO_LARGE",
2609
- `Attachment "${attachment.filename ?? "unnamed"}" is ${String(bytes.length)} bytes after decode; max_inline_mb=${String(args.max_inline_mb)} allows up to ${String(capBytes)} bytes.`
2610
- );
2611
- }
2612
- const filename = attachment.filename ?? args.filename ?? "attachment.bin";
2613
- const contentType = attachment.contentType ?? "application/octet-stream";
2614
- const partId = attachment.partId ?? args.part_id ?? "?";
2615
- return {
2616
- content: [
2617
- {
2618
- type: "text",
2619
- text: `${filename} (${contentType}, ${String(bytes.length)} bytes) - bytes returned inline as base64. Not cached anywhere.`
2620
- }
2621
- ],
2622
- structuredContent: {
2623
- folder: args.folder,
2624
- uid: args.uid,
2625
- part_id: partId,
2626
- filename,
2627
- content_type: contentType,
2628
- size_bytes: bytes.length,
2629
- content_base64: bytes.toString("base64")
2630
- }
2631
- };
19
+ process.on("warning", (w) => {
20
+ if (w.name === "ExperimentalWarning" && /SQLite is an experimental feature/i.test(w.message)) {
21
+ return;
2632
22
  }
23
+ process.stderr.write(`${w.stack ?? w.message}
24
+ `);
2633
25
  });
2634
- function findAttachmentPart(structure, selector) {
2635
- const stack = [structure];
2636
- while (stack.length > 0) {
2637
- const node = stack.pop();
2638
- if (!node) continue;
2639
- if (node.childNodes) {
2640
- for (const child of node.childNodes) stack.push(child);
2641
- continue;
2642
- }
2643
- const partId = node.part;
2644
- if (!partId) continue;
2645
- const nodeFilename = node.dispositionParameters?.filename ?? node.parameters?.name;
2646
- if (selector.part_id !== void 0) {
2647
- if (partId === selector.part_id) {
2648
- return {
2649
- partId,
2650
- filename: nodeFilename,
2651
- contentType: node.type,
2652
- size: node.size
2653
- };
2654
- }
2655
- continue;
2656
- }
2657
- if (selector.filename !== void 0 && nodeFilename === selector.filename) {
2658
- return {
2659
- partId,
2660
- filename: nodeFilename,
2661
- contentType: node.type,
2662
- size: node.size
2663
- };
2664
- }
2665
- }
2666
- return null;
2667
- }
2668
- function pickAttachment(attachments, selector) {
2669
- if (selector.partId !== void 0) {
2670
- const byPart = attachments.find((a) => a.partId === selector.partId);
2671
- if (byPart) return byPart;
2672
- }
2673
- if (selector.filename !== void 0) {
2674
- const byFilename = attachments.find((a) => a.filename === selector.filename);
2675
- if (byFilename) return byFilename;
2676
- }
2677
- return null;
2678
- }
2679
-
2680
- // src/tools/registry.ts
2681
- var tools = [
2682
- // Read
2683
- listFoldersTool,
2684
- listEmailsTool,
2685
- getEmailTool,
2686
- searchEmailsTool,
2687
- listDraftsTool,
2688
- getDraftTool,
2689
- // Write (flag + move + delete)
2690
- markReadTool,
2691
- markUnreadTool,
2692
- moveToFolderTool,
2693
- deleteEmailTool,
2694
- // Bulk variants of the same (one IMAP round-trip for N UIDs)
2695
- markReadMultipleTool,
2696
- markUnreadMultipleTool,
2697
- moveMultipleTool,
2698
- deleteMultipleTool,
2699
- // Drafts (compose)
2700
- createDraftTool,
2701
- updateDraftTool,
2702
- // Send (SMTP)
2703
- sendEmailTool,
2704
- sendDraftTool,
2705
- replyTool,
2706
- forwardTool,
2707
- // Attachments (transient, memory-only)
2708
- getAttachmentTool
2709
- ];
2710
- function findTool(name) {
2711
- return tools.find((t) => t.name === name);
2712
- }
2713
- function listToolEntries() {
2714
- return tools.map((t) => ({
2715
- name: t.name,
2716
- description: t.description,
2717
- // `unrepresentable: 'any'` is needed because some schemas use
2718
- // `z.coerce.date()` (which has no JSON Schema equivalent). With
2719
- // this setting, such types become `{}` (matches anything) in the
2720
- // exposed inputSchema, and the real validation still happens on
2721
- // the Zod side inside the CallTool dispatcher.
2722
- inputSchema: z21.toJSONSchema(t.inputSchema, {
2723
- target: "draft-7",
2724
- unrepresentable: "any"
2725
- }),
2726
- annotations: t.annotations
2727
- }));
2728
- }
2729
-
2730
- // src/server.ts
2731
- var log6 = createLogger("mcp-inbox:server");
2732
- function createMcpServer(ctx) {
2733
- const server = new Server(
2734
- {
2735
- name: "mcp-inbox",
2736
- version: "0.1.0"
2737
- },
2738
- {
2739
- capabilities: {
2740
- tools: {}
2741
- }
2742
- }
2743
- );
2744
- server.setRequestHandler(ListToolsRequestSchema, () => {
2745
- return { tools: listToolEntries() };
2746
- });
2747
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
2748
- const toolName = request.params.name;
2749
- const tool = findTool(toolName);
2750
- if (!tool) {
2751
- log6.warn("unknown tool", { tool: toolName });
2752
- return errorResult(`Unknown tool: ${toolName}`);
2753
- }
2754
- const parsed = tool.inputSchema.safeParse(request.params.arguments ?? {});
2755
- if (!parsed.success) {
2756
- const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
2757
- log6.warn("invalid tool args", { tool: toolName, issues });
2758
- return errorResult(`Invalid arguments for ${toolName}: ${issues}`);
2759
- }
2760
- try {
2761
- return await tool.handler(parsed.data, ctx);
2762
- } catch (err) {
2763
- if (isMcpInboxError(err)) {
2764
- log6.warn("tool returned mcp-inbox error", {
2765
- tool: toolName,
2766
- code: err.code,
2767
- msg: err.userMessage
2768
- });
2769
- return errorResult(err.userMessage);
2770
- }
2771
- log6.error("tool handler threw", {
2772
- tool: toolName,
2773
- msg: err instanceof Error ? err.message : String(err)
2774
- });
2775
- return errorResult(`Internal error in ${toolName}. Check server logs for details.`);
2776
- }
2777
- });
2778
- server.onerror = (err) => {
2779
- const meta = isMcpInboxError(err) ? { code: err.code, msg: err.userMessage } : { msg: err instanceof Error ? err.message : String(err) };
2780
- log6.error("mcp server error", meta);
2781
- };
2782
- return server;
2783
- }
2784
- function errorResult(text2) {
2785
- return {
2786
- isError: true,
2787
- content: [{ type: "text", text: text2 }]
2788
- };
2789
- }
2790
26
 
2791
27
  // src/index.ts
2792
- function loadConfigOrExit() {
2793
- try {
2794
- return loadConfig();
2795
- } catch (err) {
2796
- const message = err instanceof Error ? err.message : String(err);
2797
- process.stderr.write(`${message}
2798
- `);
2799
- process.exit(1);
2800
- }
2801
- }
2802
- try {
2803
- const config = loadConfigOrExit();
2804
- configureLogger({ debug: config.debug, level: "info" });
2805
- rootLogger.info("booting mcp-inbox", {
2806
- imapHost: config.imap.host,
2807
- cacheEnabled: config.cache.enabled,
2808
- cacheDir: config.cache.dir,
2809
- idleEnabled: config.idle.enabled,
2810
- idleFolders: config.idle.folders
2811
- });
2812
- const cache = openCache(join2(config.cache.dir, "cache.db"));
2813
- const imapClient = new ImapClient(config.imap);
2814
- const smtpClient = new SmtpClient(config.smtp);
2815
- const ctx = {
2816
- db: cache.db,
2817
- imap: imapClient,
2818
- smtp: smtpClient,
2819
- cacheConfig: config.cache,
2820
- defaults: {
2821
- fromAddress: config.imap.user
2822
- },
2823
- now: () => Date.now()
2824
- };
2825
- const idleManager = config.idle.enabled && config.idle.folders.length > 0 ? new IdleManager({
2826
- imap: config.imap,
2827
- db: cache.db,
2828
- folders: config.idle.folders
2829
- }) : null;
2830
- if (idleManager) {
2831
- void idleManager.start();
2832
- }
2833
- const server = createMcpServer(ctx);
2834
- const transport = new StdioServerTransport();
2835
- let shuttingDown = false;
2836
- const shutdown = async (signal) => {
2837
- if (shuttingDown) return;
2838
- shuttingDown = true;
2839
- rootLogger.info("shutting down", { signal });
2840
- try {
2841
- await server.close();
2842
- } catch (err) {
2843
- rootLogger.error("error closing MCP server", {
2844
- msg: err instanceof Error ? err.message : String(err)
2845
- });
2846
- }
2847
- try {
2848
- if (idleManager) await idleManager.stop();
2849
- } catch (err) {
2850
- rootLogger.error("error stopping IDLE manager", {
2851
- msg: err instanceof Error ? err.message : String(err)
2852
- });
2853
- }
2854
- try {
2855
- await imapClient.close();
2856
- } catch (err) {
2857
- rootLogger.error("error closing IMAP client", {
2858
- msg: err instanceof Error ? err.message : String(err)
2859
- });
2860
- }
2861
- smtpClient.close();
2862
- cache.close();
2863
- process.exit(0);
2864
- };
2865
- const onSignal = (signal) => {
2866
- shutdown(signal).catch((err) => {
2867
- const msg = err instanceof Error ? err.message : String(err);
2868
- process.stderr.write(`shutdown failed: ${msg}
2869
- `);
2870
- process.exit(1);
2871
- });
2872
- };
2873
- process.on("SIGINT", () => onSignal("SIGINT"));
2874
- process.on("SIGTERM", () => onSignal("SIGTERM"));
2875
- await server.connect(transport);
2876
- rootLogger.info("mcp-inbox ready");
2877
- } catch (err) {
2878
- const top = err instanceof Error ? err.stack ?? err.message : String(err);
2879
- process.stderr.write(`fatal: ${top}
2880
- `);
2881
- let cause = err instanceof Error ? err.cause : void 0;
2882
- let depth = 0;
2883
- while (cause instanceof Error && depth < 5) {
2884
- process.stderr.write(`caused by: ${cause.stack ?? cause.message}
2885
- `);
2886
- cause = cause.cause;
2887
- depth++;
2888
- }
2889
- process.exit(1);
2890
- }
28
+ await import("./app.js");
2891
29
  //# sourceMappingURL=index.js.map