Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: MCP fixes (#5870)
Oleg Isonen7d781bdc867e
diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/animations-select.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/animations-select.tsxindex 922cc1e2c3..5d9c631247 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/animations-select.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/animations-select.tsx@@ -46,6 +46,7 @@ import { newViewAnimations } from "./new-view-animations";import { AnimationPanelContent } from "./animation-panel-content";import { CollapsibleSectionRoot } from "~/builder/shared/collapsible-section";import { z } from "zod";+import { readClipboardText } from "~/shared/clipboard";const newAnimationsPerType: {scroll: ScrollAnimation[];@@ -116,9 +117,11 @@ const AnimationContextMenu = ({const pasteAnimations = () => {const index = lastClickedAnimationIndex.current;- navigator.clipboard- .readText()+ readClipboardText().then((text) => {+ if (text === undefined) {+ return;+ }if (action.type === "scroll") {const animations = parseScrollAnimations(text);const newAction = structuredClone(action);diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex b2a8058723..374297b915 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -70,6 +70,7 @@ import { showWrapComponentsList } from "../features/command-panel/groups/wrap-grimport { showConvertComponentsList } from "../features/command-panel/groups/convert-group";import { showDuplicateTokensView } from "../features/command-panel/groups/duplicate-tokens-group";import { builderApi } from "~/shared/builder-api";+import { readClipboardText } from "~/shared/clipboard";import { getSetting, setSetting } from "./client-settings";import { generateFragmentFromHtml } from "@webstudio-is/project-build/runtime/html";import { generateFragmentFromTailwind } from "~/shared/tailwind/tailwind";@@ -1087,7 +1088,10 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({) {return;}- const html = await navigator.clipboard.readText();+ const html = await readClipboardText();+ if (html === undefined) {+ return;+ }const parseResult = generateFragmentFromHtml(html);const { skippedSelectors } = parseResult;let fragment: WebstudioFragment = parseResult;diff --git a/apps/builder/app/builder/shared/css-editor/css-editor-context-menu.tsx b/apps/builder/app/builder/shared/css-editor/css-editor-context-menu.tsxindex 7456675c81..ffc674e8a1 100644--- a/apps/builder/app/builder/shared/css-editor/css-editor-context-menu.tsx+++ b/apps/builder/app/builder/shared/css-editor/css-editor-context-menu.tsx@@ -14,6 +14,7 @@ import {type CssStyleMap,} from "@webstudio-is/css-engine";import type { ComputedStyleDecl } from "~/shared/style-object-model";+import { readClipboardText } from "~/shared/clipboard";export const copyAttribute = "data-declaration";@@ -34,8 +35,11 @@ export const CssEditorContextMenu = ({}) => {const lastClickedProperty = useRef<string>();- const handlePaste = () => {- navigator.clipboard.readText().then(onPaste);+ const handlePaste = async () => {+ const text = await readClipboardText();+ if (text !== undefined) {+ onPaste(text);+ }};// Gets all currently visible declarations based on what's in the search or filters.diff --git a/apps/builder/app/services/api-build.server.test.ts b/apps/builder/app/services/api-build.server.test.tsindex c0e0f41969..ace0c5485f 100644--- a/apps/builder/app/services/api-build.server.test.ts+++ b/apps/builder/app/services/api-build.server.test.ts@@ -286,6 +286,18 @@ describe("api build snapshot", () => {test("returns page folders and data namespaces when requested", () => {const pages = createDefaultPages({ rootInstanceId: "root-1" });pages.redirects = [{ old: "/old", new: "/new", status: "301" }];+ pages.pageTemplates = new Map([+ [+ "template-1",+ {+ id: "template-1",+ name: "Landing",+ title: "Landing",+ rootInstanceId: "template-root-1",+ meta: {},+ },+ ],+ ]);const build = {id: "build-1",projectId: "project-1",@@ -332,6 +344,15 @@ describe("api build snapshot", () => {compiler: { atomicStyles: true },},redirects: [{ old: "/old", new: "/new", status: "301" }],+ pageTemplates: [+ {+ id: "template-1",+ name: "Landing",+ title: "Landing",+ rootInstanceId: "template-root-1",+ meta: {},+ },+ ],resources: [{ id: "resource-1" }],variables: [{ id: "variable-1" }],breakpoints: [{ id: "breakpoint-1" }],diff --git a/apps/builder/app/services/api-build.server.ts b/apps/builder/app/services/api-build.server.tsindex 6780f8afab..d3637f262b 100644--- a/apps/builder/app/services/api-build.server.ts+++ b/apps/builder/app/services/api-build.server.ts@@ -102,6 +102,7 @@ export const createBuildSnapshot = ({snapshot.rootFolderId = pages.rootFolderId;if (include.has("pages")) {snapshot.redirects = pages.redirects;+ snapshot.pageTemplates = pages.pageTemplates;}add("pages", pages.pages);add("folders", pages.folders);diff --git a/apps/builder/app/services/api-compatibility.server.test.ts b/apps/builder/app/services/api-compatibility.server.test.tsdeleted file mode 100644index f4bd12c7ac..0000000000--- a/apps/builder/app/services/api-compatibility.server.test.ts+++ /dev/null@@ -1,32 +0,0 @@-import { describe, expect, test } from "vitest";-import { getApiCompatibilityPayload } from "@webstudio-is/trpc-interface/api-compatibility";-import { assertCliProjectSettingsContract } from "./api-compatibility.server";--describe("API client compatibility", () => {- test("requires updated CLI clients when pages move to project settings", () => {- let error: unknown;- try {- assertCliProjectSettingsContract("cli", new Set(["pages"]));- } catch (caught) {- error = caught;- }-- expect(getApiCompatibilityPayload(error)).toMatchObject({- reason: "clientVersionUnsupported",- target: "cli",- action: { type: "updateCli" },- });- });-- test("accepts current CLI and non-CLI snapshot contracts", () => {- expect(() =>- assertCliProjectSettingsContract(- "cli",- new Set(["pages", "projectSettings"])- )- ).not.toThrow();- expect(() =>- assertCliProjectSettingsContract("browser", new Set(["pages"]))- ).not.toThrow();- });-});diff --git a/apps/builder/app/services/api-compatibility.server.ts b/apps/builder/app/services/api-compatibility.server.tsindex 21902173f7..a8b91ae12d 100644--- a/apps/builder/app/services/api-compatibility.server.ts+++ b/apps/builder/app/services/api-compatibility.server.ts@@ -1,7 +1,6 @@import { TRPCError } from "@trpc/server";import {createApiCompatibilityPayload,- type ApiClient,type ApiCompatibilityTarget,} from "@webstudio-is/trpc-interface/api-compatibility";@@ -17,16 +16,3 @@ export const throwApiClientUpdateRequired = (}),});};--export const assertCliProjectSettingsContract = (- client: ApiClient | "unknown" | undefined,- include: ReadonlySet<string>-) => {- if (- client === "cli" &&- include.has("pages") &&- include.has("projectSettings") === false- ) {- throwApiClientUpdateRequired("cli");- }-};diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.tsindex 68cf914dce..3da001c450 100644--- a/apps/builder/app/services/api-router.server.test.ts+++ b/apps/builder/app/services/api-router.server.test.ts@@ -71,6 +71,35 @@ const createCaller = (context: AppContext) =>apiRouter.createCaller(context) as ApiRouterCaller & RuntimeApiCaller;describe("api router build operation adapters", () => {+ test("allows CLI clients to refresh pages without project settings", async () => {+ const build = {+ id: "build-1",+ projectId: "project-1",+ version: 1,+ pages: createDefaultPages({ rootInstanceId: "root" }),+ projectSettings: { agents: "Project instructions" },+ } as unknown as Awaited<+ ReturnType<typeof projectBuild.loadDevBuildByProjectId>+ >;+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue(build);++ const caller = createCaller({+ ...createContext(true),+ apiClient: { type: "cli", version: "0.276.0" },+ });++ await expect(+ caller.build.get({ projectId: "project-1", include: ["pages"] })+ ).resolves.toMatchObject({+ projectId: "project-1",+ buildId: "build-1",+ version: 1,+ pages: expect.any(Array),+ });+ });+test("public operation catalog paths exist on the api router", () => {const procedures = getApiRouterProcedures(apiRouter);diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.tsindex e93b46457e..a044a05ea7 100644--- a/apps/builder/app/services/api-router.server.ts+++ b/apps/builder/app/services/api-router.server.ts@@ -55,7 +55,6 @@ import {serializeProjectSummary,} from "./api-build.server";import { throwApiError } from "./api-errors.server";-import { assertCliProjectSettingsContract } from "./api-compatibility.server";import {createBuilderRuntimeState,executeApiRuntimeMutation,@@ -595,7 +594,6 @@ export const apiRouter = router({}const include = new Set(input.include ?? []);- assertCliProjectSettingsContract(ctx.apiClient?.type, include);const snapshot = createBuildSnapshot({build,include,diff --git a/apps/builder/app/services/api-runtime.server.test.ts b/apps/builder/app/services/api-runtime.server.test.tsindex ebe5c6efa9..468e6bfd9e 100644--- a/apps/builder/app/services/api-runtime.server.test.ts+++ b/apps/builder/app/services/api-runtime.server.test.ts@@ -13,7 +13,14 @@ const createBuild = (): CompactBuild =>projectId: "project-1",version: 1,pages: createDefaultPages({ rootInstanceId: "root-1" }),- instances: [{ type: "instance", id: "root-1", component: "Body" }],+ instances: [+ {+ type: "instance",+ id: "root-1",+ component: "Body",+ children: [],+ },+ ],props: [],styles: [],styleSources: [],@@ -60,6 +67,16 @@ describe("api runtime adapter", () => {).rejects.toThrow("Page not found");});+ test("strips API transport fields before strict runtime validation", async () => {+ await expect(+ executeApiRuntimeOperation({+ id: "project.search",+ build: createBuild(),+ input: { projectId: "project-1", query: "Home" },+ })+ ).resolves.toMatchObject({ query: "Home" });+ });+test("awaits async runtime mutations before reading mutation payload", async () => {const mutation = await executeApiRuntimeOperation({id: "instances.insertComponent",diff --git a/apps/builder/app/services/staged-upload.server.test.ts b/apps/builder/app/services/staged-upload.server.test.tsindex 5bbc265ab4..8fc0604d4c 100644--- a/apps/builder/app/services/staged-upload.server.test.ts+++ b/apps/builder/app/services/staged-upload.server.test.ts@@ -29,6 +29,7 @@ describe("staged upload server", () => {expect(server.options.path).toBe(stagedUploadPath);expect(server.options.maxSize).toBe(maxProjectBundleSize);+ expect(server.options.relativeLocation).toBe(true);expect(server.options.allowedHeaders).toContain(stagedUploadProjectIdHeader);diff --git a/apps/builder/app/services/staged-upload.server.ts b/apps/builder/app/services/staged-upload.server.tsindex 40fdf0a08b..80f7a5b385 100644--- a/apps/builder/app/services/staged-upload.server.ts+++ b/apps/builder/app/services/staged-upload.server.ts@@ -124,7 +124,7 @@ const createStagedUploadServer = (path: stagedUploadPath,datastore: dependencies.datastore ?? createStagedUploadStore(),maxSize: maxProjectBundleSize,- relativeLocation: false,+ relativeLocation: true,respectForwardedHeaders: true,allowedHeaders: [authTokenHeader, stagedUploadProjectIdHeader],async onIncomingRequest(request) {diff --git a/apps/builder/app/shared/clipboard.test.ts b/apps/builder/app/shared/clipboard.test.tsnew file mode 100644index 0000000000..5b901835ea--- /dev/null+++ b/apps/builder/app/shared/clipboard.test.ts@@ -0,0 +1,35 @@+import { afterEach, expect, test, vi } from "vitest";+import { initBuilderApi } from "./builder-api";+import { readClipboardText } from "./clipboard";++afterEach(() => {+ vi.unstubAllGlobals();+});++test("reads clipboard text", async () => {+ vi.stubGlobal("navigator", {+ clipboard: { readText: vi.fn().mockResolvedValue("clipboard text") },+ });++ await expect(readClipboardText()).resolves.toBe("clipboard text");+});++test("reports denied clipboard access without rejecting", async () => {+ initBuilderApi();+ const toastError = vi.fn();+ window.__webstudio__$__builderApi.toast.error = toastError;+ vi.stubGlobal("navigator", {+ clipboard: {+ readText: vi+ .fn()+ .mockRejectedValue(+ new DOMException("Permission denied", "NotAllowedError")+ ),+ },+ });++ await expect(readClipboardText()).resolves.toBeUndefined();+ expect(toastError).toHaveBeenCalledWith(+ "Webstudio cannot read the clipboard. Allow clipboard access in your browser, then try again."+ );+});diff --git a/apps/builder/app/shared/clipboard.ts b/apps/builder/app/shared/clipboard.tsnew file mode 100644index 0000000000..ac9037b3cf--- /dev/null+++ b/apps/builder/app/shared/clipboard.ts@@ -0,0 +1,12 @@+import { builderApi } from "./builder-api";++const clipboardReadErrorMessage =+ "Webstudio cannot read the clipboard. Allow clipboard access in your browser, then try again.";++export const readClipboardText = async () => {+ try {+ return await navigator.clipboard.readText();+ } catch {+ builderApi.toast.error(clipboardReadErrorMessage);+ }+};diff --git a/apps/builder/app/shared/copy-paste/copy-paste.ts b/apps/builder/app/shared/copy-paste/copy-paste.tsindex 6afa8cb55d..31d00cb3d1 100644--- a/apps/builder/app/shared/copy-paste/copy-paste.ts+++ b/apps/builder/app/shared/copy-paste/copy-paste.ts@@ -16,6 +16,7 @@ import { jsx } from "./plugin-jsx";import { markdown } from "./plugin-markdown";import { webflow } from "./plugin-webflow/plugin-webflow";import { builderApi } from "../builder-api";+import { readClipboardText } from "../clipboard";const isTextEditing = (event: ClipboardEvent) => {// Text is edited on the Canvas using the default Canvas text editor settings.@@ -291,14 +292,20 @@ export const copyTemplate = (templateId: string) => {};export const pastePage = async (targetFolderId?: string) => {- const text = await navigator.clipboard.readText();+ const text = await readClipboardText();+ if (text === undefined) {+ return false;+ }const result = await handlePastePage(text, targetFolderId);reportPasteResult(result);return isPasteHandled(result);};export const emitPaste = async () => {- const text = await navigator.clipboard.readText();+ const text = await readClipboardText();+ if (text === undefined) {+ return;+ }// Create and dispatch a paste event to go through the normal handlePaste flowconst dataTransfer = new DataTransfer();diff --git a/apps/builder/e2e/flows/generated-app.ts b/apps/builder/e2e/flows/generated-app.tsindex 481946fba6..f9ac74f600 100644--- a/apps/builder/e2e/flows/generated-app.ts+++ b/apps/builder/e2e/flows/generated-app.ts@@ -318,8 +318,20 @@ export const expectGeneratedAppNavigation = async ({name: linkText,exact: true,});- const ariaCurrent = await activeLink.getAttribute("aria-current");- if (ariaCurrent !== "page") {+ try {+ await activeLink.waitFor({ state: "visible" });+ await page.waitForFunction(+ ({ linkText }) =>+ Array.from(document.querySelectorAll("a")).some(+ (link) =>+ link.textContent?.trim() === linkText &&+ link.getAttribute("aria-current") === "page"+ ),+ { linkText },+ { timeout: 10_000 }+ );+ } catch {+ const ariaCurrent = await activeLink.getAttribute("aria-current");throw new Error(`Expected generated preview link ${JSON.stringify(linkText)} to be active after navigating to ${JSON.stringify(targetPath)}. Received aria-current=${JSON.stringify(ariaCurrent)}.`);diff --git a/packages/asset-uploader/src/asset-patch-core.ts b/packages/asset-uploader/src/asset-patch-core.tsindex 93ccfb10a6..4947881fe9 100644--- a/packages/asset-uploader/src/asset-patch-core.ts+++ b/packages/asset-uploader/src/asset-patch-core.ts@@ -127,8 +127,7 @@ export const patchAssetsWithClient = async (assetsMap.set(asset.id, asset);}const patchedAssets = applyPatches(assetsMap, patches);- // validate assets without recreating objects- // we expect referencial equality to find updated assets+ // Validate assets without recreating objects.assets.parse(patchedAssets);const deletedAssetIds: Asset["id"][] = [];@@ -143,14 +142,28 @@ export const patchAssetsWithClient = async (for (const asset of assetsMap.values()) {const patchedAsset = patchedAssets.get(asset.id);- if (asset !== patchedAsset && patchedAsset) {+ const metadataChanged =+ patchedAsset !== undefined &&+ (asset.filename !== patchedAsset.filename ||+ asset.description !== patchedAsset.description);+ if (metadataChanged) {const { filename, description } = patchedAsset;const updatedAsset = await client.from("Asset").update({ filename, description }).eq("id", asset.id)- .eq("projectId", asset.projectId);+ .eq("projectId", asset.projectId)+ .select("filename, description")+ .single();assertPostgrestSuccess(updatedAsset);+ if (+ updatedAsset.data?.filename !== (filename ?? null) ||+ updatedAsset.data?.description !== (description ?? null)+ ) {+ throw new Error(+ `Asset metadata update was not persisted for ${asset.id}`+ );+ }}}diff --git a/packages/asset-uploader/src/patch.test.ts b/packages/asset-uploader/src/patch.test.tsindex c37059a1c3..ee4ec51e64 100644--- a/packages/asset-uploader/src/patch.test.ts+++ b/packages/asset-uploader/src/patch.test.ts@@ -7,7 +7,10 @@ import {testContext,} from "@webstudio-is/postgrest/testing";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";-import { patchAssetsWithClient } from "./asset-patch-core";+import {+ loadAssetsByProjectWithClient,+ patchAssetsWithClient,+} from "./asset-patch-core";import { patchAssets } from "./patch";import type { Patch } from "immer";@@ -73,7 +76,9 @@ describe("patchAssets (msw)", () => {test("updates asset description via patch", async () => {const projectId = uid();- const localAssetRow = { ...assetRow, projectId };+ let localAssetRow: Omit<typeof assetRow, "description"> & {+ description: string | null;+ } = { ...assetRow, projectId };let updatedDescription: string | undefined;server.use(@@ -82,7 +87,14 @@ describe("patchAssets (msw)", () => {db.patch("Asset", async ({ request }) => {const body = (await request.json()) as { description?: string };updatedDescription = body.description ?? undefined;- return json({ id: "asset-1" });+ localAssetRow = {+ ...localAssetRow,+ description: body.description ?? localAssetRow.description,+ };+ return json({+ filename: localAssetRow.filename,+ description: localAssetRow.description,+ });}));@@ -100,7 +112,7 @@ describe("patchAssets (msw)", () => {test("updates asset filename via patch", async () => {const projectId = uid();- const localAssetRow = { ...assetRow, projectId };+ let localAssetRow = { ...assetRow, projectId };let updatedFilename: string | undefined;server.use(@@ -109,7 +121,14 @@ describe("patchAssets (msw)", () => {db.patch("Asset", async ({ request }) => {const body = (await request.json()) as { filename?: string };updatedFilename = body.filename;- return json({ id: "asset-1" });+ localAssetRow = {+ ...localAssetRow,+ filename: body.filename ?? localAssetRow.filename,+ };+ return json({+ filename: localAssetRow.filename,+ description: localAssetRow.description,+ });}));@@ -123,6 +142,77 @@ describe("patchAssets (msw)", () => {await patchAssets({ projectId }, patches, createContext());expect(updatedFilename).toBe("renamed-photo.jpg");+ await expect(+ loadAssetsByProjectWithClient(projectId, testContext.postgrest.client)+ ).resolves.toEqual([+ expect.objectContaining({+ id: "asset-1",+ filename: "renamed-photo.jpg",+ }),+ ]);+ });++ test("does not update metadata when adding an existing asset", async () => {+ const projectId = uid();+ const localAssetRow = { ...assetRow, projectId };+ let updateCount = 0;++ server.use(+ ownershipHandler,+ db.get("Asset", () => json([localAssetRow])),+ db.patch("Asset", () => {+ updateCount += 1;+ return json({+ filename: localAssetRow.filename,+ description: localAssetRow.description,+ });+ })+ );++ const [asset] = await loadAssetsByProjectWithClient(+ projectId,+ testContext.postgrest.client+ );+ await patchAssets(+ { projectId },+ [{ op: "add", path: [asset.id], value: asset }],+ createContext()+ );++ expect(updateCount).toBe(0);+ });++ test("throws when an asset metadata update matches no database row", async () => {+ const projectId = uid();+ const localAssetRow = { ...assetRow, projectId };++ server.use(+ ownershipHandler,+ db.get("Asset", () => json([localAssetRow])),+ db.patch("Asset", () =>+ json(+ {+ code: "PGRST116",+ message: "The result contains 0 rows",+ },+ { status: 406 }+ )+ )+ );++ await expect(+ patchAssets(+ { projectId },+ [+ {+ op: "replace",+ path: ["asset-1", "filename"],+ value: "renamed-photo.jpg",+ },+ ],+ createContext()+ )+ ).rejects.toThrow();});test("adds new asset when patch inserts an entry", async () => {diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.tsindex 66f3a11024..d8945652af 100644--- a/packages/cli/src/commands/mcp.test.ts+++ b/packages/cli/src/commands/mcp.test.ts@@ -10,6 +10,7 @@ const {assertSingleOpCallToolSupported,applyMcpRunOptions,createMcpPreviewHandlers,+ createMcpResourceErrorPayload,createMcpRunCheckpointStopPayload,createMcpRunErrorPayload,createMcpSingleOpCallErrorPayload,@@ -95,6 +96,18 @@ test("documents MCP stdio startup and discovery tools", () => {expect.any(Function),expect.any(Function));+ expect(yargs.command).toHaveBeenCalledWith(+ ["list-resources"],+ "List the MCP resources available for the configured project",+ expect.any(Function),+ expect.any(Function)+ );+ expect(yargs.command).toHaveBeenCalledWith(+ ["read-resource <uri>"],+ "Read one MCP resource by URI",+ expect.any(Function),+ expect.any(Function)+ );expect(yargs.example).toHaveBeenCalledWith("$0 mcp single-op-call meta.index","Debug one MCP tool without writing a stdio client script"@@ -103,6 +116,14 @@ test("documents MCP stdio startup and discovery tools", () => {"$0 mcp list-tools","Print the concise MCP tool catalog");+ expect(yargs.example).toHaveBeenCalledWith(+ "$0 mcp list-resources",+ "List available MCP resources"+ );+ expect(yargs.example).toHaveBeenCalledWith(+ "$0 mcp read-resource webstudio://project/guide",+ "Read the project MCP guide"+ );expect(yargs.example).toHaveBeenCalledWith('$0 mcp run \'[{"tool":"components.search","input":{"brief":"button"}}]\'',"Run a small multi-step MCP workflow from inline JSON"@@ -457,6 +478,22 @@ test("formats MCP single-op-call failures as structured JSON payloads", () => {});});+test("formats unknown MCP resource failures as structured JSON", () => {+ expect(+ createMcpResourceErrorPayload(+ new Error('Unknown MCP resource "webstudio://project/unknown".'),+ 12+ )+ ).toEqual({+ ok: false,+ error: {+ code: "MCP_RESOURCE_FAILED",+ message: 'Unknown MCP resource "webstudio://project/unknown".',+ },+ meta: { elapsedMs: 12 },+ });+});+test("formats missing Builder API access in MCP single-op-call failures", () => {const error = Object.assign(new Error("Project owner can't be found for token token-1"),diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex 040555442f..75e9f6ed32 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -432,6 +432,18 @@ export const mcpOptions = (yargs: CommonYargsArgv) =>mcpListToolsOptions,mcpListTools)+ .command(+ ["list-resources"],+ "List the MCP resources available for the configured project",+ mcpListResourcesOptions,+ mcpListResources+ )+ .command(+ ["read-resource <uri>"],+ "Read one MCP resource by URI",+ mcpReadResourceOptions,+ mcpReadResource+ ).command(["single-op-call <tool> [input]"],"Call one MCP tool in a fresh CLI process for debugging",@@ -453,6 +465,11 @@ export const mcpOptions = (yargs: CommonYargsArgv) =>"Debug one MCP tool without writing a stdio client script").example("$0 mcp list-tools", "Print the concise MCP tool catalog")+ .example("$0 mcp list-resources", "List available MCP resources")+ .example(+ "$0 mcp read-resource webstudio://project/guide",+ "Read the project MCP guide"+ ).example('$0 mcp run \'[{"tool":"components.search","input":{"brief":"button"}}]\'',"Run a small multi-step MCP workflow from inline JSON"@@ -486,6 +503,35 @@ type McpListToolsOptions = StrictYargsOptionsToInterface<typeof mcpListToolsOptions>;+const mcpListResourcesOptions = (yargs: CommonYargsArgv) =>+ yargs.option("json", {+ type: "boolean",+ describe: "Accepted for compatibility. MCP resource output is always JSON",+ default: false,+ });++type McpListResourcesOptions = StrictYargsOptionsToInterface<+ typeof mcpListResourcesOptions+>;++const mcpReadResourceOptions = (yargs: CommonYargsArgv) =>+ yargs+ .positional("uri", {+ type: "string",+ describe: "MCP resource URI, for example webstudio://project/guide",+ demandOption: true,+ })+ .option("json", {+ type: "boolean",+ describe:+ "Accepted for compatibility. MCP resource output is always JSON",+ default: false,+ });++type McpReadResourceOptions = StrictYargsOptionsToInterface<+ typeof mcpReadResourceOptions+> & { uri?: string };+const mcpSingleOpCallOptions = (yargs: CommonYargsArgv) =>yargs.positional("tool", {@@ -796,6 +842,14 @@ export const __testing__ = {assertPersistedMcpCheckpointAcknowledged,clearPersistedMcpCheckpoint,createMcpSingleOpCallErrorPayload,+ createMcpResourceErrorPayload: (error: unknown, elapsedMs: number) => ({+ ok: false,+ error: {+ code: getStableErrorCode(error) ?? "MCP_RESOURCE_FAILED",+ message: error instanceof Error ? error.message : String(error),+ },+ meta: { elapsedMs },+ }),createMcpRunErrorPayload,createMcpRunCheckpointStopPayload,getLoadedProjectSessionSnapshot,@@ -1148,6 +1202,38 @@ export const mcpListTools = async (_options: McpListToolsOptions) => {printJson(result.structuredContent);};+export const mcpListResources = async (_options: McpListResourcesOptions) => {+ const startedAt = Date.now();+ const { host } = await createCliMcpHost();+ const core = createProjectSessionMcpCore(host);+ printJson({+ ok: true,+ data: { resources: core.listResources() },+ meta: { elapsedMs: Date.now() - startedAt },+ });+};++export const mcpReadResource = async (options: McpReadResourceOptions) => {+ if (options.uri === undefined || options.uri.trim() === "") {+ throw new Error("mcp read-resource requires a resource URI.");+ }+ const startedAt = Date.now();+ try {+ const { host } = await createCliMcpHost();+ const core = createProjectSessionMcpCore(host);+ printJson({+ ok: true,+ data: await core.readResource({ uri: options.uri }),+ meta: { elapsedMs: Date.now() - startedAt },+ });+ } catch (error) {+ printJson(+ __testing__.createMcpResourceErrorPayload(error, Date.now() - startedAt)+ );+ throw new HandledCliError();+ }+};+export const mcp = async () => {const status = createMcpStatusReporter();status.starting();diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex 22540c969c..8c3b6b60a3 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -2,7 +2,7 @@// Edit markdown files in src/docs instead.export const cliDocs = {"api-use-cases":- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n\nNotes:\n\n- Use `webstudio schema mcp` for a tiny machine-readable MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` or focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Use `resources/list` and `resources/read` for overview resources and read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused discovery is insufficient.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Upload, replace, delete, and inspect asset usage.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview isolates generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown component ids fall back to a single-element instance when no template exists.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"includeStyles":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `includeStyles:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\nNotes:\n\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility,seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n\nNotes:\n\n- Use `webstudio schema mcp` for a tiny machine-readable MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` or focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Upload, replace, delete, and inspect asset usage.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview isolates generated app dependencies under `.webstudio/preview` by linking to the CLI package dependency tree.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If preview fails with a missing generated-app command/package such as react-router, react-router-serve, or vite, install dependencies for the CLI package and retry.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown component ids fall back to a single-element instance when no template exists.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"includeStyles":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `includeStyles:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\nNotes:\n\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility,seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',"manual-api":'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, `string[]`, and `json`.\nUse `string[]` for lists of strings such as tags or selected categories; use\n`json` for objects, arrays with mixed shapes, or nested API filter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a resource with `scopeInstanceId`/`--scope-instance` when the fetched\nresource result should be available as a read data variable. Scoped resources\nare generated into the page resource `data` map and may be loaded during page\nrendering. Use this shape for read-oriented resources such as GET CMS/API data.\nUse `dataSourceName` or `--data-source-name` to choose the variable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',"manual-llm":diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdindex 560b9c69c8..95e3966e3f 100644--- a/packages/cli/src/docs/api-use-cases.md+++ b/packages/cli/src/docs/api-use-cases.md@@ -54,11 +54,13 @@ Commands:- MCP tool: meta.index {}- MCP tool: meta.guide {"brief":"Create a pricing page"}- MCP tool: meta.get_more_tools {"brief":"update-styles"}+- webstudio mcp list-resources+- webstudio mcp read-resource webstudio://project/guideNotes:- Use `webstudio schema mcp` for a tiny machine-readable MCP tool overview. Use `webstudio schema mcp --detail summary` for all tool descriptions, and `webstudio schema mcp --detail full` or focused `meta.get_more_tools` calls only when exact input schemas are needed.-- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Use `resources/list` and `resources/read` for overview resources and read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused discovery is insufficient.+- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.- From a shell, call one MCP tool with the shortcut form `webstudio <tool> '<json>'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> '<json>'`. Use `--input-file` for large payloads.## Inspect external shadcn registry itemsdiff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.tsindex 5aae08cba9..8df32bf528 100644--- a/packages/cli/src/project-session.test.ts+++ b/packages/cli/src/project-session.test.ts@@ -253,6 +253,15 @@ describe("cli project session transport", () => {meta: {},},],+ pageTemplates: [+ {+ id: "template-1",+ name: "Landing",+ title: "Landing",+ rootInstanceId: "template-body",+ meta: {},+ },+ ],homePageId: "home",rootFolderId: "root",meta: { siteName: "Acme" },@@ -288,6 +297,9 @@ describe("cli project session transport", () => {});expect(snapshot.state.pages?.pages.get("home")?.name).toBe("Home");+ expect(snapshot.state.pages?.pageTemplates?.get("template-1")?.name).toBe(+ "Landing"+ );expect(snapshot.state.pages?.meta).toBeUndefined();expect(snapshot.state.pages?.compiler).toBeUndefined();expect(snapshot.state.pages?.redirects).toEqual([diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.tsindex df47f3ab55..bee65c8c57 100644--- a/packages/cli/src/project-session.ts+++ b/packages/cli/src/project-session.ts@@ -54,6 +54,7 @@ type PublicBuildSnapshot = Omit<homePageId?: string;rootFolderId?: string;pages?: unknown;+ pageTemplates?: unknown;folders?: unknown;meta?: unknown;compiler?: unknown;@@ -105,6 +106,7 @@ const toPages = (snapshot: PublicBuildSnapshot) => {homePageId: snapshot.homePageId,rootFolderId: snapshot.rootFolderId,pages: snapshot.pages,+ pageTemplates: snapshot.pageTemplates,folders: snapshot.folders,meta: snapshot.meta,compiler: snapshot.compiler,diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.tsindex 45e2952197..a5c165658c 100644--- a/packages/http-client/src/index.test.ts+++ b/packages/http-client/src/index.test.ts@@ -1376,7 +1376,7 @@ test("imports project bundle with assets and retries missing asset uploads", asyuploadedAssets: [createImageAssetFixture({id: `server-generated-asset-${uploadAttempts}`,- name: "image.png",+ name: "image_destination.png",}),],})@@ -1473,13 +1473,13 @@ test("imports project bundle with assets and retries missing asset uploads", asyexpect(calls).toContain("GET /trpc/build.checkProjectBuildPermission");expect(importAttempts).toBe(2);- expect(uploadAttempts).toBe(2);+ expect(uploadAttempts).toBe(1);expect(uploadUrls.every((url) => url.includes("assetId=") === false)).toBe(true);expect(uploadOffsets.size).toBe(2);expect(importAttemptMessages).toEqual(["attempt", "attempt"]);- expect(missingAssetMessages).toEqual(["image.png"]);+ expect(missingAssetMessages).toEqual([]);expect(uploadAssetMessages).toEqual(["image.png"]);});diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 95cd605df2..d0d700b1a5 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -1601,19 +1601,11 @@ export const importProjectBundleWithAssets = async (): Promise<ImportProjectBundleResult> => {await checkProjectBuildPermission(params);- const dataToImport =+ let dataToImport =params.skipAssets === true ? { ...params.data, assets: [] } : params.data;- if (params.skipAssets !== true) {- params.onUploadAssets?.(params.data.assets);- await uploadAssets({- ...params,- assets: params.data.assets,- readAssetData: params.readAssetData,- });- }-const maxRetries = params.maxMissingAssetImportRetries ?? 5;+ let uploadAttempts = 0;for (let attempt = 0; attempt <= maxRetries; attempt += 1) {params.onImportAttempt?.();try {@@ -1632,10 +1624,20 @@ export const importProjectBundleWithAssets = async (throw error;}- const missingAssets = params.data.assets.filter((asset) =>+ const missingImportAssets = dataToImport.assets.filter((asset) =>assetNames.includes(asset.name));- if (missingAssets.length !== assetNames.length) {+ if (missingImportAssets.length !== assetNames.length) {+ throw error;+ }++ const missingAssetIds = new Set(+ missingImportAssets.map((asset) => asset.id)+ );+ const missingAssets = params.data.assets.filter((asset) =>+ missingAssetIds.has(asset.id)+ );+ if (missingAssets.length !== missingImportAssets.length) {throw error;}@@ -1645,12 +1647,35 @@ export const importProjectBundleWithAssets = async (throw error;}- params.onMissingAssets?.(missingAssets);- await uploadAssets({+ if (uploadAttempts === 0) {+ params.onUploadAssets?.(missingAssets);+ } else {+ params.onMissingAssets?.(missingAssets);+ }+ const uploadedAssets = await uploadAssets({...params,assets: missingAssets,readAssetData,});+ if (uploadedAssets.length !== missingAssets.length) {+ throw new Error(+ `Expected ${missingAssets.length} uploaded assets, received ${uploadedAssets.length}.`+ );+ }+ const uploadedNamesById = new Map(+ missingAssets.map((asset, index) => [+ asset.id,+ uploadedAssets[index].name,+ ])+ );+ dataToImport = {+ ...dataToImport,+ assets: dataToImport.assets.map((asset) => {+ const name = uploadedNamesById.get(asset.id);+ return name === undefined ? asset : { ...asset, name };+ }),+ };+ uploadAttempts += 1;}}diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex 522f266622..66a4188007 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -37244,6 +37244,8 @@ export const runtimeOperationContractData = [properties: {filename: {type: "string",+ description:+ "Editable display filename. This does not change the immutable uploaded asset name; list-assets returns both name and filename.",},description: {anyOf: [diff --git a/packages/project-build/src/mcp-rendered-audit.test.ts b/packages/project-build/src/mcp-rendered-audit.test.tsindex 24655b1aa5..9fc3fe0531 100644--- a/packages/project-build/src/mcp-rendered-audit.test.ts+++ b/packages/project-build/src/mcp-rendered-audit.test.ts@@ -1,5 +1,6 @@-import { describe, expect, test } from "vitest";+import { describe, expect, test, vi } from "vitest";import {+ augmentAuditWithRenderedChecks,getRenderedAuditViewports,getRenderedImageIssues,getRenderedResourceIssues,@@ -90,4 +91,62 @@ describe("rendered audit evidence", () => {}).map(({ kind }) => kind)).toEqual(["render-blocking-resource", "legacy-font-format"]);});++ test("rejects project-wide capture plans above the bounded limit", async () => {+ const startPreview = vi.fn();+ const stopPreview = vi.fn();+ const captureScreenshot = vi.fn();+ const result = await augmentAuditWithRenderedChecks({+ envelope: {+ operationId: "project.audit",+ source: "remote",+ projectId: "project",+ buildId: "build",+ version: 1,+ committed: false,+ result: {+ scopes: ["accessibility"],+ manualCheckCount: 1,+ },+ } as never,+ input: { rendered: true, verbose: true },+ executeRead: async (command) =>+ ({+ operationId:+ command === "list-pages" ? "pages.list" : "breakpoints.list",+ source: "remote",+ projectId: "project",+ buildId: "build",+ version: 1,+ committed: false,+ result:+ command === "list-pages"+ ? {+ pages: Array.from({ length: 61 }, (_, index) => ({+ id: `page-${index}`,+ path: `/page-${index}`,+ })),+ }+ : { breakpoints: [] },+ }) as never,+ startPreview,+ stopPreview,+ captureScreenshot,+ });++ expect(result.result).toMatchObject({+ renderedCheckCount: 0,+ renderedFailureCount: 1,+ renderedFailures: [+ {+ message: expect.stringContaining(+ "122 screenshots, exceeding the 120-screenshot limit"+ ),+ },+ ],+ });+ expect(startPreview).not.toHaveBeenCalled();+ expect(stopPreview).not.toHaveBeenCalled();+ expect(captureScreenshot).not.toHaveBeenCalled();+ });});diff --git a/packages/project-build/src/mcp-rendered-audit.ts b/packages/project-build/src/mcp-rendered-audit.tsindex 083a938289..0fae03a4e7 100644--- a/packages/project-build/src/mcp-rendered-audit.ts+++ b/packages/project-build/src/mcp-rendered-audit.ts@@ -18,7 +18,7 @@ type ExecuteRead = () => Promise<ProjectSessionEnvelope>;type StartPreview = (- input: { source: "session" },+ input: { source: "session"; port: number },progress: { report: (message: string) => void }) => Promise<unknown>;@@ -26,6 +26,13 @@ type CaptureScreenshot = (input: ProjectSessionScreenshotInput) => Promise<ProjectSessionScreenshotResult>;+type StopPreview = () => Promise<unknown>;++export const maxRenderedAuditCaptures = 120;+const renderedAuditScreenshotTimeout = 10_000;+const renderedAuditPreviewPort = 5177;+const renderedAuditCaptureConcurrency = 3;+export const getRenderedAuditViewports = (breakpoints: unknown): Viewport[] => {const widths = new Set([375, 1440]);if (isRecord(breakpoints) && Array.isArray(breakpoints.breakpoints)) {@@ -177,6 +184,7 @@ export const augmentAuditWithRenderedChecks = async ({input,executeRead,startPreview,+ stopPreview,captureScreenshot,reportProgress,}: {@@ -184,6 +192,7 @@ export const augmentAuditWithRenderedChecks = async ({input: unknown;executeRead: ExecuteRead;startPreview?: StartPreview;+ stopPreview?: StopPreview;captureScreenshot?: CaptureScreenshot;reportProgress?: (message: string) => void;}): Promise<ProjectSessionEnvelope> => {@@ -191,6 +200,7 @@ export const augmentAuditWithRenderedChecks = async ({isRecord(input) === false ||input.rendered !== true ||startPreview === undefined ||+ stopPreview === undefined ||captureScreenshot === undefined ||isRecord(envelope.result) === false) {@@ -217,13 +227,9 @@ export const augmentAuditWithRenderedChecks = async ({try {pagesEnvelope = await executeRead("list-pages", {});breakpointsEnvelope = await executeRead("list-breakpoints", {});- await startPreview(- { source: "session" },- { report: (message) => reportProgress?.(message) }- );} catch (error) {failures.push({- message: `Rendered audit could not start: ${error instanceof Error ? error.message : String(error)}`,+ message: `Rendered audit could not prepare: ${error instanceof Error ? error.message : String(error)}`,});return finish(false);}@@ -237,8 +243,40 @@ export const augmentAuditWithRenderedChecks = async ({return finish(false);}- for (const page of pages) {- for (const viewport of viewports) {+ const captureCount = pages.length * viewports.length;+ if (captureCount > maxRenderedAuditCaptures) {+ failures.push({+ message:+ `Rendered audit requires ${captureCount} screenshots, exceeding the ` ++ `${maxRenderedAuditCaptures}-screenshot limit. Run it for one page with pagePath or pageId.`,+ });+ return finish(false);+ }++ try {+ await startPreview(+ { source: "session", port: renderedAuditPreviewPort },+ { report: (message) => reportProgress?.(message) }+ );+ } catch (error) {+ failures.push({+ message: `Rendered audit could not start: ${error instanceof Error ? error.message : String(error)}`,+ });+ return finish(false);+ }++ try {+ const captures = pages.flatMap((page) =>+ viewports.map((viewport) => ({ page, viewport }))+ );+ let nextCapture = 0;+ const captureNext = async (): Promise<void> => {+ const capture = captures[nextCapture];+ nextCapture += 1;+ if (capture === undefined) {+ return;+ }+ const { page, viewport } = capture;const pagePath = page.path || "/";reportProgress?.(`tool audit capturing ${pagePath} at ${viewport.width}px`@@ -252,6 +290,7 @@ export const augmentAuditWithRenderedChecks = async ({includeImageMetrics: performanceEnabled,includeResourceMetrics: performanceEnabled,browser: "auto",+ timeout: renderedAuditScreenshotTimeout,});if (screenshot.layout === undefined) {failures.push({@@ -260,7 +299,7 @@ export const augmentAuditWithRenderedChecks = async ({viewport,message: "Screenshot did not return rendered layout metrics.",});- continue;+ return await captureNext();}const layout: Layout = {...screenshot.layout,@@ -297,6 +336,21 @@ export const augmentAuditWithRenderedChecks = async ({message: error instanceof Error ? error.message : String(error),});}+ await captureNext();+ };+ await Promise.all(+ Array.from(+ { length: Math.min(renderedAuditCaptureConcurrency, captures.length) },+ captureNext+ )+ );+ } finally {+ try {+ await stopPreview();+ } catch (error) {+ failures.push({+ message: `Rendered audit could not stop its preview: ${error instanceof Error ? error.message : String(error)}`,+ });}}return finish(diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex aed7685c46..9fcaaa3f1a 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -1156,6 +1156,10 @@ describe("project session mcp adapter", () => {url: "http://127.0.0.1:5173",running: true,}));+ const stopPreview = vi.fn(async () => ({+ url: "http://127.0.0.1:5173",+ running: false,+ }));const captureScreenshot = vi.fn(async (input) => ({output: `/tmp/${input.viewport.width}.png`,browserPath: "/browser",@@ -1238,6 +1242,7 @@ describe("project session mcp adapter", () => {executeOperation,startPreview,getPreviewStatus: vi.fn(),+ stopPreview,captureScreenshot,});@@ -1253,10 +1258,12 @@ describe("project session mcp adapter", () => {});expect(startPreview).toHaveBeenCalledTimes(1);+ expect(stopPreview).toHaveBeenCalledTimes(1);expect(captureScreenshot).toHaveBeenCalledTimes(4);expect(captureScreenshot).toHaveBeenCalledWith(expect.objectContaining({path: "/",+ timeout: 10_000,viewport: { width: 375, height: 812 },}));@@ -1324,6 +1331,7 @@ describe("project session mcp adapter", () => {});expect(captureScreenshot).toHaveBeenCalledTimes(4);+ expect(stopPreview).toHaveBeenCalledTimes(2);expect(captureScreenshot).toHaveBeenCalledWith(expect.objectContaining({includeImageMetrics: false,@@ -1403,6 +1411,7 @@ describe("project session mcp adapter", () => {throw new Error("preview build failed");}),getPreviewStatus: vi.fn(),+ stopPreview: vi.fn(),captureScreenshot: vi.fn(),});@@ -5217,6 +5226,9 @@ describe("project session mcp adapter", () => {]),}));+ await expect(+ adapter.readResource({ uri: "webstudio://project/unknown" })+ ).rejects.toThrow('Unknown MCP resource "webstudio://project/unknown".');});test("connects through the official MCP SDK and exposes discovery", async () => {diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex 97e37c44ba..a875f96390 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -5124,7 +5124,9 @@ export const createProjectSessionMcpCore = <Command extends string = string>({const isRenderedAudit = isAuditInput && input.rendered === true;if (isRenderedAudit &&- (startPreview === undefined || captureScreenshot === undefined)+ (startPreview === undefined ||+ stopPreview === undefined ||+ captureScreenshot === undefined)) {throw new Error("Rendered audit is unavailable because this MCP host does not provide preview and screenshot capabilities."@@ -5158,6 +5160,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({: operationInput,executeRead,startPreview,+ stopPreview,captureScreenshot,reportProgress: reportToolProgress,})diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.tsindex 7959026483..9444af9e4d 100644--- a/packages/project-build/src/runtime/assets.test.ts+++ b/packages/project-build/src/runtime/assets.test.ts@@ -273,6 +273,24 @@ describe("asset runtime operations", () => {});});+ test("lists editable filenames separately from immutable asset names", () => {+ const asset = imageAsset("renamed");+ asset.name = "uploaded_hash.png";+ asset.filename = "campaign-hero.png";++ expect(+ listAssets({ ...state, assets: new Map([[asset.id, asset]]) })+ ).toMatchObject({+ items: [+ {+ id: "renamed",+ name: "uploaded_hash.png",+ filename: "campaign-hero.png",+ },+ ],+ });+ });+test("paginates assets and rejects invalid cursors", () => {expect(listAssets(state, { cursor: "1", limit: 1 })).toMatchObject({items: [{ id: "next" }],diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.tsindex 0d9e9041e5..53edbd8f75 100644--- a/packages/project-build/src/runtime/assets.ts+++ b/packages/project-build/src/runtime/assets.ts@@ -57,7 +57,12 @@ export const assetUpdateInput = z.object({assetId: z.string(),values: z.object({- filename: z.string().optional(),+ filename: z+ .string()+ .describe(+ "Editable display filename. This does not change the immutable uploaded asset name; list-assets returns both name and filename."+ )+ .optional(),description: z.union([z.string(), z.null()]).optional(),}).refine((values) => Object.keys(values).length > 0, {@@ -722,6 +727,7 @@ const getAssetUsageCounts = (build: AssetReferenceBuild, assets: Asset[]) => {const serializeAssetSummary = (asset: Asset) => ({id: asset.id,name: asset.name,+ filename: asset.filename,description: asset.description,type: asset.type,size: asset.size,diff --git a/packages/project-build/src/runtime/page-copy.ts b/packages/project-build/src/runtime/page-copy.tsindex a89c49cb81..ecefe522af 100644--- a/packages/project-build/src/runtime/page-copy.ts+++ b/packages/project-build/src/runtime/page-copy.ts@@ -960,7 +960,7 @@ export const reorderPageTemplatesMutable = (sourceId: string,targetId: string,position: "before" | "after",- data: WebstudioData+ data: Pick<WebstudioData, "pages">) => {const templates = data.pages.pageTemplates;if (templates === undefined || sourceId === targetId) {@@ -993,8 +993,8 @@ export const reorderPageTemplates = (state: BuilderState,input: z.infer<typeof pageTemplateReorderInput>) => {- const data = getRequiredWebstudioData(state);- const templates = data.pages.pageTemplates;+ const pages = getRequiredPages(state);+ const templates = pages.pageTemplates;if (templates?.has(input.sourceTemplateId) !== true) {return throwBuilderRuntimeError("NOT_FOUND",@@ -1008,16 +1008,12 @@ export const reorderPageTemplates = ();}- const before = createWebstudioDataFromBuild({- build: data,- assets: Array.from(data.assets.values()),- });- const after = structuredClone(before);+ const after = structuredClone(pages);reorderPageTemplatesMutable(input.sourceTemplateId,input.targetTemplateId,input.position,- after+ { pages: after });return createRuntimeMutation({payload:@@ -1030,7 +1026,7 @@ export const reorderPageTemplates = ({op: "replace",path: ["pageTemplates"],- value: after.pages.pageTemplates ?? new Map(),+ value: after.pageTemplates ?? new Map(),},],},diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.tsindex 6407729425..17db23b0d1 100644--- a/packages/project-build/src/runtime/registry.ts+++ b/packages/project-build/src/runtime/registry.ts@@ -77,6 +77,35 @@ type RuntimeOperationContractInput =requiresConfirm?: boolean;};+const parseOperationInput = <Schema extends z.ZodTypeAny>(+ schema: Schema,+ input: unknown+): z.infer<Schema> => {+ const result = schema.safeParse(input ?? {});+ if (result.success) {+ return result.data;+ }+ const hasUnknownTransportField = result.error.issues.some(+ (issue) =>+ issue.code === "unrecognized_keys" &&+ issue.keys.some((key) => key === "projectId" || key === "confirm")+ );+ if (+ hasUnknownTransportField &&+ typeof input === "object" &&+ input !== null &&+ Array.isArray(input) === false+ ) {+ const {+ projectId: _projectId,+ confirm: _confirm,+ ...operationInput+ } = input as Record<string, unknown>;+ return schema.parse(operationInput);+ }+ throw result.error;+};+const runtimeOperation = <Id extends string,Schema extends z.ZodTypeAny,@@ -129,7 +158,7 @@ const runtimeOperation = <execute: ({ state, input, context }) => {const result = execute({state,- input: inputSchema.parse(input ?? {}),+ input: parseOperationInput(inputSchema, input),context,});if (outputSchema === undefined) {diff --git a/packages/project-build/src/state/immer.ts b/packages/project-build/src/state/immer.tsindex 74e6bbf254..c672c22ec1 100644--- a/packages/project-build/src/state/immer.ts+++ b/packages/project-build/src/state/immer.ts@@ -1,5 +1,9 @@import { enableMapSet, enablePatches } from "immer";// Project data uses Map-backed namespaces and emits Immer patches.-enableMapSet();-enablePatches();+export const enableImmerPatchPlugins = () => {+ enableMapSet();+ enablePatches();+};++enableImmerPatchPlugins();diff --git a/packages/project-build/src/state/patch.ts b/packages/project-build/src/state/patch.tsindex 79af9eaf4f..8217a4b6ec 100644--- a/packages/project-build/src/state/patch.ts+++ b/packages/project-build/src/state/patch.ts@@ -1,5 +1,5 @@import { applyPatches, type Patch } from "immer";-import "./immer";+import { enableImmerPatchPlugins } from "./immer";import type {BuilderPatch,BuilderPatchChange,@@ -9,6 +9,10 @@ import { compactBuilderPatchPayload } from "../contracts/patch";import type { BuilderState } from "./builder-state";import type { BuilderNamespace } from "../contracts/namespaces";+// Keep initialization attached to the patch implementation. A bare side-effect+// import can be removed because project-build declares sideEffects: false.+enableImmerPatchPlugins();+export class MissingBuilderStateNamespaceError extends Error {constructor(namespace: BuilderNamespace) {super(`Builder state namespace "${namespace}" is missing.`);