Skip to content

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.

fix: Improve MCP preview and mutation reliability (#6073)

Oleg Isonen1fe087ed2615
diff --git a/docs/university/mcp.md b/docs/university/mcp.md
index c4c80fbfbd..dae6ad8390 100644
--- a/docs/university/mcp.md
+++ b/docs/university/mcp.md
@@ -87,7 +87,7 @@ webstudio insert-fragment --input-file .temp/insert-fragment.json
### Tool name convention
-MCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`.
+MCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.
### Readable fragment inputs
@@ -413,23 +413,27 @@ Vision-capable AI can use MCP to see what it is building:
2. 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.
3. 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.
4. `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.
-5. Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.
-6. If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.
-7. 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.
-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. 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.
+5. Dependency installation honors `npm_config_cache`, including a caller-provided writable cache on Windows.
+6. Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.
+7. If dependency installation fails, the error includes sanitized npm diagnostics. Check the reported npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.
+8. 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.
+9. 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.
+10. 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.
+11. 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.
+12. An explicit occupied `port` fails immediately with `PREVIEW_PORT_IN_USE`. To capture a generated site already running in another process, pass its `baseUrl` with `path`; otherwise choose another port.
+13. Automatic browser discovery checks system installations, configured browser paths, and Chromium installations in the Playwright browser cache.
+14. 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.
+15. 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.
+16. 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.
+17. 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.
+18. If the screenshot does not match, apply another focused mutation and repeat screenshot verification.
Generated app setup:
- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.
+- Dependency installation honors `npm_config_cache`, including a caller-provided writable cache on Windows.
- 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.
+- If dependency installation fails, the error includes sanitized npm diagnostics. Check the reported npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.
## MCP argument examples
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 5123ea09da..45c1af7414 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -47,18 +47,22 @@
"chrome-launcher": "^1.2.1",
"deepmerge": "^4.3.1",
"decode-named-character-reference": "^1.0.2",
+ "detect-port": "^2.1.0",
"env-paths": "^3.0.0",
"esbuild": "^0.25.3",
"fast-deep-equal": "^3.1.3",
+ "get-port": "^7.2.0",
"immer": "^10.1.1",
"nanoid": "^5.1.5",
"p-limit": "^6.2.0",
"parse5": "7.3.0",
+ "path-key": "^4.0.0",
"picocolors": "^1.1.1",
"reserved-identifiers": "^1.0.0",
"tinyexec": "^0.3.2",
"tus-js-client": "^4.3.1",
"warn-once": "^0.1.1",
+ "which": "^5.0.0",
"yargs": "^17.7.2",
"zod": "^4.4.3"
},
@@ -80,6 +84,7 @@
"@types/mdast": "^4.0.4",
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
+ "@types/which": "^3.0.4",
"@types/yargs": "^17.0.33",
"@vercel/react-router": "^1.1.0",
"@vitejs/plugin-react": "^4.4.1",
diff --git a/packages/cli/src/commands/mcp-preview.test.ts b/packages/cli/src/commands/mcp-preview.test.ts
index ef5df6d654..d538c173a2 100644
--- a/packages/cli/src/commands/mcp-preview.test.ts
+++ b/packages/cli/src/commands/mcp-preview.test.ts
@@ -35,7 +35,7 @@ test("allocates and reuses a collision-free port for automatic screenshots", asy
viewport: { width: 390, height: 844 },
},
{ running: false, url: "http://127.0.0.1:5173/" },
- getAvailablePort
+ { getAvailablePort }
)
).resolves.toMatchObject({ port: 53124 });
await expect(
@@ -46,7 +46,7 @@ test("allocates and reuses a collision-free port for automatic screenshots", asy
viewport: { width: 1440, height: 900 },
},
{ running: true, url: "http://127.0.0.1:53125/" },
- getAvailablePort
+ { getAvailablePort }
)
).resolves.toMatchObject({ port: 53125 });
await expect(
@@ -58,12 +58,77 @@ test("allocates and reuses a collision-free port for automatic screenshots", asy
viewport: { width: 1440, height: 900 },
},
{ running: false, url: "http://127.0.0.1:5173/" },
- getAvailablePort
+ { getAvailablePort }
)
).resolves.toMatchObject({ port: 4173 });
expect(getAvailablePort).toHaveBeenCalledOnce();
});
+test("rejects an occupied explicit screenshot port before preview preparation", async () => {
+ const isPortAvailable = vi.fn(async () => false);
+
+ await expect(
+ resolveMcpScreenshotInput(
+ {
+ path: "/account",
+ port: 5199,
+ viewport: { width: 1440, height: 900 },
+ },
+ { running: false },
+ {
+ getAvailablePort: vi.fn(async () => 53124),
+ isPortAvailable,
+ }
+ )
+ ).rejects.toMatchObject({
+ code: "PREVIEW_PORT_IN_USE",
+ message: expect.stringContaining(
+ "Pass baseUrl with path to capture that existing site"
+ ),
+ });
+ expect(isPortAvailable).toHaveBeenCalledWith("127.0.0.1", 5199);
+});
+
+test("reuses an owned explicit screenshot port when host is omitted", async () => {
+ const isPortAvailable = vi.fn(async () => false);
+
+ await expect(
+ resolveMcpScreenshotInput(
+ {
+ path: "/account",
+ port: 5199,
+ viewport: { width: 1440, height: 900 },
+ },
+ { running: true, url: "http://localhost:5199/" },
+ {
+ getAvailablePort: vi.fn(async () => 53124),
+ isPortAvailable,
+ }
+ )
+ ).resolves.toMatchObject({ port: 5199 });
+ expect(isPortAvailable).not.toHaveBeenCalled();
+});
+
+test("reuses an owned preview on the default HTTP port", async () => {
+ const isPortAvailable = vi.fn(async () => false);
+
+ await expect(
+ resolveMcpScreenshotInput(
+ {
+ path: "/account",
+ port: 80,
+ viewport: { width: 1440, height: 900 },
+ },
+ { running: true, url: "http://localhost/" },
+ {
+ getAvailablePort: vi.fn(async () => 53124),
+ isPortAvailable,
+ }
+ )
+ ).resolves.toMatchObject({ port: 80 });
+ expect(isPortAvailable).not.toHaveBeenCalled();
+});
+
test("retries automatic MCP preview ports after a startup race", async () => {
const getAvailablePort = vi
.fn()
diff --git a/packages/cli/src/commands/mcp-preview.ts b/packages/cli/src/commands/mcp-preview.ts
index 51b65b0273..4d4d0b70f1 100644
--- a/packages/cli/src/commands/mcp-preview.ts
+++ b/packages/cli/src/commands/mcp-preview.ts
@@ -2,6 +2,7 @@ import {
arePreviewImageDomainsEqual,
createPreviewController,
findAvailablePort,
+ isPreviewPortAvailable,
type PreviewMode,
} from "../preview-server";
import {
@@ -127,28 +128,66 @@ export const resolveMcpPreviewInput = async (
};
};
+const getRunningPreviewPort = (
+ previewStatus: { running: boolean; url?: string },
+ host: string | undefined
+) => {
+ if (previewStatus.running === false || previewStatus.url === undefined) {
+ return;
+ }
+ const previewUrl = new URL(previewStatus.url);
+ if (host !== undefined && previewUrl.hostname !== host) {
+ return;
+ }
+ const defaultPort =
+ previewUrl.protocol === "http:"
+ ? 80
+ : previewUrl.protocol === "https:"
+ ? 443
+ : undefined;
+ const port = previewUrl.port === "" ? defaultPort : Number(previewUrl.port);
+ return port !== undefined && Number.isInteger(port) && port > 0
+ ? port
+ : undefined;
+};
+
export const resolveMcpScreenshotInput = async (
input: McpScreenshotInput,
previewStatus: { running: boolean; url?: string },
- getAvailablePort: (host?: string) => Promise<number> = findAvailablePort
+ {
+ getAvailablePort = findAvailablePort,
+ isPortAvailable = isPreviewPortAvailable,
+ }: {
+ getAvailablePort?: (host?: string) => Promise<number>;
+ isPortAvailable?: (host: string, port: number) => Promise<boolean>;
+ } = {}
) => {
if (
input.url !== undefined ||
input.baseUrl !== undefined ||
- input.source === "local" ||
- (input.port !== undefined && input.port !== 0)
+ input.source === "local"
) {
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 };
- }
+ const runningPreviewPort = getRunningPreviewPort(previewStatus, input.host);
+ if (input.port !== undefined && input.port !== 0) {
+ const host = input.host ?? "127.0.0.1";
+ if (runningPreviewPort === input.port) {
+ return input;
+ }
+ if ((await isPortAvailable(host, input.port)) === false) {
+ throw Object.assign(
+ new Error(
+ `Preview port ${input.port} is already in use on ${host}. Pass baseUrl with path to capture that existing site, or choose another port.`
+ ),
+ { code: "PREVIEW_PORT_IN_USE" }
+ );
}
+ return input;
+ }
+ const host = input.host ?? "127.0.0.1";
+ if (runningPreviewPort !== undefined) {
+ return { ...input, port: runningPreviewPort };
}
return { ...input, port: await getAvailablePort(host) };
};
diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts
index 025e8eb229..18a8ef9727 100644
--- a/packages/cli/src/commands/preview.test.ts
+++ b/packages/cli/src/commands/preview.test.ts
@@ -455,7 +455,7 @@ test("installs isolated generated dependencies when the cli does not ship them",
expect(execFile).toHaveBeenCalledWith(
"npm",
expect.arrayContaining(["install", "--legacy-peer-deps"]),
- { cwd: "/tmp/project/.webstudio/preview" }
+ expect.objectContaining({ cwd: "/tmp/project/.webstudio/preview" })
);
expect(writeFile).toHaveBeenCalledWith(
"/tmp/project/.webstudio/preview/node_modules/.webstudio-preview-dependencies",
@@ -495,7 +495,45 @@ test("reuses the npm cli that launched webstudio on windows", async () => {
"C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js",
"install",
]),
- { cwd: "/tmp/project/.webstudio/preview" }
+ expect.objectContaining({ cwd: "/tmp/project/.webstudio/preview" })
+ );
+});
+
+test("uses npm-cli from an npx launcher and forwards a writable npm cache", async () => {
+ let installed = false;
+ const execFile = vi.fn(async () => {
+ installed = true;
+ return { stdout: "", stderr: "" };
+ });
+ const env = { npm_config_cache: "C:\\workspace\\.npm-cache" };
+
+ await ensurePreviewDependencies("C:/project/.webstudio/preview", {
+ access: vi.fn(async (path) => {
+ if (installed && path.startsWith("C:/project/.webstudio/preview")) {
+ return;
+ }
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ execFile,
+ lstat: vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ readFile: vi.fn(async () => '{"dependencies":{"vite":"1.0.0"}}'),
+ nodeExecPath: "C:\\Program Files\\nodejs\\node.exe",
+ npmExecPath:
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npx-cli.js",
+ platform: "win32",
+ env,
+ writeFile: vi.fn(async () => undefined),
+ });
+
+ expect(execFile).toHaveBeenCalledWith(
+ "C:\\Program Files\\nodejs\\node.exe",
+ expect.arrayContaining([
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js",
+ "install",
+ ]),
+ { cwd: "C:/project/.webstudio/preview", env }
);
});
@@ -522,6 +560,32 @@ test("reports an actionable error when generated dependencies cannot install", a
);
});
+test("reports sanitized package-manager diagnostics for preview install failures", async () => {
+ const installError = Object.assign(new Error("npm install failed"), {
+ code: 1,
+ stderr:
+ "npm error code EACCES\nnpm error cache C:\\Users\\agent\\.npm authToken=private-token",
+ });
+
+ const promise = ensurePreviewDependencies("C:/project/.webstudio/preview", {
+ access: vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ execFile: vi.fn(async () => {
+ throw installError;
+ }),
+ lstat: vi.fn(async () => {
+ throw Object.assign(new Error("missing"), { code: "ENOENT" });
+ }),
+ readFile: vi.fn(async () => '{"dependencies":{"vite":"1.0.0"}}'),
+ platform: "win32",
+ });
+
+ await expect(promise).rejects.toThrow("npm error code EACCES");
+ await expect(promise).rejects.toThrow("authToken=[redacted]");
+ await expect(promise).rejects.not.toThrow("private-token");
+});
+
test("rejects an incomplete generated dependency tree", async () => {
await expect(
ensurePreviewDependencies("/tmp/project/.webstudio/preview", {
diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts
index e31bb0adf3..03ac549a1a 100644
--- a/packages/cli/src/commands/preview.ts
+++ b/packages/cli/src/commands/preview.ts
@@ -21,6 +21,7 @@ import {
projectPreviewSources,
type ProjectPreviewSource,
} from "@webstudio-is/project-build/visual";
+import { sanitizeValidationDetail } from "@webstudio-is/project-build/runtime";
import { generatedFilesManifest, prebuild } from "../prebuild";
import { LOCAL_CONFIG_FILE, LOCAL_DATA_FILE } from "../config";
import { HandledCliError } from "../errors";
@@ -162,7 +163,7 @@ type PreviewDependencyOperations = {
execFile: (
file: string,
args: string[],
- options: { cwd: string }
+ options: { cwd: string; env: NodeJS.ProcessEnv }
) => Promise<unknown>;
lstat: (path: string) => Promise<{ isSymbolicLink: () => boolean }>;
readFile: (path: string, encoding: "utf8") => Promise<string>;
@@ -179,6 +180,27 @@ type PreviewDependencyOperations = {
nodeExecPath: string;
npmExecPath?: string;
platform: NodeJS.Platform;
+ env: NodeJS.ProcessEnv;
+};
+
+const getPreviewInstallFailureDiagnostics = (error: unknown) => {
+ if (typeof error !== "object" || error === null) {
+ return sanitizeValidationDetail(String(error)).trim().slice(-2000);
+ }
+ const record = error as Record<string, unknown>;
+ const output = [record.stderr, record.stdout, record.message].find(
+ (value) => typeof value === "string" && value.trim().length > 0
+ );
+ const diagnostics = sanitizeValidationDetail(
+ typeof output === "string" ? output : String(error)
+ )
+ .trim()
+ .slice(-2000);
+ const code =
+ typeof record.code === "string" || typeof record.code === "number"
+ ? String(record.code)
+ : undefined;
+ return `${code === undefined ? "" : `npm exit code ${code}. `}${diagnostics}`;
};
export const getPreviewProjectDir = (projectDir = cwd()) =>
@@ -199,6 +221,7 @@ export const ensurePreviewDependencies = async (
nodeExecPath: process.execPath,
npmExecPath: process.env.npm_execpath,
platform: process.platform,
+ env: process.env,
...dependencies,
};
const previewNodeModules = join(previewProjectDir, "node_modules");
@@ -276,10 +299,11 @@ export const ensurePreviewDependencies = async (
try {
await operations.execFile(invocation.command, invocation.args, {
cwd: previewProjectDir,
+ env: operations.env,
});
} catch (error) {
throw new Error(
- "PREVIEW_DEPENDENCY_INSTALL_FAILED: Could not install the generated preview dependencies. Check the npm/network configuration, then reinstall or update webstudio if the problem persists.",
+ `PREVIEW_DEPENDENCY_INSTALL_FAILED: Could not install the generated preview dependencies. Check the npm/network configuration, then reinstall or update webstudio if the problem persists.\n\nPackage-manager diagnostics:\n${getPreviewInstallFailureDiagnostics(error)}`,
{ cause: error }
);
}
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 97eb059475..93e4353d8c 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -8,11 +8,11 @@ export const cliDocs = {
"manual-llm":
'# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `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"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\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 readable payload in `.temp/insert-fragment.json`:\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\nSingle quotes inside the JSX keep the JSON valid without backslash-escaped attributes. The same local shortcut form is shorter and 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 this simple path, 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 to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS. For simpler cases, use React-style object syntax such as`style={{ padding: 24 }}`. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX 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\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For 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- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. 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, report that command/result, then 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 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 `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource that always executes a structured query. `result:"many"` returns the existing ID-keyed collection shape and is the backward-compatible default. `result:"one"`, `result:"first"`, and `result:"last"` return one direct item or `null`; first and last require explicit sorting. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output.\n- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.\n- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.\n- Query Markdown files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.\n- For `result:"many"`, Assets expose an ID-keyed map at `<dataSourceName>.data` and `totalCount`/`hasMore` at `<dataSourceName>.meta`; bind a listing Collection to `posts.data`. Single-result modes expose the selected item or `null` directly at `<dataSourceName>.data`, always include its `id`, and expose `totalCount` in meta. Bind detail components and page settings directly from expressions such as `post.data?.properties?.title`, `post.data?.content?.text`, and `post.data ? 200 : 404` without a Collection.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. 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 are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can use an expression such as `"Bearer " + auth.token`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
"manual-mcp":
- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits 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`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag=\'h2\'>Northstar Product OS</ws.element><ws.element ws:tag=\'p\'>Reusable patterns for teams.</ws.element></ws.element>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<ws.element\n ws:tag="section"\n style={{ padding: 32, borderRadius: 16 }}\n>\n <ws.element ws:tag="h2">Operations Console</ws.element>\n <ws.element ws:tag="p">\n React-style object styles become editable Webstudio styles.\n </ws.element>\n</ws.element>\n\n<ws.element\n ws:tag="section"\n ws:tokens={[token("accent", css`color: #0f766e;`)]}\n>\n <ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </ws.element>\n</ws.element>\n\n<ws.element ws:tag="section">\n <radix.Switch>\n <radix.SwitchThumb />\n </radix.Switch>\n</ws.element>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\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>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build 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- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. 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\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
+ '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits 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`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag=\'h2\'>Northstar Product OS</ws.element><ws.element ws:tag=\'p\'>Reusable patterns for teams.</ws.element></ws.element>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<ws.element\n ws:tag="section"\n style={{ padding: 32, borderRadius: 16 }}\n>\n <ws.element ws:tag="h2">Operations Console</ws.element>\n <ws.element ws:tag="p">\n React-style object styles become editable Webstudio styles.\n </ws.element>\n</ws.element>\n\n<ws.element\n ws:tag="section"\n ws:tokens={[token("accent", css`color: #0f766e;`)]}\n>\n <ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </ws.element>\n</ws.element>\n\n<ws.element ws:tag="section">\n <radix.Switch>\n <radix.SwitchThumb />\n </radix.Switch>\n</ws.element>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\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>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build 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- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. 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\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
"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- 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',
+ '# 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- Dependency installation honors `npm_config_cache`, including a caller-provided writable cache on Windows.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, the error includes sanitized npm diagnostics. Check the reported 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- An explicit occupied `port` fails immediately with `PREVIEW_PORT_IN_USE`. To capture a generated site already running in another process, pass its `baseUrl` with `path`; otherwise choose another port.\n- Automatic browser discovery checks system installations, configured browser paths, and Chromium installations in the Playwright browser cache.\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/manual-mcp.md b/packages/cli/src/docs/manual-mcp.md
index 0c6376f4ef..d7d87973d8 100644
--- a/packages/cli/src/docs/manual-mcp.md
+++ b/packages/cli/src/docs/manual-mcp.md
@@ -69,7 +69,7 @@ webstudio insert-fragment --input-file .temp/insert-fragment.json
### Tool name convention
-MCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`.
+MCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.
### Readable fragment inputs
diff --git a/packages/cli/src/docs/mcp-vision.md b/packages/cli/src/docs/mcp-vision.md
index 1ed2d61f16..c72083d13a 100644
--- a/packages/cli/src/docs/mcp-vision.md
+++ b/packages/cli/src/docs/mcp-vision.md
@@ -3,8 +3,9 @@
## Generated App Dependency Notes
- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.
+- Dependency installation honors `npm_config_cache`, including a caller-provided writable cache on Windows.
- 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.
+- If dependency installation fails, the error includes sanitized npm diagnostics. Check the reported npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.
## Visual Verification Rule
@@ -28,6 +29,8 @@ 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.
+- An explicit occupied `port` fails immediately with `PREVIEW_PORT_IN_USE`. To capture a generated site already running in another process, pass its `baseUrl` with `path`; otherwise choose another port.
+- Automatic browser discovery checks system installations, configured browser paths, and Chromium installations in the Playwright browser cache.
- 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.
diff --git a/packages/cli/src/mcp-guidance.test.ts b/packages/cli/src/mcp-guidance.test.ts
index c6ff06a650..b79da2bb3d 100644
--- a/packages/cli/src/mcp-guidance.test.ts
+++ b/packages/cli/src/mcp-guidance.test.ts
@@ -10,8 +10,9 @@ import {
test("documents generated app setup for visual verification", () => {
expect(generatedAppDependencyNotes).toEqual([
expect.stringContaining("install generated app dependencies"),
+ expect.stringContaining("npm_config_cache"),
expect.stringContaining("Do not add generated-preview dependencies"),
- expect.stringContaining("check npm and network configuration"),
+ expect.stringContaining("Check the reported npm and network configuration"),
]);
expect(visualVerificationRule).toContain(
"generated project files are current"
diff --git a/packages/cli/src/preview-server.test.ts b/packages/cli/src/preview-server.test.ts
index f85d7775fd..d359217bb4 100644
--- a/packages/cli/src/preview-server.test.ts
+++ b/packages/cli/src/preview-server.test.ts
@@ -1,4 +1,5 @@
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, test, vi } from "vitest";
@@ -6,10 +7,10 @@ import {
createPreviewController,
findAvailablePort,
getPreviewBuildArgs,
- getPreviewCommand,
getNpmInvocation,
getPreviewStartArgs,
getPreviewUrl,
+ isPreviewPortAvailable,
materializePreviewAssets,
runPreviewBuild,
startPreviewServer,
@@ -24,6 +25,28 @@ test("allocates an available local preview port", async () => {
expect(port).toBeLessThanOrEqual(65_535);
});
+test("repeatedly reports an unoccupied explicit preview port as available", async () => {
+ const server = createServer();
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ const address = server.address();
+ if (address === null || typeof address === "string") {
+ throw new Error("Expected the test server to have a TCP address.");
+ }
+ await new Promise<void>((resolve, reject) => {
+ server.close((error) => (error === undefined ? resolve() : reject(error)));
+ });
+
+ await expect(isPreviewPortAvailable("127.0.0.1", address.port)).resolves.toBe(
+ true
+ );
+ await expect(isPreviewPortAvailable("127.0.0.1", address.port)).resolves.toBe(
+ true
+ );
+});
+
const createDependencies = (
overrides: Partial<PreviewServerDependencies> = {}
): PreviewServerDependencies => ({
@@ -114,12 +137,6 @@ test("builds iterative preview args for an ordinary reload server", () => {
]);
});
-test("uses the platform npm executable for preview commands", () => {
- expect(getPreviewCommand("linux")).toBe("npm");
- expect(getPreviewCommand("darwin")).toBe("npm");
- expect(getPreviewCommand("win32")).toBe("npm.cmd");
-});
-
test("reuses the npm cli that launched webstudio for preview commands", () => {
expect(
getNpmInvocation(["run", "build"], {
@@ -138,6 +155,41 @@ test("reuses the npm cli that launched webstudio for preview commands", () => {
});
});
+test("uses npm-cli when webstudio was launched through npx on windows", () => {
+ expect(
+ getNpmInvocation(["run", "build"], {
+ nodeExecPath: "C:\\Program Files\\nodejs\\node.exe",
+ npmExecPath:
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npx-cli.js",
+ platform: "win32",
+ })
+ ).toEqual({
+ command: "C:\\Program Files\\nodejs\\node.exe",
+ args: [
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js",
+ "run",
+ "build",
+ ],
+ });
+});
+
+test("uses npm-cli when windows npm launcher metadata is unavailable", () => {
+ expect(
+ getNpmInvocation(["run", "build"], {
+ nodeExecPath: "C:\\Program Files\\nodejs\\node.exe",
+ npmExecPath: undefined,
+ platform: "win32",
+ })
+ ).toEqual({
+ command: "C:\\Program Files\\nodejs\\node.exe",
+ args: [
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js",
+ "run",
+ "build",
+ ],
+ });
+});
+
test("runs generated project production build", async () => {
const process = createPreviewProcess();
const spawn = vi.fn(() => process);
@@ -186,21 +238,33 @@ test("does not fail when the generated preview has no downloaded assets", async
}
});
-test("runs generated project production build with the windows npm executable", async () => {
+test("runs generated project production build through windows npm-cli", async () => {
const process = createPreviewProcess();
const spawn = vi.fn(() => process);
resolveProcessExit(process);
await runPreviewBuild(
- createDependencies({ spawn: spawn as never, platform: "win32" }),
+ createDependencies({
+ spawn: spawn as never,
+ nodeExecPath: "C:\\Program Files\\nodejs\\node.exe",
+ platform: "win32",
+ }),
"C:/project/.webstudio/preview"
);
- expect(spawn).toHaveBeenCalledWith("npm.cmd", ["run", "build"], {
- cwd: "C:/project/.webstudio/preview",
- stdio: "inherit",
- env: expect.objectContaining({ NODE_ENV: "production" }),
- });
+ expect(spawn).toHaveBeenCalledWith(
+ "C:\\Program Files\\nodejs\\node.exe",
+ [
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js",
+ "run",
+ "build",
+ ],
+ {
+ cwd: "C:/project/.webstudio/preview",
+ stdio: "inherit",
+ env: expect.objectContaining({ NODE_ENV: "production" }),
+ }
+ );
});
test("starts generated project production server with inherited stdio", () => {
@@ -252,7 +316,7 @@ test("passes explicit external image domains to the preview optimizer", () => {
);
});
-test("starts generated project production server with the windows npm executable", () => {
+test("starts generated project production server through windows npm-cli", () => {
const process = {} as ReturnType<typeof startPreviewServer>["process"];
const spawn = vi.fn(() => process);
@@ -263,21 +327,33 @@ test("starts generated project production server with the windows npm executable
port: 5173,
cwd: "C:/project/.webstudio/preview",
},
- createDependencies({ spawn: spawn as never, platform: "win32" })
+ createDependencies({
+ spawn: spawn as never,
+ nodeExecPath: "C:\\Program Files\\nodejs\\node.exe",
+ platform: "win32",
+ })
)
).toEqual({
url: "http://127.0.0.1:5173/",
process,
});
- expect(spawn).toHaveBeenCalledWith("npm.cmd", ["run", "start"], {
- cwd: "C:/project/.webstudio/preview",
- stdio: "inherit",
- env: expect.objectContaining({
- HOST: "127.0.0.1",
- PORT: "5173",
- NODE_ENV: "production",
- }),
- });
+ expect(spawn).toHaveBeenCalledWith(
+ "C:\\Program Files\\nodejs\\node.exe",
+ [
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js",
+ "run",
+ "start",
+ ],
+ {
+ cwd: "C:/project/.webstudio/preview",
+ stdio: "inherit",
+ env: expect.objectContaining({
+ HOST: "127.0.0.1",
+ PORT: "5173",
+ NODE_ENV: "production",
+ }),
+ }
+ );
});
test("preview controller builds once and reuses a running server", async () => {
@@ -359,6 +435,48 @@ test("iterative preview starts without a production build", async () => {
);
});
+test("starts a managed Windows preview through npm-cli with supported spawn options", async () => {
+ const process = createPreviewProcess();
+ const spawn = vi.fn(() => process);
+ const controller = createPreviewController(
+ {
+ host: "127.0.0.1",
+ port: 5173,
+ cwd: "C:/project/.webstudio/preview",
+ mode: "iterative",
+ },
+ createDependencies({
+ spawn: spawn as never,
+ nodeExecPath: "C:\\Program Files\\nodejs\\node.exe",
+ npmExecPath:
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npx-cli.js",
+ platform: "win32",
+ })
+ );
+
+ await expect(controller.start()).resolves.toMatchObject({ running: true });
+
+ expect(spawn).toHaveBeenCalledWith(
+ "C:\\Program Files\\nodejs\\node.exe",
+ [
+ "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js",
+ "run",
+ "dev",
+ "--",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ "5173",
+ "--strictPort",
+ ],
+ expect.objectContaining({
+ cwd: "C:/project/.webstudio/preview",
+ detached: false,
+ stdio: ["ignore", "pipe", "pipe"],
+ })
+ );
+});
+
test("preview status omits fabricated server details when stopped", () => {
const controller = createPreviewController({
host: "127.0.0.1",
diff --git a/packages/cli/src/preview-server.ts b/packages/cli/src/preview-server.ts
index a1dd7425d3..fa5a7a1af7 100644
--- a/packages/cli/src/preview-server.ts
+++ b/packages/cli/src/preview-server.ts
@@ -5,8 +5,10 @@ import {
type StdioOptions,
} from "node:child_process";
import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
-import { createServer as createTcpServer } from "node:net";
import { basename, delimiter, dirname, join, parse, win32 } from "node:path";
+import detectPort from "detect-port";
+import getPort from "get-port";
+import pathKey from "path-key";
import { parse as parseHtml, type DefaultTreeAdapterMap } from "parse5";
import type { ProjectPreviewMode } from "@webstudio-is/project-build/visual";
@@ -82,27 +84,14 @@ export const defaultPreviewServerDependencies: PreviewServerDependencies = {
platform: process.platform,
};
-export const findAvailablePort = (host = "127.0.0.1") =>
- new Promise<number>((resolve, reject) => {
- const server = createTcpServer();
- server.unref();
- server.once("error", reject);
- server.listen({ host, port: 0, exclusive: true }, () => {
- const address = server.address();
- if (address === null || typeof address === "string") {
- server.close();
- reject(new Error("Could not allocate a local preview port."));
- return;
- }
- server.close((error) =>
- error === undefined ? resolve(address.port) : reject(error)
- );
- });
- });
+export const findAvailablePort = (host = "127.0.0.1") => getPort({ host });
-const processEnv = () => process.env;
+export const isPreviewPortAvailable = async (host: string, port: number) => {
+ const availablePort = await detectPort({ hostname: host, port });
+ return availablePort === port;
+};
-const pathKey = () => (process.platform === "win32" ? "Path" : "PATH");
+const processEnv = () => process.env;
const getAncestorBinPaths = (directory: string) => {
const paths: string[] = [];
@@ -130,7 +119,7 @@ const getPreviewEnv = (
if (cwd === undefined) {
return extraEnv;
}
- const key = pathKey();
+ const key = pathKey({ env: extraEnv });
return {
...extraEnv,
[key]: [...getAncestorBinPaths(cwd), extraEnv[key]]
@@ -162,10 +151,6 @@ export const getPreviewStartArgs = (options: PreviewServerOptions) =>
]
: ["run", "start"];
-export const getPreviewCommand = (
- platform: typeof process.platform = process.platform
-) => (platform === "win32" ? "npm.cmd" : "npm");
-
export const getNpmInvocation = (
args: string[],
{
@@ -184,10 +169,35 @@ export const getNpmInvocation = (
: platform === "win32"
? win32.basename(npmExecPath)
: basename(npmExecPath);
- if (npmExecPath !== undefined && npmCliName === "npm-cli.js") {
- return { command: nodeExecPath, args: [npmExecPath, ...args] };
+ if (npmExecPath !== undefined && npmCliName !== undefined) {
+ const npmCliPath =
+ npmCliName === "npm-cli.js"
+ ? npmExecPath
+ : npmCliName === "npx-cli.js"
+ ? platform === "win32"
+ ? win32.join(win32.dirname(npmExecPath), "npm-cli.js")
+ : join(dirname(npmExecPath), "npm-cli.js")
+ : undefined;
+ if (npmCliPath !== undefined) {
+ return { command: nodeExecPath, args: [npmCliPath, ...args] };
+ }
+ }
+ if (platform === "win32") {
+ return {
+ command: nodeExecPath,
+ args: [
+ win32.join(
+ win32.dirname(nodeExecPath),
+ "node_modules",
+ "npm",
+ "bin",
+ "npm-cli.js"
+ ),
+ ...args,
+ ],
+ };
}
- return { command: getPreviewCommand(platform), args };
+ return { command: "npm", args };
};
export const runPreviewBuild = async (
diff --git a/packages/cli/src/screenshot.test.ts b/packages/cli/src/screenshot.test.ts
index ecc9306e0b..0a31aaa607 100644
--- a/packages/cli/src/screenshot.test.ts
+++ b/packages/cli/src/screenshot.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, test, vi } from "vitest";
import { constants } from "node:fs";
+import { mkdir, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
+import { join } from "node:path";
import {
BrowserNotFoundError,
BrowserInstallUnavailableError,
@@ -9,6 +11,7 @@ import {
createScreenshotCaptureSession,
getChromiumInstallCommand,
getNoBrowserFoundMessage,
+ getPlaywrightInstallations,
installTesseractForOcr,
resolveScreenshotBrowser,
shouldOfferBrowserInstall,
@@ -25,6 +28,7 @@ const createDependencies = (
mkdir: vi.fn(async () => undefined),
which: vi.fn(async () => undefined),
getChromeLauncherInstallations: vi.fn(() => []),
+ getPlaywrightInstallations: vi.fn(async () => []),
spawnBrowser: vi.fn(() => ({
kill: vi.fn(),
once: vi.fn(),
@@ -45,6 +49,66 @@ const createDependencies = (
});
describe("resolveScreenshotBrowser", () => {
+ test("finds Playwright Chromium executables in the configured cache", async () => {
+ const cacheDirectory = await mkdtemp(
+ join(tmpdir(), "webstudio-playwright-cache-")
+ );
+ try {
+ await mkdir(join(cacheDirectory, "chromium-1208"));
+
+ await expect(
+ getPlaywrightInstallations({
+ env: { PLAYWRIGHT_BROWSERS_PATH: cacheDirectory },
+ platform: "linux",
+ })
+ ).resolves.toEqual([
+ join(cacheDirectory, "chromium-1208", "chrome-linux64", "chrome"),
+ join(cacheDirectory, "chromium-1208", "chrome-linux", "chrome"),
+ ]);
+ } finally {
+ await rm(cacheDirectory, { recursive: true, force: true });
+ }
+ });
+
+ test.each([
+ {
+ platform: "darwin" as const,
+ cacheSegments: ["Library", "Caches", "ms-playwright"],
+ executableSegments: [
+ "chromium-1208",
+ "chrome-mac",
+ "Chromium.app",
+ "Contents",
+ "MacOS",
+ "Chromium",
+ ],
+ },
+ {
+ platform: "win32" as const,
+ cacheSegments: ["AppData", "Local", "ms-playwright"],
+ executableSegments: ["chromium-1208", "chrome-win", "chrome.exe"],
+ },
+ ])(
+ "finds Playwright Chromium in the default $platform cache",
+ async ({ platform, cacheSegments, executableSegments }) => {
+ const homeDirectory = await mkdtemp(
+ join(tmpdir(), "webstudio-playwright-home-")
+ );
+ try {
+ const cacheDirectory = join(homeDirectory, ...cacheSegments);
+ await mkdir(join(cacheDirectory, "chromium-1208"), {
+ recursive: true,
+ });
+
+ await expect(
+ getPlaywrightInstallations({ env: {}, platform, homeDirectory })
+ ).resolves.toContain(join(cacheDirectory, ...executableSegments));
+ } finally {
+ await rm(homeDirectory, { recursive: true, force: true });
+ }
+ }
+ );
+
test("uses explicit browser path before discovered browsers", async () => {
const dependencies = createDependencies({
which: vi.fn(async (command) =>
@@ -118,6 +182,31 @@ describe("resolveScreenshotBrowser", () => {
);
});
+ test("discovers Chromium installed in the Playwright browser cache", async () => {
+ const dependencies = createDependencies({
+ access: vi.fn(async (path) => {
+ if (
+ path ===
+ "/root/.cache/ms-playwright/chromium-1208/chrome-linux64/chrome"
+ ) {
+ return;
+ }
+ throw new Error("missing");
+ }),
+ getPlaywrightInstallations: vi.fn(async () => [
+ "/root/.cache/ms-playwright/chromium-1208/chrome-linux64/chrome",
+ ]),
+ });
+
+ await expect(
+ resolveScreenshotBrowser({ browser: "auto" }, dependencies)
+ ).resolves.toEqual({
+ path: "/root/.cache/ms-playwright/chromium-1208/chrome-linux64/chrome",
+ source: "playwright",
+ browser: "chromium",
+ });
+ });
+
test("throws with checked paths when no browser is executable", async () => {
const dependencies = createDependencies({
access: vi.fn(async () => {
diff --git a/packages/cli/src/screenshot.ts b/packages/cli/src/screenshot.ts
index f7ed844897..3175c20911 100644
--- a/packages/cli/src/screenshot.ts
+++ b/packages/cli/src/screenshot.ts
@@ -1,10 +1,10 @@
import { constants } from "node:fs";
-import { access, mkdir } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { dirname, resolve } from "node:path";
-import { execFile, spawn } from "node:child_process";
-import { promisify } from "node:util";
+import { access, mkdir, readdir } from "node:fs/promises";
+import { homedir, tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { spawn } from "node:child_process";
import { Launcher } from "chrome-launcher";
+import which from "which";
import {
defaultScreenshotTimeout,
defaultScreenshotWaitForTimeout,
@@ -22,11 +22,15 @@ import {
type BrowserScreenshotOptions,
} from "./screenshot-browser-cdp";
-const execFileAsync = promisify(execFile);
-
export type BrowserCandidate = {
path: string;
- source: "option" | "env" | "path" | "platform" | "chrome-launcher";
+ source:
+ | "option"
+ | "env"
+ | "path"
+ | "platform"
+ | "playwright"
+ | "chrome-launcher";
browser: Exclude<ScreenshotBrowser, "auto">;
};
@@ -54,6 +58,7 @@ export type ScreenshotDependencies = {
mkdir: (path: string, options: { recursive: true }) => Promise<unknown>;
which: (command: string) => Promise<string | undefined>;
getChromeLauncherInstallations: () => string[];
+ getPlaywrightInstallations: () => Promise<string[]>;
} & BrowserScreenshotDependencies & {
captureBrowserScreenshot?: (
options: BrowserScreenshotOptions
@@ -68,15 +73,8 @@ export const defaultScreenshotDependencies: ScreenshotDependencies = {
platform: process.platform,
access,
mkdir,
- async which(command) {
- const lookup = process.platform === "win32" ? "where" : "which";
- try {
- const { stdout } = await execFileAsync(lookup, [command]);
- return stdout.split(/\r?\n/).find((path) => path.length > 0);
- } catch {
- return undefined;
- }
- },
+ which: async (command) =>
+ (await which(command, { nothrow: true })) ?? undefined,
getChromeLauncherInstallations() {
try {
return Launcher.getInstallations();
@@ -84,6 +82,7 @@ export const defaultScreenshotDependencies: ScreenshotDependencies = {
return [];
}
},
+ getPlaywrightInstallations: () => getPlaywrightInstallations(),
...defaultBrowserScreenshotDependencies,
async installCommand(file, args) {
await new Promise<void>((resolve, reject) => {
@@ -121,6 +120,69 @@ const pathCommandCandidates = [
{ command: "brave", browser: "brave" },
] as const;
+export const getPlaywrightInstallations = async ({
+ env = process.env,
+ platform = process.platform,
+ homeDirectory = homedir(),
+}: {
+ env?: NodeJS.ProcessEnv;
+ platform?: NodeJS.Platform;
+ homeDirectory?: string;
+} = {}) => {
+ const configuredCache = env.PLAYWRIGHT_BROWSERS_PATH;
+ const defaultCacheDirectory =
+ platform === "darwin"
+ ? join(homeDirectory, "Library", "Caches", "ms-playwright")
+ : platform === "win32"
+ ? join(
+ env.LOCALAPPDATA ?? join(homeDirectory, "AppData", "Local"),
+ "ms-playwright"
+ )
+ : join(
+ env.XDG_CACHE_HOME ?? join(homeDirectory, ".cache"),
+ "ms-playwright"
+ );
+ const cacheDirectory =
+ configuredCache === undefined || configuredCache === ""
+ ? defaultCacheDirectory
+ : configuredCache === "0"
+ ? undefined
+ : resolve(configuredCache);
+ if (cacheDirectory === undefined) {
+ return [];
+ }
+ const entries = await readdir(cacheDirectory, { withFileTypes: true }).catch(
+ () => []
+ );
+ const executablePaths =
+ platform === "win32"
+ ? [["chrome-win", "chrome.exe"]]
+ : platform === "darwin"
+ ? [
+ ["chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium"],
+ [
+ "chrome-mac-arm64",
+ "Chromium.app",
+ "Contents",
+ "MacOS",
+ "Chromium",
+ ],
+ ]
+ : [
+ ["chrome-linux64", "chrome"],
+ ["chrome-linux", "chrome"],
+ ];
+ return entries
+ .filter(
+ (entry) => entry.isDirectory() && entry.name.startsWith("chromium-")
+ )
+ .flatMap((entry) =>
+ executablePaths.map((segments) =>
+ join(cacheDirectory, entry.name, ...segments)
+ )
+ );
+};
+
const platformPathCandidates: Record<
NodeJS.Platform,
readonly BrowserCandidate[]
@@ -298,6 +360,16 @@ export const resolveScreenshotBrowser = async (
)
);
+ if (options.browser === "auto" || options.browser === "chromium") {
+ candidates.push(
+ ...(await dependencies.getPlaywrightInstallations()).map((path) => ({
+ path,
+ source: "playwright" as const,
+ browser: "chromium" as const,
+ }))
+ );
+ }
+
candidates.push(
...dependencies
.getChromeLauncherInstallations()
diff --git a/packages/project-build/package.json b/packages/project-build/package.json
index 91bb1e77fe..99ab87a8fb 100644
--- a/packages/project-build/package.json
+++ b/packages/project-build/package.json
@@ -91,6 +91,7 @@
"css-tree": "^3.1.0",
"esbuild": "^0.25.3",
"fast-deep-equal": "^3.1.3",
+ "fastest-levenshtein": "^1.0.16",
"fast-png": "8.0.0",
"immer": "^10.1.1",
"nanoid": "^5.1.5",
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index 053800a263..83ebb9ff03 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -1,6 +1,7 @@
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
+import { PassThrough } from "node:stream";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
@@ -19,6 +20,7 @@ import { BuilderRuntimeError } from "./runtime/errors";
import {
createProjectSessionMcpCore,
createProjectSessionMcpServer,
+ createMcpStdioTransport,
hiddenMcpOperationCommands,
listProjectSessionMcpResources,
listProjectSessionMcpTools,
@@ -3882,6 +3884,10 @@ describe("project session mcp adapter", () => {
name: "meta.get-more-tools",
input: { tools: ["insert_fragment"] },
});
+ const stringifiedToolDetails = 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"] },
@@ -3901,6 +3907,13 @@ describe("project session mcp adapter", () => {
]),
})
);
+ expect(stringifiedToolDetails.structuredContent.data).toEqual(
+ expect.objectContaining({
+ requestedTools: ["insert-fragment"],
+ missingTools: [],
+ count: 1,
+ })
+ );
expect(index.structuredContent.data).toEqual(
expect.objectContaining({
readThisFirst: expect.stringContaining(
@@ -7051,12 +7064,42 @@ describe("project session mcp adapter", () => {
});
await expect(adapter.callTool({ name: "unknown-tool" })).rejects.toThrow(
- 'Unknown MCP tool "unknown-tool".'
+ 'Unknown MCP tool "unknown-tool". Use meta.index to list available tools.'
+ );
+ await expect(adapter.callTool({ name: "updat_styles" })).rejects.toThrow(
+ 'Unknown MCP tool "updat_styles". Did you mean "update-styles"? Use meta.index to list available tools.'
);
expect(createProjectSession).not.toHaveBeenCalled();
expect(executeOperation).not.toHaveBeenCalled();
});
+ test("accepts exposed underscore spellings in direct MCP calls", async () => {
+ const executeOperation = createExecuteOperation();
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ });
+
+ await adapter.callTool({
+ name: "update_styles",
+ input: {
+ updates: [
+ {
+ instanceId: "body",
+ breakpointId: "base",
+ property: "display",
+ value: "grid",
+ },
+ ],
+ },
+ });
+
+ expect(executeOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ command: "update-styles" })
+ );
+ });
+
test.each([
{
command: "insert-fragment",
@@ -7764,6 +7807,33 @@ describe("project session mcp adapter", () => {
}
});
+ test("recovers stdio transport after an idle partial JSON-RPC frame", async () => {
+ const stdin = new PassThrough();
+ const stdout = new PassThrough();
+ const transport = await createMcpStdioTransport({
+ stdin,
+ stdout,
+ partialFrameTimeoutMs: 10,
+ });
+ const messages: unknown[] = [];
+ const errors: Error[] = [];
+ transport.onmessage = (message) => messages.push(message);
+ transport.onerror = (error) => errors.push(error);
+ await transport.start();
+
+ stdin.write('{"jsonrpc":"2.0","id":1,"method":"tools/call"');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ stdin.write(
+ `${JSON.stringify({ jsonrpc: "2.0", id: 2, method: "ping" })}\n`
+ );
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(messages).toEqual([{ jsonrpc: "2.0", id: 2, method: "ping" }]);
+ expect(errors).toEqual([]);
+
+ await transport.close();
+ });
+
test("sends sparse protocol-native startup logging after initialization", async () => {
const onInitialized = vi.fn();
const server = await createProjectSessionMcpServer({
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index fd774f5797..b03de91cb5 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -16,8 +16,10 @@ import {
allowedArrayMethods,
allowedStringMethods,
} from "@webstudio-is/expression";
+import { distance as getLevenshteinDistance } from "fastest-levenshtein";
import type { BuilderApiCapability } from "./contracts/permissions";
import path from "node:path";
+import { Transform } from "node:stream";
import {
projectSessionRestorePointSummarySchema,
projectSessionBusyMessage,
@@ -6145,18 +6147,12 @@ const getExactToolSelection = (
toolNames: readonly string[],
tools: readonly ProjectSessionMcpTool[]
) => {
- const toolByName = new Map(
- tools.map((tool) => [toUnderscoredToolName(tool.name), tool])
- );
- for (const tool of tools) {
- toolByName.set(tool.name, tool);
- }
+ const toolNameIndex = createToolNameIndex(tools);
const selectedTools: ProjectSessionMcpTool[] = [];
const missingTools: string[] = [];
const includedToolNames = new Set<string>();
for (const requestedName of toolNames) {
- const resolvedName = resolveToolName(requestedName);
- const tool = toolByName.get(resolvedName);
+ const tool = toolNameIndex.get(requestedName);
if (tool === undefined) {
missingTools.push(requestedName);
continue;
@@ -6293,7 +6289,72 @@ const toolAliases = new Map([
["meta.get_more_tools", "meta.get-more-tools"],
]);
-const resolveToolName = (name: string) => toolAliases.get(name) ?? name;
+const createToolNameIndex = (tools: readonly ProjectSessionMcpTool[]) => {
+ const toolByAcceptedName = new Map(
+ tools.map((tool) => [tool.name, tool] as const)
+ );
+ const canonicalNamesByUnderscoredName = new Map<string, string[]>();
+ for (const tool of tools) {
+ const underscoredName = toUnderscoredToolName(tool.name);
+ const canonicalNames =
+ canonicalNamesByUnderscoredName.get(underscoredName) ?? [];
+ canonicalNames.push(tool.name);
+ canonicalNamesByUnderscoredName.set(underscoredName, canonicalNames);
+ }
+ for (const [
+ underscoredName,
+ canonicalNames,
+ ] of canonicalNamesByUnderscoredName) {
+ if (
+ canonicalNames.length === 1 &&
+ toolByAcceptedName.has(underscoredName) === false
+ ) {
+ const tool = toolByAcceptedName.get(canonicalNames[0] ?? "");
+ if (tool !== undefined) {
+ toolByAcceptedName.set(underscoredName, tool);
+ }
+ }
+ }
+ const getAcceptedName = (name: string) => toolAliases.get(name) ?? name;
+ const get = (name: string) => toolByAcceptedName.get(getAcceptedName(name));
+ return {
+ canonicalNamesByUnderscoredName,
+ get,
+ resolve: (name: string) => get(name)?.name ?? getAcceptedName(name),
+ };
+};
+
+const getUnknownToolMessage = (
+ requestedName: string,
+ tools: readonly ProjectSessionMcpTool[]
+) => {
+ const normalizedRequestedName = toUnderscoredToolName(
+ requestedName.toLowerCase()
+ );
+ const suggestions = tools
+ .map((tool) => ({
+ name: tool.name,
+ distance: getLevenshteinDistance(
+ normalizedRequestedName,
+ toUnderscoredToolName(tool.name.toLowerCase())
+ ),
+ }))
+ .filter(
+ ({ distance }) =>
+ distance <= Math.max(2, Math.floor(normalizedRequestedName.length / 3))
+ )
+ .sort(
+ (left, right) =>
+ left.distance - right.distance || left.name.localeCompare(right.name)
+ )
+ .slice(0, 3)
+ .map(({ name }) => name);
+ const suggestion =
+ suggestions.length === 0
+ ? ""
+ : ` Did you mean ${suggestions.map((name) => `"${name}"`).join(", ")}?`;
+ return `Unknown MCP tool "${requestedName}".${suggestion} Use meta.index to list available tools.`;
+};
export const isReadOnlyProjectSessionMcpTool = (tool: ProjectSessionMcpTool) =>
tool.annotations.method === "query" ||
@@ -6304,11 +6365,8 @@ export const isReadOnlyProjectSessionMcpToolCall = (
name: string,
tools: readonly ProjectSessionMcpTool[]
) => {
- const resolvedName = resolveToolName(name);
- return tools.some(
- (tool) =>
- tool.name === resolvedName && isReadOnlyProjectSessionMcpTool(tool)
- );
+ const tool = createToolNameIndex(tools).get(name);
+ return tool !== undefined && isReadOnlyProjectSessionMcpTool(tool);
};
const sdkScalarSchemaKeys = new Set([
@@ -7223,18 +7281,19 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
const operationByCommand = new Map(
operations.map((operation) => [operation.command, operation])
);
- const listTools = () =>
- listProjectSessionMcpTools(operations, {
- includeImport: importProject !== undefined,
- includeDownloadAsset: downloadAsset !== undefined,
- includeScreenshot: captureScreenshot !== undefined,
- includeResponsiveScreenshot: capturePageScreenshots !== undefined,
- includeScreenshotDiff: diffScreenshots !== undefined,
- includeInstallOcr: installOcr !== undefined,
- includePreview:
- startPreview !== undefined && getPreviewStatus !== undefined,
- includeRestorePoints: restorePoints !== undefined,
- });
+ const tools = listProjectSessionMcpTools(operations, {
+ includeImport: importProject !== undefined,
+ includeDownloadAsset: downloadAsset !== undefined,
+ includeScreenshot: captureScreenshot !== undefined,
+ includeResponsiveScreenshot: capturePageScreenshots !== undefined,
+ includeScreenshotDiff: diffScreenshots !== undefined,
+ includeInstallOcr: installOcr !== undefined,
+ includePreview:
+ startPreview !== undefined && getPreviewStatus !== undefined,
+ includeRestorePoints: restorePoints !== undefined,
+ });
+ const listTools = () => [...tools];
+ const toolNameIndex = createToolNameIndex(tools);
const getSession = () => {
session ??= createProjectSession();
return session;
@@ -7453,7 +7512,8 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
dryRun?: boolean;
signal?: AbortSignal;
}): Promise<ProjectSessionMcpToolResult> {
- name = resolveToolName(name);
+ const requestedName = name;
+ name = toolNameIndex.resolve(name);
if (name === "checkpoint.ack") {
if (
isRecord(input) === false ||
@@ -7578,11 +7638,15 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
return toCheckpointedMetaResult(name, getWorkflowNext(input));
}
if (name === "meta.get-more-tools") {
+ const normalizedInput = parseStringifiedJsonInputFields(
+ input,
+ toolDetailsInputSchema
+ );
return toMetaResult(
getMoreTools(
- getBrief(input, "meta.get-more-tools"),
- getToolNamesInput(input),
- listTools()
+ getBrief(normalizedInput, "meta.get-more-tools"),
+ getToolNamesInput(normalizedInput),
+ tools
)
);
}
@@ -7922,7 +7986,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
}
const operation = operationByCommand.get(name as Command);
if (operation === undefined) {
- throw new Error(`Unknown MCP tool "${name}".`);
+ throw new Error(getUnknownToolMessage(requestedName, tools));
}
const transportInput = getToolCallInput(input, operation.requiresConfirm);
const toolInput = transportInput.input;
@@ -8280,28 +8344,28 @@ export const createProjectSessionMcpServer = async <
sendLog("info", message);
},
});
- const exposedTools = core.listTools().map((tool) => ({
+ const tools = core.listTools();
+ const toolNameIndex = createToolNameIndex(tools);
+ const exposedTools = tools.map((tool) => ({
...tool,
name:
toolNameFormat === "underscores"
? toUnderscoredToolName(tool.name)
: tool.name,
}));
- const canonicalToolNameByExposedName = new Map<string, string>();
- for (const [index, tool] of core.listTools().entries()) {
- const exposedName = exposedTools[index]?.name;
- if (exposedName === undefined) {
- continue;
- }
- const existingName = canonicalToolNameByExposedName.get(exposedName);
- if (existingName !== undefined && existingName !== tool.name) {
+ if (toolNameFormat === "underscores") {
+ for (const [
+ exposedName,
+ canonicalNames,
+ ] of toolNameIndex.canonicalNamesByUnderscoredName) {
+ if (canonicalNames.length < 2) {
+ continue;
+ }
throw new Error(
- `MCP tool names ${existingName} and ${tool.name} both map to ${exposedName}.`
+ `MCP tool names ${canonicalNames.join(" and ")} both map to ${exposedName}.`
);
}
- canonicalToolNameByExposedName.set(exposedName, tool.name);
}
-
server.oninitialized = () => {
onInitialized?.(server.getClientVersion()?.name);
sendLog(
@@ -8355,7 +8419,7 @@ export const createProjectSessionMcpServer = async <
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
const params = getRequestParams(request);
const exposedName = typeof params.name === "string" ? params.name : "";
- const name = canonicalToolNameByExposedName.get(exposedName) ?? exposedName;
+ const name = toolNameIndex.resolve(exposedName);
const { input, dryRun } = getToolCallInput(params.arguments ?? {});
const startedAt = Date.now();
sendLog("info", `tool ${name} started${dryRun ? " (dry run)" : ""}`);
@@ -8413,9 +8477,72 @@ export const connectProjectSessionMcpServer = async <Command extends string>({
export const createMcpStdioTransport = async ({
stdin,
stdout,
+ partialFrameTimeoutMs = 5_000,
}: {
- stdin: ConstructorParameters<typeof StdioServerTransport>[0];
+ stdin: NonNullable<ConstructorParameters<typeof StdioServerTransport>[0]>;
stdout: ConstructorParameters<typeof StdioServerTransport>[1];
+ partialFrameTimeoutMs?: number;
}): Promise<McpTransport> => {
- return new StdioServerTransport(stdin, stdout);
+ let partialFrame: Buffer | undefined;
+ let discardTimer: ReturnType<typeof setTimeout> | undefined;
+ const clearDiscardTimer = () => {
+ if (discardTimer !== undefined) {
+ clearTimeout(discardTimer);
+ discardTimer = undefined;
+ }
+ };
+ const scheduleDiscard = () => {
+ clearDiscardTimer();
+ if (partialFrame === undefined || partialFrameTimeoutMs <= 0) {
+ return;
+ }
+ discardTimer = setTimeout(() => {
+ partialFrame = undefined;
+ discardTimer = undefined;
+ }, partialFrameTimeoutMs);
+ discardTimer.unref?.();
+ };
+ const recoveringInput = new Transform({
+ transform(chunk: Buffer | string, encoding: BufferEncoding, callback) {
+ const nextChunk = Buffer.isBuffer(chunk)
+ ? chunk
+ : Buffer.from(chunk, encoding);
+ const buffered =
+ partialFrame === undefined
+ ? nextChunk
+ : Buffer.concat([partialFrame, nextChunk]);
+ const lastNewline = buffered.lastIndexOf(10);
+ if (lastNewline === -1) {
+ partialFrame = buffered;
+ scheduleDiscard();
+ callback();
+ return;
+ }
+ clearDiscardTimer();
+ this.push(buffered.subarray(0, lastNewline + 1));
+ const remainder = buffered.subarray(lastNewline + 1);
+ partialFrame = remainder.length === 0 ? undefined : remainder;
+ scheduleDiscard();
+ callback();
+ },
+ flush(callback) {
+ clearDiscardTimer();
+ partialFrame = undefined;
+ callback();
+ },
+ destroy(error, callback) {
+ clearDiscardTimer();
+ partialFrame = undefined;
+ callback(error);
+ },
+ });
+ stdin.pipe(recoveringInput);
+ const transport = new StdioServerTransport(recoveringInput, stdout);
+ const closeTransport = transport.close.bind(transport);
+ transport.close = async () => {
+ await closeTransport();
+ stdin.unpipe(recoveringInput);
+ recoveringInput.destroy();
+ };
+ return transport;
};
diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsx
index 478e5f6aac..f2c63f64e5 100644
--- a/packages/project-build/src/runtime/data.test.tsx
+++ b/packages/project-build/src/runtime/data.test.tsx
@@ -693,6 +693,141 @@ test("update data variable converts resource data source and deletes resource",
]);
});
+test("renames a resource-backed variable without replacing its value", () => {
+ const dataSource: DataSource = {
+ id: "data-source-id",
+ scopeInstanceId: "body",
+ name: "ficheMoto",
+ type: "resource",
+ resourceId: "resource-id",
+ };
+ const resource: Resource = {
+ id: "resource-id",
+ name: "Motorcycles",
+ method: "get",
+ url: `"https://example.com/motorcycles"`,
+ headers: [],
+ };
+
+ expect(
+ updateDataVariable(
+ {
+ pages: createDefaultPages({ rootInstanceId: "body" }),
+ instances: new Map(),
+ props: new Map(),
+ dataSources: new Map([[dataSource.id, dataSource]]),
+ resources: new Map([[resource.id, resource]]),
+ },
+ {
+ dataSourceId: dataSource.id,
+ values: { name: "ficheQuad" },
+ }
+ ).payload
+ ).toEqual([
+ {
+ namespace: "dataSources",
+ patches: [
+ {
+ op: "replace",
+ path: ["data-source-id", "name"],
+ value: "ficheQuad",
+ },
+ ],
+ },
+ ]);
+});
+
+test("rebinds expressions when moving a resource-backed variable", () => {
+ const dataSource: DataSource = {
+ id: "data-source-id",
+ scopeInstanceId: "old-scope",
+ name: "records",
+ type: "resource",
+ resourceId: "resource-id",
+ };
+ const resource: Resource = {
+ id: "resource-id",
+ name: "Records",
+ method: "get",
+ url: `"https://example.com/records"`,
+ headers: [],
+ };
+
+ expect(
+ updateDataVariable(
+ {
+ pages: createDefaultPages({ rootInstanceId: "body" }),
+ instances: new Map([
+ [
+ "body",
+ {
+ type: "instance",
+ id: "body",
+ component: "Body",
+ children: [
+ { type: "id", value: "new-scope" },
+ { type: "id", value: "old-scope" },
+ ],
+ },
+ ],
+ [
+ "new-scope",
+ {
+ type: "instance",
+ id: "new-scope",
+ component: "Box",
+ children: [{ type: "expression", value: "records" }],
+ },
+ ],
+ [
+ "old-scope",
+ {
+ type: "instance",
+ id: "old-scope",
+ component: "Box",
+ children: [],
+ },
+ ],
+ ]),
+ props: new Map(),
+ dataSources: new Map([[dataSource.id, dataSource]]),
+ resources: new Map([[resource.id, resource]]),
+ },
+ {
+ dataSourceId: dataSource.id,
+ values: { scopeInstanceId: "new-scope" },
+ }
+ ).payload
+ ).toEqual([
+ {
+ namespace: "instances",
+ patches: [
+ {
+ op: "replace",
+ path: ["new-scope", "children", 0, "value"],
+ value: encodeDataVariableId("data-source-id"),
+ },
+ ],
+ },
+ {
+ namespace: "dataSources",
+ patches: [
+ {
+ op: "replace",
+ path: ["data-source-id"],
+ value: {
+ id: "data-source-id",
+ scopeInstanceId: "new-scope",
+ name: "records",
+ type: "resource",
+ resourceId: "resource-id",
+ },
+ },
+ ],
+ },
+ ]);
+});
+
test("dencode data variable name with dollar sign", () => {
expect(
decodeDataVariableName(encodeDataVariableName("$my$Variable"))
diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.ts
index 0290c8462c..848c342f1f 100644
--- a/packages/project-build/src/runtime/data.ts
+++ b/packages/project-build/src/runtime/data.ts
@@ -1333,18 +1333,18 @@ export const createDataVariableCreatePayload = ({
};
};
-const createDataVariableUpsertPayload = ({
+const createDataSourceUpsertPayload = ({
pages,
instances,
props,
dataSources,
resources,
- variable,
+ dataSource,
}: Pick<
BuilderState,
"pages" | "instances" | "props" | "dataSources" | "resources"
> & {
- variable: DataVariable;
+ dataSource: DataSource;
}) => {
if (
instances === undefined ||
@@ -1354,20 +1354,20 @@ const createDataVariableUpsertPayload = ({
) {
return [];
}
- if (variable.scopeInstanceId === undefined) {
+ if (dataSource.scopeInstanceId === undefined) {
return [];
}
- const scopeInstanceId = variable.scopeInstanceId;
+ const scopeInstanceId = dataSource.scopeInstanceId;
return produceWebstudioDataMutation(
{ pages, instances, props, dataSources, resources },
(draft) => {
- if (variable.type === "variable") {
- const previous = draft.dataSources.get(variable.id);
+ if (dataSource.type === "variable") {
+ const previous = draft.dataSources.get(dataSource.id);
if (previous?.type === "resource") {
draft.resources.delete(previous.resourceId);
}
}
- draft.dataSources.set(variable.id, variable);
+ draft.dataSources.set(dataSource.id, dataSource);
rebindTreeVariablesMutable({
startingInstanceId: scopeInstanceId,
...draft,
@@ -1381,7 +1381,7 @@ export const createDataVariableUpdatePayload = ({
values,
dataSources,
}: {
- variable: DataVariable;
+ variable: Pick<DataSource, "id" | "name" | "scopeInstanceId">;
values: Partial<Pick<DataVariable, "scopeInstanceId" | "name" | "value">>;
dataSources: Iterable<DataSource>;
}) => {
@@ -1445,9 +1445,9 @@ export const createDataVariable = (
});
return createRuntimeMutation({
payload:
- createDataVariableUpsertPayload({
+ createDataSourceUpsertPayload({
...state,
- variable,
+ dataSource: variable,
}) ?? payload,
result: { dataSourceId },
invalidatesNamespaces: [
@@ -1472,12 +1472,6 @@ export const updateDataVariable = (
if (dataSource === undefined) {
return throwBuilderRuntimeError("NOT_FOUND", "Variable not found");
}
- if (dataSource.type !== "variable" && input.values.value === undefined) {
- return throwBuilderRuntimeError(
- "BAD_REQUEST",
- "Variable value is required"
- );
- }
const scopeInstanceId =
input.values.scopeInstanceId ?? dataSource.scopeInstanceId;
if (scopeInstanceId === undefined) {
@@ -1486,30 +1480,49 @@ export const updateDataVariable = (
"Variable scope instance is required"
);
}
- const variable =
- dataSource.type === "variable"
- ? dataSource
- : createDataVariableValue({
- dataSourceId: dataSource.id,
- scopeInstanceId,
- name: dataSource.name,
- value: input.values.value ?? { type: "string", value: "" },
- });
- const { error } = createDataVariableUpdatePayload({
- variable,
+ const { error, payload } = createDataVariableUpdatePayload({
+ variable: dataSource,
values: input.values,
dataSources: dataSources.values(),
});
if (error) {
return throwBuilderRuntimeError("BAD_REQUEST", error.message);
}
- const nextVariable = { ...variable, ...input.values };
+ const { value, ...metadataValues } = input.values;
+ if (
+ dataSource.type === "resource" &&
+ value === undefined &&
+ (metadataValues.scopeInstanceId === undefined ||
+ metadataValues.scopeInstanceId === dataSource.scopeInstanceId)
+ ) {
+ return createRuntimeMutation({
+ payload,
+ result: { dataSourceId: dataSource.id },
+ invalidatesNamespaces: ["dataSources"],
+ });
+ }
+ const nextDataSource =
+ dataSource.type === "resource" && value !== undefined
+ ? {
+ ...createDataVariableValue({
+ dataSourceId: dataSource.id,
+ scopeInstanceId,
+ name: dataSource.name,
+ value,
+ }),
+ ...metadataValues,
+ }
+ : {
+ ...dataSource,
+ ...metadataValues,
+ ...(value === undefined ? {} : { value }),
+ };
return createRuntimeMutation({
- payload: createDataVariableUpsertPayload({
+ payload: createDataSourceUpsertPayload({
...state,
- variable: nextVariable,
+ dataSource: nextDataSource,
}),
- result: { dataSourceId: variable.id },
+ result: { dataSourceId: nextDataSource.id },
invalidatesNamespaces: [
"pages",
"instances",
diff --git a/packages/project-build/src/runtime/styles.test.ts b/packages/project-build/src/runtime/styles.test.ts
index 84a85e4326..86fffe92ee 100644
--- a/packages/project-build/src/runtime/styles.test.ts
+++ b/packages/project-build/src/runtime/styles.test.ts
@@ -1361,6 +1361,40 @@ describe("runtime style operations", () => {
});
});
+ test("parses CSS strings when updating design token styles", () => {
+ const mutation = updateDesignTokenStyles(
+ {
+ breakpoints: runtimeBreakpoints,
+ styles: new Map(),
+ styleSources: sources([token("token", "Layout")]),
+ styleSourceSelections: new Map(),
+ },
+ {
+ designTokenId: "token",
+ updates: [
+ {
+ property: "max-width",
+ value: "max(var(--x), calc(50% - 40rem))",
+ },
+ ],
+ }
+ );
+
+ expect(mutation.payload).toContainEqual({
+ namespace: "styles",
+ patches: [
+ {
+ op: "add",
+ path: ["token:desktop:maxWidth:"],
+ value: createStyleDecl("token", "desktop", "maxWidth", {
+ type: "unparsed",
+ value: "max(var(--x), calc(50% - 40rem))",
+ }),
+ },
+ ],
+ });
+ });
+
test("creates and attaches design tokens atomically", () => {
const mutation = createAttachedDesignTokens(
{
diff --git a/packages/project-build/src/runtime/styles.ts b/packages/project-build/src/runtime/styles.ts
index fa013623f0..76671f6332 100644
--- a/packages/project-build/src/runtime/styles.ts
+++ b/packages/project-build/src/runtime/styles.ts
@@ -1363,25 +1363,21 @@ export const validateStyleSourceName = ({
export const createDesignTokenStyleInputs = (input: {
styles?: Record<string, z.infer<typeof designTokenStyleValueInput>>;
declarations?: DesignTokenStyleInput[];
-}): Array<Omit<DesignTokenStyleInput, "value"> & { value: StyleValue }> => [
- ...Object.entries(input.styles ?? {}).map(([property, value]) => ({
- property,
+}): Array<Omit<DesignTokenStyleInput, "value"> & { value: StyleValue }> => {
+ const parseInput = ({ value, ...declaration }: DesignTokenStyleInput) => ({
+ ...declaration,
value:
typeof value === "string"
- ? parseCssValue(hyphenateProperty(property), value)
+ ? parseCssValue(hyphenateProperty(declaration.property), value)
: styleValue.parse(value),
- })),
- ...(input.declarations ?? []).map((declaration) => ({
- ...declaration,
- value:
- typeof declaration.value === "string"
- ? parseCssValue(
- hyphenateProperty(declaration.property),
- declaration.value
- )
- : styleValue.parse(declaration.value),
- })),
-];
+ });
+ return [
+ ...Object.entries(input.styles ?? {}).map(([property, value]) =>
+ parseInput({ property, value })
+ ),
+ ...(input.declarations ?? []).map(parseInput),
+ ];
+};
export const getLocalStyleSourceId = ({
styleSources,
@@ -3806,8 +3802,8 @@ export const updateDesignTokenStyles = (
getDesignTokenOrThrow(styleState.styleSources.values(), input.designTokenId);
const { payload, styleKeys } = createDesignTokenStyleUpdatePayload({
designTokenId: input.designTokenId,
- updates: input.updates.map((update) =>
- withValidatedBreakpoint(update, state.breakpoints)
+ updates: createDesignTokenStyleInputs({ declarations: input.updates }).map(
+ (update) => withValidatedBreakpoint(update, state.breakpoints)
),
styles: styleState.styles.values(),
});
diff --git a/packages/project-build/src/visual/screenshot-text-diff.ts b/packages/project-build/src/visual/screenshot-text-diff.ts
index a2759c143e..bdc7607881 100644
--- a/packages/project-build/src/visual/screenshot-text-diff.ts
+++ b/packages/project-build/src/visual/screenshot-text-diff.ts
@@ -4,6 +4,7 @@
* License: Apache-2.0
*/
+import { distance as getLevenshteinDistance } from "fastest-levenshtein";
import { extractOcrTextBlocks, type OcrTextBlock } from "./screenshot-ocr";
import type {
ScreenshotDiffBounds,
@@ -635,31 +636,8 @@ const normalizedTextSimilarity = (left: string, right: string) =>
left === right
? 1
: 1 -
- levenshteinDistance(left, right) / Math.max(left.length, right.length, 1);
-
-const levenshteinDistance = (left: string, right: string) => {
- const previous = new Array<number>(right.length + 1);
- const current = new Array<number>(right.length + 1);
- for (let index = 0; index <= right.length; index++) {
- previous[index] = index;
- }
-
- for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {
- current[0] = leftIndex;
- for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {
- const cost = left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1;
- current[rightIndex] = Math.min(
- current[rightIndex - 1] + 1,
- previous[rightIndex] + 1,
- previous[rightIndex - 1] + cost
- );
- }
- for (let index = 0; index <= right.length; index++) {
- previous[index] = current[index];
- }
- }
- return previous[right.length];
-};
+ getLevenshteinDistance(left, right) /
+ Math.max(left.length, right.length, 1);
const boundsDelta = (
baseline: ScreenshotDiffBounds,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 35a705376c..fb04bb59a8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1279,6 +1279,9 @@ importers:
deepmerge:
specifier: ^4.3.1
version: 4.3.1
+ detect-port:
+ specifier: ^2.1.0
+ version: 2.1.0
env-paths:
specifier: ^3.0.0
version: 3.0.0
@@ -1288,6 +1291,9 @@ importers:
fast-deep-equal:
specifier: ^3.1.3
version: 3.1.3
+ get-port:
+ specifier: ^7.2.0
+ version: 7.2.0
immer:
specifier: ^10.1.1
version: 10.1.1
@@ -1300,6 +1306,9 @@ importers:
parse5:
specifier: 7.3.0
version: 7.3.0
+ path-key:
+ specifier: ^4.0.0
+ version: 4.0.0
picocolors:
specifier: ^1.1.1
version: 1.1.1
@@ -1315,6 +1324,9 @@ importers:
warn-once:
specifier: ^0.1.1
version: 0.1.1
+ which:
+ specifier: ^5.0.0
+ version: 5.0.0
yargs:
specifier: ^17.7.2
version: 17.7.2
@@ -1373,6 +1385,9 @@ importers:
'@types/react-dom':
specifier: ^18.2.25
version: 18.2.25
+ '@types/which':
+ specifier: ^3.0.4
+ version: 3.0.4
'@types/yargs':
specifier: ^17.0.33
version: 17.0.33
@@ -2234,6 +2249,9 @@ importers:
fast-png:
specifier: 8.0.0
version: 8.0.0
+ fastest-levenshtein:
+ specifier: ^1.0.16
+ version: 1.0.16
immer:
specifier: ^10.1.1
version: 10.1.1
@@ -6755,6 +6773,9 @@ packages:
resolution: {integrity: sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-liyfuo/106JdlgSchJzXEQCVArk0CvevqPote8F8HgWgJ3dRCcTHgJIsLDuee0kxk/mhbInzIZk3QWSZJ8R+2w==}
+
resolution: {integrity: sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==}
@@ -7055,6 +7076,10 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
+ resolution: {integrity: sha512-XNAb/a6TCqou+TufU8/u11HCu9x1gYvOoxLwtlXgIqmkrYQADVv6ljyW2zwiPhHz9R1gItAWpuDrdJMmrOBFEA==}
+ engines: {node: '>= 16.0.0'}
+
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
@@ -7824,6 +7849,11 @@ packages:
resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}
+ resolution: {integrity: sha512-epZuWb/6Q62L+nDHJc/hQAqf8pylsqgk3BpZXVBx1CDnr3nkrVNn73Uu1rXcFzkNcc+hkP3whuOg7JZYaQB65Q==}
+ engines: {node: '>= 16.0.0'}
+ hasBin: true
+
resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
@@ -8201,6 +8231,10 @@ packages:
resolution: {integrity: sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==}
+ resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==}
+ engines: {node: '>= 4.9.1'}
+
resolution: {integrity: sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==}
@@ -8379,8 +8413,8 @@ packages:
resolution: {integrity: sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-QB9NKEeDg3xxVwCCwJQ9+xycaz6pBB6iQ76wiWMl1927n0Kir6alPiP+yuiICLLU4jpMe08dXfpebuQppFA2zw==}
+ resolution: {integrity: sha512-afP4W205ONCuMoPBqcR6PSXnzX35KTcJygfJfcp+QY+uwm3p20p1YczWXhlICIzGMCxYBQcySEcOgsJcrkyobg==}
engines: {node: '>=16'}
@@ -11595,6 +11629,11 @@ packages:
engines: {node: ^16.13.0 || >=18.0.0}
hasBin: true
+ resolution: {integrity: sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==}
+ engines: {node: ^18.17.0 || >=20.5.0}
+ hasBin: true
+
resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
engines: {node: '>=8'}
@@ -12589,7 +12628,7 @@ snapshots:
'@cloudflare/unenv-preset': 2.3.1([email protected])([email protected])
'@hattip/adapter-node': 0.0.49
'@rollup/plugin-replace': 6.0.2([email protected])
- get-port: 7.1.0
+ get-port: 7.2.0
miniflare: 4.20250428.1
picocolors: 1.1.1
tinyglobby: 0.2.13
@@ -12608,7 +12647,7 @@ snapshots:
'@cloudflare/unenv-preset': 2.3.1([email protected])([email protected])
'@hattip/adapter-node': 0.0.49
'@rollup/plugin-replace': 6.0.2([email protected])
- get-port: 7.1.0
+ get-port: 7.2.0
miniflare: 4.20250428.1
picocolors: 1.1.1
tinyglobby: 0.2.13
@@ -16011,6 +16050,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
@@ -16342,6 +16383,8 @@ snapshots:
+
dependencies:
debug: 4.4.3
@@ -17063,6 +17106,10 @@ snapshots:
+ dependencies:
+ address: 2.0.3
+
dependencies:
dequal: 2.0.3
@@ -17621,6 +17668,8 @@ snapshots:
+
dependencies:
reusify: 1.0.4
@@ -17814,7 +17863,7 @@ snapshots:
dependencies:
@@ -21633,6 +21682,10 @@ snapshots:
dependencies:
isexe: 3.1.5
+ dependencies:
+ isexe: 3.1.5
+
dependencies:
siginfo: 2.0.0