@kbzowski/mcp-inbox 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.js CHANGED
@@ -10,6 +10,127 @@ var __export = (target, all) => {
10
10
  import { join as join2 } from "node:path";
11
11
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12
12
 
13
+ // src/http.ts
14
+ import { createServer } from "node:http";
15
+ import { timingSafeEqual } from "node:crypto";
16
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
17
+
18
+ // src/utils/logger.ts
19
+ var LEVEL_WEIGHT = {
20
+ debug: 10,
21
+ info: 20,
22
+ warn: 30,
23
+ error: 40
24
+ };
25
+ var LoggerContext = class {
26
+ // JS hard-private - consumers of the published package cannot poke at these
27
+ // from plain JS. TS `private` would be compile-time only.
28
+ #enabledNamespaces = [];
29
+ #minLevel = "info";
30
+ configure(opts) {
31
+ this.#enabledNamespaces = parseNamespaces(opts.debug ?? "");
32
+ this.#minLevel = opts.level ?? "info";
33
+ }
34
+ shouldEmit(level, namespace) {
35
+ if (LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[this.#minLevel]) return true;
36
+ return this.#enabledNamespaces.some((re) => re.test(namespace));
37
+ }
38
+ emit(level, namespace, msg, meta) {
39
+ 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");
48
+ }
49
+ logger(namespace) {
50
+ return {
51
+ debug: (msg, meta) => this.emit("debug", namespace, msg, meta),
52
+ info: (msg, meta) => this.emit("info", namespace, msg, meta),
53
+ warn: (msg, meta) => this.emit("warn", namespace, msg, meta),
54
+ error: (msg, meta) => this.emit("error", namespace, msg, meta),
55
+ child: (sub) => this.logger(`${namespace}:${sub}`)
56
+ };
57
+ }
58
+ };
59
+ function parseNamespaces(spec) {
60
+ return spec.split(",").map((s) => s.trim()).filter((s) => s.length > 0).map((pattern) => {
61
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
62
+ return new RegExp(`^${escaped}$`);
63
+ });
64
+ }
65
+ var defaultContext = new LoggerContext();
66
+ function configureLogger(opts) {
67
+ defaultContext.configure(opts);
68
+ }
69
+ function createLogger(namespace, context = defaultContext) {
70
+ return context.logger(namespace);
71
+ }
72
+ var rootLogger = createLogger("mcp-inbox");
73
+
74
+ // src/http.ts
75
+ var log = createLogger("mcp-inbox:http");
76
+ function tokenOk(header, token) {
77
+ const given = Buffer.from(header?.replace(/^Bearer /i, "") ?? "");
78
+ const want = Buffer.from(token);
79
+ return given.length === want.length && timingSafeEqual(given, want);
80
+ }
81
+ function startHttpServer(cfg, makeServer) {
82
+ const http = createServer((req, res) => {
83
+ const reply = (status, msg) => {
84
+ res.writeHead(status, { "content-type": "text/plain" }).end(msg);
85
+ };
86
+ const path = (req.url ?? "").split("?")[0];
87
+ if (path !== "/mcp") return reply(404, "Not found");
88
+ if (!tokenOk(req.headers.authorization, cfg.token)) return reply(401, "Unauthorized");
89
+ if (req.method !== "POST") return reply(405, "Method not allowed");
90
+ const chunks = [];
91
+ let size = 0;
92
+ req.on("data", (c) => {
93
+ size += c.length;
94
+ if (size > 25 * 1024 * 1024) req.destroy();
95
+ else chunks.push(c);
96
+ });
97
+ req.on("end", () => {
98
+ void (async () => {
99
+ let body;
100
+ try {
101
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
102
+ } catch {
103
+ return reply(400, "Invalid JSON");
104
+ }
105
+ const server = makeServer();
106
+ const transport = new StreamableHTTPServerTransport({
107
+ enableJsonResponse: true
108
+ });
109
+ res.on("close", () => {
110
+ void transport.close();
111
+ void server.close();
112
+ });
113
+ try {
114
+ await server.connect(transport);
115
+ await transport.handleRequest(req, res, body);
116
+ } catch (err) {
117
+ log.error("http request failed", {
118
+ msg: err instanceof Error ? err.message : String(err)
119
+ });
120
+ if (!res.headersSent) reply(500, "Internal error");
121
+ }
122
+ })();
123
+ });
124
+ });
125
+ return new Promise((resolve, reject) => {
126
+ http.once("error", reject);
127
+ http.listen(cfg.port, cfg.host, () => {
128
+ log.info("listening", { host: cfg.host, port: cfg.port, path: "/mcp" });
129
+ resolve(http);
130
+ });
131
+ });
132
+ }
133
+
13
134
  // src/config/env.ts
14
135
  import { z } from "zod";
15
136
  import { homedir, platform } from "node:os";
@@ -40,11 +161,29 @@ var EnvSchema = z.object({
40
161
  IMAP_CACHE_DIR: z.string().min(1).optional(),
41
162
  IMAP_CACHE_DEFAULT_STALENESS_SEC: z.coerce.number().int().min(0).default(60),
42
163
  IMAP_CACHE_BODY_RETAIN_DAYS: z.coerce.number().int().min(0).default(180),
164
+ // Embeddings (semantic search). Gated on BASE_URL rather than API_KEY -
165
+ // a self-hosted endpoint may not require a key at all.
166
+ IMAP_EMBEDDINGS_BASE_URL: z.url().optional(),
167
+ IMAP_EMBEDDINGS_API_KEY: z.string().min(1).optional(),
168
+ IMAP_EMBEDDINGS_MODEL: z.string().min(1).default("arctic-embed-l-v2"),
169
+ IMAP_EMBEDDINGS_DIMS: z.coerce.number().int().min(1).max(8192).default(1024),
170
+ IMAP_EMBEDDINGS_BATCH_SIZE: z.coerce.number().int().min(1).max(512).default(64),
171
+ IMAP_EMBEDDINGS_TIMEOUT_MS: z.coerce.number().int().positive().default(3e4),
172
+ IMAP_EMBEDDINGS_SWEEP_MINUTES: z.coerce.number().int().min(0).max(1440).default(15),
173
+ IMAP_EMBEDDINGS_SWEEP_BATCH: z.coerce.number().int().min(1).max(5e3).default(200),
43
174
  // IDLE
44
175
  IMAP_IDLE_ENABLED: BooleanString.default(true),
45
176
  IMAP_IDLE_FOLDERS: CsvList.default(["INBOX"]),
177
+ // Transport. Unset MCP_HTTP_PORT = stdio. Set = streamable HTTP, which
178
+ // exposes the mailbox over the network, so a token is mandatory.
179
+ MCP_HTTP_PORT: z.coerce.number().int().min(1).max(65535).optional(),
180
+ MCP_HTTP_HOST: z.string().min(1).default("127.0.0.1"),
181
+ MCP_AUTH_TOKEN: z.string().min(16, "MCP_AUTH_TOKEN must be at least 16 characters").optional(),
46
182
  // Debug
47
183
  DEBUG: z.string().optional()
184
+ }).refine((raw) => raw.MCP_HTTP_PORT === void 0 || raw.MCP_AUTH_TOKEN !== void 0, {
185
+ path: ["MCP_AUTH_TOKEN"],
186
+ message: "MCP_AUTH_TOKEN is required when MCP_HTTP_PORT is set"
48
187
  }).transform((raw) => ({
49
188
  imap: {
50
189
  user: raw.IMAP_USER,
@@ -67,10 +206,23 @@ var EnvSchema = z.object({
67
206
  defaultStalenessSec: raw.IMAP_CACHE_DEFAULT_STALENESS_SEC,
68
207
  bodyRetainDays: raw.IMAP_CACHE_BODY_RETAIN_DAYS
69
208
  },
209
+ embeddings: raw.IMAP_EMBEDDINGS_BASE_URL === void 0 ? null : {
210
+ baseUrl: raw.IMAP_EMBEDDINGS_BASE_URL.replace(/\/+$/, ""),
211
+ ...raw.IMAP_EMBEDDINGS_API_KEY !== void 0 && {
212
+ apiKey: raw.IMAP_EMBEDDINGS_API_KEY
213
+ },
214
+ model: raw.IMAP_EMBEDDINGS_MODEL,
215
+ dims: raw.IMAP_EMBEDDINGS_DIMS,
216
+ batchSize: raw.IMAP_EMBEDDINGS_BATCH_SIZE,
217
+ timeoutMs: raw.IMAP_EMBEDDINGS_TIMEOUT_MS,
218
+ sweepMinutes: raw.IMAP_EMBEDDINGS_SWEEP_MINUTES,
219
+ sweepBatch: raw.IMAP_EMBEDDINGS_SWEEP_BATCH
220
+ },
70
221
  idle: {
71
222
  enabled: raw.IMAP_IDLE_ENABLED,
72
223
  folders: raw.IMAP_IDLE_FOLDERS
73
224
  },
225
+ http: raw.MCP_HTTP_PORT === void 0 ? null : { port: raw.MCP_HTTP_PORT, host: raw.MCP_HTTP_HOST, token: raw.MCP_AUTH_TOKEN },
74
226
  debug: raw.DEBUG ?? ""
75
227
  }));
76
228
  function defaultCacheDir() {
@@ -104,12 +256,14 @@ import { dirname } from "node:path";
104
256
  import { fileURLToPath } from "node:url";
105
257
  import { drizzle } from "drizzle-orm/node-sqlite";
106
258
  import { migrate } from "drizzle-orm/node-sqlite/migrator";
259
+ import * as sqliteVec from "sqlite-vec";
107
260
 
108
261
  // src/cache/schema.ts
109
262
  var schema_exports = {};
110
263
  __export(schema_exports, {
111
264
  emails: () => emails,
112
- folders: () => folders
265
+ folders: () => folders,
266
+ vecIndexState: () => vecIndexState
113
267
  });
114
268
  import { sqliteTable, text, integer, primaryKey, index } from "drizzle-orm/sqlite-core";
115
269
  var folders = sqliteTable("folders", {
@@ -167,6 +321,14 @@ var emails = sqliteTable(
167
321
  index("idx_emails_message_id").on(t.messageId)
168
322
  ]
169
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
+ });
170
332
 
171
333
  // src/errors/types.ts
172
334
  var McpInboxError = class extends Error {
@@ -186,71 +348,17 @@ var SmtpError = class extends McpInboxError {
186
348
  };
187
349
  var CacheError = class extends McpInboxError {
188
350
  };
351
+ var EmbeddingError = class extends McpInboxError {
352
+ };
189
353
  var ToolInputError = class extends McpInboxError {
190
354
  constructor(userMessage, cause) {
191
355
  super("TOOL_INVALID_INPUT", userMessage, cause);
192
356
  }
193
357
  };
194
358
 
195
- // src/utils/logger.ts
196
- var LEVEL_WEIGHT = {
197
- debug: 10,
198
- info: 20,
199
- warn: 30,
200
- error: 40
201
- };
202
- var LoggerContext = class {
203
- // JS hard-private - consumers of the published package cannot poke at these
204
- // from plain JS. TS `private` would be compile-time only.
205
- #enabledNamespaces = [];
206
- #minLevel = "info";
207
- configure(opts) {
208
- this.#enabledNamespaces = parseNamespaces(opts.debug ?? "");
209
- this.#minLevel = opts.level ?? "info";
210
- }
211
- shouldEmit(level, namespace) {
212
- if (LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[this.#minLevel]) return true;
213
- return this.#enabledNamespaces.some((re) => re.test(namespace));
214
- }
215
- emit(level, namespace, msg, meta) {
216
- if (!this.shouldEmit(level, namespace)) return;
217
- const entry = {
218
- ...meta,
219
- ts: (/* @__PURE__ */ new Date()).toISOString(),
220
- level,
221
- ns: namespace,
222
- msg
223
- };
224
- process.stderr.write(JSON.stringify(entry) + "\n");
225
- }
226
- logger(namespace) {
227
- return {
228
- debug: (msg, meta) => this.emit("debug", namespace, msg, meta),
229
- info: (msg, meta) => this.emit("info", namespace, msg, meta),
230
- warn: (msg, meta) => this.emit("warn", namespace, msg, meta),
231
- error: (msg, meta) => this.emit("error", namespace, msg, meta),
232
- child: (sub) => this.logger(`${namespace}:${sub}`)
233
- };
234
- }
235
- };
236
- function parseNamespaces(spec) {
237
- return spec.split(",").map((s) => s.trim()).filter((s) => s.length > 0).map((pattern) => {
238
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
239
- return new RegExp(`^${escaped}$`);
240
- });
241
- }
242
- var defaultContext = new LoggerContext();
243
- function configureLogger(opts) {
244
- defaultContext.configure(opts);
245
- }
246
- function createLogger(namespace, context = defaultContext) {
247
- return context.logger(namespace);
248
- }
249
- var rootLogger = createLogger("mcp-inbox");
250
-
251
359
  // src/cache/db.ts
252
360
  var DEFAULT_MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url));
253
- var log = createLogger("mcp-inbox:cache");
361
+ var log2 = createLogger("mcp-inbox:cache");
254
362
  function openCache(path, migrationsFolder) {
255
363
  if (path !== ":memory:") {
256
364
  try {
@@ -261,18 +369,19 @@ function openCache(path, migrationsFolder) {
261
369
  }
262
370
  let sqlite;
263
371
  try {
264
- sqlite = new DatabaseSync(path);
372
+ sqlite = new DatabaseSync(path, { allowExtension: true });
265
373
  } catch (err) {
266
374
  throw new CacheError("CACHE_IO_FAILED", diagnoseOpenError(path, err), err);
267
375
  }
268
376
  sqlite.exec("PRAGMA journal_mode = WAL;");
269
377
  sqlite.exec("PRAGMA foreign_keys = ON;");
270
378
  sqlite.exec("PRAGMA synchronous = NORMAL;");
379
+ const vectorsAvailable = loadVectorExtension(sqlite);
271
380
  const db = drizzle({ client: sqlite, schema: schema_exports });
272
381
  if (migrationsFolder) {
273
382
  try {
274
383
  migrate(db, { migrationsFolder });
275
- log.info("cache migrations applied", { migrationsFolder });
384
+ log2.info("cache migrations applied", { migrationsFolder });
276
385
  } catch (err) {
277
386
  sqlite.close();
278
387
  throw new CacheError(
@@ -284,17 +393,35 @@ function openCache(path, migrationsFolder) {
284
393
  }
285
394
  return {
286
395
  db,
396
+ vectorsAvailable,
287
397
  close: () => {
288
398
  try {
289
399
  sqlite.close();
290
400
  } catch (err) {
291
- log.warn("error closing cache db", {
401
+ log2.warn("error closing cache db", {
292
402
  msg: err instanceof Error ? err.message : String(err)
293
403
  });
294
404
  }
295
405
  }
296
406
  };
297
407
  }
408
+ function loadVectorExtension(sqlite) {
409
+ try {
410
+ sqlite.enableLoadExtension(true);
411
+ sqliteVec.load(sqlite);
412
+ return true;
413
+ } catch (err) {
414
+ log2.warn("sqlite-vec unavailable - semantic search tools will be disabled", {
415
+ msg: err instanceof Error ? err.message : String(err)
416
+ });
417
+ return false;
418
+ } finally {
419
+ try {
420
+ sqlite.enableLoadExtension(false);
421
+ } catch {
422
+ }
423
+ }
424
+ }
298
425
  function diagnoseOpenError(path, err) {
299
426
  const msg = err instanceof Error ? err.message : String(err);
300
427
  const code = err && typeof err === "object" && "code" in err ? String(err.code) : void 0;
@@ -314,8 +441,159 @@ function diagnoseOpenError(path, err) {
314
441
  }
315
442
 
316
443
  // src/cache/queries.ts
317
- import { and, desc, eq, gte, inArray, lt, sql } from "drizzle-orm";
318
- var log2 = createLogger("mcp-inbox:cache");
444
+ import { and, asc, desc, eq as eq2, gt, gte, inArray, lt, or as or2, sql as sql2 } from "drizzle-orm";
445
+
446
+ // src/cache/vectors.ts
447
+ import { eq, ne, or, sql } from "drizzle-orm";
448
+ var log3 = createLogger("mcp-inbox:vectors");
449
+ var ENVELOPE_PART = 0;
450
+ var INDEX_VERSION = "b1";
451
+ function indexModelId(model) {
452
+ return model.includes("#") ? model : `${model}#${INDEX_VERSION}`;
453
+ }
454
+ var int = (value) => BigInt(Math.trunc(value));
455
+ var toBlob = (vector) => new Uint8Array(vector.buffer, vector.byteOffset, vector.byteLength);
456
+ function ensureVecTable(db, model, dims) {
457
+ const wanted = indexModelId(model);
458
+ const stale = db.select().from(vecIndexState).where(or(ne(vecIndexState.model, wanted), ne(vecIndexState.dims, dims))).all();
459
+ if (stale.length > 0) {
460
+ log3.warn(
461
+ "embedding model or index format changed - dropping vector index, re-run imap_index_folder",
462
+ {
463
+ folders: stale.map((s) => s.folder),
464
+ was: stale.map((s) => `${s.model}/${String(s.dims)}`),
465
+ now: `${wanted}/${String(dims)}`
466
+ }
467
+ );
468
+ db.run(sql.raw("DROP TABLE IF EXISTS vec_emails"));
469
+ db.delete(vecIndexState).run();
470
+ }
471
+ db.run(
472
+ sql.raw(
473
+ `CREATE VIRTUAL TABLE IF NOT EXISTS vec_emails USING vec0(
474
+ folder text partition key,
475
+ uid integer,
476
+ part integer,
477
+ date integer,
478
+ embedding float[${dims}] distance_metric=cosine
479
+ )`
480
+ )
481
+ );
482
+ }
483
+ function indexedFolders(db) {
484
+ return db.select({ folder: vecIndexState.folder }).from(vecIndexState).all().map((r) => r.folder).toSorted((a, b) => a.localeCompare(b));
485
+ }
486
+ function getVecState(db, folder) {
487
+ return db.select().from(vecIndexState).where(eq(vecIndexState.folder, folder)).get();
488
+ }
489
+ function upsertVecState(db, row) {
490
+ const normalized = { ...row, model: indexModelId(row.model) };
491
+ db.insert(vecIndexState).values(normalized).onConflictDoUpdate({
492
+ target: vecIndexState.folder,
493
+ set: {
494
+ model: normalized.model,
495
+ dims: row.dims,
496
+ fromUid: row.fromUid,
497
+ toUid: row.toUid,
498
+ indexedAt: row.indexedAt
499
+ }
500
+ }).run();
501
+ }
502
+ function insertVectors(db, folder, rows) {
503
+ if (rows.length === 0) return;
504
+ const uids = [...new Set(rows.map((r) => r.uid))];
505
+ db.transaction((tx) => {
506
+ for (const uid of uids) {
507
+ tx.run(sql`DELETE FROM vec_emails WHERE folder = ${folder} AND uid = ${int(uid)}`);
508
+ }
509
+ for (const row of rows) {
510
+ tx.run(
511
+ sql`INSERT INTO vec_emails(folder, uid, part, date, embedding)
512
+ VALUES (${folder}, ${int(row.uid)}, ${int(row.part)}, ${int(row.date ?? 0)}, ${toBlob(row.vector)})`
513
+ );
514
+ }
515
+ });
516
+ }
517
+ function deleteVectorsByFolder(db, folder) {
518
+ if (getVecState(db, folder) === void 0) return;
519
+ try {
520
+ db.run(sql`DELETE FROM vec_emails WHERE folder = ${folder}`);
521
+ db.update(vecIndexState).set({ fromUid: 0, toUid: 0 }).where(eq(vecIndexState.folder, folder)).run();
522
+ } catch (err) {
523
+ log3.warn("could not drop vectors for folder", { folder, msg: messageOf(err) });
524
+ }
525
+ }
526
+ function deleteVectorsByUids(db, folder, uids) {
527
+ if (uids.length === 0 || getVecState(db, folder) === void 0) return;
528
+ try {
529
+ db.transaction((tx) => {
530
+ for (const uid of uids) {
531
+ tx.run(sql`DELETE FROM vec_emails WHERE folder = ${folder} AND uid = ${int(uid)}`);
532
+ }
533
+ });
534
+ } catch (err) {
535
+ log3.warn("could not drop vectors for uids", {
536
+ folder,
537
+ count: uids.length,
538
+ msg: messageOf(err)
539
+ });
540
+ }
541
+ }
542
+ function knnSearch(db, query, k, opts = {}) {
543
+ if (opts.folders?.length === 0) return [];
544
+ const filters = [];
545
+ if (opts.folders !== void 0) {
546
+ const list = opts.folders.map((f) => sql`${f}`);
547
+ filters.push(sql` AND folder IN (${sql.join(list, sql`, `)})`);
548
+ }
549
+ if (opts.sinceMs !== void 0) filters.push(sql` AND date >= ${int(opts.sinceMs)}`);
550
+ if (opts.beforeMs !== void 0) filters.push(sql` AND date < ${int(opts.beforeMs)}`);
551
+ return db.all(sql`
552
+ WITH knn AS MATERIALIZED (
553
+ SELECT folder, uid, distance FROM vec_emails
554
+ WHERE embedding MATCH ${toBlob(query)}
555
+ AND k = ${int(k)}
556
+ ${sql.join(filters, sql``)}
557
+ )
558
+ SELECT folder, uid, min(distance) AS distance
559
+ FROM knn GROUP BY folder, uid ORDER BY distance
560
+ `);
561
+ }
562
+ function pruneOrphanedVectors(db, folder) {
563
+ if (getVecState(db, folder) === void 0) return 0;
564
+ try {
565
+ const indexed = db.all(
566
+ sql`SELECT uid FROM vec_emails WHERE folder = ${folder}`
567
+ );
568
+ const live = new Set(
569
+ db.select({ uid: emails.uid }).from(emails).where(eq(emails.folder, folder)).all().map((r) => r.uid)
570
+ );
571
+ const orphans = [...new Set(indexed.map((r) => r.uid))].filter((uid) => !live.has(uid));
572
+ if (orphans.length === 0) return 0;
573
+ db.transaction((tx) => {
574
+ for (const uid of orphans) {
575
+ tx.run(sql`DELETE FROM vec_emails WHERE folder = ${folder} AND uid = ${int(uid)}`);
576
+ }
577
+ });
578
+ log3.info("pruned orphaned vectors", { folder, count: orphans.length });
579
+ return orphans.length;
580
+ } catch (err) {
581
+ log3.warn("could not prune orphaned vectors", { folder, msg: messageOf(err) });
582
+ return 0;
583
+ }
584
+ }
585
+ function countVectors(db, folder) {
586
+ const row = db.get(
587
+ sql`SELECT count(DISTINCT uid) AS c FROM vec_emails WHERE folder = ${folder}`
588
+ );
589
+ return row?.c ?? 0;
590
+ }
591
+ function messageOf(err) {
592
+ return err instanceof Error ? err.message : String(err);
593
+ }
594
+
595
+ // src/cache/queries.ts
596
+ var log4 = createLogger("mcp-inbox:cache");
319
597
  function upsertFolder(db, row) {
320
598
  db.insert(folders).values(row).onConflictDoUpdate({
321
599
  target: folders.name,
@@ -330,7 +608,7 @@ function upsertFolder(db, row) {
330
608
  }).run();
331
609
  }
332
610
  function getFolder(db, name) {
333
- return db.select().from(folders).where(eq(folders.name, name)).get();
611
+ return db.select().from(folders).where(eq2(folders.name, name)).get();
334
612
  }
335
613
  function upsertEmail(db, row) {
336
614
  db.insert(emails).values(row).onConflictDoUpdate({
@@ -357,24 +635,24 @@ function upsertEmails(db, rows) {
357
635
  });
358
636
  }
359
637
  function getEmail(db, folder, uid) {
360
- return db.select().from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
638
+ return db.select().from(emails).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).get();
361
639
  }
362
640
  function getEmailsByUids(db, folder, uids) {
363
641
  const out = /* @__PURE__ */ new Map();
364
642
  if (uids.length === 0) return out;
365
643
  inBatches(uids, (batch) => {
366
- const rows = db.select().from(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, batch))).all();
644
+ const rows = db.select().from(emails).where(and(eq2(emails.folder, folder), inArray(emails.uid, batch))).all();
367
645
  for (const row of rows) out.set(row.uid, row);
368
646
  });
369
647
  return out;
370
648
  }
371
649
  function buildFolderConditions(folder, opts) {
372
- const conditions = [eq(emails.folder, folder)];
650
+ const conditions = [eq2(emails.folder, folder)];
373
651
  if (opts.sinceMs !== void 0) conditions.push(gte(emails.date, opts.sinceMs));
374
652
  if (opts.beforeMs !== void 0) conditions.push(lt(emails.date, opts.beforeMs));
375
653
  if (opts.unseenOnly) {
376
654
  conditions.push(
377
- sql`NOT EXISTS (SELECT 1 FROM json_each(${emails.flags}) WHERE value = ${"\\Seen"})`
655
+ sql2`NOT EXISTS (SELECT 1 FROM json_each(${emails.flags}) WHERE value = ${"\\Seen"})`
378
656
  );
379
657
  }
380
658
  return conditions;
@@ -385,15 +663,28 @@ function listEmailsByFolder(db, folder, opts = {}) {
385
663
  }
386
664
  function countEmailsInFolder(db, folder, opts = {}) {
387
665
  const conditions = buildFolderConditions(folder, opts);
388
- const row = db.select({ n: sql`count(*)` }).from(emails).where(and(...conditions)).get();
666
+ const row = db.select({ n: sql2`count(*)` }).from(emails).where(and(...conditions)).get();
667
+ return row?.n ?? 0;
668
+ }
669
+ function listIndexCandidates(db, folder, opts) {
670
+ const conditions = [eq2(emails.folder, folder)];
671
+ if (opts.aboveUid !== void 0) conditions.push(gt(emails.uid, opts.aboveUid));
672
+ if (opts.belowUid !== void 0) conditions.push(lt(emails.uid, opts.belowUid));
673
+ return db.select().from(emails).where(and(...conditions)).orderBy(opts.order === "asc" ? asc(emails.uid) : desc(emails.uid)).limit(opts.limit).all();
674
+ }
675
+ function countEmailsOutsideUidRange(db, folder, fromUid, toUid) {
676
+ 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(
678
+ outside === void 0 ? eq2(emails.folder, folder) : and(eq2(emails.folder, folder), outside)
679
+ ).get();
389
680
  return row?.n ?? 0;
390
681
  }
391
682
  function listCachedUidsForFolder(db, folder) {
392
- const rows = db.select({ uid: emails.uid }).from(emails).where(eq(emails.folder, folder)).all();
683
+ const rows = db.select({ uid: emails.uid }).from(emails).where(eq2(emails.folder, folder)).all();
393
684
  return rows.map((r) => r.uid);
394
685
  }
395
686
  function setEmailFlags(db, folder, uid, flags) {
396
- db.update(emails).set({ flags }).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
687
+ db.update(emails).set({ flags }).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).run();
397
688
  }
398
689
  var UID_BATCH = 1e4;
399
690
  function inBatches(items, run) {
@@ -406,11 +697,11 @@ function setFlagsForUids(db, folder, next) {
406
697
  const uids = [...next.keys()];
407
698
  db.transaction((tx) => {
408
699
  inBatches(uids, (batch) => {
409
- const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, batch))).all();
700
+ const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq2(emails.folder, folder), inArray(emails.uid, batch))).all();
410
701
  for (const row of rows) {
411
702
  const flags = next.get(row.uid);
412
703
  if (!flags || flagsEqual(row.flags, flags)) continue;
413
- tx.update(emails).set({ flags }).where(and(eq(emails.folder, folder), eq(emails.uid, row.uid))).run();
704
+ tx.update(emails).set({ flags }).where(and(eq2(emails.folder, folder), eq2(emails.uid, row.uid))).run();
414
705
  }
415
706
  });
416
707
  });
@@ -419,11 +710,11 @@ function mutateEmailFlagsForUids(db, folder, uids, mutate) {
419
710
  if (uids.length === 0) return;
420
711
  db.transaction((tx) => {
421
712
  inBatches(uids, (batch) => {
422
- const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, batch))).all();
713
+ const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq2(emails.folder, folder), inArray(emails.uid, batch))).all();
423
714
  for (const row of rows) {
424
715
  const next = mutate(row.flags);
425
716
  if (flagsEqual(row.flags, next)) continue;
426
- tx.update(emails).set({ flags: next }).where(and(eq(emails.folder, folder), eq(emails.uid, row.uid))).run();
717
+ tx.update(emails).set({ flags: next }).where(and(eq2(emails.folder, folder), eq2(emails.uid, row.uid))).run();
427
718
  }
428
719
  });
429
720
  });
@@ -435,19 +726,22 @@ function flagsEqual(a, b) {
435
726
  return true;
436
727
  }
437
728
  function deleteEmailsByFolder(db, folder) {
438
- db.delete(emails).where(eq(emails.folder, folder)).run();
729
+ db.delete(emails).where(eq2(emails.folder, folder)).run();
730
+ deleteVectorsByFolder(db, folder);
439
731
  }
440
732
  function deleteEmail(db, folder, uid) {
441
- db.delete(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
733
+ db.delete(emails).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).run();
734
+ deleteVectorsByUids(db, folder, [uid]);
442
735
  }
443
736
  function deleteEmailsByUids(db, folder, uids) {
444
737
  if (uids.length === 0) return;
445
738
  inBatches(uids, (batch) => {
446
- db.delete(emails).where(and(eq(emails.folder, folder), inArray(emails.uid, batch))).run();
739
+ db.delete(emails).where(and(eq2(emails.folder, folder), inArray(emails.uid, batch))).run();
447
740
  });
741
+ deleteVectorsByUids(db, folder, uids);
448
742
  }
449
743
  function pruneBodiesBefore(db, cutoffMs) {
450
- const stale = db.select({ n: sql`count(*)` }).from(emails).where(lt(emails.bodyCachedAt, cutoffMs)).get();
744
+ const stale = db.select({ n: sql2`count(*)` }).from(emails).where(lt(emails.bodyCachedAt, cutoffMs)).get();
451
745
  const count = stale?.n ?? 0;
452
746
  if (count === 0) return 0;
453
747
  db.update(emails).set({ bodyText: null, bodyHtml: null, attachmentsJson: null, bodyCachedAt: null }).where(lt(emails.bodyCachedAt, cutoffMs)).run();
@@ -459,13 +753,13 @@ function getEmailBody(db, folder, uid) {
459
753
  bodyHtml: emails.bodyHtml,
460
754
  attachments: emails.attachmentsJson,
461
755
  bodyCachedAt: emails.bodyCachedAt
462
- }).from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
756
+ }).from(emails).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).get();
463
757
  return row;
464
758
  }
465
759
  function setEmailBody(db, folder, uid, body, nowMs) {
466
- const existing = db.select({ uid: emails.uid }).from(emails).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).get();
760
+ const existing = db.select({ uid: emails.uid }).from(emails).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).get();
467
761
  if (!existing) {
468
- log2.warn("cannot cache body, envelope row missing", { folder, uid });
762
+ log4.warn("cannot cache body, envelope row missing", { folder, uid });
469
763
  return false;
470
764
  }
471
765
  db.update(emails).set({
@@ -473,7 +767,7 @@ function setEmailBody(db, folder, uid, body, nowMs) {
473
767
  bodyHtml: body.html,
474
768
  attachmentsJson: body.attachments ?? [],
475
769
  bodyCachedAt: nowMs
476
- }).where(and(eq(emails.folder, folder), eq(emails.uid, uid))).run();
770
+ }).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).run();
477
771
  return true;
478
772
  }
479
773
 
@@ -570,9 +864,9 @@ function isMcpInboxError(err) {
570
864
  }
571
865
 
572
866
  // src/imap/client.ts
573
- var log3 = createLogger("mcp-inbox:imap");
867
+ var log5 = createLogger("mcp-inbox:imap");
574
868
  async function createImapConnection(config) {
575
- log3.info("opening IMAP connection", {
869
+ log5.info("opening IMAP connection", {
576
870
  host: config.host,
577
871
  port: config.port,
578
872
  tls: config.tls
@@ -593,7 +887,7 @@ async function createImapConnection(config) {
593
887
  greetingTimeout: config.authTimeoutMs
594
888
  });
595
889
  flow.on("error", (err) => {
596
- log3.error("IMAP connection error", {
890
+ log5.error("IMAP connection error", {
597
891
  msg: err instanceof Error ? err.message : String(err)
598
892
  });
599
893
  });
@@ -602,7 +896,7 @@ async function createImapConnection(config) {
602
896
  } catch (err) {
603
897
  throw mapImapError(err);
604
898
  }
605
- log3.info("IMAP connection ready");
899
+ log5.info("IMAP connection ready");
606
900
  return flow;
607
901
  }
608
902
  var ImapClient = class {
@@ -657,7 +951,7 @@ var ImapClient = class {
657
951
  const flow = await createImapConnection(this.#config);
658
952
  flow.on("close", () => {
659
953
  if (!this.#closed) {
660
- log3.warn("IMAP connection closed unexpectedly");
954
+ log5.warn("IMAP connection closed unexpectedly");
661
955
  }
662
956
  if (this.#flow === flow) {
663
957
  this.#flow = null;
@@ -677,7 +971,7 @@ var ImapClient = class {
677
971
  try {
678
972
  await flow.logout();
679
973
  } catch (err) {
680
- log3.warn("error during IMAP logout", {
974
+ log5.warn("error during IMAP logout", {
681
975
  msg: err instanceof Error ? err.message : String(err)
682
976
  });
683
977
  }
@@ -686,7 +980,7 @@ var ImapClient = class {
686
980
  };
687
981
 
688
982
  // src/cache/sync.ts
689
- var log4 = createLogger("mcp-inbox:sync");
983
+ var log6 = createLogger("mcp-inbox:sync");
690
984
  var ENVELOPE_FLUSH_SIZE = 500;
691
985
  async function syncFolder(ctx, folderPath) {
692
986
  const started = Date.now();
@@ -699,7 +993,7 @@ async function syncFolder(ctx, folderPath) {
699
993
  const cached = getFolder(ctx.db, folderPath);
700
994
  const uidValidityChanged = cached !== void 0 && cached.uidValidity !== Number(box.uidValidity);
701
995
  if (uidValidityChanged) {
702
- log4.warn("UIDVALIDITY changed - wiping folder cache", {
996
+ log6.warn("UIDVALIDITY changed - wiping folder cache", {
703
997
  folder: folderPath,
704
998
  cached: cached?.uidValidity,
705
999
  server: Number(box.uidValidity)
@@ -717,7 +1011,7 @@ async function syncFolder(ctx, folderPath) {
717
1011
  lastSyncedAt: Date.now()
718
1012
  });
719
1013
  const durationMs = Date.now() - started;
720
- log4.info("folder synced", { folder: folderPath, syncType, fetched, durationMs });
1014
+ log6.info("folder synced", { folder: folderPath, syncType, fetched, durationMs });
721
1015
  return { folder: folderPath, syncType, fetched, durationMs };
722
1016
  } catch (err) {
723
1017
  throw mapImapError(err);
@@ -744,7 +1038,7 @@ async function runSync(ctx, folderPath, box, cached, uidValidityChanged) {
744
1038
  const { missing, ghosts } = diffUids(listCachedUidsForFolder(ctx.db, folderPath), serverUids);
745
1039
  if (ghosts.length > 0) {
746
1040
  deleteEmailsByUids(ctx.db, folderPath, ghosts);
747
- log4.info("evicted ghost UIDs", { folder: folderPath, removed: ghosts.length });
1041
+ log6.info("evicted ghost UIDs", { folder: folderPath, removed: ghosts.length });
748
1042
  }
749
1043
  const fetched = missing.length > 0 ? await fetchEnvelopes(ctx, folderPath, missing) : 0;
750
1044
  const serverModseq = box.highestModseq !== void 0 ? Number(box.highestModseq) : null;
@@ -823,7 +1117,7 @@ function hasAttachments(structure) {
823
1117
  }
824
1118
 
825
1119
  // src/cache/idle.ts
826
- var log5 = createLogger("mcp-inbox:idle");
1120
+ var log7 = createLogger("mcp-inbox:idle");
827
1121
  var IdleManager = class {
828
1122
  #opts;
829
1123
  #subscriptions = [];
@@ -839,7 +1133,7 @@ var IdleManager = class {
839
1133
  const sub = await this.#watchFolder(folder);
840
1134
  this.#subscriptions.push(sub);
841
1135
  } catch (err) {
842
- log5.error("failed to open IDLE for folder", {
1136
+ log7.error("failed to open IDLE for folder", {
843
1137
  folder,
844
1138
  msg: err instanceof Error ? err.message : String(err)
845
1139
  });
@@ -857,13 +1151,13 @@ var IdleManager = class {
857
1151
  async #watchFolder(folder) {
858
1152
  const imap = await createImapConnection(this.#opts.imap);
859
1153
  await imap.mailboxOpen(folder);
860
- log5.info("watching folder", { folder });
1154
+ log7.info("watching folder", { folder });
861
1155
  const onExists = (e) => {
862
- log5.debug("exists event", { folder: e.path, count: e.count, prevCount: e.prevCount });
1156
+ log7.debug("exists event", { folder: e.path, count: e.count, prevCount: e.prevCount });
863
1157
  void this.#handleExists(folder, imap);
864
1158
  };
865
1159
  const onFlags = (e) => {
866
- log5.debug("flags event", { folder: e.path, uid: e.uid, flags: Array.from(e.flags) });
1160
+ log7.debug("flags event", { folder: e.path, uid: e.uid, flags: Array.from(e.flags) });
867
1161
  if (e.uid !== void 0) {
868
1162
  setEmailFlags(this.#opts.db, folder, e.uid, Array.from(e.flags));
869
1163
  } else {
@@ -871,7 +1165,7 @@ var IdleManager = class {
871
1165
  }
872
1166
  };
873
1167
  const onExpunge = (e) => {
874
- log5.debug("expunge event", { folder: e.path, uid: e.uid, seq: e.seq });
1168
+ log7.debug("expunge event", { folder: e.path, uid: e.uid, seq: e.seq });
875
1169
  if (e.uid !== void 0) {
876
1170
  deleteEmail(this.#opts.db, folder, e.uid);
877
1171
  } else {
@@ -890,7 +1184,7 @@ var IdleManager = class {
890
1184
  try {
891
1185
  await imap.logout();
892
1186
  } catch (err) {
893
- log5.warn("error closing IDLE connection", {
1187
+ log7.warn("error closing IDLE connection", {
894
1188
  folder,
895
1189
  msg: err instanceof Error ? err.message : String(err)
896
1190
  });
@@ -898,31 +1192,548 @@ var IdleManager = class {
898
1192
  }
899
1193
  };
900
1194
  }
901
- async #handleExists(folder, imap) {
1195
+ async #handleExists(folder, imap) {
1196
+ try {
1197
+ await syncFolder({ db: this.#opts.db, imap }, folder);
1198
+ } catch (err) {
1199
+ log7.error("exists sync failed", {
1200
+ folder,
1201
+ msg: err instanceof Error ? err.message : String(err)
1202
+ });
1203
+ }
1204
+ }
1205
+ async #resyncFolder(folder, imap) {
1206
+ try {
1207
+ await syncFolder({ db: this.#opts.db, imap }, folder);
1208
+ } catch (err) {
1209
+ log7.error("resync failed", {
1210
+ folder,
1211
+ msg: err instanceof Error ? err.message : String(err)
1212
+ });
1213
+ }
1214
+ }
1215
+ };
1216
+
1217
+ // src/embeddings/client.ts
1218
+ import { z as z2 } from "zod";
1219
+ var log8 = createLogger("mcp-inbox:embeddings");
1220
+ var MAX_ATTEMPTS = 3;
1221
+ var BASE_BACKOFF_MS = 500;
1222
+ var MAX_RETRY_AFTER_MS = 6e4;
1223
+ var EmbeddingsResponse = z2.object({
1224
+ data: z2.array(
1225
+ z2.object({
1226
+ index: z2.number().int().min(0),
1227
+ embedding: z2.array(z2.number())
1228
+ })
1229
+ ).min(1)
1230
+ });
1231
+ function envelopeText(email) {
1232
+ return `Subject: ${email.subject ?? ""}
1233
+ From: ${email.fromAddr ?? ""}`;
1234
+ }
1235
+ async function embedTexts(texts, cfg) {
1236
+ if (texts.length === 0) return [];
1237
+ const out = [];
1238
+ for (let i = 0; i < texts.length; i += cfg.batchSize) {
1239
+ const batch = texts.slice(i, i + cfg.batchSize);
1240
+ out.push(...await embedBatch(batch, cfg));
1241
+ }
1242
+ return out;
1243
+ }
1244
+ async function embedBatch(batch, cfg) {
1245
+ const response = await postWithRetry(batch, cfg);
1246
+ let body;
1247
+ try {
1248
+ body = await response.json();
1249
+ } catch (err) {
1250
+ throw new EmbeddingError(
1251
+ "EMBEDDING_UNREACHABLE",
1252
+ `The embeddings endpoint at ${cfg.baseUrl} returned a non-JSON response. Check IMAP_EMBEDDINGS_BASE_URL points at an OpenAI-compatible API.`,
1253
+ err
1254
+ );
1255
+ }
1256
+ const parsed = EmbeddingsResponse.safeParse(body);
1257
+ if (!parsed.success) {
1258
+ throw new EmbeddingError(
1259
+ "EMBEDDING_UNREACHABLE",
1260
+ `The embeddings endpoint at ${cfg.baseUrl} returned an unexpected response shape. Check that IMAP_EMBEDDINGS_MODEL="${cfg.model}" is an embedding model, not a chat model.`,
1261
+ parsed.error
1262
+ );
1263
+ }
1264
+ const ordered = parsed.data.data.toSorted((a, b) => a.index - b.index);
1265
+ if (ordered.length !== batch.length) {
1266
+ throw new EmbeddingError(
1267
+ "EMBEDDING_UNREACHABLE",
1268
+ `Asked the embeddings endpoint for ${batch.length} vectors but received ${ordered.length}.`
1269
+ );
1270
+ }
1271
+ return ordered.map((item) => {
1272
+ if (item.embedding.length !== cfg.dims) {
1273
+ throw new EmbeddingError(
1274
+ "EMBEDDING_DIM_MISMATCH",
1275
+ `Model "${cfg.model}" returned ${item.embedding.length}-dimensional vectors but IMAP_EMBEDDINGS_DIMS is ${cfg.dims}. Set IMAP_EMBEDDINGS_DIMS=${item.embedding.length} and re-run imap_index_folder.`
1276
+ );
1277
+ }
1278
+ return Float32Array.from(item.embedding);
1279
+ });
1280
+ }
1281
+ async function postWithRetry(batch, cfg) {
1282
+ let lastError;
1283
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
1284
+ let response;
1285
+ try {
1286
+ response = await fetch(`${cfg.baseUrl}/embeddings`, {
1287
+ method: "POST",
1288
+ headers: {
1289
+ "content-type": "application/json",
1290
+ ...cfg.apiKey !== void 0 && { authorization: `Bearer ${cfg.apiKey}` }
1291
+ },
1292
+ body: JSON.stringify({ model: cfg.model, input: batch, encoding_format: "float" }),
1293
+ signal: AbortSignal.timeout(cfg.timeoutMs)
1294
+ });
1295
+ } catch (err) {
1296
+ lastError = err;
1297
+ if (attempt === MAX_ATTEMPTS) break;
1298
+ await sleep(backoffMs(attempt));
1299
+ continue;
1300
+ }
1301
+ if (response.ok) return response;
1302
+ if (response.status === 401 || response.status === 403) {
1303
+ throw new EmbeddingError(
1304
+ "EMBEDDING_AUTH_FAILED",
1305
+ `The embeddings endpoint at ${cfg.baseUrl} rejected the credentials (HTTP ${response.status}). Check IMAP_EMBEDDINGS_API_KEY.`
1306
+ );
1307
+ }
1308
+ lastError = new Error(`HTTP ${response.status}: ${(await safeText(response)).slice(0, 200)}`);
1309
+ if (!isRetryable(response.status) || attempt === MAX_ATTEMPTS) break;
1310
+ log8.debug("embeddings request failed, retrying", { status: response.status, attempt });
1311
+ await sleep(retryAfterMs(response) ?? backoffMs(attempt));
1312
+ }
1313
+ throw new EmbeddingError(
1314
+ "EMBEDDING_UNREACHABLE",
1315
+ `Could not reach the embeddings endpoint at ${cfg.baseUrl} after ${MAX_ATTEMPTS} attempts. Check IMAP_EMBEDDINGS_BASE_URL and that the service is up.`,
1316
+ lastError
1317
+ );
1318
+ }
1319
+ function isRetryable(status) {
1320
+ return status === 408 || status === 429 || status >= 500;
1321
+ }
1322
+ function retryAfterMs(response) {
1323
+ const header = response.headers.get("retry-after");
1324
+ if (header === null) return void 0;
1325
+ const seconds = Number(header);
1326
+ if (!Number.isFinite(seconds) || seconds < 0) return void 0;
1327
+ return Math.min(seconds * 1e3, MAX_RETRY_AFTER_MS);
1328
+ }
1329
+ function backoffMs(attempt) {
1330
+ return BASE_BACKOFF_MS * 2 ** (attempt - 1) + Math.random() * 250;
1331
+ }
1332
+ async function safeText(response) {
1333
+ try {
1334
+ return await response.text();
1335
+ } catch {
1336
+ return "";
1337
+ }
1338
+ }
1339
+ function sleep(ms) {
1340
+ return new Promise((resolve) => setTimeout(resolve, ms));
1341
+ }
1342
+
1343
+ // src/embeddings/chunk.ts
1344
+ var CHUNK_TARGET = 1200;
1345
+ var CHUNK_OVERLAP = 150;
1346
+ var MAX_CHUNKS = 10;
1347
+ var MIN_CHUNK = 40;
1348
+ var MIN_AFTER_STRIP = 200;
1349
+ var FORWARD_SUBJECT = /\b(fwd?|fw|pd)\s*:/i;
1350
+ var QUOTE_MARKERS = [
1351
+ /^\s*>/,
1352
+ /^\s*_{5,}\s*$/,
1353
+ /^\s*-{2,}\s*(?:Original Message|Forwarded message)\s*-{2,}/i,
1354
+ /^\s*-{2,}\s*(?:Wiadomo[śs][ćc] oryginalna|Oryginalna wiadomo[śs][ćc])\s*-{2,}/i,
1355
+ /^\s*On\b.{0,200}\bwrote:\s*$/i,
1356
+ /^\s*(?:W dniu|Dnia)\b.{0,200}\b(?:napisa[łl](?:\(a\))?|pisze)\s*:\s*$/i
1357
+ ];
1358
+ var HEADER_START = /^\s*(?:From|Od)\s*:\s*\S/i;
1359
+ var HEADER_FOLLOW = /^\s*(?:Sent|Wys[łl]ano|To|Do|Subject|Temat)\s*:\s*\S/i;
1360
+ function stripQuoted(text2, subject) {
1361
+ if (FORWARD_SUBJECT.test(subject ?? "")) return text2;
1362
+ const lines = text2.split(/\r?\n/);
1363
+ let cutAt = -1;
1364
+ for (const [i, line] of lines.entries()) {
1365
+ if (QUOTE_MARKERS.some((re) => re.test(line))) {
1366
+ cutAt = i;
1367
+ break;
1368
+ }
1369
+ if (HEADER_START.test(line) && lines.slice(i + 1, i + 4).some((l) => HEADER_FOLLOW.test(l))) {
1370
+ cutAt = i;
1371
+ break;
1372
+ }
1373
+ }
1374
+ if (cutAt < 0) return text2;
1375
+ const kept = lines.slice(0, cutAt).join("\n").trim();
1376
+ return kept.length < MIN_AFTER_STRIP ? text2 : kept;
1377
+ }
1378
+ function chunkText(text2) {
1379
+ const paragraphs = splitParagraphs(text2.replace(/\r\n/g, "\n").trim());
1380
+ const chunks = [];
1381
+ let current = "";
1382
+ for (const paragraph of paragraphs) {
1383
+ if (chunks.length >= MAX_CHUNKS) break;
1384
+ if (current.length > 0 && current.length + paragraph.length + 2 > CHUNK_TARGET) {
1385
+ chunks.push(current.trim());
1386
+ current = overlapFrom(current);
1387
+ }
1388
+ current = current.length > 0 ? `${current}
1389
+
1390
+ ${paragraph}` : paragraph;
1391
+ }
1392
+ if (chunks.length < MAX_CHUNKS && current.trim().length > 0) chunks.push(current.trim());
1393
+ return chunks.slice(0, MAX_CHUNKS).filter((c) => c.length >= MIN_CHUNK);
1394
+ }
1395
+ function bodyChunks(text2, subject) {
1396
+ return chunkText(stripQuoted(text2, subject));
1397
+ }
1398
+ function splitParagraphs(text2) {
1399
+ const out = [];
1400
+ for (const block of text2.split(/\n\s*\n/)) {
1401
+ const trimmed = block.trim();
1402
+ if (trimmed.length === 0) continue;
1403
+ if (trimmed.length <= CHUNK_TARGET) {
1404
+ out.push(trimmed);
1405
+ continue;
1406
+ }
1407
+ for (const piece of hardSplit(trimmed)) out.push(piece);
1408
+ }
1409
+ return out;
1410
+ }
1411
+ function hardSplit(paragraph) {
1412
+ const out = [];
1413
+ let rest = paragraph;
1414
+ while (rest.length > CHUNK_TARGET) {
1415
+ const window = rest.slice(0, CHUNK_TARGET);
1416
+ const cut = window.lastIndexOf(" ");
1417
+ const at = cut > CHUNK_TARGET / 2 ? cut : CHUNK_TARGET;
1418
+ out.push(rest.slice(0, at).trim());
1419
+ rest = rest.slice(at).trim();
1420
+ }
1421
+ if (rest.length > 0) out.push(rest);
1422
+ return out;
1423
+ }
1424
+ function overlapFrom(chunk) {
1425
+ if (chunk.length <= CHUNK_OVERLAP) return chunk;
1426
+ const tail = chunk.slice(-CHUNK_OVERLAP);
1427
+ const space = tail.indexOf(" ");
1428
+ return space === -1 ? tail : tail.slice(space + 1);
1429
+ }
1430
+
1431
+ // src/cache/backfill.ts
1432
+ var log9 = createLogger("mcp-inbox:backfill");
1433
+ function pendingForFolders(db, folders2) {
1434
+ let total = 0;
1435
+ for (const folder of folders2) {
1436
+ const state = getVecState(db, folder);
1437
+ if (state === void 0) continue;
1438
+ total += countEmailsOutsideUidRange(db, folder, state.fromUid, state.toUid);
1439
+ }
1440
+ return total;
1441
+ }
1442
+ async function backfillFolder(db, folder, cfg, budget, direction, now, fetchBodies) {
1443
+ const state = getVecState(db, folder);
1444
+ if (state === void 0) {
1445
+ throw new EmbeddingError(
1446
+ "EMBEDDING_NOT_INDEXED",
1447
+ `Folder "${folder}" is not indexed for semantic search. Run imap_index_folder with folder="${folder}" first, or use imap_search_emails.`
1448
+ );
1449
+ }
1450
+ let { fromUid, toUid } = state;
1451
+ let embedded = 0;
1452
+ let bodiesIndexed = 0;
1453
+ let left = budget;
1454
+ let bodiesAvailable = fetchBodies !== void 0;
1455
+ const startedEmpty = fromUid === 0 && toUid === 0;
1456
+ const runBatch = async (rows) => {
1457
+ let bodies = { texts: /* @__PURE__ */ new Map(), expected: 0 };
1458
+ if (bodiesAvailable && fetchBodies) {
1459
+ bodies = await fetchBodies(rows.map((r) => r.uid));
1460
+ if (bodies.expected > 0 && bodies.texts.size === 0) {
1461
+ bodiesAvailable = false;
1462
+ log9.warn("server returned no body parts - indexing envelopes only", { folder });
1463
+ }
1464
+ }
1465
+ bodiesIndexed += bodies.texts.size;
1466
+ await embedBatch2(db, folder, rows, cfg, bodies.texts);
1467
+ };
1468
+ const widenRange = (rows) => {
1469
+ const uids = rows.map((r) => r.uid);
1470
+ fromUid = fromUid === 0 ? Math.min(...uids) : Math.min(fromUid, ...uids);
1471
+ toUid = Math.max(toUid, ...uids);
1472
+ upsertVecState(db, {
1473
+ folder,
1474
+ model: cfg.model,
1475
+ dims: cfg.dims,
1476
+ fromUid,
1477
+ toUid,
1478
+ indexedAt: now()
1479
+ });
1480
+ };
1481
+ if (!startedEmpty) {
1482
+ while (left > 0) {
1483
+ const rows = listIndexCandidates(db, folder, {
1484
+ aboveUid: toUid,
1485
+ limit: Math.min(cfg.batchSize, left),
1486
+ order: "asc"
1487
+ });
1488
+ if (rows.length === 0) break;
1489
+ await runBatch(rows);
1490
+ widenRange(rows);
1491
+ embedded += rows.length;
1492
+ left -= rows.length;
1493
+ }
1494
+ }
1495
+ if (startedEmpty || direction === "both") {
1496
+ while (left > 0) {
1497
+ const rows = listIndexCandidates(db, folder, {
1498
+ ...fromUid > 0 && { belowUid: fromUid },
1499
+ limit: Math.min(cfg.batchSize, left),
1500
+ order: "desc"
1501
+ });
1502
+ if (rows.length === 0) break;
1503
+ await runBatch(rows);
1504
+ widenRange(rows);
1505
+ embedded += rows.length;
1506
+ left -= rows.length;
1507
+ }
1508
+ }
1509
+ return {
1510
+ embedded,
1511
+ bodiesIndexed,
1512
+ remaining: countEmailsOutsideUidRange(db, folder, fromUid, toUid)
1513
+ };
1514
+ }
1515
+ async function embedBatch2(db, folder, rows, cfg, bodies) {
1516
+ const texts = [];
1517
+ const owners = [];
1518
+ for (const row of rows) {
1519
+ texts.push(envelopeText(row));
1520
+ owners.push({ uid: row.uid, part: ENVELOPE_PART, date: row.date });
1521
+ const body = bodies.get(row.uid);
1522
+ if (body === void 0) continue;
1523
+ for (const [i, chunk] of bodyChunks(body, row.subject).entries()) {
1524
+ texts.push(chunk);
1525
+ owners.push({ uid: row.uid, part: i + 1, date: row.date });
1526
+ }
1527
+ }
1528
+ const vectors = await embedTexts(texts, cfg);
1529
+ const toInsert = [];
1530
+ for (const [i, owner] of owners.entries()) {
1531
+ const vector = vectors[i];
1532
+ if (vector === void 0) {
1533
+ throw new EmbeddingError(
1534
+ "EMBEDDING_UNREACHABLE",
1535
+ `The embeddings endpoint returned ${vectors.length} vectors for ${owners.length} texts.`
1536
+ );
1537
+ }
1538
+ toInsert.push({ ...owner, vector });
1539
+ }
1540
+ insertVectors(db, folder, toInsert);
1541
+ }
1542
+
1543
+ // src/imap/body-text.ts
1544
+ var log10 = createLogger("mcp-inbox:body-text");
1545
+ var MAX_PART_BYTES = 1e6;
1546
+ function pickTextPart(structure) {
1547
+ if (structure === void 0) return null;
1548
+ let best = null;
1549
+ const queue = [structure];
1550
+ while (queue.length > 0) {
1551
+ const node = queue.shift();
1552
+ if (node === void 0) continue;
1553
+ if (isAttachment(node)) continue;
1554
+ const rank = node.type === "text/plain" ? 0 : node.type === "text/html" ? 1 : -1;
1555
+ if (rank >= 0 && (best === null || rank < best.rank)) {
1556
+ best = { node, rank };
1557
+ }
1558
+ if (node.childNodes) queue.push(...node.childNodes);
1559
+ }
1560
+ if (best === null) return null;
1561
+ if (typeof best.node.size === "number" && best.node.size > MAX_PART_BYTES) return null;
1562
+ return {
1563
+ part: best.node.part ?? "1",
1564
+ charset: best.node.parameters?.["charset"] ?? "utf-8",
1565
+ encoding: best.node.encoding ?? "7bit",
1566
+ isHtml: best.rank === 1
1567
+ };
1568
+ }
1569
+ function decodeTextPart(raw, part, alreadyDecoded = false) {
1570
+ const bytes = alreadyDecoded ? raw : decodeTransfer(raw, part.encoding);
1571
+ let text2;
1572
+ try {
1573
+ text2 = new TextDecoder(part.charset).decode(bytes);
1574
+ } catch {
1575
+ text2 = new TextDecoder("utf-8").decode(bytes);
1576
+ }
1577
+ return part.isHtml ? flattenHtml(text2) : text2;
1578
+ }
1579
+ async function fetchTextBodies(imap, uids) {
1580
+ const texts = /* @__PURE__ */ new Map();
1581
+ if (uids.length === 0) return { texts, expected: 0 };
1582
+ const parts = /* @__PURE__ */ new Map();
1583
+ for await (const msg of imap.fetch([...uids], { bodyStructure: true }, { uid: true })) {
1584
+ const picked = pickTextPart(msg.bodyStructure);
1585
+ if (picked !== null) parts.set(msg.uid, picked);
1586
+ }
1587
+ const groups = /* @__PURE__ */ new Map();
1588
+ for (const [uid, part] of parts) {
1589
+ const bucket = groups.get(part.part);
1590
+ if (bucket === void 0) groups.set(part.part, [uid]);
1591
+ else bucket.push(uid);
1592
+ }
1593
+ for (const [partId, groupUids] of groups) {
1594
+ const key = partId.toLowerCase();
902
1595
  try {
903
- await syncFolder({ db: this.#opts.db, imap }, folder);
1596
+ for await (const msg of imap.fetch([...groupUids], { bodyParts: [partId] }, { uid: true })) {
1597
+ const raw = msg.bodyParts?.get(key);
1598
+ const part = parts.get(msg.uid);
1599
+ if (raw === void 0 || raw.length === 0 || part === void 0) continue;
1600
+ const decoded = decodeTextPart(raw, part, msg.binaryParts?.has(key) === true);
1601
+ const trimmed = decoded.trim();
1602
+ if (trimmed.length > 0) texts.set(msg.uid, trimmed);
1603
+ }
904
1604
  } catch (err) {
905
- log5.error("exists sync failed", {
906
- folder,
1605
+ log10.warn("body part fetch failed for a part group", {
1606
+ part: partId,
1607
+ uids: groupUids.length,
907
1608
  msg: err instanceof Error ? err.message : String(err)
908
1609
  });
909
1610
  }
910
1611
  }
911
- async #resyncFolder(folder, imap) {
1612
+ return { texts, expected: parts.size };
1613
+ }
1614
+ function bodyFetcherFor(client, folder) {
1615
+ return async (uids) => {
912
1616
  try {
913
- await syncFolder({ db: this.#opts.db, imap }, folder);
1617
+ const imap = await client.connection();
1618
+ const lock = await imap.getMailboxLock(folder);
1619
+ try {
1620
+ return await fetchTextBodies(imap, uids);
1621
+ } finally {
1622
+ lock.release();
1623
+ }
914
1624
  } catch (err) {
915
- log5.error("resync failed", {
1625
+ log10.warn("could not fetch body text", {
916
1626
  folder,
917
1627
  msg: err instanceof Error ? err.message : String(err)
918
1628
  });
1629
+ return { texts: /* @__PURE__ */ new Map(), expected: 0 };
1630
+ }
1631
+ };
1632
+ }
1633
+ function isAttachment(node) {
1634
+ return node.disposition === "attachment" || node.dispositionParameters?.["filename"] !== void 0;
1635
+ }
1636
+ function decodeTransfer(raw, encoding) {
1637
+ switch (encoding.toLowerCase()) {
1638
+ case "base64":
1639
+ return Buffer.from(raw.toString("ascii"), "base64");
1640
+ case "quoted-printable":
1641
+ return decodeQuotedPrintable(raw);
1642
+ default:
1643
+ return raw;
1644
+ }
1645
+ }
1646
+ function decodeQuotedPrintable(raw) {
1647
+ const source = raw.toString("latin1").replace(/=\r?\n/g, "");
1648
+ const out = [];
1649
+ for (let i = 0; i < source.length; i++) {
1650
+ if (source.charAt(i) === "=" && /^[\da-f]{2}$/i.test(source.slice(i + 1, i + 3))) {
1651
+ out.push(Number.parseInt(source.slice(i + 1, i + 3), 16));
1652
+ i += 2;
1653
+ continue;
1654
+ }
1655
+ out.push(source.charCodeAt(i));
1656
+ }
1657
+ return Buffer.from(out);
1658
+ }
1659
+ function flattenHtml(html) {
1660
+ return html.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, " ").replace(/<(?:br|\/p|\/div|\/tr|\/li|\/h[1-6])\b[^>]*>/gi, "\n").replace(/<[^>]+>/g, " ").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#(\d+);/g, (_m, code) => String.fromCodePoint(Number(code))).replace(/[ \t]{2,}/g, " ").replace(/\n{3,}/g, "\n\n");
1661
+ }
1662
+
1663
+ // src/cache/indexer.ts
1664
+ var log11 = createLogger("mcp-inbox:indexer");
1665
+ var IndexSweeper = class {
1666
+ #opts;
1667
+ #timer = null;
1668
+ #running = false;
1669
+ #stopped = false;
1670
+ constructor(opts) {
1671
+ this.#opts = opts;
1672
+ }
1673
+ start() {
1674
+ if (this.#timer !== null || this.#stopped || this.#opts.intervalMs <= 0) return;
1675
+ this.#timer = setInterval(() => {
1676
+ void this.sweepOnce();
1677
+ }, this.#opts.intervalMs);
1678
+ this.#timer.unref();
1679
+ log11.info("background index sweeper started", { everyMs: this.#opts.intervalMs });
1680
+ }
1681
+ stop() {
1682
+ this.#stopped = true;
1683
+ if (this.#timer !== null) {
1684
+ clearInterval(this.#timer);
1685
+ this.#timer = null;
1686
+ }
1687
+ }
1688
+ /**
1689
+ * One pass over the indexed folders. Never rejects: this runs detached from
1690
+ * any request, so an escaping error would be an unhandled rejection.
1691
+ */
1692
+ async sweepOnce() {
1693
+ if (this.#running || this.#stopped) return { folders: 0, embedded: 0 };
1694
+ this.#running = true;
1695
+ let embedded = 0;
1696
+ let visited = 0;
1697
+ let budget = this.#opts.budgetPerTick;
1698
+ try {
1699
+ ensureVecTable(this.#opts.db, this.#opts.cfg.model, this.#opts.cfg.dims);
1700
+ for (const folder of indexedFolders(this.#opts.db)) {
1701
+ if (budget <= 0 || this.#stopped) break;
1702
+ visited++;
1703
+ try {
1704
+ const imap = await this.#opts.imap.connection();
1705
+ await syncFolder({ db: this.#opts.db, imap }, folder);
1706
+ const result = await backfillFolder(
1707
+ this.#opts.db,
1708
+ folder,
1709
+ this.#opts.cfg,
1710
+ budget,
1711
+ "newer",
1712
+ this.#opts.now,
1713
+ bodyFetcherFor(this.#opts.imap, folder)
1714
+ );
1715
+ embedded += result.embedded;
1716
+ budget -= result.embedded;
1717
+ } catch (err) {
1718
+ log11.warn("sweep failed for folder", {
1719
+ folder,
1720
+ msg: err instanceof Error ? err.message : String(err)
1721
+ });
1722
+ }
1723
+ }
1724
+ } catch (err) {
1725
+ log11.warn("sweep aborted", { msg: err instanceof Error ? err.message : String(err) });
1726
+ } finally {
1727
+ this.#running = false;
919
1728
  }
1729
+ if (embedded > 0) log11.info("background index sweep", { folders: visited, embedded });
1730
+ return { folders: visited, embedded };
920
1731
  }
921
1732
  };
922
1733
 
923
1734
  // src/smtp/client.ts
924
- import nodemailer from "nodemailer";
925
- var log6 = createLogger("mcp-inbox:smtp");
1735
+ import { createTransport } from "nodemailer";
1736
+ var log12 = createLogger("mcp-inbox:smtp");
926
1737
  var SmtpClient = class {
927
1738
  #config;
928
1739
  #transporter = null;
@@ -935,12 +1746,12 @@ var SmtpClient = class {
935
1746
  throw new Error("SmtpClient has been closed");
936
1747
  }
937
1748
  if (this.#transporter) return this.#transporter;
938
- log6.info("creating SMTP transporter", {
1749
+ log12.info("creating SMTP transporter", {
939
1750
  host: this.#config.host,
940
1751
  port: this.#config.port,
941
1752
  secure: this.#config.secure
942
1753
  });
943
- this.#transporter = nodemailer.createTransport({
1754
+ this.#transporter = createTransport({
944
1755
  host: this.#config.host,
945
1756
  port: this.#config.port,
946
1757
  secure: this.#config.secure,
@@ -993,7 +1804,7 @@ import {
993
1804
  // package.json
994
1805
  var package_default = {
995
1806
  name: "@kbzowski/mcp-inbox",
996
- version: "0.5.1",
1807
+ version: "0.6.0",
997
1808
  description: "MCP server exposing IMAP/SMTP email over a fast local cache. Read, search, compose, and manage email from any IMAP provider with near-instant response times via background sync and IDLE push.",
998
1809
  type: "module",
999
1810
  main: "./dist/index.js",
@@ -1057,36 +1868,36 @@ var package_default = {
1057
1868
  release: "changeset publish"
1058
1869
  },
1059
1870
  dependencies: {
1060
- "@modelcontextprotocol/sdk": "^1.20.0",
1871
+ "@modelcontextprotocol/sdk": "^1.32.2",
1061
1872
  "drizzle-orm": "1.0.0-beta.22",
1062
- imapflow: "^1.3.2",
1063
- mailparser: "^3.7.2",
1064
- nodemailer: "^9.0.4",
1065
- zod: "^4.0.0"
1873
+ imapflow: "^2.10.0",
1874
+ mailparser: "^3.14.1",
1875
+ nodemailer: "^10.3.1",
1876
+ "sqlite-vec": "0.1.9",
1877
+ zod: "^4.6.7"
1066
1878
  },
1067
1879
  devDependencies: {
1068
- "@changesets/cli": "^2.27.10",
1069
- "@types/mailparser": "^3.4.5",
1070
- "@types/node": "^26.1.2",
1071
- "@types/nodemailer": "^8.0.0",
1880
+ "@changesets/cli": "^3.0.3",
1881
+ "@types/mailparser": "^3.9.0",
1882
+ "@types/node": "^26.6.6",
1072
1883
  "drizzle-kit": "1.0.0-beta.22",
1073
- esbuild: "^0.28.0",
1074
- lefthook: "^2.1.6",
1075
- oxfmt: "^0.62.0",
1076
- oxlint: "^1.77.0",
1077
- "oxlint-tsgolint": "^7.0.2001",
1078
- testcontainers: "^12.1.0",
1079
- tsx: "^4.19.0",
1884
+ esbuild: "^0.28.2",
1885
+ 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",
1890
+ tsx: "^4.23.15",
1080
1891
  typescript: "^7.0.2",
1081
- vitest: "^4.0.0"
1892
+ vitest: "^5.0.5"
1082
1893
  }
1083
1894
  };
1084
1895
 
1085
1896
  // src/tools/registry.ts
1086
- import { z as z23 } from "zod";
1897
+ import { z as z26 } from "zod";
1087
1898
 
1088
1899
  // src/tools/folders/list-folders.ts
1089
- import { z as z2 } from "zod";
1900
+ import { z as z3 } from "zod";
1090
1901
 
1091
1902
  // src/tools/define-tool.ts
1092
1903
  function defineTool(def) {
@@ -1102,6 +1913,33 @@ function formatFoldersMarkdown(folders2) {
1102
1913
  }
1103
1914
  return lines.join("\n");
1104
1915
  }
1916
+ function formatSemanticResultsMarkdown(rows, pendingIndex) {
1917
+ if (rows.length === 0) return "_No indexed message resembles that query._";
1918
+ const lines = [
1919
+ "| # | Score | Flags | From | Subject | Date | Folder | UID |",
1920
+ "|---|---|---|---|---|---|---|---|"
1921
+ ];
1922
+ rows.forEach((r, i) => {
1923
+ const marks = (r.unseen ? "UNSEEN " : "") + (r.has_attachments ? "\u{1F4CE}" : "");
1924
+ const subject = (r.subject ?? "").replace(/\|/g, "\\|");
1925
+ const from = (r.from ?? "").replace(/\|/g, "\\|");
1926
+ const folder = r.folder.replace(/\|/g, "\\|");
1927
+ const date = r.date === null ? "" : r.date.slice(0, 16).replace("T", " ");
1928
+ const row = `| ${i + 1} | ${r.score.toFixed(3)} | ${marks.trim()} | ${from} | ${subject} | ${date} | ${folder} | ${r.uid} |`;
1929
+ lines.push(r.unseen ? `**${row}**` : row);
1930
+ });
1931
+ lines.push(
1932
+ "",
1933
+ "_Scores are relative cosine similarity, not probabilities: this model rates even strong matches around 0.4-0.6, so judge each result on its own merits rather than against a fixed cutoff. A large gap between consecutive scores says more than any single value._"
1934
+ );
1935
+ if (pendingIndex > 0) {
1936
+ lines.push(
1937
+ "",
1938
+ `_${pendingIndex} message(s) in this folder are not yet indexed; re-run \`imap_index_folder\` to include them._`
1939
+ );
1940
+ }
1941
+ return lines.join("\n");
1942
+ }
1105
1943
  function formatEmailListMarkdown(emails2) {
1106
1944
  if (emails2.length === 0) return "_No emails match._";
1107
1945
  const lines = [
@@ -1121,8 +1959,8 @@ function formatEmailListMarkdown(emails2) {
1121
1959
  }
1122
1960
 
1123
1961
  // src/tools/folders/list-folders.ts
1124
- var Input = z2.object({
1125
- response_format: z2.enum(["markdown", "json"]).default("markdown")
1962
+ var Input = z3.object({
1963
+ response_format: z3.enum(["markdown", "json"]).default("markdown")
1126
1964
  });
1127
1965
  var listFoldersTool = defineTool({
1128
1966
  name: "imap_list_folders",
@@ -1157,7 +1995,7 @@ var listFoldersTool = defineTool({
1157
1995
  });
1158
1996
 
1159
1997
  // src/tools/emails/list-emails.ts
1160
- import { z as z3 } from "zod";
1998
+ import { z as z4 } from "zod";
1161
1999
 
1162
2000
  // src/tools/emails/shared.ts
1163
2001
  import { simpleParser } from "mailparser";
@@ -1224,6 +2062,21 @@ async function syncIfStale(ctx, folder, maxStalenessSec = ctx.cacheConfig.defaul
1224
2062
  }
1225
2063
  return stale;
1226
2064
  }
2065
+ function requireEmbeddings(ctx) {
2066
+ if (ctx.embeddings === null) {
2067
+ throw new EmbeddingError(
2068
+ "EMBEDDING_DISABLED",
2069
+ "Semantic search is not configured on this server (IMAP_EMBEDDINGS_BASE_URL is unset). Use imap_search_emails instead - it searches subject, sender, and body text server-side."
2070
+ );
2071
+ }
2072
+ if (!ctx.vectorsAvailable) {
2073
+ throw new EmbeddingError(
2074
+ "EMBEDDING_INDEX_UNAVAILABLE",
2075
+ "Semantic search is unavailable: the sqlite-vec extension has no build for this platform (win32-arm64 and Alpine/musl are unsupported). Use imap_search_emails instead."
2076
+ );
2077
+ }
2078
+ return ctx.embeddings;
2079
+ }
1227
2080
  function readEnvelopes(ctx, folder, opts) {
1228
2081
  const rows = listEmailsByFolder(ctx.db, folder, opts);
1229
2082
  const total = countEmailsInFolder(ctx.db, folder, opts);
@@ -1332,17 +2185,17 @@ function projectEmailSummary(e) {
1332
2185
  }
1333
2186
 
1334
2187
  // src/tools/emails/list-emails.ts
1335
- var Input2 = z3.object({
1336
- folder: z3.string().min(1).default("INBOX").describe("Folder path to list. Use imap_list_folders to discover paths."),
1337
- limit: z3.number().int().min(1).max(100).default(20),
1338
- offset: z3.number().int().min(0).default(0),
1339
- unseen_only: z3.boolean().default(false),
1340
- since_date: z3.string().date().optional().describe("YYYY-MM-DD. Only return emails received on or after this date."),
1341
- before_date: z3.string().date().optional().describe("YYYY-MM-DD. Only return emails received strictly before this date."),
1342
- max_staleness_seconds: z3.number().int().min(0).optional().describe(
2188
+ var Input2 = z4.object({
2189
+ folder: z4.string().min(1).default("INBOX").describe("Folder path to list. Use imap_list_folders to discover paths."),
2190
+ limit: z4.number().int().min(1).max(100).default(20),
2191
+ offset: z4.number().int().min(0).default(0),
2192
+ unseen_only: z4.boolean().default(false),
2193
+ since_date: z4.string().date().optional().describe("YYYY-MM-DD. Only return emails received on or after this date."),
2194
+ before_date: z4.string().date().optional().describe("YYYY-MM-DD. Only return emails received strictly before this date."),
2195
+ max_staleness_seconds: z4.number().int().min(0).optional().describe(
1343
2196
  "Serve from cache if the folder was synced within this many seconds. Pass 0 to force a fresh sync. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
1344
2197
  ),
1345
- response_format: z3.enum(["markdown", "json"]).default("markdown")
2198
+ response_format: z4.enum(["markdown", "json"]).default("markdown")
1346
2199
  });
1347
2200
  var listEmailsTool = defineTool({
1348
2201
  name: "imap_list_emails",
@@ -1384,16 +2237,16 @@ var listEmailsTool = defineTool({
1384
2237
  });
1385
2238
 
1386
2239
  // src/tools/emails/get-email.ts
1387
- import { z as z4 } from "zod";
1388
- var Input3 = z4.object({
1389
- folder: z4.string().min(1).describe("Folder containing the message."),
1390
- uid: z4.number().int().positive().describe(
2240
+ import { z as z5 } from "zod";
2241
+ var Input3 = z5.object({
2242
+ folder: z5.string().min(1).describe("Folder containing the message."),
2243
+ uid: z5.number().int().positive().describe(
1391
2244
  "IMAP UID of the message. UIDs are folder-scoped - a UID from INBOX cannot be reused with the Sent folder."
1392
2245
  ),
1393
- max_staleness_seconds: z4.number().int().min(0).optional().describe(
2246
+ max_staleness_seconds: z5.number().int().min(0).optional().describe(
1394
2247
  "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
1395
2248
  ),
1396
- response_format: z4.enum(["markdown", "json"]).default("markdown")
2249
+ response_format: z5.enum(["markdown", "json"]).default("markdown")
1397
2250
  });
1398
2251
  var getEmailTool = defineTool({
1399
2252
  name: "imap_get_email",
@@ -1454,7 +2307,7 @@ function formatEmailDetail(e) {
1454
2307
  }
1455
2308
 
1456
2309
  // src/tools/emails/search-emails.ts
1457
- import { z as z5 } from "zod";
2310
+ import { z as z6 } from "zod";
1458
2311
 
1459
2312
  // src/imap/search.ts
1460
2313
  function buildImapSearch(c) {
@@ -1479,47 +2332,47 @@ function buildImapSearch(c) {
1479
2332
  }
1480
2333
 
1481
2334
  // src/tools/emails/search-emails.ts
1482
- var Criteria = z5.lazy(
1483
- () => z5.object({
1484
- subject: z5.string().min(1).optional(),
1485
- from: z5.string().min(1).optional(),
1486
- to: z5.string().min(1).optional(),
1487
- body: z5.string().min(1).optional(),
1488
- unseen: z5.boolean().optional(),
1489
- flagged: z5.boolean().optional(),
1490
- answered: z5.boolean().optional(),
1491
- since: z5.coerce.date().optional(),
1492
- before: z5.coerce.date().optional(),
1493
- larger_than_bytes: z5.number().int().positive().optional(),
1494
- smaller_than_bytes: z5.number().int().positive().optional(),
1495
- or: z5.array(Criteria).min(2).optional(),
2335
+ var Criteria = z6.lazy(
2336
+ () => z6.object({
2337
+ subject: z6.string().min(1).optional(),
2338
+ from: z6.string().min(1).optional(),
2339
+ to: z6.string().min(1).optional(),
2340
+ body: z6.string().min(1).optional(),
2341
+ unseen: z6.boolean().optional(),
2342
+ flagged: z6.boolean().optional(),
2343
+ answered: z6.boolean().optional(),
2344
+ since: z6.coerce.date().optional(),
2345
+ before: z6.coerce.date().optional(),
2346
+ larger_than_bytes: z6.number().int().positive().optional(),
2347
+ smaller_than_bytes: z6.number().int().positive().optional(),
2348
+ or: z6.array(Criteria).min(2).optional(),
1496
2349
  not: Criteria.optional()
1497
2350
  })
1498
2351
  );
1499
- var Input4 = z5.object({
1500
- folder: z5.string().min(1).default("INBOX"),
1501
- subject: z5.string().min(1).optional(),
1502
- from: z5.string().min(1).optional(),
1503
- to: z5.string().min(1).optional(),
1504
- body: z5.string().min(1).optional(),
1505
- unseen: z5.boolean().optional(),
1506
- flagged: z5.boolean().optional().describe("true = starred only, false = unstarred only, omit for no filter."),
1507
- answered: z5.boolean().optional().describe("true = replied-to only, false = not-replied-to only, omit for no filter."),
1508
- since_date: z5.string().date().optional(),
1509
- before_date: z5.string().date().optional(),
1510
- larger_than_bytes: z5.number().int().positive().optional().describe("Only match messages larger than this many bytes."),
1511
- smaller_than_bytes: z5.number().int().positive().optional().describe("Only match messages smaller than this many bytes."),
1512
- or: z5.array(Criteria).min(2).optional().describe(
2352
+ var Input4 = z6.object({
2353
+ folder: z6.string().min(1).default("INBOX"),
2354
+ subject: z6.string().min(1).optional(),
2355
+ from: z6.string().min(1).optional(),
2356
+ to: z6.string().min(1).optional(),
2357
+ body: z6.string().min(1).optional(),
2358
+ unseen: z6.boolean().optional(),
2359
+ flagged: z6.boolean().optional().describe("true = starred only, false = unstarred only, omit for no filter."),
2360
+ answered: z6.boolean().optional().describe("true = replied-to only, false = not-replied-to only, omit for no filter."),
2361
+ since_date: z6.string().date().optional(),
2362
+ before_date: z6.string().date().optional(),
2363
+ larger_than_bytes: z6.number().int().positive().optional().describe("Only match messages larger than this many bytes."),
2364
+ smaller_than_bytes: z6.number().int().positive().optional().describe("Only match messages smaller than this many bytes."),
2365
+ or: z6.array(Criteria).min(2).optional().describe(
1513
2366
  '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)`.'
1514
2367
  ),
1515
2368
  not: Criteria.optional().describe(
1516
2369
  'Sub-criteria that must NOT match. Useful for excluding auto-generated mail, e.g. `{not: {from: "noreply"}}`.'
1517
2370
  ),
1518
- limit: z5.number().int().min(1).max(100).default(20),
1519
- max_staleness_seconds: z5.number().int().min(0).optional().describe(
2371
+ limit: z6.number().int().min(1).max(100).default(20),
2372
+ max_staleness_seconds: z6.number().int().min(0).optional().describe(
1520
2373
  "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
1521
2374
  ),
1522
- response_format: z5.enum(["markdown", "json"]).default("markdown")
2375
+ response_format: z6.enum(["markdown", "json"]).default("markdown")
1523
2376
  }).refine(
1524
2377
  (v) => [
1525
2378
  v.subject,
@@ -1628,8 +2481,205 @@ var searchEmailsTool = defineTool({
1628
2481
  }
1629
2482
  });
1630
2483
 
2484
+ // src/tools/emails/semantic-search.ts
2485
+ import { z as z7 } from "zod";
2486
+ var OVERFETCH_FACTOR = 5;
2487
+ var Input5 = z7.object({
2488
+ query: z7.string().min(1).describe("Natural-language description of the message you are looking for."),
2489
+ folder: z7.string().min(1).optional().describe("Restrict the search to one folder. Omit to search every indexed folder at once."),
2490
+ limit: z7.number().int().min(1).max(50).default(10),
2491
+ since_date: z7.string().date().optional(),
2492
+ before_date: z7.string().date().optional(),
2493
+ max_staleness_seconds: z7.number().int().min(0).optional().describe(
2494
+ "Sync the folder first if its cache is older than this. Ignored when no folder is given. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2495
+ ),
2496
+ response_format: z7.enum(["markdown", "json"]).default("markdown")
2497
+ });
2498
+ var semanticSearchTool = defineTool({
2499
+ name: "imap_semantic_search",
2500
+ description: 'Find messages by meaning rather than by keyword - "the invoice from the hosting provider" can match a message titled "Payment receipt #4417". Ranks cached messages by embedding similarity over their subject, sender, and message text, so it finds a message by what it says even when the subject is useless ("Re: 4417"), and works across languages and paraphrases. Always returns the top `limit` matches, however weak: it never filters, so decide for yourself which of the returned messages actually answer the question and ignore the rest. Searches every indexed folder unless you name one, and each result says which folder it came from. Only folders that imap_index_folder has already covered are searched. A non-zero `pending_index` means some messages are still unindexed and the answer may be incomplete; the server catches up on its own within minutes. For exact words, sender addresses, flags, or text inside message bodies, use imap_search_emails instead: it is faster and searches full bodies server-side.',
2501
+ annotations: {
2502
+ readOnlyHint: true,
2503
+ destructiveHint: false,
2504
+ idempotentHint: true,
2505
+ openWorldHint: true
2506
+ },
2507
+ inputSchema: Input5,
2508
+ handler: async (args, ctx) => {
2509
+ const cfg = requireEmbeddings(ctx);
2510
+ ensureVecTable(ctx.db, cfg.model, cfg.dims);
2511
+ const indexed = indexedFolders(ctx.db);
2512
+ if (indexed.length === 0) {
2513
+ throw new EmbeddingError(
2514
+ "EMBEDDING_NOT_INDEXED",
2515
+ "No folder has been indexed for semantic search yet. Run imap_index_folder first, or use imap_search_emails."
2516
+ );
2517
+ }
2518
+ if (args.folder !== void 0 && !indexed.includes(args.folder)) {
2519
+ throw new EmbeddingError(
2520
+ "EMBEDDING_NOT_INDEXED",
2521
+ `Folder "${args.folder}" is not indexed for semantic search. Run imap_index_folder with folders=["${args.folder}"] first, search the indexed folders instead (${indexed.join(", ")}), or use imap_search_emails.`
2522
+ );
2523
+ }
2524
+ const folders2 = args.folder === void 0 ? indexed : [args.folder];
2525
+ if (args.folder !== void 0) {
2526
+ await syncIfStale(ctx, args.folder, args.max_staleness_seconds);
2527
+ }
2528
+ const remaining = pendingForFolders(ctx.db, folders2);
2529
+ const [queryVector] = await embedTexts([args.query], cfg);
2530
+ if (queryVector === void 0) {
2531
+ throw new EmbeddingError(
2532
+ "EMBEDDING_UNREACHABLE",
2533
+ "The embeddings endpoint returned no vector for the search query."
2534
+ );
2535
+ }
2536
+ const hits = knnSearch(ctx.db, queryVector, args.limit * OVERFETCH_FACTOR, {
2537
+ ...args.folder !== void 0 && { folders: folders2 },
2538
+ ...args.since_date !== void 0 && { sinceMs: Date.parse(args.since_date) },
2539
+ ...args.before_date !== void 0 && { beforeMs: Date.parse(args.before_date) }
2540
+ });
2541
+ const byFolder = /* @__PURE__ */ new Map();
2542
+ for (const hit of hits) {
2543
+ const bucket = byFolder.get(hit.folder);
2544
+ if (bucket === void 0) byFolder.set(hit.folder, [hit.uid]);
2545
+ else bucket.push(hit.uid);
2546
+ }
2547
+ const cached = /* @__PURE__ */ new Map();
2548
+ for (const [folder, uids] of byFolder) {
2549
+ cached.set(folder, getEmailsByUids(ctx.db, folder, uids));
2550
+ }
2551
+ const ranked = hits.map((hit) => ({ hit, email: cached.get(hit.folder)?.get(hit.uid) })).filter((r) => r.email !== void 0).slice(0, args.limit);
2552
+ const structured = {
2553
+ folders: folders2,
2554
+ query: args.query,
2555
+ returned: ranked.length,
2556
+ pending_index: remaining,
2557
+ emails: ranked.map(
2558
+ ({ hit, email }) => Object.assign(projectEmailSummary(email), {
2559
+ score: Number((1 - hit.distance).toFixed(4))
2560
+ })
2561
+ )
2562
+ };
2563
+ const text2 = args.response_format === "json" ? JSON.stringify(structured, null, 2) : formatSemanticResultsMarkdown(structured.emails, remaining);
2564
+ return {
2565
+ content: [{ type: "text", text: text2 }],
2566
+ structuredContent: structured
2567
+ };
2568
+ }
2569
+ });
2570
+
2571
+ // src/tools/emails/index-folder.ts
2572
+ import { z as z8 } from "zod";
2573
+ var Input6 = z8.object({
2574
+ folders: z8.array(z8.string().min(1)).min(1).max(50).default(["INBOX"]).describe("Folders to index. They share the max_messages budget for this call."),
2575
+ max_messages: z8.number().int().min(1).max(5e4).default(500).describe(
2576
+ "Cap on how many messages are embedded in this call, shared across all listed folders and spent newest-first. Measured at roughly four messages per second, so 500 takes about two minutes; raise it only if your client tolerates a longer tool call. Re-run the tool to continue where it left off."
2577
+ ),
2578
+ max_staleness_seconds: z8.number().int().min(0).optional().describe(
2579
+ "Sync each folder first if its cache is older than this. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2580
+ ),
2581
+ response_format: z8.enum(["markdown", "json"]).default("markdown")
2582
+ });
2583
+ var indexFolderTool = defineTool({
2584
+ name: "imap_index_folder",
2585
+ description: "Build the local semantic-search index for one or more folders by embedding each message's subject, sender, and body text through the configured embeddings API. Attachments are never downloaded. Opt-in per folder and safe to re-run: already-indexed messages are skipped, so a large mailbox can be indexed across several calls, and `remaining > 0` means you should call it again. Required before imap_semantic_search can use a folder. Changing the embedding model, or upgrading to a release whose index format changed, discards the index and re-embeds it on the next call.",
2586
+ annotations: {
2587
+ readOnlyHint: false,
2588
+ destructiveHint: false,
2589
+ idempotentHint: true,
2590
+ openWorldHint: true
2591
+ },
2592
+ inputSchema: Input6,
2593
+ handler: async (args, ctx) => {
2594
+ const cfg = requireEmbeddings(ctx);
2595
+ ensureVecTable(ctx.db, cfg.model, cfg.dims);
2596
+ const reports = [];
2597
+ let budget = args.max_messages;
2598
+ for (const folder of args.folders) {
2599
+ const report = await indexOne(ctx, cfg, folder, budget, args.max_staleness_seconds);
2600
+ reports.push(report);
2601
+ budget -= report.embedded;
2602
+ if (budget <= 0) break;
2603
+ }
2604
+ const structured = {
2605
+ model: cfg.model,
2606
+ dims: cfg.dims,
2607
+ embedded: sum(reports, (r) => r.embedded),
2608
+ bodies_indexed: sum(reports, (r) => r.bodies_indexed),
2609
+ indexed_total: sum(reports, (r) => r.indexed_total),
2610
+ remaining: sum(reports, (r) => r.remaining),
2611
+ complete: reports.length === args.folders.length && reports.every((r) => r.complete),
2612
+ folders: reports
2613
+ };
2614
+ const text2 = args.response_format === "json" ? JSON.stringify(structured, null, 2) : formatIndexMarkdown(structured);
2615
+ return {
2616
+ content: [{ type: "text", text: text2 }],
2617
+ structuredContent: structured
2618
+ };
2619
+ }
2620
+ });
2621
+ async function indexOne(ctx, cfg, folder, budget, maxStalenessSeconds) {
2622
+ await syncIfStale(ctx, folder, maxStalenessSeconds);
2623
+ if (getVecState(ctx.db, folder) === void 0) {
2624
+ upsertVecState(ctx.db, {
2625
+ folder,
2626
+ model: cfg.model,
2627
+ dims: cfg.dims,
2628
+ fromUid: 0,
2629
+ toUid: 0,
2630
+ indexedAt: ctx.now()
2631
+ });
2632
+ }
2633
+ const pruned = pruneOrphanedVectors(ctx.db, folder);
2634
+ const result = await backfillFolder(
2635
+ ctx.db,
2636
+ folder,
2637
+ cfg,
2638
+ budget,
2639
+ "both",
2640
+ ctx.now,
2641
+ bodyFetcherFor(ctx.imap, folder)
2642
+ );
2643
+ return {
2644
+ folder,
2645
+ embedded: result.embedded,
2646
+ bodies_indexed: result.bodiesIndexed,
2647
+ pruned,
2648
+ indexed_total: countVectors(ctx.db, folder),
2649
+ remaining: result.remaining,
2650
+ complete: result.remaining === 0
2651
+ };
2652
+ }
2653
+ function sum(reports, pick) {
2654
+ return reports.reduce((total, r) => total + pick(r), 0);
2655
+ }
2656
+ function formatIndexMarkdown(s) {
2657
+ const lines = [
2658
+ `Indexed ${String(s.folders.length)} folder(s) for semantic search using \`${s.model}\`.`,
2659
+ "",
2660
+ "| Folder | Embedded | With text | Indexed | Pending |",
2661
+ "|---|---|---|---|---|"
2662
+ ];
2663
+ for (const r of s.folders) {
2664
+ lines.push(
2665
+ `| ${r.folder} | ${r.embedded} | ${r.bodies_indexed} | ${r.indexed_total} | ${r.remaining} |`
2666
+ );
2667
+ }
2668
+ lines.push("");
2669
+ if (s.embedded > 0 && s.bodies_indexed === 0) {
2670
+ lines.push(
2671
+ "This server did not return message text, so only subjects and senders were indexed.",
2672
+ ""
2673
+ );
2674
+ }
2675
+ lines.push(
2676
+ s.complete ? "Everything listed is fully indexed. `imap_semantic_search` is ready to use." : "The budget ran out before finishing. Re-run `imap_index_folder` to continue."
2677
+ );
2678
+ return lines.join("\n");
2679
+ }
2680
+
1631
2681
  // src/tools/emails/mark-read.ts
1632
- import { z as z6 } from "zod";
2682
+ import { z as z9 } from "zod";
1633
2683
 
1634
2684
  // src/tools/emails/flags.ts
1635
2685
  async function applyFlags(ctx, folder, uids, change) {
@@ -1660,9 +2710,9 @@ async function applyFlags(ctx, folder, uids, change) {
1660
2710
  }
1661
2711
 
1662
2712
  // src/tools/emails/mark-read.ts
1663
- var Input5 = z6.object({
1664
- folder: z6.string().min(1).describe("Folder containing the message."),
1665
- uid: z6.number().int().positive().describe("IMAP UID of the message. UIDs are folder-scoped.")
2713
+ var Input7 = z9.object({
2714
+ folder: z9.string().min(1).describe("Folder containing the message."),
2715
+ uid: z9.number().int().positive().describe("IMAP UID of the message. UIDs are folder-scoped.")
1666
2716
  });
1667
2717
  function updateSeenFlag(ctx, folder, uid, want) {
1668
2718
  return applyFlags(
@@ -1681,7 +2731,7 @@ var markReadTool = defineTool({
1681
2731
  idempotentHint: true,
1682
2732
  openWorldHint: true
1683
2733
  },
1684
- inputSchema: Input5,
2734
+ inputSchema: Input7,
1685
2735
  handler: async (args, ctx) => {
1686
2736
  await updateSeenFlag(ctx, args.folder, args.uid, "add");
1687
2737
  return {
@@ -1704,7 +2754,7 @@ var markUnreadTool = defineTool({
1704
2754
  idempotentHint: true,
1705
2755
  openWorldHint: true
1706
2756
  },
1707
- inputSchema: Input5,
2757
+ inputSchema: Input7,
1708
2758
  handler: async (args, ctx) => {
1709
2759
  await updateSeenFlag(ctx, args.folder, args.uid, "remove");
1710
2760
  return {
@@ -1720,10 +2770,10 @@ var markUnreadTool = defineTool({
1720
2770
  });
1721
2771
 
1722
2772
  // src/tools/emails/mark-read-multiple.ts
1723
- import { z as z7 } from "zod";
1724
- var Input6 = z7.object({
1725
- folder: z7.string().min(1).describe("Folder containing the messages."),
1726
- uids: z7.array(z7.number().int().positive()).min(1).max(500).describe(
2773
+ import { z as z10 } from "zod";
2774
+ var Input8 = z10.object({
2775
+ folder: z10.string().min(1).describe("Folder containing the messages."),
2776
+ uids: z10.array(z10.number().int().positive()).min(1).max(500).describe(
1727
2777
  "UIDs of messages to flip. Max 500 per call - chunk your own list for larger batches."
1728
2778
  )
1729
2779
  });
@@ -1744,7 +2794,7 @@ var markReadMultipleTool = defineTool({
1744
2794
  idempotentHint: true,
1745
2795
  openWorldHint: true
1746
2796
  },
1747
- inputSchema: Input6,
2797
+ inputSchema: Input8,
1748
2798
  handler: async (args, ctx) => {
1749
2799
  await updateSeenFlagBulk(ctx, args.folder, args.uids, "add");
1750
2800
  return {
@@ -1772,7 +2822,7 @@ var markUnreadMultipleTool = defineTool({
1772
2822
  idempotentHint: true,
1773
2823
  openWorldHint: true
1774
2824
  },
1775
- inputSchema: Input6,
2825
+ inputSchema: Input8,
1776
2826
  handler: async (args, ctx) => {
1777
2827
  await updateSeenFlagBulk(ctx, args.folder, args.uids, "remove");
1778
2828
  return {
@@ -1793,13 +2843,13 @@ var markUnreadMultipleTool = defineTool({
1793
2843
  });
1794
2844
 
1795
2845
  // src/tools/emails/set-flags.ts
1796
- import { z as z8 } from "zod";
1797
- var Flag = z8.enum(["\\Flagged", "\\Answered"]);
1798
- var Input7 = z8.object({
1799
- folder: z8.string().min(1).describe("Folder containing the messages."),
1800
- uids: z8.array(z8.number().int().positive()).min(1).max(500).describe("UIDs to change. Max 500 per call - chunk your own list for larger batches."),
1801
- add: z8.array(Flag).optional().describe("Flags to set. \\Flagged is the star / follow-up marker in mail clients."),
1802
- remove: z8.array(Flag).optional().describe("Flags to clear.")
2846
+ import { z as z11 } from "zod";
2847
+ var Flag = z11.enum(["\\Flagged", "\\Answered"]);
2848
+ var Input9 = z11.object({
2849
+ folder: z11.string().min(1).describe("Folder containing the messages."),
2850
+ uids: z11.array(z11.number().int().positive()).min(1).max(500).describe("UIDs to change. Max 500 per call - chunk your own list for larger batches."),
2851
+ add: z11.array(Flag).optional().describe("Flags to set. \\Flagged is the star / follow-up marker in mail clients."),
2852
+ remove: z11.array(Flag).optional().describe("Flags to clear.")
1803
2853
  }).refine((v) => (v.add?.length ?? 0) > 0 || (v.remove?.length ?? 0) > 0, {
1804
2854
  message: "Provide at least one flag in `add` or `remove`."
1805
2855
  }).refine((v) => !v.add?.some((f) => v.remove?.includes(f)), {
@@ -1814,7 +2864,7 @@ var setFlagsTool = defineTool({
1814
2864
  idempotentHint: true,
1815
2865
  openWorldHint: true
1816
2866
  },
1817
- inputSchema: Input7,
2867
+ inputSchema: Input9,
1818
2868
  handler: async (args, ctx) => {
1819
2869
  const change = {
1820
2870
  ...args.add !== void 0 && { add: args.add },
@@ -1845,11 +2895,11 @@ var setFlagsTool = defineTool({
1845
2895
  });
1846
2896
 
1847
2897
  // src/tools/emails/move-to-folder.ts
1848
- import { z as z9 } from "zod";
1849
- var Input8 = z9.object({
1850
- folder: z9.string().min(1).describe("Current folder of the message."),
1851
- uid: z9.number().int().positive().describe("IMAP UID of the message to move."),
1852
- destination: z9.string().min(1).describe(
2898
+ import { z as z12 } from "zod";
2899
+ var Input10 = z12.object({
2900
+ folder: z12.string().min(1).describe("Current folder of the message."),
2901
+ uid: z12.number().int().positive().describe("IMAP UID of the message to move."),
2902
+ destination: z12.string().min(1).describe(
1853
2903
  "Target folder path. Use imap_list_folders to discover valid destinations. Must exist on the server."
1854
2904
  )
1855
2905
  });
@@ -1863,7 +2913,7 @@ var moveToFolderTool = defineTool({
1863
2913
  idempotentHint: false,
1864
2914
  openWorldHint: true
1865
2915
  },
1866
- inputSchema: Input8,
2916
+ inputSchema: Input10,
1867
2917
  handler: async (args, ctx) => {
1868
2918
  const imap = await ctx.imap.connection();
1869
2919
  const lock = await imap.getMailboxLock(args.folder);
@@ -1901,11 +2951,11 @@ var moveToFolderTool = defineTool({
1901
2951
  });
1902
2952
 
1903
2953
  // src/tools/emails/move-multiple.ts
1904
- import { z as z10 } from "zod";
1905
- var Input9 = z10.object({
1906
- folder: z10.string().min(1).describe("Current folder of the messages."),
1907
- uids: z10.array(z10.number().int().positive()).min(1).max(500).describe("UIDs to move. Max 500 per call."),
1908
- destination: z10.string().min(1).describe("Target folder. Must exist on the server.")
2954
+ import { z as z13 } from "zod";
2955
+ var Input11 = z13.object({
2956
+ folder: z13.string().min(1).describe("Current folder of the messages."),
2957
+ uids: z13.array(z13.number().int().positive()).min(1).max(500).describe("UIDs to move. Max 500 per call."),
2958
+ destination: z13.string().min(1).describe("Target folder. Must exist on the server.")
1909
2959
  });
1910
2960
  var moveMultipleTool = defineTool({
1911
2961
  name: "imap_move_multiple",
@@ -1916,7 +2966,7 @@ var moveMultipleTool = defineTool({
1916
2966
  idempotentHint: false,
1917
2967
  openWorldHint: true
1918
2968
  },
1919
- inputSchema: Input9,
2969
+ inputSchema: Input11,
1920
2970
  handler: async (args, ctx) => {
1921
2971
  const imap = await ctx.imap.connection();
1922
2972
  const lock = await imap.getMailboxLock(args.folder);
@@ -1953,11 +3003,11 @@ var moveMultipleTool = defineTool({
1953
3003
  });
1954
3004
 
1955
3005
  // src/tools/emails/delete-email.ts
1956
- import { z as z11 } from "zod";
1957
- var Input10 = z11.object({
1958
- folder: z11.string().min(1).describe("Folder containing the message to delete."),
1959
- uid: z11.number().int().positive().describe("IMAP UID of the message to delete."),
1960
- hard_delete: z11.boolean().default(false).describe(
3006
+ import { z as z14 } from "zod";
3007
+ var Input12 = z14.object({
3008
+ folder: z14.string().min(1).describe("Folder containing the message to delete."),
3009
+ uid: z14.number().int().positive().describe("IMAP UID of the message to delete."),
3010
+ hard_delete: z14.boolean().default(false).describe(
1961
3011
  "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."
1962
3012
  )
1963
3013
  });
@@ -1970,7 +3020,7 @@ var deleteEmailTool = defineTool({
1970
3020
  idempotentHint: false,
1971
3021
  openWorldHint: true
1972
3022
  },
1973
- inputSchema: Input10,
3023
+ inputSchema: Input12,
1974
3024
  handler: async (args, ctx) => {
1975
3025
  const imap = await ctx.imap.connection();
1976
3026
  if (args.hard_delete) {
@@ -2038,11 +3088,11 @@ var deleteEmailTool = defineTool({
2038
3088
  });
2039
3089
 
2040
3090
  // src/tools/emails/delete-multiple.ts
2041
- import { z as z12 } from "zod";
2042
- var Input11 = z12.object({
2043
- folder: z12.string().min(1).describe("Folder containing the messages to delete."),
2044
- uids: z12.array(z12.number().int().positive()).min(1).max(500).describe("UIDs to delete. Max 500 per call."),
2045
- hard_delete: z12.boolean().default(false).describe(
3091
+ import { z as z15 } from "zod";
3092
+ var Input13 = z15.object({
3093
+ folder: z15.string().min(1).describe("Folder containing the messages to delete."),
3094
+ uids: z15.array(z15.number().int().positive()).min(1).max(500).describe("UIDs to delete. Max 500 per call."),
3095
+ hard_delete: z15.boolean().default(false).describe(
2046
3096
  "When false (default), messages move to the server Trash and can be recovered. When true, they are permanently expunged."
2047
3097
  )
2048
3098
  });
@@ -2055,7 +3105,7 @@ var deleteMultipleTool = defineTool({
2055
3105
  idempotentHint: false,
2056
3106
  openWorldHint: true
2057
3107
  },
2058
- inputSchema: Input11,
3108
+ inputSchema: Input13,
2059
3109
  handler: async (args, ctx) => {
2060
3110
  const imap = await ctx.imap.connection();
2061
3111
  if (args.hard_delete) {
@@ -2125,17 +3175,17 @@ var deleteMultipleTool = defineTool({
2125
3175
  });
2126
3176
 
2127
3177
  // src/tools/drafts/list-drafts.ts
2128
- import { z as z13 } from "zod";
2129
- var Input12 = z13.object({
2130
- folder: z13.string().min(1).optional().describe(
3178
+ import { z as z16 } from "zod";
3179
+ var Input14 = z16.object({
3180
+ folder: z16.string().min(1).optional().describe(
2131
3181
  "Optional explicit Drafts folder path. If omitted, mcp-inbox auto-detects via RFC 6154 SPECIAL-USE."
2132
3182
  ),
2133
- limit: z13.number().int().min(1).max(100).default(20),
2134
- offset: z13.number().int().min(0).default(0),
2135
- max_staleness_seconds: z13.number().int().min(0).optional().describe(
3183
+ limit: z16.number().int().min(1).max(100).default(20),
3184
+ offset: z16.number().int().min(0).default(0),
3185
+ max_staleness_seconds: z16.number().int().min(0).optional().describe(
2136
3186
  "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2137
3187
  ),
2138
- response_format: z13.enum(["markdown", "json"]).default("markdown")
3188
+ response_format: z16.enum(["markdown", "json"]).default("markdown")
2139
3189
  });
2140
3190
  var listDraftsTool = defineTool({
2141
3191
  name: "imap_list_drafts",
@@ -2146,7 +3196,7 @@ var listDraftsTool = defineTool({
2146
3196
  idempotentHint: true,
2147
3197
  openWorldHint: true
2148
3198
  },
2149
- inputSchema: Input12,
3199
+ inputSchema: Input14,
2150
3200
  handler: async (args, ctx) => {
2151
3201
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2152
3202
  const didSync = await syncIfStale(ctx, folder, args.max_staleness_seconds);
@@ -2173,14 +3223,14 @@ ${formatEmailListMarkdown(rows)}`;
2173
3223
  });
2174
3224
 
2175
3225
  // src/tools/drafts/get-draft.ts
2176
- import { z as z14 } from "zod";
2177
- var Input13 = z14.object({
2178
- uid: z14.number().int().positive().describe("IMAP UID of the draft in the Drafts folder. Use imap_list_drafts to discover UIDs."),
2179
- folder: z14.string().min(1).optional().describe("Optional explicit Drafts folder path. Auto-detected from SPECIAL-USE when omitted."),
2180
- max_staleness_seconds: z14.number().int().min(0).optional().describe(
3226
+ import { z as z17 } from "zod";
3227
+ var Input15 = z17.object({
3228
+ uid: z17.number().int().positive().describe("IMAP UID of the draft in the Drafts folder. Use imap_list_drafts to discover UIDs."),
3229
+ folder: z17.string().min(1).optional().describe("Optional explicit Drafts folder path. Auto-detected from SPECIAL-USE when omitted."),
3230
+ max_staleness_seconds: z17.number().int().min(0).optional().describe(
2181
3231
  "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2182
3232
  ),
2183
- response_format: z14.enum(["markdown", "json"]).default("markdown")
3233
+ response_format: z17.enum(["markdown", "json"]).default("markdown")
2184
3234
  });
2185
3235
  var getDraftTool = defineTool({
2186
3236
  name: "imap_get_draft",
@@ -2191,7 +3241,7 @@ var getDraftTool = defineTool({
2191
3241
  idempotentHint: true,
2192
3242
  openWorldHint: true
2193
3243
  },
2194
- inputSchema: Input13,
3244
+ inputSchema: Input15,
2195
3245
  handler: async (args, ctx) => {
2196
3246
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2197
3247
  const envelope = await ensureEnvelopeCached(ctx, folder, args.uid, args.max_staleness_seconds);
@@ -2226,7 +3276,7 @@ function formatDraftMarkdown(d) {
2226
3276
  }
2227
3277
 
2228
3278
  // src/tools/drafts/create-draft.ts
2229
- import { z as z16 } from "zod";
3279
+ import { z as z19 } from "zod";
2230
3280
 
2231
3281
  // src/imap/mime-builder.ts
2232
3282
  import MailComposer from "nodemailer/lib/mail-composer/index.js";
@@ -2250,16 +3300,16 @@ async function buildRawMessage(input) {
2250
3300
  }
2251
3301
 
2252
3302
  // src/tools/compose-schema.ts
2253
- import { z as z15 } from "zod";
2254
- var AddressList = z15.union([z15.string().min(1), z15.array(z15.string().min(1)).min(1)]);
2255
- var AttachmentInput = z15.object({
2256
- filename: z15.string().min(1).describe('Name the recipient sees, e.g. "invoice.pdf".'),
2257
- content_base64: z15.base64().describe(
3303
+ import { z as z18 } from "zod";
3304
+ var AddressList = z18.union([z18.string().min(1), z18.array(z18.string().min(1)).min(1).max(500)]);
3305
+ var AttachmentInput = z18.object({
3306
+ filename: z18.string().min(1).describe('Name the recipient sees, e.g. "invoice.pdf".'),
3307
+ content_base64: z18.base64().describe(
2258
3308
  "Base64-encoded file bytes. These pass through the model context, so a 2 MB PDF costs roughly 2.7M characters - prefer imap_forward when relaying a file you did not create."
2259
3309
  ),
2260
- content_type: z15.string().min(1).optional().describe("MIME type. Omit to let the type be derived from `filename`.")
3310
+ content_type: z18.string().min(1).optional().describe("MIME type. Omit to let the type be derived from `filename`.")
2261
3311
  });
2262
- var AttachmentList = z15.array(AttachmentInput).optional();
3312
+ var AttachmentList = z18.array(AttachmentInput).max(20).optional();
2263
3313
  function toMessageAttachments(input) {
2264
3314
  if (input === void 0) return void 0;
2265
3315
  return input.map((a) => ({
@@ -2270,17 +3320,17 @@ function toMessageAttachments(input) {
2270
3320
  }
2271
3321
 
2272
3322
  // src/tools/drafts/create-draft.ts
2273
- var Input14 = z16.object({
3323
+ var Input16 = z19.object({
2274
3324
  to: AddressList.describe("Recipient email address or array of addresses."),
2275
- subject: z16.string(),
2276
- body: z16.string().optional().describe("Plain-text body."),
2277
- html: z16.string().optional().describe("HTML body (combined with text via multipart/alternative)."),
3325
+ subject: z19.string(),
3326
+ body: z19.string().optional().describe("Plain-text body."),
3327
+ html: z19.string().optional().describe("HTML body (combined with text via multipart/alternative)."),
2278
3328
  cc: AddressList.optional(),
2279
3329
  bcc: AddressList.optional(),
2280
- from: z16.string().min(1).optional().describe(
3330
+ from: z19.string().min(1).optional().describe(
2281
3331
  "Sender address. Defaults to IMAP_USER. Some providers reject mismatched From headers."
2282
3332
  ),
2283
- folder: z16.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted."),
3333
+ folder: z19.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted."),
2284
3334
  attachments: AttachmentList
2285
3335
  });
2286
3336
  var createDraftTool = defineTool({
@@ -2292,7 +3342,7 @@ var createDraftTool = defineTool({
2292
3342
  idempotentHint: false,
2293
3343
  openWorldHint: true
2294
3344
  },
2295
- inputSchema: Input14,
3345
+ inputSchema: Input16,
2296
3346
  handler: async (args, ctx) => {
2297
3347
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2298
3348
  const attachments = toMessageAttachments(args.attachments);
@@ -2334,17 +3384,17 @@ var createDraftTool = defineTool({
2334
3384
  });
2335
3385
 
2336
3386
  // src/tools/drafts/update-draft.ts
2337
- import { z as z17 } from "zod";
2338
- var Input15 = z17.object({
2339
- uid: z17.number().int().positive().describe("UID of the existing draft to replace. Use imap_list_drafts to find it."),
3387
+ import { z as z20 } from "zod";
3388
+ var Input17 = z20.object({
3389
+ uid: z20.number().int().positive().describe("UID of the existing draft to replace. Use imap_list_drafts to find it."),
2340
3390
  to: AddressList,
2341
- subject: z17.string(),
2342
- body: z17.string().optional(),
2343
- html: z17.string().optional(),
3391
+ subject: z20.string(),
3392
+ body: z20.string().optional(),
3393
+ html: z20.string().optional(),
2344
3394
  cc: AddressList.optional(),
2345
3395
  bcc: AddressList.optional(),
2346
- from: z17.string().min(1).optional(),
2347
- folder: z17.string().min(1).optional(),
3396
+ from: z20.string().min(1).optional(),
3397
+ folder: z20.string().min(1).optional(),
2348
3398
  attachments: AttachmentList
2349
3399
  });
2350
3400
  var updateDraftTool = defineTool({
@@ -2357,7 +3407,7 @@ var updateDraftTool = defineTool({
2357
3407
  idempotentHint: false,
2358
3408
  openWorldHint: true
2359
3409
  },
2360
- inputSchema: Input15,
3410
+ inputSchema: Input17,
2361
3411
  handler: async (args, ctx) => {
2362
3412
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2363
3413
  const attachments = toMessageAttachments(args.attachments);
@@ -2431,7 +3481,7 @@ var updateDraftTool = defineTool({
2431
3481
  });
2432
3482
 
2433
3483
  // src/tools/send/send-email.ts
2434
- import { z as z18 } from "zod";
3484
+ import { z as z21 } from "zod";
2435
3485
 
2436
3486
  // src/tools/send/shared.ts
2437
3487
  function normalizeAddrs(value) {
@@ -2473,14 +3523,14 @@ function flattenCompose(args) {
2473
3523
  }
2474
3524
 
2475
3525
  // src/tools/send/send-email.ts
2476
- var Input16 = z18.object({
3526
+ var Input18 = z21.object({
2477
3527
  to: AddressList.describe("Recipient email address or array of addresses."),
2478
- subject: z18.string(),
2479
- body: z18.string().optional().describe("Plain-text body."),
2480
- html: z18.string().optional().describe("HTML body (sent as multipart/alternative with text)."),
3528
+ subject: z21.string(),
3529
+ body: z21.string().optional().describe("Plain-text body."),
3530
+ html: z21.string().optional().describe("HTML body (sent as multipart/alternative with text)."),
2481
3531
  cc: AddressList.optional(),
2482
3532
  bcc: AddressList.optional(),
2483
- from: z18.string().min(1).optional().describe(
3533
+ from: z21.string().min(1).optional().describe(
2484
3534
  "Sender address. Defaults to IMAP_USER. Providers like Gmail and Fastmail reject mismatched From unless the address is a verified alias."
2485
3535
  ),
2486
3536
  attachments: AttachmentList
@@ -2494,7 +3544,7 @@ var sendEmailTool = defineTool({
2494
3544
  idempotentHint: false,
2495
3545
  openWorldHint: true
2496
3546
  },
2497
- inputSchema: Input16,
3547
+ inputSchema: Input18,
2498
3548
  handler: async (args, ctx) => {
2499
3549
  const compose = flattenCompose({
2500
3550
  ...args.from !== void 0 && { from: args.from },
@@ -2543,11 +3593,11 @@ var sendEmailTool = defineTool({
2543
3593
  });
2544
3594
 
2545
3595
  // src/tools/send/send-draft.ts
2546
- import { z as z19 } from "zod";
3596
+ import { z as z22 } from "zod";
2547
3597
  import { simpleParser as simpleParser2 } from "mailparser";
2548
- var Input17 = z19.object({
2549
- uid: z19.number().int().positive().describe("UID of the draft to send."),
2550
- folder: z19.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted.")
3598
+ var Input19 = z22.object({
3599
+ uid: z22.number().int().positive().describe("UID of the draft to send."),
3600
+ folder: z22.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted.")
2551
3601
  });
2552
3602
  var sendDraftTool = defineTool({
2553
3603
  name: "imap_send_draft",
@@ -2558,7 +3608,7 @@ var sendDraftTool = defineTool({
2558
3608
  idempotentHint: false,
2559
3609
  openWorldHint: true
2560
3610
  },
2561
- inputSchema: Input17,
3611
+ inputSchema: Input19,
2562
3612
  handler: async (args, ctx) => {
2563
3613
  const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
2564
3614
  const imap = await ctx.imap.connection();
@@ -2658,23 +3708,23 @@ function addressList(field) {
2658
3708
  }
2659
3709
 
2660
3710
  // src/tools/send/reply.ts
2661
- import { z as z20 } from "zod";
2662
- var Input18 = z20.object({
2663
- folder: z20.string().min(1).describe("Folder of the original message."),
2664
- uid: z20.number().int().positive().describe("UID of the message being replied to."),
2665
- body: z20.string().optional(),
2666
- html: z20.string().optional(),
3711
+ import { z as z23 } from "zod";
3712
+ var Input20 = z23.object({
3713
+ folder: z23.string().min(1).describe("Folder of the original message."),
3714
+ uid: z23.number().int().positive().describe("UID of the message being replied to."),
3715
+ body: z23.string().optional(),
3716
+ html: z23.string().optional(),
2667
3717
  cc: AddressList.optional(),
2668
3718
  bcc: AddressList.optional(),
2669
- reply_all: z20.boolean().default(false).describe(
3719
+ reply_all: z23.boolean().default(false).describe(
2670
3720
  "When true, CC the original To + Cc recipients (minus the sender). When false, reply only to the original From."
2671
3721
  ),
2672
- from: z20.string().min(1).optional(),
2673
- max_staleness_seconds: z20.number().int().min(0).optional().describe(
3722
+ from: z23.string().min(1).optional(),
3723
+ max_staleness_seconds: z23.number().int().min(0).optional().describe(
2674
3724
  "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2675
3725
  ),
2676
3726
  attachments: AttachmentList,
2677
- mark_answered: z20.boolean().default(true).describe(
3727
+ mark_answered: z23.boolean().default(true).describe(
2678
3728
  "Set \\Answered on the original after sending, so the thread shows as replied in the user mail client. Never fails the send - problems are reported in mark_answered_error."
2679
3729
  )
2680
3730
  });
@@ -2687,7 +3737,7 @@ var replyTool = defineTool({
2687
3737
  idempotentHint: false,
2688
3738
  openWorldHint: true
2689
3739
  },
2690
- inputSchema: Input18,
3740
+ inputSchema: Input20,
2691
3741
  handler: async (args, ctx) => {
2692
3742
  const original = await ensureEnvelopeCached(
2693
3743
  ctx,
@@ -2820,18 +3870,18 @@ function dedupeAddrs(addrs, exclude) {
2820
3870
  }
2821
3871
 
2822
3872
  // src/tools/send/forward.ts
2823
- import { z as z21 } from "zod";
2824
- var Input19 = z21.object({
2825
- folder: z21.string().min(1).describe("Folder of the original message."),
2826
- uid: z21.number().int().positive().describe("UID of the message to forward."),
3873
+ import { z as z24 } from "zod";
3874
+ var Input21 = z24.object({
3875
+ folder: z24.string().min(1).describe("Folder of the original message."),
3876
+ uid: z24.number().int().positive().describe("UID of the message to forward."),
2827
3877
  to: AddressList.describe("Recipient(s) to forward to."),
2828
- body: z21.string().optional().describe(
3878
+ body: z24.string().optional().describe(
2829
3879
  'Optional prefix body (e.g. "FYI, thought you should see this."). Quoted original follows.'
2830
3880
  ),
2831
3881
  cc: AddressList.optional(),
2832
3882
  bcc: AddressList.optional(),
2833
- from: z21.string().min(1).optional(),
2834
- max_staleness_seconds: z21.number().int().min(0).optional().describe(
3883
+ from: z24.string().min(1).optional(),
3884
+ max_staleness_seconds: z24.number().int().min(0).optional().describe(
2835
3885
  "Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
2836
3886
  ),
2837
3887
  attachments: AttachmentList.describe(
@@ -2847,7 +3897,7 @@ var forwardTool = defineTool({
2847
3897
  idempotentHint: false,
2848
3898
  openWorldHint: true
2849
3899
  },
2850
- inputSchema: Input19,
3900
+ inputSchema: Input21,
2851
3901
  handler: async (args, ctx) => {
2852
3902
  const original = await ensureEnvelopeCached(
2853
3903
  ctx,
@@ -2939,16 +3989,16 @@ function escapeHtml(s) {
2939
3989
  }
2940
3990
 
2941
3991
  // src/tools/attachments/get-attachment.ts
2942
- import { z as z22 } from "zod";
3992
+ import { z as z25 } from "zod";
2943
3993
  import { simpleParser as simpleParser3 } from "mailparser";
2944
- var Input20 = z22.object({
2945
- folder: z22.string().min(1).describe("Folder containing the message."),
2946
- uid: z22.number().int().positive().describe("IMAP UID of the message."),
2947
- filename: z22.string().min(1).optional().describe(
3994
+ var Input22 = z25.object({
3995
+ folder: z25.string().min(1).describe("Folder containing the message."),
3996
+ uid: z25.number().int().positive().describe("IMAP UID of the message."),
3997
+ filename: z25.string().min(1).optional().describe(
2948
3998
  "Filename of the attachment to fetch. First match wins if the message has multiple attachments with the same name - use part_id to disambiguate."
2949
3999
  ),
2950
- part_id: z22.string().min(1).optional().describe('MIME part ID (e.g. "1.2"). Use when multiple parts share a filename.'),
2951
- max_inline_mb: z22.number().int().min(1).max(50).default(5).describe(
4000
+ part_id: z25.string().min(1).optional().describe('MIME part ID (e.g. "1.2"). Use when multiple parts share a filename.'),
4001
+ max_inline_mb: z25.number().int().min(1).max(50).default(5).describe(
2952
4002
  "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."
2953
4003
  )
2954
4004
  }).refine((v) => v.filename !== void 0 || v.part_id !== void 0, {
@@ -2963,7 +4013,7 @@ var getAttachmentTool = defineTool({
2963
4013
  idempotentHint: true,
2964
4014
  openWorldHint: true
2965
4015
  },
2966
- inputSchema: Input20,
4016
+ inputSchema: Input22,
2967
4017
  handler: async (args, ctx) => {
2968
4018
  const imap = await ctx.imap.connection();
2969
4019
  const lock = await imap.getMailboxLock(args.folder);
@@ -3081,6 +4131,9 @@ var tools = [
3081
4131
  searchEmailsTool,
3082
4132
  listDraftsTool,
3083
4133
  getDraftTool,
4134
+ // Semantic search (opt-in per folder, needs IMAP_EMBEDDINGS_BASE_URL)
4135
+ indexFolderTool,
4136
+ semanticSearchTool,
3084
4137
  // Write (flag + move + delete)
3085
4138
  markReadTool,
3086
4139
  markUnreadTool,
@@ -3115,7 +4168,7 @@ function listToolEntries() {
3115
4168
  // this setting, such types become `{}` (matches anything) in the
3116
4169
  // exposed inputSchema, and the real validation still happens on
3117
4170
  // the Zod side inside the CallTool dispatcher.
3118
- inputSchema: z23.toJSONSchema(t.inputSchema, {
4171
+ inputSchema: z26.toJSONSchema(t.inputSchema, {
3119
4172
  target: "draft-7",
3120
4173
  unrepresentable: "any"
3121
4174
  }),
@@ -3124,7 +4177,7 @@ function listToolEntries() {
3124
4177
  }
3125
4178
 
3126
4179
  // src/server.ts
3127
- var log7 = createLogger("mcp-inbox:server");
4180
+ var log13 = createLogger("mcp-inbox:server");
3128
4181
  function createMcpServer(ctx) {
3129
4182
  const server = new Server(
3130
4183
  {
@@ -3144,27 +4197,27 @@ function createMcpServer(ctx) {
3144
4197
  const toolName = request.params.name;
3145
4198
  const tool = findTool(toolName);
3146
4199
  if (!tool) {
3147
- log7.warn("unknown tool", { tool: toolName });
4200
+ log13.warn("unknown tool", { tool: toolName });
3148
4201
  return errorResult(`Unknown tool: ${toolName}`);
3149
4202
  }
3150
4203
  const parsed = tool.inputSchema.safeParse(request.params.arguments ?? {});
3151
4204
  if (!parsed.success) {
3152
4205
  const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
3153
- log7.warn("invalid tool args", { tool: toolName, issues });
4206
+ log13.warn("invalid tool args", { tool: toolName, issues });
3154
4207
  return errorResult(`Invalid arguments for ${toolName}: ${issues}`);
3155
4208
  }
3156
4209
  try {
3157
4210
  return await tool.handler(parsed.data, ctx);
3158
4211
  } catch (err) {
3159
4212
  if (isMcpInboxError(err)) {
3160
- log7.warn("tool returned mcp-inbox error", {
4213
+ log13.warn("tool returned mcp-inbox error", {
3161
4214
  tool: toolName,
3162
4215
  code: err.code,
3163
4216
  msg: err.userMessage
3164
4217
  });
3165
4218
  return errorResult(err.userMessage);
3166
4219
  }
3167
- log7.error("tool handler threw", {
4220
+ log13.error("tool handler threw", {
3168
4221
  tool: toolName,
3169
4222
  msg: err instanceof Error ? err.message : String(err)
3170
4223
  });
@@ -3173,7 +4226,7 @@ function createMcpServer(ctx) {
3173
4226
  });
3174
4227
  server.onerror = (err) => {
3175
4228
  const meta = isMcpInboxError(err) ? { code: err.code, msg: err.userMessage } : { msg: err instanceof Error ? err.message : String(err) };
3176
- log7.error("mcp server error", meta);
4229
+ log13.error("mcp server error", meta);
3177
4230
  };
3178
4231
  return server;
3179
4232
  }
@@ -3223,6 +4276,8 @@ try {
3223
4276
  imap: imapClient,
3224
4277
  smtp: smtpClient,
3225
4278
  cacheConfig: config.cache,
4279
+ embeddings: config.embeddings,
4280
+ vectorsAvailable: cache.vectorsAvailable,
3226
4281
  defaults: {
3227
4282
  fromAddress: config.imap.user
3228
4283
  },
@@ -3236,13 +4291,23 @@ try {
3236
4291
  if (idleManager) {
3237
4292
  void idleManager.start();
3238
4293
  }
4294
+ const sweeper = config.embeddings !== null && cache.vectorsAvailable && config.embeddings.sweepMinutes > 0 ? new IndexSweeper({
4295
+ db: cache.db,
4296
+ imap: imapClient,
4297
+ cfg: config.embeddings,
4298
+ intervalMs: config.embeddings.sweepMinutes * 6e4,
4299
+ budgetPerTick: config.embeddings.sweepBatch,
4300
+ now: () => Date.now()
4301
+ }) : null;
4302
+ sweeper?.start();
3239
4303
  const server = createMcpServer(ctx);
3240
- const transport = new StdioServerTransport();
4304
+ let httpServer = null;
3241
4305
  let shuttingDown = false;
3242
4306
  const shutdown = async (signal) => {
3243
4307
  if (shuttingDown) return;
3244
4308
  shuttingDown = true;
3245
4309
  rootLogger.info("shutting down", { signal });
4310
+ httpServer?.close();
3246
4311
  try {
3247
4312
  await server.close();
3248
4313
  } catch (err) {
@@ -3250,6 +4315,7 @@ try {
3250
4315
  msg: err instanceof Error ? err.message : String(err)
3251
4316
  });
3252
4317
  }
4318
+ sweeper?.stop();
3253
4319
  try {
3254
4320
  if (idleManager) await idleManager.stop();
3255
4321
  } catch (err) {
@@ -3278,7 +4344,11 @@ try {
3278
4344
  };
3279
4345
  process.on("SIGINT", () => onSignal("SIGINT"));
3280
4346
  process.on("SIGTERM", () => onSignal("SIGTERM"));
3281
- await server.connect(transport);
4347
+ if (config.http) {
4348
+ httpServer = await startHttpServer(config.http, () => createMcpServer(ctx));
4349
+ } else {
4350
+ await server.connect(new StdioServerTransport());
4351
+ }
3282
4352
  rootLogger.info("mcp-inbox ready");
3283
4353
  } catch (err) {
3284
4354
  const top = err instanceof Error ? err.stack ?? err.message : String(err);