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: guide agents through webstudio cli (#5847)

Oleg Isonenb1a3eed1f89b
diff --git a/packages/cli/package.json b/packages/cli/package.json
index d1a5c8bf61..56d9a7d246 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -23,7 +23,7 @@
],
"scripts": {
"typecheck": "tsgo --noEmit",
- "generate-docs": "node scripts/generate-docs.mjs",
+ "generate-docs": "tsx scripts/generate-docs.ts",
"build": "pnpm generate-docs && rm -rf lib && vite build",
"test": "vitest run"
},
@@ -68,6 +68,7 @@
"@remix-run/node": "^2.16.5",
"@remix-run/react": "^2.16.5",
"@remix-run/server-runtime": "^2.16.5",
+ "@types/mdast": "^4.0.4",
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
"@types/yargs": "^17.0.33",
@@ -88,6 +89,10 @@
"h3": "^1.15.1",
"ipx": "^3.0.3",
"isbot": "^5.1.25",
+ "mdast-util-directive": "^3.1.0",
+ "mdast-util-from-markdown": "^2.0.3",
+ "mdast-util-to-string": "^4.0.0",
+ "micromark-extension-directive": "^4.0.0",
"prettier": "3.5.3",
"react": "18.3.0-canary-14898b6a9-20240318",
"react-dom": "18.3.0-canary-14898b6a9-20240318",
diff --git a/packages/cli/scripts/generate-docs.ts b/packages/cli/scripts/generate-docs.ts
new file mode 100644
index 0000000000..4632611669
--- /dev/null
+++ b/packages/cli/scripts/generate-docs.ts
@@ -0,0 +1,50 @@
+import { readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { basename, join } from "node:path";
+import { format } from "prettier";
+import {
+ buildDocSections,
+ buildDocTitles,
+ stripDocMeta,
+} from "./markdown-docs";
+
+const docsDir = new URL("../src/docs", import.meta.url);
+const outputFile = new URL("../src/docs.generated.ts", import.meta.url);
+
+const sourceDocs = Object.fromEntries(
+ readdirSync(docsDir)
+ .filter((fileName) => fileName.endsWith(".md"))
+ .sort()
+ .map((fileName) => [
+ basename(fileName, ".md"),
+ readFileSync(join(docsDir.pathname, fileName), "utf8"),
+ ])
+);
+
+const docs = Object.fromEntries(
+ Object.entries(sourceDocs).map(([docName, markdown]) => [
+ docName,
+ stripDocMeta(markdown),
+ ])
+);
+const docTitles = buildDocTitles(sourceDocs);
+const docSections = buildDocSections(sourceDocs);
+
+const output = await format(
+ [
+ "// This file is generated by scripts/generate-docs.ts.",
+ "// Edit markdown files in src/docs instead.",
+ `export const cliDocs = ${JSON.stringify(docs, null, 2)} as const;`,
+ "",
+ `export const cliDocTitles = ${JSON.stringify(docTitles, null, 2)} as const;`,
+ "",
+ `export const cliDocSections = ${JSON.stringify(docSections, null, 2)} as const;`,
+ "",
+ "export type CliDocName = keyof typeof cliDocs;",
+ "",
+ ].join("\n"),
+ {
+ filepath: outputFile.pathname,
+ }
+);
+
+writeFileSync(outputFile, output, "utf8");
diff --git a/packages/cli/scripts/markdown-docs.test.ts b/packages/cli/scripts/markdown-docs.test.ts
new file mode 100644
index 0000000000..9ae2b3f3bf
--- /dev/null
+++ b/packages/cli/scripts/markdown-docs.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, test } from "vitest";
+import {
+ buildDocTitles,
+ buildDocSections,
+ stripDocMeta,
+} from "./markdown-docs";
+
+describe("markdown docs metadata extraction", () => {
+ test("builds directive-marked doc sections", () => {
+ const docs = {
+ "manual-api": `# API
+
+::doc-section{field="safetyRules"}
+
+Rules:
+
+- API rule.
+
+::doc-section{field="safetyRules"}
+
+## Safety Rules
+
+- Safety rule.`,
+ "manual-llm": `# LLM
+
+::doc-section{field="implementationProcess"}
+
+## LLM Implementation Process
+
+1. Discover.
+
+::doc-section{field="visualDesignWorkflow"}
+
+## Visual Design Workflow
+
+- Verify visually.
+
+::doc-section{field="generatedFileGuardrails"}
+
+## Generated Files Guardrails
+
+- Avoid generated files.
+
+::doc-section{field="rules"}
+
+## Rules
+
+- LLM rule.`,
+ "manual-mcp": `# MCP
+
+::doc-section{field="rules"}
+
+## Core Rules
+
+- MCP rule.`,
+ };
+
+ expect(buildDocSections(docs)).toEqual({
+ "manual-api": {
+ safetyRules: ["API rule.", "Safety rule."],
+ },
+ "manual-llm": {
+ implementationProcess: ["Discover."],
+ visualDesignWorkflow: ["Verify visually."],
+ generatedFileGuardrails: ["Avoid generated files."],
+ rules: ["LLM rule."],
+ },
+ "manual-mcp": {
+ rules: ["MCP rule."],
+ },
+ });
+ });
+
+ test("builds titles and strips generation-only directives", () => {
+ const docs = {
+ "manual-api": `# API
+
+::doc-section{field="safetyRules"}
+
+## Safety Rules
+
+- Safety rule.`,
+ };
+
+ expect(buildDocTitles(docs)).toEqual({
+ "manual-api": "API",
+ });
+ expect(stripDocMeta(docs["manual-api"])).not.toContain("doc-section");
+ expect(stripDocMeta(docs["manual-api"])).toContain(
+ "# API\n\n## Safety Rules"
+ );
+ });
+
+ test("fails on empty directive-marked lists", () => {
+ expect(() =>
+ buildDocSections({
+ "manual-mcp":
+ '# MCP\n\n::doc-section{field="rules"}\n\n## Core Rules\n\nOnly prose.',
+ })
+ ).toThrow("Missing generated doc section manual-mcp:rules");
+
+ expect(() =>
+ buildDocSections({
+ "manual-mcp": "# MCP\n\n## Core Rules\n\n- Rule.",
+ })
+ ).toThrow("Missing generated doc sections manual-mcp");
+ });
+});
diff --git a/packages/cli/scripts/markdown-docs.ts b/packages/cli/scripts/markdown-docs.ts
new file mode 100644
index 0000000000..6b55224948
--- /dev/null
+++ b/packages/cli/scripts/markdown-docs.ts
@@ -0,0 +1,143 @@
+import { fromMarkdown } from "mdast-util-from-markdown";
+import { toString } from "mdast-util-to-string";
+import { directive } from "micromark-extension-directive";
+import {
+ directiveFromMarkdown,
+ type LeafDirective,
+} from "mdast-util-directive";
+import type { ListItem, RootContent } from "mdast";
+
+const docSectionDirectiveName = "doc-section";
+
+const parseMarkdown = (markdown: string) =>
+ fromMarkdown(markdown, {
+ extensions: [directive()],
+ mdastExtensions: [directiveFromMarkdown()],
+ });
+
+const getStartOffset = (node: RootContent) => node.position?.start.offset ?? 0;
+
+const getNodeText = (node: RootContent | ListItem) => toString(node);
+
+const getSectionEndIndex = (
+ children: readonly RootContent[],
+ startIndex: number,
+ maxHeadingDepth: number | undefined
+) => {
+ for (let index = startIndex; index < children.length; index += 1) {
+ const node = children[index];
+ if (node?.type !== "heading") {
+ continue;
+ }
+ if (maxHeadingDepth === undefined || (node.depth ?? 0) <= maxHeadingDepth) {
+ return index;
+ }
+ }
+ return children.length;
+};
+
+const getMarkedSectionNodes = (
+ children: readonly RootContent[],
+ directiveIndex: number
+) => {
+ const firstNode = children[directiveIndex + 1];
+ if (firstNode === undefined) {
+ return [];
+ }
+ const startsWithHeading = firstNode.type === "heading";
+ const contentStartIndex = startsWithHeading
+ ? directiveIndex + 2
+ : directiveIndex + 1;
+ const endIndex = getSectionEndIndex(
+ children,
+ contentStartIndex,
+ startsWithHeading ? (firstNode.depth ?? 0) : undefined
+ );
+ return children.slice(contentStartIndex, endIndex);
+};
+
+const isDocSectionDirective = (node: RootContent): node is LeafDirective =>
+ node.type === "leafDirective" && node.name === docSectionDirectiveName;
+
+const getDirectiveRemovalEnd = (markdown: string, node: LeafDirective) => {
+ let end = node.position?.end.offset ?? 0;
+ while (markdown[end] === "\n") {
+ end += 1;
+ }
+ return end;
+};
+
+export const stripDocMeta = (markdown: string) => {
+ const tree = parseMarkdown(markdown);
+ const ranges = tree.children
+ .filter(isDocSectionDirective)
+ .map((node) => ({
+ start: getStartOffset(node),
+ end: getDirectiveRemovalEnd(markdown, node),
+ }))
+ .sort((left, right) => right.start - left.start);
+ let strippedMarkdown = markdown;
+ for (const range of ranges) {
+ strippedMarkdown =
+ strippedMarkdown.slice(0, range.start) +
+ strippedMarkdown.slice(range.end);
+ }
+ return strippedMarkdown;
+};
+
+const getListItemText = (node: ListItem) =>
+ getNodeText(node).replace(/\s+/g, " ").trim();
+
+const getListItems = (nodes: readonly RootContent[]) =>
+ nodes.flatMap((node) =>
+ node.type === "list" ? node.children.map(getListItemText) : []
+ );
+
+export const getTitle = (markdown: string) => {
+ const heading = parseMarkdown(markdown).children.find(
+ (node) => node.type === "heading" && node.depth === 1
+ );
+ return heading === undefined ? "" : getNodeText(heading).trim();
+};
+
+export const buildDocSections = (docs: Record<string, string>) =>
+ Object.fromEntries(
+ Object.entries(docs).map(([docName, markdown]) => {
+ const tree = parseMarkdown(markdown);
+ const docSections: Record<string, string[]> = {};
+ tree.children.forEach((node, index) => {
+ if (isDocSectionDirective(node) === false) {
+ return;
+ }
+ const fieldName = node.attributes?.field;
+ if (typeof fieldName !== "string" || fieldName.length === 0) {
+ throw new Error(`Missing doc-section field ${docName}`);
+ }
+ const items = getListItems(getMarkedSectionNodes(tree.children, index));
+ if (items.length === 0) {
+ throw new Error(
+ `Missing generated doc section ${docName}:${fieldName}`
+ );
+ }
+ docSections[fieldName] = [...(docSections[fieldName] ?? []), ...items];
+ });
+ if (
+ docName.startsWith("manual-") &&
+ Object.keys(docSections).length === 0
+ ) {
+ throw new Error(`Missing generated doc sections ${docName}`);
+ }
+ return [docName, docSections];
+ })
+ );
+
+export const buildDocTitles = (docs: Record<string, string>) =>
+ Object.fromEntries(
+ Object.entries(docs).map(([docName, markdown]) => {
+ const title = getTitle(markdown);
+ if (title === "" && docName.startsWith("manual-")) {
+ throw new Error(`Missing generated doc title ${docName}`);
+ }
+ return [docName, title === "" ? docName : title];
+ })
+ );
diff --git a/packages/cli/src/commands/man.test.ts b/packages/cli/src/commands/man.test.ts
index 81cac70c87..8b0292377e 100644
--- a/packages/cli/src/commands/man.test.ts
+++ b/packages/cli/src/commands/man.test.ts
@@ -264,10 +264,76 @@ test("prints llm manual with discovery rules", () => {
expect(output).toContain('"instanceId": "instance-id"');
expect(output).toContain("Never guess ids");
expect(output).toContain("--refresh");
+ expect(output).toContain("## LLM Implementation Process");
+ expect(output).toContain("## Visual Design Workflow");
+ expect(output).toContain("## Generated Files Guardrails");
+ expect(output).toContain(
+ "Make edits through Webstudio semantic commands/MCP tools"
+ );
+ expect(output).toContain(
+ "Do not edit `app/__generated__`, generated route files"
+ );
+ expect(output).toContain("inspect it with vision");
+ expect(output).toContain(
+ "Pass --json only to commands whose help/schema documents it"
+ );
expect(output).toContain("## Known Gaps");
expect(output).toContain("Provider-specific authenticated pages");
});
+test("prints llm manual as json with implementation process", () => {
+ vi.spyOn(console, "info").mockImplementation(() => undefined);
+
+ man({ topic: "llm", json: true });
+
+ const output = JSON.parse(vi.mocked(console.info).mock.calls.at(-1)?.[0]);
+ expect(output.topic).toBe("llm");
+ expect(output.implementationProcess).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining("Discover capabilities"),
+ expect.stringContaining("inspect it with vision"),
+ ])
+ );
+ expect(output.visualDesignWorkflow).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining("Read editable Webstudio structure first"),
+ expect.stringContaining(
+ "Make edits through Webstudio semantic commands/MCP tools"
+ ),
+ ])
+ );
+ expect(output.responsiveVerification).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining("Read breakpoints with list-breakpoints"),
+ expect.stringContaining("viewport"),
+ expect.stringContaining("Inspect every viewport screenshot with vision"),
+ ])
+ );
+ expect(output.generatedFileGuardrails).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining("Do not edit app/__generated__"),
+ expect.stringContaining("Generated files are build artifacts"),
+ ])
+ );
+ expect(output.rules).toContain(
+ "Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported."
+ );
+ expect(output.rules).toContain(
+ "For visual/design work, verify the rendered result with vision before finishing."
+ );
+ expect(output.visionVerificationLoop).toContain(
+ getVisionVerificationLoop({ includeDiff: true })[1]
+ );
+ expect(output.visionVerificationLoop).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining("list-breakpoints"),
+ expect.stringContaining("viewport"),
+ ])
+ );
+ expect(output.screenshotVerification).toContain("screenshot.diff");
+ expect(output.screenshotVerification).toContain("list-breakpoints");
+});
+
test("prints mcp manual with startup and JSON argument examples", () => {
vi.spyOn(console, "info").mockImplementation(() => undefined);
@@ -306,8 +372,10 @@ test("prints mcp manual as json", () => {
expect(output.visionVerificationLoop).toEqual(
expect.arrayContaining([
expect.stringContaining(
- 'Call screenshot with { path: "/" } or the changed page path.'
+ 'Call screenshot with { path: "/" } or the changed page path and viewport'
),
+ expect.stringContaining("list-breakpoints"),
+ expect.stringContaining("viewport"),
])
);
expect(output.visionVerificationLoop).toContain(
diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.ts
index 69bf9dd051..be0ecab090 100644
--- a/packages/cli/src/commands/man.ts
+++ b/packages/cli/src/commands/man.ts
@@ -4,7 +4,7 @@ import type {
} from "./yargs-types";
import { buildPatchNamespaces } from "@webstudio-is/protocol";
import { mcpArgumentExamples } from "@webstudio-is/project-build/mcp";
-import { readCliDoc } from "../docs";
+import { readCliDoc, readCliDocSections, readCliDocTitle } from "../docs";
import {
generatedAppDependencyNotes,
getVisionVerificationLoop,
@@ -472,132 +472,139 @@ const apiManual = renderMarkdownTemplate(apiManualMarkdown, manualReplacements);
const llmManual = renderMarkdownTemplate(llmManualMarkdown, manualReplacements);
const mcpManual = renderMarkdownTemplate(mcpManualMarkdown, manualReplacements);
+const apiDocSections = readCliDocSections("manual-api");
+const llmDocSections = readCliDocSections("manual-llm");
+const mcpDocSections = readCliDocSections("manual-mcp");
+
+const mergeDocSections = <Json extends Record<string, unknown>>(
+ topic: string,
+ json: Json,
+ sections: Record<string, unknown>
+) => {
+ for (const fieldName of Object.keys(sections)) {
+ if (Object.hasOwn(json, fieldName)) {
+ throw new Error(
+ `Doc metadata field "${fieldName}" conflicts with ${topic} manual JSON`
+ );
+ }
+ }
+ return { ...json, ...sections };
+};
+
const topics = {
api: {
manual: apiManual,
- json: {
- topic: "api",
- title: "Webstudio API CLI Manual",
- workflows: [
- "webstudio init --link <api-share-link> --json",
- "webstudio permissions --json",
- "webstudio schema api --json",
- "webstudio publish deploy --target production --json",
- "webstudio domains list --json",
- "webstudio mcp",
- ],
- taskRecipes,
- useCaseScenarios,
- knownGaps: knownCliGaps,
- topLevelCommands: topLevelCommandCatalog,
- apiCommandsByArea,
- mcpOnlyCommands: mcpOnlyCommandCatalog,
- inputFileShapes,
- mcpArgumentExamples,
- commands: commandCatalog,
- readCommands,
- writeCommands,
- mutationNamespaces: buildPatchNamespaces,
- sessionBehavior: {
- localReads:
- "Use compatible cached namespaces and fetch only missing or stale namespaces.",
- localMutations:
- "Build patches locally, commit with the cached build version, and update local state only after remote commit succeeds.",
- serverOnly:
- "Run remotely and invalidate/refetch namespaces declared by the public operation catalog.",
- refreshFlag:
- "Use --refresh to refresh required namespaces before local-capable commands.",
- metadata:
- "Successful command JSON includes meta.session with operationId, buildId, version, source, committed, compatibility, namespace metadata, and diagnostics.",
+ json: mergeDocSections(
+ "api",
+ {
+ topic: "api",
+ title: readCliDocTitle("manual-api"),
+ workflows: [
+ "webstudio init --link <api-share-link> --json",
+ "webstudio permissions --json",
+ "webstudio schema api --json",
+ "webstudio publish deploy --target production --json",
+ "webstudio domains list --json",
+ "webstudio mcp",
+ ],
+ taskRecipes,
+ useCaseScenarios,
+ knownGaps: knownCliGaps,
+ topLevelCommands: topLevelCommandCatalog,
+ apiCommandsByArea,
+ mcpOnlyCommands: mcpOnlyCommandCatalog,
+ inputFileShapes,
+ mcpArgumentExamples,
+ commands: commandCatalog,
+ readCommands,
+ writeCommands,
+ mutationNamespaces: buildPatchNamespaces,
+ sessionBehavior: {
+ localReads:
+ "Use compatible cached namespaces and fetch only missing or stale namespaces.",
+ localMutations:
+ "Build patches locally, commit with the cached build version, and update local state only after remote commit succeeds.",
+ serverOnly:
+ "Run remotely and invalidate/refetch namespaces declared by the public operation catalog.",
+ refreshFlag:
+ "Use --refresh to refresh required namespaces before local-capable commands.",
+ metadata:
+ "Successful command JSON includes meta.session with operationId, buildId, version, source, committed, compatibility, namespace metadata, and diagnostics.",
+ },
},
- safetyRules: [
- "Always pass --json.",
- "Never pass project ids; commands use the configured project.",
- "Read ids before writing.",
- "Prefer semantic MCP write tools over apply-patch.",
- "For MCP apply-patch, read the latest version with MCP snapshot before writing.",
- "Reuse ids from MCP snapshot output when updating existing records.",
- "Generate new unique ids when adding records.",
- "Regenerate the patch after a version conflict.",
- ],
- },
+ apiDocSections
+ ),
},
llm: {
manual: llmManual,
- json: {
- topic: "llm",
- title: "Webstudio CLI Manual for LLMs",
- discovery: [
- "webstudio schema api --json",
- "webstudio permissions --json",
- "webstudio mcp",
- "MCP tool: status",
- "MCP resource: webstudio://project/tools",
- ],
- taskRecipes,
- useCaseScenarios,
- knownGaps: knownCliGaps,
- topLevelCommands: topLevelCommandCatalog,
- apiCommandsByArea,
- mcpOnlyCommands: mcpOnlyCommandCatalog,
- inputFileShapes,
- mcpArgumentExamples,
- commands: commandCatalog,
- readCommands,
- writeCommands,
- sessionBehavior: [
- "Read meta.session.source and meta.session.namespaces to understand whether data came from local cache, remote refresh, dry-run, or server-only execution.",
- "Use --refresh before a local-capable command when the cached snapshot may be stale.",
- "A mutation is durable only when meta.session.committed is true.",
- ],
- writes: [
- "Use MCP tools for fine-grained project edits.",
- "Use top-level CLI only for link/sync/build/publish/domains/permissions/discovery workflows.",
- ],
- rules: [
- "Always pass --json.",
- "Never guess ids for existing records. Read them first.",
- "Use the configured project only.",
- "Regenerate patches after VERSION_CONFLICT.",
- "Use stdout JSON as the contract.",
- ],
- },
+ json: mergeDocSections(
+ "llm",
+ {
+ topic: "llm",
+ title: readCliDocTitle("manual-llm"),
+ discovery: [
+ "webstudio schema api --json",
+ "webstudio permissions --json",
+ "webstudio mcp",
+ "MCP tool: status",
+ "MCP resource: webstudio://project/tools",
+ ],
+ taskRecipes,
+ useCaseScenarios,
+ knownGaps: knownCliGaps,
+ topLevelCommands: topLevelCommandCatalog,
+ apiCommandsByArea,
+ mcpOnlyCommands: mcpOnlyCommandCatalog,
+ inputFileShapes,
+ mcpArgumentExamples,
+ commands: commandCatalog,
+ readCommands,
+ writeCommands,
+ sessionBehavior: [
+ "Read meta.session.source and meta.session.namespaces to understand whether data came from local cache, remote refresh, dry-run, or server-only execution.",
+ "Use --refresh before a local-capable command when the cached snapshot may be stale.",
+ "A mutation is durable only when meta.session.committed is true.",
+ ],
+ writes: [
+ "Use MCP tools for fine-grained project edits.",
+ "Use top-level CLI only for link/sync/build/publish/domains/permissions/discovery workflows.",
+ ],
+ visionVerificationLoop: [...mcpVisionVerificationLoop],
+ screenshotVerification: screenshotVerificationSummary,
+ },
+ llmDocSections
+ ),
},
mcp: {
manual: mcpManual,
- json: {
- topic: "mcp",
- title: "Webstudio MCP Manual",
- startup: [
- "webstudio init --link <api-share-link> --json",
- "webstudio permissions --json",
- "webstudio mcp",
- ],
- discovery: [
- "tools/list",
- "resources/list",
- "meta.index",
- "meta.guide",
- "meta.get_more_tools",
- ],
- resources: [
- "webstudio://project/status",
- "webstudio://project/tools",
- "webstudio://project/guide",
- ],
- rules: [
- "stdout is reserved for MCP JSON-RPC while the server is running.",
- "Operate on the configured project only.",
- "Read ids before writing.",
- "Prefer semantic tools over apply-patch.",
- "Use status and refresh when cached namespaces may be stale.",
- "A mutation is durable only when meta.session.committed is true.",
- "For visual/design work, verify the rendered result with vision before finishing.",
- ],
- visionVerificationLoop: [...mcpVisionVerificationLoop],
- mcpArgumentExamples,
- screenshotVerification: screenshotVerificationSummary,
- },
+ json: mergeDocSections(
+ "mcp",
+ {
+ topic: "mcp",
+ title: readCliDocTitle("manual-mcp"),
+ startup: [
+ "webstudio init --link <api-share-link> --json",
+ "webstudio permissions --json",
+ "webstudio mcp",
+ ],
+ discovery: [
+ "tools/list",
+ "resources/list",
+ "meta.index",
+ "meta.guide",
+ "meta.get_more_tools",
+ ],
+ resources: [
+ "webstudio://project/status",
+ "webstudio://project/tools",
+ "webstudio://project/guide",
+ ],
+ visionVerificationLoop: [...mcpVisionVerificationLoop],
+ mcpArgumentExamples,
+ screenshotVerification: screenshotVerificationSummary,
+ },
+ mcpDocSections
+ ),
},
};
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index d5ff351f0a..d51a731eb2 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -24,6 +24,9 @@ test("documents MCP stdio startup and discovery tools", () => {
expect(yargs.epilogue).toHaveBeenCalledWith(
expect.stringContaining("current Builder dev build")
);
+ expect(yargs.epilogue).toHaveBeenCalledWith(
+ expect.stringContaining("webstudio://project/guide")
+ );
});
test("marks cached namespaces stale before serving MCP tools", async () => {
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 537fefaf8b..57d966d034 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -27,6 +27,7 @@ import {
getVisionWorkflowSummary,
visualVerificationRule,
} from "../mcp-guidance";
+import { readCliDoc } from "../docs";
import { apiCompatibilityHeaders } from "./api";
import { importProject as importProjectCommand } from "./import";
import type { CommonYargsArgv } from "./yargs-types";
@@ -57,14 +58,7 @@ export const mcpOptions = (yargs: CommonYargsArgv) =>
"MCP tool: meta.guide",
"Ask for the recommended workflow and relevant tools"
)
- .epilogue(
- [
- "Plain `webstudio mcp` starts the stdio MCP server.",
- "Startup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.",
- "After startup, MCP clients discover capabilities with tools/list, resources/list, meta.index, meta.guide, and meta.get_more_tools.",
- "stdout is reserved for MCP JSON-RPC messages while the server is running.",
- ].join("\n")
- );
+ .epilogue(readCliDoc("mcp-startup-epilogue"));
export const mcp = async () => {
const connection = await resolveApiConnection();
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 894006390a..08f7b26afc 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -1,16 +1,102 @@
-// This file is generated by scripts/generate-docs.mjs.
+// This file is generated by scripts/generate-docs.ts.
// 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 --json\n- webstudio man api --json\n- webstudio man llm --json\n- webstudio man mcp --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n\nNotes:\n\n- Use `tools/list` for machine-readable MCP tool schemas.\n- Use `resources/list` and `resources/read` for longer MCP resources such as `webstudio://project/tools` and `webstudio://project/guide`.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\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 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: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":"before.png","currentPath":"current.png","outputDir":".webstudio/screenshots"}\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 what was actually built.\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- For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.start or webstudio preview.\n- If preview fails with a missing generated-app command/package such as react-router or vite, install the generated app dependencies and retry.\n- When a baseline exists, use screenshot.diff to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches.\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 preview --template ssg, then webstudio screenshot <url> --output current.png.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans","status":"200"}\n- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"settings":"project-settings.json contents"}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"oldPath":"/old","newPath":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"oldPath":"/old","newPath":"/newer","status":302}\n- MCP tool: update-redirect {"oldPath":"/old","status":null}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"oldPath":"/old"}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","label":"Tablet","maxWidth":1023}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","condition":null,"minWidth":768}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet","confirm":true}\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 from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {"includePages":true}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","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## Append/prepend/replace child elements\n\nCommands:\n\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","parentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceId":"<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## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\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\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceId":"<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 {"replacements":"replace.json contents"}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {"withUsage":true}\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 {"styleSourceId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"styleSourceId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"token":"token.json contents"}\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 {"variables":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","confirm":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"variableId":"<variableId>","value":{"type":"json","value":{"count":1}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"variableId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\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\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":"asset.json contents","assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":"assets.json contents","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>","confirm":true}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetId":"<assetId>","confirm":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: snapshot {"include":["marketplaceProduct"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\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 this for finding elements by label, type, href/resource patterns, HTML snippets, missing accessibility metadata, or asset usage.\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: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>","confirm":true}\n- MCP tool: replace-styles {"replacements":"replace.json contents"}\n- MCP tool: rewrite-css-variable-refs {"variables":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {"includeFolders":true}\n- MCP tool: update-page {"pageId":"<pageId>","title":"Pricing","description":"Plans"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","maxWidth":1023}\n- MCP tool: get-styles {"instanceId":"<instanceId>","includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"styleSourceId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"settings":"project-settings.json contents"}\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-resource {"name":"Posts","method":"get","url":"https://api.example.com/posts"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","url":"https://api.example.com/posts"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\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\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"name":"Seats","method":"get","url":"https://api.example.com/seats"}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use existing scripts/resources for behavior, then move presentational structure into editable Webstudio instances where possible.\n- There is no dedicated semantic command yet for converting script-generated UI into editable Webstudio structure.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","auth":{"login":"<login>","password":"<password>"}}\n- MCP tool: create-resource {"name":"Session","method":"get","url":"https://api.example.com/session"}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still requires manual resources, props, embeds, or patches.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"variables":"vars.json contents"}\n- MCP tool: append-instance {"parentInstanceId":"<instanceId>","children":"children.json contents"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/","output":"current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after external design interpretation. There is no dedicated import command for Figma, screenshots, Inception output, or design.md yet.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n- webstudio permissions --json\n- webstudio mcp\n\nNotes:\n\n- Public API and CLI intentionally operate on one configured project at a time. Use an external script to loop over projects.\n\n# Known CLI Gaps\n\n## General project search and audit\n\nMissing:\nNo single semantic command searches across instance labels, props, hrefs, resource URLs, HTML embeds, asset references, and missing accessibility metadata.\n\nCurrent fallback:\nUse focused MCP reads such as list-instances, list-texts, list-assets, find-asset-usage, and snapshot.\n\nSuggested commands:\n\n- search-project\n- audit-accessibility\n- find-prop-usage\n\n## Save and manage page templates\n\nMissing:\nCLI can list page templates and create pages from existing templates, but cannot save a page as a template or update/delete templates semantically.\n\nCurrent fallback:\nUse MCP snapshot and apply-patch only when the template data model is understood.\n\nSuggested commands:\n\n- create-page-template\n- update-page-template\n- delete-page-template\n\n## Semantic marketplace metadata\n\nMissing:\nMarketplace metadata is only available through MCP snapshot/apply-patch, not dedicated semantic commands.\n\nCurrent fallback:\nUse MCP snapshot --include marketplaceProduct and apply-patch.\n\nSuggested commands:\n\n- get-marketplace\n- update-marketplace\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCreate the page, resources, variables, props, and embeds manually with existing MCP semantic tools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Dynamic script/runtime integration helpers\n\nMissing:\nCLI can manipulate props/resources/embeds, but has no semantic workflow for converting script-generated UI into editable Webstudio structures.\n\nCurrent fallback:\nUse MCP append-instance, props, resources, and raw patch where necessary.\n\nSuggested commands:\n\n- integrate-runtime-ui\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nUse external generation, then apply semantic CLI commands or apply-patch.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',
"manual-api":
- '# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\nRules:\n\n- Always pass --json.\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 meta.session with operationId, buildId, version, source, committed, compatibility, namespace freshness, and diagnostics.\n\n## CLI Capability Inventory\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP-Only Operations\n\nThese are intentionally exposed through `webstudio mcp`, not as top-level shell commands:\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": "unique-client-transaction-id",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\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: site metadata, redirects, page records, folders, 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\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "tx-site-name",\n"payload": [\n{\n"namespace": "pages",\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": "tx-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": "tx-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 a data variable:\n\n[\n{\n"id": "tx-variable",\n"payload": [\n{\n"namespace": "dataSources",\n"patches": [\n{\n"op": "add",\n"path": ["variable-id"],\n"value": {\n"type": "variable",\n"id": "variable-id",\n"scopeInstanceId": "instance-id",\n"name": "headline",\n"value": { "type": "string", "value": "Launch faster" }\n}\n}\n]\n}\n]\n}\n]\n\nCreate a design token:\n\n[\n{\n"id": "tx-token",\n"payload": [\n{\n"namespace": "styleSources",\n"patches": [\n{ "op": "add", "path": ["token-id"], "value": { "type": "token", "id": "token-id", "name": "Brand Primary" } }\n]\n},\n{\n"namespace": "styles",\n"patches": [\n{\n"op": "add",\n"path": ["token-id:base:color:"],\n"value": {\n"styleSourceId": "token-id",\n"breakpointId": "base",\n"property": "color",\n"value": { "type": "keyword", "value": "red" }\n}\n}\n]\n}\n]\n}\n]\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- Generate new unique ids when adding records.\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',
+ '# 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 meta.session with operationId, buildId, version, source, committed, compatibility, namespace freshness, and diagnostics.\n\n## CLI Capability Inventory\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP-Only Operations\n\nThese are intentionally exposed through `webstudio mcp`, not as top-level shell commands:\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": "unique-client-transaction-id",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\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: site metadata, redirects, page records, folders, 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\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "tx-site-name",\n"payload": [\n{\n"namespace": "pages",\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": "tx-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": "tx-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 a data variable:\n\n[\n{\n"id": "tx-variable",\n"payload": [\n{\n"namespace": "dataSources",\n"patches": [\n{\n"op": "add",\n"path": ["variable-id"],\n"value": {\n"type": "variable",\n"id": "variable-id",\n"scopeInstanceId": "instance-id",\n"name": "headline",\n"value": { "type": "string", "value": "Launch faster" }\n}\n}\n]\n}\n]\n}\n]\n\nCreate a design token:\n\n[\n{\n"id": "tx-token",\n"payload": [\n{\n"namespace": "styleSources",\n"patches": [\n{ "op": "add", "path": ["token-id"], "value": { "type": "token", "id": "token-id", "name": "Brand Primary" } }\n]\n},\n{\n"namespace": "styles",\n"patches": [\n{\n"op": "add",\n"path": ["token-id:base:color:"],\n"value": {\n"styleSourceId": "token-id",\n"breakpointId": "base",\n"property": "color",\n"value": { "type": "keyword", "value": "red" }\n}\n}\n]\n}\n]\n}\n]\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- Generate new unique ids when adding records.\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\n## Always\n\n1. webstudio permissions --json\n2. webstudio mcp\n3. Read MCP resource webstudio://project/tools.\n4. Pick focused MCP read tool.\n5. Pick semantic MCP write tool.\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- 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- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api --json for machine-readable command metadata.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n",
+ '# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\n## Always\n\n1. webstudio permissions --json\n2. webstudio mcp\n3. Read MCP resource webstudio://project/tools.\n4. Pick focused MCP read tool.\n5. Pick semantic MCP write tool.\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 llm --json`, `webstudio schema api --json`, and MCP `meta.index` or `webstudio://project/tools`.\n2. Inspect current project state with semantic reads such as `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer `append-instance`, `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## 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- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api --json for machine-readable command metadata.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
"manual-mcp":
- "# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for the configured project.\n\n## Startup\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Start the server with `webstudio mcp`.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process.\n\n## Discovery\n\nUse MCP itself after startup:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available longer JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior\n\nUseful resources:\n\n- `webstudio://project/status`: current ProjectSession status\n- `webstudio://project/tools`: operation catalog\n- `webstudio://project/guide`: concise discovery guide\n\n## Core Rules\n\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.\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 the configured project.\n\n## Startup\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Start the server with `webstudio mcp`.\n4. In the MCP client, read `webstudio://project/guide` before editing, or call `meta.index` and `meta.guide`.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process.\n\n## Discovery\n\nUse MCP itself after startup:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available longer JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior\n\nUseful resources:\n\n- `webstudio://project/status`: current ProjectSession status\n- `webstudio://project/tools`: operation catalog\n- `webstudio://project/guide`: concise discovery guide\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.\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":
+ "Plain `webstudio mcp` starts the stdio MCP server.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, read MCP resource `webstudio://project/guide` before editing.\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",
"mcp-vision":
- '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.start or webstudio preview.\n- If preview fails with a missing generated-app command/package such as react-router or vite, install the generated app dependencies and retry.\n\n## Visual Verification Rule\n\nFor visual/design work, use preview.start and screenshot after generated project files are current and generated app dependencies are installed so vision can inspect the rendered result before finishing. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\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 and generated app dependencies are installed, then call preview.start once to keep the generated site running.\n- {{dependency-notes}}\n- Call screenshot with { path: "/" } or the changed page 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.\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, ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect the 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 and generated app dependencies are installed, call preview.start, then screenshot({ path }); use screenshot.diff 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 and generated app dependencies are installed, call preview.start, then screenshot({ path }); inspect the PNG with vision before finishing.\n\n## Screenshot Verification Summary\n\nInside MCP, prefer preview.start plus screenshot({ path: "/" }) after generated project files are current and generated app dependencies are installed, so the preview server stays running for fast repeated checks. 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. Outside MCP, use webstudio preview and webstudio screenshot <url> --output current.png.\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.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',
+ '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- For a fresh checkout, copied fixture, or newly generated app, run npm install or pnpm install in the generated project before preview.start or webstudio preview.\n- If preview fails with a missing generated-app command/package such as react-router or vite, install the generated app dependencies and retry.\n\n## Visual Verification Rule\n\nFor visual/design work, use preview.start and screenshot after generated project files are current and generated app dependencies are installed so vision can inspect the rendered result before finishing. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\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 and generated app dependencies are installed, then call preview.start once to keep the generated site running.\n- {{dependency-notes}}\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 }. 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.\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, 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 and generated app dependencies are installed, call preview.start, then screenshot({ path, viewport }); for responsive work, use list-breakpoints and capture the changed page at Builder breakpoint widths plus mobile and desktop widths; use screenshot.diff 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 and generated app dependencies are installed, call preview.start, then screenshot({ path, viewport }); for responsive work, use list-breakpoints and capture the changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.\n\n## Screenshot Verification Summary\n\nInside MCP, prefer preview.start plus screenshot({ path: "/", viewport }) after generated project files are current and generated app dependencies are installed, so the preview server stays running for fast repeated checks. For responsive work, read list-breakpoints and capture viewport widths from Builder breakpoint edges plus mobile and desktop widths 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. Outside MCP, use webstudio preview and webstudio screenshot <url> --output current.png.\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.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',
+} as const;
+
+export const cliDocTitles = {
+ "api-use-cases": "CLI API Use Cases",
+ "manual-api": "Webstudio API CLI Manual",
+ "manual-llm": "Webstudio CLI Manual for LLMs",
+ "manual-mcp": "Webstudio MCP Manual",
+ "mcp-startup-epilogue": "mcp-startup-epilogue",
+ "mcp-vision": "MCP Vision Verification",
+} as const;
+
+export const cliDocSections = {
+ "api-use-cases": {},
+ "manual-api": {
+ safetyRules: [
+ "Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.",
+ "Never pass a project id. Commands use configured project only.",
+ "Read ids before writing. Do not invent ids for existing records.",
+ "stdout is one JSON object. stderr is diagnostics.",
+ "Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.",
+ "For MCP apply-patch, read the latest version with MCP snapshot before writing.",
+ "Reuse ids from MCP snapshot output when updating existing records.",
+ "Generate new unique ids when adding records.",
+ "If apply-patch reports a version conflict, read the latest build and regenerate the patch.",
+ "Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.",
+ ],
+ },
+ "manual-llm": {
+ implementationProcess: [
+ "Discover capabilities with webstudio man llm --json, webstudio schema api --json, and MCP meta.index or webstudio://project/tools.",
+ "Inspect current project state with semantic reads such as list-pages, get-page-by-path, list-instances, inspect-instance, get-styles, list-assets, list-breakpoints, and snapshot only when needed.",
+ "Mutate the Webstudio project with semantic MCP write tools first. Prefer append-instance, update-text, update-props, update-styles, upload-asset, create-page, and page/project settings tools over raw patches.",
+ "Use apply-patch only when no semantic tool covers the required change, and only after reading the latest snapshot/version.",
+ "For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.",
+ "Report what changed and what verification ran.",
+ ],
+ visualDesignWorkflow: [
+ "Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.",
+ "Do not use generated route/component files as the source of truth for editable content.",
+ "Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next webstudio build.",
+ "Keep generated project files current, start preview, and capture the changed page with screenshot.",
+ "Use screenshot.diff when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.",
+ "If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.",
+ ],
+ responsiveVerification: [
+ "Read breakpoints with list-breakpoints before deciding responsive behavior.",
+ "Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.",
+ "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.",
+ '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}}.',
+ "Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.",
+ "If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.",
+ ],
+ generatedFileGuardrails: [
+ "Do not edit app/__generated__, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.",
+ "Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.",
+ "Generated files are build artifacts and may be overwritten by webstudio build.",
+ "If a task truly requires generated app customization, keep it outside app/__generated__ where possible and explain that it is not editable Webstudio content.",
+ ],
+ rules: [
+ "Never guess ids for existing records. Read them first.",
+ "Never use project ids from user input. Commands use the configured project.",
+ "Use --refresh before a local-capable command when cached data may be stale.",
+ "Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.",
+ "On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.",
+ "Treat stdout JSON as the API contract and stderr as diagnostics.",
+ "For visual/design work, verify the rendered result with vision before finishing.",
+ "Do not edit generated files for normal Webstudio content/design requests.",
+ "Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.",
+ "Use webstudio schema api --json for machine-readable command metadata.",
+ ],
+ },
+ "manual-mcp": {
+ rules: [
+ "stdout is reserved for MCP JSON-RPC while the server is running.",
+ "Operate on the configured project only.",
+ "Read ids before writing.",
+ "Prefer semantic tools over apply-patch.",
+ "Use status and refresh when cached namespaces may be stale.",
+ "A mutation is durable only when meta.session.committed is true.",
+ "For visual/design work, verify the rendered result with vision before finishing.",
+ ],
+ },
+ "mcp-startup-epilogue": {},
+ "mcp-vision": {},
} as const;
export type CliDocName = keyof typeof cliDocs;
diff --git a/packages/cli/src/docs.ts b/packages/cli/src/docs.ts
index 8f41c53547..922bac3e48 100644
--- a/packages/cli/src/docs.ts
+++ b/packages/cli/src/docs.ts
@@ -1,3 +1,14 @@
-import { cliDocs, type CliDocName } from "./docs.generated";
+import {
+ cliDocs,
+ cliDocSections,
+ cliDocTitles,
+ type CliDocName,
+} from "./docs.generated";
export const readCliDoc = (name: CliDocName) => cliDocs[name];
+
+export const readCliDocTitle = (name: CliDocName) => cliDocTitles[name];
+
+export const readCliDocSections = <Name extends keyof typeof cliDocSections>(
+ name: Name
+) => cliDocSections[name];
diff --git a/packages/cli/src/docs/manual-api.md b/packages/cli/src/docs/manual-api.md
index 70c47dd1e5..6a1ee1e391 100644
--- a/packages/cli/src/docs/manual-api.md
+++ b/packages/cli/src/docs/manual-api.md
@@ -5,9 +5,9 @@ The API commands operate on the single project configured by:
- .webstudio/config.json: projectId
- global Webstudio config: origin and token
-Rules:
+::doc-section{field="safetyRules"}
-- Always pass --json.
+- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.
- Never pass a project id. Commands use configured project only.
- Read ids before writing. Do not invent ids for existing records.
- stdout is one JSON object. stderr is diagnostics.
@@ -208,6 +208,8 @@ Create a design token:
}
]
+::doc-section{field="safetyRules"}
+
## Safety Rules
- For MCP apply-patch, read the latest version with MCP snapshot before writing.
diff --git a/packages/cli/src/docs/manual-llm.md b/packages/cli/src/docs/manual-llm.md
index f4940f347b..935189307b 100644
--- a/packages/cli/src/docs/manual-llm.md
+++ b/packages/cli/src/docs/manual-llm.md
@@ -10,6 +10,54 @@ Use this order. Stop only when a command returns ok:false.
4. Pick focused MCP read tool.
5. Pick semantic MCP write tool.
+::doc-section{field="implementationProcess"}
+
+## LLM Implementation Process
+
+Use this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:
+
+1. Discover capabilities with `webstudio man llm --json`, `webstudio schema api --json`, and MCP `meta.index` or `webstudio://project/tools`.
+2. Inspect current project state with semantic reads such as `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed.
+3. Mutate the Webstudio project with semantic MCP write tools first. Prefer `append-instance`, `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.
+4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.
+5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.
+6. Report what changed and what verification ran.
+
+::doc-section{field="visualDesignWorkflow"}
+
+## Visual Design Workflow
+
+For requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:
+
+1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.
+2. Do not use generated route/component files as the source of truth for editable content.
+3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.
+4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.
+5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.
+6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.
+
+::doc-section{field="responsiveVerification"}
+
+## Responsive Verification Workflow
+
+For responsive page work, use Builder breakpoints as the source of truth:
+
+1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.
+2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.
+3. 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.
+4. 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}}`.
+5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.
+6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.
+
+::doc-section{field="generatedFileGuardrails"}
+
+## Generated Files Guardrails
+
+- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.
+- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.
+- Generated files are build artifacts and may be overwritten by `webstudio build`.
+- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.
+
## Pick Read Command
{{readFirst}}
@@ -30,13 +78,18 @@ MCP tools receive JSON argument objects, not CLI flags. Use these shapes:
{{mcpArgumentExampleIndex}}
+::doc-section{field="rules"}
+
## Rules
- Never guess ids for existing records. Read them first.
- Never use project ids from user input. Commands use the configured project.
- Use --refresh before a local-capable command when cached data may be stale.
+- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.
- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.
- Treat stdout JSON as the API contract and stderr as diagnostics.
+- For visual/design work, verify the rendered result with vision before finishing.
+- Do not edit generated files for normal Webstudio content/design requests.
- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.
- Use webstudio schema api --json for machine-readable command metadata.
diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.md
index 1f09053f57..9e2075cb5c 100644
--- a/packages/cli/src/docs/manual-mcp.md
+++ b/packages/cli/src/docs/manual-mcp.md
@@ -7,6 +7,7 @@
1. Configure a project with `webstudio init --link <api-share-link> --json`.
2. Check capabilities with `webstudio permissions --json`.
3. Start the server with `webstudio mcp`.
+4. In the MCP client, read `webstudio://project/guide` before editing, or call `meta.index` and `meta.guide`.
While the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process.
@@ -26,8 +27,11 @@ Useful resources:
- `webstudio://project/tools`: operation catalog
- `webstudio://project/guide`: concise discovery guide
+::doc-section{field="rules"}
+
## Core Rules
+- stdout is reserved for MCP JSON-RPC while the server is running.
- Operate on the configured project only.
- Read ids before writing.
- Prefer semantic tools over `apply-patch`.
diff --git a/packages/cli/src/docs/mcp-startup-epilogue.md b/packages/cli/src/docs/mcp-startup-epilogue.md
new file mode 100644
index 0000000000..612c21b5c3
--- /dev/null
+++ b/packages/cli/src/docs/mcp-startup-epilogue.md
@@ -0,0 +1,9 @@
+Plain `webstudio mcp` starts the stdio MCP server.
+
+Startup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.
+
+After startup, read MCP resource `webstudio://project/guide` before editing.
+
+After startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get_more_tools`.
+
+stdout is reserved for MCP JSON-RPC messages while the server is running.
diff --git a/packages/cli/src/docs/mcp-vision.md b/packages/cli/src/docs/mcp-vision.md
index ba4f31a667..0fff4af181 100644
--- a/packages/cli/src/docs/mcp-vision.md
+++ b/packages/cli/src/docs/mcp-vision.md
@@ -14,23 +14,24 @@ For visual/design work, use preview.start and screenshot after generated project
- Make focused page/content/style changes with semantic MCP tools.
- Make sure generated project files are current and generated app dependencies are installed, then call preview.start once to keep the generated site running.
- {{dependency-notes}}
-- Call screenshot with { path: "/" } or the changed page path. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.
+- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.
+- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.
- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir.
- {{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, ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.
-- Inspect the PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.
+- 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.
- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.
## Workflow Summary With Diff
-For visual/design work, make sure generated project files are current and generated app dependencies are installed, call preview.start, then screenshot({ path }); use screenshot.diff when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.
+For visual/design work, make sure generated project files are current and generated app dependencies are installed, call preview.start, then screenshot({ path, viewport }); for responsive work, use list-breakpoints and capture the changed page at Builder breakpoint widths plus mobile and desktop widths; use screenshot.diff when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.
## Workflow Summary Without Diff
-For visual/design work, make sure generated project files are current and generated app dependencies are installed, call preview.start, then screenshot({ path }); inspect the PNG with vision before finishing.
+For visual/design work, make sure generated project files are current and generated app dependencies are installed, call preview.start, then screenshot({ path, viewport }); for responsive work, use list-breakpoints and capture the changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.
## Screenshot Verification Summary
-Inside MCP, prefer preview.start plus screenshot({ path: "/" }) after generated project files are current and generated app dependencies are installed, so the preview server stays running for fast repeated checks. 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. Outside MCP, use webstudio preview and webstudio screenshot <url> --output current.png.
+Inside MCP, prefer preview.start plus screenshot({ path: "/", viewport }) after generated project files are current and generated app dependencies are installed, so the preview server stays running for fast repeated checks. For responsive work, read list-breakpoints and capture viewport widths from Builder breakpoint edges plus mobile and desktop widths 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. Outside MCP, use webstudio preview and webstudio screenshot <url> --output current.png.
## Screenshot Diff Evidence
diff --git a/packages/cli/src/mcp-guidance.test.ts b/packages/cli/src/mcp-guidance.test.ts
index 8dc3ecdaa9..1e964831a7 100644
--- a/packages/cli/src/mcp-guidance.test.ts
+++ b/packages/cli/src/mcp-guidance.test.ts
@@ -14,6 +14,8 @@ test("documents generated app setup for visual verification", () => {
]);
expect(visualVerificationRule).toContain("generated app dependencies");
expect(screenshotVerificationSummary).toContain("preview.start");
+ expect(screenshotVerificationSummary).toContain("list-breakpoints");
+ expect(screenshotVerificationSummary).toContain("viewport");
});
test("builds vision loop with optional screenshot diff guidance", () => {
@@ -28,6 +30,12 @@ test("builds vision loop with optional screenshot diff guidance", () => {
expect(visionLoopWithDiff).toEqual(
expect.arrayContaining([expect.stringContaining("vision.install-ocr")])
);
+ expect(visionLoopWithDiff).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining("list-breakpoints"),
+ expect.stringContaining("viewport"),
+ ])
+ );
expect(getVisionWorkflowSummary({ includeDiff: false })).not.toContain(
"screenshot.diff"
);
diff --git a/packages/project-build/package.json b/packages/project-build/package.json
index 44880676f1..603aa4c25b 100644
--- a/packages/project-build/package.json
+++ b/packages/project-build/package.json
@@ -162,6 +162,7 @@
},
"sideEffects": false,
"scripts": {
+ "generate-docs": "node scripts/generate-docs.mjs",
"typecheck": "tsgo --noEmit",
"test": "vitest run"
},
diff --git a/packages/cli/scripts/generate-docs.mjs b/packages/project-build/scripts/generate-docs.mjs
similarity index 83%
rename from packages/cli/scripts/generate-docs.mjs
rename to packages/project-build/scripts/generate-docs.mjs
index bf86ad7413..74030d569b 100644
--- a/packages/cli/scripts/generate-docs.mjs
+++ b/packages/project-build/scripts/generate-docs.mjs
@@ -19,9 +19,9 @@ const output = await format(
[
"// This file is generated by scripts/generate-docs.mjs.",
"// Edit markdown files in src/docs instead.",
- `export const cliDocs = ${JSON.stringify(docs, null, 2)} as const;`,
+ `export const projectBuildDocs = ${JSON.stringify(docs, null, 2)} as const;`,
"",
- "export type CliDocName = keyof typeof cliDocs;",
+ "export type ProjectBuildDocName = keyof typeof projectBuildDocs;",
"",
].join("\n"),
{
diff --git a/packages/project-build/src/docs.generated.ts b/packages/project-build/src/docs.generated.ts
new file mode 100644
index 0000000000..4981d0f1c6
--- /dev/null
+++ b/packages/project-build/src/docs.generated.ts
@@ -0,0 +1,8 @@
+// This file is generated by scripts/generate-docs.mjs.
+// Edit markdown files in src/docs instead.
+export const projectBuildDocs = {
+ "mcp-startup-guidance":
+ "Before editing a Webstudio project, read `webstudio://project/guide` and `webstudio://project/tools`, or call `meta.index` and `meta.guide`. Follow the guide: read ids and Builder breakpoints first, prefer semantic tools over `apply-patch`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.\n",
+} as const;
+
+export type ProjectBuildDocName = keyof typeof projectBuildDocs;
diff --git a/packages/project-build/src/docs.ts b/packages/project-build/src/docs.ts
new file mode 100644
index 0000000000..95c23e1bc5
--- /dev/null
+++ b/packages/project-build/src/docs.ts
@@ -0,0 +1,4 @@
+import { projectBuildDocs, type ProjectBuildDocName } from "./docs.generated";
+
+export const readProjectBuildDoc = (name: ProjectBuildDocName) =>
+ projectBuildDocs[name];
diff --git a/packages/project-build/src/docs/mcp-startup-guidance.md b/packages/project-build/src/docs/mcp-startup-guidance.md
new file mode 100644
index 0000000000..12903a020d
--- /dev/null
+++ b/packages/project-build/src/docs/mcp-startup-guidance.md
@@ -0,0 +1 @@
+Before editing a Webstudio project, read `webstudio://project/guide` and `webstudio://project/tools`, or call `meta.index` and `meta.guide`. Follow the guide: read ids and Builder breakpoints first, prefer semantic tools over `apply-patch`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index 77d9d42abf..5b4dff3971 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -504,6 +504,7 @@ describe("project session mcp adapter", () => {
expect(session.initialize).not.toHaveBeenCalled();
expect(index.structuredContent.data).toEqual(
expect.objectContaining({
+ readThisFirst: expect.stringContaining("webstudio://project/guide"),
startHere: expect.arrayContaining(["meta.guide"]),
capabilities: expect.arrayContaining([
expect.objectContaining({
@@ -1178,6 +1179,7 @@ describe("project session mcp adapter", () => {
);
expect(JSON.parse(guide.contents[0]?.text ?? "{}")).toEqual(
expect.objectContaining({
+ readThisFirst: expect.stringContaining("webstudio://project/guide"),
startHere: expect.arrayContaining(["meta.index"]),
})
);
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 88fa3a5634..d0939a742c 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -24,6 +24,7 @@ import {
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
+import { readProjectBuildDoc } from "./docs";
type PublicMcpOperationMethod = "query" | "mutation";
type PublicMcpOperationPermit = "api" | "view" | "build" | "edit" | "admin";
@@ -1067,6 +1068,8 @@ const filterCapabilities = (tools: readonly ProjectSessionMcpTool[]) => {
.filter((capability) => capability.tools.length > 0);
};
+const startupGuidance = readProjectBuildDoc("mcp-startup-guidance").trim();
+
const getMetaIndex = (
tools: readonly ProjectSessionMcpTool[],
guidance: ProjectSessionMcpGuidance | undefined
@@ -1076,6 +1079,7 @@ const getMetaIndex = (
names.has(tool)
);
return {
+ readThisFirst: startupGuidance,
startHere: ["meta.index", "meta.guide", "status", "permissions"].filter(
(tool) => names.has(tool)
),
@@ -1696,8 +1700,7 @@ export const createProjectSessionMcpServer = async <
tools: {},
resources: {},
},
- instructions:
- "Use meta.index, meta.guide, and meta.get_more_tools to discover Webstudio project capabilities. Read ids before writing and prefer semantic tools over apply-patch.",
+ instructions: startupGuidance,
}
);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a1035bd0ce..3d17a4e6d0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1240,6 +1240,9 @@ importers:
'@remix-run/server-runtime':
specifier: ^2.16.5
version: 2.16.5([email protected])
+ '@types/mdast':
+ specifier: ^4.0.4
+ version: 4.0.4
'@types/react':
specifier: ^18.2.70
version: 18.2.79
@@ -1300,6 +1303,18 @@ importers:
isbot:
specifier: ^5.1.25
version: 5.1.25
+ mdast-util-directive:
+ specifier: ^3.1.0
+ version: 3.1.0
+ mdast-util-from-markdown:
+ specifier: ^2.0.3
+ version: 2.0.3
+ mdast-util-to-string:
+ specifier: ^4.0.0
+ version: 4.0.0
+ micromark-extension-directive:
+ specifier: ^4.0.0
+ version: 4.0.0
prettier:
specifier: 3.5.3
version: 3.5.3
@@ -5957,6 +5972,9 @@ packages:
resolution: {integrity: sha512-LnwD+mUEfxWMa1QpDraczIn6k0Ee3SMicuYSSzS6ZYl2gKS09EClnJYGd8Du6rfc5r/GZEk5o1mRb8TaTj03sQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==}
+
resolution: {integrity: sha512-+OWZQfAYyio6YkJb3HLxDrvnx6SWWDbC0zVPfBRzUk0/nqoDyf6dNxQi3eArPe8rJ473nobTMQ/8Zk+LxJ+Yuw==}
@@ -6008,8 +6026,8 @@ packages:
resolution: {integrity: sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==}
- '@types/[email protected]':
- resolution: {integrity: sha512-MFETx3tbTjE7Uk6vvnWINA/1iJ7LuMdO4fcq8UfF0pRbj01aGLduVvQcRyswuACJdpnHgg8E3rQLhaRdNEJS0w==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
resolution: {integrity: sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==}
@@ -7942,9 +7960,15 @@ packages:
resolution: {integrity: sha512-8SVPMuHqlPME/z3gqVwWY4zVXn8lqKv/pAhC57FuJ40ImXyBpmO5ukh98zB2v7Blql2FiHjHv9LVztSIqjY+MA==}
+ resolution: {integrity: sha512-I3fNFt+DHmpWCYAT7quoM6lHf9wuqtI+oCOfvILnoicNIqjh5E3dEJWiXuYME2gNe8vl1iMQwyUHa7bgFmak6Q==}
+
resolution: {integrity: sha512-4xTO/M8c82qBcnQc1tgpNtubGUW/Y1tBQ1B0i5CtSoelOLKFYlElIr3bvgREYYO5iRqbMY1YuqZng0GVOI8Qww==}
+ resolution: {integrity: sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==}
+
resolution: {integrity: sha512-JjA2OjxRqAa8wEG8hloD0uTU0kdn8kbtOWpPP94NBkfAlbxn4S8gCGf/9DwFtEeGPXrDcNXdiDjVaRdUFqYokw==}
@@ -7963,15 +7987,24 @@ packages:
resolution: {integrity: sha512-WmI1gTXUBJo4/ZmSk79Wcb2HcjPJBzM1nlI/OUWA8yk2X9ik3ffNbBGsU+09BFmXaL1IBb9fiuvq6/KMiNycSg==}
+ resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}
+
resolution: {integrity: sha512-pits93r8PhnIoU4Vy9bjW39M2jJ6/tdHyja9rrot9uujkN7UTU9SDnE6WNJz/IGyQk3XHX6yNNtrBH6cQzm8Hw==}
resolution: {integrity: sha512-bbv7TPv/WC49thZPg3jXuqzuvI45IL2EVAr/KxF0BSdHsU0ceFHOmwQn6evxAh1GaoK/6GQ1wp4R4oW2+LFL/A==}
+ resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}
+
resolution: {integrity: sha512-V4Zn/ncyN1QNSqSBxTrMOLpjr+IKdHl2v3KVLoWmDPscP4r9GcCi71gjgvUV1SFSKh92AjAG4peFuBl2/YgCJg==}
+ resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}
+
resolution: {integrity: sha512-aylIc7Z9y4yzHYAJNuESG3hfhC+0Ibp/MAMiaOZgNv4pmEdFyfZhhhny4MNiAfWdBQ1RQ2mfDWmM1x8SvGyp8g==}
@@ -8026,6 +8059,9 @@ packages:
resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}
+ resolution: {integrity: sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg==}
+
resolution: {integrity: sha512-m2UH9a7n3W8VAH9JO9y01APpPKmNNNs71P0RbknEmYSaZU5Ghogv38BYO94AI5Xw6OYfxZRdHZZ2nYjs/Z+SZQ==}
@@ -8131,6 +8167,9 @@ packages:
resolution: {integrity: sha512-YphLGCK8gM1tG1bd54azwyrQRjCFcmgj2S2GoJDNnh4vYtnL38JS8M4gpxzOPNyHdNEpheyWXCTnnTDY3N+NVQ==}
+ resolution: {integrity: sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==}
+
resolution: {integrity: sha512-EuEzTWSTAj9PA5GOAs992GzNh2dGQO52UvAbtSOMvXTxv3Criqb6IOzJUBCmEqrrXSblJIJBbFFv6zPxpreiJw==}
@@ -9695,6 +9734,9 @@ packages:
resolution: {integrity: sha512-Glt17jWwZeyqrFqOK0pF1Ded5U3yzJnFr8CG1GMjCWTp9zDo2p+cmD6pWbZU8AgM5WU3IzRv6+rBwhzsGh6hBQ==}
+ resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}
+
resolution: {integrity: sha512-poZa0eXpS+/XpoQwGwl79UUdea4ol2ZuCYguVaJS4qzIOMDzbqz8a3erUCOmubSZkaOuGamb3tX790iwOIROww==}
@@ -9707,12 +9749,21 @@ packages:
resolution: {integrity: sha512-k5GzIBZ/QatR8N5X2y+drfpWG8IDBzdnVj6OInRNWm1oXrzydiaAT2OQiA8DPRRZyAKb9b6I2a6PxYklZD0gKg==}
+ resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}
+
resolution: {integrity: sha512-x6+y8g7wWMyQhL1iZfhIPhDAs7Xwbn9nRosDXl7qoPTSCy0yNxnKc+hWokFifWQIDGi154rdUqKvbCa4+1kLhg==}
+ resolution: {integrity: sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==}
+
resolution: {integrity: sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg==}
+ resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==}
+
resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==}
engines: {node: '>= 4.0.0'}
@@ -13890,7 +13941,7 @@ snapshots:
dependencies:
- '@types/unist': 3.0.0
+ '@types/unist': 3.0.3
'@types/[email protected]': {}
@@ -13900,6 +13951,10 @@ snapshots:
dependencies:
'@types/unist': 2.0.6
+ '@types/[email protected]':
+ dependencies:
+ '@types/unist': 3.0.3
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -13952,7 +14007,7 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]': {}
+ '@types/[email protected]': {}
'@types/[email protected]': {}
@@ -16214,6 +16269,20 @@ snapshots:
'@types/unist': 2.0.6
unist-util-visit: 4.1.2
+ dependencies:
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ ccount: 2.0.1
+ devlop: 1.1.0
+ mdast-util-from-markdown: 2.0.3
+ mdast-util-to-markdown: 2.1.2
+ parse-entities: 4.0.0
+ stringify-entities: 4.0.3
+ unist-util-visit-parents: 6.0.2
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/mdast': 3.0.15
@@ -16231,6 +16300,23 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ decode-named-character-reference: 1.0.2
+ devlop: 1.1.0
+ mdast-util-to-string: 4.0.0
+ micromark: 4.0.2
+ micromark-util-decode-numeric-character-reference: 2.0.2
+ micromark-util-decode-string: 2.0.1
+ micromark-util-normalize-identifier: 2.0.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+ unist-util-stringify-position: 4.0.0
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@types/mdast': 3.0.15
@@ -16289,6 +16375,11 @@ snapshots:
'@types/mdast': 3.0.15
unist-util-is: 5.2.0
+ dependencies:
+ '@types/mdast': 4.0.4
+ unist-util-is: 6.0.1
+
dependencies:
'@types/hast': 2.3.4
@@ -16311,10 +16402,26 @@ snapshots:
unist-util-visit: 4.1.2
zwitch: 2.0.4
+ dependencies:
+ '@types/mdast': 4.0.4
+ '@types/unist': 3.0.3
+ longest-streak: 3.1.0
+ mdast-util-phrasing: 4.1.0
+ mdast-util-to-string: 4.0.0
+ micromark-util-classify-character: 2.0.1
+ micromark-util-decode-string: 2.0.1
+ unist-util-visit: 5.1.0
+ zwitch: 2.0.4
+
dependencies:
'@types/mdast': 3.0.15
+ dependencies:
+ '@types/mdast': 4.0.4
+
@@ -16387,6 +16494,16 @@ snapshots:
micromark-util-symbol: 2.0.1
micromark-util-types: 2.0.2
+ dependencies:
+ devlop: 1.1.0
+ micromark-factory-space: 2.0.1
+ micromark-factory-whitespace: 2.0.1
+ micromark-util-character: 2.1.1
+ micromark-util-symbol: 2.0.1
+ micromark-util-types: 2.0.2
+ parse-entities: 4.0.0
+
dependencies:
fault: 2.0.1
@@ -16633,6 +16750,13 @@ snapshots:
micromark-util-decode-numeric-character-reference: 1.1.0
micromark-util-symbol: 1.1.0
+ dependencies:
+ decode-named-character-reference: 1.0.2
+ micromark-util-character: 2.1.1
+ micromark-util-decode-numeric-character-reference: 2.0.2
+ micromark-util-symbol: 2.0.1
+
@@ -18333,6 +18457,10 @@ snapshots:
+ dependencies:
+ '@types/unist': 3.0.3
+
dependencies:
'@types/unist': 2.0.6
@@ -18350,17 +18478,32 @@ snapshots:
dependencies:
'@types/unist': 2.0.6
+ dependencies:
+ '@types/unist': 3.0.3
+
dependencies:
'@types/unist': 2.0.6
unist-util-is: 5.2.0
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-is: 6.0.1
+
dependencies:
'@types/unist': 2.0.6
unist-util-is: 5.2.0
unist-util-visit-parents: 5.1.3
+ dependencies:
+ '@types/unist': 3.0.3
+ unist-util-is: 6.0.1
+ unist-util-visit-parents: 6.0.2
+
optional: true