bambu-printer-mcp 1.1.50 → 1.1.52

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.
Files changed (54) hide show
  1. package/README.md +33 -8
  2. package/dist/ams-mapping.d.ts +19 -0
  3. package/dist/ams-mapping.js +49 -0
  4. package/dist/bambu-network-bridge.d.ts +86 -9
  5. package/dist/bambu-network-bridge.js +284 -4
  6. package/dist/control-reply.d.ts +21 -0
  7. package/dist/control-reply.js +44 -0
  8. package/dist/counterpart/info.js +1 -0
  9. package/dist/counterpart/route.d.ts +37 -0
  10. package/dist/counterpart/route.js +78 -0
  11. package/dist/counterpart/schemas.d.ts +4 -0
  12. package/dist/counterpart/schemas.js +1 -0
  13. package/dist/design-guidance.d.ts +26 -0
  14. package/dist/design-guidance.js +177 -0
  15. package/dist/fusion-mcp-bridge.d.ts +8 -4
  16. package/dist/fusion-mcp-bridge.js +36 -10
  17. package/dist/index.js +219 -54
  18. package/dist/printers/bambu.d.ts +38 -13
  19. package/dist/printers/bambu.js +204 -69
  20. package/dist/printers/camera-sources.d.ts +8 -0
  21. package/dist/printers/camera-sources.js +66 -0
  22. package/dist/printers/camera-stream.d.ts +65 -0
  23. package/dist/printers/camera-stream.js +227 -0
  24. package/dist/printers/camera-tools.d.ts +192 -0
  25. package/dist/printers/camera-tools.js +29 -0
  26. package/dist/printers/camera-wire.d.ts +7 -0
  27. package/dist/printers/camera-wire.js +40 -0
  28. package/dist/safety/print-file.d.ts +3 -0
  29. package/dist/safety/print-file.js +11 -2
  30. package/dist/safety/printer-state.d.ts +7 -0
  31. package/dist/safety/printer-state.js +11 -1
  32. package/dist/slicer/layer-pauses.d.ts +47 -0
  33. package/dist/slicer/layer-pauses.js +130 -0
  34. package/dist/stl/stl-manipulator.d.ts +40 -1
  35. package/dist/stl/stl-manipulator.js +253 -83
  36. package/package.json +2 -1
  37. package/src/ams-mapping.ts +52 -0
  38. package/src/bambu-network-bridge.ts +311 -8
  39. package/src/control-reply.ts +41 -0
  40. package/src/counterpart/info.ts +1 -0
  41. package/src/counterpart/route.ts +91 -0
  42. package/src/counterpart/schemas.ts +2 -0
  43. package/src/design-guidance.ts +188 -0
  44. package/src/fusion-mcp-bridge.ts +30 -10
  45. package/src/index.ts +213 -57
  46. package/src/printers/bambu.ts +194 -60
  47. package/src/printers/camera-sources.ts +53 -0
  48. package/src/printers/camera-stream.ts +165 -0
  49. package/src/printers/camera-tools.ts +29 -0
  50. package/src/printers/camera-wire.ts +39 -0
  51. package/src/safety/print-file.ts +12 -2
  52. package/src/safety/printer-state.ts +11 -1
  53. package/src/slicer/layer-pauses.ts +143 -0
  54. package/src/stl/stl-manipulator.ts +298 -93
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import {CAMERA_STREAM_TOOLS} from "./printers/camera-tools.js";
2
3
 
3
4
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -8,10 +9,13 @@ import {
8
9
  ReadResourceRequestSchema,
9
10
  ListToolsRequestSchema,
10
11
  CallToolRequestSchema,
12
+ ListPromptsRequestSchema,
13
+ GetPromptRequestSchema,
11
14
  ErrorCode,
12
15
  McpError
13
16
  } from "@modelcontextprotocol/sdk/types.js";
14
17
  import dotenv from "dotenv";
18
+ import { PRINT_ROUTES, connectionForRoute, ownLocalOf, routeOf, routeOptions, writeEnvValues, type PrintRoute } from "./counterpart/route.js";
15
19
  import fs from "fs";
16
20
  import os from "node:os";
17
21
  import path from "path";
@@ -21,6 +25,7 @@ import {
21
25
  STLManipulator,
22
26
  SLICER_TYPES,
23
27
  normalizeSlicerType,
28
+ SlicerRunError,
24
29
  type BambuSliceOptions,
25
30
  type SlicerType,
26
31
  } from "./stl/stl-manipulator.js";
@@ -40,11 +45,11 @@ import {
40
45
  } from "./bambu-native.js";
41
46
  import { importFileViaBambuConnect } from "./bambu-connect.js";
42
47
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
43
- import { FUSION_CALL_OUTPUT_SCHEMA, FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge } from "./fusion-mcp-bridge.js";
44
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue } from "./ams-mapping.js";
48
+ import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge } from "./fusion-mcp-bridge.js";
49
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
45
50
  import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, parse3MF } from './3mf_parser.js';
46
51
  import type { ThreeMFAmsRequirements } from "./types.js";
47
- import { BambuImplementation, assertDirectPrintSupported, checkedFile } from "./printers/bambu.js";
52
+ import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
48
53
  import { resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "./studio-print-options.js";
49
54
  import { inspectPrintFile } from "./safety/print-file.js";
50
55
  import { SERIAL_MODELS, externalStorageState, validatePrinterState } from "./safety/printer-state.js";
@@ -52,10 +57,12 @@ import { isDualNozzleModel } from "./safety/limits.js";
52
57
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
53
58
  import { detectProfilesRoot } from "./slicer/profile-flatten.js";
54
59
  import { bambuPrinterInfo } from "./counterpart/info.js";
60
+ import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, SERVER_INSTRUCTIONS } from "./design-guidance.js";
55
61
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
56
62
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
57
63
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
58
64
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
65
+ import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
59
66
 
60
67
  dotenv.config();
61
68
 
@@ -90,8 +97,29 @@ const DEFAULT_BAMBU_MODEL =
90
97
  process.env.BAMBU_PRINTER_MODEL?.trim().toLowerCase() ||
91
98
  process.env.BAMBU_MODEL?.trim().toLowerCase() ||
92
99
  "";
93
- const DEFAULT_BAMBU_CONNECTION_MODE =
100
+ // counterpart_print_route changes these at run time (and in the .env file they came from).
101
+ let DEFAULT_BAMBU_CONNECTION_MODE =
94
102
  process.env.BAMBU_DEFAULT_CONNECTION_MODE?.trim().toLowerCase() || "";
103
+ let DEFAULT_BAMBU_CONNECTION_TYPE =
104
+ process.env.BAMBU_DEFAULT_CONNECTION_TYPE?.trim().toLowerCase() || "";
105
+ /** The connection configured at start, before counterpart_print_route changes it: its own local route is kept. */
106
+ const CONFIGURED_CONNECTION = { mode: DEFAULT_BAMBU_CONNECTION_MODE, type: DEFAULT_BAMBU_CONNECTION_TYPE };
107
+ const CONNECTION_MODES = ["lan_mqtt_ftps", "bambu_native", "bambu_network", "bambu_connect"];
108
+
109
+ /**
110
+ * The one route decision for a printer: print_3mf and every print control
111
+ * (cancel, pause, resume) resolve it here, so a job is never controlled over a
112
+ * different connection than the one that started it. Arguments override the
113
+ * server's configured defaults; without either, X2D uses its native route and
114
+ * every other model direct LAN MQTT/FTPS.
115
+ */
116
+ function resolveConnection(args: Record<string, unknown> | undefined, model?: string): { mode: string; type: string } {
117
+ const mode = String(args?.connection_mode || DEFAULT_BAMBU_CONNECTION_MODE || (model === "x2d" ? "bambu_native" : "lan_mqtt_ftps")).trim().toLowerCase();
118
+ if (!CONNECTION_MODES.includes(mode)) throw new Error("Unsupported connection_mode.");
119
+ const type = String(args?.connection_type || DEFAULT_BAMBU_CONNECTION_TYPE || "cloud").trim().toLowerCase();
120
+ if (!["cloud", "lan"].includes(type)) throw new Error('connection_type must be "cloud" or "lan".');
121
+ return { mode, type };
122
+ }
95
123
  const DEFAULT_BED_TYPE = process.env.BED_TYPE?.trim().toLowerCase() || "textured_plate";
96
124
  const DEFAULT_NOZZLE_DIAMETER = process.env.NOZZLE_DIAMETER?.trim() || "0.4";
97
125
  /** MCP initialize name/version; counterpart_printer_info reports the same values. */
@@ -102,7 +130,8 @@ const SERVER_INFO = {
102
130
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
103
131
  const OUTPUT_SCHEMA_TOOLS = new Set([
104
132
  "counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
105
- "fusion_mcp_status", "fusion_mcp_call", "fusion_mcp_new_design", "fusion_mcp_export",
133
+ "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
134
+ "camera_stream_start", "camera_frame", "camera_stream_stop",
106
135
  ]);
107
136
 
108
137
  /** Bound for each Linux X2D emergency MQTT send (BAMBU_EMERGENCY_MQTT_TIMEOUT_MS, 1–60000 ms). */
@@ -933,6 +962,7 @@ type StructuredToolError = {
933
962
  suggestion: string;
934
963
  message: string;
935
964
  tool: string;
965
+ slicer_result?: Record<string, unknown>;
936
966
  };
937
967
 
938
968
  type UploadGcodeSource = {
@@ -1254,9 +1284,11 @@ class BambuPrinterMCPServer {
1254
1284
  SERVER_INFO,
1255
1285
  {
1256
1286
  capabilities: {
1287
+ prompts: {},
1257
1288
  resources: {},
1258
1289
  tools: {}
1259
- }
1290
+ },
1291
+ instructions: SERVER_INSTRUCTIONS
1260
1292
  }
1261
1293
  );
1262
1294
 
@@ -1280,11 +1312,11 @@ class BambuPrinterMCPServer {
1280
1312
  throw new Error(`No hardware confirmation within ${describeDuration(this.confirmationTimeoutMs)}; nothing was sent to the printer. Retry when someone can check the printer, or raise BAMBU_CONFIRMATION_TIMEOUT_MS.`);
1281
1313
  }
1282
1314
  if (isElicitationUnsupported(error)) {
1283
- throw new Error("Human hardware confirmation requires an MCP client with elicitation support. For deliberately headless operation, BAMBU_REQUIRE_CONFIRMATION=0 disables ordinary print/heat prompts; hardware-error confirmation still requires elicitation.");
1315
+ throw new Error("Human hardware confirmation requires an MCP client with elicitation support. Only clearing hardware errors, the first print after a clear, and resuming a file that could not be re-read ask.");
1284
1316
  }
1285
1317
  throw new Error(`Human hardware confirmation failed: ${error?.message ?? error}. Nothing was sent to the printer.`);
1286
1318
  }
1287
- });
1319
+ }, { resumeStateDir: defaultResumeStateDir() });
1288
1320
  this.bambuNetwork = new BambuNetworkBridge();
1289
1321
  this.stlManipulator = new STLManipulator(TEMP_DIR);
1290
1322
 
@@ -1300,6 +1332,7 @@ class BambuPrinterMCPServer {
1300
1332
 
1301
1333
  setupHandlers() {
1302
1334
  this.setupResourceHandlers();
1335
+ this.setupPromptHandlers();
1303
1336
  this.setupToolHandlers();
1304
1337
  }
1305
1338
 
@@ -1609,10 +1642,7 @@ class BambuPrinterMCPServer {
1609
1642
  throw new Error("plate_index must be a non-negative integer.");
1610
1643
  }
1611
1644
 
1612
- const connectionType = String(args?.connection_type || "cloud").trim().toLowerCase();
1613
- if (!["cloud", "lan"].includes(connectionType)) {
1614
- throw new Error('connection_type must be "cloud" or "lan".');
1615
- }
1645
+ const connectionType = resolveConnection(args).type;
1616
1646
 
1617
1647
  const bridgePrintMethod = resolveBambuNetworkPrintMethod(
1618
1648
  args?.bambu_network_method !== undefined ? String(args.bambu_network_method) : undefined,
@@ -1719,7 +1749,10 @@ class BambuPrinterMCPServer {
1719
1749
  nozzle_mapping: stringifyBridgeJson(args?.nozzle_mapping) || "",
1720
1750
  ams_mapping: amsMapping || "",
1721
1751
  ams_mapping2: nativeAmsMapping2(mapping, isDualNozzleModel(printModel)) || "",
1722
- ams_mapping_info: stringifyBridgeJson(args?.ams_mapping_info) || "",
1752
+ // Bambu Studio and FULU's slicer send this with every job (get_ams_mapping_result).
1753
+ ams_mapping_info: mapping && inspection.projectFilaments?.length
1754
+ ? JSON.stringify(studioAmsMappingInfo(inspection.projectFilaments, mapping, tray => trayColour(confirmedStatus.raw, tray)))
1755
+ : "",
1723
1756
  nozzles_info: stringifyBridgeJson(args?.nozzles_info) || "",
1724
1757
  connection_type: connectionType,
1725
1758
  comments: String(args?.comments || ""),
@@ -1811,7 +1844,7 @@ class BambuPrinterMCPServer {
1811
1844
  assertActive
1812
1845
  ));
1813
1846
  } else {
1814
- bridgeResult = await this.bambuNetwork.callWithAgent(bridgeMethod, { client_job_id: clientJobId, params }, bridgeOptions);
1847
+ ({ result: bridgeResult, jobUpdates } = await this.bambuNetwork.startCloudPrint(devId, bridgeMethod, { client_job_id: clientJobId, params }, bridgeOptions, assertActive));
1815
1848
  }
1816
1849
 
1817
1850
  if (typeof bridgeResult === "object" && bridgeResult !== null && (bridgeResult as { ok?: unknown }).ok === false) {
@@ -2195,6 +2228,21 @@ class BambuPrinterMCPServer {
2195
2228
  };
2196
2229
  }
2197
2230
 
2231
+ /** The FDM design guidance as MCP prompts: the client decides when to attach each one. */
2232
+ setupPromptHandlers() {
2233
+ this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
2234
+ prompts: DESIGN_PROMPTS.map(({ name, title, description }) => ({ name, title, description })),
2235
+ }));
2236
+ this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
2237
+ const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name);
2238
+ if (!prompt) throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${request.params.name}`);
2239
+ return {
2240
+ description: prompt.description,
2241
+ messages: [{ role: "user" as const, content: { type: "text" as const, text: prompt.text } }],
2242
+ };
2243
+ });
2244
+ }
2245
+
2198
2246
  setupResourceHandlers() {
2199
2247
  this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
2200
2248
  return {
@@ -2216,7 +2264,8 @@ class BambuPrinterMCPServer {
2216
2264
  name: "Bambu Printer HMS Diagnostics",
2217
2265
  mimeType: "application/json",
2218
2266
  description: "HMS and error-related fields from the latest printer status"
2219
- }
2267
+ },
2268
+ FDM_CAPABILITY_RESOURCE
2220
2269
  ],
2221
2270
  templates: [
2222
2271
  {
@@ -2240,6 +2289,9 @@ class BambuPrinterMCPServer {
2240
2289
 
2241
2290
  this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
2242
2291
  const uri = request.params.uri;
2292
+ if (uri === FDM_CAPABILITY_URI) {
2293
+ return { contents: [{ uri, mimeType: FDM_CAPABILITY_RESOURCE.mimeType, text: FDM_CAPABILITY_GUIDANCE }] };
2294
+ }
2243
2295
  const match = uri.match(/^printer:\/\/([^\/]+)\/(.+)$/);
2244
2296
 
2245
2297
  if (!match) {
@@ -2526,13 +2578,14 @@ class BambuPrinterMCPServer {
2526
2578
  ensure_on_bed: { type: "boolean", description: "Lift floating models onto the bed." },
2527
2579
  arrange: { type: "boolean", description: "Auto-arrange objects on the build plate." },
2528
2580
  orient: { type: "boolean", description: "Auto-orient model for optimal printability." },
2529
- repetitions: { type: "number", description: "Number of copies to print." },
2581
+ repetitions: { type: "number", description: "Total copies of an STL, using clone_objects internally. Do not also pass clone_objects. The slicer may place copies on multiple plates; print_3mf prints one selected plate per call. For 3MF input, select slice_plate explicitly." },
2530
2582
  scale: { type: "number", description: "Uniform scale factor." },
2531
2583
  rotate: { type: "number", description: "Z-axis rotation in degrees." },
2532
2584
  rotate_x: { type: "number", description: "X-axis rotation in degrees." },
2533
2585
  rotate_y: { type: "number", description: "Y-axis rotation in degrees." },
2534
2586
  min_save: { type: "boolean", description: "Produce smaller output 3MF." },
2535
2587
  skip_modified_gcodes: { type: "boolean", description: "Ignore stale custom gcodes in the 3MF." },
2588
+ 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." },
2536
2589
  slice_plate: { type: "number", description: "Which plate index to slice. 0 = all plates." }
2537
2590
  },
2538
2591
  required: ["stl_path", "template_name", "bambu_model"]
@@ -2540,7 +2593,7 @@ class BambuPrinterMCPServer {
2540
2593
  },
2541
2594
  {
2542
2595
  name: "slice_stl",
2543
- 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.",
2596
+ 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.",
2544
2597
  inputSchema: {
2545
2598
  type: "object",
2546
2599
  properties: {
@@ -2578,7 +2631,7 @@ class BambuPrinterMCPServer {
2578
2631
  },
2579
2632
  use_printer_filaments: { type: "boolean", description: "When true, and no explicit slicer profile or load_filaments override is provided, use the printer's current or first loaded AMS filament as the slicer filament profile. Template 3MF process settings can still be used at the same time." },
2580
2633
  uptodate: { type: "boolean", description: "Refresh 3MF preset configs to match the latest BambuStudio version. Use when slicing downloaded or older 3MF files to prevent stale-config failures." },
2581
- repetitions: { type: "number", description: "Print N identical copies of the model. Each copy gets its own plate placement. Example: 3 prints three copies. OrcaSlicer copies an STL with --clone-objects; do not combine with clone_objects." },
2634
+ repetitions: { type: "number", description: "Slice N identical copies of the model. Bambu Studio and OrcaSlicer copy an STL with --clone-objects; do not also pass clone_objects. Copies may need multiple plates; print_3mf prints one selected plate per call. For 3MF input, select slice_plate explicitly." },
2582
2635
  orient: { type: "boolean", description: "Auto-orient the model for optimal printability (minimize supports, maximize bed adhesion). Recommended for raw STL imports that lack a pre-set orientation." },
2583
2636
  arrange: { type: "boolean", description: "Auto-arrange all objects on the build plate with optimal spacing; STL input is arranged by default. Set false only to keep a 3MF's existing layout: an STL that is not already on the plate then fails to slice." },
2584
2637
  ensure_on_bed: { type: "boolean", description: "Detect models floating above the bed and lower them onto the build surface. Safety net for imported models with incorrect Z origins." },
@@ -2596,6 +2649,7 @@ class BambuPrinterMCPServer {
2596
2649
  rotate_y: { type: "number", description: "Rotate the model around the Y-axis by this many degrees before slicing. Useful for reorienting prints for better layer adhesion." },
2597
2650
  min_save: { type: "boolean", description: "Write a smaller output 3MF by omitting non-essential metadata. Reduces file size for faster FTP upload to the printer." },
2598
2651
  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." },
2652
+ 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." },
2599
2653
  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." },
2600
2654
  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." },
2601
2655
  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." },
@@ -2724,6 +2778,7 @@ class BambuPrinterMCPServer {
2724
2778
  required: ["three_mf_path", "bambu_model"]
2725
2779
  }
2726
2780
  },
2781
+ ...CAMERA_STREAM_TOOLS,
2727
2782
  {
2728
2783
  name: "camera_snapshot",
2729
2784
  description: "Capture a single JPEG frame from the printer's chamber camera. A1/P1 use TCP-on-6000; X1/P2S/H2/X2D use RTSP via ffmpeg. Returns JPEG as base64; pass save_path to also write the bytes to disk.",
@@ -2855,7 +2910,9 @@ class BambuPrinterMCPServer {
2855
2910
  properties: {
2856
2911
  host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
2857
2912
  bambu_serial: { type: "string", description: "Serial number (default: value from env)" },
2858
- bambu_token: { type: "string", description: "Access token (default: value from env)" }
2913
+ bambu_token: { type: "string", description: "Access token (default: value from env)" },
2914
+ connection_mode: { type: "string", enum: ["lan_mqtt_ftps", "bambu_network", "bambu_native"], description: "The connection the print used. Defaults to BAMBU_DEFAULT_CONNECTION_MODE, the same default print_3mf uses, else the model's route." },
2915
+ connection_type: { type: "string", enum: ["lan", "cloud"], description: "FULU BambuNetwork connection type the print used. Defaults to BAMBU_DEFAULT_CONNECTION_TYPE, as for print_3mf. Authenticated controls support lan." }
2859
2916
  }
2860
2917
  }
2861
2918
  },
@@ -2867,19 +2924,23 @@ class BambuPrinterMCPServer {
2867
2924
  properties: {
2868
2925
  host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
2869
2926
  bambu_serial: { type: "string", description: "Serial number (default: value from env)" },
2870
- bambu_token: { type: "string", description: "Access token (default: value from env)" }
2927
+ bambu_token: { type: "string", description: "Access token (default: value from env)" },
2928
+ connection_mode: { type: "string", enum: ["lan_mqtt_ftps", "bambu_network", "bambu_native"], description: "The connection the print used. Defaults to BAMBU_DEFAULT_CONNECTION_MODE, the same default print_3mf uses, else the model's route." },
2929
+ connection_type: { type: "string", enum: ["lan", "cloud"], description: "FULU BambuNetwork connection type the print used. Defaults to BAMBU_DEFAULT_CONNECTION_TYPE, as for print_3mf. Authenticated controls support lan." }
2871
2930
  }
2872
2931
  }
2873
2932
  },
2874
2933
  {
2875
2934
  name: "resume_print",
2876
- description: "Resume a paused job that this server inspected and started. It re-downloads the job's file over FTPS and compares its SHA-256, asks a person to confirm (unless BAMBU_REQUIRE_CONFIRMATION=0), and reads the printer again before sending. A job that was cancelled, ended or replaced is never resumed. Returns jobName and bytesVerified.",
2935
+ description: "Resume a paused job that this server inspected and started. It re-downloads the job's file over FTPS and compares its SHA-256, asks a person to confirm only when the file could not be re-read, and reads the printer again before sending. A job that was cancelled, ended or replaced is never resumed. Returns jobName and bytesVerified.",
2877
2936
  inputSchema: {
2878
2937
  type: "object",
2879
2938
  properties: {
2880
2939
  host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
2881
2940
  bambu_serial: { type: "string", description: "Serial number (default: value from env)" },
2882
- bambu_token: { type: "string", description: "Access token (default: value from env)" }
2941
+ bambu_token: { type: "string", description: "Access token (default: value from env)" },
2942
+ connection_mode: { type: "string", enum: ["lan_mqtt_ftps", "bambu_network", "bambu_native"], description: "The connection the print used. Defaults to BAMBU_DEFAULT_CONNECTION_MODE, the same default print_3mf uses, else the model's route." },
2943
+ connection_type: { type: "string", enum: ["lan", "cloud"], description: "FULU BambuNetwork connection type the print used. Defaults to BAMBU_DEFAULT_CONNECTION_TYPE, as for print_3mf. Authenticated controls support lan." }
2883
2944
  }
2884
2945
  }
2885
2946
  },
@@ -3085,6 +3146,7 @@ class BambuPrinterMCPServer {
3085
3146
  type: "object",
3086
3147
  properties: {
3087
3148
  three_mf_path: { type: "string", description: "Path to the 3MF file to print" },
3149
+ 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. Used when the 3MF has no G-code yet; a sliced 3MF must already carry these pauses, or it is refused." },
3088
3150
  bambu_model: {
3089
3151
  type: "string",
3090
3152
  enum: [...VALID_BAMBU_MODELS],
@@ -3215,7 +3277,7 @@ class BambuPrinterMCPServer {
3215
3277
  },
3216
3278
  {
3217
3279
  name: "lay_flat",
3218
- description: "Rotate the model so its largest flat face lies on the XY plane (Z=0)",
3280
+ description: "Rotate the model so a face rests on the bed (Z=0), choosing the orientation with the least part and support volume per mm² of bed contact. A face counts only if nothing hangs below it. Returns the new STL path; structuredContent.laid_flat is false, with the input path, when no orientation qualifies.",
3219
3281
  inputSchema: {
3220
3282
  type: "object",
3221
3283
  properties: {
@@ -3291,6 +3353,17 @@ class BambuPrinterMCPServer {
3291
3353
  outputSchema: PRINTER_INFO_OUTPUT_SCHEMA,
3292
3354
  annotations: { readOnlyHint: true }
3293
3355
  },
3356
+ {
3357
+ name: "counterpart_print_route",
3358
+ description: "Counterpart contract (counterpart/1): how this server reaches the printer for prints and for Stop/Pause/Resume. route is \"lan\" (the local network through FULU's BambuNetwork bridge, or the configured X2D native or Bambu Connect mode), \"cloud\" (Bambu Cloud through FULU's bridge) or \"developer\" (the local network straight to a printer in LAN Only + Developer Mode, whose Pause, Resume and Stop need no Bambu app). options lists each with its label, whether it can be chosen here (and why not) and what controls do on it; choices lists the ids that can be chosen. mode and type are BAMBU_DEFAULT_CONNECTION_MODE and BAMBU_DEFAULT_CONNECTION_TYPE as resolved. Pass route to change it: the change applies to the next print and control at once, and is saved to the .env file in this server's working directory when that file exists (savedTo; null otherwise). Sends nothing to the printer.",
3359
+ inputSchema: {
3360
+ type: "object",
3361
+ properties: {
3362
+ route: { type: "string", enum: ["lan", "cloud", "developer"], description: "Change the route. Omit to read it." }
3363
+ },
3364
+ additionalProperties: false
3365
+ }
3366
+ },
3294
3367
  {
3295
3368
  name: "counterpart_print_progress",
3296
3369
  description: "Counterpart contract (counterpart/1): the printer's state, current job (name, task id, percent, time left, layers, stage words), temperatures, active filament and problems with Bambu's HMS messages and links. Read from the MQTT report this server keeps, so a held session asks the printer nothing; observedAt is when the printer sent it. An unreachable printer reports state offline. Read-only; not a safety check.",
@@ -3354,14 +3427,14 @@ class BambuPrinterMCPServer {
3354
3427
  inputSchema: {
3355
3428
  type: "object",
3356
3429
  properties: {
3430
+ document_id: { type: "string", minLength: 1, description: "Session identity returned by a bound new design. Every operation targets this document, even if the user changes tabs." },
3357
3431
  tool_name: { type: "string", description: "Exact tool name advertised by the Fusion MCP server." },
3358
3432
  arguments: { type: "object", description: "Arguments matching the remote tool's discovered input schema." },
3359
3433
  timeout_ms: { type: "integer", minimum: 100, maximum: 600000, description: "Total deadline in milliseconds; defaults to FUSION_MCP_TIMEOUT_MS or 180000." }
3360
3434
  },
3361
3435
  required: ["tool_name"],
3362
3436
  additionalProperties: false
3363
- },
3364
- outputSchema: FUSION_CALL_OUTPUT_SCHEMA
3437
+ }
3365
3438
  },
3366
3439
  {
3367
3440
  name: "fusion_mcp_new_design",
@@ -3369,6 +3442,8 @@ class BambuPrinterMCPServer {
3369
3442
  inputSchema: {
3370
3443
  type: "object",
3371
3444
  properties: {
3445
+ bind_document: { type: "boolean", description: "Create an isolated document and return its session identity, restoring the previously active document. Requires document-binding support in the configured bridge/add-in." },
3446
+ source_f3d: { type: "string", description: "With bind_document, import this absolute F3D path into a new document for revision." },
3372
3447
  timeout_ms: { type: "integer", minimum: 100, maximum: 600000, description: "Total deadline in milliseconds; defaults to FUSION_MCP_TIMEOUT_MS or 180000." }
3373
3448
  },
3374
3449
  additionalProperties: false
@@ -3381,6 +3456,7 @@ class BambuPrinterMCPServer {
3381
3456
  inputSchema: {
3382
3457
  type: "object",
3383
3458
  properties: {
3459
+ document_id: { type: "string", minLength: 1, description: "Session identity returned by a bound new design. Every operation targets this document, even if the user changes tabs." },
3384
3460
  output_dir: { type: "string", description: "Existing directory for the three files." },
3385
3461
  name: { type: "string", description: "File name without extension, such as bracket." },
3386
3462
  body_name: { type: "string", description: "The body to export as STL. Optional when the design has exactly one body." },
@@ -3446,6 +3522,29 @@ class BambuPrinterMCPServer {
3446
3522
  // again once every older helper for this printer has exited, and only
3447
3523
  // that send counts. Either counted route succeeding is success. macOS
3448
3524
  // stays native-only.
3525
+ // Print controls go over the same connection as the print (resolveConnection).
3526
+ // undefined keeps the direct MQTT route in BambuImplementation.
3527
+ const printerControl = (command: "stop" | "pause" | "resume") => {
3528
+ const nativeCommand = (assertActive?: () => void, beforeDispatch?: () => Promise<void>) => sendNativeCommand({ host, serial: bambuSerial, token: bambuToken,
3529
+ messageJson: JSON.stringify({ print: { command, param: "", sequence_id: String(Date.now()) } }), qos: 1 },
3530
+ command === "resume" ? { signal: extra.signal, assertActive, beforeDispatch } : undefined);
3531
+ // The selected route decides first: a job started over FULU's bridge (LAN or cloud) is controlled there,
3532
+ // even on an X2D whose native plug-in is installed. Otherwise an X2D uses its native route when it can.
3533
+ const route = resolveConnection(args);
3534
+ if (route.mode !== "bambu_network" && nativeControls()) {
3535
+ return command === "stop"
3536
+ ? linuxEmergency(() => nativeCommand(), signal => this.bambu.sendStopOverMqtt(host, bambuSerial, bambuToken, signal))
3537
+ : nativeCommand;
3538
+ }
3539
+ if (route.mode === "bambu_native") throw new Error(nativeUnavailableReason()!);
3540
+ if (route.mode !== "bambu_network") return undefined;
3541
+ return (assertActive?: () => void, beforeDispatch?: () => Promise<void>) => {
3542
+ const options = { assertDispatchAllowed: () => { extra.signal.throwIfAborted(); assertActive?.(); } };
3543
+ return route.type === "cloud"
3544
+ ? this.bambuNetwork.sendCloudPrintCommand(bambuSerial, command, options, beforeDispatch)
3545
+ : this.bambuNetwork.sendLocalPrintCommand({ devId: bambuSerial, devIp: host, username: "bblp", password: bambuToken, useSsl: true }, command, options, beforeDispatch);
3546
+ };
3547
+ };
3449
3548
  const linuxEmergency = (native: () => Promise<any>, mqtt: (signal: AbortSignal) => Promise<any>) => async () => {
3450
3549
  if (process.platform !== "linux") return native();
3451
3550
  // An unreachable printer makes the MQTT connect retry forever; bound each
@@ -3647,6 +3746,24 @@ class BambuPrinterMCPServer {
3647
3746
  break;
3648
3747
  }
3649
3748
 
3749
+ case "camera_stream_start":
3750
+ result = this.bambu.cameraStreamStart(host, bambuSerial, bambuToken, {
3751
+ bambuModel: (args?.bambu_model as string | undefined) ?? process.env.BAMBU_MODEL ?? process.env.BAMBU_PRINTER_MODEL,
3752
+ fps: args?.fps as number | undefined, idleTimeoutMs: args?.idle_timeout_ms as number | undefined,
3753
+ ffmpegPath: this.runtimeConfig.ffmpegPath,
3754
+ });
3755
+ break;
3756
+ case "camera_frame":
3757
+ result = await this.bambu.cameraStreamFrame(host, bambuSerial, {
3758
+ sinceSeq: args?.since_seq as number | undefined, waitMs: args?.wait_ms as number | undefined,
3759
+ maxWidth: args?.max_width as number | undefined, maxBytes: args?.max_bytes as number | undefined, changedOnly: args?.changed_only as boolean | undefined,
3760
+ minChange: args?.min_change as number | undefined, signal: extra.signal,
3761
+ });
3762
+ break;
3763
+ case "camera_stream_stop":
3764
+ result = this.bambu.cameraStreamStop(host, bambuSerial);
3765
+ break;
3766
+
3650
3767
  case "camera_snapshot": {
3651
3768
  const snapshotModel = (args?.bambu_model as string | undefined) ?? process.env.BAMBU_MODEL ?? process.env.BAMBU_PRINTER_MODEL;
3652
3769
  result = await this.bambu.cameraSnapshot(host, bambuSerial, bambuToken, {
@@ -3728,29 +3845,15 @@ class BambuPrinterMCPServer {
3728
3845
  }
3729
3846
 
3730
3847
  case "cancel_print":
3731
- result = await this.bambu.cancelJob(host, bambuSerial, bambuToken,
3732
- nativeControls()
3733
- ? linuxEmergency(
3734
- () => sendNativeCommand({ host, serial: bambuSerial, token: bambuToken,
3735
- messageJson: JSON.stringify({ print: { command: "stop", param: "", sequence_id: String(Date.now()) } }), qos: 1 }),
3736
- signal => this.bambu.sendStopOverMqtt(host, bambuSerial, bambuToken, signal))
3737
- : undefined);
3848
+ result = await this.bambu.cancelJob(host, bambuSerial, bambuToken, printerControl("stop"));
3738
3849
  break;
3739
3850
 
3740
3851
  case "pause_print":
3741
- result = await this.bambu.pauseJob(host, bambuSerial, bambuToken,
3742
- nativeControls()
3743
- ? () => sendNativeCommand({ host, serial: bambuSerial, token: bambuToken,
3744
- messageJson: JSON.stringify({ print: { command: "pause", param: "", sequence_id: String(Date.now()) } }), qos: 1 })
3745
- : undefined);
3852
+ result = await this.bambu.pauseJob(host, bambuSerial, bambuToken, printerControl("pause"));
3746
3853
  break;
3747
3854
 
3748
3855
  case "resume_print":
3749
- result = await this.bambu.resumeJob(host, bambuSerial, bambuToken,
3750
- nativeControls()
3751
- ? (assertActive, beforeDispatch) => sendNativeCommand({ host, serial: bambuSerial, token: bambuToken,
3752
- messageJson: JSON.stringify({ print: { command: "resume", param: "", sequence_id: String(Date.now()) } }), qos: 1 }, { signal: extra.signal, assertActive, beforeDispatch })
3753
- : undefined);
3856
+ result = await this.bambu.resumeJob(host, bambuSerial, bambuToken, printerControl("resume"));
3754
3857
  break;
3755
3858
 
3756
3859
  case "x2d_native_control": {
@@ -4150,6 +4253,7 @@ class BambuPrinterMCPServer {
4150
4253
  if (args?.min_save !== undefined) sliceBambuOptions.minSave = Boolean(args.min_save);
4151
4254
  if (args?.skip_modified_gcodes !== undefined) sliceBambuOptions.skipModifiedGcodes = Boolean(args.skip_modified_gcodes);
4152
4255
  if (args?.slice_plate !== undefined) sliceBambuOptions.slicePlate = Number(args.slice_plate);
4256
+ { const pauses = parsePauseLayers(args?.pause_at_layers); if (pauses) sliceBambuOptions.pauseAtLayers = pauses; }
4153
4257
  const usePrinterFilaments =
4154
4258
  args?.use_printer_filaments !== undefined ? Boolean(args.use_printer_filaments) : true;
4155
4259
  if (
@@ -4238,6 +4342,7 @@ class BambuPrinterMCPServer {
4238
4342
  if (args?.min_save !== undefined) sliceBambuOptions.minSave = Boolean(args.min_save);
4239
4343
  if (args?.skip_modified_gcodes !== undefined) sliceBambuOptions.skipModifiedGcodes = Boolean(args.skip_modified_gcodes);
4240
4344
  if (args?.slice_plate !== undefined) sliceBambuOptions.slicePlate = Number(args.slice_plate);
4345
+ { const pauses = parsePauseLayers(args?.pause_at_layers); if (pauses) sliceBambuOptions.pauseAtLayers = pauses; }
4241
4346
  const processOverrides = parseProcessOverrides(args as Record<string, unknown>, Number(nozzleDiam));
4242
4347
  if (processOverrides) sliceBambuOptions.processOverrides = processOverrides;
4243
4348
  if (sliceBambuOptions.loadFilamentIds && String(args.stl_path).toLowerCase().endsWith(".3mf")) {
@@ -4269,14 +4374,16 @@ class BambuPrinterMCPServer {
4269
4374
  }
4270
4375
  }
4271
4376
 
4272
- result = await this.stlManipulator.sliceSTL(
4377
+ const sliced = await this.stlManipulator.sliceSTLWithResult(
4273
4378
  String(args.stl_path), slicerType, slicerPath,
4274
4379
  activeSlicerProfile,
4275
4380
  undefined, // progressCallback
4276
4381
  printerPreset,
4277
4382
  sliceBambuOptions
4278
4383
  );
4279
- break;
4384
+ await progressNotifications;
4385
+ // The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim.
4386
+ return { content: [{ type: "text", text: sliced.path }], structuredContent: sliced };
4280
4387
  }
4281
4388
 
4282
4389
  case "print_3mf": {
@@ -4286,11 +4393,7 @@ class BambuPrinterMCPServer {
4286
4393
  const printModel = await this.resolveBambuModel(args.bambu_model as string | undefined);
4287
4394
  const resolvedArgs = { ...args, bambu_model: printModel };
4288
4395
  const requestedModel = printModel;
4289
- const defaultConnectionMode =
4290
- DEFAULT_BAMBU_CONNECTION_MODE ||
4291
- (requestedModel === "x2d" ? "bambu_native" : "lan_mqtt_ftps");
4292
- const connectionMode = String(args?.connection_mode || defaultConnectionMode).trim().toLowerCase();
4293
- if (!["lan_mqtt_ftps", "bambu_native", "bambu_network", "bambu_connect"].includes(connectionMode)) throw new Error("Unsupported connection_mode.");
4396
+ const connectionMode = resolveConnection(args, requestedModel).mode;
4294
4397
  // X2D firmware accepts the Bambu Studio :6000/eMMC route but
4295
4398
  // rejects the legacy direct FTPS STOR operation with 553. Keep
4296
4399
  // an explicit old-mode request from re-entering that known-bad
@@ -4348,6 +4451,16 @@ class BambuPrinterMCPServer {
4348
4451
  const hasGcode = Object.values(zip.files).some(
4349
4452
  entry => !entry.dir && /\.gcode$/i.test(entry.name)
4350
4453
  );
4454
+ const pauseLayers = parsePauseLayers(args?.pause_at_layers);
4455
+ if (hasGcode && pauseLayers) {
4456
+ // Already sliced: its G-code is what prints, so the pauses must already be in it.
4457
+ const gcode = await readPlateGcode(threeMFPath, Number(args?.plate_index ?? 0) + 1);
4458
+ const placed = gcode ? pausedLayers(gcode, machinePauseGcode(gcode)) : [];
4459
+ const missing = pauseLayers.filter(layer => !placed.includes(layer));
4460
+ if (missing.length) {
4461
+ throw new Error(`This 3MF is already sliced without a pause before layer ${missing.join(", ")}. Slice it again with pause_at_layers (slice_stl), or add the pause in Bambu Studio or OrcaSlicer.`);
4462
+ }
4463
+ }
4351
4464
  if (!hasGcode) {
4352
4465
  assertUniformCliNozzles(args as Record<string, any>);
4353
4466
  if (printBedType === "supertack_plate") {
@@ -4363,6 +4476,7 @@ class BambuPrinterMCPServer {
4363
4476
  bedType: printBedType,
4364
4477
  nozzleType: resolveNozzleType(args?.nozzle_type),
4365
4478
  nozzleVolumeType: resolveNozzleVolumeType(args?.nozzle_volume_type),
4479
+ ...(pauseLayers ? { pauseAtLayers: pauseLayers } : {}),
4366
4480
  };
4367
4481
  if (!explicitSlicerProfile) {
4368
4482
  try {
@@ -4598,10 +4712,13 @@ class BambuPrinterMCPServer {
4598
4712
  result = await this.stlManipulator.centerModel(String(args.stl_path));
4599
4713
  break;
4600
4714
 
4601
- case "lay_flat":
4715
+ case "lay_flat": {
4602
4716
  if (!args?.stl_path) throw new Error("Missing required parameter: stl_path");
4603
- result = await this.stlManipulator.layFlat(String(args.stl_path));
4604
- break;
4717
+ const layFlatResult = await this.stlManipulator.layFlatWithResult(String(args.stl_path));
4718
+ await progressNotifications;
4719
+ // The text stays the STL path clients read; structuredContent says whether it was laid flat.
4720
+ return { content: [{ type: "text", text: layFlatResult.path }], structuredContent: layFlatResult };
4721
+ }
4605
4722
 
4606
4723
  case "blender_mcp_status":
4607
4724
  result = await this.blender.status(args ?? {}, extra.signal);
@@ -4627,6 +4744,36 @@ class BambuPrinterMCPServer {
4627
4744
  result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial) });
4628
4745
  break;
4629
4746
 
4747
+ case "counterpart_print_route": {
4748
+ let savedTo: string | null = null;
4749
+ // FULU's bridge is set up, so the routes through it can be used.
4750
+ const bridgeConfigured = Boolean(this.bambuNetwork.resolveBridgeCommand());
4751
+ const routeModel = this.displayModel(args, bambuSerial);
4752
+ // The printer's own local route (X2D native by default, or a configured native/Bambu Connect mode),
4753
+ // resolved from the start-up configuration so it survives choosing another route.
4754
+ const ownLocal = ownLocalOf({ mode: CONFIGURED_CONNECTION.mode || (routeModel === "x2d" ? "bambu_native" : ""), type: CONFIGURED_CONNECTION.type || "lan" });
4755
+ if (args?.route !== undefined) {
4756
+ if (!PRINT_ROUTES.includes(args.route as PrintRoute)) throw new Error('route must be "lan", "cloud" or "developer".');
4757
+ const next = connectionForRoute(args.route as PrintRoute, resolveConnection({}, routeModel), bridgeConfigured, ownLocal);
4758
+ // dotenv loaded .env from the working directory at start; a client's own env block has no file to update.
4759
+ const file = path.resolve(process.cwd(), ".env");
4760
+ if (fs.existsSync(file)) {
4761
+ writeEnvValues(file, {
4762
+ ...(next.mode ? { BAMBU_DEFAULT_CONNECTION_MODE: next.mode } : {}),
4763
+ ...(next.type ? { BAMBU_DEFAULT_CONNECTION_TYPE: next.type } : {}),
4764
+ });
4765
+ savedTo = file;
4766
+ }
4767
+ DEFAULT_BAMBU_CONNECTION_MODE = next.mode;
4768
+ DEFAULT_BAMBU_CONNECTION_TYPE = next.type;
4769
+ }
4770
+ const connection = resolveConnection({}, routeModel);
4771
+ const options = routeOptions(connection, bridgeConfigured, ownLocal);
4772
+ result = { route: routeOf(connection), mode: connection.mode, type: connection.type,
4773
+ choices: options.filter(option => option.available).map(option => option.id), options, savedTo };
4774
+ break;
4775
+ }
4776
+
4630
4777
  case "counterpart_print_progress": {
4631
4778
  const report = await this.bambu.readProgressReport(host, bambuSerial, bambuToken);
4632
4779
  result = report
@@ -4644,9 +4791,9 @@ class BambuPrinterMCPServer {
4644
4791
  break;
4645
4792
 
4646
4793
  case "fusion_mcp_call": {
4647
- // The remote result passes through unchanged; its structuredContent satisfies the open schema.
4648
- const remote = await this.fusion.call(args ?? {}, extra.signal);
4649
- return { ...remote, structuredContent: remote.structuredContent ?? {} };
4794
+ // Preserve polymorphic text/images/errors. An invented empty structured result
4795
+ // masks useful text in clients that prefer structuredContent.
4796
+ return await this.fusion.call(args ?? {}, extra.signal);
4650
4797
  }
4651
4798
 
4652
4799
  case "fusion_mcp_new_design":
@@ -4662,7 +4809,11 @@ class BambuPrinterMCPServer {
4662
4809
  }
4663
4810
 
4664
4811
  await progressNotifications;
4665
- const text = typeof result === "string" ? result : JSON.stringify(result, null, 2);
4812
+ // A stream image belongs in structuredContent once. Repeating its base64 in text
4813
+ // doubles the wire budget; text-only clients still receive useful frame metadata.
4814
+ const textResult = name === "camera_frame" && result && typeof result === "object"
4815
+ ? Object.fromEntries(Object.entries(result).filter(([key]) => key !== "base64")) : result;
4816
+ const text = typeof textResult === "string" ? textResult : JSON.stringify(textResult, null, 2);
4666
4817
 
4667
4818
  // A declared outputSchema obliges structuredContent whatever MCP_HTTP_JSON_RESPONSE says.
4668
4819
  if ((this.runtimeConfig.enableJsonResponse || OUTPUT_SCHEMA_TOOLS.has(name)) && typeof result === "object") {
@@ -4686,12 +4837,15 @@ class BambuPrinterMCPServer {
4686
4837
  : `Check parameters and try again. Error: ${message}`,
4687
4838
  message,
4688
4839
  tool: name,
4840
+ // The slicer's own result.json; the message starts with its error_string and warnings.
4841
+ ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult } : {}),
4689
4842
  };
4690
4843
 
4691
4844
  // MCP clients validate structuredContent against a declared outputSchema even on
4692
4845
  // errors (SDK 1.32 Client.callTool), so those tools return the error as text only.
4693
4846
  return {
4694
- content: [{ type: "text", text: `Error: ${message}` }],
4847
+ // A slicer failure leads with the slicer's own words.
4848
+ content: [{ type: "text", text: error instanceof SlicerRunError && error.slicerText ? message : `Error: ${message}` }],
4695
4849
  ...(OUTPUT_SCHEMA_TOOLS.has(name) ? {} : { structuredContent: structured }),
4696
4850
  isError: true,
4697
4851
  };
@@ -4710,6 +4864,8 @@ class BambuPrinterMCPServer {
4710
4864
  if (this.shuttingDown) return;
4711
4865
  this.shuttingDown = true;
4712
4866
  try {
4867
+ // Close camera sockets/processes first, waking any waiting frame requests.
4868
+ this.bambu.cameraStreams.stopAll();
4713
4869
  // Closing the MCP transport aborts its active requests before exit cleanup.
4714
4870
  await this.server.close();
4715
4871
  await this.fusion.close();