imap-mcp 1.4.0 → 1.5.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 +87 -6
- package/dist/access.js +5 -1
- package/dist/index.js +8 -0
- package/dist/index.test.js +20 -0
- package/dist/instructions.js +5 -2
- package/dist/instructions.test.js +8 -0
- package/dist/tools/archive-emails.js +55 -0
- package/dist/tools/archive-emails.test.js +154 -0
- package/dist/tools/batch.js +219 -0
- package/dist/tools/fake-imap.js +94 -5
- package/dist/tools/imap.js +21 -3
- package/dist/tools/mark-emails.js +131 -0
- package/dist/tools/mark-emails.test.js +124 -0
- package/dist/tools/move-emails.js +55 -0
- package/dist/tools/move-emails.test.js +169 -0
- package/dist/tools/trash-emails.js +37 -0
- package/dist/tools/trash-emails.test.js +73 -0
- package/package.json +1 -1
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// Shared plumbing for the tools that change mail (mark_emails,
|
|
2
|
+
// archive_emails, move_emails, trash_emails): the ids argument, finding where
|
|
3
|
+
// each id's message is, moving messages between folders, and the per-id
|
|
4
|
+
// result line. Shaped like langmail-mcp's file-emails-common.
|
|
5
|
+
import { z } from "zod/v4";
|
|
6
|
+
import { decodeMessageId, errorMessage, errorResult, examine, placeOf, searchUids, selectableFolders, textResult, uidRanges, } from "./imap.js";
|
|
7
|
+
const MAX_IDS = 50;
|
|
8
|
+
export const idsShape = {
|
|
9
|
+
ids: z
|
|
10
|
+
.array(z.string().min(1))
|
|
11
|
+
.min(1)
|
|
12
|
+
.max(MAX_IDS)
|
|
13
|
+
.describe(`Message ids to act on (1–${MAX_IDS}), as returned by search_emails or get_thread. ` +
|
|
14
|
+
"To act on a whole conversation, pass every id get_thread lists."),
|
|
15
|
+
};
|
|
16
|
+
/** Duplicates collapse, so one message never counts twice. */
|
|
17
|
+
export const uniqueIds = (ids) => [...new Set(ids)];
|
|
18
|
+
export const NOT_FOUND = "not found";
|
|
19
|
+
const NOT_AN_ID = "not a message id";
|
|
20
|
+
/**
|
|
21
|
+
* Finds every copy of each id's message: for a stable id one SEARCH per
|
|
22
|
+
* folder for all of them, for a UID id its folder, UIDVALIDITY and UID.
|
|
23
|
+
*/
|
|
24
|
+
export async function locateMessages(client, ids) {
|
|
25
|
+
const folders = await selectableFolders(client);
|
|
26
|
+
const locations = new Map();
|
|
27
|
+
const failed = [];
|
|
28
|
+
const add = (id, loc) => locations.set(id, [...(locations.get(id) ?? []), loc]);
|
|
29
|
+
const stable = new Map();
|
|
30
|
+
const byPath = new Map();
|
|
31
|
+
for (const id of ids) {
|
|
32
|
+
const ref = decodeMessageId(id);
|
|
33
|
+
if (!ref) {
|
|
34
|
+
failed.push({ id, status: "failed", reason: NOT_AN_ID });
|
|
35
|
+
}
|
|
36
|
+
else if (ref.kind === "stable") {
|
|
37
|
+
stable.set(ref.emailId, id);
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
byPath.set(ref.path, [...(byPath.get(ref.path) ?? []), { id, ...ref }]);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
for (const folder of folders) {
|
|
44
|
+
const wanted = byPath.get(folder.path) ?? [];
|
|
45
|
+
if (stable.size === 0 && wanted.length === 0)
|
|
46
|
+
continue;
|
|
47
|
+
const opened = await examine(client, folder.path);
|
|
48
|
+
if (!opened || opened.exists === 0)
|
|
49
|
+
continue;
|
|
50
|
+
if (stable.size > 0) {
|
|
51
|
+
const emailIds = [...stable.keys()];
|
|
52
|
+
const uids = await searchUids(client, emailIds.length === 1
|
|
53
|
+
? { emailId: emailIds[0] }
|
|
54
|
+
: { or: emailIds.map((emailId) => ({ emailId })) }, folder.path);
|
|
55
|
+
if (uids.length > 0) {
|
|
56
|
+
for await (const msg of client.fetch(uidRanges(uids), { uid: true, emailId: true }, { uid: true })) {
|
|
57
|
+
const id = msg.emailId ? stable.get(msg.emailId) : undefined;
|
|
58
|
+
if (id)
|
|
59
|
+
add(id, { folder, uid: msg.uid });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const current = wanted.filter((w) => w.uidValidity === opened.uidValidity.toString());
|
|
64
|
+
if (current.length > 0) {
|
|
65
|
+
const present = new Set(await searchUids(client, { uid: uidRanges(current.map((w) => w.uid)) }, folder.path));
|
|
66
|
+
for (const w of current) {
|
|
67
|
+
if (present.has(w.uid))
|
|
68
|
+
add(w.id, { folder, uid: w.uid });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const id of ids) {
|
|
73
|
+
if (!locations.has(id) && !failed.some((f) => f.id === id)) {
|
|
74
|
+
failed.push({ id, status: "failed", reason: NOT_FOUND });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { folders, locations, failed };
|
|
78
|
+
}
|
|
79
|
+
/** The ids whose copies are listed, grouped by folder path. */
|
|
80
|
+
export function byFolder(copies) {
|
|
81
|
+
const out = new Map();
|
|
82
|
+
for (const { id, loc } of copies) {
|
|
83
|
+
out.set(loc.folder.path, [
|
|
84
|
+
...(out.get(loc.folder.path) ?? []),
|
|
85
|
+
{ id, uid: loc.uid },
|
|
86
|
+
]);
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/** Gmail's All Mail: every message that is not in Spam or Trash. */
|
|
91
|
+
export const isAllMail = (folder) => folder.specialUse?.toLowerCase() === "\\all";
|
|
92
|
+
/**
|
|
93
|
+
* A folder that shows messages by a flag (Gmail's Starred and Important):
|
|
94
|
+
* moving a message out of it clears the flag, so it is never a source.
|
|
95
|
+
*/
|
|
96
|
+
const isFlagView = (folder) => ["\\flagged", "\\important"].includes(folder.specialUse?.toLowerCase() ?? "");
|
|
97
|
+
/**
|
|
98
|
+
* Moves each listed copy into `destination`, folder by folder, with UID
|
|
99
|
+
* MOVE. Without MOVE (RFC 6851), imapflow copies, flags `\Deleted` and
|
|
100
|
+
* expunges: by UID with UIDPLUS (RFC 4315), else with a plain EXPUNGE that
|
|
101
|
+
* would take every `\Deleted` message, so then a folder holding others is
|
|
102
|
+
* left alone. Returns the ids moved and the reason for each that failed.
|
|
103
|
+
*/
|
|
104
|
+
export async function moveCopies(client, copies, destination) {
|
|
105
|
+
// Gmail's All Mail holds every message that is not in Spam or Trash, and
|
|
106
|
+
// taking one out of it deletes it. COPY adds the destination label and
|
|
107
|
+
// leaves it there; only into Trash does it leave All Mail.
|
|
108
|
+
const copyFrom = new Set(copies.filter((c) => isAllMail(c.loc.folder)).map((c) => c.loc.folder.path));
|
|
109
|
+
const toTrash = placeOf(destination)?.name === "Trash";
|
|
110
|
+
const moved = new Set();
|
|
111
|
+
const failed = new Map();
|
|
112
|
+
const caps = client.capabilities;
|
|
113
|
+
const plainExpunge = !caps.has("MOVE") && !caps.has("UIDPLUS");
|
|
114
|
+
for (const [path, entries] of byFolder(copies)) {
|
|
115
|
+
const uids = entries.map((e) => e.uid);
|
|
116
|
+
const fail = (reason) => entries.forEach((e) => failed.set(e.id, reason));
|
|
117
|
+
try {
|
|
118
|
+
await client.mailboxOpen(path);
|
|
119
|
+
if (copyFrom.has(path) && !toTrash) {
|
|
120
|
+
if (!(await client.messageCopy(uidRanges(uids), destination.path, {
|
|
121
|
+
uid: true,
|
|
122
|
+
}))) {
|
|
123
|
+
fail(`the server refused the copy out of ${path}`);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
entries.forEach((e) => moved.add(e.id));
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (plainExpunge) {
|
|
130
|
+
const deleted = await searchUids(client, { deleted: true }, path);
|
|
131
|
+
if (deleted.some((uid) => !uids.includes(uid))) {
|
|
132
|
+
fail(`the server cannot move without expunging the other deleted messages in ${path}`);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const result = await client.messageMove(uidRanges(uids), destination.path, {
|
|
137
|
+
uid: true,
|
|
138
|
+
});
|
|
139
|
+
if (!result) {
|
|
140
|
+
fail(`the server refused the move out of ${path}`);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
entries.forEach((e) => moved.add(e.id));
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
fail(errorMessage(err));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return { moved, failed };
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Turns per-copy results into one outcome per id: changed when any copy
|
|
153
|
+
* changed, failed when none did and one failed, otherwise already in place.
|
|
154
|
+
*/
|
|
155
|
+
export function outcomesOf(ids, changed, failed) {
|
|
156
|
+
return ids.map((id) => {
|
|
157
|
+
if (changed.has(id))
|
|
158
|
+
return { id, status: "changed" };
|
|
159
|
+
const reason = failed.get(id);
|
|
160
|
+
if (reason !== undefined)
|
|
161
|
+
return { id, status: "failed", reason };
|
|
162
|
+
return { id, status: "already" };
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* langmail-mcp's result line, "Archived 2 message(s).", plus how many were
|
|
167
|
+
* already in place and each id not updated with the reason. An error only
|
|
168
|
+
* when nothing changed and an id was refused: an id whose message is gone or
|
|
169
|
+
* has moved is listed, not an error for the whole call.
|
|
170
|
+
*/
|
|
171
|
+
export function formatBatchResult(verb, outcomes, opts) {
|
|
172
|
+
const changed = outcomes.filter((o) => o.status === "changed").length;
|
|
173
|
+
const already = outcomes.filter((o) => o.status === "already").length;
|
|
174
|
+
const failed = outcomes.flatMap((o) => (o.status === "failed" ? [o] : []));
|
|
175
|
+
let text = `${verb} ${changed} message(s)${opts.suffix ?? ""}.`;
|
|
176
|
+
if (already > 0)
|
|
177
|
+
text += ` ${already} message(s) ${opts.already}.`;
|
|
178
|
+
if (failed.length === 0)
|
|
179
|
+
return textResult(text);
|
|
180
|
+
text += ` Not updated (${failed.length}): ${failed.map((f) => `${f.id} (${f.reason})`).join(", ")}.`;
|
|
181
|
+
if (failed.some((f) => f.reason === NOT_FOUND || f.reason === NOT_AN_ID)) {
|
|
182
|
+
text += " Re-run search_emails or get_thread for current ids.";
|
|
183
|
+
}
|
|
184
|
+
const refused = failed.some((f) => f.reason !== NOT_FOUND);
|
|
185
|
+
return changed === 0 && already === 0 && refused
|
|
186
|
+
? errorResult(text)
|
|
187
|
+
: textResult(text);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Moves every id's message into `destination` from the copies `sourcesOf`
|
|
191
|
+
* picks; an id with no copy to move is already in place. Outcomes come back
|
|
192
|
+
* in the order of `ids`.
|
|
193
|
+
*/
|
|
194
|
+
export async function fileMessages(client, ids, located, destination, sourcesOf) {
|
|
195
|
+
const copies = [...located.locations].flatMap(([id, locs]) => sourcesOf(locs).map((loc) => ({ id, loc })));
|
|
196
|
+
const { moved, failed } = await moveCopies(client, copies, destination);
|
|
197
|
+
const outcomes = new Map([
|
|
198
|
+
...outcomesOf([...located.locations.keys()], moved, failed).map((o) => [o.id, o]),
|
|
199
|
+
...located.failed.map((o) => [o.id, o]),
|
|
200
|
+
]);
|
|
201
|
+
return ids.flatMap((id) => outcomes.get(id) ?? []);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Every copy outside `destination`, flag views left out. On Gmail, All Mail follows the other
|
|
205
|
+
* folders (labels), so it is a source only when the message is in no other
|
|
206
|
+
* folder, the destination included.
|
|
207
|
+
*/
|
|
208
|
+
export function copiesOutside(destination) {
|
|
209
|
+
return (locations) => {
|
|
210
|
+
const others = locations.filter((l) => l.folder.path !== destination.path && !isFlagView(l.folder));
|
|
211
|
+
const labelled = others.filter((l) => !isAllMail(l.folder));
|
|
212
|
+
if (labelled.length > 0)
|
|
213
|
+
return labelled;
|
|
214
|
+
// Already in the destination, and in All Mail only because of it.
|
|
215
|
+
if (locations.some((l) => l.folder.path === destination.path))
|
|
216
|
+
return [];
|
|
217
|
+
return others;
|
|
218
|
+
};
|
|
219
|
+
}
|
package/dist/tools/fake-imap.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
// An in-memory stand-in for ImapFlow, for the
|
|
2
|
-
//
|
|
3
|
-
// A message with `
|
|
1
|
+
// An in-memory stand-in for ImapFlow, for the tools' tests: folders holding
|
|
2
|
+
// messages, and the SEARCH, FETCH, STORE and MOVE subset the tools use.
|
|
3
|
+
// A message with `emailId` behaves as on a server with OBJECTID or Gmail.
|
|
4
|
+
// Without MOVE in `capabilities`, a move is imapflow's fallback: COPY,
|
|
5
|
+
// \Deleted, then UID EXPUNGE with UIDPLUS or else a plain EXPUNGE.
|
|
4
6
|
import { vi } from "vitest";
|
|
5
7
|
const DAY = (d) => new Date(d).toISOString().slice(0, 10);
|
|
6
8
|
function header(m, name) {
|
|
@@ -24,7 +26,11 @@ function matches(m, q) {
|
|
|
24
26
|
}
|
|
25
27
|
if (q.threadId && m.threadId !== q.threadId)
|
|
26
28
|
return false;
|
|
29
|
+
if (q.uid && !parseRanges(String(q.uid)).includes(m.uid))
|
|
30
|
+
return false;
|
|
27
31
|
const flags = new Set(m.flags ?? []);
|
|
32
|
+
if (q.deleted !== undefined && flags.has("\\Deleted") !== q.deleted)
|
|
33
|
+
return false;
|
|
28
34
|
if (q.seen !== undefined && flags.has("\\Seen") !== q.seen)
|
|
29
35
|
return false;
|
|
30
36
|
if (q.flagged !== undefined && flags.has("\\Flagged") !== q.flagged)
|
|
@@ -55,8 +61,25 @@ function parseRanges(range) {
|
|
|
55
61
|
return Array.from({ length: b - a + 1 }, (_, i) => a + i);
|
|
56
62
|
});
|
|
57
63
|
}
|
|
58
|
-
export function fakeClient(folders) {
|
|
64
|
+
export function fakeClient(folders, capabilities = ["MOVE", "UIDPLUS", "OBJECTID"]) {
|
|
59
65
|
let open;
|
|
66
|
+
const commands = [];
|
|
67
|
+
const setFlags = (range, change) => {
|
|
68
|
+
for (const uid of parseRanges(range)) {
|
|
69
|
+
const m = find(uid);
|
|
70
|
+
if (!m)
|
|
71
|
+
continue;
|
|
72
|
+
const flags = new Set(m.flags ?? []);
|
|
73
|
+
change(flags);
|
|
74
|
+
m.flags = [...flags];
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const expunge = (uids) => {
|
|
78
|
+
if (!open)
|
|
79
|
+
return;
|
|
80
|
+
open.messages = open.messages.filter((m) => !(m.flags ?? []).includes("\\Deleted") ||
|
|
81
|
+
(uids !== undefined && !uids.includes(m.uid)));
|
|
82
|
+
};
|
|
60
83
|
const find = (uid) => open?.messages.find((m) => m.uid === uid);
|
|
61
84
|
const toFetched = (m) => ({
|
|
62
85
|
seq: m.uid,
|
|
@@ -82,6 +105,8 @@ export function fakeClient(folders) {
|
|
|
82
105
|
source: m.source === undefined ? undefined : Buffer.from(m.source),
|
|
83
106
|
});
|
|
84
107
|
const client = {
|
|
108
|
+
capabilities: new Map(capabilities.map((c) => [c, true])),
|
|
109
|
+
commands,
|
|
85
110
|
on: vi.fn(),
|
|
86
111
|
connect: vi.fn(async () => { }),
|
|
87
112
|
logout: vi.fn(async () => { }),
|
|
@@ -110,9 +135,73 @@ export function fakeClient(folders) {
|
|
|
110
135
|
readOnly: opts?.readOnly,
|
|
111
136
|
uidValidity: BigInt(open.uidValidity ?? 1),
|
|
112
137
|
exists: open.messages.length,
|
|
138
|
+
permanentFlags: opts?.readOnly || !open.permanentFlags
|
|
139
|
+
? undefined
|
|
140
|
+
: new Set(open.permanentFlags),
|
|
113
141
|
};
|
|
114
142
|
}),
|
|
115
|
-
|
|
143
|
+
messageFlagsAdd: vi.fn(async (range, flags) => {
|
|
144
|
+
if (open?.refuseWrites)
|
|
145
|
+
return false;
|
|
146
|
+
commands.push(`STORE ${open?.path} ${range} +${flags.join(" ")}`);
|
|
147
|
+
setFlags(range, (set) => flags.forEach((f) => set.add(f)));
|
|
148
|
+
return true;
|
|
149
|
+
}),
|
|
150
|
+
messageFlagsRemove: vi.fn(async (range, flags) => {
|
|
151
|
+
if (open?.refuseWrites)
|
|
152
|
+
return false;
|
|
153
|
+
commands.push(`STORE ${open?.path} ${range} -${flags.join(" ")}`);
|
|
154
|
+
setFlags(range, (set) => flags.forEach((f) => set.delete(f)));
|
|
155
|
+
return true;
|
|
156
|
+
}),
|
|
157
|
+
messageCopy: vi.fn(async (range, destination) => {
|
|
158
|
+
const dest = folders.find((f) => f.path === destination);
|
|
159
|
+
if (!open || !dest || open.refuseWrites)
|
|
160
|
+
return false;
|
|
161
|
+
commands.push(`COPY ${open.path} ${range} ${destination}`);
|
|
162
|
+
const uids = parseRanges(range);
|
|
163
|
+
let next = Math.max(0, ...dest.messages.map((m) => m.uid)) + 1;
|
|
164
|
+
dest.messages.push(...open.messages
|
|
165
|
+
.filter((m) => uids.includes(m.uid))
|
|
166
|
+
.map((m) => ({ ...m, flags: [...(m.flags ?? [])], uid: next++ })));
|
|
167
|
+
return { path: open.path, destination };
|
|
168
|
+
}),
|
|
169
|
+
messageMove: vi.fn(async (range, destination) => {
|
|
170
|
+
const source = open;
|
|
171
|
+
const dest = folders.find((f) => f.path === destination);
|
|
172
|
+
if (!source || !dest || source.refuseWrites)
|
|
173
|
+
return false;
|
|
174
|
+
const uids = parseRanges(range);
|
|
175
|
+
const moving = source.messages.filter((m) => uids.includes(m.uid));
|
|
176
|
+
let next = Math.max(0, ...dest.messages.map((m) => m.uid)) + 1;
|
|
177
|
+
dest.messages.push(...moving.map((m) => ({
|
|
178
|
+
...m,
|
|
179
|
+
flags: [...(m.flags ?? [])],
|
|
180
|
+
uid: next++,
|
|
181
|
+
})));
|
|
182
|
+
if (capabilities.includes("MOVE")) {
|
|
183
|
+
commands.push(`MOVE ${source.path} ${range} ${destination}`);
|
|
184
|
+
source.messages = source.messages.filter((m) => !uids.includes(m.uid));
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
commands.push(`COPY ${source.path} ${range} ${destination}`);
|
|
188
|
+
setFlags(range, (set) => set.add("\\Deleted"));
|
|
189
|
+
const byUid = capabilities.includes("UIDPLUS");
|
|
190
|
+
commands.push(`${byUid ? "UID EXPUNGE" : "EXPUNGE"} ${source.path}`);
|
|
191
|
+
expunge(byUid ? uids : undefined);
|
|
192
|
+
}
|
|
193
|
+
return { path: source.path, destination };
|
|
194
|
+
}),
|
|
195
|
+
search: vi.fn(async (q) => {
|
|
196
|
+
// imapflow refuses EMAILID without OBJECTID or Gmail's extension.
|
|
197
|
+
const stable = ["OBJECTID", "X-GM-EXT-1"].some((c) => capabilities.includes(c));
|
|
198
|
+
if (JSON.stringify(q).includes('"emailId"') && !stable) {
|
|
199
|
+
throw new Error("Missing server extension");
|
|
200
|
+
}
|
|
201
|
+
return (open?.messages ?? [])
|
|
202
|
+
.filter((m) => matches(m, q))
|
|
203
|
+
.map((m) => m.uid);
|
|
204
|
+
}),
|
|
116
205
|
fetch: vi.fn(async function* (range) {
|
|
117
206
|
for (const uid of parseRanges(range)) {
|
|
118
207
|
const m = find(uid);
|
package/dist/tools/imap.js
CHANGED
|
@@ -9,6 +9,20 @@ export const READ_ONLY = {
|
|
|
9
9
|
openWorldHint: false,
|
|
10
10
|
readOnlyHint: true,
|
|
11
11
|
};
|
|
12
|
+
/** Writes inside the user's own mailbox that the user can undo: langmail-mcp's ACCOUNT_WRITE. */
|
|
13
|
+
export const ACCOUNT_WRITE = {
|
|
14
|
+
destructiveHint: false,
|
|
15
|
+
idempotentHint: false,
|
|
16
|
+
openWorldHint: false,
|
|
17
|
+
readOnlyHint: false,
|
|
18
|
+
};
|
|
19
|
+
/** Removes something from the user's mailbox: langmail-mcp's ACCOUNT_DESTRUCTIVE. */
|
|
20
|
+
export const ACCOUNT_DESTRUCTIVE = {
|
|
21
|
+
destructiveHint: true,
|
|
22
|
+
idempotentHint: false,
|
|
23
|
+
openWorldHint: false,
|
|
24
|
+
readOnlyHint: false,
|
|
25
|
+
};
|
|
12
26
|
/**
|
|
13
27
|
* Annotations of a tool that reaches someone outside the mailbox and cannot
|
|
14
28
|
* be taken back, such as an unsubscribe request (langmail-mcp's
|
|
@@ -74,7 +88,7 @@ export async function selectableFolders(client) {
|
|
|
74
88
|
const folders = await client.list();
|
|
75
89
|
return folders.filter((f) => ![...f.flags].some((flag) => ["\\noselect", "\\nonexistent"].includes(flag.toLowerCase())));
|
|
76
90
|
}
|
|
77
|
-
function placeOf(folder) {
|
|
91
|
+
export function placeOf(folder) {
|
|
78
92
|
const specialUse = folder.path.toUpperCase() === "INBOX"
|
|
79
93
|
? "\\Inbox"
|
|
80
94
|
: folder.specialUse?.toLowerCase();
|
|
@@ -98,7 +112,7 @@ export function sortFolderLabels(labels) {
|
|
|
98
112
|
* special-use attribute (RFC 6154), anything else to the folder with exactly
|
|
99
113
|
* that path or name. Never creates a folder.
|
|
100
114
|
*/
|
|
101
|
-
export function resolveMailbox(folders, name) {
|
|
115
|
+
export function resolveMailbox(folders, name, nothing = "Nothing was searched.") {
|
|
102
116
|
const place = PLACES.find((p) => p.name.toLowerCase() === name.toLowerCase());
|
|
103
117
|
const found = (place && folders.find((f) => placeOf(f) === place)) ||
|
|
104
118
|
folders.find((f) => f.path === name) ||
|
|
@@ -106,7 +120,11 @@ export function resolveMailbox(folders, name) {
|
|
|
106
120
|
if (found)
|
|
107
121
|
return found;
|
|
108
122
|
const available = sortFolderLabels(folders.map(folderLabel));
|
|
109
|
-
return errorResult(`Mailbox not found: ${name}.
|
|
123
|
+
return errorResult(`Mailbox not found: ${name}. ${nothing} Available folders: ${available.join(", ")}.`);
|
|
124
|
+
}
|
|
125
|
+
/** The folder holding a standard place, such as Archive or Trash, if any. */
|
|
126
|
+
export function findPlace(folders, name) {
|
|
127
|
+
return folders.find((f) => placeOf(f)?.name === name);
|
|
110
128
|
}
|
|
111
129
|
/**
|
|
112
130
|
* A UID set as IMAP ranges ("1:3,7"), so a FETCH for thousands of hits stays
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// mark_emails: sets and clears the user-facing flags on messages: read
|
|
2
|
+
// (\Seen), starred (\Flagged) and to-do (the $label:todo keyword
|
|
3
|
+
// langmail-mcp sets, so both servers share one to-do list). One field per
|
|
4
|
+
// flag, holding the state it should end up in; a flag left out is untouched,
|
|
5
|
+
// and nothing moves. Shaped like langmail-mcp's mark_emails; the
|
|
6
|
+
// differences are in the description.
|
|
7
|
+
import { z } from "zod/v4";
|
|
8
|
+
import { byFolder, formatBatchResult, idsShape, locateMessages, outcomesOf, uniqueIds, } from "./batch.js";
|
|
9
|
+
import { ACCOUNT_WRITE, errorMessage, errorResult, TODO_KEYWORD, uidRanges, withClient, } from "./imap.js";
|
|
10
|
+
export const markEmailsShape = {
|
|
11
|
+
...idsShape,
|
|
12
|
+
read: z
|
|
13
|
+
.boolean()
|
|
14
|
+
.optional()
|
|
15
|
+
.describe("true marks the messages read, false marks them unread. Leave out to keep read state."),
|
|
16
|
+
starred: z
|
|
17
|
+
.boolean()
|
|
18
|
+
.optional()
|
|
19
|
+
.describe("true stars the messages, false removes the star. Leave out to keep it."),
|
|
20
|
+
todo: z
|
|
21
|
+
.boolean()
|
|
22
|
+
.optional()
|
|
23
|
+
.describe("true flags the messages as a to-do for the user, false clears the to-do (e.g. once it is done). " +
|
|
24
|
+
"Leave out to keep it."),
|
|
25
|
+
};
|
|
26
|
+
// Field order here is the order the result line names the flags in.
|
|
27
|
+
const FLAGS = {
|
|
28
|
+
read: { flag: "\\Seen", off: "unread", on: "read" },
|
|
29
|
+
todo: { flag: TODO_KEYWORD, off: "not to-do", on: "to-do" },
|
|
30
|
+
starred: { flag: "\\Flagged", off: "unstarred", on: "starred" },
|
|
31
|
+
};
|
|
32
|
+
export async function markEmails(createClient, args) {
|
|
33
|
+
const wanted = [];
|
|
34
|
+
const labels = [];
|
|
35
|
+
for (const [field, spec] of Object.entries(FLAGS)) {
|
|
36
|
+
const value = args[field];
|
|
37
|
+
if (value === undefined)
|
|
38
|
+
continue;
|
|
39
|
+
wanted.push({ flag: spec.flag, set: value });
|
|
40
|
+
labels.push(value ? spec.on : spec.off);
|
|
41
|
+
}
|
|
42
|
+
if (wanted.length === 0) {
|
|
43
|
+
const fields = Object.keys(FLAGS);
|
|
44
|
+
const choices = `${fields.slice(0, -1).join(", ")} or ${fields.at(-1)}`;
|
|
45
|
+
return errorResult(`No flag given, so nothing was changed. Pass at least one of ${choices}.`);
|
|
46
|
+
}
|
|
47
|
+
const ids = uniqueIds(args.ids);
|
|
48
|
+
return withClient(createClient, async (client) => {
|
|
49
|
+
const located = await locateMessages(client, ids);
|
|
50
|
+
const changed = new Set();
|
|
51
|
+
const failed = new Map();
|
|
52
|
+
const copies = [...located.locations].flatMap(([id, locs]) => locs.map((loc) => ({ id, loc })));
|
|
53
|
+
for (const [path, entries] of byFolder(copies)) {
|
|
54
|
+
try {
|
|
55
|
+
// Read-write: PERMANENTFLAGS from a read-only open often lists none.
|
|
56
|
+
const opened = await client.mailboxOpen(path);
|
|
57
|
+
const permanent = opened.permanentFlags;
|
|
58
|
+
const keepsTodo = !permanent || permanent.has("\\*") || permanent.has(TODO_KEYWORD);
|
|
59
|
+
const idOf = new Map(entries.map((e) => [e.uid, e.id]));
|
|
60
|
+
const pending = new Set();
|
|
61
|
+
const add = new Map();
|
|
62
|
+
const remove = new Map();
|
|
63
|
+
for await (const msg of client.fetch(uidRanges([...idOf.keys()]), { uid: true, flags: true }, { uid: true })) {
|
|
64
|
+
const id = idOf.get(msg.uid);
|
|
65
|
+
if (!id)
|
|
66
|
+
continue;
|
|
67
|
+
const has = msg.flags ?? new Set();
|
|
68
|
+
const todo = wanted.find((w) => w.flag === TODO_KEYWORD);
|
|
69
|
+
if (todo?.set && !has.has(TODO_KEYWORD) && !keepsTodo) {
|
|
70
|
+
failed.set(id, `the server does not keep the to-do keyword in ${path}`);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
for (const { flag, set } of wanted) {
|
|
74
|
+
if (has.has(flag) === set)
|
|
75
|
+
continue;
|
|
76
|
+
const target = set ? add : remove;
|
|
77
|
+
target.set(flag, [...(target.get(flag) ?? []), msg.uid]);
|
|
78
|
+
pending.add(id);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// imapflow answers a refused STORE with false, not an error.
|
|
82
|
+
for (const [flag, uids] of add) {
|
|
83
|
+
if (!(await client.messageFlagsAdd(uidRanges(uids), [flag], {
|
|
84
|
+
uid: true,
|
|
85
|
+
}))) {
|
|
86
|
+
throw new Error(`the server refused to set ${flag} in ${path}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
for (const [flag, uids] of remove) {
|
|
90
|
+
if (!(await client.messageFlagsRemove(uidRanges(uids), [flag], {
|
|
91
|
+
uid: true,
|
|
92
|
+
}))) {
|
|
93
|
+
throw new Error(`the server refused to clear ${flag} in ${path}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
pending.forEach((id) => changed.add(id));
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
entries.forEach((e) => failed.set(e.id, errorMessage(err)));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const outcomes = new Map([
|
|
103
|
+
...outcomesOf([...located.locations.keys()], changed, failed),
|
|
104
|
+
...located.failed,
|
|
105
|
+
].map((o) => [o.id, o]));
|
|
106
|
+
return formatBatchResult("Marked", ids.flatMap((id) => outcomes.get(id) ?? []), {
|
|
107
|
+
suffix: ` as ${labels.join(", ")}`,
|
|
108
|
+
already: `already ${labels.join(", ")}`,
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
export const MARK_EMAILS_DESCRIPTION = "Set or clear the flags on one or more messages: read / unread, to-do, and starred. " +
|
|
113
|
+
"Reading a message with get_email, get_thread or search_emails never changes its read state, so " +
|
|
114
|
+
'call this when the user wants what you read marked read or says "keep this unread"; set todo when ' +
|
|
115
|
+
'a message needs action from the user ("flag this for me", "add it to my to-dos"), clear it when ' +
|
|
116
|
+
'the to-do is done ("mark it done"), and set starred for "star this". Several flags go in one call; ' +
|
|
117
|
+
"a flag you leave out is untouched. To finish a to-do, call this tool with todo: false (plus " +
|
|
118
|
+
"read: true if it is still unread), then archive_emails. Takes message ids from search_emails or " +
|
|
119
|
+
"get_thread; folders are untouched, and re-running it on the same ids is harmless. To get a " +
|
|
120
|
+
"message out of the inbox use archive_emails or move_emails instead; to mark something as spam, " +
|
|
121
|
+
"use move_emails with Junk. Starred is the IMAP \\Flagged flag and the to-do is the " +
|
|
122
|
+
`${TODO_KEYWORD} keyword, which a server that keeps no custom keywords cannot store. ` +
|
|
123
|
+
"Reports how many messages were marked and lists any id that could not be marked, with the reason.";
|
|
124
|
+
export function registerMarkEmails(createClient, server) {
|
|
125
|
+
server.registerTool("mark_emails", {
|
|
126
|
+
title: "Mark emails read, to-do or starred",
|
|
127
|
+
description: MARK_EMAILS_DESCRIPTION,
|
|
128
|
+
inputSchema: markEmailsShape,
|
|
129
|
+
annotations: ACCOUNT_WRITE,
|
|
130
|
+
}, async (args) => markEmails(createClient, args));
|
|
131
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { describe, expect, test, vi } from "vitest";
|
|
2
|
+
import { fakeClient } from "./fake-imap.js";
|
|
3
|
+
import { ACCOUNT_WRITE, encodeMessageId } from "./imap.js";
|
|
4
|
+
import { markEmails, registerMarkEmails } from "./mark-emails.js";
|
|
5
|
+
const msg = (uid, emailId, flags) => ({
|
|
6
|
+
uid,
|
|
7
|
+
emailId,
|
|
8
|
+
date: "2026-11-01T09:00:00Z",
|
|
9
|
+
subject: `Message ${uid}`,
|
|
10
|
+
from: "sender@example.com",
|
|
11
|
+
flags,
|
|
12
|
+
});
|
|
13
|
+
const folders = () => [
|
|
14
|
+
{
|
|
15
|
+
path: "INBOX",
|
|
16
|
+
permanentFlags: ["\\Seen", "\\Flagged", "\\*"],
|
|
17
|
+
messages: [msg(1, "m1"), msg(2, "m2", ["\\Seen", "\\Flagged"])],
|
|
18
|
+
},
|
|
19
|
+
{ path: "Archive", specialUse: "\\Archive", messages: [] },
|
|
20
|
+
];
|
|
21
|
+
const stable = (emailId) => encodeMessageId({ kind: "stable", emailId });
|
|
22
|
+
describe("mark_emails", () => {
|
|
23
|
+
test("registers as an account write named mark_emails", () => {
|
|
24
|
+
const server = { registerTool: vi.fn() };
|
|
25
|
+
registerMarkEmails(fakeClient([]).createClient, server);
|
|
26
|
+
expect(server.registerTool).toHaveBeenCalledWith("mark_emails", expect.objectContaining({ annotations: ACCOUNT_WRITE }), expect.any(Function));
|
|
27
|
+
});
|
|
28
|
+
test("sets read and to-do, leaves starred alone, and moves nothing", async () => {
|
|
29
|
+
const data = folders();
|
|
30
|
+
const { client, createClient } = fakeClient(data);
|
|
31
|
+
const result = await markEmails(createClient, {
|
|
32
|
+
ids: [stable("m1")],
|
|
33
|
+
read: true,
|
|
34
|
+
todo: true,
|
|
35
|
+
});
|
|
36
|
+
expect(result).toEqual({
|
|
37
|
+
content: [{ type: "text", text: "Marked 1 message(s) as read, to-do." }],
|
|
38
|
+
});
|
|
39
|
+
expect(data[0].messages[0].flags).toEqual(["\\Seen", "$label:todo"]);
|
|
40
|
+
expect(client.messageMove).not.toHaveBeenCalled();
|
|
41
|
+
});
|
|
42
|
+
test("clears flags, and counts a message already so as unchanged", async () => {
|
|
43
|
+
const data = folders();
|
|
44
|
+
const { client, createClient } = fakeClient(data);
|
|
45
|
+
const result = await markEmails(createClient, {
|
|
46
|
+
ids: [stable("m1"), stable("m2")],
|
|
47
|
+
read: false,
|
|
48
|
+
starred: false,
|
|
49
|
+
});
|
|
50
|
+
expect(result.content[0].text).toBe("Marked 1 message(s) as unread, unstarred. 1 message(s) already unread, unstarred.");
|
|
51
|
+
expect(data[0].messages[1].flags).toEqual([]);
|
|
52
|
+
expect(client.commands).toEqual([
|
|
53
|
+
"STORE INBOX 2 -\\Seen",
|
|
54
|
+
"STORE INBOX 2 -\\Flagged",
|
|
55
|
+
]);
|
|
56
|
+
});
|
|
57
|
+
test("a second identical call changes nothing and is not an error", async () => {
|
|
58
|
+
const { client, createClient } = fakeClient(folders());
|
|
59
|
+
await markEmails(createClient, { ids: [stable("m1")], starred: true });
|
|
60
|
+
client.commands.length = 0;
|
|
61
|
+
const again = await markEmails(createClient, {
|
|
62
|
+
ids: [stable("m1")],
|
|
63
|
+
starred: true,
|
|
64
|
+
});
|
|
65
|
+
expect(again).toEqual({
|
|
66
|
+
content: [
|
|
67
|
+
{
|
|
68
|
+
type: "text",
|
|
69
|
+
text: "Marked 0 message(s) as starred. 1 message(s) already starred.",
|
|
70
|
+
},
|
|
71
|
+
],
|
|
72
|
+
});
|
|
73
|
+
expect(client.commands).toEqual([]);
|
|
74
|
+
});
|
|
75
|
+
test("names the ids whose to-do the server cannot keep", async () => {
|
|
76
|
+
const data = folders();
|
|
77
|
+
data[0].permanentFlags = ["\\Seen", "\\Flagged"];
|
|
78
|
+
const { createClient } = fakeClient(data);
|
|
79
|
+
const result = await markEmails(createClient, {
|
|
80
|
+
ids: [stable("m1")],
|
|
81
|
+
todo: true,
|
|
82
|
+
});
|
|
83
|
+
expect(result.isError).toBe(true);
|
|
84
|
+
expect(result.content[0].text).toBe(`Marked 0 message(s) as to-do. Not updated (1): ${stable("m1")} (the server does not keep the to-do keyword in INBOX).`);
|
|
85
|
+
expect(data[0].messages[0].flags).toBeUndefined();
|
|
86
|
+
});
|
|
87
|
+
test("without a flag, changes nothing", async () => {
|
|
88
|
+
const { client, createClient } = fakeClient(folders());
|
|
89
|
+
const result = await markEmails(createClient, { ids: [stable("m1")] });
|
|
90
|
+
expect(result).toEqual({
|
|
91
|
+
content: [
|
|
92
|
+
{
|
|
93
|
+
type: "text",
|
|
94
|
+
text: "No flag given, so nothing was changed. Pass at least one of read, todo or starred.",
|
|
95
|
+
},
|
|
96
|
+
],
|
|
97
|
+
isError: true,
|
|
98
|
+
});
|
|
99
|
+
expect(client.connect).not.toHaveBeenCalled();
|
|
100
|
+
});
|
|
101
|
+
test("a refused STORE is reported, not counted as marked", async () => {
|
|
102
|
+
const data = folders();
|
|
103
|
+
data[0].refuseWrites = true;
|
|
104
|
+
const { createClient } = fakeClient(data);
|
|
105
|
+
const result = await markEmails(createClient, {
|
|
106
|
+
ids: [stable("m1")],
|
|
107
|
+
read: true,
|
|
108
|
+
});
|
|
109
|
+
expect(result.isError).toBe(true);
|
|
110
|
+
expect(result.content[0].text).toBe(`Marked 0 message(s) as read. Not updated (1): ${stable("m1")} (the server refused to set \\Seen in INBOX).`);
|
|
111
|
+
});
|
|
112
|
+
test("marks a message in several folders once", async () => {
|
|
113
|
+
const data = folders();
|
|
114
|
+
data[1].messages.push(msg(5, "m1"));
|
|
115
|
+
const { createClient } = fakeClient(data);
|
|
116
|
+
const result = await markEmails(createClient, {
|
|
117
|
+
ids: [stable("m1")],
|
|
118
|
+
starred: true,
|
|
119
|
+
});
|
|
120
|
+
expect(result.content[0].text).toBe("Marked 1 message(s) as starred.");
|
|
121
|
+
expect(data[0].messages[0].flags).toEqual(["\\Flagged"]);
|
|
122
|
+
expect(data[1].messages[0].flags).toEqual(["\\Flagged"]);
|
|
123
|
+
});
|
|
124
|
+
});
|