bambu-printer-mcp 1.1.88 → 1.1.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1274,7 +1274,7 @@ Check only by default. `{"install":true}` installs a pinned isolated environment
1274
1274
 
1275
1275
  #### cad_run
1276
1276
 
1277
- Read the `cad_design` prompt first. Supply `script` or a saved `script_path`, `output_dir`, and `name`. Scripts declare literal `P = {...}` parameters and a `build()` function returning a build123d shape. One later call with `script_path` and `parameters` changes a dimension and rebuilds. Each run creates a new subfolder and preserves its source/parameter checkpoint, even on failure. The result contains STL/STEP paths, measured geometry, validity checks, six views and a contact sheet.
1277
+ Read the `cad_design` prompt first. Supply `script` or a saved `script_path`, `output_dir`, and `name`. Scripts declare literal `P = {...}` parameters and a `build()` function returning a build123d shape. One later call with `script_path` and `parameters` changes a dimension and rebuilds. Each run creates a new subfolder and preserves its source/parameter checkpoint, even on failure. The result contains STL/STEP paths, measured geometry, validity checks, six orthographic views, a perspective view and a contact sheet with the perspective view large beside the six.
1278
1278
 
1279
1279
  Explicit `inputs: [{"name": "scan", "path": "/allowed/scan.stl"}]` snapshots the files a script may read as `INPUTS["scan"]`. For a mesh-only edit, use `mode: "mesh"` and return `trimesh.Trimesh`: it exports and validates STL plus renders, with `step: null` and a clear reason. For captured meshes, the injected `load_scan` helper takes explicit source units and an up-axis, converts coordinates to millimetres/Z-up, and grounds the mesh without fitting its size. Cleanup choices and labels belong to the caller’s rules; the MCP supplies execution, mesh libraries, checks and renders.
1280
1280
 
@@ -1284,6 +1284,10 @@ Runs wait for the environment's execution slot up to their own total timeout and
1284
1284
 
1285
1285
  Unchanged declared inputs reuse immutable content-hash bundles, with `snapshot_bytes_added` and `snapshot_bytes_reused` in the result. Keep the referenced `.cad-inputs` bundles with saved designs. Previews now use depth cues and feature edges to reveal windows and recesses without a heavy renderer.
1286
1286
 
1287
+ #### cad_examples
1288
+
1289
+ The code engine's cookbook: twelve worked build123d designs from simple to complex (cable clip, wall hook, knurled knob, phone stand, swept headphone hook, lofted tool handle, threaded jar, bag clip, hinged box, bistable clicker, chainmail, trigger capo), each modelled on the best bought version of the thing, with its concept, the published sizes it used and its script. Without arguments it lists them with the pattern each shows; with `name` it returns one record and script. The `cad_design` prompt names every example in one line, so a design worker reads the one that works like its request and adapts the pattern. Read-only; needs no CAD runtime. The scripts are in `src/cad/examples/`.
1290
+
1287
1291
  #### cad_check_fit
1288
1292
 
1289
1293
  Check a model and reference STL with an explicit rigid transform. Returns interference volume and minimum surface gap, without quietly scaling a scan. Open/nonmanifold meshes are refused. A gap of zero includes intentional floor contact, so choose clearance checks to match the interface you actually want to measure.
@@ -1514,6 +1518,7 @@ The server carries manufacturing judgment for agents that design or edit a model
1514
1518
  - `fdm_slicing` -- for every design or model-editing task, next to `fdm_design`: how this server's configured slicer (`SLICER_TYPE`) orients a model and generates supports, and how to check a choice with a checkpoint `slice_stl`. Its text follows the slicer: Bambu Studio's auto-orient and `enable_support`, or plainly that a slicer here doesn't orient or take support settings.
1515
1519
  - `guidance://fdm/capability-guidance` (resource) -- planning bands and sources for bridges and overhangs, for when one is consequential and there is no sufficiently specific measured capability for the printer, material and profile.
1516
1520
  - `guidance://fdm/fit-by-function` (resource) -- the same text as the `fdm_fit` prompt, in resource form for clients that read resources.
1521
+ - `design_guidance` (tool) -- the same on-demand texts by name (`fdm_fit`, `fdm_flexures`, `fdm_assembly`, `fdm_multicolor`, `fdm_after_slice`, `fdm_capability`), for a design worker that is given tools but not prompts or resources. `fdm_design` and `cad_design` tell such a worker to read `fdm_fit` and `fdm_flexures` this way when they apply. Read-only.
1517
1522
 
1518
1523
  mcp-3D-printer-server serves the same guidance.
1519
1524
 
@@ -6,6 +6,7 @@ export declare const CAD_CAPABILITY: {
6
6
  readonly setup: "cad_setup";
7
7
  readonly run: "cad_run";
8
8
  readonly checkFit: "cad_check_fit";
9
+ readonly examples: "cad_examples";
9
10
  readonly prompt: "cad_design";
10
11
  };
11
12
  export declare const CAD_TOOLS: ({
@@ -298,6 +299,89 @@ export declare const CAD_TOOLS: ({
298
299
  required: string[];
299
300
  })[];
300
301
  };
302
+ } | {
303
+ name: string;
304
+ description: string;
305
+ inputSchema: {
306
+ type: "object";
307
+ properties: {
308
+ name: {
309
+ type: string;
310
+ description: string;
311
+ maxLength?: undefined;
312
+ };
313
+ install?: undefined;
314
+ inputs?: undefined;
315
+ mode?: undefined;
316
+ script?: undefined;
317
+ script_path?: undefined;
318
+ parameters?: undefined;
319
+ output_dir?: undefined;
320
+ final?: undefined;
321
+ timeout_ms?: undefined;
322
+ model?: undefined;
323
+ reference?: undefined;
324
+ transform?: undefined;
325
+ clearance_mm?: undefined;
326
+ };
327
+ additionalProperties: boolean;
328
+ required?: undefined;
329
+ };
330
+ outputSchema: {
331
+ type: "object";
332
+ anyOf: ({
333
+ type: string;
334
+ properties: {
335
+ status: {
336
+ type: string;
337
+ const: string;
338
+ };
339
+ code: {
340
+ type: string;
341
+ enum: ("cad-uv-missing" | "cad-data-volume-refused" | "cad-setup-busy" | "cad-operation-busy" | "cad-queue-timeout" | "cad-not-ready" | "cad-confinement-unavailable" | "cad-disabled" | "cad-failed")[];
342
+ };
343
+ message: {
344
+ type: string;
345
+ };
346
+ tool: {
347
+ type: string;
348
+ };
349
+ retryable: {
350
+ type: string;
351
+ };
352
+ suggestion: {
353
+ type: string;
354
+ };
355
+ storage: {
356
+ type: string;
357
+ properties: {
358
+ expected_download_bytes: {
359
+ type: string;
360
+ };
361
+ expected_installed_bytes: {
362
+ type: string;
363
+ };
364
+ installed_bytes: {
365
+ type: string[];
366
+ };
367
+ measurement: {
368
+ type: string;
369
+ const: string;
370
+ };
371
+ measured_at: {
372
+ type: string;
373
+ };
374
+ };
375
+ required: string[];
376
+ };
377
+ };
378
+ required: string[];
379
+ } | {
380
+ type: string;
381
+ properties: Record<string, unknown>;
382
+ required: string[];
383
+ })[];
384
+ };
301
385
  } | {
302
386
  name: string;
303
387
  description: string;
@@ -1,4 +1,5 @@
1
1
  import { CAD_REFUSAL_CODES } from "./refusal.js";
2
+ import { cadExampleLines } from "./examples.js";
2
3
  /** cad/1 is an optional engine owned by the printer MCP. Readiness comes from cad_status, not the capability. */
3
4
  export function cadEnabled(env = process.env) {
4
5
  return !["0", "false", "off"].includes(env.CAD_ENABLED?.trim().toLowerCase() ?? "");
@@ -9,6 +10,7 @@ export const CAD_CAPABILITY = {
9
10
  setup: "cad_setup",
10
11
  run: "cad_run",
11
12
  checkFit: "cad_check_fit",
13
+ examples: "cad_examples",
12
14
  prompt: "cad_design",
13
15
  };
14
16
  const storage = {
@@ -35,6 +37,7 @@ const status = {
35
37
  build123d: { type: "string" },
36
38
  platform: { type: "string" },
37
39
  error: { type: "string" },
40
+ reverified: { type: "string" },
38
41
  };
39
42
  const failure = {
40
43
  type: "object",
@@ -62,7 +65,7 @@ const timeout = {
62
65
  export const CAD_TOOLS = [
63
66
  {
64
67
  name: "cad_status",
65
- description: "Read the optional code-CAD runtime's last verified readiness and pinned version, without starting Python or installing anything.",
68
+ description: "Read the optional code-CAD runtime's readiness and pinned version. Never installs or downloads anything. When only this MCP's own engine files changed since the runtime was last verified (an update) and the installed runtime still matches the pinned lock exactly, it re-runs setup's confined build, STL and STEP round trip (about 15 to 20 seconds) and reports ready; a changed runtime still needs cad_setup with install: true.",
66
69
  inputSchema: {
67
70
  type: "object",
68
71
  properties: {},
@@ -100,7 +103,7 @@ export const CAD_TOOLS = [
100
103
  },
101
104
  {
102
105
  name: "cad_run",
103
- description: "Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six renders and a contact sheet; valid geometry is not a physical-fit or motion proof.",
106
+ description: "Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six orthographic renders, a perspective view and a contact sheet, the closest approach between every pair of solids (bodies), problems, and what was checked and not checked; valid means only that the exported geometry is sound, never that the part fits, holds, moves or prints.",
104
107
  inputSchema: {
105
108
  type: "object",
106
109
  properties: {
@@ -189,6 +192,17 @@ export const CAD_TOOLS = [
189
192
  type: "object",
190
193
  additionalProperties: { type: ["boolean", "null"] },
191
194
  },
195
+ bodies: {
196
+ type: "object",
197
+ description: "Solid mode: near pairs of solids screened on tessellations and measured exactly on the STEP where the screen cannot clear them, against a print-in-place clearance from P.print_in_place_clearance_mm or 0.3 mm (touching or overlap only when P.print_in_place is false); touching or overlapping pairs, pairs under the clearance, pairs only screened, solids below the print plate (Z = 0) or above it with no solid under them that reaches it, and labelled bodies that are not exactly one solid.",
198
+ },
199
+ problems: {
200
+ type: "array",
201
+ items: { type: "string" },
202
+ description: "Defects found by the checks that valid does not cover (fused or too-close bodies, a severed body, a solid below the plate or starting in mid-air, pairs not measured). Each kind lists up to eight, then a count of the rest. Empty when none were found, which is not a pass on anything listed in not_checked.",
203
+ },
204
+ checked: { type: "array", items: { type: "string" } },
205
+ not_checked: { type: "array", items: { type: "string" } },
192
206
  renders: { type: "object", additionalProperties: { type: "string" } },
193
207
  seconds: { type: "number" },
194
208
  }, [
@@ -211,6 +225,44 @@ export const CAD_TOOLS = [
211
225
  "renders",
212
226
  ]),
213
227
  },
228
+ {
229
+ name: "cad_examples",
230
+ description: "The code engine's cookbook: worked build123d designs from simple to complex, each modelled on the best bought version of the thing, with its concept, published sizes and script. Without arguments, lists them (name, title, the pattern each shows, the product it is modelled on). With name, returns that example's record and full script to adapt. Read-only; starts no process.",
231
+ inputSchema: {
232
+ type: "object",
233
+ properties: {
234
+ name: {
235
+ type: "string",
236
+ description: "An example's name from the list; omit to list them.",
237
+ },
238
+ },
239
+ additionalProperties: false,
240
+ },
241
+ outputSchema: output({
242
+ examples: {
243
+ type: "array",
244
+ items: {
245
+ type: "object",
246
+ properties: {
247
+ name: { type: "string" },
248
+ title: { type: "string" },
249
+ pattern: { type: "string" },
250
+ modelled_on: { type: "string" },
251
+ },
252
+ required: ["name", "title", "pattern"],
253
+ },
254
+ },
255
+ usage: { type: "string" },
256
+ name: { type: "string" },
257
+ title: { type: "string" },
258
+ pattern: { type: "string" },
259
+ modelled_on: { type: "string" },
260
+ published_sizes: { type: "string" },
261
+ concept: { type: "string" },
262
+ what_makes_this_good: { type: "string" },
263
+ script: { type: "string" },
264
+ }, []),
265
+ },
214
266
  {
215
267
  name: "cad_check_fit",
216
268
  description: "Check two allowed watertight manifold STL meshes in millimetres. Applies only the explicit rigid transform to reference: XYZ rotation in degrees about the origin, then translation. Never silently scales a scan. Reports Boolean interference volume and minimum surface gap (zero on contact/intersection), plus a clearance verdict; intentional support contact also has zero gap. Fails rather than guessing for open meshes or excessive triangle workload.",
@@ -278,13 +330,18 @@ export const CAD_DESIGN_PROMPT = {
278
330
  title: "Parametric code-CAD design",
279
331
  description: "MCP-owned rules for headless build123d designs and one-call parameter revisions.",
280
332
  text: `Use code-CAD for dimensioned functional designs and parameter edits. Build in millimetres with build123d 0.13.0; the MCP owns the Python environment, execution, export, validation and rendering. Check cad_status and use cad_setup with install: true when needed. No Blender, Fusion, network or printer access is available to your script.
281
- Declare exactly one top-level P = {...} dictionary of JSON-compatible literal named parameters. Put every functional dimension in P; derive geometry from P. Define build() to return a build123d Shape or Compound of disjoint solid parts. Do not put construction or exports in a __main__ block: cad_run calls build() and exports the result. Imports, functions and derived P entries are fine. Parameters are applied to the literal defaults before derived expressions execute. For solid designs without inputs, the script and parameters file alone reconstruct it. For input-dependent designs, declare inputs as an array of {name, path} files: cad_run snapshots only those allowed files, exposes INPUTS[alias] to your script, and saves an inputs manifest. Retain the snapshots too for recovery; subsequent script_path edits reuse them unless inputs is explicitly supplied. No other personal files are readable. For a mesh-only experiment use mode: "mesh" and return a trimesh.Trimesh from build(); it exports and checks STL plus six renders, with step: null and an explicit reason. It does not manufacture a fake parametric STEP or promise scan-cleanup capability.
333
+ Form first: build the product's shape, not a profile pushed up. Before any geometry, write the concept in a few lines: the bought product you are following, its mechanism, the load path, the print orientation and why. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
334
+ Worked examples: cad_examples lists this engine's cookbook (each modelled on a bought product, with its concept, published sizes and script) and returns one script by name. When the request works like one of these, read that example first and adapt its pattern, never its sizes:
335
+ ${cadExampleLines()}
336
+ What the cookbook taught about this engine: return several bodies as Compound([a, b]); bodies that touch or overlap come back invalid, so leave a real gap (0.2 mm or more) or union them, and check that solid_count equals the bodies you intend (for a print-in-place mechanism that count is the first evidence nothing fused). fillet() often fails on the edges of an outline unioned from many curves, where chamfer() usually succeeds: fillet or chamfer simple bodies before the booleans that complicate them, and when a chamfer fails too, apply it to the plain body and union the details on afterwards. Do not round a sketch by growing and shrinking it with offset(): the solid looks right and its STEP comes back with no solids (the step_solids check fails). A whole Sphere() exports open at its poles: trim them (Sphere(r) & Box(2 * r, 2 * r, 2 * r - 0.1)). One fillet of the same radius over every edge of a box can export open: fillet in two passes with different radii. A model with moving parts takes a pose parameter: the assembled pose to judge it, the print plate to make it.
337
+ Declare exactly one top-level P = {...} dictionary of JSON-compatible literal named parameters. Put every functional dimension in P; derive geometry from P. Define build() to return a build123d Shape or Compound of disjoint solid parts. When a design has separate bodies (print-in-place parts, a captive wheel, links of a fabric), return Compound(children=[...]) with a label on each body: cad_run then checks that each labelled body is exactly one solid, so a piece cut off one body cannot hide behind two bodies fused into one. Near pairs of solids are screened and, where the screen cannot clear them, measured exactly against P["print_in_place_clearance_mm"] when you declare it, else 0.3 mm. If the bodies are shown assembled rather than printed in place (a shaft in its hole at a fit clearance), set P["print_in_place"] = False: only touching or overlap is then a problem. Export in print orientation with the plate at Z = 0: a solid below it, or above it with nothing under it that reaches it, is a problem. Do not put construction or exports in a __main__ block: cad_run calls build() and exports the result. Imports, functions and derived P entries are fine. Parameters are applied to the literal defaults before derived expressions execute. For solid designs without inputs, the script and parameters file alone reconstruct it. For input-dependent designs, declare inputs as an array of {name, path} files: cad_run snapshots only those allowed files, exposes INPUTS[alias] to your script, and saves an inputs manifest. Retain the snapshots too for recovery; subsequent script_path edits reuse them unless inputs is explicitly supplied. No other personal files are readable. For a mesh-only experiment use mode: "mesh" and return a trimesh.Trimesh from build(); it exports and checks STL plus the same renders, with step: null and an explicit reason. It does not manufacture a fake parametric STEP or promise scan-cleanup capability.
282
338
  Call cad_run with script, output_dir and a plain name. It saves <name>.py and <name>.parameters.json before running, then exports <name>.stl and <name>.step in a fresh subfolder. For an edit, one cad_run with script_path pointing to the earlier .py, parameters containing just the changed dimension, output_dir and name regenerates it without resending the script. Existing parameter values are retained; unknown names and type changes are refused. A killed run can be retried from its checkpoint in a new workspace; mutations are never replayed automatically.
283
339
  Captured mesh preparation: load_scan(name, source_units="m" or "mm", up_axis="x"|"-x"|"y"|"-y"|"z"|"-z", ground=True) is provided to build(). Name must be a declared input. Declare source units and the object's usage-up axis explicitly: the helper converts metres to millimetres, applies a rigid up-axis rotation and translates the lowest Z to zero; it never guesses scale or fits to calipers. Geometry/texture references must be declared inputs too; snapshots preserve distinct original filenames. Exports must be millimetres, Z up, in the orientation the object is used.
284
340
  Fit reference workflow: return load_scan("scan", source_units="m", up_axis="y") from build() in mode: "mesh" to export an unchanged, prepared reference STL for cad_check_fit. Declare every linked OBJ/MTL/texture asset. If you crop, simplify, fill, or otherwise alter this reference, report exactly what you excluded/changed and that the fit check proves only that reduced reference in the stated pose. A fit check against a scan is information; it must never resize or override an interface specified by measured dimensions. Keep those measured interfaces and report the discrepancy.
285
341
  Result selection and edits: set final: true only on the result you select. cad-result.json in each immediate run folder is protected from script writes and retains final, completed_at, lineage_id (source hash), full checks and artifact paths; clients can discover the latest completed final record after restart without rebuilding. Final is a selection marker, not a replacement for valid/checks. Queued calls may expire with cad-queue-timeout before dispatch; do not automatically replay. Unchanged declared files reuse a read-only content-addressed bundle under output_dir/.cad-inputs, preserving filenames and restricting reads to that bundle. Keep this shared cache with the saved runs.
286
342
  Mesh cleanup workflow: return a trimesh.Trimesh in mode: "mesh". Load the prepared mesh, fit needed geometry with NumPy/SciPy, rebuild regular sections/features with build123d or manifold3d CrossSection/extrusion/revolve, and combine meshes with manifold3d booleans. scikit-image supplies marching cubes for voxel/SDF work; Shapely supplies planar operations; Pillow supplies image/texture reads. Keep numeric choices in P and regenerate from declared inputs. Validate closure, winding, manifold status, dimensions and all six views using cad_run. What to regularise, infer, preserve or label comes from the caller's cleanup rules, not this engine prompt.
287
- The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, six orthographic renders (front, back, left, right, top, bottom) and contact sheet. Inspect all six; revise visible defects. A valid mesh or nominal parameter does not prove the requested dimension: measure the actual exported interfaces. Use cad_check_fit on a model and reference STL with an explicit rigid transform; report raw-scan interference and minimum gap. Calipers are authoritative but disagreement with a scan is unresolved measurement evidence, not permission to silently rescale it. Check assembly/insertion paths and actual articulated poses, not sums of local joint limits or reference points alone. Printing, clearance under load, supports and motion need separate evidence.
343
+ Captured scan touch-up: t = scan_touchup(load_scan("scan", source_units="m", up_axis="y", ground=False), colour="colour", normal="normal", edge_mm=0.4) takes a textured capture (declare its OBJ, MTL and colour and normal map PNGs as inputs; pass the map aliases). It removes loose pieces and spikes, closes holes and refines to edge_mm without shrinking the body. t.regions() prints the colour regions (id, colour, area, size, flatness; 0 is the body) to build.log and saves regions.png in the run folder: read both, then name regions by id in the same scan and edge_mm. t.flatten(ids, shape="plane" or "curved"), t.bead(id, diameter_mm, proud_mm), t.cord(id, diameter_mm, proud_mm) (a cord follows its region's own curve) and t.seat(height_mm) record steps; return t.mesh(relief_gain=1.0), which adds the normal map's measured relief, applies the steps with manifold3d and prints its changes. Keep relief_gain at 1: a larger gain amplifies the map's noise, not stitches. When the caller's rules call for a textile's relief the scan missed (fabric, knit, crochet the photos show raised), t.texture_relief(height_mm, regions=None) raises its stitch pattern from the colour texture on the textile only (never flattened, beaded or corded regions); about 0.6 to 1.0 mm peak to peak prints visibly. It is off unless called: never for hard objects, printed graphics or labels.
344
+ The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, bodies (closest approach between solids, contact with the print plate at Z = 0, labelled bodies that are not one solid), problems, checked and not_checked, six orthographic renders (front, back, left, right, top, bottom), a perspective view from the front right and above, and a contact sheet with the perspective view large beside the six. Fix every entry in problems before selecting a result; an empty problems list proves nothing listed in not_checked. Judge the form from the perspective view first: would a person recognise the product and want it? Then inspect all six; revise visible defects. A valid mesh or nominal parameter does not prove the requested dimension: measure the actual exported interfaces. Use cad_check_fit on a model and reference STL with an explicit rigid transform; report raw-scan interference and minimum gap. Calipers are authoritative but disagreement with a scan is unresolved measurement evidence, not permission to silently rescale it. Check assembly/insertion paths and actual articulated poses, not sums of local joint limits or reference points alone. Printing, clearance under load, supports and motion need separate evidence.
288
345
  Fit, flexure and thread parameters: put each interface's nominal size, its source (measured, published, or assumed), the print correction, and the design fit in P as separate named values, so a fit report revises one number without resending the script. Model every dimension you claim: a parameter the geometry never uses (a wallet or case width that no cut or wall reads) is a defect; use it or remove it. Shape flexures so their bending lies in the layer plane of the exported print orientation, with the stroke, preload, and hard-stop gap as P values; build the stopped pose as well as the rest pose when checking. Model printed threads as explicit coarse geometry with the same pitch on both sides and clearance as a radial P offset; never scale a screw to clear its hole.
289
- Check insertion and articulated poses with cad_check_fit against each object state that matters (the bare product, the product in its case, and the case with its attachment as its own reference envelope), including the widest section on the way in. Report interference and minimum gap per state. In your summary, attach each "fits", "holds", and "prints without supports" claim to the check or slice number that shows it; a valid flag alone shows none of them. Apply fdm_design and fdm_slicing too, with fdm_fit and fdm_flexures when they apply; never invoke a printer as part of constructing CAD.`,
346
+ Check insertion and articulated poses with cad_check_fit against each object state that matters (the bare product, the product in its case, and the case with its attachment as its own reference envelope), including the widest section on the way in. Report interference and minimum gap per state. In your summary, attach each "fits", "holds", and "prints without supports" claim to the check or slice number that shows it; a valid flag alone shows none of them. Apply fdm_design and fdm_slicing too. When a part meets a real object apply fdm_fit, and when it flexes, grips, snaps or springs apply fdm_flexures: if they were not attached, read them with the design_guidance tool before choosing that fit or spring. Never invoke a printer as part of constructing CAD.`,
290
347
  };
@@ -0,0 +1,22 @@
1
+ declare const FIELDS: {
2
+ readonly Pattern: "pattern";
3
+ readonly "Modelled on": "modelled_on";
4
+ readonly "Published sizes used": "published_sizes";
5
+ readonly Concept: "concept";
6
+ readonly "What makes this good": "what_makes_this_good";
7
+ };
8
+ type Field = (typeof FIELDS)[keyof typeof FIELDS];
9
+ export type CadExample = {
10
+ name: string;
11
+ title: string;
12
+ script: string;
13
+ } & Record<Field, string>;
14
+ /** Simplest first: the order the list and the prompt present them in. */
15
+ export declare const CAD_EXAMPLE_ORDER: string[];
16
+ /** Every example on disk, in cookbook order (unlisted files last, by name). Empty when the folder is missing. */
17
+ export declare function cadExamples(): CadExample[];
18
+ /** One line per example for the cad_design prompt: "name: what it is; the pattern it shows". */
19
+ export declare function cadExampleLines(): string;
20
+ /** cad_examples: without a name, the list; with one, that example's record and script. */
21
+ export declare function cadExamplesTool(args: Record<string, unknown>): Record<string, unknown>;
22
+ export {};
@@ -0,0 +1,81 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ /**
5
+ * The code engine's cookbook: worked build123d designs, each modelled on the best bought version of the thing, kept as
6
+ * plain scripts in src/cad/examples/. A design worker reaches them only through this MCP: the cad_design prompt names
7
+ * each pattern in one line, and the read-only cad_examples tool returns one script on request, so the prompt pays a
8
+ * line per example instead of a script per example.
9
+ *
10
+ * A script's header (its docstring) is the record: title on the first line, then "Pattern:", "Modelled on:",
11
+ * "Published sizes used:", "Concept:" and "What makes this good:".
12
+ */
13
+ const DIR = fileURLToPath(new URL("../../src/cad/examples/", import.meta.url));
14
+ const FIELDS = {
15
+ "Pattern": "pattern",
16
+ "Modelled on": "modelled_on",
17
+ "Published sizes used": "published_sizes",
18
+ "Concept": "concept",
19
+ "What makes this good": "what_makes_this_good",
20
+ };
21
+ /** Simplest first: the order the list and the prompt present them in. */
22
+ export const CAD_EXAMPLE_ORDER = [
23
+ "cable_clip", "wall_hook", "knurled_knob", "phone_stand", "swept_hook", "loft_handle", "threaded_jar",
24
+ "bag_clip", "hinged_box", "bistable_clicker", "chainmail", "trigger_capo",
25
+ ];
26
+ function parse(name, script) {
27
+ const header = /^\s*"""([\s\S]*?)"""/.exec(script)?.[1] ?? "";
28
+ const lines = header.split("\n");
29
+ const example = { name, title: (lines.shift() ?? name).trim(), script };
30
+ let field;
31
+ for (const line of lines) {
32
+ const start = /^([A-Z][A-Za-z ]+):\s*(.*)$/.exec(line);
33
+ const key = start && FIELDS[start[1]];
34
+ if (start && key) {
35
+ field = key;
36
+ example[key] = start[2].trim();
37
+ }
38
+ else if (field && line.trim())
39
+ example[field] += " " + line.trim();
40
+ }
41
+ for (const key of Object.values(FIELDS))
42
+ example[key] ?? (example[key] = "");
43
+ return example;
44
+ }
45
+ let cache;
46
+ /** Every example on disk, in cookbook order (unlisted files last, by name). Empty when the folder is missing. */
47
+ export function cadExamples() {
48
+ if (cache)
49
+ return cache;
50
+ let files = [];
51
+ try {
52
+ files = fs.readdirSync(DIR).filter((f) => /^[a-z0-9_]+\.py$/.test(f));
53
+ }
54
+ catch { /* no cookbook shipped */ }
55
+ const rank = (n) => { const i = CAD_EXAMPLE_ORDER.indexOf(n); return i < 0 ? CAD_EXAMPLE_ORDER.length : i; };
56
+ cache = files.map((f) => parse(f.slice(0, -3), fs.readFileSync(path.join(DIR, f), "utf8")))
57
+ .sort((a, b) => rank(a.name) - rank(b.name) || a.name.localeCompare(b.name));
58
+ return cache;
59
+ }
60
+ /** One line per example for the cad_design prompt: "name: what it is; the pattern it shows". */
61
+ export function cadExampleLines() {
62
+ return cadExamples().map((e) => `${e.name}: ${e.title}; ${e.pattern}`).join("\n");
63
+ }
64
+ /** cad_examples: without a name, the list; with one, that example's record and script. */
65
+ export function cadExamplesTool(args) {
66
+ const extra = Object.keys(args).filter((k) => k !== "name");
67
+ if (extra.length)
68
+ throw new Error("cad_examples accepts only name.");
69
+ const all = cadExamples();
70
+ if (args.name === undefined)
71
+ return {
72
+ examples: all.map(({ name, title, pattern, modelled_on }) => ({ name, title, pattern, modelled_on })),
73
+ usage: "Call cad_examples with one name to read its concept and script. Adapt the pattern to the request and to the product the person means; do not paste an example's sizes onto a different object.",
74
+ };
75
+ if (typeof args.name !== "string")
76
+ throw new Error("name must be a string.");
77
+ const found = all.find((e) => e.name === args.name);
78
+ if (!found)
79
+ throw new Error(`No example named ${JSON.stringify(args.name)}. Examples: ${all.map((e) => e.name).join(", ")}.`);
80
+ return { ...found };
81
+ }
@@ -144,6 +144,9 @@ ${r.readonly
144
144
  args.push("--bind", r.job, r.job);
145
145
  for (const file of r.readonly.filter((file) => !(r.inputs ?? []).includes(file)))
146
146
  args.push("--ro-bind", file, file);
147
+ // bubblewrap makes the folders above each bind on its own root tmpfs; left writable (bubblewrap 0.11), a script
148
+ // could create files beside the job folder (never on the host) and setup's forbidden-write proof fails
149
+ args.push("--remount-ro", "/");
147
150
  args.push("--chdir", r.job);
148
151
  return { command: "bwrap", args };
149
152
  }
@@ -14,11 +14,19 @@ export interface CadStatus {
14
14
  platform: string;
15
15
  storage: CadStorage;
16
16
  error?: string;
17
+ /** Set when this call re-verified a runtime that only the engine's own sources had changed under. */
18
+ reverified?: string;
17
19
  }
18
20
  export declare class CadEngine {
19
21
  private readonly options;
20
22
  private readonly system;
21
23
  readonly dataDir: string;
24
+ private reverifyFailure?;
25
+ /** How long a re-check waits for another CAD operation to let go of the engine (Counterpart reads status with 30 s). */
26
+ busyWaitMs: number;
27
+ /** Within this window a freed engine is re-checked here; later this call only waits for the other call's result, so
28
+ * a wait plus a ~17 s re-check cannot overrun the status deadline. */
29
+ busyRetryMs: number;
22
30
  constructor(options: CadOptions);
23
31
  status(): Promise<CadStatus>;
24
32
  failure(error: unknown, tool: string): Promise<{
@@ -35,6 +43,23 @@ export declare class CadEngine {
35
43
  private exclusive;
36
44
  private confined;
37
45
  setup(args: CadArguments, signal?: AbortSignal): Promise<Record<string, unknown>>;
46
+ /**
47
+ * The proof setup ends with: the runtime's imports, then the confined build, STL and STEP round trip, then the ready
48
+ * marker with the engine fingerprint and the runtime identity it proved. Shared by cad_setup and the automatic
49
+ * re-verification after an update that changed only the engine's sources.
50
+ */
51
+ private verify;
52
+ /**
53
+ * Re-verifies without installing when only the engine's own sources changed since the last proof (#609): the
54
+ * marker matches this platform, build123d and data device, its engine fingerprint differs, and the installed
55
+ * runtime still matches requirements.lock exactly with the same interpreter. Anything else, including a changed
56
+ * lock, still needs cad_setup with install: true. A failed re-verification is reported, not retried, until the
57
+ * engine changes again or setup runs.
58
+ */
59
+ ensureReady(signal?: AbortSignal, deadline?: number): Promise<CadStatus>;
60
+ private onlyEngineChanged;
61
+ /** The interpreter the venv runs and whether its installed distributions are exactly requirements.lock's pins. */
62
+ private runtimeIdentity;
38
63
  private fingerprint;
39
64
  private requireSupportedStorage;
40
65
  private inputFile;