@mailquilt/mcp 0.0.0 → 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/src/tools.ts ADDED
@@ -0,0 +1,882 @@
1
+ import {
2
+ BLOCK_TYPES,
3
+ createEditor,
4
+ createEmail,
5
+ loadDocument,
6
+ ROW_LAYOUTS,
7
+ } from "@mailquilt/core";
8
+ import type { BlocksDocument, Command } from "@mailquilt/core";
9
+ import { checkEmail, renderEmail, renderText } from "@mailquilt/renderer";
10
+ import type { CheckEmailOptions } from "@mailquilt/renderer";
11
+ import { GMAIL_CLIP_BYTES, gmailKilobytes } from "@mailquilt/renderer/internal";
12
+
13
+ import { buildBlockCatalog } from "./catalog.js";
14
+ import { summarizeDocument } from "./summary.js";
15
+ import {
16
+ readWorkspaceFile,
17
+ resolveWorkspaceWritePath,
18
+ WorkspacePathError,
19
+ writeWorkspaceFileAtomic,
20
+ } from "./workspace.js";
21
+
22
+ export interface McpToolDefinition {
23
+ readonly name: string;
24
+ readonly description: string;
25
+ readonly inputSchema: Record<string, unknown>;
26
+ }
27
+
28
+ export interface McpToolResult {
29
+ readonly content: readonly [{ readonly type: "text"; readonly text: string }];
30
+ readonly isError?: boolean;
31
+ }
32
+
33
+ export interface ToolContext {
34
+ readonly root: string;
35
+ readonly devUrl?: string | undefined;
36
+ }
37
+
38
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
39
+ typeof value === "object" && value !== null && !Array.isArray(value);
40
+
41
+ const jsonResult = (payload: unknown, isError = false): McpToolResult => ({
42
+ content: [{ text: JSON.stringify(payload, null, 2), type: "text" }],
43
+ ...(isError ? { isError: true } : {}),
44
+ });
45
+
46
+ const errorResult = (message: string, extra: Record<string, unknown> = {}) =>
47
+ jsonResult({ error: message, ok: false, ...extra }, true);
48
+
49
+ const errorMessage = (error: unknown): string =>
50
+ error instanceof Error ? error.message : String(error);
51
+
52
+ const parseOptionalString = (
53
+ args: Record<string, unknown>,
54
+ key: string
55
+ ): { ok: true; value: string | undefined } | { ok: false; error: string } => {
56
+ const value = args[key];
57
+ if (value === undefined) {
58
+ return { ok: true, value: undefined };
59
+ }
60
+ if (typeof value !== "string" || value.trim() === "") {
61
+ return { ok: false, error: `"${key}" must be a non-empty string.` };
62
+ }
63
+ return { ok: true, value };
64
+ };
65
+
66
+ const loadTargetDocument = async (
67
+ context: ToolContext,
68
+ args: Record<string, unknown>
69
+ ): Promise<
70
+ | { ok: true; document: BlocksDocument; relativePath?: string }
71
+ | { ok: false; result: McpToolResult }
72
+ > => {
73
+ const hasPath = args.path !== undefined;
74
+ const hasDocument = args.document !== undefined;
75
+
76
+ if (hasPath === hasDocument) {
77
+ return {
78
+ ok: false,
79
+ result: errorResult(
80
+ 'Provide either "path" (inside the workspace root) or inline "document", not both.'
81
+ ),
82
+ };
83
+ }
84
+
85
+ if (hasPath) {
86
+ if (typeof args.path !== "string") {
87
+ return { ok: false, result: errorResult('"path" must be a string.') };
88
+ }
89
+ let content: string;
90
+ let relativePath: string;
91
+ try {
92
+ const read = await readWorkspaceFile(context.root, args.path);
93
+ ({ content, relativePath } = read);
94
+ } catch (error) {
95
+ return {
96
+ ok: false,
97
+ result: errorResult(
98
+ errorMessage(error),
99
+ error instanceof WorkspacePathError ? { code: error.code } : {}
100
+ ),
101
+ };
102
+ }
103
+
104
+ let parsed: unknown;
105
+ try {
106
+ parsed = JSON.parse(content);
107
+ } catch (error) {
108
+ return {
109
+ ok: false,
110
+ result: errorResult(
111
+ `Invalid JSON in "${relativePath}": ${errorMessage(error)}`,
112
+ { code: "invalid_json", path: relativePath }
113
+ ),
114
+ };
115
+ }
116
+
117
+ const loaded = loadDocument(parsed);
118
+ if (!loaded.ok) {
119
+ return {
120
+ ok: false,
121
+ result: errorResult(
122
+ `Document "${relativePath}" was refused: ${loaded.reason}`,
123
+ {
124
+ code: "invalid_document",
125
+ path: relativePath,
126
+ reason: loaded.reason,
127
+ }
128
+ ),
129
+ };
130
+ }
131
+ return { document: loaded.document, ok: true, relativePath };
132
+ }
133
+
134
+ const loaded = loadDocument(args.document);
135
+ if (!loaded.ok) {
136
+ return {
137
+ ok: false,
138
+ result: errorResult(`Document was refused: ${loaded.reason}`, {
139
+ code: "invalid_document",
140
+ reason: loaded.reason,
141
+ }),
142
+ };
143
+ }
144
+ return { document: loaded.document, ok: true };
145
+ };
146
+
147
+ const parseMergeTags = (
148
+ value: unknown
149
+ ):
150
+ | { ok: true; value: CheckEmailOptions["mergeTags"] }
151
+ | { ok: false; error: string } => {
152
+ if (value === undefined) {
153
+ return { ok: true, value: undefined };
154
+ }
155
+ if (!Array.isArray(value)) {
156
+ return { ok: false, error: '"mergeTags" must be an array.' };
157
+ }
158
+ const tags: { name: string; unsubscribe?: boolean }[] = [];
159
+ for (const [index, entry] of value.entries()) {
160
+ if (
161
+ !isRecord(entry) ||
162
+ typeof entry.name !== "string" ||
163
+ entry.name.trim() === ""
164
+ ) {
165
+ return {
166
+ error: `"mergeTags[${index}]" must be an object with a non-empty string "name".`,
167
+ ok: false,
168
+ };
169
+ }
170
+ if (
171
+ entry.unsubscribe !== undefined &&
172
+ typeof entry.unsubscribe !== "boolean"
173
+ ) {
174
+ return {
175
+ error: `"mergeTags[${index}].unsubscribe" must be a boolean.`,
176
+ ok: false,
177
+ };
178
+ }
179
+ tags.push(
180
+ entry.unsubscribe === undefined
181
+ ? { name: entry.name }
182
+ : { name: entry.name, unsubscribe: entry.unsubscribe }
183
+ );
184
+ }
185
+ return { ok: true, value: tags };
186
+ };
187
+
188
+ const handleListBlockTypes = (args: Record<string, unknown>): McpToolResult => {
189
+ const blockTypeArg = parseOptionalString(args, "blockType");
190
+ if (!blockTypeArg.ok) {
191
+ return errorResult(blockTypeArg.error);
192
+ }
193
+
194
+ const catalog = buildBlockCatalog(blockTypeArg.value);
195
+ if (blockTypeArg.value !== undefined && catalog.blockTypes.length === 0) {
196
+ const valid = BLOCK_TYPES.map(({ type }) => type).join(", ");
197
+ return errorResult(
198
+ `Unknown Block type "${blockTypeArg.value}". Available Block types: ${valid}.`
199
+ );
200
+ }
201
+ return jsonResult(catalog);
202
+ };
203
+
204
+ const validateCreateArgs = (
205
+ args: Record<string, unknown>
206
+ ): McpToolResult | null => {
207
+ if (args.overwrite !== undefined && typeof args.overwrite !== "boolean") {
208
+ return errorResult('"overwrite" must be a boolean.');
209
+ }
210
+ if (args.blank !== undefined && typeof args.blank !== "boolean") {
211
+ return errorResult('"blank" must be a boolean.');
212
+ }
213
+ if (args.settings !== undefined && !isRecord(args.settings)) {
214
+ return errorResult('"settings" must be an object.');
215
+ }
216
+ if (args.style !== undefined && !isRecord(args.style)) {
217
+ return errorResult('"style" must be an object.');
218
+ }
219
+ if (args.rows !== undefined && !Array.isArray(args.rows)) {
220
+ return errorResult('"rows" must be an array.');
221
+ }
222
+ return null;
223
+ };
224
+
225
+ const applyCreateRows = (
226
+ initialEditor: ReturnType<typeof createEditor>,
227
+ rows: readonly unknown[]
228
+ ):
229
+ | { ok: true; editor: ReturnType<typeof createEditor> }
230
+ | { ok: false; result: McpToolResult } => {
231
+ let editor = initialEditor;
232
+ for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {
233
+ const rowSpec: unknown = rows[rowIndex];
234
+ if (!isRecord(rowSpec)) {
235
+ return {
236
+ ok: false,
237
+ result: errorResult(`"rows[${rowIndex}]" must be an object.`),
238
+ };
239
+ }
240
+ if ("layout" in rowSpec) {
241
+ const applied = editor.apply({
242
+ ...rowSpec,
243
+ index: rowIndex,
244
+ type: "insertRow",
245
+ } as Command);
246
+ if (!applied.ok) {
247
+ return {
248
+ ok: false,
249
+ result: errorResult(applied.reason, {
250
+ code: applied.code,
251
+ index: rowIndex,
252
+ }),
253
+ };
254
+ }
255
+ } else {
256
+ const candidate = editor.getDocument();
257
+ const loaded = loadDocument({
258
+ ...candidate,
259
+ rows: [...candidate.rows, rowSpec],
260
+ });
261
+ if (!loaded.ok) {
262
+ return {
263
+ ok: false,
264
+ result: errorResult(loaded.reason, {
265
+ code: "invalid_document",
266
+ index: rowIndex,
267
+ }),
268
+ };
269
+ }
270
+ editor = createEditor({ document: loaded.document });
271
+ }
272
+ }
273
+ return { editor, ok: true };
274
+ };
275
+
276
+ const handleCreateEmail = async (
277
+ context: ToolContext,
278
+ args: Record<string, unknown>
279
+ ): Promise<McpToolResult> => {
280
+ const pathArg = parseOptionalString(args, "path");
281
+ if (!pathArg.ok) {
282
+ return errorResult(pathArg.error);
283
+ }
284
+ const argError = validateCreateArgs(args);
285
+ if (argError !== null) {
286
+ return argError;
287
+ }
288
+
289
+ const base = createEmail();
290
+ if (args.blank === true || args.rows !== undefined) {
291
+ base.rows = [];
292
+ }
293
+
294
+ let editor = createEditor({ document: base });
295
+
296
+ if (isRecord(args.settings)) {
297
+ const applied = editor.apply({
298
+ settings: args.settings,
299
+ type: "updateEmailSettings",
300
+ });
301
+ if (!applied.ok && applied.code !== "unchanged") {
302
+ return errorResult(applied.reason, { code: applied.code });
303
+ }
304
+ }
305
+
306
+ if (isRecord(args.style)) {
307
+ const applied = editor.apply({
308
+ style: args.style,
309
+ type: "updateEmailStyle",
310
+ });
311
+ if (!applied.ok && applied.code !== "unchanged") {
312
+ return errorResult(applied.reason, { code: applied.code });
313
+ }
314
+ }
315
+
316
+ if (Array.isArray(args.rows)) {
317
+ const builtRows = applyCreateRows(editor, args.rows);
318
+ if (!builtRows.ok) {
319
+ return builtRows.result;
320
+ }
321
+ ({ editor } = builtRows);
322
+ }
323
+
324
+ const finalLoaded = loadDocument(editor.getDocument());
325
+ if (!finalLoaded.ok) {
326
+ return errorResult(finalLoaded.reason, { code: "invalid_document" });
327
+ }
328
+
329
+ const { document } = finalLoaded;
330
+ const summary = summarizeDocument(document);
331
+
332
+ if (pathArg.value !== undefined) {
333
+ try {
334
+ const written = await writeWorkspaceFileAtomic(
335
+ context.root,
336
+ pathArg.value,
337
+ `${JSON.stringify(document, null, 2)}\n`,
338
+ { overwrite: args.overwrite === true }
339
+ );
340
+ return jsonResult({
341
+ document,
342
+ ok: true,
343
+ path: written.relativePath,
344
+ summary,
345
+ });
346
+ } catch (error) {
347
+ return errorResult(
348
+ errorMessage(error),
349
+ error instanceof WorkspacePathError ? { code: error.code } : {}
350
+ );
351
+ }
352
+ }
353
+
354
+ return jsonResult({ document, ok: true, summary });
355
+ };
356
+
357
+ const handleReadEmail = async (
358
+ context: ToolContext,
359
+ args: Record<string, unknown>
360
+ ): Promise<McpToolResult> => {
361
+ if (typeof args.path !== "string") {
362
+ return errorResult('"path" is required and must be a string.');
363
+ }
364
+ const target = await loadTargetDocument(context, { path: args.path });
365
+ if (!target.ok) {
366
+ return target.result;
367
+ }
368
+ return jsonResult({
369
+ document: target.document,
370
+ path: target.relativePath,
371
+ summary: summarizeDocument(target.document),
372
+ });
373
+ };
374
+
375
+ const handleApplyCommands = async (
376
+ context: ToolContext,
377
+ args: Record<string, unknown>
378
+ ): Promise<McpToolResult> => {
379
+ if (!Array.isArray(args.commands)) {
380
+ return errorResult('"commands" must be an array of Mail Quilt Commands.');
381
+ }
382
+
383
+ const target = await loadTargetDocument(context, args);
384
+ if (!target.ok) {
385
+ return target.result;
386
+ }
387
+
388
+ if (typeof args.path === "string") {
389
+ try {
390
+ await resolveWorkspaceWritePath(context.root, args.path);
391
+ } catch (error) {
392
+ return errorResult(
393
+ errorMessage(error),
394
+ error instanceof WorkspacePathError ? { code: error.code } : {}
395
+ );
396
+ }
397
+ }
398
+
399
+ const editor = createEditor({ document: target.document });
400
+ const createdIds: string[] = [];
401
+
402
+ for (let index = 0; index < args.commands.length; index += 1) {
403
+ const command: unknown = args.commands[index];
404
+ const applied = editor.apply(command as Command);
405
+ if (!applied.ok) {
406
+ // Roll back completely: discard in-memory mutations and leave any file
407
+ // on disk untouched.
408
+ while (editor.undo()) {
409
+ // Rewind applied steps before discarding.
410
+ }
411
+ return jsonResult(
412
+ {
413
+ code: applied.code,
414
+ index,
415
+ ok: false,
416
+ reason: applied.reason,
417
+ rolledBack: true,
418
+ },
419
+ true
420
+ );
421
+ }
422
+ if (applied.createdId !== undefined) {
423
+ createdIds.push(applied.createdId);
424
+ }
425
+ }
426
+
427
+ const updated = editor.getDocument();
428
+ const verified = loadDocument(updated);
429
+ if (!verified.ok) {
430
+ return errorResult(
431
+ `Updated document failed validation: ${verified.reason}`,
432
+ { code: "invalid_document", rolledBack: true }
433
+ );
434
+ }
435
+
436
+ const summary = summarizeDocument(verified.document);
437
+
438
+ if (typeof args.path === "string") {
439
+ try {
440
+ const written = await writeWorkspaceFileAtomic(
441
+ context.root,
442
+ args.path,
443
+ `${JSON.stringify(verified.document, null, 2)}\n`,
444
+ { overwrite: true }
445
+ );
446
+ return jsonResult({
447
+ appliedCount: args.commands.length,
448
+ createdIds,
449
+ ok: true,
450
+ path: written.relativePath,
451
+ summary,
452
+ });
453
+ } catch (error) {
454
+ return errorResult(
455
+ errorMessage(error),
456
+ error instanceof WorkspacePathError ? { code: error.code } : {}
457
+ );
458
+ }
459
+ }
460
+
461
+ return jsonResult({
462
+ appliedCount: args.commands.length,
463
+ createdIds,
464
+ document: verified.document,
465
+ ok: true,
466
+ summary,
467
+ });
468
+ };
469
+
470
+ const handleRenderHtml = async (
471
+ context: ToolContext,
472
+ args: Record<string, unknown>
473
+ ): Promise<McpToolResult> => {
474
+ const socialIconsUrl = parseOptionalString(args, "socialIconsUrl");
475
+ if (!socialIconsUrl.ok) {
476
+ return errorResult(socialIconsUrl.error);
477
+ }
478
+
479
+ const target = await loadTargetDocument(context, args);
480
+ if (!target.ok) {
481
+ return target.result;
482
+ }
483
+
484
+ try {
485
+ const html = await renderEmail(
486
+ target.document,
487
+ socialIconsUrl.value === undefined
488
+ ? {}
489
+ : { socialIconsUrl: socialIconsUrl.value }
490
+ );
491
+ const bytes = Buffer.byteLength(html, "utf-8");
492
+ const gmailClipped = bytes > GMAIL_CLIP_BYTES;
493
+ return jsonResult({
494
+ bytes,
495
+ gmailClipped,
496
+ gmailLimitBytes: GMAIL_CLIP_BYTES,
497
+ gmailStatus: gmailClipped ? "clipped" : "ok",
498
+ html,
499
+ kilobytes: gmailKilobytes(bytes),
500
+ ...(target.relativePath === undefined
501
+ ? {}
502
+ : { path: target.relativePath }),
503
+ });
504
+ } catch (error) {
505
+ return errorResult(`Failed to render HTML: ${errorMessage(error)}`);
506
+ }
507
+ };
508
+
509
+ const handleRenderText = async (
510
+ context: ToolContext,
511
+ args: Record<string, unknown>
512
+ ): Promise<McpToolResult> => {
513
+ const target = await loadTargetDocument(context, args);
514
+ if (!target.ok) {
515
+ return target.result;
516
+ }
517
+
518
+ try {
519
+ const text = renderText(target.document);
520
+ return jsonResult({
521
+ bytes: Buffer.byteLength(text, "utf-8"),
522
+ ...(target.relativePath === undefined
523
+ ? {}
524
+ : { path: target.relativePath }),
525
+ text,
526
+ });
527
+ } catch (error) {
528
+ return errorResult(`Failed to render plain text: ${errorMessage(error)}`);
529
+ }
530
+ };
531
+
532
+ const handleCheckEmail = async (
533
+ context: ToolContext,
534
+ args: Record<string, unknown>
535
+ ): Promise<McpToolResult> => {
536
+ const socialIconsUrl = parseOptionalString(args, "socialIconsUrl");
537
+ if (!socialIconsUrl.ok) {
538
+ return errorResult(socialIconsUrl.error);
539
+ }
540
+ const mergeTags = parseMergeTags(args.mergeTags);
541
+ if (!mergeTags.ok) {
542
+ return errorResult(mergeTags.error);
543
+ }
544
+
545
+ const target = await loadTargetDocument(context, args);
546
+ if (!target.ok) {
547
+ return target.result;
548
+ }
549
+
550
+ try {
551
+ const problems = await checkEmail(target.document, {
552
+ ...(mergeTags.value === undefined ? {} : { mergeTags: mergeTags.value }),
553
+ ...(socialIconsUrl.value === undefined
554
+ ? {}
555
+ : { socialIconsUrl: socialIconsUrl.value }),
556
+ });
557
+ return jsonResult({
558
+ passed: problems.length === 0,
559
+ ...(target.relativePath === undefined
560
+ ? {}
561
+ : { path: target.relativePath }),
562
+ problemCount: problems.length,
563
+ problems,
564
+ });
565
+ } catch (error) {
566
+ return errorResult(`Failed to check email: ${errorMessage(error)}`);
567
+ }
568
+ };
569
+
570
+ const handleGetPreviewUrl = async (
571
+ context: ToolContext,
572
+ args: Record<string, unknown>
573
+ ): Promise<McpToolResult> => {
574
+ const pathArg = parseOptionalString(args, "path");
575
+ if (!pathArg.ok) {
576
+ return errorResult(pathArg.error);
577
+ }
578
+
579
+ let relativePath: string | undefined;
580
+ if (pathArg.value !== undefined) {
581
+ try {
582
+ const resolved = await resolveWorkspaceWritePath(
583
+ context.root,
584
+ pathArg.value
585
+ );
586
+ ({ relativePath } = resolved);
587
+ } catch (error) {
588
+ return errorResult(
589
+ errorMessage(error),
590
+ error instanceof WorkspacePathError ? { code: error.code } : {}
591
+ );
592
+ }
593
+ }
594
+
595
+ const configured = (
596
+ context.devUrl ??
597
+ process.env.MAILQUILT_DEV_URL ??
598
+ ""
599
+ ).trim();
600
+ if (configured === "") {
601
+ return jsonResult({
602
+ active: false,
603
+ message:
604
+ "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).",
605
+ ...(relativePath === undefined ? {} : { path: relativePath }),
606
+ url: null,
607
+ });
608
+ }
609
+
610
+ let parsedUrl: URL;
611
+ try {
612
+ parsedUrl = new URL(configured);
613
+ } catch {
614
+ return errorResult(
615
+ `Configured dev URL "${configured}" is not a valid URL.`
616
+ );
617
+ }
618
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
619
+ return errorResult(
620
+ `Configured dev URL "${configured}" must use http: or https:.`
621
+ );
622
+ }
623
+
624
+ if (relativePath !== undefined) {
625
+ parsedUrl.searchParams.set("file", relativePath);
626
+ }
627
+
628
+ return jsonResult({
629
+ active: true,
630
+ ...(relativePath === undefined ? {} : { path: relativePath }),
631
+ url: parsedUrl.toString(),
632
+ });
633
+ };
634
+
635
+ /** Returns the live tool definitions dynamically reflecting `@mailquilt/core`. */
636
+ export const getToolDefinitions = (): readonly McpToolDefinition[] => [
637
+ {
638
+ description:
639
+ "Return the live catalog of Mail Quilt Block types, Row layouts, and JSON Schemas derived directly from @mailquilt/core.",
640
+ inputSchema: {
641
+ additionalProperties: false,
642
+ properties: {
643
+ blockType: {
644
+ description:
645
+ "Optional Block type to filter the returned catalog to a single Block type.",
646
+ enum: BLOCK_TYPES.map(({ type }) => type),
647
+ type: "string",
648
+ },
649
+ },
650
+ type: "object",
651
+ },
652
+ name: "list_block_types",
653
+ },
654
+ {
655
+ description:
656
+ "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.",
657
+ inputSchema: {
658
+ additionalProperties: false,
659
+ properties: {
660
+ blank: {
661
+ description:
662
+ "When true and rows is omitted, create an email with zero Rows instead of the default single-Text Row.",
663
+ type: "boolean",
664
+ },
665
+ overwrite: {
666
+ description:
667
+ "Allow overwriting an existing file at path (default false).",
668
+ type: "boolean",
669
+ },
670
+ path: {
671
+ description:
672
+ "Optional path inside the workspace root where the JSON email will be written.",
673
+ type: "string",
674
+ },
675
+ rows: {
676
+ description:
677
+ "Optional initial Rows, either as insertRow specs ({ layout, props?, columns? }) or full validated Row objects.",
678
+ items: { type: "object" },
679
+ type: "array",
680
+ },
681
+ settings: {
682
+ description:
683
+ "Optional EmailSettings overrides (width, backgroundColor, fontFamily, preheader, language, style, fonts).",
684
+ type: "object",
685
+ },
686
+ style: {
687
+ description: "Optional EmailStyle overrides.",
688
+ type: "object",
689
+ },
690
+ },
691
+ type: "object",
692
+ },
693
+ name: "create_email",
694
+ },
695
+ {
696
+ description:
697
+ "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.",
698
+ inputSchema: {
699
+ additionalProperties: false,
700
+ properties: {
701
+ path: {
702
+ description: "Path to the email JSON file inside the workspace root.",
703
+ type: "string",
704
+ },
705
+ },
706
+ required: ["path"],
707
+ type: "object",
708
+ },
709
+ name: "read_email",
710
+ },
711
+ {
712
+ description:
713
+ "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.",
714
+ inputSchema: {
715
+ additionalProperties: false,
716
+ properties: {
717
+ commands: {
718
+ 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.`,
719
+ items: { type: "object" },
720
+ type: "array",
721
+ },
722
+ document: {
723
+ description:
724
+ "Inline BlocksDocument to update in memory (mutually exclusive with path).",
725
+ type: "object",
726
+ },
727
+ path: {
728
+ description:
729
+ "Path to the email JSON file inside the workspace root to update (mutually exclusive with document).",
730
+ type: "string",
731
+ },
732
+ },
733
+ required: ["commands"],
734
+ type: "object",
735
+ },
736
+ name: "apply_commands",
737
+ },
738
+ {
739
+ description:
740
+ "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.",
741
+ inputSchema: {
742
+ additionalProperties: false,
743
+ properties: {
744
+ document: {
745
+ description:
746
+ "Inline BlocksDocument to render (mutually exclusive with path).",
747
+ type: "object",
748
+ },
749
+ path: {
750
+ description:
751
+ "Path to the email JSON file inside the workspace root (mutually exclusive with document).",
752
+ type: "string",
753
+ },
754
+ socialIconsUrl: {
755
+ description:
756
+ "Optional base URL of a folder hosting Social Block icons instead of jsDelivr.",
757
+ type: "string",
758
+ },
759
+ },
760
+ type: "object",
761
+ },
762
+ name: "render_html",
763
+ },
764
+ {
765
+ description:
766
+ "Render a Mail Quilt email file or inline document to plain text via renderText().",
767
+ inputSchema: {
768
+ additionalProperties: false,
769
+ properties: {
770
+ document: {
771
+ description:
772
+ "Inline BlocksDocument to render (mutually exclusive with path).",
773
+ type: "object",
774
+ },
775
+ path: {
776
+ description:
777
+ "Path to the email JSON file inside the workspace root (mutually exclusive with document).",
778
+ type: "string",
779
+ },
780
+ },
781
+ type: "object",
782
+ },
783
+ name: "render_text",
784
+ },
785
+ {
786
+ description:
787
+ "Run Mail Quilt's checkEmail() on a file or inline document, returning structured Problems and pass/fail status.",
788
+ inputSchema: {
789
+ additionalProperties: false,
790
+ properties: {
791
+ document: {
792
+ description:
793
+ "Inline BlocksDocument to check (mutually exclusive with path).",
794
+ type: "object",
795
+ },
796
+ mergeTags: {
797
+ description:
798
+ "Optional list of Host app Merge Tags ({ name, unsubscribe? }) to check unknown tags and unsubscribe link presence.",
799
+ items: {
800
+ additionalProperties: false,
801
+ properties: {
802
+ name: { type: "string" },
803
+ unsubscribe: { type: "boolean" },
804
+ },
805
+ required: ["name"],
806
+ type: "object",
807
+ },
808
+ type: "array",
809
+ },
810
+ path: {
811
+ description:
812
+ "Path to the email JSON file inside the workspace root (mutually exclusive with document).",
813
+ type: "string",
814
+ },
815
+ socialIconsUrl: {
816
+ description:
817
+ "Optional base URL of a folder hosting Social Block icons when measuring rendered HTML.",
818
+ type: "string",
819
+ },
820
+ },
821
+ type: "object",
822
+ },
823
+ name: "check_email",
824
+ },
825
+ {
826
+ description:
827
+ "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.",
828
+ inputSchema: {
829
+ additionalProperties: false,
830
+ properties: {
831
+ path: {
832
+ description:
833
+ "Optional email file path inside the workspace root to link directly in the dev editor.",
834
+ type: "string",
835
+ },
836
+ },
837
+ type: "object",
838
+ },
839
+ name: "get_preview_url",
840
+ },
841
+ ];
842
+
843
+ export const TOOL_NAMES: ReadonlySet<string> = new Set(
844
+ getToolDefinitions().map(({ name }) => name)
845
+ );
846
+
847
+ /** Executes a named MCP tool with raw arguments. Returns `null` if unknown. */
848
+ export const dispatchTool = async (
849
+ context: ToolContext,
850
+ name: string,
851
+ rawArgs: Record<string, unknown>
852
+ ): Promise<McpToolResult | null> => {
853
+ switch (name) {
854
+ case "list_block_types": {
855
+ return handleListBlockTypes(rawArgs);
856
+ }
857
+ case "create_email": {
858
+ return await handleCreateEmail(context, rawArgs);
859
+ }
860
+ case "read_email": {
861
+ return await handleReadEmail(context, rawArgs);
862
+ }
863
+ case "apply_commands": {
864
+ return await handleApplyCommands(context, rawArgs);
865
+ }
866
+ case "render_html": {
867
+ return await handleRenderHtml(context, rawArgs);
868
+ }
869
+ case "render_text": {
870
+ return await handleRenderText(context, rawArgs);
871
+ }
872
+ case "check_email": {
873
+ return await handleCheckEmail(context, rawArgs);
874
+ }
875
+ case "get_preview_url": {
876
+ return await handleGetPreviewUrl(context, rawArgs);
877
+ }
878
+ default: {
879
+ return null;
880
+ }
881
+ }
882
+ };