bambu-printer-mcp 1.1.75 → 1.1.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1086,7 +1086,7 @@ If the project does not match those assumptions, the tool fails fast with a stru
1086
1086
 
1087
1087
  #### Counterpart tools (`counterpart/1`)
1088
1088
 
1089
- [Counterpart](https://github.com/DMontgomery40/scan-to-make) (Scan to Make) reads printers through a small contract that this server and [mcp-3D-printer-server](https://github.com/DMontgomery40/mcp-3D-printer-server) share. Each tool declares an `outputSchema` and returns `structuredContent`, plus the same JSON as text for older clients. An error is returned as text only, because MCP clients check `structuredContent` against the schema even on errors. Other tools return an error's details in `structuredContent` (`status`, `retryable`, `suggestion`, `message`). When the printer refuses a print, the error also carries a stable `code`: `printer-command-rejected`, `printer-not-ready`, or `printer-upload-failed` when the file didn't reach the printer and no print command was sent, so a client can act on the code rather than the wording. `counterpart_printer_info` reports `capabilities.slicing` (`supports`, `copies`, `orient`), so a client can offer those choices without knowing the slicer. `counterpart_printer_info` and `counterpart_print_progress` take the usual optional `host`, `bambu_serial`, `bambu_token` and `bambu_model` (default `BAMBU_MODEL`) arguments.
1089
+ [Counterpart](https://github.com/DMontgomery40/scan-to-make) (Scan to Make) reads printers through a small contract that this server and [mcp-3D-printer-server](https://github.com/DMontgomery40/mcp-3D-printer-server) share. Each tool declares an `outputSchema` and returns `structuredContent`, plus the same JSON as text for older clients. An error is returned as text only, because MCP clients check `structuredContent` against the schema even on errors. Other tools return an error's details in `structuredContent` (`status`, `retryable`, `suggestion`, `message`). When the printer refuses a print, the error also carries a stable `code`: `printer-command-rejected`, `printer-not-ready`, or `printer-upload-failed` when the file didn't reach the printer and no print command was sent, so a client can act on the code rather than the wording. A `print_3mf` call made with a progress token reports its LAN upload as MCP progress: `progress` is bytes sent, `total` the file's bytes, and `_meta["counterpart/stage"]` is `"upload"`, at most once per whole percent. `counterpart_printer_info` reports `capabilities.slicing` (`supports`, `copies`, `orient`), so a client can offer those choices without knowing the slicer. `counterpart_printer_info` and `counterpart_print_progress` take the usual optional `host`, `bambu_serial`, `bambu_token` and `bambu_model` (default `BAMBU_MODEL`) arguments.
1090
1090
 
1091
1091
  - **`counterpart_printer_info`** returns `{contract, server: {name, version}, printer: {kind: "bambu", model, serial, host}, capabilities}`. `capabilities` lists progress, layers, the camera transport (`bambu-tcp` for A1/P1, `rtsp` for X1, P2S, H2 and X2D, `none` without a model), `cameraStream: true` for supported camera models, `filaments: "ams"`, pause, resume, cancel, `print3mf` and `gcode` (false on X2D). It sends nothing to the printer and never returns the access code.
1092
1092
  - **`counterpart_print_route`** reads or changes how prints and Stop/Pause/Resume reach the printer: `{route, mode, type, choices, savedTo}`, where `route` is `lan` (the local network, in the configured `BAMBU_DEFAULT_CONNECTION_MODE`) or `cloud` (Bambu Cloud through the [FULU bridge](docs/FULU.md)). Pass `route` to change it; the next print and control use it at once, and it is written to the `.env` in the server's working directory when one exists (`savedTo`, otherwise `null`). It is not part of the shared contract: it has no `outputSchema`, and mcp-3D-printer-server has no Bambu Cloud route.
@@ -52,6 +52,10 @@ export declare const FUSION_STATUS_OUTPUT_SCHEMA: {
52
52
  fusionRunning: {
53
53
  type: string;
54
54
  };
55
+ activeDesign: {
56
+ type: string;
57
+ description: string;
58
+ };
55
59
  tools: {
56
60
  type: string;
57
61
  items: {
@@ -177,6 +177,10 @@ function resultText(result) {
177
177
  function failed(result, name) {
178
178
  return result.isError === true || resultText(result).trimStart().startsWith(`**${name}** ERROR`);
179
179
  }
180
+ /** The add-in's error kind from faust's "**tool** ERROR (KIND)" heading (fusion360_mcp/server.py), when it failed with one. */
181
+ function errorKind(result, name) {
182
+ return new RegExp(`^\\*\\*${name}\\*\\* ERROR \\(([A-Z_]+)\\)`).exec(resultText(result).trimStart())?.[1];
183
+ }
180
184
  /** The value of one " key: value" line in faust's text result. */
181
185
  function resultField(result, key) {
182
186
  for (const line of resultText(result).split("\n")) {
@@ -228,6 +232,7 @@ export const FUSION_STATUS_OUTPUT_SCHEMA = {
228
232
  connected: { type: "boolean", description: "The Fusion MCP server started and the add-in answered its ping." },
229
233
  addinReachable: { type: "boolean", description: "The Fusion360MCP add-in answered a ping on FUSION_MCP_HOST:FUSION_MCP_PORT (default localhost:9877) within 2 s. Another program on that port, such as Blender's MCP add-on, does not count." },
230
234
  fusionRunning: { type: "boolean" },
235
+ activeDesign: { type: "boolean", description: "When connected: whether Fusion has a design open, from the add-in's read-only get_design_type (false is its NO_ACTIVE_DESIGN). The pinned add-in refuses every design command, fusion_mcp_new_design included, without one (faust issue #12). Absent when unknown." },
231
236
  tools: { type: "array", items: { type: "object", properties: { name: { type: "string" } }, required: ["name"] } },
232
237
  launched: { type: "boolean", description: "This call started Fusion." },
233
238
  transport: { type: "string" },
@@ -449,6 +454,25 @@ export class FusionMcpBridge {
449
454
  const ping = await this.invoke(live, options, dispatched, "ping", {});
450
455
  result.connected = !failed(ping, "ping");
451
456
  }
457
+ // Whether a design is open, from the add-in itself. get_design_type reads the active document's Design product
458
+ // (the add-in's _design(), as every design command does) and changes nothing; with no design it fails with the
459
+ // add-in's own error kind NO_ACTIVE_DESIGN (its hints.py). Any other answer leaves activeDesign out: unknown.
460
+ if (result.connected === true && live.tools.some(tool => tool.name === "get_design_type")) {
461
+ let read;
462
+ // A read that didn't finish (timeout, cancel, lost connection): Fusion isn't usable now. request() closes the
463
+ // cut-off session and names what happened, which status reports as its error.
464
+ try {
465
+ read = await this.invoke(live, options, dispatched, "get_design_type", {});
466
+ }
467
+ catch (error) {
468
+ result.connected = false;
469
+ throw error;
470
+ }
471
+ if (!failed(read, "get_design_type"))
472
+ result.activeDesign = true;
473
+ else if (errorKind(read, "get_design_type") === "NO_ACTIVE_DESIGN")
474
+ result.activeDesign = false;
475
+ }
452
476
  });
453
477
  }
454
478
  catch (error) {
package/dist/index.js CHANGED
@@ -52,6 +52,7 @@ import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTP
52
52
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
53
53
  import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
54
54
  import { PrinterRefusal } from "./refusal.js";
55
+ import { uploadProgressReporter } from "./upload-progress.js";
55
56
  import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
56
57
  dotenv.config();
57
58
  const DEFAULT_HOST = process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST || "localhost";
@@ -3222,6 +3223,14 @@ class BambuPrinterMCPServer {
3222
3223
  }))
3223
3224
  .catch(() => { });
3224
3225
  };
3226
+ // counterpart/1: print_3mf reports its FTPS upload as MCP progress (src/upload-progress.ts).
3227
+ const reportUpload = progressToken === undefined
3228
+ ? undefined
3229
+ : uploadProgressReporter(params => {
3230
+ progressNotifications = progressNotifications
3231
+ .then(() => extra.sendNotification({ method: "notifications/progress", params: { progressToken, ...params } }))
3232
+ .catch(() => { });
3233
+ });
3225
3234
  const host = String(args?.host || DEFAULT_HOST);
3226
3235
  const bambuSerial = String(args?.bambu_serial || DEFAULT_BAMBU_SERIAL);
3227
3236
  const bambuToken = String(args?.bambu_token || DEFAULT_BAMBU_TOKEN);
@@ -4195,6 +4204,7 @@ class BambuPrinterMCPServer {
4195
4204
  bedType: printBedType,
4196
4205
  ...callerPrintOptions(args),
4197
4206
  timelapse: args?.timelapse !== undefined ? Boolean(args.timelapse) : undefined,
4207
+ onUploadProgress: reportUpload,
4198
4208
  });
4199
4209
  // Report what the printer did, not merely that a command was published.
4200
4210
  break;
@@ -4229,6 +4239,7 @@ class BambuPrinterMCPServer {
4229
4239
  bedType: printBedType,
4230
4240
  ...callerPrintOptions(args),
4231
4241
  timelapse: args?.timelapse !== undefined ? Boolean(args.timelapse) : false,
4242
+ onUploadProgress: reportUpload,
4232
4243
  });
4233
4244
  result = {
4234
4245
  ...result,
@@ -3,6 +3,8 @@ import { inspectPrintFile, type PrintFileInspection } from "../safety/print-file
3
3
  import { type PrinterStateRequirements } from "../safety/printer-state.js";
4
4
  export declare function assertDirectPrintSupported(model: string | undefined, serial?: string): void;
5
5
  interface BambuPrintOptionsInternal {
6
+ /** Bytes sent to the printer so far over FTPS, and the file's size (LAN route). */
7
+ onUploadProgress?: (sent: number, total: number) => void;
6
8
  projectName: string;
7
9
  filePath: string;
8
10
  bambuModel?: string;
@@ -1089,7 +1089,7 @@ export class BambuImplementation {
1089
1089
  this.assertPrintPreflight(confirmedStatus, preflight);
1090
1090
  assertActive();
1091
1091
  try {
1092
- await this.ftpUpload(host, token, options.filePath, remoteUploadPath);
1092
+ await this.ftpUpload(host, token, options.filePath, remoteUploadPath, options.onUploadProgress);
1093
1093
  }
1094
1094
  catch (error) {
1095
1095
  // Nothing has been sent to the printer but (part of) a file, so the print certainly did not start.
@@ -2248,7 +2248,7 @@ export class BambuImplementation {
2248
2248
  * into the target directory, then uploadFrom uses the full relative path
2249
2249
  * again, resulting in e.g. /cache/cache/file.3mf).
2250
2250
  */
2251
- async ftpUpload(host, token, localPath, remotePath) {
2251
+ async ftpUpload(host, token, localPath, remotePath, onProgress) {
2252
2252
  const client = new FTPClient(15000);
2253
2253
  try {
2254
2254
  await client.access({
@@ -2273,7 +2273,7 @@ export class BambuImplementation {
2273
2273
  }
2274
2274
  const fileData = await fs.readFile(localPath);
2275
2275
  // Small writes, so a multi-megabyte job on a slow SD card is not mistaken for a stall.
2276
- await uploadBytes(client, fileData, absoluteRemote);
2276
+ await uploadBytes(client, fileData, absoluteRemote, { onProgress });
2277
2277
  }
2278
2278
  finally {
2279
2279
  client.close();
@@ -2,16 +2,27 @@ import type { Client as FTPClient } from "basic-ftp";
2
2
  /** Bytes per write on the FTPS data socket; matches fs.createReadStream's default. */
3
3
  export declare const FTP_UPLOAD_CHUNK_BYTES: number;
4
4
  /**
5
- * Store bytes on the printer in small writes.
5
+ * How long a print upload may wait for the printer to take more data before it is
6
+ * reported as stalled. A P1S writing a large file to its SD card pauses mid-file
7
+ * for longer than the 15 s used for FTP commands: an 18.4 MB plate stopped at
8
+ * 13.3 MB for over 15 s (2026-11-06), while 4.6 and 11.5 MB files went through
9
+ * at 130-160 KiB/s. A printer that has really stopped is still reported, after this.
10
+ */
11
+ export declare const FTP_UPLOAD_STALL_MS = 120000;
12
+ /**
13
+ * Store bytes on the printer in small writes, allowing the printer's SD card to pause.
6
14
  *
7
15
  * basic-ftp's TransferWatchdog reports a stall ("Timeout (data socket)") when
8
16
  * the data socket's bytesWritten stops changing while data is still queued.
9
17
  * Readable.from(buffer) hands the whole file over as one write, which counts in
10
- * bytesWritten at once; while the printer drains it at SD-card speed (a few
11
- * hundred KB/s on a P1S) the count never moves, so a multi-megabyte job is
12
- * declared stalled after the timeout although its bytes are still flowing.
13
- * Small writes move the count as each one completes, so the watchdog only fires
14
- * when the printer stops taking data. The bytes are the ones already read and
15
- * inspected; nothing is re-read from disk.
18
+ * bytesWritten at once, so small writes are used: the count moves as each one
19
+ * completes. The watchdog's limit is the client's timeout, read when the transfer
20
+ * starts; it is raised to stallMs for this transfer (and the wait for the
21
+ * printer's 226 after it) and restored afterwards, so other commands keep theirs.
22
+ * The bytes are the ones already read and inspected; nothing is re-read from disk.
16
23
  */
17
- export declare function uploadBytes(client: FTPClient, bytes: Buffer, remotePath: string, chunkBytes?: number): Promise<void>;
24
+ export declare function uploadBytes(client: FTPClient, bytes: Buffer, remotePath: string, { chunkBytes, stallMs, onProgress }?: {
25
+ chunkBytes?: number;
26
+ stallMs?: number;
27
+ onProgress?: (sent: number, total: number) => void;
28
+ }): Promise<void>;
@@ -6,18 +6,44 @@ function* chunks(bytes, size) {
6
6
  yield bytes.subarray(offset, offset + size);
7
7
  }
8
8
  /**
9
- * Store bytes on the printer in small writes.
9
+ * How long a print upload may wait for the printer to take more data before it is
10
+ * reported as stalled. A P1S writing a large file to its SD card pauses mid-file
11
+ * for longer than the 15 s used for FTP commands: an 18.4 MB plate stopped at
12
+ * 13.3 MB for over 15 s (2026-11-06), while 4.6 and 11.5 MB files went through
13
+ * at 130-160 KiB/s. A printer that has really stopped is still reported, after this.
14
+ */
15
+ export const FTP_UPLOAD_STALL_MS = 120000;
16
+ /**
17
+ * Store bytes on the printer in small writes, allowing the printer's SD card to pause.
10
18
  *
11
19
  * basic-ftp's TransferWatchdog reports a stall ("Timeout (data socket)") when
12
20
  * the data socket's bytesWritten stops changing while data is still queued.
13
21
  * Readable.from(buffer) hands the whole file over as one write, which counts in
14
- * bytesWritten at once; while the printer drains it at SD-card speed (a few
15
- * hundred KB/s on a P1S) the count never moves, so a multi-megabyte job is
16
- * declared stalled after the timeout although its bytes are still flowing.
17
- * Small writes move the count as each one completes, so the watchdog only fires
18
- * when the printer stops taking data. The bytes are the ones already read and
19
- * inspected; nothing is re-read from disk.
22
+ * bytesWritten at once, so small writes are used: the count moves as each one
23
+ * completes. The watchdog's limit is the client's timeout, read when the transfer
24
+ * starts; it is raised to stallMs for this transfer (and the wait for the
25
+ * printer's 226 after it) and restored afterwards, so other commands keep theirs.
26
+ * The bytes are the ones already read and inspected; nothing is re-read from disk.
20
27
  */
21
- export async function uploadBytes(client, bytes, remotePath, chunkBytes = FTP_UPLOAD_CHUNK_BYTES) {
22
- await client.uploadFrom(Readable.from(chunks(bytes, chunkBytes)), remotePath);
28
+ export async function uploadBytes(client, bytes, remotePath, { chunkBytes = FTP_UPLOAD_CHUNK_BYTES, stallMs = FTP_UPLOAD_STALL_MS, onProgress } = {}) {
29
+ // Typed readonly, but a plain property that basic-ftp 6.x reads when each transfer starts
30
+ // (TransferResolver.onDataStart/onDataDone); tests/ftp-upload-chunks.test.mjs fails if that changes.
31
+ const context = client.ftp;
32
+ const commandTimeout = context.timeout;
33
+ context.timeout = Math.max(commandTimeout, stallMs);
34
+ // Bytes the data connection has sent so far, reported to the caller (MCP progress, counterpart/1).
35
+ if (onProgress) {
36
+ onProgress(0, bytes.length);
37
+ client.trackProgress(info => { if (info.type === "upload")
38
+ onProgress(Math.min(info.bytes, bytes.length), bytes.length); });
39
+ }
40
+ try {
41
+ await client.uploadFrom(Readable.from(chunks(bytes, chunkBytes)), remotePath);
42
+ onProgress?.(bytes.length, bytes.length);
43
+ }
44
+ finally {
45
+ context.timeout = commandTimeout;
46
+ if (onProgress)
47
+ client.trackProgress();
48
+ }
23
49
  }
@@ -0,0 +1,15 @@
1
+ /** counterpart/1: the `_meta` key and value that mark a print_3mf progress notification as the file upload. */
2
+ export declare const UPLOAD_STAGE_META: {
3
+ readonly "counterpart/stage": "upload";
4
+ };
5
+ export interface UploadProgressParams {
6
+ progress: number;
7
+ total: number;
8
+ message: string;
9
+ _meta: typeof UPLOAD_STAGE_META;
10
+ }
11
+ /**
12
+ * Turns bytes sent over FTPS into MCP progress params: progress = bytes sent, total = file bytes,
13
+ * marked as the upload stage, at most once per whole percent so a slow upload doesn't flood the client.
14
+ */
15
+ export declare function uploadProgressReporter(send: (params: UploadProgressParams) => void): (sent: number, total: number) => void;
@@ -0,0 +1,16 @@
1
+ /** counterpart/1: the `_meta` key and value that mark a print_3mf progress notification as the file upload. */
2
+ export const UPLOAD_STAGE_META = { "counterpart/stage": "upload" };
3
+ /**
4
+ * Turns bytes sent over FTPS into MCP progress params: progress = bytes sent, total = file bytes,
5
+ * marked as the upload stage, at most once per whole percent so a slow upload doesn't flood the client.
6
+ */
7
+ export function uploadProgressReporter(send) {
8
+ let last = -1;
9
+ return (sent, total) => {
10
+ const percent = total > 0 ? Math.floor(sent * 100 / total) : 100;
11
+ if (percent === last)
12
+ return;
13
+ last = percent;
14
+ send({ progress: sent, total, message: `Sending to the printer: ${percent}%`, _meta: UPLOAD_STAGE_META });
15
+ };
16
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.75",
3
+ "version": "1.1.77",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
@@ -189,6 +189,11 @@ function failed(result: CallToolResult, name: string): boolean {
189
189
  return result.isError === true || resultText(result).trimStart().startsWith(`**${name}** ERROR`);
190
190
  }
191
191
 
192
+ /** The add-in's error kind from faust's "**tool** ERROR (KIND)" heading (fusion360_mcp/server.py), when it failed with one. */
193
+ function errorKind(result: CallToolResult, name: string): string | undefined {
194
+ return new RegExp(`^\\*\\*${name}\\*\\* ERROR \\(([A-Z_]+)\\)`).exec(resultText(result).trimStart())?.[1];
195
+ }
196
+
192
197
  /** The value of one " key: value" line in faust's text result. */
193
198
  function resultField(result: CallToolResult, key: string): string | undefined {
194
199
  for (const line of resultText(result).split("\n")) {
@@ -242,6 +247,7 @@ export const FUSION_STATUS_OUTPUT_SCHEMA = {
242
247
  connected: { type: "boolean", description: "The Fusion MCP server started and the add-in answered its ping." },
243
248
  addinReachable: { type: "boolean", description: "The Fusion360MCP add-in answered a ping on FUSION_MCP_HOST:FUSION_MCP_PORT (default localhost:9877) within 2 s. Another program on that port, such as Blender's MCP add-on, does not count." },
244
249
  fusionRunning: { type: "boolean" },
250
+ activeDesign: { type: "boolean", description: "When connected: whether Fusion has a design open, from the add-in's read-only get_design_type (false is its NO_ACTIVE_DESIGN). The pinned add-in refuses every design command, fusion_mcp_new_design included, without one (faust issue #12). Absent when unknown." },
245
251
  tools: { type: "array", items: { type: "object", properties: { name: { type: "string" } }, required: ["name"] } },
246
252
  launched: { type: "boolean", description: "This call started Fusion." },
247
253
  transport: { type: "string" },
@@ -449,6 +455,18 @@ export class FusionMcpBridge {
449
455
  const ping = await this.invoke(live, options, dispatched, "ping", {});
450
456
  result.connected = !failed(ping, "ping");
451
457
  }
458
+ // Whether a design is open, from the add-in itself. get_design_type reads the active document's Design product
459
+ // (the add-in's _design(), as every design command does) and changes nothing; with no design it fails with the
460
+ // add-in's own error kind NO_ACTIVE_DESIGN (its hints.py). Any other answer leaves activeDesign out: unknown.
461
+ if (result.connected === true && live.tools.some(tool => tool.name === "get_design_type")) {
462
+ let read: CallToolResult;
463
+ // A read that didn't finish (timeout, cancel, lost connection): Fusion isn't usable now. request() closes the
464
+ // cut-off session and names what happened, which status reports as its error.
465
+ try { read = await this.invoke(live, options, dispatched, "get_design_type", {}); }
466
+ catch (error) { result.connected = false; throw error; }
467
+ if (!failed(read, "get_design_type")) result.activeDesign = true;
468
+ else if (errorKind(read, "get_design_type") === "NO_ACTIVE_DESIGN") result.activeDesign = false;
469
+ }
452
470
  });
453
471
  } catch (error) {
454
472
  result.error = error instanceof Error ? error.message : String(error);
package/src/index.ts CHANGED
@@ -83,6 +83,7 @@ import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTP
83
83
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
84
84
  import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
85
85
  import { PrinterRefusal } from "./refusal.js";
86
+ import { uploadProgressReporter } from "./upload-progress.js";
86
87
  import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
87
88
 
88
89
  dotenv.config();
@@ -3739,6 +3740,15 @@ class BambuPrinterMCPServer {
3739
3740
  .catch(() => {});
3740
3741
  };
3741
3742
 
3743
+ // counterpart/1: print_3mf reports its FTPS upload as MCP progress (src/upload-progress.ts).
3744
+ const reportUpload = progressToken === undefined
3745
+ ? undefined
3746
+ : uploadProgressReporter(params => {
3747
+ progressNotifications = progressNotifications
3748
+ .then(() => extra.sendNotification({ method: "notifications/progress", params: { progressToken, ...params } }))
3749
+ .catch(() => {});
3750
+ });
3751
+
3742
3752
  const host = String(args?.host || DEFAULT_HOST);
3743
3753
  const bambuSerial = String(args?.bambu_serial || DEFAULT_BAMBU_SERIAL);
3744
3754
  const bambuToken = String(args?.bambu_token || DEFAULT_BAMBU_TOKEN);
@@ -4867,6 +4877,7 @@ class BambuPrinterMCPServer {
4867
4877
  bedType: printBedType,
4868
4878
  ...callerPrintOptions(args),
4869
4879
  timelapse: args?.timelapse !== undefined ? Boolean(args.timelapse) : undefined,
4880
+ onUploadProgress: reportUpload,
4870
4881
  });
4871
4882
  // Report what the printer did, not merely that a command was published.
4872
4883
  break;
@@ -4932,6 +4943,7 @@ class BambuPrinterMCPServer {
4932
4943
  bedType: printBedType,
4933
4944
  ...callerPrintOptions(args),
4934
4945
  timelapse: args?.timelapse !== undefined ? Boolean(args.timelapse) : false,
4946
+ onUploadProgress: reportUpload,
4935
4947
  });
4936
4948
 
4937
4949
  result = {
@@ -172,6 +172,8 @@ function isP2SModelName(model: unknown): boolean {
172
172
  }
173
173
 
174
174
  interface BambuPrintOptionsInternal {
175
+ /** Bytes sent to the printer so far over FTPS, and the file's size (LAN route). */
176
+ onUploadProgress?: (sent: number, total: number) => void;
175
177
  projectName: string;
176
178
  filePath: string;
177
179
  bambuModel?: string;
@@ -1257,7 +1259,7 @@ export class BambuImplementation {
1257
1259
  this.assertPrintPreflight(confirmedStatus, preflight);
1258
1260
  assertActive();
1259
1261
  try {
1260
- await this.ftpUpload(host, token, options.filePath, remoteUploadPath);
1262
+ await this.ftpUpload(host, token, options.filePath, remoteUploadPath, options.onUploadProgress);
1261
1263
  } catch (error) {
1262
1264
  // Nothing has been sent to the printer but (part of) a file, so the print certainly did not start.
1263
1265
  throw new PrinterRefusal("printer-upload-failed", `The print file did not reach the printer (${error instanceof Error ? error.message : String(error)}). No print was started.`);
@@ -2510,7 +2512,8 @@ export class BambuImplementation {
2510
2512
  host: string,
2511
2513
  token: string,
2512
2514
  localPath: string,
2513
- remotePath: string
2515
+ remotePath: string,
2516
+ onProgress?: (sent: number, total: number) => void
2514
2517
  ): Promise<void> {
2515
2518
  const client = new FTPClient(15_000);
2516
2519
  try {
@@ -2536,7 +2539,7 @@ export class BambuImplementation {
2536
2539
  }
2537
2540
  const fileData = await fs.readFile(localPath);
2538
2541
  // Small writes, so a multi-megabyte job on a slow SD card is not mistaken for a stall.
2539
- await uploadBytes(client, fileData, absoluteRemote);
2542
+ await uploadBytes(client, fileData, absoluteRemote, { onProgress });
2540
2543
  } finally {
2541
2544
  client.close();
2542
2545
  }
@@ -9,18 +9,44 @@ function* chunks(bytes: Buffer, size: number): Generator<Buffer> {
9
9
  }
10
10
 
11
11
  /**
12
- * Store bytes on the printer in small writes.
12
+ * How long a print upload may wait for the printer to take more data before it is
13
+ * reported as stalled. A P1S writing a large file to its SD card pauses mid-file
14
+ * for longer than the 15 s used for FTP commands: an 18.4 MB plate stopped at
15
+ * 13.3 MB for over 15 s (2026-11-06), while 4.6 and 11.5 MB files went through
16
+ * at 130-160 KiB/s. A printer that has really stopped is still reported, after this.
17
+ */
18
+ export const FTP_UPLOAD_STALL_MS = 120_000;
19
+
20
+ /**
21
+ * Store bytes on the printer in small writes, allowing the printer's SD card to pause.
13
22
  *
14
23
  * basic-ftp's TransferWatchdog reports a stall ("Timeout (data socket)") when
15
24
  * the data socket's bytesWritten stops changing while data is still queued.
16
25
  * Readable.from(buffer) hands the whole file over as one write, which counts in
17
- * bytesWritten at once; while the printer drains it at SD-card speed (a few
18
- * hundred KB/s on a P1S) the count never moves, so a multi-megabyte job is
19
- * declared stalled after the timeout although its bytes are still flowing.
20
- * Small writes move the count as each one completes, so the watchdog only fires
21
- * when the printer stops taking data. The bytes are the ones already read and
22
- * inspected; nothing is re-read from disk.
26
+ * bytesWritten at once, so small writes are used: the count moves as each one
27
+ * completes. The watchdog's limit is the client's timeout, read when the transfer
28
+ * starts; it is raised to stallMs for this transfer (and the wait for the
29
+ * printer's 226 after it) and restored afterwards, so other commands keep theirs.
30
+ * The bytes are the ones already read and inspected; nothing is re-read from disk.
23
31
  */
24
- export async function uploadBytes(client: FTPClient, bytes: Buffer, remotePath: string, chunkBytes = FTP_UPLOAD_CHUNK_BYTES): Promise<void> {
25
- await client.uploadFrom(Readable.from(chunks(bytes, chunkBytes)), remotePath);
32
+ export async function uploadBytes(client: FTPClient, bytes: Buffer, remotePath: string,
33
+ { chunkBytes = FTP_UPLOAD_CHUNK_BYTES, stallMs = FTP_UPLOAD_STALL_MS, onProgress }:
34
+ { chunkBytes?: number; stallMs?: number; onProgress?: (sent: number, total: number) => void } = {}): Promise<void> {
35
+ // Typed readonly, but a plain property that basic-ftp 6.x reads when each transfer starts
36
+ // (TransferResolver.onDataStart/onDataDone); tests/ftp-upload-chunks.test.mjs fails if that changes.
37
+ const context = client.ftp as { timeout: number };
38
+ const commandTimeout = context.timeout;
39
+ context.timeout = Math.max(commandTimeout, stallMs);
40
+ // Bytes the data connection has sent so far, reported to the caller (MCP progress, counterpart/1).
41
+ if (onProgress) {
42
+ onProgress(0, bytes.length);
43
+ client.trackProgress(info => { if (info.type === "upload") onProgress(Math.min(info.bytes, bytes.length), bytes.length); });
44
+ }
45
+ try {
46
+ await client.uploadFrom(Readable.from(chunks(bytes, chunkBytes)), remotePath);
47
+ onProgress?.(bytes.length, bytes.length);
48
+ } finally {
49
+ context.timeout = commandTimeout;
50
+ if (onProgress) client.trackProgress();
51
+ }
26
52
  }
@@ -0,0 +1,23 @@
1
+ /** counterpart/1: the `_meta` key and value that mark a print_3mf progress notification as the file upload. */
2
+ export const UPLOAD_STAGE_META = { "counterpart/stage": "upload" } as const;
3
+
4
+ export interface UploadProgressParams {
5
+ progress: number;
6
+ total: number;
7
+ message: string;
8
+ _meta: typeof UPLOAD_STAGE_META;
9
+ }
10
+
11
+ /**
12
+ * Turns bytes sent over FTPS into MCP progress params: progress = bytes sent, total = file bytes,
13
+ * marked as the upload stage, at most once per whole percent so a slow upload doesn't flood the client.
14
+ */
15
+ export function uploadProgressReporter(send: (params: UploadProgressParams) => void): (sent: number, total: number) => void {
16
+ let last = -1;
17
+ return (sent, total) => {
18
+ const percent = total > 0 ? Math.floor(sent * 100 / total) : 100;
19
+ if (percent === last) return;
20
+ last = percent;
21
+ send({ progress: sent, total, message: `Sending to the printer: ${percent}%`, _meta: UPLOAD_STAGE_META });
22
+ };
23
+ }