bambu-printer-mcp 1.1.93 → 1.1.94

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
@@ -1069,7 +1069,7 @@ Dry-run the AMS match without uploading or starting a print. The tool reads `Met
1069
1069
 
1070
1070
  #### list_3mf_plates
1071
1071
 
1072
- List a designer's 3MF plates as Bambu Studio shows them when the file is opened, before slicing. A downloaded kit's six plates are six plates here too. For each plate it gives `index` (from 0, so `slice_stl`'s `slice_plate` is `index + 1`), `name`, the `objects` on it, and `sliced` (whether the file already holds its G-code). It also gives `plate_count` and the file's `title`, `designer` and `licence` when they're set. A plain 3MF with no plate metadata is one plate. `include_thumbnails` adds each plate's own preview from the file. Read-only.
1072
+ List a designer's 3MF plates as Bambu Studio shows them when the file is opened, before slicing. A downloaded kit's six plates are six plates here too. For each plate it gives `index` (from 0, so `slice_stl`'s `slice_plate` is `index + 1`), `name`, the `objects` on it, and `sliced` (whether the file already holds its G-code). To draw each plate from the open 3MF standard alone, `build_items` lists the root `3D/3dmodel.model` build items on it (0-based, in build order), and `parts` lists each model part of its objects once: `object_id` (the mesh object), `path` when that mesh is in another model part (`p:path`, e.g. `/3D/Objects/object_1.model`), `build_object_id` (the root object a build item places), `name`, `filament` (1-based, the project filament it prints in) and `painted: true` when slicer painting recolours some of its facets. Negative parts, modifiers and support blockers are not listed. It also gives `plate_count` and the file's `title`, `designer` and `licence` when they're set. A plain 3MF with no plate metadata is one plate. `include_thumbnails` adds each plate's own preview from the file. Read-only.
1073
1073
 
1074
1074
  ```json
1075
1075
  {
@@ -1325,6 +1325,8 @@ Read the `cad_design` prompt first. Supply `script` or a saved `script_path`, `o
1325
1325
 
1326
1326
  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.
1327
1327
 
1328
+ For a multi-colour result, `build()` returns `project_3mf()`: a new project of named parts with filaments and plates, or (with `project_3mf("kit")` on a declared input 3MF, in `mode: "mesh"`) an edit that adds, replaces, renames or recolours parts and keeps the designer's print settings, painting, plates and other files byte for byte. The run writes `<name>.3mf` with the same writer as `counterpart_make_3mf` and returns `three_mf` and `three_mf_project` (each plate's parts and filaments, read back from the file). See [docs/CAD.md](docs/CAD.md#multi-colour-3mf-projects).
1329
+
1328
1330
  `cad_status` and `cad_setup` expose `storage.expected_download_bytes`, `expected_installed_bytes` and cached measured `installed_bytes`; the first two are fresh-install budget estimates, not remaining transfer sizes. Setup failures carry `structuredContent.code`, `message`, `suggestion` and `retryable`, so clients do not parse wording.
1329
1331
 
1330
1332
  Runs wait for the environment's execution slot up to their own total timeout and return `queue_wait_ms`. Mark the selected result with `final: true`: each run's script-protected `cad-result.json` keeps the flag, full validation and artifact paths for recovery after restart. Check `status`, `valid` and the checks as well as `final`.
@@ -4,6 +4,7 @@ import * as fs from 'fs/promises';
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
6
  import * as path from 'node:path';
7
+ import { readSafe3mfArchive } from './safety/archive.js';
7
8
  // Parses Bambu Studio's JSON config data
8
9
  function parseBambuJSONConfig(jsonData) {
9
10
  const config = {};
@@ -462,8 +463,8 @@ export async function analyze3MFAmsRequirements(filePath, plateIndex = 0) {
462
463
  * is never a slice_info object.
463
464
  */
464
465
  export async function analyze3MFPlateObjects(filePath, plateIndex = 0) {
465
- const data = await fs.readFile(filePath);
466
- const zip = await JSZip.loadAsync(data);
466
+ // Bounded, with colliding or inconsistent entry names refused, as the other 3MF reads here.
467
+ const { zip } = await readSafe3mfArchive(filePath);
467
468
  const plateNumber = plateIndex + 1;
468
469
  const sliceInfo = zip.file('Metadata/slice_info.config');
469
470
  if (!sliceInfo) {
@@ -209,6 +209,14 @@ export const CAD_TOOLS = [
209
209
  type: "string",
210
210
  description: "The script's own print() output from this run, capped at 4000 characters (build.log keeps the rest). The script's words, not a measurement by the engine.",
211
211
  },
212
+ three_mf: {
213
+ type: "string",
214
+ description: "When build() returned project_3mf(): the written 3MF project, ready for slice_stl.",
215
+ },
216
+ three_mf_project: {
217
+ type: "object",
218
+ description: "When build() returned project_3mf(): base (the edited input alias, or null for a new project), changes, and the written file read back as list_3mf_plates reads it (plates with build_items, parts and filaments; project_filaments).",
219
+ },
212
220
  seconds: { type: "number" },
213
221
  }, [
214
222
  "valid",
@@ -349,6 +357,7 @@ Captured mesh preparation: load_scan(name, source_units="m" or "mm", up_axis="x"
349
357
  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.
350
358
  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.
351
359
  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.
360
+ Multi-colour 3MF projects: build() may return project_3mf() instead of a shape. A new project: p = project_3mf(); p.add_part(shape, name="Lid", filament=2, object="Box", plate=1) for each part (parts that share object= are one object, printed as one piece; plates from 1), in solid mode with build123d shapes (the checks fuse each object's parts) or mode: "mesh" with trimesh parts. Editing a designer's 3MF: declare it as an input and p = project_3mf("kit") in mode: "mesh"; p.objects lists its objects (name, id, plate; p.object(id or unique name)) and their parts (name, id, filament, painted, mesh: a trimesh in the object's frame); p.add_part(shape, name=..., filament=..., object="Body") adds a part in that object's frame, p.replace_part(part, mesh) swaps a part's mesh (its painting goes with the old mesh) and p.set_part(part, name=..., filament=...) renames or recolours one; everything else in the file (print settings, painting, plates, other parts) is kept. cad_run writes <name>.3mf beside the STL and returns three_mf and three_mf_project (each plate's parts and filaments, read back from the file); slice it with slice_stl, never by rebuilding it from the STL.
352
361
  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.
353
362
  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. After every cad_run, Read its perspective view (renders.perspective, as the result's next says) before the next cad_run or any other change: a run you have not looked at tells you nothing about the form. Judge the form from the perspective view first: would a person recognise the product and want it? Then inspect all six; revise visible defects. Before the final run, list what the views show is wrong against the bought product you named (for a scan, the object in its photos), and fix each one or report it. To get a number out of a design (a spring force, a strain, a clearance you derived), print() it in the script: the result returns it as printed, with no need to make a run fail. 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.
354
363
  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.
@@ -64,5 +64,10 @@ export declare class CadEngine {
64
64
  private requireSupportedStorage;
65
65
  private inputFile;
66
66
  run(args: CadArguments, signal?: AbortSignal): Promise<Record<string, unknown>>;
67
+ /**
68
+ * When build() returned project_3mf(), write <name>.3mf from the sandbox's manifest and part STLs (this trusted
69
+ * process writes it; the sandbox only meshed the parts) and read it back as list_3mf_plates does.
70
+ */
71
+ private project3mf;
67
72
  checkFit(args: CadArguments, signal?: AbortSignal): Promise<Record<string, unknown>>;
68
73
  }
@@ -6,6 +6,8 @@ import { createHash, randomUUID } from "node:crypto";
6
6
  import { createRequire } from "node:module";
7
7
  import { performance } from "node:perf_hooks";
8
8
  import { CadRefusal, cadFailure } from "./cad/refusal.js";
9
+ import { writeCadProject3mf } from "./counterpart/make-3mf.js";
10
+ import { listModelPlates } from "./counterpart/model-plates.js";
9
11
  import { withCadLock } from "./cad/serial.js";
10
12
  import { measureEnvironment, snapshotInputs, storageInfo, } from "./cad/storage.js";
11
13
  import { cadSandbox, defaultCadSystem } from "./cad/process.js";
@@ -365,6 +367,7 @@ export class CadEngine {
365
367
  "worker.py",
366
368
  "geometry.py",
367
369
  "scan_touchup.py",
370
+ "project3mf.py",
368
371
  "process.ts",
369
372
  "storage.ts",
370
373
  "serial.ts",
@@ -588,8 +591,10 @@ export class CadEngine {
588
591
  }
589
592
  const checked = JSON.parse((await this.confined("inspect", request, job, protectedFiles, remaining(), signal, readableInputs)).stdout);
590
593
  const printed = built.stdout.trim();
594
+ const project = await this.project3mf(job, name, snapshots);
591
595
  const result = {
592
596
  ...checked,
597
+ ...project,
593
598
  // Beside the image paths, where the next step is decided.
594
599
  next: "Read renders.perspective before the next cad_run or any other change: say what it shows is wrong against what you are making (the bought product you named, or the object in the photos), then fix that.",
595
600
  // The script's own print() output: its words, not a measurement by this engine.
@@ -636,6 +641,35 @@ export class CadEngine {
636
641
  }
637
642
  }, "run", signal, deadline);
638
643
  }
644
+ /**
645
+ * When build() returned project_3mf(), write <name>.3mf from the sandbox's manifest and part STLs (this trusted
646
+ * process writes it; the sandbox only meshed the parts) and read it back as list_3mf_plates does.
647
+ */
648
+ async project3mf(job, name, inputs) {
649
+ const manifestPath = path.join(job, `${name}.project.json`);
650
+ const st = await fs.lstat(manifestPath).catch(() => undefined);
651
+ if (!st)
652
+ return {};
653
+ if (!st.isFile() || st.size > 1024 * 1024)
654
+ throw new Error("The design's 3MF project manifest is unsafe or too large.");
655
+ const partsDir = path.join(job, `${name}.parts`);
656
+ const dir = await fs.lstat(partsDir).catch(() => undefined);
657
+ if (!dir?.isDirectory())
658
+ throw new Error("The design's 3MF project parts are missing.");
659
+ const out = path.join(job, `${name}.3mf`);
660
+ const written = await writeCadProject3mf(JSON.parse(await fs.readFile(manifestPath, "utf8")), partsDir, inputs, out);
661
+ const listed = await listModelPlates(out);
662
+ return {
663
+ three_mf: out,
664
+ three_mf_project: {
665
+ base: written.base,
666
+ changes: written.changed,
667
+ plate_count: listed.plate_count,
668
+ plates: listed.plates.map(plate => ({ index: plate.index, name: plate.name, build_items: plate.build_items, parts: plate.parts, filaments: plate.filaments })),
669
+ project_filaments: listed.project_filaments,
670
+ },
671
+ };
672
+ }
639
673
  async checkFit(args, signal) {
640
674
  only(args, [
641
675
  "model",
@@ -179,7 +179,7 @@ export declare const FLIGHT_ASSESS_PROPERTIES: {
179
179
  };
180
180
  visibility: {
181
181
  type: string;
182
- enum: ("dark" | "clear" | "unknown" | "occluded" | "out_of_view")[];
182
+ enum: ("dark" | "unknown" | "clear" | "occluded" | "out_of_view")[];
183
183
  description: string;
184
184
  };
185
185
  footprint_visible: {
@@ -201,7 +201,7 @@ export declare const FLIGHT_ASSESS_PROPERTIES: {
201
201
  };
202
202
  reference_visibility: {
203
203
  type: string;
204
- enum: ("dark" | "clear" | "unknown" | "occluded" | "out_of_view")[];
204
+ enum: ("dark" | "unknown" | "clear" | "occluded" | "out_of_view")[];
205
205
  description: string;
206
206
  };
207
207
  reference_empty: {
@@ -14,3 +14,13 @@ export type Make3mfResult = {
14
14
  }[];
15
15
  };
16
16
  export declare function makeCounterpart3mf(args: Record<string, unknown>): Promise<Make3mfResult>;
17
+ /**
18
+ * Write the 3MF a cad_run design script returned as project_3mf() (src/cad/project3mf.py): `manifest` is the
19
+ * sandbox's <name>.project.json, `partsDir` its STL parts, `inputs` the run's input snapshots by alias. A new project
20
+ * is written as counterpart_make_3mf writes one, an object per assembly on its plate. An edit copies the base 3MF and
21
+ * changes only what the script changed, so its print settings, painting, plates and other parts stay as they were.
22
+ */
23
+ export declare function writeCadProject3mf(manifest: unknown, partsDir: string, inputs: Record<string, string>, outPath: string): Promise<{
24
+ base: string | null;
25
+ changed: string[];
26
+ }>;