langmail-mcp 0.0.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 (138) 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/test-client.js +0 -43
  75. package/dist/mcp/tool-logging.js +0 -67
  76. package/dist/observability/errors.js +0 -41
  77. package/dist/rules/apply.js +0 -236
  78. package/dist/rules/rule.js +0 -280
  79. package/dist/rules/store.js +0 -92
  80. package/dist/tools/annotations.js +0 -71
  81. package/dist/tools/archive-emails.js +0 -40
  82. package/dist/tools/calendar-lookup.js +0 -64
  83. package/dist/tools/contact-common.js +0 -146
  84. package/dist/tools/contact-format.js +0 -72
  85. package/dist/tools/contact-write-through.js +0 -37
  86. package/dist/tools/create-calendar-event.js +0 -231
  87. package/dist/tools/create-calendar.js +0 -54
  88. package/dist/tools/create-contact.js +0 -172
  89. package/dist/tools/create-draft.js +0 -369
  90. package/dist/tools/create-mail-rule.js +0 -101
  91. package/dist/tools/delete-calendar-event.js +0 -165
  92. package/dist/tools/delete-contact.js +0 -60
  93. package/dist/tools/delete-draft.js +0 -129
  94. package/dist/tools/delete-mail-rule.js +0 -38
  95. package/dist/tools/download-attachment.js +0 -90
  96. package/dist/tools/download-email.js +0 -112
  97. package/dist/tools/draft-common.js +0 -600
  98. package/dist/tools/email-types.js +0 -58
  99. package/dist/tools/error-detail.js +0 -10
  100. package/dist/tools/file-emails-common.js +0 -75
  101. package/dist/tools/format.js +0 -131
  102. package/dist/tools/forward-message.js +0 -237
  103. package/dist/tools/forward-quote.js +0 -179
  104. package/dist/tools/get-draft.js +0 -61
  105. package/dist/tools/get-email.js +0 -164
  106. package/dist/tools/get-thread.js +0 -67
  107. package/dist/tools/keywords.js +0 -43
  108. package/dist/tools/list-calendar-events.js +0 -180
  109. package/dist/tools/list-calendars.js +0 -44
  110. package/dist/tools/list-drafts.js +0 -134
  111. package/dist/tools/list-mail-rules.js +0 -28
  112. package/dist/tools/list-unsubscribe.js +0 -152
  113. package/dist/tools/list-upcoming-birthdays.js +0 -165
  114. package/dist/tools/mail-rule-common.js +0 -43
  115. package/dist/tools/mail-rule-format.js +0 -79
  116. package/dist/tools/mailbox-lookup.js +0 -13
  117. package/dist/tools/mark-emails.js +0 -78
  118. package/dist/tools/merge-contacts.js +0 -145
  119. package/dist/tools/move-calendar-events.js +0 -340
  120. package/dist/tools/move-emails.js +0 -64
  121. package/dist/tools/one-click-post.js +0 -275
  122. package/dist/tools/preview-email.js +0 -204
  123. package/dist/tools/preview-mail-rule.js +0 -79
  124. package/dist/tools/reply-quote.js +0 -426
  125. package/dist/tools/reply-to-message.js +0 -292
  126. package/dist/tools/respond-to-event.js +0 -110
  127. package/dist/tools/result.js +0 -9
  128. package/dist/tools/search-contacts.js +0 -431
  129. package/dist/tools/search-emails.js +0 -570
  130. package/dist/tools/send-draft.js +0 -308
  131. package/dist/tools/trash-emails.js +0 -36
  132. package/dist/tools/unsubscribe-from-list.js +0 -249
  133. package/dist/tools/update-calendar-event.js +0 -973
  134. package/dist/tools/update-calendar.js +0 -100
  135. package/dist/tools/update-contact.js +0 -382
  136. package/dist/tools/update-draft.js +0 -714
  137. package/dist/tools/update-mail-rule.js +0 -103
  138. package/dist/tools/upload-attachments.js +0 -126
@@ -1,236 +0,0 @@
1
- // Applying a rule to EXISTING mail — the explicit, opt-in counterpart to
2
- // the Sieve script that governs future deliveries. Conditions translate to
3
- // a JMAP Email/query filter; actions translate to one uniform Email/set
4
- // patch (keywords + mailbox membership) applied to every match. Two action
5
- // types cannot be replayed onto stored mail and are reported as skipped:
6
- // forward (would re-send old messages) and stopProcessing (only meaningful
7
- // during rule evaluation).
8
- //
9
- // The JMAP wire calls live behind the `ApplyIo` seam so the engine is
10
- // unit-testable; `makeLiveApplyIo` wires the real JMAP calls (`src/jmap`).
11
- import { accountIdForMail, authorizationHeader, emailQueryFilter, emailSetMany, mailboxCreate, mailboxIdByNameOrRole, mailboxIdByRole, roleForPlaceName, threadsExpandEmailIds, toLabelKeyword, } from "../jmap/index.js";
12
- import { tagToKeywordSuffix, } from "./rule.js";
13
- // Backfills touching more matches than this require the client to re-call
14
- // with explicit confirmation (the spec's "large backfills" guard).
15
- export const LARGE_APPLY_THRESHOLD = 200;
16
- // Hard per-call ceiling for both estimates and backfills. A full window is
17
- // reported as "N+" and, for apply, the client can simply run the call again
18
- // — the query re-evaluates against the not-yet-modified remainder for
19
- // mailbox-moving rules, and idempotent patches make repeats harmless.
20
- const APPLY_WINDOW = 1000;
21
- // --- conditions → JMAP filter ------------------------------------------------
22
- export const ruleFilter = (rule, inboxId) => {
23
- const conditions = [];
24
- const c = rule.conditions;
25
- if (c.from) {
26
- conditions.push({ from: c.from });
27
- }
28
- if (c.to) {
29
- conditions.push({ to: c.to });
30
- }
31
- if (c.subject) {
32
- conditions.push({ subject: c.subject });
33
- }
34
- if (c.bodyContains) {
35
- conditions.push({ body: c.bodyContains });
36
- }
37
- if (c.hasAttachment) {
38
- conditions.push({ hasAttachment: true });
39
- }
40
- const node = conditions.length === 1 && conditions[0]
41
- ? conditions[0]
42
- : { conditions, operator: rule.match === "any" ? "OR" : "AND" };
43
- // Scope ANDs around the condition node so any/all only governs the
44
- // user's conditions, never the mailbox restriction.
45
- return inboxId
46
- ? { conditions: [{ inMailbox: inboxId }, node], operator: "AND" }
47
- : node;
48
- };
49
- // --- actions → Email/set patch --------------------------------------------------
50
- const APPLYABLE = new Set([
51
- "addTag",
52
- "archive",
53
- "copy",
54
- "delete",
55
- "flag",
56
- "markRead",
57
- "markUnread",
58
- "move",
59
- "removeTag",
60
- ]);
61
- export const skippedActionTypes = (actions) => [
62
- ...new Set(actions.filter((a) => !APPLYABLE.has(a.type)).map((a) => a.type)),
63
- ];
64
- // One uniform EmailSetChanges for the whole batch. Mailbox-moving actions
65
- // (archive/move/delete) add the target and drop the Inbox — the JMAP
66
- // equivalent of Sieve's fileinto cancelling the implicit keep.
67
- export const buildChanges = async (actions, ctx) => {
68
- const keywords = {};
69
- const mailboxIds = {};
70
- let leftInbox = false;
71
- for (const action of actions) {
72
- switch (action.type) {
73
- case "addTag": {
74
- const suffix = tagToKeywordSuffix(action.tag);
75
- if (suffix) {
76
- keywords[toLabelKeyword(suffix)] = true;
77
- }
78
- break;
79
- }
80
- case "archive": {
81
- mailboxIds[await ctx.resolveByRole("archive", "Archive")] = true;
82
- leftInbox = true;
83
- break;
84
- }
85
- case "copy": {
86
- mailboxIds[await ctx.resolveByName(action.mailbox)] = true;
87
- break;
88
- }
89
- case "delete": {
90
- mailboxIds[await ctx.resolveByRole("trash", "Trash")] = true;
91
- leftInbox = true;
92
- break;
93
- }
94
- case "flag": {
95
- keywords.$flagged = true;
96
- break;
97
- }
98
- case "markRead": {
99
- keywords.$seen = true;
100
- break;
101
- }
102
- case "markUnread": {
103
- keywords.$seen = false;
104
- break;
105
- }
106
- case "move": {
107
- mailboxIds[await ctx.resolveByName(action.mailbox)] = true;
108
- leftInbox = true;
109
- break;
110
- }
111
- case "removeTag": {
112
- const suffix = tagToKeywordSuffix(action.tag);
113
- if (suffix) {
114
- keywords[toLabelKeyword(suffix)] = false;
115
- }
116
- break;
117
- }
118
- default:
119
- break;
120
- }
121
- }
122
- if (leftInbox && ctx.inboxId && !(ctx.inboxId in mailboxIds)) {
123
- mailboxIds[ctx.inboxId] = false;
124
- }
125
- return {
126
- ...(Object.keys(keywords).length > 0 ? { keywords } : {}),
127
- ...(Object.keys(mailboxIds).length > 0 ? { mailboxIds } : {}),
128
- };
129
- };
130
- export const makeMailRulesApplier = (io) => {
131
- const scopedFilter = async (token, rule, scope) => {
132
- const inboxId = scope === "inbox"
133
- ? await io.resolveMailboxByRole(token, "inbox", "Inbox")
134
- : null;
135
- return ruleFilter(rule, inboxId);
136
- };
137
- return {
138
- applyToExisting: async (token, rule, mode, scope) => {
139
- const filter = await scopedFilter(token, rule, scope);
140
- const matchedIds = await io.queryEmailIds(token, filter, APPLY_WINDOW);
141
- const targetIds = mode === "conversations"
142
- ? await io.expandToThreads(token, matchedIds)
143
- : matchedIds;
144
- if (targetIds.length === 0) {
145
- return {
146
- failed: 0,
147
- matched: 0,
148
- modified: 0,
149
- skippedActions: skippedActionTypes(rule.actions),
150
- };
151
- }
152
- const inboxId = await io.resolveMailboxByRole(token, "inbox", "Inbox");
153
- const changes = await buildChanges(rule.actions, {
154
- inboxId,
155
- resolveByName: (name) => io.resolveMailboxByName(token, name),
156
- resolveByRole: (role, createName) => io.resolveMailboxByRole(token, role, createName),
157
- });
158
- if (!(changes.keywords || changes.mailboxIds)) {
159
- return {
160
- failed: 0,
161
- matched: targetIds.length,
162
- modified: 0,
163
- skippedActions: skippedActionTypes(rule.actions),
164
- };
165
- }
166
- const { updated, notUpdated } = await io.updateEmails(token, targetIds, changes);
167
- return {
168
- failed: notUpdated.length,
169
- matched: targetIds.length,
170
- modified: updated.length,
171
- skippedActions: skippedActionTypes(rule.actions),
172
- };
173
- },
174
- estimate: async (token, rule, scope) => {
175
- const filter = await scopedFilter(token, rule, scope);
176
- const ids = await io.queryEmailIds(token, filter, APPLY_WINDOW);
177
- const conversations = await io.countConversations(token, filter, APPLY_WINDOW);
178
- return {
179
- capped: ids.length >= APPLY_WINDOW,
180
- conversations,
181
- messages: ids.length,
182
- };
183
- },
184
- };
185
- };
186
- // --- live wiring -------------------------------------------------------------------
187
- export const makeLiveApplyIo = (live, authorize = authorizationHeader) => {
188
- const ctx = async (token) => {
189
- const authorization = authorize(token);
190
- const session = await live.getSession(authorization);
191
- return {
192
- accountId: accountIdForMail(session),
193
- apiUrl: session.apiUrl,
194
- authorization,
195
- };
196
- };
197
- return {
198
- countConversations: async (token, filter, limit) => {
199
- const c = await ctx(token);
200
- const ids = await emailQueryFilter({
201
- ...c,
202
- collapseThreads: true,
203
- filter,
204
- limit,
205
- });
206
- return ids.length;
207
- },
208
- expandToThreads: async (token, emailIds) => {
209
- const c = await ctx(token);
210
- return threadsExpandEmailIds({ ...c, emailIds });
211
- },
212
- queryEmailIds: async (token, filter, limit) => {
213
- const c = await ctx(token);
214
- return emailQueryFilter({ ...c, filter, limit });
215
- },
216
- resolveMailboxByName: async (token, name) => {
217
- const c = await ctx(token);
218
- // A rule naming a place ("move to Sent") must bind to the mailbox holding
219
- // that role even when the server calls it something else — creating a
220
- // second folder under the typed name would split the place in two, and
221
- // the role-based actions (archive/delete) would keep using the original.
222
- const role = roleForPlaceName(name);
223
- return ((await mailboxIdByNameOrRole({ ...c, name })) ??
224
- mailboxCreate({ ...c, name, role }));
225
- },
226
- resolveMailboxByRole: async (token, role, createName) => {
227
- const c = await ctx(token);
228
- return ((await mailboxIdByRole({ ...c, role })) ??
229
- mailboxCreate({ ...c, name: createName, role }));
230
- },
231
- updateEmails: async (token, ids, changes) => {
232
- const c = await ctx(token);
233
- return emailSetMany({ ...c, changes, ids });
234
- },
235
- };
236
- };
@@ -1,280 +0,0 @@
1
- // The mail-rule domain model and its Sieve projection.
2
- //
3
- // A rule is a structured object the MCP client distills from the user's
4
- // natural-language request ("whenever I receive an invoice from Stripe,
5
- // move it to Finance"): matching conditions (composed with all/any), an
6
- // ordered list of actions, a name, and an enabled flag. Rules are stored
7
- // *in Stalwart itself* as one managed Sieve script (open protocol, no side
8
- // database): each rule is serialized as a single-line JSON metadata comment
9
- // followed by the generated Sieve block. The comments are the source of
10
- // truth on read — `parseSieveScript` round-trips them — and the whole
11
- // script is regenerated from the rule list on every write, so the Sieve
12
- // code never drifts from the metadata. Consequence: hand-edits inside the
13
- // managed script (including a corrupted metadata line) do not survive the
14
- // next write; hand-written Sieve belongs in a *differently named* script.
15
- //
16
- // Rules govern FUTURE mail (Sieve runs at delivery). Applying a rule to
17
- // existing mail is a separate, explicit operation — see apply.ts.
18
- import { z } from "zod";
19
- import { toLabelKeyword } from "../jmap/index.js";
20
- // The name of the managed script in the user's Sieve script list. Scripts
21
- // under any other name (e.g. hand-written via ManageSieve) are never
22
- // rewritten — but note only one script can be *active* per account, so
23
- // activating ours deactivates a previously active foreign script.
24
- export const RULES_SCRIPT_NAME = "langmail-rules";
25
- const RULE_MARKER = "# langmail-rule ";
26
- // Sieve quoted strings may not contain raw control characters (RFC 5228
27
- // §2.4.2 permits only CRLF, which we never emit inside a value), so reject
28
- // them at the schema instead of failing the save with an opaque
29
- // invalidScript error.
30
- // biome-ignore lint/suspicious/noControlCharactersInRegex: the pattern exists to reject control characters
31
- const NO_CONTROL_CHARS_RE = /^[^\u0000-\u001F\u007F]*$/u;
32
- const conditionString = (max) => z.string().min(1).max(max).regex(NO_CONTROL_CHARS_RE, {
33
- message: "control characters are not allowed",
34
- });
35
- // --- conditions --------------------------------------------------------------
36
- // These `.describe()` strings are repeated verbatim in the indexed metadata of
37
- // all three mail-rule tools (create/update/preview all embed the conditions and
38
- // actions schema), so each one costs three times its length in tool search.
39
- // Keep them to a single clause.
40
- export const mailRuleConditionsShape = {
41
- bodyContains: conditionString(200)
42
- .optional()
43
- .describe("Message body contains this text."),
44
- from: conditionString(200)
45
- .optional()
46
- .describe('Sender (From) contains this — an address, a domain like "github.com", or a name like "Acme Corp".'),
47
- hasAttachment: z
48
- .boolean()
49
- .optional()
50
- .describe('true matches messages that look like they carry an attachment (heuristic); false means "not set".'),
51
- subject: conditionString(200)
52
- .optional()
53
- .describe("Subject line contains this."),
54
- to: conditionString(200)
55
- .optional()
56
- .describe("A To/Cc recipient contains this (address or name)."),
57
- };
58
- const conditionsSchema = z.object(mailRuleConditionsShape);
59
- export const hasAnyCondition = (c) => Boolean(c.from ?? c.to ?? c.subject ?? c.bodyContains ?? c.hasAttachment);
60
- // hasAttachment:false means "not set" (see the .describe above); dropping it
61
- // here keeps the stored metadata canonical.
62
- export const normalizeConditions = (c) => ({
63
- ...(c.from ? { from: c.from } : {}),
64
- ...(c.to ? { to: c.to } : {}),
65
- ...(c.subject ? { subject: c.subject } : {}),
66
- ...(c.bodyContains ? { bodyContains: c.bodyContains } : {}),
67
- ...(c.hasAttachment ? { hasAttachment: true } : {}),
68
- });
69
- // --- actions -------------------------------------------------------------------
70
- // The tag-id normalization of the `$label:` keyword convention JMAP mail
71
- // clients show as label chips: lower → non-[a-z0-9_-] to '-' → collapse runs
72
- // → trim. Every writer of such a keyword has to normalize the same way, or a
73
- // rule's tag and a label of the same name written elsewhere become two chips.
74
- export const tagToKeywordSuffix = (name) => {
75
- const slug = name
76
- .toLowerCase()
77
- .replaceAll(/[^a-z0-9_-]+/gu, "-")
78
- .replaceAll(/-+/gu, "-")
79
- .replaceAll(/^-+|-+$/gu, "");
80
- return slug.length > 0 ? slug : null;
81
- };
82
- const tagString = conditionString(50).refine((t) => tagToKeywordSuffix(t) !== null, {
83
- message: 'tag must contain at least one letter, digit, "_" or "-"',
84
- });
85
- const mailboxString = conditionString(100);
86
- // Ordered action list (RFC-agnostic, provider-portable vocabulary). Each
87
- // entry is a discriminated object so new action types can grow fields
88
- // without breaking the stored shape.
89
- export const mailRuleActionSchema = z.discriminatedUnion("type", [
90
- z
91
- .object({ type: z.literal("archive") })
92
- .describe("Move it out of the Inbox into Archive."),
93
- z.object({
94
- mailbox: mailboxString.describe("Target mailbox/folder name; created if missing."),
95
- type: z.literal("move"),
96
- }),
97
- z.object({
98
- mailbox: mailboxString.describe("Target mailbox/folder name; created if missing."),
99
- type: z.literal("copy"),
100
- }),
101
- z.object({
102
- tag: tagString.describe('Tag name, e.g. "GitHub"; slugified to a tag id ("Acme Corp" -> "acme-corp").'),
103
- type: z.literal("addTag"),
104
- }),
105
- z.object({ tag: tagString, type: z.literal("removeTag") }),
106
- z.object({ type: z.literal("markRead") }),
107
- z.object({ type: z.literal("markUnread") }),
108
- z.object({ type: z.literal("flag") }).describe("Flag/star it."),
109
- z
110
- .object({ type: z.literal("delete") })
111
- .describe("Move it to Trash (not a permanent erase)."),
112
- z.object({
113
- to: z
114
- .email()
115
- .describe("Forward a copy here; the original still lands in the mailbox."),
116
- type: z.literal("forward"),
117
- }),
118
- z
119
- .object({ type: z.literal("stopProcessing") })
120
- .describe("Skip any later rules for this message. Only useful as the last action."),
121
- ]);
122
- export const mailRuleActionsSchema = z
123
- .array(mailRuleActionSchema)
124
- .min(1)
125
- .max(10);
126
- // --- rule ------------------------------------------------------------------------
127
- export const MATCH_VALUES = ["all", "any"];
128
- // The stored shape: what the metadata comment carries and what
129
- // list/update/delete round-trip.
130
- export const mailRuleSchema = z.object({
131
- actions: mailRuleActionsSchema,
132
- conditions: conditionsSchema.refine(hasAnyCondition, {
133
- message: "a rule needs at least one condition",
134
- }),
135
- createdAt: z.iso.datetime().optional(),
136
- enabled: z.boolean(),
137
- id: z.string().min(1).max(64),
138
- match: z.enum(MATCH_VALUES),
139
- name: conditionString(200).optional(),
140
- updatedAt: z.iso.datetime().optional(),
141
- });
142
- // --- Sieve projection --------------------------------------------------------
143
- // RFC 5228 §2.4.2 quoted strings: backslash and double-quote are the only
144
- // characters that need escaping (control chars are rejected at the schema).
145
- const sieveString = (value) => `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
146
- const conditionTests = (c) => {
147
- const tests = [];
148
- if (c.from) {
149
- tests.push(`header :contains "from" ${sieveString(c.from)}`);
150
- }
151
- if (c.to) {
152
- tests.push(`header :contains ["to", "cc"] ${sieveString(c.to)}`);
153
- }
154
- if (c.subject) {
155
- tests.push(`header :contains "subject" ${sieveString(c.subject)}`);
156
- }
157
- if (c.bodyContains) {
158
- // RFC 5173 body test, default :text transform.
159
- tests.push(`body :contains ${sieveString(c.bodyContains)}`);
160
- }
161
- if (c.hasAttachment) {
162
- // Sieve has no first-class attachment test; multipart/mixed is the
163
- // conventional heuristic (attachments force that top-level type). The
164
- // schema description discloses the imprecision.
165
- tests.push('header :contains "content-type" "multipart/mixed"');
166
- }
167
- return tests;
168
- };
169
- const actionCommand = (a) => {
170
- switch (a.type) {
171
- case "addTag": {
172
- const suffix = tagToKeywordSuffix(a.tag);
173
- return suffix ? `addflag ${sieveString(toLabelKeyword(suffix))};` : null;
174
- }
175
- case "archive":
176
- // :specialuse targets the account's real Archive folder by JMAP role
177
- // (RFC 8579), the same way archive_emails finds it; "Archive" is
178
- // only the creation name if none exists yet.
179
- return 'fileinto :specialuse "\\\\Archive" :create "Archive";';
180
- case "copy":
181
- // :copy keeps the message where it would otherwise go (RFC 3894).
182
- return `fileinto :copy :create ${sieveString(a.mailbox)};`;
183
- case "delete":
184
- return 'fileinto :specialuse "\\\\Trash" :create "Trash";';
185
- case "flag":
186
- return 'addflag "\\\\Flagged";';
187
- case "forward":
188
- // :copy keeps the local delivery; a forwarding rule must never be the
189
- // reason a message silently vanishes from the user's own mailbox.
190
- return `redirect :copy ${sieveString(a.to)};`;
191
- case "markRead":
192
- return 'addflag "\\\\Seen";';
193
- case "markUnread":
194
- return 'removeflag "\\\\Seen";';
195
- case "move":
196
- // :create files into the mailbox even if it doesn't exist yet, and
197
- // cancels the implicit keep — the message leaves the Inbox.
198
- return `fileinto :create ${sieveString(a.mailbox)};`;
199
- case "removeTag": {
200
- const suffix = tagToKeywordSuffix(a.tag);
201
- return suffix
202
- ? `removeflag ${sieveString(toLabelKeyword(suffix))};`
203
- : null;
204
- }
205
- case "stopProcessing":
206
- return "stop;";
207
- default:
208
- return null;
209
- }
210
- };
211
- const isFlagAction = (a) => a.type === "addTag" ||
212
- a.type === "removeTag" ||
213
- a.type === "markRead" ||
214
- a.type === "markUnread" ||
215
- a.type === "flag";
216
- // Emit a rule's actions as Sieve commands. Sieve's imap4flags model (RFC
217
- // 5232) applies the *current* internal flag set at each keep/fileinto, so
218
- // flag mutations are emitted before filing/redirect commands regardless of
219
- // the listed order — that is what makes "archive, then tag, then mark read"
220
- // mean what the user means. `stop` always goes last.
221
- const actionCommands = (actions) => {
222
- const flags = actions.filter(isFlagAction);
223
- const filings = actions.filter((a) => !(isFlagAction(a) || a.type === "stopProcessing"));
224
- const stop = actions.some((a) => a.type === "stopProcessing");
225
- const ordered = [
226
- ...flags,
227
- ...filings,
228
- ...(stop ? [{ type: "stopProcessing" }] : []),
229
- ];
230
- return ordered.map(actionCommand).filter((c) => c !== null);
231
- };
232
- const ruleBlock = (rule) => {
233
- const metadata = `${RULE_MARKER}${JSON.stringify(rule)}`;
234
- if (!rule.enabled) {
235
- // Disabled rules keep their metadata (so list/update round-trip) but
236
- // contribute no executable code.
237
- return metadata;
238
- }
239
- const combinator = rule.match === "any" ? "anyof" : "allof";
240
- const tests = conditionTests(rule.conditions);
241
- const body = actionCommands(rule.actions)
242
- .map((c) => ` ${c}`)
243
- .join("\n");
244
- return [metadata, `if ${combinator} (${tests.join(", ")}) {`, body, "}"].join("\n");
245
- };
246
- // The full managed script. Deterministic output for a given rule list —
247
- // saved verbatim, parsed back by `parseSieveScript`.
248
- export const generateSieveScript = (rules) => {
249
- const header = [
250
- "# Langmail mail rules — generated from the metadata comments below.",
251
- "# Managed by the Langmail MCP server; do not edit by hand.",
252
- 'require ["fileinto", "imap4flags", "mailbox", "copy", "special-use", "body"];',
253
- ];
254
- return [header.join("\n"), ...rules.map(ruleBlock)].join("\n\n").concat("\n");
255
- };
256
- // Recover the rule list from a stored script by re-parsing the metadata
257
- // comments. Lines that fail to parse or validate are skipped — and because
258
- // every save regenerates the whole script, a skipped rule is dropped on the
259
- // next write (see the module header for why that is the contract).
260
- export const parseSieveScript = (script) => {
261
- const rules = [];
262
- for (const line of script.split("\n")) {
263
- const trimmed = line.trim();
264
- if (!trimmed.startsWith(RULE_MARKER)) {
265
- continue;
266
- }
267
- let raw;
268
- try {
269
- raw = JSON.parse(trimmed.slice(RULE_MARKER.length));
270
- }
271
- catch {
272
- continue;
273
- }
274
- const parsed = mailRuleSchema.safeParse(raw);
275
- if (parsed.success) {
276
- rules.push(parsed.data);
277
- }
278
- }
279
- return rules;
280
- };
@@ -1,92 +0,0 @@
1
- // Persistence for mail rules: one managed Sieve script in the user's own
2
- // Stalwart account (RFC 9661 SieveScript objects; content travels as a
3
- // blob). No side database — deleting the script deletes every rule, and a
4
- // ManageSieve client sees exactly what the MCP wrote.
5
- //
6
- // The JMAP wire calls live behind the `SieveIo` seam so the store logic is
7
- // unit-testable; `makeLiveSieveIo` wires the real JMAP calls (`src/jmap`).
8
- import { accountIdForSieve, authorizationHeader, blobDownload, blobUpload, sieveScriptCreate, sieveScriptList, sieveScriptUpdate, } from "../jmap/index.js";
9
- import { generateSieveScript, parseSieveScript, RULES_SCRIPT_NAME, } from "./rule.js";
10
- export const makeMailRulesStore = (io) => ({
11
- load: async (token) => {
12
- const script = await io.findScript(token);
13
- if (!script) {
14
- return [];
15
- }
16
- return parseSieveScript(await io.downloadScript(token, script.blobId));
17
- },
18
- save: async (token, rules) => {
19
- const blobId = await io.uploadScript(token, generateSieveScript(rules));
20
- const script = await io.findScript(token);
21
- if (script) {
22
- await io.updateScript(token, script.id, blobId);
23
- }
24
- else {
25
- await io.createScript(token, blobId);
26
- }
27
- },
28
- });
29
- // --- live wiring -------------------------------------------------------------
30
- // `authorize` maps the tool-layer token to a full Authorization header. The
31
- // token already is that header here, so the default passes it through
32
- // unchanged; a caller can pin a different credential through the same seam.
33
- export const makeLiveSieveIo = (live, authorize = authorizationHeader) => {
34
- const sessionAndAccount = async (token) => {
35
- const session = await live.getSession(authorize(token));
36
- return { accountId: accountIdForSieve(session), session };
37
- };
38
- return {
39
- createScript: async (token, blobId) => {
40
- const { session, accountId } = await sessionAndAccount(token);
41
- await sieveScriptCreate({
42
- accountId,
43
- apiUrl: session.apiUrl,
44
- authorization: authorize(token),
45
- blobId,
46
- name: RULES_SCRIPT_NAME,
47
- });
48
- },
49
- downloadScript: async (token, blobId) => {
50
- const { session, accountId } = await sessionAndAccount(token);
51
- const res = await blobDownload({
52
- accountId,
53
- authorization: authorize(token),
54
- blobId,
55
- downloadUrl: session.downloadUrl,
56
- name: `${RULES_SCRIPT_NAME}.sieve`,
57
- type: "application/sieve",
58
- });
59
- return res.text();
60
- },
61
- findScript: async (token) => {
62
- const { session, accountId } = await sessionAndAccount(token);
63
- const scripts = await sieveScriptList({
64
- accountId,
65
- apiUrl: session.apiUrl,
66
- authorization: authorize(token),
67
- });
68
- const managed = scripts.find((s) => s.name === RULES_SCRIPT_NAME);
69
- return managed ? { blobId: managed.blobId, id: managed.id } : null;
70
- },
71
- updateScript: async (token, scriptId, blobId) => {
72
- const { session, accountId } = await sessionAndAccount(token);
73
- await sieveScriptUpdate({
74
- accountId,
75
- apiUrl: session.apiUrl,
76
- authorization: authorize(token),
77
- blobId,
78
- scriptId,
79
- });
80
- },
81
- uploadScript: async (token, content) => {
82
- const { session, accountId } = await sessionAndAccount(token);
83
- return blobUpload({
84
- accountId,
85
- authorization: authorize(token),
86
- content,
87
- type: "application/sieve",
88
- uploadUrl: session.uploadUrl,
89
- });
90
- },
91
- };
92
- };
@@ -1,71 +0,0 @@
1
- // MCP tool annotations for this surface, as five named risk classes.
2
- //
3
- // The point of annotating every tool rather than a few is that a client can
4
- // then decide which calls need a confirmation step *from the annotations
5
- // alone*, without hard-coding tool names — which is the only version of that
6
- // check that survives new tools being added.
7
- //
8
- // Two hints carry the decision, and this surface uses them with fixed meanings:
9
- //
10
- // openWorldHint the call reaches someone outside the user's own account —
11
- // a recipient, an attendee, an iMIP notice.
12
- // destructiveHint the call cannot be taken back from here: it removes
13
- // something, or it hands something to a third party.
14
- //
15
- // Staging is deliberately distinguishable from sending on those two alone:
16
- // create_draft is ACCOUNT_WRITE (nobody outside the mailbox sees it, the user
17
- // can delete it), send_draft is OUTWARD_DESTRUCTIVE. That is the whole
18
- // asymmetry the sending surface rests on, expressed where a client can read it.
19
- //
20
- // `idempotentHint` stays false on every write. The composition tools accept an
21
- // `idempotencyKey` that does make a retry safe, but the hint describes the tool
22
- // unconditionally and a caller that omits the key gets a second send — so
23
- // claiming idempotence here would be a lie in exactly the case it matters.
24
- // Reads nothing but the user's own data back to them.
25
- export const READ_ONLY = {
26
- destructiveHint: false,
27
- idempotentHint: true,
28
- openWorldHint: false,
29
- readOnlyHint: true,
30
- };
31
- // Writes inside the user's own account. No third party learns anything and the
32
- // user can undo it in the UI — staging a draft, creating a calendar, adding a
33
- // mail rule.
34
- export const ACCOUNT_WRITE = {
35
- destructiveHint: false,
36
- idempotentHint: false,
37
- openWorldHint: false,
38
- readOnlyHint: false,
39
- };
40
- // Removes something from the user's own account. Still nobody outside sees it,
41
- // but this surface cannot undo it — a deleted rule is gone, an edited draft
42
- // is replaced, trashed mail is recoverable only from the mail client until
43
- // Trash is emptied.
44
- export const ACCOUNT_DESTRUCTIVE = {
45
- destructiveHint: true,
46
- idempotentHint: false,
47
- openWorldHint: false,
48
- readOnlyHint: false,
49
- };
50
- // Third parties are notified, but nothing is destroyed — an invitation, an RSVP.
51
- //
52
- // The mail-rule writers live here rather than under ACCOUNT_WRITE because a rule
53
- // may carry a `forward` action, which redirects a copy of every matching future
54
- // message to an arbitrary address. A static annotation has to describe what the
55
- // tool *can* do, and "quietly installs a persistent data-forwarding rule" is the
56
- // most consequential outward reach on this surface — a client gating on
57
- // `openWorldHint` has to see it.
58
- export const OUTWARD_WRITE = {
59
- destructiveHint: false,
60
- idempotentHint: false,
61
- openWorldHint: true,
62
- readOnlyHint: false,
63
- };
64
- // Irreversible and visible outside the account: mail is delivered, a meeting is
65
- // cancelled, attendees are notified. These are the calls worth confirming.
66
- export const OUTWARD_DESTRUCTIVE = {
67
- destructiveHint: true,
68
- idempotentHint: false,
69
- openWorldHint: true,
70
- readOnlyHint: false,
71
- };