Revert "AI Scene Bridge (MCP)"

This commit is contained in:
Formsmith
2026-06-26 15:31:37 +03:00
committed by GitHub
parent a525626607
commit 5ed0e61cb8
20 changed files with 1 additions and 3034 deletions
Binary file not shown.
-127
View File
@@ -1,127 +0,0 @@
# Scene Bridge — Build Plan
Work one phase per session. Each phase is a vertical slice that is independently
testable. Do not start a phase until the previous one meets its acceptance criteria.
---
## Phase 0 — Orientation (NO CODE)
**Goal:** Prove you understand the architecture before touching anything.
Read only these:
- `CLAUDE.md` (root)
- `apps/web/src/types/sketchforge.ts`
- The persistence block in `apps/web/src/app/page.tsx` (IndexedDB + localStorage helpers, ~44–135)
- `apps/web/src/app/api/local-download/route.ts` (route + same-origin guard template)
- `apps/web/src/lib/shapeCatalog.ts` and `apps/web/src/lib/workplaneShapes.ts`
**Deliverable:** a short note (`docs/scene-bridge/NOTES.md`) stating, in your own words:
the IndexedDB record shape, the exact localStorage key, the existing read/write helper
names you will reuse, the URL the editor opens with, and the data flow diagram from
`CLAUDE.md`. List anything that contradicts `CLAUDE.md` — alpha drift is expected.
**Acceptance:** the note is correct against source. No code written.
---
## Phase 1 — Bridge route (server only)
**Goal:** A local HTTP endpoint that stages and returns a scene.
- Create `apps/web/src/app/api/scene/route.ts`.
- `POST` body `{ projectId: string, shapes: WorkplaneShape[], op?: "upsertScene", name?: string }`.
Validate with the existing routes' style (size cap, `isLocalSameOriginRequest`, `safeProjectId`).
Assign a monotonic `stagingRevision` and write `.codex/pending-scenes/<safeId>.json` =
`{ stagingRevision, op, projectId, name, shapes, updatedAt }`. This `stagingRevision` is the
bridge's OWN counter — it is NOT the app's project revision (keep them separate).
- `GET ?projectId=&sinceStaging=<n>` returns the staged command if its stagingRevision is
newer, else 204/empty.
- Do **not** import or validate full geometry here — just the JSON shape.
**Acceptance (curl, app running):**
- `curl -X POST .../api/scene` with a 1-box scene → 200, file appears under `.codex/pending-scenes/`.
- `GET` returns it; `GET` with `since` equal to current revision returns empty.
- Non-local / wrong-origin request → 403 (verify a plain Node `fetch` from localhost passes;
if it does not, document the exact header the MCP must send).
---
## Phase 2 — Client hydrator (browser side)
**Goal:** The running app picks up a staged command and shows the scene.
- Add a `SceneTransport` interface (`poll()` now; `subscribe()` reserved for V2) and a
polling implementation that hits `GET /api/scene?...&sinceStaging=` for the target project.
- Add the poller as a **hook called from `Home`** (`page.tsx`) — NOT a `components/` module.
On a command whose `stagingRevision` exceeds the last one applied:
- if `op === "upsertScene"` and the project id is unknown, create it via the existing
create-project path, then make it the active/open project;
- call the existing `updateProjectShapes({ projectId, shapes })` — it writes IndexedDB +
localStorage + a winning project revision, and the editor's existing rehydration effect
(keyed on `initialShapes`/`projectRevision`) re-renders the viewport for free.
- record the applied `stagingRevision` to avoid re-applying.
- Gate behind a flag (e.g. `?bridge=1` or an env var) so normal use is untouched.
- Do NOT write IndexedDB directly and do NOT set a project revision yourself.
**Acceptance:**
- From the dashboard, `POST` an `upsertScene` for a NEW project id (2 shapes, one with
`hole: true`, grouped) → project is created, opened, and the geometry renders, no console
errors. `POST` again with a higher `stagingRevision` → scene updates. Reload → it persists
(it's in IndexedDB). While dragging a shape, an incoming push is deferred, not fought.
---
## Phase 3 — MCP server (`apps/mcp/`)
**Goal:** Claude-callable tools that drive the bridge.
- New workspace `apps/mcp/`. Import `WorkplaneShape`, `canonicalizeShape`, and the per-kind
defaults from `apps/web` (shared in the monorepo).
- Tools:
- `get_scene(projectId)` → current staged shapes.
- `set_scene(projectId, shapes, name?)` → validate, then `POST /api/scene` as `upsertScene`
(unknown ids are fine — the client creates the project in Phase 2).
- `add_shapes(projectId, shapes)` → merge with current, re-`POST`.
- `list_kinds()` → kinds + required/optional fields + defaults derived from the catalog,
so the model self-corrects.
- Validation: zod checks the `ShapeKind` **union enum** + base required numerics ONLY, then
run the imported `canonicalizeShape` to clamp/default. Do NOT hand-author parameter ranges —
the app's canonicaliser is the single source of truth. Reject only structurally-broken shapes.
- Ship a few example scenes (phone stand, bracket with bolt holes) as in-context references.
**Acceptance:**
- From Claude Code (or an MCP inspector): `set_scene` with a hand-written 3-shape scene for a
fresh project id → project is created and the scene appears. Invalid shape (bad kind /
malformed) → rejected by zod with a useful message, nothing staged. A valid-but-extreme shape
is clamped by `canonicalizeShape`, not rejected.
---
## Phase 4 — End-to-end + polish
**Goal:** Prompt → scene in the editor.
- Driving Claude through the MCP: "a 40 mm phone stand with a cable slot" → valid
`WorkplaneShape[]` → renders.
- Add `get_scene` round-trip so the model can read back and iterate ("make the slot 5 mm wider").
- Document the loop in `docs/scene-bridge/README.md`. Add 1–2 vitest cases for the schema
validator and the route handler.
**Acceptance:** three different natural-language prompts each produce a sensible,
error-free scene; iteration on an existing scene works.
---
## V2 — MCP as source of truth (separate effort)
Only after V1 is solid. The seams are already in place:
- Replace the polling `SceneTransport` with a WebSocket implementation (`subscribe()`);
route stays as a fallback.
- MCP holds the canonical scene; pushes diffs; the editor reflects them live and
round-trips user edits back over the socket.
- Keep the `WorkplaneShape` contract identical so V1 tools keep working.
Do not build V2 abstractions early. The `SceneTransport` interface from Phase 2 is the
only forward-compatibility you need now.
-134
View File
@@ -1,134 +0,0 @@
# AI Scene Bridge
Push parametric 3D scenes from Claude (via an MCP server) into the running SketchForge
editor. Claude emits `WorkplaneShape[]` JSON; the editor's existing save path hydrates it
into the viewport. Manifold WASM (client-side) does all the actual CSG/meshing — the bridge
never does mesh maths.
## The loop
```
Claude ──(MCP tool call)──▶ apps/mcp ──POST /api/scene──▶ Next route (server)
│ stages a command file:
│ .codex/pending-scenes/<id>.json
▼
editor viewport ◀── rehydration effect ◀── updateProjectShapes() ◀── poller in Home (page.tsx)
(renders shapes) (initialShapes/ (writes IndexedDB + GET /api/scene?sinceStaging=
projectRevision) localStorage + revision)
```
An MCP server is a Node process and **cannot** write the browser's IndexedDB/localStorage —
that storage is sandboxed to the page origin. So the bridge always goes through the HTTP
route + an in-page poller that reuses the app's own save path.
### Two independent counters
- **`stagingRevision`** — the bridge's own monotonic counter (per project, in the staged
file). The poller polls `GET /api/scene?sinceStaging=<last applied>` and only applies
newer commands.
- **project `revision`** — the app's existing per-project revision, owned entirely by
`updateProjectShapes()`. The bridge never sets it.
These are kept separate on purpose: the bridge can re-deliver without fighting the app's
own revisioning, and the editor defers an incoming push while the user is mid-drag.
## Running it
1. Start the app:
```
npm run dev # http://127.0.0.1:3000
```
2. Open the editor in **bridge mode**, choosing any project id you like:
```
http://127.0.0.1:3000/?bridge=1&project=my-first-scene
```
The id need not exist yet — the first `set_scene` creates and opens it.
3. The MCP server is registered for Claude Code in [`.mcp.json`](../../.mcp.json) at the repo
root (`sketchforge-scene-bridge`). It launches via `npm run start --prefix apps/mcp` and
talks to the app at `SKETCHFORGE_BASE_URL` (default `http://127.0.0.1:3000`). Claude Code
picks up `.mcp.json` on startup — restart it once after first checkout and approve the
server.
You can also run the server standalone for an MCP inspector:
```
SKETCHFORGE_BASE_URL=http://127.0.0.1:3000 npm run start --prefix apps/mcp
```
## Tools
| Tool | Args | What it does |
|------|------|--------------|
| `list_kinds` | — | Lists every shape kind, its default dimensions, which optional fields matter, and example scenes. **Call this first.** |
| `set_scene` | `projectId, shapes[], name?` | Replaces the project's scene. Unknown ids are created automatically. |
| `add_shapes` | `projectId, shapes[]` | Appends shapes to the current scene (merge + re-stage). |
| `get_scene` | `projectId` | Reads the current staged shapes back, so you can iterate. |
## The data contract
`WorkplaneShape` (`apps/web/src/types/sketchforge.ts`) is THE contract. For authoring:
- Units are **millimetres**. `x`/`z` position on the workplane; `elevation` is height above it.
- Every shape needs `kind` + `width` + `depth` + `height`. `color`/`name` auto-fill if omitted;
position defaults to the origin.
- A **cutter** is any shape with `hole: true`.
- A **boolean/combined result** carries its parts in `groupedShapes: WorkplaneShape[]`.
- `kind` must be one of the 18 `ShapeKind` values (`list_kinds`). Some kinds need extra data
(`text` → `text`/`font`; `mesh` → imported geometry) and aren't directly generatable.
### Validation
The MCP validates with zod against the `ShapeKind` **union enum** + the base numerics only,
then runs the app's own `sceneShape`/`canonicalizeShape` to fill defaults and canonicalise.
There are **no hand-authored parameter ranges** — the app's canonicaliser is the single
source of truth. So:
- a bad kind or malformed (non-numeric) field is **rejected** with a useful message, nothing
is staged;
- a valid-but-extreme shape (e.g. `rotation: 725`) is **canonicalised** (→ `5`), not rejected.
## Example prompts → scenes
- *"a 40 mm phone stand with a cable slot"* → base box + tilted backrest + front lip +
a `hole: true` cylinder for the cable slot.
- *"a pen holder, a 50 mm cylinder hollowed from the top"* → outer cylinder + inner
`hole: true` cylinder.
- *"a little toy house"* → a box body + a `roof` on top.
## Iterating on a scene
```
get_scene(projectId) # read the current shapes
# edit the shape you want, e.g. widen the cable slot by 5 mm
set_scene(projectId, shapes) # re-stage; the editor updates in place
```
Because the scene lives in IndexedDB, it persists across reloads. While the user is dragging
a shape, an incoming push is deferred (not fought) and applied when the drag ends.
## Tests
```
npm run test
```
- `tests/unit/sceneRoute.test.ts` — the `/api/scene` route handler (stage/poll, monotonic
`stagingRevision`, same-origin 403, validation 400, 204 semantics).
- `tests/unit/sceneSchema.test.ts` — the MCP schema validator (defaults via the app's
defaulter, cutter/grouped preserved, bad kind / malformed rejected, extreme canonicalised).
## File map
| Path | Role |
|------|------|
| `apps/web/src/app/api/scene/route.ts` | Bridge route (stages/serves commands). |
| `apps/web/src/lib/sceneBridge.ts` | `SceneTransport` interface + polling transport (V2 swap point). |
| `apps/web/src/app/page.tsx` | `useSceneBridge` poller hook + `applyBridgeCommand` (in `Home`). |
| `apps/mcp/` | MCP server: tools, zod schema, app-reused defaulter, example scenes. |
| `.codex/pending-scenes/<id>.json` | Staged command (gitignored). |
## V2 (later)
The `SceneTransport` interface in `sceneBridge.ts` is the only forward-compatibility seam:
V2 replaces the polling transport with a WebSocket (`subscribe()`) so the MCP becomes the
live source of truth, while the route stays as a fallback and the `WorkplaneShape` contract
is unchanged. See `PLAN.md` → V2.