bambu-printer-mcp 1.1.68 → 1.1.70

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
@@ -1022,6 +1022,17 @@ Dry-run the AMS match without uploading or starting a print. The tool reads `Met
1022
1022
  }
1023
1023
  ```
1024
1024
 
1025
+ #### list_3mf_plates
1026
+
1027
+ 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.
1028
+
1029
+ ```json
1030
+ {
1031
+ "three_mf_path": "/Users/yourname/Downloads/kit.3mf",
1032
+ "include_thumbnails": true
1033
+ }
1034
+ ```
1035
+
1025
1036
  #### list_3mf_plate_objects
1026
1037
 
1027
1038
  List object IDs from a sliced 3MF plate. Use this before `skip_objects` so you pass real Bambu object IDs instead of display-order guesses.
@@ -0,0 +1,20 @@
1
+ export interface ModelPlate {
2
+ /** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
3
+ index: number;
4
+ name: string;
5
+ objects: string[];
6
+ /** The file already holds this plate's G-code. */
7
+ sliced: boolean;
8
+ /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
9
+ thumbnail_png_base64?: string;
10
+ }
11
+ export interface ModelPlates {
12
+ plate_count: number;
13
+ plates: ModelPlate[];
14
+ title?: string;
15
+ designer?: string;
16
+ licence?: string;
17
+ }
18
+ export declare function listModelPlates(filePath: string, options?: {
19
+ thumbnails?: boolean;
20
+ }): Promise<ModelPlates>;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * list_3mf_plates: a Bambu Studio / OrcaSlicer project's plates as its designer laid them out, before slicing
3
+ * (Counterpart PRD §5.5 "Plates of an imported 3MF", §8.0 item 9). Bambu Studio shows a downloaded kit as its
4
+ * plates straight away; clients show the same from here instead of parsing the project files themselves.
5
+ *
6
+ * Plates come from Metadata/model_settings.config (`<plate>` with `plater_id`, `plater_name` and the objects it
7
+ * holds) and, for a sliced file, from Metadata/plate_N.json and plate_N.gcode. A plain 3MF with no plate metadata
8
+ * is one plate. Only bounded metadata is read; nothing is extracted or run.
9
+ */
10
+ import { readSafe3mfArchive } from "../safety/archive.js";
11
+ /** For the settings and plate files; the model file can be large and is only scanned. */
12
+ const MAX_METADATA_BYTES = 8 * 1024 * 1024;
13
+ const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
14
+ const MAX_PLATES = 1000;
15
+ const words = (value) => value
16
+ .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]))
17
+ .replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 256);
18
+ export async function listModelPlates(filePath, options = {}) {
19
+ const { zip } = await readSafe3mfArchive(filePath);
20
+ const text = async (name) => {
21
+ const file = zip.file(name);
22
+ if (!file)
23
+ return "";
24
+ const bytes = await file.async("nodebuffer");
25
+ if (bytes.length > MAX_METADATA_BYTES)
26
+ throw new Error(`${name} is too large to read.`);
27
+ return bytes.toString("utf8");
28
+ };
29
+ // The model file can hold the whole mesh (a plain 3MF): scanned as bytes, never made one string.
30
+ const modelBytes = await zip.file("3D/3dmodel.model")?.async("nodebuffer");
31
+ const head = modelBytes?.subarray(0, 1024 * 1024).toString("utf8") ?? "";
32
+ if (!/<(?:\w+:)?model\b/.test(head))
33
+ throw new Error("That file is not a 3MF model.");
34
+ // An element named `tag`, plain or with a namespace prefix (<item …>, <p:item …>).
35
+ const has = (tag) => !!modelBytes && [" ", ">", "/", "\n", "\r", "\t"].some(end => modelBytes.includes(`<${tag}${end}`) || modelBytes.includes(`:${tag}${end}`));
36
+ const result = { plate_count: 0, plates: [] };
37
+ const metadata = new Map([...head.matchAll(/<metadata\s+name="([^"]+)"[^>]*>([^<]*)<\/metadata>/g)].map(match => [match[1], words(match[2])]));
38
+ if (metadata.get("Title"))
39
+ result.title = metadata.get("Title");
40
+ if (metadata.get("Designer"))
41
+ result.designer = metadata.get("Designer");
42
+ if (metadata.get("License"))
43
+ result.licence = metadata.get("License");
44
+ const settings = await text("Metadata/model_settings.config");
45
+ const objects = new Map([...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
46
+ const name = /<metadata\s+key="name"\s+value="([^"]*)"/.exec(match[2]);
47
+ return [match[1], words(name?.[1] ?? "")];
48
+ }));
49
+ const plates = new Map();
50
+ // A plate number out of range is skipped, as a slicer would not show it.
51
+ const valid = (number) => Number.isSafeInteger(number) && number >= 1 && number <= MAX_PLATES;
52
+ for (const match of settings.matchAll(/<plate\b[^>]*>([\s\S]*?)<\/plate>/g)) {
53
+ const id = /<metadata\s+key="plater_id"\s+value="(\d+)"/.exec(match[1]);
54
+ if (!id)
55
+ continue;
56
+ const number = Number(id[1]);
57
+ if (!valid(number))
58
+ continue;
59
+ const name = /<metadata\s+key="plater_name"\s+value="([^"]*)"/.exec(match[1]);
60
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false,
61
+ objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])] : []) });
62
+ }
63
+ for (const name of Object.keys(zip.files)) {
64
+ const match = /^Metadata\/plate_([1-9]\d*)\.(json|gcode)$/.exec(name);
65
+ if (!match)
66
+ continue;
67
+ const number = Number(match[1]);
68
+ if (!valid(number))
69
+ continue;
70
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], sliced: false };
71
+ if (match[2] === "gcode")
72
+ plate.sliced = true;
73
+ else {
74
+ try {
75
+ const value = JSON.parse(await text(name));
76
+ if (Array.isArray(value.bbox_objects))
77
+ plate.objects = value.bbox_objects
78
+ .flatMap(object => typeof object.name === "string" && object.name !== "wipe_tower" ? [words(object.name)] : []).slice(0, 200);
79
+ }
80
+ catch { /* the plate keeps the objects model_settings lists */ }
81
+ }
82
+ plates.set(number, plate);
83
+ }
84
+ result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
85
+ // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
86
+ if (!result.plates.length)
87
+ result.plates.push({ index: 0, name: "Plate 1", objects: [], sliced: false });
88
+ const geometry = has("item") && (has("mesh") || has("component"));
89
+ if (!geometry) {
90
+ // A sliced-only file (previews and G-code, no model): only its sliced plates can print.
91
+ result.plates = result.plates.filter(plate => plate.sliced);
92
+ if (!result.plates.length)
93
+ throw new Error("This 3MF has previews and settings but no model or printable plate.");
94
+ }
95
+ if (options.thumbnails)
96
+ for (const plate of result.plates) {
97
+ const file = zip.file(`Metadata/plate_${plate.index + 1}.png`);
98
+ if (!file)
99
+ continue;
100
+ const bytes = await file.async("nodebuffer");
101
+ if (bytes.length <= MAX_THUMBNAIL_BYTES && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
102
+ plate.thumbnail_png_base64 = bytes.toString("base64");
103
+ }
104
+ result.plate_count = result.plates.length;
105
+ return result;
106
+ }
@@ -8,6 +8,7 @@ export const REMOTE_SCOPES = {
8
8
  get_printer_filaments: "read",
9
9
  resolve_3mf_ams_slots: "read",
10
10
  list_3mf_plate_objects: "read",
11
+ list_3mf_plates: "read",
11
12
  get_stl_info: "read",
12
13
  list_templates: "read",
13
14
  list_printer_files: "read",
@@ -20,12 +20,17 @@ export interface SlicedFileFacts {
20
20
  /** The facts of a sliced 3MF or G-code file for one zero-based plate; what can't be read is left out, never an error. */
21
21
  export declare function slicedFileFacts(filePath: string, plateIndex?: number): Promise<SlicedFileFacts>;
22
22
  /**
23
- * Bambu Studio's (or OrcaSlicer's) verdict on a slice, from its result.json: whether it failed, its own words
24
- * (the error and every plate's warning, verbatim), and how many plates it sliced.
23
+ * Bambu Studio's (or OrcaSlicer's) verdict on a slice, from its result.json: whether it failed, what a person is
24
+ * told (`message`: a plain sentence for a refusal, src/slicer/slicer-messages.ts; the plates' warnings for a slice
25
+ * that worked), the slicer's own words for the log (`slicer_message`: the error and every plate's warning,
26
+ * verbatim), and how many plates it sliced.
25
27
  */
26
28
  export interface SlicerReport {
27
29
  failed: boolean;
28
30
  message?: string;
31
+ slicer_message?: string;
29
32
  plate_count?: number;
30
33
  }
34
+ /** A refusal's report: the plain sentence, and the slicer's words kept beside it. */
35
+ export declare function refusalReport(words: string): SlicerReport;
31
36
  export declare function slicerReport(result: unknown): SlicerReport | undefined;
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import { loadSafe3mfArchive, readBoundedPrintFile } from "../safety/archive.js";
3
+ import { plainSlicerError, UNKNOWN_SLICER_ERROR } from "../slicer/slicer-messages.js";
3
4
  const number = (value) => {
4
5
  const parsed = typeof value === "number" ? value : typeof value === "string" ? Number.parseFloat(value) : NaN;
5
6
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
@@ -92,6 +93,11 @@ async function readFacts(filePath, plateIndex) {
92
93
  return { ...(plates.size ? { plate_count: plates.size } : {}), ...(estimate ? { estimate } : {}), settings };
93
94
  }
94
95
  const clean = (text) => text.replace(/\r\n?/g, "\n").replace(/[\x00-\x09\x0b-\x1f\x7f]/g, " ").trim();
96
+ /** A refusal's report: the plain sentence, and the slicer's words kept beside it. */
97
+ export function refusalReport(words) {
98
+ const raw = clean(words).slice(0, 2000);
99
+ return { failed: true, message: plainSlicerError(raw) ?? UNKNOWN_SLICER_ERROR, ...(raw ? { slicer_message: raw } : {}) };
100
+ }
95
101
  export function slicerReport(result) {
96
102
  if (!result || typeof result !== "object" || Array.isArray(result))
97
103
  return undefined;
@@ -105,6 +111,6 @@ export function slicerReport(result) {
105
111
  const error = typeof value.error_string === "string" ? clean(value.error_string) : "";
106
112
  const words = [...new Set([...(failed && error ? [error] : []), ...warnings])].join("\n").slice(0, 2000);
107
113
  if (failed)
108
- return { failed, message: words || `The slicer could not slice this model (return code ${String(value.return_code)}).` };
109
- return { failed, ...(words ? { message: words } : {}), ...(plateCount ? { plate_count: plateCount } : {}) };
114
+ return refusalReport(words || `return code ${String(value.return_code)}`);
115
+ return { failed, ...(words ? { message: words, slicer_message: words } : {}), ...(plateCount ? { plate_count: plateCount } : {}) };
110
116
  }
package/dist/index.js CHANGED
@@ -2,7 +2,8 @@
2
2
  import { CAMERA_STREAM_TOOLS } from "./printers/camera-tools.js";
3
3
  import { withAnnotations } from "./tool-annotations.js";
4
4
  import { withRemote } from "./counterpart/remote.js";
5
- import { slicedFileFacts, slicerReport } from "./counterpart/sliced-file.js";
5
+ import { refusalReport, slicedFileFacts, slicerReport } from "./counterpart/sliced-file.js";
6
+ import { listModelPlates } from "./counterpart/model-plates.js";
6
7
  /** The slicer's verdict beside its result.json (`slicer_report`). */
7
8
  function reportOf(result) {
8
9
  const report = slicerReport(result);
@@ -2060,6 +2061,18 @@ class BambuPrinterMCPServer {
2060
2061
  required: ["three_mf_path"]
2061
2062
  }
2062
2063
  },
2064
+ {
2065
+ name: "list_3mf_plates",
2066
+ description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it and whether the file already holds its G-code (sliced). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2067
+ inputSchema: {
2068
+ type: "object",
2069
+ properties: {
2070
+ three_mf_path: { type: "string", description: "Path to the 3MF (a designer's project, sliced or not)" },
2071
+ include_thumbnails: { type: "boolean", description: "Include each plate's own preview PNG from the file, base64 (default false)" }
2072
+ },
2073
+ required: ["three_mf_path"]
2074
+ }
2075
+ },
2063
2076
  {
2064
2077
  name: "list_3mf_plate_objects",
2065
2078
  description: "List object IDs from a sliced 3MF plate. Use these IDs with skip_objects during a running print.",
@@ -2250,7 +2263,7 @@ class BambuPrinterMCPServer {
2250
2263
  },
2251
2264
  {
2252
2265
  name: "slice_stl",
2253
- description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. A failed slice's text starts with those words. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2266
+ description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. structuredContent.slicer_report says whether it failed; for a failure, its message is a plain sentence for a person and slicer_message keeps the slicer's words, which a failed slice's text gives after that sentence. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2254
2267
  inputSchema: {
2255
2268
  type: "object",
2256
2269
  properties: {
@@ -3367,6 +3380,14 @@ class BambuPrinterMCPServer {
3367
3380
  };
3368
3381
  break;
3369
3382
  }
3383
+ case "list_3mf_plates": {
3384
+ if (typeof args?.three_mf_path !== "string" || !args.three_mf_path)
3385
+ throw new Error("Missing required parameter: three_mf_path");
3386
+ if (args.include_thumbnails !== undefined && typeof args.include_thumbnails !== "boolean")
3387
+ throw new Error("include_thumbnails must be a boolean.");
3388
+ const plates = await listModelPlates(args.three_mf_path, { thumbnails: args.include_thumbnails === true });
3389
+ return { content: [{ type: "text", text: JSON.stringify(plates) }], structuredContent: plates };
3390
+ }
3370
3391
  case "list_3mf_plate_objects": {
3371
3392
  if (!args?.three_mf_path) {
3372
3393
  throw new Error("Missing required parameter: three_mf_path");
@@ -3995,6 +4016,8 @@ class BambuPrinterMCPServer {
3995
4016
  console.warn("Could not resolve live printer filaments for slicing:", filamentError);
3996
4017
  }
3997
4018
  }
4019
+ // A client that cancels this call (it no longer wants the slice) stops the slicer.
4020
+ sliceBambuOptions.signal = extra.signal;
3998
4021
  const sliced = await this.stlManipulator.sliceSTLWithResult(String(args.stl_path), slicerType, slicerPath, activeSlicerProfile, undefined, // progressCallback
3999
4022
  printerPreset, sliceBambuOptions);
4000
4023
  await progressNotifications;
@@ -4395,13 +4418,18 @@ class BambuPrinterMCPServer {
4395
4418
  tool: name,
4396
4419
  ...(error instanceof PrinterRefusal ? { code: error.code } : {}),
4397
4420
  // The slicer's own result.json; the message starts with its error_string and warnings.
4398
- ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult, ...reportOf(error.slicerResult) } : {}),
4421
+ // A slicer failure always carries slicer_report: the plain sentence a person sees, the slicer's words for the log.
4422
+ // The report always says failed (a result.json that says success can still leave no output file).
4423
+ ...(error instanceof SlicerRunError ? {
4424
+ ...(error.slicerResult ? { slicer_result: error.slicerResult } : {}),
4425
+ slicer_report: { ...refusalReport(error.words), message: error.plain ?? error.words.slice(0, 2000) },
4426
+ } : {}),
4399
4427
  };
4400
4428
  // MCP clients validate structuredContent against a declared outputSchema even on
4401
4429
  // errors (SDK 1.32 Client.callTool), so those tools return the error as text only.
4402
4430
  return {
4403
- // A slicer failure leads with the slicer's own words.
4404
- content: [{ type: "text", text: error instanceof SlicerRunError && error.slicerText ? message : `Error: ${message}` }],
4431
+ // A slicer's refusal leads with its plain sentence, then the slicer's own words.
4432
+ content: [{ type: "text", text: error instanceof SlicerRunError && error.plain ? message : `Error: ${message}` }],
4405
4433
  ...(OUTPUT_SCHEMA_TOOLS.has(name) ? {} : { structuredContent: structured }),
4406
4434
  isError: true,
4407
4435
  };
@@ -509,7 +509,12 @@ export async function inspectPrintFile(filePath, options) {
509
509
  invalid();
510
510
  continue;
511
511
  }
512
- if (!['M117', 'M118', 'M1002', 'M1006', 'M900', 'M970', 'M983.1', 'G383'].includes(code) && /[GM]\s*\d/i.test(argumentsText))
512
+ // Bambu Studio's skip-object start carries one base64 mask of the layer's objects (M624 /g8C/B8AAAA=), whose
513
+ // letters and digits can read as a command; only that exact one-token form is exempt.
514
+ const mask = argumentsText.trim();
515
+ // A whole base64 value (length a multiple of 4) that doesn't itself start like a command (M104S300, G28, T1).
516
+ const objectMask = code === 'M624' && /^[A-Za-z0-9+/]+={0,2}$/.test(mask) && mask.length % 4 === 0 && !/^[GMT]\d/i.test(mask);
517
+ if (!objectMask && !['M117', 'M118', 'M1002', 'M1006', 'M900', 'M970', 'M983.1', 'G383'].includes(code) && /[GM]\s*\d/i.test(argumentsText))
513
518
  fail('multiple commands on one line are unsupported');
514
519
  // Coordinated extrusion closes the startup-only allowance even when the
515
520
  // source omits layer comments. Retraction also closes it conservatively.
@@ -630,7 +630,11 @@ async function writeTemp(tempDir, kind, leafName, data) {
630
630
  const safe = leafName.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 64);
631
631
  const filename = `flat-${kind}-${safe}-${hash}.json`;
632
632
  const out = path.join(tempDir, filename);
633
- await fs.writeFile(out, serialized, "utf8");
633
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
634
+ // rename it into place, so a reader never sees it truncated or half-written.
635
+ const partial = `${out}.${crypto.randomUUID()}.partial`;
636
+ await fs.writeFile(partial, serialized, "utf8");
637
+ await fs.rename(partial, out);
634
638
  return out;
635
639
  }
636
640
  /* -------------------------------------------------------------------------- */
@@ -10,6 +10,8 @@ const SUPPORTED_OPTIONS = new Set([
10
10
  'nozzleType', 'nozzleVolumeType', 'slicePlate',
11
11
  // Written into the uploaded process preset before the request, not sent as API options.
12
12
  'processOverrides',
13
+ // The request's cancellation, honoured through isCancelled; never sent.
14
+ 'signal',
13
15
  ]);
14
16
  function configuration() {
15
17
  let url;
@@ -0,0 +1,4 @@
1
+ /** The plain sentence for a slicer's error, or undefined when the words aren't one this knows. */
2
+ export declare function plainSlicerError(words: string): string | undefined;
3
+ /** What a person is told when the slicer refused with words this doesn't know. */
4
+ export declare const UNKNOWN_SLICER_ERROR = "The slicer couldn't slice this model. Its own message is kept for the log.";
@@ -0,0 +1,62 @@
1
+ /**
2
+ * A slicer's refusal in plain words. Bambu Studio, OrcaSlicer, PrusaSlicer and CuraEngine word their errors for
3
+ * their own windows ("One of the plate is empty or has no object fully inside it..."); a client shows the person
4
+ * the sentence here and keeps the slicer's own words for its logs (`slicer_report.slicer_message`).
5
+ *
6
+ * The phrases are the slicers' own strings: Bambu Studio 02.09 and OrcaSlicer 2.3 (their CLI and validation
7
+ * messages), PrusaSlicer 2.9.2 (src/libslic3r/Print.cpp, src/CLI/ProcessActions.cpp) and CuraEngine
8
+ * (src/FffPolygonGenerator.cpp). Matching is on a lowercase fragment, so a version that adds a prefix or a
9
+ * plate number still matches.
10
+ */
11
+ const PLAIN = [
12
+ {
13
+ phrases: [
14
+ "one of the plate is empty or has no object fully inside it",
15
+ "a plate is empty or has no object fully inside it",
16
+ "cannot send the print job for empty plate",
17
+ "no object is fully inside the print volume",
18
+ "found no objects in print volume to slice",
19
+ "found no objects in print volume after skip",
20
+ "all objects are outside of the print volume",
21
+ "arrangement ignored the following objects which can't fit into a single bed",
22
+ ],
23
+ sentence: "Nothing on this plate can be printed: no part sits fully on the bed. A part is off the plate or across its edge, or the model is bigger than the bed.",
24
+ },
25
+ {
26
+ phrases: [
27
+ "laid over the boundary of plate or exceeds the height limit",
28
+ "layed over the boundary of plate",
29
+ "laid over the plate boundaries",
30
+ "partly inside, can not be sliced",
31
+ "located over the boundary of the heated bed",
32
+ ],
33
+ sentence: "A part sits across the edge of the plate, or is taller than the printer can print, so it can't be sliced as it is placed.",
34
+ },
35
+ {
36
+ phrases: ["exceeds the maximum build volume height", "exceeds the printable height"],
37
+ sentence: "The model is taller than the printer can print.",
38
+ },
39
+ {
40
+ phrases: ["object too large", "scale to fit error", "printable area/volume reduced"],
41
+ sentence: "The model is larger than the printer's bed.",
42
+ },
43
+ {
44
+ phrases: ["found g-code outside of the printable area", "found g-code in unprintable area", "g-code path exceeds the printable range"],
45
+ sentence: "The print would go outside the area the printer can reach, usually a brim, skirt, support or the wipe tower near an edge. Move the model further onto the plate.",
46
+ },
47
+ {
48
+ phrases: ["g-code path conflicts found", "found gcode path conflicts between object"],
49
+ sentence: "Two parts are so close that their print paths overlap. Move them apart.",
50
+ },
51
+ {
52
+ phrases: ["the supplied settings will cause an empty print", "there are no non-empty layers"],
53
+ sentence: "These settings would print nothing: no layer of the model has anything to print.",
54
+ },
55
+ ];
56
+ /** The plain sentence for a slicer's error, or undefined when the words aren't one this knows. */
57
+ export function plainSlicerError(words) {
58
+ const text = words.toLowerCase();
59
+ return PLAIN.find(entry => entry.phrases.some(phrase => text.includes(phrase)))?.sentence;
60
+ }
61
+ /** What a person is told when the slicer refused with words this doesn't know. */
62
+ export const UNKNOWN_SLICER_ERROR = "The slicer couldn't slice this model. Its own message is kept for the log.";
@@ -28,6 +28,8 @@ export type SlicerType = typeof SLICER_TYPES[number];
28
28
  export declare function normalizeSlicerType(rawSlicerType: string): SlicerType;
29
29
  export declare function isBambuCompatibleSlicer(slicerType: SlicerType): boolean;
30
30
  export interface BambuSliceOptions {
31
+ /** The request's own cancellation: aborting it stops the slicer (the MCP client cancelled the call). */
32
+ signal?: AbortSignal;
31
33
  uptodate?: boolean;
32
34
  repetitions?: number;
33
35
  orient?: boolean;
@@ -68,6 +70,10 @@ export type SliceOutput = {
68
70
  export declare class SlicerRunError extends Error {
69
71
  readonly slicerResult?: SlicerResult | undefined;
70
72
  readonly slicerText: string;
73
+ /** What a person is told for a slicer's refusal: a plain sentence, never its own words (src/slicer/slicer-messages.ts). */
74
+ readonly plain?: string;
75
+ /** The slicer's words and this server's detail, after the plain sentence: what slicer_report.slicer_message keeps. */
76
+ readonly words: string;
71
77
  constructor(detail: string, slicerResult?: SlicerResult | undefined);
72
78
  }
73
79
  export declare class STLManipulator extends EventEmitter {
@@ -78,6 +84,11 @@ export declare class STLManipulator extends EventEmitter {
78
84
  * Generate a unique operation ID
79
85
  */
80
86
  private generateOperationId;
87
+ /**
88
+ * A new folder for one slice's outputs, under TEMP_DIR/slices. A sliced file's path stays valid for a day after
89
+ * its slice (callers print from it); older slice folders are removed as new slices start.
90
+ */
91
+ private newSliceFolder;
81
92
  private getAvailableProfileRoots;
82
93
  private findProfileFile;
83
94
  private buildFilamentIdIndex;
@@ -12,10 +12,13 @@ import * as crypto from 'crypto';
12
12
  import { execFile } from 'child_process';
13
13
  import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
14
14
  import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
15
+ import { plainSlicerError, UNKNOWN_SLICER_ERROR } from '../slicer/slicer-messages.js';
15
16
  import { applyProcessOverrides } from '../slicer/process-overrides.js';
16
17
  import { profileJsonFiles } from '../slicer/profile-files.js';
17
18
  import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
18
19
  import { sliceWithOrcaApi, validateRemoteSliceOptions } from '../slicer/remote-slicer.js';
20
+ /** How long a slice's folder (its sliced file and result.json) is kept: a day, then a later slice removes it. */
21
+ const SLICE_FOLDER_LIFETIME_MS = 24 * 60 * 60 * 1000;
19
22
  const readFileAsync = promisify(fs.readFile);
20
23
  const writeFileAsync = promisify(fs.writeFile);
21
24
  const BAMBU_PROFILE_ROOTS = [
@@ -122,10 +125,16 @@ const PROFILE_METADATA_KEYS = new Set([
122
125
  export class SlicerRunError extends Error {
123
126
  constructor(detail, slicerResult) {
124
127
  const slicerText = slicerResult ? slicerResultText(slicerResult) : "";
125
- super(slicerText ? `${slicerText}\n${detail}` : detail);
128
+ const words = slicerText ? `${slicerText}\n${detail}` : detail;
129
+ // A known refusal, or one in the slicer's own words, is said plainly. A fault of the setup (no slicer, a crash,
130
+ // no output) stays in this server's own words, which say what to fix.
131
+ const plain = plainSlicerError(words) ?? (slicerText ? UNKNOWN_SLICER_ERROR : undefined);
132
+ super(plain ? `${plain}\nThe slicer said: ${words}` : words);
126
133
  this.slicerResult = slicerResult;
127
134
  this.name = "SlicerRunError";
128
135
  this.slicerText = slicerText;
136
+ this.plain = plain;
137
+ this.words = words;
129
138
  }
130
139
  }
131
140
  /**
@@ -212,6 +221,24 @@ export class STLManipulator extends EventEmitter {
212
221
  generateOperationId() {
213
222
  return crypto.randomUUID();
214
223
  }
224
+ /**
225
+ * A new folder for one slice's outputs, under TEMP_DIR/slices. A sliced file's path stays valid for a day after
226
+ * its slice (callers print from it); older slice folders are removed as new slices start.
227
+ */
228
+ async newSliceFolder(operationId) {
229
+ const root = path.join(this.tempDir, 'slices');
230
+ await fs.promises.mkdir(root, { recursive: true });
231
+ const cutoff = Date.now() - SLICE_FOLDER_LIFETIME_MS;
232
+ for (const name of await fs.promises.readdir(root).catch(() => [])) {
233
+ const folder = path.join(root, name);
234
+ const info = await fs.promises.stat(folder).catch(() => undefined);
235
+ if (info?.isDirectory() && info.mtimeMs < cutoff)
236
+ await fs.promises.rm(folder, { recursive: true, force: true }).catch(() => undefined);
237
+ }
238
+ const folder = path.join(root, operationId);
239
+ await fs.promises.mkdir(folder);
240
+ return folder;
241
+ }
215
242
  getAvailableProfileRoots() {
216
243
  const selectedRoot = process.env.BAMBU_PROFILES_ROOT;
217
244
  return [
@@ -300,7 +327,11 @@ export class STLManipulator extends EventEmitter {
300
327
  const serialized = JSON.stringify(value, null, 2);
301
328
  const hash = crypto.createHash('sha256').update(serialized).digest('hex').slice(0, 16);
302
329
  const outPath = path.join(this.tempDir, `${outputBase}_${suffix}_${hash}.json`);
303
- fs.writeFileSync(outPath, serialized);
330
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
331
+ // rename it into place, so a reader never sees it truncated or half-written.
332
+ const partial = `${outPath}.${crypto.randomUUID()}.partial`;
333
+ fs.writeFileSync(partial, serialized);
334
+ fs.renameSync(partial, outPath);
304
335
  return outPath;
305
336
  }
306
337
  async resolveBambuLikeSettingsBundle(outputBase, slicerType, slicerProfile, printerPreset, bambuOptions, activeProfilesRoot, preserveOrcaExtrusionMode = false) {
@@ -1391,6 +1422,14 @@ export class STLManipulator extends EventEmitter {
1391
1422
  async sliceSTLOnce(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1392
1423
  const operationId = this.generateOperationId();
1393
1424
  this.activeOperations.set(operationId, true);
1425
+ // A cancelled request stops its slice: the slicer is killed (below) instead of finishing a slice nobody reads.
1426
+ const signal = bambuOptions?.signal;
1427
+ const cancel = () => { if (this.activeOperations.has(operationId))
1428
+ this.activeOperations.set(operationId, false); };
1429
+ if (signal?.aborted) {
1430
+ this.activeOperations.delete(operationId);
1431
+ throw new Error("Slicing operation cancelled");
1432
+ }
1394
1433
  if (slicerType !== 'orca-slicer-api' && isPathLikeExecutable(slicerPath) && !fs.existsSync(slicerPath)) {
1395
1434
  throw new Error(`Slicer executable not found at: ${slicerPath}`);
1396
1435
  }
@@ -1407,7 +1446,10 @@ export class STLManipulator extends EventEmitter {
1407
1446
  let cliResult;
1408
1447
  const orcaTemporaryDirectories = [];
1409
1448
  const temporaryFiles = [];
1449
+ // This slice's own folder (local Bambu-compatible CLI): removed if the slice fails or is cancelled.
1450
+ let sliceDir;
1410
1451
  try {
1452
+ signal?.addEventListener('abort', cancel, { once: true });
1411
1453
  if (progressCallback)
1412
1454
  progressCallback(0, `Starting slicing with ${slicerType}...`);
1413
1455
  switch (slicerType) {
@@ -1456,7 +1498,13 @@ export class STLManipulator extends EventEmitter {
1456
1498
  throw new Error('Remote slicing process profile does not exist.');
1457
1499
  }
1458
1500
  const profileSlicerType = remote ? 'orcaslicer' : slicerType;
1459
- const bambuOutputPath = path.join(this.tempDir, outputBase + (remote ? `_${operationId}` : '') + '_sliced.3mf');
1501
+ // Every local slice writes into a folder of its own, so two slices at once, even of same-named inputs, never
1502
+ // read, replace or delete each other's files. Bambu Studio's CLI (v02.08.02.61) writes fixed names into
1503
+ // --outputdir: result.json, each plate's G-code as plate_<n>.gcode (and its .tmp) before packing it into
1504
+ // the 3MF, and the exported 3MF's .tmp; its own scratch files under the system temp dir are per process.
1505
+ const bambuOutputPath = remote
1506
+ ? path.join(this.tempDir, `${outputBase}_${operationId}_sliced.3mf`)
1507
+ : path.join(sliceDir = await this.newSliceFolder(operationId), `${outputBase}_sliced.3mf`);
1460
1508
  const outputDir = path.dirname(bambuOutputPath);
1461
1509
  const selectedProfilesRoot = detectProfilesRoot(remote ? undefined : slicerPath, profileSlicerType);
1462
1510
  const profilesRoot = !remote && profileSlicerType === 'orcaslicer'
@@ -1697,6 +1745,9 @@ export class STLManipulator extends EventEmitter {
1697
1745
  }
1698
1746
  catch (error) {
1699
1747
  console.error(`Slicing failed for ${stlFilePath}:`, error);
1748
+ // Nothing in a failed or cancelled slice's folder is handed back (its result.json is already in the error).
1749
+ if (sliceDir)
1750
+ await fs.promises.rm(sliceDir, { recursive: true, force: true }).catch(() => undefined);
1700
1751
  this.emit('operationError', {
1701
1752
  operationId,
1702
1753
  type: 'slice',
@@ -1705,6 +1756,7 @@ export class STLManipulator extends EventEmitter {
1705
1756
  throw error;
1706
1757
  }
1707
1758
  finally {
1759
+ signal?.removeEventListener('abort', cancel);
1708
1760
  this.activeOperations.delete(operationId);
1709
1761
  for (const file of temporaryFiles) {
1710
1762
  await fs.promises.rm(file, { force: true }).catch(error => console.error('Could not remove a temporary mesh:', error));
@@ -31,6 +31,7 @@ export const TOOL_ANNOTATIONS = {
31
31
  // Local reads
32
32
  inspect_print_file: READ_LOCAL,
33
33
  list_3mf_plate_objects: READ_LOCAL,
34
+ list_3mf_plates: READ_LOCAL,
34
35
  get_stl_info: READ_LOCAL,
35
36
  list_templates: READ_LOCAL,
36
37
  get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.68",
3
+ "version": "1.1.70",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
@@ -0,0 +1,111 @@
1
+ /**
2
+ * list_3mf_plates: a Bambu Studio / OrcaSlicer project's plates as its designer laid them out, before slicing
3
+ * (Counterpart PRD §5.5 "Plates of an imported 3MF", §8.0 item 9). Bambu Studio shows a downloaded kit as its
4
+ * plates straight away; clients show the same from here instead of parsing the project files themselves.
5
+ *
6
+ * Plates come from Metadata/model_settings.config (`<plate>` with `plater_id`, `plater_name` and the objects it
7
+ * holds) and, for a sliced file, from Metadata/plate_N.json and plate_N.gcode. A plain 3MF with no plate metadata
8
+ * is one plate. Only bounded metadata is read; nothing is extracted or run.
9
+ */
10
+ import { readSafe3mfArchive } from "../safety/archive.js";
11
+
12
+ export interface ModelPlate {
13
+ /** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
14
+ index: number;
15
+ name: string;
16
+ objects: string[];
17
+ /** The file already holds this plate's G-code. */
18
+ sliced: boolean;
19
+ /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
20
+ thumbnail_png_base64?: string;
21
+ }
22
+ export interface ModelPlates {
23
+ plate_count: number;
24
+ plates: ModelPlate[];
25
+ title?: string;
26
+ designer?: string;
27
+ licence?: string;
28
+ }
29
+
30
+ /** For the settings and plate files; the model file can be large and is only scanned. */
31
+ const MAX_METADATA_BYTES = 8 * 1024 * 1024;
32
+ const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
33
+ const MAX_PLATES = 1000;
34
+
35
+ const words = (value: string) => value
36
+ .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]!))
37
+ .replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 256);
38
+
39
+ export async function listModelPlates(filePath: string, options: { thumbnails?: boolean } = {}): Promise<ModelPlates> {
40
+ const { zip } = await readSafe3mfArchive(filePath);
41
+ const text = async (name: string) => {
42
+ const file = zip.file(name);
43
+ if (!file) return "";
44
+ const bytes = await file.async("nodebuffer");
45
+ if (bytes.length > MAX_METADATA_BYTES) throw new Error(`${name} is too large to read.`);
46
+ return bytes.toString("utf8");
47
+ };
48
+ // The model file can hold the whole mesh (a plain 3MF): scanned as bytes, never made one string.
49
+ const modelBytes = await zip.file("3D/3dmodel.model")?.async("nodebuffer");
50
+ const head = modelBytes?.subarray(0, 1024 * 1024).toString("utf8") ?? "";
51
+ if (!/<(?:\w+:)?model\b/.test(head)) throw new Error("That file is not a 3MF model.");
52
+ // An element named `tag`, plain or with a namespace prefix (<item …>, <p:item …>).
53
+ const has = (tag: string) => !!modelBytes && [" ", ">", "/", "\n", "\r", "\t"].some(end => modelBytes.includes(`<${tag}${end}`) || modelBytes.includes(`:${tag}${end}`));
54
+ const result: ModelPlates = { plate_count: 0, plates: [] };
55
+ const metadata = new Map([...head.matchAll(/<metadata\s+name="([^"]+)"[^>]*>([^<]*)<\/metadata>/g)].map(match => [match[1], words(match[2])]));
56
+ if (metadata.get("Title")) result.title = metadata.get("Title");
57
+ if (metadata.get("Designer")) result.designer = metadata.get("Designer");
58
+ if (metadata.get("License")) result.licence = metadata.get("License");
59
+
60
+ const settings = await text("Metadata/model_settings.config");
61
+ const objects = new Map([...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
62
+ const name = /<metadata\s+key="name"\s+value="([^"]*)"/.exec(match[2]);
63
+ return [match[1], words(name?.[1] ?? "")];
64
+ }));
65
+ const plates = new Map<number, ModelPlate>();
66
+ // A plate number out of range is skipped, as a slicer would not show it.
67
+ const valid = (number: number) => Number.isSafeInteger(number) && number >= 1 && number <= MAX_PLATES;
68
+ for (const match of settings.matchAll(/<plate\b[^>]*>([\s\S]*?)<\/plate>/g)) {
69
+ const id = /<metadata\s+key="plater_id"\s+value="(\d+)"/.exec(match[1]);
70
+ if (!id) continue;
71
+ const number = Number(id[1]);
72
+ if (!valid(number)) continue;
73
+ const name = /<metadata\s+key="plater_name"\s+value="([^"]*)"/.exec(match[1]);
74
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false,
75
+ objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])!] : []) });
76
+ }
77
+ for (const name of Object.keys(zip.files)) {
78
+ const match = /^Metadata\/plate_([1-9]\d*)\.(json|gcode)$/.exec(name);
79
+ if (!match) continue;
80
+ const number = Number(match[1]);
81
+ if (!valid(number)) continue;
82
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], sliced: false };
83
+ if (match[2] === "gcode") plate.sliced = true;
84
+ else {
85
+ try {
86
+ const value = JSON.parse(await text(name)) as { bbox_objects?: { name?: unknown }[] };
87
+ if (Array.isArray(value.bbox_objects)) plate.objects = value.bbox_objects
88
+ .flatMap(object => typeof object.name === "string" && object.name !== "wipe_tower" ? [words(object.name)] : []).slice(0, 200);
89
+ } catch { /* the plate keeps the objects model_settings lists */ }
90
+ }
91
+ plates.set(number, plate);
92
+ }
93
+ result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
94
+ // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
95
+ if (!result.plates.length) result.plates.push({ index: 0, name: "Plate 1", objects: [], sliced: false });
96
+ const geometry = has("item") && (has("mesh") || has("component"));
97
+ if (!geometry) {
98
+ // A sliced-only file (previews and G-code, no model): only its sliced plates can print.
99
+ result.plates = result.plates.filter(plate => plate.sliced);
100
+ if (!result.plates.length) throw new Error("This 3MF has previews and settings but no model or printable plate.");
101
+ }
102
+ if (options.thumbnails) for (const plate of result.plates) {
103
+ const file = zip.file(`Metadata/plate_${plate.index + 1}.png`);
104
+ if (!file) continue;
105
+ const bytes = await file.async("nodebuffer");
106
+ if (bytes.length <= MAX_THUMBNAIL_BYTES && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
107
+ plate.thumbnail_png_base64 = bytes.toString("base64");
108
+ }
109
+ result.plate_count = result.plates.length;
110
+ return result;
111
+ }
@@ -31,6 +31,7 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
31
31
  get_printer_filaments: "read",
32
32
  resolve_3mf_ams_slots: "read",
33
33
  list_3mf_plate_objects: "read",
34
+ list_3mf_plates: "read",
34
35
  get_stl_info: "read",
35
36
  list_templates: "read",
36
37
  list_printer_files: "read",
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import { loadSafe3mfArchive, readBoundedPrintFile } from "../safety/archive.js";
3
+ import { plainSlicerError, UNKNOWN_SLICER_ERROR } from "../slicer/slicer-messages.js";
3
4
 
4
5
  /**
5
6
  * What a client shows about a sliced file, read here so it never parses slicer formats itself (Counterpart PRD
@@ -92,13 +93,21 @@ async function readFacts(filePath: string, plateIndex: number): Promise<SlicedFi
92
93
  }
93
94
 
94
95
  /**
95
- * Bambu Studio's (or OrcaSlicer's) verdict on a slice, from its result.json: whether it failed, its own words
96
- * (the error and every plate's warning, verbatim), and how many plates it sliced.
96
+ * Bambu Studio's (or OrcaSlicer's) verdict on a slice, from its result.json: whether it failed, what a person is
97
+ * told (`message`: a plain sentence for a refusal, src/slicer/slicer-messages.ts; the plates' warnings for a slice
98
+ * that worked), the slicer's own words for the log (`slicer_message`: the error and every plate's warning,
99
+ * verbatim), and how many plates it sliced.
97
100
  */
98
- export interface SlicerReport { failed: boolean; message?: string; plate_count?: number }
101
+ export interface SlicerReport { failed: boolean; message?: string; slicer_message?: string; plate_count?: number }
99
102
 
100
103
  const clean = (text: string) => text.replace(/\r\n?/g, "\n").replace(/[\x00-\x09\x0b-\x1f\x7f]/g, " ").trim();
101
104
 
105
+ /** A refusal's report: the plain sentence, and the slicer's words kept beside it. */
106
+ export function refusalReport(words: string): SlicerReport {
107
+ const raw = clean(words).slice(0, 2000);
108
+ return { failed: true, message: plainSlicerError(raw) ?? UNKNOWN_SLICER_ERROR, ...(raw ? { slicer_message: raw } : {}) };
109
+ }
110
+
102
111
  export function slicerReport(result: unknown): SlicerReport | undefined {
103
112
  if (!result || typeof result !== "object" || Array.isArray(result)) return undefined;
104
113
  const value = result as { return_code?: unknown; error_string?: unknown; sliced_plates?: unknown };
@@ -110,6 +119,6 @@ export function slicerReport(result: unknown): SlicerReport | undefined {
110
119
  const failed = value.return_code !== 0;
111
120
  const error = typeof value.error_string === "string" ? clean(value.error_string) : "";
112
121
  const words = [...new Set([...(failed && error ? [error] : []), ...warnings])].join("\n").slice(0, 2000);
113
- if (failed) return { failed, message: words || `The slicer could not slice this model (return code ${String(value.return_code)}).` };
114
- return { failed, ...(words ? { message: words } : {}), ...(plateCount ? { plate_count: plateCount } : {}) };
122
+ if (failed) return refusalReport(words || `return code ${String(value.return_code)}`);
123
+ return { failed, ...(words ? { message: words, slicer_message: words } : {}), ...(plateCount ? { plate_count: plateCount } : {}) };
115
124
  }
package/src/index.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  import {CAMERA_STREAM_TOOLS} from "./printers/camera-tools.js";
3
3
  import { withAnnotations } from "./tool-annotations.js";
4
4
  import { withRemote } from "./counterpart/remote.js";
5
- import { slicedFileFacts, slicerReport } from "./counterpart/sliced-file.js";
5
+ import { refusalReport, slicedFileFacts, slicerReport } from "./counterpart/sliced-file.js";
6
+ import { listModelPlates } from "./counterpart/model-plates.js";
6
7
 
7
8
  /** The slicer's verdict beside its result.json (`slicer_report`). */
8
9
  function reportOf(result: unknown): { slicer_report?: ReturnType<typeof slicerReport> } {
@@ -2576,6 +2577,18 @@ class BambuPrinterMCPServer {
2576
2577
  required: ["three_mf_path"]
2577
2578
  }
2578
2579
  },
2580
+ {
2581
+ name: "list_3mf_plates",
2582
+ description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it and whether the file already holds its G-code (sliced). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2583
+ inputSchema: {
2584
+ type: "object",
2585
+ properties: {
2586
+ three_mf_path: { type: "string", description: "Path to the 3MF (a designer's project, sliced or not)" },
2587
+ include_thumbnails: { type: "boolean", description: "Include each plate's own preview PNG from the file, base64 (default false)" }
2588
+ },
2589
+ required: ["three_mf_path"]
2590
+ }
2591
+ },
2579
2592
  {
2580
2593
  name: "list_3mf_plate_objects",
2581
2594
  description: "List object IDs from a sliced 3MF plate. Use these IDs with skip_objects during a running print.",
@@ -2766,7 +2779,7 @@ class BambuPrinterMCPServer {
2766
2779
  },
2767
2780
  {
2768
2781
  name: "slice_stl",
2769
- description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. A failed slice's text starts with those words. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2782
+ description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. structuredContent.slicer_report says whether it failed; for a failure, its message is a plain sentence for a person and slicer_message keeps the slicer's words, which a failed slice's text gives after that sentence. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2770
2783
  inputSchema: {
2771
2784
  type: "object",
2772
2785
  properties: {
@@ -3902,6 +3915,12 @@ class BambuPrinterMCPServer {
3902
3915
  break;
3903
3916
  }
3904
3917
 
3918
+ case "list_3mf_plates": {
3919
+ if (typeof args?.three_mf_path !== "string" || !args.three_mf_path) throw new Error("Missing required parameter: three_mf_path");
3920
+ if (args.include_thumbnails !== undefined && typeof args.include_thumbnails !== "boolean") throw new Error("include_thumbnails must be a boolean.");
3921
+ const plates = await listModelPlates(args.three_mf_path, { thumbnails: args.include_thumbnails === true });
3922
+ return { content: [{ type: "text", text: JSON.stringify(plates) }], structuredContent: plates };
3923
+ }
3905
3924
  case "list_3mf_plate_objects": {
3906
3925
  if (!args?.three_mf_path) {
3907
3926
  throw new Error("Missing required parameter: three_mf_path");
@@ -4625,6 +4644,8 @@ class BambuPrinterMCPServer {
4625
4644
  }
4626
4645
  }
4627
4646
 
4647
+ // A client that cancels this call (it no longer wants the slice) stops the slicer.
4648
+ sliceBambuOptions.signal = extra.signal;
4628
4649
  const sliced = await this.stlManipulator.sliceSTLWithResult(
4629
4650
  String(args.stl_path), slicerType, slicerPath,
4630
4651
  activeSlicerProfile,
@@ -5138,14 +5159,19 @@ class BambuPrinterMCPServer {
5138
5159
  tool: name,
5139
5160
  ...(error instanceof PrinterRefusal ? { code: error.code } : {}),
5140
5161
  // The slicer's own result.json; the message starts with its error_string and warnings.
5141
- ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult, ...reportOf(error.slicerResult) } : {}),
5162
+ // A slicer failure always carries slicer_report: the plain sentence a person sees, the slicer's words for the log.
5163
+ // The report always says failed (a result.json that says success can still leave no output file).
5164
+ ...(error instanceof SlicerRunError ? {
5165
+ ...(error.slicerResult ? { slicer_result: error.slicerResult } : {}),
5166
+ slicer_report: { ...refusalReport(error.words), message: error.plain ?? error.words.slice(0, 2000) },
5167
+ } : {}),
5142
5168
  };
5143
5169
 
5144
5170
  // MCP clients validate structuredContent against a declared outputSchema even on
5145
5171
  // errors (SDK 1.32 Client.callTool), so those tools return the error as text only.
5146
5172
  return {
5147
- // A slicer failure leads with the slicer's own words.
5148
- content: [{ type: "text", text: error instanceof SlicerRunError && error.slicerText ? message : `Error: ${message}` }],
5173
+ // A slicer's refusal leads with its plain sentence, then the slicer's own words.
5174
+ content: [{ type: "text", text: error instanceof SlicerRunError && error.plain ? message : `Error: ${message}` }],
5149
5175
  ...(OUTPUT_SCHEMA_TOOLS.has(name) ? {} : { structuredContent: structured }),
5150
5176
  isError: true,
5151
5177
  };
@@ -396,7 +396,12 @@ export async function inspectPrintFile(filePath: string, options: {model:string;
396
396
  !['','XY','UV'].includes(position) || [...position].some(key=>!inRange(args,key,0,limit[key]))) invalid();
397
397
  continue;
398
398
  }
399
- if(!['M117','M118','M1002','M1006','M900','M970','M983.1','G383'].includes(code) && /[GM]\s*\d/i.test(argumentsText)) fail('multiple commands on one line are unsupported');
399
+ // Bambu Studio's skip-object start carries one base64 mask of the layer's objects (M624 /g8C/B8AAAA=), whose
400
+ // letters and digits can read as a command; only that exact one-token form is exempt.
401
+ const mask = argumentsText.trim();
402
+ // A whole base64 value (length a multiple of 4) that doesn't itself start like a command (M104S300, G28, T1).
403
+ const objectMask = code==='M624' && /^[A-Za-z0-9+/]+={0,2}$/.test(mask) && mask.length % 4 === 0 && !/^[GMT]\d/i.test(mask);
404
+ if(!objectMask && !['M117','M118','M1002','M1006','M900','M970','M983.1','G383'].includes(code) && /[GM]\s*\d/i.test(argumentsText)) fail('multiple commands on one line are unsupported');
400
405
  // Coordinated extrusion closes the startup-only allowance even when the
401
406
  // source omits layer comments. Retraction also closes it conservatively.
402
407
  if(['G0','G1','G2','G3'].includes(code) && /E/i.test(argumentsText) && /[XY]/i.test(argumentsText)) closeStartupWindow();
@@ -793,7 +793,11 @@ async function writeTemp(
793
793
  const safe = leafName.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 64);
794
794
  const filename = `flat-${kind}-${safe}-${hash}.json`;
795
795
  const out = path.join(tempDir, filename);
796
- await fs.writeFile(out, serialized, "utf8");
796
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
797
+ // rename it into place, so a reader never sees it truncated or half-written.
798
+ const partial = `${out}.${crypto.randomUUID()}.partial`;
799
+ await fs.writeFile(partial, serialized, "utf8");
800
+ await fs.rename(partial, out);
797
801
  return out;
798
802
  }
799
803
 
@@ -12,6 +12,8 @@ const SUPPORTED_OPTIONS = new Set([
12
12
  'nozzleType', 'nozzleVolumeType', 'slicePlate',
13
13
  // Written into the uploaded process preset before the request, not sent as API options.
14
14
  'processOverrides',
15
+ // The request's cancellation, honoured through isCancelled; never sent.
16
+ 'signal',
15
17
  ]);
16
18
 
17
19
  function configuration(): { base: string; headers: Record<string, string>; mode: string; timeout: number } {
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A slicer's refusal in plain words. Bambu Studio, OrcaSlicer, PrusaSlicer and CuraEngine word their errors for
3
+ * their own windows ("One of the plate is empty or has no object fully inside it..."); a client shows the person
4
+ * the sentence here and keeps the slicer's own words for its logs (`slicer_report.slicer_message`).
5
+ *
6
+ * The phrases are the slicers' own strings: Bambu Studio 02.09 and OrcaSlicer 2.3 (their CLI and validation
7
+ * messages), PrusaSlicer 2.9.2 (src/libslic3r/Print.cpp, src/CLI/ProcessActions.cpp) and CuraEngine
8
+ * (src/FffPolygonGenerator.cpp). Matching is on a lowercase fragment, so a version that adds a prefix or a
9
+ * plate number still matches.
10
+ */
11
+ const PLAIN: { phrases: string[]; sentence: string }[] = [
12
+ {
13
+ phrases: [
14
+ "one of the plate is empty or has no object fully inside it",
15
+ "a plate is empty or has no object fully inside it",
16
+ "cannot send the print job for empty plate",
17
+ "no object is fully inside the print volume",
18
+ "found no objects in print volume to slice",
19
+ "found no objects in print volume after skip",
20
+ "all objects are outside of the print volume",
21
+ "arrangement ignored the following objects which can't fit into a single bed",
22
+ ],
23
+ sentence: "Nothing on this plate can be printed: no part sits fully on the bed. A part is off the plate or across its edge, or the model is bigger than the bed.",
24
+ },
25
+ {
26
+ phrases: [
27
+ "laid over the boundary of plate or exceeds the height limit",
28
+ "layed over the boundary of plate",
29
+ "laid over the plate boundaries",
30
+ "partly inside, can not be sliced",
31
+ "located over the boundary of the heated bed",
32
+ ],
33
+ sentence: "A part sits across the edge of the plate, or is taller than the printer can print, so it can't be sliced as it is placed.",
34
+ },
35
+ {
36
+ phrases: ["exceeds the maximum build volume height", "exceeds the printable height"],
37
+ sentence: "The model is taller than the printer can print.",
38
+ },
39
+ {
40
+ phrases: ["object too large", "scale to fit error", "printable area/volume reduced"],
41
+ sentence: "The model is larger than the printer's bed.",
42
+ },
43
+ {
44
+ phrases: ["found g-code outside of the printable area", "found g-code in unprintable area", "g-code path exceeds the printable range"],
45
+ sentence: "The print would go outside the area the printer can reach, usually a brim, skirt, support or the wipe tower near an edge. Move the model further onto the plate.",
46
+ },
47
+ {
48
+ phrases: ["g-code path conflicts found", "found gcode path conflicts between object"],
49
+ sentence: "Two parts are so close that their print paths overlap. Move them apart.",
50
+ },
51
+ {
52
+ phrases: ["the supplied settings will cause an empty print", "there are no non-empty layers"],
53
+ sentence: "These settings would print nothing: no layer of the model has anything to print.",
54
+ },
55
+ ];
56
+
57
+ /** The plain sentence for a slicer's error, or undefined when the words aren't one this knows. */
58
+ export function plainSlicerError(words: string): string | undefined {
59
+ const text = words.toLowerCase();
60
+ return PLAIN.find(entry => entry.phrases.some(phrase => text.includes(phrase)))?.sentence;
61
+ }
62
+
63
+ /** What a person is told when the slicer refused with words this doesn't know. */
64
+ export const UNKNOWN_SLICER_ERROR = "The slicer couldn't slice this model. Its own message is kept for the log.";
@@ -12,11 +12,14 @@ import * as crypto from 'crypto';
12
12
  import { execFile } from 'child_process';
13
13
  import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
14
14
  import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
15
+ import { plainSlicerError, UNKNOWN_SLICER_ERROR } from '../slicer/slicer-messages.js';
15
16
  import { applyProcessOverrides, type ProcessOverrides } from '../slicer/process-overrides.js';
16
17
  import { profileJsonFiles } from '../slicer/profile-files.js';
17
18
  import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
18
19
  import { sliceWithOrcaApi, validateRemoteSliceOptions } from '../slicer/remote-slicer.js';
19
20
 
21
+ /** How long a slice's folder (its sliced file and result.json) is kept: a day, then a later slice removes it. */
22
+ const SLICE_FOLDER_LIFETIME_MS = 24 * 60 * 60 * 1000;
20
23
  const readFileAsync = promisify(fs.readFile);
21
24
  const writeFileAsync = promisify(fs.writeFile);
22
25
  const BAMBU_PROFILE_ROOTS = [
@@ -163,6 +166,8 @@ function configuredBambuProfileDirs(): string[] {
163
166
 
164
167
  // Bambu-compatible slicer CLI flags exposed via the slice_stl tool
165
168
  export interface BambuSliceOptions {
169
+ /** The request's own cancellation: aborting it stops the slicer (the MCP client cancelled the call). */
170
+ signal?: AbortSignal;
166
171
  uptodate?: boolean; // --uptodate: update 3MF configs to latest presets
167
172
  repetitions?: number; // STL: --clone-objects N; 3MF: --repetitions N on the selected plate
168
173
  orient?: boolean; // --orient 1: auto-orient for printability
@@ -228,11 +233,21 @@ export type SliceOutput = { path: string; slicer_result?: SlicerResult };
228
233
  */
229
234
  export class SlicerRunError extends Error {
230
235
  readonly slicerText: string;
236
+ /** What a person is told for a slicer's refusal: a plain sentence, never its own words (src/slicer/slicer-messages.ts). */
237
+ readonly plain?: string;
238
+ /** The slicer's words and this server's detail, after the plain sentence: what slicer_report.slicer_message keeps. */
239
+ readonly words: string;
231
240
  constructor(detail: string, readonly slicerResult?: SlicerResult) {
232
241
  const slicerText = slicerResult ? slicerResultText(slicerResult) : "";
233
- super(slicerText ? `${slicerText}\n${detail}` : detail);
242
+ const words = slicerText ? `${slicerText}\n${detail}` : detail;
243
+ // A known refusal, or one in the slicer's own words, is said plainly. A fault of the setup (no slicer, a crash,
244
+ // no output) stays in this server's own words, which say what to fix.
245
+ const plain = plainSlicerError(words) ?? (slicerText ? UNKNOWN_SLICER_ERROR : undefined);
246
+ super(plain ? `${plain}\nThe slicer said: ${words}` : words);
234
247
  this.name = "SlicerRunError";
235
248
  this.slicerText = slicerText;
249
+ this.plain = plain;
250
+ this.words = words;
236
251
  }
237
252
  }
238
253
 
@@ -331,6 +346,24 @@ export class STLManipulator extends EventEmitter {
331
346
  return crypto.randomUUID();
332
347
  }
333
348
 
349
+ /**
350
+ * A new folder for one slice's outputs, under TEMP_DIR/slices. A sliced file's path stays valid for a day after
351
+ * its slice (callers print from it); older slice folders are removed as new slices start.
352
+ */
353
+ private async newSliceFolder(operationId: string): Promise<string> {
354
+ const root = path.join(this.tempDir, 'slices');
355
+ await fs.promises.mkdir(root, { recursive: true });
356
+ const cutoff = Date.now() - SLICE_FOLDER_LIFETIME_MS;
357
+ for (const name of await fs.promises.readdir(root).catch(() => [] as string[])) {
358
+ const folder = path.join(root, name);
359
+ const info = await fs.promises.stat(folder).catch(() => undefined);
360
+ if (info?.isDirectory() && info.mtimeMs < cutoff) await fs.promises.rm(folder, { recursive: true, force: true }).catch(() => undefined);
361
+ }
362
+ const folder = path.join(root, operationId);
363
+ await fs.promises.mkdir(folder);
364
+ return folder;
365
+ }
366
+
334
367
  private getAvailableProfileRoots(): string[] {
335
368
  const selectedRoot = process.env.BAMBU_PROFILES_ROOT;
336
369
  return [
@@ -445,7 +478,11 @@ export class STLManipulator extends EventEmitter {
445
478
  const serialized = JSON.stringify(value, null, 2);
446
479
  const hash = crypto.createHash('sha256').update(serialized).digest('hex').slice(0, 16);
447
480
  const outPath = path.join(this.tempDir, `${outputBase}_${suffix}_${hash}.json`);
448
- fs.writeFileSync(outPath, serialized);
481
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
482
+ // rename it into place, so a reader never sees it truncated or half-written.
483
+ const partial = `${outPath}.${crypto.randomUUID()}.partial`;
484
+ fs.writeFileSync(partial, serialized);
485
+ fs.renameSync(partial, outPath);
449
486
  return outPath;
450
487
  }
451
488
 
@@ -1795,6 +1832,13 @@ export class STLManipulator extends EventEmitter {
1795
1832
  ): Promise<SliceOutput> {
1796
1833
  const operationId = this.generateOperationId();
1797
1834
  this.activeOperations.set(operationId, true);
1835
+ // A cancelled request stops its slice: the slicer is killed (below) instead of finishing a slice nobody reads.
1836
+ const signal = bambuOptions?.signal;
1837
+ const cancel = () => { if (this.activeOperations.has(operationId)) this.activeOperations.set(operationId, false); };
1838
+ if (signal?.aborted) {
1839
+ this.activeOperations.delete(operationId);
1840
+ throw new Error("Slicing operation cancelled");
1841
+ }
1798
1842
 
1799
1843
  if (slicerType !== 'orca-slicer-api' && isPathLikeExecutable(slicerPath) && !fs.existsSync(slicerPath)) {
1800
1844
  throw new Error(`Slicer executable not found at: ${slicerPath}`);
@@ -1815,8 +1859,11 @@ export class STLManipulator extends EventEmitter {
1815
1859
  let cliResult: CliResultSource | undefined;
1816
1860
  const orcaTemporaryDirectories: string[] = [];
1817
1861
  const temporaryFiles: string[] = [];
1862
+ // This slice's own folder (local Bambu-compatible CLI): removed if the slice fails or is cancelled.
1863
+ let sliceDir: string | undefined;
1818
1864
 
1819
1865
  try {
1866
+ signal?.addEventListener('abort', cancel, { once: true });
1820
1867
  if (progressCallback) progressCallback(0, `Starting slicing with ${slicerType}...`);
1821
1868
 
1822
1869
  switch (slicerType) {
@@ -1865,7 +1912,13 @@ export class STLManipulator extends EventEmitter {
1865
1912
  if (slicerProfile && !fs.existsSync(slicerProfile)) throw new Error('Remote slicing process profile does not exist.');
1866
1913
  }
1867
1914
  const profileSlicerType = remote ? 'orcaslicer' : slicerType;
1868
- const bambuOutputPath = path.join(this.tempDir, outputBase + (remote ? `_${operationId}` : '') + '_sliced.3mf');
1915
+ // Every local slice writes into a folder of its own, so two slices at once, even of same-named inputs, never
1916
+ // read, replace or delete each other's files. Bambu Studio's CLI (v02.08.02.61) writes fixed names into
1917
+ // --outputdir: result.json, each plate's G-code as plate_<n>.gcode (and its .tmp) before packing it into
1918
+ // the 3MF, and the exported 3MF's .tmp; its own scratch files under the system temp dir are per process.
1919
+ const bambuOutputPath = remote
1920
+ ? path.join(this.tempDir, `${outputBase}_${operationId}_sliced.3mf`)
1921
+ : path.join(sliceDir = await this.newSliceFolder(operationId), `${outputBase}_sliced.3mf`);
1869
1922
  const outputDir = path.dirname(bambuOutputPath);
1870
1923
  const selectedProfilesRoot = detectProfilesRoot(remote ? undefined : slicerPath, profileSlicerType);
1871
1924
  const profilesRoot = !remote && profileSlicerType === 'orcaslicer'
@@ -2107,6 +2160,8 @@ export class STLManipulator extends EventEmitter {
2107
2160
  return slicerResult ? { path: outputFilePath, slicer_result: slicerResult } : { path: outputFilePath };
2108
2161
  } catch (error) {
2109
2162
  console.error(`Slicing failed for ${stlFilePath}:`, error);
2163
+ // Nothing in a failed or cancelled slice's folder is handed back (its result.json is already in the error).
2164
+ if (sliceDir) await fs.promises.rm(sliceDir, { recursive: true, force: true }).catch(() => undefined);
2110
2165
  this.emit('operationError', {
2111
2166
  operationId,
2112
2167
  type: 'slice',
@@ -2114,6 +2169,7 @@ export class STLManipulator extends EventEmitter {
2114
2169
  });
2115
2170
  throw error;
2116
2171
  } finally {
2172
+ signal?.removeEventListener('abort', cancel);
2117
2173
  this.activeOperations.delete(operationId);
2118
2174
  for (const file of temporaryFiles) {
2119
2175
  await fs.promises.rm(file, { force: true }).catch(error => console.error('Could not remove a temporary mesh:', error));
@@ -54,6 +54,7 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
54
54
  // Local reads
55
55
  inspect_print_file: READ_LOCAL,
56
56
  list_3mf_plate_objects: READ_LOCAL,
57
+ list_3mf_plates: READ_LOCAL,
57
58
  get_stl_info: READ_LOCAL,
58
59
  list_templates: READ_LOCAL,
59
60
  get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory