bambu-printer-mcp 1.1.62 → 1.1.64

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.
@@ -0,0 +1,292 @@
1
+ import { COUNTERPART_CONTRACT, PRINTER_KINDS } from "./schemas.js";
2
+ export declare const SETUP_FIELD_NAMES: readonly ["host", "port", "serial", "model", "secret", "slicer", "slicer-path", "profiles"];
3
+ export type SetupField = {
4
+ /** The client's form field this is: an address, a port, a serial number, a model choice or a secret. */
5
+ name: typeof SETUP_FIELD_NAMES[number];
6
+ /** The variable to write. */
7
+ env: string;
8
+ /** Older names for it that this server reads before `env`: a client writing `env` removes these lines, or the old value wins. */
9
+ aliases?: string[];
10
+ label: string;
11
+ hint?: string;
12
+ required: boolean;
13
+ /** A path on this computer (a slicer app, a profiles folder): a client may offer a file chooser. */
14
+ input?: "path";
15
+ /** Written as typed, or upper-cased (Bambu serial numbers). */
16
+ transform?: "uppercase";
17
+ choices?: Array<{
18
+ value: string;
19
+ label: string;
20
+ }>;
21
+ /** A model field: the model a serial number names, by its first `prefixLength` characters. */
22
+ fromSerial?: {
23
+ prefixLength: number;
24
+ models: Record<string, string>;
25
+ };
26
+ };
27
+ export type SetupKind = {
28
+ kind: typeof PRINTER_KINDS[number];
29
+ label: string;
30
+ /** Values this server needs for the kind whatever the person enters (MCP_TRANSPORT, PRINTER_TYPE). */
31
+ env: Record<string, string>;
32
+ fields: SetupField[];
33
+ };
34
+ /** The slicer this server runs, as it resolves it now, and the settings that choose it (for every printer). */
35
+ export type SlicerSetup = {
36
+ type: string;
37
+ /** The slicer app it would run, and whether that app is there. */
38
+ path?: string;
39
+ found: boolean;
40
+ /** The Bambu profiles folder it would read (Bambu Studio and Orca), and whether it has BBL's profiles. */
41
+ profilesRoot?: string;
42
+ profilesFound?: boolean;
43
+ fields: SetupField[];
44
+ };
45
+ export type SetupFields = {
46
+ contract: typeof COUNTERPART_CONTRACT;
47
+ server: {
48
+ name: string;
49
+ version: string;
50
+ };
51
+ kinds: SetupKind[];
52
+ model?: string;
53
+ slicer?: SlicerSetup;
54
+ };
55
+ /**
56
+ * The slicer settings, with what this server resolves now: a client shows "Bambu Studio isn't installed" or asks for
57
+ * its location instead of the person editing SLICER_PATH by hand. A setting is required only when what it would
58
+ * default to isn't there.
59
+ */
60
+ export declare function slicerSetup(options: {
61
+ types: readonly string[];
62
+ type: string;
63
+ path?: string;
64
+ found: boolean;
65
+ profilesRoot?: string;
66
+ profilesFound?: boolean;
67
+ remote?: boolean;
68
+ }): SlicerSetup;
69
+ /** Each serial prefix's model in this server's values (bambu_model), where it has one. */
70
+ export declare function serialModelValues(valid: readonly string[]): Record<string, string>;
71
+ /** Bambu's display names for this server's model values ("a1mini" → "A1 Mini"). */
72
+ export declare function modelChoices(valid: readonly string[]): Array<{
73
+ value: string;
74
+ label: string;
75
+ }>;
76
+ export declare function bambuSetupFields(options: {
77
+ server: {
78
+ name: string;
79
+ version: string;
80
+ };
81
+ models: readonly string[];
82
+ serial?: string;
83
+ slicer?: SlicerSetup;
84
+ }): SetupFields;
85
+ export declare const SETUP_FIELDS_OUTPUT_SCHEMA: {
86
+ type: "object";
87
+ properties: {
88
+ contract: {
89
+ type: string;
90
+ const: string;
91
+ };
92
+ server: {
93
+ type: string;
94
+ properties: {
95
+ name: {
96
+ type: string;
97
+ };
98
+ version: {
99
+ type: string;
100
+ };
101
+ };
102
+ required: string[];
103
+ };
104
+ kinds: {
105
+ type: string;
106
+ items: {
107
+ type: string;
108
+ properties: {
109
+ kind: {
110
+ type: string;
111
+ enum: ("bambu" | "octoprint" | "klipper" | "prusa" | "duet" | "repetier" | "creality")[];
112
+ };
113
+ label: {
114
+ type: string;
115
+ };
116
+ env: {
117
+ type: string;
118
+ additionalProperties: {
119
+ type: string;
120
+ };
121
+ };
122
+ fields: {
123
+ type: string;
124
+ items: {
125
+ type: string;
126
+ properties: {
127
+ name: {
128
+ type: string;
129
+ enum: ("model" | "slicer" | "host" | "port" | "profiles" | "serial" | "secret" | "slicer-path")[];
130
+ };
131
+ env: {
132
+ type: string;
133
+ };
134
+ aliases: {
135
+ type: string;
136
+ items: {
137
+ type: string;
138
+ };
139
+ description: string;
140
+ };
141
+ label: {
142
+ type: string;
143
+ };
144
+ hint: {
145
+ type: string;
146
+ };
147
+ required: {
148
+ type: string;
149
+ };
150
+ input: {
151
+ type: string;
152
+ enum: string[];
153
+ };
154
+ transform: {
155
+ type: string;
156
+ enum: string[];
157
+ };
158
+ choices: {
159
+ type: string;
160
+ items: {
161
+ type: string;
162
+ properties: {
163
+ value: {
164
+ type: string;
165
+ };
166
+ label: {
167
+ type: string;
168
+ };
169
+ };
170
+ required: string[];
171
+ };
172
+ };
173
+ fromSerial: {
174
+ type: string;
175
+ properties: {
176
+ prefixLength: {
177
+ type: string;
178
+ };
179
+ models: {
180
+ type: string;
181
+ additionalProperties: {
182
+ type: string;
183
+ };
184
+ };
185
+ };
186
+ required: string[];
187
+ };
188
+ };
189
+ required: string[];
190
+ };
191
+ };
192
+ };
193
+ required: string[];
194
+ };
195
+ };
196
+ model: {
197
+ type: string;
198
+ };
199
+ slicer: {
200
+ type: string;
201
+ properties: {
202
+ type: {
203
+ type: string;
204
+ };
205
+ path: {
206
+ type: string;
207
+ };
208
+ found: {
209
+ type: string;
210
+ };
211
+ profilesRoot: {
212
+ type: string;
213
+ };
214
+ profilesFound: {
215
+ type: string;
216
+ };
217
+ fields: {
218
+ type: string;
219
+ items: {
220
+ type: string;
221
+ properties: {
222
+ name: {
223
+ type: string;
224
+ enum: ("model" | "slicer" | "host" | "port" | "profiles" | "serial" | "secret" | "slicer-path")[];
225
+ };
226
+ env: {
227
+ type: string;
228
+ };
229
+ aliases: {
230
+ type: string;
231
+ items: {
232
+ type: string;
233
+ };
234
+ description: string;
235
+ };
236
+ label: {
237
+ type: string;
238
+ };
239
+ hint: {
240
+ type: string;
241
+ };
242
+ required: {
243
+ type: string;
244
+ };
245
+ input: {
246
+ type: string;
247
+ enum: string[];
248
+ };
249
+ transform: {
250
+ type: string;
251
+ enum: string[];
252
+ };
253
+ choices: {
254
+ type: string;
255
+ items: {
256
+ type: string;
257
+ properties: {
258
+ value: {
259
+ type: string;
260
+ };
261
+ label: {
262
+ type: string;
263
+ };
264
+ };
265
+ required: string[];
266
+ };
267
+ };
268
+ fromSerial: {
269
+ type: string;
270
+ properties: {
271
+ prefixLength: {
272
+ type: string;
273
+ };
274
+ models: {
275
+ type: string;
276
+ additionalProperties: {
277
+ type: string;
278
+ };
279
+ };
280
+ };
281
+ required: string[];
282
+ };
283
+ };
284
+ required: string[];
285
+ };
286
+ };
287
+ };
288
+ required: string[];
289
+ };
290
+ };
291
+ required: string[];
292
+ };
@@ -0,0 +1,91 @@
1
+ /**
2
+ * counterpart_setup_fields (counterpart/1): the printers this server drives and the settings it reads for each, by the
3
+ * environment variable names it reads (`env`, and older `aliases` it reads first). A client renders these fields, writes the values
4
+ * to this server's .env and never needs its own printer or model tables. Pure: no printer traffic, no secrets returned.
5
+ */
6
+ import { normalizeModel } from "../safety/limits.js";
7
+ import { SERIAL_MODELS } from "../safety/printer-state.js";
8
+ import { COUNTERPART_CONTRACT, PRINTER_KINDS } from "./schemas.js";
9
+ export const SETUP_FIELD_NAMES = ["host", "port", "serial", "model", "secret", "slicer", "slicer-path", "profiles"];
10
+ const SLICER_LABELS = {
11
+ bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "OrcaSlicer-bambulab (FULU)", "orca-slicer-api": "OrcaSlicer API (remote)",
12
+ prusaslicer: "PrusaSlicer", cura: "Cura", slic3r: "Slic3r",
13
+ };
14
+ /**
15
+ * The slicer settings, with what this server resolves now: a client shows "Bambu Studio isn't installed" or asks for
16
+ * its location instead of the person editing SLICER_PATH by hand. A setting is required only when what it would
17
+ * default to isn't there.
18
+ */
19
+ export function slicerSetup(options) {
20
+ const label = SLICER_LABELS[options.type] ?? options.type;
21
+ const fields = [
22
+ { name: "slicer", env: "SLICER_TYPE", label: "Slicer", required: false, choices: options.types.map(value => ({ value, label: SLICER_LABELS[value] ?? value })) },
23
+ ];
24
+ if (!options.remote)
25
+ fields.push({ name: "slicer-path", env: "SLICER_PATH", label: `${label} app`, input: "path", required: !options.found,
26
+ hint: options.found ? `Found at ${options.path}. Set this only to use another copy.`
27
+ : options.path ? `${label} isn't at ${options.path}. Install it, or choose where it is.` : `Where ${label} is installed.` });
28
+ if (options.profilesFound !== undefined)
29
+ fields.push({ name: "profiles", env: "BAMBU_PROFILES_ROOT", label: "Bambu profiles folder", input: "path", required: !options.profilesFound,
30
+ hint: options.profilesFound ? `Found at ${options.profilesRoot}. Set this only to use other profiles.` : `The folder with ${label}'s BBL profiles (it holds BBL/machine). Install ${label}, or choose the folder.` });
31
+ return { type: options.type, ...(options.path !== undefined ? { path: options.path } : {}), found: options.found,
32
+ ...(options.profilesRoot !== undefined ? { profilesRoot: options.profilesRoot } : {}), ...(options.profilesFound !== undefined ? { profilesFound: options.profilesFound } : {}), fields };
33
+ }
34
+ /** Each serial prefix's model in this server's values (bambu_model), where it has one. */
35
+ export function serialModelValues(valid) {
36
+ return Object.fromEntries(Object.entries(SERIAL_MODELS).flatMap(([prefix, name]) => {
37
+ const model = normalizeModel(name);
38
+ return model && valid.includes(model) ? [[prefix, model]] : [];
39
+ }));
40
+ }
41
+ /** Bambu's display names for this server's model values ("a1mini" → "A1 Mini"). */
42
+ export function modelChoices(valid) {
43
+ const names = new Map(Object.values(SERIAL_MODELS).map(name => [normalizeModel(name), name]));
44
+ return valid.map(value => ({ value, label: names.get(value) ?? value.toUpperCase() }));
45
+ }
46
+ export function bambuSetupFields(options) {
47
+ const fromSerial = { prefixLength: 3, models: serialModelValues(options.models) };
48
+ const model = options.serial ? fromSerial.models[options.serial.trim().slice(0, 3).toUpperCase()] : undefined;
49
+ return {
50
+ contract: COUNTERPART_CONTRACT,
51
+ server: options.server,
52
+ kinds: [{
53
+ kind: "bambu", label: "Bambu Lab", env: { MCP_TRANSPORT: "stdio" },
54
+ fields: [
55
+ { name: "host", env: "PRINTER_HOST", aliases: ["BAMBU_PRINTER_HOST"], label: "Address", hint: "The printer's IP address: on the printer, Settings → WLAN", required: true },
56
+ { name: "serial", env: "BAMBU_SERIAL", aliases: ["BAMBU_PRINTER_SERIAL"], label: "Serial number", hint: "On the printer: Settings → Device", required: true, transform: "uppercase" },
57
+ { name: "model", env: "BAMBU_MODEL", aliases: ["BAMBU_PRINTER_MODEL"], label: "Model", required: true, choices: modelChoices(options.models), fromSerial },
58
+ { name: "secret", env: "BAMBU_TOKEN", aliases: ["BAMBU_PRINTER_ACCESS_TOKEN"], label: "Access code", hint: "On the printer: Settings → WLAN → Access Code", required: true },
59
+ ],
60
+ }],
61
+ ...(model ? { model } : {}),
62
+ ...(options.slicer ? { slicer: options.slicer } : {}),
63
+ };
64
+ }
65
+ const field = {
66
+ type: "object",
67
+ properties: {
68
+ name: { type: "string", enum: [...SETUP_FIELD_NAMES] }, env: { type: "string" }, aliases: { type: "array", items: { type: "string" }, description: "Older names this server reads before env: a client writing env removes these, or the old value wins." },
69
+ label: { type: "string" }, hint: { type: "string" }, required: { type: "boolean" }, input: { type: "string", enum: ["path"] }, transform: { type: "string", enum: ["uppercase"] },
70
+ choices: { type: "array", items: { type: "object", properties: { value: { type: "string" }, label: { type: "string" } }, required: ["value", "label"] } },
71
+ fromSerial: { type: "object", properties: { prefixLength: { type: "integer" }, models: { type: "object", additionalProperties: { type: "string" } } }, required: ["prefixLength", "models"] },
72
+ },
73
+ required: ["name", "env", "label", "required"],
74
+ };
75
+ export const SETUP_FIELDS_OUTPUT_SCHEMA = {
76
+ type: "object",
77
+ properties: {
78
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
79
+ server: { type: "object", properties: { name: { type: "string" }, version: { type: "string" } }, required: ["name", "version"] },
80
+ kinds: { type: "array", items: { type: "object", properties: {
81
+ kind: { type: "string", enum: [...PRINTER_KINDS] }, label: { type: "string" },
82
+ env: { type: "object", additionalProperties: { type: "string" } }, fields: { type: "array", items: field },
83
+ }, required: ["kind", "label", "env", "fields"] } },
84
+ model: { type: "string" },
85
+ slicer: { type: "object", properties: {
86
+ type: { type: "string" }, path: { type: "string" }, found: { type: "boolean" }, profilesRoot: { type: "string" }, profilesFound: { type: "boolean" },
87
+ fields: { type: "array", items: field },
88
+ }, required: ["type", "found", "fields"] },
89
+ },
90
+ required: ["contract", "server", "kinds"],
91
+ };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * What a client shows about a sliced file, read here so it never parses slicer formats itself (Counterpart PRD
3
+ * §8.0 item 9): the selected plate's estimate and slice settings, and how many printable plates the file has.
4
+ * Bambu Studio and OrcaSlicer 3MFs carry them in Metadata/slice_info.config, project_settings.config and the
5
+ * plate's G-code header; a G-code file in its own header and footer comments. Anything not found is left out.
6
+ */
7
+ export interface SlicedFileFacts {
8
+ plate_count?: number;
9
+ estimate?: {
10
+ seconds?: number;
11
+ grams?: number;
12
+ };
13
+ settings: {
14
+ layer_height_mm?: number;
15
+ sparse_infill_percent?: number;
16
+ wall_loops?: number;
17
+ layer_count?: number;
18
+ };
19
+ }
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
+ export declare function slicedFileFacts(filePath: string, plateIndex?: number): Promise<SlicedFileFacts>;
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.
25
+ */
26
+ export interface SlicerReport {
27
+ failed: boolean;
28
+ message?: string;
29
+ plate_count?: number;
30
+ }
31
+ export declare function slicerReport(result: unknown): SlicerReport | undefined;
@@ -0,0 +1,110 @@
1
+ import fs from "node:fs";
2
+ import { loadSafe3mfArchive, readBoundedPrintFile } from "../safety/archive.js";
3
+ const number = (value) => {
4
+ const parsed = typeof value === "number" ? value : typeof value === "string" ? Number.parseFloat(value) : NaN;
5
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
6
+ };
7
+ const first = (value) => Array.isArray(value) ? value[0] : value;
8
+ const defined = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
9
+ function headerSettings(text) {
10
+ const read = (pattern) => number(text.match(pattern)?.[1]);
11
+ const layers = read(/^;\s*(?:total layer number|total layers count|LAYER_COUNT)\s*[:=]\s*(\d+)/im);
12
+ const walls = read(/^;\s*(?:wall_loops|perimeters)\s*=\s*(\d+)/im);
13
+ return defined({
14
+ layer_height_mm: read(/^;\s*layer_height\s*=\s*([\d.]+)/im),
15
+ sparse_infill_percent: read(/^;\s*(?:sparse_infill_density|fill_density)\s*=\s*([\d.]+)%/im),
16
+ wall_loops: walls === undefined ? undefined : Math.trunc(walls),
17
+ layer_count: layers ? Math.trunc(layers) : undefined,
18
+ });
19
+ }
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
+ export async function slicedFileFacts(filePath, plateIndex = 0) {
22
+ try {
23
+ return await readFacts(filePath, plateIndex);
24
+ }
25
+ catch {
26
+ return { settings: {} };
27
+ }
28
+ }
29
+ async function readFacts(filePath, plateIndex) {
30
+ const head = Buffer.alloc(4);
31
+ const handle = await fs.promises.open(filePath, "r");
32
+ try {
33
+ await handle.read(head, 0, 4, 0);
34
+ }
35
+ finally {
36
+ await handle.close();
37
+ }
38
+ if (head[0] !== 0x50 || head[1] !== 0x4b) {
39
+ // G-code: PrusaSlicer and Orca write their settings in a footer, others in a header; read both ends.
40
+ const stat = await fs.promises.stat(filePath);
41
+ const size = 256 * 1024;
42
+ const read = async (start) => {
43
+ const buffer = Buffer.alloc(Math.min(size, stat.size));
44
+ const file = await fs.promises.open(filePath, "r");
45
+ try {
46
+ await file.read(buffer, 0, buffer.length, start);
47
+ }
48
+ finally {
49
+ await file.close();
50
+ }
51
+ return buffer.toString("latin1");
52
+ };
53
+ return { plate_count: 1, settings: headerSettings(`${await read(0)}\n${await read(Math.max(0, stat.size - size))}`) };
54
+ }
55
+ const zip = await loadSafe3mfArchive(await readBoundedPrintFile(filePath));
56
+ const plates = new Set(Object.keys(zip.files).flatMap(name => /^Metadata\/plate_([1-9]\d*)\.gcode$/.exec(name)?.[1] ?? []));
57
+ const text = async (name) => zip.file(name)?.async("string");
58
+ let settings = {};
59
+ const project = await text("Metadata/project_settings.config");
60
+ if (project) {
61
+ try {
62
+ const values = JSON.parse(project);
63
+ const infill = String(first(values.sparse_infill_density) ?? "");
64
+ const walls = number(first(values.wall_loops));
65
+ settings = defined({
66
+ layer_height_mm: number(first(values.layer_height)),
67
+ sparse_infill_percent: infill === "" ? undefined : number(infill.replace("%", "")),
68
+ wall_loops: walls === undefined ? undefined : Math.trunc(walls),
69
+ });
70
+ }
71
+ catch { /* the settings stay unknown */ }
72
+ }
73
+ // Only the plate G-code's header, never the whole (often hundreds of MB) as a string.
74
+ const gcode = await zip.file(`Metadata/plate_${plateIndex + 1}.gcode`)?.async("nodebuffer");
75
+ // The project settings are authoritative; the plate's G-code header adds the layer count.
76
+ if (gcode)
77
+ settings = { ...headerSettings(gcode.subarray(0, 64 * 1024).toString("latin1")), ...settings };
78
+ let estimate;
79
+ const info = await text("Metadata/slice_info.config");
80
+ const plate = info?.match(/<plate(?:\s[^>]*)?>[\s\S]*?<\/plate>/g)
81
+ ?.find(block => new RegExp(`<metadata\\s+key=["']index["']\\s+value=["']${plateIndex + 1}["']`).test(block));
82
+ if (plate) {
83
+ const value = (key) => {
84
+ const found = plate.match(new RegExp(`<metadata\\s+key=["']${key}["']\\s+value=["']([^"']+)["']`))?.[1];
85
+ const parsed = found && /^\d+(?:\.\d+)?$/.test(found) ? Number(found) : undefined;
86
+ return parsed !== undefined && parsed > 0 ? parsed : undefined;
87
+ };
88
+ const seconds = value("prediction"), grams = value("weight");
89
+ if (seconds !== undefined || grams !== undefined)
90
+ estimate = defined({ seconds, grams });
91
+ }
92
+ return { ...(plates.size ? { plate_count: plates.size } : {}), ...(estimate ? { estimate } : {}), settings };
93
+ }
94
+ const clean = (text) => text.replace(/\r\n?/g, "\n").replace(/[\x00-\x09\x0b-\x1f\x7f]/g, " ").trim();
95
+ export function slicerReport(result) {
96
+ if (!result || typeof result !== "object" || Array.isArray(result))
97
+ return undefined;
98
+ const value = result;
99
+ const plates = Array.isArray(value.sliced_plates) ? value.sliced_plates : [];
100
+ const ids = plates.map(plate => plate && typeof plate === "object" ? plate.id : undefined);
101
+ const plateCount = ids.length && ids.every(id => typeof id === "number" && Number.isSafeInteger(id) && id > 0) ? new Set(ids).size : undefined;
102
+ const warnings = plates.map(plate => plate && typeof plate.warning_message === "string" ? clean(plate.warning_message) : "").filter(Boolean);
103
+ // Anything but the slicer's success code fails closed, a missing one included.
104
+ const failed = value.return_code !== 0;
105
+ const error = typeof value.error_string === "string" ? clean(value.error_string) : "";
106
+ const words = [...new Set([...(failed && error ? [error] : []), ...warnings])].join("\n").slice(0, 2000);
107
+ 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 } : {}) };
110
+ }