@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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["isRecord","isRecord","packageJson.name","packageJson.version"],"sources":["../src/catalog.ts","../package.json","../src/summary.ts","../src/workspace.ts","../src/tools.ts","../src/server.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\n\nimport { BLOCK_TYPES, ROW_LAYOUTS } from \"@mailquilt/core\";\nimport type { BlockType, RowLayout } from \"@mailquilt/core\";\n\nexport type JsonSchemaObject = Record<string, unknown>;\n\nexport interface BlockTypeCatalogEntry {\n readonly type: BlockType | string;\n readonly label: string;\n readonly requiredProps: readonly string[];\n readonly propNames: readonly string[];\n readonly propsSchema: JsonSchemaObject | null;\n}\n\nexport interface BlockCatalog {\n readonly documentVersion: number | null;\n readonly schemaId: string | null;\n readonly rowLayouts: readonly RowLayout[];\n readonly blockTypes: readonly BlockTypeCatalogEntry[];\n readonly rowPropsSchema: JsonSchemaObject | null;\n readonly columnPropsSchema: JsonSchemaObject | null;\n readonly settingsSchema: JsonSchemaObject | null;\n}\n\nconst require = createRequire(import.meta.url);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** Loads the live JSON Schema published by `@mailquilt/core/schema.json`. */\nexport const loadCoreJsonSchema = (): JsonSchemaObject => {\n const schemaPath = require.resolve(\"@mailquilt/core/schema.json\");\n const raw = readFileSync(schemaPath, \"utf-8\");\n const parsed: unknown = JSON.parse(raw);\n if (!isRecord(parsed)) {\n throw new Error(\"@mailquilt/core/schema.json did not export an object.\");\n }\n return parsed;\n};\n\nconst getNestedRecord = (\n root: Record<string, unknown> | undefined,\n keys: readonly string[]\n): Record<string, unknown> | undefined => {\n let cursor: unknown = root;\n for (const key of keys) {\n if (!isRecord(cursor)) {\n return undefined;\n }\n cursor = cursor[key];\n }\n return isRecord(cursor) ? cursor : undefined;\n};\n\nconst extractBlockSchemas = (\n schema: JsonSchemaObject\n): Map<string, JsonSchemaObject> => {\n const result = new Map<string, JsonSchemaObject>();\n const blockItems = getNestedRecord(schema, [\n \"properties\",\n \"rows\",\n \"items\",\n \"properties\",\n \"columns\",\n \"items\",\n \"properties\",\n \"blocks\",\n \"items\",\n ]);\n const variants = blockItems?.oneOf;\n if (!Array.isArray(variants)) {\n return result;\n }\n\n for (const variant of variants) {\n if (!isRecord(variant) || !isRecord(variant.properties)) {\n continue;\n }\n const typeSchema = variant.properties.type;\n const propsSchema = variant.properties.props;\n if (\n isRecord(typeSchema) &&\n typeof typeSchema.const === \"string\" &&\n isRecord(propsSchema)\n ) {\n result.set(typeSchema.const, propsSchema);\n }\n }\n\n return result;\n};\n\nconst stringArray = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((item): item is string => typeof item === \"string\")\n : [];\n\n/**\n * Builds the live Block, Row layout, and JSON Schema catalog directly from\n * `@mailquilt/core` (`BLOCK_TYPES`, `ROW_LAYOUTS`, `@mailquilt/core/schema.json`).\n */\nexport const buildBlockCatalog = (filterBlockType?: string): BlockCatalog => {\n const schema = loadCoreJsonSchema();\n const blockSchemas = extractBlockSchemas(schema);\n\n const versionSchema = getNestedRecord(schema, [\"properties\", \"version\"]);\n const documentVersion =\n typeof versionSchema?.const === \"number\" ? versionSchema.const : null;\n const schemaId = typeof schema.$id === \"string\" ? schema.$id : null;\n\n const allEntries: BlockTypeCatalogEntry[] = BLOCK_TYPES.map(\n ({ label, type }) => {\n const propsSchema = blockSchemas.get(type) ?? null;\n const propProperties =\n propsSchema && isRecord(propsSchema.properties)\n ? Object.keys(propsSchema.properties)\n : [];\n const requiredProps = propsSchema\n ? stringArray(propsSchema.required)\n : [];\n return {\n label,\n propNames: propProperties,\n propsSchema,\n requiredProps,\n type,\n };\n }\n );\n\n // Also surface any extra block types present in schema.json even if not yet\n // reflected in BLOCK_TYPES.\n const knownTypes = new Set<string>(allEntries.map(({ type }) => type));\n for (const [type, propsSchema] of blockSchemas.entries()) {\n if (knownTypes.has(type)) {\n continue;\n }\n const propProperties = isRecord(propsSchema.properties)\n ? Object.keys(propsSchema.properties)\n : [];\n allEntries.push({\n label: type,\n propNames: propProperties,\n propsSchema,\n requiredProps: stringArray(propsSchema.required),\n type,\n });\n }\n\n const blockTypes =\n filterBlockType === undefined\n ? allEntries\n : allEntries.filter(({ type }) => type === filterBlockType);\n\n const rowPropsSchema =\n getNestedRecord(schema, [\n \"properties\",\n \"rows\",\n \"items\",\n \"properties\",\n \"props\",\n ]) ?? null;\n const columnPropsSchema =\n getNestedRecord(schema, [\n \"properties\",\n \"rows\",\n \"items\",\n \"properties\",\n \"columns\",\n \"items\",\n \"properties\",\n \"props\",\n ]) ?? null;\n const settingsSchema =\n getNestedRecord(schema, [\"properties\", \"settings\"]) ?? null;\n\n return {\n blockTypes,\n columnPropsSchema,\n documentVersion,\n rowLayouts: [...ROW_LAYOUTS],\n rowPropsSchema,\n schemaId,\n settingsSchema,\n };\n};\n","","import type { Block, BlocksDocument } from \"@mailquilt/core\";\nimport { rowLayoutOf } from \"@mailquilt/core/internal\";\n\nexport interface BlockSummary {\n readonly id: string;\n readonly index: number;\n readonly type: Block[\"type\"];\n readonly preview?: string;\n}\n\nexport interface ColumnSummary {\n readonly id: string;\n readonly index: number;\n readonly width: number;\n readonly blockCount: number;\n readonly blocks: readonly BlockSummary[];\n}\n\nexport interface RowSummary {\n readonly id: string;\n readonly index: number;\n readonly layout?: string;\n readonly columnCount: number;\n readonly columns: readonly ColumnSummary[];\n}\n\nexport interface DocumentSummary {\n readonly version: number;\n readonly settings: {\n readonly width: number;\n readonly backgroundColor: string;\n readonly fontFamily: string;\n readonly preheader?: string;\n readonly language?: string;\n readonly hasStyle: boolean;\n };\n readonly rowCount: number;\n readonly blockCount: number;\n readonly rows: readonly RowSummary[];\n}\n\nconst MAX_PREVIEW_LENGTH = 80;\n\nconst truncate = (value: string): string => {\n const collapsed = value.replaceAll(/\\s+/gu, \" \").trim();\n if (collapsed.length <= MAX_PREVIEW_LENGTH) {\n return collapsed;\n }\n return `${collapsed.slice(0, MAX_PREVIEW_LENGTH - 1)}…`;\n};\n\nconst extractRichTextSnippet = (node: unknown): string => {\n if (typeof node !== \"object\" || node === null) {\n return \"\";\n }\n const record = node as Record<string, unknown>;\n if (record.type === \"text\" && typeof record.text === \"string\") {\n return record.text;\n }\n if (record.type === \"mergeTag\") {\n const attrs = record.attrs as { name?: unknown } | undefined;\n return typeof attrs?.name === \"string\" ? `{{${attrs.name}}}` : \"\";\n }\n if (record.type === \"hardBreak\") {\n return \" \";\n }\n if (Array.isArray(record.content)) {\n return record.content\n .map((child) => extractRichTextSnippet(child))\n .filter((part) => part !== \"\")\n .join(\" \");\n }\n return \"\";\n};\n\nconst summarizeBlockPreview = (block: Block): string | undefined => {\n const props = block.props as Record<string, unknown>;\n if (\"content\" in props) {\n const snippet = truncate(extractRichTextSnippet(props.content));\n if (snippet !== \"\") {\n return snippet;\n }\n }\n if (typeof props.label === \"string\" && props.label.trim() !== \"\") {\n return truncate(props.label);\n }\n if (typeof props.alt === \"string\" && props.alt.trim() !== \"\") {\n return truncate(props.alt);\n }\n if (typeof props.src === \"string\" && props.src.trim() !== \"\") {\n return truncate(props.src);\n }\n if (typeof props.url === \"string\" && props.url.trim() !== \"\") {\n return truncate(props.url);\n }\n if (Array.isArray(props.links)) {\n const items = props.links\n .map((item) => {\n if (typeof item !== \"object\" || item === null) {\n return \"\";\n }\n const entry = item as Record<string, unknown>;\n if (typeof entry.label === \"string\" && entry.label.trim() !== \"\") {\n return entry.label.trim();\n }\n if (typeof entry.network === \"string\") {\n return entry.network;\n }\n return \"\";\n })\n .filter((part) => part !== \"\");\n if (items.length > 0) {\n return truncate(items.join(\", \"));\n }\n }\n if (typeof props.height === \"number\") {\n return `${props.height}px`;\n }\n if (typeof props.thickness === \"number\") {\n return `${props.thickness}px`;\n }\n return undefined;\n};\n\n/**\n * Produces a concise structural outline of an email (Rows, Columns, Blocks and\n * their IDs) so agents can target Commands without scanning full ProseMirror JSON.\n */\nexport const summarizeDocument = (\n document: BlocksDocument\n): DocumentSummary => {\n let blockCount = 0;\n const rows: RowSummary[] = document.rows.map((row, rowIndex) => {\n const layout = rowLayoutOf(row);\n const columns: ColumnSummary[] = row.columns.map((column, columnIndex) => {\n const blocks: BlockSummary[] = column.blocks.map((block, blockIndex) => {\n blockCount += 1;\n const preview = summarizeBlockPreview(block);\n return preview === undefined\n ? { id: block.id, index: blockIndex, type: block.type }\n : { id: block.id, index: blockIndex, preview, type: block.type };\n });\n return {\n blockCount: blocks.length,\n blocks,\n id: column.id,\n index: columnIndex,\n width: column.width,\n };\n });\n return {\n columnCount: columns.length,\n columns,\n id: row.id,\n index: rowIndex,\n ...(layout === undefined ? {} : { layout }),\n };\n });\n\n const { settings } = document;\n return {\n blockCount,\n rowCount: rows.length,\n rows,\n settings: {\n backgroundColor: settings.backgroundColor,\n fontFamily: settings.fontFamily,\n hasStyle: settings.style !== undefined,\n ...(settings.language === undefined\n ? {}\n : { language: settings.language }),\n ...(settings.preheader === undefined\n ? {}\n : { preheader: settings.preheader }),\n width: settings.width,\n },\n version: document.version,\n };\n};\n","import { randomBytes } from \"node:crypto\";\nimport { realpathSync } from \"node:fs\";\nimport {\n lstat,\n mkdir,\n readFile,\n realpath,\n rename,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/** Error thrown when a path resolves outside the configured workspace root. */\nexport class WorkspacePathError extends Error {\n readonly code: \"invalid_path\" | \"not_a_file\" | \"not_found\" | \"outside_root\";\n\n constructor(\n code: \"invalid_path\" | \"not_a_file\" | \"not_found\" | \"outside_root\",\n message: string\n ) {\n super(message);\n this.name = \"WorkspacePathError\";\n this.code = code;\n }\n}\n\nexport interface ResolvedWorkspacePath {\n /** Absolute, symlink-verified path on disk. */\n readonly absolutePath: string;\n /** Normalized POSIX-style path relative to the workspace root. */\n readonly relativePath: string;\n}\n\nconst isErrnoException = (error: unknown): error is NodeJS.ErrnoException =>\n typeof error === \"object\" && error !== null && \"code\" in error;\n\n/**\n * Resolves the workspace root directory to a canonical realpath when it exists,\n * or resolves its deepest existing ancestor when the directory is not yet created.\n */\nexport const canonicalizeRoot = (root: string): string => {\n const absolute = path.resolve(root);\n try {\n return realpathSync(absolute);\n } catch (error) {\n if (!isErrnoException(error) || error.code !== \"ENOENT\") {\n throw error;\n }\n }\n const missing: string[] = [];\n let cursor = absolute;\n while (true) {\n const parent = path.dirname(cursor);\n if (parent === cursor) {\n return absolute;\n }\n missing.unshift(path.basename(cursor));\n cursor = parent;\n try {\n return path.join(realpathSync(cursor), ...missing);\n } catch (error) {\n if (!isErrnoException(error) || error.code !== \"ENOENT\") {\n throw error;\n }\n }\n }\n};\n\n/** Returns true when `target` is strictly inside `root` (never equal to `root`). */\nconst isStrictlyInsideRoot = (root: string, target: string): boolean => {\n const relative = path.relative(root, target);\n return (\n relative !== \"\" &&\n relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative)\n );\n};\n\n/** Returns true when `target` is equal to or inside `root`. */\nconst isWithinRoot = (root: string, target: string): boolean => {\n const relative = path.relative(root, target);\n return (\n relative === \"\" ||\n (relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative))\n );\n};\n\nconst toPosixRelative = (root: string, target: string): string =>\n path.relative(root, target).split(path.sep).join(\"/\");\n\nconst validateCandidate = (\n canonicalRoot: string,\n inputPath: string\n): { candidate: string; lexicalRelative: string } => {\n if (typeof inputPath !== \"string\" || inputPath.trim() === \"\") {\n throw new WorkspacePathError(\n \"invalid_path\",\n \"Path must be a non-empty string.\"\n );\n }\n if (inputPath.includes(\"\\0\")) {\n throw new WorkspacePathError(\n \"invalid_path\",\n \"Path must not contain null bytes.\"\n );\n }\n const candidate = path.resolve(canonicalRoot, inputPath);\n if (!isStrictlyInsideRoot(canonicalRoot, candidate)) {\n throw new WorkspacePathError(\n \"outside_root\",\n `Path \"${inputPath}\" escapes the workspace root.`\n );\n }\n return {\n candidate,\n lexicalRelative: path.relative(canonicalRoot, candidate),\n };\n};\n\n/**\n * Resolves an existing file inside `root`, rejecting `..` traversal, absolute\n * paths outside `root`, directories, and symlinks pointing outside `root`.\n */\nexport const resolveWorkspaceReadPath = async (\n root: string,\n inputPath: string\n): Promise<ResolvedWorkspacePath> => {\n const canonicalRoot = canonicalizeRoot(root);\n const { candidate } = validateCandidate(canonicalRoot, inputPath);\n\n let realTarget: string;\n try {\n realTarget = await realpath(candidate);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n // Distinguish a broken symlink escaping root from a missing file.\n try {\n const linkStat = await lstat(candidate);\n if (linkStat.isSymbolicLink()) {\n throw new WorkspacePathError(\n \"outside_root\",\n `Symlink \"${inputPath}\" cannot be resolved inside the workspace root.`\n );\n }\n } catch (lstatError) {\n if (lstatError instanceof WorkspacePathError) {\n throw lstatError;\n }\n }\n throw new WorkspacePathError(\n \"not_found\",\n `File \"${inputPath}\" was not found.`\n );\n }\n throw error;\n }\n\n if (!isStrictlyInsideRoot(canonicalRoot, realTarget)) {\n throw new WorkspacePathError(\n \"outside_root\",\n `Path \"${inputPath}\" resolves outside the workspace root.`\n );\n }\n\n const targetStat = await lstat(realTarget);\n if (!targetStat.isFile()) {\n throw new WorkspacePathError(\n \"not_a_file\",\n `Path \"${inputPath}\" is not a regular file.`\n );\n }\n\n return {\n absolutePath: realTarget,\n relativePath: toPosixRelative(canonicalRoot, realTarget),\n };\n};\n\nconst resolveWriteSegment = async (\n canonicalRoot: string,\n inputPath: string,\n current: string,\n segments: readonly string[],\n index: number\n): Promise<ResolvedWorkspacePath> => {\n if (index >= segments.length) {\n if (!isStrictlyInsideRoot(canonicalRoot, current)) {\n throw new WorkspacePathError(\n \"outside_root\",\n `Path \"${inputPath}\" resolves outside the workspace root.`\n );\n }\n return {\n absolutePath: current,\n relativePath: toPosixRelative(canonicalRoot, current),\n };\n }\n\n const segment = segments[index];\n if (!segment) {\n return await resolveWriteSegment(\n canonicalRoot,\n inputPath,\n current,\n segments,\n index + 1\n );\n }\n\n const next = path.join(current, segment);\n const isLast = index === segments.length - 1;\n\n let entryStat: Awaited<ReturnType<typeof lstat>>;\n try {\n entryStat = await lstat(next);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n // From this component onward nothing exists on disk yet, so no\n // symlink can redirect outside `current`.\n const finalPath = path.join(current, ...segments.slice(index));\n if (!isStrictlyInsideRoot(canonicalRoot, finalPath)) {\n throw new WorkspacePathError(\n \"outside_root\",\n `Path \"${inputPath}\" escapes the workspace root.`\n );\n }\n return {\n absolutePath: finalPath,\n relativePath: toPosixRelative(canonicalRoot, finalPath),\n };\n }\n throw error;\n }\n\n if (entryStat.isSymbolicLink()) {\n let realNext: string;\n try {\n realNext = await realpath(next);\n } catch {\n throw new WorkspacePathError(\n \"outside_root\",\n `Symlink \"${inputPath}\" cannot be resolved inside the workspace root.`\n );\n }\n if (!isWithinRoot(canonicalRoot, realNext)) {\n throw new WorkspacePathError(\n \"outside_root\",\n `Path \"${inputPath}\" traverses a symlink outside the workspace root.`\n );\n }\n if (isLast && !isStrictlyInsideRoot(canonicalRoot, realNext)) {\n throw new WorkspacePathError(\n \"outside_root\",\n `Path \"${inputPath}\" resolves outside the workspace root.`\n );\n }\n const resolvedStat = await lstat(realNext);\n if (isLast && resolvedStat.isDirectory()) {\n throw new WorkspacePathError(\n \"not_a_file\",\n `Path \"${inputPath}\" is a directory.`\n );\n }\n if (!isLast && !resolvedStat.isDirectory()) {\n throw new WorkspacePathError(\n \"invalid_path\",\n `Parent of \"${inputPath}\" is not a directory.`\n );\n }\n return await resolveWriteSegment(\n canonicalRoot,\n inputPath,\n realNext,\n segments,\n index + 1\n );\n }\n\n if (isLast) {\n if (entryStat.isDirectory()) {\n throw new WorkspacePathError(\n \"not_a_file\",\n `Path \"${inputPath}\" is a directory.`\n );\n }\n return await resolveWriteSegment(\n canonicalRoot,\n inputPath,\n next,\n segments,\n index + 1\n );\n }\n\n if (!entryStat.isDirectory()) {\n throw new WorkspacePathError(\n \"invalid_path\",\n `Parent of \"${inputPath}\" is not a directory.`\n );\n }\n return await resolveWriteSegment(\n canonicalRoot,\n inputPath,\n next,\n segments,\n index + 1\n );\n};\n\n/**\n * Resolves a target file path for writing inside `root`. Walks every existing\n * path component from `root` downward to verify that neither an ancestor\n * directory symlink nor the target symlink escapes `root`.\n */\nexport const resolveWorkspaceWritePath = async (\n root: string,\n inputPath: string\n): Promise<ResolvedWorkspacePath> => {\n const canonicalRoot = canonicalizeRoot(root);\n const { lexicalRelative } = validateCandidate(canonicalRoot, inputPath);\n const segments = lexicalRelative.split(path.sep);\n return await resolveWriteSegment(\n canonicalRoot,\n inputPath,\n canonicalRoot,\n segments,\n 0\n );\n};\n\n/** Reads a UTF-8 file strictly inside `root`. */\nexport const readWorkspaceFile = async (\n root: string,\n inputPath: string\n): Promise<ResolvedWorkspacePath & { content: string }> => {\n const resolved = await resolveWorkspaceReadPath(root, inputPath);\n const content = await readFile(resolved.absolutePath, \"utf-8\");\n return { ...resolved, content };\n};\n\n/**\n * Atomically writes UTF-8 content to a file strictly inside `root` by writing\n * to a sibling temporary file and renaming it into place.\n */\nexport const writeWorkspaceFileAtomic = async (\n root: string,\n inputPath: string,\n content: string,\n options: { overwrite?: boolean } = {}\n): Promise<ResolvedWorkspacePath> => {\n const { overwrite = true } = options;\n const resolved = await resolveWorkspaceWritePath(root, inputPath);\n\n if (!overwrite) {\n try {\n await lstat(resolved.absolutePath);\n throw new Error(\n `File \"${resolved.relativePath}\" already exists. Pass overwrite: true to replace it.`\n );\n } catch (error) {\n if (!isErrnoException(error) || error.code !== \"ENOENT\") {\n throw error;\n }\n }\n }\n\n const directory = path.dirname(resolved.absolutePath);\n await mkdir(directory, { recursive: true });\n\n // Re-verify parent directory realpath after creation.\n const canonicalRoot = canonicalizeRoot(root);\n const realDir = await realpath(directory);\n if (!isWithinRoot(canonicalRoot, realDir)) {\n throw new WorkspacePathError(\n \"outside_root\",\n `Parent directory for \"${inputPath}\" escapes the workspace root.`\n );\n }\n\n const tempPath = path.join(\n realDir,\n `.mailquilt-tmp-${process.pid}-${randomBytes(6).toString(\"hex\")}`\n );\n try {\n await writeFile(tempPath, content, \"utf-8\");\n await rename(tempPath, resolved.absolutePath);\n } catch (error) {\n try {\n await unlink(tempPath);\n } catch {\n // Ignore cleanup failures if the temp file was never created.\n }\n throw error;\n }\n\n return resolved;\n};\n","import {\n BLOCK_TYPES,\n createEditor,\n createEmail,\n loadDocument,\n ROW_LAYOUTS,\n} from \"@mailquilt/core\";\nimport type { BlocksDocument, Command } from \"@mailquilt/core\";\nimport { checkEmail, renderEmail, renderText } from \"@mailquilt/renderer\";\nimport type { CheckEmailOptions } from \"@mailquilt/renderer\";\nimport { GMAIL_CLIP_BYTES, gmailKilobytes } from \"@mailquilt/renderer/internal\";\n\nimport { buildBlockCatalog } from \"./catalog.js\";\nimport { summarizeDocument } from \"./summary.js\";\nimport {\n readWorkspaceFile,\n resolveWorkspaceWritePath,\n WorkspacePathError,\n writeWorkspaceFileAtomic,\n} from \"./workspace.js\";\n\nexport interface McpToolDefinition {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: Record<string, unknown>;\n}\n\nexport interface McpToolResult {\n readonly content: readonly [{ readonly type: \"text\"; readonly text: string }];\n readonly isError?: boolean;\n}\n\nexport interface ToolContext {\n readonly root: string;\n readonly devUrl?: string | undefined;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst jsonResult = (payload: unknown, isError = false): McpToolResult => ({\n content: [{ text: JSON.stringify(payload, null, 2), type: \"text\" }],\n ...(isError ? { isError: true } : {}),\n});\n\nconst errorResult = (message: string, extra: Record<string, unknown> = {}) =>\n jsonResult({ error: message, ok: false, ...extra }, true);\n\nconst errorMessage = (error: unknown): string =>\n error instanceof Error ? error.message : String(error);\n\nconst parseOptionalString = (\n args: Record<string, unknown>,\n key: string\n): { ok: true; value: string | undefined } | { ok: false; error: string } => {\n const value = args[key];\n if (value === undefined) {\n return { ok: true, value: undefined };\n }\n if (typeof value !== \"string\" || value.trim() === \"\") {\n return { ok: false, error: `\"${key}\" must be a non-empty string.` };\n }\n return { ok: true, value };\n};\n\nconst loadTargetDocument = async (\n context: ToolContext,\n args: Record<string, unknown>\n): Promise<\n | { ok: true; document: BlocksDocument; relativePath?: string }\n | { ok: false; result: McpToolResult }\n> => {\n const hasPath = args.path !== undefined;\n const hasDocument = args.document !== undefined;\n\n if (hasPath === hasDocument) {\n return {\n ok: false,\n result: errorResult(\n 'Provide either \"path\" (inside the workspace root) or inline \"document\", not both.'\n ),\n };\n }\n\n if (hasPath) {\n if (typeof args.path !== \"string\") {\n return { ok: false, result: errorResult('\"path\" must be a string.') };\n }\n let content: string;\n let relativePath: string;\n try {\n const read = await readWorkspaceFile(context.root, args.path);\n ({ content, relativePath } = read);\n } catch (error) {\n return {\n ok: false,\n result: errorResult(\n errorMessage(error),\n error instanceof WorkspacePathError ? { code: error.code } : {}\n ),\n };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n return {\n ok: false,\n result: errorResult(\n `Invalid JSON in \"${relativePath}\": ${errorMessage(error)}`,\n { code: \"invalid_json\", path: relativePath }\n ),\n };\n }\n\n const loaded = loadDocument(parsed);\n if (!loaded.ok) {\n return {\n ok: false,\n result: errorResult(\n `Document \"${relativePath}\" was refused: ${loaded.reason}`,\n {\n code: \"invalid_document\",\n path: relativePath,\n reason: loaded.reason,\n }\n ),\n };\n }\n return { document: loaded.document, ok: true, relativePath };\n }\n\n const loaded = loadDocument(args.document);\n if (!loaded.ok) {\n return {\n ok: false,\n result: errorResult(`Document was refused: ${loaded.reason}`, {\n code: \"invalid_document\",\n reason: loaded.reason,\n }),\n };\n }\n return { document: loaded.document, ok: true };\n};\n\nconst parseMergeTags = (\n value: unknown\n):\n | { ok: true; value: CheckEmailOptions[\"mergeTags\"] }\n | { ok: false; error: string } => {\n if (value === undefined) {\n return { ok: true, value: undefined };\n }\n if (!Array.isArray(value)) {\n return { ok: false, error: '\"mergeTags\" must be an array.' };\n }\n const tags: { name: string; unsubscribe?: boolean }[] = [];\n for (const [index, entry] of value.entries()) {\n if (\n !isRecord(entry) ||\n typeof entry.name !== \"string\" ||\n entry.name.trim() === \"\"\n ) {\n return {\n error: `\"mergeTags[${index}]\" must be an object with a non-empty string \"name\".`,\n ok: false,\n };\n }\n if (\n entry.unsubscribe !== undefined &&\n typeof entry.unsubscribe !== \"boolean\"\n ) {\n return {\n error: `\"mergeTags[${index}].unsubscribe\" must be a boolean.`,\n ok: false,\n };\n }\n tags.push(\n entry.unsubscribe === undefined\n ? { name: entry.name }\n : { name: entry.name, unsubscribe: entry.unsubscribe }\n );\n }\n return { ok: true, value: tags };\n};\n\nconst handleListBlockTypes = (args: Record<string, unknown>): McpToolResult => {\n const blockTypeArg = parseOptionalString(args, \"blockType\");\n if (!blockTypeArg.ok) {\n return errorResult(blockTypeArg.error);\n }\n\n const catalog = buildBlockCatalog(blockTypeArg.value);\n if (blockTypeArg.value !== undefined && catalog.blockTypes.length === 0) {\n const valid = BLOCK_TYPES.map(({ type }) => type).join(\", \");\n return errorResult(\n `Unknown Block type \"${blockTypeArg.value}\". Available Block types: ${valid}.`\n );\n }\n return jsonResult(catalog);\n};\n\nconst validateCreateArgs = (\n args: Record<string, unknown>\n): McpToolResult | null => {\n if (args.overwrite !== undefined && typeof args.overwrite !== \"boolean\") {\n return errorResult('\"overwrite\" must be a boolean.');\n }\n if (args.blank !== undefined && typeof args.blank !== \"boolean\") {\n return errorResult('\"blank\" must be a boolean.');\n }\n if (args.settings !== undefined && !isRecord(args.settings)) {\n return errorResult('\"settings\" must be an object.');\n }\n if (args.style !== undefined && !isRecord(args.style)) {\n return errorResult('\"style\" must be an object.');\n }\n if (args.rows !== undefined && !Array.isArray(args.rows)) {\n return errorResult('\"rows\" must be an array.');\n }\n return null;\n};\n\nconst applyCreateRows = (\n initialEditor: ReturnType<typeof createEditor>,\n rows: readonly unknown[]\n):\n | { ok: true; editor: ReturnType<typeof createEditor> }\n | { ok: false; result: McpToolResult } => {\n let editor = initialEditor;\n for (let rowIndex = 0; rowIndex < rows.length; rowIndex += 1) {\n const rowSpec: unknown = rows[rowIndex];\n if (!isRecord(rowSpec)) {\n return {\n ok: false,\n result: errorResult(`\"rows[${rowIndex}]\" must be an object.`),\n };\n }\n if (\"layout\" in rowSpec) {\n const applied = editor.apply({\n ...rowSpec,\n index: rowIndex,\n type: \"insertRow\",\n } as Command);\n if (!applied.ok) {\n return {\n ok: false,\n result: errorResult(applied.reason, {\n code: applied.code,\n index: rowIndex,\n }),\n };\n }\n } else {\n const candidate = editor.getDocument();\n const loaded = loadDocument({\n ...candidate,\n rows: [...candidate.rows, rowSpec],\n });\n if (!loaded.ok) {\n return {\n ok: false,\n result: errorResult(loaded.reason, {\n code: \"invalid_document\",\n index: rowIndex,\n }),\n };\n }\n editor = createEditor({ document: loaded.document });\n }\n }\n return { editor, ok: true };\n};\n\nconst handleCreateEmail = async (\n context: ToolContext,\n args: Record<string, unknown>\n): Promise<McpToolResult> => {\n const pathArg = parseOptionalString(args, \"path\");\n if (!pathArg.ok) {\n return errorResult(pathArg.error);\n }\n const argError = validateCreateArgs(args);\n if (argError !== null) {\n return argError;\n }\n\n const base = createEmail();\n if (args.blank === true || args.rows !== undefined) {\n base.rows = [];\n }\n\n let editor = createEditor({ document: base });\n\n if (isRecord(args.settings)) {\n const applied = editor.apply({\n settings: args.settings,\n type: \"updateEmailSettings\",\n });\n if (!applied.ok && applied.code !== \"unchanged\") {\n return errorResult(applied.reason, { code: applied.code });\n }\n }\n\n if (isRecord(args.style)) {\n const applied = editor.apply({\n style: args.style,\n type: \"updateEmailStyle\",\n });\n if (!applied.ok && applied.code !== \"unchanged\") {\n return errorResult(applied.reason, { code: applied.code });\n }\n }\n\n if (Array.isArray(args.rows)) {\n const builtRows = applyCreateRows(editor, args.rows);\n if (!builtRows.ok) {\n return builtRows.result;\n }\n ({ editor } = builtRows);\n }\n\n const finalLoaded = loadDocument(editor.getDocument());\n if (!finalLoaded.ok) {\n return errorResult(finalLoaded.reason, { code: \"invalid_document\" });\n }\n\n const { document } = finalLoaded;\n const summary = summarizeDocument(document);\n\n if (pathArg.value !== undefined) {\n try {\n const written = await writeWorkspaceFileAtomic(\n context.root,\n pathArg.value,\n `${JSON.stringify(document, null, 2)}\\n`,\n { overwrite: args.overwrite === true }\n );\n return jsonResult({\n document,\n ok: true,\n path: written.relativePath,\n summary,\n });\n } catch (error) {\n return errorResult(\n errorMessage(error),\n error instanceof WorkspacePathError ? { code: error.code } : {}\n );\n }\n }\n\n return jsonResult({ document, ok: true, summary });\n};\n\nconst handleReadEmail = async (\n context: ToolContext,\n args: Record<string, unknown>\n): Promise<McpToolResult> => {\n if (typeof args.path !== \"string\") {\n return errorResult('\"path\" is required and must be a string.');\n }\n const target = await loadTargetDocument(context, { path: args.path });\n if (!target.ok) {\n return target.result;\n }\n return jsonResult({\n document: target.document,\n path: target.relativePath,\n summary: summarizeDocument(target.document),\n });\n};\n\nconst handleApplyCommands = async (\n context: ToolContext,\n args: Record<string, unknown>\n): Promise<McpToolResult> => {\n if (!Array.isArray(args.commands)) {\n return errorResult('\"commands\" must be an array of Mail Quilt Commands.');\n }\n\n const target = await loadTargetDocument(context, args);\n if (!target.ok) {\n return target.result;\n }\n\n if (typeof args.path === \"string\") {\n try {\n await resolveWorkspaceWritePath(context.root, args.path);\n } catch (error) {\n return errorResult(\n errorMessage(error),\n error instanceof WorkspacePathError ? { code: error.code } : {}\n );\n }\n }\n\n const editor = createEditor({ document: target.document });\n const createdIds: string[] = [];\n\n for (let index = 0; index < args.commands.length; index += 1) {\n const command: unknown = args.commands[index];\n const applied = editor.apply(command as Command);\n if (!applied.ok) {\n // Roll back completely: discard in-memory mutations and leave any file\n // on disk untouched.\n while (editor.undo()) {\n // Rewind applied steps before discarding.\n }\n return jsonResult(\n {\n code: applied.code,\n index,\n ok: false,\n reason: applied.reason,\n rolledBack: true,\n },\n true\n );\n }\n if (applied.createdId !== undefined) {\n createdIds.push(applied.createdId);\n }\n }\n\n const updated = editor.getDocument();\n const verified = loadDocument(updated);\n if (!verified.ok) {\n return errorResult(\n `Updated document failed validation: ${verified.reason}`,\n { code: \"invalid_document\", rolledBack: true }\n );\n }\n\n const summary = summarizeDocument(verified.document);\n\n if (typeof args.path === \"string\") {\n try {\n const written = await writeWorkspaceFileAtomic(\n context.root,\n args.path,\n `${JSON.stringify(verified.document, null, 2)}\\n`,\n { overwrite: true }\n );\n return jsonResult({\n appliedCount: args.commands.length,\n createdIds,\n ok: true,\n path: written.relativePath,\n summary,\n });\n } catch (error) {\n return errorResult(\n errorMessage(error),\n error instanceof WorkspacePathError ? { code: error.code } : {}\n );\n }\n }\n\n return jsonResult({\n appliedCount: args.commands.length,\n createdIds,\n document: verified.document,\n ok: true,\n summary,\n });\n};\n\nconst handleRenderHtml = async (\n context: ToolContext,\n args: Record<string, unknown>\n): Promise<McpToolResult> => {\n const socialIconsUrl = parseOptionalString(args, \"socialIconsUrl\");\n if (!socialIconsUrl.ok) {\n return errorResult(socialIconsUrl.error);\n }\n\n const target = await loadTargetDocument(context, args);\n if (!target.ok) {\n return target.result;\n }\n\n try {\n const html = await renderEmail(\n target.document,\n socialIconsUrl.value === undefined\n ? {}\n : { socialIconsUrl: socialIconsUrl.value }\n );\n const bytes = Buffer.byteLength(html, \"utf-8\");\n const gmailClipped = bytes > GMAIL_CLIP_BYTES;\n return jsonResult({\n bytes,\n gmailClipped,\n gmailLimitBytes: GMAIL_CLIP_BYTES,\n gmailStatus: gmailClipped ? \"clipped\" : \"ok\",\n html,\n kilobytes: gmailKilobytes(bytes),\n ...(target.relativePath === undefined\n ? {}\n : { path: target.relativePath }),\n });\n } catch (error) {\n return errorResult(`Failed to render HTML: ${errorMessage(error)}`);\n }\n};\n\nconst handleRenderText = async (\n context: ToolContext,\n args: Record<string, unknown>\n): Promise<McpToolResult> => {\n const target = await loadTargetDocument(context, args);\n if (!target.ok) {\n return target.result;\n }\n\n try {\n const text = renderText(target.document);\n return jsonResult({\n bytes: Buffer.byteLength(text, \"utf-8\"),\n ...(target.relativePath === undefined\n ? {}\n : { path: target.relativePath }),\n text,\n });\n } catch (error) {\n return errorResult(`Failed to render plain text: ${errorMessage(error)}`);\n }\n};\n\nconst handleCheckEmail = async (\n context: ToolContext,\n args: Record<string, unknown>\n): Promise<McpToolResult> => {\n const socialIconsUrl = parseOptionalString(args, \"socialIconsUrl\");\n if (!socialIconsUrl.ok) {\n return errorResult(socialIconsUrl.error);\n }\n const mergeTags = parseMergeTags(args.mergeTags);\n if (!mergeTags.ok) {\n return errorResult(mergeTags.error);\n }\n\n const target = await loadTargetDocument(context, args);\n if (!target.ok) {\n return target.result;\n }\n\n try {\n const problems = await checkEmail(target.document, {\n ...(mergeTags.value === undefined ? {} : { mergeTags: mergeTags.value }),\n ...(socialIconsUrl.value === undefined\n ? {}\n : { socialIconsUrl: socialIconsUrl.value }),\n });\n return jsonResult({\n passed: problems.length === 0,\n ...(target.relativePath === undefined\n ? {}\n : { path: target.relativePath }),\n problemCount: problems.length,\n problems,\n });\n } catch (error) {\n return errorResult(`Failed to check email: ${errorMessage(error)}`);\n }\n};\n\nconst handleGetPreviewUrl = async (\n context: ToolContext,\n args: Record<string, unknown>\n): Promise<McpToolResult> => {\n const pathArg = parseOptionalString(args, \"path\");\n if (!pathArg.ok) {\n return errorResult(pathArg.error);\n }\n\n let relativePath: string | undefined;\n if (pathArg.value !== undefined) {\n try {\n const resolved = await resolveWorkspaceWritePath(\n context.root,\n pathArg.value\n );\n ({ relativePath } = resolved);\n } catch (error) {\n return errorResult(\n errorMessage(error),\n error instanceof WorkspacePathError ? { code: error.code } : {}\n );\n }\n }\n\n const configured = (\n context.devUrl ??\n process.env.MAILQUILT_DEV_URL ??\n \"\"\n ).trim();\n if (configured === \"\") {\n return jsonResult({\n active: false,\n message:\n \"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).\",\n ...(relativePath === undefined ? {} : { path: relativePath }),\n url: null,\n });\n }\n\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(configured);\n } catch {\n return errorResult(\n `Configured dev URL \"${configured}\" is not a valid URL.`\n );\n }\n if (parsedUrl.protocol !== \"http:\" && parsedUrl.protocol !== \"https:\") {\n return errorResult(\n `Configured dev URL \"${configured}\" must use http: or https:.`\n );\n }\n\n if (relativePath !== undefined) {\n parsedUrl.searchParams.set(\"file\", relativePath);\n }\n\n return jsonResult({\n active: true,\n ...(relativePath === undefined ? {} : { path: relativePath }),\n url: parsedUrl.toString(),\n });\n};\n\n/** Returns the live tool definitions dynamically reflecting `@mailquilt/core`. */\nexport const getToolDefinitions = (): readonly McpToolDefinition[] => [\n {\n description:\n \"Return the live catalog of Mail Quilt Block types, Row layouts, and JSON Schemas derived directly from @mailquilt/core.\",\n inputSchema: {\n additionalProperties: false,\n properties: {\n blockType: {\n description:\n \"Optional Block type to filter the returned catalog to a single Block type.\",\n enum: BLOCK_TYPES.map(({ type }) => type),\n type: \"string\",\n },\n },\n type: \"object\",\n },\n name: \"list_block_types\",\n },\n {\n description:\n \"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.\",\n inputSchema: {\n additionalProperties: false,\n properties: {\n blank: {\n description:\n \"When true and rows is omitted, create an email with zero Rows instead of the default single-Text Row.\",\n type: \"boolean\",\n },\n overwrite: {\n description:\n \"Allow overwriting an existing file at path (default false).\",\n type: \"boolean\",\n },\n path: {\n description:\n \"Optional path inside the workspace root where the JSON email will be written.\",\n type: \"string\",\n },\n rows: {\n description:\n \"Optional initial Rows, either as insertRow specs ({ layout, props?, columns? }) or full validated Row objects.\",\n items: { type: \"object\" },\n type: \"array\",\n },\n settings: {\n description:\n \"Optional EmailSettings overrides (width, backgroundColor, fontFamily, preheader, language, style, fonts).\",\n type: \"object\",\n },\n style: {\n description: \"Optional EmailStyle overrides.\",\n type: \"object\",\n },\n },\n type: \"object\",\n },\n name: \"create_email\",\n },\n {\n description:\n \"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.\",\n inputSchema: {\n additionalProperties: false,\n properties: {\n path: {\n description: \"Path to the email JSON file inside the workspace root.\",\n type: \"string\",\n },\n },\n required: [\"path\"],\n type: \"object\",\n },\n name: \"read_email\",\n },\n {\n description:\n \"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.\",\n inputSchema: {\n additionalProperties: false,\n properties: {\n commands: {\n 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.`,\n items: { type: \"object\" },\n type: \"array\",\n },\n document: {\n description:\n \"Inline BlocksDocument to update in memory (mutually exclusive with path).\",\n type: \"object\",\n },\n path: {\n description:\n \"Path to the email JSON file inside the workspace root to update (mutually exclusive with document).\",\n type: \"string\",\n },\n },\n required: [\"commands\"],\n type: \"object\",\n },\n name: \"apply_commands\",\n },\n {\n description:\n \"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.\",\n inputSchema: {\n additionalProperties: false,\n properties: {\n document: {\n description:\n \"Inline BlocksDocument to render (mutually exclusive with path).\",\n type: \"object\",\n },\n path: {\n description:\n \"Path to the email JSON file inside the workspace root (mutually exclusive with document).\",\n type: \"string\",\n },\n socialIconsUrl: {\n description:\n \"Optional base URL of a folder hosting Social Block icons instead of jsDelivr.\",\n type: \"string\",\n },\n },\n type: \"object\",\n },\n name: \"render_html\",\n },\n {\n description:\n \"Render a Mail Quilt email file or inline document to plain text via renderText().\",\n inputSchema: {\n additionalProperties: false,\n properties: {\n document: {\n description:\n \"Inline BlocksDocument to render (mutually exclusive with path).\",\n type: \"object\",\n },\n path: {\n description:\n \"Path to the email JSON file inside the workspace root (mutually exclusive with document).\",\n type: \"string\",\n },\n },\n type: \"object\",\n },\n name: \"render_text\",\n },\n {\n description:\n \"Run Mail Quilt's checkEmail() on a file or inline document, returning structured Problems and pass/fail status.\",\n inputSchema: {\n additionalProperties: false,\n properties: {\n document: {\n description:\n \"Inline BlocksDocument to check (mutually exclusive with path).\",\n type: \"object\",\n },\n mergeTags: {\n description:\n \"Optional list of Host app Merge Tags ({ name, unsubscribe? }) to check unknown tags and unsubscribe link presence.\",\n items: {\n additionalProperties: false,\n properties: {\n name: { type: \"string\" },\n unsubscribe: { type: \"boolean\" },\n },\n required: [\"name\"],\n type: \"object\",\n },\n type: \"array\",\n },\n path: {\n description:\n \"Path to the email JSON file inside the workspace root (mutually exclusive with document).\",\n type: \"string\",\n },\n socialIconsUrl: {\n description:\n \"Optional base URL of a folder hosting Social Block icons when measuring rendered HTML.\",\n type: \"string\",\n },\n },\n type: \"object\",\n },\n name: \"check_email\",\n },\n {\n description:\n \"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.\",\n inputSchema: {\n additionalProperties: false,\n properties: {\n path: {\n description:\n \"Optional email file path inside the workspace root to link directly in the dev editor.\",\n type: \"string\",\n },\n },\n type: \"object\",\n },\n name: \"get_preview_url\",\n },\n];\n\nexport const TOOL_NAMES: ReadonlySet<string> = new Set(\n getToolDefinitions().map(({ name }) => name)\n);\n\n/** Executes a named MCP tool with raw arguments. Returns `null` if unknown. */\nexport const dispatchTool = async (\n context: ToolContext,\n name: string,\n rawArgs: Record<string, unknown>\n): Promise<McpToolResult | null> => {\n switch (name) {\n case \"list_block_types\": {\n return handleListBlockTypes(rawArgs);\n }\n case \"create_email\": {\n return await handleCreateEmail(context, rawArgs);\n }\n case \"read_email\": {\n return await handleReadEmail(context, rawArgs);\n }\n case \"apply_commands\": {\n return await handleApplyCommands(context, rawArgs);\n }\n case \"render_html\": {\n return await handleRenderHtml(context, rawArgs);\n }\n case \"render_text\": {\n return await handleRenderText(context, rawArgs);\n }\n case \"check_email\": {\n return await handleCheckEmail(context, rawArgs);\n }\n case \"get_preview_url\": {\n return await handleGetPreviewUrl(context, rawArgs);\n }\n default: {\n return null;\n }\n }\n};\n","import { createInterface } from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\n\nimport packageJson from \"../package.json\" with { type: \"json\" };\nimport { dispatchTool, getToolDefinitions } from \"./tools.js\";\nimport type { McpToolDefinition, McpToolResult } from \"./tools.js\";\nimport { canonicalizeRoot } from \"./workspace.js\";\n\nconst SUPPORTED_PROTOCOL_VERSIONS = [\n \"2025-11-25\",\n \"2025-06-18\",\n \"2025-03-26\",\n \"2024-11-05\",\n] as const;\n\nconst DEFAULT_PROTOCOL_VERSION = \"2025-03-26\";\n\nconst JSON_RPC_PARSE_ERROR = -32_700;\nconst JSON_RPC_INVALID_REQUEST = -32_600;\nconst JSON_RPC_METHOD_NOT_FOUND = -32_601;\nconst JSON_RPC_INVALID_PARAMS = -32_602;\nconst JSON_RPC_INTERNAL_ERROR = -32_603;\n\ntype JsonRpcId = string | number | null;\n\nexport interface JsonRpcSuccess {\n readonly jsonrpc: \"2.0\";\n readonly id: JsonRpcId;\n readonly result: unknown;\n}\n\nexport interface JsonRpcFailure {\n readonly jsonrpc: \"2.0\";\n readonly id: JsonRpcId;\n readonly error: {\n readonly code: number;\n readonly message: string;\n };\n}\n\nexport type JsonRpcResponse = JsonRpcSuccess | JsonRpcFailure;\n\nexport interface McpServerOptions {\n /** Workspace root directory; all file reads/writes are restricted inside it. */\n readonly root?: string | undefined;\n /** Optional active `mailquilt dev` preview URL (overrides MAILQUILT_DEV_URL). */\n readonly devUrl?: string | undefined;\n}\n\nexport interface McpServer {\n readonly root: string;\n readonly listTools: () => readonly McpToolDefinition[];\n readonly callTool: (\n name: string,\n args?: Record<string, unknown>\n ) => Promise<McpToolResult>;\n readonly handleJsonRpcMessage: (\n message: unknown\n ) => Promise<JsonRpcResponse | readonly JsonRpcResponse[] | null>;\n readonly handleLine: (line: string) => Promise<string | null>;\n readonly startStdio: (input?: Readable, output?: Writable) => Promise<void>;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isValidId = (value: unknown): value is JsonRpcId =>\n value === null ||\n typeof value === \"string\" ||\n (typeof value === \"number\" && Number.isFinite(value));\n\nconst success = (id: JsonRpcId, result: unknown): JsonRpcSuccess => ({\n id,\n jsonrpc: \"2.0\",\n result,\n});\n\nconst failure = (\n id: JsonRpcId,\n code: number,\n message: string\n): JsonRpcFailure => ({\n error: { code, message },\n id,\n jsonrpc: \"2.0\",\n});\n\nconst negotiateProtocolVersion = (requested: unknown): string => {\n if (\n typeof requested === \"string\" &&\n (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(requested)\n ) {\n return requested;\n }\n return DEFAULT_PROTOCOL_VERSION;\n};\n\nconst handleMethod = async (\n context: { readonly devUrl?: string | undefined; readonly root: string },\n id: JsonRpcId,\n method: string,\n params: unknown\n): Promise<JsonRpcResponse> => {\n switch (method) {\n case \"initialize\": {\n const requestedVersion = isRecord(params)\n ? params.protocolVersion\n : undefined;\n return success(id, {\n capabilities: {\n tools: { listChanged: false },\n },\n instructions:\n \"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().\",\n protocolVersion: negotiateProtocolVersion(requestedVersion),\n serverInfo: {\n name: packageJson.name,\n version: packageJson.version,\n },\n });\n }\n case \"ping\": {\n return success(id, {});\n }\n case \"tools/list\": {\n return success(id, { tools: getToolDefinitions() });\n }\n case \"tools/call\": {\n if (!isRecord(params) || typeof params.name !== \"string\") {\n return failure(\n id,\n JSON_RPC_INVALID_PARAMS,\n \"tools/call requires params.name as a string.\"\n );\n }\n const rawArgs = params.arguments ?? {};\n if (!isRecord(rawArgs)) {\n return failure(\n id,\n JSON_RPC_INVALID_PARAMS,\n \"tools/call params.arguments must be an object.\"\n );\n }\n const result = await dispatchTool(context, params.name, rawArgs);\n if (result === null) {\n return failure(\n id,\n JSON_RPC_INVALID_PARAMS,\n `Unknown tool: ${params.name}`\n );\n }\n return success(id, result);\n }\n default: {\n return failure(\n id,\n JSON_RPC_METHOD_NOT_FOUND,\n `Method not found: ${method}`\n );\n }\n }\n};\n\nconst runSequentialBatch = async (\n items: readonly unknown[],\n index: number,\n handleOne: (item: unknown) => Promise<JsonRpcResponse | null>,\n collected: JsonRpcResponse[]\n): Promise<JsonRpcResponse[]> => {\n if (index >= items.length) {\n return collected;\n }\n const response = await handleOne(items[index]);\n if (response !== null) {\n collected.push(response);\n }\n return await runSequentialBatch(items, index + 1, handleOne, collected);\n};\n\n/**\n * Creates a Mail Quilt MCP server scoped to `options.root` (default `process.cwd()`).\n */\nexport const createMcpServer = (options: McpServerOptions = {}): McpServer => {\n const root = canonicalizeRoot(options.root ?? process.cwd());\n const context = { devUrl: options.devUrl, root };\n\n const callTool = async (\n name: string,\n args: Record<string, unknown> = {}\n ): Promise<McpToolResult> => {\n const result = await dispatchTool(context, name, args);\n if (result === null) {\n throw new Error(`Unknown tool \"${name}\".`);\n }\n return result;\n };\n\n const handleSingleMessage = async (\n message: unknown\n ): Promise<JsonRpcResponse | null> => {\n if (!isRecord(message)) {\n return failure(null, JSON_RPC_INVALID_REQUEST, \"Invalid Request\");\n }\n\n const hasId = Object.hasOwn(message, \"id\") && message.id !== undefined;\n const id: JsonRpcId = hasId && isValidId(message.id) ? message.id : null;\n\n if (message.jsonrpc !== \"2.0\" || typeof message.method !== \"string\") {\n return hasId\n ? failure(id, JSON_RPC_INVALID_REQUEST, \"Invalid Request\")\n : null;\n }\n\n // Notifications carry no `id` and MUST NOT receive a response.\n if (!hasId) {\n return null;\n }\n\n if (!isValidId(message.id)) {\n return failure(null, JSON_RPC_INVALID_REQUEST, \"Invalid Request id\");\n }\n\n try {\n return await handleMethod(context, id, message.method, message.params);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n return failure(id, JSON_RPC_INTERNAL_ERROR, detail);\n }\n };\n\n const handleJsonRpcMessage = async (\n message: unknown\n ): Promise<JsonRpcResponse | readonly JsonRpcResponse[] | null> => {\n if (Array.isArray(message)) {\n if (message.length === 0) {\n return failure(null, JSON_RPC_INVALID_REQUEST, \"Invalid Request\");\n }\n const responses = await runSequentialBatch(\n message,\n 0,\n handleSingleMessage,\n []\n );\n return responses.length > 0 ? responses : null;\n }\n return await handleSingleMessage(message);\n };\n\n const handleLine = async (line: string): Promise<string | null> => {\n const trimmed = line.trim();\n if (trimmed === \"\") {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n return JSON.stringify(failure(null, JSON_RPC_PARSE_ERROR, \"Parse error\"));\n }\n const response = await handleJsonRpcMessage(parsed);\n return response === null ? null : JSON.stringify(response);\n };\n\n const startStdio = async (\n input: Readable = process.stdin,\n output: Writable = process.stdout\n ): Promise<void> => {\n const lines = createInterface({\n crlfDelay: Number.POSITIVE_INFINITY,\n input,\n });\n for await (const line of lines) {\n const response = await handleLine(line);\n if (response !== null) {\n output.write(`${response}\\n`);\n }\n }\n };\n\n return {\n callTool,\n handleJsonRpcMessage,\n handleLine,\n listTools: getToolDefinitions,\n root,\n startStdio,\n };\n};\n\n/** Starts the Mail Quilt MCP stdio server and resolves once stdin closes. */\nexport const startMcpStdioServer = async (\n options: McpServerOptions & {\n readonly input?: Readable | undefined;\n readonly output?: Writable | undefined;\n } = {}\n): Promise<void> => {\n const server = createMcpServer(options);\n await server.startStdio(options.input, options.output);\n};\n"],"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S;CAC1B,CAAC;AACH;;AAGA,MAAa,2BAAyD;CACpE;EACE,aACE;EACF,aAAa;GACX,sBAAsB;GACtB,YAAY,EACV,WAAW;IACT,aACE;IACF,MAAM,YAAY,KAAK,EAAE,WAAW,IAAI;IACxC,MAAM;GACR,EACF;GACA,MAAM;EACR;EACA,MAAM;CACR;CACA;EACE,aACE;EACF,aAAa;GACX,sBAAsB;GACtB,YAAY;IACV,OAAO;KACL,aACE;KACF,MAAM;IACR;IACA,WAAW;KACT,aACE;KACF,MAAM;IACR;IACA,MAAM;KACJ,aACE;KACF,MAAM;IACR;IACA,MAAM;KACJ,aACE;KACF,OAAO,EAAE,MAAM,SAAS;KACxB,MAAM;IACR;IACA,UAAU;KACR,aACE;KACF,MAAM;IACR;IACA,OAAO;KACL,aAAa;KACb,MAAM;IACR;GACF;GACA,MAAM;EACR;EACA,MAAM;CACR;CACA;EACE,aACE;EACF,aAAa;GACX,sBAAsB;GACtB,YAAY,EACV,MAAM;IACJ,aAAa;IACb,MAAM;GACR,EACF;GACA,UAAU,CAAC,MAAM;GACjB,MAAM;EACR;EACA,MAAM;CACR;CACA;EACE,aACE;EACF,aAAa;GACX,sBAAsB;GACtB,YAAY;IACV,UAAU;KACR,aAAa,mFAAmF,YAAY,KAAK,IAAI,EAAE;KACvH,OAAO,EAAE,MAAM,SAAS;KACxB,MAAM;IACR;IACA,UAAU;KACR,aACE;KACF,MAAM;IACR;IACA,MAAM;KACJ,aACE;KACF,MAAM;IACR;GACF;GACA,UAAU,CAAC,UAAU;GACrB,MAAM;EACR;EACA,MAAM;CACR;CACA;EACE,aACE;EACF,aAAa;GACX,sBAAsB;GACtB,YAAY;IACV,UAAU;KACR,aACE;KACF,MAAM;IACR;IACA,MAAM;KACJ,aACE;KACF,MAAM;IACR;IACA,gBAAgB;KACd,aACE;KACF,MAAM;IACR;GACF;GACA,MAAM;EACR;EACA,MAAM;CACR;CACA;EACE,aACE;EACF,aAAa;GACX,sBAAsB;GACtB,YAAY;IACV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
- "version": "0.0.0",
4
- "description": "Placeholder for @mailquilt/mcp (0.5.0 release pending)",
3
+ "version": "0.5.0",
4
+ "description": "Model Context Protocol (MCP) server for Mail Quilt: create, edit, check, and render emails over stdio without a DOM.",
5
+ "keywords": [
6
+ "email",
7
+ "email-builder",
8
+ "email-editor",
9
+ "email-template",
10
+ "mcp",
11
+ "model-context-protocol",
12
+ "stdio"
13
+ ],
14
+ "homepage": "https://editor.mailquilt.com",
15
+ "bugs": {
16
+ "url": "https://github.com/mailquilt/editor/issues"
17
+ },
5
18
  "license": "MIT",
6
19
  "repository": {
7
20
  "type": "git",
8
21
  "url": "git+https://github.com/mailquilt/editor.git",
9
22
  "directory": "packages/mcp"
23
+ },
24
+ "bin": {
25
+ "mailquilt-mcp": "./dist/bin.js"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "src"
30
+ ],
31
+ "type": "module",
32
+ "sideEffects": false,
33
+ "main": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
35
+ "exports": {
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "default": "./dist/index.js"
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "@mailquilt/core": "0.5.0",
47
+ "@mailquilt/renderer": "0.5.0"
48
+ },
49
+ "devDependencies": {
50
+ "@repo/typescript-config": "0.0.0",
51
+ "@types/node": "^24.19.2",
52
+ "tsdown": "^0.23.5",
53
+ "typescript": "7.0.2",
54
+ "vitest": "^5.1.0"
55
+ },
56
+ "engines": {
57
+ "node": ">=22"
58
+ },
59
+ "scripts": {
60
+ "build": "tsdown",
61
+ "check-types": "tsc --noEmit && tsc --noEmit -p test",
62
+ "test": "vitest run"
10
63
  }
11
- }
64
+ }
package/src/bin.ts ADDED
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+
4
+ import packageJson from "../package.json" with { type: "json" };
5
+ import { startMcpStdioServer } from "./server.js";
6
+
7
+ const HELP_TEXT = `Usage: mailquilt-mcp [options]
8
+
9
+ Start the Mail Quilt Model Context Protocol (MCP) server over stdio.
10
+
11
+ Options:
12
+ --root <dir> Workspace root directory (default: current working directory)
13
+ --dev-url <url> Active mailquilt dev URL (default: MAILQUILT_DEV_URL)
14
+ -h, --help Show this help message
15
+ -v, --version Show package version
16
+ `;
17
+
18
+ const run = async () => {
19
+ const { values } = parseArgs({
20
+ allowPositionals: false,
21
+ args: process.argv.slice(2),
22
+ options: {
23
+ "dev-url": { type: "string" },
24
+ help: { short: "h", type: "boolean" },
25
+ root: { type: "string" },
26
+ version: { short: "v", type: "boolean" },
27
+ },
28
+ strict: true,
29
+ });
30
+
31
+ if (values.help) {
32
+ process.stdout.write(HELP_TEXT);
33
+ return;
34
+ }
35
+
36
+ if (values.version) {
37
+ process.stdout.write(`${packageJson.version}\n`);
38
+ return;
39
+ }
40
+
41
+ await startMcpStdioServer({
42
+ devUrl: values["dev-url"],
43
+ root: values.root,
44
+ });
45
+ };
46
+
47
+ try {
48
+ await run();
49
+ } catch (error) {
50
+ const message = error instanceof Error ? error.message : String(error);
51
+ process.stderr.write(`mailquilt-mcp: ${message}\n`);
52
+ process.exitCode = 1;
53
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,188 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+
4
+ import { BLOCK_TYPES, ROW_LAYOUTS } from "@mailquilt/core";
5
+ import type { BlockType, RowLayout } from "@mailquilt/core";
6
+
7
+ export type JsonSchemaObject = Record<string, unknown>;
8
+
9
+ export interface BlockTypeCatalogEntry {
10
+ readonly type: BlockType | string;
11
+ readonly label: string;
12
+ readonly requiredProps: readonly string[];
13
+ readonly propNames: readonly string[];
14
+ readonly propsSchema: JsonSchemaObject | null;
15
+ }
16
+
17
+ export interface BlockCatalog {
18
+ readonly documentVersion: number | null;
19
+ readonly schemaId: string | null;
20
+ readonly rowLayouts: readonly RowLayout[];
21
+ readonly blockTypes: readonly BlockTypeCatalogEntry[];
22
+ readonly rowPropsSchema: JsonSchemaObject | null;
23
+ readonly columnPropsSchema: JsonSchemaObject | null;
24
+ readonly settingsSchema: JsonSchemaObject | null;
25
+ }
26
+
27
+ const require = createRequire(import.meta.url);
28
+
29
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
30
+ typeof value === "object" && value !== null && !Array.isArray(value);
31
+
32
+ /** Loads the live JSON Schema published by `@mailquilt/core/schema.json`. */
33
+ export const loadCoreJsonSchema = (): JsonSchemaObject => {
34
+ const schemaPath = require.resolve("@mailquilt/core/schema.json");
35
+ const raw = readFileSync(schemaPath, "utf-8");
36
+ const parsed: unknown = JSON.parse(raw);
37
+ if (!isRecord(parsed)) {
38
+ throw new Error("@mailquilt/core/schema.json did not export an object.");
39
+ }
40
+ return parsed;
41
+ };
42
+
43
+ const getNestedRecord = (
44
+ root: Record<string, unknown> | undefined,
45
+ keys: readonly string[]
46
+ ): Record<string, unknown> | undefined => {
47
+ let cursor: unknown = root;
48
+ for (const key of keys) {
49
+ if (!isRecord(cursor)) {
50
+ return undefined;
51
+ }
52
+ cursor = cursor[key];
53
+ }
54
+ return isRecord(cursor) ? cursor : undefined;
55
+ };
56
+
57
+ const extractBlockSchemas = (
58
+ schema: JsonSchemaObject
59
+ ): Map<string, JsonSchemaObject> => {
60
+ const result = new Map<string, JsonSchemaObject>();
61
+ const blockItems = getNestedRecord(schema, [
62
+ "properties",
63
+ "rows",
64
+ "items",
65
+ "properties",
66
+ "columns",
67
+ "items",
68
+ "properties",
69
+ "blocks",
70
+ "items",
71
+ ]);
72
+ const variants = blockItems?.oneOf;
73
+ if (!Array.isArray(variants)) {
74
+ return result;
75
+ }
76
+
77
+ for (const variant of variants) {
78
+ if (!isRecord(variant) || !isRecord(variant.properties)) {
79
+ continue;
80
+ }
81
+ const typeSchema = variant.properties.type;
82
+ const propsSchema = variant.properties.props;
83
+ if (
84
+ isRecord(typeSchema) &&
85
+ typeof typeSchema.const === "string" &&
86
+ isRecord(propsSchema)
87
+ ) {
88
+ result.set(typeSchema.const, propsSchema);
89
+ }
90
+ }
91
+
92
+ return result;
93
+ };
94
+
95
+ const stringArray = (value: unknown): string[] =>
96
+ Array.isArray(value)
97
+ ? value.filter((item): item is string => typeof item === "string")
98
+ : [];
99
+
100
+ /**
101
+ * Builds the live Block, Row layout, and JSON Schema catalog directly from
102
+ * `@mailquilt/core` (`BLOCK_TYPES`, `ROW_LAYOUTS`, `@mailquilt/core/schema.json`).
103
+ */
104
+ export const buildBlockCatalog = (filterBlockType?: string): BlockCatalog => {
105
+ const schema = loadCoreJsonSchema();
106
+ const blockSchemas = extractBlockSchemas(schema);
107
+
108
+ const versionSchema = getNestedRecord(schema, ["properties", "version"]);
109
+ const documentVersion =
110
+ typeof versionSchema?.const === "number" ? versionSchema.const : null;
111
+ const schemaId = typeof schema.$id === "string" ? schema.$id : null;
112
+
113
+ const allEntries: BlockTypeCatalogEntry[] = BLOCK_TYPES.map(
114
+ ({ label, type }) => {
115
+ const propsSchema = blockSchemas.get(type) ?? null;
116
+ const propProperties =
117
+ propsSchema && isRecord(propsSchema.properties)
118
+ ? Object.keys(propsSchema.properties)
119
+ : [];
120
+ const requiredProps = propsSchema
121
+ ? stringArray(propsSchema.required)
122
+ : [];
123
+ return {
124
+ label,
125
+ propNames: propProperties,
126
+ propsSchema,
127
+ requiredProps,
128
+ type,
129
+ };
130
+ }
131
+ );
132
+
133
+ // Also surface any extra block types present in schema.json even if not yet
134
+ // reflected in BLOCK_TYPES.
135
+ const knownTypes = new Set<string>(allEntries.map(({ type }) => type));
136
+ for (const [type, propsSchema] of blockSchemas.entries()) {
137
+ if (knownTypes.has(type)) {
138
+ continue;
139
+ }
140
+ const propProperties = isRecord(propsSchema.properties)
141
+ ? Object.keys(propsSchema.properties)
142
+ : [];
143
+ allEntries.push({
144
+ label: type,
145
+ propNames: propProperties,
146
+ propsSchema,
147
+ requiredProps: stringArray(propsSchema.required),
148
+ type,
149
+ });
150
+ }
151
+
152
+ const blockTypes =
153
+ filterBlockType === undefined
154
+ ? allEntries
155
+ : allEntries.filter(({ type }) => type === filterBlockType);
156
+
157
+ const rowPropsSchema =
158
+ getNestedRecord(schema, [
159
+ "properties",
160
+ "rows",
161
+ "items",
162
+ "properties",
163
+ "props",
164
+ ]) ?? null;
165
+ const columnPropsSchema =
166
+ getNestedRecord(schema, [
167
+ "properties",
168
+ "rows",
169
+ "items",
170
+ "properties",
171
+ "columns",
172
+ "items",
173
+ "properties",
174
+ "props",
175
+ ]) ?? null;
176
+ const settingsSchema =
177
+ getNestedRecord(schema, ["properties", "settings"]) ?? null;
178
+
179
+ return {
180
+ blockTypes,
181
+ columnPropsSchema,
182
+ documentVersion,
183
+ rowLayouts: [...ROW_LAYOUTS],
184
+ rowPropsSchema,
185
+ schemaId,
186
+ settingsSchema,
187
+ };
188
+ };
package/src/index.ts ADDED
@@ -0,0 +1,32 @@
1
+ export { buildBlockCatalog, loadCoreJsonSchema } from "./catalog.js";
2
+ export type {
3
+ BlockCatalog,
4
+ BlockTypeCatalogEntry,
5
+ JsonSchemaObject,
6
+ } from "./catalog.js";
7
+ export { createMcpServer, startMcpStdioServer } from "./server.js";
8
+ export type {
9
+ JsonRpcFailure,
10
+ JsonRpcResponse,
11
+ JsonRpcSuccess,
12
+ McpServer,
13
+ McpServerOptions,
14
+ } from "./server.js";
15
+ export { summarizeDocument } from "./summary.js";
16
+ export type {
17
+ BlockSummary,
18
+ ColumnSummary,
19
+ DocumentSummary,
20
+ RowSummary,
21
+ } from "./summary.js";
22
+ export { getToolDefinitions } from "./tools.js";
23
+ export type { McpToolDefinition, McpToolResult } from "./tools.js";
24
+ export {
25
+ canonicalizeRoot,
26
+ readWorkspaceFile,
27
+ resolveWorkspaceReadPath,
28
+ resolveWorkspaceWritePath,
29
+ WorkspacePathError,
30
+ writeWorkspaceFileAtomic,
31
+ } from "./workspace.js";
32
+ export type { ResolvedWorkspacePath } from "./workspace.js";