Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Report anonymous MCP reliability issues (#6021)
Oleg Isonen8e7a8a21aa4a
diff --git a/apps/builder/app/env/env.server.ts b/apps/builder/app/env/env.server.tsindex 2154f59264..0ea6c17f33 100644--- a/apps/builder/app/env/env.server.ts+++ b/apps/builder/app/env/env.server.ts@@ -5,6 +5,8 @@ const environment = z.object({DEV_LOGIN: z.string().optional(),GH_CLIENT_ID: z.string().optional(),GH_CLIENT_SECRET: z.string().optional(),+ GITHUB_ISSUE_REPORT_APP_ID: z.string().optional(),+ GITHUB_ISSUE_REPORT_PRIVATE_KEY: z.string().optional(),GOOGLE_CLIENT_ID: z.string().optional(),GOOGLE_CLIENT_SECRET: z.string().optional(),@@ -85,6 +87,8 @@ const rawEnv = {DEV_LOGIN: process.env.DEV_LOGIN,GH_CLIENT_ID: process.env.GH_CLIENT_ID,GH_CLIENT_SECRET: process.env.GH_CLIENT_SECRET,+ GITHUB_ISSUE_REPORT_APP_ID: process.env.GITHUB_ISSUE_REPORT_APP_ID,+ GITHUB_ISSUE_REPORT_PRIVATE_KEY: process.env.GITHUB_ISSUE_REPORT_PRIVATE_KEY,GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,AUTH_SECRET: process.env.AUTH_SECRET,diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.tsindex c92672e34b..50ce4c5c8b 100644--- a/apps/builder/app/services/api-router.server.ts+++ b/apps/builder/app/services/api-router.server.ts@@ -46,6 +46,7 @@ import {publicApiContractVersion,publicApiOperationRequiresServerSupport,publicApiOperations,+ issueReportInput,} from "@webstudio-is/protocol";import {assertApiProjectPermit,@@ -84,6 +85,7 @@ import {} from "./api-runtime.server";import { createAssetClient } from "../shared/asset-client";import { previewProjectAssetQuery } from "./asset-query-preview.server";+import { publishConfiguredIssueReport } from "./github-issue-report.server";const assertApiPublishDomains = ({auth,@@ -690,6 +692,31 @@ export const apiRouter = router({),}),+ reports: router({+ issue: projectMutation(+ withProjectId(issueReportInput),+ "view",+ async ({ ctx, input }) => {+ const { projectId: _projectId, ...report } = input;+ return await publishConfiguredIssueReport({+ ...report,+ ...(report.runtime === undefined+ ? {}+ : {+ runtime: {+ ...report.runtime,+ ...(ctx.apiClient.version === undefined+ ? {}+ : { cliVersion: ctx.apiClient.version }),+ apiContractVersion: publicApiContractVersion,+ },+ }),+ });+ },+ { command: "report-issue", client: "reportIssue" }+ ),+ }),+build: router({get: projectQuery(buildGetInput,diff --git a/apps/builder/app/services/github-issue-report.server.test.ts b/apps/builder/app/services/github-issue-report.server.test.tsnew file mode 100644index 0000000000..cdb8369924--- /dev/null+++ b/apps/builder/app/services/github-issue-report.server.test.ts@@ -0,0 +1,156 @@+import { describe, expect, test } from "vitest";+import type { IssueReportInput } from "@webstudio-is/protocol";+import {+ createGitHubInstallationToken,+ formatIssueReport,+ publishIssueReport,+} from "./github-issue-report.server";++const report: IssueReportInput = {+ trigger: "automatic-friction",+ category: "schema-or-docs-mismatch",+ deduplicationKey: "update-props-input-contract",+ title: "fix: Clarify the update-props input contract",+ agent: {+ client: "Codex",+ clientVersion: "1.2.3",+ provider: "OpenAI",+ model: "gpt-5.6-sol",+ reasoningEffort: "medium",+ },+ runtime: {+ cliVersion: "1.2.3",+ nodeVersion: "22.14.0",+ os: "linux",+ osVersion: "6",+ architecture: "arm64",+ executionMode: "mcp",+ apiContractVersion: "public-api:client",+ },+ report: {+ userStory:+ "As a Webstudio user, I want routine MCP edits to complete without corrective retries.",+ summary: "A documented operation required a corrected retry.",+ attemptedWorkflow: ["Inspect the component.", "Attempt the update."],+ expectedBehavior: "The documented input should be accepted.",+ actualResult: "The initial call returned BAD_REQUEST.",+ recoveryAttempts: ["Inspect the schema and retry."],+ userImpact: "The edit required extra tool calls.",+ technicalContext: "The update-props input shape was ambiguous.",+ acceptanceCriteria: ["The documented input succeeds."],+ },+};++describe("GitHub issue reports", () => {+ test("formats the complete LLM-authored workflow and agent runtime", () => {+ const body = formatIssueReport(report);++ expect(body).toContain("## User story");+ expect(body).toContain(report.report.userStory);+ expect(body).toContain("## Expected behavior");+ expect(body).toContain(report.report.actualResult);+ expect(body).toContain("- Client: Codex 1.2.3");+ expect(body).toContain("- CLI: 1.2.3");+ expect(body).toContain("- Node.js: 22.14.0");+ expect(body).toContain("- Operating system: linux 6 (arm64)");+ expect(body).toContain("- Execution mode: mcp");+ expect(body).toContain("- API contract: public-api:client");+ expect(body).toContain("- Model: gpt-5.6-sol");+ expect(body).toContain("- Reasoning effort: medium");+ expect(body).toContain(+ "<!-- webstudio-issue-report:update-props-input-contract -->"+ );+ });++ test("discovers the repository installation before creating its token", async () => {+ const requests: Array<{ url: URL; init?: RequestInit }> = [];+ const request: typeof fetch = async (input, init) => {+ const url = new URL(input.toString());+ requests.push({ url, init });+ if (url.pathname === "/repos/webstudio-is/webstudio/installation") {+ return Response.json({ id: 123 });+ }+ return Response.json({ token: "installation-token" });+ };++ await expect(+ createGitHubInstallationToken({+ appId: "app-id",+ privateKey: "private-key",+ createJwt: () => "app-jwt",+ request,+ })+ ).resolves.toBe("installation-token");+ expect(requests.map(({ url }) => url.pathname)).toEqual([+ "/repos/webstudio-is/webstudio/installation",+ "/app/installations/123/access_tokens",+ ]);+ expect(requests[0]?.init?.headers).toMatchObject({+ Authorization: "Bearer app-jwt",+ });+ });++ test("returns an existing issue with the same deduplication key", async () => {+ const requests: URL[] = [];+ const request: typeof fetch = async (input) => {+ requests.push(new URL(input.toString()));+ return Response.json({+ items: [+ {+ number: 6020,+ html_url: "https://github.com/webstudio-is/webstudio/issues/6020",+ },+ ],+ });+ };++ await expect(+ publishIssueReport(report, {+ getInstallationToken: async () => "installation-token",+ request,+ })+ ).resolves.toEqual({+ status: "existing",+ issueNumber: 6020,+ issueUrl: "https://github.com/webstudio-is/webstudio/issues/6020",+ });+ expect(requests).toHaveLength(1);+ expect(requests[0]?.searchParams.get("q")).toContain(+ "webstudio-issue-report:update-props-input-contract"+ );+ });++ test("creates a new issue using only the authored report", async () => {+ const requests: Array<{ url: URL; init?: RequestInit }> = [];+ const request: typeof fetch = async (input, init) => {+ const url = new URL(input.toString());+ requests.push({ url, init });+ if (url.pathname === "/search/issues") {+ return Response.json({ items: [] });+ }+ return Response.json({+ number: 6021,+ html_url: "https://github.com/webstudio-is/webstudio/issues/6021",+ });+ };++ await expect(+ publishIssueReport(report, {+ getInstallationToken: async () => "installation-token",+ request,+ })+ ).resolves.toEqual({+ status: "created",+ issueNumber: 6021,+ issueUrl: "https://github.com/webstudio-is/webstudio/issues/6021",+ });+ const createRequest = requests[1];+ expect(createRequest?.url.pathname).toBe(+ "/repos/webstudio-is/webstudio/issues"+ );+ expect(JSON.parse(String(createRequest?.init?.body))).toEqual({+ title: report.title,+ body: formatIssueReport(report),+ });+ });+});diff --git a/apps/builder/app/services/github-issue-report.server.ts b/apps/builder/app/services/github-issue-report.server.tsnew file mode 100644index 0000000000..d80e9ac033--- /dev/null+++ b/apps/builder/app/services/github-issue-report.server.ts@@ -0,0 +1,243 @@+import { createSign } from "node:crypto";+import type {+ IssueReportInput,+ IssueReportResult,+} from "@webstudio-is/protocol";+import env from "~/env/env.server";++type GitHubIssue = {+ number: number;+ html_url: string;+};++type GitHubSearchResponse = {+ items?: GitHubIssue[];+};++const githubApiVersion = "2022-11-28";+const reportRepository = "webstudio-is/webstudio";++const getReportMarker = (deduplicationKey: string) =>+ `<!-- webstudio-issue-report:${deduplicationKey} -->`;++const formatItems = (items: readonly string[]) =>+ items.map((item, index) => `${index + 1}. ${item}`).join("\n");++export const formatIssueReport = ({+ agent,+ category,+ deduplicationKey,+ report,+ runtime,+ trigger,+}: IssueReportInput) => `${getReportMarker(deduplicationKey)}++## User story++${report.userStory}++## Summary++${report.summary}++## What the agent tried++${formatItems(report.attemptedWorkflow)}++## Expected behavior++${report.expectedBehavior}++## Actual result++${report.actualResult}++## Recovery attempts++${formatItems(report.recoveryAttempts)}++## User impact++${report.userImpact}++## Technical context++${report.technicalContext}++## Agent environment++- Client: ${agent.client}${agent.clientVersion === undefined ? "" : ` ${agent.clientVersion}`}+- Provider: ${agent.provider ?? "unknown"}+- Model: ${agent.model}+- Reasoning effort: ${agent.reasoningEffort}+- Trigger: ${trigger}+- Category: ${category}+${+ runtime === undefined+ ? ""+ : `+## Technical runtime++- CLI: ${runtime.cliVersion}+- Node.js: ${runtime.nodeVersion}+- Operating system: ${runtime.os} ${runtime.osVersion} (${runtime.architecture})+- Execution mode: ${runtime.executionMode}+- API contract: ${runtime.apiContractVersion}+`+}++## Acceptance criteria++${formatItems(report.acceptanceCriteria)}+`;++const requestGitHub = async <Result>({+ body,+ method,+ path,+ request,+ token,+}: {+ body?: object;+ method?: "GET" | "POST";+ path: string;+ request: typeof fetch;+ token: string;+}) => {+ const response = await request(new URL(path, "https://api.github.com"), {+ method,+ headers: {+ Accept: "application/vnd.github+json",+ Authorization: `Bearer ${token}`,+ "X-GitHub-Api-Version": githubApiVersion,+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),+ },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ if (response.ok === false) {+ throw new Error(+ `GitHub issue reporting failed with HTTP ${response.status}.`+ );+ }+ return (await response.json()) as Result;+};++const encodeJwtPart = (value: object) =>+ Buffer.from(JSON.stringify(value)).toString("base64url");++export const createGitHubAppJwt = ({+ appId,+ privateKey,+ now = Date.now(),+}: {+ appId: string;+ privateKey: string;+ now?: number;+}) => {+ const issuedAt = Math.floor(now / 1000) - 60;+ const unsignedToken = [+ encodeJwtPart({ alg: "RS256", typ: "JWT" }),+ encodeJwtPart({ iss: appId, iat: issuedAt, exp: issuedAt + 10 * 60 }),+ ].join(".");+ const signer = createSign("RSA-SHA256");+ signer.update(unsignedToken);+ signer.end();+ const signature = signer+ .sign(privateKey.split("\\n").join("\n"))+ .toString("base64url");+ return `${unsignedToken}.${signature}`;+};++export const createGitHubInstallationToken = async ({+ appId,+ createJwt = createGitHubAppJwt,+ privateKey,+ request = fetch,+}: {+ appId: string;+ createJwt?: typeof createGitHubAppJwt;+ privateKey: string;+ request?: typeof fetch;+}) => {+ const appJwt = createJwt({ appId, privateKey });+ const installation = await requestGitHub<{ id?: unknown }>({+ path: `/repos/${reportRepository}/installation`,+ request,+ token: appJwt,+ });+ if (typeof installation.id !== "number") {+ throw new Error("GitHub App installation was not found.");+ }+ const result = await requestGitHub<{ token?: unknown }>({+ method: "POST",+ path: `/app/installations/${installation.id}/access_tokens`,+ request,+ token: appJwt,+ });+ if (typeof result.token !== "string" || result.token.length === 0) {+ throw new Error("GitHub App did not return an installation token.");+ }+ return result.token;+};++export const publishIssueReport = async (+ input: IssueReportInput,+ {+ getInstallationToken,+ request = fetch,+ }: {+ getInstallationToken: () => Promise<string>;+ request?: typeof fetch;+ }+): Promise<IssueReportResult> => {+ const token = await getInstallationToken();+ const searchUrl = new URL("https://api.github.com/search/issues");+ searchUrl.searchParams.set(+ "q",+ `repo:${reportRepository} is:issue in:body "${getReportMarker(input.deduplicationKey)}"`+ );+ const search = await requestGitHub<GitHubSearchResponse>({+ path: `${searchUrl.pathname}${searchUrl.search}`,+ request,+ token,+ });+ const existing = search.items?.[0];+ if (existing !== undefined) {+ return {+ status: "existing",+ issueNumber: existing.number,+ issueUrl: existing.html_url,+ };+ }++ const created = await requestGitHub<GitHubIssue>({+ method: "POST",+ path: `/repos/${reportRepository}/issues`,+ request,+ token,+ body: {+ title: input.title,+ body: formatIssueReport(input),+ },+ });+ return {+ status: "created",+ issueNumber: created.number,+ issueUrl: created.html_url,+ };+};++export const publishConfiguredIssueReport = async (input: IssueReportInput) => {+ const appId = env.GITHUB_ISSUE_REPORT_APP_ID;+ const privateKey = env.GITHUB_ISSUE_REPORT_PRIVATE_KEY;+ if (appId === undefined || privateKey === undefined) {+ throw new Error("GitHub issue reporting is not configured.");+ }+ return await publishIssueReport(input, {+ getInstallationToken: async () =>+ await createGitHubInstallationToken({+ appId,+ privateKey,+ }),+ });+};diff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex 039c40ca11..077723b442 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -874,6 +874,42 @@ source of truth. For tools with no required arguments, pass `{}`.}```+### report-issue++```json+{+ "trigger": "user-requested",+ "category": "schema-or-docs-mismatch",+ "deduplicationKey": "update-props-input-contract",+ "title": "fix: Clarify the update-props input contract",+ "agent": {+ "client": "Codex",+ "provider": "OpenAI",+ "model": "gpt-5.6-sol",+ "reasoningEffort": "medium"+ },+ "report": {+ "userStory": "As a Webstudio user, I want routine MCP edits to complete without corrective retries.",+ "summary": "A documented operation required a corrected retry.",+ "attemptedWorkflow": [+ "Inspect the target component.",+ "Attempt the update with the advertised tool."+ ],+ "expectedBehavior": "The documented input should be accepted.",+ "actualResult": "The initial call returned BAD_REQUEST.",+ "recoveryAttempts": [+ "Inspect the schema and retry with corrected input nesting."+ ],+ "userImpact": "The edit required extra tool calls.",+ "technicalContext": "The update-props input shape was ambiguous.",+ "acceptanceCriteria": [+ "The exposed schema matches runtime validation.",+ "A regression test covers the workflow."+ ]+ }+}+```+### insert-component```jsondiff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex 8d95a0b4d8..c120926d83 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -10,7 +10,7 @@ export const cliDocs = {"manual-mcp":'# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag=\'h2\'>Northstar Product OS</ws.element><ws.element ws:tag=\'p\'>Reusable patterns for teams.</ws.element></ws.element>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<ws.element\n ws:tag="section"\n style={{ padding: 32, borderRadius: 16 }}\n>\n <ws.element ws:tag="h2">Operations Console</ws.element>\n <ws.element ws:tag="p">\n React-style object styles become editable Webstudio styles.\n </ws.element>\n</ws.element>\n\n<ws.element\n ws:tag="section"\n ws:tokens={[token("accent", css`color: #0f766e;`)]}\n>\n <ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </ws.element>\n</ws.element>\n\n<ws.element ws:tag="section">\n <radix.Switch>\n <radix.SwitchThumb />\n </radix.Switch>\n</ws.element>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\n- In `insert-fragment` JSX, use ``ws:style={css`...`}`` for Webstudio-native CSS, or use React-style object syntax such as `style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- 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\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',"mcp-startup-epilogue":- 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag=\'h2\'>Launch Kit</ws.element><ws.element ws:tag=\'p\'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag=\'button\'>Get started</ws.element></ws.element>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get-more-tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nIf a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',+ 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag=\'h2\'>Launch Kit</ws.element><ws.element ws:tag=\'p\'>A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag=\'button\'>Get started</ws.element></ws.element>"\n}\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get-more-tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nWhen `report-issue` is available, use it when the user explicitly asks to report a problem. Also use it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. Write a complete anonymous report with the generalized user story, attempted workflow, expected behavior, actual result, recovery attempts, impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, exact unique values, or raw contextual tool data.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',"mcp-vision":'# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n\n## Visual Verification Rule\n\nFor visual/design work, use `preview.start` and `screenshot({ path })` so vision can inspect the current MCP session before finishing and verify that generated project files are current. Iterative preview is the default: it keeps one generated-site server and browser alive, regenerates changed files, and performs an ordinary page reload without Vite HMR. Use `mode: "production"` only for release-like verification; rendered audit selects it automatically. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\nAn authenticated project share URL is used with `webstudio init --link`; it is\nnot a generated-site preview URL. Project screenshots and rendered audits use\nthe generated local preview owned by the current CLI/MCP process. Do not pass a\nBuilder/share URL to `screenshot`, even without query parameters. Use `path`\nafter starting preview, or use `baseUrl` only for an intentional generated site\nthat is already running. Path captures verify the generated-site root marker\nand fail instead of returning a screenshot of Builder chrome.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Call preview.start once to keep the iterative generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate the current session in place, wait for its exact project version, and normally reload the route. The server and browser remain alive. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running generated site without starting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing. Use mode: "production" only for release-like verification.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Inspect every PNG with vision before finishing. Use mode: "production" only for release-like verification.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, call preview.start once, then use screenshot({ path, viewport }) for fast repeated checks across multiple pages. Iterative mode is the default: after MCP mutations, path screenshots regenerate changed files and reload the requested route while keeping the server and browser alive. Use mode: "production" only for release-like verification. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',} as const;diff --git a/packages/cli/src/docs/mcp-startup-epilogue.md b/packages/cli/src/docs/mcp-startup-epilogue.mdindex f43f977921..c8af195cf0 100644--- a/packages/cli/src/docs/mcp-startup-epilogue.md+++ b/packages/cli/src/docs/mcp-startup-epilogue.md@@ -49,6 +49,6 @@ The server advertises MCP `logging` capability and sends sparse `notifications/m`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.-If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.+When `report-issue` is available, use it when the user explicitly asks to report a problem. Also use it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. Write a complete anonymous report with the generalized user story, attempted workflow, expected behavior, actual result, recovery attempts, impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, exact unique values, or raw contextual tool data.If you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.tsindex 06b7a5111d..ec5ccbfea7 100644--- a/packages/cli/src/project-session.test.ts+++ b/packages/cli/src/project-session.test.ts@@ -10,6 +10,7 @@ import {createCliProjectRestorePointStorage,createCliProjectSessionStorage,createCliProjectSessionTransport,+ addIssueReportRuntime,getCliServerApiContract,getCliProjectSessionFile,getCliProjectRestorePointsFile,@@ -17,6 +18,25 @@ import {loadCliProjectSessionAssetIndex,} from "./project-session";+test("adds anonymous local runtime metadata only to issue reports", () => {+ const report = { title: "test: Report transport" };+ const runtime = {+ cliVersion: "1.2.3",+ nodeVersion: "22.14.0",+ os: "linux",+ osVersion: "6",+ architecture: "arm64",+ executionMode: "mcp" as const,+ apiContractVersion: "public-api:client",+ };++ expect(addIssueReportRuntime("report-issue", report, runtime)).toEqual({+ ...report,+ runtime,+ });+ expect(addIssueReportRuntime("audit", report, runtime)).toBe(report);+});+test("scopes project session files for explicitly selected projects", () => {expect(getCliProjectSessionFile("/workspace", "project/a")).toBe("/workspace/.webstudio/projects/project%2Fa/project-session.json"diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.tsindex 26b4c65959..da73f3231c 100644--- a/packages/cli/src/project-session.ts+++ b/packages/cli/src/project-session.ts@@ -1,4 +1,5 @@import { rm } from "node:fs/promises";+import { release } from "node:os";import { join } from "node:path";import { cwd } from "node:process";import { parseContentDatabaseMaxBytes } from "@webstudio-is/content-engine";@@ -14,8 +15,10 @@ import {publicApiContractVersion,publicApiOperationRequiresServerSupport,publicApiOperations,+ type IssueReportRuntime,type PublishedProjectBundle,} from "@webstudio-is/protocol";+import packageJson from "../package.json";import {createReachableAssetContentCompilationPlan,getHomePage,@@ -224,6 +227,27 @@ const publicOperationById = new Map(publicApiOperations.map((operation) => [operation.id, operation]));+const getIssueReportRuntime = (): IssueReportRuntime => ({+ cliVersion: packageJson.version,+ nodeVersion: process.versions.node,+ os: process.platform,+ osVersion: release().split(".")[0] ?? "unknown",+ architecture: process.arch,+ executionMode: "mcp",+ apiContractVersion: publicApiContractVersion,+});++export const addIssueReportRuntime = (+ operationId: string,+ input: unknown,+ runtime: IssueReportRuntime = getIssueReportRuntime()+) => {+ if (operationId !== "report-issue" || isPlainRecord(input) === false) {+ return input;+ }+ return { ...input, runtime };+};+const executePublicServerOperation = async ({connection,operationId,@@ -247,7 +271,7 @@ const executePublicServerOperation = async ({}return await client({...connection,- ...(input as Record<string, unknown>),+ ...(addIssueReportRuntime(operationId, input) as Record<string, unknown>),projectId: connection.projectId,});};diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 9760dc7569..0a3d4e3c5c 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -44,6 +44,8 @@ import {isPublicApiRemoteErrorCode,type PublishedProjectBundle,type PublicApiCommand,+ type IssueReportInput,+ type IssueReportResult,} from "@webstudio-is/protocol";export { getBundleVersion, bundleVersion } from "@webstudio-is/protocol";export { parseBuilderUrl } from "@webstudio-is/protocol";@@ -1462,6 +1464,11 @@ export const audit = projectQueryInput<AuthProjectParams & Record<string, unknown>>("audit");+export const reportIssue = projectMutationInput<+ AuthProjectParams & IssueReportInput,+ IssueReportResult+>("report-issue");+export const verifyBindings = projectQueryInput<AuthProjectParams & PaginatedQueryInput & Record<string, unknown>>("verify-bindings");diff --git a/packages/project-build/src/docs.generated.ts b/packages/project-build/src/docs.generated.tsindex 9fdd7e289f..fe9ca031fd 100644--- a/packages/project-build/src/docs.generated.ts+++ b/packages/project-build/src/docs.generated.ts@@ -6,7 +6,7 @@ export const projectBuildDocs = {expressions:'# Webstudio Expressions\n\nUse an expression only when a value must be computed at runtime from scoped\ndata. Use direct text and direct prop values for fixed content.\n\n## Source Format\n\nExpression-capable MCP fields receive JavaScript expression source as a JSON\nstring. Send one expression, without a `return` statement or surrounding\nfunction. For example:\n\n```json\n{ "binding": { "type": "expression", "value": "post.title ?? \\"Untitled\\"" } }\n```\n\nInside that string, use readable JavaScript syntax rather than serialized JSON.\nFor object expressions, leave identifier property names unquoted, for example\n`{ query: queryText, variables: { slug: system.params.slug } }`. Quote a property\nname only when JavaScript requires it, such as `{ "published-at": date }`. Do\nnot pass a JSON-stringified object as an expression.\n\nDo not send a fixed prop string as an expression. Use `update-props` with\n`type:"string"`. Page metadata and resource URLs accept plain fixed strings and\nnormalize them for storage. Expression-only resource headers, search parameters,\nand bodies accept `{ "type": "literal", "value": "fixed text" }` when the\nvalue is not dynamic.\n\n## Scope\n\n- Data variables are available on their scope instance and descendants.\n- An inner variable with the same name masks the outer variable.\n- A scoped resource result is a variable. Read its payload from its result\n wrapper, usually `resourceName.data`; APIs may nest the desired value deeper.\n- Collection creates internal `collectionItem` and `collectionItemKey`\n parameters. They are available only to that Collection\'s descendants.\n Preserve those generated parameters and do not reuse encoded parameter ids\n copied from another Collection.\n- Array Collection iteration exposes the current item. Object iteration exposes\n the current key and value.\n- The built-in `system` context is available only where supplied by the runtime.\n Its documented fields are `system.origin`, `system.pathname`, `system.params`,\n and `system.search`. There is no `system.path`.\n- Actions expose only their declared arguments, such as `event`, plus data that\n is in scope.\n\nRead `list-variables`, `list-resources`, `inspect-instance`, and existing\nbindings before writing an expression. Do not guess identifier names. Syntax is\nvalidated when a mutation is submitted. A valid expression that references an\nidentifier unavailable in that scope is accepted with a structured warning\ncontaining the field path, source range, affected record, and remediation.\n\n## Supported Syntax\n\nExpressions support literals, arrays, objects, property and index access,\noptional chaining, unary and arithmetic operators, comparisons, logical\noperators, nullish coalescing, ternaries, and template literals.\n\nSupported string methods:\n\n{{allowedStringMethods}}\n\nSupported array methods:\n\n{{allowedArrayMethods}}\n\nOther values support `toString`. Arbitrary global functions and arbitrary\nmethod calls are not supported.\n\n## Unsupported Syntax\n\nDo not use statements, declarations, functions, arrow functions, classes,\n`new`, `this`, `await`, imports, tagged templates, sequence expressions,\nincrement/decrement, or destructuring assignment. Assignment is allowed only\ninside actions. Use an explicit assignment there rather than `++` or `--`.\n\n## Common Examples\n\n- Text: `post.title ?? "Untitled"`\n- Prop: `post.url`\n- Nested API array for Collection: `posts.data.items`\n- Resource URL: `"https://api.example.com/posts?tag=" + filters.tag`\n- Header: `"Bearer " + auth.token`\n- Search parameter: `String(filters.page ?? 1)` is not supported because global\n function calls are forbidden; use `(filters.page ?? 1).toString()` instead.\n- Resource body: `{ query: queryText, variables: { slug: system.params.slug } }`\n- Conditional: `featured ? "Featured" : "Standard"`\n- Safe nested access: `post.author?.name ?? "Unknown author"`\n\n## Collections\n\nWhenever an array or object should render repeated UI, call `insert-collection`\nwith the complete iterable and one repeated-item JSX root. Do not pass the\nresponse wrapper or one indexed item. The command creates the Collection and\nits private item parameters atomically, then renders the item root once per\nentry. Bind descendants with expressions such as `collectionItem.name`; for\nobject iteration, `collectionItemKey` contains the current key. Wrap multiple\nrepeated siblings in one `ws.element` root.\n\n## Verification\n\nInspect every returned expression warning. Correct warnings that indicate a\nmisspelled or unavailable variable, then run `verify-bindings` for persisted\nsyntax, scope, and reference integrity. A warning does not roll back the\nmutation, and successful static verification does not prove runtime data has\nthe expected shape. `verify-bindings` never executes external resources or\nresolves rendered values. Preview representative data, empty/null data, and\nCollection item counts; use `audit` for relevant structural findings.\n',"mcp-startup-guidance":- 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get-more-tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get-more-tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.\n',+ 'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get-more-tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get-more-tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.\n\nWhen `report-issue` is available and the user explicitly asks to report a problem, call it once without requiring a GitHub login. Also call it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. The LLM must write a complete anonymous technical report with the generalized user story, summary, attempted workflow, expected behavior, actual result, recovery attempts, user impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, or exact unique values. Do not copy raw tool inputs, outputs, or contextual errors; preserve only stable tool names, schema fields, error codes, CLI versions, and generalized input shapes. Use `unknown` instead of guessing unavailable model metadata.\n',} as const;export type ProjectBuildDocName = keyof typeof projectBuildDocs;diff --git a/packages/project-build/src/docs/mcp-startup-guidance.md b/packages/project-build/src/docs/mcp-startup-guidance.mdindex d6d72a181d..f24823ab0e 100644--- a/packages/project-build/src/docs/mcp-startup-guidance.md+++ b/packages/project-build/src/docs/mcp-startup-guidance.md@@ -1 +1,3 @@If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output. Before editing a Webstudio project, do one small discovery step, then act. For delegated design-system or “use every component” tasks, the first MCP command is `workflow.next {"goal":"design-system-page"}`; report that returned checkpoint to the parent/user and stop until continued. For a simple authored/styled section, the intended path is literal: call `meta.index`, call `meta.get-more-tools` with `{"tools":["insert-fragment"]}`, read the target parent id with `list-pages`/`get-page-by-path`/`list-instances` only if needed, then call `insert-fragment`. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. Do not grep source files, dump full MCP resources, or write parser scripts before trying focused MCP calls. Good first calls are `meta.index` for orientation, `meta.guide` for a goal workflow, `workflow.next` for one bounded delegated phase, `meta.get-more-tools` for exact tool schemas, and `components.coverage-plan`, `components.coverage-insert-next`, `components.find`, or `components.get` for component work. Do not call every discovery tool up front. For delegated or non-streaming agents whose parent cannot see live stderr/stdout, treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report its command/result, and wait for the parent before the next MCP command. Do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands; they hide progress from the parent. Do not take a broad task such as creating a full design-system page as one execution unit. Instead call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint to the parent, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For design-system or “use every component” tasks, start with `workflow.next`, acknowledge its checkpoint only after parent/user continuation, then run compact `components.coverage-plan`, checkpoint, create the page, checkpoint, then call `components.coverage-insert-next` once per coverage checkpoint, and finish with the `presentation-pass` workflow phase. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world design-system examples instead of raw unstyled component dumps. Request component coverage details with `components.coverage-plan {"detail":"roots"}` or `components.coverage-plan {"detail":"parts"}` only when needed. `list-pages` does not accept `detail`; use `list-pages {}` or `get-page-by-path` for page lookup. Read overview resources such as `webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview` only when focused tools are insufficient. Do not dump or parse full resources such as `webstudio://project/tools` or `webstudio://project/components` unless the focused tools are insufficient. Run one-shot shortcut or explicit `webstudio mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. For experiments, pass `--dry-run` to local-capable mutations. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project. If a one-shot call returns checkpoint.required, the CLI persists `CHECKPOINT_REQUIRED` across later one-shot calls until you report the checkpoint, wait until continued, and call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially. Complete one bounded phase and return a checkpoint before continuing. Follow the guide: read ids and Builder breakpoints first, use focused component discovery for component ids, props, and content model composition, prefer semantic tools over `apply-patch`, use direct value tools for fixed text/props, use bindings only for dynamic expressions/resources/actions, page metadata and fixed resource URLs accept plain strings, put page/resource update fields under `values`, do not edit generated files for normal content/design changes, and use `preview.start` plus screenshot/vision for visual work.++When `report-issue` is available and the user explicitly asks to report a problem, call it once without requiring a GitHub login. Also call it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. The LLM must write a complete anonymous technical report with the generalized user story, summary, attempted workflow, expected behavior, actual result, recovery attempts, user impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, or exact unique values. Do not copy raw tool inputs, outputs, or contextual errors; preserve only stable tool names, schema fields, error codes, CLI versions, and generalized input shapes. Use `unknown` instead of guessing unavailable model metadata.diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex 4f43fba34c..cca198fe70 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -1841,6 +1841,40 @@ export const mcpArgumentExamples: Record<{ pagePath: "/pricing", severities: ["error", "warning"] },{ scopes: ["accessibility"], verbose: true },],+ "report-issue": [+ {+ trigger: "user-requested",+ category: "schema-or-docs-mismatch",+ deduplicationKey: "update-props-input-contract",+ title: "fix: Clarify the update-props input contract",+ agent: {+ client: "Codex",+ provider: "OpenAI",+ model: "gpt-5.6-sol",+ reasoningEffort: "medium",+ },+ report: {+ userStory:+ "As a Webstudio user, I want routine MCP edits to complete without corrective retries.",+ summary: "A documented operation required a corrected retry.",+ attemptedWorkflow: [+ "Inspect the target component.",+ "Attempt the update with the advertised tool.",+ ],+ expectedBehavior: "The documented input should be accepted.",+ actualResult: "The initial call returned BAD_REQUEST.",+ recoveryAttempts: [+ "Inspect the schema and retry with corrected input nesting.",+ ],+ userImpact: "The edit required extra tool calls.",+ technicalContext: "The update-props input shape was ambiguous.",+ acceptanceCriteria: [+ "The exposed schema matches runtime validation.",+ "A regression test covers the workflow.",+ ],+ },+ },+ ],"insert-component": [{parentInstanceId: "parent-id",@@ -3546,6 +3580,11 @@ const capabilityAreas = ["inspect",],},+ {+ area: "reporting",+ goal: "Report anonymous, actionable CLI and MCP product issues without requiring the user to authenticate with GitHub.",+ tools: ["report-issue"],+ },{area: "project-lifecycle",goal: "Refresh local project state and move synced project bundles between projects.",diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.tsindex 457e7e07ce..b8871ec3bb 100644--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts@@ -70,6 +70,229 @@ export const serverOnlyRouterOperationMetadata = {required: ["acknowledgePublicSubmission"],},},+ "reports.issue": {+ id: "reports.issue",+ command: "report-issue",+ method: "mutation",+ path: "api.reports.issue",+ client: "reportIssue",+ permit: "view",+ inputSchema: {+ type: "object",+ properties: {+ trigger: {+ type: "string",+ enum: ["user-requested", "automatic-friction"],+ },+ category: {+ type: "string",+ enum: [+ "tool-failure",+ "incorrect-result",+ "schema-or-docs-mismatch",+ "documented-recovery-failed",+ "undocumented-workaround",+ "hang-or-crash",+ "feature-request",+ "other",+ ],+ },+ deduplicationKey: {+ type: "string",+ minLength: 3,+ maxLength: 160,+ pattern: "^[a-z0-9]+(?:[.-][a-z0-9]+)*$",+ description:+ "Stable lowercase anonymous technical slug without user, project, resource, or domain identifiers.",+ },+ title: {+ type: "string",+ minLength: 1,+ maxLength: 160,+ },+ agent: {+ type: "object",+ properties: {+ client: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ clientVersion: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ provider: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ model: {+ type: "string",+ minLength: 1,+ maxLength: 200,+ },+ reasoningEffort: {+ type: "string",+ enum: [+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ "ultra",+ "unknown",+ ],+ },+ },+ required: ["client", "model", "reasoningEffort"],+ additionalProperties: false,+ },+ runtime: {+ type: "object",+ properties: {+ cliVersion: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ nodeVersion: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ os: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ osVersion: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ architecture: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ executionMode: {+ type: "string",+ enum: ["mcp"],+ },+ apiContractVersion: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ },+ required: [+ "cliVersion",+ "nodeVersion",+ "os",+ "osVersion",+ "architecture",+ "executionMode",+ "apiContractVersion",+ ],+ additionalProperties: false,+ description:+ "Anonymous CLI-collected runtime metadata without host, user, path, environment, network, location, project, or argument data.",+ },+ report: {+ type: "object",+ properties: {+ userStory: {+ type: "string",+ minLength: 1,+ maxLength: 4000,+ },+ summary: {+ type: "string",+ minLength: 1,+ maxLength: 4000,+ },+ attemptedWorkflow: {+ minItems: 1,+ maxItems: 20,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ maxLength: 4000,+ },+ },+ expectedBehavior: {+ type: "string",+ minLength: 1,+ maxLength: 4000,+ },+ actualResult: {+ type: "string",+ minLength: 1,+ maxLength: 4000,+ },+ recoveryAttempts: {+ minItems: 1,+ maxItems: 20,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ maxLength: 4000,+ },+ },+ userImpact: {+ type: "string",+ minLength: 1,+ maxLength: 4000,+ },+ technicalContext: {+ type: "string",+ minLength: 1,+ maxLength: 4000,+ },+ acceptanceCriteria: {+ minItems: 1,+ maxItems: 20,+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ maxLength: 4000,+ },+ },+ },+ required: [+ "userStory",+ "summary",+ "attemptedWorkflow",+ "expectedBehavior",+ "actualResult",+ "recoveryAttempts",+ "userImpact",+ "technicalContext",+ "acceptanceCriteria",+ ],+ additionalProperties: false,+ },+ },+ required: [+ "trigger",+ "category",+ "deduplicationKey",+ "title",+ "agent",+ "report",+ ],+ additionalProperties: false,+ description:+ "Anonymous LLM-authored technical report. Generalize context, exclude all identifying or project-specific data, and preserve only stable tool, schema, error, version, and input-shape details.",+ },+ },"build.get": {id: "build.get",command: "snapshot",diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.tsindex 8ba35c9b73..4423c31b24 100644--- a/packages/protocol/src/builder-api/operation-docs.ts+++ b/packages/protocol/src/builder-api/operation-docs.ts@@ -313,6 +313,14 @@ const curatedPublicApiOperationDocumentation = ['MCP tool: audit {"scopes":["craft"],"verbose":true}',],},+ {+ command: "report-issue",+ description:+ "Create or deduplicate a structured anonymous LLM-authored issue after an explicit request or qualifying MCP friction. Exclude all identifying and project-specific data.",+ examples: [+ 'MCP tool: report-issue {"trigger":"user-requested","category":"schema-or-docs-mismatch","deduplicationKey":"update-props-input-contract","title":"fix: Clarify the update-props input contract","agent":{"client":"Codex","provider":"OpenAI","model":"gpt-5.6-sol","reasoningEffort":"medium"},"report":{"userStory":"As a Webstudio user, I want routine MCP edits to complete without corrective retries.","summary":"A documented operation required a corrected retry.","attemptedWorkflow":["Inspect the target component.","Attempt the update with the advertised tool."],"expectedBehavior":"The documented input should be accepted.","actualResult":"The initial call returned BAD_REQUEST.","recoveryAttempts":["Inspect the schema and retry with corrected input nesting."],"userImpact":"The edit required extra tool calls.","technicalContext":"The update-props input shape was ambiguous.","acceptanceCriteria":["The exposed schema matches runtime validation.","A regression test covers the workflow."]}}',+ ],+ },{command: "verify-bindings",description:diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex a2a274783c..371578a0c7 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -9,3 +9,4 @@ export * from "./builder-api/errors";export * from "./builder-api/runtime-contracts";export * from "./builder-api/operations";export * from "./builder-api/url";+export * from "./issue-report";diff --git a/packages/protocol/src/issue-report.test.ts b/packages/protocol/src/issue-report.test.tsnew file mode 100644index 0000000000..669b3bc724--- /dev/null+++ b/packages/protocol/src/issue-report.test.ts@@ -0,0 +1,72 @@+import { describe, expect, test } from "vitest";+import { issueReportInput } from "./issue-report";++const report = {+ trigger: "user-requested",+ category: "schema-or-docs-mismatch",+ deduplicationKey: "update-props-input-contract",+ title: "fix: Clarify the update-props input contract",+ agent: {+ client: "Codex",+ provider: "OpenAI",+ model: "gpt-5.6-sol",+ reasoningEffort: "medium",+ },+ runtime: {+ cliVersion: "1.2.3",+ nodeVersion: "22.14.0",+ os: "linux",+ osVersion: "6",+ architecture: "arm64",+ executionMode: "mcp",+ apiContractVersion: "public-api:client",+ },+ report: {+ userStory:+ "As a Webstudio user, I want an agent to update component properties through MCP so routine edits complete without corrective retries.",+ summary:+ "A property update required multiple attempts because the initially inferred input shape was rejected.",+ attemptedWorkflow: [+ "Inspect the target component.",+ "Attempt the property update with the advertised tool.",+ ],+ expectedBehavior:+ "The exposed contract should make the accepted input structure unambiguous.",+ actualResult:+ "The first call returned BAD_REQUEST and required separate schema inspection.",+ recoveryAttempts: [+ "Inspect the tool contract and retry with corrected input nesting.",+ ],+ userImpact: "A routine edit required extra discovery and tool calls.",+ technicalContext:+ "The problem involved update-props input validation and the values field.",+ acceptanceCriteria: [+ "The exposed schema matches runtime validation.",+ "A regression test covers the corrected workflow.",+ ],+ },+} as const;++describe("issue report contract", () => {+ test("accepts a complete anonymous LLM-authored report", () => {+ expect(issueReportInput.parse(report)).toEqual(report);+ });++ test("requires every user-workflow section", () => {+ const { expectedBehavior: _expectedBehavior, ...incomplete } =+ report.report;++ expect(() =>+ issueReportInput.parse({ ...report, report: incomplete })+ ).toThrow();+ });++ test("restricts deduplication keys to anonymous technical slugs", () => {+ expect(() =>+ issueReportInput.parse({+ ...report,+ deduplicationKey: "project/[email protected]",+ })+ ).toThrow();+ });+});diff --git a/packages/protocol/src/issue-report.ts b/packages/protocol/src/issue-report.tsnew file mode 100644index 0000000000..de724a001e--- /dev/null+++ b/packages/protocol/src/issue-report.ts@@ -0,0 +1,103 @@+import { z } from "zod";++const issueReportTrigger = z.enum(["user-requested", "automatic-friction"]);++const issueReportCategory = z.enum([+ "tool-failure",+ "incorrect-result",+ "schema-or-docs-mismatch",+ "documented-recovery-failed",+ "undocumented-workaround",+ "hang-or-crash",+ "feature-request",+ "other",+]);++const issueReportReasoningEffort = z.enum([+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ "ultra",+ "unknown",+]);++const reportText = z.string().trim().min(1).max(4_000);+const reportItems = z.array(reportText).min(1).max(20);++const issueReportAgent = z+ .object({+ client: z.string().trim().min(1).max(100),+ clientVersion: z.string().trim().min(1).max(100).optional(),+ provider: z.string().trim().min(1).max(100).optional(),+ model: z.string().trim().min(1).max(200),+ reasoningEffort: issueReportReasoningEffort,+ })+ .strict();++const issueReportRuntime = z+ .object({+ cliVersion: z.string().trim().min(1).max(100),+ nodeVersion: z.string().trim().min(1).max(100),+ os: z.string().trim().min(1).max(100),+ osVersion: z.string().trim().min(1).max(100),+ architecture: z.string().trim().min(1).max(100),+ executionMode: z.enum(["mcp"]),+ apiContractVersion: z.string().trim().min(1).max(100),+ })+ .strict()+ .describe(+ "Anonymous CLI-collected runtime metadata without host, user, path, environment, network, location, project, or argument data."+ );++const issueReportContent = z+ .object({+ userStory: reportText,+ summary: reportText,+ attemptedWorkflow: reportItems,+ expectedBehavior: reportText,+ actualResult: reportText,+ recoveryAttempts: reportItems,+ userImpact: reportText,+ technicalContext: reportText,+ acceptanceCriteria: reportItems,+ })+ .strict();++export const issueReportInput = z+ .object({+ trigger: issueReportTrigger,+ category: issueReportCategory,+ deduplicationKey: z+ .string()+ .trim()+ .min(3)+ .max(160)+ .regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/)+ .describe(+ "Stable lowercase anonymous technical slug without user, project, resource, or domain identifiers."+ ),+ title: z.string().trim().min(1).max(160),+ agent: issueReportAgent,+ runtime: issueReportRuntime.optional(),+ report: issueReportContent,+ })+ .strict()+ .describe(+ "Anonymous LLM-authored technical report. Generalize context, exclude all identifying or project-specific data, and preserve only stable tool, schema, error, version, and input-shape details."+ );++export const issueReportResult = z+ .object({+ status: z.enum(["created", "existing"]),+ issueNumber: z.number().int().positive(),+ issueUrl: z.string().url(),+ })+ .strict();++export type IssueReportInput = z.infer<typeof issueReportInput>;+export type IssueReportResult = z.infer<typeof issueReportResult>;+export type IssueReportRuntime = z.infer<typeof issueReportRuntime>;