Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Improve MCP authoring reliability (#6056)
Oleg Isonend5b3f3ab802b
diff --git a/apps/builder/app/services/github-issue-report.server.test.ts b/apps/builder/app/services/github-issue-report.server.test.tsindex cdb8369924..a07a79e0fe 100644--- a/apps/builder/app/services/github-issue-report.server.test.ts+++ b/apps/builder/app/services/github-issue-report.server.test.ts@@ -62,6 +62,17 @@ describe("GitHub issue reports", () => {);});+ test("keeps version fields visible for reports from legacy clients", () => {+ const legacyReport = structuredClone(report);+ delete legacyReport.runtime;++ const body = formatIssueReport(legacyReport);++ expect(body).toContain("## Technical runtime");+ expect(body).toContain("- CLI: unknown");+ expect(body).toContain("- Node.js: unknown");+ });+test("discovers the repository installation before creating its token", async () => {const requests: Array<{ url: URL; init?: RequestInit }> = [];const request: typeof fetch = async (input, init) => {diff --git a/apps/builder/app/services/github-issue-report.server.ts b/apps/builder/app/services/github-issue-report.server.tsindex d80e9ac033..353d9940a2 100644--- a/apps/builder/app/services/github-issue-report.server.ts+++ b/apps/builder/app/services/github-issue-report.server.ts@@ -23,6 +23,21 @@ const getReportMarker = (deduplicationKey: string) =>const formatItems = (items: readonly string[]) =>items.map((item, index) => `${index + 1}. ${item}`).join("\n");+const formatRuntime = (runtime: IssueReportInput["runtime"]) =>+ [+ "## Technical runtime",+ "",+ `- CLI: ${runtime?.cliVersion ?? "unknown"}`,+ `- Node.js: ${runtime?.nodeVersion ?? "unknown"}`,+ ...(runtime === undefined+ ? []+ : [+ `- Operating system: ${runtime.os} ${runtime.osVersion} (${runtime.architecture})`,+ `- Execution mode: ${runtime.executionMode}`,+ `- API contract: ${runtime.apiContractVersion}`,+ ]),+ ].join("\n");+export const formatIssueReport = ({agent,category,@@ -72,19 +87,8 @@ ${report.technicalContext}- Reasoning effort: ${agent.reasoningEffort}- Trigger: ${trigger}- Category: ${category}-${- runtime === undefined- ? ""- : `-## Technical runtime--- CLI: ${runtime.cliVersion}-- Node.js: ${runtime.nodeVersion}-- Operating system: ${runtime.os} ${runtime.osVersion} (${runtime.architecture})-- Execution mode: ${runtime.executionMode}-- API contract: ${runtime.apiContractVersion}-`-}++${formatRuntime(runtime)}## Acceptance criteriadiff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex f3ffdbe1af..c4c80fbfbd 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -419,10 +419,11 @@ Vision-capable AI can use MCP to see what it is building:8. For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.9. For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.10. Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.-11. When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.-12. Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.-13. Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.-14. If the screenshot does not match, apply another focused mutation and repeat screenshot verification.+11. The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.+12. When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.+13. Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.+14. Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.+15. If the screenshot does not match, apply another focused mutation and repeat screenshot verification.Generated app setup:diff --git a/packages/cli/evaluations/high-impact/agent-runner.ts b/packages/cli/evaluations/high-impact/agent-runner.tsindex 0ade7572d5..e9d00b39ce 100644--- a/packages/cli/evaluations/high-impact/agent-runner.ts+++ b/packages/cli/evaluations/high-impact/agent-runner.ts@@ -153,7 +153,7 @@ export const createMinimalAgentTask = (? ["For this fixture, meta.guide already returns the required auth discovery and authoring tool schemas. Do not call list-breakpoints because responsive styling is not required, and do not call meta.get-more-tools or any other tool discovery operation. Create exactly one scoped non-secret fixture variable and keep the required state gallery expression-free. Do not call list-variables again after creating it.","After meta.guide, call inspect-auth-context exactly once. Do not call get-project-settings, list-pages, list-resources, or list-variables separately.",- 'After the context read, call create-page exactly once. Then call create-variable exactly once with {"name":"Account preview state","scopeInstanceId":"<returned-account-root-id>","value":{"type":"string","value":"signed-out"}}, substituting only the returned root id. Keep type exactly string; do not invent a state type. Then call create-resource exactly once with the returned variable id. Do not parallelize these mutations or retry failed calls. Call insert-fragment-verified only after all three succeed, using their returned ids and pagePath /account. Do not call insert-fragment or verify-bindings separately.',+ 'After the context read, call create-page exactly once. Then call create-variable exactly once with {"name":"Account preview state","scopeInstanceId":"<returned-account-root-id>","value":{"type":"string","value":"signed-out"}}, substituting only the returned root id. Keep type exactly string; do not invent a state type. Then call create-resource exactly once with {"scopeInstanceId":"<returned-account-root-id>","dataSourceName":"accountSession","resource":{"name":"Account session via server","method":"get","url":"/api/auth/session","headers":[],"searchParams":[]}}, again substituting only the returned root id. Do not set exposeAsDataSource separately, parallelize these mutations, or retry failed calls. Call insert-fragment-verified only after all three succeed, using their returned ids and pagePath /account. Do not call insert-fragment or verify-bindings separately.','Then call verify-page-responsive exactly once with {"path":"/account","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. It captures both required screenshots and runs the terminal static audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately.',]: []),@@ -189,10 +189,10 @@ export const createMinimalAgentTask = ("For this fixture, the exact sequence below supersedes every workflow and mutation meta.next suggestion. After a listed call succeeds, continue immediately to the next listed call without inspecting, repairing, updating, or repeating its result. If any call fails, stop immediately; retries and repair mutations fail this evaluation. Never call update-assets-resource or any tool not explicitly listed in these fixture constraints.","Create exactly two pages: first /blog, then /blog/:slug. Do not call create-assets-resource while creating either page. Never call create-assets-resource without a query. After both page calls succeed, make exactly two create-assets-resource calls total using the complete inputs below; any omitted query or additional resource fails this evaluation.","Database size is part of the evaluated outcome. The final project must have exactly the two intended reachable Assets queries, one materialized overview, all five source documents included without truncation, and zero embedded Markdown body bytes. Do not leave a placeholder, preview copy, stale resource, or replacement data source in the project.",- 'First call create-assets-resource exactly once with this complete overview input, substituting the returned overview root id and Blog folder id: {"name":"Published posts","scopeInstanceId":"<overview-root-id>","dataSourceName":"posts","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["folderId"],"operator":"eq","value":{"type":"literal","value":"<blog-folder-id>"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"},{"field":["id"],"direction":"asc"}],"limit":{"type":"literal","value":20},"offset":{"type":"literal","value":0},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","author"],["properties","excerpt"]]},"content":{"mode":"none"}}}. Keep literal wrappers and field-path arrays unchanged.',- 'Then call create-assets-resource exactly once with this complete detail input, substituting the returned detail root id and the same Blog folder id: {"name":"Post by slug","scopeInstanceId":"<detail-root-id>","dataSourceName":"post","query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["folderId"],"operator":"eq","value":{"type":"literal","value":"<blog-folder-id>"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"limit":{"type":"literal","value":1},"offset":{"type":"literal","value":0},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","author"]]},"content":{"mode":"markdown-body-ref"}}}. Do not call create-assets-resource again.',+ 'First call create-assets-resource exactly once with this complete overview input, substituting the returned overview root id and Blog folder id: {"name":"Published posts","scopeInstanceId":"<overview-root-id>","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["folderId"],"operator":"eq","value":{"type":"literal","value":"<blog-folder-id>"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"},{"field":["id"],"direction":"asc"}],"limit":{"type":"literal","value":20},"offset":{"type":"literal","value":0},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","author"],["properties","excerpt"]]},"content":{"mode":"none"}}}. Keep literal wrappers and field-path arrays unchanged.',+ 'Then call create-assets-resource exactly once with this complete detail input, substituting the returned detail root id and the same Blog folder id: {"name":"Post by slug","scopeInstanceId":"<detail-root-id>","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["folderId"],"operator":"eq","value":{"type":"literal","value":"<blog-folder-id>"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","author"]]},"content":{"mode":"markdown-body-ref"}}}. Do not call create-assets-resource again.','After both resources succeed, call insert-collection exactly once on the overview root with {"parentInstanceId":"<overview-root-id>","data":{"type":"expression","value":"posts.data"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h2\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><ws.element ws:tag=\"p\">{expression`collectionItem.properties.excerpt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"p\">By {expression`collectionItem.properties.author.name`}</ws.element><ws.element ws:tag=\"time\">{expression`collectionItem.properties.publishedAt ?? \\"\\"`}</ws.element><ws.element ws:tag=\"a\" href={expression`\\"/blog/\\" + collectionItem.properties.slug`}>Read article</ws.element></ws.element>"}, substituting only the returned overview root id.',- 'Then call insert-collection exactly once on the detail root with {"parentInstanceId":"<detail-root-id>","data":{"type":"expression","value":"post.data"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h1\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><ws.element ws:tag=\"p\">By {expression`collectionItem.properties.author.name`}</ws.element><$.MarkdownEmbed code={expression`collectionItem.content.text`} /></ws.element>"}, substituting only the returned detail root id. insert-collection validates and persists its bindings atomically, so do not call verify-bindings or perform any repair afterward.',+ 'Then call insert-collection exactly once on the detail root with {"parentInstanceId":"<detail-root-id>","data":{"type":"expression","value":"post.data == null ? [] : [post.data]"},"itemFragment":"<ws.element ws:tag=\"article\"><ws.element ws:tag=\"h1\">{expression`collectionItem.properties.title ?? \\"Untitled\\"`}</ws.element><ws.element ws:tag=\"p\">By {expression`collectionItem.properties.author.name`}</ws.element><$.MarkdownEmbed code={expression`collectionItem.content.text`} /></ws.element>"}, substituting only the returned detail root id. insert-collection validates and persists its bindings atomically, so do not call verify-bindings or perform any repair afterward.','After both Collections succeed, call verify-page-responsive exactly twice: first with {"path":"/blog","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}, then with {"path":"/blog/aurora-trails","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. Do not mutate, rediscover, restart preview, or capture separate screenshots or audits after verification begins. If either verification fails, stop immediately without retrying or changing the project.',]: []),diff --git a/packages/cli/evaluations/high-impact/validate.test.ts b/packages/cli/evaluations/high-impact/validate.test.tsindex 27e1f9bbbc..f9be624979 100644--- a/packages/cli/evaluations/high-impact/validate.test.ts+++ b/packages/cli/evaluations/high-impact/validate.test.ts@@ -288,6 +288,7 @@ const addMarkdownBlog = (): EvaluationProject => {"post-resource","Post",createStructuredAssetQueryResourceBody({+ result: "one",where: {all: [{ field: ["extension"], operator: "eq", value: '"md"' },@@ -300,7 +301,7 @@ const addMarkdownBlog = (): EvaluationProject => {],},sort: [],- limit: "1",+ limit: "20",offset: "0",output: {mode: "fields",diff --git a/packages/cli/evaluations/high-impact/validate.ts b/packages/cli/evaluations/high-impact/validate.tsindex 2dcbce6992..189fb06a92 100644--- a/packages/cli/evaluations/high-impact/validate.ts+++ b/packages/cli/evaluations/high-impact/validate.ts@@ -906,7 +906,7 @@ const validateMarkdownBlog = (value: "system.params.slug",normalizeExpression,}) &&- article.limit === "1" &&+ article.result === "one" &&article.output.includeMetadata === false &&hasOutputField(article.output, ["properties", "body"]) === false,"The detail Assets resource does not defer one Markdown body selected by the dynamic slug parameter."diff --git a/packages/cli/src/async-utils.ts b/packages/cli/src/async-utils.tsindex 3937c29f93..374be16378 100644--- a/packages/cli/src/async-utils.ts+++ b/packages/cli/src/async-utils.ts@@ -14,3 +14,21 @@ export const createExclusiveAsyncRunner = () => {}};};++export const withTimeout = async <Result>(+ operation: Promise<Result>,+ timeout: number,+ createTimeoutError: () => Error+) => {+ let timeoutId: NodeJS.Timeout | undefined;+ const timeoutPromise = new Promise<never>((_, reject) => {+ timeoutId = setTimeout(() => reject(createTimeoutError()), timeout);+ });+ try {+ return await Promise.race([operation, timeoutPromise]);+ } finally {+ if (timeoutId !== undefined) {+ clearTimeout(timeoutId);+ }+ }+};diff --git a/packages/cli/src/commands/mcp-checkpoint.test.ts b/packages/cli/src/commands/mcp-checkpoint.test.tsnew file mode 100644index 0000000000..bc492756b4--- /dev/null+++ b/packages/cli/src/commands/mcp-checkpoint.test.ts@@ -0,0 +1,125 @@+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, expect, test } from "vitest";+import { listProjectSessionMcpTools } from "@webstudio-is/project-build/mcp";+import { publicApiOperations } from "@webstudio-is/protocol";+import {+ assertPersistedMcpCheckpointAcknowledged,+ readPersistedMcpCheckpoint,+ updatePersistedMcpCheckpoint,+} from "./mcp-checkpoint";++const tempDirs: string[] = [];++afterEach(async () => {+ await Promise.all(+ tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))+ );+});++test("persists and acknowledges MCP checkpoints", async () => {+ const tools = listProjectSessionMcpTools(publicApiOperations);+ const dir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-checkpoint-"));+ tempDirs.push(dir);++ await updatePersistedMcpCheckpoint({+ tool: "components.coverage-plan",+ scope: { projectRoot: dir },+ structuredContent: {+ data: {+ checkpoint: {+ required: true,+ instruction:+ "Stop after this coverage-plan response and report before continuing.",+ nextCommand:+ 'node packages/cli/local.js workflow.next \'{"goal":"design-system-page","phase":"page-creation"}\'',+ },+ },+ },+ });++ await expect(+ readPersistedMcpCheckpoint({ projectRoot: dir })+ ).resolves.toEqual({+ tool: "components.coverage-plan",+ message:+ "Stop after this coverage-plan response and report before continuing.",+ nextCommand:+ 'node packages/cli/local.js workflow.next \'{"goal":"design-system-page","phase":"page-creation"}\'',+ });+ await expect(+ assertPersistedMcpCheckpointAcknowledged("components.get", tools, {+ projectRoot: dir,+ })+ ).resolves.toBeUndefined();+ await expect(+ assertPersistedMcpCheckpointAcknowledged("create-page", tools, {+ projectRoot: dir,+ })+ ).rejects.toMatchObject({+ code: "CHECKPOINT_REQUIRED",+ message: expect.stringContaining("CHECKPOINT_REQUIRED"),+ });+ await expect(+ assertPersistedMcpCheckpointAcknowledged("checkpoint.ack", tools, {+ projectRoot: dir,+ })+ ).resolves.toBeUndefined();++ await updatePersistedMcpCheckpoint({+ tool: "checkpoint.ack",+ scope: { projectRoot: dir },+ structuredContent: { data: { acknowledged: true } },+ });++ await expect(+ readPersistedMcpCheckpoint({ projectRoot: dir })+ ).resolves.toBeUndefined();+ await expect(+ assertPersistedMcpCheckpointAcknowledged("create-page", tools, {+ projectRoot: dir,+ })+ ).resolves.toBeUndefined();+});++test("isolates persisted MCP checkpoints by project", async () => {+ const dir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-projects-"));+ tempDirs.push(dir);+ await updatePersistedMcpCheckpoint({+ tool: "workflow.next",+ scope: { projectRoot: dir, projectId: "project-a" },+ structuredContent: {+ data: { checkpoint: { required: true, instruction: "Report project A" } },+ },+ });++ await expect(+ readPersistedMcpCheckpoint({ projectRoot: dir, projectId: "project-a" })+ ).resolves.toEqual(expect.objectContaining({ message: "Report project A" }));+ await expect(+ readPersistedMcpCheckpoint({ projectRoot: dir, projectId: "project-b" })+ ).resolves.toBeUndefined();+});++test("persists the checkpoint producer tool name", async () => {+ const dir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-checkpoint-"));+ tempDirs.push(dir);++ await updatePersistedMcpCheckpoint({+ tool: "future.checkpoint-tool",+ scope: { projectRoot: dir },+ structuredContent: {+ data: {+ checkpoint: {+ required: true,+ instruction: "Report this future checkpoint before continuing.",+ },+ },+ },+ });++ await expect(+ readPersistedMcpCheckpoint({ projectRoot: dir })+ ).resolves.toMatchObject({ tool: "future.checkpoint-tool" });+});diff --git a/packages/cli/src/commands/mcp-checkpoint.ts b/packages/cli/src/commands/mcp-checkpoint.tsnew file mode 100644index 0000000000..cb9b4bb0c4--- /dev/null+++ b/packages/cli/src/commands/mcp-checkpoint.ts@@ -0,0 +1,114 @@+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { cwd } from "node:process";+import path from "node:path";+import {+ getProjectSessionMcpCheckpoint,+ isReadOnlyProjectSessionMcpToolCall,+ type ProjectSessionMcpTool,+} from "@webstudio-is/project-build/mcp";+import { getLocalProjectStateDirectory } from "../config";+import { isPlainRecord } from "../type-utils";++const checkpointFilename = "mcp-checkpoint.json";++export type PersistedMcpCheckpoint = {+ tool: string;+ message: string;+ nextCommand?: string;+};++export type McpProjectScope = {+ projectRoot?: string;+ projectId?: string;+};++const getMcpCheckpointPath = ({+ projectRoot = cwd(),+ projectId,+}: McpProjectScope = {}) =>+ path.join(+ getLocalProjectStateDirectory(projectRoot, projectId),+ checkpointFilename+ );++export const readPersistedMcpCheckpoint = async (+ scope: McpProjectScope = {}+) => {+ try {+ return JSON.parse(+ await readFile(getMcpCheckpointPath(scope), "utf8")+ ) as PersistedMcpCheckpoint;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {+ return;+ }+ throw error;+ }+};++const writePersistedMcpCheckpoint = async (+ checkpoint: PersistedMcpCheckpoint,+ scope: McpProjectScope = {}+) => {+ const checkpointPath = getMcpCheckpointPath(scope);+ await mkdir(path.dirname(checkpointPath), { recursive: true });+ await writeFile(checkpointPath, JSON.stringify(checkpoint, undefined, 2));+};++export const clearPersistedMcpCheckpoint = async (+ scope: McpProjectScope = {}+) => {+ await rm(getMcpCheckpointPath(scope), { force: true });+};++export const assertPersistedMcpCheckpointAcknowledged = async (+ tool: string,+ tools: readonly ProjectSessionMcpTool[],+ scope: McpProjectScope = {}+) => {+ if (+ tool === "checkpoint.ack" ||+ isReadOnlyProjectSessionMcpToolCall(tool, tools)+ ) {+ return;+ }+ const checkpoint = await readPersistedMcpCheckpoint(scope);+ if (checkpoint === undefined) {+ return;+ }+ throw Object.assign(+ new Error(+ `CHECKPOINT_REQUIRED: ${checkpoint.message} Stop now and report the previous checkpoint to the parent/user. Only after the parent/user continues, call checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"} before calling "${tool}".`+ ),+ { code: "CHECKPOINT_REQUIRED" }+ );+};++export const getResultCheckpoint = (+ tool: string,+ structuredContent: unknown+) => {+ if (isPlainRecord(structuredContent) === false) {+ return;+ }+ return getProjectSessionMcpCheckpoint(tool, structuredContent.data);+};++export const updatePersistedMcpCheckpoint = async ({+ tool,+ structuredContent,+ scope = {},+}: {+ tool: string;+ structuredContent: unknown;+ scope?: McpProjectScope;+}) => {+ if (tool === "checkpoint.ack") {+ await clearPersistedMcpCheckpoint(scope);+ return;+ }+ const checkpoint = getResultCheckpoint(tool, structuredContent);+ if (checkpoint !== undefined) {+ await writePersistedMcpCheckpoint(checkpoint, scope);+ }+};diff --git a/packages/cli/src/commands/mcp-preview.test.ts b/packages/cli/src/commands/mcp-preview.test.tsindex 90169ffa20..ef5df6d654 100644--- a/packages/cli/src/commands/mcp-preview.test.ts+++ b/packages/cli/src/commands/mcp-preview.test.ts@@ -2,8 +2,98 @@ import { expect, test, vi } from "vitest";import {createMcpPreviewHandlers,createPreviewFreshness,+ resolveMcpPreviewInput,+ resolveMcpScreenshotInput,+ startMcpPreview,} from "./mcp-preview";+test("allocates an available port only when MCP preview omits one", async () => {+ const getAvailablePort = vi.fn(async () => 53124);++ await expect(+ resolveMcpPreviewInput({ source: "session" }, getAvailablePort)+ ).resolves.toEqual({ source: "session", port: 53124 });+ await expect(+ resolveMcpPreviewInput({ source: "session", port: 0 }, getAvailablePort)+ ).resolves.toEqual({ source: "session", port: 53124 });+ await expect(+ resolveMcpPreviewInput({ source: "session", port: 4173 }, getAvailablePort)+ ).resolves.toEqual({ source: "session", port: 4173 });+ expect(getAvailablePort).toHaveBeenCalledTimes(2);+ expect(getAvailablePort).toHaveBeenNthCalledWith(1, "127.0.0.1");+ expect(getAvailablePort).toHaveBeenNthCalledWith(2, "127.0.0.1");+});++test("allocates and reuses a collision-free port for automatic screenshots", async () => {+ const getAvailablePort = vi.fn(async () => 53124);++ await expect(+ resolveMcpScreenshotInput(+ {+ path: "/account",+ browser: "auto",+ viewport: { width: 390, height: 844 },+ },+ { running: false, url: "http://127.0.0.1:5173/" },+ getAvailablePort+ )+ ).resolves.toMatchObject({ port: 53124 });+ await expect(+ resolveMcpScreenshotInput(+ {+ path: "/account",+ browser: "auto",+ viewport: { width: 1440, height: 900 },+ },+ { running: true, url: "http://127.0.0.1:53125/" },+ getAvailablePort+ )+ ).resolves.toMatchObject({ port: 53125 });+ await expect(+ resolveMcpScreenshotInput(+ {+ path: "/account",+ browser: "auto",+ port: 4173,+ viewport: { width: 1440, height: 900 },+ },+ { running: false, url: "http://127.0.0.1:5173/" },+ getAvailablePort+ )+ ).resolves.toMatchObject({ port: 4173 });+ expect(getAvailablePort).toHaveBeenCalledOnce();+});++test("retries automatic MCP preview ports after a startup race", async () => {+ const getAvailablePort = vi+ .fn()+ .mockResolvedValueOnce(53124)+ .mockResolvedValueOnce(53125);+ const startPreview = vi+ .fn()+ .mockRejectedValueOnce(new Error("Preview server exited before ready"))+ .mockResolvedValueOnce({ url: "http://127.0.0.1:53125/" });+ const sleep = vi.fn(async () => undefined);++ await expect(+ startMcpPreview({+ input: { source: "session" },+ getAvailablePort,+ startPreview,+ sleep,+ })+ ).resolves.toEqual({ url: "http://127.0.0.1:53125/" });+ expect(startPreview).toHaveBeenNthCalledWith(1, {+ source: "session",+ port: 53124,+ });+ expect(startPreview).toHaveBeenNthCalledWith(2, {+ source: "session",+ port: 53125,+ });+ expect(sleep).toHaveBeenCalledWith(500);+});+test("does not mark a preview fresh after a newer mutation", () => {const freshness = createPreviewFreshness();const capturedRevision = freshness.capture();@@ -194,6 +284,7 @@ test("captures stale path screenshots through the restarted preview server", asytest("passes explicit preview source to preview preparation", async () => {const events: string[] = [];+ let projectVersion = 1;const preview = {status: vi.fn(() => ({url: "",@@ -210,18 +301,23 @@ test("passes explicit preview source to preview preparation", async () => {}),resolveUrl: vi.fn(),};- const prepareSessionDataFile = vi.fn(async () => undefined);+ const prepareSessionDataFile = vi.fn(async () => {+ projectVersion = 2;+ });const preparePreview = vi.fn(async (source, prepareSessionDataFile) => {events.push(`prepare:${source}`);await prepareSessionDataFile?.();return { cwd: "/tmp/generated-preview" };});const progress: string[] = [];+ const markFresh = vi.fn();const handlers = createMcpPreviewHandlers({preview,preparePreview,prepareSessionDataFile,+ getProjectVersion: () => projectVersion,+ markFresh,});await handlers.startPreview(@@ -242,6 +338,7 @@ test("passes explicit preview source to preview preparation", async () => {});expect(prepareSessionDataFile).toHaveBeenCalledOnce();+ expect(markFresh).toHaveBeenCalledWith(expect.any(Number), 2);expect(events).toEqual(["prepare:session","start:/tmp/generated-preview:true",@@ -252,6 +349,46 @@ test("passes explicit preview source to preview preparation", async () => {]);});+test("restarts a stale iterative preview for external clients", async () => {+ const preview = {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ canReuse: vi.fn(() => true),+ startAndWait: vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ resolveUrl: vi.fn(),+ };+ const preparePreview = vi.fn(async () => ({+ cwd: "/tmp/generated-preview",+ buildCacheKey: "version-2",+ }));+ const handlers = createMcpPreviewHandlers({+ preview,+ isStale: () => true,+ preparePreview,+ });++ await handlers.startPreview({ mode: "iterative" });++ expect(preparePreview).toHaveBeenCalledWith("session", undefined, {+ preserveGeneratedProject: true,+ prepareForIncrementalGeneration: true,+ });+ expect(preview.startAndWait).toHaveBeenCalledWith(+ expect.objectContaining({+ cwd: "/tmp/generated-preview",+ buildCacheKey: "version-2",+ restart: true,+ })+ );+});+test("rejects invalid external image domains before preparing preview", async () => {const preview = {status: vi.fn(() => ({@@ -427,6 +564,60 @@ test("reuses and closes one browser capture session for session screenshots", asexpect(preview.stop).toHaveBeenCalledOnce();});+test("times out a stalled screenshot after preview start and releases its session", async () => {+ let running = false;+ const stop = vi.fn(async () => {+ running = false;+ return { running: false as const };+ });+ const preview = {+ status: vi.fn(() =>+ running+ ? {+ url: "http://127.0.0.1:5173/",+ running: true as const,+ mode: "iterative" as const,+ }+ : { running: false as const }+ ),+ startAndWait: vi.fn(async () => {+ running = true;+ return {+ url: "http://127.0.0.1:5173/",+ running: true as const,+ mode: "iterative" as const,+ };+ }),+ resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),+ stop,+ };+ const close = vi.fn(async () => undefined);+ const handlers = createMcpPreviewHandlers({+ preview,+ preparePreview: vi.fn(async () => ({ cwd: "/tmp/preview" })),+ createCaptureSession: vi.fn(() => ({+ capture: vi.fn(() => new Promise<never>(() => undefined)),+ capturePage: vi.fn(),+ close,+ })) as never,+ });++ await handlers.startPreview({ source: "session", mode: "iterative" });+ await expect(+ handlers.captureScreenshot({+ path: "/",+ source: "session",+ mode: "iterative",+ viewport: { width: 1440, height: 900 },+ timeout: 5,+ })+ ).rejects.toMatchObject({ code: "SCREENSHOT_TIMEOUT" });+ expect(close).toHaveBeenCalledOnce();++ await expect(handlers.stopPreview()).resolves.toEqual({ running: false });+ expect(stop).toHaveBeenCalledOnce();+});+test("applies internal page credentials only to owned preview captures", async () => {const preview = {status: vi.fn(() => ({@@ -666,6 +857,41 @@ test("captures one session page across multiple viewports through resize", asyncexpect(preview.startAndWait).not.toHaveBeenCalled();});+test("times out a stalled responsive capture and releases its session", async () => {+ const close = vi.fn(async () => undefined);+ const preview = {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "iterative" as const,+ })),+ startAndWait: vi.fn(),+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),+ };+ const handlers = createMcpPreviewHandlers({+ preview,+ isStale: () => false,+ createCaptureSession: vi.fn(() => ({+ capture: vi.fn(),+ capturePage: vi.fn(() => new Promise<never>(() => undefined)),+ close,+ })) as never,+ });++ await expect(+ handlers.capturePageScreenshots(+ [375, 768, 1024, 1440].map((width) => ({+ path: "/responsive",+ source: "session" as const,+ mode: "iterative" as const,+ viewport: { width, height: 900 },+ timeout: 5,+ }))+ )+ ).rejects.toMatchObject({ code: "SCREENSHOT_TIMEOUT" });+ expect(close).toHaveBeenCalledOnce();+});+test.each([["browser", { browser: "chromium" as const }, { browser: "chrome" as const }],["mode", { mode: "iterative" as const }, { mode: "production" as const }],diff --git a/packages/cli/src/commands/mcp-preview.ts b/packages/cli/src/commands/mcp-preview.tsindex 26741d8640..51b65b0273 100644--- a/packages/cli/src/commands/mcp-preview.ts+++ b/packages/cli/src/commands/mcp-preview.ts@@ -1,6 +1,7 @@import {arePreviewImageDomainsEqual,createPreviewController,+ findAvailablePort,type PreviewMode,} from "../preview-server";import {@@ -8,7 +9,8 @@ import {createScreenshotCaptureSession,} from "../screenshot";import { inspectGeneratedBuildMetrics } from "../generated-build-metrics";-import { createExclusiveAsyncRunner } from "../async-utils";+import { createExclusiveAsyncRunner, withTimeout } from "../async-utils";+import { defaultScreenshotTimeout } from "@webstudio-is/project-build/visual";import {preparePreviewProject,previewDefaultTemplate,@@ -111,6 +113,77 @@ const isSameCaptureSessionConfig = (const defaultPreviewSource = "session" satisfies PreviewSource;const defaultSleep = (durationMs: number) =>new Promise<void>((resolve) => setTimeout(resolve, durationMs));++export const resolveMcpPreviewInput = async (+ input: McpPreviewInput,+ getAvailablePort: (host?: string) => Promise<number> = findAvailablePort+) => {+ if (input.port !== undefined && input.port !== 0) {+ return input;+ }+ return {+ ...input,+ port: await getAvailablePort(input.host ?? "127.0.0.1"),+ };+};++export const resolveMcpScreenshotInput = async (+ input: McpScreenshotInput,+ previewStatus: { running: boolean; url?: string },+ getAvailablePort: (host?: string) => Promise<number> = findAvailablePort+) => {+ if (+ input.url !== undefined ||+ input.baseUrl !== undefined ||+ input.source === "local" ||+ (input.port !== undefined && input.port !== 0)+ ) {+ return input;+ }+ const host = input.host ?? "127.0.0.1";+ if (previewStatus.running && previewStatus.url !== undefined) {+ const previewUrl = new URL(previewStatus.url);+ if (input.host === undefined || previewUrl.hostname === input.host) {+ const previewPort = Number(previewUrl.port);+ if (Number.isInteger(previewPort) && previewPort > 0) {+ return { ...input, port: previewPort };+ }+ }+ }+ return { ...input, port: await getAvailablePort(host) };+};++export const startMcpPreview = async <Result>({+ input,+ startPreview,+ getAvailablePort = findAvailablePort,+ sleep = defaultSleep,+}: {+ input: McpPreviewInput;+ startPreview: (input: McpPreviewInput) => Promise<Result>;+ getAvailablePort?: (host?: string) => Promise<number>;+ sleep?: (durationMs: number) => Promise<void>;+}) => {+ const attempts = input.port === undefined || input.port === 0 ? 5 : 1;+ for (let attempt = 0; attempt < attempts; attempt += 1) {+ const resolvedInput = await resolveMcpPreviewInput(input, getAvailablePort);+ try {+ return await startPreview(resolvedInput);+ } catch (error) {+ if (attempt === attempts - 1) {+ throw error;+ }+ await sleep(500);+ }+ }+ throw new Error("MCP preview did not start.");+};++const createScreenshotTimeoutError = (timeout: number) =>+ Object.assign(+ new Error(`Screenshot capture did not finish within ${timeout}ms.`),+ { code: "SCREENSHOT_TIMEOUT" }+ );const getPreviewSource = (source: PreviewSource | undefined): PreviewSource =>source ?? defaultPreviewSource;@@ -202,6 +275,22 @@ export const createMcpPreviewHandlers = ({captureSessionConfig = undefined;}};+ const captureWithTimeout = async <Result>(+ operation: () => Promise<Result>,+ timeout: number,+ resetSession?: () => Promise<void>+ ) => {+ try {+ return await withTimeout(operation(), timeout, () =>+ createScreenshotTimeoutError(timeout)+ );+ } catch (error) {+ if (resetSession !== undefined) {+ await resetSession().catch(() => undefined);+ }+ throw error;+ }+ };const getCaptureSession = async (input: McpScreenshotInput) => {if (createCaptureSession === undefined) {throw new Error("Reusable screenshot capture is unavailable.");@@ -296,7 +385,6 @@ export const createMcpPreviewHandlers = ({});progress?.report("tool screenshot preparing generated preview project");const freshness = captureFreshness();- const projectVersion = getProjectVersion();const previewProject = await preparePreview(source,prepareSessionDataFile,@@ -305,6 +393,7 @@ export const createMcpPreviewHandlers = ({prepareForIncrementalGeneration: mode === "iterative",});+ const projectVersion = getProjectVersion();progress?.report(`tool screenshot ${canReusePreview ? "refreshing" : "starting"} ${mode} preview server`);@@ -365,15 +454,21 @@ export const createMcpPreviewHandlers = ({}return result;};+ const getManagedPreviewMetadata = (input: McpScreenshotInput) =>+ input.path !== undefined && input.baseUrl === undefined+ ? { previewMode: preview.status().mode }+ : {};return {async startPreview(input: McpPreviewInput, progress?: McpToolProgress) {return await runPreviewLifecycle(async () => {const mode = input.mode ?? "iterative";const source = getPreviewSource(input.source);+ const previewWasStale = isStale();const canReusePreview =mode === "iterative" &&isPreviewTargetCompatible(input, mode, preview.status());- if (canReusePreview === false) {+ const restartPreview = canReusePreview === false || previewWasStale;+ if (restartPreview) {await closeCaptureSession();}validatePreviewServerOptions({@@ -385,7 +480,6 @@ export const createMcpPreviewHandlers = ({"tool preview.start preparing generated preview project");const freshness = captureFreshness();- const projectVersion = getProjectVersion();const previewProject = await preparePreview(source,prepareSessionDataFile,@@ -394,6 +488,7 @@ export const createMcpPreviewHandlers = ({prepareForIncrementalGeneration: mode === "iterative",});+ const projectVersion = getProjectVersion();progress?.report(`tool preview.start ${canReusePreview ? "refreshing" : "starting"} ${mode} preview server`);@@ -402,7 +497,7 @@ export const createMcpPreviewHandlers = ({mode,cwd: previewProject.cwd,buildCacheKey: previewProject.buildCacheKey,- restart: canReusePreview === false,+ restart: restartPreview,});activeSource = source;markFresh(freshness, projectVersion);@@ -428,39 +523,42 @@ export const createMcpPreviewHandlers = ({const previewReadyAt = Date.now();progress?.report(`tool screenshot capturing ${url}`);const captureOptions = getCaptureOptions(input, url);- let result: Awaited<ReturnType<typeof captureScreenshot>>;- if (- isManagedSessionPreviewCapture(input) &&- createCaptureSession !== undefined- ) {- const captureSession = await getCaptureSession(input);- result = await captureSession.capture(captureOptions);- for (- let retry = 0;- retry < 2 && result.navigation?.generatedSiteRootPresent === false;- retry += 1- ) {- progress?.report(- "tool screenshot waiting for refreshed generated route"- );- await sleep(1000);- result = await captureSession.capture(captureOptions);- }- } else {- result = await captureScreenshot({- ...captureOptions,- isJson: false,- isMcp: true,- isInteractive: false,- confirmInstall: async () => false,- });- }+ const managedCapture = isManagedSessionPreviewCapture(input);+ const timeout = input.timeout ?? defaultScreenshotTimeout;+ const result = await captureWithTimeout(+ async () => {+ if (managedCapture && createCaptureSession !== undefined) {+ const captureSession = await getCaptureSession(input);+ let captureResult = await captureSession.capture(captureOptions);+ for (+ let retry = 0;+ retry < 2 &&+ captureResult.navigation?.generatedSiteRootPresent === false;+ retry += 1+ ) {+ progress?.report(+ "tool screenshot waiting for refreshed generated route"+ );+ await sleep(1000);+ captureResult = await captureSession.capture(captureOptions);+ }+ return captureResult;+ }+ return await captureScreenshot({+ ...captureOptions,+ isJson: false,+ isMcp: true,+ isInteractive: false,+ confirmInstall: async () => false,+ });+ },+ timeout,+ managedCapture ? closeCaptureSession : undefined+ );const completedAt = Date.now();return {...assertGeneratedSiteCapture(input, result),- ...(input.path !== undefined && input.baseUrl === undefined- ? { previewMode: preview.status().mode }- : {}),+ ...getManagedPreviewMetadata(input),lifecycleTimings: {previewRefreshMs: previewReadyAt - startedAt,captureMs: completedAt - previewReadyAt,@@ -503,16 +601,24 @@ export const createMcpPreviewHandlers = ({progress?.report(`tool screenshot capturing ${new Set(urls).size} pages across ${inputs.length} viewport widths`);- const results = await (- await getCaptureSession(firstInput)- ).capturePage(- inputs.map((input, index) => {- const url = urls[index];- if (url === undefined) {- throw new Error("Screenshot URL resolution was incomplete.");- }- return getCaptureOptions(input, url);- })+ const timeout = Math.max(+ ...inputs.map((input) => input.timeout ?? defaultScreenshotTimeout)+ );+ const results = await captureWithTimeout(+ async () => {+ const captureSession = await getCaptureSession(firstInput);+ return await captureSession.capturePage(+ inputs.map((input, index) => {+ const url = urls[index];+ if (url === undefined) {+ throw new Error("Screenshot URL resolution was incomplete.");+ }+ return getCaptureOptions(input, url);+ })+ );+ },+ timeout,+ closeCaptureSession);return results.map((result, index) => {const input = inputs[index];@@ -521,9 +627,7 @@ export const createMcpPreviewHandlers = ({}return {...assertGeneratedSiteCapture(input, result),- ...(input.path !== undefined && input.baseUrl === undefined- ? { previewMode: preview.status().mode }- : {}),+ ...getManagedPreviewMetadata(input),};});});diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.tsindex 237e58db93..b2946005eb 100644--- a/packages/cli/src/commands/mcp.test.ts+++ b/packages/cli/src/commands/mcp.test.ts@@ -7,10 +7,10 @@ import {listProjectSessionMcpTools,} from "@webstudio-is/project-build/mcp";import { publicApiOperations } from "@webstudio-is/protocol";+import { updatePersistedMcpCheckpoint } from "./mcp-checkpoint";import { __testing__, mcpOptions, prepareMcpProjectSession } from "./mcp";const {- assertPersistedMcpCheckpointAcknowledged,assertSingleOpCallToolSupported,applyMcpRunOptions,createMcpResourceErrorPayload,@@ -27,99 +27,22 @@ const {validateSingleOpCallInput,isMcpToolCallFailure,getMcpToolCallError,- readPersistedMcpCheckpoint,- updatePersistedMcpCheckpoint,executeMcpRunCall,- resolveMcpPreviewInput,- resolveMcpScreenshotInput,- startMcpPreview,+ withMcpHost,} = __testing__;-test("allocates an available port only when MCP preview omits one", async () => {- const getAvailablePort = vi.fn(async () => 53124);+test("disposes an MCP host when its operation fails", async () => {+ const dispose = vi.fn(async () => undefined);await expect(- resolveMcpPreviewInput({ source: "session" }, getAvailablePort)- ).resolves.toEqual({ source: "session", port: 53124 });- await expect(- resolveMcpPreviewInput({ source: "session", port: 0 }, getAvailablePort)- ).resolves.toEqual({ source: "session", port: 53124 });- await expect(- resolveMcpPreviewInput({ source: "session", port: 4173 }, getAvailablePort)- ).resolves.toEqual({ source: "session", port: 4173 });- expect(getAvailablePort).toHaveBeenCalledTimes(2);- expect(getAvailablePort).toHaveBeenNthCalledWith(1, "127.0.0.1");- expect(getAvailablePort).toHaveBeenNthCalledWith(2, "127.0.0.1");-});--test("allocates and reuses a collision-free port for automatic screenshots", async () => {- const getAvailablePort = vi.fn(async () => 53124);-- await expect(- resolveMcpScreenshotInput(- {- path: "/account",- browser: "auto",- viewport: { width: 390, height: 844 },- },- { running: false, url: "http://127.0.0.1:5173/" },- getAvailablePort+ withMcpHost(+ async () => ({ dispose }),+ async () => {+ throw new Error("operation failed");+ })- ).resolves.toMatchObject({ port: 53124 });- await expect(- resolveMcpScreenshotInput(- {- path: "/account",- browser: "auto",- viewport: { width: 1440, height: 900 },- },- { running: true, url: "http://127.0.0.1:53125/" },- getAvailablePort- )- ).resolves.toMatchObject({ port: 53125 });- await expect(- resolveMcpScreenshotInput(- {- path: "/account",- browser: "auto",- port: 4173,- viewport: { width: 1440, height: 900 },- },- { running: false, url: "http://127.0.0.1:5173/" },- getAvailablePort- )- ).resolves.toMatchObject({ port: 4173 });- expect(getAvailablePort).toHaveBeenCalledOnce();-});--test("retries automatic MCP preview ports after a startup race", async () => {- const getAvailablePort = vi- .fn()- .mockResolvedValueOnce(53124)- .mockResolvedValueOnce(53125);- const startPreview = vi- .fn()- .mockRejectedValueOnce(new Error("Preview server exited before ready"))- .mockResolvedValueOnce({ url: "http://127.0.0.1:53125/" });- const sleep = vi.fn(async () => undefined);-- await expect(- startMcpPreview({- input: { source: "session" },- getAvailablePort,- startPreview,- sleep,- })- ).resolves.toEqual({ url: "http://127.0.0.1:53125/" });- expect(startPreview).toHaveBeenNthCalledWith(1, {- source: "session",- port: 53124,- });- expect(startPreview).toHaveBeenNthCalledWith(2, {- source: "session",- port: 53125,- });- expect(sleep).toHaveBeenCalledWith(500);+ ).rejects.toThrow("operation failed");+ expect(dispose).toHaveBeenCalledOnce();});test("classifies structured MCP tool failures for nonzero CLI exit", () => {@@ -604,90 +527,6 @@ test("explains extract-slot selectors in focused MCP discovery", async () => {);});-test("persists MCP checkpoints across single-op-call processes", async () => {- const tools = listProjectSessionMcpTools(publicApiOperations);- const dir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-checkpoint-"));- tempDirs.push(dir);-- await updatePersistedMcpCheckpoint({- tool: "components.coverage-plan",- scope: { projectRoot: dir },- structuredContent: {- data: {- checkpoint: {- required: true,- instruction:- "Stop after this coverage-plan response and report before continuing.",- nextCommand:- 'node packages/cli/local.js workflow.next \'{"goal":"design-system-page","phase":"page-creation"}\'',- },- },- },- });-- await expect(- readPersistedMcpCheckpoint({ projectRoot: dir })- ).resolves.toEqual({- tool: "components.coverage-plan",- message:- "Stop after this coverage-plan response and report before continuing.",- nextCommand:- 'node packages/cli/local.js workflow.next \'{"goal":"design-system-page","phase":"page-creation"}\'',- });- await expect(- assertPersistedMcpCheckpointAcknowledged("components.get", tools, {- projectRoot: dir,- })- ).resolves.toBeUndefined();- await expect(- assertPersistedMcpCheckpointAcknowledged("create-page", tools, {- projectRoot: dir,- })- ).rejects.toMatchObject({- code: "CHECKPOINT_REQUIRED",- message: expect.stringContaining("CHECKPOINT_REQUIRED"),- });- await expect(- assertPersistedMcpCheckpointAcknowledged("checkpoint.ack", tools, {- projectRoot: dir,- })- ).resolves.toBeUndefined();-- await updatePersistedMcpCheckpoint({- tool: "checkpoint.ack",- scope: { projectRoot: dir },- structuredContent: { data: { acknowledged: true } },- });-- await expect(- readPersistedMcpCheckpoint({ projectRoot: dir })- ).resolves.toBeUndefined();- await expect(- assertPersistedMcpCheckpointAcknowledged("create-page", tools, {- projectRoot: dir,- })- ).resolves.toBeUndefined();-});--test("isolates persisted MCP checkpoints by selected project", async () => {- const dir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-projects-"));- tempDirs.push(dir);- await updatePersistedMcpCheckpoint({- tool: "workflow.next",- scope: { projectRoot: dir, projectId: "project-a" },- structuredContent: {- data: { checkpoint: { required: true, instruction: "Report project A" } },- },- });-- await expect(- readPersistedMcpCheckpoint({ projectRoot: dir, projectId: "project-a" })- ).resolves.toEqual(expect.objectContaining({ message: "Report project A" }));- await expect(- readPersistedMcpCheckpoint({ projectRoot: dir, projectId: "project-b" })- ).resolves.toBeUndefined();-});-test("checks persisted checkpoints before every MCP run call", async () => {const dir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-run-checkpoint-")@@ -950,30 +789,6 @@ test("preserves already structured MCP run errors", () => {});});-test("persists checkpoint producer tool name", async () => {- const dir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-checkpoint-"));- tempDirs.push(dir);-- await updatePersistedMcpCheckpoint({- tool: "future.checkpoint-tool",- scope: { projectRoot: dir },- structuredContent: {- data: {- checkpoint: {- required: true,- instruction: "Report this future checkpoint before continuing.",- },- },- },- });-- await expect(- readPersistedMcpCheckpoint({ projectRoot: dir })- ).resolves.toMatchObject({- tool: "future.checkpoint-tool",- });-});-test("parses inline MCP run JSON input", async () => {await expect(parseMcpRunInput('[{"tool":"components.find","input":{"brief":"button"}}]')diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex 89154db8d5..300758c236 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -1,15 +1,11 @@import { cwd, stdin, stdout, stderr } from "node:process";-import { mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { mkdir, readFile, writeFile } from "node:fs/promises";import path from "node:path";import {connectProjectSessionMcpServer,createProjectSessionMcpCore,createMcpStdioTransport,- getProjectSessionMcpCheckpoint,isReadOnlyProjectSessionMcpToolCall,- type ProjectSessionPreviewInput,- type ProjectSessionScreenshotInput,- type ProjectSessionMcpTool,} from "@webstudio-is/project-build/mcp";import {getProjectBasicAuthCredentials,@@ -40,12 +36,11 @@ import {getCliProjectRestorePointsFile,getCliServerApiContract,getSupportedPublicApiOperations,- loadCliProjectSessionAssetIndex,type CliServerApiContract,- writeCliProjectSessionDataFile,+ writeCliProjectSessionPreviewDataFile,} from "../project-session";import { executeProjectSessionApiOperation } from "../project-session-api";-import { createPreviewController, findAvailablePort } from "../preview-server";+import { createPreviewController } from "../preview-server";import {createScreenshotCaptureSession,installTesseractForOcr,@@ -66,7 +61,7 @@ import {import { readCliDoc } from "../docs";import { printJson } from "../json-output";import { isPlainRecord } from "../type-utils";-import { getLocalProjectStateDirectory, LOCAL_DATA_FILE } from "../config";+import { LOCAL_DATA_FILE } from "../config";import {assertMcpBatchMutationApproved,isMcpProjectsManifest,@@ -76,9 +71,19 @@ import {} from "./mcp-batch";import { apiCompatibilityHeaders } from "./api";import { importProject as importProjectCommand } from "./import";+import {+ assertPersistedMcpCheckpointAcknowledged,+ getResultCheckpoint,+ readPersistedMcpCheckpoint,+ updatePersistedMcpCheckpoint,+ type McpProjectScope,+ type PersistedMcpCheckpoint,+} from "./mcp-checkpoint";import {createMcpPreviewHandlers,createPreviewFreshness,+ resolveMcpScreenshotInput,+ startMcpPreview,} from "./mcp-preview";import type {CommonYargsArgv,@@ -105,7 +110,6 @@ export const prepareMcpProjectSession = async (};const mcpStatusPrefix = "[webstudio mcp]";-const mcpCheckpointFilename = "mcp-checkpoint.json";const renderedAuditArtifactDirectory = ".webstudio/audits";export const formatMcpStatusLine = (message: string) =>@@ -212,100 +216,6 @@ const getMcpUpdateAssetContentInput = (input: unknown) => {});};-type PersistedMcpCheckpoint = {- tool: string;- message: string;- nextCommand?: string;-};--type McpProjectScope = {- projectRoot?: string;- projectId?: string;-};--const getMcpCheckpointPath = ({- projectRoot = cwd(),- projectId,-}: McpProjectScope = {}) =>- path.join(- getLocalProjectStateDirectory(projectRoot, projectId),- mcpCheckpointFilename- );--const readPersistedMcpCheckpoint = async (scope: McpProjectScope = {}) => {- try {- return JSON.parse(- await readFile(getMcpCheckpointPath(scope), "utf8")- ) as PersistedMcpCheckpoint;- } catch (error) {- if ((error as NodeJS.ErrnoException).code === "ENOENT") {- return;- }- throw error;- }-};--const writePersistedMcpCheckpoint = async (- checkpoint: PersistedMcpCheckpoint,- scope: McpProjectScope = {}-) => {- const checkpointPath = getMcpCheckpointPath(scope);- await mkdir(path.dirname(checkpointPath), { recursive: true });- await writeFile(checkpointPath, JSON.stringify(checkpoint, undefined, 2));-};--const clearPersistedMcpCheckpoint = async (scope: McpProjectScope = {}) => {- await rm(getMcpCheckpointPath(scope), { force: true });-};--const assertPersistedMcpCheckpointAcknowledged = async (- tool: string,- tools: readonly ProjectSessionMcpTool[],- scope: McpProjectScope = {}-) => {- if (- tool === "checkpoint.ack" ||- isReadOnlyProjectSessionMcpToolCall(tool, tools)- ) {- return;- }- const checkpoint = await readPersistedMcpCheckpoint(scope);- if (checkpoint === undefined) {- return;- }- throw createMcpInputError(- `CHECKPOINT_REQUIRED: ${checkpoint.message} Stop now and report the previous checkpoint to the parent/user. Only after the parent/user continues, call checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"} before calling "${tool}".`,- "CHECKPOINT_REQUIRED"- );-};--const getResultCheckpoint = (tool: string, structuredContent: unknown) => {- if (isPlainRecord(structuredContent) === false) {- return;- }- const data = structuredContent.data;- return getProjectSessionMcpCheckpoint(tool, data);-};--const updatePersistedMcpCheckpoint = async ({- tool,- structuredContent,- scope = {},-}: {- tool: string;- structuredContent: unknown;- scope?: McpProjectScope;-}) => {- if (tool === "checkpoint.ack") {- await clearPersistedMcpCheckpoint(scope);- return;- }- const checkpoint = getResultCheckpoint(tool, structuredContent);- if (checkpoint !== undefined) {- await writePersistedMcpCheckpoint(checkpoint, scope);- }-};-const getMcpOperationInput = (command: string, input: unknown) => {if (command === "upload-asset") {return getMcpUploadAssetInput(input);@@ -922,72 +832,6 @@ const assertSingleOpCallToolSupported = (tool: string) => {}};-const resolveMcpPreviewInput = async (- input: ProjectSessionPreviewInput,- getAvailablePort: (host?: string) => Promise<number> = findAvailablePort-) => {- if (input.port !== undefined && input.port !== 0) {- return input;- }- return {- ...input,- port: await getAvailablePort(input.host ?? "127.0.0.1"),- };-};--const resolveMcpScreenshotInput = async (- input: ProjectSessionScreenshotInput,- previewStatus: { running: boolean; url: string },- getAvailablePort: (host?: string) => Promise<number> = findAvailablePort-) => {- if (- input.url !== undefined ||- input.baseUrl !== undefined ||- input.source === "local" ||- (input.port !== undefined && input.port !== 0)- ) {- return input;- }- const host = input.host ?? "127.0.0.1";- if (previewStatus.running) {- const previewUrl = new URL(previewStatus.url);- if (input.host === undefined || previewUrl.hostname === input.host) {- const previewPort = Number(previewUrl.port);- if (Number.isInteger(previewPort) && previewPort > 0) {- return { ...input, port: previewPort };- }- }- }- return { ...input, port: await getAvailablePort(host) };-};--const startMcpPreview = async <Result>({- input,- startPreview,- getAvailablePort = findAvailablePort,- sleep = async (durationMs) =>- await new Promise<void>((resolve) => setTimeout(resolve, durationMs)),-}: {- input: ProjectSessionPreviewInput;- startPreview: (input: ProjectSessionPreviewInput) => Promise<Result>;- getAvailablePort?: (host?: string) => Promise<number>;- sleep?: (durationMs: number) => Promise<void>;-}) => {- const attempts = input.port === undefined || input.port === 0 ? 5 : 1;- for (let attempt = 0; attempt < attempts; attempt += 1) {- const resolvedInput = await resolveMcpPreviewInput(input, getAvailablePort);- try {- return await startPreview(resolvedInput);- } catch (error) {- if (attempt === attempts - 1) {- throw error;- }- await sleep(500);- }- }- throw new Error("MCP preview did not start.");-};-const createCliMcpHost = async ({projectRoot = cwd(),projectId,@@ -1041,17 +885,12 @@ const createCliMcpHost = async ({pagePath),prepareSessionDataFile: async () => {- const snapshot = getLoadedProjectSessionSnapshot(session);- const assetIndex = await loadCliProjectSessionAssetIndex(- snapshot,- apiConnection,- path.join(projectRoot, LOCAL_ASSETS_DIR)- );- await writeCliProjectSessionDataFile(- snapshot,- path.join(projectRoot, LOCAL_DATA_FILE),- { origin: connection.origin, assetIndex }- );+ await writeCliProjectSessionPreviewDataFile({+ session,+ connection: apiConnection,+ path: path.join(projectRoot, LOCAL_DATA_FILE),+ assetsDirectory: path.join(projectRoot, LOCAL_ASSETS_DIR),+ });},});type ScreenshotResult = Awaited<@@ -1181,7 +1020,21 @@ const createCliMcpHost = async ({startPreview: async (resolvedInput) =>await previewHandlers.startPreview(resolvedInput, progress),});- return { ...result, ...previewFreshness.status() };+ if (+ result.running === false ||+ result.url === undefined ||+ result.mode === undefined+ ) {+ throw new Error("Preview server did not start.");+ }+ return {+ ...result,+ ...previewFreshness.status(),+ url: result.url,+ pid: result.pid,+ running: true,+ mode: result.mode,+ };},async getPreviewStatus() {return { ...preview.status(), ...previewFreshness.status() };@@ -1253,6 +1106,9 @@ const createCliMcpHost = async ({}stderr.write(`${formatMcpStatusLine(message)}\n`);},+ async dispose() {+ await previewHandlers.stopPreview();+ },};};@@ -1264,6 +1120,21 @@ const createCliMcpCore = (host: CliMcpHost) =>},});+const withMcpHost = async <+ Host extends { dispose: () => Promise<void> },+ Result,+>(+ createHost: () => Promise<Host>,+ callback: (host: Host) => Promise<Result>+) => {+ const host = await createHost();+ try {+ return await callback(host);+ } finally {+ await host.dispose().catch(() => undefined);+ }+};+type CliMcpCore = ReturnType<typeof createProjectSessionMcpCore<PublicApiCommand>>;@@ -1313,113 +1184,80 @@ const executeMcpRunCall = async ({return { result, checkpoint };};-export const __testing__ = {- createMcpStatusReporter,- formatMcpStatusLine,- assertSingleOpCallToolSupported,- assertPersistedMcpCheckpointAcknowledged,- clearPersistedMcpCheckpoint,- createMcpSingleOpCallErrorPayload,- createMcpResourceErrorPayload: (error: unknown, elapsedMs: number) => ({- ok: false,- error: {- code: getStableErrorCode(error) ?? "MCP_RESOURCE_FAILED",- message: error instanceof Error ? error.message : String(error),- },- meta: { elapsedMs },- }),- createMcpRunErrorPayload,- reportMcpRunTermination,- createMcpRunCheckpointStopPayload,- getLoadedProjectSessionSnapshot,- getResultCheckpoint,- getMcpOperationInput,- parseMcpSingleOpCallInput,- validateSingleOpCallInput,- isMcpToolCallFailure,- getMcpToolCallError,- applyMcpRunOptions,- parseMcpRunCalls,- parseMcpRunInput,- readPersistedMcpCheckpoint,- updatePersistedMcpCheckpoint,- executeMcpRunCall,- resolveMcpPreviewInput,- resolveMcpScreenshotInput,- startMcpPreview,-};-export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {if (options.tool === undefined || options.tool === "") {throw new Error("mcp single-op-call requires a tool name.");}+ const tool = options.tool;const startedAt = Date.now();stderr.write(`${formatMcpStatusLine(- `single-op-call ${options.tool} started${options.dryRun === true ? " (dry run)" : ""}`+ `single-op-call ${tool} started${options.dryRun === true ? " (dry run)" : ""}`)}\n`);try {- assertSingleOpCallToolSupported(options.tool);+ assertSingleOpCallToolSupported(tool);const input = await parseMcpSingleOpCallInput(options);- validateSingleOpCallInput(options.tool, input);- const { host, apiContract, scope } = await createCliMcpHost({- projectId: options.project,- });- assertMcpToolServerSupport(options.tool, apiContract);- const core = createCliMcpCore(host);- const persistedCheckpoint =- options.tool === "checkpoint.ack"- ? await readPersistedMcpCheckpoint(scope)- : undefined;- await assertPersistedMcpCheckpointAcknowledged(- options.tool,- core.listTools(),- scope- );- if (options.refresh === true && options.tool !== "refresh") {- await core.callTool({ name: "refresh" });- }- const result = await core.callTool({- name: options.tool,- input,- dryRun: options.dryRun,- });- if (isMcpToolCallFailure(result)) {- stderr.write(- `${formatMcpStatusLine(- `single-op-call ${options.tool} failed in ${Date.now() - startedAt}ms`- )}\n`- );- printJson(result.structuredContent);- throw new HandledCliError();- }- if (- options.tool === "checkpoint.ack" &&- persistedCheckpoint?.nextCommand !== undefined &&- isPlainRecord(result.structuredContent.data)- ) {- result.structuredContent.data.nextCommand =- persistedCheckpoint.nextCommand;- }- await updatePersistedMcpCheckpoint({- tool: options.tool,- structuredContent: result.structuredContent,- scope,- });- const session = result.structuredContent.meta.session;- const committed =- session === undefined ? "" : `; committed=${session.committed}`;- stderr.write(- `${formatMcpStatusLine(- `single-op-call ${options.tool} succeeded in ${Date.now() - startedAt}ms${committed}`- )}\n`+ validateSingleOpCallInput(tool, input);+ await withMcpHost(+ () => createCliMcpHost({ projectId: options.project }),+ async ({ host, apiContract, scope }) => {+ assertMcpToolServerSupport(tool, apiContract);+ const core = createCliMcpCore(host);+ const persistedCheckpoint =+ tool === "checkpoint.ack"+ ? await readPersistedMcpCheckpoint(scope)+ : undefined;+ await assertPersistedMcpCheckpointAcknowledged(+ tool,+ core.listTools(),+ scope+ );+ if (options.refresh === true && tool !== "refresh") {+ await core.callTool({ name: "refresh" });+ }+ const result = await core.callTool({+ name: tool,+ input,+ dryRun: options.dryRun,+ });+ if (isMcpToolCallFailure(result)) {+ stderr.write(+ `${formatMcpStatusLine(+ `single-op-call ${tool} failed in ${Date.now() - startedAt}ms`+ )}\n`+ );+ printJson(result.structuredContent);+ throw new HandledCliError();+ }+ if (+ tool === "checkpoint.ack" &&+ persistedCheckpoint?.nextCommand !== undefined &&+ isPlainRecord(result.structuredContent.data)+ ) {+ result.structuredContent.data.nextCommand =+ persistedCheckpoint.nextCommand;+ }+ await updatePersistedMcpCheckpoint({+ tool,+ structuredContent: result.structuredContent,+ scope,+ });+ const session = result.structuredContent.meta.session;+ const committed =+ session === undefined ? "" : `; committed=${session.committed}`;+ stderr.write(+ `${formatMcpStatusLine(+ `single-op-call ${tool} succeeded in ${Date.now() - startedAt}ms${committed}`+ )}\n`+ );+ if (options.printSuccess === undefined) {+ printJson(result.structuredContent);+ } else {+ options.printSuccess(result.structuredContent.data);+ }+ });- if (options.printSuccess === undefined) {- printJson(result.structuredContent);- } else {- options.printSuccess(result.structuredContent.data);- }} catch (error) {if (isHandledCliError(error)) {throw error;@@ -1430,7 +1268,7 @@ export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {});stderr.write(`${formatMcpStatusLine(- `single-op-call ${options.tool} failed in ${payload.meta.elapsedMs}ms: ${payload.error.message}`+ `single-op-call ${tool} failed in ${payload.meta.elapsedMs}ms: ${payload.error.message}`)}\n`);printJson(payload);@@ -1470,45 +1308,54 @@ const runMcpProjectsBatch = async ({`batch project ${project.id} started at call ${startCall + 1}/${project.calls.length}`)}\n`);- const { host, apiContract } = await createCliMcpHost({- projectRoot: project.root,- });- const core = createCliMcpCore(host);- const tools = new Map(core.listTools().map((tool) => [tool.name, tool]));- for (const call of project.calls.slice(startCall)) {- assertMcpToolServerSupport(call.tool, apiContract);- const tool = tools.get(call.tool);- assertMcpBatchMutationApproved({- projectId: project.id,- call,- method: tool?.annotations.method,- approved: options.approveMutations === true,- });- }- for (let index = startCall; index < project.calls.length; index++) {- const call = project.calls[index]!;- const tool = tools.get(call.tool);- await callStarted(- index,- call.dryRun || tool?.annotations.method !== "mutation"- );- const { checkpoint } = await executeMcpRunCall({- core,- call,- scope: { projectRoot: project.root },- });- await callSucceeded(index + 1);- const nextTool = project.calls[index + 1]?.tool;- if (- checkpoint !== undefined &&- index + 1 < project.calls.length &&- (nextTool === undefined ||- isReadOnlyProjectSessionMcpToolCall(nextTool, core.listTools()) ===- false)- ) {- throw createMcpInputError(checkpoint.message, "CHECKPOINT_REQUIRED");+ await withMcpHost(+ () => createCliMcpHost({ projectRoot: project.root }),+ async ({ host, apiContract }) => {+ const core = createCliMcpCore(host);+ const tools = new Map(+ core.listTools().map((tool) => [tool.name, tool])+ );+ for (const call of project.calls.slice(startCall)) {+ assertMcpToolServerSupport(call.tool, apiContract);+ const tool = tools.get(call.tool);+ assertMcpBatchMutationApproved({+ projectId: project.id,+ call,+ method: tool?.annotations.method,+ approved: options.approveMutations === true,+ });+ }+ for (let index = startCall; index < project.calls.length; index++) {+ const call = project.calls[index]!;+ const tool = tools.get(call.tool);+ await callStarted(+ index,+ call.dryRun || tool?.annotations.method !== "mutation"+ );+ const { checkpoint } = await executeMcpRunCall({+ core,+ call,+ scope: { projectRoot: project.root },+ });+ await callSucceeded(index + 1);+ const nextTool = project.calls[index + 1]?.tool;+ if (+ checkpoint !== undefined &&+ index + 1 < project.calls.length &&+ (nextTool === undefined ||+ isReadOnlyProjectSessionMcpToolCall(+ nextTool,+ core.listTools()+ ) === false)+ ) {+ throw createMcpInputError(+ checkpoint.message,+ "CHECKPOINT_REQUIRED"+ );+ }+ }}- }+ );},});const succeeded = reports.filter(@@ -1573,17 +1420,20 @@ export const mcpRun = async (options: McpRunOptions) => {const results: unknown[] = [];let core: ReturnType<typeof createProjectSessionMcpCore<PublicApiCommand>>;let scope: McpProjectScope = {};+ let disposeHost: () => Promise<void> = async () => undefined;try {const mcpHost = await createCliMcpHost({projectId: options.project,});const { host, apiContract } = mcpHost;+ disposeHost = mcpHost.dispose;scope = mcpHost.scope;for (const call of calls) {assertMcpToolServerSupport(call.tool, apiContract);}core = createCliMcpCore(host);} catch (error) {+ await disposeHost().catch(() => undefined);reportMcpRunPreflightFailure({error,startedAt,@@ -1598,87 +1448,90 @@ export const mcpRun = async (options: McpRunOptions) => {results,startedAt,});- for (const [index, call] of calls.entries()) {- const callNumber = index + 1;- activeCall = { number: callNumber, tool: call.tool };- stderr.write(- `${formatMcpStatusLine(- `run ${callNumber}/${calls.length} ${call.tool} started${call.dryRun ? " (dry run)" : ""}`- )}\n`- );- try {- const { result, checkpoint } = await executeMcpRunCall({- core,- call,- scope,- });- const session = result.structuredContent.meta.session;- const committed =- session === undefined ? "" : `; committed=${session.committed}`;+ try {+ for (const [index, call] of calls.entries()) {+ const callNumber = index + 1;+ activeCall = { number: callNumber, tool: call.tool };stderr.write(`${formatMcpStatusLine(- `run ${callNumber}/${calls.length} ${call.tool} succeeded${committed}`+ `run ${callNumber}/${calls.length} ${call.tool} started${call.dryRun ? " (dry run)" : ""}`)}\n`);- results.push({- tool: call.tool,- ok: true,- structuredContent: result.structuredContent,- });- activeCall = undefined;- const nextTool = calls[callNumber]?.tool;- if (- checkpoint !== undefined &&- callNumber < calls.length &&- (nextTool === undefined ||- isReadOnlyProjectSessionMcpToolCall(nextTool, core.listTools()) ===- false)- ) {- const checkpointStopPayload = createMcpRunCheckpointStopPayload({- checkpoint,- completedCalls: callNumber,+ try {+ const { result, checkpoint } = await executeMcpRunCall({+ core,+ call,+ scope,+ });+ const session = result.structuredContent.meta.session;+ const committed =+ session === undefined ? "" : `; committed=${session.committed}`;+ stderr.write(+ `${formatMcpStatusLine(+ `run ${callNumber}/${calls.length} ${call.tool} succeeded${committed}`+ )}\n`+ );+ results.push({+ tool: call.tool,+ ok: true,+ structuredContent: result.structuredContent,+ });+ activeCall = undefined;+ const nextTool = calls[callNumber]?.tool;+ if (+ checkpoint !== undefined &&+ callNumber < calls.length &&+ (nextTool === undefined ||+ isReadOnlyProjectSessionMcpToolCall(nextTool, core.listTools()) ===+ false)+ ) {+ const checkpointStopPayload = createMcpRunCheckpointStopPayload({+ checkpoint,+ completedCalls: callNumber,+ totalCalls: calls.length,+ results,+ elapsedMs: Date.now() - startedAt,+ });+ stderr.write(+ `${formatMcpStatusLine(+ `run stopped after ${callNumber}/${calls.length} ${call.tool}: ${checkpointStopPayload.error.message}`+ )}\n`+ );+ printJson(checkpointStopPayload);+ throw new McpRunCheckpointStop();+ }+ } catch (error) {+ activeCall = undefined;+ if (error instanceof McpRunCheckpointStop) {+ throw new HandledCliError();+ }+ const structuredError = getMcpRunError(error);+ results.push({+ tool: call.tool,+ ok: false,+ error: structuredError,+ });+ const payload = createMcpRunErrorPayload({+ error: structuredError,+ completedCalls: index,+ failedCall: callNumber,totalCalls: calls.length,results,elapsedMs: Date.now() - startedAt,});stderr.write(`${formatMcpStatusLine(- `run stopped after ${callNumber}/${calls.length} ${call.tool}: ${checkpointStopPayload.error.message}`+ `run ${callNumber}/${calls.length} ${call.tool} failed: ${payload.error.message}`)}\n`);- printJson(checkpointStopPayload);- throw new McpRunCheckpointStop();- }- } catch (error) {- activeCall = undefined;- disposeTerminationHandlers();- if (error instanceof McpRunCheckpointStop) {+ printJson(payload);throw new HandledCliError();}- const structuredError = getMcpRunError(error);- results.push({- tool: call.tool,- ok: false,- error: structuredError,- });- const payload = createMcpRunErrorPayload({- error: structuredError,- completedCalls: index,- failedCall: callNumber,- totalCalls: calls.length,- results,- elapsedMs: Date.now() - startedAt,- });- stderr.write(- `${formatMcpStatusLine(- `run ${callNumber}/${calls.length} ${call.tool} failed: ${payload.error.message}`- )}\n`- );- printJson(payload);- throw new HandledCliError();}+ } finally {+ disposeTerminationHandlers();+ await disposeHost().catch(() => undefined);}- disposeTerminationHandlers();stderr.write(`${formatMcpStatusLine(`run succeeded in ${Date.now() - startedAt}ms with ${calls.length} calls`@@ -1754,19 +1607,31 @@ export const mcp = async () => {const status = createMcpStatusReporter();let didReportClose = false;+ let disposeHost: () => Promise<void> = async () => undefined;const reportClose = () => {if (didReportClose) {return;}didReportClose = true;status.connectionClosed();+ void disposeHost().catch((error: unknown) => {+ status.connectionError(+ error instanceof Error ? error : new Error(String(error))+ );+ });};stdin.once("end", reportClose);stdin.once("close", reportClose);status.starting();- const { host, toolCount, reportLog, apiContract } = await createCliMcpHost({- projectId: options.project,- });+ const { host, toolCount, reportLog, apiContract, dispose } =+ await createCliMcpHost({+ projectId: options.project,+ });+ disposeHost = dispose;+ if (didReportClose) {+ await disposeHost().catch(() => undefined);+ return;+ }status.sessionReady();status.apiContract(apiContract);status.ready(toolCount);@@ -1784,3 +1649,32 @@ export const mcp = async (status.connectionError(error);};};++export const __testing__ = {+ createMcpStatusReporter,+ formatMcpStatusLine,+ assertSingleOpCallToolSupported,+ createMcpSingleOpCallErrorPayload,+ createMcpResourceErrorPayload: (error: unknown, elapsedMs: number) => ({+ ok: false,+ error: {+ code: getStableErrorCode(error) ?? "MCP_RESOURCE_FAILED",+ message: error instanceof Error ? error.message : String(error),+ },+ meta: { elapsedMs },+ }),+ createMcpRunErrorPayload,+ reportMcpRunTermination,+ createMcpRunCheckpointStopPayload,+ getLoadedProjectSessionSnapshot,+ getMcpOperationInput,+ parseMcpSingleOpCallInput,+ validateSingleOpCallInput,+ isMcpToolCallFailure,+ getMcpToolCallError,+ applyMcpRunOptions,+ parseMcpRunCalls,+ parseMcpRunInput,+ executeMcpRunCall,+ withMcpHost,+};diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.tsindex c2878593a0..e31bb0adf3 100644--- a/packages/cli/src/commands/preview.ts+++ b/packages/cli/src/commands/preview.ts@@ -17,7 +17,6 @@ import { join } from "node:path";import { chdir, cwd } from "node:process";import { promisify } from "node:util";import { log } from "@clack/prompts";-import { builderNamespaces } from "@webstudio-is/project-build/contracts";import {projectPreviewSources,type ProjectPreviewSource,@@ -42,8 +41,7 @@ import { sync, defaultSyncDependencies, type SyncDependencies } from "./sync";import { resolveApiConnection } from "../api-connection";import {createCliProjectSession,- loadCliProjectSessionAssetIndex,- writeCliProjectSessionDataFile,+ writeCliProjectSessionPreviewDataFile,} from "../project-session";import { LOCAL_ASSETS_DIR } from "../asset-files";import packageJson from "../../package.json" with { type: "json" };@@ -447,15 +445,10 @@ export const preparePreviewProject = async ({const connection = await resolveApiConnection();const session = createCliProjectSession({ connection });await session.initialize();- const snapshot = await session.ensureNamespaces(builderNamespaces);- const assetIndex = await loadCliProjectSessionAssetIndex(- snapshot,+ await writeCliProjectSessionPreviewDataFile({+ session,connection,- join(cwd(), LOCAL_ASSETS_DIR)- );- await writeCliProjectSessionDataFile(snapshot, undefined, {- origin: connection.origin,- assetIndex,+ assetsDirectory: join(cwd(), LOCAL_ASSETS_DIR),});},}: {diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex 16a34b4bcf..97eb059475 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -2,7 +2,7 @@// Edit markdown files in src/docs instead.export const cliDocs = {"api-use-cases":- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- `preview.status` reports whether generated output is `stale`. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\'section\' ws:style={css`padding: 32px;`}><ws.element ws:tag=\'h2\'>Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<jsonLdInstanceId>","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\'https://api.example.com/posts?tag=\' + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\'Bearer \' + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-ref"}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}\n- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-ref"}}}\n\nNotes:\n\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading Markdown files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected Markdown files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the Markdown file\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Use `result:"many"` for listings. It returns the ID-keyed map at `<dataSourceName>.data`, with `totalCount` and `hasMore` at `<dataSourceName>.meta`, and remains the default for existing queries. Bind a listing Collection to `posts.data`.\n- Use `result:"one"` for a unique detail route. It returns the selected item or `null` directly at `post.data`, always includes its `id`, and omits pagination. Bind components and page settings directly with expressions such as `post.data?.properties?.title`, `post.data?.content?.text`, and `post.data ? 200 : 404`. `result:"first"` and `result:"last"` also return a direct item or `null` but require explicit sorting.\n- Assets always executes a structured query. Omit `query` to use the default many-result query, which selects URL and optional image dimensions. Set `values.query:null` to restore it.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\'article\'><ws.element ws:tag=\'h2\'>{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\'section\'><ws.element ws:tag=\'p\'>Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.\n- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.\n\n- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## Submit marketplace product\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"marketplace-thumbnail.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"<uploadedAssetId>","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: publish {"target":"production"}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nNotes:\n\n- Wait for the production publish to complete before submitting the product for review.\n- Submission requires complete, valid marketplace metadata.\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\'section\' ws:style={css`padding: 32px;`}><ws.element ws:tag=\'h2\'>Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: bind-props {"bindings":[{"instanceId":"<jsonLdInstanceId>","name":"code","binding":{"type":"expression","value":"({ \'@context\': \'https://schema.org\', \'@type\': \'Article\', headline: post.title })"}}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- For fixed structured data, store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- For structured data containing runtime values, use `bind-props` with an expression that evaluates directly to an object or array. Do not call `JSON.stringify` or assemble JSON with string concatenation. Webstudio stores the expression as source text, evaluates it at runtime, and the `JsonLd` component validates and serializes the resulting value.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":{"--color-primary":"#2d3748","--color-accent":"#e53e3e","--space-card":"1.5rem"},"overwrite":true}\n\nNotes:\n\n- Define or overwrite multiple CSS variables atomically by including every name and value in one `vars` object.\n- Pass colors as CSS strings. Structured `hex` color components use normalized values from `0` to `1`, not `0` to `255`.\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":["--color-primary","--color-accent","--space-card"],"force":true}\n\nNotes:\n\n- Delete multiple CSS variables atomically by including every name in one `names` array. Destructive MCP calls still require the returned confirmation token before they commit.\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays and objects.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\'https://api.example.com/posts?tag=\' + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\'Bearer \' + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Query Markdown assets\n\nCommands:\n\n- MCP tool: get-asset-field-catalog {}\n- MCP tool: validate-asset-query {"query":{"where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","draft"],"operator":"ne","value":true}]},"limit":20}}\n- MCP tool: create-assets-resource {"name":"All assets","scopeInstanceId":"<instanceId>","dataSourceName":"assets"}\n- MCP tool: create-assets-resource {"name":"Published posts","scopeInstanceId":"<instanceId>","dataSourceName":"posts","query":{"result":"many","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","draft"],"operator":"ne","value":{"type":"literal","value":true}}]},"sort":[{"field":["properties","publishedAt"],"direction":"desc"}],"limit":{"type":"literal","value":20},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","slug"],["properties","publishedAt"],["properties","excerpt"]]},"content":{"mode":"none"}}}\n- MCP tool: create-assets-resource {"name":"Post by slug or ID","scopeInstanceId":"<instanceId>","dataSourceName":"post","query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":{"type":"literal","value":"md"}},{"field":["properties","slug"],"operator":"eq","value":"system.params.slug"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"],["properties","publishedAt"]]},"content":{"mode":"markdown-body-ref"}}}\n- MCP tool: list-assets-resources {}\n- MCP tool: get-assets-resource {"resourceId":"<resourceId>"}\n- MCP tool: update-assets-resource {"resourceId":"<resourceId>","values":{"query":null}}\n- MCP tool: preview-asset-query {"query":{"result":"one","where":{"all":[{"field":["extension"],"operator":"eq","value":"md"},{"field":["properties","slug"],"operator":"eq","value":"hello-world"}]},"output":{"mode":"fields","includeMetadata":false,"fields":[["properties","title"]]},"content":{"mode":"markdown-body-ref"}}}\n\nNotes:\n\n- Read the field catalog before authoring unfamiliar queries. It includes dynamic schema-less frontmatter paths such as `properties.author.name`, observed types, optionality, and mixed-type state without downloading Markdown files.\n- Minimize the deployed content database by using `output.mode:"fields"` and selecting only fields the rendered page needs. Keep `includeMetadata:false` unless the rendered value needs file metadata such as name, path, MIME type, or creation date, and avoid `output.mode:"all"` as a convenience default. Query diagnostics are returned separately and do not require metadata output. Filters and sorting may still require their referenced fields in the database.\n- Every reachable Assets data source contributes to the shared published database. Keep one final resource per rendered query. Update an existing scoped resource rather than creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicates.\n- Keep bounded overview filters, limits, and offsets literal and add a deterministic ID tie-breaker to the sort. With `content.mode:"none"`, compilation can materialize the small overview result instead of retaining its output fields across every candidate document. Use runtime expressions only for genuinely dynamic values such as the detail slug.\n- Combine filters with `where.all` (AND) and `where.any` (OR), including nested groups. Filter values, limit, and offset on a saved resource may be Webstudio expressions evaluated at render time. Preview queries use concrete JSON values.\n- Query Markdown files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database retains metadata and a document reference, then fetches only the selected Markdown files from Asset storage at runtime; it does not embed their bodies. Filter and paginate before content is loaded.\n- `full` and bounded `range` continue to request embedded file bytes. Use them only when the caller requires the complete source or a byte range.\n- In Markdown, reference sibling Assets with conventional relative URLs such as `../images/hero.png`. Deferred `markdown-body-ref` content resolves matching files against the Markdown file\'s folder and emits the correct Builder or published Asset URL. Keep external URLs absolute.\n- Markdown Embed renders sanitized authored HTML for figures, captions, audio, video, and iframes. Scripts, inline event handlers, `srcdoc`, and unsafe URL protocols are removed. Executable component composition remains separate future MDX work.\n- Preview each query with concrete values before saving it. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes must not be summed and are not separate allowances. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A completed Markdown blog should include every source document without truncation, contain no embedded Markdown bodies, and retain only its intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files.\n- Use `result:"many"` for listings. It returns the ID-keyed map at `<dataSourceName>.data`, with `totalCount` and `hasMore` at `<dataSourceName>.meta`, and remains the default for existing queries. Bind a listing Collection to `posts.data`.\n- Use `result:"one"` for a unique detail route. It returns the selected item or `null` directly at `post.data`, always includes its `id`, and omits pagination. Bind components and page settings directly with expressions such as `post.data?.properties?.title`, `post.data?.content?.text`, and `post.data ? 200 : 404`. `result:"first"` and `result:"last"` also return a direct item or `null` but require explicit sorting.\n- Assets always executes a structured query. Omit `query` to use the default many-result query, which selects URL and optional image dimensions. Set `values.query:null` to restore it.\n- `create-assets-resource` and `update-assets-resource` are the semantic authoring path. Do not construct the internal query URL, headers, or body expression manually.\n- The shared metadata index is maintained automatically and is emitted only when a configured Assets resource is reachable.\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n- MCP tool: submit-marketplace-product {"acknowledgePublicSubmission":true}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"json","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \'query Post($slug: String!) { post(slug: $slug) { title } }\', variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\'article\'><ws.element ws:tag=\'h2\'>{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\'section\'><ws.element ws:tag=\'p\'>Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',"manual-api":'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, and `json`. Use `json`\nfor all arrays and objects, including tags, selected categories, and nested API\nfilter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',"manual-llm":@@ -12,7 +12,7 @@ export const cliDocs = {"mcp-startup-epilogue":'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag=\'h2\'>Launch Kit</ws.element><ws.element ws:tag=\'p\'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag=\'button\'>Get started</ws.element></ws.element>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get-more-tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nWhen `report-issue` is available, use it when the user explicitly asks to report a problem. Also use it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. Write a complete anonymous report with the generalized user story, attempted workflow, expected behavior, actual result, recovery attempts, impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, exact unique values, or raw contextual tool data.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',"mcp-vision":- '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n\n## Visual Verification Rule\n\nFor visual/design work, use `preview.start` and `screenshot({ path })` so vision can inspect the current MCP session before finishing and verify that generated project files are current. Iterative preview is the default: it keeps one generated-site server and browser alive, regenerates changed files, and performs an ordinary page reload without Vite HMR. Use `mode: "production"` only for release-like verification; rendered audit selects it automatically. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\nAn authenticated project share URL is used with `webstudio init --link`; it is\nnot a generated-site preview URL. Project screenshots and rendered audits use\nthe generated local preview owned by the current CLI/MCP process. Do not pass a\nBuilder/share URL to `screenshot`, even without query parameters. Use `path`\nafter starting preview, or use `baseUrl` only for an intentional generated site\nthat is already running. Path captures verify the generated-site root marker\nand fail instead of returning a screenshot of Builder chrome.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Call preview.start once to keep the iterative generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- Read `preview.status.stale` before relying on generated output. When present, `renderedProjectVersion` identifies the last project version materialized into the preview; a stale preview refreshes automatically on the next managed screenshot or `preview.start` call.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate the current session in place, wait for its exact project version, and normally reload the route. The server and browser remain alive. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running generated site without starting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing. Use mode: "production" only for release-like verification.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Inspect every PNG with vision before finishing. Use mode: "production" only for release-like verification.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, call preview.start once, then use screenshot({ path, viewport }) for fast repeated checks across multiple pages. Iterative mode is the default: after MCP mutations, path screenshots regenerate changed files and reload the requested route while keeping the server and browser alive. Use mode: "production" only for release-like verification. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',+ '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n\n## Visual Verification Rule\n\nFor visual/design work, use `preview.start` and `screenshot({ path })` so vision can inspect the current MCP session before finishing and verify that generated project files are current. Iterative preview is the default: it keeps one generated-site server and browser alive, regenerates changed files, and performs an ordinary page reload without Vite HMR. Use `mode: "production"` only for release-like verification; rendered audit selects it automatically. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\nAn authenticated project share URL is used with `webstudio init --link`; it is\nnot a generated-site preview URL. Project screenshots and rendered audits use\nthe generated local preview owned by the current CLI/MCP process. Do not pass a\nBuilder/share URL to `screenshot`, even without query parameters. Use `path`\nafter starting preview, or use `baseUrl` only for an intentional generated site\nthat is already running. Path captures verify the generated-site root marker\nand fail instead of returning a screenshot of Builder chrome.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Call preview.start once to keep the iterative generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- Read `preview.status.stale` before relying on generated output. When present, `renderedProjectVersion` identifies the last project version materialized into the preview; a stale preview refreshes automatically on the next managed screenshot or `preview.start` call.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate the current session in place, wait for its exact project version, and normally reload the route. The server and browser remain alive. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running generated site without starting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing. Use mode: "production" only for release-like verification.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Inspect every PNG with vision before finishing. Use mode: "production" only for release-like verification.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, call preview.start once, then use screenshot({ path, viewport }) for fast repeated checks across multiple pages. Iterative mode is the default: after MCP mutations, path screenshots regenerate changed files and reload the requested route while keeping the server and browser alive. Use mode: "production" only for release-like verification. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',} as const;export const cliDocTitles = {diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdindex 1446a7fa38..f16dbd2c78 100644--- a/packages/cli/src/docs/api-use-cases.md+++ b/packages/cli/src/docs/api-use-cases.md@@ -145,16 +145,18 @@ Commands:Notes:-- `preview.status` reports whether generated output is `stale`. When present, `renderedProjectVersion` is the last project version materialized into the preview.+- `preview.status` reports whether generated output is `stale`. When no preview is running, `url`, `pid`, and `mode` are omitted. When present, `renderedProjectVersion` is the last project version materialized into the preview.- A managed `screenshot` or another `preview.start` refreshes stale generated output before capture.- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.+- Calling `preview.start` after a committed mutation restarts a stale iterative server so external browsers and HTTP clients receive the newly generated project.- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process's preview controller.- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.+- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.diff --git a/packages/cli/src/docs/mcp-vision.md b/packages/cli/src/docs/mcp-vision.mdindex 86dab62799..1ed2d61f16 100644--- a/packages/cli/src/docs/mcp-vision.md+++ b/packages/cli/src/docs/mcp-vision.md@@ -28,6 +28,7 @@ and fail instead of returning a screenshot of Builder chrome.- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.+- The screenshot timeout bounds browser capture after the preview is ready. A timeout returns `SCREENSHOT_TIMEOUT`, resets the reusable browser session, and releases the shared preview lifecycle for cleanup.- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.diff --git a/packages/cli/src/framework-react-router.test.ts b/packages/cli/src/framework-react-router.test.tsnew file mode 100644index 0000000000..63bb885256--- /dev/null+++ b/packages/cli/src/framework-react-router.test.ts@@ -0,0 +1,35 @@+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expect, test } from "vitest";+import { createFramework } from "./framework-react-router";++test("loads generated route templates from the preview workspace", async () => {+ const testDirectory = await mkdtemp(join(tmpdir(), "webstudio-framework-"));+ const projectDirectory = join(testDirectory, "project");+ const previewDirectory = join(testDirectory, "preview");+ const templatesDirectory = join(previewDirectory, "app", "route-templates");+ await Promise.all([+ mkdir(projectDirectory),+ mkdir(templatesDirectory, { recursive: true }),+ ]);+ await Promise.all(+ ["html.tsx", "xml.tsx", "text.tsx", "default-sitemap.tsx"].map((file) =>+ writeFile(join(templatesDirectory, file), file, "utf8")+ )+ );++ const previousDirectory = process.cwd();+ process.chdir(projectDirectory);+ try {+ const framework = await createFramework({+ preserveTemplates: true,+ templatesDirectory,+ });++ expect(framework.html({ pagePath: "/" })[0]?.template).toBe("html.tsx");+ } finally {+ process.chdir(previousDirectory);+ await rm(testDirectory, { recursive: true, force: true });+ }+});diff --git a/packages/cli/src/framework-react-router.ts b/packages/cli/src/framework-react-router.tsindex 69014dbb96..d07c167d0e 100644--- a/packages/cli/src/framework-react-router.ts+++ b/packages/cli/src/framework-react-router.ts@@ -8,7 +8,7 @@ import {import * as reactRouterComponents from "@webstudio-is/sdk-components-react-router";import {cleanupFrameworkTemplates,- routeTemplatesDirectory,+ getFrameworkTemplatesDirectory,type Framework,type FrameworkOptions,} from "./framework";@@ -16,20 +16,21 @@ import {export const createFramework = async (options: FrameworkOptions = {}): Promise<Framework> => {+ const templatesDirectory = getFrameworkTemplatesDirectory(options);const htmlTemplate = await readFile(- join(routeTemplatesDirectory, "html.tsx"),+ join(templatesDirectory, "html.tsx"),"utf8");const xmlTemplate = await readFile(- join(routeTemplatesDirectory, "xml.tsx"),+ join(templatesDirectory, "xml.tsx"),"utf8");const textTemplate = await readFile(- join(routeTemplatesDirectory, "text.tsx"),+ join(templatesDirectory, "text.tsx"),"utf8");const defaultSitemapTemplate = await readFile(- join(routeTemplatesDirectory, "default-sitemap.tsx"),+ join(templatesDirectory, "default-sitemap.tsx"),"utf8");// cleanup route templates after reading to not bloat generated codediff --git a/packages/cli/src/framework-remix.ts b/packages/cli/src/framework-remix.tsindex 8edb28229c..03934c91b3 100644--- a/packages/cli/src/framework-remix.ts+++ b/packages/cli/src/framework-remix.ts@@ -8,7 +8,7 @@ import {import * as remixComponents from "@webstudio-is/sdk-components-react-remix";import {cleanupFrameworkTemplates,- routeTemplatesDirectory,+ getFrameworkTemplatesDirectory,type Framework,type FrameworkOptions,} from "./framework";@@ -16,20 +16,21 @@ import {export const createFramework = async (options: FrameworkOptions = {}): Promise<Framework> => {+ const templatesDirectory = getFrameworkTemplatesDirectory(options);const htmlTemplate = await readFile(- join(routeTemplatesDirectory, "html.tsx"),+ join(templatesDirectory, "html.tsx"),"utf8");const xmlTemplate = await readFile(- join(routeTemplatesDirectory, "xml.tsx"),+ join(templatesDirectory, "xml.tsx"),"utf8");const textTemplate = await readFile(- join(routeTemplatesDirectory, "text.tsx"),+ join(templatesDirectory, "text.tsx"),"utf8");const defaultSitemapTemplate = await readFile(- join(routeTemplatesDirectory, "default-sitemap.tsx"),+ join(templatesDirectory, "default-sitemap.tsx"),"utf8");// cleanup route templates after reading to not bloat generated codediff --git a/packages/cli/src/framework-vike-ssg.ts b/packages/cli/src/framework-vike-ssg.tsindex 7c5af19db7..98ade5c282 100644--- a/packages/cli/src/framework-vike-ssg.ts+++ b/packages/cli/src/framework-vike-ssg.ts@@ -7,7 +7,7 @@ import {} from "@webstudio-is/sdk-components-registry/framework";import {cleanupFrameworkTemplates,- routeTemplatesDirectory,+ getFrameworkTemplatesDirectory,type Framework,type FrameworkOptions,} from "./framework";@@ -31,16 +31,17 @@ const generateVikeRoute = (pagePath: string) => {export const createFramework = async (options: FrameworkOptions = {}): Promise<Framework> => {+ const templatesDirectory = getFrameworkTemplatesDirectory(options);const htmlPageTemplate = await readFile(- join(routeTemplatesDirectory, "html", "+Page.tsx"),+ join(templatesDirectory, "html", "+Page.tsx"),"utf8");const htmlHeadTemplate = await readFile(- join(routeTemplatesDirectory, "html", "+Head.tsx"),+ join(templatesDirectory, "html", "+Head.tsx"),"utf8");const htmlDataTemplate = await readFile(- join(routeTemplatesDirectory, "html", "+data.ts"),+ join(templatesDirectory, "html", "+data.ts"),"utf8");diff --git a/packages/cli/src/framework.ts b/packages/cli/src/framework.tsindex c7c8be2e48..47f82a537f 100644--- a/packages/cli/src/framework.ts+++ b/packages/cli/src/framework.ts@@ -2,14 +2,22 @@ import { rm } from "node:fs/promises";import { join } from "node:path";import type { ComponentBuildHook, WsComponentMeta } from "@webstudio-is/sdk";-export type FrameworkOptions = { preserveTemplates?: boolean };export const routeTemplatesDirectory = join("app", "route-templates");+export type FrameworkOptions = {+ preserveTemplates?: boolean;+ templatesDirectory?: string;+};++export const getFrameworkTemplatesDirectory = (+ options: FrameworkOptions = {}+) => options.templatesDirectory ?? routeTemplatesDirectory;export const cleanupFrameworkTemplates = async ({preserveTemplates = false,+ templatesDirectory = routeTemplatesDirectory,}: FrameworkOptions = {}) => {if (preserveTemplates === false) {- await rm(routeTemplatesDirectory, { recursive: true, force: true });+ await rm(templatesDirectory, { recursive: true, force: true });}};diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex ad2b3f9521..09fe8de051 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -100,6 +100,7 @@ import { formatZodIssues } from "./zod-utils";import { createFramework as createRemixFramework } from "./framework-remix";import { createFramework as createReactRouterFramework } from "./framework-react-router";import { createFramework as createVikeSsgFramework } from "./framework-vike-ssg";+import { routeTemplatesDirectory } from "./framework";export const generatedFilesManifest = join(".webstudio",@@ -879,19 +880,17 @@ export const prebuild = async (options: {const preserveRouteTemplates =options.incremental === true || options.preserveRouteTemplates === true;+ const frameworkOptions = {+ preserveTemplates: preserveRouteTemplates,+ templatesDirectory: join(buildRoot, routeTemplatesDirectory),+ };let framework;if (options.template.includes("ssg")) {- framework = await createVikeSsgFramework({- preserveTemplates: preserveRouteTemplates,- });+ framework = await createVikeSsgFramework(frameworkOptions);} else if (options.template.includes("react-router")) {- framework = await createReactRouterFramework({- preserveTemplates: preserveRouteTemplates,- });+ framework = await createReactRouterFramework(frameworkOptions);} else {- framework = await createRemixFramework({- preserveTemplates: preserveRouteTemplates,- });+ framework = await createRemixFramework(frameworkOptions);}const assetBaseUrl = await readAssetBaseUrl(join(cwd(), "app/constants.mjs"));diff --git a/packages/cli/src/preview-server.test.ts b/packages/cli/src/preview-server.test.tsindex d9c8ee1d02..f85d7775fd 100644--- a/packages/cli/src/preview-server.test.ts+++ b/packages/cli/src/preview-server.test.ts@@ -36,6 +36,7 @@ const createDependencies = (writeFile: vi.fn(async () => undefined) as never,sleep: vi.fn(async () => undefined),killProcess: vi.fn(() => true),+ killWindowsProcessTree: vi.fn(async () => true),parentProcess: {pid: 456,once: vi.fn(),@@ -358,6 +359,17 @@ test("iterative preview starts without a production build", async () => {);});+test("preview status omits fabricated server details when stopped", () => {+ const controller = createPreviewController({+ host: "127.0.0.1",+ port: 5173,+ });++ expect(controller.status()).toEqual({+ running: false,+ });+});+test("preview controller reuses a matching persisted production build", async () => {const process = createPreviewProcess();const spawn = vi.fn(() => process);@@ -455,13 +467,19 @@ test("preview controller passes image domains to the managed server", async () =);});-test("preview controller stops the running server", async () => {+test("preview controller stops the Windows preview process tree", async () => {const process = createPreviewProcess();const buildProcess = createPreviewProcess();+ let exitListener: (() => void) | undefined;+ const killWindowsProcessTree = vi.fn(async () => {+ exitListener?.();+ return true;+ });const controller = createPreviewController({ host: "127.0.0.1", port: 5173, cwd: "/tmp/preview" },createDependencies({platform: "win32",+ killWindowsProcessTree,spawn: vi.fn().mockReturnValueOnce(buildProcess)@@ -469,7 +487,6 @@ test("preview controller stops the running server", async () => {}));resolveProcessExit(buildProcess);- let exitListener: (() => void) | undefined;vi.mocked(process.once as (event: string, callback: unknown) => unknown).mockImplementation((event, callback) => {@@ -478,25 +495,15 @@ test("preview controller stops the running server", async () => {}return process;});- vi.mocked(process.kill).mockImplementation(() => {- exitListener?.();- return true;- });-await controller.start();await expect(controller.stop()).resolves.toEqual({- url: "http://127.0.0.1:5173/",- pid: undefined,running: false,- mode: "production",});- expect(process.kill).toHaveBeenCalledOnce();+ expect(killWindowsProcessTree).toHaveBeenCalledWith(123);+ expect(process.kill).not.toHaveBeenCalled();await expect(controller.stop()).resolves.toEqual({- url: "http://127.0.0.1:5173/",- pid: undefined,running: false,- mode: "production",});});@@ -567,8 +574,11 @@ test("preview controller stops its process group before propagating termination"| undefined;signalHandler?.();+ await vi.waitFor(() => {+ expect(parentProcess.kill).toHaveBeenCalledWith(456, "SIGTERM");+ });+expect(killProcess).toHaveBeenCalledWith(-123, "SIGTERM");- expect(parentProcess.kill).toHaveBeenCalledWith(456, "SIGTERM");expect(controller.status().running).toBe(false);});diff --git a/packages/cli/src/preview-server.ts b/packages/cli/src/preview-server.tsindex 28e7072176..a1dd7425d3 100644--- a/packages/cli/src/preview-server.ts+++ b/packages/cli/src/preview-server.ts@@ -1,4 +1,5 @@import {+ execFile,spawn,type ChildProcess,type StdioOptions,@@ -27,6 +28,7 @@ export type PreviewServerResult = {export type PreviewServerDependencies = {spawn: typeof spawn;killProcess: (pid: number, signal: NodeJS.Signals) => boolean;+ killWindowsProcessTree: (pid: number) => Promise<boolean>;parentProcess: {pid: number;once: (signal: NodeJS.Signals, handler: () => void) => unknown;@@ -48,6 +50,25 @@ export type PreviewServerDependencies = {export const defaultPreviewServerDependencies: PreviewServerDependencies = {spawn,killProcess: process.kill,+ killWindowsProcessTree: (pid) =>+ new Promise((resolve, reject) => {+ execFile(+ "taskkill.exe",+ ["/pid", String(pid), "/T", "/F"],+ { windowsHide: true },+ (error) => {+ if (error === null) {+ resolve(true);+ return;+ }+ if (error.code === 128) {+ resolve(false);+ return;+ }+ reject(error);+ }+ );+ }),parentProcess: process,fetch,cp,@@ -264,11 +285,14 @@ export const startPreviewServer = (};};-const killPreviewProcess = (+const killPreviewProcess = async (previewProcess: ChildProcess,signal: NodeJS.Signals,dependencies: PreviewServerDependencies) => {+ if (dependencies.platform === "win32" && previewProcess.pid !== undefined) {+ return await dependencies.killWindowsProcessTree(previewProcess.pid);+ }if (dependencies.platform !== "win32" && previewProcess.pid !== undefined) {try {return dependencies.killProcess(-previewProcess.pid, signal);@@ -293,10 +317,10 @@ export const waitForPreviewExit = async (process: ChildProcess) => {};export type PreviewControllerResult = {- url: string;+ url?: string;pid?: number;running: boolean;- mode: PreviewMode;+ mode?: PreviewMode;};type PreviewControllerStartOptions = Partial<PreviewServerOptions> & {@@ -532,16 +556,21 @@ export const createPreviewController = (const activeServer = server;server = undefined;removeTerminationHandlers();- try {- if (activeServer !== undefined) {- killPreviewProcess(activeServer.process, "SIGTERM", dependencies);- }- } finally {+ if (activeServer === undefined) {dependencies.parentProcess.kill(dependencies.parentProcess.pid,signal);+ return;}+ void killPreviewProcess(activeServer.process, "SIGTERM", dependencies)+ .catch(() => undefined)+ .finally(() => {+ dependencies.parentProcess.kill(+ dependencies.parentProcess.pid,+ signal+ );+ });};terminationHandlers.set(signal, handler);dependencies.parentProcess.once(signal, handler);@@ -555,12 +584,17 @@ export const createPreviewController = (server.process.killed === false &&server.process.exitCode === null &&server.process.signalCode === null;- const getStatus = (): PreviewControllerResult => ({- url: getPreviewUrl(currentOptions),- pid: server?.process.pid,- running: isRunning(),- mode: currentOptions.mode ?? "production",- });+ const getStatus = (): PreviewControllerResult => {+ if (isRunning() === false) {+ return { running: false };+ }+ return {+ url: getPreviewUrl(currentOptions),+ pid: server?.process.pid,+ running: true,+ mode: currentOptions.mode ?? "production",+ };+ };const resolveOptions = (options: PreviewControllerStartOptions): PreviewServerOptions => {@@ -608,13 +642,16 @@ export const createPreviewController = () {return;}- await new Promise<void>((resolve, reject) => {+ const exited = new Promise<void>((resolve, reject) => {process.once("error", reject);process.once("exit", () => resolve());- if (killPreviewProcess(process, "SIGTERM", dependencies) === false) {- resolve();- }});+ if (+ (await killPreviewProcess(process, "SIGTERM", dependencies)) === false+ ) {+ return;+ }+ await exited;};const start = async (options: PreviewControllerStartOptions = {}@@ -690,13 +727,14 @@ export const createPreviewController = (dependencies);const result = await start(options);+ const url = result.url ?? getPreviewUrl(currentOptions);const requiredAssetNames =result.mode === "production"? await getPreviewCssAssetNames(currentCwd, dependencies): [];try {await waitForPreviewReady(- result.url,+ url,{ isRunning, requiredAssetNames, requiredProject },dependencies);@@ -707,7 +745,7 @@ export const createPreviewController = (formatPreviewServerStartupError({message: error.message,output,- url: result.url,+ url,}));}diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.tsindex 27bf1e4aa9..77a16cbe1b 100644--- a/packages/cli/src/project-session.test.ts+++ b/packages/cli/src/project-session.test.ts@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";import { afterEach, describe, expect, test, vi } from "vitest";import { createBuilderStateFromSnapshot } from "@webstudio-is/project-build/state";import { createBuilderStateFreshness } from "@webstudio-is/project-build/state";+import { builderNamespaces } from "@webstudio-is/project-build/contracts";import { createStructuredAssetQueryResourceBody } from "@webstudio-is/sdk";import {createLocalProjectBundleFromSessionSnapshot,@@ -16,6 +17,7 @@ import {getCliProjectRestorePointsFile,getSupportedPublicApiOperations,loadCliProjectSessionAssetIndex,+ writeCliProjectSessionPreviewDataFile,} from "./project-session";test("adds anonymous local runtime metadata only to issue reports", () => {@@ -353,19 +355,20 @@ describe("CLI/server operation contract", () => {});});-test("creates preview bundle from project session snapshot", () => {- const marketplaceProduct = {- category: "pageTemplates" as const,- name: "Session template",- thumbnailAssetId: "asset-1",- author: "Webstudio",- email: "[email protected]",- website: "https://example.com",- issues: "",- description: "A reusable project-session template.",- };+const previewMarketplaceProduct = {+ category: "pageTemplates" as const,+ name: "Session template",+ thumbnailAssetId: "asset-1",+ author: "Webstudio",+ email: "[email protected]",+ website: "https://example.com",+ issues: "",+ description: "A reusable project-session template.",+};++const createPreviewSessionSnapshot = () => {const state = createBuilderStateFromSnapshot({- marketplaceProduct,+ marketplaceProduct: previewMarketplaceProduct,pages: {homePageId: "home",rootFolderId: "root",@@ -409,7 +412,38 @@ test("creates preview bundle from project session snapshot", () => {instances: [["body",- { type: "instance", id: "body", component: "Body", children: [] },+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "header" },+ { type: "id", value: "main" },+ { type: "id", value: "footer" },+ ],+ },+ ],+ [+ "header",+ {+ type: "instance",+ id: "header",+ component: "Box",+ children: [],+ },+ ],+ [+ "main",+ { type: "instance", id: "main", component: "Box", children: [] },+ ],+ [+ "footer",+ {+ type: "instance",+ id: "footer",+ component: "Box",+ children: [],+ },],["design-system-body",@@ -432,25 +466,37 @@ test("creates preview bundle from project session snapshot", () => {},],],+ props: [],+ styles: [],+ styleSources: [],+ styleSourceSelections: [],+ dataSources: [],+ resources: [],+ assets: [],+ breakpoints: [],});+ return {+ projectId: "project",+ buildId: "build",+ version: 7,+ state,+ freshness: createBuilderStateFreshness({ state, version: 7 }),+ compatibilityVersion: "test",+ compatibility: {+ sessionVersion: "test",+ runtimeContractVersion: "test-runtime",+ projectSchemaVersion: "test-schema",+ },+ };+};+test("creates preview bundle from complete project session snapshot", async () => {+ const snapshot = createPreviewSessionSnapshot();const assetIndex = { marker: "derived-index" } as never;- const bundle = createLocalProjectBundleFromSessionSnapshot(- {- projectId: "project",- buildId: "build",- version: 7,- state,- freshness: createBuilderStateFreshness({ state, version: 7 }),- compatibilityVersion: "test",- compatibility: {- sessionVersion: "test",- runtimeContractVersion: "test-runtime",- projectSchemaVersion: "test-schema",- },- },- { origin: "https://assets.example.com", assetIndex }- );+ const bundle = createLocalProjectBundleFromSessionSnapshot(snapshot, {+ origin: "https://assets.example.com",+ assetIndex,+ });expect(bundle.origin).toBe("https://assets.example.com");expect(bundle.assetIndex).toBe(assetIndex);@@ -460,12 +506,50 @@ test("creates preview bundle from project session snapshot", () => {expect(bundle.build.pages.pages).toEqual(bundle.pages);expect(bundle.build.instances.map(([id]) => id)).toEqual(["body",+ "header",+ "main",+ "footer","design-system-body",]);- expect(bundle.build.marketplaceProduct).toEqual(marketplaceProduct);+ expect(bundle.build.marketplaceProduct).toEqual(previewMarketplaceProduct);expect(bundle.assetFolders).toEqual([expect.objectContaining({ id: "asset-folder", name: "Images" }),]);++ const directory = await createTemporaryDirectory();+ const path = join(directory, "data.json");+ const ensureNamespaces = vi.fn(async () => snapshot);+ await writeCliProjectSessionPreviewDataFile({+ session: { ensureNamespaces },+ connection: {+ projectId: "project",+ origin: "https://assets.example.com",+ authToken: "token",+ },+ path,+ assetsDirectory: directory,+ });++ expect(ensureNamespaces).toHaveBeenCalledWith(builderNamespaces);+ const written = JSON.parse(await readFile(path, "utf8")) as {+ build: {+ instances: Array<[string, { children: Array<{ value: string }> }]>;+ styles: unknown[];+ };+ };+ expect(+ written.build.instances[0]?.[1].children.map(({ value }) => value)+ ).toEqual(["header", "main", "footer"]);+ expect(written.build.styles).toEqual([]);+});++test("rejects incomplete project session snapshots before preview generation", () => {+ const snapshot = createPreviewSessionSnapshot();+ snapshot.state.styles = undefined;++ expect(() => createLocalProjectBundleFromSessionSnapshot(snapshot)).toThrow(+ "Project session is missing preview data: styles"+ );});describe("cli project session transport", () => {diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.tsindex 06b5f30043..1224195075 100644--- a/packages/cli/src/project-session.ts+++ b/packages/cli/src/project-session.ts@@ -37,12 +37,17 @@ import {type ProjectSessionStorage,type ProjectSessionTransport,} from "@webstudio-is/project-build/project-session";-import type { BuilderNamespace } from "@webstudio-is/project-build/contracts";+import {+ builderNamespaces,+ webstudioDataNamespaces,+ type BuilderNamespace,+} from "@webstudio-is/project-build/contracts";import {createBuilderStateFromBuildData,createBuilderStateFromSerializedSnapshot,createSerializedBuilderBuildDataFromState,createSerializedBuilderStateSnapshotFromState,+ getMissingBuilderStateNamespaces,type BuilderBuildDataSnapshot,type SerializedBuilderStateSnapshot,} from "@webstudio-is/project-build/state";@@ -591,6 +596,15 @@ export const createLocalProjectBundleFromSessionSnapshot = (assetIndex?: PublishedProjectBundle["assetIndex"];} = {}): PublishedProjectBundle => {+ const missing = getMissingBuilderStateNamespaces(+ snapshot.state,+ webstudioDataNamespaces+ );+ if (missing.length > 0) {+ throw new Error(+ `Project session is missing preview data: ${missing.join(", ")}`+ );+ }const pages = snapshot.state.pages;if (pages === undefined) {throw new Error("Project session pages namespace is missing.");@@ -639,3 +653,26 @@ export const writeCliProjectSessionDataFile = async (const data = createLocalProjectBundleFromSessionSnapshot(snapshot, options);await writeFileAtomic(path, `${JSON.stringify(data, undefined, 2)}\n`);};++export const writeCliProjectSessionPreviewDataFile = async ({+ session,+ connection,+ path,+ assetsDirectory = LOCAL_ASSETS_DIR,+}: {+ session: Pick<CliProjectSession, "ensureNamespaces">;+ connection: ApiConnection;+ path?: string;+ assetsDirectory?: string;+}) => {+ const snapshot = await session.ensureNamespaces(builderNamespaces);+ const assetIndex = await loadCliProjectSessionAssetIndex(+ snapshot,+ connection,+ assetsDirectory+ );+ await writeCliProjectSessionDataFile(snapshot, path, {+ origin: connection.origin,+ assetIndex,+ });+};diff --git a/packages/cli/src/screenshot-browser-cdp.test.ts b/packages/cli/src/screenshot-browser-cdp.test.tsindex c617ed78f0..f9055c032e 100644--- a/packages/cli/src/screenshot-browser-cdp.test.ts+++ b/packages/cli/src/screenshot-browser-cdp.test.ts@@ -581,7 +581,10 @@ test("ignores lifecycle readiness from child frames", async () => {},createDependencies({ socket }))- ).rejects.toThrow("Page did not reach networkidle");+ ).rejects.toMatchObject({+ code: "SCREENSHOT_TIMEOUT",+ message: expect.stringContaining("Page did not reach networkidle"),+ });});test("reuses one browser process across screenshot captures", async () => {@@ -850,6 +853,99 @@ test("restarts the shared browser once after an unexpected exit", async () => {expect(dependencies.rm).toHaveBeenCalledTimes(2);});+test("retries browser startup before capturing a viewport batch", async () => {+ const failedBrowser = new FakeBrowserProcess();+ const activeBrowser = new FakeBrowserProcess();+ const dependencies = createDependencies();+ vi.mocked(dependencies.spawnBrowser)+ .mockImplementationOnce(() => {+ setTimeout(() => failedBrowser.emit("exit", 21), 0);+ return failedBrowser as never;+ })+ .mockImplementationOnce(() => activeBrowser as never);+ vi.mocked(dependencies.readFile)+ .mockImplementationOnce(async () => await new Promise(() => undefined))+ .mockResolvedValue("9222\n/devtools/browser/1\n");+ dependencies.createWebSocket = vi.fn(+ () => new FakeWebSocket() as unknown as WebSocket+ );+ const options = {+ url: "https://example.com",+ output: "/tmp/current.png",+ width: 800,+ height: 600,+ browserPath: "/usr/bin/chromium",+ waitUntil: "networkidle" as const,+ waitForTimeout: 0,+ timeout: 1000,+ };++ const session = await createBrowserScreenshotSession(options, dependencies);+ await session.capturePage([+ options,+ { ...options, output: "/tmp/mobile.png", width: 375 },+ { ...options, output: "/tmp/tablet.png", width: 768 },+ { ...options, output: "/tmp/desktop.png", width: 1440 },+ ]);+ await session.close();++ expect(dependencies.spawnBrowser).toHaveBeenCalledTimes(2);+ expect(dependencies.writeFile).toHaveBeenCalledTimes(4);+});++test("reports browser startup exit diagnostics without local paths", async () => {+ const dependencies = createDependencies();+ vi.mocked(dependencies.spawnBrowser).mockImplementation(() => {+ const browserProcess = new FakeBrowserProcess();+ setTimeout(() => browserProcess.emit("exit", 21), 0);+ return browserProcess as never;+ });+ vi.mocked(dependencies.readFile).mockImplementation(+ async () => await new Promise(() => undefined)+ );++ await expect(+ createBrowserScreenshotSession(+ {+ url: "https://example.com",+ output: "/tmp/current.png",+ width: 800,+ height: 600,+ browserPath: "/Users/example/Applications/Chromium",+ waitUntil: "networkidle",+ waitForTimeout: 0,+ timeout: 1000,+ },+ dependencies+ )+ ).rejects.toMatchObject({+ message:+ "Browser exited before its DevTools endpoint became ready (exit code 21). Check the browser installation or set WEBSTUDIO_BROWSER_PATH to a supported Chromium executable.",+ });+});++test("does not restart a browser session after cleanup", async () => {+ const dependencies = createDependencies();+ const options = {+ url: "https://example.com",+ output: "/tmp/closed.png",+ width: 800,+ height: 600,+ browserPath: "/usr/bin/chromium",+ waitUntil: "networkidle" as const,+ waitForTimeout: 0,+ timeout: 1000,+ };+ const session = await createBrowserScreenshotSession(options, dependencies);++ await session.close();++ await expect(session.capture(options)).rejects.toThrow(+ "Browser screenshot session was closed."+ );+ expect(dependencies.spawnBrowser).toHaveBeenCalledOnce();+});+test("captures full page and returns DevTools layout metrics", async () => {const browserProcess = new FakeBrowserProcess();const socket = new FakeWebSocket();diff --git a/packages/cli/src/screenshot-browser-cdp.ts b/packages/cli/src/screenshot-browser-cdp.tsindex 683dd49277..f77fc47fb4 100644--- a/packages/cli/src/screenshot-browser-cdp.ts+++ b/packages/cli/src/screenshot-browser-cdp.ts@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { spawn, type ChildProcess } from "node:child_process";import type { ScreenshotWaitUntil } from "@webstudio-is/project-build/visual";+import { withTimeout } from "./async-utils";type BrowserProcess = Pick<ChildProcess, "kill" | "once">;@@ -100,27 +101,18 @@ const delay = (ms: number) =>new Promise<void>((resolveDelay) => setTimeout(resolveDelay, ms));const createTimeoutError = (message: string, timeout: number) =>- new Error(`${message} within ${timeout}ms.`);+ Object.assign(new Error(`${message} within ${timeout}ms.`), {+ code: "SCREENSHOT_TIMEOUT",+ });const withDeadline = async <Result>(promise: Promise<Result>,message: string,timeout: number-): Promise<Result> => {- let timeoutId: NodeJS.Timeout | undefined;- const timeoutPromise = new Promise<never>((_, reject) => {- timeoutId = setTimeout(() => {- reject(createTimeoutError(message, timeout));- }, timeout);- });- try {- return await Promise.race([promise, timeoutPromise]);- } finally {- if (timeoutId !== undefined) {- clearTimeout(timeoutId);- }- }-};+): Promise<Result> =>+ await withTimeout(promise, timeout, () =>+ createTimeoutError(message, timeout)+ );const measureDuration = async <Result>(operation: () => Promise<Result>) => {const startedAt = Date.now();@@ -1185,16 +1177,19 @@ const getScreenshotCaptureParams = async ({class BrowserSessionClosedError extends Error {}+const getBrowserExitMessage = (message: string, reason?: string) =>+ `${message}${reason === undefined ? "" : ` (${reason})`}. Check the browser installation or set WEBSTUDIO_BROWSER_PATH to a supported Chromium executable.`;+type BrowserRuntime = {userDataDir: string;browserProcess: BrowserProcess;- browserClosed: Promise<void>;+ browserClosed: Promise<string | undefined>;port: string;running: boolean;close: () => Promise<void>;};-const startBrowserRuntime = async (+const startBrowserRuntimeOnce = async (options: BrowserScreenshotOptions,dependencies: BrowserScreenshotDependencies): Promise<BrowserRuntime> => {@@ -1211,20 +1206,34 @@ const startBrowserRuntime = async (}));let running = true;- const browserClosed = new Promise<void>((resolveClosed) => {- const close = () => {+ const browserClosed = new Promise<string | undefined>((resolveClosed) => {+ const close = (reason?: string) => {running = false;- resolveClosed();+ resolveClosed(reason);};- browserProcess.once("exit", close);- browserProcess.once("error", close);+ browserProcess.once("exit", (code, signal) =>+ close(+ typeof code === "number"+ ? `exit code ${code}`+ : typeof signal === "string"+ ? `signal ${signal}`+ : undefined+ )+ );+ browserProcess.once("error", (error) => {+ const code = "code" in error ? error.code : undefined;+ close(code === undefined ? undefined : `spawn error ${code}`);+ });});try {const { port } = await Promise.race([waitForDevToolsPort(userDataDir, dependencies, options.timeout),- browserClosed.then(() => {+ browserClosed.then((reason) => {throw new BrowserSessionClosedError(- "Browser exited before its DevTools endpoint became ready."+ getBrowserExitMessage(+ "Browser exited before its DevTools endpoint became ready",+ reason+ ));}),]);@@ -1264,6 +1273,20 @@ const startBrowserRuntime = async (}};+const startBrowserRuntime = async (+ options: BrowserScreenshotOptions,+ dependencies: BrowserScreenshotDependencies+) => {+ try {+ return await startBrowserRuntimeOnce(options, dependencies);+ } catch (error) {+ if (error instanceof BrowserSessionClosedError === false) {+ throw error;+ }+ }+ return await startBrowserRuntimeOnce(options, dependencies);+};+const capturePageWithBrowserRuntime = async (runtime: BrowserRuntime,optionsList: readonly BrowserScreenshotOptions[],@@ -1278,9 +1301,12 @@ const capturePageWithBrowserRuntime = async (const layouts: BrowserScreenshotLayout[] = [];try {await Promise.race([- runtime.browserClosed.then(() => {+ runtime.browserClosed.then((reason) => {throw new BrowserSessionClosedError(- "Browser exited before screenshot capture completed."+ getBrowserExitMessage(+ "Browser exited before screenshot capture completed",+ reason+ ));}),(async () => {@@ -1637,12 +1663,18 @@ export const createBrowserScreenshotSession = async (): Promise<BrowserScreenshotSession> => {let runtime = await startBrowserRuntime(options, dependencies);let restartPromise: Promise<BrowserRuntime> | undefined;+ let closed = false;const restart = async (failedRuntime: BrowserRuntime) => {if (runtime !== failedRuntime) {return runtime;}restartPromise ??= (async () => {await failedRuntime.close();+ if (closed) {+ throw new BrowserSessionClosedError(+ "Browser screenshot session was closed."+ );+ }const next = await startBrowserRuntime(options, dependencies);runtime = next;restartPromise = undefined;@@ -1653,12 +1685,18 @@ export const createBrowserScreenshotSession = async (const captureWithRestart = async <Result>(capture: (activeRuntime: BrowserRuntime) => Promise<Result>) => {+ if (closed) {+ throw new BrowserSessionClosedError(+ "Browser screenshot session was closed."+ );+ }for (let attempt = 0; attempt < 2; attempt += 1) {const activeRuntime = runtime;try {return await capture(activeRuntime);} catch (error) {if (+ closed ||attempt === 1 ||(error instanceof BrowserSessionClosedError === false &&activeRuntime.running)@@ -1692,6 +1730,7 @@ export const createBrowserScreenshotSession = async ();},async close() {+ closed = true;await runtime.close();},};diff --git a/packages/cli/src/screenshot.test.ts b/packages/cli/src/screenshot.test.tsindex 8d0693eeba..ecc9306e0b 100644--- a/packages/cli/src/screenshot.test.ts+++ b/packages/cli/src/screenshot.test.ts@@ -382,9 +382,9 @@ describe("captureScreenshot", () => {test("resets a reusable capture session after browser startup rejects", async () => {const spawnBrowser = vi.fn(() => ({kill: vi.fn(() => true),- once: vi.fn((event: string, listener: () => void) => {+ once: vi.fn((event: string, listener: (error: Error) => void) => {if (event === "error") {- setTimeout(listener, 0);+ setTimeout(() => listener(new Error("spawn failed")), 0);}}),}));@@ -410,7 +410,7 @@ test("resets a reusable capture session after browser startup rejects", async ()"Browser exited before its DevTools endpoint became ready.");await session.close();- expect(spawnBrowser).toHaveBeenCalledTimes(2);+ expect(spawnBrowser).toHaveBeenCalledTimes(4);});describe("browser installation", () => {diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex dd25bef6e6..a9c5340f1b 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -67016,6 +67016,10 @@ export const runtimeOperationContractData = [query: {type: "object",properties: {+ result: {+ type: "string",+ enum: ["many", "one", "first", "last"],+ },where: {$ref: "#/$defs/__schema1",},@@ -67180,7 +67184,14 @@ export const runtimeOperationContractData = [],},},- required: ["where", "sort", "limit", "offset", "content"],+ required: [+ "result",+ "where",+ "sort",+ "limit",+ "offset",+ "content",+ ],additionalProperties: {},},configurationError: {@@ -67402,6 +67413,10 @@ export const runtimeOperationContractData = [query: {type: "object",properties: {+ result: {+ type: "string",+ enum: ["many", "one", "first", "last"],+ },where: {$ref: "#/$defs/__schema1",},@@ -67566,7 +67581,14 @@ export const runtimeOperationContractData = [],},},- required: ["where", "sort", "limit", "offset", "content"],+ required: [+ "result",+ "where",+ "sort",+ "limit",+ "offset",+ "content",+ ],additionalProperties: {},},configurationError: {diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex bc2331f484..053800a263 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -970,14 +970,18 @@ describe("project session mcp adapter", () => {})).not.toThrow();for (const command of ["preview.start", "preview.status", "preview.stop"]) {+ const outputSchema = getSuccessfulOutputDataSchema(+ visualTools.find((tool) => tool.name === command)?.outputSchema+ );expect(- getSuccessfulOutputDataSchema(- visualTools.find((tool) => tool.name === command)?.outputSchema- ),+ outputSchema,`Missing MCP output schema for ${command}`).toMatchObject({type: "object",- required: ["url", "running", "mode"],+ required:+ command === "preview.start"+ ? ["url", "running", "mode"]+ : ["running"],properties: {url: { type: "string" },pid: { type: "integer" },@@ -3874,6 +3878,10 @@ describe("project session mcp adapter", () => {name: "meta.get_more_tools",input: { tools: ["meta.get_more_tools", "meta.get-more-tools"] },});+ const underscoreToolDetails = await adapter.callTool({+ name: "meta.get-more-tools",+ input: { tools: ["insert_fragment"] },+ });const insertFragmentDetails = await adapter.callTool({name: "meta.get-more-tools",input: { tools: ["insert-fragment"] },@@ -3884,6 +3892,15 @@ describe("project session mcp adapter", () => {});expect(session.initialize).not.toHaveBeenCalled();+ expect(underscoreToolDetails.structuredContent.data).toEqual(+ expect.objectContaining({+ missingTools: [],+ count: 1,+ tools: expect.arrayContaining([+ expect.objectContaining({ name: "insert-fragment" }),+ ]),+ })+ );expect(index.structuredContent.data).toEqual(expect.objectContaining({readThisFirst: expect.stringContaining(@@ -4615,36 +4632,28 @@ describe("project session mcp adapter", () => {"collectionItem.properties.author.name"),}),- detailFragment: expect.objectContaining({- fragment: expect.stringContaining("post.data?.content?.text"),+ detailCollection: expect.objectContaining({+ data: {+ type: "expression",+ value: "post.data == null ? [] : [post.data]",+ },+ itemFragment: expect.stringContaining(+ "collectionItem.content.text"+ ),}),}),workflow: expect.arrayContaining([- expect.stringContaining(- 'meta.get-more-tools with {"tools":["create-assets-resource"]}'- ),- expect.stringContaining(- "Upload all Markdown source files together in one upload-assets call"- ),+ expect.stringContaining("meta.get-more-tools once"),expect.stringContaining('"format":"md"'),- expect.stringContaining("Do not create companion JSON descriptors"),- expect.stringContaining("exactly two Builder pages"),- expect.stringContaining("do not dry-run it"),- expect.stringContaining('fixed path "/blog"'),- expect.stringContaining('dynamic path "/blog/:slug"'),- expect.stringContaining("Do not create one page per post"),- expect.stringContaining("exactly one final Assets resource"),+ expect.stringContaining("do not create companion files"),+ expect.stringContaining('"/blog/:slug"'),+ expect.stringContaining("create one page per post"),+ expect.stringContaining("exactly one scoped Assets resource"),+ expect.stringContaining("only dynamic value"),expect.stringContaining(- "bounded metadata-only result can be materialized"+ "Both bindings must remain editable Collections"),- expect.stringContaining("only one materialized overview query"),- expect.stringContaining('content.mode:"markdown-body-ref"'),- expect.stringContaining('result:"one"'),- expect.stringContaining("do not wrap the detail result"),- expect.stringContaining('"value":"posts.data"'),- expect.stringContaining("only the Markdown document reference"),- expect.stringContaining('field:["extension"]'),- expect.stringContaining("both pages load their content from Assets"),+ expect.stringContaining("Assets-backed content"),]),tools: expect.arrayContaining([expect.objectContaining({ name: "upload-assets" }),@@ -7540,11 +7549,7 @@ describe("project session mcp adapter", () => {getSchemaProperties(listedTools.tools.find(({ name }) => name === "audit")?.inputSchema)- ).toMatchObject({- cursor: { type: "string" },- limit: { type: "integer", minimum: 1, maximum: 200 },- verbose: { type: "boolean" },- });+ ).toEqual({ verbose: { type: "boolean" } });expect(getSchemaProperties(listedTools.tools.find(({ name }) => name === "define-css-variable")@@ -7562,7 +7567,7 @@ describe("project session mcp adapter", () => {listedTools.tools.find(({ name }) => name === "list-instances")?.inputSchema).maxDepth- ).toMatchObject({ type: "integer", minimum: 0 });+ ).toBeUndefined();expect(getSchemaProperties(listedTools.tools.find(({ name }) => name === "publish")?.inputSchemadiff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex f8f92f808b..fd774f5797 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -313,12 +313,19 @@ export type ProjectSessionPreviewResult = {mode: ProjectSessionPreviewMode;};+export type ProjectSessionPreviewStatusResult = {+ url?: string;+ pid?: number;+ running: boolean;+ mode?: ProjectSessionPreviewMode;+};+type StartPreview = (input: ProjectSessionPreviewInput,progress?: McpToolProgress) => Promise<ProjectSessionPreviewResult>;-type GetPreviewStatus = () => Promise<ProjectSessionPreviewResult>;-type StopPreview = () => Promise<ProjectSessionPreviewResult>;+type GetPreviewStatus = () => Promise<ProjectSessionPreviewStatusResult>;+type StopPreview = () => Promise<ProjectSessionPreviewStatusResult>;export type ProjectSessionImportInput = {to: string;@@ -1295,7 +1302,8 @@ const screenshotInputSchema = {timeout: {type: "number",default: defaultScreenshotTimeout,- description: "Maximum milliseconds to wait for page readiness.",+ description:+ "Maximum milliseconds for browser capture after preview is ready.",},source: {type: "string",@@ -2458,20 +2466,28 @@ const refreshDataSchema = {additionalProperties: false,} as const satisfies InputJsonSchema;-const previewDataSchema = {+const previewStatusDataSchema = {type: "object",properties: {url: { type: "string" },pid: { type: "integer" },running: { type: "boolean" },- mode: { type: "string", enum: projectSessionPreviewModes },+ mode: {+ type: "string",+ enum: projectSessionPreviewModes,+ },stale: { type: "boolean" },renderedProjectVersion: { type: "integer" },},- required: ["url", "running", "mode"],+ required: ["running"],additionalProperties: false,} as const satisfies InputJsonSchema;+const previewDataSchema = {+ ...previewStatusDataSchema,+ required: ["url", "running", "mode"],+} as const satisfies InputJsonSchema;+const restorePointSummaryDataSchema = getZodObjectSchema(projectSessionRestorePointSummarySchema);@@ -3306,7 +3322,7 @@ const previewTools: readonly ProjectSessionMcpTool[] = [description:"Return the active generated-site preview server URL and process state for screenshot-based verification.",inputSchema: emptyInputSchema,- outputSchema: getMcpOutputSchema(previewDataSchema),+ outputSchema: getMcpOutputSchema(previewStatusDataSchema),mcpExamples: getMcpExamples("preview.status"),annotations: {command: "preview.status",@@ -3326,7 +3342,7 @@ const previewTools: readonly ProjectSessionMcpTool[] = [description:"Stop the active generated-site preview server owned by this MCP session.",inputSchema: emptyInputSchema,- outputSchema: getMcpOutputSchema(previewDataSchema),+ outputSchema: getMcpOutputSchema(previewStatusDataSchema),mcpExamples: getMcpExamples("preview.stop"),annotations: {command: "preview.stop",@@ -5582,21 +5598,17 @@ const metaGoalGuides = ["preview-asset-query","create-page","create-assets-resource",- "insert-fragment-verified","insert-collection","verify-page-responsive",],workflow: [- 'Call meta.get-more-tools with {"tools":["create-assets-resource"]} once for the complete nested query contract. Use exact tool names, not brief search, and do not repeat discovery for this workflow.',- 'Create one Blog asset folder. Upload all Markdown source files together in one upload-assets call with assetsDir ".webstudio/assets". Put queryable metadata such as slug, title, author, publishedAt, excerpt, and draft in each file\'s frontmatter. Every file must use {"name":"<filename>.md","type":"file","format":"md","folderId":"<blog-folder-id>","meta":{}}. Do not create companion JSON descriptors, use a combined format value, or retry a failed mutation; report its actionable error instead.',- 'Ensure the blog has exactly two Builder pages: an overview at the fixed path "/blog" and one detail page at the dynamic path "/blog/:slug". Create each page once with a committed call; do not dry-run it. Both pages load their content from Assets resources. Do not create one page per post or copy Markdown content into page-specific static structures.',- "Every reachable Assets data source contributes its query to one shared published database. Keep exactly one final Assets resource for the overview and one for the detail page. Never create a placeholder, preview copy, or repair replacement; update the existing scoped resource when requirements change and remove obsolete duplicates.",- 'Field paths are arrays of segments, for example field:["extension"]. Literal query values use {"type":"literal","value":"..."}; raw strings are runtime expressions. Keep every overview filter value, limit, and offset literal so the bounded metadata-only result can be materialized instead of retaining its fields across every article. Use a deterministic secondary ID sort. Query Markdown posts with static extension and blog-folder constraints before any dynamic condition. Use output.mode:"fields", includeMetadata:false, and only fields rendered by that route.',- 'Keep content.mode:"none" on the overview and use content.mode:"markdown-body-ref" only on the detail route. Set result:"one" on the detail query, use exactly one dynamic value, system.params.slug, omit limit and offset, and select only the title and author metadata rendered above Markdown Embed. The published database keeps only the Markdown document reference and fetches the selected body from Asset storage at runtime.',- "Call create-assets-resource exactly once with recipe.overviewResource after substituting the returned /blog root id and Blog folder id. Then call it exactly once with recipe.detailResource after substituting the returned /blog/:slug root id and the same Blog folder id.",- 'Call insert-collection exactly once with the entire recipe.overviewCollection object, changing only parentInstanceId to the returned overview root id. Call insert-fragment-verified exactly once with recipe.detailFragment, changing only parentInstanceId to the detail root id. Keep the listing data object exactly as {"type":"expression","value":"posts.data"} and bind detail fields directly from post.data; do not wrap the detail result in a Collection or call meta.get-more-tools again.',- "Validate both queries and preview the detail query with one concrete slug before saving dynamic expressions. Query-preview diagnostics report this query separately from the merged published database; use the merged database measurement when checking the deployment limit. The merged database must contain every source document without truncation, no embedded Markdown contents, and only one materialized overview query.",- "Verify only after both insertions succeed and confirm that both pages load their content from Assets. Call verify-page-responsive once for /blog and once for one concrete detail route, including empty/not-found behavior, before finishing. If any call fails, stop and report it without retrying.",+ 'Call meta.get-more-tools once with {"tools":["create-assets-resource"]}; the recipe below supplies the remaining inputs.',+ 'Create one asset folder named exactly "Blog", then call upload-assets exactly once with all Markdown files and assetsDir ".webstudio/assets". Put slug, title, author, publishedAt, excerpt, and draft in frontmatter. Each asset uses {"name":"<filename>.md","type":"file","format":"md","folderId":"<blog-folder-id>","meta":{}}; do not create companion files.',+ 'Create exactly two pages once: "/blog" and "/blog/:slug". Do not dry-run page creation, create one page per post, or copy Markdown into static page content.',+ "Substitute the returned folder id in both recipe queries. Validate both, then preview the detail query with one concrete slug. Keep overview values literal and keep system.params.slug as the detail query's only dynamic value.",+ 'Create exactly one scoped Assets resource per page by copying recipe.overviewResource and recipe.detailResource unchanged except for id placeholders. Keep the detail query result as "one"; Collection accepts this single-result object. Do not add query defaults or create placeholder resources.',+ "Insert recipe.overviewCollection under the overview root and recipe.detailCollection under the detail root. Use each object unchanged except for parentInstanceId. Both bindings must remain editable Collections; do not replace the detail Collection with a static fragment.",+ 'After both insertions succeed, call verify-page-responsive once for "/blog" and once for one concrete detail path with desktop and mobile viewports. Confirm Assets-backed content and empty/not-found behavior. Stop on an error instead of retrying.',],recipe: {overviewResource: {@@ -5686,10 +5698,14 @@ const metaGoalGuides = [itemFragment:'<ws.element ws:tag="article"><ws.element ws:tag="h2">{expression`collectionItem.properties.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">{expression`collectionItem.properties.excerpt ?? ""`}</ws.element><ws.element ws:tag="p">By {expression`collectionItem.properties.author.name`}</ws.element><ws.element ws:tag="time">{expression`collectionItem.properties.publishedAt ?? ""`}</ws.element><ws.element ws:tag="a" href={expression`"/blog/" + collectionItem.properties.slug`}>Read article</ws.element></ws.element>',},- detailFragment: {+ detailCollection: {parentInstanceId: "<detail-root-id>",- fragment:- '<ws.element ws:tag="article"><ws.element ws:tag="h1">{expression`post.data?.properties?.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">By {expression`post.data?.properties?.author?.name ?? ""`}</ws.element><$.MarkdownEmbed code={expression`post.data?.content?.text ?? ""`} /></ws.element>',+ data: {+ type: "expression",+ value: "post.data == null ? [] : [post.data]",+ },+ itemFragment:+ '<ws.element ws:tag="article"><ws.element ws:tag="h1">{expression`collectionItem.properties.title ?? "Untitled"`}</ws.element><ws.element ws:tag="p">By {expression`collectionItem.properties.author.name ?? ""`}</ws.element><$.MarkdownEmbed code={expression`collectionItem.content.text ?? ""`} /></ws.element>',},},},@@ -5914,25 +5930,25 @@ const getMetaGuide = (const canDiffScreenshots = tools.some((tool) => tool.name === "screenshot.diff");+ const generalWorkflow = [+ "Use the fewest discovery calls needed for the immediate action.",+ "Call permissions or status only when the task depends on capabilities or local session freshness.",+ matches.some((tool) => tool.annotations.localCapable) &&+ matches.some((tool) => tool.name === "verify-font-assets") === false+ ? "Call refresh if cached namespaces may be stale."+ : undefined,+ "Use focused read tools to collect ids and current values.",+ "Use the smallest semantic mutation tool that matches the requested change.",+ valuesVsBindingsRule,+ "Use apply-patch only when no semantic mutation tool fits.",+ canVerifyVisually && guidance !== undefined+ ? guidance.getVisionWorkflowSummary({ includeDiff: canDiffScreenshots })+ : undefined,+ ].filter(Boolean);return {delegatedAgentRule:"Do not spend the whole phase on discovery. If you are delegated/non-streaming and the parent asks for status within 30 seconds, run exactly one shortcut command such as webstudio meta.index or one explicit webstudio mcp single-op-call command, report its command/result, and wait before the next MCP command.",- workflow: [- ...(goalGuide?.workflow ?? []),- "Use the fewest discovery calls needed for the immediate action.",- "Call permissions or status only when the task depends on capabilities or local session freshness.",- matches.some((tool) => tool.annotations.localCapable) &&- matches.some((tool) => tool.name === "verify-font-assets") === false- ? "Call refresh if cached namespaces may be stale."- : undefined,- "Use focused read tools to collect ids and current values.",- "Use the smallest semantic mutation tool that matches the requested change.",- valuesVsBindingsRule,- "Use apply-patch only when no semantic mutation tool fits.",- canVerifyVisually && guidance !== undefined- ? guidance.getVisionWorkflowSummary({ includeDiff: canDiffScreenshots })- : undefined,- ].filter(Boolean),+ workflow: goalGuide?.workflow ?? generalWorkflow,tools: matches.map((tool) =>serializeMetaGuideTool(tool, goalGuide === undefined)),@@ -5942,7 +5958,7 @@ const getMetaGuide = (more:goalGuide === undefined? "The MCP handshake provides top-level argument contracts and required fields, while this guide includes exact examples plus complete schemas for selected complex tools. Call meta.get-more-tools once with all needed tool names only when a nested input shape is not covered here or when you need server/local behavior that the guide does not cover."- : "The MCP client loads each named tool's exact argument contract before calling it. This guide includes a complete schema only for selected complex inputs. Call meta.get-more-tools once with all needed tool names only when the client does not expose a nested input shape or when you need server/local behavior that the guide does not cover.",+ : "Follow this workflow and recipe without additional discovery unless the workflow explicitly requests it.",};};@@ -6122,11 +6138,19 @@ const getWorkflowNext = (input: unknown) => {};};+const toUnderscoredToolName = (name: string) =>+ name.replace(/[^a-zA-Z0-9_]/g, "_");+const getExactToolSelection = (toolNames: readonly string[],tools: readonly ProjectSessionMcpTool[]) => {- const toolByName = new Map(tools.map((tool) => [tool.name, tool]));+ const toolByName = new Map(+ tools.map((tool) => [toUnderscoredToolName(tool.name), tool])+ );+ for (const tool of tools) {+ toolByName.set(tool.name, tool);+ }const selectedTools: ProjectSessionMcpTool[] = [];const missingTools: string[] = [];const includedToolNames = new Set<string>();@@ -6137,10 +6161,10 @@ const getExactToolSelection = (missingTools.push(requestedName);continue;}- if (includedToolNames.has(resolvedName)) {+ if (includedToolNames.has(tool.name)) {continue;}- includedToolNames.add(resolvedName);+ includedToolNames.add(tool.name);selectedTools.push(tool);}return { tools: selectedTools, missingTools };@@ -6392,11 +6416,15 @@ const getSdkInputSchema = (};};-const sdkDescribedToolNames = new Set([+const sdkDetailedInputToolNames = new Set(["meta.index","meta.guide","meta.get-more-tools","workflow.next",+]);++const sdkDescribedToolNames = new Set([+ ...sdkDetailedInputToolNames,...metaGoalGuides.flatMap(({ tools }) => tools),]);@@ -6426,7 +6454,7 @@ const toSdkTool = (tool: ProjectSessionMcpTool): SdkTool => {: {}),inputSchema: getSdkInputSchema(tool.inputSchema,- sdkDescribedToolNames.has(tool.name)+ sdkDetailedInputToolNames.has(tool.name)),...(annotations === undefined ? {} : { annotations }),};@@ -8256,7 +8284,7 @@ export const createProjectSessionMcpServer = async <...tool,name:toolNameFormat === "underscores"- ? tool.name.replace(/[^a-zA-Z0-9_]/g, "_")+ ? toUnderscoredToolName(tool.name): tool.name,}));const canonicalToolNameByExposedName = new Map<string, string>();diff --git a/packages/project-build/src/runtime/asset-resources.ts b/packages/project-build/src/runtime/asset-resources.tsindex 4d67e0eb20..19f52c3c7c 100644--- a/packages/project-build/src/runtime/asset-resources.ts+++ b/packages/project-build/src/runtime/asset-resources.ts@@ -64,6 +64,7 @@ const createAssetResourceBody = (configuration: z.output<typeof assetQueryResourceConfigurationInput>) =>createStructuredAssetQueryResourceBody({+ result: configuration.result,where: normalizeWhere(configuration.where),sort: configuration.sort,limit: normalizeResourceExpressionInput(configuration.limit),@@ -114,6 +115,7 @@ const serializeAssetResource = ({}: {query: {+ result: configuration.result,where: serializeWhere(configuration.where, unsetNameById),sort: configuration.sort,limit: unsetExpressionVariables({diff --git a/packages/project-build/src/runtime/audit.test.ts b/packages/project-build/src/runtime/audit.test.tsindex ebb1855138..e00bc7392a 100644--- a/packages/project-build/src/runtime/audit.test.ts+++ b/packages/project-build/src/runtime/audit.test.ts@@ -515,6 +515,88 @@ describe("project audit and analysis", () => {});});+ test("recognizes dynamic image alt text and htmlFor label aliases", () => {+ const instances = new Map<string, Instance>(state.instances);+ instances.set("image-link", {+ type: "instance",+ id: "image-link",+ component: "Link",+ tag: "a",+ children: [{ type: "id", value: "dynamic-image" }],+ });+ instances.set("dynamic-image", {+ type: "instance",+ id: "dynamic-image",+ component: "Image",+ tag: "img",+ children: [],+ });+ instances.set("label", {+ type: "instance",+ id: "label",+ component: "Label",+ tag: "label",+ children: [{ type: "text", value: "Email" }],+ });+ instances.set("input", {+ type: "instance",+ id: "input",+ component: "Input",+ tag: "input",+ children: [],+ });+ instances.set("body", {+ ...instances.get("body")!,+ children: [+ ...instances.get("body")!.children,+ { type: "id", value: "image-link" },+ { type: "id", value: "label" },+ { type: "id", value: "input" },+ ],+ });+ const props = new Map<string, Prop>(state.props);+ props.set("dynamic-alt", {+ id: "dynamic-alt",+ instanceId: "dynamic-image",+ name: "alt",+ type: "expression",+ value: "product.alt",+ });+ props.set("label-for", {+ id: "label-for",+ instanceId: "label",+ name: "htmlFor",+ type: "string",+ value: "email",+ });+ props.set("input-id", {+ id: "input-id",+ instanceId: "input",+ name: "id",+ type: "string",+ value: "email",+ });++ const result = audit(+ { ...state, instances, props },+ { scopes: ["accessibility"], pageId: "home" },+ { projectVersion: 1 }+ );++ expect(result.findings).not.toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ ruleId: "missing-accessible-name",+ location: expect.objectContaining({ instanceId: "image-link" }),+ }),+ expect.objectContaining({+ ruleId: "missing-form-label",+ location: expect.objectContaining({ instanceId: "input" }),+ }),+ ])+ );+ });+test("reports resource, parameter, and text expression audit values as skipped", () => {const instances = new Map<string, Instance>(state.instances);instances.set("resource-image", {diff --git a/packages/project-build/src/runtime/collection.ts b/packages/project-build/src/runtime/collection.tsindex fd47a9b367..39d4d70e41 100644--- a/packages/project-build/src/runtime/collection.ts+++ b/packages/project-build/src/runtime/collection.ts@@ -1,6 +1,5 @@import {collectionComponent,- webstudioFragment,type DataSource,type Instance,type Prop,@@ -12,6 +11,7 @@ import { componentInsertResult } from "./component-insert-contract";import type { ComponentTemplateRegistry } from "./component-template";import { bindExpressionToInstanceScope } from "./data";import { throwBuilderRuntimeError } from "./errors";+import { webstudioFragmentMutationInput } from "./fragment";import { insertIndexInput, instanceInsertModeInput } from "./instances";const collectionDataInput = z.discriminatedUnion("type", [@@ -35,7 +35,7 @@ export const insertCollectionInput = z.object({data: collectionDataInput.describe("Complete iterable for the Collection. Do not pass one indexed item."),- itemFragment: webstudioFragment.describe(+ itemFragment: webstudioFragmentMutationInput.describe("One structured repeated-item fragment. Descendant expressions may reference collectionItem and collectionItemKey."),mode: instanceInsertModeInput.optional(),diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.tsindex 57c6b4b1e8..817f3d8920 100644--- a/packages/project-build/src/runtime/components.test.ts+++ b/packages/project-build/src/runtime/components.test.ts@@ -24,6 +24,7 @@ import {import { getZodValidationIssues } from "./errors";import { getComponentTemplates } from "./component-templates";import { createEmptyWebstudioFragment } from "./component-template";+import { insertCollectionInput } from "./collection";import { isLikelyWebstudioJsxFragment, parseWebstudioJsxFragment } from "./jsx";import { inspectWebstudioJsxFragmentSyntax } from "./jsx/syntax";@@ -1416,6 +1417,77 @@ test("rejects invalid token syntax in webstudio jsx fragments", async () => {);});+test("rejects unsupported expressions in shared fragment inputs", async () => {+ const fragment = await parseWebstudioJsxFragment(+ `<$.Text>{expression\`items.map(item => item.title).join(", ")\`}</$.Text>`+ );+ const result = insertFragmentInput.safeParse({+ parentInstanceId: "parent",+ fragment,+ });+ if (result.success) {+ throw new Error("Expected fragment expression validation to fail");+ }+ const issues = getZodValidationIssues(result.error);+ expect(issues).toHaveLength(2);+ expect(issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ code: "invalid_expression",+ path: ["fragment", "instances", "0", "children", "0", "value"],+ detail: "Functions are not supported",+ }),+ expect.objectContaining({+ code: "invalid_expression",+ path: ["fragment", "instances", "0", "children", "0", "value"],+ detail: '"map" function is not supported',+ }),+ ])+ );+ expect(+ insertCollectionInput.safeParse({+ parentInstanceId: "parent",+ data: { type: "json", value: [] },+ itemFragment: fragment,+ }).success+ ).toBe(false);+});++test("uses component content models to require element children", async () => {+ const parent = createParent();+ const invalidFragment = await parseWebstudioJsxFragment(+ `<radix.Collapsible><radix.CollapsibleTrigger>Open</radix.CollapsibleTrigger></radix.Collapsible>`+ );+ expect(() =>+ insertFragment(+ createState(parent),+ { parentInstanceId: parent.id, fragment: invalidFragment },+ { createId: createIdFactory(), projectId: "project-id" }+ )+ ).toThrow('"CollapsibleTrigger" does not accept text content');++ const fragment = await parseWebstudioJsxFragment(+ `<radix.Collapsible><radix.CollapsibleTrigger><ws.element ws:tag="span">Open</ws.element></radix.CollapsibleTrigger></radix.Collapsible>`+ );+ expect(() =>+ insertFragment(+ createState(parent),+ { parentInstanceId: parent.id, fragment },+ { createId: createIdFactory(), projectId: "project-id" }+ )+ ).not.toThrow();+});++test("reports unsupported existing resource references in jsx", async () => {+ await expect(+ parseWebstudioJsxFragment(+ `<$.Form action={new ResourceValue("resource-id")} />`+ )+ ).rejects.toThrow(+ "ResourceValue requires a resource definition. Existing resource ids are not supported in JSX"+ );+});+test("converts react prop aliases in webstudio jsx fragments", async () => {expect((await parseWebstudioJsxFragment(`<$.Box className="panel">Hello</$.Box>`))diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.tsindex a1c9541d3c..b3e0f683d9 100644--- a/packages/project-build/src/runtime/components.ts+++ b/packages/project-build/src/runtime/components.ts@@ -3,7 +3,6 @@ import {elementComponent,instanceComponent,ROOT_INSTANCE_ID,- webstudioFragment,type Breakpoints,type DataSource,type DataSources,@@ -49,6 +48,7 @@ import { addZodValidationIssue, throwBuilderRuntimeError } from "./errors";import {detectFragmentTokenConflicts,insertWebstudioFragmentCopy,+ webstudioFragmentMutationInput,} from "./fragment";import {createInstanceAppendPayload,@@ -86,7 +86,7 @@ export const insertComponentInput = z.object({export const insertFragmentInput = z.object({parentInstanceId: z.string().optional(),- fragment: webstudioFragment.describe(+ fragment: webstudioFragmentMutationInput.describe("Structured Webstudio fragment produced by Webstudio JSX/template helpers. Runtime remaps fragment ids to generated project ids."),conflictResolution: conflictResolutionInput.optional(),diff --git a/packages/project-build/src/runtime/content-model.ts b/packages/project-build/src/runtime/content-model.tsindex e76cefe52f..7f9d64432e 100644--- a/packages/project-build/src/runtime/content-model.ts+++ b/packages/project-build/src/runtime/content-model.ts@@ -218,12 +218,14 @@ const isTextContentCapableInstance = ({}) => {const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });const elementContentModel = getElementContentModel(tag);+ const componentChildren = getComponentContentModel(+ metas.get(instance.component)+ ).children;return ((elementContentModel === undefined ||elementContentModel.children.length > 0) &&- getComponentContentModel(metas.get(instance.component)).children.includes(- "rich-text"- )+ (componentChildren.includes("rich-text") ||+ componentChildren.includes("text")));};@@ -459,6 +461,22 @@ export const isTreeSatisfyingContentModel = ({}}let isSatisfying = isTagSatisfying && isComponentSatisfying;+ if (+ instance.children.some((child) => child.type !== "id") &&+ isTextContentCapableInstance({+ instance,+ props,+ metas,+ htmlTagsByInstanceId,+ }) === false+ ) {+ const [, name] = parseComponentName(instance.component);+ onError?.(+ `"${name}" does not accept text content. Insert an element child instead.`,+ instanceSelector+ );+ isSatisfying = false;+ }const contentModel = getComponentContentModel(metas.get(instance.component));allowedCategories = getElementChildren(tag, allowedCategories);allowedParentCategories = contentModel.children;diff --git a/packages/project-build/src/runtime/expression-validation.ts b/packages/project-build/src/runtime/expression-validation.tsindex 692d12b5c6..6557d49d7f 100644--- a/packages/project-build/src/runtime/expression-validation.ts+++ b/packages/project-build/src/runtime/expression-validation.ts@@ -1,6 +1,6 @@import { lintExpression } from "@webstudio-is/expression";import { z } from "zod";-import type { SemanticValidationIssue } from "./errors";+import { addZodValidationIssue, type SemanticValidationIssue } from "./errors";export const getExpressionErrorMessages = (options: Parameters<typeof lintExpression>[0]@@ -12,6 +12,23 @@ export const getExpressionErrorMessages = (export const getExpressionErrors = (expression: string) =>getExpressionErrorMessages({ expression });+export const addExpressionValidationIssues = (+ context: z.RefinementCtx,+ errors: readonly string[],+ path: (string | number)[] = []+) => {+ for (const detail of errors) {+ addZodValidationIssue(context, {+ code: "invalid_expression",+ path: path.map(String),+ message: "Invalid Webstudio expression",+ constraint: "valid_webstudio_expression",+ example: "item.title",+ detail,+ });+ }+};+export const hasExpressionDiagnostics = (options: Parameters<typeof lintExpression>[0]) => lintExpression(options).length > 0;diff --git a/packages/project-build/src/runtime/fragment.ts b/packages/project-build/src/runtime/fragment.tsindex a969cba9a0..01dd9e523d 100644--- a/packages/project-build/src/runtime/fragment.ts+++ b/packages/project-build/src/runtime/fragment.ts@@ -21,6 +21,7 @@ import {findTreeInstanceIdsExcludingSlotDescendants,getHomePage,portalComponent,+ webstudioFragment,} from "@webstudio-is/sdk";import {findAvailableVariables,@@ -30,6 +31,10 @@ import {} from "./data";import { cloneInstanceWithNewIds } from "./instances";import { clonePropForInstance, listPropExpressions } from "./props";+import {+ addExpressionValidationIssues,+ getExpressionErrorMessages,+} from "./expression-validation";import { buildMergedBreakpointIds, maxBreakpoints } from "./breakpoints";import {collectStyleSourcesFromInstances,@@ -89,6 +94,19 @@ export const listFragmentExpressions = (fragment: WebstudioFragment) => [),];+export const webstudioFragmentMutationInput = webstudioFragment.superRefine(+ (fragment, context) => {+ for (const entry of listFragmentExpressions(fragment)) {+ const errors = getExpressionErrorMessages({+ expression: entry.expression,+ allowAssignment: entry.allowAssignment,+ availableVariables: new Set(entry.variables),+ });+ addExpressionValidationIssues(context, errors, entry.path);+ }+ }+);+const mergeById = <Item extends { id: string }>(items: Item[]) =>Array.from(new Map(items.map((item) => [item.id, item])).values());diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.tsindex 8d6c959a04..6423f968e8 100644--- a/packages/project-build/src/runtime/output-schemas.ts+++ b/packages/project-build/src/runtime/output-schemas.ts@@ -13,6 +13,7 @@ import {instance,} from "@webstudio-is/sdk";import {+ assetQueryResultMode,assetQuerySort,assetResourceContentOptions,assetResourceOutputSelection,@@ -196,6 +197,7 @@ const resource = looseObject({dataSourceId: id.optional(),});const assetResourceConfiguration = looseObject({+ result: assetQueryResultMode,where: assetQueryWhereExpression,sort: z.array(assetQuerySort),limit: z.string(),diff --git a/packages/project-build/src/runtime/props.ts b/packages/project-build/src/runtime/props.tsindex 548eb4ff9e..cd6b311437 100644--- a/packages/project-build/src/runtime/props.ts+++ b/packages/project-build/src/runtime/props.ts@@ -9,9 +9,10 @@ import {} from "@webstudio-is/sdk";import { validateJsonLd } from "@webstudio-is/sdk/runtime";import type { BuilderState } from "../state/builder-state";-import { addZodValidationIssue, throwBuilderRuntimeError } from "./errors";+import { throwBuilderRuntimeError } from "./errors";import { replaceTextValue } from "./text-replacement";import {+ addExpressionValidationIssues,getExpressionErrorMessages,getExpressionErrors,} from "./expression-validation";@@ -148,23 +149,6 @@ export const validatePrimitiveValue = (value: unknown, label: string) => {}};-const addExpressionIssues = (- context: z.RefinementCtx,- errors: readonly string[],- path: (string | number)[] = []-) => {- for (const message of errors) {- addZodValidationIssue(context, {- code: "invalid_expression",- path: path.map(String),- message: "Invalid Webstudio expression",- constraint: "valid_webstudio_expression",- example: "item.title",- detail: message,- });- }-};-const propValueBaseInput = {propId: runtimeGeneratedIdInput,instanceId: z.string().describe("Instance id that owns the prop."),@@ -261,7 +245,9 @@ export const propValueInput = z'Direct prop value update. Match value to type: use type "string" for fixed text attributes such as placeholder, aria-label, alt, id, class, href, and title; use bind-props for dynamic expressions/resources/actions.').superRefine((value, context) => {- addExpressionIssues(context, getPropValueErrors(value), ["value"]);+ addExpressionValidationIssues(context, getPropValueErrors(value), [+ "value",+ ]);});export const dataPropBindingInput = z.discriminatedUnion("type", [@@ -299,7 +285,7 @@ export const propBindingInput = z]),}).superRefine((value, context) => {- addExpressionIssues(+ addExpressionValidationIssues(context,getPropValueErrors({type: value.binding.type,diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.tsindex ced6c56c91..cddc656433 100644--- a/packages/project-build/src/runtime/registry.test.ts+++ b/packages/project-build/src/runtime/registry.test.ts@@ -1741,6 +1741,7 @@ describe("builder runtime read families", () => {name: "Blog posts",scopeInstanceId: "heading",query: {+ result: "one",where: {all: [{@@ -1815,6 +1816,7 @@ describe("builder runtime read families", () => {scopeInstanceId: "heading",mode: "query",query: {+ result: "one",where: {all: [{@@ -1825,7 +1827,7 @@ describe("builder runtime read families", () => {],},sort: [],- limit: "1",+ limit: "20",offset: "0",output: {mode: "fields",@@ -1851,6 +1853,7 @@ describe("builder runtime read families", () => {resourceId: "asset-resource",values: {query: {+ result: "many",limit: "2",},},@@ -1868,6 +1871,7 @@ describe("builder runtime read families", () => {expect(updatedPayload).toContain("properties");expect(updatedPayload).toContain("system.params.slug");expect(updatedPayload).toContain("markdown-body-ref");+ expect(updatedPayload).toContain('result: \\"many\\"');expect(updatedPayload).toContain("limit: 2");const reset = executeBuilderRuntimeOperation({diff --git a/packages/project-build/src/runtime/search.ts b/packages/project-build/src/runtime/search.tsindex 71ba3dd9ac..d74227c194 100644--- a/packages/project-build/src/runtime/search.ts+++ b/packages/project-build/src/runtime/search.ts@@ -221,6 +221,9 @@ const createParentIdsByInstance = (return parentIdsByInstance;};+const getLabelTargetId = (props: ReadonlyMap<string, unknown> | undefined) =>+ props?.get("for") ?? props?.get("htmlFor");+const hasAssociatedFormLabel = ({instanceId,instances,@@ -245,7 +248,7 @@ const hasAssociatedFormLabel = ({}if (id !== undefined &&- propsByInstance.get(label.id)?.get("for") === id &&+ getLabelTargetId(propsByInstance.get(label.id)) === id &&hasAccessibleName({instanceId: label.id,instances,@@ -833,6 +836,7 @@ export const analyzeProject = (instanceId: instance.id,instances: state.instances,propsByInstance,+ propTypesByInstance,}) === false) {matches.push({@@ -857,6 +861,7 @@ export const analyzeProject = (instanceId: instance.id,instances: state.instances,propsByInstance,+ propTypesByInstance,}) === false &&hasAssociatedFormLabel({instanceId: instance.id,@@ -1059,7 +1064,7 @@ export const analyzeProject = () {continue;}- const htmlFor = propsByInstance.get(instance.id)?.get("for");+ const htmlFor = getLabelTargetId(propsByInstance.get(instance.id));if (typeof htmlFor !== "string" || htmlFor.trim().length === 0) {continue;}diff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.tsindex 1877e4616f..84a85e4326 100644--- a/packages/project-build/src/runtime/styles.test.ts+++ b/packages/project-build/src/runtime/styles.test.ts@@ -2235,6 +2235,28 @@ describe("style declaration helpers", () => {).toThrow('Invalid value for shorthand CSS property "inset"');});+ test("expands unresolved variable shorthand values", () => {+ expect(+ createStyleDeclsFromInput({+ styleSourceId: "token",+ property: "borderRadius",+ value: { type: "var", value: "radius" },+ })+ ).toEqual(+ [+ "borderTopLeftRadius",+ "borderTopRightRadius",+ "borderBottomRightRadius",+ "borderBottomLeftRadius",+ ].map((property) => ({+ styleSourceId: "token",+ breakpointId: "base",+ property,+ value: { type: "var", value: "radius" },+ }))+ );+ });+test("creates style declaration keys from user input with base breakpoint default", () => {expect(getStyleDeclKeyFromInput({diff --git a/packages/project-build/src/runtime/styles.ts b/packages/project-build/src/runtime/styles.tsindex b4d1e1dde7..fa013623f0 100644--- a/packages/project-build/src/runtime/styles.ts+++ b/packages/project-build/src/runtime/styles.ts@@ -1918,8 +1918,11 @@ export const createStyleDeclsFromInput = ({`.styles{${cssProperty}:${toValue(parsedValue.data)}}`,new Map());+ const unresolvedVariableWasExpanded = parsed.styles.every(+ ({ value: parsedStyleValue }) => parsedStyleValue.type === "var"+ );if (- parsed.errors.length > 0 ||+ (parsed.errors.length > 0 && unresolvedVariableWasExpanded === false) ||parsed.styles.length === 0 ||parsed.styles.some(({ value: parsedStyleValue }) =>["invalid", "guaranteedInvalid"].includes(parsedStyleValue.type)diff --git a/packages/react-sdk/src/component-generator.test.tsx b/packages/react-sdk/src/component-generator.test.tsxindex ededd245f4..736bd2270f 100644--- a/packages/react-sdk/src/component-generator.test.tsx+++ b/packages/react-sdk/src/component-generator.test.tsx@@ -396,6 +396,53 @@ test("generate jsx children with expression", () => {);});+test("preserves siblings before expression children", () => {+ expect(+ generateJsxChildren({+ scope: createScope(),+ metas: new Map(),+ children: [+ { type: "id", value: "strong" },+ { type: "expression", value: "$ws$dataSource$var" },+ ],+ instances: new Map([+ [+ "strong",+ {+ type: "instance",+ id: "strong",+ component: "Text",+ tag: "strong",+ children: [{ type: "text", value: "Important: " }],+ },+ ],+ ]),+ props: new Map(),+ dataSources: toMap([+ {+ id: "var",+ scopeInstanceId: "body",+ name: "message",+ type: "variable",+ value: { type: "string", value: "Details" },+ },+ ]),+ usedDataSources: new Map(),+ indexesWithinAncestors: new Map(),+ })+ ).toEqual(+ validateJSX(+ clear(`+ <Text+ data-ws-tag="strong">+ {"Important: "}+ </Text>+ {renderText(message)}+ `)+ )+ );+});+test("generate jsx children with nested instances", () => {expect(generateJsxChildren({diff --git a/packages/react-sdk/src/component-generator.ts b/packages/react-sdk/src/component-generator.tsindex aa0e7f1cef..19c1cf53d5 100644--- a/packages/react-sdk/src/component-generator.ts+++ b/packages/react-sdk/src/component-generator.ts@@ -405,7 +405,7 @@ export const generateJsxChildren = ({usedDataSources,scope,});- generatedChildren = `{renderText(${expression})}\n`;+ generatedChildren += `{renderText(${expression})}\n`;continue;}if (child.type === "id") {diff --git a/packages/sdk-components-react-radix/src/collapsible.ws.ts b/packages/sdk-components-react-radix/src/collapsible.ws.tsindex dad6e4bb27..c940db2a02 100644--- a/packages/sdk-components-react-radix/src/collapsible.ws.ts+++ b/packages/sdk-components-react-radix/src/collapsible.ws.ts@@ -34,7 +34,7 @@ export const metaCollapsibleTrigger: WsComponentMeta = {icon: TriggerIcon,contentModel: {category: "none",- children: ["instance", "rich-text"],+ children: ["instance"],},states: [{ label: "Open", selector: '[data-state="open"]' },diff --git a/packages/template/src/jsx.ts b/packages/template/src/jsx.tsindex 8f22545ecd..404ded16bc 100644--- a/packages/template/src/jsx.ts+++ b/packages/template/src/jsx.ts@@ -79,6 +79,11 @@ export class ResourceValue {name: string;config: ResourceConfig;constructor(name: string, config: ResourceConfig) {+ if (config === undefined) {+ throw new Error(+ "Invalid JSX prop: ResourceValue requires a resource definition. Existing resource ids are not supported in JSX; insert the component first, then bind its resource prop with update-props."+ );+ }this.name = name;this.config = config;}