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 { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { expect } from "@playwright/test";
import { encodeDataSourceVariable } from "@webstudio-is/sdk";
import {
migratePages,
serializePages,
} from "@webstudio-is/project-migrations/pages";
import { runtimeOperationContracts } from "@webstudio-is/project-build/contracts";
import {
createProjectSessionMcpServer,
type PublicMcpOperation,
} from "@webstudio-is/project-build/mcp";
import {
createProjectSession,
type ProjectSessionPersistedSnapshot,
type ProjectSessionRemoteSnapshot,
} from "@webstudio-is/project-build/project-session";
import {
applyBuilderPatchTransactions,
createBuilderBuildDataSnapshotFromState,
createBuilderStateFromBuildData,
} from "@webstudio-is/project-build/state";
import {
executeBuilderRuntimeOperation,
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { loadDevBuild, updateBuild } from "../db";
import { seedSavedLegacyForm } from "./saved-legacy-form";
const commands = new Set([
"insert-fragment",
"set-text-content",
"create-variable",
"create-resource",
"update-props",
"inspect-instance",
]);
const operations: PublicMcpOperation[] = runtimeOperationContracts
.filter(({ command }) => commands.has(command))
.map((contract) => ({
command: contract.command,
id: contract.id,
method: contract.kind === "mutation" ? "mutation" : "query",
permit: contract.permit ?? "view",
description: contract.command,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
localCapable: true,
serverOnly: false,
readNamespaces: contract.readNamespaces,
writeNamespaces: contract.writeNamespaces,
invalidatesNamespaces: contract.invalidatesNamespaces,
retryOnConflict: contract.retryOnConflict,
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const mode = process.argv[3];
const receiverUrl = process.argv[4];
const verifyFieldChange = process.argv[5] === "field-change";
if ((mode !== "legacy" && mode !== "managed") || receiverUrl === undefined) {
throw new Error("Expected legacy/managed mode and a local receiver URL");
}
const author = async () => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
const pages = migratePages(parse("pages"));
const home = pages.pages.get(pages.homePageId);
if (home === undefined) {
throw new Error("Expected a home page in the E2E fixture");
}
const initialState = createBuilderStateFromBuildData({
pages,
instances: parse("instances"),
props: parse("props"),
styles: parse("styles"),
styleSources: parse("styleSources"),
styleSourceSelections: parse("styleSourceSelections"),
dataSources: parse("dataSources"),
resources: parse("resources"),
breakpoints: parse("breakpoints"),
assets: [],
assetFolders: [],
});
let remote: ProjectSessionRemoteSnapshot = {
projectId: projectId,
buildId: build.id,
version: build.version,
state: initialState,
};
let stored: ProjectSessionPersistedSnapshot | undefined;
let revision = 0;
let nextId = 0;
const persist = async () => {
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
build = await updateBuild(build.id, {
version: remote.version,
pages: JSON.stringify(serializePages(snapshot.pages!)),
instances: JSON.stringify(snapshot.instances),
props: JSON.stringify(snapshot.props),
styles: JSON.stringify(snapshot.styles),
styleSources: JSON.stringify(snapshot.styleSources),
styleSourceSelections: JSON.stringify(snapshot.styleSourceSelections),
dataSources: JSON.stringify(snapshot.dataSources),
resources: JSON.stringify(snapshot.resources),
breakpoints: JSON.stringify(snapshot.breakpoints),
});
};
const session = createProjectSession({
projectId: projectId,
compatibilityVersion: "mcp-form-callbacks-e2e-v1",
runtimeContext: { createId: () => `mcp-callback-${nextId++}` },
storage: {
load: async () => stored,
save: async (snapshot, options) => {
expect(options.expectedRevision).toBe(stored?.revision);
stored = { ...snapshot, revision: `revision-${++revision}` };
return { revision: stored.revision };
},
clear: async () => {
stored = undefined;
},
},
transport: {
fetchNamespaces: async () => remote,
commitPatch: async ({ baseVersion, transactions }) => {
expect(baseVersion).toBe(remote.version);
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, transactions)
.state,
};
await persist();
return { version: remote.version };
},
commitRestorePoint: async () => {
throw new Error("Restore points are outside this E2E fixture");
},
getPermissions: async () => ({
canView: true,
canEdit: true,
canBuild: true,
canAdmin: false,
canUseApi: true,
}),
getCompatibility: async () => ({
sessionVersion: "mcp-form-callbacks-e2e-v1",
runtimeContractVersion: "test-runtime-contracts",
projectSchemaVersion: "test-project-schema",
apiCompatibilityVersion: "test-api",
}),
executeServerOperation: async <Result>({
operationId,
input,
}: {
operationId: string;
input: unknown;
}): Promise<Result> => {
const mutation =
await executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
id: operationId,
state: remote.state,
input,
context: {
createId: () => `mcp-callback-server-${nextId++}`,
projectId: remote.projectId,
projectVersion: remote.version,
},
});
expect(mutation.kind).toBe("mutation");
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, [
{
id: `mcp-callback-transaction-${nextId++}`,
payload: mutation.payload,
},
]).state,
};
await persist();
return mutation.result as Result;
},
},
});
const server = await createProjectSessionMcpServer({
operations,
createProjectSession: () => session,
executeOperation: async ({ command, input, dryRun }) => {
const operation = operations.find(
(candidate) => candidate.command === command
);
const contract = runtimeOperationContracts.find(
({ id }) => id === operation?.id
);
if (operation === undefined || contract === undefined) {
throw new Error(`Unexpected MCP operation: ${command}`);
}
const scopedInput = {
...(input as object),
projectId: projectId,
};
const result =
operation.method === "mutation"
? await session.mutate(contract.id, scopedInput, {
permit: operation.permit,
dryRun,
})
: await session.read(contract.id, scopedInput, {
permit: operation.permit,
});
const failure = result.diagnostics.find(({ level }) => level === "error");
if (failure) {
throw new Error(failure.message);
}
return result;
},
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const client = new Client({
name: "mcp-form-callbacks-e2e",
version: "1.0.0",
});
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const call = async (name: string, args: Record<string, unknown> = {}) => {
const response = await client.callTool({ name, arguments: args });
if (response.isError) {
throw new Error(`${name}: ${JSON.stringify(response.structuredContent)}`);
}
const payload = response.structuredContent as {
ok: boolean;
data: Record<string, unknown>;
};
expect(payload.ok, name).toBe(true);
return payload.data;
};
try {
const state = await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
name: "callbackState",
value: { type: "string", value: "initial" },
});
const history = await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
name: "callbackHistory",
value: { type: "string", value: "" },
});
const results = await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
name: "callbackResults",
value: { type: "json", value: [] },
});
const errors = await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
name: "callbackErrors",
value: { type: "json", value: [] },
});
const changeCount = verifyFieldChange
? await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
name: "fieldChangeCount",
value: { type: "number", value: 0 },
})
: undefined;
let formId: string;
let inputId: string | undefined;
let effectId: string | undefined;
let auditId: string;
let errorId: string;
if (mode === "legacy") {
await expect(
call("insert-fragment", {
parentInstanceId: home.rootInstanceId,
fragment: "<WebhookForm />",
})
).rejects.toThrow("Webhook Form is deprecated");
formId = `saved-legacy-callback-${nextId++}`;
remote = {
...remote,
version: remote.version + 1,
state: seedSavedLegacyForm({
state: remote.state,
rootInstanceId: home.rootInstanceId,
formId,
}),
};
await persist();
await call("refresh");
await call("update-props", {
updates: [
{
instanceId: formId,
name: "id",
type: "string",
value: "callback-form",
},
],
});
await call("insert-fragment", {
parentInstanceId: formId,
fragment:
'<Input name="outcome" /><Button type="submit">Submit callback form</Button>',
});
const fragment = await call("insert-fragment", {
parentInstanceId: home.rootInstanceId,
fragment:
'<Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>',
});
[auditId, errorId] = fragment.rootInstanceIds as string[];
} else {
const fragment = await call("insert-fragment", {
parentInstanceId: home.rootInstanceId,
fragment: verifyFieldChange
? '<ResourceForm id="callback-form" /><Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>'
: '<ResourceForm id="callback-form"><Input name="outcome" /><Button type="submit">Submit callback form</Button></ResourceForm><Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>',
});
[formId, auditId, errorId] = fragment.rootInstanceIds as string[];
if (verifyFieldChange) {
const controls = await call("insert-fragment", {
parentInstanceId: formId,
fragment:
'<Input name="outcome" /><Input name="changeCount" type="hidden" /><Button type="submit">Submit callback form</Button>',
});
[inputId, effectId] = controls.rootInstanceIds as string[];
}
}
const resource = await call("create-resource", {
resource: {
name: "Callback receiver",
method: "post",
url:
mode === "legacy"
? receiverUrl
: "https://mcp-delivery.example/submit",
headers: [],
},
scopeInstanceId: formId,
dataSourceName: "Callback receiver",
exposeAsDataSource: true,
});
const encoded = (variable: Record<string, unknown>) =>
encodeDataSourceVariable(variable.dataSourceId as string);
const stateCode = encoded(state);
const historyCode = encoded(history);
const resultsCode = encoded(results);
const errorsCode = encoded(errors);
const changeCountCode = changeCount && encoded(changeCount);
await call("update-props", {
updates: [
{
instanceId: formId,
name: "action",
...(mode === "legacy"
? { type: "resource", value: resource.resourceId }
: {
type: "json",
value: [{ dataSourceId: resource.dataSourceId }],
}),
},
{
instanceId: formId,
name: "state",
type: "expression",
value: stateCode,
},
...(changeCountCode && inputId && effectId
? [
{
instanceId: inputId,
name: "onChange",
type: "action",
value: [
{
type: "execute",
args: [],
code: `${changeCountCode} = ${changeCountCode} + 1`,
},
],
},
{
instanceId: effectId,
name: "value",
type: "expression",
value: changeCountCode,
},
]
: []),
{
instanceId: formId,
name: "onStateChange",
type: "action",
value: [
{ type: "execute", args: ["state"], code: `${stateCode} = state` },
{
type: "execute",
args: ["state"],
code: `${historyCode} = ${historyCode} + "|" + state`,
},
],
},
...(mode === "managed"
? [
{
instanceId: formId,
name: "onResultChange",
type: "action",
value: [
{
type: "execute",
args: ["result"],
code: `${resultsCode} = result.results`,
},
{
type: "execute",
args: ["result"],
code: `${errorsCode} = result.errors`,
},
],
},
]
: []),
],
});
await call("set-text-content", {
operation: "set",
instanceId: auditId,
mode: "expression",
text: '"state=" + callbackState + ";history=" + callbackHistory + ";results=" + callbackResults.length + ";errors=" + callbackErrors.length + ";status=" + (callbackResults[0]?.status ?? 0)',
});
await call("set-text-content", {
operation: "set",
instanceId: errorId,
mode: "expression",
text: 'callbackErrors[0]?.message ?? "no errors"',
});
await call("refresh");
if (inputId) {
const inputInspection = await call("inspect-instance", {
instanceId: inputId,
include: ["props"],
});
expect(inputInspection.props).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "onChange", type: "action" }),
])
);
}
const inspection = await call("inspect-instance", {
instanceId: formId,
include: ["props"],
});
expect(inspection.props).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "onStateChange", type: "action" }),
expect.objectContaining({
name: "action",
type: mode === "legacy" ? "resource" : "json",
}),
])
);
process.stdout.write(
`${JSON.stringify({ formId, resourceId: resource.resourceId })}\n`
);
} finally {
await client.close();
await server.close();
}
};
await author();