bambu-printer-mcp 1.1.51 → 1.1.53

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 (57) 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 +206 -51
  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 +3 -0
  35. package/dist/stl/stl-manipulator.js +50 -4
  36. package/dist/tool-annotations.d.ts +25 -0
  37. package/dist/tool-annotations.js +96 -0
  38. package/package.json +2 -1
  39. package/src/ams-mapping.ts +52 -0
  40. package/src/bambu-network-bridge.ts +311 -8
  41. package/src/control-reply.ts +41 -0
  42. package/src/counterpart/info.ts +1 -0
  43. package/src/counterpart/route.ts +91 -0
  44. package/src/counterpart/schemas.ts +2 -0
  45. package/src/design-guidance.ts +188 -0
  46. package/src/fusion-mcp-bridge.ts +30 -10
  47. package/src/index.ts +199 -55
  48. package/src/printers/bambu.ts +194 -60
  49. package/src/printers/camera-sources.ts +53 -0
  50. package/src/printers/camera-stream.ts +165 -0
  51. package/src/printers/camera-tools.ts +29 -0
  52. package/src/printers/camera-wire.ts +39 -0
  53. package/src/safety/print-file.ts +12 -2
  54. package/src/safety/printer-state.ts +11 -1
  55. package/src/slicer/layer-pauses.ts +143 -0
  56. package/src/stl/stl-manipulator.ts +58 -5
  57. package/src/tool-annotations.ts +126 -0
package/dist/index.js CHANGED
@@ -1,9 +1,12 @@
1
1
  #!/usr/bin/env node
2
+ import { CAMERA_STREAM_TOOLS } from "./printers/camera-tools.js";
3
+ import { withAnnotations } from "./tool-annotations.js";
2
4
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
6
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
- import { ListResourcesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
7
+ import { ListResourcesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
6
8
  import dotenv from "dotenv";
9
+ import { PRINT_ROUTES, connectionForRoute, ownLocalOf, routeOf, routeOptions, writeEnvValues } from "./counterpart/route.js";
7
10
  import fs from "fs";
8
11
  import os from "node:os";
9
12
  import path from "path";
@@ -14,10 +17,10 @@ import { BambuNetworkBridge, describeBambuNetworkPrintError } from "./bambu-netw
14
17
  import { assertBambuNativeAvailable, bambuNativeControlsAvailable, bambuNativeUnavailableReason, interruptNativeOperations, validateBambuNativeMetadata, buildBambuNativeFanCommand, buildBambuNativeTemperatureCommand, printWithBambuNative, sendCommandWithBambuNative, uploadWithBambuNative, } from "./bambu-native.js";
15
18
  import { importFileViaBambuConnect } from "./bambu-connect.js";
16
19
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
17
- 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";
18
- import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue } from "./ams-mapping.js";
20
+ import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge } from "./fusion-mcp-bridge.js";
21
+ import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
19
22
  import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, parse3MF } from './3mf_parser.js';
20
- import { BambuImplementation, assertDirectPrintSupported, checkedFile } from "./printers/bambu.js";
23
+ import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
21
24
  import { resolveStudioPrintOptions, usedNozzleCount } from "./studio-print-options.js";
22
25
  import { inspectPrintFile } from "./safety/print-file.js";
23
26
  import { SERIAL_MODELS, externalStorageState, validatePrinterState } from "./safety/printer-state.js";
@@ -25,10 +28,12 @@ import { isDualNozzleModel } from "./safety/limits.js";
25
28
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
26
29
  import { detectProfilesRoot } from "./slicer/profile-flatten.js";
27
30
  import { bambuPrinterInfo } from "./counterpart/info.js";
31
+ import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, SERVER_INSTRUCTIONS } from "./design-guidance.js";
28
32
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
29
33
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
30
34
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
31
35
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
36
+ import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
32
37
  dotenv.config();
33
38
  const DEFAULT_HOST = process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST || "localhost";
34
39
  const DEFAULT_BAMBU_SERIAL = process.env.BAMBU_PRINTER_SERIAL || process.env.BAMBU_SERIAL || "";
@@ -59,7 +64,28 @@ if (AUTOMATIC_TEMP_DIR) {
59
64
  const DEFAULT_BAMBU_MODEL = process.env.BAMBU_PRINTER_MODEL?.trim().toLowerCase() ||
60
65
  process.env.BAMBU_MODEL?.trim().toLowerCase() ||
61
66
  "";
62
- const DEFAULT_BAMBU_CONNECTION_MODE = process.env.BAMBU_DEFAULT_CONNECTION_MODE?.trim().toLowerCase() || "";
67
+ // counterpart_print_route changes these at run time (and in the .env file they came from).
68
+ let DEFAULT_BAMBU_CONNECTION_MODE = process.env.BAMBU_DEFAULT_CONNECTION_MODE?.trim().toLowerCase() || "";
69
+ let DEFAULT_BAMBU_CONNECTION_TYPE = process.env.BAMBU_DEFAULT_CONNECTION_TYPE?.trim().toLowerCase() || "";
70
+ /** The connection configured at start, before counterpart_print_route changes it: its own local route is kept. */
71
+ const CONFIGURED_CONNECTION = { mode: DEFAULT_BAMBU_CONNECTION_MODE, type: DEFAULT_BAMBU_CONNECTION_TYPE };
72
+ const CONNECTION_MODES = ["lan_mqtt_ftps", "bambu_native", "bambu_network", "bambu_connect"];
73
+ /**
74
+ * The one route decision for a printer: print_3mf and every print control
75
+ * (cancel, pause, resume) resolve it here, so a job is never controlled over a
76
+ * different connection than the one that started it. Arguments override the
77
+ * server's configured defaults; without either, X2D uses its native route and
78
+ * every other model direct LAN MQTT/FTPS.
79
+ */
80
+ function resolveConnection(args, model) {
81
+ const mode = String(args?.connection_mode || DEFAULT_BAMBU_CONNECTION_MODE || (model === "x2d" ? "bambu_native" : "lan_mqtt_ftps")).trim().toLowerCase();
82
+ if (!CONNECTION_MODES.includes(mode))
83
+ throw new Error("Unsupported connection_mode.");
84
+ const type = String(args?.connection_type || DEFAULT_BAMBU_CONNECTION_TYPE || "cloud").trim().toLowerCase();
85
+ if (!["cloud", "lan"].includes(type))
86
+ throw new Error('connection_type must be "cloud" or "lan".');
87
+ return { mode, type };
88
+ }
63
89
  const DEFAULT_BED_TYPE = process.env.BED_TYPE?.trim().toLowerCase() || "textured_plate";
64
90
  const DEFAULT_NOZZLE_DIAMETER = process.env.NOZZLE_DIAMETER?.trim() || "0.4";
65
91
  /** MCP initialize name/version; counterpart_printer_info reports the same values. */
@@ -70,7 +96,8 @@ const SERVER_INFO = {
70
96
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
71
97
  const OUTPUT_SCHEMA_TOOLS = new Set([
72
98
  "counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
73
- "fusion_mcp_status", "fusion_mcp_call", "fusion_mcp_new_design", "fusion_mcp_export",
99
+ "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
100
+ "camera_stream_start", "camera_frame", "camera_stream_stop",
74
101
  ]);
75
102
  /** Bound for each Linux X2D emergency MQTT send (BAMBU_EMERGENCY_MQTT_TIMEOUT_MS, 1–60000 ms). */
76
103
  function withEmergencyMqttTimeout(send) {
@@ -959,9 +986,11 @@ class BambuPrinterMCPServer {
959
986
  this.runtimeConfig = readRuntimeConfig();
960
987
  this.server = new Server(SERVER_INFO, {
961
988
  capabilities: {
989
+ prompts: {},
962
990
  resources: {},
963
991
  tools: {}
964
- }
992
+ },
993
+ instructions: SERVER_INSTRUCTIONS
965
994
  });
966
995
  this.bambu = new BambuImplementation(async (message) => {
967
996
  try {
@@ -984,11 +1013,11 @@ class BambuPrinterMCPServer {
984
1013
  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.`);
985
1014
  }
986
1015
  if (isElicitationUnsupported(error)) {
987
- 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.");
1016
+ 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.");
988
1017
  }
989
1018
  throw new Error(`Human hardware confirmation failed: ${error?.message ?? error}. Nothing was sent to the printer.`);
990
1019
  }
991
- });
1020
+ }, { resumeStateDir: defaultResumeStateDir() });
992
1021
  this.bambuNetwork = new BambuNetworkBridge();
993
1022
  this.stlManipulator = new STLManipulator(TEMP_DIR);
994
1023
  this.setupHandlers();
@@ -1001,6 +1030,7 @@ class BambuPrinterMCPServer {
1001
1030
  }
1002
1031
  setupHandlers() {
1003
1032
  this.setupResourceHandlers();
1033
+ this.setupPromptHandlers();
1004
1034
  this.setupToolHandlers();
1005
1035
  }
1006
1036
  /**
@@ -1216,10 +1246,7 @@ class BambuPrinterMCPServer {
1216
1246
  if (!Number.isInteger(plateIndex) || plateIndex < 0) {
1217
1247
  throw new Error("plate_index must be a non-negative integer.");
1218
1248
  }
1219
- const connectionType = String(args?.connection_type || "cloud").trim().toLowerCase();
1220
- if (!["cloud", "lan"].includes(connectionType)) {
1221
- throw new Error('connection_type must be "cloud" or "lan".');
1222
- }
1249
+ const connectionType = resolveConnection(args).type;
1223
1250
  const bridgePrintMethod = resolveBambuNetworkPrintMethod(args?.bambu_network_method !== undefined ? String(args.bambu_network_method) : undefined, connectionType);
1224
1251
  const bridgeMethod = toBridgeMethod(bridgePrintMethod);
1225
1252
  const isLocalBridgePrint = bridgePrintMethod !== "start_print";
@@ -1306,7 +1333,10 @@ class BambuPrinterMCPServer {
1306
1333
  nozzle_mapping: stringifyBridgeJson(args?.nozzle_mapping) || "",
1307
1334
  ams_mapping: amsMapping || "",
1308
1335
  ams_mapping2: nativeAmsMapping2(mapping, isDualNozzleModel(printModel)) || "",
1309
- ams_mapping_info: stringifyBridgeJson(args?.ams_mapping_info) || "",
1336
+ // Bambu Studio and FULU's slicer send this with every job (get_ams_mapping_result).
1337
+ ams_mapping_info: mapping && inspection.projectFilaments?.length
1338
+ ? JSON.stringify(studioAmsMappingInfo(inspection.projectFilaments, mapping, tray => trayColour(confirmedStatus.raw, tray)))
1339
+ : "",
1310
1340
  nozzles_info: stringifyBridgeJson(args?.nozzles_info) || "",
1311
1341
  connection_type: connectionType,
1312
1342
  comments: String(args?.comments || ""),
@@ -1395,7 +1425,7 @@ class BambuPrinterMCPServer {
1395
1425
  ({ 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));
1396
1426
  }
1397
1427
  else {
1398
- bridgeResult = await this.bambuNetwork.callWithAgent(bridgeMethod, { client_job_id: clientJobId, params }, bridgeOptions);
1428
+ ({ result: bridgeResult, jobUpdates } = await this.bambuNetwork.startCloudPrint(devId, bridgeMethod, { client_job_id: clientJobId, params }, bridgeOptions, assertActive));
1399
1429
  }
1400
1430
  if (typeof bridgeResult === "object" && bridgeResult !== null && bridgeResult.ok === false) {
1401
1431
  throw new Error(`FULU BambuNetwork bridge method ${bridgeMethod} failed: ${String(bridgeResult.error || "unknown bridge error")}`);
@@ -1669,6 +1699,21 @@ class BambuPrinterMCPServer {
1669
1699
  resolved_path: registryEntry,
1670
1700
  };
1671
1701
  }
1702
+ /** The FDM design guidance as MCP prompts: the client decides when to attach each one. */
1703
+ setupPromptHandlers() {
1704
+ this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
1705
+ prompts: DESIGN_PROMPTS.map(({ name, title, description }) => ({ name, title, description })),
1706
+ }));
1707
+ this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
1708
+ const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name);
1709
+ if (!prompt)
1710
+ throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${request.params.name}`);
1711
+ return {
1712
+ description: prompt.description,
1713
+ messages: [{ role: "user", content: { type: "text", text: prompt.text } }],
1714
+ };
1715
+ });
1716
+ }
1672
1717
  setupResourceHandlers() {
1673
1718
  this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
1674
1719
  return {
@@ -1690,7 +1735,8 @@ class BambuPrinterMCPServer {
1690
1735
  name: "Bambu Printer HMS Diagnostics",
1691
1736
  mimeType: "application/json",
1692
1737
  description: "HMS and error-related fields from the latest printer status"
1693
- }
1738
+ },
1739
+ FDM_CAPABILITY_RESOURCE
1694
1740
  ],
1695
1741
  templates: [
1696
1742
  {
@@ -1713,6 +1759,9 @@ class BambuPrinterMCPServer {
1713
1759
  });
1714
1760
  this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
1715
1761
  const uri = request.params.uri;
1762
+ if (uri === FDM_CAPABILITY_URI) {
1763
+ return { contents: [{ uri, mimeType: FDM_CAPABILITY_RESOURCE.mimeType, text: FDM_CAPABILITY_GUIDANCE }] };
1764
+ }
1716
1765
  const match = uri.match(/^printer:\/\/([^\/]+)\/(.+)$/);
1717
1766
  if (!match) {
1718
1767
  throw new McpError(ErrorCode.InvalidRequest, `Invalid resource URI: ${uri}`);
@@ -1997,13 +2046,14 @@ class BambuPrinterMCPServer {
1997
2046
  ensure_on_bed: { type: "boolean", description: "Lift floating models onto the bed." },
1998
2047
  arrange: { type: "boolean", description: "Auto-arrange objects on the build plate." },
1999
2048
  orient: { type: "boolean", description: "Auto-orient model for optimal printability." },
2000
- repetitions: { type: "number", description: "Number of copies to print." },
2049
+ 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." },
2001
2050
  scale: { type: "number", description: "Uniform scale factor." },
2002
2051
  rotate: { type: "number", description: "Z-axis rotation in degrees." },
2003
2052
  rotate_x: { type: "number", description: "X-axis rotation in degrees." },
2004
2053
  rotate_y: { type: "number", description: "Y-axis rotation in degrees." },
2005
2054
  min_save: { type: "boolean", description: "Produce smaller output 3MF." },
2006
2055
  skip_modified_gcodes: { type: "boolean", description: "Ignore stale custom gcodes in the 3MF." },
2056
+ 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." },
2007
2057
  slice_plate: { type: "number", description: "Which plate index to slice. 0 = all plates." }
2008
2058
  },
2009
2059
  required: ["stl_path", "template_name", "bambu_model"]
@@ -2049,7 +2099,7 @@ class BambuPrinterMCPServer {
2049
2099
  },
2050
2100
  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." },
2051
2101
  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." },
2052
- 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." },
2102
+ 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." },
2053
2103
  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." },
2054
2104
  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." },
2055
2105
  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." },
@@ -2067,6 +2117,7 @@ class BambuPrinterMCPServer {
2067
2117
  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." },
2068
2118
  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." },
2069
2119
  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
+ 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." },
2070
2121
  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." },
2071
2122
  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." },
2072
2123
  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." },
@@ -2195,6 +2246,7 @@ class BambuPrinterMCPServer {
2195
2246
  required: ["three_mf_path", "bambu_model"]
2196
2247
  }
2197
2248
  },
2249
+ ...CAMERA_STREAM_TOOLS,
2198
2250
  {
2199
2251
  name: "camera_snapshot",
2200
2252
  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.",
@@ -2326,7 +2378,9 @@ class BambuPrinterMCPServer {
2326
2378
  properties: {
2327
2379
  host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
2328
2380
  bambu_serial: { type: "string", description: "Serial number (default: value from env)" },
2329
- bambu_token: { type: "string", description: "Access token (default: value from env)" }
2381
+ bambu_token: { type: "string", description: "Access token (default: value from env)" },
2382
+ 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." },
2383
+ 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." }
2330
2384
  }
2331
2385
  }
2332
2386
  },
@@ -2338,19 +2392,23 @@ class BambuPrinterMCPServer {
2338
2392
  properties: {
2339
2393
  host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
2340
2394
  bambu_serial: { type: "string", description: "Serial number (default: value from env)" },
2341
- bambu_token: { type: "string", description: "Access token (default: value from env)" }
2395
+ bambu_token: { type: "string", description: "Access token (default: value from env)" },
2396
+ 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." },
2397
+ 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." }
2342
2398
  }
2343
2399
  }
2344
2400
  },
2345
2401
  {
2346
2402
  name: "resume_print",
2347
- 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.",
2403
+ 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.",
2348
2404
  inputSchema: {
2349
2405
  type: "object",
2350
2406
  properties: {
2351
2407
  host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
2352
2408
  bambu_serial: { type: "string", description: "Serial number (default: value from env)" },
2353
- bambu_token: { type: "string", description: "Access token (default: value from env)" }
2409
+ bambu_token: { type: "string", description: "Access token (default: value from env)" },
2410
+ 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." },
2411
+ 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." }
2354
2412
  }
2355
2413
  }
2356
2414
  },
@@ -2535,7 +2593,6 @@ class BambuPrinterMCPServer {
2535
2593
  {
2536
2594
  name: "inspect_print_file",
2537
2595
  description: "Inspect an exact private snapshot of a prepared sliced 3MF or textual G-code file and selected plate without contacting a printer. Returns versioned file-only evidence; no printer readiness or permission to dispatch is established. Does not auto-slice.",
2538
- annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
2539
2596
  inputSchema: {
2540
2597
  type: "object",
2541
2598
  additionalProperties: false,
@@ -2556,6 +2613,7 @@ class BambuPrinterMCPServer {
2556
2613
  type: "object",
2557
2614
  properties: {
2558
2615
  three_mf_path: { type: "string", description: "Path to the 3MF file to print" },
2616
+ 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." },
2559
2617
  bambu_model: {
2560
2618
  type: "string",
2561
2619
  enum: [...VALID_BAMBU_MODELS],
@@ -2759,8 +2817,18 @@ class BambuPrinterMCPServer {
2759
2817
  bambu_token: { type: "string", description: "Access token (default: value from env); never returned." }
2760
2818
  }
2761
2819
  },
2762
- outputSchema: PRINTER_INFO_OUTPUT_SCHEMA,
2763
- annotations: { readOnlyHint: true }
2820
+ outputSchema: PRINTER_INFO_OUTPUT_SCHEMA
2821
+ },
2822
+ {
2823
+ name: "counterpart_print_route",
2824
+ 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.",
2825
+ inputSchema: {
2826
+ type: "object",
2827
+ properties: {
2828
+ route: { type: "string", enum: ["lan", "cloud", "developer"], description: "Change the route. Omit to read it." }
2829
+ },
2830
+ additionalProperties: false
2831
+ }
2764
2832
  },
2765
2833
  {
2766
2834
  name: "counterpart_print_progress",
@@ -2774,8 +2842,7 @@ class BambuPrinterMCPServer {
2774
2842
  bambu_token: { type: "string", description: "Access token (default: value from env)" }
2775
2843
  }
2776
2844
  },
2777
- outputSchema: PRINT_PROGRESS_OUTPUT_SCHEMA,
2778
- annotations: { readOnlyHint: true }
2845
+ outputSchema: PRINT_PROGRESS_OUTPUT_SCHEMA
2779
2846
  },
2780
2847
  {
2781
2848
  name: "counterpart_make_3mf",
@@ -2825,14 +2892,14 @@ class BambuPrinterMCPServer {
2825
2892
  inputSchema: {
2826
2893
  type: "object",
2827
2894
  properties: {
2895
+ 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." },
2828
2896
  tool_name: { type: "string", description: "Exact tool name advertised by the Fusion MCP server." },
2829
2897
  arguments: { type: "object", description: "Arguments matching the remote tool's discovered input schema." },
2830
2898
  timeout_ms: { type: "integer", minimum: 100, maximum: 600000, description: "Total deadline in milliseconds; defaults to FUSION_MCP_TIMEOUT_MS or 180000." }
2831
2899
  },
2832
2900
  required: ["tool_name"],
2833
2901
  additionalProperties: false
2834
- },
2835
- outputSchema: FUSION_CALL_OUTPUT_SCHEMA
2902
+ }
2836
2903
  },
2837
2904
  {
2838
2905
  name: "fusion_mcp_new_design",
@@ -2840,6 +2907,8 @@ class BambuPrinterMCPServer {
2840
2907
  inputSchema: {
2841
2908
  type: "object",
2842
2909
  properties: {
2910
+ 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." },
2911
+ source_f3d: { type: "string", description: "With bind_document, import this absolute F3D path into a new document for revision." },
2843
2912
  timeout_ms: { type: "integer", minimum: 100, maximum: 600000, description: "Total deadline in milliseconds; defaults to FUSION_MCP_TIMEOUT_MS or 180000." }
2844
2913
  },
2845
2914
  additionalProperties: false
@@ -2852,6 +2921,7 @@ class BambuPrinterMCPServer {
2852
2921
  inputSchema: {
2853
2922
  type: "object",
2854
2923
  properties: {
2924
+ 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." },
2855
2925
  output_dir: { type: "string", description: "Existing directory for the three files." },
2856
2926
  name: { type: "string", description: "File name without extension, such as bracket." },
2857
2927
  body_name: { type: "string", description: "The body to export as STL. Optional when the design has exactly one body." },
@@ -2862,7 +2932,7 @@ class BambuPrinterMCPServer {
2862
2932
  },
2863
2933
  outputSchema: FUSION_EXPORT_OUTPUT_SCHEMA
2864
2934
  }
2865
- ]
2935
+ ].map(withAnnotations)
2866
2936
  };
2867
2937
  });
2868
2938
  this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
@@ -2910,6 +2980,30 @@ class BambuPrinterMCPServer {
2910
2980
  // again once every older helper for this printer has exited, and only
2911
2981
  // that send counts. Either counted route succeeding is success. macOS
2912
2982
  // stays native-only.
2983
+ // Print controls go over the same connection as the print (resolveConnection).
2984
+ // undefined keeps the direct MQTT route in BambuImplementation.
2985
+ const printerControl = (command) => {
2986
+ const nativeCommand = (assertActive, beforeDispatch) => sendNativeCommand({ host, serial: bambuSerial, token: bambuToken,
2987
+ messageJson: JSON.stringify({ print: { command, param: "", sequence_id: String(Date.now()) } }), qos: 1 }, command === "resume" ? { signal: extra.signal, assertActive, beforeDispatch } : undefined);
2988
+ // The selected route decides first: a job started over FULU's bridge (LAN or cloud) is controlled there,
2989
+ // even on an X2D whose native plug-in is installed. Otherwise an X2D uses its native route when it can.
2990
+ const route = resolveConnection(args);
2991
+ if (route.mode !== "bambu_network" && nativeControls()) {
2992
+ return command === "stop"
2993
+ ? linuxEmergency(() => nativeCommand(), signal => this.bambu.sendStopOverMqtt(host, bambuSerial, bambuToken, signal))
2994
+ : nativeCommand;
2995
+ }
2996
+ if (route.mode === "bambu_native")
2997
+ throw new Error(nativeUnavailableReason());
2998
+ if (route.mode !== "bambu_network")
2999
+ return undefined;
3000
+ return (assertActive, beforeDispatch) => {
3001
+ const options = { assertDispatchAllowed: () => { extra.signal.throwIfAborted(); assertActive?.(); } };
3002
+ return route.type === "cloud"
3003
+ ? this.bambuNetwork.sendCloudPrintCommand(bambuSerial, command, options, beforeDispatch)
3004
+ : this.bambuNetwork.sendLocalPrintCommand({ devId: bambuSerial, devIp: host, username: "bblp", password: bambuToken, useSsl: true }, command, options, beforeDispatch);
3005
+ };
3006
+ };
2913
3007
  const linuxEmergency = (native, mqtt) => async () => {
2914
3008
  if (process.platform !== "linux")
2915
3009
  return native();
@@ -3079,6 +3173,23 @@ class BambuPrinterMCPServer {
3079
3173
  result = await this.print3mfViaBambuNetwork(args, host, bambuSerial, bambuToken);
3080
3174
  break;
3081
3175
  }
3176
+ case "camera_stream_start":
3177
+ result = this.bambu.cameraStreamStart(host, bambuSerial, bambuToken, {
3178
+ bambuModel: args?.bambu_model ?? process.env.BAMBU_MODEL ?? process.env.BAMBU_PRINTER_MODEL,
3179
+ fps: args?.fps, idleTimeoutMs: args?.idle_timeout_ms,
3180
+ ffmpegPath: this.runtimeConfig.ffmpegPath,
3181
+ });
3182
+ break;
3183
+ case "camera_frame":
3184
+ result = await this.bambu.cameraStreamFrame(host, bambuSerial, {
3185
+ sinceSeq: args?.since_seq, waitMs: args?.wait_ms,
3186
+ maxWidth: args?.max_width, maxBytes: args?.max_bytes, changedOnly: args?.changed_only,
3187
+ minChange: args?.min_change, signal: extra.signal,
3188
+ });
3189
+ break;
3190
+ case "camera_stream_stop":
3191
+ result = this.bambu.cameraStreamStop(host, bambuSerial);
3192
+ break;
3082
3193
  case "camera_snapshot": {
3083
3194
  const snapshotModel = args?.bambu_model ?? process.env.BAMBU_MODEL ?? process.env.BAMBU_PRINTER_MODEL;
3084
3195
  result = await this.bambu.cameraSnapshot(host, bambuSerial, bambuToken, {
@@ -3140,22 +3251,13 @@ class BambuPrinterMCPServer {
3140
3251
  break;
3141
3252
  }
3142
3253
  case "cancel_print":
3143
- result = await this.bambu.cancelJob(host, bambuSerial, bambuToken, nativeControls()
3144
- ? linuxEmergency(() => sendNativeCommand({ host, serial: bambuSerial, token: bambuToken,
3145
- messageJson: JSON.stringify({ print: { command: "stop", param: "", sequence_id: String(Date.now()) } }), qos: 1 }), signal => this.bambu.sendStopOverMqtt(host, bambuSerial, bambuToken, signal))
3146
- : undefined);
3254
+ result = await this.bambu.cancelJob(host, bambuSerial, bambuToken, printerControl("stop"));
3147
3255
  break;
3148
3256
  case "pause_print":
3149
- result = await this.bambu.pauseJob(host, bambuSerial, bambuToken, nativeControls()
3150
- ? () => sendNativeCommand({ host, serial: bambuSerial, token: bambuToken,
3151
- messageJson: JSON.stringify({ print: { command: "pause", param: "", sequence_id: String(Date.now()) } }), qos: 1 })
3152
- : undefined);
3257
+ result = await this.bambu.pauseJob(host, bambuSerial, bambuToken, printerControl("pause"));
3153
3258
  break;
3154
3259
  case "resume_print":
3155
- result = await this.bambu.resumeJob(host, bambuSerial, bambuToken, nativeControls()
3156
- ? (assertActive, beforeDispatch) => sendNativeCommand({ host, serial: bambuSerial, token: bambuToken,
3157
- messageJson: JSON.stringify({ print: { command: "resume", param: "", sequence_id: String(Date.now()) } }), qos: 1 }, { signal: extra.signal, assertActive, beforeDispatch })
3158
- : undefined);
3260
+ result = await this.bambu.resumeJob(host, bambuSerial, bambuToken, printerControl("resume"));
3159
3261
  break;
3160
3262
  case "x2d_native_control": {
3161
3263
  if (!args?.message_json) {
@@ -3507,6 +3609,11 @@ class BambuPrinterMCPServer {
3507
3609
  sliceBambuOptions.skipModifiedGcodes = Boolean(args.skip_modified_gcodes);
3508
3610
  if (args?.slice_plate !== undefined)
3509
3611
  sliceBambuOptions.slicePlate = Number(args.slice_plate);
3612
+ {
3613
+ const pauses = parsePauseLayers(args?.pause_at_layers);
3614
+ if (pauses)
3615
+ sliceBambuOptions.pauseAtLayers = pauses;
3616
+ }
3510
3617
  const usePrinterFilaments = args?.use_printer_filaments !== undefined ? Boolean(args.use_printer_filaments) : true;
3511
3618
  if (usePrinterFilaments &&
3512
3619
  !explicitSlicerProfile &&
@@ -3588,6 +3695,11 @@ class BambuPrinterMCPServer {
3588
3695
  sliceBambuOptions.skipModifiedGcodes = Boolean(args.skip_modified_gcodes);
3589
3696
  if (args?.slice_plate !== undefined)
3590
3697
  sliceBambuOptions.slicePlate = Number(args.slice_plate);
3698
+ {
3699
+ const pauses = parsePauseLayers(args?.pause_at_layers);
3700
+ if (pauses)
3701
+ sliceBambuOptions.pauseAtLayers = pauses;
3702
+ }
3591
3703
  const processOverrides = parseProcessOverrides(args, Number(nozzleDiam));
3592
3704
  if (processOverrides)
3593
3705
  sliceBambuOptions.processOverrides = processOverrides;
@@ -3624,11 +3736,7 @@ class BambuPrinterMCPServer {
3624
3736
  const printModel = await this.resolveBambuModel(args.bambu_model);
3625
3737
  const resolvedArgs = { ...args, bambu_model: printModel };
3626
3738
  const requestedModel = printModel;
3627
- const defaultConnectionMode = DEFAULT_BAMBU_CONNECTION_MODE ||
3628
- (requestedModel === "x2d" ? "bambu_native" : "lan_mqtt_ftps");
3629
- const connectionMode = String(args?.connection_mode || defaultConnectionMode).trim().toLowerCase();
3630
- if (!["lan_mqtt_ftps", "bambu_native", "bambu_network", "bambu_connect"].includes(connectionMode))
3631
- throw new Error("Unsupported connection_mode.");
3739
+ const connectionMode = resolveConnection(args, requestedModel).mode;
3632
3740
  // X2D firmware accepts the Bambu Studio :6000/eMMC route but
3633
3741
  // rejects the legacy direct FTPS STOR operation with 553. Keep
3634
3742
  // an explicit old-mode request from re-entering that known-bad
@@ -3669,6 +3777,16 @@ class BambuPrinterMCPServer {
3669
3777
  const zipData = fs.readFileSync(threeMFPath);
3670
3778
  const zip = await JSZip.loadAsync(zipData);
3671
3779
  const hasGcode = Object.values(zip.files).some(entry => !entry.dir && /\.gcode$/i.test(entry.name));
3780
+ const pauseLayers = parsePauseLayers(args?.pause_at_layers);
3781
+ if (hasGcode && pauseLayers) {
3782
+ // Already sliced: its G-code is what prints, so the pauses must already be in it.
3783
+ const gcode = await readPlateGcode(threeMFPath, Number(args?.plate_index ?? 0) + 1);
3784
+ const placed = gcode ? pausedLayers(gcode, machinePauseGcode(gcode)) : [];
3785
+ const missing = pauseLayers.filter(layer => !placed.includes(layer));
3786
+ if (missing.length) {
3787
+ 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.`);
3788
+ }
3789
+ }
3672
3790
  if (!hasGcode) {
3673
3791
  assertUniformCliNozzles(args);
3674
3792
  if (printBedType === "supertack_plate") {
@@ -3682,6 +3800,7 @@ class BambuPrinterMCPServer {
3682
3800
  bedType: printBedType,
3683
3801
  nozzleType: resolveNozzleType(args?.nozzle_type),
3684
3802
  nozzleVolumeType: resolveNozzleVolumeType(args?.nozzle_volume_type),
3803
+ ...(pauseLayers ? { pauseAtLayers: pauseLayers } : {}),
3685
3804
  };
3686
3805
  if (!explicitSlicerProfile) {
3687
3806
  try {
@@ -3874,6 +3993,36 @@ class BambuPrinterMCPServer {
3874
3993
  case "counterpart_printer_info":
3875
3994
  result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial) });
3876
3995
  break;
3996
+ case "counterpart_print_route": {
3997
+ let savedTo = null;
3998
+ // FULU's bridge is set up, so the routes through it can be used.
3999
+ const bridgeConfigured = Boolean(this.bambuNetwork.resolveBridgeCommand());
4000
+ const routeModel = this.displayModel(args, bambuSerial);
4001
+ // The printer's own local route (X2D native by default, or a configured native/Bambu Connect mode),
4002
+ // resolved from the start-up configuration so it survives choosing another route.
4003
+ const ownLocal = ownLocalOf({ mode: CONFIGURED_CONNECTION.mode || (routeModel === "x2d" ? "bambu_native" : ""), type: CONFIGURED_CONNECTION.type || "lan" });
4004
+ if (args?.route !== undefined) {
4005
+ if (!PRINT_ROUTES.includes(args.route))
4006
+ throw new Error('route must be "lan", "cloud" or "developer".');
4007
+ const next = connectionForRoute(args.route, resolveConnection({}, routeModel), bridgeConfigured, ownLocal);
4008
+ // dotenv loaded .env from the working directory at start; a client's own env block has no file to update.
4009
+ const file = path.resolve(process.cwd(), ".env");
4010
+ if (fs.existsSync(file)) {
4011
+ writeEnvValues(file, {
4012
+ ...(next.mode ? { BAMBU_DEFAULT_CONNECTION_MODE: next.mode } : {}),
4013
+ ...(next.type ? { BAMBU_DEFAULT_CONNECTION_TYPE: next.type } : {}),
4014
+ });
4015
+ savedTo = file;
4016
+ }
4017
+ DEFAULT_BAMBU_CONNECTION_MODE = next.mode;
4018
+ DEFAULT_BAMBU_CONNECTION_TYPE = next.type;
4019
+ }
4020
+ const connection = resolveConnection({}, routeModel);
4021
+ const options = routeOptions(connection, bridgeConfigured, ownLocal);
4022
+ result = { route: routeOf(connection), mode: connection.mode, type: connection.type,
4023
+ choices: options.filter(option => option.available).map(option => option.id), options, savedTo };
4024
+ break;
4025
+ }
3877
4026
  case "counterpart_print_progress": {
3878
4027
  const report = await this.bambu.readProgressReport(host, bambuSerial, bambuToken);
3879
4028
  result = report
@@ -3888,9 +4037,9 @@ class BambuPrinterMCPServer {
3888
4037
  result = await this.fusion.status(args ?? {}, extra.signal);
3889
4038
  break;
3890
4039
  case "fusion_mcp_call": {
3891
- // The remote result passes through unchanged; its structuredContent satisfies the open schema.
3892
- const remote = await this.fusion.call(args ?? {}, extra.signal);
3893
- return { ...remote, structuredContent: remote.structuredContent ?? {} };
4040
+ // Preserve polymorphic text/images/errors. An invented empty structured result
4041
+ // masks useful text in clients that prefer structuredContent.
4042
+ return await this.fusion.call(args ?? {}, extra.signal);
3894
4043
  }
3895
4044
  case "fusion_mcp_new_design":
3896
4045
  result = await this.fusion.newDesign(args ?? {}, extra.signal);
@@ -3902,7 +4051,11 @@ class BambuPrinterMCPServer {
3902
4051
  throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
3903
4052
  }
3904
4053
  await progressNotifications;
3905
- const text = typeof result === "string" ? result : JSON.stringify(result, null, 2);
4054
+ // A stream image belongs in structuredContent once. Repeating its base64 in text
4055
+ // doubles the wire budget; text-only clients still receive useful frame metadata.
4056
+ const textResult = name === "camera_frame" && result && typeof result === "object"
4057
+ ? Object.fromEntries(Object.entries(result).filter(([key]) => key !== "base64")) : result;
4058
+ const text = typeof textResult === "string" ? textResult : JSON.stringify(textResult, null, 2);
3906
4059
  // A declared outputSchema obliges structuredContent whatever MCP_HTTP_JSON_RESPONSE says.
3907
4060
  if ((this.runtimeConfig.enableJsonResponse || OUTPUT_SCHEMA_TOOLS.has(name)) && typeof result === "object") {
3908
4061
  return {
@@ -3949,6 +4102,8 @@ class BambuPrinterMCPServer {
3949
4102
  return;
3950
4103
  this.shuttingDown = true;
3951
4104
  try {
4105
+ // Close camera sockets/processes first, waking any waiting frame requests.
4106
+ this.bambu.cameraStreams.stopAll();
3952
4107
  // Closing the MCP transport aborts its active requests before exit cleanup.
3953
4108
  await this.server.close();
3954
4109
  await this.fusion.close();