Skip to content

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

fix: Forward fragment token conflict resolution (#6122)

Oleg Isonen146e65fe0d8f
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index 7583675a8a..0527b25e7c 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -2,8 +2,14 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, expect, test, vi } from "vitest";
+import {
+ getInputJsonSchemaMetadata,
+ getInputJsonSchemaProperties,
+} from "@webstudio-is/sdk";
import {
createProjectSessionMcpCore,
+ getDetailedProjectSessionMcpInputSchema,
+ hiddenMcpOperationCommands,
listProjectSessionMcpTools,
} from "@webstudio-is/project-build/mcp";
import { publicApiOperations } from "@webstudio-is/protocol";
@@ -78,6 +84,111 @@ const tempDirs: string[] = [];
type CommandBuilder = (yargs: unknown) => unknown;
type CommandCall = [readonly string[], string, CommandBuilder, unknown];
+const normalizeMcpJsonValueSchemas = (value: unknown): unknown => {
+ if (Array.isArray(value)) {
+ return value.map(normalizeMcpJsonValueSchemas);
+ }
+ if (value === null || typeof value !== "object") {
+ return value;
+ }
+ const object = value as Record<string, unknown>;
+ if (
+ Object.keys(object).length === 1 &&
+ Array.isArray(object.anyOf) &&
+ JSON.stringify(object.anyOf) ===
+ JSON.stringify([
+ { type: "string" },
+ { type: "number" },
+ { type: "boolean" },
+ { type: "null" },
+ { type: "array", items: {} },
+ { type: "object" },
+ ])
+ ) {
+ return {};
+ }
+ const omitSyntheticTupleItems =
+ Array.isArray(object.prefixItems) &&
+ object.items !== null &&
+ typeof object.items === "object" &&
+ Object.keys(object.items).length === 0;
+ return Object.fromEntries(
+ Object.entries(object)
+ .filter(([key]) => omitSyntheticTupleItems === false || key !== "items")
+ .map(([key, nestedValue]) => [
+ key,
+ normalizeMcpJsonValueSchemas(nestedValue),
+ ])
+ );
+};
+
+test("keeps every MCP API tool aligned with its public API contract", () => {
+ const toolsByName = new Map(
+ listProjectSessionMcpTools(publicApiOperations).map((tool) => [
+ tool.name,
+ tool,
+ ])
+ );
+
+ for (const operation of publicApiOperations) {
+ if (hiddenMcpOperationCommands.has(operation.command)) {
+ expect(toolsByName.has(operation.command), operation.command).toBe(false);
+ continue;
+ }
+
+ const tool = toolsByName.get(operation.command);
+ expect(tool, operation.command).toBeDefined();
+ if (tool === undefined) {
+ continue;
+ }
+
+ const schema = getDetailedProjectSessionMcpInputSchema(tool);
+ const transportFields = [
+ ...(operation.method === "mutation" && operation.localCapable
+ ? ["dryRun"]
+ : []),
+ ...(operation.requiresConfirm && operation.localCapable
+ ? ["confirmDestructive", "confirmationToken"]
+ : []),
+ ];
+ const schemaMetadata = getInputJsonSchemaMetadata(schema);
+ const semanticFields = schemaMetadata.inputFields.filter(
+ (field) => transportFields.includes(field) === false
+ );
+ expect(new Set(semanticFields), operation.command).toEqual(
+ new Set(operation.inputFields)
+ );
+
+ const apiProperties = getInputJsonSchemaProperties(operation.inputSchema);
+ const mcpProperties = getInputJsonSchemaProperties(schema);
+ for (const field of operation.inputFields) {
+ const isRepresentationOverride =
+ (operation.command === "insert-fragment" &&
+ ["parentInstanceId", "fragment"].includes(field)) ||
+ (operation.command === "insert-collection" && field === "itemFragment");
+ if (isRepresentationOverride) {
+ continue;
+ }
+ expect(
+ normalizeMcpJsonValueSchemas(mcpProperties?.[field]),
+ `${operation.command}.${field}`
+ ).toEqual(apiProperties?.[field]);
+ }
+
+ const requiredFields = [...operation.requiredInputFields];
+ if (
+ operation.command === "insert-fragment" &&
+ requiredFields.includes("parentInstanceId") === false
+ ) {
+ requiredFields.push("parentInstanceId");
+ }
+ expect(
+ new Set(schemaMetadata.requiredInputFields),
+ operation.command
+ ).toEqual(new Set(requiredFields));
+ }
+});
+
afterEach(async () => {
vi.restoreAllMocks();
await Promise.all(
diff --git a/packages/cli/src/commands/schema.test.ts b/packages/cli/src/commands/schema.test.ts
index 1a66d5566d..0ef2be5211 100644
--- a/packages/cli/src/commands/schema.test.ts
+++ b/packages/cli/src/commands/schema.test.ts
@@ -245,6 +245,8 @@ test("prints full mcp tool input schemas when requested", () => {
expect(Object.keys(insertFragmentTool.inputSchema.properties)).toEqual([
"parentInstanceId",
"fragment",
+ "conflictResolution",
+ "contentMode",
"mode",
"insertIndex",
"dryRun",
diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
index 4503cad7ed..9f1907dbb6 100644
--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts
@@ -39616,8 +39616,12 @@ export const runtimeOperationContractData = [
conflictResolution: {
type: "string",
enum: ["ours", "theirs", "merge"],
+ description:
+ 'How to resolve incoming design tokens that share a name with an existing token. "ours" keeps the existing token styles and id, "theirs" uses incoming styles, and "merge" combines both.',
},
contentMode: {
+ description:
+ "Apply content-mode copy restrictions to props and styles while reusing existing tokens and breakpoints.",
type: "boolean",
},
mode: {
@@ -54817,8 +54821,12 @@ export const runtimeOperationContractData = [
conflictResolution: {
type: "string",
enum: ["ours", "theirs", "merge"],
+ description:
+ 'How to resolve incoming design tokens that share a name with an existing token. "ours" keeps the existing token styles and id, "theirs" uses incoming styles, and "merge" combines both.',
},
contentMode: {
+ description:
+ "Apply content-mode copy restrictions to props and styles while reusing existing tokens and breakpoints.",
type: "boolean",
},
mode: {
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index 1d3733fc9b..5b9f2f0d42 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -21,6 +21,7 @@ import {
createProjectSessionMcpCore,
createProjectSessionMcpServer,
createMcpStdioTransport,
+ getDetailedProjectSessionMcpInputSchema,
hiddenMcpOperationCommands,
listProjectSessionMcpResources,
listProjectSessionMcpTools,
@@ -29,6 +30,7 @@ import {
type ProjectSessionScreenshotInput,
} from "./mcp";
import { getComponentTemplates } from "./runtime/component-templates";
+import { insertFragmentInput } from "./runtime/components";
import { createEmptyWebstudioFragment } from "./runtime/component-template";
import {
projectSessionBusyMessage,
@@ -319,14 +321,7 @@ const publicMcpOperations: readonly PublicMcpOperation[] = [
method: "mutation",
permit: "build",
description: "Insert fragment",
- inputSchema: getTestInputSchema(
- z.object({
- parentInstanceId: z.string(),
- fragment: z.unknown(),
- mode: z.enum(["append", "prepend", "replace"]).optional(),
- insertIndex: z.number().optional(),
- })
- ),
+ inputSchema: getTestInputSchema(insertFragmentInput),
readNamespaces: ["pages", "instances"],
writeNamespaces: ["instances", "props", "styles"],
invalidatesNamespaces: ["instances", "props", "styles"],
@@ -1025,6 +1020,18 @@ describe("project session mcp adapter", () => {
const insertFragmentTool = tools.find(
(tool) => tool.name === "insert-fragment"
);
+ const runtimeInsertFragmentProperties = Object.keys(
+ getInputSchemaMetadata(insertFragmentInput).inputJsonSchema.properties ??
+ {}
+ );
+ expect(
+ Object.keys(
+ insertFragmentTool === undefined
+ ? {}
+ : (getDetailedProjectSessionMcpInputSchema(insertFragmentTool)
+ .properties ?? {})
+ ).filter((property) => property !== "dryRun")
+ ).toEqual(runtimeInsertFragmentProperties);
expect(insertFragmentTool?.inputSchema.required).toEqual([
"parentInstanceId",
"fragment",
@@ -1034,21 +1041,28 @@ describe("project session mcp adapter", () => {
).toEqual([
"parentInstanceId",
"fragment",
+ "conflictResolution",
+ "contentMode",
"mode",
"insertIndex",
"dryRun",
]);
const fragmentSchema = insertFragmentTool?.inputSchema.properties?.fragment;
expect(fragmentSchema).toEqual(expect.objectContaining({ type: "string" }));
+ const detailedFragmentSchema =
+ insertFragmentTool === undefined
+ ? undefined
+ : getDetailedProjectSessionMcpInputSchema(insertFragmentTool).properties
+ ?.fragment;
expect(
tools.find((tool) => tool.name === "insert-fragment-verified")
?.inputSchema.required
).toEqual(["parentInstanceId", "fragment", "pagePath"]);
const jsxDescription =
- typeof fragmentSchema === "object" &&
- "description" in fragmentSchema &&
- typeof fragmentSchema.description === "string"
- ? fragmentSchema.description
+ typeof detailedFragmentSchema === "object" &&
+ "description" in detailedFragmentSchema &&
+ typeof detailedFragmentSchema.description === "string"
+ ? detailedFragmentSchema.description
: undefined;
expect(jsxDescription).toContain("not React aliases className or htmlFor");
expect(jsxDescription).toContain("Use ws:style");
@@ -2412,12 +2426,23 @@ describe("project session mcp adapter", () => {
executeOperation,
});
+ expect(
+ adapter.listTools().find(({ name }) => name === "insert-fragment")
+ ?.inputSchema.properties?.conflictResolution
+ ).toEqual({
+ type: "string",
+ enum: ["ours", "theirs", "merge"],
+ description: expect.any(String),
+ });
+
await adapter.callTool({
name: "insert-fragment",
input: {
parentInstanceId: "body",
fragment:
'<ws.element ws:tag="section"><ws.element ws:tag="h2">Title</ws.element></ws.element>',
+ conflictResolution: "ours",
+ contentMode: true,
},
});
@@ -2432,6 +2457,8 @@ describe("project session mcp adapter", () => {
expect.objectContaining({ component: "ws:element" }),
]),
}),
+ conflictResolution: "ours",
+ contentMode: true,
mode: undefined,
insertIndex: undefined,
},
@@ -2465,12 +2492,23 @@ describe("project session mcp adapter", () => {
expect(adapter.listTools().map(({ name }) => name)).toContain(
"insert-fragment-verified"
);
+ expect(
+ adapter
+ .listTools()
+ .find(({ name }) => name === "insert-fragment-verified")?.inputSchema
+ .properties?.conflictResolution
+ ).toEqual({
+ type: "string",
+ enum: ["ours", "theirs", "merge"],
+ description: expect.any(String),
+ });
const result = await adapter.callTool({
name: "insert-fragment-verified",
input: {
parentInstanceId: "root-id",
pagePath: "/account",
fragment: '<ws.element ws:tag="section" />',
+ conflictResolution: "merge",
},
});
@@ -2478,6 +2516,7 @@ describe("project session mcp adapter", () => {
1,
expect.objectContaining({
command: "insert-fragment",
+ input: expect.objectContaining({ conflictResolution: "merge" }),
dryRun: false,
})
);
@@ -2575,6 +2614,8 @@ describe("project session mcp adapter", () => {
data: { type: "expression", value: "Posts.data.items" },
itemFragment:
'<ws.element ws:tag="article"><ws.element ws:tag="h2">{expression`collectionItem.title`}</ws.element></ws.element>',
+ mode: "prepend",
+ insertIndex: 2,
},
});
@@ -2592,8 +2633,8 @@ describe("project session mcp adapter", () => {
expect.objectContaining({ component: "ws:element", tag: "h2" }),
]),
}),
- mode: undefined,
- insertIndex: undefined,
+ mode: "prepend",
+ insertIndex: 2,
},
dryRun: false,
});
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 6b09e53995..df49742509 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -75,6 +75,7 @@ import {
} from "./runtime/component-templates";
import {
getTemplateRequiredStructure,
+ insertFragmentInput,
parseComponentEdge,
} from "./runtime/components";
import { getInputSchemaMetadata } from "./contracts/input-schema";
@@ -496,49 +497,6 @@ const workflowNextInputSchema = {
required: [],
} as const satisfies ProjectSessionMcpInputSchema;
-const insertFragmentMcpInputSchema = {
- ...emptyInputSchema,
- description:
- "Insert a Webstudio fragment from a Webstudio JSX string. The CLI converts JSX into structured Webstudio data before mutation.",
- additionalProperties: false,
- properties: {
- parentInstanceId: {
- type: "string",
- description: "Parent instance id where the fragment is inserted.",
- },
- fragment: {
- type: "string",
- description: webstudioJsxFragmentInputDescription,
- },
- mode: {
- type: "string",
- enum: ["append", "prepend", "replace"],
- description:
- "Append, prepend, or replace parent children before inserting the fragment.",
- },
- insertIndex: {
- type: "number",
- description: "Zero-based child index for insertion.",
- },
- },
- required: ["parentInstanceId", "fragment"],
-} as const satisfies ProjectSessionMcpInputSchema;
-
-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 insertCollectionMcpInput = insertCollectionInput
.omit({ itemFragment: true })
.extend({
@@ -770,6 +728,35 @@ const getZodObjectSchema = (schema: z.ZodTypeAny) => {
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,
});
@@ -3407,11 +3394,12 @@ export const hiddenMcpOperationCommands = new Set<string>([
"copy-page",
]);
-const compactMcpOperationCommands = new Set([
- "create-assets-resource",
- "update-assets-resource",
- "validate-asset-query",
- "preview-asset-query",
+const mcpOperationSchemaInlineSizes = new Map<string, number>([
+ ["insert-fragment", 1_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<
@@ -3449,7 +3437,7 @@ export const listProjectSessionMcpTools = (
});
const { inputSchema, detailedInputSchema } = getHandshakeInputSchema(
operationInputSchema,
- compactMcpOperationCommands.has(operation.command) ? 2_500 : undefined
+ mcpOperationSchemaInlineSizes.get(operation.command)
);
const tool = createProjectSessionMcpTool({
name: operation.command,
@@ -3878,28 +3866,12 @@ const getInsertFragmentInput = async (input: unknown) => {
'insert-fragment requires fragment as a Webstudio JSX string, for example {"fragment":"<ws.element ws:tag=\'section\' />"}.'
);
}
- const fragment = await parseWebstudioJsxFragment(input.fragment);
- const mode = input.mode;
- if (
- mode !== undefined &&
- mode !== "append" &&
- mode !== "prepend" &&
- mode !== "replace"
- ) {
- throw new Error(
- 'insert-fragment mode must be "append", "prepend", or "replace".'
- );
- }
- const insertIndex = input.insertIndex;
- if (insertIndex !== undefined && typeof insertIndex !== "number") {
- throw new Error("insert-fragment insertIndex must be a number.");
- }
- return {
- parentInstanceId: input.parentInstanceId,
- fragment,
- mode,
- insertIndex,
- };
+ const { fragment: fragmentSource, ...runtimeInput } =
+ insertFragmentMcpInput.parse(input);
+ return insertFragmentInput.parse({
+ ...runtimeInput,
+ fragment: await parseWebstudioJsxFragment(fragmentSource),
+ });
};
const getInsertCollectionInput = async (input: unknown) => {
diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.ts
index 81645f0bd8..84dca0a422 100644
--- a/packages/project-build/src/runtime/components.test.ts
+++ b/packages/project-build/src/runtime/components.test.ts
@@ -1099,6 +1099,17 @@ test("honors fragment token conflict resolution", async () => {
"styleSources"
).filter((styleSource) => styleSource.type === "token");
expect(addedTokenSources).toEqual([]);
+ expect(
+ getAddedValues<{ instanceId: string; values: string[] }>(
+ mutation,
+ "styleSourceSelections"
+ )
+ ).toEqual([
+ {
+ instanceId: "generated-1",
+ values: [existingFragment.styleSources[0]?.id],
+ },
+ ]);
expect(
getAddedValues<{ property: string; value: unknown }>(mutation, "styles")
).not.toContainEqual(
diff --git a/packages/project-build/src/runtime/components.ts b/packages/project-build/src/runtime/components.ts
index b3e0f683d9..91a360363a 100644
--- a/packages/project-build/src/runtime/components.ts
+++ b/packages/project-build/src/runtime/components.ts
@@ -67,7 +67,11 @@ import {
} from "./matcher";
import { z } from "zod";
-const conflictResolutionInput = z.enum(["ours", "theirs", "merge"]);
+const conflictResolutionInput = z
+ .enum(["ours", "theirs", "merge"])
+ .describe(
+ 'How to resolve incoming design tokens that share a name with an existing token. "ours" keeps the existing token styles and id, "theirs" uses incoming styles, and "merge" combines both.'
+ );
export const insertComponentInput = z.object({
parentInstanceId: z.string(),
@@ -90,7 +94,12 @@ export const insertFragmentInput = z
"Structured Webstudio fragment produced by Webstudio JSX/template helpers. Runtime remaps fragment ids to generated project ids."
),
conflictResolution: conflictResolutionInput.optional(),
- contentMode: z.boolean().optional(),
+ contentMode: z
+ .boolean()
+ .optional()
+ .describe(
+ "Apply content-mode copy restrictions to props and styles while reusing existing tokens and breakpoints."
+ ),
mode: instanceInsertModeInput.optional(),
insertIndex: insertIndexInput.optional(),
})