@open-workspace/email 0.3.0 → 0.4.1

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 (221) hide show
  1. package/README.md +22 -22
  2. package/alchemy/index.ts +273 -0
  3. package/drizzle/mailbox/0000_puzzling_dracula.sql +149 -0
  4. package/drizzle/mailbox/0001_mute_jack_flag.sql +12 -0
  5. package/drizzle/mailbox/meta/0000_snapshot.json +1002 -0
  6. package/drizzle/mailbox/meta/0001_snapshot.json +1002 -0
  7. package/drizzle/mailbox/meta/_journal.json +20 -0
  8. package/drizzle/mailbox/migrations.js +12 -0
  9. package/index.ts +3 -1
  10. package/migrations/{0000_email.sql → 0000_dry_moon_knight.sql} +26 -20
  11. package/migrations/meta/0000_snapshot.json +125 -109
  12. package/migrations/meta/_journal.json +2 -2
  13. package/package.json +74 -68
  14. package/shared/attachment-preview.ts +37 -27
  15. package/shared/folder-order.ts +106 -0
  16. package/shared/mail-authentication.ts +8 -3
  17. package/shared/mail-feedback.ts +18 -25
  18. package/shared/mail-headers.ts +114 -39
  19. package/shared/mail-import.ts +38 -0
  20. package/shared/mail-path.ts +42 -0
  21. package/shared/mail-received.ts +174 -31
  22. package/shared/mail-remote.ts +59 -2
  23. package/shared/mail-sender-intel.ts +22 -4
  24. package/shared/mail.ts +77 -28
  25. package/shared/module.ts +33 -0
  26. package/shared/office-preview.ts +14 -2
  27. package/shared/pdfjs-assets.ts +35 -0
  28. package/shared/permissions.ts +73 -0
  29. package/shared/webhooks.ts +41 -0
  30. package/src/admin/blocked-senders.tsx +189 -0
  31. package/src/client.tsx +97 -0
  32. package/src/lib/mail-api.ts +9 -0
  33. package/src/mail/attachment-preview-dialog.tsx +161 -0
  34. package/src/mail/blocked-senders.tsx +138 -0
  35. package/src/mail/compose-window-chrome.tsx +194 -0
  36. package/src/mail/compose-window.tsx +486 -0
  37. package/src/mail/composer-asset-bookmarks.ts +409 -0
  38. package/src/mail/composer-asset.tsx +229 -0
  39. package/src/mail/composer-attachment-list.tsx +138 -0
  40. package/src/mail/composer-editor-document.ts +65 -0
  41. package/src/mail/composer-editor.tsx +284 -0
  42. package/src/mail/composer-linked-attachment-text.ts +12 -0
  43. package/src/mail/composer-recipient-fields.tsx +165 -0
  44. package/src/mail/composer-recipients.ts +208 -0
  45. package/src/mail/composer-session.ts +562 -0
  46. package/src/mail/composer-toolbar.tsx +303 -0
  47. package/src/mail/composer-upload-client.ts +105 -0
  48. package/src/mail/composer-upload-progress.ts +53 -0
  49. package/src/mail/conversation-list.tsx +550 -0
  50. package/src/mail/conversation-loading-skeleton.tsx +119 -0
  51. package/src/mail/conversation-message.tsx +346 -0
  52. package/src/mail/conversation-reply.tsx +470 -0
  53. package/src/mail/conversation-selection-toolbar.tsx +322 -0
  54. package/src/mail/conversation-view.tsx +437 -0
  55. package/src/mail/delivery-indicator.tsx +272 -0
  56. package/src/mail/email-html-body.tsx +203 -0
  57. package/src/mail/folder-glyph.tsx +46 -0
  58. package/src/mail/folder-manager.tsx +532 -0
  59. package/src/mail/format-bytes.ts +7 -0
  60. package/src/mail/mail-app-bar.tsx +253 -0
  61. package/src/mail/mail-background.tsx +12 -0
  62. package/src/mail/mail-dock.tsx +137 -0
  63. package/src/mail/mail-folders.ts +44 -0
  64. package/src/mail/mail-layout.css +236 -0
  65. package/src/mail/mail-location.ts +73 -0
  66. package/src/mail/mail-mailbox-sheet.tsx +275 -0
  67. package/src/mail/mail-nav-rail.tsx +129 -0
  68. package/src/mail/mail-nav.tsx +324 -0
  69. package/src/mail/mail-prefetch.ts +59 -0
  70. package/src/mail/mail-primitives.tsx +66 -0
  71. package/src/mail/mail-queries.ts +209 -0
  72. package/src/mail/mail-query-cache.ts +486 -0
  73. package/src/mail/mail-seed.ts +47 -0
  74. package/src/mail/mail-shell.tsx +126 -0
  75. package/src/mail/mailbox-ai-settings.tsx +185 -0
  76. package/src/mail/mailbox-realtime.tsx +251 -0
  77. package/src/mail/mailbox-route.tsx +15 -0
  78. package/src/mail/message-actions.tsx +353 -0
  79. package/src/mail/message-attachments.tsx +200 -0
  80. package/src/mail/message-format.ts +75 -0
  81. package/src/mail/message-header.tsx +260 -0
  82. package/src/mail/message-translation.tsx +225 -0
  83. package/src/mail/original-message-sheet.tsx +619 -0
  84. package/src/mail/original-message.ts +191 -0
  85. package/src/mail/outbound-notification.ts +53 -0
  86. package/src/mail/pane-splitter.tsx +117 -0
  87. package/src/mail/pdf-preview-toolbar.tsx +152 -0
  88. package/src/mail/pdf-preview.css +44 -0
  89. package/src/mail/pdf-preview.tsx +156 -0
  90. package/src/mail/pdf-translation-layout.ts +95 -0
  91. package/src/mail/print-message.ts +92 -0
  92. package/src/mail/reader-pane.tsx +535 -0
  93. package/src/mail/recipient-combobox.tsx +335 -0
  94. package/src/mail/recipient-field-row.tsx +34 -0
  95. package/src/mail/reply-to-warning.tsx +50 -0
  96. package/src/mail/sanitize-email-html.ts +430 -0
  97. package/src/mail/sender-actions.tsx +149 -0
  98. package/src/mail/sender-authentication.tsx +485 -0
  99. package/src/mail/sender-dialogs.tsx +384 -0
  100. package/src/mail/sender-security.tsx +545 -0
  101. package/src/mail/toolbar-tooltip.tsx +29 -0
  102. package/src/mail/translation-html.ts +49 -0
  103. package/src/mail/translation-language.ts +21 -0
  104. package/src/mail/types.ts +53 -0
  105. package/src/mail/unread-document-indicator.tsx +60 -0
  106. package/src/mail/use-compose-submission.ts +208 -0
  107. package/src/mail/use-composer-attachment-preflight.ts +184 -0
  108. package/src/mail/use-composer-submission.ts +117 -0
  109. package/src/mail/use-conversation-selection.ts +186 -0
  110. package/src/mail/use-mail-controller.ts +427 -0
  111. package/src/mail/use-mail-data.ts +279 -0
  112. package/src/mail/use-mail-safety.ts +155 -0
  113. package/src/mail/use-mail-send.ts +142 -0
  114. package/src/mail/use-pdf-translation-overlay.ts +156 -0
  115. package/src/mail/use-pdf-translation.ts +100 -0
  116. package/src/mail/use-pdf-viewer.ts +215 -0
  117. package/src/mail/use-reply-submission.ts +114 -0
  118. package/src/mail/use-sanitized-email-html.ts +20 -0
  119. package/src/mail/use-visible-message-read.ts +138 -0
  120. package/src/pwa/push-subscription.ts +151 -0
  121. package/src/settings/mail-apps-page.tsx +235 -0
  122. package/src/settings/notifications-page.tsx +291 -0
  123. package/worker/admin/blocked-sender-routes.ts +166 -0
  124. package/worker/admin/schemas.ts +11 -0
  125. package/worker/bindings.d.ts +14 -10
  126. package/worker/db/schema.ts +63 -40
  127. package/worker/jmap/eventsource.ts +84 -16
  128. package/worker/jmap/methods.ts +1630 -524
  129. package/worker/jmap/push-types.ts +27 -0
  130. package/worker/jmap/push.ts +140 -56
  131. package/worker/jmap/routes.ts +366 -105
  132. package/worker/mail/access.ts +258 -21
  133. package/worker/mail/ai-classification.ts +36 -20
  134. package/worker/mail/ai-translation.ts +13 -6
  135. package/worker/mail/auth-headers.ts +395 -137
  136. package/worker/mail/bimi.ts +200 -73
  137. package/worker/mail/bootstrap.ts +79 -0
  138. package/worker/mail/capped-body.ts +36 -0
  139. package/worker/mail/classification-signals.ts +35 -25
  140. package/worker/mail/conversation-cursor.ts +30 -19
  141. package/worker/mail/delivery-events.ts +88 -62
  142. package/worker/mail/delivery-facts.ts +46 -10
  143. package/worker/mail/demo-routes.ts +34 -10
  144. package/worker/mail/doh.ts +62 -23
  145. package/worker/mail/downloads.ts +75 -40
  146. package/worker/mail/edge-cache.ts +155 -0
  147. package/worker/mail/header-metadata.ts +88 -22
  148. package/worker/mail/impersonation.ts +160 -38
  149. package/worker/mail/import-routes.ts +313 -0
  150. package/worker/mail/inbound-delivery.ts +19 -9
  151. package/worker/mail/inbound-threading.ts +18 -8
  152. package/worker/mail/inbound.ts +82 -40
  153. package/worker/mail/ip-intel.ts +110 -27
  154. package/worker/mail/isolate-cache.ts +35 -0
  155. package/worker/mail/link-domains.ts +29 -7
  156. package/worker/mail/mailbox-deletion.ts +10 -4
  157. package/worker/mail/mailbox-directory.ts +16 -6
  158. package/worker/mail/mailing-list.ts +94 -39
  159. package/worker/mail/message-security.ts +90 -15
  160. package/worker/mail/message-view.ts +18 -6
  161. package/worker/mail/office-conversion.ts +31 -9
  162. package/worker/mail/office-preview-container.ts +40 -13
  163. package/worker/mail/office-preview-queue.ts +76 -32
  164. package/worker/mail/org-domain.ts +8 -1
  165. package/worker/mail/outbound-content.ts +71 -26
  166. package/worker/mail/outbound-delivery.ts +31 -17
  167. package/worker/mail/outbound-service.ts +48 -30
  168. package/worker/mail/outbound-threading.ts +30 -17
  169. package/worker/mail/outbound.ts +97 -70
  170. package/worker/mail/outgoing-context.ts +25 -15
  171. package/worker/mail/participants.ts +44 -29
  172. package/worker/mail/push-notifications.ts +271 -173
  173. package/worker/mail/quote-parser.ts +21 -10
  174. package/worker/mail/r2-presigned-urls.ts +31 -25
  175. package/worker/mail/receive.ts +23 -11
  176. package/worker/mail/recipients.ts +6 -1
  177. package/worker/mail/remote-proxy.ts +187 -31
  178. package/worker/mail/remote-routes.ts +87 -0
  179. package/worker/mail/remote-token.ts +104 -0
  180. package/worker/mail/repeat.ts +19 -0
  181. package/worker/mail/reply-plan.ts +62 -33
  182. package/worker/mail/rfc.ts +32 -7
  183. package/worker/mail/routes.ts +870 -541
  184. package/worker/mail/safety-routes.ts +328 -200
  185. package/worker/mail/schemas.ts +84 -105
  186. package/worker/mail/search.ts +1 -0
  187. package/worker/mail/security-settings.ts +41 -9
  188. package/worker/mail/sender-intel.ts +206 -51
  189. package/worker/mail/spamhaus.ts +92 -45
  190. package/worker/mail/unsubscribe.ts +76 -18
  191. package/worker/mail/uploads.ts +126 -93
  192. package/worker/mail/webhook-source.ts +35 -12
  193. package/worker/mail/workspace-safety.ts +97 -38
  194. package/worker/mailbox/demo-html.ts +7 -7
  195. package/worker/mailbox/demo-seed.ts +10 -44
  196. package/worker/mailbox/demo.ts +595 -225
  197. package/worker/mailbox/email-index.ts +53 -0
  198. package/worker/mailbox/folder-model.ts +53 -17
  199. package/worker/mailbox/import-placement.ts +88 -0
  200. package/worker/mailbox/inbox-counts.ts +106 -0
  201. package/worker/mailbox/index.ts +1734 -721
  202. package/worker/mailbox/jmap-store.ts +139 -35
  203. package/worker/mailbox/model.ts +8 -6
  204. package/worker/mailbox/office-preview-jobs.ts +56 -25
  205. package/worker/mailbox/schema.ts +87 -66
  206. package/worker/mailbox/senders.ts +176 -70
  207. package/worker/mcp/mail-action-tools.ts +128 -87
  208. package/worker/mcp/mail-compose-tools.ts +133 -82
  209. package/worker/mcp/mail-query-tools.ts +120 -71
  210. package/worker/mcp/mail-safety-tools.ts +321 -248
  211. package/worker/mcp/schemas.ts +43 -0
  212. package/worker/mcp/tools.ts +13 -10
  213. package/worker/module.ts +43 -18
  214. package/worker/sql.d.ts +8 -0
  215. package/alchemy.ts +0 -142
  216. package/containers/office-preview/Dockerfile +0 -10
  217. package/shared/mail-rules.ts +0 -156
  218. package/worker/admin/report-routes.ts +0 -164
  219. package/worker/mail/reported-messages.ts +0 -68
  220. package/worker/mailbox/migrations.ts +0 -10
  221. package/worker/mailbox/rules.ts +0 -110
@@ -1,12 +1,18 @@
1
- import { McpServer } from "@modelcontextprotocol/server";
1
+ import type {
2
+ ScopedToolRegistrar,
3
+ AccountApiClient,
4
+ } from "@open-workspace/core/module";
5
+ import { apiPath, runTool } from "@open-workspace/core/module";
2
6
  import { z } from "zod";
3
- import type { InboundAuthentication, MessageSecurity } from "../../shared/mail-authentication";
4
- import type { SenderIntel } from "../../shared/mail-sender-intel";
5
- import { reportStatusSchema, workspaceBlockSchema } from "@open-workspace/core/worker/admin/schemas.ts";
6
- import { mailRuleSchema } from "../mail/schemas";
7
- import { AccountApiClient, apiPath } from "@open-workspace/core/worker/mcp/account-client.ts";
8
- import { runTool } from "@open-workspace/core/worker/mcp/results.ts";
9
- import { entityIdSchema, mailboxIdSchema } from "@open-workspace/core/worker/mcp/schemas.ts";
7
+
8
+ import {
9
+ MAIL_ORGANIZE_SCOPE,
10
+ MAIL_READ_SCOPE,
11
+ MAIL_SEND_SCOPE,
12
+ BLOCK_SENDERS_SCOPE,
13
+ } from "../../shared/permissions";
14
+ import { workspaceBlockSchema } from "../admin/schemas";
15
+ import { entityIdSchema, mailboxIdSchema } from "./schemas";
10
16
 
11
17
  const readOnly = {
12
18
  readOnlyHint: true,
@@ -27,62 +33,166 @@ const messageInputSchema = z.object({
27
33
  messageId: entityIdSchema,
28
34
  });
29
35
 
30
- const blockPatternSchema = z.string().trim().min(3).max(320).describe(
31
- "An email address (alex@example.com) or a domain (example.com or @example.com; also matches its subdomains).",
32
- );
36
+ const blockPatternSchema = z
37
+ .string()
38
+ .trim()
39
+ .min(3)
40
+ .max(320)
41
+ .describe(
42
+ "An email address (alex@example.com) or a domain (example.com or @example.com; also matches its subdomains)."
43
+ );
33
44
 
34
- const reportKindSchema = z.enum(["spam", "phishing"]);
45
+ const nullableString = z.string().nullable();
35
46
 
36
- const RULE_SEMANTICS = "Rules run in list order on new incoming mail. Every condition present must match: from/to take an address (exact) or a domain (matches subdomains); subjectContains is a case-insensitive substring; listId is the List-Id. Actions: at most one destination (folderId of a custom folder, archive, or spam), plus optional markRead and neverSpam (overrides the AI spam verdict; cannot combine with spam).";
47
+ /** The parts of a message's InboundAuthentication (shared/mail-authentication) the summary reads. */
48
+ const authenticationSchema = z.object({
49
+ remoteIp: nullableString,
50
+ helo: nullableString,
51
+ envelopeFrom: nullableString,
52
+ spf: z
53
+ .object({
54
+ result: z.string(),
55
+ domain: nullableString,
56
+ aligned: z.boolean(),
57
+ })
58
+ .nullable(),
59
+ dkim: z.array(
60
+ z.object({
61
+ result: z.string(),
62
+ domain: z.string(),
63
+ selector: nullableString,
64
+ aligned: z.boolean(),
65
+ })
66
+ ),
67
+ dmarc: z
68
+ .object({
69
+ result: z.string(),
70
+ headerFrom: nullableString,
71
+ policy: nullableString,
72
+ alignedVia: z.array(z.string()),
73
+ })
74
+ .nullable(),
75
+ arc: z
76
+ .object({
77
+ result: z.string(),
78
+ chainLength: z.number(),
79
+ sealers: z.array(z.object({ domain: nullableString })),
80
+ })
81
+ .nullable(),
82
+ spamScore: z.number().nullable(),
83
+ verdict: z.string(),
84
+ verdictReason: z.string(),
85
+ });
37
86
 
38
- const mailRuleInputSchema = z.object({
39
- mailboxId: mailboxIdSchema,
40
- ...mailRuleSchema.shape,
87
+ const spamhausListingSchema = z.object({
88
+ zone: z.string(),
89
+ target: z.string(),
90
+ list: z.string(),
91
+ severity: z.string(),
41
92
  });
42
93
 
43
- type AuthenticationResponse = {
44
- original: {
45
- subject: string;
46
- from: string;
47
- to: string[];
48
- messageId: string | null;
49
- receivedAt: string;
50
- envelopeFrom: string | null;
51
- envelopeTo: string | null;
52
- };
53
- authentication: InboundAuthentication | null;
54
- security: MessageSecurity | null;
55
- senderIntel: SenderIntel | null;
56
- };
94
+ /** The parts of a message's SenderIntel (shared/mail-sender-intel) the summary reads. */
95
+ const senderIntelSchema = z.object({
96
+ checkedAt: z.number(),
97
+ ip: nullableString,
98
+ ptr: z.object({
99
+ names: z.array(z.string()),
100
+ confirmed: nullableString,
101
+ fcrdns: z.boolean().nullable(),
102
+ generic: z.boolean().nullable(),
103
+ }),
104
+ heloMatchesPtr: z.boolean().nullable(),
105
+ network: z.object({
106
+ asn: z.number().nullable(),
107
+ asName: nullableString,
108
+ country: nullableString,
109
+ }),
110
+ spamhaus: z
111
+ .object({
112
+ zen: z.object({ listings: z.array(spamhausListingSchema) }),
113
+ dbl: z.object({ listings: z.array(spamhausListingSchema) }),
114
+ })
115
+ .nullable(),
116
+ });
117
+
118
+ /** The parts of a message's MessageSecurity (shared/mail-authentication) the summary reads. */
119
+ const securitySchema = z.object({
120
+ verdict: z.string(),
121
+ verdictReason: z.string(),
122
+ fromDomain: nullableString,
123
+ mailedBy: nullableString,
124
+ signedBy: nullableString,
125
+ via: nullableString,
126
+ external: z.boolean(),
127
+ listUnsubscribe: z
128
+ .object({
129
+ httpsUrl: nullableString,
130
+ mailto: nullableString,
131
+ oneClick: z.boolean(),
132
+ })
133
+ .nullable(),
134
+ warnings: z.array(z.json()),
135
+ firstTimeSender: z.boolean(),
136
+ replyToMismatch: z
137
+ .object({ address: z.string(), domain: z.string() })
138
+ .nullable(),
139
+ });
57
140
 
58
- function authLine(result: string, details: Array<string | null | false | undefined>) {
141
+ /** GET /mail/messages/:id/authentication, as far as the summary reads it. */
142
+ const authenticationResponseSchema = z.object({
143
+ original: z.object({
144
+ subject: z.string(),
145
+ from: z.string(),
146
+ receivedAt: z.string(),
147
+ }),
148
+ authentication: authenticationSchema.nullable(),
149
+ security: securitySchema.nullable(),
150
+ senderIntel: senderIntelSchema.nullable(),
151
+ });
152
+
153
+ type AuthenticationResponse = z.output<typeof authenticationResponseSchema>;
154
+
155
+ function authLine(
156
+ result: string,
157
+ details: (string | null | false | undefined)[]
158
+ ) {
59
159
  const extra = details.filter(Boolean).join(", ");
160
+
60
161
  return extra ? `${result} (${extra})` : result;
61
162
  }
62
163
 
63
- function compactAuthentication(auth: InboundAuthentication | null) {
164
+ function compactAuthentication(auth: AuthenticationResponse["authentication"]) {
64
165
  if (!auth) return null;
166
+
65
167
  return {
66
168
  spf: auth.spf
67
- ? authLine(auth.spf.result, [auth.spf.domain, auth.spf.aligned && "aligned"])
169
+ ? authLine(auth.spf.result, [
170
+ auth.spf.domain,
171
+ auth.spf.aligned && "aligned",
172
+ ])
68
173
  : null,
69
- dkim: auth.dkim.map((dkim) => authLine(dkim.result, [
70
- dkim.domain,
71
- dkim.selector && `s=${dkim.selector}`,
72
- dkim.aligned && "aligned",
73
- ])),
174
+ dkim: auth.dkim.map((dkim) =>
175
+ authLine(dkim.result, [
176
+ dkim.domain,
177
+ dkim.selector && `s=${dkim.selector}`,
178
+ dkim.aligned && "aligned",
179
+ ])
180
+ ),
74
181
  dmarc: auth.dmarc
75
182
  ? authLine(auth.dmarc.result, [
76
- auth.dmarc.headerFrom,
77
- auth.dmarc.policy && `p=${auth.dmarc.policy}`,
78
- auth.dmarc.alignedVia.length > 0 && `via ${auth.dmarc.alignedVia.join("+")}`,
79
- ])
183
+ auth.dmarc.headerFrom,
184
+ auth.dmarc.policy && `p=${auth.dmarc.policy}`,
185
+ auth.dmarc.alignedVia.length > 0 &&
186
+ `via ${auth.dmarc.alignedVia.join("+")}`,
187
+ ])
80
188
  : null,
81
189
  arc: auth.arc
82
190
  ? authLine(auth.arc.result, [
83
- auth.arc.chainLength > 1 && `forwarded through ${auth.arc.sealers
84
- .map((sealer) => sealer.domain ?? "unknown").join(", ")}`,
85
- ])
191
+ auth.arc.chainLength > 1 &&
192
+ `forwarded through ${auth.arc.sealers
193
+ .map((sealer) => sealer.domain ?? "unknown")
194
+ .join(", ")}`,
195
+ ])
86
196
  : null,
87
197
  remoteIp: auth.remoteIp,
88
198
  helo: auth.helo,
@@ -91,16 +201,20 @@ function compactAuthentication(auth: InboundAuthentication | null) {
91
201
  };
92
202
  }
93
203
 
94
- function compactSenderIntel(intel: SenderIntel | null) {
204
+ function compactSenderIntel(intel: AuthenticationResponse["senderIntel"]) {
95
205
  if (!intel) return null;
206
+
96
207
  const spamhausHits = intel.spamhaus
97
- ? [...intel.spamhaus.zen.listings, ...intel.spamhaus.dbl.listings].map((listing) => ({
98
- zone: listing.zone,
99
- target: listing.target,
100
- list: listing.list,
101
- severity: listing.severity,
102
- }))
208
+ ? [...intel.spamhaus.zen.listings, ...intel.spamhaus.dbl.listings].map(
209
+ (listing) => ({
210
+ zone: listing.zone,
211
+ target: listing.target,
212
+ list: listing.list,
213
+ severity: listing.severity,
214
+ })
215
+ )
103
216
  : null;
217
+
104
218
  return {
105
219
  checkedAt: new Date(intel.checkedAt).toISOString(),
106
220
  ip: intel.ip,
@@ -117,16 +231,19 @@ function compactSenderIntel(intel: SenderIntel | null) {
117
231
  }
118
232
 
119
233
  function compactSecurity(messageId: string, response: AuthenticationResponse) {
120
- const security = response.security;
234
+ const { security } = response;
121
235
  const unsubscribe = security?.listUnsubscribe ?? null;
236
+
122
237
  return {
123
238
  ok: true,
124
239
  messageId,
125
240
  from: response.original.from,
126
241
  subject: response.original.subject,
127
242
  receivedAt: response.original.receivedAt,
128
- verdict: security?.verdict ?? response.authentication?.verdict ?? "unavailable",
129
- verdictReason: security?.verdictReason ?? response.authentication?.verdictReason ?? null,
243
+ verdict:
244
+ security?.verdict ?? response.authentication?.verdict ?? "unavailable",
245
+ verdictReason:
246
+ security?.verdictReason ?? response.authentication?.verdictReason ?? null,
130
247
  fromDomain: security?.fromDomain ?? null,
131
248
  mailedBy: security?.mailedBy ?? null,
132
249
  signedBy: security?.signedBy ?? null,
@@ -146,29 +263,41 @@ function compactSecurity(messageId: string, response: AuthenticationResponse) {
146
263
  };
147
264
  }
148
265
 
149
- export function registerMailSafetyTools(server: McpServer, api: AccountApiClient) {
150
- server.registerTool(
266
+ export function registerMailSafetyTools(
267
+ tool: ScopedToolRegistrar,
268
+ api: AccountApiClient
269
+ ) {
270
+ tool(MAIL_READ_SCOPE)(
151
271
  "get_message_security",
152
272
  {
153
273
  title: "Get message security assessment",
154
- description: "Summarize whether an incoming message is safe to trust: sender verdict (verified/unverified/suspicious/unavailable), one-line SPF/DKIM/DMARC/ARC results, mailed-by/signed-by/via, whether the sender is external, security warnings (lookalike domain, impersonation, Spamhaus listings, reply-to mismatch), sender server intel (IP, PTR, ASN, country, Spamhaus hits), and whether the message offers an unsubscribe option. Use this before acting on a suspicious message; use get_message_authentication only when the full parsed header data is needed. Blocked/trusted sender state is in get_conversation's per-message `sender` field.",
274
+ description:
275
+ "Summarize whether an incoming message is safe to trust: sender verdict (verified/unverified/suspicious/unavailable), one-line SPF/DKIM/DMARC/ARC results, mailed-by/signed-by/via, whether the sender is external, security warnings (lookalike domain, impersonation, Spamhaus listings, reply-to mismatch), sender server intel (IP, PTR, ASN, country, Spamhaus hits), and whether the message offers an unsubscribe option. Use this before acting on a suspicious message; use get_message_authentication only when the full parsed header data is needed. Blocked/trusted sender state is in get_conversation's per-message `sender` field.",
155
276
  inputSchema: messageInputSchema,
156
277
  annotations: readOnly,
157
278
  },
158
- ({ mailboxId, messageId }) => runTool(async () => compactSecurity(
159
- messageId,
160
- await api.json(apiPath(
161
- `/mail/messages/${encodeURIComponent(messageId)}/authentication`,
162
- { mailboxId },
163
- )) as unknown as AuthenticationResponse,
164
- )),
279
+ ({ mailboxId, messageId }) =>
280
+ runTool(async () =>
281
+ compactSecurity(
282
+ messageId,
283
+ authenticationResponseSchema.parse(
284
+ await api.json(
285
+ apiPath(
286
+ `/mail/messages/${encodeURIComponent(messageId)}/authentication`,
287
+ { mailboxId }
288
+ )
289
+ )
290
+ )
291
+ )
292
+ )
165
293
  );
166
294
 
167
- server.registerTool(
295
+ tool(MAIL_SEND_SCOPE)(
168
296
  "unsubscribe_from_mailing_list",
169
297
  {
170
298
  title: "Unsubscribe from mailing list",
171
- description: "OUTBOUND ACTION: unsubscribe this mailbox from the mailing list that sent an incoming message. With method \"auto\" the server tries, in order: an RFC 8058 one-click POST to the sender's URL (outcome \"done\"); an unsubscribe email sent from this mailbox, which requires send access (outcome \"requested\"); otherwise it returns the sender's unsubscribe page URL for the user to open themselves (outcome \"link\"). Method \"link\" only records that the user is opening the page and returns its URL; it contacts no one. Confirm with the user before calling. Rate-limited to 20 requests per minute. Check get_message_security's unsubscribe field first.",
299
+ description:
300
+ 'OUTBOUND ACTION: unsubscribe this mailbox from the mailing list that sent an incoming message. With method "auto" the server tries, in order: an RFC 8058 one-click POST to the sender\'s URL (outcome "done"); an unsubscribe email sent from this mailbox, which requires send access (outcome "requested"); otherwise it returns the sender\'s unsubscribe page URL for the user to open themselves (outcome "link"). Method "link" only records that the user is opening the page and returns its URL; it contacts no one. Confirm with the user before calling. Rate-limited to 20 requests per minute. Check get_message_security\'s unsubscribe field first.',
172
301
  inputSchema: messageInputSchema.extend({
173
302
  method: z.enum(["auto", "link"]).default("auto"),
174
303
  }),
@@ -179,64 +308,89 @@ export function registerMailSafetyTools(server: McpServer, api: AccountApiClient
179
308
  openWorldHint: true,
180
309
  },
181
310
  },
182
- ({ mailboxId, messageId, method }) => runTool(() => api.json(apiPath(
183
- `/mail/messages/${encodeURIComponent(messageId)}/unsubscribe`,
184
- { mailboxId },
185
- ), { method: "POST", json: { method } })),
311
+ ({ mailboxId, messageId, method }) =>
312
+ runTool(() =>
313
+ api.json(
314
+ apiPath(
315
+ `/mail/messages/${encodeURIComponent(messageId)}/unsubscribe`,
316
+ { mailboxId }
317
+ ),
318
+ { method: "POST", json: { method } }
319
+ )
320
+ )
186
321
  );
187
322
 
188
- server.registerTool(
323
+ tool(MAIL_ORGANIZE_SCOPE)(
189
324
  "report_message",
190
325
  {
191
- title: "Report spam or phishing",
192
- description: "Report an incoming message as spam or phishing: labels it, trains the sender's reputation, and moves its conversation to Spam. Phishing also opens a report for workspace administrators. Nothing is sent outside the workspace. Confirm with the user before reporting.",
193
- inputSchema: messageInputSchema.extend({ kind: reportKindSchema }),
326
+ title: "Report spam",
327
+ description:
328
+ "Report an incoming message as spam: labels it, trains the sender's reputation here and across the workspace, and moves its conversation to Spam. Nothing is sent outside the workspace. Confirm with the user before reporting.",
329
+ inputSchema: messageInputSchema,
194
330
  annotations: { ...write, idempotentHint: false },
195
331
  },
196
- ({ mailboxId, messageId, kind }) => runTool(() => api.json(apiPath(
197
- `/mail/messages/${encodeURIComponent(messageId)}/report`,
198
- { mailboxId },
199
- ), { method: "POST", json: { kind } })),
332
+ ({ mailboxId, messageId }) =>
333
+ runTool(() =>
334
+ api.json(
335
+ apiPath(`/mail/messages/${encodeURIComponent(messageId)}/report`, {
336
+ mailboxId,
337
+ }),
338
+ { method: "POST" }
339
+ )
340
+ )
200
341
  );
201
342
 
202
- server.registerTool(
343
+ tool(MAIL_ORGANIZE_SCOPE)(
203
344
  "report_conversations",
204
345
  {
205
- title: "Report conversations as spam or phishing",
206
- description: "Report the newest incoming message of up to 100 conversations as spam or phishing and move them to Spam. Phishing also opens administrator reports. Confirm with the user first.",
346
+ title: "Report conversations as spam",
347
+ description:
348
+ "Report the newest incoming message of up to 100 conversations as spam and move them to Spam. Confirm with the user first.",
207
349
  inputSchema: z.object({
208
350
  mailboxId: mailboxIdSchema,
209
- kind: reportKindSchema,
210
- conversationIds: z.array(entityIdSchema).min(1).max(100)
351
+ conversationIds: z
352
+ .array(entityIdSchema)
353
+ .min(1)
354
+ .max(100)
211
355
  .transform((ids) => [...new Set(ids)]),
212
356
  }),
213
357
  annotations: { ...write, idempotentHint: false },
214
358
  },
215
- ({ mailboxId, kind, conversationIds }) => runTool(() => api.json(apiPath(
216
- "/mail/conversations/report",
217
- { mailboxId },
218
- ), { method: "POST", json: { kind, conversationIds } })),
359
+ ({ mailboxId, conversationIds }) =>
360
+ runTool(() =>
361
+ api.json(apiPath("/mail/conversations/report", { mailboxId }), {
362
+ method: "POST",
363
+ json: { conversationIds },
364
+ })
365
+ )
219
366
  );
220
367
 
221
- server.registerTool(
368
+ tool(MAIL_ORGANIZE_SCOPE)(
222
369
  "mark_message_not_spam",
223
370
  {
224
371
  title: "Mark message not spam",
225
- description: "Move an incoming message's conversation from Spam back to Inbox, clear its spam/phishing label, record the feedback, and mark the sender as trusted in this mailbox.",
372
+ description:
373
+ "Move an incoming message's conversation from Spam back to Inbox, clear its spam label, record the feedback, and mark the sender as trusted in this mailbox.",
226
374
  inputSchema: messageInputSchema,
227
375
  annotations: write,
228
376
  },
229
- ({ mailboxId, messageId }) => runTool(() => api.json(apiPath(
230
- `/mail/messages/${encodeURIComponent(messageId)}/not-spam`,
231
- { mailboxId },
232
- ), { method: "POST" })),
377
+ ({ mailboxId, messageId }) =>
378
+ runTool(() =>
379
+ api.json(
380
+ apiPath(`/mail/messages/${encodeURIComponent(messageId)}/not-spam`, {
381
+ mailboxId,
382
+ }),
383
+ { method: "POST" }
384
+ )
385
+ )
233
386
  );
234
387
 
235
- server.registerTool(
388
+ tool(MAIL_ORGANIZE_SCOPE)(
236
389
  "set_sender_trusted",
237
390
  {
238
391
  title: "Trust or untrust sender",
239
- description: "Mark a sender address as trusted (or not) for everyone using this mailbox. Trusted senders have caution warnings hidden; danger warnings still show.",
392
+ description:
393
+ "Mark a sender address as trusted (or not) for everyone using this mailbox. Trusted senders have caution warnings hidden; danger warnings still show.",
240
394
  inputSchema: z.object({
241
395
  mailboxId: mailboxIdSchema,
242
396
  address: z.email(),
@@ -244,30 +398,38 @@ export function registerMailSafetyTools(server: McpServer, api: AccountApiClient
244
398
  }),
245
399
  annotations: write,
246
400
  },
247
- ({ mailboxId, address, trusted }) => runTool(() => api.json(
248
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/trusted-senders`,
249
- { method: "PUT", json: { address, trusted } },
250
- )),
401
+ ({ mailboxId, address, trusted }) =>
402
+ runTool(() =>
403
+ api.json(
404
+ `/mail/mailboxes/${encodeURIComponent(mailboxId)}/trusted-senders`,
405
+ { method: "PUT", json: { address, trusted } }
406
+ )
407
+ )
251
408
  );
252
409
 
253
- server.registerTool(
410
+ tool(MAIL_READ_SCOPE)(
254
411
  "list_blocked_senders",
255
412
  {
256
413
  title: "List blocked senders",
257
- description: "List addresses and domains blocked in this mailbox, plus workspace-wide blocks set by administrators (which the mailbox cannot remove).",
414
+ description:
415
+ "List addresses and domains blocked in this mailbox, plus workspace-wide blocks set by administrators (which the mailbox cannot remove).",
258
416
  inputSchema: z.object({ mailboxId: mailboxIdSchema }),
259
417
  annotations: readOnly,
260
418
  },
261
- ({ mailboxId }) => runTool(() => api.json(
262
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/blocked-senders`,
263
- )),
419
+ ({ mailboxId }) =>
420
+ runTool(() =>
421
+ api.json(
422
+ `/mail/mailboxes/${encodeURIComponent(mailboxId)}/blocked-senders`
423
+ )
424
+ )
264
425
  );
265
426
 
266
- server.registerTool(
427
+ tool(MAIL_ORGANIZE_SCOPE)(
267
428
  "block_sender",
268
429
  {
269
430
  title: "Block sender or domain",
270
- description: "Block an address or domain for everyone using this mailbox: future mail from it goes to Spam. With moveExisting, existing conversations from it are also moved to Spam. The mailbox's own address or domain cannot be blocked.",
431
+ description:
432
+ "Block an address or domain for everyone using this mailbox: future mail from it goes to Spam. With moveExisting, existing conversations from it are also moved to Spam. The mailbox's own address or domain cannot be blocked.",
271
433
  inputSchema: z.object({
272
434
  mailboxId: mailboxIdSchema,
273
435
  pattern: blockPatternSchema,
@@ -275,178 +437,89 @@ export function registerMailSafetyTools(server: McpServer, api: AccountApiClient
275
437
  }),
276
438
  annotations: write,
277
439
  },
278
- ({ mailboxId, pattern, moveExisting }) => runTool(() => api.json(
279
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/blocked-senders`,
280
- { method: "POST", json: { pattern, moveExisting } },
281
- )),
440
+ ({ mailboxId, pattern, moveExisting }) =>
441
+ runTool(() =>
442
+ api.json(
443
+ `/mail/mailboxes/${encodeURIComponent(mailboxId)}/blocked-senders`,
444
+ { method: "POST", json: { pattern, moveExisting } }
445
+ )
446
+ )
282
447
  );
283
448
 
284
- server.registerTool(
449
+ tool(MAIL_ORGANIZE_SCOPE)(
285
450
  "unblock_sender",
286
451
  {
287
452
  title: "Unblock sender or domain",
288
- description: "Remove a mailbox block. Mail already moved to Spam stays there. Workspace-wide blocks can only be removed by an administrator.",
453
+ description:
454
+ "Remove a mailbox block. Mail already moved to Spam stays there. Workspace-wide blocks can only be removed by an administrator.",
289
455
  inputSchema: z.object({
290
456
  mailboxId: mailboxIdSchema,
291
457
  pattern: blockPatternSchema,
292
458
  }),
293
459
  annotations: write,
294
460
  },
295
- ({ mailboxId, pattern }) => runTool(() => api.json(apiPath(
296
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/blocked-senders`,
297
- { pattern },
298
- ), { method: "DELETE" })),
299
- );
300
-
301
- server.registerTool(
302
- "list_mail_rules",
303
- {
304
- title: "List mail rules",
305
- description: `List the mailbox's filter rules in the order they run. ${RULE_SEMANTICS}`,
306
- inputSchema: z.object({ mailboxId: mailboxIdSchema }),
307
- annotations: readOnly,
308
- },
309
- ({ mailboxId }) => runTool(() => api.json(
310
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/rules`,
311
- )),
312
- );
313
-
314
- server.registerTool(
315
- "create_mail_rule",
316
- {
317
- title: "Create mail rule",
318
- description: `Create a filter rule shared by everyone using the mailbox, appended to the end of the list. It applies to new mail only; call apply_mail_rule to run it on existing mail. ${RULE_SEMANTICS}`,
319
- inputSchema: mailRuleInputSchema,
320
- annotations: { ...write, idempotentHint: false },
321
- },
322
- ({ mailboxId, ...rule }) => runTool(() => api.json(
323
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/rules`,
324
- { method: "POST", json: rule },
325
- )),
326
- );
327
-
328
- server.registerTool(
329
- "update_mail_rule",
330
- {
331
- title: "Update mail rule",
332
- description: `Replace a rule's name, enabled state, conditions, and actions. ${RULE_SEMANTICS}`,
333
- inputSchema: mailRuleInputSchema.extend({ ruleId: entityIdSchema }),
334
- annotations: write,
335
- },
336
- ({ mailboxId, ruleId, ...rule }) => runTool(() => api.json(
337
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/rules/${encodeURIComponent(ruleId)}`,
338
- { method: "PUT", json: rule },
339
- )),
340
- );
341
-
342
- server.registerTool(
343
- "delete_mail_rule",
344
- {
345
- title: "Delete mail rule",
346
- description: "Delete a mail rule. Mail it already filed stays where it is.",
347
- inputSchema: z.object({ mailboxId: mailboxIdSchema, ruleId: entityIdSchema }),
348
- annotations: { ...write, destructiveHint: true },
349
- },
350
- ({ mailboxId, ruleId }) => runTool(() => api.json(
351
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/rules/${encodeURIComponent(ruleId)}`,
352
- { method: "DELETE" },
353
- )),
354
- );
355
-
356
- server.registerTool(
357
- "reorder_mail_rules",
358
- {
359
- title: "Reorder mail rules",
360
- description: "Set the complete run order of the mailbox's rules. ruleIds must list every existing rule exactly once; otherwise the call fails and the rules should be listed again.",
361
- inputSchema: z.object({
362
- mailboxId: mailboxIdSchema,
363
- ruleIds: z.array(entityIdSchema).max(100),
364
- }),
365
- annotations: write,
366
- },
367
- ({ mailboxId, ruleIds }) => runTool(() => api.json(
368
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/rules-order`,
369
- { method: "PUT", json: { ruleIds } },
370
- )),
371
- );
372
-
373
- server.registerTool(
374
- "apply_mail_rule",
375
- {
376
- title: "Apply mail rule to existing mail",
377
- description: "Run one rule over the newest 5,000 incoming messages already in the mailbox. Matching Inbox conversations move to the rule's destination (a Spam rule also takes archived ones); markRead applies only for the current account. This moves many conversations at once; confirm with the user first.",
378
- inputSchema: z.object({ mailboxId: mailboxIdSchema, ruleId: entityIdSchema }),
379
- annotations: { ...write, idempotentHint: false },
380
- },
381
- ({ mailboxId, ruleId }) => runTool(() => api.json(
382
- `/mail/mailboxes/${encodeURIComponent(mailboxId)}/rules/${encodeURIComponent(ruleId)}/apply`,
383
- { method: "POST" },
384
- )),
461
+ ({ mailboxId, pattern }) =>
462
+ runTool(() =>
463
+ api.json(
464
+ apiPath(
465
+ `/mail/mailboxes/${encodeURIComponent(mailboxId)}/blocked-senders`,
466
+ { pattern }
467
+ ),
468
+ { method: "DELETE" }
469
+ )
470
+ )
385
471
  );
386
472
  }
387
473
 
388
- export function registerAdminSafetyTools(server: McpServer, api: AccountApiClient) {
389
- server.registerTool(
390
- "list_reported_messages",
474
+ export function registerAdminSafetyTools(
475
+ tool: ScopedToolRegistrar,
476
+ api: AccountApiClient
477
+ ) {
478
+ tool(BLOCK_SENDERS_SCOPE)(
479
+ "list_workspace_blocked_senders",
391
480
  {
392
- title: "List reported phishing",
393
- description: "Administrator: list the 200 most recent phishing reports across the workspace (sender, subject, reporter, security snapshot, status, whether the sender or domain is blocked workspace-wide), plus every workspace-wide block. Reported messages can only be inspected through their report.",
394
- inputSchema: z.object({
395
- status: z.enum(["open", "resolved", "dismissed"]).optional()
396
- .describe("Return only reports with this status."),
397
- }),
481
+ title: "List senders blocked for everyone",
482
+ description:
483
+ "Administrator: list the addresses and domains blocked for every mailbox in the workspace, with who blocked each and when.",
398
484
  annotations: readOnly,
399
485
  },
400
- ({ status }) => runTool(async () => {
401
- const result = await api.json("/admin/reported-messages");
402
- if (!status || !Array.isArray(result.reports)) return result;
403
- return {
404
- ...result,
405
- reports: (result.reports as Array<{ status: string }>)
406
- .filter((report) => report.status === status),
407
- };
408
- }),
486
+ () => runTool(() => api.json("/admin/blocked-senders"))
409
487
  );
410
488
 
411
- server.registerTool(
412
- "set_report_status",
413
- {
414
- title: "Resolve or dismiss phishing report",
415
- description: "Administrator: set a phishing report to open, resolved, or dismissed.",
416
- inputSchema: reportStatusSchema.safeExtend({ reportId: entityIdSchema }),
417
- annotations: write,
418
- },
419
- ({ reportId, status }) => runTool(() => api.json(
420
- `/admin/reported-messages/${encodeURIComponent(reportId)}`,
421
- { method: "PATCH", json: { status } },
422
- )),
423
- );
424
-
425
- server.registerTool(
489
+ tool(BLOCK_SENDERS_SCOPE)(
426
490
  "block_sender_for_workspace",
427
491
  {
428
492
  title: "Block sender for everyone",
429
- description: "Administrator: block an address or domain for every mailbox in the workspace; its future mail goes to Spam everywhere, and by default (moveExisting) mail already delivered from it is moved to Spam in every mailbox too. Workspace domains cannot be blocked. Pass reportId to also resolve the phishing report that prompted the block. Confirm with the user first.",
430
- inputSchema: workspaceBlockSchema.safeExtend({ pattern: blockPatternSchema }),
493
+ description:
494
+ "Administrator: block an address or domain for every mailbox in the workspace; its future mail goes to Spam everywhere, and by default (moveExisting) mail already delivered from it is moved to Spam in every mailbox too. Workspace mail domains cannot be blocked. Confirm with the user first.",
495
+ inputSchema: workspaceBlockSchema.safeExtend({
496
+ pattern: blockPatternSchema,
497
+ }),
431
498
  annotations: write,
432
499
  },
433
- (input) => runTool(() => api.json("/admin/blocked-senders", {
434
- method: "POST",
435
- json: input,
436
- })),
500
+ (input) =>
501
+ runTool(() =>
502
+ api.json("/admin/blocked-senders", {
503
+ method: "POST",
504
+ json: input,
505
+ })
506
+ )
437
507
  );
438
508
 
439
- server.registerTool(
509
+ tool(BLOCK_SENDERS_SCOPE)(
440
510
  "unblock_sender_for_workspace",
441
511
  {
442
512
  title: "Remove workspace-wide block",
443
- description: "Administrator: remove a workspace-wide block. Mailbox-level blocks are unaffected.",
513
+ description:
514
+ "Administrator: remove a workspace-wide block. Mailbox-level blocks are unaffected.",
444
515
  inputSchema: z.object({ pattern: blockPatternSchema }),
445
516
  annotations: write,
446
517
  },
447
- ({ pattern }) => runTool(() => api.json(
448
- apiPath("/admin/blocked-senders", { pattern }),
449
- { method: "DELETE" },
450
- )),
518
+ ({ pattern }) =>
519
+ runTool(() =>
520
+ api.json(apiPath("/admin/blocked-senders", { pattern }), {
521
+ method: "DELETE",
522
+ })
523
+ )
451
524
  );
452
525
  }