@teamnetwork-nz/smtp-mcp-server 1.3.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +3 -2
- package/README.md +11 -4
- package/dist/config.js +22 -13
- package/dist/email.js +4 -1
- package/dist/env.js +10 -0
- package/dist/http-server.js +90 -0
- package/dist/index.js +236 -218
- package/dist/package-info.js +8 -0
- package/dist/restrictions.js +2 -2
- package/dist/strict-tools.js +32 -0
- package/package.json +3 -2
package/.env.example
CHANGED
|
@@ -13,5 +13,6 @@ SMTP_FROM_NAME=My Agent # optional, defaults to SMTP_FROM_ADDRESS
|
|
|
13
13
|
# Recipient restrictions (at least one recommended for production)
|
|
14
14
|
# An address passes if it matches ANY rule — domain OR explicit address.
|
|
15
15
|
# If both variables are empty, all addresses are permitted (open mode).
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
SMTP_READWRITE=false # set true to register send_email
|
|
17
|
+
SMTP_ALLOWED_DOMAINS=example.com,partner.org # comma-separated domains
|
|
18
|
+
SMTP_ALLOWED_ADDRESSES=external@other.com # comma-separated explicit addresses
|
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
|
|
@@ -47,10 +51,12 @@ All configuration is via environment variables (loaded from `.env` if present).
|
|
|
47
51
|
| `SMTP_PASS` | no | SMTP auth password — omit for unauthenticated relays |
|
|
48
52
|
| `SMTP_FROM_ADDRESS` | yes | Envelope From address |
|
|
49
53
|
| `SMTP_FROM_NAME` | no | Display name — defaults to `SMTP_FROM_ADDRESS` |
|
|
50
|
-
| `
|
|
51
|
-
| `
|
|
54
|
+
| `SMTP_READWRITE` | no | Set to `true` to register `send_email`; defaults to read-only |
|
|
55
|
+
| `SMTP_ALLOWED_DOMAINS` | for sending | Comma-separated domains, e.g. `acme.com,partner.org` |
|
|
56
|
+
| `SMTP_ALLOWED_ADDRESSES` | for sending | Comma-separated explicit addresses |
|
|
57
|
+
| `SMTP_HTTP_MAX_BODY_BYTES` | no | Positive request-body limit; default 1048576, maximum 16777216 |
|
|
52
58
|
|
|
53
|
-
**Restriction logic:**
|
|
59
|
+
**Restriction logic:** `send_email` is absent unless `SMTP_READWRITE=true`. When enabled, at least one recipient allowlist is required. A recipient is permitted if its domain matches `SMTP_ALLOWED_DOMAINS` **or** it appears in `SMTP_ALLOWED_ADDRESSES`. All addresses across `to`, `cc`, and `bcc` are checked — a single blocked address rejects the whole request. `ALLOWED_DOMAINS` and `ALLOWED_ADDRESSES` remain one-release deprecated aliases.
|
|
54
60
|
|
|
55
61
|
## Claude Code Integration
|
|
56
62
|
|
|
@@ -69,7 +75,8 @@ Add to your `.claude/mcp_config.json` (or `claude_desktop_config.json`):
|
|
|
69
75
|
"SMTP_PASS": "your-password",
|
|
70
76
|
"SMTP_FROM_ADDRESS": "agent@example.com",
|
|
71
77
|
"SMTP_FROM_NAME": "My Agent",
|
|
72
|
-
"
|
|
78
|
+
"SMTP_READWRITE": "true",
|
|
79
|
+
"SMTP_ALLOWED_DOMAINS": "example.com"
|
|
73
80
|
}
|
|
74
81
|
}
|
|
75
82
|
}
|
package/dist/config.js
CHANGED
|
@@ -8,17 +8,12 @@ const dotenv_1 = __importDefault(require("dotenv"));
|
|
|
8
8
|
const zod_1 = require("zod");
|
|
9
9
|
dotenv_1.default.config({ quiet: true });
|
|
10
10
|
const configSchema = zod_1.z.object({
|
|
11
|
+
readWrite: zod_1.z.boolean().default(false),
|
|
11
12
|
smtp: zod_1.z.object({
|
|
12
13
|
host: zod_1.z.string().min(1, "SMTP_HOST is required"),
|
|
13
14
|
port: zod_1.z.coerce.number().int().min(1).max(65535).default(587),
|
|
14
|
-
secure: zod_1.z
|
|
15
|
-
|
|
16
|
-
.transform((v) => v.toLowerCase() === "true")
|
|
17
|
-
.default(false),
|
|
18
|
-
ignoreTls: zod_1.z
|
|
19
|
-
.string()
|
|
20
|
-
.transform((v) => v.toLowerCase() === "true")
|
|
21
|
-
.default(false),
|
|
15
|
+
secure: zod_1.z.boolean().default(false),
|
|
16
|
+
ignoreTls: zod_1.z.boolean().default(false),
|
|
22
17
|
user: zod_1.z.string().min(1).optional(),
|
|
23
18
|
pass: zod_1.z.string().min(1).optional(),
|
|
24
19
|
}),
|
|
@@ -39,13 +34,23 @@ function parseList(value) {
|
|
|
39
34
|
.map((s) => s.trim())
|
|
40
35
|
.filter(Boolean);
|
|
41
36
|
}
|
|
37
|
+
function parseListEnv(canonicalName, legacyName) {
|
|
38
|
+
if (process.env[canonicalName] !== undefined)
|
|
39
|
+
return parseList(process.env[canonicalName]);
|
|
40
|
+
if (process.env[legacyName] !== undefined) {
|
|
41
|
+
process.stderr.write(`[deprecated] ${legacyName} is deprecated; use ${canonicalName}.\n`);
|
|
42
|
+
return parseList(process.env[legacyName]);
|
|
43
|
+
}
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
42
46
|
function loadConfig() {
|
|
43
47
|
const raw = {
|
|
48
|
+
readWrite: (process.env.SMTP_READWRITE ?? "").toLowerCase() === "true",
|
|
44
49
|
smtp: {
|
|
45
50
|
host: process.env.SMTP_HOST,
|
|
46
51
|
port: process.env.SMTP_PORT,
|
|
47
|
-
secure: process.env.SMTP_SECURE,
|
|
48
|
-
ignoreTls: process.env.SMTP_IGNORE_TLS,
|
|
52
|
+
secure: (process.env.SMTP_SECURE ?? "").toLowerCase() === "true",
|
|
53
|
+
ignoreTls: (process.env.SMTP_IGNORE_TLS ?? "").toLowerCase() === "true",
|
|
49
54
|
user: process.env.SMTP_USER,
|
|
50
55
|
pass: process.env.SMTP_PASS,
|
|
51
56
|
},
|
|
@@ -54,8 +59,8 @@ function loadConfig() {
|
|
|
54
59
|
name: process.env.SMTP_FROM_NAME,
|
|
55
60
|
},
|
|
56
61
|
restrictions: {
|
|
57
|
-
allowedDomains:
|
|
58
|
-
allowedAddresses:
|
|
62
|
+
allowedDomains: parseListEnv("SMTP_ALLOWED_DOMAINS", "ALLOWED_DOMAINS"),
|
|
63
|
+
allowedAddresses: parseListEnv("SMTP_ALLOWED_ADDRESSES", "ALLOWED_ADDRESSES"),
|
|
59
64
|
},
|
|
60
65
|
};
|
|
61
66
|
const result = configSchema.safeParse(raw);
|
|
@@ -63,13 +68,17 @@ function loadConfig() {
|
|
|
63
68
|
const messages = result.error.issues
|
|
64
69
|
.map((i) => ` ${i.path.join(".")}: ${i.message}`)
|
|
65
70
|
.join("\n");
|
|
66
|
-
|
|
71
|
+
process.stderr.write(`Configuration error:\n${messages}\n`);
|
|
67
72
|
process.exit(1);
|
|
68
73
|
}
|
|
69
74
|
const config = result.data;
|
|
70
75
|
if (!config.from.name) {
|
|
71
76
|
config.from.name = config.from.address;
|
|
72
77
|
}
|
|
78
|
+
if (config.readWrite && config.restrictions.allowedDomains.length === 0 && config.restrictions.allowedAddresses.length === 0) {
|
|
79
|
+
process.stderr.write("Configuration error:\n restrictions: SMTP_READWRITE=true requires SMTP_ALLOWED_DOMAINS or SMTP_ALLOWED_ADDRESSES\n");
|
|
80
|
+
process.exit(1);
|
|
81
|
+
}
|
|
73
82
|
return config;
|
|
74
83
|
}
|
|
75
84
|
exports.config = loadConfig();
|
package/dist/email.js
CHANGED
|
@@ -71,7 +71,10 @@ function resolveAttachment(a) {
|
|
|
71
71
|
contentType: validateContentType(content_type, filename),
|
|
72
72
|
};
|
|
73
73
|
}
|
|
74
|
-
async function sendEmail(transport, from, options) {
|
|
74
|
+
async function sendEmail(transport, from, options, readWrite) {
|
|
75
|
+
if (!readWrite) {
|
|
76
|
+
throw new Error("Write operations are disabled. Set SMTP_READWRITE=true and configure a recipient allowlist to enable sending.");
|
|
77
|
+
}
|
|
75
78
|
const message = {
|
|
76
79
|
from: `"${from.name}" <${from.address}>`,
|
|
77
80
|
to: options.to,
|
package/dist/env.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parsePositiveInt = parsePositiveInt;
|
|
4
|
+
function parsePositiveInt(name, raw, fallback, maximum) {
|
|
5
|
+
const value = raw === undefined || raw === '' ? fallback : Number(raw);
|
|
6
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > maximum) {
|
|
7
|
+
throw new Error(`${name} must be a positive integer no greater than ${maximum}`);
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
@@ -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,212 +41,219 @@ 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");
|
|
45
|
+
const env_js_1 = require("./env.js");
|
|
46
|
+
const package_info_js_1 = require("./package-info.js");
|
|
47
|
+
const strict_tools_js_1 = require("./strict-tools.js");
|
|
44
48
|
const transport = (0, email_js_1.createTransport)(config_js_1.config.smtp);
|
|
45
|
-
|
|
46
|
-
name:
|
|
47
|
-
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
//
|
|
51
|
-
//
|
|
52
|
-
|
|
53
|
-
.
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
//
|
|
70
|
-
//
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
"
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
content: [{ type: "text", text: lines.join("\n") }],
|
|
111
|
-
};
|
|
112
|
-
});
|
|
113
|
-
// ---------------------------------------------------------------------------
|
|
114
|
-
// Tool: encode_file
|
|
115
|
-
// ---------------------------------------------------------------------------
|
|
116
|
-
server.registerTool("encode_file", {
|
|
117
|
-
description: "Read a file from disk and return it base64-encoded. " +
|
|
118
|
-
"NOTE: prefer supplying 'path' directly in the send_email attachments array — " +
|
|
119
|
-
"the server will encode the file itself without passing binary data through the agent. " +
|
|
120
|
-
"Use encode_file only when you need to inspect or transform the content before sending.",
|
|
121
|
-
inputSchema: {
|
|
122
|
-
path: zod_1.z.string().min(1).describe("Absolute or relative path to the file"),
|
|
123
|
-
content_type: zod_1.z
|
|
124
|
-
.string()
|
|
125
|
-
.optional()
|
|
126
|
-
.describe("MIME type override. If omitted the type is detected from the file extension."),
|
|
127
|
-
},
|
|
128
|
-
}, async (args) => {
|
|
129
|
-
const fs = await Promise.resolve().then(() => __importStar(require("fs")));
|
|
130
|
-
const nodePath = await Promise.resolve().then(() => __importStar(require("path")));
|
|
131
|
-
if (!fs.existsSync(args.path)) {
|
|
132
|
-
return {
|
|
133
|
-
isError: true,
|
|
134
|
-
content: [{ type: "text", text: `File not found: ${args.path}` }],
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
try {
|
|
138
|
-
const data = fs.readFileSync(args.path);
|
|
139
|
-
const content = data.toString("base64");
|
|
140
|
-
const filename = nodePath.basename(args.path);
|
|
141
|
-
const content_type = args.content_type ?? (0, mime_js_1.mimeFromExtension)(args.path);
|
|
142
|
-
return {
|
|
143
|
-
content: [
|
|
144
|
-
{
|
|
145
|
-
type: "text",
|
|
146
|
-
text: JSON.stringify({ filename, content_type, content }),
|
|
147
|
-
},
|
|
148
|
-
],
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
catch (err) {
|
|
152
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
49
|
+
function createConfiguredServer() {
|
|
50
|
+
const server = new mcp_js_1.McpServer({ name: package_info_js_1.packageName, version: package_info_js_1.packageVersion }, {
|
|
51
|
+
instructions: "SMTP email MCP server. Sending is restricted to configured recipient allowlists. Treat message bodies and attachments as sensitive, verify recipients before sending, and use the usage resource to inspect the active sender identity and restrictions.",
|
|
52
|
+
});
|
|
53
|
+
(0, strict_tools_js_1.enforceStrictToolInputs)(server);
|
|
54
|
+
// ---------------------------------------------------------------------------
|
|
55
|
+
// Shared schemas
|
|
56
|
+
// ---------------------------------------------------------------------------
|
|
57
|
+
const attachmentSchema = zod_1.z
|
|
58
|
+
.object({
|
|
59
|
+
path: zod_1.z.string().optional().describe("Absolute path to the file on disk — server reads and encodes it"),
|
|
60
|
+
filename: zod_1.z.string().optional().describe("Override the filename shown to the recipient"),
|
|
61
|
+
content: zod_1.z.string().optional().describe("Base64-encoded file content (use path instead where possible)"),
|
|
62
|
+
content_type: zod_1.z.string().optional().describe("MIME type — auto-detected from path extension if omitted"),
|
|
63
|
+
})
|
|
64
|
+
.refine((a) => a.path || a.content, {
|
|
65
|
+
message: "Each attachment must include either 'path' (preferred) or 'content' (base64)",
|
|
66
|
+
})
|
|
67
|
+
.refine((a) => !a.content || (a.filename && a.content_type), {
|
|
68
|
+
message: "Attachments using 'content' must also include 'filename' and 'content_type'",
|
|
69
|
+
});
|
|
70
|
+
const recipientSchema = zod_1.z
|
|
71
|
+
.union([zod_1.z.string().email(), zod_1.z.array(zod_1.z.string().email()).min(1)])
|
|
72
|
+
.transform((v) => (Array.isArray(v) ? v : [v]));
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
// Tool: health
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
server.registerTool("health", {
|
|
77
|
+
description: "Check that the SMTP server is reachable and the configuration is valid. " +
|
|
78
|
+
"Returns the active settings (host, port, auth mode, sender identity, restrictions) " +
|
|
79
|
+
"and the result of a live connection test.",
|
|
80
|
+
}, async () => {
|
|
81
|
+
const start = Date.now();
|
|
82
|
+
let connectionStatus;
|
|
83
|
+
let isError = false;
|
|
84
|
+
try {
|
|
85
|
+
await (0, email_js_1.verifyTransport)(transport);
|
|
86
|
+
connectionStatus = `OK (${Date.now() - start} ms)`;
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
connectionStatus = `FAILED — ${err instanceof Error ? err.message : String(err)}`;
|
|
90
|
+
isError = true;
|
|
91
|
+
}
|
|
92
|
+
const { allowedDomains, allowedAddresses } = config_js_1.config.restrictions;
|
|
93
|
+
const restrictionSummary = allowedDomains.length === 0 && allowedAddresses.length === 0
|
|
94
|
+
? "none (sending disabled)"
|
|
95
|
+
: [
|
|
96
|
+
allowedDomains.length
|
|
97
|
+
? `domains: ${allowedDomains.join(", ")}`
|
|
98
|
+
: null,
|
|
99
|
+
allowedAddresses.length
|
|
100
|
+
? `addresses: ${allowedAddresses.join(", ")}`
|
|
101
|
+
: null,
|
|
102
|
+
]
|
|
103
|
+
.filter(Boolean)
|
|
104
|
+
.join(" | ");
|
|
105
|
+
const lines = [
|
|
106
|
+
`connection: ${connectionStatus}`,
|
|
107
|
+
`smtp_host: ${config_js_1.config.smtp.host}:${config_js_1.config.smtp.port}`,
|
|
108
|
+
`tls: ${config_js_1.config.smtp.secure ? "implicit TLS" : config_js_1.config.smtp.ignoreTls ? "none (plain SMTP)" : "STARTTLS"}`,
|
|
109
|
+
`auth: ${config_js_1.config.smtp.user ? `authenticated as ${config_js_1.config.smtp.user}` : "unauthenticated"}`,
|
|
110
|
+
`from: "${config_js_1.config.from.name}" <${config_js_1.config.from.address}>`,
|
|
111
|
+
`mode: ${config_js_1.config.readWrite ? "read-write" : "read-only"}`,
|
|
112
|
+
`restrictions: ${restrictionSummary}`,
|
|
113
|
+
];
|
|
153
114
|
return {
|
|
154
|
-
isError
|
|
155
|
-
content: [{ type: "text", text:
|
|
115
|
+
isError,
|
|
116
|
+
content: [{ type: "text", text: lines.join("\n") }],
|
|
156
117
|
};
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
//
|
|
160
|
-
//
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
118
|
+
});
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// Tool: encode_file
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
server.registerTool("encode_file", {
|
|
123
|
+
description: "Read a file from disk and return it base64-encoded. " +
|
|
124
|
+
"NOTE: prefer supplying 'path' directly in the send_email attachments array — " +
|
|
125
|
+
"the server will encode the file itself without passing binary data through the agent. " +
|
|
126
|
+
"Use encode_file only when you need to inspect or transform the content before sending.",
|
|
127
|
+
inputSchema: {
|
|
128
|
+
path: zod_1.z.string().min(1).describe("Absolute or relative path to the file"),
|
|
129
|
+
content_type: zod_1.z
|
|
130
|
+
.string()
|
|
131
|
+
.optional()
|
|
132
|
+
.describe("MIME type override. If omitted the type is detected from the file extension."),
|
|
133
|
+
},
|
|
134
|
+
}, async (args) => {
|
|
135
|
+
const fs = await Promise.resolve().then(() => __importStar(require("fs")));
|
|
136
|
+
const nodePath = await Promise.resolve().then(() => __importStar(require("path")));
|
|
137
|
+
if (!fs.existsSync(args.path)) {
|
|
138
|
+
return {
|
|
139
|
+
isError: true,
|
|
140
|
+
content: [{ type: "text", text: `File not found: ${args.path}` }],
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const data = fs.readFileSync(args.path);
|
|
145
|
+
const content = data.toString("base64");
|
|
146
|
+
const filename = nodePath.basename(args.path);
|
|
147
|
+
const content_type = args.content_type ?? (0, mime_js_1.mimeFromExtension)(args.path);
|
|
148
|
+
return {
|
|
149
|
+
content: [
|
|
150
|
+
{
|
|
151
|
+
type: "text",
|
|
152
|
+
text: JSON.stringify({ filename, content_type, content }),
|
|
153
|
+
},
|
|
154
|
+
],
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
catch (err) {
|
|
158
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
159
|
+
return {
|
|
160
|
+
isError: true,
|
|
161
|
+
content: [{ type: "text", text: `Failed to read file: ${message}` }],
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
// ---------------------------------------------------------------------------
|
|
166
|
+
// Tool: send_email
|
|
167
|
+
// ---------------------------------------------------------------------------
|
|
168
|
+
if (config_js_1.config.readWrite)
|
|
169
|
+
server.registerTool("send_email", {
|
|
170
|
+
description: "Send an email via SMTP. Recipient addresses are validated against the server's allowed domains/addresses policy.",
|
|
171
|
+
inputSchema: {
|
|
172
|
+
to: recipientSchema.describe("Recipient address or list of addresses"),
|
|
173
|
+
subject: zod_1.z.string().min(1).describe("Email subject line"),
|
|
174
|
+
body: zod_1.z.string().min(1).describe("Email body content"),
|
|
175
|
+
body_type: zod_1.z
|
|
176
|
+
.enum(["text", "html"])
|
|
177
|
+
.default("text")
|
|
178
|
+
.describe("Body format — plain text (default) or HTML"),
|
|
179
|
+
cc: recipientSchema
|
|
180
|
+
.optional()
|
|
181
|
+
.describe("CC address or list of addresses"),
|
|
182
|
+
bcc: recipientSchema
|
|
183
|
+
.optional()
|
|
184
|
+
.describe("BCC address or list of addresses"),
|
|
185
|
+
attachments: zod_1.z
|
|
186
|
+
.array(attachmentSchema)
|
|
187
|
+
.optional()
|
|
188
|
+
.describe("Files to attach"),
|
|
189
|
+
},
|
|
190
|
+
}, async (args) => {
|
|
191
|
+
const allRecipients = [
|
|
192
|
+
...args.to,
|
|
193
|
+
...(args.cc ?? []),
|
|
194
|
+
...(args.bcc ?? []),
|
|
195
|
+
];
|
|
196
|
+
const check = (0, restrictions_js_1.checkRecipients)(allRecipients, config_js_1.config.restrictions);
|
|
197
|
+
if (!check.allowed) {
|
|
198
|
+
return {
|
|
199
|
+
isError: true,
|
|
200
|
+
content: [
|
|
201
|
+
{
|
|
202
|
+
type: "text",
|
|
203
|
+
text: `Recipient(s) not permitted by server policy: ${check.blocked.join(", ")}`,
|
|
204
|
+
},
|
|
205
|
+
],
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
const result = await (0, email_js_1.sendEmail)(transport, config_js_1.config.from, {
|
|
210
|
+
to: args.to,
|
|
211
|
+
subject: args.subject,
|
|
212
|
+
body: args.body,
|
|
213
|
+
body_type: args.body_type,
|
|
214
|
+
cc: args.cc,
|
|
215
|
+
bcc: args.bcc,
|
|
216
|
+
attachments: args.attachments,
|
|
217
|
+
}, config_js_1.config.readWrite);
|
|
218
|
+
return {
|
|
219
|
+
content: [
|
|
220
|
+
{
|
|
221
|
+
type: "text",
|
|
222
|
+
text: `Email sent successfully. Message ID: ${result.messageId}`,
|
|
223
|
+
},
|
|
224
|
+
],
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
229
|
+
return {
|
|
230
|
+
isError: true,
|
|
231
|
+
content: [{ type: "text", text: `Failed to send email: ${message}` }],
|
|
232
|
+
};
|
|
233
|
+
}
|
|
210
234
|
});
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
const hasRestrictions = allowedDomains.length > 0 || allowedAddresses.length > 0;
|
|
234
|
-
const restrictionSection = hasRestrictions
|
|
235
|
-
? [
|
|
236
|
-
"RECIPIENT RESTRICTIONS",
|
|
237
|
-
"An address is permitted when it satisfies at least one rule:",
|
|
238
|
-
allowedDomains.length
|
|
239
|
-
? ` Allowed domains: ${allowedDomains.join(", ")}`
|
|
240
|
-
: null,
|
|
241
|
-
allowedAddresses.length
|
|
242
|
-
? ` Allowed addresses: ${allowedAddresses.join(", ")}`
|
|
243
|
-
: null,
|
|
244
|
-
"Blocked addresses are rejected before any connection is made to the SMTP server.",
|
|
245
|
-
]
|
|
246
|
-
.filter((l) => l !== null)
|
|
247
|
-
.join("\n")
|
|
248
|
-
: "RECIPIENT RESTRICTIONS\nNone configured — all addresses are permitted.";
|
|
249
|
-
return `
|
|
235
|
+
// ---------------------------------------------------------------------------
|
|
236
|
+
// Resource: usage guide for agents
|
|
237
|
+
// ---------------------------------------------------------------------------
|
|
238
|
+
function buildUsageText() {
|
|
239
|
+
const { allowedDomains, allowedAddresses } = config_js_1.config.restrictions;
|
|
240
|
+
const hasRestrictions = allowedDomains.length > 0 || allowedAddresses.length > 0;
|
|
241
|
+
const restrictionSection = hasRestrictions
|
|
242
|
+
? [
|
|
243
|
+
"RECIPIENT RESTRICTIONS",
|
|
244
|
+
"An address is permitted when it satisfies at least one rule:",
|
|
245
|
+
allowedDomains.length
|
|
246
|
+
? ` Allowed domains: ${allowedDomains.join(", ")}`
|
|
247
|
+
: null,
|
|
248
|
+
allowedAddresses.length
|
|
249
|
+
? ` Allowed addresses: ${allowedAddresses.join(", ")}`
|
|
250
|
+
: null,
|
|
251
|
+
"Blocked addresses are rejected before any connection is made to the SMTP server.",
|
|
252
|
+
]
|
|
253
|
+
.filter((l) => l !== null)
|
|
254
|
+
.join("\n")
|
|
255
|
+
: "RECIPIENT RESTRICTIONS\nNone configured — sending cannot be enabled.";
|
|
256
|
+
return `
|
|
250
257
|
SMTP MCP SERVER — USAGE GUIDE
|
|
251
258
|
==============================
|
|
252
259
|
|
|
@@ -254,6 +261,9 @@ This server sends email on behalf of agents via an SMTP relay.
|
|
|
254
261
|
All configuration (credentials, sender identity, restrictions) is fixed at
|
|
255
262
|
startup and cannot be changed by tool calls.
|
|
256
263
|
|
|
264
|
+
MODE
|
|
265
|
+
${config_js_1.config.readWrite ? "read-write — send_email is available" : "read-only — send_email is not registered"}
|
|
266
|
+
|
|
257
267
|
SENDER IDENTITY
|
|
258
268
|
From name: ${config_js_1.config.from.name}
|
|
259
269
|
From address: ${config_js_1.config.from.address}
|
|
@@ -335,27 +345,35 @@ TIPS
|
|
|
335
345
|
- If you are unsure of a file's MIME type, use application/octet-stream — it
|
|
336
346
|
will arrive correctly, and the recipient's mail client will identify it.
|
|
337
347
|
`.trim();
|
|
348
|
+
}
|
|
349
|
+
server.registerResource("usage", "smtp://server/usage", {
|
|
350
|
+
title: "SMTP MCP Server — Usage Guide",
|
|
351
|
+
description: "Reference guide describing this server's tools, parameters, active sender identity, and recipient restrictions.",
|
|
352
|
+
mimeType: "text/plain",
|
|
353
|
+
}, async () => ({
|
|
354
|
+
contents: [
|
|
355
|
+
{
|
|
356
|
+
uri: "smtp://server/usage",
|
|
357
|
+
text: buildUsageText(),
|
|
358
|
+
mimeType: "text/plain",
|
|
359
|
+
},
|
|
360
|
+
],
|
|
361
|
+
}));
|
|
362
|
+
return server;
|
|
338
363
|
}
|
|
339
|
-
server.registerResource("usage", "smtp://server/usage", {
|
|
340
|
-
title: "SMTP MCP Server — Usage Guide",
|
|
341
|
-
description: "Reference guide describing this server's tools, parameters, active sender identity, and recipient restrictions.",
|
|
342
|
-
mimeType: "text/plain",
|
|
343
|
-
}, async () => ({
|
|
344
|
-
contents: [
|
|
345
|
-
{
|
|
346
|
-
uri: "smtp://server/usage",
|
|
347
|
-
text: buildUsageText(),
|
|
348
|
-
mimeType: "text/plain",
|
|
349
|
-
},
|
|
350
|
-
],
|
|
351
|
-
}));
|
|
352
364
|
// ---------------------------------------------------------------------------
|
|
353
365
|
// Start
|
|
354
366
|
// ---------------------------------------------------------------------------
|
|
355
367
|
async function main() {
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
368
|
+
if ((process.env.SMTP_TRANSPORT ?? "stdio") === "http") {
|
|
369
|
+
const host = process.env.SMTP_HTTP_HOST ?? "127.0.0.1";
|
|
370
|
+
const port = (0, env_js_1.parsePositiveInt)("SMTP_HTTP_PORT", process.env.SMTP_HTTP_PORT, 3000, 65535);
|
|
371
|
+
(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), maxBodyBytes: (0, env_js_1.parsePositiveInt)("SMTP_HTTP_MAX_BODY_BYTES", process.env.SMTP_HTTP_MAX_BODY_BYTES, 1_048_576, 16_777_216) }).listen(port, host, () => console.error(`SMTP MCP server listening on ${host}:${port}/mcp`));
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
await createConfiguredServer().connect(new stdio_js_1.StdioServerTransport());
|
|
375
|
+
console.error("SMTP MCP server running on stdio");
|
|
376
|
+
}
|
|
359
377
|
}
|
|
360
378
|
main().catch((err) => {
|
|
361
379
|
console.error("Fatal error:", err);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.packageVersion = exports.packageName = void 0;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const packageJson = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(__dirname, '..', 'package.json'), 'utf8'));
|
|
7
|
+
exports.packageName = packageJson.name ?? 'smtp-mcp-server';
|
|
8
|
+
exports.packageVersion = packageJson.version ?? '0.0.0';
|
package/dist/restrictions.js
CHANGED
|
@@ -6,9 +6,9 @@ function domainOf(address) {
|
|
|
6
6
|
}
|
|
7
7
|
function checkRecipients(addresses, restrictions) {
|
|
8
8
|
const { allowedDomains, allowedAddresses } = restrictions;
|
|
9
|
-
//
|
|
9
|
+
// A write-enabled server must always have an explicit recipient allowlist.
|
|
10
10
|
if (allowedDomains.length === 0 && allowedAddresses.length === 0) {
|
|
11
|
-
return { allowed:
|
|
11
|
+
return { allowed: false, blocked: addresses };
|
|
12
12
|
}
|
|
13
13
|
const normalizedAllowedAddresses = allowedAddresses.map((a) => a.toLowerCase());
|
|
14
14
|
const normalizedAllowedDomains = allowedDomains.map((d) => d.toLowerCase());
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.enforceStrictToolInputs = enforceStrictToolInputs;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
function isSchema(value) {
|
|
6
|
+
return typeof value === "object" && value !== null && "_def" in value;
|
|
7
|
+
}
|
|
8
|
+
function isRawShape(value) {
|
|
9
|
+
if (typeof value !== "object" || value === null || isSchema(value))
|
|
10
|
+
return false;
|
|
11
|
+
const values = Object.values(value);
|
|
12
|
+
return values.length === 0 || values.some(isSchema);
|
|
13
|
+
}
|
|
14
|
+
function strictSchema(schema) {
|
|
15
|
+
if (schema === undefined)
|
|
16
|
+
return zod_1.z.object({}).strict();
|
|
17
|
+
if (isRawShape(schema))
|
|
18
|
+
return zod_1.z.object(schema).strict();
|
|
19
|
+
if (isSchema(schema) && typeof schema.strict === "function")
|
|
20
|
+
return schema.strict();
|
|
21
|
+
return schema;
|
|
22
|
+
}
|
|
23
|
+
/** Make every tool object reject undeclared arguments, including no-argument tools. */
|
|
24
|
+
function enforceStrictToolInputs(server) {
|
|
25
|
+
const mutable = server;
|
|
26
|
+
const createRegisteredTool = mutable._createRegisteredTool.bind(server);
|
|
27
|
+
mutable._createRegisteredTool = (...args) => {
|
|
28
|
+
// SDK 1.29 funnels both tool() and registerTool() through this method.
|
|
29
|
+
args[3] = strictSchema(args[3]);
|
|
30
|
+
return createRegisteredTool(...args);
|
|
31
|
+
};
|
|
32
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teamnetwork-nz/smtp-mcp-server",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.1",
|
|
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"
|
|
@@ -37,7 +38,7 @@
|
|
|
37
38
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
38
39
|
"dotenv": "^17.4.2",
|
|
39
40
|
"nodemailer": "^8.0.7",
|
|
40
|
-
"zod": "^
|
|
41
|
+
"zod": "^3.25.0"
|
|
41
42
|
},
|
|
42
43
|
"devDependencies": {
|
|
43
44
|
"@types/node": "^25.7.0",
|