imap-mcp 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +75 -2
- package/dist/access.js +119 -0
- package/dist/access.test.js +84 -0
- package/dist/index.js +31 -11
- package/dist/index.test.js +75 -14
- package/dist/instructions.js +30 -0
- package/dist/instructions.test.js +30 -0
- package/dist/tools/create-draft.js +49 -78
- package/dist/tools/create-draft.test.js +49 -32
- package/dist/tools/fake-imap.js +112 -0
- package/dist/tools/get-email.js +171 -0
- package/dist/tools/get-email.test.js +128 -0
- package/dist/tools/imap.js +228 -0
- package/dist/tools/search-emails.js +366 -0
- package/dist/tools/search-emails.test.js +298 -0
- package/package.json +4 -4
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
// search_emails: finds messages in every folder of the IMAP mailbox, or in
|
|
2
|
+
// one, by free text and filters, a page at a time. Shaped like langmail-mcp's
|
|
3
|
+
// self-hosted search_emails; the differences are in the description.
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { z } from "zod/v4";
|
|
6
|
+
import { attachmentsOf, errorResult, folderLabel, formatAddresses, formatAttachmentLine, formatDate, messageFlags, messageId, messageTags, READ_ONLY, resolveMailbox, searchUids, uidRanges, examine, SAFETY_LINE, selectableFolders, sortFolderLabels, textResult, TODO_KEYWORD, withClient, } from "./imap.js";
|
|
7
|
+
// The largest page a caller can ask for.
|
|
8
|
+
const MAX_LIMIT = 100;
|
|
9
|
+
// Only the first terms of a long query are searched.
|
|
10
|
+
const MAX_QUERY_TERMS = 10;
|
|
11
|
+
// Attachments listed per hit; get_email lists them all.
|
|
12
|
+
const LIST_ATTACHMENT_LIMIT = 5;
|
|
13
|
+
const QUERY_DESCRIPTION = 'Free-text search over subject, body, and addresses (IMAP SEARCH TEXT: every header counts, and most servers match a term anywhere inside a word, so "art" finds "party"). Terms are OR\'d — a message matches if it contains ANY term. Messages containing every term come first, then the rest ranked by how many terms they contain, across all pages (each hit shows matched: X/N terms). Wrap a phrase in double quotes to match only messages holding those words next to each other, in that order. Narrow with from/after/before/read/starred/todo, not by adding terms; only the first 10 terms are used.';
|
|
14
|
+
export const searchEmailsShape = {
|
|
15
|
+
after: z.iso
|
|
16
|
+
.datetime()
|
|
17
|
+
.optional()
|
|
18
|
+
.describe('Only messages received on/after this UTC ISO-8601 timestamp, e.g. "2026-04-01T00:00:00Z" (start of "last 3 months"). Filters the RECEIVED date, not any date the message talks about: a confirmation arrives before the event it confirms, so for an event-anchored request ("yesterday\'s show", "last week\'s flight") start the window a booking lead time — days to weeks — before the event rather than on the event day.'),
|
|
19
|
+
before: z.iso
|
|
20
|
+
.datetime()
|
|
21
|
+
.optional()
|
|
22
|
+
.describe('Only messages received strictly before this UTC ISO-8601 timestamp, e.g. "2026-07-01T00:00:00Z". Filters the received date; for an event-anchored request, end the window at the event rather than bounding it to the event day.'),
|
|
23
|
+
cursor: z
|
|
24
|
+
.string()
|
|
25
|
+
.min(1)
|
|
26
|
+
.max(100_000)
|
|
27
|
+
.optional()
|
|
28
|
+
.describe("The cursor a previous search_emails result printed, to get the page after it. Pass it exactly as printed, with the same query and filters as that search (limit may change); leave it out to start from the newest match."),
|
|
29
|
+
from: z
|
|
30
|
+
.string()
|
|
31
|
+
.min(1)
|
|
32
|
+
.max(200)
|
|
33
|
+
.optional()
|
|
34
|
+
.describe("Substring match on the sender name or address."),
|
|
35
|
+
limit: z
|
|
36
|
+
.number()
|
|
37
|
+
.int()
|
|
38
|
+
.min(1)
|
|
39
|
+
.max(MAX_LIMIT)
|
|
40
|
+
.default(20)
|
|
41
|
+
.describe(`Hits per page, 1–${MAX_LIMIT}. When more match, the page prints a cursor for the next one.`),
|
|
42
|
+
mailbox: z
|
|
43
|
+
.string()
|
|
44
|
+
.min(1)
|
|
45
|
+
.optional()
|
|
46
|
+
.describe('Restrict to a named mailbox/folder (e.g. "Inbox"). The standard places — Inbox, Sent, Archive, Drafts, Trash, Junk — resolve to the folder holding that role, so they work under whatever name the server gives them ("Sent" finds a mailbox called "Sent Items" or "[Gmail]/Sent Mail"). Any other value matches a folder name exactly.'),
|
|
47
|
+
query: z.string().min(1).max(500).optional().describe(QUERY_DESCRIPTION),
|
|
48
|
+
read: z
|
|
49
|
+
.boolean()
|
|
50
|
+
.optional()
|
|
51
|
+
.describe('false finds only unread messages, true only read ones. Leave out to match both. Without mailbox it covers every folder, so { read: false } alone is "everything not read yet", Archive, Junk and Trash included.'),
|
|
52
|
+
starred: z
|
|
53
|
+
.boolean()
|
|
54
|
+
.optional()
|
|
55
|
+
.describe("true finds only starred messages, false only unstarred ones. Leave out to match both."),
|
|
56
|
+
todo: z
|
|
57
|
+
.boolean()
|
|
58
|
+
.optional()
|
|
59
|
+
.describe(`true finds only messages flagged as a to-do (the ${TODO_KEYWORD} keyword Langmail sets), false only messages without it. Leave out to match both.`),
|
|
60
|
+
};
|
|
61
|
+
const NO_FILTER_MESSAGE = "Provide at least one filter: query, after, before, from, mailbox, read, starred, or todo.";
|
|
62
|
+
const searchEmailsInput = z
|
|
63
|
+
.object(searchEmailsShape)
|
|
64
|
+
.refine((v) => Boolean(v.query ?? v.after ?? v.before ?? v.from ?? v.mailbox) ||
|
|
65
|
+
v.read !== undefined ||
|
|
66
|
+
v.starred !== undefined ||
|
|
67
|
+
v.todo !== undefined);
|
|
68
|
+
// --- query terms --------------------------------------------------------------
|
|
69
|
+
const QUERY_TERM_RE = /"([^"]*)"|(\S+)/gu;
|
|
70
|
+
/**
|
|
71
|
+
* Splits a query into terms: a double-quoted phrase stays one term (IMAP
|
|
72
|
+
* SEARCH TEXT matches it as a substring, so its words stay in order),
|
|
73
|
+
* everything else splits on whitespace.
|
|
74
|
+
*/
|
|
75
|
+
export const queryTerms = (query) => [...query.matchAll(QUERY_TERM_RE)].flatMap((m) => {
|
|
76
|
+
const phrase = m[1]?.trim();
|
|
77
|
+
if (phrase !== undefined)
|
|
78
|
+
return phrase ? [phrase] : [];
|
|
79
|
+
return m[2] ? [m[2]] : [];
|
|
80
|
+
});
|
|
81
|
+
const CURSOR_PREFIX = "v1.";
|
|
82
|
+
const cursorSchema = z.object({
|
|
83
|
+
q: z.string().min(1),
|
|
84
|
+
r: z.number().int().min(0),
|
|
85
|
+
w: z.number().int(),
|
|
86
|
+
s: z.array(z.string().min(1)),
|
|
87
|
+
});
|
|
88
|
+
export const encodeCursor = (c) => `${CURSOR_PREFIX}${Buffer.from(JSON.stringify({ q: c.search, r: c.rank, w: c.second, s: c.seen })).toString("base64url")}`;
|
|
89
|
+
export const decodeCursor = (raw) => {
|
|
90
|
+
if (!raw.startsWith(CURSOR_PREFIX))
|
|
91
|
+
return undefined;
|
|
92
|
+
try {
|
|
93
|
+
const parsed = cursorSchema.safeParse(JSON.parse(Buffer.from(raw.slice(CURSOR_PREFIX.length), "base64url").toString("utf8")));
|
|
94
|
+
return parsed.success
|
|
95
|
+
? {
|
|
96
|
+
search: parsed.data.q,
|
|
97
|
+
rank: parsed.data.r,
|
|
98
|
+
second: parsed.data.w,
|
|
99
|
+
seen: parsed.data.s,
|
|
100
|
+
}
|
|
101
|
+
: undefined;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
/** Every argument that decides which messages match. */
|
|
108
|
+
export const searchFingerprint = (args) => createHash("sha256")
|
|
109
|
+
.update(JSON.stringify([
|
|
110
|
+
args.after,
|
|
111
|
+
args.before,
|
|
112
|
+
args.from,
|
|
113
|
+
args.mailbox,
|
|
114
|
+
args.query,
|
|
115
|
+
args.read,
|
|
116
|
+
args.starred,
|
|
117
|
+
args.todo,
|
|
118
|
+
]))
|
|
119
|
+
.digest("base64url")
|
|
120
|
+
.slice(0, 10);
|
|
121
|
+
const BAD_CURSOR_MESSAGE = "cursor is not one search_emails printed. Nothing was searched. Pass the cursor exactly as the result printed it, or leave cursor out to start from the newest match.";
|
|
122
|
+
const OTHER_SEARCH_MESSAGE = "cursor belongs to a search with other filters. Nothing was searched. Pass it with the same query and filters as the search that printed it, or leave cursor out to start this search from the newest match.";
|
|
123
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
124
|
+
/**
|
|
125
|
+
* The filters every SEARCH of this call shares. IMAP SINCE and BEFORE
|
|
126
|
+
* compare dates, not times, so they get a day of margin each way and the
|
|
127
|
+
* exact bounds are applied to INTERNALDATE afterwards.
|
|
128
|
+
*/
|
|
129
|
+
function baseCriteria(args) {
|
|
130
|
+
const criteria = {};
|
|
131
|
+
if (args.read !== undefined)
|
|
132
|
+
criteria.seen = args.read;
|
|
133
|
+
if (args.starred !== undefined)
|
|
134
|
+
criteria.flagged = args.starred;
|
|
135
|
+
if (args.todo === true)
|
|
136
|
+
criteria.keyword = TODO_KEYWORD;
|
|
137
|
+
if (args.todo === false)
|
|
138
|
+
criteria.unKeyword = TODO_KEYWORD;
|
|
139
|
+
if (args.from)
|
|
140
|
+
criteria.from = args.from;
|
|
141
|
+
if (args.after)
|
|
142
|
+
criteria.since = new Date(Date.parse(args.after) - DAY_MS);
|
|
143
|
+
if (args.before)
|
|
144
|
+
criteria.before = new Date(Date.parse(args.before) + DAY_MS);
|
|
145
|
+
return criteria;
|
|
146
|
+
}
|
|
147
|
+
/** UIDs matching the search in the open folder, with the terms each holds. */
|
|
148
|
+
async function searchFolder(client, base, terms, path) {
|
|
149
|
+
const ranks = new Map();
|
|
150
|
+
if (terms.length === 0) {
|
|
151
|
+
const criteria = Object.keys(base).length > 0 ? base : { all: true };
|
|
152
|
+
for (const uid of await searchUids(client, criteria, path)) {
|
|
153
|
+
ranks.set(uid, 0);
|
|
154
|
+
}
|
|
155
|
+
return ranks;
|
|
156
|
+
}
|
|
157
|
+
for (const term of terms) {
|
|
158
|
+
const uids = await searchUids(client, { ...base, text: term }, path);
|
|
159
|
+
for (const uid of uids)
|
|
160
|
+
ranks.set(uid, (ranks.get(uid) ?? 0) + 1);
|
|
161
|
+
}
|
|
162
|
+
return ranks;
|
|
163
|
+
}
|
|
164
|
+
async function collectHits(client, folders, args, terms) {
|
|
165
|
+
const base = baseCriteria(args);
|
|
166
|
+
const after = args.after ? Date.parse(args.after) : -Infinity;
|
|
167
|
+
const before = args.before ? Date.parse(args.before) : Infinity;
|
|
168
|
+
const hits = new Map();
|
|
169
|
+
for (const folder of folders) {
|
|
170
|
+
// EXAMINE: nothing in a read-only folder changes, \Seen included.
|
|
171
|
+
const opened = await examine(client, folder.path);
|
|
172
|
+
if (!opened || opened.exists === 0)
|
|
173
|
+
continue;
|
|
174
|
+
const ranks = await searchFolder(client, base, terms, folder.path);
|
|
175
|
+
if (ranks.size === 0)
|
|
176
|
+
continue;
|
|
177
|
+
for await (const msg of client.fetch(uidRanges([...ranks.keys()]), { uid: true, internalDate: true }, { uid: true })) {
|
|
178
|
+
const date = msg.internalDate ? new Date(msg.internalDate).getTime() : 0;
|
|
179
|
+
if (date < after || date >= before)
|
|
180
|
+
continue;
|
|
181
|
+
const id = messageId(msg, folder.path, opened.uidValidity);
|
|
182
|
+
const rank = ranks.get(msg.uid) ?? 0;
|
|
183
|
+
const hit = hits.get(id);
|
|
184
|
+
if (hit) {
|
|
185
|
+
hit.folders.add(folderLabel(folder));
|
|
186
|
+
hit.rank = Math.max(hit.rank, rank);
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
hits.set(id, {
|
|
190
|
+
id,
|
|
191
|
+
date,
|
|
192
|
+
rank,
|
|
193
|
+
folders: new Set([folderLabel(folder)]),
|
|
194
|
+
path: folder.path,
|
|
195
|
+
uid: msg.uid,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return [...hits.values()].sort((a, b) => b.rank - a.rank ||
|
|
201
|
+
b.date - a.date ||
|
|
202
|
+
(a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
203
|
+
}
|
|
204
|
+
const secondOf = (ms) => Math.floor(ms / 1000);
|
|
205
|
+
/** The hits after the cursor, in the same order. */
|
|
206
|
+
function afterCursor(hits, cursor) {
|
|
207
|
+
if (!cursor)
|
|
208
|
+
return hits;
|
|
209
|
+
const seen = new Set(cursor.seen);
|
|
210
|
+
return hits.filter((h) => h.rank < cursor.rank ||
|
|
211
|
+
(h.rank === cursor.rank && secondOf(h.date) < cursor.second) ||
|
|
212
|
+
(h.rank === cursor.rank &&
|
|
213
|
+
secondOf(h.date) === cursor.second &&
|
|
214
|
+
!seen.has(h.id)));
|
|
215
|
+
}
|
|
216
|
+
function nextCursor(search, page, previous) {
|
|
217
|
+
const last = page[page.length - 1];
|
|
218
|
+
const second = secondOf(last.date);
|
|
219
|
+
const sameKey = (h) => h.rank === last.rank && secondOf(h.date) === second;
|
|
220
|
+
const carried = previous && previous.rank === last.rank && previous.second === second
|
|
221
|
+
? previous.seen
|
|
222
|
+
: [];
|
|
223
|
+
return {
|
|
224
|
+
search,
|
|
225
|
+
rank: last.rank,
|
|
226
|
+
second,
|
|
227
|
+
seen: [...new Set([...carried, ...page.filter(sameKey).map((h) => h.id)])],
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/** Fetches the page's details folder by folder and renders each hit. */
|
|
231
|
+
async function renderPage(client, page, termCount) {
|
|
232
|
+
const byPath = new Map();
|
|
233
|
+
for (const hit of page) {
|
|
234
|
+
byPath.set(hit.path, [...(byPath.get(hit.path) ?? []), hit]);
|
|
235
|
+
}
|
|
236
|
+
const lines = new Map();
|
|
237
|
+
for (const [path, hits] of byPath) {
|
|
238
|
+
await client.mailboxOpen(path, { readOnly: true });
|
|
239
|
+
const byUid = new Map(hits.map((h) => [h.uid, h]));
|
|
240
|
+
for await (const msg of client.fetch(uidRanges([...byUid.keys()]), { uid: true, envelope: true, flags: true, bodyStructure: true }, { uid: true })) {
|
|
241
|
+
const hit = byUid.get(msg.uid);
|
|
242
|
+
if (!hit)
|
|
243
|
+
continue;
|
|
244
|
+
const out = [
|
|
245
|
+
`${msg.envelope?.subject || "(no subject)"}`,
|
|
246
|
+
` id: ${hit.id}`,
|
|
247
|
+
` from: ${formatAddresses(msg.envelope?.from) || "(unknown sender)"}`,
|
|
248
|
+
` date: ${formatDate(hit.date)}`,
|
|
249
|
+
` folders: ${sortFolderLabels(hit.folders).join(", ")}`,
|
|
250
|
+
];
|
|
251
|
+
const tags = messageTags(msg.flags);
|
|
252
|
+
if (tags.length > 0)
|
|
253
|
+
out.push(` tags: ${tags.join(", ")}`);
|
|
254
|
+
const flags = messageFlags(msg.flags);
|
|
255
|
+
if (flags.length > 0)
|
|
256
|
+
out.push(` flags: ${flags.join(", ")}`);
|
|
257
|
+
const attachments = attachmentsOf(msg.bodyStructure).filter((a) => !a.inline);
|
|
258
|
+
if (attachments.length > 0) {
|
|
259
|
+
out.push(" attachments:", ...attachments
|
|
260
|
+
.slice(0, LIST_ATTACHMENT_LIMIT)
|
|
261
|
+
.map((a, i) => ` ${formatAttachmentLine(i + 1, a)}`));
|
|
262
|
+
if (attachments.length > LIST_ATTACHMENT_LIMIT) {
|
|
263
|
+
out.push(` … +${attachments.length - LIST_ATTACHMENT_LIMIT} more (see get_email)`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
if (termCount > 1)
|
|
267
|
+
out.push(` matched: ${hit.rank}/${termCount} terms`);
|
|
268
|
+
lines.set(hit.id, out.join("\n"));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return page.flatMap((h, i) => {
|
|
272
|
+
const line = lines.get(h.id);
|
|
273
|
+
return line ? [`${i + 1}. ${line}`] : [];
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
function matchHeader(opts) {
|
|
277
|
+
const { continued, cursor, limit, shown, total } = opts;
|
|
278
|
+
const noun = continued ? "remaining message(s)" : "message(s)";
|
|
279
|
+
if (!cursor)
|
|
280
|
+
return `${shown} of ${total} ${noun} matched:`;
|
|
281
|
+
const raise = limit < MAX_LIMIT ? `, or raise limit (max ${MAX_LIMIT})` : "";
|
|
282
|
+
return `${shown} of ${total} ${noun} matched — ${total - shown} more not shown. For the next page, repeat this search with cursor: "${cursor}". To narrow instead, use after/before or other filters${raise}:`;
|
|
283
|
+
}
|
|
284
|
+
export async function searchEmails(createClient, args) {
|
|
285
|
+
const terms = args.query
|
|
286
|
+
? queryTerms(args.query).slice(0, MAX_QUERY_TERMS)
|
|
287
|
+
: [];
|
|
288
|
+
if (args.query && terms.length === 0) {
|
|
289
|
+
return errorResult("query contains no searchable terms. Nothing was searched. Put words in query, or leave it out and search with the other filters.");
|
|
290
|
+
}
|
|
291
|
+
const search = searchFingerprint(args);
|
|
292
|
+
let cursor;
|
|
293
|
+
if (args.cursor !== undefined) {
|
|
294
|
+
cursor = decodeCursor(args.cursor);
|
|
295
|
+
if (!cursor)
|
|
296
|
+
return errorResult(BAD_CURSOR_MESSAGE);
|
|
297
|
+
if (cursor.search !== search)
|
|
298
|
+
return errorResult(OTHER_SEARCH_MESSAGE);
|
|
299
|
+
}
|
|
300
|
+
return withClient(createClient, async (client) => {
|
|
301
|
+
let folders = await selectableFolders(client);
|
|
302
|
+
if (args.mailbox) {
|
|
303
|
+
const resolved = resolveMailbox(folders, args.mailbox);
|
|
304
|
+
if ("content" in resolved)
|
|
305
|
+
return resolved;
|
|
306
|
+
if (!(await examine(client, resolved.path))) {
|
|
307
|
+
return errorResult(`Mailbox ${args.mailbox} (${resolved.path}) could not be opened, so nothing was searched. Search without mailbox to cover every folder the account can open.`);
|
|
308
|
+
}
|
|
309
|
+
folders = [resolved];
|
|
310
|
+
}
|
|
311
|
+
const remaining = afterCursor(await collectHits(client, folders, args, terms), cursor);
|
|
312
|
+
if (remaining.length === 0) {
|
|
313
|
+
return textResult(cursor
|
|
314
|
+
? "No more messages matched after this cursor."
|
|
315
|
+
: "No messages matched.");
|
|
316
|
+
}
|
|
317
|
+
const page = remaining.slice(0, args.limit);
|
|
318
|
+
const lines = await renderPage(client, page, terms.length);
|
|
319
|
+
const next = remaining.length > page.length
|
|
320
|
+
? encodeCursor(nextCursor(search, page, cursor))
|
|
321
|
+
: undefined;
|
|
322
|
+
const header = matchHeader({
|
|
323
|
+
continued: cursor !== undefined,
|
|
324
|
+
cursor: next,
|
|
325
|
+
limit: args.limit,
|
|
326
|
+
shown: page.length,
|
|
327
|
+
total: remaining.length,
|
|
328
|
+
});
|
|
329
|
+
return textResult(`${header}\n\n${lines.join("\n\n")}`);
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
export const SEARCH_EMAILS_DESCRIPTION = "Search the user's IMAP mailbox, in every folder or in one. Combine free-text (query — " +
|
|
333
|
+
"any-term match, quoted phrases supported) with optional filters: date " +
|
|
334
|
+
"range (after/before), sender (from), read state (read), starred, to-do (todo), and mailbox. " +
|
|
335
|
+
"At least one filter is required. " +
|
|
336
|
+
'For "what have I not read yet" use read: false without mailbox — new mail is not only in the ' +
|
|
337
|
+
"Inbox, and a date window misses older unhandled mail. A hit in Junk is mail the server filtered " +
|
|
338
|
+
'as spam. For "what is on my to-do list" use todo: true. Returns ' +
|
|
339
|
+
"matching messages, headed by how many of the total matches are shown (e.g. " +
|
|
340
|
+
'"20 of 213") — multi-term queries list messages matching every term first, then partial ' +
|
|
341
|
+
"matches ranked by how many terms they hold; otherwise newest-first — with id, subject, sender, date, " +
|
|
342
|
+
"folders (Inbox, Archive, Sent, Drafts, Junk, Trash, or the name of any other folder), tags, flags (unread, " +
|
|
343
|
+
'starred; a hit without "unread" has been read) and the attachments\' names, types and sizes. ' +
|
|
344
|
+
"Hits carry no body snippet: use get_email with a hit's id for the body and recipients. " +
|
|
345
|
+
"The id stays valid when the message moves to another folder only on servers with a stable message id " +
|
|
346
|
+
"(OBJECTID or Gmail); elsewhere it changes on a move, so search again to find the message. " +
|
|
347
|
+
"When more match than a page shows, the result prints a cursor; " +
|
|
348
|
+
"when the request needs more than this page (every unread message, all invoices this year), repeat the same " +
|
|
349
|
+
"search with that cursor for the next page, until no cursor comes back. " +
|
|
350
|
+
"Searching never marks anything read. " +
|
|
351
|
+
SAFETY_LINE;
|
|
352
|
+
export function registerSearchEmails(createClient, server) {
|
|
353
|
+
server.registerTool("search_emails", {
|
|
354
|
+
title: "Search emails",
|
|
355
|
+
description: SEARCH_EMAILS_DESCRIPTION,
|
|
356
|
+
inputSchema: searchEmailsShape,
|
|
357
|
+
annotations: READ_ONLY,
|
|
358
|
+
}, async (args) => {
|
|
359
|
+
// The SDK validated each field; what is left is the cross-field
|
|
360
|
+
// "at least one filter" rule.
|
|
361
|
+
const parsed = searchEmailsInput.safeParse(args);
|
|
362
|
+
if (!parsed.success)
|
|
363
|
+
return errorResult(NO_FILTER_MESSAGE);
|
|
364
|
+
return searchEmails(createClient, parsed.data);
|
|
365
|
+
});
|
|
366
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { describe, expect, test, vi } from "vitest";
|
|
2
|
+
import { fakeClient } from "./fake-imap.js";
|
|
3
|
+
import { encodeMessageId, READ_ONLY, uidRanges } from "./imap.js";
|
|
4
|
+
import { queryTerms, registerSearchEmails, searchEmails, } from "./search-emails.js";
|
|
5
|
+
const gmail = () => [
|
|
6
|
+
{
|
|
7
|
+
path: "INBOX",
|
|
8
|
+
messages: [
|
|
9
|
+
{
|
|
10
|
+
uid: 1,
|
|
11
|
+
emailId: "m1",
|
|
12
|
+
date: "2026-11-01T09:00:00Z",
|
|
13
|
+
subject: "Invoice November",
|
|
14
|
+
from: "billing@example.com",
|
|
15
|
+
text: "Your invoice from Example Corp",
|
|
16
|
+
flags: ["$label:todo"],
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
uid: 2,
|
|
20
|
+
emailId: "m2",
|
|
21
|
+
date: "2026-11-02T09:00:00Z",
|
|
22
|
+
subject: "Lunch?",
|
|
23
|
+
from: "friend@example.org",
|
|
24
|
+
flags: ["\\Seen"],
|
|
25
|
+
},
|
|
26
|
+
],
|
|
27
|
+
},
|
|
28
|
+
{ path: "[Gmail]", flags: ["\\Noselect"], messages: [] },
|
|
29
|
+
{
|
|
30
|
+
path: "[Gmail]/Sent Mail",
|
|
31
|
+
specialUse: "\\Sent",
|
|
32
|
+
messages: [
|
|
33
|
+
{
|
|
34
|
+
uid: 7,
|
|
35
|
+
emailId: "m3",
|
|
36
|
+
date: "2026-11-03T09:00:00Z",
|
|
37
|
+
subject: "Re: Lunch?",
|
|
38
|
+
from: "me@example.com",
|
|
39
|
+
flags: ["\\Seen"],
|
|
40
|
+
},
|
|
41
|
+
],
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
path: "Work",
|
|
45
|
+
messages: [
|
|
46
|
+
{
|
|
47
|
+
uid: 3,
|
|
48
|
+
emailId: "m1",
|
|
49
|
+
date: "2026-11-01T09:00:00Z",
|
|
50
|
+
subject: "Invoice November",
|
|
51
|
+
from: "billing@example.com",
|
|
52
|
+
text: "Your invoice from Example Corp",
|
|
53
|
+
flags: ["$label:todo"],
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
uid: 4,
|
|
57
|
+
emailId: "m4",
|
|
58
|
+
date: "2026-10-01T09:00:00Z",
|
|
59
|
+
subject: "Old invoice",
|
|
60
|
+
from: "billing@example.com",
|
|
61
|
+
flags: ["\\Flagged"],
|
|
62
|
+
bodyStructure: {
|
|
63
|
+
type: "multipart/mixed",
|
|
64
|
+
childNodes: [
|
|
65
|
+
{ type: "text/plain", part: "1" },
|
|
66
|
+
{
|
|
67
|
+
type: "application/pdf",
|
|
68
|
+
part: "2",
|
|
69
|
+
disposition: "attachment",
|
|
70
|
+
dispositionParameters: { filename: "invoice.pdf" },
|
|
71
|
+
size: 2048,
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
type: "image/png",
|
|
75
|
+
part: "3",
|
|
76
|
+
disposition: "inline",
|
|
77
|
+
id: "<logo>",
|
|
78
|
+
dispositionParameters: { filename: "logo.png" },
|
|
79
|
+
size: 10,
|
|
80
|
+
},
|
|
81
|
+
],
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
],
|
|
85
|
+
},
|
|
86
|
+
];
|
|
87
|
+
const search = (folders, args) => {
|
|
88
|
+
const fake = fakeClient(folders);
|
|
89
|
+
const result = searchEmails(fake.createClient, {
|
|
90
|
+
limit: 20,
|
|
91
|
+
...args,
|
|
92
|
+
});
|
|
93
|
+
return { ...fake, result };
|
|
94
|
+
};
|
|
95
|
+
const text = async (p) => (await p).content[0].text;
|
|
96
|
+
describe("search_emails", () => {
|
|
97
|
+
test("registers as a read-only tool named search_emails", () => {
|
|
98
|
+
const server = { registerTool: vi.fn() };
|
|
99
|
+
registerSearchEmails(fakeClient([]).createClient, server);
|
|
100
|
+
expect(server.registerTool).toHaveBeenCalledWith("search_emails", expect.objectContaining({ annotations: READ_ONLY }), expect.any(Function));
|
|
101
|
+
});
|
|
102
|
+
test("requires at least one filter", async () => {
|
|
103
|
+
const server = { registerTool: vi.fn() };
|
|
104
|
+
registerSearchEmails(fakeClient([]).createClient, server);
|
|
105
|
+
const handler = server.registerTool.mock.calls[0][2];
|
|
106
|
+
const result = await handler({ limit: 20 });
|
|
107
|
+
expect(result.isError).toBe(true);
|
|
108
|
+
expect(result.content[0].text).toContain("Provide at least one filter");
|
|
109
|
+
});
|
|
110
|
+
test("read: false finds unread mail in every folder, merged by stable id, naming its folders", async () => {
|
|
111
|
+
const { client, result } = search(gmail(), { read: false });
|
|
112
|
+
const out = await text(result);
|
|
113
|
+
expect(out).toMatch(/^2 of 2 message\(s\) matched:/);
|
|
114
|
+
expect(out).toContain(`1. Invoice November\n id: ${encodeMessageId({ kind: "stable", emailId: "m1" })}\n from: billing@example.com\n date: 2026-11-01T09:00:00Z\n folders: Inbox, Work\n tags: todo\n flags: unread`);
|
|
115
|
+
expect(out).toContain("2. Old invoice");
|
|
116
|
+
expect(out).not.toContain("Lunch");
|
|
117
|
+
// \Noselect folders are never opened; every open is read-only
|
|
118
|
+
const opened = client.mailboxOpen.mock.calls;
|
|
119
|
+
expect(opened.map((c) => c[0])).not.toContain("[Gmail]");
|
|
120
|
+
expect(opened.every((c) => c[1]?.readOnly === true)).toBe(true);
|
|
121
|
+
});
|
|
122
|
+
test("Sent resolves through the special-use attribute", async () => {
|
|
123
|
+
const out = await text(search(gmail(), { mailbox: "Sent" }).result);
|
|
124
|
+
expect(out).toContain("Re: Lunch?");
|
|
125
|
+
expect(out).toContain("folders: Sent");
|
|
126
|
+
expect(out).not.toContain("Invoice");
|
|
127
|
+
});
|
|
128
|
+
test("any other mailbox matches a folder name exactly, and a miss lists the folders", async () => {
|
|
129
|
+
expect(await text(search(gmail(), { mailbox: "Work" }).result)).toContain("Old invoice");
|
|
130
|
+
const miss = await search(gmail(), { mailbox: "work" }).result;
|
|
131
|
+
expect(miss.isError).toBe(true);
|
|
132
|
+
expect(miss.content[0].text).toBe("Mailbox not found: work. Nothing was searched. Available folders: Inbox, Sent, Work.");
|
|
133
|
+
});
|
|
134
|
+
test("passes the flag and sender filters to IMAP SEARCH", async () => {
|
|
135
|
+
const { client, result } = search(gmail(), {
|
|
136
|
+
starred: true,
|
|
137
|
+
todo: false,
|
|
138
|
+
from: "billing",
|
|
139
|
+
mailbox: "Work",
|
|
140
|
+
});
|
|
141
|
+
expect(await text(result)).toContain("Old invoice");
|
|
142
|
+
expect(client.search).toHaveBeenCalledWith({ flagged: true, unKeyword: "$label:todo", from: "billing" }, { uid: true });
|
|
143
|
+
});
|
|
144
|
+
test("todo: true finds the to-do list", async () => {
|
|
145
|
+
const out = await text(search(gmail(), { todo: true }).result);
|
|
146
|
+
expect(out).toMatch(/^1 of 1 message/);
|
|
147
|
+
expect(out).toContain("Invoice November");
|
|
148
|
+
});
|
|
149
|
+
test("after and before bound the received time exactly", async () => {
|
|
150
|
+
const out = await text(search(gmail(), {
|
|
151
|
+
after: "2026-11-01T10:00:00Z",
|
|
152
|
+
before: "2026-11-03T09:00:00Z",
|
|
153
|
+
}).result);
|
|
154
|
+
expect(out).toMatch(/^1 of 1 message/);
|
|
155
|
+
expect(out).toContain("Lunch?");
|
|
156
|
+
});
|
|
157
|
+
test("lists attachments, hiding inline images", async () => {
|
|
158
|
+
const out = await text(search(gmail(), { starred: true }).result);
|
|
159
|
+
expect(out).toContain(" attachments:\n 1. invoice.pdf — application/pdf, 2.0 KB");
|
|
160
|
+
expect(out).not.toContain("logo.png");
|
|
161
|
+
});
|
|
162
|
+
test("ranks messages holding every term first and shows the terms matched", async () => {
|
|
163
|
+
const out = await text(search(gmail(), { query: "invoice lunch" }).result);
|
|
164
|
+
// every hit holds one term: newest first
|
|
165
|
+
expect(out.indexOf("Re: Lunch?")).toBeLessThan(out.indexOf("Old invoice"));
|
|
166
|
+
expect(out).toContain("matched: 1/2 terms");
|
|
167
|
+
const both = await text(search(gmail(), { query: 'invoice "example corp"' }).result);
|
|
168
|
+
expect(both.indexOf("Invoice November")).toBeLessThan(both.indexOf("Old invoice"));
|
|
169
|
+
expect(both).toContain("matched: 2/2 terms");
|
|
170
|
+
});
|
|
171
|
+
test("pages with a cursor, without skipping or repeating", async () => {
|
|
172
|
+
const first = await text(search(gmail(), { from: "e", limit: 2 }).result);
|
|
173
|
+
expect(first).toMatch(/^2 of 4 message\(s\) matched — 2 more not shown/);
|
|
174
|
+
const cursor = first.match(/cursor: "([^"]+)"/)[1];
|
|
175
|
+
const second = await text(search(gmail(), { from: "e", limit: 2, cursor }).result);
|
|
176
|
+
expect(second).toMatch(/^2 of 2 remaining message\(s\) matched:/);
|
|
177
|
+
expect(second).toContain("Invoice November");
|
|
178
|
+
expect(second).toContain("Old invoice");
|
|
179
|
+
expect(first).not.toContain("Invoice November");
|
|
180
|
+
const other = await search(gmail(), { from: "x", cursor }).result;
|
|
181
|
+
expect(other.content[0].text).toContain("cursor belongs to a search");
|
|
182
|
+
});
|
|
183
|
+
test("without a stable id, each folder's copy has its own id", async () => {
|
|
184
|
+
const folders = gmail().map((f) => ({
|
|
185
|
+
...f,
|
|
186
|
+
messages: f.messages.map((m) => ({ ...m, emailId: undefined })),
|
|
187
|
+
}));
|
|
188
|
+
const out = await text(search(folders, { todo: true }).result);
|
|
189
|
+
expect(out).toMatch(/^2 of 2 message/);
|
|
190
|
+
expect(out).toContain(encodeMessageId({ kind: "uid", path: "Work", uidValidity: "1", uid: 3 }));
|
|
191
|
+
});
|
|
192
|
+
test("pages through hits received in the same second without skipping or repeating", async () => {
|
|
193
|
+
const folders = [
|
|
194
|
+
{
|
|
195
|
+
path: "INBOX",
|
|
196
|
+
messages: [1, 2, 3].map((uid) => ({
|
|
197
|
+
uid,
|
|
198
|
+
date: "2026-11-01T09:00:00Z",
|
|
199
|
+
subject: `Same second ${uid}`,
|
|
200
|
+
from: "a@example.com",
|
|
201
|
+
})),
|
|
202
|
+
},
|
|
203
|
+
];
|
|
204
|
+
const seen = [];
|
|
205
|
+
let cursor;
|
|
206
|
+
do {
|
|
207
|
+
const out = await text(search(folders, { from: "a", limit: 1, cursor }).result);
|
|
208
|
+
seen.push(...(out.match(/Same second \d/g) ?? []));
|
|
209
|
+
cursor = out.match(/cursor: "([^"]+)"/)?.[1];
|
|
210
|
+
} while (cursor);
|
|
211
|
+
expect(seen.sort()).toEqual([
|
|
212
|
+
"Same second 1",
|
|
213
|
+
"Same second 2",
|
|
214
|
+
"Same second 3",
|
|
215
|
+
]);
|
|
216
|
+
});
|
|
217
|
+
test("fetches hits with UID ranges, not one UID after another", async () => {
|
|
218
|
+
const { client, result } = search(gmail(), { mailbox: "Work" });
|
|
219
|
+
await result;
|
|
220
|
+
expect(client.fetch.mock.calls[0][0]).toBe("3:4");
|
|
221
|
+
expect(uidRanges([7, 1, 2, 3, 9, 10])).toBe("1:3,7,9:10");
|
|
222
|
+
});
|
|
223
|
+
test("a refused SEARCH is an error, not an empty result", async () => {
|
|
224
|
+
const fake = fakeClient(gmail());
|
|
225
|
+
fake.client.search.mockResolvedValueOnce(false);
|
|
226
|
+
await expect(searchEmails(fake.createClient, { limit: 20, read: false })).rejects.toThrow("The server refused the search in INBOX.");
|
|
227
|
+
});
|
|
228
|
+
test("skips a folder the account cannot open", async () => {
|
|
229
|
+
const fake = fakeClient(gmail());
|
|
230
|
+
const open = fake.client.mailboxOpen.getMockImplementation();
|
|
231
|
+
fake.client.mailboxOpen.mockImplementation(async (path, opts) => {
|
|
232
|
+
if (path === "Work")
|
|
233
|
+
throw new Error("NO [NOPERM]");
|
|
234
|
+
return open(path, opts);
|
|
235
|
+
});
|
|
236
|
+
const out = await text(searchEmails(fake.createClient, { limit: 20, todo: true }));
|
|
237
|
+
expect(out).toContain("folders: Inbox\n");
|
|
238
|
+
});
|
|
239
|
+
test("a mailbox the account cannot open is an error, not an empty result", async () => {
|
|
240
|
+
const fake = fakeClient(gmail());
|
|
241
|
+
const open = fake.client.mailboxOpen.getMockImplementation();
|
|
242
|
+
fake.client.mailboxOpen.mockImplementation(async (path, opts) => {
|
|
243
|
+
if (path === "Work")
|
|
244
|
+
throw new Error("NO [NOPERM]");
|
|
245
|
+
return open(path, opts);
|
|
246
|
+
});
|
|
247
|
+
const result = await searchEmails(fake.createClient, {
|
|
248
|
+
limit: 20,
|
|
249
|
+
mailbox: "Work",
|
|
250
|
+
});
|
|
251
|
+
expect(result.isError).toBe(true);
|
|
252
|
+
expect(result.content[0].text).toContain("Mailbox Work (Work) could not be opened, so nothing was searched.");
|
|
253
|
+
});
|
|
254
|
+
test("lists a forwarded message as one attachment", async () => {
|
|
255
|
+
const folders = [
|
|
256
|
+
{
|
|
257
|
+
path: "INBOX",
|
|
258
|
+
messages: [
|
|
259
|
+
{
|
|
260
|
+
uid: 1,
|
|
261
|
+
date: "2026-11-01T09:00:00Z",
|
|
262
|
+
subject: "Fwd: report",
|
|
263
|
+
from: "a@example.com",
|
|
264
|
+
bodyStructure: {
|
|
265
|
+
type: "multipart/mixed",
|
|
266
|
+
childNodes: [
|
|
267
|
+
{ type: "text/plain", part: "1" },
|
|
268
|
+
{
|
|
269
|
+
type: "message/rfc822",
|
|
270
|
+
part: "2",
|
|
271
|
+
size: 3000,
|
|
272
|
+
childNodes: [
|
|
273
|
+
{
|
|
274
|
+
type: "application/pdf",
|
|
275
|
+
part: "2.1",
|
|
276
|
+
disposition: "attachment",
|
|
277
|
+
dispositionParameters: { filename: "inner.pdf" },
|
|
278
|
+
},
|
|
279
|
+
],
|
|
280
|
+
},
|
|
281
|
+
],
|
|
282
|
+
},
|
|
283
|
+
},
|
|
284
|
+
],
|
|
285
|
+
},
|
|
286
|
+
];
|
|
287
|
+
const out = await text(search(folders, { from: "a" }).result);
|
|
288
|
+
expect(out).toContain("1. (unnamed) — message/rfc822, 2.9 KB");
|
|
289
|
+
expect(out).not.toContain("inner.pdf");
|
|
290
|
+
});
|
|
291
|
+
test("splits a query into words and quoted phrases", () => {
|
|
292
|
+
expect(queryTerms('invoice "example corp" 2026')).toEqual([
|
|
293
|
+
"invoice",
|
|
294
|
+
"example corp",
|
|
295
|
+
"2026",
|
|
296
|
+
]);
|
|
297
|
+
});
|
|
298
|
+
});
|