openscad-mcp-v2 1.1.0 → 1.2.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 +16 -4
  2. package/dist/index.js +348 -41
  3. package/package.json +2 -1
package/README.md CHANGED
@@ -52,6 +52,7 @@ You open the 3MF in Bambu Studio, OrcaSlicer or PrusaSlicer and print it.
52
52
 
53
53
  - **Checks its own work.** OpenSCAD errors come back with file, line and the source around it; failed `assert()`s and missing modules count as errors, although OpenSCAD itself only warns.
54
54
  - **Sees the part.** Every save returns a rendered image of the sides you ask for; `render_views` shows any side and cuts the part open. The client compares the image with your request and fixes what is off.
55
+ - **Measures what images can't show.** `measure_design` reads wall thicknesses, hole sizes and the gap between a lid and its rim or between hinge knuckles off the rendered model, in millimetres.
55
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.
56
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.
57
58
  - **Never loses a state.** Every save is a version; going back adds a new one.
@@ -61,7 +62,16 @@ You open the 3MF in Bambu Studio, OrcaSlicer or PrusaSlicer and print it.
61
62
 
62
63
  ## Quickstart
63
64
 
64
- You need **Node.js 22** or newer and **OpenSCAD**. Set them up by hand (steps 1 to 3 below), or let a coding agent do it.
65
+ You need **OpenSCAD** in every case. **Claude Desktop** installs the server in one click from a bundle and needs nothing else. Other clients need **Node.js 22** or newer: set them up by hand (steps 1 to 3 below), or let a coding agent do it.
66
+
67
+ ### Claude Desktop: one-click install
68
+
69
+ 1. Install OpenSCAD, the development snapshot: [step 1](#1-install-openscad-the-development-snapshot-not-202101).
70
+ 2. Download `openscad-mcp-v2-<version>.mcpb` from the [latest release](https://github.com/JohnnyTheTank/openscad-mcp-v2/releases/latest) (releases from 1.2.0 on carry it).
71
+ 3. Open the file: double-click it, drag it onto the Claude Desktop window, or install it under Settings → Extensions. Claude Desktop shows three optional settings: the design folder, your [printers](#printer-profiles) (for example `a1,a1mini`) and the OpenSCAD executable, which is only needed when it is not found on its own.
72
+ 4. Ask in a new chat: *"Run check_setup, then design a wall hook for a 28 mm broom handle."*
73
+
74
+ Claude Desktop runs the bundle with its own Node.js. To update, install the `.mcpb` of the newer release. The other [settings](#configuration) keep their defaults in the bundle; for those, use the JSON configuration in [step 2](#2-add-the-server-to-your-client) instead.
65
75
 
66
76
  ### Let your coding agent set it up
67
77
 
@@ -130,7 +140,7 @@ Your client needs to start local (stdio) MCP servers, so ChatGPT works in the de
130
140
  <details>
131
141
  <summary><b>Claude Desktop</b></summary>
132
142
 
133
- Settings → Developer → Edit Config opens `claude_desktop_config.json`. Add:
143
+ The [one-click bundle](#claude-desktop-one-click-install) is the easier way. By hand: Settings → Developer → Edit Config opens `claude_desktop_config.json`. Add:
134
144
 
135
145
  ```json
136
146
  {
@@ -392,7 +402,7 @@ Or start with the prompt `new_design`. Designs are saved in `~/openscad-designs`
392
402
  | `OPENSCAD_MCP_IMAGE_SIZE` | `800x600` | Size of rendered images in pixels |
393
403
  | `OPENSCAD_MCP_COLORSCHEME` | `Tomorrow` | OpenSCAD colour scheme for images |
394
404
  | `OPENSCAD_MCP_PREVIEW_TIMEOUT_MS` | `60000` | Limit for validation and the automatic image |
395
- | `OPENSCAD_MCP_RENDER_TIMEOUT_MS` | `300000` | Limit for `render_views`, `analyze_design` and `export_design` |
405
+ | `OPENSCAD_MCP_RENDER_TIMEOUT_MS` | `300000` | Limit for `render_views`, `analyze_design`, `measure_design` and `export_design` |
396
406
  | `OPENSCAD_MCP_MANAGE_GUI_PREFS` | `true` | `false`: never change OpenSCAD's "Automatic Reload and Preview" setting |
397
407
 
398
408
  ### Printer profiles
@@ -427,7 +437,8 @@ A single call can name another one: `printer: "x1c"` or `printer: "300x300x400"`
427
437
  | `list_versions`, `restore_version` | History, and going back (a restore is a new version) |
428
438
  | `set_parameters` | Lists the customizer parameters, or changes their values in the file |
429
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 |
430
- | `export_design` | 3MF (default) or binary STL into the design's `exports/` folder, with path, size and fit |
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
+ | `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 |
431
442
  | `record_learning`, `list_learnings`, `forget_learning` | Lessons for later designs: your corrections and preferences, techniques that failed or worked |
432
443
 
433
444
  Resources: `openscad://guidelines/3d-printing`, `openscad://guidelines/openscad-reference`, `openscad://guidelines/libraries`, `openscad://guidelines/learnings`, `openscad://design/{name}`. Prompts: `new_design`, `refine_design`.
@@ -513,6 +524,7 @@ git clone https://github.com/JohnnyTheTank/openscad-mcp-v2.git
513
524
  cd openscad-mcp-v2
514
525
  npm install
515
526
  npm run build
527
+ npm run bundle # optional: build/openscad-mcp-v2-<version>.mcpb for Claude Desktop
516
528
  ```
517
529
 
518
530
  ```bash
package/dist/index.js CHANGED
@@ -649,10 +649,10 @@ import { dirname, resolve } from "path";
649
649
  import { fileURLToPath } from "url";
650
650
 
651
651
  // src/printers.ts
652
- var profile = (id, label, x, y, z13) => ({
652
+ var profile = (id, label2, x, y, z14) => ({
653
653
  id,
654
- label,
655
- size: [x, y, z13]
654
+ label: label2,
655
+ size: [x, y, z14]
656
656
  });
657
657
  var BUILT_IN_PRINTERS = [
658
658
  profile("a1mini", "Bambu Lab A1 mini", 180, 180, 180),
@@ -715,20 +715,20 @@ function parsePrinters(raw) {
715
715
  }
716
716
  var round = (n) => Math.round(n * 100) / 100;
717
717
  function checkFit(size, printer) {
718
- const [x, y, z13] = size;
718
+ const [x, y, z14] = size;
719
719
  const [bx, by, bz] = printer.size;
720
- const fitsAsIs = x <= bx && y <= by && z13 <= bz;
721
- const fitsTurned = y <= bx && x <= by && z13 <= bz;
720
+ const fitsAsIs = x <= bx && y <= by && z14 <= bz;
721
+ const fitsTurned = y <= bx && x <= by && z14 <= bz;
722
722
  const exceeds = [];
723
723
  if (!fitsAsIs && !fitsTurned) {
724
- if (z13 > bz) exceeds.push(`Z ${round(z13)} mm > ${bz} mm`);
724
+ if (z14 > bz) exceeds.push(`Z ${round(z14)} mm > ${bz} mm`);
725
725
  const [long, short] = x >= y ? [x, y] : [y, x];
726
726
  const [bedLong, bedShort] = bx >= by ? [bx, by] : [by, bx];
727
727
  if (long > bedLong) exceeds.push(`longest footprint side ${round(long)} mm > ${bedLong} mm`);
728
728
  if (short > bedShort) exceeds.push(`shorter footprint side ${round(short)} mm > ${bedShort} mm`);
729
729
  }
730
730
  let diagonal;
731
- if (!fitsAsIs && !fitsTurned && z13 <= bz) {
731
+ if (!fitsAsIs && !fitsTurned && z14 <= bz) {
732
732
  for (let deg = 1; deg < 90 && diagonal === void 0; deg++) {
733
733
  const a = deg * Math.PI / 180;
734
734
  const w = x * Math.cos(a) + y * Math.sin(a);
@@ -1342,19 +1342,19 @@ function createDesign(config, input) {
1342
1342
  function applyEdits(code, edits) {
1343
1343
  let out = code;
1344
1344
  edits.forEach((edit, i) => {
1345
- const label = `Edit ${i + 1}`;
1346
- if (!edit.old_string) throw new UserError(`${label}: old_string is empty.`);
1345
+ const label2 = `Edit ${i + 1}`;
1346
+ if (!edit.old_string) throw new UserError(`${label2}: old_string is empty.`);
1347
1347
  if (edit.old_string === edit.new_string)
1348
- throw new UserError(`${label}: old_string and new_string are equal.`);
1348
+ throw new UserError(`${label2}: old_string and new_string are equal.`);
1349
1349
  const count = out.split(edit.old_string).length - 1;
1350
1350
  if (count === 0) {
1351
1351
  throw new UserError(
1352
- `${label}: old_string was not found in the current code (whitespace and line breaks must match exactly). Read the code with get_design, or send the full code instead.`
1352
+ `${label2}: old_string was not found in the current code (whitespace and line breaks must match exactly). Read the code with get_design, or send the full code instead.`
1353
1353
  );
1354
1354
  }
1355
1355
  if (count > 1 && !edit.replace_all) {
1356
1356
  throw new UserError(
1357
- `${label}: old_string occurs ${count} times. Add surrounding lines to make it unique, or set replace_all.`
1357
+ `${label2}: old_string occurs ${count} times. Add surrounding lines to make it unique, or set replace_all.`
1358
1358
  );
1359
1359
  }
1360
1360
  out = edit.replace_all ? out.split(edit.old_string).join(edit.new_string) : out.replace(edit.old_string, () => edit.new_string);
@@ -2168,6 +2168,10 @@ peg_diameter = 10;
2168
2168
  // Clearance between peg and socket, per side (mm)
2169
2169
  clearance = 0.2;
2170
2170
 
2171
+ /* [Parts] */
2172
+ // all: every part, laid out for printing; socket or peg: that part alone
2173
+ part = "all"; // [all, socket, peg]
2174
+
2171
2175
  /* [Checks] */
2172
2176
  // print: the print layout; assembled: the parts in place
2173
2177
  show = "print"; // [print, assembled]
@@ -2187,18 +2191,22 @@ module peg_in_place() translate([0, 0, 2]) peg();
2187
2191
 
2188
2192
  if (show_overlap) intersection() { socket(); peg_in_place(); }
2189
2193
  else if (show == "assembled") { socket(); peg_in_place(); }
2194
+ else if (part == "socket") socket();
2195
+ else if (part == "peg") peg();
2190
2196
  else { translate([-10, 0, 0]) socket(); translate([20, 0, 0]) peg(); } // centred, 10 mm apart
2191
2197
  \`\`\`
2192
2198
 
2193
2199
  - 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.
2194
2200
  - \`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.
2201
+ - \`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.
2195
2202
  - \`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.
2196
- - The defaults stay the print layout (\`show = "print"\`, \`show_overlap = false\`): that is what gets exported.
2203
+ - The defaults stay the print layout (\`show = "print"\`, \`show_overlap = false\`, \`part = "all"\`): that is what gets exported.
2204
+ - 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.
2197
2205
 
2198
2206
  ## Recipes for common mechanisms
2199
2207
 
2200
2208
  - **Snap-fit lid**: a lip on the lid, 1.2\u20131.6 mm thick, goes inside the wall with 0.2 mm clearance per side. A 0.5 mm bead with 45\xB0 flanks along the lip clicks into a 0.6 mm groove with 45\xB0 flanks in the wall, 2\u20133 mm below the rim. The 45\xB0 flanks print without supports and let the lid come off again.
2201
- - **Print-in-place hinge**: knuckles alternate between the two leaves along the axis, with a 0.4 mm gap everywhere: between the knuckles, around the pin, and between each leaf and the other leaf's knuckles. Instead of a cylindrical pin, give one leaf's knuckles 45\xB0 cones that sit in cone-shaped sockets of the neighbouring knuckles; move each socket back by gap \xD7 \u221A2 along the axis, so the gap is the same across the cone faces. Stop at 180\xB0 (opened flat): with the axis at z = r (knuckle radius), fill the lower half of every knuckle down to the bed across its full diameter (\`translate([0, -r, 0]) cube([knuckle_length, 2 * r, r])\`), and end the other leaf's plate beside that knuckle at y = \xB1(r + gap). The hinge still folds closed, and the knuckles get a flat base on the bed. Opening past flat swings the filled half against the other plate's end after about gap / r radians (gap 0.4, r = 3: about 8\xB0). Check with a pose parameter: flat and half closed are "Empty", 15\xB0 past flat overlaps (that overlap is the stop).
2209
+ - **Print-in-place hinge**: knuckles alternate between the two leaves along the axis, with a 0.4 mm gap everywhere: between the knuckles, around the pin, and between each leaf and the other leaf's knuckles. Instead of a cylindrical pin, give one leaf's knuckles 45\xB0 cones that sit in cone-shaped sockets of the neighbouring knuckles; move each socket back by gap \xD7 \u221A2 along the axis, so the gap is the same across the cone faces. Stop at 180\xB0 (opened flat): with the axis at z = r (knuckle radius), fill the lower half of every knuckle down to the bed across its full diameter (\`translate([0, -r, 0]) cube([knuckle_length, 2 * r, r])\`), and end the other leaf's plate beside that knuckle at y = \xB1(r + gap). The hinge still folds closed, and the knuckles get a flat base on the bed. Opening past flat swings the filled half against the other plate's end after about gap / r radians (gap 0.4, r = 3: about 8\xB0). Check with a pose parameter: flat and half closed are "Empty", 15\xB0 past flat overlaps (that overlap is the stop). To measure the gaps between the knuckles with \`measure_design\`, run a line parallel to the axis beside the cones, about 0.5 mm inside the knuckle surface (\`{through: [0, r - 0.5, r + 0.5], axis: "x"}\`): it shows each 0.4 mm gap. A line on the axis runs through the cones and their sockets and shows the gap along the axis there, gap \xD7 \u221A2 (0.57 mm), which is correct.
2202
2210
  - **Enclosure for a circuit board**: standoffs at the mounting holes (M2.5 self-tapping: 2.1 mm hole in a 5\u20136 mm standoff). Connectors stick out 1\u20132 mm past the board edge, so plan how the board goes in: tilted, connectors first, or with cut-outs that reach the rim as open slots. Make openings 0.5 mm larger than the connector on each side.
2203
2211
 
2204
2212
  ## Common mistakes to check for in the images
@@ -2444,9 +2452,9 @@ async function validate(bin, design, config, opts = {}) {
2444
2452
  return annotate(toReport(run, config.previewTimeoutMs), design);
2445
2453
  }
2446
2454
  function formatDiagnostic(d) {
2447
- const where = d.line !== void 0 ? `${d.file ? `${d.file}:` : "line "}${d.line}: ` : "";
2455
+ const where2 = d.line !== void 0 ? `${d.file ? `${d.file}:` : "line "}${d.line}: ` : "";
2448
2456
  const times = d.count && d.count > 1 ? ` (\xD7${d.count})` : "";
2449
- const lines2 = [`- ${where}${d.message}${times}`];
2457
+ const lines2 = [`- ${where2}${d.message}${times}`];
2450
2458
  if (d.source) lines2.push(d.source.replace(/^/gm, " "));
2451
2459
  for (const t of d.trace ?? []) lines2.push(` trace: ${t}`);
2452
2460
  return lines2.join("\n");
@@ -2960,11 +2968,11 @@ function selectPrinters(configured, requested) {
2960
2968
  }
2961
2969
  var BED_EPS = 0.01;
2962
2970
  function describeGeometry(geometry, printers, code) {
2963
- const [x, y, z13] = geometry.size;
2971
+ const [x, y, z14] = geometry.size;
2964
2972
  const warnings = [];
2965
2973
  const lines2 = [];
2966
2974
  lines2.push(
2967
- `Size: ${mm(x)} \xD7 ${mm(y)} \xD7 ${mm(z13)} 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])}.`
2975
+ `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])}.`
2968
2976
  );
2969
2977
  const counts = `${geometry.facets !== void 0 ? `, ${geometry.facets} facets` : ""}${geometry.vertices !== void 0 ? `, ${geometry.vertices} vertices` : ""}`;
2970
2978
  if (geometry.closed) {
@@ -2984,7 +2992,7 @@ function describeGeometry(geometry, printers, code) {
2984
2992
  } else {
2985
2993
  lines2.push("Bed contact: the lowest point is on z = 0.");
2986
2994
  }
2987
- if (Math.max(x, y, z13) < 2) {
2995
+ if (Math.max(x, y, z14) < 2) {
2988
2996
  warnings.push("The whole part is smaller than 2 mm. Check the units: dimensions are millimetres.");
2989
2997
  }
2990
2998
  const fits = printers.map((p) => checkFit(geometry.size, p));
@@ -3111,32 +3119,111 @@ import path9 from "path";
3111
3119
  import * as z6 from "zod/v4";
3112
3120
  var kB = (bytes) => bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} kB`;
3113
3121
  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.`;
3122
+ var LAYOUT_VALUES = /* @__PURE__ */ new Set(["all", "print", "layout", "assembled", "assembly"]);
3123
+ 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`.';
3124
+ function partValues(parameters) {
3125
+ const part = parameters.find((p) => p.name === "part");
3126
+ if (part?.type !== "string") throw new UserError(NO_PARTS);
3127
+ const values = (part.options ?? []).map((o) => o.value).filter((v) => typeof v === "string" && !LAYOUT_VALUES.has(v.toLowerCase()));
3128
+ if (values.length === 0) throw new UserError(NO_PARTS);
3129
+ return [...new Set(values)];
3130
+ }
3114
3131
  function registerExportTools(env) {
3115
3132
  const { server, config } = env;
3116
3133
  server.registerTool(
3117
3134
  "export_design",
3118
3135
  {
3119
3136
  title: "Export a design",
3120
- 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. This server does not slice or print.",
3137
+ 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.",
3121
3138
  inputSchema: z6.object({
3122
3139
  name: designName,
3123
3140
  format: z6.enum(["3mf", "stl"]).optional().describe('Default "3mf".'),
3124
3141
  printer: printerArg,
3125
- params: paramsArg
3142
+ params: paramsArg,
3143
+ parts: z6.boolean().optional().describe(
3144
+ 'true: one file per value of the `part` parameter (e.g. "box" and "lid"), not the print layout.'
3145
+ )
3126
3146
  }),
3127
3147
  annotations: WRITE_IDEMPOTENT
3128
3148
  },
3129
- safe(async ({ name, format, printer, params }, ctx) => {
3149
+ safe(async ({ name, format, printer, params, parts }, ctx) => {
3130
3150
  const design = await readDesign(config, name);
3131
3151
  const printers = selectPrinters(config.printers, printer);
3132
3152
  const { bin } = await env.openscad();
3133
3153
  const fmt = format ?? "3mf";
3134
3154
  const overrides = Object.keys(params ?? {});
3135
3155
  const variant = overrides.length ? `-${createHash2("sha256").update(JSON.stringify(params)).digest("hex").slice(0, 6)}` : "";
3136
- const out = path9.join(
3156
+ const fileName = (suffix) => path9.join(
3137
3157
  design.paths.exports,
3138
- `${design.paths.slug}-v${versionLabel(design.meta.version)}${variant}.${fmt}`
3158
+ `${design.paths.slug}-v${versionLabel(design.meta.version)}${variant}${suffix}.${fmt}`
3139
3159
  );
3160
+ const note = overrides.length ? `Exported with parameter overrides: ${overrides.join(", ")}.` : void 0;
3161
+ if (parts) {
3162
+ if (params && "part" in params) {
3163
+ throw new UserError(
3164
+ "`parts: true` sets `part` for every part itself; leave `part` out of `params`."
3165
+ );
3166
+ }
3167
+ const values = partValues(await readParameters(bin, design, config, ctx.mcpReq.signal));
3168
+ const builds = await Promise.all(
3169
+ values.map(async (value) => ({
3170
+ value,
3171
+ built: await buildModel(bin, design, config, {
3172
+ out: fileName(`-${designSlug(value)}`),
3173
+ format: fmt,
3174
+ params: { ...params, part: value },
3175
+ title: `${design.paths.slug} ${value}`,
3176
+ signal: ctx.mcpReq.signal
3177
+ })
3178
+ }))
3179
+ );
3180
+ const lines2 = [];
3181
+ const data = [];
3182
+ for (const { value, built: built2 } of builds) {
3183
+ if (built2.file && built2.geometry) {
3184
+ const geo2 = describeGeometry(built2.geometry, printers, design.code);
3185
+ lines2.push(
3186
+ `Part "${value}": ${built2.file} (${kB(built2.bytes ?? 0)}, rendered in ${duration(built2.report.durationMs)})`,
3187
+ ...geo2.lines.map((l) => ` ${l}`)
3188
+ );
3189
+ if (!built2.report.ok || built2.report.warnings.length)
3190
+ lines2.push(` ${formatValidation(built2.report)}`);
3191
+ data.push({ part: value, exported: true, path: built2.file, bytes: built2.bytes, ...geo2.data });
3192
+ } else {
3193
+ const empty = isEmptyModel(built2.report);
3194
+ lines2.push(
3195
+ empty ? `Part "${value}": not exported, the model is empty with part = "${value}". Draw that part when \`part\` has this value, or remove the value from the parameter's list.` : `Part "${value}": not exported.
3196
+ ${formatValidation(built2.report)}`
3197
+ );
3198
+ data.push({
3199
+ part: value,
3200
+ exported: false,
3201
+ ...empty ? { empty: true } : {},
3202
+ ...validationData(built2.report)
3203
+ });
3204
+ }
3205
+ }
3206
+ const done = data.filter((d) => d.exported).length;
3207
+ return result(
3208
+ [
3209
+ `Exported ${done} of ${values.length} parts of "${design.paths.slug}" version ${design.meta.version} as ${fmt.toUpperCase()}, one file per part:`,
3210
+ note,
3211
+ externalNote(design.external),
3212
+ ...lines2,
3213
+ done < values.length ? "Fix the parts that failed with update_design and export again." : void 0,
3214
+ HANDOFF
3215
+ ].filter(Boolean).join("\n"),
3216
+ {
3217
+ name: design.paths.slug,
3218
+ version: design.meta.version,
3219
+ format: fmt,
3220
+ exported: done === values.length,
3221
+ ...overrides.length ? { params } : {},
3222
+ parts: data
3223
+ }
3224
+ );
3225
+ }
3226
+ const out = fileName("");
3140
3227
  const built = await buildModel(bin, design, config, {
3141
3228
  out,
3142
3229
  format: fmt,
@@ -3144,7 +3231,6 @@ function registerExportTools(env) {
3144
3231
  title: design.paths.slug,
3145
3232
  signal: ctx.mcpReq.signal
3146
3233
  });
3147
- const note = overrides.length ? `Exported with parameter overrides: ${overrides.join(", ")}.` : void 0;
3148
3234
  if (!built.file || !built.geometry) {
3149
3235
  return result(
3150
3236
  [
@@ -3584,8 +3670,228 @@ function registerLearningTools(env) {
3584
3670
  );
3585
3671
  }
3586
3672
 
3587
- // src/tools/render.ts
3673
+ // src/tools/measure.ts
3674
+ import { mkdtemp as mkdtemp3, readFile as readFile5, rm as rm4 } from "fs/promises";
3675
+ import os6 from "os";
3676
+ import path13 from "path";
3588
3677
  import * as z11 from "zod/v4";
3678
+
3679
+ // src/mesh/probe.ts
3680
+ var AXES = {
3681
+ // [axis, u, v] with (u, v, axis) cyclic, so the projected orientation is the normal's sign.
3682
+ x: [0, 1, 2],
3683
+ y: [1, 2, 0],
3684
+ z: [2, 0, 1]
3685
+ };
3686
+ var JITTER_U = 1234567e-11;
3687
+ var JITTER_V = 7654321e-12;
3688
+ var SAME = 1e-6;
3689
+ function lineSegments(mesh, through, axis) {
3690
+ const [a, u, v] = AXES[axis];
3691
+ const pu = through[u] + JITTER_U;
3692
+ const pv = through[v] + JITTER_V;
3693
+ const t = mesh.triangles;
3694
+ const hits = [];
3695
+ for (let i2 = 0; i2 < mesh.count; i2++) {
3696
+ const o = i2 * 9;
3697
+ const au = t[o + u];
3698
+ const av = t[o + v];
3699
+ const bu = t[o + 3 + u];
3700
+ const bv = t[o + 3 + v];
3701
+ const cu = t[o + 6 + u];
3702
+ const cv = t[o + 6 + v];
3703
+ const area = (bu - au) * (cv - av) - (bv - av) * (cu - au);
3704
+ if (area === 0) continue;
3705
+ const w0 = (bu - pu) * (cv - pv) - (bv - pv) * (cu - pu);
3706
+ const w1 = (cu - pu) * (av - pv) - (cv - pv) * (au - pu);
3707
+ const w2 = (au - pu) * (bv - pv) - (av - pv) * (bu - pu);
3708
+ const inside = area > 0 ? w0 >= 0 && w1 >= 0 && w2 >= 0 : w0 <= 0 && w1 <= 0 && w2 <= 0;
3709
+ if (!inside) continue;
3710
+ const at = (w0 * t[o + a] + w1 * t[o + 3 + a] + w2 * t[o + 6 + a]) / area;
3711
+ hits.push({ at, delta: area > 0 ? -1 : 1 });
3712
+ }
3713
+ if (hits.length === 0) return [];
3714
+ hits.sort((p, q) => p.at - q.at);
3715
+ const segments = [];
3716
+ let winding = 0;
3717
+ let i = 0;
3718
+ while (i < hits.length) {
3719
+ const at = hits[i].at;
3720
+ while (i < hits.length && hits[i].at - at < SAME) winding += hits[i++].delta;
3721
+ const next = hits[i]?.at;
3722
+ if (next === void 0) break;
3723
+ const kind = winding > 0 ? "solid" : "empty";
3724
+ const last = segments[segments.length - 1];
3725
+ if (last && last.kind === kind) last.to = next;
3726
+ else segments.push({ kind, from: at, to: next });
3727
+ }
3728
+ while (segments[0]?.kind === "empty") segments.shift();
3729
+ while (segments[segments.length - 1]?.kind === "empty") segments.pop();
3730
+ return segments;
3731
+ }
3732
+ var SURFACE = 1e-3;
3733
+ function pointState(mesh, at) {
3734
+ const z14 = at[2];
3735
+ for (const s of lineSegments(mesh, at, "z")) {
3736
+ if (Math.abs(z14 - s.from) < SURFACE || Math.abs(z14 - s.to) < SURFACE) return "surface";
3737
+ if (z14 > s.from && z14 < s.to) return s.kind;
3738
+ }
3739
+ return "empty";
3740
+ }
3741
+
3742
+ // src/mesh/stl.ts
3743
+ var HEADER = 80;
3744
+ var RECORD = 50;
3745
+ var StlError = class extends Error {
3746
+ name = "StlError";
3747
+ };
3748
+ function parseBinaryStl(buf) {
3749
+ if (buf.length < HEADER + 4) throw new StlError("The STL file is too short.");
3750
+ const count = buf.readUInt32LE(HEADER);
3751
+ if (buf.length < HEADER + 4 + count * RECORD) {
3752
+ throw new StlError(`The STL file announces ${count} triangles but is too short for them.`);
3753
+ }
3754
+ const triangles = new Float32Array(count * 9);
3755
+ for (let i = 0; i < count; i++) {
3756
+ const base = HEADER + 4 + i * RECORD + 12;
3757
+ for (let j = 0; j < 9; j++) triangles[i * 9 + j] = buf.readFloatLE(base + j * 4);
3758
+ }
3759
+ return { triangles, count };
3760
+ }
3761
+
3762
+ // src/tools/measure.ts
3763
+ var vec3 = z11.tuple([z11.number(), z11.number(), z11.number()]);
3764
+ var label = z11.string().max(60).optional().describe('What is measured, e.g. "gap lid to rim".');
3765
+ var MAX_SEGMENTS = 40;
3766
+ var where = (p) => `(${p.map(mm).join(", ")})`;
3767
+ function formatSegments(segments) {
3768
+ if (segments.length === 0) return "misses the model";
3769
+ const shown2 = segments.slice(0, MAX_SEGMENTS).map((s) => `${s.kind} ${mm(s.to - s.from)} (${mm(s.from)} \u2026 ${mm(s.to)})`);
3770
+ const more = segments.length - MAX_SEGMENTS;
3771
+ return shown2.join(", ") + (more > 0 ? `, \u2026 ${more} more segments` : "");
3772
+ }
3773
+ function registerMeasureTools(env) {
3774
+ const { server, config } = env;
3775
+ server.registerTool(
3776
+ "measure_design",
3777
+ {
3778
+ title: "Measure a design",
3779
+ 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.",
3780
+ inputSchema: z11.object({
3781
+ name: designName,
3782
+ lines: z11.array(
3783
+ z11.object({
3784
+ through: vec3.describe("A point on the line [x, y, z] in mm."),
3785
+ axis: z11.enum(["x", "y", "z"]).describe("Direction of the line."),
3786
+ label
3787
+ })
3788
+ ).max(10).optional().describe("Up to 10 lines."),
3789
+ points: z11.array(z11.object({ at: vec3.describe("[x, y, z] in mm."), label })).max(20).optional().describe("Up to 20 points."),
3790
+ params: paramsArg
3791
+ }),
3792
+ annotations: READ
3793
+ },
3794
+ safe(async ({ name, lines: lines2, points, params }, ctx) => {
3795
+ if (!lines2?.length && !points?.length) {
3796
+ throw new UserError(
3797
+ 'Give at least one line or point, e.g. lines: [{through: [0, 0, 5], axis: "x", label: "wall"}].'
3798
+ );
3799
+ }
3800
+ const design = await readDesign(config, name);
3801
+ const { bin } = await env.openscad();
3802
+ const tmp = await mkdtemp3(path13.join(os6.tmpdir(), "openscad-mcp-measure-"));
3803
+ try {
3804
+ const built = await buildModel(bin, design, config, {
3805
+ out: path13.join(tmp, "model.stl"),
3806
+ format: "stl",
3807
+ params,
3808
+ signal: ctx.mcpReq.signal
3809
+ });
3810
+ const overrides = Object.keys(params ?? {});
3811
+ const head = [
3812
+ `Design "${design.paths.slug}", version ${design.meta.version} (full render, ${duration(built.report.durationMs)}).`,
3813
+ overrides.length ? `Measured with parameter overrides: ${overrides.join(", ")}.` : void 0,
3814
+ externalNote(design.external)
3815
+ ];
3816
+ const base = { name: design.paths.slug, version: design.meta.version };
3817
+ if (overrides.length && isEmptyModel(built.report)) {
3818
+ const clean2 = { ...built.report, ok: true, errors: [] };
3819
+ return result(
3820
+ [
3821
+ ...head,
3822
+ "Empty: with these parameter overrides the model has no geometry.",
3823
+ formatValidation(clean2)
3824
+ ].filter(Boolean).join("\n"),
3825
+ { ...base, empty: true, ...validationData(clean2) }
3826
+ );
3827
+ }
3828
+ if (!built.file || !built.geometry) {
3829
+ return result(
3830
+ [...head, formatValidation(built.report), "No geometry to measure."].filter(Boolean).join("\n"),
3831
+ { ...base, ...validationData(built.report) }
3832
+ );
3833
+ }
3834
+ const mesh = parseBinaryStl(await readFile5(built.file));
3835
+ const g = built.geometry;
3836
+ const out = [
3837
+ ...head.filter(Boolean),
3838
+ `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.`
3839
+ ];
3840
+ const measuredLines = (lines2 ?? []).map((l) => {
3841
+ const segments = lineSegments(mesh, l.through, l.axis);
3842
+ return { ...l, segments };
3843
+ });
3844
+ if (measuredLines.length) {
3845
+ out.push(
3846
+ "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):"
3847
+ );
3848
+ for (const l of measuredLines) {
3849
+ const name2 = l.label ? `"${l.label}" ` : "";
3850
+ out.push(
3851
+ `- ${name2}along ${l.axis.toUpperCase()} through ${where(l.through)}: ${formatSegments(l.segments)}`
3852
+ );
3853
+ }
3854
+ }
3855
+ const measuredPoints = (points ?? []).map((p) => ({ ...p, state: pointState(mesh, p.at) }));
3856
+ if (measuredPoints.length) {
3857
+ out.push("Points:");
3858
+ for (const p of measuredPoints) {
3859
+ const name2 = p.label ? `"${p.label}" ` : "";
3860
+ out.push(`- ${name2}${where(p.at)}: ${p.state === "surface" ? "on a surface" : p.state}`);
3861
+ }
3862
+ }
3863
+ out.push(formatValidation(built.report));
3864
+ const round2 = (n) => Math.round(n * 1e3) / 1e3;
3865
+ return result(out.join("\n"), {
3866
+ ...base,
3867
+ bounding_box: { min: g.min, max: g.max },
3868
+ lines: measuredLines.map((l) => ({
3869
+ ...l.label ? { label: l.label } : {},
3870
+ axis: l.axis,
3871
+ through: l.through,
3872
+ segments: l.segments.map((s) => ({
3873
+ kind: s.kind,
3874
+ from: round2(s.from),
3875
+ to: round2(s.to),
3876
+ length: round2(s.to - s.from)
3877
+ }))
3878
+ })),
3879
+ points: measuredPoints.map((p) => ({
3880
+ ...p.label ? { label: p.label } : {},
3881
+ at: p.at,
3882
+ state: p.state
3883
+ })),
3884
+ ...validationData(built.report)
3885
+ });
3886
+ } finally {
3887
+ await rm4(tmp, { recursive: true, force: true });
3888
+ }
3889
+ })
3890
+ );
3891
+ }
3892
+
3893
+ // src/tools/render.ts
3894
+ import * as z12 from "zod/v4";
3589
3895
  var DEFAULT_VIEWS = ["iso", "front", "top", "right"];
3590
3896
  function registerRenderTools(env) {
3591
3897
  const { server, config } = env;
@@ -3594,14 +3900,14 @@ function registerRenderTools(env) {
3594
3900
  {
3595
3901
  title: "Render views",
3596
3902
  description: 'OpenSCAD: renders PNG images of a design from the chosen sides (iso, iso_back, front, back, left, right, top, bottom; default iso, front, top, right) and returns them with the console output. Mode "render" (the default when OpenSCAD has the Manifold backend) shows the exact geometry that would be exported. Mode "preview" is OpenSCAD\'s quick OpenCSG view with $preview = true; it can show holes or missing faces that are not in the model. `params` overrides parameters for this render only, without changing the file. `section` cuts the model open at a plane (always rendered geometry): it removes the part in front of (y < at), right of (x > at) or above (z > at) the plane, so the front, right or top view looks at the cut face; default views with a section: that view and iso.',
3597
- inputSchema: z11.object({
3903
+ inputSchema: z12.object({
3598
3904
  name: designName,
3599
- views: z11.array(z11.enum(VIEW_NAMES)).min(1).max(8).optional().describe("Sides to render. Default: iso, front, top, right."),
3600
- mode: z11.enum(["render", "preview"]).optional().describe('Default: "render" with the Manifold backend, otherwise "preview".'),
3905
+ views: z12.array(z12.enum(VIEW_NAMES)).min(1).max(8).optional().describe("Sides to render. Default: iso, front, top, right."),
3906
+ mode: z12.enum(["render", "preview"]).optional().describe('Default: "render" with the Manifold backend, otherwise "preview".'),
3601
3907
  params: paramsArg,
3602
- section: z11.object({
3603
- axis: z11.enum(["x", "y", "z"]).describe("Normal of the cutting plane."),
3604
- at: z11.number().optional().describe("Position of the plane on that axis in mm. Default: 0.")
3908
+ section: z12.object({
3909
+ axis: z12.enum(["x", "y", "z"]).describe("Normal of the cutting plane."),
3910
+ at: z12.number().optional().describe("Position of the plane on that axis in mm. Default: 0.")
3605
3911
  }).optional().describe(
3606
3912
  'Cut the model open, e.g. {axis: "y", at: 0} to see a fit, a thread or a wall in profile.'
3607
3913
  )
@@ -3659,7 +3965,7 @@ function registerRenderTools(env) {
3659
3965
  }
3660
3966
 
3661
3967
  // src/tools/versions.ts
3662
- import * as z12 from "zod/v4";
3968
+ import * as z13 from "zod/v4";
3663
3969
  function checkValue(p, value) {
3664
3970
  const expected = Array.isArray(p.initial) ? "list" : p.type;
3665
3971
  const got = Array.isArray(value) ? "list" : typeof value;
@@ -3684,7 +3990,7 @@ function registerVersionTools(env) {
3684
3990
  {
3685
3991
  title: "List versions",
3686
3992
  description: "OpenSCAD: lists the saved versions of a design, newest first, with time, origin (create, update, set-parameters, restore, external-edit), note and size. Every change through this server is a version; changes typed in OpenSCAD's editor are recorded as external-edit, with the changed values and the number of other changed lines.",
3687
- inputSchema: z12.object({ name: designName }),
3993
+ inputSchema: z13.object({ name: designName }),
3688
3994
  annotations: READ
3689
3995
  },
3690
3996
  safe(async ({ name }) => {
@@ -3708,10 +4014,10 @@ function registerVersionTools(env) {
3708
4014
  {
3709
4015
  title: "Restore a version",
3710
4016
  description: "OpenSCAD: makes an earlier version the current code of a design again. The restored code is saved as a new version, so the versions in between stay available. Validates the result and returns an image like update_design.",
3711
- inputSchema: z12.object({
4017
+ inputSchema: z13.object({
3712
4018
  name: designName,
3713
- version: z12.number().int().positive().describe("The version to bring back (see list_versions)."),
3714
- preview: z12.boolean().optional().describe("Attach an image of the restored model. Default: true."),
4019
+ version: z13.number().int().positive().describe("The version to bring back (see list_versions)."),
4020
+ preview: z13.boolean().optional().describe("Attach an image of the restored model. Default: true."),
3715
4021
  views: previewViewsArg
3716
4022
  }),
3717
4023
  annotations: WRITE
@@ -3743,10 +4049,10 @@ function registerVersionTools(env) {
3743
4049
  {
3744
4050
  title: "Set parameters",
3745
4051
  description: "OpenSCAD: changes the default values of a design's parameters in the file (the plain assignments at the top that OpenSCAD's Customizer also offers) and saves the result as a new version. Only the values change; code and comments stay as they are. Called without `params` it lists the parameters with type, current value, range and description.",
3746
- inputSchema: z12.object({
4052
+ inputSchema: z13.object({
3747
4053
  name: designName,
3748
4054
  params: paramsArg,
3749
- preview: z12.boolean().optional().describe("Attach an image of the changed model. Default: true."),
4055
+ preview: z13.boolean().optional().describe("Attach an image of the changed model. Default: true."),
3750
4056
  views: previewViewsArg
3751
4057
  }),
3752
4058
  annotations: WRITE
@@ -3813,7 +4119,7 @@ var INSTRUCTIONS = `OpenSCAD MCP: you write parametric OpenSCAD code for 3D-prin
3813
4119
  Workflow
3814
4120
  1. Before the first design of a conversation, call get_guidelines (design rules, code structure, installed libraries).
3815
4121
  2. create_design with complete code. The result carries OpenSCAD's errors and warnings and, when the code is valid, an image of the rendered model.
3816
- 3. Look at the image; \`views\` on a save or render_views shows other sides, and render_views with \`section\` cuts the model open. Fix errors and visual problems with update_design, preferring \`edits\` so working code stays untouched.
4122
+ 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.
3817
4123
  4. open_in_openscad shows the model in the user's OpenSCAD window, which then follows every change.
3818
4124
  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.
3819
4125
  6. Size changes that are parameters go through set_parameters. analyze_design gives the real size and the fit on the user's printers.
@@ -3874,6 +4180,7 @@ function createServer({ config, guiSystem }) {
3874
4180
  registerGuiTools(env);
3875
4181
  registerVersionTools(env);
3876
4182
  registerAnalyzeTools(env);
4183
+ registerMeasureTools(env);
3877
4184
  registerExportTools(env);
3878
4185
  registerLearningTools(env);
3879
4186
  registerResources(env);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openscad-mcp-v2",
3
- "version": "1.1.0",
3
+ "version": "1.2.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",
@@ -53,6 +53,7 @@
53
53
  ],
54
54
  "scripts": {
55
55
  "build": "tsup",
56
+ "bundle": "tsx scripts/bundle.ts",
56
57
  "dev": "tsx src/index.ts",
57
58
  "start": "node dist/index.js",
58
59
  "typecheck": "tsc --noEmit",