@eusend_dev/mcp 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,12 +10,12 @@ SDK. The same server runs two ways — **stdio** (local, launched by your client
10
10
 
11
11
  ## Tools
12
12
 
13
- | Area | Tools |
14
- |------|-------|
15
- | Emails | `send_email`, `list_emails`, `get_email`, `cancel_email` |
16
- | Domains | `list_domains`, `get_domain`, `create_domain` |
17
- | Audiences & contacts | `list_audiences`, `create_audience`, `list_contacts`, `create_contact` |
18
- | Broadcasts | `list_broadcasts`, `get_broadcast`, `create_broadcast`, `send_broadcast` |
13
+ | Area | Tools |
14
+ | -------------------- | ------------------------------------------------------------------------ |
15
+ | Emails | `send_email`, `list_emails`, `get_email`, `cancel_email` |
16
+ | Domains | `list_domains`, `get_domain`, `create_domain` |
17
+ | Audiences & contacts | `list_audiences`, `create_audience`, `list_contacts`, `create_contact` |
18
+ | Broadcasts | `list_broadcasts`, `get_broadcast`, `create_broadcast`, `send_broadcast` |
19
19
 
20
20
  Destructive operations (deleting domains, audiences, contacts, API keys) are intentionally
21
21
  **not** exposed. `send_broadcast` is a bulk send — clients are instructed to confirm first.
@@ -76,16 +76,16 @@ your public host when running behind a proxy.
76
76
 
77
77
  ## Configuration
78
78
 
79
- | Flag | Env | Purpose |
80
- |------|-----|---------|
81
- | `--key` | `EUSEND_API_KEY` | API key (stdio only; HTTP takes it per-request) |
82
- | `--from` | `EUSEND_FROM` / `SENDER_EMAIL_ADDRESS` | Default sender address |
83
- | `--reply-to` | `EUSEND_REPLY_TO` | Default Reply-To |
84
- | `--base-url` | `EUSEND_BASE_URL` | Override the API base URL |
85
- | `--http` | — | Run the HTTP transport instead of stdio |
86
- | `--port` | `MCP_PORT` | HTTP port (default 3000) |
87
- | `--host` | `MCP_HOST` | HTTP bind host (default 127.0.0.1) |
88
- | `--allowed-hosts` | `MCP_ALLOWED_HOSTS` | Comma-separated Host allowlist |
79
+ | Flag | Env | Purpose |
80
+ | ----------------- | -------------------------------------- | ----------------------------------------------- |
81
+ | `--key` | `EUSEND_API_KEY` | API key (stdio only; HTTP takes it per-request) |
82
+ | `--from` | `EUSEND_FROM` / `SENDER_EMAIL_ADDRESS` | Default sender address |
83
+ | `--reply-to` | `EUSEND_REPLY_TO` | Default Reply-To |
84
+ | `--base-url` | `EUSEND_BASE_URL` | Override the API base URL |
85
+ | `--http` | — | Run the HTTP transport instead of stdio |
86
+ | `--port` | `MCP_PORT` | HTTP port (default 3000) |
87
+ | `--host` | `MCP_HOST` | HTTP bind host (default 127.0.0.1) |
88
+ | `--allowed-hosts` | `MCP_ALLOWED_HOSTS` | Comma-separated Host allowlist |
89
89
 
90
90
  ## Development
91
91
 
@@ -1,8 +1,8 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
1
+ import { McpServer, createMcpHandler } from "@modelcontextprotocol/server";
2
2
  import { Eusend } from "@eusend_dev/sdk";
3
3
  import { z } from "zod";
4
4
  import { createServer } from "node:http";
5
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
+ import { hostHeaderValidation, toNodeHandler } from "@modelcontextprotocol/node";
6
6
  //#region src/respond.ts
7
7
  /** Wrap a successful payload as pretty-printed JSON text content. */
8
8
  function ok(data) {
@@ -58,7 +58,7 @@ function registerEmailTools(server, client, config) {
58
58
  server.registerTool("send_email", {
59
59
  title: "Send an email",
60
60
  description: "Send a transactional email through Eusend. Provide `html` or `text` (or both). The sender domain must be verified on the account — use list_domains to check. If `from` is omitted, the server-configured default sender is used.",
61
- inputSchema: {
61
+ inputSchema: z.object({
62
62
  from: z.string().optional().describe("Sender, e.g. \"Acme <hi@acme.com>\". Defaults to the configured sender."),
63
63
  to: recipients.describe("Recipient address or list of addresses."),
64
64
  subject: z.string().describe("Email subject line."),
@@ -67,8 +67,9 @@ function registerEmailTools(server, client, config) {
67
67
  cc: recipients.optional(),
68
68
  bcc: recipients.optional(),
69
69
  replyTo: recipients.optional().describe("Reply-To address(es)."),
70
+ tags: z.record(z.string(), z.string()).optional().describe("Labels for log filtering and webhook routing, e.g. {\"category\": \"password_reset\"}. Names and values allow ASCII letters, numbers, underscores and dashes; max 10 tags."),
70
71
  scheduledAt: z.string().optional().describe("Future send time: ISO 8601 or natural language like \"in 1 hour\". Max 30 days out.")
71
- }
72
+ })
72
73
  }, async (args) => {
73
74
  const from = args.from ?? config.defaultFrom;
74
75
  if (!from) return failText("No sender specified and no default sender configured. Pass `from`, or set EUSEND_FROM / --from on the server.");
@@ -82,29 +83,31 @@ function registerEmailTools(server, client, config) {
82
83
  cc: args.cc,
83
84
  bcc: args.bcc,
84
85
  replyTo: args.replyTo ?? config.defaultReplyTo,
86
+ tags: args.tags,
85
87
  scheduledAt: args.scheduledAt
86
88
  }));
87
89
  });
88
90
  server.registerTool("list_emails", {
89
91
  title: "List emails",
90
92
  description: "List recently sent emails, most recent first. Supports cursor pagination and filtering.",
91
- inputSchema: {
93
+ inputSchema: z.object({
92
94
  limit: z.number().int().min(1).max(100).optional().describe("Max results (1–100)."),
93
95
  cursor: z.string().optional().describe("Pagination cursor from a previous nextCursor."),
94
96
  status: emailStatus.optional().describe("Filter by delivery status."),
95
97
  from: z.string().optional().describe("Filter by sender address."),
96
- to: z.string().optional().describe("Filter by recipient address.")
97
- }
98
+ to: z.string().optional().describe("Filter by recipient address."),
99
+ tag: z.union([z.string(), z.array(z.string())]).optional().describe("Filter by tag: \"category:password_reset\" for an exact pair, or bare \"category\" for any email carrying the tag. An array requires all of them.")
100
+ })
98
101
  }, async (args) => respond(await client.emails.list(args)));
99
102
  server.registerTool("get_email", {
100
103
  title: "Get an email",
101
104
  description: "Fetch a single email by id, including its full delivery event history.",
102
- inputSchema: { id: z.string().describe("The email id returned by send_email or list_emails.") }
105
+ inputSchema: z.object({ id: z.string().describe("The email id returned by send_email or list_emails.") })
103
106
  }, async ({ id }) => respond(await client.emails.get(id)));
104
107
  server.registerTool("cancel_email", {
105
108
  title: "Cancel a scheduled email",
106
109
  description: "Cancel a scheduled email before it sends. Fails once the email has started sending.",
107
- inputSchema: { id: z.string().describe("The id of a scheduled email.") }
110
+ inputSchema: z.object({ id: z.string().describe("The id of a scheduled email.") })
108
111
  }, async ({ id }) => respond(await client.emails.cancel(id)));
109
112
  }
110
113
  //#endregion
@@ -113,17 +116,17 @@ function registerDomainTools(server, client) {
113
116
  server.registerTool("list_domains", {
114
117
  title: "List domains",
115
118
  description: "List sending domains on the account and their verification status.",
116
- inputSchema: {}
119
+ inputSchema: z.object({})
117
120
  }, async () => respond(await client.domains.list()));
118
121
  server.registerTool("get_domain", {
119
122
  title: "Get a domain",
120
123
  description: "Fetch a single domain by id, including its DKIM selector and verification state.",
121
- inputSchema: { id: z.string().describe("The domain id.") }
124
+ inputSchema: z.object({ id: z.string().describe("The domain id.") })
122
125
  }, async ({ id }) => respond(await client.domains.get(id)));
123
126
  server.registerTool("create_domain", {
124
127
  title: "Add a sending domain",
125
128
  description: "Register a new sending domain. Returns the DKIM, SPF, and DMARC DNS records that must be added at the domain's DNS provider before it can send. Present these records to the user.",
126
- inputSchema: { name: z.string().describe("The domain to add, e.g. \"mail.acme.com\".") }
129
+ inputSchema: z.object({ name: z.string().describe("The domain to add, e.g. \"mail.acme.com\".") })
127
130
  }, async ({ name }) => respond(await client.domains.create(name)));
128
131
  }
129
132
  //#endregion
@@ -132,33 +135,33 @@ function registerAudienceTools(server, client) {
132
135
  server.registerTool("list_audiences", {
133
136
  title: "List audiences",
134
137
  description: "List contact audiences (lists) on the account, with per-audience contact counts.",
135
- inputSchema: {}
138
+ inputSchema: z.object({})
136
139
  }, async () => respond(await client.audiences.list()));
137
140
  server.registerTool("create_audience", {
138
141
  title: "Create an audience",
139
142
  description: "Create a new audience (contact list) to hold contacts for broadcasts.",
140
- inputSchema: { name: z.string().describe("Human-readable name for the audience.") }
143
+ inputSchema: z.object({ name: z.string().describe("Human-readable name for the audience.") })
141
144
  }, async ({ name }) => respond(await client.audiences.create(name)));
142
145
  server.registerTool("list_contacts", {
143
146
  title: "List contacts",
144
147
  description: "List contacts in an audience. Supports search and subscription filtering.",
145
- inputSchema: {
148
+ inputSchema: z.object({
146
149
  audienceId: z.string().describe("The audience to list contacts from."),
147
150
  limit: z.number().int().min(1).max(100).optional(),
148
151
  cursor: z.string().optional().describe("Pagination cursor from a previous nextCursor."),
149
152
  search: z.string().optional().describe("Filter by email or name substring."),
150
153
  subscribed: z.boolean().optional().describe("true = only subscribed, false = only unsubscribed.")
151
- }
154
+ })
152
155
  }, async ({ audienceId, ...opts }) => respond(await client.audiences.listContacts(audienceId, opts)));
153
156
  server.registerTool("create_contact", {
154
157
  title: "Add a contact",
155
158
  description: "Add a contact to an audience.",
156
- inputSchema: {
159
+ inputSchema: z.object({
157
160
  audienceId: z.string().describe("The audience to add the contact to."),
158
161
  email: z.string().describe("Contact email address."),
159
162
  firstName: z.string().optional(),
160
163
  lastName: z.string().optional()
161
- }
164
+ })
162
165
  }, async ({ audienceId, email, firstName, lastName }) => respond(await client.audiences.createContact(audienceId, {
163
166
  email,
164
167
  firstName,
@@ -171,23 +174,23 @@ function registerBroadcastTools(server, client, config) {
171
174
  server.registerTool("list_broadcasts", {
172
175
  title: "List broadcasts",
173
176
  description: "List broadcasts (bulk sends to an audience) with their status and send counts.",
174
- inputSchema: {}
177
+ inputSchema: z.object({})
175
178
  }, async () => respond(await client.broadcasts.list()));
176
179
  server.registerTool("get_broadcast", {
177
180
  title: "Get a broadcast",
178
181
  description: "Fetch a broadcast by id, including recipient/sent counts and per-event stats.",
179
- inputSchema: { id: z.string().describe("The broadcast id.") }
182
+ inputSchema: z.object({ id: z.string().describe("The broadcast id.") })
180
183
  }, async ({ id }) => respond(await client.broadcasts.get(id)));
181
184
  server.registerTool("create_broadcast", {
182
185
  title: "Create a broadcast (draft)",
183
186
  description: "Create a broadcast in draft state, targeting an audience. Does NOT send it — use send_broadcast to send or schedule after reviewing. If `from` is omitted the configured default sender is used.",
184
- inputSchema: {
187
+ inputSchema: z.object({
185
188
  name: z.string().describe("Internal name for the broadcast."),
186
189
  audienceId: z.string().describe("The audience to send to."),
187
190
  subject: z.string().describe("Email subject line."),
188
191
  from: z.string().optional().describe("Sender. Defaults to the configured sender."),
189
192
  html: z.string().optional().describe("HTML body of the broadcast.")
190
- }
193
+ })
191
194
  }, async (args) => {
192
195
  const from = args.from ?? config.defaultFrom;
193
196
  if (!from) return failText("No sender specified and no default sender configured. Pass `from`, or set EUSEND_FROM / --from on the server.");
@@ -202,13 +205,43 @@ function registerBroadcastTools(server, client, config) {
202
205
  server.registerTool("send_broadcast", {
203
206
  title: "Send or schedule a broadcast",
204
207
  description: "Send a draft broadcast to its entire audience now, or schedule it for later. This is a bulk send — confirm with the user before calling. Omit `scheduledAt` to send immediately.",
205
- inputSchema: {
208
+ inputSchema: z.object({
206
209
  id: z.string().describe("The draft broadcast id."),
207
210
  scheduledAt: z.string().optional().describe("Optional future send time (ISO 8601). Omit to send immediately.")
208
- }
211
+ })
209
212
  }, async ({ id, scheduledAt }) => respond(await client.broadcasts.send(id, { scheduledAt })));
210
213
  }
211
214
  //#endregion
215
+ //#region src/tools/suppressions.ts
216
+ const reason = z.enum([
217
+ "bounce",
218
+ "complaint",
219
+ "manual"
220
+ ]);
221
+ function registerSuppressionTools(server, client) {
222
+ server.registerTool("list_suppressions", {
223
+ title: "List suppressed addresses",
224
+ description: "List addresses the account will not send to. Hard bounces and spam complaints are suppressed automatically. Use this to explain why an email came back with status \"suppressed\" or an ALL_SUPPRESSED error.",
225
+ inputSchema: z.object({
226
+ email: z.string().optional().describe("Match addresses containing this substring. Pass a domain (\"@acme.com\") to see every suppressed address there."),
227
+ reason: reason.optional().describe("Filter by why the address was suppressed."),
228
+ limit: z.number().int().min(1).max(100).optional(),
229
+ cursor: z.string().optional().describe("Pagination cursor from a previous next_cursor.")
230
+ })
231
+ }, async (opts) => respond(await client.suppressions.list(opts)));
232
+ server.registerTool("create_suppression", {
233
+ title: "Suppress an address",
234
+ description: "Stop sending to an address. If it is already suppressed the existing entry is returned unchanged — this never overwrites the reason an address was suppressed for.",
235
+ inputSchema: z.object({
236
+ email: z.string().describe("The address to suppress."),
237
+ reason: reason.optional().describe("Defaults to \"manual\".")
238
+ })
239
+ }, async ({ email, reason: why }) => respond(await client.suppressions.create({
240
+ email,
241
+ reason: why
242
+ })));
243
+ }
244
+ //#endregion
212
245
  //#region src/server.ts
213
246
  const SERVER_NAME = "eusend";
214
247
  const SERVER_VERSION = "0.1.1";
@@ -228,6 +261,7 @@ function createServer$1(config) {
228
261
  registerDomainTools(server, client);
229
262
  registerAudienceTools(server, client);
230
263
  registerBroadcastTools(server, client, config);
264
+ registerSuppressionTools(server, client);
231
265
  return server;
232
266
  }
233
267
  //#endregion
@@ -273,6 +307,9 @@ function createRateLimiter(limit, windowMs) {
273
307
  //#endregion
274
308
  //#region src/http.ts
275
309
  const MCP_PATH = "/mcp";
310
+ const MAX_BODY_BYTES = Number(process.env.MCP_MAX_BODY_BYTES ?? String(1024 * 1024));
311
+ /** Thrown by readBody when the request body exceeds MAX_BODY_BYTES; mapped to 413. */
312
+ var BodyTooLargeError = class extends Error {};
276
313
  const rateLimiter = createRateLimiter(Number(process.env.RATE_LIMIT_PER_MIN ?? "120"), 6e4);
277
314
  function json(res, status, body) {
278
315
  res.writeHead(status, { "Content-Type": "application/json" });
@@ -285,36 +322,78 @@ function bearerKey(req) {
285
322
  const [scheme, value] = header.split(" ");
286
323
  return scheme?.toLowerCase() === "bearer" && value ? value : void 0;
287
324
  }
288
- async function readBody(req) {
289
- const chunks = [];
290
- for await (const chunk of req) chunks.push(chunk);
291
- if (chunks.length === 0) return void 0;
292
- return JSON.parse(Buffer.concat(chunks).toString("utf8"));
325
+ /**
326
+ * Buffer the request body, refusing anything over MAX_BODY_BYTES.
327
+ *
328
+ * Deliberately event-based rather than `for await`: async iteration destroys the
329
+ * stream when the loop exits early, which tears down the socket before the 413
330
+ * can flush and leaves the caller with a connection reset instead of an answer.
331
+ * Here we stop consuming and leave the socket up for `handle` to reply on.
332
+ */
333
+ function readBody(req) {
334
+ return new Promise((resolve, reject) => {
335
+ const chunks = [];
336
+ let size = 0;
337
+ let settled = false;
338
+ req.on("data", (chunk) => {
339
+ if (settled) return;
340
+ size += chunk.length;
341
+ if (size > MAX_BODY_BYTES) {
342
+ settled = true;
343
+ req.pause();
344
+ reject(new BodyTooLargeError(`Request body exceeds the ${MAX_BODY_BYTES}-byte limit`));
345
+ return;
346
+ }
347
+ chunks.push(chunk);
348
+ });
349
+ req.on("end", () => {
350
+ if (settled) return;
351
+ settled = true;
352
+ if (chunks.length === 0) return resolve(void 0);
353
+ try {
354
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
355
+ } catch (err) {
356
+ reject(err);
357
+ }
358
+ });
359
+ req.on("error", (err) => {
360
+ if (settled) return;
361
+ settled = true;
362
+ reject(err);
363
+ });
364
+ });
293
365
  }
294
366
  /**
295
367
  * Run the Eusend MCP server over Streamable HTTP — the hosted/remote transport.
296
- * Stateless: every request builds a fresh server bound to the caller's API key,
297
- * so one endpoint safely serves many accounts. Mount this behind TLS at, e.g.,
298
- * https://mcp.eusend.dev/mcp.
368
+ *
369
+ * `createMcpHandler` serves both protocol eras from the one endpoint: 2026-07-28
370
+ * traffic natively, and 2025-era traffic through its stateless legacy fallback
371
+ * (the default). The factory runs once per request, so every request still gets a
372
+ * fresh server bound to that caller's API key and one endpoint safely serves many
373
+ * accounts. Mount this behind TLS at, e.g., https://mcp.eusend.dev/mcp.
299
374
  */
300
375
  async function runHttp(options) {
376
+ const nodeHandler = toNodeHandler(createMcpHandler(({ authInfo }) => {
377
+ if (!authInfo) throw new Error("MCP request reached the server factory without an API key.");
378
+ return createServer$1({
379
+ apiKey: authInfo.token,
380
+ ...options.defaults
381
+ });
382
+ }, { onerror: (err) => console.error("MCP handler error:", err) }), { onerror: (err) => console.error("MCP adapter error:", err) });
383
+ const validateHost = hostHeaderValidation(options.allowedHosts);
301
384
  const httpServer = createServer((req, res) => {
302
- handle(req, res, options);
385
+ handle(req, res, nodeHandler, validateHost);
303
386
  });
304
387
  await new Promise((resolve) => {
305
388
  httpServer.listen(options.port, options.host, resolve);
306
389
  });
307
390
  console.error(`Eusend MCP server (HTTP) listening on http://${options.host}:${options.port}${MCP_PATH}`);
308
391
  }
309
- async function handle(req, res, options) {
392
+ async function handle(req, res, nodeHandler, validateHost) {
310
393
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
311
394
  if (url.pathname === "/health") return json(res, 200, { status: "ok" });
312
395
  if (url.pathname !== MCP_PATH) return json(res, 404, { error: "Not found" });
313
- if (req.method !== "POST") {
314
- res.writeHead(405, { Allow: "POST" });
315
- res.end();
316
- return;
317
- }
396
+ if (!validateHost(req, res)) return;
318
397
  if (!rateLimiter.check(req)) return json(res, 429, {
319
398
  jsonrpc: "2.0",
320
399
  error: {
@@ -332,24 +411,31 @@ async function handle(req, res, options) {
332
411
  },
333
412
  id: null
334
413
  });
335
- const server = createServer$1({
336
- apiKey,
337
- ...options.defaults
338
- });
339
- const transport = new StreamableHTTPServerTransport({
340
- sessionIdGenerator: void 0,
341
- enableDnsRebindingProtection: true,
342
- allowedHosts: options.allowedHosts
343
- });
344
- res.on("close", () => {
345
- transport.close();
346
- server.close();
347
- });
414
+ req.auth = {
415
+ token: apiKey,
416
+ clientId: "eusend-api-key",
417
+ scopes: []
418
+ };
348
419
  try {
349
- await server.connect(transport);
350
- const body = await readBody(req);
351
- await transport.handleRequest(req, res, body);
420
+ await nodeHandler(req, res, await readBody(req));
352
421
  } catch (err) {
422
+ if (err instanceof BodyTooLargeError) {
423
+ if (!res.headersSent) {
424
+ res.writeHead(413, {
425
+ "Content-Type": "application/json",
426
+ Connection: "close"
427
+ });
428
+ res.end(JSON.stringify({
429
+ jsonrpc: "2.0",
430
+ error: {
431
+ code: -32600,
432
+ message: "Request body too large."
433
+ },
434
+ id: null
435
+ }), () => req.destroy());
436
+ }
437
+ return;
438
+ }
353
439
  console.error("Error handling MCP request:", err);
354
440
  if (!res.headersSent) json(res, 500, {
355
441
  jsonrpc: "2.0",
@@ -364,4 +450,4 @@ async function handle(req, res, options) {
364
450
  //#endregion
365
451
  export { createServer$1 as n, runHttp as t };
366
452
 
367
- //# sourceMappingURL=http-BiRaRNNh.mjs.map
453
+ //# sourceMappingURL=http-DynZno_J.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http-DynZno_J.mjs","names":["createServer","createServer","createHttpServer"],"sources":["../src/respond.ts","../src/tools/emails.ts","../src/tools/domains.ts","../src/tools/audiences.ts","../src/tools/broadcasts.ts","../src/tools/suppressions.ts","../src/server.ts","../src/ratelimit.ts","../src/http.ts"],"sourcesContent":["import type { CallToolResult } from '@modelcontextprotocol/server'\nimport type { EusendError, EusendResponse } from '@eusend_dev/sdk'\n\n/** MCP tool return shape. */\nexport type ToolResult = CallToolResult\n\n/** Wrap a successful payload as pretty-printed JSON text content. */\nexport function ok(data: unknown): ToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n }\n}\n\n/**\n * Surface an SDK error as an MCP tool error. `isError: true` tells the client\n * the call failed, and the error `name` (e.g. DOMAIN_NOT_VERIFIED) gives the\n * agent enough to self-correct — e.g. verify the domain, then retry.\n */\nexport function fail(error: EusendError): ToolResult {\n return {\n content: [{ type: 'text', text: `Error [${error.name}]: ${error.message}` }],\n isError: true,\n }\n}\n\n/** Plain text error for validation the tool does itself before hitting the API. */\nexport function failText(message: string): ToolResult {\n return { content: [{ type: 'text', text: message }], isError: true }\n}\n\n/** Turn any SDK `EusendResponse` into a tool result. */\nexport function respond<T>(res: EusendResponse<T>): ToolResult {\n return res.error ? fail(res.error) : ok(res.data)\n}\n","import type { McpServer } from '@modelcontextprotocol/server'\nimport type { Eusend } from '@eusend_dev/sdk'\nimport { z } from 'zod'\nimport type { McpConfig } from '../config.js'\nimport { respond, failText } from '../respond.js'\n\nconst emailStatus = z.enum([\n 'queued',\n 'scheduled',\n 'canceled',\n 'sending',\n 'sent',\n 'delivered',\n 'bounced',\n 'complained',\n 'suppressed',\n 'failed',\n])\n\nconst recipients = z.union([z.string(), z.array(z.string())])\n\nexport function registerEmailTools(server: McpServer, client: Eusend, config: McpConfig): void {\n server.registerTool(\n 'send_email',\n {\n title: 'Send an email',\n description:\n 'Send a transactional email through Eusend. Provide `html` or `text` (or both). ' +\n 'The sender domain must be verified on the account — use list_domains to check. ' +\n 'If `from` is omitted, the server-configured default sender is used.',\n inputSchema: z.object({\n from: z\n .string()\n .optional()\n .describe('Sender, e.g. \"Acme <hi@acme.com>\". Defaults to the configured sender.'),\n to: recipients.describe('Recipient address or list of addresses.'),\n subject: z.string().describe('Email subject line.'),\n text: z.string().optional().describe('Plain-text body.'),\n html: z.string().optional().describe('HTML body. Takes precedence over text for display.'),\n cc: recipients.optional(),\n bcc: recipients.optional(),\n replyTo: recipients.optional().describe('Reply-To address(es).'),\n tags: z\n .record(z.string(), z.string())\n .optional()\n .describe(\n 'Labels for log filtering and webhook routing, e.g. {\"category\": \"password_reset\"}. ' +\n 'Names and values allow ASCII letters, numbers, underscores and dashes; max 10 tags.',\n ),\n scheduledAt: z\n .string()\n .optional()\n .describe(\n 'Future send time: ISO 8601 or natural language like \"in 1 hour\". Max 30 days out.',\n ),\n }),\n },\n async (args) => {\n const from = args.from ?? config.defaultFrom\n if (!from) {\n return failText(\n 'No sender specified and no default sender configured. Pass `from`, or set EUSEND_FROM / --from on the server.',\n )\n }\n if (!args.html && !args.text) {\n return failText('Provide at least one of `html` or `text`.')\n }\n return respond(\n await client.emails.send({\n from,\n to: args.to,\n subject: args.subject,\n text: args.text,\n html: args.html,\n cc: args.cc,\n bcc: args.bcc,\n replyTo: args.replyTo ?? config.defaultReplyTo,\n tags: args.tags,\n scheduledAt: args.scheduledAt,\n }),\n )\n },\n )\n\n server.registerTool(\n 'list_emails',\n {\n title: 'List emails',\n description:\n 'List recently sent emails, most recent first. Supports cursor pagination and filtering.',\n inputSchema: z.object({\n limit: z.number().int().min(1).max(100).optional().describe('Max results (1–100).'),\n cursor: z.string().optional().describe('Pagination cursor from a previous nextCursor.'),\n status: emailStatus.optional().describe('Filter by delivery status.'),\n from: z.string().optional().describe('Filter by sender address.'),\n to: z.string().optional().describe('Filter by recipient address.'),\n tag: z\n .union([z.string(), z.array(z.string())])\n .optional()\n .describe(\n 'Filter by tag: \"category:password_reset\" for an exact pair, or bare \"category\" ' +\n 'for any email carrying the tag. An array requires all of them.',\n ),\n }),\n },\n async (args) => respond(await client.emails.list(args)),\n )\n\n server.registerTool(\n 'get_email',\n {\n title: 'Get an email',\n description: 'Fetch a single email by id, including its full delivery event history.',\n inputSchema: z.object({\n id: z.string().describe('The email id returned by send_email or list_emails.'),\n }),\n },\n async ({ id }) => respond(await client.emails.get(id)),\n )\n\n server.registerTool(\n 'cancel_email',\n {\n title: 'Cancel a scheduled email',\n description:\n 'Cancel a scheduled email before it sends. Fails once the email has started sending.',\n inputSchema: z.object({\n id: z.string().describe('The id of a scheduled email.'),\n }),\n },\n async ({ id }) => respond(await client.emails.cancel(id)),\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/server'\nimport type { Eusend } from '@eusend_dev/sdk'\nimport { z } from 'zod'\nimport { respond } from '../respond.js'\n\nexport function registerDomainTools(server: McpServer, client: Eusend): void {\n server.registerTool(\n 'list_domains',\n {\n title: 'List domains',\n description: 'List sending domains on the account and their verification status.',\n inputSchema: z.object({}),\n },\n async () => respond(await client.domains.list()),\n )\n\n server.registerTool(\n 'get_domain',\n {\n title: 'Get a domain',\n description:\n 'Fetch a single domain by id, including its DKIM selector and verification state.',\n inputSchema: z.object({\n id: z.string().describe('The domain id.'),\n }),\n },\n async ({ id }) => respond(await client.domains.get(id)),\n )\n\n server.registerTool(\n 'create_domain',\n {\n title: 'Add a sending domain',\n description:\n 'Register a new sending domain. Returns the DKIM, SPF, and DMARC DNS records that must be ' +\n \"added at the domain's DNS provider before it can send. Present these records to the user.\",\n inputSchema: z.object({\n name: z.string().describe('The domain to add, e.g. \"mail.acme.com\".'),\n }),\n },\n async ({ name }) => respond(await client.domains.create(name)),\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/server'\nimport type { Eusend } from '@eusend_dev/sdk'\nimport { z } from 'zod'\nimport { respond } from '../respond.js'\n\nexport function registerAudienceTools(server: McpServer, client: Eusend): void {\n server.registerTool(\n 'list_audiences',\n {\n title: 'List audiences',\n description:\n 'List contact audiences (lists) on the account, with per-audience contact counts.',\n inputSchema: z.object({}),\n },\n async () => respond(await client.audiences.list()),\n )\n\n server.registerTool(\n 'create_audience',\n {\n title: 'Create an audience',\n description: 'Create a new audience (contact list) to hold contacts for broadcasts.',\n inputSchema: z.object({\n name: z.string().describe('Human-readable name for the audience.'),\n }),\n },\n async ({ name }) => respond(await client.audiences.create(name)),\n )\n\n server.registerTool(\n 'list_contacts',\n {\n title: 'List contacts',\n description: 'List contacts in an audience. Supports search and subscription filtering.',\n inputSchema: z.object({\n audienceId: z.string().describe('The audience to list contacts from.'),\n limit: z.number().int().min(1).max(100).optional(),\n cursor: z.string().optional().describe('Pagination cursor from a previous nextCursor.'),\n search: z.string().optional().describe('Filter by email or name substring.'),\n subscribed: z\n .boolean()\n .optional()\n .describe('true = only subscribed, false = only unsubscribed.'),\n }),\n },\n async ({ audienceId, ...opts }) =>\n respond(await client.audiences.listContacts(audienceId, opts)),\n )\n\n server.registerTool(\n 'create_contact',\n {\n title: 'Add a contact',\n description: 'Add a contact to an audience.',\n inputSchema: z.object({\n audienceId: z.string().describe('The audience to add the contact to.'),\n email: z.string().describe('Contact email address.'),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n }),\n },\n async ({ audienceId, email, firstName, lastName }) =>\n respond(await client.audiences.createContact(audienceId, { email, firstName, lastName })),\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/server'\nimport type { Eusend } from '@eusend_dev/sdk'\nimport { z } from 'zod'\nimport type { McpConfig } from '../config.js'\nimport { respond, failText } from '../respond.js'\n\nexport function registerBroadcastTools(server: McpServer, client: Eusend, config: McpConfig): void {\n server.registerTool(\n 'list_broadcasts',\n {\n title: 'List broadcasts',\n description: 'List broadcasts (bulk sends to an audience) with their status and send counts.',\n inputSchema: z.object({}),\n },\n async () => respond(await client.broadcasts.list()),\n )\n\n server.registerTool(\n 'get_broadcast',\n {\n title: 'Get a broadcast',\n description: 'Fetch a broadcast by id, including recipient/sent counts and per-event stats.',\n inputSchema: z.object({\n id: z.string().describe('The broadcast id.'),\n }),\n },\n async ({ id }) => respond(await client.broadcasts.get(id)),\n )\n\n server.registerTool(\n 'create_broadcast',\n {\n title: 'Create a broadcast (draft)',\n description:\n 'Create a broadcast in draft state, targeting an audience. Does NOT send it — use send_broadcast ' +\n 'to send or schedule after reviewing. If `from` is omitted the configured default sender is used.',\n inputSchema: z.object({\n name: z.string().describe('Internal name for the broadcast.'),\n audienceId: z.string().describe('The audience to send to.'),\n subject: z.string().describe('Email subject line.'),\n from: z.string().optional().describe('Sender. Defaults to the configured sender.'),\n html: z.string().optional().describe('HTML body of the broadcast.'),\n }),\n },\n async (args) => {\n const from = args.from ?? config.defaultFrom\n if (!from) {\n return failText(\n 'No sender specified and no default sender configured. Pass `from`, or set EUSEND_FROM / --from on the server.',\n )\n }\n return respond(\n await client.broadcasts.create({\n name: args.name,\n audienceId: args.audienceId,\n subject: args.subject,\n from,\n html: args.html,\n }),\n )\n },\n )\n\n server.registerTool(\n 'send_broadcast',\n {\n title: 'Send or schedule a broadcast',\n description:\n 'Send a draft broadcast to its entire audience now, or schedule it for later. This is a bulk send — ' +\n 'confirm with the user before calling. Omit `scheduledAt` to send immediately.',\n inputSchema: z.object({\n id: z.string().describe('The draft broadcast id.'),\n scheduledAt: z\n .string()\n .optional()\n .describe('Optional future send time (ISO 8601). Omit to send immediately.'),\n }),\n },\n async ({ id, scheduledAt }) => respond(await client.broadcasts.send(id, { scheduledAt })),\n )\n}\n","import type { McpServer } from '@modelcontextprotocol/server'\nimport type { Eusend } from '@eusend_dev/sdk'\nimport { z } from 'zod'\nimport { respond } from '../respond.js'\n\nconst reason = z.enum(['bounce', 'complaint', 'manual'])\n\nexport function registerSuppressionTools(server: McpServer, client: Eusend): void {\n server.registerTool(\n 'list_suppressions',\n {\n title: 'List suppressed addresses',\n description:\n 'List addresses the account will not send to. Hard bounces and spam complaints are suppressed automatically. Use this to explain why an email came back with status \"suppressed\" or an ALL_SUPPRESSED error.',\n inputSchema: z.object({\n email: z\n .string()\n .optional()\n .describe(\n 'Match addresses containing this substring. Pass a domain (\"@acme.com\") to see every suppressed address there.',\n ),\n reason: reason.optional().describe('Filter by why the address was suppressed.'),\n limit: z.number().int().min(1).max(100).optional(),\n cursor: z.string().optional().describe('Pagination cursor from a previous next_cursor.'),\n }),\n },\n async (opts) => respond(await client.suppressions.list(opts)),\n )\n\n server.registerTool(\n 'create_suppression',\n {\n title: 'Suppress an address',\n description:\n 'Stop sending to an address. If it is already suppressed the existing entry is returned unchanged — this never overwrites the reason an address was suppressed for.',\n inputSchema: z.object({\n email: z.string().describe('The address to suppress.'),\n reason: reason.optional().describe('Defaults to \"manual\".'),\n }),\n },\n async ({ email, reason: why }) =>\n respond(await client.suppressions.create({ email, reason: why })),\n )\n\n // Un-suppressing is deliberately absent, in line with the server's rule that\n // destructive actions stay out of the assistant's reach. Suppressing stops mail, which\n // is the safe direction; removing an entry re-enables sending to an address that\n // bounced or complained, and doing that in bulk is precisely what wrecks a sender's\n // reputation. Bulk import/export are out for the same reason — neither belongs in a\n // single tool call.\n}\n","import { McpServer } from '@modelcontextprotocol/server'\nimport { Eusend } from '@eusend_dev/sdk'\nimport type { McpConfig } from './config.js'\nimport { registerEmailTools } from './tools/emails.js'\nimport { registerDomainTools } from './tools/domains.js'\nimport { registerAudienceTools } from './tools/audiences.js'\nimport { registerBroadcastTools } from './tools/broadcasts.js'\nimport { registerSuppressionTools } from './tools/suppressions.js'\n\nexport const SERVER_NAME = 'eusend'\nexport const SERVER_VERSION = '0.1.1'\n\n/**\n * Build a fully-wired MCP server for one Eusend account. This is\n * transport-agnostic: the stdio entry (index.ts) and the HTTP entry (http.ts)\n * both call this and then attach their own transport. All tool definitions live\n * in ./tools and are registered here exactly once.\n */\nexport function createServer(config: McpConfig): McpServer {\n const server = new McpServer({\n name: SERVER_NAME,\n version: SERVER_VERSION,\n })\n\n const client = new Eusend(config.apiKey, { baseUrl: config.baseUrl })\n\n registerEmailTools(server, client, config)\n registerDomainTools(server, client)\n registerAudienceTools(server, client)\n registerBroadcastTools(server, client, config)\n registerSuppressionTools(server, client)\n\n return server\n}\n","import type { IncomingMessage } from 'node:http'\n\n/**\n * Minimal in-memory fixed-window IP rate limiter for the public /mcp endpoint.\n *\n * The endpoint is unauthenticated at the transport layer (initialize/tools/list\n * work before any API key is validated), so it needs its own basic DoS ceiling\n * independent of the API's rate limiting. In-memory on purpose: it keeps the box\n * free of any external dependency or credential. Per-container state is fine here\n * — the limit is a coarse abuse ceiling, not an accounting mechanism.\n */\nexport interface RateLimiter {\n /** Returns true if the request is allowed, false if it should be rejected (429). */\n check(req: IncomingMessage): boolean\n}\n\n// Hard cap on distinct tracked IPs so a high-cardinality flood can't grow the map\n// unbounded within a window. When exceeded, new IPs are denied until the next sweep\n// (fail closed under abuse) rather than consuming memory.\nconst MAX_BUCKETS = 50_000\n\n/**\n * Trusted client IP. Coolify's Traefik sits in front and OVERWRITES X-Real-Ip with the\n * real connection address, so it can't be spoofed by a client-sent header. We deliberately\n * do NOT trust X-Forwarded-For here: Traefik appends the real IP to any client-supplied\n * XFF, so its leftmost entry is attacker-controlled and would let a caller mint a fresh\n * bucket per request. Falls back to the socket address when there's no proxy (local runs).\n */\nfunction clientIp(req: IncomingMessage): string {\n const realIp = req.headers['x-real-ip']\n if (typeof realIp === 'string' && realIp.length > 0) {\n return realIp.trim()\n }\n return req.socket.remoteAddress ?? 'unknown'\n}\n\nexport function createRateLimiter(limit: number, windowMs: number): RateLimiter {\n const buckets = new Map<string, { count: number; resetAt: number }>()\n\n // Evict stale buckets so the map can't grow unbounded under a churn of IPs.\n const sweep = setInterval(() => {\n const now = Date.now()\n for (const [key, b] of buckets) {\n if (now > b.resetAt) buckets.delete(key)\n }\n }, windowMs)\n sweep.unref()\n\n return {\n check(req) {\n const key = clientIp(req)\n const now = Date.now()\n const bucket = buckets.get(key)\n if (!bucket || now > bucket.resetAt) {\n if (!bucket && buckets.size >= MAX_BUCKETS) {\n // Try to reclaim expired buckets before refusing.\n for (const [k, b] of buckets) if (now > b.resetAt) buckets.delete(k)\n if (buckets.size >= MAX_BUCKETS) return false\n }\n buckets.set(key, { count: 1, resetAt: now + windowMs })\n return true\n }\n bucket.count += 1\n return bucket.count <= limit\n },\n }\n}\n","import {\n createServer as createHttpServer,\n type IncomingMessage,\n type ServerResponse,\n} from 'node:http'\nimport { createMcpHandler, type AuthInfo } from '@modelcontextprotocol/server'\nimport { hostHeaderValidation, toNodeHandler } from '@modelcontextprotocol/node'\nimport type { McpDefaults } from './config.js'\nimport { createServer } from './server.js'\nimport { createRateLimiter } from './ratelimit.js'\n\nexport interface RunHttpOptions {\n /** Account-agnostic defaults; the API key comes per-request from the caller. */\n defaults: McpDefaults\n port: number\n host: string\n /** Hostnames allowed in the Host header (DNS-rebinding protection). */\n allowedHosts: string[]\n}\n\nconst MCP_PATH = '/mcp'\n\n// Cap the request body before buffering it. node:http imposes no default limit, so without\n// this an unauthenticated caller (only a *present* bearer is required to reach readBody, not a\n// valid one) could stream an arbitrarily large body straight into memory. An MCP JSON-RPC\n// envelope is tiny, so 1 MB is generous. Mirrors the API tier's bodyLimit.\nconst MAX_BODY_BYTES = Number(process.env.MCP_MAX_BODY_BYTES ?? String(1024 * 1024))\n\n/** Thrown by readBody when the request body exceeds MAX_BODY_BYTES; mapped to 413. */\nclass BodyTooLargeError extends Error {}\n\n// Coarse per-IP DoS ceiling for the public endpoint. Each JSON-RPC call over an\n// MCP session is one request, so this is generous for a real agent while still\n// capping an anonymous flood. Tune via RATE_LIMIT_PER_MIN if needed.\nconst RATE_LIMIT_PER_MIN = Number(process.env.RATE_LIMIT_PER_MIN ?? '120')\nconst rateLimiter = createRateLimiter(RATE_LIMIT_PER_MIN, 60_000)\n\n/**\n * `toNodeHandler` reads the caller's identity off `req.auth` and hands it to the\n * factory as `authInfo`. `IncomingMessage` has no such field, so widen it here.\n */\ntype AuthenticatedRequest = IncomingMessage & { auth?: AuthInfo }\n\nfunction json(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'Content-Type': 'application/json' })\n res.end(JSON.stringify(body))\n}\n\n/** Pull the API key out of `Authorization: Bearer <key>`. */\nfunction bearerKey(req: IncomingMessage): string | undefined {\n const header = req.headers.authorization\n if (!header) return undefined\n const [scheme, value] = header.split(' ')\n return scheme?.toLowerCase() === 'bearer' && value ? value : undefined\n}\n\n/**\n * Buffer the request body, refusing anything over MAX_BODY_BYTES.\n *\n * Deliberately event-based rather than `for await`: async iteration destroys the\n * stream when the loop exits early, which tears down the socket before the 413\n * can flush and leaves the caller with a connection reset instead of an answer.\n * Here we stop consuming and leave the socket up for `handle` to reply on.\n */\nfunction readBody(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = []\n let size = 0\n let settled = false\n\n req.on('data', (chunk: Buffer) => {\n if (settled) return\n size += chunk.length\n if (size > MAX_BODY_BYTES) {\n settled = true\n req.pause()\n reject(new BodyTooLargeError(`Request body exceeds the ${MAX_BODY_BYTES}-byte limit`))\n return\n }\n chunks.push(chunk)\n })\n\n req.on('end', () => {\n if (settled) return\n settled = true\n if (chunks.length === 0) return resolve(undefined)\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (err) {\n reject(err)\n }\n })\n\n req.on('error', (err) => {\n if (settled) return\n settled = true\n reject(err)\n })\n })\n}\n\n/**\n * Run the Eusend MCP server over Streamable HTTP — the hosted/remote transport.\n *\n * `createMcpHandler` serves both protocol eras from the one endpoint: 2026-07-28\n * traffic natively, and 2025-era traffic through its stateless legacy fallback\n * (the default). The factory runs once per request, so every request still gets a\n * fresh server bound to that caller's API key and one endpoint safely serves many\n * accounts. Mount this behind TLS at, e.g., https://mcp.eusend.dev/mcp.\n */\nexport async function runHttp(options: RunHttpOptions): Promise<void> {\n const handler = createMcpHandler(\n ({ authInfo }) => {\n if (!authInfo) {\n // Unreachable: handle() answers 401 before the handler is ever invoked.\n throw new Error('MCP request reached the server factory without an API key.')\n }\n return createServer({ apiKey: authInfo.token, ...options.defaults })\n },\n { onerror: (err) => console.error('MCP handler error:', err) },\n )\n\n const nodeHandler = toNodeHandler(handler, {\n onerror: (err) => console.error('MCP adapter error:', err),\n })\n const validateHost = hostHeaderValidation(options.allowedHosts)\n\n const httpServer = createHttpServer((req, res) => {\n void handle(req, res, nodeHandler, validateHost)\n })\n\n await new Promise<void>((resolve) => {\n httpServer.listen(options.port, options.host, resolve)\n })\n console.error(\n `Eusend MCP server (HTTP) listening on http://${options.host}:${options.port}${MCP_PATH}`,\n )\n}\n\ntype NodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n parsedBody?: unknown,\n) => Promise<void>\ntype HostGuard = (req: IncomingMessage, res: ServerResponse) => boolean\n\nasync function handle(\n req: IncomingMessage,\n res: ServerResponse,\n nodeHandler: NodeHandler,\n validateHost: HostGuard,\n): Promise<void> {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`)\n\n if (url.pathname === '/health') {\n return json(res, 200, { status: 'ok' })\n }\n\n if (url.pathname !== MCP_PATH) {\n return json(res, 404, { error: 'Not found' })\n }\n\n // DNS-rebinding protection. The guard answers 403 itself when it rejects; the\n // 2025 session verbs GET and DELETE are answered 405 by the handler's stateless\n // legacy fallback, and the 2026 era has no server-push channel to open.\n if (!validateHost(req, res)) return\n\n if (!rateLimiter.check(req)) {\n return json(res, 429, {\n jsonrpc: '2.0',\n error: { code: -32029, message: 'Too many requests. Slow down.' },\n id: null,\n })\n }\n\n const apiKey = bearerKey(req)\n if (!apiKey) {\n return json(res, 401, {\n jsonrpc: '2.0',\n error: {\n code: -32001,\n message: 'Missing or malformed Authorization: Bearer <api-key> header.',\n },\n id: null,\n })\n }\n\n // Carried to the factory from here; the API validates it on the first call the\n // constructed server makes.\n ;(req as AuthenticatedRequest).auth = { token: apiKey, clientId: 'eusend-api-key', scopes: [] }\n\n try {\n // Read the body here to keep the size cap, then pass it pre-parsed so the\n // adapter never re-reads the stream.\n const body = await readBody(req)\n await nodeHandler(req, res, body)\n } catch (err) {\n if (err instanceof BodyTooLargeError) {\n if (!res.headersSent) {\n // The caller is still uploading. Answer early, close the connection rather\n // than draining the rest, and only tear the socket down once the 413 has\n // actually flushed — destroying sooner is what turns this into a reset.\n res.writeHead(413, { 'Content-Type': 'application/json', Connection: 'close' })\n res.end(\n JSON.stringify({\n jsonrpc: '2.0',\n error: { code: -32600, message: 'Request body too large.' },\n id: null,\n }),\n () => req.destroy(),\n )\n }\n return\n }\n console.error('Error handling MCP request:', err)\n if (!res.headersSent) {\n json(res, 500, {\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n })\n }\n }\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,GAAG,MAA2B;CAC5C,OAAO,EACL,SAAS,CAAC;EAAE,MAAM;EAAQ,MAAM,KAAK,UAAU,MAAM,MAAM,CAAC;CAAE,CAAC,EACjE;AACF;;;;;;AAOA,SAAgB,KAAK,OAAgC;CACnD,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM,UAAU,MAAM,KAAK,KAAK,MAAM;EAAU,CAAC;EAC3E,SAAS;CACX;AACF;;AAGA,SAAgB,SAAS,SAA6B;CACpD,OAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAQ,CAAC;EAAG,SAAS;CAAK;AACrE;;AAGA,SAAgB,QAAW,KAAoC;CAC7D,OAAO,IAAI,QAAQ,KAAK,IAAI,KAAK,IAAI,GAAG,IAAI,IAAI;AAClD;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IAAI,aAAa,UACnB,OAAO,KAAK,KAAK,KAAK,EAAE,OAAO,YAAY,CAAC;CAM9C,IAAI,CAAC,aAAa,KAAK,GAAG,GAAG;CAE7B,IAAI,CAAC,YAAY,MAAM,GAAG,GACxB,OAAO,KAAK,KAAK,KAAK;EACpB,SAAS;EACT,OAAO;GAAE,MAAM;GAAQ,SAAS;EAAgC;EAChE,IAAI;CACN,CAAC;CAGH,MAAM,SAAS,UAAU,GAAG;CAC5B,IAAI,CAAC,QACH,OAAO,KAAK,KAAK,KAAK;EACpB,SAAS;EACT,OAAO;GACL,MAAM;GACN,SAAS;EACX;EACA,IAAI;CACN,CAAC;CAKF,IAA8B,OAAO;EAAE,OAAO;EAAQ,UAAU;EAAkB,QAAQ,CAAC;CAAE;CAE9F,IAAI;EAIF,MAAM,YAAY,KAAK,KAAK,MADT,SAAS,GAAG,CACC;CAClC,SAAS,KAAK;EACZ,IAAI,eAAe,mBAAmB;GACpC,IAAI,CAAC,IAAI,aAAa;IAIpB,IAAI,UAAU,KAAK;KAAE,gBAAgB;KAAoB,YAAY;IAAQ,CAAC;IAC9E,IAAI,IACF,KAAK,UAAU;KACb,SAAS;KACT,OAAO;MAAE,MAAM;MAAQ,SAAS;KAA0B;KAC1D,IAAI;IACN,CAAC,SACK,IAAI,QAAQ,CACpB;GACF;GACA;EACF;EACA,QAAQ,MAAM,+BAA+B,GAAG;EAChD,IAAI,CAAC,IAAI,aACP,KAAK,KAAK,KAAK;GACb,SAAS;GACT,OAAO;IAAE,MAAM;IAAQ,SAAS;GAAwB;GACxD,IAAI;EACN,CAAC;CAEL;AACF"}
package/dist/http.d.mts CHANGED
@@ -35,9 +35,12 @@ interface RunHttpOptions {
35
35
  }
36
36
  /**
37
37
  * Run the Eusend MCP server over Streamable HTTP — the hosted/remote transport.
38
- * Stateless: every request builds a fresh server bound to the caller's API key,
39
- * so one endpoint safely serves many accounts. Mount this behind TLS at, e.g.,
40
- * https://mcp.eusend.dev/mcp.
38
+ *
39
+ * `createMcpHandler` serves both protocol eras from the one endpoint: 2026-07-28
40
+ * traffic natively, and 2025-era traffic through its stateless legacy fallback
41
+ * (the default). The factory runs once per request, so every request still gets a
42
+ * fresh server bound to that caller's API key and one endpoint safely serves many
43
+ * accounts. Mount this behind TLS at, e.g., https://mcp.eusend.dev/mcp.
41
44
  */
42
45
  declare function runHttp(options: RunHttpOptions): Promise<void>;
43
46
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"http.d.mts","names":[],"sources":["../src/config.ts","../src/http.ts"],"mappings":";;;;;;;;;UAQiB;;EAEf;;EAEA;;;;;;EAMA;;EAEA;;;KAIU,cAAc,KAAK;;;UClBd;;EAEf,UAAU;EACV;EACA;;EAEA;;;;;;;;iBAqCoB,QAAQ,SAAS,iBAAiB"}
1
+ {"version":3,"file":"http.d.mts","names":[],"sources":["../src/config.ts","../src/http.ts"],"mappings":";;;;;;;;;UAQiB;;EAEf;;EAEA;;;;;;EAMA;;EAEA;;;KAIU,cAAc,KAAK;;;UCbd;;EAEf,UAAU;EACV;EACA;;EAEA;;;;;;;;;;;iBA6FoB,QAAQ,SAAS,iBAAiB"}
package/dist/http.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as runHttp } from "./http-BiRaRNNh.mjs";
1
+ import { t as runHttp } from "./http-DynZno_J.mjs";
2
2
  export { runHttp };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { n as createServer, t as runHttp } from "./http-BiRaRNNh.mjs";
3
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2
+ import { n as createServer, t as runHttp } from "./http-DynZno_J.mjs";
3
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
4
4
  //#region src/config.ts
5
5
  function readEnv(name) {
6
6
  const v = process.env[name];
@@ -42,8 +42,7 @@ function parseCliOptions(argv) {
42
42
  allowedHosts: allowedHostsRaw ? allowedHostsRaw.split(",").map((h) => h.trim()).filter(Boolean) : [
43
43
  "127.0.0.1",
44
44
  "localhost",
45
- `127.0.0.1:${port}`,
46
- `localhost:${port}`
45
+ "[::1]"
47
46
  ],
48
47
  config: {
49
48
  apiKey,
@@ -74,9 +73,7 @@ async function main() {
74
73
  console.error("Missing Eusend API key. Set EUSEND_API_KEY (or pass --key). Get one at https://eusend.dev/api-keys");
75
74
  process.exit(1);
76
75
  }
77
- const server = createServer(options.config);
78
- const transport = new StdioServerTransport();
79
- await server.connect(transport);
76
+ serveStdio(() => createServer(options.config), { onerror: (err) => console.error("MCP stdio error:", err) });
80
77
  console.error("Eusend MCP server running on stdio.");
81
78
  }
82
79
  main().catch((err) => {
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/config.ts","../src/index.ts"],"sourcesContent":["/**\n * Runtime configuration for the Eusend MCP server.\n *\n * In stdio mode this is resolved once, at startup, from CLI flags and the\n * environment. In HTTP mode the `apiKey` is supplied per-request from the\n * caller's `Authorization: Bearer` header, while the defaults (`defaultFrom`,\n * `baseUrl`, …) come from the process environment shared across all callers.\n */\nexport interface McpConfig {\n /** Eusend API key used to authenticate every call the server makes. */\n apiKey: string;\n /** Override the API base URL (defaults to https://api.eusend.dev). */\n baseUrl?: string;\n /**\n * Sender address used when `send_email` / `create_broadcast` are called\n * without an explicit `from`. Pinning this here keeps an agent from\n * inventing an unverified sender on its first call.\n */\n defaultFrom?: string;\n /** Default reply-to used when a send omits one. */\n defaultReplyTo?: string;\n}\n\n/** Shared defaults with no API key — used by the HTTP server, which takes the key per-request. */\nexport type McpDefaults = Omit<McpConfig, 'apiKey'>;\n\nexport interface CliOptions {\n http: boolean;\n port: number;\n host: string;\n /** Hostnames permitted in HTTP mode, for DNS-rebinding protection. */\n allowedHosts: string[];\n config: McpConfig;\n}\n\nfunction readEnv(name: string): string | undefined {\n const v = process.env[name];\n return v && v.length > 0 ? v : undefined;\n}\n\n/**\n * Parse `process.argv` and the environment into resolved options.\n * Flags take precedence over environment variables.\n */\nexport function parseCliOptions(argv: string[]): CliOptions {\n const flags = new Map<string, string | boolean>();\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (!arg.startsWith('--')) continue;\n const key = arg.slice(2);\n const next = argv[i + 1];\n if (next === undefined || next.startsWith('--')) {\n flags.set(key, true);\n } else {\n flags.set(key, next);\n i++;\n }\n }\n\n const str = (key: string): string | undefined => {\n const v = flags.get(key);\n return typeof v === 'string' ? v : undefined;\n };\n\n const http = flags.get('http') === true || flags.get('http') === 'true';\n\n const apiKey = str('key') ?? readEnv('EUSEND_API_KEY') ?? '';\n const baseUrl = str('base-url') ?? readEnv('EUSEND_BASE_URL');\n const defaultFrom =\n str('from') ?? readEnv('EUSEND_FROM') ?? readEnv('SENDER_EMAIL_ADDRESS');\n const defaultReplyTo = str('reply-to') ?? readEnv('EUSEND_REPLY_TO');\n\n // PORT is read last as the platform-injected fallback (Coolify sets it to 3000).\n const port = Number(str('port') ?? readEnv('MCP_PORT') ?? readEnv('PORT') ?? '3000');\n const host = str('host') ?? readEnv('MCP_HOST') ?? '127.0.0.1';\n\n // The DNS-rebinding check matches the Host header verbatim, which includes the\n // port. Default the allowlist to both bare and port-qualified local forms.\n // Behind a reverse proxy at mcp.eusend.dev, pass --allowed-hosts explicitly.\n const allowedHostsRaw = str('allowed-hosts') ?? readEnv('MCP_ALLOWED_HOSTS');\n const allowedHosts = allowedHostsRaw\n ? allowedHostsRaw.split(',').map((h) => h.trim()).filter(Boolean)\n : ['127.0.0.1', 'localhost', `127.0.0.1:${port}`, `localhost:${port}`];\n\n return {\n http,\n port,\n host,\n allowedHosts,\n config: { apiKey, baseUrl, defaultFrom, defaultReplyTo },\n };\n}\n","#!/usr/bin/env node\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { parseCliOptions } from './config.js';\nimport { createServer } from './server.js';\nimport { runHttp } from './http.js';\n\nasync function main(): Promise<void> {\n const options = parseCliOptions(process.argv.slice(2));\n\n if (options.http) {\n // Remote/hosted mode: one HTTP endpoint, API key taken per-request from\n // the Authorization header. Same tools, different transport.\n await runHttp({\n defaults: {\n baseUrl: options.config.baseUrl,\n defaultFrom: options.config.defaultFrom,\n defaultReplyTo: options.config.defaultReplyTo,\n },\n port: options.port,\n host: options.host,\n allowedHosts: options.allowedHosts,\n });\n return;\n }\n\n // Local mode: the client launched us as a subprocess and talks over stdio.\n if (!options.config.apiKey) {\n // stderr, not stdout — stdout is the MCP protocol channel and must stay clean.\n console.error(\n 'Missing Eusend API key. Set EUSEND_API_KEY (or pass --key). Get one at https://eusend.dev/api-keys',\n );\n process.exit(1);\n }\n\n const server = createServer(options.config);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n console.error('Eusend MCP server running on stdio.');\n}\n\nmain().catch((err) => {\n console.error('Fatal error starting Eusend MCP server:', err);\n process.exit(1);\n});\n"],"mappings":";;;;AAmCA,SAAS,QAAQ,MAAkC;CACjD,MAAM,IAAI,QAAQ,IAAI;CACtB,OAAO,KAAK,EAAE,SAAS,IAAI,IAAI,KAAA;AACjC;;;;;AAMA,SAAgB,gBAAgB,MAA4B;CAC1D,MAAM,wBAAQ,IAAI,IAA8B;CAChD,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,IAAI,WAAW,IAAI,GAAG;EAC3B,MAAM,MAAM,IAAI,MAAM,CAAC;EACvB,MAAM,OAAO,KAAK,IAAI;EACtB,IAAI,SAAS,KAAA,KAAa,KAAK,WAAW,IAAI,GAC5C,MAAM,IAAI,KAAK,IAAI;OACd;GACL,MAAM,IAAI,KAAK,IAAI;GACnB;EACF;CACF;CAEA,MAAM,OAAO,QAAoC;EAC/C,MAAM,IAAI,MAAM,IAAI,GAAG;EACvB,OAAO,OAAO,MAAM,WAAW,IAAI,KAAA;CACrC;CAEA,MAAM,OAAO,MAAM,IAAI,MAAM,MAAM,QAAQ,MAAM,IAAI,MAAM,MAAM;CAEjE,MAAM,SAAS,IAAI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,MAAM,2CAA2C,GAAG;CAC5D,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/config.ts","../src/index.ts"],"sourcesContent":["/**\n * Runtime configuration for the Eusend MCP server.\n *\n * In stdio mode this is resolved once, at startup, from CLI flags and the\n * environment. In HTTP mode the `apiKey` is supplied per-request from the\n * caller's `Authorization: Bearer` header, while the defaults (`defaultFrom`,\n * `baseUrl`, …) come from the process environment shared across all callers.\n */\nexport interface McpConfig {\n /** Eusend API key used to authenticate every call the server makes. */\n apiKey: string\n /** Override the API base URL (defaults to https://api.eusend.dev). */\n baseUrl?: string\n /**\n * Sender address used when `send_email` / `create_broadcast` are called\n * without an explicit `from`. Pinning this here keeps an agent from\n * inventing an unverified sender on its first call.\n */\n defaultFrom?: string\n /** Default reply-to used when a send omits one. */\n defaultReplyTo?: string\n}\n\n/** Shared defaults with no API key — used by the HTTP server, which takes the key per-request. */\nexport type McpDefaults = Omit<McpConfig, 'apiKey'>\n\nexport interface CliOptions {\n http: boolean\n port: number\n host: string\n /** Hostnames permitted in HTTP mode, for DNS-rebinding protection. */\n allowedHosts: string[]\n config: McpConfig\n}\n\nfunction readEnv(name: string): string | undefined {\n const v = process.env[name]\n return v && v.length > 0 ? v : undefined\n}\n\n/**\n * Parse `process.argv` and the environment into resolved options.\n * Flags take precedence over environment variables.\n */\nexport function parseCliOptions(argv: string[]): CliOptions {\n const flags = new Map<string, string | boolean>()\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]\n if (!arg.startsWith('--')) continue\n const key = arg.slice(2)\n const next = argv[i + 1]\n if (next === undefined || next.startsWith('--')) {\n flags.set(key, true)\n } else {\n flags.set(key, next)\n i++\n }\n }\n\n const str = (key: string): string | undefined => {\n const v = flags.get(key)\n return typeof v === 'string' ? v : undefined\n }\n\n const http = flags.get('http') === true || flags.get('http') === 'true'\n\n const apiKey = str('key') ?? readEnv('EUSEND_API_KEY') ?? ''\n const baseUrl = str('base-url') ?? readEnv('EUSEND_BASE_URL')\n const defaultFrom = str('from') ?? readEnv('EUSEND_FROM') ?? readEnv('SENDER_EMAIL_ADDRESS')\n const defaultReplyTo = str('reply-to') ?? readEnv('EUSEND_REPLY_TO')\n\n // PORT is read last as the platform-injected fallback (Coolify sets it to 3000).\n const port = Number(str('port') ?? readEnv('MCP_PORT') ?? readEnv('PORT') ?? '3000')\n const host = str('host') ?? readEnv('MCP_HOST') ?? '127.0.0.1'\n\n // The DNS-rebinding check compares hostnames only — the port in the Host header\n // is ignored — so allowlist entries must be bare hostnames, IPv6 bracketed.\n // Behind a reverse proxy at mcp.eusend.dev, pass --allowed-hosts explicitly.\n const allowedHostsRaw = str('allowed-hosts') ?? readEnv('MCP_ALLOWED_HOSTS')\n const allowedHosts = allowedHostsRaw\n ? allowedHostsRaw\n .split(',')\n .map((h) => h.trim())\n .filter(Boolean)\n : ['127.0.0.1', 'localhost', '[::1]']\n\n return {\n http,\n port,\n host,\n allowedHosts,\n config: { apiKey, baseUrl, defaultFrom, defaultReplyTo },\n }\n}\n","#!/usr/bin/env node\nimport { serveStdio } from '@modelcontextprotocol/server/stdio'\nimport { parseCliOptions } from './config.js'\nimport { createServer } from './server.js'\nimport { runHttp } from './http.js'\n\nasync function main(): Promise<void> {\n const options = parseCliOptions(process.argv.slice(2))\n\n if (options.http) {\n // Remote/hosted mode: one HTTP endpoint, API key taken per-request from\n // the Authorization header. Same tools, different transport.\n await runHttp({\n defaults: {\n baseUrl: options.config.baseUrl,\n defaultFrom: options.config.defaultFrom,\n defaultReplyTo: options.config.defaultReplyTo,\n },\n port: options.port,\n host: options.host,\n allowedHosts: options.allowedHosts,\n })\n return\n }\n\n // Local mode: the client launched us as a subprocess and talks over stdio.\n if (!options.config.apiKey) {\n // stderr, not stdout — stdout is the MCP protocol channel and must stay clean.\n console.error(\n 'Missing Eusend API key. Set EUSEND_API_KEY (or pass --key). Get one at https://eusend.dev/api-keys',\n )\n process.exit(1)\n }\n\n // serveStdio owns the era decision: the opening exchange picks 2026-07-28 or the\n // 2025 handshake, and one instance from the factory is pinned for the lifetime\n // of the connection.\n serveStdio(() => createServer(options.config), {\n onerror: (err) => console.error('MCP stdio error:', err),\n })\n console.error('Eusend MCP server running on stdio.')\n}\n\nmain().catch((err) => {\n console.error('Fatal error starting Eusend MCP server:', err)\n process.exit(1)\n})\n"],"mappings":";;;;AAmCA,SAAS,QAAQ,MAAkC;CACjD,MAAM,IAAI,QAAQ,IAAI;CACtB,OAAO,KAAK,EAAE,SAAS,IAAI,IAAI,KAAA;AACjC;;;;;AAMA,SAAgB,gBAAgB,MAA4B;CAC1D,MAAM,wBAAQ,IAAI,IAA8B;CAChD,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;EACjB,IAAI,CAAC,IAAI,WAAW,IAAI,GAAG;EAC3B,MAAM,MAAM,IAAI,MAAM,CAAC;EACvB,MAAM,OAAO,KAAK,IAAI;EACtB,IAAI,SAAS,KAAA,KAAa,KAAK,WAAW,IAAI,GAC5C,MAAM,IAAI,KAAK,IAAI;OACd;GACL,MAAM,IAAI,KAAK,IAAI;GACnB;EACF;CACF;CAEA,MAAM,OAAO,QAAoC;EAC/C,MAAM,IAAI,MAAM,IAAI,GAAG;EACvB,OAAO,OAAO,MAAM,WAAW,IAAI,KAAA;CACrC;CAEA,MAAM,OAAO,MAAM,IAAI,MAAM,MAAM,QAAQ,MAAM,IAAI,MAAM,MAAM;CAEjE,MAAM,SAAS,IAAI,KAAK,KAAK,QAAQ,gBAAgB,KAAK;CAC1D,MAAM,UAAU,IAAI,UAAU,KAAK,QAAQ,iBAAiB;CAC5D,MAAM,cAAc,IAAI,MAAM,KAAK,QAAQ,aAAa,KAAK,QAAQ,sBAAsB;CAC3F,MAAM,iBAAiB,IAAI,UAAU,KAAK,QAAQ,iBAAiB;CAGnE,MAAM,OAAO,OAAO,IAAI,MAAM,KAAK,QAAQ,UAAU,KAAK,QAAQ,MAAM,KAAK,MAAM;CACnF,MAAM,OAAO,IAAI,MAAM,KAAK,QAAQ,UAAU,KAAK;CAKnD,MAAM,kBAAkB,IAAI,eAAe,KAAK,QAAQ,mBAAmB;CAQ3E,OAAO;EACL;EACA;EACA;EACA,cAXmB,kBACjB,gBACG,MAAM,GAAG,CAAC,CACV,KAAK,MAAM,EAAE,KAAK,CAAC,CAAC,CACpB,OAAO,OAAO,IACjB;GAAC;GAAa;GAAa;EAAO;EAOpC,QAAQ;GAAE;GAAQ;GAAS;GAAa;EAAe;CACzD;AACF;;;ACvFA,eAAe,OAAsB;CACnC,MAAM,UAAU,gBAAgB,QAAQ,KAAK,MAAM,CAAC,CAAC;CAErD,IAAI,QAAQ,MAAM;EAGhB,MAAM,QAAQ;GACZ,UAAU;IACR,SAAS,QAAQ,OAAO;IACxB,aAAa,QAAQ,OAAO;IAC5B,gBAAgB,QAAQ,OAAO;GACjC;GACA,MAAM,QAAQ;GACd,MAAM,QAAQ;GACd,cAAc,QAAQ;EACxB,CAAC;EACD;CACF;CAGA,IAAI,CAAC,QAAQ,OAAO,QAAQ;EAE1B,QAAQ,MACN,oGACF;EACA,QAAQ,KAAK,CAAC;CAChB;CAKA,iBAAiB,aAAa,QAAQ,MAAM,GAAG,EAC7C,UAAU,QAAQ,QAAQ,MAAM,oBAAoB,GAAG,EACzD,CAAC;CACD,QAAQ,MAAM,qCAAqC;AACrD;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,MAAM,2CAA2C,GAAG;CAC5D,QAAQ,KAAK,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,9 +1,17 @@
1
1
  {
2
2
  "name": "@eusend_dev/mcp",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Model Context Protocol server for the Eusend API — send email and manage domains, audiences, and broadcasts from any MCP client.",
5
5
  "author": "Eusend",
6
6
  "license": "MIT",
7
+ "homepage": "https://eusend.dev/docs/mcp",
8
+ "keywords": [
9
+ "mcp",
10
+ "model-context-protocol",
11
+ "email",
12
+ "eusend",
13
+ "transactional-email"
14
+ ],
7
15
  "type": "module",
8
16
  "bin": {
9
17
  "eusend-mcp": "./dist/index.mjs"
@@ -25,6 +33,12 @@
25
33
  "files": [
26
34
  "dist"
27
35
  ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "engines": {
40
+ "node": ">=20"
41
+ },
28
42
  "scripts": {
29
43
  "build": "tsdown src/index.ts src/http.ts --format esm --dts",
30
44
  "dev": "tsdown src/index.ts src/http.ts --format esm --dts --watch",
@@ -33,13 +47,14 @@
33
47
  "typecheck": "tsc --noEmit"
34
48
  },
35
49
  "dependencies": {
36
- "@eusend_dev/sdk": "workspace:*",
37
- "@modelcontextprotocol/sdk": "^1.12.0",
38
- "zod": "latest"
50
+ "@eusend_dev/sdk": "^0.11.0",
51
+ "zod": "^4.4.3",
52
+ "@modelcontextprotocol/node": "^2.0.0",
53
+ "@modelcontextprotocol/server": "^2.0.0"
39
54
  },
40
55
  "devDependencies": {
41
- "@types/node": "latest",
42
- "tsdown": "latest",
43
- "typescript": "latest"
56
+ "@types/node": "^26.1.1",
57
+ "tsdown": "^0.22.14",
58
+ "typescript": "^7.0.2"
44
59
  }
45
60
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"http-BiRaRNNh.mjs","names":["createServer","createHttpServer","createServer"],"sources":["../src/respond.ts","../src/tools/emails.ts","../src/tools/domains.ts","../src/tools/audiences.ts","../src/tools/broadcasts.ts","../src/server.ts","../src/ratelimit.ts","../src/http.ts"],"sourcesContent":["import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport type { EusendError, EusendResponse } from '@eusend_dev/sdk';\n\n/** MCP tool return shape. */\nexport type ToolResult = CallToolResult;\n\n/** Wrap a successful payload as pretty-printed JSON text content. */\nexport function ok(data: unknown): ToolResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n };\n}\n\n/**\n * Surface an SDK error as an MCP tool error. `isError: true` tells the client\n * the call failed, and the error `name` (e.g. DOMAIN_NOT_VERIFIED) gives the\n * agent enough to self-correct — e.g. verify the domain, then retry.\n */\nexport function fail(error: EusendError): ToolResult {\n return {\n content: [{ type: 'text', text: `Error [${error.name}]: ${error.message}` }],\n isError: true,\n };\n}\n\n/** Plain text error for validation the tool does itself before hitting the API. */\nexport function failText(message: string): ToolResult {\n return { content: [{ type: 'text', text: message }], isError: true };\n}\n\n/** Turn any SDK `EusendResponse` into a tool result. */\nexport function respond<T>(res: EusendResponse<T>): ToolResult {\n return res.error ? fail(res.error) : ok(res.data);\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { Eusend } from '@eusend_dev/sdk';\nimport { z } from 'zod';\nimport type { McpConfig } from '../config.js';\nimport { respond, failText } from '../respond.js';\n\nconst emailStatus = z.enum([\n 'queued',\n 'scheduled',\n 'canceled',\n 'sending',\n 'sent',\n 'delivered',\n 'bounced',\n 'complained',\n 'suppressed',\n 'failed',\n]);\n\nconst recipients = z.union([z.string(), z.array(z.string())]);\n\nexport function registerEmailTools(server: McpServer, client: Eusend, config: McpConfig): void {\n server.registerTool(\n 'send_email',\n {\n title: 'Send an email',\n description:\n 'Send a transactional email through Eusend. Provide `html` or `text` (or both). ' +\n 'The sender domain must be verified on the account — use list_domains to check. ' +\n 'If `from` is omitted, the server-configured default sender is used.',\n inputSchema: {\n from: z\n .string()\n .optional()\n .describe('Sender, e.g. \"Acme <hi@acme.com>\". Defaults to the configured sender.'),\n to: recipients.describe('Recipient address or list of addresses.'),\n subject: z.string().describe('Email subject line.'),\n text: z.string().optional().describe('Plain-text body.'),\n html: z.string().optional().describe('HTML body. Takes precedence over text for display.'),\n cc: recipients.optional(),\n bcc: recipients.optional(),\n replyTo: recipients.optional().describe('Reply-To address(es).'),\n scheduledAt: z\n .string()\n .optional()\n .describe('Future send time: ISO 8601 or natural language like \"in 1 hour\". Max 30 days out.'),\n },\n },\n async (args) => {\n const from = args.from ?? config.defaultFrom;\n if (!from) {\n return failText(\n 'No sender specified and no default sender configured. Pass `from`, or set EUSEND_FROM / --from on the server.',\n );\n }\n if (!args.html && !args.text) {\n return failText('Provide at least one of `html` or `text`.');\n }\n return respond(\n await client.emails.send({\n from,\n to: args.to,\n subject: args.subject,\n text: args.text,\n html: args.html,\n cc: args.cc,\n bcc: args.bcc,\n replyTo: args.replyTo ?? config.defaultReplyTo,\n scheduledAt: args.scheduledAt,\n }),\n );\n },\n );\n\n server.registerTool(\n 'list_emails',\n {\n title: 'List emails',\n description: 'List recently sent emails, most recent first. Supports cursor pagination and filtering.',\n inputSchema: {\n limit: z.number().int().min(1).max(100).optional().describe('Max results (1–100).'),\n cursor: z.string().optional().describe('Pagination cursor from a previous nextCursor.'),\n status: emailStatus.optional().describe('Filter by delivery status.'),\n from: z.string().optional().describe('Filter by sender address.'),\n to: z.string().optional().describe('Filter by recipient address.'),\n },\n },\n async (args) => respond(await client.emails.list(args)),\n );\n\n server.registerTool(\n 'get_email',\n {\n title: 'Get an email',\n description: 'Fetch a single email by id, including its full delivery event history.',\n inputSchema: {\n id: z.string().describe('The email id returned by send_email or list_emails.'),\n },\n },\n async ({ id }) => respond(await client.emails.get(id)),\n );\n\n server.registerTool(\n 'cancel_email',\n {\n title: 'Cancel a scheduled email',\n description: 'Cancel a scheduled email before it sends. Fails once the email has started sending.',\n inputSchema: {\n id: z.string().describe('The id of a scheduled email.'),\n },\n },\n async ({ id }) => respond(await client.emails.cancel(id)),\n );\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { Eusend } from '@eusend_dev/sdk';\nimport { z } from 'zod';\nimport { respond } from '../respond.js';\n\nexport function registerDomainTools(server: McpServer, client: Eusend): void {\n server.registerTool(\n 'list_domains',\n {\n title: 'List domains',\n description: 'List sending domains on the account and their verification status.',\n inputSchema: {},\n },\n async () => respond(await client.domains.list()),\n );\n\n server.registerTool(\n 'get_domain',\n {\n title: 'Get a domain',\n description: 'Fetch a single domain by id, including its DKIM selector and verification state.',\n inputSchema: {\n id: z.string().describe('The domain id.'),\n },\n },\n async ({ id }) => respond(await client.domains.get(id)),\n );\n\n server.registerTool(\n 'create_domain',\n {\n title: 'Add a sending domain',\n description:\n 'Register a new sending domain. Returns the DKIM, SPF, and DMARC DNS records that must be ' +\n 'added at the domain\\'s DNS provider before it can send. Present these records to the user.',\n inputSchema: {\n name: z.string().describe('The domain to add, e.g. \"mail.acme.com\".'),\n },\n },\n async ({ name }) => respond(await client.domains.create(name)),\n );\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { Eusend } from '@eusend_dev/sdk';\nimport { z } from 'zod';\nimport { respond } from '../respond.js';\n\nexport function registerAudienceTools(server: McpServer, client: Eusend): void {\n server.registerTool(\n 'list_audiences',\n {\n title: 'List audiences',\n description: 'List contact audiences (lists) on the account, with per-audience contact counts.',\n inputSchema: {},\n },\n async () => respond(await client.audiences.list()),\n );\n\n server.registerTool(\n 'create_audience',\n {\n title: 'Create an audience',\n description: 'Create a new audience (contact list) to hold contacts for broadcasts.',\n inputSchema: {\n name: z.string().describe('Human-readable name for the audience.'),\n },\n },\n async ({ name }) => respond(await client.audiences.create(name)),\n );\n\n server.registerTool(\n 'list_contacts',\n {\n title: 'List contacts',\n description: 'List contacts in an audience. Supports search and subscription filtering.',\n inputSchema: {\n audienceId: z.string().describe('The audience to list contacts from.'),\n limit: z.number().int().min(1).max(100).optional(),\n cursor: z.string().optional().describe('Pagination cursor from a previous nextCursor.'),\n search: z.string().optional().describe('Filter by email or name substring.'),\n subscribed: z.boolean().optional().describe('true = only subscribed, false = only unsubscribed.'),\n },\n },\n async ({ audienceId, ...opts }) => respond(await client.audiences.listContacts(audienceId, opts)),\n );\n\n server.registerTool(\n 'create_contact',\n {\n title: 'Add a contact',\n description: 'Add a contact to an audience.',\n inputSchema: {\n audienceId: z.string().describe('The audience to add the contact to.'),\n email: z.string().describe('Contact email address.'),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n },\n },\n async ({ audienceId, email, firstName, lastName }) =>\n respond(await client.audiences.createContact(audienceId, { email, firstName, lastName })),\n );\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { Eusend } from '@eusend_dev/sdk';\nimport { z } from 'zod';\nimport type { McpConfig } from '../config.js';\nimport { respond, failText } from '../respond.js';\n\nexport function registerBroadcastTools(server: McpServer, client: Eusend, config: McpConfig): void {\n server.registerTool(\n 'list_broadcasts',\n {\n title: 'List broadcasts',\n description: 'List broadcasts (bulk sends to an audience) with their status and send counts.',\n inputSchema: {},\n },\n async () => respond(await client.broadcasts.list()),\n );\n\n server.registerTool(\n 'get_broadcast',\n {\n title: 'Get a broadcast',\n description: 'Fetch a broadcast by id, including recipient/sent counts and per-event stats.',\n inputSchema: {\n id: z.string().describe('The broadcast id.'),\n },\n },\n async ({ id }) => respond(await client.broadcasts.get(id)),\n );\n\n server.registerTool(\n 'create_broadcast',\n {\n title: 'Create a broadcast (draft)',\n description:\n 'Create a broadcast in draft state, targeting an audience. Does NOT send it — use send_broadcast ' +\n 'to send or schedule after reviewing. If `from` is omitted the configured default sender is used.',\n inputSchema: {\n name: z.string().describe('Internal name for the broadcast.'),\n audienceId: z.string().describe('The audience to send to.'),\n subject: z.string().describe('Email subject line.'),\n from: z.string().optional().describe('Sender. Defaults to the configured sender.'),\n html: z.string().optional().describe('HTML body of the broadcast.'),\n },\n },\n async (args) => {\n const from = args.from ?? config.defaultFrom;\n if (!from) {\n return failText(\n 'No sender specified and no default sender configured. Pass `from`, or set EUSEND_FROM / --from on the server.',\n );\n }\n return respond(\n await client.broadcasts.create({\n name: args.name,\n audienceId: args.audienceId,\n subject: args.subject,\n from,\n html: args.html,\n }),\n );\n },\n );\n\n server.registerTool(\n 'send_broadcast',\n {\n title: 'Send or schedule a broadcast',\n description:\n 'Send a draft broadcast to its entire audience now, or schedule it for later. This is a bulk send — ' +\n 'confirm with the user before calling. Omit `scheduledAt` to send immediately.',\n inputSchema: {\n id: z.string().describe('The draft broadcast id.'),\n scheduledAt: z\n .string()\n .optional()\n .describe('Optional future send time (ISO 8601). Omit to send immediately.'),\n },\n },\n async ({ id, scheduledAt }) => respond(await client.broadcasts.send(id, { scheduledAt })),\n );\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { Eusend } from '@eusend_dev/sdk';\nimport type { McpConfig } from './config.js';\nimport { registerEmailTools } from './tools/emails.js';\nimport { registerDomainTools } from './tools/domains.js';\nimport { registerAudienceTools } from './tools/audiences.js';\nimport { registerBroadcastTools } from './tools/broadcasts.js';\n\nexport const SERVER_NAME = 'eusend';\nexport const SERVER_VERSION = '0.1.1';\n\n/**\n * Build a fully-wired MCP server for one Eusend account. This is\n * transport-agnostic: the stdio entry (index.ts) and the HTTP entry (http.ts)\n * both call this and then attach their own transport. All tool definitions live\n * in ./tools and are registered here exactly once.\n */\nexport function createServer(config: McpConfig): McpServer {\n const server = new McpServer({\n name: SERVER_NAME,\n version: SERVER_VERSION,\n });\n\n const client = new Eusend(config.apiKey, { baseUrl: config.baseUrl });\n\n registerEmailTools(server, client, config);\n registerDomainTools(server, client);\n registerAudienceTools(server, client);\n registerBroadcastTools(server, client, config);\n\n return server;\n}\n","import type { IncomingMessage } from 'node:http';\n\n/**\n * Minimal in-memory fixed-window IP rate limiter for the public /mcp endpoint.\n *\n * The endpoint is unauthenticated at the transport layer (initialize/tools/list\n * work before any API key is validated), so it needs its own basic DoS ceiling\n * independent of the API's rate limiting. In-memory on purpose: it keeps the box\n * free of any external dependency or credential. Per-container state is fine here\n * — the limit is a coarse abuse ceiling, not an accounting mechanism.\n */\nexport interface RateLimiter {\n /** Returns true if the request is allowed, false if it should be rejected (429). */\n check(req: IncomingMessage): boolean;\n}\n\n// Hard cap on distinct tracked IPs so a high-cardinality flood can't grow the map\n// unbounded within a window. When exceeded, new IPs are denied until the next sweep\n// (fail closed under abuse) rather than consuming memory.\nconst MAX_BUCKETS = 50_000;\n\n/**\n * Trusted client IP. Coolify's Traefik sits in front and OVERWRITES X-Real-Ip with the\n * real connection address, so it can't be spoofed by a client-sent header. We deliberately\n * do NOT trust X-Forwarded-For here: Traefik appends the real IP to any client-supplied\n * XFF, so its leftmost entry is attacker-controlled and would let a caller mint a fresh\n * bucket per request. Falls back to the socket address when there's no proxy (local runs).\n */\nfunction clientIp(req: IncomingMessage): string {\n const realIp = req.headers['x-real-ip'];\n if (typeof realIp === 'string' && realIp.length > 0) {\n return realIp.trim();\n }\n return req.socket.remoteAddress ?? 'unknown';\n}\n\nexport function createRateLimiter(limit: number, windowMs: number): RateLimiter {\n const buckets = new Map<string, { count: number; resetAt: number }>();\n\n // Evict stale buckets so the map can't grow unbounded under a churn of IPs.\n const sweep = setInterval(() => {\n const now = Date.now();\n for (const [key, b] of buckets) {\n if (now > b.resetAt) buckets.delete(key);\n }\n }, windowMs);\n sweep.unref();\n\n return {\n check(req) {\n const key = clientIp(req);\n const now = Date.now();\n const bucket = buckets.get(key);\n if (!bucket || now > bucket.resetAt) {\n if (!bucket && buckets.size >= MAX_BUCKETS) {\n // Try to reclaim expired buckets before refusing.\n for (const [k, b] of buckets) if (now > b.resetAt) buckets.delete(k);\n if (buckets.size >= MAX_BUCKETS) return false;\n }\n buckets.set(key, { count: 1, resetAt: now + windowMs });\n return true;\n }\n bucket.count += 1;\n return bucket.count <= limit;\n },\n };\n}\n","import { createServer as createHttpServer, type IncomingMessage, type ServerResponse } from 'node:http';\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\nimport type { McpDefaults } from './config.js';\nimport { createServer } from './server.js';\nimport { createRateLimiter } from './ratelimit.js';\n\nexport interface RunHttpOptions {\n /** Account-agnostic defaults; the API key comes per-request from the caller. */\n defaults: McpDefaults;\n port: number;\n host: string;\n /** Hostnames allowed in the Host header (DNS-rebinding protection). */\n allowedHosts: string[];\n}\n\nconst MCP_PATH = '/mcp';\n\n// Coarse per-IP DoS ceiling for the public endpoint. Each JSON-RPC call over an\n// MCP session is one request, so this is generous for a real agent while still\n// capping an anonymous flood. Tune via RATE_LIMIT_PER_MIN if needed.\nconst RATE_LIMIT_PER_MIN = Number(process.env.RATE_LIMIT_PER_MIN ?? '120');\nconst rateLimiter = createRateLimiter(RATE_LIMIT_PER_MIN, 60_000);\n\nfunction json(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(body));\n}\n\n/** Pull the API key out of `Authorization: Bearer <key>`. */\nfunction bearerKey(req: IncomingMessage): string | undefined {\n const header = req.headers.authorization;\n if (!header) return undefined;\n const [scheme, value] = header.split(' ');\n return scheme?.toLowerCase() === 'bearer' && value ? value : undefined;\n}\n\nasync function readBody(req: IncomingMessage): Promise<unknown> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n if (chunks.length === 0) return undefined;\n return JSON.parse(Buffer.concat(chunks).toString('utf8'));\n}\n\n/**\n * Run the Eusend MCP server over Streamable HTTP — the hosted/remote transport.\n * Stateless: every request builds a fresh server bound to the caller's API key,\n * so one endpoint safely serves many accounts. Mount this behind TLS at, e.g.,\n * https://mcp.eusend.dev/mcp.\n */\nexport async function runHttp(options: RunHttpOptions): Promise<void> {\n const httpServer = createHttpServer((req, res) => {\n void handle(req, res, options);\n });\n\n await new Promise<void>((resolve) => {\n httpServer.listen(options.port, options.host, resolve);\n });\n console.error(`Eusend MCP server (HTTP) listening on http://${options.host}:${options.port}${MCP_PATH}`);\n}\n\nasync function handle(req: IncomingMessage, res: ServerResponse, options: RunHttpOptions): Promise<void> {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);\n\n if (url.pathname === '/health') {\n return json(res, 200, { status: 'ok' });\n }\n\n if (url.pathname !== MCP_PATH) {\n return json(res, 404, { error: 'Not found' });\n }\n\n // Stateless server: sessions aren't retained, so GET (server-push stream) and\n // DELETE (session teardown) have nothing to act on.\n if (req.method !== 'POST') {\n res.writeHead(405, { Allow: 'POST' });\n return void res.end();\n }\n\n if (!rateLimiter.check(req)) {\n return json(res, 429, {\n jsonrpc: '2.0',\n error: { code: -32029, message: 'Too many requests. Slow down.' },\n id: null,\n });\n }\n\n const apiKey = bearerKey(req);\n if (!apiKey) {\n return json(res, 401, {\n jsonrpc: '2.0',\n error: { code: -32001, message: 'Missing or malformed Authorization: Bearer <api-key> header.' },\n id: null,\n });\n }\n\n const server = createServer({ apiKey, ...options.defaults });\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n enableDnsRebindingProtection: true,\n allowedHosts: options.allowedHosts,\n });\n\n res.on('close', () => {\n void transport.close();\n void server.close();\n });\n\n try {\n await server.connect(transport);\n const body = await readBody(req);\n await transport.handleRequest(req, res, body);\n } catch (err) {\n console.error('Error handling MCP request:', err);\n if (!res.headersSent) {\n json(res, 500, {\n jsonrpc: '2.0',\n error: { code: -32603, message: 'Internal server error' },\n id: null,\n });\n }\n }\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,GAAG,MAA2B;CAC5C,OAAO,EACL,SAAS,CAAC;EAAE,MAAM;EAAQ,MAAM,KAAK,UAAU,MAAM,MAAM,CAAC;CAAE,CAAC,EACjE;AACF;;;;;;AAOA,SAAgB,KAAK,OAAgC;CACnD,OAAO;EACL,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM,UAAU,MAAM,KAAK,KAAK,MAAM;EAAU,CAAC;EAC3E,SAAS;CACX;AACF;;AAGA,SAAgB,SAAS,SAA6B;CACpD,OAAO;EAAE,SAAS,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAQ,CAAC;EAAG,SAAS;CAAK;AACrE;;AAGA,SAAgB,QAAW,KAAoC;CAC7D,OAAO,IAAI,QAAQ,KAAK,IAAI,KAAK,IAAI,GAAG,IAAI,IAAI;AAClD;;;AC3BA,MAAM,cAAc,EAAE,KAAK;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,a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