@constructorfleet/sketchforge3d 1.31.0 → 1.32.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 CHANGED
@@ -1,969 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { readFileSync, writeFileSync } from "node:fs";
4
- import path from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { resolveMcpReadPath, resolveMcpWritePath } from "./filesystemPaths.mjs";
7
- import { listMacros, macroTools, runMacroByName } from "./macroTools.mjs";
8
- import { callLocalEngineTool } from "./localEngine.mjs";
9
- import {
10
- CREATE_SHAPE_KINDS,
11
- EDITOR_SHAPE_KINDS,
12
- LOCAL_SHAPE_KINDS,
13
- LOCAL_SOLID_KINDS,
14
- LOCAL_STORED_KINDS,
15
- STEP_KINDS,
16
- TAPER_KINDS,
17
- } from "./createShapeKinds.mjs";
3
+ import { createDispatcher, rpcError } from "./protocol.mjs";
4
+ import { callTool, tools } from "./tools.mjs";
18
5
 
19
-
20
- /**
21
- * The version this bridge reports is the package's, read at startup rather than
22
- * written here: it ships inside `@constructorfleet/sketchforge3d`, whose version
23
- * tracks the app's, and a client that logs a hand-written number would say
24
- * something untrue after the first release.
25
- */
26
- const version = (() => {
27
- try {
28
- const manifest = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json");
29
- const parsed = JSON.parse(readFileSync(manifest, "utf8"));
30
- return typeof parsed.version === "string" ? parsed.version : "0.0.0";
31
- } catch {
32
- return "0.0.0";
33
- }
34
- })();
35
- const MCP_ROUTE = "/api/sketchforge-mcp";
36
- /** What a drawing shows, as `POST /exports` and the engine name it. Kept in step by `localMcpEngine.test.ts`. */
37
- const PROJECTION_LAYOUTS = ["multiview", "front", "back", "top", "bottom", "left", "right", "iso"];
38
- const SECTION_PLANES = ["xy", "xz", "yz"];
39
-
40
-
41
- const editorTargetSchema = {
42
- type: "object",
43
- properties: {
44
- url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
45
- projectId: { type: "string", description: "Project id in SKETCHFORGE_PROJECTS_DIR when running the MCP in local mode." },
46
- editorNumber: { type: "number", description: "The 5-digit SketchForge editor number from sketchforge_list_editors." },
47
- editorId: { type: "string", description: "Optional internal editor id. Prefer editorNumber for human-directed use." },
48
- timeoutMs: { type: "number", description: "Command timeout in milliseconds. Defaults to 15000." },
49
- },
50
- };
51
- const localProjectSchema = { type: "object", properties: {} };
52
- /** What group_objects and boolean_cut may name and colour the shape they leave behind. */
53
- const resultAttributeProperties = {
54
- name: { type: "string", description: "Name for the result (default \"Group\")." },
55
- color: { type: "string", description: "Color for the result, stored as given as create_shape stores its color, such as #2a9d8f (default the first solid's color)." },
56
- };
57
-
58
- const tools = [
59
- {
60
- name: "sketchforge_list_projects",
61
- description: "List projects stored in SKETCHFORGE_PROJECTS_DIR for offline MCP use.",
62
- inputSchema: localProjectSchema,
63
- },
64
- {
65
- name: "sketchforge_create_project",
66
- description: "Create an empty project in the local SKETCHFORGE_PROJECTS_DIR.",
67
- inputSchema: { ...localProjectSchema, required: ["name"], properties: { name: { type: "string" } } },
68
- },
69
- {
70
- name: "sketchforge_import_project",
71
- description: "Import a local .skf file as a new project in SKETCHFORGE_PROJECTS_DIR. File reads are confined to SKETCHFORGE_MCP_FILES_DIR, or SKETCHFORGE_PROJECTS_DIR when unset; if both are unset, paths are unrestricted.",
72
- inputSchema: { ...localProjectSchema, required: ["filePath"], properties: { filePath: { type: "string", description: "Path to a .skf under SKETCHFORGE_MCP_FILES_DIR (or SKETCHFORGE_PROJECTS_DIR when unset); unrestricted if neither is set." }, name: { type: "string" } } },
73
- },
74
- {
75
- name: "sketchforge_list_editors",
76
- description: "List SketchForge editor tabs that are currently open and heartbeating, including editorNumber and projectName.",
77
- inputSchema: { ...editorTargetSchema, properties: { url: editorTargetSchema.properties.url } },
78
- },
79
- {
80
- name: "sketchforge_read_scene",
81
- 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.",
82
- inputSchema: {
83
- ...editorTargetSchema,
84
- properties: {
85
- ...editorTargetSchema.properties,
86
- includeRawShapes: { type: "boolean", description: "Include raw WorkplaneShape JSON. Can be large for imported meshes." },
87
- shapeIds: { type: "array", items: { type: "string" }, description: "Limit the response to these object ids (including rawShapes)." },
88
- excludeShapeIds: { type: "array", items: { type: "string" }, description: "Omit these object ids, useful for large reference meshes." },
89
- includeRawShapeIds: { type: "array", items: { type: "string" }, description: "Include raw geometry only for these ids; takes precedence over includeRawShapes." },
90
- },
91
- },
92
- },
93
- {
94
- name: "sketchforge_list_objects",
95
- 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.",
96
- inputSchema: editorTargetSchema,
97
- },
98
- {
99
- name: "sketchforge_select_objects",
100
- description: "Select objects by id in the SketchForge editor.",
101
- inputSchema: {
102
- ...editorTargetSchema,
103
- required: ["ids"],
104
- properties: {
105
- ...editorTargetSchema.properties,
106
- ids: { type: "array", items: { type: "string" } },
107
- },
108
- },
109
- },
110
- {
111
- name: "sketchforge_mirror_objects",
112
- description: "Mirror objects across the center plane of their combined bounds, using the editor's mirror behavior.",
113
- 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"] } } },
114
- },
115
- {
116
- name: "sketchforge_mirror_baked",
117
- description: "Reflect exact parameter-built solids across their shared bounds plane and bake the result to BREP. Imported meshes, groups, and previously treated shapes are refused.",
118
- inputSchema: { ...editorTargetSchema, required: ["projectId", "ids", "axis"], properties: { ...editorTargetSchema.properties, projectId: { type: "string" }, ids: { type: "array", minItems: 1, items: { type: "string" } }, axis: { type: "string", enum: ["x", "y", "z"] } } },
119
- },
120
- {
121
- name: "sketchforge_delete_objects",
122
- description: "Delete objects by id, or delete the current selection when ids are omitted.",
123
- inputSchema: {
124
- ...editorTargetSchema,
125
- properties: {
126
- ...editorTargetSchema.properties,
127
- ids: { type: "array", items: { type: "string" } },
128
- id: { type: "string" },
129
- },
130
- },
131
- },
132
- {
133
- name: "sketchforge_create_shape",
134
- description: `Create a parameterized shape, extruded sketch, revolve, or standard screw thread in SketchForge. Local mode (no url) accepts ${LOCAL_SHAPE_KINDS.join(", ")}; the kind description says which of those it can measure and export. An editor (url) builds ${EDITOR_SHAPE_KINDS.join(", ")}. sketch is editor-only. Each parameter's description names the kinds it applies to.`,
135
- inputSchema: {
136
- ...editorTargetSchema,
137
- required: ["kind"],
138
- properties: {
139
- ...editorTargetSchema.properties,
140
- kind: {
141
- type: "string",
142
- enum: CREATE_SHAPE_KINDS,
143
- description: [
144
- `Local mode builds ${LOCAL_SOLID_KINDS.join(", ")} as solids that measure and export as STL.`,
145
- "A roundRoof's height may be at most half its width; a taller one fails to build.",
146
- `${LOCAL_STORED_KINDS.join(", ")} are stored only: local mode records the parameters but cannot measure or export them; open the project in an editor for those.`,
147
- `STEP export holds only ${STEP_KINDS.join(", ")}; export the other solids as STL.`,
148
- "revolve there means a plain revolve: no pitch, no coreRadius, one closed profile region with straight edges, and not resized unevenly across its axis; any other revolve, like a thread, exports as STL only. A plain revolve is in STEP only when exported by the server or local mode, from its exact solid; an open editor's own STEP export skips it.",
149
- "sketch is editor-only: it needs an open editor (url), and local mode refuses it.",
150
- `An editor builds only ${EDITOR_SHAPE_KINDS.join(", ")}.`,
151
- ].join(" "),
152
- },
153
- profile: {
154
- type: "array",
155
- 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.",
156
- items: { type: "array", items: { type: "number" }, minItems: 2, maxItems: 2 },
157
- },
158
- 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." },
159
- turns: { type: "number", description: "For kind revolve/thread: how many full turns to sweep (default 8 for a thread)." },
160
- 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." },
161
- length: { type: "number", description: "For kind thread: how long the thread should be in mm, instead of giving turns." },
162
- hole: {
163
- type: "boolean",
164
- description: "Any kind: create the shape as a hole (a cutter), so grouping it with a solid cuts it out of that solid without a separate update_object call. For kind thread it also cuts the form wider by a clearance so a bolt of that size fits, which taps the solid.",
165
- },
166
- clearance: { type: "number", description: "For kind thread with hole: how much wider to cut, per side, in mm (default 0.2 for printed parts)." },
167
- startAngle: { type: "number", description: "For kind revolve: rotation the sweep starts at, in degrees." },
168
- sweepAngle: { type: "number", description: "For kind revolve with no pitch: how far round to revolve, in degrees (±360). x/z place the axis of revolution, so a partial sweep lies to one side of them; the result's x/z is its box centre, and local mode reports the axis as revolveAxis." },
169
- name: { type: "string" },
170
- color: { type: "string" },
171
- x: { type: "number" },
172
- z: { type: "number" },
173
- elevation: { type: "number" },
174
- width: { type: "number", description: "For loft, this is the bottom end's width." },
175
- depth: { type: "number", description: "For loft, this is the bottom end's depth." },
176
- height: { type: "number" },
177
- size: {
178
- type: ["number", "string"],
179
- 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).',
180
- },
181
- rotation: { type: "number" },
182
- rotationX: { type: "number" },
183
- rotationZ: { type: "number" },
184
- sides: { type: "number", description: "Number of flat sides around the axis, at least 3. For cylinder: default 96, which builds a true round cylinder; fewer builds a prism. For pyramid: default 4, a rectangular base; any other count is a regular polygon base. A cone and roundRoof are always round, whatever sides says. For kind revolve/thread: facets per full turn of the sweep, 3-512 (default 64). On a 150 mm ring 64 facets are about 7.4 mm wide and 256 about 1.8 mm; the triangle count grows with it." },
185
- quality: { type: "number", description: "For kind revolve/thread: how finely curved segments of the profile are sampled, 1-10 (default 6). An outline of [x, z] points is all straight segments, so it changes nothing there; raise sides to smooth the turn." },
186
- steps: { type: "number", description: "For sphere and halfSphere: display mesh segments around and over the surface (at least 4, default 32). The measured and exported solid is a true curved surface whatever steps says." },
187
- bevel: {
188
- type: "number",
189
- description: "For tube and ring: wall thickness in mm, measured inward from the outer radius (default 4). It is clamped to at least 0.1 and at most the smaller outer radius less 0.1, so the bore never closes: on a 20 mm wide tube, any bevel above 9.9 builds a 9.9 mm wall. A 20x20x10 tube with bevel 4 has a 6 mm inner radius. For text: edge rounding in mm (default 0).",
190
- },
191
- segments: { type: "number", description: "For text: curve segments per glyph outline (at least 1, default 2)." },
192
- topRadius: { type: "number", description: "For cone: radius of the top in mm (default 0, a point)." },
193
- baseRadius: { type: "number", description: "For cone: recorded base radius in mm (default half the width). It does not change the solid: a cone stands on half its width, so set width and depth to size the base." },
194
- taperTopWidth: { type: "number", description: `For ${TAPER_KINDS.join(", ")} in local mode: footprint width at the top of the extrusion in mm (default width). Other kinds store it, but measuring or exporting a tapered one is refused. An editor ignores it.` },
195
- taperTopDepth: { type: "number", description: `For ${TAPER_KINDS.join(", ")} in local mode: footprint depth at the top of the extrusion in mm (default depth). Other kinds store it, but measuring or exporting a tapered one is refused. An editor ignores it.` },
196
- taperBottomWidth: { type: "number", description: `For ${TAPER_KINDS.join(", ")} in local mode: footprint width at the bottom of the extrusion in mm (default width). Other kinds store it, but measuring or exporting a tapered one is refused. An editor ignores it.` },
197
- taperBottomDepth: { type: "number", description: `For ${TAPER_KINDS.join(", ")} in local mode: footprint depth at the bottom of the extrusion in mm (default depth). Other kinds store it, but measuring or exporting a tapered one is refused. An editor ignores it.` },
198
- teeth: { type: "number", description: "For gear: tooth count (default 12)." },
199
- toothSize: { type: "number", description: "For gear: radial tooth height in mm (default 2.5)." },
200
- toothWidth: { type: "number", description: "For gear: tooth width in mm (default 0.54 of the tooth pitch, clamped between 0.12 and 0.82 of it)." },
201
- centerHoleSize: { type: "number", description: "For gear: centre hole size in mm (default 6, clamped so it stays inside the tooth roots; 0 for none)." },
202
- gearType: { type: "string", enum: ["spur", "helical", "bevel"], description: "For gear: tooth form (default spur)." },
203
- helixAngle: { type: "number", description: "For gear with gearType helical: helix angle in degrees (default 22.5)." },
204
- text: { type: "string", description: "For text: the characters to extrude (default TEXT)." },
205
- font: { type: "string", description: "For text: font name (default Multilanguage)." },
206
- loftBottomShape: { type: "string", enum: ["Oval", "Rectangle", "Triangle", "Pentagon", "Hexagon"], description: "loft only. Defaults to Rectangle." },
207
- loftTopShape: { type: "string", enum: ["Oval", "Rectangle", "Triangle", "Pentagon", "Hexagon"], description: "loft only. Defaults to Oval." },
208
- loftTopWidth: { type: "number", description: "loft only. Independent of the bottom's width, like a cone's top radius. Defaults to matching width." },
209
- loftTopDepth: { type: "number", description: "loft only. Independent of the bottom's depth. Defaults to matching depth." },
210
- loftBottomRotation: { type: "number", description: "loft only. Bottom end rotation in degrees." },
211
- loftTopRotation: { type: "number", description: "loft only. Top end rotation in degrees." },
212
- loftSegments: { type: "number", description: "loft only. Angular resolution, 8-128." },
213
- loftLayers: { type: "number", description: "loft only. Vertical resolution, 2-80." },
214
- },
215
- },
216
- },
217
- {
218
- name: "sketchforge_import_mesh",
219
- description: "Import a triangle mesh into SketchForge from raw position and optional normal arrays.",
220
- inputSchema: {
221
- ...editorTargetSchema,
222
- required: ["positions"],
223
- properties: {
224
- ...editorTargetSchema.properties,
225
- name: { type: "string" },
226
- color: { type: "string" },
227
- x: { type: "number" },
228
- z: { type: "number" },
229
- elevation: { type: "number" },
230
- width: { type: "number" },
231
- depth: { type: "number" },
232
- height: { type: "number" },
233
- positions: { type: "array", items: { type: "number" } },
234
- normals: { type: "array", items: { type: "number" } },
235
- },
236
- },
237
- },
238
- {
239
- name: "sketchforge_import_file",
240
- description: "Import an STL, OBJ, or SVG file from the MCP host filesystem into SketchForge. The source filename supplies the shape name; color and placement use importer defaults. In local mode provide projectId and filePath; with url, the file is sent to POST /api/v1/imports. File reads are confined to SKETCHFORGE_MCP_FILES_DIR, or SKETCHFORGE_PROJECTS_DIR when unset; if both are unset, paths are unrestricted.",
241
- inputSchema: {
242
- type: "object",
243
- required: ["projectId", "filePath"],
244
- properties: {
245
- url: editorTargetSchema.properties.url,
246
- projectId: { type: "string" },
247
- filePath: { type: "string", description: "Path to an .stl, .obj, or .svg file under the configured MCP files root; unrestricted when no root is set." },
248
- },
249
- },
250
- },
251
- {
252
- name: "sketchforge_import_stl",
253
- description: "Local-only compatibility alias for sketchforge_import_file. Accepts STL, OBJ, or SVG files. Optional name, color, and placement fields override the imported shape. A remote url is not supported.",
254
- inputSchema: {
255
- type: "object",
256
- required: ["projectId", "filePath"],
257
- properties: {
258
- projectId: { type: "string" },
259
- filePath: { type: "string", description: "Path to an .stl, .obj, or .svg file under the configured MCP files root; unrestricted when no root is set." },
260
- name: { type: "string" },
261
- color: { type: "string" },
262
- x: { type: "number" },
263
- z: { type: "number" },
264
- elevation: { type: "number" },
265
- },
266
- },
267
- },
268
- {
269
- name: "sketchforge_update_object",
270
- description: "Update one object's exact dimensions, position, color, name, hole state, or rotations.",
271
- inputSchema: {
272
- ...editorTargetSchema,
273
- required: ["id"],
274
- properties: {
275
- ...editorTargetSchema.properties,
276
- id: { type: "string" },
277
- name: { type: "string" },
278
- color: { type: "string" },
279
- faceColors: { type: "object", description: "Optional colors keyed by stable face IDs from sketchforge_list_faces, such as {'face_abc':'#ff0000'}. Numeric face indexes remain accepted for older projects." },
280
- hole: { type: "boolean" },
281
- x: { type: "number" },
282
- z: { type: "number" },
283
- elevation: { type: "number" },
284
- width: { type: "number" },
285
- depth: { type: "number" },
286
- height: { type: "number" },
287
- size: { type: "number" },
288
- rotation: { type: "number" },
289
- rotationX: { type: "number" },
290
- rotationZ: { type: "number" },
291
- },
292
- },
293
- },
294
- {
295
- name: "sketchforge_pattern_objects",
296
- 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.",
297
- inputSchema: {
298
- ...editorTargetSchema,
299
- properties: {
300
- ...editorTargetSchema.properties,
301
- ids: { type: "array", items: { type: "string" }, description: "Object ids to repeat. If omitted, uses the current selection." },
302
- kind: { type: "string", enum: ["linear", "circular"], description: "linear=a row; circular=a ring about a centre. Default linear." },
303
- count: { type: "number", description: "Total copies including the original, so 4 adds 3 (2-200). Default 4." },
304
- stepX: { type: "number", description: "For kind linear: centre-to-centre step along X in mm. This is a pitch, not a gap." },
305
- stepZ: { type: "number", description: "For kind linear: centre-to-centre step along Z in mm." },
306
- centerX: { type: "number", description: "For kind circular: X of the point to turn about." },
307
- centerZ: { type: "number", description: "For kind circular: Z of the point to turn about." },
308
- 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." },
309
- 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." },
310
- },
311
- },
312
- },
313
- {
314
- name: "sketchforge_distribute_objects",
315
- 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.",
316
- inputSchema: {
317
- ...editorTargetSchema,
318
- properties: {
319
- ...editorTargetSchema.properties,
320
- ids: { type: "array", items: { type: "string" }, description: "Object ids to distribute. If omitted, uses the current selection." },
321
- axis: { type: "string", enum: ["x", "z"], description: "Axis to spread along. Omit to use whichever axis the objects are already most spread along." },
322
- spacing: { type: "string", enum: ["gaps", "centers"], description: "gaps=equal clear space between objects (default); centers=equal centre-to-centre pitch." },
323
- },
324
- },
325
- },
326
- {
327
- name: "sketchforge_align_objects",
328
- description: "Align two or more SketchForge objects using the same alignment logic as the editor Alignment button.",
329
- inputSchema: {
330
- ...editorTargetSchema,
331
- required: ["axis", "target"],
332
- properties: {
333
- ...editorTargetSchema.properties,
334
- ids: { type: "array", items: { type: "string" }, description: "Object ids to align. If omitted, uses the current selection." },
335
- anchorId: { type: "string", description: "Optional object id to keep fixed as the alignment reference." },
336
- axis: { type: "string", enum: ["x", "y", "z"], description: "x=left/right, z=front/back, y=bottom/top." },
337
- target: { type: "string", enum: ["min", "center", "max"], description: "Which side/center to align." },
338
- },
339
- },
340
- },
341
- {
342
- name: "sketchforge_group_objects",
343
- description: "Group objects by id using SketchForge's normal grouping/boolean pipeline. A selection holding a hole comes back cut. Optional name and color are set on the result.",
344
- inputSchema: {
345
- ...editorTargetSchema,
346
- required: ["ids"],
347
- properties: {
348
- ...editorTargetSchema.properties,
349
- ids: { type: "array", items: { type: "string" } },
350
- ...resultAttributeProperties,
351
- },
352
- },
353
- },
354
- {
355
- name: "sketchforge_ungroup_objects",
356
- description: "Ungroup one or more grouped objects by id and preserve their edited geometry.",
357
- inputSchema: {
358
- ...editorTargetSchema,
359
- properties: {
360
- ...editorTargetSchema.properties,
361
- ids: { type: "array", items: { type: "string" } },
362
- id: { type: "string" },
363
- },
364
- },
365
- },
366
- {
367
- name: "sketchforge_boolean_cut",
368
- description: "Cut solids with hole objects. Provide solidIds and holeIds; the result replaces the operands. Optional name and color are set on the result.",
369
- inputSchema: {
370
- ...editorTargetSchema,
371
- required: ["solidIds", "holeIds"],
372
- properties: {
373
- ...editorTargetSchema.properties,
374
- solidIds: { type: "array", items: { type: "string" } },
375
- holeIds: { type: "array", items: { type: "string" } },
376
- ...resultAttributeProperties,
377
- },
378
- },
379
- },
380
- {
381
- name: "sketchforge_separate_parts",
382
- description: "Separate one disconnected multi-part object into independent objects.",
383
- inputSchema: {
384
- ...editorTargetSchema,
385
- properties: {
386
- ...editorTargetSchema.properties,
387
- id: { type: "string" },
388
- },
389
- },
390
- },
391
- {
392
- name: "sketchforge_explode_step_assembly",
393
- description: "Explode an imported STEP assembly into independent exact solids. Limited to 200 solids and 8 MiB source files.",
394
- inputSchema: { ...editorTargetSchema, required: ["projectId", "shapeId"], properties: { ...editorTargetSchema.properties, projectId: { type: "string" }, shapeId: { type: "string" } } },
395
- },
396
- {
397
- name: "sketchforge_list_edges",
398
- description: "List real CAD edge ids for one object so a later chamfer/fillet can target specific edges.",
399
- inputSchema: {
400
- ...editorTargetSchema,
401
- required: ["id"],
402
- properties: {
403
- ...editorTargetSchema.properties,
404
- id: { type: "string" },
405
- sharpAngle: { type: "number" },
406
- },
407
- },
408
- },
409
- {
410
- name: "sketchforge_apply_edge_treatment",
411
- description: "Apply chamfer or fillet to specific edge ids returned by sketchforge_list_edges.",
412
- inputSchema: {
413
- ...editorTargetSchema,
414
- required: ["id", "kind", "edgeIds", "amount"],
415
- properties: {
416
- ...editorTargetSchema.properties,
417
- id: { type: "string" },
418
- kind: { type: "string", enum: ["chamfer", "fillet"] },
419
- edgeIds: {
420
- anyOf: [
421
- { type: "array", items: { type: "number" } },
422
- { type: "string", enum: ["all"] },
423
- ],
424
- },
425
- allEdges: { type: "boolean" },
426
- amount: { type: "number" },
427
- chamferAngle: { type: "number" },
428
- sharpAngle: { type: "number" },
429
- quality: { type: "string", enum: ["draft", "standard", "fine"] },
430
- preserveEdgeSize: { type: "boolean" },
431
- },
432
- },
433
- },
434
- {
435
- name: "sketchforge_inspect_errors",
436
- description: "Inspect the editor notice, last MCP error, and active edge modifier error.",
437
- inputSchema: editorTargetSchema,
438
- },
439
- {
440
- name: "sketchforge_capture_image",
441
- description: "Capture a PNG image from current/home/top/bottom/front/back/right/left view. Editor mode captures the live viewport. Local project mode rasterises the kernel's hidden-line drawing of the stored geometry: a named face is that one view, home and current are the four-view grid. Prefer sketchforge_project_view for the SVG itself.",
442
- inputSchema: {
443
- ...editorTargetSchema,
444
- properties: {
445
- ...editorTargetSchema.properties,
446
- face: { type: "string", enum: ["current", "home", "top", "bottom", "front", "back", "right", "left"] },
447
- featureAngle: { type: "number", minimum: 0, maximum: 180, description: "Crease angle in degrees for mesh shapes (imported, mesh-derived, boolean results): an edge between two triangles is drawn only where they meet at more than this, besides boundaries and silhouettes. Default 30; 0 draws every edge that is not flat. Exact solids ignore it. Local project mode only; the live editor viewport ignores it." },
448
- },
449
- },
450
- },
451
- {
452
- name: "sketchforge_export_scene",
453
- description: "Export selected objects or the whole scene as STL, OBJ, 3MF, STEP, SKF, a ZIP kit, SVG drawings, or section DXF. DXF needs section {plane, offset}. Set outputPath to save on the MCP host; writes are confined to SKETCHFORGE_MCP_FILES_DIR, or SKETCHFORGE_PROJECTS_DIR when unset. If both are unset, paths are unrestricted. Existing files require overwrite: true.",
454
- inputSchema: { ...editorTargetSchema, required: ["format"], properties: { ...editorTargetSchema.properties, format: { type: "string", enum: ["stl", "obj", "3mf", "step", "skf", "zip", "svg", "dxf"] }, view: { type: "string", enum: PROJECTION_LAYOUTS, description: "For svg only: one named view, or the multiview grid (default)." }, section: { type: "object", description: "For svg or dxf section export.", properties: { plane: { type: "string", enum: ["xy", "xz", "yz"] }, offset: { type: "number" } }, required: ["plane", "offset"] }, shapeIds: { type: "array", items: { type: "string" }, description: "Optional object ids." }, name: { type: "string" }, outputPath: { type: "string", description: "Destination path under SKETCHFORGE_MCP_FILES_DIR (or SKETCHFORGE_PROJECTS_DIR when unset); unrestricted if neither is set." }, overwrite: { type: "boolean", description: "Set true to replace an existing output file." } } },
455
- },
456
- {
457
- name: "sketchforge_project_view",
458
- description: "Draw a stored project as an SVG by the CAD kernel's hidden-line removal: true curves, hidden edges dashed, a gnomon per view and the overall size. Mesh shapes are drawn by feature edges (see featureAngle), silhouettes and boundaries rather than every triangle. The multiview grid (front, top, right, iso) is the readable picture of the geometry; a single view is a 2D drawing of that face. Works offline or against a server when url is supplied.",
459
- inputSchema: {
460
- type: "object",
461
- required: ["projectId"],
462
- properties: {
463
- url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
464
- projectId: { type: "string", description: "The server-side project id." },
465
- view: { type: "string", enum: PROJECTION_LAYOUTS, description: "One named view, or the multiview grid (default)." },
466
- featureAngle: { type: "number", minimum: 0, maximum: 180, description: "Crease angle in degrees for mesh shapes (imported, mesh-derived, boolean results): an edge between two triangles is drawn only where they meet at more than this, besides boundaries and silhouettes. Default 30; 0 draws every edge that is not flat. Exact solids ignore it." },
467
- shapeIds: { type: "array", items: { type: "string" }, description: "Optional object ids; defaults to the current selection, or the whole scene when nothing is selected." },
468
- name: { type: "string", description: "Optional base name for the file." },
469
- outputPath: { type: "string", description: "Optional destination path under SKETCHFORGE_MCP_FILES_DIR (or SKETCHFORGE_PROJECTS_DIR when unset); unrestricted if neither is set. SVG text is returned inline otherwise." },
470
- overwrite: { type: "boolean", description: "Set true to replace an existing output file." },
471
- },
472
- },
473
- },
474
- {
475
- name: "sketchforge_section_view",
476
- description: "Return a CAD section drawing as SVG by cutting the stored solids with one axis-aligned plane in drawing coordinates. offset is the coordinate of the omitted axis, in millimetres. Exact shapes are cut by the OCCT kernel; mesh shapes (imported STL/OBJ and other mesh-backed shapes) are sliced directly, up to 2,000,000 triangles across the selection -- pass shapeIds to section fewer shapes when over that. Works offline or against a server when url is supplied.",
477
- inputSchema: {
478
- type: "object",
479
- required: ["projectId", "plane", "offset"],
480
- properties: {
481
- url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
482
- projectId: { type: "string", description: "The project id." },
483
- plane: { type: "string", enum: SECTION_PLANES, description: "Plane in drawing coordinates; XY omits Z, XZ omits Y, and YZ omits X." },
484
- offset: { type: "number", description: "Coordinate of the omitted axis in millimetres; must intersect the selected scene." },
485
- shapeIds: { type: "array", items: { type: "string" }, description: "Optional object ids; defaults to the current selection, or the whole scene when nothing is selected." },
486
- name: { type: "string", description: "Optional base name for the file." },
487
- outputPath: { type: "string", description: "Optional destination path under SKETCHFORGE_MCP_FILES_DIR (or SKETCHFORGE_PROJECTS_DIR when unset); unrestricted if neither is set. SVG text is returned inline otherwise." },
488
- overwrite: { type: "boolean", description: "Set true to replace an existing output file." },
489
- },
490
- },
491
- },
492
- {
493
- name: "sketchforge_validate_scene",
494
- description: "Check triangle topology, conservative AABB clearance bounds, and exact Manifold intersection volumes for overlapping scene objects.",
495
- inputSchema: { ...editorTargetSchema, properties: { ...editorTargetSchema.properties, shapeIds: { type: "array", items: { type: "string" } }, excludeShapeIds: { type: "array", items: { type: "string" } } } },
496
- },
497
- {
498
- name: "sketchforge_check_interference",
499
- description: "Check exact OCCT surface gaps and overlap volumes between visible, non-cutter solids. Clearance is in millimetres. The report refuses the whole request above 128 shapes or 512 AABB candidate pairs; narrow ids or reduce clearance. Works offline or against a server.",
500
- inputSchema: { ...editorTargetSchema, properties: { ...editorTargetSchema.properties, ids: { type: "array", items: { type: "string" }, description: "Optional shape ids; defaults to all visible non-cutter solids." }, clearance: { type: "number", minimum: 0, description: "Maximum exact surface gap to report, in mm (default 0)." } } },
501
- },
502
- // CAD operations use the local engine by default and the server API when a URL is supplied.
503
- {
504
- name: "sketchforge_list_faces",
505
- description: "List a stored project shape's CAD faces with stable IDs and compatibility indexes, plus the direction name each one can be opened by. Use the stable ID to assign a face color; use the index for treatments, measurements, and shell openings. Works offline or against a server when url is supplied.",
506
- inputSchema: {
507
- type: "object",
508
- required: ["projectId", "shapeId"],
509
- properties: {
510
- url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
511
- projectId: { type: "string", description: "The server-side project id." },
512
- shapeId: { type: "string", description: "The id of the shape to read." },
513
- },
514
- },
515
- },
516
- // Measuring uses exact CAD geometry in either the local engine or server API.
517
- {
518
- name: "sketchforge_measure_shape",
519
- 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.",
520
- inputSchema: {
521
- type: "object",
522
- required: ["projectId", "shapeId"],
523
- properties: {
524
- url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
525
- projectId: { type: "string", description: "The server-side project id." },
526
- shapeId: { type: "string", description: "The id of the shape to measure." },
527
- },
528
- },
529
- },
530
- {
531
- name: "sketchforge_measure_between",
532
- 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.",
533
- inputSchema: {
534
- type: "object",
535
- required: ["projectId", "from", "to"],
536
- properties: {
537
- url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
538
- projectId: { type: "string", description: "The server-side project id." },
539
- from: {
540
- type: "object",
541
- required: ["shapeId"],
542
- properties: {
543
- shapeId: { type: "string", description: "The shape this end is part of." },
544
- entity: {
545
- type: "string",
546
- enum: ["shape", "edge", "face"],
547
- description: "What to measure to. 'shape' is the whole solid and takes no index; 'edge' and 'face' need one.",
548
- },
549
- index: { type: "number", description: "Which edge or face, by the index the measurement listing gave it." },
550
- },
551
- },
552
- to: {
553
- type: "object",
554
- required: ["shapeId"],
555
- properties: {
556
- shapeId: { type: "string", description: "The shape this end is part of." },
557
- entity: { type: "string", enum: ["shape", "edge", "face"] },
558
- index: { type: "number" },
559
- },
560
- },
561
- },
562
- },
563
- },
564
- {
565
- name: "sketchforge_shape_properties",
566
- description: "Read one stored shape's volume, surface area, center of mass, bounds and validity, with provenance identifying the geometry source and whether precision is exact or tessellated. A group of solids is measured as the union of its children. Exact shapes are measured by the CAD kernel; closed mesh-sourced shapes are measured directly from their triangles, counting every shell and subtracting enclosed voids, and a mesh that does not close is left to the kernel, which refuses it. Works offline or against a server when url is supplied.",
567
- inputSchema: {
568
- type: "object",
569
- required: ["projectId", "shapeId"],
570
- properties: {
571
- url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
572
- projectId: { type: "string", description: "The project id." },
573
- shapeId: { type: "string", description: "The shape id." },
574
- },
575
- },
576
- },
577
- {
578
- name: "sketchforge_estimate_wall_thickness",
579
- description: "Estimate wall thickness from a 5 by 5 UV sample grid on each face. This is a screening estimate and may miss thin regions between samples; it is not a certified minimum-thickness result.",
580
- inputSchema: { type: "object", required: ["projectId", "shapeId"], properties: { url: { type: "string" }, projectId: { type: "string" }, shapeId: { type: "string" } } },
581
- },
582
- {
583
- name: "sketchforge_hollow_shape",
584
- 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.",
585
- inputSchema: {
586
- type: "object",
587
- required: ["projectId", "shapeId", "thickness"],
588
- properties: {
589
- url: { type: "string", description: "Optional SketchForge server URL. Omit to work offline with local project files." },
590
- projectId: { type: "string", description: "The server-side project id." },
591
- shapeId: { type: "string", description: "The id of the shape to hollow." },
592
- thickness: { type: "number", description: "Wall thickness in mm, measured inwards. Must be well under half the part's smallest span." },
593
- openFaces: {
594
- type: "array",
595
- description: 'Faces to leave open. Direction names ("top", "bottom", "left", "right", "front", "back") or face indexes from sketchforge_list_faces. Omit for a sealed hollow.',
596
- items: { type: ["string", "number"] },
597
- },
598
- },
599
- },
600
- },
601
- // Macros run only from the directory the operator configured.
602
- ...macroTools,
603
- ];
604
-
605
- const API_TOKEN_ENV = "SKETCHFORGE_API_TOKEN";
606
-
607
- /**
608
- * One request to the headless REST API, as the operator's token.
609
- *
610
- * The editor bridge cannot serve every tool here: hollowing is a server-side
611
- * OCCT operation on a stored project, with no editor tab involved and nothing
612
- * to ask one for. The token is the same one the server was started with, and
613
- * without it every route answers 404 rather than saying it is switched off.
614
- */
615
- async function restRequest(method, path, { query = {}, body, baseUrl } = {}) {
616
- const token = process.env[API_TOKEN_ENV];
617
- if (!token) {
618
- throw new Error(
619
- `${API_TOKEN_ENV} is not set. It is the same token the SketchForge server was started with; without it the REST API answers 404 to everything.`,
620
- );
621
- }
622
- const url = new URL(`/api/v1${path}`, baseUrl);
623
- for (const [key, value] of Object.entries(query)) {
624
- if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
625
- }
626
- const response = await fetch(url, {
627
- method,
628
- headers: { authorization: `Bearer ${token}`, ...(body ? { "Content-Type": "application/json" } : {}) },
629
- ...(body ? { body: JSON.stringify(body) } : {}),
630
- });
631
- const payload = await response.json().catch(() => null);
632
- if (!response.ok) {
633
- // The sentence is for whoever reads the log; the code is the half a client
634
- // can act on, so carry both rather than flattening to a status.
635
- throw new Error(
636
- payload?.error
637
- ? `${payload.error}${payload.code ? ` [${payload.code}]` : ""}`
638
- : `SketchForge API returned HTTP ${response.status}`,
639
- );
640
- }
641
- return payload;
642
- }
643
-
644
- function bridgeUrl(baseUrl) {
645
- return new URL(MCP_ROUTE, baseUrl);
646
- }
647
-
648
- async function bridgeGet(baseUrl) {
649
- const response = await fetch(bridgeUrl(baseUrl));
650
- const payload = await response.json().catch(() => null);
651
- if (!response.ok) {
652
- throw new Error(payload?.error || `SketchForge bridge returned HTTP ${response.status}`);
653
- }
654
- return payload;
655
- }
656
-
657
- async function bridgeCommand(action, args = {}, defaultTimeoutMs = 15000, baseUrl) {
658
- const { editorNumber, editorId, timeoutMs, url, ...params } = args || {};
659
- let targetNumber = typeof editorNumber === "number" ? editorNumber : undefined;
660
- let targetId = typeof editorId === "string" ? editorId : undefined;
661
-
662
- if (!targetNumber && !targetId) {
663
- const { editors = [] } = await bridgeGet(baseUrl);
664
- if (editors.length === 1) {
665
- targetNumber = editors[0].editorNumber;
666
- } else {
667
- throw new Error(editors.length === 0 ? "No open SketchForge editors found" : "Provide editorNumber because multiple SketchForge editors are open");
668
- }
669
- }
670
-
671
- const response = await fetch(bridgeUrl(baseUrl), {
672
- method: "POST",
673
- headers: { "Content-Type": "application/json" },
674
- body: JSON.stringify({
675
- type: "command",
676
- editorNumber: targetNumber,
677
- editorId: targetId,
678
- action,
679
- params,
680
- timeoutMs: typeof timeoutMs === "number" ? timeoutMs : defaultTimeoutMs,
681
- }),
682
- });
683
- const payload = await response.json().catch(() => null);
684
- if (!payload?.ok) {
685
- throw new Error(payload?.error || `SketchForge command failed with HTTP ${response.status}`);
686
- }
687
- return payload.data;
688
- }
689
-
690
- async function callRemoteTool(name, args, baseUrl) {
691
- switch (name) {
692
- case "sketchforge_list_editors":
693
- return bridgeGet(baseUrl);
694
- case "sketchforge_read_scene":
695
- return bridgeCommand("get_scene", args, 15000, baseUrl);
696
- case "sketchforge_list_objects":
697
- return bridgeCommand("list_objects", args, 15000, baseUrl);
698
- case "sketchforge_select_objects":
699
- return bridgeCommand("select_objects", args, 15000, baseUrl);
700
- case "sketchforge_mirror_objects":
701
- return bridgeCommand("mirror_objects", args, 15000, baseUrl);
702
- case "sketchforge_mirror_baked":
703
- return restRequest("POST", "/mirrors", {
704
- query: { projectId: args.projectId },
705
- body: { ids: args.ids, axis: args.axis },
706
- baseUrl,
707
- });
708
- case "sketchforge_delete_objects":
709
- return bridgeCommand("delete_objects", args, 15000, baseUrl);
710
- case "sketchforge_create_shape":
711
- return bridgeCommand("create_shape", args, 15000, baseUrl);
712
- case "sketchforge_import_mesh":
713
- return bridgeCommand("import_mesh", args, 60000, baseUrl);
714
- case "sketchforge_import_file": {
715
- const sourcePath = await resolveMcpReadPath(args.filePath);
716
- const extension = path.extname(sourcePath).toLowerCase();
717
- const mediaType = extension === ".stl" ? "model/stl" : extension === ".obj" ? "model/obj" : extension === ".svg" ? "image/svg+xml" : undefined;
718
- if (!mediaType) throw new Error("filePath must point to an .stl, .obj, or .svg file.");
719
- const bytes = readFileSync(sourcePath);
720
- return restRequest("POST", "/imports", {
721
- query: { projectId: args.projectId },
722
- body: { fileName: path.basename(sourcePath), data: bytes.toString("base64"), mediaType },
723
- baseUrl,
724
- });
725
- }
726
- case "sketchforge_update_object":
727
- return bridgeCommand("update_object", args, 15000, baseUrl);
728
- case "sketchforge_align_objects":
729
- return bridgeCommand("align_objects", args, 15000, baseUrl);
730
- case "sketchforge_distribute_objects":
731
- return bridgeCommand("distribute_objects", args, 15000, baseUrl);
732
- case "sketchforge_pattern_objects":
733
- return bridgeCommand("pattern_objects", args, 15000, baseUrl);
734
- case "sketchforge_group_objects":
735
- return bridgeCommand("group_objects", args, 30000, baseUrl);
736
- case "sketchforge_ungroup_objects":
737
- return bridgeCommand("ungroup_objects", args, 15000, baseUrl);
738
- case "sketchforge_boolean_cut":
739
- return bridgeCommand("boolean_cut", args, 45000, baseUrl);
740
- case "sketchforge_separate_parts":
741
- return bridgeCommand("separate_parts", args, 15000, baseUrl);
742
- case "sketchforge_explode_step_assembly":
743
- return restRequest("POST", "/explode", { query: { projectId: args.projectId, shapeId: args.shapeId }, body: {}, baseUrl });
744
- case "sketchforge_list_edges":
745
- return bridgeCommand("list_edges", args, 30000, baseUrl);
746
- case "sketchforge_apply_edge_treatment":
747
- return bridgeCommand("apply_edge_treatment", args, 60000, baseUrl);
748
- case "sketchforge_list_faces":
749
- return restRequest("GET", "/faces", { query: { projectId: args.projectId, shapeId: args.shapeId }, baseUrl });
750
- case "sketchforge_measure_shape":
751
- return restRequest("GET", "/measurements", { query: { projectId: args.projectId, shapeId: args.shapeId }, baseUrl });
752
- case "sketchforge_shape_properties":
753
- return restRequest("GET", "/properties", { query: { projectId: args.projectId, shapeId: args.shapeId }, baseUrl });
754
- case "sketchforge_estimate_wall_thickness":
755
- return restRequest("GET", "/thickness", { query: { projectId: args.projectId, shapeId: args.shapeId }, baseUrl });
756
- case "sketchforge_measure_between":
757
- return restRequest("POST", "/measurements", {
758
- query: { projectId: args.projectId },
759
- body: { from: args.from, to: args.to },
760
- baseUrl,
761
- });
762
- case "sketchforge_hollow_shape":
763
- return restRequest("POST", "/shell", {
764
- query: { projectId: args.projectId, shapeId: args.shapeId },
765
- body: {
766
- thickness: args.thickness,
767
- ...(args.openFaces === undefined ? {} : { openFaces: args.openFaces }),
768
- },
769
- baseUrl,
770
- });
771
- case "sketchforge_inspect_errors":
772
- return bridgeCommand("inspect_errors", args, 15000, baseUrl);
773
- case "sketchforge_capture_image":
774
- return bridgeCommand("capture_image", args, 30000, baseUrl);
775
- case "sketchforge_project_view": {
776
- const artifact = await restRequest("POST", "/exports", {
777
- query: { projectId: args.projectId },
778
- body: {
779
- format: "svg",
780
- ...(args.view === undefined ? {} : { view: args.view }),
781
- ...(args.featureAngle === undefined ? {} : { featureAngle: args.featureAngle }),
782
- ...(args.shapeIds === undefined ? {} : { shapeIds: args.shapeIds }),
783
- ...(args.name === undefined ? {} : { name: args.name }),
784
- },
785
- baseUrl,
786
- });
787
- const bytes = Buffer.from(artifact.base64, "base64");
788
- const response = { view: args.view ?? "multiview", filename: artifact.filename, mimeType: artifact.mimeType, bytes: artifact.bytes, shapeCount: artifact.shapeCount };
789
- if (typeof args.outputPath === "string" && args.outputPath.trim()) {
790
- const destination = await resolveMcpWritePath(args.outputPath, { overwrite: args.overwrite === true });
791
- writeFileSync(destination, bytes, { flag: args.overwrite === true ? "w" : "wx" });
792
- return { ...response, savedTo: path.resolve(args.outputPath) };
793
- }
794
- return { ...response, svg: bytes.toString("utf8") };
795
- }
796
- case "sketchforge_section_view": {
797
- const artifact = await restRequest("POST", "/exports", {
798
- query: { projectId: args.projectId },
799
- body: {
800
- format: "svg",
801
- section: { plane: args.plane, offset: args.offset },
802
- ...(args.shapeIds === undefined ? {} : { shapeIds: args.shapeIds }),
803
- ...(args.name === undefined ? {} : { name: args.name }),
804
- },
805
- baseUrl,
806
- });
807
- const bytes = Buffer.from(artifact.base64, "base64");
808
- const response = { plane: args.plane, offset: args.offset, filename: artifact.filename, mimeType: artifact.mimeType, bytes: artifact.bytes, shapeCount: artifact.shapeCount };
809
- if (typeof args.outputPath === "string" && args.outputPath.trim()) {
810
- const destination = await resolveMcpWritePath(args.outputPath, { overwrite: args.overwrite === true });
811
- writeFileSync(destination, bytes, { flag: args.overwrite === true ? "w" : "wx" });
812
- return { ...response, savedTo: path.resolve(args.outputPath) };
813
- }
814
- return { ...response, svg: bytes.toString("utf8") };
815
- }
816
- case "sketchforge_export_scene": {
817
- // An SVG is drawn on the server from the stored project; the editor
818
- // bridge has no such export, so this one takes the REST path.
819
- const artifact = args.format === "svg" || args.format === "dxf"
820
- ? await restRequest("POST", "/exports", {
821
- query: { projectId: args.projectId },
822
- body: {
823
- format: args.format,
824
- ...(args.view === undefined ? {} : { view: args.view }),
825
- ...(args.section === undefined ? {} : { section: args.section }),
826
- ...(args.shapeIds === undefined ? {} : { shapeIds: args.shapeIds }),
827
- ...(args.name === undefined ? {} : { name: args.name }),
828
- },
829
- baseUrl,
830
- })
831
- : await bridgeCommand("export_scene", args, 60000, baseUrl);
832
- if (typeof args.outputPath === "string" && args.outputPath.trim()) {
833
- const destination = await resolveMcpWritePath(args.outputPath, { overwrite: args.overwrite === true });
834
- writeFileSync(destination, Buffer.from(artifact.base64, "base64"), { flag: args.overwrite === true ? "w" : "wx" });
835
- return { filename: artifact.filename, mimeType: artifact.mimeType, bytes: artifact.bytes, shapeCount: artifact.shapeCount, savedTo: path.resolve(args.outputPath) };
836
- }
837
- return artifact;
838
- }
839
- case "sketchforge_validate_scene":
840
- return bridgeCommand("validate_scene", args, 60000, baseUrl);
841
- case "sketchforge_check_interference":
842
- return restRequest("POST", "/interference", {
843
- query: { projectId: args.projectId },
844
- body: { ...(Array.isArray(args.ids) && args.ids.length ? { ids: args.ids } : {}), ...(args.clearance === undefined ? {} : { clearance: args.clearance }) },
845
- baseUrl,
846
- });
847
- case "sketchforge_list_macros":
848
- return listMacros();
849
- case "sketchforge_run_macro":
850
- return runMacroByName(args, { environment: { ...process.env, SKETCHFORGE_URL: baseUrl } });
851
- default:
852
- throw new Error(`Unknown tool: ${name}`);
853
- }
854
- }
855
-
856
- function normalizedServerUrl(value) {
857
- let parsed;
858
- try {
859
- parsed = new URL(value);
860
- } catch {
861
- throw new Error("url must be an absolute http:// or https:// SketchForge server URL.");
862
- }
863
- if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password) {
864
- throw new Error("url must be an absolute http:// or https:// SketchForge server URL without embedded credentials.");
865
- }
866
- return parsed.toString().replace(/\/$/, "");
867
- }
868
-
869
- async function callTool(name, args = {}) {
870
- const { url, ...toolArgs } = args || {};
871
- if (name === "sketchforge_import_stl" && typeof url === "string" && url.trim()) {
872
- throw new Error("sketchforge_import_stl is only available in local mode; omit url.");
873
- }
874
- if (["sketchforge_list_projects", "sketchforge_create_project", "sketchforge_import_project"].includes(name) && typeof url === "string" && url.trim()) {
875
- throw new Error(`${name} is only available in local mode; omit url.`);
876
- }
877
- if (typeof url === "string" && url.trim()) {
878
- return callRemoteTool(name, toolArgs, normalizedServerUrl(url.trim()));
879
- }
880
- if (name === "sketchforge_list_macros") return listMacros();
881
- if (name === "sketchforge_run_macro") return runMacroByName(toolArgs);
882
- return callLocalEngineTool(name, toolArgs);
883
- }
884
-
885
- function textContent(value) {
886
- return {
887
- type: "text",
888
- text: typeof value === "string" ? value : JSON.stringify(value, null, 2),
889
- };
890
- }
891
-
892
- function toolResult(value) {
893
- if (value?.dataUrl?.startsWith?.("data:image/png;base64,")) {
894
- return {
895
- content: [
896
- textContent({ face: value.face, ...(value.view === undefined ? {} : { view: value.view }), bytesApprox: value.bytesApprox }),
897
- {
898
- type: "image",
899
- data: value.dataUrl.slice("data:image/png;base64,".length),
900
- mimeType: "image/png",
901
- },
902
- ],
903
- };
904
- }
905
- return { content: [textContent(value)] };
906
- }
6
+ const dispatch = createDispatcher({ tools, callTool });
907
7
 
908
8
  function send(message) {
909
9
  process.stdout.write(`${JSON.stringify(message)}\n`);
910
10
  }
911
11
 
912
- function sendResult(id, result) {
913
- send({ jsonrpc: "2.0", id, result });
914
- }
915
-
916
- function sendError(id, code, message) {
917
- send({ jsonrpc: "2.0", id, error: { code, message } });
918
- }
919
-
920
- async function handleMessage(message) {
921
- if (!message || typeof message !== "object") return;
922
- const { id, method, params } = message;
923
- try {
924
- if (method === "initialize") {
925
- sendResult(id, {
926
- protocolVersion: params?.protocolVersion || "2024-11-05",
927
- capabilities: { tools: {} },
928
- serverInfo: { name: "sketchforge-mcp", version },
929
- });
930
- return;
931
- }
932
- if (method === "notifications/initialized") {
933
- return;
934
- }
935
- if (method === "ping") {
936
- sendResult(id, {});
937
- return;
938
- }
939
- if (method === "tools/list") {
940
- sendResult(id, { tools });
941
- return;
942
- }
943
- if (method === "tools/call") {
944
- const name = params?.name;
945
- if (typeof name !== "string") {
946
- sendError(id, -32602, "Expected tool name");
947
- return;
948
- }
949
- const result = await callTool(name, params?.arguments || {});
950
- sendResult(id, toolResult(result));
951
- return;
952
- }
953
- if (method === "resources/list") {
954
- sendResult(id, { resources: [] });
955
- return;
956
- }
957
- sendError(id, -32601, `Unknown method: ${method}`);
958
- } catch (error) {
959
- if (method === "tools/call") {
960
- sendResult(id, { isError: true, content: [textContent(error instanceof Error ? error.message : String(error))] });
961
- return;
962
- }
963
- sendError(id, -32000, error instanceof Error ? error.message : String(error));
964
- }
965
- }
966
-
967
12
  let buffer = "";
968
13
  process.stdin.setEncoding("utf8");
969
14
  process.stdin.on("data", (chunk) => {
@@ -973,10 +18,15 @@ process.stdin.on("data", (chunk) => {
973
18
  lines.forEach((line) => {
974
19
  const trimmed = line.trim();
975
20
  if (!trimmed) return;
21
+ let message;
976
22
  try {
977
- void handleMessage(JSON.parse(trimmed));
23
+ message = JSON.parse(trimmed);
978
24
  } catch (error) {
979
- sendError(null, -32700, error instanceof Error ? error.message : String(error));
25
+ send(rpcError(null, -32700, error instanceof Error ? error.message : String(error)));
26
+ return;
980
27
  }
28
+ void dispatch(message).then((response) => {
29
+ if (response) send(response);
30
+ });
981
31
  });
982
32
  });