@teamnetwork-nz/smtp-mcp-server 1.2.0 → 1.4.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
@@ -1,5 +1,9 @@
1
1
  # @teamnetwork-nz/smtp-mcp-server
2
2
 
3
+ ## Streamable HTTP
4
+
5
+ Set `SMTP_TRANSPORT=http` to serve stateless MCP at `/mcp`. The default bind is `127.0.0.1`; remote binding requires `SMTP_HTTP_BEARER_TOKEN` and `SMTP_HTTP_ALLOWED_HOSTS`. `SMTP_HTTP_PORT` and `SMTP_HTTP_ALLOWED_ORIGINS` are optional.
6
+
3
7
  An MCP server that lets AI agents send email via any SMTP relay. Recipient restrictions, sender identity, and SMTP credentials are all enforced server-side — an agent cannot override them.
4
8
 
5
9
  ## Features
@@ -95,11 +99,9 @@ Returns JSON with `filename`, `content_type`, and `content` (base64). Pass these
95
99
 
96
100
  **Recommended workflow for attachments:**
97
101
  ```
98
- 1. encode_file({ path: "/path/to/report.zip" })
99
- → { filename: "report.zip", content_type: "application/zip", content: "..." }
100
-
101
- 2. send_email({ ..., attachments: [{ filename, content_type, content }] })
102
+ send_email({ ..., attachments: [{ path: "/absolute/path/to/report.zip" }] })
102
103
  ```
104
+ The server reads, encodes, and detects the MIME type automatically. Binary data never passes through the agent's context.
103
105
 
104
106
  ---
105
107
 
@@ -132,13 +134,14 @@ Returns `isError: true` if the connection test fails, with the SMTP error messag
132
134
  | `bcc` | string \| string[] | no | BCC recipient(s) |
133
135
  | `attachments` | Attachment[] | no | Files to attach |
134
136
 
135
- **Attachment object:**
137
+ **Attachment object — supply `path` or `content`, not both:**
136
138
 
137
- | Field | Type | Description |
138
- |---|---|---|
139
- | `filename` | string | Name shown to recipient |
140
- | `content` | string | Base64-encoded file data |
141
- | `content_type` | string | MIME type, e.g. `application/pdf` |
139
+ | Field | Type | Required | Description |
140
+ |---|---|---|---|
141
+ | `path` | string | if no `content` | Absolute path to file — server reads and encodes it |
142
+ | `content` | string | if no `path` | Base64-encoded file data (no `data:` URI prefix) |
143
+ | `filename` | string | if using `content` | Name shown to recipient; defaults to basename of `path` |
144
+ | `content_type` | string | if using `content` | MIME type; auto-detected from `path` extension if omitted |
142
145
 
143
146
  ---
144
147
 
package/dist/email.js CHANGED
@@ -6,7 +6,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createTransport = createTransport;
7
7
  exports.verifyTransport = verifyTransport;
8
8
  exports.sendEmail = sendEmail;
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
9
11
  const nodemailer_1 = __importDefault(require("nodemailer"));
12
+ const mime_js_1 = require("./mime.js");
10
13
  const DATA_URI_PREFIX = /^data:[^;,]*(;[^,]*)?,/;
11
14
  const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;
12
15
  const MIME_TYPE_PATTERN = /^[\w!#$&\-^.+]+\/[\w!#$&\-^.+]+$/;
@@ -48,6 +51,26 @@ function createTransport(smtpConfig) {
48
51
  async function verifyTransport(transport) {
49
52
  await transport.verify();
50
53
  }
54
+ function resolveAttachment(a) {
55
+ if (a.path) {
56
+ if (!fs_1.default.existsSync(a.path)) {
57
+ throw new Error(`Attachment file not found: ${a.path}`);
58
+ }
59
+ return {
60
+ filename: a.filename ?? path_1.default.basename(a.path),
61
+ content: fs_1.default.readFileSync(a.path),
62
+ contentType: a.content_type ?? (0, mime_js_1.mimeFromExtension)(a.path),
63
+ };
64
+ }
65
+ const content = a.content;
66
+ const filename = a.filename;
67
+ const content_type = a.content_type;
68
+ return {
69
+ filename,
70
+ content: Buffer.from(normalizeAndValidateBase64(content, filename), "base64"),
71
+ contentType: validateContentType(content_type, filename),
72
+ };
73
+ }
51
74
  async function sendEmail(transport, from, options) {
52
75
  const message = {
53
76
  from: `"${from.name}" <${from.address}>`,
@@ -55,11 +78,7 @@ async function sendEmail(transport, from, options) {
55
78
  subject: options.subject,
56
79
  cc: options.cc,
57
80
  bcc: options.bcc,
58
- attachments: options.attachments?.map((a) => ({
59
- filename: a.filename,
60
- content: Buffer.from(normalizeAndValidateBase64(a.content, a.filename), "base64"),
61
- contentType: validateContentType(a.content_type, a.filename),
62
- })),
81
+ attachments: options.attachments?.map((a) => resolveAttachment(a)),
63
82
  };
64
83
  if (options.body_type === "html") {
65
84
  message.html = options.body;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateHttpOptions = validateHttpOptions;
7
+ exports.createHttpServer = createHttpServer;
8
+ const node_crypto_1 = require("node:crypto");
9
+ const node_http_1 = __importDefault(require("node:http"));
10
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
11
+ const loopback = new Set(["127.0.0.1", "::1", "localhost"]);
12
+ const send = (res, status, body) => {
13
+ res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(body));
14
+ };
15
+ const error = (res, status, code, message) => send(res, status, { jsonrpc: "2.0", error: { code, message }, id: null });
16
+ const matches = (value, expected) => {
17
+ if (!value?.startsWith("Bearer "))
18
+ return false;
19
+ const supplied = Buffer.from(value.slice(7));
20
+ const wanted = Buffer.from(expected);
21
+ return supplied.length === wanted.length && (0, node_crypto_1.timingSafeEqual)(supplied, wanted);
22
+ };
23
+ const readBody = (req, limit) => new Promise((resolve, reject) => {
24
+ const chunks = [];
25
+ let size = 0;
26
+ let oversized = false;
27
+ req.on("data", (chunk) => { size += chunk.length; oversized ||= size > limit; if (!oversized)
28
+ chunks.push(chunk); });
29
+ req.on("end", () => {
30
+ if (oversized)
31
+ return reject(Object.assign(new Error("Request body too large"), { statusCode: 413 }));
32
+ try {
33
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
34
+ }
35
+ catch {
36
+ reject(Object.assign(new Error("Invalid JSON body"), { statusCode: 400 }));
37
+ }
38
+ });
39
+ req.on("error", reject);
40
+ });
41
+ function validateHttpOptions(o) {
42
+ if (!Number.isInteger(o.port) || o.port < 1 || o.port > 65535)
43
+ throw new Error(`Invalid HTTP port: ${o.port}`);
44
+ if (o.maxBodyBytes !== undefined && (!Number.isInteger(o.maxBodyBytes) || o.maxBodyBytes < 1))
45
+ throw new Error(`Invalid HTTP body limit: ${o.maxBodyBytes}`);
46
+ if (!loopback.has(o.host) && !o.bearerToken)
47
+ throw new Error("A bearer token is required when binding beyond loopback");
48
+ if (!loopback.has(o.host) && !o.allowedHosts?.length)
49
+ throw new Error("HTTP_ALLOWED_HOSTS is required when binding beyond loopback");
50
+ }
51
+ function createHttpServer(factory, o) {
52
+ validateHttpOptions(o);
53
+ const hosts = new Set(o.allowedHosts?.map(v => v.toLowerCase()));
54
+ const origins = new Set(o.allowedOrigins?.map(v => v.toLowerCase()));
55
+ return node_http_1.default.createServer(async (req, res) => {
56
+ const path = new URL(req.url ?? "/", "http://localhost").pathname;
57
+ if (path === "/health")
58
+ return send(res, 200, { status: "ok", server: o.serverName });
59
+ if (path !== "/mcp")
60
+ return void res.writeHead(404).end();
61
+ if (hosts.size && !hosts.has((req.headers.host ?? "").toLowerCase()))
62
+ return error(res, 403, -32000, "Host not allowed");
63
+ if (req.headers.origin && !origins.has(req.headers.origin.toLowerCase()))
64
+ return error(res, 403, -32000, "Origin not allowed");
65
+ if (o.bearerToken && !matches(req.headers.authorization, o.bearerToken)) {
66
+ res.setHeader("WWW-Authenticate", "Bearer");
67
+ return error(res, 401, -32001, "Unauthorized");
68
+ }
69
+ if (req.method !== "POST") {
70
+ res.setHeader("Allow", "POST");
71
+ return error(res, 405, -32000, "Method not allowed");
72
+ }
73
+ const server = factory();
74
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
75
+ try {
76
+ const body = await readBody(req, o.maxBodyBytes ?? 1048576);
77
+ await server.connect(transport);
78
+ await transport.handleRequest(req, res, body);
79
+ res.once("close", () => { void transport.close(); void server.close(); });
80
+ }
81
+ catch (cause) {
82
+ void transport.close();
83
+ void server.close();
84
+ if (!res.headersSent) {
85
+ const status = cause.statusCode ?? 500;
86
+ error(res, status, status === 400 ? -32700 : -32603, status < 500 ? cause.message : "Internal server error");
87
+ }
88
+ }
89
+ });
90
+ }
package/dist/index.js CHANGED
@@ -41,203 +41,214 @@ const config_js_1 = require("./config.js");
41
41
  const restrictions_js_1 = require("./restrictions.js");
42
42
  const email_js_1 = require("./email.js");
43
43
  const mime_js_1 = require("./mime.js");
44
+ const http_server_js_1 = require("./http-server.js");
44
45
  const transport = (0, email_js_1.createTransport)(config_js_1.config.smtp);
45
- const server = new mcp_js_1.McpServer({
46
- name: "smtp-mcp",
47
- version: "1.2.0",
48
- });
49
- // ---------------------------------------------------------------------------
50
- // Shared schemas
51
- // ---------------------------------------------------------------------------
52
- const attachmentSchema = zod_1.z.object({
53
- filename: zod_1.z.string().min(1),
54
- content: zod_1.z.string().min(1).describe("Base64-encoded file content"),
55
- content_type: zod_1.z.string().min(1).describe("MIME type, e.g. application/pdf"),
56
- });
57
- const recipientSchema = zod_1.z
58
- .union([zod_1.z.string().email(), zod_1.z.array(zod_1.z.string().email()).min(1)])
59
- .transform((v) => (Array.isArray(v) ? v : [v]));
60
- // ---------------------------------------------------------------------------
61
- // Tool: health
62
- // ---------------------------------------------------------------------------
63
- server.registerTool("health", {
64
- description: "Check that the SMTP server is reachable and the configuration is valid. " +
65
- "Returns the active settings (host, port, auth mode, sender identity, restrictions) " +
66
- "and the result of a live connection test.",
67
- }, async () => {
68
- const start = Date.now();
69
- let connectionStatus;
70
- let isError = false;
71
- try {
72
- await (0, email_js_1.verifyTransport)(transport);
73
- connectionStatus = `OK (${Date.now() - start} ms)`;
74
- }
75
- catch (err) {
76
- connectionStatus = `FAILED — ${err instanceof Error ? err.message : String(err)}`;
77
- isError = true;
78
- }
79
- const { allowedDomains, allowedAddresses } = config_js_1.config.restrictions;
80
- const restrictionSummary = allowedDomains.length === 0 && allowedAddresses.length === 0
81
- ? "none (all addresses permitted)"
82
- : [
83
- allowedDomains.length
84
- ? `domains: ${allowedDomains.join(", ")}`
85
- : null,
86
- allowedAddresses.length
87
- ? `addresses: ${allowedAddresses.join(", ")}`
88
- : null,
89
- ]
90
- .filter(Boolean)
91
- .join(" | ");
92
- const lines = [
93
- `connection: ${connectionStatus}`,
94
- `smtp_host: ${config_js_1.config.smtp.host}:${config_js_1.config.smtp.port}`,
95
- `tls: ${config_js_1.config.smtp.secure ? "implicit TLS" : config_js_1.config.smtp.ignoreTls ? "none (plain SMTP)" : "STARTTLS"}`,
96
- `auth: ${config_js_1.config.smtp.user ? `authenticated as ${config_js_1.config.smtp.user}` : "unauthenticated"}`,
97
- `from: "${config_js_1.config.from.name}" <${config_js_1.config.from.address}>`,
98
- `restrictions: ${restrictionSummary}`,
99
- ];
100
- return {
101
- isError,
102
- content: [{ type: "text", text: lines.join("\n") }],
103
- };
104
- });
105
- // ---------------------------------------------------------------------------
106
- // Tool: encode_file
107
- // ---------------------------------------------------------------------------
108
- server.registerTool("encode_file", {
109
- description: "Read a file from disk and return it base64-encoded, ready to pass directly " +
110
- "into the send_email attachments array. Also returns the detected MIME type " +
111
- "and filename so the agent does not need to derive them manually.",
112
- inputSchema: {
113
- path: zod_1.z.string().min(1).describe("Absolute or relative path to the file"),
114
- content_type: zod_1.z
115
- .string()
116
- .optional()
117
- .describe("MIME type override. If omitted the type is detected from the file extension."),
118
- },
119
- }, async (args) => {
120
- const fs = await Promise.resolve().then(() => __importStar(require("fs")));
121
- const nodePath = await Promise.resolve().then(() => __importStar(require("path")));
122
- if (!fs.existsSync(args.path)) {
123
- return {
124
- isError: true,
125
- content: [{ type: "text", text: `File not found: ${args.path}` }],
126
- };
127
- }
128
- try {
129
- const data = fs.readFileSync(args.path);
130
- const content = data.toString("base64");
131
- const filename = nodePath.basename(args.path);
132
- const content_type = args.content_type ?? (0, mime_js_1.mimeFromExtension)(args.path);
133
- return {
134
- content: [
135
- {
136
- type: "text",
137
- text: JSON.stringify({ filename, content_type, content }),
138
- },
139
- ],
140
- };
141
- }
142
- catch (err) {
143
- const message = err instanceof Error ? err.message : String(err);
144
- return {
145
- isError: true,
146
- content: [{ type: "text", text: `Failed to read file: ${message}` }],
147
- };
148
- }
149
- });
150
- // ---------------------------------------------------------------------------
151
- // Tool: send_email
152
- // ---------------------------------------------------------------------------
153
- server.registerTool("send_email", {
154
- description: "Send an email via SMTP. Recipient addresses are validated against the server's allowed domains/addresses policy.",
155
- inputSchema: {
156
- to: recipientSchema.describe("Recipient address or list of addresses"),
157
- subject: zod_1.z.string().min(1).describe("Email subject line"),
158
- body: zod_1.z.string().min(1).describe("Email body content"),
159
- body_type: zod_1.z
160
- .enum(["text", "html"])
161
- .default("text")
162
- .describe("Body format — plain text (default) or HTML"),
163
- cc: recipientSchema
164
- .optional()
165
- .describe("CC address or list of addresses"),
166
- bcc: recipientSchema
167
- .optional()
168
- .describe("BCC address or list of addresses"),
169
- attachments: zod_1.z
170
- .array(attachmentSchema)
171
- .optional()
172
- .describe("Files to attach"),
173
- },
174
- }, async (args) => {
175
- const allRecipients = [
176
- ...args.to,
177
- ...(args.cc ?? []),
178
- ...(args.bcc ?? []),
179
- ];
180
- const check = (0, restrictions_js_1.checkRecipients)(allRecipients, config_js_1.config.restrictions);
181
- if (!check.allowed) {
182
- return {
183
- isError: true,
184
- content: [
185
- {
186
- type: "text",
187
- text: `Recipient(s) not permitted by server policy: ${check.blocked.join(", ")}`,
188
- },
189
- ],
190
- };
191
- }
192
- try {
193
- const result = await (0, email_js_1.sendEmail)(transport, config_js_1.config.from, {
194
- to: args.to,
195
- subject: args.subject,
196
- body: args.body,
197
- body_type: args.body_type,
198
- cc: args.cc,
199
- bcc: args.bcc,
200
- attachments: args.attachments,
201
- });
46
+ function createConfiguredServer() {
47
+ const server = new mcp_js_1.McpServer({
48
+ name: "smtp-mcp",
49
+ version: "1.4.0",
50
+ });
51
+ // ---------------------------------------------------------------------------
52
+ // Shared schemas
53
+ // ---------------------------------------------------------------------------
54
+ const attachmentSchema = zod_1.z
55
+ .object({
56
+ path: zod_1.z.string().optional().describe("Absolute path to the file on disk — server reads and encodes it"),
57
+ filename: zod_1.z.string().optional().describe("Override the filename shown to the recipient"),
58
+ content: zod_1.z.string().optional().describe("Base64-encoded file content (use path instead where possible)"),
59
+ content_type: zod_1.z.string().optional().describe("MIME type — auto-detected from path extension if omitted"),
60
+ })
61
+ .refine((a) => a.path || a.content, {
62
+ message: "Each attachment must include either 'path' (preferred) or 'content' (base64)",
63
+ })
64
+ .refine((a) => !a.content || (a.filename && a.content_type), {
65
+ message: "Attachments using 'content' must also include 'filename' and 'content_type'",
66
+ });
67
+ const recipientSchema = zod_1.z
68
+ .union([zod_1.z.string().email(), zod_1.z.array(zod_1.z.string().email()).min(1)])
69
+ .transform((v) => (Array.isArray(v) ? v : [v]));
70
+ // ---------------------------------------------------------------------------
71
+ // Tool: health
72
+ // ---------------------------------------------------------------------------
73
+ server.registerTool("health", {
74
+ description: "Check that the SMTP server is reachable and the configuration is valid. " +
75
+ "Returns the active settings (host, port, auth mode, sender identity, restrictions) " +
76
+ "and the result of a live connection test.",
77
+ }, async () => {
78
+ const start = Date.now();
79
+ let connectionStatus;
80
+ let isError = false;
81
+ try {
82
+ await (0, email_js_1.verifyTransport)(transport);
83
+ connectionStatus = `OK (${Date.now() - start} ms)`;
84
+ }
85
+ catch (err) {
86
+ connectionStatus = `FAILED — ${err instanceof Error ? err.message : String(err)}`;
87
+ isError = true;
88
+ }
89
+ const { allowedDomains, allowedAddresses } = config_js_1.config.restrictions;
90
+ const restrictionSummary = allowedDomains.length === 0 && allowedAddresses.length === 0
91
+ ? "none (all addresses permitted)"
92
+ : [
93
+ allowedDomains.length
94
+ ? `domains: ${allowedDomains.join(", ")}`
95
+ : null,
96
+ allowedAddresses.length
97
+ ? `addresses: ${allowedAddresses.join(", ")}`
98
+ : null,
99
+ ]
100
+ .filter(Boolean)
101
+ .join(" | ");
102
+ const lines = [
103
+ `connection: ${connectionStatus}`,
104
+ `smtp_host: ${config_js_1.config.smtp.host}:${config_js_1.config.smtp.port}`,
105
+ `tls: ${config_js_1.config.smtp.secure ? "implicit TLS" : config_js_1.config.smtp.ignoreTls ? "none (plain SMTP)" : "STARTTLS"}`,
106
+ `auth: ${config_js_1.config.smtp.user ? `authenticated as ${config_js_1.config.smtp.user}` : "unauthenticated"}`,
107
+ `from: "${config_js_1.config.from.name}" <${config_js_1.config.from.address}>`,
108
+ `restrictions: ${restrictionSummary}`,
109
+ ];
202
110
  return {
203
- content: [
204
- {
205
- type: "text",
206
- text: `Email sent successfully. Message ID: ${result.messageId}`,
207
- },
208
- ],
111
+ isError,
112
+ content: [{ type: "text", text: lines.join("\n") }],
209
113
  };
210
- }
211
- catch (err) {
212
- const message = err instanceof Error ? err.message : String(err);
213
- return {
214
- isError: true,
215
- content: [{ type: "text", text: `Failed to send email: ${message}` }],
216
- };
217
- }
218
- });
219
- // ---------------------------------------------------------------------------
220
- // Resource: usage guide for agents
221
- // ---------------------------------------------------------------------------
222
- function buildUsageText() {
223
- const { allowedDomains, allowedAddresses } = config_js_1.config.restrictions;
224
- const hasRestrictions = allowedDomains.length > 0 || allowedAddresses.length > 0;
225
- const restrictionSection = hasRestrictions
226
- ? [
227
- "RECIPIENT RESTRICTIONS",
228
- "An address is permitted when it satisfies at least one rule:",
229
- allowedDomains.length
230
- ? ` Allowed domains: ${allowedDomains.join(", ")}`
231
- : null,
232
- allowedAddresses.length
233
- ? ` Allowed addresses: ${allowedAddresses.join(", ")}`
234
- : null,
235
- "Blocked addresses are rejected before any connection is made to the SMTP server.",
236
- ]
237
- .filter((l) => l !== null)
238
- .join("\n")
239
- : "RECIPIENT RESTRICTIONS\nNone configured — all addresses are permitted.";
240
- return `
114
+ });
115
+ // ---------------------------------------------------------------------------
116
+ // Tool: encode_file
117
+ // ---------------------------------------------------------------------------
118
+ server.registerTool("encode_file", {
119
+ description: "Read a file from disk and return it base64-encoded. " +
120
+ "NOTE: prefer supplying 'path' directly in the send_email attachments array — " +
121
+ "the server will encode the file itself without passing binary data through the agent. " +
122
+ "Use encode_file only when you need to inspect or transform the content before sending.",
123
+ inputSchema: {
124
+ path: zod_1.z.string().min(1).describe("Absolute or relative path to the file"),
125
+ content_type: zod_1.z
126
+ .string()
127
+ .optional()
128
+ .describe("MIME type override. If omitted the type is detected from the file extension."),
129
+ },
130
+ }, async (args) => {
131
+ const fs = await Promise.resolve().then(() => __importStar(require("fs")));
132
+ const nodePath = await Promise.resolve().then(() => __importStar(require("path")));
133
+ if (!fs.existsSync(args.path)) {
134
+ return {
135
+ isError: true,
136
+ content: [{ type: "text", text: `File not found: ${args.path}` }],
137
+ };
138
+ }
139
+ try {
140
+ const data = fs.readFileSync(args.path);
141
+ const content = data.toString("base64");
142
+ const filename = nodePath.basename(args.path);
143
+ const content_type = args.content_type ?? (0, mime_js_1.mimeFromExtension)(args.path);
144
+ return {
145
+ content: [
146
+ {
147
+ type: "text",
148
+ text: JSON.stringify({ filename, content_type, content }),
149
+ },
150
+ ],
151
+ };
152
+ }
153
+ catch (err) {
154
+ const message = err instanceof Error ? err.message : String(err);
155
+ return {
156
+ isError: true,
157
+ content: [{ type: "text", text: `Failed to read file: ${message}` }],
158
+ };
159
+ }
160
+ });
161
+ // ---------------------------------------------------------------------------
162
+ // Tool: send_email
163
+ // ---------------------------------------------------------------------------
164
+ server.registerTool("send_email", {
165
+ description: "Send an email via SMTP. Recipient addresses are validated against the server's allowed domains/addresses policy.",
166
+ inputSchema: {
167
+ to: recipientSchema.describe("Recipient address or list of addresses"),
168
+ subject: zod_1.z.string().min(1).describe("Email subject line"),
169
+ body: zod_1.z.string().min(1).describe("Email body content"),
170
+ body_type: zod_1.z
171
+ .enum(["text", "html"])
172
+ .default("text")
173
+ .describe("Body format — plain text (default) or HTML"),
174
+ cc: recipientSchema
175
+ .optional()
176
+ .describe("CC address or list of addresses"),
177
+ bcc: recipientSchema
178
+ .optional()
179
+ .describe("BCC address or list of addresses"),
180
+ attachments: zod_1.z
181
+ .array(attachmentSchema)
182
+ .optional()
183
+ .describe("Files to attach"),
184
+ },
185
+ }, async (args) => {
186
+ const allRecipients = [
187
+ ...args.to,
188
+ ...(args.cc ?? []),
189
+ ...(args.bcc ?? []),
190
+ ];
191
+ const check = (0, restrictions_js_1.checkRecipients)(allRecipients, config_js_1.config.restrictions);
192
+ if (!check.allowed) {
193
+ return {
194
+ isError: true,
195
+ content: [
196
+ {
197
+ type: "text",
198
+ text: `Recipient(s) not permitted by server policy: ${check.blocked.join(", ")}`,
199
+ },
200
+ ],
201
+ };
202
+ }
203
+ try {
204
+ const result = await (0, email_js_1.sendEmail)(transport, config_js_1.config.from, {
205
+ to: args.to,
206
+ subject: args.subject,
207
+ body: args.body,
208
+ body_type: args.body_type,
209
+ cc: args.cc,
210
+ bcc: args.bcc,
211
+ attachments: args.attachments,
212
+ });
213
+ return {
214
+ content: [
215
+ {
216
+ type: "text",
217
+ text: `Email sent successfully. Message ID: ${result.messageId}`,
218
+ },
219
+ ],
220
+ };
221
+ }
222
+ catch (err) {
223
+ const message = err instanceof Error ? err.message : String(err);
224
+ return {
225
+ isError: true,
226
+ content: [{ type: "text", text: `Failed to send email: ${message}` }],
227
+ };
228
+ }
229
+ });
230
+ // ---------------------------------------------------------------------------
231
+ // Resource: usage guide for agents
232
+ // ---------------------------------------------------------------------------
233
+ function buildUsageText() {
234
+ const { allowedDomains, allowedAddresses } = config_js_1.config.restrictions;
235
+ const hasRestrictions = allowedDomains.length > 0 || allowedAddresses.length > 0;
236
+ const restrictionSection = hasRestrictions
237
+ ? [
238
+ "RECIPIENT RESTRICTIONS",
239
+ "An address is permitted when it satisfies at least one rule:",
240
+ allowedDomains.length
241
+ ? ` Allowed domains: ${allowedDomains.join(", ")}`
242
+ : null,
243
+ allowedAddresses.length
244
+ ? ` Allowed addresses: ${allowedAddresses.join(", ")}`
245
+ : null,
246
+ "Blocked addresses are rejected before any connection is made to the SMTP server.",
247
+ ]
248
+ .filter((l) => l !== null)
249
+ .join("\n")
250
+ : "RECIPIENT RESTRICTIONS\nNone configured — all addresses are permitted.";
251
+ return `
241
252
  SMTP MCP SERVER — USAGE GUIDE
242
253
  ==============================
243
254
 
@@ -271,10 +282,10 @@ encode_file
271
282
  Optional
272
283
  content_type string MIME type override. Auto-detected from extension if omitted.
273
284
 
274
- Reads the file, base64-encodes it, and returns a JSON object with three fields:
275
- { filename, content_type, content }
276
- These can be spread directly into a send_email attachment entry.
277
- Use this tool instead of reading and encoding files manually.
285
+ Reads the file and returns { filename, content_type, content } as JSON.
286
+ NOTE: for files on disk, prefer passing path directly in send_email attachments
287
+ instead — the server encodes the file itself without routing binary data through
288
+ the agent. Use encode_file only when you need to inspect the content first.
278
289
 
279
290
  send_email
280
291
  Required
@@ -288,24 +299,32 @@ send_email
288
299
  bcc string | string[] Blind carbon copy recipients.
289
300
  attachments Attachment[] Files to attach (see schema below).
290
301
 
291
- Attachment schema
292
- filename string Name shown to the recipient (e.g. "report.pdf").
293
- content string File data encoded as base64. Use encode_file to produce this.
294
- content_type string MIME type (e.g. "application/pdf", "image/png").
302
+ Attachment schema — provide EITHER path OR content for each attachment:
303
+
304
+ Path-based (preferred for files on disk):
305
+ path string Absolute path to the file. Server reads and encodes it.
306
+ filename string Optional. Defaults to the filename from the path.
307
+ content_type string Optional. Auto-detected from the file extension.
295
308
 
296
- ATTACHMENTS — HOW TO PREPARE FILES
297
- ------------------------------------
298
- Use the encode_file tool — it handles reading, encoding, and MIME detection:
309
+ Content-based (for programmatically generated data):
310
+ content string Raw base64-encoded data. No data: URI prefix.
311
+ filename string Required when using content.
312
+ content_type string Required when using content.
299
313
 
300
- 1. Call encode_file({ path: "/absolute/path/to/file.zip" })
301
- 2. Parse the returned JSON: { filename, content_type, content }
302
- 3. Pass those three fields as an entry in the send_email attachments array
314
+ ATTACHMENTS — RECOMMENDED APPROACH
315
+ -------------------------------------
316
+ Pass the file path directly in the attachments array and let the server handle
317
+ encoding. Binary data never passes through the agent's context:
303
318
 
304
- Do NOT use a generic file-reading tool to load binary files — text-mode
305
- readers corrupt binary content. encode_file always reads in binary mode.
319
+ send_email({
320
+ ...,
321
+ attachments: [{ path: "/absolute/path/to/file.zip" }]
322
+ })
306
323
 
307
- If you already have base64 content from another source, ensure it is a raw
308
- base64 string with no data URL prefix (strip any "data:<type>;base64," first).
324
+ Only use content-based attachments when the data is generated at runtime
325
+ (e.g. a report built in memory) rather than read from an existing file.
326
+ If you do supply raw base64 content, ensure it has no "data:<type>;base64,"
327
+ prefix — provide the raw base64 string only.
309
328
 
310
329
  TIPS
311
330
  ----
@@ -318,27 +337,35 @@ TIPS
318
337
  - If you are unsure of a file's MIME type, use application/octet-stream — it
319
338
  will arrive correctly, and the recipient's mail client will identify it.
320
339
  `.trim();
340
+ }
341
+ server.registerResource("usage", "smtp://server/usage", {
342
+ title: "SMTP MCP Server — Usage Guide",
343
+ description: "Reference guide describing this server's tools, parameters, active sender identity, and recipient restrictions.",
344
+ mimeType: "text/plain",
345
+ }, async () => ({
346
+ contents: [
347
+ {
348
+ uri: "smtp://server/usage",
349
+ text: buildUsageText(),
350
+ mimeType: "text/plain",
351
+ },
352
+ ],
353
+ }));
354
+ return server;
321
355
  }
322
- server.registerResource("usage", "smtp://server/usage", {
323
- title: "SMTP MCP Server — Usage Guide",
324
- description: "Reference guide describing this server's tools, parameters, active sender identity, and recipient restrictions.",
325
- mimeType: "text/plain",
326
- }, async () => ({
327
- contents: [
328
- {
329
- uri: "smtp://server/usage",
330
- text: buildUsageText(),
331
- mimeType: "text/plain",
332
- },
333
- ],
334
- }));
335
356
  // ---------------------------------------------------------------------------
336
357
  // Start
337
358
  // ---------------------------------------------------------------------------
338
359
  async function main() {
339
- const stdio = new stdio_js_1.StdioServerTransport();
340
- await server.connect(stdio);
341
- console.error("SMTP MCP server running on stdio");
360
+ if ((process.env.SMTP_TRANSPORT ?? "stdio") === "http") {
361
+ const host = process.env.SMTP_HTTP_HOST ?? "127.0.0.1";
362
+ const port = Number.parseInt(process.env.SMTP_HTTP_PORT ?? "3000", 10);
363
+ (0, http_server_js_1.createHttpServer)(createConfiguredServer, { host, port, serverName: "@teamnetwork-nz/smtp-mcp-server", bearerToken: process.env.SMTP_HTTP_BEARER_TOKEN, allowedHosts: process.env.SMTP_HTTP_ALLOWED_HOSTS?.split(",").map(v => v.trim()).filter(Boolean), allowedOrigins: process.env.SMTP_HTTP_ALLOWED_ORIGINS?.split(",").map(v => v.trim()).filter(Boolean) }).listen(port, host, () => console.error(`SMTP MCP server listening on ${host}:${port}/mcp`));
364
+ }
365
+ else {
366
+ await createConfiguredServer().connect(new stdio_js_1.StdioServerTransport());
367
+ console.error("SMTP MCP server running on stdio");
368
+ }
342
369
  }
343
370
  main().catch((err) => {
344
371
  console.error("Fatal error:", err);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/smtp-mcp-server",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "MCP server for sending email via SMTP relay",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -13,6 +13,7 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "build": "tsc",
16
+ "test": "npm run build && node --test tests/*.test.mjs",
16
17
  "start": "node dist/index.js",
17
18
  "dev": "tsc --watch",
18
19
  "prepublishOnly": "npm run build"