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
|
@@ -1,91 +1,62 @@
|
|
|
1
1
|
import { z } from "zod/v4";
|
|
2
|
-
|
|
2
|
+
import { errorMessage, withClient } from "./imap.js";
|
|
3
|
+
/** Folders tried in order when the server marks none as `\Drafts`. */
|
|
4
|
+
const FALLBACK_DRAFTS_FOLDERS = ["INBOX.Drafts", "Drafts"];
|
|
5
|
+
export function registerCreateDraft(createClient, server) {
|
|
3
6
|
server.tool("create_draft", "Creates a draft email message", {
|
|
4
7
|
to: z.string(),
|
|
5
8
|
subject: z.string(),
|
|
6
9
|
body: z.string(),
|
|
7
10
|
from: z.string().optional(),
|
|
8
|
-
}, async ({ to, subject, body, from }) => {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
createDraftMessage();
|
|
35
|
-
});
|
|
36
|
-
return;
|
|
37
|
-
}
|
|
38
|
-
createDraftMessage();
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
function createDraftMessage() {
|
|
42
|
-
const message = [
|
|
43
|
-
`From: ${from || process.env.IMAP_USERNAME || ""}`,
|
|
44
|
-
`To: ${to}`,
|
|
45
|
-
`Subject: ${subject}`,
|
|
46
|
-
"",
|
|
47
|
-
body,
|
|
48
|
-
].join("\r\n");
|
|
49
|
-
client.append(message, { flags: ["\\Draft"] }, (err) => {
|
|
50
|
-
if (err) {
|
|
51
|
-
reject(new Error(`Failed to create draft: ${err.message}`));
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
resolve({
|
|
55
|
-
content: [
|
|
56
|
-
{
|
|
57
|
-
type: "text",
|
|
58
|
-
text: `Draft created successfully for ${to}`,
|
|
59
|
-
},
|
|
60
|
-
],
|
|
61
|
-
});
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
|
-
client.once("error", (err) => {
|
|
66
|
-
reject(new Error(`IMAP connection error: ${err.message}`));
|
|
67
|
-
});
|
|
68
|
-
client.connect();
|
|
69
|
-
});
|
|
70
|
-
});
|
|
11
|
+
}, async ({ to, subject, body, from }) => withClient(createClient, async (client) => {
|
|
12
|
+
const draftsPath = await openDraftsFolder(client);
|
|
13
|
+
const message = [
|
|
14
|
+
`From: ${from || process.env.IMAP_USERNAME || ""}`,
|
|
15
|
+
`To: ${to}`,
|
|
16
|
+
`Subject: ${subject}`,
|
|
17
|
+
"",
|
|
18
|
+
body,
|
|
19
|
+
].join("\r\n");
|
|
20
|
+
try {
|
|
21
|
+
await client.append(draftsPath, message, ["\\Draft"]);
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
throw new Error(`Failed to create draft: ${errorMessage(err)}`);
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
content: [
|
|
28
|
+
{
|
|
29
|
+
type: "text",
|
|
30
|
+
text: `Draft created successfully for ${to}`,
|
|
31
|
+
},
|
|
32
|
+
],
|
|
33
|
+
};
|
|
34
|
+
}));
|
|
71
35
|
}
|
|
72
36
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
37
|
+
* Opens the folder marked `\Drafts`, or else the first fallback folder that
|
|
38
|
+
* exists, and returns its path.
|
|
75
39
|
*/
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
40
|
+
async function openDraftsFolder(client) {
|
|
41
|
+
const folders = await client.list().catch(() => []);
|
|
42
|
+
const marked = findDraftsFolder(folders);
|
|
43
|
+
const candidates = marked ? [marked] : FALLBACK_DRAFTS_FOLDERS;
|
|
44
|
+
let lastError;
|
|
45
|
+
for (const path of candidates) {
|
|
46
|
+
try {
|
|
47
|
+
await client.mailboxOpen(path);
|
|
48
|
+
return path;
|
|
83
49
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if (found)
|
|
87
|
-
return found;
|
|
50
|
+
catch (err) {
|
|
51
|
+
lastError = err;
|
|
88
52
|
}
|
|
89
53
|
}
|
|
90
|
-
|
|
54
|
+
throw new Error(`Failed to open drafts folder: ${errorMessage(lastError)}`);
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Returns the path of the folder the server marks with the `\Drafts`
|
|
58
|
+
* special-use attribute (RFC 6154), or undefined if none is marked.
|
|
59
|
+
*/
|
|
60
|
+
export function findDraftsFolder(folders) {
|
|
61
|
+
return folders.find((folder) => [...folder.flags].some((flag) => flag.toLowerCase() === "\\drafts"))?.path;
|
|
91
62
|
}
|
|
@@ -1,32 +1,38 @@
|
|
|
1
1
|
import { describe, expect, test, vi } from "vitest";
|
|
2
2
|
import { registerCreateDraft } from "./create-draft.js";
|
|
3
|
-
function
|
|
3
|
+
function folder(path, flags) {
|
|
4
|
+
const segments = path.split("/");
|
|
4
5
|
return {
|
|
5
|
-
|
|
6
|
+
path,
|
|
7
|
+
pathAsListed: path,
|
|
8
|
+
name: segments[segments.length - 1],
|
|
6
9
|
delimiter: "/",
|
|
7
|
-
|
|
8
|
-
|
|
10
|
+
parent: segments.slice(0, -1),
|
|
11
|
+
parentPath: segments.slice(0, -1).join("/"),
|
|
12
|
+
flags: new Set(flags),
|
|
13
|
+
listed: true,
|
|
14
|
+
subscribed: true,
|
|
9
15
|
};
|
|
10
16
|
}
|
|
11
|
-
function setup(
|
|
12
|
-
const listeners = {};
|
|
17
|
+
function setup(folders, existing, { connectError } = {}) {
|
|
13
18
|
let openedBox;
|
|
14
19
|
const client = {
|
|
15
|
-
|
|
16
|
-
|
|
20
|
+
on: vi.fn(),
|
|
21
|
+
connect: vi.fn(async () => {
|
|
22
|
+
if (connectError)
|
|
23
|
+
throw connectError;
|
|
17
24
|
}),
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
openedBox = name;
|
|
23
|
-
cb(null);
|
|
24
|
-
}
|
|
25
|
-
else {
|
|
26
|
-
cb(new Error(`Mailbox doesn't exist: ${name}`));
|
|
25
|
+
list: vi.fn(async () => folders),
|
|
26
|
+
mailboxOpen: vi.fn(async (path) => {
|
|
27
|
+
if (!existing.includes(path)) {
|
|
28
|
+
throw new Error(`Mailbox doesn't exist: ${path}`);
|
|
27
29
|
}
|
|
30
|
+
openedBox = path;
|
|
31
|
+
return { path };
|
|
28
32
|
}),
|
|
29
|
-
append: vi.fn((
|
|
33
|
+
append: vi.fn(async () => ({ destination: openedBox })),
|
|
34
|
+
logout: vi.fn(async () => { }),
|
|
35
|
+
close: vi.fn(),
|
|
30
36
|
};
|
|
31
37
|
let handler;
|
|
32
38
|
const server = {
|
|
@@ -34,33 +40,33 @@ function setup(boxes, existing) {
|
|
|
34
40
|
handler = args[args.length - 1];
|
|
35
41
|
}),
|
|
36
42
|
};
|
|
37
|
-
registerCreateDraft(client, server);
|
|
43
|
+
registerCreateDraft(() => client, server);
|
|
38
44
|
const run = () => handler({ to: "jane@example.com", subject: "Hi", body: "Hello" });
|
|
39
45
|
return { client, server, run, openedBox: () => openedBox };
|
|
40
46
|
}
|
|
41
47
|
describe("create_draft", () => {
|
|
42
48
|
test("registers the tool as create_draft", () => {
|
|
43
|
-
const { server } = setup(
|
|
49
|
+
const { server } = setup([folder("Drafts", ["\\Drafts"])], ["Drafts"]);
|
|
44
50
|
expect(server.tool).toHaveBeenCalledWith("create_draft", expect.any(String), expect.any(Object), expect.any(Function));
|
|
45
51
|
});
|
|
46
52
|
test("saves to the folder marked \\Drafts, whatever its name and nesting", async () => {
|
|
47
|
-
const { client, run, openedBox } = setup(
|
|
48
|
-
INBOX
|
|
49
|
-
"[Gmail]"
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}, ["[Gmail]/Entwürfe", "Drafts"]);
|
|
53
|
+
const { client, run, openedBox } = setup([
|
|
54
|
+
folder("INBOX", ["\\HasNoChildren"]),
|
|
55
|
+
folder("[Gmail]", ["\\Noselect", "\\HasChildren"]),
|
|
56
|
+
folder("[Gmail]/All Mail", ["\\All"]),
|
|
57
|
+
folder("[Gmail]/Entwürfe", ["\\HasNoChildren", "\\Drafts"]),
|
|
58
|
+
folder("Drafts", []),
|
|
59
|
+
], ["[Gmail]/Entwürfe", "Drafts"]);
|
|
55
60
|
const result = await run();
|
|
56
61
|
expect(openedBox()).toBe("[Gmail]/Entwürfe");
|
|
57
|
-
expect(client.append).
|
|
62
|
+
expect(client.append).toHaveBeenCalledExactlyOnceWith("[Gmail]/Entwürfe", "From: \r\nTo: jane@example.com\r\nSubject: Hi\r\n\r\nHello", ["\\Draft"]);
|
|
58
63
|
expect(result.content[0].text).toBe("Draft created successfully for jane@example.com");
|
|
64
|
+
expect(client.logout).toHaveBeenCalledOnce();
|
|
59
65
|
});
|
|
60
66
|
test("falls back to INBOX.Drafts or Drafts when no folder is marked \\Drafts", async () => {
|
|
61
|
-
const { client, run, openedBox } = setup(
|
|
67
|
+
const { client, run, openedBox } = setup([folder("INBOX", []), folder("Drafts", [])], ["Drafts"]);
|
|
62
68
|
await run();
|
|
63
|
-
expect(client.
|
|
69
|
+
expect(client.mailboxOpen.mock.calls.map((c) => c[0])).toEqual([
|
|
64
70
|
"INBOX.Drafts",
|
|
65
71
|
"Drafts",
|
|
66
72
|
]);
|
|
@@ -68,8 +74,19 @@ describe("create_draft", () => {
|
|
|
68
74
|
expect(client.append).toHaveBeenCalledOnce();
|
|
69
75
|
});
|
|
70
76
|
test("fails when no drafts folder can be opened", async () => {
|
|
71
|
-
const { client, run } = setup(
|
|
77
|
+
const { client, run } = setup([folder("INBOX", [])], []);
|
|
72
78
|
await expect(run()).rejects.toThrow("Failed to open drafts folder");
|
|
73
79
|
expect(client.append).not.toHaveBeenCalled();
|
|
80
|
+
expect(client.logout).toHaveBeenCalledOnce();
|
|
81
|
+
});
|
|
82
|
+
test("reports a connection or login failure as a tool error", async () => {
|
|
83
|
+
// imapflow's shape for a server's NO: a generic message, the reason apart
|
|
84
|
+
const connectError = Object.assign(new Error("Command failed"), {
|
|
85
|
+
responseText: "[AUTHENTICATIONFAILED] Invalid credentials",
|
|
86
|
+
});
|
|
87
|
+
const { client, run } = setup([], [], { connectError });
|
|
88
|
+
await expect(run()).rejects.toThrow("IMAP connection error: [AUTHENTICATIONFAILED] Invalid credentials");
|
|
89
|
+
expect(client.on).toHaveBeenCalledWith("error", expect.any(Function));
|
|
90
|
+
expect(client.list).not.toHaveBeenCalled();
|
|
74
91
|
});
|
|
75
92
|
});
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// An in-memory stand-in for ImapFlow, for the read tools' tests: folders
|
|
2
|
+
// holding messages, and the SEARCH and FETCH subset those tools use.
|
|
3
|
+
import { vi } from "vitest";
|
|
4
|
+
const DAY = (d) => new Date(d).toISOString().slice(0, 10);
|
|
5
|
+
function matches(m, q) {
|
|
6
|
+
const flags = new Set(m.flags ?? []);
|
|
7
|
+
if (q.seen !== undefined && flags.has("\\Seen") !== q.seen)
|
|
8
|
+
return false;
|
|
9
|
+
if (q.flagged !== undefined && flags.has("\\Flagged") !== q.flagged)
|
|
10
|
+
return false;
|
|
11
|
+
if (q.keyword && !flags.has(q.keyword))
|
|
12
|
+
return false;
|
|
13
|
+
if (q.unKeyword && flags.has(q.unKeyword))
|
|
14
|
+
return false;
|
|
15
|
+
if (q.from && !m.from.toLowerCase().includes(q.from.toLowerCase()))
|
|
16
|
+
return false;
|
|
17
|
+
if (q.emailId && m.emailId !== q.emailId)
|
|
18
|
+
return false;
|
|
19
|
+
if (q.since && DAY(m.date) < DAY(q.since))
|
|
20
|
+
return false;
|
|
21
|
+
if (q.before && DAY(m.date) >= DAY(q.before))
|
|
22
|
+
return false;
|
|
23
|
+
if (q.text) {
|
|
24
|
+
const haystack = `${m.subject} ${m.from} ${m.text ?? ""}`.toLowerCase();
|
|
25
|
+
if (!haystack.includes(q.text.toLowerCase()))
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
/** "1:3,7" as [1, 2, 3, 7]. */
|
|
31
|
+
function parseRanges(range) {
|
|
32
|
+
return range.split(",").flatMap((r) => {
|
|
33
|
+
const [a, b = a] = r.split(":").map(Number);
|
|
34
|
+
return Array.from({ length: b - a + 1 }, (_, i) => a + i);
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
export function fakeClient(folders) {
|
|
38
|
+
let open;
|
|
39
|
+
const find = (uid) => open?.messages.find((m) => m.uid === uid);
|
|
40
|
+
const toFetched = (m) => ({
|
|
41
|
+
seq: m.uid,
|
|
42
|
+
uid: m.uid,
|
|
43
|
+
emailId: m.emailId,
|
|
44
|
+
internalDate: new Date(m.date),
|
|
45
|
+
flags: new Set(m.flags ?? []),
|
|
46
|
+
size: m.size ?? (m.source ?? "").length,
|
|
47
|
+
envelope: {
|
|
48
|
+
subject: m.subject,
|
|
49
|
+
from: [{ name: "", address: m.from }],
|
|
50
|
+
to: m.to ? [{ name: "", address: m.to }] : [],
|
|
51
|
+
},
|
|
52
|
+
bodyStructure: m.bodyStructure ?? { type: "text/plain", part: "1" },
|
|
53
|
+
source: m.source === undefined ? undefined : Buffer.from(m.source),
|
|
54
|
+
});
|
|
55
|
+
const client = {
|
|
56
|
+
on: vi.fn(),
|
|
57
|
+
connect: vi.fn(async () => { }),
|
|
58
|
+
logout: vi.fn(async () => { }),
|
|
59
|
+
close: vi.fn(),
|
|
60
|
+
list: vi.fn(async () => folders.map((f) => {
|
|
61
|
+
const segments = f.path.split("/");
|
|
62
|
+
return {
|
|
63
|
+
path: f.path,
|
|
64
|
+
pathAsListed: f.path,
|
|
65
|
+
name: segments[segments.length - 1],
|
|
66
|
+
delimiter: "/",
|
|
67
|
+
parent: segments.slice(0, -1),
|
|
68
|
+
parentPath: segments.slice(0, -1).join("/"),
|
|
69
|
+
flags: new Set(f.flags ?? []),
|
|
70
|
+
specialUse: f.specialUse,
|
|
71
|
+
listed: true,
|
|
72
|
+
subscribed: true,
|
|
73
|
+
};
|
|
74
|
+
})),
|
|
75
|
+
mailboxOpen: vi.fn(async (path, opts) => {
|
|
76
|
+
open = folders.find((f) => f.path === path);
|
|
77
|
+
if (!open)
|
|
78
|
+
throw new Error(`Mailbox doesn't exist: ${path}`);
|
|
79
|
+
return {
|
|
80
|
+
path,
|
|
81
|
+
readOnly: opts?.readOnly,
|
|
82
|
+
uidValidity: BigInt(open.uidValidity ?? 1),
|
|
83
|
+
exists: open.messages.length,
|
|
84
|
+
};
|
|
85
|
+
}),
|
|
86
|
+
search: vi.fn(async (q) => (open?.messages ?? []).filter((m) => matches(m, q)).map((m) => m.uid)),
|
|
87
|
+
fetch: vi.fn(async function* (range) {
|
|
88
|
+
for (const uid of parseRanges(range)) {
|
|
89
|
+
const m = find(uid);
|
|
90
|
+
if (m)
|
|
91
|
+
yield toFetched(m);
|
|
92
|
+
}
|
|
93
|
+
}),
|
|
94
|
+
fetchOne: vi.fn(async (uid, query) => {
|
|
95
|
+
void query;
|
|
96
|
+
const m = find(Number(uid));
|
|
97
|
+
return m ? toFetched(m) : false;
|
|
98
|
+
}),
|
|
99
|
+
download: vi.fn(async (uid) => {
|
|
100
|
+
const m = find(Number(uid));
|
|
101
|
+
if (!m)
|
|
102
|
+
return {};
|
|
103
|
+
return {
|
|
104
|
+
meta: {},
|
|
105
|
+
content: (async function* () {
|
|
106
|
+
yield Buffer.from(m.text ?? "");
|
|
107
|
+
})(),
|
|
108
|
+
};
|
|
109
|
+
}),
|
|
110
|
+
};
|
|
111
|
+
return { client, createClient: () => client };
|
|
112
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
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, examine, searchUids, errorResult, folderLabel, formatAddresses, formatAttachmentLine, formatDate, messageTags, READ_ONLY, SAFETY_LINE, selectableFolders, sortFolderLabels, 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."),
|
|
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
|
+
async function locate(client, ref) {
|
|
22
|
+
const folders = await selectableFolders(client);
|
|
23
|
+
if (ref.kind === "uid") {
|
|
24
|
+
const folder = folders.find((f) => f.path === ref.path);
|
|
25
|
+
if (!folder)
|
|
26
|
+
return undefined;
|
|
27
|
+
const opened = await client.mailboxOpen(ref.path, { readOnly: true });
|
|
28
|
+
if (opened.uidValidity.toString() !== ref.uidValidity)
|
|
29
|
+
return undefined;
|
|
30
|
+
return { path: ref.path, uid: ref.uid, folders: [folderLabel(folder)] };
|
|
31
|
+
}
|
|
32
|
+
// A stable id: every folder holding it, since one message can be in
|
|
33
|
+
// several (Gmail labels).
|
|
34
|
+
let first;
|
|
35
|
+
const labels = [];
|
|
36
|
+
for (const folder of folders) {
|
|
37
|
+
const opened = await examine(client, folder.path);
|
|
38
|
+
if (!opened || opened.exists === 0)
|
|
39
|
+
continue;
|
|
40
|
+
const uids = await searchUids(client, { emailId: ref.emailId }, folder.path);
|
|
41
|
+
if (uids.length === 0)
|
|
42
|
+
continue;
|
|
43
|
+
first ??= { folder, uid: uids[0] };
|
|
44
|
+
labels.push(folderLabel(folder));
|
|
45
|
+
}
|
|
46
|
+
if (!first)
|
|
47
|
+
return undefined;
|
|
48
|
+
return {
|
|
49
|
+
path: first.folder.path,
|
|
50
|
+
uid: first.uid,
|
|
51
|
+
folders: sortFolderLabels(labels),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** The whole message through langmail, or null when that path is unavailable. */
|
|
55
|
+
function cleanedBody(source) {
|
|
56
|
+
if (!source)
|
|
57
|
+
return null;
|
|
58
|
+
try {
|
|
59
|
+
const processed = langmail.preprocessWithOptions(source, {
|
|
60
|
+
maxBodyLength: MAX_BODY_CHARS,
|
|
61
|
+
// The agent opened this message, so nothing is silently dropped.
|
|
62
|
+
stripQuotes: false,
|
|
63
|
+
stripSignature: false,
|
|
64
|
+
});
|
|
65
|
+
return processed.body.trim() || null;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** The first text/plain part, for messages too large for the raw path. */
|
|
72
|
+
async function plainTextBody(client, msg) {
|
|
73
|
+
const find = (node = msg.bodyStructure) => {
|
|
74
|
+
if (!node)
|
|
75
|
+
return undefined;
|
|
76
|
+
// Not into a forwarded message: its text is not this message's body.
|
|
77
|
+
if (node.type.toLowerCase() === "message/rfc822")
|
|
78
|
+
return undefined;
|
|
79
|
+
if (node.childNodes?.length) {
|
|
80
|
+
for (const child of node.childNodes) {
|
|
81
|
+
const part = find(child);
|
|
82
|
+
if (part)
|
|
83
|
+
return part;
|
|
84
|
+
}
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
return node.type.toLowerCase() === "text/plain" &&
|
|
88
|
+
node.disposition?.toLowerCase() !== "attachment"
|
|
89
|
+
? (node.part ?? "1")
|
|
90
|
+
: undefined;
|
|
91
|
+
};
|
|
92
|
+
const part = find();
|
|
93
|
+
if (!part)
|
|
94
|
+
return null;
|
|
95
|
+
const { content } = await client.download(String(msg.uid), part, {
|
|
96
|
+
uid: true,
|
|
97
|
+
maxBytes: MAX_BODY_CHARS,
|
|
98
|
+
});
|
|
99
|
+
if (!content)
|
|
100
|
+
return null;
|
|
101
|
+
const chunks = [];
|
|
102
|
+
for await (const chunk of content)
|
|
103
|
+
chunks.push(Buffer.from(chunk));
|
|
104
|
+
return Buffer.concat(chunks).toString("utf8").trim() || null;
|
|
105
|
+
}
|
|
106
|
+
export async function getEmail(createClient, id) {
|
|
107
|
+
const ref = decodeMessageId(id);
|
|
108
|
+
if (!ref) {
|
|
109
|
+
return errorResult(`Not a message id: ${id}. Pass an id exactly as search_emails printed it.`);
|
|
110
|
+
}
|
|
111
|
+
return withClient(createClient, async (client) => {
|
|
112
|
+
const located = await locate(client, ref);
|
|
113
|
+
if (!located)
|
|
114
|
+
return notFound(id);
|
|
115
|
+
await client.mailboxOpen(located.path, { readOnly: true });
|
|
116
|
+
const msg = await client.fetchOne(String(located.uid), {
|
|
117
|
+
uid: true,
|
|
118
|
+
envelope: true,
|
|
119
|
+
flags: true,
|
|
120
|
+
internalDate: true,
|
|
121
|
+
size: true,
|
|
122
|
+
bodyStructure: true,
|
|
123
|
+
}, { uid: true });
|
|
124
|
+
if (!msg)
|
|
125
|
+
return notFound(id);
|
|
126
|
+
const { envelope } = msg;
|
|
127
|
+
const header = [
|
|
128
|
+
`Subject: ${envelope?.subject || "(no subject)"}`,
|
|
129
|
+
`From: ${formatAddresses(envelope?.from) || "(unknown sender)"}`,
|
|
130
|
+
`To: ${formatAddresses(envelope?.to) || "(none)"}`,
|
|
131
|
+
];
|
|
132
|
+
const cc = formatAddresses(envelope?.cc);
|
|
133
|
+
if (cc)
|
|
134
|
+
header.push(`Cc: ${cc}`);
|
|
135
|
+
header.push(`Date: ${formatDate(msg.internalDate)}`);
|
|
136
|
+
header.push(`Folders: ${located.folders.join(", ")}`);
|
|
137
|
+
const tags = messageTags(msg.flags);
|
|
138
|
+
if (tags.length > 0)
|
|
139
|
+
header.push(`Tags: ${tags.join(", ")}`);
|
|
140
|
+
let body = null;
|
|
141
|
+
if (msg.size !== undefined && msg.size <= MAX_RAW_MESSAGE_BYTES) {
|
|
142
|
+
// BODY.PEEK[] in a folder opened read-only: \Seen stays as it was.
|
|
143
|
+
const raw = await client.fetchOne(String(located.uid), { source: true }, { uid: true });
|
|
144
|
+
body = cleanedBody(raw ? raw.source : undefined);
|
|
145
|
+
}
|
|
146
|
+
body ??= await plainTextBody(client, msg);
|
|
147
|
+
const attachments = attachmentsOf(msg.bodyStructure);
|
|
148
|
+
const attachmentSection = attachments.length > 0
|
|
149
|
+
? `\n\nAttachments (${attachments.length}):\n${attachments.map((a, i) => formatAttachmentLine(i + 1, a)).join("\n")}`
|
|
150
|
+
: "";
|
|
151
|
+
return textResult(`${header.join("\n")}\n\n${body ?? "(no text body)"}${attachmentSection}`);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
export const GET_EMAIL_DESCRIPTION = "Fetch a single message's recipients, folders and body by id. The body is " +
|
|
155
|
+
"rendered as readable text/markdown regardless of how the sender " +
|
|
156
|
+
"formatted it (HTML newsletters and invoices come back as clean " +
|
|
157
|
+
"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; on servers without a stable " +
|
|
158
|
+
"message id (OBJECTID or Gmail) the id changes when the message moves to another folder, so " +
|
|
159
|
+
"search again if it is not found. Attachments are listed after the body with filename, media type " +
|
|
160
|
+
'and size; parts marked "inline" are images referenced by the HTML body (logos, ' +
|
|
161
|
+
"signatures) rather than genuine documents. Attachment contents are never returned here. " +
|
|
162
|
+
"This tool never shows bcc. Fetching a message does not mark it read. " +
|
|
163
|
+
SAFETY_LINE;
|
|
164
|
+
export function registerGetEmail(createClient, server) {
|
|
165
|
+
server.registerTool("get_email", {
|
|
166
|
+
title: "Get email",
|
|
167
|
+
description: GET_EMAIL_DESCRIPTION,
|
|
168
|
+
inputSchema: getEmailShape,
|
|
169
|
+
annotations: READ_ONLY,
|
|
170
|
+
}, async ({ id }) => getEmail(createClient, id));
|
|
171
|
+
}
|