bambu-printer-mcp 1.1.72 → 1.1.74

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.
@@ -10,16 +10,16 @@ import fs from "node:fs/promises";
10
10
  import { createReadStream, readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, rmSync } from "node:fs";
11
11
  import path from "node:path";
12
12
  import os from "node:os";
13
- import { Readable } from "node:stream";
14
13
  import { readSafe3mfArchive } from "../safety/archive.js";
15
14
  import { inspectPrintFile } from "../safety/print-file.js";
16
15
  import { isDualNozzleModel, normalizeModel, validateTemperature } from "../safety/limits.js";
17
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange } from "../ams-mapping.js";
16
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, describeAmsTrayRange, studioAmsMapping } from "../ams-mapping.js";
18
17
  import { describeHmsKey, hiddenHmsKeys, hiddenHmsNotices, reportedHmsKey, unchippedNozzles, validatePrinterState, manualHeatingRequirements } from "../safety/printer-state.js";
19
18
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName, normalizedRemotePath, cancelPendingPrinterOperations } from "../safety/artifact.js";
20
19
  import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
21
20
  import { resolveStudioPrintOptions, usedNozzleCount } from "../studio-print-options.js";
22
21
  import { Client as FTPClient } from "basic-ftp";
22
+ import { uploadBytes } from "./ftp-upload.js";
23
23
  import * as mqtt from "mqtt";
24
24
  import { BambuClient, GCodeFileCommand, GCodeLineCommand, PushAllCommand, UpdateFanCommand, UpdateLightCommand, } from "bambu-node";
25
25
  /**
@@ -1016,7 +1016,9 @@ export class BambuImplementation {
1016
1016
  if (options.amsMapping && options.amsMapping.length > 0) {
1017
1017
  for (const v of options.amsMapping)
1018
1018
  validateTrayValue(v, "ams_mapping");
1019
- baseMapping = options.amsMapping.slice();
1019
+ // Bambu Studio sends a tray only for the filaments the plate prints and -1 for every other project filament
1020
+ // (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500): so does this route.
1021
+ baseMapping = studioAmsMapping(options.amsMapping, inspection.usedFilamentPositions);
1020
1022
  }
1021
1023
  else if (options.amsSlots && options.amsSlots.length > 0) {
1022
1024
  for (const v of options.amsSlots)
@@ -1086,7 +1088,13 @@ export class BambuImplementation {
1086
1088
  validatePrinterState(confirmedStatus, requirements);
1087
1089
  this.assertPrintPreflight(confirmedStatus, preflight);
1088
1090
  assertActive();
1089
- await this.ftpUpload(host, token, options.filePath, remoteUploadPath);
1091
+ try {
1092
+ await this.ftpUpload(host, token, options.filePath, remoteUploadPath);
1093
+ }
1094
+ catch (error) {
1095
+ // Nothing has been sent to the printer but (part of) a file, so the print certainly did not start.
1096
+ throw new PrinterRefusal("printer-upload-failed", `The print file did not reach the printer (${error instanceof Error ? error.message : String(error)}). No print was started.`);
1097
+ }
1090
1098
  // Uploads can be long. Recheck current state before the command is dispatched.
1091
1099
  const dispatchStatus = await this.getSafetyStatus(host, serial, token);
1092
1100
  if (legacyContainer)
@@ -2264,7 +2272,8 @@ export class BambuImplementation {
2264
2272
  throw new Error(`Refusing to overwrite existing printer file ${absoluteRemote}. Choose a new filename.`);
2265
2273
  }
2266
2274
  const fileData = await fs.readFile(localPath);
2267
- await client.uploadFrom(Readable.from(fileData), absoluteRemote);
2275
+ // Small writes, so a multi-megabyte job on a slow SD card is not mistaken for a stall.
2276
+ await uploadBytes(client, fileData, absoluteRemote);
2268
2277
  }
2269
2278
  finally {
2270
2279
  client.close();
@@ -0,0 +1,17 @@
1
+ import type { Client as FTPClient } from "basic-ftp";
2
+ /** Bytes per write on the FTPS data socket; matches fs.createReadStream's default. */
3
+ export declare const FTP_UPLOAD_CHUNK_BYTES: number;
4
+ /**
5
+ * Store bytes on the printer in small writes.
6
+ *
7
+ * basic-ftp's TransferWatchdog reports a stall ("Timeout (data socket)") when
8
+ * the data socket's bytesWritten stops changing while data is still queued.
9
+ * Readable.from(buffer) hands the whole file over as one write, which counts in
10
+ * bytesWritten at once; while the printer drains it at SD-card speed (a few
11
+ * hundred KB/s on a P1S) the count never moves, so a multi-megabyte job is
12
+ * declared stalled after the timeout although its bytes are still flowing.
13
+ * Small writes move the count as each one completes, so the watchdog only fires
14
+ * when the printer stops taking data. The bytes are the ones already read and
15
+ * inspected; nothing is re-read from disk.
16
+ */
17
+ export declare function uploadBytes(client: FTPClient, bytes: Buffer, remotePath: string, chunkBytes?: number): Promise<void>;
@@ -0,0 +1,23 @@
1
+ import { Readable } from "node:stream";
2
+ /** Bytes per write on the FTPS data socket; matches fs.createReadStream's default. */
3
+ export const FTP_UPLOAD_CHUNK_BYTES = 64 * 1024;
4
+ function* chunks(bytes, size) {
5
+ for (let offset = 0; offset < bytes.length; offset += size)
6
+ yield bytes.subarray(offset, offset + size);
7
+ }
8
+ /**
9
+ * Store bytes on the printer in small writes.
10
+ *
11
+ * basic-ftp's TransferWatchdog reports a stall ("Timeout (data socket)") when
12
+ * the data socket's bytesWritten stops changing while data is still queued.
13
+ * Readable.from(buffer) hands the whole file over as one write, which counts in
14
+ * bytesWritten at once; while the printer drains it at SD-card speed (a few
15
+ * hundred KB/s on a P1S) the count never moves, so a multi-megabyte job is
16
+ * declared stalled after the timeout although its bytes are still flowing.
17
+ * Small writes move the count as each one completes, so the watchdog only fires
18
+ * when the printer stops taking data. The bytes are the ones already read and
19
+ * inspected; nothing is re-read from disk.
20
+ */
21
+ export async function uploadBytes(client, bytes, remotePath, chunkBytes = FTP_UPLOAD_CHUNK_BYTES) {
22
+ await client.uploadFrom(Readable.from(chunks(bytes, chunkBytes)), remotePath);
23
+ }
package/dist/refusal.d.ts CHANGED
@@ -6,8 +6,9 @@
6
6
  * - printer-command-rejected: the printer refused the print command itself (for Bambu, HMS 0500-0500-0001-0007,
7
7
  * MQTT command verification); the file was uploaded and the command sent, but nothing is printing.
8
8
  * - printer-not-ready: the printer isn't in a state that can start a print (busy, paused, failed, unknown).
9
+ * - printer-upload-failed: the print file didn't reach the printer, so no print command was sent.
9
10
  */
10
- export declare const REFUSAL_CODES: readonly ["printer-command-rejected", "printer-not-ready"];
11
+ export declare const REFUSAL_CODES: readonly ["printer-command-rejected", "printer-not-ready", "printer-upload-failed"];
11
12
  export type RefusalCode = (typeof REFUSAL_CODES)[number];
12
13
  export declare class PrinterRefusal extends Error {
13
14
  readonly code: RefusalCode;
package/dist/refusal.js CHANGED
@@ -6,8 +6,9 @@
6
6
  * - printer-command-rejected: the printer refused the print command itself (for Bambu, HMS 0500-0500-0001-0007,
7
7
  * MQTT command verification); the file was uploaded and the command sent, but nothing is printing.
8
8
  * - printer-not-ready: the printer isn't in a state that can start a print (busy, paused, failed, unknown).
9
+ * - printer-upload-failed: the print file didn't reach the printer, so no print command was sent.
9
10
  */
10
- export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready"];
11
+ export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready", "printer-upload-failed"];
11
12
  export class PrinterRefusal extends Error {
12
13
  constructor(code, message) {
13
14
  super(message);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.72",
3
+ "version": "1.1.74",
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": {
@@ -132,3 +132,13 @@ export function studioAmsMappingInfo(filaments: ProjectFilament[], mapping: numb
132
132
  };
133
133
  });
134
134
  }
135
+
136
+ /**
137
+ * A project-level ams_mapping as Bambu Studio sends it: the caller's tray for each filament the selected plate prints,
138
+ * -1 for every project filament it doesn't (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500,
139
+ * maps only the plate's own filaments). A tray for an unused filament is never sent to the printer.
140
+ */
141
+ export function studioAmsMapping(mapping: number[], usedPositions: number[]): number[] {
142
+ const used = new Set(usedPositions);
143
+ return mapping.map((tray, position) => used.has(position) ? tray : -1);
144
+ }
@@ -8,6 +8,7 @@
8
8
  * is one plate. Only bounded metadata is read; nothing is extracted or run.
9
9
  */
10
10
  import { readSafe3mfArchive } from "../safety/archive.js";
11
+ import { plateFilaments, type PlateFilament, type PlateLayout } from "./plate-filaments.js";
11
12
 
12
13
  export interface ModelPlate {
13
14
  /** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
@@ -22,6 +23,12 @@ export interface ModelPlate {
22
23
  instances: { identify_id: number; name: string }[];
23
24
  /** The file already holds this plate's G-code. */
24
25
  sliced: boolean;
26
+ /**
27
+ * The project filaments this plate prints with, and only those (counterpart/1): what a client asks the person to
28
+ * choose spools for. From the slice when the file holds one (plate_N.json filament_ids), otherwise worked out as
29
+ * Bambu Studio does for the objects on this plate (see plate-filaments.ts). Filaments of other plates never appear.
30
+ */
31
+ filaments: PlateFilament[];
25
32
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
26
33
  thumbnail_png_base64?: string;
27
34
  }
@@ -31,6 +38,11 @@ export interface ModelPlates {
31
38
  title?: string;
32
39
  designer?: string;
33
40
  licence?: string;
41
+ /**
42
+ * Every filament the project declares (project_settings.config), used on a plate or not, from 1: slice_stl takes one
43
+ * load_filaments profile per declared filament. Empty for a 3MF that declares none.
44
+ */
45
+ project_filaments: PlateFilament[];
34
46
  }
35
47
 
36
48
  /** For the settings and plate files; the model file can be large and is only scanned. */
@@ -58,7 +70,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
58
70
  if (!/<(?:\w+:)?model\b/.test(head)) throw new Error("That file is not a 3MF model.");
59
71
  // An element named `tag`, plain or with a namespace prefix (<item …>, <p:item …>).
60
72
  const has = (tag: string) => !!modelBytes && [" ", ">", "/", "\n", "\r", "\t"].some(end => modelBytes.includes(`<${tag}${end}`) || modelBytes.includes(`:${tag}${end}`));
61
- const result: ModelPlates = { plate_count: 0, plates: [] };
73
+ const result: ModelPlates = { plate_count: 0, plates: [], project_filaments: [] };
62
74
  const metadata = new Map([...head.matchAll(/<metadata\s+name="([^"]+)"[^>]*>([^<]*)<\/metadata>/g)].map(match => [match[1], words(match[2])]));
63
75
  if (metadata.get("Title")) result.title = metadata.get("Title");
64
76
  if (metadata.get("Designer")) result.designer = metadata.get("Designer");
@@ -70,6 +82,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
70
82
  return [match[1], words(name?.[1] ?? "")];
71
83
  }));
72
84
  const plates = new Map<number, ModelPlate>();
85
+ const layouts = new Map<number, PlateLayout>();
73
86
  // A plate number out of range is skipped, as a slicer would not show it.
74
87
  const valid = (number: number) => Number.isSafeInteger(number) && number >= 1 && number <= MAX_PLATES;
75
88
  for (const match of settings.matchAll(/<plate\b[^>]*>([\s\S]*?)<\/plate>/g)) {
@@ -84,7 +97,13 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
84
97
  return object !== undefined && Number.isSafeInteger(identify) && identify > 0
85
98
  ? [{ identify_id: identify, name: objects.get(object) ?? "" }] : [];
86
99
  }).slice(0, MAX_INSTANCES_PER_PLATE);
87
- plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances,
100
+ layouts.set(number, { number, objectIds: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].map(item => item[1]),
101
+ instances: [...match[1].matchAll(/<model_instance>([\s\S]*?)<\/model_instance>/g)].flatMap(instance => {
102
+ const objectId = /<metadata\s+key="object_id"\s+value="(\d+)"/.exec(instance[1])?.[1];
103
+ const instanceId = Number(/<metadata\s+key="instance_id"\s+value="(\d+)"/.exec(instance[1])?.[1] ?? 0);
104
+ return objectId ? [{ objectId, instanceId }] : [];
105
+ }) });
106
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [],
88
107
  objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])!] : []) });
89
108
  }
90
109
  for (const name of Object.keys(zip.files)) {
@@ -92,11 +111,15 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
92
111
  if (!match) continue;
93
112
  const number = Number(match[1]);
94
113
  if (!valid(number)) continue;
95
- const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false };
114
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [] };
115
+ const layout = layouts.get(number) ?? { number, objectIds: [] };
116
+ layouts.set(number, layout);
96
117
  if (match[2] === "gcode") plate.sliced = true;
97
118
  else {
98
119
  try {
99
- const value = JSON.parse(await text(name)) as { bbox_objects?: { name?: unknown }[] };
120
+ const value = JSON.parse(await text(name)) as { bbox_objects?: { name?: unknown }[]; filament_ids?: unknown };
121
+ // Studio's record of the filaments this plate's slice uses (0-based project positions).
122
+ if (Array.isArray(value.filament_ids)) layout.slicedFilamentIds = value.filament_ids.filter((id): id is number => Number.isInteger(id) && id >= 0 && id < 64);
100
123
  if (Array.isArray(value.bbox_objects)) plate.objects = value.bbox_objects
101
124
  .flatMap(object => typeof object.name === "string" && object.name !== "wipe_tower" ? [words(object.name)] : []).slice(0, 200);
102
125
  } catch { /* the plate keeps the objects model_settings lists */ }
@@ -105,13 +128,25 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
105
128
  }
106
129
  result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
107
130
  // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
108
- if (!result.plates.length) result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false });
131
+ if (!result.plates.length) {
132
+ result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [] });
133
+ // Without plates every object is on the one plate.
134
+ layouts.set(1, { number: 1, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
135
+ }
109
136
  const geometry = has("item") && (has("mesh") || has("component"));
110
137
  if (!geometry) {
111
138
  // A sliced-only file (previews and G-code, no model): only its sliced plates can print.
112
139
  result.plates = result.plates.filter(plate => plate.sliced);
113
140
  if (!result.plates.length) throw new Error("This 3MF has previews and settings but no model or printable plate.");
114
141
  }
142
+ // A slice's G-code without its plate_N.json gives no filament list: the derivation stands.
143
+ // A model file too large to read whole: its resources come first and its build items last (a plain 3MF).
144
+ const modelText = !modelBytes ? "" : modelBytes.length <= 64 * 1024 * 1024 ? modelBytes.toString("utf8")
145
+ : `${head}${modelBytes.subarray(-1024 * 1024).toString("utf8")}`;
146
+ const filaments = await plateFilaments(zip, settings, modelText,
147
+ result.plates.map(plate => layouts.get(plate.index + 1) ?? { number: plate.index + 1, objectIds: [] }));
148
+ for (const plate of result.plates) plate.filaments = filaments.plates.get(plate.index + 1) ?? [];
149
+ result.project_filaments = filaments.project;
115
150
  if (options.thumbnails) for (const plate of result.plates) {
116
151
  const file = zip.file(`Metadata/plate_${plate.index + 1}.png`);
117
152
  if (!file) continue;
@@ -0,0 +1,338 @@
1
+ /**
2
+ * The project filaments each plate of a Bambu Studio / OrcaSlicer 3MF prints with, worked out the way Bambu Studio
3
+ * does it (v02.08.02.61), so a client asks the person to choose spools only for the filaments that plate uses.
4
+ *
5
+ * - A sliced plate: Studio's own record, Metadata/plate_N.json `filament_ids` (0-based), written from the slice.
6
+ * - An unsliced plate: PartPlate::get_extruders_under_cli (src/slic3r/GUI/PartPlate.cpp:1298-1420) over the objects
7
+ * with an instance on the plate (model_settings.config <model_instance>; an instance with printable="0" in the
8
+ * 3dmodel.model build is skipped, PartPlate.cpp:1321):
9
+ * - each volume's ModelVolume::get_extruders (src/libslic3r/Model.cpp:3357-3412): negative parts, support blockers
10
+ * and enforcers print nothing; the volume's painted states (mmu_segmentation, `paint_color`); the volume's own
11
+ * extruder (ModelVolume::extruder_id, Model.cpp:3295-3306: the part's, else the object's, else 1) unless paint
12
+ * covers every facet of a model part; and the volume's wall/solid/sparse infill filaments, else the object's;
13
+ * - the object's layer-range extruders (Metadata/layer_config_ranges.xml, by 1-based model object index);
14
+ * - the object's feature filaments when separate_filaments_for_features is on;
15
+ * - the support and support-interface filaments when the object (or the project) prints support or a raft;
16
+ * - the plate's tool changes (Metadata/custom_gcode_per_layer.xml, CustomGCode::ToolChange = 2,
17
+ * PartPlate.cpp:1263-1274).
18
+ * Painting is decoded as FacetsAnnotation::set_triangle_from_string (Model.cpp:4631-4650) and
19
+ * TriangleSelector::deserialize (src/libslic3r/TriangleSelector.cpp:2111-2139) read it; this is a reimplementation
20
+ * from that documented behaviour, not Studio's code.
21
+ *
22
+ * Only bounded metadata and mesh text are read; nothing is extracted or run.
23
+ */
24
+ import type JSZip from "jszip";
25
+
26
+ export interface PlateFilament {
27
+ /** 1-based project filament number: slice_stl's load_filaments/filament_colours position, print_3mf's ams_mapping index + 1. */
28
+ index: number;
29
+ /** As the project declares it (project_settings.config filament_colour), #RRGGBB. */
30
+ colour?: string;
31
+ /** project_settings.config filament_type. */
32
+ material?: string;
33
+ /** project_settings.config filament_ids (Bambu's filament id, e.g. GFA00). */
34
+ filament_id?: string;
35
+ /** The first part (else object) on this plate that prints with it; absent for support, painting or tool changes only. */
36
+ name?: string;
37
+ }
38
+
39
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
40
+ const MAX_MESH_BYTES = 64 * 1024 * 1024;
41
+ const MAX_MESH_TOTAL = 256 * 1024 * 1024;
42
+ const MAX_FILAMENT = 64;
43
+
44
+ const words = (value: string) => value
45
+ .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]!))
46
+ .replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 256);
47
+
48
+ type Settings = Map<string, string>;
49
+ interface Part { id: string; subtype: string; name: string; settings: Settings }
50
+ interface ObjectEntry { id: string; name: string; settings: Settings; parts: Part[] }
51
+
52
+ const metadataOf = (block: string): Settings => new Map([...block.matchAll(/<metadata\s+key="([^"]+)"\s+value="([^"]*)"\s*\/?>/g)].map(match => [match[1], match[2]]));
53
+
54
+ /** model_settings.config objects with their own settings and parts (parts never nest). */
55
+ export function readModelObjects(settings: string): ObjectEntry[] {
56
+ return [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
57
+ const parts = [...match[2].matchAll(/<part\b([^>]*)>([\s\S]*?)<\/part>/g)].map(part => {
58
+ const own = metadataOf(part[2]);
59
+ return { id: /\bid="(\d+)"/.exec(part[1])?.[1] ?? "", subtype: /\bsubtype="([^"]+)"/.exec(part[1])?.[1] ?? "normal_part", name: words(own.get("name") ?? ""), settings: own };
60
+ });
61
+ const own = metadataOf(match[2].replace(/<part\b[^>]*>[\s\S]*?<\/part>/g, ""));
62
+ return { id: match[1], name: words(own.get("name") ?? ""), settings: own, parts };
63
+ });
64
+ }
65
+
66
+ /** An integer setting (Studio stores "0"/"1"/"3" strings; a project list keeps its first value). */
67
+ function intOf(value: unknown): number | undefined {
68
+ const first = Array.isArray(value) ? value[0] : value;
69
+ if (typeof first === "number" && Number.isInteger(first)) return first;
70
+ if (typeof first !== "string" || !/^\s*-?\d+\s*$/.test(first)) return undefined;
71
+ return Number(first);
72
+ }
73
+ function boolOf(value: unknown): boolean | undefined {
74
+ const first = Array.isArray(value) ? value[0] : value;
75
+ if (typeof first === "boolean") return first;
76
+ if (typeof first !== "string") return undefined;
77
+ if (/^(?:1|true)$/i.test(first.trim())) return true;
78
+ if (/^(?:0|false)$/i.test(first.trim())) return false;
79
+ return undefined;
80
+ }
81
+
82
+ /**
83
+ * The filament states a painted facet string holds (0 is "the volume's own filament"). Studio's string is hex,
84
+ * read last character first, each digit four bits low bit first, so the nibbles are the digits in reverse order.
85
+ * Each node is one nibble: two low bits are the split-side count (children = sides + 1); a leaf's state is the high
86
+ * two bits, or, when both are set, 3 + the next nibble + 15 for every preceding 0b1111 nibble.
87
+ */
88
+ export function paintedStates(paint: string): number[] {
89
+ const nibbles: number[] = [];
90
+ for (let i = paint.length - 1; i >= 0; i--) {
91
+ const digit = Number.parseInt(paint[i], 16);
92
+ if (Number.isNaN(digit)) return [];
93
+ nibbles.push(digit);
94
+ }
95
+ const states: number[] = [];
96
+ let at = 0, pending = 1;
97
+ const next = () => (at < nibbles.length ? nibbles[at++] : undefined);
98
+ while (pending > 0) {
99
+ const code = next();
100
+ if (code === undefined) break;
101
+ pending -= 1;
102
+ const sides = code & 0b11;
103
+ if (sides) { pending += sides + 1; continue; }
104
+ if ((code & 0b1100) === 0b1100) {
105
+ let more = 0, value = next();
106
+ while (value === 0b1111) { more += 1; value = next(); }
107
+ if (value === undefined) break;
108
+ states.push(value + 15 * more + 3);
109
+ } else states.push(code >> 2);
110
+ }
111
+ return states;
112
+ }
113
+
114
+ /** What a mesh's painting says: the painted filament states, and whether any facet keeps the volume's own filament. */
115
+ interface MeshPaint { states: Set<number>; ownFilament: boolean }
116
+
117
+ /**
118
+ * Per component file and sub-object id, the painting of that mesh. Only files that contain painting are read in full.
119
+ */
120
+ async function readPainting(zip: JSZip, paths: Set<string>): Promise<Map<string, MeshPaint>> {
121
+ const result = new Map<string, MeshPaint>();
122
+ let total = 0;
123
+ for (const path of paths) {
124
+ const file = zip.file(path);
125
+ if (!file) continue;
126
+ // A mesh past the read budget is taken as unpainted (its part's own filament), never a failed listing.
127
+ const size = (file as unknown as { _data?: { uncompressedSize?: number } })._data?.uncompressedSize;
128
+ if (size !== undefined && (size > MAX_MESH_BYTES || total + size > MAX_MESH_TOTAL)) continue;
129
+ const bytes = await file.async("nodebuffer");
130
+ if (bytes.length > MAX_MESH_BYTES || (total += bytes.length) > MAX_MESH_TOTAL) continue;
131
+ if (!bytes.includes("paint_color=\"")) continue;
132
+ const text = bytes.toString("utf8");
133
+ for (const object of text.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
134
+ const paint: MeshPaint = { states: new Set(), ownFilament: false };
135
+ for (const triangle of object[2].matchAll(/<triangle\b([^>]*)\/?>/g)) {
136
+ const value = /\bpaint_color="([0-9A-Fa-f]*)"/.exec(triangle[1])?.[1];
137
+ if (!value) { paint.ownFilament = true; continue; }
138
+ for (const state of paintedStates(value)) {
139
+ if (state === 0) paint.ownFilament = true;
140
+ else paint.states.add(state);
141
+ }
142
+ }
143
+ result.set(`${path}#${object[1]}`, paint);
144
+ }
145
+ }
146
+ return result;
147
+ }
148
+
149
+ interface ProjectFilaments { colours: string[]; materials: string[]; ids: string[]; config: Record<string, unknown> }
150
+
151
+ function projectFilaments(config: Record<string, unknown>): ProjectFilaments {
152
+ const list = (key: string): string[] => Array.isArray(config[key]) ? (config[key] as unknown[]).map(String) : [];
153
+ return { colours: list("filament_colour"), materials: list("filament_type"), ids: list("filament_ids"), config };
154
+ }
155
+
156
+ function describe(index: number, project: ProjectFilaments, name?: string): PlateFilament {
157
+ const colour = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(project.colours[index - 1]?.trim() ?? "");
158
+ const material = project.materials[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
159
+ const filamentId = project.ids[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
160
+ return { index, ...(colour ? { colour: `#${colour[1].toUpperCase()}` } : {}), ...(material ? { material } : {}),
161
+ ...(filamentId ? { filament_id: filamentId } : {}), ...(name ? { name } : {}) };
162
+ }
163
+
164
+ export interface PlateLayout {
165
+ /** 1-based plate number. */
166
+ number: number;
167
+ /** model_settings.config object ids with an instance on this plate, in plate order. */
168
+ objectIds: string[];
169
+ /** Each copy on the plate: its object and that object's instance_id (model_settings.config <model_instance>). */
170
+ instances?: { objectId: string; instanceId: number }[];
171
+ /** Metadata/plate_N.json filament_ids (0-based) when the file holds this plate's slice. */
172
+ slicedFilamentIds?: number[];
173
+ }
174
+
175
+ /**
176
+ * The filaments each plate prints with, keyed by plate number. `settings` is model_settings.config, `model` the root
177
+ * 3D/3dmodel.model text.
178
+ */
179
+ export async function plateFilaments(zip: JSZip, settings: string, model: string, plates: PlateLayout[]): Promise<{ plates: Map<number, PlateFilament[]>; project: PlateFilament[] }> {
180
+ const text = async (name: string) => {
181
+ const file = zip.file(name);
182
+ if (!file) return "";
183
+ const bytes = await file.async("nodebuffer");
184
+ if (bytes.length > MAX_TEXT_BYTES) throw new Error(`${name} is too large to read.`);
185
+ return bytes.toString("utf8");
186
+ };
187
+ let config: Record<string, unknown> = {};
188
+ try {
189
+ const parsed = JSON.parse(await text("Metadata/project_settings.config") || "{}") as unknown;
190
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) config = parsed as Record<string, unknown>;
191
+ } catch { /* a project without readable settings declares no filaments */ }
192
+ const project = projectFilaments(config);
193
+ const declared = Math.min(MAX_FILAMENT, Math.max(project.colours.length, project.materials.length, project.ids.length));
194
+ const valid = (index: number | undefined): index is number => index !== undefined && Number.isInteger(index) && index >= 1 && index <= MAX_FILAMENT && (!declared || index <= declared);
195
+
196
+ const objects = new Map(readModelObjects(settings).map(object => [object.id, object]));
197
+ // Root objects' components: which sub-object mesh in which file each part is (part id = component objectid).
198
+ const components = new Map<string, Map<string, string>>();
199
+ for (const object of model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/(?:\w+:)?object>/g)) {
200
+ const parts = new Map<string, string>();
201
+ for (const component of object[2].matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
202
+ const path = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1];
203
+ const id = /\bobjectid="(\d+)"/.exec(component[1])?.[1];
204
+ // Studio keys a component by (path, objectid); one without p:path names a mesh object in the root model
205
+ // itself, keyed by the root's empty path (bbs_3mf.cpp:4131-4148, 3891).
206
+ if (id) parts.set(id, path || "3D/3dmodel.model");
207
+ }
208
+ if (parts.size) components.set(object[1], parts);
209
+ }
210
+ // Model object order (1-based in layer_config_ranges.xml): the build items' order, as Studio creates the objects.
211
+ const buildItems = [...model.matchAll(/<(?:\w+:)?item\b([^>]*)\/?>/g)].map(item => item[1]);
212
+ const order = [...new Set(buildItems.flatMap(item => /\bobjectid="(\d+)"/.exec(item)?.[1] ?? []))];
213
+ // Each build item adds its object's next instance, with its own printable flag (bbs_3mf.cpp:4183-4185, 4375-4380);
214
+ // a plate names its copies by object_id and instance_id (bbs_3mf.cpp:4717-4719), and the CLI skips each copy that
215
+ // isn't printable (PartPlate.cpp:1311-1322).
216
+ const printableItems = new Map<string, boolean[]>();
217
+ for (const item of buildItems) {
218
+ const id = /\bobjectid="(\d+)"/.exec(item)?.[1];
219
+ if (id) printableItems.set(id, [...(printableItems.get(id) ?? []), !/\bprintable="(?:0|false)"/.test(item)]);
220
+ }
221
+ const printableCopy = (objectId: string, instanceId?: number) => {
222
+ const flags = printableItems.get(objectId);
223
+ if (!flags) return true;
224
+ return instanceId === undefined ? flags.some(Boolean) : flags[instanceId] !== false;
225
+ };
226
+
227
+
228
+ const rangeExtruders = new Map<string, number[]>();
229
+ const ranges = await text("Metadata/layer_config_ranges.xml");
230
+ for (const object of ranges.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
231
+ const objectId = order[Number(object[1]) - 1];
232
+ if (!objectId) continue;
233
+ // A range's extruder sets all three feature filaments; a range's own feature filament overrides one
234
+ // (apply_to_print_region_config and resolve_filament_value, PrintObject.cpp:3069-3079, 3134-3137).
235
+ rangeExtruders.set(objectId, [...object[2].matchAll(/<option\s+opt_key="(?:extruder|wall_filament|sparse_infill_filament|solid_infill_filament)"\s*>\s*(\d+)\s*<\/option>/g)].map(match => Number(match[1])).filter(id => id > 0));
236
+ }
237
+ const toolChanges = new Map<number, number[]>();
238
+ const custom = await text("Metadata/custom_gcode_per_layer.xml");
239
+ for (const plate of custom.matchAll(/<plate>([\s\S]*?)<\/plate>/g)) {
240
+ const id = Number(/<plate_info\b[^>]*\bid="(\d+)"/.exec(plate[1])?.[1]);
241
+ if (!Number.isInteger(id)) continue;
242
+ toolChanges.set(id, [...plate[1].matchAll(/<layer\b([^>]*)\/?>/g)]
243
+ .filter(layer => /\btype="2"/.test(layer[1]))
244
+ .map(layer => Number(/\bextruder="(\d+)"/.exec(layer[1])?.[1])));
245
+ }
246
+
247
+ // Painting only matters for parts on a plate that is not sliced yet.
248
+ const paintPaths = new Set<string>();
249
+ for (const plate of plates) if (!plate.slicedFilamentIds) for (const objectId of plate.objectIds)
250
+ for (const path of components.get(objectId)?.values() ?? []) paintPaths.add(path);
251
+ const painting = await readPainting(zip, paintPaths);
252
+
253
+ const global = (key: string) => intOf(config[key]) ?? 0;
254
+ const FEATURES = ["wall_filament", "sparse_infill_filament", "solid_infill_filament"] as const;
255
+ const result = new Map<number, PlateFilament[]>();
256
+ for (const plate of plates) {
257
+ const used = new Map<number, string | undefined>();
258
+ const add = (index: number | undefined, name?: string) => {
259
+ if (!valid(index)) return;
260
+ if (!used.has(index) || (!used.get(index) && name)) used.set(index, name || undefined);
261
+ };
262
+ // An object counts once on a plate when any of its copies there prints.
263
+ const printing = plate.instances?.length
264
+ ? [...new Set(plate.instances.filter(copy => printableCopy(copy.objectId, copy.instanceId)).map(copy => copy.objectId))]
265
+ : plate.objectIds.filter(objectId => printableCopy(objectId));
266
+ for (const objectId of printing) {
267
+ const object = objects.get(objectId);
268
+ if (!object) continue;
269
+ const objectInt = (key: string) => intOf(object.settings.get(key));
270
+ const parts = object.parts.length ? object.parts : [{ id: "", subtype: "normal_part", name: "", settings: new Map() as Settings }];
271
+ for (const part of parts) {
272
+ if (["negative_part", "support_blocker", "support_enforcer"].includes(part.subtype)) continue;
273
+ const partInt = (key: string) => intOf(part.settings.get(key));
274
+ // What the slicer prints the part with (region_config_from_model_volume, PrintObject.cpp:3105-3150): the
275
+ // project's feature filaments, replaced by the object's and then the part's extruder when one is set
276
+ // (non-zero), then by a feature filament the part, else the object, sets above 0.
277
+ const extruderSet = (partInt("extruder") ?? 0) > 0 || (objectInt("extruder") ?? 0) > 0;
278
+ const ownExtruder = partInt("extruder") || objectInt("extruder") || 1;
279
+ const label = part.name || object.name;
280
+ const path = components.get(objectId)?.get(part.id);
281
+ const paint = path ? painting.get(`${path}#${part.id}`) : undefined;
282
+ for (const state of paint?.states ?? []) if (part.subtype === "normal_part") add(state, label);
283
+ // A modifier's own filament counts whatever its paint (Model.cpp:3384-3390).
284
+ if (part.subtype !== "normal_part" || !paint || paint.ownFilament) {
285
+ if (extruderSet) add(ownExtruder, label);
286
+ // Neither the part nor its object names an extruder: the project's feature filaments print it (each
287
+ // above 0; a project without them prints with filament 1, ModelVolume::extruder_id's default).
288
+ else for (const key of FEATURES) add(global(key) > 0 ? global(key) : 1, label);
289
+ }
290
+ for (const key of ["wall_filament", "solid_infill_filament", "sparse_infill_filament"]) {
291
+ const own = partInt(key);
292
+ if (own !== undefined) { if (own > 0) add(own, label); }
293
+ else if ((objectInt(key) ?? 0) > 0) add(objectInt(key), label);
294
+ }
295
+ // separate_filaments_for_features gates these only in Studio's plate list (PartPlate.cpp:1338-1381): it isn't
296
+ // a slicer setting in 02.08.02.61 (libslic3r never reads it), and the slice applies the part's or object's
297
+ // feature filaments whatever it says (PrintObject.cpp:3124-3150), as the loop above does.
298
+ }
299
+ for (const extruder of rangeExtruders.get(objectId) ?? []) add(extruder, object.name);
300
+ // Support and raft as the slice resolves them: each setting the object's own, else the project's, one key at a
301
+ // time (PrintObject::object_config_from_model_object, PrintObject.cpp:3052-3063). Studio's plate list resolves
302
+ // the pair together (PartPlate.cpp:1383-1393), which drops support an object with only a raft override prints.
303
+ const setting = (key: string) => object.settings.has(key) ? object.settings.get(key) : config[key];
304
+ const support = (boolOf(setting("enable_support")) ?? false) || (intOf(setting("raft_layers")) ?? 0) > 0;
305
+ if (support) {
306
+ // 0 is "default": the support prints with the object's own filament (Print.cpp:490-501).
307
+ add(intOf(setting("support_interface_filament")) || undefined);
308
+ add(intOf(setting("support_filament")) || undefined);
309
+ }
310
+ }
311
+ for (const extruder of toolChanges.get(plate.number) ?? []) add(extruder);
312
+ // Objects the settings don't describe (a plain 3MF) name no extruder: the project's feature filaments print them,
313
+ // else filament 1 (ModelVolume::extruder_id's default).
314
+ if (!used.size && (plate.objectIds.some(id => !objects.has(id)) || (!objects.size && buildItems.length)))
315
+ for (const key of FEATURES) add(global(key) > 0 ? global(key) : 1);
316
+ // A mixed filament slot prints as its component filaments (PartPlate.cpp:1437-1449, expand_mixed_filaments in
317
+ // FilamentMixer.cpp:460-478; components are 1-based, comma-separated, FilamentMixer.cpp:165-180).
318
+ const mixed = Array.isArray(config.filament_is_mixed) ? (config.filament_is_mixed as unknown[]).map(value => boolOf(value) === true) : [];
319
+ const mixedComponents = Array.isArray(config.filament_mixed_components) ? (config.filament_mixed_components as unknown[]).map(String) : [];
320
+ if (mixed.some(Boolean)) for (const [index, name] of [...used]) {
321
+ if (!mixed[index - 1] || index - 1 >= mixedComponents.length) continue;
322
+ used.delete(index);
323
+ for (const part of mixedComponents[index - 1].split(",")) {
324
+ const component = /^\s*\d+\s*$/.test(part) ? Number(part) : 0;
325
+ if (component >= 1) add(component, name);
326
+ }
327
+ }
328
+ if (plate.slicedFilamentIds) {
329
+ // The slice is Studio's own answer: it replaces the derivation, keeping names the derivation found.
330
+ const names = new Map(used);
331
+ used.clear();
332
+ for (const id of plate.slicedFilamentIds) add(id + 1, names.get(id + 1));
333
+ }
334
+ result.set(plate.number, [...used.entries()].sort((a, b) => a[0] - b[0]).map(([index, name]) => describe(index, project, name)));
335
+ }
336
+ // Every filament the project declares, used on a plate or not: slice_stl takes one profile per declared filament.
337
+ return { plates: result, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)) };
338
+ }
package/src/index.ts CHANGED
@@ -60,7 +60,7 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
60
60
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
61
61
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_MCP_PIN, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge, addinAddress } from "./fusion-mcp-bridge.js";
62
62
  import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake, type BlenderAddonHandshake } from "./design-app-setup.js";
63
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
63
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMapping, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
64
64
  import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, hasSlicerSettingsFile, parse3MF, withExtractedSettingsCleanup } from './3mf_parser.js';
65
65
  import type { ThreeMFAmsRequirements } from "./types.js";
66
66
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
@@ -1829,7 +1829,8 @@ class BambuPrinterMCPServer {
1829
1829
  const resumeFile = await checkedFile(inspection, snapshot);
1830
1830
  // The options Bambu Studio's Send dialog would send; explicit ones win.
1831
1831
  const studio = resolveStudioPrintOptions(printModel, callerPrintOptions(args), { usedNozzles: usedNozzleCount(inspection) });
1832
- let mapping = finalAmsMapping?.slice();
1832
+ // Bambu Studio maps only the plate's own filaments; every other project filament is -1 (SelectMachine.cpp:1463-1500).
1833
+ let mapping = finalAmsMapping ? studioAmsMapping(finalAmsMapping, inspection.usedFilamentPositions) : undefined;
1833
1834
  if (finalAmsSlots) {
1834
1835
  if (finalAmsSlots.length !== inspection.usedFilamentPositions.length) throw new Error("ams_slots must supply exactly one physical tray per used filament.");
1835
1836
  mapping = Array(inspection.materials.length).fill(-1);
@@ -2568,7 +2569,7 @@ class BambuPrinterMCPServer {
2568
2569
  },
2569
2570
  {
2570
2571
  name: "list_3mf_plates",
2571
- 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, each object copy's identify_id (instances: the ids slice_stl's skip_objects takes) 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.",
2572
+ 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, each object copy's identify_id (instances: the ids slice_stl's skip_objects takes) whether the file already holds its G-code (sliced), and filaments: the project filaments that plate prints with and only those (index from 1 = slice_stl's load_filaments/filament_colours position and print_3mf's ams_mapping position + 1; colour, material, filament_id, and the first part using it), from the slice when there is one, otherwise worked out as Bambu Studio does from the plate's parts, painting, support, layer ranges and tool changes. project_filaments lists every filament the project declares, used or not (slice_stl takes one load_filaments profile per declared filament). 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.",
2572
2573
  inputSchema: {
2573
2574
  type: "object",
2574
2575
  properties: {
@@ -3373,7 +3374,7 @@ class BambuPrinterMCPServer {
3373
3374
  use_ams: { type: "boolean", description: "Whether to use the AMS (default: auto-detect from 3MF)" },
3374
3375
  ams_mapping: {
3375
3376
  type: "array",
3376
- description: "Project-level AMS mapping array. Position = project filament index, value = absolute AMS tray (0-3=AMS 0, 4-7=AMS 1, 8-11=AMS 2, 128+=AMS-HT, 254=external, -1=unused). On dual-nozzle printers (H2D, H2D Pro, H2C, X2D) 254 is the LEFT/deputy nozzle external spool and 255 the RIGHT/main nozzle external spool, matching Bambu Studio's virtual tray ids; the gcode header's filament_map (1=left, 2=right) says which nozzle each filament was sliced for. Prefer ams_slots unless you know the project-level layout.",
3377
+ description: "Project-level AMS mapping array. Position = project filament index, value = absolute AMS tray. Positions the selected plate does not print are sent as -1, as Bambu Studio sends them, whatever is passed there (0-3=AMS 0, 4-7=AMS 1, 8-11=AMS 2, 128+=AMS-HT, 254=external, -1=unused). On dual-nozzle printers (H2D, H2D Pro, H2C, X2D) 254 is the LEFT/deputy nozzle external spool and 255 the RIGHT/main nozzle external spool, matching Bambu Studio's virtual tray ids; the gcode header's filament_map (1=left, 2=right) says which nozzle each filament was sliced for. Prefer ams_slots unless you know the project-level layout.",
3377
3378
  items: { type: "number" }
3378
3379
  },
3379
3380
  ams_slots: {