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:
co-authored by
Claude Opus 4.7
parent
42bd05db9c
commit
e8d0b13ff5
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user