@mailquilt/mcp 0.0.0-stage → 0.5.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/dist/bin.js ADDED
@@ -0,0 +1,1154 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import { parseArgs } from "node:util";
4
+ import { createInterface } from "node:readline";
5
+ import { BLOCK_TYPES, ROW_LAYOUTS, createEditor, createEmail, loadDocument } from "@mailquilt/core";
6
+ import { checkEmail, renderEmail, renderText } from "@mailquilt/renderer";
7
+ import { GMAIL_CLIP_BYTES, gmailKilobytes } from "@mailquilt/renderer/internal";
8
+ import { readFileSync, realpathSync } from "node:fs";
9
+ import { rowLayoutOf } from "@mailquilt/core/internal";
10
+ import { randomBytes } from "node:crypto";
11
+ import { lstat, mkdir, readFile, realpath, rename, unlink, writeFile } from "node:fs/promises";
12
+ import path from "node:path";
13
+ // package.json
14
+ var name = "@mailquilt/mcp";
15
+ var version = "0.5.0";
16
+ // src/catalog.ts
17
+ const require = createRequire(import.meta.url);
18
+ const isRecord$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
19
+ /** Loads the live JSON Schema published by `@mailquilt/core/schema.json`. */
20
+ const loadCoreJsonSchema = () => {
21
+ const schemaPath = require.resolve("@mailquilt/core/schema.json");
22
+ const raw = readFileSync(schemaPath, "utf-8");
23
+ const parsed = JSON.parse(raw);
24
+ if (!isRecord$2(parsed)) throw new Error("@mailquilt/core/schema.json did not export an object.");
25
+ return parsed;
26
+ };
27
+ const getNestedRecord = (root, keys) => {
28
+ let cursor = root;
29
+ for (const key of keys) {
30
+ if (!isRecord$2(cursor)) return;
31
+ cursor = cursor[key];
32
+ }
33
+ return isRecord$2(cursor) ? cursor : void 0;
34
+ };
35
+ const extractBlockSchemas = (schema) => {
36
+ const result = /* @__PURE__ */ new Map();
37
+ const variants = getNestedRecord(schema, [
38
+ "properties",
39
+ "rows",
40
+ "items",
41
+ "properties",
42
+ "columns",
43
+ "items",
44
+ "properties",
45
+ "blocks",
46
+ "items"
47
+ ])?.oneOf;
48
+ if (!Array.isArray(variants)) return result;
49
+ for (const variant of variants) {
50
+ if (!isRecord$2(variant) || !isRecord$2(variant.properties)) continue;
51
+ const typeSchema = variant.properties.type;
52
+ const propsSchema = variant.properties.props;
53
+ if (isRecord$2(typeSchema) && typeof typeSchema.const === "string" && isRecord$2(propsSchema)) result.set(typeSchema.const, propsSchema);
54
+ }
55
+ return result;
56
+ };
57
+ const stringArray = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
58
+ /**
59
+ * Builds the live Block, Row layout, and JSON Schema catalog directly from
60
+ * `@mailquilt/core` (`BLOCK_TYPES`, `ROW_LAYOUTS`, `@mailquilt/core/schema.json`).
61
+ */
62
+ const buildBlockCatalog = (filterBlockType) => {
63
+ const schema = loadCoreJsonSchema();
64
+ const blockSchemas = extractBlockSchemas(schema);
65
+ const versionSchema = getNestedRecord(schema, ["properties", "version"]);
66
+ const documentVersion = typeof versionSchema?.const === "number" ? versionSchema.const : null;
67
+ const schemaId = typeof schema.$id === "string" ? schema.$id : null;
68
+ const allEntries = BLOCK_TYPES.map(({ label, type }) => {
69
+ const propsSchema = blockSchemas.get(type) ?? null;
70
+ return {
71
+ label,
72
+ propNames: propsSchema && isRecord$2(propsSchema.properties) ? Object.keys(propsSchema.properties) : [],
73
+ propsSchema,
74
+ requiredProps: propsSchema ? stringArray(propsSchema.required) : [],
75
+ type
76
+ };
77
+ });
78
+ const knownTypes = new Set(allEntries.map(({ type }) => type));
79
+ for (const [type, propsSchema] of blockSchemas.entries()) {
80
+ if (knownTypes.has(type)) continue;
81
+ const propProperties = isRecord$2(propsSchema.properties) ? Object.keys(propsSchema.properties) : [];
82
+ allEntries.push({
83
+ label: type,
84
+ propNames: propProperties,
85
+ propsSchema,
86
+ requiredProps: stringArray(propsSchema.required),
87
+ type
88
+ });
89
+ }
90
+ const blockTypes = filterBlockType === void 0 ? allEntries : allEntries.filter(({ type }) => type === filterBlockType);
91
+ const rowPropsSchema = getNestedRecord(schema, [
92
+ "properties",
93
+ "rows",
94
+ "items",
95
+ "properties",
96
+ "props"
97
+ ]) ?? null;
98
+ const columnPropsSchema = getNestedRecord(schema, [
99
+ "properties",
100
+ "rows",
101
+ "items",
102
+ "properties",
103
+ "columns",
104
+ "items",
105
+ "properties",
106
+ "props"
107
+ ]) ?? null;
108
+ const settingsSchema = getNestedRecord(schema, ["properties", "settings"]) ?? null;
109
+ return {
110
+ blockTypes,
111
+ columnPropsSchema,
112
+ documentVersion,
113
+ rowLayouts: [...ROW_LAYOUTS],
114
+ rowPropsSchema,
115
+ schemaId,
116
+ settingsSchema
117
+ };
118
+ };
119
+ // src/summary.ts
120
+ const MAX_PREVIEW_LENGTH = 80;
121
+ const truncate = (value) => {
122
+ const collapsed = value.replaceAll(/\s+/gu, " ").trim();
123
+ if (collapsed.length <= MAX_PREVIEW_LENGTH) return collapsed;
124
+ return `${collapsed.slice(0, 79)}…`;
125
+ };
126
+ const extractRichTextSnippet = (node) => {
127
+ if (typeof node !== "object" || node === null) return "";
128
+ const record = node;
129
+ if (record.type === "text" && typeof record.text === "string") return record.text;
130
+ if (record.type === "mergeTag") {
131
+ const attrs = record.attrs;
132
+ return typeof attrs?.name === "string" ? `{{${attrs.name}}}` : "";
133
+ }
134
+ if (record.type === "hardBreak") return " ";
135
+ if (Array.isArray(record.content)) return record.content.map((child) => extractRichTextSnippet(child)).filter((part) => part !== "").join(" ");
136
+ return "";
137
+ };
138
+ const summarizeBlockPreview = (block) => {
139
+ const props = block.props;
140
+ if ("content" in props) {
141
+ const snippet = truncate(extractRichTextSnippet(props.content));
142
+ if (snippet !== "") return snippet;
143
+ }
144
+ if (typeof props.label === "string" && props.label.trim() !== "") return truncate(props.label);
145
+ if (typeof props.alt === "string" && props.alt.trim() !== "") return truncate(props.alt);
146
+ if (typeof props.src === "string" && props.src.trim() !== "") return truncate(props.src);
147
+ if (typeof props.url === "string" && props.url.trim() !== "") return truncate(props.url);
148
+ if (Array.isArray(props.links)) {
149
+ const items = props.links.map((item) => {
150
+ if (typeof item !== "object" || item === null) return "";
151
+ const entry = item;
152
+ if (typeof entry.label === "string" && entry.label.trim() !== "") return entry.label.trim();
153
+ if (typeof entry.network === "string") return entry.network;
154
+ return "";
155
+ }).filter((part) => part !== "");
156
+ if (items.length > 0) return truncate(items.join(", "));
157
+ }
158
+ if (typeof props.height === "number") return `${props.height}px`;
159
+ if (typeof props.thickness === "number") return `${props.thickness}px`;
160
+ };
161
+ /**
162
+ * Produces a concise structural outline of an email (Rows, Columns, Blocks and
163
+ * their IDs) so agents can target Commands without scanning full ProseMirror JSON.
164
+ */
165
+ const summarizeDocument = (document) => {
166
+ let blockCount = 0;
167
+ const rows = document.rows.map((row, rowIndex) => {
168
+ const layout = rowLayoutOf(row);
169
+ const columns = row.columns.map((column, columnIndex) => {
170
+ const blocks = column.blocks.map((block, blockIndex) => {
171
+ blockCount += 1;
172
+ const preview = summarizeBlockPreview(block);
173
+ return preview === void 0 ? {
174
+ id: block.id,
175
+ index: blockIndex,
176
+ type: block.type
177
+ } : {
178
+ id: block.id,
179
+ index: blockIndex,
180
+ preview,
181
+ type: block.type
182
+ };
183
+ });
184
+ return {
185
+ blockCount: blocks.length,
186
+ blocks,
187
+ id: column.id,
188
+ index: columnIndex,
189
+ width: column.width
190
+ };
191
+ });
192
+ return {
193
+ columnCount: columns.length,
194
+ columns,
195
+ id: row.id,
196
+ index: rowIndex,
197
+ ...layout === void 0 ? {} : { layout }
198
+ };
199
+ });
200
+ const { settings } = document;
201
+ return {
202
+ blockCount,
203
+ rowCount: rows.length,
204
+ rows,
205
+ settings: {
206
+ backgroundColor: settings.backgroundColor,
207
+ fontFamily: settings.fontFamily,
208
+ hasStyle: settings.style !== void 0,
209
+ ...settings.language === void 0 ? {} : { language: settings.language },
210
+ ...settings.preheader === void 0 ? {} : { preheader: settings.preheader },
211
+ width: settings.width
212
+ },
213
+ version: document.version
214
+ };
215
+ };
216
+ // src/workspace.ts
217
+ /** Error thrown when a path resolves outside the configured workspace root. */
218
+ var WorkspacePathError = class extends Error {
219
+ code;
220
+ constructor(code, message) {
221
+ super(message);
222
+ this.name = "WorkspacePathError";
223
+ this.code = code;
224
+ }
225
+ };
226
+ const isErrnoException = (error) => typeof error === "object" && error !== null && "code" in error;
227
+ /**
228
+ * Resolves the workspace root directory to a canonical realpath when it exists,
229
+ * or resolves its deepest existing ancestor when the directory is not yet created.
230
+ */
231
+ const canonicalizeRoot = (root) => {
232
+ const absolute = path.resolve(root);
233
+ try {
234
+ return realpathSync(absolute);
235
+ } catch (error) {
236
+ if (!isErrnoException(error) || error.code !== "ENOENT") throw error;
237
+ }
238
+ const missing = [];
239
+ let cursor = absolute;
240
+ while (true) {
241
+ const parent = path.dirname(cursor);
242
+ if (parent === cursor) return absolute;
243
+ missing.unshift(path.basename(cursor));
244
+ cursor = parent;
245
+ try {
246
+ return path.join(realpathSync(cursor), ...missing);
247
+ } catch (error) {
248
+ if (!isErrnoException(error) || error.code !== "ENOENT") throw error;
249
+ }
250
+ }
251
+ };
252
+ /** Returns true when `target` is strictly inside `root` (never equal to `root`). */
253
+ const isStrictlyInsideRoot = (root, target) => {
254
+ const relative = path.relative(root, target);
255
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
256
+ };
257
+ /** Returns true when `target` is equal to or inside `root`. */
258
+ const isWithinRoot = (root, target) => {
259
+ const relative = path.relative(root, target);
260
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
261
+ };
262
+ const toPosixRelative = (root, target) => path.relative(root, target).split(path.sep).join("/");
263
+ const validateCandidate = (canonicalRoot, inputPath) => {
264
+ if (typeof inputPath !== "string" || inputPath.trim() === "") throw new WorkspacePathError("invalid_path", "Path must be a non-empty string.");
265
+ if (inputPath.includes("\0")) throw new WorkspacePathError("invalid_path", "Path must not contain null bytes.");
266
+ const candidate = path.resolve(canonicalRoot, inputPath);
267
+ if (!isStrictlyInsideRoot(canonicalRoot, candidate)) throw new WorkspacePathError("outside_root", `Path "${inputPath}" escapes the workspace root.`);
268
+ return {
269
+ candidate,
270
+ lexicalRelative: path.relative(canonicalRoot, candidate)
271
+ };
272
+ };
273
+ /**
274
+ * Resolves an existing file inside `root`, rejecting `..` traversal, absolute
275
+ * paths outside `root`, directories, and symlinks pointing outside `root`.
276
+ */
277
+ const resolveWorkspaceReadPath = async (root, inputPath) => {
278
+ const canonicalRoot = canonicalizeRoot(root);
279
+ const { candidate } = validateCandidate(canonicalRoot, inputPath);
280
+ let realTarget;
281
+ try {
282
+ realTarget = await realpath(candidate);
283
+ } catch (error) {
284
+ if (isErrnoException(error) && error.code === "ENOENT") {
285
+ try {
286
+ if ((await lstat(candidate)).isSymbolicLink()) throw new WorkspacePathError("outside_root", `Symlink "${inputPath}" cannot be resolved inside the workspace root.`);
287
+ } catch (lstatError) {
288
+ if (lstatError instanceof WorkspacePathError) throw lstatError;
289
+ }
290
+ throw new WorkspacePathError("not_found", `File "${inputPath}" was not found.`);
291
+ }
292
+ throw error;
293
+ }
294
+ if (!isStrictlyInsideRoot(canonicalRoot, realTarget)) throw new WorkspacePathError("outside_root", `Path "${inputPath}" resolves outside the workspace root.`);
295
+ if (!(await lstat(realTarget)).isFile()) throw new WorkspacePathError("not_a_file", `Path "${inputPath}" is not a regular file.`);
296
+ return {
297
+ absolutePath: realTarget,
298
+ relativePath: toPosixRelative(canonicalRoot, realTarget)
299
+ };
300
+ };
301
+ const resolveWriteSegment = async (canonicalRoot, inputPath, current, segments, index) => {
302
+ if (index >= segments.length) {
303
+ if (!isStrictlyInsideRoot(canonicalRoot, current)) throw new WorkspacePathError("outside_root", `Path "${inputPath}" resolves outside the workspace root.`);
304
+ return {
305
+ absolutePath: current,
306
+ relativePath: toPosixRelative(canonicalRoot, current)
307
+ };
308
+ }
309
+ const segment = segments[index];
310
+ if (!segment) return await resolveWriteSegment(canonicalRoot, inputPath, current, segments, index + 1);
311
+ const next = path.join(current, segment);
312
+ const isLast = index === segments.length - 1;
313
+ let entryStat;
314
+ try {
315
+ entryStat = await lstat(next);
316
+ } catch (error) {
317
+ if (isErrnoException(error) && error.code === "ENOENT") {
318
+ const finalPath = path.join(current, ...segments.slice(index));
319
+ if (!isStrictlyInsideRoot(canonicalRoot, finalPath)) throw new WorkspacePathError("outside_root", `Path "${inputPath}" escapes the workspace root.`);
320
+ return {
321
+ absolutePath: finalPath,
322
+ relativePath: toPosixRelative(canonicalRoot, finalPath)
323
+ };
324
+ }
325
+ throw error;
326
+ }
327
+ if (entryStat.isSymbolicLink()) {
328
+ let realNext;
329
+ try {
330
+ realNext = await realpath(next);
331
+ } catch {
332
+ throw new WorkspacePathError("outside_root", `Symlink "${inputPath}" cannot be resolved inside the workspace root.`);
333
+ }
334
+ if (!isWithinRoot(canonicalRoot, realNext)) throw new WorkspacePathError("outside_root", `Path "${inputPath}" traverses a symlink outside the workspace root.`);
335
+ if (isLast && !isStrictlyInsideRoot(canonicalRoot, realNext)) throw new WorkspacePathError("outside_root", `Path "${inputPath}" resolves outside the workspace root.`);
336
+ const resolvedStat = await lstat(realNext);
337
+ if (isLast && resolvedStat.isDirectory()) throw new WorkspacePathError("not_a_file", `Path "${inputPath}" is a directory.`);
338
+ if (!isLast && !resolvedStat.isDirectory()) throw new WorkspacePathError("invalid_path", `Parent of "${inputPath}" is not a directory.`);
339
+ return await resolveWriteSegment(canonicalRoot, inputPath, realNext, segments, index + 1);
340
+ }
341
+ if (isLast) {
342
+ if (entryStat.isDirectory()) throw new WorkspacePathError("not_a_file", `Path "${inputPath}" is a directory.`);
343
+ return await resolveWriteSegment(canonicalRoot, inputPath, next, segments, index + 1);
344
+ }
345
+ if (!entryStat.isDirectory()) throw new WorkspacePathError("invalid_path", `Parent of "${inputPath}" is not a directory.`);
346
+ return await resolveWriteSegment(canonicalRoot, inputPath, next, segments, index + 1);
347
+ };
348
+ /**
349
+ * Resolves a target file path for writing inside `root`. Walks every existing
350
+ * path component from `root` downward to verify that neither an ancestor
351
+ * directory symlink nor the target symlink escapes `root`.
352
+ */
353
+ const resolveWorkspaceWritePath = async (root, inputPath) => {
354
+ const canonicalRoot = canonicalizeRoot(root);
355
+ const { lexicalRelative } = validateCandidate(canonicalRoot, inputPath);
356
+ const segments = lexicalRelative.split(path.sep);
357
+ return await resolveWriteSegment(canonicalRoot, inputPath, canonicalRoot, segments, 0);
358
+ };
359
+ /** Reads a UTF-8 file strictly inside `root`. */
360
+ const readWorkspaceFile = async (root, inputPath) => {
361
+ const resolved = await resolveWorkspaceReadPath(root, inputPath);
362
+ const content = await readFile(resolved.absolutePath, "utf-8");
363
+ return {
364
+ ...resolved,
365
+ content
366
+ };
367
+ };
368
+ /**
369
+ * Atomically writes UTF-8 content to a file strictly inside `root` by writing
370
+ * to a sibling temporary file and renaming it into place.
371
+ */
372
+ const writeWorkspaceFileAtomic = async (root, inputPath, content, options = {}) => {
373
+ const { overwrite = true } = options;
374
+ const resolved = await resolveWorkspaceWritePath(root, inputPath);
375
+ if (!overwrite) try {
376
+ await lstat(resolved.absolutePath);
377
+ throw new Error(`File "${resolved.relativePath}" already exists. Pass overwrite: true to replace it.`);
378
+ } catch (error) {
379
+ if (!isErrnoException(error) || error.code !== "ENOENT") throw error;
380
+ }
381
+ const directory = path.dirname(resolved.absolutePath);
382
+ await mkdir(directory, { recursive: true });
383
+ const canonicalRoot = canonicalizeRoot(root);
384
+ const realDir = await realpath(directory);
385
+ if (!isWithinRoot(canonicalRoot, realDir)) throw new WorkspacePathError("outside_root", `Parent directory for "${inputPath}" escapes the workspace root.`);
386
+ const tempPath = path.join(realDir, `.mailquilt-tmp-${process.pid}-${randomBytes(6).toString("hex")}`);
387
+ try {
388
+ await writeFile(tempPath, content, "utf-8");
389
+ await rename(tempPath, resolved.absolutePath);
390
+ } catch (error) {
391
+ try {
392
+ await unlink(tempPath);
393
+ } catch {}
394
+ throw error;
395
+ }
396
+ return resolved;
397
+ };
398
+ // src/tools.ts
399
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
400
+ const jsonResult = (payload, isError = false) => ({
401
+ content: [{
402
+ text: JSON.stringify(payload, null, 2),
403
+ type: "text"
404
+ }],
405
+ ...isError ? { isError: true } : {}
406
+ });
407
+ const errorResult = (message, extra = {}) => jsonResult({
408
+ error: message,
409
+ ok: false,
410
+ ...extra
411
+ }, true);
412
+ const errorMessage = (error) => error instanceof Error ? error.message : String(error);
413
+ const parseOptionalString = (args, key) => {
414
+ const value = args[key];
415
+ if (value === void 0) return {
416
+ ok: true,
417
+ value: void 0
418
+ };
419
+ if (typeof value !== "string" || value.trim() === "") return {
420
+ ok: false,
421
+ error: `"${key}" must be a non-empty string.`
422
+ };
423
+ return {
424
+ ok: true,
425
+ value
426
+ };
427
+ };
428
+ const loadTargetDocument = async (context, args) => {
429
+ const hasPath = args.path !== void 0;
430
+ if (hasPath === (args.document !== void 0)) return {
431
+ ok: false,
432
+ result: errorResult("Provide either \"path\" (inside the workspace root) or inline \"document\", not both.")
433
+ };
434
+ if (hasPath) {
435
+ if (typeof args.path !== "string") return {
436
+ ok: false,
437
+ result: errorResult("\"path\" must be a string.")
438
+ };
439
+ let content;
440
+ let relativePath;
441
+ try {
442
+ const read = await readWorkspaceFile(context.root, args.path);
443
+ ({content, relativePath} = read);
444
+ } catch (error) {
445
+ return {
446
+ ok: false,
447
+ result: errorResult(errorMessage(error), error instanceof WorkspacePathError ? { code: error.code } : {})
448
+ };
449
+ }
450
+ let parsed;
451
+ try {
452
+ parsed = JSON.parse(content);
453
+ } catch (error) {
454
+ return {
455
+ ok: false,
456
+ result: errorResult(`Invalid JSON in "${relativePath}": ${errorMessage(error)}`, {
457
+ code: "invalid_json",
458
+ path: relativePath
459
+ })
460
+ };
461
+ }
462
+ const loaded = loadDocument(parsed);
463
+ if (!loaded.ok) return {
464
+ ok: false,
465
+ result: errorResult(`Document "${relativePath}" was refused: ${loaded.reason}`, {
466
+ code: "invalid_document",
467
+ path: relativePath,
468
+ reason: loaded.reason
469
+ })
470
+ };
471
+ return {
472
+ document: loaded.document,
473
+ ok: true,
474
+ relativePath
475
+ };
476
+ }
477
+ const loaded = loadDocument(args.document);
478
+ if (!loaded.ok) return {
479
+ ok: false,
480
+ result: errorResult(`Document was refused: ${loaded.reason}`, {
481
+ code: "invalid_document",
482
+ reason: loaded.reason
483
+ })
484
+ };
485
+ return {
486
+ document: loaded.document,
487
+ ok: true
488
+ };
489
+ };
490
+ const parseMergeTags = (value) => {
491
+ if (value === void 0) return {
492
+ ok: true,
493
+ value: void 0
494
+ };
495
+ if (!Array.isArray(value)) return {
496
+ ok: false,
497
+ error: "\"mergeTags\" must be an array."
498
+ };
499
+ const tags = [];
500
+ for (const [index, entry] of value.entries()) {
501
+ if (!isRecord$1(entry) || typeof entry.name !== "string" || entry.name.trim() === "") return {
502
+ error: `"mergeTags[${index}]" must be an object with a non-empty string "name".`,
503
+ ok: false
504
+ };
505
+ if (entry.unsubscribe !== void 0 && typeof entry.unsubscribe !== "boolean") return {
506
+ error: `"mergeTags[${index}].unsubscribe" must be a boolean.`,
507
+ ok: false
508
+ };
509
+ tags.push(entry.unsubscribe === void 0 ? { name: entry.name } : {
510
+ name: entry.name,
511
+ unsubscribe: entry.unsubscribe
512
+ });
513
+ }
514
+ return {
515
+ ok: true,
516
+ value: tags
517
+ };
518
+ };
519
+ const handleListBlockTypes = (args) => {
520
+ const blockTypeArg = parseOptionalString(args, "blockType");
521
+ if (!blockTypeArg.ok) return errorResult(blockTypeArg.error);
522
+ const catalog = buildBlockCatalog(blockTypeArg.value);
523
+ if (blockTypeArg.value !== void 0 && catalog.blockTypes.length === 0) {
524
+ const valid = BLOCK_TYPES.map(({ type }) => type).join(", ");
525
+ return errorResult(`Unknown Block type "${blockTypeArg.value}". Available Block types: ${valid}.`);
526
+ }
527
+ return jsonResult(catalog);
528
+ };
529
+ const validateCreateArgs = (args) => {
530
+ if (args.overwrite !== void 0 && typeof args.overwrite !== "boolean") return errorResult("\"overwrite\" must be a boolean.");
531
+ if (args.blank !== void 0 && typeof args.blank !== "boolean") return errorResult("\"blank\" must be a boolean.");
532
+ if (args.settings !== void 0 && !isRecord$1(args.settings)) return errorResult("\"settings\" must be an object.");
533
+ if (args.style !== void 0 && !isRecord$1(args.style)) return errorResult("\"style\" must be an object.");
534
+ if (args.rows !== void 0 && !Array.isArray(args.rows)) return errorResult("\"rows\" must be an array.");
535
+ return null;
536
+ };
537
+ const applyCreateRows = (initialEditor, rows) => {
538
+ let editor = initialEditor;
539
+ for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
540
+ const rowSpec = rows[rowIndex];
541
+ if (!isRecord$1(rowSpec)) return {
542
+ ok: false,
543
+ result: errorResult(`"rows[${rowIndex}]" must be an object.`)
544
+ };
545
+ if ("layout" in rowSpec) {
546
+ const applied = editor.apply({
547
+ ...rowSpec,
548
+ index: rowIndex,
549
+ type: "insertRow"
550
+ });
551
+ if (!applied.ok) return {
552
+ ok: false,
553
+ result: errorResult(applied.reason, {
554
+ code: applied.code,
555
+ index: rowIndex
556
+ })
557
+ };
558
+ } else {
559
+ const candidate = editor.getDocument();
560
+ const loaded = loadDocument({
561
+ ...candidate,
562
+ rows: [...candidate.rows, rowSpec]
563
+ });
564
+ if (!loaded.ok) return {
565
+ ok: false,
566
+ result: errorResult(loaded.reason, {
567
+ code: "invalid_document",
568
+ index: rowIndex
569
+ })
570
+ };
571
+ editor = createEditor({ document: loaded.document });
572
+ }
573
+ }
574
+ return {
575
+ editor,
576
+ ok: true
577
+ };
578
+ };
579
+ const handleCreateEmail = async (context, args) => {
580
+ const pathArg = parseOptionalString(args, "path");
581
+ if (!pathArg.ok) return errorResult(pathArg.error);
582
+ const argError = validateCreateArgs(args);
583
+ if (argError !== null) return argError;
584
+ const base = createEmail();
585
+ if (args.blank === true || args.rows !== void 0) base.rows = [];
586
+ let editor = createEditor({ document: base });
587
+ if (isRecord$1(args.settings)) {
588
+ const applied = editor.apply({
589
+ settings: args.settings,
590
+ type: "updateEmailSettings"
591
+ });
592
+ if (!applied.ok && applied.code !== "unchanged") return errorResult(applied.reason, { code: applied.code });
593
+ }
594
+ if (isRecord$1(args.style)) {
595
+ const applied = editor.apply({
596
+ style: args.style,
597
+ type: "updateEmailStyle"
598
+ });
599
+ if (!applied.ok && applied.code !== "unchanged") return errorResult(applied.reason, { code: applied.code });
600
+ }
601
+ if (Array.isArray(args.rows)) {
602
+ const builtRows = applyCreateRows(editor, args.rows);
603
+ if (!builtRows.ok) return builtRows.result;
604
+ ({editor} = builtRows);
605
+ }
606
+ const finalLoaded = loadDocument(editor.getDocument());
607
+ if (!finalLoaded.ok) return errorResult(finalLoaded.reason, { code: "invalid_document" });
608
+ const { document } = finalLoaded;
609
+ const summary = summarizeDocument(document);
610
+ if (pathArg.value !== void 0) try {
611
+ const written = await writeWorkspaceFileAtomic(context.root, pathArg.value, `${JSON.stringify(document, null, 2)}\n`, { overwrite: args.overwrite === true });
612
+ return jsonResult({
613
+ document,
614
+ ok: true,
615
+ path: written.relativePath,
616
+ summary
617
+ });
618
+ } catch (error) {
619
+ return errorResult(errorMessage(error), error instanceof WorkspacePathError ? { code: error.code } : {});
620
+ }
621
+ return jsonResult({
622
+ document,
623
+ ok: true,
624
+ summary
625
+ });
626
+ };
627
+ const handleReadEmail = async (context, args) => {
628
+ if (typeof args.path !== "string") return errorResult("\"path\" is required and must be a string.");
629
+ const target = await loadTargetDocument(context, { path: args.path });
630
+ if (!target.ok) return target.result;
631
+ return jsonResult({
632
+ document: target.document,
633
+ path: target.relativePath,
634
+ summary: summarizeDocument(target.document)
635
+ });
636
+ };
637
+ const handleApplyCommands = async (context, args) => {
638
+ if (!Array.isArray(args.commands)) return errorResult("\"commands\" must be an array of Mail Quilt Commands.");
639
+ const target = await loadTargetDocument(context, args);
640
+ if (!target.ok) return target.result;
641
+ if (typeof args.path === "string") try {
642
+ await resolveWorkspaceWritePath(context.root, args.path);
643
+ } catch (error) {
644
+ return errorResult(errorMessage(error), error instanceof WorkspacePathError ? { code: error.code } : {});
645
+ }
646
+ const editor = createEditor({ document: target.document });
647
+ const createdIds = [];
648
+ for (let index = 0; index < args.commands.length; index += 1) {
649
+ const command = args.commands[index];
650
+ const applied = editor.apply(command);
651
+ if (!applied.ok) {
652
+ while (editor.undo());
653
+ return jsonResult({
654
+ code: applied.code,
655
+ index,
656
+ ok: false,
657
+ reason: applied.reason,
658
+ rolledBack: true
659
+ }, true);
660
+ }
661
+ if (applied.createdId !== void 0) createdIds.push(applied.createdId);
662
+ }
663
+ const updated = editor.getDocument();
664
+ const verified = loadDocument(updated);
665
+ if (!verified.ok) return errorResult(`Updated document failed validation: ${verified.reason}`, {
666
+ code: "invalid_document",
667
+ rolledBack: true
668
+ });
669
+ const summary = summarizeDocument(verified.document);
670
+ if (typeof args.path === "string") try {
671
+ const written = await writeWorkspaceFileAtomic(context.root, args.path, `${JSON.stringify(verified.document, null, 2)}\n`, { overwrite: true });
672
+ return jsonResult({
673
+ appliedCount: args.commands.length,
674
+ createdIds,
675
+ ok: true,
676
+ path: written.relativePath,
677
+ summary
678
+ });
679
+ } catch (error) {
680
+ return errorResult(errorMessage(error), error instanceof WorkspacePathError ? { code: error.code } : {});
681
+ }
682
+ return jsonResult({
683
+ appliedCount: args.commands.length,
684
+ createdIds,
685
+ document: verified.document,
686
+ ok: true,
687
+ summary
688
+ });
689
+ };
690
+ const handleRenderHtml = async (context, args) => {
691
+ const socialIconsUrl = parseOptionalString(args, "socialIconsUrl");
692
+ if (!socialIconsUrl.ok) return errorResult(socialIconsUrl.error);
693
+ const target = await loadTargetDocument(context, args);
694
+ if (!target.ok) return target.result;
695
+ try {
696
+ const html = await renderEmail(target.document, socialIconsUrl.value === void 0 ? {} : { socialIconsUrl: socialIconsUrl.value });
697
+ const bytes = Buffer.byteLength(html, "utf-8");
698
+ const gmailClipped = bytes > GMAIL_CLIP_BYTES;
699
+ return jsonResult({
700
+ bytes,
701
+ gmailClipped,
702
+ gmailLimitBytes: GMAIL_CLIP_BYTES,
703
+ gmailStatus: gmailClipped ? "clipped" : "ok",
704
+ html,
705
+ kilobytes: gmailKilobytes(bytes),
706
+ ...target.relativePath === void 0 ? {} : { path: target.relativePath }
707
+ });
708
+ } catch (error) {
709
+ return errorResult(`Failed to render HTML: ${errorMessage(error)}`);
710
+ }
711
+ };
712
+ const handleRenderText = async (context, args) => {
713
+ const target = await loadTargetDocument(context, args);
714
+ if (!target.ok) return target.result;
715
+ try {
716
+ const text = renderText(target.document);
717
+ return jsonResult({
718
+ bytes: Buffer.byteLength(text, "utf-8"),
719
+ ...target.relativePath === void 0 ? {} : { path: target.relativePath },
720
+ text
721
+ });
722
+ } catch (error) {
723
+ return errorResult(`Failed to render plain text: ${errorMessage(error)}`);
724
+ }
725
+ };
726
+ const handleCheckEmail = async (context, args) => {
727
+ const socialIconsUrl = parseOptionalString(args, "socialIconsUrl");
728
+ if (!socialIconsUrl.ok) return errorResult(socialIconsUrl.error);
729
+ const mergeTags = parseMergeTags(args.mergeTags);
730
+ if (!mergeTags.ok) return errorResult(mergeTags.error);
731
+ const target = await loadTargetDocument(context, args);
732
+ if (!target.ok) return target.result;
733
+ try {
734
+ const problems = await checkEmail(target.document, {
735
+ ...mergeTags.value === void 0 ? {} : { mergeTags: mergeTags.value },
736
+ ...socialIconsUrl.value === void 0 ? {} : { socialIconsUrl: socialIconsUrl.value }
737
+ });
738
+ return jsonResult({
739
+ passed: problems.length === 0,
740
+ ...target.relativePath === void 0 ? {} : { path: target.relativePath },
741
+ problemCount: problems.length,
742
+ problems
743
+ });
744
+ } catch (error) {
745
+ return errorResult(`Failed to check email: ${errorMessage(error)}`);
746
+ }
747
+ };
748
+ const handleGetPreviewUrl = async (context, args) => {
749
+ const pathArg = parseOptionalString(args, "path");
750
+ if (!pathArg.ok) return errorResult(pathArg.error);
751
+ let relativePath;
752
+ if (pathArg.value !== void 0) try {
753
+ const resolved = await resolveWorkspaceWritePath(context.root, pathArg.value);
754
+ ({relativePath} = resolved);
755
+ } catch (error) {
756
+ return errorResult(errorMessage(error), error instanceof WorkspacePathError ? { code: error.code } : {});
757
+ }
758
+ const configured = (context.devUrl ?? process.env.MAILQUILT_DEV_URL ?? "").trim();
759
+ if (configured === "") return jsonResult({
760
+ active: false,
761
+ message: "No local mailquilt dev server URL is active. Start one with `mailquilt dev [dir]` (or `npx @mailquilt/cli dev [dir]`) and set MAILQUILT_DEV_URL (for example, http://127.0.0.1:4173).",
762
+ ...relativePath === void 0 ? {} : { path: relativePath },
763
+ url: null
764
+ });
765
+ let parsedUrl;
766
+ try {
767
+ parsedUrl = new URL(configured);
768
+ } catch {
769
+ return errorResult(`Configured dev URL "${configured}" is not a valid URL.`);
770
+ }
771
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") return errorResult(`Configured dev URL "${configured}" must use http: or https:.`);
772
+ if (relativePath !== void 0) parsedUrl.searchParams.set("file", relativePath);
773
+ return jsonResult({
774
+ active: true,
775
+ ...relativePath === void 0 ? {} : { path: relativePath },
776
+ url: parsedUrl.toString()
777
+ });
778
+ };
779
+ /** Returns the live tool definitions dynamically reflecting `@mailquilt/core`. */
780
+ const getToolDefinitions = () => [
781
+ {
782
+ description: "Return the live catalog of Mail Quilt Block types, Row layouts, and JSON Schemas derived directly from @mailquilt/core.",
783
+ inputSchema: {
784
+ additionalProperties: false,
785
+ properties: { blockType: {
786
+ description: "Optional Block type to filter the returned catalog to a single Block type.",
787
+ enum: BLOCK_TYPES.map(({ type }) => type),
788
+ type: "string"
789
+ } },
790
+ type: "object"
791
+ },
792
+ name: "list_block_types"
793
+ },
794
+ {
795
+ description: "Create a new validated Mail Quilt email (BlocksDocument), optionally applying initial settings, Email style, and Rows, and either write it inside the workspace root or return the JSON.",
796
+ inputSchema: {
797
+ additionalProperties: false,
798
+ properties: {
799
+ blank: {
800
+ description: "When true and rows is omitted, create an email with zero Rows instead of the default single-Text Row.",
801
+ type: "boolean"
802
+ },
803
+ overwrite: {
804
+ description: "Allow overwriting an existing file at path (default false).",
805
+ type: "boolean"
806
+ },
807
+ path: {
808
+ description: "Optional path inside the workspace root where the JSON email will be written.",
809
+ type: "string"
810
+ },
811
+ rows: {
812
+ description: "Optional initial Rows, either as insertRow specs ({ layout, props?, columns? }) or full validated Row objects.",
813
+ items: { type: "object" },
814
+ type: "array"
815
+ },
816
+ settings: {
817
+ description: "Optional EmailSettings overrides (width, backgroundColor, fontFamily, preheader, language, style, fonts).",
818
+ type: "object"
819
+ },
820
+ style: {
821
+ description: "Optional EmailStyle overrides.",
822
+ type: "object"
823
+ }
824
+ },
825
+ type: "object"
826
+ },
827
+ name: "create_email"
828
+ },
829
+ {
830
+ description: "Read and validate an email JSON file inside the workspace root via loadDocument(), returning both the document and a concise structural summary of Row, Column, and Block IDs.",
831
+ inputSchema: {
832
+ additionalProperties: false,
833
+ properties: { path: {
834
+ description: "Path to the email JSON file inside the workspace root.",
835
+ type: "string"
836
+ } },
837
+ required: ["path"],
838
+ type: "object"
839
+ },
840
+ name: "read_email"
841
+ },
842
+ {
843
+ description: "Atomically apply an array of Mail Quilt Commands (insertRow, removeRow, moveRow, setRowLayout, updateRowProps, updateColumnProps, insertBlock, insertBlockInNewRow, removeBlock, moveBlock, moveBlockToNewRow, updateBlockProps, updateEmailSettings, updateEmailStyle) to an email file or inline document via createEditor(). Rolls back completely if any Command is refused.",
844
+ inputSchema: {
845
+ additionalProperties: false,
846
+ properties: {
847
+ commands: {
848
+ description: `Ordered list of Mail Quilt Commands to apply atomically. Supported Row layouts: ${ROW_LAYOUTS.join(", ")}. Call list_block_types for live Block types and prop schemas.`,
849
+ items: { type: "object" },
850
+ type: "array"
851
+ },
852
+ document: {
853
+ description: "Inline BlocksDocument to update in memory (mutually exclusive with path).",
854
+ type: "object"
855
+ },
856
+ path: {
857
+ description: "Path to the email JSON file inside the workspace root to update (mutually exclusive with document).",
858
+ type: "string"
859
+ }
860
+ },
861
+ required: ["commands"],
862
+ type: "object"
863
+ },
864
+ name: "apply_commands"
865
+ },
866
+ {
867
+ description: "Render a Mail Quilt email file or inline document to email-client HTML via renderEmail(), returning HTML, UTF-8 byte size, and Gmail 102 KB clipping status.",
868
+ inputSchema: {
869
+ additionalProperties: false,
870
+ properties: {
871
+ document: {
872
+ description: "Inline BlocksDocument to render (mutually exclusive with path).",
873
+ type: "object"
874
+ },
875
+ path: {
876
+ description: "Path to the email JSON file inside the workspace root (mutually exclusive with document).",
877
+ type: "string"
878
+ },
879
+ socialIconsUrl: {
880
+ description: "Optional base URL of a folder hosting Social Block icons instead of jsDelivr.",
881
+ type: "string"
882
+ }
883
+ },
884
+ type: "object"
885
+ },
886
+ name: "render_html"
887
+ },
888
+ {
889
+ description: "Render a Mail Quilt email file or inline document to plain text via renderText().",
890
+ inputSchema: {
891
+ additionalProperties: false,
892
+ properties: {
893
+ document: {
894
+ description: "Inline BlocksDocument to render (mutually exclusive with path).",
895
+ type: "object"
896
+ },
897
+ path: {
898
+ description: "Path to the email JSON file inside the workspace root (mutually exclusive with document).",
899
+ type: "string"
900
+ }
901
+ },
902
+ type: "object"
903
+ },
904
+ name: "render_text"
905
+ },
906
+ {
907
+ description: "Run Mail Quilt's checkEmail() on a file or inline document, returning structured Problems and pass/fail status.",
908
+ inputSchema: {
909
+ additionalProperties: false,
910
+ properties: {
911
+ document: {
912
+ description: "Inline BlocksDocument to check (mutually exclusive with path).",
913
+ type: "object"
914
+ },
915
+ mergeTags: {
916
+ description: "Optional list of Host app Merge Tags ({ name, unsubscribe? }) to check unknown tags and unsubscribe link presence.",
917
+ items: {
918
+ additionalProperties: false,
919
+ properties: {
920
+ name: { type: "string" },
921
+ unsubscribe: { type: "boolean" }
922
+ },
923
+ required: ["name"],
924
+ type: "object"
925
+ },
926
+ type: "array"
927
+ },
928
+ path: {
929
+ description: "Path to the email JSON file inside the workspace root (mutually exclusive with document).",
930
+ type: "string"
931
+ },
932
+ socialIconsUrl: {
933
+ description: "Optional base URL of a folder hosting Social Block icons when measuring rendered HTML.",
934
+ type: "string"
935
+ }
936
+ },
937
+ type: "object"
938
+ },
939
+ name: "check_email"
940
+ },
941
+ {
942
+ description: "Return the active local mailquilt dev preview URL when MAILQUILT_DEV_URL (or a configured dev server URL) is set, or instructions for starting mailquilt dev.",
943
+ inputSchema: {
944
+ additionalProperties: false,
945
+ properties: { path: {
946
+ description: "Optional email file path inside the workspace root to link directly in the dev editor.",
947
+ type: "string"
948
+ } },
949
+ type: "object"
950
+ },
951
+ name: "get_preview_url"
952
+ }
953
+ ];
954
+ new Set(getToolDefinitions().map(({ name }) => name));
955
+ /** Executes a named MCP tool with raw arguments. Returns `null` if unknown. */
956
+ const dispatchTool = async (context, name, rawArgs) => {
957
+ switch (name) {
958
+ case "list_block_types": return handleListBlockTypes(rawArgs);
959
+ case "create_email": return await handleCreateEmail(context, rawArgs);
960
+ case "read_email": return await handleReadEmail(context, rawArgs);
961
+ case "apply_commands": return await handleApplyCommands(context, rawArgs);
962
+ case "render_html": return await handleRenderHtml(context, rawArgs);
963
+ case "render_text": return await handleRenderText(context, rawArgs);
964
+ case "check_email": return await handleCheckEmail(context, rawArgs);
965
+ case "get_preview_url": return await handleGetPreviewUrl(context, rawArgs);
966
+ default: return null;
967
+ }
968
+ };
969
+ // src/server.ts
970
+ const SUPPORTED_PROTOCOL_VERSIONS = [
971
+ "2025-11-25",
972
+ "2025-06-18",
973
+ "2025-03-26",
974
+ "2024-11-05"
975
+ ];
976
+ const DEFAULT_PROTOCOL_VERSION = "2025-03-26";
977
+ const JSON_RPC_PARSE_ERROR = -32700;
978
+ const JSON_RPC_INVALID_REQUEST = -32600;
979
+ const JSON_RPC_METHOD_NOT_FOUND = -32601;
980
+ const JSON_RPC_INVALID_PARAMS = -32602;
981
+ const JSON_RPC_INTERNAL_ERROR = -32603;
982
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
983
+ const isValidId = (value) => value === null || typeof value === "string" || typeof value === "number" && Number.isFinite(value);
984
+ const success = (id, result) => ({
985
+ id,
986
+ jsonrpc: "2.0",
987
+ result
988
+ });
989
+ const failure = (id, code, message) => ({
990
+ error: {
991
+ code,
992
+ message
993
+ },
994
+ id,
995
+ jsonrpc: "2.0"
996
+ });
997
+ const negotiateProtocolVersion = (requested) => {
998
+ if (typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)) return requested;
999
+ return DEFAULT_PROTOCOL_VERSION;
1000
+ };
1001
+ const handleMethod = async (context, id, method, params) => {
1002
+ switch (method) {
1003
+ case "initialize": {
1004
+ const requestedVersion = isRecord(params) ? params.protocolVersion : void 0;
1005
+ return success(id, {
1006
+ capabilities: { tools: { listChanged: false } },
1007
+ instructions: "Use list_block_types to inspect live Mail Quilt Block types, Row layouts, and JSON Schemas. All file operations are restricted to the configured workspace root and validated through loadDocument().",
1008
+ protocolVersion: negotiateProtocolVersion(requestedVersion),
1009
+ serverInfo: {
1010
+ name,
1011
+ version
1012
+ }
1013
+ });
1014
+ }
1015
+ case "ping": return success(id, {});
1016
+ case "tools/list": return success(id, { tools: getToolDefinitions() });
1017
+ case "tools/call": {
1018
+ if (!isRecord(params) || typeof params.name !== "string") return failure(id, JSON_RPC_INVALID_PARAMS, "tools/call requires params.name as a string.");
1019
+ const rawArgs = params.arguments ?? {};
1020
+ if (!isRecord(rawArgs)) return failure(id, JSON_RPC_INVALID_PARAMS, "tools/call params.arguments must be an object.");
1021
+ const result = await dispatchTool(context, params.name, rawArgs);
1022
+ if (result === null) return failure(id, JSON_RPC_INVALID_PARAMS, `Unknown tool: ${params.name}`);
1023
+ return success(id, result);
1024
+ }
1025
+ default: return failure(id, JSON_RPC_METHOD_NOT_FOUND, `Method not found: ${method}`);
1026
+ }
1027
+ };
1028
+ const runSequentialBatch = async (items, index, handleOne, collected) => {
1029
+ if (index >= items.length) return collected;
1030
+ const response = await handleOne(items[index]);
1031
+ if (response !== null) collected.push(response);
1032
+ return await runSequentialBatch(items, index + 1, handleOne, collected);
1033
+ };
1034
+ /**
1035
+ * Creates a Mail Quilt MCP server scoped to `options.root` (default `process.cwd()`).
1036
+ */
1037
+ const createMcpServer = (options = {}) => {
1038
+ const root = canonicalizeRoot(options.root ?? process.cwd());
1039
+ const context = {
1040
+ devUrl: options.devUrl,
1041
+ root
1042
+ };
1043
+ const callTool = async (name, args = {}) => {
1044
+ const result = await dispatchTool(context, name, args);
1045
+ if (result === null) throw new Error(`Unknown tool "${name}".`);
1046
+ return result;
1047
+ };
1048
+ const handleSingleMessage = async (message) => {
1049
+ if (!isRecord(message)) return failure(null, JSON_RPC_INVALID_REQUEST, "Invalid Request");
1050
+ const hasId = Object.hasOwn(message, "id") && message.id !== void 0;
1051
+ const id = hasId && isValidId(message.id) ? message.id : null;
1052
+ if (message.jsonrpc !== "2.0" || typeof message.method !== "string") return hasId ? failure(id, JSON_RPC_INVALID_REQUEST, "Invalid Request") : null;
1053
+ if (!hasId) return null;
1054
+ if (!isValidId(message.id)) return failure(null, JSON_RPC_INVALID_REQUEST, "Invalid Request id");
1055
+ try {
1056
+ return await handleMethod(context, id, message.method, message.params);
1057
+ } catch (error) {
1058
+ const detail = error instanceof Error ? error.message : String(error);
1059
+ return failure(id, JSON_RPC_INTERNAL_ERROR, detail);
1060
+ }
1061
+ };
1062
+ const handleJsonRpcMessage = async (message) => {
1063
+ if (Array.isArray(message)) {
1064
+ if (message.length === 0) return failure(null, JSON_RPC_INVALID_REQUEST, "Invalid Request");
1065
+ const responses = await runSequentialBatch(message, 0, handleSingleMessage, []);
1066
+ return responses.length > 0 ? responses : null;
1067
+ }
1068
+ return await handleSingleMessage(message);
1069
+ };
1070
+ const handleLine = async (line) => {
1071
+ const trimmed = line.trim();
1072
+ if (trimmed === "") return null;
1073
+ let parsed;
1074
+ try {
1075
+ parsed = JSON.parse(trimmed);
1076
+ } catch {
1077
+ return JSON.stringify(failure(null, JSON_RPC_PARSE_ERROR, "Parse error"));
1078
+ }
1079
+ const response = await handleJsonRpcMessage(parsed);
1080
+ return response === null ? null : JSON.stringify(response);
1081
+ };
1082
+ const startStdio = async (input = process.stdin, output = process.stdout) => {
1083
+ const lines = createInterface({
1084
+ crlfDelay: Number.POSITIVE_INFINITY,
1085
+ input
1086
+ });
1087
+ for await (const line of lines) {
1088
+ const response = await handleLine(line);
1089
+ if (response !== null) output.write(`${response}\n`);
1090
+ }
1091
+ };
1092
+ return {
1093
+ callTool,
1094
+ handleJsonRpcMessage,
1095
+ handleLine,
1096
+ listTools: getToolDefinitions,
1097
+ root,
1098
+ startStdio
1099
+ };
1100
+ };
1101
+ /** Starts the Mail Quilt MCP stdio server and resolves once stdin closes. */
1102
+ const startMcpStdioServer = async (options = {}) => {
1103
+ await createMcpServer(options).startStdio(options.input, options.output);
1104
+ };
1105
+ // src/bin.ts
1106
+ const HELP_TEXT = `Usage: mailquilt-mcp [options]
1107
+
1108
+ Start the Mail Quilt Model Context Protocol (MCP) server over stdio.
1109
+
1110
+ Options:
1111
+ --root <dir> Workspace root directory (default: current working directory)
1112
+ --dev-url <url> Active mailquilt dev URL (default: MAILQUILT_DEV_URL)
1113
+ -h, --help Show this help message
1114
+ -v, --version Show package version
1115
+ `;
1116
+ const run = async () => {
1117
+ const { values } = parseArgs({
1118
+ allowPositionals: false,
1119
+ args: process.argv.slice(2),
1120
+ options: {
1121
+ "dev-url": { type: "string" },
1122
+ help: {
1123
+ short: "h",
1124
+ type: "boolean"
1125
+ },
1126
+ root: { type: "string" },
1127
+ version: {
1128
+ short: "v",
1129
+ type: "boolean"
1130
+ }
1131
+ },
1132
+ strict: true
1133
+ });
1134
+ if (values.help) {
1135
+ process.stdout.write(HELP_TEXT);
1136
+ return;
1137
+ }
1138
+ if (values.version) {
1139
+ process.stdout.write(`${version}\n`);
1140
+ return;
1141
+ }
1142
+ await startMcpStdioServer({
1143
+ devUrl: values["dev-url"],
1144
+ root: values.root
1145
+ });
1146
+ };
1147
+ try {
1148
+ await run();
1149
+ } catch (error) {
1150
+ const message = error instanceof Error ? error.message : String(error);
1151
+ process.stderr.write(`mailquilt-mcp: ${message}\n`);
1152
+ process.exitCode = 1;
1153
+ }
1154
+ export {};