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
@@ -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()
})
})