@zabaca/zbc 0.6.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/commands/add.ts +107 -4
- package/src/commands/secret.test.ts +717 -0
- package/src/commands/secret.ts +429 -0
- package/src/engine/apply.ts +3 -1
- package/src/index.ts +2 -0
- package/templates/CLAUDE.md +1 -1
- package/templates/apps/inbox/package.json +6 -2
- package/templates/apps/inbox/public/index.html +3 -3
- package/templates/apps/inbox/registry.json +3 -3
- package/templates/apps/inbox/worker/inbox-do.ts +291 -36
- package/templates/apps/inbox/worker/index.ts +212 -97
- package/templates/apps/inbox/worker/mcp.ts +279 -0
- package/templates/apps/inbox/worker/send-op.ts +174 -0
- package/templates/apps/inbox/worker/shared.ts +117 -0
- package/templates/apps/inbox/wrangler.jsonc +17 -4
- package/templates/apps/secret-relay/package.json +10 -0
- package/templates/apps/secret-relay/registry.json +11 -0
- package/templates/apps/secret-relay/src/crypto.ts +151 -0
- package/templates/apps/secret-relay/src/page.ts +173 -0
- package/templates/apps/secret-relay/src/relay.ts +139 -0
- package/templates/apps/secret-relay/src/worker.ts +42 -0
- package/templates/apps/secret-relay/wrangler.jsonc +11 -0
- package/templates/infra/modules/cloudflare/index.ts +214 -5
- package/templates/infra/modules/r2/index.ts +137 -0
- package/templates/infra/modules/r2/registry.json +8 -0
|
@@ -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,24 +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
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
*/
|
|
57
|
-
function normalizeMsgId(id: string | undefined | null): string {
|
|
58
|
-
return (id ?? '').replace(/[\s<>]/g, '')
|
|
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
|
|
59
41
|
}
|
|
60
42
|
|
|
61
43
|
/** Constant-time bearer check: compare SHA-256 digests so length never leaks. */
|
|
@@ -79,18 +61,49 @@ function inboxStub(env: Env) {
|
|
|
79
61
|
return env.INBOX.get(env.INBOX.idFromName('inbox'))
|
|
80
62
|
}
|
|
81
63
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
+
}
|
|
90
103
|
}
|
|
91
104
|
|
|
92
105
|
export default {
|
|
93
|
-
async email(message: ForwardableEmailMessage, env: Env): Promise<void> {
|
|
106
|
+
async email(message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext): Promise<void> {
|
|
94
107
|
const id = newId()
|
|
95
108
|
const r2Key = `msgs/${id}`
|
|
96
109
|
|
|
@@ -102,21 +115,21 @@ export default {
|
|
|
102
115
|
|
|
103
116
|
const parsed = await PostalMime.parse(raw)
|
|
104
117
|
const text = parsed.text ?? ''
|
|
105
|
-
const snippet = (text
|
|
106
|
-
.replace(/\s+/g, ' ')
|
|
107
|
-
.trim()
|
|
108
|
-
.slice(0, 200)
|
|
118
|
+
const snippet = makeSnippet(text, parsed.html ?? '')
|
|
109
119
|
|
|
110
|
-
|
|
120
|
+
const stub = inboxStub(env)
|
|
121
|
+
const fromAddr = parsed.from?.address ?? message.from
|
|
122
|
+
const subject = parsed.subject ?? ''
|
|
123
|
+
const { threadId } = await stub.insert({
|
|
111
124
|
id,
|
|
112
125
|
direction: 'inbound',
|
|
113
126
|
in_reply_to: normalizeMsgId(parsed.inReplyTo),
|
|
114
127
|
message_id: normalizeMsgId(parsed.messageId),
|
|
115
128
|
// Prefer the header From (what the sender shows as) over the SMTP
|
|
116
129
|
// envelope sender (often a bounce address like bounces@cf-bounce.…).
|
|
117
|
-
from_addr:
|
|
130
|
+
from_addr: fromAddr,
|
|
118
131
|
to_addr: message.to,
|
|
119
|
-
subject
|
|
132
|
+
subject,
|
|
120
133
|
date: parsed.date ?? new Date().toISOString(),
|
|
121
134
|
snippet,
|
|
122
135
|
text_body: text,
|
|
@@ -131,13 +144,34 @@ export default {
|
|
|
131
144
|
),
|
|
132
145
|
size: raw.byteLength,
|
|
133
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
|
+
)
|
|
134
168
|
},
|
|
135
169
|
|
|
136
|
-
async fetch(request: Request, env: Env): Promise<Response> {
|
|
170
|
+
async fetch(request: Request, env: Env, _ctx: ExecutionContext): Promise<Response> {
|
|
137
171
|
const url = new URL(request.url)
|
|
138
172
|
const { pathname } = url
|
|
139
173
|
|
|
140
|
-
if (!pathname.startsWith('/api/')) {
|
|
174
|
+
if (pathname !== '/mcp' && !pathname.startsWith('/api/')) {
|
|
141
175
|
return env.ASSETS.fetch(request)
|
|
142
176
|
}
|
|
143
177
|
|
|
@@ -147,11 +181,25 @@ export default {
|
|
|
147
181
|
|
|
148
182
|
const stub = inboxStub(env)
|
|
149
183
|
|
|
150
|
-
// GET /
|
|
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=
|
|
151
190
|
if (pathname === '/api/messages' && request.method === 'GET') {
|
|
152
191
|
const limit = Number(url.searchParams.get('limit') ?? '50')
|
|
153
192
|
const cursor = url.searchParams.get('cursor') ?? undefined
|
|
154
|
-
|
|
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) })
|
|
155
203
|
}
|
|
156
204
|
|
|
157
205
|
// GET /api/threads?limit=&cursor= — newest-first, one row per thread
|
|
@@ -168,7 +216,7 @@ export default {
|
|
|
168
216
|
return messages.length ? json({ messages }) : json({ error: 'not found' }, 404)
|
|
169
217
|
}
|
|
170
218
|
|
|
171
|
-
// POST /api/send
|
|
219
|
+
// POST /api/send — immediate, or queued for the DO alarm when sendAt set
|
|
172
220
|
if (pathname === '/api/send' && request.method === 'POST') {
|
|
173
221
|
let body: SendBody
|
|
174
222
|
try {
|
|
@@ -176,61 +224,128 @@ export default {
|
|
|
176
224
|
} catch {
|
|
177
225
|
return json({ error: 'invalid JSON body' }, 400)
|
|
178
226
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
const from = body.from ?? env.DEFAULT_FROM
|
|
183
|
-
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
|
+
}
|
|
184
230
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
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
|
+
}
|
|
236
|
+
|
|
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
|
+
}
|
|
195
243
|
|
|
244
|
+
// POST /api/drafts — store an outbound message without sending it
|
|
245
|
+
if (pathname === '/api/drafts' && request.method === 'POST') {
|
|
246
|
+
let body: SendBody
|
|
196
247
|
try {
|
|
197
|
-
await
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
subject: body.subject,
|
|
201
|
-
...(body.text ? { text: body.text } : {}),
|
|
202
|
-
...(body.html ? { html: body.html } : {}),
|
|
203
|
-
...(headers ? { headers } : {}),
|
|
204
|
-
})
|
|
205
|
-
} catch (err) {
|
|
206
|
-
return json({ error: `send failed: ${(err as Error).message}` }, 502)
|
|
248
|
+
body = (await request.json()) as SendBody
|
|
249
|
+
} catch {
|
|
250
|
+
return json({ error: 'invalid JSON body' }, 400)
|
|
207
251
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
// form), so r2_key stays empty and /raw 404s for these.
|
|
252
|
+
// Drafts may be partial — completeness is enforced at send time.
|
|
253
|
+
const id = newId()
|
|
254
|
+
const from = body.from ?? env.DEFAULT_FROM ?? ''
|
|
212
255
|
const text = body.text ?? ''
|
|
213
|
-
|
|
214
|
-
.replace(/\s+/g, ' ')
|
|
215
|
-
.trim()
|
|
216
|
-
.slice(0, 200)
|
|
217
|
-
const { threadId } = await stub.insert({
|
|
256
|
+
await stub.insert({
|
|
218
257
|
id,
|
|
258
|
+
status: 'draft',
|
|
219
259
|
direction: 'outbound',
|
|
220
|
-
in_reply_to: inReplyTo,
|
|
221
|
-
message_id:
|
|
260
|
+
in_reply_to: normalizeMsgId(body.inReplyTo),
|
|
261
|
+
message_id: `${id}@${from.split('@')[1] || 'localhost'}`,
|
|
222
262
|
from_addr: from,
|
|
223
|
-
to_addr: body.to,
|
|
224
|
-
subject: body.subject,
|
|
263
|
+
to_addr: body.to ?? '',
|
|
264
|
+
subject: body.subject ?? '',
|
|
225
265
|
date: new Date().toISOString(),
|
|
226
|
-
snippet,
|
|
266
|
+
snippet: makeSnippet(text, body.html ?? ''),
|
|
227
267
|
text_body: text,
|
|
228
268
|
html_body: body.html ?? '',
|
|
229
269
|
r2_key: '',
|
|
230
270
|
attachments_json: '[]',
|
|
231
271
|
size: text.length + (body.html?.length ?? 0),
|
|
232
272
|
})
|
|
233
|
-
return json({ ok: true, id,
|
|
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
|
+
: {}),
|
|
306
|
+
})
|
|
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)
|
|
313
|
+
}
|
|
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
|
+
})
|
|
234
349
|
}
|
|
235
350
|
|
|
236
351
|
// /api/messages/:id[/raw]
|
|
@@ -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
|
+
}
|