@constructorfleet/sketchforge3d 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -233,6 +233,6 @@ The MCP uses the extracted engine package directly against project files, with n
233
233
  SKETCHFORGE_PROJECTS_DIR="$HOME/SketchForgeProjects" npm run mcp:sketchforge
234
234
  ```
235
235
 
236
- The directory uses the same `<projectId>.json` and `<projectId>.skf` files as server-side project storage. In local mode, pass `projectId` to project tools. `sketchforge_read_scene` and `sketchforge_list_objects` accept `shapeIds`, `excludeShapeIds`, `includeRawShapes`, and `includeRawShapeIds`, so a large imported reference mesh can stay out of the response. STL, OBJ, 3MF, ZIP-kit, SKF, and STEP exports can write to `outputPath`; the project name supplies the default filename.
236
+ The directory uses the same `<projectId>.json` and `<projectId>.skf` files as server-side project storage. In local mode, use `sketchforge_list_projects` to discover projects, `sketchforge_create_project` to start an empty one, or `sketchforge_import_project` with a local `.skf` `filePath` to add an existing package. These tools return the new `projectId` for other project tools. The configured directory is created when needed. `sketchforge_read_scene` and `sketchforge_list_objects` accept `shapeIds`, `excludeShapeIds`, `includeRawShapes`, and `includeRawShapeIds`, so a large imported reference mesh can stay out of the response. STL, OBJ, 3MF, ZIP-kit, SKF, and STEP exports can write to `outputPath`; the project name supplies the default filename.
237
237
 
238
238
  Local mode covers project reads and edits, shape creation/import, arranging, mirroring, grouping, booleans, edge and face operations, measurements, hollowing, mesh and STEP exports, scene topology, clearance and intersection checks, and JavaScript macros. Image capture renders a headless model view from stored geometry; it does not capture editor chrome or the live viewport camera. The npm MCP client and `@constructorfleet/sketchforge-engine` are published together by the release workflow. Editor discovery and editor error inspection require a URL and open editor. Python macros require a URL and the HTTP adapter.
@@ -1,4 +1,6 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { writeFileSync } from "node:fs";
3
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
4
  import path from "node:path";
3
5
 
4
6
  const projectsDir = process.env.SKETCHFORGE_PROJECTS_DIR;
@@ -10,6 +12,7 @@ async function getBackend() {
10
12
  if (!projectsDir) throw new Error("Set SKETCHFORGE_PROJECTS_DIR to a directory containing SketchForge project files.");
11
13
  if (!backend) {
12
14
  enginePackagePromise ??= import("@constructorfleet/sketchforge-engine");
15
+ await mkdir(projectsDir, { recursive: true });
13
16
  const { createEngine, directoryProjectStore } = await enginePackagePromise;
14
17
  const store = directoryProjectStore(projectsDir);
15
18
  backend = { store, engine: createEngine(store), package: await enginePackagePromise };
@@ -79,108 +82,28 @@ async function exportScene(args) {
79
82
  const document = await store.read(id);
80
83
  if (!document) throw new Error(`Project not found: ${id}`);
81
84
  const requestedIds = Array.isArray(args.shapeIds) && args.shapeIds.length ? args.shapeIds : selectedObjectIds;
82
- const shapes = requestedIds.length ? document.shapes.filter((shape) => requestedIds.includes(shape.id)) : document.shapes;
83
- if (args.format === "skf") {
84
- const bytes = await enginePackage.exportSkfProject({
85
- projectId: id, projectName: document.projectName, createdAt: document.createdAt, modifiedAt: Date.now(),
86
- shapes, history: document.history, historyIndex: document.historyIndex, assets: document.assets,
87
- workspace: document.workspace, snapGrid: document.snapGrid, placementElevation: document.placementElevation,
88
- placementWorkplane: document.placementWorkplane, sketchPlacementWorkplane: document.sketchPlacementWorkplane,
89
- });
90
- const artifact = { filename: `${args.name || document.projectName}.skf`, mimeType: "application/vnd.sketchforge.project+zip", bytes: bytes.byteLength, shapeCount: shapes.length, base64: Buffer.from(bytes).toString("base64") };
91
- if (typeof args.outputPath === "string" && args.outputPath.trim()) {
92
- const destination = path.resolve(args.outputPath);
93
- writeFileSync(destination, bytes);
94
- return { ...artifact, base64: undefined, savedTo: destination };
95
- }
96
- return artifact;
97
- }
98
- if (args.format === "step") {
99
- const result = await enginePackage.exportShapesToStep(shapes.filter((shape) => shape.hidden !== true));
100
- const artifact = { filename: `${args.name || document.projectName}.step`, mimeType: "model/step", bytes: result.blob.size, exportedCount: result.exportedCount, skipped: result.skipped, base64: Buffer.from(await result.blob.arrayBuffer()).toString("base64") };
101
- if (typeof args.outputPath === "string" && args.outputPath.trim()) {
102
- const destination = path.resolve(args.outputPath);
103
- writeFileSync(destination, Buffer.from(artifact.base64, "base64"));
104
- return { ...artifact, base64: undefined, savedTo: destination };
105
- }
106
- return artifact;
107
- }
108
- if (["stl", "obj", "3mf", "zip"].includes(args.format)) {
109
- const visible = shapes.filter((shape) => shape.hidden !== true && shape.hole !== true);
110
- if (!visible.length) throw new Error("No visible solid objects to export.");
111
- const meshes = await enginePackage.meshProjectShapes(visible);
112
- const bytes = await exportMeshFormat(args.format, meshes, document, enginePackage);
113
- const extensions = args.format === "zip" ? "zip" : args.format;
114
- const mimeType = { stl: "model/stl", obj: "text/plain", "3mf": "model/3mf", zip: "application/zip" }[args.format];
115
- const filename = `${args.name || document.projectName}.${extensions}`;
116
- const artifact = { filename, mimeType, bytes: bytes.byteLength, shapeCount: meshes.length, base64: Buffer.from(bytes).toString("base64") };
117
- if (typeof args.outputPath === "string" && args.outputPath.trim()) {
118
- const destination = path.resolve(args.outputPath);
119
- writeFileSync(destination, bytes);
120
- return { ...artifact, base64: undefined, savedTo: destination };
121
- }
122
- return artifact;
123
- }
124
- throw new Error(`Unsupported export format in local mode: ${args.format}`);
125
- }
126
-
127
- function meshBytesAsStl(meshes) {
128
- const triangles = meshes.reduce((sum, mesh) => sum + mesh.faces.length, 0);
129
- const bytes = new Uint8Array(84 + triangles * 50);
130
- bytes.set(new TextEncoder().encode("SketchForge binary STL"));
131
- const view = new DataView(bytes.buffer);
132
- view.setUint32(80, triangles, true);
133
- let offset = 84;
134
- for (const mesh of meshes) for (const [ia, ib, ic] of mesh.faces) {
135
- const points = [mesh.vertices[ia], mesh.vertices[ib], mesh.vertices[ic]].map(([x, y, z]) => [x, -z, y]);
136
- const [a, b, c] = points;
137
- const u = b.map((v, i) => v - a[i]);
138
- const w = c.map((v, i) => v - a[i]);
139
- let n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
140
- const length = Math.hypot(...n) || 1;
141
- n = n.map((v) => v / length);
142
- for (const value of [...n, ...a, ...b, ...c]) { view.setFloat32(offset, value, true); offset += 4; }
143
- view.setUint16(offset, 0, true); offset += 2;
144
- }
145
- return bytes;
146
- }
147
-
148
- function meshBytesAsObj(meshes) {
149
- const lines = ["# SketchForge OBJ export"];
150
- let index = 1;
151
- for (const mesh of meshes) {
152
- lines.push(`o ${mesh.name.replace(/\\s+/g, "_")}`);
153
- for (const [x, y, z] of mesh.vertices) lines.push(`v ${x} ${y} ${z}`);
154
- for (const [a, b, c] of mesh.faces) lines.push(`f ${a + index} ${b + index} ${c + index}`);
155
- index += mesh.vertices.length;
156
- }
157
- return new TextEncoder().encode(lines.join("\n"));
158
- }
159
-
160
- async function exportMeshFormat(format, meshes, document, enginePackage) {
161
- if (format === "stl") return meshBytesAsStl(meshes);
162
- if (format === "obj") return meshBytesAsObj(meshes);
163
- const stl = meshBytesAsStl(meshes);
164
- const { zipSync, strToU8 } = await import("fflate");
165
- if (format === "zip") {
166
- const skf = await enginePackage.exportSkfProject({
167
- projectId: document.projectId, projectName: document.projectName, createdAt: document.createdAt,
168
- modifiedAt: Date.now(), shapes: document.shapes, history: document.history, historyIndex: document.historyIndex,
169
- assets: document.assets, workspace: document.workspace, snapGrid: document.snapGrid,
170
- placementElevation: document.placementElevation, placementWorkplane: document.placementWorkplane,
171
- sketchPlacementWorkplane: document.sketchPlacementWorkplane,
172
- });
173
- return zipSync({ [`${document.projectName}.stl`]: stl, [`${document.projectName}.skf`]: skf });
174
- }
175
- const xmlEscape = (value) => String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;");
176
- const vertices = meshes.map((mesh, i) => `<object id="${i + 1}" type="model" name="${xmlEscape(mesh.name)}"><mesh><vertices>${mesh.vertices.map(([x,y,z]) => `<vertex x="${x}" y="${-z}" z="${y}"/>`).join("")}</vertices><triangles>${mesh.faces.map(([v1,v2,v3]) => `<triangle v1="${v1}" v2="${v2}" v3="${v3}"/>`).join("")}</triangles></mesh></object>`).join("");
177
- const buildItems = meshes.map((_, i) => `<item objectid="${i + 1}"/>`).join("");
178
- const model = `<?xml version="1.0" encoding="UTF-8"?><model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><resources>${vertices}</resources><build>${buildItems}</build></model>`;
179
- return zipSync({
180
- "[Content_Types].xml": strToU8('<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/></Types>'),
181
- "_rels/.rels": strToU8('<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Target="/3D/3dmodel.model" Id="rel0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/></Relationships>'),
182
- "3D/3dmodel.model": strToU8(model),
85
+ const artifact = await enginePackage.exportProjectScene(document, {
86
+ format: args.format,
87
+ shapeIds: requestedIds.length ? requestedIds : undefined,
88
+ name: args.name,
183
89
  });
90
+ const bytes = artifact.data;
91
+ const response = {
92
+ format: artifact.format,
93
+ filename: artifact.filename,
94
+ mimeType: artifact.mimeType,
95
+ bytes: bytes.byteLength,
96
+ shapeCount: artifact.shapeCount,
97
+ ...(artifact.exportedCount === undefined ? {} : { exportedCount: artifact.exportedCount }),
98
+ ...(artifact.skipped === undefined ? {} : { skipped: artifact.skipped }),
99
+ base64: Buffer.from(bytes).toString("base64"),
100
+ };
101
+ if (typeof args.outputPath === "string" && args.outputPath.trim()) {
102
+ const destination = path.resolve(args.outputPath);
103
+ writeFileSync(destination, bytes);
104
+ return { ...response, base64: undefined, savedTo: destination };
105
+ }
106
+ return response;
184
107
  }
185
108
 
186
109
  async function validateScene(args) {
@@ -300,8 +223,54 @@ export async function callLocalEngineTool(name, args = {}) {
300
223
  if (["sketchforge_list_editors", "sketchforge_inspect_errors"].includes(name)) {
301
224
  throw new Error(`${name} needs an open SketchForge editor and is unavailable in local mode.`);
302
225
  }
303
- const id = requireProjectId(args);
304
226
  const { engine, package: enginePackage } = await getBackend();
227
+ if (name === "sketchforge_list_projects") {
228
+ const projects = await Promise.all((await backend.store.list()).map(async (record) => {
229
+ const project = await unwrap(await engine.project(record.projectId));
230
+ return {
231
+ id: record.projectId,
232
+ name: String(record.metadata.name ?? "Untitled design"),
233
+ shapes: project.shapes.length,
234
+ revision: project.revision,
235
+ updatedAt: record.updatedAt,
236
+ packageBytes: record.packageBytes,
237
+ };
238
+ }));
239
+ return { projects };
240
+ }
241
+ if (name === "sketchforge_create_project") {
242
+ const projectName = String(args.name ?? "").trim().slice(0, 80);
243
+ if (!projectName) throw new Error("name is required to create a project.");
244
+ const id = randomUUID();
245
+ const now = Date.now();
246
+ await writeFile(path.join(projectsDir, `${id}.json`), JSON.stringify({ name: projectName, createdAt: now, updatedAt: now, revision: 1 }), { flag: "wx" });
247
+ return { projectId: id, name: projectName, shapeCount: 0, revision: 1 };
248
+ }
249
+ if (name === "sketchforge_import_project") {
250
+ const sourcePath = path.resolve(String(args.filePath ?? ""));
251
+ if (path.extname(sourcePath).toLowerCase() !== ".skf") throw new Error("filePath must point to a .skf project file.");
252
+ const bytes = await readFile(sourcePath);
253
+ const imported = await enginePackage.importSkfProject(bytes);
254
+ const projectName = String(args.name ?? imported.projectName ?? "Imported design").trim().slice(0, 80);
255
+ if (!projectName) throw new Error("name must not be empty.");
256
+ const id = randomUUID();
257
+ const now = Date.now();
258
+ const packagePath = path.join(projectsDir, `${id}.skf`);
259
+ const metadataPath = path.join(projectsDir, `${id}.json`);
260
+ const temporaryPackage = `${packagePath}.tmp`;
261
+ const temporaryMetadata = `${metadataPath}.tmp`;
262
+ try {
263
+ await writeFile(temporaryPackage, bytes, { flag: "wx" });
264
+ await writeFile(temporaryMetadata, JSON.stringify({ name: projectName, createdAt: now, updatedAt: now, revision: 1 }), { flag: "wx" });
265
+ await rename(temporaryPackage, packagePath);
266
+ await rename(temporaryMetadata, metadataPath);
267
+ } catch (error) {
268
+ await Promise.all([unlink(temporaryPackage).catch(() => {}), unlink(temporaryMetadata).catch(() => {}), unlink(packagePath).catch(() => {})]);
269
+ throw error;
270
+ }
271
+ return { projectId: id, name: projectName, shapeCount: imported.shapes.length, revision: 1 };
272
+ }
273
+ const id = requireProjectId(args);
305
274
  switch (name) {
306
275
  case "sketchforge_read_scene":
307
276
  case "sketchforge_list_objects":
@@ -50,6 +50,60 @@ export function macroDirectory(environment = process.env) {
50
50
  return path.resolve(configured);
51
51
  }
52
52
 
53
+ function pythonRunnerEnvironment(environment) {
54
+ const pythonPath = existsSync(bundledPythonSource)
55
+ ? [bundledPythonSource, environment.PYTHONPATH].filter(Boolean).join(path.delimiter)
56
+ : environment.PYTHONPATH;
57
+ return {
58
+ command: environment.SKETCHFORGE_MACRO_PYTHON || "python3",
59
+ environment: { ...environment, ...(pythonPath ? { PYTHONPATH: pythonPath } : {}) },
60
+ };
61
+ }
62
+
63
+ function inspectPythonMacro(filePath, environment) {
64
+ const runner = pythonRunnerEnvironment(environment);
65
+ return new Promise((resolve) => {
66
+ const child = spawn(runner.command, ["-m", "sketchforge3d.macro", filePath, "--describe", "--json"], {
67
+ cwd: path.dirname(filePath),
68
+ env: runner.environment,
69
+ stdio: ["ignore", "pipe", "ignore"],
70
+ });
71
+ let stdout = "";
72
+ let finished = false;
73
+ const timer = setTimeout(() => {
74
+ finished = true;
75
+ child.kill("SIGKILL");
76
+ resolve(null);
77
+ }, 5_000);
78
+ child.stdout?.on("data", (chunk) => {
79
+ stdout += chunk;
80
+ if (stdout.length > 64 * 1024) {
81
+ finished = true;
82
+ clearTimeout(timer);
83
+ child.kill("SIGKILL");
84
+ resolve(null);
85
+ }
86
+ });
87
+ child.on("error", () => {
88
+ if (finished) return;
89
+ finished = true;
90
+ clearTimeout(timer);
91
+ resolve(null);
92
+ });
93
+ child.on("close", (code) => {
94
+ if (finished) return;
95
+ finished = true;
96
+ clearTimeout(timer);
97
+ if (code !== 0) return resolve(null);
98
+ try {
99
+ resolve(JSON.parse(stdout));
100
+ } catch {
101
+ resolve(null);
102
+ }
103
+ });
104
+ });
105
+ }
106
+
53
107
  /**
54
108
  * The macros an operator has installed.
55
109
  *
@@ -75,11 +129,13 @@ export async function listMacros(environment = process.env) {
75
129
  // A symlink out of the directory is still a file the operator put there on
76
130
  // purpose; what matters is that the name came from this listing.
77
131
  if (!info?.isFile()) continue;
132
+ const metadata = extension === ".py" ? await inspectPythonMacro(full, environment) : null;
78
133
  macros.push({
79
134
  name: entry.name,
80
135
  language: extension === ".py" ? "python" : "javascript",
81
136
  bytes: info.size,
82
137
  modifiedAt: new Date(info.mtimeMs).toISOString(),
138
+ ...(metadata ? { metadata } : {}),
83
139
  });
84
140
  }
85
141
  return { directory, macros: macros.sort((left, right) => left.name.localeCompare(right.name)) };
@@ -104,14 +160,11 @@ function runnerFor(macroName, environment) {
104
160
  return { command: process.execPath, leadingArguments: [path.join(moduleDirectory, "localMacroRunner.mjs")], extraEnvironment: {} };
105
161
  }
106
162
  if (path.extname(macroName).toLowerCase() === ".py") {
107
- const python = environment.SKETCHFORGE_MACRO_PYTHON || "python3";
108
- const pythonPath = existsSync(bundledPythonSource)
109
- ? [bundledPythonSource, environment.PYTHONPATH].filter(Boolean).join(path.delimiter)
110
- : environment.PYTHONPATH;
163
+ const runner = pythonRunnerEnvironment(environment);
111
164
  return {
112
- command: python,
165
+ command: runner.command,
113
166
  leadingArguments: ["-m", "sketchforge3d.macro"],
114
- extraEnvironment: pythonPath ? { PYTHONPATH: pythonPath } : {},
167
+ extraEnvironment: runner.environment,
115
168
  };
116
169
  }
117
170
  return { command: process.execPath, leadingArguments: [javascriptRunner(environment)], extraEnvironment: {} };
package/mcp/server.mjs CHANGED
@@ -35,6 +35,21 @@ const editorTargetSchema = {
35
35
  };
36
36
 
37
37
  const tools = [
38
+ {
39
+ name: "sketchforge_list_projects",
40
+ description: "List projects stored in SKETCHFORGE_PROJECTS_DIR for offline MCP use.",
41
+ inputSchema: { ...editorTargetSchema, properties: { url: editorTargetSchema.properties.url } },
42
+ },
43
+ {
44
+ name: "sketchforge_create_project",
45
+ description: "Create an empty project in the local SKETCHFORGE_PROJECTS_DIR.",
46
+ inputSchema: { ...editorTargetSchema, required: ["name"], properties: { ...editorTargetSchema.properties, name: { type: "string" } } },
47
+ },
48
+ {
49
+ name: "sketchforge_import_project",
50
+ description: "Import a local .skf file as a new project in SKETCHFORGE_PROJECTS_DIR.",
51
+ inputSchema: { ...editorTargetSchema, required: ["filePath"], properties: { ...editorTargetSchema.properties, filePath: { type: "string" }, name: { type: "string" } } },
52
+ },
38
53
  {
39
54
  name: "sketchforge_list_editors",
40
55
  description: "List SketchForge editor tabs that are currently open and heartbeating, including editorNumber and projectName.",
@@ -608,6 +623,9 @@ function normalizedServerUrl(value) {
608
623
 
609
624
  async function callTool(name, args = {}) {
610
625
  const { url, ...toolArgs } = args || {};
626
+ if (["sketchforge_list_projects", "sketchforge_create_project", "sketchforge_import_project"].includes(name) && typeof url === "string" && url.trim()) {
627
+ throw new Error(`${name} is only available in local mode; omit url.`);
628
+ }
611
629
  if (typeof url === "string" && url.trim()) {
612
630
  return callRemoteTool(name, toolArgs, normalizedServerUrl(url.trim()));
613
631
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@constructorfleet/sketchforge3d",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "Typed client and macro runner for the SketchForge REST API.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": {
@@ -19,7 +19,7 @@
19
19
  "client"
20
20
  ],
21
21
  "dependencies": {
22
- "@constructorfleet/sketchforge-engine": "1.7.0",
22
+ "@constructorfleet/sketchforge-engine": "1.8.0",
23
23
  "fflate": "^0.8.3",
24
24
  "sharp": "^0.35.5"
25
25
  },