@kbzowski/mcp-inbox 0.5.1 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -0
- package/dist/app.js +1559 -426
- package/dist/cache/backfill.d.ts +35 -0
- package/dist/cache/db.d.ts +7 -2
- package/dist/cache/indexer.d.ts +34 -0
- package/dist/cache/queries.d.ts +18 -0
- package/dist/cache/schema.d.ts +117 -0
- package/dist/cache/vectors.d.ts +77 -0
- package/dist/config/env.d.ts +38 -0
- package/dist/embeddings/chunk.d.ts +3 -0
- package/dist/embeddings/client.d.ts +11 -0
- package/dist/errors/types.d.ts +3 -1
- package/dist/formatters/markdown.d.ts +23 -0
- package/dist/http.d.ts +14 -0
- package/dist/imap/body-text.d.ts +47 -0
- package/dist/migrations/20260804153609_illegal_scream/migration.sql +8 -0
- package/dist/migrations/20260804153609_illegal_scream/snapshot.json +383 -0
- package/dist/tools/define-tool.d.ts +4 -0
- package/dist/tools/emails/index-folder.d.ts +10 -0
- package/dist/tools/emails/semantic-search.d.ts +13 -0
- package/dist/tools/emails/shared.d.ts +14 -0
- package/dist/utils/logger.d.ts +8 -5
- package/package.json +20 -20
package/dist/app.js
CHANGED
|
@@ -1,15 +1,188 @@
|
|
|
1
1
|
import { createRequire as __mcpCreateRequire } from 'node:module';
|
|
2
2
|
globalThis.require = globalThis.require ?? __mcpCreateRequire(import.meta.url);
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __export = (target, all) => {
|
|
5
|
-
for (var name in all)
|
|
6
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
7
|
-
};
|
|
8
3
|
|
|
9
4
|
// src/app.ts
|
|
10
5
|
import { join as join2 } from "node:path";
|
|
11
6
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
12
7
|
|
|
8
|
+
// src/http.ts
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { timingSafeEqual } from "node:crypto";
|
|
11
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
12
|
+
|
|
13
|
+
// src/utils/logger.ts
|
|
14
|
+
var LEVEL_WEIGHT = {
|
|
15
|
+
debug: 10,
|
|
16
|
+
info: 20,
|
|
17
|
+
warn: 30,
|
|
18
|
+
error: 40
|
|
19
|
+
};
|
|
20
|
+
var ERROR_FIELDS = [
|
|
21
|
+
"name",
|
|
22
|
+
"message",
|
|
23
|
+
"code",
|
|
24
|
+
"errno",
|
|
25
|
+
"syscall",
|
|
26
|
+
"address",
|
|
27
|
+
"port",
|
|
28
|
+
"responseStatus",
|
|
29
|
+
"responseText",
|
|
30
|
+
"serverResponseCode",
|
|
31
|
+
"executedCommand",
|
|
32
|
+
"authenticationFailed",
|
|
33
|
+
"throttleReset",
|
|
34
|
+
"command",
|
|
35
|
+
"responseCode"
|
|
36
|
+
];
|
|
37
|
+
var MAX_FIELD_LENGTH = 1e3;
|
|
38
|
+
var MAX_STACK_LENGTH = 4e3;
|
|
39
|
+
var EMAIL_ADDRESS = /[^\s<>"'@]+@[^\s<>"'@]+/g;
|
|
40
|
+
function clean(text2, maxLength = MAX_FIELD_LENGTH) {
|
|
41
|
+
return text2.slice(0, maxLength).replace(EMAIL_ADDRESS, "[address]");
|
|
42
|
+
}
|
|
43
|
+
function serializeError(err) {
|
|
44
|
+
const source = err;
|
|
45
|
+
const out = {};
|
|
46
|
+
for (const field of ERROR_FIELDS) {
|
|
47
|
+
const value = source[field];
|
|
48
|
+
if (typeof value === "string") out[field] = clean(value);
|
|
49
|
+
else if (typeof value === "number" || typeof value === "boolean") out[field] = value;
|
|
50
|
+
}
|
|
51
|
+
if (Array.isArray(source["errors"])) {
|
|
52
|
+
out["errors"] = source["errors"].filter((e) => e instanceof Error);
|
|
53
|
+
}
|
|
54
|
+
if (typeof source["stack"] === "string") out["stack"] = clean(source["stack"], MAX_STACK_LENGTH);
|
|
55
|
+
if (source["cause"] !== void 0) out["cause"] = source["cause"];
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
function createReplacer() {
|
|
59
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
60
|
+
return (key, value) => {
|
|
61
|
+
if (typeof value === "bigint") return value.toString();
|
|
62
|
+
if (!(value instanceof Error) && key !== "err" && key !== "cause") return value;
|
|
63
|
+
if (typeof value === "string") return clean(value);
|
|
64
|
+
if (typeof value !== "object" || value === null) return value;
|
|
65
|
+
if (seen.has(value)) return "[circular]";
|
|
66
|
+
seen.add(value);
|
|
67
|
+
return serializeError(value);
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
var LoggerContext = class {
|
|
71
|
+
// JS hard-private - consumers of the published package cannot poke at these
|
|
72
|
+
// from plain JS. TS `private` would be compile-time only.
|
|
73
|
+
#enabledNamespaces = [];
|
|
74
|
+
#minLevel = "info";
|
|
75
|
+
configure(opts) {
|
|
76
|
+
this.#enabledNamespaces = parseNamespaces(opts.debug ?? "");
|
|
77
|
+
this.#minLevel = opts.level ?? "info";
|
|
78
|
+
}
|
|
79
|
+
shouldEmit(level, namespace) {
|
|
80
|
+
if (LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[this.#minLevel]) return true;
|
|
81
|
+
return this.#enabledNamespaces.some((re) => re.test(namespace));
|
|
82
|
+
}
|
|
83
|
+
emit(level, namespace, msg, meta) {
|
|
84
|
+
if (!this.shouldEmit(level, namespace)) return;
|
|
85
|
+
const base = { ts: (/* @__PURE__ */ new Date()).toISOString(), level, ns: namespace, msg };
|
|
86
|
+
let line;
|
|
87
|
+
try {
|
|
88
|
+
line = JSON.stringify({ ...base, ...meta, ...base }, createReplacer());
|
|
89
|
+
} catch (err) {
|
|
90
|
+
line = JSON.stringify({ ...base, logFailure: String(err) });
|
|
91
|
+
}
|
|
92
|
+
process.stderr.write(line + "\n");
|
|
93
|
+
}
|
|
94
|
+
logger(namespace) {
|
|
95
|
+
return {
|
|
96
|
+
debug: (msg, meta) => this.emit("debug", namespace, msg, meta),
|
|
97
|
+
info: (msg, meta) => this.emit("info", namespace, msg, meta),
|
|
98
|
+
warn: (msg, meta) => this.emit("warn", namespace, msg, meta),
|
|
99
|
+
error: (msg, meta) => this.emit("error", namespace, msg, meta),
|
|
100
|
+
child: (sub) => this.logger(`${namespace}:${sub}`)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
function parseNamespaces(spec) {
|
|
105
|
+
return spec.split(",").map((s) => s.trim()).filter((s) => s.length > 0).map((pattern) => {
|
|
106
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
|
|
107
|
+
return new RegExp(`^${escaped}$`);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
var defaultContext = new LoggerContext();
|
|
111
|
+
function configureLogger(opts) {
|
|
112
|
+
defaultContext.configure(opts);
|
|
113
|
+
}
|
|
114
|
+
function createLogger(namespace, context = defaultContext) {
|
|
115
|
+
return context.logger(namespace);
|
|
116
|
+
}
|
|
117
|
+
var rootLogger = createLogger("mcp-inbox");
|
|
118
|
+
|
|
119
|
+
// src/http.ts
|
|
120
|
+
var log = createLogger("mcp-inbox:http");
|
|
121
|
+
function tokenOk(header, token) {
|
|
122
|
+
const given = Buffer.from(header?.replace(/^Bearer /i, "") ?? "");
|
|
123
|
+
const want = Buffer.from(token);
|
|
124
|
+
return given.length === want.length && timingSafeEqual(given, want);
|
|
125
|
+
}
|
|
126
|
+
function startHttpServer(cfg, makeServer) {
|
|
127
|
+
const http = createServer((req, res) => {
|
|
128
|
+
const reply = (status, msg) => {
|
|
129
|
+
res.writeHead(status, { "content-type": "text/plain" }).end(msg);
|
|
130
|
+
};
|
|
131
|
+
const path = (req.url ?? "").split("?")[0];
|
|
132
|
+
if (path !== "/mcp") return reply(404, "Not found");
|
|
133
|
+
if (!tokenOk(req.headers.authorization, cfg.token)) return reply(401, "Unauthorized");
|
|
134
|
+
if (req.method !== "POST") return reply(405, "Method not allowed");
|
|
135
|
+
const chunks = [];
|
|
136
|
+
let size = 0;
|
|
137
|
+
req.on("data", (c) => {
|
|
138
|
+
size += c.length;
|
|
139
|
+
if (size > 25 * 1024 * 1024) req.destroy();
|
|
140
|
+
else chunks.push(c);
|
|
141
|
+
});
|
|
142
|
+
req.on("end", () => {
|
|
143
|
+
void (async () => {
|
|
144
|
+
let body;
|
|
145
|
+
try {
|
|
146
|
+
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
147
|
+
} catch {
|
|
148
|
+
return reply(400, "Invalid JSON");
|
|
149
|
+
}
|
|
150
|
+
const server = makeServer();
|
|
151
|
+
const transport = new StreamableHTTPServerTransport({
|
|
152
|
+
enableJsonResponse: true
|
|
153
|
+
});
|
|
154
|
+
res.on("close", () => {
|
|
155
|
+
void transport.close();
|
|
156
|
+
void server.close();
|
|
157
|
+
});
|
|
158
|
+
try {
|
|
159
|
+
await server.connect(transport);
|
|
160
|
+
await transport.handleRequest(req, res, body);
|
|
161
|
+
if (res.statusCode >= 400) {
|
|
162
|
+
log.warn("request rejected", {
|
|
163
|
+
status: res.statusCode,
|
|
164
|
+
userAgent: req.headers["user-agent"],
|
|
165
|
+
protocolVersion: req.headers["mcp-protocol-version"]
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
} catch (err) {
|
|
169
|
+
log.error("http request failed", {
|
|
170
|
+
err
|
|
171
|
+
});
|
|
172
|
+
if (!res.headersSent) reply(500, "Internal error");
|
|
173
|
+
}
|
|
174
|
+
})();
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
return new Promise((resolve, reject) => {
|
|
178
|
+
http.once("error", reject);
|
|
179
|
+
http.listen(cfg.port, cfg.host, () => {
|
|
180
|
+
log.info("listening", { host: cfg.host, port: cfg.port, path: "/mcp" });
|
|
181
|
+
resolve(http);
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
13
186
|
// src/config/env.ts
|
|
14
187
|
import { z } from "zod";
|
|
15
188
|
import { homedir, platform } from "node:os";
|
|
@@ -40,11 +213,29 @@ var EnvSchema = z.object({
|
|
|
40
213
|
IMAP_CACHE_DIR: z.string().min(1).optional(),
|
|
41
214
|
IMAP_CACHE_DEFAULT_STALENESS_SEC: z.coerce.number().int().min(0).default(60),
|
|
42
215
|
IMAP_CACHE_BODY_RETAIN_DAYS: z.coerce.number().int().min(0).default(180),
|
|
216
|
+
// Embeddings (semantic search). Gated on BASE_URL rather than API_KEY -
|
|
217
|
+
// a self-hosted endpoint may not require a key at all.
|
|
218
|
+
IMAP_EMBEDDINGS_BASE_URL: z.url().optional(),
|
|
219
|
+
IMAP_EMBEDDINGS_API_KEY: z.string().min(1).optional(),
|
|
220
|
+
IMAP_EMBEDDINGS_MODEL: z.string().min(1).default("arctic-embed-l-v2"),
|
|
221
|
+
IMAP_EMBEDDINGS_DIMS: z.coerce.number().int().min(1).max(8192).default(1024),
|
|
222
|
+
IMAP_EMBEDDINGS_BATCH_SIZE: z.coerce.number().int().min(1).max(512).default(64),
|
|
223
|
+
IMAP_EMBEDDINGS_TIMEOUT_MS: z.coerce.number().int().positive().default(3e4),
|
|
224
|
+
IMAP_EMBEDDINGS_SWEEP_MINUTES: z.coerce.number().int().min(0).max(1440).default(15),
|
|
225
|
+
IMAP_EMBEDDINGS_SWEEP_BATCH: z.coerce.number().int().min(1).max(5e3).default(200),
|
|
43
226
|
// IDLE
|
|
44
227
|
IMAP_IDLE_ENABLED: BooleanString.default(true),
|
|
45
228
|
IMAP_IDLE_FOLDERS: CsvList.default(["INBOX"]),
|
|
229
|
+
// Transport. Unset MCP_HTTP_PORT = stdio. Set = streamable HTTP, which
|
|
230
|
+
// exposes the mailbox over the network, so a token is mandatory.
|
|
231
|
+
MCP_HTTP_PORT: z.coerce.number().int().min(1).max(65535).optional(),
|
|
232
|
+
MCP_HTTP_HOST: z.string().min(1).default("127.0.0.1"),
|
|
233
|
+
MCP_AUTH_TOKEN: z.string().min(16, "MCP_AUTH_TOKEN must be at least 16 characters").optional(),
|
|
46
234
|
// Debug
|
|
47
235
|
DEBUG: z.string().optional()
|
|
236
|
+
}).refine((raw) => raw.MCP_HTTP_PORT === void 0 || raw.MCP_AUTH_TOKEN !== void 0, {
|
|
237
|
+
path: ["MCP_AUTH_TOKEN"],
|
|
238
|
+
message: "MCP_AUTH_TOKEN is required when MCP_HTTP_PORT is set"
|
|
48
239
|
}).transform((raw) => ({
|
|
49
240
|
imap: {
|
|
50
241
|
user: raw.IMAP_USER,
|
|
@@ -67,10 +258,23 @@ var EnvSchema = z.object({
|
|
|
67
258
|
defaultStalenessSec: raw.IMAP_CACHE_DEFAULT_STALENESS_SEC,
|
|
68
259
|
bodyRetainDays: raw.IMAP_CACHE_BODY_RETAIN_DAYS
|
|
69
260
|
},
|
|
261
|
+
embeddings: raw.IMAP_EMBEDDINGS_BASE_URL === void 0 ? null : {
|
|
262
|
+
baseUrl: raw.IMAP_EMBEDDINGS_BASE_URL.replace(/\/+$/, ""),
|
|
263
|
+
...raw.IMAP_EMBEDDINGS_API_KEY !== void 0 && {
|
|
264
|
+
apiKey: raw.IMAP_EMBEDDINGS_API_KEY
|
|
265
|
+
},
|
|
266
|
+
model: raw.IMAP_EMBEDDINGS_MODEL,
|
|
267
|
+
dims: raw.IMAP_EMBEDDINGS_DIMS,
|
|
268
|
+
batchSize: raw.IMAP_EMBEDDINGS_BATCH_SIZE,
|
|
269
|
+
timeoutMs: raw.IMAP_EMBEDDINGS_TIMEOUT_MS,
|
|
270
|
+
sweepMinutes: raw.IMAP_EMBEDDINGS_SWEEP_MINUTES,
|
|
271
|
+
sweepBatch: raw.IMAP_EMBEDDINGS_SWEEP_BATCH
|
|
272
|
+
},
|
|
70
273
|
idle: {
|
|
71
274
|
enabled: raw.IMAP_IDLE_ENABLED,
|
|
72
275
|
folders: raw.IMAP_IDLE_FOLDERS
|
|
73
276
|
},
|
|
277
|
+
http: raw.MCP_HTTP_PORT === void 0 ? null : { port: raw.MCP_HTTP_PORT, host: raw.MCP_HTTP_HOST, token: raw.MCP_AUTH_TOKEN },
|
|
74
278
|
debug: raw.DEBUG ?? ""
|
|
75
279
|
}));
|
|
76
280
|
function defaultCacheDir() {
|
|
@@ -104,69 +308,7 @@ import { dirname } from "node:path";
|
|
|
104
308
|
import { fileURLToPath } from "node:url";
|
|
105
309
|
import { drizzle } from "drizzle-orm/node-sqlite";
|
|
106
310
|
import { migrate } from "drizzle-orm/node-sqlite/migrator";
|
|
107
|
-
|
|
108
|
-
// src/cache/schema.ts
|
|
109
|
-
var schema_exports = {};
|
|
110
|
-
__export(schema_exports, {
|
|
111
|
-
emails: () => emails,
|
|
112
|
-
folders: () => folders
|
|
113
|
-
});
|
|
114
|
-
import { sqliteTable, text, integer, primaryKey, index } from "drizzle-orm/sqlite-core";
|
|
115
|
-
var folders = sqliteTable("folders", {
|
|
116
|
-
/** Full mailbox path as returned by IMAP LIST (e.g. "INBOX", "[Gmail]/Sent Mail"). */
|
|
117
|
-
name: text("name").primaryKey(),
|
|
118
|
-
/** Delimiter the server uses - usually "." (Dovecot) or "/" (Gmail). */
|
|
119
|
-
delimiter: text("delimiter").notNull(),
|
|
120
|
-
/** RFC 6154 attribute ("\\Drafts", "\\Sent", etc.) or null. */
|
|
121
|
-
specialUse: text("special_use"),
|
|
122
|
-
/** UIDVALIDITY from SELECT response. If this changes, wipe the cache. */
|
|
123
|
-
uidValidity: integer("uid_validity").notNull(),
|
|
124
|
-
/** Next UID the server will assign. Used for new-message detection. */
|
|
125
|
-
uidNext: integer("uid_next"),
|
|
126
|
-
/** HIGHESTMODSEQ from CONDSTORE. NULL if the server doesn't support it. */
|
|
127
|
-
highestModseq: integer("highest_modseq"),
|
|
128
|
-
/** Epoch milliseconds of the last successful sync completion. */
|
|
129
|
-
lastSyncedAt: integer("last_synced_at").notNull()
|
|
130
|
-
});
|
|
131
|
-
var emails = sqliteTable(
|
|
132
|
-
"emails",
|
|
133
|
-
{
|
|
134
|
-
folder: text("folder").notNull(),
|
|
135
|
-
uid: integer("uid").notNull(),
|
|
136
|
-
/** RFC 5322 Message-ID header (with angle brackets). Enables cross-folder dedup. */
|
|
137
|
-
messageId: text("message_id"),
|
|
138
|
-
subject: text("subject"),
|
|
139
|
-
fromAddr: text("from_addr"),
|
|
140
|
-
/** JSON array of recipient email strings. */
|
|
141
|
-
toAddrs: text("to_addrs", { mode: "json" }).$type(),
|
|
142
|
-
ccAddrs: text("cc_addrs", { mode: "json" }).$type(),
|
|
143
|
-
/** INTERNALDATE in epoch ms. */
|
|
144
|
-
date: integer("date"),
|
|
145
|
-
/** JSON array of IMAP flags ("\\Seen", "\\Flagged", etc.). */
|
|
146
|
-
flags: text("flags", { mode: "json" }).$type().notNull(),
|
|
147
|
-
/** Whether any MIME part is an attachment. Indexed for "has-attachment" filters. */
|
|
148
|
-
hasAttachments: integer("has_attachments", { mode: "boolean" }).notNull().default(false),
|
|
149
|
-
/** Full parsed envelope as JSON, for detail-view tools. */
|
|
150
|
-
envelopeJson: text("envelope_json").notNull(),
|
|
151
|
-
/** Plain-text body, nullable - fetched on first read of the message. */
|
|
152
|
-
bodyText: text("body_text"),
|
|
153
|
-
/** HTML body, nullable. Can be large; keep lazy by default. */
|
|
154
|
-
bodyHtml: text("body_html"),
|
|
155
|
-
/** Attachment metadata, written with the body in the same fetch. */
|
|
156
|
-
attachmentsJson: text("attachments_json", { mode: "json" }).$type(),
|
|
157
|
-
/** Per-message MODSEQ (RFC 7162). Used for CONDSTORE incremental sync. */
|
|
158
|
-
modseq: integer("modseq"),
|
|
159
|
-
/** Epoch ms of envelope cache write. */
|
|
160
|
-
cachedAt: integer("cached_at").notNull(),
|
|
161
|
-
/** Epoch ms of body cache write (NULL if body not yet fetched). */
|
|
162
|
-
bodyCachedAt: integer("body_cached_at")
|
|
163
|
-
},
|
|
164
|
-
(t) => [
|
|
165
|
-
primaryKey({ columns: [t.folder, t.uid] }),
|
|
166
|
-
index("idx_emails_date").on(t.folder, t.date),
|
|
167
|
-
index("idx_emails_message_id").on(t.messageId)
|
|
168
|
-
]
|
|
169
|
-
);
|
|
311
|
+
import * as sqliteVec from "sqlite-vec";
|
|
170
312
|
|
|
171
313
|
// src/errors/types.ts
|
|
172
314
|
var McpInboxError = class extends Error {
|
|
@@ -177,7 +319,6 @@ var McpInboxError = class extends Error {
|
|
|
177
319
|
this.name = new.target.name;
|
|
178
320
|
this.code = code;
|
|
179
321
|
this.userMessage = userMessage;
|
|
180
|
-
Error.captureStackTrace(this, new.target);
|
|
181
322
|
}
|
|
182
323
|
};
|
|
183
324
|
var ImapError = class extends McpInboxError {
|
|
@@ -186,71 +327,17 @@ var SmtpError = class extends McpInboxError {
|
|
|
186
327
|
};
|
|
187
328
|
var CacheError = class extends McpInboxError {
|
|
188
329
|
};
|
|
330
|
+
var EmbeddingError = class extends McpInboxError {
|
|
331
|
+
};
|
|
189
332
|
var ToolInputError = class extends McpInboxError {
|
|
190
333
|
constructor(userMessage, cause) {
|
|
191
334
|
super("TOOL_INVALID_INPUT", userMessage, cause);
|
|
192
335
|
}
|
|
193
336
|
};
|
|
194
337
|
|
|
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
338
|
// src/cache/db.ts
|
|
252
339
|
var DEFAULT_MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url));
|
|
253
|
-
var
|
|
340
|
+
var log2 = createLogger("mcp-inbox:cache");
|
|
254
341
|
function openCache(path, migrationsFolder) {
|
|
255
342
|
if (path !== ":memory:") {
|
|
256
343
|
try {
|
|
@@ -261,18 +348,19 @@ function openCache(path, migrationsFolder) {
|
|
|
261
348
|
}
|
|
262
349
|
let sqlite;
|
|
263
350
|
try {
|
|
264
|
-
sqlite = new DatabaseSync(path);
|
|
351
|
+
sqlite = new DatabaseSync(path, { allowExtension: true });
|
|
265
352
|
} catch (err) {
|
|
266
353
|
throw new CacheError("CACHE_IO_FAILED", diagnoseOpenError(path, err), err);
|
|
267
354
|
}
|
|
268
355
|
sqlite.exec("PRAGMA journal_mode = WAL;");
|
|
269
356
|
sqlite.exec("PRAGMA foreign_keys = ON;");
|
|
270
357
|
sqlite.exec("PRAGMA synchronous = NORMAL;");
|
|
271
|
-
const
|
|
358
|
+
const vectorsAvailable = loadVectorExtension(sqlite);
|
|
359
|
+
const db = drizzle({ client: sqlite });
|
|
272
360
|
if (migrationsFolder) {
|
|
273
361
|
try {
|
|
274
362
|
migrate(db, { migrationsFolder });
|
|
275
|
-
|
|
363
|
+
log2.info("cache migrations applied", { migrationsFolder });
|
|
276
364
|
} catch (err) {
|
|
277
365
|
sqlite.close();
|
|
278
366
|
throw new CacheError(
|
|
@@ -284,17 +372,35 @@ function openCache(path, migrationsFolder) {
|
|
|
284
372
|
}
|
|
285
373
|
return {
|
|
286
374
|
db,
|
|
375
|
+
vectorsAvailable,
|
|
287
376
|
close: () => {
|
|
288
377
|
try {
|
|
289
378
|
sqlite.close();
|
|
290
379
|
} catch (err) {
|
|
291
|
-
|
|
292
|
-
|
|
380
|
+
log2.warn("error closing cache db", {
|
|
381
|
+
err
|
|
293
382
|
});
|
|
294
383
|
}
|
|
295
384
|
}
|
|
296
385
|
};
|
|
297
386
|
}
|
|
387
|
+
function loadVectorExtension(sqlite) {
|
|
388
|
+
try {
|
|
389
|
+
sqlite.enableLoadExtension(true);
|
|
390
|
+
sqliteVec.load(sqlite);
|
|
391
|
+
return true;
|
|
392
|
+
} catch (err) {
|
|
393
|
+
log2.warn("sqlite-vec unavailable - semantic search tools will be disabled", {
|
|
394
|
+
err
|
|
395
|
+
});
|
|
396
|
+
return false;
|
|
397
|
+
} finally {
|
|
398
|
+
try {
|
|
399
|
+
sqlite.enableLoadExtension(false);
|
|
400
|
+
} catch {
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
298
404
|
function diagnoseOpenError(path, err) {
|
|
299
405
|
const msg = err instanceof Error ? err.message : String(err);
|
|
300
406
|
const code = err && typeof err === "object" && "code" in err ? String(err.code) : void 0;
|
|
@@ -314,8 +420,224 @@ function diagnoseOpenError(path, err) {
|
|
|
314
420
|
}
|
|
315
421
|
|
|
316
422
|
// src/cache/queries.ts
|
|
317
|
-
import { and, desc, eq, gte, inArray, lt, sql } from "drizzle-orm";
|
|
318
|
-
|
|
423
|
+
import { and, asc, count, desc, eq as eq2, gt, gte, inArray, lt, or as or2, sql as sql2 } from "drizzle-orm";
|
|
424
|
+
|
|
425
|
+
// src/cache/vectors.ts
|
|
426
|
+
import { eq, ne, or, sql } from "drizzle-orm";
|
|
427
|
+
|
|
428
|
+
// src/cache/schema.ts
|
|
429
|
+
import { sqliteTable, text, integer, primaryKey, index } from "drizzle-orm/sqlite-core";
|
|
430
|
+
var folders = sqliteTable("folders", {
|
|
431
|
+
/** Full mailbox path as returned by IMAP LIST (e.g. "INBOX", "[Gmail]/Sent Mail"). */
|
|
432
|
+
name: text("name").primaryKey(),
|
|
433
|
+
/** Delimiter the server uses - usually "." (Dovecot) or "/" (Gmail). */
|
|
434
|
+
delimiter: text("delimiter").notNull(),
|
|
435
|
+
/** RFC 6154 attribute ("\\Drafts", "\\Sent", etc.) or null. */
|
|
436
|
+
specialUse: text("special_use"),
|
|
437
|
+
/** UIDVALIDITY from SELECT response. If this changes, wipe the cache. */
|
|
438
|
+
uidValidity: integer("uid_validity").notNull(),
|
|
439
|
+
/** Next UID the server will assign. Used for new-message detection. */
|
|
440
|
+
uidNext: integer("uid_next"),
|
|
441
|
+
/** HIGHESTMODSEQ from CONDSTORE. NULL if the server doesn't support it. */
|
|
442
|
+
highestModseq: integer("highest_modseq"),
|
|
443
|
+
/** Epoch milliseconds of the last successful sync completion. */
|
|
444
|
+
lastSyncedAt: integer("last_synced_at").notNull()
|
|
445
|
+
});
|
|
446
|
+
var emails = sqliteTable(
|
|
447
|
+
"emails",
|
|
448
|
+
{
|
|
449
|
+
folder: text("folder").notNull(),
|
|
450
|
+
uid: integer("uid").notNull(),
|
|
451
|
+
/** RFC 5322 Message-ID header (with angle brackets). Enables cross-folder dedup. */
|
|
452
|
+
messageId: text("message_id"),
|
|
453
|
+
subject: text("subject"),
|
|
454
|
+
fromAddr: text("from_addr"),
|
|
455
|
+
/** JSON array of recipient email strings. */
|
|
456
|
+
toAddrs: text("to_addrs", { mode: "json" }).$type(),
|
|
457
|
+
ccAddrs: text("cc_addrs", { mode: "json" }).$type(),
|
|
458
|
+
/** INTERNALDATE in epoch ms. */
|
|
459
|
+
date: integer("date"),
|
|
460
|
+
/** JSON array of IMAP flags ("\\Seen", "\\Flagged", etc.). */
|
|
461
|
+
flags: text("flags", { mode: "json" }).$type().notNull(),
|
|
462
|
+
/** Whether any MIME part is an attachment. Indexed for "has-attachment" filters. */
|
|
463
|
+
hasAttachments: integer("has_attachments", { mode: "boolean" }).notNull().default(false),
|
|
464
|
+
/** Full parsed envelope as JSON, for detail-view tools. */
|
|
465
|
+
envelopeJson: text("envelope_json").notNull(),
|
|
466
|
+
/** Plain-text body, nullable - fetched on first read of the message. */
|
|
467
|
+
bodyText: text("body_text"),
|
|
468
|
+
/** HTML body, nullable. Can be large; keep lazy by default. */
|
|
469
|
+
bodyHtml: text("body_html"),
|
|
470
|
+
/** Attachment metadata, written with the body in the same fetch. */
|
|
471
|
+
attachmentsJson: text("attachments_json", { mode: "json" }).$type(),
|
|
472
|
+
/** Per-message MODSEQ (RFC 7162). Used for CONDSTORE incremental sync. */
|
|
473
|
+
modseq: integer("modseq"),
|
|
474
|
+
/** Epoch ms of envelope cache write. */
|
|
475
|
+
cachedAt: integer("cached_at").notNull(),
|
|
476
|
+
/** Epoch ms of body cache write (NULL if body not yet fetched). */
|
|
477
|
+
bodyCachedAt: integer("body_cached_at")
|
|
478
|
+
},
|
|
479
|
+
(t) => [
|
|
480
|
+
primaryKey({ columns: [t.folder, t.uid] }),
|
|
481
|
+
index("idx_emails_date").on(t.folder, t.date),
|
|
482
|
+
index("idx_emails_message_id").on(t.messageId)
|
|
483
|
+
]
|
|
484
|
+
);
|
|
485
|
+
var vecIndexState = sqliteTable("vec_index_state", {
|
|
486
|
+
folder: text("folder").primaryKey(),
|
|
487
|
+
model: text("model").notNull(),
|
|
488
|
+
dims: integer("dims").notNull(),
|
|
489
|
+
fromUid: integer("from_uid").notNull(),
|
|
490
|
+
toUid: integer("to_uid").notNull(),
|
|
491
|
+
indexedAt: integer("indexed_at").notNull()
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
// src/cache/vectors.ts
|
|
495
|
+
var log3 = createLogger("mcp-inbox:vectors");
|
|
496
|
+
var ENVELOPE_PART = 0;
|
|
497
|
+
var INDEX_VERSION = "b1";
|
|
498
|
+
function indexModelId(model) {
|
|
499
|
+
return model.includes("#") ? model : `${model}#${INDEX_VERSION}`;
|
|
500
|
+
}
|
|
501
|
+
var int = (value) => BigInt(Math.trunc(value));
|
|
502
|
+
var toBlob = (vector) => new Uint8Array(vector.buffer, vector.byteOffset, vector.byteLength);
|
|
503
|
+
function ensureVecTable(db, model, dims) {
|
|
504
|
+
const wanted = indexModelId(model);
|
|
505
|
+
const stale = db.select().from(vecIndexState).where(or(ne(vecIndexState.model, wanted), ne(vecIndexState.dims, dims))).all();
|
|
506
|
+
if (stale.length > 0) {
|
|
507
|
+
log3.warn(
|
|
508
|
+
"embedding model or index format changed - dropping vector index, re-run imap_index_folder",
|
|
509
|
+
{
|
|
510
|
+
folders: stale.map((s) => s.folder),
|
|
511
|
+
was: stale.map((s) => `${s.model}/${String(s.dims)}`),
|
|
512
|
+
now: `${wanted}/${String(dims)}`
|
|
513
|
+
}
|
|
514
|
+
);
|
|
515
|
+
db.run(sql.raw("DROP TABLE IF EXISTS vec_emails"));
|
|
516
|
+
db.delete(vecIndexState).run();
|
|
517
|
+
}
|
|
518
|
+
db.run(
|
|
519
|
+
sql.raw(
|
|
520
|
+
`CREATE VIRTUAL TABLE IF NOT EXISTS vec_emails USING vec0(
|
|
521
|
+
folder text partition key,
|
|
522
|
+
uid integer,
|
|
523
|
+
part integer,
|
|
524
|
+
date integer,
|
|
525
|
+
embedding float[${dims}] distance_metric=cosine
|
|
526
|
+
)`
|
|
527
|
+
)
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
function indexedFolders(db) {
|
|
531
|
+
return db.select({ folder: vecIndexState.folder }).from(vecIndexState).all().map((r) => r.folder).toSorted((a, b) => a.localeCompare(b));
|
|
532
|
+
}
|
|
533
|
+
function getVecState(db, folder) {
|
|
534
|
+
return db.select().from(vecIndexState).where(eq(vecIndexState.folder, folder)).get();
|
|
535
|
+
}
|
|
536
|
+
function upsertVecState(db, row) {
|
|
537
|
+
const normalized = { ...row, model: indexModelId(row.model) };
|
|
538
|
+
db.insert(vecIndexState).values(normalized).onConflictDoUpdate({
|
|
539
|
+
target: vecIndexState.folder,
|
|
540
|
+
set: {
|
|
541
|
+
model: normalized.model,
|
|
542
|
+
dims: row.dims,
|
|
543
|
+
fromUid: row.fromUid,
|
|
544
|
+
toUid: row.toUid,
|
|
545
|
+
indexedAt: row.indexedAt
|
|
546
|
+
}
|
|
547
|
+
}).run();
|
|
548
|
+
}
|
|
549
|
+
function insertVectors(db, folder, rows) {
|
|
550
|
+
if (rows.length === 0) return;
|
|
551
|
+
const uids = [...new Set(rows.map((r) => r.uid))];
|
|
552
|
+
db.transaction((tx) => {
|
|
553
|
+
for (const uid of uids) {
|
|
554
|
+
tx.run(sql`DELETE FROM vec_emails WHERE folder = ${folder} AND uid = ${int(uid)}`);
|
|
555
|
+
}
|
|
556
|
+
for (const row of rows) {
|
|
557
|
+
tx.run(
|
|
558
|
+
sql`INSERT INTO vec_emails(folder, uid, part, date, embedding)
|
|
559
|
+
VALUES (${folder}, ${int(row.uid)}, ${int(row.part)}, ${int(row.date ?? 0)}, ${toBlob(row.vector)})`
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
function deleteVectorsByFolder(db, folder) {
|
|
565
|
+
if (getVecState(db, folder) === void 0) return;
|
|
566
|
+
try {
|
|
567
|
+
db.run(sql`DELETE FROM vec_emails WHERE folder = ${folder}`);
|
|
568
|
+
db.update(vecIndexState).set({ fromUid: 0, toUid: 0 }).where(eq(vecIndexState.folder, folder)).run();
|
|
569
|
+
} catch (err) {
|
|
570
|
+
log3.warn("could not drop vectors for folder", { folder, err });
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
function deleteVectorsByUids(db, folder, uids) {
|
|
574
|
+
if (uids.length === 0 || getVecState(db, folder) === void 0) return;
|
|
575
|
+
try {
|
|
576
|
+
db.transaction((tx) => {
|
|
577
|
+
for (const uid of uids) {
|
|
578
|
+
tx.run(sql`DELETE FROM vec_emails WHERE folder = ${folder} AND uid = ${int(uid)}`);
|
|
579
|
+
}
|
|
580
|
+
});
|
|
581
|
+
} catch (err) {
|
|
582
|
+
log3.warn("could not drop vectors for uids", {
|
|
583
|
+
folder,
|
|
584
|
+
count: uids.length,
|
|
585
|
+
err
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
function knnSearch(db, query, k, opts = {}) {
|
|
590
|
+
if (opts.folders?.length === 0) return [];
|
|
591
|
+
const filters = [];
|
|
592
|
+
if (opts.folders !== void 0) {
|
|
593
|
+
const list = opts.folders.map((f) => sql`${f}`);
|
|
594
|
+
filters.push(sql` AND folder IN (${sql.join(list, sql`, `)})`);
|
|
595
|
+
}
|
|
596
|
+
if (opts.sinceMs !== void 0) filters.push(sql` AND date >= ${int(opts.sinceMs)}`);
|
|
597
|
+
if (opts.beforeMs !== void 0) filters.push(sql` AND date < ${int(opts.beforeMs)}`);
|
|
598
|
+
return db.all(sql`
|
|
599
|
+
WITH knn AS MATERIALIZED (
|
|
600
|
+
SELECT folder, uid, distance FROM vec_emails
|
|
601
|
+
WHERE embedding MATCH ${toBlob(query)}
|
|
602
|
+
AND k = ${int(k)}
|
|
603
|
+
${sql.join(filters, sql``)}
|
|
604
|
+
)
|
|
605
|
+
SELECT folder, uid, min(distance) AS distance
|
|
606
|
+
FROM knn GROUP BY folder, uid ORDER BY distance
|
|
607
|
+
`);
|
|
608
|
+
}
|
|
609
|
+
function pruneOrphanedVectors(db, folder) {
|
|
610
|
+
if (getVecState(db, folder) === void 0) return 0;
|
|
611
|
+
try {
|
|
612
|
+
const indexed = db.all(
|
|
613
|
+
sql`SELECT uid FROM vec_emails WHERE folder = ${folder}`
|
|
614
|
+
);
|
|
615
|
+
const live = new Set(
|
|
616
|
+
db.select({ uid: emails.uid }).from(emails).where(eq(emails.folder, folder)).all().map((r) => r.uid)
|
|
617
|
+
);
|
|
618
|
+
const orphans = [...new Set(indexed.map((r) => r.uid))].filter((uid) => !live.has(uid));
|
|
619
|
+
if (orphans.length === 0) return 0;
|
|
620
|
+
db.transaction((tx) => {
|
|
621
|
+
for (const uid of orphans) {
|
|
622
|
+
tx.run(sql`DELETE FROM vec_emails WHERE folder = ${folder} AND uid = ${int(uid)}`);
|
|
623
|
+
}
|
|
624
|
+
});
|
|
625
|
+
log3.info("pruned orphaned vectors", { folder, count: orphans.length });
|
|
626
|
+
return orphans.length;
|
|
627
|
+
} catch (err) {
|
|
628
|
+
log3.warn("could not prune orphaned vectors", { folder, err });
|
|
629
|
+
return 0;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
function countVectors(db, folder) {
|
|
633
|
+
const row = db.get(
|
|
634
|
+
sql`SELECT count(DISTINCT uid) AS c FROM vec_emails WHERE folder = ${folder}`
|
|
635
|
+
);
|
|
636
|
+
return row?.c ?? 0;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// src/cache/queries.ts
|
|
640
|
+
var log4 = createLogger("mcp-inbox:cache");
|
|
319
641
|
function upsertFolder(db, row) {
|
|
320
642
|
db.insert(folders).values(row).onConflictDoUpdate({
|
|
321
643
|
target: folders.name,
|
|
@@ -330,7 +652,7 @@ function upsertFolder(db, row) {
|
|
|
330
652
|
}).run();
|
|
331
653
|
}
|
|
332
654
|
function getFolder(db, name) {
|
|
333
|
-
return db.select().from(folders).where(
|
|
655
|
+
return db.select().from(folders).where(eq2(folders.name, name)).get();
|
|
334
656
|
}
|
|
335
657
|
function upsertEmail(db, row) {
|
|
336
658
|
db.insert(emails).values(row).onConflictDoUpdate({
|
|
@@ -357,24 +679,24 @@ function upsertEmails(db, rows) {
|
|
|
357
679
|
});
|
|
358
680
|
}
|
|
359
681
|
function getEmail(db, folder, uid) {
|
|
360
|
-
return db.select().from(emails).where(and(
|
|
682
|
+
return db.select().from(emails).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).get();
|
|
361
683
|
}
|
|
362
684
|
function getEmailsByUids(db, folder, uids) {
|
|
363
685
|
const out = /* @__PURE__ */ new Map();
|
|
364
686
|
if (uids.length === 0) return out;
|
|
365
687
|
inBatches(uids, (batch) => {
|
|
366
|
-
const rows = db.select().from(emails).where(and(
|
|
688
|
+
const rows = db.select().from(emails).where(and(eq2(emails.folder, folder), inArray(emails.uid, batch))).all();
|
|
367
689
|
for (const row of rows) out.set(row.uid, row);
|
|
368
690
|
});
|
|
369
691
|
return out;
|
|
370
692
|
}
|
|
371
693
|
function buildFolderConditions(folder, opts) {
|
|
372
|
-
const conditions = [
|
|
694
|
+
const conditions = [eq2(emails.folder, folder)];
|
|
373
695
|
if (opts.sinceMs !== void 0) conditions.push(gte(emails.date, opts.sinceMs));
|
|
374
696
|
if (opts.beforeMs !== void 0) conditions.push(lt(emails.date, opts.beforeMs));
|
|
375
697
|
if (opts.unseenOnly) {
|
|
376
698
|
conditions.push(
|
|
377
|
-
|
|
699
|
+
sql2`NOT EXISTS (SELECT 1 FROM json_each(${emails.flags}) WHERE value = ${"\\Seen"})`
|
|
378
700
|
);
|
|
379
701
|
}
|
|
380
702
|
return conditions;
|
|
@@ -385,15 +707,28 @@ function listEmailsByFolder(db, folder, opts = {}) {
|
|
|
385
707
|
}
|
|
386
708
|
function countEmailsInFolder(db, folder, opts = {}) {
|
|
387
709
|
const conditions = buildFolderConditions(folder, opts);
|
|
388
|
-
const row = db.select({ n:
|
|
710
|
+
const row = db.select({ n: count() }).from(emails).where(and(...conditions)).get();
|
|
711
|
+
return row?.n ?? 0;
|
|
712
|
+
}
|
|
713
|
+
function listIndexCandidates(db, folder, opts) {
|
|
714
|
+
const conditions = [eq2(emails.folder, folder)];
|
|
715
|
+
if (opts.aboveUid !== void 0) conditions.push(gt(emails.uid, opts.aboveUid));
|
|
716
|
+
if (opts.belowUid !== void 0) conditions.push(lt(emails.uid, opts.belowUid));
|
|
717
|
+
return db.select().from(emails).where(and(...conditions)).orderBy(opts.order === "asc" ? asc(emails.uid) : desc(emails.uid)).limit(opts.limit).all();
|
|
718
|
+
}
|
|
719
|
+
function countEmailsOutsideUidRange(db, folder, fromUid, toUid) {
|
|
720
|
+
const outside = fromUid === 0 && toUid === 0 ? void 0 : or2(lt(emails.uid, fromUid), gt(emails.uid, toUid));
|
|
721
|
+
const row = db.select({ n: count() }).from(emails).where(
|
|
722
|
+
outside === void 0 ? eq2(emails.folder, folder) : and(eq2(emails.folder, folder), outside)
|
|
723
|
+
).get();
|
|
389
724
|
return row?.n ?? 0;
|
|
390
725
|
}
|
|
391
726
|
function listCachedUidsForFolder(db, folder) {
|
|
392
|
-
const rows = db.select({ uid: emails.uid }).from(emails).where(
|
|
727
|
+
const rows = db.select({ uid: emails.uid }).from(emails).where(eq2(emails.folder, folder)).all();
|
|
393
728
|
return rows.map((r) => r.uid);
|
|
394
729
|
}
|
|
395
730
|
function setEmailFlags(db, folder, uid, flags) {
|
|
396
|
-
db.update(emails).set({ flags }).where(and(
|
|
731
|
+
db.update(emails).set({ flags }).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).run();
|
|
397
732
|
}
|
|
398
733
|
var UID_BATCH = 1e4;
|
|
399
734
|
function inBatches(items, run) {
|
|
@@ -406,11 +741,11 @@ function setFlagsForUids(db, folder, next) {
|
|
|
406
741
|
const uids = [...next.keys()];
|
|
407
742
|
db.transaction((tx) => {
|
|
408
743
|
inBatches(uids, (batch) => {
|
|
409
|
-
const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(
|
|
744
|
+
const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq2(emails.folder, folder), inArray(emails.uid, batch))).all();
|
|
410
745
|
for (const row of rows) {
|
|
411
746
|
const flags = next.get(row.uid);
|
|
412
747
|
if (!flags || flagsEqual(row.flags, flags)) continue;
|
|
413
|
-
tx.update(emails).set({ flags }).where(and(
|
|
748
|
+
tx.update(emails).set({ flags }).where(and(eq2(emails.folder, folder), eq2(emails.uid, row.uid))).run();
|
|
414
749
|
}
|
|
415
750
|
});
|
|
416
751
|
});
|
|
@@ -419,11 +754,11 @@ function mutateEmailFlagsForUids(db, folder, uids, mutate) {
|
|
|
419
754
|
if (uids.length === 0) return;
|
|
420
755
|
db.transaction((tx) => {
|
|
421
756
|
inBatches(uids, (batch) => {
|
|
422
|
-
const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(
|
|
757
|
+
const rows = tx.select({ uid: emails.uid, flags: emails.flags }).from(emails).where(and(eq2(emails.folder, folder), inArray(emails.uid, batch))).all();
|
|
423
758
|
for (const row of rows) {
|
|
424
759
|
const next = mutate(row.flags);
|
|
425
760
|
if (flagsEqual(row.flags, next)) continue;
|
|
426
|
-
tx.update(emails).set({ flags: next }).where(and(
|
|
761
|
+
tx.update(emails).set({ flags: next }).where(and(eq2(emails.folder, folder), eq2(emails.uid, row.uid))).run();
|
|
427
762
|
}
|
|
428
763
|
});
|
|
429
764
|
});
|
|
@@ -435,23 +770,26 @@ function flagsEqual(a, b) {
|
|
|
435
770
|
return true;
|
|
436
771
|
}
|
|
437
772
|
function deleteEmailsByFolder(db, folder) {
|
|
438
|
-
db.delete(emails).where(
|
|
773
|
+
db.delete(emails).where(eq2(emails.folder, folder)).run();
|
|
774
|
+
deleteVectorsByFolder(db, folder);
|
|
439
775
|
}
|
|
440
776
|
function deleteEmail(db, folder, uid) {
|
|
441
|
-
db.delete(emails).where(and(
|
|
777
|
+
db.delete(emails).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).run();
|
|
778
|
+
deleteVectorsByUids(db, folder, [uid]);
|
|
442
779
|
}
|
|
443
780
|
function deleteEmailsByUids(db, folder, uids) {
|
|
444
781
|
if (uids.length === 0) return;
|
|
445
782
|
inBatches(uids, (batch) => {
|
|
446
|
-
db.delete(emails).where(and(
|
|
783
|
+
db.delete(emails).where(and(eq2(emails.folder, folder), inArray(emails.uid, batch))).run();
|
|
447
784
|
});
|
|
785
|
+
deleteVectorsByUids(db, folder, uids);
|
|
448
786
|
}
|
|
449
787
|
function pruneBodiesBefore(db, cutoffMs) {
|
|
450
|
-
const stale = db.select({ n:
|
|
451
|
-
const
|
|
452
|
-
if (
|
|
788
|
+
const stale = db.select({ n: count() }).from(emails).where(lt(emails.bodyCachedAt, cutoffMs)).get();
|
|
789
|
+
const cleared = stale?.n ?? 0;
|
|
790
|
+
if (cleared === 0) return 0;
|
|
453
791
|
db.update(emails).set({ bodyText: null, bodyHtml: null, attachmentsJson: null, bodyCachedAt: null }).where(lt(emails.bodyCachedAt, cutoffMs)).run();
|
|
454
|
-
return
|
|
792
|
+
return cleared;
|
|
455
793
|
}
|
|
456
794
|
function getEmailBody(db, folder, uid) {
|
|
457
795
|
const row = db.select({
|
|
@@ -459,13 +797,13 @@ function getEmailBody(db, folder, uid) {
|
|
|
459
797
|
bodyHtml: emails.bodyHtml,
|
|
460
798
|
attachments: emails.attachmentsJson,
|
|
461
799
|
bodyCachedAt: emails.bodyCachedAt
|
|
462
|
-
}).from(emails).where(and(
|
|
800
|
+
}).from(emails).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).get();
|
|
463
801
|
return row;
|
|
464
802
|
}
|
|
465
803
|
function setEmailBody(db, folder, uid, body, nowMs) {
|
|
466
|
-
const existing = db.select({ uid: emails.uid }).from(emails).where(and(
|
|
804
|
+
const existing = db.select({ uid: emails.uid }).from(emails).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).get();
|
|
467
805
|
if (!existing) {
|
|
468
|
-
|
|
806
|
+
log4.warn("cannot cache body, envelope row missing", { folder, uid });
|
|
469
807
|
return false;
|
|
470
808
|
}
|
|
471
809
|
db.update(emails).set({
|
|
@@ -473,7 +811,7 @@ function setEmailBody(db, folder, uid, body, nowMs) {
|
|
|
473
811
|
bodyHtml: body.html,
|
|
474
812
|
attachmentsJson: body.attachments ?? [],
|
|
475
813
|
bodyCachedAt: nowMs
|
|
476
|
-
}).where(and(
|
|
814
|
+
}).where(and(eq2(emails.folder, folder), eq2(emails.uid, uid))).run();
|
|
477
815
|
return true;
|
|
478
816
|
}
|
|
479
817
|
|
|
@@ -570,9 +908,9 @@ function isMcpInboxError(err) {
|
|
|
570
908
|
}
|
|
571
909
|
|
|
572
910
|
// src/imap/client.ts
|
|
573
|
-
var
|
|
911
|
+
var log5 = createLogger("mcp-inbox:imap");
|
|
574
912
|
async function createImapConnection(config) {
|
|
575
|
-
|
|
913
|
+
log5.info("opening IMAP connection", {
|
|
576
914
|
host: config.host,
|
|
577
915
|
port: config.port,
|
|
578
916
|
tls: config.tls
|
|
@@ -593,8 +931,8 @@ async function createImapConnection(config) {
|
|
|
593
931
|
greetingTimeout: config.authTimeoutMs
|
|
594
932
|
});
|
|
595
933
|
flow.on("error", (err) => {
|
|
596
|
-
|
|
597
|
-
|
|
934
|
+
log5.error("IMAP connection error", {
|
|
935
|
+
err
|
|
598
936
|
});
|
|
599
937
|
});
|
|
600
938
|
try {
|
|
@@ -602,7 +940,7 @@ async function createImapConnection(config) {
|
|
|
602
940
|
} catch (err) {
|
|
603
941
|
throw mapImapError(err);
|
|
604
942
|
}
|
|
605
|
-
|
|
943
|
+
log5.info("IMAP connection ready");
|
|
606
944
|
return flow;
|
|
607
945
|
}
|
|
608
946
|
var ImapClient = class {
|
|
@@ -657,7 +995,7 @@ var ImapClient = class {
|
|
|
657
995
|
const flow = await createImapConnection(this.#config);
|
|
658
996
|
flow.on("close", () => {
|
|
659
997
|
if (!this.#closed) {
|
|
660
|
-
|
|
998
|
+
log5.warn("IMAP connection closed unexpectedly");
|
|
661
999
|
}
|
|
662
1000
|
if (this.#flow === flow) {
|
|
663
1001
|
this.#flow = null;
|
|
@@ -677,8 +1015,8 @@ var ImapClient = class {
|
|
|
677
1015
|
try {
|
|
678
1016
|
await flow.logout();
|
|
679
1017
|
} catch (err) {
|
|
680
|
-
|
|
681
|
-
|
|
1018
|
+
log5.warn("error during IMAP logout", {
|
|
1019
|
+
err
|
|
682
1020
|
});
|
|
683
1021
|
}
|
|
684
1022
|
}
|
|
@@ -686,8 +1024,9 @@ var ImapClient = class {
|
|
|
686
1024
|
};
|
|
687
1025
|
|
|
688
1026
|
// src/cache/sync.ts
|
|
689
|
-
var
|
|
1027
|
+
var log6 = createLogger("mcp-inbox:sync");
|
|
690
1028
|
var ENVELOPE_FLUSH_SIZE = 500;
|
|
1029
|
+
var FETCH_UID_BATCH = 500;
|
|
691
1030
|
async function syncFolder(ctx, folderPath) {
|
|
692
1031
|
const started = Date.now();
|
|
693
1032
|
const lock = await ctx.imap.getMailboxLock(folderPath);
|
|
@@ -699,7 +1038,7 @@ async function syncFolder(ctx, folderPath) {
|
|
|
699
1038
|
const cached = getFolder(ctx.db, folderPath);
|
|
700
1039
|
const uidValidityChanged = cached !== void 0 && cached.uidValidity !== Number(box.uidValidity);
|
|
701
1040
|
if (uidValidityChanged) {
|
|
702
|
-
|
|
1041
|
+
log6.warn("UIDVALIDITY changed - wiping folder cache", {
|
|
703
1042
|
folder: folderPath,
|
|
704
1043
|
cached: cached?.uidValidity,
|
|
705
1044
|
server: Number(box.uidValidity)
|
|
@@ -717,7 +1056,7 @@ async function syncFolder(ctx, folderPath) {
|
|
|
717
1056
|
lastSyncedAt: Date.now()
|
|
718
1057
|
});
|
|
719
1058
|
const durationMs = Date.now() - started;
|
|
720
|
-
|
|
1059
|
+
log6.info("folder synced", { folder: folderPath, syncType, fetched, durationMs });
|
|
721
1060
|
return { folder: folderPath, syncType, fetched, durationMs };
|
|
722
1061
|
} catch (err) {
|
|
723
1062
|
throw mapImapError(err);
|
|
@@ -744,7 +1083,7 @@ async function runSync(ctx, folderPath, box, cached, uidValidityChanged) {
|
|
|
744
1083
|
const { missing, ghosts } = diffUids(listCachedUidsForFolder(ctx.db, folderPath), serverUids);
|
|
745
1084
|
if (ghosts.length > 0) {
|
|
746
1085
|
deleteEmailsByUids(ctx.db, folderPath, ghosts);
|
|
747
|
-
|
|
1086
|
+
log6.info("evicted ghost UIDs", { folder: folderPath, removed: ghosts.length });
|
|
748
1087
|
}
|
|
749
1088
|
const fetched = missing.length > 0 ? await fetchEnvelopes(ctx, folderPath, missing) : 0;
|
|
750
1089
|
const serverModseq = box.highestModseq !== void 0 ? Number(box.highestModseq) : null;
|
|
@@ -760,26 +1099,28 @@ async function runSync(ctx, folderPath, box, cached, uidValidityChanged) {
|
|
|
760
1099
|
}
|
|
761
1100
|
async function fetchEnvelopes(ctx, folderPath, uids) {
|
|
762
1101
|
const now = Date.now();
|
|
763
|
-
let
|
|
764
|
-
const iterator = ctx.imap.fetch(
|
|
765
|
-
uids,
|
|
766
|
-
{ envelope: true, flags: true, internalDate: true, bodyStructure: true },
|
|
767
|
-
{ uid: true }
|
|
768
|
-
);
|
|
1102
|
+
let count2 = 0;
|
|
769
1103
|
const buffer = [];
|
|
770
|
-
for
|
|
771
|
-
const
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
1104
|
+
for (let i = 0; i < uids.length; i += FETCH_UID_BATCH) {
|
|
1105
|
+
const iterator = ctx.imap.fetch(
|
|
1106
|
+
uids.slice(i, i + FETCH_UID_BATCH),
|
|
1107
|
+
{ envelope: true, flags: true, internalDate: true, bodyStructure: true },
|
|
1108
|
+
{ uid: true }
|
|
1109
|
+
);
|
|
1110
|
+
for await (const msg of iterator) {
|
|
1111
|
+
const insert = messageToInsert(folderPath, msg, now);
|
|
1112
|
+
if (insert) {
|
|
1113
|
+
buffer.push(insert);
|
|
1114
|
+
count2++;
|
|
1115
|
+
if (buffer.length >= ENVELOPE_FLUSH_SIZE) {
|
|
1116
|
+
upsertEmails(ctx.db, buffer);
|
|
1117
|
+
buffer.length = 0;
|
|
1118
|
+
}
|
|
778
1119
|
}
|
|
779
1120
|
}
|
|
780
1121
|
}
|
|
781
1122
|
upsertEmails(ctx.db, buffer);
|
|
782
|
-
return
|
|
1123
|
+
return count2;
|
|
783
1124
|
}
|
|
784
1125
|
async function refreshFlags(ctx, folderPath, cachedModseq) {
|
|
785
1126
|
const options = cachedModseq !== null ? { uid: true, changedSince: BigInt(cachedModseq) } : { uid: true };
|
|
@@ -823,7 +1164,7 @@ function hasAttachments(structure) {
|
|
|
823
1164
|
}
|
|
824
1165
|
|
|
825
1166
|
// src/cache/idle.ts
|
|
826
|
-
var
|
|
1167
|
+
var log7 = createLogger("mcp-inbox:idle");
|
|
827
1168
|
var IdleManager = class {
|
|
828
1169
|
#opts;
|
|
829
1170
|
#subscriptions = [];
|
|
@@ -839,9 +1180,9 @@ var IdleManager = class {
|
|
|
839
1180
|
const sub = await this.#watchFolder(folder);
|
|
840
1181
|
this.#subscriptions.push(sub);
|
|
841
1182
|
} catch (err) {
|
|
842
|
-
|
|
1183
|
+
log7.error("failed to open IDLE for folder", {
|
|
843
1184
|
folder,
|
|
844
|
-
|
|
1185
|
+
err
|
|
845
1186
|
});
|
|
846
1187
|
}
|
|
847
1188
|
}
|
|
@@ -857,13 +1198,13 @@ var IdleManager = class {
|
|
|
857
1198
|
async #watchFolder(folder) {
|
|
858
1199
|
const imap = await createImapConnection(this.#opts.imap);
|
|
859
1200
|
await imap.mailboxOpen(folder);
|
|
860
|
-
|
|
1201
|
+
log7.info("watching folder", { folder });
|
|
861
1202
|
const onExists = (e) => {
|
|
862
|
-
|
|
1203
|
+
log7.debug("exists event", { folder: e.path, count: e.count, prevCount: e.prevCount });
|
|
863
1204
|
void this.#handleExists(folder, imap);
|
|
864
1205
|
};
|
|
865
1206
|
const onFlags = (e) => {
|
|
866
|
-
|
|
1207
|
+
log7.debug("flags event", { folder: e.path, uid: e.uid, flags: Array.from(e.flags) });
|
|
867
1208
|
if (e.uid !== void 0) {
|
|
868
1209
|
setEmailFlags(this.#opts.db, folder, e.uid, Array.from(e.flags));
|
|
869
1210
|
} else {
|
|
@@ -871,7 +1212,7 @@ var IdleManager = class {
|
|
|
871
1212
|
}
|
|
872
1213
|
};
|
|
873
1214
|
const onExpunge = (e) => {
|
|
874
|
-
|
|
1215
|
+
log7.debug("expunge event", { folder: e.path, uid: e.uid, seq: e.seq });
|
|
875
1216
|
if (e.uid !== void 0) {
|
|
876
1217
|
deleteEmail(this.#opts.db, folder, e.uid);
|
|
877
1218
|
} else {
|
|
@@ -890,39 +1231,550 @@ var IdleManager = class {
|
|
|
890
1231
|
try {
|
|
891
1232
|
await imap.logout();
|
|
892
1233
|
} catch (err) {
|
|
893
|
-
|
|
1234
|
+
log7.warn("error closing IDLE connection", {
|
|
894
1235
|
folder,
|
|
895
|
-
|
|
1236
|
+
err
|
|
896
1237
|
});
|
|
897
1238
|
}
|
|
898
1239
|
}
|
|
899
1240
|
};
|
|
900
1241
|
}
|
|
901
|
-
async #handleExists(folder, imap) {
|
|
1242
|
+
async #handleExists(folder, imap) {
|
|
1243
|
+
try {
|
|
1244
|
+
await syncFolder({ db: this.#opts.db, imap }, folder);
|
|
1245
|
+
} catch (err) {
|
|
1246
|
+
log7.error("exists sync failed", {
|
|
1247
|
+
folder,
|
|
1248
|
+
err
|
|
1249
|
+
});
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
async #resyncFolder(folder, imap) {
|
|
1253
|
+
try {
|
|
1254
|
+
await syncFolder({ db: this.#opts.db, imap }, folder);
|
|
1255
|
+
} catch (err) {
|
|
1256
|
+
log7.error("resync failed", {
|
|
1257
|
+
folder,
|
|
1258
|
+
err
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
};
|
|
1263
|
+
|
|
1264
|
+
// src/embeddings/client.ts
|
|
1265
|
+
import { z as z2 } from "zod";
|
|
1266
|
+
var log8 = createLogger("mcp-inbox:embeddings");
|
|
1267
|
+
var MAX_ATTEMPTS = 3;
|
|
1268
|
+
var BASE_BACKOFF_MS = 500;
|
|
1269
|
+
var MAX_RETRY_AFTER_MS = 6e4;
|
|
1270
|
+
var EmbeddingsResponse = z2.object({
|
|
1271
|
+
data: z2.array(
|
|
1272
|
+
z2.object({
|
|
1273
|
+
index: z2.number().int().min(0),
|
|
1274
|
+
embedding: z2.array(z2.number())
|
|
1275
|
+
})
|
|
1276
|
+
).min(1)
|
|
1277
|
+
});
|
|
1278
|
+
function envelopeText(email) {
|
|
1279
|
+
return `Subject: ${email.subject ?? ""}
|
|
1280
|
+
From: ${email.fromAddr ?? ""}`;
|
|
1281
|
+
}
|
|
1282
|
+
async function embedTexts(texts, cfg) {
|
|
1283
|
+
if (texts.length === 0) return [];
|
|
1284
|
+
const out = [];
|
|
1285
|
+
for (let i = 0; i < texts.length; i += cfg.batchSize) {
|
|
1286
|
+
const batch = texts.slice(i, i + cfg.batchSize);
|
|
1287
|
+
out.push(...await embedBatch(batch, cfg));
|
|
1288
|
+
}
|
|
1289
|
+
return out;
|
|
1290
|
+
}
|
|
1291
|
+
async function embedBatch(batch, cfg) {
|
|
1292
|
+
const response = await postWithRetry(batch, cfg);
|
|
1293
|
+
let body;
|
|
1294
|
+
try {
|
|
1295
|
+
body = await response.json();
|
|
1296
|
+
} catch (err) {
|
|
1297
|
+
throw new EmbeddingError(
|
|
1298
|
+
"EMBEDDING_UNREACHABLE",
|
|
1299
|
+
`The embeddings endpoint at ${cfg.baseUrl} returned a non-JSON response. Check IMAP_EMBEDDINGS_BASE_URL points at an OpenAI-compatible API.`,
|
|
1300
|
+
err
|
|
1301
|
+
);
|
|
1302
|
+
}
|
|
1303
|
+
const parsed = EmbeddingsResponse.safeParse(body);
|
|
1304
|
+
if (!parsed.success) {
|
|
1305
|
+
throw new EmbeddingError(
|
|
1306
|
+
"EMBEDDING_UNREACHABLE",
|
|
1307
|
+
`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.`,
|
|
1308
|
+
parsed.error
|
|
1309
|
+
);
|
|
1310
|
+
}
|
|
1311
|
+
const ordered = parsed.data.data.toSorted((a, b) => a.index - b.index);
|
|
1312
|
+
if (ordered.length !== batch.length) {
|
|
1313
|
+
throw new EmbeddingError(
|
|
1314
|
+
"EMBEDDING_UNREACHABLE",
|
|
1315
|
+
`Asked the embeddings endpoint for ${batch.length} vectors but received ${ordered.length}.`
|
|
1316
|
+
);
|
|
1317
|
+
}
|
|
1318
|
+
return ordered.map((item) => {
|
|
1319
|
+
if (item.embedding.length !== cfg.dims) {
|
|
1320
|
+
throw new EmbeddingError(
|
|
1321
|
+
"EMBEDDING_DIM_MISMATCH",
|
|
1322
|
+
`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.`
|
|
1323
|
+
);
|
|
1324
|
+
}
|
|
1325
|
+
return Float32Array.from(item.embedding);
|
|
1326
|
+
});
|
|
1327
|
+
}
|
|
1328
|
+
async function postWithRetry(batch, cfg) {
|
|
1329
|
+
let lastError;
|
|
1330
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
1331
|
+
let response;
|
|
1332
|
+
try {
|
|
1333
|
+
response = await fetch(`${cfg.baseUrl}/embeddings`, {
|
|
1334
|
+
method: "POST",
|
|
1335
|
+
headers: {
|
|
1336
|
+
"content-type": "application/json",
|
|
1337
|
+
...cfg.apiKey !== void 0 && { authorization: `Bearer ${cfg.apiKey}` }
|
|
1338
|
+
},
|
|
1339
|
+
body: JSON.stringify({ model: cfg.model, input: batch, encoding_format: "float" }),
|
|
1340
|
+
signal: AbortSignal.timeout(cfg.timeoutMs)
|
|
1341
|
+
});
|
|
1342
|
+
} catch (err) {
|
|
1343
|
+
lastError = err;
|
|
1344
|
+
if (attempt === MAX_ATTEMPTS) break;
|
|
1345
|
+
await sleep(backoffMs(attempt));
|
|
1346
|
+
continue;
|
|
1347
|
+
}
|
|
1348
|
+
if (response.ok) return response;
|
|
1349
|
+
if (response.status === 401 || response.status === 403) {
|
|
1350
|
+
throw new EmbeddingError(
|
|
1351
|
+
"EMBEDDING_AUTH_FAILED",
|
|
1352
|
+
`The embeddings endpoint at ${cfg.baseUrl} rejected the credentials (HTTP ${response.status}). Check IMAP_EMBEDDINGS_API_KEY.`
|
|
1353
|
+
);
|
|
1354
|
+
}
|
|
1355
|
+
await response.body?.cancel();
|
|
1356
|
+
lastError = new Error(`HTTP ${response.status}`);
|
|
1357
|
+
if (!isRetryable(response.status) || attempt === MAX_ATTEMPTS) break;
|
|
1358
|
+
log8.debug("embeddings request failed, retrying", { status: response.status, attempt });
|
|
1359
|
+
await sleep(retryAfterMs(response) ?? backoffMs(attempt));
|
|
1360
|
+
}
|
|
1361
|
+
throw new EmbeddingError(
|
|
1362
|
+
"EMBEDDING_UNREACHABLE",
|
|
1363
|
+
`Could not reach the embeddings endpoint at ${cfg.baseUrl} after ${MAX_ATTEMPTS} attempts. Check IMAP_EMBEDDINGS_BASE_URL and that the service is up.`,
|
|
1364
|
+
lastError
|
|
1365
|
+
);
|
|
1366
|
+
}
|
|
1367
|
+
function isRetryable(status) {
|
|
1368
|
+
return status === 408 || status === 429 || status >= 500;
|
|
1369
|
+
}
|
|
1370
|
+
function retryAfterMs(response) {
|
|
1371
|
+
const header = response.headers.get("retry-after");
|
|
1372
|
+
if (header === null) return void 0;
|
|
1373
|
+
const seconds = Number(header);
|
|
1374
|
+
if (!Number.isFinite(seconds) || seconds < 0) return void 0;
|
|
1375
|
+
return Math.min(seconds * 1e3, MAX_RETRY_AFTER_MS);
|
|
1376
|
+
}
|
|
1377
|
+
function backoffMs(attempt) {
|
|
1378
|
+
return BASE_BACKOFF_MS * 2 ** (attempt - 1) + Math.random() * 250;
|
|
1379
|
+
}
|
|
1380
|
+
function sleep(ms) {
|
|
1381
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
// src/embeddings/chunk.ts
|
|
1385
|
+
var CHUNK_TARGET = 1200;
|
|
1386
|
+
var CHUNK_OVERLAP = 150;
|
|
1387
|
+
var MAX_CHUNKS = 10;
|
|
1388
|
+
var MIN_CHUNK = 40;
|
|
1389
|
+
var MIN_AFTER_STRIP = 200;
|
|
1390
|
+
var FORWARD_SUBJECT = /\b(fwd?|fw|pd)\s*:/i;
|
|
1391
|
+
var QUOTE_MARKERS = [
|
|
1392
|
+
/^\s*>/,
|
|
1393
|
+
/^\s*_{5,}\s*$/,
|
|
1394
|
+
/^\s*-{2,}\s*(?:Original Message|Forwarded message)\s*-{2,}/i,
|
|
1395
|
+
/^\s*-{2,}\s*(?:Wiadomo[śs][ćc] oryginalna|Oryginalna wiadomo[śs][ćc])\s*-{2,}/i,
|
|
1396
|
+
/^\s*On\b.{0,200}\bwrote:\s*$/i,
|
|
1397
|
+
/^\s*(?:W dniu|Dnia)\b.{0,200}\b(?:napisa[łl](?:\(a\))?|pisze)\s*:\s*$/i
|
|
1398
|
+
];
|
|
1399
|
+
var HEADER_START = /^\s*(?:From|Od)\s*:\s*\S/i;
|
|
1400
|
+
var HEADER_FOLLOW = /^\s*(?:Sent|Wys[łl]ano|To|Do|Subject|Temat)\s*:\s*\S/i;
|
|
1401
|
+
function stripQuoted(text2, subject) {
|
|
1402
|
+
if (FORWARD_SUBJECT.test(subject ?? "")) return text2;
|
|
1403
|
+
const lines = text2.split(/\r?\n/);
|
|
1404
|
+
let cutAt = -1;
|
|
1405
|
+
for (const [i, line] of lines.entries()) {
|
|
1406
|
+
if (QUOTE_MARKERS.some((re) => re.test(line))) {
|
|
1407
|
+
cutAt = i;
|
|
1408
|
+
break;
|
|
1409
|
+
}
|
|
1410
|
+
if (HEADER_START.test(line) && lines.slice(i + 1, i + 4).some((l) => HEADER_FOLLOW.test(l))) {
|
|
1411
|
+
cutAt = i;
|
|
1412
|
+
break;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
if (cutAt < 0) return text2;
|
|
1416
|
+
const kept = lines.slice(0, cutAt).join("\n").trim();
|
|
1417
|
+
return kept.length < MIN_AFTER_STRIP ? text2 : kept;
|
|
1418
|
+
}
|
|
1419
|
+
function chunkText(text2) {
|
|
1420
|
+
const paragraphs = splitParagraphs(text2.replace(/\r\n/g, "\n").trim());
|
|
1421
|
+
const chunks = [];
|
|
1422
|
+
let current = "";
|
|
1423
|
+
for (const paragraph of paragraphs) {
|
|
1424
|
+
if (chunks.length >= MAX_CHUNKS) break;
|
|
1425
|
+
if (current.length > 0 && current.length + paragraph.length + 2 > CHUNK_TARGET) {
|
|
1426
|
+
chunks.push(current.trim());
|
|
1427
|
+
current = overlapFrom(current);
|
|
1428
|
+
}
|
|
1429
|
+
current = current.length > 0 ? `${current}
|
|
1430
|
+
|
|
1431
|
+
${paragraph}` : paragraph;
|
|
1432
|
+
}
|
|
1433
|
+
if (chunks.length < MAX_CHUNKS && current.trim().length > 0) chunks.push(current.trim());
|
|
1434
|
+
return chunks.slice(0, MAX_CHUNKS).filter((c) => c.length >= MIN_CHUNK);
|
|
1435
|
+
}
|
|
1436
|
+
function bodyChunks(text2, subject) {
|
|
1437
|
+
return chunkText(stripQuoted(text2, subject));
|
|
1438
|
+
}
|
|
1439
|
+
function splitParagraphs(text2) {
|
|
1440
|
+
const out = [];
|
|
1441
|
+
for (const block of text2.split(/\n\s*\n/)) {
|
|
1442
|
+
const trimmed = block.trim();
|
|
1443
|
+
if (trimmed.length === 0) continue;
|
|
1444
|
+
if (trimmed.length <= CHUNK_TARGET) {
|
|
1445
|
+
out.push(trimmed);
|
|
1446
|
+
continue;
|
|
1447
|
+
}
|
|
1448
|
+
for (const piece of hardSplit(trimmed)) out.push(piece);
|
|
1449
|
+
}
|
|
1450
|
+
return out;
|
|
1451
|
+
}
|
|
1452
|
+
function hardSplit(paragraph) {
|
|
1453
|
+
const out = [];
|
|
1454
|
+
let rest = paragraph;
|
|
1455
|
+
while (rest.length > CHUNK_TARGET) {
|
|
1456
|
+
const window = rest.slice(0, CHUNK_TARGET);
|
|
1457
|
+
const cut = window.lastIndexOf(" ");
|
|
1458
|
+
const at = cut > CHUNK_TARGET / 2 ? cut : CHUNK_TARGET;
|
|
1459
|
+
out.push(rest.slice(0, at).trim());
|
|
1460
|
+
rest = rest.slice(at).trim();
|
|
1461
|
+
}
|
|
1462
|
+
if (rest.length > 0) out.push(rest);
|
|
1463
|
+
return out;
|
|
1464
|
+
}
|
|
1465
|
+
function overlapFrom(chunk) {
|
|
1466
|
+
if (chunk.length <= CHUNK_OVERLAP) return chunk;
|
|
1467
|
+
const tail = chunk.slice(-CHUNK_OVERLAP);
|
|
1468
|
+
const space = tail.indexOf(" ");
|
|
1469
|
+
return space === -1 ? tail : tail.slice(space + 1);
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
// src/cache/backfill.ts
|
|
1473
|
+
var log9 = createLogger("mcp-inbox:backfill");
|
|
1474
|
+
function pendingForFolders(db, folders2) {
|
|
1475
|
+
let total = 0;
|
|
1476
|
+
for (const folder of folders2) {
|
|
1477
|
+
const state = getVecState(db, folder);
|
|
1478
|
+
if (state === void 0) continue;
|
|
1479
|
+
total += countEmailsOutsideUidRange(db, folder, state.fromUid, state.toUid);
|
|
1480
|
+
}
|
|
1481
|
+
return total;
|
|
1482
|
+
}
|
|
1483
|
+
async function backfillFolder(db, folder, cfg, budget, direction, now, fetchBodies) {
|
|
1484
|
+
const state = getVecState(db, folder);
|
|
1485
|
+
if (state === void 0) {
|
|
1486
|
+
throw new EmbeddingError(
|
|
1487
|
+
"EMBEDDING_NOT_INDEXED",
|
|
1488
|
+
`Folder "${folder}" is not indexed for semantic search. Run imap_index_folder with folder="${folder}" first, or use imap_search_emails.`
|
|
1489
|
+
);
|
|
1490
|
+
}
|
|
1491
|
+
let { fromUid, toUid } = state;
|
|
1492
|
+
let embedded = 0;
|
|
1493
|
+
let bodiesIndexed = 0;
|
|
1494
|
+
let left = budget;
|
|
1495
|
+
let bodiesAvailable = fetchBodies !== void 0;
|
|
1496
|
+
const startedEmpty = fromUid === 0 && toUid === 0;
|
|
1497
|
+
const runBatch = async (rows) => {
|
|
1498
|
+
let bodies = { texts: /* @__PURE__ */ new Map(), expected: 0 };
|
|
1499
|
+
if (bodiesAvailable && fetchBodies) {
|
|
1500
|
+
bodies = await fetchBodies(rows.map((r) => r.uid));
|
|
1501
|
+
if (bodies.expected > 0 && bodies.texts.size === 0) {
|
|
1502
|
+
bodiesAvailable = false;
|
|
1503
|
+
log9.warn("server returned no body parts - indexing envelopes only", { folder });
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
bodiesIndexed += bodies.texts.size;
|
|
1507
|
+
await embedBatch2(db, folder, rows, cfg, bodies.texts);
|
|
1508
|
+
};
|
|
1509
|
+
const widenRange = (rows) => {
|
|
1510
|
+
const uids = rows.map((r) => r.uid);
|
|
1511
|
+
fromUid = fromUid === 0 ? Math.min(...uids) : Math.min(fromUid, ...uids);
|
|
1512
|
+
toUid = Math.max(toUid, ...uids);
|
|
1513
|
+
upsertVecState(db, {
|
|
1514
|
+
folder,
|
|
1515
|
+
model: cfg.model,
|
|
1516
|
+
dims: cfg.dims,
|
|
1517
|
+
fromUid,
|
|
1518
|
+
toUid,
|
|
1519
|
+
indexedAt: now()
|
|
1520
|
+
});
|
|
1521
|
+
};
|
|
1522
|
+
if (!startedEmpty) {
|
|
1523
|
+
while (left > 0) {
|
|
1524
|
+
const rows = listIndexCandidates(db, folder, {
|
|
1525
|
+
aboveUid: toUid,
|
|
1526
|
+
limit: Math.min(cfg.batchSize, left),
|
|
1527
|
+
order: "asc"
|
|
1528
|
+
});
|
|
1529
|
+
if (rows.length === 0) break;
|
|
1530
|
+
await runBatch(rows);
|
|
1531
|
+
widenRange(rows);
|
|
1532
|
+
embedded += rows.length;
|
|
1533
|
+
left -= rows.length;
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
if (startedEmpty || direction === "both") {
|
|
1537
|
+
while (left > 0) {
|
|
1538
|
+
const rows = listIndexCandidates(db, folder, {
|
|
1539
|
+
...fromUid > 0 && { belowUid: fromUid },
|
|
1540
|
+
limit: Math.min(cfg.batchSize, left),
|
|
1541
|
+
order: "desc"
|
|
1542
|
+
});
|
|
1543
|
+
if (rows.length === 0) break;
|
|
1544
|
+
await runBatch(rows);
|
|
1545
|
+
widenRange(rows);
|
|
1546
|
+
embedded += rows.length;
|
|
1547
|
+
left -= rows.length;
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
return {
|
|
1551
|
+
embedded,
|
|
1552
|
+
bodiesIndexed,
|
|
1553
|
+
remaining: countEmailsOutsideUidRange(db, folder, fromUid, toUid)
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
async function embedBatch2(db, folder, rows, cfg, bodies) {
|
|
1557
|
+
const texts = [];
|
|
1558
|
+
const owners = [];
|
|
1559
|
+
for (const row of rows) {
|
|
1560
|
+
texts.push(envelopeText(row));
|
|
1561
|
+
owners.push({ uid: row.uid, part: ENVELOPE_PART, date: row.date });
|
|
1562
|
+
const body = bodies.get(row.uid);
|
|
1563
|
+
if (body === void 0) continue;
|
|
1564
|
+
for (const [i, chunk] of bodyChunks(body, row.subject).entries()) {
|
|
1565
|
+
texts.push(chunk);
|
|
1566
|
+
owners.push({ uid: row.uid, part: i + 1, date: row.date });
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
const vectors = await embedTexts(texts, cfg);
|
|
1570
|
+
const toInsert = [];
|
|
1571
|
+
for (const [i, owner] of owners.entries()) {
|
|
1572
|
+
const vector = vectors[i];
|
|
1573
|
+
if (vector === void 0) {
|
|
1574
|
+
throw new EmbeddingError(
|
|
1575
|
+
"EMBEDDING_UNREACHABLE",
|
|
1576
|
+
`The embeddings endpoint returned ${vectors.length} vectors for ${owners.length} texts.`
|
|
1577
|
+
);
|
|
1578
|
+
}
|
|
1579
|
+
toInsert.push({ ...owner, vector });
|
|
1580
|
+
}
|
|
1581
|
+
insertVectors(db, folder, toInsert);
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
// src/imap/body-text.ts
|
|
1585
|
+
var log10 = createLogger("mcp-inbox:body-text");
|
|
1586
|
+
var MAX_PART_BYTES = 1e6;
|
|
1587
|
+
function pickTextPart(structure) {
|
|
1588
|
+
if (structure === void 0) return null;
|
|
1589
|
+
let best = null;
|
|
1590
|
+
const queue = [structure];
|
|
1591
|
+
while (queue.length > 0) {
|
|
1592
|
+
const node = queue.shift();
|
|
1593
|
+
if (node === void 0) continue;
|
|
1594
|
+
if (isAttachment(node)) continue;
|
|
1595
|
+
const rank = node.type === "text/plain" ? 0 : node.type === "text/html" ? 1 : -1;
|
|
1596
|
+
if (rank >= 0 && (best === null || rank < best.rank)) {
|
|
1597
|
+
best = { node, rank };
|
|
1598
|
+
}
|
|
1599
|
+
if (node.childNodes) queue.push(...node.childNodes);
|
|
1600
|
+
}
|
|
1601
|
+
if (best === null) return null;
|
|
1602
|
+
if (typeof best.node.size === "number" && best.node.size > MAX_PART_BYTES) return null;
|
|
1603
|
+
return {
|
|
1604
|
+
part: best.node.part ?? "1",
|
|
1605
|
+
charset: best.node.parameters?.["charset"] ?? "utf-8",
|
|
1606
|
+
encoding: best.node.encoding ?? "7bit",
|
|
1607
|
+
isHtml: best.rank === 1
|
|
1608
|
+
};
|
|
1609
|
+
}
|
|
1610
|
+
function decodeTextPart(raw, part, alreadyDecoded = false) {
|
|
1611
|
+
const bytes = alreadyDecoded ? raw : decodeTransfer(raw, part.encoding);
|
|
1612
|
+
let text2;
|
|
1613
|
+
try {
|
|
1614
|
+
text2 = new TextDecoder(part.charset).decode(bytes);
|
|
1615
|
+
} catch {
|
|
1616
|
+
text2 = new TextDecoder("utf-8").decode(bytes);
|
|
1617
|
+
}
|
|
1618
|
+
return part.isHtml ? flattenHtml(text2) : text2;
|
|
1619
|
+
}
|
|
1620
|
+
async function fetchTextBodies(imap, uids) {
|
|
1621
|
+
const texts = /* @__PURE__ */ new Map();
|
|
1622
|
+
if (uids.length === 0) return { texts, expected: 0 };
|
|
1623
|
+
const parts = /* @__PURE__ */ new Map();
|
|
1624
|
+
for await (const msg of imap.fetch([...uids], { bodyStructure: true }, { uid: true })) {
|
|
1625
|
+
const picked = pickTextPart(msg.bodyStructure);
|
|
1626
|
+
if (picked !== null) parts.set(msg.uid, picked);
|
|
1627
|
+
}
|
|
1628
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1629
|
+
for (const [uid, part] of parts) {
|
|
1630
|
+
const bucket = groups.get(part.part);
|
|
1631
|
+
if (bucket === void 0) groups.set(part.part, [uid]);
|
|
1632
|
+
else bucket.push(uid);
|
|
1633
|
+
}
|
|
1634
|
+
for (const [partId, groupUids] of groups) {
|
|
1635
|
+
const key = partId.toLowerCase();
|
|
902
1636
|
try {
|
|
903
|
-
await
|
|
1637
|
+
for await (const msg of imap.fetch([...groupUids], { bodyParts: [partId] }, { uid: true })) {
|
|
1638
|
+
const raw = msg.bodyParts?.get(key);
|
|
1639
|
+
const part = parts.get(msg.uid);
|
|
1640
|
+
if (raw === void 0 || raw.length === 0 || part === void 0) continue;
|
|
1641
|
+
const decoded = decodeTextPart(raw, part, msg.binaryParts?.has(key) === true);
|
|
1642
|
+
const trimmed = decoded.trim();
|
|
1643
|
+
if (trimmed.length > 0) texts.set(msg.uid, trimmed);
|
|
1644
|
+
}
|
|
904
1645
|
} catch (err) {
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
1646
|
+
log10.warn("body part fetch failed for a part group", {
|
|
1647
|
+
part: partId,
|
|
1648
|
+
uids: groupUids.length,
|
|
1649
|
+
err
|
|
908
1650
|
});
|
|
909
1651
|
}
|
|
910
1652
|
}
|
|
911
|
-
|
|
1653
|
+
return { texts, expected: parts.size };
|
|
1654
|
+
}
|
|
1655
|
+
function bodyFetcherFor(client, folder) {
|
|
1656
|
+
return async (uids) => {
|
|
912
1657
|
try {
|
|
913
|
-
|
|
1658
|
+
const imap = await client.connection();
|
|
1659
|
+
const lock = await imap.getMailboxLock(folder);
|
|
1660
|
+
try {
|
|
1661
|
+
return await fetchTextBodies(imap, uids);
|
|
1662
|
+
} finally {
|
|
1663
|
+
lock.release();
|
|
1664
|
+
}
|
|
914
1665
|
} catch (err) {
|
|
915
|
-
|
|
1666
|
+
log10.warn("could not fetch body text", {
|
|
916
1667
|
folder,
|
|
917
|
-
|
|
1668
|
+
err
|
|
918
1669
|
});
|
|
1670
|
+
return { texts: /* @__PURE__ */ new Map(), expected: 0 };
|
|
1671
|
+
}
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
function isAttachment(node) {
|
|
1675
|
+
return node.disposition === "attachment" || node.dispositionParameters?.["filename"] !== void 0;
|
|
1676
|
+
}
|
|
1677
|
+
function decodeTransfer(raw, encoding) {
|
|
1678
|
+
switch (encoding.toLowerCase()) {
|
|
1679
|
+
case "base64":
|
|
1680
|
+
return Buffer.from(raw.toString("ascii"), "base64");
|
|
1681
|
+
case "quoted-printable":
|
|
1682
|
+
return decodeQuotedPrintable(raw);
|
|
1683
|
+
default:
|
|
1684
|
+
return raw;
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
function decodeQuotedPrintable(raw) {
|
|
1688
|
+
const source = raw.toString("latin1").replace(/=\r?\n/g, "");
|
|
1689
|
+
const out = [];
|
|
1690
|
+
for (let i = 0; i < source.length; i++) {
|
|
1691
|
+
if (source.charAt(i) === "=" && /^[\da-f]{2}$/i.test(source.slice(i + 1, i + 3))) {
|
|
1692
|
+
out.push(Number.parseInt(source.slice(i + 1, i + 3), 16));
|
|
1693
|
+
i += 2;
|
|
1694
|
+
continue;
|
|
1695
|
+
}
|
|
1696
|
+
out.push(source.charCodeAt(i));
|
|
1697
|
+
}
|
|
1698
|
+
return Buffer.from(out);
|
|
1699
|
+
}
|
|
1700
|
+
function flattenHtml(html) {
|
|
1701
|
+
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(/ /gi, " ").replace(/&/gi, "&").replace(/</gi, "<").replace(/>/gi, ">").replace(/"/gi, '"').replace(/&#(\d+);/g, (_m, code) => String.fromCodePoint(Number(code))).replace(/[ \t]{2,}/g, " ").replace(/\n{3,}/g, "\n\n");
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
// src/cache/indexer.ts
|
|
1705
|
+
var log11 = createLogger("mcp-inbox:indexer");
|
|
1706
|
+
var IndexSweeper = class {
|
|
1707
|
+
#opts;
|
|
1708
|
+
#timer = null;
|
|
1709
|
+
#running = false;
|
|
1710
|
+
#stopped = false;
|
|
1711
|
+
constructor(opts) {
|
|
1712
|
+
this.#opts = opts;
|
|
1713
|
+
}
|
|
1714
|
+
start() {
|
|
1715
|
+
if (this.#timer !== null || this.#stopped || this.#opts.intervalMs <= 0) return;
|
|
1716
|
+
this.#timer = setInterval(() => {
|
|
1717
|
+
void this.sweepOnce();
|
|
1718
|
+
}, this.#opts.intervalMs);
|
|
1719
|
+
this.#timer.unref();
|
|
1720
|
+
log11.info("background index sweeper started", { everyMs: this.#opts.intervalMs });
|
|
1721
|
+
}
|
|
1722
|
+
stop() {
|
|
1723
|
+
this.#stopped = true;
|
|
1724
|
+
if (this.#timer !== null) {
|
|
1725
|
+
clearInterval(this.#timer);
|
|
1726
|
+
this.#timer = null;
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
/**
|
|
1730
|
+
* One pass over the indexed folders. Never rejects: this runs detached from
|
|
1731
|
+
* any request, so an escaping error would be an unhandled rejection.
|
|
1732
|
+
*/
|
|
1733
|
+
async sweepOnce() {
|
|
1734
|
+
if (this.#running || this.#stopped) return { folders: 0, embedded: 0 };
|
|
1735
|
+
this.#running = true;
|
|
1736
|
+
let embedded = 0;
|
|
1737
|
+
let visited = 0;
|
|
1738
|
+
let budget = this.#opts.budgetPerTick;
|
|
1739
|
+
try {
|
|
1740
|
+
ensureVecTable(this.#opts.db, this.#opts.cfg.model, this.#opts.cfg.dims);
|
|
1741
|
+
for (const folder of indexedFolders(this.#opts.db)) {
|
|
1742
|
+
if (budget <= 0 || this.#stopped) break;
|
|
1743
|
+
visited++;
|
|
1744
|
+
try {
|
|
1745
|
+
const imap = await this.#opts.imap.connection();
|
|
1746
|
+
await syncFolder({ db: this.#opts.db, imap }, folder);
|
|
1747
|
+
const result = await backfillFolder(
|
|
1748
|
+
this.#opts.db,
|
|
1749
|
+
folder,
|
|
1750
|
+
this.#opts.cfg,
|
|
1751
|
+
budget,
|
|
1752
|
+
"newer",
|
|
1753
|
+
this.#opts.now,
|
|
1754
|
+
bodyFetcherFor(this.#opts.imap, folder)
|
|
1755
|
+
);
|
|
1756
|
+
embedded += result.embedded;
|
|
1757
|
+
budget -= result.embedded;
|
|
1758
|
+
} catch (err) {
|
|
1759
|
+
log11.warn("sweep failed for folder", {
|
|
1760
|
+
folder,
|
|
1761
|
+
err
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
}
|
|
1765
|
+
} catch (err) {
|
|
1766
|
+
log11.warn("sweep aborted", { err });
|
|
1767
|
+
} finally {
|
|
1768
|
+
this.#running = false;
|
|
919
1769
|
}
|
|
1770
|
+
if (embedded > 0) log11.info("background index sweep", { folders: visited, embedded });
|
|
1771
|
+
return { folders: visited, embedded };
|
|
920
1772
|
}
|
|
921
1773
|
};
|
|
922
1774
|
|
|
923
1775
|
// src/smtp/client.ts
|
|
924
|
-
import
|
|
925
|
-
var
|
|
1776
|
+
import { createTransport } from "nodemailer";
|
|
1777
|
+
var log12 = createLogger("mcp-inbox:smtp");
|
|
926
1778
|
var SmtpClient = class {
|
|
927
1779
|
#config;
|
|
928
1780
|
#transporter = null;
|
|
@@ -935,12 +1787,12 @@ var SmtpClient = class {
|
|
|
935
1787
|
throw new Error("SmtpClient has been closed");
|
|
936
1788
|
}
|
|
937
1789
|
if (this.#transporter) return this.#transporter;
|
|
938
|
-
|
|
1790
|
+
log12.info("creating SMTP transporter", {
|
|
939
1791
|
host: this.#config.host,
|
|
940
1792
|
port: this.#config.port,
|
|
941
1793
|
secure: this.#config.secure
|
|
942
1794
|
});
|
|
943
|
-
this.#transporter =
|
|
1795
|
+
this.#transporter = createTransport({
|
|
944
1796
|
host: this.#config.host,
|
|
945
1797
|
port: this.#config.port,
|
|
946
1798
|
secure: this.#config.secure,
|
|
@@ -993,7 +1845,7 @@ import {
|
|
|
993
1845
|
// package.json
|
|
994
1846
|
var package_default = {
|
|
995
1847
|
name: "@kbzowski/mcp-inbox",
|
|
996
|
-
version: "0.
|
|
1848
|
+
version: "0.6.1",
|
|
997
1849
|
description: "MCP server exposing IMAP/SMTP email over a fast local cache. Read, search, compose, and manage email from any IMAP provider with near-instant response times via background sync and IDLE push.",
|
|
998
1850
|
type: "module",
|
|
999
1851
|
main: "./dist/index.js",
|
|
@@ -1057,36 +1909,36 @@ var package_default = {
|
|
|
1057
1909
|
release: "changeset publish"
|
|
1058
1910
|
},
|
|
1059
1911
|
dependencies: {
|
|
1060
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
1061
|
-
"drizzle-orm": "1.0.0-
|
|
1062
|
-
imapflow: "^
|
|
1063
|
-
mailparser: "^3.
|
|
1064
|
-
nodemailer: "^
|
|
1065
|
-
|
|
1912
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
1913
|
+
"drizzle-orm": "1.0.0-rc.6",
|
|
1914
|
+
imapflow: "^2.12.2",
|
|
1915
|
+
mailparser: "^3.15.0",
|
|
1916
|
+
nodemailer: "^10.6.1",
|
|
1917
|
+
"sqlite-vec": "0.1.9",
|
|
1918
|
+
zod: "^4.6.7"
|
|
1066
1919
|
},
|
|
1067
1920
|
devDependencies: {
|
|
1068
|
-
"@changesets/cli": "^
|
|
1069
|
-
"@types/mailparser": "^3.
|
|
1070
|
-
"@types/node": "^26.
|
|
1071
|
-
"
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
oxlint: "^
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
tsx: "^4.19.0",
|
|
1921
|
+
"@changesets/cli": "^3.0.3",
|
|
1922
|
+
"@types/mailparser": "^3.9.0",
|
|
1923
|
+
"@types/node": "^26.6.6",
|
|
1924
|
+
"drizzle-kit": "1.0.0-rc.6",
|
|
1925
|
+
esbuild: "^0.28.2",
|
|
1926
|
+
lefthook: "^2.2.2",
|
|
1927
|
+
oxfmt: "^0.79.0",
|
|
1928
|
+
oxlint: "^1.94.0",
|
|
1929
|
+
"oxlint-tsgolint": "^7.0.2008",
|
|
1930
|
+
testcontainers: "^12.2.2",
|
|
1931
|
+
tsx: "^4.23.15",
|
|
1080
1932
|
typescript: "^7.0.2",
|
|
1081
|
-
vitest: "^
|
|
1933
|
+
vitest: "^5.1.1"
|
|
1082
1934
|
}
|
|
1083
1935
|
};
|
|
1084
1936
|
|
|
1085
1937
|
// src/tools/registry.ts
|
|
1086
|
-
import { z as
|
|
1938
|
+
import { z as z26 } from "zod";
|
|
1087
1939
|
|
|
1088
1940
|
// src/tools/folders/list-folders.ts
|
|
1089
|
-
import { z as
|
|
1941
|
+
import { z as z3 } from "zod";
|
|
1090
1942
|
|
|
1091
1943
|
// src/tools/define-tool.ts
|
|
1092
1944
|
function defineTool(def) {
|
|
@@ -1102,6 +1954,33 @@ function formatFoldersMarkdown(folders2) {
|
|
|
1102
1954
|
}
|
|
1103
1955
|
return lines.join("\n");
|
|
1104
1956
|
}
|
|
1957
|
+
function formatSemanticResultsMarkdown(rows, pendingIndex) {
|
|
1958
|
+
if (rows.length === 0) return "_No indexed message resembles that query._";
|
|
1959
|
+
const lines = [
|
|
1960
|
+
"| # | Score | Flags | From | Subject | Date | Folder | UID |",
|
|
1961
|
+
"|---|---|---|---|---|---|---|---|"
|
|
1962
|
+
];
|
|
1963
|
+
rows.forEach((r, i) => {
|
|
1964
|
+
const marks = (r.unseen ? "UNSEEN " : "") + (r.has_attachments ? "\u{1F4CE}" : "");
|
|
1965
|
+
const subject = (r.subject ?? "").replace(/\|/g, "\\|");
|
|
1966
|
+
const from = (r.from ?? "").replace(/\|/g, "\\|");
|
|
1967
|
+
const folder = r.folder.replace(/\|/g, "\\|");
|
|
1968
|
+
const date = r.date === null ? "" : r.date.slice(0, 16).replace("T", " ");
|
|
1969
|
+
const row = `| ${i + 1} | ${r.score.toFixed(3)} | ${marks.trim()} | ${from} | ${subject} | ${date} | ${folder} | ${r.uid} |`;
|
|
1970
|
+
lines.push(r.unseen ? `**${row}**` : row);
|
|
1971
|
+
});
|
|
1972
|
+
lines.push(
|
|
1973
|
+
"",
|
|
1974
|
+
"_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._"
|
|
1975
|
+
);
|
|
1976
|
+
if (pendingIndex > 0) {
|
|
1977
|
+
lines.push(
|
|
1978
|
+
"",
|
|
1979
|
+
`_${pendingIndex} message(s) in this folder are not yet indexed; re-run \`imap_index_folder\` to include them._`
|
|
1980
|
+
);
|
|
1981
|
+
}
|
|
1982
|
+
return lines.join("\n");
|
|
1983
|
+
}
|
|
1105
1984
|
function formatEmailListMarkdown(emails2) {
|
|
1106
1985
|
if (emails2.length === 0) return "_No emails match._";
|
|
1107
1986
|
const lines = [
|
|
@@ -1121,8 +2000,8 @@ function formatEmailListMarkdown(emails2) {
|
|
|
1121
2000
|
}
|
|
1122
2001
|
|
|
1123
2002
|
// src/tools/folders/list-folders.ts
|
|
1124
|
-
var Input =
|
|
1125
|
-
response_format:
|
|
2003
|
+
var Input = z3.object({
|
|
2004
|
+
response_format: z3.enum(["markdown", "json"]).default("markdown")
|
|
1126
2005
|
});
|
|
1127
2006
|
var listFoldersTool = defineTool({
|
|
1128
2007
|
name: "imap_list_folders",
|
|
@@ -1157,7 +2036,7 @@ var listFoldersTool = defineTool({
|
|
|
1157
2036
|
});
|
|
1158
2037
|
|
|
1159
2038
|
// src/tools/emails/list-emails.ts
|
|
1160
|
-
import { z as
|
|
2039
|
+
import { z as z4 } from "zod";
|
|
1161
2040
|
|
|
1162
2041
|
// src/tools/emails/shared.ts
|
|
1163
2042
|
import { simpleParser } from "mailparser";
|
|
@@ -1214,6 +2093,11 @@ var NAME_CANDIDATES = {
|
|
|
1214
2093
|
};
|
|
1215
2094
|
|
|
1216
2095
|
// src/tools/emails/shared.ts
|
|
2096
|
+
async function deleteOrThrow(imap, folder, uids) {
|
|
2097
|
+
if (!await imap.messageDelete(uids, { uid: true })) {
|
|
2098
|
+
throw new ImapError("IMAP_UNKNOWN", `Server did not delete the message(s) from ${folder}.`);
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
1217
2101
|
async function syncIfStale(ctx, folder, maxStalenessSec = ctx.cacheConfig.defaultStalenessSec) {
|
|
1218
2102
|
const cached = getFolder(ctx.db, folder);
|
|
1219
2103
|
const ageMs = cached ? ctx.now() - cached.lastSyncedAt : Infinity;
|
|
@@ -1224,6 +2108,21 @@ async function syncIfStale(ctx, folder, maxStalenessSec = ctx.cacheConfig.defaul
|
|
|
1224
2108
|
}
|
|
1225
2109
|
return stale;
|
|
1226
2110
|
}
|
|
2111
|
+
function requireEmbeddings(ctx) {
|
|
2112
|
+
if (ctx.embeddings === null) {
|
|
2113
|
+
throw new EmbeddingError(
|
|
2114
|
+
"EMBEDDING_DISABLED",
|
|
2115
|
+
"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."
|
|
2116
|
+
);
|
|
2117
|
+
}
|
|
2118
|
+
if (!ctx.vectorsAvailable) {
|
|
2119
|
+
throw new EmbeddingError(
|
|
2120
|
+
"EMBEDDING_INDEX_UNAVAILABLE",
|
|
2121
|
+
"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."
|
|
2122
|
+
);
|
|
2123
|
+
}
|
|
2124
|
+
return ctx.embeddings;
|
|
2125
|
+
}
|
|
1227
2126
|
function readEnvelopes(ctx, folder, opts) {
|
|
1228
2127
|
const rows = listEmailsByFolder(ctx.db, folder, opts);
|
|
1229
2128
|
const total = countEmailsInFolder(ctx.db, folder, opts);
|
|
@@ -1332,17 +2231,17 @@ function projectEmailSummary(e) {
|
|
|
1332
2231
|
}
|
|
1333
2232
|
|
|
1334
2233
|
// src/tools/emails/list-emails.ts
|
|
1335
|
-
var Input2 =
|
|
1336
|
-
folder:
|
|
1337
|
-
limit:
|
|
1338
|
-
offset:
|
|
1339
|
-
unseen_only:
|
|
1340
|
-
since_date:
|
|
1341
|
-
before_date:
|
|
1342
|
-
max_staleness_seconds:
|
|
2234
|
+
var Input2 = z4.object({
|
|
2235
|
+
folder: z4.string().min(1).default("INBOX").describe("Folder path to list. Use imap_list_folders to discover paths."),
|
|
2236
|
+
limit: z4.number().int().min(1).max(100).default(20),
|
|
2237
|
+
offset: z4.number().int().min(0).default(0),
|
|
2238
|
+
unseen_only: z4.boolean().default(false),
|
|
2239
|
+
since_date: z4.string().date().optional().describe("YYYY-MM-DD. Only return emails received on or after this date."),
|
|
2240
|
+
before_date: z4.string().date().optional().describe("YYYY-MM-DD. Only return emails received strictly before this date."),
|
|
2241
|
+
max_staleness_seconds: z4.number().int().min(0).optional().describe(
|
|
1343
2242
|
"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
2243
|
),
|
|
1345
|
-
response_format:
|
|
2244
|
+
response_format: z4.enum(["markdown", "json"]).default("markdown")
|
|
1346
2245
|
});
|
|
1347
2246
|
var listEmailsTool = defineTool({
|
|
1348
2247
|
name: "imap_list_emails",
|
|
@@ -1384,16 +2283,16 @@ var listEmailsTool = defineTool({
|
|
|
1384
2283
|
});
|
|
1385
2284
|
|
|
1386
2285
|
// src/tools/emails/get-email.ts
|
|
1387
|
-
import { z as
|
|
1388
|
-
var Input3 =
|
|
1389
|
-
folder:
|
|
1390
|
-
uid:
|
|
2286
|
+
import { z as z5 } from "zod";
|
|
2287
|
+
var Input3 = z5.object({
|
|
2288
|
+
folder: z5.string().min(1).describe("Folder containing the message."),
|
|
2289
|
+
uid: z5.number().int().positive().describe(
|
|
1391
2290
|
"IMAP UID of the message. UIDs are folder-scoped - a UID from INBOX cannot be reused with the Sent folder."
|
|
1392
2291
|
),
|
|
1393
|
-
max_staleness_seconds:
|
|
2292
|
+
max_staleness_seconds: z5.number().int().min(0).optional().describe(
|
|
1394
2293
|
"Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
|
|
1395
2294
|
),
|
|
1396
|
-
response_format:
|
|
2295
|
+
response_format: z5.enum(["markdown", "json"]).default("markdown")
|
|
1397
2296
|
});
|
|
1398
2297
|
var getEmailTool = defineTool({
|
|
1399
2298
|
name: "imap_get_email",
|
|
@@ -1454,7 +2353,7 @@ function formatEmailDetail(e) {
|
|
|
1454
2353
|
}
|
|
1455
2354
|
|
|
1456
2355
|
// src/tools/emails/search-emails.ts
|
|
1457
|
-
import { z as
|
|
2356
|
+
import { z as z6 } from "zod";
|
|
1458
2357
|
|
|
1459
2358
|
// src/imap/search.ts
|
|
1460
2359
|
function buildImapSearch(c) {
|
|
@@ -1479,47 +2378,47 @@ function buildImapSearch(c) {
|
|
|
1479
2378
|
}
|
|
1480
2379
|
|
|
1481
2380
|
// src/tools/emails/search-emails.ts
|
|
1482
|
-
var Criteria =
|
|
1483
|
-
() =>
|
|
1484
|
-
subject:
|
|
1485
|
-
from:
|
|
1486
|
-
to:
|
|
1487
|
-
body:
|
|
1488
|
-
unseen:
|
|
1489
|
-
flagged:
|
|
1490
|
-
answered:
|
|
1491
|
-
since:
|
|
1492
|
-
before:
|
|
1493
|
-
larger_than_bytes:
|
|
1494
|
-
smaller_than_bytes:
|
|
1495
|
-
or:
|
|
2381
|
+
var Criteria = z6.lazy(
|
|
2382
|
+
() => z6.object({
|
|
2383
|
+
subject: z6.string().min(1).optional(),
|
|
2384
|
+
from: z6.string().min(1).optional(),
|
|
2385
|
+
to: z6.string().min(1).optional(),
|
|
2386
|
+
body: z6.string().min(1).optional(),
|
|
2387
|
+
unseen: z6.boolean().optional(),
|
|
2388
|
+
flagged: z6.boolean().optional(),
|
|
2389
|
+
answered: z6.boolean().optional(),
|
|
2390
|
+
since: z6.coerce.date().optional(),
|
|
2391
|
+
before: z6.coerce.date().optional(),
|
|
2392
|
+
larger_than_bytes: z6.number().int().positive().optional(),
|
|
2393
|
+
smaller_than_bytes: z6.number().int().positive().optional(),
|
|
2394
|
+
or: z6.array(Criteria).min(2).optional(),
|
|
1496
2395
|
not: Criteria.optional()
|
|
1497
2396
|
})
|
|
1498
2397
|
);
|
|
1499
|
-
var Input4 =
|
|
1500
|
-
folder:
|
|
1501
|
-
subject:
|
|
1502
|
-
from:
|
|
1503
|
-
to:
|
|
1504
|
-
body:
|
|
1505
|
-
unseen:
|
|
1506
|
-
flagged:
|
|
1507
|
-
answered:
|
|
1508
|
-
since_date:
|
|
1509
|
-
before_date:
|
|
1510
|
-
larger_than_bytes:
|
|
1511
|
-
smaller_than_bytes:
|
|
1512
|
-
or:
|
|
2398
|
+
var Input4 = z6.object({
|
|
2399
|
+
folder: z6.string().min(1).default("INBOX"),
|
|
2400
|
+
subject: z6.string().min(1).optional(),
|
|
2401
|
+
from: z6.string().min(1).optional(),
|
|
2402
|
+
to: z6.string().min(1).optional(),
|
|
2403
|
+
body: z6.string().min(1).optional(),
|
|
2404
|
+
unseen: z6.boolean().optional(),
|
|
2405
|
+
flagged: z6.boolean().optional().describe("true = starred only, false = unstarred only, omit for no filter."),
|
|
2406
|
+
answered: z6.boolean().optional().describe("true = replied-to only, false = not-replied-to only, omit for no filter."),
|
|
2407
|
+
since_date: z6.string().date().optional(),
|
|
2408
|
+
before_date: z6.string().date().optional(),
|
|
2409
|
+
larger_than_bytes: z6.number().int().positive().optional().describe("Only match messages larger than this many bytes."),
|
|
2410
|
+
smaller_than_bytes: z6.number().int().positive().optional().describe("Only match messages smaller than this many bytes."),
|
|
2411
|
+
or: z6.array(Criteria).min(2).optional().describe(
|
|
1513
2412
|
'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
2413
|
),
|
|
1515
2414
|
not: Criteria.optional().describe(
|
|
1516
2415
|
'Sub-criteria that must NOT match. Useful for excluding auto-generated mail, e.g. `{not: {from: "noreply"}}`.'
|
|
1517
2416
|
),
|
|
1518
|
-
limit:
|
|
1519
|
-
max_staleness_seconds:
|
|
2417
|
+
limit: z6.number().int().min(1).max(100).default(20),
|
|
2418
|
+
max_staleness_seconds: z6.number().int().min(0).optional().describe(
|
|
1520
2419
|
"Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
|
|
1521
2420
|
),
|
|
1522
|
-
response_format:
|
|
2421
|
+
response_format: z6.enum(["markdown", "json"]).default("markdown")
|
|
1523
2422
|
}).refine(
|
|
1524
2423
|
(v) => [
|
|
1525
2424
|
v.subject,
|
|
@@ -1628,8 +2527,205 @@ var searchEmailsTool = defineTool({
|
|
|
1628
2527
|
}
|
|
1629
2528
|
});
|
|
1630
2529
|
|
|
2530
|
+
// src/tools/emails/semantic-search.ts
|
|
2531
|
+
import { z as z7 } from "zod";
|
|
2532
|
+
var OVERFETCH_FACTOR = 5;
|
|
2533
|
+
var Input5 = z7.object({
|
|
2534
|
+
query: z7.string().min(1).describe("Natural-language description of the message you are looking for."),
|
|
2535
|
+
folder: z7.string().min(1).optional().describe("Restrict the search to one folder. Omit to search every indexed folder at once."),
|
|
2536
|
+
limit: z7.number().int().min(1).max(50).default(10),
|
|
2537
|
+
since_date: z7.string().date().optional(),
|
|
2538
|
+
before_date: z7.string().date().optional(),
|
|
2539
|
+
max_staleness_seconds: z7.number().int().min(0).optional().describe(
|
|
2540
|
+
"Sync the folder first if its cache is older than this. Ignored when no folder is given. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
|
|
2541
|
+
),
|
|
2542
|
+
response_format: z7.enum(["markdown", "json"]).default("markdown")
|
|
2543
|
+
});
|
|
2544
|
+
var semanticSearchTool = defineTool({
|
|
2545
|
+
name: "imap_semantic_search",
|
|
2546
|
+
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.',
|
|
2547
|
+
annotations: {
|
|
2548
|
+
readOnlyHint: true,
|
|
2549
|
+
destructiveHint: false,
|
|
2550
|
+
idempotentHint: true,
|
|
2551
|
+
openWorldHint: true
|
|
2552
|
+
},
|
|
2553
|
+
inputSchema: Input5,
|
|
2554
|
+
handler: async (args, ctx) => {
|
|
2555
|
+
const cfg = requireEmbeddings(ctx);
|
|
2556
|
+
ensureVecTable(ctx.db, cfg.model, cfg.dims);
|
|
2557
|
+
const indexed = indexedFolders(ctx.db);
|
|
2558
|
+
if (indexed.length === 0) {
|
|
2559
|
+
throw new EmbeddingError(
|
|
2560
|
+
"EMBEDDING_NOT_INDEXED",
|
|
2561
|
+
"No folder has been indexed for semantic search yet. Run imap_index_folder first, or use imap_search_emails."
|
|
2562
|
+
);
|
|
2563
|
+
}
|
|
2564
|
+
if (args.folder !== void 0 && !indexed.includes(args.folder)) {
|
|
2565
|
+
throw new EmbeddingError(
|
|
2566
|
+
"EMBEDDING_NOT_INDEXED",
|
|
2567
|
+
`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.`
|
|
2568
|
+
);
|
|
2569
|
+
}
|
|
2570
|
+
const folders2 = args.folder === void 0 ? indexed : [args.folder];
|
|
2571
|
+
if (args.folder !== void 0) {
|
|
2572
|
+
await syncIfStale(ctx, args.folder, args.max_staleness_seconds);
|
|
2573
|
+
}
|
|
2574
|
+
const remaining = pendingForFolders(ctx.db, folders2);
|
|
2575
|
+
const [queryVector] = await embedTexts([args.query], cfg);
|
|
2576
|
+
if (queryVector === void 0) {
|
|
2577
|
+
throw new EmbeddingError(
|
|
2578
|
+
"EMBEDDING_UNREACHABLE",
|
|
2579
|
+
"The embeddings endpoint returned no vector for the search query."
|
|
2580
|
+
);
|
|
2581
|
+
}
|
|
2582
|
+
const hits = knnSearch(ctx.db, queryVector, args.limit * OVERFETCH_FACTOR, {
|
|
2583
|
+
...args.folder !== void 0 && { folders: folders2 },
|
|
2584
|
+
...args.since_date !== void 0 && { sinceMs: Date.parse(args.since_date) },
|
|
2585
|
+
...args.before_date !== void 0 && { beforeMs: Date.parse(args.before_date) }
|
|
2586
|
+
});
|
|
2587
|
+
const byFolder = /* @__PURE__ */ new Map();
|
|
2588
|
+
for (const hit of hits) {
|
|
2589
|
+
const bucket = byFolder.get(hit.folder);
|
|
2590
|
+
if (bucket === void 0) byFolder.set(hit.folder, [hit.uid]);
|
|
2591
|
+
else bucket.push(hit.uid);
|
|
2592
|
+
}
|
|
2593
|
+
const cached = /* @__PURE__ */ new Map();
|
|
2594
|
+
for (const [folder, uids] of byFolder) {
|
|
2595
|
+
cached.set(folder, getEmailsByUids(ctx.db, folder, uids));
|
|
2596
|
+
}
|
|
2597
|
+
const ranked = hits.map((hit) => ({ hit, email: cached.get(hit.folder)?.get(hit.uid) })).filter((r) => r.email !== void 0).slice(0, args.limit);
|
|
2598
|
+
const structured = {
|
|
2599
|
+
folders: folders2,
|
|
2600
|
+
query: args.query,
|
|
2601
|
+
returned: ranked.length,
|
|
2602
|
+
pending_index: remaining,
|
|
2603
|
+
emails: ranked.map(
|
|
2604
|
+
({ hit, email }) => Object.assign(projectEmailSummary(email), {
|
|
2605
|
+
score: Number((1 - hit.distance).toFixed(4))
|
|
2606
|
+
})
|
|
2607
|
+
)
|
|
2608
|
+
};
|
|
2609
|
+
const text2 = args.response_format === "json" ? JSON.stringify(structured, null, 2) : formatSemanticResultsMarkdown(structured.emails, remaining);
|
|
2610
|
+
return {
|
|
2611
|
+
content: [{ type: "text", text: text2 }],
|
|
2612
|
+
structuredContent: structured
|
|
2613
|
+
};
|
|
2614
|
+
}
|
|
2615
|
+
});
|
|
2616
|
+
|
|
2617
|
+
// src/tools/emails/index-folder.ts
|
|
2618
|
+
import { z as z8 } from "zod";
|
|
2619
|
+
var Input6 = z8.object({
|
|
2620
|
+
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."),
|
|
2621
|
+
max_messages: z8.number().int().min(1).max(5e4).default(500).describe(
|
|
2622
|
+
"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."
|
|
2623
|
+
),
|
|
2624
|
+
max_staleness_seconds: z8.number().int().min(0).optional().describe(
|
|
2625
|
+
"Sync each folder first if its cache is older than this. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
|
|
2626
|
+
),
|
|
2627
|
+
response_format: z8.enum(["markdown", "json"]).default("markdown")
|
|
2628
|
+
});
|
|
2629
|
+
var indexFolderTool = defineTool({
|
|
2630
|
+
name: "imap_index_folder",
|
|
2631
|
+
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.",
|
|
2632
|
+
annotations: {
|
|
2633
|
+
readOnlyHint: false,
|
|
2634
|
+
destructiveHint: false,
|
|
2635
|
+
idempotentHint: true,
|
|
2636
|
+
openWorldHint: true
|
|
2637
|
+
},
|
|
2638
|
+
inputSchema: Input6,
|
|
2639
|
+
handler: async (args, ctx) => {
|
|
2640
|
+
const cfg = requireEmbeddings(ctx);
|
|
2641
|
+
ensureVecTable(ctx.db, cfg.model, cfg.dims);
|
|
2642
|
+
const reports = [];
|
|
2643
|
+
let budget = args.max_messages;
|
|
2644
|
+
for (const folder of args.folders) {
|
|
2645
|
+
const report = await indexOne(ctx, cfg, folder, budget, args.max_staleness_seconds);
|
|
2646
|
+
reports.push(report);
|
|
2647
|
+
budget -= report.embedded;
|
|
2648
|
+
if (budget <= 0) break;
|
|
2649
|
+
}
|
|
2650
|
+
const structured = {
|
|
2651
|
+
model: cfg.model,
|
|
2652
|
+
dims: cfg.dims,
|
|
2653
|
+
embedded: sum(reports, (r) => r.embedded),
|
|
2654
|
+
bodies_indexed: sum(reports, (r) => r.bodies_indexed),
|
|
2655
|
+
indexed_total: sum(reports, (r) => r.indexed_total),
|
|
2656
|
+
remaining: sum(reports, (r) => r.remaining),
|
|
2657
|
+
complete: reports.length === args.folders.length && reports.every((r) => r.complete),
|
|
2658
|
+
folders: reports
|
|
2659
|
+
};
|
|
2660
|
+
const text2 = args.response_format === "json" ? JSON.stringify(structured, null, 2) : formatIndexMarkdown(structured);
|
|
2661
|
+
return {
|
|
2662
|
+
content: [{ type: "text", text: text2 }],
|
|
2663
|
+
structuredContent: structured
|
|
2664
|
+
};
|
|
2665
|
+
}
|
|
2666
|
+
});
|
|
2667
|
+
async function indexOne(ctx, cfg, folder, budget, maxStalenessSeconds) {
|
|
2668
|
+
await syncIfStale(ctx, folder, maxStalenessSeconds);
|
|
2669
|
+
if (getVecState(ctx.db, folder) === void 0) {
|
|
2670
|
+
upsertVecState(ctx.db, {
|
|
2671
|
+
folder,
|
|
2672
|
+
model: cfg.model,
|
|
2673
|
+
dims: cfg.dims,
|
|
2674
|
+
fromUid: 0,
|
|
2675
|
+
toUid: 0,
|
|
2676
|
+
indexedAt: ctx.now()
|
|
2677
|
+
});
|
|
2678
|
+
}
|
|
2679
|
+
const pruned = pruneOrphanedVectors(ctx.db, folder);
|
|
2680
|
+
const result = await backfillFolder(
|
|
2681
|
+
ctx.db,
|
|
2682
|
+
folder,
|
|
2683
|
+
cfg,
|
|
2684
|
+
budget,
|
|
2685
|
+
"both",
|
|
2686
|
+
ctx.now,
|
|
2687
|
+
bodyFetcherFor(ctx.imap, folder)
|
|
2688
|
+
);
|
|
2689
|
+
return {
|
|
2690
|
+
folder,
|
|
2691
|
+
embedded: result.embedded,
|
|
2692
|
+
bodies_indexed: result.bodiesIndexed,
|
|
2693
|
+
pruned,
|
|
2694
|
+
indexed_total: countVectors(ctx.db, folder),
|
|
2695
|
+
remaining: result.remaining,
|
|
2696
|
+
complete: result.remaining === 0
|
|
2697
|
+
};
|
|
2698
|
+
}
|
|
2699
|
+
function sum(reports, pick) {
|
|
2700
|
+
return reports.reduce((total, r) => total + pick(r), 0);
|
|
2701
|
+
}
|
|
2702
|
+
function formatIndexMarkdown(s) {
|
|
2703
|
+
const lines = [
|
|
2704
|
+
`Indexed ${String(s.folders.length)} folder(s) for semantic search using \`${s.model}\`.`,
|
|
2705
|
+
"",
|
|
2706
|
+
"| Folder | Embedded | With text | Indexed | Pending |",
|
|
2707
|
+
"|---|---|---|---|---|"
|
|
2708
|
+
];
|
|
2709
|
+
for (const r of s.folders) {
|
|
2710
|
+
lines.push(
|
|
2711
|
+
`| ${r.folder} | ${r.embedded} | ${r.bodies_indexed} | ${r.indexed_total} | ${r.remaining} |`
|
|
2712
|
+
);
|
|
2713
|
+
}
|
|
2714
|
+
lines.push("");
|
|
2715
|
+
if (s.embedded > 0 && s.bodies_indexed === 0) {
|
|
2716
|
+
lines.push(
|
|
2717
|
+
"This server did not return message text, so only subjects and senders were indexed.",
|
|
2718
|
+
""
|
|
2719
|
+
);
|
|
2720
|
+
}
|
|
2721
|
+
lines.push(
|
|
2722
|
+
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."
|
|
2723
|
+
);
|
|
2724
|
+
return lines.join("\n");
|
|
2725
|
+
}
|
|
2726
|
+
|
|
1631
2727
|
// src/tools/emails/mark-read.ts
|
|
1632
|
-
import { z as
|
|
2728
|
+
import { z as z9 } from "zod";
|
|
1633
2729
|
|
|
1634
2730
|
// src/tools/emails/flags.ts
|
|
1635
2731
|
async function applyFlags(ctx, folder, uids, change) {
|
|
@@ -1660,9 +2756,9 @@ async function applyFlags(ctx, folder, uids, change) {
|
|
|
1660
2756
|
}
|
|
1661
2757
|
|
|
1662
2758
|
// src/tools/emails/mark-read.ts
|
|
1663
|
-
var
|
|
1664
|
-
folder:
|
|
1665
|
-
uid:
|
|
2759
|
+
var Input7 = z9.object({
|
|
2760
|
+
folder: z9.string().min(1).describe("Folder containing the message."),
|
|
2761
|
+
uid: z9.number().int().positive().describe("IMAP UID of the message. UIDs are folder-scoped.")
|
|
1666
2762
|
});
|
|
1667
2763
|
function updateSeenFlag(ctx, folder, uid, want) {
|
|
1668
2764
|
return applyFlags(
|
|
@@ -1681,7 +2777,7 @@ var markReadTool = defineTool({
|
|
|
1681
2777
|
idempotentHint: true,
|
|
1682
2778
|
openWorldHint: true
|
|
1683
2779
|
},
|
|
1684
|
-
inputSchema:
|
|
2780
|
+
inputSchema: Input7,
|
|
1685
2781
|
handler: async (args, ctx) => {
|
|
1686
2782
|
await updateSeenFlag(ctx, args.folder, args.uid, "add");
|
|
1687
2783
|
return {
|
|
@@ -1704,7 +2800,7 @@ var markUnreadTool = defineTool({
|
|
|
1704
2800
|
idempotentHint: true,
|
|
1705
2801
|
openWorldHint: true
|
|
1706
2802
|
},
|
|
1707
|
-
inputSchema:
|
|
2803
|
+
inputSchema: Input7,
|
|
1708
2804
|
handler: async (args, ctx) => {
|
|
1709
2805
|
await updateSeenFlag(ctx, args.folder, args.uid, "remove");
|
|
1710
2806
|
return {
|
|
@@ -1720,10 +2816,10 @@ var markUnreadTool = defineTool({
|
|
|
1720
2816
|
});
|
|
1721
2817
|
|
|
1722
2818
|
// src/tools/emails/mark-read-multiple.ts
|
|
1723
|
-
import { z as
|
|
1724
|
-
var
|
|
1725
|
-
folder:
|
|
1726
|
-
uids:
|
|
2819
|
+
import { z as z10 } from "zod";
|
|
2820
|
+
var Input8 = z10.object({
|
|
2821
|
+
folder: z10.string().min(1).describe("Folder containing the messages."),
|
|
2822
|
+
uids: z10.array(z10.number().int().positive()).min(1).max(500).describe(
|
|
1727
2823
|
"UIDs of messages to flip. Max 500 per call - chunk your own list for larger batches."
|
|
1728
2824
|
)
|
|
1729
2825
|
});
|
|
@@ -1744,7 +2840,7 @@ var markReadMultipleTool = defineTool({
|
|
|
1744
2840
|
idempotentHint: true,
|
|
1745
2841
|
openWorldHint: true
|
|
1746
2842
|
},
|
|
1747
|
-
inputSchema:
|
|
2843
|
+
inputSchema: Input8,
|
|
1748
2844
|
handler: async (args, ctx) => {
|
|
1749
2845
|
await updateSeenFlagBulk(ctx, args.folder, args.uids, "add");
|
|
1750
2846
|
return {
|
|
@@ -1772,7 +2868,7 @@ var markUnreadMultipleTool = defineTool({
|
|
|
1772
2868
|
idempotentHint: true,
|
|
1773
2869
|
openWorldHint: true
|
|
1774
2870
|
},
|
|
1775
|
-
inputSchema:
|
|
2871
|
+
inputSchema: Input8,
|
|
1776
2872
|
handler: async (args, ctx) => {
|
|
1777
2873
|
await updateSeenFlagBulk(ctx, args.folder, args.uids, "remove");
|
|
1778
2874
|
return {
|
|
@@ -1793,13 +2889,13 @@ var markUnreadMultipleTool = defineTool({
|
|
|
1793
2889
|
});
|
|
1794
2890
|
|
|
1795
2891
|
// src/tools/emails/set-flags.ts
|
|
1796
|
-
import { z as
|
|
1797
|
-
var Flag =
|
|
1798
|
-
var
|
|
1799
|
-
folder:
|
|
1800
|
-
uids:
|
|
1801
|
-
add:
|
|
1802
|
-
remove:
|
|
2892
|
+
import { z as z11 } from "zod";
|
|
2893
|
+
var Flag = z11.enum(["\\Flagged", "\\Answered"]);
|
|
2894
|
+
var Input9 = z11.object({
|
|
2895
|
+
folder: z11.string().min(1).describe("Folder containing the messages."),
|
|
2896
|
+
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."),
|
|
2897
|
+
add: z11.array(Flag).optional().describe("Flags to set. \\Flagged is the star / follow-up marker in mail clients."),
|
|
2898
|
+
remove: z11.array(Flag).optional().describe("Flags to clear.")
|
|
1803
2899
|
}).refine((v) => (v.add?.length ?? 0) > 0 || (v.remove?.length ?? 0) > 0, {
|
|
1804
2900
|
message: "Provide at least one flag in `add` or `remove`."
|
|
1805
2901
|
}).refine((v) => !v.add?.some((f) => v.remove?.includes(f)), {
|
|
@@ -1814,7 +2910,7 @@ var setFlagsTool = defineTool({
|
|
|
1814
2910
|
idempotentHint: true,
|
|
1815
2911
|
openWorldHint: true
|
|
1816
2912
|
},
|
|
1817
|
-
inputSchema:
|
|
2913
|
+
inputSchema: Input9,
|
|
1818
2914
|
handler: async (args, ctx) => {
|
|
1819
2915
|
const change = {
|
|
1820
2916
|
...args.add !== void 0 && { add: args.add },
|
|
@@ -1845,11 +2941,11 @@ var setFlagsTool = defineTool({
|
|
|
1845
2941
|
});
|
|
1846
2942
|
|
|
1847
2943
|
// src/tools/emails/move-to-folder.ts
|
|
1848
|
-
import { z as
|
|
1849
|
-
var
|
|
1850
|
-
folder:
|
|
1851
|
-
uid:
|
|
1852
|
-
destination:
|
|
2944
|
+
import { z as z12 } from "zod";
|
|
2945
|
+
var Input10 = z12.object({
|
|
2946
|
+
folder: z12.string().min(1).describe("Current folder of the message."),
|
|
2947
|
+
uid: z12.number().int().positive().describe("IMAP UID of the message to move."),
|
|
2948
|
+
destination: z12.string().min(1).describe(
|
|
1853
2949
|
"Target folder path. Use imap_list_folders to discover valid destinations. Must exist on the server."
|
|
1854
2950
|
)
|
|
1855
2951
|
});
|
|
@@ -1863,7 +2959,7 @@ var moveToFolderTool = defineTool({
|
|
|
1863
2959
|
idempotentHint: false,
|
|
1864
2960
|
openWorldHint: true
|
|
1865
2961
|
},
|
|
1866
|
-
inputSchema:
|
|
2962
|
+
inputSchema: Input10,
|
|
1867
2963
|
handler: async (args, ctx) => {
|
|
1868
2964
|
const imap = await ctx.imap.connection();
|
|
1869
2965
|
const lock = await imap.getMailboxLock(args.folder);
|
|
@@ -1901,11 +2997,11 @@ var moveToFolderTool = defineTool({
|
|
|
1901
2997
|
});
|
|
1902
2998
|
|
|
1903
2999
|
// src/tools/emails/move-multiple.ts
|
|
1904
|
-
import { z as
|
|
1905
|
-
var
|
|
1906
|
-
folder:
|
|
1907
|
-
uids:
|
|
1908
|
-
destination:
|
|
3000
|
+
import { z as z13 } from "zod";
|
|
3001
|
+
var Input11 = z13.object({
|
|
3002
|
+
folder: z13.string().min(1).describe("Current folder of the messages."),
|
|
3003
|
+
uids: z13.array(z13.number().int().positive()).min(1).max(500).describe("UIDs to move. Max 500 per call."),
|
|
3004
|
+
destination: z13.string().min(1).describe("Target folder. Must exist on the server.")
|
|
1909
3005
|
});
|
|
1910
3006
|
var moveMultipleTool = defineTool({
|
|
1911
3007
|
name: "imap_move_multiple",
|
|
@@ -1916,7 +3012,7 @@ var moveMultipleTool = defineTool({
|
|
|
1916
3012
|
idempotentHint: false,
|
|
1917
3013
|
openWorldHint: true
|
|
1918
3014
|
},
|
|
1919
|
-
inputSchema:
|
|
3015
|
+
inputSchema: Input11,
|
|
1920
3016
|
handler: async (args, ctx) => {
|
|
1921
3017
|
const imap = await ctx.imap.connection();
|
|
1922
3018
|
const lock = await imap.getMailboxLock(args.folder);
|
|
@@ -1953,11 +3049,11 @@ var moveMultipleTool = defineTool({
|
|
|
1953
3049
|
});
|
|
1954
3050
|
|
|
1955
3051
|
// src/tools/emails/delete-email.ts
|
|
1956
|
-
import { z as
|
|
1957
|
-
var
|
|
1958
|
-
folder:
|
|
1959
|
-
uid:
|
|
1960
|
-
hard_delete:
|
|
3052
|
+
import { z as z14 } from "zod";
|
|
3053
|
+
var Input12 = z14.object({
|
|
3054
|
+
folder: z14.string().min(1).describe("Folder containing the message to delete."),
|
|
3055
|
+
uid: z14.number().int().positive().describe("IMAP UID of the message to delete."),
|
|
3056
|
+
hard_delete: z14.boolean().default(false).describe(
|
|
1961
3057
|
"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
3058
|
)
|
|
1963
3059
|
});
|
|
@@ -1970,13 +3066,13 @@ var deleteEmailTool = defineTool({
|
|
|
1970
3066
|
idempotentHint: false,
|
|
1971
3067
|
openWorldHint: true
|
|
1972
3068
|
},
|
|
1973
|
-
inputSchema:
|
|
3069
|
+
inputSchema: Input12,
|
|
1974
3070
|
handler: async (args, ctx) => {
|
|
1975
3071
|
const imap = await ctx.imap.connection();
|
|
1976
3072
|
if (args.hard_delete) {
|
|
1977
3073
|
const lock2 = await imap.getMailboxLock(args.folder);
|
|
1978
3074
|
try {
|
|
1979
|
-
await imap.
|
|
3075
|
+
await deleteOrThrow(imap, args.folder, String(args.uid));
|
|
1980
3076
|
} catch (err) {
|
|
1981
3077
|
throw mapImapError(err);
|
|
1982
3078
|
} finally {
|
|
@@ -2038,11 +3134,11 @@ var deleteEmailTool = defineTool({
|
|
|
2038
3134
|
});
|
|
2039
3135
|
|
|
2040
3136
|
// src/tools/emails/delete-multiple.ts
|
|
2041
|
-
import { z as
|
|
2042
|
-
var
|
|
2043
|
-
folder:
|
|
2044
|
-
uids:
|
|
2045
|
-
hard_delete:
|
|
3137
|
+
import { z as z15 } from "zod";
|
|
3138
|
+
var Input13 = z15.object({
|
|
3139
|
+
folder: z15.string().min(1).describe("Folder containing the messages to delete."),
|
|
3140
|
+
uids: z15.array(z15.number().int().positive()).min(1).max(500).describe("UIDs to delete. Max 500 per call."),
|
|
3141
|
+
hard_delete: z15.boolean().default(false).describe(
|
|
2046
3142
|
"When false (default), messages move to the server Trash and can be recovered. When true, they are permanently expunged."
|
|
2047
3143
|
)
|
|
2048
3144
|
});
|
|
@@ -2055,13 +3151,13 @@ var deleteMultipleTool = defineTool({
|
|
|
2055
3151
|
idempotentHint: false,
|
|
2056
3152
|
openWorldHint: true
|
|
2057
3153
|
},
|
|
2058
|
-
inputSchema:
|
|
3154
|
+
inputSchema: Input13,
|
|
2059
3155
|
handler: async (args, ctx) => {
|
|
2060
3156
|
const imap = await ctx.imap.connection();
|
|
2061
3157
|
if (args.hard_delete) {
|
|
2062
3158
|
const lock2 = await imap.getMailboxLock(args.folder);
|
|
2063
3159
|
try {
|
|
2064
|
-
await imap.
|
|
3160
|
+
await deleteOrThrow(imap, args.folder, args.uids);
|
|
2065
3161
|
} catch (err) {
|
|
2066
3162
|
throw mapImapError(err);
|
|
2067
3163
|
} finally {
|
|
@@ -2125,17 +3221,17 @@ var deleteMultipleTool = defineTool({
|
|
|
2125
3221
|
});
|
|
2126
3222
|
|
|
2127
3223
|
// src/tools/drafts/list-drafts.ts
|
|
2128
|
-
import { z as
|
|
2129
|
-
var
|
|
2130
|
-
folder:
|
|
3224
|
+
import { z as z16 } from "zod";
|
|
3225
|
+
var Input14 = z16.object({
|
|
3226
|
+
folder: z16.string().min(1).optional().describe(
|
|
2131
3227
|
"Optional explicit Drafts folder path. If omitted, mcp-inbox auto-detects via RFC 6154 SPECIAL-USE."
|
|
2132
3228
|
),
|
|
2133
|
-
limit:
|
|
2134
|
-
offset:
|
|
2135
|
-
max_staleness_seconds:
|
|
3229
|
+
limit: z16.number().int().min(1).max(100).default(20),
|
|
3230
|
+
offset: z16.number().int().min(0).default(0),
|
|
3231
|
+
max_staleness_seconds: z16.number().int().min(0).optional().describe(
|
|
2136
3232
|
"Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
|
|
2137
3233
|
),
|
|
2138
|
-
response_format:
|
|
3234
|
+
response_format: z16.enum(["markdown", "json"]).default("markdown")
|
|
2139
3235
|
});
|
|
2140
3236
|
var listDraftsTool = defineTool({
|
|
2141
3237
|
name: "imap_list_drafts",
|
|
@@ -2146,7 +3242,7 @@ var listDraftsTool = defineTool({
|
|
|
2146
3242
|
idempotentHint: true,
|
|
2147
3243
|
openWorldHint: true
|
|
2148
3244
|
},
|
|
2149
|
-
inputSchema:
|
|
3245
|
+
inputSchema: Input14,
|
|
2150
3246
|
handler: async (args, ctx) => {
|
|
2151
3247
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
2152
3248
|
const didSync = await syncIfStale(ctx, folder, args.max_staleness_seconds);
|
|
@@ -2173,14 +3269,14 @@ ${formatEmailListMarkdown(rows)}`;
|
|
|
2173
3269
|
});
|
|
2174
3270
|
|
|
2175
3271
|
// src/tools/drafts/get-draft.ts
|
|
2176
|
-
import { z as
|
|
2177
|
-
var
|
|
2178
|
-
uid:
|
|
2179
|
-
folder:
|
|
2180
|
-
max_staleness_seconds:
|
|
3272
|
+
import { z as z17 } from "zod";
|
|
3273
|
+
var Input15 = z17.object({
|
|
3274
|
+
uid: z17.number().int().positive().describe("IMAP UID of the draft in the Drafts folder. Use imap_list_drafts to discover UIDs."),
|
|
3275
|
+
folder: z17.string().min(1).optional().describe("Optional explicit Drafts folder path. Auto-detected from SPECIAL-USE when omitted."),
|
|
3276
|
+
max_staleness_seconds: z17.number().int().min(0).optional().describe(
|
|
2181
3277
|
"Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
|
|
2182
3278
|
),
|
|
2183
|
-
response_format:
|
|
3279
|
+
response_format: z17.enum(["markdown", "json"]).default("markdown")
|
|
2184
3280
|
});
|
|
2185
3281
|
var getDraftTool = defineTool({
|
|
2186
3282
|
name: "imap_get_draft",
|
|
@@ -2191,7 +3287,7 @@ var getDraftTool = defineTool({
|
|
|
2191
3287
|
idempotentHint: true,
|
|
2192
3288
|
openWorldHint: true
|
|
2193
3289
|
},
|
|
2194
|
-
inputSchema:
|
|
3290
|
+
inputSchema: Input15,
|
|
2195
3291
|
handler: async (args, ctx) => {
|
|
2196
3292
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
2197
3293
|
const envelope = await ensureEnvelopeCached(ctx, folder, args.uid, args.max_staleness_seconds);
|
|
@@ -2226,7 +3322,7 @@ function formatDraftMarkdown(d) {
|
|
|
2226
3322
|
}
|
|
2227
3323
|
|
|
2228
3324
|
// src/tools/drafts/create-draft.ts
|
|
2229
|
-
import { z as
|
|
3325
|
+
import { z as z19 } from "zod";
|
|
2230
3326
|
|
|
2231
3327
|
// src/imap/mime-builder.ts
|
|
2232
3328
|
import MailComposer from "nodemailer/lib/mail-composer/index.js";
|
|
@@ -2250,16 +3346,16 @@ async function buildRawMessage(input) {
|
|
|
2250
3346
|
}
|
|
2251
3347
|
|
|
2252
3348
|
// src/tools/compose-schema.ts
|
|
2253
|
-
import { z as
|
|
2254
|
-
var AddressList =
|
|
2255
|
-
var AttachmentInput =
|
|
2256
|
-
filename:
|
|
2257
|
-
content_base64:
|
|
3349
|
+
import { z as z18 } from "zod";
|
|
3350
|
+
var AddressList = z18.union([z18.string().min(1), z18.array(z18.string().min(1)).min(1).max(500)]);
|
|
3351
|
+
var AttachmentInput = z18.object({
|
|
3352
|
+
filename: z18.string().min(1).describe('Name the recipient sees, e.g. "invoice.pdf".'),
|
|
3353
|
+
content_base64: z18.base64().describe(
|
|
2258
3354
|
"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
3355
|
),
|
|
2260
|
-
content_type:
|
|
3356
|
+
content_type: z18.string().min(1).optional().describe("MIME type. Omit to let the type be derived from `filename`.")
|
|
2261
3357
|
});
|
|
2262
|
-
var AttachmentList =
|
|
3358
|
+
var AttachmentList = z18.array(AttachmentInput).max(20).optional();
|
|
2263
3359
|
function toMessageAttachments(input) {
|
|
2264
3360
|
if (input === void 0) return void 0;
|
|
2265
3361
|
return input.map((a) => ({
|
|
@@ -2270,17 +3366,17 @@ function toMessageAttachments(input) {
|
|
|
2270
3366
|
}
|
|
2271
3367
|
|
|
2272
3368
|
// src/tools/drafts/create-draft.ts
|
|
2273
|
-
var
|
|
3369
|
+
var Input16 = z19.object({
|
|
2274
3370
|
to: AddressList.describe("Recipient email address or array of addresses."),
|
|
2275
|
-
subject:
|
|
2276
|
-
body:
|
|
2277
|
-
html:
|
|
3371
|
+
subject: z19.string(),
|
|
3372
|
+
body: z19.string().optional().describe("Plain-text body."),
|
|
3373
|
+
html: z19.string().optional().describe("HTML body (combined with text via multipart/alternative)."),
|
|
2278
3374
|
cc: AddressList.optional(),
|
|
2279
3375
|
bcc: AddressList.optional(),
|
|
2280
|
-
from:
|
|
3376
|
+
from: z19.string().min(1).optional().describe(
|
|
2281
3377
|
"Sender address. Defaults to IMAP_USER. Some providers reject mismatched From headers."
|
|
2282
3378
|
),
|
|
2283
|
-
folder:
|
|
3379
|
+
folder: z19.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted."),
|
|
2284
3380
|
attachments: AttachmentList
|
|
2285
3381
|
});
|
|
2286
3382
|
var createDraftTool = defineTool({
|
|
@@ -2292,7 +3388,7 @@ var createDraftTool = defineTool({
|
|
|
2292
3388
|
idempotentHint: false,
|
|
2293
3389
|
openWorldHint: true
|
|
2294
3390
|
},
|
|
2295
|
-
inputSchema:
|
|
3391
|
+
inputSchema: Input16,
|
|
2296
3392
|
handler: async (args, ctx) => {
|
|
2297
3393
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
2298
3394
|
const attachments = toMessageAttachments(args.attachments);
|
|
@@ -2334,17 +3430,18 @@ var createDraftTool = defineTool({
|
|
|
2334
3430
|
});
|
|
2335
3431
|
|
|
2336
3432
|
// src/tools/drafts/update-draft.ts
|
|
2337
|
-
import { z as
|
|
2338
|
-
var
|
|
2339
|
-
|
|
3433
|
+
import { z as z20 } from "zod";
|
|
3434
|
+
var log13 = createLogger("mcp-inbox:drafts");
|
|
3435
|
+
var Input17 = z20.object({
|
|
3436
|
+
uid: z20.number().int().positive().describe("UID of the existing draft to replace. Use imap_list_drafts to find it."),
|
|
2340
3437
|
to: AddressList,
|
|
2341
|
-
subject:
|
|
2342
|
-
body:
|
|
2343
|
-
html:
|
|
3438
|
+
subject: z20.string(),
|
|
3439
|
+
body: z20.string().optional(),
|
|
3440
|
+
html: z20.string().optional(),
|
|
2344
3441
|
cc: AddressList.optional(),
|
|
2345
3442
|
bcc: AddressList.optional(),
|
|
2346
|
-
from:
|
|
2347
|
-
folder:
|
|
3443
|
+
from: z20.string().min(1).optional(),
|
|
3444
|
+
folder: z20.string().min(1).optional(),
|
|
2348
3445
|
attachments: AttachmentList
|
|
2349
3446
|
});
|
|
2350
3447
|
var updateDraftTool = defineTool({
|
|
@@ -2357,7 +3454,7 @@ var updateDraftTool = defineTool({
|
|
|
2357
3454
|
idempotentHint: false,
|
|
2358
3455
|
openWorldHint: true
|
|
2359
3456
|
},
|
|
2360
|
-
inputSchema:
|
|
3457
|
+
inputSchema: Input17,
|
|
2361
3458
|
handler: async (args, ctx) => {
|
|
2362
3459
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
2363
3460
|
const attachments = toMessageAttachments(args.attachments);
|
|
@@ -2389,8 +3486,13 @@ var updateDraftTool = defineTool({
|
|
|
2389
3486
|
const lock = await imap.getMailboxLock(folder);
|
|
2390
3487
|
let deletedOld = true;
|
|
2391
3488
|
try {
|
|
2392
|
-
await imap
|
|
3489
|
+
await deleteOrThrow(imap, folder, String(args.uid));
|
|
2393
3490
|
} catch (err) {
|
|
3491
|
+
log13.warn("new draft saved, but deleting the old one failed", {
|
|
3492
|
+
folder,
|
|
3493
|
+
uid: args.uid,
|
|
3494
|
+
err
|
|
3495
|
+
});
|
|
2394
3496
|
deletedOld = false;
|
|
2395
3497
|
return {
|
|
2396
3498
|
content: [
|
|
@@ -2431,9 +3533,10 @@ var updateDraftTool = defineTool({
|
|
|
2431
3533
|
});
|
|
2432
3534
|
|
|
2433
3535
|
// src/tools/send/send-email.ts
|
|
2434
|
-
import { z as
|
|
3536
|
+
import { z as z21 } from "zod";
|
|
2435
3537
|
|
|
2436
3538
|
// src/tools/send/shared.ts
|
|
3539
|
+
var log14 = createLogger("mcp-inbox:send");
|
|
2437
3540
|
function normalizeAddrs(value) {
|
|
2438
3541
|
if (value === void 0) return [];
|
|
2439
3542
|
return Array.isArray(value) ? value : [value];
|
|
@@ -2454,6 +3557,7 @@ async function sendRawAndAppendSent(ctx, raw, envelope) {
|
|
|
2454
3557
|
const imap = await ctx.imap.connection();
|
|
2455
3558
|
await imap.append(sentFolder, raw, ["\\Seen"]);
|
|
2456
3559
|
} catch (err) {
|
|
3560
|
+
log14.warn("sent, but saving the copy failed", { folder: sentFolder, err });
|
|
2457
3561
|
sentSaveError = err instanceof Error ? err.message : String(err);
|
|
2458
3562
|
sentFolder = null;
|
|
2459
3563
|
}
|
|
@@ -2473,14 +3577,14 @@ function flattenCompose(args) {
|
|
|
2473
3577
|
}
|
|
2474
3578
|
|
|
2475
3579
|
// src/tools/send/send-email.ts
|
|
2476
|
-
var
|
|
3580
|
+
var Input18 = z21.object({
|
|
2477
3581
|
to: AddressList.describe("Recipient email address or array of addresses."),
|
|
2478
|
-
subject:
|
|
2479
|
-
body:
|
|
2480
|
-
html:
|
|
3582
|
+
subject: z21.string(),
|
|
3583
|
+
body: z21.string().optional().describe("Plain-text body."),
|
|
3584
|
+
html: z21.string().optional().describe("HTML body (sent as multipart/alternative with text)."),
|
|
2481
3585
|
cc: AddressList.optional(),
|
|
2482
3586
|
bcc: AddressList.optional(),
|
|
2483
|
-
from:
|
|
3587
|
+
from: z21.string().min(1).optional().describe(
|
|
2484
3588
|
"Sender address. Defaults to IMAP_USER. Providers like Gmail and Fastmail reject mismatched From unless the address is a verified alias."
|
|
2485
3589
|
),
|
|
2486
3590
|
attachments: AttachmentList
|
|
@@ -2494,7 +3598,7 @@ var sendEmailTool = defineTool({
|
|
|
2494
3598
|
idempotentHint: false,
|
|
2495
3599
|
openWorldHint: true
|
|
2496
3600
|
},
|
|
2497
|
-
inputSchema:
|
|
3601
|
+
inputSchema: Input18,
|
|
2498
3602
|
handler: async (args, ctx) => {
|
|
2499
3603
|
const compose = flattenCompose({
|
|
2500
3604
|
...args.from !== void 0 && { from: args.from },
|
|
@@ -2543,11 +3647,12 @@ var sendEmailTool = defineTool({
|
|
|
2543
3647
|
});
|
|
2544
3648
|
|
|
2545
3649
|
// src/tools/send/send-draft.ts
|
|
2546
|
-
import { z as
|
|
3650
|
+
import { z as z22 } from "zod";
|
|
2547
3651
|
import { simpleParser as simpleParser2 } from "mailparser";
|
|
2548
|
-
var
|
|
2549
|
-
|
|
2550
|
-
|
|
3652
|
+
var log15 = createLogger("mcp-inbox:send");
|
|
3653
|
+
var Input19 = z22.object({
|
|
3654
|
+
uid: z22.number().int().positive().describe("UID of the draft to send."),
|
|
3655
|
+
folder: z22.string().min(1).optional().describe("Explicit Drafts folder. Auto-resolves via SPECIAL-USE when omitted.")
|
|
2551
3656
|
});
|
|
2552
3657
|
var sendDraftTool = defineTool({
|
|
2553
3658
|
name: "imap_send_draft",
|
|
@@ -2558,7 +3663,7 @@ var sendDraftTool = defineTool({
|
|
|
2558
3663
|
idempotentHint: false,
|
|
2559
3664
|
openWorldHint: true
|
|
2560
3665
|
},
|
|
2561
|
-
inputSchema:
|
|
3666
|
+
inputSchema: Input19,
|
|
2562
3667
|
handler: async (args, ctx) => {
|
|
2563
3668
|
const folder = await resolveSpecialFolder(ctx, "\\Drafts", args.folder);
|
|
2564
3669
|
const imap = await ctx.imap.connection();
|
|
@@ -2606,9 +3711,10 @@ var sendDraftTool = defineTool({
|
|
|
2606
3711
|
const imap2 = await ctx.imap.connection();
|
|
2607
3712
|
const lock2 = await imap2.getMailboxLock(folder);
|
|
2608
3713
|
try {
|
|
2609
|
-
await imap2
|
|
3714
|
+
await deleteOrThrow(imap2, folder, String(args.uid));
|
|
2610
3715
|
deleteEmail(ctx.db, folder, args.uid);
|
|
2611
3716
|
} catch (err) {
|
|
3717
|
+
log15.warn("sent, but deleting the draft failed", { folder, uid: args.uid, err });
|
|
2612
3718
|
draftDeleted = false;
|
|
2613
3719
|
draftDeleteError = err instanceof Error ? err.message : String(err);
|
|
2614
3720
|
} finally {
|
|
@@ -2658,23 +3764,24 @@ function addressList(field) {
|
|
|
2658
3764
|
}
|
|
2659
3765
|
|
|
2660
3766
|
// src/tools/send/reply.ts
|
|
2661
|
-
import { z as
|
|
2662
|
-
var
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
3767
|
+
import { z as z23 } from "zod";
|
|
3768
|
+
var log16 = createLogger("mcp-inbox:send");
|
|
3769
|
+
var Input20 = z23.object({
|
|
3770
|
+
folder: z23.string().min(1).describe("Folder of the original message."),
|
|
3771
|
+
uid: z23.number().int().positive().describe("UID of the message being replied to."),
|
|
3772
|
+
body: z23.string().optional(),
|
|
3773
|
+
html: z23.string().optional(),
|
|
2667
3774
|
cc: AddressList.optional(),
|
|
2668
3775
|
bcc: AddressList.optional(),
|
|
2669
|
-
reply_all:
|
|
3776
|
+
reply_all: z23.boolean().default(false).describe(
|
|
2670
3777
|
"When true, CC the original To + Cc recipients (minus the sender). When false, reply only to the original From."
|
|
2671
3778
|
),
|
|
2672
|
-
from:
|
|
2673
|
-
max_staleness_seconds:
|
|
3779
|
+
from: z23.string().min(1).optional(),
|
|
3780
|
+
max_staleness_seconds: z23.number().int().min(0).optional().describe(
|
|
2674
3781
|
"Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
|
|
2675
3782
|
),
|
|
2676
3783
|
attachments: AttachmentList,
|
|
2677
|
-
mark_answered:
|
|
3784
|
+
mark_answered: z23.boolean().default(true).describe(
|
|
2678
3785
|
"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
3786
|
)
|
|
2680
3787
|
});
|
|
@@ -2687,7 +3794,7 @@ var replyTool = defineTool({
|
|
|
2687
3794
|
idempotentHint: false,
|
|
2688
3795
|
openWorldHint: true
|
|
2689
3796
|
},
|
|
2690
|
-
inputSchema:
|
|
3797
|
+
inputSchema: Input20,
|
|
2691
3798
|
handler: async (args, ctx) => {
|
|
2692
3799
|
const original = await ensureEnvelopeCached(
|
|
2693
3800
|
ctx,
|
|
@@ -2740,6 +3847,11 @@ var replyTool = defineTool({
|
|
|
2740
3847
|
markAnsweredError = `Server did not apply \\Answered to UID ${String(args.uid)} in ${args.folder}.`;
|
|
2741
3848
|
}
|
|
2742
3849
|
} catch (err) {
|
|
3850
|
+
log16.warn("replied, but setting \\Answered failed", {
|
|
3851
|
+
folder: args.folder,
|
|
3852
|
+
uid: args.uid,
|
|
3853
|
+
err
|
|
3854
|
+
});
|
|
2743
3855
|
markAnsweredError = err instanceof Error ? err.message : String(err);
|
|
2744
3856
|
}
|
|
2745
3857
|
}
|
|
@@ -2820,18 +3932,18 @@ function dedupeAddrs(addrs, exclude) {
|
|
|
2820
3932
|
}
|
|
2821
3933
|
|
|
2822
3934
|
// src/tools/send/forward.ts
|
|
2823
|
-
import { z as
|
|
2824
|
-
var
|
|
2825
|
-
folder:
|
|
2826
|
-
uid:
|
|
3935
|
+
import { z as z24 } from "zod";
|
|
3936
|
+
var Input21 = z24.object({
|
|
3937
|
+
folder: z24.string().min(1).describe("Folder of the original message."),
|
|
3938
|
+
uid: z24.number().int().positive().describe("UID of the message to forward."),
|
|
2827
3939
|
to: AddressList.describe("Recipient(s) to forward to."),
|
|
2828
|
-
body:
|
|
3940
|
+
body: z24.string().optional().describe(
|
|
2829
3941
|
'Optional prefix body (e.g. "FYI, thought you should see this."). Quoted original follows.'
|
|
2830
3942
|
),
|
|
2831
3943
|
cc: AddressList.optional(),
|
|
2832
3944
|
bcc: AddressList.optional(),
|
|
2833
|
-
from:
|
|
2834
|
-
max_staleness_seconds:
|
|
3945
|
+
from: z24.string().min(1).optional(),
|
|
3946
|
+
max_staleness_seconds: z24.number().int().min(0).optional().describe(
|
|
2835
3947
|
"Serve from cache if the folder was synced within this many seconds. Defaults to IMAP_CACHE_DEFAULT_STALENESS_SEC."
|
|
2836
3948
|
),
|
|
2837
3949
|
attachments: AttachmentList.describe(
|
|
@@ -2847,7 +3959,7 @@ var forwardTool = defineTool({
|
|
|
2847
3959
|
idempotentHint: false,
|
|
2848
3960
|
openWorldHint: true
|
|
2849
3961
|
},
|
|
2850
|
-
inputSchema:
|
|
3962
|
+
inputSchema: Input21,
|
|
2851
3963
|
handler: async (args, ctx) => {
|
|
2852
3964
|
const original = await ensureEnvelopeCached(
|
|
2853
3965
|
ctx,
|
|
@@ -2939,16 +4051,16 @@ function escapeHtml(s) {
|
|
|
2939
4051
|
}
|
|
2940
4052
|
|
|
2941
4053
|
// src/tools/attachments/get-attachment.ts
|
|
2942
|
-
import { z as
|
|
4054
|
+
import { z as z25 } from "zod";
|
|
2943
4055
|
import { simpleParser as simpleParser3 } from "mailparser";
|
|
2944
|
-
var
|
|
2945
|
-
folder:
|
|
2946
|
-
uid:
|
|
2947
|
-
filename:
|
|
4056
|
+
var Input22 = z25.object({
|
|
4057
|
+
folder: z25.string().min(1).describe("Folder containing the message."),
|
|
4058
|
+
uid: z25.number().int().positive().describe("IMAP UID of the message."),
|
|
4059
|
+
filename: z25.string().min(1).optional().describe(
|
|
2948
4060
|
"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
4061
|
),
|
|
2950
|
-
part_id:
|
|
2951
|
-
max_inline_mb:
|
|
4062
|
+
part_id: z25.string().min(1).optional().describe('MIME part ID (e.g. "1.2"). Use when multiple parts share a filename.'),
|
|
4063
|
+
max_inline_mb: z25.number().int().min(1).max(50).default(5).describe(
|
|
2952
4064
|
"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
4065
|
)
|
|
2954
4066
|
}).refine((v) => v.filename !== void 0 || v.part_id !== void 0, {
|
|
@@ -2963,7 +4075,7 @@ var getAttachmentTool = defineTool({
|
|
|
2963
4075
|
idempotentHint: true,
|
|
2964
4076
|
openWorldHint: true
|
|
2965
4077
|
},
|
|
2966
|
-
inputSchema:
|
|
4078
|
+
inputSchema: Input22,
|
|
2967
4079
|
handler: async (args, ctx) => {
|
|
2968
4080
|
const imap = await ctx.imap.connection();
|
|
2969
4081
|
const lock = await imap.getMailboxLock(args.folder);
|
|
@@ -3081,6 +4193,9 @@ var tools = [
|
|
|
3081
4193
|
searchEmailsTool,
|
|
3082
4194
|
listDraftsTool,
|
|
3083
4195
|
getDraftTool,
|
|
4196
|
+
// Semantic search (opt-in per folder, needs IMAP_EMBEDDINGS_BASE_URL)
|
|
4197
|
+
indexFolderTool,
|
|
4198
|
+
semanticSearchTool,
|
|
3084
4199
|
// Write (flag + move + delete)
|
|
3085
4200
|
markReadTool,
|
|
3086
4201
|
markUnreadTool,
|
|
@@ -3115,7 +4230,7 @@ function listToolEntries() {
|
|
|
3115
4230
|
// this setting, such types become `{}` (matches anything) in the
|
|
3116
4231
|
// exposed inputSchema, and the real validation still happens on
|
|
3117
4232
|
// the Zod side inside the CallTool dispatcher.
|
|
3118
|
-
inputSchema:
|
|
4233
|
+
inputSchema: z26.toJSONSchema(t.inputSchema, {
|
|
3119
4234
|
target: "draft-7",
|
|
3120
4235
|
unrepresentable: "any"
|
|
3121
4236
|
}),
|
|
@@ -3124,7 +4239,7 @@ function listToolEntries() {
|
|
|
3124
4239
|
}
|
|
3125
4240
|
|
|
3126
4241
|
// src/server.ts
|
|
3127
|
-
var
|
|
4242
|
+
var log17 = createLogger("mcp-inbox:server");
|
|
3128
4243
|
function createMcpServer(ctx) {
|
|
3129
4244
|
const server = new Server(
|
|
3130
4245
|
{
|
|
@@ -3144,39 +4259,42 @@ function createMcpServer(ctx) {
|
|
|
3144
4259
|
const toolName = request.params.name;
|
|
3145
4260
|
const tool = findTool(toolName);
|
|
3146
4261
|
if (!tool) {
|
|
3147
|
-
|
|
4262
|
+
log17.warn("unknown tool", { tool: toolName });
|
|
3148
4263
|
return errorResult(`Unknown tool: ${toolName}`);
|
|
3149
4264
|
}
|
|
3150
4265
|
const parsed = tool.inputSchema.safeParse(request.params.arguments ?? {});
|
|
3151
4266
|
if (!parsed.success) {
|
|
3152
4267
|
const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
|
|
3153
|
-
|
|
4268
|
+
log17.warn("invalid tool args", { tool: toolName, issues });
|
|
3154
4269
|
return errorResult(`Invalid arguments for ${toolName}: ${issues}`);
|
|
3155
4270
|
}
|
|
4271
|
+
const started = Date.now();
|
|
3156
4272
|
try {
|
|
3157
4273
|
return await tool.handler(parsed.data, ctx);
|
|
3158
4274
|
} catch (err) {
|
|
4275
|
+
const meta = {
|
|
4276
|
+
tool: toolName,
|
|
4277
|
+
durationMs: Date.now() - started,
|
|
4278
|
+
...failureContext(parsed.data),
|
|
4279
|
+
err
|
|
4280
|
+
};
|
|
3159
4281
|
if (isMcpInboxError(err)) {
|
|
3160
|
-
|
|
3161
|
-
tool: toolName,
|
|
3162
|
-
code: err.code,
|
|
3163
|
-
msg: err.userMessage
|
|
3164
|
-
});
|
|
4282
|
+
log17.warn("tool returned mcp-inbox error", meta);
|
|
3165
4283
|
return errorResult(err.userMessage);
|
|
3166
4284
|
}
|
|
3167
|
-
|
|
3168
|
-
tool: toolName,
|
|
3169
|
-
msg: err instanceof Error ? err.message : String(err)
|
|
3170
|
-
});
|
|
4285
|
+
log17.error("tool handler threw", meta);
|
|
3171
4286
|
return errorResult(`Internal error in ${toolName}. Check server logs for details.`);
|
|
3172
4287
|
}
|
|
3173
4288
|
});
|
|
3174
4289
|
server.onerror = (err) => {
|
|
3175
|
-
|
|
3176
|
-
log7.error("mcp server error", meta);
|
|
4290
|
+
log17.error("mcp server error", { err });
|
|
3177
4291
|
};
|
|
3178
4292
|
return server;
|
|
3179
4293
|
}
|
|
4294
|
+
function failureContext(args) {
|
|
4295
|
+
const { folder, uid, uids, destination } = args;
|
|
4296
|
+
return { folder, uid, uidCount: Array.isArray(uids) ? uids.length : void 0, destination };
|
|
4297
|
+
}
|
|
3180
4298
|
function errorResult(text2) {
|
|
3181
4299
|
return {
|
|
3182
4300
|
isError: true,
|
|
@@ -3223,6 +4341,8 @@ try {
|
|
|
3223
4341
|
imap: imapClient,
|
|
3224
4342
|
smtp: smtpClient,
|
|
3225
4343
|
cacheConfig: config.cache,
|
|
4344
|
+
embeddings: config.embeddings,
|
|
4345
|
+
vectorsAvailable: cache.vectorsAvailable,
|
|
3226
4346
|
defaults: {
|
|
3227
4347
|
fromAddress: config.imap.user
|
|
3228
4348
|
},
|
|
@@ -3236,32 +4356,43 @@ try {
|
|
|
3236
4356
|
if (idleManager) {
|
|
3237
4357
|
void idleManager.start();
|
|
3238
4358
|
}
|
|
4359
|
+
const sweeper = config.embeddings !== null && cache.vectorsAvailable && config.embeddings.sweepMinutes > 0 ? new IndexSweeper({
|
|
4360
|
+
db: cache.db,
|
|
4361
|
+
imap: imapClient,
|
|
4362
|
+
cfg: config.embeddings,
|
|
4363
|
+
intervalMs: config.embeddings.sweepMinutes * 6e4,
|
|
4364
|
+
budgetPerTick: config.embeddings.sweepBatch,
|
|
4365
|
+
now: () => Date.now()
|
|
4366
|
+
}) : null;
|
|
4367
|
+
sweeper?.start();
|
|
3239
4368
|
const server = createMcpServer(ctx);
|
|
3240
|
-
|
|
4369
|
+
let httpServer = null;
|
|
3241
4370
|
let shuttingDown = false;
|
|
3242
4371
|
const shutdown = async (signal) => {
|
|
3243
4372
|
if (shuttingDown) return;
|
|
3244
4373
|
shuttingDown = true;
|
|
3245
4374
|
rootLogger.info("shutting down", { signal });
|
|
4375
|
+
httpServer?.close();
|
|
3246
4376
|
try {
|
|
3247
4377
|
await server.close();
|
|
3248
4378
|
} catch (err) {
|
|
3249
4379
|
rootLogger.error("error closing MCP server", {
|
|
3250
|
-
|
|
4380
|
+
err
|
|
3251
4381
|
});
|
|
3252
4382
|
}
|
|
4383
|
+
sweeper?.stop();
|
|
3253
4384
|
try {
|
|
3254
4385
|
if (idleManager) await idleManager.stop();
|
|
3255
4386
|
} catch (err) {
|
|
3256
4387
|
rootLogger.error("error stopping IDLE manager", {
|
|
3257
|
-
|
|
4388
|
+
err
|
|
3258
4389
|
});
|
|
3259
4390
|
}
|
|
3260
4391
|
try {
|
|
3261
4392
|
await imapClient.close();
|
|
3262
4393
|
} catch (err) {
|
|
3263
4394
|
rootLogger.error("error closing IMAP client", {
|
|
3264
|
-
|
|
4395
|
+
err
|
|
3265
4396
|
});
|
|
3266
4397
|
}
|
|
3267
4398
|
smtpClient.close();
|
|
@@ -3270,15 +4401,17 @@ try {
|
|
|
3270
4401
|
};
|
|
3271
4402
|
const onSignal = (signal) => {
|
|
3272
4403
|
shutdown(signal).catch((err) => {
|
|
3273
|
-
|
|
3274
|
-
process.stderr.write(`shutdown failed: ${msg}
|
|
3275
|
-
`);
|
|
4404
|
+
rootLogger.error("shutdown failed", { err });
|
|
3276
4405
|
process.exit(1);
|
|
3277
4406
|
});
|
|
3278
4407
|
};
|
|
3279
4408
|
process.on("SIGINT", () => onSignal("SIGINT"));
|
|
3280
4409
|
process.on("SIGTERM", () => onSignal("SIGTERM"));
|
|
3281
|
-
|
|
4410
|
+
if (config.http) {
|
|
4411
|
+
httpServer = await startHttpServer(config.http, () => createMcpServer(ctx));
|
|
4412
|
+
} else {
|
|
4413
|
+
await server.connect(new StdioServerTransport());
|
|
4414
|
+
}
|
|
3282
4415
|
rootLogger.info("mcp-inbox ready");
|
|
3283
4416
|
} catch (err) {
|
|
3284
4417
|
const top = err instanceof Error ? err.stack ?? err.message : String(err);
|