Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
Add AI scene bridge (V1): MCP -> /api/scene -> editor
Additive fork feature letting an MCP server (driven by Claude) push parametric WorkplaneShape[] scenes into the running SketchForge editor. The Node side never writes browser storage; it stages a command file that an in-page poller applies through the editor's existing updateProjectShapes() save path. - Phase 1: apps/web/src/app/api/scene/route.ts — stages/serves commands behind the existing same-origin guard, with its own monotonic stagingRevision (separate from the app's project revision). - Phase 2: apps/web/src/lib/sceneBridge.ts (SceneTransport seam + polling transport) and a useSceneBridge poller hook in page.tsx (gated on ?bridge=1), which creates unknown projects and hydrates via updateProjectShapes; defers while dragging. - Phase 3: apps/mcp/ MCP server — set_scene/get_scene/add_shapes/list_kinds. zod validates the ShapeKind union enum + base numerics, then reuses the app's own sceneShape/canonicalizeShape for defaults/canonicalisation (no hand-authored ranges). - Phase 4: docs/scene-bridge/README.md plus vitest cases for the route handler and the schema validator. Staged scenes live under .codex/pending-scenes/ (gitignored). MCP registered via .mcp.json. npm run test: 29 passing. Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
d99fc1e650
commit
dee2765538
@@ -0,0 +1,43 @@
|
||||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
// Where the running Next app (and its /api/scene bridge) lives. The route's same-origin
|
||||
// guard passes a plain Node fetch from localhost with no extra headers (verified in Phase 1).
|
||||
const BASE_URL = (process.env.SKETCHFORGE_BASE_URL ?? process.env.SCENE_BRIDGE_URL ?? "http://127.0.0.1:3000").replace(/\/$/, "");
|
||||
|
||||
export function bridgeBaseUrl() {
|
||||
return BASE_URL;
|
||||
}
|
||||
|
||||
export type StagedScene = {
|
||||
shapes: WorkplaneShape[];
|
||||
stagingRevision: number | null;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export async function postScene(projectId: string, shapes: WorkplaneShape[], name?: string): Promise<{ stagingRevision: number }> {
|
||||
const response = await fetch(`${BASE_URL}/api/scene`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ projectId, op: "upsertScene", name, shapes }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`POST /api/scene failed (${response.status}): ${await response.text().catch(() => response.statusText)}`);
|
||||
}
|
||||
return (await response.json()) as { stagingRevision: number };
|
||||
}
|
||||
|
||||
export async function getScene(projectId: string): Promise<StagedScene> {
|
||||
const params = new URLSearchParams({ projectId, sinceStaging: "0" });
|
||||
const response = await fetch(`${BASE_URL}/api/scene?${params.toString()}`, {
|
||||
method: "GET",
|
||||
headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
if (response.status === 204) {
|
||||
return { shapes: [], stagingRevision: null };
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(`GET /api/scene failed (${response.status}): ${await response.text().catch(() => response.statusText)}`);
|
||||
}
|
||||
const command = (await response.json()) as { shapes?: WorkplaneShape[]; stagingRevision?: number; name?: string };
|
||||
return { shapes: command.shapes ?? [], stagingRevision: command.stagingRevision ?? null, name: command.name };
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { ShapeInput } from "./shapes";
|
||||
|
||||
// In-context reference scenes the model can copy from. Plain WorkplaneShape inputs:
|
||||
// dimensions in millimetres, x/z on the workplane, elevation = height above it, a cutter
|
||||
// is any shape with hole: true. These are intentionally simple and valid.
|
||||
|
||||
export const PHONE_STAND_EXAMPLE: { name: string; shapes: ShapeInput[] } = {
|
||||
name: "Phone stand",
|
||||
shapes: [
|
||||
{ name: "Base", kind: "box", color: "#0098c7", x: 0, z: 0, elevation: 0, width: 80, depth: 70, height: 8 },
|
||||
// Backrest tilted back ~20° so a phone leans against it.
|
||||
{ name: "Backrest", kind: "box", color: "#0098c7", x: 0, z: -22, elevation: 4, width: 80, depth: 8, height: 70, rotationX: 20 },
|
||||
// Lip at the front to stop the phone sliding off.
|
||||
{ name: "Lip", kind: "box", color: "#0098c7", x: 0, z: 28, elevation: 8, width: 80, depth: 8, height: 14 },
|
||||
// Cable slot cut through the base.
|
||||
{ name: "Cable slot", kind: "cylinder", color: "#d41721", hole: true, x: 0, z: 6, elevation: 0, width: 16, depth: 16, height: 24, radius: 8, sides: 64 },
|
||||
],
|
||||
};
|
||||
|
||||
export const BRACKET_EXAMPLE: { name: string; shapes: ShapeInput[] } = {
|
||||
name: "L-bracket with bolt holes",
|
||||
shapes: [
|
||||
{ name: "Base flange", kind: "box", color: "#33983d", x: 0, z: 0, elevation: 0, width: 60, depth: 40, height: 6 },
|
||||
{ name: "Upright flange", kind: "box", color: "#33983d", x: 0, z: -17, elevation: 6, width: 60, depth: 6, height: 40 },
|
||||
{ name: "Bolt hole L", kind: "cylinder", color: "#d41721", hole: true, x: -18, z: 8, elevation: 0, width: 8, depth: 8, height: 12, radius: 4, sides: 48 },
|
||||
{ name: "Bolt hole R", kind: "cylinder", color: "#d41721", hole: true, x: 18, z: 8, elevation: 0, width: 8, depth: 8, height: 12, radius: 4, sides: 48 },
|
||||
],
|
||||
};
|
||||
|
||||
export const EXAMPLE_SCENES = [PHONE_STAND_EXAMPLE, BRACKET_EXAMPLE];
|
||||
@@ -0,0 +1,149 @@
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import { z } from "zod";
|
||||
import { bridgeBaseUrl, getScene, postScene } from "./bridgeClient";
|
||||
import { shapeInputSchema, toWorkplaneShapes, type ShapeInput } from "./shapes";
|
||||
import { describeKinds } from "./kinds";
|
||||
import { EXAMPLE_SCENES } from "./examples";
|
||||
|
||||
const projectIdSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Editor project id. Open the app at /?bridge=1&project=<id> to watch it live; unknown ids are created automatically.");
|
||||
|
||||
function viewUrl(projectId: string) {
|
||||
return `${bridgeBaseUrl()}/?bridge=1&project=${encodeURIComponent(projectId)}`;
|
||||
}
|
||||
|
||||
function jsonResult(summary: string, data: unknown) {
|
||||
return {
|
||||
content: [
|
||||
{ type: "text" as const, text: summary },
|
||||
{ type: "text" as const, text: JSON.stringify(data, null, 2) },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function errorResult(message: string) {
|
||||
return { isError: true, content: [{ type: "text" as const, text: message }] };
|
||||
}
|
||||
|
||||
const server = new McpServer(
|
||||
{ name: "sketchforge-scene-bridge", version: "0.1.0" },
|
||||
{
|
||||
instructions:
|
||||
"Push parametric 3D scenes into the SketchForge editor. Scenes are arrays of WorkplaneShape " +
|
||||
"objects (millimetres; x/z on the workplane, elevation = height above it; a cutter is any shape " +
|
||||
"with hole:true; a boolean result carries its parts in groupedShapes). The user must have the app " +
|
||||
"open at /?bridge=1&project=<id> to see updates live. Call list_kinds first to learn the shape " +
|
||||
"kinds, their default sizes, and example scenes. Use set_scene to replace a scene, add_shapes to " +
|
||||
"append, and get_scene to read the current scene back before iterating.",
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"list_kinds",
|
||||
{
|
||||
title: "List shape kinds",
|
||||
description:
|
||||
"List every valid shape kind with its default dimensions and which optional fields matter, plus " +
|
||||
"ready-to-use example scenes. Call this before generating shapes so you self-correct on kind names " +
|
||||
"and required fields.",
|
||||
inputSchema: {},
|
||||
},
|
||||
async () => {
|
||||
return jsonResult("Valid shape kinds, defaults, and example scenes.", {
|
||||
note: "Every shape needs kind, width, depth, height. color/name are auto-filled if omitted. Positions default to the origin. Sizes are clamped/canonicalised by the editor, not by this server.",
|
||||
kinds: describeKinds(),
|
||||
examples: EXAMPLE_SCENES,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"get_scene",
|
||||
{
|
||||
title: "Get current scene",
|
||||
description: "Read back the shapes currently staged for a project, so you can iterate on an existing scene.",
|
||||
inputSchema: { projectId: projectIdSchema },
|
||||
},
|
||||
async ({ projectId }) => {
|
||||
try {
|
||||
const scene = await getScene(projectId);
|
||||
return jsonResult(
|
||||
`Project ${projectId} has ${scene.shapes.length} staged shape(s)` +
|
||||
(scene.stagingRevision === null ? " (nothing staged yet)." : `.`),
|
||||
scene,
|
||||
);
|
||||
} catch (error) {
|
||||
return errorResult(error instanceof Error ? error.message : "Could not read scene");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"set_scene",
|
||||
{
|
||||
title: "Set (replace) scene",
|
||||
description:
|
||||
"Replace the project's scene with the given shapes. Unknown project ids are created automatically. " +
|
||||
"Shapes are validated against the shape-kind contract, then defaulted/canonicalised by the editor.",
|
||||
inputSchema: {
|
||||
projectId: projectIdSchema,
|
||||
shapes: z.array(shapeInputSchema).min(1).describe("The full scene as an array of WorkplaneShape inputs."),
|
||||
name: z.string().optional().describe("Optional project name used only when the project is first created."),
|
||||
},
|
||||
},
|
||||
async ({ projectId, shapes, name }) => {
|
||||
try {
|
||||
const workplaneShapes = toWorkplaneShapes(shapes as ShapeInput[]);
|
||||
const { stagingRevision } = await postScene(projectId, workplaneShapes, name);
|
||||
return jsonResult(`Staged ${workplaneShapes.length} shape(s) for ${projectId}. View: ${viewUrl(projectId)}`, {
|
||||
projectId,
|
||||
stagingRevision,
|
||||
shapeCount: workplaneShapes.length,
|
||||
viewUrl: viewUrl(projectId),
|
||||
});
|
||||
} catch (error) {
|
||||
return errorResult(error instanceof Error ? error.message : "Could not stage scene");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"add_shapes",
|
||||
{
|
||||
title: "Add shapes to scene",
|
||||
description: "Append shapes to the project's current staged scene (merge, then re-stage the whole scene).",
|
||||
inputSchema: {
|
||||
projectId: projectIdSchema,
|
||||
shapes: z.array(shapeInputSchema).min(1).describe("Shapes to append to the existing scene."),
|
||||
},
|
||||
},
|
||||
async ({ projectId, shapes }) => {
|
||||
try {
|
||||
const current = await getScene(projectId);
|
||||
const added = toWorkplaneShapes(shapes as ShapeInput[]);
|
||||
const merged = [...current.shapes, ...added];
|
||||
const { stagingRevision } = await postScene(projectId, merged);
|
||||
return jsonResult(
|
||||
`Added ${added.length} shape(s) to ${projectId} (now ${merged.length} total). View: ${viewUrl(projectId)}`,
|
||||
{ projectId, stagingRevision, added: added.length, total: merged.length, viewUrl: viewUrl(projectId) },
|
||||
);
|
||||
} catch (error) {
|
||||
return errorResult(error instanceof Error ? error.message : "Could not add shapes");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
async function main() {
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
// stderr only — stdout is the MCP JSON-RPC channel.
|
||||
console.error(`sketchforge-scene-bridge MCP server ready (bridge: ${bridgeBaseUrl()})`);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error("Fatal MCP server error:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { sceneShape } from "@/lib/shapeCatalog";
|
||||
import { fallbackSolidColor } from "@/lib/workplaneShapes";
|
||||
import type { ShapeKind, WorkplaneShape } from "@/types/sketchforge";
|
||||
import { SHAPE_KINDS } from "./shapes";
|
||||
|
||||
// Per-kind guidance for the model. This is NOT the validation enum (that's SHAPE_KINDS /
|
||||
// the ShapeKind union) — it's hints about which optional fields matter and which kinds need
|
||||
// payloads a model can't author by hand. "requires" lists fields beyond width/depth/height.
|
||||
const KIND_GUIDANCE: Record<ShapeKind, { requires?: string[]; useful?: string[]; note?: string; generatable: boolean }> = {
|
||||
box: { useful: ["radius (corner fillet)"], generatable: true },
|
||||
cylinder: { useful: ["radius", "sides"], generatable: true },
|
||||
sphere: { useful: ["steps"], generatable: true },
|
||||
cone: { useful: ["baseRadius", "topRadius", "sides"], generatable: true },
|
||||
pyramid: { useful: ["sides"], generatable: true },
|
||||
wedge: { generatable: true },
|
||||
roundRoof: { useful: ["sides"], generatable: true },
|
||||
halfSphere: { useful: ["steps"], generatable: true },
|
||||
torus: { useful: ["radius", "bevel"], generatable: true },
|
||||
tube: { useful: ["radius", "bevel"], generatable: true },
|
||||
ring: { useful: ["radius", "bevel"], generatable: true },
|
||||
polygon: { useful: ["sides"], generatable: true },
|
||||
icosahedron: { generatable: true },
|
||||
roof: { generatable: true },
|
||||
text: { requires: ["text", "font"], note: "Set text to the string and font to a font name.", generatable: true },
|
||||
sketch: { note: "Free-form sketch; not directly generatable from numeric params.", generatable: false },
|
||||
scribble: { note: "Free-form scribble; not directly generatable from numeric params.", generatable: false },
|
||||
mesh: { requires: ["importedMesh"], note: "Needs imported geometry (positions/normals) — produced by STL import, not authored.", generatable: false },
|
||||
};
|
||||
|
||||
export type KindInfo = {
|
||||
kind: ShapeKind;
|
||||
generatable: boolean;
|
||||
defaults: { width: number; depth: number; height: number; size: number; rotation: number };
|
||||
requires: string[];
|
||||
useful: string[];
|
||||
note?: string;
|
||||
};
|
||||
|
||||
export function describeKinds(): KindInfo[] {
|
||||
return SHAPE_KINDS.map((kind) => {
|
||||
// Derive defaults from the app's own defaulter rather than hard-coding them.
|
||||
const d = sceneShape({ name: kind, kind, color: fallbackSolidColor({ kind } as WorkplaneShape) });
|
||||
const guidance = KIND_GUIDANCE[kind];
|
||||
return {
|
||||
kind,
|
||||
generatable: guidance.generatable,
|
||||
defaults: { width: d.width, depth: d.depth, height: d.height, size: d.size, rotation: d.rotation },
|
||||
requires: guidance.requires ?? [],
|
||||
useful: guidance.useful ?? [],
|
||||
note: guidance.note,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { z } from "zod";
|
||||
import { sceneShape } from "@/lib/shapeCatalog";
|
||||
import { fallbackSolidColor } from "@/lib/workplaneShapes";
|
||||
import type { ShapeKind, WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
// The ShapeKind union is the validation source of truth (CLAUDE.md). The type is
|
||||
// compile-time only, so we mirror it here as a runtime list for the zod enum, with a
|
||||
// two-way compile-time guard so the list can never silently drift from the union.
|
||||
export const SHAPE_KINDS = [
|
||||
"box",
|
||||
"cylinder",
|
||||
"sphere",
|
||||
"sketch",
|
||||
"scribble",
|
||||
"cone",
|
||||
"pyramid",
|
||||
"roof",
|
||||
"text",
|
||||
"roundRoof",
|
||||
"halfSphere",
|
||||
"torus",
|
||||
"tube",
|
||||
"ring",
|
||||
"wedge",
|
||||
"polygon",
|
||||
"icosahedron",
|
||||
"mesh",
|
||||
] as const;
|
||||
|
||||
type MissingFromList = Exclude<ShapeKind, (typeof SHAPE_KINDS)[number]>;
|
||||
type ExtraInList = Exclude<(typeof SHAPE_KINDS)[number], ShapeKind>;
|
||||
// If either of these errors, SHAPE_KINDS and the ShapeKind union have drifted — fix the list.
|
||||
const _assertNoneMissing: MissingFromList extends never ? true : false = true;
|
||||
const _assertNoneExtra: ExtraInList extends never ? true : false = true;
|
||||
void _assertNoneMissing;
|
||||
void _assertNoneExtra;
|
||||
|
||||
// Structural input contract for a model-authored shape. We require only the base
|
||||
// numerics every kind needs (width/depth/height) plus a valid kind; everything else is
|
||||
// optional and gets filled + canonicalised by the app's own sceneShape(). We deliberately
|
||||
// do NOT encode parameter ranges here — the app's canonicaliser owns that.
|
||||
export interface ShapeInput {
|
||||
id?: string;
|
||||
name?: string;
|
||||
kind: ShapeKind;
|
||||
color?: string;
|
||||
hole?: boolean;
|
||||
x?: number;
|
||||
z?: number;
|
||||
elevation?: number;
|
||||
width: number;
|
||||
depth: number;
|
||||
height: number;
|
||||
size?: number;
|
||||
rotation?: number;
|
||||
rotationX?: number;
|
||||
rotationZ?: number;
|
||||
mirrorX?: boolean;
|
||||
mirrorY?: boolean;
|
||||
mirrorZ?: boolean;
|
||||
radius?: number;
|
||||
steps?: number;
|
||||
sides?: number;
|
||||
bevel?: number;
|
||||
segments?: number;
|
||||
topRadius?: number;
|
||||
baseRadius?: number;
|
||||
text?: string;
|
||||
font?: string;
|
||||
importedMesh?: unknown;
|
||||
imagePlate?: unknown;
|
||||
groupedShapes?: ShapeInput[];
|
||||
groupedBaseWidth?: number;
|
||||
groupedBaseDepth?: number;
|
||||
groupedBaseHeight?: number;
|
||||
locked?: boolean;
|
||||
hidden?: boolean;
|
||||
}
|
||||
|
||||
const finiteNumber = z.number().finite();
|
||||
|
||||
// z.lazy for the groupedShapes recursion (a boolean result carries its parts).
|
||||
export const shapeInputSchema: z.ZodType<ShapeInput> = z.lazy(() =>
|
||||
z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
kind: z.enum(SHAPE_KINDS),
|
||||
color: z.string().optional(),
|
||||
hole: z.boolean().optional(),
|
||||
x: finiteNumber.optional(),
|
||||
z: finiteNumber.optional(),
|
||||
elevation: finiteNumber.optional(),
|
||||
width: finiteNumber,
|
||||
depth: finiteNumber,
|
||||
height: finiteNumber,
|
||||
size: finiteNumber.optional(),
|
||||
rotation: finiteNumber.optional(),
|
||||
rotationX: finiteNumber.optional(),
|
||||
rotationZ: finiteNumber.optional(),
|
||||
mirrorX: z.boolean().optional(),
|
||||
mirrorY: z.boolean().optional(),
|
||||
mirrorZ: z.boolean().optional(),
|
||||
radius: finiteNumber.optional(),
|
||||
steps: finiteNumber.optional(),
|
||||
sides: finiteNumber.optional(),
|
||||
bevel: finiteNumber.optional(),
|
||||
segments: finiteNumber.optional(),
|
||||
topRadius: finiteNumber.optional(),
|
||||
baseRadius: finiteNumber.optional(),
|
||||
text: z.string().optional(),
|
||||
font: z.string().optional(),
|
||||
importedMesh: z.unknown().optional(),
|
||||
imagePlate: z.unknown().optional(),
|
||||
groupedShapes: z.array(shapeInputSchema).optional(),
|
||||
groupedBaseWidth: finiteNumber.optional(),
|
||||
groupedBaseDepth: finiteNumber.optional(),
|
||||
groupedBaseHeight: finiteNumber.optional(),
|
||||
locked: z.boolean().optional(),
|
||||
hidden: z.boolean().optional(),
|
||||
}),
|
||||
);
|
||||
|
||||
export const shapesArraySchema = z.array(shapeInputSchema);
|
||||
|
||||
function prettifyKind(kind: ShapeKind) {
|
||||
const spaced = kind.replace(/([a-z])([A-Z])/g, "$1 $2");
|
||||
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
|
||||
}
|
||||
|
||||
// Validate-then-defaults pipeline: the zod layer only rejects structurally broken shapes;
|
||||
// sceneShape() (which calls canonicalizeShape) is the single source of truth for defaults
|
||||
// + canonicalisation. Grouped parts are normalised depth-first so children get defaults too.
|
||||
export function toWorkplaneShape(input: ShapeInput): WorkplaneShape {
|
||||
const kind = input.kind;
|
||||
const color = input.color ?? fallbackSolidColor({ kind } as WorkplaneShape);
|
||||
const name = input.name ?? prettifyKind(kind);
|
||||
const groupedShapes = input.groupedShapes?.map(toWorkplaneShape);
|
||||
return sceneShape({
|
||||
...(input as Partial<WorkplaneShape>),
|
||||
name,
|
||||
kind,
|
||||
color,
|
||||
groupedShapes,
|
||||
});
|
||||
}
|
||||
|
||||
export function toWorkplaneShapes(inputs: ShapeInput[]): WorkplaneShape[] {
|
||||
return inputs.map(toWorkplaneShape);
|
||||
}
|
||||
Reference in New Issue
Block a user