Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: Improve MCP safety, context efficiency, and agent workflows (#5895)

Oleg Isonen98d5c607ee37
diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.ts
index 97cfed4bc2..daf34cec62 100644
--- a/apps/builder/app/services/api-router.server.ts
+++ b/apps/builder/app/services/api-router.server.ts
@@ -226,6 +226,19 @@ const runtimeBuildQuery = <Result = unknown>(id: RuntimeOperationId) =>
})
);
+const withConfirm = <Schema extends z.ZodTypeAny>(input: Schema) =>
+ z.intersection(input, z.object({ confirm: z.literal(true) })) as z.ZodType<
+ z.infer<Schema> & { confirm: true }
+ >;
+
+const runtimeMutationInput = (
+ id: RuntimeOperationId,
+ requiresConfirm: boolean
+) => {
+ const input = runtimeProjectInput(id);
+ return requiresConfirm ? withConfirm(input) : input;
+};
+
const buildMutation = <Schema extends z.ZodType<{ projectId: string }>, Result>(
input: Schema,
handler: (args: {
@@ -261,15 +274,18 @@ const buildMutation = <Schema extends z.ZodType<{ projectId: string }>, Result>(
});
const runtimeBuildMutation = <Result extends Record<string, unknown> = {}>(
- id: RuntimeOperationId
+ id: RuntimeOperationId,
+ requiresConfirm: boolean
) =>
- buildMutation(runtimeProjectInput(id), async ({ input, build, commit }) =>
- commitRuntimeMutation<Result>({
- id,
- build,
- input,
- commit,
- })
+ buildMutation(
+ runtimeMutationInput(id, requiresConfirm),
+ async ({ input, build, commit }) =>
+ commitRuntimeMutation<Result>({
+ id,
+ build,
+ input,
+ commit,
+ })
);
type BuildCommit = <CommitResult extends Record<string, unknown> = {}>(
@@ -387,10 +403,11 @@ const contentOrBuildMutation = <
const runtimeContentOrBuildMutation = <
Result extends Record<string, unknown> = {},
>(
- id: RuntimeOperationId
+ id: RuntimeOperationId,
+ requiresConfirm: boolean
) =>
contentOrBuildMutation(
- runtimeProjectInput(id),
+ runtimeMutationInput(id, requiresConfirm),
async ({ input, build, commit }) =>
commitRuntimeMutation<Result>({
id,
@@ -400,11 +417,6 @@ const runtimeContentOrBuildMutation = <
})
);
-const withConfirm = <Schema extends z.ZodTypeAny>(input: Schema) =>
- z.intersection(input, z.object({ confirm: z.literal(true) })) as z.ZodType<
- z.infer<Schema> & { confirm: true }
- >;
-
const runtimeAssetsQuery = <Result = unknown>(id: RuntimeOperationId) =>
projectQuery(runtimeProjectInput(id), "view", async ({ ctx, input }) => {
const assets = await loadAssetsByProject(input.projectId, ctx, {
@@ -423,7 +435,7 @@ const runtimeAssetsMutation = <Result extends Record<string, unknown> = {}>(
id: RuntimeOperationId
) =>
buildMutation(
- withConfirm(runtimeProjectInput(id)),
+ runtimeMutationInput(id, true),
async ({ ctx, input, build, commit }) => {
const assets = await loadAssetsByProject(input.projectId, ctx, {
skipPermissionsCheck: true,
@@ -472,25 +484,13 @@ const createRuntimeOperationProcedure = (operation: RuntimeOperation) => {
? runtimeAssetsQuery(id)
: runtimeAssetsMutation(id);
}
- if (operation.requiresConfirm) {
- return buildMutation(
- withConfirm(runtimeProjectInput(id)),
- async ({ input, build, commit }) =>
- commitRuntimeMutation({
- id,
- build,
- input,
- commit,
- })
- );
- }
if (operation.kind === "read") {
return runtimeBuildQuery(id);
}
if (operation.permit === "edit") {
- return runtimeContentOrBuildMutation(id);
+ return runtimeContentOrBuildMutation(id, operation.requiresConfirm);
}
- return runtimeBuildMutation(id);
+ return runtimeBuildMutation(id, operation.requiresConfirm);
};
const createRuntimeOperationRouters = () => {
diff --git a/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts b/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts
index 70b32683c0..1dcda13a9c 100644
--- a/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts
+++ b/packages/cli/evaluations/high-impact/mcp-trace-proxy.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
import { getMcpTraceRequest, getMcpTraceResponse } from "./mcp-trace-proxy";
describe("bounded MCP tracing", () => {
- test("retains only the tool name and screenshot viewport", () => {
+ test("retains only bounded verification fields", () => {
expect(
getMcpTraceRequest({
jsonrpc: "2.0",
@@ -26,6 +26,34 @@ describe("bounded MCP tracing", () => {
});
});
+ test("records confirmation flow without retaining its token", () => {
+ expect(
+ getMcpTraceRequest({
+ id: 8,
+ method: "tools/call",
+ params: {
+ name: "delete-instance",
+ arguments: {
+ instanceId: "private-instance-id",
+ dryRun: true,
+ confirmDestructive: true,
+ confirmationToken: "private-token",
+ },
+ },
+ })
+ ).toEqual({
+ id: 8,
+ call: {
+ name: "delete-instance",
+ arguments: {
+ dryRun: true,
+ confirmDestructive: true,
+ hasConfirmationToken: true,
+ },
+ },
+ });
+ });
+
test("records success or failure after the matching response", () => {
const pending = new Map([
[1, { name: "meta.guide" }],
diff --git a/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts b/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts
index ea8e62b205..3fc88e58bd 100644
--- a/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts
+++ b/packages/cli/evaluations/high-impact/mcp-trace-proxy.ts
@@ -7,7 +7,12 @@ type JsonRpcId = string | number;
export type BoundedMcpCall = {
name: string;
- arguments?: { viewport: { width: number; height: number } };
+ arguments?: {
+ viewport?: { width: number; height: number };
+ dryRun?: true;
+ confirmDestructive?: true;
+ hasConfirmationToken?: true;
+ };
isError?: true;
};
@@ -25,16 +30,28 @@ export const getMcpTraceRequest = (value: unknown) => {
return;
}
const call: BoundedMcpCall = { name: params.name };
- if (params.name === "screenshot" && isPlainRecord(params.arguments)) {
+ if (isPlainRecord(params.arguments)) {
+ const args: NonNullable<BoundedMcpCall["arguments"]> = {};
const viewport = params.arguments.viewport;
if (
+ params.name === "screenshot" &&
isPlainRecord(viewport) &&
typeof viewport.width === "number" &&
typeof viewport.height === "number"
) {
- call.arguments = {
- viewport: { width: viewport.width, height: viewport.height },
- };
+ args.viewport = { width: viewport.width, height: viewport.height };
+ }
+ if (params.arguments.dryRun === true) {
+ args.dryRun = true;
+ }
+ if (params.arguments.confirmDestructive === true) {
+ args.confirmDestructive = true;
+ }
+ if (typeof params.arguments.confirmationToken === "string") {
+ args.hasConfirmationToken = true;
+ }
+ if (Object.keys(args).length > 0) {
+ call.arguments = args;
}
}
return { id, call };
diff --git a/packages/cli/src/api-connection.test.ts b/packages/cli/src/api-connection.test.ts
index 0b448e09bb..cd0fd41488 100644
--- a/packages/cli/src/api-connection.test.ts
+++ b/packages/cli/src/api-connection.test.ts
@@ -64,6 +64,26 @@ describe("resolveApiConnection", () => {
);
});
+ test("resolves an explicitly selected saved project without local config", async () => {
+ const dependencies = createDependencies({
+ exists: false,
+ files: {
+ [GLOBAL_CONFIG_FILE]: JSON.stringify({
+ "project-2": { origin: "https://two.example.com", token: "token-2" },
+ }),
+ },
+ });
+
+ await expect(
+ resolveApiConnection(dependencies, "/workspace/agency", "project-2")
+ ).resolves.toEqual({
+ projectId: "project-2",
+ origin: "https://two.example.com",
+ authToken: "token-2",
+ });
+ expect(dependencies.isFileExists).not.toHaveBeenCalled();
+ });
+
test("requires a local project config", async () => {
await expect(
resolveApiConnection(createDependencies({ exists: false }))
diff --git a/packages/cli/src/api-connection.ts b/packages/cli/src/api-connection.ts
index ceb8f71fe5..316c123dc4 100644
--- a/packages/cli/src/api-connection.ts
+++ b/packages/cli/src/api-connection.ts
@@ -28,31 +28,40 @@ export const defaultApiConnectionDependencies: ApiConnectionDependencies = {
export const resolveApiConnection = async (
dependencies = defaultApiConnectionDependencies,
- projectRoot = cwd()
+ projectRoot = cwd(),
+ projectId?: string
): Promise<ApiConnection> => {
- const localConfigFile = join(projectRoot, LOCAL_CONFIG_FILE);
- if ((await dependencies.isFileExists(localConfigFile)) === false) {
- throw new Error(
- "Local config file is not found. Run webstudio init --link <api-share-link> from a Webstudio project."
- );
+ const isExplicitProject = projectId !== undefined;
+ if (projectId === undefined) {
+ const localConfigFile = join(projectRoot, LOCAL_CONFIG_FILE);
+ if ((await dependencies.isFileExists(localConfigFile)) === false) {
+ throw new Error(
+ "Local config file is not found. Run webstudio init --link <api-share-link> from a Webstudio project."
+ );
+ }
+ projectId = jsonToLocalConfig(
+ JSON.parse(await dependencies.readFile(localConfigFile, "utf-8"))
+ ).projectId;
}
- const localConfig = jsonToLocalConfig(
- JSON.parse(await dependencies.readFile(localConfigFile, "utf-8"))
- );
+ if (projectId.trim() === "") {
+ throw new Error("Project id must not be empty.");
+ }
const globalConfig = jsonToGlobalConfig(
JSON.parse(await dependencies.readFile(GLOBAL_CONFIG_FILE, "utf-8"))
);
- const projectConfig = globalConfig[localConfig.projectId];
+ const projectConfig = globalConfig[projectId];
if (projectConfig === undefined) {
throw new Error(
- "Project config is not found. Run webstudio init --link <api-share-link>."
+ isExplicitProject
+ ? `Project config for "${projectId}" is not found. Run webstudio init --link <api-share-link> once to save its credentials.`
+ : "Project config is not found. Run webstudio init --link <api-share-link>."
);
}
return {
origin: projectConfig.origin,
authToken: projectConfig.token,
- projectId: localConfig.projectId,
+ projectId,
};
};
diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.ts
index abeec388ec..eb5f1485b7 100644
--- a/packages/cli/src/commands/api-command.test.ts
+++ b/packages/cli/src/commands/api-command.test.ts
@@ -1125,6 +1125,10 @@ test("duplicates page", async () => {
name: "Pricing Copy",
path: "/pricing-copy",
parentFolder: "folder-1",
+ substitutions: JSON.stringify({
+ text: { London: "Paris" },
+ variables: { city: { type: "string", value: "Paris" } },
+ }),
},
call: apiCalls.duplicatePage,
connection: {
@@ -1132,6 +1136,10 @@ test("duplicates page", async () => {
name: "Pricing Copy",
path: "/pricing-copy",
parentFolderId: "folder-1",
+ substitutions: {
+ text: { London: "Paris" },
+ variables: { city: { type: "string", value: "Paris" } },
+ },
},
});
});
diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.ts
index ca20a06478..5553bef622 100644
--- a/packages/cli/src/commands/api-command.ts
+++ b/packages/cli/src/commands/api-command.ts
@@ -409,6 +409,11 @@ export const duplicatePageCommandOptions = (yargs: CommonYargsArgv) =>
.option("parent-folder", {
type: "string",
describe: "Folder id where the duplicated page should be inserted",
+ })
+ .option("substitutions", {
+ type: "string",
+ describe:
+ "JSON object with exact text replacements and copied variable value overrides",
});
export const listPageTemplatesCommandOptions = (yargs: CommonYargsArgv) =>
@@ -1325,6 +1330,7 @@ export type ApiCommandOptions = {
authPassword?: string;
message?: string;
parentFolder?: string;
+ substitutions?: string;
sourceTemplate?: string;
targetTemplate?: string;
root?: string;
@@ -2213,11 +2219,16 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
);
},
"duplicate-page": async (options, connection, dependencies) => {
+ const substitutions =
+ options.substitutions === undefined
+ ? undefined
+ : (JSON.parse(options.substitutions) as unknown);
const input = {
pageId: requireOption(options.page, "--page"),
parentFolderId: options.parentFolder,
name: options.name,
path: options.path,
+ substitutions,
};
return runProjectSessionCommand(
"duplicate-page",
diff --git a/packages/cli/src/commands/mcp-preview.test.ts b/packages/cli/src/commands/mcp-preview.test.ts
new file mode 100644
index 0000000000..8806888ce8
--- /dev/null
+++ b/packages/cli/src/commands/mcp-preview.test.ts
@@ -0,0 +1,469 @@
+import { expect, test, vi } from "vitest";
+import { createMcpPreviewHandlers } from "./mcp-preview";
+
+const createCaptureScreenshotMock = (events: string[]) =>
+ vi.fn(async (options) => {
+ events.push(`capture:${options.url}`);
+ return {
+ output: "screenshot.png",
+ browser: {
+ browser: "chromium" as const,
+ path: "/browser",
+ source: "path" as const,
+ },
+ viewport: { width: options.width, height: options.height },
+ fullPage: options.fullPage === true,
+ elapsedMs: 1,
+ warnings: [],
+ layout: {
+ viewportWidth: options.width,
+ viewportHeight: options.height,
+ contentWidth: options.width + 20,
+ contentHeight: options.height * 2,
+ horizontalOverflow: true,
+ images: [],
+ resources: [],
+ },
+ };
+ });
+
+test("captures stale path screenshots through the restarted preview server", async () => {
+ const events: string[] = [];
+ const prepareSessionDataFile = vi.fn(async () => {
+ events.push("session");
+ });
+ const preview = {
+ status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
+ startAndWait: vi.fn(async (options) => {
+ events.push(`start:${options.cwd}:${options.restart}`);
+ return { url: "http://127.0.0.1:3000/", running: true };
+ }),
+ resolveUrl: vi.fn((path: string) => {
+ events.push(`resolve:${path}`);
+ return `http://127.0.0.1:3000${path}`;
+ }),
+ };
+ const captureScreenshot = createCaptureScreenshotMock(events);
+ const progress: string[] = [];
+
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => true,
+ preparePreview: async () => {
+ events.push("prepare");
+ return { cwd: "/tmp/generated-preview" };
+ },
+ prepareSessionDataFile,
+ captureScreenshot,
+ });
+
+ await expect(
+ handlers.captureScreenshot(
+ {
+ path: "/pricing",
+ source: "session",
+ viewport: { width: 1440, height: 900 },
+ },
+ {
+ report: (message) => {
+ progress.push(message);
+ },
+ }
+ )
+ ).resolves.toMatchObject({
+ output: "screenshot.png",
+ layout: {
+ viewportWidth: 1440,
+ contentWidth: 1460,
+ horizontalOverflow: true,
+ images: [],
+ resources: [],
+ },
+ });
+
+ expect(captureScreenshot).toHaveBeenCalledWith(
+ expect.objectContaining({
+ browser: "auto",
+ url: "http://127.0.0.1:3000/pricing",
+ })
+ );
+ expect(events).toEqual([
+ "prepare",
+ "start:/tmp/generated-preview:true",
+ "resolve:/pricing",
+ "capture:http://127.0.0.1:3000/pricing",
+ ]);
+ expect(prepareSessionDataFile).not.toHaveBeenCalled();
+ expect(progress).toEqual([
+ "tool screenshot preparing generated preview project",
+ "tool screenshot starting production preview server",
+ "tool screenshot capturing http://127.0.0.1:3000/pricing",
+ ]);
+});
+
+test("passes explicit preview source to preview preparation", async () => {
+ const events: string[] = [];
+ const preview = {
+ status: vi.fn(() => ({ url: "", running: false })),
+ startAndWait: vi.fn(async (options) => {
+ events.push(`start:${options.cwd}:${options.restart}`);
+ return { url: "http://127.0.0.1:3000/", running: true };
+ }),
+ resolveUrl: vi.fn(),
+ };
+ const prepareSessionDataFile = vi.fn(async () => undefined);
+ const preparePreview = vi.fn(async (source, prepareSessionDataFile) => {
+ events.push(`prepare:${source}`);
+ await prepareSessionDataFile?.();
+ return { cwd: "/tmp/generated-preview" };
+ });
+ const progress: string[] = [];
+
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ preparePreview,
+ prepareSessionDataFile,
+ });
+
+ await handlers.startPreview(
+ { source: "session" },
+ {
+ report: (message) => {
+ progress.push(message);
+ },
+ }
+ );
+
+ expect(preparePreview).toHaveBeenCalledWith(
+ "session",
+ prepareSessionDataFile
+ );
+ expect(prepareSessionDataFile).toHaveBeenCalledOnce();
+ expect(events).toEqual([
+ "prepare:session",
+ "start:/tmp/generated-preview:true",
+ ]);
+ expect(progress).toEqual([
+ "tool preview.start preparing generated preview project",
+ "tool preview.start starting production preview server",
+ ]);
+});
+
+test("rejects invalid external image domains before preparing preview", async () => {
+ const preview = {
+ status: vi.fn(() => ({ url: "", running: false })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn(),
+ };
+ const preparePreview = vi.fn();
+ const handlers = createMcpPreviewHandlers({ preview, preparePreview });
+
+ await expect(
+ handlers.startPreview({
+ imageDomains: ["https://images.example.com/path"],
+ })
+ ).rejects.toThrow(
+ "Image domains must be hostnames without a protocol or path"
+ );
+ await expect(
+ handlers.captureScreenshot({
+ path: "/",
+ imageDomains: ["https://images.example.com/path"],
+ viewport: { width: 1440, height: 900 },
+ })
+ ).rejects.toThrow(
+ "Image domains must be hostnames without a protocol or path"
+ );
+
+ expect(preparePreview).not.toHaveBeenCalled();
+ expect(preview.startAndWait).not.toHaveBeenCalled();
+});
+
+test("captures fresh path screenshots through the running preview server", async () => {
+ const events: string[] = [];
+ const preview = {
+ status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn((path: string) => {
+ events.push(`resolve:${path}`);
+ return `http://127.0.0.1:3000${path}`;
+ }),
+ };
+ const captureScreenshot = createCaptureScreenshotMock(events);
+ const progress: string[] = [];
+
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => false,
+ preparePreview: async () => {
+ events.push("prepare");
+ return { cwd: "/tmp/generated-preview" };
+ },
+ captureScreenshot,
+ });
+
+ await handlers.captureScreenshot(
+ {
+ path: "/about",
+ viewport: { width: 1440, height: 900 },
+ fullPage: true,
+ },
+ {
+ report: (message) => {
+ progress.push(message);
+ },
+ }
+ );
+
+ expect(preview.startAndWait).not.toHaveBeenCalled();
+ expect(events).toEqual([
+ "resolve:/about",
+ "capture:http://127.0.0.1:3000/about",
+ ]);
+ expect(captureScreenshot).toHaveBeenCalledWith(
+ expect.objectContaining({
+ fullPage: true,
+ })
+ );
+ expect(progress).toEqual([
+ "tool screenshot capturing http://127.0.0.1:3000/about",
+ ]);
+});
+
+test("reuses and closes one browser capture session for session screenshots", async () => {
+ const preview = {
+ status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
+ stop: vi.fn(async () => ({ url: "", running: false })),
+ };
+ const capture = createCaptureScreenshotMock([]);
+ const close = vi.fn(async () => undefined);
+ const capturePage = vi.fn(async () => []);
+ const createCaptureSession = vi.fn(() => ({ capture, capturePage, close }));
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => false,
+ createCaptureSession,
+ });
+
+ await handlers.captureScreenshot({
+ path: "/one",
+ source: "session",
+ viewport: { width: 1440, height: 900 },
+ });
+ await handlers.captureScreenshot({
+ path: "/two",
+ source: "session",
+ viewport: { width: 390, height: 844 },
+ });
+
+ expect(createCaptureSession).toHaveBeenCalledOnce();
+ expect(capture).toHaveBeenCalledTimes(2);
+ expect(close).not.toHaveBeenCalled();
+
+ await handlers.stopPreview();
+
+ expect(close).toHaveBeenCalledOnce();
+ expect(preview.stop).toHaveBeenCalledOnce();
+});
+
+test("stops the owned preview when browser capture cleanup fails", async () => {
+ const preview = {
+ status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
+ stop: vi.fn(async () => ({ url: "", running: false })),
+ };
+ const cleanupError = new Error("browser cleanup failed");
+ const createCaptureSession = vi.fn(() => ({
+ capture: createCaptureScreenshotMock([]),
+ capturePage: vi.fn(async () => []),
+ close: vi.fn(async () => {
+ throw cleanupError;
+ }),
+ }));
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => false,
+ createCaptureSession,
+ });
+
+ await handlers.captureScreenshot({
+ path: "/one",
+ source: "session",
+ viewport: { width: 1440, height: 900 },
+ });
+
+ await expect(handlers.stopPreview()).rejects.toBe(cleanupError);
+ expect(preview.stop).toHaveBeenCalledOnce();
+});
+
+test("captures one session page across multiple viewports through resize", async () => {
+ const preview = {
+ status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
+ };
+ const capture = createCaptureScreenshotMock([]);
+ const capturePage = vi.fn(
+ async (optionsList) => await Promise.all(optionsList.map(capture))
+ );
+ const close = vi.fn(async () => undefined);
+ const createCaptureSession = vi.fn(() => ({
+ capture,
+ capturePage,
+ close,
+ }));
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => false,
+ createCaptureSession,
+ });
+
+ const results = await handlers.capturePageScreenshots([
+ {
+ path: "/responsive",
+ source: "session",
+ viewport: { width: 375, height: 812 },
+ waitForTimeout: 0,
+ },
+ {
+ path: "/responsive",
+ source: "session",
+ viewport: { width: 1440, height: 900 },
+ waitForTimeout: 0,
+ },
+ ]);
+
+ expect(results.map((result) => result.viewport.width)).toEqual([375, 1440]);
+ expect(createCaptureSession).toHaveBeenCalledOnce();
+ expect(capturePage).toHaveBeenCalledWith([
+ expect.objectContaining({
+ url: "http://127.0.0.1:3000/responsive",
+ width: 375,
+ waitForTimeout: 0,
+ }),
+ expect.objectContaining({
+ url: "http://127.0.0.1:3000/responsive",
+ width: 1440,
+ waitForTimeout: 0,
+ }),
+ ]);
+ expect(preview.startAndWait).not.toHaveBeenCalled();
+});
+
+test("captures path screenshots through an existing base URL without preview", async () => {
+ const events: string[] = [];
+ const preview = {
+ status: vi.fn(),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn(),
+ };
+ const captureScreenshot = createCaptureScreenshotMock(events);
+ const preparePreview = vi.fn(async () => {
+ events.push("prepare");
+ return { cwd: "/tmp/generated-preview" };
+ });
+ const progress: string[] = [];
+
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ preparePreview,
+ captureScreenshot,
+ });
+
+ await handlers.captureScreenshot(
+ {
+ baseUrl: "http://127.0.0.1:5177",
+ path: "/design-system",
+ viewport: { width: 1440, height: 900 },
+ },
+ {
+ report: (message) => {
+ progress.push(message);
+ },
+ }
+ );
+
+ expect(preview.status).not.toHaveBeenCalled();
+ expect(preview.startAndWait).not.toHaveBeenCalled();
+ expect(preview.resolveUrl).not.toHaveBeenCalled();
+ expect(preparePreview).not.toHaveBeenCalled();
+ expect(events).toEqual(["capture:http://127.0.0.1:5177/design-system"]);
+ expect(progress).toEqual([
+ "tool screenshot capturing http://127.0.0.1:5177/design-system",
+ ]);
+});
+
+test("rejects authenticated Builder URLs as generated preview targets", async () => {
+ const preview = {
+ status: vi.fn(),
+ startAndWait: vi.fn(),
+ resolveUrl: vi.fn(),
+ };
+ const captureScreenshot = vi.fn();
+ const handlers = createMcpPreviewHandlers({ preview, captureScreenshot });
+
+ await expect(
+ handlers.captureScreenshot({
+ url: "https://p-project.wstd.dev:5173/?authToken=secret&mode=design",
+ viewport: { width: 1440, height: 900 },
+ })
+ ).rejects.toMatchObject({ code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" });
+ await expect(
+ handlers.captureScreenshot({
+ baseUrl:
+ "https://p-project.apps.webstudio.is/?authToken=secret&mode=preview",
+ path: "/pricing",
+ viewport: { width: 1440, height: 900 },
+ })
+ ).rejects.toMatchObject({ code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" });
+
+ expect(captureScreenshot).not.toHaveBeenCalled();
+ expect(preview.startAndWait).not.toHaveBeenCalled();
+});
+
+test("captures path screenshots through an explicit preview target", async () => {
+ const events: string[] = [];
+ const preview = {
+ status: vi.fn(() => ({ url: "http://127.0.0.1:5173/", running: true })),
+ startAndWait: vi.fn(async (options) => {
+ events.push(
+ `start:${options.cwd}:${options.host}:${options.port}:${options.restart}`
+ );
+ return { url: "http://127.0.0.1:5175/", running: true };
+ }),
+ resolveUrl: vi.fn((path: string) => {
+ events.push(`resolve:${path}`);
+ return `http://127.0.0.1:5175${path}`;
+ }),
+ };
+ const captureScreenshot = createCaptureScreenshotMock(events);
+ const preparePreview = vi.fn(async (source: unknown) => {
+ events.push(`prepare:${source}`);
+ return { cwd: "/tmp/generated-preview" };
+ });
+
+ const handlers = createMcpPreviewHandlers({
+ preview,
+ isStale: () => false,
+ preparePreview,
+ captureScreenshot,
+ });
+
+ await handlers.captureScreenshot({
+ path: "/design-system",
+ source: "session",
+ host: "127.0.0.1",
+ port: 5175,
+ viewport: { width: 1440, height: 900 },
+ });
+
+ expect(events).toEqual([
+ "prepare:session",
+ "start:/tmp/generated-preview:127.0.0.1:5175:true",
+ "resolve:/design-system",
+ "capture:http://127.0.0.1:5175/design-system",
+ ]);
+});
diff --git a/packages/cli/src/commands/mcp-preview.ts b/packages/cli/src/commands/mcp-preview.ts
new file mode 100644
index 0000000000..738481686e
--- /dev/null
+++ b/packages/cli/src/commands/mcp-preview.ts
@@ -0,0 +1,305 @@
+import { createPreviewController } from "../preview-server";
+import {
+ captureScreenshotWithBrowserInstall,
+ createScreenshotCaptureSession,
+} from "../screenshot";
+import { inspectGeneratedBuildMetrics } from "../generated-build-metrics";
+import {
+ preparePreviewProject,
+ previewDefaultTemplate,
+ type PreviewSource,
+ validatePreviewServerOptions,
+} from "./preview";
+
+type McpPreviewController = Pick<
+ ReturnType<typeof createPreviewController>,
+ "startAndWait" | "status" | "resolveUrl"
+> &
+ Partial<Pick<ReturnType<typeof createPreviewController>, "stop">>;
+
+type McpPreviewInput = {
+ host?: string;
+ port?: number;
+ source?: PreviewSource;
+ imageDomains?: string[];
+};
+
+type CaptureScreenshotInput = Parameters<
+ typeof captureScreenshotWithBrowserInstall
+>[0];
+
+type McpScreenshotInput = {
+ url?: string;
+ baseUrl?: string;
+ path?: string;
+ output?: string;
+ host?: string;
+ port?: number;
+ imageDomains?: string[];
+ viewport: { width: number; height: number };
+ fullPage?: boolean;
+ includeImageMetrics?: boolean;
+ includeResourceMetrics?: boolean;
+ includeContrastMetrics?: boolean;
+ browser?: CaptureScreenshotInput["browser"];
+ browserPath?: string;
+ waitUntil?: CaptureScreenshotInput["waitUntil"];
+ waitForSelector?: string;
+ waitForTimeout?: number;
+ timeout?: number;
+ source?: PreviewSource;
+ format?: "png" | "jpeg" | "webp";
+ quality?: number;
+ scale?: number;
+};
+
+type McpToolProgress = {
+ report: (message: string) => void;
+};
+
+const prepareDefaultPreviewProject = (
+ source: PreviewSource = "local",
+ prepareSessionDataFile?: () => Promise<void>
+) =>
+ preparePreviewProject({
+ assets: true,
+ template: [...previewDefaultTemplate],
+ generate: true,
+ source,
+ syncIfMissing: true,
+ silent: true,
+ prepareSessionDataFile,
+ });
+
+export const createMcpPreviewHandlers = ({
+ preview,
+ isStale = () => true,
+ markFresh = () => undefined,
+ preparePreview = prepareDefaultPreviewProject,
+ prepareSessionDataFile,
+ captureScreenshot = captureScreenshotWithBrowserInstall,
+ createCaptureSession,
+}: {
+ preview: McpPreviewController;
+ isStale?: () => boolean;
+ markFresh?: () => void;
+ preparePreview?: typeof prepareDefaultPreviewProject;
+ prepareSessionDataFile?: () => Promise<void>;
+ captureScreenshot?: typeof captureScreenshotWithBrowserInstall;
+ createCaptureSession?: typeof createScreenshotCaptureSession;
+}) => {
+ let captureSession:
+ | ReturnType<typeof createScreenshotCaptureSession>
+ | undefined;
+ const closeCaptureSession = async () => {
+ try {
+ await captureSession?.close();
+ } finally {
+ captureSession = undefined;
+ }
+ };
+ const rejectBuilderUrl = (value: string) => {
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return;
+ }
+ const isProjectHost =
+ url.hostname.startsWith("p-") &&
+ (url.hostname.endsWith(".wstd.dev") ||
+ url.hostname.endsWith(".apps.webstudio.is"));
+ if (
+ isProjectHost &&
+ url.searchParams.has("authToken") &&
+ url.searchParams.has("mode")
+ ) {
+ throw Object.assign(
+ new Error(
+ "This is an authenticated Builder/share URL, not a generated-site preview. Use the share URL with webstudio init --link, then capture a generated route with screenshot { path }, or pass an intentional standalone site URL without Builder authentication parameters."
+ ),
+ { code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" }
+ );
+ }
+ };
+ const resolveScreenshotUrl = async (
+ input: McpScreenshotInput,
+ progress?: McpToolProgress
+ ) => {
+ if (input.url !== undefined) {
+ rejectBuilderUrl(input.url);
+ return input.url;
+ }
+ if (input.path === undefined) {
+ throw new Error("MCP screenshot requires url or path.");
+ }
+ if (input.baseUrl !== undefined) {
+ rejectBuilderUrl(input.baseUrl);
+ return new URL(input.path, input.baseUrl).toString();
+ }
+ const hasExplicitPreviewTarget =
+ input.host !== undefined || input.port !== undefined;
+ if (
+ preview.status().running === false ||
+ isStale() ||
+ hasExplicitPreviewTarget
+ ) {
+ await closeCaptureSession();
+ validatePreviewServerOptions({
+ host: input.host ?? "127.0.0.1",
+ port: input.port ?? 5173,
+ imageDomains: input.imageDomains,
+ });
+ progress?.report("tool screenshot preparing generated preview project");
+ const previewProject = await preparePreview(
+ input.source,
+ prepareSessionDataFile
+ );
+ progress?.report("tool screenshot starting production preview server");
+ await preview.startAndWait({
+ cwd: previewProject.cwd,
+ buildCacheKey: previewProject.buildCacheKey,
+ host: input.host,
+ port: input.port,
+ imageDomains: input.imageDomains,
+ restart: true,
+ });
+ markFresh();
+ }
+ return preview.resolveUrl(input.path);
+ };
+ const getCaptureOptions = (input: McpScreenshotInput, url: string) => ({
+ url,
+ output: input.output,
+ width: input.viewport.width,
+ height: input.viewport.height,
+ fullPage: input.fullPage,
+ includeImageMetrics: input.includeImageMetrics,
+ includeResourceMetrics: input.includeResourceMetrics,
+ includeContrastMetrics: input.includeContrastMetrics,
+ browser: input.browser ?? "auto",
+ browserPath: input.browserPath,
+ waitUntil: input.waitUntil,
+ waitForSelector: input.waitForSelector,
+ waitForTimeout: input.waitForTimeout,
+ timeout: input.timeout,
+ format: input.format,
+ quality: input.quality,
+ scale: input.scale,
+ });
+ return {
+ async startPreview(input: McpPreviewInput, progress?: McpToolProgress) {
+ await closeCaptureSession();
+ validatePreviewServerOptions({
+ host: input.host ?? "127.0.0.1",
+ port: input.port ?? 5173,
+ imageDomains: input.imageDomains,
+ });
+ progress?.report(
+ "tool preview.start preparing generated preview project"
+ );
+ const previewProject = await preparePreview(
+ input.source,
+ prepareSessionDataFile
+ );
+ progress?.report("tool preview.start starting production preview server");
+ const result = await preview.startAndWait({
+ ...input,
+ cwd: previewProject.cwd,
+ buildCacheKey: previewProject.buildCacheKey,
+ restart: true,
+ });
+ markFresh();
+ return {
+ ...result,
+ generatedBuildMetrics: await inspectGeneratedBuildMetrics(
+ previewProject.cwd
+ ),
+ };
+ },
+ async captureScreenshot(
+ input: McpScreenshotInput,
+ progress?: McpToolProgress
+ ) {
+ const url = await resolveScreenshotUrl(input, progress);
+ progress?.report(`tool screenshot capturing ${url}`);
+ const captureOptions = getCaptureOptions(input, url);
+ if (input.source === "session" && createCaptureSession !== undefined) {
+ captureSession ??= createCaptureSession();
+ return await captureSession.capture(captureOptions);
+ }
+ return await captureScreenshot({
+ ...captureOptions,
+ isJson: false,
+ isMcp: true,
+ isInteractive: false,
+ confirmInstall: async () => false,
+ });
+ },
+ async capturePageScreenshots(
+ inputs: readonly McpScreenshotInput[],
+ progress?: McpToolProgress
+ ) {
+ const firstInput = inputs[0];
+ if (firstInput === undefined) {
+ return [];
+ }
+ if (
+ createCaptureSession === undefined ||
+ firstInput.source !== "session" ||
+ inputs.some((input) => input.source !== firstInput.source)
+ ) {
+ throw new Error(
+ "Resized screenshot capture requires session preview pages."
+ );
+ }
+ const urls: string[] = [];
+ for (const input of inputs) {
+ urls.push(await resolveScreenshotUrl(input, progress));
+ }
+ progress?.report(
+ `tool screenshot capturing ${new Set(urls).size} pages across ${inputs.length} viewport widths`
+ );
+ captureSession ??= createCaptureSession();
+ return await captureSession.capturePage(
+ inputs.map((input, index) => {
+ const url = urls[index];
+ if (url === undefined) {
+ throw new Error("Screenshot URL resolution was incomplete.");
+ }
+ return getCaptureOptions(input, url);
+ })
+ );
+ },
+ async stopPreview() {
+ const errors: unknown[] = [];
+ try {
+ await closeCaptureSession();
+ } catch (error) {
+ errors.push(error);
+ }
+ let result;
+ try {
+ if (preview.stop === undefined) {
+ throw new Error("Preview controller cannot stop its owned preview.");
+ }
+ result = await preview.stop();
+ } catch (error) {
+ errors.push(error);
+ }
+ if (errors.length === 1) {
+ throw errors[0];
+ }
+ if (errors.length > 1) {
+ throw new AggregateError(
+ errors,
+ "Could not clean up screenshot capture or stop the owned preview."
+ );
+ }
+ if (result === undefined) {
+ throw new Error("Preview controller did not return its stopped state.");
+ }
+ return result;
+ },
+ };
+};
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index db110874e7..710fc96042 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -2,13 +2,14 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, expect, test, vi } from "vitest";
+import { listProjectSessionMcpTools } from "@webstudio-is/project-build/mcp";
+import { publicApiOperations } from "@webstudio-is/protocol";
import { __testing__, mcpOptions, prepareMcpProjectSession } from "./mcp";
const {
assertPersistedMcpCheckpointAcknowledged,
assertSingleOpCallToolSupported,
applyMcpRunOptions,
- createMcpPreviewHandlers,
createMcpResourceErrorPayload,
createMcpRunCheckpointStopPayload,
createMcpRunErrorPayload,
@@ -24,6 +25,7 @@ const {
getMcpToolCallError,
readPersistedMcpCheckpoint,
updatePersistedMcpCheckpoint,
+ executeMcpRunCall,
} = __testing__;
test("classifies structured MCP tool failures for nonzero CLI exit", () => {
@@ -68,12 +70,18 @@ afterEach(async () => {
test("documents MCP stdio startup and discovery tools", () => {
const yargs = {
command: vi.fn(() => yargs),
+ option: vi.fn(() => yargs),
example: vi.fn(() => yargs),
epilogue: vi.fn(() => yargs),
};
mcpOptions(yargs as never);
+ expect(yargs.option).toHaveBeenCalledWith(
+ "project",
+ expect.objectContaining({ type: "string" })
+ );
+
expect(yargs.example).toHaveBeenCalledWith(
"$0 mcp",
"Run a local MCP server over stdio for the configured Webstudio project"
@@ -462,12 +470,13 @@ test("applies batch dry-run to every MCP run call", () => {
});
test("persists MCP checkpoints across single-op-call processes", async () => {
+ const tools = listProjectSessionMcpTools(publicApiOperations);
const dir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-checkpoint-"));
tempDirs.push(dir);
await updatePersistedMcpCheckpoint({
tool: "components.coverage-plan",
- projectRoot: dir,
+ scope: { projectRoot: dir },
structuredContent: {
data: {
checkpoint: {
@@ -481,7 +490,9 @@ test("persists MCP checkpoints across single-op-call processes", async () => {
},
});
- await expect(readPersistedMcpCheckpoint(dir)).resolves.toEqual({
+ await expect(
+ readPersistedMcpCheckpoint({ projectRoot: dir })
+ ).resolves.toEqual({
tool: "components.coverage-plan",
message:
"Stop after this coverage-plan response and report before continuing.",
@@ -489,27 +500,95 @@ test("persists MCP checkpoints across single-op-call processes", async () => {
'node packages/cli/local.js workflow.next \'{"goal":"design-system-page","phase":"page-creation"}\'',
});
await expect(
- assertPersistedMcpCheckpointAcknowledged("components.get", dir)
+ assertPersistedMcpCheckpointAcknowledged("components.get", tools, {
+ projectRoot: dir,
+ })
+ ).resolves.toBeUndefined();
+ await expect(
+ assertPersistedMcpCheckpointAcknowledged("create-page", tools, {
+ projectRoot: dir,
+ })
).rejects.toMatchObject({
code: "CHECKPOINT_REQUIRED",
message: expect.stringContaining("CHECKPOINT_REQUIRED"),
});
await expect(
- assertPersistedMcpCheckpointAcknowledged("checkpoint.ack", dir)
+ assertPersistedMcpCheckpointAcknowledged("checkpoint.ack", tools, {
+ projectRoot: dir,
+ })
).resolves.toBeUndefined();
await updatePersistedMcpCheckpoint({
tool: "checkpoint.ack",
- projectRoot: dir,
+ scope: { projectRoot: dir },
structuredContent: { data: { acknowledged: true } },
});
- await expect(readPersistedMcpCheckpoint(dir)).resolves.toBeUndefined();
await expect(
- assertPersistedMcpCheckpointAcknowledged("components.get", dir)
+ readPersistedMcpCheckpoint({ projectRoot: dir })
+ ).resolves.toBeUndefined();
+ await expect(
+ assertPersistedMcpCheckpointAcknowledged("create-page", tools, {
+ projectRoot: dir,
+ })
).resolves.toBeUndefined();
});
+test("isolates persisted MCP checkpoints by selected project", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "webstudio-mcp-projects-"));
+ tempDirs.push(dir);
+ await updatePersistedMcpCheckpoint({
+ tool: "workflow.next",
+ scope: { projectRoot: dir, projectId: "project-a" },
+ structuredContent: {
+ data: { checkpoint: { required: true, instruction: "Report project A" } },
+ },
+ });
+
+ await expect(
+ readPersistedMcpCheckpoint({ projectRoot: dir, projectId: "project-a" })
+ ).resolves.toEqual(expect.objectContaining({ message: "Report project A" }));
+ await expect(
+ readPersistedMcpCheckpoint({ projectRoot: dir, projectId: "project-b" })
+ ).resolves.toBeUndefined();
+});
+
+test("checks persisted checkpoints before every MCP run call", async () => {
+ const dir = await mkdtemp(
+ path.join(tmpdir(), "webstudio-mcp-run-checkpoint-")
+ );
+ tempDirs.push(dir);
+ const scope = { projectRoot: dir };
+ const tools = listProjectSessionMcpTools(publicApiOperations);
+ const callTool = vi.fn(async () => ({
+ structuredContent: { ok: true, data: {}, meta: {} },
+ }));
+ const core = { listTools: () => tools, callTool };
+ await updatePersistedMcpCheckpoint({
+ tool: "workflow.next",
+ scope,
+ structuredContent: {
+ data: { checkpoint: { required: true, instruction: "Report first" } },
+ },
+ });
+
+ await expect(
+ executeMcpRunCall({
+ core: core as never,
+ call: { tool: "components.get", input: {}, dryRun: false },
+ scope,
+ })
+ ).resolves.toBeDefined();
+ await expect(
+ executeMcpRunCall({
+ core: core as never,
+ call: { tool: "create-page", input: {}, dryRun: false },
+ scope,
+ })
+ ).rejects.toMatchObject({ code: "CHECKPOINT_REQUIRED" });
+ expect(callTool).toHaveBeenCalledTimes(1);
+});
+
test("formats MCP run checkpoint stops with partial results", () => {
const result = createMcpRunCheckpointStopPayload({
checkpoint: {
@@ -697,7 +776,7 @@ test("persists checkpoint producer tool name", async () => {
await updatePersistedMcpCheckpoint({
tool: "future.checkpoint-tool",
- projectRoot: dir,
+ scope: { projectRoot: dir },
structuredContent: {
data: {
checkpoint: {
@@ -708,7 +787,9 @@ test("persists checkpoint producer tool name", async () => {
},
});
- await expect(readPersistedMcpCheckpoint(dir)).resolves.toMatchObject({
+ await expect(
+ readPersistedMcpCheckpoint({ projectRoot: dir })
+ ).resolves.toMatchObject({
tool: "future.checkpoint-tool",
});
});
@@ -821,470 +902,3 @@ test("adapts MCP upload assets input to public API upload input", () => {
});
expect(input).toHaveProperty("readAssetData", expect.any(Function));
});
-
-const createCaptureScreenshotMock = (events: string[]) =>
- vi.fn(async (options) => {
- events.push(`capture:${options.url}`);
- return {
- output: "screenshot.png",
- browser: {
- browser: "chromium" as const,
- path: "/browser",
- source: "path" as const,
- },
- viewport: { width: options.width, height: options.height },
- fullPage: options.fullPage === true,
- elapsedMs: 1,
- warnings: [],
- layout: {
- viewportWidth: options.width,
- viewportHeight: options.height,
- contentWidth: options.width + 20,
- contentHeight: options.height * 2,
- horizontalOverflow: true,
- images: [],
- resources: [],
- },
- };
- });
-
-test("captures stale path screenshots through the restarted preview server", async () => {
- const events: string[] = [];
- const prepareSessionDataFile = vi.fn(async () => {
- events.push("session");
- });
- const preview = {
- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
- startAndWait: vi.fn(async (options) => {
- events.push(`start:${options.cwd}:${options.restart}`);
- return { url: "http://127.0.0.1:3000/", running: true };
- }),
- resolveUrl: vi.fn((path: string) => {
- events.push(`resolve:${path}`);
- return `http://127.0.0.1:3000${path}`;
- }),
- };
- const captureScreenshot = createCaptureScreenshotMock(events);
- const progress: string[] = [];
-
- const handlers = createMcpPreviewHandlers({
- preview,
- isStale: () => true,
- preparePreview: async () => {
- events.push("prepare");
- return { cwd: "/tmp/generated-preview" };
- },
- prepareSessionDataFile,
- captureScreenshot,
- });
-
- await expect(
- handlers.captureScreenshot(
- {
- path: "/pricing",
- source: "session",
- viewport: { width: 1440, height: 900 },
- },
- {
- report: (message) => {
- progress.push(message);
- },
- }
- )
- ).resolves.toMatchObject({
- output: "screenshot.png",
- layout: {
- viewportWidth: 1440,
- contentWidth: 1460,
- horizontalOverflow: true,
- images: [],
- resources: [],
- },
- });
-
- expect(captureScreenshot).toHaveBeenCalledWith(
- expect.objectContaining({
- browser: "auto",
- url: "http://127.0.0.1:3000/pricing",
- })
- );
- expect(events).toEqual([
- "prepare",
- "start:/tmp/generated-preview:true",
- "resolve:/pricing",
- "capture:http://127.0.0.1:3000/pricing",
- ]);
- expect(prepareSessionDataFile).not.toHaveBeenCalled();
- expect(progress).toEqual([
- "tool screenshot preparing generated preview project",
- "tool screenshot starting production preview server",
- "tool screenshot capturing http://127.0.0.1:3000/pricing",
- ]);
-});
-
-test("passes explicit preview source to preview preparation", async () => {
- const events: string[] = [];
- const preview = {
- status: vi.fn(() => ({ url: "", running: false })),
- startAndWait: vi.fn(async (options) => {
- events.push(`start:${options.cwd}:${options.restart}`);
- return { url: "http://127.0.0.1:3000/", running: true };
- }),
- resolveUrl: vi.fn(),
- };
- const prepareSessionDataFile = vi.fn(async () => undefined);
- const preparePreview = vi.fn(async (source, prepareSessionDataFile) => {
- events.push(`prepare:${source}`);
- await prepareSessionDataFile?.();
- return { cwd: "/tmp/generated-preview" };
- });
- const progress: string[] = [];
-
- const handlers = createMcpPreviewHandlers({
- preview,
- preparePreview,
- prepareSessionDataFile,
- });
-
- await handlers.startPreview(
- { source: "session" },
- {
- report: (message) => {
- progress.push(message);
- },
- }
- );
-
- expect(preparePreview).toHaveBeenCalledWith(
- "session",
- prepareSessionDataFile
- );
- expect(prepareSessionDataFile).toHaveBeenCalledOnce();
- expect(events).toEqual([
- "prepare:session",
- "start:/tmp/generated-preview:true",
- ]);
- expect(progress).toEqual([
- "tool preview.start preparing generated preview project",
- "tool preview.start starting production preview server",
- ]);
-});
-
-test("rejects invalid external image domains before preparing preview", async () => {
- const preview = {
- status: vi.fn(() => ({ url: "", running: false })),
- startAndWait: vi.fn(),
- resolveUrl: vi.fn(),
- };
- const preparePreview = vi.fn();
- const handlers = createMcpPreviewHandlers({ preview, preparePreview });
-
- await expect(
- handlers.startPreview({
- imageDomains: ["https://images.example.com/path"],
- })
- ).rejects.toThrow(
- "Image domains must be hostnames without a protocol or path"
- );
- await expect(
- handlers.captureScreenshot({
- path: "/",
- imageDomains: ["https://images.example.com/path"],
- viewport: { width: 1440, height: 900 },
- })
- ).rejects.toThrow(
- "Image domains must be hostnames without a protocol or path"
- );
-
- expect(preparePreview).not.toHaveBeenCalled();
- expect(preview.startAndWait).not.toHaveBeenCalled();
-});
-
-test("captures fresh path screenshots through the running preview server", async () => {
- const events: string[] = [];
- const preview = {
- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
- startAndWait: vi.fn(),
- resolveUrl: vi.fn((path: string) => {
- events.push(`resolve:${path}`);
- return `http://127.0.0.1:3000${path}`;
- }),
- };
- const captureScreenshot = createCaptureScreenshotMock(events);
- const progress: string[] = [];
-
- const handlers = createMcpPreviewHandlers({
- preview,
- isStale: () => false,
- preparePreview: async () => {
- events.push("prepare");
- return { cwd: "/tmp/generated-preview" };
- },
- captureScreenshot,
- });
-
- await handlers.captureScreenshot(
- {
- path: "/about",
- viewport: { width: 1440, height: 900 },
- fullPage: true,
- },
- {
- report: (message) => {
- progress.push(message);
- },
- }
- );
-
- expect(preview.startAndWait).not.toHaveBeenCalled();
- expect(events).toEqual([
- "resolve:/about",
- "capture:http://127.0.0.1:3000/about",
- ]);
- expect(captureScreenshot).toHaveBeenCalledWith(
- expect.objectContaining({
- fullPage: true,
- })
- );
- expect(progress).toEqual([
- "tool screenshot capturing http://127.0.0.1:3000/about",
- ]);
-});
-
-test("reuses and closes one browser capture session for session screenshots", async () => {
- const preview = {
- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
- startAndWait: vi.fn(),
- resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
- stop: vi.fn(async () => ({ url: "", running: false })),
- };
- const capture = createCaptureScreenshotMock([]);
- const close = vi.fn(async () => undefined);
- const capturePage = vi.fn(async () => []);
- const createCaptureSession = vi.fn(() => ({ capture, capturePage, close }));
- const handlers = createMcpPreviewHandlers({
- preview,
- isStale: () => false,
- createCaptureSession,
- });
-
- await handlers.captureScreenshot({
- path: "/one",
- source: "session",
- viewport: { width: 1440, height: 900 },
- });
- await handlers.captureScreenshot({
- path: "/two",
- source: "session",
- viewport: { width: 390, height: 844 },
- });
-
- expect(createCaptureSession).toHaveBeenCalledOnce();
- expect(capture).toHaveBeenCalledTimes(2);
- expect(close).not.toHaveBeenCalled();
-
- await handlers.stopPreview();
-
- expect(close).toHaveBeenCalledOnce();
- expect(preview.stop).toHaveBeenCalledOnce();
-});
-
-test("stops the owned preview when browser capture cleanup fails", async () => {
- const preview = {
- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
- startAndWait: vi.fn(),
- resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
- stop: vi.fn(async () => ({ url: "", running: false })),
- };
- const cleanupError = new Error("browser cleanup failed");
- const createCaptureSession = vi.fn(() => ({
- capture: createCaptureScreenshotMock([]),
- capturePage: vi.fn(async () => []),
- close: vi.fn(async () => {
- throw cleanupError;
- }),
- }));
- const handlers = createMcpPreviewHandlers({
- preview,
- isStale: () => false,
- createCaptureSession,
- });
-
- await handlers.captureScreenshot({
- path: "/one",
- source: "session",
- viewport: { width: 1440, height: 900 },
- });
-
- await expect(handlers.stopPreview()).rejects.toBe(cleanupError);
- expect(preview.stop).toHaveBeenCalledOnce();
-});
-
-test("captures one session page across multiple viewports through resize", async () => {
- const preview = {
- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),
- startAndWait: vi.fn(),
- resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),
- };
- const capture = createCaptureScreenshotMock([]);
- const capturePage = vi.fn(
- async (optionsList) => await Promise.all(optionsList.map(capture))
- );
- const close = vi.fn(async () => undefined);
- const createCaptureSession = vi.fn(() => ({
- capture,
- capturePage,
- close,
- }));
- const handlers = createMcpPreviewHandlers({
- preview,
- isStale: () => false,
- createCaptureSession,
- });
-
- const results = await handlers.capturePageScreenshots([
- {
- path: "/responsive",
- source: "session",
- viewport: { width: 375, height: 812 },
- waitForTimeout: 0,
- },
- {
- path: "/responsive",
- source: "session",
- viewport: { width: 1440, height: 900 },
- waitForTimeout: 0,
- },
- ]);
-
- expect(results.map((result) => result.viewport.width)).toEqual([375, 1440]);
- expect(createCaptureSession).toHaveBeenCalledOnce();
- expect(capturePage).toHaveBeenCalledWith([
- expect.objectContaining({
- url: "http://127.0.0.1:3000/responsive",
- width: 375,
- waitForTimeout: 0,
- }),
- expect.objectContaining({
- url: "http://127.0.0.1:3000/responsive",
- width: 1440,
- waitForTimeout: 0,
- }),
- ]);
- expect(preview.startAndWait).not.toHaveBeenCalled();
-});
-
-test("captures path screenshots through an existing base URL without preview", async () => {
- const events: string[] = [];
- const preview = {
- status: vi.fn(),
- startAndWait: vi.fn(),
- resolveUrl: vi.fn(),
- };
- const captureScreenshot = createCaptureScreenshotMock(events);
- const preparePreview = vi.fn(async () => {
- events.push("prepare");
- return { cwd: "/tmp/generated-preview" };
- });
- const progress: string[] = [];
-
- const handlers = createMcpPreviewHandlers({
- preview,
- preparePreview,
- captureScreenshot,
- });
-
- await handlers.captureScreenshot(
- {
- baseUrl: "http://127.0.0.1:5177",
- path: "/design-system",
- viewport: { width: 1440, height: 900 },
- },
- {
- report: (message) => {
- progress.push(message);
- },
- }
- );
-
- expect(preview.status).not.toHaveBeenCalled();
- expect(preview.startAndWait).not.toHaveBeenCalled();
- expect(preview.resolveUrl).not.toHaveBeenCalled();
- expect(preparePreview).not.toHaveBeenCalled();
- expect(events).toEqual(["capture:http://127.0.0.1:5177/design-system"]);
- expect(progress).toEqual([
- "tool screenshot capturing http://127.0.0.1:5177/design-system",
- ]);
-});
-
-test("rejects authenticated Builder URLs as generated preview targets", async () => {
- const preview = {
- status: vi.fn(),
- startAndWait: vi.fn(),
- resolveUrl: vi.fn(),
- };
- const captureScreenshot = vi.fn();
- const handlers = createMcpPreviewHandlers({ preview, captureScreenshot });
-
- await expect(
- handlers.captureScreenshot({
- url: "https://p-project.wstd.dev:5173/?authToken=secret&mode=design",
- viewport: { width: 1440, height: 900 },
- })
- ).rejects.toMatchObject({ code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" });
- await expect(
- handlers.captureScreenshot({
- baseUrl:
- "https://p-project.apps.webstudio.is/?authToken=secret&mode=preview",
- path: "/pricing",
- viewport: { width: 1440, height: 900 },
- })
- ).rejects.toMatchObject({ code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" });
-
- expect(captureScreenshot).not.toHaveBeenCalled();
- expect(preview.startAndWait).not.toHaveBeenCalled();
-});
-
-test("captures path screenshots through an explicit preview target", async () => {
- const events: string[] = [];
- const preview = {
- status: vi.fn(() => ({ url: "http://127.0.0.1:5173/", running: true })),
- startAndWait: vi.fn(async (options) => {
- events.push(
- `start:${options.cwd}:${options.host}:${options.port}:${options.restart}`
- );
- return { url: "http://127.0.0.1:5175/", running: true };
- }),
- resolveUrl: vi.fn((path: string) => {
- events.push(`resolve:${path}`);
- return `http://127.0.0.1:5175${path}`;
- }),
- };
- const captureScreenshot = createCaptureScreenshotMock(events);
- const preparePreview = vi.fn(async (source: unknown) => {
- events.push(`prepare:${source}`);
- return { cwd: "/tmp/generated-preview" };
- });
-
- const handlers = createMcpPreviewHandlers({
- preview,
- isStale: () => false,
- preparePreview,
- captureScreenshot,
- });
-
- await handlers.captureScreenshot({
- path: "/design-system",
- source: "session",
- host: "127.0.0.1",
- port: 5175,
- viewport: { width: 1440, height: 900 },
- });
-
- expect(events).toEqual([
- "prepare:session",
- "start:/tmp/generated-preview:127.0.0.1:5175:true",
- "resolve:/design-system",
- "capture:http://127.0.0.1:5175/design-system",
- ]);
-});
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 0ca893aad7..2070fc50ec 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -6,6 +6,8 @@ import {
createProjectSessionMcpCore,
createMcpStdioTransport,
getProjectSessionMcpCheckpoint,
+ isReadOnlyProjectSessionMcpToolCall,
+ type ProjectSessionMcpTool,
} from "@webstudio-is/project-build/mcp";
import type { BuilderNamespace } from "@webstudio-is/project-build/contracts";
import { diffPngFiles } from "@webstudio-is/project-build/visual";
@@ -38,7 +40,6 @@ import {
import { executeProjectSessionApiOperation } from "../project-session-api";
import { createPreviewController, findAvailablePort } from "../preview-server";
import {
- captureScreenshotWithBrowserInstall,
createScreenshotCaptureSession,
installTesseractForOcr,
} from "../screenshot";
@@ -54,8 +55,7 @@ import {
import { readCliDoc } from "../docs";
import { printJson } from "../json-output";
import { isPlainRecord } from "../type-utils";
-import { inspectGeneratedBuildMetrics } from "../generated-build-metrics";
-import { LOCAL_DATA_FILE } from "../config";
+import { getLocalProjectStateDirectory, LOCAL_DATA_FILE } from "../config";
import {
assertMcpBatchMutationApproved,
isMcpProjectsManifest,
@@ -65,12 +65,7 @@ import {
} from "./mcp-batch";
import { apiCompatibilityHeaders } from "./api";
import { importProject as importProjectCommand } from "./import";
-import {
- preparePreviewProject,
- previewDefaultTemplate,
- type PreviewSource,
- validatePreviewServerOptions,
-} from "./preview";
+import { createMcpPreviewHandlers } from "./mcp-preview";
import type {
CommonYargsArgv,
StrictYargsOptionsToInterface,
@@ -82,52 +77,6 @@ type StartableProjectSession = {
markStale: (namespaces: readonly BuilderNamespace[]) => Promise<unknown>;
};
-type McpPreviewController = Pick<
- ReturnType<typeof createPreviewController>,
- "startAndWait" | "status" | "resolveUrl"
-> &
- Partial<Pick<ReturnType<typeof createPreviewController>, "stop">>;
-
-type McpPreviewInput = {
- host?: string;
- port?: number;
- source?: PreviewSource;
- imageDomains?: string[];
-};
-
-type CaptureScreenshotInput = Parameters<
- typeof captureScreenshotWithBrowserInstall
->[0];
-
-type McpScreenshotInput = {
- url?: string;
- baseUrl?: string;
- path?: string;
- output?: string;
- host?: string;
- port?: number;
- imageDomains?: string[];
- viewport: { width: number; height: number };
- fullPage?: boolean;
- includeImageMetrics?: boolean;
- includeResourceMetrics?: boolean;
- includeContrastMetrics?: boolean;
- browser?: CaptureScreenshotInput["browser"];
- browserPath?: string;
- waitUntil?: CaptureScreenshotInput["waitUntil"];
- waitForSelector?: string;
- waitForTimeout?: number;
- timeout?: number;
- source?: PreviewSource;
- format?: "png" | "jpeg" | "webp";
- quality?: number;
- scale?: number;
-};
-
-type McpToolProgress = {
- report: (message: string) => void;
-};
-
type PublicApiCommand = (typeof publicApiOperations)[number]["command"];
type CliMcpHost = Parameters<
typeof createProjectSessionMcpCore<PublicApiCommand>
@@ -142,7 +91,7 @@ export const prepareMcpProjectSession = async (
};
const mcpStatusPrefix = "[webstudio mcp]";
-const mcpCheckpointFile = ".webstudio/mcp-checkpoint.json";
+const mcpCheckpointFilename = "mcp-checkpoint.json";
const renderedAuditArtifactDirectory = ".webstudio/audits";
export const formatMcpStatusLine = (message: string) =>
@@ -236,13 +185,24 @@ type PersistedMcpCheckpoint = {
nextCommand?: string;
};
-const getMcpCheckpointPath = (projectRoot = cwd()) =>
- path.join(projectRoot, mcpCheckpointFile);
+type McpProjectScope = {
+ projectRoot?: string;
+ projectId?: string;
+};
+
+const getMcpCheckpointPath = ({
+ projectRoot = cwd(),
+ projectId,
+}: McpProjectScope = {}) =>
+ path.join(
+ getLocalProjectStateDirectory(projectRoot, projectId),
+ mcpCheckpointFilename
+ );
-const readPersistedMcpCheckpoint = async (projectRoot = cwd()) => {
+const readPersistedMcpCheckpoint = async (scope: McpProjectScope = {}) => {
try {
return JSON.parse(
- await readFile(getMcpCheckpointPath(projectRoot), "utf8")
+ await readFile(getMcpCheckpointPath(scope), "utf8")
) as PersistedMcpCheckpoint;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
@@ -254,25 +214,29 @@ const readPersistedMcpCheckpoint = async (projectRoot = cwd()) => {
const writePersistedMcpCheckpoint = async (
checkpoint: PersistedMcpCheckpoint,
- projectRoot = cwd()
+ scope: McpProjectScope = {}
) => {
- const checkpointPath = getMcpCheckpointPath(projectRoot);
+ const checkpointPath = getMcpCheckpointPath(scope);
await mkdir(path.dirname(checkpointPath), { recursive: true });
await writeFile(checkpointPath, JSON.stringify(checkpoint, undefined, 2));
};
-const clearPersistedMcpCheckpoint = async (projectRoot = cwd()) => {
- await rm(getMcpCheckpointPath(projectRoot), { force: true });
+const clearPersistedMcpCheckpoint = async (scope: McpProjectScope = {}) => {
+ await rm(getMcpCheckpointPath(scope), { force: true });
};
const assertPersistedMcpCheckpointAcknowledged = async (
tool: string,
- projectRoot = cwd()
+ tools: readonly ProjectSessionMcpTool[],
+ scope: McpProjectScope = {}
) => {
- if (tool === "checkpoint.ack") {
+ if (
+ tool === "checkpoint.ack" ||
+ isReadOnlyProjectSessionMcpToolCall(tool, tools)
+ ) {
return;
}
- const checkpoint = await readPersistedMcpCheckpoint(projectRoot);
+ const checkpoint = await readPersistedMcpCheckpoint(scope);
if (checkpoint === undefined) {
return;
}
@@ -293,19 +257,19 @@ const getResultCheckpoint = (tool: string, structuredContent: unknown) => {
const updatePersistedMcpCheckpoint = async ({
tool,
structuredContent,
- projectRoot = cwd(),
+ scope = {},
}: {
tool: string;
structuredContent: unknown;
- projectRoot?: string;
+ scope?: McpProjectScope;
}) => {
if (tool === "checkpoint.ack") {
- await clearPersistedMcpCheckpoint(projectRoot);
+ await clearPersistedMcpCheckpoint(scope);
return;
}
const checkpoint = getResultCheckpoint(tool, structuredContent);
if (checkpoint !== undefined) {
- await writePersistedMcpCheckpoint(checkpoint, projectRoot);
+ await writePersistedMcpCheckpoint(checkpoint, scope);
}
};
@@ -327,20 +291,6 @@ const publicApiOperationByCommand = new Map<
const shouldInvalidatePreview = (command: string) =>
publicApiOperationByCommand.get(command)?.method === "mutation";
-const prepareDefaultPreviewProject = (
- source: PreviewSource = "local",
- prepareSessionDataFile?: () => Promise<void>
-) =>
- preparePreviewProject({
- assets: true,
- template: [...previewDefaultTemplate],
- generate: true,
- source,
- syncIfMissing: true,
- silent: true,
- prepareSessionDataFile,
- });
-
const getLoadedProjectSessionSnapshot = (session: StartableProjectSession) => {
const snapshot = session.snapshot;
if (snapshot === undefined) {
@@ -351,241 +301,13 @@ const getLoadedProjectSessionSnapshot = (session: StartableProjectSession) => {
return snapshot;
};
-const createMcpPreviewHandlers = ({
- preview,
- isStale = () => true,
- markFresh = () => undefined,
- preparePreview = prepareDefaultPreviewProject,
- prepareSessionDataFile,
- captureScreenshot = captureScreenshotWithBrowserInstall,
- createCaptureSession,
-}: {
- preview: McpPreviewController;
- isStale?: () => boolean;
- markFresh?: () => void;
- preparePreview?: typeof prepareDefaultPreviewProject;
- prepareSessionDataFile?: () => Promise<void>;
- captureScreenshot?: typeof captureScreenshotWithBrowserInstall;
- createCaptureSession?: typeof createScreenshotCaptureSession;
-}) => {
- let captureSession:
- | ReturnType<typeof createScreenshotCaptureSession>
- | undefined;
- const closeCaptureSession = async () => {
- try {
- await captureSession?.close();
- } finally {
- captureSession = undefined;
- }
- };
- const rejectBuilderUrl = (value: string) => {
- let url: URL;
- try {
- url = new URL(value);
- } catch {
- return;
- }
- const isProjectHost =
- url.hostname.startsWith("p-") &&
- (url.hostname.endsWith(".wstd.dev") ||
- url.hostname.endsWith(".apps.webstudio.is"));
- if (
- isProjectHost &&
- url.searchParams.has("authToken") &&
- url.searchParams.has("mode")
- ) {
- throw Object.assign(
- new Error(
- "This is an authenticated Builder/share URL, not a generated-site preview. Use the share URL with webstudio init --link, then capture a generated route with screenshot { path }, or pass an intentional standalone site URL without Builder authentication parameters."
- ),
- { code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" }
- );
- }
- };
- const resolveScreenshotUrl = async (
- input: McpScreenshotInput,
- progress?: McpToolProgress
- ) => {
- if (input.url !== undefined) {
- rejectBuilderUrl(input.url);
- return input.url;
- }
- if (input.path === undefined) {
- throw new Error("MCP screenshot requires url or path.");
- }
- if (input.baseUrl !== undefined) {
- rejectBuilderUrl(input.baseUrl);
- return new URL(input.path, input.baseUrl).toString();
- }
- const hasExplicitPreviewTarget =
- input.host !== undefined || input.port !== undefined;
- if (
- preview.status().running === false ||
- isStale() ||
- hasExplicitPreviewTarget
- ) {
- await closeCaptureSession();
- validatePreviewServerOptions({
- host: input.host ?? "127.0.0.1",
- port: input.port ?? 5173,
- imageDomains: input.imageDomains,
- });
- progress?.report("tool screenshot preparing generated preview project");
- const previewProject = await preparePreview(
- input.source,
- prepareSessionDataFile
- );
- progress?.report("tool screenshot starting production preview server");
- await preview.startAndWait({
- cwd: previewProject.cwd,
- buildCacheKey: previewProject.buildCacheKey,
- host: input.host,
- port: input.port,
- imageDomains: input.imageDomains,
- restart: true,
- });
- markFresh();
- }
- return preview.resolveUrl(input.path);
- };
- const getCaptureOptions = (input: McpScreenshotInput, url: string) => ({
- url,
- output: input.output,
- width: input.viewport.width,
- height: input.viewport.height,
- fullPage: input.fullPage,
- includeImageMetrics: input.includeImageMetrics,
- includeResourceMetrics: input.includeResourceMetrics,
- includeContrastMetrics: input.includeContrastMetrics,
- browser: input.browser ?? "auto",
- browserPath: input.browserPath,
- waitUntil: input.waitUntil,
- waitForSelector: input.waitForSelector,
- waitForTimeout: input.waitForTimeout,
- timeout: input.timeout,
- format: input.format,
- quality: input.quality,
- scale: input.scale,
- });
- return {
- async startPreview(input: McpPreviewInput, progress?: McpToolProgress) {
- await closeCaptureSession();
- validatePreviewServerOptions({
- host: input.host ?? "127.0.0.1",
- port: input.port ?? 5173,
- imageDomains: input.imageDomains,
- });
- progress?.report(
- "tool preview.start preparing generated preview project"
- );
- const previewProject = await preparePreview(
- input.source,
- prepareSessionDataFile
- );
- progress?.report("tool preview.start starting production preview server");
- const result = await preview.startAndWait({
- ...input,
- cwd: previewProject.cwd,
- buildCacheKey: previewProject.buildCacheKey,
- restart: true,
- });
- markFresh();
- return {
- ...result,
- generatedBuildMetrics: await inspectGeneratedBuildMetrics(
- previewProject.cwd
- ),
- };
- },
- async captureScreenshot(
- input: McpScreenshotInput,
- progress?: McpToolProgress
- ) {
- const url = await resolveScreenshotUrl(input, progress);
- progress?.report(`tool screenshot capturing ${url}`);
- const captureOptions = getCaptureOptions(input, url);
- if (input.source === "session" && createCaptureSession !== undefined) {
- captureSession ??= createCaptureSession();
- return await captureSession.capture(captureOptions);
- }
- return await captureScreenshot({
- ...captureOptions,
- isJson: false,
- isMcp: true,
- isInteractive: false,
- confirmInstall: async () => false,
- });
- },
- async capturePageScreenshots(
- inputs: readonly McpScreenshotInput[],
- progress?: McpToolProgress
- ) {
- const firstInput = inputs[0];
- if (firstInput === undefined) {
- return [];
- }
- if (
- createCaptureSession === undefined ||
- firstInput.source !== "session" ||
- inputs.some((input) => input.source !== firstInput.source)
- ) {
- throw new Error(
- "Resized screenshot capture requires session preview pages."
- );
- }
- const urls: string[] = [];
- for (const input of inputs) {
- urls.push(await resolveScreenshotUrl(input, progress));
- }
- progress?.report(
- `tool screenshot capturing ${new Set(urls).size} pages across ${inputs.length} viewport widths`
- );
- captureSession ??= createCaptureSession();
- return await captureSession.capturePage(
- inputs.map((input, index) => {
- const url = urls[index];
- if (url === undefined) {
- throw new Error("Screenshot URL resolution was incomplete.");
- }
- return getCaptureOptions(input, url);
- })
- );
- },
- async stopPreview() {
- const errors: unknown[] = [];
- try {
- await closeCaptureSession();
- } catch (error) {
- errors.push(error);
- }
- let result;
- try {
- if (preview.stop === undefined) {
- throw new Error("Preview controller cannot stop its owned preview.");
- }
- result = await preview.stop();
- } catch (error) {
- errors.push(error);
- }
- if (errors.length === 1) {
- throw errors[0];
- }
- if (errors.length > 1) {
- throw new AggregateError(
- errors,
- "Could not clean up screenshot capture or stop the owned preview."
- );
- }
- if (result === undefined) {
- throw new Error("Preview controller did not return its stopped state.");
- }
- return result;
- },
- };
-};
-
export const mcpOptions = (yargs: CommonYargsArgv) =>
yargs
+ .option("project", {
+ type: "string",
+ describe:
+ "Saved project id to use without changing this directory's linked project",
+ })
.command(
["list-tools"],
"Print the concise MCP tool catalog as JSON",
@@ -665,7 +387,7 @@ const mcpListToolsOptions = (yargs: CommonYargsArgv) =>
type McpListToolsOptions = StrictYargsOptionsToInterface<
typeof mcpListToolsOptions
->;
+> & { project?: string };
const mcpListResourcesOptions = (yargs: CommonYargsArgv) =>
yargs.option("json", {
@@ -676,7 +398,7 @@ const mcpListResourcesOptions = (yargs: CommonYargsArgv) =>
type McpListResourcesOptions = StrictYargsOptionsToInterface<
typeof mcpListResourcesOptions
->;
+> & { project?: string };
const mcpReadResourceOptions = (yargs: CommonYargsArgv) =>
yargs
@@ -694,7 +416,7 @@ const mcpReadResourceOptions = (yargs: CommonYargsArgv) =>
type McpReadResourceOptions = StrictYargsOptionsToInterface<
typeof mcpReadResourceOptions
-> & { uri?: string };
+> & { uri?: string; project?: string };
const mcpSingleOpCallOptions = (yargs: CommonYargsArgv) =>
yargs
@@ -731,6 +453,7 @@ type McpSingleOpCallOptions = {
refresh?: boolean;
json?: boolean;
printSuccess?: (data: unknown) => void;
+ project?: string;
};
const mcpRunOptions = (yargs: CommonYargsArgv) =>
@@ -768,6 +491,7 @@ const mcpRunOptions = (yargs: CommonYargsArgv) =>
type McpRunOptions = StrictYargsOptionsToInterface<typeof mcpRunOptions> & {
input?: string;
+ project?: string;
};
const parseMcpSingleOpCallInput = async ({
@@ -1072,40 +796,18 @@ const assertSingleOpCallToolSupported = (tool: string) => {
}
};
-export const __testing__ = {
- createMcpPreviewHandlers,
- createMcpStatusReporter,
- formatMcpStatusLine,
- assertSingleOpCallToolSupported,
- assertPersistedMcpCheckpointAcknowledged,
- clearPersistedMcpCheckpoint,
- createMcpSingleOpCallErrorPayload,
- createMcpResourceErrorPayload: (error: unknown, elapsedMs: number) => ({
- ok: false,
- error: {
- code: getStableErrorCode(error) ?? "MCP_RESOURCE_FAILED",
- message: error instanceof Error ? error.message : String(error),
- },
- meta: { elapsedMs },
- }),
- createMcpRunErrorPayload,
- createMcpRunCheckpointStopPayload,
- getLoadedProjectSessionSnapshot,
- getResultCheckpoint,
- getMcpOperationInput,
- parseMcpSingleOpCallInput,
- validateSingleOpCallInput,
- isMcpToolCallFailure,
- getMcpToolCallError,
- applyMcpRunOptions,
- parseMcpRunCalls,
- parseMcpRunInput,
- readPersistedMcpCheckpoint,
- updatePersistedMcpCheckpoint,
-};
-
-const createCliMcpHost = async (projectRoot = cwd()) => {
- const connection = await resolveApiConnection(undefined, projectRoot);
+const createCliMcpHost = async ({
+ projectRoot = cwd(),
+ projectId,
+}: {
+ projectRoot?: string;
+ projectId?: string;
+} = {}) => {
+ const connection = await resolveApiConnection(
+ undefined,
+ projectRoot,
+ projectId
+ );
const apiConnection = {
...connection,
headers: apiCompatibilityHeaders,
@@ -1125,6 +827,7 @@ const createCliMcpHost = async (projectRoot = cwd()) => {
const session = createCliProjectSession({
connection: apiConnection,
projectRoot,
+ sessionProjectId: projectId,
});
await prepareMcpProjectSession(session);
const preview = createPreviewController({ host: "127.0.0.1", port: 5173 });
@@ -1261,6 +964,7 @@ const createCliMcpHost = async (projectRoot = cwd()) => {
},
};
return {
+ scope: { projectRoot, projectId } satisfies McpProjectScope,
session,
host,
apiContract,
@@ -1302,12 +1006,17 @@ const assertMcpToolServerSupport = (
const executeMcpRunCall = async ({
core,
call,
- projectRoot,
+ scope,
}: {
core: CliMcpCore;
call: McpRunCall;
- projectRoot?: string;
+ scope?: McpProjectScope;
}) => {
+ await assertPersistedMcpCheckpointAcknowledged(
+ call.tool,
+ core.listTools(),
+ scope
+ );
const result = await core.callTool({
name: call.tool,
input: call.input,
@@ -1321,11 +1030,43 @@ const executeMcpRunCall = async ({
await updatePersistedMcpCheckpoint({
tool: call.tool,
structuredContent: result.structuredContent,
- projectRoot,
+ scope,
});
return { result, checkpoint };
};
+export const __testing__ = {
+ createMcpStatusReporter,
+ formatMcpStatusLine,
+ assertSingleOpCallToolSupported,
+ assertPersistedMcpCheckpointAcknowledged,
+ clearPersistedMcpCheckpoint,
+ createMcpSingleOpCallErrorPayload,
+ createMcpResourceErrorPayload: (error: unknown, elapsedMs: number) => ({
+ ok: false,
+ error: {
+ code: getStableErrorCode(error) ?? "MCP_RESOURCE_FAILED",
+ message: error instanceof Error ? error.message : String(error),
+ },
+ meta: { elapsedMs },
+ }),
+ createMcpRunErrorPayload,
+ createMcpRunCheckpointStopPayload,
+ getLoadedProjectSessionSnapshot,
+ getResultCheckpoint,
+ getMcpOperationInput,
+ parseMcpSingleOpCallInput,
+ validateSingleOpCallInput,
+ isMcpToolCallFailure,
+ getMcpToolCallError,
+ applyMcpRunOptions,
+ parseMcpRunCalls,
+ parseMcpRunInput,
+ readPersistedMcpCheckpoint,
+ updatePersistedMcpCheckpoint,
+ executeMcpRunCall,
+};
+
export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {
if (options.tool === undefined || options.tool === "") {
throw new Error("mcp single-op-call requires a tool name.");
@@ -1340,14 +1081,20 @@ export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {
assertSingleOpCallToolSupported(options.tool);
const input = await parseMcpSingleOpCallInput(options);
validateSingleOpCallInput(options.tool, input);
- const { host, apiContract } = await createCliMcpHost();
+ const { host, apiContract, scope } = await createCliMcpHost({
+ projectId: options.project,
+ });
assertMcpToolServerSupport(options.tool, apiContract);
const core = createCliMcpCore(host);
const persistedCheckpoint =
options.tool === "checkpoint.ack"
- ? await readPersistedMcpCheckpoint()
+ ? await readPersistedMcpCheckpoint(scope)
: undefined;
- await assertPersistedMcpCheckpointAcknowledged(options.tool);
+ await assertPersistedMcpCheckpointAcknowledged(
+ options.tool,
+ core.listTools(),
+ scope
+ );
if (options.refresh === true && options.tool !== "refresh") {
await core.callTool({ name: "refresh" });
}
@@ -1376,6 +1123,7 @@ export const mcpSingleOpCall = async (options: McpSingleOpCallOptions) => {
await updatePersistedMcpCheckpoint({
tool: options.tool,
structuredContent: result.structuredContent,
+ scope,
});
const session = result.structuredContent.meta.session;
const committed =
@@ -1440,7 +1188,9 @@ const runMcpProjectsBatch = async ({
`batch project ${project.id} started at call ${startCall + 1}/${project.calls.length}`
)}\n`
);
- const { host, apiContract } = await createCliMcpHost(project.root);
+ const { host, apiContract } = await createCliMcpHost({
+ projectRoot: project.root,
+ });
const core = createCliMcpCore(host);
const tools = new Map(core.listTools().map((tool) => [tool.name, tool]));
for (const call of project.calls.slice(startCall)) {
@@ -1453,12 +1203,6 @@ const runMcpProjectsBatch = async ({
approved: options.approveMutations === true,
});
}
- if (startCall < project.calls.length) {
- await assertPersistedMcpCheckpointAcknowledged(
- project.calls[startCall]!.tool,
- project.root
- );
- }
for (let index = startCall; index < project.calls.length; index++) {
const call = project.calls[index]!;
const tool = tools.get(call.tool);
@@ -1469,10 +1213,17 @@ const runMcpProjectsBatch = async ({
const { checkpoint } = await executeMcpRunCall({
core,
call,
- projectRoot: project.root,
+ scope: { projectRoot: project.root },
});
await callSucceeded(index + 1);
- if (checkpoint !== undefined && index + 1 < project.calls.length) {
+ const nextTool = project.calls[index + 1]?.tool;
+ if (
+ checkpoint !== undefined &&
+ index + 1 < project.calls.length &&
+ (nextTool === undefined ||
+ isReadOnlyProjectSessionMcpToolCall(nextTool, core.listTools()) ===
+ false)
+ ) {
throw createMcpInputError(checkpoint.message, "CHECKPOINT_REQUIRED");
}
}
@@ -1539,15 +1290,17 @@ export const mcpRun = async (options: McpRunOptions) => {
);
const results: unknown[] = [];
let core: ReturnType<typeof createProjectSessionMcpCore<PublicApiCommand>>;
+ let scope: McpProjectScope = {};
try {
- const { host, apiContract } = await createCliMcpHost();
+ const mcpHost = await createCliMcpHost({
+ projectId: options.project,
+ });
+ const { host, apiContract } = mcpHost;
+ scope = mcpHost.scope;
for (const call of calls) {
assertMcpToolServerSupport(call.tool, apiContract);
}
core = createCliMcpCore(host);
- if (calls.length > 0) {
- await assertPersistedMcpCheckpointAcknowledged(calls[0]!.tool);
- }
} catch (error) {
reportMcpRunPreflightFailure({
error,
@@ -1564,7 +1317,11 @@ export const mcpRun = async (options: McpRunOptions) => {
)}\n`
);
try {
- const { result, checkpoint } = await executeMcpRunCall({ core, call });
+ const { result, checkpoint } = await executeMcpRunCall({
+ core,
+ call,
+ scope,
+ });
const session = result.structuredContent.meta.session;
const committed =
session === undefined ? "" : `; committed=${session.committed}`;
@@ -1578,7 +1335,14 @@ export const mcpRun = async (options: McpRunOptions) => {
ok: true,
structuredContent: result.structuredContent,
});
- if (checkpoint !== undefined && callNumber < calls.length) {
+ const nextTool = calls[callNumber]?.tool;
+ if (
+ checkpoint !== undefined &&
+ callNumber < calls.length &&
+ (nextTool === undefined ||
+ isReadOnlyProjectSessionMcpToolCall(nextTool, core.listTools()) ===
+ false)
+ ) {
const checkpointStopPayload = createMcpRunCheckpointStopPayload({
checkpoint,
completedCalls: callNumber,
@@ -1638,10 +1402,10 @@ export const mcpRun = async (options: McpRunOptions) => {
});
};
-export const mcpListTools = async (_options: McpListToolsOptions) => {
+export const mcpListTools = async (options: McpListToolsOptions) => {
const startedAt = Date.now();
stderr.write(`${formatMcpStatusLine("list-tools started")}\n`);
- const { host } = await createCliMcpHost();
+ const { host } = await createCliMcpHost({ projectId: options.project });
const core = createCliMcpCore(host);
const result = await core.callTool({
name: "meta.index",
@@ -1656,9 +1420,9 @@ export const mcpListTools = async (_options: McpListToolsOptions) => {
printJson(result.structuredContent);
};
-export const mcpListResources = async (_options: McpListResourcesOptions) => {
+export const mcpListResources = async (options: McpListResourcesOptions) => {
const startedAt = Date.now();
- const { host } = await createCliMcpHost();
+ const { host } = await createCliMcpHost({ projectId: options.project });
const core = createCliMcpCore(host);
printJson({
ok: true,
@@ -1673,7 +1437,7 @@ export const mcpReadResource = async (options: McpReadResourceOptions) => {
}
const startedAt = Date.now();
try {
- const { host } = await createCliMcpHost();
+ const { host } = await createCliMcpHost({ projectId: options.project });
const core = createCliMcpCore(host);
printJson({
ok: true,
@@ -1688,7 +1452,7 @@ export const mcpReadResource = async (options: McpReadResourceOptions) => {
}
};
-export const mcp = async () => {
+export const mcp = async (options: { project?: string } = {}) => {
const status = createMcpStatusReporter();
let didReportClose = false;
const reportClose = () => {
@@ -1701,7 +1465,9 @@ export const mcp = async () => {
stdin.once("end", reportClose);
stdin.once("close", reportClose);
status.starting();
- const { host, toolCount, reportLog, apiContract } = await createCliMcpHost();
+ const { host, toolCount, reportLog, apiContract } = await createCliMcpHost({
+ projectId: options.project,
+ });
status.sessionReady();
status.apiContract(apiContract);
status.ready(toolCount);
diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.ts
index e03308e098..0cc5773030 100644
--- a/packages/cli/src/commands/schema.test.ts
+++ b/packages/cli/src/commands/schema.test.ts
@@ -161,6 +161,20 @@ test("prints compact mcp tool summaries as json by default", () => {
);
expect(output.resources).toEqual(listProjectSessionMcpResources());
expect(output.toolCount).toBe(expectedTools.length);
+ const handshakePayload = expectedTools.map(
+ ({ name, description, inputSchema }) => ({
+ name,
+ description,
+ inputSchema,
+ })
+ );
+ expect(JSON.stringify(handshakePayload).length).toBeLessThan(200_000);
+ expect(
+ JSON.stringify(
+ expectedTools.find(({ name }) => name === "insert-page-transfer-item")
+ ?.inputSchema
+ ).length
+ ).toBeLessThan(1_000);
expect(output.tools).toEqual(
expect.arrayContaining([
expect.objectContaining({
@@ -233,6 +247,7 @@ test("prints full mcp tool input schemas when requested", () => {
"fragment",
"mode",
"insertIndex",
+ "dryRun",
]);
const fragmentSchema = insertFragmentTool.inputSchema.properties.fragment;
expect(fragmentSchema.type).toBe("string");
@@ -344,6 +359,24 @@ test("prints focused mcp tool schema when topic is a tool name", () => {
]);
});
+test("prints deferred schemas in full for focused discovery", () => {
+ vi.spyOn(console, "info").mockImplementation(() => undefined);
+
+ schema({ topic: "insert-page-transfer-item", json: true });
+
+ const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);
+ expect(output.tools[0]).toEqual(
+ expect.objectContaining({
+ name: "insert-page-transfer-item",
+ inputSchema: expect.objectContaining({
+ properties: expect.objectContaining({
+ item: expect.objectContaining({ anyOf: expect.any(Array) }),
+ }),
+ }),
+ })
+ );
+});
+
test("prints mcp tool overview as json without json flag", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
diff --git a/packages/cli/src/commands/schema.ts b/packages/cli/src/commands/schema.ts
index 53b7f468a5..22d5a06539 100644
--- a/packages/cli/src/commands/schema.ts
+++ b/packages/cli/src/commands/schema.ts
@@ -3,6 +3,7 @@ import {
publicApiOperations,
} from "@webstudio-is/protocol";
import {
+ getDetailedProjectSessionMcpInputSchema,
listProjectSessionMcpResources,
listProjectSessionMcpTools,
} from "@webstudio-is/project-build/mcp";
@@ -113,7 +114,7 @@ const mcpToolSchema = listProjectSessionMcpTools(publicApiOperations, {
}).map((tool) => ({
name: tool.name,
description: tool.description,
- inputSchema: tool.inputSchema,
+ inputSchema: getDetailedProjectSessionMcpInputSchema(tool),
...(tool.outputSchema === undefined
? {}
: { outputSchema: tool.outputSchema }),
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
index 17f6610907..c4070f155f 100644
--- a/packages/cli/src/config.ts
+++ b/packages/cli/src/config.ts
@@ -1,4 +1,4 @@
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { readdirSync } from "node:fs";
import envPaths from "env-paths";
import { z } from "zod";
@@ -14,6 +14,19 @@ export const GLOBAL_CONFIG_FILE = join(
export const LOCAL_CONFIG_FILE = ".webstudio/config.json";
export const LOCAL_DATA_FILE = ".webstudio/data.json";
+export const getLocalProjectStateDirectory = (
+ projectRoot: string,
+ projectId?: string
+) =>
+ projectId === undefined
+ ? join(projectRoot, dirname(LOCAL_CONFIG_FILE))
+ : join(
+ projectRoot,
+ dirname(LOCAL_CONFIG_FILE),
+ "projects",
+ encodeURIComponent(projectId)
+ );
+
const zLocalConfig = z.object({
projectId: z.string(),
});
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 52d653aff1..e0cadd15eb 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -2,15 +2,15 @@
// Edit markdown files in src/docs instead.
export const cliDocs = {
"api-use-cases":
- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- 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 installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\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 {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: 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 {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"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 --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"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## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- 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 installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\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- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: 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 {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"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 --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"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## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
"manual-api":
'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, `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 GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',
"manual-llm":
'# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get_more_tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe same local shortcut form is shorter and preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor this simple path, do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, `status`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
"manual-mcp":
- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Generate the client configuration with `webstudio connect claude`,\n `webstudio connect codex`, `webstudio connect cursor`, or\n `webstudio connect vscode`. Use `--print` to preview file-based config.\n3. Check capabilities with `webstudio permissions --json`.\n4. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n5. For MCP clients, start the server with `webstudio mcp`.\n6. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nEvery supported client follows the same generated quickstart: link the project,\nsync it, run `webstudio connect <client>`, reload or restart the client, then ask\nthe agent to use Webstudio MCP to list the project pages. The supported client\nnames are `claude`, `codex`, `cursor`, and `vscode`.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, `mcp run` stops immediately before later calls and prints partial results with `CHECKPOINT_REQUIRED`. Stop now and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: shadcn-compatible registry items for visible components and templates\n- `components.summary`: compact structured component catalog with insertability and template hints\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: shadcn-compatible registry items for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, string list, and JSON variables.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List, upload, add, update, find usage for, replace, and delete assets.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
+ '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Generate the client configuration with `webstudio connect claude`,\n `webstudio connect codex`, `webstudio connect cursor`, or\n `webstudio connect vscode`. Use `--print` to preview file-based config.\n3. Check capabilities with `webstudio permissions --json`.\n4. For shell-driven agents, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n5. For MCP clients, start the server with `webstudio mcp`.\n6. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nEvery supported client follows the same generated quickstart: link the project,\nsync it, run `webstudio connect <client>`, reload or restart the client, then ask\nthe agent to use Webstudio MCP to list the project pages. The supported client\nnames are `claude`, `codex`, `cursor`, and `vscode`.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, string list, and JSON variables.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List, upload, add, update, find usage for, replace, and delete assets.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
"mcp-startup-epilogue":
- 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get_more_tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, later one-shot calls fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nIf a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',
+ 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get_more_tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nIf a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',
"mcp-vision":
'# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n\n## Visual Verification Rule\n\nFor visual/design work, use preview.start and screenshot after generated project files are current so vision can inspect the rendered result before finishing. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\nAn authenticated project share URL is used with `webstudio init --link`; it is\nnot a generated-site preview URL. Project screenshots and rendered audits use\nthe generated local preview owned by the current CLI/MCP process. Do not pass a\nBuilder URL containing `authToken` and `mode` to `screenshot`; use `path` after\nstarting preview, or use `baseUrl` only for an intentional generated site that\nis already running.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Make sure generated project files are current, then call preview.start to build the app and keep the production-like generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate/restart preview as needed before capture; when preview is fresh in the same long-running MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview without starting or restarting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',
} as const;
diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.md
index 6c567fbcdd..0b6f5569f2 100644
--- a/packages/cli/src/docs/api-use-cases.md
+++ b/packages/cli/src/docs/api-use-cases.md
@@ -62,6 +62,7 @@ Notes:
- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.
- 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.
+- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.
- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.
- 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.
@@ -294,6 +295,14 @@ Commands:
Commands:
- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}
+- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}
+- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions '{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}' --json
+
+Notes:
+
+- Text substitutions replace exact fixed text only in the duplicated page's text children, string props, title, and metadata.
+- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.
+- Existing expressions and cloned variable/resource references keep their remapped ids.
## List page templates
diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.md
index 2fa75d4241..a55efea1fd 100644
--- a/packages/cli/src/docs/manual-mcp.md
+++ b/packages/cli/src/docs/manual-mcp.md
@@ -84,6 +84,7 @@ Rules:
- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.
- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.
- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.
+- To work with another previously linked project without changing the directory's default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.
- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.
## Reporting CLI/MCP Issues
@@ -159,7 +160,7 @@ Input shape:
Rules:
- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.
-- If a call returns `checkpoint.required`, `mcp run` stops immediately before later calls and prints partial results with `CHECKPOINT_REQUIRED`. Stop now and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing.
+- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.
- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.
- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.
@@ -201,14 +202,14 @@ Use MCP itself after startup, or call the same tools with `webstudio mcp single-
- `meta.index`: concise capability catalog
- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`
- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them
-- `components.list`: shadcn-compatible registry items for visible components and templates
-- `components.summary`: compact structured component catalog with insertability and template hints
+- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details
+- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries
- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more
- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`
- `components.search`: focused component/template search by id, namespace, label, category, or content model
- `components.find`: compatibility alias for focused component search
- `components.get`: full metadata for one component id
-- `templates.list`: shadcn-compatible registry items for template-backed insertions only
+- `templates.list`: compact metadata for template-backed insertions only
- `templates.get`: full registry item and payload metadata for one template
Component and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.
diff --git a/packages/cli/src/docs/mcp-startup-epilogue.md b/packages/cli/src/docs/mcp-startup-epilogue.md
index ae218a3b16..5b674e6537 100644
--- a/packages/cli/src/docs/mcp-startup-epilogue.md
+++ b/packages/cli/src/docs/mcp-startup-epilogue.md
@@ -36,7 +36,7 @@ stdout is reserved for MCP JSON-RPC messages while the server is running.
The server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.
-`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, later one-shot calls fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack '{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}'`.
+`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack '{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}'`.
`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.
diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.ts
index 63b45bb82b..d441a28d7c 100644
--- a/packages/cli/src/project-session.test.ts
+++ b/packages/cli/src/project-session.test.ts
@@ -9,9 +9,19 @@ import {
createCliProjectSessionStorage,
createCliProjectSessionTransport,
getCliServerApiContract,
+ getCliProjectSessionFile,
getSupportedPublicApiOperations,
} from "./project-session";
+test("scopes project session files for explicitly selected projects", () => {
+ expect(getCliProjectSessionFile("/workspace", "project/a")).toBe(
+ "/workspace/.webstudio/projects/project%2Fa/project-session.json"
+ );
+ expect(getCliProjectSessionFile("/workspace")).toBe(
+ "/workspace/.webstudio/project-session.json"
+ );
+});
+
const temporaryDirectories: string[] = [];
const createTemporaryDirectory = async () => {
diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.ts
index 0fab0d1b1f..7e7c1f3f40 100644
--- a/packages/cli/src/project-session.ts
+++ b/packages/cli/src/project-session.ts
@@ -1,5 +1,5 @@
import { readFile, rm } from "node:fs/promises";
-import { dirname, join } from "node:path";
+import { join } from "node:path";
import { cwd } from "node:process";
import {
migratePages,
@@ -37,7 +37,7 @@ import {
} from "@webstudio-is/project-build/state";
import { removeLegacyProjectSettingsFromPages } from "@webstudio-is/project-build";
import type { BuilderStateFreshness } from "@webstudio-is/project-build/state";
-import { LOCAL_CONFIG_FILE, LOCAL_DATA_FILE } from "./config";
+import { getLocalProjectStateDirectory, LOCAL_DATA_FILE } from "./config";
import type { ApiConnection } from "./api-connection";
import { getStableErrorCode } from "./error-codes";
import { writeFileAtomic } from "./fs-utils";
@@ -142,8 +142,14 @@ type PersistedCliProjectSessionSnapshot = Omit<
state: SerializedBuilderStateSnapshot;
};
-export const getCliProjectSessionFile = (projectRoot = cwd()) =>
- join(projectRoot, dirname(LOCAL_CONFIG_FILE), "project-session.json");
+export const getCliProjectSessionFile = (
+ projectRoot = cwd(),
+ projectId?: string
+) =>
+ join(
+ getLocalProjectStateDirectory(projectRoot, projectId),
+ "project-session.json"
+ );
const compatibilityVersion = "cli-project-session-v1";
const createCliProjectSessionCompatibility = (
@@ -382,12 +388,14 @@ export const createCliProjectSession = ({
connection,
storage,
projectRoot,
+ sessionProjectId,
executeServerOperation,
getPermissions,
}: {
connection: ApiConnection;
storage?: ProjectSessionStorage;
projectRoot?: string;
+ sessionProjectId?: string;
executeServerOperation?: ProjectSessionTransport["executeServerOperation"];
getPermissions?: ProjectSessionTransport["getPermissions"];
}) =>
@@ -400,7 +408,9 @@ export const createCliProjectSession = ({
}),
storage:
storage ??
- createCliProjectSessionStorage(getCliProjectSessionFile(projectRoot)),
+ createCliProjectSessionStorage(
+ getCliProjectSessionFile(projectRoot, sessionProjectId)
+ ),
compatibilityVersion,
});
diff --git a/packages/project-build/src/confirmation-token.test.ts b/packages/project-build/src/confirmation-token.test.ts
new file mode 100644
index 0000000000..6ec56ac6ce
--- /dev/null
+++ b/packages/project-build/src/confirmation-token.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, test, vi } from "vitest";
+import {
+ createConfirmationToken,
+ validateConfirmationToken,
+} from "./confirmation-token";
+
+describe("confirmation tokens", () => {
+ test("bind a token to its signature and expiry", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-07-16T12:00:00Z"));
+ const { token } = await createConfirmationToken("original", 1_000);
+
+ expect(await validateConfirmationToken(token, "original")).toBe(true);
+ expect(await validateConfirmationToken(token, "changed")).toBe(false);
+
+ vi.advanceTimersByTime(1_001);
+ expect(await validateConfirmationToken(token, "original")).toBe(false);
+ vi.useRealTimers();
+ });
+
+ test("treats object key order as insignificant", async () => {
+ const { token } = await createConfirmationToken(
+ { b: 2, a: [{ d: 4, c: 3 }, 1] },
+ 1_000
+ );
+ expect(
+ await validateConfirmationToken(token, {
+ a: [{ c: 3, d: 4 }, 1],
+ b: 2,
+ })
+ ).toBe(true);
+ });
+});
diff --git a/packages/project-build/src/confirmation-token.ts b/packages/project-build/src/confirmation-token.ts
new file mode 100644
index 0000000000..35f8e7414d
--- /dev/null
+++ b/packages/project-build/src/confirmation-token.ts
@@ -0,0 +1,56 @@
+const encodeDigest = (digest: ArrayBuffer) =>
+ btoa(String.fromCharCode(...new Uint8Array(digest)))
+ .replaceAll("+", "-")
+ .replaceAll("/", "_")
+ .replaceAll("=", "");
+
+const stringifyCanonicalJson = (value: unknown) =>
+ JSON.stringify(value, (_key, child: unknown) => {
+ if (child === null || Array.isArray(child) || typeof child !== "object") {
+ return child;
+ }
+ return Object.fromEntries(
+ Object.entries(child).sort(([left], [right]) => left.localeCompare(right))
+ );
+ });
+
+const getConfirmationDigest = async (payload: unknown, expiresAt: number) =>
+ encodeDigest(
+ await globalThis.crypto.subtle.digest(
+ "SHA-256",
+ new TextEncoder().encode(
+ `${expiresAt}:${stringifyCanonicalJson(payload)}`
+ )
+ )
+ );
+
+export const createConfirmationToken = async (
+ payload: unknown,
+ ttlMs: number
+) => {
+ const expiresAt = Date.now() + ttlMs;
+ const digest = await getConfirmationDigest(payload, expiresAt);
+ return { token: `${expiresAt.toString(36)}.${digest}`, expiresAt };
+};
+
+export const validateConfirmationToken = async (
+ token: string | undefined,
+ payload: unknown
+) => {
+ if (token === undefined) {
+ return false;
+ }
+ const [encodedExpiresAt, digest, ...extra] = token.split(".");
+ if (
+ encodedExpiresAt === undefined ||
+ digest === undefined ||
+ extra.length > 0
+ ) {
+ return false;
+ }
+ const expiresAt = Number.parseInt(encodedExpiresAt, 36);
+ if (Number.isSafeInteger(expiresAt) === false || expiresAt < Date.now()) {
+ return false;
+ }
+ return digest === (await getConfirmationDigest(payload, expiresAt));
+};
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index 1d35b6515f..1ddfdd8ddc 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -1787,6 +1787,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["pages"],
invalidatesNamespaces: ["pages"],
retryOnConflict: true,
+ requiresConfirm: true,
},
{
id: "redirects.setAll",
@@ -1834,6 +1835,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["pages"],
invalidatesNamespaces: ["pages"],
retryOnConflict: true,
+ requiresConfirm: true,
},
{
id: "breakpoints.list",
@@ -2071,6 +2073,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["breakpoints", "styles"],
invalidatesNamespaces: ["breakpoints", "styles"],
retryOnConflict: true,
+ requiresConfirm: true,
},
{
id: "pages.delete",
@@ -2127,6 +2130,7 @@ export const runtimeOperationContractData = [
"styleSourceSelections",
],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "pages.duplicate",
@@ -2149,6 +2153,103 @@ export const runtimeOperationContractData = [
path: {
type: "string",
},
+ substitutions: {
+ type: "object",
+ properties: {
+ text: {
+ description:
+ "Exact fixed-text replacements applied only to the duplicated page's text children, string props, title, and metadata.",
+ type: "object",
+ propertyNames: {
+ type: "string",
+ minLength: 1,
+ },
+ additionalProperties: {
+ type: "string",
+ },
+ },
+ variables: {
+ description:
+ "Copied variable values keyed by the source variable name. Ambiguous duplicate names are rejected.",
+ type: "object",
+ propertyNames: {
+ type: "string",
+ minLength: 1,
+ },
+ additionalProperties: {
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "number",
+ },
+ value: {
+ type: "number",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "string",
+ },
+ value: {
+ type: "string",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "boolean",
+ },
+ value: {
+ type: "boolean",
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "string[]",
+ },
+ value: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ },
+ required: ["type", "value"],
+ },
+ {
+ type: "object",
+ properties: {
+ type: {
+ type: "string",
+ const: "json",
+ },
+ value: {},
+ },
+ required: ["type"],
+ },
+ ],
+ },
+ },
+ },
+ required: [],
+ },
},
required: ["pageId"],
},
@@ -2892,6 +2993,7 @@ export const runtimeOperationContractData = [
],
retryOnConflict: false,
requiresAssets: true,
+ requiresConfirm: true,
},
{
id: "pageTemplates.duplicate",
@@ -3315,6 +3417,7 @@ export const runtimeOperationContractData = [
"styleSourceSelections",
],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "folders.duplicate",
@@ -57961,6 +58064,7 @@ export const runtimeOperationContractData = [
"styleSourceSelections",
],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "instances.deleteBySelector",
@@ -58037,6 +58141,7 @@ export const runtimeOperationContractData = [
],
retryOnConflict: false,
requiresAssets: true,
+ requiresConfirm: true,
},
{
id: "instances.updateProps",
@@ -58569,6 +58674,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["props"],
invalidatesNamespaces: ["props"],
retryOnConflict: true,
+ requiresConfirm: true,
},
{
id: "instances.deleteProps",
@@ -58615,6 +58721,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["props", "resources"],
invalidatesNamespaces: ["props", "resources"],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "instances.bindProps",
@@ -59138,6 +59245,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["instances"],
invalidatesNamespaces: ["instances"],
retryOnConflict: true,
+ requiresConfirm: true,
},
{
id: "instances.setTextContent",
@@ -59775,6 +59883,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["styles"],
invalidatesNamespaces: ["styles"],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "styles.updateSelectedDeclarations",
@@ -59899,6 +60008,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["styles"],
invalidatesNamespaces: ["styles"],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "styles.replaceValues",
@@ -59945,6 +60055,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["styles"],
invalidatesNamespaces: ["styles"],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "designTokens.list",
@@ -60354,6 +60465,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["styles"],
invalidatesNamespaces: ["styles"],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "designTokens.attach",
@@ -60562,6 +60674,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["styles", "styleSources", "styleSourceSelections"],
invalidatesNamespaces: ["styles", "styleSources", "styleSourceSelections"],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "styleSources.setLock",
@@ -60673,6 +60786,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["styles"],
invalidatesNamespaces: ["styles"],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "styleSources.duplicate",
@@ -64180,6 +64294,7 @@ export const runtimeOperationContractData = [
"resources",
],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "variables.deleteUnused",
@@ -64226,6 +64341,7 @@ export const runtimeOperationContractData = [
"resources",
],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "resources.list",
@@ -64943,6 +65059,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["resources"],
invalidatesNamespaces: ["resources"],
retryOnConflict: true,
+ requiresConfirm: true,
},
{
id: "resources.upsert",
@@ -65390,6 +65507,7 @@ export const runtimeOperationContractData = [
writeNamespaces: ["dataSources", "resources", "props"],
invalidatesNamespaces: ["dataSources", "resources", "props"],
retryOnConflict: false,
+ requiresConfirm: true,
},
{
id: "assets.list",
@@ -66315,6 +66433,7 @@ export const runtimeOperationContractData = [
],
retryOnConflict: false,
requiresAssets: true,
+ requiresConfirm: true,
},
{
id: "assets.delete",
@@ -66363,5 +66482,6 @@ export const runtimeOperationContractData = [
invalidatesNamespaces: ["assets"],
retryOnConflict: false,
requiresAssets: true,
+ requiresConfirm: true,
},
] as const;
diff --git a/packages/project-build/src/mcp-rendered-audit.ts b/packages/project-build/src/mcp-rendered-audit.ts
index f763319c96..227d87725d 100644
--- a/packages/project-build/src/mcp-rendered-audit.ts
+++ b/packages/project-build/src/mcp-rendered-audit.ts
@@ -16,6 +16,10 @@ import type {
ProjectSessionScreenshotInput,
ProjectSessionScreenshotResult,
} from "./mcp";
+import {
+ createConfirmationToken,
+ validateConfirmationToken,
+} from "./confirmation-token";
type Viewport = { width: number; height: number; purposes: string[] };
type RenderedAuditPlan = z.infer<typeof renderedAuditPlan>;
@@ -270,50 +274,13 @@ const getRenderedAuditPlanSignature = ({
},
});
-const getRenderedAuditConfirmationDigest = async (
- signature: string,
- expiresAt: number
-) => {
- const digest = await globalThis.crypto.subtle.digest(
- "SHA-256",
- new TextEncoder().encode(`${expiresAt}:${signature}`)
- );
- return btoa(String.fromCharCode(...new Uint8Array(digest)))
- .replaceAll("+", "-")
- .replaceAll("/", "_")
- .replaceAll("=", "");
-};
+const createRenderedAuditConfirmation = (signature: string) =>
+ createConfirmationToken(signature, renderedAuditConfirmationTtlMs);
-const createRenderedAuditConfirmation = async (signature: string) => {
- const expiresAt = Date.now() + renderedAuditConfirmationTtlMs;
- const digest = await getRenderedAuditConfirmationDigest(signature, expiresAt);
- const token = `${expiresAt.toString(36)}.${digest}`;
- return { token, expiresAt };
-};
-
-const validateRenderedAuditConfirmation = async (
+const validateRenderedAuditConfirmation = (
token: string | undefined,
signature: string
-) => {
- if (token === undefined) {
- return false;
- }
- const [encodedExpiresAt, digest, ...extra] = token.split(".");
- if (
- encodedExpiresAt === undefined ||
- digest === undefined ||
- extra.length > 0
- ) {
- return false;
- }
- const expiresAt = Number.parseInt(encodedExpiresAt, 36);
- if (Number.isSafeInteger(expiresAt) === false || expiresAt < Date.now()) {
- return false;
- }
- return (
- digest === (await getRenderedAuditConfirmationDigest(signature, expiresAt))
- );
-};
+) => validateConfirmationToken(token, signature);
export const getRenderedAuditViewports = (breakpoints: unknown): Viewport[] => {
const popularViewports = [
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index fa510ed444..8d0f23c4fd 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -68,6 +68,7 @@ const publicOperation = (
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
+ requiresConfirm: false,
outputSchema: runtimeContractById.get(operation.id)?.outputSchema,
...operationFields,
};
@@ -353,6 +354,7 @@ const publicMcpOperations: readonly PublicMcpOperation[] = [
),
writeNamespaces: ["instances"],
invalidatesNamespaces: ["instances"],
+ requiresConfirm: true,
}),
publicOperation({
command: "move-instance",
@@ -701,6 +703,14 @@ describe("project session mcp adapter", () => {
includePreview: true,
});
for (const tool of completeTools) {
+ expect(
+ tool.inputSchema.additionalProperties,
+ `MCP input schema accepts unknown root fields for ${tool.name}`
+ ).not.toBe(true);
+ expect(
+ getUnresolvedLocalSchemaRefs(tool.inputSchema),
+ `MCP input schema has unresolved local references for ${tool.name}`
+ ).toEqual([]);
if (tool.outputSchema !== undefined) {
expect(
tool.outputSchema.type,
@@ -720,6 +730,11 @@ describe("project session mcp adapter", () => {
expect(JSON.stringify(imageDescriptionsTool?.inputSchema)).toContain(
"rendered image in context"
);
+ expect(
+ JSON.stringify(
+ tools.find(({ name }) => name === "update-styles")?.inputSchema
+ )
+ ).toContain("JSON-compatible value.");
expect(
getSuccessfulOutputDataSchema(
tools.find((tool) => tool.name === "refresh")?.outputSchema
@@ -803,7 +818,13 @@ describe("project session mcp adapter", () => {
]);
expect(
Object.keys(insertFragmentTool?.inputSchema.properties ?? {})
- ).toEqual(["parentInstanceId", "fragment", "mode", "insertIndex"]);
+ ).toEqual([
+ "parentInstanceId",
+ "fragment",
+ "mode",
+ "insertIndex",
+ "dryRun",
+ ]);
const fragmentSchema = insertFragmentTool?.inputSchema.properties?.fragment;
expect(fragmentSchema).toEqual(expect.objectContaining({ type: "string" }));
const jsxDescription =
@@ -929,6 +950,51 @@ describe("project session mcp adapter", () => {
tools.find((tool) => tool.name === "delete-instance")?.annotations
.requiredInputFields
).toEqual(["instanceIds"]);
+ expect(
+ tools.find((tool) => tool.name === "delete-instance")?.inputSchema
+ .properties
+ ).toEqual(
+ expect.objectContaining({
+ dryRun: expect.objectContaining({ type: "boolean" }),
+ confirmDestructive: expect.objectContaining({ type: "boolean" }),
+ confirmationToken: expect.objectContaining({ type: "string" }),
+ })
+ );
+ });
+
+ test("defers oversized input schemas until focused discovery", async () => {
+ const description = "x".repeat(25_000);
+ const operation = publicOperation({
+ command: "large-input",
+ id: "test.largeInput",
+ description: "Accept a large structured input",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ targetId: { type: "string" },
+ payload: { type: "object", description },
+ },
+ required: ["targetId", "payload"],
+ },
+ });
+ const [tool] = listProjectSessionMcpTools([operation]);
+
+ expect(JSON.stringify(tool?.inputSchema).length).toBeLessThan(1_000);
+ expect(tool?.inputSchema.required).toEqual(["targetId", "payload"]);
+
+ const adapter = createProjectSessionMcpCore({
+ operations: [operation],
+ createProjectSession: createSessionFactory(),
+ executeOperation: createExecuteOperation(),
+ });
+ const details = await adapter.callTool({
+ name: "meta.get_more_tools",
+ input: { tools: ["large-input"] },
+ });
+ expect(JSON.stringify(details.structuredContent.data)).toContain(
+ description
+ );
});
test("exposes page expression input descriptions to MCP clients", async () => {
@@ -1082,7 +1148,7 @@ describe("project session mcp adapter", () => {
expect(tool?.inputSchema.required).toEqual(["settings"]);
expect(tool?.annotations).toMatchObject({
- inputFields: ["settings"],
+ inputFields: ["dryRun", "settings"],
requiredInputFields: ["settings"],
});
});
@@ -1835,9 +1901,8 @@ describe("project session mcp adapter", () => {
});
const result = await adapter.callTool({
- name: "list-pages",
- input: {},
- dryRun: true,
+ name: "move-instance",
+ input: { moves: [], dryRun: true },
});
expect(result.structuredContent).toMatchObject({
@@ -1852,6 +1917,97 @@ describe("project session mcp adapter", () => {
});
});
+ test("plans and confirms destructive mutations without blind retries", async () => {
+ const transaction = {
+ id: "planned-delete",
+ payload: [
+ {
+ namespace: "instances" as const,
+ patches: [{ op: "remove" as const, path: ["target"] }],
+ },
+ ],
+ };
+ const executeOperation = createExecuteOperation(async ({ dryRun }) =>
+ createEnvelope({
+ operationId: "instances.delete",
+ source: dryRun ? "dry-run" : "remote",
+ result: { deletedInstanceIds: ["target"] },
+ state: { committed: dryRun === false, freshness: {} },
+ ...(dryRun ? { transaction } : {}),
+ })
+ );
+ const adapter = createProjectSessionMcpCore({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ });
+
+ const planned = await adapter.callTool({
+ name: "delete-instance",
+ input: { instanceIds: ["target"] },
+ });
+
+ expect(planned).toMatchObject({
+ isError: true,
+ structuredContent: {
+ ok: false,
+ error: { code: "DESTRUCTIVE_CONFIRMATION_REQUIRED" },
+ meta: {
+ session: { source: "dry-run", committed: false, transaction },
+ confirmation: {
+ required: true,
+ operation: "delete-instance",
+ token: expect.any(String),
+ summary: {
+ namespaces: ["instances"],
+ changeCount: 1,
+ patchCount: 1,
+ patchOperations: { remove: 1 },
+ },
+ },
+ },
+ },
+ });
+ expect(executeOperation).toHaveBeenCalledTimes(1);
+
+ const confirmation = planned.structuredContent.meta.confirmation;
+ if (confirmation === undefined) {
+ throw new Error("Expected destructive confirmation");
+ }
+ const altered = await adapter.callTool({
+ name: "delete-instance",
+ input: {
+ instanceIds: ["other"],
+ confirmDestructive: true,
+ confirmationToken: confirmation.token,
+ },
+ });
+ expect(altered).toMatchObject({
+ structuredContent: {
+ ok: false,
+ error: { code: "DESTRUCTIVE_CONFIRMATION_INVALID" },
+ },
+ });
+ expect(executeOperation).toHaveBeenCalledTimes(2);
+
+ const committed = await adapter.callTool({
+ name: "delete-instance",
+ input: {
+ confirmationToken: confirmation.token,
+ instanceIds: ["target"],
+ confirmDestructive: true,
+ },
+ });
+
+ expect(committed).toMatchObject({
+ structuredContent: {
+ ok: true,
+ meta: { session: { committed: true } },
+ },
+ });
+ expect(executeOperation).toHaveBeenCalledTimes(4);
+ });
+
test("rejects unsupported operation input fields before execution", async () => {
const executeOperation: ExecuteOperation = vi.fn();
const adapter = createProjectSessionMcpCore({
@@ -2847,7 +3003,7 @@ describe("project session mcp adapter", () => {
expect(executeOperation).toHaveBeenCalledWith({
command: "delete-instance",
input: { instanceIds },
- dryRun: false,
+ dryRun: true,
});
});
@@ -3105,11 +3261,12 @@ describe("project session mcp adapter", () => {
name: "workflow.next",
input: { goal: "design-system-page" },
});
+ const detailsWhileCheckpointed = await adapter.callTool({
+ name: "meta.get_more_tools",
+ input: { tools: ["publish"] },
+ });
await expect(
- adapter.callTool({
- name: "meta.get_more_tools",
- input: { tools: ["publish"] },
- })
+ adapter.callTool({ name: "create-page", input: { name: "Blocked" } })
).rejects.toThrow("CHECKPOINT_REQUIRED");
const ackCheckpoint = () =>
adapter.callTool({
@@ -3275,6 +3432,9 @@ describe("project session mcp adapter", () => {
nextPhase: "page-creation",
})
);
+ expect(detailsWhileCheckpointed.structuredContent.data).toEqual(
+ expect.objectContaining({ tools: expect.any(Array) })
+ );
expect(workflowPhase.structuredContent.data).toEqual(
expect.objectContaining({
goal: "design-system-page",
@@ -3895,6 +4055,10 @@ describe("project session mcp adapter", () => {
});
const summary = await adapter.callTool({ name: "components.summary" });
+ const summaryDetails = await adapter.callTool({
+ name: "components.summary",
+ input: { detail: "components", limit: 100 },
+ });
const componentRegistry = await adapter.callTool({
name: "components.list",
input: { source: "all", limit: 200 },
@@ -3906,12 +4070,13 @@ describe("project session mcp adapter", () => {
const coveragePlan = await adapter.callTool({
name: "components.coverage-plan",
});
- await expect(
- adapter.callTool({
- name: "components.find",
- input: { brief: "radix select" },
- })
- ).rejects.toThrow("CHECKPOINT_REQUIRED");
+ const checkpointedFind = await adapter.callTool({
+ name: "components.find",
+ input: { brief: "radix select" },
+ });
+ expect(checkpointedFind.structuredContent.data).toEqual(
+ expect.objectContaining({ components: expect.any(Array) })
+ );
await expect(
adapter.callTool({
name: "checkpoint.ack",
@@ -4082,14 +4247,22 @@ describe("project session mcp adapter", () => {
expect(session.initialize).not.toHaveBeenCalled();
expect(summary.structuredContent.data).toEqual(
expect.objectContaining({
- usage: expect.stringContaining("Do not dump/parse"),
+ usage: expect.stringContaining("Default summary is compact"),
total: expect.any(Number),
- templateComponents: expect.arrayContaining([
- "@webstudio-is/sdk-components-react-radix:Select",
- ]),
- nonStandaloneComponents: expect.arrayContaining([
- "@webstudio-is/sdk-components-react-radix:SelectItemIndicator",
- ]),
+ templateCount: expect.any(Number),
+ standaloneInsertableCount: expect.any(Number),
+ nonStandaloneCount: expect.any(Number),
+ })
+ );
+ expect(summary.structuredContent.data).not.toHaveProperty("components");
+ expect(JSON.stringify(summary.structuredContent.data).length).toBeLessThan(
+ 1_000
+ );
+ expect(summaryDetails.structuredContent.data).toEqual(
+ expect.objectContaining({
+ detail: "components",
+ count: expect.any(Number),
+ pagination: { offset: 0, limit: 100, nextOffset: undefined },
components: expect.arrayContaining([
expect.objectContaining({
component: "@webstudio-is/sdk-components-react-radix:Select",
@@ -4115,14 +4288,13 @@ describe("project session mcp adapter", () => {
);
expect(componentRegistry.structuredContent.data).toEqual(
expect.objectContaining({
- usage: expect.stringContaining("shadcn-compatible"),
+ usage: expect.stringContaining("compact metadata"),
source: "all",
documentType: "html",
items: expect.arrayContaining([
expect.objectContaining({
name: "component:HtmlEmbed",
type: "registry:ui",
- files: [],
meta: expect.objectContaining({
source: "meta",
component: "HtmlEmbed",
@@ -4135,13 +4307,6 @@ describe("project session mcp adapter", () => {
expect.objectContaining({
name: "template:@webstudio-is/sdk-components-react-radix:Select",
type: "registry:ui",
- files: [
- expect.objectContaining({
- type: "registry:file",
- target:
- "webstudio/components/%40webstudio-is%2Fsdk-components-react-radix%3ASelect.template.json",
- }),
- ],
meta: expect.objectContaining({
source: "template",
component: "@webstudio-is/sdk-components-react-radix:Select",
@@ -4154,6 +4319,9 @@ describe("project session mcp adapter", () => {
]),
})
);
+ expect(
+ JSON.stringify(componentRegistry.structuredContent.data)
+ ).not.toContain('"files"');
expect(templateRegistry.structuredContent.data).toEqual(
expect.objectContaining({
source: "template",
@@ -4171,6 +4339,9 @@ describe("project session mcp adapter", () => {
]),
})
);
+ expect(
+ JSON.stringify(templateRegistry.structuredContent.data).length
+ ).toBeLessThan(50_000);
expect(coveragePlan.structuredContent.data).toEqual(
expect.objectContaining({
usage: expect.stringContaining("intentionally compact"),
@@ -4592,7 +4763,10 @@ describe("project session mcp adapter", () => {
createProjectSession: createSessionFactory(),
executeOperation: createExecuteOperation(),
});
- const summary = await adapter.callTool({ name: "components.summary" });
+ const summary = await adapter.callTool({
+ name: "components.summary",
+ input: { detail: "components", limit: 100 },
+ });
const find = await adapter.callTool({
name: "components.find",
input: { brief: "ConcealedWidget" },
@@ -4819,10 +4993,17 @@ describe("project session mcp adapter", () => {
}),
})
);
+ const find = await adapter.callTool({
+ name: "components.find",
+ input: { brief: "button" },
+ });
+ expect(find.structuredContent.data).toEqual(
+ expect.objectContaining({ components: expect.any(Array) })
+ );
await expect(
adapter.callTool({
- name: "components.find",
- input: { brief: "button" },
+ name: "components.coverage-insert-next",
+ input: { pagePath: "/design-system", parentInstanceId: "root" },
})
).rejects.toThrow("CHECKPOINT_REQUIRED");
});
@@ -6104,7 +6285,7 @@ describe("project session mcp adapter", () => {
name: "publish",
annotations: expect.objectContaining({
readOnlyHint: false,
- destructiveHint: true,
+ destructiveHint: false,
openWorldHint: true,
}),
}),
@@ -6131,6 +6312,13 @@ describe("project session mcp adapter", () => {
}),
expect.objectContaining({
name: "reset-session",
+ annotations: expect.objectContaining({
+ readOnlyHint: false,
+ destructiveHint: false,
+ }),
+ }),
+ expect.objectContaining({
+ name: "delete-instance",
annotations: expect.objectContaining({
readOnlyHint: false,
destructiveHint: true,
@@ -6158,6 +6346,99 @@ describe("project session mcp adapter", () => {
}
});
+ test("exposes dry-run and destructive confirmation through stdio MCP", async () => {
+ const transaction = {
+ id: "stdio-delete-plan",
+ payload: [
+ {
+ namespace: "instances" as const,
+ patches: [{ op: "remove" as const, path: ["target"] }],
+ },
+ ],
+ };
+ const executeOperation = createExecuteOperation(async ({ dryRun }) =>
+ createEnvelope({
+ operationId: "instances.delete",
+ source: dryRun ? "dry-run" : "remote",
+ result: { deletedInstanceIds: ["target"] },
+ state: { committed: dryRun === false, freshness: {} },
+ ...(dryRun ? { transaction } : {}),
+ })
+ );
+ const server = await createProjectSessionMcpServer({
+ operations: publicMcpOperations,
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ });
+ const { client, close } = await createConnectedClient(server);
+
+ try {
+ const tools = await client.listTools();
+ const deleteTool = tools.tools.find(
+ ({ name }) => name === "delete-instance"
+ );
+ expect(deleteTool).toMatchObject({
+ inputSchema: {
+ properties: expect.objectContaining({
+ dryRun: expect.objectContaining({ type: "boolean" }),
+ confirmDestructive: expect.objectContaining({ type: "boolean" }),
+ confirmationToken: expect.objectContaining({ type: "string" }),
+ }),
+ },
+ annotations: expect.objectContaining({ destructiveHint: true }),
+ });
+ expect(
+ tools.tools.find(({ name }) => name === "move-instance")
+ ).toMatchObject({
+ inputSchema: {
+ properties: expect.objectContaining({
+ dryRun: expect.objectContaining({ type: "boolean" }),
+ }),
+ },
+ annotations: expect.objectContaining({ destructiveHint: false }),
+ });
+ expect(
+ tools.tools.find(({ name }) => name === "publish")?.inputSchema
+ .properties
+ ).not.toHaveProperty("dryRun");
+
+ const planned = await client.callTool({
+ name: "delete-instance",
+ arguments: { instanceIds: ["target"] },
+ });
+ const plannedContent = planned.structuredContent as
+ | {
+ ok: boolean;
+ error?: { code: string };
+ meta: { confirmation?: { token: string } };
+ }
+ | undefined;
+ expect(plannedContent).toMatchObject({
+ ok: false,
+ error: { code: "DESTRUCTIVE_CONFIRMATION_REQUIRED" },
+ });
+ const confirmation = plannedContent?.meta.confirmation;
+ if (confirmation === undefined) {
+ throw new Error("Expected stdio destructive confirmation");
+ }
+
+ const committed = await client.callTool({
+ name: "delete-instance",
+ arguments: {
+ instanceIds: ["target"],
+ confirmDestructive: true,
+ confirmationToken: confirmation.token,
+ },
+ });
+ expect(committed.structuredContent).toMatchObject({
+ ok: true,
+ meta: { session: { committed: true } },
+ });
+ } finally {
+ await close();
+ }
+ });
+
test("keeps one MCP SDK connection healthy across repeated reads and mutations", async () => {
const executeOperation = createExecuteOperation(async ({ command }) =>
createEnvelope({
@@ -6782,7 +7063,7 @@ describe("project session mcp adapter", () => {
}
});
- test("blocks long-lived MCP tool chains until required checkpoint is acknowledged", async () => {
+ test("allows reads but blocks mutations until a required checkpoint is acknowledged", async () => {
const server = await createProjectSessionMcpServer({
operations: publicMcpOperations,
createProjectSession: createSessionFactory(),
@@ -6812,17 +7093,26 @@ describe("project session mcp adapter", () => {
name: "components.find",
arguments: { brief: "button" },
})
+ ).resolves.toEqual(
+ expect.objectContaining({
+ structuredContent: expect.objectContaining({ ok: true }),
+ })
+ );
+ await expect(
+ client.callTool({
+ name: "create-page",
+ arguments: { name: "Blocked", path: "/blocked" },
+ })
).resolves.toEqual(
expect.objectContaining({
isError: true,
- structuredContent: {
+ structuredContent: expect.objectContaining({
ok: false,
- error: {
+ error: expect.objectContaining({
message: expect.stringContaining("CHECKPOINT_REQUIRED"),
code: "CHECKPOINT_REQUIRED",
- },
- meta: {},
- },
+ }),
+ }),
})
);
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 31d681422e..1408e5722c 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -11,6 +11,7 @@ import {
parseComponentName,
toInputJsonSchemaObject,
type InputJsonSchema,
+ type InputJsonSchemaValue,
} from "@webstudio-is/sdk";
import type { BuilderApiCapability } from "./contracts/permissions";
import path from "node:path";
@@ -75,6 +76,10 @@ import {
type SemanticValidationIssue,
} from "./runtime/errors";
import { z } from "zod";
+import {
+ createConfirmationToken,
+ validateConfirmationToken,
+} from "./confirmation-token";
type PublicMcpOperationMethod = "query" | "mutation";
type PublicMcpOperationPermit = BuilderApiCapability;
@@ -95,6 +100,7 @@ export type PublicMcpOperation<Command extends string = string> = {
writeNamespaces: readonly string[];
invalidatesNamespaces: readonly string[];
retryOnConflict: boolean;
+ requiresConfirm: boolean;
};
type ProjectSessionLike = {
@@ -330,7 +336,7 @@ const emptyInputSchema = {
type: "object",
description:
"Pass this MCP tool's JSON arguments. Use meta.get_more_tools for examples and required fields. For authored content with styles, prefer insert-fragment so the CLI converts JSX into Webstudio data.",
- additionalProperties: true,
+ additionalProperties: false,
} as const satisfies ProjectSessionMcpInputSchema;
const textInputSchema = (description: string) =>
@@ -422,6 +428,29 @@ const registryListInputSchema = {
required: [],
} as const satisfies ProjectSessionMcpInputSchema;
+const componentSummaryInputSchema = {
+ ...emptyInputSchema,
+ additionalProperties: false,
+ properties: {
+ detail: {
+ type: "string",
+ enum: ["summary", "components"],
+ description:
+ 'Response detail. Defaults to "summary"; use "components" for paginated component entries.',
+ },
+ limit: {
+ type: "number",
+ description:
+ "Maximum component entries to return with detail components. Defaults to 20 and is capped at 100.",
+ },
+ offset: {
+ type: "number",
+ description: "Zero-based component pagination offset.",
+ },
+ },
+ required: [],
+} as const satisfies ProjectSessionMcpInputSchema;
+
const templateInputSchema = {
...emptyInputSchema,
additionalProperties: false,
@@ -591,6 +620,125 @@ const getOperationInputSchema = (
};
};
+const jsonCompatibleValueSchema = {
+ anyOf: [
+ { type: "string" },
+ { type: "number" },
+ { type: "boolean" },
+ { type: "null" },
+ { type: "array" },
+ { type: "object" },
+ ],
+ description: "JSON-compatible value.",
+} as const satisfies InputJsonSchema;
+
+const constrainUnconstrainedInputSchemaValue = (
+ value: InputJsonSchemaValue
+): InputJsonSchemaValue => {
+ if (typeof value === "boolean") {
+ return value;
+ }
+ if (Object.keys(value).length === 0) {
+ return jsonCompatibleValueSchema;
+ }
+ return constrainUnconstrainedInputSchemas(value);
+};
+
+const constrainUnconstrainedInputSchemas = <Schema extends InputJsonSchema>(
+ schema: Schema
+): Schema => {
+ const result: InputJsonSchema = { ...schema };
+ if (schema.properties !== undefined) {
+ result.properties = Object.fromEntries(
+ Object.entries(schema.properties).map(([name, value]) => [
+ name,
+ constrainUnconstrainedInputSchemaValue(value),
+ ])
+ );
+ }
+ if (schema.additionalProperties !== undefined) {
+ result.additionalProperties = constrainUnconstrainedInputSchemaValue(
+ schema.additionalProperties
+ );
+ }
+ if (schema.items !== undefined) {
+ result.items = constrainUnconstrainedInputSchemaValue(schema.items);
+ }
+ for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"] as const) {
+ const values = schema[key];
+ if (Array.isArray(values)) {
+ result[key] = values.map(constrainUnconstrainedInputSchemaValue);
+ }
+ }
+ if (schema.$defs !== undefined) {
+ result.$defs = Object.fromEntries(
+ Object.entries(schema.$defs).map(([name, value]) => [
+ name,
+ constrainUnconstrainedInputSchemaValue(value),
+ ])
+ );
+ }
+ return result as Schema;
+};
+
+const maxInlineMcpInputSchemaSize = 20_000;
+
+const getCompactSchemaProperty = (schema: InputJsonSchema): InputJsonSchema => {
+ const description =
+ schema.description === undefined
+ ? undefined
+ : schema.description.length <= 240
+ ? schema.description
+ : `${schema.description.slice(0, 239)}…`;
+ const compact = {
+ ...(schema.type === undefined ? {} : { type: schema.type }),
+ ...(description === undefined ? {} : { description }),
+ ...(schema.enum === undefined ? {} : { enum: schema.enum }),
+ };
+ if (Object.keys(compact).length > 0) {
+ return compact;
+ }
+ return {
+ description:
+ "Complex structured value. Use meta.get_more_tools with this exact tool name for its complete schema.",
+ };
+};
+
+const getHandshakeInputSchema = (
+ schema: ProjectSessionMcpInputSchema
+): {
+ inputSchema: ProjectSessionMcpInputSchema;
+ detailedInputSchema?: ProjectSessionMcpInputSchema;
+} => {
+ if (JSON.stringify(schema).length <= maxInlineMcpInputSchemaSize) {
+ return { inputSchema: schema };
+ }
+ return {
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: Object.fromEntries(
+ Object.entries(schema.properties ?? {}).map(([name, property]) => {
+ const propertySchema = toInputJsonSchemaObject(property);
+ const serializedProperty = JSON.stringify(property);
+ return [
+ name,
+ propertySchema === undefined ||
+ (serializedProperty.length <= maxInlineMcpInputSchemaSize &&
+ serializedProperty.includes('"$ref"') === false)
+ ? property
+ : getCompactSchemaProperty(propertySchema),
+ ];
+ })
+ ),
+ required: schema.required,
+ description:
+ "Compact handshake schema. Use meta.get_more_tools with this exact tool name for the complete input schema.",
+ },
+ detailedInputSchema: schema,
+ };
+};
+
const insertCollectionMcpInputSchema = getOperationInputSchema({
inputSchema: getInputSchemaMetadata(insertCollectionMcpInput).inputJsonSchema,
});
@@ -1055,21 +1203,62 @@ const renderedAuditConfirmationInputProperties = {
},
} as const;
+const dryRunInputProperty = {
+ type: "boolean",
+ description:
+ "Plan this local-capable mutation without committing it. Returns the planned transaction in meta.session.transaction.",
+} as const;
+
+const destructiveConfirmationInputProperties = {
+ confirmDestructive: {
+ type: "boolean",
+ description:
+ "Commit the unchanged destructive plan. Requires the short-lived confirmationToken returned by the previous planned call.",
+ },
+ confirmationToken: {
+ type: "string",
+ description:
+ "Short-lived token returned with the unchanged destructive mutation plan.",
+ },
+} as const;
+
const getMcpOperationInputSchema = (
operation: PublicMcpOperation,
- options: { includeRenderedAudit: boolean }
+ options: {
+ includeRenderedAudit: boolean;
+ schema?: ProjectSessionMcpInputSchema;
+ }
) => {
- const schema = getOperationInputSchema(operation);
- if (operation.command !== "audit" || options.includeRenderedAudit === false) {
+ let schema = constrainUnconstrainedInputSchemas(
+ options.schema ?? getOperationInputSchema(operation)
+ );
+ const properties = getInputJsonSchemaProperties(schema);
+ if (
+ schema.additionalProperties === true &&
+ (properties === undefined || Object.keys(properties).length === 0)
+ ) {
+ schema = { ...schema, additionalProperties: false };
+ }
+ const transportProperties = {
+ ...(operation.method === "mutation" && operation.localCapable
+ ? { dryRun: dryRunInputProperty }
+ : {}),
+ ...(operation.requiresConfirm && operation.localCapable
+ ? destructiveConfirmationInputProperties
+ : {}),
+ ...(operation.command === "audit" && options.includeRenderedAudit
+ ? {
+ rendered: renderedAuditInputProperty,
+ ...renderedAuditConfirmationInputProperties,
+ }
+ : {}),
+ };
+ if (Object.keys(transportProperties).length === 0) {
return schema;
}
return {
...schema,
- properties: {
- ...schema.properties,
- rendered: renderedAuditInputProperty,
- ...renderedAuditConfirmationInputProperties,
- },
+ properties: { ...schema.properties, ...transportProperties },
} satisfies InputJsonSchema;
};
@@ -1247,14 +1436,15 @@ export type ProjectSessionMcpTool = {
writeNamespaces: readonly string[];
invalidatesNamespaces: readonly string[];
retryOnConflict: boolean;
+ requiresConfirm: boolean;
};
};
type ProjectSessionMcpToolInput = Omit<ProjectSessionMcpTool, "annotations"> & {
annotations: Omit<
ProjectSessionMcpTool["annotations"],
- "inputFields" | "requiredInputFields"
- >;
+ "inputFields" | "requiredInputFields" | "requiresConfirm"
+ > & { requiresConfirm?: boolean };
};
const createProjectSessionMcpTool = (
@@ -1269,6 +1459,7 @@ const createProjectSessionMcpTool = (
...tool.annotations,
inputFields,
requiredInputFields,
+ requiresConfirm: tool.annotations.requiresConfirm ?? false,
},
};
};
@@ -1854,8 +2045,8 @@ const sessionTools: readonly ProjectSessionMcpTool[] = [
createProjectSessionMcpTool({
name: "components.summary",
description:
- "Return a compact structured component catalog summary. Use this before full component resources.",
- inputSchema: emptyInputSchema,
+ 'Return component counts by default, or paginated component entries with detail:"components".',
+ inputSchema: componentSummaryInputSchema,
annotations: {
command: "components.summary",
operationId: "components.summary",
@@ -1872,7 +2063,7 @@ const sessionTools: readonly ProjectSessionMcpTool[] = [
createProjectSessionMcpTool({
name: "components.list",
description:
- "Return shadcn-compatible Webstudio registry items for insertable components and templates. Use this when you need the shared Builder/MCP component list shape.",
+ "List compact metadata for insertable components and templates. Use components.get or templates.get for one complete item.",
inputSchema: registryListInputSchema,
annotations: {
command: "components.list",
@@ -2042,7 +2233,7 @@ const sessionTools: readonly ProjectSessionMcpTool[] = [
createProjectSessionMcpTool({
name: "templates.list",
description:
- "Return shadcn-compatible Webstudio registry items for registered templates only, including explicit registry:file payload metadata.",
+ "List compact metadata for registered templates. Use templates.get for one complete insertion payload.",
inputSchema: registryListInputSchema,
annotations: {
command: "templates.list",
@@ -2292,24 +2483,29 @@ type McpStructuredError = {
issues?: readonly SemanticValidationIssue[];
};
-type ProjectSessionMcpStructuredContent =
- | {
- ok: true;
- data: unknown;
- meta: {
- session?: ReturnType<typeof serializeProjectSessionMeta>;
- next?: string[];
- };
- }
- | {
- ok: false;
- data: unknown;
- error: McpStructuredError;
- meta: {
- session?: ReturnType<typeof serializeProjectSessionMeta>;
- next?: string[];
- };
- };
+type DestructiveConfirmation = {
+ required: true;
+ operation: string;
+ token: string;
+ expiresAt: string;
+ summary: {
+ namespaces: string[];
+ changeCount: number;
+ patchCount: number;
+ patchOperations: Record<string, number>;
+ };
+};
+
+type ProjectSessionMcpMeta = {
+ session?: ReturnType<typeof serializeProjectSessionMeta>;
+ next?: string[];
+ confirmation?: DestructiveConfirmation;
+};
+
+type ProjectSessionMcpStructuredContent = {
+ data: unknown;
+ meta: ProjectSessionMcpMeta;
+} & ({ ok: true } | { ok: false; error: McpStructuredError });
class ProjectSessionMcpCheckpointError extends Error {
code = "CHECKPOINT_REQUIRED";
@@ -2354,6 +2550,15 @@ export const hiddenMcpOperationCommands = new Set<string>([
"copy-page",
]);
+const detailedMcpInputSchemas = new WeakMap<
+ ProjectSessionMcpTool,
+ ProjectSessionMcpInputSchema
+>();
+
+export const getDetailedProjectSessionMcpInputSchema = (
+ tool: ProjectSessionMcpTool
+) => detailedMcpInputSchemas.get(tool) ?? tool.inputSchema;
+
export const listProjectSessionMcpTools = (
operations: readonly PublicMcpOperation[],
options: {
@@ -2370,16 +2575,18 @@ export const listProjectSessionMcpTools = (
)
.map((operation) => {
const override = mcpOperationOverrides.get(operation.command);
- return createProjectSessionMcpTool({
+ const { inputSchema, detailedInputSchema } = getHandshakeInputSchema(
+ getMcpOperationInputSchema(operation, {
+ includeRenderedAudit:
+ options.includeScreenshot === true &&
+ options.includePreview === true,
+ schema: override?.inputSchema,
+ })
+ );
+ const tool = createProjectSessionMcpTool({
name: operation.command,
description: override?.description ?? operation.description,
- inputSchema:
- override?.inputSchema ??
- getMcpOperationInputSchema(operation, {
- includeRenderedAudit:
- options.includeScreenshot === true &&
- options.includePreview === true,
- }),
+ inputSchema,
...(operation.outputSchema === undefined
? {}
: { outputSchema: getMcpOutputSchema(operation.outputSchema) }),
@@ -2395,8 +2602,13 @@ export const listProjectSessionMcpTools = (
writeNamespaces: operation.writeNamespaces,
invalidatesNamespaces: operation.invalidatesNamespaces,
retryOnConflict: operation.retryOnConflict,
+ requiresConfirm: operation.requiresConfirm,
},
});
+ if (detailedInputSchema !== undefined) {
+ detailedMcpInputSchemas.set(tool, detailedInputSchema);
+ }
+ return tool;
}),
...sessionTools.map((tool) => ({
...tool,
@@ -2697,17 +2909,12 @@ const getRegistryListInput = (
`${toolName} input.documentType must be one of html, xml, text.`
);
}
- const limit = Math.min(
- 100,
- Math.max(
- 1,
- Math.floor(getOptionalNumberInput(input, "limit", toolName) ?? 50)
- )
- );
- const offset = Math.max(
- 0,
- Math.floor(getOptionalNumberInput(input, "offset", toolName) ?? 0)
- );
+ const { limit, offset } = getOffsetPaginationInput({
+ input,
+ toolName,
+ defaultLimit: 50,
+ maxLimit: 100,
+ });
return {
source: source as RegistryListSource,
documentType: documentType as CoveragePlanDocumentType,
@@ -2823,6 +3030,32 @@ const getOptionalNumberInput = (
return value;
};
+const getOffsetPaginationInput = ({
+ input,
+ toolName,
+ defaultLimit,
+ maxLimit,
+}: {
+ input: unknown;
+ toolName: string;
+ defaultLimit: number;
+ maxLimit: number;
+}) => ({
+ offset: Math.max(
+ 0,
+ Math.floor(getOptionalNumberInput(input, "offset", toolName) ?? 0)
+ ),
+ limit: Math.min(
+ maxLimit,
+ Math.max(
+ 1,
+ Math.floor(
+ getOptionalNumberInput(input, "limit", toolName) ?? defaultLimit
+ )
+ )
+ ),
+});
+
const getCoveragePlanInput = (input: unknown) => {
const detail =
getOptionalStringInput(input, "detail", "components.coverage-plan") ||
@@ -2846,21 +3079,12 @@ const getCoveragePlanInput = (input: unknown) => {
`components.coverage-plan input.documentType must be one of ${coveragePlanDocumentTypes.join(", ")}.`
);
}
- const offset = Math.max(
- 0,
- Math.floor(
- getOptionalNumberInput(input, "offset", "components.coverage-plan") ?? 0
- )
- );
- const limit = Math.min(
- 100,
- Math.max(
- 1,
- Math.floor(
- getOptionalNumberInput(input, "limit", "components.coverage-plan") ?? 20
- )
- )
- );
+ const { offset, limit } = getOffsetPaginationInput({
+ input,
+ toolName: "components.coverage-plan",
+ defaultLimit: 20,
+ maxLimit: 100,
+ });
return {
detail: detail as CoveragePlanDetail,
namespace: getOptionalStringInput(
@@ -3293,6 +3517,7 @@ const filterCapabilities = (tools: readonly ProjectSessionMcpTool[]) => {
const startupGuidance = [
"For any multi-step authoring task, first call meta.guide with the user's objective and follow its complete workflow, including final audit, preview, and screenshot steps.",
"Mutation responses can include meta.next. Treat those steps as required before reporting completion.",
+ "Every local-capable mutation exposes dryRun. Destructive delete, replace, and replace-all calls plan first; review the transaction, ask the user to confirm, then retry the unchanged call with confirmDestructive: true and meta.confirmation.token. Never retry blindly because changed input, version, or plan invalidates the short-lived token.",
readProjectBuildDoc("mcp-startup-guidance").trim(),
].join("\n\n");
const formatExpressionMethods = (methods: ReadonlySet<string>) =>
@@ -3558,7 +3783,7 @@ type ComponentSummaryEntry = NonNullable<
ReturnType<typeof getComponentSummaryEntry>
>;
-const getComponentSummary = () => {
+const getComponentCatalogSummary = () => {
const templates = getComponentTemplates();
const entries = [...componentMetas.keys()]
.flatMap((component) => {
@@ -3588,6 +3813,51 @@ const getComponentSummary = () => {
};
};
+const getComponentSummary = (input: unknown) => {
+ const detail =
+ getOptionalStringInput(input, "detail", "components.summary") || "summary";
+ if (detail !== "summary" && detail !== "components") {
+ throw new Error(
+ "components.summary input.detail must be summary or components."
+ );
+ }
+ const summary = getComponentCatalogSummary();
+ const base = {
+ usage:
+ 'Default summary is compact. Use detail:"components" with offset and limit for component entries, or components.search/components.get for focused discovery.',
+ total: summary.total,
+ namespaceCounts: summary.namespaceCounts,
+ templateCount: summary.templateComponents.length,
+ standaloneInsertableCount: summary.standaloneInsertable.length,
+ nonStandaloneCount: summary.nonStandaloneComponents.length,
+ };
+ if (detail === "summary") {
+ return base;
+ }
+ const { offset, limit } = getOffsetPaginationInput({
+ input,
+ toolName: "components.summary",
+ defaultLimit: 20,
+ maxLimit: 100,
+ });
+ const components = summary.components.slice(offset, offset + limit);
+ return {
+ ...base,
+ detail,
+ count: components.length,
+ omittedCount: Math.max(0, summary.total - offset - components.length),
+ pagination: {
+ offset,
+ limit,
+ nextOffset:
+ offset + components.length < summary.total
+ ? offset + components.length
+ : undefined,
+ },
+ components,
+ };
+};
+
const getComponentRegistryItems = () =>
listComponentRegistryItems({
metas: componentMetas,
@@ -3609,6 +3879,21 @@ const filterRegistryItemsBySource = (
);
};
+const toRegistryItemSummary = (item: ComponentRegistryItem) => ({
+ name: item.name,
+ title: item.title,
+ description: item.description,
+ type: item.type,
+ meta: {
+ catalogId: item.meta.catalogId,
+ source: item.meta.source,
+ component: item.meta.component,
+ category: item.meta.category,
+ label: item.meta.label,
+ insert: item.meta.insert,
+ },
+});
+
const listRegistryItems = ({
input,
toolName,
@@ -3636,7 +3921,7 @@ const listRegistryItems = ({
const items = allItems.slice(offset, offset + limit);
return {
usage:
- "Registry items use the shadcn-compatible shape plus Webstudio insertion metadata in meta. Use meta.insert.component with insert-component for automatic templates, or use insert-fragment for authored/styled JSX sections.",
+ "Registry lists return compact metadata. Use components.get or templates.get for one complete item before insertion.",
source,
documentType,
count: items.length,
@@ -3647,7 +3932,7 @@ const listRegistryItems = ({
limit,
nextOffset: offset + limit < allItems.length ? offset + limit : undefined,
},
- items,
+ items: items.map(toRegistryItemSummary),
};
};
@@ -3683,7 +3968,7 @@ const getTemplateDetails = (input: unknown) => {
const getComponentCoveragePlan = async (input: unknown) => {
const { detail, namespace, documentType, offset, limit } =
getCoveragePlanInput(input);
- const summary = getComponentSummary();
+ const summary = getComponentCatalogSummary();
const documentEntries = summary.components.filter((entry) =>
isComponentAvailableForDocumentType({
component: entry.component,
@@ -3890,7 +4175,7 @@ const getAvailableComponentEntries = async ({
}: {
documentType: CoveragePlanDocumentType;
}) => {
- const summary = getComponentSummary();
+ const summary = getComponentCatalogSummary();
return summary.components.filter((entry) =>
isComponentAvailableForDocumentType({
component: entry.component,
@@ -4132,17 +4417,12 @@ const getComponentFindInput = (
input: unknown,
toolName: "components.find" | "components.search"
) => {
- const limit = Math.min(
- 25,
- Math.max(
- 1,
- Math.floor(getOptionalNumberInput(input, "limit", toolName) ?? 12)
- )
- );
- const offset = Math.max(
- 0,
- Math.floor(getOptionalNumberInput(input, "offset", toolName) ?? 0)
- );
+ const { limit, offset } = getOffsetPaginationInput({
+ input,
+ toolName,
+ defaultLimit: 12,
+ maxLimit: 25,
+ });
return {
brief: getRequiredStringInput(input, "brief", toolName),
limit,
@@ -4169,7 +4449,7 @@ const findComponents = async (
toolName: "components.find" | "components.search" = "components.find"
) => {
const { brief, limit, offset } = getComponentFindInput(input, toolName);
- const summary = getComponentSummary();
+ const summary = getComponentCatalogSummary();
const normalizedBrief = normalize(brief);
const tokens = normalizedBrief
.split(/\s+/)
@@ -4718,7 +4998,7 @@ const getExactTools = (
const serializeToolDetails = (tool: ProjectSessionMcpTool) => ({
name: tool.name,
description: tool.description,
- inputSchema: tool.inputSchema,
+ inputSchema: getDetailedProjectSessionMcpInputSchema(tool),
inputFields: tool.annotations.inputFields,
requiredInputFields: tool.annotations.requiredInputFields,
mcpExamples: tool.mcpExamples ?? [],
@@ -4819,7 +5099,6 @@ const readOnlySessionTools = new Set([
"meta.index",
"meta.guide",
"meta.get_more_tools",
- "workflow.next",
"status",
"components.summary",
"components.list",
@@ -4839,14 +5118,21 @@ const toolAliases = new Map([
const resolveToolName = (name: string) => toolAliases.get(name) ?? name;
-const isReadOnlyTool = (tool: ProjectSessionMcpTool) =>
+export const isReadOnlyProjectSessionMcpTool = (tool: ProjectSessionMcpTool) =>
tool.annotations.method === "query" ||
(tool.annotations.method === "session" &&
readOnlySessionTools.has(tool.name));
-const isDestructiveTool = (tool: ProjectSessionMcpTool) =>
- tool.annotations.method === "mutation" ||
- tool.annotations.invalidatesNamespaces.length > 0;
+export const isReadOnlyProjectSessionMcpToolCall = (
+ name: string,
+ tools: readonly ProjectSessionMcpTool[]
+) => {
+ const resolvedName = resolveToolName(name);
+ return tools.some(
+ (tool) =>
+ tool.name === resolvedName && isReadOnlyProjectSessionMcpTool(tool)
+ );
+};
const toSdkTool = (tool: ProjectSessionMcpTool): SdkTool => ({
name: tool.name,
@@ -4856,8 +5142,8 @@ const toSdkTool = (tool: ProjectSessionMcpTool): SdkTool => ({
? {}
: { outputSchema: tool.outputSchema }),
annotations: {
- readOnlyHint: isReadOnlyTool(tool),
- destructiveHint: isDestructiveTool(tool),
+ readOnlyHint: isReadOnlyProjectSessionMcpTool(tool),
+ destructiveHint: tool.annotations.requiresConfirm,
openWorldHint: tool.annotations.serverOnly,
},
_meta: {
@@ -4925,12 +5211,32 @@ export const listProjectSessionMcpResources =
},
];
+const destructiveConfirmationTtlMs = 5 * 60 * 1000;
+
+const getDestructivePlanSummary = (
+ envelope: ProjectSessionEnvelope
+): DestructiveConfirmation["summary"] => {
+ const changes = envelope.transaction?.payload ?? [];
+ const patches = changes.flatMap(({ patches }) => patches);
+ const patchOperations: Record<string, number> = {};
+ for (const patch of patches) {
+ patchOperations[patch.op] = (patchOperations[patch.op] ?? 0) + 1;
+ }
+ return {
+ namespaces: [...new Set(changes.map(({ namespace }) => namespace))],
+ changeCount: changes.length,
+ patchCount: patches.length,
+ patchOperations,
+ };
+};
+
const toCallResult = (
envelope: Parameters<typeof serializeProjectSessionMeta>[0],
options: {
verboseSession?: boolean;
error?: { code: string; message: string };
next?: string[];
+ confirmation?: DestructiveConfirmation;
} = {}
): ProjectSessionMcpToolResult => {
const meta = {
@@ -4938,6 +5244,9 @@ const toCallResult = (
verbose: options.verboseSession,
}),
...(options.next === undefined ? {} : { next: options.next }),
+ ...(options.confirmation === undefined
+ ? {}
+ : { confirmation: options.confirmation }),
};
const structuredContent: ProjectSessionMcpStructuredContent =
options.error === undefined
@@ -4964,6 +5273,85 @@ const toCallResult = (
};
};
+const executeDestructiveMcpOperation = async <Command extends string>({
+ command,
+ input,
+ dryRun,
+ confirmDestructive,
+ confirmationToken,
+ executeOperation,
+}: {
+ command: Command;
+ input: unknown;
+ dryRun: boolean;
+ confirmDestructive: boolean;
+ confirmationToken?: string;
+ executeOperation: ExecuteMcpOperation<Command>;
+}): Promise<[ProjectSessionEnvelope, ProjectSessionMcpToolResult?]> => {
+ const plannedEnvelope = await executeOperation({
+ command,
+ input,
+ dryRun: true,
+ });
+ if (plannedEnvelope.transaction === undefined) {
+ return [plannedEnvelope, toCallResult(plannedEnvelope)];
+ }
+ const confirmationPayload = {
+ operation: command,
+ input,
+ projectId: plannedEnvelope.projectId,
+ buildId: plannedEnvelope.buildId,
+ version: plannedEnvelope.version,
+ payload: plannedEnvelope.transaction.payload,
+ };
+ const confirmation = async (): Promise<DestructiveConfirmation> => {
+ const { token, expiresAt } = await createConfirmationToken(
+ confirmationPayload,
+ destructiveConfirmationTtlMs
+ );
+ return {
+ required: true,
+ operation: command,
+ token,
+ expiresAt: new Date(expiresAt).toISOString(),
+ summary: getDestructivePlanSummary(plannedEnvelope),
+ };
+ };
+ if (dryRun) {
+ return [
+ plannedEnvelope,
+ toCallResult(plannedEnvelope, {
+ confirmation: await confirmation(),
+ next: [
+ "Review the planned result and transaction. To commit the unchanged destructive operation, retry with confirmDestructive: true and this confirmationToken before it expires.",
+ ],
+ }),
+ ];
+ }
+ const isConfirmed =
+ confirmDestructive &&
+ (await validateConfirmationToken(confirmationToken, confirmationPayload));
+ if (isConfirmed === false) {
+ return [
+ plannedEnvelope,
+ toCallResult(plannedEnvelope, {
+ error: {
+ code: confirmDestructive
+ ? "DESTRUCTIVE_CONFIRMATION_INVALID"
+ : "DESTRUCTIVE_CONFIRMATION_REQUIRED",
+ message:
+ "Review the planned destructive mutation, then retry the unchanged call with confirmDestructive: true and the returned confirmationToken before it expires.",
+ },
+ confirmation: await confirmation(),
+ next: [
+ "Do not retry blindly. Review meta.session.transaction and meta.confirmation.summary, ask the user to confirm, then retry the unchanged operation with confirmDestructive: true and meta.confirmation.token.",
+ ],
+ }),
+ ];
+ }
+ return [await executeOperation({ command, input, dryRun: false })];
+};
+
const getRenderedAuditError = (
envelope: Parameters<typeof serializeProjectSessionMeta>[0],
rendered: boolean
@@ -5616,7 +6004,10 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
nextCommand,
});
}
- if (pendingCheckpoint !== undefined) {
+ if (
+ pendingCheckpoint !== undefined &&
+ isReadOnlyProjectSessionMcpToolCall(name, listTools()) === false
+ ) {
throw new ProjectSessionMcpCheckpointError(
`CHECKPOINT_REQUIRED: ${pendingCheckpoint.message} Stop now and report the checkpoint to the parent/user. Only after the parent/user continues, call checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"} before calling "${name}".`
);
@@ -5650,7 +6041,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
);
}
if (name === "components.summary") {
- return toMetaResult(getComponentSummary());
+ return toMetaResult(getComponentSummary(input));
}
if (name === "components.list") {
return toMetaResult(
@@ -5759,20 +6150,23 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
if (operation === undefined) {
throw new Error(`Unknown MCP tool "${name}".`);
}
- const normalizedInput = await normalizeMcpOperationInput(name, input);
- const isAuditInput = name === "audit" && isRecord(input);
+ const transportInput = getToolCallInput(input, operation.requiresConfirm);
+ const toolInput = transportInput.input;
+ dryRun = dryRun || transportInput.dryRun;
+ const normalizedInput = await normalizeMcpOperationInput(name, toolInput);
+ const isAuditInput = name === "audit" && isRecord(toolInput);
if (
isAuditInput &&
- input.rendered !== undefined &&
- typeof input.rendered !== "boolean"
+ toolInput.rendered !== undefined &&
+ typeof toolInput.rendered !== "boolean"
) {
throw new Error("audit input.rendered must be a boolean.");
}
if (
isAuditInput &&
- input.routeExamples !== undefined &&
- (Array.isArray(input.routeExamples) === false ||
- input.routeExamples.some(
+ toolInput.routeExamples !== undefined &&
+ (Array.isArray(toolInput.routeExamples) === false ||
+ toolInput.routeExamples.some(
(example) =>
isRecord(example) === false ||
typeof example.pageId !== "string" ||
@@ -5787,7 +6181,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
"audit input.routeExamples must contain { pageId, path } objects with concrete paths beginning with one slash."
);
}
- const isRenderedAudit = isAuditInput && input.rendered === true;
+ const isRenderedAudit = isAuditInput && toolInput.rendered === true;
const renderedOnlyInputFields = [
"confirmLargeRun",
"confirmationToken",
@@ -5795,7 +6189,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
"routeExamples",
] as const;
const providedRenderedOnlyInput = renderedOnlyInputFields.find(
- (field) => isAuditInput && input[field] !== undefined
+ (field) => isAuditInput && toolInput[field] !== undefined
);
if (isAuditInput && isRenderedAudit === false) {
if (providedRenderedOnlyInput !== undefined) {
@@ -5806,23 +6200,23 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
}
if (
isAuditInput &&
- input.confirmLargeRun !== undefined &&
- typeof input.confirmLargeRun !== "boolean"
+ toolInput.confirmLargeRun !== undefined &&
+ typeof toolInput.confirmLargeRun !== "boolean"
) {
throw new Error("audit input.confirmLargeRun must be a boolean.");
}
if (
isAuditInput &&
- input.confirmationToken !== undefined &&
- typeof input.confirmationToken !== "string"
+ toolInput.confirmationToken !== undefined &&
+ typeof toolInput.confirmationToken !== "string"
) {
throw new Error("audit input.confirmationToken must be a string.");
}
if (
isAuditInput &&
- input.imageDomains !== undefined &&
- (Array.isArray(input.imageDomains) === false ||
- input.imageDomains.some(
+ toolInput.imageDomains !== undefined &&
+ (Array.isArray(toolInput.imageDomains) === false ||
+ toolInput.imageDomains.some(
(domain) =>
typeof domain !== "string" ||
/^[a-z0-9.-]+(?::\d+)?$/i.test(domain) === false
@@ -5842,7 +6236,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
"Rendered audit is unavailable because this MCP host does not provide preview and screenshot capabilities."
);
}
- if (isRenderedAudit && typeof input.cursor === "string") {
+ if (isRenderedAudit && typeof toolInput.cursor === "string") {
throw new Error(
"Rendered audit cannot be combined with cursor pagination. Run the rendered pass once without cursor."
);
@@ -5851,7 +6245,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
operation,
isAuditInput
? Object.fromEntries(
- Object.entries(input).filter(
+ Object.entries(toolInput).filter(
([key]) =>
key !== "rendered" &&
key !== "confirmLargeRun" &&
@@ -5862,11 +6256,25 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
)
: normalizedInput
);
- const envelope = await executeOperation({
- command: name as Command,
- input: operationInput,
- dryRun,
- });
+ const [envelope, response] = operation.requiresConfirm
+ ? await executeDestructiveMcpOperation({
+ command: name as Command,
+ input: operationInput,
+ dryRun,
+ confirmDestructive: transportInput.confirmDestructive,
+ confirmationToken: transportInput.confirmationToken,
+ executeOperation,
+ })
+ : [
+ await executeOperation({
+ command: name as Command,
+ input: operationInput,
+ dryRun,
+ }),
+ ];
+ if (response !== undefined) {
+ return response;
+ }
if (name === "audit") {
const auditedEnvelope = await augmentAuditWithRenderedChecks({
envelope,
@@ -5875,17 +6283,17 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
? {
...operationInput,
rendered: true,
- ...(input.confirmLargeRun === true
+ ...(toolInput.confirmLargeRun === true
? { confirmLargeRun: true }
: {}),
- ...(typeof input.confirmationToken === "string"
- ? { confirmationToken: input.confirmationToken }
+ ...(typeof toolInput.confirmationToken === "string"
+ ? { confirmationToken: toolInput.confirmationToken }
: {}),
- ...(Array.isArray(input.imageDomains)
- ? { imageDomains: input.imageDomains }
+ ...(Array.isArray(toolInput.imageDomains)
+ ? { imageDomains: toolInput.imageDomains }
: {}),
- ...(Array.isArray(input.routeExamples)
- ? { routeExamples: input.routeExamples }
+ ...(Array.isArray(toolInput.routeExamples)
+ ? { routeExamples: toolInput.routeExamples }
: {}),
}
: operationInput,
@@ -5934,13 +6342,41 @@ export const createProjectSessionMcpCore = <Command extends string = string>({
};
};
-const getToolCallInput = (input: unknown) => {
- if (isRecord(input) === false) {
- return { input, dryRun: false };
+const getToolCallInput = (input: unknown, destructive = false) => {
+ if (isPlainRecord(input) === false) {
+ return {
+ input,
+ dryRun: false,
+ confirmDestructive: false,
+ confirmationToken: undefined,
+ };
}
const dryRun = input.dryRun === true || input["dry-run"] === true;
- const { dryRun: _dryRun, "dry-run": _dashDryRun, ...rest } = input;
- return { input: rest, dryRun };
+ const confirmDestructive = input.confirmDestructive === true;
+ const confirmationToken =
+ typeof input.confirmationToken === "string"
+ ? input.confirmationToken
+ : undefined;
+ const { dryRun: _dryRun, "dry-run": _dashDryRun, ...withoutDryRun } = input;
+ if (destructive) {
+ const {
+ confirmDestructive: _confirmDestructive,
+ confirmationToken: _confirmationToken,
+ ...operationInput
+ } = withoutDryRun;
+ return {
+ input: operationInput,
+ dryRun,
+ confirmDestructive,
+ confirmationToken,
+ };
+ }
+ return {
+ input: withoutDryRun,
+ dryRun,
+ confirmDestructive: false,
+ confirmationToken: undefined,
+ };
};
type ProjectSessionMcpErrorResult = {
diff --git a/packages/project-build/src/runtime/page-copy.test.tsx b/packages/project-build/src/runtime/page-copy.test.tsx
index e615244e11..94e1a7c11f 100644
--- a/packages/project-build/src/runtime/page-copy.test.tsx
+++ b/packages/project-build/src/runtime/page-copy.test.tsx
@@ -9,6 +9,7 @@ import {
type DataSource,
type Instance,
type PageTemplate,
+ type Prop,
type WebstudioData,
} from "@webstudio-is/sdk";
import { migratePages } from "@webstudio-is/project-migrations/pages";
@@ -18,6 +19,7 @@ import {
} from "@webstudio-is/project-build";
import {
pageCopyTesting,
+ pageDuplicateInput,
createPageTemplate,
createPageFromTemplate,
createPageDuplicatePayload,
@@ -42,6 +44,7 @@ import {
ws,
} from "@webstudio-is/template";
import { nanoid } from "nanoid";
+import { applyBuilderPatchTransactions } from "../state/patch";
const { deduplicateName, deduplicatePath, joinPath } = pageCopyTesting;
@@ -53,6 +56,28 @@ const getCopiedPages = (data: WebstudioData) =>
(page) => page.id !== data.pages.homePageId
);
+test("validates duplicate page substitutions", () => {
+ expect(
+ pageDuplicateInput.parse({
+ projectId: "projectId",
+ pageId: "pageId",
+ substitutions: {
+ text: { London: "Paris" },
+ variables: { city: { type: "string", value: "Paris" } },
+ },
+ })
+ ).toMatchObject({ substitutions: { text: { London: "Paris" } } });
+ expect(
+ pageDuplicateInput.safeParse({
+ projectId: "projectId",
+ pageId: "pageId",
+ substitutions: {
+ variables: { city: { type: "number", value: "not a number" } },
+ },
+ }).success
+ ).toBe(false);
+});
+
const getWebstudioDataStub = (
data?: Partial<WebstudioData>
): WebstudioData => ({
@@ -383,6 +408,150 @@ describe("insert page copy", () => {
});
});
+ test("runtime duplicate atomically substitutes copied page text and variables", () => {
+ const data = getWebstudioDataStub({
+ instances: toMap<Instance>([
+ {
+ type: "instance",
+ id: ROOT_INSTANCE_ID,
+ component: "Slot",
+ children: [],
+ },
+ {
+ type: "instance",
+ id: "bodyId",
+ component: "Body",
+ children: [
+ { type: "text", value: "Old city" },
+ { type: "text", value: "toString" },
+ ],
+ },
+ ]),
+ props: toMap<Prop>([
+ {
+ id: "rootLabelProp",
+ instanceId: ROOT_INSTANCE_ID,
+ name: "aria-label",
+ type: "string",
+ value: "Old city",
+ },
+ {
+ id: "labelProp",
+ instanceId: "bodyId",
+ name: "aria-label",
+ type: "string",
+ value: "Old city",
+ },
+ ]),
+ dataSources: toMap<DataSource>([
+ {
+ id: "cityVariable",
+ scopeInstanceId: "bodyId",
+ name: "city",
+ type: "variable",
+ value: { type: "string", value: "Old city" },
+ },
+ ]),
+ pages: migratePages({
+ meta: {},
+ homePage: {
+ id: "homePageId",
+ name: "Home",
+ path: "",
+ title: `"Home"`,
+ meta: {},
+ rootInstanceId: "bodyId",
+ },
+ pages: [
+ {
+ id: "pageId",
+ name: "City",
+ path: "/old-city",
+ title: `"Old city"`,
+ meta: { description: `"Visit Old city"` },
+ rootInstanceId: "bodyId",
+ },
+ ],
+ folders: [createRootFolder(["homePageId", "pageId"])],
+ }),
+ });
+ let nextId = 0;
+ const mutation = duplicatePage(
+ data,
+ {
+ projectId: "projectId",
+ pageId: "pageId",
+ path: "/new-city",
+ substitutions: {
+ text: {
+ "Old city": "New city",
+ "Visit Old city": "Visit New city",
+ },
+ variables: {
+ city: { type: "string", value: "New city" },
+ },
+ },
+ },
+ { createId: () => `copy-${nextId++}` }
+ );
+ const updated = applyBuilderPatchTransactions(data, [
+ { id: "duplicate-page", payload: mutation.payload },
+ ]).state as WebstudioData;
+ const copiedPage = updated.pages.pages.get(mutation.result.pageId);
+ const copiedRootId = copiedPage?.rootInstanceId;
+
+ expect(copiedPage).toMatchObject({
+ path: "/new-city",
+ title: `"New city"`,
+ meta: { description: `"Visit New city"` },
+ });
+ expect(updated.instances.get(copiedRootId ?? "")?.children).toEqual([
+ { type: "text", value: "New city" },
+ { type: "text", value: "toString" },
+ ]);
+ expect(
+ Array.from(updated.props.values()).find(
+ (prop) => prop.instanceId === copiedRootId && prop.name === "aria-label"
+ )
+ ).toMatchObject({ type: "string", value: "New city" });
+ expect(
+ Array.from(updated.dataSources.values()).find(
+ (dataSource) =>
+ dataSource.scopeInstanceId === copiedRootId &&
+ dataSource.name === "city"
+ )
+ ).toMatchObject({
+ type: "variable",
+ value: { type: "string", value: "New city" },
+ });
+ expect(data.instances.get("bodyId")?.children).toEqual([
+ { type: "text", value: "Old city" },
+ { type: "text", value: "toString" },
+ ]);
+ expect(data.dataSources.get("cityVariable")).toMatchObject({
+ value: { type: "string", value: "Old city" },
+ });
+ expect(updated.props.get("rootLabelProp")).toMatchObject({
+ value: "Old city",
+ });
+ expect(() =>
+ duplicatePage(
+ data,
+ {
+ projectId: "projectId",
+ pageId: "pageId",
+ substitutions: {
+ variables: {
+ missing: { type: "string", value: "No match" },
+ },
+ },
+ },
+ { createId: nanoid }
+ )
+ ).toThrow('Copied variable "missing" was not found');
+ expect(data.pages.pages.size).toBe(2);
+ });
+
test("runtime duplicate rejects explicit path conflicts", () => {
const data = getWebstudioDataStub({
instances: toMap<Instance>([
diff --git a/packages/project-build/src/runtime/page-copy.ts b/packages/project-build/src/runtime/page-copy.ts
index 02b39d58cc..539c546656 100644
--- a/packages/project-build/src/runtime/page-copy.ts
+++ b/packages/project-build/src/runtime/page-copy.ts
@@ -23,6 +23,7 @@ import {
type Asset,
type Folder,
type DataSource,
+ dataSourceVariableValue,
type Page,
type PageTemplate,
type Pages,
@@ -37,6 +38,7 @@ import { paginateOutput, type PaginatedOutputInput } from "./output";
import { webstudioDataNamespaces } from "../contracts/namespaces";
import { throwBuilderRuntimeError } from "./errors";
import { createRuntimeMutation } from "./mutation";
+import { getStaticStringLiteral } from "./text-replacement";
import {
collectExclusiveInstanceIds,
createInstanceCleanupPayload,
@@ -59,12 +61,28 @@ import {
type CreateId = () => string;
+const pageDuplicateSubstitutionsInput = z.object({
+ text: z
+ .record(z.string().min(1), z.string())
+ .optional()
+ .describe(
+ "Exact fixed-text replacements applied only to the duplicated page's text children, string props, title, and metadata."
+ ),
+ variables: z
+ .record(z.string().min(1), dataSourceVariableValue)
+ .optional()
+ .describe(
+ "Copied variable values keyed by the source variable name. Ambiguous duplicate names are rejected."
+ ),
+});
+
export const pageDuplicateInput = z.object({
projectId: z.string(),
pageId: z.string(),
parentFolderId: z.string().optional(),
name: z.string().min(1).optional(),
path: z.string().optional(),
+ substitutions: pageDuplicateSubstitutionsInput.optional(),
});
const isHydratedWebstudioData = (value: unknown): value is WebstudioData => {
@@ -572,7 +590,7 @@ export const insertPageFromTemplateMutable = ({
return newPage.id;
};
-export const insertPageCopyMutable = ({
+const copyPageMutable = ({
source,
target,
projectId,
@@ -601,7 +619,124 @@ export const insertPageCopyMutable = ({
if (copied === undefined) {
return;
}
- return insertCopiedPageMutable({ page, copied, target, createId });
+ return {
+ pageId: insertCopiedPageMutable({ page, copied, target, createId }),
+ copied,
+ };
+};
+
+export const insertPageCopyMutable = (
+ input: Parameters<typeof copyPageMutable>[0]
+) => copyPageMutable(input)?.pageId;
+
+type PageDuplicateSubstitutions = z.infer<
+ typeof pageDuplicateSubstitutionsInput
+>;
+
+const applyCopiedPageTextSubstitutions = ({
+ target,
+ pageId,
+ instanceIds,
+ replacements,
+}: {
+ target: WebstudioData;
+ pageId: Page["id"];
+ instanceIds: ReadonlySet<string>;
+ replacements: Record<string, string>;
+}) => {
+ const replacementsByText = new Map(Object.entries(replacements));
+ const replaceText = (value: string) => replacementsByText.get(value) ?? value;
+ for (const instanceId of instanceIds) {
+ const instance = target.instances.get(instanceId);
+ if (instance !== undefined) {
+ instance.children = instance.children.map((child) =>
+ child.type === "text"
+ ? { ...child, value: replaceText(child.value) }
+ : child
+ );
+ }
+ }
+ for (const prop of target.props.values()) {
+ if (prop.type === "string" && instanceIds.has(prop.instanceId)) {
+ prop.value = replaceText(prop.value);
+ }
+ }
+ const page = target.pages.pages.get(pageId);
+ if (page === undefined) {
+ return;
+ }
+ const replaceFixedExpression = (expression: string) => {
+ const value = getStaticStringLiteral(expression);
+ const replacement =
+ value === undefined ? undefined : replacementsByText.get(value);
+ return replacement === undefined ? expression : JSON.stringify(replacement);
+ };
+ page.title = replaceFixedExpression(page.title);
+ copyAndTransformPageMeta(page.meta, page.meta, replaceFixedExpression);
+};
+
+const applyPageDuplicateSubstitutions = ({
+ source,
+ target,
+ pageId,
+ copied,
+ substitutions,
+}: {
+ source: WebstudioData;
+ target: WebstudioData;
+ pageId: Page["id"];
+ copied: NonNullable<ReturnType<typeof copyPageRootAndBodyMutable>>;
+ substitutions: PageDuplicateSubstitutions;
+}) => {
+ if (
+ substitutions.text !== undefined &&
+ Object.keys(substitutions.text).length > 0
+ ) {
+ const copiedInstanceIds = new Set(copied.newInstanceIds.values());
+ copiedInstanceIds.delete(ROOT_INSTANCE_ID);
+ applyCopiedPageTextSubstitutions({
+ target,
+ pageId,
+ instanceIds: copiedInstanceIds,
+ replacements: substitutions.text,
+ });
+ }
+
+ const variablesByName = new Map<string, DataSource[]>();
+ for (const sourceId of copied.newDataSourceIds.keys()) {
+ const dataSource = source.dataSources.get(sourceId);
+ if (dataSource?.type !== "variable") {
+ continue;
+ }
+ const variables = variablesByName.get(dataSource.name) ?? [];
+ variables.push(dataSource);
+ variablesByName.set(dataSource.name, variables);
+ }
+ for (const [name, value] of Object.entries(substitutions.variables ?? {})) {
+ const matches = variablesByName.get(name) ?? [];
+ if (matches.length === 0) {
+ return throwBuilderRuntimeError(
+ "NOT_FOUND",
+ `Copied variable "${name}" was not found`
+ );
+ }
+ if (matches.length > 1) {
+ return throwBuilderRuntimeError(
+ "CONFLICT",
+ `Copied variable name "${name}" is ambiguous`
+ );
+ }
+ const newId = copied.newDataSourceIds.get(matches[0]!.id);
+ const variable =
+ newId === undefined ? undefined : target.dataSources.get(newId);
+ if (variable?.type !== "variable") {
+ return throwBuilderRuntimeError(
+ "NOT_FOUND",
+ `Copied variable "${name}" was not found`
+ );
+ }
+ variable.value = structuredClone(value);
+ }
};
export const createPageDuplicatePayload = ({
@@ -612,6 +747,7 @@ export const createPageDuplicatePayload = ({
parentFolderId,
name,
path,
+ substitutions,
createId = nanoid,
}: {
build: Parameters<typeof createWebstudioDataFromBuild>[0]["build"];
@@ -621,17 +757,19 @@ export const createPageDuplicatePayload = ({
parentFolderId: Folder["id"];
name?: Page["name"];
path?: Page["path"];
+ substitutions?: PageDuplicateSubstitutions;
createId?: CreateId;
}) => {
const before = createWebstudioDataFromBuild({ build, assets });
let duplicatedPageId: Page["id"] | undefined;
const { payload } = produceWebstudioDataMutation(before, (draft) => {
- duplicatedPageId = insertPageCopyMutable({
+ const duplicate = copyPageMutable({
source: { data: draft, pageId },
target: { data: draft, folderId: parentFolderId },
projectId,
createId,
});
+ duplicatedPageId = duplicate?.pageId;
if (duplicatedPageId === undefined) {
return;
}
@@ -646,6 +784,15 @@ export const createPageDuplicatePayload = ({
if (path !== undefined) {
page.path = path;
}
+ if (substitutions !== undefined && duplicate !== undefined) {
+ applyPageDuplicateSubstitutions({
+ source: before,
+ target: draft,
+ pageId: duplicatedPageId,
+ copied: duplicate.copied,
+ substitutions,
+ });
+ }
});
if (duplicatedPageId === undefined) {
return;
@@ -695,6 +842,7 @@ export const duplicatePage = (
parentFolderId,
name: input.name,
path: input.path,
+ substitutions: input.substitutions,
createId: context.createId,
});
if (duplicate === undefined) {
diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.ts
index 5a00e0944e..0e13b071a9 100644
--- a/packages/project-build/src/runtime/registry.test.ts
+++ b/packages/project-build/src/runtime/registry.test.ts
@@ -13,6 +13,7 @@ import {
builderRuntimeOperations,
executeBuilderRuntimeOperation,
getBuilderRuntimeOperation,
+ isDestructiveRuntimeCommand,
} from "./registry";
import { runtimeGeneratedIdInput } from "./generated-id-input";
import { getRuntimeOutputSchema, runtimeOutputSchemas } from "./output-schemas";
@@ -1943,11 +1944,23 @@ describe("builder runtime registry", () => {
operation.writeNamespaces.includes("assets")
);
}
+ for (const operation of builderRuntimeOperations.filter((operation) =>
+ isDestructiveRuntimeCommand(operation.command)
+ )) {
+ expect(operation.requiresConfirm, operation.command).toBe(true);
+ }
+ expect(getBuilderRuntimeOperation("folders.delete").requiresConfirm).toBe(
+ true
+ );
+ expect(getBuilderRuntimeOperation("redirects.setAll").requiresConfirm).toBe(
+ true
+ );
expect(
- builderRuntimeOperations
- .filter((operation) => operation.requiresConfirm)
- .map((operation) => operation.id)
- ).toEqual(["cssVariables.delete"]);
+ getBuilderRuntimeOperation("styleSources.clearStyles").requiresConfirm
+ ).toBe(true);
+ expect(getBuilderRuntimeOperation("pages.create").requiresConfirm).toBe(
+ false
+ );
});
test("rejects client-supplied generated ids and hides generated id fields", () => {
diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.ts
index 9a493ffb17..65b1c6d914 100644
--- a/packages/project-build/src/runtime/registry.ts
+++ b/packages/project-build/src/runtime/registry.ts
@@ -243,7 +243,8 @@ const runtimeOperation = <
writeNamespaces.includes("assets")),
requiresConfirm:
contract.kind === "mutation"
- ? (contract.requiresConfirm ?? false)
+ ? (contract.requiresConfirm ??
+ isDestructiveRuntimeCommand(publicApi.command))
: false,
execute: ({ state, input, context }) => {
const result = execute({
@@ -274,6 +275,11 @@ const api = (
permit?: BuilderApiCapability
): RuntimeOperationPublicApi => ({ command, client, permit });
+export const isDestructiveRuntimeCommand = (command: string) =>
+ command.startsWith("delete-") ||
+ command.startsWith("replace-") ||
+ command === "set-redirects";
+
const readContract = (
readNamespaces: readonly BuilderNamespace[],
options: { requiresAssets?: boolean } = {}
@@ -1529,6 +1535,7 @@ export const builderRuntimeOperations = [
mutationContract({
readNamespaces: ["styles", "styleSources"],
writeNamespaces: ["styles"],
+ requiresConfirm: true,
}),
styles.styleSourceClearStylesInput,
({ state, input }) => styles.clearStyleSourceStyles(state, input)
diff --git a/packages/protocol/src/builder-api/operation-docs.test.ts b/packages/protocol/src/builder-api/operation-docs.test.ts
index 0c222de747..08e5465abb 100644
--- a/packages/protocol/src/builder-api/operation-docs.test.ts
+++ b/packages/protocol/src/builder-api/operation-docs.test.ts
@@ -31,6 +31,7 @@ test("documents every public API command with examples", () => {
for (const item of publicApiOperationDocumentation) {
expect(item.description).not.toBe("");
+ expect(item.description).not.toContain("MCP/public API operation");
expect(item.examples.length).toBeGreaterThan(0);
}
});
diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.ts
index 6e07e9cb5c..34dcbce1ad 100644
--- a/packages/protocol/src/builder-api/operation-docs.ts
+++ b/packages/protocol/src/builder-api/operation-docs.ts
@@ -179,10 +179,12 @@ const curatedPublicApiOperationDocumentation = [
},
{
command: "duplicate-page",
- description: "Duplicate a page and its page content",
+ description:
+ "Duplicate a page and optionally substitute copied fixed text and variable values atomically",
requiredOptions: ["page", "json"],
examples: [
'webstudio duplicate-page --page page-id --name "Pricing Copy" --path /pricing-copy --json',
+ `webstudio duplicate-page --page page-id --name Paris --path /paris --substitutions '{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}' --json`,
],
},
{
@@ -730,13 +732,21 @@ for (const documentation of curatedPublicApiOperationDocumentation) {
const createDefaultDocumentation = (
command: string
-): PublicApiOperationDocumentation => ({
- command,
- description: `Run the "${command}" MCP/public API operation. Use the operation input schema for valid JSON fields.`,
- examples: [
- `MCP/API: call "${command}" with JSON input matching its operation schema.`,
- ],
-});
+): PublicApiOperationDocumentation => {
+ const words = command
+ .split("-")
+ .map((word) =>
+ word === "css" || word === "ui" ? word.toUpperCase() : word
+ )
+ .join(" ");
+ return {
+ command,
+ description: `${words.charAt(0).toUpperCase()}${words.slice(1)}.`,
+ examples: [
+ `MCP/API: call "${command}" with JSON input matching its operation schema.`,
+ ],
+ };
+};
const documentedCommands = new Set<string>();