langmail-mcp 0.1.0 → 0.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.
Files changed (137) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +89 -169
  3. package/dist/chunk-0fxfqny0.js +12642 -0
  4. package/dist/langmail-mcp.js +7 -0
  5. package/package.json +93 -98
  6. package/THIRD_PARTY_NOTICES.md +0 -388
  7. package/dist/attachments/download.js +0 -69
  8. package/dist/attachments/routes.js +0 -42
  9. package/dist/attachments/tickets.js +0 -45
  10. package/dist/attachments/upload-tickets.js +0 -43
  11. package/dist/attachments/upload.js +0 -136
  12. package/dist/caldav/account-settings.js +0 -92
  13. package/dist/caldav/agenda.js +0 -277
  14. package/dist/caldav/alarm.js +0 -97
  15. package/dist/caldav/client.js +0 -408
  16. package/dist/caldav/ical.js +0 -248
  17. package/dist/caldav/occurrence.js +0 -534
  18. package/dist/caldav/recurrence.js +0 -313
  19. package/dist/caldav/rsvp.js +0 -107
  20. package/dist/caldav/scheduling-handover.js +0 -22
  21. package/dist/caldav/timezone.js +0 -103
  22. package/dist/caldav/types.js +0 -5
  23. package/dist/config.js +0 -219
  24. package/dist/contacts/address-class.js +0 -79
  25. package/dist/contacts/birthdays.js +0 -81
  26. package/dist/contacts/card.js +0 -58
  27. package/dist/contacts/constants.js +0 -46
  28. package/dist/contacts/fold.js +0 -309
  29. package/dist/contacts/index.js +0 -10
  30. package/dist/contacts/merge.js +0 -388
  31. package/dist/contacts/observations.js +0 -115
  32. package/dist/contacts/profile.js +0 -402
  33. package/dist/contacts/scoring.js +0 -146
  34. package/dist/contacts/types.js +0 -7
  35. package/dist/contacts/upsert.js +0 -131
  36. package/dist/drafts/attachments.js +0 -254
  37. package/dist/drafts/idempotency.js +0 -60
  38. package/dist/drafts/send-guard.js +0 -184
  39. package/dist/email-render/email-viewer.html +0 -143
  40. package/dist/email-render/image-proxy.js +0 -389
  41. package/dist/email-render/meta.js +0 -48
  42. package/dist/email-render/sanitize.js +0 -93
  43. package/dist/email-render/viewer-resource.js +0 -104
  44. package/dist/http/bearer.js +0 -30
  45. package/dist/http/guard.js +0 -57
  46. package/dist/http/hosts.js +0 -10
  47. package/dist/http/listener.js +0 -170
  48. package/dist/http/routes.js +0 -72
  49. package/dist/ical/ical-parse.js +0 -357
  50. package/dist/ical/index.js +0 -4
  51. package/dist/ical/timezone.js +0 -22
  52. package/dist/ical/windows-zones.js +0 -155
  53. package/dist/index.js +0 -79
  54. package/dist/jmap/blob.js +0 -49
  55. package/dist/jmap/contacts.js +0 -226
  56. package/dist/jmap/drafts.js +0 -480
  57. package/dist/jmap/email.js +0 -668
  58. package/dist/jmap/index.js +0 -12
  59. package/dist/jmap/keywords.js +0 -22
  60. package/dist/jmap/live.js +0 -21
  61. package/dist/jmap/origin.js +0 -113
  62. package/dist/jmap/patch.js +0 -29
  63. package/dist/jmap/request.js +0 -37
  64. package/dist/jmap/session.js +0 -89
  65. package/dist/jmap/sieve.js +0 -71
  66. package/dist/jmap/submission.js +0 -107
  67. package/dist/jmap/timeout.js +0 -30
  68. package/dist/jmap/types.js +0 -6
  69. package/dist/logger.js +0 -48
  70. package/dist/mcp/handler.js +0 -255
  71. package/dist/mcp/http.js +0 -29
  72. package/dist/mcp/instructions.js +0 -44
  73. package/dist/mcp/links.js +0 -64
  74. package/dist/mcp/tool-logging.js +0 -67
  75. package/dist/observability/errors.js +0 -41
  76. package/dist/rules/apply.js +0 -236
  77. package/dist/rules/rule.js +0 -280
  78. package/dist/rules/store.js +0 -92
  79. package/dist/tools/annotations.js +0 -71
  80. package/dist/tools/archive-emails.js +0 -40
  81. package/dist/tools/calendar-lookup.js +0 -64
  82. package/dist/tools/contact-common.js +0 -146
  83. package/dist/tools/contact-format.js +0 -72
  84. package/dist/tools/contact-write-through.js +0 -37
  85. package/dist/tools/create-calendar-event.js +0 -231
  86. package/dist/tools/create-calendar.js +0 -54
  87. package/dist/tools/create-contact.js +0 -172
  88. package/dist/tools/create-draft.js +0 -369
  89. package/dist/tools/create-mail-rule.js +0 -101
  90. package/dist/tools/delete-calendar-event.js +0 -165
  91. package/dist/tools/delete-contact.js +0 -60
  92. package/dist/tools/delete-draft.js +0 -129
  93. package/dist/tools/delete-mail-rule.js +0 -38
  94. package/dist/tools/download-attachment.js +0 -90
  95. package/dist/tools/download-email.js +0 -112
  96. package/dist/tools/draft-common.js +0 -600
  97. package/dist/tools/email-types.js +0 -58
  98. package/dist/tools/error-detail.js +0 -10
  99. package/dist/tools/file-emails-common.js +0 -75
  100. package/dist/tools/format.js +0 -131
  101. package/dist/tools/forward-message.js +0 -237
  102. package/dist/tools/forward-quote.js +0 -179
  103. package/dist/tools/get-draft.js +0 -61
  104. package/dist/tools/get-email.js +0 -164
  105. package/dist/tools/get-thread.js +0 -67
  106. package/dist/tools/keywords.js +0 -43
  107. package/dist/tools/list-calendar-events.js +0 -180
  108. package/dist/tools/list-calendars.js +0 -44
  109. package/dist/tools/list-drafts.js +0 -134
  110. package/dist/tools/list-mail-rules.js +0 -28
  111. package/dist/tools/list-unsubscribe.js +0 -152
  112. package/dist/tools/list-upcoming-birthdays.js +0 -165
  113. package/dist/tools/mail-rule-common.js +0 -43
  114. package/dist/tools/mail-rule-format.js +0 -79
  115. package/dist/tools/mailbox-lookup.js +0 -13
  116. package/dist/tools/mark-emails.js +0 -78
  117. package/dist/tools/merge-contacts.js +0 -145
  118. package/dist/tools/move-calendar-events.js +0 -340
  119. package/dist/tools/move-emails.js +0 -64
  120. package/dist/tools/one-click-post.js +0 -275
  121. package/dist/tools/preview-email.js +0 -204
  122. package/dist/tools/preview-mail-rule.js +0 -79
  123. package/dist/tools/reply-quote.js +0 -426
  124. package/dist/tools/reply-to-message.js +0 -292
  125. package/dist/tools/respond-to-event.js +0 -110
  126. package/dist/tools/result.js +0 -9
  127. package/dist/tools/search-contacts.js +0 -431
  128. package/dist/tools/search-emails.js +0 -570
  129. package/dist/tools/send-draft.js +0 -308
  130. package/dist/tools/trash-emails.js +0 -36
  131. package/dist/tools/unsubscribe-from-list.js +0 -249
  132. package/dist/tools/update-calendar-event.js +0 -973
  133. package/dist/tools/update-calendar.js +0 -100
  134. package/dist/tools/update-contact.js +0 -382
  135. package/dist/tools/update-draft.js +0 -714
  136. package/dist/tools/update-mail-rule.js +0 -103
  137. package/dist/tools/upload-attachments.js +0 -126
@@ -1,275 +0,0 @@
1
- // The one outward HTTP request on the MCP surface: an RFC 8058 one-click
2
- // unsubscribe POST to a URL the *sender* wrote. The sender also controls that
3
- // host's DNS, so the address check runs inside the connection's own DNS
4
- // lookup — the IP that is checked is the IP that is dialled, and a rebinding
5
- // answer between a check and a connect cannot slip through. Every redirect
6
- // hop is a new request through the same guard, and must be https too.
7
- import { lookup as dnsLookup } from "node:dns";
8
- import https from "node:https";
9
- import { BlockList, isIP } from "node:net";
10
- // Ranges a sender-supplied URL must never reach: this host, the private
11
- // network, the cloud metadata endpoint, and every reserved or translated
12
- // range that can lead back into them.
13
- const BLOCKED = new BlockList();
14
- for (const [net, prefix] of [
15
- ["0.0.0.0", 8],
16
- ["10.0.0.0", 8],
17
- ["100.64.0.0", 10],
18
- ["127.0.0.0", 8],
19
- ["169.254.0.0", 16],
20
- ["172.16.0.0", 12],
21
- ["192.0.0.0", 24],
22
- ["192.0.2.0", 24],
23
- ["192.168.0.0", 16],
24
- ["198.18.0.0", 15],
25
- ["198.51.100.0", 24],
26
- ["203.0.113.0", 24],
27
- ["224.0.0.0", 4],
28
- ["240.0.0.0", 4],
29
- ]) {
30
- BLOCKED.addSubnet(net, prefix, "ipv4");
31
- }
32
- for (const [net, prefix] of [
33
- ["::", 96],
34
- // IPv4-mapped (::ffff:0:0/96) is deliberately absent: BlockList checks
35
- // every IPv4 address against it too, which would block them all. Mapped
36
- // addresses are checked against the IPv4 rules instead (isBlockedAddress,
37
- // and BlockList's own folding for the hex form). This entry is SIIT
38
- // (RFC 2765 IPv4-translated), a different prefix.
39
- ["::ffff:0:0:0", 96],
40
- ["2001::", 32],
41
- ["64:ff9b:1::", 48],
42
- ["::1", 128],
43
- ["64:ff9b::", 96],
44
- ["100::", 64],
45
- ["2001:db8::", 32],
46
- ["2002::", 16],
47
- ["fc00::", 7],
48
- ["fe80::", 10],
49
- ["fec0::", 10],
50
- ["ff00::", 8],
51
- ]) {
52
- BLOCKED.addSubnet(net, prefix, "ipv6");
53
- }
54
- const BRACKETS_RE = /^\[|\]$/gu;
55
- const IPV4_MAPPED_RE = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/iu;
56
- export const isBlockedAddress = (address) => {
57
- const mapped = IPV4_MAPPED_RE.exec(address)?.[1];
58
- if (mapped) {
59
- return BLOCKED.check(mapped, "ipv4");
60
- }
61
- const family = isIP(address);
62
- if (family === 0) {
63
- return true;
64
- }
65
- return BLOCKED.check(address, family === 4 ? "ipv4" : "ipv6");
66
- };
67
- export class BlockedAddressError extends Error {
68
- constructor(host) {
69
- super(`${host} resolves to a private or internal address`);
70
- this.name = "BlockedAddressError";
71
- }
72
- }
73
- const systemResolve = (host) => new Promise((resolve, reject) => {
74
- dnsLookup(host, { all: true }, (err, addresses) => err ? reject(err) : resolve(addresses));
75
- });
76
- // A `lookup` for https.request that refuses the whole connection when any
77
- // address the name resolves to is internal: a name with one public and one
78
- // private record could otherwise be dialled on the private one.
79
- export const guardedLookup = (resolve) => (host, opts, cb) => {
80
- resolve(host)
81
- .then((addresses) => {
82
- if (addresses.length === 0 ||
83
- addresses.some((a) => isBlockedAddress(a.address))) {
84
- cb(new BlockedAddressError(host));
85
- return;
86
- }
87
- if (typeof opts === "object" && opts?.all) {
88
- cb(null, addresses);
89
- return;
90
- }
91
- const [first] = addresses;
92
- cb(null, first?.address, first?.family);
93
- })
94
- .catch((err) => cb(err instanceof Error ? err : new Error(String(err))));
95
- };
96
- const TIMEOUT_MS = 10_000;
97
- const MAX_BODY_BYTES = 16_384;
98
- const ONE_CLICK_BODY = "List-Unsubscribe=One-Click";
99
- // One request, nothing followed. The whole hop — connect, TLS, headers and
100
- // body — has one hard deadline (the socket `timeout` alone only fires on an
101
- // idle socket, so a trickling sender could hold the call forever), and the
102
- // body is cut off at a cap: a sender's endpoint has no business sending more
103
- // than a confirmation page.
104
- export const makeSendHop = (resolve = systemResolve) => (url, method) => new Promise((resolvePromise, rejectPromise) => {
105
- // Settle once: the body cap destroys the response, which can still emit
106
- // `end` or `error` afterwards, and the deadline must not outlive the hop.
107
- let settled = false;
108
- const settle = (fn) => {
109
- if (!settled) {
110
- settled = true;
111
- clearTimeout(deadline);
112
- fn();
113
- }
114
- };
115
- const reject = (err) => settle(() => rejectPromise(err));
116
- const req = https.request(url, {
117
- headers: {
118
- "user-agent": "langmail-mcp-unsubscribe",
119
- ...(method === "POST"
120
- ? {
121
- "content-length": String(ONE_CLICK_BODY.length),
122
- "content-type": "application/x-www-form-urlencoded",
123
- }
124
- : {}),
125
- },
126
- lookup: guardedLookup(resolve),
127
- method,
128
- }, (res) => {
129
- const chunks = [];
130
- let size = 0;
131
- const finish = () => settle(() => resolvePromise({
132
- body: Buffer.concat(chunks)
133
- .subarray(0, MAX_BODY_BYTES)
134
- .toString("utf8"),
135
- location: typeof res.headers.location === "string"
136
- ? res.headers.location
137
- : null,
138
- status: res.statusCode ?? 0,
139
- }));
140
- res.on("data", (chunk) => {
141
- chunks.push(chunk);
142
- size += chunk.length;
143
- if (size >= MAX_BODY_BYTES) {
144
- finish();
145
- res.destroy();
146
- }
147
- });
148
- res.on("end", finish);
149
- res.on("error", reject);
150
- });
151
- const deadline = setTimeout(() => req.destroy(new HopTimeoutError()), TIMEOUT_MS);
152
- req.on("error", reject);
153
- req.end(method === "POST" ? ONE_CLICK_BODY : undefined);
154
- });
155
- class HopTimeoutError extends Error {
156
- constructor() {
157
- super(`no answer within ${TIMEOUT_MS / 1000} seconds`);
158
- this.name = "HopTimeoutError";
159
- }
160
- }
161
- // A short, generic reason for a failed request. The raw message can carry the
162
- // address and port that was dialled, which the sender must not learn back
163
- // through the agent.
164
- const failureReason = (err) => {
165
- if (err instanceof HopTimeoutError) {
166
- return err.message;
167
- }
168
- const code = err?.code;
169
- if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
170
- return "the host name does not resolve";
171
- }
172
- if (code === "ECONNREFUSED" ||
173
- code === "ECONNRESET" ||
174
- code === "EHOSTUNREACH" ||
175
- code === "ENETUNREACH") {
176
- return "the connection failed";
177
- }
178
- if (typeof code === "string" &&
179
- (code.includes("CERT") ||
180
- code.startsWith("ERR_TLS") ||
181
- code.includes("SSL"))) {
182
- return "the TLS handshake failed";
183
- }
184
- return "the request failed";
185
- };
186
- const MAX_REDIRECTS = 3;
187
- const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
188
- const isBlockedError = (err) => err instanceof BlockedAddressError ||
189
- (err instanceof Error && err.name === "BlockedAddressError");
190
- // One hop: the https check, then the request, with a thrown error turned into
191
- // an outcome. A HopResponse means "go on".
192
- const runHop = async (current, hop, method, sendHop) => {
193
- let target;
194
- try {
195
- target = new URL(current);
196
- }
197
- catch {
198
- return { kind: "refused", reason: "the link is not a valid URL" };
199
- }
200
- if (target.protocol !== "https:") {
201
- return {
202
- kind: "refused",
203
- reason: hop === 0
204
- ? "the link is not https"
205
- : `the sender redirected to a non-https address (${target.protocol})`,
206
- };
207
- }
208
- // An IP literal never goes through `lookup` (Node skips DNS for
209
- // it), so the guard has to check it here.
210
- const literal = target.hostname.replace(BRACKETS_RE, "");
211
- if (isIP(literal) !== 0 && isBlockedAddress(literal)) {
212
- return {
213
- kind: "refused",
214
- reason: new BlockedAddressError(target.hostname).message,
215
- };
216
- }
217
- try {
218
- return { res: await sendHop(target.href, method), target };
219
- }
220
- catch (err) {
221
- if (isBlockedError(err)) {
222
- return { kind: "refused", reason: err.message };
223
- }
224
- return { kind: "failed", reachedSender: false, reason: failureReason(err) };
225
- }
226
- };
227
- // POST `List-Unsubscribe=One-Click` to the URL, following at most three
228
- // redirects. 307/308 repeat the POST (the RFC 7231 rule); 301/302/303 turn
229
- // into a GET, as browsers do. Every hop must be https and pass the guard.
230
- export const postOneClick = async (url, sendHop) => {
231
- let current = url;
232
- let method = "POST";
233
- for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
234
- const step = await runHop(current, hop, method, sendHop);
235
- if ("kind" in step) {
236
- // Past the first hop the POST already reached the sender: a refused or
237
- // failed redirect does not mean nothing was sent.
238
- if (hop > 0 && step.kind !== "response") {
239
- const reason = step.kind === "refused"
240
- ? `${step.reason}, so Langmail did not follow it`
241
- : step.reason;
242
- return { kind: "failed", reachedSender: true, reason };
243
- }
244
- return step;
245
- }
246
- const { res, target } = step;
247
- if (!(REDIRECT_STATUSES.has(res.status) && res.location)) {
248
- return {
249
- body: res.body,
250
- host: target.host,
251
- kind: "response",
252
- redirected: hop > 0,
253
- status: res.status,
254
- };
255
- }
256
- try {
257
- current = new URL(res.location, target).href;
258
- }
259
- catch {
260
- return {
261
- kind: "failed",
262
- reachedSender: true,
263
- reason: "the sender redirected to an invalid address",
264
- };
265
- }
266
- if (res.status !== 307 && res.status !== 308) {
267
- method = "GET";
268
- }
269
- }
270
- return {
271
- kind: "failed",
272
- reachedSender: true,
273
- reason: `the sender redirected more than ${MAX_REDIRECTS} times`,
274
- };
275
- };
@@ -1,204 +0,0 @@
1
- // preview_email tool — full-fidelity inline rendering of one message via the
2
- // MCP Apps extension (SEP-1865). One result, two audiences on separate
3
- // channels: the model gets token-cheap metadata in structuredContent, the
4
- // user gets the sanitized HTML body rendered by the ui://langmail/email-viewer
5
- // template. The raw body never enters model context — it rides in result
6
- // _meta, which hosts forward to the view (ui/notifications/tool-result) but
7
- // keep out of the conversation.
8
- //
9
- // The HTTP transport is stateless (one McpServer per request), so the server
10
- // cannot see client capabilities at call time and never branches on Apps
11
- // support, on either transport: the UI metadata is always attached, and hosts without the
12
- // extension simply show the text/metadata. The result text says so, so the
13
- // agent can set expectations honestly.
14
- import { registerAppTool } from "@modelcontextprotocol/ext-apps/server";
15
- import { z } from "zod";
16
- import { isProxyableImageUrl, } from "../email-render/image-proxy.js";
17
- import { EMAIL_VIEWER_RESOURCE_URI, PREVIEW_META_KEY, } from "../email-render/meta.js";
18
- import { sanitizeEmailHtml } from "../email-render/sanitize.js";
19
- import { authorizationHeader, blobDownload, emailGetDetail, } from "../jmap/index.js";
20
- import { logger } from "../logger.js";
21
- import { READ_ONLY } from "./annotations.js";
22
- import { emailTags, formatAddressList, isInlinePart } from "./format.js";
23
- import { bodyText, MAX_BODY_VALUE_BYTES } from "./get-email.js";
24
- import { errorResult } from "./result.js";
25
- // HTML parts above this size skip the download (a body this big is not a
26
- // ticket or an invoice) and fall back to the text rendering.
27
- const MAX_HTML_PART_BYTES = 2_000_000;
28
- const previewEmailShape = {
29
- id: z
30
- .string()
31
- .min(1)
32
- .describe("The message id, as returned by search_emails or get_thread."),
33
- };
34
- export const previewEmailInput = z.object(previewEmailShape);
35
- const previewEmailOutputShape = {
36
- attachmentCount: z.number(),
37
- date: z.string(),
38
- from: z.string(),
39
- renderSource: z
40
- .enum(["html", "text"])
41
- .describe("Whether the preview shows the HTML part or a plain-text fallback."),
42
- subject: z.string(),
43
- tags: z
44
- .array(z.string())
45
- .describe('The message tags ($type/$label), e.g. "ticket" or "receipt".'),
46
- };
47
- const ESCAPES = {
48
- "&": "&amp;",
49
- "<": "&lt;",
50
- ">": "&gt;",
51
- };
52
- const escapeHtml = (text) => text.replace(/[&<>]/g, (c) => ESCAPES[c] ?? c);
53
- // Plain-text fallback rendered as HTML so the viewer has one input shape.
54
- const textAsHtml = (text) => `<pre style="margin:0;white-space:pre-wrap;word-break:break-word;font:14px/1.5 ui-sans-serif,system-ui,sans-serif">${escapeHtml(text)}</pre>`;
55
- // The message's own HTML, if it has a usable text/html part: first such part,
56
- // downloaded in full (no truncation cap — a cut-off tag soup renders worse
57
- // than the text fallback). Bytes are decoded as UTF-8; that is the modern
58
- // default and charset plumbing isn't worth the edge case.
59
- const htmlOfEmail = async (deps, p, email) => {
60
- const part = (email.htmlBody ?? []).find((c) => c.type === "text/html" && c.blobId);
61
- // An unknown size counts as oversized — the guard must not be bypassable
62
- // by a missing property (same stance as get_email's raw-message cap).
63
- if (!part?.blobId ||
64
- (part.size ?? Number.POSITIVE_INFINITY) > MAX_HTML_PART_BYTES) {
65
- return null;
66
- }
67
- try {
68
- const raw = await deps.downloadHtmlPart({ ...p, blobId: part.blobId });
69
- const html = new TextDecoder().decode(raw).trim();
70
- return html || null;
71
- }
72
- catch (err) {
73
- logger.warn({ detail: err instanceof Error ? err.name : "unknown" }, "html part download failed, using text fallback");
74
- return null;
75
- }
76
- };
77
- export const previewEmail = async (deps, ctx) => {
78
- const { token, args } = ctx;
79
- const authorization = authorizationHeader(token);
80
- const accountId = await deps.resolveAccountId(authorization);
81
- const [email] = await deps.emailGetDetail({
82
- accountId,
83
- apiUrl: "",
84
- authorization,
85
- ids: [args.id],
86
- maxBodyValueBytes: MAX_BODY_VALUE_BYTES,
87
- });
88
- if (!email) {
89
- return errorResult(`Email not found: ${args.id}`);
90
- }
91
- const rawHtml = await htmlOfEmail(deps, { accountId, authorization }, email);
92
- const publicUrl = rawHtml ? await deps.publicUrl() : "";
93
- const { mintImageToken } = deps;
94
- // Remote images left out because the user has not turned them on.
95
- let remoteImagesOff = 0;
96
- const html = rawHtml
97
- ? sanitizeEmailHtml(rawHtml, {
98
- resolveCid: (cid) => {
99
- const part = (email.attachments ?? []).find((a) => a.cid === cid && a.blobId);
100
- if (!part?.blobId) {
101
- return null;
102
- }
103
- const ticket = deps.mintAttachmentTicket({
104
- accountId,
105
- authorization,
106
- blobId: part.blobId,
107
- name: part.name ?? "inline",
108
- type: part.type ?? "application/octet-stream",
109
- });
110
- return `${publicUrl}/attachments/${ticket}`;
111
- },
112
- resolveRemote: (url) => {
113
- if (!mintImageToken) {
114
- remoteImagesOff += 1;
115
- return null;
116
- }
117
- return isProxyableImageUrl(url)
118
- ? `${publicUrl}/image-proxy/${mintImageToken(url)}`
119
- : null;
120
- },
121
- })
122
- : textAsHtml(bodyText(email) || "(no text body)");
123
- const renderSource = rawHtml ? "html" : "text";
124
- const structuredContent = {
125
- // Real documents only: an inline cid part (the QR, a logo) is already
126
- // rendered in the preview and must not read as a separate attachment.
127
- attachmentCount: (email.attachments ?? []).filter((part) => !isInlinePart(part)).length,
128
- date: email.receivedAt ?? "",
129
- from: formatAddressList(email.from) || "(unknown sender)",
130
- renderSource,
131
- subject: email.subject ?? "(no subject)",
132
- tags: emailTags(email),
133
- };
134
- return {
135
- _meta: {
136
- [PREVIEW_META_KEY]: {
137
- html,
138
- // The one origin the email document may load images from: where
139
- // the links minted above live. A text rendering has none.
140
- ...(publicUrl ? { imageOrigin: new URL(publicUrl).origin } : {}),
141
- renderSource,
142
- },
143
- },
144
- content: [
145
- {
146
- text: `Preview of "${structuredContent.subject}" prepared (${renderSource} rendering). ` +
147
- "On clients with MCP Apps support the email renders inline in the conversation. " +
148
- "If no rendered email is visible to the user, this client does not support inline " +
149
- "rendering — say so, and use get_email to relay the content instead." +
150
- (remoteImagesOff > 0
151
- ? ` ${remoteImagesOff} image(s) the email loads from the sender's servers are left out of the preview: this server fetches such images only with LANGMAIL_MCP_ALLOW_REMOTE_IMAGES on; it is off.`
152
- : ""),
153
- type: "text",
154
- },
155
- ],
156
- structuredContent,
157
- };
158
- };
159
- // --- live-deps wiring ----------------------------------------------------
160
- export const makeLiveDeps = (live, tickets,
161
- // Undefined unless the user has turned remote images on.
162
- images, publicUrl) => ({
163
- downloadHtmlPart: async (p) => {
164
- const res = await blobDownload({
165
- accountId: p.accountId,
166
- authorization: p.authorization,
167
- blobId: p.blobId,
168
- downloadUrl: (await live.getSession(p.authorization)).downloadUrl,
169
- name: "body.html",
170
- type: "text/html",
171
- });
172
- return new Uint8Array(await res.arrayBuffer());
173
- },
174
- emailGetDetail: async (p) => emailGetDetail({
175
- ...p,
176
- apiUrl: (await live.getSession(p.authorization)).apiUrl,
177
- }),
178
- mintAttachmentTicket: tickets.mint,
179
- mintImageToken: images?.mint,
180
- publicUrl,
181
- resolveAccountId: live.resolveAccountId,
182
- });
183
- // --- MCP registration ----------------------------------------------------
184
- export const registerPreviewEmail = (server, deps, getToken) => {
185
- registerAppTool(server, "preview_email", {
186
- _meta: { ui: { resourceUri: EMAIL_VIEWER_RESOURCE_URI } },
187
- annotations: READ_ONLY,
188
- description: "Show one email to the user as a rendered document, inline in the " +
189
- "conversation. Use it when the user asks to see, show, or display an " +
190
- "email or a document contained in one — tickets, boarding passes, " +
191
- "invoices, receipts — where the visual rendering (QR codes, barcodes, " +
192
- "table layouts) is the point. Use get_email instead when you need the " +
193
- "content for reasoning, summarization, or extraction and the user does " +
194
- "not need the pixels. The result gives the model only compact metadata; " +
195
- "the rendered body is shown to the user by the client and is not in " +
196
- "your context — do not claim to have read it from this call.",
197
- inputSchema: z.object(previewEmailShape),
198
- outputSchema: z.object(previewEmailOutputShape),
199
- title: "Preview email",
200
- }, (args) => {
201
- const parsed = previewEmailInput.parse(args);
202
- return previewEmail(deps, { args: parsed, token: getToken() });
203
- });
204
- };
@@ -1,79 +0,0 @@
1
- // preview_mail_rule tool — validate a proposed rule and estimate its blast
2
- // radius WITHOUT creating, modifying, or touching anything. This is the
3
- // step that lets a client show the user "~184 existing messages would be
4
- // affected" before committing, and the prerequisite for confirming a large
5
- // backfill on create/update.
6
- import { z } from "zod";
7
- import { skippedActionTypes } from "../rules/apply.js";
8
- import { hasAnyCondition, normalizeConditions, } from "../rules/rule.js";
9
- import { READ_ONLY } from "./annotations.js";
10
- import { existingMailSchema, existingMailShape, ruleActionsField, ruleConditionsField, ruleMatchFieldWithDefault, ruleNameField, } from "./mail-rule-common.js";
11
- import { describeActions, describeConditions, formatEstimate, } from "./mail-rule-format.js";
12
- import { textResult } from "./result.js";
13
- const previewMailRuleShape = {
14
- actions: ruleActionsField,
15
- conditions: ruleConditionsField,
16
- existingMail: z
17
- .object(existingMailShape)
18
- .optional()
19
- .describe("The existing-mail policy being considered — its scope decides where matches are counted (default: inbox)."),
20
- match: ruleMatchFieldWithDefault,
21
- name: ruleNameField.optional(),
22
- };
23
- export const previewMailRuleInput = z.object(previewMailRuleShape);
24
- export const previewMailRule = async (deps, ctx) => {
25
- const { args, token } = ctx;
26
- // Validity is part of the preview RESULT, not a tool error — the client
27
- // is explicitly asking "would this work?".
28
- if (!hasAnyCondition(args.conditions)) {
29
- return textResult("Rule is INVALID: provide at least one condition (from, to, subject, bodyContains, or hasAttachment). Nothing was created.");
30
- }
31
- const existingMail = existingMailSchema.parse(args.existingMail ?? {});
32
- const rule = {
33
- actions: args.actions,
34
- conditions: normalizeConditions(args.conditions),
35
- enabled: true,
36
- id: "preview",
37
- match: args.match,
38
- ...(args.name ? { name: args.name } : {}),
39
- };
40
- const estimate = await deps.applier.estimate(token, rule, existingMail.scope);
41
- const warnings = [];
42
- const skipped = skippedActionTypes(rule.actions);
43
- if (skipped.length > 0) {
44
- warnings.push(`These actions apply to future mail only and would be skipped in a backfill: ${skipped.join(", ")}.`);
45
- }
46
- if (rule.conditions.hasAttachment) {
47
- warnings.push("Attachment detection for future mail is heuristic; some signed or inline-attachment messages may not match.");
48
- }
49
- const lines = [
50
- "Rule is valid. Nothing was created or modified.",
51
- "",
52
- `Would match when ${rule.match === "any" ? "ANY" : "ALL"} of: ${describeConditions(rule.conditions, rule.match)}`,
53
- `Would then: ${describeActions(rule.actions)}`,
54
- "",
55
- formatEstimate(estimate, existingMail.scope),
56
- ];
57
- if (warnings.length > 0) {
58
- lines.push("", `Warnings:\n- ${warnings.join("\n- ")}`);
59
- }
60
- lines.push("", "To install it, call create_mail_rule with the same rule (add existingMail to also process the existing matches).");
61
- return textResult(lines.join("\n"));
62
- };
63
- // --- MCP registration ----------------------------------------------------
64
- export const registerPreviewMailRule = (server, deps, getToken) => {
65
- server.registerTool("preview_mail_rule", {
66
- annotations: READ_ONLY,
67
- description: "Validate a proposed mail rule and estimate its effect WITHOUT creating or changing " +
68
- "anything — returns whether the rule is valid, warnings, how many existing messages " +
69
- "and conversations currently match, and a plain-language summary of what would happen. " +
70
- "Use this before create_mail_rule when the user should see the blast radius first, and " +
71
- "always before applying a rule to existing mail (large backfills require the count to " +
72
- "be confirmed). This tool never modifies mail and never installs a rule.",
73
- inputSchema: z.object(previewMailRuleShape),
74
- title: "Preview mail rule",
75
- }, (args) => previewMailRule(deps, {
76
- args: previewMailRuleInput.parse(args),
77
- token: getToken(),
78
- }));
79
- };