openscad-mcp-v2 1.2.1 → 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.
Files changed (3) hide show
  1. package/README.md +4 -4
  2. package/dist/index.js +592 -362
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -56,7 +56,7 @@ You open the 3MF in Bambu Studio, OrcaSlicer or PrusaSlicer and print it.
56
56
  - **Live in OpenSCAD.** `open_in_openscad` opens the design in your OpenSCAD window, which follows every change. Edits you make there are noticed and kept.
57
57
  - **Works on your files too.** `link_file` takes an existing `.scad` file, such as the one open in OpenSCAD right now, and edits it where it is, with the same versions and checks.
58
58
  - **Never loses a state.** Every save is a version; going back adds a new one.
59
- - **Fits your printer.** Real size, closed-solid check and fit on your printers' build volumes (Bambu Lab, Prusa, Creality profiles built in, your own by size).
59
+ - **Fits your printer.** Real size, closed-solid check and fit on your printers' build volumes (Bambu Lab, Prusa, Creality profiles built in, your own by size), and the overhangs that would need supports.
60
60
  - **Learns your preferences.** Corrections such as "always round the edges" are saved and come back with the guidelines for the next part.
61
61
  - **Designs for FDM.** Built-in guidelines for wall thickness, overhangs, tolerances, screw and nut sizes, plus usage notes for BOSL2, NopSCADlib and MCAD when installed.
62
62
 
@@ -436,7 +436,7 @@ A single call can name another one: `printer: "x1c"` or `printer: "300x300x400"`
436
436
  | `open_in_openscad` | Shows the design in the OpenSCAD window, which then follows every change |
437
437
  | `list_versions`, `restore_version` | History, and going back (a restore is a new version) |
438
438
  | `set_parameters` | Lists the customizer parameters, or changes their values in the file |
439
- | `analyze_design` | Real size, bounding box, closed-solid check, bed contact, fit per printer; with parameter overrides an overlap check answers "Empty", "Touching only" or the size of the overlap |
439
+ | `analyze_design` | Real size, bounding box, closed-solid check, bed contact, fit per printer, overhangs steeper than 45° (area, position, narrowest width); with parameter overrides an overlap check answers "Empty", "Touching only" or the size of the overlap; `variants` checks up to 4 poses in one call |
440
440
  | `measure_design` | Distances in the rendered model: solid and empty stretches along lines parallel to X, Y or Z (wall thickness, the gap between two parts, hole widths), and whether points are in material; optional parameter overrides, e.g. an assembled pose |
441
441
  | `export_design` | 3MF (default) or binary STL into the design's `exports/` folder, with path, size and fit; `parts: true` writes one file per part (box and lid separately) from the design's `part` parameter |
442
442
  | `record_learning`, `list_learnings`, `forget_learning` | Lessons for later designs: your corrections and preferences, techniques that failed or worked |
@@ -511,7 +511,7 @@ Printer servers can start a print without asking. This server's instructions tel
511
511
  ## Limits
512
512
 
513
513
  - The closed-solid check is OpenSCAD's own. Two bodies that only share an edge pass it.
514
- - Wall thickness, overhangs and bridges are not measured; the guidelines make the model design for them, and the slicer preview is the final check.
514
+ - Overhangs are found, but whether one needs supports is left to the model: a flat region between two walls is a bridge, a ledge is not, and the server does not tell them apart. Wall thickness is measured only where `measure_design` is asked to look. The slicer preview is the final check.
515
515
  - Images show the bounding box fitted to the frame; there is no free camera yet.
516
516
  - Of a linked file only the file itself is edited; files it includes stay as they are. Code typed in OpenSCAD but not saved is not visible to the server.
517
517
 
@@ -539,7 +539,7 @@ Notes for coding agents are in [CLAUDE.md](CLAUDE.md).
539
539
 
540
540
  ### Benchmark
541
541
 
542
- The server's guidance (instructions, guidelines, tool descriptions) decides how good the models get, so changes to it are measured. `bench/tasks.ts` holds six complex parts (Raspberry Pi case, planetary gears, screw-top jar, print-in-place hinge, Gridfinity bin, phone stand), each a first request plus two follow-up requests. Claude solves them through this server's tools, with a fresh workspace per run; the final design is graded with a full render: valid closed solid on z = 0, size, Customizer parameters, render time, point probes (solid or empty at a given position), parameter values and whether a follow-up used `set_parameters`. `--judge` adds a rating of six rendered views against a per-task rubric.
542
+ The server's guidance (instructions, guidelines, tool descriptions) decides how good the models get, so changes to it are measured. `bench/tasks.ts` holds six complex parts (Raspberry Pi case, planetary gears, screw-top jar, print-in-place hinge, Gridfinity bin, phone stand), each a first request plus two follow-up requests, and one change to a file the user already has (`edit-file`: a wall hook written to a folder outside the workspace, which has to be linked and edited in place). Claude solves them through this server's tools, with a fresh workspace per run; the final design is graded with a full render: valid closed solid on z = 0, size, Customizer parameters, render time, point probes (solid or empty at a given position), parameter values, whether a follow-up used `set_parameters`, and for `edit-file` whether the file was linked and kept most of its lines. `--judge` adds a rating of six rendered views against a per-task rubric.
543
543
 
544
544
  ```bash
545
545
  npm run bench -- --tasks jar --runs 1 # one task, to try it
package/dist/index.js CHANGED
@@ -2149,7 +2149,7 @@ difference() {
2149
2149
  | Topic | Rule |
2150
2150
  |---|---|
2151
2151
  | Wall thickness | at least 1.2 mm, 2\u20133 mm for parts under load, 4 mm and more for brackets and hooks |
2152
- | Overhangs | at most 45\xB0 from vertical without supports; turn steeper ones into chamfers |
2152
+ | Overhangs | at most 45\xB0 from vertical without supports; turn steeper ones into chamfers. \`analyze_design\` lists every steeper region with area, position and narrowest width: compare them with the PRINT ORIENTATION line |
2153
2153
  | Bridges | under 50 mm between two supports |
2154
2154
  | Layer height | features in Z are multiples of 0.2 mm; details below 0.4 mm in XY do not print |
2155
2155
  | Clearance, moving parts | 0.2 mm per side (0.3\u20130.5 mm for a loose fit) |
@@ -2223,7 +2223,7 @@ else { translate([-10, 0, 0]) socket(); translate([20, 0, 0]) peg(); } // centre
2223
2223
  - Lay several parts out along X, 5 mm or more apart, the group centred on the origin. The automatic image then shows all of them; a part placed at +Y hides behind a taller one.
2224
2224
  - \`render_views\` with \`section: {axis: "y", at: 0}\` and \`params: {show: "assembled"}\` cuts the assembly open: the \`front\` view shows the fit in profile, cut faces in orange: lips in grooves, threads, pins in their holes, the gap all around.
2225
2225
  - \`measure_design\` with \`params: {show: "assembled"}\` gives the gap in numbers: a line across the fit, \`{through: [0, 0, 6], axis: "x"}\`, returns the solid and empty stretches along X, here socket wall, 0.2 empty, peg 10, 0.2 empty, socket wall. Measure clearances, wall thicknesses and hole sizes this way instead of estimating them from an image; one call takes up to 10 lines.
2226
- - \`analyze_design\` with \`params: {show_overlap: true}\` answers whether the parts collide: "Empty" means they do not touch, "Touching only" means faces meet without overlapping (a lid resting on a rim), a size means they overlap there. Every call is a full render, so let one call answer for all parts: with more than two, \`show_overlap\` is the union of the intersections of every pair that can meet (\`union() { intersection() { a(); b(); } intersection() { b(); c(); } }\`). A moving part gets a pose parameter (an angle) and at most three checks: the print pose, one pose in between, and just past the end stop. Do not sweep a pose or search for a clearance with repeated calls; take clearances from these guidelines, and once a check is "Empty", move on.
2226
+ - \`analyze_design\` with \`params: {show_overlap: true}\` answers whether the parts collide: "Empty" means they do not touch, "Touching only" means faces meet without overlapping (a lid resting on a rim), a size means they overlap there. Every call is a full render, so let one call answer for all parts: with more than two, \`show_overlap\` is the union of the intersections of every pair that can meet (\`union() { intersection() { a(); b(); } intersection() { b(); c(); } }\`). A moving part gets a pose parameter (an angle) and at most three checks: the print pose, one pose in between, and just past the end stop, all in one call with \`variants\`: \`[{label: "print", params: {show_overlap: true, angle: 0}}, {label: "half", params: {show_overlap: true, angle: 90}}, {label: "past the stop", params: {show_overlap: true, angle: 195}}]\`. Do not sweep a pose or search for a clearance with repeated calls; take clearances from these guidelines, and once a check is "Empty", move on.
2227
2227
  - The defaults stay the print layout (\`show = "print"\`, \`show_overlap = false\`, \`part = "all"\`): that is what gets exported.
2228
2228
  - A design with more than one part gets the \`part\` parameter: "all" is the print layout, every other value draws that one part alone, on z = 0 in its print orientation. \`export_design\` with \`parts: true\` then writes one file per part, so the user can print a single part again; \`params: {part: "peg"}\` on \`analyze_design\` gives the size of one part.
2229
2229
 
@@ -2441,10 +2441,108 @@ function registerResources(env) {
2441
2441
  }
2442
2442
 
2443
2443
  // src/tools/analyze.ts
2444
- import { mkdtemp as mkdtemp2, rm as rm3 } from "fs/promises";
2445
- import os6 from "os";
2446
- import path9 from "path";
2447
- import * as z5 from "zod/v4";
2444
+ import { mkdtemp as mkdtemp3, readFile as readFile6, rm as rm4 } from "fs/promises";
2445
+ import os7 from "os";
2446
+ import path10 from "path";
2447
+ import * as z6 from "zod/v4";
2448
+
2449
+ // src/mesh/overhang.ts
2450
+ var BED_EPS = 0.01;
2451
+ var GRID = 1e-4;
2452
+ var TOLERANCE_DEG = 0.5;
2453
+ function findOverhangs(mesh, limitDeg = 45) {
2454
+ const t = mesh.triangles;
2455
+ let minZ = Infinity;
2456
+ for (let i = 2; i < t.length; i += 3) if (t[i] < minZ) minZ = t[i];
2457
+ const threshold = Math.sin((limitDeg + TOLERANCE_DEG) * Math.PI / 180);
2458
+ const picked = [];
2459
+ for (let k = 0; k < mesh.count; k++) {
2460
+ const o = k * 9;
2461
+ const ax = t[o], ay = t[o + 1], az = t[o + 2];
2462
+ const bx = t[o + 3] - ax, by = t[o + 4] - ay, bz = t[o + 5] - az;
2463
+ const cx = t[o + 6] - ax, cy = t[o + 7] - ay, cz = t[o + 8] - az;
2464
+ const nx = by * cz - bz * cy;
2465
+ const ny = bz * cx - bx * cz;
2466
+ const nz = bx * cy - by * cx;
2467
+ const len = Math.hypot(nx, ny, nz);
2468
+ if (len === 0 || -nz / len <= threshold) continue;
2469
+ if (Math.max(az, t[o + 5], t[o + 8]) <= minZ + BED_EPS) continue;
2470
+ const angle = Math.asin(Math.min(1, -nz / len)) * 180 / Math.PI;
2471
+ picked.push({ tri: k, area: len / 2, angle });
2472
+ }
2473
+ const parent = picked.map((_, i) => i);
2474
+ const find = (i) => {
2475
+ while (parent[i] !== i) {
2476
+ parent[i] = parent[parent[i]];
2477
+ i = parent[i];
2478
+ }
2479
+ return i;
2480
+ };
2481
+ const owner = /* @__PURE__ */ new Map();
2482
+ picked.forEach((p, i) => {
2483
+ for (let v = 0; v < 3; v++) {
2484
+ const o = p.tri * 9 + v * 3;
2485
+ const key = `${Math.round(t[o] / GRID)},${Math.round(t[o + 1] / GRID)},${Math.round(t[o + 2] / GRID)}`;
2486
+ const seen = owner.get(key);
2487
+ if (seen === void 0) owner.set(key, i);
2488
+ else {
2489
+ const a = find(seen);
2490
+ const b = find(i);
2491
+ if (a !== b) parent[a] = b;
2492
+ }
2493
+ }
2494
+ });
2495
+ const groups = /* @__PURE__ */ new Map();
2496
+ picked.forEach((p, i) => {
2497
+ const root = find(i);
2498
+ let r = groups.get(root);
2499
+ if (!r) {
2500
+ r = {
2501
+ area: 0,
2502
+ min: [Infinity, Infinity, Infinity],
2503
+ max: [-Infinity, -Infinity, -Infinity],
2504
+ narrowest: 0,
2505
+ maxAngle: 0,
2506
+ flat: true,
2507
+ triangles: 0
2508
+ };
2509
+ groups.set(root, r);
2510
+ }
2511
+ r.area += p.area;
2512
+ r.triangles++;
2513
+ r.maxAngle = Math.max(r.maxAngle, p.angle);
2514
+ if (p.angle < 89) r.flat = false;
2515
+ for (let v = 0; v < 3; v++) {
2516
+ for (let a = 0; a < 3; a++) {
2517
+ const value = t[p.tri * 9 + v * 3 + a];
2518
+ if (value < r.min[a]) r.min[a] = value;
2519
+ if (value > r.max[a]) r.max[a] = value;
2520
+ }
2521
+ }
2522
+ });
2523
+ const regions = [...groups.values()].map((r) => ({ ...r, narrowest: Math.min(r.max[0] - r.min[0], r.max[1] - r.min[1]) })).sort((a, b) => b.area - a.area);
2524
+ return { limitDeg, regions, totalArea: regions.reduce((s, r) => s + r.area, 0) };
2525
+ }
2526
+
2527
+ // src/mesh/stl.ts
2528
+ var HEADER = 80;
2529
+ var RECORD = 50;
2530
+ var StlError = class extends Error {
2531
+ name = "StlError";
2532
+ };
2533
+ function parseBinaryStl(buf) {
2534
+ if (buf.length < HEADER + 4) throw new StlError("The STL file is too short.");
2535
+ const count = buf.readUInt32LE(HEADER);
2536
+ if (buf.length < HEADER + 4 + count * RECORD) {
2537
+ throw new StlError(`The STL file announces ${count} triangles but is too short for them.`);
2538
+ }
2539
+ const triangles = new Float32Array(count * 9);
2540
+ for (let i = 0; i < count; i++) {
2541
+ const base = HEADER + 4 + i * RECORD + 12;
2542
+ for (let j = 0; j < 9; j++) triangles[i * 9 + j] = buf.readFloatLE(base + j * 4);
2543
+ }
2544
+ return { triangles, count };
2545
+ }
2448
2546
 
2449
2547
  // src/openscad/engine.ts
2450
2548
  import { mkdir as mkdir4, mkdtemp, readFile as readFile4, rename as rename2, rm as rm2, stat as stat4, writeFile as writeFile3 } from "fs/promises";
@@ -3058,14 +3156,36 @@ function selectPrinters(configured, requested) {
3058
3156
  const byId = configured.find((p) => p.id === wanted.toLowerCase().replace(/[\s_-]+/g, ""));
3059
3157
  return [byId ?? parsePrinter(wanted)];
3060
3158
  }
3061
- var BED_EPS = 0.01;
3159
+ var BED_EPS2 = 0.01;
3160
+ function bedWarning(minZ) {
3161
+ if (minZ > BED_EPS2) {
3162
+ return `The part starts at z = ${mm(minZ)} mm, above the bed. Move it down so its lowest face is on z = 0.`;
3163
+ }
3164
+ if (minZ < -BED_EPS2) {
3165
+ return `The part reaches ${mm(-minZ)} mm below z = 0. Move it up so its lowest face is on z = 0.`;
3166
+ }
3167
+ return void 0;
3168
+ }
3169
+ var sizeText = (g) => `${mm(g.size[0])} \xD7 ${mm(g.size[1])} \xD7 ${mm(g.size[2])} mm (X \xD7 Y \xD7 Z)`;
3170
+ var boxText = (g) => `X ${mm(g.min[0])} \u2026 ${mm(g.max[0])}, Y ${mm(g.min[1])} \u2026 ${mm(g.max[1])}, Z ${mm(g.min[2])} \u2026 ${mm(g.max[2])}`;
3171
+ function briefGeometry(geometry) {
3172
+ const bed = bedWarning(geometry.min[2]);
3173
+ const closed = geometry.closed ? "closed solid" : "closedness not checked (one object without boolean operations)";
3174
+ return {
3175
+ line: `Size: ${sizeText(geometry)}; bounding box ${boxText(geometry)}; ${closed}; ${bed ? `not on the bed. ${bed}` : "lowest point on z = 0."}`,
3176
+ data: {
3177
+ size_mm: geometry.size,
3178
+ bounding_box: { min: geometry.min, max: geometry.max },
3179
+ closed_solid: geometry.closed ?? null,
3180
+ on_bed: bed === void 0
3181
+ }
3182
+ };
3183
+ }
3062
3184
  function describeGeometry(geometry, printers, code) {
3063
3185
  const [x, y, z14] = geometry.size;
3064
3186
  const warnings = [];
3065
3187
  const lines2 = [];
3066
- lines2.push(
3067
- `Size: ${mm(x)} \xD7 ${mm(y)} \xD7 ${mm(z14)} mm (X \xD7 Y \xD7 Z). Bounding box: X ${mm(geometry.min[0])} \u2026 ${mm(geometry.max[0])}, Y ${mm(geometry.min[1])} \u2026 ${mm(geometry.max[1])}, Z ${mm(geometry.min[2])} \u2026 ${mm(geometry.max[2])}.`
3068
- );
3188
+ lines2.push(`Size: ${sizeText(geometry)}. Bounding box: ${boxText(geometry)}.`);
3069
3189
  const counts = `${geometry.facets !== void 0 ? `, ${geometry.facets} facets` : ""}${geometry.vertices !== void 0 ? `, ${geometry.vertices} vertices` : ""}`;
3070
3190
  if (geometry.closed) {
3071
3191
  lines2.push(`Mesh: closed solid${counts}.`);
@@ -3074,16 +3194,9 @@ function describeGeometry(geometry, printers, code) {
3074
3194
  `Mesh: one object without boolean operations${counts}; OpenSCAD checks closedness only for the result of union, difference or intersection. Primitives and extrusions are closed; a polyhedron() with a missing or flipped face is not caught here.`
3075
3195
  );
3076
3196
  }
3077
- const minZ = geometry.min[2];
3078
- if (minZ > BED_EPS) {
3079
- warnings.push(
3080
- `The part starts at z = ${mm(minZ)} mm, above the bed. Move it down so its lowest face is on z = 0.`
3081
- );
3082
- } else if (minZ < -BED_EPS) {
3083
- warnings.push(`The part reaches ${mm(-minZ)} mm below z = 0. Move it up so its lowest face is on z = 0.`);
3084
- } else {
3085
- lines2.push("Bed contact: the lowest point is on z = 0.");
3086
- }
3197
+ const bed = bedWarning(geometry.min[2]);
3198
+ if (bed) warnings.push(bed);
3199
+ else lines2.push("Bed contact: the lowest point is on z = 0.");
3087
3200
  if (Math.max(x, y, z14) < 2) {
3088
3201
  warnings.push("The whole part is smaller than 2 mm. Check the units: dimensions are millimetres.");
3089
3202
  }
@@ -3119,108 +3232,451 @@ function describeGeometry(geometry, printers, code) {
3119
3232
  };
3120
3233
  }
3121
3234
 
3122
- // src/tools/analyze.ts
3123
- var printerArg = z5.string().max(60).optional().describe(
3124
- 'Printer to check against: a configured or built-in profile id (e.g. "a1mini") or a build volume "WIDTHxDEPTHxHEIGHT" in mm. Default: every configured profile.'
3125
- );
3126
- var FLAT_MM = 0.01;
3127
- function flatAxis(size) {
3128
- const i = size.findIndex((s) => s < FLAT_MM);
3129
- return i < 0 ? void 0 : ["x", "y", "z"][i];
3235
+ // src/tools/measure.ts
3236
+ import { mkdtemp as mkdtemp2, readFile as readFile5, rm as rm3 } from "fs/promises";
3237
+ import os6 from "os";
3238
+ import path9 from "path";
3239
+ import * as z5 from "zod/v4";
3240
+
3241
+ // src/mesh/probe.ts
3242
+ var AXES = {
3243
+ // [axis, u, v] with (u, v, axis) cyclic, so the projected orientation is the normal's sign.
3244
+ x: [0, 1, 2],
3245
+ y: [1, 2, 0],
3246
+ z: [2, 0, 1]
3247
+ };
3248
+ var JITTER_U = 1234567e-11;
3249
+ var JITTER_V = 7654321e-12;
3250
+ var SAME = 1e-6;
3251
+ function lineSegments(mesh, through, axis) {
3252
+ const [a, u, v] = AXES[axis];
3253
+ const pu = through[u] + JITTER_U;
3254
+ const pv = through[v] + JITTER_V;
3255
+ const t = mesh.triangles;
3256
+ const hits = [];
3257
+ for (let i2 = 0; i2 < mesh.count; i2++) {
3258
+ const o = i2 * 9;
3259
+ const au = t[o + u];
3260
+ const av = t[o + v];
3261
+ const bu = t[o + 3 + u];
3262
+ const bv = t[o + 3 + v];
3263
+ const cu = t[o + 6 + u];
3264
+ const cv = t[o + 6 + v];
3265
+ const area = (bu - au) * (cv - av) - (bv - av) * (cu - au);
3266
+ if (area === 0) continue;
3267
+ const w0 = (bu - pu) * (cv - pv) - (bv - pv) * (cu - pu);
3268
+ const w1 = (cu - pu) * (av - pv) - (cv - pv) * (au - pu);
3269
+ const w2 = (au - pu) * (bv - pv) - (av - pv) * (bu - pu);
3270
+ const inside = area > 0 ? w0 >= 0 && w1 >= 0 && w2 >= 0 : w0 <= 0 && w1 <= 0 && w2 <= 0;
3271
+ if (!inside) continue;
3272
+ const at = (w0 * t[o + a] + w1 * t[o + 3 + a] + w2 * t[o + 6 + a]) / area;
3273
+ hits.push({ at, delta: area > 0 ? -1 : 1 });
3274
+ }
3275
+ if (hits.length === 0) return [];
3276
+ hits.sort((p, q) => p.at - q.at);
3277
+ const segments = [];
3278
+ let winding = 0;
3279
+ let i = 0;
3280
+ while (i < hits.length) {
3281
+ const at = hits[i].at;
3282
+ while (i < hits.length && hits[i].at - at < SAME) winding += hits[i++].delta;
3283
+ const next = hits[i]?.at;
3284
+ if (next === void 0) break;
3285
+ const kind = winding > 0 ? "solid" : "empty";
3286
+ const last = segments[segments.length - 1];
3287
+ if (last && last.kind === kind) last.to = next;
3288
+ else segments.push({ kind, from: at, to: next });
3289
+ }
3290
+ while (segments[0]?.kind === "empty") segments.shift();
3291
+ while (segments[segments.length - 1]?.kind === "empty") segments.pop();
3292
+ return segments;
3130
3293
  }
3131
- function isEmptyModel(report) {
3132
- return report.errors.length > 0 && report.errors.every((e) => /^Current top level object is empty/.test(e.message));
3294
+ var SURFACE = 1e-3;
3295
+ function pointState(mesh, at) {
3296
+ const z14 = at[2];
3297
+ for (const s of lineSegments(mesh, at, "z")) {
3298
+ if (Math.abs(z14 - s.from) < SURFACE || Math.abs(z14 - s.to) < SURFACE) return "surface";
3299
+ if (z14 > s.from && z14 < s.to) return s.kind;
3300
+ }
3301
+ return "empty";
3133
3302
  }
3134
- function registerAnalyzeTools(env) {
3303
+
3304
+ // src/tools/measure.ts
3305
+ var vec3 = z5.tuple([z5.number(), z5.number(), z5.number()]);
3306
+ var label = z5.string().max(60).optional().describe('What is measured, e.g. "gap lid to rim".');
3307
+ var MAX_SEGMENTS = 40;
3308
+ var MAX_STL_BYTES = 256 * 1024 * 1024;
3309
+ var where = (p) => `(${p.map(mm).join(", ")})`;
3310
+ function formatSegments(segments) {
3311
+ if (segments.length === 0) return "misses the model";
3312
+ const shown2 = segments.slice(0, MAX_SEGMENTS).map((s) => `${s.kind} ${mm(s.to - s.from)} (${mm(s.from)} \u2026 ${mm(s.to)})`);
3313
+ const more = segments.length - MAX_SEGMENTS;
3314
+ return shown2.join(", ") + (more > 0 ? `, \u2026 ${more} more segments` : "");
3315
+ }
3316
+ function registerMeasureTools(env) {
3135
3317
  const { server, config } = env;
3136
3318
  server.registerTool(
3137
- "analyze_design",
3319
+ "measure_design",
3138
3320
  {
3139
- title: "Analyze a design",
3140
- description: "OpenSCAD: renders the final geometry of a design and reports its size and bounding box in mm, facet count, whether the mesh is a closed solid, whether the part sits on z = 0, and whether it fits the build volume of each configured printer (also turned 90\xB0 around Z). Writes no file. `params` analyzes a variant without changing the design; a variant without geometry (for example an intersection of two parts that do not touch) is reported as empty, not as an error, and one without thickness (parts that only touch) as touching.",
3141
- inputSchema: z5.object({ name: designName, printer: printerArg, params: paramsArg }),
3321
+ title: "Measure a design",
3322
+ description: "OpenSCAD: renders the final geometry of a design and measures it. Each line runs parallel to the X, Y or Z axis through a given point and returns the stretches of material (solid) and air (empty) it crosses, with their lengths and start and end coordinates in mm, from the first surface to the last: wall thickness, gaps between parts, hole and slot widths. Each point is reported as solid, empty or on a surface. Curved surfaces are measured on the rendered facets ($fn). `params` measures a variant (for example an assembled pose) without changing the design. Writes no file.",
3323
+ inputSchema: z5.object({
3324
+ name: designName,
3325
+ lines: z5.array(
3326
+ z5.object({
3327
+ through: vec3.describe("A point on the line [x, y, z] in mm."),
3328
+ axis: z5.enum(["x", "y", "z"]).describe("Direction of the line."),
3329
+ label
3330
+ })
3331
+ ).max(10).optional().describe("Up to 10 lines."),
3332
+ points: z5.array(z5.object({ at: vec3.describe("[x, y, z] in mm."), label })).max(20).optional().describe("Up to 20 points."),
3333
+ params: paramsArg
3334
+ }),
3142
3335
  annotations: READ
3143
3336
  },
3144
- safe(async ({ name, printer, params }, ctx) => {
3337
+ safe(async ({ name, lines: lines2, points, params }, ctx) => {
3338
+ if (!lines2?.length && !points?.length) {
3339
+ throw new UserError(
3340
+ 'Give at least one line or point, e.g. lines: [{through: [0, 0, 5], axis: "x", label: "wall"}].'
3341
+ );
3342
+ }
3145
3343
  const design = await readDesign(config, name);
3146
- const printers = selectPrinters(config.printers, printer);
3147
3344
  const { bin } = await env.openscad();
3148
- const tmp = await mkdtemp2(path9.join(os6.tmpdir(), "openscad-mcp-analyze-"));
3345
+ const tmp = await mkdtemp2(path9.join(os6.tmpdir(), "openscad-mcp-measure-"));
3149
3346
  try {
3150
3347
  const built = await buildModel(bin, design, config, {
3151
- out: path9.join(tmp, "model.3mf"),
3152
- format: "3mf",
3348
+ out: path9.join(tmp, "model.stl"),
3349
+ format: "stl",
3153
3350
  params,
3154
3351
  signal: ctx.mcpReq.signal
3155
3352
  });
3156
- const head = `Design "${design.paths.slug}", version ${design.meta.version} (full render, ${duration(built.report.durationMs)}).`;
3157
3353
  const overrides = Object.keys(params ?? {});
3158
- const note = overrides.length ? `Analyzed with parameter overrides: ${overrides.join(", ")}.` : void 0;
3354
+ const head = [
3355
+ `Design "${design.paths.slug}", version ${design.meta.version} (full render, ${duration(built.report.durationMs)}).`,
3356
+ overrides.length ? `Measured with parameter overrides: ${overrides.join(", ")}.` : void 0,
3357
+ externalNote(design.external)
3358
+ ];
3359
+ const base = { name: design.paths.slug, version: design.meta.version };
3159
3360
  if (overrides.length && isEmptyModel(built.report)) {
3361
+ const clean2 = { ...built.report, ok: true, errors: [] };
3160
3362
  return result(
3161
3363
  [
3162
- head,
3163
- note,
3164
- externalNote(design.external),
3165
- "Empty: with these parameter overrides the model has no geometry. If the overrides switch on an overlap check (an intersection of two parts), the parts do not overlap.",
3166
- formatValidation({ ...built.report, ok: true, errors: [] })
3364
+ ...head,
3365
+ "Empty: with these parameter overrides the model has no geometry.",
3366
+ formatValidation(clean2)
3167
3367
  ].filter(Boolean).join("\n"),
3168
- {
3169
- name: design.paths.slug,
3170
- version: design.meta.version,
3171
- empty: true,
3172
- ...validationData({ ...built.report, ok: true, errors: [] })
3173
- }
3368
+ { ...base, empty: true, ...validationData(clean2) }
3174
3369
  );
3175
3370
  }
3176
3371
  if (!built.file || !built.geometry) {
3177
3372
  return result(
3178
- [
3179
- head,
3180
- note,
3181
- externalNote(design.external),
3182
- formatValidation(built.report),
3183
- "No geometry to analyze."
3184
- ].filter(Boolean).join("\n"),
3185
- { name: design.paths.slug, version: design.meta.version, ...validationData(built.report) }
3373
+ [...head, formatValidation(built.report), "No geometry to measure."].filter(Boolean).join("\n"),
3374
+ { ...base, ...validationData(built.report) }
3186
3375
  );
3187
3376
  }
3188
- const geo = describeGeometry(built.geometry, printers, design.code);
3189
- const flat = overrides.length ? flatAxis(built.geometry.size) : void 0;
3190
- const touching = flat ? `Touching only: the result is 0 mm thick in ${flat.toUpperCase()}, a face and not a volume. If the overrides switch on an overlap check, the parts touch there (for example a lid resting on a rim) but do not overlap.` : void 0;
3191
- return result(
3192
- [head, note, externalNote(design.external), touching, ...geo.lines, formatValidation(built.report)].filter(Boolean).join("\n"),
3193
- {
3194
- name: design.paths.slug,
3195
- version: design.meta.version,
3196
- ...geo.data,
3197
- ...flat ? { touching_only: true } : {},
3198
- ...validationData(built.report)
3377
+ if ((built.bytes ?? 0) > MAX_STL_BYTES) {
3378
+ throw new UserError(
3379
+ `The rendered model has ${Math.round((built.bytes ?? 0) / 1024 / 1024)} MB, more than measure_design reads (${MAX_STL_BYTES / 1024 / 1024} MB). Lower $fn or measure a simpler variant with \`params\`.`
3380
+ );
3381
+ }
3382
+ const mesh = parseBinaryStl(await readFile5(built.file));
3383
+ const g = built.geometry;
3384
+ const out = [
3385
+ ...head.filter(Boolean),
3386
+ `Model extent: X ${mm(g.min[0])} \u2026 ${mm(g.max[0])}, Y ${mm(g.min[1])} \u2026 ${mm(g.max[1])}, Z ${mm(g.min[2])} \u2026 ${mm(g.max[2])} mm.`
3387
+ ];
3388
+ const measuredLines = (lines2 ?? []).map((l) => {
3389
+ const segments = lineSegments(mesh, l.through, l.axis);
3390
+ return { ...l, segments };
3391
+ });
3392
+ if (measuredLines.length) {
3393
+ out.push(
3394
+ "Lines (stretches in order of rising coordinate on the line's axis; solid = material, empty = air, a gap or a hole; lengths and coordinates in mm):"
3395
+ );
3396
+ for (const l of measuredLines) {
3397
+ const name2 = l.label ? `"${l.label}" ` : "";
3398
+ out.push(
3399
+ `- ${name2}along ${l.axis.toUpperCase()} through ${where(l.through)}: ${formatSegments(l.segments)}`
3400
+ );
3199
3401
  }
3200
- );
3201
- } finally {
3202
- await rm3(tmp, { recursive: true, force: true });
3203
- }
3204
- })
3205
- );
3206
- }
3207
-
3208
- // src/tools/export.ts
3209
- import { createHash as createHash2 } from "crypto";
3210
- import path10 from "path";
3211
- import * as z6 from "zod/v4";
3212
- var kB = (bytes) => bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} kB`;
3213
- var HANDOFF = `Next step: this file is the model, not a print job. A slicer (Bambu Studio, OrcaSlicer, PrusaSlicer) turns it into one; a printer MCP server that slices can take the path as it is. Start a print only after the user asked for it in this conversation.`;
3214
- var LAYOUT_VALUES = /* @__PURE__ */ new Set(["all", "print", "layout", "assembled", "assembly"]);
3215
- var NO_PARTS = 'For `parts: true` the design needs a string parameter `part` with a Customizer list of its parts, e.g. `part = "all"; // [all, box, lid]`, where "all" is the print layout and every other value draws that one part alone, on z = 0 in its print orientation. Add it with update_design, or export without `parts`.';
3216
- var MAX_PARTS = 20;
3217
- function partValues(parameters) {
3218
- const part = parameters.find((p) => p.name === "part");
3219
- if (part?.type !== "string") throw new UserError(NO_PARTS);
3220
- const values = (part.options ?? []).map((o) => o.value).filter((v) => typeof v === "string" && !LAYOUT_VALUES.has(v.toLowerCase()));
3221
- if (values.length === 0) throw new UserError(NO_PARTS);
3222
- const unique = [...new Set(values)];
3223
- if (unique.length > MAX_PARTS) {
3402
+ }
3403
+ const measuredPoints = (points ?? []).map((p) => ({ ...p, state: pointState(mesh, p.at) }));
3404
+ if (measuredPoints.length) {
3405
+ out.push("Points:");
3406
+ for (const p of measuredPoints) {
3407
+ const name2 = p.label ? `"${p.label}" ` : "";
3408
+ out.push(`- ${name2}${where(p.at)}: ${p.state === "surface" ? "on a surface" : p.state}`);
3409
+ }
3410
+ }
3411
+ out.push(formatValidation(built.report));
3412
+ const round2 = (n) => Math.round(n * 1e3) / 1e3;
3413
+ return result(out.join("\n"), {
3414
+ ...base,
3415
+ bounding_box: { min: g.min, max: g.max },
3416
+ lines: measuredLines.map((l) => ({
3417
+ ...l.label ? { label: l.label } : {},
3418
+ axis: l.axis,
3419
+ through: l.through,
3420
+ segments: l.segments.map((s) => ({
3421
+ kind: s.kind,
3422
+ from: round2(s.from),
3423
+ to: round2(s.to),
3424
+ length: round2(s.to - s.from)
3425
+ }))
3426
+ })),
3427
+ points: measuredPoints.map((p) => ({
3428
+ ...p.label ? { label: p.label } : {},
3429
+ at: p.at,
3430
+ state: p.state
3431
+ })),
3432
+ ...validationData(built.report)
3433
+ });
3434
+ } finally {
3435
+ await rm3(tmp, { recursive: true, force: true });
3436
+ }
3437
+ })
3438
+ );
3439
+ }
3440
+
3441
+ // src/tools/analyze.ts
3442
+ var printerArg = z6.string().max(60).optional().describe(
3443
+ 'Printer to check against: a configured or built-in profile id (e.g. "a1mini") or a build volume "WIDTHxDEPTHxHEIGHT" in mm. Default: every configured profile.'
3444
+ );
3445
+ var FLAT_MM = 0.01;
3446
+ var MAX_VARIANTS = 4;
3447
+ var PARALLEL = 2;
3448
+ var SHOWN_REGIONS = 8;
3449
+ function flatAxis(size) {
3450
+ const i = size.findIndex((s) => s < FLAT_MM);
3451
+ return i < 0 ? void 0 : ["x", "y", "z"][i];
3452
+ }
3453
+ function isEmptyModel(report) {
3454
+ return report.errors.length > 0 && report.errors.every((e) => /^Current top level object is empty/.test(e.message));
3455
+ }
3456
+ var EMPTY_TEXT = "Empty: with these parameter overrides the model has no geometry. If the overrides switch on an overlap check (an intersection of two parts), the parts do not overlap.";
3457
+ var touchingText = (axis) => `Touching only: the result is 0 mm thick in ${axis.toUpperCase()}, a face and not a volume. If the overrides switch on an overlap check, the parts touch there (for example a lid resting on a rim) but do not overlap.`;
3458
+ var NO_SUPPORTS = /\b(no|without|none)\b[^.;]{0,20}\bsupports?\b|\bsupports?\b[^.;]{0,10}\b(none|not needed)\b|support-?free/i;
3459
+ function formatOverhangs(report, orientation) {
3460
+ const head = `Overhangs (faces more than ${report.limitDeg}\xB0 from vertical that point down and are not on the bed)`;
3461
+ if (report.regions.length === 0) return [`${head}: none.`];
3462
+ const lines2 = [
3463
+ `${head}: ${report.regions.length} region${report.regions.length === 1 ? "" : "s"}, ${mm(report.totalArea)} mm\xB2 in total. Largest first; "narrowest" is the smaller of the X and Y extent, the span of a bridge or the width of a ledge:`
3464
+ ];
3465
+ for (const r of report.regions.slice(0, SHOWN_REGIONS)) {
3466
+ const z14 = r.max[2] - r.min[2] < 0.01 ? `z = ${mm(r.min[2])}` : `z ${mm(r.min[2])} \u2026 ${mm(r.max[2])}`;
3467
+ lines2.push(
3468
+ `- ${mm(r.area)} mm\xB2, ${r.flat ? "flat (a ceiling)" : `sloped, up to ${Math.round(r.maxAngle)}\xB0 from vertical`}, ${z14}, X ${mm(r.min[0])} \u2026 ${mm(r.max[0])}, Y ${mm(r.min[1])} \u2026 ${mm(r.max[1])}, narrowest ${mm(r.narrowest)} mm`
3469
+ );
3470
+ }
3471
+ const rest = report.regions.slice(SHOWN_REGIONS);
3472
+ if (rest.length) {
3473
+ lines2.push(
3474
+ `- \u2026 ${rest.length} more region${rest.length === 1 ? "" : "s"}, ${mm(rest.reduce((s, r) => s + r.area, 0))} mm\xB2 together`
3475
+ );
3476
+ }
3477
+ lines2.push(
3478
+ "Whether a region needs supports depends on what holds it: a flat region between two walls is a bridge (guidelines: under 50 mm), the top of a small horizontal hole usually prints, a ledge that sticks out does not. Chamfer an overhang to 45\xB0 or turn the part to avoid supports."
3479
+ );
3480
+ if (orientation && NO_SUPPORTS.test(orientation)) {
3481
+ lines2.push("The print orientation in the code says no supports: check the regions above against it.");
3482
+ }
3483
+ return lines2;
3484
+ }
3485
+ function overhangData(report) {
3486
+ const r2 = (n) => Math.round(n * 100) / 100;
3487
+ return {
3488
+ limit_deg: report.limitDeg,
3489
+ total_area_mm2: r2(report.totalArea),
3490
+ regions: report.regions.slice(0, SHOWN_REGIONS).map((r) => ({
3491
+ area_mm2: r2(r.area),
3492
+ min: r.min.map(r2),
3493
+ max: r.max.map(r2),
3494
+ narrowest_mm: r2(r.narrowest),
3495
+ max_angle_deg: Math.round(r.maxAngle),
3496
+ flat: r.flat
3497
+ })),
3498
+ region_count: report.regions.length
3499
+ };
3500
+ }
3501
+ async function inBatches(items, limit, fn) {
3502
+ const out = new Array(items.length);
3503
+ let next = 0;
3504
+ const worker = async () => {
3505
+ while (next < items.length) {
3506
+ const i = next++;
3507
+ out[i] = await fn(items[i]);
3508
+ }
3509
+ };
3510
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
3511
+ return out;
3512
+ }
3513
+ function registerAnalyzeTools(env) {
3514
+ const { server, config } = env;
3515
+ const build = async (bin, design, dir, params, signal) => buildModel(bin, design, config, { out: path10.join(dir, "model.stl"), format: "stl", params, signal });
3516
+ server.registerTool(
3517
+ "analyze_design",
3518
+ {
3519
+ title: "Analyze a design",
3520
+ description: "OpenSCAD: renders the final geometry of a design and reports its size and bounding box in mm, facet count, whether the mesh is a closed solid, whether the part sits on z = 0, whether it fits the build volume of each configured printer (also turned 90\xB0 around Z), and its overhangs: regions of faces more than 45\xB0 from vertical that point down and are not on the bed, with area, position and narrowest width. Writes no file. `params` analyzes a variant without changing the design; a variant without geometry (for example an intersection of two parts that do not touch) is reported as empty, not as an error, and one without thickness (parts that only touch) as touching. `variants` analyzes up to 4 variants in one call (each a full render, `params` applies to all of them), with size, closedness, bed contact, empty and touching per variant, without printer fit and overhangs.",
3521
+ inputSchema: z6.object({
3522
+ name: designName,
3523
+ printer: printerArg,
3524
+ params: paramsArg,
3525
+ variants: z6.array(
3526
+ z6.object({
3527
+ label: z6.string().min(1).max(60).describe('What the variant shows, e.g. "lid closed".'),
3528
+ params: paramsArg.unwrap().describe("Parameter overrides of this variant, on top of `params`.")
3529
+ })
3530
+ ).min(1).max(MAX_VARIANTS).optional().describe(
3531
+ 'Several variants in one call, e.g. overlap checks in different poses: [{label: "closed", params: {show_overlap: true, angle: 0}}, {label: "past the stop", params: {show_overlap: true, angle: 195}}].'
3532
+ )
3533
+ }),
3534
+ annotations: READ
3535
+ },
3536
+ safe(async ({ name, printer, params, variants }, ctx) => {
3537
+ const design = await readDesign(config, name);
3538
+ const { bin } = await env.openscad();
3539
+ const signal = ctx.mcpReq.signal;
3540
+ const tmp = await mkdtemp3(path10.join(os7.tmpdir(), "openscad-mcp-analyze-"));
3541
+ try {
3542
+ if (variants) {
3543
+ if (printer !== void 0) {
3544
+ throw new UserError("`printer` applies to a single analysis; leave it out with `variants`.");
3545
+ }
3546
+ const runs = await inBatches(
3547
+ variants.map((v, i) => ({ ...v, i })),
3548
+ PARALLEL,
3549
+ async (v) => {
3550
+ const dir = path10.join(tmp, String(v.i));
3551
+ await rm4(dir, { recursive: true, force: true });
3552
+ const merged = { ...params, ...v.params };
3553
+ return { label: v.label, params: merged, built: await build(bin, design, dir, merged, signal) };
3554
+ }
3555
+ );
3556
+ return variantResult(design, runs);
3557
+ }
3558
+ const printers = selectPrinters(config.printers, printer);
3559
+ const built = await build(bin, design, tmp, params, signal);
3560
+ const head = `Design "${design.paths.slug}", version ${design.meta.version} (full render, ${duration(built.report.durationMs)}).`;
3561
+ const overrides = Object.keys(params ?? {});
3562
+ const note = overrides.length ? `Analyzed with parameter overrides: ${overrides.join(", ")}.` : void 0;
3563
+ if (overrides.length && isEmptyModel(built.report)) {
3564
+ return result(
3565
+ [
3566
+ head,
3567
+ note,
3568
+ externalNote(design.external),
3569
+ EMPTY_TEXT,
3570
+ formatValidation({ ...built.report, ok: true, errors: [] })
3571
+ ].filter(Boolean).join("\n"),
3572
+ {
3573
+ name: design.paths.slug,
3574
+ version: design.meta.version,
3575
+ empty: true,
3576
+ ...validationData({ ...built.report, ok: true, errors: [] })
3577
+ }
3578
+ );
3579
+ }
3580
+ if (!built.file || !built.geometry) {
3581
+ return result(
3582
+ [
3583
+ head,
3584
+ note,
3585
+ externalNote(design.external),
3586
+ formatValidation(built.report),
3587
+ "No geometry to analyze."
3588
+ ].filter(Boolean).join("\n"),
3589
+ { name: design.paths.slug, version: design.meta.version, ...validationData(built.report) }
3590
+ );
3591
+ }
3592
+ const geo = describeGeometry(built.geometry, printers, design.code);
3593
+ const flat = overrides.length ? flatAxis(built.geometry.size) : void 0;
3594
+ let overhangLines = [];
3595
+ let overhangs;
3596
+ if (!flat && (built.bytes ?? 0) <= MAX_STL_BYTES) {
3597
+ const report = findOverhangs(parseBinaryStl(await readFile6(built.file)));
3598
+ overhangLines = formatOverhangs(report, printOrientation(design.code));
3599
+ overhangs = overhangData(report);
3600
+ }
3601
+ return result(
3602
+ [
3603
+ head,
3604
+ note,
3605
+ externalNote(design.external),
3606
+ flat ? touchingText(flat) : void 0,
3607
+ ...geo.lines,
3608
+ ...overhangLines,
3609
+ formatValidation(built.report)
3610
+ ].filter(Boolean).join("\n"),
3611
+ {
3612
+ name: design.paths.slug,
3613
+ version: design.meta.version,
3614
+ ...geo.data,
3615
+ ...overhangs ? { overhangs } : {},
3616
+ ...flat ? { touching_only: true } : {},
3617
+ ...validationData(built.report)
3618
+ }
3619
+ );
3620
+ } finally {
3621
+ await rm4(tmp, { recursive: true, force: true });
3622
+ }
3623
+ })
3624
+ );
3625
+ }
3626
+ function variantResult(design, runs) {
3627
+ const lines2 = [
3628
+ `Design "${design.paths.slug}", version ${design.meta.version}: ${runs.length} variant${runs.length === 1 ? "" : "s"}, each a full render.`
3629
+ ];
3630
+ const note = externalNote(design.external);
3631
+ if (note) lines2.push(note);
3632
+ const data = [];
3633
+ for (const { label: label2, params, built } of runs) {
3634
+ const overrides = Object.entries(params).map(([k, v]) => `${k} = ${JSON.stringify(v)}`).join(", ");
3635
+ lines2.push(`Variant "${label2}" (${overrides || "no overrides"}; ${duration(built.report.durationMs)}):`);
3636
+ const entry = { label: label2, params };
3637
+ if (isEmptyModel(built.report)) {
3638
+ const clean2 = { ...built.report, ok: true, errors: [] };
3639
+ lines2.push(`- ${EMPTY_TEXT}`, formatValidation(clean2));
3640
+ Object.assign(entry, { empty: true, ...validationData(clean2) });
3641
+ } else if (!built.geometry || !built.file) {
3642
+ lines2.push(formatValidation(built.report), "- No geometry to analyze.");
3643
+ Object.assign(entry, validationData(built.report));
3644
+ } else {
3645
+ const flat = flatAxis(built.geometry.size);
3646
+ const brief = briefGeometry(built.geometry);
3647
+ lines2.push(
3648
+ ...flat ? [`- ${touchingText(flat)}`] : [],
3649
+ `- ${brief.line}`,
3650
+ formatValidation(built.report)
3651
+ );
3652
+ Object.assign(entry, brief.data, flat ? { touching_only: true } : {}, validationData(built.report));
3653
+ }
3654
+ data.push(entry);
3655
+ }
3656
+ return result(lines2.join("\n"), {
3657
+ name: design.paths.slug,
3658
+ version: design.meta.version,
3659
+ variants: data,
3660
+ ok: data.every((d) => d.ok === true)
3661
+ });
3662
+ }
3663
+
3664
+ // src/tools/export.ts
3665
+ import { createHash as createHash2 } from "crypto";
3666
+ import path11 from "path";
3667
+ import * as z7 from "zod/v4";
3668
+ var kB = (bytes) => bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} kB`;
3669
+ var HANDOFF = `Next step: this file is the model, not a print job. A slicer (Bambu Studio, OrcaSlicer, PrusaSlicer) turns it into one; a printer MCP server that slices can take the path as it is. Start a print only after the user asked for it in this conversation.`;
3670
+ var LAYOUT_VALUES = /* @__PURE__ */ new Set(["all", "print", "layout", "assembled", "assembly"]);
3671
+ var NO_PARTS = 'For `parts: true` the design needs a string parameter `part` with a Customizer list of its parts, e.g. `part = "all"; // [all, box, lid]`, where "all" is the print layout and every other value draws that one part alone, on z = 0 in its print orientation. Add it with update_design, or export without `parts`.';
3672
+ var MAX_PARTS = 20;
3673
+ function partValues(parameters) {
3674
+ const part = parameters.find((p) => p.name === "part");
3675
+ if (part?.type !== "string") throw new UserError(NO_PARTS);
3676
+ const values = (part.options ?? []).map((o) => o.value).filter((v) => typeof v === "string" && !LAYOUT_VALUES.has(v.toLowerCase()));
3677
+ if (values.length === 0) throw new UserError(NO_PARTS);
3678
+ const unique = [...new Set(values)];
3679
+ if (unique.length > MAX_PARTS) {
3224
3680
  throw new UserError(
3225
3681
  `The \`part\` parameter lists ${unique.length} parts; \`parts: true\` exports at most ${MAX_PARTS} at once. Export single parts with \`params\` {"part": "<value>"} instead.`
3226
3682
  );
@@ -3234,12 +3690,12 @@ function registerExportTools(env) {
3234
3690
  {
3235
3691
  title: "Export a design",
3236
3692
  description: "OpenSCAD: renders the final geometry of a design and writes it to the design's exports folder as 3MF (default) or binary STL. Returns the absolute file path, the size and bounding box in mm, the fit per configured printer, the mesh and bed-contact checks and the print orientation stated in the code. The file name carries the version, so earlier exports stay. `params` exports a variant without changing the design. `parts: true` writes one file per part instead: one for every value of the design's string parameter `part` except all, print, layout, assembled and assembly, each rendered with only that value set, with its own size, fit and checks. This server does not slice or print.",
3237
- inputSchema: z6.object({
3693
+ inputSchema: z7.object({
3238
3694
  name: designName,
3239
- format: z6.enum(["3mf", "stl"]).optional().describe('Default "3mf".'),
3695
+ format: z7.enum(["3mf", "stl"]).optional().describe('Default "3mf".'),
3240
3696
  printer: printerArg,
3241
3697
  params: paramsArg,
3242
- parts: z6.boolean().optional().describe(
3698
+ parts: z7.boolean().optional().describe(
3243
3699
  'true: one file per value of the `part` parameter (e.g. "box" and "lid"), not the print layout.'
3244
3700
  )
3245
3701
  }),
@@ -3252,7 +3708,7 @@ function registerExportTools(env) {
3252
3708
  const fmt = format ?? "3mf";
3253
3709
  const overrides = Object.keys(params ?? {});
3254
3710
  const variant = overrides.length ? `-${createHash2("sha256").update(JSON.stringify(params)).digest("hex").slice(0, 6)}` : "";
3255
- const fileName = (suffix) => path10.join(
3711
+ const fileName = (suffix) => path11.join(
3256
3712
  design.paths.exports,
3257
3713
  `${design.paths.slug}-v${versionLabel(design.meta.version)}${variant}${suffix}.${fmt}`
3258
3714
  );
@@ -3375,25 +3831,25 @@ function registerExportTools(env) {
3375
3831
 
3376
3832
  // src/tools/files.ts
3377
3833
  import { realpath as realpath4 } from "fs/promises";
3378
- import path12 from "path";
3379
- import * as z7 from "zod/v4";
3834
+ import path13 from "path";
3835
+ import * as z8 from "zod/v4";
3380
3836
 
3381
3837
  // src/workspace/files.ts
3382
3838
  import { readdir as readdir4, realpath as realpath3, stat as stat5 } from "fs/promises";
3383
- import path11 from "path";
3839
+ import path12 from "path";
3384
3840
  var FIND_MAX_DEPTH = 3;
3385
3841
  var FIND_MAX_FILES = 200;
3386
3842
  var SKIP = /* @__PURE__ */ new Set(["node_modules", "Library", "Applications", "System"]);
3387
3843
  async function findScadFiles(config, folder) {
3388
3844
  const given = expandHome(folder.trim());
3389
- if (!path11.isAbsolute(given)) {
3845
+ if (!path12.isAbsolute(given)) {
3390
3846
  throw new UserError(
3391
3847
  `"${folder}" is not an absolute path. Pass the full path of a folder, e.g. "~/3d-print".`
3392
3848
  );
3393
3849
  }
3394
3850
  const root = await realpath3(given).catch(() => void 0);
3395
3851
  if (!root || !(await stat5(root)).isDirectory()) throw new UserError(`There is no folder at ${given}.`);
3396
- const workspace = await realpath3(config.workspace).catch(() => path11.resolve(config.workspace));
3852
+ const workspace = await realpath3(config.workspace).catch(() => path12.resolve(config.workspace));
3397
3853
  if (isInside(workspace, root)) {
3398
3854
  throw new UserError(`${given} is the design workspace. list_designs lists its designs.`);
3399
3855
  }
@@ -3408,7 +3864,7 @@ async function findScadFiles(config, folder) {
3408
3864
  return;
3409
3865
  }
3410
3866
  if (e.name.startsWith(".")) continue;
3411
- const full = path11.join(dir, e.name);
3867
+ const full = path12.join(dir, e.name);
3412
3868
  if (e.isDirectory()) {
3413
3869
  if (full === workspace) {
3414
3870
  skippedWorkspace = true;
@@ -3439,7 +3895,7 @@ function registerFileTools(env) {
3439
3895
  const sys = () => env.guiSystem ?? realSystem;
3440
3896
  const location = () => env.openscad().catch(() => void 0);
3441
3897
  async function designIndex() {
3442
- const workspace = await realpath4(config.workspace).catch(() => path12.resolve(config.workspace));
3898
+ const workspace = await realpath4(config.workspace).catch(() => path13.resolve(config.workspace));
3443
3899
  const linked = new Map(
3444
3900
  (await listDesigns(config)).filter((d) => d.linked).map((d) => [d.path, d.name])
3445
3901
  );
@@ -3447,7 +3903,7 @@ function registerFileTools(env) {
3447
3903
  const name = linked.get(file);
3448
3904
  if (name) return { design: name, linked: true };
3449
3905
  if (isInside(workspace, file)) {
3450
- const first = path12.relative(workspace, file).split(path12.sep)[0];
3906
+ const first = path13.relative(workspace, file).split(path13.sep)[0];
3451
3907
  if (first) return { design: first, linked: false };
3452
3908
  }
3453
3909
  return void 0;
@@ -3458,8 +3914,8 @@ function registerFileTools(env) {
3458
3914
  {
3459
3915
  title: "Find OpenSCAD files",
3460
3916
  description: `OpenSCAD: without \`folder\`, lists the files OpenSCAD opened or saved last, newest first (the first one is usually the file open in OpenSCAD right now), and whether OpenSCAD is running. With \`folder\`, lists the .scad files in that folder and up to ${FIND_MAX_DEPTH} levels of sub-folders (at most ${FIND_MAX_FILES}, newest first, hidden folders skipped). Each file shows the design it belongs to, if any.`,
3461
- inputSchema: z7.object({
3462
- folder: z7.string().min(1).max(1024).optional().describe(
3917
+ inputSchema: z8.object({
3918
+ folder: z8.string().min(1).max(1024).optional().describe(
3463
3919
  `Absolute folder path, "~" allowed, e.g. "~/Documents/3d-print". Default: OpenSCAD's recent files.`
3464
3920
  )
3465
3921
  }),
@@ -3520,13 +3976,13 @@ function registerFileTools(env) {
3520
3976
  {
3521
3977
  title: "Link an existing file",
3522
3978
  description: "OpenSCAD: makes an existing .scad file outside the workspace a design that is edited where it is: update_design, set_parameters and restore_version then write into this file, and every state is kept as a version in the workspace (version 1 is the file as found). OpenSCAD runs in the file's folder, so relative include<> and use<> keep working. Returns the code, the parameters and the validation like create_design, with an image when the code is valid. Linking a linked file again returns its design; a linked design whose file was moved is connected to the new path by passing its name.",
3523
- inputSchema: z7.object({
3524
- path: z7.string().min(1).max(1024).describe('Absolute path of the .scad file, "~" allowed.'),
3979
+ inputSchema: z8.object({
3980
+ path: z8.string().min(1).max(1024).describe('Absolute path of the .scad file, "~" allowed.'),
3525
3981
  name: designName.optional().describe(
3526
3982
  "Design name; default is the file name without .scad. Pass the name of a linked design whose file moved to connect it again."
3527
3983
  ),
3528
- description: z7.string().max(300).optional().describe("One line on what the part is and what it is for."),
3529
- preview: z7.boolean().optional().describe("Attach an image of the model when the code is valid. Default: true (server setting)."),
3984
+ description: z8.string().max(300).optional().describe("One line on what the part is and what it is for."),
3985
+ preview: z8.boolean().optional().describe("Attach an image of the model when the code is valid. Default: true (server setting)."),
3530
3986
  views: previewViewsArg
3531
3987
  }),
3532
3988
  annotations: WRITE
@@ -3545,7 +4001,7 @@ function registerFileTools(env) {
3545
4001
  openInGui2 = true;
3546
4002
  autoReload = await readAutoReload(sys());
3547
4003
  if (sys().platform === "darwin" && loc.appBundle) {
3548
- await markOpened(sys(), path12.join(stateDir(config), "gui.json"), scad, pids[0]);
4004
+ await markOpened(sys(), path13.join(stateDir(config), "gui.json"), scad, pids[0]);
3549
4005
  }
3550
4006
  }
3551
4007
  }
@@ -3588,8 +4044,8 @@ function registerFileTools(env) {
3588
4044
  }
3589
4045
 
3590
4046
  // src/tools/gui.ts
3591
- import path13 from "path";
3592
- import * as z8 from "zod/v4";
4047
+ import path14 from "path";
4048
+ import * as z9 from "zod/v4";
3593
4049
  function registerGuiTools(env) {
3594
4050
  const { server, config } = env;
3595
4051
  server.registerTool(
@@ -3597,9 +4053,9 @@ function registerGuiTools(env) {
3597
4053
  {
3598
4054
  title: "Open in OpenSCAD",
3599
4055
  description: `OpenSCAD: opens a design in the OpenSCAD application on the user's screen, starting OpenSCAD when needed. With OpenSCAD's setting "${AUTORELOAD_MENU}" the window then follows every later change to the design; the result says whether that setting is on. A design this server already opened is not opened a second time: OpenSCAD is brought to the front instead.`,
3600
- inputSchema: z8.object({
4056
+ inputSchema: z9.object({
3601
4057
  name: designName,
3602
- reopen: z8.boolean().optional().describe(
4058
+ reopen: z9.boolean().optional().describe(
3603
4059
  "Open a window again although this server already opened the design (the user closed the window)."
3604
4060
  )
3605
4061
  }),
@@ -3611,7 +4067,7 @@ function registerGuiTools(env) {
3611
4067
  const r = await openInGui({
3612
4068
  location,
3613
4069
  file: design.paths.scad,
3614
- stateFile: path13.join(stateDir(config), "gui.json"),
4070
+ stateFile: path14.join(stateDir(config), "gui.json"),
3615
4071
  managePrefs: config.manageGuiPrefs,
3616
4072
  reopen,
3617
4073
  system: env.guiSystem
@@ -3651,15 +4107,15 @@ function registerGuiTools(env) {
3651
4107
  }
3652
4108
 
3653
4109
  // src/tools/guidelines.ts
3654
- import * as z9 from "zod/v4";
4110
+ import * as z10 from "zod/v4";
3655
4111
  function registerGuidelineTools(env) {
3656
4112
  env.server.registerTool(
3657
4113
  "get_guidelines",
3658
4114
  {
3659
4115
  title: "Get design guidelines",
3660
4116
  description: 'OpenSCAD: returns the design guidelines of this server. Topic "3d-printing" (default, together with "libraries" and, when there are any, "learnings"): workflow, code structure, orientation, FDM printing rules, standard screw sizes and what to check in the images. "openscad-reference": language reference with tested helper modules. "libraries": the libraries installed on this machine with usage examples. "learnings": lessons recorded with record_learning in this workspace.',
3661
- inputSchema: z9.object({
3662
- topic: z9.enum(TOPICS).optional().describe('Default: "3d-printing" plus "libraries" plus "learnings" when there are any.')
4117
+ inputSchema: z10.object({
4118
+ topic: z10.enum(TOPICS).optional().describe('Default: "3d-printing" plus "libraries" plus "learnings" when there are any.')
3663
4119
  }),
3664
4120
  annotations: READ
3665
4121
  },
@@ -3681,8 +4137,8 @@ More: get_guidelines with topic ${others.map((t) => `"${t}"`).join(" or ")} (als
3681
4137
  }
3682
4138
 
3683
4139
  // src/tools/learnings.ts
3684
- import * as z10 from "zod/v4";
3685
- var learningId = z10.number().int().positive().describe("Id of the learning, as list_learnings shows it.");
4140
+ import * as z11 from "zod/v4";
4141
+ var learningId = z11.number().int().positive().describe("Id of the learning, as list_learnings shows it.");
3686
4142
  function registerLearningTools(env) {
3687
4143
  const { server, config } = env;
3688
4144
  server.registerTool(
@@ -3690,15 +4146,15 @@ function registerLearningTools(env) {
3690
4146
  {
3691
4147
  title: "Record a learning",
3692
4148
  description: `OpenSCAD: saves a short lesson for later designs in the workspace (.openscad-mcp/learnings.json): a technique that failed or worked, a printing rule, or a preference of the user. get_guidelines returns every learning together with the guidelines. \`replaces\` swaps an existing learning for a refined one. At most ${MAX_LEARNINGS} learnings; an identical text is refused.`,
3693
- inputSchema: z10.object({
3694
- category: z10.enum(LEARNING_CATEGORIES).describe(
4149
+ inputSchema: z11.object({
4150
+ category: z11.enum(LEARNING_CATEGORIES).describe(
3695
4151
  '"technique": how to model something in OpenSCAD; "printing": what prints well or badly; "preference": what the user wants in their parts.'
3696
4152
  ),
3697
- text: z10.string().min(1).max(MAX_TEXT).describe(
4153
+ text: z11.string().min(1).max(MAX_TEXT).describe(
3698
4154
  'The lesson as one general sentence that holds for later parts, e.g. "Round every outer edge, also the top and bottom of extrusions; screw holes stay sharp."'
3699
4155
  ),
3700
- reason: z10.string().min(1).max(MAX_REASON).describe('What led to it, e.g. "User asked for all edges rounded on broom-holder".'),
3701
- design: z10.string().max(80).optional().describe("The design it came from."),
4156
+ reason: z11.string().min(1).max(MAX_REASON).describe('What led to it, e.g. "User asked for all edges rounded on broom-holder".'),
4157
+ design: z11.string().max(80).optional().describe("The design it came from."),
3702
4158
  replaces: learningId.optional().describe("Id of a learning this one refines; that one is forgotten.")
3703
4159
  }),
3704
4160
  annotations: WRITE
@@ -3726,9 +4182,9 @@ function registerLearningTools(env) {
3726
4182
  {
3727
4183
  title: "List learnings",
3728
4184
  description: "OpenSCAD: lists the learnings of this workspace with id, category, text, reason, design and date. Forgotten and replaced ones only with `include_forgotten`.",
3729
- inputSchema: z10.object({
3730
- category: z10.enum(LEARNING_CATEGORIES).optional().describe("Only this category."),
3731
- include_forgotten: z10.boolean().optional().describe("Also list forgotten and replaced learnings.")
4185
+ inputSchema: z11.object({
4186
+ category: z11.enum(LEARNING_CATEGORIES).optional().describe("Only this category."),
4187
+ include_forgotten: z11.boolean().optional().describe("Also list forgotten and replaced learnings.")
3732
4188
  }),
3733
4189
  annotations: READ
3734
4190
  },
@@ -3752,9 +4208,9 @@ function registerLearningTools(env) {
3752
4208
  {
3753
4209
  title: "Forget a learning",
3754
4210
  description: "OpenSCAD: marks a learning as forgotten, so get_guidelines no longer returns it. It stays in the file with the reason; list_learnings with `include_forgotten` shows it. A learning that is already forgotten stays as it is.",
3755
- inputSchema: z10.object({
4211
+ inputSchema: z11.object({
3756
4212
  id: learningId,
3757
- reason: z10.string().max(MAX_REASON).optional().describe("Why it no longer holds.")
4213
+ reason: z11.string().max(MAX_REASON).optional().describe("Why it no longer holds.")
3758
4214
  }),
3759
4215
  annotations: WRITE_IDEMPOTENT
3760
4216
  },
@@ -3768,232 +4224,6 @@ function registerLearningTools(env) {
3768
4224
  );
3769
4225
  }
3770
4226
 
3771
- // src/tools/measure.ts
3772
- import { mkdtemp as mkdtemp3, readFile as readFile5, rm as rm4 } from "fs/promises";
3773
- import os7 from "os";
3774
- import path14 from "path";
3775
- import * as z11 from "zod/v4";
3776
-
3777
- // src/mesh/probe.ts
3778
- var AXES = {
3779
- // [axis, u, v] with (u, v, axis) cyclic, so the projected orientation is the normal's sign.
3780
- x: [0, 1, 2],
3781
- y: [1, 2, 0],
3782
- z: [2, 0, 1]
3783
- };
3784
- var JITTER_U = 1234567e-11;
3785
- var JITTER_V = 7654321e-12;
3786
- var SAME = 1e-6;
3787
- function lineSegments(mesh, through, axis) {
3788
- const [a, u, v] = AXES[axis];
3789
- const pu = through[u] + JITTER_U;
3790
- const pv = through[v] + JITTER_V;
3791
- const t = mesh.triangles;
3792
- const hits = [];
3793
- for (let i2 = 0; i2 < mesh.count; i2++) {
3794
- const o = i2 * 9;
3795
- const au = t[o + u];
3796
- const av = t[o + v];
3797
- const bu = t[o + 3 + u];
3798
- const bv = t[o + 3 + v];
3799
- const cu = t[o + 6 + u];
3800
- const cv = t[o + 6 + v];
3801
- const area = (bu - au) * (cv - av) - (bv - av) * (cu - au);
3802
- if (area === 0) continue;
3803
- const w0 = (bu - pu) * (cv - pv) - (bv - pv) * (cu - pu);
3804
- const w1 = (cu - pu) * (av - pv) - (cv - pv) * (au - pu);
3805
- const w2 = (au - pu) * (bv - pv) - (av - pv) * (bu - pu);
3806
- const inside = area > 0 ? w0 >= 0 && w1 >= 0 && w2 >= 0 : w0 <= 0 && w1 <= 0 && w2 <= 0;
3807
- if (!inside) continue;
3808
- const at = (w0 * t[o + a] + w1 * t[o + 3 + a] + w2 * t[o + 6 + a]) / area;
3809
- hits.push({ at, delta: area > 0 ? -1 : 1 });
3810
- }
3811
- if (hits.length === 0) return [];
3812
- hits.sort((p, q) => p.at - q.at);
3813
- const segments = [];
3814
- let winding = 0;
3815
- let i = 0;
3816
- while (i < hits.length) {
3817
- const at = hits[i].at;
3818
- while (i < hits.length && hits[i].at - at < SAME) winding += hits[i++].delta;
3819
- const next = hits[i]?.at;
3820
- if (next === void 0) break;
3821
- const kind = winding > 0 ? "solid" : "empty";
3822
- const last = segments[segments.length - 1];
3823
- if (last && last.kind === kind) last.to = next;
3824
- else segments.push({ kind, from: at, to: next });
3825
- }
3826
- while (segments[0]?.kind === "empty") segments.shift();
3827
- while (segments[segments.length - 1]?.kind === "empty") segments.pop();
3828
- return segments;
3829
- }
3830
- var SURFACE = 1e-3;
3831
- function pointState(mesh, at) {
3832
- const z14 = at[2];
3833
- for (const s of lineSegments(mesh, at, "z")) {
3834
- if (Math.abs(z14 - s.from) < SURFACE || Math.abs(z14 - s.to) < SURFACE) return "surface";
3835
- if (z14 > s.from && z14 < s.to) return s.kind;
3836
- }
3837
- return "empty";
3838
- }
3839
-
3840
- // src/mesh/stl.ts
3841
- var HEADER = 80;
3842
- var RECORD = 50;
3843
- var StlError = class extends Error {
3844
- name = "StlError";
3845
- };
3846
- function parseBinaryStl(buf) {
3847
- if (buf.length < HEADER + 4) throw new StlError("The STL file is too short.");
3848
- const count = buf.readUInt32LE(HEADER);
3849
- if (buf.length < HEADER + 4 + count * RECORD) {
3850
- throw new StlError(`The STL file announces ${count} triangles but is too short for them.`);
3851
- }
3852
- const triangles = new Float32Array(count * 9);
3853
- for (let i = 0; i < count; i++) {
3854
- const base = HEADER + 4 + i * RECORD + 12;
3855
- for (let j = 0; j < 9; j++) triangles[i * 9 + j] = buf.readFloatLE(base + j * 4);
3856
- }
3857
- return { triangles, count };
3858
- }
3859
-
3860
- // src/tools/measure.ts
3861
- var vec3 = z11.tuple([z11.number(), z11.number(), z11.number()]);
3862
- var label = z11.string().max(60).optional().describe('What is measured, e.g. "gap lid to rim".');
3863
- var MAX_SEGMENTS = 40;
3864
- var MAX_STL_BYTES = 256 * 1024 * 1024;
3865
- var where = (p) => `(${p.map(mm).join(", ")})`;
3866
- function formatSegments(segments) {
3867
- if (segments.length === 0) return "misses the model";
3868
- const shown2 = segments.slice(0, MAX_SEGMENTS).map((s) => `${s.kind} ${mm(s.to - s.from)} (${mm(s.from)} \u2026 ${mm(s.to)})`);
3869
- const more = segments.length - MAX_SEGMENTS;
3870
- return shown2.join(", ") + (more > 0 ? `, \u2026 ${more} more segments` : "");
3871
- }
3872
- function registerMeasureTools(env) {
3873
- const { server, config } = env;
3874
- server.registerTool(
3875
- "measure_design",
3876
- {
3877
- title: "Measure a design",
3878
- description: "OpenSCAD: renders the final geometry of a design and measures it. Each line runs parallel to the X, Y or Z axis through a given point and returns the stretches of material (solid) and air (empty) it crosses, with their lengths and start and end coordinates in mm, from the first surface to the last: wall thickness, gaps between parts, hole and slot widths. Each point is reported as solid, empty or on a surface. Curved surfaces are measured on the rendered facets ($fn). `params` measures a variant (for example an assembled pose) without changing the design. Writes no file.",
3879
- inputSchema: z11.object({
3880
- name: designName,
3881
- lines: z11.array(
3882
- z11.object({
3883
- through: vec3.describe("A point on the line [x, y, z] in mm."),
3884
- axis: z11.enum(["x", "y", "z"]).describe("Direction of the line."),
3885
- label
3886
- })
3887
- ).max(10).optional().describe("Up to 10 lines."),
3888
- points: z11.array(z11.object({ at: vec3.describe("[x, y, z] in mm."), label })).max(20).optional().describe("Up to 20 points."),
3889
- params: paramsArg
3890
- }),
3891
- annotations: READ
3892
- },
3893
- safe(async ({ name, lines: lines2, points, params }, ctx) => {
3894
- if (!lines2?.length && !points?.length) {
3895
- throw new UserError(
3896
- 'Give at least one line or point, e.g. lines: [{through: [0, 0, 5], axis: "x", label: "wall"}].'
3897
- );
3898
- }
3899
- const design = await readDesign(config, name);
3900
- const { bin } = await env.openscad();
3901
- const tmp = await mkdtemp3(path14.join(os7.tmpdir(), "openscad-mcp-measure-"));
3902
- try {
3903
- const built = await buildModel(bin, design, config, {
3904
- out: path14.join(tmp, "model.stl"),
3905
- format: "stl",
3906
- params,
3907
- signal: ctx.mcpReq.signal
3908
- });
3909
- const overrides = Object.keys(params ?? {});
3910
- const head = [
3911
- `Design "${design.paths.slug}", version ${design.meta.version} (full render, ${duration(built.report.durationMs)}).`,
3912
- overrides.length ? `Measured with parameter overrides: ${overrides.join(", ")}.` : void 0,
3913
- externalNote(design.external)
3914
- ];
3915
- const base = { name: design.paths.slug, version: design.meta.version };
3916
- if (overrides.length && isEmptyModel(built.report)) {
3917
- const clean2 = { ...built.report, ok: true, errors: [] };
3918
- return result(
3919
- [
3920
- ...head,
3921
- "Empty: with these parameter overrides the model has no geometry.",
3922
- formatValidation(clean2)
3923
- ].filter(Boolean).join("\n"),
3924
- { ...base, empty: true, ...validationData(clean2) }
3925
- );
3926
- }
3927
- if (!built.file || !built.geometry) {
3928
- return result(
3929
- [...head, formatValidation(built.report), "No geometry to measure."].filter(Boolean).join("\n"),
3930
- { ...base, ...validationData(built.report) }
3931
- );
3932
- }
3933
- if ((built.bytes ?? 0) > MAX_STL_BYTES) {
3934
- throw new UserError(
3935
- `The rendered model has ${Math.round((built.bytes ?? 0) / 1024 / 1024)} MB, more than measure_design reads (${MAX_STL_BYTES / 1024 / 1024} MB). Lower $fn or measure a simpler variant with \`params\`.`
3936
- );
3937
- }
3938
- const mesh = parseBinaryStl(await readFile5(built.file));
3939
- const g = built.geometry;
3940
- const out = [
3941
- ...head.filter(Boolean),
3942
- `Model extent: X ${mm(g.min[0])} \u2026 ${mm(g.max[0])}, Y ${mm(g.min[1])} \u2026 ${mm(g.max[1])}, Z ${mm(g.min[2])} \u2026 ${mm(g.max[2])} mm.`
3943
- ];
3944
- const measuredLines = (lines2 ?? []).map((l) => {
3945
- const segments = lineSegments(mesh, l.through, l.axis);
3946
- return { ...l, segments };
3947
- });
3948
- if (measuredLines.length) {
3949
- out.push(
3950
- "Lines (stretches in order of rising coordinate on the line's axis; solid = material, empty = air, a gap or a hole; lengths and coordinates in mm):"
3951
- );
3952
- for (const l of measuredLines) {
3953
- const name2 = l.label ? `"${l.label}" ` : "";
3954
- out.push(
3955
- `- ${name2}along ${l.axis.toUpperCase()} through ${where(l.through)}: ${formatSegments(l.segments)}`
3956
- );
3957
- }
3958
- }
3959
- const measuredPoints = (points ?? []).map((p) => ({ ...p, state: pointState(mesh, p.at) }));
3960
- if (measuredPoints.length) {
3961
- out.push("Points:");
3962
- for (const p of measuredPoints) {
3963
- const name2 = p.label ? `"${p.label}" ` : "";
3964
- out.push(`- ${name2}${where(p.at)}: ${p.state === "surface" ? "on a surface" : p.state}`);
3965
- }
3966
- }
3967
- out.push(formatValidation(built.report));
3968
- const round2 = (n) => Math.round(n * 1e3) / 1e3;
3969
- return result(out.join("\n"), {
3970
- ...base,
3971
- bounding_box: { min: g.min, max: g.max },
3972
- lines: measuredLines.map((l) => ({
3973
- ...l.label ? { label: l.label } : {},
3974
- axis: l.axis,
3975
- through: l.through,
3976
- segments: l.segments.map((s) => ({
3977
- kind: s.kind,
3978
- from: round2(s.from),
3979
- to: round2(s.to),
3980
- length: round2(s.to - s.from)
3981
- }))
3982
- })),
3983
- points: measuredPoints.map((p) => ({
3984
- ...p.label ? { label: p.label } : {},
3985
- at: p.at,
3986
- state: p.state
3987
- })),
3988
- ...validationData(built.report)
3989
- });
3990
- } finally {
3991
- await rm4(tmp, { recursive: true, force: true });
3992
- }
3993
- })
3994
- );
3995
- }
3996
-
3997
4227
  // src/tools/render.ts
3998
4228
  import * as z12 from "zod/v4";
3999
4229
  var DEFAULT_VIEWS = ["iso", "front", "top", "right"];
@@ -4226,7 +4456,7 @@ Workflow
4226
4456
  3. Look at the image; \`views\` on a save or render_views shows other sides, and render_views with \`section\` cuts the model open, and measure_design gives wall thicknesses, gaps and hole sizes in mm. Fix errors and visual problems with update_design, preferring \`edits\` so working code stays untouched.
4227
4457
  4. open_in_openscad shows the model in the user's OpenSCAD window, which then follows every change.
4228
4458
  5. Repeat until the part matches the request, then tell the user what you built and which assumptions you made. Every save is a version (list_versions, restore_version), so nothing is lost.
4229
- 6. Size changes that are parameters go through set_parameters. analyze_design gives the real size and the fit on the user's printers.
4459
+ 6. Size changes that are parameters go through set_parameters. analyze_design gives the real size, the fit on the user's printers and the overhangs.
4230
4460
  7. export_design only when the user asks for the file. It returns the absolute path of the 3MF or STL.
4231
4461
 
4232
4462
  Existing files: to change a .scad file the user already has (the one open in OpenSCAD, or one saved somewhere), find it with find_scad_files (without a folder it lists OpenSCAD's recent files; the first one is usually the file open right now) or take the path the user gives, then link_file. The file stays where it is and is edited in place with update_design (prefer \`edits\`) and set_parameters; version 1 keeps the file as it was. Link only files the user names or clearly means. The server sees the saved file only: if the user is typing in OpenSCAD, ask them to save first. Keep the file's own structure and style instead of rewriting it to the code rules below.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openscad-mcp-v2",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "description": "MCP server for OpenSCAD: describe a 3D-printable part in Claude, Cursor, VS Code or any MCP client and get checked, rendered, versioned parametric SCAD code and a 3MF/STL for your slicer",
5
5
  "type": "module",
6
6
  "license": "MIT",