@zabaca/zbc 0.6.1 → 0.7.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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Inbox Worker: an agent-accessible inbox for your email domain.
2
+ * Inbox Worker: an agent-accessible email inbox.
3
3
  *
4
4
  * - `email()` handler: Email Routing (catch-all) delivers inbound mail here.
5
5
  * Raw MIME → R2; parsed metadata + bodies → the Inbox Durable Object.
@@ -8,27 +8,12 @@
8
8
  */
9
9
  import PostalMime from 'postal-mime'
10
10
  import { Inbox } from './inbox-do'
11
+ import { handleMcp } from './mcp'
12
+ import { type SendBody, performDraftSend, performSend } from './send-op'
13
+ import { type SendEmailBinding, emitWebhook, makeSnippet, newId, normalizeMsgId } from './shared'
11
14
 
12
15
  export { Inbox }
13
16
 
14
- /**
15
- * Email Service send binding (the NEW object-based API, not the legacy
16
- * EmailMessage one). The legacy `new EmailMessage(from, to, raw)` path routes
17
- * through Email Routing and only delivers to VERIFIED destination addresses;
18
- * the object form goes through Email Sending and accepts any recipient as
19
- * long as the From domain is onboarded.
20
- */
21
- interface SendEmailBinding {
22
- send(message: {
23
- from: string
24
- to: string
25
- subject: string
26
- text?: string
27
- html?: string
28
- headers?: Record<string, string>
29
- }): Promise<unknown>
30
- }
31
-
32
17
  export interface Env {
33
18
  ASSETS: { fetch: (request: Request) => Promise<Response> }
34
19
  INBOX: DurableObjectNamespace<Inbox>
@@ -38,16 +23,21 @@ export interface Env {
38
23
  INBOX_TOKEN?: string
39
24
  /** Default From address for /api/send (wrangler var). */
40
25
  DEFAULT_FROM?: string
41
- }
42
-
43
- /** Time-ordered id: ms timestamp (base36, padded) + random suffix. Sortable as TEXT. */
44
- function newId(): string {
45
- const time = Date.now().toString(36).padStart(9, '0')
46
- const rand = crypto.getRandomValues(new Uint8Array(8))
47
- const suffix = Array.from(rand, (b) => b.toString(36).padStart(2, '0'))
48
- .join('')
49
- .slice(0, 12)
50
- return `${time}-${suffix}`
26
+ /**
27
+ * Optional webhook: POSTed a JSON event on every received/sent message.
28
+ * Best-effort (one retry, never blocks mail handling). Signed with
29
+ * WEBHOOK_SECRET when set (x-inbox-signature: sha256=<hex HMAC of body>).
30
+ */
31
+ WEBHOOK_URL?: string
32
+ WEBHOOK_SECRET?: string
33
+ /**
34
+ * Optional inbound labeling: when both ANTHROPIC_API_KEY (worker secret)
35
+ * and LABELS (comma-separated set, e.g. "billing,support,spam,other") are
36
+ * set, each received message is classified into one label after insert.
37
+ * Best-effort — a classifier failure just leaves label = ''.
38
+ */
39
+ ANTHROPIC_API_KEY?: string
40
+ LABELS?: string
51
41
  }
52
42
 
53
43
  /** Constant-time bearer check: compare SHA-256 digests so length never leaks. */
@@ -71,18 +61,49 @@ function inboxStub(env: Env) {
71
61
  return env.INBOX.get(env.INBOX.idFromName('inbox'))
72
62
  }
73
63
 
74
- interface SendBody {
75
- to: string
76
- subject: string
77
- text?: string
78
- html?: string
79
- from?: string
80
- /** RFC 5322 Message-ID of the message being replied to → In-Reply-To/References. */
81
- inReplyTo?: string
64
+ /**
65
+ * Classify an inbound message into one of env.LABELS via the Anthropic API.
66
+ * Returns '' (no label) on any failure or an answer outside the label set —
67
+ * labeling is strictly best-effort and must never block ingestion.
68
+ */
69
+ async function classify(env: Env, subject: string, snippet: string): Promise<string> {
70
+ if (!env.ANTHROPIC_API_KEY || !env.LABELS) return ''
71
+ const labels = env.LABELS.split(',')
72
+ .map((l) => l.trim())
73
+ .filter(Boolean)
74
+ if (labels.length === 0) return ''
75
+ try {
76
+ const res = await fetch('https://api.anthropic.com/v1/messages', {
77
+ method: 'POST',
78
+ headers: {
79
+ 'x-api-key': env.ANTHROPIC_API_KEY,
80
+ 'anthropic-version': '2023-06-01',
81
+ 'content-type': 'application/json',
82
+ },
83
+ body: JSON.stringify({
84
+ model: 'claude-haiku-4-5-20251001',
85
+ max_tokens: 16,
86
+ messages: [
87
+ {
88
+ role: 'user',
89
+ content:
90
+ `Classify this email into exactly one of these labels: ${labels.join(', ')}.\n` +
91
+ `Reply with the label only.\n\nSubject: ${subject}\nBody: ${snippet}`,
92
+ },
93
+ ],
94
+ }),
95
+ })
96
+ if (!res.ok) return ''
97
+ const data = (await res.json()) as { content?: Array<{ type: string; text?: string }> }
98
+ const answer = (data.content?.find((b) => b.type === 'text')?.text ?? '').trim().toLowerCase()
99
+ return labels.find((l) => l.toLowerCase() === answer) ?? ''
100
+ } catch {
101
+ return ''
102
+ }
82
103
  }
83
104
 
84
105
  export default {
85
- async email(message: ForwardableEmailMessage, env: Env): Promise<void> {
106
+ async email(message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext): Promise<void> {
86
107
  const id = newId()
87
108
  const r2Key = `msgs/${id}`
88
109
 
@@ -94,19 +115,21 @@ export default {
94
115
 
95
116
  const parsed = await PostalMime.parse(raw)
96
117
  const text = parsed.text ?? ''
97
- const snippet = (text || (parsed.html ?? '').replace(/<[^>]+>/g, ' '))
98
- .replace(/\s+/g, ' ')
99
- .trim()
100
- .slice(0, 200)
118
+ const snippet = makeSnippet(text, parsed.html ?? '')
101
119
 
102
- await inboxStub(env).insert({
120
+ const stub = inboxStub(env)
121
+ const fromAddr = parsed.from?.address ?? message.from
122
+ const subject = parsed.subject ?? ''
123
+ const { threadId } = await stub.insert({
103
124
  id,
104
- message_id: parsed.messageId ?? '',
125
+ direction: 'inbound',
126
+ in_reply_to: normalizeMsgId(parsed.inReplyTo),
127
+ message_id: normalizeMsgId(parsed.messageId),
105
128
  // Prefer the header From (what the sender shows as) over the SMTP
106
129
  // envelope sender (often a bounce address like bounces@cf-bounce.…).
107
- from_addr: parsed.from?.address ?? message.from,
130
+ from_addr: fromAddr,
108
131
  to_addr: message.to,
109
- subject: parsed.subject ?? '',
132
+ subject,
110
133
  date: parsed.date ?? new Date().toISOString(),
111
134
  snippet,
112
135
  text_body: text,
@@ -121,13 +144,34 @@ export default {
121
144
  ),
122
145
  size: raw.byteLength,
123
146
  })
147
+
148
+ // Post-insert extras, off the critical path: webhook push + optional
149
+ // labeling. waitUntil keeps the email handler's completion independent of
150
+ // either — a webhook receiver outage or classifier failure never bounces
151
+ // mail.
152
+ ctx.waitUntil(
153
+ emitWebhook(env, 'message.received', {
154
+ id,
155
+ threadId,
156
+ from: fromAddr,
157
+ to: message.to,
158
+ subject,
159
+ snippet,
160
+ direction: 'inbound',
161
+ }),
162
+ )
163
+ ctx.waitUntil(
164
+ classify(env, subject, snippet).then((label) =>
165
+ label ? stub.setLabel(id, label) : undefined,
166
+ ),
167
+ )
124
168
  },
125
169
 
126
- async fetch(request: Request, env: Env): Promise<Response> {
170
+ async fetch(request: Request, env: Env, _ctx: ExecutionContext): Promise<Response> {
127
171
  const url = new URL(request.url)
128
172
  const { pathname } = url
129
173
 
130
- if (!pathname.startsWith('/api/')) {
174
+ if (pathname !== '/mcp' && !pathname.startsWith('/api/')) {
131
175
  return env.ASSETS.fetch(request)
132
176
  }
133
177
 
@@ -137,14 +181,42 @@ export default {
137
181
 
138
182
  const stub = inboxStub(env)
139
183
 
140
- // GET /api/messages?limit=&cursor=
184
+ // POST/GET/DELETE /mcp — MCP server (Streamable HTTP), same bearer token
185
+ if (pathname === '/mcp') {
186
+ return handleMcp(request, { env, stub })
187
+ }
188
+
189
+ // GET /api/messages?limit=&cursor=&label=
141
190
  if (pathname === '/api/messages' && request.method === 'GET') {
142
191
  const limit = Number(url.searchParams.get('limit') ?? '50')
143
192
  const cursor = url.searchParams.get('cursor') ?? undefined
144
- return json(await stub.list(Number.isFinite(limit) ? limit : 50, cursor))
193
+ const label = url.searchParams.get('label') ?? undefined
194
+ return json(await stub.list(Number.isFinite(limit) ? limit : 50, cursor, label))
195
+ }
196
+
197
+ // GET /api/search?q=&limit= — keyword match over subject + text body
198
+ if (pathname === '/api/search' && request.method === 'GET') {
199
+ const q = url.searchParams.get('q') ?? ''
200
+ if (!q.trim()) return json({ error: 'required: q' }, 400)
201
+ const limit = Number(url.searchParams.get('limit') ?? '50')
202
+ return json({ messages: await stub.search(q.trim(), Number.isFinite(limit) ? limit : 50) })
203
+ }
204
+
205
+ // GET /api/threads?limit=&cursor= — newest-first, one row per thread
206
+ if (pathname === '/api/threads' && request.method === 'GET') {
207
+ const limit = Number(url.searchParams.get('limit') ?? '50')
208
+ const cursor = url.searchParams.get('cursor') ?? undefined
209
+ return json(await stub.listThreads(Number.isFinite(limit) ? limit : 50, cursor))
145
210
  }
146
211
 
147
- // POST /api/send
212
+ // GET /api/threads/:id — all messages in the thread, oldest-first
213
+ const threadMatch = pathname.match(/^\/api\/threads\/([^/]+)$/)
214
+ if (threadMatch && request.method === 'GET') {
215
+ const messages = await stub.getThread(threadMatch[1]!)
216
+ return messages.length ? json({ messages }) : json({ error: 'not found' }, 404)
217
+ }
218
+
219
+ // POST /api/send — immediate, or queued for the DO alarm when sendAt set
148
220
  if (pathname === '/api/send' && request.method === 'POST') {
149
221
  let body: SendBody
150
222
  try {
@@ -152,29 +224,128 @@ export default {
152
224
  } catch {
153
225
  return json({ error: 'invalid JSON body' }, 400)
154
226
  }
155
- if (!body.to || !body.subject || (!body.text && !body.html)) {
156
- return json({ error: 'required: to, subject, and text or html' }, 400)
157
- }
158
- const from = body.from ?? env.DEFAULT_FROM
159
- if (!from) return json({ error: 'no from address (set DEFAULT_FROM or pass from)' }, 400)
227
+ const outcome = await performSend(env, stub, body)
228
+ return json(outcome.body, outcome.status)
229
+ }
230
+
231
+ // GET /api/scheduled — pending + failed scheduled sends, soonest first
232
+ if (pathname === '/api/scheduled' && request.method === 'GET') {
233
+ const limit = Number(url.searchParams.get('limit') ?? '50')
234
+ return json({ scheduled: await stub.listScheduled(Number.isFinite(limit) ? limit : 50) })
235
+ }
160
236
 
161
- const headers: Record<string, string> | undefined = body.inReplyTo
162
- ? { 'In-Reply-To': body.inReplyTo, References: body.inReplyTo }
163
- : undefined
237
+ // DELETE /api/scheduled/:id — cancel a pending (or dismiss a failed) send
238
+ const schedMatch = pathname.match(/^\/api\/scheduled\/([^/]+)$/)
239
+ if (schedMatch && request.method === 'DELETE') {
240
+ const cancelled = await stub.cancelScheduled(schedMatch[1]!)
241
+ return cancelled ? json({ ok: true }) : json({ error: 'not a scheduled send' }, 404)
242
+ }
164
243
 
244
+ // POST /api/drafts — store an outbound message without sending it
245
+ if (pathname === '/api/drafts' && request.method === 'POST') {
246
+ let body: SendBody
165
247
  try {
166
- await env.EMAIL.send({
167
- from,
168
- to: body.to,
169
- subject: body.subject,
170
- ...(body.text ? { text: body.text } : {}),
171
- ...(body.html ? { html: body.html } : {}),
172
- ...(headers ? { headers } : {}),
248
+ body = (await request.json()) as SendBody
249
+ } catch {
250
+ return json({ error: 'invalid JSON body' }, 400)
251
+ }
252
+ // Drafts may be partial — completeness is enforced at send time.
253
+ const id = newId()
254
+ const from = body.from ?? env.DEFAULT_FROM ?? ''
255
+ const text = body.text ?? ''
256
+ await stub.insert({
257
+ id,
258
+ status: 'draft',
259
+ direction: 'outbound',
260
+ in_reply_to: normalizeMsgId(body.inReplyTo),
261
+ message_id: `${id}@${from.split('@')[1] || 'localhost'}`,
262
+ from_addr: from,
263
+ to_addr: body.to ?? '',
264
+ subject: body.subject ?? '',
265
+ date: new Date().toISOString(),
266
+ snippet: makeSnippet(text, body.html ?? ''),
267
+ text_body: text,
268
+ html_body: body.html ?? '',
269
+ r2_key: '',
270
+ attachments_json: '[]',
271
+ size: text.length + (body.html?.length ?? 0),
272
+ })
273
+ return json({ ok: true, id, status: 'draft' }, 201)
274
+ }
275
+
276
+ // GET /api/drafts
277
+ if (pathname === '/api/drafts' && request.method === 'GET') {
278
+ const limit = Number(url.searchParams.get('limit') ?? '50')
279
+ return json({ drafts: await stub.listDrafts(Number.isFinite(limit) ? limit : 50) })
280
+ }
281
+
282
+ // PUT /api/drafts/:id | POST /api/drafts/:id/send
283
+ const draftMatch = pathname.match(/^\/api\/drafts\/([^/]+)(\/send)?$/)
284
+ if (draftMatch) {
285
+ const [, draftId, sendSuffix] = draftMatch
286
+
287
+ if (!sendSuffix && request.method === 'PUT') {
288
+ let body: SendBody
289
+ try {
290
+ body = (await request.json()) as SendBody
291
+ } catch {
292
+ return json({ error: 'invalid JSON body' }, 400)
293
+ }
294
+ const text = body.text
295
+ const html = body.html
296
+ const updated = await stub.updateDraft(draftId!, {
297
+ ...(body.from !== undefined ? { from_addr: body.from } : {}),
298
+ ...(body.to !== undefined ? { to_addr: body.to } : {}),
299
+ ...(body.subject !== undefined ? { subject: body.subject } : {}),
300
+ ...(text !== undefined ? { text_body: text } : {}),
301
+ ...(html !== undefined ? { html_body: html } : {}),
302
+ ...(body.inReplyTo !== undefined ? { in_reply_to: normalizeMsgId(body.inReplyTo) } : {}),
303
+ ...(text !== undefined || html !== undefined
304
+ ? { snippet: makeSnippet(text ?? '', html ?? '') }
305
+ : {}),
173
306
  })
174
- } catch (err) {
175
- return json({ error: `send failed: ${(err as Error).message}` }, 502)
307
+ return updated ? json({ ok: true, id: draftId }) : json({ error: 'not a draft' }, 404)
308
+ }
309
+
310
+ if (sendSuffix && request.method === 'POST') {
311
+ const outcome = await performDraftSend(env, stub, draftId!)
312
+ return json(outcome.body, outcome.status)
176
313
  }
177
- return json({ ok: true, from, to: body.to })
314
+ if (!sendSuffix && request.method === 'GET') {
315
+ const draft = await stub.get(draftId!)
316
+ return draft && draft.status === 'draft' ? json(draft) : json({ error: 'not a draft' }, 404)
317
+ }
318
+ if (!sendSuffix && request.method === 'DELETE') {
319
+ const draft = await stub.get(draftId!)
320
+ if (!draft || draft.status !== 'draft') return json({ error: 'not a draft' }, 404)
321
+ await stub.delete(draftId!)
322
+ return json({ ok: true })
323
+ }
324
+ }
325
+
326
+ // GET /api/messages/:id/attachments/:n — raw bytes of one attachment.
327
+ // Re-parses the R2 MIME blob per request (cheap at the 5 MiB cap) rather
328
+ // than pre-splitting attachments at write time.
329
+ const attMatch = pathname.match(/^\/api\/messages\/([^/]+)\/attachments\/(\d+)$/)
330
+ if (attMatch && request.method === 'GET') {
331
+ const msg = await stub.get(attMatch[1]!)
332
+ if (!msg) return json({ error: 'not found' }, 404)
333
+ if (!msg.r2_key) return json({ error: 'no raw MIME (outbound message)' }, 404)
334
+ const obj = await env.RAW.get(msg.r2_key)
335
+ if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
336
+ const parsed = await PostalMime.parse(await obj.arrayBuffer())
337
+ const n = Number(attMatch[2])
338
+ const att = (parsed.attachments ?? [])[n]
339
+ if (!att) return json({ error: `no attachment at index ${n}` }, 404)
340
+ const body =
341
+ typeof att.content === 'string' ? new TextEncoder().encode(att.content) : att.content
342
+ return new Response(body, {
343
+ headers: {
344
+ 'content-type': att.mimeType || 'application/octet-stream',
345
+ 'content-disposition': `attachment; filename="${(att.filename ?? 'attachment').replace(/["\r\n]/g, '')}"`,
346
+ 'cache-control': 'no-store',
347
+ },
348
+ })
178
349
  }
179
350
 
180
351
  // /api/messages/:id[/raw]
@@ -185,6 +356,7 @@ export default {
185
356
  if (rawSuffix && request.method === 'GET') {
186
357
  const msg = await stub.get(id!)
187
358
  if (!msg) return json({ error: 'not found' }, 404)
359
+ if (!msg.r2_key) return json({ error: 'no raw MIME (outbound message)' }, 404)
188
360
  const obj = await env.RAW.get(msg.r2_key)
189
361
  if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
190
362
  return new Response(obj.body, {
@@ -0,0 +1,279 @@
1
+ import { StreamableHTTPTransport } from '@hono/mcp'
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
3
+ import { Hono } from 'hono'
4
+ import { z } from 'zod'
5
+ import type {
6
+ Inbox,
7
+ InsertMessage,
8
+ MessageFull,
9
+ MessageMeta,
10
+ ScheduledMeta,
11
+ ThreadMeta,
12
+ } from './inbox-do'
13
+ import { type SendEnv, performDraftSend, performSend } from './send-op'
14
+ import { makeSnippet, newId, normalizeMsgId } from './shared'
15
+
16
+ /**
17
+ * MCP server over the inbox — the same operations as /api/*, exposed as
18
+ * tools for MCP clients (Claude Code, claude.ai, etc.) at POST /mcp with
19
+ * Streamable HTTP transport (cedarpad's pattern: stateless per request, a
20
+ * fresh McpServer each call — workers isolates hold no session).
21
+ *
22
+ * Auth is the SAME bearer token as /api/* — the caller checks it before
23
+ * invoking this, and MCP clients send it as a normal Authorization header.
24
+ * Tools call the Durable Object stub directly (a Worker cannot fetch its
25
+ * own routes), so this file is wiring, not logic.
26
+ */
27
+
28
+ const text = (v: unknown) => ({
29
+ content: [{ type: 'text' as const, text: JSON.stringify(v, null, 2) }],
30
+ })
31
+
32
+ /** Unwrap a SendOutcome into MCP result-or-error. */
33
+ const outcome = (o: { status: number; body: Record<string, unknown> }) => {
34
+ if (o.status >= 400) throw new Error(String(o.body.error ?? `failed (${o.status})`))
35
+ return text(o.body)
36
+ }
37
+
38
+ /**
39
+ * The DO surface the tools use, with plain Promise returns. The raw
40
+ * DurableObjectStub<Inbox> type expands workers-types' recursive RPC
41
+ * serialization generics inside every registerTool inference and trips
42
+ * TS2589 — this narrow view is the same calls without the type machinery.
43
+ */
44
+ interface InboxApi {
45
+ list(
46
+ limit: number,
47
+ cursor?: string,
48
+ label?: string,
49
+ ): Promise<{ messages: MessageMeta[]; nextCursor: string | null }>
50
+ listThreads(
51
+ limit: number,
52
+ cursor?: string,
53
+ ): Promise<{ threads: ThreadMeta[]; nextCursor: string | null }>
54
+ getThread(threadId: string): Promise<MessageFull[]>
55
+ get(id: string): Promise<MessageFull | null>
56
+ search(q: string, limit: number): Promise<MessageMeta[]>
57
+ insert(msg: InsertMessage): Promise<{ threadId: string }>
58
+ listDrafts(limit: number): Promise<MessageMeta[]>
59
+ updateDraft(id: string, fields: Record<string, string>): Promise<boolean>
60
+ listScheduled(limit: number): Promise<ScheduledMeta[]>
61
+ cancelScheduled(id: string): Promise<boolean>
62
+ delete(id: string): Promise<string | null>
63
+ }
64
+
65
+ interface McpDeps {
66
+ env: SendEnv & { RAW: R2Bucket }
67
+ stub: DurableObjectStub<Inbox>
68
+ }
69
+
70
+ export async function handleMcp(request: Request, deps: McpDeps): Promise<Response> {
71
+ const { env } = deps
72
+ const stub = deps.stub as unknown as InboxApi
73
+ const server = new McpServer({ name: 'inbox', version: '1.0.0' })
74
+
75
+ server.registerTool(
76
+ 'list_threads',
77
+ {
78
+ description:
79
+ 'List conversation threads, newest first. Each row is the latest message of its thread plus thread_count. Page with cursor = the last id from the previous page.',
80
+ inputSchema: { limit: z.number().optional(), cursor: z.string().optional() },
81
+ },
82
+ async ({ limit, cursor }) => text(await stub.listThreads(limit ?? 50, cursor)),
83
+ )
84
+ server.registerTool(
85
+ 'read_thread',
86
+ {
87
+ description:
88
+ 'Read every message in a thread (oldest first) with full text/html bodies and attachment metadata.',
89
+ inputSchema: { thread_id: z.string() },
90
+ },
91
+ async ({ thread_id }) => {
92
+ const messages = await stub.getThread(thread_id)
93
+ if (!messages.length) throw new Error('thread not found')
94
+ return text({ messages })
95
+ },
96
+ )
97
+ server.registerTool(
98
+ 'list_messages',
99
+ {
100
+ description:
101
+ 'List individual messages, newest first (both directions; drafts and scheduled excluded). Optional label filter (see labeling). Page with cursor.',
102
+ inputSchema: {
103
+ limit: z.number().optional(),
104
+ cursor: z.string().optional(),
105
+ label: z.string().optional(),
106
+ },
107
+ },
108
+ async ({ limit, cursor, label }) => text(await stub.list(limit ?? 50, cursor, label)),
109
+ )
110
+ server.registerTool(
111
+ 'read_message',
112
+ {
113
+ description: 'Read one message by id: full bodies, headers, attachment metadata.',
114
+ inputSchema: { id: z.string() },
115
+ },
116
+ async ({ id }) => {
117
+ const msg = await stub.get(id)
118
+ if (!msg) throw new Error('message not found')
119
+ return text(msg)
120
+ },
121
+ )
122
+ server.registerTool(
123
+ 'search_messages',
124
+ {
125
+ description: 'Keyword search over subject + text body (case-insensitive), newest first.',
126
+ inputSchema: { q: z.string(), limit: z.number().optional() },
127
+ },
128
+ async ({ q, limit }) => text({ messages: await stub.search(q, limit ?? 50) }),
129
+ )
130
+ server.registerTool(
131
+ 'send_email',
132
+ {
133
+ description:
134
+ 'Send an email now, or pass send_at (ISO timestamp) to schedule it. from defaults to DEFAULT_FROM. To reply into an existing thread, pass in_reply_to = the message_id of the message being replied to.',
135
+ inputSchema: {
136
+ to: z.string(),
137
+ subject: z.string(),
138
+ text: z.string().optional(),
139
+ html: z.string().optional(),
140
+ from: z.string().optional(),
141
+ in_reply_to: z.string().optional(),
142
+ send_at: z.string().optional(),
143
+ },
144
+ },
145
+ async (input) =>
146
+ outcome(
147
+ await performSend(env, deps.stub, {
148
+ to: input.to,
149
+ subject: input.subject,
150
+ text: input.text,
151
+ html: input.html,
152
+ from: input.from,
153
+ inReplyTo: input.in_reply_to,
154
+ sendAt: input.send_at,
155
+ }),
156
+ ),
157
+ )
158
+ server.registerTool(
159
+ 'create_draft',
160
+ {
161
+ description:
162
+ 'Store an outbound draft without sending. All fields optional — completeness is checked at send_draft time.',
163
+ inputSchema: {
164
+ to: z.string().optional(),
165
+ subject: z.string().optional(),
166
+ text: z.string().optional(),
167
+ html: z.string().optional(),
168
+ from: z.string().optional(),
169
+ in_reply_to: z.string().optional(),
170
+ },
171
+ },
172
+ async (input) => {
173
+ const id = newId()
174
+ const from = input.from ?? env.DEFAULT_FROM ?? ''
175
+ const bodyText = input.text ?? ''
176
+ await stub.insert({
177
+ id,
178
+ status: 'draft',
179
+ direction: 'outbound',
180
+ in_reply_to: normalizeMsgId(input.in_reply_to),
181
+ message_id: `${id}@${from.split('@')[1] || 'localhost'}`,
182
+ from_addr: from,
183
+ to_addr: input.to ?? '',
184
+ subject: input.subject ?? '',
185
+ date: new Date().toISOString(),
186
+ snippet: makeSnippet(bodyText, input.html ?? ''),
187
+ text_body: bodyText,
188
+ html_body: input.html ?? '',
189
+ r2_key: '',
190
+ attachments_json: '[]',
191
+ size: bodyText.length + (input.html?.length ?? 0),
192
+ })
193
+ return text({ ok: true, id, status: 'draft' })
194
+ },
195
+ )
196
+ server.registerTool(
197
+ 'list_drafts',
198
+ { description: 'List unsent drafts, newest first.' },
199
+ async () => text({ drafts: await stub.listDrafts(50) }),
200
+ )
201
+ server.registerTool(
202
+ 'update_draft',
203
+ {
204
+ description: 'Update an unsent draft. Only the fields passed change.',
205
+ inputSchema: {
206
+ id: z.string(),
207
+ to: z.string().optional(),
208
+ subject: z.string().optional(),
209
+ text: z.string().optional(),
210
+ html: z.string().optional(),
211
+ from: z.string().optional(),
212
+ in_reply_to: z.string().optional(),
213
+ },
214
+ },
215
+ async ({ id, ...input }) => {
216
+ const updated = await stub.updateDraft(id, {
217
+ ...(input.from !== undefined ? { from_addr: input.from } : {}),
218
+ ...(input.to !== undefined ? { to_addr: input.to } : {}),
219
+ ...(input.subject !== undefined ? { subject: input.subject } : {}),
220
+ ...(input.text !== undefined ? { text_body: input.text } : {}),
221
+ ...(input.html !== undefined ? { html_body: input.html } : {}),
222
+ ...(input.in_reply_to !== undefined
223
+ ? { in_reply_to: normalizeMsgId(input.in_reply_to) }
224
+ : {}),
225
+ ...(input.text !== undefined || input.html !== undefined
226
+ ? { snippet: makeSnippet(input.text ?? '', input.html ?? '') }
227
+ : {}),
228
+ })
229
+ if (!updated) throw new Error('not a draft')
230
+ return text({ ok: true, id })
231
+ },
232
+ )
233
+ server.registerTool(
234
+ 'send_draft',
235
+ {
236
+ description: 'Send an existing draft (must have to, subject, and text or html).',
237
+ inputSchema: { id: z.string() },
238
+ },
239
+ async ({ id }) => outcome(await performDraftSend(env, deps.stub, id)),
240
+ )
241
+ server.registerTool(
242
+ 'list_scheduled',
243
+ {
244
+ description:
245
+ 'List pending scheduled sends (and failed ones, with send_error), soonest first.',
246
+ },
247
+ async () => text({ scheduled: await stub.listScheduled(50) }),
248
+ )
249
+ server.registerTool(
250
+ 'cancel_scheduled',
251
+ {
252
+ description: 'Cancel a pending scheduled send (or dismiss a failed one). Deletes the row.',
253
+ inputSchema: { id: z.string() },
254
+ },
255
+ async ({ id }) => {
256
+ if (!(await stub.cancelScheduled(id))) throw new Error('not a scheduled send')
257
+ return text({ ok: true })
258
+ },
259
+ )
260
+ server.registerTool(
261
+ 'delete_message',
262
+ {
263
+ description: 'Delete a message (any status) and its raw MIME blob.',
264
+ inputSchema: { id: z.string() },
265
+ },
266
+ async ({ id }) => {
267
+ const r2Key = await stub.delete(id)
268
+ if (r2Key === null) throw new Error('message not found')
269
+ if (r2Key) await env.RAW.delete(r2Key)
270
+ return text({ ok: true })
271
+ },
272
+ )
273
+
274
+ const transport = new StreamableHTTPTransport()
275
+ await server.connect(transport)
276
+ const app = new Hono()
277
+ app.all('/mcp', (c) => transport.handleRequest(c))
278
+ return app.fetch(request)
279
+ }