@constructorfleet/sketchforge3d 1.2.0 → 1.3.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/mcp/server.mjs ADDED
@@ -0,0 +1,524 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { listMacros, macroTools, runMacroByName } from "./macroTools.mjs";
7
+
8
+ const DEFAULT_BASE_URL = "http://127.0.0.1:3000";
9
+
10
+ /**
11
+ * The version this bridge reports is the package's, read at startup rather than
12
+ * written here: it ships inside `@constructorfleet/sketchforge3d`, whose version
13
+ * tracks the app's, and a client that logs a hand-written number would say
14
+ * something untrue after the first release.
15
+ */
16
+ const version = (() => {
17
+ try {
18
+ const manifest = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
19
+ const parsed = JSON.parse(readFileSync(manifest, "utf8"));
20
+ return typeof parsed.version === "string" ? parsed.version : "0.0.0";
21
+ } catch {
22
+ return "0.0.0";
23
+ }
24
+ })();
25
+ const MCP_ROUTE = "/api/sketchforge-mcp";
26
+ const baseUrl = process.env.SKETCHFORGE_URL || DEFAULT_BASE_URL;
27
+
28
+ const editorTargetSchema = {
29
+ type: "object",
30
+ properties: {
31
+ editorNumber: { type: "number", description: "The 5-digit SketchForge editor number from sketchforge_list_editors." },
32
+ editorId: { type: "string", description: "Optional internal editor id. Prefer editorNumber for human-directed use." },
33
+ timeoutMs: { type: "number", description: "Command timeout in milliseconds. Defaults to 15000." },
34
+ },
35
+ };
36
+
37
+ const tools = [
38
+ {
39
+ name: "sketchforge_list_editors",
40
+ description: "List SketchForge editor tabs that are currently open and heartbeating, including editorNumber and projectName.",
41
+ inputSchema: { type: "object", properties: {} },
42
+ },
43
+ {
44
+ name: "sketchforge_read_scene",
45
+ description: "Read the current scene, selection, workspace units, and exact object dimensions from an open SketchForge editor.",
46
+ inputSchema: {
47
+ ...editorTargetSchema,
48
+ properties: {
49
+ ...editorTargetSchema.properties,
50
+ includeRawShapes: { type: "boolean", description: "Include raw WorkplaneShape JSON. Can be large for imported meshes." },
51
+ },
52
+ },
53
+ },
54
+ {
55
+ name: "sketchforge_list_objects",
56
+ description: "List all current objects available in the editor with exact dimensions, position, rotation, and object ids.",
57
+ inputSchema: editorTargetSchema,
58
+ },
59
+ {
60
+ name: "sketchforge_select_objects",
61
+ description: "Select objects by id in the SketchForge editor.",
62
+ inputSchema: {
63
+ ...editorTargetSchema,
64
+ required: ["ids"],
65
+ properties: {
66
+ ...editorTargetSchema.properties,
67
+ ids: { type: "array", items: { type: "string" } },
68
+ },
69
+ },
70
+ },
71
+ {
72
+ name: "sketchforge_delete_objects",
73
+ description: "Delete objects by id, or delete the current selection when ids are omitted.",
74
+ inputSchema: {
75
+ ...editorTargetSchema,
76
+ properties: {
77
+ ...editorTargetSchema.properties,
78
+ ids: { type: "array", items: { type: "string" } },
79
+ id: { type: "string" },
80
+ },
81
+ },
82
+ },
83
+ {
84
+ name: "sketchforge_create_shape",
85
+ description: "Create a box/cube, cylinder, loft, simple extruded sketch, revolve, or standard screw thread in SketchForge.",
86
+ inputSchema: {
87
+ ...editorTargetSchema,
88
+ required: ["kind"],
89
+ properties: {
90
+ ...editorTargetSchema.properties,
91
+ kind: { type: "string", enum: ["box", "cube", "cylinder", "sketch", "loft", "revolve", "thread"] },
92
+ profile: {
93
+ 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.",
95
+ items: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2 },
96
+ },
97
+ 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." },
98
+ turns: { type: "number", description: "For kind revolve/thread: how many full turns to sweep (default 8 for a thread)." },
99
+ diameter: { type: "number", description: "For kind thread: outside diameter in mm, for a size the catalog does not list. The 60-degree ISO profile follows from this and the pitch." },
100
+ length: { type: "number", description: "For kind thread: how long the thread should be in mm, instead of giving turns." },
101
+ hole: { type: "boolean", description: "For kind thread: cut the form wider by a clearance so a bolt of that size fits, and mark the shape as a hole so grouping it with a solid taps that solid." },
102
+ clearance: { type: "number", description: "For kind thread with hole: how much wider to cut, per side, in mm (default 0.2 for printed parts)." },
103
+ startAngle: { type: "number", description: "For kind revolve: rotation the sweep starts at, in degrees." },
104
+ sweepAngle: { type: "number", description: "For kind revolve with no pitch: how far round to revolve, in degrees (±360)." },
105
+ name: { type: "string" },
106
+ color: { type: "string" },
107
+ x: { type: "number" },
108
+ z: { type: "number" },
109
+ elevation: { type: "number" },
110
+ width: { type: "number", description: "For loft, this is the bottom end's width." },
111
+ depth: { type: "number", description: "For loft, this is the bottom end's depth." },
112
+ height: { type: "number" },
113
+ size: {
114
+ type: ["number", "string"],
115
+ description: 'A number sets width, depth and height at once. For kind thread it may instead be a catalog designation carrying its own pitch: "M2" to "M20" metric coarse, or "#4-40" to "1/2-13" imperial UNC (default M8).',
116
+ },
117
+ rotation: { type: "number" },
118
+ rotationX: { type: "number" },
119
+ rotationZ: { type: "number" },
120
+ sides: { type: "number" },
121
+ loftBottomShape: { type: "string", enum: ["Oval", "Rectangle", "Triangle", "Pentagon", "Hexagon"], description: "loft only. Defaults to Rectangle." },
122
+ loftTopShape: { type: "string", enum: ["Oval", "Rectangle", "Triangle", "Pentagon", "Hexagon"], description: "loft only. Defaults to Oval." },
123
+ loftTopWidth: { type: "number", description: "loft only. Independent of the bottom's width, like a cone's top radius. Defaults to matching width." },
124
+ loftTopDepth: { type: "number", description: "loft only. Independent of the bottom's depth. Defaults to matching depth." },
125
+ loftBottomRotation: { type: "number", description: "loft only. Bottom end rotation in degrees." },
126
+ loftTopRotation: { type: "number", description: "loft only. Top end rotation in degrees." },
127
+ loftSegments: { type: "number", description: "loft only. Angular resolution, 8-128." },
128
+ loftLayers: { type: "number", description: "loft only. Vertical resolution, 2-80." },
129
+ },
130
+ },
131
+ },
132
+ {
133
+ name: "sketchforge_import_mesh",
134
+ description: "Import a triangle mesh into SketchForge from raw position and optional normal arrays.",
135
+ inputSchema: {
136
+ ...editorTargetSchema,
137
+ required: ["positions"],
138
+ properties: {
139
+ ...editorTargetSchema.properties,
140
+ name: { type: "string" },
141
+ color: { type: "string" },
142
+ x: { type: "number" },
143
+ z: { type: "number" },
144
+ elevation: { type: "number" },
145
+ width: { type: "number" },
146
+ depth: { type: "number" },
147
+ height: { type: "number" },
148
+ positions: { type: "array", items: { type: "number" } },
149
+ normals: { type: "array", items: { type: "number" } },
150
+ },
151
+ },
152
+ },
153
+ {
154
+ name: "sketchforge_update_object",
155
+ description: "Update one object's exact dimensions, position, color, name, hole state, or rotations.",
156
+ inputSchema: {
157
+ ...editorTargetSchema,
158
+ required: ["id"],
159
+ properties: {
160
+ ...editorTargetSchema.properties,
161
+ id: { type: "string" },
162
+ name: { type: "string" },
163
+ color: { type: "string" },
164
+ hole: { type: "boolean" },
165
+ x: { type: "number" },
166
+ z: { type: "number" },
167
+ elevation: { type: "number" },
168
+ width: { type: "number" },
169
+ depth: { type: "number" },
170
+ height: { type: "number" },
171
+ size: { type: "number" },
172
+ rotation: { type: "number" },
173
+ rotationX: { type: "number" },
174
+ rotationZ: { type: "number" },
175
+ },
176
+ },
177
+ },
178
+ {
179
+ name: "sketchforge_pattern_objects",
180
+ description: "Repeat SketchForge objects in a row or around a ring, the way the editor's Repeat panel does. Makes the copies; sketchforge_distribute_objects only re-spaces objects that already exist.",
181
+ inputSchema: {
182
+ ...editorTargetSchema,
183
+ properties: {
184
+ ...editorTargetSchema.properties,
185
+ ids: { type: "array", items: { type: "string" }, description: "Object ids to repeat. If omitted, uses the current selection." },
186
+ kind: { type: "string", enum: ["linear", "circular"], description: "linear=a row; circular=a ring about a centre. Default linear." },
187
+ count: { type: "number", description: "Total copies including the original, so 4 adds 3 (2-200). Default 4." },
188
+ stepX: { type: "number", description: "For kind linear: centre-to-centre step along X in mm. This is a pitch, not a gap." },
189
+ stepZ: { type: "number", description: "For kind linear: centre-to-centre step along Z in mm." },
190
+ centerX: { type: "number", description: "For kind circular: X of the point to turn about." },
191
+ centerZ: { type: "number", description: "For kind circular: Z of the point to turn about." },
192
+ sweepAngle: { type: "number", description: "For kind circular: how far round to spread the copies, in degrees. 360 divides evenly so the last does not land on the first; a partial sweep puts one copy at each end. Default 360." },
193
+ rotateCopies: { type: "boolean", description: "For kind circular: whether each copy turns to follow the ring (default true). A spoke or vane needs it; a bolt hole does not." },
194
+ },
195
+ },
196
+ },
197
+ {
198
+ name: "sketchforge_distribute_objects",
199
+ description: "Spread three or more SketchForge objects evenly along an axis, the way the editor's Distribute buttons do. The outermost two keep their places and define the span.",
200
+ inputSchema: {
201
+ ...editorTargetSchema,
202
+ properties: {
203
+ ...editorTargetSchema.properties,
204
+ ids: { type: "array", items: { type: "string" }, description: "Object ids to distribute. If omitted, uses the current selection." },
205
+ axis: { type: "string", enum: ["x", "z"], description: "Axis to spread along. Omit to use whichever axis the objects are already most spread along." },
206
+ spacing: { type: "string", enum: ["gaps", "centers"], description: "gaps=equal clear space between objects (default); centers=equal centre-to-centre pitch." },
207
+ },
208
+ },
209
+ },
210
+ {
211
+ name: "sketchforge_align_objects",
212
+ description: "Align two or more SketchForge objects using the same alignment logic as the editor Alignment button.",
213
+ inputSchema: {
214
+ ...editorTargetSchema,
215
+ required: ["axis", "target"],
216
+ properties: {
217
+ ...editorTargetSchema.properties,
218
+ ids: { type: "array", items: { type: "string" }, description: "Object ids to align. If omitted, uses the current selection." },
219
+ anchorId: { type: "string", description: "Optional object id to keep fixed as the alignment reference." },
220
+ axis: { type: "string", enum: ["x", "y", "z"], description: "x=left/right, z=front/back, y=bottom/top." },
221
+ target: { type: "string", enum: ["min", "center", "max"], description: "Which side/center to align." },
222
+ },
223
+ },
224
+ },
225
+ {
226
+ name: "sketchforge_group_objects",
227
+ description: "Group objects by id using SketchForge's normal grouping/boolean pipeline.",
228
+ inputSchema: {
229
+ ...editorTargetSchema,
230
+ required: ["ids"],
231
+ properties: {
232
+ ...editorTargetSchema.properties,
233
+ ids: { type: "array", items: { type: "string" } },
234
+ },
235
+ },
236
+ },
237
+ {
238
+ name: "sketchforge_ungroup_objects",
239
+ description: "Ungroup one or more grouped objects by id and preserve their edited geometry.",
240
+ inputSchema: {
241
+ ...editorTargetSchema,
242
+ properties: {
243
+ ...editorTargetSchema.properties,
244
+ ids: { type: "array", items: { type: "string" } },
245
+ id: { type: "string" },
246
+ },
247
+ },
248
+ },
249
+ {
250
+ name: "sketchforge_boolean_cut",
251
+ description: "Cut solids with hole objects. Provide solidIds and holeIds; the result replaces the operands.",
252
+ inputSchema: {
253
+ ...editorTargetSchema,
254
+ required: ["solidIds", "holeIds"],
255
+ properties: {
256
+ ...editorTargetSchema.properties,
257
+ solidIds: { type: "array", items: { type: "string" } },
258
+ holeIds: { type: "array", items: { type: "string" } },
259
+ },
260
+ },
261
+ },
262
+ {
263
+ name: "sketchforge_separate_parts",
264
+ description: "Separate one disconnected multi-part object into independent objects.",
265
+ inputSchema: {
266
+ ...editorTargetSchema,
267
+ properties: {
268
+ ...editorTargetSchema.properties,
269
+ id: { type: "string" },
270
+ },
271
+ },
272
+ },
273
+ {
274
+ name: "sketchforge_list_edges",
275
+ description: "List real CAD edge ids for one object so a later chamfer/fillet can target specific edges.",
276
+ inputSchema: {
277
+ ...editorTargetSchema,
278
+ required: ["id"],
279
+ properties: {
280
+ ...editorTargetSchema.properties,
281
+ id: { type: "string" },
282
+ sharpAngle: { type: "number" },
283
+ },
284
+ },
285
+ },
286
+ {
287
+ name: "sketchforge_apply_edge_treatment",
288
+ description: "Apply chamfer or fillet to specific edge ids returned by sketchforge_list_edges.",
289
+ inputSchema: {
290
+ ...editorTargetSchema,
291
+ required: ["id", "kind", "edgeIds", "amount"],
292
+ properties: {
293
+ ...editorTargetSchema.properties,
294
+ id: { type: "string" },
295
+ kind: { type: "string", enum: ["chamfer", "fillet"] },
296
+ edgeIds: {
297
+ anyOf: [
298
+ { type: "array", items: { type: "number" } },
299
+ { type: "string", enum: ["all"] },
300
+ ],
301
+ },
302
+ allEdges: { type: "boolean" },
303
+ amount: { type: "number" },
304
+ chamferAngle: { type: "number" },
305
+ sharpAngle: { type: "number" },
306
+ quality: { type: "string", enum: ["draft", "standard", "fine"] },
307
+ preserveEdgeSize: { type: "boolean" },
308
+ },
309
+ },
310
+ },
311
+ {
312
+ name: "sketchforge_inspect_errors",
313
+ description: "Inspect the editor notice, last MCP error, and active edge modifier error.",
314
+ inputSchema: editorTargetSchema,
315
+ },
316
+ {
317
+ name: "sketchforge_capture_image",
318
+ description: "Capture a PNG image of the editor viewport from current/home/top/bottom/front/back/right/left view.",
319
+ inputSchema: {
320
+ ...editorTargetSchema,
321
+ properties: {
322
+ ...editorTargetSchema.properties,
323
+ face: { type: "string", enum: ["current", "home", "top", "bottom", "front", "back", "right", "left"] },
324
+ },
325
+ },
326
+ },
327
+ // Macros drive the headless REST API rather than an editor tab, and run only
328
+ // from the directory the operator configured.
329
+ ...macroTools,
330
+ ];
331
+
332
+ function bridgeUrl() {
333
+ return new URL(MCP_ROUTE, baseUrl);
334
+ }
335
+
336
+ async function bridgeGet() {
337
+ const response = await fetch(bridgeUrl());
338
+ const payload = await response.json().catch(() => null);
339
+ if (!response.ok) {
340
+ throw new Error(payload?.error || `SketchForge bridge returned HTTP ${response.status}`);
341
+ }
342
+ return payload;
343
+ }
344
+
345
+ async function bridgeCommand(action, args = {}, defaultTimeoutMs = 15000) {
346
+ const { editorNumber, editorId, timeoutMs, ...params } = args || {};
347
+ let targetNumber = typeof editorNumber === "number" ? editorNumber : undefined;
348
+ let targetId = typeof editorId === "string" ? editorId : undefined;
349
+
350
+ if (!targetNumber && !targetId) {
351
+ const { editors = [] } = await bridgeGet();
352
+ if (editors.length === 1) {
353
+ targetNumber = editors[0].editorNumber;
354
+ } else {
355
+ throw new Error(editors.length === 0 ? "No open SketchForge editors found" : "Provide editorNumber because multiple SketchForge editors are open");
356
+ }
357
+ }
358
+
359
+ const response = await fetch(bridgeUrl(), {
360
+ method: "POST",
361
+ headers: { "Content-Type": "application/json" },
362
+ body: JSON.stringify({
363
+ type: "command",
364
+ editorNumber: targetNumber,
365
+ editorId: targetId,
366
+ action,
367
+ params,
368
+ timeoutMs: typeof timeoutMs === "number" ? timeoutMs : defaultTimeoutMs,
369
+ }),
370
+ });
371
+ const payload = await response.json().catch(() => null);
372
+ if (!payload?.ok) {
373
+ throw new Error(payload?.error || `SketchForge command failed with HTTP ${response.status}`);
374
+ }
375
+ return payload.data;
376
+ }
377
+
378
+ async function callTool(name, args) {
379
+ switch (name) {
380
+ case "sketchforge_list_editors":
381
+ return bridgeGet();
382
+ case "sketchforge_read_scene":
383
+ return bridgeCommand("get_scene", args);
384
+ case "sketchforge_list_objects":
385
+ return bridgeCommand("list_objects", args);
386
+ case "sketchforge_select_objects":
387
+ return bridgeCommand("select_objects", args);
388
+ case "sketchforge_delete_objects":
389
+ return bridgeCommand("delete_objects", args);
390
+ case "sketchforge_create_shape":
391
+ return bridgeCommand("create_shape", args);
392
+ case "sketchforge_import_mesh":
393
+ return bridgeCommand("import_mesh", args, 60000);
394
+ case "sketchforge_update_object":
395
+ return bridgeCommand("update_object", args);
396
+ case "sketchforge_align_objects":
397
+ return bridgeCommand("align_objects", args);
398
+ case "sketchforge_distribute_objects":
399
+ return bridgeCommand("distribute_objects", args);
400
+ case "sketchforge_pattern_objects":
401
+ return bridgeCommand("pattern_objects", args);
402
+ case "sketchforge_group_objects":
403
+ return bridgeCommand("group_objects", args, 30000);
404
+ case "sketchforge_ungroup_objects":
405
+ return bridgeCommand("ungroup_objects", args);
406
+ case "sketchforge_boolean_cut":
407
+ return bridgeCommand("boolean_cut", args, 45000);
408
+ case "sketchforge_separate_parts":
409
+ return bridgeCommand("separate_parts", args);
410
+ case "sketchforge_list_edges":
411
+ return bridgeCommand("list_edges", args, 30000);
412
+ case "sketchforge_apply_edge_treatment":
413
+ return bridgeCommand("apply_edge_treatment", args, 60000);
414
+ case "sketchforge_inspect_errors":
415
+ return bridgeCommand("inspect_errors", args);
416
+ case "sketchforge_capture_image":
417
+ return bridgeCommand("capture_image", args, 30000);
418
+ case "sketchforge_list_macros":
419
+ return listMacros();
420
+ case "sketchforge_run_macro":
421
+ return runMacroByName(args);
422
+ default:
423
+ throw new Error(`Unknown tool: ${name}`);
424
+ }
425
+ }
426
+
427
+ function textContent(value) {
428
+ return {
429
+ type: "text",
430
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2),
431
+ };
432
+ }
433
+
434
+ function toolResult(value) {
435
+ if (value?.dataUrl?.startsWith?.("data:image/png;base64,")) {
436
+ return {
437
+ content: [
438
+ textContent({ face: value.face, bytesApprox: value.bytesApprox }),
439
+ {
440
+ type: "image",
441
+ data: value.dataUrl.slice("data:image/png;base64,".length),
442
+ mimeType: "image/png",
443
+ },
444
+ ],
445
+ };
446
+ }
447
+ return { content: [textContent(value)] };
448
+ }
449
+
450
+ function send(message) {
451
+ process.stdout.write(`${JSON.stringify(message)}\n`);
452
+ }
453
+
454
+ function sendResult(id, result) {
455
+ send({ jsonrpc: "2.0", id, result });
456
+ }
457
+
458
+ function sendError(id, code, message) {
459
+ send({ jsonrpc: "2.0", id, error: { code, message } });
460
+ }
461
+
462
+ async function handleMessage(message) {
463
+ if (!message || typeof message !== "object") return;
464
+ const { id, method, params } = message;
465
+ try {
466
+ if (method === "initialize") {
467
+ sendResult(id, {
468
+ protocolVersion: params?.protocolVersion || "2024-11-05",
469
+ capabilities: { tools: {} },
470
+ serverInfo: { name: "sketchforge-mcp", version },
471
+ });
472
+ return;
473
+ }
474
+ if (method === "notifications/initialized") {
475
+ return;
476
+ }
477
+ if (method === "ping") {
478
+ sendResult(id, {});
479
+ return;
480
+ }
481
+ if (method === "tools/list") {
482
+ sendResult(id, { tools });
483
+ return;
484
+ }
485
+ if (method === "tools/call") {
486
+ const name = params?.name;
487
+ if (typeof name !== "string") {
488
+ sendError(id, -32602, "Expected tool name");
489
+ return;
490
+ }
491
+ const result = await callTool(name, params?.arguments || {});
492
+ sendResult(id, toolResult(result));
493
+ return;
494
+ }
495
+ if (method === "resources/list") {
496
+ sendResult(id, { resources: [] });
497
+ return;
498
+ }
499
+ sendError(id, -32601, `Unknown method: ${method}`);
500
+ } catch (error) {
501
+ if (method === "tools/call") {
502
+ sendResult(id, { isError: true, content: [textContent(error instanceof Error ? error.message : String(error))] });
503
+ return;
504
+ }
505
+ sendError(id, -32000, error instanceof Error ? error.message : String(error));
506
+ }
507
+ }
508
+
509
+ let buffer = "";
510
+ process.stdin.setEncoding("utf8");
511
+ process.stdin.on("data", (chunk) => {
512
+ buffer += chunk;
513
+ const lines = buffer.split(/\r?\n/);
514
+ buffer = lines.pop() || "";
515
+ lines.forEach((line) => {
516
+ const trimmed = line.trim();
517
+ if (!trimmed) return;
518
+ try {
519
+ void handleMessage(JSON.parse(trimmed));
520
+ } catch (error) {
521
+ sendError(null, -32700, error instanceof Error ? error.message : String(error));
522
+ }
523
+ });
524
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@constructorfleet/sketchforge3d",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Typed client and macro runner for the SketchForge REST API.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": {
@@ -28,11 +28,13 @@
28
28
  }
29
29
  },
30
30
  "bin": {
31
- "sketchforge-macro": "./dist/cli.js"
31
+ "sketchforge-macro": "./dist/cli.js",
32
+ "sketchforge-mcp": "./mcp/server.mjs"
32
33
  },
33
34
  "files": [
34
35
  "dist",
35
36
  "examples",
37
+ "mcp",
36
38
  "README.md"
37
39
  ],
38
40
  "engines": {