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.
package/README.md CHANGED
@@ -1086,7 +1086,7 @@ If the project does not match those assumptions, the tool fails fast with a stru
1086
1086
 
1087
1087
  #### Counterpart tools (`counterpart/1`)
1088
1088
 
1089
- [Counterpart](https://github.com/DMontgomery40/scan-to-make) (Scan to Make) reads printers through a small contract that this server and [mcp-3D-printer-server](https://github.com/DMontgomery40/mcp-3D-printer-server) share. Each tool declares an `outputSchema` and returns `structuredContent`, plus the same JSON as text for older clients. An error is returned as text only, because MCP clients check `structuredContent` against the schema even on errors. Other tools return an error's details in `structuredContent` (`status`, `retryable`, `suggestion`, `message`). When the printer refuses a print, the error also carries a stable `code`, either `printer-command-rejected` or `printer-not-ready`, so a client can act on the code rather than the wording. `counterpart_printer_info` reports `capabilities.slicing` (`supports`, `copies`, `orient`), so a client can offer those choices without knowing the slicer. `counterpart_printer_info` and `counterpart_print_progress` take the usual optional `host`, `bambu_serial`, `bambu_token` and `bambu_model` (default `BAMBU_MODEL`) arguments.
1089
+ [Counterpart](https://github.com/DMontgomery40/scan-to-make) (Scan to Make) reads printers through a small contract that this server and [mcp-3D-printer-server](https://github.com/DMontgomery40/mcp-3D-printer-server) share. Each tool declares an `outputSchema` and returns `structuredContent`, plus the same JSON as text for older clients. An error is returned as text only, because MCP clients check `structuredContent` against the schema even on errors. Other tools return an error's details in `structuredContent` (`status`, `retryable`, `suggestion`, `message`). When the printer refuses a print, the error also carries a stable `code`: `printer-command-rejected`, `printer-not-ready`, or `printer-upload-failed` when the file didn't reach the printer and no print command was sent, so a client can act on the code rather than the wording. `counterpart_printer_info` reports `capabilities.slicing` (`supports`, `copies`, `orient`), so a client can offer those choices without knowing the slicer. `counterpart_printer_info` and `counterpart_print_progress` take the usual optional `host`, `bambu_serial`, `bambu_token` and `bambu_model` (default `BAMBU_MODEL`) arguments.
1090
1090
 
1091
1091
  - **`counterpart_printer_info`** returns `{contract, server: {name, version}, printer: {kind: "bambu", model, serial, host}, capabilities}`. `capabilities` lists progress, layers, the camera transport (`bambu-tcp` for A1/P1, `rtsp` for X1, P2S, H2 and X2D, `none` without a model), `cameraStream: true` for supported camera models, `filaments: "ams"`, pause, resume, cancel, `print3mf` and `gcode` (false on X2D). It sends nothing to the printer and never returns the access code.
1092
1092
  - **`counterpart_print_route`** reads or changes how prints and Stop/Pause/Resume reach the printer: `{route, mode, type, choices, savedTo}`, where `route` is `lan` (the local network, in the configured `BAMBU_DEFAULT_CONNECTION_MODE`) or `cloud` (Bambu Cloud through the [FULU bridge](docs/FULU.md)). Pass `route` to change it; the next print and control use it at once, and it is written to the `.env` in the server's working directory when one exists (`savedTo`, otherwise `null`). It is not part of the shared contract: it has no `outputSchema`, and mcp-3D-printer-server has no Bambu Cloud route.
@@ -36,3 +36,9 @@ export declare function trayColour(rawStatus: any, tray: number): string | undef
36
36
  * Filament-map nozzle 1 (left) is cloud nozzle 1 and 2 (right) is 0 (CloudTaskNozzleId).
37
37
  */
38
38
  export declare function studioAmsMappingInfo(filaments: ProjectFilament[], mapping: number[], colourOfTray: (tray: number) => string | undefined): Array<Record<string, unknown>>;
39
+ /**
40
+ * A project-level ams_mapping as Bambu Studio sends it: the caller's tray for each filament the selected plate prints,
41
+ * -1 for every project filament it doesn't (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500,
42
+ * maps only the plate's own filaments). A tray for an unused filament is never sent to the printer.
43
+ */
44
+ export declare function studioAmsMapping(mapping: number[], usedPositions: number[]): number[];
@@ -125,3 +125,12 @@ export function studioAmsMappingInfo(filaments, mapping, colourOfTray) {
125
125
  };
126
126
  });
127
127
  }
128
+ /**
129
+ * A project-level ams_mapping as Bambu Studio sends it: the caller's tray for each filament the selected plate prints,
130
+ * -1 for every project filament it doesn't (SelectMachineDialog::get_ams_mapping_result, SelectMachine.cpp:1463-1500,
131
+ * maps only the plate's own filaments). A tray for an unused filament is never sent to the printer.
132
+ */
133
+ export function studioAmsMapping(mapping, usedPositions) {
134
+ const used = new Set(usedPositions);
135
+ return mapping.map((tray, position) => used.has(position) ? tray : -1);
136
+ }
@@ -1,3 +1,4 @@
1
+ import { type PlateFilament } from "./plate-filaments.js";
1
2
  export interface ModelPlate {
2
3
  /** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
3
4
  index: number;
@@ -14,6 +15,12 @@ export interface ModelPlate {
14
15
  }[];
15
16
  /** The file already holds this plate's G-code. */
16
17
  sliced: boolean;
18
+ /**
19
+ * The project filaments this plate prints with, and only those (counterpart/1): what a client asks the person to
20
+ * choose spools for. From the slice when the file holds one (plate_N.json filament_ids), otherwise worked out as
21
+ * Bambu Studio does for the objects on this plate (see plate-filaments.ts). Filaments of other plates never appear.
22
+ */
23
+ filaments: PlateFilament[];
17
24
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
18
25
  thumbnail_png_base64?: string;
19
26
  }
@@ -23,6 +30,11 @@ export interface ModelPlates {
23
30
  title?: string;
24
31
  designer?: string;
25
32
  licence?: string;
33
+ /**
34
+ * Every filament the project declares (project_settings.config), used on a plate or not, from 1: slice_stl takes one
35
+ * load_filaments profile per declared filament. Empty for a 3MF that declares none.
36
+ */
37
+ project_filaments: PlateFilament[];
26
38
  }
27
39
  export declare function listModelPlates(filePath: string, options?: {
28
40
  thumbnails?: boolean;
@@ -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 } from "./plate-filaments.js";
11
12
  /** For the settings and plate files; the model file can be large and is only scanned. */
12
13
  const MAX_METADATA_BYTES = 8 * 1024 * 1024;
13
14
  const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
@@ -34,7 +35,7 @@ export async function listModelPlates(filePath, options = {}) {
34
35
  throw new Error("That file is not a 3MF model.");
35
36
  // An element named `tag`, plain or with a namespace prefix (<item …>, <p:item …>).
36
37
  const has = (tag) => !!modelBytes && [" ", ">", "/", "\n", "\r", "\t"].some(end => modelBytes.includes(`<${tag}${end}`) || modelBytes.includes(`:${tag}${end}`));
37
- const result = { plate_count: 0, plates: [] };
38
+ const result = { plate_count: 0, plates: [], project_filaments: [] };
38
39
  const metadata = new Map([...head.matchAll(/<metadata\s+name="([^"]+)"[^>]*>([^<]*)<\/metadata>/g)].map(match => [match[1], words(match[2])]));
39
40
  if (metadata.get("Title"))
40
41
  result.title = metadata.get("Title");
@@ -48,6 +49,7 @@ export async function listModelPlates(filePath, options = {}) {
48
49
  return [match[1], words(name?.[1] ?? "")];
49
50
  }));
50
51
  const plates = new Map();
52
+ const layouts = new Map();
51
53
  // A plate number out of range is skipped, as a slicer would not show it.
52
54
  const valid = (number) => Number.isSafeInteger(number) && number >= 1 && number <= MAX_PLATES;
53
55
  for (const match of settings.matchAll(/<plate\b[^>]*>([\s\S]*?)<\/plate>/g)) {
@@ -64,7 +66,13 @@ export async function listModelPlates(filePath, options = {}) {
64
66
  return object !== undefined && Number.isSafeInteger(identify) && identify > 0
65
67
  ? [{ identify_id: identify, name: objects.get(object) ?? "" }] : [];
66
68
  }).slice(0, MAX_INSTANCES_PER_PLATE);
67
- plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances,
69
+ layouts.set(number, { number, objectIds: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].map(item => item[1]),
70
+ instances: [...match[1].matchAll(/<model_instance>([\s\S]*?)<\/model_instance>/g)].flatMap(instance => {
71
+ const objectId = /<metadata\s+key="object_id"\s+value="(\d+)"/.exec(instance[1])?.[1];
72
+ const instanceId = Number(/<metadata\s+key="instance_id"\s+value="(\d+)"/.exec(instance[1])?.[1] ?? 0);
73
+ return objectId ? [{ objectId, instanceId }] : [];
74
+ }) });
75
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [],
68
76
  objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])] : []) });
69
77
  }
70
78
  for (const name of Object.keys(zip.files)) {
@@ -74,12 +82,17 @@ export async function listModelPlates(filePath, options = {}) {
74
82
  const number = Number(match[1]);
75
83
  if (!valid(number))
76
84
  continue;
77
- const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false };
85
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [] };
86
+ const layout = layouts.get(number) ?? { number, objectIds: [] };
87
+ layouts.set(number, layout);
78
88
  if (match[2] === "gcode")
79
89
  plate.sliced = true;
80
90
  else {
81
91
  try {
82
92
  const value = JSON.parse(await text(name));
93
+ // Studio's record of the filaments this plate's slice uses (0-based project positions).
94
+ if (Array.isArray(value.filament_ids))
95
+ layout.slicedFilamentIds = value.filament_ids.filter((id) => Number.isInteger(id) && id >= 0 && id < 64);
83
96
  if (Array.isArray(value.bbox_objects))
84
97
  plate.objects = value.bbox_objects
85
98
  .flatMap(object => typeof object.name === "string" && object.name !== "wipe_tower" ? [words(object.name)] : []).slice(0, 200);
@@ -90,8 +103,11 @@ export async function listModelPlates(filePath, options = {}) {
90
103
  }
91
104
  result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
92
105
  // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
93
- if (!result.plates.length)
94
- result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false });
106
+ if (!result.plates.length) {
107
+ result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [] });
108
+ // Without plates every object is on the one plate.
109
+ layouts.set(1, { number: 1, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
110
+ }
95
111
  const geometry = has("item") && (has("mesh") || has("component"));
96
112
  if (!geometry) {
97
113
  // A sliced-only file (previews and G-code, no model): only its sliced plates can print.
@@ -99,6 +115,14 @@ export async function listModelPlates(filePath, options = {}) {
99
115
  if (!result.plates.length)
100
116
  throw new Error("This 3MF has previews and settings but no model or printable plate.");
101
117
  }
118
+ // A slice's G-code without its plate_N.json gives no filament list: the derivation stands.
119
+ // A model file too large to read whole: its resources come first and its build items last (a plain 3MF).
120
+ const modelText = !modelBytes ? "" : modelBytes.length <= 64 * 1024 * 1024 ? modelBytes.toString("utf8")
121
+ : `${head}${modelBytes.subarray(-1024 * 1024).toString("utf8")}`;
122
+ const filaments = await plateFilaments(zip, settings, modelText, result.plates.map(plate => layouts.get(plate.index + 1) ?? { number: plate.index + 1, objectIds: [] }));
123
+ for (const plate of result.plates)
124
+ plate.filaments = filaments.plates.get(plate.index + 1) ?? [];
125
+ result.project_filaments = filaments.project;
102
126
  if (options.thumbnails)
103
127
  for (const plate of result.plates) {
104
128
  const file = zip.file(`Metadata/plate_${plate.index + 1}.png`);
@@ -0,0 +1,80 @@
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
+ export interface PlateFilament {
26
+ /** 1-based project filament number: slice_stl's load_filaments/filament_colours position, print_3mf's ams_mapping index + 1. */
27
+ index: number;
28
+ /** As the project declares it (project_settings.config filament_colour), #RRGGBB. */
29
+ colour?: string;
30
+ /** project_settings.config filament_type. */
31
+ material?: string;
32
+ /** project_settings.config filament_ids (Bambu's filament id, e.g. GFA00). */
33
+ filament_id?: string;
34
+ /** The first part (else object) on this plate that prints with it; absent for support, painting or tool changes only. */
35
+ name?: string;
36
+ }
37
+ type Settings = Map<string, string>;
38
+ interface Part {
39
+ id: string;
40
+ subtype: string;
41
+ name: string;
42
+ settings: Settings;
43
+ }
44
+ interface ObjectEntry {
45
+ id: string;
46
+ name: string;
47
+ settings: Settings;
48
+ parts: Part[];
49
+ }
50
+ /** model_settings.config objects with their own settings and parts (parts never nest). */
51
+ export declare function readModelObjects(settings: string): ObjectEntry[];
52
+ /**
53
+ * The filament states a painted facet string holds (0 is "the volume's own filament"). Studio's string is hex,
54
+ * read last character first, each digit four bits low bit first, so the nibbles are the digits in reverse order.
55
+ * Each node is one nibble: two low bits are the split-side count (children = sides + 1); a leaf's state is the high
56
+ * two bits, or, when both are set, 3 + the next nibble + 15 for every preceding 0b1111 nibble.
57
+ */
58
+ export declare function paintedStates(paint: string): number[];
59
+ export interface PlateLayout {
60
+ /** 1-based plate number. */
61
+ number: number;
62
+ /** model_settings.config object ids with an instance on this plate, in plate order. */
63
+ objectIds: string[];
64
+ /** Each copy on the plate: its object and that object's instance_id (model_settings.config <model_instance>). */
65
+ instances?: {
66
+ objectId: string;
67
+ instanceId: number;
68
+ }[];
69
+ /** Metadata/plate_N.json filament_ids (0-based) when the file holds this plate's slice. */
70
+ slicedFilamentIds?: number[];
71
+ }
72
+ /**
73
+ * The filaments each plate prints with, keyed by plate number. `settings` is model_settings.config, `model` the root
74
+ * 3D/3dmodel.model text.
75
+ */
76
+ export declare function plateFilaments(zip: JSZip, settings: string, model: string, plates: PlateLayout[]): Promise<{
77
+ plates: Map<number, PlateFilament[]>;
78
+ project: PlateFilament[];
79
+ }>;
80
+ export {};
@@ -0,0 +1,325 @@
1
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
2
+ const MAX_MESH_BYTES = 64 * 1024 * 1024;
3
+ const MAX_MESH_TOTAL = 256 * 1024 * 1024;
4
+ const MAX_FILAMENT = 64;
5
+ const words = (value) => value
6
+ .replace(/&(?:amp|lt|gt|quot|apos);/g, entity => ({ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": "\"", "&apos;": "'" }[entity]))
7
+ .replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 256);
8
+ const metadataOf = (block) => new Map([...block.matchAll(/<metadata\s+key="([^"]+)"\s+value="([^"]*)"\s*\/?>/g)].map(match => [match[1], match[2]]));
9
+ /** model_settings.config objects with their own settings and parts (parts never nest). */
10
+ export function readModelObjects(settings) {
11
+ return [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
12
+ const parts = [...match[2].matchAll(/<part\b([^>]*)>([\s\S]*?)<\/part>/g)].map(part => {
13
+ const own = metadataOf(part[2]);
14
+ return { id: /\bid="(\d+)"/.exec(part[1])?.[1] ?? "", subtype: /\bsubtype="([^"]+)"/.exec(part[1])?.[1] ?? "normal_part", name: words(own.get("name") ?? ""), settings: own };
15
+ });
16
+ const own = metadataOf(match[2].replace(/<part\b[^>]*>[\s\S]*?<\/part>/g, ""));
17
+ return { id: match[1], name: words(own.get("name") ?? ""), settings: own, parts };
18
+ });
19
+ }
20
+ /** An integer setting (Studio stores "0"/"1"/"3" strings; a project list keeps its first value). */
21
+ function intOf(value) {
22
+ const first = Array.isArray(value) ? value[0] : value;
23
+ if (typeof first === "number" && Number.isInteger(first))
24
+ return first;
25
+ if (typeof first !== "string" || !/^\s*-?\d+\s*$/.test(first))
26
+ return undefined;
27
+ return Number(first);
28
+ }
29
+ function boolOf(value) {
30
+ const first = Array.isArray(value) ? value[0] : value;
31
+ if (typeof first === "boolean")
32
+ return first;
33
+ if (typeof first !== "string")
34
+ return undefined;
35
+ if (/^(?:1|true)$/i.test(first.trim()))
36
+ return true;
37
+ if (/^(?:0|false)$/i.test(first.trim()))
38
+ return false;
39
+ return undefined;
40
+ }
41
+ /**
42
+ * The filament states a painted facet string holds (0 is "the volume's own filament"). Studio's string is hex,
43
+ * read last character first, each digit four bits low bit first, so the nibbles are the digits in reverse order.
44
+ * Each node is one nibble: two low bits are the split-side count (children = sides + 1); a leaf's state is the high
45
+ * two bits, or, when both are set, 3 + the next nibble + 15 for every preceding 0b1111 nibble.
46
+ */
47
+ export function paintedStates(paint) {
48
+ const nibbles = [];
49
+ for (let i = paint.length - 1; i >= 0; i--) {
50
+ const digit = Number.parseInt(paint[i], 16);
51
+ if (Number.isNaN(digit))
52
+ return [];
53
+ nibbles.push(digit);
54
+ }
55
+ const states = [];
56
+ let at = 0, pending = 1;
57
+ const next = () => (at < nibbles.length ? nibbles[at++] : undefined);
58
+ while (pending > 0) {
59
+ const code = next();
60
+ if (code === undefined)
61
+ break;
62
+ pending -= 1;
63
+ const sides = code & 0b11;
64
+ if (sides) {
65
+ pending += sides + 1;
66
+ continue;
67
+ }
68
+ if ((code & 0b1100) === 0b1100) {
69
+ let more = 0, value = next();
70
+ while (value === 0b1111) {
71
+ more += 1;
72
+ value = next();
73
+ }
74
+ if (value === undefined)
75
+ break;
76
+ states.push(value + 15 * more + 3);
77
+ }
78
+ else
79
+ states.push(code >> 2);
80
+ }
81
+ return states;
82
+ }
83
+ /**
84
+ * Per component file and sub-object id, the painting of that mesh. Only files that contain painting are read in full.
85
+ */
86
+ async function readPainting(zip, paths) {
87
+ const result = new Map();
88
+ let total = 0;
89
+ for (const path of paths) {
90
+ const file = zip.file(path);
91
+ if (!file)
92
+ continue;
93
+ // A mesh past the read budget is taken as unpainted (its part's own filament), never a failed listing.
94
+ const size = file._data?.uncompressedSize;
95
+ if (size !== undefined && (size > MAX_MESH_BYTES || total + size > MAX_MESH_TOTAL))
96
+ continue;
97
+ const bytes = await file.async("nodebuffer");
98
+ if (bytes.length > MAX_MESH_BYTES || (total += bytes.length) > MAX_MESH_TOTAL)
99
+ continue;
100
+ if (!bytes.includes("paint_color=\""))
101
+ continue;
102
+ const text = bytes.toString("utf8");
103
+ for (const object of text.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
104
+ const paint = { states: new Set(), ownFilament: false };
105
+ for (const triangle of object[2].matchAll(/<triangle\b([^>]*)\/?>/g)) {
106
+ const value = /\bpaint_color="([0-9A-Fa-f]*)"/.exec(triangle[1])?.[1];
107
+ if (!value) {
108
+ paint.ownFilament = true;
109
+ continue;
110
+ }
111
+ for (const state of paintedStates(value)) {
112
+ if (state === 0)
113
+ paint.ownFilament = true;
114
+ else
115
+ paint.states.add(state);
116
+ }
117
+ }
118
+ result.set(`${path}#${object[1]}`, paint);
119
+ }
120
+ }
121
+ return result;
122
+ }
123
+ function projectFilaments(config) {
124
+ const list = (key) => Array.isArray(config[key]) ? config[key].map(String) : [];
125
+ return { colours: list("filament_colour"), materials: list("filament_type"), ids: list("filament_ids"), config };
126
+ }
127
+ function describe(index, project, name) {
128
+ const colour = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(project.colours[index - 1]?.trim() ?? "");
129
+ const material = project.materials[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
130
+ const filamentId = project.ids[index - 1]?.trim().replace(/[\u0000-\u001f\u007f]/g, " ").slice(0, 64);
131
+ return { index, ...(colour ? { colour: `#${colour[1].toUpperCase()}` } : {}), ...(material ? { material } : {}),
132
+ ...(filamentId ? { filament_id: filamentId } : {}), ...(name ? { name } : {}) };
133
+ }
134
+ /**
135
+ * The filaments each plate prints with, keyed by plate number. `settings` is model_settings.config, `model` the root
136
+ * 3D/3dmodel.model text.
137
+ */
138
+ export async function plateFilaments(zip, settings, model, plates) {
139
+ const text = async (name) => {
140
+ const file = zip.file(name);
141
+ if (!file)
142
+ return "";
143
+ const bytes = await file.async("nodebuffer");
144
+ if (bytes.length > MAX_TEXT_BYTES)
145
+ throw new Error(`${name} is too large to read.`);
146
+ return bytes.toString("utf8");
147
+ };
148
+ let config = {};
149
+ try {
150
+ const parsed = JSON.parse(await text("Metadata/project_settings.config") || "{}");
151
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
152
+ config = parsed;
153
+ }
154
+ catch { /* a project without readable settings declares no filaments */ }
155
+ const project = projectFilaments(config);
156
+ const declared = Math.min(MAX_FILAMENT, Math.max(project.colours.length, project.materials.length, project.ids.length));
157
+ const valid = (index) => index !== undefined && Number.isInteger(index) && index >= 1 && index <= MAX_FILAMENT && (!declared || index <= declared);
158
+ const objects = new Map(readModelObjects(settings).map(object => [object.id, object]));
159
+ // Root objects' components: which sub-object mesh in which file each part is (part id = component objectid).
160
+ const components = new Map();
161
+ for (const object of model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/(?:\w+:)?object>/g)) {
162
+ const parts = new Map();
163
+ for (const component of object[2].matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
164
+ const path = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1];
165
+ const id = /\bobjectid="(\d+)"/.exec(component[1])?.[1];
166
+ // Studio keys a component by (path, objectid); one without p:path names a mesh object in the root model
167
+ // itself, keyed by the root's empty path (bbs_3mf.cpp:4131-4148, 3891).
168
+ if (id)
169
+ parts.set(id, path || "3D/3dmodel.model");
170
+ }
171
+ if (parts.size)
172
+ components.set(object[1], parts);
173
+ }
174
+ // Model object order (1-based in layer_config_ranges.xml): the build items' order, as Studio creates the objects.
175
+ const buildItems = [...model.matchAll(/<(?:\w+:)?item\b([^>]*)\/?>/g)].map(item => item[1]);
176
+ const order = [...new Set(buildItems.flatMap(item => /\bobjectid="(\d+)"/.exec(item)?.[1] ?? []))];
177
+ // Each build item adds its object's next instance, with its own printable flag (bbs_3mf.cpp:4183-4185, 4375-4380);
178
+ // a plate names its copies by object_id and instance_id (bbs_3mf.cpp:4717-4719), and the CLI skips each copy that
179
+ // isn't printable (PartPlate.cpp:1311-1322).
180
+ const printableItems = new Map();
181
+ for (const item of buildItems) {
182
+ const id = /\bobjectid="(\d+)"/.exec(item)?.[1];
183
+ if (id)
184
+ printableItems.set(id, [...(printableItems.get(id) ?? []), !/\bprintable="(?:0|false)"/.test(item)]);
185
+ }
186
+ const printableCopy = (objectId, instanceId) => {
187
+ const flags = printableItems.get(objectId);
188
+ if (!flags)
189
+ return true;
190
+ return instanceId === undefined ? flags.some(Boolean) : flags[instanceId] !== false;
191
+ };
192
+ const rangeExtruders = new Map();
193
+ const ranges = await text("Metadata/layer_config_ranges.xml");
194
+ for (const object of ranges.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)) {
195
+ const objectId = order[Number(object[1]) - 1];
196
+ if (!objectId)
197
+ continue;
198
+ // A range's extruder sets all three feature filaments; a range's own feature filament overrides one
199
+ // (apply_to_print_region_config and resolve_filament_value, PrintObject.cpp:3069-3079, 3134-3137).
200
+ 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));
201
+ }
202
+ const toolChanges = new Map();
203
+ const custom = await text("Metadata/custom_gcode_per_layer.xml");
204
+ for (const plate of custom.matchAll(/<plate>([\s\S]*?)<\/plate>/g)) {
205
+ const id = Number(/<plate_info\b[^>]*\bid="(\d+)"/.exec(plate[1])?.[1]);
206
+ if (!Number.isInteger(id))
207
+ continue;
208
+ toolChanges.set(id, [...plate[1].matchAll(/<layer\b([^>]*)\/?>/g)]
209
+ .filter(layer => /\btype="2"/.test(layer[1]))
210
+ .map(layer => Number(/\bextruder="(\d+)"/.exec(layer[1])?.[1])));
211
+ }
212
+ // Painting only matters for parts on a plate that is not sliced yet.
213
+ const paintPaths = new Set();
214
+ for (const plate of plates)
215
+ if (!plate.slicedFilamentIds)
216
+ for (const objectId of plate.objectIds)
217
+ for (const path of components.get(objectId)?.values() ?? [])
218
+ paintPaths.add(path);
219
+ const painting = await readPainting(zip, paintPaths);
220
+ const global = (key) => intOf(config[key]) ?? 0;
221
+ const FEATURES = ["wall_filament", "sparse_infill_filament", "solid_infill_filament"];
222
+ const result = new Map();
223
+ for (const plate of plates) {
224
+ const used = new Map();
225
+ const add = (index, name) => {
226
+ if (!valid(index))
227
+ return;
228
+ if (!used.has(index) || (!used.get(index) && name))
229
+ used.set(index, name || undefined);
230
+ };
231
+ // An object counts once on a plate when any of its copies there prints.
232
+ const printing = plate.instances?.length
233
+ ? [...new Set(plate.instances.filter(copy => printableCopy(copy.objectId, copy.instanceId)).map(copy => copy.objectId))]
234
+ : plate.objectIds.filter(objectId => printableCopy(objectId));
235
+ for (const objectId of printing) {
236
+ const object = objects.get(objectId);
237
+ if (!object)
238
+ continue;
239
+ const objectInt = (key) => intOf(object.settings.get(key));
240
+ const parts = object.parts.length ? object.parts : [{ id: "", subtype: "normal_part", name: "", settings: new Map() }];
241
+ for (const part of parts) {
242
+ if (["negative_part", "support_blocker", "support_enforcer"].includes(part.subtype))
243
+ continue;
244
+ const partInt = (key) => intOf(part.settings.get(key));
245
+ // What the slicer prints the part with (region_config_from_model_volume, PrintObject.cpp:3105-3150): the
246
+ // project's feature filaments, replaced by the object's and then the part's extruder when one is set
247
+ // (non-zero), then by a feature filament the part, else the object, sets above 0.
248
+ const extruderSet = (partInt("extruder") ?? 0) > 0 || (objectInt("extruder") ?? 0) > 0;
249
+ const ownExtruder = partInt("extruder") || objectInt("extruder") || 1;
250
+ const label = part.name || object.name;
251
+ const path = components.get(objectId)?.get(part.id);
252
+ const paint = path ? painting.get(`${path}#${part.id}`) : undefined;
253
+ for (const state of paint?.states ?? [])
254
+ if (part.subtype === "normal_part")
255
+ add(state, label);
256
+ // A modifier's own filament counts whatever its paint (Model.cpp:3384-3390).
257
+ if (part.subtype !== "normal_part" || !paint || paint.ownFilament) {
258
+ if (extruderSet)
259
+ add(ownExtruder, label);
260
+ // Neither the part nor its object names an extruder: the project's feature filaments print it (each
261
+ // above 0; a project without them prints with filament 1, ModelVolume::extruder_id's default).
262
+ else
263
+ for (const key of FEATURES)
264
+ add(global(key) > 0 ? global(key) : 1, label);
265
+ }
266
+ for (const key of ["wall_filament", "solid_infill_filament", "sparse_infill_filament"]) {
267
+ const own = partInt(key);
268
+ if (own !== undefined) {
269
+ if (own > 0)
270
+ add(own, label);
271
+ }
272
+ else if ((objectInt(key) ?? 0) > 0)
273
+ add(objectInt(key), label);
274
+ }
275
+ // separate_filaments_for_features gates these only in Studio's plate list (PartPlate.cpp:1338-1381): it isn't
276
+ // a slicer setting in 02.08.02.61 (libslic3r never reads it), and the slice applies the part's or object's
277
+ // feature filaments whatever it says (PrintObject.cpp:3124-3150), as the loop above does.
278
+ }
279
+ for (const extruder of rangeExtruders.get(objectId) ?? [])
280
+ add(extruder, object.name);
281
+ // Support and raft as the slice resolves them: each setting the object's own, else the project's, one key at a
282
+ // time (PrintObject::object_config_from_model_object, PrintObject.cpp:3052-3063). Studio's plate list resolves
283
+ // the pair together (PartPlate.cpp:1383-1393), which drops support an object with only a raft override prints.
284
+ const setting = (key) => object.settings.has(key) ? object.settings.get(key) : config[key];
285
+ const support = (boolOf(setting("enable_support")) ?? false) || (intOf(setting("raft_layers")) ?? 0) > 0;
286
+ if (support) {
287
+ // 0 is "default": the support prints with the object's own filament (Print.cpp:490-501).
288
+ add(intOf(setting("support_interface_filament")) || undefined);
289
+ add(intOf(setting("support_filament")) || undefined);
290
+ }
291
+ }
292
+ for (const extruder of toolChanges.get(plate.number) ?? [])
293
+ add(extruder);
294
+ // Objects the settings don't describe (a plain 3MF) name no extruder: the project's feature filaments print them,
295
+ // else filament 1 (ModelVolume::extruder_id's default).
296
+ if (!used.size && (plate.objectIds.some(id => !objects.has(id)) || (!objects.size && buildItems.length)))
297
+ for (const key of FEATURES)
298
+ add(global(key) > 0 ? global(key) : 1);
299
+ // A mixed filament slot prints as its component filaments (PartPlate.cpp:1437-1449, expand_mixed_filaments in
300
+ // FilamentMixer.cpp:460-478; components are 1-based, comma-separated, FilamentMixer.cpp:165-180).
301
+ const mixed = Array.isArray(config.filament_is_mixed) ? config.filament_is_mixed.map(value => boolOf(value) === true) : [];
302
+ const mixedComponents = Array.isArray(config.filament_mixed_components) ? config.filament_mixed_components.map(String) : [];
303
+ if (mixed.some(Boolean))
304
+ for (const [index, name] of [...used]) {
305
+ if (!mixed[index - 1] || index - 1 >= mixedComponents.length)
306
+ continue;
307
+ used.delete(index);
308
+ for (const part of mixedComponents[index - 1].split(",")) {
309
+ const component = /^\s*\d+\s*$/.test(part) ? Number(part) : 0;
310
+ if (component >= 1)
311
+ add(component, name);
312
+ }
313
+ }
314
+ if (plate.slicedFilamentIds) {
315
+ // The slice is Studio's own answer: it replaces the derivation, keeping names the derivation found.
316
+ const names = new Map(used);
317
+ used.clear();
318
+ for (const id of plate.slicedFilamentIds)
319
+ add(id + 1, names.get(id + 1));
320
+ }
321
+ result.set(plate.number, [...used.entries()].sort((a, b) => a[0] - b[0]).map(([index, name]) => describe(index, project, name)));
322
+ }
323
+ // Every filament the project declares, used on a plate or not: slice_stl takes one profile per declared filament.
324
+ return { plates: result, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)) };
325
+ }
package/dist/index.js CHANGED
@@ -30,7 +30,7 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
30
30
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
31
31
  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";
32
32
  import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake } from "./design-app-setup.js";
33
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
33
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMapping, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
34
34
  import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, hasSlicerSettingsFile, parse3MF, withExtractedSettingsCleanup } from './3mf_parser.js';
35
35
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
36
36
  import { resolveStudioPrintOptions, usedNozzleCount } from "./studio-print-options.js";
@@ -1429,7 +1429,8 @@ class BambuPrinterMCPServer {
1429
1429
  const resumeFile = await checkedFile(inspection, snapshot);
1430
1430
  // The options Bambu Studio's Send dialog would send; explicit ones win.
1431
1431
  const studio = resolveStudioPrintOptions(printModel, callerPrintOptions(args), { usedNozzles: usedNozzleCount(inspection) });
1432
- let mapping = finalAmsMapping?.slice();
1432
+ // Bambu Studio maps only the plate's own filaments; every other project filament is -1 (SelectMachine.cpp:1463-1500).
1433
+ let mapping = finalAmsMapping ? studioAmsMapping(finalAmsMapping, inspection.usedFilamentPositions) : undefined;
1433
1434
  if (finalAmsSlots) {
1434
1435
  if (finalAmsSlots.length !== inspection.usedFilamentPositions.length)
1435
1436
  throw new Error("ams_slots must supply exactly one physical tray per used filament.");
@@ -2057,7 +2058,7 @@ class BambuPrinterMCPServer {
2057
2058
  },
2058
2059
  {
2059
2060
  name: "list_3mf_plates",
2060
- 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.",
2061
+ 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.",
2061
2062
  inputSchema: {
2062
2063
  type: "object",
2063
2064
  properties: {
@@ -2862,7 +2863,7 @@ class BambuPrinterMCPServer {
2862
2863
  use_ams: { type: "boolean", description: "Whether to use the AMS (default: auto-detect from 3MF)" },
2863
2864
  ams_mapping: {
2864
2865
  type: "array",
2865
- 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.",
2866
+ 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.",
2866
2867
  items: { type: "number" }
2867
2868
  },
2868
2869
  ams_slots: {