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
import {
builderNamespaces,
restorePointNamespaces,
type BuilderNamespace,
} from "./contracts/namespaces";
import {
getInputJsonSchemaMetadata,
getInputJsonSchemaProperties,
getFileExtension,
getComponentJsxName,
inputJsonSchemaAcceptsType,
parseComponentName,
toInputJsonSchemaObject,
type WsComponentMeta,
type ContentBlockDiagnostic,
type InputJsonSchema,
type InputJsonSchemaValue,
} from "@webstudio-is/sdk";
import {
allowedArrayMethods,
allowedStringMethods,
} from "@webstudio-is/expression";
import {
isMdxTemplateComponentName,
type TextAssetSourceDiagnostic,
} from "@webstudio-is/content-engine/mdx";
import { validateAssetQuery } from "@webstudio-is/content-engine";
import { distance as getLevenshteinDistance } from "fastest-levenshtein";
import type { BuilderApiCapability } from "./contracts/permissions";
import path from "node:path";
import { Transform } from "node:stream";
import {
projectSessionRestorePointSummarySchema,
projectSessionBusyMessage,
serializeProjectSessionMeta,
type ProjectSessionEnvelope,
type ProjectSessionRestorePointSummary,
} from "./project-session";
import type {
ScreenshotDiffResult,
ScreenshotVisualExpectation,
} from "@webstudio-is/vision/diff";
import { isScreenshotVisualExpectation } from "@webstudio-is/vision/diff";
import { isPlainRecord, isRecord } from "./shared/type-utils";
import {
augmentAuditWithRenderedChecks,
type RenderedAuditArtifactManifest,
} from "./mcp-rendered-audit";
import {
defaultScreenshotTimeout,
defaultScreenshotWaitForTimeout,
defaultScreenshotWaitUntil,
isScreenshotBrowser,
isScreenshotWaitUntil,
screenshotBrowserChoices,
screenshotWaitUntilValues,
type BrowserScreenshotLayout,
type BrowserScreenshotNavigation,
type BrowserScreenshotTimings,
type ScreenshotCaptureOptions,
} from "@webstudio-is/vision/browser";
import {
projectPreviewModes,
projectPreviewSources,
type ProjectPreviewMode,
type ProjectPreviewSource,
} from "./preview";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import {
CallToolRequestSchema,
LoggingMessageNotificationSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
import { readProjectBuildDoc } from "./docs";
import type { ComponentTemplateRegistry } from "./runtime/component-template";
import {
getComponentCatalogSources,
getComponentTemplates,
} from "./runtime/component-templates";
import {
getTemplateRequiredStructure,
insertFragmentInput,
parseComponentEdge,
} from "./runtime/components";
import { getInputSchemaMetadata } from "./contracts/input-schema";
import { insertCollectionInput } from "./runtime/collection";
import {
isComponentAvailableForDocumentType,
isComponentHiddenFromCatalog,
isComponentMetaUnavailableInCatalog,
listComponentRegistryItems,
type ComponentRegistryItem,
} from "./runtime/component-catalog";
import { parseWebstudioJsxFragment } from "./runtime/jsx";
import { webstudioJsxFragmentInputDescription } from "./runtime/jsx/bindings";
import {
formatValidationErrorMessage,
getValidationIssues,
getZodValidationIssues,
semanticValidationIssuesJsonSchema,
throwBuilderValidationError,
type SemanticValidationIssue,
} from "./runtime/errors";
import { z } from "zod";
import {
createConfirmationToken,
getConfirmationTokenInvalidReason,
validateConfirmationToken,
} from "./confirmation-token";
type PublicMcpOperationMethod = "query" | "mutation";
type PublicMcpOperationPermit = BuilderApiCapability;
export type PublicMcpOperation<Command extends string = string> = {
command: Command;
id: string;
method: PublicMcpOperationMethod;
permit: PublicMcpOperationPermit;
description: string;
inputSchema: InputJsonSchema;
outputSchema?: InputJsonSchema;
requiredOptions?: readonly string[];
examples?: readonly string[];
localCapable: boolean;
serverOnly: boolean;
readNamespaces: readonly string[];
writeNamespaces: readonly string[];
invalidatesNamespaces: readonly string[];
retryOnConflict: boolean;
requiresConfirm: boolean;
};
type ProjectSessionLike = {
initialize: () => Promise<ProjectSessionEnvelope>;
refresh: (
namespaces: readonly BuilderNamespace[]
) => Promise<ProjectSessionEnvelope>;
reset: () => Promise<ProjectSessionEnvelope>;
};
type CreateProjectSession = () => ProjectSessionLike;
type ExecuteMcpOperation<Command extends string = string> = (options: {
command: Command;
input: unknown;
dryRun: boolean;
}) => Promise<ProjectSessionEnvelope>;
export type McpErrorCodeResolver = (error: unknown) => string | undefined;
export type McpTransport = Transport;
type McpLogLevel = "info" | "error";
export const projectSessionPreviewSources = projectPreviewSources;
export type ProjectSessionPreviewSource = ProjectPreviewSource;
export const projectSessionPreviewModes = projectPreviewModes;
export type ProjectSessionPreviewMode = ProjectPreviewMode;
type ProjectSessionScreenshotNavigation = Omit<
BrowserScreenshotNavigation,
"pageMetadata"
> & {
generatedSiteRootPresent: boolean;
projectId?: string;
projectVersion?: number;
};
export type ProjectSessionScreenshotInput = ScreenshotCaptureOptions & {
url?: string;
baseUrl?: string;
path?: string;
imageDomains?: string[];
source?: ProjectSessionPreviewSource;
mode?: ProjectSessionPreviewMode;
};
type ProjectSessionScreenshotLayout = Omit<
BrowserScreenshotLayout,
"navigation"
> & {
navigation?: ProjectSessionScreenshotNavigation;
};
export type ProjectSessionScreenshotResult = {
output: string;
browserPath: string;
browser: "chromium" | "chrome" | "edge" | "brave";
viewport: {
width: number;
height: number;
};
fullPage: boolean;
elapsedMs: number;
warnings: readonly string[];
previewMode?: ProjectSessionPreviewMode;
renderedProjectId?: string;
renderedProjectVersion?: number;
lifecycleTimings?: {
previewRefreshMs: number;
captureMs: number;
totalMs: number;
};
timings?: BrowserScreenshotTimings;
navigation?: ProjectSessionScreenshotNavigation;
layout?: ProjectSessionScreenshotLayout;
};
type McpToolProgress = {
report: (message: string) => void;
};
type CaptureScreenshot = (
input: ProjectSessionScreenshotInput,
progress?: McpToolProgress
) => Promise<ProjectSessionScreenshotResult>;
type CapturePageScreenshots = (
inputs: readonly ProjectSessionScreenshotInput[],
progress?: McpToolProgress
) => Promise<ProjectSessionScreenshotResult[]>;
export type ProjectSessionScreenshotDiffInput = {
baselinePath: string;
currentPath: string;
outputDir: string;
threshold?: number;
ignoreTopNormalizedY?: number;
expectedText?: readonly string[];
expectedVisual?: ScreenshotVisualExpectation;
};
type DiffScreenshots = (
input: ProjectSessionScreenshotDiffInput
) => Promise<ScreenshotDiffResult>;
export type ProjectSessionInstallOcrResult = {
installed: boolean;
alreadyAvailable: boolean;
command?: string;
tesseractPath?: string;
installUrl: string;
warnings: readonly string[];
};
type InstallOcr = () => Promise<ProjectSessionInstallOcrResult>;
export type ProjectSessionPreviewInput = {
source?: ProjectSessionPreviewSource;
imageDomains?: string[];
mode?: ProjectSessionPreviewMode;
};
export type ProjectSessionPreviewResult = {
url: string;
pid?: number;
running: boolean;
mode: ProjectSessionPreviewMode;
};
export type ProjectSessionPreviewStatusResult = {
url?: string;
pid?: number;
running: boolean;
mode?: ProjectSessionPreviewMode;
};
export type ProjectSessionPreviewSubmitFormInput = {
path: string;
selector: string;
values: readonly {
name: string;
value?: string;
file?: { name: string; base64: string; type?: string };
}[];
submitter?: string;
timeout?: number;
};
export type ProjectSessionPreviewSubmitFormResult = {
status: "validation_failed" | "submitted" | "unknown";
formState?: string;
results: readonly {
status: number;
resourceId?: string;
resourceName?: string;
}[];
errors: readonly { status?: number; name?: string; message: string }[];
exchanges: readonly { status: number; url: string }[];
pageUrl: string;
redirect?: string;
correlationId: string;
};
type SubmitPreviewForm = (
input: ProjectSessionPreviewSubmitFormInput
) => Promise<ProjectSessionPreviewSubmitFormResult>;
export type ProjectSessionSimulateFormInput = {
path: string;
siteOrigin?: string;
formId: string;
values: readonly { name: string; value: string }[];
arrayNames?: readonly string[];
};
export type ProjectSessionSimulateFormResult = {
success: boolean;
status: number;
results: readonly { status: number; resourceId?: string }[];
errors: readonly { status?: number; message: string }[];
};
type SimulateForm = (
input: ProjectSessionSimulateFormInput
) => Promise<ProjectSessionSimulateFormResult>;
type StartPreview = (
input: ProjectSessionPreviewInput,
progress?: McpToolProgress
) => Promise<ProjectSessionPreviewResult>;
type GetPreviewStatus = () => Promise<ProjectSessionPreviewStatusResult>;
type StopPreview = () => Promise<ProjectSessionPreviewStatusResult>;
export type ProjectSessionImportInput = {
to: string;
assetsDir?: string;
ignoreVersionCheck?: boolean;
skipAssets?: boolean;
};
export type ProjectSessionImportResult = {
imported: true;
};
type ImportProject = (
input: ProjectSessionImportInput
) => Promise<ProjectSessionImportResult>;
export type ProjectSessionDownloadAssetInput = {
assetId: string;
assetsDir?: string;
};
export type ProjectSessionDownloadAssetResult = {
assetId: string;
path: string;
source?: string;
diagnostics?: readonly (ContentBlockDiagnostic | TextAssetSourceDiagnostic)[];
};
type DownloadAsset = (
input: ProjectSessionDownloadAssetInput
) => Promise<ProjectSessionDownloadAssetResult>;
export type ProjectSessionMcpGuidance = {
visualVerificationRule: string;
getVisionVerificationLoop: (options: {
includeDiff: boolean;
}) => readonly string[];
getVisionWorkflowSummary: (options: { includeDiff: boolean }) => string;
};
const isProjectSessionPreviewSource = (
value: unknown
): value is ProjectSessionPreviewSource =>
projectSessionPreviewSources.some((source) => source === value);
const isProjectSessionPreviewMode = (
value: unknown
): value is ProjectSessionPreviewMode =>
projectSessionPreviewModes.some((mode) => mode === value);
const getRequestParams = (request: unknown) =>
isRecord(request) && isRecord(request.params) ? request.params : {};
type ProjectSessionMcpInputSchema = InputJsonSchema & {
type: "object";
additionalProperties: boolean | InputJsonSchema;
};
const emptyInputSchema = {
type: "object",
description:
"Pass this MCP tool's JSON arguments. Use meta.get-more-tools for examples and required fields. For authored content with styles, prefer insert-fragment so the CLI converts JSX into Webstudio data.",
additionalProperties: false,
} as const satisfies ProjectSessionMcpInputSchema;
const taskScopes = [
"read-only-audit",
"small-value-or-reference-correction",
"focused-page-change",
"visual-change",
"structural-project-change",
"project-wide-migration",
] as const;
type TaskScope = (typeof taskScopes)[number];
const metaGuideWorkflows = [
"general",
"markdown-blog",
"json-ld",
"collection",
"expression",
"authenticated-page",
"font-assets",
"design-input",
"content-block-source",
"craft",
] as const;
type MetaGuideWorkflow = (typeof metaGuideWorkflows)[number];
type SpecializedMetaGuideWorkflow = Exclude<MetaGuideWorkflow, "general">;
const metaGuideInputSchema = {
...emptyInputSchema,
properties: {
brief: {
type: "string",
description: "Short user goal, for example: publish a site.",
},
taskScope: {
type: "string",
enum: taskScopes,
description:
"Explicit scope; use read-only-audit when no project or local state may change. Never inferred from brief.",
default: "focused-page-change",
},
workflow: {
type: "string",
enum: metaGuideWorkflows,
description: "Explicit specialized workflow. Never inferred from brief.",
default: "general",
},
authoredFragment: {
type: "boolean",
description: "Whether the change uses an authored fragment.",
default: false,
},
reuseDesignSystem: {
type: "boolean",
description:
"With authoredFragment, retain design-system discovery tools.",
default: false,
},
},
required: ["brief"],
} as const satisfies ProjectSessionMcpInputSchema;
const metaIndexInputSchema = {
type: "object",
description: "No input is accepted. Call meta.guide for goal-specific input.",
additionalProperties: false,
properties: {},
required: [],
} as const satisfies ProjectSessionMcpInputSchema;
const toolDetailsInputSchema = {
...emptyInputSchema,
properties: {
brief: {
type: "string",
description:
"Tool name, operation id, area, or goal, for example: insert-fragment or build.publish.",
},
tools: {
type: "array",
description:
"Exact MCP tool names to return. Prefer this when you already know the tool names.",
items: { type: "string" },
},
},
required: [],
} as const satisfies ProjectSessionMcpInputSchema;
const componentFindInputSchema = {
...emptyInputSchema,
additionalProperties: false,
properties: {
brief: {
type: "string",
description:
"Component search text, for example: radix select or checkbox indicator.",
},
limit: {
type: "number",
description:
"Maximum number of compact search results to return. Defaults to 12 and is capped at 25.",
},
offset: {
type: "number",
description: "Zero-based pagination offset for additional results.",
},
},
required: ["brief"],
} as const satisfies ProjectSessionMcpInputSchema;
const registryListInputSchema = {
...emptyInputSchema,
additionalProperties: false,
properties: {
source: {
type: "string",
enum: ["all", "component", "template"],
description:
'Registry item source filter. Defaults to "all" for components.list and "template" for templates.list.',
},
documentType: {
type: "string",
enum: ["html", "xml", "text"],
description:
'Target page document type. Defaults to "html"; XML-only items are included only for "xml".',
},
limit: {
type: "number",
description:
"Maximum registry items to return. Defaults to 50 and is capped at 100.",
},
offset: {
type: "number",
description: "Zero-based pagination offset for additional items.",
},
},
required: [],
} as const satisfies ProjectSessionMcpInputSchema;
const componentSummaryInputSchema = {
...emptyInputSchema,
additionalProperties: false,
properties: {
detail: {
type: "string",
enum: ["summary", "components"],
description:
'Response detail. Defaults to "summary"; use "components" for paginated component entries.',
},
limit: {
type: "number",
description:
"Maximum component entries to return with detail components. Defaults to 20 and is capped at 100.",
},
offset: {
type: "number",
description: "Zero-based component pagination offset.",
},
},
required: [],
} as const satisfies ProjectSessionMcpInputSchema;
const templateInputSchema = {
...emptyInputSchema,
additionalProperties: false,
properties: {
template: {
type: "string",
description:
"Template registry item name or component id, for example template:@webstudio-is/sdk-components-react-radix:Select or @webstudio-is/sdk-components-react-radix:Select.",
},
component: {
type: "string",
description:
"Template component id, for example @webstudio-is/sdk-components-react-radix:Select.",
},
name: {
type: "string",
description:
"Template registry item name, for example template:@webstudio-is/sdk-components-react-radix:Select.",
},
},
required: [],
} as const satisfies ProjectSessionMcpInputSchema;
const workflowPhaseNames = [
"discovery",
"page-creation",
"dry-run-section",
"commit-section",
"coverage-batch",
"presentation-pass",
] as const;
type WorkflowPhaseName = (typeof workflowPhaseNames)[number];
const workflowNextInputSchema = {
...emptyInputSchema,
additionalProperties: false,
properties: {
goal: {
type: "string",
description:
'Workflow goal. Currently "design-system-page" gives bounded phases for delegated all-component page work.',
},
phase: {
type: "string",
enum: workflowPhaseNames,
description:
"Optional phase to inspect. Omit to get the first phase for the goal.",
},
},
required: [],
} as const satisfies ProjectSessionMcpInputSchema;
const insertCollectionMcpInput = insertCollectionInput
.omit({ itemFragment: true })
.extend({
itemFragment: z
.string()
.describe(
`${webstudioJsxFragmentInputDescription} Pass exactly one root instance. Expressions may reference collectionItem and collectionItemKey, for example {expression\`collectionItem.name\`}.`
),
})
.describe(
"Create a Collection, bind its complete iterable, and insert one repeated-item Webstudio JSX fragment atomically. Internal item parameters are generated automatically."
);
const componentInputSchema = {
...emptyInputSchema,
properties: {
component: {
type: "string",
description:
"Exact component id, for example Box or @webstudio-is/sdk-components-react-radix:Switch.",
},
},
required: ["component"],
} as const satisfies ProjectSessionMcpInputSchema;
const componentCoverageStatusInputSchema = {
...emptyInputSchema,
description:
"Report which available components are present on a page and which remain missing.",
additionalProperties: false,
properties: {
pagePath: {
type: "string",
description: "Page path to inspect, for example /design-system.",
},
pageId: {
type: "string",
description: "Page id to inspect when pagePath is not provided.",
},
documentType: {
type: "string",
enum: ["html", "xml", "text"],
description:
'Document type used to decide available components. Defaults to "html".',
},
},
required: [],
} as const satisfies ProjectSessionMcpInputSchema;
const componentCoverageInsertNextInputSchema = {
...componentCoverageStatusInputSchema,
description:
"Insert exactly one missing root/template component on a page and return coverage before and after in one checkpoint-safe call.",
properties: {
...componentCoverageStatusInputSchema.properties,
parentInstanceId: {
type: "string",
description:
"Parent instance id where the missing root/template component should be inserted.",
},
component: {
type: "string",
description:
"Optional exact missing root/template component id to insert. When omitted, the first missing root/template component is inserted.",
},
},
required: ["parentInstanceId"],
} as const satisfies ProjectSessionMcpInputSchema;
const getOperationInputSchema = (
operation: Pick<PublicMcpOperation, "inputSchema">
): ProjectSessionMcpInputSchema => {
const { requiredInputFields } = getInputJsonSchemaMetadata(
operation.inputSchema
);
const properties = getInputJsonSchemaProperties(operation.inputSchema);
const additionalProperties =
operation.inputSchema.additionalProperties ??
(properties === undefined || Object.keys(properties).length === 0);
return {
...emptyInputSchema,
...operation.inputSchema,
type: "object",
additionalProperties,
required: requiredInputFields,
};
};
const jsonCompatibleValueSchema = {
anyOf: [
{ type: "string" },
{ type: "number" },
{ type: "boolean" },
{ type: "null" },
{ type: "array", items: {} },
{ type: "object" },
],
} as const satisfies InputJsonSchema;
const constrainUnconstrainedInputSchemaValue = (
value: InputJsonSchemaValue
): InputJsonSchemaValue => {
if (typeof value === "boolean") {
return value;
}
if (Object.keys(value).length === 0) {
return jsonCompatibleValueSchema;
}
return constrainUnconstrainedInputSchemas(value);
};
const constrainUnconstrainedInputSchemas = <Schema extends InputJsonSchema>(
schema: Schema
): Schema => {
const result: InputJsonSchema = { ...schema };
if (schema.properties !== undefined) {
result.properties = Object.fromEntries(
Object.entries(schema.properties).map(([name, value]) => [
name,
constrainUnconstrainedInputSchemaValue(value),
])
);
}
if (schema.additionalProperties !== undefined) {
result.additionalProperties = constrainUnconstrainedInputSchemaValue(
schema.additionalProperties
);
}
if (schema.type === "array" && schema.items === undefined) {
result.items = {};
} else if (schema.items !== undefined) {
result.items = constrainUnconstrainedInputSchemaValue(schema.items);
}
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"] as const) {
const values = schema[key];
if (Array.isArray(values)) {
result[key] = values.map(constrainUnconstrainedInputSchemaValue);
}
}
if (schema.$defs !== undefined) {
result.$defs = Object.fromEntries(
Object.entries(schema.$defs).map(([name, value]) => [
name,
constrainUnconstrainedInputSchemaValue(value),
])
);
}
return result as Schema;
};
const maxInlineMcpInputSchemaSize = 20_000;
const getCompactSchemaProperty = (schema: InputJsonSchema): InputJsonSchema => {
const description =
schema.description === undefined
? undefined
: schema.description.length <= 240
? schema.description
: `${schema.description.slice(0, 239)}…`;
const compact = {
...(schema.type === undefined ? {} : { type: schema.type }),
...(schema.type === "array"
? {
items: {},
}
: {}),
...(description === undefined ? {} : { description }),
...(schema.enum === undefined ? {} : { enum: schema.enum }),
};
if (Object.keys(compact).length > 0) {
return compact;
}
return {
description:
"Complex structured value. Use meta.get-more-tools with this exact tool name for its complete schema.",
};
};
const getHandshakeInputSchema = (
schema: ProjectSessionMcpInputSchema,
maxInlineSize = maxInlineMcpInputSchemaSize
): {
inputSchema: ProjectSessionMcpInputSchema;
detailedInputSchema?: ProjectSessionMcpInputSchema;
} => {
if (JSON.stringify(schema).length <= maxInlineSize) {
return { inputSchema: schema };
}
return {
inputSchema: {
type: "object",
additionalProperties: false,
properties: Object.fromEntries(
Object.entries(schema.properties ?? {}).map(([name, property]) => {
const propertySchema = toInputJsonSchemaObject(property);
const serializedProperty = JSON.stringify(property);
return [
name,
propertySchema === undefined ||
(serializedProperty.length <= maxInlineSize &&
serializedProperty.includes('"$ref"') === false)
? property
: getCompactSchemaProperty(propertySchema),
];
})
),
required: schema.required,
description:
"Compact handshake schema. Use meta.get-more-tools with this exact tool name for the complete input schema.",
},
detailedInputSchema: schema,
};
};
const getZodObjectSchema = (schema: z.ZodTypeAny) => {
const inputSchema = toInputJsonSchemaObject(
getInputSchemaMetadata(schema).inputJsonSchema
);
if (inputSchema?.type !== "object") {
throw new Error("MCP schema must be an object");
}
return {
...inputSchema,
type: "object",
additionalProperties: inputSchema.additionalProperties ?? false,
} as const;
};
const getZodMcpInputSchema = (schema: z.ZodTypeAny) =>
getHandshakeInputSchema(getZodObjectSchema(schema)).inputSchema;
const insertFragmentMcpInput = z
.object({
...insertFragmentInput.shape,
parentInstanceId: insertFragmentInput.shape.parentInstanceId
.unwrap()
.describe("Parent instance id where the fragment is inserted."),
fragment: z.string().describe(webstudioJsxFragmentInputDescription),
})
.describe(
"Insert a Webstudio fragment from a Webstudio JSX string. The CLI converts JSX into structured Webstudio data before mutation."
);
const insertFragmentMcpInputSchema = getZodObjectSchema(insertFragmentMcpInput);
const insertFragmentVerifiedMcpInputSchema = {
...insertFragmentMcpInputSchema,
description:
"Insert a Webstudio fragment and immediately verify its persisted bindings in one call.",
properties: {
...insertFragmentMcpInputSchema.properties,
pagePath: {
type: "string",
description:
"Concrete page path used for post-commit binding verification, for example /account.",
},
},
required: ["parentInstanceId", "fragment", "pagePath"],
} as const satisfies ProjectSessionMcpInputSchema;
const insertCollectionMcpInputSchema = getOperationInputSchema({
inputSchema: getInputSchemaMetadata(insertCollectionMcpInput).inputJsonSchema,
});
const assetsResourceResultDescription =
"Pass query as structured tool input with Webstudio JavaScript expressions. Keep one final resource per rendered query and remove obsolete duplicates. Use result many for listings and result one for unique details; first and last require sorting. Keep static filters, limits, and offsets literal; single modes omit pagination. Select only rendered fields, keep includeMetadata false, and use content mode none unless file content is rendered. For Markdown details, use markdown-body-ref; compilation keeps a document reference and fetches the body at runtime. Bind <dataSourceName>.data, including id and content.text. Many returns an ID map plus totalCount and hasMore at <dataSourceName>.meta; single modes return an item or null plus totalCount.";
const mcpOperationOverrides = new Map<
string,
{
description: string;
inputSchema?: ProjectSessionMcpInputSchema;
}
>([
[
"insert-fragment",
{
description:
"Insert an authored/styled Webstudio fragment with components, text, props, tokens, and styles. Pass fragment as a Webstudio JSX string.",
inputSchema: insertFragmentMcpInputSchema,
},
],
[
"insert-collection",
{
description:
"Create a Collection from array/object data and one repeated-item Webstudio JSX fragment. Internal item parameters and bindings are created atomically.",
inputSchema: insertCollectionMcpInputSchema,
},
],
[
"create-assets-resource",
{
description: `Create a scoped Assets resource. ${assetsResourceResultDescription}`,
},
],
[
"update-assets-resource",
{
description: `Update an Assets resource or its query. ${assetsResourceResultDescription}`,
},
],
]);
const acceptsJsonType = (
schema: InputJsonSchema | undefined,
type: "object" | "array"
): boolean => {
if (schema === undefined) {
return false;
}
return inputJsonSchemaAcceptsType(schema, type, {
treatUnconstrainedAsAny: true,
});
};
const isArrayInputSchema = (schema: InputJsonSchema | undefined) =>
schema === undefined ? false : inputJsonSchemaAcceptsType(schema, "array");
const getSingleArrayInputProperty = (schema: InputJsonSchema | undefined) => {
const entries = Object.entries(schema?.properties ?? {});
if (entries.length !== 1) {
return;
}
const [field, fieldSchema] = entries[0]!;
const fieldSchemaObject = toInputJsonSchemaObject(fieldSchema);
if (
fieldSchemaObject !== undefined &&
isArrayInputSchema(fieldSchemaObject)
) {
return { field, schema: fieldSchemaObject };
}
};
const parseJsonStringForSchema = (
value: unknown,
schema: InputJsonSchema | undefined
) => {
if (typeof value === "string") {
const acceptsObject = acceptsJsonType(schema, "object");
const acceptsArray = acceptsJsonType(schema, "array");
if (acceptsObject === false && acceptsArray === false) {
return value;
}
try {
const parsed = JSON.parse(value);
if (acceptsArray && Array.isArray(parsed)) {
return parsed;
}
if (acceptsObject && isPlainRecord(parsed)) {
return parsed;
}
return value;
} catch {
return value;
}
}
return value;
};
const resolveDiscriminatedInputSchema = (
schema: InputJsonSchema | undefined,
value: unknown
) => {
if (schema === undefined || isPlainRecord(value) === false) {
return schema;
}
const branches = [...(schema.oneOf ?? []), ...(schema.anyOf ?? [])];
for (const branch of branches) {
const branchSchema = toInputJsonSchemaObject(branch);
const properties = getInputJsonSchemaProperties(branchSchema);
const discriminatorEntries = Object.entries(properties ?? {}).filter(
([, propertySchema]) => {
const property = toInputJsonSchemaObject(propertySchema);
return property !== undefined && "const" in property;
}
);
if (
discriminatorEntries.length > 0 &&
discriminatorEntries.every(([field, propertySchema]) => {
const property = toInputJsonSchemaObject(propertySchema);
return property?.const === value[field];
})
) {
return branchSchema;
}
}
return schema;
};
const parseStringifiedJsonInputFields = (
input: unknown,
schema: InputJsonSchema | undefined
): unknown => {
const parsedInput = parseJsonStringForSchema(input, schema);
const resolvedSchema = resolveDiscriminatedInputSchema(schema, parsedInput);
if (Array.isArray(parsedInput)) {
const prefixItems = Array.isArray(resolvedSchema?.prefixItems)
? resolvedSchema.prefixItems
: undefined;
return parsedInput.map((item, index) =>
parseStringifiedJsonInputFields(
item,
toInputJsonSchemaObject(prefixItems?.[index] ?? resolvedSchema?.items)
)
);
}
if (isPlainRecord(parsedInput) === false) {
return parsedInput;
}
const properties = getInputJsonSchemaProperties(resolvedSchema);
const additionalProperties = resolvedSchema?.additionalProperties;
if (properties === undefined && additionalProperties === undefined) {
return parsedInput;
}
return Object.fromEntries(
Object.entries(parsedInput).map(([field, value]) => [
field,
parseStringifiedJsonInputFields(
value,
toInputJsonSchemaObject(properties?.[field] ?? additionalProperties)
),
])
);
};
const getClosestInputField = (
field: string,
allowedFields: readonly string[]
) => {
const normalizedField = field.toLowerCase();
return allowedFields.find((allowedField) => {
const normalizedAllowedField = allowedField.toLowerCase();
return (
normalizedAllowedField === `max${normalizedField}` ||
normalizedAllowedField.endsWith(normalizedField) ||
normalizedAllowedField.includes(normalizedField)
);
});
};
const getUnsupportedInputFieldHint = ({
command,
field,
}: {
command: string;
field: string;
}) => {
if (
field === "detail" &&
(command === "get-page" || command === "get-page-by-path")
) {
return " Use get-page/get-page-by-path for page metadata, list-instances to inspect page root contents, and inspect-instance for props, styles, children, bindings, or sources.";
}
if (command === "list-instances" && field === "instanceId") {
return " Use rootInstanceId to list a subtree, or inspect-instance to inspect one element.";
}
return "";
};
export const getMcpTextAssetFormat = (
value: string
): "md" | "mdx" | undefined => {
const extension = (getFileExtension(value) ?? value).toLowerCase();
return extension === "md" || extension === "mdx" ? extension : undefined;
};
export const getMcpTextAssetDescriptorIssues = ({
assets,
pathPrefix,
}: {
assets: readonly Record<string, unknown>[];
pathPrefix: readonly string[];
}): SemanticValidationIssue[] => {
const issues: SemanticValidationIssue[] = [];
for (const [index, asset] of assets.entries()) {
const name = typeof asset.name === "string" ? asset.name : undefined;
const filenameFormat =
name === undefined ? undefined : getFileExtension(name)?.toLowerCase();
const declaredFormat =
typeof asset.format === "string" ? asset.format.toLowerCase() : undefined;
const mentionsTextFormat =
filenameFormat === "md" ||
filenameFormat === "mdx" ||
declaredFormat === "md" ||
declaredFormat === "mdx";
const assetPath =
pathPrefix[0] === "asset"
? [...pathPrefix]
: [...pathPrefix, String(index)];
if (
name !== undefined &&
mentionsTextFormat &&
declaredFormat !== undefined &&
declaredFormat !== filenameFormat
) {
issues.push({
path: [...assetPath, "format"],
code: "asset_filename_format_mismatch",
message: `Asset filename and format must match. ${JSON.stringify(
name
)} has extension ${JSON.stringify(
filenameFormat ?? "(none)"
)} but format is ${JSON.stringify(declaredFormat)}.`,
constraint: "asset_filename_format_mismatch",
});
}
if (
mentionsTextFormat &&
typeof asset.type === "string" &&
asset.type !== "file"
) {
issues.push({
path: [...assetPath, "type"],
code: "markdown_asset_type_mismatch",
message: `Markdown and MDX Assets must use type "file", not ${JSON.stringify(
asset.type
)}.`,
constraint: "markdown_asset_type_mismatch",
});
}
}
return issues;
};
const getLocalTextAssetInputIssues = ({
command,
input,
}: {
command: string;
input: unknown;
}) => {
if (isPlainRecord(input) === false) {
return [];
}
if (command === "upload-asset") {
return isPlainRecord(input.asset)
? getMcpTextAssetDescriptorIssues({
assets: [input.asset],
pathPrefix: ["asset"],
})
: [];
}
if (command === "upload-assets") {
return Array.isArray(input.assets)
? getMcpTextAssetDescriptorIssues({
assets: input.assets.filter(isPlainRecord),
pathPrefix: ["assets"],
})
: [];
}
return [];
};
const collectUnknownInputFields = ({
command,
input,
schema,
path = [],
}: {
command: string;
input: unknown;
schema: InputJsonSchema | undefined;
path?: string[];
}): Array<{ message: string; issue: SemanticValidationIssue }> => {
const results: Array<{ message: string; issue: SemanticValidationIssue }> =
[];
if (Array.isArray(input)) {
for (const [index, item] of input.entries()) {
results.push(
...collectUnknownInputFields({
command,
input: item,
schema: toInputJsonSchemaObject(schema?.items),
path: [...path, String(index)],
})
);
}
return results;
}
if (isPlainRecord(input) === false) {
return results;
}
const properties = getInputJsonSchemaProperties(schema);
const additionalProperties = schema?.additionalProperties;
const allowedFields = Object.keys(properties ?? {});
for (const [field, value] of Object.entries(input)) {
const isKnownField =
properties !== undefined &&
Object.prototype.hasOwnProperty.call(properties, field);
const fieldSchema = isKnownField
? toInputJsonSchemaObject(properties[field])
: typeof additionalProperties === "object"
? toInputJsonSchemaObject(additionalProperties)
: undefined;
if (isKnownField === false && additionalProperties === false) {
const inputPath = ["input", ...path, field].join(".");
const expected =
allowedFields.length === 0
? "No fields are supported."
: `Expected one of: ${allowedFields.join(", ")}.`;
const closestField = getClosestInputField(field, allowedFields);
const suggestion =
closestField === undefined ? "" : ` Did you mean ${closestField}?`;
const hint = getUnsupportedInputFieldHint({ command, field });
const message = `${command} ${inputPath} is not supported. ${expected}${suggestion}${hint}`;
results.push({
message,
issue: {
code: "unknown_field",
path: [...path, field],
message,
constraint: "known_input_field",
...(closestField === undefined ? {} : { example: closestField }),
},
});
continue;
}
if (fieldSchema === undefined) {
continue;
}
results.push(
...collectUnknownInputFields({
command,
input: value,
schema: fieldSchema,
path: [...path, field],
})
);
}
return results;
};
const getJsonValueType = (value: unknown) => {
if (value === null) {
return "null";
}
if (Array.isArray(value)) {
return "array";
}
if (typeof value === "number" && Number.isInteger(value)) {
return "integer";
}
return typeof value;
};
const collectInputSchemaIssues = ({
command,
input,
schema,
path = [],
depth = 0,
}: {
command: string;
input: unknown;
schema: InputJsonSchema | undefined;
path?: string[];
depth?: number;
}): SemanticValidationIssue[] => {
if (schema === undefined || depth > 64) {
return [];
}
const inputPath = ["input", ...path].join(".");
const issue = ({
code,
message,
constraint,
example,
}: {
code: string;
message: string;
constraint: string;
example?: unknown;
}): SemanticValidationIssue => ({
code,
path,
message: `${command} ${inputPath} ${message}`,
constraint,
...(example === undefined ? {} : { example }),
});
const discriminatedSchema = resolveDiscriminatedInputSchema(schema, input);
if (discriminatedSchema !== schema) {
return collectInputSchemaIssues({
command,
input,
schema: discriminatedSchema,
path,
depth: depth + 1,
});
}
const allowedTypes =
schema.type === undefined
? []
: Array.isArray(schema.type)
? schema.type
: [schema.type];
if (allowedTypes.length > 0) {
const actualType = getJsonValueType(input);
const matches = allowedTypes.some(
(type) =>
type === actualType || (type === "number" && actualType === "integer")
);
if (matches === false) {
return [
issue({
code: "invalid_type",
message: `must be ${allowedTypes.join(" or ")}, not ${actualType}.`,
constraint: `type:${allowedTypes.join("|")}`,
}),
];
}
}
if ("const" in schema && Object.is(input, schema.const) === false) {
return [
issue({
code: "invalid_value",
message: `must equal ${JSON.stringify(schema.const)}.`,
constraint: "const",
example: schema.const,
}),
];
}
if (
Array.isArray(schema.enum) &&
schema.enum.some((value) => Object.is(value, input)) === false
) {
return [
issue({
code: "invalid_value",
message: `must be one of ${schema.enum
.map((value) => JSON.stringify(value))
.join(", ")}.`,
constraint: "enum",
example: schema.enum[0],
}),
];
}
const issues: SemanticValidationIssue[] = [];
if (typeof input === "string") {
if (
typeof schema.minLength === "number" &&
input.length < schema.minLength
) {
issues.push(
issue({
code: "too_small",
message: `must contain at least ${schema.minLength} characters.`,
constraint: `minLength:${schema.minLength}`,
})
);
}
if (
typeof schema.maxLength === "number" &&
input.length > schema.maxLength
) {
issues.push(
issue({
code: "too_big",
message: `must contain at most ${schema.maxLength} characters.`,
constraint: `maxLength:${schema.maxLength}`,
})
);
}
}
if (typeof input === "number") {
if (typeof schema.minimum === "number" && input < schema.minimum) {
issues.push(
issue({
code: "too_small",
message: `must be at least ${schema.minimum}.`,
constraint: `minimum:${schema.minimum}`,
})
);
}
if (typeof schema.maximum === "number" && input > schema.maximum) {
issues.push(
issue({
code: "too_big",
message: `must be at most ${schema.maximum}.`,
constraint: `maximum:${schema.maximum}`,
})
);
}
if (
typeof schema.exclusiveMinimum === "number" &&
input <= schema.exclusiveMinimum
) {
issues.push(
issue({
code: "too_small",
message: `must be greater than ${schema.exclusiveMinimum}.`,
constraint: `exclusiveMinimum:${schema.exclusiveMinimum}`,
})
);
}
if (
typeof schema.exclusiveMaximum === "number" &&
input >= schema.exclusiveMaximum
) {
issues.push(
issue({
code: "too_big",
message: `must be less than ${schema.exclusiveMaximum}.`,
constraint: `exclusiveMaximum:${schema.exclusiveMaximum}`,
})
);
}
}
if (isPlainRecord(input)) {
for (const requiredField of schema.required ?? []) {
if (typeof requiredField !== "string" || requiredField in input) {
continue;
}
issues.push({
code: "invalid_type",
path: [...path, requiredField],
message: `${command} ${["input", ...path, requiredField].join(
"."
)} is required.`,
constraint: "required",
});
}
const properties = getInputJsonSchemaProperties(schema);
for (const [field, value] of Object.entries(input)) {
const fieldSchema = toInputJsonSchemaObject(properties?.[field]);
if (fieldSchema === undefined) {
continue;
}
issues.push(
...collectInputSchemaIssues({
command,
input: value,
schema: fieldSchema,
path: [...path, field],
depth: depth + 1,
})
);
}
}
if (Array.isArray(input)) {
if (typeof schema.minItems === "number" && input.length < schema.minItems) {
issues.push(
issue({
code: "too_small",
message: `must contain at least ${schema.minItems} items.`,
constraint: `minItems:${schema.minItems}`,
})
);
}
if (typeof schema.maxItems === "number" && input.length > schema.maxItems) {
issues.push(
issue({
code: "too_big",
message: `must contain at most ${schema.maxItems} items.`,
constraint: `maxItems:${schema.maxItems}`,
})
);
}
const itemSchema = toInputJsonSchemaObject(schema.items);
if (itemSchema !== undefined) {
for (const [index, value] of input.entries()) {
issues.push(
...collectInputSchemaIssues({
command,
input: value,
schema: itemSchema,
path: [...path, String(index)],
depth: depth + 1,
})
);
}
}
}
for (const branch of schema.allOf ?? []) {
issues.push(
...collectInputSchemaIssues({
command,
input,
schema: toInputJsonSchemaObject(branch),
path,
depth: depth + 1,
})
);
}
const oneOfBranches = (schema.oneOf ?? []).flatMap((branch) => {
const branchSchema = toInputJsonSchemaObject(branch);
return branchSchema === undefined
? []
: [
collectInputSchemaIssues({
command,
input,
schema: branchSchema,
path,
depth: depth + 1,
}),
];
});
if (oneOfBranches.length > 0) {
const matchingBranches = oneOfBranches.filter(
(branchIssues) => branchIssues.length === 0
).length;
if (matchingBranches !== 1) {
const requiredFields = (schema.oneOf ?? []).flatMap((branch) => {
const branchSchema = toInputJsonSchemaObject(branch);
return branchSchema?.required?.length === 1 &&
typeof branchSchema.required[0] === "string"
? [branchSchema.required[0]]
: [];
});
issues.push(
issue({
code: "invalid_union",
message:
requiredFields.length === oneOfBranches.length
? `must provide exactly one of ${requiredFields.join(", ")}.`
: "must match exactly one allowed input shape.",
constraint:
requiredFields.length === oneOfBranches.length
? `exactly_one_of:${requiredFields.join("|")}`
: "oneOf",
})
);
}
}
const anyOfBranches = (schema.anyOf ?? []).flatMap((branch) => {
const branchSchema = toInputJsonSchemaObject(branch);
return branchSchema === undefined
? []
: [
collectInputSchemaIssues({
command,
input,
schema: branchSchema,
path,
depth: depth + 1,
}),
];
});
if (
anyOfBranches.length > 0 &&
anyOfBranches.some((branchIssues) => branchIssues.length === 0) === false
) {
issues.push(
...anyOfBranches.reduce((best, current) =>
current.length < best.length ? current : best
)
);
}
return issues;
};
const assertKnownInputFields = (
options: Parameters<typeof collectUnknownInputFields>[0]
) => {
const validatesAssetQuery =
options.command === "validate-asset-query" ||
options.command === "preview-asset-query";
const queryValidation =
validatesAssetQuery && isPlainRecord(options.input)
? validateAssetQuery({ query: options.input.query })
: undefined;
const queryIssues = (queryValidation?.issues ?? [])
.filter(({ severity }) => severity === "error")
.map(
(issue): SemanticValidationIssue => ({
...issue,
constraint: issue.code,
})
);
const outsideQuery = (issue: SemanticValidationIssue) =>
validatesAssetQuery === false || issue.path[0] !== "query";
const unknownFields = collectUnknownInputFields(options).filter(({ issue }) =>
outsideQuery(issue)
);
const localTextAssetIssues = getLocalTextAssetInputIssues(options);
const validatesLocalTextAssetInput =
options.command === "upload-asset" ||
options.command === "upload-assets" ||
options.command === "update-asset-content";
// The operation executor remains the source of truth for ordinary schema
// validation. Only validate the JSON-schema shape here when this boundary
// must already reject the call, so its unknown-field error does not hide
// simultaneous missing or wrong-type fields. Query validation is also owned
// here because both MCP query tools must use the shared query validator.
const schemaIssues =
unknownFields.length > 0 ||
queryIssues.length > 0 ||
validatesLocalTextAssetInput
? collectInputSchemaIssues(options).filter(outsideQuery)
: [];
const issues = [
...queryIssues,
...schemaIssues,
...localTextAssetIssues,
...unknownFields.map(({ issue }) => issue),
];
if (issues.length > 0) {
const messages = [
...queryIssues.map(({ message }) => message),
...schemaIssues.map(({ message }) => message),
...localTextAssetIssues.map(({ message }) => message),
...unknownFields.map(({ message }) => message),
];
throwBuilderValidationError(messages.join("\n"), issues);
}
};
const normalizeOperationInputAliases = ({
command,
input,
}: {
command: string;
input: unknown;
}) => {
if (
command === "create-resource" &&
isPlainRecord(input) &&
Object.keys(input).length === 1 &&
isPlainRecord(input.resource) &&
isPlainRecord(input.resource.resource) &&
typeof input.resource.scopeInstanceId === "string"
) {
return input.resource;
}
if (command === "create-page" && isPlainRecord(input)) {
const normalizedInput: Record<string, unknown> =
"description" in input
? (() => {
const { description, meta, ...rest } = input;
return {
...rest,
meta: {
...(isPlainRecord(meta) ? meta : {}),
description,
},
};
})()
: input;
if (
typeof normalizedInput.path !== "string" ||
normalizedInput.path === ""
) {
return normalizedInput;
}
try {
const base = new URL("https://webstudio.invalid/");
const parsed = new URL(normalizedInput.path, base);
if (
parsed.origin === base.origin &&
parsed.search === "" &&
parsed.hash === ""
) {
return { ...normalizedInput, path: parsed.pathname };
}
} catch {
return normalizedInput;
}
return normalizedInput;
}
if (
command === "insert-component" &&
isPlainRecord(input) &&
"position" in input &&
"mode" in input === false
) {
const { position, ...rest } = input;
return { ...rest, mode: position };
}
return input;
};
const normalizeOperationInputValues = (command: string, input: unknown) => {
if (
command !== "update-styles" ||
isPlainRecord(input) === false ||
Array.isArray(input.updates) === false
) {
return input;
}
const normalizeStyleValue = (value: unknown) => {
if (
isPlainRecord(value) &&
typeof value.value === "string" &&
["unit", "length", "color"].includes(String(value.type)) &&
(value.type !== "color" || "colorSpace" in value === false)
) {
return { type: "keyword", value: value.value };
}
return typeof value === "string" ? { type: "keyword", value } : value;
};
return {
...input,
updates: input.updates.flatMap((update) => {
if (isPlainRecord(update) === false) {
return [update];
}
if (typeof update.property === "string" && "value" in update) {
return [
{
...update,
value: normalizeStyleValue(update.value),
},
];
}
const grouped = isPlainRecord(update.styles)
? update.styles
: isPlainRecord(update.declarations)
? update.declarations
: undefined;
if (grouped === undefined) {
return [update];
}
const { styles: _styles, declarations: _declarations, ...rest } = update;
return Object.entries(grouped).map(([property, value]) => ({
...rest,
property,
value: normalizeStyleValue(value),
}));
}),
};
};
const getNormalizedOperationInput = (
operation: PublicMcpOperation,
input: unknown
) => {
const schema = getOperationInputSchema(operation);
const singleArrayInputProperty = getSingleArrayInputProperty(schema);
const parsedRootArrayInput =
typeof input === "string" && singleArrayInputProperty !== undefined
? parseJsonStringForSchema(input, singleArrayInputProperty.schema)
: input;
const wrappedInput =
Array.isArray(parsedRootArrayInput) &&
singleArrayInputProperty !== undefined
? { [singleArrayInputProperty.field]: parsedRootArrayInput }
: parsedRootArrayInput;
const aliasedInput = normalizeOperationInputAliases({
command: operation.command,
input: wrappedInput,
});
const normalizedInput = normalizeOperationInputValues(
operation.command,
parseStringifiedJsonInputFields(aliasedInput, schema)
);
assertKnownInputFields({
command: operation.command,
input: normalizedInput,
schema,
});
return normalizedInput;
};
const screenshotInputSchema = {
...emptyInputSchema,
description:
'Capture the generated site for AI vision review. For the configured project, use { path: "/" }; this refreshes the current MCP session and reloads only the generated site. Never pass a Webstudio Builder/share URL or screenshot the Builder UI. Use { url } only for an intentional standalone external site, or { baseUrl, path } for an existing generated-site server.',
properties: {
url: {
type: "string",
description: "Absolute URL to capture.",
},
baseUrl: {
type: "string",
description:
"Existing site base URL used with path, for example http://127.0.0.1:5177. Skips preview generation and startup.",
},
path: {
type: "string",
description:
"Generated-site path, for example /pricing. With baseUrl, capture that site; otherwise use or start the MCP preview.",
},
output: {
type: "string",
description: "PNG output path.",
},
viewport: {
type: "object",
description: "Viewport dimensions in CSS pixels.",
properties: {
width: { type: "number", default: 1440 },
height: { type: "number", default: 900 },
},
},
fullPage: {
type: "boolean",
default: false,
description:
"Capture the full page after layout, rather than the viewport.",
},
includeImageMetrics: {
type: "boolean",
default: false,
description:
"Include image loading state and natural/rendered dimensions. Rendered audit enables this automatically.",
},
includeResourceMetrics: {
type: "boolean",
default: false,
description:
"Include sanitized Resource Timing and render-blocking data. Rendered audit enables this automatically.",
},
includeContrastMetrics: {
type: "boolean",
default: false,
description:
"Include only statically resolvable opaque text/background contrast measurements. Rendered accessibility audit enables this automatically.",
},
browser: {
type: "string",
enum: screenshotBrowserChoices,
default: "auto",
},
browserPath: {
type: "string",
description: "Explicit Chromium-family browser executable path.",
},
waitUntil: {
type: "string",
enum: screenshotWaitUntilValues,
default: defaultScreenshotWaitUntil,
description:
"Page readiness event to wait for before capture: commit, domcontentloaded, load, or networkidle.",
},
waitForSelector: {
type: "string",
description: "CSS selector that must exist before capture.",
},
waitForFonts: {
type: "boolean",
default: true,
description:
"Wait for document.fonts.ready. Set false if fonts never settle; layout still stabilizes.",
},
waitForTimeout: {
type: "number",
default: defaultScreenshotWaitForTimeout,
description:
"Extra milliseconds to wait after readiness, selector, fonts, and layout frames.",
},
timeout: {
type: "number",
default: defaultScreenshotTimeout,
description:
"Maximum milliseconds for browser capture after preview is ready.",
},
source: {
type: "string",
enum: projectSessionPreviewSources,
default: "session",
description:
"Preview source: local uses .webstudio/data.json; session uses the current ProjectSession snapshot.",
},
mode: {
type: "string",
enum: projectSessionPreviewModes,
default: "iterative",
description:
"Iterative reloads a persistent dev server and browser after MCP edits. Production builds the generated site for audits.",
},
imageDomains: {
type: "array",
description:
"External image hostnames allowed by the generated preview optimizer, for example storage.example.com.",
items: { type: "string" },
},
},
oneOf: [
{
required: ["url"],
not: { anyOf: [{ required: ["path"] }, { required: ["baseUrl"] }] },
},
{ required: ["path"], not: { required: ["url"] } },
],
required: ["viewport"],
} as const satisfies ProjectSessionMcpInputSchema;
const responsiveScreenshotInputSchema = {
...emptyInputSchema,
description:
"Capture one generated-site route at multiple viewport sizes in one shared preview/browser session. This starts or refreshes the session preview automatically.",
properties: {
path: screenshotInputSchema.properties.path,
viewports: {
type: "array",
minItems: 1,
maxItems: 8,
description: "Viewport dimensions to capture in the provided order.",
items: {
type: "object",
properties: {
width: { type: "number" },
height: { type: "number" },
},
required: ["width", "height"],
additionalProperties: false,
},
},
fullPage: screenshotInputSchema.properties.fullPage,
source: screenshotInputSchema.properties.source,
mode: screenshotInputSchema.properties.mode,
imageDomains: screenshotInputSchema.properties.imageDomains,
browser: screenshotInputSchema.properties.browser,
waitUntil: screenshotInputSchema.properties.waitUntil,
waitForSelector: screenshotInputSchema.properties.waitForSelector,
waitForFonts: screenshotInputSchema.properties.waitForFonts,
waitForTimeout: screenshotInputSchema.properties.waitForTimeout,
timeout: screenshotInputSchema.properties.timeout,
},
required: ["path", "viewports"],
} as const satisfies ProjectSessionMcpInputSchema;
const statusInputSchema = {
...emptyInputSchema,
properties: {
verbose: {
type: "boolean",
description:
"Include full namespace arrays, freshness, compatibility details, and diagnostics. Omit for the compact default response.",
},
},
} as const satisfies ProjectSessionMcpInputSchema;
const renderedAuditInputProperty = {
type: "boolean",
description:
"Run a rendered responsive pass through this long-lived MCP session. Cannot be combined with cursor pagination.",
} as const;
const renderedAuditConfirmationInputProperties = {
confirmLargeRun: {
type: "boolean",
description:
"Confirm an audit plan above the unconfirmed capture threshold. Requires the unchanged plan's confirmationToken.",
},
confirmationToken: {
type: "string",
description:
"Short-lived token returned with a large rendered plan. Use with confirmLargeRun: true.",
},
imageDomains: {
type: "array",
description:
"External image hostnames allowed by the generated preview optimizer during rendered audit.",
items: { type: "string" },
},
routeExamples: {
type: "array",
description:
'Concrete paths for dynamic pages, identified by page id. For example [{"pageId":"post","path":"/blog/hello"}].',
items: {
type: "object",
additionalProperties: false,
properties: {
pageId: { type: "string" },
path: { type: "string" },
},
required: ["pageId", "path"],
},
},
} as const;
const dryRunInputProperty = {
type: "boolean",
description:
"Plan this local-capable mutation without committing it. Returns the planned transaction in meta.session.transaction.",
} as const;
const destructiveConfirmationInputProperties = {
confirmDestructive: {
type: "boolean",
description:
"Commit the unchanged destructive plan. Requires the short-lived confirmationToken returned by the previous planned call.",
},
confirmationToken: {
type: "string",
description:
"Short-lived token returned with the unchanged destructive mutation plan.",
},
} as const;
const getMcpOperationInputSchema = (
operation: PublicMcpOperation,
options: {
includeRenderedAudit: boolean;
schema?: ProjectSessionMcpInputSchema;
}
) => {
let schema = constrainUnconstrainedInputSchemas(
options.schema ?? getOperationInputSchema(operation)
);
if (operation.command === "report-issue") {
const { runtime: _runtime, ...properties } = schema.properties ?? {};
schema = {
...schema,
properties,
required: schema.required?.filter((field) => field !== "runtime"),
};
}
const properties = getInputJsonSchemaProperties(schema);
if (
schema.additionalProperties === true &&
(properties === undefined || Object.keys(properties).length === 0)
) {
schema = { ...schema, additionalProperties: false };
}
const transportProperties = {
...(operation.method === "mutation" && operation.localCapable
? { dryRun: dryRunInputProperty }
: {}),
...(operation.requiresConfirm && operation.localCapable
? destructiveConfirmationInputProperties
: {}),
...(operation.command === "audit" && options.includeRenderedAudit
? {
rendered: renderedAuditInputProperty,
...renderedAuditConfirmationInputProperties,
}
: {}),
};
if (Object.keys(transportProperties).length === 0) {
return schema;
}
return {
...schema,
properties: { ...schema.properties, ...transportProperties },
} satisfies InputJsonSchema;
};
const screenshotDiffInputSchema = {
...emptyInputSchema,
description:
"Compare one baseline/current PNG screenshot pair and return pixel-region plus OCR text-change evidence for AI vision review. Run once per page or viewport pair. OCR uses the system tesseract binary when available.",
properties: {
baselinePath: {
type: "string",
description: "Baseline PNG path.",
},
currentPath: {
type: "string",
description: "Current PNG path.",
},
outputDir: {
type: "string",
description:
"Directory for diff artifacts. Defaults to the current screenshot directory.",
},
threshold: {
type: "number",
default: 0.1,
description: "RGB distance threshold from 0 to 1.",
},
ignoreTopNormalizedY: {
type: "number",
default: 0,
description:
"Ignore the top fraction of the image, useful for browser chrome or status bars.",
},
expectedText: {
type: "array",
items: { type: "string" },
description:
"Text that OCR must find in the current screenshot. Returns pass/fail assertions plus found and missing text. Requires Tesseract OCR.",
},
expectedVisual: {
type: "object",
additionalProperties: false,
properties: {
maxMismatchPercentage: {
type: "number",
minimum: 0,
maximum: 100,
description: "Fail when changed pixels exceed this percentage.",
},
minChangedRegions: {
type: "integer",
minimum: 0,
description: "Fail when fewer changed regions are detected.",
},
maxChangedRegions: {
type: "integer",
minimum: 0,
description: "Fail when more changed regions are detected.",
},
dominantColorChange: {
type: "object",
additionalProperties: false,
properties: {
channel: {
type: "string",
enum: ["red", "green", "blue", "luminance"],
},
direction: {
type: "string",
enum: ["increase", "decrease"],
},
minMagnitude: {
type: "number",
minimum: 0,
},
},
required: ["channel", "direction"],
description:
"Expected overall dominant color or brightness direction across changed pixels.",
},
},
description:
"Quantitative visual assertions derived from pixel-diff evidence.",
},
},
required: ["baselinePath", "currentPath"],
} as const satisfies ProjectSessionMcpInputSchema;
const installOcrInputSchema = {
...emptyInputSchema,
description:
"Install the Tesseract OCR binary needed for screenshot.diff textAnalysis. MCP cannot prompt; ask the user first, then pass { confirm: true }.",
properties: {
confirm: {
type: "boolean",
description:
"Must be true after explicit user consent. The tool refuses to install without it.",
},
},
required: ["confirm"],
} as const satisfies ProjectSessionMcpInputSchema;
const previewInputSchema = {
...emptyInputSchema,
description:
"Start or refresh the generated-site preview. Iterative mode is the default for repeated MCP edit and screenshot cycles: it keeps one server alive, regenerates the current session, and uses normal page reloads without HMR. Use production mode for release-like audits.",
properties: {
source: {
type: "string",
enum: projectSessionPreviewSources,
default: "session",
description:
"Project data source for generated preview: local uses .webstudio/data.json; session materializes the current ProjectSession snapshot first, which is the right choice after MCP mutations.",
},
mode: {
type: "string",
enum: projectSessionPreviewModes,
default: "iterative",
},
imageDomains: {
type: "array",
description:
"External image hostnames allowed by the generated preview optimizer, for example storage.example.com.",
items: { type: "string" },
},
maxDurationMs: {
type: "integer",
minimum: 1,
description:
"Maximum acceptable duration. Slow work returns a confirmation preflight instead of starting when it cannot reasonably fit this budget.",
},
confirmSlow: {
type: "boolean",
description:
"Must be true after explicit user consent for the unchanged slow-operation preflight.",
},
confirmationToken: {
type: "string",
description:
"Short-lived token returned by the unchanged slow-operation preflight.",
},
},
} as const satisfies ProjectSessionMcpInputSchema;
const previewSubmitFormInputSchema = {
type: "object",
properties: {
path: {
type: "string",
description:
"Path on this session's local Preview, for example /contact.",
},
selector: {
type: "string",
description: "CSS selector identifying the rendered form.",
},
values: {
type: "array",
maxItems: 100,
items: {
type: "object",
properties: {
name: { type: "string" },
value: { type: "string" },
file: {
type: "object",
properties: {
name: { type: "string" },
base64: {
type: "string",
description: "Base64 file bytes, at most 1 MiB.",
},
type: { type: "string" },
},
required: ["name", "base64"],
additionalProperties: false,
},
},
required: ["name"],
additionalProperties: false,
},
},
submitter: {
type: "string",
description: "Optional CSS selector for the submit button.",
},
timeout: { type: "integer", minimum: 1, maximum: 60000 },
},
required: ["path", "selector", "values"],
additionalProperties: false,
} as const satisfies ProjectSessionMcpInputSchema;
const importInputSchema = {
...emptyInputSchema,
description:
"Import local .webstudio/data.json into another project using a destination share link with build permissions.",
properties: {
to: {
type: "string",
description: "Destination Builder share link with build permissions.",
},
assetsDir: {
type: "string",
description:
"Directory containing local asset files referenced by the bundle.",
},
ignoreVersionCheck: {
type: "boolean",
description:
"Import even when local bundle version differs from the current CLI/API contract.",
},
skipAssets: {
type: "boolean",
description:
"Import project data without uploading or importing asset files.",
},
},
required: ["to"],
} as const satisfies ProjectSessionMcpInputSchema;
const downloadAssetInputSchema = {
...emptyInputSchema,
description:
"Download one project Asset. Markdown and MDX results also include source and diagnostics.",
properties: {
assetId: {
type: "string",
description: "Existing asset id from list-assets.",
},
assetsDir: {
type: "string",
description:
"Optional destination directory. Defaults to .webstudio/assets.",
},
},
required: ["assetId"],
} as const satisfies ProjectSessionMcpInputSchema;
export type ProjectSessionMcpTool = {
name: string;
description: string;
inputSchema: ProjectSessionMcpInputSchema;
outputSchema?: InputJsonSchema;
mcpExamples?: readonly unknown[];
annotations: {
command: string;
operationId: string;
method: PublicMcpOperation["method"] | "session";
permit: PublicMcpOperation["permit"];
inputFields: readonly string[];
requiredInputFields: readonly string[];
localCapable: boolean;
serverOnly: boolean;
readNamespaces: readonly string[];
writeNamespaces: readonly string[];
invalidatesNamespaces: readonly string[];
retryOnConflict: boolean;
requiresConfirm: boolean;
};
};
type ProjectSessionMcpToolInput = Omit<ProjectSessionMcpTool, "annotations"> & {
annotations: Omit<
ProjectSessionMcpTool["annotations"],
"inputFields" | "requiredInputFields" | "requiresConfirm"
> & { requiresConfirm?: boolean };
};
const createProjectSessionMcpTool = (
tool: ProjectSessionMcpToolInput
): ProjectSessionMcpTool => {
const { inputFields, requiredInputFields } = getInputJsonSchemaMetadata(
tool.inputSchema
);
return {
...tool,
annotations: {
...tool.annotations,
inputFields,
requiredInputFields,
requiresConfirm: tool.annotations.requiresConfirm ?? false,
},
};
};
export const mcpArgumentExamples: Record<
string,
readonly Readonly<Record<string, unknown>>[]
> = {
"meta.guide": [
{
brief: "Create a pricing page and style the hero",
taskScope: "visual-change",
workflow: "general",
},
{
brief: "Inventory custom code without changing the project",
taskScope: "read-only-audit",
workflow: "general",
},
{
brief: "Recreate a supplied design as a responsive page",
taskScope: "visual-change",
workflow: "design-input",
},
],
"inspect-auth-context": [{}],
"inspect-design-context": [{}],
"verify-font-assets": [{ assetIds: ["asset-regular", "asset-bold"] }],
"workflow.next": [
{ goal: "design-system-page" },
{ goal: "design-system-page", phase: "dry-run-section" },
],
"meta.get-more-tools": [
{ tools: ["insert-fragment"] },
{ tools: ["insert-component"] },
{ brief: "update-styles" },
],
"components.summary": [{}],
"components.list": [{ source: "all", documentType: "html" }],
"components.coverage-plan": [
{},
{ documentType: "html" },
{ documentType: "xml", detail: "roots" },
{ detail: "full" },
{ detail: "roots", offset: 0, limit: 20 },
{ detail: "parts", namespace: "@webstudio-is/sdk-components-react-radix" },
],
"components.coverage-status": [{ pagePath: "/design-system" }],
"components.coverage-insert-next": [
{
pagePath: "/design-system",
parentInstanceId: "root-instance-id",
},
],
"components.find": [{ brief: "radix tabs dialog select" }],
"components.search": [{ brief: "radix tabs dialog select" }],
"components.get": [
{ component: "@webstudio-is/sdk-components-react-radix:Select" },
],
"templates.list": [{ documentType: "html" }],
"templates.get": [
{ component: "@webstudio-is/sdk-components-react-radix:Select" },
],
refresh: [{ namespaces: ["pages", "instances", "styles"] }],
import: [
{
to: "https://p-destination-project-id.wstd.dev/?authToken=destination-token",
},
],
"download-asset": [{ assetId: "asset-id" }],
"upload-asset": [
{
asset: {
name: "Rajdhani-SemiBold.woff2",
type: "font",
format: "woff2",
meta: { family: "Rajdhani", style: "normal", weight: 600 },
},
assetsDir: ".webstudio/assets",
},
{
asset: {
name: "hero.png",
type: "image",
format: "png",
folderId: "folder-id",
meta: { width: 1200, height: 630 },
},
assetsDir: ".webstudio/assets",
},
{
asset: {
name: "hero.png",
type: "image",
format: "png",
meta: { width: 1200, height: 630 },
force: true,
},
assetsDir: ".webstudio/assets",
},
],
"upload-assets": [
{
assets: [
{
name: "hero.png",
type: "image",
format: "png",
folderId: "folder-id",
meta: { width: 1200, height: 630 },
},
],
assetsDir: ".webstudio/assets",
},
],
"list-asset-folders": [{}],
"create-asset-folder": [
{ name: "Marketing" },
{ name: "Photos", parentId: "marketing-folder-id" },
],
"update-asset-folder": [
{ folderId: "folder-id", values: { name: "Brand" } },
{ folderId: "folder-id", values: { parentId: null } },
],
"duplicate-asset-folder": [
{ folderId: "folder-id" },
{ folderId: "folder-id", parentId: "target-folder-id" },
],
"delete-asset-folder": [{ folderId: "folder-id" }],
"get-asset": [{ assetId: "asset-id" }],
"duplicate-asset": [
{ assetId: "asset-id" },
{ assetId: "asset-id", folderId: "target-folder-id" },
],
"preview.start": [{ source: "session" }],
"preview.submit-form": [
{
path: "/contact",
selector: "form",
values: [{ name: "email", value: "[email protected]" }],
},
],
"preview.status": [{}],
"preview.stop": [{}],
status: [{}, { verbose: true }],
"list-pages": [{ limit: 20 }],
"get-page-by-path": [{ path: "/pricing" }],
"list-instances": [{ pagePath: "/", maxDepth: 3 }],
"inspect-instance": [
{
instanceId: "instance-id",
include: ["props", "styles", "children"],
},
],
"search-project": [
{ query: "pricing" },
{ query: "api.example.com", namespaces: ["resources"] },
],
audit: [
{},
{ scopes: ["accessibility", "seo"] },
{ 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",
component: "@webstudio-is/sdk-components-react-radix:Switch",
},
],
"extract-slot": [
{
instanceSelector: ["header-section-id", "body-id"],
label: "Site header",
},
{
instanceSelector: ["header-section-id", "page-wrapper-id", "body-id"],
label: "Site header",
},
],
"insert-collection": [
{
parentInstanceId: "parent-id",
data: { type: "expression", value: "Posts.data.items" },
itemFragment:
"<article><h2>{expression`collectionItem.title ?? 'Untitled'`}</h2></article>",
},
{
parentInstanceId: "parent-id",
data: {
type: "json",
value: [{ name: "Starter" }, { name: "Pro" }],
},
itemFragment: "<div>{expression`collectionItem.name`}</div>",
},
],
"insert-fragment": [
{
parentInstanceId: "parent-id",
fragment:
"<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>",
},
{
parentInstanceId: "parent-id",
fragment:
"<section style={{ padding: 32, borderRadius: 16 }}><h2>Operations Console</h2><p>Semantic section with React-style object styles converted into editable Webstudio styles.</p></section>",
},
{
parentInstanceId: "parent-id",
fragment:
"<section ws:tokens={[token('accent', css`color: #0f766e;`)]} ws:style={css`display: grid; gap: 12px;`}><h2>Token Example</h2><button onClick={new ActionValue(['event'], expression`console.log(event)`)}>Track launch</button></section>",
},
{
parentInstanceId: "parent-id",
fragment:
"<section ws:tokens={[token('accent')]}><h2>Reuse an existing accent token</h2></section>",
},
{
parentInstanceId: "parent-id",
fragment: "<section><Switch><SwitchThumb /></Switch></section>",
},
],
"insert-fragment-verified": [
{
parentInstanceId: "parent-id",
pagePath: "/pricing",
fragment: "<section><h2>Pricing</h2></section>",
},
],
"update-text": [
{
instanceId: "instance-id",
childIndex: 0,
text: "Launch faster",
mode: "text",
},
{
instanceId: "instance-id",
childIndex: 0,
text: "user.name",
mode: "expression",
},
],
"replace-text": [
{
find: "Start free",
replace: "Get started",
match: "exact",
pagePath: "/pricing",
limit: 20,
},
],
"replace-prop-text": [
{
find: "old.example.com",
replace: "www.example.com",
match: "substring",
names: ["href", "code"],
limit: 20,
},
],
"update-page": [
{
pageId: "page-id",
values: {
title: '"Pricing"',
meta: {
description: '"Pricing plans"',
},
},
},
],
"update-props": [
{
updates: [
{
instanceId: "button-id",
name: "aria-label",
type: "string",
value: "Open menu",
},
{
instanceId: "textarea-id",
name: "placeholder",
type: "string",
value: "Describe your project",
},
],
},
],
"bind-props": [
{
bindings: [
{
instanceId: "link-id",
name: "href",
binding: { type: "expression", value: "currentPost.url" },
},
],
},
],
"list-css-variables": [{ withUsage: true }],
"define-css-variable": [
{
vars: {
"--color-primary": "#2d3748",
"--color-accent": "#e53e3e",
"--space-card": "1.5rem",
},
overwrite: true,
},
],
"delete-css-variable": [
{
names: ["--color-primary", "--color-accent", "--space-card"],
force: true,
},
],
"create-variable": [
{
scopeInstanceId: "body-id",
name: "title",
value: { type: "string", value: "Hello" },
},
{
scopeInstanceId: "body-id",
name: "count",
value: { type: "number", value: 3 },
},
{
scopeInstanceId: "body-id",
name: "featured",
value: { type: "boolean", value: true },
},
{
scopeInstanceId: "body-id",
name: "tags",
value: { type: "json", value: ["news", "product"] },
},
{
scopeInstanceId: "body-id",
name: "filters",
value: { type: "json", value: { tag: "news", page: 1 } },
},
],
"update-variable": [
{
dataSourceId: "variable-id",
values: { value: { type: "json", value: ["news", "product"] } },
},
],
"create-resource": [
{
resource: {
name: "Posts",
method: "get",
url: "https://api.example.com/posts",
headers: [],
},
},
{
resource: {
name: "Filtered Posts",
method: "get",
url: "https://api.example.com/posts",
searchParams: [
{ name: "tag", value: "filters.tag" },
{ name: "source", value: { type: "literal", value: "website" } },
{ name: "page", value: "(filters.page ?? 1).toString()" },
],
headers: [{ name: "Authorization", value: '"Bearer " + auth.token' }],
},
scopeInstanceId: "body-id",
dataSourceName: "posts",
},
{
resource: {
name: "Post GraphQL",
control: "graphql",
method: "post",
url: "https://api.example.com/graphql",
headers: [
{
name: "Content-Type",
value: { type: "literal", value: "application/json" },
},
],
body: '{ query: "query Post($slug: String!) { post(slug: $slug) { title } }", variables: { slug: system.params.slug } }',
},
scopeInstanceId: "body-id",
dataSourceName: "post",
exposeAsDataSource: true,
},
{
resource: {
name: "Current Date",
control: "system",
method: "get",
url: "/$resources/current-date",
headers: [],
},
scopeInstanceId: "body-id",
dataSourceName: "currentDate",
},
],
"update-resource": [
{
resourceId: "resource-id",
values: { url: "https://api.example.com/posts" },
},
{
resourceId: "resource-id",
values: { method: "post" },
exposeAsDataSource: false,
},
],
"list-assets-resources": [{}],
"get-assets-resource": [{ resourceId: "resource-id" }],
"create-assets-resource": [
{
name: "All assets",
scopeInstanceId: "body-id",
dataSourceName: "assets",
},
{
name: "Published posts",
scopeInstanceId: "body-id",
dataSourceName: "posts",
query: {
result: "many",
where: {
all: [
{
field: ["extension"],
operator: "eq",
value: { type: "literal", value: "md" },
},
{
field: ["folderId"],
operator: "eq",
value: { type: "literal", value: "folder-id" },
},
{
field: ["properties", "draft"],
operator: "ne",
value: { type: "literal", value: true },
},
],
},
sort: [
{ field: ["properties", "publishedAt"], direction: "desc" },
{ field: ["id"], direction: "asc" },
],
limit: { type: "literal", value: 20 },
offset: { type: "literal", value: 0 },
output: {
mode: "fields",
includeMetadata: false,
fields: [
["properties", "title"],
["properties", "slug"],
["properties", "publishedAt"],
["properties", "excerpt"],
],
},
content: { mode: "none" },
},
},
{
name: "Post by slug",
scopeInstanceId: "body-id",
dataSourceName: "post",
query: {
result: "one",
where: {
all: [
{
field: ["extension"],
operator: "eq",
value: { type: "literal", value: "md" },
},
{
field: ["folderId"],
operator: "eq",
value: { type: "literal", value: "folder-id" },
},
{
field: ["properties", "slug"],
operator: "eq",
value: "system.params.slug",
},
{
field: ["properties", "draft"],
operator: "ne",
value: { type: "literal", value: true },
},
],
},
output: {
mode: "fields",
includeMetadata: false,
fields: [
["properties", "title"],
["properties", "publishedAt"],
["properties", "excerpt"],
["properties", "featureImage"],
],
},
content: { mode: "markdown-body-ref" },
},
},
],
"update-assets-resource": [
{
resourceId: "resource-id",
values: {
query: {
limit: "50",
},
},
},
{ resourceId: "resource-id", values: { query: null } },
],
"validate-asset-query": [
{
query: {
where: {
all: [
{
field: ["properties", "slug"],
operator: "eq",
value: "hello-world",
},
],
},
limit: 1,
},
},
],
"preview-asset-query": [
{
query: {
result: "one",
where: {
all: [
{
field: ["extension"],
operator: "eq",
value: "md",
},
{
field: ["properties", "slug"],
operator: "eq",
value: "hello-world",
},
],
},
output: {
mode: "fields",
includeMetadata: false,
fields: [["properties", "title"]],
},
content: { mode: "markdown-body-ref", maxBytes: 1_048_576 },
},
},
],
"get-asset-field-catalog": [{}],
"update-asset": [
{
assetId: "font-asset-id",
values: { meta: { family: "Rajdhani", style: "normal", weight: 600 } },
},
{
assetId: "asset-id",
values: { description: "Team collaborating around a whiteboard" },
},
{
assetId: "asset-id",
values: { filename: "hero", folderId: "folder-id" },
},
{ assetId: "asset-id", values: { folderId: null } },
],
"list-assets": [{}, { verbose: true }],
"replace-asset": [{ fromAssetId: "old-asset-id", toAssetId: "new-asset-id" }],
"delete-asset": [
{ assetIds: ["asset-id"] },
{ assetIdPrefixes: ["generated-prefix"] },
],
"set-image-descriptions": [
{
updates: [
{
assetId: "hero-asset-id",
description: "Team collaborating around a whiteboard",
},
{ assetId: "background-texture-id", decorative: true },
],
},
],
"replace-resource-text": [
{
find: "api.old.example.com",
replace: "api.example.com",
fields: ["url"],
limit: 20,
},
],
"update-styles": [
{
updates: [
{
instanceId: "instance-id",
property: "color",
value: { type: "keyword", value: "red" },
},
],
},
],
"delete-styles": [
{
deletions: [{ instanceId: "instance-id", property: "box-shadow" }],
},
],
"apply-patch": [
{
baseVersion: 12,
transactions: [
{
id: "patch-transaction-label",
payload: [
{
namespace: "pages",
patches: [
{
op: "replace",
path: ["meta", "siteName"],
value: "Site name",
},
],
},
],
},
],
},
],
publish: [{ target: "production" }],
"create-domain": [{ domain: "www.example.com" }],
screenshot: [
{
path: "/",
output: "screenshots/home.png",
viewport: { width: 1440, height: 900 },
waitUntil: "load",
waitForTimeout: 250,
},
{
path: "/pricing",
output: "screenshots/pricing.png",
viewport: { width: 1440, height: 900 },
waitUntil: "load",
waitForTimeout: 250,
},
{
url: "https://example.com",
output: "current.png",
viewport: { width: 1440, height: 900 },
browser: "auto",
},
],
"screenshot.responsive": [
{
path: "/pricing",
viewports: [
{ width: 1440, height: 900 },
{ width: 390, height: 844 },
],
source: "session",
},
],
"verify-page-responsive": [
{
path: "/pricing",
viewports: [
{ width: 1440, height: 900 },
{ width: 390, height: 844 },
],
source: "session",
},
],
"screenshot.diff": [
{
baselinePath: "baseline.png",
currentPath: "current.png",
outputDir: "visual-diff",
threshold: 0.1,
ignoreTopNormalizedY: 0,
expectedText: ["Pricing", "Start free"],
expectedVisual: {
maxMismatchPercentage: 2,
maxChangedRegions: 3,
dominantColorChange: {
channel: "luminance",
direction: "increase",
minMagnitude: 10,
},
},
},
],
"vision.install-ocr": [{ confirm: true }],
} as const;
const getMcpExamples = (command: string): readonly unknown[] =>
mcpArgumentExamples[command] ?? [];
const getMcpOutputSchema = (dataSchema: InputJsonSchema): InputJsonSchema => {
const { $defs, ...data } = dataSchema;
return {
type: "object",
...($defs === undefined ? {} : { $defs }),
oneOf: [
{
type: "object",
properties: {
ok: { type: "boolean", const: true },
data,
meta: { type: "object", additionalProperties: true },
},
required: ["ok", "data", "meta"],
additionalProperties: false,
},
{
type: "object",
properties: {
ok: { type: "boolean", const: false },
data,
error: {
type: "object",
properties: {
code: { type: "string" },
message: { type: "string" },
issues: semanticValidationIssuesJsonSchema,
},
required: ["code", "message"],
additionalProperties: true,
},
meta: { type: "object", additionalProperties: true },
},
required: ["ok", "error", "meta"],
additionalProperties: false,
},
],
};
};
const sessionStatusDataSchema = {
type: "object",
properties: { loaded: { type: "boolean" } },
required: ["loaded"],
additionalProperties: false,
} as const satisfies InputJsonSchema;
const refreshDataSchema = {
type: "object",
properties: {
refreshedNamespaces: {
type: "array",
items: { type: "string", enum: builderNamespaces },
},
},
required: ["refreshedNamespaces"],
additionalProperties: false,
} as const satisfies InputJsonSchema;
const previewStatusDataSchema = {
type: "object",
properties: {
url: { type: "string" },
pid: { type: "integer" },
running: { type: "boolean" },
mode: {
type: "string",
enum: projectSessionPreviewModes,
},
stale: { type: "boolean" },
renderedProjectVersion: { type: "integer" },
},
required: ["running"],
additionalProperties: false,
} as const satisfies InputJsonSchema;
const previewDataSchema = {
...previewStatusDataSchema,
properties: {
...previewStatusDataSchema.properties,
confirmationRequired: { type: "boolean" },
operation: { type: "string" },
estimatedDuration: { type: "string" },
reason: { type: "string" },
confirmationToken: { type: "string" },
fasterAlternative: {
type: "object",
properties: {
operation: { type: "string" },
estimatedDuration: { type: "string" },
limitations: { type: "string" },
},
required: ["operation", "estimatedDuration", "limitations"],
additionalProperties: false,
},
},
required: ["running", "mode"],
} as const satisfies InputJsonSchema;
const previewSubmitFormDataSchema = {
type: "object",
properties: {
status: {
type: "string",
enum: ["validation_failed", "submitted", "unknown"],
},
formState: { type: "string" },
results: {
type: "array",
items: {
type: "object",
properties: {
status: { type: "integer" },
resourceId: { type: "string" },
resourceName: { type: "string" },
},
required: ["status"],
additionalProperties: false,
},
},
errors: {
type: "array",
items: {
type: "object",
properties: {
status: { type: "integer" },
name: { type: "string" },
message: { type: "string" },
},
required: ["message"],
additionalProperties: false,
},
},
exchanges: {
type: "array",
items: {
type: "object",
properties: {
status: { type: "integer" },
url: { type: "string" },
},
required: ["status", "url"],
additionalProperties: false,
},
},
pageUrl: { type: "string" },
redirect: { type: "string" },
correlationId: { type: "string" },
},
required: [
"status",
"results",
"errors",
"exchanges",
"pageUrl",
"correlationId",
],
additionalProperties: false,
} as const satisfies InputJsonSchema;
const restorePointSummaryDataSchema = getZodObjectSchema(
projectSessionRestorePointSummarySchema
);
const restorePointCreateInput = z.object({ name: z.string().trim().min(1) });
const restorePointRevertInput = z.object({ id: z.string().min(1) });
const restorePointDeleteInput = z.object({
id: z.string().min(1),
confirm: z.literal(true),
});
const restorePointTools: readonly ProjectSessionMcpTool[] = [
createProjectSessionMcpTool({
name: "create-restore-point",
description:
"Create a named local restore point for versioned Build data before risky agent work. Asset records remain unchanged by restore points.",
inputSchema: getZodMcpInputSchema(restorePointCreateInput),
outputSchema: getMcpOutputSchema(restorePointSummaryDataSchema),
annotations: {
command: "create-restore-point",
operationId: "project-session.restore-point.create",
method: "session",
permit: "edit",
localCapable: true,
serverOnly: false,
readNamespaces: restorePointNamespaces,
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "list-restore-points",
description: "List named local restore points for the configured project.",
inputSchema: emptyInputSchema,
outputSchema: getMcpOutputSchema({
type: "object",
properties: {
points: { type: "array", items: restorePointSummaryDataSchema },
},
required: ["points"],
additionalProperties: false,
}),
annotations: {
command: "list-restore-points",
operationId: "project-session.restore-point.list",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "delete-restore-point",
description:
"Permanently delete one local restore point after explicit confirmation.",
inputSchema: getZodMcpInputSchema(restorePointDeleteInput),
outputSchema: getMcpOutputSchema({
type: "object",
properties: { deleted: { type: "boolean" } },
required: ["deleted"],
additionalProperties: false,
}),
annotations: {
command: "delete-restore-point",
operationId: "project-session.restore-point.delete",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "revert-to-restore-point",
description:
"Revert versioned Build data to a named restore point without changing assets. This is destructive and requires a reviewed dry-run confirmation token.",
inputSchema: getZodMcpInputSchema(restorePointRevertInput),
outputSchema: getMcpOutputSchema({
type: "object",
properties: {
restoredNamespaces: {
type: "array",
items: { type: "string", enum: restorePointNamespaces },
},
},
required: ["restoredNamespaces"],
additionalProperties: false,
}),
annotations: {
command: "revert-to-restore-point",
operationId: "project-session.restore-point.revert",
method: "session",
permit: "edit",
localCapable: true,
serverOnly: false,
readNamespaces: restorePointNamespaces,
writeNamespaces: restorePointNamespaces,
invalidatesNamespaces: [],
retryOnConflict: false,
requiresConfirm: true,
},
}),
];
const sessionTools: readonly ProjectSessionMcpTool[] = [
createProjectSessionMcpTool({
name: "meta.index",
description:
"Return a concise Webstudio MCP capability catalog and discovery guide.",
inputSchema: metaIndexInputSchema,
annotations: {
command: "meta.index",
operationId: "meta.index",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "meta.guide",
description:
'Return a workflow and tools for a user goal. Pass taskScope and workflow explicitly; use taskScope:"read-only-audit" when no state may change. Brief text only ranks general tool discovery.',
inputSchema: metaGuideInputSchema,
annotations: {
command: "meta.guide",
operationId: "meta.guide",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "workflow.next",
description:
"Return one bounded workflow phase for delegated/non-streaming agents. Use this to avoid broad silent work such as creating a full design-system page in one run.",
inputSchema: workflowNextInputSchema,
annotations: {
command: "workflow.next",
operationId: "workflow.next",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "meta.get-more-tools",
description:
'Return detailed tool metadata and examples. Prefer exact tool names, for example {"tools":["insert-fragment"]}. To search, pass a string brief such as {"brief":"style updates"}.',
inputSchema: toolDetailsInputSchema,
annotations: {
command: "meta.get-more-tools",
operationId: "meta.get-more-tools",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "checkpoint.ack",
description:
"Acknowledge that the previous checkpoint was reported to the parent/user before continuing a long-running task.",
inputSchema: {
type: "object",
additionalProperties: false,
properties: {
reported: {
type: "boolean",
description:
"Must be true after the checkpoint was reported to the parent/user.",
},
summary: {
type: "string",
minLength: 1,
description:
"Brief parent-visible checkpoint summary that was reported, including the phase, command/result, issue/workaround, and next intended action.",
},
continueAfterReport: {
type: "boolean",
description:
"Must be true only after the parent/user has seen the checkpoint summary and continued the task.",
},
},
required: ["reported", "summary", "continueAfterReport"],
},
annotations: {
command: "checkpoint.ack",
operationId: "checkpoint.ack",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "components.summary",
description:
'Return component counts by default, or paginated component entries with detail:"components".',
inputSchema: componentSummaryInputSchema,
annotations: {
command: "components.summary",
operationId: "components.summary",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "components.list",
description:
"List compact metadata for insertable components and templates. Use components.get or templates.get for one complete item.",
inputSchema: registryListInputSchema,
annotations: {
command: "components.list",
operationId: "components.list",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "components.coverage-plan",
description:
'Return a paged plan for using every known component. Default is compact; pass detail:"full", detail:"roots", or detail:"parts" for more.',
inputSchema: {
type: "object",
additionalProperties: false,
properties: {
detail: {
type: "string",
enum: ["summary", "roots", "parts", "full"],
description:
"Amount of coverage detail to return. Default summary returns counts and the first root page only.",
},
namespace: {
type: "string",
description:
"Optional component namespace filter, for example @webstudio-is/sdk-components-react-radix.",
},
documentType: {
type: "string",
enum: ["html", "xml", "text"],
description:
'Target page document type. Defaults to "html"; XML-only components are included only for "xml".',
},
offset: {
type: "number",
description: "Zero-based pagination offset for roots or parts.",
},
limit: {
type: "number",
description:
"Maximum roots or parts to return. Defaults to 20 and is capped at 100.",
},
},
required: [],
},
annotations: {
command: "components.coverage-plan",
operationId: "components.coverage-plan",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "components.coverage-status",
description:
"Compare a page's current instances with the available component catalog and return covered/missing components.",
inputSchema: componentCoverageStatusInputSchema,
annotations: {
command: "components.coverage-status",
operationId: "components.coverage-status",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: ["pages", "instances"],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "components.coverage-insert-next",
description:
"Checkpoint-safe design-system helper: inspect coverage, insert exactly one missing root/template component, then return coverage before and after.",
inputSchema: componentCoverageInsertNextInputSchema,
annotations: {
command: "components.coverage-insert-next",
operationId: "components.coverage-insert-next",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: ["pages", "instances"],
writeNamespaces: [
"instances",
"props",
"styles",
"styleSources",
"styleSourceSelections",
],
invalidatesNamespaces: [
"instances",
"props",
"styles",
"styleSources",
"styleSourceSelections",
],
retryOnConflict: true,
},
}),
createProjectSessionMcpTool({
name: "components.find",
description:
'Search known components by id, namespace, label, category, or content model. Pass a string brief, for example {"brief":"radix tabs dialog select"}.',
inputSchema: componentFindInputSchema,
annotations: {
command: "components.find",
operationId: "components.find",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "components.search",
description:
'Search shadcn-compatible Webstudio component/template registry items by id, namespace, label, category, or content model. Pass a string brief, for example {"brief":"radix tabs dialog select"}.',
inputSchema: componentFindInputSchema,
annotations: {
command: "components.search",
operationId: "components.search",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "components.get",
description:
"Return full metadata for one known component id, including insertability, props, states, and content model.",
inputSchema: componentInputSchema,
annotations: {
command: "components.get",
operationId: "components.get",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "templates.list",
description:
"List compact metadata for registered templates. Use templates.get for one complete insertion payload.",
inputSchema: registryListInputSchema,
annotations: {
command: "templates.list",
operationId: "templates.list",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "templates.get",
description:
"Return one shadcn-compatible Webstudio template registry item and its insertion payload metadata.",
inputSchema: templateInputSchema,
annotations: {
command: "templates.get",
operationId: "templates.get",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "status",
description:
"Read the current local ProjectSession status. Pass verbose true only when debugging namespace, compatibility, freshness, or diagnostic details.",
inputSchema: statusInputSchema,
outputSchema: getMcpOutputSchema(sessionStatusDataSchema),
annotations: {
command: "status",
operationId: "project-session.status",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "refresh",
description:
"Refresh local ProjectSession namespaces from the configured project. Pass { namespaces } or omit it to refresh all namespaces.",
inputSchema: {
...emptyInputSchema,
properties: {
namespaces: {
type: "array",
items: { type: "string", enum: builderNamespaces },
description:
"Synced namespaces to refresh. Omit to refresh every namespace.",
},
},
},
outputSchema: getMcpOutputSchema(refreshDataSchema),
annotations: {
command: "refresh",
operationId: "project-session.refresh",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: builderNamespaces,
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "reset-session",
description: "Delete the persisted local ProjectSession snapshot.",
inputSchema: emptyInputSchema,
outputSchema: getMcpOutputSchema(sessionStatusDataSchema),
annotations: {
command: "reset-session",
operationId: "project-session.reset",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: builderNamespaces,
retryOnConflict: false,
},
}),
];
const authContextOperationCommands = [
"get-project-settings",
"list-pages",
"list-resources",
"list-variables",
] as const;
const inspectAuthContextTool = createProjectSessionMcpTool({
name: "inspect-auth-context",
description:
"Return one bounded authentication discovery bundle with project settings, pages, resources, and variables. Use once before authentication mutations instead of calling the four underlying reads separately.",
inputSchema: emptyInputSchema,
mcpExamples: getMcpExamples("inspect-auth-context"),
annotations: {
command: "inspect-auth-context",
operationId: "workflow.auth-context",
method: "session",
permit: "view",
localCapable: true,
serverOnly: false,
readNamespaces: ["projectSettings", "pages", "resources", "dataSources"],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
const designContextOperationCommands = [
"list-pages",
"list-breakpoints",
"list-design-tokens",
"list-assets",
"list-variables",
] as const;
const inspectDesignContextTool = createProjectSessionMcpTool({
name: "inspect-design-context",
description:
"Return one bounded design discovery bundle with pages, breakpoints, design tokens, assets, and variables. Use once before design-driven page mutations instead of calling the five underlying reads separately.",
inputSchema: emptyInputSchema,
mcpExamples: getMcpExamples("inspect-design-context"),
annotations: {
command: "inspect-design-context",
operationId: "workflow.design-context",
method: "session",
permit: "view",
localCapable: true,
serverOnly: false,
readNamespaces: ["pages", "breakpoints", "styles", "assets", "dataSources"],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
const verifyFontAssetsInputSchema = {
...emptyInputSchema,
properties: {
assetIds: {
type: "array",
description: "Font asset ids returned by upload-assets.",
items: { type: "string" },
minItems: 1,
maxItems: 50,
},
},
required: ["assetIds"],
} as const satisfies ProjectSessionMcpInputSchema;
const verifyFontAssetsTool = createProjectSessionMcpTool({
name: "verify-font-assets",
description:
"Refresh the asset namespace and return several persisted font assets in one verification call.",
inputSchema: verifyFontAssetsInputSchema,
mcpExamples: getMcpExamples("verify-font-assets"),
annotations: {
command: "verify-font-assets",
operationId: "workflow.verify-font-assets",
method: "session",
permit: "api",
localCapable: true,
serverOnly: false,
readNamespaces: ["assets"],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
const insertFragmentVerifiedOperationCommands = [
"insert-fragment",
"verify-bindings",
] as const;
const createInsertFragmentVerifiedTool = (
operations: readonly PublicMcpOperation[]
) => {
const insertion = operations.find(
(operation) => operation.command === "insert-fragment"
);
const verification = operations.find(
(operation) => operation.command === "verify-bindings"
);
if (insertion === undefined || verification === undefined) {
throw new Error(
"insert-fragment-verified requires insert-fragment and verify-bindings operations."
);
}
const mergeNamespaces = (
key: "readNamespaces" | "writeNamespaces" | "invalidatesNamespaces"
) => [...new Set([...insertion[key], ...verification[key]])];
return createProjectSessionMcpTool({
name: "insert-fragment-verified",
description:
"Insert an authored Webstudio JSX fragment and immediately verify persisted bindings on its page. Prefer this when binding verification is required directly after insertion.",
inputSchema: insertFragmentVerifiedMcpInputSchema,
mcpExamples: getMcpExamples("insert-fragment-verified"),
annotations: {
command: "insert-fragment-verified",
operationId: "workflow.insert-fragment-verified",
method: "mutation",
permit: insertion.permit,
localCapable: insertion.localCapable && verification.localCapable,
serverOnly: insertion.serverOnly || verification.serverOnly,
readNamespaces: mergeNamespaces("readNamespaces"),
writeNamespaces: mergeNamespaces("writeNamespaces"),
invalidatesNamespaces: mergeNamespaces("invalidatesNamespaces"),
retryOnConflict: insertion.retryOnConflict,
},
});
};
const screenshotTool = createProjectSessionMcpTool({
name: "screenshot",
description:
"Capture a PNG screenshot plus rendered viewport/content dimensions and horizontal-overflow evidence so an AI can inspect what was actually built, compare it with the intent, and iterate.",
inputSchema: screenshotInputSchema,
mcpExamples: getMcpExamples("screenshot"),
annotations: {
command: "screenshot",
operationId: "screenshot.capture",
method: "session",
permit: "api",
localCapable: false,
serverOnly: true,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
const responsiveScreenshotTool = createProjectSessionMcpTool({
name: "screenshot.responsive",
description:
"Capture one generated route at multiple viewport sizes in one call. Starts or refreshes the session preview automatically and reuses one browser session.",
inputSchema: responsiveScreenshotInputSchema,
mcpExamples: getMcpExamples("screenshot.responsive"),
annotations: {
command: "screenshot.responsive",
operationId: "screenshot.responsive",
method: "session",
permit: "api",
localCapable: false,
serverOnly: true,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
const createResponsivePageVerificationTool = (
operations: readonly PublicMcpOperation[]
) => {
const audit = operations.find((operation) => operation.command === "audit");
if (audit === undefined) {
throw new Error("verify-page-responsive requires the audit operation.");
}
return createProjectSessionMcpTool({
name: "verify-page-responsive",
description:
"Capture one generated route at multiple viewport sizes and immediately run its static audit in one terminal verification call.",
inputSchema: responsiveScreenshotInputSchema,
mcpExamples: getMcpExamples("verify-page-responsive"),
annotations: {
command: "verify-page-responsive",
operationId: "workflow.verify-page-responsive",
method: "session",
permit: audit.permit,
localCapable: false,
serverOnly: true,
readNamespaces: audit.readNamespaces,
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
};
const screenshotDiffTool = createProjectSessionMcpTool({
name: "screenshot.diff",
description:
"Compare two PNG screenshots, write diff artifacts, and return pixel regions plus optional OCR textAnalysis for visual verification.",
inputSchema: screenshotDiffInputSchema,
mcpExamples: getMcpExamples("screenshot.diff"),
annotations: {
command: "screenshot.diff",
operationId: "screenshot.diff",
method: "session",
permit: "api",
localCapable: false,
serverOnly: true,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
const installOcrTool = createProjectSessionMcpTool({
name: "vision.install-ocr",
description:
"Install Tesseract OCR for screenshot.diff textAnalysis after explicit user consent. Use only when OCR is unavailable and the user agrees.",
inputSchema: installOcrInputSchema,
mcpExamples: getMcpExamples("vision.install-ocr"),
annotations: {
command: "vision.install-ocr",
operationId: "vision.install-ocr",
method: "session",
permit: "api",
localCapable: false,
serverOnly: true,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
const importTool = createProjectSessionMcpTool({
name: "import",
description:
"Import the local synced project bundle into a destination project. Run sync first; pass a destination share link with build permissions.",
inputSchema: importInputSchema,
mcpExamples: getMcpExamples("import"),
annotations: {
command: "import",
operationId: "project.import",
method: "session",
permit: "build",
localCapable: false,
serverOnly: true,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
const downloadAssetTool = createProjectSessionMcpTool({
name: "download-asset",
description:
"Download one project Asset. Markdown and MDX include source and diagnostics.",
inputSchema: downloadAssetInputSchema,
outputSchema: getMcpOutputSchema({
type: "object",
properties: {
assetId: { type: "string" },
path: { type: "string" },
source: { type: "string" },
diagnostics: {
type: "array",
items: {
type: "object",
properties: {
code: { type: "string" },
severity: { type: "string", enum: ["error", "warning"] },
message: { type: "string" },
nodeType: { type: "string" },
reason: { type: "string" },
assetId: { type: "string" },
blockInstanceId: { type: "string" },
contentRef: { type: "string" },
renderScope: { type: "string" },
templateName: { type: "string" },
propName: { type: "string" },
line: { type: "number" },
column: { type: "number" },
sourceRange: {
type: "object",
properties: {
start: {
type: "object",
properties: {
line: { type: "number" },
column: { type: "number" },
offset: { type: "number" },
},
required: ["line", "column"],
},
end: {
type: "object",
properties: {
line: { type: "number" },
column: { type: "number" },
offset: { type: "number" },
},
required: ["line", "column"],
},
},
required: ["start", "end"],
},
},
required: ["code", "severity"],
},
},
},
required: ["assetId", "path"],
additionalProperties: false,
}),
mcpExamples: getMcpExamples("download-asset"),
annotations: {
command: "download-asset",
operationId: "assets.download",
method: "session",
permit: "view",
localCapable: false,
serverOnly: true,
readNamespaces: ["assets"],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
const previewTools: readonly ProjectSessionMcpTool[] = [
createProjectSessionMcpTool({
name: "preview.submit-form",
description:
"Submit a rendered form in this session's local Preview browser. Native validation runs before dispatch. Unknown outcomes are never retried; inspect the correlationId before deciding what to do next.",
inputSchema: previewSubmitFormInputSchema,
outputSchema: getMcpOutputSchema(previewSubmitFormDataSchema),
mcpExamples: getMcpExamples("preview.submit-form"),
annotations: {
command: "preview.submit-form",
operationId: "preview.submit-form",
method: "session",
permit: "api",
localCapable: false,
serverOnly: true,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "preview.start",
description:
"Start or refresh a generated-site preview. The iterative default keeps the server and browser alive and normally reloads the generated route after each MCP edit; production mode performs the full build used by audits.",
inputSchema: previewInputSchema,
outputSchema: getMcpOutputSchema(previewDataSchema),
mcpExamples: getMcpExamples("preview.start"),
annotations: {
command: "preview.start",
operationId: "preview.start",
method: "session",
permit: "api",
localCapable: false,
serverOnly: true,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "preview.status",
description:
"Return the active generated-site preview server URL and process state for screenshot-based verification.",
inputSchema: emptyInputSchema,
outputSchema: getMcpOutputSchema(previewStatusDataSchema),
mcpExamples: getMcpExamples("preview.status"),
annotations: {
command: "preview.status",
operationId: "preview.status",
method: "session",
permit: "api",
localCapable: false,
serverOnly: true,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
createProjectSessionMcpTool({
name: "preview.stop",
description:
"Stop the active generated-site preview server owned by this MCP session.",
inputSchema: emptyInputSchema,
outputSchema: getMcpOutputSchema(previewStatusDataSchema),
mcpExamples: getMcpExamples("preview.stop"),
annotations: {
command: "preview.stop",
operationId: "preview.stop",
method: "session",
permit: "api",
localCapable: false,
serverOnly: true,
readNamespaces: [],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
}),
];
const simulateFormTool = createProjectSessionMcpTool({
name: "forms.simulate-submission",
description:
"Submit synthetic string fields for a saved Form through the trusted Builder server Form engine. This can trigger configured HTTP and Email Resources, so verify recipients before calling.",
inputSchema: {
type: "object",
properties: {
path: { type: "string" },
siteOrigin: {
type: "string",
description:
"Optional check against the project's publisher origin; the Builder server determines the actual origin.",
},
formId: { type: "string" },
arrayNames: { type: "array", items: { type: "string" } },
values: {
type: "array",
items: {
type: "object",
properties: { name: { type: "string" }, value: { type: "string" } },
required: ["name", "value"],
additionalProperties: false,
},
},
},
required: ["path", "formId", "values"],
additionalProperties: false,
},
outputSchema: getMcpOutputSchema({
type: "object",
properties: {
success: { type: "boolean" },
status: { type: "integer" },
results: {
type: "array",
items: {
type: "object",
properties: {
status: { type: "integer" },
resourceId: { type: "string" },
},
required: ["status"],
additionalProperties: false,
},
},
errors: {
type: "array",
items: {
type: "object",
properties: {
status: { type: "integer" },
message: { type: "string" },
},
required: ["message"],
additionalProperties: false,
},
},
},
required: ["success", "status", "results", "errors"],
additionalProperties: false,
}),
annotations: {
command: "forms.simulate-submission",
operationId: "forms.simulate-submission",
method: "session",
permit: "api",
localCapable: false,
serverOnly: true,
readNamespaces: [
"pages",
"instances",
"props",
"dataSources",
"resources",
"projectSettings",
],
writeNamespaces: [],
invalidatesNamespaces: [],
retryOnConflict: false,
},
});
type McpStructuredError = {
code: string;
message: string;
issues?: readonly SemanticValidationIssue[];
};
type DestructiveConfirmation = {
required: true;
operation: string;
token: string;
expiresAt: string;
summary: {
namespaces: string[];
changeCount: number;
patchCount: number;
patchOperations: Record<string, number>;
};
};
type ProjectSessionMcpMeta = {
session?: ReturnType<typeof serializeProjectSessionMeta>;
next?: string[];
confirmation?: DestructiveConfirmation;
};
type ProjectSessionMcpStructuredContent = {
data: unknown;
meta: ProjectSessionMcpMeta;
} & ({ ok: true } | { ok: false; error: McpStructuredError });
class ProjectSessionMcpCheckpointError extends Error {
code = "CHECKPOINT_REQUIRED";
}
export type ProjectSessionMcpCheckpoint = {
tool: string;
message: string;
nextCommand?: string;
};
export type ProjectSessionMcpToolResult = {
content: [{ type: "text"; text: string }];
structuredContent: ProjectSessionMcpStructuredContent;
isError?: boolean;
};
export type ProjectSessionMcpResource = {
uri: string;
name: string;
description: string;
mimeType: "application/json" | "text/markdown";
};
type SdkTool = {
name: string;
description?: string;
inputSchema: ProjectSessionMcpInputSchema;
annotations?: {
readOnlyHint?: true;
destructiveHint?: false;
openWorldHint?: false;
};
};
export const hiddenMcpOperationCommands = new Set<string>([
// Hydrated Map-backed sourceData is available only to typed API callers.
// MCP callers use duplicate-page or serializable page-transfer workflows.
"copy-page",
]);
const mcpOperationSchemaInlineSizes = new Map<string, number>([
["search-project", 0],
["set-instance-name", 0],
["migrate-content-block-template-references", 0],
["edit-content-block-source", 0],
["update-content-block-frontmatter", 0],
["insert-fragment", 1_000],
// The nested Resource schema is available through meta.get-more-tools.
["upsert-resource-prop", 2_000],
["create-assets-resource", 2_500],
["update-assets-resource", 2_500],
["validate-asset-query", 2_500],
["preview-asset-query", 2_500],
]);
const detailedMcpInputSchemas = new WeakMap<
ProjectSessionMcpTool,
ProjectSessionMcpInputSchema
>();
export const getDetailedProjectSessionMcpInputSchema = (
tool: ProjectSessionMcpTool
) => detailedMcpInputSchemas.get(tool) ?? tool.inputSchema;
export const listProjectSessionMcpTools = (
operations: readonly PublicMcpOperation[],
options: {
includeImport?: boolean;
includeDownloadAsset?: boolean;
includeScreenshot?: boolean;
includeResponsiveScreenshot?: boolean;
includeScreenshotDiff?: boolean;
includeInstallOcr?: boolean;
includePreview?: boolean;
includePreviewSubmitForm?: boolean;
includeSimulateForm?: boolean;
includeRestorePoints?: boolean;
} = {}
): ProjectSessionMcpTool[] => [
...operations
.filter(
(operation) => hiddenMcpOperationCommands.has(operation.command) === false
)
.map((operation) => {
const override = mcpOperationOverrides.get(operation.command);
const operationInputSchema = getMcpOperationInputSchema(operation, {
includeRenderedAudit:
options.includeScreenshot === true && options.includePreview === true,
schema: override?.inputSchema,
});
const { inputSchema, detailedInputSchema } = getHandshakeInputSchema(
operationInputSchema,
mcpOperationSchemaInlineSizes.get(operation.command)
);
const tool = createProjectSessionMcpTool({
name: operation.command,
description: override?.description ?? operation.description,
inputSchema,
...(operation.outputSchema === undefined
? {}
: { outputSchema: getMcpOutputSchema(operation.outputSchema) }),
mcpExamples: getMcpExamples(operation.command),
annotations: {
command: operation.command,
operationId: operation.id,
method: operation.method,
permit: operation.permit,
localCapable: operation.localCapable,
serverOnly: operation.serverOnly,
readNamespaces: operation.readNamespaces,
writeNamespaces: operation.writeNamespaces,
invalidatesNamespaces: operation.invalidatesNamespaces,
retryOnConflict: operation.retryOnConflict,
requiresConfirm: operation.requiresConfirm,
},
});
if (detailedInputSchema !== undefined) {
detailedMcpInputSchemas.set(tool, detailedInputSchema);
}
return tool;
}),
...sessionTools.map((tool) => ({
...tool,
mcpExamples: getMcpExamples(tool.name),
})),
...(authContextOperationCommands.every((command) =>
operations.some((operation) => operation.command === command)
)
? [inspectAuthContextTool]
: []),
...(designContextOperationCommands.every((command) =>
operations.some((operation) => operation.command === command)
)
? [inspectDesignContextTool]
: []),
...(operations.some((operation) => operation.command === "get-asset")
? [verifyFontAssetsTool]
: []),
...(insertFragmentVerifiedOperationCommands.every((command) =>
operations.some((operation) => operation.command === command)
)
? [createInsertFragmentVerifiedTool(operations)]
: []),
...(options.includeRestorePoints ? restorePointTools : []),
...(options.includeImport ? [importTool] : []),
...(options.includeDownloadAsset ? [downloadAssetTool] : []),
...(options.includeScreenshot ? [screenshotTool] : []),
...(options.includeResponsiveScreenshot ? [responsiveScreenshotTool] : []),
...(options.includeResponsiveScreenshot &&
operations.some((operation) => operation.command === "audit")
? [createResponsivePageVerificationTool(operations)]
: []),
...(options.includeScreenshotDiff ? [screenshotDiffTool] : []),
...(options.includeInstallOcr ? [installOcrTool] : []),
...(options.includeSimulateForm ? [simulateFormTool] : []),
...(options.includePreview
? previewTools.filter(
(tool) =>
tool.name !== "preview.submit-form" ||
options.includePreviewSubmitForm === true
)
: []),
];
const toMetaResult = (data: unknown): ProjectSessionMcpToolResult => {
const structuredContent = {
ok: true as const,
data,
meta: {},
} satisfies ProjectSessionMcpStructuredContent;
return {
content: [{ type: "text", text: JSON.stringify(structuredContent) }],
structuredContent,
};
};
export const getProjectSessionMcpCheckpoint = (
tool: string,
data: unknown
): ProjectSessionMcpCheckpoint | undefined => {
if (isPlainRecord(data) === false) {
return;
}
const checkpoint = data.checkpoint;
if (
isPlainRecord(checkpoint) &&
checkpoint.required === true &&
typeof checkpoint.instruction === "string"
) {
return {
tool,
message: checkpoint.instruction,
nextCommand:
typeof checkpoint.nextCommand === "string"
? checkpoint.nextCommand
: undefined,
};
}
};
type McpCapabilityArea = {
area: string;
goal: string;
tools: string[];
};
const capabilityAreas = [
{
area: "visual-verification",
goal: "Let a vision-capable AI see the rendered result, compare it with the user's intent, and iterate.",
tools: [
"preview.start",
"preview.status",
"preview.stop",
"screenshot",
"verify-page-responsive",
"screenshot.diff",
"vision.install-ocr",
],
},
{
area: "discover",
goal: "Understand connection, permissions, project status, and available tools.",
tools: [
"meta.index",
"meta.guide",
"meta.get-more-tools",
"workflow.next",
"inspect-auth-context",
"inspect-design-context",
"verify-font-assets",
"components.summary",
"components.coverage-plan",
"components.coverage-status",
"components.coverage-insert-next",
"components.find",
"components.get",
"status",
"permissions",
"whoami",
"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.",
tools: ["refresh", "reset-session", "import"],
},
{
area: "pages",
goal: "Create, inspect, update, duplicate, delete, and organize pages and folders.",
tools: [
"list-pages",
"get-page",
"get-page-by-path",
"create-page",
"update-page",
"get-project-settings",
"update-project-settings",
"list-response-headers",
"set-response-header",
"delete-response-header",
"list-redirects",
"create-redirect",
"update-redirect",
"delete-redirect",
"duplicate-page",
"delete-page",
"list-page-templates",
"create-page-template",
"update-page-template",
"delete-page-template",
"duplicate-page-template",
"reorder-page-template",
"create-page-from-template",
"list-folders",
"create-folder",
"update-folder",
"delete-folder",
],
},
{
area: "content",
goal: "Inspect and edit element instances, text, props, bindings, and page content.",
tools: [
"list-instances",
"inspect-instance",
"insert-fragment",
"insert-fragment-verified",
"insert-component",
"move-instance",
"clone-instance",
"delete-instance",
"list-texts",
"update-text",
"set-text-content",
"replace-text",
"replace-prop-text",
"update-props",
"delete-props",
"bind-props",
],
},
{
area: "styles",
goal: "Read and change styles, design tokens, CSS variables, and breakpoints.",
tools: [
"get-styles",
"update-styles",
"delete-styles",
"replace-styles",
"list-design-tokens",
"create-design-token",
"update-design-token-styles",
"delete-design-token-styles",
"attach-design-token",
"detach-design-token",
"extract-design-token",
"list-css-variables",
"define-css-variable",
"delete-css-variable",
"rewrite-css-variable-refs",
"list-breakpoints",
"create-breakpoint",
"update-breakpoint",
"delete-breakpoint",
],
},
{
area: "data",
goal: "Manage data variables and resources.",
tools: [
"list-variables",
"create-variable",
"update-variable",
"delete-variable",
"list-resources",
"create-resource",
"update-resource",
"replace-resource-text",
"delete-resource",
],
},
{
area: "assets",
goal: "Manage asset folders and uploaded assets, including listing, creating, renaming, moving, duplicating, downloading, uploading, editing text content, replacing, and deleting.",
tools: [
"list-asset-folders",
"create-asset-folder",
"update-asset-folder",
"duplicate-asset-folder",
"delete-asset-folder",
"list-assets",
"get-asset",
"list-fonts",
"upload-asset",
"upload-assets",
"download-asset",
"update-asset-content",
"update-asset",
"duplicate-asset",
"set-image-descriptions",
"find-asset-usage",
"replace-asset",
"delete-asset",
],
},
{
area: "publish",
goal: "Validate and publish projects, inspect publish jobs, and manage domains.",
tools: [
"validate-publish",
"publish",
"list-publishes",
"get-publish-job",
"unpublish",
"list-domains",
"create-domain",
"update-domain",
"delete-domain",
"verify-domain",
],
},
{
area: "raw-patch",
goal: "Use raw Builder patches only when no semantic tool fits.",
tools: ["snapshot", "apply-patch"],
},
] satisfies readonly McpCapabilityArea[];
const getOptionalStringInput = (
input: unknown,
field: string,
toolName: string
) => {
if (isRecord(input) === false || field in input === false) {
return "";
}
const value = input[field];
if (typeof value !== "string") {
throw new Error(
`${toolName} input.${field} must be a string when provided. Received ${
Array.isArray(value) ? "array" : typeof value
}.`
);
}
return value;
};
const getRequiredStringInput = (
input: unknown,
field: string,
toolName: string
) => {
const value = getOptionalStringInput(input, field, toolName);
if (value === "") {
throw new Error(`${toolName} input.${field} is required.`);
}
return value;
};
const getBrief = (input: unknown, toolName: string) =>
getOptionalStringInput(input, "brief", toolName);
const getOptionalBooleanInput = (
input: unknown,
field: string,
toolName: string
) => {
if (isRecord(input) === false || field in input === false) {
return false;
}
const value = input[field];
if (typeof value !== "boolean") {
throw new Error(
`${toolName} input.${field} must be a boolean when provided. Received ${
Array.isArray(value) ? "array" : typeof value
}.`
);
}
return value;
};
const getMetaGuideInput = (input: unknown) => {
const taskScope =
getOptionalStringInput(input, "taskScope", "meta.guide") ||
"focused-page-change";
if (taskScopes.includes(taskScope as TaskScope) === false) {
throw new Error(
`meta.guide input.taskScope must be one of ${taskScopes.join(", ")}.`
);
}
const workflow =
getOptionalStringInput(input, "workflow", "meta.guide") || "general";
if (metaGuideWorkflows.includes(workflow as MetaGuideWorkflow) === false) {
throw new Error(
`meta.guide input.workflow must be one of ${metaGuideWorkflows.join(
", "
)}.`
);
}
return {
brief: getBrief(input, "meta.guide"),
taskScope: taskScope as TaskScope,
workflow: workflow as MetaGuideWorkflow,
authoredFragment: getOptionalBooleanInput(
input,
"authoredFragment",
"meta.guide"
),
reuseDesignSystem: getOptionalBooleanInput(
input,
"reuseDesignSystem",
"meta.guide"
),
};
};
const getToolNamesInput = (input: unknown) => {
if (isRecord(input) === false || "tools" in input === false) {
return [];
}
const value = input.tools;
if (Array.isArray(value) === false) {
throw new Error(
`meta.get-more-tools input.tools must be an array of strings when provided. Received ${typeof value}.`
);
}
return value.map((tool, index) => {
if (typeof tool !== "string" || tool === "") {
throw new Error(
`meta.get-more-tools input.tools[${index}] must be a non-empty string.`
);
}
return tool;
});
};
const getComponentInput = (input: unknown) =>
getRequiredStringInput(input, "component", "components.get");
const registryListSources = ["all", "component", "template"] as const;
type RegistryListSource = (typeof registryListSources)[number];
const getRegistryListInput = (
input: unknown,
toolName: "components.list" | "templates.list",
defaultSource: RegistryListSource
) => {
const source =
getOptionalStringInput(input, "source", toolName) || defaultSource;
if (registryListSources.includes(source as RegistryListSource) === false) {
throw new Error(
`${toolName} input.source must be one of all, component, template.`
);
}
const documentType =
getOptionalStringInput(input, "documentType", toolName) || "html";
if (
coveragePlanDocumentTypes.includes(
documentType as CoveragePlanDocumentType
) === false
) {
throw new Error(
`${toolName} input.documentType must be one of html, xml, text.`
);
}
const { limit, offset } = getOffsetPaginationInput({
input,
toolName,
defaultLimit: 50,
maxLimit: 100,
});
return {
source: source as RegistryListSource,
documentType: documentType as CoveragePlanDocumentType,
limit,
offset,
};
};
const getTemplateInput = (input: unknown) => {
const template = getOptionalStringInput(input, "template", "templates.get");
const component = getOptionalStringInput(input, "component", "templates.get");
const name = getOptionalStringInput(input, "name", "templates.get");
const value = template || component || name;
if (value === "") {
throw new Error(
"templates.get requires input.template, input.component, or input.name."
);
}
return value;
};
const getInsertFragmentInput = async (input: unknown) => {
if (isPlainRecord(input) === false) {
throw new Error(
'insert-fragment requires {"parentInstanceId":"...","fragment":"<section />"}.'
);
}
if ("parentId" in input && "parentInstanceId" in input === false) {
throw new Error(
"insert-fragment input.parentId is not supported. Use input.parentInstanceId instead."
);
}
if (typeof input.parentInstanceId !== "string") {
throw new Error("insert-fragment requires parentInstanceId.");
}
if ("source" in input) {
throw new Error(
"insert-fragment input.source is not supported. Put JSX in input.fragment instead."
);
}
if ("jsx" in input) {
throw new Error(
"insert-fragment input.jsx is not supported. Put JSX in input.fragment instead."
);
}
if (typeof input.fragment !== "string") {
throw new Error(
'insert-fragment requires fragment as a Webstudio JSX string, for example {"fragment":"<section />"}.'
);
}
const { fragment: fragmentSource, ...runtimeInput } =
insertFragmentMcpInput.parse(input);
return insertFragmentInput.parse({
...runtimeInput,
fragment: await parseWebstudioJsxFragment(fragmentSource),
});
};
const getInsertCollectionInput = async (input: unknown) => {
const { itemFragment, ...parsedInput } =
insertCollectionMcpInput.parse(input);
return {
...parsedInput,
itemFragment: await parseWebstudioJsxFragment(itemFragment),
};
};
const normalizeMcpOperationInput = async (name: string, input: unknown) => {
if (name === "insert-fragment") {
return await getInsertFragmentInput(input);
}
if (name === "insert-collection") {
return await getInsertCollectionInput(input);
}
if (
name === "update-styles" &&
isPlainRecord(input) &&
Array.isArray(input.updates)
) {
const updateIndex = input.updates.findIndex(
(update) => isPlainRecord(update) && "breakpointId" in update
);
if (updateIndex !== -1) {
throwBuilderValidationError(
`update-styles input.updates[${updateIndex}].breakpointId is not supported. Use input.updates[${updateIndex}].breakpoint instead.`,
[
{
code: "unrecognized_keys",
path: ["updates", String(updateIndex), "breakpointId"],
message: "breakpointId is not supported; use breakpoint instead",
constraint: "field:breakpoint",
},
]
);
}
}
return input;
};
/** @deprecated Guard only for the deprecated Webhook Form component. */
const assertNoDeprecatedWebhookFormInsertion = (
name: string,
input: unknown
) => {
if (isRecord(input) === false) {
return;
}
let instances: unknown;
if (name === "update-text-tree") {
instances = input.instances;
} else if (name === "insert-fragment" && isRecord(input.fragment)) {
instances = input.fragment.instances;
} else if (name === "insert-collection" && isRecord(input.itemFragment)) {
instances = input.itemFragment.instances;
} else if (name === "integrate-runtime-ui" && isRecord(input.structure)) {
const fragment =
input.structure.type === "fragment"
? input.structure.fragment
: input.structure.itemFragment;
if (isRecord(fragment)) {
instances = fragment.instances;
}
}
if (
(["insert-component", "wrap-instance", "convert-instance"].includes(name) &&
input.component === "WebhookForm") ||
(Array.isArray(instances) &&
instances.some(
(instance) => isRecord(instance) && instance.component === "WebhookForm"
))
) {
throw new Error(
'Webhook Form is deprecated and cannot be inserted through MCP. Use component "ResourceForm".'
);
}
if (
name === "apply-patch" &&
Array.isArray(input.transactions) &&
input.transactions.some(
(transaction) =>
isRecord(transaction) &&
hasDeprecatedWebhookFormInstancePatch(transaction.payload)
)
) {
throw new Error(
'Webhook Form is deprecated and cannot be created through MCP patches. Use component "ResourceForm".'
);
}
};
/** @deprecated Copy operations inspected only for saved Webhook Forms. */
const deprecatedWebhookFormCopyCommands = new Set([
"insert-mdx-text",
"duplicate-page",
"duplicate-page-template",
"duplicate-folder",
"copy-page",
"insert-page-transfer-item",
]);
/** @deprecated Detects only saved Webhook Form instances. */
const containsDeprecatedWebhookFormInstance = (value: unknown): boolean => {
if (value instanceof Map) {
return Array.from(value.values()).some(
containsDeprecatedWebhookFormInstance
);
}
if (Array.isArray(value)) {
return value.some(containsDeprecatedWebhookFormInstance);
}
if (isRecord(value)) {
return (
value.component === "WebhookForm" ||
Object.values(value).some(containsDeprecatedWebhookFormInstance)
);
}
return false;
};
/** @deprecated Detects only patches that create Webhook Form instances. */
const hasDeprecatedWebhookFormInstancePatch = (payload: unknown) =>
Array.isArray(payload) &&
payload.some(
(change) =>
isRecord(change) &&
change.namespace === "instances" &&
Array.isArray(change.patches) &&
change.patches.some(
(patch) =>
isRecord(patch) &&
patch.op !== "remove" &&
((Array.isArray(patch.path) &&
patch.path.at(-1) === "component" &&
patch.value === "WebhookForm") ||
containsDeprecatedWebhookFormInstance(patch.value))
)
);
/** @deprecated Copy guard only for saved Webhook Forms. */
const assertNoDeprecatedWebhookFormCopy = (
envelope: ProjectSessionEnvelope
) => {
if (envelope.transaction === undefined) {
throw new Error("MCP could not inspect the planned copy transaction.");
}
if (hasDeprecatedWebhookFormInstancePatch(envelope.transaction.payload)) {
throw new Error(
'Webhook Form is deprecated and cannot be copied through MCP. Use component "ResourceForm".'
);
}
};
const coveragePlanDetailValues = ["summary", "roots", "parts", "full"] as const;
type CoveragePlanDetail = (typeof coveragePlanDetailValues)[number];
const coveragePlanDocumentTypes = ["html", "xml", "text"] as const;
type CoveragePlanDocumentType = (typeof coveragePlanDocumentTypes)[number];
const getOptionalNumberInput = (
input: unknown,
field: string,
toolName: string
) => {
if (isRecord(input) === false || field in input === false) {
return undefined;
}
const value = input[field];
if (typeof value !== "number" || Number.isFinite(value) === false) {
throw new Error(
`${toolName} input.${field} must be a finite number when provided. Received ${
Array.isArray(value) ? "array" : typeof value
}.`
);
}
return value;
};
const getOffsetPaginationInput = ({
input,
toolName,
defaultLimit,
maxLimit,
}: {
input: unknown;
toolName: string;
defaultLimit: number;
maxLimit: number;
}) => ({
offset: Math.max(
0,
Math.floor(getOptionalNumberInput(input, "offset", toolName) ?? 0)
),
limit: Math.min(
maxLimit,
Math.max(
1,
Math.floor(
getOptionalNumberInput(input, "limit", toolName) ?? defaultLimit
)
)
),
});
const getCoveragePlanInput = (input: unknown) => {
const detail =
getOptionalStringInput(input, "detail", "components.coverage-plan") ||
"summary";
if (
coveragePlanDetailValues.includes(detail as CoveragePlanDetail) === false
) {
throw new Error(
`components.coverage-plan input.detail must be one of ${coveragePlanDetailValues.join(
", "
)}.`
);
}
const documentType =
getOptionalStringInput(input, "documentType", "components.coverage-plan") ||
"html";
if (
coveragePlanDocumentTypes.includes(
documentType as CoveragePlanDocumentType
) === false
) {
throw new Error(
`components.coverage-plan input.documentType must be one of ${coveragePlanDocumentTypes.join(
", "
)}.`
);
}
const { offset, limit } = getOffsetPaginationInput({
input,
toolName: "components.coverage-plan",
defaultLimit: 20,
maxLimit: 100,
});
return {
detail: detail as CoveragePlanDetail,
namespace: getOptionalStringInput(
input,
"namespace",
"components.coverage-plan"
),
documentType: documentType as CoveragePlanDocumentType,
offset,
limit,
};
};
const getCoverageStatusInput = (input: unknown) => {
const documentType =
getOptionalStringInput(
input,
"documentType",
"components.coverage-status"
) || "html";
if (
coveragePlanDocumentTypes.includes(
documentType as CoveragePlanDocumentType
) === false
) {
throw new Error(
`components.coverage-status input.documentType must be one of ${coveragePlanDocumentTypes.join(
", "
)}.`
);
}
const pageId = getOptionalStringInput(
input,
"pageId",
"components.coverage-status"
);
const pagePath = getOptionalStringInput(
input,
"pagePath",
"components.coverage-status"
);
return {
pageId: pageId === "" ? undefined : pageId,
pagePath: pagePath === "" ? undefined : pagePath,
documentType: documentType as CoveragePlanDocumentType,
};
};
const getCoverageInsertNextInput = (input: unknown) => {
const statusInput = getCoverageStatusInput(input);
const component = getOptionalStringInput(
input,
"component",
"components.coverage-insert-next"
);
return {
...statusInput,
parentInstanceId: getRequiredStringInput(
input,
"parentInstanceId",
"components.coverage-insert-next"
),
component: component === "" ? undefined : component,
};
};
const normalize = (value: string) =>
value.toLowerCase().replace(/[^a-z0-9]+/g, " ");
const discoveryStopWords = new Set([
"and",
"clear",
"delete",
"detach",
"for",
"add",
"remove",
"replace",
"using",
"build",
"change",
"create",
"edit",
"make",
"new",
"the",
"set",
"update",
"use",
"verify",
"via",
"with",
"without",
]);
const hasAnyToken = (tokens: ReadonlySet<string>, values: readonly string[]) =>
values.some((value) => tokens.has(value));
const destructiveDiscoveryTokens = [
"clear",
"delete",
"detach",
"remove",
] as const;
const createDiscoveryTokens = ["add", "create", "set"] as const;
const cloneDiscoveryTokens = ["clone", "copy", "duplicate"] as const;
const findDiscoveryTokens = ["find", "search"] as const;
const getDiscoveryTokens = ["detail", "details", "get", "inspect"] as const;
const moveDiscoveryTokens = ["move", "reorder"] as const;
const replaceDiscoveryTokens = ["replace", "swap"] as const;
const statusDiscoveryTokens = ["check", "status", "verify"] as const;
const updateDiscoveryTokens = ["change", "edit", "update"] as const;
const isDestructiveDiscoveryTool = (toolName: string) =>
toolName.startsWith("delete-") || toolName.startsWith("detach-");
const mutationToolSearchRules = [
{ tokens: updateDiscoveryTokens, toolNamePrefixes: ["update-"] },
{ tokens: replaceDiscoveryTokens, toolNamePrefixes: ["replace-"] },
{ tokens: moveDiscoveryTokens, toolNamePrefixes: ["move-"] },
{
tokens: cloneDiscoveryTokens,
toolNamePrefixes: ["clone-", "duplicate-"],
},
] as const;
const hasToolNamePrefix = (toolName: string, prefixes: readonly string[]) =>
prefixes.some((prefix) => toolName.startsWith(prefix));
const getDiscoveryTokenVariants = (token: string) => {
const variants = new Set([token, getSingularDiscoveryToken(token)]);
if (token === "image" || token === "images") {
variants.add("asset");
}
if (
token === "component" ||
token === "components" ||
token === "element" ||
token === "elements" ||
token === "section" ||
token === "sections"
) {
variants.add("instance");
}
if (token === "compare" || token === "comparison") {
variants.add("diff");
}
return variants;
};
const getSingularDiscoveryToken = (token: string) => {
if (token.endsWith("ies") && token.length > 4) {
return `${token.slice(0, -3)}y`;
}
if (token.endsWith("s") && token.length > 3) {
return token.slice(0, -1);
}
return token;
};
const destructiveContextTokens = [
"asset",
"css",
"design",
"folder",
"page",
"prop",
"style",
] as const;
const hasDiscoveryTokenVariant = (value: string, token: string) =>
[...getDiscoveryTokenVariants(token)].some((variant) =>
value.includes(variant)
);
const hasDiscoverySubject = (
tokens: ReadonlySet<string>,
subjects: readonly string[]
) =>
subjects.some((subject) =>
[...tokens].some((token) =>
[...getDiscoveryTokenVariants(token)].some(
(variant) =>
variant === subject || getDiscoveryTokenVariants(subject).has(variant)
)
)
);
const scoreTool = (tool: ProjectSessionMcpTool, brief: string) => {
// Free text is used only to rank discovery results. It must never determine
// task scope, workflow, permissions, safety, execution, or verification.
const normalizedBrief = normalize(brief);
if (normalizedBrief.trim().length === 0) {
return 0;
}
const tokens = new Set(
normalizedBrief.split(/\s+/).filter((token) => token.length > 0)
);
const hasDestructiveSearchTerm = hasAnyToken(
tokens,
destructiveDiscoveryTokens
);
const hasCreateSearchTerm = hasAnyToken(tokens, createDiscoveryTokens);
const hasFindSearchTerm = hasAnyToken(tokens, findDiscoveryTokens);
const hasGetSearchTerm = hasAnyToken(tokens, getDiscoveryTokens);
const hasStatusSearchTerm = hasAnyToken(tokens, statusDiscoveryTokens);
const matchingMutationSearchRules = mutationToolSearchRules.filter((rule) =>
hasAnyToken(tokens, rule.tokens)
);
const hasComponentSubject = hasDiscoverySubject(tokens, ["component"]);
const hasCoverageSubject = hasDiscoverySubject(tokens, ["coverage"]);
const hasDesignTokenSubject =
tokens.has("design") && hasDiscoverySubject(tokens, ["token"]);
const hasStyleSubject = hasDiscoverySubject(tokens, ["style"]);
const hasInstanceSubject = hasDiscoverySubject(tokens, [
"component",
"element",
"instance",
"section",
]);
if (
isDestructiveDiscoveryTool(tool.name) &&
hasDestructiveSearchTerm === false
) {
return 0;
}
if (
hasDestructiveSearchTerm &&
tool.annotations.method === "mutation" &&
isDestructiveDiscoveryTool(tool.name) === false
) {
return 0;
}
if (
tool.annotations.method === "mutation" &&
matchingMutationSearchRules.some(
(rule) => hasToolNamePrefix(tool.name, rule.toolNamePrefixes) === false
)
) {
return 0;
}
if (
hasComponentSubject &&
(hasFindSearchTerm || hasGetSearchTerm || hasCoverageSubject) &&
tool.annotations.method === "mutation"
) {
return 0;
}
const toolName = normalize(tool.name);
if (
hasDestructiveSearchTerm &&
hasDesignTokenSubject &&
hasStyleSubject === false &&
hasInstanceSubject === false &&
tokens.has("detach") === false &&
(tool.name === "delete-design-token-styles" ||
tool.name === "detach-design-token")
) {
return 0;
}
if (hasDestructiveSearchTerm && isDestructiveDiscoveryTool(tool.name)) {
for (const contextToken of destructiveContextTokens) {
if (
hasDiscoveryTokenVariant(normalizedBrief, contextToken) &&
hasDiscoveryTokenVariant(toolName, contextToken) === false
) {
return 0;
}
}
}
const haystack = normalize(
[tool.name, tool.description, tool.annotations.operationId].join(" ")
);
let score = 0;
if (toolName.includes(normalizedBrief.trim())) {
score += 50;
}
const singularBrief = normalizedBrief
.trim()
.split(/\s+/)
.map(getSingularDiscoveryToken)
.join(" ");
if (
singularBrief !== normalizedBrief.trim() &&
toolName.includes(singularBrief)
) {
score += 50;
}
if (
tool.name === "insert-fragment" &&
hasFindSearchTerm === false &&
hasGetSearchTerm === false &&
hasCoverageSubject === false &&
hasAnyToken(tokens, [
"insert",
"component",
"hero",
"layout",
"section",
"tree",
])
) {
score += 80;
}
if (hasFindSearchTerm && tool.name === "components.search") {
score += 120;
}
if (hasFindSearchTerm && tool.name === "components.find") {
score += 100;
}
if (hasGetSearchTerm && tool.name === "components.get") {
score += 100;
}
if (
hasCoverageSubject &&
hasStatusSearchTerm &&
tool.name === "components.coverage-status"
) {
score += 150;
} else if (
hasCoverageSubject &&
hasStatusSearchTerm === false &&
tool.name === "components.coverage-plan"
) {
score += 150;
} else if (
hasCoverageSubject &&
tool.name.startsWith("components.coverage-")
) {
score += 100;
}
if (
hasCreateSearchTerm &&
tool.name.startsWith("define-") &&
(tool.name.startsWith("define-css-") === false || tokens.has("css"))
) {
score += 50;
}
let matchedToolNameToken = false;
for (const token of normalizedBrief.split(/\s+/)) {
if (token.length < 3) {
continue;
}
if (discoveryStopWords.has(token)) {
continue;
}
if (hasDiscoveryTokenVariant(toolName, token)) {
matchedToolNameToken = true;
score += token.length * 3;
continue;
}
if (hasDiscoveryTokenVariant(haystack, token)) {
score += token.length;
}
}
if (
hasDestructiveSearchTerm &&
isDestructiveDiscoveryTool(tool.name) &&
matchedToolNameToken === false
) {
return 0;
}
if (
score > 0 &&
hasDestructiveSearchTerm &&
isDestructiveDiscoveryTool(tool.name)
) {
score += 50;
}
for (const rule of matchingMutationSearchRules) {
if (score > 0 && hasToolNamePrefix(tool.name, rule.toolNamePrefixes)) {
score += 50;
}
}
return score;
};
const getMatchingTools = (
brief: string,
tools: readonly ProjectSessionMcpTool[]
) => {
const normalizedBrief = normalize(brief);
if (normalizedBrief.trim().length === 0) {
const names = new Set<string>(
capabilityAreas.find((area) => area.area === "discover")?.tools ?? []
);
return tools.filter((tool) => names.has(tool.name));
}
const area = capabilityAreas.find((area) =>
[area.area, area.goal]
.map(normalize)
.some((value) => value.includes(normalizedBrief))
);
if (area !== undefined) {
const names = new Set<string>(area.tools);
const toolIndexes = new Map(tools.map((tool, index) => [tool.name, index]));
return tools
.filter((tool) => names.has(tool.name))
.map((tool) => ({ tool, score: scoreTool(tool, brief) }))
.sort(
(left, right) =>
right.score - left.score ||
(toolIndexes.get(left.tool.name) ?? 0) -
(toolIndexes.get(right.tool.name) ?? 0)
)
.map(({ tool }) => tool);
}
return tools
.map((tool) => ({ tool, score: scoreTool(tool, brief) }))
.filter(({ score }) => score > 0)
.sort((left, right) => right.score - left.score)
.map(({ tool }) => tool);
};
const filterCapabilities = (tools: readonly ProjectSessionMcpTool[]) => {
const names = new Set(tools.map((tool) => tool.name));
const categorizedNames = new Set<string>(
capabilityAreas.flatMap((capability) => capability.tools)
);
const uncategorizedTools = [...names]
.filter((name) => categorizedNames.has(name) === false)
.sort((left, right) => left.localeCompare(right));
const capabilities: McpCapabilityArea[] = capabilityAreas
.map((capability) => ({
...capability,
tools: capability.tools.filter((tool) => names.has(tool)),
}))
.filter((capability) => capability.tools.length > 0);
if (uncategorizedTools.length > 0) {
capabilities.push({
area: "operations",
goal: "Use additional catalog-derived MCP operation tools.",
tools: uncategorizedTools,
});
}
return capabilities;
};
const startupGuidance = [
"For any multi-step authoring task, first call meta.guide with the user's objective and follow its proportional workflow. Small corrections stop after focused assertions. Never start preview, screenshots, diffs, OCR, or rendered audits automatically: ask whether the user wants visual verification unless they explicitly requested it.",
"Mutation responses can include meta.next. Follow non-visual steps before reporting completion. A visual-consent step pauses the visual workflow until the user opts in; if they decline, stop after the listed focused or static checks.",
"Every local-capable mutation exposes dryRun. Destructive delete, replace, and replace-all calls plan first; review the transaction, ask the user to confirm, then retry the unchanged call with confirmDestructive: true and meta.confirmation.token. Never retry blindly because changed input, version, or plan invalidates the short-lived token.",
readProjectBuildDoc("mcp-startup-guidance").trim(),
].join("\n\n");
const formatExpressionMethods = (methods: ReadonlySet<string>) =>
[...methods]
.sort((left, right) => left.localeCompare(right))
.map((method) => `- \`${method}\``)
.join("\n");
const expressionsGuide = readProjectBuildDoc("expressions")
.replace(
"{{allowedStringMethods}}",
formatExpressionMethods(allowedStringMethods)
)
.replace(
"{{allowedArrayMethods}}",
formatExpressionMethods(allowedArrayMethods)
);
const valuesVsBindingsRule =
"Use direct value tools for fixed text/props. Use bindings only for dynamic expressions, resources, actions, or existing scoped runtime context such as system. Parameters are internal scoped runtime values, not a public create/update/delete surface. Page metadata and fixed resource URLs accept plain strings; use JavaScript expression code only when values are computed. Page and resource updates put changed fields under values.";
const bindingVerificationWriteNamespaces = new Set([
"props",
"dataSources",
"resources",
]);
const visualVerificationWriteNamespaces = new Set([
"pages",
"instances",
"props",
"styles",
"styleSources",
"styleSourceSelections",
]);
const getComponentStateUsage = (
states:
| readonly {
label: string;
selector: string;
}[]
| undefined
) => {
if (states === undefined || states.length === 0) {
return undefined;
}
return `Stateful component: style every exposed state selector when creating polished examples. Exposed states: ${states
.map((state) => `${state.label} (${state.selector})`)
.join(", ")}.`;
};
const animationComponentGuidanceByComponent = new Map<string, string>([
[
"@webstudio-is/sdk-components-animation:AnimateChildren",
[
"Animation Group is the root animation controller. Put the instances to animate directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it.",
'Set the action prop to an animationAction. Use type:"view" for visibility-driven entry/exit animations and type:"scroll" for scroll-progress animations.',
"For view actions, common settings are axis, subject, insetStart, insetEnd, isPinned, debug, and animations. Use subject only when another element should drive progress.",
"For scroll actions, common settings are axis, source (nearest, root, or closest), isPinned, debug, and animations.",
'Each animation needs keyframes; timing is optional and defaults to {}. In keyframes[].styles, use CSS property names with raw CSS strings such as transform:"translateX(-75%)"; update-props parses them into Webstudio style data. Timing can use rangeStart/rangeEnd, fill, easing, duration, delay, and iterations. Duration makes Range End unnecessary because duration defines when the animation ends.',
'Use fill:"backwards" for in animations from animation styles to canvas styles, and fill:"forwards" for out animations from canvas styles to animation styles.',
"Direct child animations expose --index and --total to support staggered formulas such as calc(var(--index) * 20%).",
"For polished pages, design the element's normal canvas styles as the final state, then set the Animation Group keyframes to the starting or ending animated state.",
].join(" "),
],
[
"@webstudio-is/sdk-components-animation:AnimateText",
[
"Text Animation must be a direct child of Animation Group. Do not use it as a standalone section root.",
"Put Heading, Paragraph, Text, or other text-containing instances inside Text Animation. It wraps non-empty descendant text nodes in inline spans and applies the parent Animation Group progress to each split part.",
'Settings: slidingWindow number, default 5; easing, default linear; splitBy, default char. splitBy options are char, space, symbol "#", and symbol "~".',
'Use splitBy:"char" for letter-by-letter effects and splitBy:"space" for word-by-word effects. Use larger slidingWindow values for overlapping waves and 0 for instant typewriter-like stepping.',
"The actual movement, opacity, scale, or other CSS changes belong on the parent Animation Group action keyframes.",
].join(" "),
],
[
"@webstudio-is/sdk-components-animation:StaggerAnimation",
[
"Stagger Animation must be a direct child of Animation Group. Do not use it as a standalone section root.",
"Put the repeated cards, list items, text rows, images, or other instances as direct children of Stagger Animation. It applies the parent Animation Group progress across those direct children.",
"Settings: slidingWindow number, default 1; easing, default linear.",
"slidingWindow 0 makes each child switch instantly in sequence, 1 animates one child at a time, and values above 1 overlap multiple children for a wave.",
"The actual fade, translate, scale, or other CSS changes belong on the parent Animation Group action keyframes.",
].join(" "),
],
[
"@webstudio-is/sdk-components-animation:VideoAnimation",
[
"Video Animation must be a direct child of Animation Group. Prefer insert-component for Video Animation so Webstudio inserts the required Video child template.",
"Put a Video component inside Video Animation and configure its video asset/source on that child.",
"Settings: timeline boolean. When enabled, the child Video receives timeline/progress data from the Animation Group; when disabled, visibility/progress still comes from the group.",
"Use an Animation Group view action such as rangeStart cover 0% and rangeEnd cover 100% for scroll-linked video progress examples.",
"Use short, seek-friendly videos for smooth scroll-linked playback.",
].join(" "),
],
]);
const getAnimationComponentGuidance = (component: string) =>
animationComponentGuidanceByComponent.get(component);
const collectionComponentUsage =
"Use Collection whenever an array or object from a resource or data variable should render a repeated list, grid, set of cards, table rows, options, tabs, or similar UI. Prefer insert-collection: pass the complete array/object plus one repeated-item JSX root, and it creates the Collection, private item/itemKey parameters, iterable binding, and item bindings atomically. External resource arrays are often nested below the scoped result's data field. Array iteration exposes `collectionItem`; object iteration also exposes `collectionItemKey`. Use expressions such as expression`collectionItem.name` in item JSX. Wrap multiple repeated siblings in one Element. For repeated Radix items, bind a stable unique id or slug to required value props. Do not create, replace, or delete internal Collection parameter records directly.";
const isComponentAvailableInMcpCatalog = (
component: string,
meta: WsComponentMeta
) =>
// The explicit check hides the deprecated Webhook Form even with older metadata.
component !== "WebhookForm" &&
isComponentMetaUnavailableInCatalog(meta) === false;
const getComponentCatalog = () => ({
source: "@webstudio-is/sdk-components-registry/metas",
usage:
'Full component catalog. Prefer components.list({"source":"all"}), templates.list({}), components.search({"brief":"radix select"}), components.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}), and templates.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) for normal component discovery. Prefer insert-fragment for authored/styled sections. Use insert-component only when you want exactly one component template inserted automatically. Known components with contentModel.category "none" are not standalone-insertable; insert their root component template instead so required providers/parents are included.',
components: [...componentMetas.entries()]
.filter(([component, meta]) =>
isComponentAvailableInMcpCatalog(component, meta)
)
.map(([component, meta]) => {
const [namespace, exportName] = parseComponentName(component);
return {
component,
exportName,
namespace,
label: meta.label,
description: meta.description,
category: meta.category,
contentModel: meta.contentModel,
initialProps: meta.initialProps ?? [],
props: meta.props ?? {},
states: meta.states ?? [],
stateUsage: getComponentStateUsage(meta.states),
indexWithinAncestor: meta.indexWithinAncestor,
};
})
.sort((left, right) => left.component.localeCompare(right.component)),
});
const getCompactComponentCatalogEntries = () =>
[...componentMetas.entries()]
.filter(([component, meta]) =>
isComponentAvailableInMcpCatalog(component, meta)
)
.map(([component, meta]) => {
const [parsedNamespace, exportName] = parseComponentName(component);
const namespace = parsedNamespace ?? "global";
const category = meta.category ?? "uncategorized";
return {
component,
exportName,
namespace,
label: meta.label,
category,
};
})
.sort((left, right) => left.component.localeCompare(right.component));
const getComponentCatalogOverview = () => {
const categories = new Map<string, number>();
const namespaces = new Map<string, number>();
const components = getCompactComponentCatalogEntries();
for (const { category, namespace } of components) {
namespaces.set(namespace, (namespaces.get(namespace) ?? 0) + 1);
categories.set(category, (categories.get(category) ?? 0) + 1);
}
return {
source: "@webstudio-is/sdk-components-registry/metas",
usage:
'Short component overview. Prefer MCP tools components.list({"source":"all"}), templates.list({}), components.search({"brief":"radix select"}), and components.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) for structured discovery. Read the bounded webstudio://project/components catalog only when needed.',
count: components.length,
namespaces: Object.fromEntries([...namespaces.entries()].sort()),
categories: Object.fromEntries([...categories.entries()].sort()),
};
};
const getComponentSummaryEntry = ({
component,
templates,
includeHiddenRequiredPart = false,
}: {
component: string;
templates: ComponentTemplateRegistry;
includeHiddenRequiredPart?: boolean;
}) => {
const meta = componentMetas.get(component);
if (meta === undefined) {
return;
}
const templateMeta = templates.get(component);
const visibleCategory = templateMeta?.category ?? meta.category;
const hiddenRequiredPart =
includeHiddenRequiredPart &&
meta.deprecated !== true &&
meta.category === "hidden" &&
meta.contentModel?.category === "none" &&
Array.from(templates.values()).some((entry) =>
entry.template.instances.some(
(instance) => instance.component === component
)
);
if (
// Keep the deprecated Webhook Form out of component search and templates.
component === "WebhookForm" ||
(hiddenRequiredPart === false &&
(isComponentMetaUnavailableInCatalog(meta) ||
isComponentHiddenFromCatalog(meta, visibleCategory)))
) {
return;
}
const [parsedNamespace, exportName] = parseComponentName(component);
const namespace = parsedNamespace ?? "global";
const candidateJsxName = getComponentJsxName({
component,
components: componentMetas.keys(),
});
const jsxName = isMdxTemplateComponentName(candidateJsxName)
? candidateJsxName
: undefined;
const template = templateMeta?.template;
const hasTemplate = template !== undefined;
const instancesById = new Map(
template?.instances.map((instance) => [instance.id, instance]) ?? []
);
const templateRootComponents =
template?.children.flatMap((child) => {
if (child.type !== "id") {
return [];
}
const rootInstance = instancesById.get(child.value);
return rootInstance === undefined ? [] : [rootInstance.component];
}) ?? [];
const templateTextContent =
template === undefined
? []
: template.instances.flatMap((instance) =>
instance.children.flatMap((child, childIndex) => {
if (child.type !== "text") {
return [];
}
return [
{
instanceComponent: instance.component,
instanceLabel: instance.label,
childIndex,
value: child.value,
placeholder: child.placeholder === true ? true : undefined,
},
];
})
);
const templateRequiredStructure = getTemplateRequiredStructure(
component,
templates
);
const templateRequiredEdges =
templateRequiredStructure.edges.map(parseComponentEdge);
const nonStandalone = meta.contentModel?.category === "none";
return {
component,
exportName,
namespace,
...(jsxName === undefined ? {} : { jsxName, jsxElement: `<${jsxName} />` }),
label: meta.label,
category: visibleCategory,
contentCategory: meta.contentModel?.category,
hasTemplate,
templateRootComponents,
templateRequiredParts:
templateRequiredStructure.parts.length > 0
? templateRequiredStructure.parts
: undefined,
templateRequiredEdges:
templateRequiredEdges.length > 0 ? templateRequiredEdges : undefined,
templateTextContent:
templateTextContent.length > 0 ? templateTextContent : undefined,
standaloneInsertable: hasTemplate || nonStandalone === false,
insertWith: hasTemplate || nonStandalone === false ? component : undefined,
note: nonStandalone
? "Not standalone-insertable. Insert a root/template component that contains it."
: undefined,
};
};
type ComponentSummaryEntry = NonNullable<
ReturnType<typeof getComponentSummaryEntry>
>;
const getComponentCatalogSummary = () => {
const templates = getComponentTemplates();
const entries = [...componentMetas.keys()]
.flatMap((component) => {
const entry = getComponentSummaryEntry({ component, templates });
return entry === undefined ? [] : [entry];
})
.sort((left, right) => left.component.localeCompare(right.component));
const namespaces = new Map<string, number>();
for (const entry of entries) {
namespaces.set(entry.namespace, (namespaces.get(entry.namespace) ?? 0) + 1);
}
return {
usage:
"Use this structured summary before paging through component resources. Do not dump/parse the whole component catalog. Prefer components.list for shadcn-compatible registry items, components.search for search, templates.list for templates, and components.get/templates.get for one item.",
total: entries.length,
namespaceCounts: Object.fromEntries([...namespaces.entries()].sort()),
templateComponents: entries
.filter((entry) => entry.hasTemplate)
.map((entry) => entry.component),
standaloneInsertable: entries
.filter((entry) => entry.standaloneInsertable)
.map((entry) => entry.component),
nonStandaloneComponents: entries
.filter((entry) => entry.standaloneInsertable === false)
.map((entry) => entry.component),
components: entries,
};
};
const getComponentSummary = (input: unknown) => {
const detail =
getOptionalStringInput(input, "detail", "components.summary") || "summary";
if (detail !== "summary" && detail !== "components") {
throw new Error(
"components.summary input.detail must be summary or components."
);
}
const summary = getComponentCatalogSummary();
const base = {
usage:
'Default summary is compact. Use detail:"components" with offset and limit for component entries, or components.search/components.get for focused discovery.',
total: summary.total,
namespaceCounts: summary.namespaceCounts,
templateCount: summary.templateComponents.length,
standaloneInsertableCount: summary.standaloneInsertable.length,
nonStandaloneCount: summary.nonStandaloneComponents.length,
};
if (detail === "summary") {
return base;
}
const { offset, limit } = getOffsetPaginationInput({
input,
toolName: "components.summary",
defaultLimit: 20,
maxLimit: 100,
});
const components = summary.components.slice(offset, offset + limit);
return {
...base,
detail,
count: components.length,
omittedCount: Math.max(0, summary.total - offset - components.length),
pagination: {
offset,
limit,
nextOffset:
offset + components.length < summary.total
? offset + components.length
: undefined,
},
components,
};
};
// The final filter hides the deprecated Webhook Form from registry discovery.
const getComponentRegistryItems = () =>
listComponentRegistryItems({
metas: componentMetas,
templates: getComponentTemplates(),
sources: getComponentCatalogSources(),
}).filter((item) => item.meta.component !== "WebhookForm");
const filterRegistryItemsBySource = (
items: readonly ComponentRegistryItem[],
source: RegistryListSource
) => {
if (source === "all") {
return items;
}
return items.filter((item) =>
source === "template"
? item.meta.source === "template"
: item.meta.source === "meta"
);
};
const toRegistryItemSummary = (item: ComponentRegistryItem) => ({
name: item.name,
title: item.title,
description: item.description,
type: item.type,
meta: {
catalogId: item.meta.catalogId,
source: item.meta.source,
component: item.meta.component,
category: item.meta.category,
label: item.meta.label,
insert: item.meta.insert,
},
});
const listRegistryItems = ({
input,
toolName,
defaultSource,
}: {
input: unknown;
toolName: "components.list" | "templates.list";
defaultSource: RegistryListSource;
}) => {
const { source, documentType, limit, offset } = getRegistryListInput(
input,
toolName,
defaultSource
);
const allItems = filterRegistryItemsBySource(
getComponentRegistryItems().filter((item) =>
isComponentAvailableForDocumentType({
component: item.meta.component,
category: item.meta.category,
documentType,
})
),
source
);
const items = allItems.slice(offset, offset + limit);
return {
usage:
"Registry lists return compact metadata. Use components.get or templates.get for one complete item before insertion.",
source,
documentType,
count: items.length,
totalCount: allItems.length,
omittedCount: Math.max(0, allItems.length - offset - items.length),
pagination: {
offset,
limit,
nextOffset: offset + limit < allItems.length ? offset + limit : undefined,
},
items: items.map(toRegistryItemSummary),
};
};
const getTemplateRootComponent = (
templates: ComponentTemplateRegistry,
name: string
) => {
const template = templates.get(name)?.template;
const child =
template?.children.length === 1 ? template.children[0] : undefined;
return child?.type === "id"
? template?.instances.find((instance) => instance.id === child.value)
?.component
: undefined;
};
const getTemplateDetails = (input: unknown) => {
const requested = getTemplateInput(input);
const templateName = requested.startsWith("template:")
? requested
: `template:${requested}`;
const templates = getComponentTemplates();
const items = getComponentRegistryItems();
const item =
items.find(
(candidate) =>
candidate.meta.source === "template" &&
(candidate.name === requested ||
candidate.name === templateName ||
candidate.meta.component === requested)
) ??
items.find(
(candidate) =>
candidate.meta.source === "template" &&
getTemplateRootComponent(templates, candidate.meta.component) ===
requested
);
if (item === undefined) {
return {
found: false,
requested,
usage:
'Template was not found in the shared registry. Use templates.list or components.list with source:"template" to discover exact template ids.',
};
}
const template = templates.get(item.meta.component);
const formUsage =
item.meta.component === "form"
? " The Form template adds formProgress: status is idle or pending, loaded and total start at 0 and measure bytes for the whole request; total 0 means unknown. Files contain id, fieldName, name, size, and type without per-file transfer counts. Find its ID with list-variables and read webstudio://project/expressions before binding the editable Progress container or its children with bind-props; style them with update-styles. Browser submission supplies live progress; forms.simulate-submission and preview.submit-form report only final outcomes."
: "";
return {
found: true,
...item,
template: template?.template,
usage: `Use insert-component with component "${item.meta.insert.component}" when you want Webstudio to insert this registered template automatically. The files entry is the shadcn-compatible registry:file representation of the same template payload.${formUsage}`,
};
};
const getComponentCoveragePlan = async (input: unknown) => {
const { detail, namespace, documentType, offset, limit } =
getCoveragePlanInput(input);
const summary = getComponentCatalogSummary();
const documentEntries = summary.components.filter((entry) =>
isComponentAvailableForDocumentType({
component: entry.component,
category: entry.category,
documentType,
})
);
const namespaceCounts = new Map<string, number>();
for (const entry of documentEntries) {
namespaceCounts.set(
entry.namespace,
(namespaceCounts.get(entry.namespace) ?? 0) + 1
);
}
const coveredComponentsByRoot = new Map<string, string[]>();
for (const entry of documentEntries) {
const meta = componentMetas.get(entry.component);
const contentModel = meta?.contentModel;
const directOrNestedComponents = [
...(contentModel?.children ?? []),
...(contentModel?.descendants ?? []),
];
coveredComponentsByRoot.set(
entry.component,
directOrNestedComponents.filter(
(component): component is string =>
typeof component === "string" && componentMetas.has(component)
)
);
}
const getCoveredComponents = (component: string) => {
const visited = new Set<string>();
const queue = [...(coveredComponentsByRoot.get(component) ?? [])];
while (queue.length > 0) {
const coveredComponent = queue.shift();
if (coveredComponent === undefined || visited.has(coveredComponent)) {
continue;
}
visited.add(coveredComponent);
queue.push(...(coveredComponentsByRoot.get(coveredComponent) ?? []));
}
return [...visited];
};
const rootEntries = documentEntries.filter(
(entry) => entry.standaloneInsertable
);
const partEntries = documentEntries.filter(
(entry) => entry.standaloneInsertable === false
);
const allRoots = rootEntries.map((entry) => {
const covers = getCoveredComponents(entry.component);
return {
component: entry.component,
namespace: entry.namespace,
jsxElement: entry.jsxElement,
label: entry.label,
hasTemplate: entry.hasTemplate,
templateRootComponents: entry.templateRootComponents,
templateRequiredParts: entry.templateRequiredParts,
insertWith: entry.insertWith,
covers,
coveredCount: covers.length,
};
});
const allPartComponents = partEntries.map((entry) => {
const coveredBy = allRoots
.filter((root) => root.covers.includes(entry.component))
.map((root) => root.component);
return {
component: entry.component,
namespace: entry.namespace,
jsxElement: entry.jsxElement,
label: entry.label,
coveredBy,
note:
coveredBy.length === 0
? "No covering root was found from contentModel children or descendants; inspect with components.get before using."
: "Covered by inserting one of the listed root/template components.",
};
});
const namespaceMatches = <Entry extends { namespace: string }>(
entry: Entry
) => namespace === "" || entry.namespace === namespace;
const roots = allRoots.filter(namespaceMatches);
const partComponents = allPartComponents.filter(namespaceMatches);
const pagedRoots = roots.slice(offset, offset + limit);
const pagedPartComponents = partComponents.slice(offset, offset + limit);
const uncoveredPartComponents = partComponents.filter(
(part) => part.coveredBy.length === 0
);
const base = {
usage:
'Use this for design-system coverage tasks. Default output is intentionally compact for LLMs. Default documentType is "html", so XML-only components are excluded unless documentType:"xml" is passed. Prefer insert-fragment for authored/styled real-world examples. Use insert-component only when you want exactly one component template inserted automatically. For details call components.coverage-plan with {"detail":"roots","offset":20}, {"detail":"parts"}, or {"detail":"full"}. Child/part components should be covered by their root templates instead of inserted standalone.',
checkpoint: {
required: true,
reason:
"Design-system/all-component work is long-running and must be split into visible checkpoints.",
instruction:
"Stop after this coverage-plan response and report these counts plus the next planned action to the parent before calling more discovery or mutation tools.",
nextCommand:
detail === "summary"
? 'node packages/cli/local.js workflow.next \'{"goal":"design-system-page","phase":"page-creation"}\''
: undefined,
nextAllowedAfterReport:
detail === "summary"
? "After reporting, create the page, then call components.coverage-insert-next once per coverage checkpoint."
: "After reporting, continue with the requested page of coverage details or one bounded insertion phase.",
},
total: documentEntries.length,
rootCount: roots.length,
partCount: partComponents.length,
namespaceCounts: Object.fromEntries([...namespaceCounts.entries()].sort()),
namespace: namespace || undefined,
documentType,
pagination: {
offset,
limit,
nextRootOffset:
offset + limit < roots.length &&
(detail === "summary" || detail === "roots")
? offset + limit
: undefined,
nextPartOffset:
offset + limit < partComponents.length && detail === "parts"
? offset + limit
: undefined,
},
uncoveredPartCount: uncoveredPartComponents.length,
};
if (detail === "full") {
return {
...base,
pagination: undefined,
roots,
partComponents,
uncoveredPartComponents,
};
}
if (detail === "parts") {
return {
...base,
partComponents: pagedPartComponents,
next:
offset + limit < partComponents.length
? {
detail: "parts",
namespace: namespace || undefined,
offset: offset + limit,
limit,
}
: undefined,
};
}
if (detail === "summary") {
const summaryRoots = roots.slice(offset, offset + Math.min(limit, 12));
return {
...base,
pagination: {
...base.pagination,
limit: Math.min(limit, 12),
nextRootOffset:
offset + Math.min(limit, 12) < roots.length
? offset + Math.min(limit, 12)
: undefined,
},
roots: summaryRoots.map(({ covers: _covers, ...root }) => root),
next:
offset + Math.min(limit, 12) < roots.length
? {
detail: "roots",
namespace: namespace || undefined,
offset: offset + Math.min(limit, 12),
limit,
}
: undefined,
};
}
return {
...base,
roots: pagedRoots.map(({ covers, ...root }) => ({
...root,
sampleCovers: covers.slice(0, 8),
moreCovers: Math.max(0, covers.length - 8),
})),
next:
offset + limit < roots.length
? {
detail: "roots",
namespace: namespace || undefined,
offset: offset + limit,
limit,
}
: undefined,
};
};
const getAvailableComponentEntries = async ({
documentType,
}: {
documentType: CoveragePlanDocumentType;
}) => {
const summary = getComponentCatalogSummary();
return summary.components.filter((entry) =>
isComponentAvailableForDocumentType({
component: entry.component,
category: entry.category,
documentType,
})
);
};
const getComponentCoverageStatus = async ({
input,
executeOperation,
}: {
input: unknown;
executeOperation: ExecuteMcpOperation;
}) => {
const { pageId, pagePath, documentType } = getCoverageStatusInput(input);
const envelope = await executeOperation({
command: "list-instances",
input: {
pageId,
pagePath,
},
dryRun: false,
});
const instancesResult = envelope.result;
if (
isPlainRecord(instancesResult) === false ||
Array.isArray(instancesResult.instances) === false
) {
throw new Error(
"components.coverage-status could not read list-instances result."
);
}
const presentComponents = new Set(
instancesResult.instances.flatMap((instance) =>
isPlainRecord(instance) && typeof instance.component === "string"
? [instance.component]
: []
)
);
const instanceIdsByComponent = new Map<string, string[]>();
for (const instance of instancesResult.instances) {
if (
isPlainRecord(instance) === false ||
typeof instance.component !== "string" ||
typeof instance.id !== "string"
) {
continue;
}
const instanceIds = instanceIdsByComponent.get(instance.component) ?? [];
instanceIds.push(instance.id);
instanceIdsByComponent.set(instance.component, instanceIds);
}
const availableEntries = await getAvailableComponentEntries({
documentType,
});
const covered = availableEntries.filter((entry) =>
presentComponents.has(entry.component)
);
const missing = availableEntries.filter(
(entry) => presentComponents.has(entry.component) === false
);
const toCoverageEntry = ({
component,
jsxName,
jsxElement,
namespace,
label,
}: ComponentSummaryEntry) => ({
component,
jsxName,
jsxElement,
namespace,
label,
instanceIds: instanceIdsByComponent.get(component),
});
return {
usage:
"Use this after bounded insertions to verify component coverage for one page. Continue by inserting missingRoots with insert-fragment or insert-component; missingParts are usually covered by root/template components.",
pageId,
pagePath,
documentType,
total: availableEntries.length,
coveredCount: covered.length,
missingCount: missing.length,
covered: covered.map(toCoverageEntry),
missing: missing.map(toCoverageEntry),
missingRoots: missing
.filter((entry) => entry.standaloneInsertable)
.map(toCoverageEntry),
missingParts: missing
.filter((entry) => entry.standaloneInsertable === false)
.map(toCoverageEntry),
session: serializeProjectSessionMeta(envelope),
};
};
const getComponentCoverageInsertNext = async ({
input,
executeOperation,
dryRun,
}: {
input: unknown;
executeOperation: ExecuteMcpOperation;
dryRun: boolean;
}) => {
const { parentInstanceId, component, ...statusInput } =
getCoverageInsertNextInput(input);
const definedStatusInput = Object.fromEntries(
Object.entries(statusInput).filter(([, value]) => value !== undefined)
);
const before = await getComponentCoverageStatus({
input: definedStatusInput,
executeOperation,
});
const missingRoots = before.missingRoots;
const missingParts = before.missingParts;
const selectedRoot =
component === undefined
? missingRoots[0]
: missingRoots.find((entry) => entry.component === component);
const selectedPart =
selectedRoot === undefined && component !== undefined
? missingParts.find((entry) => entry.component === component)
: selectedRoot === undefined && missingRoots.length === 0
? missingParts[0]
: undefined;
const getCompatibleParent = (childComponent: string) => {
for (const coveredEntry of before.covered) {
const contentModel = componentMetas.get(
coveredEntry.component
)?.contentModel;
const childComponents = [
...(contentModel?.children ?? []),
...(contentModel?.descendants ?? []),
];
if (childComponents.includes(childComponent) === false) {
continue;
}
const [parentInstanceId] = coveredEntry.instanceIds ?? [];
if (parentInstanceId !== undefined) {
return parentInstanceId;
}
}
};
const partParentInstanceId =
selectedPart === undefined
? undefined
: getCompatibleParent(selectedPart.component);
if (selectedRoot === undefined && selectedPart === undefined) {
const available = [...missingRoots, ...missingParts]
.slice(0, 12)
.map((entry) => entry.component)
.join(", ");
throw new Error(
component === undefined
? "components.coverage-insert-next found no missing components to insert."
: `components.coverage-insert-next input.component must be one of the missing components. Available examples: ${available}`
);
}
if (selectedPart !== undefined && partParentInstanceId === undefined) {
throw new Error(
`components.coverage-insert-next cannot insert non-standalone component "${selectedPart.component}" because no compatible parent instance is present on the page. Insert a root/template component that allows it first, or use insert-fragment with an explicit valid parent.`
);
}
const selected = selectedRoot ?? selectedPart;
if (selected === undefined) {
throw new Error("components.coverage-insert-next found no component.");
}
const insert = await executeOperation({
command: "insert-component",
input: {
parentInstanceId:
selectedRoot === undefined ? partParentInstanceId : parentInstanceId,
component: selected.component,
},
dryRun,
});
const after = await getComponentCoverageStatus({
input: definedStatusInput,
executeOperation,
});
return {
usage:
"Checkpoint-safe coverage mutation. Report this single inserted component and coverage before/after before continuing.",
checkpoint: {
required: true,
reason:
"Design-system/all-component work must report after each coverage insertion.",
instruction:
"Stop after this components.coverage-insert-next response and report the inserted component, committed version, and coverage before/after to the parent before calling more tools.",
nextCommand:
'node packages/cli/local.js components.coverage-insert-next \'{"pagePath":"' +
(statusInput.pagePath ?? "/design-system") +
'","parentInstanceId":"' +
parentInstanceId +
"\"}'",
nextAllowedAfterReport:
"After reporting and parent/user continuation, call checkpoint.ack before the next workflow.next or components.coverage-insert-next call.",
},
inserted: {
component: selected.component,
label: selected.label,
jsxElement: selected.jsxElement,
namespace: selected.namespace,
mode: "component",
},
parentInstanceId:
selectedRoot === undefined ? partParentInstanceId : parentInstanceId,
committed: insert.state.committed,
insertResult: insert.result,
before: {
total: before.total,
coveredCount: before.coveredCount,
missingCount: before.missingCount,
},
after: {
total: after.total,
coveredCount: after.coveredCount,
missingCount: after.missingCount,
nextMissingRoots: after.missingRoots.slice(0, 12),
remainingMissingRootCount: after.missingRoots.length,
},
session: serializeProjectSessionMeta(insert),
};
};
const getComponentFindInput = (
input: unknown,
toolName: "components.find" | "components.search"
) => {
const { limit, offset } = getOffsetPaginationInput({
input,
toolName,
defaultLimit: 12,
maxLimit: 25,
});
return {
brief: getRequiredStringInput(input, "brief", toolName),
limit,
offset,
};
};
const compactComponentSearchEntry = (entry: Record<string, unknown>) => {
const {
templateRequiredEdges: _templateRequiredEdges,
templateRequiredParts: _templateRequiredParts,
templateTextContent: _templateTextContent,
...compactEntry
} = entry;
return Object.fromEntries(
Object.entries(compactEntry).filter(([, value]) => value !== undefined)
);
};
const findComponents = async (
input: unknown,
toolName: "components.find" | "components.search" = "components.find"
) => {
const { brief, limit, offset } = getComponentFindInput(input, toolName);
const summary = getComponentCatalogSummary();
const normalizedBrief = normalize(brief);
const tokens = normalizedBrief
.split(/\s+/)
.filter((token) => token.length > 1);
const registryOnlyTemplates = getComponentRegistryItems()
.filter(
(item) =>
item.meta.source === "template" &&
componentMetas.has(item.meta.component) === false
)
.map((item) => {
const [parsedNamespace, exportName] = parseComponentName(
item.meta.component
);
return {
component: item.meta.component,
exportName,
namespace: parsedNamespace ?? "global",
label: item.meta.label,
category: item.meta.category,
hasTemplate: true,
standaloneInsertable: true,
insertWith: item.meta.insert.component,
template: item.name,
description: item.description,
};
});
const components =
tokens.length === 0
? []
: [...summary.components, ...registryOnlyTemplates]
.map((entry) => {
const haystack = normalize(
[
entry.component,
entry.exportName,
entry.namespace,
entry.label,
entry.category,
"contentCategory" in entry ? entry.contentCategory : undefined,
"template" in entry ? entry.template : undefined,
"description" in entry ? entry.description : undefined,
]
.filter(Boolean)
.join(" ")
);
const matchedTokens = tokens.filter((token) =>
haystack.includes(token)
);
return {
entry,
matchedTokens,
score:
matchedTokens.reduce(
(total, token) => total + token.length * 20,
0
) +
(entry.standaloneInsertable ? 100 : 0) +
(matchedTokens.some((token) =>
normalize(entry.exportName).includes(token)
)
? 10
: 0),
};
})
.filter(({ matchedTokens }) => matchedTokens.length > 0)
.sort(
(left, right) =>
right.score - left.score ||
left.entry.component.localeCompare(right.entry.component)
)
.map(({ entry, matchedTokens }) => ({
...entry,
matchedTokens,
}));
const pagedComponents = components
.slice(offset, offset + limit)
.map(compactComponentSearchEntry);
const nextOffset =
offset + limit < components.length ? offset + limit : undefined;
return {
usage:
"Search results are ranked, compact, and paged. Standalone/template roots are ranked before child parts. Multi-word searches match any meaningful token. Prefer insert-fragment for authored/styled sections. Use insert-component with insertWith/component only when inserting one standalone template/component. For component details, call components.get with component. For registry-only template results, call templates.get with the returned template id.",
query: brief,
count: pagedComponents.length,
totalCount: components.length,
omittedCount: Math.max(
0,
components.length - offset - pagedComponents.length
),
pagination: {
offset,
limit,
nextOffset,
},
components: pagedComponents,
};
};
const getComponentDetails = (component: string) => {
const templates = getComponentTemplates();
const entry = getComponentSummaryEntry({
component,
templates,
includeHiddenRequiredPart: true,
});
const meta = componentMetas.get(component);
const stateUsage = getComponentStateUsage(meta?.states);
const animationUsage = getAnimationComponentGuidance(component);
const collectionUsage =
component === "ws:collection" ? collectionComponentUsage : undefined;
const jsonLdUsage =
component === "JsonLd"
? 'Prefer placing JsonLd inside HeadSlot. Insert it with insert-component using the HeadSlot instance as parentInstanceId and component "JsonLd". For fixed structured data, set code with update-props using type "string" and a compact JSON object or array string. For structured data containing runtime values, use bind-props with an expression that evaluates directly to an object or array. The binding value stores expression source text, but the evaluated result must not be a string. Do not call JSON.stringify or assemble JSON with string concatenation; JsonLd validates and serializes the evaluated value. Fixed values with structurally invalid JSON-LD are rejected. Run audit with the seo scope after editing to find unknown, superseded, unsupported, or incompatible Schema.org terms; vocabulary findings are warnings because custom vocabularies remain valid.'
: undefined;
if (entry === undefined || meta === undefined) {
const templateItem = getComponentRegistryItems().find((item) => {
if (item.meta.source !== "template") {
return false;
}
return (
item.meta.component === component ||
getTemplateRootComponent(templates, item.meta.component) === component
);
});
if (templateItem !== undefined) {
const template = templates.get(templateItem.meta.component)?.template;
const rootComponent = getTemplateRootComponent(
templates,
templateItem.meta.component
);
const rootMeta = componentMetas.get(rootComponent ?? "");
return {
found: true,
component: rootComponent ?? templateItem.meta.component,
...templateItem,
props: rootMeta?.props ?? {},
states: rootMeta?.states ?? [],
template,
usage: `Use insert-component with component "${templateItem.meta.component}" to insert this template.`,
};
}
return {
found: false,
component,
usage:
'Component id was not found in the known registry. Do not insert a guessed component id; use components.search, components.list, or templates.list to discover the exact id. For a native HTML element, use component "ws:element" with its "tag" property instead of inventing an id such as "ws:div".',
};
}
return {
found: true,
...entry,
description: meta.description,
contentModel: meta.contentModel,
initialProps: meta.initialProps ?? [],
props: meta.props ?? {},
states: meta.states ?? [],
stateUsage,
animationUsage,
collectionUsage,
jsonLdUsage,
indexWithinAncestor: meta.indexWithinAncestor,
usage: [
entry.standaloneInsertable
? `Use insert-fragment when composing/styling a section, or insert-component with component "${component}" when inserting exactly this component template. A registered template is applied automatically by insert-component when available. For JSX, include templateRequiredParts and nest them according to templateRequiredEdges; templateRootComponents shows the roots produced by the template.`
: "Do not insert this component standalone. It is a child/part component and must be created by inserting a containing root/template component.",
stateUsage,
animationUsage,
collectionUsage,
jsonLdUsage,
]
.filter(Boolean)
.join(" "),
};
};
const insertFragmentInputFilePath = ".temp/insert-fragment.json";
const insertFragmentInputFileExample = {
parentInstanceId: "parent-id",
fragment:
"<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Section title</h2><p>Section copy.</p></section>",
};
const getToolCatalogOverview = (tools: readonly ProjectSessionMcpTool[]) => ({
usage:
'Short tool overview. Do one small discovery step, then act. Start with meta.index or meta.guide({"brief":"Create a pricing page"}). Use meta.get-more-tools({"tools":["insert-fragment"]}) for exact details, or read the bounded webstudio://project/tools catalog.',
count: tools.length,
capabilities: filterCapabilities(tools).map((capability) => ({
area: capability.area,
goal: capability.goal,
count: capability.tools.length,
})),
});
const getMetaIndex = (
tools: readonly ProjectSessionMcpTool[],
guidance: ProjectSessionMcpGuidance | undefined
) => {
const names = new Set(tools.map((tool) => tool.name));
const canVerifyVisually = ["preview.start", "screenshot"].every((tool) =>
names.has(tool)
);
return {
readThisFirst: startupGuidance,
startHere: [
"meta.index",
"meta.guide",
"workflow.next",
"components.list",
"components.summary",
"status",
"permissions",
].filter((tool) => names.has(tool)),
discovery: {
overview:
"Do not call every discovery tool up front. Use this meta.index response for orientation, then call at most one focused discovery tool before acting.",
tools:
'Use meta.get-more-tools({"tools":["insert-fragment"]}) for the primary authored/styled insertion tool. Use {"brief":"style updates"} only for search. Page through webstudio://project/tools only when broader operation discovery is necessary.',
insertFragment: `Primary authored/styled insertion command shape: save ${JSON.stringify(
insertFragmentInputFileExample
)} as ${insertFragmentInputFilePath}, then run node packages/cli/local.js insert-fragment --input-file ${insertFragmentInputFilePath} --dry-run. Use parentInstanceId, not parentId. Use lowercase HTML elements, direct registered component identifiers, and helpers such as css, token, expression, and ActionValue. Use ws:style={css\`...\`} for Webstudio-native CSS, or style={{ padding: 24 }} for React-style object syntax converted into editable Webstudio styles. Use node packages/cli/local.js mcp single-op-call insert-fragment only when you need the explicit MCP form.`,
resources:
"Use MCP resources/list to discover overview and full resources.",
projectSearch:
'Use search-project({"query":"known value"}) to find a value or id across local Builder data without passing full namespaces to the model. Add namespaces only to narrow the search.',
components:
'Use components.list({"source":"all"}) for shadcn-compatible registry items, templates.list({}) for templates, components.summary for a compact catalog, components.coverage-plan for design-system/all-component tasks, components.coverage-insert-next({"pagePath":"/design-system","parentInstanceId":"root-id"}) for one checkpoint-safe coverage insertion, components.coverage-status({"pagePath":"/design-system"}) to verify progress, components.search({"brief":"radix select"}) to search, and components.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) or templates.get({"component":"@webstudio-is/sdk-components-react-radix:Select"}) for one item. Do not dump or parse webstudio://project/components unless those focused tools are insufficient.',
guide:
'Use meta.guide({"brief":"Create a design system page using every component"}) for a goal-specific workflow.',
expressions:
"Read webstudio://project/expressions before authoring unfamiliar expressions, Collection item bindings, or dynamic resource fields.",
accessibility:
"For an accessibility review, read webstudio://project/accessibility-review and run audit with scopes [accessibility]. Ask before using preview and screenshots unless the user explicitly requested visual verification.",
workflow:
'Use workflow.next({"goal":"design-system-page"}) for one bounded phase when delegated/non-streaming agents must return progress instead of silently running a broad task.',
details:
'Use meta.get-more-tools({"tools":["insert-fragment"]}) for matching params and examples.',
},
delegatedAgentRule:
"If your parent cannot see live command output, treat each 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 before the next MCP command.",
rules: [
"Operate on the configured project only.",
"Read ids before writing.",
"Prefer semantic tools over apply-patch.",
"For every collection.json frontmatter property, add a JSON Schema description that tells editors what to enter instead of repeating its label.",
"When a content collection has a dynamic entry page, read that page's id and store it as x-webstudio.entryPageId in collection.json. The page must have exactly one URL parameter. Webstudio does not infer this link from the page path or Assets query. Before handoff, verify Open on canvas from both an entry menu and Entry settings.",
valuesVsBindingsRule,
"Use status/refresh when cached data may be stale.",
guidance?.visualVerificationRule,
].filter((rule): rule is string => rule !== undefined),
visionLoop:
canVerifyVisually && guidance !== undefined
? guidance.getVisionVerificationLoop({
includeDiff: names.has("screenshot.diff"),
})
: [],
capabilities: filterCapabilities(tools),
};
};
const metaGoalGuides = [
{
id: "markdown-blog",
tools: [
"create-asset-folder",
"upload-assets",
"list-pages",
"list-assets",
"get-asset-field-catalog",
"validate-asset-query",
"preview-asset-query",
"create-page",
"create-assets-resource",
"insert-collection",
"insert-fragment",
"update-page",
"verify-page-responsive",
],
workflow: [
"Use .md for Markdown-only editing; use .mdx when visual Content mode is needed. MDX compiles during publishing, and Asset sync downloads both formats.",
"Follow recipe.executionOrder in order. Resolve documented placeholders from earlier results, and do not add calls outside that sequence.",
'Create one asset folder named exactly "Blog", then call upload-assets exactly once with all Markdown files and assetsDir ".webstudio/assets". Put slug, title, author, publishedAt, excerpt, and draft in frontmatter. Each asset uses {"name":"<filename>.md","type":"file","format":"md","folderId":"<blog-folder-id>","meta":{}}; do not create companion files.',
'Create exactly two pages once using the recipe pages payloads exactly: call create-page with {"path":"/blog","name":"Blog"} and {"path":"/blog/:slug","name":"Blog article"}. Use each returned pageId and rootInstanceId in later recipe placeholders. Do not omit name, dry-run page creation, create one page per post, or copy Markdown into static page content.',
"Substitute the returned folder id in every recipe query. Pass recipe.overviewValidationQuery and recipe.detailValidationQuery directly to validate-asset-query, then pass recipe.detailValidationQuery directly to preview-asset-query. These execution queries contain resolved JSON values. Do not copy the expression-bearing resource queries into validation or preview tools.",
"After both validations and the preview succeed, call recipe.toolDiscovery exactly once immediately before creating the resources. Do not call meta.get-more-tools again.",
'Create exactly one scoped Assets resource per page by copying recipe.overviewResource and recipe.detailResource unchanged except for id placeholders. Keep the detail query result as "one" and bind it directly without a Collection. Do not add query defaults or create placeholder resources.',
"Insert recipe.overviewCollection under the overview root with insert-collection, then insert recipe.detailFragment under the detail root with insert-fragment. The overview repeats posts; the detail page binds post.data directly.",
"Apply the page settings with update-page using recipe.detailPageSettings so the article title, description, social image, and 404 status use the same post resource as the page content.",
'After both insertions succeed, ask whether the user wants visual verification unless they explicitly requested it. If they decline, use focused reads and a static audit. If they opt in, call verify-page-responsive once for "/blog" and once for one concrete detail path with desktop and mobile viewports. Confirm Assets-backed content and empty/not-found behavior. Stop on an error instead of retrying.',
],
recipe: {
articleFormat: {
extension: "md",
editSurface: "asset-source-editor",
publishCompilation: false,
assetSyncDownloadsFiles: true,
visualAlternative: {
extension: "mdx",
editSurface: "content-block-canvas",
publishCompilation: true,
assetSyncDownloadsFiles: true,
workflow: "general",
tool: "connect-content-block-source",
},
},
executionOrder: [
{ tool: "create-asset-folder", calls: 1 },
{ tool: "upload-assets", calls: 1 },
{ tool: "create-page", calls: 2 },
{ tool: "validate-asset-query", calls: 2 },
{ tool: "preview-asset-query", calls: 1 },
{ tool: "meta.get-more-tools", calls: 1 },
{ tool: "create-assets-resource", calls: 2 },
{ tool: "insert-collection", calls: 1 },
{ tool: "insert-fragment", calls: 1 },
{ tool: "update-page", calls: 1 },
{ tool: "verify-page-responsive", calls: 2, terminal: true },
],
pages: [
{ path: "/blog", name: "Blog" },
{ path: "/blog/:slug", name: "Blog article" },
],
toolDiscovery: {
tool: "meta.get-more-tools",
when: "after-query-verification",
input: {
tools: ["create-assets-resource"],
},
},
overviewValidationQuery: {
result: "many",
where: {
all: [
{
field: ["extension"],
operator: "eq",
value: "md",
},
{
field: ["folderId"],
operator: "eq",
value: "<blog-folder-id>",
},
{
field: ["properties", "draft"],
operator: "ne",
value: true,
},
],
},
sort: [
{ field: ["properties", "publishedAt"], direction: "desc" },
{ field: ["id"], direction: "asc" },
],
limit: 20,
offset: 0,
output: {
mode: "fields",
includeMetadata: false,
fields: [
["properties", "title"],
["properties", "slug"],
["properties", "publishedAt"],
["properties", "author"],
["properties", "excerpt"],
],
},
content: { mode: "none" },
},
detailValidationQuery: {
result: "one",
where: {
all: [
{
field: ["extension"],
operator: "eq",
value: "md",
},
{
field: ["folderId"],
operator: "eq",
value: "<blog-folder-id>",
},
{
field: ["properties", "slug"],
operator: "eq",
value: "aurora-trails",
},
{
field: ["properties", "draft"],
operator: "ne",
value: true,
},
],
},
output: {
mode: "fields",
includeMetadata: false,
fields: [
["properties", "title"],
["properties", "author"],
["properties", "excerpt"],
["properties", "featureImage", "src"],
],
},
content: { mode: "markdown-body-ref" },
},
overviewResource: {
name: "Published posts",
scopeInstanceId: "<overview-root-id>",
dataSourceName: "posts",
query: {
result: "many",
where: {
all: [
{
field: ["extension"],
operator: "eq",
value: { type: "literal", value: "md" },
},
{
field: ["folderId"],
operator: "eq",
value: { type: "literal", value: "<blog-folder-id>" },
},
{
field: ["properties", "draft"],
operator: "ne",
value: { type: "literal", value: true },
},
],
},
sort: [
{ field: ["properties", "publishedAt"], direction: "desc" },
{ field: ["id"], direction: "asc" },
],
limit: { type: "literal", value: 20 },
offset: { type: "literal", value: 0 },
output: {
mode: "fields",
includeMetadata: false,
fields: [
["properties", "title"],
["properties", "slug"],
["properties", "publishedAt"],
["properties", "author"],
["properties", "excerpt"],
],
},
content: { mode: "none" },
},
},
detailResource: {
name: "Post by slug",
scopeInstanceId: "<detail-root-id>",
dataSourceName: "post",
query: {
result: "one",
where: {
all: [
{
field: ["extension"],
operator: "eq",
value: { type: "literal", value: "md" },
},
{
field: ["folderId"],
operator: "eq",
value: { type: "literal", value: "<blog-folder-id>" },
},
{
field: ["properties", "slug"],
operator: "eq",
value: "system.params.slug",
},
{
field: ["properties", "draft"],
operator: "ne",
value: { type: "literal", value: true },
},
],
},
output: {
mode: "fields",
includeMetadata: false,
fields: [
["properties", "title"],
["properties", "author"],
["properties", "excerpt"],
["properties", "featureImage", "src"],
],
},
content: { mode: "markdown-body-ref" },
},
},
overviewCollection: {
parentInstanceId: "<overview-root-id>",
data: { type: "expression", value: "posts.data" },
itemFragment:
'<article><h2>{expression`collectionItem.properties.title ?? "Untitled"`}</h2><p>{expression`collectionItem.properties.excerpt ?? ""`}</p><p>By {expression`collectionItem.properties.author.name`}</p><time>{expression`collectionItem.properties.publishedAt ?? ""`}</time><a href={expression`"/blog/" + collectionItem.properties.slug`}>Read article</a></article>',
},
detailFragment: {
parentInstanceId: "<detail-root-id>",
fragment:
'<article><h1>{expression`post.data.properties.title ?? "Untitled"`}</h1><p>By {expression`post.data.properties.author.name ?? ""`}</p><MarkdownEmbed code={expression`post.data.content.text`} /></article>',
},
detailPageSettings: {
pageId: "<detail-page-id>",
values: {
title: 'post.data.properties.title ?? "Article"',
meta: {
description: 'post.data.properties.excerpt ?? ""',
socialImageUrl: 'post.data.properties.featureImage.src ?? ""',
status: "post.data ? 200 : 404",
},
},
},
},
},
{
id: "content-block-source",
tools: [
"inspect-instance",
"connect-content-block-source",
"inspect-content-block-source",
"update-text",
"bind-props",
"update-content-block-frontmatter",
"reload-content-block-source",
"audit",
],
workflow: [
"Inspect the designed Content Block and its persistent header instances. Connect the Markdown or MDX Asset with connect-content-block-source, then inspect the source to get the actual document parameter name and scope.",
"Before changing frontmatter, bind every requested designed header text value directly to the document parameter with update-text and expressionBindingMode readwrite. Use exact frontmatter paths; keep fixed suffixes and labels as separate static text. Use bind-props only for component properties, not text children.",
"Update frontmatter with update-content-block-frontmatter, preserving every existing property the user did not ask to change. Do not target MDX-rendered descendants with generic instance mutations.",
"Reload the connected source, inspect the saved frontmatter and diagnostics, then run audit. Confirm each requested header value is still a direct writable binding and remains outside the MDX body.",
],
recipe: {
executionOrder: [
{ tool: "inspect-instance", calls: 1 },
{ tool: "connect-content-block-source", calls: 1 },
{ tool: "inspect-content-block-source", calls: 1 },
{
tool: "update-text",
calls: "once per requested designed text field",
},
{ tool: "update-content-block-frontmatter", calls: 1 },
{ tool: "reload-content-block-source", calls: 1 },
{ tool: "inspect-content-block-source", calls: 1 },
{ tool: "audit", calls: 1 },
],
connectSource: {
source: { type: "asset", assetId: "<md-or-mdx-asset-id>" },
},
designedTextBinding: {
tool: "update-text",
input: {
instanceId: "<designedTextInstanceId>",
childIndex: 0,
text: "<documentVariable>.frontmatter.<exactFieldPath>",
mode: "expression",
expressionBindingMode: "readwrite",
},
},
},
},
{
id: "json-ld",
tools: [
"components.get",
"list-instances",
"insert-component",
"update-props",
"bind-props",
"audit",
],
workflow: [
'Call components.get with {"component":"JsonLd"}; do not use update-page custom metadata for JSON-LD.',
"Find the page HeadSlot instance with list-instances.",
'Insert JsonLd under HeadSlot with insert-component. For fixed structured data, set code with update-props using type "string" and a compact JSON object or array string.',
"For structured data containing runtime values, set code with bind-props using an expression that evaluates directly to an object or array. The binding value stores expression source text, but the evaluated result must not be a string. Do not call JSON.stringify or assemble JSON with string concatenation; JsonLd performs validation and serialization.",
'Run audit with {"scopes":["seo"],"pagePath":"<path>"} and fix any JSON-LD finding.',
],
recipe: {
fixedCodeUpdate: {
updates: [
{
instanceId: "<json-ld-instance-id>",
name: "code",
type: "string",
value:
'{"@context":"https://schema.org","@type":"Organization","name":"Acme"}',
},
],
},
dynamicCodeBinding: {
bindings: [
{
instanceId: "<json-ld-instance-id>",
name: "code",
binding: {
type: "expression",
value:
'({ "@context": "https://schema.org", "@type": "Article", headline: post.title })',
},
},
],
},
},
},
{
id: "collection",
tools: [
"components.get",
"list-variables",
"list-resources",
"insert-collection",
"inspect-instance",
"audit",
],
workflow: [
"Find the array or object to repeat. For a scoped resource result, select the complete nested array/object, commonly below the result's data field; do not bind the response wrapper or one indexed item.",
"Call insert-collection once with the complete iterable and one repeated-item JSX root. Use expression`collectionItem.name` and expression`collectionItemKey` inside the item fragment; the operation creates and binds private parameters atomically.",
"Wrap multiple repeated sibling instances in one lowercase HTML element such as <div>. Do not create, replace, or delete Collection parameter records manually.",
"Verify that every array/object entry renders once. For repeated Radix items, bind a stable unique id or slug to required value props.",
],
},
{
id: "expression",
tools: [
"list-variables",
"list-resources",
"list-texts",
"inspect-instance",
"update-text",
"bind-props",
"update-resource",
],
workflow: [
"Read webstudio://project/expressions for the supported syntax, method allowlist, scope rules, and encoding examples.",
"Read variables, resources, the target instance, and existing bindings before writing an expression; do not guess scoped identifier names.",
"Use one expression rather than a statement or function. Use direct values for fixed content and expressions only for runtime-computed values.",
"A successful syntax validation does not prove the runtime data shape or scope is correct. Ask whether the user wants visual verification unless they explicitly requested it. If they decline, stop after focused binding and data-shape checks. If they opt in, preview the affected route with representative and empty data.",
],
},
{
id: "authenticated-page",
tools: [
"inspect-auth-context",
"list-instances",
"create-page",
"create-resource",
"create-variable",
"insert-fragment-verified",
"update-page",
"verify-page-responsive",
],
workflow: [
"Inspect the project's existing auth resources, variables, page settings, and agent instructions before choosing a provider workflow. Call inspect-auth-context exactly once instead of calling get-project-settings, list-pages, list-resources, or list-variables separately; use at most one focused search-project call only when that bundle does not identify the auth convention. Treat its pages section as authoritative for route existence. Do not call get-page-by-path to confirm that /account is absent. Reuse that convention; do not add a second auth system implicitly.",
"Do not call meta.index after this guide. If an exact mutation schema is still needed, make at most one meta.get-more-tools call listing all immediately required authoring tools rather than rediscovering them one at a time.",
"Never place credentials, service-role keys, refresh tokens, private session values, or authenticated response bodies in project data, command output, screenshots, agent instructions, or error reports. Ask the user to configure secrets in the provider/server environment.",
"Keep all four auth states in the editable component structure even when bindings select only one at runtime. Give each state a visible label using the exact terms signed-out, loading, signed-in, and failed-auth so authors can inspect and verify every state. Use page basic auth only when the user asks for Webstudio's fixed login/password gate; it is not Supabase or Firebase authentication.",
"Use focused resources and variables for public client configuration and session-shaped data. Keep authorization enforcement and privileged provider calls server-side; a hidden Builder element is not an authorization boundary.",
"When fixture/session data must feed a resource, create the page and scoped fixture variables there. Use create-page's returned rootInstanceId directly instead of listing instances to rediscover it. Call list-variables after creation only when a resource expression actually needs the returned encoded name. Do not repeat list-variables when the fixture variable is not referenced, as in the expression-free state gallery, and do not guess or reference variables before they exist.",
"Create resources only after their scope and referenced variables exist. When reusing the discovered /api/auth/session convention, pass recipe.createResourceInput directly as the entire create-resource tool input, unchanged except for its account root id placeholder. Do not wrap it in another resource object. Keep every request field nested under resource. resource.url is the HTTP request target, not a provider call or session-state expression. Use literal wrappers only for fixed header, search-parameter, and body text.",
"Keep the server-mediated session resource as provider-convention evidence, but use only non-secret scoped fixture variables to drive local auth-state visibility. Do not bind that server-only resource into local preview rendering: its endpoint is intentionally absent locally and can recurse through the generated route.",
"Insert signed-out, loading, signed-in, and failed-auth panels together as one expression-free semantic fragment that acts as a state gallery. Keep all four panels visible together for local visual verification; do not add conditional visibility bindings or mutate fixture state solely to capture more screenshots. Use that exact fragment verbatim without adding styles, props, expressions, components, or changing its nesting: <main><section><h2>Signed-out</h2></section><section><h2>Loading</h2></section><section><h2>Signed-in</h2></section><section><h2>Failed-auth</h2></section></main>.",
"Do not call selector-based structural tools such as wrap-instance unless a focused list-instances result supplied the complete non-empty selector from the target through its page root. Prefer direct style, prop, or binding corrections when the structure is already sound.",
'Insert the complete account fragment with insert-fragment-verified and {"pagePath":"/account"} so persisted bindings are checked in the same call. Resolve every returned validity, scope, and reference finding before previewing. If post-commit verification reports an infrastructure failure, do not repeat the insertion; call verify-bindings separately for /account. Updating only a fixture variable\'s literal state does not require another binding verification.',
'Ask whether the user wants visual verification unless they explicitly requested it. If they decline, run a focused static audit and stop without preview or screenshots. If they opt in, call verify-page-responsive once with path "/account" and the required desktop and mobile viewports; it starts or refreshes the session preview, captures both viewports in one browser session, and immediately runs the static page audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately. Do not run discovery, inspect-instance, mutate, or repeat binding verification after this terminal verification begins. The screenshots are the rendered evidence and the bundled audit is the static evidence. Do not claim the real provider flow works until redirects, session refresh, failure handling, and protected data access are exercised in its configured environment.',
],
recipe: {
createResourceInput: {
scopeInstanceId: "<account-root-id>",
dataSourceName: "accountSession",
resource: {
name: "Account session via server",
method: "get",
url: "/api/auth/session",
headers: [],
searchParams: [],
},
},
},
},
{
id: "font-assets",
tools: [
"list-fonts",
"list-assets",
"upload-asset",
"upload-assets",
"update-asset",
"verify-font-assets",
"audit",
],
workflow: [
"The guide and MCP handshake already provide the required tool schemas. Do not call meta.index or meta.get-more-tools for this workflow.",
"Use upload-asset or upload-assets with the local filename, detected format, and complete family, style, and weight metadata. Use the returned asset ids directly; do not read a project snapshot to rediscover uploaded assets.",
"Use update-asset to correct font metadata without re-uploading the binary.",
"After font mutations, call verify-font-assets exactly once with every changed asset id. It refreshes the asset namespace and returns the persisted metadata in one bounded verification call; do not call refresh or get-asset separately.",
"Finish with exactly one audit call using recipe.audit. Do not pass asset ids or other unsupported fields to audit.",
],
recipe: {
upload: {
tool: "upload-assets",
input: {
assetsDir: ".webstudio/assets",
assetFields: ["name", "type", "format", "meta"],
excludedAssetFields: ["path"],
},
},
audit: { tool: "audit", input: {} },
},
},
{
id: "design-input",
tools: [
"inspect-design-context",
"list-style-sources",
"attach-design-token",
"components.search",
"create-page",
"insert-fragment-verified",
"update-styles",
"upload-asset",
"verify-page-responsive",
"screenshot.diff",
],
workflow: [
"The guide and MCP handshake already provide the required tool schemas. Do not call meta.index or meta.get-more-tools for this workflow.",
"Interpret the supplied design before mutating: identify page sections, responsive behavior, reusable patterns, assets, typography, color, spacing, and interaction states. Ask for missing source assets rather than inventing brand-critical content.",
"Before the first mutation, call inspect-design-context exactly once instead of calling list-pages, list-breakpoints, list-design-tokens, list-assets, or list-variables separately. Use one list-instances call only when needed to inspect a representative existing page pattern. Do not call get-styles: the bounded design context and optional focused instance result provide the reusable design-system evidence needed here without risking an oversized style dump. Reuse exact existing values, breakpoint ids, and patterns; do not create a parallel design system from approximate screenshot colors or spacing.",
"Call create-page exactly once and use its returned rootInstanceId as the insertion parent. Insert the complete semantic page in one fragment when practical, and use the insertion result's instanceIds for follow-up token attachments. Do not call list-instances after the first mutation to rediscover ids already returned by mutations.",
"After insertion, call attach-design-token at least once with an exact existing style source id returned by inspect-design-context. Attach it where the shared typography, color, or other token is intended. Reusing only the token's current raw value creates a disconnected local copy.",
"Create semantic editable structure with insert-fragment-verified using only lowercase HTML elements and literal text. Do not include inline styles or ws:style in the fragment; apply fixed CSS with update-styles after insertion. Do not improvise component names, expression syntax, or object-valued style expressions. Use assets for real imagery and text or controls for real content; do not flatten the design into one image or absolute-position every element.",
"Implement responsive behavior inside the project's actual breakpoint ranges.",
'Represent literal CSS values as {"type":"keyword","value":"..."}, including lengths such as "48px" and colors such as "#fff". Do not invent value types such as "length"; use {"type":"unit","value":48,"unit":"px"} only when numeric structure is specifically needed.',
"Each update-styles updates item is flat: include instanceId, property, value, and optional breakpoint directly on every item. Do not group properties under styles or declarations.",
'Call insert-fragment-verified exactly once with {"pagePath":"/summer"} so insertion and persisted binding verification share one bounded call; do not guess a page id or alternate input shape. Treat its verification result as the structural and binding checkpoint before attaching tokens or applying fixed style/page updates. If post-commit verification reports an infrastructure failure, do not repeat the insertion; call verify-bindings separately for /summer. Later fixed-value mutations do not require another binding verification. Finish them before asking whether the user wants visual verification, unless they explicitly requested it. If they decline, run a focused static audit and stop without preview or screenshots. If they opt in, call verify-page-responsive once with path "/summer" and exactly the two supplied viewports, 1440x900 and 390x844. It starts or refreshes preview automatically, captures both viewports, and immediately runs the static page audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately, and do not add exploratory or intermediate captures. Do not mutate, rediscover, or repeat binding verification after this terminal verification begins. The screenshots are the rendered evidence and the bundled audit is the static evidence. Visual similarity is evidence, not permission to discard accessibility or project conventions.',
],
recipe: {
insertion: { includeStyles: false },
tokenReuse: {
minimumAttachments: 1,
source: "inspect-design-context",
},
responsiveStyles: {
tool: "update-styles",
breakpointSource: "inspect-design-context",
minimumBreakpointSpecificUpdates: 1,
},
},
},
{
id: "craft",
tools: [
"audit",
"list-variables",
"list-design-tokens",
"list-style-sources",
"list-pages",
"update-styles",
],
workflow: [
'Run audit with {"scopes":["craft"]} before changing the project. Use profileStatuses for the detected profile, source provenance, next action, preservation guidance, and template compatibility.',
"If Craft is not detected, do not add Craft variables, tokens, or templates unless the user explicitly asks to adopt Craft.",
"For partial or modified Craft projects, apply only the first reported missing or incompatible requirement, preserve project-specific values and non-Craft styles, then rerun the Craft audit.",
"Use a Craft-dependent template only when templateCompatibility is compatible; requires-review means repair or explicitly resolve the mismatch first.",
],
},
] as const satisfies readonly {
id: SpecializedMetaGuideWorkflow;
tools: readonly string[];
workflow: readonly string[];
recipe?: unknown;
}[];
const metaGuideExampleTools = new Set(["upload-assets"]);
const workflowOnlyGuideToolNames = new Set([
"inspect-auth-context",
"inspect-design-context",
]);
const designSystemGuideToolNames = new Set([
"list-design-tokens",
"attach-design-token",
"update-design-token-styles",
]);
const readOnlyDiscoveryToolNames = [
"search-project",
"list-instances",
"inspect-instance",
"get-project-settings",
"snapshot",
] as const;
const serializeMetaGuideTool = (
tool: ProjectSessionMcpTool,
includeHandshakeFields: boolean
) =>
includeHandshakeFields
? {
name: tool.name,
use: tool.description,
method: tool.annotations.method,
permit: tool.annotations.permit,
inputFields: tool.annotations.inputFields,
requiredInputFields: tool.annotations.requiredInputFields,
mcpExamples: tool.mcpExamples ?? [],
}
: {
name: tool.name,
...(metaGuideExampleTools.has(tool.name)
? { mcpExamples: tool.mcpExamples ?? [] }
: {}),
};
const getReadOnlyMetaGuide = (
brief: string,
tools: readonly ProjectSessionMcpTool[]
) => {
const toolByName = new Map(tools.map((tool) => [tool.name, tool]));
const prioritizedTools = readOnlyDiscoveryToolNames.flatMap((name) => {
const tool = toolByName.get(name);
return tool === undefined ? [] : [tool];
});
const matches = [...prioritizedTools, ...getMatchingTools(brief, tools)]
.filter((tool) => tool.annotations.method === "query")
.filter(
(tool, index, selectedTools) =>
selectedTools.findIndex(({ name }) => name === tool.name) === index
)
.slice(0, 12);
return {
taskScope: "read-only-audit",
routing: {
matchedBy: "explicit-read-only",
workflow: "read-only-discovery",
broadContextTools: [],
authoredFragment: false,
},
constraints: {
readOnly: true,
mutationToolsExcluded: true,
},
delegatedAgentRule:
"Do not spend the whole phase on discovery. If you are delegated/non-streaming and 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 before the next MCP command.",
visionLoop: [],
workflow: [
"Keep every call read-only. Preserve the brief's prohibitions; do not create, update, delete, publish, preview, install, or otherwise change project or local state.",
"Use search-project for known values, identifiers, selectors, URLs, or code fragments across project data.",
"Use focused list, get, and inspect tools to identify the existing structure and read details only for relevant results.",
"Read project settings only when they are part of the requested inventory. Use a bounded snapshot only when focused reads cannot provide the required cross-namespace context.",
"Return the requested inventory, classifications, risks, and consolidation plan without applying the plan.",
],
tools: matches.map((tool) => serializeMetaGuideTool(tool, true)),
more: "This guide excludes mutation and side-effecting session tools. Use focused read-only discovery only.",
};
};
const getMetaGuide = ({
brief,
taskScope,
workflow,
authoredFragment,
reuseDesignSystem,
tools,
guidance,
}: {
brief: string;
taskScope: TaskScope;
workflow: MetaGuideWorkflow;
authoredFragment: boolean;
reuseDesignSystem: boolean;
tools: readonly ProjectSessionMcpTool[];
guidance: ProjectSessionMcpGuidance | undefined;
}) => {
if (taskScope === "read-only-audit") {
return getReadOnlyMetaGuide(brief, tools);
}
const isSmallCorrection = taskScope === "small-value-or-reference-correction";
const goalGuide =
workflow === "general"
? undefined
: metaGoalGuides.find(({ id }) => id === workflow);
const matchedTools =
goalGuide === undefined
? getMatchingTools(brief, tools)
.filter(
(tool) =>
workflowOnlyGuideToolNames.has(tool.name) === false &&
(authoredFragment === false ||
(tool.name.startsWith("components.") === false &&
tool.name.startsWith("templates.") === false)) &&
(authoredFragment === false ||
reuseDesignSystem ||
designSystemGuideToolNames.has(tool.name) === false)
)
.slice(0, 12)
: getExactToolSelection(goalGuide.tools, tools).tools;
const searchProjectTool = tools.find(
(tool) => tool.name === "search-project"
);
const matches =
goalGuide === undefined &&
isSmallCorrection &&
searchProjectTool !== undefined
? [
searchProjectTool,
...matchedTools.filter((tool) => tool !== searchProjectTool),
].slice(0, 12)
: matchedTools;
const canVerifyVisually =
tools.some((tool) => tool.name === "preview.start") &&
tools.some((tool) => tool.name === "screenshot");
const canDiffScreenshots = tools.some(
(tool) => tool.name === "screenshot.diff"
);
const needsVisualVerification = taskScope === "visual-change";
const generalWorkflow = [
isSmallCorrection
? "Call search-project once with the known value or id, then make the smallest semantic edit and run targeted assertions."
: undefined,
"Use the fewest discovery calls needed for the immediate action.",
"Call permissions or status only when the task depends on capabilities or local session freshness.",
matches.some((tool) => tool.annotations.localCapable) &&
matches.some((tool) => tool.name === "verify-font-assets") === false
? "Call refresh if cached namespaces may be stale."
: undefined,
"Use search-project for a known value or id across project data. Use focused list/get tools when the structure or target is not yet known.",
"Use the smallest semantic mutation tool that matches the requested change.",
valuesVsBindingsRule,
"Use apply-patch only when no semantic mutation tool fits.",
needsVisualVerification && canVerifyVisually && guidance !== undefined
? guidance.getVisionWorkflowSummary({ includeDiff: canDiffScreenshots })
: undefined,
].filter(Boolean);
const generalGuide =
goalGuide === undefined
? {
delegatedAgentRule:
"Do not spend the whole phase on discovery. If you are delegated/non-streaming and 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 before the next MCP command.",
visionLoop:
needsVisualVerification &&
canVerifyVisually &&
guidance !== undefined
? guidance.getVisionVerificationLoop({
includeDiff: canDiffScreenshots,
})
: [],
slowOperation: {
confirmationRequired: true,
operation: "full production preview",
estimatedDuration: "30–60 seconds",
reason:
"Builds complete rendered output and is unnecessary for a focused value correction unless the requested outcome depends on layout or runtime behavior.",
fasterAlternative: {
operation: "targeted route validation",
estimatedDuration: "2–5 seconds",
limitations: "Does not visually inspect layout.",
},
},
}
: {};
return {
taskScope,
routing: {
matchedBy:
goalGuide === undefined ? "general-tool-ranking" : "explicit-workflow",
workflow,
broadContextTools:
goalGuide?.tools.filter((tool) =>
workflowOnlyGuideToolNames.has(tool)
) ?? [],
authoredFragment,
},
...generalGuide,
...(isSmallCorrection && goalGuide === undefined
? {
focusedCorrection: {
search: {
tool: "search-project",
requiredInput: ["query"],
calls: 1,
},
edit: { strategy: "smallest-semantic-mutation" },
verify: { strategy: "targeted-assertions" },
},
}
: {}),
workflow: goalGuide?.workflow ?? generalWorkflow,
tools: matches.map((tool) =>
serializeMetaGuideTool(tool, goalGuide === undefined)
),
...(goalGuide !== undefined && "recipe" in goalGuide
? { recipe: goalGuide.recipe }
: {}),
more:
goalGuide === undefined
? "The MCP handshake provides tool argument contracts and required fields. This guide includes focused examples; call meta.get-more-tools once with all needed tool names when you need a focused copy of nested input schemas or server/local behavior."
: "Follow this workflow and recipe without additional discovery unless the workflow explicitly requests it.",
};
};
const getWorkflowInput = (input: unknown) => {
if (isPlainRecord(input) === false) {
return { goal: "design-system-page", phase: undefined };
}
const goal =
typeof input.goal === "string" && input.goal.length > 0
? input.goal
: "design-system-page";
const phase = input.phase;
if (phase === undefined) {
return { goal, phase: undefined };
}
if (
typeof phase !== "string" ||
workflowPhaseNames.includes(phase as WorkflowPhaseName) === false
) {
throw new Error(
`workflow.next input.phase must be one of ${workflowPhaseNames.join(
", "
)}.`
);
}
return { goal, phase: phase as WorkflowPhaseName };
};
const designSystemWorkflowPhases: Record<
WorkflowPhaseName,
{
purpose: string;
allowedTools: readonly string[];
commandPattern: string;
fallbackCommandPattern?: string;
inputFile?: {
path: string;
contents: {
parentInstanceId: string;
fragment: string;
};
};
constraints?: readonly string[];
expectedReturn: readonly string[];
nextPhase?: WorkflowPhaseName;
}
> = {
discovery: {
purpose:
"Discover component coverage counts and the first page of root/template components.",
allowedTools: ["components.coverage-plan"],
commandPattern: "node packages/cli/local.js components.coverage-plan",
expectedReturn: [
"coverage totals",
"root/part counts",
"next planned phase",
],
nextPhase: "page-creation",
},
"page-creation": {
purpose:
"Identify exactly one target page and return its page id and root instance id. Create it only if lookup proves it is missing.",
allowedTools: ["create-page", "list-pages", "get-page-by-path"],
commandPattern: "node packages/cli/local.js list-pages '{\"limit\":20}'",
fallbackCommandPattern:
'node packages/cli/local.js create-page \'{"path":"/design-system","name":"Design System"}\'',
expectedReturn: [
"page id",
"page path",
"root instance id",
"whether /design-system already exists",
"if missing, report that create-page is the next phase action",
],
nextPhase: "dry-run-section",
},
"dry-run-section": {
purpose:
"Validate one tiny authored/styled JSX smoke fragment without committing.",
allowedTools: ["meta.get-more-tools", "components.get", "insert-fragment"],
commandPattern:
"node packages/cli/local.js insert-fragment --input-file .temp/design-system-section.json --dry-run",
inputFile: {
path: ".temp/design-system-section.json",
contents: {
parentInstanceId: "root-id",
fragment:
"<section ws:style={css`padding: 24px;`}><h2>Design System</h2></section>",
},
},
constraints: [
"Save inputFile.contents at inputFile.path, replacing only root-id, then use the commandPattern as-is.",
"Keep the dry-run fragment tiny, ideally under 500 characters.",
"Do not design the real page in this phase.",
"Use lowercase HTML tags or direct component identifiers confirmed by components.get; do not use legacy ws.element, $.Box, $.Heading, $.Paragraph, or $.Button syntax.",
"Return immediately after one dry-run result.",
],
expectedReturn: [
"dry-run diagnostics",
"computed transaction",
"whether the JSX is valid",
],
nextPhase: "commit-section",
},
"commit-section": {
purpose:
"Commit exactly one previously validated authored/styled JSX section or one template root.",
allowedTools: ["insert-fragment", "insert-component"],
commandPattern:
"node packages/cli/local.js insert-fragment --input-file .temp/design-system-section.json",
expectedReturn: ["committed version", "inserted root instance id"],
nextPhase: "coverage-batch",
},
"coverage-batch": {
purpose:
"Inspect coverage and insert exactly one missing root/template component, then return before continuing. This is only the mechanical coverage phase, not visual completion.",
allowedTools: ["components.coverage-insert-next"],
commandPattern:
'node packages/cli/local.js components.coverage-insert-next \'{"pagePath":"/design-system","parentInstanceId":"root-id"}\'',
expectedReturn: [
"covered and missing counts",
"the single component attempted in this checkpoint",
"next missing components or next coverage offset",
],
nextPhase: "presentation-pass",
},
"presentation-pass": {
purpose:
"Turn the mechanically covered component set into a real design-system page: group examples into styled sections/cards, apply spacing/background/type styles, and verify the page does not look like raw unstyled component dumps.",
allowedTools: [
"list-instances",
"inspect-instance",
"insert-fragment",
"move-instance",
"update-styles",
"components.coverage-status",
],
commandPattern:
'node packages/cli/local.js list-instances \'{"pagePath":"/design-system","maxDepth":2}\'',
constraints: [
"Do not treat coverage 72/72 as completion by itself.",
"Keep every covered component on the page while improving layout and styling.",
"Use styled lowercase HTML sections/cards, update-styles, and move-instance as needed.",
"Return a checkpoint with visual/presentation changes and final coverage.",
],
expectedReturn: [
"presentation changes made",
"final coverage totals",
"remaining visual issues or explicit none",
],
},
};
const getWorkflowNext = (input: unknown) => {
const { goal, phase } = getWorkflowInput(input);
if (goal !== "design-system-page") {
throw new Error(
'workflow.next currently supports goal "design-system-page".'
);
}
const phaseName = phase ?? "discovery";
const phaseInfo = designSystemWorkflowPhases[phaseName];
return {
goal,
phase: phaseName,
mustReturnAfter: true,
parentVisibleCheckpoint:
"Run only this phase, then return the command/result to the parent before any next MCP command. After the parent continues, acknowledge this checkpoint first, then call workflow.next with the next phase.",
checkpoint: {
required: true,
reason:
"workflow.next is a delegated-agent phase boundary and must be reported before more MCP calls.",
instruction:
"Stop after this workflow.next response and report the phase, allowed tools, command pattern, and planned next action to the parent before calling more MCP tools.",
nextCommand: phaseInfo.commandPattern,
nextAllowedAfterReport: `After reporting and parent/user continuation, call checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}, run only the ${phaseName} phase, then return another checkpoint before continuing. To move to the next phase later, acknowledge that phase checkpoint before calling workflow.next again.`,
},
...phaseInfo,
allPhases: workflowPhaseNames,
};
};
const toUnderscoredToolName = (name: string) =>
name.replace(/[^a-zA-Z0-9_]/g, "_");
const getExactToolSelection = (
toolNames: readonly string[],
tools: readonly ProjectSessionMcpTool[]
) => {
const toolNameIndex = createToolNameIndex(tools);
const selectedTools: ProjectSessionMcpTool[] = [];
const missingTools: string[] = [];
const includedToolNames = new Set<string>();
for (const requestedName of toolNames) {
const tool = toolNameIndex.get(requestedName);
if (tool === undefined) {
missingTools.push(requestedName);
continue;
}
if (includedToolNames.has(tool.name)) {
continue;
}
includedToolNames.add(tool.name);
selectedTools.push(tool);
}
return { tools: selectedTools, missingTools };
};
const serializeToolDetails = (tool: ProjectSessionMcpTool) => ({
name: tool.name,
description: tool.description,
inputSchema: getDetailedProjectSessionMcpInputSchema(tool),
inputFields: tool.annotations.inputFields,
requiredInputFields: tool.annotations.requiredInputFields,
mcpExamples: tool.mcpExamples ?? [],
inputNote: `MCP tool arguments are JSON objects, not CLI flags. For authored content with styles, prefer insert-fragment so JSX is converted locally into Webstudio data before mutation. Examples show intent, but do not imply MCP flag names. ${valuesVsBindingsRule}`,
annotations: tool.annotations,
});
const serializeCompactTool = (tool: ProjectSessionMcpTool) => ({
name: tool.name,
description:
tool.description.length <= 240
? tool.description
: `${tool.description.slice(0, 239)}…`,
method: tool.annotations.method,
requiredInputFields: tool.annotations.requiredInputFields,
});
const maxDiscoveryResourcePageSize = 50;
const defaultDiscoveryResourcePageSize = 20;
const getDiscoveryResourceInput = (uri: string, resourceUri: string) => {
const url = new URL(uri);
const baseUri = `${url.protocol}//${url.host}${url.pathname}`;
if (baseUri !== resourceUri) {
return;
}
for (const name of url.searchParams.keys()) {
if (["cursor", "limit", "verbose"].includes(name) === false) {
throw new Error(`Unknown ${resourceUri} parameter "${name}".`);
}
}
const cursor = url.searchParams.get("cursor");
if (cursor !== null && /^(0|[1-9]\d*)$/.test(cursor) === false) {
throw new Error(`Invalid ${resourceUri} cursor "${cursor}".`);
}
const rawLimit = url.searchParams.get("limit");
if (rawLimit !== null && /^(0|[1-9]\d*)$/.test(rawLimit) === false) {
throw new Error(`Invalid ${resourceUri} limit "${rawLimit}".`);
}
const requestedLimit =
rawLimit === null
? defaultDiscoveryResourcePageSize
: Number.parseInt(rawLimit, 10);
if (requestedLimit < 1) {
throw new Error(`${resourceUri} limit must be at least 1.`);
}
const rawVerbose = url.searchParams.get("verbose");
if (rawVerbose !== null && rawVerbose !== "true" && rawVerbose !== "false") {
throw new Error(`${resourceUri} verbose must be true or false.`);
}
return {
offset: cursor === null ? 0 : Number.parseInt(cursor, 10),
limit: Math.min(requestedLimit, maxDiscoveryResourcePageSize),
verbose: rawVerbose === "true",
};
};
const paginateDiscoveryResource = (
items: readonly unknown[],
input: NonNullable<ReturnType<typeof getDiscoveryResourceInput>>
) => {
const page = items.slice(input.offset, input.offset + input.limit);
return {
total: items.length,
returnedCount: page.length,
nextCursor:
input.offset + page.length < items.length
? String(input.offset + page.length)
: undefined,
page,
};
};
const getMoreTools = (
brief: string,
toolNames: readonly string[],
tools: readonly ProjectSessionMcpTool[]
) => {
const { tools: exactTools, missingTools } = getExactToolSelection(
toolNames,
tools
);
const matchedTools =
toolNames.length > 0 ? exactTools : getMatchingTools(brief, tools);
const limitedTools = matchedTools.slice(0, 12);
return {
usage:
'Prefer { tools: ["exact-tool-name"] } for precise details. Brief search is capped to avoid oversized responses; refine the brief or pass exact tool names when omittedCount is greater than 0.',
brief,
requestedTools: toolNames,
missingTools,
count: matchedTools.length,
omittedCount: Math.max(0, matchedTools.length - limitedTools.length),
tools: limitedTools.map(serializeToolDetails),
};
};
const readOnlySessionTools = new Set([
"meta.index",
"meta.guide",
"meta.get-more-tools",
"status",
"components.summary",
"components.list",
"components.coverage-plan",
"components.coverage-status",
"components.find",
"components.search",
"components.get",
"templates.list",
"templates.get",
"preview.status",
]);
const toolAliases = new Map([
["get-component-coverage-plan", "components.coverage-plan"],
["meta.get_more_tools", "meta.get-more-tools"],
]);
const createToolNameIndex = (tools: readonly ProjectSessionMcpTool[]) => {
const toolByAcceptedName = new Map(
tools.map((tool) => [tool.name, tool] as const)
);
const canonicalNamesByUnderscoredName = new Map<string, string[]>();
for (const tool of tools) {
const underscoredName = toUnderscoredToolName(tool.name);
const canonicalNames =
canonicalNamesByUnderscoredName.get(underscoredName) ?? [];
canonicalNames.push(tool.name);
canonicalNamesByUnderscoredName.set(underscoredName, canonicalNames);
}
for (const [
underscoredName,
canonicalNames,
] of canonicalNamesByUnderscoredName) {
if (
canonicalNames.length === 1 &&
toolByAcceptedName.has(underscoredName) === false
) {
const tool = toolByAcceptedName.get(canonicalNames[0] ?? "");
if (tool !== undefined) {
toolByAcceptedName.set(underscoredName, tool);
}
}
}
const getAcceptedName = (name: string) => toolAliases.get(name) ?? name;
const get = (name: string) => toolByAcceptedName.get(getAcceptedName(name));
return {
canonicalNamesByUnderscoredName,
get,
resolve: (name: string) => get(name)?.name ?? getAcceptedName(name),
};
};
const getUnknownToolMessage = (
requestedName: string,
tools: readonly ProjectSessionMcpTool[]
) => {
const normalizedRequestedName = toUnderscoredToolName(
requestedName.toLowerCase()
);
const suggestions = tools
.map((tool) => ({
name: tool.name,
distance: getLevenshteinDistance(
normalizedRequestedName,
toUnderscoredToolName(tool.name.toLowerCase())
),
}))
.filter(
({ distance }) =>
distance <= Math.max(2, Math.floor(normalizedRequestedName.length / 3))
)
.sort(
(left, right) =>
left.distance - right.distance || left.name.localeCompare(right.name)
)
.slice(0, 3)
.map(({ name }) => name);
const suggestion =
suggestions.length === 0
? ""
: ` Did you mean ${suggestions.map((name) => `"${name}"`).join(", ")}?`;
return `Unknown MCP tool "${requestedName}".${suggestion} Use meta.index to list available tools.`;
};
export const isReadOnlyProjectSessionMcpTool = (tool: ProjectSessionMcpTool) =>
tool.annotations.method === "query" ||
(tool.annotations.method === "session" &&
readOnlySessionTools.has(tool.name));
export const isReadOnlyProjectSessionMcpToolCall = (
name: string,
tools: readonly ProjectSessionMcpTool[]
) => {
const tool = createToolNameIndex(tools).get(name);
return tool !== undefined && isReadOnlyProjectSessionMcpTool(tool);
};
const sdkScalarSchemaKeys = new Set([
"type",
"enum",
"const",
"format",
"default",
"minimum",
"maximum",
"exclusiveMinimum",
"exclusiveMaximum",
"multipleOf",
"minLength",
"maxLength",
"pattern",
"minItems",
"maxItems",
"uniqueItems",
]);
const sdkDetailedOptionalSchemaProperties = new Set(["confirmationToken"]);
const isSdkBooleanSchemaProperty = (value: InputJsonSchemaValue) =>
typeof value !== "boolean" && value.type === "boolean";
const getSdkSchemaProperty = (
value: InputJsonSchemaValue,
preserveRequiredShape = false
): InputJsonSchemaValue => {
if (typeof value === "boolean") {
return value;
}
const result: InputJsonSchema = Object.fromEntries(
Object.entries(value).filter(([key]) => sdkScalarSchemaKeys.has(key))
);
if (value.items !== undefined) {
result.items = getSdkSchemaProperty(value.items, preserveRequiredShape);
}
if (
preserveRequiredShape &&
Array.isArray(value.required) &&
value.required.length > 0
) {
result.required = value.required;
const required = new Set(value.required);
const properties = Object.fromEntries(
Object.entries(value.properties ?? {}).flatMap(([name, property]) =>
required.has(name)
? [[name, getSdkSchemaProperty(property)] as const]
: []
)
);
if (Object.keys(properties).length > 0) {
result.properties = properties;
}
}
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"] as const) {
const branches = value[key];
if (Array.isArray(branches)) {
result[key] = branches.map((branch) =>
getSdkSchemaProperty(branch, preserveRequiredShape)
);
}
}
return result;
};
const getSdkInputSchema = (
schema: ProjectSessionMcpInputSchema,
includeOptionalProperties: boolean
): ProjectSessionMcpInputSchema => {
const required = new Set(schema.required ?? []);
const properties = Object.fromEntries(
Object.entries(schema.properties ?? {}).flatMap(([name, value]) =>
required.has(name) ||
includeOptionalProperties ||
sdkDetailedOptionalSchemaProperties.has(name) ||
isSdkBooleanSchemaProperty(value)
? [[name, getSdkSchemaProperty(value)]]
: []
)
);
return {
type: "object",
additionalProperties:
schema.additionalProperties === undefined
? false
: getSdkSchemaProperty(schema.additionalProperties),
...(Object.keys(properties).length === 0 ? {} : { properties }),
...(required.size === 0 ? {} : { required: [...required] }),
...Object.fromEntries(
(["allOf", "anyOf", "oneOf"] as const).flatMap((key) => {
const branches = schema[key];
return Array.isArray(branches)
? [
[
key,
branches.map((branch) => getSdkSchemaProperty(branch, true)),
] as const,
]
: [];
})
),
};
};
const sdkDetailedInputToolNames = new Set([
"meta.index",
"meta.guide",
"meta.get-more-tools",
"workflow.next",
]);
const getSdkToolAnnotations = (tool: ProjectSessionMcpTool) => {
const readOnly = isReadOnlyProjectSessionMcpTool(tool);
const annotations: NonNullable<SdkTool["annotations"]> = {
...(readOnly ? { readOnlyHint: true } : {}),
...(readOnly === false && tool.annotations.requiresConfirm === false
? { destructiveHint: false }
: {}),
...(tool.annotations.serverOnly ? {} : { openWorldHint: false }),
};
return Object.keys(annotations).length === 0 ? undefined : annotations;
};
const toSdkTool = (tool: ProjectSessionMcpTool): SdkTool => {
const annotations = getSdkToolAnnotations(tool);
return {
name: tool.name,
description: tool.description,
inputSchema: getSdkInputSchema(
tool.inputSchema,
sdkDetailedInputToolNames.has(tool.name)
),
...(annotations === undefined ? {} : { annotations }),
};
};
export const listProjectSessionMcpResources =
(): ProjectSessionMcpResource[] => [
{
uri: "webstudio://project/status",
name: "ProjectSession status",
description:
"Current local ProjectSession status and namespace metadata.",
mimeType: "application/json",
},
{
uri: "webstudio://project/tools-overview",
name: "Webstudio operation tools overview",
description:
"Small operation overview grouped by capability area. Use before paging through the tool catalog.",
mimeType: "application/json",
},
{
uri: "webstudio://project/tools",
name: "Webstudio operation tools",
description:
"Bounded tool catalog. Supports cursor, limit (maximum 50), and verbose query parameters.",
mimeType: "application/json",
},
{
uri: "webstudio://project/components-overview",
name: "Webstudio components overview",
description:
"Small component overview with namespace and category counts. Use before paging through the component catalog.",
mimeType: "application/json",
},
{
uri: "webstudio://project/components",
name: "Webstudio components",
description:
"Bounded component catalog. Supports cursor, limit (maximum 50), and verbose query parameters.",
mimeType: "application/json",
},
{
uri: "webstudio://project/guide",
name: "Webstudio MCP guide",
description:
"Concise model-facing guide for discovering and choosing Webstudio MCP tools.",
mimeType: "application/json",
},
{
uri: "webstudio://project/expressions",
name: "Webstudio expressions",
description:
"Model-facing reference for expression syntax, scope, supported methods, bindings, Collections, and verification.",
mimeType: "text/markdown",
},
{
uri: "webstudio://project/accessibility-review",
name: "Webstudio accessibility review",
description:
"Model-facing workflow for evidence-based accessibility reviews using Webstudio MCP tools and screenshots.",
mimeType: "text/markdown",
},
];
const destructiveConfirmationTtlMs = 5 * 60 * 1000;
const getDestructivePlanSummary = (
envelope: ProjectSessionEnvelope
): DestructiveConfirmation["summary"] => {
const changes = envelope.transaction?.payload ?? [];
const patches = changes.flatMap(({ patches }) => patches);
const patchOperations: Record<string, number> = {};
for (const patch of patches) {
patchOperations[patch.op] = (patchOperations[patch.op] ?? 0) + 1;
}
return {
namespaces: [...new Set(changes.map(({ namespace }) => namespace))],
changeCount: changes.length,
patchCount: patches.length,
patchOperations,
};
};
const maxMcpStyleKeyResults = 20;
const compactMcpOperationResult = (result: unknown) => {
if (isPlainRecord(result) === false) {
return result;
}
const styleKeys = result.styleKeys;
if (
Array.isArray(styleKeys) === false ||
styleKeys.length <= maxMcpStyleKeyResults
) {
return result;
}
return {
...result,
styleKeys: styleKeys.slice(0, maxMcpStyleKeyResults),
styleKeyCount: styleKeys.length,
styleKeysTruncated: true,
};
};
const toCallResult = (
envelope: Parameters<typeof serializeProjectSessionMeta>[0],
options: {
verboseSession?: boolean;
error?: McpStructuredError;
next?: string[];
confirmation?: DestructiveConfirmation;
} = {}
): ProjectSessionMcpToolResult => {
const meta = {
session: serializeProjectSessionMeta(envelope, {
verbose: options.verboseSession,
}),
...(options.next === undefined ? {} : { next: options.next }),
...(options.confirmation === undefined
? {}
: { confirmation: options.confirmation }),
};
const structuredContent: ProjectSessionMcpStructuredContent =
options.error === undefined
? {
ok: true,
data: compactMcpOperationResult(envelope.result),
meta,
}
: {
ok: false,
data: compactMcpOperationResult(envelope.result),
error: options.error,
meta,
};
return {
content: [
{
type: "text",
text: JSON.stringify(structuredContent),
},
],
structuredContent,
...(options.error === undefined ? {} : { isError: true }),
};
};
const executeDestructiveMcpOperation = async <Command extends string>({
command,
input,
dryRun,
confirmDestructive,
confirmationToken,
executeOperation,
}: {
command: Command;
input: unknown;
dryRun: boolean;
confirmDestructive: boolean;
confirmationToken?: string;
executeOperation: ExecuteMcpOperation<Command>;
}): Promise<[ProjectSessionEnvelope, ProjectSessionMcpToolResult?]> => {
const plannedEnvelope = await executeOperation({
command,
input,
dryRun: true,
});
if (plannedEnvelope.transaction === undefined) {
return [plannedEnvelope, toCallResult(plannedEnvelope)];
}
const confirmationPayload = {
operation: command,
input,
projectId: plannedEnvelope.projectId,
buildId: plannedEnvelope.buildId,
version: plannedEnvelope.version,
payload: plannedEnvelope.transaction.payload,
};
const confirmation = async (): Promise<DestructiveConfirmation> => {
const { token, expiresAt } = await createConfirmationToken(
confirmationPayload,
destructiveConfirmationTtlMs
);
return {
required: true,
operation: command,
token,
expiresAt: new Date(expiresAt).toISOString(),
summary: getDestructivePlanSummary(plannedEnvelope),
};
};
if (dryRun) {
return [
plannedEnvelope,
toCallResult(plannedEnvelope, {
confirmation: await confirmation(),
next: [
"Review the planned result and transaction. To commit the unchanged destructive operation, retry with confirmDestructive: true and this confirmationToken before it expires.",
],
}),
];
}
const invalidReason = confirmDestructive
? await getConfirmationTokenInvalidReason(
confirmationToken,
confirmationPayload
)
: undefined;
const isConfirmed = confirmDestructive && invalidReason === undefined;
if (isConfirmed === false) {
const message =
"Review the planned destructive mutation, then retry the unchanged call with confirmDestructive: true and the returned confirmationToken before it expires.";
return [
plannedEnvelope,
toCallResult(plannedEnvelope, {
error: {
code: confirmDestructive
? "DESTRUCTIVE_CONFIRMATION_INVALID"
: "DESTRUCTIVE_CONFIRMATION_REQUIRED",
message,
...(invalidReason === undefined
? {}
: {
issues: [
{
code: `DESTRUCTIVE_CONFIRMATION_${invalidReason.toUpperCase()}`,
path: ["confirmationToken"],
message,
constraint: "unchanged_destructive_plan",
},
],
}),
},
confirmation: await confirmation(),
next: [
"Do not retry blindly. Review meta.session.transaction and meta.confirmation.summary, ask the user to confirm, then retry the unchanged operation with confirmDestructive: true and meta.confirmation.token.",
],
}),
];
}
return [await executeOperation({ command, input, dryRun: false })];
};
const getRenderedAuditError = (
envelope: Parameters<typeof serializeProjectSessionMeta>[0],
rendered: boolean
) => {
if (rendered === false || isRecord(envelope.result) === false) {
return undefined;
}
const state = envelope.result.renderedState;
if (state === "complete" || state === "confirmation-required") {
return undefined;
}
return state === "failed"
? {
code: "RENDERED_AUDIT_FAILED",
message:
"The static audit completed, but the requested rendered audit completed no rendered checks.",
}
: state === "partial"
? {
code: "RENDERED_AUDIT_PARTIAL",
message:
"The static audit completed, but some requested rendered checks failed.",
}
: undefined;
};
const toResourceContent = (
envelope: Parameters<typeof serializeProjectSessionMeta>[0]
) => ({
data: envelope.result,
meta: {
session: serializeProjectSessionMeta(envelope),
},
});
const builderNamespaceSet = new Set<string>(builderNamespaces);
const isBuilderNamespace = (value: unknown): value is BuilderNamespace =>
typeof value === "string" && builderNamespaceSet.has(value);
const getRefreshNamespaces = (input: unknown): readonly BuilderNamespace[] => {
const namespaces =
typeof input === "object" && input !== null && "namespaces" in input
? (input as { namespaces?: unknown }).namespaces
: undefined;
if (namespaces === undefined) {
return builderNamespaces;
}
if (Array.isArray(namespaces) === false) {
throw new Error("refresh namespaces must be an array.");
}
const result: BuilderNamespace[] = [];
for (const namespace of namespaces) {
if (isBuilderNamespace(namespace) === false) {
throw new Error(`Unknown ProjectSession namespace "${namespace}".`);
}
result.push(namespace);
}
return result;
};
const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {
if (isRecord(input) === false) {
throw new Error("screenshot input must be an object.");
}
if ("host" in input || "port" in input) {
throw new Error(
"screenshot does not accept host or port. The MCP runner selects an available local address and returns its URL."
);
}
const url =
typeof input.url === "string" && input.url.length > 0
? input.url
: undefined;
const baseUrl =
typeof input.baseUrl === "string" && input.baseUrl.length > 0
? input.baseUrl
: undefined;
const path =
typeof input.path === "string" && input.path.length > 0
? input.path
: undefined;
if (url === undefined && path === undefined) {
throw new Error("screenshot requires url or path.");
}
if (url !== undefined && (path !== undefined || baseUrl !== undefined)) {
throw new Error("screenshot accepts either url or path/baseUrl, not both.");
}
if (baseUrl !== undefined && path === undefined) {
throw new Error("screenshot baseUrl requires path.");
}
const viewport = isRecord(input.viewport) ? input.viewport : {};
const width =
typeof viewport.width === "number" && Number.isInteger(viewport.width)
? viewport.width
: 1440;
const height =
typeof viewport.height === "number" && Number.isInteger(viewport.height)
? viewport.height
: 900;
if (width <= 0 || height <= 0) {
throw new Error("screenshot viewport width and height must be positive.");
}
const browser = input.browser === undefined ? "auto" : input.browser;
if (isScreenshotBrowser(browser) === false) {
throw new Error(
"screenshot browser must be auto, chromium, chrome, edge, or brave."
);
}
const waitUntil = input.waitUntil === undefined ? undefined : input.waitUntil;
if (waitUntil !== undefined && isScreenshotWaitUntil(waitUntil) === false) {
throw new Error(
"screenshot waitUntil must be commit, domcontentloaded, load, or networkidle."
);
}
const waitForTimeout = input.waitForTimeout;
if (
waitForTimeout !== undefined &&
(typeof waitForTimeout !== "number" ||
Number.isInteger(waitForTimeout) === false ||
waitForTimeout < 0)
) {
throw new Error(
"screenshot waitForTimeout must be a non-negative integer."
);
}
const timeout = input.timeout;
if (
timeout !== undefined &&
(typeof timeout !== "number" ||
Number.isInteger(timeout) === false ||
timeout <= 0)
) {
throw new Error("screenshot timeout must be a positive integer.");
}
const waitForSelector = input.waitForSelector;
if (waitForSelector !== undefined) {
if (typeof waitForSelector !== "string" || waitForSelector.length === 0) {
throw new Error("screenshot waitForSelector must be a non-empty string.");
}
}
if (
input.waitForFonts !== undefined &&
typeof input.waitForFonts !== "boolean"
) {
throw new Error("screenshot waitForFonts must be a boolean.");
}
const source = input.source === undefined ? undefined : input.source;
if (source !== undefined && isProjectSessionPreviewSource(source) === false) {
throw new Error("screenshot source must be local or session.");
}
const mode = input.mode === undefined ? undefined : input.mode;
if (mode !== undefined && isProjectSessionPreviewMode(mode) === false) {
throw new Error("screenshot mode must be iterative or production.");
}
const imageDomains = input.imageDomains;
if (
imageDomains !== undefined &&
(Array.isArray(imageDomains) === false ||
imageDomains.some(
(domain) =>
typeof domain !== "string" ||
/^[a-z0-9.-]+(?::\d+)?$/i.test(domain) === false
))
) {
throw new Error(
"screenshot imageDomains must contain hostnames without a protocol or path."
);
}
if (baseUrl !== undefined) {
try {
new URL(baseUrl);
} catch {
throw new Error("screenshot baseUrl must be an absolute URL.");
}
if (
source !== undefined ||
mode !== undefined ||
imageDomains !== undefined
) {
throw new Error(
"screenshot baseUrl uses an existing preview/site and cannot be combined with source, mode, or imageDomains."
);
}
}
return {
url,
baseUrl,
path,
output: typeof input.output === "string" ? input.output : undefined,
imageDomains,
source,
mode,
viewport: { width, height },
fullPage: input.fullPage === true,
includeImageMetrics: input.includeImageMetrics === true,
includeResourceMetrics: input.includeResourceMetrics === true,
includeContrastMetrics: input.includeContrastMetrics === true,
browser,
browserPath:
typeof input.browserPath === "string" ? input.browserPath : undefined,
waitUntil,
waitForSelector,
waitForFonts: input.waitForFonts,
waitForTimeout,
timeout,
};
};
const getResponsiveScreenshotInputs = (
input: unknown
): ProjectSessionScreenshotInput[] => {
if (isRecord(input) === false) {
throw new Error("screenshot.responsive input must be an object.");
}
if (
Array.isArray(input.viewports) === false ||
input.viewports.length === 0 ||
input.viewports.length > 8
) {
throw new Error(
"screenshot.responsive input.viewports must contain between 1 and 8 viewport objects."
);
}
return input.viewports.map((viewport, index) => {
if (
isRecord(viewport) === false ||
typeof viewport.width !== "number" ||
Number.isInteger(viewport.width) === false ||
viewport.width <= 0 ||
typeof viewport.height !== "number" ||
Number.isInteger(viewport.height) === false ||
viewport.height <= 0
) {
throw new Error(
`screenshot.responsive input.viewports.${index} must contain positive integer width and height.`
);
}
return getScreenshotInput({ ...input, viewport });
});
};
const getScreenshotDiffInput = (
input: unknown
): ProjectSessionScreenshotDiffInput => {
if (isRecord(input) === false) {
throw new Error("screenshot.diff input must be an object.");
}
const baselinePath =
typeof input.baselinePath === "string" && input.baselinePath.length > 0
? input.baselinePath
: undefined;
const currentPath =
typeof input.currentPath === "string" && input.currentPath.length > 0
? input.currentPath
: undefined;
if (baselinePath === undefined || currentPath === undefined) {
throw new Error("screenshot.diff requires baselinePath and currentPath.");
}
const threshold =
typeof input.threshold === "number" ? input.threshold : undefined;
if (
threshold !== undefined &&
(Number.isFinite(threshold) === false || threshold < 0 || threshold > 1)
) {
throw new Error("screenshot.diff threshold must be between 0 and 1.");
}
const ignoreTopNormalizedY =
typeof input.ignoreTopNormalizedY === "number"
? input.ignoreTopNormalizedY
: undefined;
if (
ignoreTopNormalizedY !== undefined &&
(Number.isFinite(ignoreTopNormalizedY) === false ||
ignoreTopNormalizedY < 0 ||
ignoreTopNormalizedY > 1)
) {
throw new Error(
"screenshot.diff ignoreTopNormalizedY must be between 0 and 1."
);
}
const expectedText = input.expectedText;
if (
expectedText !== undefined &&
(Array.isArray(expectedText) === false ||
expectedText.length === 0 ||
expectedText.some(
(value) => typeof value !== "string" || value.trim().length === 0
))
) {
throw new Error(
"screenshot.diff expectedText must be a non-empty array of non-empty strings."
);
}
const expectedVisual = input.expectedVisual;
if (
expectedVisual !== undefined &&
isScreenshotVisualExpectation(expectedVisual) === false
) {
throw new Error(
"screenshot.diff expectedVisual must include valid maxMismatchPercentage (0-100), minChangedRegions, or maxChangedRegions values."
);
}
return {
baselinePath,
currentPath,
outputDir:
typeof input.outputDir === "string" && input.outputDir.length > 0
? input.outputDir
: path.dirname(currentPath),
threshold,
ignoreTopNormalizedY,
expectedText,
expectedVisual,
};
};
const assertInstallOcrConfirmed = (input: unknown) => {
if (isRecord(input) === false) {
throw new Error("vision.install-ocr input must be an object.");
}
if (input.confirm !== true) {
throw new Error(
"vision.install-ocr requires confirm: true after explicit user consent."
);
}
};
const getPreviewInput = (input: unknown): ProjectSessionPreviewInput => {
if (isRecord(input) === false) {
return {};
}
if ("host" in input || "port" in input) {
throw new Error(
"preview.start does not accept host or port. The MCP runner selects an available local address and returns its URL."
);
}
const source = input.source === undefined ? undefined : input.source;
if (source !== undefined && isProjectSessionPreviewSource(source) === false) {
throw new Error("preview source must be local or session.");
}
const mode = input.mode === undefined ? undefined : input.mode;
if (mode !== undefined && isProjectSessionPreviewMode(mode) === false) {
throw new Error("preview mode must be iterative or production.");
}
const imageDomains = input.imageDomains;
if (
imageDomains !== undefined &&
(Array.isArray(imageDomains) === false ||
imageDomains.some(
(domain) =>
typeof domain !== "string" ||
/^[a-z0-9.-]+(?::\d+)?$/i.test(domain) === false
))
) {
throw new Error(
"preview imageDomains must contain hostnames without a protocol or path."
);
}
return {
source,
mode,
imageDomains,
};
};
const getPreviewSubmitFormInput = (
input: unknown
): ProjectSessionPreviewSubmitFormInput =>
z
.object({
path: z.string().min(1),
selector: z.string().min(1).max(500),
values: z
.array(
z
.object({
name: z.string().min(1),
value: z.string().optional(),
file: z
.object({
name: z.string().min(1),
base64: z.string().max(1_400_000),
type: z.string().optional(),
})
.strict()
.optional(),
})
.strict()
.refine(
(value) =>
(value.value === undefined) !== (value.file === undefined)
)
)
.max(100),
submitter: z.string().min(1).max(500).optional(),
timeout: z.number().int().min(1).max(60_000).optional(),
})
.strict()
.parse(input);
const slowOperationConfirmationTtlMs = 5 * 60 * 1000;
const getProductionPreviewPreflight = async (input: unknown) => {
if (isRecord(input) === false || input.mode !== "production") {
return;
}
const previewInput = getPreviewInput(input);
const confirmationPayload = {
operation: "production preview build",
input: previewInput,
maxDurationMs:
typeof input.maxDurationMs === "number" ? input.maxDurationMs : undefined,
};
if (
input.confirmSlow === true &&
(await validateConfirmationToken(
typeof input.confirmationToken === "string"
? input.confirmationToken
: undefined,
confirmationPayload
))
) {
return;
}
const { token } = await createConfirmationToken(
confirmationPayload,
slowOperationConfirmationTtlMs
);
const maxDurationMs =
typeof input.maxDurationMs === "number" ? input.maxDurationMs : undefined;
return {
running: false,
mode: "production" as const,
confirmationRequired: true,
operation: "production preview build",
estimatedDuration: "30–60 seconds",
reason:
maxDurationMs !== undefined && maxDurationMs < 30_000
? `A full production preview cannot reasonably finish within the ${maxDurationMs}ms budget.`
: "A full production preview builds complete rendered output and is expected to exceed 10 seconds.",
confirmationToken: token,
fasterAlternative: {
operation: "targeted route validation",
estimatedDuration: "2–5 seconds",
limitations: "Does not visually inspect layout.",
},
};
};
const getImportInput = (input: unknown): ProjectSessionImportInput => {
if (isRecord(input) === false) {
throw new Error("import input must be an object.");
}
if (typeof input.to !== "string" || input.to.length === 0) {
throw new Error("import requires destination share link in to.");
}
const assetsDir =
typeof input.assetsDir === "string" && input.assetsDir.length > 0
? input.assetsDir
: undefined;
return {
to: input.to,
assetsDir,
ignoreVersionCheck: input.ignoreVersionCheck === true,
skipAssets: input.skipAssets === true,
};
};
const getDownloadAssetInput = (
input: unknown
): ProjectSessionDownloadAssetInput => {
if (isRecord(input) === false) {
throw new Error("download-asset input must be an object.");
}
if (typeof input.assetId !== "string" || input.assetId.length === 0) {
throw new Error("download-asset requires assetId.");
}
return {
assetId: input.assetId,
assetsDir:
typeof input.assetsDir === "string" && input.assetsDir.length > 0
? input.assetsDir
: undefined,
};
};
type ProjectSessionMcpCoreOptions<Command extends string> = {
operations: readonly (PublicMcpOperation & { command: Command })[];
createProjectSession: CreateProjectSession;
executeOperation: ExecuteMcpOperation<Command>;
importProject?: ImportProject;
downloadAsset?: DownloadAsset;
captureScreenshot?: CaptureScreenshot;
capturePageScreenshots?: CapturePageScreenshots;
diffScreenshots?: DiffScreenshots;
installOcr?: InstallOcr;
startPreview?: StartPreview;
submitPreviewForm?: SubmitPreviewForm;
simulateForm?: SimulateForm;
getPreviewStatus?: GetPreviewStatus;
stopPreview?: StopPreview;
guidance?: ProjectSessionMcpGuidance;
reportToolProgress?: (message: string) => void;
storeRenderedAuditArtifacts?: (
manifest: RenderedAuditArtifactManifest
) => Promise<string>;
restorePoints?: ProjectSessionRestorePointHandlers;
onProjectSessionChange?: () => void;
};
type ProjectSessionRestorePointHandlers = {
create: (input: {
name: string;
}) => Promise<ProjectSessionRestorePointSummary>;
list: () => Promise<{ points: ProjectSessionRestorePointSummary[] }>;
delete: (input: { id: string }) => Promise<{ deleted: boolean }>;
revert: (
input: { id: string },
options: { dryRun: boolean }
) => Promise<ProjectSessionEnvelope>;
};
export const createProjectSessionMcpCore = <Command extends string = string>({
operations,
createProjectSession,
executeOperation,
importProject,
downloadAsset,
captureScreenshot,
capturePageScreenshots,
diffScreenshots,
installOcr,
startPreview,
submitPreviewForm,
simulateForm,
getPreviewStatus,
stopPreview,
guidance,
reportToolProgress,
storeRenderedAuditArtifacts,
restorePoints,
onProjectSessionChange,
}: ProjectSessionMcpCoreOptions<Command>) => {
let session: ReturnType<CreateProjectSession> | undefined;
let pendingCheckpoint: ProjectSessionMcpCheckpoint | undefined;
const toCheckpointedMetaResult = (
tool: string,
data: unknown
): ProjectSessionMcpToolResult => {
pendingCheckpoint = getProjectSessionMcpCheckpoint(tool, data);
return toMetaResult(data);
};
const operationByCommand = new Map(
operations.map((operation) => [operation.command, operation])
);
const tools = listProjectSessionMcpTools(operations, {
includeImport: importProject !== undefined,
includeDownloadAsset: downloadAsset !== undefined,
includeScreenshot: captureScreenshot !== undefined,
includeResponsiveScreenshot: capturePageScreenshots !== undefined,
includeScreenshotDiff: diffScreenshots !== undefined,
includeInstallOcr: installOcr !== undefined,
includePreview:
startPreview !== undefined && getPreviewStatus !== undefined,
includePreviewSubmitForm: submitPreviewForm !== undefined,
includeSimulateForm: simulateForm !== undefined,
includeRestorePoints: restorePoints !== undefined,
});
const listTools = () => [...tools];
const toolNameIndex = createToolNameIndex(tools);
const getSession = () => {
session ??= createProjectSession();
return session;
};
const executeRead = async (command: string, input: unknown) => {
if (operationByCommand.has(command as Command) === false) {
throw new Error(`Rendered audit requires the ${command} operation.`);
}
return await executeOperation({
command: command as Command,
input,
dryRun: false,
});
};
const callContextBundle = async ({
toolName,
operationId,
calls,
getResult,
}: {
toolName: string;
operationId: string;
calls: readonly {
command: string;
input: Record<string, unknown>;
resultKey?: string;
}[];
getResult: (results: ReadonlyMap<string, unknown>) => unknown;
}) => {
const envelopes: Array<{
command: string;
envelope: ProjectSessionEnvelope;
}> = [];
for (const { command, input, resultKey } of calls) {
if (operationByCommand.has(command as Command) === false) {
throw new Error(`${toolName} requires the ${command} operation.`);
}
envelopes.push({
command: resultKey ?? command,
envelope: await executeOperation({
command: command as Command,
input,
dryRun: false,
}),
});
}
const lastEnvelope = envelopes.at(-1)?.envelope;
if (lastEnvelope === undefined) {
throw new Error(`${toolName} produced no results.`);
}
const resultByCommand = new Map(
envelopes.map(({ command, envelope }) => [command, envelope.result])
);
const mergeNamespaces = (
key: keyof ProjectSessionEnvelope["namespaces"]
) => [
...new Set(envelopes.flatMap(({ envelope }) => envelope.namespaces[key])),
];
return toCallResult({
...lastEnvelope,
operationId,
result: getResult(resultByCommand),
namespaces: {
read: mergeNamespaces("read"),
write: mergeNamespaces("write"),
invalidated: mergeNamespaces("invalidated"),
missing: mergeNamespaces("missing"),
},
diagnostics: envelopes.flatMap(({ envelope }) => envelope.diagnostics),
});
};
return {
listTools,
listResources: listProjectSessionMcpResources,
async readResource({ uri }: { uri: string }) {
if (uri === "webstudio://project/tools-overview") {
return {
contents: [
{
uri,
mimeType: "application/json",
text: JSON.stringify(getToolCatalogOverview(listTools())),
},
],
};
}
const toolsInput = getDiscoveryResourceInput(
uri,
"webstudio://project/tools"
);
if (toolsInput !== undefined) {
const tools = listTools();
const serializedTools = toolsInput.verbose
? tools.map(serializeToolDetails)
: tools.map(serializeCompactTool);
const { page, ...pagination } = paginateDiscoveryResource(
serializedTools,
toolsInput
);
return {
contents: [
{
uri,
mimeType: "application/json",
text: JSON.stringify({
usage:
"Use cursor to continue. Pass verbose=true for schemas and examples for this page only.",
detail: toolsInput.verbose ? "verbose" : "compact",
...pagination,
tools: page,
}),
},
],
};
}
if (uri === "webstudio://project/components-overview") {
return {
contents: [
{
uri,
mimeType: "application/json",
text: JSON.stringify(getComponentCatalogOverview()),
},
],
};
}
const componentsInput = getDiscoveryResourceInput(
uri,
"webstudio://project/components"
);
if (componentsInput !== undefined) {
const compactCatalog = getComponentCatalogOverview();
const items = componentsInput.verbose
? getComponentCatalog().components
: getCompactComponentCatalogEntries();
const { page, ...pagination } = paginateDiscoveryResource(
items,
componentsInput
);
return {
contents: [
{
uri,
mimeType: "application/json",
text: JSON.stringify({
source: "@webstudio-is/sdk-components-registry/metas",
usage:
"Use cursor to continue. Pass verbose=true for props, states, and composition details for this page only.",
detail: componentsInput.verbose ? "verbose" : "compact",
namespaces: compactCatalog.namespaces,
categories: compactCatalog.categories,
...pagination,
components: page,
}),
},
],
};
}
if (uri === "webstudio://project/guide") {
return {
contents: [
{
uri,
mimeType: "application/json",
text: JSON.stringify(getMetaIndex(listTools(), guidance)),
},
],
};
}
if (uri === "webstudio://project/expressions") {
return {
contents: [
{
uri,
mimeType: "text/markdown",
text: expressionsGuide,
},
],
};
}
if (uri === "webstudio://project/accessibility-review") {
return {
contents: [
{
uri,
mimeType: "text/markdown",
text: readProjectBuildDoc("accessibility-review"),
},
],
};
}
if (uri === "webstudio://project/status") {
const session = getSession();
return {
contents: [
{
uri,
mimeType: "application/json",
text: JSON.stringify(
toResourceContent(await session.initialize())
),
},
],
};
}
throw new Error(`Unknown MCP resource "${uri}".`);
},
async callTool({
name,
input = {},
dryRun = false,
signal,
}: {
name: string;
input?: unknown;
dryRun?: boolean;
signal?: AbortSignal;
}): Promise<ProjectSessionMcpToolResult> {
const requestedName = name;
name = toolNameIndex.resolve(name);
if (name === "checkpoint.ack") {
if (
isRecord(input) === false ||
input.reported !== true ||
input.continueAfterReport !== true ||
typeof input.summary !== "string" ||
input.summary.trim().length === 0
) {
throw new Error(
'checkpoint.ack requires {"reported":true,"continueAfterReport":true,"summary":"..."} after the parent/user has seen the checkpoint and continued the task.'
);
}
const nextCommand = pendingCheckpoint?.nextCommand;
pendingCheckpoint = undefined;
return toMetaResult({
acknowledged: true,
summary: input.summary,
nextCommand,
});
}
if (
pendingCheckpoint !== undefined &&
isReadOnlyProjectSessionMcpToolCall(name, listTools()) === false
) {
throw new ProjectSessionMcpCheckpointError(
`CHECKPOINT_REQUIRED: ${pendingCheckpoint.message} Stop now and report the checkpoint to the parent/user. Only after the parent/user continues, call checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"} before calling "${name}".`
);
}
if (name === "meta.index") {
if (
input !== undefined &&
(isPlainRecord(input) === false || Object.keys(input).length > 0)
) {
throw new Error(
'meta.index does not accept input. Call meta.guide with {"brief":"..."} for goal-specific guidance.'
);
}
return toMetaResult(getMetaIndex(listTools(), guidance));
}
if (name === "meta.guide") {
return toMetaResult(
getMetaGuide({
...getMetaGuideInput(input),
tools: listTools(),
guidance,
})
);
}
if (name === "inspect-auth-context") {
if (isPlainRecord(input) === false || Object.keys(input).length > 0) {
throw new Error("inspect-auth-context does not accept input.");
}
return await callContextBundle({
toolName: name,
operationId: "workflow.auth-context",
calls: [
{ command: "get-project-settings", input: {} },
{ command: "list-pages", input: { limit: 50 } },
{ command: "list-resources", input: { limit: 50 } },
{ command: "list-variables", input: { limit: 50 } },
],
getResult: (resultByCommand) => ({
projectSettings: resultByCommand.get("get-project-settings"),
pages: resultByCommand.get("list-pages"),
resources: resultByCommand.get("list-resources"),
variables: resultByCommand.get("list-variables"),
}),
});
}
if (name === "inspect-design-context") {
if (isPlainRecord(input) === false || Object.keys(input).length > 0) {
throw new Error("inspect-design-context does not accept input.");
}
return await callContextBundle({
toolName: name,
operationId: "workflow.design-context",
calls: [
{ command: "list-pages", input: { limit: 50 } },
{ command: "list-breakpoints", input: {} },
{ command: "list-design-tokens", input: { limit: 50 } },
{ command: "list-assets", input: { limit: 50 } },
{ command: "list-variables", input: { limit: 50 } },
],
getResult: (resultByCommand) => ({
pages: resultByCommand.get("list-pages"),
breakpoints: resultByCommand.get("list-breakpoints"),
designTokens: resultByCommand.get("list-design-tokens"),
assets: resultByCommand.get("list-assets"),
variables: resultByCommand.get("list-variables"),
}),
});
}
if (name === "verify-font-assets") {
if (
isPlainRecord(input) === false ||
Array.isArray(input.assetIds) === false ||
input.assetIds.length === 0 ||
input.assetIds.length > 50 ||
input.assetIds.some(
(assetId) => typeof assetId !== "string" || assetId.length === 0
)
) {
throw new Error(
"verify-font-assets requires assetIds with 1 to 50 non-empty strings."
);
}
const assetIds = [...new Set(input.assetIds as string[])];
const projectSession = getSession();
await projectSession.initialize();
await projectSession.refresh(["assets"]);
onProjectSessionChange?.();
return await callContextBundle({
toolName: name,
operationId: "workflow.verify-font-assets",
calls: assetIds.map((assetId) => ({
command: "get-asset",
resultKey: assetId,
input: { assetId },
})),
getResult: (resultByAssetId) => ({
assets: assetIds.map((assetId) => resultByAssetId.get(assetId)),
}),
});
}
if (name === "workflow.next") {
return toCheckpointedMetaResult(name, getWorkflowNext(input));
}
if (name === "meta.get-more-tools") {
const normalizedInput = parseStringifiedJsonInputFields(
input,
toolDetailsInputSchema
);
return toMetaResult(
getMoreTools(
getBrief(normalizedInput, "meta.get-more-tools"),
getToolNamesInput(normalizedInput),
tools
)
);
}
if (name === "components.summary") {
return toMetaResult(getComponentSummary(input));
}
if (name === "components.list") {
return toMetaResult(
listRegistryItems({
input,
toolName: "components.list",
defaultSource: "all",
})
);
}
if (name === "components.coverage-plan") {
const coveragePlan = await getComponentCoveragePlan(input);
return toCheckpointedMetaResult(name, coveragePlan);
}
if (name === "components.coverage-status") {
return toMetaResult(
await getComponentCoverageStatus({
input,
executeOperation: executeOperation as ExecuteMcpOperation,
})
);
}
if (name === "components.coverage-insert-next") {
return toCheckpointedMetaResult(
name,
await getComponentCoverageInsertNext({
input,
executeOperation: executeOperation as ExecuteMcpOperation,
dryRun,
})
);
}
if (name === "components.find") {
return toMetaResult(await findComponents(input));
}
if (name === "components.search") {
return toMetaResult(await findComponents(input, "components.search"));
}
if (name === "components.get") {
return toMetaResult(getComponentDetails(getComponentInput(input)));
}
if (name === "templates.list") {
return toMetaResult(
listRegistryItems({
input,
toolName: "templates.list",
defaultSource: "template",
})
);
}
if (name === "templates.get") {
return toMetaResult(getTemplateDetails(input));
}
if (name === "status") {
const session = getSession();
return toCallResult(await session.initialize(), {
verboseSession: isRecord(input) && input.verbose === true,
});
}
if (name === "refresh") {
const session = getSession();
await session.initialize();
const result = await session.refresh(getRefreshNamespaces(input));
onProjectSessionChange?.();
return toCallResult(result);
}
if (name === "reset-session") {
const session = getSession();
const result = await session.reset();
onProjectSessionChange?.();
return toCallResult(result);
}
if (name === "create-restore-point" && restorePoints !== undefined) {
return toMetaResult(
await restorePoints.create(restorePointCreateInput.parse(input))
);
}
if (name === "list-restore-points" && restorePoints !== undefined) {
return toMetaResult(await restorePoints.list());
}
if (name === "delete-restore-point" && restorePoints !== undefined) {
const { id } = restorePointDeleteInput.parse(input);
return toMetaResult(await restorePoints.delete({ id }));
}
if (name === "revert-to-restore-point" && restorePoints !== undefined) {
const transportInput = getToolCallInput(input, true);
const restoreInput = restorePointRevertInput.parse(
transportInput.input
);
const [envelope, response] = await executeDestructiveMcpOperation({
command: "revert-to-restore-point",
input: restoreInput,
dryRun: dryRun || transportInput.dryRun,
confirmDestructive: transportInput.confirmDestructive,
confirmationToken: transportInput.confirmationToken,
executeOperation: async ({ input, dryRun }) =>
await restorePoints.revert(restorePointRevertInput.parse(input), {
dryRun,
}),
});
return response ?? toCallResult(envelope);
}
if (name === "import" && importProject !== undefined) {
return toMetaResult(await importProject(getImportInput(input)));
}
if (name === "download-asset" && downloadAsset !== undefined) {
return toMetaResult(await downloadAsset(getDownloadAssetInput(input)));
}
if (name === "screenshot" && captureScreenshot !== undefined) {
const screenshotInput = getScreenshotInput(input);
try {
return toMetaResult(
await captureScreenshot(screenshotInput, {
report: (message) => {
reportToolProgress?.(message);
},
})
);
} catch (error) {
const message =
error instanceof Error ? error.message : String(error);
const issues = getValidationIssues(error);
throw Object.assign(
new Error(
`Screenshot capture failed: ${message}. Check preview.status, verify that the route loads, and retry with an installed browser or explicit browserPath.`
),
{
code: "SCREENSHOT_CAPTURE_FAILED",
cause: error,
...(issues === undefined ? {} : { issues }),
}
);
}
}
if (
name === "verify-page-responsive" &&
capturePageScreenshots !== undefined
) {
const auditOperation = operationByCommand.get("audit" as Command);
if (auditOperation === undefined) {
throw new Error(
"verify-page-responsive requires the audit operation."
);
}
const screenshotInputs = getResponsiveScreenshotInputs(input);
const pagePath = screenshotInputs[0]?.path;
if (typeof pagePath !== "string" || pagePath.length === 0) {
throw new Error(
"verify-page-responsive requires a generated route path."
);
}
const screenshots = await capturePageScreenshots(screenshotInputs, {
report: (message) => {
reportToolProgress?.(message);
},
});
const auditEnvelope = await executeOperation({
command: "audit" as Command,
input: getNormalizedOperationInput(auditOperation, { pagePath }),
dryRun: false,
});
return toCallResult({
...auditEnvelope,
operationId: "workflow.verify-page-responsive",
result: { screenshots, audit: auditEnvelope.result },
});
}
if (
name === "screenshot.responsive" &&
capturePageScreenshots !== undefined
) {
return toMetaResult({
screenshots: await capturePageScreenshots(
getResponsiveScreenshotInputs(input),
{
report: (message) => {
reportToolProgress?.(message);
},
}
),
});
}
if (name === "screenshot.diff" && diffScreenshots !== undefined) {
return toMetaResult(
await diffScreenshots(getScreenshotDiffInput(input))
);
}
if (name === "vision.install-ocr" && installOcr !== undefined) {
assertInstallOcrConfirmed(input);
return toMetaResult(await installOcr());
}
if (name === "preview.start" && startPreview !== undefined) {
const preflight = await getProductionPreviewPreflight(input);
if (preflight !== undefined) {
return toMetaResult(preflight);
}
return toMetaResult(
await startPreview(getPreviewInput(input), {
report: (message) => {
reportToolProgress?.(message);
},
})
);
}
if (name === "preview.submit-form" && submitPreviewForm !== undefined) {
return toMetaResult(
await submitPreviewForm(getPreviewSubmitFormInput(input))
);
}
if (name === "forms.simulate-submission" && simulateForm !== undefined) {
const values = z
.object({ name: z.string().min(1), value: z.string() })
.strict();
const parsed = z
.object({
path: z.string().startsWith("/").max(2048),
siteOrigin: z.string().url().max(2048).optional(),
formId: z.string().min(1),
values: z.array(values).max(100),
arrayNames: z.array(z.string().min(1)).max(100).optional(),
})
.strict()
.parse(input);
if (parsed.siteOrigin !== undefined) {
const origin = new URL(parsed.siteOrigin);
if (
origin.protocol !== "https:" ||
origin.username !== "" ||
origin.password !== "" ||
origin.pathname !== "/" ||
origin.search !== "" ||
origin.hash !== ""
) {
throw new Error("siteOrigin must be a bare HTTPS origin.");
}
}
return toMetaResult(await simulateForm(parsed));
}
if (name === "preview.status" && getPreviewStatus !== undefined) {
return toMetaResult(await getPreviewStatus());
}
if (name === "preview.stop" && stopPreview !== undefined) {
return toMetaResult(await stopPreview());
}
if (name === "insert-fragment-verified") {
const insertionOperation = operationByCommand.get(
"insert-fragment" as Command
);
const verificationOperation = operationByCommand.get(
"verify-bindings" as Command
);
if (
insertionOperation === undefined ||
verificationOperation === undefined
) {
throw new Error(
"insert-fragment-verified requires insert-fragment and verify-bindings operations."
);
}
const transportInput = getToolCallInput(input);
if (
isPlainRecord(transportInput.input) === false ||
typeof transportInput.input.pagePath !== "string"
) {
throw new Error(
"insert-fragment-verified requires a pagePath for persisted binding verification."
);
}
const insertionInput = getNormalizedOperationInput(
insertionOperation,
await getInsertFragmentInput(transportInput.input)
);
assertNoDeprecatedWebhookFormInsertion(
"insert-fragment",
insertionInput
);
const verificationInput = getNormalizedOperationInput(
verificationOperation,
{ pagePath: transportInput.input.pagePath, limit: 200 }
);
const compositeDryRun = dryRun || transportInput.dryRun;
const insertionEnvelope = await executeOperation({
command: "insert-fragment" as Command,
input: insertionInput,
dryRun: compositeDryRun,
});
if (compositeDryRun) {
return toCallResult(
{
...insertionEnvelope,
operationId: "workflow.insert-fragment-verified",
result: {
insertion: insertionEnvelope.result,
verification: {
status: "skipped",
reason: "Verification runs only after a committed insertion.",
},
},
},
{
next: [
"Review the planned insertion. Commit it with the same input and dryRun omitted before relying on binding verification.",
],
}
);
}
let verificationEnvelope: ProjectSessionEnvelope;
try {
verificationEnvelope = await executeOperation({
command: "verify-bindings" as Command,
input: verificationInput,
dryRun: false,
});
} catch {
return toCallResult(
{
...insertionEnvelope,
operationId: "workflow.insert-fragment-verified",
result: {
insertion: insertionEnvelope.result,
verification: { status: "failed-after-commit" },
},
},
{
error: {
code: "POST_COMMIT_VERIFICATION_FAILED",
message:
"The fragment was committed, but binding verification could not run. Do not retry the insertion; call verify-bindings separately for the same pagePath.",
},
next: [
"Do not retry insert-fragment-verified. Call verify-bindings separately for the same pagePath and resolve every finding.",
],
}
);
}
const mergeNamespaces = (
key: keyof ProjectSessionEnvelope["namespaces"]
) => [
...new Set([
...insertionEnvelope.namespaces[key],
...verificationEnvelope.namespaces[key],
]),
];
return toCallResult(
{
...verificationEnvelope,
operationId: "workflow.insert-fragment-verified",
result: {
insertion: insertionEnvelope.result,
verification: verificationEnvelope.result,
},
state: {
...verificationEnvelope.state,
committed: insertionEnvelope.state.committed,
},
namespaces: {
read: mergeNamespaces("read"),
write: mergeNamespaces("write"),
invalidated: mergeNamespaces("invalidated"),
missing: mergeNamespaces("missing"),
},
diagnostics: [
...insertionEnvelope.diagnostics,
...verificationEnvelope.diagnostics,
],
},
{
next: [
"Resolve every binding verification finding before previewing.",
"Before reporting completion, run audit for the changed page or project.",
...(startPreview !== undefined && captureScreenshot !== undefined
? [
"Ask whether the user wants visual verification unless they explicitly requested it. If they decline, stop after the binding verification and static audit; if they opt in, start a session preview and capture desktop and mobile screenshots.",
]
: []),
],
}
);
}
const operation = operationByCommand.get(name as Command);
if (operation === undefined) {
throw new Error(getUnknownToolMessage(requestedName, tools));
}
const transportInput = getToolCallInput(input, operation.requiresConfirm);
const toolInput = transportInput.input;
dryRun = dryRun || transportInput.dryRun;
const normalizedInput = await normalizeMcpOperationInput(name, toolInput);
assertNoDeprecatedWebhookFormInsertion(name, normalizedInput);
if (
// Block duplication of a saved, deprecated Webhook Form.
(name === "clone-instance" || name === "duplicate-instance") &&
isRecord(normalizedInput) &&
typeof normalizedInput.sourceInstanceId === "string"
) {
const source = await executeRead("list-instances", {
rootInstanceId: normalizedInput.sourceInstanceId,
component: "WebhookForm",
limit: 1,
});
if (
isRecord(source.result) &&
Array.isArray(source.result.instances) &&
source.result.instances.length > 0
) {
throw new Error(
'Webhook Form is deprecated and cannot be duplicated through MCP. Use component "ResourceForm".'
);
}
}
const isAuditInput = name === "audit" && isRecord(toolInput);
if (
isAuditInput &&
toolInput.rendered !== undefined &&
typeof toolInput.rendered !== "boolean"
) {
throw new Error("audit input.rendered must be a boolean.");
}
if (
isAuditInput &&
toolInput.routeExamples !== undefined &&
(Array.isArray(toolInput.routeExamples) === false ||
toolInput.routeExamples.some(
(example) =>
isRecord(example) === false ||
typeof example.pageId !== "string" ||
example.pageId.length === 0 ||
typeof example.path !== "string" ||
/^\/(?!\/)/.test(example.path) === false ||
example.path.includes(":") ||
example.path.includes("*")
))
) {
throw new Error(
"audit input.routeExamples must contain { pageId, path } objects with concrete paths beginning with one slash."
);
}
const isRenderedAudit = isAuditInput && toolInput.rendered === true;
const renderedOnlyInputFields = [
"confirmLargeRun",
"confirmationToken",
"imageDomains",
"routeExamples",
] as const;
const providedRenderedOnlyInput = renderedOnlyInputFields.find(
(field) => isAuditInput && toolInput[field] !== undefined
);
if (isAuditInput && isRenderedAudit === false) {
if (providedRenderedOnlyInput !== undefined) {
throw new Error(
`audit input.${providedRenderedOnlyInput} requires rendered: true.`
);
}
}
if (
isAuditInput &&
toolInput.confirmLargeRun !== undefined &&
typeof toolInput.confirmLargeRun !== "boolean"
) {
throw new Error("audit input.confirmLargeRun must be a boolean.");
}
if (
isAuditInput &&
toolInput.confirmationToken !== undefined &&
typeof toolInput.confirmationToken !== "string"
) {
throw new Error("audit input.confirmationToken must be a string.");
}
if (
isAuditInput &&
toolInput.imageDomains !== undefined &&
(Array.isArray(toolInput.imageDomains) === false ||
toolInput.imageDomains.some(
(domain) =>
typeof domain !== "string" ||
/^[a-z0-9.-]+(?::\d+)?$/i.test(domain) === false
))
) {
throw new Error(
"audit input.imageDomains must contain hostnames without a protocol or path."
);
}
if (
isRenderedAudit &&
(startPreview === undefined ||
stopPreview === undefined ||
captureScreenshot === undefined)
) {
throw new Error(
"Rendered audit is unavailable because this MCP host does not provide preview and screenshot capabilities."
);
}
if (isRenderedAudit && typeof toolInput.cursor === "string") {
throw new Error(
"Rendered audit cannot be combined with cursor pagination. Run the rendered pass once without cursor."
);
}
const operationInput = getNormalizedOperationInput(
operation,
isAuditInput
? Object.fromEntries(
Object.entries(toolInput).filter(
([key]) =>
key !== "rendered" &&
key !== "confirmLargeRun" &&
key !== "confirmationToken" &&
key !== "imageDomains" &&
key !== "routeExamples"
)
)
: normalizedInput
);
const plannedCopy = deprecatedWebhookFormCopyCommands.has(name)
? await executeOperation({
command: name as Command,
input: operationInput,
dryRun: true,
})
: undefined;
if (plannedCopy !== undefined) {
assertNoDeprecatedWebhookFormCopy(plannedCopy);
}
const [envelope, response] = operation.requiresConfirm
? await executeDestructiveMcpOperation({
command: name as Command,
input: operationInput,
dryRun,
confirmDestructive: transportInput.confirmDestructive,
confirmationToken: transportInput.confirmationToken,
executeOperation,
})
: [
dryRun && plannedCopy !== undefined
? plannedCopy
: await executeOperation({
command: name as Command,
input: operationInput,
dryRun,
}),
];
if (response !== undefined) {
return response;
}
if (name === "audit") {
const auditedEnvelope = await augmentAuditWithRenderedChecks({
envelope,
input:
isRenderedAudit && isRecord(operationInput)
? {
...operationInput,
rendered: true,
...(toolInput.confirmLargeRun === true
? { confirmLargeRun: true }
: {}),
...(typeof toolInput.confirmationToken === "string"
? { confirmationToken: toolInput.confirmationToken }
: {}),
...(Array.isArray(toolInput.imageDomains)
? { imageDomains: toolInput.imageDomains }
: {}),
...(Array.isArray(toolInput.routeExamples)
? { routeExamples: toolInput.routeExamples }
: {}),
}
: operationInput,
executeRead,
startPreview,
stopPreview,
captureScreenshot,
capturePageScreenshots,
reportProgress: reportToolProgress,
storeRenderedAuditArtifacts,
signal,
});
return toCallResult(auditedEnvelope, {
error: getRenderedAuditError(auditedEnvelope, isRenderedAudit),
});
}
const needsBindingVerification = operation.writeNamespaces.some(
(namespace) => bindingVerificationWriteNamespaces.has(namespace)
);
const needsVisualVerification = operation.writeNamespaces.some(
(namespace) => visualVerificationWriteNamespaces.has(namespace)
);
const next = [
...(needsBindingVerification
? [
"After changing props, variables, or resources, run verify-bindings for the changed page or instance and resolve every finding.",
]
: []),
...(needsVisualVerification
? [
"For a small fixed-value or reference correction, re-read the changed value and run only relevant focused assertions; stop when they pass. Run audit when the change is structural or broader.",
...(startPreview !== undefined && captureScreenshot !== undefined
? [
"Ask whether the user wants visual verification unless they explicitly requested it. If they decline, stop after focused assertions or the static audit; if they opt in, start a session preview and capture only the necessary screenshots. Production preview also requires a slow-operation preflight and explicit confirmation.",
]
: []),
]
: []),
];
return toCallResult(envelope, {
...(operation.method !== "mutation" || dryRun || next.length === 0
? {}
: { next }),
});
},
};
};
const getToolCallInput = (input: unknown, destructive = false) => {
if (isPlainRecord(input) === false) {
return {
input,
dryRun: false,
confirmDestructive: false,
confirmationToken: undefined,
};
}
const dryRun = input.dryRun === true || input["dry-run"] === true;
const confirmDestructive = input.confirmDestructive === true;
const confirmationToken =
typeof input.confirmationToken === "string"
? input.confirmationToken
: undefined;
const { dryRun: _dryRun, "dry-run": _dashDryRun, ...withoutDryRun } = input;
if (destructive) {
const {
confirmDestructive: _confirmDestructive,
confirmationToken: _confirmationToken,
...operationInput
} = withoutDryRun;
return {
input: operationInput,
dryRun,
confirmDestructive,
confirmationToken,
};
}
return {
input: withoutDryRun,
dryRun,
confirmDestructive: false,
confirmationToken: undefined,
};
};
type ProjectSessionMcpErrorResult = {
isError: true;
content: [{ type: "text"; text: string }];
structuredContent: {
ok: false;
error: McpStructuredError;
meta: Record<string, never>;
};
};
const toToolErrorResult = (
error: unknown,
getErrorCode: McpErrorCodeResolver | undefined,
inputSchema?: InputJsonSchema
): ProjectSessionMcpErrorResult => {
const structuredCode =
typeof error === "object" &&
error !== null &&
"code" in error &&
typeof error.code === "string"
? error.code
: undefined;
const code =
error instanceof z.ZodError
? "INVALID_INPUT"
: (getErrorCode?.(error) ?? structuredCode ?? "MCP_TOOL_FAILED");
const validationIssues =
error instanceof z.ZodError
? getZodValidationIssues(error, inputSchema)
: getValidationIssues(error);
const baseMessage =
code === "PROJECT_SESSION_BUSY"
? projectSessionBusyMessage
: error instanceof z.ZodError
? "Tool input is invalid."
: error instanceof Error
? error.message
: String(error);
const message =
validationIssues === undefined || validationIssues.length === 0
? baseMessage
: formatValidationErrorMessage(baseMessage, validationIssues);
const structuredContent = {
ok: false as const,
error: {
message,
code,
...(validationIssues === undefined ? {} : { issues: validationIssues }),
},
meta: {},
};
return {
isError: true,
content: [{ type: "text", text: JSON.stringify(structuredContent) }],
structuredContent,
};
};
export const createProjectSessionMcpServer = async <
Command extends string = string,
>({
operations,
createProjectSession,
executeOperation,
importProject,
captureScreenshot,
capturePageScreenshots,
diffScreenshots,
installOcr,
startPreview,
submitPreviewForm,
simulateForm,
getPreviewStatus,
stopPreview,
guidance,
getErrorCode,
reportLog,
storeRenderedAuditArtifacts,
restorePoints,
onProjectSessionChange,
onInitialized,
toolNameFormat = "canonical",
toolHeartbeatIntervalMs = 10_000,
onToolFailure,
onToolSuccess,
additionalInstructions,
}: Omit<ProjectSessionMcpCoreOptions<Command>, "reportToolProgress"> & {
additionalInstructions?: string;
getErrorCode?: McpErrorCodeResolver;
reportLog?: (level: McpLogLevel, message: string) => void;
onInitialized?: (clientName: string | undefined) => void;
toolNameFormat?: "canonical" | "underscores";
toolHeartbeatIntervalMs?: number;
onToolFailure?: (
canonicalTool: string,
error: unknown,
elapsedMs: number,
input: unknown
) => void | Promise<void>;
onToolSuccess?: (
canonicalTool: string,
input: unknown
) => void | Promise<void>;
}) => {
const server = new Server(
{ name: "webstudio", version: "0.0.0" },
{
capabilities: {
tools: {},
resources: {},
logging: {},
},
instructions: [startupGuidance, additionalInstructions?.trim()]
.filter(Boolean)
.join("\n\n"),
}
);
const sendLog = (level: "info" | "error", data: string) => {
reportLog?.(level, data);
void server
.sendLoggingMessage({
level,
logger: "webstudio",
data,
} satisfies (typeof LoggingMessageNotificationSchema._output)["params"])
.catch(() => {
// Heartbeats can finish after the client disconnects. A logging
// notification is best effort and must not crash the MCP server.
if (server.transport !== undefined) {
reportLog?.("error", "MCP logging notification failed");
}
});
};
const core = createProjectSessionMcpCore({
operations,
createProjectSession,
executeOperation,
importProject,
captureScreenshot,
capturePageScreenshots,
diffScreenshots,
installOcr,
startPreview,
submitPreviewForm,
simulateForm,
getPreviewStatus,
stopPreview,
guidance,
storeRenderedAuditArtifacts,
restorePoints,
onProjectSessionChange,
reportToolProgress: (message) => {
sendLog("info", message);
},
});
const tools = core.listTools();
const toolNameIndex = createToolNameIndex(tools);
const exposedTools = tools.map((tool) => ({
...tool,
name:
toolNameFormat === "underscores"
? toUnderscoredToolName(tool.name)
: tool.name,
}));
if (toolNameFormat === "underscores") {
for (const [
exposedName,
canonicalNames,
] of toolNameIndex.canonicalNamesByUnderscoredName) {
if (canonicalNames.length < 2) {
continue;
}
throw new Error(
`MCP tool names ${canonicalNames.join(
" and "
)} both map to ${exposedName}.`
);
}
}
server.oninitialized = () => {
onInitialized?.(server.getClientVersion()?.name);
sendLog(
"info",
`ready with ${
core.listTools().length
} tools; use tools/list, meta.index, or webstudio://project/guide`
);
};
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: exposedTools.map(toSdkTool),
}));
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
resources: core.listResources(),
}));
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const params = getRequestParams(request);
const uri = typeof params.uri === "string" ? params.uri : "";
try {
return await core.readResource({
uri,
});
} catch (error) {
const code = getErrorCode?.(error) ?? "MCP_RESOURCE_FAILED";
const message =
code === "PROJECT_SESSION_BUSY"
? projectSessionBusyMessage
: error instanceof Error
? error.message
: String(error);
return {
contents: [
{
uri,
mimeType: "application/json",
text: JSON.stringify({
ok: false,
error: {
message,
code,
},
meta: {},
}),
},
],
};
}
});
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
const params = getRequestParams(request);
const exposedName = typeof params.name === "string" ? params.name : "";
const canonicalName = toolNameIndex.get(exposedName)?.name;
const name = toolNameIndex.resolve(exposedName);
const { input, dryRun } = getToolCallInput(params.arguments ?? {});
const startedAt = Date.now();
sendLog("info", `tool ${name} started${dryRun ? " (dry run)" : ""}`);
const heartbeat =
toolHeartbeatIntervalMs > 0
? setInterval(() => {
sendLog(
"info",
`tool ${name} still running after ${Date.now() - startedAt}ms`
);
}, toolHeartbeatIntervalMs)
: undefined;
try {
const result = await core.callTool({
name,
input,
dryRun,
signal: extra.signal,
});
const elapsedMs = Date.now() - startedAt;
if (result.structuredContent.ok === false) {
await onToolFailure?.(
canonicalName ?? "unknown",
result.structuredContent.error,
elapsedMs,
input
);
sendLog("error", `tool ${name} failed in ${elapsedMs}ms`);
} else {
await onToolSuccess?.(canonicalName ?? "unknown", input);
sendLog("info", `tool ${name} succeeded in ${elapsedMs}ms`);
}
return result;
} catch (error) {
const elapsedMs = Date.now() - startedAt;
await onToolFailure?.(
canonicalName ?? "unknown",
error,
elapsedMs,
input
);
sendLog(
"error",
`tool ${name} failed in ${elapsedMs}ms: ${
error instanceof Error ? error.message : String(error)
}`
);
return toToolErrorResult(
error,
getErrorCode,
core.listTools().find((tool) => tool.name === name)?.inputSchema
);
} finally {
if (heartbeat !== undefined) {
clearInterval(heartbeat);
}
}
});
return server;
};
export const connectProjectSessionMcpServer = async <Command extends string>({
transport,
...options
}: Parameters<typeof createProjectSessionMcpServer<Command>>[0] & {
transport: McpTransport;
}) => {
const server = await createProjectSessionMcpServer(options);
await server.connect(transport);
return server;
};
export const createMcpStdioTransport = async ({
stdin,
stdout,
partialFrameTimeoutMs = 5_000,
}: {
stdin: NonNullable<ConstructorParameters<typeof StdioServerTransport>[0]>;
stdout: ConstructorParameters<typeof StdioServerTransport>[1];
partialFrameTimeoutMs?: number;
}): Promise<McpTransport> => {
let partialFrame: Buffer | undefined;
let discardTimer: ReturnType<typeof setTimeout> | undefined;
const clearDiscardTimer = () => {
if (discardTimer !== undefined) {
clearTimeout(discardTimer);
discardTimer = undefined;
}
};
const scheduleDiscard = () => {
clearDiscardTimer();
if (partialFrame === undefined || partialFrameTimeoutMs <= 0) {
return;
}
discardTimer = setTimeout(() => {
partialFrame = undefined;
discardTimer = undefined;
}, partialFrameTimeoutMs);
discardTimer.unref?.();
};
const recoveringInput = new Transform({
transform(chunk: Buffer | string, encoding: BufferEncoding, callback) {
const nextChunk = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(chunk, encoding);
const buffered =
partialFrame === undefined
? nextChunk
: Buffer.concat([partialFrame, nextChunk]);
const lastNewline = buffered.lastIndexOf(10);
if (lastNewline === -1) {
partialFrame = buffered;
scheduleDiscard();
callback();
return;
}
clearDiscardTimer();
this.push(buffered.subarray(0, lastNewline + 1));
const remainder = buffered.subarray(lastNewline + 1);
partialFrame = remainder.length === 0 ? undefined : remainder;
scheduleDiscard();
callback();
},
flush(callback) {
clearDiscardTimer();
partialFrame = undefined;
callback();
},
destroy(error, callback) {
clearDiscardTimer();
partialFrame = undefined;
callback(error);
},
});
stdin.pipe(recoveringInput);
const transport = new StdioServerTransport(recoveringInput, stdout);
const closeTransport = transport.close.bind(transport);
transport.close = async () => {
await closeTransport();
stdin.unpipe(recoveringInput);
recoveringInput.destroy();
};
return transport;
};