imap-mcp 1.1.0 → 1.3.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,138 @@
1
+ // get_email: one message's recipients, folders and readable body, by the id
2
+ // search_emails returns. Shaped like langmail-mcp's get_email; the
3
+ // differences are in the description.
4
+ // A default import: langmail is a CommonJS (napi) module, and Node does not
5
+ // find its named exports from ESM.
6
+ import langmail from "langmail";
7
+ import { z } from "zod/v4";
8
+ import { attachmentsOf, decodeMessageId, errorResult, formatAddresses, formatAttachmentLine, formatDate, locateMessage, messageTags, READ_ONLY, SAFETY_LINE, textResult, withClient, } from "./imap.js";
9
+ // Larger messages skip the download-and-clean path: attachments are inside
10
+ // the raw message, so a big one means buffering megabytes for the body.
11
+ const MAX_RAW_MESSAGE_BYTES = 10_000_000;
12
+ // Caps the body so a huge newsletter cannot blow the token budget.
13
+ const MAX_BODY_CHARS = 100_000;
14
+ export const getEmailShape = {
15
+ id: z
16
+ .string()
17
+ .min(1)
18
+ .describe("The message id, as returned by search_emails or get_thread."),
19
+ };
20
+ const notFound = (id) => errorResult(`Email not found: ${id}. It may have been deleted, or moved on a server without a stable message id. Find it again with search_emails.`);
21
+ /** The whole message through langmail, or null when that path is unavailable. */
22
+ function cleanedBody(source) {
23
+ if (!source)
24
+ return null;
25
+ try {
26
+ const processed = langmail.preprocessWithOptions(source, {
27
+ maxBodyLength: MAX_BODY_CHARS,
28
+ // The agent opened this message, so nothing is silently dropped.
29
+ stripQuotes: false,
30
+ stripSignature: false,
31
+ });
32
+ return processed.body.trim() || null;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ /** The first text/plain part, for messages too large for the raw path. */
39
+ async function plainTextBody(client, msg) {
40
+ const find = (node = msg.bodyStructure) => {
41
+ if (!node)
42
+ return undefined;
43
+ // Not into a forwarded message: its text is not this message's body.
44
+ if (node.type.toLowerCase() === "message/rfc822")
45
+ return undefined;
46
+ if (node.childNodes?.length) {
47
+ for (const child of node.childNodes) {
48
+ const part = find(child);
49
+ if (part)
50
+ return part;
51
+ }
52
+ return undefined;
53
+ }
54
+ return node.type.toLowerCase() === "text/plain" &&
55
+ node.disposition?.toLowerCase() !== "attachment"
56
+ ? (node.part ?? "1")
57
+ : undefined;
58
+ };
59
+ const part = find();
60
+ if (!part)
61
+ return null;
62
+ const { content } = await client.download(String(msg.uid), part, {
63
+ uid: true,
64
+ maxBytes: MAX_BODY_CHARS,
65
+ });
66
+ if (!content)
67
+ return null;
68
+ const chunks = [];
69
+ for await (const chunk of content)
70
+ chunks.push(Buffer.from(chunk));
71
+ return Buffer.concat(chunks).toString("utf8").trim() || null;
72
+ }
73
+ export async function getEmail(createClient, id) {
74
+ const ref = decodeMessageId(id);
75
+ if (!ref) {
76
+ return errorResult(`Not a message id: ${id}. Pass an id exactly as search_emails or get_thread printed it.`);
77
+ }
78
+ return withClient(createClient, async (client) => {
79
+ const located = await locateMessage(client, ref);
80
+ if (!located)
81
+ return notFound(id);
82
+ await client.mailboxOpen(located.path, { readOnly: true });
83
+ const msg = await client.fetchOne(String(located.uid), {
84
+ uid: true,
85
+ envelope: true,
86
+ flags: true,
87
+ internalDate: true,
88
+ size: true,
89
+ bodyStructure: true,
90
+ }, { uid: true });
91
+ if (!msg)
92
+ return notFound(id);
93
+ const { envelope } = msg;
94
+ const header = [
95
+ `Subject: ${envelope?.subject || "(no subject)"}`,
96
+ `From: ${formatAddresses(envelope?.from) || "(unknown sender)"}`,
97
+ `To: ${formatAddresses(envelope?.to) || "(none)"}`,
98
+ ];
99
+ const cc = formatAddresses(envelope?.cc);
100
+ if (cc)
101
+ header.push(`Cc: ${cc}`);
102
+ header.push(`Date: ${formatDate(msg.internalDate)}`);
103
+ header.push(`Folders: ${located.folders.join(", ")}`);
104
+ const tags = messageTags(msg.flags);
105
+ if (tags.length > 0)
106
+ header.push(`Tags: ${tags.join(", ")}`);
107
+ let body = null;
108
+ if (msg.size !== undefined && msg.size <= MAX_RAW_MESSAGE_BYTES) {
109
+ // BODY.PEEK[] in a folder opened read-only: \Seen stays as it was.
110
+ const raw = await client.fetchOne(String(located.uid), { source: true }, { uid: true });
111
+ body = cleanedBody(raw ? raw.source : undefined);
112
+ }
113
+ body ??= await plainTextBody(client, msg);
114
+ const attachments = attachmentsOf(msg.bodyStructure);
115
+ const attachmentSection = attachments.length > 0
116
+ ? `\n\nAttachments (${attachments.length}):\n${attachments.map((a, i) => formatAttachmentLine(i + 1, a)).join("\n")}`
117
+ : "";
118
+ return textResult(`${header.join("\n")}\n\n${body ?? "(no text body)"}${attachmentSection}`);
119
+ });
120
+ }
121
+ export const GET_EMAIL_DESCRIPTION = "Fetch a single message's recipients, folders and body by id. The body is " +
122
+ "rendered as readable text/markdown regardless of how the sender " +
123
+ "formatted it (HTML newsletters and invoices come back as clean " +
124
+ "markdown, not raw HTML); a message over 10 MB shows only its plain-text part, if it has one. Use the id returned by search_emails or get_thread; on servers without a stable " +
125
+ "message id (OBJECTID or Gmail) the id changes when the message moves to another folder, so " +
126
+ "search again if it is not found. Attachments are listed after the body with filename, media type " +
127
+ 'and size; parts marked "inline" are images referenced by the HTML body (logos, ' +
128
+ "signatures) rather than genuine documents. Attachment contents are never returned here. " +
129
+ "This tool never shows bcc. Fetching a message does not mark it read. " +
130
+ SAFETY_LINE;
131
+ export function registerGetEmail(createClient, server) {
132
+ server.registerTool("get_email", {
133
+ title: "Get email",
134
+ description: GET_EMAIL_DESCRIPTION,
135
+ inputSchema: getEmailShape,
136
+ annotations: READ_ONLY,
137
+ }, async ({ id }) => getEmail(createClient, id));
138
+ }
@@ -0,0 +1,128 @@
1
+ import { describe, expect, test, vi } from "vitest";
2
+ import { fakeClient } from "./fake-imap.js";
3
+ import { encodeMessageId, READ_ONLY } from "./imap.js";
4
+ import { getEmail, registerGetEmail } from "./get-email.js";
5
+ const SOURCE = [
6
+ "From: Example Billing <billing@example.com>",
7
+ "To: jane@example.com",
8
+ "Subject: Invoice November",
9
+ "Date: Sun, 01 Nov 2026 09:00:00 +0000",
10
+ "MIME-Version: 1.0",
11
+ 'Content-Type: text/html; charset="utf-8"',
12
+ "",
13
+ "<html><body><h1>Invoice</h1><p>Total: <b>42 EUR</b></p></body></html>",
14
+ ].join("\r\n");
15
+ const folders = () => [
16
+ {
17
+ path: "INBOX",
18
+ uidValidity: 9,
19
+ messages: [
20
+ {
21
+ uid: 1,
22
+ emailId: "m1",
23
+ date: "2026-11-01T09:00:00Z",
24
+ subject: "Invoice November",
25
+ from: "billing@example.com",
26
+ to: "jane@example.com",
27
+ flags: ["$label:todo"],
28
+ source: SOURCE,
29
+ bodyStructure: {
30
+ type: "multipart/mixed",
31
+ childNodes: [
32
+ { type: "text/html", part: "1" },
33
+ {
34
+ type: "application/pdf",
35
+ part: "2",
36
+ disposition: "attachment",
37
+ dispositionParameters: { filename: "invoice.pdf" },
38
+ size: 2048,
39
+ },
40
+ ],
41
+ },
42
+ },
43
+ ],
44
+ },
45
+ {
46
+ path: "Work",
47
+ messages: [
48
+ {
49
+ uid: 5,
50
+ emailId: "m1",
51
+ date: "2026-11-01T09:00:00Z",
52
+ subject: "Invoice November",
53
+ from: "billing@example.com",
54
+ },
55
+ ],
56
+ },
57
+ {
58
+ path: "Old",
59
+ uidValidity: 4,
60
+ messages: [
61
+ {
62
+ uid: 2,
63
+ date: "2026-01-01T09:00:00Z",
64
+ subject: "Big one",
65
+ from: "friend@example.org",
66
+ text: "Plain text body",
67
+ source: SOURCE,
68
+ size: 20_000_000,
69
+ bodyStructure: {
70
+ type: "multipart/mixed",
71
+ childNodes: [{ type: "text/plain", part: "1" }],
72
+ },
73
+ },
74
+ ],
75
+ },
76
+ ];
77
+ const stable = encodeMessageId({ kind: "stable", emailId: "m1" });
78
+ describe("get_email", () => {
79
+ test("registers as a read-only tool named get_email", () => {
80
+ const server = { registerTool: vi.fn() };
81
+ registerGetEmail(fakeClient([]).createClient, server);
82
+ expect(server.registerTool).toHaveBeenCalledWith("get_email", expect.objectContaining({ annotations: READ_ONLY }), expect.any(Function));
83
+ });
84
+ test("reads a message by stable id: recipients, every folder, Markdown body, attachments", async () => {
85
+ const { client, createClient } = fakeClient(folders());
86
+ const result = await getEmail(createClient, stable);
87
+ const out = result.content[0].text;
88
+ expect(out).toMatch(/^Subject: Invoice November\nFrom: billing@example.com\nTo: jane@example.com\nDate: 2026-11-01T09:00:00Z\nFolders: Inbox, Work\nTags: todo\n\n/);
89
+ expect(out).toContain("42 EUR");
90
+ expect(out).not.toContain("<html>");
91
+ expect(out).toMatch(/\n\nAttachments \(1\):\n1\. invoice\.pdf — application\/pdf, 2\.0 KB$/);
92
+ // Opened read-only, so \Seen never changes
93
+ expect(client.mailboxOpen.mock.calls.every((c) => c[1]?.readOnly === true)).toBe(true);
94
+ });
95
+ test("reads a message by folder and UID, falling back to its text part when too large", async () => {
96
+ const id = encodeMessageId({
97
+ kind: "uid",
98
+ path: "Old",
99
+ uidValidity: "4",
100
+ uid: 2,
101
+ });
102
+ const { client: c, createClient: make } = fakeClient(folders());
103
+ const out = (await getEmail(make, id)).content[0].text;
104
+ expect(out).toContain("Folders: Old");
105
+ expect(out).toMatch(/\n\nPlain text body$/);
106
+ // Over 10 MB: the raw message is never fetched
107
+ expect(c.fetchOne.mock.calls.some((call) => "source" in (call[1] ?? {}))).toBe(false);
108
+ });
109
+ test("a UID id from another UIDVALIDITY is not found", async () => {
110
+ const { createClient } = fakeClient(folders());
111
+ const id = encodeMessageId({
112
+ kind: "uid",
113
+ path: "Old",
114
+ uidValidity: "3",
115
+ uid: 2,
116
+ });
117
+ const result = await getEmail(createClient, id);
118
+ expect(result.isError).toBe(true);
119
+ expect(result.content[0].text).toContain("Email not found");
120
+ });
121
+ test("an unknown or malformed id is an error", async () => {
122
+ const { createClient } = fakeClient(folders());
123
+ expect((await getEmail(createClient, encodeMessageId({ kind: "stable", emailId: "nope" }))).isError).toBe(true);
124
+ const bad = await getEmail(createClient, "garbage");
125
+ expect(bad.isError).toBe(true);
126
+ expect(bad.content[0].text).toContain("Not a message id");
127
+ });
128
+ });
@@ -0,0 +1,149 @@
1
+ // get_thread: every message of a message's conversation, oldest first, in
2
+ // search_emails' hit format, the user's replies in Sent included. Shaped like
3
+ // langmail-mcp's get_thread; the differences are in the description.
4
+ //
5
+ // A thread is the server's thread id where it has one (OBJECTID's THREADID,
6
+ // RFC 8474, or Gmail's X-GM-THRID), else the Message-ID, In-Reply-To and
7
+ // References headers, searched in every folder. The THREAD extension
8
+ // (RFC 5256) is not used: it threads one folder at a time, so it misses Sent.
9
+ import { z } from "zod/v4";
10
+ import { decodeMessageId, errorResult, examine, folderLabel, locateMessage, messageId, READ_ONLY, renderHits, SAFETY_LINE, searchUids, selectableFolders, textResult, uidRanges, withClient, } from "./imap.js";
11
+ // Message-IDs per SEARCH, so a long References chain stays a short command.
12
+ const IDS_PER_SEARCH = 10;
13
+ export const getThreadShape = {
14
+ id: z
15
+ .string()
16
+ .min(1)
17
+ .describe("A message id; every message in its thread is returned."),
18
+ };
19
+ const notFound = (id) => errorResult(`Thread not found for message: ${id}. It may have been deleted, or moved on a server without a stable message id. Find it again with search_emails.`);
20
+ /** The `<…>` message ids in a header value. */
21
+ export const messageIdsIn = (value) => value.match(/<[^<>\s]+>/g) ?? [];
22
+ async function threadKey(client, path, uid) {
23
+ await client.mailboxOpen(path, { readOnly: true });
24
+ // Asks for THREADID only on servers that announce OBJECTID or Gmail's
25
+ // extension; Dovecot may answer THREADID NIL, which comes back undefined.
26
+ const msg = await client.fetchOne(String(uid), { uid: true, threadId: true, envelope: true, headers: ["references"] }, { uid: true });
27
+ if (!msg)
28
+ return undefined;
29
+ if (msg.threadId)
30
+ return { threadId: msg.threadId };
31
+ const ids = new Set([
32
+ ...messageIdsIn(msg.envelope?.messageId ?? ""),
33
+ ...messageIdsIn(msg.envelope?.inReplyTo ?? ""),
34
+ ...messageIdsIn(msg.headers?.toString("utf8") ?? ""),
35
+ ]);
36
+ return { messageIds: [...ids] };
37
+ }
38
+ /**
39
+ * The searches that find the thread in one folder. By header: a message whose
40
+ * Message-ID is one of the ids, or that replies to or references one. Replies
41
+ * carry their ancestors in References, the root included, so one pass finds
42
+ * parents, siblings and descendants.
43
+ */
44
+ function threadSearches(key) {
45
+ if ("threadId" in key)
46
+ return [{ threadId: key.threadId }];
47
+ const searches = [];
48
+ for (let i = 0; i < key.messageIds.length; i += IDS_PER_SEARCH) {
49
+ const or = key.messageIds
50
+ .slice(i, i + IDS_PER_SEARCH)
51
+ .flatMap((id) => [
52
+ { header: { "message-id": id } },
53
+ { header: { "in-reply-to": id } },
54
+ { header: { references: id } },
55
+ ]);
56
+ searches.push({ or });
57
+ }
58
+ return searches;
59
+ }
60
+ async function threadMessages(client, folders, key) {
61
+ const hits = new Map();
62
+ const searches = threadSearches(key);
63
+ if (searches.length === 0)
64
+ return hits;
65
+ for (const folder of folders) {
66
+ // EXAMINE: nothing in a read-only folder changes, \Seen included.
67
+ const opened = await examine(client, folder.path);
68
+ if (!opened || opened.exists === 0)
69
+ continue;
70
+ const uids = new Set();
71
+ for (const search of searches) {
72
+ for (const uid of await searchUids(client, search, folder.path)) {
73
+ uids.add(uid);
74
+ }
75
+ }
76
+ if (uids.size === 0)
77
+ continue;
78
+ for await (const msg of client.fetch(uidRanges([...uids]), { uid: true, internalDate: true }, { uid: true })) {
79
+ const id = messageId(msg, folder.path, opened.uidValidity);
80
+ const hit = hits.get(id);
81
+ if (hit) {
82
+ hit.folders.add(folderLabel(folder));
83
+ continue;
84
+ }
85
+ hits.set(id, {
86
+ id,
87
+ date: msg.internalDate ? new Date(msg.internalDate).getTime() : 0,
88
+ rank: 0,
89
+ folders: new Set([folderLabel(folder)]),
90
+ path: folder.path,
91
+ uid: msg.uid,
92
+ });
93
+ }
94
+ }
95
+ return hits;
96
+ }
97
+ export async function getThread(createClient, id) {
98
+ const ref = decodeMessageId(id);
99
+ if (!ref) {
100
+ return errorResult(`Not a message id: ${id}. Pass an id exactly as search_emails or get_thread printed it.`);
101
+ }
102
+ return withClient(createClient, async (client) => {
103
+ const located = await locateMessage(client, ref);
104
+ if (!located)
105
+ return notFound(id);
106
+ const key = await threadKey(client, located.path, located.uid);
107
+ if (!key)
108
+ return notFound(id);
109
+ const folders = await selectableFolders(client);
110
+ const hits = await threadMessages(client, folders, key);
111
+ // The message asked about is always part of its thread, also when it
112
+ // has no Message-ID to search by.
113
+ if (!hits.has(id)) {
114
+ await client.mailboxOpen(located.path, { readOnly: true });
115
+ const msg = await client.fetchOne(String(located.uid), { uid: true, internalDate: true }, { uid: true });
116
+ hits.set(id, {
117
+ id,
118
+ date: msg && msg.internalDate ? new Date(msg.internalDate).getTime() : 0,
119
+ rank: 0,
120
+ folders: new Set(located.folders),
121
+ path: located.path,
122
+ uid: located.uid,
123
+ });
124
+ }
125
+ const ordered = [...hits.values()].sort((a, b) => a.date - b.date || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
126
+ const lines = await renderHits(client, ordered, { requestedId: id });
127
+ return textResult(`${ordered.length} message(s) in thread:\n\n${lines.join("\n\n")}`);
128
+ });
129
+ }
130
+ export const GET_THREAD_DESCRIPTION = "List every message in the same thread as a given message id, oldest-first, " +
131
+ "with id, subject, sender, date, folders (Inbox, Archive, Sent, Drafts, Junk, Trash, or the name of any other folder), " +
132
+ 'tags, flags (unread, starred; a message without "unread" has been read) and the attachments\' names, types and sizes; ' +
133
+ 'the message asked about is marked "← requested". ' +
134
+ "The thread spans every folder, so the user's own replies in Sent are included. " +
135
+ "It is the server's thread id where the server has one (THREADID, RFC 8474, or Gmail), otherwise every message " +
136
+ "linked to this one by its Message-ID, In-Reply-To and References headers. " +
137
+ "Messages carry no body snippet: use get_email with an id for full bodies and recipients. " +
138
+ "Take the id from search_emails; on servers without a stable message id (OBJECTID or Gmail) ids change when " +
139
+ "a message moves to another folder, so search again if it is not found. " +
140
+ "Listing a thread does not mark its messages read. " +
141
+ SAFETY_LINE;
142
+ export function registerGetThread(createClient, server) {
143
+ server.registerTool("get_thread", {
144
+ title: "Get thread",
145
+ description: GET_THREAD_DESCRIPTION,
146
+ inputSchema: getThreadShape,
147
+ annotations: READ_ONLY,
148
+ }, async ({ id }) => getThread(createClient, id));
149
+ }
@@ -0,0 +1,224 @@
1
+ import { describe, expect, test, vi } from "vitest";
2
+ import { fakeClient } from "./fake-imap.js";
3
+ import { encodeMessageId, READ_ONLY } from "./imap.js";
4
+ import { getThread, messageIdsIn, registerGetThread } from "./get-thread.js";
5
+ // Gmail-like: stable message ids and thread ids, a message in two folders.
6
+ const gmail = () => [
7
+ {
8
+ path: "INBOX",
9
+ messages: [
10
+ {
11
+ uid: 1,
12
+ emailId: "m1",
13
+ threadId: "t1",
14
+ date: "2026-11-01T09:00:00Z",
15
+ subject: "Offsite plan",
16
+ from: "lead@example.com",
17
+ },
18
+ {
19
+ uid: 2,
20
+ emailId: "m3",
21
+ threadId: "t1",
22
+ date: "2026-11-03T09:00:00Z",
23
+ subject: "Re: Offsite plan",
24
+ from: "lead@example.com",
25
+ },
26
+ {
27
+ uid: 3,
28
+ emailId: "m9",
29
+ threadId: "t9",
30
+ date: "2026-11-02T09:00:00Z",
31
+ subject: "Unrelated",
32
+ from: "news@example.org",
33
+ },
34
+ ],
35
+ },
36
+ {
37
+ path: "[Gmail]/Sent Mail",
38
+ specialUse: "\\Sent",
39
+ messages: [
40
+ {
41
+ uid: 7,
42
+ emailId: "m2",
43
+ threadId: "t1",
44
+ date: "2026-11-02T10:00:00Z",
45
+ subject: "Re: Offsite plan",
46
+ from: "me@example.com",
47
+ flags: ["\\Seen"],
48
+ },
49
+ ],
50
+ },
51
+ {
52
+ path: "[Gmail]/All Mail",
53
+ specialUse: "\\All",
54
+ messages: [
55
+ {
56
+ uid: 11,
57
+ emailId: "m1",
58
+ threadId: "t1",
59
+ date: "2026-11-01T09:00:00Z",
60
+ subject: "Offsite plan",
61
+ from: "lead@example.com",
62
+ },
63
+ ],
64
+ },
65
+ ];
66
+ // A plain IMAP server: no stable ids, threads only by headers.
67
+ const plain = () => [
68
+ {
69
+ path: "INBOX",
70
+ uidValidity: 5,
71
+ messages: [
72
+ {
73
+ uid: 1,
74
+ date: "2026-11-01T09:00:00Z",
75
+ subject: "Budget",
76
+ from: "cfo@example.com",
77
+ messageId: "<root@example.com>",
78
+ },
79
+ {
80
+ uid: 2,
81
+ date: "2026-11-03T09:00:00Z",
82
+ subject: "Re: Budget",
83
+ from: "cfo@example.com",
84
+ messageId: "<r2@example.com>",
85
+ inReplyTo: "<r1@example.org>",
86
+ references: "<root@example.com>\r\n <r1@example.org>",
87
+ },
88
+ {
89
+ uid: 3,
90
+ date: "2026-11-02T09:00:00Z",
91
+ subject: "Lunch",
92
+ from: "friend@example.org",
93
+ messageId: "<lunch@example.org>",
94
+ },
95
+ {
96
+ uid: 4,
97
+ date: "2026-11-04T09:00:00Z",
98
+ subject: "No id",
99
+ from: "old@example.org",
100
+ },
101
+ ],
102
+ },
103
+ {
104
+ path: "Sent",
105
+ specialUse: "\\Sent",
106
+ uidValidity: 6,
107
+ messages: [
108
+ {
109
+ uid: 9,
110
+ date: "2026-11-02T10:00:00Z",
111
+ subject: "Re: Budget",
112
+ from: "me@example.org",
113
+ messageId: "<r1@example.org>",
114
+ inReplyTo: "<root@example.com>",
115
+ references: "<root@example.com>",
116
+ flags: ["\\Seen"],
117
+ },
118
+ ],
119
+ },
120
+ ];
121
+ const uidId = (path, uidValidity, uid) => encodeMessageId({ kind: "uid", path, uidValidity, uid });
122
+ describe("get_thread", () => {
123
+ test("registers as a read-only tool named get_thread", () => {
124
+ const server = { registerTool: vi.fn() };
125
+ registerGetThread(fakeClient([]).createClient, server);
126
+ expect(server.registerTool).toHaveBeenCalledWith("get_thread", expect.objectContaining({ annotations: READ_ONLY }), expect.any(Function));
127
+ });
128
+ test("by thread id: the conversation across folders, oldest first, the requested one marked", async () => {
129
+ const { client, createClient } = fakeClient(gmail());
130
+ const result = await getThread(createClient, encodeMessageId({ kind: "stable", emailId: "m3" }));
131
+ const out = result.content[0].text;
132
+ expect(result.isError).toBeUndefined();
133
+ expect(out).toMatch(/^3 message\(s\) in thread:\n\n1\. Offsite plan\n/);
134
+ expect(out).toContain(" id: e.m1\n");
135
+ expect(out).toContain(" folders: Inbox, [Gmail]/All Mail\n");
136
+ expect(out).toMatch(/2\. Re: Offsite plan\n {3}id: e\.m2\n {3}from: me@example\.com\n {3}date: 2026-11-02T10:00:00Z\n {3}folders: Sent\n\n/);
137
+ expect(out).toContain("3. Re: Offsite plan ← requested\n id: e.m3");
138
+ expect(out).not.toContain("Unrelated");
139
+ // Opened read-only, so \Seen never changes
140
+ expect(client.mailboxOpen.mock.calls.every((c) => c[1]?.readOnly === true)).toBe(true);
141
+ });
142
+ test("by headers: replies in Sent and later replies, not other mail", async () => {
143
+ const { client, createClient } = fakeClient(plain());
144
+ const root = uidId("INBOX", "5", 1);
145
+ const out = (await getThread(createClient, root)).content[0].text;
146
+ expect(out).toBe([
147
+ "3 message(s) in thread:",
148
+ "",
149
+ "1. Budget ← requested",
150
+ ` id: ${root}`,
151
+ " from: cfo@example.com",
152
+ " date: 2026-11-01T09:00:00Z",
153
+ " folders: Inbox",
154
+ " flags: unread",
155
+ "",
156
+ "2. Re: Budget",
157
+ ` id: ${uidId("Sent", "6", 9)}`,
158
+ " from: me@example.org",
159
+ " date: 2026-11-02T10:00:00Z",
160
+ " folders: Sent",
161
+ "",
162
+ "3. Re: Budget",
163
+ ` id: ${uidId("INBOX", "5", 2)}`,
164
+ " from: cfo@example.com",
165
+ " date: 2026-11-03T09:00:00Z",
166
+ " folders: Inbox",
167
+ " flags: unread",
168
+ ].join("\n"));
169
+ expect(out).not.toContain("Lunch");
170
+ expect(out).not.toContain("No id");
171
+ expect(client.mailboxOpen.mock.calls.every((c) => c[1]?.readOnly === true)).toBe(true);
172
+ });
173
+ test("by headers from the middle of a thread: parent and child found", async () => {
174
+ const { createClient } = fakeClient(plain());
175
+ const out = (await getThread(createClient, uidId("Sent", "6", 9)))
176
+ .content[0].text;
177
+ expect(out).toMatch(/^3 message\(s\) in thread:/);
178
+ expect(out).toContain("2. Re: Budget ← requested");
179
+ });
180
+ test("by headers from the newest reply: its References find the root, In-Reply-To a later reply", async () => {
181
+ const withLater = plain();
182
+ // A client that sets In-Reply-To but no References.
183
+ withLater[0].messages.push({
184
+ uid: 5,
185
+ date: "2026-11-05T09:00:00Z",
186
+ subject: "Re: Re: Budget",
187
+ from: "me@example.org",
188
+ messageId: "<r3@example.org>",
189
+ inReplyTo: "<r2@example.com>",
190
+ });
191
+ const { createClient } = fakeClient(withLater);
192
+ const out = (await getThread(createClient, uidId("INBOX", "5", 2)))
193
+ .content[0].text;
194
+ const subjects = [...out.matchAll(/^\d+\. (.*)$/gm)].map((m) => m[1]);
195
+ expect(subjects).toEqual([
196
+ "Budget",
197
+ "Re: Budget",
198
+ "Re: Budget ← requested",
199
+ "Re: Re: Budget",
200
+ ]);
201
+ });
202
+ test("a message without a Message-ID is a thread of one", async () => {
203
+ const { createClient } = fakeClient(plain());
204
+ const out = (await getThread(createClient, uidId("INBOX", "5", 4)))
205
+ .content[0].text;
206
+ expect(out).toMatch(/^1 message\(s\) in thread:\n\n1\. No id {2}← requested\n/);
207
+ });
208
+ test("an unknown or malformed id is an error", async () => {
209
+ const { createClient } = fakeClient(gmail());
210
+ const missing = await getThread(createClient, encodeMessageId({ kind: "stable", emailId: "nope" }));
211
+ expect(missing.isError).toBe(true);
212
+ expect(missing.content[0].text).toContain("Thread not found for message");
213
+ const bad = await getThread(createClient, "garbage");
214
+ expect(bad.isError).toBe(true);
215
+ expect(bad.content[0].text).toContain("Not a message id");
216
+ });
217
+ test("reads message ids out of a folded header", () => {
218
+ expect(messageIdsIn("<a@example.com>\r\n <b@example.org> junk")).toEqual([
219
+ "<a@example.com>",
220
+ "<b@example.org>",
221
+ ]);
222
+ expect(messageIdsIn("")).toEqual([]);
223
+ });
224
+ });