@vernal-systems/mcp 0.0.0-stage → 1.0.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,3 +1,7 @@
1
- # Temporary Holding Version
1
+ # Vernal Mail MCP server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Requires Node.js 20 or newer. Set `VERNAL_API_KEY` in your MCP client's environment. Set `VERNAL_GATEWAY_URL` to your gateway origin when using a separate environment. It defaults to `https://api.vernalmail.dev`.
4
+
5
+ The server uses standard input and output. Use `npx -y --package @vernal-systems/mcp vernal-mcp` after registry publication, or `npx -y --package /absolute/path/to/vernal-systems-mcp-1.0.0.tgz vernal-mcp` with an approved release archive.
6
+
7
+ Start with `vernal_send_email` and `dryRun: true`. For live sends, supply one `idempotencyKey` per intentional submission. The send tool waits up to 15 seconds for a complete gateway response. If the outcome is unknown, reuse the same key and payload within the 24-hour retry window. If you sent without a key or the retry window has passed, check Message Logs before submitting again. Use `vernal_get_message` to check an accepted job by ID. Gateway responses include `httpStatus` and, when present, `retryAfter`.
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Content-level preflight checks.
3
+ *
4
+ * These are heuristics, not a spam score: authentication (SPF/DKIM/DMARC),
5
+ * reputation and recipient engagement matter more. The point is to catch
6
+ * self-inflicted problems (missing plain text, URL shorteners, image-only HTML,
7
+ * missing unsubscribe headers) before a message leaves the building.
8
+ */
9
+ import { emailDomain } from "../util.js";
10
+ const SHORTENERS = new Set([
11
+ "bit.ly",
12
+ "bit.do",
13
+ "buff.ly",
14
+ "cutt.ly",
15
+ "goo.gl",
16
+ "is.gd",
17
+ "ow.ly",
18
+ "rebrand.ly",
19
+ "shorturl.at",
20
+ "t.co",
21
+ "tiny.cc",
22
+ "tinyurl.com",
23
+ "tr.im",
24
+ ]);
25
+ const COMMON_ACRONYMS = new Set([
26
+ "API",
27
+ "CNAME",
28
+ "CTO",
29
+ "CEO",
30
+ "DKIM",
31
+ "DMARC",
32
+ "DNS",
33
+ "EU",
34
+ "FAQ",
35
+ "HTML",
36
+ "HTTP",
37
+ "HTTPS",
38
+ "MFA",
39
+ "MX",
40
+ "OTP",
41
+ "PDF",
42
+ "SMTP",
43
+ "SPF",
44
+ "TLS",
45
+ "TXT",
46
+ "UK",
47
+ "URI",
48
+ "URL",
49
+ "USA",
50
+ "VPN",
51
+ ]);
52
+ const SPAM_PHRASES = [
53
+ "act now",
54
+ "buy now",
55
+ "cash bonus",
56
+ "click here",
57
+ "congratulations you",
58
+ "credit repair",
59
+ "double your",
60
+ "earn extra cash",
61
+ "free money",
62
+ "guaranteed",
63
+ "limited time",
64
+ "lowest price",
65
+ "make money fast",
66
+ "no risk",
67
+ "risk free",
68
+ "satisfaction guaranteed",
69
+ "urgent",
70
+ "winner",
71
+ "work from home",
72
+ ];
73
+ function stripHtml(html) {
74
+ return html
75
+ .replace(/<(script|style)[\s\S]*?<\/\1>/gi, " ")
76
+ .replace(/<br\s*\/?>/gi, "\n")
77
+ .replace(/<\/p>/gi, "\n")
78
+ .replace(/<[^>]+>/g, " ")
79
+ .replace(/&nbsp;/gi, " ")
80
+ .replace(/&amp;/gi, "&")
81
+ .replace(/&lt;/gi, "<")
82
+ .replace(/&gt;/gi, ">")
83
+ .replace(/&quot;/gi, '"')
84
+ .replace(/&#39;/gi, "'")
85
+ .replace(/[ \t]+/g, " ")
86
+ .replace(/\n\s*\n+/g, "\n\n")
87
+ .trim();
88
+ }
89
+ function extractUrls(value) {
90
+ const matches = value.match(/https?:\/\/[^\s"'<>)\]]+/gi) ?? [];
91
+ return matches.map((url) => url.replace(/[.,;:!?]+$/, ""));
92
+ }
93
+ function headerValue(headers, name) {
94
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase());
95
+ return entry?.[1];
96
+ }
97
+ function scoreFindings(findings) {
98
+ const penalty = findings.reduce((total, finding) => {
99
+ if (finding.severity === "error")
100
+ return total + 20;
101
+ if (finding.severity === "warning")
102
+ return total + 5;
103
+ return total + 1;
104
+ }, 0);
105
+ const score = Math.max(0, Math.min(100, 100 - penalty));
106
+ const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 65 ? "C" : score >= 50 ? "D" : "F";
107
+ return { score, grade };
108
+ }
109
+ export function lintMessage(input) {
110
+ const findings = [];
111
+ const add = (severity, code, message, hint) => {
112
+ findings.push({ severity, code, message, ...(hint ? { hint } : {}) });
113
+ };
114
+ const subject = input.subject ?? "";
115
+ const text = input.text ?? "";
116
+ const html = input.html ?? "";
117
+ const headers = input.headers ?? {};
118
+ const bulk = Boolean(input.bulk);
119
+ if (!input.to.length) {
120
+ add("error", "no-recipients", "No recipients were provided.");
121
+ }
122
+ if (!subject.trim()) {
123
+ add("error", "empty-subject", "The subject is empty.");
124
+ }
125
+ if (/[\r\n]/.test(subject)) {
126
+ add("error", "subject-newline", "The subject contains a line break.");
127
+ }
128
+ if (subject.trim().length > 78) {
129
+ add("warning", "long-subject", `The subject is ${subject.trim().length} characters; many clients truncate around 70–78.`);
130
+ }
131
+ if (/\{\{|\}\}|\[\[[^\]]+\]\]|%recipient\./i.test(subject + text + html)) {
132
+ add("error", "unresolved-placeholder", "The message still contains an unresolved template placeholder.", "Render all merge tags before sending.");
133
+ }
134
+ const letters = subject.replace(/[^A-Za-z]/g, "");
135
+ if (letters.length >= 10 && letters.replace(/[^A-Z]/g, "").length / letters.length > 0.7) {
136
+ add("warning", "shouting-subject", "Most of the subject is in capitals.");
137
+ }
138
+ if ((subject.match(/!/g) ?? []).length >= 3) {
139
+ add("warning", "exclamation-marks", "The subject contains three or more exclamation marks.");
140
+ }
141
+ if (/^(re|fw|fwd):/i.test(subject.trim())) {
142
+ add("info", "fake-reply-subject", "The subject starts with Re:/Fwd:; filters can treat unsolicited reply subjects as deceptive.");
143
+ }
144
+ if (!text.trim()) {
145
+ add("error", "missing-text", "There is no plain-text part.", "Always include a text/plain alternative; HTML-only mail is a common spam signal.");
146
+ }
147
+ else if (text.trim().length < 25) {
148
+ add("info", "short-text", "The plain-text part is very short.");
149
+ }
150
+ if (!html.trim()) {
151
+ add("info", "no-html", "No HTML part. Plain-text mail is deliverable, just less visual.");
152
+ }
153
+ const visibleHtml = stripHtml(html);
154
+ const imageCount = (html.match(/<img\b/gi) ?? []).length;
155
+ if (imageCount > 0 && visibleHtml.length < 50) {
156
+ add("warning", "image-only", "The HTML body is effectively image-only.", "Add real text; image-heavy mail is filtered aggressively.");
157
+ }
158
+ if (imageCount > 0) {
159
+ const withoutAlt = (html.match(/<img\b[^>]*>/gi) ?? []).filter((tag) => !/\balt\s*=/i.test(tag)).length;
160
+ if (withoutAlt > 0) {
161
+ add("info", "img-no-alt", `${withoutAlt} image(s) have no alt text.`);
162
+ }
163
+ if (/<img\b[^>]*(?:width|height)\s*=\s*["']?1["']?/i.test(html)) {
164
+ add("info", "tracking-pixel", "A 1×1 tracking pixel was detected.");
165
+ }
166
+ }
167
+ if (/display\s*:\s*none|visibility\s*:\s*hidden/i.test(html)) {
168
+ add("warning", "hidden-content", "Hidden text (display:none/visibility:hidden) was found in the HTML.", "Hidden copy is a classic spam-filter trigger.");
169
+ }
170
+ if (/<script\b/i.test(html)) {
171
+ add("warning", "script-tag", "HTML contains a <script> tag; mail clients strip it.");
172
+ }
173
+ const urls = [...extractUrls(text), ...extractUrls(html)];
174
+ const hostnames = urls
175
+ .map((url) => {
176
+ try {
177
+ return new URL(url).hostname.toLowerCase();
178
+ }
179
+ catch {
180
+ return undefined;
181
+ }
182
+ })
183
+ .filter((host) => Boolean(host));
184
+ const uniqueHosts = [...new Set(hostnames)];
185
+ if (urls.length > 20) {
186
+ add("warning", "many-links", `The message contains ${urls.length} links.`);
187
+ }
188
+ for (const host of uniqueHosts) {
189
+ if (SHORTENERS.has(host)) {
190
+ add("warning", "url-shortener", `Link shortener detected: ${host}`, "Use your real domain; shorteners hide the destination and hurt trust.");
191
+ }
192
+ }
193
+ if (urls.some((url) => /^http:\/\//i.test(url))) {
194
+ add("warning", "insecure-links", "At least one link uses plain http:// instead of https://.");
195
+ }
196
+ if (urls.some((url) => /^https?:\/\/\d{1,3}(?:\.\d{1,3}){3}/i.test(url))) {
197
+ add("warning", "ip-link", "At least one link points at a bare IP address.");
198
+ }
199
+ let unsubscribeHost;
200
+ if (input.config.unsubscribeUrl) {
201
+ try {
202
+ unsubscribeHost = new URL(input.config.unsubscribeUrl).hostname.toLowerCase();
203
+ }
204
+ catch {
205
+ // Config validation normally catches this; ignore a hand-built invalid value.
206
+ }
207
+ }
208
+ const allowedHosts = new Set([
209
+ emailDomain(input.from),
210
+ input.config.domain,
211
+ ...(unsubscribeHost ? [unsubscribeHost] : []),
212
+ ]);
213
+ const foreignHosts = uniqueHosts.filter((host) => {
214
+ return ![...allowedHosts].some((allowed) => host === allowed || host.endsWith(`.${allowed}`));
215
+ });
216
+ if (foreignHosts.length > 3) {
217
+ add("info", "many-external-domains", `Links point to ${foreignHosts.length} unrelated domains.`, "Keep links on your own domain where possible.");
218
+ }
219
+ const lowercaseText = `${subject}\n${text}\n${visibleHtml}`.toLowerCase();
220
+ const phrases = SPAM_PHRASES.filter((phrase) => lowercaseText.includes(phrase));
221
+ if (phrases.length > 0) {
222
+ add("warning", "spam-phrases", `Common spam-filter phrases found: ${phrases.slice(0, 5).join(", ")}${phrases.length > 5 ? "…" : ""}`, "These are heuristics; natural transactional copy is usually fine.");
223
+ }
224
+ const capsWords = [
225
+ ...new Set(`${text} ${visibleHtml}`
226
+ .split(/\s+/)
227
+ .map((word) => word.replace(/[^A-Za-z]/g, ""))
228
+ .filter((word) => word.length >= 4 && /^[A-Z]+$/.test(word))),
229
+ ].filter((word) => !COMMON_ACRONYMS.has(word));
230
+ if (capsWords.length >= 6) {
231
+ add("warning", "shouting-body", `${capsWords.length} words are in ALL CAPS.`);
232
+ }
233
+ if (input.sizeBytes && input.sizeBytes > 102_400) {
234
+ add("warning", "gmail-clipping", `The message is ${Math.round(input.sizeBytes / 1024)} KB; Gmail clips messages over ~102 KB.`);
235
+ }
236
+ if (html.length > 102_400) {
237
+ add("warning", "large-html", "The HTML part alone is over 100 KB.");
238
+ }
239
+ if (bulk) {
240
+ const unsubscribe = headerValue(headers, "List-Unsubscribe");
241
+ const oneClick = headerValue(headers, "List-Unsubscribe-Post");
242
+ if (!unsubscribe) {
243
+ add("error", "missing-list-unsubscribe", "Bulk mail is missing the List-Unsubscribe header.", "Gmail and Yahoo require one-click unsubscribe for bulk senders.");
244
+ }
245
+ else {
246
+ const httpsTarget = /<https:\/\/[^>]+>/i.test(unsubscribe);
247
+ if (!httpsTarget) {
248
+ add("warning", "no-one-click-unsubscribe", "List-Unsubscribe has no https:// target, so one-click unsubscribe is unavailable.", "Add an HTTPS endpoint and List-Unsubscribe-Post: List-Unsubscribe=One-Click.");
249
+ }
250
+ else if (!oneClick?.toLowerCase().includes("list-unsubscribe=one-click")) {
251
+ add("warning", "missing-one-click-post", "List-Unsubscribe-Post: List-Unsubscribe=One-Click is missing.");
252
+ }
253
+ }
254
+ if (!input.config.postalAddress) {
255
+ add("warning", "missing-postal-address", "No physical postal address is configured (required for commercial mail in the US).", "Set POSTAL_ADDRESS and include it in the footer.");
256
+ }
257
+ if (!/\bunsubscribe\b/i.test(`${text} ${visibleHtml}`)) {
258
+ add("warning", "no-unsubscribe-body", "The body has no visible unsubscribe link.");
259
+ }
260
+ }
261
+ const fromDomain = emailDomain(input.from);
262
+ if (fromDomain && fromDomain !== input.config.domain) {
263
+ add("warning", "from-domain-mismatch", `From uses ${fromDomain}, but the configured domain is ${input.config.domain}.`, "SPF/DKIM alignment will be for the wrong domain. This is the free-Gmail alias trap.");
264
+ }
265
+ if (!input.config.fromName.trim()) {
266
+ add("info", "no-from-name", "The From header has no display name.");
267
+ }
268
+ if (emailDomain(input.config.bounceEmail) !== fromDomain) {
269
+ add("warning", "bounce-domain-mismatch", "The envelope sender (BOUNCE_EMAIL) is on a different domain from From.", "SPF is evaluated against the envelope sender, so this weakens alignment.");
270
+ }
271
+ if (input.config.gmailUser && emailDomain(input.config.gmailUser) !== fromDomain) {
272
+ add("info", "gmail-send-as", `Authenticated Gmail user ${input.config.gmailUser} differs from From.`, "Workspace requires a verified “Send mail as” alias for this address.");
273
+ }
274
+ const order = { error: 0, warning: 1, info: 2 };
275
+ findings.sort((a, b) => order[a.severity] - order[b.severity]);
276
+ const errors = findings.filter((finding) => finding.severity === "error").length;
277
+ const warnings = findings.filter((finding) => finding.severity === "warning").length;
278
+ return { findings, errors, warnings, ...scoreFindings(findings) };
279
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Deliverability-friendly transactional email templates.
3
+ *
4
+ * Each template produces both a clean plain-text version and an aligned,
5
+ * responsive HTML version to maintain strict spam-filter compliance.
6
+ */
7
+ export const escapeHtml = (value) => value
8
+ .replace(/&/g, "&amp;")
9
+ .replace(/</g, "&lt;")
10
+ .replace(/>/g, "&gt;")
11
+ .replace(/"/g, "&quot;")
12
+ .replace(/'/g, "&#39;");
13
+ /**
14
+ * Replaces {{variable}} placeholders with values from data.
15
+ */
16
+ export function interpolate(template, data) {
17
+ if (!data)
18
+ return template;
19
+ return template.replace(/\{\{\s*([a-zA-Z0-9_-]+)\s*\}\}/g, (_, key) => {
20
+ return key in data ? String(data[key]) : `{{${key}}}`;
21
+ });
22
+ }
23
+ function buildFooter(config, bulk) {
24
+ const brand = config.brandName;
25
+ const text = [
26
+ bulk
27
+ ? `You are receiving this because you asked to hear from ${brand}.`
28
+ : `This is an automated transactional message from ${brand}.`,
29
+ config.postalAddress ? config.postalAddress : undefined,
30
+ config.unsubscribeUrl
31
+ ? `Unsubscribe: ${config.unsubscribeUrl}`
32
+ : bulk
33
+ ? `Unsubscribe: mail ${config.bounceEmail} with the subject "unsubscribe".`
34
+ : undefined,
35
+ ]
36
+ .filter(Boolean)
37
+ .join("\n");
38
+ const html = `
39
+ <p style="margin:28px 0 0;font-size:12px;line-height:18px;color:#6b7280;border-top:1px solid #f3f4f6;padding-top:16px;">
40
+ ${escapeHtml(bulk
41
+ ? `You are receiving this because you asked to hear from ${brand}.`
42
+ : `This is an automated transactional message from ${brand}.`)}
43
+ ${config.postalAddress ? `<br>${escapeHtml(config.postalAddress)}` : ""}
44
+ ${config.unsubscribeUrl
45
+ ? `<br><a href="${escapeHtml(config.unsubscribeUrl)}" style="color:#6b7280;text-decoration:underline;">Unsubscribe</a>`
46
+ : bulk
47
+ ? `<br>Unsubscribe by replying with “unsubscribe”.`
48
+ : ""}
49
+ </p>`;
50
+ return { text, html };
51
+ }
52
+ function wrapLayout(subject, contentHtml) {
53
+ return `<!doctype html>
54
+ <html lang="en">
55
+ <head>
56
+ <meta charset="utf-8">
57
+ <meta name="viewport" content="width=device-width,initial-scale=1">
58
+ <title>${escapeHtml(subject)}</title>
59
+ </head>
60
+ <body style="margin:0;padding:0;background:#f6f7f9;">
61
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f6f7f9;padding:32px 12px;">
62
+ <tr>
63
+ <td align="center">
64
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;background:#ffffff;border:1px solid #e5e7eb;">
65
+ <tr>
66
+ <td style="padding:32px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;font-size:16px;line-height:26px;color:#111827;">
67
+ ${contentHtml}
68
+ </td>
69
+ </tr>
70
+ </table>
71
+ </td>
72
+ </tr>
73
+ </table>
74
+ </body>
75
+ </html>`;
76
+ }
77
+ /** 1. Default greeting template */
78
+ export function hello(config, options = {}) {
79
+ const name = options.recipientName?.trim() || options.data?.name;
80
+ const greeting = name ? `Hi ${name},` : "Hi there,";
81
+ const brand = config.brandName;
82
+ const site = `https://${config.domain}`;
83
+ const subject = `A quick hello from ${brand}`;
84
+ const footer = buildFooter(config, Boolean(options.bulk));
85
+ const text = `${greeting}
86
+
87
+ This is a deliverability test from ${brand}. If it landed in your inbox, SPF, DKIM and DMARC are working.
88
+
89
+ You can reply to this message — replies go to a real mailbox, which is itself a positive signal.
90
+
91
+ ${site}
92
+
93
+ — The ${brand} team
94
+
95
+ ${footer.text}
96
+ `;
97
+ const contentHtml = `
98
+ <p style="margin:0 0 16px;">${escapeHtml(greeting)}</p>
99
+ <p style="margin:0 0 16px;">
100
+ This is a deliverability test from <strong>${escapeHtml(brand)}</strong>.
101
+ If it landed in your inbox, SPF, DKIM and DMARC are working.
102
+ </p>
103
+ <p style="margin:0 0 24px;">
104
+ You can reply to this message — replies go to a real mailbox, which is itself a positive signal.
105
+ </p>
106
+ <p style="margin:0 0 24px;">
107
+ <a href="${escapeHtml(site)}" style="background:#111827;color:#ffffff;text-decoration:none;padding:12px 20px;display:inline-block;font-weight:600;">Visit ${escapeHtml(brand)}</a>
108
+ </p>
109
+ <p style="margin:0;">— The ${escapeHtml(brand)} team</p>
110
+ ${footer.html}
111
+ `;
112
+ return { subject, text, html: wrapLayout(subject, contentHtml) };
113
+ }
114
+ /** 2. OTP / Verification Code template */
115
+ export function otp(config, options = {}) {
116
+ const data = options.data ?? {};
117
+ const code = String(data.code ?? "------");
118
+ const expiry = String(data.expiryMinutes ?? "10");
119
+ const name = options.recipientName?.trim() || data.name;
120
+ const greeting = name ? `Hi ${name},` : "Hi,";
121
+ const brand = config.brandName;
122
+ const subject = `${code} is your verification code for ${brand}`;
123
+ const footer = buildFooter(config, false);
124
+ const text = `${greeting}
125
+
126
+ Your ${brand} verification code is:
127
+
128
+ ${code}
129
+
130
+ This code will expire in ${expiry} minutes. If you did not request this code, you can safely ignore this email.
131
+
132
+ — The ${brand} Security Team
133
+
134
+ ${footer.text}
135
+ `;
136
+ const contentHtml = `
137
+ <p style="margin:0 0 16px;">${escapeHtml(greeting)}</p>
138
+ <p style="margin:0 0 16px;">Your verification code for <strong>${escapeHtml(brand)}</strong> is:</p>
139
+ <div style="margin:24px 0;padding:16px 24px;background:#f3f4f6;text-align:center;">
140
+ <span style="font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-size:32px;font-weight:700;letter-spacing:6px;color:#111827;">${escapeHtml(code)}</span>
141
+ </div>
142
+ <p style="margin:0 0 16px;font-size:14px;color:#4b5563;">
143
+ This code will expire in <strong>${escapeHtml(expiry)} minutes</strong>. If you did not request this, please secure your account.
144
+ </p>
145
+ <p style="margin:16px 0 0;">— The ${escapeHtml(brand)} Security Team</p>
146
+ ${footer.html}
147
+ `;
148
+ return { subject, text, html: wrapLayout(subject, contentHtml) };
149
+ }
150
+ /** 3. Transaction / Receipt template */
151
+ export function receipt(config, options = {}) {
152
+ const data = options.data ?? {};
153
+ const item = String(data.item ?? "Order Confirmation");
154
+ const amount = String(data.amount ?? "");
155
+ const receiptUrl = String(data.receiptUrl ?? `https://${config.domain}`);
156
+ const name = options.recipientName?.trim() || data.name;
157
+ const greeting = name ? `Hi ${name},` : "Hi,";
158
+ const brand = config.brandName;
159
+ const subject = `Your receipt from ${brand}${amount ? ` (${amount})` : ""}`;
160
+ const footer = buildFooter(config, false);
161
+ const text = `${greeting}
162
+
163
+ Thanks for your order with ${brand}!
164
+
165
+ Item: ${item}
166
+ ${amount ? `Total: ${amount}\n` : ""}
167
+ You can view and download your full invoice receipt here:
168
+ ${receiptUrl}
169
+
170
+ — The ${brand} Team
171
+
172
+ ${footer.text}
173
+ `;
174
+ const contentHtml = `
175
+ <p style="margin:0 0 16px;">${escapeHtml(greeting)}</p>
176
+ <p style="margin:0 0 16px;">Thanks for your order with <strong>${escapeHtml(brand)}</strong>!</p>
177
+ <div style="margin:24px 0;padding:20px;border:1px solid #e5e7eb;">
178
+ <p style="margin:0 0 8px;font-weight:600;font-size:18px;">${escapeHtml(item)}</p>
179
+ ${amount ? `<p style="margin:0 0 16px;font-size:22px;font-weight:700;color:#059669;">${escapeHtml(amount)}</p>` : ""}
180
+ <a href="${escapeHtml(receiptUrl)}" style="background:#111827;color:#ffffff;text-decoration:none;padding:10px 18px;display:inline-block;font-size:14px;font-weight:600;">View Receipt</a>
181
+ </div>
182
+ <p style="margin:16px 0 0;">— The ${escapeHtml(brand)} Team</p>
183
+ ${footer.html}
184
+ `;
185
+ return { subject, text, html: wrapLayout(subject, contentHtml) };
186
+ }
187
+ /** 4. Security / Account Alert template */
188
+ export function alert(config, options = {}) {
189
+ const data = options.data ?? {};
190
+ const title = String(data.title ?? "Important Account Notification");
191
+ const message = String(data.message ?? "We noticed new activity on your account.");
192
+ const actionUrl = data.actionUrl ? String(data.actionUrl) : undefined;
193
+ const actionText = String(data.actionText ?? "Review Activity");
194
+ const name = options.recipientName?.trim() || data.name;
195
+ const greeting = name ? `Hi ${name},` : "Hi,";
196
+ const brand = config.brandName;
197
+ const subject = `${title} - ${brand}`;
198
+ const footer = buildFooter(config, false);
199
+ const text = `${greeting}
200
+
201
+ ${title}
202
+
203
+ ${message}
204
+ ${actionUrl ? `\nReview here: ${actionUrl}\n` : ""}
205
+ — The ${brand} Support Team
206
+
207
+ ${footer.text}
208
+ `;
209
+ const contentHtml = `
210
+ <p style="margin:0 0 16px;">${escapeHtml(greeting)}</p>
211
+ <div style="margin:0 0 20px;padding:16px;background:#fef2f2;border-left:4px solid #ef4444;">
212
+ <p style="margin:0 0 8px;font-weight:700;color:#991b1b;font-size:16px;">${escapeHtml(title)}</p>
213
+ <p style="margin:0;color:#7f1d1d;font-size:14px;line-height:22px;">${escapeHtml(message)}</p>
214
+ </div>
215
+ ${actionUrl
216
+ ? `<p style="margin:24px 0;"><a href="${escapeHtml(actionUrl)}" style="background:#ef4444;color:#ffffff;text-decoration:none;padding:12px 20px;display:inline-block;font-weight:600;">${escapeHtml(actionText)}</a></p>`
217
+ : ""}
218
+ <p style="margin:16px 0 0;">— The ${escapeHtml(brand)} Support Team</p>
219
+ ${footer.html}
220
+ `;
221
+ return { subject, text, html: wrapLayout(subject, contentHtml) };
222
+ }
223
+ export const templates = {
224
+ hello,
225
+ otp,
226
+ receipt,
227
+ alert,
228
+ };
@@ -0,0 +1,350 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from 'node:fs';
3
+ import * as readline from 'node:readline';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { lintMessage } from '../mail/lint.js';
6
+ import { hello, otp, receipt, alert } from '../mail/templates.js';
7
+ const GATEWAY_URL = process.env.VERNAL_GATEWAY_URL || 'https://api.vernalmail.dev';
8
+ const API_KEY = process.env.VERNAL_API_KEY || '';
9
+ const SEND_TIMEOUT_MS = 15_000;
10
+ const TOOLS = [
11
+ {
12
+ name: 'vernal_send_email',
13
+ description: 'Send a transactional or marketing email via Vernal Gateway with deliverability linting.',
14
+ inputSchema: {
15
+ type: 'object',
16
+ properties: {
17
+ to: { type: 'string', description: 'Recipient email address' },
18
+ subject: { type: 'string', description: 'Subject line (required for custom emails)' },
19
+ text: { type: 'string', description: 'Plain-text body' },
20
+ html: { type: 'string', description: 'Optional HTML body' },
21
+ template: {
22
+ type: 'string',
23
+ enum: ['otp', 'receipt', 'alert', 'hello'],
24
+ description: 'Built-in responsive template name'
25
+ },
26
+ templateData: {
27
+ type: 'object',
28
+ description: 'Key-value variables matching template placeholders (e.g. { code: "123456" })'
29
+ },
30
+ dryRun: {
31
+ type: 'boolean',
32
+ description: 'Validate and score deliverability without sending to SMTP (default: false)'
33
+ },
34
+ idempotencyKey: {
35
+ type: 'string',
36
+ pattern: '^[A-Za-z0-9._~-]{1,128}$',
37
+ description: 'Supply one key per logical send and reuse it with the same payload after a timeout.'
38
+ }
39
+ },
40
+ required: ['to']
41
+ }
42
+ },
43
+ {
44
+ name: 'vernal_lint_email',
45
+ description: 'Preflight deliverability and anti-spam audit for an email message. Returns score (0-100), letter grade, and actionable recommendations.',
46
+ inputSchema: {
47
+ type: 'object',
48
+ properties: {
49
+ to: { type: 'string', description: 'Recipient email address' },
50
+ subject: { type: 'string', description: 'Subject line' },
51
+ text: { type: 'string', description: 'Plain-text content' },
52
+ html: { type: 'string', description: 'HTML content' }
53
+ },
54
+ required: ['subject', 'text']
55
+ }
56
+ },
57
+ {
58
+ name: 'vernal_get_message',
59
+ description: 'Check the delivery status, attempt counter, and audit trail of an email job.',
60
+ inputSchema: {
61
+ type: 'object',
62
+ properties: {
63
+ id: { type: 'string', description: 'Message Job ID returned from vernal_send_email' }
64
+ },
65
+ required: ['id']
66
+ }
67
+ },
68
+ {
69
+ name: 'vernal_manage_domains',
70
+ description: 'Manage multi-tenant custom domains, inspect 2048-bit RSA DKIM keys, and verify DNS records via DoH.',
71
+ inputSchema: {
72
+ type: 'object',
73
+ properties: {
74
+ action: {
75
+ type: 'string',
76
+ enum: ['list', 'create', 'verify', 'get'],
77
+ description: 'Action to perform'
78
+ },
79
+ name: { type: 'string', description: 'Domain name (required for create)' },
80
+ id: { type: 'string', description: 'Domain ID (required for verify and get)' }
81
+ },
82
+ required: ['action']
83
+ }
84
+ },
85
+ {
86
+ name: 'vernal_gateway_health',
87
+ description: 'Inspect Vernal Gateway operational status, configured tenant domain, and queue metrics.',
88
+ inputSchema: {
89
+ type: 'object',
90
+ properties: {}
91
+ }
92
+ }
93
+ ];
94
+ function sendResponse(res) {
95
+ process.stdout.write(JSON.stringify(res) + '\n');
96
+ }
97
+ const defaultMockConfig = {
98
+ domain: 'vernalmail.dev',
99
+ fromName: 'Vernal Mail',
100
+ fromEmail: 'noreply@vernalmail.dev',
101
+ brandName: 'Vernal Mail',
102
+ bounceEmail: 'bounce@vernalmail.dev',
103
+ unsubscribeUrl: 'https://vernalmail.dev/unsubscribe',
104
+ postalAddress: '1916 Post Road, Vernal, UT 84078',
105
+ dkim: { selector: 'vernal' },
106
+ dmarc: { policy: 'none' },
107
+ cloudflare: {}
108
+ };
109
+ async function handleToolCall(name, args = {}) {
110
+ switch (name) {
111
+ case 'vernal_send_email': {
112
+ const { idempotencyKey, ...payload } = args;
113
+ if (idempotencyKey !== undefined &&
114
+ (typeof idempotencyKey !== 'string' || !/^[A-Za-z0-9._~-]{1,128}$/.test(idempotencyKey))) {
115
+ throw new Error('Invalid idempotency key. Use 1–128 ASCII letters, digits, dots, underscores, tildes or hyphens.');
116
+ }
117
+ // If template is used locally without API key, render locally if dryRun is true
118
+ if (args.dryRun && !API_KEY && args.template) {
119
+ const tplFnMap = { hello, otp, receipt, alert };
120
+ const tplFn = tplFnMap[args.template];
121
+ if (!tplFn) {
122
+ throw new Error(`Unknown template: ${args.template}`);
123
+ }
124
+ const tpl = tplFn(defaultMockConfig, { data: args.templateData, recipientName: args.templateData?.name });
125
+ const lint = lintMessage({
126
+ config: defaultMockConfig,
127
+ to: Array.isArray(args.to) ? args.to : [args.to],
128
+ from: 'noreply@vernalmail.dev',
129
+ subject: tpl.subject,
130
+ text: tpl.text,
131
+ html: tpl.html
132
+ });
133
+ return {
134
+ success: true,
135
+ dryRun: true,
136
+ mode: 'offline_local_simulation',
137
+ subject: tpl.subject,
138
+ lint
139
+ };
140
+ }
141
+ const signal = AbortSignal.timeout(SEND_TIMEOUT_MS);
142
+ try {
143
+ const res = await fetch(`${GATEWAY_URL}/v1/send`, {
144
+ method: 'POST',
145
+ headers: {
146
+ 'Content-Type': 'application/json',
147
+ ...(API_KEY ? { Authorization: `Bearer ${API_KEY}` } : {}),
148
+ ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {})
149
+ },
150
+ body: JSON.stringify(payload),
151
+ signal
152
+ });
153
+ const data = await res.json();
154
+ const retryAfter = res.headers.get('retry-after');
155
+ return { ...data, httpStatus: res.status, ...(retryAfter ? { retryAfter } : {}) };
156
+ }
157
+ catch {
158
+ const problem = signal.aborted ? 'The gateway response timed out.' : 'The gateway response could not be read.';
159
+ const recovery = idempotencyKey
160
+ ? 'Within the retry window, retry with the same idempotency key and payload.'
161
+ : 'Check Message Logs before submitting again.';
162
+ throw new Error(`${problem} The send may have been accepted. ${recovery}`);
163
+ }
164
+ }
165
+ case 'vernal_lint_email': {
166
+ const toList = Array.isArray(args.to) ? args.to : [args.to || 'recipient@example.com'];
167
+ const lint = lintMessage({
168
+ config: defaultMockConfig,
169
+ to: toList,
170
+ from: args.from || 'noreply@vernalmail.dev',
171
+ subject: args.subject,
172
+ text: args.text,
173
+ html: args.html
174
+ });
175
+ const passed = lint.errors === 0;
176
+ return {
177
+ score: lint.score,
178
+ grade: lint.grade,
179
+ passed,
180
+ findings: lint.findings,
181
+ summary: `Preflight score: ${lint.score}/100 (Grade: ${lint.grade}) - ${passed ? 'PASSED' : 'FAILED'}`
182
+ };
183
+ }
184
+ case 'vernal_get_message': {
185
+ const res = await fetch(`${GATEWAY_URL}/v1/messages/${encodeURIComponent(args.id)}`, {
186
+ headers: {
187
+ ...(API_KEY ? { Authorization: `Bearer ${API_KEY}` } : {})
188
+ }
189
+ });
190
+ return await res.json();
191
+ }
192
+ case 'vernal_manage_domains': {
193
+ const { action, name, id } = args;
194
+ if (action === 'list') {
195
+ const res = await fetch(`${GATEWAY_URL}/v1/domains`, {
196
+ headers: { ...(API_KEY ? { Authorization: `Bearer ${API_KEY}` } : {}) }
197
+ });
198
+ return await res.json();
199
+ }
200
+ if (action === 'create') {
201
+ if (!name)
202
+ throw new Error('name is required for action=create');
203
+ const res = await fetch(`${GATEWAY_URL}/v1/domains`, {
204
+ method: 'POST',
205
+ headers: {
206
+ 'Content-Type': 'application/json',
207
+ ...(API_KEY ? { Authorization: `Bearer ${API_KEY}` } : {})
208
+ },
209
+ body: JSON.stringify({ name })
210
+ });
211
+ return await res.json();
212
+ }
213
+ if (action === 'verify') {
214
+ if (!id)
215
+ throw new Error('id is required for action=verify');
216
+ const res = await fetch(`${GATEWAY_URL}/v1/domains/${encodeURIComponent(id)}/verify`, {
217
+ method: 'POST',
218
+ headers: { ...(API_KEY ? { Authorization: `Bearer ${API_KEY}` } : {}) }
219
+ });
220
+ return await res.json();
221
+ }
222
+ if (action === 'get') {
223
+ if (!id)
224
+ throw new Error('id is required for action=get');
225
+ const res = await fetch(`${GATEWAY_URL}/v1/domains/${encodeURIComponent(id)}`, {
226
+ headers: { ...(API_KEY ? { Authorization: `Bearer ${API_KEY}` } : {}) }
227
+ });
228
+ return await res.json();
229
+ }
230
+ throw new Error(`Unknown action: ${action}`);
231
+ }
232
+ case 'vernal_gateway_health': {
233
+ const res = await fetch(`${GATEWAY_URL}/v1/health`);
234
+ return await res.json();
235
+ }
236
+ default:
237
+ throw new Error(`Tool not found: ${name}`);
238
+ }
239
+ }
240
+ export function startMcpServer() {
241
+ const rl = readline.createInterface({
242
+ input: process.stdin,
243
+ output: process.stdout,
244
+ terminal: false
245
+ });
246
+ rl.on('line', async (line) => {
247
+ const trimmed = line.trim();
248
+ if (!trimmed)
249
+ return;
250
+ let req;
251
+ try {
252
+ req = JSON.parse(trimmed);
253
+ }
254
+ catch (err) {
255
+ sendResponse({
256
+ jsonrpc: '2.0',
257
+ error: { code: -32700, message: `Parse error: ${err.message}` }
258
+ });
259
+ return;
260
+ }
261
+ if (req.method === 'initialize') {
262
+ sendResponse({
263
+ jsonrpc: '2.0',
264
+ id: req.id,
265
+ result: {
266
+ protocolVersion: '2024-11-05',
267
+ capabilities: {
268
+ tools: {}
269
+ },
270
+ serverInfo: {
271
+ name: 'vernal-mcp',
272
+ version: '1.0.0'
273
+ }
274
+ }
275
+ });
276
+ return;
277
+ }
278
+ if (req.method === 'notifications/initialized') {
279
+ return;
280
+ }
281
+ if (req.method === 'ping') {
282
+ sendResponse({
283
+ jsonrpc: '2.0',
284
+ id: req.id,
285
+ result: {}
286
+ });
287
+ return;
288
+ }
289
+ if (req.method === 'tools/list') {
290
+ sendResponse({
291
+ jsonrpc: '2.0',
292
+ id: req.id,
293
+ result: {
294
+ tools: TOOLS
295
+ }
296
+ });
297
+ return;
298
+ }
299
+ if (req.method === 'tools/call') {
300
+ const toolName = req.params?.name;
301
+ const toolArgs = req.params?.arguments || {};
302
+ try {
303
+ const output = await handleToolCall(toolName, toolArgs);
304
+ sendResponse({
305
+ jsonrpc: '2.0',
306
+ id: req.id,
307
+ result: {
308
+ content: [
309
+ {
310
+ type: 'text',
311
+ text: JSON.stringify(output, null, 2)
312
+ }
313
+ ],
314
+ isError: false
315
+ }
316
+ });
317
+ }
318
+ catch (err) {
319
+ sendResponse({
320
+ jsonrpc: '2.0',
321
+ id: req.id,
322
+ result: {
323
+ content: [
324
+ {
325
+ type: 'text',
326
+ text: `Error executing ${toolName}: ${err.message}`
327
+ }
328
+ ],
329
+ isError: true
330
+ }
331
+ });
332
+ }
333
+ return;
334
+ }
335
+ if (req.id !== undefined) {
336
+ sendResponse({
337
+ jsonrpc: '2.0',
338
+ id: req.id,
339
+ error: {
340
+ code: -32601,
341
+ message: `Method not found: ${req.method}`
342
+ }
343
+ });
344
+ }
345
+ });
346
+ }
347
+ // Start immediately if executed directly
348
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
349
+ startMcpServer();
350
+ }
package/dist/util.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Shared, dependency-free helpers.
3
+ */
4
+ export class AppError extends Error {
5
+ hint;
6
+ statusCode;
7
+ constructor(message, hintOrStatus, statusCode) {
8
+ super(message);
9
+ this.name = "AppError";
10
+ if (typeof hintOrStatus === "number") {
11
+ this.statusCode = hintOrStatus;
12
+ }
13
+ else {
14
+ this.hint = hintOrStatus;
15
+ this.statusCode = statusCode;
16
+ }
17
+ }
18
+ }
19
+ export class ConfigError extends AppError {
20
+ constructor(message, hint) {
21
+ super(message, hint);
22
+ this.name = "ConfigError";
23
+ }
24
+ }
25
+ export class UsageError extends AppError {
26
+ constructor(message, hint) {
27
+ super(message, hint);
28
+ this.name = "UsageError";
29
+ }
30
+ }
31
+ /** Reject values that would allow SMTP/header injection. */
32
+ export function assertHeaderSafe(value, field) {
33
+ if (/[\r\n]/.test(value)) {
34
+ throw new UsageError(`${field} must not contain line breaks`);
35
+ }
36
+ // NUL bytes are not valid in headers either.
37
+ if (value.includes("\0")) {
38
+ throw new UsageError(`${field} must not contain NUL bytes`);
39
+ }
40
+ return value;
41
+ }
42
+ export function isEmail(value) {
43
+ // Intentionally pragmatic: one @, no whitespace, a dot in the domain.
44
+ return /^[^\s@<>()[\]\\,;:]+@[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?\.[A-Za-z]{2,}$/.test(value);
45
+ }
46
+ export function normalizeDomain(value) {
47
+ return value.trim().toLowerCase().replace(/\.$/, "");
48
+ }
49
+ export function isDomain(value) {
50
+ return /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(value);
51
+ }
52
+ export function emailDomain(address) {
53
+ if (!address || typeof address !== "string")
54
+ return "";
55
+ const at = address.lastIndexOf("@");
56
+ return at === -1 ? "" : normalizeDomain(address.slice(at + 1));
57
+ }
58
+ export function truncate(value, max) {
59
+ return value.length <= max ? value : `${value.slice(0, Math.max(0, max - 1))}…`;
60
+ }
61
+ export function unique(values) {
62
+ return [...new Set(values)];
63
+ }
64
+ export function slugify(value) {
65
+ return (value
66
+ .toLowerCase()
67
+ .replace(/[^a-z0-9]+/g, "-")
68
+ .replace(/^-+|-+$/g, "")
69
+ .slice(0, 60) || "message");
70
+ }
71
+ /** Very small fixed-width table renderer for CLI output. */
72
+ export function renderTable(headers, rows) {
73
+ const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length)));
74
+ const line = (cells) => cells
75
+ .map((cell, index) => cell.padEnd(widths[index] ?? 0))
76
+ .join(" ")
77
+ .trimEnd();
78
+ const separator = widths.map((width) => "─".repeat(width)).join(" ");
79
+ return [line(headers), separator, ...rows.map(line)].join("\n");
80
+ }
package/package.json CHANGED
@@ -1,6 +1,10 @@
1
1
  {
2
2
  "name": "@vernal-systems/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Vernal Mail MCP server for email preflight, dispatch and job status",
5
+ "type": "module",
6
+ "engines": { "node": ">=20" },
7
+ "bin": { "vernal-mcp": "./dist/mcp/server.js" },
8
+ "files": ["dist/mcp/server.js", "dist/mail/lint.js", "dist/mail/templates.js", "dist/util.js", "README.md"],
9
+ "license": "UNLICENSED"
10
+ }