@constructorfleet/sketchforge3d 1.5.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.
@@ -0,0 +1,125 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { writeFile, unlink } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { directoryProjectStore, createEngine } from "@constructorfleet/sketchforge-engine";
6
+ import { macroFromModule, runMacro } from "../dist/index.js";
7
+
8
+ const root = process.env.SKETCHFORGE_PROJECTS_DIR;
9
+ if (!root) throw new Error("SKETCHFORGE_PROJECTS_DIR is required for local macro execution.");
10
+ const store = directoryProjectStore(path.resolve(root));
11
+ const engine = createEngine(store);
12
+ const unwrap = (result) => {
13
+ if (result.ok) return result.value;
14
+ throw new Error(`Engine operation failed: ${JSON.stringify(result.failure)}`);
15
+ };
16
+
17
+ async function projectSummary(record) {
18
+ const project = unwrap(await engine.project(record.projectId));
19
+ return {
20
+ id: record.projectId,
21
+ name: String(record.metadata.name ?? "Untitled design"),
22
+ shapes: project.shapes.length,
23
+ revision: project.revision,
24
+ updatedAt: record.updatedAt,
25
+ packageBytes: record.packageBytes,
26
+ };
27
+ }
28
+
29
+ async function createProject(name) {
30
+ const id = randomUUID();
31
+ const now = Date.now();
32
+ await writeFile(path.join(root, `${id}.json`), JSON.stringify({ name: String(name).slice(0, 80), createdAt: now, updatedAt: now, revision: 1 }));
33
+ return { id, name: String(name).slice(0, 80), shapes: 0, revision: 1, updatedAt: now, packageBytes: 0 };
34
+ }
35
+
36
+ function projectHandle(id) {
37
+ const read = async () => unwrap(await engine.project(id));
38
+ const addMany = async (shapes) => unwrap(await engine.addShapes(id, shapes));
39
+ const getEdges = async (shapeId) => unwrap(await engine.edges(id, shapeId));
40
+ const withTriangleCount = (written) => ({ ...written, triangles: written.shape.importedMesh?.triangleCount ?? 0 });
41
+ const treat = async (shapeId, treatment) => withTriangleCount(unwrap(await engine.treat(id, shapeId, treatment)));
42
+ const shell = async (shapeId, request) => withTriangleCount(unwrap(await engine.shell(id, shapeId, request)));
43
+ return {
44
+ id,
45
+ get: async () => {
46
+ const project = await read();
47
+ return { id, name: project.name, createdAt: project.createdAt, snapGrid: project.snapGrid, workspace: project.workspace, shapes: project.shapes };
48
+ },
49
+ listShapes: async () => (await read()).shapes,
50
+ add: async (shape) => (await addMany([shape])).shapes[0],
51
+ addMany,
52
+ update: async (shapeId, changes) => unwrap(await engine.changeShape(id, shapeId, changes)),
53
+ remove: (shapeId) => engine.removeShape(id, shapeId).then(unwrap),
54
+ clear: async () => {
55
+ const shapes = (await read()).shapes;
56
+ for (const shape of shapes) await unwrap(await engine.removeShape(id, shape.id));
57
+ return shapes.length;
58
+ },
59
+ edges: getEdges,
60
+ filletableEdges: async (shapeId) => (await getEdges(shapeId)).filter((edge) => edge.filletable).map((edge) => edge.index),
61
+ treat,
62
+ fillet: (shapeId, radius, edges) => treat(shapeId, { kind: "fillet", amount: radius, ...(edges ? { edges } : {}) }),
63
+ chamfer: (shapeId, distance, options = {}) => treat(shapeId, { kind: "chamfer", amount: distance, ...options }),
64
+ faces: async (shapeId) => unwrap(await engine.faces(id, shapeId)),
65
+ facesFacing: async (shapeId, direction) => (await unwrap(await engine.faces(id, shapeId))).filter((face) => face.direction === direction).map((face) => face.index),
66
+ measurements: (shapeId) => engine.measurements(id, shapeId).then(unwrap),
67
+ measureBetween: (from, to) => engine.measureBetween(id, from, to).then(unwrap),
68
+ shell,
69
+ hollow: (shapeId, thickness) => shell(shapeId, { thickness }),
70
+ tray: (shapeId, thickness, openFaces) => shell(shapeId, { thickness, ...(openFaces ? { openFaces } : {}) }),
71
+ align: (request) => engine.align(id, request).then(unwrap),
72
+ alignTops: (ids, anchorId) => engine.align(id, { ids: [...ids], axis: "y", target: "max", ...(anchorId ? { anchorId } : {}) }).then(unwrap),
73
+ distribute: (request) => engine.distribute(id, request).then(unwrap),
74
+ pattern: (request) => engine.pattern(id, request).then(unwrap),
75
+ row: (ids, count, stepX, stepZ = 0) => engine.pattern(id, { ids: [...ids], kind: "linear", count, stepX, stepZ }).then(unwrap),
76
+ ring: (ids, count, center, options = {}) => engine.pattern(id, { ids: [...ids], kind: "circular", count, centerX: center.x, centerZ: center.z, ...options }).then(unwrap),
77
+ importMesh: (request) => engine.importMesh(id, request).then(unwrap),
78
+ cut: (request) => engine.cut(id, request).then(unwrap),
79
+ group: (ids) => engine.group(id, [...ids]).then(unwrap),
80
+ ungroup: (shapeId) => engine.ungroup(id, shapeId).then(unwrap),
81
+ separate: (shapeId) => engine.separate(id, shapeId).then(unwrap),
82
+ };
83
+ }
84
+
85
+ const client = {
86
+ project: projectHandle,
87
+ projects: {
88
+ list: async () => Promise.all((await store.list()).map(projectSummary)),
89
+ findByName: async (name) => (await Promise.all((await store.list()).map(projectSummary))).find((project) => project.name === name) ?? null,
90
+ create: createProject,
91
+ get: async (id) => projectHandle(id).get(),
92
+ delete: async (id) => {
93
+ const metadata = path.join(root, `${id}.json`);
94
+ const file = path.join(root, `${id}.skf`);
95
+ let deleted = false;
96
+ for (const target of [metadata, file]) try { await unlink(target); deleted = true; } catch (error) { if (error.code !== "ENOENT") throw error; }
97
+ return { deleted };
98
+ },
99
+ },
100
+ };
101
+ client.shapes = {
102
+ list: async (id) => projectHandle(id).listShapes(),
103
+ create: async (id, shape) => projectHandle(id).add(shape),
104
+ createMany: async (id, shapes) => projectHandle(id).addMany(shapes),
105
+ update: async (id, shapeId, changes) => projectHandle(id).update(shapeId, changes),
106
+ delete: async (id, shapeId) => projectHandle(id).remove(shapeId),
107
+ deleteAll: async (id) => projectHandle(id).clear(),
108
+ };
109
+
110
+ const argv = process.argv.slice(2);
111
+ const file = argv[0];
112
+ if (!file) throw new Error("Expected a macro file path.");
113
+ const options = { params: {}, targetProjectId: undefined };
114
+ for (const argument of argv.slice(1)) {
115
+ if (argument === "--json") continue;
116
+ if (argument.startsWith("--project=")) options.targetProjectId = argument.slice("--project=".length);
117
+ else if (argument.startsWith("--")) {
118
+ const [key, ...value] = argument.slice(2).split("=");
119
+ options.params[key] = value.join("=");
120
+ }
121
+ }
122
+ const module = await import(pathToFileURL(path.resolve(file)).href);
123
+ const definition = macroFromModule(module, path.basename(file).replace(/\.[cm]?[jt]s$/, ""));
124
+ const report = await runMacro(client, definition, options);
125
+ process.stdout.write(`${JSON.stringify(report)}\n`);
@@ -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)) };
@@ -97,15 +153,18 @@ function javascriptRunner(environment) {
97
153
  }
98
154
 
99
155
  function runnerFor(macroName, environment) {
156
+ if (environment.SKETCHFORGE_PROJECTS_DIR) {
157
+ if (path.extname(macroName).toLowerCase() === ".py") {
158
+ throw new MacroToolError("Python macros need the HTTP API adapter; local project mode runs JavaScript macros directly against the engine.");
159
+ }
160
+ return { command: process.execPath, leadingArguments: [path.join(moduleDirectory, "localMacroRunner.mjs")], extraEnvironment: {} };
161
+ }
100
162
  if (path.extname(macroName).toLowerCase() === ".py") {
101
- const python = environment.SKETCHFORGE_MACRO_PYTHON || "python3";
102
- const pythonPath = existsSync(bundledPythonSource)
103
- ? [bundledPythonSource, environment.PYTHONPATH].filter(Boolean).join(path.delimiter)
104
- : environment.PYTHONPATH;
163
+ const runner = pythonRunnerEnvironment(environment);
105
164
  return {
106
- command: python,
165
+ command: runner.command,
107
166
  leadingArguments: ["-m", "sketchforge3d.macro"],
108
- extraEnvironment: pythonPath ? { PYTHONPATH: pythonPath } : {},
167
+ extraEnvironment: runner.environment,
109
168
  };
110
169
  }
111
170
  return { command: process.execPath, leadingArguments: [javascriptRunner(environment)], extraEnvironment: {} };
@@ -221,11 +280,12 @@ export const macroTools = [
221
280
  {
222
281
  name: "sketchforge_run_macro",
223
282
  description:
224
- "Run one installed macro by name, against the headless REST API. Parameters are the macro's own declared parameters. Only files already present in SKETCHFORGE_MACRO_DIR can be run; code cannot be passed in.",
283
+ "Run one installed macro by name, offline by default or against an optional SketchForge server URL. Parameters are the macro's own declared parameters. Only files already present in SKETCHFORGE_MACRO_DIR can be run; code cannot be passed in.",
225
284
  inputSchema: {
226
285
  type: "object",
227
286
  required: ["macro"],
228
287
  properties: {
288
+ url: { type: "string", description: "Optional SketchForge server URL. Omit to run against local project files." },
229
289
  macro: { type: "string", description: "A file name from sketchforge_list_macros." },
230
290
  params: {
231
291
  type: "object",
package/mcp/server.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { readFileSync } from "node:fs";
3
+ import { readFileSync, writeFileSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { listMacros, macroTools, runMacroByName } from "./macroTools.mjs";
7
+ import { callLocalEngineTool } from "./localEngine.mjs";
7
8
 
8
- const DEFAULT_BASE_URL = "http://127.0.0.1:3000";
9
9
 
10
10
  /**
11
11
  * The version this bridge reports is the package's, read at startup rather than
@@ -23,11 +23,11 @@ const version = (() => {
23
23
  }
24
24
  })();
25
25
  const MCP_ROUTE = "/api/sketchforge-mcp";
26
- const baseUrl = process.env.SKETCHFORGE_URL || DEFAULT_BASE_URL;
27
-
28
26
  const editorTargetSchema = {
29
27
  type: "object",
30
28
  properties: {
29
+ url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
30
+ projectId: { type: "string", description: "Project id in SKETCHFORGE_PROJECTS_DIR when running the MCP in local mode." },
31
31
  editorNumber: { type: "number", description: "The 5-digit SketchForge editor number from sketchforge_list_editors." },
32
32
  editorId: { type: "string", description: "Optional internal editor id. Prefer editorNumber for human-directed use." },
33
33
  timeoutMs: { type: "number", description: "Command timeout in milliseconds. Defaults to 15000." },
@@ -35,25 +35,43 @@ 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.",
41
- inputSchema: { type: "object", properties: {} },
56
+ inputSchema: { ...editorTargetSchema, properties: { url: editorTargetSchema.properties.url } },
42
57
  },
43
58
  {
44
59
  name: "sketchforge_read_scene",
45
- description: "Read the current scene, selection, workspace units, and exact object dimensions from an open SketchForge editor.",
60
+ description: "Read the current scene and exact object dimensions from local project files by default, or from an editor when a server url is supplied.",
46
61
  inputSchema: {
47
62
  ...editorTargetSchema,
48
63
  properties: {
49
64
  ...editorTargetSchema.properties,
50
65
  includeRawShapes: { type: "boolean", description: "Include raw WorkplaneShape JSON. Can be large for imported meshes." },
66
+ shapeIds: { type: "array", items: { type: "string" }, description: "Limit the response to these object ids (including rawShapes)." },
67
+ excludeShapeIds: { type: "array", items: { type: "string" }, description: "Omit these object ids, useful for large reference meshes." },
68
+ includeRawShapeIds: { type: "array", items: { type: "string" }, description: "Include raw geometry only for these ids; takes precedence over includeRawShapes." },
51
69
  },
52
70
  },
53
71
  },
54
72
  {
55
73
  name: "sketchforge_list_objects",
56
- description: "List all current objects available in the editor with exact dimensions, position, rotation, and object ids.",
74
+ description: "List all objects in the local project by default, or in the editor when a server url is supplied, with exact dimensions, position, rotation, and object ids.",
57
75
  inputSchema: editorTargetSchema,
58
76
  },
59
77
  {
@@ -68,6 +86,11 @@ const tools = [
68
86
  },
69
87
  },
70
88
  },
89
+ {
90
+ name: "sketchforge_mirror_objects",
91
+ description: "Mirror objects across the center plane of their combined bounds, using the editor's mirror behavior.",
92
+ inputSchema: { ...editorTargetSchema, required: ["axis"], properties: { ...editorTargetSchema.properties, ids: { type: "array", items: { type: "string" }, description: "Object ids; defaults to the current selection." }, axis: { type: "string", enum: ["x", "y", "z"] } } },
93
+ },
71
94
  {
72
95
  name: "sketchforge_delete_objects",
73
96
  description: "Delete objects by id, or delete the current selection when ids are omitted.",
@@ -91,7 +114,7 @@ const tools = [
91
114
  kind: { type: "string", enum: ["box", "cube", "cylinder", "sketch", "loft", "revolve", "thread"] },
92
115
  profile: {
93
116
  type: "array",
94
- description: "For kind revolve: the closed outline to revolve, as [x, z] pairs. x is the distance from the axis, z runs along it. A triangle makes a thread, a rectangle a tube, a polygon a spring.",
117
+ description: "For kind sketch: a closed 2D outline to extrude, as [x, z] pairs. For kind revolve: the closed outline to revolve, where x is distance from axis and z runs along it.",
95
118
  items: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2 },
96
119
  },
97
120
  pitch: { type: "number", description: "For kind revolve/thread: axial rise per turn in mm. 0 is a plain revolve; negative is a left-hand thread." },
@@ -315,7 +338,7 @@ const tools = [
315
338
  },
316
339
  {
317
340
  name: "sketchforge_capture_image",
318
- description: "Capture a PNG image of the editor viewport from current/home/top/bottom/front/back/right/left view.",
341
+ description: "Capture a PNG image from current/home/top/bottom/front/back/right/left view. Local project mode renders the model headlessly; editor mode captures the live viewport.",
319
342
  inputSchema: {
320
343
  ...editorTargetSchema,
321
344
  properties: {
@@ -324,30 +347,39 @@ const tools = [
324
347
  },
325
348
  },
326
349
  },
327
- // Hollowing runs on the headless REST API rather than in an editor tab: the
328
- // operation is server-side OCCT, and the editor has no action for it yet.
350
+ {
351
+ name: "sketchforge_export_scene",
352
+ description: "Export selected objects or the whole scene as STL, OBJ, 3MF, STEP, SKF, or a ZIP kit. Set outputPath to save directly on the MCP host and avoid returning large base64 data. Use shapeIds to keep a reference mesh out of mesh exports.",
353
+ inputSchema: { ...editorTargetSchema, required: ["format"], properties: { ...editorTargetSchema.properties, format: { type: "string", enum: ["stl", "obj", "3mf", "step", "skf", "zip"] }, shapeIds: { type: "array", items: { type: "string" }, description: "Optional object ids; defaults to the current selection, or the whole scene when nothing is selected." }, name: { type: "string" }, outputPath: { type: "string", description: "Optional destination path on the computer running the SketchForge MCP server." } } },
354
+ },
355
+ {
356
+ name: "sketchforge_validate_scene",
357
+ description: "Check triangle topology, conservative AABB clearance bounds, and exact Manifold intersection volumes for overlapping scene objects.",
358
+ inputSchema: { ...editorTargetSchema, properties: { ...editorTargetSchema.properties, shapeIds: { type: "array", items: { type: "string" } }, excludeShapeIds: { type: "array", items: { type: "string" } } } },
359
+ },
360
+ // CAD operations use the local engine by default and the server API when a URL is supplied.
329
361
  {
330
362
  name: "sketchforge_list_faces",
331
- description: "List a stored project shape's CAD faces, with the direction name each one can be opened by, so a hollow can leave the right ones off. Works on a project on the server (REST API), not on an open editor tab.",
363
+ description: "List a stored project shape's CAD faces, with the direction name each one can be opened by, so a hollow can leave the right ones off. Works offline or against a server when url is supplied.",
332
364
  inputSchema: {
333
365
  type: "object",
334
366
  required: ["projectId", "shapeId"],
335
367
  properties: {
368
+ url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
336
369
  projectId: { type: "string", description: "The server-side project id." },
337
370
  shapeId: { type: "string", description: "The id of the shape to read." },
338
371
  },
339
372
  },
340
373
  },
341
- // Measuring runs on the REST API for the same reason hollowing does: the
342
- // numbers come from server-side OCCT's own curve and surface analysis, which
343
- // is the only place the exact geometry lives.
374
+ // Measuring uses exact CAD geometry in either the local engine or server API.
344
375
  {
345
376
  name: "sketchforge_measure_shape",
346
- description: "Measure every edge and face of a stored project shape from its exact CAD geometry: edge length, the radius and diameter of a circular edge or arc, face area, and a cylindrical face's radius. Exact (OCCT), so a round hole has a real radius rather than the chord length of a facet. A measurement that is not meaningful for the entity -- the radius of a straight edge, of an ellipse, or of a cone whose radius changes along it -- comes back null with a reason in radiusUnavailable. Works on a project on the server (REST API), not on an open editor tab.",
377
+ description: "Measure every edge and face of a stored project shape from its exact CAD geometry: edge length, the radius and diameter of a circular edge or arc, face area, and a cylindrical face's radius. Exact (OCCT), so a round hole has a real radius rather than the chord length of a facet. A measurement that is not meaningful for the entity -- the radius of a straight edge, of an ellipse, or of a cone whose radius changes along it -- comes back null with a reason in radiusUnavailable. Works offline or against a server when url is supplied.",
347
378
  inputSchema: {
348
379
  type: "object",
349
380
  required: ["projectId", "shapeId"],
350
381
  properties: {
382
+ url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
351
383
  projectId: { type: "string", description: "The server-side project id." },
352
384
  shapeId: { type: "string", description: "The id of the shape to measure." },
353
385
  },
@@ -355,11 +387,12 @@ const tools = [
355
387
  },
356
388
  {
357
389
  name: "sketchforge_measure_between",
358
- description: "The exact minimum distance between two CAD entities in a stored project, and the angle between them when both are flat faces. Each end names a shape and either the whole solid, or one edge or face by the index the measurement listing gave it. Distance is measured between the real surfaces where the shapes sit, so two round posts 5mm apart at their nearest walls read 5 -- not the gap between their bounding boxes. Works on a project on the server (REST API), not on an open editor tab.",
390
+ description: "The exact minimum distance between two CAD entities in a stored project, and the angle between them when both are flat faces. Each end names a shape and either the whole solid, or one edge or face by the index the measurement listing gave it. Distance is measured between the real surfaces where the shapes sit, so two round posts 5mm apart at their nearest walls read 5 -- not the gap between their bounding boxes. Works offline or against a server when url is supplied.",
359
391
  inputSchema: {
360
392
  type: "object",
361
393
  required: ["projectId", "from", "to"],
362
394
  properties: {
395
+ url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
363
396
  projectId: { type: "string", description: "The server-side project id." },
364
397
  from: {
365
398
  type: "object",
@@ -388,11 +421,12 @@ const tools = [
388
421
  },
389
422
  {
390
423
  name: "sketchforge_hollow_shape",
391
- description: "Hollow a stored project shape out to a wall of a given thickness, optionally leaving faces open so a box becomes a tray. Exact (OCCT), so the result still exports to STEP and can still be filleted. A sphere, torus, cone or round-walled tube cannot be hollowed at any thickness. Works on a project on the server (REST API), not on an open editor tab.",
424
+ description: "Hollow a stored project shape out to a wall of a given thickness, optionally leaving faces open so a box becomes a tray. Exact (OCCT), so the result still exports to STEP and can still be filleted. A sphere, torus, cone or round-walled tube cannot be hollowed at any thickness. Works offline or against a server when url is supplied.",
392
425
  inputSchema: {
393
426
  type: "object",
394
427
  required: ["projectId", "shapeId", "thickness"],
395
428
  properties: {
429
+ url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
396
430
  projectId: { type: "string", description: "The server-side project id." },
397
431
  shapeId: { type: "string", description: "The id of the shape to hollow." },
398
432
  thickness: { type: "number", description: "Wall thickness in mm, measured inwards. Must be well under half the part's smallest span." },
@@ -404,8 +438,7 @@ const tools = [
404
438
  },
405
439
  },
406
440
  },
407
- // Macros drive the headless REST API rather than an editor tab, and run only
408
- // from the directory the operator configured.
441
+ // Macros run only from the directory the operator configured.
409
442
  ...macroTools,
410
443
  ];
411
444
 
@@ -419,7 +452,7 @@ const API_TOKEN_ENV = "SKETCHFORGE_API_TOKEN";
419
452
  * to ask one for. The token is the same one the server was started with, and
420
453
  * without it every route answers 404 rather than saying it is switched off.
421
454
  */
422
- async function restRequest(method, path, { query = {}, body } = {}) {
455
+ async function restRequest(method, path, { query = {}, body, baseUrl } = {}) {
423
456
  const token = process.env[API_TOKEN_ENV];
424
457
  if (!token) {
425
458
  throw new Error(
@@ -448,12 +481,12 @@ async function restRequest(method, path, { query = {}, body } = {}) {
448
481
  return payload;
449
482
  }
450
483
 
451
- function bridgeUrl() {
484
+ function bridgeUrl(baseUrl) {
452
485
  return new URL(MCP_ROUTE, baseUrl);
453
486
  }
454
487
 
455
- async function bridgeGet() {
456
- const response = await fetch(bridgeUrl());
488
+ async function bridgeGet(baseUrl) {
489
+ const response = await fetch(bridgeUrl(baseUrl));
457
490
  const payload = await response.json().catch(() => null);
458
491
  if (!response.ok) {
459
492
  throw new Error(payload?.error || `SketchForge bridge returned HTTP ${response.status}`);
@@ -461,13 +494,13 @@ async function bridgeGet() {
461
494
  return payload;
462
495
  }
463
496
 
464
- async function bridgeCommand(action, args = {}, defaultTimeoutMs = 15000) {
465
- const { editorNumber, editorId, timeoutMs, ...params } = args || {};
497
+ async function bridgeCommand(action, args = {}, defaultTimeoutMs = 15000, baseUrl) {
498
+ const { editorNumber, editorId, timeoutMs, url, ...params } = args || {};
466
499
  let targetNumber = typeof editorNumber === "number" ? editorNumber : undefined;
467
500
  let targetId = typeof editorId === "string" ? editorId : undefined;
468
501
 
469
502
  if (!targetNumber && !targetId) {
470
- const { editors = [] } = await bridgeGet();
503
+ const { editors = [] } = await bridgeGet(baseUrl);
471
504
  if (editors.length === 1) {
472
505
  targetNumber = editors[0].editorNumber;
473
506
  } else {
@@ -475,7 +508,7 @@ async function bridgeCommand(action, args = {}, defaultTimeoutMs = 15000) {
475
508
  }
476
509
  }
477
510
 
478
- const response = await fetch(bridgeUrl(), {
511
+ const response = await fetch(bridgeUrl(baseUrl), {
479
512
  method: "POST",
480
513
  headers: { "Content-Type": "application/json" },
481
514
  body: JSON.stringify({
@@ -494,50 +527,53 @@ async function bridgeCommand(action, args = {}, defaultTimeoutMs = 15000) {
494
527
  return payload.data;
495
528
  }
496
529
 
497
- async function callTool(name, args) {
530
+ async function callRemoteTool(name, args, baseUrl) {
498
531
  switch (name) {
499
532
  case "sketchforge_list_editors":
500
- return bridgeGet();
533
+ return bridgeGet(baseUrl);
501
534
  case "sketchforge_read_scene":
502
- return bridgeCommand("get_scene", args);
535
+ return bridgeCommand("get_scene", args, 15000, baseUrl);
503
536
  case "sketchforge_list_objects":
504
- return bridgeCommand("list_objects", args);
537
+ return bridgeCommand("list_objects", args, 15000, baseUrl);
505
538
  case "sketchforge_select_objects":
506
- return bridgeCommand("select_objects", args);
539
+ return bridgeCommand("select_objects", args, 15000, baseUrl);
540
+ case "sketchforge_mirror_objects":
541
+ return bridgeCommand("mirror_objects", args, 15000, baseUrl);
507
542
  case "sketchforge_delete_objects":
508
- return bridgeCommand("delete_objects", args);
543
+ return bridgeCommand("delete_objects", args, 15000, baseUrl);
509
544
  case "sketchforge_create_shape":
510
- return bridgeCommand("create_shape", args);
545
+ return bridgeCommand("create_shape", args, 15000, baseUrl);
511
546
  case "sketchforge_import_mesh":
512
- return bridgeCommand("import_mesh", args, 60000);
547
+ return bridgeCommand("import_mesh", args, 60000, baseUrl);
513
548
  case "sketchforge_update_object":
514
- return bridgeCommand("update_object", args);
549
+ return bridgeCommand("update_object", args, 15000, baseUrl);
515
550
  case "sketchforge_align_objects":
516
- return bridgeCommand("align_objects", args);
551
+ return bridgeCommand("align_objects", args, 15000, baseUrl);
517
552
  case "sketchforge_distribute_objects":
518
- return bridgeCommand("distribute_objects", args);
553
+ return bridgeCommand("distribute_objects", args, 15000, baseUrl);
519
554
  case "sketchforge_pattern_objects":
520
- return bridgeCommand("pattern_objects", args);
555
+ return bridgeCommand("pattern_objects", args, 15000, baseUrl);
521
556
  case "sketchforge_group_objects":
522
- return bridgeCommand("group_objects", args, 30000);
557
+ return bridgeCommand("group_objects", args, 30000, baseUrl);
523
558
  case "sketchforge_ungroup_objects":
524
- return bridgeCommand("ungroup_objects", args);
559
+ return bridgeCommand("ungroup_objects", args, 15000, baseUrl);
525
560
  case "sketchforge_boolean_cut":
526
- return bridgeCommand("boolean_cut", args, 45000);
561
+ return bridgeCommand("boolean_cut", args, 45000, baseUrl);
527
562
  case "sketchforge_separate_parts":
528
- return bridgeCommand("separate_parts", args);
563
+ return bridgeCommand("separate_parts", args, 15000, baseUrl);
529
564
  case "sketchforge_list_edges":
530
- return bridgeCommand("list_edges", args, 30000);
565
+ return bridgeCommand("list_edges", args, 30000, baseUrl);
531
566
  case "sketchforge_apply_edge_treatment":
532
- return bridgeCommand("apply_edge_treatment", args, 60000);
567
+ return bridgeCommand("apply_edge_treatment", args, 60000, baseUrl);
533
568
  case "sketchforge_list_faces":
534
- return restRequest("GET", "/faces", { query: { projectId: args.projectId, shapeId: args.shapeId } });
569
+ return restRequest("GET", "/faces", { query: { projectId: args.projectId, shapeId: args.shapeId }, baseUrl });
535
570
  case "sketchforge_measure_shape":
536
- return restRequest("GET", "/measurements", { query: { projectId: args.projectId, shapeId: args.shapeId } });
571
+ return restRequest("GET", "/measurements", { query: { projectId: args.projectId, shapeId: args.shapeId }, baseUrl });
537
572
  case "sketchforge_measure_between":
538
573
  return restRequest("POST", "/measurements", {
539
574
  query: { projectId: args.projectId },
540
575
  body: { from: args.from, to: args.to },
576
+ baseUrl,
541
577
  });
542
578
  case "sketchforge_hollow_shape":
543
579
  return restRequest("POST", "/shell", {
@@ -546,20 +582,58 @@ async function callTool(name, args) {
546
582
  thickness: args.thickness,
547
583
  ...(args.openFaces === undefined ? {} : { openFaces: args.openFaces }),
548
584
  },
585
+ baseUrl,
549
586
  });
550
587
  case "sketchforge_inspect_errors":
551
- return bridgeCommand("inspect_errors", args);
588
+ return bridgeCommand("inspect_errors", args, 15000, baseUrl);
552
589
  case "sketchforge_capture_image":
553
- return bridgeCommand("capture_image", args, 30000);
590
+ return bridgeCommand("capture_image", args, 30000, baseUrl);
591
+ case "sketchforge_export_scene": {
592
+ const artifact = await bridgeCommand("export_scene", args, 60000, baseUrl);
593
+ if (typeof args.outputPath === "string" && args.outputPath.trim()) {
594
+ const destination = path.resolve(args.outputPath);
595
+ writeFileSync(destination, Buffer.from(artifact.base64, "base64"));
596
+ return { filename: artifact.filename, mimeType: artifact.mimeType, bytes: artifact.bytes, shapeCount: artifact.shapeCount, savedTo: destination };
597
+ }
598
+ return artifact;
599
+ }
600
+ case "sketchforge_validate_scene":
601
+ return bridgeCommand("validate_scene", args, 60000, baseUrl);
554
602
  case "sketchforge_list_macros":
555
603
  return listMacros();
556
604
  case "sketchforge_run_macro":
557
- return runMacroByName(args);
605
+ return runMacroByName(args, { environment: { ...process.env, SKETCHFORGE_URL: baseUrl } });
558
606
  default:
559
607
  throw new Error(`Unknown tool: ${name}`);
560
608
  }
561
609
  }
562
610
 
611
+ function normalizedServerUrl(value) {
612
+ let parsed;
613
+ try {
614
+ parsed = new URL(value);
615
+ } catch {
616
+ throw new Error("url must be an absolute http:// or https:// SketchForge server URL.");
617
+ }
618
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password) {
619
+ throw new Error("url must be an absolute http:// or https:// SketchForge server URL without embedded credentials.");
620
+ }
621
+ return parsed.toString().replace(/\/$/, "");
622
+ }
623
+
624
+ async function callTool(name, args = {}) {
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
+ }
629
+ if (typeof url === "string" && url.trim()) {
630
+ return callRemoteTool(name, toolArgs, normalizedServerUrl(url.trim()));
631
+ }
632
+ if (name === "sketchforge_list_macros") return listMacros();
633
+ if (name === "sketchforge_run_macro") return runMacroByName(toolArgs);
634
+ return callLocalEngineTool(name, toolArgs);
635
+ }
636
+
563
637
  function textContent(value) {
564
638
  return {
565
639
  type: "text",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@constructorfleet/sketchforge3d",
3
- "version": "1.5.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": {
@@ -18,6 +18,11 @@
18
18
  "macro",
19
19
  "client"
20
20
  ],
21
+ "dependencies": {
22
+ "@constructorfleet/sketchforge-engine": "1.8.0",
23
+ "fflate": "^0.8.3",
24
+ "sharp": "^0.35.5"
25
+ },
21
26
  "type": "module",
22
27
  "main": "./dist/index.js",
23
28
  "types": "./dist/index.d.ts",
@@ -38,7 +43,7 @@
38
43
  "README.md"
39
44
  ],
40
45
  "engines": {
41
- "node": ">=18"
46
+ "node": ">=20"
42
47
  },
43
48
  "publishConfig": {
44
49
  "access": "public"