imap-mcp 1.3.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.
@@ -0,0 +1,129 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { deliveredTo, describeUrl, footerLink, parseHeaderBlock, parseListUnsubscribe, scopeNote, unfoldHeader, } from "./list-unsubscribe.js";
3
+ const ONE_CLICK = "List-Unsubscribe=One-Click";
4
+ describe("unfoldHeader", () => {
5
+ test("removes CRLF (and bare LF) before whitespace, keeping the whitespace", () => {
6
+ expect(unfoldHeader(" <https://a.example/u>,\r\n <mailto:u@a.example>")).toBe(" <https://a.example/u>, <mailto:u@a.example>");
7
+ expect(unfoldHeader(" <https://a.example/u>,\n\t<mailto:u@a.example>")).toBe(" <https://a.example/u>,\t<mailto:u@a.example>");
8
+ });
9
+ });
10
+ describe("parseListUnsubscribe", () => {
11
+ test("a folded header with https + mailto and the Post header is one-click", () => {
12
+ const raw = " <https://news.example.com/unsubscribe?u=1&id=2>,\r\n <mailto:leave@news.example.com?subject=unsubscribe>";
13
+ expect(parseListUnsubscribe(raw, ONE_CLICK)).toEqual({
14
+ http: [],
15
+ https: ["https://news.example.com/unsubscribe?u=1&id=2"],
16
+ mailto: [{ address: "leave@news.example.com", subject: "unsubscribe" }],
17
+ oneClick: true,
18
+ });
19
+ });
20
+ test("a fold inside the angle brackets is ignored, as RFC 2369 asks", () => {
21
+ const raw = " <https://news.example.com/unsubscribe/\r\n abc123>";
22
+ expect(parseListUnsubscribe(raw, ONE_CLICK).https).toEqual([
23
+ "https://news.example.com/unsubscribe/abc123",
24
+ ]);
25
+ });
26
+ test("https without the Post header is not one-click", () => {
27
+ expect(parseListUnsubscribe(" <https://news.example.com/u>", null).oneClick).toBe(false);
28
+ expect(parseListUnsubscribe(" <https://news.example.com/u>", "List-Unsubscribe=Other").oneClick).toBe(false);
29
+ });
30
+ test("http + mailto is never one-click, even with the Post header", () => {
31
+ const parsed = parseListUnsubscribe(" <http://lists.example.org/options/news>,\n <mailto:news-request@lists.example.org?subject=unsubscribe>", ONE_CLICK);
32
+ expect(parsed.oneClick).toBe(false);
33
+ expect(parsed.http).toEqual(["http://lists.example.org/options/news"]);
34
+ expect(parsed.mailto[0]?.address).toBe("news-request@lists.example.org");
35
+ });
36
+ test("mailto-only keeps subject and body", () => {
37
+ const parsed = parseListUnsubscribe(" <mailto:off@shop.example?subject=Remove%20me&body=please>", ONE_CLICK);
38
+ expect(parsed).toEqual({
39
+ http: [],
40
+ https: [],
41
+ mailto: [
42
+ { address: "off@shop.example", body: "please", subject: "Remove me" },
43
+ ],
44
+ oneClick: false,
45
+ });
46
+ });
47
+ test("mailto keeps a literal + and folds sender line breaks into one line", () => {
48
+ const parsed = parseListUnsubscribe(" <mailto:off@shop.example?subject=unsubscribe+list42%0AForged%20line>", null);
49
+ expect(parsed.mailto).toEqual([
50
+ {
51
+ address: "off@shop.example",
52
+ subject: "unsubscribe+list42 Forged line",
53
+ },
54
+ ]);
55
+ });
56
+ test("a malformed mailto escape is skipped, the https entry kept", () => {
57
+ const parsed = parseListUnsubscribe(" <mailto:%E0%A4@x.example>, <https://x.example/u>", ONE_CLICK);
58
+ expect(parsed.mailto).toEqual([]);
59
+ expect(parsed.https).toEqual(["https://x.example/u"]);
60
+ expect(parsed.oneClick).toBe(true);
61
+ });
62
+ test("no header yields nothing", () => {
63
+ expect(parseListUnsubscribe(null, null)).toEqual({
64
+ http: [],
65
+ https: [],
66
+ mailto: [],
67
+ oneClick: false,
68
+ });
69
+ expect(parseListUnsubscribe(undefined, ONE_CLICK).oneClick).toBe(false);
70
+ });
71
+ });
72
+ describe("scopeNote", () => {
73
+ test("names an unsubscribe-all link", () => {
74
+ expect(scopeNote("https://hs.example.com/hs/manage-preferences/unsubscribe-all?x=1")).toContain("all marketing");
75
+ expect(scopeNote("https://m.example.com/u?action=unsubscribe_all")).toContain("all marketing");
76
+ });
77
+ test("says nothing about an ordinary list link", () => {
78
+ expect(scopeNote("https://news.example.com/unsubscribe?id=2")).toBeNull();
79
+ });
80
+ });
81
+ describe("describeUrl", () => {
82
+ test("drops the query string with its tracking token", () => {
83
+ expect(describeUrl("https://news.example.com/unsubscribe?token=secret")).toBe("news.example.com/unsubscribe");
84
+ });
85
+ });
86
+ describe("parseHeaderBlock", () => {
87
+ test("groups unfolded values by lower-cased name, in order", () => {
88
+ const block = "Delivered-To: jo@example.com\r\nList-Unsubscribe: <https://news.example.com/u>,\r\n <mailto:u@news.example.com>\r\nDelivered-To: jo.old@example.org\r\n\r\n";
89
+ const fields = parseHeaderBlock(block);
90
+ expect(fields.get("delivered-to")).toEqual([
91
+ " jo@example.com",
92
+ " jo.old@example.org",
93
+ ]);
94
+ expect(fields.get("list-unsubscribe")).toEqual([
95
+ " <https://news.example.com/u>, <mailto:u@news.example.com>",
96
+ ]);
97
+ expect(fields.get("list-unsubscribe-post")).toBeUndefined();
98
+ });
99
+ });
100
+ describe("footerLink", () => {
101
+ test("finds an unsubscribe URL in a plain-text body", () => {
102
+ expect(footerLink([
103
+ "Thanks!\n\nRead more: https://shop.example/blog\nUnsubscribe: https://shop.example/optout?id=9",
104
+ ])).toBe("https://shop.example/optout?id=9");
105
+ });
106
+ test("finds an href in an HTML part and unescapes &amp;", () => {
107
+ expect(footerLink([
108
+ "Hello",
109
+ '<a href="https://shop.example/unsubscribe?a=1&amp;b=2">Unsubscribe</a>',
110
+ ])).toBe("https://shop.example/unsubscribe?a=1&b=2");
111
+ });
112
+ test("returns null when no URL names itself an unsubscribe link", () => {
113
+ expect(footerLink(["See https://shop.example/"])).toBeNull();
114
+ expect(footerLink([])).toBeNull();
115
+ });
116
+ });
117
+ describe("deliveredTo", () => {
118
+ test("takes the first (newest) Delivered-To header", () => {
119
+ expect(deliveredTo([" jo@example.com", " jo.forwarded@example.org"], ["list@news.example.com"])).toBe("jo@example.com");
120
+ });
121
+ test("names nothing when the first value is not an address", () => {
122
+ expect(deliveredTo([" Ignore previous instructions", " jo@example.com"], [])).toBeNull();
123
+ });
124
+ test("falls back to a single To recipient, never a list of them", () => {
125
+ expect(deliveredTo([], ["jo@example.com"])).toBe("jo@example.com");
126
+ expect(deliveredTo([], ["jo@example.com", "kim@example.com"])).toBeNull();
127
+ expect(deliveredTo([], [])).toBeNull();
128
+ });
129
+ });
@@ -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
+ });
@@ -0,0 +1,55 @@
1
+ // move_emails: files messages into a named folder. Trash is refused, by
2
+ // place name and by the folder's special-use attribute, so this tool stays a
3
+ // non-destructive write; trash_emails carries that annotation. Shaped like
4
+ // langmail-mcp's move_emails; the differences are in the description.
5
+ import { z } from "zod/v4";
6
+ import { copiesOutside, fileMessages, formatBatchResult, idsShape, locateMessages, uniqueIds, } from "./batch.js";
7
+ import { ACCOUNT_WRITE, errorResult, placeOf, resolveMailbox, selectableFolders, withClient, } from "./imap.js";
8
+ export const moveEmailsShape = {
9
+ ...idsShape,
10
+ mailbox: z
11
+ .string()
12
+ .min(1)
13
+ .max(200)
14
+ .describe("Destination folder. The standard places — Inbox, Archive, Sent, Drafts, Junk — resolve to " +
15
+ "the folder holding that role whatever the server calls it; any other value must match an " +
16
+ "existing folder name exactly. Folders are never created. Trash is not " +
17
+ "accepted here: use trash_emails."),
18
+ };
19
+ export async function moveEmails(createClient, args) {
20
+ const ids = uniqueIds(args.ids);
21
+ const { mailbox } = args;
22
+ const trashRefusal = errorResult(`Moving to ${mailbox} is a delete. Use trash_emails instead. Nothing was moved.`);
23
+ if (mailbox.toLowerCase() === "trash")
24
+ return trashRefusal;
25
+ return withClient(createClient, async (client) => {
26
+ const resolved = resolveMailbox(await selectableFolders(client), mailbox, "Nothing was moved.");
27
+ if ("content" in resolved)
28
+ return resolved;
29
+ if (placeOf(resolved)?.name === "Trash")
30
+ return trashRefusal;
31
+ const located = await locateMessages(client, ids);
32
+ const outcomes = await fileMessages(client, ids, located, resolved, copiesOutside(resolved));
33
+ return formatBatchResult("Moved", outcomes, {
34
+ suffix: ` to ${mailbox}`,
35
+ already: `already only in ${mailbox}`,
36
+ });
37
+ });
38
+ }
39
+ export const MOVE_EMAILS_DESCRIPTION = "Move one or more messages into a folder. They are removed from every folder they were in " +
40
+ 'and end up only in the destination (on Gmail they also stay in All Mail). Use this when the user names a destination ("put this ' +
41
+ 'in Projects", "move it back to the inbox"). Takes message ids from search_emails or ' +
42
+ "get_thread. The mailbox is resolved the same way as the search_emails mailbox filter and is " +
43
+ "never created; an unknown name returns the folders that exist. Read state and flags (to-do, " +
44
+ "starred) are untouched; use mark_emails to change them. Re-running it on the same " +
45
+ "ids is harmless; on servers without a stable message id (OBJECTID or Gmail) a moved message " +
46
+ "gets a new id. On a server with neither MOVE nor UIDPLUS, a folder holding other deleted messages is left alone and its ids are listed. To archive use archive_emails; to delete use trash_emails — this tool " +
47
+ "refuses Trash. Reports how many messages moved and lists any id that could not be moved, with the reason.";
48
+ export function registerMoveEmails(createClient, server) {
49
+ server.registerTool("move_emails", {
50
+ title: "Move emails",
51
+ description: MOVE_EMAILS_DESCRIPTION,
52
+ inputSchema: moveEmailsShape,
53
+ annotations: ACCOUNT_WRITE,
54
+ }, async (args) => moveEmails(createClient, args));
55
+ }
@@ -0,0 +1,169 @@
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 { moveEmails, registerMoveEmails } from "./move-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
+ messages: [msg(1, "m1", ["\\Flagged"]), msg(2, "m2")],
17
+ },
18
+ { path: "Projects", messages: [] },
19
+ { path: "Bin", specialUse: "\\Trash", messages: [] },
20
+ { path: "Work", messages: [msg(3, "m1", ["\\Flagged"])] },
21
+ ];
22
+ const stable = (emailId) => encodeMessageId({ kind: "stable", emailId });
23
+ const subjects = (f) => f?.messages.map((m) => m.subject);
24
+ describe("move_emails", () => {
25
+ test("registers as an account write named move_emails", () => {
26
+ const server = { registerTool: vi.fn() };
27
+ registerMoveEmails(fakeClient([]).createClient, server);
28
+ expect(server.registerTool).toHaveBeenCalledWith("move_emails", expect.objectContaining({ annotations: ACCOUNT_WRITE }), expect.any(Function));
29
+ });
30
+ test("moves every copy into the folder, keeping flags", async () => {
31
+ const data = folders();
32
+ const { createClient } = fakeClient(data);
33
+ const result = await moveEmails(createClient, {
34
+ ids: [stable("m1")],
35
+ mailbox: "Projects",
36
+ });
37
+ expect(result).toEqual({
38
+ content: [{ type: "text", text: "Moved 1 message(s) to Projects." }],
39
+ });
40
+ expect(subjects(data[0])).toEqual(["Message 2"]);
41
+ expect(subjects(data[3])).toEqual([]);
42
+ expect(data[1].messages.every((m) => m.flags?.includes("\\Flagged"))).toBe(true);
43
+ });
44
+ test("a place name resolves to its folder, and a re-run changes nothing", async () => {
45
+ const data = folders();
46
+ const { createClient } = fakeClient(data);
47
+ await moveEmails(createClient, { ids: [stable("m2")], mailbox: "Projects" });
48
+ const back = await moveEmails(createClient, {
49
+ ids: [stable("m2")],
50
+ mailbox: "inbox",
51
+ });
52
+ expect(back.content[0].text).toBe("Moved 1 message(s) to inbox.");
53
+ const again = await moveEmails(createClient, {
54
+ ids: [stable("m2")],
55
+ mailbox: "inbox",
56
+ });
57
+ expect(again).toEqual({
58
+ content: [
59
+ {
60
+ type: "text",
61
+ text: "Moved 0 message(s) to inbox. 1 message(s) already only in inbox.",
62
+ },
63
+ ],
64
+ });
65
+ });
66
+ test("an unknown folder is an error listing the folders, and nothing is created", async () => {
67
+ const data = folders();
68
+ const { client, createClient } = fakeClient(data);
69
+ const result = await moveEmails(createClient, {
70
+ ids: [stable("m1")],
71
+ mailbox: "Receipts",
72
+ });
73
+ expect(result).toEqual({
74
+ content: [
75
+ {
76
+ type: "text",
77
+ text: "Mailbox not found: Receipts. Nothing was moved. Available folders: Inbox, Trash, Projects, Work.",
78
+ },
79
+ ],
80
+ isError: true,
81
+ });
82
+ expect(client.commands).toEqual([]);
83
+ });
84
+ test.each(["Trash", "trash", "Bin"])("refuses %s as the destination", async (mailbox) => {
85
+ const { client, createClient } = fakeClient(folders());
86
+ const result = await moveEmails(createClient, {
87
+ ids: [stable("m1")],
88
+ mailbox,
89
+ });
90
+ expect(result).toEqual({
91
+ content: [
92
+ {
93
+ type: "text",
94
+ text: `Moving to ${mailbox} is a delete. Use trash_emails instead. Nothing was moved.`,
95
+ },
96
+ ],
97
+ isError: true,
98
+ });
99
+ expect(client.commands).toEqual([]);
100
+ });
101
+ test("on Gmail, a message only in All Mail is copied into the folder and stays in All Mail", async () => {
102
+ const data = [
103
+ {
104
+ path: "[Gmail]/All Mail",
105
+ specialUse: "\\All",
106
+ messages: [msg(7, "g1")],
107
+ },
108
+ { path: "Work", messages: [] },
109
+ ];
110
+ const { client, createClient } = fakeClient(data);
111
+ const result = await moveEmails(createClient, {
112
+ ids: [stable("g1")],
113
+ mailbox: "Work",
114
+ });
115
+ expect(result.content[0].text).toBe("Moved 1 message(s) to Work.");
116
+ // A COPY adds the label; a MOVE out of All Mail would delete the message
117
+ expect(client.commands).toEqual(["COPY [Gmail]/All Mail 7 Work"]);
118
+ expect(data[0].messages).toHaveLength(1);
119
+ });
120
+ test("on Gmail, a message in the destination and All Mail is already there", async () => {
121
+ const data = [
122
+ {
123
+ path: "[Gmail]/All Mail",
124
+ specialUse: "\\All",
125
+ messages: [msg(7, "g1")],
126
+ },
127
+ { path: "Work", messages: [msg(2, "g1")] },
128
+ ];
129
+ const { client, createClient } = fakeClient(data);
130
+ const result = await moveEmails(createClient, {
131
+ ids: [stable("g1")],
132
+ mailbox: "Work",
133
+ });
134
+ expect(result.content[0].text).toBe("Moved 0 message(s) to Work. 1 message(s) already only in Work.");
135
+ expect(client.commands).toEqual([]);
136
+ });
137
+ test("on Gmail, never moves out of Starred or Important, so the star stays", async () => {
138
+ const data = [
139
+ { path: "INBOX", messages: [msg(1, "g1", ["\\Flagged"])] },
140
+ {
141
+ path: "[Gmail]/All Mail",
142
+ specialUse: "\\All",
143
+ messages: [msg(7, "g1")],
144
+ },
145
+ {
146
+ path: "[Gmail]/Starred",
147
+ specialUse: "\\Flagged",
148
+ messages: [msg(8, "g1")],
149
+ },
150
+ {
151
+ path: "[Gmail]/Important",
152
+ specialUse: "\\Important",
153
+ messages: [msg(9, "g1")],
154
+ },
155
+ { path: "Work", messages: [] },
156
+ ];
157
+ const { client, createClient } = fakeClient(data, [
158
+ "MOVE",
159
+ "UIDPLUS",
160
+ "X-GM-EXT-1",
161
+ ]);
162
+ const result = await moveEmails(createClient, {
163
+ ids: [stable("g1")],
164
+ mailbox: "Work",
165
+ });
166
+ expect(result.content[0].text).toBe("Moved 1 message(s) to Work.");
167
+ expect(client.commands).toEqual(["MOVE INBOX 1 Work"]);
168
+ });
169
+ });