bambu-printer-mcp 1.1.64 → 1.1.66

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
@@ -1139,7 +1139,7 @@ Inspect the slicer settings embedded in a saved 3MF template or in an extracted
1139
1139
  }
1140
1140
  ```
1141
1141
 
1142
- This returns a compact summary of the high-signal settings such as printer preset, default print profile, filament profiles, layer height, infill density, shell counts, support mode, and bed type. It accepts either `source_path` or `template_name`. For 3MF inputs it also writes the extracted settings blob to a temp path so the result can be reused directly, and returns `own_process`: true when the 3MF carries its own process (a designer's project), so `slice_stl` and `print_3mf`'s auto-slice slice it with that process unless the call names `slicer_profile`, `template_name` or `template_3mf_path`.
1142
+ This returns a compact summary of the high-signal settings such as printer preset, default print profile, filament profiles, layer height, infill density, shell counts, support mode, and bed type. It accepts either `source_path` or `template_name`. For 3MF inputs it also writes the extracted settings blob to a temp path so the result can be reused directly, and returns `own_process`. With `source_path`, pass the slice's other arguments too (`slicer_profile`, `template_name`, `template_3mf_path`, `layer_height`, `wall_loops`, `sparse_infill_density`, `quality`, `strength`). `own_process` is then true when that `slice_stl` call prints the process the 3MF carries (a designer's project) unchanged. A 3MF with no slicer settings returns `raw_key_count` 0 and no extracted path; a file that can't be read is an error.
1143
1143
 
1144
1144
  #### slice_with_template
1145
1145
 
@@ -1,9 +1,20 @@
1
1
  import { ThreeMFData, CollarCharmAnalysis, ThreeMFAmsRequirements, ThreeMFPlateObjects } from './types.js';
2
+ /** Whether a 3MF carries a slicer settings file at all (readable or not). */
3
+ export declare function hasSlicerSettingsFile(filePath: string): Promise<boolean>;
2
4
  export { ThreeMFData };
3
5
  export declare function parse3MF(filePath: string): Promise<ThreeMFData>;
4
6
  /** Whether a 3MF carries its own Bambu Studio/Orca process (a designer's project, not a bare mesh archive). */
5
7
  export declare function hasBambuProjectSettings(filePath: string): Promise<boolean>;
6
- export declare function extractBambuTemplateSettings(filePath: string, outputDir: string): Promise<string>;
8
+ /** Runs one operation; the directory of every settings file extracted during it is removed when it settles. */
9
+ export declare function withExtractedSettingsCleanup<T>(operation: () => Promise<T>): Promise<T>;
10
+ /**
11
+ * Writes a 3MF's slicer settings to a file of their own and returns its path. Each extraction gets its own directory,
12
+ * removed when the surrounding withExtractedSettingsCleanup operation settles. `keep` is for a path handed back to the
13
+ * caller: it is named by content, so repeat calls reuse one file, and written whole before it is renamed into place.
14
+ */
15
+ export declare function extractBambuTemplateSettings(filePath: string, outputDir: string, options?: {
16
+ keep?: boolean;
17
+ }): Promise<string>;
7
18
  export declare function analyzeCollarCharm3MF(filePath: string, plateIndex?: number): Promise<CollarCharmAnalysis>;
8
19
  export declare function getCollarCharmRolePolicy(): {
9
20
  colors: {
@@ -1,7 +1,9 @@
1
1
  import JSZip from 'jszip';
2
2
  import { parseStringPromise } from 'xml2js';
3
3
  import * as fs from 'fs/promises';
4
- import { createHash } from 'crypto';
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import * as path from 'node:path';
5
7
  // Parses Bambu Studio's JSON config data
6
8
  function parseBambuJSONConfig(jsonData) {
7
9
  const config = {};
@@ -76,14 +78,21 @@ function parseBambuJSONConfig(jsonData) {
76
78
  }
77
79
  return config;
78
80
  }
81
+ /** The files a 3MF's slicer settings are read from, first found wins. */
82
+ const SLICER_SETTINGS_FILES = [
83
+ 'Metadata/project_settings.config',
84
+ 'Metadata/Slic3r_PE.config',
85
+ 'Metadata/model_settings.config',
86
+ 'Metadata/slice_info.config'
87
+ ];
88
+ /** Whether a 3MF carries a slicer settings file at all (readable or not). */
89
+ export async function hasSlicerSettingsFile(filePath) {
90
+ const zip = await JSZip.loadAsync(await fs.readFile(filePath));
91
+ return SLICER_SETTINGS_FILES.some(name => zip.file(name));
92
+ }
79
93
  async function parseBambuConfig(zip) {
80
94
  // Look for common Bambu config file names
81
- const potentialFiles = [
82
- 'Metadata/project_settings.config',
83
- 'Metadata/Slic3r_PE.config',
84
- 'Metadata/model_settings.config',
85
- 'Metadata/slice_info.config'
86
- ];
95
+ const potentialFiles = SLICER_SETTINGS_FILES;
87
96
  let configFile = null;
88
97
  let configContent = '';
89
98
  for (const name of potentialFiles) {
@@ -234,23 +243,44 @@ export async function hasBambuProjectSettings(filePath) {
234
243
  return false;
235
244
  }
236
245
  }
237
- export async function extractBambuTemplateSettings(filePath, outputDir) {
246
+ const extractionScope = new AsyncLocalStorage();
247
+ /** Runs one operation; the directory of every settings file extracted during it is removed when it settles. */
248
+ export async function withExtractedSettingsCleanup(operation) {
249
+ const dirs = [];
250
+ try {
251
+ return await extractionScope.run(dirs, operation);
252
+ }
253
+ finally {
254
+ await Promise.all(dirs.map(dir => fs.rm(dir, { recursive: true, force: true }).catch(() => undefined)));
255
+ }
256
+ }
257
+ /**
258
+ * Writes a 3MF's slicer settings to a file of their own and returns its path. Each extraction gets its own directory,
259
+ * removed when the surrounding withExtractedSettingsCleanup operation settles. `keep` is for a path handed back to the
260
+ * caller: it is named by content, so repeat calls reuse one file, and written whole before it is renamed into place.
261
+ */
262
+ export async function extractBambuTemplateSettings(filePath, outputDir, options = {}) {
238
263
  const data = await fs.readFile(filePath);
239
264
  const zip = await JSZip.loadAsync(data);
240
- const potentialFiles = [
241
- 'Metadata/project_settings.config',
242
- 'Metadata/Slic3r_PE.config',
243
- 'Metadata/model_settings.config',
244
- 'Metadata/slice_info.config'
245
- ];
265
+ const potentialFiles = SLICER_SETTINGS_FILES;
246
266
  for (const name of potentialFiles) {
247
267
  const file = zip.file(name);
248
268
  if (!file)
249
269
  continue;
250
270
  const content = await file.async('string');
251
- // Named by content, so two projects sliced at once never share (or overwrite) one settings file.
252
- const digest = createHash('sha256').update(content).digest('hex').slice(0, 16);
253
- const outputPath = `${outputDir}/${digest}_${name.replace(/\//g, '_')}`;
271
+ if (options.keep) {
272
+ const digest = createHash('sha256').update(content).digest('hex').slice(0, 16);
273
+ const outputPath = path.join(outputDir, `${digest}_${name.replace(/\//g, '_')}`);
274
+ const partial = `${outputPath}.${randomUUID()}.partial`;
275
+ await fs.writeFile(partial, content, 'utf8');
276
+ await fs.rename(partial, outputPath);
277
+ return outputPath;
278
+ }
279
+ // Its own directory for every extraction, so two slices at once (of different projects or the same one)
280
+ // never share, overwrite or half-read one settings file.
281
+ const dir = await fs.mkdtemp(path.join(outputDir, 'slicer-settings-'));
282
+ extractionScope.getStore()?.push(dir);
283
+ const outputPath = path.join(dir, name.replace(/\//g, '_'));
254
284
  await fs.writeFile(outputPath, content, 'utf8');
255
285
  return outputPath;
256
286
  }
package/dist/index.js CHANGED
@@ -29,7 +29,7 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
29
29
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
30
30
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge } from "./fusion-mcp-bridge.js";
31
31
  import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
32
- import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, parse3MF } from './3mf_parser.js';
32
+ import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, hasSlicerSettingsFile, parse3MF, withExtractedSettingsCleanup } from './3mf_parser.js';
33
33
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
34
34
  import { resolveStudioPrintOptions, usedNozzleCount } from "./studio-print-options.js";
35
35
  import { inspectPrintFile } from "./safety/print-file.js";
@@ -805,6 +805,17 @@ async function previewOfSnapshot(snapshot, plateIndex, sha256) {
805
805
  const preview = await previewPrintFile({ gcode, ...(projectColours ? { projectColours } : {}) });
806
806
  return preview ? { ...preview, artifact_sha256: sha256, plate_index: plateIndex } : undefined;
807
807
  }
808
+ /**
809
+ * The slice's arguments change a resolved process: an explicit value (layer height, walls, infill, supports), or a
810
+ * quality or strength other than standard. Invalid values throw, as slice_stl's own parsing does.
811
+ */
812
+ function changesProcess(args) {
813
+ // slice_stl's own validation of these values (quality, strength, layer height, walls, infill, supports).
814
+ const nozzle = Number(args.nozzle_diameter || DEFAULT_NOZZLE_DIAMETER);
815
+ parseProcessOverrides(withPrintQuality(args, nozzle), nozzle);
816
+ return ["layer_height", "wall_loops", "sparse_infill_density", "enable_support", "support_type", "support_threshold_angle"].some(key => args[key] !== undefined)
817
+ || (args.quality !== undefined && args.quality !== "standard") || (args.strength !== undefined && args.strength !== "standard");
818
+ }
808
819
  function hasExplicitSlicerProfile(args) {
809
820
  return typeof args?.slicer_profile === "string" && args.slicer_profile.trim().length > 0;
810
821
  }
@@ -1683,7 +1694,12 @@ class BambuPrinterMCPServer {
1683
1694
  }
1684
1695
  return inventory;
1685
1696
  }
1686
- async inspectSliceSettings(sourcePath) {
1697
+ /**
1698
+ * `sliceArgs`: the slice_stl arguments a client would send with this file (slicer_profile, template_name,
1699
+ * template_3mf_path, layer_height, wall_loops, sparse_infill_density, quality, strength). `requestedTemplatePath`:
1700
+ * their template, resolved. own_process says whether that slice prints the process the 3MF carries, unchanged.
1701
+ */
1702
+ async inspectSliceSettings(sourcePath, sliceArgs = {}, requestedTemplatePath) {
1687
1703
  if (!fs.existsSync(sourcePath)) {
1688
1704
  throw new Error(`Slice settings source not found: ${sourcePath}`);
1689
1705
  }
@@ -1692,19 +1708,27 @@ class BambuPrinterMCPServer {
1692
1708
  fs.mkdirSync(tempDir, { recursive: true });
1693
1709
  if (extension === ".3mf") {
1694
1710
  const parsed = await parse3MF(sourcePath);
1695
- const extractedSettingsPath = await extractBambuTemplateSettings(sourcePath, tempDir);
1696
1711
  const config = (parsed.slicerConfig || {});
1712
+ // A 3MF with no settings file says so (raw_key_count 0) rather than failing, so a client can tell a file with
1713
+ // none to keep from one whose settings couldn't be read, which stays an error.
1714
+ const hasSettingsFile = await hasSlicerSettingsFile(sourcePath);
1715
+ if (hasSettingsFile && !Object.keys(config).length)
1716
+ throw new Error(`The slicer settings in ${sourcePath} couldn't be read.`);
1717
+ // Returned to the caller, so it stays.
1718
+ const extractedSettingsPath = hasSettingsFile ? await extractBambuTemplateSettings(sourcePath, tempDir, { keep: true }) : undefined;
1697
1719
  return {
1698
1720
  source_path: sourcePath,
1699
1721
  source_type: "3mf",
1700
- extracted_settings_path: extractedSettingsPath,
1722
+ ...(extractedSettingsPath ? { extracted_settings_path: extractedSettingsPath } : {}),
1701
1723
  object_count: parsed.objects.length,
1702
1724
  build_item_count: parsed.build.items.length,
1703
1725
  metadata_keys: Object.keys(parsed.metadata),
1704
1726
  summary: summarizeSliceSettings(config),
1705
1727
  raw_key_count: Object.keys(config).length,
1706
- // ownProcessTemplate itself, for a call that names no profile or template, so this can't drift from slicing.
1707
- own_process: (await ownProcessTemplate({}, sourcePath, undefined)) !== undefined,
1728
+ // ownProcessTemplate itself, with the slice's own arguments, so this can't drift from slicing; an explicit
1729
+ // value or a quality or strength other than standard changes the process the file carries.
1730
+ // Validated first, so an invalid value is refused even when a named profile or template decides the answer.
1731
+ own_process: !changesProcess(sliceArgs) && (await ownProcessTemplate(sliceArgs, sourcePath, requestedTemplatePath)) !== undefined,
1708
1732
  };
1709
1733
  }
1710
1734
  const content = fs.readFileSync(sourcePath, "utf8");
@@ -2116,7 +2140,7 @@ class BambuPrinterMCPServer {
2116
2140
  },
2117
2141
  {
2118
2142
  name: "get_slice_settings",
2119
- description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything. For a 3MF, own_process is true when the file carries its own process (a designer's Bambu Studio or Orca project), so slice_stl and print_3mf's auto-slice slice it with that process unless the call names slicer_profile, template_name or template_3mf_path.",
2143
+ description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything. For a 3MF given as source_path, own_process is true when slice_stl, given this call's other arguments as it would take them (slicer_profile, template_name, template_3mf_path, layer_height, wall_loops, sparse_infill_density, quality, strength), prints the process the file carries (a designer's Bambu Studio or Orca project) unchanged. A 3MF with no slicer settings reports raw_key_count 0; a file that can't be read is an error.",
2120
2144
  inputSchema: {
2121
2145
  type: "object",
2122
2146
  properties: {
@@ -2126,12 +2150,21 @@ class BambuPrinterMCPServer {
2126
2150
  },
2127
2151
  template_name: {
2128
2152
  type: "string",
2129
- description: "Optional named template from the local registry. If provided, resolves source_path automatically."
2153
+ description: "Optional named template from the local registry. Without source_path it is the source read; with source_path it is the slice's template, for own_process."
2130
2154
  },
2131
2155
  template_dir: {
2132
2156
  type: "string",
2133
2157
  description: "Optional template directory override when resolving template_name."
2134
- }
2158
+ },
2159
+ slicer_profile: { type: "string", description: "For own_process: the slicer_profile slice_stl would be given." },
2160
+ template_3mf_path: { type: "string", description: "For own_process: the template_3mf_path slice_stl would be given." },
2161
+ layer_height: { type: "number", description: "For own_process: the layer_height slice_stl would be given." },
2162
+ nozzle_diameter: { type: "string", description: "For own_process: the nozzle_diameter slice_stl would be given; layer heights are checked against it." },
2163
+ wall_loops: { type: "number", description: "For own_process: the wall_loops slice_stl would be given." },
2164
+ sparse_infill_density: { type: "string", description: "For own_process: the sparse_infill_density slice_stl would be given." },
2165
+ enable_support: { type: "boolean", description: "For own_process: the enable_support slice_stl would be given." },
2166
+ support_type: { type: "string", description: "For own_process: the support_type slice_stl would be given." },
2167
+ ...PRINT_QUALITY_PROPERTIES
2135
2168
  }
2136
2169
  }
2137
2170
  },
@@ -3114,7 +3147,8 @@ class BambuPrinterMCPServer {
3114
3147
  ].map(withAnnotations).map(withRemote)
3115
3148
  };
3116
3149
  });
3117
- this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
3150
+ // A designer's settings extracted for this call are removed when it settles.
3151
+ this.server.setRequestHandler(CallToolRequestSchema, (request, extra) => withExtractedSettingsCleanup(async () => {
3118
3152
  const { name, arguments: args } = request.params;
3119
3153
  const sendNativeCommand = (options, execution = {}) => sendCommandWithBambuNative(options, { signal: extra.signal, ...execution });
3120
3154
  const progressToken = extra._meta?.progressToken;
@@ -3729,7 +3763,10 @@ class BambuPrinterMCPServer {
3729
3763
  if (!args?.source_path && !args?.template_name) {
3730
3764
  throw new Error("Missing required parameter: source_path or template_name");
3731
3765
  }
3732
- result = await this.inspectSliceSettings(String(args?.source_path || resolveTemplatePathFromName(["3mf", "json", "config"])));
3766
+ // With source_path, the other arguments are the slice's (template_name is its template), as slice_stl takes them.
3767
+ result = args?.source_path
3768
+ ? await this.inspectSliceSettings(String(args.source_path), args, namedTemplatePath(args, typeof args?.template_name === "string" && args.template_name.trim() ? resolveTemplatePathFromName(["json", "config", "3mf"]) : undefined))
3769
+ : await this.inspectSliceSettings(String(resolveTemplatePathFromName(["3mf", "json", "config"])));
3733
3770
  break;
3734
3771
  case "slice_with_template": {
3735
3772
  if (!args?.stl_path) {
@@ -4319,7 +4356,7 @@ class BambuPrinterMCPServer {
4319
4356
  isError: true,
4320
4357
  };
4321
4358
  }
4322
- });
4359
+ }));
4323
4360
  }
4324
4361
  async startStdio() {
4325
4362
  const transport = new StdioServerTransport();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.64",
3
+ "version": "1.1.66",
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/3mf_parser.ts CHANGED
@@ -2,7 +2,9 @@ import JSZip from 'jszip';
2
2
  import { parseStringPromise } from 'xml2js';
3
3
  import { ThreeMFData, BambuSlicerConfig, ThreeMFMetadata, ThreeMFObject, ThreeMFBuildItem, AMSFilamentMapping, CollarCharmAnalysis, CollarCharmRole, ThreeMFAmsRequirements, ThreeMFPlateObjects } from './types.js';
4
4
  import * as fs from 'fs/promises';
5
- import { createHash } from 'crypto';
5
+ import { AsyncLocalStorage } from 'node:async_hooks';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+ import * as path from 'node:path';
6
8
 
7
9
  // Parses Bambu Studio's JSON config data
8
10
  function parseBambuJSONConfig(jsonData: any): Partial<BambuSlicerConfig> {
@@ -71,14 +73,23 @@ function parseBambuJSONConfig(jsonData: any): Partial<BambuSlicerConfig> {
71
73
  return config;
72
74
  }
73
75
 
76
+ /** The files a 3MF's slicer settings are read from, first found wins. */
77
+ const SLICER_SETTINGS_FILES = [
78
+ 'Metadata/project_settings.config',
79
+ 'Metadata/Slic3r_PE.config',
80
+ 'Metadata/model_settings.config',
81
+ 'Metadata/slice_info.config'
82
+ ];
83
+
84
+ /** Whether a 3MF carries a slicer settings file at all (readable or not). */
85
+ export async function hasSlicerSettingsFile(filePath: string): Promise<boolean> {
86
+ const zip = await JSZip.loadAsync(await fs.readFile(filePath));
87
+ return SLICER_SETTINGS_FILES.some(name => zip.file(name));
88
+ }
89
+
74
90
  async function parseBambuConfig(zip: JSZip): Promise<Partial<BambuSlicerConfig>> {
75
91
  // Look for common Bambu config file names
76
- const potentialFiles = [
77
- 'Metadata/project_settings.config',
78
- 'Metadata/Slic3r_PE.config',
79
- 'Metadata/model_settings.config',
80
- 'Metadata/slice_info.config'
81
- ];
92
+ const potentialFiles = SLICER_SETTINGS_FILES;
82
93
  let configFile = null;
83
94
  let configContent = '';
84
95
 
@@ -241,27 +252,50 @@ export async function hasBambuProjectSettings(filePath: string): Promise<boolean
241
252
  }
242
253
  }
243
254
 
255
+ const extractionScope = new AsyncLocalStorage<string[]>();
256
+
257
+ /** Runs one operation; the directory of every settings file extracted during it is removed when it settles. */
258
+ export async function withExtractedSettingsCleanup<T>(operation: () => Promise<T>): Promise<T> {
259
+ const dirs: string[] = [];
260
+ try {
261
+ return await extractionScope.run(dirs, operation);
262
+ } finally {
263
+ await Promise.all(dirs.map(dir => fs.rm(dir, { recursive: true, force: true }).catch(() => undefined)));
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Writes a 3MF's slicer settings to a file of their own and returns its path. Each extraction gets its own directory,
269
+ * removed when the surrounding withExtractedSettingsCleanup operation settles. `keep` is for a path handed back to the
270
+ * caller: it is named by content, so repeat calls reuse one file, and written whole before it is renamed into place.
271
+ */
244
272
  export async function extractBambuTemplateSettings(
245
273
  filePath: string,
246
- outputDir: string
274
+ outputDir: string,
275
+ options: { keep?: boolean } = {}
247
276
  ): Promise<string> {
248
277
  const data = await fs.readFile(filePath);
249
278
  const zip = await JSZip.loadAsync(data);
250
- const potentialFiles = [
251
- 'Metadata/project_settings.config',
252
- 'Metadata/Slic3r_PE.config',
253
- 'Metadata/model_settings.config',
254
- 'Metadata/slice_info.config'
255
- ];
279
+ const potentialFiles = SLICER_SETTINGS_FILES;
256
280
 
257
281
  for (const name of potentialFiles) {
258
282
  const file = zip.file(name);
259
283
  if (!file) continue;
260
284
 
261
285
  const content = await file.async('string');
262
- // Named by content, so two projects sliced at once never share (or overwrite) one settings file.
263
- const digest = createHash('sha256').update(content).digest('hex').slice(0, 16);
264
- const outputPath = `${outputDir}/${digest}_${name.replace(/\//g, '_')}`;
286
+ if (options.keep) {
287
+ const digest = createHash('sha256').update(content).digest('hex').slice(0, 16);
288
+ const outputPath = path.join(outputDir, `${digest}_${name.replace(/\//g, '_')}`);
289
+ const partial = `${outputPath}.${randomUUID()}.partial`;
290
+ await fs.writeFile(partial, content, 'utf8');
291
+ await fs.rename(partial, outputPath);
292
+ return outputPath;
293
+ }
294
+ // Its own directory for every extraction, so two slices at once (of different projects or the same one)
295
+ // never share, overwrite or half-read one settings file.
296
+ const dir = await fs.mkdtemp(path.join(outputDir, 'slicer-settings-'));
297
+ extractionScope.getStore()?.push(dir);
298
+ const outputPath = path.join(dir, name.replace(/\//g, '_'));
265
299
  await fs.writeFile(outputPath, content, 'utf8');
266
300
  return outputPath;
267
301
  }
package/src/index.ts CHANGED
@@ -59,7 +59,7 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
59
59
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
60
60
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge } from "./fusion-mcp-bridge.js";
61
61
  import { bridgeAmsMapping2Entry, bridgeAmsMappingValue, externalTrayForNozzle, hasAmsMappingInput, normalizeAmsMappingObject, normalizeBridgeAmsTrayValue, studioAmsMappingInfo, trayColour } from "./ams-mapping.js";
62
- import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, parse3MF } from './3mf_parser.js';
62
+ import { analyze3MFAmsRequirements, analyze3MFPlateObjects, analyzeCollarCharm3MF, extractBambuTemplateSettings, getCollarCharmRolePolicy, hasBambuProjectSettings, hasSlicerSettingsFile, parse3MF, withExtractedSettingsCleanup } from './3mf_parser.js';
63
63
  import type { ThreeMFAmsRequirements } from "./types.js";
64
64
  import { BambuImplementation, assertDirectPrintSupported, checkedFile, defaultResumeStateDir } from "./printers/bambu.js";
65
65
  import { resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "./studio-print-options.js";
@@ -997,6 +997,18 @@ async function previewOfSnapshot(snapshot: string, plateIndex: number, sha256: s
997
997
  return preview ? { ...preview, artifact_sha256: sha256, plate_index: plateIndex } : undefined;
998
998
  }
999
999
 
1000
+ /**
1001
+ * The slice's arguments change a resolved process: an explicit value (layer height, walls, infill, supports), or a
1002
+ * quality or strength other than standard. Invalid values throw, as slice_stl's own parsing does.
1003
+ */
1004
+ function changesProcess(args: Record<string, unknown>): boolean {
1005
+ // slice_stl's own validation of these values (quality, strength, layer height, walls, infill, supports).
1006
+ const nozzle = Number(args.nozzle_diameter || DEFAULT_NOZZLE_DIAMETER);
1007
+ parseProcessOverrides(withPrintQuality(args, nozzle), nozzle);
1008
+ return ["layer_height", "wall_loops", "sparse_infill_density", "enable_support", "support_type", "support_threshold_angle"].some(key => args[key] !== undefined)
1009
+ || (args.quality !== undefined && args.quality !== "standard") || (args.strength !== undefined && args.strength !== "standard");
1010
+ }
1011
+
1000
1012
  function hasExplicitSlicerProfile(args: any): boolean {
1001
1013
  return typeof args?.slicer_profile === "string" && args.slicer_profile.trim().length > 0;
1002
1014
  }
@@ -2120,7 +2132,12 @@ class BambuPrinterMCPServer {
2120
2132
  return inventory;
2121
2133
  }
2122
2134
 
2123
- private async inspectSliceSettings(sourcePath: string) {
2135
+ /**
2136
+ * `sliceArgs`: the slice_stl arguments a client would send with this file (slicer_profile, template_name,
2137
+ * template_3mf_path, layer_height, wall_loops, sparse_infill_density, quality, strength). `requestedTemplatePath`:
2138
+ * their template, resolved. own_process says whether that slice prints the process the 3MF carries, unchanged.
2139
+ */
2140
+ private async inspectSliceSettings(sourcePath: string, sliceArgs: Record<string, unknown> = {}, requestedTemplatePath?: string) {
2124
2141
  if (!fs.existsSync(sourcePath)) {
2125
2142
  throw new Error(`Slice settings source not found: ${sourcePath}`);
2126
2143
  }
@@ -2131,19 +2148,26 @@ class BambuPrinterMCPServer {
2131
2148
 
2132
2149
  if (extension === ".3mf") {
2133
2150
  const parsed = await parse3MF(sourcePath);
2134
- const extractedSettingsPath = await extractBambuTemplateSettings(sourcePath, tempDir);
2135
2151
  const config = (parsed.slicerConfig || {}) as Record<string, any>;
2152
+ // A 3MF with no settings file says so (raw_key_count 0) rather than failing, so a client can tell a file with
2153
+ // none to keep from one whose settings couldn't be read, which stays an error.
2154
+ const hasSettingsFile = await hasSlicerSettingsFile(sourcePath);
2155
+ if (hasSettingsFile && !Object.keys(config).length) throw new Error(`The slicer settings in ${sourcePath} couldn't be read.`);
2156
+ // Returned to the caller, so it stays.
2157
+ const extractedSettingsPath = hasSettingsFile ? await extractBambuTemplateSettings(sourcePath, tempDir, { keep: true }) : undefined;
2136
2158
  return {
2137
2159
  source_path: sourcePath,
2138
2160
  source_type: "3mf",
2139
- extracted_settings_path: extractedSettingsPath,
2161
+ ...(extractedSettingsPath ? { extracted_settings_path: extractedSettingsPath } : {}),
2140
2162
  object_count: parsed.objects.length,
2141
2163
  build_item_count: parsed.build.items.length,
2142
2164
  metadata_keys: Object.keys(parsed.metadata),
2143
2165
  summary: summarizeSliceSettings(config),
2144
2166
  raw_key_count: Object.keys(config).length,
2145
- // ownProcessTemplate itself, for a call that names no profile or template, so this can't drift from slicing.
2146
- own_process: (await ownProcessTemplate({}, sourcePath, undefined)) !== undefined,
2167
+ // ownProcessTemplate itself, with the slice's own arguments, so this can't drift from slicing; an explicit
2168
+ // value or a quality or strength other than standard changes the process the file carries.
2169
+ // Validated first, so an invalid value is refused even when a named profile or template decides the answer.
2170
+ own_process: !changesProcess(sliceArgs) && (await ownProcessTemplate(sliceArgs, sourcePath, requestedTemplatePath)) !== undefined,
2147
2171
  };
2148
2172
  }
2149
2173
 
@@ -2632,7 +2656,7 @@ class BambuPrinterMCPServer {
2632
2656
  },
2633
2657
  {
2634
2658
  name: "get_slice_settings",
2635
- description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything. For a 3MF, own_process is true when the file carries its own process (a designer's Bambu Studio or Orca project), so slice_stl and print_3mf's auto-slice slice it with that process unless the call names slicer_profile, template_name or template_3mf_path.",
2659
+ description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything. For a 3MF given as source_path, own_process is true when slice_stl, given this call's other arguments as it would take them (slicer_profile, template_name, template_3mf_path, layer_height, wall_loops, sparse_infill_density, quality, strength), prints the process the file carries (a designer's Bambu Studio or Orca project) unchanged. A 3MF with no slicer settings reports raw_key_count 0; a file that can't be read is an error.",
2636
2660
  inputSchema: {
2637
2661
  type: "object",
2638
2662
  properties: {
@@ -2642,12 +2666,21 @@ class BambuPrinterMCPServer {
2642
2666
  },
2643
2667
  template_name: {
2644
2668
  type: "string",
2645
- description: "Optional named template from the local registry. If provided, resolves source_path automatically."
2669
+ description: "Optional named template from the local registry. Without source_path it is the source read; with source_path it is the slice's template, for own_process."
2646
2670
  },
2647
2671
  template_dir: {
2648
2672
  type: "string",
2649
2673
  description: "Optional template directory override when resolving template_name."
2650
- }
2674
+ },
2675
+ slicer_profile: { type: "string", description: "For own_process: the slicer_profile slice_stl would be given." },
2676
+ template_3mf_path: { type: "string", description: "For own_process: the template_3mf_path slice_stl would be given." },
2677
+ layer_height: { type: "number", description: "For own_process: the layer_height slice_stl would be given." },
2678
+ nozzle_diameter: { type: "string", description: "For own_process: the nozzle_diameter slice_stl would be given; layer heights are checked against it." },
2679
+ wall_loops: { type: "number", description: "For own_process: the wall_loops slice_stl would be given." },
2680
+ sparse_infill_density: { type: "string", description: "For own_process: the sparse_infill_density slice_stl would be given." },
2681
+ enable_support: { type: "boolean", description: "For own_process: the enable_support slice_stl would be given." },
2682
+ support_type: { type: "string", description: "For own_process: the support_type slice_stl would be given." },
2683
+ ...PRINT_QUALITY_PROPERTIES
2651
2684
  }
2652
2685
  }
2653
2686
  },
@@ -3631,7 +3664,8 @@ class BambuPrinterMCPServer {
3631
3664
  };
3632
3665
  });
3633
3666
 
3634
- this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
3667
+ // A designer's settings extracted for this call are removed when it settles.
3668
+ this.server.setRequestHandler(CallToolRequestSchema, (request, extra) => withExtractedSettingsCleanup(async () => {
3635
3669
  const { name, arguments: args } = request.params;
3636
3670
  const sendNativeCommand = (
3637
3671
  options: Parameters<typeof sendCommandWithBambuNative>[0],
@@ -4358,9 +4392,11 @@ class BambuPrinterMCPServer {
4358
4392
  if (!args?.source_path && !args?.template_name) {
4359
4393
  throw new Error("Missing required parameter: source_path or template_name");
4360
4394
  }
4361
- result = await this.inspectSliceSettings(
4362
- String(args?.source_path || resolveTemplatePathFromName(["3mf", "json", "config"]))
4363
- );
4395
+ // With source_path, the other arguments are the slice's (template_name is its template), as slice_stl takes them.
4396
+ result = args?.source_path
4397
+ ? await this.inspectSliceSettings(String(args.source_path), args as Record<string, unknown>,
4398
+ namedTemplatePath(args, typeof args?.template_name === "string" && args.template_name.trim() ? resolveTemplatePathFromName(["json", "config", "3mf"]) : undefined))
4399
+ : await this.inspectSliceSettings(String(resolveTemplatePathFromName(["3mf", "json", "config"])));
4364
4400
  break;
4365
4401
 
4366
4402
  case "slice_with_template": {
@@ -5064,7 +5100,7 @@ class BambuPrinterMCPServer {
5064
5100
  isError: true,
5065
5101
  };
5066
5102
  }
5067
- });
5103
+ }));
5068
5104
  }
5069
5105
 
5070
5106
  async startStdio() {