bambu-printer-mcp 1.1.69 → 1.1.70

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/dist/index.js CHANGED
@@ -4016,6 +4016,8 @@ class BambuPrinterMCPServer {
4016
4016
  console.warn("Could not resolve live printer filaments for slicing:", filamentError);
4017
4017
  }
4018
4018
  }
4019
+ // A client that cancels this call (it no longer wants the slice) stops the slicer.
4020
+ sliceBambuOptions.signal = extra.signal;
4019
4021
  const sliced = await this.stlManipulator.sliceSTLWithResult(String(args.stl_path), slicerType, slicerPath, activeSlicerProfile, undefined, // progressCallback
4020
4022
  printerPreset, sliceBambuOptions);
4021
4023
  await progressNotifications;
@@ -630,7 +630,11 @@ async function writeTemp(tempDir, kind, leafName, data) {
630
630
  const safe = leafName.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 64);
631
631
  const filename = `flat-${kind}-${safe}-${hash}.json`;
632
632
  const out = path.join(tempDir, filename);
633
- await fs.writeFile(out, serialized, "utf8");
633
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
634
+ // rename it into place, so a reader never sees it truncated or half-written.
635
+ const partial = `${out}.${crypto.randomUUID()}.partial`;
636
+ await fs.writeFile(partial, serialized, "utf8");
637
+ await fs.rename(partial, out);
634
638
  return out;
635
639
  }
636
640
  /* -------------------------------------------------------------------------- */
@@ -10,6 +10,8 @@ const SUPPORTED_OPTIONS = new Set([
10
10
  'nozzleType', 'nozzleVolumeType', 'slicePlate',
11
11
  // Written into the uploaded process preset before the request, not sent as API options.
12
12
  'processOverrides',
13
+ // The request's cancellation, honoured through isCancelled; never sent.
14
+ 'signal',
13
15
  ]);
14
16
  function configuration() {
15
17
  let url;
@@ -28,6 +28,8 @@ export type SlicerType = typeof SLICER_TYPES[number];
28
28
  export declare function normalizeSlicerType(rawSlicerType: string): SlicerType;
29
29
  export declare function isBambuCompatibleSlicer(slicerType: SlicerType): boolean;
30
30
  export interface BambuSliceOptions {
31
+ /** The request's own cancellation: aborting it stops the slicer (the MCP client cancelled the call). */
32
+ signal?: AbortSignal;
31
33
  uptodate?: boolean;
32
34
  repetitions?: number;
33
35
  orient?: boolean;
@@ -82,6 +84,11 @@ export declare class STLManipulator extends EventEmitter {
82
84
  * Generate a unique operation ID
83
85
  */
84
86
  private generateOperationId;
87
+ /**
88
+ * A new folder for one slice's outputs, under TEMP_DIR/slices. A sliced file's path stays valid for a day after
89
+ * its slice (callers print from it); older slice folders are removed as new slices start.
90
+ */
91
+ private newSliceFolder;
85
92
  private getAvailableProfileRoots;
86
93
  private findProfileFile;
87
94
  private buildFilamentIdIndex;
@@ -17,6 +17,8 @@ import { applyProcessOverrides } from '../slicer/process-overrides.js';
17
17
  import { profileJsonFiles } from '../slicer/profile-files.js';
18
18
  import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
19
19
  import { sliceWithOrcaApi, validateRemoteSliceOptions } from '../slicer/remote-slicer.js';
20
+ /** How long a slice's folder (its sliced file and result.json) is kept: a day, then a later slice removes it. */
21
+ const SLICE_FOLDER_LIFETIME_MS = 24 * 60 * 60 * 1000;
20
22
  const readFileAsync = promisify(fs.readFile);
21
23
  const writeFileAsync = promisify(fs.writeFile);
22
24
  const BAMBU_PROFILE_ROOTS = [
@@ -219,6 +221,24 @@ export class STLManipulator extends EventEmitter {
219
221
  generateOperationId() {
220
222
  return crypto.randomUUID();
221
223
  }
224
+ /**
225
+ * A new folder for one slice's outputs, under TEMP_DIR/slices. A sliced file's path stays valid for a day after
226
+ * its slice (callers print from it); older slice folders are removed as new slices start.
227
+ */
228
+ async newSliceFolder(operationId) {
229
+ const root = path.join(this.tempDir, 'slices');
230
+ await fs.promises.mkdir(root, { recursive: true });
231
+ const cutoff = Date.now() - SLICE_FOLDER_LIFETIME_MS;
232
+ for (const name of await fs.promises.readdir(root).catch(() => [])) {
233
+ const folder = path.join(root, name);
234
+ const info = await fs.promises.stat(folder).catch(() => undefined);
235
+ if (info?.isDirectory() && info.mtimeMs < cutoff)
236
+ await fs.promises.rm(folder, { recursive: true, force: true }).catch(() => undefined);
237
+ }
238
+ const folder = path.join(root, operationId);
239
+ await fs.promises.mkdir(folder);
240
+ return folder;
241
+ }
222
242
  getAvailableProfileRoots() {
223
243
  const selectedRoot = process.env.BAMBU_PROFILES_ROOT;
224
244
  return [
@@ -307,7 +327,11 @@ export class STLManipulator extends EventEmitter {
307
327
  const serialized = JSON.stringify(value, null, 2);
308
328
  const hash = crypto.createHash('sha256').update(serialized).digest('hex').slice(0, 16);
309
329
  const outPath = path.join(this.tempDir, `${outputBase}_${suffix}_${hash}.json`);
310
- fs.writeFileSync(outPath, serialized);
330
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
331
+ // rename it into place, so a reader never sees it truncated or half-written.
332
+ const partial = `${outPath}.${crypto.randomUUID()}.partial`;
333
+ fs.writeFileSync(partial, serialized);
334
+ fs.renameSync(partial, outPath);
311
335
  return outPath;
312
336
  }
313
337
  async resolveBambuLikeSettingsBundle(outputBase, slicerType, slicerProfile, printerPreset, bambuOptions, activeProfilesRoot, preserveOrcaExtrusionMode = false) {
@@ -1398,6 +1422,14 @@ export class STLManipulator extends EventEmitter {
1398
1422
  async sliceSTLOnce(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1399
1423
  const operationId = this.generateOperationId();
1400
1424
  this.activeOperations.set(operationId, true);
1425
+ // A cancelled request stops its slice: the slicer is killed (below) instead of finishing a slice nobody reads.
1426
+ const signal = bambuOptions?.signal;
1427
+ const cancel = () => { if (this.activeOperations.has(operationId))
1428
+ this.activeOperations.set(operationId, false); };
1429
+ if (signal?.aborted) {
1430
+ this.activeOperations.delete(operationId);
1431
+ throw new Error("Slicing operation cancelled");
1432
+ }
1401
1433
  if (slicerType !== 'orca-slicer-api' && isPathLikeExecutable(slicerPath) && !fs.existsSync(slicerPath)) {
1402
1434
  throw new Error(`Slicer executable not found at: ${slicerPath}`);
1403
1435
  }
@@ -1414,7 +1446,10 @@ export class STLManipulator extends EventEmitter {
1414
1446
  let cliResult;
1415
1447
  const orcaTemporaryDirectories = [];
1416
1448
  const temporaryFiles = [];
1449
+ // This slice's own folder (local Bambu-compatible CLI): removed if the slice fails or is cancelled.
1450
+ let sliceDir;
1417
1451
  try {
1452
+ signal?.addEventListener('abort', cancel, { once: true });
1418
1453
  if (progressCallback)
1419
1454
  progressCallback(0, `Starting slicing with ${slicerType}...`);
1420
1455
  switch (slicerType) {
@@ -1463,7 +1498,13 @@ export class STLManipulator extends EventEmitter {
1463
1498
  throw new Error('Remote slicing process profile does not exist.');
1464
1499
  }
1465
1500
  const profileSlicerType = remote ? 'orcaslicer' : slicerType;
1466
- const bambuOutputPath = path.join(this.tempDir, outputBase + (remote ? `_${operationId}` : '') + '_sliced.3mf');
1501
+ // Every local slice writes into a folder of its own, so two slices at once, even of same-named inputs, never
1502
+ // read, replace or delete each other's files. Bambu Studio's CLI (v02.08.02.61) writes fixed names into
1503
+ // --outputdir: result.json, each plate's G-code as plate_<n>.gcode (and its .tmp) before packing it into
1504
+ // the 3MF, and the exported 3MF's .tmp; its own scratch files under the system temp dir are per process.
1505
+ const bambuOutputPath = remote
1506
+ ? path.join(this.tempDir, `${outputBase}_${operationId}_sliced.3mf`)
1507
+ : path.join(sliceDir = await this.newSliceFolder(operationId), `${outputBase}_sliced.3mf`);
1467
1508
  const outputDir = path.dirname(bambuOutputPath);
1468
1509
  const selectedProfilesRoot = detectProfilesRoot(remote ? undefined : slicerPath, profileSlicerType);
1469
1510
  const profilesRoot = !remote && profileSlicerType === 'orcaslicer'
@@ -1704,6 +1745,9 @@ export class STLManipulator extends EventEmitter {
1704
1745
  }
1705
1746
  catch (error) {
1706
1747
  console.error(`Slicing failed for ${stlFilePath}:`, error);
1748
+ // Nothing in a failed or cancelled slice's folder is handed back (its result.json is already in the error).
1749
+ if (sliceDir)
1750
+ await fs.promises.rm(sliceDir, { recursive: true, force: true }).catch(() => undefined);
1707
1751
  this.emit('operationError', {
1708
1752
  operationId,
1709
1753
  type: 'slice',
@@ -1712,6 +1756,7 @@ export class STLManipulator extends EventEmitter {
1712
1756
  throw error;
1713
1757
  }
1714
1758
  finally {
1759
+ signal?.removeEventListener('abort', cancel);
1715
1760
  this.activeOperations.delete(operationId);
1716
1761
  for (const file of temporaryFiles) {
1717
1762
  await fs.promises.rm(file, { force: true }).catch(error => console.error('Could not remove a temporary mesh:', error));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.69",
3
+ "version": "1.1.70",
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": {
package/src/index.ts CHANGED
@@ -4644,6 +4644,8 @@ class BambuPrinterMCPServer {
4644
4644
  }
4645
4645
  }
4646
4646
 
4647
+ // A client that cancels this call (it no longer wants the slice) stops the slicer.
4648
+ sliceBambuOptions.signal = extra.signal;
4647
4649
  const sliced = await this.stlManipulator.sliceSTLWithResult(
4648
4650
  String(args.stl_path), slicerType, slicerPath,
4649
4651
  activeSlicerProfile,
@@ -793,7 +793,11 @@ async function writeTemp(
793
793
  const safe = leafName.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 64);
794
794
  const filename = `flat-${kind}-${safe}-${hash}.json`;
795
795
  const out = path.join(tempDir, filename);
796
- await fs.writeFile(out, serialized, "utf8");
796
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
797
+ // rename it into place, so a reader never sees it truncated or half-written.
798
+ const partial = `${out}.${crypto.randomUUID()}.partial`;
799
+ await fs.writeFile(partial, serialized, "utf8");
800
+ await fs.rename(partial, out);
797
801
  return out;
798
802
  }
799
803
 
@@ -12,6 +12,8 @@ const SUPPORTED_OPTIONS = new Set([
12
12
  'nozzleType', 'nozzleVolumeType', 'slicePlate',
13
13
  // Written into the uploaded process preset before the request, not sent as API options.
14
14
  'processOverrides',
15
+ // The request's cancellation, honoured through isCancelled; never sent.
16
+ 'signal',
15
17
  ]);
16
18
 
17
19
  function configuration(): { base: string; headers: Record<string, string>; mode: string; timeout: number } {
@@ -18,6 +18,8 @@ import { profileJsonFiles } from '../slicer/profile-files.js';
18
18
  import { materializeOrcaProfilesRoot, stageOrcaCliProfiles } from '../slicer/orca-profile-cache.js';
19
19
  import { sliceWithOrcaApi, validateRemoteSliceOptions } from '../slicer/remote-slicer.js';
20
20
 
21
+ /** How long a slice's folder (its sliced file and result.json) is kept: a day, then a later slice removes it. */
22
+ const SLICE_FOLDER_LIFETIME_MS = 24 * 60 * 60 * 1000;
21
23
  const readFileAsync = promisify(fs.readFile);
22
24
  const writeFileAsync = promisify(fs.writeFile);
23
25
  const BAMBU_PROFILE_ROOTS = [
@@ -164,6 +166,8 @@ function configuredBambuProfileDirs(): string[] {
164
166
 
165
167
  // Bambu-compatible slicer CLI flags exposed via the slice_stl tool
166
168
  export interface BambuSliceOptions {
169
+ /** The request's own cancellation: aborting it stops the slicer (the MCP client cancelled the call). */
170
+ signal?: AbortSignal;
167
171
  uptodate?: boolean; // --uptodate: update 3MF configs to latest presets
168
172
  repetitions?: number; // STL: --clone-objects N; 3MF: --repetitions N on the selected plate
169
173
  orient?: boolean; // --orient 1: auto-orient for printability
@@ -342,6 +346,24 @@ export class STLManipulator extends EventEmitter {
342
346
  return crypto.randomUUID();
343
347
  }
344
348
 
349
+ /**
350
+ * A new folder for one slice's outputs, under TEMP_DIR/slices. A sliced file's path stays valid for a day after
351
+ * its slice (callers print from it); older slice folders are removed as new slices start.
352
+ */
353
+ private async newSliceFolder(operationId: string): Promise<string> {
354
+ const root = path.join(this.tempDir, 'slices');
355
+ await fs.promises.mkdir(root, { recursive: true });
356
+ const cutoff = Date.now() - SLICE_FOLDER_LIFETIME_MS;
357
+ for (const name of await fs.promises.readdir(root).catch(() => [] as string[])) {
358
+ const folder = path.join(root, name);
359
+ const info = await fs.promises.stat(folder).catch(() => undefined);
360
+ if (info?.isDirectory() && info.mtimeMs < cutoff) await fs.promises.rm(folder, { recursive: true, force: true }).catch(() => undefined);
361
+ }
362
+ const folder = path.join(root, operationId);
363
+ await fs.promises.mkdir(folder);
364
+ return folder;
365
+ }
366
+
345
367
  private getAvailableProfileRoots(): string[] {
346
368
  const selectedRoot = process.env.BAMBU_PROFILES_ROOT;
347
369
  return [
@@ -456,7 +478,11 @@ export class STLManipulator extends EventEmitter {
456
478
  const serialized = JSON.stringify(value, null, 2);
457
479
  const hash = crypto.createHash('sha256').update(serialized).digest('hex').slice(0, 16);
458
480
  const outPath = path.join(this.tempDir, `${outputBase}_${suffix}_${hash}.json`);
459
- fs.writeFileSync(outPath, serialized);
481
+ // A slice running now may be reading this very file (it is named by its content): write it whole elsewhere and
482
+ // rename it into place, so a reader never sees it truncated or half-written.
483
+ const partial = `${outPath}.${crypto.randomUUID()}.partial`;
484
+ fs.writeFileSync(partial, serialized);
485
+ fs.renameSync(partial, outPath);
460
486
  return outPath;
461
487
  }
462
488
 
@@ -1806,6 +1832,13 @@ export class STLManipulator extends EventEmitter {
1806
1832
  ): Promise<SliceOutput> {
1807
1833
  const operationId = this.generateOperationId();
1808
1834
  this.activeOperations.set(operationId, true);
1835
+ // A cancelled request stops its slice: the slicer is killed (below) instead of finishing a slice nobody reads.
1836
+ const signal = bambuOptions?.signal;
1837
+ const cancel = () => { if (this.activeOperations.has(operationId)) this.activeOperations.set(operationId, false); };
1838
+ if (signal?.aborted) {
1839
+ this.activeOperations.delete(operationId);
1840
+ throw new Error("Slicing operation cancelled");
1841
+ }
1809
1842
 
1810
1843
  if (slicerType !== 'orca-slicer-api' && isPathLikeExecutable(slicerPath) && !fs.existsSync(slicerPath)) {
1811
1844
  throw new Error(`Slicer executable not found at: ${slicerPath}`);
@@ -1826,8 +1859,11 @@ export class STLManipulator extends EventEmitter {
1826
1859
  let cliResult: CliResultSource | undefined;
1827
1860
  const orcaTemporaryDirectories: string[] = [];
1828
1861
  const temporaryFiles: string[] = [];
1862
+ // This slice's own folder (local Bambu-compatible CLI): removed if the slice fails or is cancelled.
1863
+ let sliceDir: string | undefined;
1829
1864
 
1830
1865
  try {
1866
+ signal?.addEventListener('abort', cancel, { once: true });
1831
1867
  if (progressCallback) progressCallback(0, `Starting slicing with ${slicerType}...`);
1832
1868
 
1833
1869
  switch (slicerType) {
@@ -1876,7 +1912,13 @@ export class STLManipulator extends EventEmitter {
1876
1912
  if (slicerProfile && !fs.existsSync(slicerProfile)) throw new Error('Remote slicing process profile does not exist.');
1877
1913
  }
1878
1914
  const profileSlicerType = remote ? 'orcaslicer' : slicerType;
1879
- const bambuOutputPath = path.join(this.tempDir, outputBase + (remote ? `_${operationId}` : '') + '_sliced.3mf');
1915
+ // Every local slice writes into a folder of its own, so two slices at once, even of same-named inputs, never
1916
+ // read, replace or delete each other's files. Bambu Studio's CLI (v02.08.02.61) writes fixed names into
1917
+ // --outputdir: result.json, each plate's G-code as plate_<n>.gcode (and its .tmp) before packing it into
1918
+ // the 3MF, and the exported 3MF's .tmp; its own scratch files under the system temp dir are per process.
1919
+ const bambuOutputPath = remote
1920
+ ? path.join(this.tempDir, `${outputBase}_${operationId}_sliced.3mf`)
1921
+ : path.join(sliceDir = await this.newSliceFolder(operationId), `${outputBase}_sliced.3mf`);
1880
1922
  const outputDir = path.dirname(bambuOutputPath);
1881
1923
  const selectedProfilesRoot = detectProfilesRoot(remote ? undefined : slicerPath, profileSlicerType);
1882
1924
  const profilesRoot = !remote && profileSlicerType === 'orcaslicer'
@@ -2118,6 +2160,8 @@ export class STLManipulator extends EventEmitter {
2118
2160
  return slicerResult ? { path: outputFilePath, slicer_result: slicerResult } : { path: outputFilePath };
2119
2161
  } catch (error) {
2120
2162
  console.error(`Slicing failed for ${stlFilePath}:`, error);
2163
+ // Nothing in a failed or cancelled slice's folder is handed back (its result.json is already in the error).
2164
+ if (sliceDir) await fs.promises.rm(sliceDir, { recursive: true, force: true }).catch(() => undefined);
2121
2165
  this.emit('operationError', {
2122
2166
  operationId,
2123
2167
  type: 'slice',
@@ -2125,6 +2169,7 @@ export class STLManipulator extends EventEmitter {
2125
2169
  });
2126
2170
  throw error;
2127
2171
  } finally {
2172
+ signal?.removeEventListener('abort', cancel);
2128
2173
  this.activeOperations.delete(operationId);
2129
2174
  for (const file of temporaryFiles) {
2130
2175
  await fs.promises.rm(file, { force: true }).catch(error => console.error('Could not remove a temporary mesh:', error));