@kbzowski/mcp-inbox 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,24 +79,26 @@ The `mcp-inbox-cache` volume keeps the SQLite cache between runs; without it eve
79
79
 
80
80
  ### Shared server (streamable HTTP)
81
81
 
82
- To connect several clients to one server, run it over HTTP instead of stdio. Set `MCP_HTTP_PORT` and `MCP_AUTH_TOKEN` (16+ characters; required, because this exposes your mailbox). Put both in `.env` and run `docker compose up -d`; `compose.yaml` publishes `127.0.0.1:3000`. Without Docker: `MCP_HTTP_PORT=3000 MCP_AUTH_TOKEN=... npx -y @kbzowski/mcp-inbox`.
82
+ To connect several clients to one server, run it over HTTP instead of stdio. Set `MCP_HTTP_PORT` and `MCP_AUTH_TOKEN` (16+ characters; required, because this exposes your mailbox). Put both in `.env` and run `docker compose up -d`; `compose.yaml` publishes `127.0.0.1:3333`. Without Docker: `MCP_HTTP_PORT=3333 MCP_AUTH_TOKEN=... npx -y @kbzowski/mcp-inbox`.
83
83
 
84
84
  ```json
85
85
  {
86
86
  "mcpServers": {
87
87
  "inbox": {
88
88
  "type": "http",
89
- "url": "http://localhost:3000/mcp",
89
+ "url": "http://localhost:3333/mcp",
90
90
  "headers": { "Authorization": "Bearer your-token" }
91
91
  }
92
92
  }
93
93
  }
94
94
  ```
95
95
 
96
- Claude Code: `claude mcp add --transport http inbox http://localhost:3000/mcp --header "Authorization: Bearer your-token"`. The server is stateless and shares one IMAP connection and cache across clients. There is no TLS; keep it on localhost or put a reverse proxy in front.
96
+ Claude Code: `claude mcp add --transport http inbox http://localhost:3333/mcp --header "Authorization: Bearer your-token"`. The server is stateless and shares one IMAP connection and cache across clients. There is no TLS; keep it on localhost or put a reverse proxy in front.
97
97
 
98
98
  The image is Debian-based on purpose: `sqlite-vec` (semantic search) has no Alpine build. If your embeddings server runs on the host, use `host.docker.internal` instead of `localhost` in `IMAP_EMBEDDINGS_BASE_URL`.
99
99
 
100
+ To run embeddings locally alongside the server, add the Ollama overlay: `docker compose -f compose.yaml -f compose.embeddings.yaml up -d`. It pulls `snowflake-arctic-embed2` (~1.2 GB) on first start and keeps Ollama off the host network, so mail text never leaves the machine. Its settings override any `IMAP_EMBEDDINGS_*` in `.env`, and the model change rebuilds the index.
101
+
100
102
  ### Credentials
101
103
 
102
104
  Gmail, Outlook, Fastmail and iCloud all need an **app password**, not the account password.
package/dist/app.js CHANGED
@@ -1,10 +1,5 @@
1
1
  import { createRequire as __mcpCreateRequire } from 'node:module';
2
2
  globalThis.require = globalThis.require ?? __mcpCreateRequire(import.meta.url);
3
- var __defProp = Object.defineProperty;
4
- var __export = (target, all) => {
5
- for (var name in all)
6
- __defProp(target, name, { get: all[name], enumerable: true });
7
- };
8
3
 
9
4
  // src/app.ts
10
5
  import { join as join2 } from "node:path";
@@ -22,6 +17,56 @@ var LEVEL_WEIGHT = {
22
17
  warn: 30,
23
18
  error: 40
24
19
  };
20
+ var ERROR_FIELDS = [
21
+ "name",
22
+ "message",
23
+ "code",
24
+ "errno",
25
+ "syscall",
26
+ "address",
27
+ "port",
28
+ "responseStatus",
29
+ "responseText",
30
+ "serverResponseCode",
31
+ "executedCommand",
32
+ "authenticationFailed",
33
+ "throttleReset",
34
+ "command",
35
+ "responseCode"
36
+ ];
37
+ var MAX_FIELD_LENGTH = 1e3;
38
+ var MAX_STACK_LENGTH = 4e3;
39
+ var EMAIL_ADDRESS = /[^\s<>"'@]+@[^\s<>"'@]+/g;
40
+ function clean(text2, maxLength = MAX_FIELD_LENGTH) {
41
+ return text2.slice(0, maxLength).replace(EMAIL_ADDRESS, "[address]");
42
+ }
43
+ function serializeError(err) {
44
+ const source = err;
45
+ const out = {};
46
+ for (const field of ERROR_FIELDS) {
47
+ const value = source[field];
48
+ if (typeof value === "string") out[field] = clean(value);
49
+ else if (typeof value === "number" || typeof value === "boolean") out[field] = value;
50
+ }
51
+ if (Array.isArray(source["errors"])) {
52
+ out["errors"] = source["errors"].filter((e) => e instanceof Error);
53
+ }
54
+ if (typeof source["stack"] === "string") out["stack"] = clean(source["stack"], MAX_STACK_LENGTH);
55
+ if (source["cause"] !== void 0) out["cause"] = source["cause"];
56
+ return out;
57
+ }
58
+ function createReplacer() {
59
+ const seen = /* @__PURE__ */ new WeakSet();
60
+ return (key, value) => {
61
+ if (typeof value === "bigint") return value.toString();
62
+ if (!(value instanceof Error) && key !== "err" && key !== "cause") return value;
63
+ if (typeof value === "string") return clean(value);
64
+ if (typeof value !== "object" || value === null) return value;
65
+ if (seen.has(value)) return "[circular]";
66
+ seen.add(value);
67
+ return serializeError(value);
68
+ };
69
+ }
25
70
  var LoggerContext = class {
26
71
  // JS hard-private - consumers of the published package cannot poke at these
27
72
  // from plain JS. TS `private` would be compile-time only.
@@ -37,14 +82,14 @@ var LoggerContext = class {
37
82
  }
38
83
  emit(level, namespace, msg, meta) {
39
84
  if (!this.shouldEmit(level, namespace)) return;
40
- const entry = {
41
- ...meta,
42
- ts: (/* @__PURE__ */ new Date()).toISOString(),
43
- level,
44
- ns: namespace,
45
- msg
46
- };
47
- process.stderr.write(JSON.stringify(entry) + "\n");
85
+ const base = { ts: (/* @__PURE__ */ new Date()).toISOString(), level, ns: namespace, msg };
86
+ let line;
87
+ try {
88
+ line = JSON.stringify({ ...base, ...meta, ...base }, createReplacer());
89
+ } catch (err) {
90
+ line = JSON.stringify({ ...base, logFailure: String(err) });
91
+ }
92
+ process.stderr.write(line + "\n");
48
93
  }
49
94
  logger(namespace) {
50
95
  return {
@@ -113,9 +158,16 @@ function startHttpServer(cfg, makeServer) {
113
158
  try {
114
159
  await server.connect(transport);
115
160
  await transport.handleRequest(req, res, body);
161
+ if (res.statusCode >= 400) {
162
+ log.warn("request rejected", {
163
+ status: res.statusCode,
164
+ userAgent: req.headers["user-agent"],
165
+ protocolVersion: req.headers["mcp-protocol-version"]
166
+ });
167
+ }
116
168
  } catch (err) {
117
169
  log.error("http request failed", {
118
- msg: err instanceof Error ? err.message : String(err)
170
+ err
119
171
  });
120
172
  if (!res.headersSent) reply(500, "Internal error");
121
173
  }
@@ -258,78 +310,6 @@ import { drizzle } from "drizzle-orm/node-sqlite";
258
310
  import { migrate } from "drizzle-orm/node-sqlite/migrator";
259
311
  import * as sqliteVec from "sqlite-vec";
260
312
 
261
- // src/cache/schema.ts
262
- var schema_exports = {};
263
- __export(schema_exports, {
264
- emails: () => emails,
265
- folders: () => folders,
266
- vecIndexState: () => vecIndexState
267
- });
268
- import { sqliteTable, text, integer, primaryKey, index } from "drizzle-orm/sqlite-core";
269
- var folders = sqliteTable("folders", {
270
- /** Full mailbox path as returned by IMAP LIST (e.g. "INBOX", "[Gmail]/Sent Mail"). */
271
- name: text("name").primaryKey(),
272
- /** Delimiter the server uses - usually "." (Dovecot) or "/" (Gmail). */
273
- delimiter: text("delimiter").notNull(),
274
- /** RFC 6154 attribute ("\\Drafts", "\\Sent", etc.) or null. */
275
- specialUse: text("special_use"),
276
- /** UIDVALIDITY from SELECT response. If this changes, wipe the cache. */
277
- uidValidity: integer("uid_validity").notNull(),
278
- /** Next UID the server will assign. Used for new-message detection. */
279
- uidNext: integer("uid_next"),
280
- /** HIGHESTMODSEQ from CONDSTORE. NULL if the server doesn't support it. */
281
- highestModseq: integer("highest_modseq"),
282
- /** Epoch milliseconds of the last successful sync completion. */
283
- lastSyncedAt: integer("last_synced_at").notNull()
284
- });
285
- var emails = sqliteTable(
286
- "emails",
287
- {
288
- folder: text("folder").notNull(),
289
- uid: integer("uid").notNull(),
290
- /** RFC 5322 Message-ID header (with angle brackets). Enables cross-folder dedup. */
291
- messageId: text("message_id"),
292
- subject: text("subject"),
293
- fromAddr: text("from_addr"),
294
- /** JSON array of recipient email strings. */
295
- toAddrs: text("to_addrs", { mode: "json" }).$type(),
296
- ccAddrs: text("cc_addrs", { mode: "json" }).$type(),
297
- /** INTERNALDATE in epoch ms. */
298
- date: integer("date"),
299
- /** JSON array of IMAP flags ("\\Seen", "\\Flagged", etc.). */
300
- flags: text("flags", { mode: "json" }).$type().notNull(),
301
- /** Whether any MIME part is an attachment. Indexed for "has-attachment" filters. */
302
- hasAttachments: integer("has_attachments", { mode: "boolean" }).notNull().default(false),
303
- /** Full parsed envelope as JSON, for detail-view tools. */
304
- envelopeJson: text("envelope_json").notNull(),
305
- /** Plain-text body, nullable - fetched on first read of the message. */
306
- bodyText: text("body_text"),
307
- /** HTML body, nullable. Can be large; keep lazy by default. */
308
- bodyHtml: text("body_html"),
309
- /** Attachment metadata, written with the body in the same fetch. */
310
- attachmentsJson: text("attachments_json", { mode: "json" }).$type(),
311
- /** Per-message MODSEQ (RFC 7162). Used for CONDSTORE incremental sync. */
312
- modseq: integer("modseq"),
313
- /** Epoch ms of envelope cache write. */
314
- cachedAt: integer("cached_at").notNull(),
315
- /** Epoch ms of body cache write (NULL if body not yet fetched). */
316
- bodyCachedAt: integer("body_cached_at")
317
- },
318
- (t) => [
319
- primaryKey({ columns: [t.folder, t.uid] }),
320
- index("idx_emails_date").on(t.folder, t.date),
321
- index("idx_emails_message_id").on(t.messageId)
322
- ]
323
- );
324
- var vecIndexState = sqliteTable("vec_index_state", {
325
- folder: text("folder").primaryKey(),
326
- model: text("model").notNull(),
327
- dims: integer("dims").notNull(),
328
- fromUid: integer("from_uid").notNull(),
329
- toUid: integer("to_uid").notNull(),
330
- indexedAt: integer("indexed_at").notNull()
331
- });
332
-
333
313
  // src/errors/types.ts
334
314
  var McpInboxError = class extends Error {
335
315
  code;
@@ -339,7 +319,6 @@ var McpInboxError = class extends Error {
339
319
  this.name = new.target.name;
340
320
  this.code = code;
341
321
  this.userMessage = userMessage;
342
- Error.captureStackTrace(this, new.target);
343
322
  }
344
323
  };
345
324
  var ImapError = class extends McpInboxError {
@@ -377,7 +356,7 @@ function openCache(path, migrationsFolder) {
377
356
  sqlite.exec("PRAGMA foreign_keys = ON;");
378
357
  sqlite.exec("PRAGMA synchronous = NORMAL;");
379
358
  const vectorsAvailable = loadVectorExtension(sqlite);
380
- const db = drizzle({ client: sqlite, schema: schema_exports });
359
+ const db = drizzle({ client: sqlite });
381
360
  if (migrationsFolder) {
382
361
  try {
383
362
  migrate(db, { migrationsFolder });
@@ -399,7 +378,7 @@ function openCache(path, migrationsFolder) {
399
378
  sqlite.close();
400
379
  } catch (err) {
401
380
  log2.warn("error closing cache db", {
402
- msg: err instanceof Error ? err.message : String(err)
381
+ err
403
382
  });
404
383
  }
405
384
  }
@@ -412,7 +391,7 @@ function loadVectorExtension(sqlite) {
412
391
  return true;
413
392
  } catch (err) {
414
393
  log2.warn("sqlite-vec unavailable - semantic search tools will be disabled", {
415
- msg: err instanceof Error ? err.message : String(err)
394
+ err
416
395
  });
417
396
  return false;
418
397
  } finally {
@@ -441,10 +420,78 @@ function diagnoseOpenError(path, err) {
441
420
  }
442
421
 
443
422
  // src/cache/queries.ts
444
- import { and, asc, desc, eq as eq2, gt, gte, inArray, lt, or as or2, sql as sql2 } from "drizzle-orm";
423
+ import { and, asc, count, desc, eq as eq2, gt, gte, inArray, lt, or as or2, sql as sql2 } from "drizzle-orm";
445
424
 
446
425
  // src/cache/vectors.ts
447
426
  import { eq, ne, or, sql } from "drizzle-orm";
427
+
428
+ // src/cache/schema.ts
429
+ import { sqliteTable, text, integer, primaryKey, index } from "drizzle-orm/sqlite-core";
430
+ var folders = sqliteTable("folders", {
431
+ /** Full mailbox path as returned by IMAP LIST (e.g. "INBOX", "[Gmail]/Sent Mail"). */
432
+ name: text("name").primaryKey(),
433
+ /** Delimiter the server uses - usually "." (Dovecot) or "/" (Gmail). */
434
+ delimiter: text("delimiter").notNull(),
435
+ /** RFC 6154 attribute ("\\Drafts", "\\Sent", etc.) or null. */
436
+ specialUse: text("special_use"),
437
+ /** UIDVALIDITY from SELECT response. If this changes, wipe the cache. */
438
+ uidValidity: integer("uid_validity").notNull(),
439
+ /** Next UID the server will assign. Used for new-message detection. */
440
+ uidNext: integer("uid_next"),
441
+ /** HIGHESTMODSEQ from CONDSTORE. NULL if the server doesn't support it. */
442
+ highestModseq: integer("highest_modseq"),
443
+ /** Epoch milliseconds of the last successful sync completion. */
444
+ lastSyncedAt: integer("last_synced_at").notNull()
445
+ });
446
+ var emails = sqliteTable(
447
+ "emails",
448
+ {
449
+ folder: text("folder").notNull(),
450
+ uid: integer("uid").notNull(),
451
+ /** RFC 5322 Message-ID header (with angle brackets). Enables cross-folder dedup. */
452
+ messageId: text("message_id"),
453
+ subject: text("subject"),
454
+ fromAddr: text("from_addr"),
455
+ /** JSON array of recipient email strings. */
456
+ toAddrs: text("to_addrs", { mode: "json" }).$type(),
457
+ ccAddrs: text("cc_addrs", { mode: "json" }).$type(),
458
+ /** INTERNALDATE in epoch ms. */
459
+ date: integer("date"),
460
+ /** JSON array of IMAP flags ("\\Seen", "\\Flagged", etc.). */
461
+ flags: text("flags", { mode: "json" }).$type().notNull(),
462
+ /** Whether any MIME part is an attachment. Indexed for "has-attachment" filters. */
463
+ hasAttachments: integer("has_attachments", { mode: "boolean" }).notNull().default(false),
464
+ /** Full parsed envelope as JSON, for detail-view tools. */
465
+ envelopeJson: text("envelope_json").notNull(),
466
+ /** Plain-text body, nullable - fetched on first read of the message. */
467
+ bodyText: text("body_text"),
468
+ /** HTML body, nullable. Can be large; keep lazy by default. */
469
+ bodyHtml: text("body_html"),
470
+ /** Attachment metadata, written with the body in the same fetch. */
471
+ attachmentsJson: text("attachments_json", { mode: "json" }).$type(),
472
+ /** Per-message MODSEQ (RFC 7162). Used for CONDSTORE incremental sync. */
473
+ modseq: integer("modseq"),
474
+ /** Epoch ms of envelope cache write. */
475
+ cachedAt: integer("cached_at").notNull(),
476
+ /** Epoch ms of body cache write (NULL if body not yet fetched). */
477
+ bodyCachedAt: integer("body_cached_at")
478
+ },
479
+ (t) => [
480
+ primaryKey({ columns: [t.folder, t.uid] }),
481
+ index("idx_emails_date").on(t.folder, t.date),
482
+ index("idx_emails_message_id").on(t.messageId)
483
+ ]
484
+ );
485
+ var vecIndexState = sqliteTable("vec_index_state", {
486
+ folder: text("folder").primaryKey(),
487
+ model: text("model").notNull(),
488
+ dims: integer("dims").notNull(),
489
+ fromUid: integer("from_uid").notNull(),
490
+ toUid: integer("to_uid").notNull(),
491
+ indexedAt: integer("indexed_at").notNull()
492
+ });
493
+
494
+ // src/cache/vectors.ts
448
495
  var log3 = createLogger("mcp-inbox:vectors");
449
496
  var ENVELOPE_PART = 0;
450
497
  var INDEX_VERSION = "b1";
@@ -520,7 +567,7 @@ function deleteVectorsByFolder(db, folder) {
520
567
  db.run(sql`DELETE FROM vec_emails WHERE folder = ${folder}`);
521
568
  db.update(vecIndexState).set({ fromUid: 0, toUid: 0 }).where(eq(vecIndexState.folder, folder)).run();
522
569
  } catch (err) {
523
- log3.warn("could not drop vectors for folder", { folder, msg: messageOf(err) });
570
+ log3.warn("could not drop vectors for folder", { folder, err });
524
571
  }
525
572
  }
526
573
  function deleteVectorsByUids(db, folder, uids) {
@@ -535,7 +582,7 @@ function deleteVectorsByUids(db, folder, uids) {
535
582
  log3.warn("could not drop vectors for uids", {
536
583
  folder,
537
584
  count: uids.length,
538
- msg: messageOf(err)
585
+ err
539
586
  });
540
587
  }
541
588
  }
@@ -578,7 +625,7 @@ function pruneOrphanedVectors(db, folder) {
578
625
  log3.info("pruned orphaned vectors", { folder, count: orphans.length });
579
626
  return orphans.length;
580
627
  } catch (err) {
581
- log3.warn("could not prune orphaned vectors", { folder, msg: messageOf(err) });
628
+ log3.warn("could not prune orphaned vectors", { folder, err });
582
629
  return 0;
583
630
  }
584
631
  }
@@ -588,9 +635,6 @@ function countVectors(db, folder) {
588
635
  );
589
636
  return row?.c ?? 0;
590
637
  }
591
- function messageOf(err) {
592
- return err instanceof Error ? err.message : String(err);
593
- }
594
638
 
595
639
  // src/cache/queries.ts
596
640
  var log4 = createLogger("mcp-inbox:cache");
@@ -663,7 +707,7 @@ function listEmailsByFolder(db, folder, opts = {}) {
663
707
  }
664
708
  function countEmailsInFolder(db, folder, opts = {}) {
665
709
  const conditions = buildFolderConditions(folder, opts);
666
- const row = db.select({ n: sql2`count(*)` }).from(emails).where(and(...conditions)).get();
710
+ const row = db.select({ n: count() }).from(emails).where(and(...conditions)).get();
667
711
  return row?.n ?? 0;
668
712
  }
669
713
  function listIndexCandidates(db, folder, opts) {
@@ -674,7 +718,7 @@ function listIndexCandidates(db, folder, opts) {
674
718
  }
675
719
  function countEmailsOutsideUidRange(db, folder, fromUid, toUid) {
676
720
  const outside = fromUid === 0 && toUid === 0 ? void 0 : or2(lt(emails.uid, fromUid), gt(emails.uid, toUid));
677
- const row = db.select({ n: sql2`count(*)` }).from(emails).where(
721
+ const row = db.select({ n: count() }).from(emails).where(
678
722
  outside === void 0 ? eq2(emails.folder, folder) : and(eq2(emails.folder, folder), outside)
679
723
  ).get();
680
724
  return row?.n ?? 0;
@@ -741,11 +785,11 @@ function deleteEmailsByUids(db, folder, uids) {
741
785
  deleteVectorsByUids(db, folder, uids);
742
786
  }
743
787
  function pruneBodiesBefore(db, cutoffMs) {
744
- const stale = db.select({ n: sql2`count(*)` }).from(emails).where(lt(emails.bodyCachedAt, cutoffMs)).get();
745
- const count = stale?.n ?? 0;
746
- if (count === 0) return 0;
788
+ const stale = db.select({ n: count() }).from(emails).where(lt(emails.bodyCachedAt, cutoffMs)).get();
789
+ const cleared = stale?.n ?? 0;
790
+ if (cleared === 0) return 0;
747
791
  db.update(emails).set({ bodyText: null, bodyHtml: null, attachmentsJson: null, bodyCachedAt: null }).where(lt(emails.bodyCachedAt, cutoffMs)).run();
748
- return count;
792
+ return cleared;
749
793
  }
750
794
  function getEmailBody(db, folder, uid) {
751
795
  const row = db.select({
@@ -888,7 +932,7 @@ async function createImapConnection(config) {
888
932
  });
889
933
  flow.on("error", (err) => {
890
934
  log5.error("IMAP connection error", {
891
- msg: err instanceof Error ? err.message : String(err)
935
+ err
892
936
  });
893
937
  });
894
938
  try {
@@ -972,7 +1016,7 @@ var ImapClient = class {
972
1016
  await flow.logout();
973
1017
  } catch (err) {
974
1018
  log5.warn("error during IMAP logout", {
975
- msg: err instanceof Error ? err.message : String(err)
1019
+ err
976
1020
  });
977
1021
  }
978
1022
  }
@@ -982,6 +1026,7 @@ var ImapClient = class {
982
1026
  // src/cache/sync.ts
983
1027
  var log6 = createLogger("mcp-inbox:sync");
984
1028
  var ENVELOPE_FLUSH_SIZE = 500;
1029
+ var FETCH_UID_BATCH = 500;
985
1030
  async function syncFolder(ctx, folderPath) {
986
1031
  const started = Date.now();
987
1032
  const lock = await ctx.imap.getMailboxLock(folderPath);
@@ -1054,26 +1099,28 @@ async function runSync(ctx, folderPath, box, cached, uidValidityChanged) {
1054
1099
  }
1055
1100
  async function fetchEnvelopes(ctx, folderPath, uids) {
1056
1101
  const now = Date.now();
1057
- let count = 0;
1058
- const iterator = ctx.imap.fetch(
1059
- uids,
1060
- { envelope: true, flags: true, internalDate: true, bodyStructure: true },
1061
- { uid: true }
1062
- );
1102
+ let count2 = 0;
1063
1103
  const buffer = [];
1064
- for await (const msg of iterator) {
1065
- const insert = messageToInsert(folderPath, msg, now);
1066
- if (insert) {
1067
- buffer.push(insert);
1068
- count++;
1069
- if (buffer.length >= ENVELOPE_FLUSH_SIZE) {
1070
- upsertEmails(ctx.db, buffer);
1071
- buffer.length = 0;
1104
+ for (let i = 0; i < uids.length; i += FETCH_UID_BATCH) {
1105
+ const iterator = ctx.imap.fetch(
1106
+ uids.slice(i, i + FETCH_UID_BATCH),
1107
+ { envelope: true, flags: true, internalDate: true, bodyStructure: true },
1108
+ { uid: true }
1109
+ );
1110
+ for await (const msg of iterator) {
1111
+ const insert = messageToInsert(folderPath, msg, now);
1112
+ if (insert) {
1113
+ buffer.push(insert);
1114
+ count2++;
1115
+ if (buffer.length >= ENVELOPE_FLUSH_SIZE) {
1116
+ upsertEmails(ctx.db, buffer);
1117
+ buffer.length = 0;
1118
+ }
1072
1119
  }
1073
1120
  }
1074
1121
  }
1075
1122
  upsertEmails(ctx.db, buffer);
1076
- return count;
1123
+ return count2;
1077
1124
  }
1078
1125
  async function refreshFlags(ctx, folderPath, cachedModseq) {
1079
1126
  const options = cachedModseq !== null ? { uid: true, changedSince: BigInt(cachedModseq) } : { uid: true };
@@ -1135,7 +1182,7 @@ var IdleManager = class {
1135
1182
  } catch (err) {
1136
1183
  log7.error("failed to open IDLE for folder", {
1137
1184
  folder,
1138
- msg: err instanceof Error ? err.message : String(err)
1185
+ err
1139
1186
  });
1140
1187
  }
1141
1188
  }
@@ -1186,7 +1233,7 @@ var IdleManager = class {
1186
1233
  } catch (err) {
1187
1234
  log7.warn("error closing IDLE connection", {
1188
1235
  folder,
1189
- msg: err instanceof Error ? err.message : String(err)
1236
+ err
1190
1237
  });
1191
1238
  }
1192
1239
  }
@@ -1198,7 +1245,7 @@ var IdleManager = class {
1198
1245
  } catch (err) {
1199
1246
  log7.error("exists sync failed", {
1200
1247
  folder,
1201
- msg: err instanceof Error ? err.message : String(err)
1248
+ err
1202
1249
  });
1203
1250
  }
1204
1251
  }
@@ -1208,7 +1255,7 @@ var IdleManager = class {
1208
1255
  } catch (err) {
1209
1256
  log7.error("resync failed", {
1210
1257
  folder,
1211
- msg: err instanceof Error ? err.message : String(err)
1258
+ err
1212
1259
  });
1213
1260
  }
1214
1261
  }
@@ -1305,7 +1352,8 @@ async function postWithRetry(batch, cfg) {
1305
1352
  `The embeddings endpoint at ${cfg.baseUrl} rejected the credentials (HTTP ${response.status}). Check IMAP_EMBEDDINGS_API_KEY.`
1306
1353
  );
1307
1354
  }
1308
- lastError = new Error(`HTTP ${response.status}: ${(await safeText(response)).slice(0, 200)}`);
1355
+ await response.body?.cancel();
1356
+ lastError = new Error(`HTTP ${response.status}`);
1309
1357
  if (!isRetryable(response.status) || attempt === MAX_ATTEMPTS) break;
1310
1358
  log8.debug("embeddings request failed, retrying", { status: response.status, attempt });
1311
1359
  await sleep(retryAfterMs(response) ?? backoffMs(attempt));
@@ -1329,13 +1377,6 @@ function retryAfterMs(response) {
1329
1377
  function backoffMs(attempt) {
1330
1378
  return BASE_BACKOFF_MS * 2 ** (attempt - 1) + Math.random() * 250;
1331
1379
  }
1332
- async function safeText(response) {
1333
- try {
1334
- return await response.text();
1335
- } catch {
1336
- return "";
1337
- }
1338
- }
1339
1380
  function sleep(ms) {
1340
1381
  return new Promise((resolve) => setTimeout(resolve, ms));
1341
1382
  }
@@ -1605,7 +1646,7 @@ async function fetchTextBodies(imap, uids) {
1605
1646
  log10.warn("body part fetch failed for a part group", {
1606
1647
  part: partId,
1607
1648
  uids: groupUids.length,
1608
- msg: err instanceof Error ? err.message : String(err)
1649
+ err
1609
1650
  });
1610
1651
  }
1611
1652
  }
@@ -1624,7 +1665,7 @@ function bodyFetcherFor(client, folder) {
1624
1665
  } catch (err) {
1625
1666
  log10.warn("could not fetch body text", {
1626
1667
  folder,
1627
- msg: err instanceof Error ? err.message : String(err)
1668
+ err
1628
1669
  });
1629
1670
  return { texts: /* @__PURE__ */ new Map(), expected: 0 };
1630
1671
  }
@@ -1717,12 +1758,12 @@ var IndexSweeper = class {
1717
1758
  } catch (err) {
1718
1759
  log11.warn("sweep failed for folder", {
1719
1760
  folder,
1720
- msg: err instanceof Error ? err.message : String(err)
1761
+ err
1721
1762
  });
1722
1763
  }
1723
1764
  }
1724
1765
  } catch (err) {
1725
- log11.warn("sweep aborted", { msg: err instanceof Error ? err.message : String(err) });
1766
+ log11.warn("sweep aborted", { err });
1726
1767
  } finally {
1727
1768
  this.#running = false;
1728
1769
  }
@@ -1804,7 +1845,7 @@ import {
1804
1845
  // package.json
1805
1846
  var package_default = {
1806
1847
  name: "@kbzowski/mcp-inbox",
1807
- version: "0.6.0",
1848
+ version: "0.6.1",
1808
1849
  description: "MCP server exposing IMAP/SMTP email over a fast local cache. Read, search, compose, and manage email from any IMAP provider with near-instant response times via background sync and IDLE push.",
1809
1850
  type: "module",
1810
1851
  main: "./dist/index.js",
@@ -1869,10 +1910,10 @@ var package_default = {
1869
1910
  },
1870
1911
  dependencies: {
1871
1912
  "@modelcontextprotocol/sdk": "^1.32.2",
1872
- "drizzle-orm": "1.0.0-beta.22",
1873
- imapflow: "^2.10.0",
1874
- mailparser: "^3.14.1",
1875
- nodemailer: "^10.3.1",
1913
+ "drizzle-orm": "1.0.0-rc.6",
1914
+ imapflow: "^2.12.2",
1915
+ mailparser: "^3.15.0",
1916
+ nodemailer: "^10.6.1",
1876
1917
  "sqlite-vec": "0.1.9",
1877
1918
  zod: "^4.6.7"
1878
1919
  },
@@ -1880,16 +1921,16 @@ var package_default = {
1880
1921
  "@changesets/cli": "^3.0.3",
1881
1922
  "@types/mailparser": "^3.9.0",
1882
1923
  "@types/node": "^26.6.6",
1883
- "drizzle-kit": "1.0.0-beta.22",
1924
+ "drizzle-kit": "1.0.0-rc.6",
1884
1925
  esbuild: "^0.28.2",
1885
1926
  lefthook: "^2.2.2",
1886
- oxfmt: "^0.75.0",
1887
- oxlint: "^1.90.0",
1888
- "oxlint-tsgolint": "^7.0.2005",
1889
- testcontainers: "^12.2.1",
1927
+ oxfmt: "^0.79.0",
1928
+ oxlint: "^1.94.0",
1929
+ "oxlint-tsgolint": "^7.0.2008",
1930
+ testcontainers: "^12.2.2",
1890
1931
  tsx: "^4.23.15",
1891
1932
  typescript: "^7.0.2",
1892
- vitest: "^5.0.5"
1933
+ vitest: "^5.1.1"
1893
1934
  }
1894
1935
  };
1895
1936
 
@@ -2052,6 +2093,11 @@ var NAME_CANDIDATES = {
2052
2093
  };
2053
2094
 
2054
2095
  // src/tools/emails/shared.ts
2096
+ async function deleteOrThrow(imap, folder, uids) {
2097
+ if (!await imap.messageDelete(uids, { uid: true })) {
2098
+ throw new ImapError("IMAP_UNKNOWN", `Server did not delete the message(s) from ${folder}.`);
2099
+ }
2100
+ }
2055
2101
  async function syncIfStale(ctx, folder, maxStalenessSec = ctx.cacheConfig.defaultStalenessSec) {
2056
2102
  const cached = getFolder(ctx.db, folder);
2057
2103
  const ageMs = cached ? ctx.now() - cached.lastSyncedAt : Infinity;
@@ -3026,7 +3072,7 @@ var deleteEmailTool = defineTool({
3026
3072
  if (args.hard_delete) {
3027
3073
  const lock2 = await imap.getMailboxLock(args.folder);
3028
3074
  try {
3029
- await imap.messageDelete(String(args.uid), { uid: true });
3075
+ await deleteOrThrow(imap, args.folder, String(args.uid));
3030
3076
  } catch (err) {
3031
3077
  throw mapImapError(err);
3032
3078
  } finally {
@@ -3111,7 +3157,7 @@ var deleteMultipleTool = defineTool({
3111
3157
  if (args.hard_delete) {
3112
3158
  const lock2 = await imap.getMailboxLock(args.folder);
3113
3159
  try {
3114
- await imap.messageDelete(args.uids, { uid: true });
3160
+ await deleteOrThrow(imap, args.folder, args.uids);
3115
3161
  } catch (err) {
3116
3162
  throw mapImapError(err);
3117
3163
  } finally {
@@ -3385,6 +3431,7 @@ var createDraftTool = defineTool({
3385
3431
 
3386
3432
  // src/tools/drafts/update-draft.ts
3387
3433
  import { z as z20 } from "zod";
3434
+ var log13 = createLogger("mcp-inbox:drafts");
3388
3435
  var Input17 = z20.object({
3389
3436
  uid: z20.number().int().positive().describe("UID of the existing draft to replace. Use imap_list_drafts to find it."),
3390
3437
  to: AddressList,
@@ -3439,8 +3486,13 @@ var updateDraftTool = defineTool({
3439
3486
  const lock = await imap.getMailboxLock(folder);
3440
3487
  let deletedOld = true;
3441
3488
  try {
3442
- await imap.messageDelete(String(args.uid), { uid: true });
3489
+ await deleteOrThrow(imap, folder, String(args.uid));
3443
3490
  } catch (err) {
3491
+ log13.warn("new draft saved, but deleting the old one failed", {
3492
+ folder,
3493
+ uid: args.uid,
3494
+ err
3495
+ });
3444
3496
  deletedOld = false;
3445
3497
  return {
3446
3498
  content: [
@@ -3484,6 +3536,7 @@ var updateDraftTool = defineTool({
3484
3536
  import { z as z21 } from "zod";
3485
3537
 
3486
3538
  // src/tools/send/shared.ts
3539
+ var log14 = createLogger("mcp-inbox:send");
3487
3540
  function normalizeAddrs(value) {
3488
3541
  if (value === void 0) return [];
3489
3542
  return Array.isArray(value) ? value : [value];
@@ -3504,6 +3557,7 @@ async function sendRawAndAppendSent(ctx, raw, envelope) {
3504
3557
  const imap = await ctx.imap.connection();
3505
3558
  await imap.append(sentFolder, raw, ["\\Seen"]);
3506
3559
  } catch (err) {
3560
+ log14.warn("sent, but saving the copy failed", { folder: sentFolder, err });
3507
3561
  sentSaveError = err instanceof Error ? err.message : String(err);
3508
3562
  sentFolder = null;
3509
3563
  }
@@ -3595,6 +3649,7 @@ var sendEmailTool = defineTool({
3595
3649
  // src/tools/send/send-draft.ts
3596
3650
  import { z as z22 } from "zod";
3597
3651
  import { simpleParser as simpleParser2 } from "mailparser";
3652
+ var log15 = createLogger("mcp-inbox:send");
3598
3653
  var Input19 = z22.object({
3599
3654
  uid: z22.number().int().positive().describe("UID of the draft to send."),
3600
3655
  folder: z22.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted.")
@@ -3656,9 +3711,10 @@ var sendDraftTool = defineTool({
3656
3711
  const imap2 = await ctx.imap.connection();
3657
3712
  const lock2 = await imap2.getMailboxLock(folder);
3658
3713
  try {
3659
- await imap2.messageDelete(String(args.uid), { uid: true });
3714
+ await deleteOrThrow(imap2, folder, String(args.uid));
3660
3715
  deleteEmail(ctx.db, folder, args.uid);
3661
3716
  } catch (err) {
3717
+ log15.warn("sent, but deleting the draft failed", { folder, uid: args.uid, err });
3662
3718
  draftDeleted = false;
3663
3719
  draftDeleteError = err instanceof Error ? err.message : String(err);
3664
3720
  } finally {
@@ -3709,6 +3765,7 @@ function addressList(field) {
3709
3765
 
3710
3766
  // src/tools/send/reply.ts
3711
3767
  import { z as z23 } from "zod";
3768
+ var log16 = createLogger("mcp-inbox:send");
3712
3769
  var Input20 = z23.object({
3713
3770
  folder: z23.string().min(1).describe("Folder of the original message."),
3714
3771
  uid: z23.number().int().positive().describe("UID of the message being replied to."),
@@ -3790,6 +3847,11 @@ var replyTool = defineTool({
3790
3847
  markAnsweredError = `Server did not apply \\Answered to UID ${String(args.uid)} in ${args.folder}.`;
3791
3848
  }
3792
3849
  } catch (err) {
3850
+ log16.warn("replied, but setting \\Answered failed", {
3851
+ folder: args.folder,
3852
+ uid: args.uid,
3853
+ err
3854
+ });
3793
3855
  markAnsweredError = err instanceof Error ? err.message : String(err);
3794
3856
  }
3795
3857
  }
@@ -4177,7 +4239,7 @@ function listToolEntries() {
4177
4239
  }
4178
4240
 
4179
4241
  // src/server.ts
4180
- var log13 = createLogger("mcp-inbox:server");
4242
+ var log17 = createLogger("mcp-inbox:server");
4181
4243
  function createMcpServer(ctx) {
4182
4244
  const server = new Server(
4183
4245
  {
@@ -4197,39 +4259,42 @@ function createMcpServer(ctx) {
4197
4259
  const toolName = request.params.name;
4198
4260
  const tool = findTool(toolName);
4199
4261
  if (!tool) {
4200
- log13.warn("unknown tool", { tool: toolName });
4262
+ log17.warn("unknown tool", { tool: toolName });
4201
4263
  return errorResult(`Unknown tool: ${toolName}`);
4202
4264
  }
4203
4265
  const parsed = tool.inputSchema.safeParse(request.params.arguments ?? {});
4204
4266
  if (!parsed.success) {
4205
4267
  const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
4206
- log13.warn("invalid tool args", { tool: toolName, issues });
4268
+ log17.warn("invalid tool args", { tool: toolName, issues });
4207
4269
  return errorResult(`Invalid arguments for ${toolName}: ${issues}`);
4208
4270
  }
4271
+ const started = Date.now();
4209
4272
  try {
4210
4273
  return await tool.handler(parsed.data, ctx);
4211
4274
  } catch (err) {
4275
+ const meta = {
4276
+ tool: toolName,
4277
+ durationMs: Date.now() - started,
4278
+ ...failureContext(parsed.data),
4279
+ err
4280
+ };
4212
4281
  if (isMcpInboxError(err)) {
4213
- log13.warn("tool returned mcp-inbox error", {
4214
- tool: toolName,
4215
- code: err.code,
4216
- msg: err.userMessage
4217
- });
4282
+ log17.warn("tool returned mcp-inbox error", meta);
4218
4283
  return errorResult(err.userMessage);
4219
4284
  }
4220
- log13.error("tool handler threw", {
4221
- tool: toolName,
4222
- msg: err instanceof Error ? err.message : String(err)
4223
- });
4285
+ log17.error("tool handler threw", meta);
4224
4286
  return errorResult(`Internal error in ${toolName}. Check server logs for details.`);
4225
4287
  }
4226
4288
  });
4227
4289
  server.onerror = (err) => {
4228
- const meta = isMcpInboxError(err) ? { code: err.code, msg: err.userMessage } : { msg: err instanceof Error ? err.message : String(err) };
4229
- log13.error("mcp server error", meta);
4290
+ log17.error("mcp server error", { err });
4230
4291
  };
4231
4292
  return server;
4232
4293
  }
4294
+ function failureContext(args) {
4295
+ const { folder, uid, uids, destination } = args;
4296
+ return { folder, uid, uidCount: Array.isArray(uids) ? uids.length : void 0, destination };
4297
+ }
4233
4298
  function errorResult(text2) {
4234
4299
  return {
4235
4300
  isError: true,
@@ -4312,7 +4377,7 @@ try {
4312
4377
  await server.close();
4313
4378
  } catch (err) {
4314
4379
  rootLogger.error("error closing MCP server", {
4315
- msg: err instanceof Error ? err.message : String(err)
4380
+ err
4316
4381
  });
4317
4382
  }
4318
4383
  sweeper?.stop();
@@ -4320,14 +4385,14 @@ try {
4320
4385
  if (idleManager) await idleManager.stop();
4321
4386
  } catch (err) {
4322
4387
  rootLogger.error("error stopping IDLE manager", {
4323
- msg: err instanceof Error ? err.message : String(err)
4388
+ err
4324
4389
  });
4325
4390
  }
4326
4391
  try {
4327
4392
  await imapClient.close();
4328
4393
  } catch (err) {
4329
4394
  rootLogger.error("error closing IMAP client", {
4330
- msg: err instanceof Error ? err.message : String(err)
4395
+ err
4331
4396
  });
4332
4397
  }
4333
4398
  smtpClient.close();
@@ -4336,9 +4401,7 @@ try {
4336
4401
  };
4337
4402
  const onSignal = (signal) => {
4338
4403
  shutdown(signal).catch((err) => {
4339
- const msg = err instanceof Error ? err.message : String(err);
4340
- process.stderr.write(`shutdown failed: ${msg}
4341
- `);
4404
+ rootLogger.error("shutdown failed", { err });
4342
4405
  process.exit(1);
4343
4406
  });
4344
4407
  };
@@ -1,5 +1,4 @@
1
1
  import { drizzle } from 'drizzle-orm/node-sqlite';
2
- import * as schema from './schema';
3
2
  /**
4
3
  * Default migrations folder resolved relative to this module.
5
4
  *
@@ -8,7 +7,7 @@ import * as schema from './schema';
8
7
  * copies the migrations there so the shipped tarball is self-contained)
9
8
  */
10
9
  export declare const DEFAULT_MIGRATIONS_FOLDER: string;
11
- export type CacheDb = ReturnType<typeof drizzle<typeof schema>>;
10
+ export type CacheDb = ReturnType<typeof drizzle>;
12
11
  export interface CacheHandle {
13
12
  db: CacheDb;
14
13
  /**
@@ -132,6 +132,7 @@ export declare const folders: import("drizzle-orm/sqlite-core").SQLiteTableWithC
132
132
  }, {}>;
133
133
  };
134
134
  dialect: 'sqlite';
135
+ isAlias: false;
135
136
  }>;
136
137
  /** Metadata only - attachment bytes are never persisted. */
137
138
  export interface AttachmentInfo {
@@ -422,6 +423,7 @@ export declare const emails: import("drizzle-orm/sqlite-core").SQLiteTableWithCo
422
423
  }, {}>;
423
424
  };
424
425
  dialect: 'sqlite';
426
+ isAlias: false;
425
427
  }>;
426
428
  /**
427
429
  * Which folders are opted in to semantic search, and how much of each is
@@ -535,6 +537,7 @@ export declare const vecIndexState: import("drizzle-orm/sqlite-core").SQLiteTabl
535
537
  }, {}>;
536
538
  };
537
539
  dialect: 'sqlite';
540
+ isAlias: false;
538
541
  }>;
539
542
  export type Folder = typeof folders.$inferSelect;
540
543
  export type FolderInsert = typeof folders.$inferInsert;
@@ -1,8 +1,15 @@
1
+ import type { ImapFlow } from 'imapflow';
1
2
  import type { ToolContext } from '../define-tool';
2
3
  import type { EmbeddingsConfig } from '../../config/env';
3
4
  import { type ListEmailsOptions } from '../../cache/queries';
4
5
  import type { AttachmentInfo, Email } from '../../cache/schema';
5
6
  import { type SpecialUseAttr } from '../../imap/folders';
7
+ /**
8
+ * ImapFlow's `messageDelete` reports a server refusal by returning false, not
9
+ * by throwing, so a bare await reads a failed delete as a success. The caller
10
+ * must hold the mailbox lock.
11
+ */
12
+ export declare function deleteOrThrow(imap: Pick<ImapFlow, 'messageDelete'>, folder: string, uids: string | number[]): Promise<void>;
6
13
  /**
7
14
  * Sync a folder if its cache is older than `maxStalenessSec`, which falls
8
15
  * back to IMAP_CACHE_DEFAULT_STALENESS_SEC when the caller omits it.
@@ -14,11 +14,14 @@
14
14
  * contexts to avoid cross-test leakage.
15
15
  */
16
16
  type Level = 'debug' | 'info' | 'warn' | 'error';
17
+ type Meta = Record<string, unknown> & {
18
+ msg?: never;
19
+ };
17
20
  export interface Logger {
18
- debug: (msg: string, meta?: Record<string, unknown>) => void;
19
- info: (msg: string, meta?: Record<string, unknown>) => void;
20
- warn: (msg: string, meta?: Record<string, unknown>) => void;
21
- error: (msg: string, meta?: Record<string, unknown>) => void;
21
+ debug: (msg: string, meta?: Meta) => void;
22
+ info: (msg: string, meta?: Meta) => void;
23
+ warn: (msg: string, meta?: Meta) => void;
24
+ error: (msg: string, meta?: Meta) => void;
22
25
  child: (subNamespace: string) => Logger;
23
26
  }
24
27
  export declare class LoggerContext {
@@ -28,7 +31,7 @@ export declare class LoggerContext {
28
31
  level?: Level;
29
32
  }): void;
30
33
  shouldEmit(level: Level, namespace: string): boolean;
31
- emit(level: Level, namespace: string, msg: string, meta?: Record<string, unknown>): void;
34
+ emit(level: Level, namespace: string, msg: string, meta?: Meta): void;
32
35
  logger(namespace: string): Logger;
33
36
  }
34
37
  export declare function configureLogger(opts: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kbzowski/mcp-inbox",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "MCP server exposing IMAP/SMTP email over a fast local cache. Read, search, compose, and manage email from any IMAP provider with near-instant response times via background sync and IDLE push.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -65,10 +65,10 @@
65
65
  },
66
66
  "dependencies": {
67
67
  "@modelcontextprotocol/sdk": "^1.32.2",
68
- "drizzle-orm": "1.0.0-beta.22",
69
- "imapflow": "^2.10.0",
70
- "mailparser": "^3.14.1",
71
- "nodemailer": "^10.3.1",
68
+ "drizzle-orm": "1.0.0-rc.6",
69
+ "imapflow": "^2.12.2",
70
+ "mailparser": "^3.15.0",
71
+ "nodemailer": "^10.6.1",
72
72
  "sqlite-vec": "0.1.9",
73
73
  "zod": "^4.6.7"
74
74
  },
@@ -76,15 +76,15 @@
76
76
  "@changesets/cli": "^3.0.3",
77
77
  "@types/mailparser": "^3.9.0",
78
78
  "@types/node": "^26.6.6",
79
- "drizzle-kit": "1.0.0-beta.22",
79
+ "drizzle-kit": "1.0.0-rc.6",
80
80
  "esbuild": "^0.28.2",
81
81
  "lefthook": "^2.2.2",
82
- "oxfmt": "^0.75.0",
83
- "oxlint": "^1.90.0",
84
- "oxlint-tsgolint": "^7.0.2005",
85
- "testcontainers": "^12.2.1",
82
+ "oxfmt": "^0.79.0",
83
+ "oxlint": "^1.94.0",
84
+ "oxlint-tsgolint": "^7.0.2008",
85
+ "testcontainers": "^12.2.2",
86
86
  "tsx": "^4.23.15",
87
87
  "typescript": "^7.0.2",
88
- "vitest": "^5.0.5"
88
+ "vitest": "^5.1.1"
89
89
  }
90
90
  }