bambu-printer-mcp 1.1.67 → 1.1.69

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/src/index.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  import {CAMERA_STREAM_TOOLS} from "./printers/camera-tools.js";
3
3
  import { withAnnotations } from "./tool-annotations.js";
4
4
  import { withRemote } from "./counterpart/remote.js";
5
- import { slicedFileFacts, slicerReport } from "./counterpart/sliced-file.js";
5
+ import { refusalReport, slicedFileFacts, slicerReport } from "./counterpart/sliced-file.js";
6
+ import { listModelPlates } from "./counterpart/model-plates.js";
6
7
 
7
8
  /** The slicer's verdict beside its result.json (`slicer_report`). */
8
9
  function reportOf(result: unknown): { slicer_report?: ReturnType<typeof slicerReport> } {
@@ -41,7 +42,7 @@ import {
41
42
  type BambuSliceOptions,
42
43
  type SlicerType,
43
44
  } from "./stl/stl-manipulator.js";
44
- import { BambuNetworkBridge, describeBambuNetworkPrintError, type BambuNetworkBridgeOptions, type BridgeJobUpdate } from "./bambu-network-bridge.js";
45
+ import { BambuNetworkBridge, bridgeSnapshotRoot, describeBambuNetworkPrintError, type BambuNetworkBridgeOptions, type BridgeJobUpdate } from "./bambu-network-bridge.js";
45
46
  import {
46
47
  assertBambuNativeAvailable,
47
48
  bambuNativeControlsAvailable,
@@ -75,7 +76,7 @@ import { bambuPrinterInfo, bambuSliceCapabilities } from "./counterpart/info.js"
75
76
  import { DISCOVER_OUTPUT_SCHEMA, discoverBambu } from "./counterpart/discovery.js";
76
77
  import { SETUP_FIELDS_OUTPUT_SCHEMA, bambuSetupFields, slicerSetup, type SlicerSetup } from "./counterpart/setup.js";
77
78
  import { PROPOSE_FILAMENTS_INPUT_PROPERTIES, PROPOSE_FILAMENTS_OUTPUT_SCHEMA, NO_COLOUR_NAMES, bambuTrayLabel, loadColourNames, proposeFilaments, spoolName, type ColourNames, type ProposalTray } from "./counterpart/filaments.js";
78
- import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, SERVER_INSTRUCTIONS } from "./design-guidance.js";
79
+ import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, FDM_SLICING_PROMPT, SERVER_INSTRUCTIONS, slicingGuidance } from "./design-guidance.js";
79
80
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
80
81
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
81
82
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
@@ -2023,7 +2024,7 @@ class BambuPrinterMCPServer {
2023
2024
  amsMapping: mapping,
2024
2025
  params: redactPrintParams(params),
2025
2026
  };
2026
- }));
2027
+ }, bridgeSnapshotRoot()));
2027
2028
  }
2028
2029
 
2029
2030
  private async handoff3mfViaBambuConnect(
@@ -2387,9 +2388,17 @@ class BambuPrinterMCPServer {
2387
2388
  /** The FDM design guidance as MCP prompts: the client decides when to attach each one. */
2388
2389
  setupPromptHandlers() {
2389
2390
  this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
2390
- prompts: DESIGN_PROMPTS.map(({ name, title, description }) => ({ name, title, description })),
2391
+ prompts: [...DESIGN_PROMPTS, FDM_SLICING_PROMPT].map(({ name, title, description }) => ({ name, title, description })),
2391
2392
  }));
2392
2393
  this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
2394
+ if (request.params.name === FDM_SLICING_PROMPT.name) {
2395
+ // The slicer slice_stl uses by default, and what it applies there (as counterpart_printer_info reports it).
2396
+ const slicerType = normalizeSlicerType(DEFAULT_SLICER_TYPE);
2397
+ return {
2398
+ description: FDM_SLICING_PROMPT.description,
2399
+ messages: [{ role: "user" as const, content: { type: "text" as const, text: slicingGuidance(slicerType, bambuSliceCapabilities(slicerType)) } }],
2400
+ };
2401
+ }
2393
2402
  const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name);
2394
2403
  if (!prompt) throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${request.params.name}`);
2395
2404
  return {
@@ -2568,6 +2577,18 @@ class BambuPrinterMCPServer {
2568
2577
  required: ["three_mf_path"]
2569
2578
  }
2570
2579
  },
2580
+ {
2581
+ name: "list_3mf_plates",
2582
+ description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it and whether the file already holds its G-code (sliced). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2583
+ inputSchema: {
2584
+ type: "object",
2585
+ properties: {
2586
+ three_mf_path: { type: "string", description: "Path to the 3MF (a designer's project, sliced or not)" },
2587
+ include_thumbnails: { type: "boolean", description: "Include each plate's own preview PNG from the file, base64 (default false)" }
2588
+ },
2589
+ required: ["three_mf_path"]
2590
+ }
2591
+ },
2571
2592
  {
2572
2593
  name: "list_3mf_plate_objects",
2573
2594
  description: "List object IDs from a sliced 3MF plate. Use these IDs with skip_objects during a running print.",
@@ -2758,7 +2779,7 @@ class BambuPrinterMCPServer {
2758
2779
  },
2759
2780
  {
2760
2781
  name: "slice_stl",
2761
- description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. A failed slice's text starts with those words. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2782
+ description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. structuredContent.slicer_report says whether it failed; for a failure, its message is a plain sentence for a person and slicer_message keeps the slicer's words, which a failed slice's text gives after that sentence. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2762
2783
  inputSchema: {
2763
2784
  type: "object",
2764
2785
  properties: {
@@ -3894,6 +3915,12 @@ class BambuPrinterMCPServer {
3894
3915
  break;
3895
3916
  }
3896
3917
 
3918
+ case "list_3mf_plates": {
3919
+ if (typeof args?.three_mf_path !== "string" || !args.three_mf_path) throw new Error("Missing required parameter: three_mf_path");
3920
+ if (args.include_thumbnails !== undefined && typeof args.include_thumbnails !== "boolean") throw new Error("include_thumbnails must be a boolean.");
3921
+ const plates = await listModelPlates(args.three_mf_path, { thumbnails: args.include_thumbnails === true });
3922
+ return { content: [{ type: "text", text: JSON.stringify(plates) }], structuredContent: plates };
3923
+ }
3897
3924
  case "list_3mf_plate_objects": {
3898
3925
  if (!args?.three_mf_path) {
3899
3926
  throw new Error("Missing required parameter: three_mf_path");
@@ -5130,14 +5157,19 @@ class BambuPrinterMCPServer {
5130
5157
  tool: name,
5131
5158
  ...(error instanceof PrinterRefusal ? { code: error.code } : {}),
5132
5159
  // The slicer's own result.json; the message starts with its error_string and warnings.
5133
- ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult, ...reportOf(error.slicerResult) } : {}),
5160
+ // A slicer failure always carries slicer_report: the plain sentence a person sees, the slicer's words for the log.
5161
+ // The report always says failed (a result.json that says success can still leave no output file).
5162
+ ...(error instanceof SlicerRunError ? {
5163
+ ...(error.slicerResult ? { slicer_result: error.slicerResult } : {}),
5164
+ slicer_report: { ...refusalReport(error.words), message: error.plain ?? error.words.slice(0, 2000) },
5165
+ } : {}),
5134
5166
  };
5135
5167
 
5136
5168
  // MCP clients validate structuredContent against a declared outputSchema even on
5137
5169
  // errors (SDK 1.32 Client.callTool), so those tools return the error as text only.
5138
5170
  return {
5139
- // A slicer failure leads with the slicer's own words.
5140
- content: [{ type: "text", text: error instanceof SlicerRunError && error.slicerText ? message : `Error: ${message}` }],
5171
+ // A slicer's refusal leads with its plain sentence, then the slicer's own words.
5172
+ content: [{ type: "text", text: error instanceof SlicerRunError && error.plain ? message : `Error: ${message}` }],
5141
5173
  ...(OUTPUT_SCHEMA_TOOLS.has(name) ? {} : { structuredContent: structured }),
5142
5174
  isError: true,
5143
5175
  };
@@ -5161,6 +5193,8 @@ class BambuPrinterMCPServer {
5161
5193
  // Closing the MCP transport aborts its active requests before exit cleanup.
5162
5194
  await this.server.close();
5163
5195
  await this.fusion.close();
5196
+ // The FULU host's container (BAMBU_NETWORK_BRIDGE_IMAGE) is removed with the server, not left running.
5197
+ await this.bambuNetwork.stop();
5164
5198
  this.httpRuntime?.httpServer.close();
5165
5199
  } catch (error) {
5166
5200
  console.error("[MCP Shutdown]", error);
@@ -29,9 +29,12 @@ export async function withPrinterOperation<T>(_host: string, serial: string, ope
29
29
  finally { if (operations.get(key) === next) operations.delete(key); }
30
30
  }
31
31
 
32
- /** Inspect and send a private copy, so changes to the user's source cannot change the job. */
33
- export async function withPrintSnapshot<T>(source: string, operation: (snapshot: string, retainForDispatchedUpload: () => void) => Promise<T>): Promise<T> {
34
- const directory = await fs.mkdtemp(path.join(os.tmpdir(), "bambu-print-"));
32
+ /**
33
+ * Inspect and send a private copy, so changes to the user's source cannot change the job. `root` is where the copy
34
+ * goes (the system temporary folder unless the bridge host needs it in a folder its container mounts).
35
+ */
36
+ export async function withPrintSnapshot<T>(source: string, operation: (snapshot: string, retainForDispatchedUpload: () => void) => Promise<T>, root = os.tmpdir()): Promise<T> {
37
+ const directory = await fs.mkdtemp(path.join(root, "bambu-print-"));
35
38
  const snapshot = path.join(directory, path.basename(source));
36
39
  let retainUntilExit = false;
37
40
  try {
@@ -396,7 +396,12 @@ export async function inspectPrintFile(filePath: string, options: {model:string;
396
396
  !['','XY','UV'].includes(position) || [...position].some(key=>!inRange(args,key,0,limit[key]))) invalid();
397
397
  continue;
398
398
  }
399
- if(!['M117','M118','M1002','M1006','M900','M970','M983.1','G383'].includes(code) && /[GM]\s*\d/i.test(argumentsText)) fail('multiple commands on one line are unsupported');
399
+ // Bambu Studio's skip-object start carries one base64 mask of the layer's objects (M624 /g8C/B8AAAA=), whose
400
+ // letters and digits can read as a command; only that exact one-token form is exempt.
401
+ const mask = argumentsText.trim();
402
+ // A whole base64 value (length a multiple of 4) that doesn't itself start like a command (M104S300, G28, T1).
403
+ const objectMask = code==='M624' && /^[A-Za-z0-9+/]+={0,2}$/.test(mask) && mask.length % 4 === 0 && !/^[GMT]\d/i.test(mask);
404
+ if(!objectMask && !['M117','M118','M1002','M1006','M900','M970','M983.1','G383'].includes(code) && /[GM]\s*\d/i.test(argumentsText)) fail('multiple commands on one line are unsupported');
400
405
  // Coordinated extrusion closes the startup-only allowance even when the
401
406
  // source omits layer comments. Retraction also closes it conservatively.
402
407
  if(['G0','G1','G2','G3'].includes(code) && /E/i.test(argumentsText) && /[XY]/i.test(argumentsText)) closeStartupWindow();
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A slicer's refusal in plain words. Bambu Studio, OrcaSlicer, PrusaSlicer and CuraEngine word their errors for
3
+ * their own windows ("One of the plate is empty or has no object fully inside it..."); a client shows the person
4
+ * the sentence here and keeps the slicer's own words for its logs (`slicer_report.slicer_message`).
5
+ *
6
+ * The phrases are the slicers' own strings: Bambu Studio 02.09 and OrcaSlicer 2.3 (their CLI and validation
7
+ * messages), PrusaSlicer 2.9.2 (src/libslic3r/Print.cpp, src/CLI/ProcessActions.cpp) and CuraEngine
8
+ * (src/FffPolygonGenerator.cpp). Matching is on a lowercase fragment, so a version that adds a prefix or a
9
+ * plate number still matches.
10
+ */
11
+ const PLAIN: { phrases: string[]; sentence: string }[] = [
12
+ {
13
+ phrases: [
14
+ "one of the plate is empty or has no object fully inside it",
15
+ "a plate is empty or has no object fully inside it",
16
+ "cannot send the print job for empty plate",
17
+ "no object is fully inside the print volume",
18
+ "found no objects in print volume to slice",
19
+ "found no objects in print volume after skip",
20
+ "all objects are outside of the print volume",
21
+ "arrangement ignored the following objects which can't fit into a single bed",
22
+ ],
23
+ sentence: "Nothing on this plate can be printed: no part sits fully on the bed. A part is off the plate or across its edge, or the model is bigger than the bed.",
24
+ },
25
+ {
26
+ phrases: [
27
+ "laid over the boundary of plate or exceeds the height limit",
28
+ "layed over the boundary of plate",
29
+ "laid over the plate boundaries",
30
+ "partly inside, can not be sliced",
31
+ "located over the boundary of the heated bed",
32
+ ],
33
+ sentence: "A part sits across the edge of the plate, or is taller than the printer can print, so it can't be sliced as it is placed.",
34
+ },
35
+ {
36
+ phrases: ["exceeds the maximum build volume height", "exceeds the printable height"],
37
+ sentence: "The model is taller than the printer can print.",
38
+ },
39
+ {
40
+ phrases: ["object too large", "scale to fit error", "printable area/volume reduced"],
41
+ sentence: "The model is larger than the printer's bed.",
42
+ },
43
+ {
44
+ phrases: ["found g-code outside of the printable area", "found g-code in unprintable area", "g-code path exceeds the printable range"],
45
+ sentence: "The print would go outside the area the printer can reach, usually a brim, skirt, support or the wipe tower near an edge. Move the model further onto the plate.",
46
+ },
47
+ {
48
+ phrases: ["g-code path conflicts found", "found gcode path conflicts between object"],
49
+ sentence: "Two parts are so close that their print paths overlap. Move them apart.",
50
+ },
51
+ {
52
+ phrases: ["the supplied settings will cause an empty print", "there are no non-empty layers"],
53
+ sentence: "These settings would print nothing: no layer of the model has anything to print.",
54
+ },
55
+ ];
56
+
57
+ /** The plain sentence for a slicer's error, or undefined when the words aren't one this knows. */
58
+ export function plainSlicerError(words: string): string | undefined {
59
+ const text = words.toLowerCase();
60
+ return PLAIN.find(entry => entry.phrases.some(phrase => text.includes(phrase)))?.sentence;
61
+ }
62
+
63
+ /** What a person is told when the slicer refused with words this doesn't know. */
64
+ export const UNKNOWN_SLICER_ERROR = "The slicer couldn't slice this model. Its own message is kept for the log.";
@@ -12,6 +12,7 @@ import * as crypto from 'crypto';
12
12
  import { execFile } from 'child_process';
13
13
  import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
14
14
  import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
15
+ import { plainSlicerError, UNKNOWN_SLICER_ERROR } from '../slicer/slicer-messages.js';
15
16
  import { applyProcessOverrides, type ProcessOverrides } from '../slicer/process-overrides.js';
16
17
  import { profileJsonFiles } from '../slicer/profile-files.js';
17
18
  import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
@@ -228,11 +229,21 @@ export type SliceOutput = { path: string; slicer_result?: SlicerResult };
228
229
  */
229
230
  export class SlicerRunError extends Error {
230
231
  readonly slicerText: string;
232
+ /** What a person is told for a slicer's refusal: a plain sentence, never its own words (src/slicer/slicer-messages.ts). */
233
+ readonly plain?: string;
234
+ /** The slicer's words and this server's detail, after the plain sentence: what slicer_report.slicer_message keeps. */
235
+ readonly words: string;
231
236
  constructor(detail: string, readonly slicerResult?: SlicerResult) {
232
237
  const slicerText = slicerResult ? slicerResultText(slicerResult) : "";
233
- super(slicerText ? `${slicerText}\n${detail}` : detail);
238
+ const words = slicerText ? `${slicerText}\n${detail}` : detail;
239
+ // A known refusal, or one in the slicer's own words, is said plainly. A fault of the setup (no slicer, a crash,
240
+ // no output) stays in this server's own words, which say what to fix.
241
+ const plain = plainSlicerError(words) ?? (slicerText ? UNKNOWN_SLICER_ERROR : undefined);
242
+ super(plain ? `${plain}\nThe slicer said: ${words}` : words);
234
243
  this.name = "SlicerRunError";
235
244
  this.slicerText = slicerText;
245
+ this.plain = plain;
246
+ this.words = words;
236
247
  }
237
248
  }
238
249
 
@@ -54,6 +54,7 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
54
54
  // Local reads
55
55
  inspect_print_file: READ_LOCAL,
56
56
  list_3mf_plate_objects: READ_LOCAL,
57
+ list_3mf_plates: READ_LOCAL,
57
58
  get_stl_info: READ_LOCAL,
58
59
  list_templates: READ_LOCAL,
59
60
  get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory