feat(mcp,editor): Option A+B storage + 10 agent deliverables (Phase 7)

Ships the combined filesystem/Supabase storage adapter + MCP scene
lifecycle tools + Next.js API routes + editor /scene/[id] route, so
an MCP save is directly openable at /scene/<id> without any
injection hack. End-to-end verified: 10/10 e2e steps pass.

Storage (A1/A2/A3):
- SceneStore interface + error classes + slug helpers
- FilesystemSceneStore at $PASCAL_DATA_DIR (defaults XDG/~/.pascal)
  with atomic writes, .index sidecar, optimistic locking
- SupabaseSceneStore with scenes + scene_revisions tables, RLS
  migration SQL, mock-backed unit tests
- createSceneStore(env) auto-selects based on SUPABASE_URL +
  SUPABASE_SERVICE_ROLE_KEY

MCP tools (A4, A8, A9, A10):
- save_scene / load_scene / list_scenes / delete_scene / rename_scene
- list_templates / create_from_template (3 seed templates:
  empty-studio, two-bedroom, garden-house)
- generate_variants (7 mutation kinds, seeded RNG, save=true|false)
- photo_to_scene (vision sampling → scene graph → save)

Editor (A5, A6):
- /api/scenes + /api/scenes/[id] with RFC 7232 If-Match locking
- /scene/[id] and /scenes route pages with save button, SceneLoader
- Removed the window.__pascalScene dev injection hack

Security + UX edges (A7, A8):
- AssetUrl Zod validator: asset:// blob: data:image/ /path https:
  (http://localhost for dev) + PASCAL_ALLOWED_ASSET_ORIGINS env
  allowlist. Hardens scan.url, guide.url, item.asset.src,
  material.texture.url, MaterialMaps.*Map
- Auto-frame camera on empty→non-empty scene transition
  (camera-controls:fit-scene emitter event)

Shared utilities:
- rehydrateSiteChildren() extracted to packages/mcp/src/lib/ and
  used by both create-from-template and generate-variants to work
  around the SiteNode.children-as-objects vs. ids inconsistency
  (CROSS_CUTTING §2)
- Storage + MCP subpath exports added to packages/mcp/package.json
  (CROSS_CUTTING §4)

Tests: 293 pass / 0 fail across 40 files (was 142 pre-Phase-7).
Biome: clean.

Phase-7 e2e script at packages/mcp/test-reports/phase7-e2e.ts:
MCP HTTP + editor Next.js both point at $PASCAL_DATA_DIR =
/tmp/pascal-e2e, save_scene from MCP, GET /api/scenes/<id> from
editor server, /scenes list page renders all saved scenes, scene
page renders SceneLoader, delete_scene works.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Adrian Perez
2026-04-18 19:29:28 +02:00
co-authored by Claude Opus 4.7
parent 42bd05db9c
commit e8d0b13ff5
81 changed files with 8933 additions and 1213 deletions
+15 -1
View File
@@ -1,5 +1,6 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../bridge/scene-bridge'
import type { SceneStore } from '../storage/types'
import { registerApplyPatch } from './apply-patch'
import { registerCheckCollisions } from './check-collisions'
import { registerCreateLevel } from './create-level'
@@ -14,18 +15,25 @@ import { registerFindNodes } from './find-nodes'
import { registerGetNode } from './get-node'
import { registerGetScene } from './get-scene'
import { registerMeasure } from './measure'
import { registerPhotoToSceneTool } from './photo-to-scene'
import { registerPlaceItem } from './place-item'
import { registerRedo } from './redo'
import { registerSceneLifecycleTools } from './scene-lifecycle'
import { registerSetZone } from './set-zone'
import { registerTemplateTools } from './templates'
import { registerUndo } from './undo'
import { registerValidateScene } from './validate-scene'
import { registerVariantTools } from './variants'
/**
* Register every non-vision MCP tool against the given server.
* Vision tools (analyze_floorplan_image, analyze_room_photo) are registered
* separately via `registerVisionTools` (Agent E).
*
* Scene-lifecycle tools (save/load/list/delete/rename scene) are registered
* when a `store` is provided; callers that pass `undefined` skip them.
*/
export function registerTools(server: McpServer, bridge: SceneBridge): void {
export function registerTools(server: McpServer, bridge: SceneBridge, store?: SceneStore): void {
registerGetScene(server, bridge)
registerGetNode(server, bridge)
registerDescribeNode(server, bridge)
@@ -45,4 +53,10 @@ export function registerTools(server: McpServer, bridge: SceneBridge): void {
registerExportGlb(server, bridge)
registerValidateScene(server, bridge)
registerCheckCollisions(server, bridge)
registerTemplateTools(server, bridge, store)
if (store) {
registerSceneLifecycleTools(server, bridge, store)
registerVariantTools(server, bridge, store)
registerPhotoToSceneTool(server, bridge, store)
}
}
@@ -0,0 +1,24 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { registerPhotoToScene } from './photo-to-scene'
/**
* Register the `photo_to_scene` orchestrator tool. Chains the vision
* (`analyze_floorplan_image`-equivalent sampling call) → SceneGraph
* synthesis → optional `SceneStore.save` → `bridge.setScene` so callers get a
* navigable Pascal scene from a single photo upload.
*/
export function registerPhotoToSceneTool(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
registerPhotoToScene(server, bridge, store)
}
export {
photoToSceneInput,
photoToSceneOutput,
registerPhotoToScene,
} from './photo-to-scene'
@@ -0,0 +1,194 @@
import { describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { CreateMessageRequestSchema } from '@modelcontextprotocol/sdk/types.js'
import { SceneBridge } from '../../bridge/scene-bridge'
import { InMemorySceneStore } from '../scene-lifecycle/test-utils'
import { registerPhotoToScene } from './photo-to-scene'
type Handler = (req: unknown) => unknown | Promise<unknown>
/**
* Build a connected client/server pair for the `photo_to_scene` orchestrator.
* Optionally advertises the `sampling` capability on the client and installs
* a mock sampling handler that returns a caller-provided reply.
*/
async function makeWiredPair(opts: { withSampling: boolean; samplingHandler?: Handler }): Promise<{
client: Client
bridge: SceneBridge
store: InMemorySceneStore
}> {
const bridge = new SceneBridge()
bridge.setScene({}, [])
const store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerPhotoToScene(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
const client = new Client(
{ name: 'test-client', version: '0.0.0' },
{
capabilities: opts.withSampling ? { sampling: {} } : {},
},
)
if (opts.withSampling && opts.samplingHandler) {
const handler = opts.samplingHandler
client.setRequestHandler(
CreateMessageRequestSchema,
async (request) =>
// Cast to unknown — tests return arbitrary shapes to exercise
// parse/validation paths in the tool handler.
(await handler(request)) as never,
)
}
await Promise.all([server.connect(srvT), client.connect(cliT)])
return { client, bridge, store }
}
const VALID_VISION_JSON = {
walls: [
{ start: [0, 0], end: [5, 0], thickness: 0.2 },
{ start: [5, 0], end: [5, 4] },
{ start: [5, 4], end: [0, 4] },
{ start: [0, 4], end: [0, 0] },
],
rooms: [
{
name: 'Living Room',
polygon: [
[0, 0],
[5, 0],
[5, 4],
[0, 4],
],
approximateAreaSqM: 20,
},
],
approximateDimensions: { widthM: 5, depthM: 4 },
confidence: 0.82,
}
const VALID_REPLY = {
model: 'mock-model',
role: 'assistant',
content: {
type: 'text',
text: JSON.stringify(VALID_VISION_JSON),
},
}
describe('photo_to_scene', () => {
test('happy path: vision reply → walls + rooms + scene in bridge + saved', async () => {
const { client, bridge, store } = await makeWiredPair({
withSampling: true,
samplingHandler: () => VALID_REPLY,
})
const result = await client.callTool({
name: 'photo_to_scene',
arguments: {
image: 'aGVsbG8=',
scaleHint: '1 cm = 1 m',
name: 'Test Scene',
},
})
expect(result.isError).toBeFalsy()
const structured = result.structuredContent as {
sceneId?: string
url?: string
walls: number
rooms: number
confidence: number
}
expect(structured.walls).toBe(4)
expect(structured.rooms).toBe(1)
expect(structured.confidence).toBe(0.82)
expect(typeof structured.sceneId).toBe('string')
expect(structured.url).toBe(`/scene/${structured.sceneId}`)
// Bridge was swapped.
const rootIds = bridge.getRootNodeIds()
expect(rootIds.length).toBe(1)
const rootId = rootIds[0]!
const root = bridge.getNode(rootId)
expect(root?.type).toBe('site')
// Walls and zones exist in the flat dict.
const allNodes = Object.values(bridge.getNodes())
const walls = allNodes.filter((n) => n.type === 'wall')
const zones = allNodes.filter((n) => n.type === 'zone')
expect(walls.length).toBe(4)
expect(zones.length).toBe(1)
// Scene was persisted in the store.
const saved = await store.load(structured.sceneId!)
expect(saved).not.toBeNull()
expect(saved?.name).toBe('Test Scene')
})
test('sampling unavailable → sampling_unavailable error', async () => {
const { client } = await makeWiredPair({ withSampling: false })
const result = await client.callTool({
name: 'photo_to_scene',
arguments: { image: 'aGVsbG8=' },
})
expect(result.isError).toBe(true)
const text = (result.content as Array<{ type: string; text: string }>)[0]!.text
expect(text).toContain('sampling_unavailable')
})
test('invalid JSON reply → sampling_response_unparseable', async () => {
const { client } = await makeWiredPair({
withSampling: true,
samplingHandler: () => ({
model: 'mock-model',
role: 'assistant',
content: { type: 'text', text: 'not json at all' },
}),
})
const result = await client.callTool({
name: 'photo_to_scene',
arguments: { image: 'aGVsbG8=' },
})
expect(result.isError).toBe(true)
const text = (result.content as Array<{ type: string; text: string }>)[0]!.text
expect(text).toContain('sampling_response_unparseable')
})
test('save=false → returns graph inline, no sceneId', async () => {
const { client, store } = await makeWiredPair({
withSampling: true,
samplingHandler: () => VALID_REPLY,
})
const result = await client.callTool({
name: 'photo_to_scene',
arguments: {
image: 'aGVsbG8=',
save: false,
},
})
expect(result.isError).toBeFalsy()
const structured = result.structuredContent as {
sceneId?: string
url?: string
walls: number
rooms: number
confidence: number
graph?: { nodes: Record<string, unknown>; rootNodeIds: string[] }
}
expect(structured.sceneId).toBeUndefined()
expect(structured.url).toBeUndefined()
expect(structured.graph).toBeDefined()
expect(Array.isArray(structured.graph?.rootNodeIds)).toBe(true)
expect(structured.graph?.rootNodeIds.length).toBe(1)
expect(structured.walls).toBe(4)
expect(structured.rooms).toBe(1)
// Nothing persisted.
const list = await store.list()
expect(list.length).toBe(0)
})
})
@@ -0,0 +1,427 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNodeId, AnyNode as AnyNodeT } from '@pascal-app/core/schema'
import {
AnyNode,
BuildingNode,
LevelNode,
SiteNode,
WallNode,
ZoneNode,
} from '@pascal-app/core/schema'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
/**
* Input shape for the `photo_to_scene` orchestrator. `image` matches the
* contract documented on `analyze_floorplan_image` — base64 or http(s) URL.
*/
export const photoToSceneInput = {
image: z.string().describe('Base64 or https URL of the floor-plan photo'),
scaleHint: z.string().optional().describe('e.g. "1 cm = 1 m" or "approx 80 m²"'),
name: z.string().default('Scene from photo'),
save: z.boolean().default(true),
defaultWallThickness: z.number().default(0.2),
defaultWallHeight: z.number().default(2.6),
}
export const photoToSceneOutput = {
sceneId: z.string().optional(),
url: z.string().optional(),
walls: z.number(),
rooms: z.number(),
confidence: z.number(),
notes: z.string().optional(),
graph: z.any().optional(),
}
/**
* Shape of the vision JSON we consume. Kept in-sync with
* `analyze_floorplan_image`'s output schema (walls / rooms /
* approximateDimensions / confidence).
*/
const VisionResponseSchema = z.object({
walls: z.array(
z.object({
start: z.tuple([z.number(), z.number()]),
end: z.tuple([z.number(), z.number()]),
thickness: z.number().optional(),
}),
),
rooms: z.array(
z.object({
name: z.string(),
polygon: z.array(z.tuple([z.number(), z.number()])),
approximateAreaSqM: z.number().optional(),
}),
),
approximateDimensions: z.object({
widthM: z.number(),
depthM: z.number(),
}),
confidence: z.number().min(0).max(1),
})
type VisionResponse = z.infer<typeof VisionResponseSchema>
/**
* System prompt mirrors `analyze_floorplan_image` — the contract between
* orchestrator and host is identical, so we keep the prompt verbatim to
* guarantee wire-compatible responses.
*/
const SYSTEM_PROMPT = `You are a vision assistant that extracts structured floor-plan data from an image.
Your ONLY job: return a JSON object that exactly matches this schema — no prose, no markdown fences.
{
"walls": [{ "start": [x, z], "end": [x, z], "thickness": number? }, ...],
"rooms": [{ "name": string, "polygon": [[x,z], ...], "approximateAreaSqM": number? }, ...],
"approximateDimensions": { "widthM": number, "depthM": number },
"confidence": number 0..1
}
Coordinates are in metres. Origin can be the floor plan's centre or bottom-left — be consistent.
If the image is unclear, lower the confidence score but still produce your best attempt.
DO NOT wrap the JSON in markdown. DO NOT explain. Just output the raw JSON.`
const DATA_URI_RE = /^data:(image\/[a-z0-9.+-]+);base64,(.+)$/i
type ImageBlock = {
type: 'image'
data: string
mimeType: string
}
/**
* Resolve the `image` input into a sampling-ready image block. Follows the
* same fetch/data-uri/raw-base64 rules as the vision tool so the user gets
* consistent behaviour whether they call `photo_to_scene` or
* `analyze_floorplan_image` directly.
*/
async function resolveImageBlock(image: string): Promise<ImageBlock> {
if (/^https?:\/\//i.test(image)) {
const res = await fetch(image)
if (!res.ok) {
throw new McpError(
ErrorCode.InvalidParams,
`failed to fetch image: ${res.status} ${res.statusText}`,
{ url: image, status: res.status },
)
}
const buf = Buffer.from(await res.arrayBuffer())
const data = buf.toString('base64')
const mimeType = res.headers.get('content-type') ?? 'image/jpeg'
return { type: 'image', data, mimeType }
}
const dataUriMatch = image.match(DATA_URI_RE)
if (dataUriMatch) {
return {
type: 'image',
mimeType: dataUriMatch[1]!,
data: dataUriMatch[2]!,
}
}
return { type: 'image', mimeType: 'image/jpeg', data: image }
}
/** Collect all text content blocks returned by the sampling host into one string. */
function extractText(
content:
| { type: 'text'; text: string }
| { type: 'image' | 'audio'; data: string; mimeType: string }
| Array<
| { type: 'text'; text: string }
| { type: 'image' | 'audio'; data: string; mimeType: string }
| { type: string; [k: string]: unknown }
>,
): string {
const blocks = Array.isArray(content) ? content : [content]
const texts: string[] = []
for (const block of blocks) {
if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {
const t = (block as { text?: unknown }).text
if (typeof t === 'string') texts.push(t)
}
}
return texts.join('\n').trim()
}
/**
* Call the host's sampling capability to analyse a floor-plan photo. Throws
* `sampling_unavailable` when the host has not advertised the capability and
* `sampling_response_unparseable` / `sampling_response_invalid` when the
* reply cannot be mapped onto `VisionResponseSchema`.
*/
async function callVisionSampling(
server: McpServer,
image: string,
scaleHint: string | undefined,
): Promise<VisionResponse> {
const caps = server.server.getClientCapabilities()
if (!caps?.sampling) {
throw new McpError(ErrorCode.InvalidRequest, 'sampling_unavailable')
}
const imageBlock = await resolveImageBlock(image)
const instruction = scaleHint
? `Analyze this floor plan. Scale hint: ${scaleHint}. Return ONLY the JSON described by the system prompt.`
: 'Analyze this floor plan. Return ONLY the JSON described by the system prompt.'
const response = await server.server.createMessage({
systemPrompt: SYSTEM_PROMPT,
temperature: 0,
maxTokens: 2000,
messages: [
{
role: 'user',
content: [imageBlock, { type: 'text', text: instruction }],
},
],
})
const text = extractText(response.content as Parameters<typeof extractText>[0])
if (!text) {
throw new McpError(ErrorCode.InternalError, 'sampling_response_unparseable', {
reason: 'no text content returned by host',
})
}
let parsed: unknown
try {
parsed = JSON.parse(text)
} catch (err) {
throw new McpError(ErrorCode.InternalError, 'sampling_response_unparseable', {
raw: text,
reason: err instanceof Error ? err.message : String(err),
})
}
const validation = VisionResponseSchema.safeParse(parsed)
if (!validation.success) {
throw new McpError(ErrorCode.InternalError, 'sampling_response_invalid', {
raw: text,
errors: validation.error.issues,
})
}
return validation.data
}
type BuildResult = {
nodes: Record<AnyNodeId, AnyNodeT>
rootNodeIds: AnyNodeId[]
walls: number
rooms: number
warnings: string[]
levelId: AnyNodeId
}
/**
* Build a SceneGraph (flat `nodes` dict + `rootNodeIds`) from the vision
* response. Uses the schema factories for every node so IDs, defaults, and
* parent linkage match what the core store would produce. Each node is
* revalidated via `AnyNode.safeParse`; failures are dropped with a warning.
*/
function buildSceneGraphFromVision(
vision: VisionResponse,
defaultWallThickness: number,
defaultWallHeight: number,
): BuildResult {
const warnings: string[] = []
// Build the skeleton: site → building → level.
const building = BuildingNode.parse({})
const level = LevelNode.parse({ level: 0 })
const site = SiteNode.parse({ children: [building] })
// Link parent ids so downstream traversal works.
const siteId = site.id as AnyNodeId
const buildingId = building.id as AnyNodeId
const levelId = level.id as AnyNodeId
const linkedBuilding: AnyNodeT = {
...(building as AnyNodeT),
parentId: siteId,
}
const linkedLevel: AnyNodeT = {
...(level as AnyNodeT),
parentId: buildingId,
}
// BuildingNode children stores level ids (string[]).
;(linkedBuilding as BuildingNode).children = [levelId as BuildingNode['children'][number]]
// Collect level children (ids of walls/zones we create below).
const levelChildren: string[] = []
const nodes: Record<AnyNodeId, AnyNodeT> = {}
// Validate + add site, building, level in that order.
const siteValidated = AnyNode.safeParse(site)
if (!siteValidated.success) {
warnings.push(`site node failed schema validation: ${siteValidated.error.message}`)
}
nodes[siteId] = (siteValidated.success ? siteValidated.data : site) as AnyNodeT
const buildingValidated = AnyNode.safeParse(linkedBuilding)
if (!buildingValidated.success) {
warnings.push(`building node failed schema validation: ${buildingValidated.error.message}`)
}
nodes[buildingId] = (
buildingValidated.success ? buildingValidated.data : linkedBuilding
) as AnyNodeT
// Walls.
let wallsAdded = 0
for (let i = 0; i < vision.walls.length; i++) {
const w = vision.walls[i]!
try {
const wall = WallNode.parse({
start: w.start,
end: w.end,
thickness: w.thickness ?? defaultWallThickness,
height: defaultWallHeight,
})
const linkedWall: AnyNodeT = {
...(wall as AnyNodeT),
parentId: levelId,
}
const validated = AnyNode.safeParse(linkedWall)
if (!validated.success) {
warnings.push(`wall[${i}] dropped: ${validated.error.message}`)
continue
}
nodes[wall.id as AnyNodeId] = validated.data as AnyNodeT
levelChildren.push(wall.id)
wallsAdded++
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
warnings.push(`wall[${i}] dropped: ${msg}`)
}
}
// Rooms → zones.
let roomsAdded = 0
for (let i = 0; i < vision.rooms.length; i++) {
const r = vision.rooms[i]!
try {
const zone = ZoneNode.parse({
name: r.name,
polygon: r.polygon,
})
const linkedZone: AnyNodeT = {
...(zone as AnyNodeT),
parentId: levelId,
}
const validated = AnyNode.safeParse(linkedZone)
if (!validated.success) {
warnings.push(`room[${i}] dropped: ${validated.error.message}`)
continue
}
nodes[zone.id as AnyNodeId] = validated.data as AnyNodeT
levelChildren.push(zone.id)
roomsAdded++
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
warnings.push(`room[${i}] dropped: ${msg}`)
}
}
// Finalise the level's children array now that walls/zones are in the dict.
;(linkedLevel as LevelNode).children = levelChildren as LevelNode['children']
const levelValidated = AnyNode.safeParse(linkedLevel)
if (!levelValidated.success) {
warnings.push(`level node failed schema validation: ${levelValidated.error.message}`)
}
nodes[levelId] = (levelValidated.success ? levelValidated.data : linkedLevel) as AnyNodeT
return {
nodes,
rootNodeIds: [siteId],
walls: wallsAdded,
rooms: roomsAdded,
warnings,
levelId,
}
}
export function registerPhotoToScene(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
server.registerTool(
'photo_to_scene',
{
title: 'Photo to Pascal scene',
description:
'Orchestrator: analyse a floor-plan photo via MCP sampling, translate the structured vision result into a Pascal SceneGraph (site → building → level with walls and zones), optionally save it, and swap the bridge to the new scene. Requires host support for sampling.',
inputSchema: photoToSceneInput,
outputSchema: photoToSceneOutput,
},
async ({ image, scaleHint, name, save, defaultWallThickness, defaultWallHeight }) => {
// 1. Vision.
const vision = await callVisionSampling(server, image, scaleHint)
// 2. Build scene graph.
const built = buildSceneGraphFromVision(vision, defaultWallThickness, defaultWallHeight)
const graph: SceneGraph = {
nodes: built.nodes as SceneGraph['nodes'],
rootNodeIds: built.rootNodeIds as SceneGraph['rootNodeIds'],
collections: {} as SceneGraph['collections'],
}
// 5. Swap the bridge to the new scene so follow-up MCP calls operate on it.
bridge.setScene(graph.nodes, graph.rootNodeIds)
const notes = built.warnings.length > 0 ? built.warnings.join('; ') : undefined
// 4. Save or return inline.
if (save) {
const meta = await store.save({
name,
graph,
})
const payload: {
sceneId: string
url: string
walls: number
rooms: number
confidence: number
notes?: string
} = {
sceneId: meta.id,
url: `/scene/${meta.id}`,
walls: built.walls,
rooms: built.rooms,
confidence: vision.confidence,
}
if (notes) payload.notes = notes
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
}
const payload: {
walls: number
rooms: number
confidence: number
notes?: string
graph: SceneGraph
} = {
walls: built.walls,
rooms: built.rooms,
confidence: vision.confidence,
graph,
}
if (notes) payload.notes = notes
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
},
)
}
@@ -0,0 +1,56 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { registerDeleteScene } from './delete-scene'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
const emptyGraph: SceneGraph = { nodes: {}, rootNodeIds: [] }
describe('delete_scene', () => {
let client: Client
let store: InMemorySceneStore
beforeEach(async () => {
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerDeleteScene(server, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('deletes an existing scene and returns { deleted: true }', async () => {
await store.save({ id: 'gone-in-60', name: 'Expendable', graph: emptyGraph })
const result = await client.callTool({
name: 'delete_scene',
arguments: { id: 'gone-in-60' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.deleted).toBe(true)
expect(await store.load('gone-in-60')).toBeNull()
})
test('throws scene_not_found when deleting an unknown id', async () => {
const result = await client.callTool({
name: 'delete_scene',
arguments: { id: 'ghost' },
})
expect(result.isError).toBe(true)
})
test('throws version_conflict when expectedVersion mismatches', async () => {
await store.save({ id: 'locked', name: 'Locked', graph: emptyGraph })
const result = await client.callTool({
name: 'delete_scene',
arguments: { id: 'locked', expectedVersion: 99 },
})
expect(result.isError).toBe(true)
// Still present after failed delete.
expect(await store.load('locked')).not.toBeNull()
})
})
@@ -0,0 +1,50 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import { SceneNotFoundError, type SceneStore, SceneVersionConflictError } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
export const deleteSceneInput = {
id: z.string().min(1).max(64),
expectedVersion: z.number().int().positive().optional(),
}
export const deleteSceneOutput = {
deleted: z.boolean(),
}
export function registerDeleteScene(server: McpServer, store: SceneStore): void {
server.registerTool(
'delete_scene',
{
title: 'Delete scene',
description:
'Delete a scene from the SceneStore by id. Optionally pass `expectedVersion` for optimistic concurrency.',
inputSchema: deleteSceneInput,
outputSchema: deleteSceneOutput,
},
async ({ id, expectedVersion }) => {
try {
const deleted = await store.delete(id, {
...(expectedVersion !== undefined ? { expectedVersion } : {}),
})
const payload = { deleted }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
if (err instanceof SceneNotFoundError) {
throwMcpError(ErrorCode.InvalidParams, 'scene_not_found', { id })
}
if (err instanceof SceneVersionConflictError) {
throwMcpError(ErrorCode.InvalidRequest, 'version_conflict', {
id,
expectedVersion,
})
}
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, msg)
}
},
)
}
@@ -0,0 +1,32 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { registerDeleteScene } from './delete-scene'
import { registerListScenes } from './list-scenes'
import { registerLoadScene } from './load-scene'
import { registerRenameScene } from './rename-scene'
import { registerSaveScene } from './save-scene'
/**
* Register the scene-lifecycle MCP tools (`save_scene`, `load_scene`,
* `list_scenes`, `delete_scene`, `rename_scene`) against the given server.
* All tools operate against the supplied `SceneStore` so tests can inject an
* in-memory implementation.
*/
export function registerSceneLifecycleTools(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
registerSaveScene(server, bridge, store)
registerLoadScene(server, bridge, store)
registerListScenes(server, store)
registerDeleteScene(server, store)
registerRenameScene(server, store)
}
export { deleteSceneInput, deleteSceneOutput, registerDeleteScene } from './delete-scene'
export { listScenesInput, listScenesOutput, registerListScenes } from './list-scenes'
export { loadSceneInput, loadSceneOutput, registerLoadScene } from './load-scene'
export { registerRenameScene, renameSceneInput, renameSceneOutput } from './rename-scene'
export { registerSaveScene, saveSceneInput, saveSceneOutput } from './save-scene'
@@ -0,0 +1,73 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { registerListScenes } from './list-scenes'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
const emptyGraph: SceneGraph = { nodes: {}, rootNodeIds: [] }
describe('list_scenes', () => {
let client: Client
let store: InMemorySceneStore
beforeEach(async () => {
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerListScenes(server, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('returns all saved scenes by default', async () => {
await store.save({ id: 'a', name: 'A', graph: emptyGraph })
await store.save({ id: 'b', name: 'B', graph: emptyGraph })
const result = await client.callTool({
name: 'list_scenes',
arguments: {},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
const scenes = parsed.scenes as unknown[]
expect(scenes).toHaveLength(2)
})
test('filters by projectId', async () => {
await store.save({ id: 'a', name: 'A', projectId: 'p1', graph: emptyGraph })
await store.save({ id: 'b', name: 'B', projectId: 'p2', graph: emptyGraph })
const result = await client.callTool({
name: 'list_scenes',
arguments: { projectId: 'p1' },
})
const parsed = parseToolText(result.content as StoredTextContent[])
const scenes = parsed.scenes as { id: string }[]
expect(scenes).toHaveLength(1)
expect(scenes[0]!.id).toBe('a')
})
test('rejects non-positive limit per schema', async () => {
const result = await client.callTool({
name: 'list_scenes',
arguments: { limit: 0 },
})
expect(result.isError).toBe(true)
})
test('caps results with limit', async () => {
await store.save({ id: 'a', name: 'A', graph: emptyGraph })
await store.save({ id: 'b', name: 'B', graph: emptyGraph })
await store.save({ id: 'c', name: 'C', graph: emptyGraph })
const result = await client.callTool({
name: 'list_scenes',
arguments: { limit: 2 },
})
const parsed = parseToolText(result.content as StoredTextContent[])
const scenes = parsed.scenes as unknown[]
expect(scenes).toHaveLength(2)
})
})
@@ -0,0 +1,57 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import type { SceneStore } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
const DEFAULT_LIMIT = 100
export const listScenesInput = {
projectId: z.string().optional(),
limit: z.number().int().positive().max(1000).optional(),
}
export const listScenesOutput = {
scenes: z.array(
z.object({
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
}),
),
}
export function registerListScenes(server: McpServer, store: SceneStore): void {
server.registerTool(
'list_scenes',
{
title: 'List scenes',
description:
'List scenes in the SceneStore. Optionally filter by `projectId` and cap results with `limit` (default 100).',
inputSchema: listScenesInput,
outputSchema: listScenesOutput,
},
async ({ projectId, limit }) => {
try {
const scenes = await store.list({
...(projectId !== undefined ? { projectId } : {}),
limit: limit ?? DEFAULT_LIMIT,
})
const payload = { scenes }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, msg)
}
},
)
}
@@ -0,0 +1,64 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { SceneBridge } from '../../bridge/scene-bridge'
import { registerLoadScene } from './load-scene'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
describe('load_scene', () => {
let client: Client
let bridge: SceneBridge
let store: InMemorySceneStore
beforeEach(async () => {
bridge = new SceneBridge()
bridge.setScene({}, [])
bridge.loadDefault()
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerLoadScene(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('loads a stored scene and returns its SceneMeta', async () => {
const graph = {
nodes: {
root_a: { id: 'root_a', type: 'site', parentId: null, children: [] },
},
rootNodeIds: ['root_a'],
} as unknown as SceneGraph
const meta = await store.save({ id: 'scene-one', name: 'One', graph })
const result = await client.callTool({
name: 'load_scene',
arguments: { id: 'scene-one' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.id).toBe('scene-one')
expect(parsed.name).toBe('One')
expect(parsed.version).toBe(meta.version)
expect(bridge.getRootNodeIds()).toContain('root_a')
})
test('throws scene_not_found when id is unknown', async () => {
const result = await client.callTool({
name: 'load_scene',
arguments: { id: 'does-not-exist' },
})
expect(result.isError).toBe(true)
})
test('rejects empty id per schema', async () => {
const result = await client.callTool({
name: 'load_scene',
arguments: { id: '' },
})
expect(result.isError).toBe(true)
})
})
@@ -0,0 +1,63 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
export const loadSceneInput = {
id: z.string().min(1).max(64),
}
export const loadSceneOutput = {
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
}
export function registerLoadScene(server: McpServer, bridge: SceneBridge, store: SceneStore): void {
server.registerTool(
'load_scene',
{
title: 'Load scene',
description:
'Load a scene from the SceneStore into the bridge. Returns the scene metadata. Throws `scene_not_found` if the id does not exist.',
inputSchema: loadSceneInput,
outputSchema: loadSceneOutput,
},
async ({ id }) => {
const result = await store.load(id)
if (!result) {
throwMcpError(ErrorCode.InvalidParams, 'scene_not_found', { id })
}
try {
bridge.loadJSON(result.graph)
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InvalidRequest, `load_failed: ${msg}`, { id })
}
const payload = {
id: result.id,
name: result.name,
projectId: result.projectId,
thumbnailUrl: result.thumbnailUrl,
version: result.version,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
ownerId: result.ownerId,
sizeBytes: result.sizeBytes,
nodeCount: result.nodeCount,
}
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
},
)
}
@@ -0,0 +1,59 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { registerRenameScene } from './rename-scene'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
const emptyGraph: SceneGraph = { nodes: {}, rootNodeIds: [] }
describe('rename_scene', () => {
let client: Client
let store: InMemorySceneStore
beforeEach(async () => {
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerRenameScene(server, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('renames a scene and returns the new SceneMeta', async () => {
await store.save({ id: 'to-rename', name: 'Old Name', graph: emptyGraph })
const result = await client.callTool({
name: 'rename_scene',
arguments: { id: 'to-rename', newName: 'Brand New Name' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.id).toBe('to-rename')
expect(parsed.name).toBe('Brand New Name')
expect(parsed.version).toBe(2)
})
test('throws scene_not_found for missing ids', async () => {
const result = await client.callTool({
name: 'rename_scene',
arguments: { id: 'ghost', newName: 'Does Not Matter' },
})
expect(result.isError).toBe(true)
})
test('throws version_conflict when expectedVersion mismatches', async () => {
await store.save({ id: 'locked-name', name: 'Stable', graph: emptyGraph })
const result = await client.callTool({
name: 'rename_scene',
arguments: {
id: 'locked-name',
newName: 'Attempted',
expectedVersion: 42,
},
})
expect(result.isError).toBe(true)
})
})
@@ -0,0 +1,71 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import { SceneNotFoundError, type SceneStore, SceneVersionConflictError } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
export const renameSceneInput = {
id: z.string().min(1).max(64),
newName: z.string().min(1).max(200),
expectedVersion: z.number().int().positive().optional(),
}
export const renameSceneOutput = {
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
}
export function registerRenameScene(server: McpServer, store: SceneStore): void {
server.registerTool(
'rename_scene',
{
title: 'Rename scene',
description:
'Rename a scene in the SceneStore. Returns the updated SceneMeta. Optionally pass `expectedVersion` for optimistic concurrency.',
inputSchema: renameSceneInput,
outputSchema: renameSceneOutput,
},
async ({ id, newName, expectedVersion }) => {
try {
const meta = await store.rename(id, newName, {
...(expectedVersion !== undefined ? { expectedVersion } : {}),
})
const payload = {
id: meta.id,
name: meta.name,
projectId: meta.projectId,
thumbnailUrl: meta.thumbnailUrl,
version: meta.version,
createdAt: meta.createdAt,
updatedAt: meta.updatedAt,
ownerId: meta.ownerId,
sizeBytes: meta.sizeBytes,
nodeCount: meta.nodeCount,
}
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
if (err instanceof SceneNotFoundError) {
throwMcpError(ErrorCode.InvalidParams, 'scene_not_found', { id })
}
if (err instanceof SceneVersionConflictError) {
throwMcpError(ErrorCode.InvalidRequest, 'version_conflict', {
id,
expectedVersion,
})
}
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, msg)
}
},
)
}
@@ -0,0 +1,83 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { SceneBridge } from '../../bridge/scene-bridge'
import { registerSaveScene } from './save-scene'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
describe('save_scene', () => {
let client: Client
let bridge: SceneBridge
let store: InMemorySceneStore
beforeEach(async () => {
bridge = new SceneBridge()
bridge.setScene({}, [])
bridge.loadDefault()
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerSaveScene(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('saves the current scene and returns SceneMeta with url', async () => {
const result = await client.callTool({
name: 'save_scene',
arguments: { name: 'My Scene' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.name).toBe('My Scene')
expect(typeof parsed.id).toBe('string')
expect(parsed.version).toBe(1)
expect(parsed.url).toBe(`/scene/${parsed.id}`)
expect(parsed.nodeCount).toBeGreaterThan(0)
})
test('saves a provided graph when includeCurrentScene is false', async () => {
const graph = {
nodes: { root: { id: 'root', type: 'site', parentId: null, children: [] } },
rootNodeIds: ['root'],
}
const result = await client.callTool({
name: 'save_scene',
arguments: {
name: 'From Graph',
includeCurrentScene: false,
graph,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.name).toBe('From Graph')
expect(parsed.nodeCount).toBe(1)
})
test('errors when includeCurrentScene is false and no graph is provided', async () => {
const result = await client.callTool({
name: 'save_scene',
arguments: { name: 'No Graph', includeCurrentScene: false },
})
expect(result.isError).toBe(true)
})
test('returns version_conflict when expectedVersion mismatches', async () => {
const first = await client.callTool({
name: 'save_scene',
arguments: { name: 'Original' },
})
const parsed = parseToolText(first.content as StoredTextContent[])
const result = await client.callTool({
name: 'save_scene',
arguments: {
id: parsed.id as string,
name: 'Second',
expectedVersion: 99,
},
})
expect(result.isError).toBe(true)
})
})
@@ -0,0 +1,111 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import { type SceneStore, SceneVersionConflictError } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
export const saveSceneInput = {
id: z.string().min(1).max(64).optional(),
name: z.string().min(1).max(200),
projectId: z.string().optional(),
expectedVersion: z.number().int().positive().optional(),
thumbnail: z.string().url().optional(),
includeCurrentScene: z
.boolean()
.default(true)
.describe('If true, save the bridge current scene. If false, use the graph arg.'),
graph: z
.record(z.string(), z.unknown())
.optional()
.describe(
'Full SceneGraph { nodes, rootNodeIds, collections? } to save instead of the bridge state.',
),
}
export const saveSceneOutput = {
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
url: z.string(),
}
export function registerSaveScene(server: McpServer, bridge: SceneBridge, store: SceneStore): void {
server.registerTool(
'save_scene',
{
title: 'Save scene',
description:
'Persist the current scene (or a provided graph) to the SceneStore. Returns the SceneMeta along with a `url` pointing to `/scene/<id>`.',
inputSchema: saveSceneInput,
outputSchema: saveSceneOutput,
},
async ({ id, name, projectId, expectedVersion, thumbnail, includeCurrentScene, graph }) => {
let sceneGraph: SceneGraph
if (includeCurrentScene) {
const validation = bridge.validateScene()
if (!validation.valid) {
throwMcpError(ErrorCode.InvalidRequest, 'scene_invalid', { errors: validation.errors })
}
const exported = bridge.exportJSON()
sceneGraph = {
nodes: exported.nodes,
rootNodeIds: exported.rootNodeIds,
collections: exported.collections as SceneGraph['collections'],
}
} else {
if (!graph) {
throwMcpError(
ErrorCode.InvalidParams,
'graph_required: pass `graph` when includeCurrentScene is false',
)
}
sceneGraph = graph as unknown as SceneGraph
}
try {
const meta = await store.save({
...(id !== undefined ? { id } : {}),
name,
...(projectId !== undefined ? { projectId } : {}),
graph: sceneGraph,
...(thumbnail !== undefined ? { thumbnailUrl: thumbnail } : {}),
...(expectedVersion !== undefined ? { expectedVersion } : {}),
})
const payload = {
id: meta.id,
name: meta.name,
projectId: meta.projectId,
thumbnailUrl: meta.thumbnailUrl,
version: meta.version,
createdAt: meta.createdAt,
updatedAt: meta.updatedAt,
ownerId: meta.ownerId,
sizeBytes: meta.sizeBytes,
nodeCount: meta.nodeCount,
url: `/scene/${meta.id}`,
}
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
if (err instanceof SceneVersionConflictError) {
throwMcpError(ErrorCode.InvalidRequest, 'version_conflict', {
expectedVersion,
id,
})
}
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InvalidRequest, msg)
}
},
)
}
@@ -0,0 +1,146 @@
import {
type SceneListOptions,
type SceneMeta,
type SceneMutateOptions,
SceneNotFoundError,
type SceneSaveOptions,
type SceneStore,
SceneVersionConflictError,
type SceneWithGraph,
} from '../../storage/types'
export type StoredTextContent = { type: string; text: string }
export function parseToolText(content: StoredTextContent[]): Record<string, unknown> {
return JSON.parse(content[0]!.text) as Record<string, unknown>
}
/**
* In-memory `SceneStore` for tests. Backed by a plain `Map` keyed by id.
* Implements the full interface including optimistic concurrency via
* `expectedVersion`.
*/
export class InMemorySceneStore implements SceneStore {
readonly backend = 'filesystem' as const
private readonly data = new Map<string, SceneWithGraph>()
private idCounter = 0
async save(opts: SceneSaveOptions): Promise<SceneMeta> {
const existing = opts.id ? this.data.get(opts.id) : undefined
if (existing) {
if (opts.expectedVersion !== undefined && existing.version !== opts.expectedVersion) {
throw new SceneVersionConflictError(
`Expected version ${opts.expectedVersion}, have ${existing.version}`,
)
}
const now = new Date().toISOString()
const nodeCount = Object.keys(opts.graph.nodes ?? {}).length
const serialized = JSON.stringify(opts.graph)
const updated: SceneWithGraph = {
id: existing.id,
name: opts.name,
projectId: opts.projectId ?? existing.projectId,
thumbnailUrl: opts.thumbnailUrl ?? existing.thumbnailUrl,
version: existing.version + 1,
createdAt: existing.createdAt,
updatedAt: now,
ownerId: opts.ownerId ?? existing.ownerId,
sizeBytes: serialized.length,
nodeCount,
graph: opts.graph,
}
this.data.set(existing.id, updated)
return this.toMeta(updated)
}
if (opts.expectedVersion !== undefined) {
throw new SceneVersionConflictError('Cannot pass expectedVersion for a new scene')
}
const id = opts.id ?? `scene_${++this.idCounter}`
const now = new Date().toISOString()
const serialized = JSON.stringify(opts.graph)
const nodeCount = Object.keys(opts.graph.nodes ?? {}).length
const record: SceneWithGraph = {
id,
name: opts.name,
projectId: opts.projectId ?? null,
thumbnailUrl: opts.thumbnailUrl ?? null,
version: 1,
createdAt: now,
updatedAt: now,
ownerId: opts.ownerId ?? null,
sizeBytes: serialized.length,
nodeCount,
graph: opts.graph,
}
this.data.set(id, record)
return this.toMeta(record)
}
async load(id: string): Promise<SceneWithGraph | null> {
const rec = this.data.get(id)
if (!rec) return null
return {
...rec,
graph: JSON.parse(JSON.stringify(rec.graph)),
}
}
async list(opts?: SceneListOptions): Promise<SceneMeta[]> {
let scenes = Array.from(this.data.values()).map((r) => this.toMeta(r))
if (opts?.projectId !== undefined) {
scenes = scenes.filter((s) => s.projectId === opts.projectId)
}
if (opts?.ownerId !== undefined) {
scenes = scenes.filter((s) => s.ownerId === opts.ownerId)
}
scenes.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1))
if (opts?.limit !== undefined) scenes = scenes.slice(0, opts.limit)
return scenes
}
async delete(id: string, opts?: SceneMutateOptions): Promise<boolean> {
const rec = this.data.get(id)
if (!rec) throw new SceneNotFoundError(`Scene ${id} not found`)
if (opts?.expectedVersion !== undefined && rec.version !== opts.expectedVersion) {
throw new SceneVersionConflictError(
`Expected version ${opts.expectedVersion}, have ${rec.version}`,
)
}
return this.data.delete(id)
}
async rename(id: string, newName: string, opts?: SceneMutateOptions): Promise<SceneMeta> {
const rec = this.data.get(id)
if (!rec) throw new SceneNotFoundError(`Scene ${id} not found`)
if (opts?.expectedVersion !== undefined && rec.version !== opts.expectedVersion) {
throw new SceneVersionConflictError(
`Expected version ${opts.expectedVersion}, have ${rec.version}`,
)
}
const updated: SceneWithGraph = {
...rec,
name: newName,
version: rec.version + 1,
updatedAt: new Date().toISOString(),
}
this.data.set(id, updated)
return this.toMeta(updated)
}
private toMeta(rec: SceneWithGraph): SceneMeta {
return {
id: rec.id,
name: rec.name,
projectId: rec.projectId,
thumbnailUrl: rec.thumbnailUrl,
version: rec.version,
createdAt: rec.createdAt,
updatedAt: rec.updatedAt,
ownerId: rec.ownerId,
sizeBytes: rec.sizeBytes,
nodeCount: rec.nodeCount,
}
}
}
@@ -0,0 +1,154 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { cloneSceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNode, AnyNodeId } from '@pascal-app/core/schema'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import { rehydrateSiteChildren } from '../../lib/rehydrate-site-children'
import type { SceneStore } from '../../storage/types'
import { isTemplateId, TEMPLATES, type TemplateId } from '../../templates'
import { ErrorCode, throwMcpError } from '../errors'
export const createFromTemplateInput = {
id: z
.string()
.describe(
'Template id (see `list_templates`). Currently one of: "empty-studio", "two-bedroom", "garden-house".',
),
name: z
.string()
.min(1)
.max(200)
.optional()
.describe('Optional display name for the saved scene. Defaults to the template name.'),
/**
* When a `SceneStore` is wired into the MCP server, set this flag to `true`
* to immediately save the instantiated template and return its `SceneMeta`.
* When `false` (default) the template is applied to the bridge only.
*/
save: z.boolean().default(false),
projectId: z.string().optional(),
}
export const createFromTemplateOutput = {
templateId: z.string(),
rootNodeIds: z.array(z.string()),
nodeCount: z.number(),
/** Present when `save: true` (and a store was available). */
scene: z
.object({
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
url: z.string(),
})
.optional(),
}
/**
* `create_from_template` — instantiate a seed template into the bridge, and
* optionally persist it via the attached `SceneStore`.
*
* The source template is cloned with fresh ids (`cloneSceneGraph`) so the
* deterministic placeholders (`site_empty`, `wall_n`, …) don't collide
* across repeated calls or with other scenes.
*/
export function registerCreateFromTemplate(
server: McpServer,
bridge: SceneBridge,
store?: SceneStore,
): void {
server.registerTool(
'create_from_template',
{
title: 'Create scene from template',
description:
'Instantiate a seed Pascal scene template into the bridge. Regenerates all ids before applying. When `save: true` and a SceneStore is wired, also persists the new scene and returns the SceneMeta.',
inputSchema: createFromTemplateInput,
outputSchema: createFromTemplateOutput,
},
async ({ id, name, save, projectId }) => {
if (!isTemplateId(id)) {
throwMcpError(
ErrorCode.InvalidParams,
`unknown_template: ${id}. Call list_templates for the set of valid ids.`,
)
}
const entry = TEMPLATES[id as TemplateId]
// Clone: regenerate ids so each instantiation is independent.
// `cloneSceneGraph` flattens SiteNode.children to string ids; rehydrate
// them back to embedded objects to satisfy the SiteNode schema (see
// CROSS_CUTTING §2).
const cloned = rehydrateSiteChildren(cloneSceneGraph(entry.template))
const nodes = cloned.nodes as Record<AnyNodeId, AnyNode>
const rootNodeIds = cloned.rootNodeIds as AnyNodeId[]
try {
bridge.setScene(nodes, rootNodeIds)
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, `apply_failed: ${msg}`)
}
const basePayload = {
templateId: entry.id,
rootNodeIds: rootNodeIds as string[],
nodeCount: Object.keys(nodes).length,
}
if (!save) {
return {
content: [{ type: 'text' as const, text: JSON.stringify(basePayload) }],
structuredContent: basePayload,
}
}
if (!store) {
// Graceful no-store mode: report that save was skipped rather than
// erroring — this makes the tool usable in headless bridge-only
// deployments (tests, smoke scripts) without crashing.
const payload = { ...basePayload, saveSkipped: true } as const
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: basePayload,
}
}
try {
const meta = await store.save({
name: name ?? entry.name,
...(projectId !== undefined ? { projectId } : {}),
graph: { nodes, rootNodeIds },
})
const scene = {
id: meta.id,
name: meta.name,
projectId: meta.projectId,
thumbnailUrl: meta.thumbnailUrl,
version: meta.version,
createdAt: meta.createdAt,
updatedAt: meta.updatedAt,
ownerId: meta.ownerId,
sizeBytes: meta.sizeBytes,
nodeCount: meta.nodeCount,
url: `/scene/${meta.id}`,
}
const payload = { ...basePayload, scene }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, `save_failed: ${msg}`)
}
},
)
}
+33
View File
@@ -0,0 +1,33 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { registerCreateFromTemplate } from './create-from-template'
import { registerListTemplates } from './list-templates'
/**
* Register the template MCP tools (`list_templates`, `create_from_template`)
* against the given server.
*
* `store` is optional: when omitted, `create_from_template` still applies the
* template to the bridge but skips the save step. This makes the tool safe
* to wire into headless bridge-only deployments.
*/
export function registerTemplateTools(
server: McpServer,
bridge: SceneBridge,
store?: SceneStore,
): void {
registerListTemplates(server)
registerCreateFromTemplate(server, bridge, store)
}
export {
createFromTemplateInput,
createFromTemplateOutput,
registerCreateFromTemplate,
} from './create-from-template'
export {
listTemplatesInput,
listTemplatesOutput,
registerListTemplates,
} from './list-templates'
@@ -0,0 +1,47 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import { TEMPLATES } from '../../templates'
export const listTemplatesInput = {} as const
export const listTemplatesOutput = {
templates: z.array(
z.object({
id: z.string(),
name: z.string(),
description: z.string(),
nodeCount: z.number(),
}),
),
}
/**
* `list_templates` — enumerate the seed templates shipped with the MCP server.
* Stateless; used by the `from_brief` prompt and by the UI to populate a
* "start from a template" picker.
*/
export function registerListTemplates(server: McpServer): void {
server.registerTool(
'list_templates',
{
title: 'List scene templates',
description:
'List the seed Pascal scene templates available to `create_from_template`. Returns the id, display name, one-line description and node count for each.',
inputSchema: listTemplatesInput,
outputSchema: listTemplatesOutput,
},
async () => {
const templates = Object.values(TEMPLATES).map((entry) => ({
id: entry.id,
name: entry.name,
description: entry.description,
nodeCount: Object.keys(entry.template.nodes).length,
}))
const payload = { templates }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
},
)
}
@@ -0,0 +1,169 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { SceneBridge } from '../../bridge/scene-bridge'
import {
InMemorySceneStore,
parseToolText,
type StoredTextContent,
} from '../scene-lifecycle/test-utils'
import { registerCreateFromTemplate } from './create-from-template'
import { registerListTemplates } from './list-templates'
describe('list_templates', () => {
let client: Client
beforeEach(async () => {
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerListTemplates(server)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('enumerates all three seed templates', async () => {
const result = await client.callTool({ name: 'list_templates', arguments: {} })
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
const list = parsed.templates as Array<{
id: string
name: string
description: string
nodeCount: number
}>
const ids = list.map((t) => t.id).sort()
expect(ids).toEqual(['empty-studio', 'garden-house', 'two-bedroom'])
for (const t of list) {
expect(typeof t.name).toBe('string')
expect(t.name.length).toBeGreaterThan(0)
expect(typeof t.description).toBe('string')
expect(t.nodeCount).toBeGreaterThan(0)
}
})
test('returns structuredContent matching the text payload', async () => {
const result = await client.callTool({ name: 'list_templates', arguments: {} })
expect(result.structuredContent).toBeDefined()
const structured = result.structuredContent as { templates: Array<{ id: string }> }
expect(structured.templates.length).toBe(3)
})
})
describe('create_from_template', () => {
let client: Client
let bridge: SceneBridge
let store: InMemorySceneStore
beforeEach(async () => {
bridge = new SceneBridge()
bridge.setScene({}, [])
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerCreateFromTemplate(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('applies a template to the bridge with fresh ids', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'empty-studio' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.templateId).toBe('empty-studio')
expect((parsed.rootNodeIds as string[]).length).toBeGreaterThan(0)
expect(parsed.nodeCount as number).toBeGreaterThan(0)
// Fresh ids — placeholder "site_empty" should not appear.
const bridgeNodes = Object.keys(bridge.getNodes())
expect(bridgeNodes).not.toContain('site_empty')
expect(bridgeNodes.length).toBeGreaterThan(0)
// Root id from the tool response should exist in the bridge.
for (const rid of parsed.rootNodeIds as string[]) {
expect(bridge.getNode(rid as any)).not.toBeNull()
}
})
test('rejects unknown template ids', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'not-a-template' },
})
expect(result.isError).toBe(true)
})
test('saves to the store when save: true', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'two-bedroom', save: true, name: 'My flat' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.scene).toBeDefined()
const scene = parsed.scene as { id: string; name: string; url: string; nodeCount: number }
expect(scene.name).toBe('My flat')
expect(scene.url).toBe(`/scene/${scene.id}`)
expect(scene.nodeCount).toBeGreaterThan(0)
// Confirm the store actually holds it.
const loaded = await store.load(scene.id)
expect(loaded).not.toBeNull()
})
test('two invocations produce disjoint id sets', async () => {
const a = await client.callTool({
name: 'create_from_template',
arguments: { id: 'empty-studio' },
})
const idsA = (parseToolText(a.content as StoredTextContent[]).rootNodeIds as string[]).sort()
const b = await client.callTool({
name: 'create_from_template',
arguments: { id: 'empty-studio' },
})
const idsB = (parseToolText(b.content as StoredTextContent[]).rootNodeIds as string[]).sort()
for (const id of idsA) {
expect(idsB).not.toContain(id)
}
})
})
describe('create_from_template without a store', () => {
let client: Client
let bridge: SceneBridge
beforeEach(async () => {
bridge = new SceneBridge()
bridge.setScene({}, [])
const server = new McpServer({ name: 'test', version: '0.0.0' })
// No store passed → save should be gracefully skipped.
registerCreateFromTemplate(server, bridge)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('applies a template without erroring when no store is wired', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'garden-house' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.templateId).toBe('garden-house')
})
test('save:true is a no-op but still succeeds without a store', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'garden-house', save: true },
})
// Does not error; no `scene` field is returned because there is no store.
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.scene).toBeUndefined()
})
})
@@ -0,0 +1,295 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { type AnyNodeId, AnyNode as AnyNodeSchema } from '@pascal-app/core/schema'
import { SceneBridge } from '../../bridge/scene-bridge'
import {
InMemorySceneStore,
parseToolText,
type StoredTextContent,
} from '../scene-lifecycle/test-utils'
import { registerGenerateVariants } from './generate-variants'
type Variant = {
index: number
description: string
nodeCount: number
sceneId?: string
url?: string
graph?: SceneGraph
}
function emptyBase(): SceneGraph {
return {
nodes: {
site_empty: {
object: 'node',
id: 'site_empty',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-5, -5],
[5, -5],
[5, 5],
[-5, 5],
],
},
children: [],
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: ['site_empty'] as AnyNodeId[],
}
}
async function setup(): Promise<{
client: Client
bridge: SceneBridge
store: InMemorySceneStore
}> {
const bridge = new SceneBridge()
bridge.setScene({}, [])
bridge.loadDefault()
const store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerGenerateVariants(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
const client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
return { client, bridge, store }
}
describe('generate_variants', () => {
let client: Client
let bridge: SceneBridge
let store: InMemorySceneStore
beforeEach(async () => {
;({ client, bridge, store } = await setup())
})
test('happy path: returns count variants that exercise the mutation', async () => {
// Seed the bridge scene with some walls of known thickness.
const base = bridge.exportJSON()
// Find the level and add a couple of walls.
const level = Object.values(base.nodes).find((n) => n.type === 'level')
expect(level).toBeDefined()
const withWalls: SceneGraph = {
nodes: {
...base.nodes,
wall_1: {
object: 'node',
id: 'wall_1',
type: 'wall',
parentId: level?.id ?? null,
visible: true,
metadata: {},
start: [0, 0],
end: [5, 0],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_2: {
object: 'node',
id: 'wall_2',
type: 'wall',
parentId: level?.id ?? null,
visible: true,
metadata: {},
start: [0, 5],
end: [5, 5],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: base.rootNodeIds,
}
bridge.setScene(withWalls.nodes, withWalls.rootNodeIds)
const result = await client.callTool({
name: 'generate_variants',
arguments: {
count: 3,
vary: ['wall-thickness'],
seed: 42,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
expect(parsed.variants.length).toBe(3)
for (const v of parsed.variants) {
expect(v.graph).toBeDefined()
// Every wall's thickness is in the allowed set.
const allowed = new Set([0.1, 0.15, 0.2, 0.25])
for (const node of Object.values((v.graph as SceneGraph).nodes)) {
if (node.type !== 'wall') continue
expect(allowed.has((node as { thickness: number }).thickness)).toBe(true)
}
}
})
test('deterministic: same seed yields same mutation outputs', async () => {
// Seed walls so the mutation has something to act on.
const base = bridge.exportJSON()
const level = Object.values(base.nodes).find((n) => n.type === 'level')
const withWalls: SceneGraph = {
nodes: {
...base.nodes,
wall_a: {
object: 'node',
id: 'wall_a',
type: 'wall',
parentId: level?.id ?? null,
visible: true,
metadata: {},
start: [0, 0],
end: [4, 0],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_b: {
object: 'node',
id: 'wall_b',
type: 'wall',
parentId: level?.id ?? null,
visible: true,
metadata: {},
start: [0, 4],
end: [4, 4],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: base.rootNodeIds,
}
bridge.setScene(withWalls.nodes, withWalls.rootNodeIds)
const args = { count: 2, vary: ['wall-thickness'], seed: 123 }
const r1 = await client.callTool({ name: 'generate_variants', arguments: args })
const r2 = await client.callTool({ name: 'generate_variants', arguments: args })
const p1 = parseToolText(r1.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
const p2 = parseToolText(r2.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
expect(p1.variants.length).toBe(p2.variants.length)
// Compare the mutated fields (not the ids, which fresh-nanoid each time).
function wallThicknesses(g: SceneGraph): number[] {
return Object.values(g.nodes)
.filter((n) => n.type === 'wall')
.map((w) => (w as { thickness: number }).thickness)
.sort()
}
for (let i = 0; i < p1.variants.length; i++) {
const t1 = wallThicknesses(p1.variants[i]?.graph as SceneGraph)
const t2 = wallThicknesses(p2.variants[i]?.graph as SceneGraph)
expect(t1).toEqual(t2)
}
})
test('no-op: empty scene + wall-thickness still returns count graphs, unchanged', async () => {
const graph = emptyBase()
// Save, then reference by id.
const meta = await store.save({ name: 'empty', graph })
const result = await client.callTool({
name: 'generate_variants',
arguments: {
baseSceneId: meta.id,
count: 3,
vary: ['wall-thickness'],
seed: 99,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
expect(parsed.variants.length).toBe(3)
for (const v of parsed.variants) {
const g = v.graph as SceneGraph
expect(g).toBeDefined()
// No walls were present — so node counts should match the (forked) base.
expect(Object.keys(g.nodes).length).toBe(Object.keys(graph.nodes).length)
}
})
test('save=true: each variant gets a sceneId and url', async () => {
const result = await client.callTool({
name: 'generate_variants',
arguments: {
count: 2,
vary: ['wall-thickness'],
seed: 55,
save: true,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
expect(parsed.variants.length).toBe(2)
for (const v of parsed.variants) {
expect(typeof v.sceneId).toBe('string')
expect(v.url).toBe(`/scene/${v.sceneId}`)
// Inline graph should be omitted.
expect(v.graph).toBeUndefined()
}
const listed = await store.list()
expect(listed.length).toBe(2)
})
test('baseSceneId not found returns an error', async () => {
const result = await client.callTool({
name: 'generate_variants',
arguments: {
baseSceneId: 'scene_does_not_exist',
count: 2,
vary: ['wall-thickness'],
seed: 1,
},
})
expect(result.isError).toBe(true)
})
test('every returned variant validates against AnyNode', async () => {
const result = await client.callTool({
name: 'generate_variants',
arguments: {
count: 3,
vary: ['wall-thickness', 'wall-height'],
seed: 7,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
for (const v of parsed.variants) {
const g = v.graph as SceneGraph
for (const node of Object.values(g.nodes)) {
const res = AnyNodeSchema.safeParse(node)
expect(res.success).toBe(true)
}
}
})
})
@@ -0,0 +1,197 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { forkSceneGraph, type SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { type AnyNode, AnyNode as AnyNodeSchema } from '@pascal-app/core/schema'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
import { applyMutation, describeVariant, type MutationKind, mulberry32 } from './mutations'
const MUTATION_KINDS = [
'wall-thickness',
'wall-height',
'zone-labels',
'room-proportions',
'open-plan',
'door-positions',
'fence-style',
] as const
export const generateVariantsInput = {
baseSceneId: z
.string()
.optional()
.describe('If set, fork from this saved scene; else fork from current bridge state.'),
count: z.number().int().min(1).max(10).default(3),
vary: z.array(z.enum(MUTATION_KINDS)).min(1).default(['wall-thickness', 'wall-height']),
seed: z.number().int().optional().describe('Deterministic RNG seed.'),
save: z
.boolean()
.default(false)
.describe('If true, also save each variant via SceneStore and return ids.'),
}
export const generateVariantsOutput = {
variants: z.array(
z.object({
index: z.number(),
description: z.string(),
nodeCount: z.number(),
sceneId: z.string().optional(),
url: z.string().optional(),
graph: z.any().optional(),
}),
),
}
/**
* `forkSceneGraph` normalises `SiteNode.children` to string IDs, but the
* `SiteNode` schema declares that field as an array of full `BuildingNode` /
* `ItemNode` objects (see CROSS_CUTTING §2). To keep variants validating
* against `AnyNode`, re-embed the site children from the flat dict.
*
* Pure: returns a new graph without mutating the input.
*/
function rehydrateSiteChildren(graph: SceneGraph): SceneGraph {
const out: SceneGraph = {
nodes: { ...graph.nodes },
rootNodeIds: [...graph.rootNodeIds],
...(graph.collections ? { collections: graph.collections } : {}),
}
for (const [id, node] of Object.entries(out.nodes)) {
if (node.type !== 'site') continue
const childrenField = (node as { children?: unknown[] }).children
if (!Array.isArray(childrenField)) continue
const rehydrated: AnyNode[] = []
for (const child of childrenField) {
if (typeof child === 'string') {
const target = out.nodes[child as keyof typeof out.nodes]
if (target && (target.type === 'building' || target.type === 'item')) {
rehydrated.push(target)
}
} else if (child && typeof child === 'object' && 'id' in (child as Record<string, unknown>)) {
rehydrated.push(child as AnyNode)
}
}
out.nodes[id as keyof typeof out.nodes] = {
...(node as AnyNode),
children: rehydrated,
} as AnyNode
}
return out
}
/**
* Count how many nodes in a graph fail `AnyNode` validation. Used to keep the
* tool from returning silently corrupt variants.
*/
function countInvalidNodes(graph: SceneGraph): number {
let invalid = 0
for (const node of Object.values(graph.nodes)) {
if (!AnyNodeSchema.safeParse(node).success) invalid++
}
return invalid
}
export function registerGenerateVariants(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
server.registerTool(
'generate_variants',
{
title: 'Generate variants',
description:
'Generate N variations of a base scene by forking and applying seeded mutations. Example: "give me 5 variations of this kitchen". If `save=true`, each variant is persisted via the SceneStore and returned with an id + URL; otherwise the graph is returned inline.',
inputSchema: generateVariantsInput,
outputSchema: generateVariantsOutput,
},
async ({ baseSceneId, count, vary, seed, save }) => {
// 1. Obtain the base SceneGraph.
let base: SceneGraph
let baseName = 'scene'
if (baseSceneId) {
const loaded = await store.load(baseSceneId)
if (!loaded) {
throwMcpError(ErrorCode.InvalidParams, 'scene_not_found', { id: baseSceneId })
}
base = loaded.graph
baseName = loaded.name
} else {
const exported = bridge.exportJSON()
base = {
nodes: exported.nodes,
rootNodeIds: exported.rootNodeIds,
collections: exported.collections as SceneGraph['collections'],
}
}
// 2. Seed the RNG. Default seed is a time-ish number so runs vary, but
// tests always pass a fixed seed for determinism.
const initialSeed = seed ?? Math.floor(Math.random() * 0xffffffff)
const mutations = vary as MutationKind[]
const variants: Array<{
index: number
description: string
nodeCount: number
sceneId?: string
url?: string
graph?: SceneGraph
}> = []
for (let i = 0; i < count; i++) {
// Each variant gets its own RNG stream derived from (seed + i) so
// results are deterministic per-index.
const rng = mulberry32(initialSeed + i)
let forked: SceneGraph = forkSceneGraph(base)
for (const kind of mutations) {
forked = applyMutation(forked, rng, kind)
}
// Re-embed site children so variants match the SiteNode schema.
forked = rehydrateSiteChildren(forked)
const invalidCount = countInvalidNodes(forked)
if (invalidCount > 0) {
throwMcpError(
ErrorCode.InternalError,
`variant_invalid: variant ${i} produced ${invalidCount} invalid node(s)`,
{ index: i },
)
}
const nodeCount = Object.keys(forked.nodes).length
const description = describeVariant(forked, mutations)
if (save) {
try {
const meta = await store.save({
name: `${baseName}-variant-${i + 1}`,
graph: forked,
})
variants.push({
index: i,
description,
nodeCount,
sceneId: meta.id,
url: `/scene/${meta.id}`,
})
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, `save_failed: ${msg}`, { index: i })
}
} else {
variants.push({ index: i, description, nodeCount, graph: forked })
}
}
const payload = { variants }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
},
)
}
+30
View File
@@ -0,0 +1,30 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { registerGenerateVariants } from './generate-variants'
/**
* Register the variant-generation MCP tools against the given server. Uses the
* supplied `SceneStore` both to load a `baseSceneId` (when provided) and to
* persist variants when `save=true`.
*/
export function registerVariantTools(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
registerGenerateVariants(server, bridge, store)
}
export {
generateVariantsInput,
generateVariantsOutput,
registerGenerateVariants,
} from './generate-variants'
export {
applyMutation,
describeVariant,
type MutationKind,
mulberry32,
type Rng,
} from './mutations'
@@ -0,0 +1,409 @@
import { describe, expect, test } from 'bun:test'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNodeId } from '@pascal-app/core/schema'
import { applyMutation, mulberry32 } from './mutations'
function makeBaseGraph(): SceneGraph {
const nodes: SceneGraph['nodes'] = {
site_a: {
object: 'node',
id: 'site_a',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-10, -10],
[10, -10],
[10, 10],
[-10, 10],
],
},
children: [],
},
building_a: {
object: 'node',
id: 'building_a',
type: 'building',
parentId: 'site_a',
visible: true,
metadata: {},
position: [0, 0, 0],
rotation: [0, 0, 0],
children: ['level_a'],
},
level_a: {
object: 'node',
id: 'level_a',
type: 'level',
parentId: 'building_a',
visible: true,
metadata: {},
children: ['wall_n', 'wall_s', 'wall_e', 'wall_w', 'wall_mid', 'zone_kitchen', 'zone_living'],
},
wall_n: {
object: 'node',
id: 'wall_n',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [-10, 10],
end: [10, 10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_s: {
object: 'node',
id: 'wall_s',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [-10, -10],
end: [10, -10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_e: {
object: 'node',
id: 'wall_e',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [10, -10],
end: [10, 10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_w: {
object: 'node',
id: 'wall_w',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [-10, -10],
end: [-10, 10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_mid: {
object: 'node',
id: 'wall_mid',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [-5, 0],
end: [5, 0],
thickness: 0.1,
height: 2.5,
children: ['door_mid'],
frontSide: 'unknown',
backSide: 'unknown',
},
door_mid: {
object: 'node',
id: 'door_mid',
type: 'door',
parentId: 'wall_mid',
visible: true,
metadata: {},
position: [0, 0, 0],
rotation: [0, 0, 0],
wallId: 'wall_mid',
width: 0.9,
height: 2.1,
frameThickness: 0.05,
frameDepth: 0.07,
threshold: true,
thresholdHeight: 0.02,
hingesSide: 'left',
swingDirection: 'inward',
segments: [],
handle: true,
handleHeight: 1.05,
handleSide: 'right',
contentPadding: [0.04, 0.04],
doorCloser: false,
panicBar: false,
panicBarHeight: 1.0,
},
zone_kitchen: {
object: 'node',
id: 'zone_kitchen',
type: 'zone',
parentId: 'level_a',
visible: true,
metadata: {},
name: 'Kitchen',
polygon: [
[-5, 0],
[5, 0],
[5, 10],
[-5, 10],
],
color: '#ff0000',
},
zone_living: {
object: 'node',
id: 'zone_living',
type: 'zone',
parentId: 'level_a',
visible: true,
metadata: {},
name: 'Living',
polygon: [
[-5, -10],
[5, -10],
[5, 0],
[-5, 0],
],
color: '#00ff00',
},
fence_1: {
object: 'node',
id: 'fence_1',
type: 'fence',
parentId: 'site_a',
visible: true,
metadata: {},
start: [-8, -8],
end: [8, -8],
height: 1.8,
thickness: 0.08,
baseHeight: 0.22,
postSpacing: 2,
postSize: 0.1,
topRailHeight: 0.04,
groundClearance: 0,
edgeInset: 0.015,
baseStyle: 'grounded',
color: '#ffffff',
style: 'slat',
},
} as unknown as SceneGraph['nodes']
return {
nodes,
rootNodeIds: ['site_a'] as AnyNodeId[],
}
}
describe('mulberry32', () => {
test('is deterministic for the same seed', () => {
const a = mulberry32(42)
const b = mulberry32(42)
for (let i = 0; i < 10; i++) {
expect(a()).toBe(b())
}
})
test('produces values in [0, 1)', () => {
const rng = mulberry32(7)
for (let i = 0; i < 100; i++) {
const v = rng()
expect(v).toBeGreaterThanOrEqual(0)
expect(v).toBeLessThan(1)
}
})
})
describe('applyMutation: wall-thickness', () => {
test('assigns every wall a thickness from the fixed set', () => {
const rng = mulberry32(1)
const out = applyMutation(makeBaseGraph(), rng, 'wall-thickness')
const allowed = new Set([0.1, 0.15, 0.2, 0.25])
let walls = 0
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
walls++
expect(allowed.has((node as { thickness: number }).thickness)).toBe(true)
}
expect(walls).toBeGreaterThan(0)
})
test('does not mutate the input graph', () => {
const base = makeBaseGraph()
const before = JSON.stringify(base)
applyMutation(base, mulberry32(5), 'wall-thickness')
expect(JSON.stringify(base)).toBe(before)
})
})
describe('applyMutation: wall-height', () => {
test('assigns every wall a height from the fixed set', () => {
const rng = mulberry32(2)
const out = applyMutation(makeBaseGraph(), rng, 'wall-height')
const allowed = new Set([2.4, 2.6, 2.7, 3.0])
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
expect(allowed.has((node as { height: number }).height)).toBe(true)
}
})
})
describe('applyMutation: zone-labels', () => {
test('shuffles labels but preserves the set', () => {
const base = makeBaseGraph()
const rng = mulberry32(3)
const out = applyMutation(base, rng, 'zone-labels')
const before = new Set<string>()
for (const node of Object.values(base.nodes)) {
if (node.type === 'zone') before.add((node as { name: string }).name)
}
const after = new Set<string>()
for (const node of Object.values(out.nodes)) {
if (node.type === 'zone') after.add((node as { name: string }).name)
}
expect(after).toEqual(before)
})
})
describe('applyMutation: room-proportions', () => {
test('only nudges interior walls, leaves perimeter alone', () => {
const base = makeBaseGraph()
const rng = mulberry32(4)
const out = applyMutation(base, rng, 'room-proportions')
// Perimeter wall should be unchanged.
const n = out.nodes.wall_n as { start: [number, number]; end: [number, number] }
expect(n.start).toEqual([-10, 10])
expect(n.end).toEqual([10, 10])
// Interior wall should (usually) be different.
const mid = out.nodes.wall_mid as { start: [number, number]; end: [number, number] }
const midBase = base.nodes.wall_mid as { start: [number, number]; end: [number, number] }
const changed =
mid.start[0] !== midBase.start[0] ||
mid.start[1] !== midBase.start[1] ||
mid.end[0] !== midBase.end[0] ||
mid.end[1] !== midBase.end[1]
expect(changed).toBe(true)
})
})
describe('applyMutation: open-plan', () => {
test('removes exactly one interior wall and its attached openings', () => {
const base = makeBaseGraph()
const baseWallCount = Object.values(base.nodes).filter((n) => n.type === 'wall').length
const rng = mulberry32(5)
const out = applyMutation(base, rng, 'open-plan')
const afterWallCount = Object.values(out.nodes).filter((n) => n.type === 'wall').length
expect(afterWallCount).toBe(baseWallCount - 1)
// Interior wall `wall_mid` had a door — both should be gone.
expect(out.nodes.wall_mid).toBeUndefined()
expect(out.nodes.door_mid).toBeUndefined()
})
test('skips gracefully when there are no interior walls', () => {
const graph: SceneGraph = {
nodes: {
site_a: {
object: 'node',
id: 'site_a',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-10, -10],
[10, -10],
[10, 10],
[-10, 10],
],
},
children: [],
},
wall_n: {
object: 'node',
id: 'wall_n',
type: 'wall',
parentId: 'site_a',
visible: true,
metadata: {},
start: [-10, 10],
end: [10, 10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: ['site_a'] as AnyNodeId[],
}
const out = applyMutation(graph, mulberry32(9), 'open-plan')
expect(Object.keys(out.nodes)).toEqual(Object.keys(graph.nodes))
})
})
describe('applyMutation: door-positions', () => {
test('sets every door wallT in [0.2, 0.8]', () => {
const rng = mulberry32(6)
const out = applyMutation(makeBaseGraph(), rng, 'door-positions')
for (const node of Object.values(out.nodes)) {
if (node.type !== 'door') continue
const t = (node as { wallT?: number }).wallT
expect(typeof t).toBe('number')
expect(t as number).toBeGreaterThanOrEqual(0.2)
expect(t as number).toBeLessThanOrEqual(0.8)
}
})
})
describe('applyMutation: fence-style', () => {
test('sets every fence style to one of privacy/slat/rail', () => {
const rng = mulberry32(7)
const out = applyMutation(makeBaseGraph(), rng, 'fence-style')
const allowed = new Set(['privacy', 'slat', 'rail'])
for (const node of Object.values(out.nodes)) {
if (node.type !== 'fence') continue
expect(allowed.has((node as { style: string }).style)).toBe(true)
}
})
})
describe('applyMutation: no-op behaviour', () => {
test('wall-thickness on a graph with no walls leaves nodes unchanged', () => {
const graph: SceneGraph = {
nodes: {
site_a: {
object: 'node',
id: 'site_a',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
],
},
children: [],
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: ['site_a'] as AnyNodeId[],
}
const out = applyMutation(graph, mulberry32(8), 'wall-thickness')
expect(JSON.stringify(out.nodes)).toBe(JSON.stringify(graph.nodes))
})
})
@@ -0,0 +1,331 @@
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNode, AnyNodeId } from '@pascal-app/core/schema'
/** Mutation kinds handled by `applyMutation`. */
export type MutationKind =
| 'wall-thickness'
| 'wall-height'
| 'zone-labels'
| 'room-proportions'
| 'open-plan'
| 'door-positions'
| 'fence-style'
/** Deterministic 32-bit RNG. */
export type Rng = () => number
/**
* Tiny PRNG. Returns a function that produces uniformly distributed floats in
* [0, 1). Source: https://stackoverflow.com/a/47593316/17118
*/
export function mulberry32(seed: number): Rng {
let state = seed | 0
return () => {
state = (state + 0x6d2b79f5) | 0
let t = state
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
/** Pick a random element from a non-empty array. */
function pickFrom<T>(rng: Rng, values: readonly T[]): T {
const idx = Math.floor(rng() * values.length)
return values[Math.min(idx, values.length - 1)] as T
}
/** Shallow clone a scene graph: nodes are copied one level deep, node dict is fresh. */
function cloneGraph(graph: SceneGraph): SceneGraph {
const clonedNodes: Record<AnyNodeId, AnyNode> = {} as Record<AnyNodeId, AnyNode>
for (const [id, node] of Object.entries(graph.nodes)) {
// structuredClone so sub-objects (arrays, tuples, metadata) are independent.
clonedNodes[id as AnyNodeId] = structuredClone(node) as AnyNode
}
return {
nodes: clonedNodes,
rootNodeIds: [...graph.rootNodeIds],
...(graph.collections ? { collections: structuredClone(graph.collections) } : {}),
}
}
const WALL_THICKNESS_OPTIONS = [0.1, 0.15, 0.2, 0.25] as const
const WALL_HEIGHT_OPTIONS = [2.4, 2.6, 2.7, 3.0] as const
const FENCE_STYLES = ['privacy', 'slat', 'rail'] as const
/** FisherYates shuffle in place using the provided RNG. */
function shuffleInPlace<T>(arr: T[], rng: Rng): void {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1))
const tmp = arr[i] as T
arr[i] = arr[j] as T
arr[j] = tmp
}
}
/**
* Compute 2D bounds (min/max x/z) of the first `site` node's polygon points,
* or `null` if no site is present.
*/
function siteBounds(
graph: SceneGraph,
): { minX: number; maxX: number; minZ: number; maxZ: number } | null {
for (const node of Object.values(graph.nodes)) {
if (node.type !== 'site') continue
const pts = (node as { polygon?: { points?: Array<[number, number]> } }).polygon?.points
if (!pts || pts.length === 0) continue
let minX = Infinity
let maxX = -Infinity
let minZ = Infinity
let maxZ = -Infinity
for (const [x, z] of pts) {
if (x < minX) minX = x
if (x > maxX) maxX = x
if (z < minZ) minZ = z
if (z > maxZ) maxZ = z
}
if (!Number.isFinite(minX)) continue
return { minX, maxX, minZ, maxZ }
}
return null
}
/**
* Heuristic: a wall is a perimeter wall if either of its endpoints sits close
* to the site polygon's bounding rectangle (within `epsilon`). Returns `false`
* if there is no site polygon (treat everything as interior so the mutations
* still exercise something on partial scenes).
*/
function isPerimeterWall(
wall: AnyNode & { start?: [number, number]; end?: [number, number] },
bounds: { minX: number; maxX: number; minZ: number; maxZ: number } | null,
epsilon = 0.01,
): boolean {
if (!bounds || !wall.start || !wall.end) return false
const onBound = (x: number, z: number): boolean =>
Math.abs(x - bounds.minX) <= epsilon ||
Math.abs(x - bounds.maxX) <= epsilon ||
Math.abs(z - bounds.minZ) <= epsilon ||
Math.abs(z - bounds.maxZ) <= epsilon
const [sx, sz] = wall.start
const [ex, ez] = wall.end
return onBound(sx, sz) || onBound(ex, ez)
}
function applyWallThickness(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
;(node as { thickness?: number }).thickness = pickFrom(rng, WALL_THICKNESS_OPTIONS)
}
return out
}
function applyWallHeight(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
;(node as { height?: number }).height = pickFrom(rng, WALL_HEIGHT_OPTIONS)
}
return out
}
function applyZoneLabels(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
const zoneNodes: Array<AnyNode & { name?: string }> = []
for (const node of Object.values(out.nodes)) {
if (node.type === 'zone') zoneNodes.push(node as AnyNode & { name?: string })
}
if (zoneNodes.length < 2) return out
const labels = zoneNodes.map((z) => z.name ?? '')
shuffleInPlace(labels, rng)
for (let i = 0; i < zoneNodes.length; i++) {
;(zoneNodes[i] as { name?: string }).name = labels[i]
}
return out
}
function applyRoomProportions(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
const bounds = siteBounds(out)
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
const wall = node as AnyNode & {
start?: [number, number]
end?: [number, number]
}
if (!wall.start || !wall.end) continue
if (isPerimeterWall(wall, bounds)) continue
// Nudge each endpoint by ±10% of its current value.
const nudge = (v: number): number => v * (1 + (rng() * 2 - 1) * 0.1)
const clampX = (v: number): number =>
bounds ? Math.min(bounds.maxX, Math.max(bounds.minX, v)) : v
const clampZ = (v: number): number =>
bounds ? Math.min(bounds.maxZ, Math.max(bounds.minZ, v)) : v
const [sx, sz] = wall.start
const [ex, ez] = wall.end
wall.start = [clampX(nudge(sx)), clampZ(nudge(sz))]
wall.end = [clampX(nudge(ex)), clampZ(nudge(ez))]
}
return out
}
function applyOpenPlan(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
const bounds = siteBounds(out)
const interiorWallIds: AnyNodeId[] = []
for (const [id, node] of Object.entries(out.nodes)) {
if (node.type !== 'wall') continue
if (isPerimeterWall(node as AnyNode, bounds)) continue
interiorWallIds.push(id as AnyNodeId)
}
if (interiorWallIds.length === 0) return out
const targetId = interiorWallIds[Math.floor(rng() * interiorWallIds.length)] as AnyNodeId
// Collect any openings attached to this wall so we can drop them too.
const attached: AnyNodeId[] = []
for (const [attId, node] of Object.entries(out.nodes)) {
if ((node as { wallId?: string }).wallId === targetId) attached.push(attId as AnyNodeId)
}
const removal = new Set<AnyNodeId>([targetId, ...attached])
// Drop from nodes.
for (const id of removal) delete out.nodes[id]
// Drop from rootNodeIds (unlikely for walls, but consistent).
out.rootNodeIds = out.rootNodeIds.filter((id) => !removal.has(id))
// Drop references from any parent's `children` array.
for (const parent of Object.values(out.nodes)) {
if (!('children' in parent) || !Array.isArray((parent as { children?: unknown[] }).children)) {
continue
}
const children = (parent as { children: unknown[] }).children
;(parent as { children: unknown[] }).children = children.filter((child) => {
if (typeof child === 'string') return !removal.has(child as AnyNodeId)
if (child && typeof child === 'object' && 'id' in (child as Record<string, unknown>)) {
return !removal.has((child as { id: AnyNodeId }).id)
}
return true
})
}
return out
}
function applyDoorPositions(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
// Group doors by their parent wall so we can space them out and skip collisions.
const doorsByWall = new Map<string, Array<AnyNode & { wallT?: number; wallId?: string }>>()
for (const node of Object.values(out.nodes)) {
if (node.type !== 'door') continue
const wallId = (node as { wallId?: string }).wallId
if (!wallId) continue
let list = doorsByWall.get(wallId)
if (!list) {
list = []
doorsByWall.set(wallId, list)
}
list.push(node as AnyNode & { wallT?: number; wallId?: string })
}
for (const [, doors] of doorsByWall) {
// Minimum separation along the parametric wall axis — rough keep-away to
// avoid obvious overlaps.
const minGap = 0.15
const usedTs: number[] = []
for (const door of doors) {
let attempts = 0
let t = 0.5
while (attempts < 8) {
t = 0.2 + rng() * 0.6 // [0.2, 0.8]
const collides = usedTs.some((u) => Math.abs(u - t) < minGap)
if (!collides) break
attempts++
}
// If we still collide after 8 attempts, skip this door (leave it alone).
if (usedTs.some((u) => Math.abs(u - t) < minGap)) continue
usedTs.push(t)
;(door as { wallT?: number }).wallT = t
}
}
return out
}
function applyFenceStyle(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
let i = 0
for (const node of Object.values(out.nodes)) {
if (node.type !== 'fence') continue
// Use rng to choose a rotation offset so each call can produce a different
// starting point even when called multiple times with the same base.
const offset = Math.floor(rng() * FENCE_STYLES.length)
const style = FENCE_STYLES[(i + offset) % FENCE_STYLES.length]
;(node as { style?: string }).style = style
i++
}
return out
}
/** Pure: apply a single mutation and return a fresh graph. */
export function applyMutation(graph: SceneGraph, rng: Rng, kind: MutationKind): SceneGraph {
switch (kind) {
case 'wall-thickness':
return applyWallThickness(graph, rng)
case 'wall-height':
return applyWallHeight(graph, rng)
case 'zone-labels':
return applyZoneLabels(graph, rng)
case 'room-proportions':
return applyRoomProportions(graph, rng)
case 'open-plan':
return applyOpenPlan(graph, rng)
case 'door-positions':
return applyDoorPositions(graph, rng)
case 'fence-style':
return applyFenceStyle(graph, rng)
}
}
/**
* Human-readable summary of the mutations applied to a variant. Reads the
* interesting fields from the graph (e.g. first wall's thickness/height).
*/
export function describeVariant(graph: SceneGraph, mutations: readonly MutationKind[]): string {
const parts: string[] = []
if (mutations.includes('wall-thickness')) {
const t = firstWallField(graph, 'thickness')
if (t !== null) parts.push(`wall thickness ${t}m`)
}
if (mutations.includes('wall-height')) {
const h = firstWallField(graph, 'height')
if (h !== null) parts.push(`wall height ${h}m`)
}
if (mutations.includes('zone-labels')) {
const names: string[] = []
for (const node of Object.values(graph.nodes)) {
if (node.type === 'zone') names.push((node as { name?: string }).name ?? '')
}
if (names.length > 0) parts.push(`zones [${names.join(', ')}]`)
}
if (mutations.includes('room-proportions')) parts.push('room proportions nudged')
if (mutations.includes('open-plan')) parts.push('open-plan')
if (mutations.includes('door-positions')) parts.push('doors repositioned')
if (mutations.includes('fence-style')) {
const s = firstFenceField(graph, 'style')
if (s !== null) parts.push(`fence style ${s}`)
}
return parts.length > 0 ? parts.join(', ') : 'no-op'
}
function firstWallField(graph: SceneGraph, field: 'thickness' | 'height'): number | null {
for (const node of Object.values(graph.nodes)) {
if (node.type !== 'wall') continue
const v = (node as Record<string, unknown>)[field]
if (typeof v === 'number') return v
}
return null
}
function firstFenceField(graph: SceneGraph, field: 'style'): string | null {
for (const node of Object.values(graph.nodes)) {
if (node.type !== 'fence') continue
const v = (node as Record<string, unknown>)[field]
if (typeof v === 'string') return v
}
return null
}