bambu-printer-mcp 1.1.96 → 1.1.98

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 (49) hide show
  1. package/dist/cad/contracts.js +7 -5
  2. package/dist/cad-engine.js +1 -0
  3. package/dist/counterpart/info.js +1 -0
  4. package/dist/counterpart/make-3mf.d.ts +1 -0
  5. package/dist/counterpart/make-3mf.js +37 -5
  6. package/dist/counterpart/model-plates.d.ts +2 -0
  7. package/dist/counterpart/model-plates.js +3 -0
  8. package/dist/counterpart/part-meshes.d.ts +114 -0
  9. package/dist/counterpart/part-meshes.js +323 -0
  10. package/dist/counterpart/plate-filaments.d.ts +3 -0
  11. package/dist/counterpart/plate-filaments.js +31 -10
  12. package/dist/counterpart/remote.js +1 -0
  13. package/dist/counterpart/schemas.d.ts +10 -0
  14. package/dist/counterpart/schemas.js +2 -0
  15. package/dist/design-app-setup.d.ts +9 -0
  16. package/dist/design-app-setup.js +5 -2
  17. package/dist/design-guidance.d.ts +3 -3
  18. package/dist/design-guidance.js +11 -4
  19. package/dist/index.js +82 -6
  20. package/dist/refusal.d.ts +31 -1
  21. package/dist/refusal.js +30 -1
  22. package/dist/slicer/filament-feed.d.ts +61 -0
  23. package/dist/slicer/filament-feed.js +99 -0
  24. package/dist/slicer/floating-regions.d.ts +54 -0
  25. package/dist/slicer/floating-regions.js +198 -0
  26. package/dist/slicer/profile-flatten.js +4 -0
  27. package/dist/tool-annotations.js +2 -0
  28. package/package.json +2 -2
  29. package/src/cad/contracts.ts +7 -5
  30. package/src/cad/project3mf.py +9 -4
  31. package/src/cad/scan_measure.py +207 -0
  32. package/src/cad/scan_touchup.py +4 -1
  33. package/src/cad/worker.py +2 -1
  34. package/src/cad-engine.ts +1 -0
  35. package/src/counterpart/info.ts +1 -0
  36. package/src/counterpart/make-3mf.ts +33 -7
  37. package/src/counterpart/model-plates.ts +4 -0
  38. package/src/counterpart/part-meshes.ts +304 -0
  39. package/src/counterpart/plate-filaments.ts +25 -9
  40. package/src/counterpart/remote.ts +1 -0
  41. package/src/counterpart/schemas.ts +4 -0
  42. package/src/design-app-setup.ts +7 -2
  43. package/src/design-guidance.ts +11 -4
  44. package/src/index.ts +80 -7
  45. package/src/refusal.ts +37 -1
  46. package/src/slicer/filament-feed.ts +116 -0
  47. package/src/slicer/floating-regions.ts +187 -0
  48. package/src/slicer/profile-flatten.ts +3 -0
  49. package/src/tool-annotations.ts +2 -0
package/src/index.ts CHANGED
@@ -7,6 +7,8 @@ import { withAnnotations } from "./tool-annotations.js";
7
7
  import { withRemote } from "./counterpart/remote.js";
8
8
  import { refusalReport, slicedFileFacts, slicerReport } from "./counterpart/sliced-file.js";
9
9
  import { listModelPlates } from "./counterpart/model-plates.js";
10
+ import { floatingWarningFacts } from "./slicer/floating-regions.js";
11
+ import { feedFromBambuReport, feedVerdict, sliceColours, UNKNOWN_FEED, type PrinterFeed } from "./slicer/filament-feed.js";
10
12
 
11
13
  /** The slicer's verdict beside its result.json (`slicer_report`). */
12
14
  function reportOf(result: unknown): { slicer_report?: ReturnType<typeof slicerReport> } {
@@ -87,12 +89,13 @@ import { PROPOSE_FILAMENTS_INPUT_PROPERTIES, PROPOSE_FILAMENTS_OUTPUT_SCHEMA, NO
87
89
  import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, FDM_FIT_GUIDANCE, FDM_FIT_RESOURCE, FDM_FIT_URI, FDM_SLICING_PROMPT, SERVER_INSTRUCTIONS, slicingGuidance } from "./design-guidance.js";
88
90
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
89
91
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
92
+ import { partMeshes, PART_MESHES_OUTPUT_SCHEMA } from "./counterpart/part-meshes.js";
90
93
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
91
94
  import { SELF_CHECK_OUTPUT_SCHEMA, selfCheck } from "./counterpart/self-check.js";
92
95
  import { DIAGNOSTICS_INPUT_PROPERTIES, DIAGNOSTICS_OUTPUT_SCHEMA, appVersion, buildDiagnostics, captureServerLog, diagnosticsBudget, jsonText, recordToolError, rememberSecretArguments, serverLogText, settingsSnapshot, toolErrorsText, type DiagnosticsSource } from "./counterpart/diagnostics.js";
93
96
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
94
97
  import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
95
- import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
98
+ import { FilamentSlotsError, PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
96
99
  import { uploadProgressReporter } from "./upload-progress.js";
97
100
  import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
98
101
 
@@ -167,7 +170,7 @@ const SERVER_INFO = {
167
170
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
168
171
  const OUTPUT_SCHEMA_TOOLS = new Set([
169
172
  "cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
170
- "counterpart_printer_info", "counterpart_self_check", "counterpart_diagnostics", "counterpart_print_progress", "counterpart_make_3mf",
173
+ "counterpart_printer_info", "counterpart_self_check", "counterpart_diagnostics", "counterpart_print_progress", "counterpart_make_3mf", "counterpart_part_meshes",
171
174
  "counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
172
175
  "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
173
176
  "camera_stream_start", "camera_frame", "camera_stream_stop",
@@ -2154,6 +2157,31 @@ class BambuPrinterMCPServer {
2154
2157
  });
2155
2158
  }
2156
2159
 
2160
+ /**
2161
+ * The filaments the configured printer can feed itself, for a multi-colour slice (src/slicer/filament-feed.ts):
2162
+ * its AMS trays and external spools from a fresh report, or unknown without one. Only reads status.
2163
+ */
2164
+ private async printerFeed(usePrinterFilaments: boolean, model: string, host: string, bambuSerial: string | undefined, bambuToken: string | undefined): Promise<PrinterFeed> {
2165
+ const dual = isDualNozzleModel(model);
2166
+ const unknown = (source: string) => UNKNOWN_FEED(source, dual);
2167
+ if (!usePrinterFilaments) return unknown("use_printer_filaments is false, so the printer wasn't asked");
2168
+ if (!bambuSerial || !bambuToken) return unknown("no printer is configured to ask");
2169
+ try {
2170
+ let status = await this.bambu.getStatus(host, bambuSerial, bambuToken);
2171
+ let feed = feedFromBambuReport(status?.raw, status?.connected === true, dual);
2172
+ // An idle printer's first push can be sparse; its AMS block follows (as get_printer_filaments waits for). A
2173
+ // printer that isn't connected isn't asked twice.
2174
+ if (status?.connected === true && (!feed.known || feed.ams_slots === 0)) {
2175
+ await new Promise(resolve => setTimeout(resolve, 1500));
2176
+ status = await this.bambu.getStatus(host, bambuSerial, bambuToken);
2177
+ feed = feedFromBambuReport(status?.raw, status?.connected === true, dual);
2178
+ }
2179
+ return feed;
2180
+ } catch {
2181
+ return unknown("the printer could not be reached");
2182
+ }
2183
+ }
2184
+
2157
2185
  private async getResolvedPrinterFilamentInventory(
2158
2186
  host: string,
2159
2187
  bambuSerial: string,
@@ -2808,11 +2836,12 @@ class BambuPrinterMCPServer {
2808
2836
  },
2809
2837
  {
2810
2838
  name: "slice_stl",
2811
- description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. structuredContent.slicer_report says whether it failed; for a failure, its message is a plain sentence for a person and slicer_message keeps the slicer's words, which a failed slice's text gives after that sentence. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2839
+ description: "Slice an STL or 3MF file using a slicer to generate printable G-code or sliced 3MF. IMPORTANT: bambu_model must be specified to ensure the slicer generates safe G-code for the correct printer. The text result is the sliced file's path. When Bambu Studio or OrcaSlicer writes a result.json, structuredContent.slicer_result carries it verbatim, success or error: error_string, return_code and each sliced_plates[].warning_message, such as a floating cantilever. structuredContent.slicer_report says whether it failed; for a failure, its message is a plain sentence for a person and slicer_message keeps the slicer's words, which a failed slice's text gives after that sentence. When a slice that worked warns of floating regions, next carries the stop rule (one targeted fix and one re-slice, then report it or slice with supports on) and, for an STL the slicer did not turn, structuredContent.floating_regions lists where they are: x and y in the STL's own millimetres, z above its lowest point, and depth_mm, how far each hangs below where it joins the rest. A slice in two or more colours carries filament_feed: the colours, the filament changes the slicer reports, and whether the printer can feed them (its AMS trays and external spools from a fresh status read; unknown without one). When the printer is known not to (no AMS, or fewer filaments than colours), slice_stl refuses with code needs-more-filaments, filament_slots, filament_changes and a plain slicer_report.message, unless manual_filament_changes is true; when it is unknown, the slice succeeds and slicer_report.message says how many times it would stop without an AMS. A 3MF that carries its own process settings (a designer's Bambu Studio or Orca project) slices with them unless slicer_profile, template_name or template_3mf_path is given; the machine still comes from bambu_model. quality and strength adjust that process, and strength never lowers its walls or infill.",
2812
2840
  inputSchema: {
2813
2841
  type: "object",
2814
2842
  properties: {
2815
2843
  stl_path: { type: "string", description: "Path to the STL or 3MF file to slice" },
2844
+ manual_filament_changes: { type: "boolean", description: "The person will change filament by hand: a slice in more colours than the printer can feed (no AMS) is returned, with the number of changes, instead of refused with needs-more-filaments." },
2816
2845
  bambu_model: {
2817
2846
  type: "string",
2818
2847
  enum: [...VALID_BAMBU_MODELS],
@@ -3674,7 +3703,8 @@ class BambuPrinterMCPServer {
3674
3703
  properties: {
3675
3704
  stl_path: { type: "string", description: "Path to the part's STL file." },
3676
3705
  name: { type: "string", description: "The part's name, shown in the slicer." },
3677
- filament: { type: "integer", minimum: 1, maximum: 64, description: "1-based project filament for this part; defaults to the part's position (1, 2, ...)." }
3706
+ filament: { type: "integer", minimum: 1, maximum: 64, description: "1-based project filament for this part; defaults to the part's position (1, 2, ...)." },
3707
+ color: { type: "string", pattern: "^#[0-9A-Fa-f]{6}$", description: "The part's colour as #RRGGBB. Give every part one, or none: the 3MF then declares each filament's colour (project_settings.config filament_colour), as Bambu Studio does, and parts on one filament share it." }
3678
3708
  },
3679
3709
  required: ["stl_path", "name"],
3680
3710
  additionalProperties: false
@@ -3687,6 +3717,20 @@ class BambuPrinterMCPServer {
3687
3717
  },
3688
3718
  outputSchema: MAKE_3MF_OUTPUT_SCHEMA
3689
3719
  },
3720
+ {
3721
+ name: "counterpart_part_meshes",
3722
+ description: "Counterpart contract (counterpart/1): one STL per printable part of any 3MF (a pass's, counterpart_make_3mf's, cad_run's project_3mf, or a designer's Bambu Studio, OrcaSlicer or plain 3MF), so a client draws each part in its colour or shows the design in AR. Writes into a new folder it creates inside out_dir and never overwrites. Returns units (mm), folder and parts: [{id, name, plate?, color?, filament?, painted?, stl_path, triangles, size_mm}], one per part per printed copy. Every STL is in the 3MF's build frame in millimetres, component and build transforms applied, so the parts line up when drawn together; plate is the plate number from 1 (list_3mf_plates index + 1), absent for a 3MF without plates; color is #RRGGBB from the 3MF's own filament colours, absent when it declares none; painted means slicer painting recolours some facets. A part beyond the read limits is listed in skipped with why.",
3723
+ inputSchema: {
3724
+ type: "object",
3725
+ properties: {
3726
+ three_mf_path: { type: "string", description: "Path to the 3MF." },
3727
+ out_dir: { type: "string", description: "An existing folder; each call writes into a new subfolder of it." }
3728
+ },
3729
+ required: ["three_mf_path", "out_dir"],
3730
+ additionalProperties: false
3731
+ },
3732
+ outputSchema: PART_MESHES_OUTPUT_SCHEMA
3733
+ },
3690
3734
  {
3691
3735
  name: "blender_mcp_setup",
3692
3736
  description: "Check or update the MCP for Blender add-on that the configured Blender bridge (BLENDER_MCP_COMMAND uvx, BLENDER_MCP_ARGS naming mcp-for-blender or blender-mcp) needs. Without update: which add-on file Blender loads, its protocol and the protocol the package expects, whether Blender is listening and the running add-on's own handshake. Changes nothing. With update: true, stages the add-on with the package's own installer (mcp-for-blender install-addon) at the inspected version, checks it, keeps the old file as a backup next to it and renames the new one into place. Never starts, stops or edits Blender; a running Blender uses the new add-on once it is re-enabled or restarted. A custom bridge returns supported false.",
@@ -4725,7 +4769,23 @@ class BambuPrinterMCPServer {
4725
4769
  await progressNotifications;
4726
4770
  // The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim, and
4727
4771
  // slicer_report its verdict and words, so clients don't read the slicer's format.
4728
- return { content: [{ type: "text", text: sliced.path }], structuredContent: withSlicerReport(sliced) };
4772
+ // A warning about floating regions comes with where they are and the rule that bounds chasing it (#859).
4773
+ const reported = withSlicerReport(sliced);
4774
+ // Turned or scaled by the slicer: the STL's own coordinates would no longer match the slice.
4775
+ const turned = Boolean(args?.orient) || [args?.rotate, args?.rotate_x, args?.rotate_y].some(r => r !== undefined && Number(r) !== 0)
4776
+ || (args?.scale !== undefined && Number(args.scale) !== 1);
4777
+ const located = await floatingWarningFacts(reported.slicer_report, String(args.stl_path), turned);
4778
+ // A slice in several colours on a printer that can't feed them is refused or flagged, never sent on
4779
+ // silently (beta 8 DAD replay: 85 manual changes on a P1S with no AMS). See src/slicer/filament-feed.ts.
4780
+ let feedFacts: Record<string, unknown> = {};
4781
+ if (sliceColours(sliced.slicer_result).colours >= 2) {
4782
+ const verdict = feedVerdict(sliced.slicer_result, await this.printerFeed(usePrinterFilaments, sliceModel, host, bambuSerial, bambuToken), args?.manual_filament_changes === true);
4783
+ if (verdict.refusal) throw Object.assign(verdict.refusal, { slicerResult: sliced.slicer_result });
4784
+ if (verdict.facts) feedFacts = { filament_feed: verdict.facts };
4785
+ if (verdict.note && reported.slicer_report)
4786
+ reported.slicer_report = { ...reported.slicer_report, message: reported.slicer_report.message ? `${reported.slicer_report.message}\n${verdict.note}` : verdict.note };
4787
+ }
4788
+ return { content: [{ type: "text", text: sliced.path }], structuredContent: { ...reported, ...located, ...feedFacts } };
4729
4789
  }
4730
4790
 
4731
4791
  case "print_3mf": {
@@ -5180,6 +5240,10 @@ class BambuPrinterMCPServer {
5180
5240
  result = await makeCounterpart3mf(args ?? {});
5181
5241
  break;
5182
5242
 
5243
+ case "counterpart_part_meshes":
5244
+ result = await partMeshes(args ?? {});
5245
+ break;
5246
+
5183
5247
  case "design_guidance":
5184
5248
  result = designGuidance(args ?? {});
5185
5249
  break;
@@ -5266,7 +5330,7 @@ class BambuPrinterMCPServer {
5266
5330
  }
5267
5331
  const message = error instanceof Error ? error.message : String(error);
5268
5332
  // Refusals and printer rejections repeat unchanged; say what to fix instead of "try again".
5269
- const refused = /nothing was (?:sent|uploaded)|no command was sent|does not match the job|is ambiguous|is missing or ambiguous|rejected the print command|are refused|is refused|refused because|refused until|refused before/i.test(message);
5333
+ const refused = error instanceof FilamentSlotsError || /nothing was (?:sent|uploaded)|no command was sent|does not match the job|is ambiguous|is missing or ambiguous|rejected the print command|are refused|is refused|refused because|refused until|refused before/i.test(message);
5270
5334
  const structured: StructuredToolError = {
5271
5335
  status: "error",
5272
5336
  retryable: false,
@@ -5280,9 +5344,18 @@ class BambuPrinterMCPServer {
5280
5344
  // A slicer failure always carries slicer_report: the plain sentence a person sees, the slicer's words for the log.
5281
5345
  // The report always says failed (a result.json that says success can still leave no output file).
5282
5346
  ...(error instanceof SlicerRunError ? {
5283
- ...(error.slicerResult ? { slicer_result: error.slicerResult } : {}),
5347
+ ...(error.slicerResult ? { slicer_result: error.slicerResult as Record<string, unknown> } : {}),
5284
5348
  slicer_report: { ...refusalReport(error.words), message: error.plain ?? error.words.slice(0, 2000) },
5285
5349
  } : {}),
5350
+ // A design in more colours than filaments to slice it with: the counts and the plain answer a client shows.
5351
+ ...(error instanceof FilamentSlotsError ? {
5352
+ filament_slots: { colours: error.colours, slots: error.slots },
5353
+ ...(error.changes !== undefined ? { filament_changes: error.changes } : {}),
5354
+ ...(error.feed ? { filament_feed: error.feed } : {}),
5355
+ ...(error.slicerResult ? { slicer_result: error.slicerResult as Record<string, unknown> } : {}),
5356
+ ...(error.feed ? { suggestion: "Make it in one colour, or print each colour as its own part. If the person will change filament by hand, slice again with manual_filament_changes: true." } : {}),
5357
+ slicer_report: { failed: true, message: error.plain, slicer_message: error.detail },
5358
+ } : {}),
5286
5359
  };
5287
5360
 
5288
5361
  // MCP clients validate structuredContent against a declared outputSchema even on
package/src/refusal.ts CHANGED
@@ -12,8 +12,11 @@ import { AsyncLocalStorage } from "node:async_hooks";
12
12
  * - printer-upload-failed: the print file didn't reach the printer, so no print command was sent.
13
13
  * - slicer-waiting-on-dialog: the slicer stopped working (no CPU, no output) as it does while a window waits for an
14
14
  * answer, and was stopped; nothing was sliced or sent. Not the slicer's verdict on the model: no slicer_report.
15
+ * - needs-more-filaments: the design is in more colours than there are filaments to slice it with (a two-colour 3MF on
16
+ * a printer with no AMS loaded); nothing was sliced. structuredContent.filament_slots says how many of each, and
17
+ * slicer_report.message the plain answer a client shows (scan-to-make #858, the DAD pass).
15
18
  */
16
- export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready", "printer-upload-failed", "slicer-waiting-on-dialog"] as const;
19
+ export const REFUSAL_CODES = ["printer-command-rejected", "printer-not-ready", "printer-upload-failed", "slicer-waiting-on-dialog", "needs-more-filaments"] as const;
17
20
  export type RefusalCode = (typeof REFUSAL_CODES)[number];
18
21
 
19
22
  export class PrinterRefusal extends Error {
@@ -46,3 +49,36 @@ export function printOutcome(error: unknown): PrintOutcome {
46
49
  if (error instanceof PrinterRefusal && error.code === "printer-command-rejected") return "rejected";
47
50
  return printDispatch.getStore()?.attempted === false ? "not-sent" : "unknown";
48
51
  }
52
+
53
+ /**
54
+ * More filament colours than filament slots to slice with: the plain answer a person is shown, and the counts. The
55
+ * DAD pass sliced its two-colour 3MF for a P1S with no AMS loaded and got only "2 filament colours were supplied for
56
+ * 1 filament slots".
57
+ */
58
+ export class FilamentSlotsError extends PrinterRefusal {
59
+ readonly plain: string;
60
+ /** The filament changes the slice would make, when the slicer reported them (a printer with too few feeds). */
61
+ readonly changes?: number;
62
+ /** The slicer's own words, or this server's when the printer's feeds decided it. */
63
+ readonly detail: string;
64
+ /** The printer's feeds and the slice's colours, when they decided it (slice_stl's filament_feed). */
65
+ feed?: Record<string, unknown>;
66
+ /** The slicer's own result.json for the slice the printer's feeds refused. */
67
+ slicerResult?: unknown;
68
+ /**
69
+ * colours: the colours the design prints with; slots: the filaments there are to feed them (slice slots, or the
70
+ * printer's AMS trays plus external spools). `options` carries the plain sentence when the printer's feeds decide
71
+ * it, and the filament changes the slice would make.
72
+ */
73
+ constructor(readonly colours: number, readonly slots: number, options: { plain?: string; changes?: number } = {}) {
74
+ const plain = options.plain ?? `This design is in ${colours} colours, but only ${slots} filament${slots === 1 ? " is" : "s are"} available to print it. It needs a printer with an AMS loaded with ${colours} colours, or it can print in one colour.`;
75
+ const detail = options.plain
76
+ ? `The design prints in ${colours} filaments and the printer can feed ${slots}${options.changes !== undefined ? `; the slice makes ${options.changes} filament changes` : ""}.`
77
+ : `${colours} filament colours were supplied for ${slots} filament slots.`;
78
+ super("needs-more-filaments", `${plain}\n${options.plain ? "The slice said" : "The slicer setup said"}: ${detail}`);
79
+ this.name = "FilamentSlotsError";
80
+ this.plain = plain;
81
+ this.detail = detail;
82
+ if (options.changes !== undefined) this.changes = options.changes;
83
+ }
84
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Whether the printer can feed a multi-colour slice itself (beta 8 DAD replay, Nov 17): a two-colour 3MF sliced for a
3
+ * P1S with no AMS succeeded with 85 filament changes and no word, so a tester would have been sent a print that stops
4
+ * 85 times for a manual swap. Shared by bambu-printer-mcp and mcp-3D-printer-server.
5
+ *
6
+ * How the printer's feeds are known (the judgement, written down):
7
+ * - Feeds are the AMS trays the printer reports (every tray of every AMS unit, loaded or not: a person can load an
8
+ * empty one). Without an AMS, its external spool holders, one per nozzle (two on a dual-nozzle model). A print
9
+ * doesn't mix the external spool with AMS trays, so the two are not added. Two external spools feed two colours
10
+ * only when each colour is on its own nozzle; the slice's nozzle bindings aren't read here, so a dual-nozzle
11
+ * printer without an AMS is unknown for two colours (flagged, not passed) and too few for three.
12
+ * - Known only from a connected printer's report that carries its AMS block; one that lists no AMS unit in it means
13
+ * no AMS. A report without the block says nothing. The model alone never decides it: every model's AMS is
14
+ * optional.
15
+ * - Counted per plate: a project whose plates each print in one colour needs no change, and a slice that reports no
16
+ * filament change is never refused.
17
+ * - Unknown when there are no printer credentials, the printer can't be reached, the caller said
18
+ * use_printer_filaments: false, or the printer isn't a Bambu. Then the slice succeeds, flagged: the colours and the
19
+ * filament changes are in the result and its message, so a client never sends it on silently.
20
+ * - Known too few feeds: the slice is refused with needs-more-filaments, as 1.1.97 refuses more colours than slots,
21
+ * unless the caller says the person will change filament by hand (manual_filament_changes: true).
22
+ */
23
+ import { FilamentSlotsError } from "../refusal.js";
24
+
25
+ export interface PrinterFeed {
26
+ known: boolean;
27
+ /** AMS trays the printer reports (0: no AMS). */
28
+ ams_slots: number;
29
+ /** External spool holders: one per nozzle. */
30
+ external: number;
31
+ /** How it was known, or why it isn't. */
32
+ source: string;
33
+ }
34
+
35
+ /** The feeds a connected Bambu printer's raw report shows. */
36
+ export function feedFromBambuReport(raw: unknown, connected: boolean, dualNozzle: boolean): PrinterFeed {
37
+ const report = raw && typeof raw === "object" ? raw as Record<string, unknown> : undefined;
38
+ const external = dualNozzle ? 2 : 1;
39
+ const block = report?.ams && typeof report.ams === "object" ? report.ams as Record<string, unknown> : undefined;
40
+ if (!connected || !block) return { known: false, ams_slots: 0, external, source: connected ? "the printer's report has no AMS block yet" : "the printer's report could not be read" };
41
+ // Absence needs evidence: the unit list itself, or ams_exist_bits of zero. A partial block (an incremental push with
42
+ // tray_now but no list) says nothing, and stays unknown (Codex review, #170).
43
+ const noneExist = block.ams_exist_bits !== undefined && Number.parseInt(String(block.ams_exist_bits), 16) === 0;
44
+ if (!Array.isArray(block.ams) && !noneExist) return { known: false, ams_slots: 0, external, source: "the printer's report doesn't list its AMS units yet" };
45
+ const units = Array.isArray(block.ams) ? block.ams : [];
46
+ // A unit's own tray list when it reports one; without it, one slot for an AMS HT (ids from 128, as ams-mapping.ts
47
+ // numbers them) and four for an AMS.
48
+ const slots = units.reduce((sum: number, unit) => {
49
+ const u = unit as { id?: unknown; tray?: unknown };
50
+ return sum + (Array.isArray(u?.tray) ? u.tray.length : Number.parseInt(String(u?.id ?? "0"), 10) >= 128 ? 1 : 4);
51
+ }, 0);
52
+ return { known: true, ams_slots: slots, external, source: slots ? `the printer reports ${units.length} AMS unit${units.length === 1 ? "" : "s"}` : "the printer reports no AMS" };
53
+ }
54
+
55
+ export const UNKNOWN_FEED = (source: string, dualNozzle = false): PrinterFeed => ({ known: false, ams_slots: 0, external: dualNozzle ? 2 : 1, source });
56
+
57
+ /**
58
+ * The colours a slice prints with and its filament changes, from Bambu Studio / OrcaSlicer's result.json: the most
59
+ * colours any one plate prints with (each plate prints on its own), and the changes of every plate that prints in
60
+ * more than one, added up, so a second plate's changes are never left out (Codex review, #170).
61
+ */
62
+ export function sliceColours(result: unknown): { colours: number; changes: number | undefined } {
63
+ const plates = result && typeof result === "object" && Array.isArray((result as { sliced_plates?: unknown }).sliced_plates)
64
+ ? (result as { sliced_plates: Record<string, unknown>[] }).sliced_plates : [];
65
+ let colours = 0;
66
+ let changes: number | undefined;
67
+ for (const plate of plates) {
68
+ const used = new Set<number>();
69
+ for (const f of Array.isArray(plate?.filaments) ? plate.filaments as Record<string, unknown>[] : [])
70
+ if (typeof f?.id === "number" && (typeof f.total_used_g !== "number" || f.total_used_g > 0)) used.add(f.id);
71
+ colours = Math.max(colours, used.size);
72
+ if (used.size > 1 && typeof plate?.filament_change_times === "number") changes = (changes ?? 0) + plate.filament_change_times;
73
+ }
74
+ return { colours, changes: colours > 1 ? changes : plates.some(p => typeof p?.filament_change_times === "number") ? 0 : undefined };
75
+ }
76
+
77
+ export interface FeedVerdict {
78
+ /** The structured facts every multi-colour slice carries (additive). */
79
+ facts?: { colours: number; filament_changes?: number; printer: "feeds-all" | "too-few-feeds" | "unknown"; feeds?: number; source: string; manual?: true };
80
+ /** A sentence for slicer_report.message on a slice that worked. */
81
+ note?: string;
82
+ /** The refusal, when the printer is known not to feed the colours and the caller didn't accept manual changes. */
83
+ refusal?: FilamentSlotsError;
84
+ }
85
+
86
+ /** The verdict on one slice: nothing for a one-colour slice. */
87
+ export function feedVerdict(result: unknown, feed: PrinterFeed, manual: boolean): FeedVerdict {
88
+ const { colours, changes } = sliceColours(result);
89
+ // One colour on every plate, or a slice that changes filament nowhere, stops for nothing.
90
+ if (colours < 2 || changes === 0) return {};
91
+ const feeds = feed.ams_slots > 0 ? feed.ams_slots : feed.external;
92
+ const base = { colours, ...(changes !== undefined ? { filament_changes: changes } : {}), source: feed.source };
93
+ const stops = changes !== undefined ? `${changes} time${changes === 1 ? "" : "s"}` : "at each colour change";
94
+ if (!feed.known)
95
+ return { facts: { ...base, printer: "unknown" },
96
+ note: `This prints in ${colours} colours${changes !== undefined ? ` and changes filament ${changes} time${changes === 1 ? "" : "s"}` : ""}. Without an AMS, the printer stops ${changes !== undefined ? "for each change" : "at each colour change"} for you to swap filament: print it in one colour, or each colour as its own part.` };
97
+ if (feed.ams_slots === 0 && feed.external > 1 && colours <= feed.external)
98
+ return { facts: { ...base, printer: "unknown", feeds, source: `${feed.source}; its ${feed.external} external spools feed ${colours} colours only with each colour on its own nozzle` },
99
+ note: `This prints in ${colours} colours. Without an AMS it needs each colour on its own nozzle, or it stops ${stops} for you to swap filament.` };
100
+ // A dual-nozzle printer can also feed its other nozzle's external spool beside its AMS trays, depending on the plate's
101
+ // nozzle bindings, which aren't read here (Codex review, #170): those colours are flagged, not refused.
102
+ if (feed.ams_slots > 0 && feed.external > 1 && colours > feeds && colours <= feeds + feed.external - 1)
103
+ return { facts: { ...base, printer: "unknown", feeds: feeds + feed.external - 1, source: `${feed.source}; the other nozzle's external spool can feed one more colour, depending on the plate's nozzle bindings` },
104
+ note: `This prints in ${colours} colours, one more than the AMS holds. It needs that colour on the other nozzle's external spool, or it stops for you to swap filament.` };
105
+ if (feeds >= colours) return { facts: { ...base, printer: "feeds-all", feeds } };
106
+ const plain = feed.ams_slots === 0
107
+ ? `This prints in ${colours} colours. Your printer has no AMS, so it would stop ${stops} for you to change filament. Print it in one colour instead, or print each colour as its own part.`
108
+ : `This prints in ${colours} colours, but your printer can hold ${feeds} filaments, so it would stop for you to change filament by hand. Print it in fewer colours, or print each colour as its own part.`;
109
+ if (manual)
110
+ return { facts: { ...base, printer: "too-few-feeds", feeds, manual: true },
111
+ note: feed.ams_slots === 0 ? `Your printer has no AMS, so this print stops ${stops} for you to change filament.` : `This print stops for you to change filament by hand.` };
112
+ const facts = { ...base, printer: "too-few-feeds" as const, feeds };
113
+ const refusal = new FilamentSlotsError(colours, feeds, { plain, changes });
114
+ refusal.feed = facts;
115
+ return { facts, refusal };
116
+ }
@@ -0,0 +1,187 @@
1
+ import { promises as fs } from "node:fs";
2
+
3
+ /**
4
+ * Where a slice's "floating regions" warning comes from. Bambu Studio and OrcaSlicer say only that an object "has
5
+ * floating regions" (a layer island with nothing under it); a design worker then rebuilt and re-sliced six times
6
+ * chasing specks it could not see (scan-to-make #859, pass B). This finds them in the STL itself: each downward-facing
7
+ * low point of the surface that starts above the plate, with how far its surface hangs below the point where it joins
8
+ * something lower (its depth). The same mesh, the same places, so one fix can be aimed.
9
+ *
10
+ * Coordinates are the STL's own, in millimetres, with z measured from the model's lowest point (where the slicer
11
+ * puts the plate). Shared by bambu-printer-mcp and mcp-3D-printer-server.
12
+ */
13
+ /** One floating region: z where it starts (its lowest point), how far it hangs, and the box of what hangs (STL x, y; z from the model's lowest point). */
14
+ export interface FloatingRegion { z: number; depth_mm: number; box_mm: { min: [number, number, number]; max: [number, number, number] } }
15
+ export interface FloatingRegions {
16
+ /** The deepest regions first, at most `limit`; z from the model's lowest point. */
17
+ regions: FloatingRegion[];
18
+ /** All the low points found, before the limit. */
19
+ count: number;
20
+ /** The STL's lowest z, which the slicer moves to the plate. */
21
+ model_min_z: number;
22
+ }
23
+
24
+ /** About 500k binary triangles: the search runs between slicer calls, on the server's own thread. */
25
+ const MAX_BYTES = 25 * 1024 * 1024;
26
+
27
+ /** Triangles of a binary or ASCII STL, as a flat array of 9 numbers each. */
28
+ export function stlTriangles(bytes: Buffer): Float64Array {
29
+ const ascii = /^\s*solid\b/.test(bytes.subarray(0, 256).toString("latin1")) && bytes.includes("facet");
30
+ if (bytes.length >= 84) {
31
+ const n = bytes.readUInt32LE(80);
32
+ // Binary: exactly sized, or sized with trailing bytes some exporters add, unless it reads as ASCII.
33
+ if (84 + n * 50 === bytes.length || (84 + n * 50 < bytes.length && !ascii)) {
34
+ const out = new Float64Array(n * 9);
35
+ for (let i = 0; i < n; i++) for (let k = 0; k < 9; k++) out[i * 9 + k] = bytes.readFloatLE(84 + i * 50 + 12 + k * 4);
36
+ return out;
37
+ }
38
+ }
39
+ const text = bytes.toString("latin1");
40
+ if (!/^\s*solid/.test(text)) throw new Error("not an STL file");
41
+ const values: number[] = [];
42
+ for (const match of text.matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/g)) values.push(Number(match[1]), Number(match[2]), Number(match[3]));
43
+ if (!values.length || values.length % 9 || values.some(v => !Number.isFinite(v))) throw new Error("malformed ASCII STL");
44
+ return Float64Array.from(values);
45
+ }
46
+
47
+ /**
48
+ * The floating low points of a triangle mesh. A sweep from the bottom up joins vertices into connected pieces of the
49
+ * surface below each height; a piece that starts above `plate_mm` is a low point, and its depth is how far up it
50
+ * reaches before it joins a piece that started lower (or the whole of it, if it never does: a body in mid-air).
51
+ * Only low points whose surface faces down count (the floor of a bowl or of a closed void faces up), and only
52
+ * those deeper than `min_depth_mm` (about one layer: shallower bumps fall inside the layer that already has material).
53
+ */
54
+ export function floatingRegions(triangles: Float64Array, options: { plate_mm?: number; min_depth_mm?: number; merge_mm?: number; limit?: number } = {}): FloatingRegions {
55
+ const plate = options.plate_mm ?? 0.3, minDepth = options.min_depth_mm ?? 0.2, merge = options.merge_mm ?? 2, limit = options.limit ?? 12;
56
+ const nTri = Math.floor(triangles.length / 9);
57
+ // Weld the triangle soup by position.
58
+ const index = new Map<string, number>();
59
+ const xyz: number[] = [];
60
+ const corner = new Int32Array(nTri * 3);
61
+ for (let i = 0; i < nTri * 3; i++) {
62
+ const x = triangles[i * 3], y = triangles[i * 3 + 1], z = triangles[i * 3 + 2];
63
+ const key = `${Math.round(x * 1e4)},${Math.round(y * 1e4)},${Math.round(z * 1e4)}`;
64
+ let v = index.get(key);
65
+ if (v === undefined) { v = xyz.length / 3; index.set(key, v); xyz.push(x, y, z); }
66
+ corner[i] = v;
67
+ }
68
+ const nV = xyz.length / 3;
69
+ if (!nV) return { regions: [], count: 0, model_min_z: 0 };
70
+ let minZ = Infinity;
71
+ for (let v = 0; v < nV; v++) minZ = Math.min(minZ, xyz[v * 3 + 2]);
72
+ // Neighbours, and each vertex's area-weighted normal z (downward-facing where negative).
73
+ const neighbours: number[][] = Array.from({ length: nV }, () => []);
74
+ const normalZ = new Float64Array(nV);
75
+ for (let t = 0; t < nTri; t++) {
76
+ const a = corner[t * 3], b = corner[t * 3 + 1], c = corner[t * 3 + 2];
77
+ if (a === b || b === c || a === c) continue;
78
+ const ux = xyz[b * 3] - xyz[a * 3], uy = xyz[b * 3 + 1] - xyz[a * 3 + 1];
79
+ const vx = xyz[c * 3] - xyz[a * 3], vy = xyz[c * 3 + 1] - xyz[a * 3 + 1];
80
+ const nz = ux * vy - uy * vx; // twice the area times the normal's z
81
+ for (const [p, q] of [[a, b], [b, c], [c, a]]) { neighbours[p].push(q); neighbours[q].push(p); }
82
+ normalZ[a] += nz; normalZ[b] += nz; normalZ[c] += nz;
83
+ }
84
+ // Union-find over vertices in rising z; each piece remembers its lowest vertex.
85
+ const order = Array.from({ length: nV }, (_, i) => i).sort((p, q) => xyz[p * 3 + 2] - xyz[q * 3 + 2] || p - q);
86
+ const parent = new Int32Array(nV).fill(-1);
87
+ const lowest = new Int32Array(nV);
88
+ const find = (v: number): number => { while (parent[v] !== v) { parent[v] = parent[parent[v]]; v = parent[v]; } return v; };
89
+ const z = (v: number) => xyz[v * 3 + 2];
90
+ const found: { v: number; depth: number }[] = [];
91
+ const consider = (root: number, depth: number) => {
92
+ const low = lowest[root];
93
+ if (z(low) - minZ > plate && depth >= minDepth && normalZ[low] < 0)
94
+ found.push({ v: low, depth });
95
+ };
96
+ for (const v of order) {
97
+ parent[v] = v; lowest[v] = v;
98
+ for (const n of neighbours[v]) {
99
+ if (parent[n] < 0) continue;
100
+ const a = find(v), b = find(n);
101
+ if (a === b) continue;
102
+ // The piece that started higher ends here: it hung down by the height climbed to reach this join.
103
+ const [keep, end] = z(lowest[a]) <= z(lowest[b]) ? [a, b] : [b, a];
104
+ consider(end, z(v) - z(lowest[end]));
105
+ parent[end] = keep;
106
+ }
107
+ }
108
+ // Pieces that never joined a lower one: separate bodies; the one holding the lowest point sits on the plate.
109
+ const tops = new Map<number, number>();
110
+ for (let v = 0; v < nV; v++) { const r = find(v); tops.set(r, Math.max(tops.get(r) ?? -Infinity, z(v))); }
111
+ for (const [root, top] of tops) consider(root, top - z(lowest[root]));
112
+ /**
113
+ * The box of what hangs: the surface walked from the low point through every vertex below the height where it joins
114
+ * the rest, with each edge that crosses that height cut there. The same for any facet order (Codex review, #169).
115
+ */
116
+ const hanging = (start: number, top: number) => {
117
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
118
+ const add = (p: number[]) => { for (let k = 0; k < 3; k++) { lo[k] = Math.min(lo[k], p[k]); hi[k] = Math.max(hi[k], p[k]); } };
119
+ const seen = new Uint8Array(nV);
120
+ const stack = [start];
121
+ seen[start] = 1;
122
+ while (stack.length) {
123
+ const u = stack.pop()!;
124
+ const pu = [xyz[u * 3], xyz[u * 3 + 1], xyz[u * 3 + 2]];
125
+ add(pu);
126
+ for (const w of neighbours[u]) {
127
+ if (z(w) < top) { if (!seen[w]) { seen[w] = 1; stack.push(w); } continue; }
128
+ const f = (top - pu[2]) / (z(w) - pu[2] || 1);
129
+ add([pu[0] + (xyz[w * 3] - pu[0]) * f, pu[1] + (xyz[w * 3 + 1] - pu[1]) * f, top]);
130
+ }
131
+ }
132
+ return { lo, hi };
133
+ };
134
+ // Merge low points within merge_mm of a deeper one; deepest first.
135
+ found.sort((p, q) => q.depth - p.depth);
136
+ const kept: typeof found = [];
137
+ for (const f of found) {
138
+ const near = kept.some(k => Math.hypot(xyz[k.v * 3] - xyz[f.v * 3], xyz[k.v * 3 + 1] - xyz[f.v * 3 + 1], z(k.v) - z(f.v)) <= merge);
139
+ if (!near) kept.push(f);
140
+ }
141
+ const r2 = (n: number) => Math.round(n * 100) / 100;
142
+ return {
143
+ regions: kept.slice(0, limit).map(({ v, depth }) => ({ v, depth, ...hanging(v, z(v) + depth) })).map(({ v, depth, lo: l, hi: h }) => ({
144
+ z: r2(z(v) - minZ), depth_mm: r2(depth),
145
+ box_mm: { min: [r2(l[0]), r2(l[1]), r2(l[2] - minZ)] as [number, number, number], max: [r2(h[0]), r2(h[1]), r2(h[2] - minZ)] as [number, number, number] },
146
+ })),
147
+ count: kept.length,
148
+ model_min_z: r2(minZ),
149
+ };
150
+ }
151
+
152
+ /** The slicer said a model has floating regions or small islands: a cosmetic warning this rule bounds. */
153
+ export function isFloatingWarning(message: string | undefined): boolean {
154
+ return !!message && /floating regions?|small islands?|isolated islands?/i.test(message);
155
+ }
156
+
157
+ export const SLICE_WARNING_RULE = "A cosmetic warning (floating regions, small islands) gets one targeted fix and one re-slice, then stops: if it remains, report it in the result or slice with supports on. Do not rebuild and re-slice to chase it. A region that is a separate body in mid-air, or on a feature that carries load or makes a fit, is not cosmetic: fix that one properly.";
158
+
159
+ /**
160
+ * What slice_stl adds to a slice that worked but warned about floating regions: the rule above, and where the
161
+ * regions are when the input is an STL the slicer did not turn (orient, rotate). Never throws: a location it
162
+ * cannot find is left out, with why.
163
+ */
164
+ export async function floatingWarningFacts(
165
+ report: { failed: boolean; message?: string } | undefined,
166
+ modelPath: string,
167
+ turned: boolean,
168
+ ): Promise<Record<string, unknown>> {
169
+ if (!report || report.failed || !isFloatingWarning(report.message)) return {};
170
+ const base = { next: SLICE_WARNING_RULE };
171
+ if (!/\.stl$/i.test(modelPath)) return { ...base, floating_regions_unlocated: "Only an STL input is located; this was a 3MF." };
172
+ if (turned) return { ...base, floating_regions_unlocated: "The slicer turned or scaled the model (orient, rotate or scale), so the STL's own coordinates would mislead." };
173
+ try {
174
+ const stat = await fs.stat(modelPath);
175
+ if (stat.size > MAX_BYTES) return { ...base, floating_regions_unlocated: "The STL is too large to search." };
176
+ const located = floatingRegions(stlTriangles(await fs.readFile(modelPath)));
177
+ return {
178
+ ...base,
179
+ floating_regions: {
180
+ ...located,
181
+ frame: "Each region starts at z and hangs depth_mm below where it joins the rest; box_mm bounds what hangs. x and y are the STL's own millimetres; z is millimetres above its lowest point, which the slicer puts on the plate.",
182
+ },
183
+ };
184
+ } catch (error) {
185
+ return { ...base, floating_regions_unlocated: `Could not read the STL: ${error instanceof Error ? error.message : String(error)}` };
186
+ }
187
+ }
@@ -24,6 +24,7 @@
24
24
  * fail loud rather than producing dangerous gcode for hardware we don't own.
25
25
  */
26
26
 
27
+ import { FilamentSlotsError } from "../refusal.js";
27
28
  import fs from "node:fs/promises";
28
29
  import { existsSync, realpathSync } from "node:fs";
29
30
  import path from "node:path";
@@ -736,6 +737,8 @@ export async function flattenForCli(opts: FlattenOptions): Promise<FlattenedProf
736
737
  normalizeForCli(processFlat, "process", opts.processLeaf);
737
738
  filamentFlats.forEach((f, i) => normalizeForCli(f, "filament", opts.filamentLeaves[i]));
738
739
  if (opts.filamentColours && opts.filamentColours.length !== filamentFlats.length) {
740
+ // More colours than slots is a design the loaded filaments can't print in its colours: said plainly (#858).
741
+ if (opts.filamentColours.length > filamentFlats.length) throw new FilamentSlotsError(opts.filamentColours.length, filamentFlats.length);
739
742
  throw new Error(
740
743
  `${opts.filamentColours.length} filament colours were supplied for ${filamentFlats.length} filament slots.`
741
744
  );
@@ -83,6 +83,8 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
83
83
  slice_with_template: hints(false, true, false, true),
84
84
  // New 3MF at a caller-chosen path; never overwrites, so a repeat fails and changes nothing.
85
85
  counterpart_make_3mf: hints(false, false, true, false),
86
+ // A new folder of STLs each call, inside a caller-chosen folder; never overwrites.
87
+ counterpart_part_meshes: hints(false, false, false, false),
86
88
  // Copies into the template registry, replacing a template of the same name.
87
89
  save_template: hints(false, true, true, false),
88
90
  // Replaces BAMBU_DEFAULT_CONNECTION_MODE/TYPE in .env and in this process.