bambu-printer-mcp 1.1.54 → 1.1.56

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
@@ -1197,6 +1197,8 @@ When `slicer_type` is `bambustudio` (the default), these additional parameters a
1197
1197
  | `min_save` | boolean | Produce smaller output 3MF (faster uploads) |
1198
1198
  | `skip_modified_gcodes` | boolean | Ignore stale custom gcodes in the 3MF |
1199
1199
  | `slice_plate` | number | Which plate to slice (0 = all plates, default: 0) |
1200
+ | `quality` | string | `draft`, `standard` or `fine`: the server picks the layer height for the nozzle in use (0.28 and 0.12 mm on 0.4 mm; standard keeps the preset) |
1201
+ | `strength` | string | `standard`, `strong` or `max`: the server picks walls and infill (4 walls at 25%, 6 at 40%; standard keeps the preset) |
1200
1202
  | `layer_height` | number | Layer height in mm, such as 0.28, 0.2 or 0.12; at most the nozzle diameter |
1201
1203
  | `wall_loops` | integer | Number of walls, 0 to 1000 |
1202
1204
  | `sparse_infill_density` | string | Sparse infill density, such as `"15%"` |
@@ -1204,7 +1206,7 @@ When `slicer_type` is `bambustudio` (the default), these additional parameters a
1204
1206
  | `support_type` | string | `normal(auto)`, `tree(auto)`, `normal(manual)` or `tree(manual)` |
1205
1207
  | `support_threshold_angle` | integer | Overhang threshold for automatic supports, 0 to 90 degrees (0 lets the slicer decide) |
1206
1208
 
1207
- `layer_height`, `wall_loops`, `sparse_infill_density` and the three support arguments are written as a process override on top of the machine and process preset the tool resolves, using Bambu Studio's keys and string forms (`"0.2"`, `"2"`, `"15%"`). Every other preset value, and the machine preset, stay as resolved, and your own profile files are not changed. They work with every Bambu-compatible slicer, including remote `orca-slicer-api` slicing, and are refused for PrusaSlicer, Slic3r and Cura.
1209
+ `quality` and `strength` let a client send the person's choice without slicer numbers; an explicit `layer_height`, `wall_loops` or `sparse_infill_density` wins over them. `layer_height`, `wall_loops`, `sparse_infill_density` and the three support arguments are written as a process override on top of the machine and process preset the tool resolves, using Bambu Studio's keys and string forms (`"0.2"`, `"2"`, `"15%"`). Every other preset value, and the machine preset, stay as resolved, and your own profile files are not changed. They work with every Bambu-compatible slicer, including remote `orca-slicer-api` slicing, and are refused for PrusaSlicer, Slic3r and Cura.
1208
1210
 
1209
1211
  **Example: Slice with auto-orient and 3 copies**
1210
1212
  ```json
@@ -193,10 +193,16 @@ export declare class BambuNetworkBridge {
193
193
  * Shares the LAN session queue: one reader of the plug-in's events at a time.
194
194
  */
195
195
  withCloudSession<T>(devId: string, options: BambuNetworkBridgeOptions, assertActive: () => void, timing: Readonly<CloudTiming>, run: (session: CloudSession) => Promise<T>): Promise<T>;
196
- /** A cloud print method (start_print) in a cloud session, so the plug-in has the printer's state. */
197
- startCloudPrint(devId: string, method: string, payload: JsonObject, options?: BambuNetworkBridgeOptions, assertActive?: () => void, timing?: Readonly<CloudTiming>): Promise<{
196
+ /**
197
+ * A cloud print in a cloud session, so the plug-in has the printer's state. With a fallback this is
198
+ * Bambu Studio's order for a cloud-bound printer it can also reach on the LAN (PrintJob.cpp,
199
+ * SendAttemptRoute::LanWithRecord, then ::Cloud): start_local_print_with_record, then start_print
200
+ * when the first failed before its print command was sent. `firstFailure` is the first method's result.
201
+ */
202
+ startCloudPrint(devId: string, method: string, payload: JsonObject, options?: BambuNetworkBridgeOptions, assertActive?: () => void, timing?: Readonly<CloudTiming>, fallbackMethod?: string): Promise<{
198
203
  result: unknown;
199
204
  jobUpdates: BridgeJobUpdate[];
205
+ firstFailure?: number;
200
206
  }>;
201
207
  /**
202
208
  * A print control over Bambu Cloud: how Bambu Studio and FULU's slicer control a printer
@@ -16,8 +16,16 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 120000;
16
16
  const LOCAL_CONNECT_STATUS = ["ok", "failed", "lost"];
17
17
  // bambu_networking.hpp BAMBU_NETWORK_ERR_PRINT_LP_PUBLISH_MSG_FAILED.
18
18
  const LOCAL_PRINT_PUBLISH_FAILED = -4030;
19
+ // A with-record send falls back to start_print only on its own preparation failures (the plug-in's
20
+ // PRINT_WR_* results, -2010 to -2140: project, upload, task record, FTPS), which come before the print
21
+ // command, so the printer has no job. Any other result may have reached the printer and is never
22
+ // replayed. Of those, Studio also stops on a file missing or too large (should_stop_without_fallback).
23
+ const WITH_RECORD_PREPARATION_FAILURE = (value) => value <= -2010 && value >= -2140 && value !== -2040 && value !== -2100;
19
24
  // bambu_networking.hpp print errors that name a recoverable cause.
20
25
  const BAMBU_NETWORK_PRINT_ERRORS = {
26
+ [-2120]: "Bambu Cloud refused to create the print task",
27
+ [-2130]: "FTPS upload to the printer failed",
28
+ [-3120]: "Bambu Cloud refused to create the print task",
21
29
  [-4010]: "the file exceeds the 1 GB upload limit",
22
30
  [-4020]: "FTPS upload to the printer failed",
23
31
  [LOCAL_PRINT_PUBLISH_FAILED]: "the networking plug-in could not send the print command to the printer over MQTT",
@@ -706,9 +714,23 @@ export class BambuNetworkBridge {
706
714
  release();
707
715
  }
708
716
  }
709
- /** A cloud print method (start_print) in a cloud session, so the plug-in has the printer's state. */
710
- async startCloudPrint(devId, method, payload, options = {}, assertActive = () => { }, timing = CLOUD_PRINT_TIMING) {
711
- return await this.withCloudSession(devId, options, assertActive, timing, async (session) => ({ result: await this.callWithAgent(method, payload, options), jobUpdates: session.jobUpdates }));
717
+ /**
718
+ * A cloud print in a cloud session, so the plug-in has the printer's state. With a fallback this is
719
+ * Bambu Studio's order for a cloud-bound printer it can also reach on the LAN (PrintJob.cpp,
720
+ * SendAttemptRoute::LanWithRecord, then ::Cloud): start_local_print_with_record, then start_print
721
+ * when the first failed before its print command was sent. `firstFailure` is the first method's result.
722
+ */
723
+ async startCloudPrint(devId, method, payload, options = {}, assertActive = () => { }, timing = CLOUD_PRINT_TIMING, fallbackMethod) {
724
+ return await this.withCloudSession(devId, options, assertActive, timing, async (session) => {
725
+ const result = await this.callWithAgent(method, payload, options);
726
+ const value = bridgeNumericResult(result);
727
+ if (!fallbackMethod || value === undefined || !WITH_RECORD_PREPARATION_FAILURE(value))
728
+ return { result, jobUpdates: session.jobUpdates };
729
+ options.trace?.({ step: "fallback", from: method, to: fallbackMethod, result: value });
730
+ const params = payload.params;
731
+ const fallbackPayload = params ? { ...payload, params: { ...params, comments: `failed(${value})` } } : payload;
732
+ return { result: await this.callWithAgent(fallbackMethod, fallbackPayload, options), jobUpdates: session.jobUpdates, firstFailure: value };
733
+ });
712
734
  }
713
735
  /**
714
736
  * A print control over Bambu Cloud: how Bambu Studio and FULU's slicer control a printer
package/dist/index.js CHANGED
@@ -33,6 +33,7 @@ import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
33
33
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
34
34
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
35
35
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
36
+ import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
36
37
  import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
37
38
  dotenv.config();
38
39
  const DEFAULT_HOST = process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST || "localhost";
@@ -1247,9 +1248,15 @@ class BambuPrinterMCPServer {
1247
1248
  throw new Error("plate_index must be a non-negative integer.");
1248
1249
  }
1249
1250
  const connectionType = resolveConnection(args).type;
1250
- const bridgePrintMethod = resolveBambuNetworkPrintMethod(args?.bambu_network_method !== undefined ? String(args.bambu_network_method) : undefined, connectionType);
1251
- const bridgeMethod = toBridgeMethod(bridgePrintMethod);
1251
+ // With no method given, a cloud print follows Bambu Studio's order for a cloud-bound printer it can
1252
+ // reach on the LAN (PrintJob.cpp): start_local_print_with_record in the cloud session, then start_print.
1253
+ // This server always has the printer's IP and access code, which Studio needs for the first.
1254
+ const studioCloudRoute = connectionType === "cloud" && args?.bambu_network_method === undefined;
1255
+ const bridgePrintMethod = studioCloudRoute ? "start_local_print_with_record" : resolveBambuNetworkPrintMethod(args?.bambu_network_method !== undefined ? String(args.bambu_network_method) : undefined, connectionType);
1256
+ let bridgeMethod = toBridgeMethod(bridgePrintMethod);
1252
1257
  const isLocalBridgePrint = bridgePrintMethod !== "start_print";
1258
+ const inCloudSession = studioCloudRoute || !isLocalBridgePrint;
1259
+ let cloudFallbackMethod = studioCloudRoute ? toBridgeMethod("start_print") : undefined;
1253
1260
  const devId = String(args?.dev_id || bambuSerial || DEFAULT_BAMBU_DEV_ID).trim();
1254
1261
  if (!devId) {
1255
1262
  throw new Error("dev_id is required for FULU BambuNetwork printing. Pass dev_id or set BAMBU_DEV_ID/BAMBU_SERIAL.");
@@ -1313,6 +1320,11 @@ class BambuPrinterMCPServer {
1313
1320
  const amsMapping = stringifyBridgeJson(mapping?.map(value => bridgeAmsMappingValue(value, isDualNozzleModel(printModel))));
1314
1321
  const remoteFileName = uniquePrintName(threeMFPath);
1315
1322
  const checkedName = remoteFileName.replace(/(?:\.gcode)?\.3mf$/i, "");
1323
+ if (cloudFallbackMethod && externalStorageState(confirmedStatus.raw) !== "normal") {
1324
+ // Studio sends straight through the cloud when the printer has no storage for the LAN upload.
1325
+ bridgeMethod = cloudFallbackMethod;
1326
+ cloudFallbackMethod = undefined;
1327
+ }
1316
1328
  const params = {
1317
1329
  dev_id: devId,
1318
1330
  // Firmware can report the task name instead of the uploaded filename.
@@ -1407,26 +1419,31 @@ class BambuPrinterMCPServer {
1407
1419
  const bridgeOptions = {
1408
1420
  ...this.bridgeOptionsFromArgs(args, "print_3mf_bambu_network"),
1409
1421
  beforeDispatch: async (method) => {
1410
- if (method !== bridgeMethod)
1422
+ if (method !== bridgeMethod && method !== cloudFallbackMethod)
1411
1423
  return;
1412
1424
  assertActive();
1413
1425
  const dispatchStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1414
1426
  validatePrinterState(dispatchStatus, requirements);
1415
1427
  this.bambu.assertPrintPreflight(dispatchStatus, preflight);
1416
1428
  },
1417
- assertDispatchAllowed: method => { if (method === bridgeMethod)
1429
+ assertDispatchAllowed: method => { if (method === bridgeMethod || method === cloudFallbackMethod)
1418
1430
  assertActive(); },
1419
- onDispatched: method => { if (method === bridgeMethod)
1431
+ onDispatched: method => { if (method === bridgeMethod || method === cloudFallbackMethod)
1420
1432
  retainForDispatchedUpload(); },
1421
1433
  };
1422
1434
  let jobUpdates = [];
1423
1435
  let bridgeResult;
1424
- if (isLocalBridgePrint) {
1436
+ let firstFailure;
1437
+ if (!inCloudSession) {
1425
1438
  ({ result: bridgeResult, jobUpdates } = await this.bambuNetwork.startLocalPrint({ devId, devIp, username: String(params.username), password, useSsl: params.use_ssl_for_mqtt }, bridgeMethod, { client_job_id: clientJobId, params }, bridgeOptions, assertActive));
1426
1439
  }
1427
1440
  else {
1428
- ({ result: bridgeResult, jobUpdates } = await this.bambuNetwork.startCloudPrint(devId, bridgeMethod, { client_job_id: clientJobId, params }, bridgeOptions, assertActive));
1441
+ ({ result: bridgeResult, jobUpdates, firstFailure } = await this.bambuNetwork.startCloudPrint(devId, bridgeMethod, { client_job_id: clientJobId, params }, bridgeOptions, assertActive, undefined, cloudFallbackMethod));
1442
+ if (firstFailure !== undefined)
1443
+ bridgeMethod = cloudFallbackMethod;
1429
1444
  }
1445
+ const firstAttempt = firstFailure !== undefined
1446
+ ? ` It first tried net.start_local_print_with_record, as Bambu Studio does, which returned ${firstFailure}${describeBambuNetworkPrintError(firstFailure)}.` : "";
1430
1447
  if (typeof bridgeResult === "object" && bridgeResult !== null && bridgeResult.ok === false) {
1431
1448
  throw new Error(`FULU BambuNetwork bridge method ${bridgeMethod} failed: ${String(bridgeResult.error || "unknown bridge error")}`);
1432
1449
  }
@@ -1438,13 +1455,13 @@ class BambuPrinterMCPServer {
1438
1455
  const reported = jobUpdates.filter(update => update.code !== 0 || update.msg).slice(-3)
1439
1456
  .map(update => `status ${update.status}, code ${update.code}${update.msg ? `: ${update.msg}` : ""}`).join("; ");
1440
1457
  throw new Error(`FULU BambuNetwork bridge method ${bridgeMethod} returned non-zero result ${value}${describeBambuNetworkPrintError(value)}.` +
1441
- (reported ? ` Plug-in reported: ${reported}.` : ""));
1458
+ (reported ? ` Plug-in reported: ${reported}.` : "") + firstAttempt);
1442
1459
  }
1443
1460
  assertActive();
1444
1461
  this.bambu.recordCheckedJob(devIp, devId, remoteFileName, requirements, resumeFile, false);
1445
1462
  return {
1446
1463
  status: "success",
1447
- message: `FULU BambuNetwork ${bridgePrintMethod} command for ${threeMfFilename} sent successfully.`,
1464
+ message: `FULU BambuNetwork ${bridgeMethod.replace(/^net\./, "")} command for ${threeMfFilename} sent successfully.${firstAttempt}`,
1448
1465
  bridgeMethod,
1449
1466
  bridgeResult,
1450
1467
  clientJobId,
@@ -2119,6 +2136,7 @@ class BambuPrinterMCPServer {
2119
2136
  skip_modified_gcodes: { type: "boolean", description: "Strip custom start/end gcodes embedded in the 3MF. Recommended for downloaded 3MFs since custom gcodes from other users' profiles may be unsafe for your printer." },
2120
2137
  pause_at_layers: { type: "array", items: { type: "integer", minimum: 2 }, description: "Pause before each of these layers (1-based, as Bambu Studio and OrcaSlicer number them in the preview), for example to drop in magnets or nuts. The slicer writes the printer's own pause G-code there (M400 U1 on Bambu printers); the printer stops by itself and waits for Resume. Bambu Studio or OrcaSlicer CLI only. Pauses already in a project 3MF are kept." },
2121
2138
  slice_plate: { type: "number", description: "Which plate index to slice. 0 = all plates for local slicers; remote slicing defaults to plate 1 and rejects 0. Use 1, 2, etc. to slice only a specific plate in multi-plate 3MF projects." },
2139
+ ...PRINT_QUALITY_PROPERTIES,
2122
2140
  layer_height: { type: "number", exclusiveMinimum: 0, description: "Layer height in mm, such as 0.28 (draft), 0.2 (standard) or 0.12 (fine). Written as the process preset's layer_height over the machine and process preset this tool resolves; at most the nozzle diameter. Bambu-compatible slicers only." },
2123
2141
  wall_loops: { type: "integer", minimum: 0, maximum: 1000, description: "Number of walls (perimeters), written as the process preset's wall_loops. Bambu-compatible slicers only." },
2124
2142
  sparse_infill_density: { type: "string", pattern: "^\\s*\\d+(\\.\\d+)?\\s*%\\s*$", description: "Sparse infill density as a percentage, such as \"15%\", written as the process preset's sparse_infill_density. Bambu-compatible slicers only." },
@@ -2200,7 +2218,7 @@ class BambuPrinterMCPServer {
2200
2218
  description: "REQUIRED: Bambu Lab printer model. Ask the user if not known. Using the wrong model can damage the printer."
2201
2219
  },
2202
2220
  connection_type: { type: "string", enum: ["cloud", "lan"], description: "BambuNetwork connection type to put in FULU PrintParams; cloud uses restored internet printing, lan uses local bridge printing." },
2203
- bambu_network_method: { type: "string", enum: BAMBU_NETWORK_PRINT_METHODS, description: "FULU print method to invoke; defaults to start_print for cloud and start_local_print for lan." },
2221
+ bambu_network_method: { type: "string", enum: BAMBU_NETWORK_PRINT_METHODS, description: "FULU print method to invoke; defaults to start_local_print for lan, and for cloud to Bambu Studio's order: start_local_print_with_record, then start_print if that fails." },
2204
2222
  dev_id: { type: "string", description: "Bambu device id used by BambuNetwork; defaults to BAMBU_DEV_ID or BAMBU_SERIAL." },
2205
2223
  dev_ip: { type: "string", description: "Printer IP address for LAN/local bridge methods; defaults to host when provided." },
2206
2224
  host: { type: "string", description: "Printer host or IP address, used as dev_ip for LAN/local bridge methods." },
@@ -2629,7 +2647,7 @@ class BambuPrinterMCPServer {
2629
2647
  },
2630
2648
  try_emmc_print: { type: "boolean", description: "X2D native printing: true stores the job on internal storage (eMMC), false on the SD card or USB stick (refused unless the printer reports one ready). Omit to use the card when ready, else eMMC; BAMBU_NATIVE_TRY_EMMC_PRINT sets a server default." },
2631
2649
  connection_type: { type: "string", enum: ["cloud", "lan"], description: "BambuNetwork connection type when connection_mode is bambu_network; cloud uses restored internet printing, lan uses local bridge printing." },
2632
- bambu_network_method: { type: "string", enum: BAMBU_NETWORK_PRINT_METHODS, description: "FULU print method when connection_mode is bambu_network; defaults to start_print for cloud and start_local_print for lan." },
2650
+ bambu_network_method: { type: "string", enum: BAMBU_NETWORK_PRINT_METHODS, description: "FULU print method when connection_mode is bambu_network; defaults to start_local_print for lan, and for cloud to Bambu Studio's order: start_local_print_with_record, then start_print if that fails." },
2633
2651
  dev_id: { type: "string", description: "Bambu device id for FULU BambuNetwork printing; defaults to BAMBU_DEV_ID or BAMBU_SERIAL." },
2634
2652
  dev_ip: { type: "string", description: "Printer IP address for FULU BambuNetwork LAN/local print methods; defaults to host when provided." },
2635
2653
  bridge_command: { type: "string", description: "Override command for the FULU bridge host or macOS/WSL wrapper; defaults to BAMBU_NETWORK_BRIDGE_COMMAND. Per-call overrides require MCP_ALLOW_EXECUTABLE_ARG=1." },
@@ -3703,7 +3721,7 @@ class BambuPrinterMCPServer {
3703
3721
  if (pauses)
3704
3722
  sliceBambuOptions.pauseAtLayers = pauses;
3705
3723
  }
3706
- const processOverrides = parseProcessOverrides(args, Number(nozzleDiam));
3724
+ const processOverrides = parseProcessOverrides(withPrintQuality(args, Number(nozzleDiam)), Number(nozzleDiam));
3707
3725
  if (processOverrides)
3708
3726
  sliceBambuOptions.processOverrides = processOverrides;
3709
3727
  if (sliceBambuOptions.loadFilamentIds && String(args.stl_path).toLowerCase().endsWith(".3mf")) {
@@ -0,0 +1,26 @@
1
+ /**
2
+ * slice_stl's `quality` and `strength` (PRD §8.4): a client's print-sheet choice, mapped here to the
3
+ * slicer's own numbers so no client carries layer heights, wall counts or infill. Draft and Fine set
4
+ * the layer height for the nozzle in use (0.28 and 0.12 mm on a 0.4 mm nozzle, scaled with it); Strong
5
+ * and Max set walls and infill. Standard sends nothing: the resolved preset decides. An explicit
6
+ * layer_height, wall_loops or sparse_infill_density in the same call wins over these.
7
+ */
8
+ export declare const PRINT_QUALITIES: readonly ["draft", "standard", "fine"];
9
+ export declare const PRINT_STRENGTHS: readonly ["standard", "strong", "max"];
10
+ export type PrintQuality = (typeof PRINT_QUALITIES)[number];
11
+ export type PrintStrength = (typeof PRINT_STRENGTHS)[number];
12
+ /** The call's arguments with `quality` and `strength` written out as slicer settings. */
13
+ export declare function withPrintQuality(args: Record<string, unknown>, nozzleDiameter?: number): Record<string, unknown>;
14
+ /** slice_stl input-schema properties for both arguments. */
15
+ export declare const PRINT_QUALITY_PROPERTIES: {
16
+ readonly quality: {
17
+ readonly type: "string";
18
+ readonly enum: readonly ["draft", "standard", "fine"];
19
+ readonly description: "Print quality: draft (thicker layers, faster), standard (the preset's own layer height) or fine (thinner layers). The server picks the layer height for the nozzle in use; an explicit layer_height wins.";
20
+ };
21
+ readonly strength: {
22
+ readonly type: "string";
23
+ readonly enum: readonly ["standard", "strong", "max"];
24
+ readonly description: "Part strength: standard (the preset's walls and infill), strong or max (more walls and denser infill). The server picks the values; explicit wall_loops or sparse_infill_density win.";
25
+ };
26
+ };
@@ -0,0 +1,53 @@
1
+ /**
2
+ * slice_stl's `quality` and `strength` (PRD §8.4): a client's print-sheet choice, mapped here to the
3
+ * slicer's own numbers so no client carries layer heights, wall counts or infill. Draft and Fine set
4
+ * the layer height for the nozzle in use (0.28 and 0.12 mm on a 0.4 mm nozzle, scaled with it); Strong
5
+ * and Max set walls and infill. Standard sends nothing: the resolved preset decides. An explicit
6
+ * layer_height, wall_loops or sparse_infill_density in the same call wins over these.
7
+ */
8
+ export const PRINT_QUALITIES = ["draft", "standard", "fine"];
9
+ export const PRINT_STRENGTHS = ["standard", "strong", "max"];
10
+ /** Layer heights on the reference 0.4 mm nozzle; other nozzles scale from it. */
11
+ const REFERENCE_NOZZLE_MM = 0.4;
12
+ const LAYER_MM_ON_REFERENCE = { draft: 0.28, fine: 0.12 };
13
+ const STRENGTH = {
14
+ strong: { wall_loops: 4, sparse_infill_density: "25%" },
15
+ max: { wall_loops: 6, sparse_infill_density: "40%" },
16
+ };
17
+ /** The call's arguments with `quality` and `strength` written out as slicer settings. */
18
+ export function withPrintQuality(args, nozzleDiameter) {
19
+ if (args.quality === undefined && args.strength === undefined)
20
+ return args;
21
+ const quality = args.quality === undefined ? "standard" : args.quality;
22
+ const strength = args.strength === undefined ? "standard" : args.strength;
23
+ if (typeof quality !== "string" || !PRINT_QUALITIES.includes(quality)) {
24
+ throw new Error(`quality must be one of ${PRINT_QUALITIES.join(", ")}.`);
25
+ }
26
+ if (typeof strength !== "string" || !PRINT_STRENGTHS.includes(strength)) {
27
+ throw new Error(`strength must be one of ${PRINT_STRENGTHS.join(", ")}.`);
28
+ }
29
+ const out = { ...args };
30
+ const scale = typeof nozzleDiameter === "number" && Number.isFinite(nozzleDiameter) && nozzleDiameter > 0 ? nozzleDiameter / REFERENCE_NOZZLE_MM : 1;
31
+ const layer = LAYER_MM_ON_REFERENCE[quality];
32
+ if (layer !== undefined && out.layer_height === undefined)
33
+ out.layer_height = Math.round(layer * scale * 100) / 100;
34
+ const walls = STRENGTH[strength];
35
+ if (walls) {
36
+ if (out.wall_loops === undefined)
37
+ out.wall_loops = walls.wall_loops;
38
+ if (out.sparse_infill_density === undefined)
39
+ out.sparse_infill_density = walls.sparse_infill_density;
40
+ }
41
+ return out;
42
+ }
43
+ /** slice_stl input-schema properties for both arguments. */
44
+ export const PRINT_QUALITY_PROPERTIES = {
45
+ quality: {
46
+ type: "string", enum: [...PRINT_QUALITIES],
47
+ description: "Print quality: draft (thicker layers, faster), standard (the preset's own layer height) or fine (thinner layers). The server picks the layer height for the nozzle in use; an explicit layer_height wins.",
48
+ },
49
+ strength: {
50
+ type: "string", enum: [...PRINT_STRENGTHS],
51
+ description: "Part strength: standard (the preset's walls and infill), strong or max (more walls and denser infill). The server picks the values; explicit wall_loops or sparse_infill_density win.",
52
+ },
53
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.54",
3
+ "version": "1.1.56",
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": {
@@ -17,8 +17,16 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 120_000;
17
17
  const LOCAL_CONNECT_STATUS = ["ok", "failed", "lost"];
18
18
  // bambu_networking.hpp BAMBU_NETWORK_ERR_PRINT_LP_PUBLISH_MSG_FAILED.
19
19
  const LOCAL_PRINT_PUBLISH_FAILED = -4030;
20
+ // A with-record send falls back to start_print only on its own preparation failures (the plug-in's
21
+ // PRINT_WR_* results, -2010 to -2140: project, upload, task record, FTPS), which come before the print
22
+ // command, so the printer has no job. Any other result may have reached the printer and is never
23
+ // replayed. Of those, Studio also stops on a file missing or too large (should_stop_without_fallback).
24
+ const WITH_RECORD_PREPARATION_FAILURE = (value: number) => value <= -2010 && value >= -2140 && value !== -2040 && value !== -2100;
20
25
  // bambu_networking.hpp print errors that name a recoverable cause.
21
26
  const BAMBU_NETWORK_PRINT_ERRORS: Record<number, string> = {
27
+ [-2120]: "Bambu Cloud refused to create the print task",
28
+ [-2130]: "FTPS upload to the printer failed",
29
+ [-3120]: "Bambu Cloud refused to create the print task",
22
30
  [-4010]: "the file exceeds the 1 GB upload limit",
23
31
  [-4020]: "FTPS upload to the printer failed",
24
32
  [LOCAL_PRINT_PUBLISH_FAILED]: "the networking plug-in could not send the print command to the printer over MQTT",
@@ -852,10 +860,24 @@ export class BambuNetworkBridge {
852
860
  }
853
861
  }
854
862
 
855
- /** A cloud print method (start_print) in a cloud session, so the plug-in has the printer's state. */
863
+ /**
864
+ * A cloud print in a cloud session, so the plug-in has the printer's state. With a fallback this is
865
+ * Bambu Studio's order for a cloud-bound printer it can also reach on the LAN (PrintJob.cpp,
866
+ * SendAttemptRoute::LanWithRecord, then ::Cloud): start_local_print_with_record, then start_print
867
+ * when the first failed before its print command was sent. `firstFailure` is the first method's result.
868
+ */
856
869
  async startCloudPrint(devId: string, method: string, payload: JsonObject, options: BambuNetworkBridgeOptions = {},
857
- assertActive: () => void = () => {}, timing: Readonly<CloudTiming> = CLOUD_PRINT_TIMING): Promise<{ result: unknown; jobUpdates: BridgeJobUpdate[] }> {
858
- return await this.withCloudSession(devId, options, assertActive, timing, async session => ({ result: await this.callWithAgent(method, payload, options), jobUpdates: session.jobUpdates }));
870
+ assertActive: () => void = () => {}, timing: Readonly<CloudTiming> = CLOUD_PRINT_TIMING, fallbackMethod?: string
871
+ ): Promise<{ result: unknown; jobUpdates: BridgeJobUpdate[]; firstFailure?: number }> {
872
+ return await this.withCloudSession(devId, options, assertActive, timing, async session => {
873
+ const result = await this.callWithAgent(method, payload, options);
874
+ const value = bridgeNumericResult(result);
875
+ if (!fallbackMethod || value === undefined || !WITH_RECORD_PREPARATION_FAILURE(value)) return { result, jobUpdates: session.jobUpdates };
876
+ options.trace?.({ step: "fallback", from: method, to: fallbackMethod, result: value });
877
+ const params = (payload as { params?: JsonObject }).params;
878
+ const fallbackPayload = params ? { ...payload, params: { ...params, comments: `failed(${value})` } } : payload;
879
+ return { result: await this.callWithAgent(fallbackMethod, fallbackPayload, options), jobUpdates: session.jobUpdates, firstFailure: value };
880
+ });
859
881
  }
860
882
 
861
883
  /**
package/src/index.ts CHANGED
@@ -63,6 +63,7 @@ import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
63
63
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
64
64
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
65
65
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
66
+ import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
66
67
  import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
67
68
 
68
69
  dotenv.config();
@@ -1645,12 +1646,18 @@ class BambuPrinterMCPServer {
1645
1646
 
1646
1647
  const connectionType = resolveConnection(args).type;
1647
1648
 
1648
- const bridgePrintMethod = resolveBambuNetworkPrintMethod(
1649
+ // With no method given, a cloud print follows Bambu Studio's order for a cloud-bound printer it can
1650
+ // reach on the LAN (PrintJob.cpp): start_local_print_with_record in the cloud session, then start_print.
1651
+ // This server always has the printer's IP and access code, which Studio needs for the first.
1652
+ const studioCloudRoute = connectionType === "cloud" && args?.bambu_network_method === undefined;
1653
+ const bridgePrintMethod = studioCloudRoute ? "start_local_print_with_record" : resolveBambuNetworkPrintMethod(
1649
1654
  args?.bambu_network_method !== undefined ? String(args.bambu_network_method) : undefined,
1650
1655
  connectionType
1651
1656
  );
1652
- const bridgeMethod = toBridgeMethod(bridgePrintMethod);
1657
+ let bridgeMethod = toBridgeMethod(bridgePrintMethod);
1653
1658
  const isLocalBridgePrint = bridgePrintMethod !== "start_print";
1659
+ const inCloudSession = studioCloudRoute || !isLocalBridgePrint;
1660
+ let cloudFallbackMethod = studioCloudRoute ? toBridgeMethod("start_print") : undefined;
1654
1661
 
1655
1662
  const devId = String(args?.dev_id || bambuSerial || DEFAULT_BAMBU_DEV_ID).trim();
1656
1663
  if (!devId) {
@@ -1730,6 +1737,11 @@ class BambuPrinterMCPServer {
1730
1737
  const amsMapping = stringifyBridgeJson(mapping?.map(value => bridgeAmsMappingValue(value, isDualNozzleModel(printModel))));
1731
1738
  const remoteFileName = uniquePrintName(threeMFPath);
1732
1739
  const checkedName = remoteFileName.replace(/(?:\.gcode)?\.3mf$/i, "");
1740
+ if (cloudFallbackMethod && externalStorageState(confirmedStatus.raw) !== "normal") {
1741
+ // Studio sends straight through the cloud when the printer has no storage for the LAN upload.
1742
+ bridgeMethod = cloudFallbackMethod;
1743
+ cloudFallbackMethod = undefined;
1744
+ }
1733
1745
  const params: Record<string, unknown> = {
1734
1746
  dev_id: devId,
1735
1747
  // Firmware can report the task name instead of the uploaded filename.
@@ -1825,18 +1837,19 @@ class BambuPrinterMCPServer {
1825
1837
  const bridgeOptions: BambuNetworkBridgeOptions = {
1826
1838
  ...this.bridgeOptionsFromArgs(args, "print_3mf_bambu_network"),
1827
1839
  beforeDispatch: async method => {
1828
- if (method !== bridgeMethod) return;
1840
+ if (method !== bridgeMethod && method !== cloudFallbackMethod) return;
1829
1841
  assertActive();
1830
1842
  const dispatchStatus = await this.bambu.getSafetyStatus(devIp, devId, password || bambuToken);
1831
1843
  validatePrinterState(dispatchStatus, requirements);
1832
1844
  this.bambu.assertPrintPreflight(dispatchStatus, preflight);
1833
1845
  },
1834
- assertDispatchAllowed: method => { if (method === bridgeMethod) assertActive(); },
1835
- onDispatched: method => { if (method === bridgeMethod) retainForDispatchedUpload(); },
1846
+ assertDispatchAllowed: method => { if (method === bridgeMethod || method === cloudFallbackMethod) assertActive(); },
1847
+ onDispatched: method => { if (method === bridgeMethod || method === cloudFallbackMethod) retainForDispatchedUpload(); },
1836
1848
  };
1837
1849
  let jobUpdates: BridgeJobUpdate[] = [];
1838
1850
  let bridgeResult: unknown;
1839
- if (isLocalBridgePrint) {
1851
+ let firstFailure: number | undefined;
1852
+ if (!inCloudSession) {
1840
1853
  ({ result: bridgeResult, jobUpdates } = await this.bambuNetwork.startLocalPrint(
1841
1854
  { devId, devIp, username: String(params.username), password, useSsl: params.use_ssl_for_mqtt as boolean },
1842
1855
  bridgeMethod,
@@ -1845,8 +1858,11 @@ class BambuPrinterMCPServer {
1845
1858
  assertActive
1846
1859
  ));
1847
1860
  } else {
1848
- ({ result: bridgeResult, jobUpdates } = await this.bambuNetwork.startCloudPrint(devId, bridgeMethod, { client_job_id: clientJobId, params }, bridgeOptions, assertActive));
1861
+ ({ result: bridgeResult, jobUpdates, firstFailure } = await this.bambuNetwork.startCloudPrint(devId, bridgeMethod, { client_job_id: clientJobId, params }, bridgeOptions, assertActive, undefined, cloudFallbackMethod));
1862
+ if (firstFailure !== undefined) bridgeMethod = cloudFallbackMethod!;
1849
1863
  }
1864
+ const firstAttempt = firstFailure !== undefined
1865
+ ? ` It first tried net.start_local_print_with_record, as Bambu Studio does, which returned ${firstFailure}${describeBambuNetworkPrintError(firstFailure)}.` : "";
1850
1866
 
1851
1867
  if (typeof bridgeResult === "object" && bridgeResult !== null && (bridgeResult as { ok?: unknown }).ok === false) {
1852
1868
  throw new Error(`FULU BambuNetwork bridge method ${bridgeMethod} failed: ${String((bridgeResult as { error?: unknown }).error || "unknown bridge error")}`);
@@ -1861,7 +1877,7 @@ class BambuPrinterMCPServer {
1861
1877
  const reported = jobUpdates.filter(update => update.code !== 0 || update.msg).slice(-3)
1862
1878
  .map(update => `status ${update.status}, code ${update.code}${update.msg ? `: ${update.msg}` : ""}`).join("; ");
1863
1879
  throw new Error(`FULU BambuNetwork bridge method ${bridgeMethod} returned non-zero result ${value}${describeBambuNetworkPrintError(value)}.` +
1864
- (reported ? ` Plug-in reported: ${reported}.` : ""));
1880
+ (reported ? ` Plug-in reported: ${reported}.` : "") + firstAttempt);
1865
1881
  }
1866
1882
 
1867
1883
  assertActive();
@@ -1869,7 +1885,7 @@ class BambuPrinterMCPServer {
1869
1885
 
1870
1886
  return {
1871
1887
  status: "success",
1872
- message: `FULU BambuNetwork ${bridgePrintMethod} command for ${threeMfFilename} sent successfully.`,
1888
+ message: `FULU BambuNetwork ${bridgeMethod.replace(/^net\./, "")} command for ${threeMfFilename} sent successfully.${firstAttempt}`,
1873
1889
  bridgeMethod,
1874
1890
  bridgeResult,
1875
1891
  clientJobId,
@@ -2652,6 +2668,7 @@ class BambuPrinterMCPServer {
2652
2668
  skip_modified_gcodes: { type: "boolean", description: "Strip custom start/end gcodes embedded in the 3MF. Recommended for downloaded 3MFs since custom gcodes from other users' profiles may be unsafe for your printer." },
2653
2669
  pause_at_layers: { type: "array", items: { type: "integer", minimum: 2 }, description: "Pause before each of these layers (1-based, as Bambu Studio and OrcaSlicer number them in the preview), for example to drop in magnets or nuts. The slicer writes the printer's own pause G-code there (M400 U1 on Bambu printers); the printer stops by itself and waits for Resume. Bambu Studio or OrcaSlicer CLI only. Pauses already in a project 3MF are kept." },
2654
2670
  slice_plate: { type: "number", description: "Which plate index to slice. 0 = all plates for local slicers; remote slicing defaults to plate 1 and rejects 0. Use 1, 2, etc. to slice only a specific plate in multi-plate 3MF projects." },
2671
+ ...PRINT_QUALITY_PROPERTIES,
2655
2672
  layer_height: { type: "number", exclusiveMinimum: 0, description: "Layer height in mm, such as 0.28 (draft), 0.2 (standard) or 0.12 (fine). Written as the process preset's layer_height over the machine and process preset this tool resolves; at most the nozzle diameter. Bambu-compatible slicers only." },
2656
2673
  wall_loops: { type: "integer", minimum: 0, maximum: 1000, description: "Number of walls (perimeters), written as the process preset's wall_loops. Bambu-compatible slicers only." },
2657
2674
  sparse_infill_density: { type: "string", pattern: "^\\s*\\d+(\\.\\d+)?\\s*%\\s*$", description: "Sparse infill density as a percentage, such as \"15%\", written as the process preset's sparse_infill_density. Bambu-compatible slicers only." },
@@ -2733,7 +2750,7 @@ class BambuPrinterMCPServer {
2733
2750
  description: "REQUIRED: Bambu Lab printer model. Ask the user if not known. Using the wrong model can damage the printer."
2734
2751
  },
2735
2752
  connection_type: { type: "string", enum: ["cloud", "lan"], description: "BambuNetwork connection type to put in FULU PrintParams; cloud uses restored internet printing, lan uses local bridge printing." },
2736
- bambu_network_method: { type: "string", enum: BAMBU_NETWORK_PRINT_METHODS, description: "FULU print method to invoke; defaults to start_print for cloud and start_local_print for lan." },
2753
+ bambu_network_method: { type: "string", enum: BAMBU_NETWORK_PRINT_METHODS, description: "FULU print method to invoke; defaults to start_local_print for lan, and for cloud to Bambu Studio's order: start_local_print_with_record, then start_print if that fails." },
2737
2754
  dev_id: { type: "string", description: "Bambu device id used by BambuNetwork; defaults to BAMBU_DEV_ID or BAMBU_SERIAL." },
2738
2755
  dev_ip: { type: "string", description: "Printer IP address for LAN/local bridge methods; defaults to host when provided." },
2739
2756
  host: { type: "string", description: "Printer host or IP address, used as dev_ip for LAN/local bridge methods." },
@@ -3162,7 +3179,7 @@ class BambuPrinterMCPServer {
3162
3179
  },
3163
3180
  try_emmc_print: { type: "boolean", description: "X2D native printing: true stores the job on internal storage (eMMC), false on the SD card or USB stick (refused unless the printer reports one ready). Omit to use the card when ready, else eMMC; BAMBU_NATIVE_TRY_EMMC_PRINT sets a server default." },
3164
3181
  connection_type: { type: "string", enum: ["cloud", "lan"], description: "BambuNetwork connection type when connection_mode is bambu_network; cloud uses restored internet printing, lan uses local bridge printing." },
3165
- bambu_network_method: { type: "string", enum: BAMBU_NETWORK_PRINT_METHODS, description: "FULU print method when connection_mode is bambu_network; defaults to start_print for cloud and start_local_print for lan." },
3182
+ bambu_network_method: { type: "string", enum: BAMBU_NETWORK_PRINT_METHODS, description: "FULU print method when connection_mode is bambu_network; defaults to start_local_print for lan, and for cloud to Bambu Studio's order: start_local_print_with_record, then start_print if that fails." },
3166
3183
  dev_id: { type: "string", description: "Bambu device id for FULU BambuNetwork printing; defaults to BAMBU_DEV_ID or BAMBU_SERIAL." },
3167
3184
  dev_ip: { type: "string", description: "Printer IP address for FULU BambuNetwork LAN/local print methods; defaults to host when provided." },
3168
3185
  bridge_command: { type: "string", description: "Override command for the FULU bridge host or macOS/WSL wrapper; defaults to BAMBU_NETWORK_BRIDGE_COMMAND. Per-call overrides require MCP_ALLOW_EXECUTABLE_ARG=1." },
@@ -4344,7 +4361,7 @@ class BambuPrinterMCPServer {
4344
4361
  if (args?.skip_modified_gcodes !== undefined) sliceBambuOptions.skipModifiedGcodes = Boolean(args.skip_modified_gcodes);
4345
4362
  if (args?.slice_plate !== undefined) sliceBambuOptions.slicePlate = Number(args.slice_plate);
4346
4363
  { const pauses = parsePauseLayers(args?.pause_at_layers); if (pauses) sliceBambuOptions.pauseAtLayers = pauses; }
4347
- const processOverrides = parseProcessOverrides(args as Record<string, unknown>, Number(nozzleDiam));
4364
+ const processOverrides = parseProcessOverrides(withPrintQuality(args as Record<string, unknown>, Number(nozzleDiam)), Number(nozzleDiam));
4348
4365
  if (processOverrides) sliceBambuOptions.processOverrides = processOverrides;
4349
4366
  if (sliceBambuOptions.loadFilamentIds && String(args.stl_path).toLowerCase().endsWith(".3mf")) {
4350
4367
  // Bambu Studio's CLI refuses --load-filament-ids for 3MF input and counts it per input file.
@@ -0,0 +1,55 @@
1
+ /**
2
+ * slice_stl's `quality` and `strength` (PRD §8.4): a client's print-sheet choice, mapped here to the
3
+ * slicer's own numbers so no client carries layer heights, wall counts or infill. Draft and Fine set
4
+ * the layer height for the nozzle in use (0.28 and 0.12 mm on a 0.4 mm nozzle, scaled with it); Strong
5
+ * and Max set walls and infill. Standard sends nothing: the resolved preset decides. An explicit
6
+ * layer_height, wall_loops or sparse_infill_density in the same call wins over these.
7
+ */
8
+ export const PRINT_QUALITIES = ["draft", "standard", "fine"] as const;
9
+ export const PRINT_STRENGTHS = ["standard", "strong", "max"] as const;
10
+
11
+ export type PrintQuality = (typeof PRINT_QUALITIES)[number];
12
+ export type PrintStrength = (typeof PRINT_STRENGTHS)[number];
13
+
14
+ /** Layer heights on the reference 0.4 mm nozzle; other nozzles scale from it. */
15
+ const REFERENCE_NOZZLE_MM = 0.4;
16
+ const LAYER_MM_ON_REFERENCE: Partial<Record<PrintQuality, number>> = { draft: 0.28, fine: 0.12 };
17
+ const STRENGTH: Partial<Record<PrintStrength, { wall_loops: number; sparse_infill_density: string }>> = {
18
+ strong: { wall_loops: 4, sparse_infill_density: "25%" },
19
+ max: { wall_loops: 6, sparse_infill_density: "40%" },
20
+ };
21
+
22
+ /** The call's arguments with `quality` and `strength` written out as slicer settings. */
23
+ export function withPrintQuality(args: Record<string, unknown>, nozzleDiameter?: number): Record<string, unknown> {
24
+ if (args.quality === undefined && args.strength === undefined) return args;
25
+ const quality = args.quality === undefined ? "standard" : args.quality;
26
+ const strength = args.strength === undefined ? "standard" : args.strength;
27
+ if (typeof quality !== "string" || !(PRINT_QUALITIES as readonly string[]).includes(quality)) {
28
+ throw new Error(`quality must be one of ${PRINT_QUALITIES.join(", ")}.`);
29
+ }
30
+ if (typeof strength !== "string" || !(PRINT_STRENGTHS as readonly string[]).includes(strength)) {
31
+ throw new Error(`strength must be one of ${PRINT_STRENGTHS.join(", ")}.`);
32
+ }
33
+ const out: Record<string, unknown> = { ...args };
34
+ const scale = typeof nozzleDiameter === "number" && Number.isFinite(nozzleDiameter) && nozzleDiameter > 0 ? nozzleDiameter / REFERENCE_NOZZLE_MM : 1;
35
+ const layer = LAYER_MM_ON_REFERENCE[quality as PrintQuality];
36
+ if (layer !== undefined && out.layer_height === undefined) out.layer_height = Math.round(layer * scale * 100) / 100;
37
+ const walls = STRENGTH[strength as PrintStrength];
38
+ if (walls) {
39
+ if (out.wall_loops === undefined) out.wall_loops = walls.wall_loops;
40
+ if (out.sparse_infill_density === undefined) out.sparse_infill_density = walls.sparse_infill_density;
41
+ }
42
+ return out;
43
+ }
44
+
45
+ /** slice_stl input-schema properties for both arguments. */
46
+ export const PRINT_QUALITY_PROPERTIES = {
47
+ quality: {
48
+ type: "string", enum: [...PRINT_QUALITIES],
49
+ description: "Print quality: draft (thicker layers, faster), standard (the preset's own layer height) or fine (thinner layers). The server picks the layer height for the nozzle in use; an explicit layer_height wins.",
50
+ },
51
+ strength: {
52
+ type: "string", enum: [...PRINT_STRENGTHS],
53
+ description: "Part strength: standard (the preset's walls and infill), strong or max (more walls and denser infill). The server picks the values; explicit wall_loops or sparse_infill_density win.",
54
+ },
55
+ } as const;