bambu-printer-mcp 1.1.62 → 1.1.64

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
@@ -1,6 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { CAMERA_STREAM_TOOLS } from "./printers/camera-tools.js";
3
3
  import { withAnnotations } from "./tool-annotations.js";
4
+ import { withRemote } from "./counterpart/remote.js";
5
+ import { slicedFileFacts, slicerReport } from "./counterpart/sliced-file.js";
6
+ /** The slicer's verdict beside its result.json (`slicer_report`). */
7
+ function reportOf(result) {
8
+ const report = slicerReport(result);
9
+ return report ? { slicer_report: report } : {};
10
+ }
11
+ function withSlicerReport(sliced) {
12
+ return { ...sliced, ...reportOf(sliced.slicer_result) };
13
+ }
4
14
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
15
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
16
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
@@ -30,6 +40,9 @@ import { isDualNozzleModel } from "./safety/limits.js";
30
40
  import { withPrinterOperation, withPrintSnapshot, uniquePrintName } from "./safety/artifact.js";
31
41
  import { detectProfilesRoot } from "./slicer/profile-flatten.js";
32
42
  import { bambuPrinterInfo, bambuSliceCapabilities } from "./counterpart/info.js";
43
+ import { DISCOVER_OUTPUT_SCHEMA, discoverBambu } from "./counterpart/discovery.js";
44
+ import { SETUP_FIELDS_OUTPUT_SCHEMA, bambuSetupFields, slicerSetup } from "./counterpart/setup.js";
45
+ import { PROPOSE_FILAMENTS_INPUT_PROPERTIES, PROPOSE_FILAMENTS_OUTPUT_SCHEMA, NO_COLOUR_NAMES, bambuTrayLabel, loadColourNames, proposeFilaments, spoolName } from "./counterpart/filaments.js";
33
46
  import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, SERVER_INSTRUCTIONS } from "./design-guidance.js";
34
47
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
35
48
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
@@ -100,6 +113,7 @@ const SERVER_INFO = {
100
113
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
101
114
  const OUTPUT_SCHEMA_TOOLS = new Set([
102
115
  "counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
116
+ "counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
103
117
  "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
104
118
  "camera_stream_start", "camera_frame", "camera_stream_stop",
105
119
  ]);
@@ -241,6 +255,61 @@ const FILAMENT_MODEL_CODES = {
241
255
  };
242
256
  const COLLAR_CHARM_POLICY = getCollarCharmRolePolicy();
243
257
  let filamentProfileIndexCache = null;
258
+ /** The configured slicer's BBL filament profile folder, when the slicer configuration resolves. */
259
+ function filamentProfileDirectory() {
260
+ try {
261
+ const { slicerType, slicerPath } = resolveSlicerConfig(undefined);
262
+ return path.join(detectProfilesRoot(slicerPath, slicerType), "BBL", "filament");
263
+ }
264
+ catch {
265
+ return undefined;
266
+ }
267
+ }
268
+ /** An executable path, or a bare command found on PATH. */
269
+ function executableExists(command) {
270
+ if (!command)
271
+ return false;
272
+ if (command.includes("/") || command.includes("\\"))
273
+ return fs.existsSync(command);
274
+ return (process.env.PATH ?? "").split(path.delimiter).some(dir => dir && fs.existsSync(path.join(dir, command)));
275
+ }
276
+ /** A Bambu profile tree: BBL's machine profiles, or Orca's packed BBL.opc. */
277
+ function bblProfilesAt(root) {
278
+ return fs.existsSync(path.join(root, "BBL", "machine")) || fs.existsSync(path.join(root, "BBL.opc"));
279
+ }
280
+ /** The slicer this server would run now and the settings that choose it, for counterpart_setup_fields. */
281
+ function slicerSetupNow() {
282
+ let config;
283
+ try {
284
+ config = resolveSlicerConfig(undefined);
285
+ }
286
+ catch {
287
+ config = { slicerType: String(DEFAULT_SLICER_TYPE), slicerPath: "" };
288
+ }
289
+ if (config.slicerType === "orca-slicer-api")
290
+ return slicerSetup({ types: SLICER_TYPES, type: config.slicerType, found: Boolean(process.env.SLICER_API_URL), remote: true });
291
+ const bbl = ["bambustudio", "orcaslicer", "orcaslicer-bambulab"].includes(config.slicerType);
292
+ let profilesRoot;
293
+ try {
294
+ profilesRoot = bbl ? detectProfilesRoot(config.slicerPath, config.slicerType) : undefined;
295
+ }
296
+ catch {
297
+ profilesRoot = undefined;
298
+ }
299
+ return slicerSetup({ types: SLICER_TYPES, type: config.slicerType, path: config.slicerPath, found: executableExists(config.slicerPath),
300
+ ...(bbl ? { profilesFound: Boolean(profilesRoot && bblProfilesAt(profilesRoot)), ...(profilesRoot ? { profilesRoot } : {}) } : {}) });
301
+ }
302
+ let colourNamesCache = null;
303
+ /** Bambu Studio's own colour names for its filaments, read once from the configured slicer's profiles. */
304
+ function colourNames() {
305
+ if (colourNamesCache)
306
+ return colourNamesCache;
307
+ const names = loadColourNames(filamentProfileDirectory());
308
+ // A slicer installed later still names its colours: only a table that loaded is kept.
309
+ if (names !== NO_COLOUR_NAMES)
310
+ colourNamesCache = names;
311
+ return names;
312
+ }
244
313
  function buildFilamentProfileIndex() {
245
314
  const byName = new Map();
246
315
  const baseNameByFilamentId = new Map();
@@ -380,6 +449,8 @@ function normalizePrinterFilamentInventory(status, bambuModel, nozzleDiameter) {
380
449
  profile_resolution: profileResolution.resolution,
381
450
  match_confidence: matchConfidence,
382
451
  display_name: displayParts.length > 0 ? displayParts.join(" ") : "empty/unknown",
452
+ label: amsId !== null && trayId !== null ? bambuTrayLabel(amsId, trayId) : null,
453
+ spool_name: trayType ? spoolName(traySubBrands || trayType, trayInfoIdx && trayColor ? colourNames().spool(trayInfoIdx, trayColor) : undefined) : null,
383
454
  profile_candidates: profileResolution.paths,
384
455
  });
385
456
  }
@@ -2889,6 +2960,44 @@ class BambuPrinterMCPServer {
2889
2960
  },
2890
2961
  outputSchema: PRINTER_INFO_OUTPUT_SCHEMA
2891
2962
  },
2963
+ {
2964
+ name: "counterpart_discover_printers",
2965
+ description: "Counterpart contract (counterpart/1): Bambu printers on the local network, from their own SSDP announcements (UDP 2021), with serial, model (as bambu_model names it), name and firmware. Listens for duration_ms (default 4000). network is \"unavailable\" when another app holds the port. Never connects to or authenticates with a printer.",
2966
+ inputSchema: {
2967
+ type: "object",
2968
+ properties: { duration_ms: { type: "integer", minimum: 500, maximum: 15000, description: "How long to listen (default 4000)." } },
2969
+ additionalProperties: false
2970
+ },
2971
+ outputSchema: DISCOVER_OUTPUT_SCHEMA
2972
+ },
2973
+ {
2974
+ name: "counterpart_setup_fields",
2975
+ description: "Counterpart contract (counterpart/1): the printers this server drives and the settings it reads for each, by .env variable name (first canonical, then aliases): label, hint, whether required, the model choices and the model each serial-number prefix names. Pass serial to get the model it names. Sends nothing to a printer and returns no configured values.",
2976
+ inputSchema: {
2977
+ type: "object",
2978
+ properties: { serial: { type: "string", maxLength: 64, description: "A Bambu serial number: model is the one it names, when known." } },
2979
+ additionalProperties: false
2980
+ },
2981
+ outputSchema: SETUP_FIELDS_OUTPUT_SCHEMA
2982
+ },
2983
+ {
2984
+ name: "counterpart_propose_filaments",
2985
+ description: "Counterpart contract (counterpart/1): which loaded AMS spool prints each of a model's colours, before slicing. Reads the live AMS once. trays lists the spools a person may choose (label like \"A2\", a person-readable name, colour, material, feed). proposal gives each filament its nearest spool in OKLab colour with the asked-for material preferred, and a verdict: same-colour, closest (that colour isn't loaded; note says so), no-colour or none. One print feeds from one source. Pass chosen to check the person's spools against what is loaded now; mapping then lists every filament slot's spool (painted slots included), and problems says why a choice can't print.",
2986
+ inputSchema: {
2987
+ type: "object",
2988
+ properties: {
2989
+ ...PROPOSE_FILAMENTS_INPUT_PROPERTIES,
2990
+ bambu_model: { type: "string", description: "Printer model; defaults to BAMBU_MODEL. Selects the filament profiles that decide which spools can slice." },
2991
+ nozzle_diameter: { type: "string", description: "Nozzle diameter (default NOZZLE_DIAMETER or 0.4)." },
2992
+ host: { type: "string", description: "Hostname or IP of the printer (default: value from env)" },
2993
+ bambu_serial: { type: "string", description: "Serial number (default: value from env)" },
2994
+ bambu_token: { type: "string", description: "Access token (default: value from env); never returned." }
2995
+ },
2996
+ required: ["filaments"],
2997
+ additionalProperties: false
2998
+ },
2999
+ outputSchema: PROPOSE_FILAMENTS_OUTPUT_SCHEMA
3000
+ },
2892
3001
  {
2893
3002
  name: "counterpart_print_route",
2894
3003
  description: "Counterpart contract (counterpart/1): how this server reaches the printer for prints and for Stop/Pause/Resume. route is \"lan\" (the local network through FULU's BambuNetwork bridge, or the configured X2D native or Bambu Connect mode), \"cloud\" (Bambu Cloud through FULU's bridge) or \"developer\" (the local network straight to a printer in LAN Only + Developer Mode, whose Pause, Resume and Stop need no Bambu app). options lists each with its label, whether it can be chosen here (and why not) and what controls do on it; choices lists the ids that can be chosen. mode and type are BAMBU_DEFAULT_CONNECTION_MODE and BAMBU_DEFAULT_CONNECTION_TYPE as resolved. Pass route to change it: the change applies to the next print and control at once, and is saved to the .env file in this server's working directory when that file exists (savedTo; null otherwise). Sends nothing to the printer.",
@@ -3002,7 +3111,7 @@ class BambuPrinterMCPServer {
3002
3111
  },
3003
3112
  outputSchema: FUSION_EXPORT_OUTPUT_SCHEMA
3004
3113
  }
3005
- ].map(withAnnotations)
3114
+ ].map(withAnnotations).map(withRemote)
3006
3115
  };
3007
3116
  });
3008
3117
  this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
@@ -3148,6 +3257,8 @@ class BambuPrinterMCPServer {
3148
3257
  artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
3149
3258
  selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
3150
3259
  inspection,
3260
+ // The plate's estimate and slice settings, and the file's plate count, read here so clients don't parse slicer files.
3261
+ sliced: await slicedFileFacts(snapshot, plateIndex),
3151
3262
  ...(preview ? { preview } : {}),
3152
3263
  };
3153
3264
  });
@@ -3810,8 +3921,9 @@ class BambuPrinterMCPServer {
3810
3921
  const sliced = await this.stlManipulator.sliceSTLWithResult(String(args.stl_path), slicerType, slicerPath, activeSlicerProfile, undefined, // progressCallback
3811
3922
  printerPreset, sliceBambuOptions);
3812
3923
  await progressNotifications;
3813
- // The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim.
3814
- return { content: [{ type: "text", text: sliced.path }], structuredContent: sliced };
3924
+ // The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim, and
3925
+ // slicer_report its verdict and words, so clients don't read the slicer's format.
3926
+ return { content: [{ type: "text", text: sliced.path }], structuredContent: withSlicerReport(sliced) };
3815
3927
  }
3816
3928
  case "print_3mf": {
3817
3929
  if (!args?.three_mf_path) {
@@ -4078,6 +4190,35 @@ class BambuPrinterMCPServer {
4078
4190
  case "blender_mcp_edit_model":
4079
4191
  result = await this.blender.edit(args ?? {}, this.resolveExecutableSelectorArg(args?.bridge_command, "blender_mcp_edit_model", "bridge_command", true) ?? (!process.env.BLENDER_MCP_COMMAND?.trim() ? this.runtimeConfig.blenderBridgeCommand : undefined), extra.signal);
4080
4192
  break;
4193
+ case "counterpart_discover_printers": {
4194
+ const requested = Number(args?.duration_ms);
4195
+ const found = await discoverBambu(Number.isFinite(requested) ? requested : 4000);
4196
+ // Only models bambu_model accepts: the X1 (serial 00W) has none, so it stays unset.
4197
+ result = { contract: "counterpart/1", network: found.state, printers: found.printers.map(({ model, ...printer }) => ({ ...printer, ...(model && VALID_BAMBU_MODELS.includes(model) ? { model } : {}) })) };
4198
+ break;
4199
+ }
4200
+ case "counterpart_setup_fields":
4201
+ result = bambuSetupFields({ server: SERVER_INFO, models: VALID_BAMBU_MODELS, slicer: slicerSetupNow(), ...(typeof args?.serial === "string" ? { serial: args.serial } : {}) });
4202
+ break;
4203
+ case "counterpart_propose_filaments": {
4204
+ const requestedModel = (String(args?.bambu_model ?? DEFAULT_BAMBU_MODEL ?? "")).trim().toLowerCase();
4205
+ const normalizedModel = requestedModel ? validateBambuModel(requestedModel) : undefined;
4206
+ const inventory = await this.getResolvedPrinterFilamentInventory(host, bambuSerial, bambuToken, normalizedModel, String(args?.nozzle_diameter || DEFAULT_NOZZLE_DIAMETER));
4207
+ const trays = inventory.trays.flatMap(tray => {
4208
+ const colour = normalizeRgbColor(tray.tray_color);
4209
+ if (!tray.loaded || tray.slot === null || !colour || !tray.tray_type || !tray.label)
4210
+ return [];
4211
+ // print_3mf's tray value: an AMS-HT unit (id 128 and up, one tray) is its unit id, not ams_id × 4 + tray.
4212
+ const slot = tray.ams_id !== null && tray.ams_id >= 128 ? tray.ams_id : tray.slot;
4213
+ return [{ slot, label: tray.label, name: tray.spool_name ?? tray.tray_type, colour: `#${colour.toUpperCase()}`,
4214
+ material: tray.tray_type, filamentId: tray.tray_info_idx ?? "", feed: "ams", sliceable: Boolean(tray.resolved_profile_path),
4215
+ ...(tray.resolved_profile_path ? { profile: tray.resolved_profile_path } : {}) }];
4216
+ });
4217
+ result = proposeFilaments({ trays, filaments: Array.isArray(args?.filaments) ? args.filaments : [],
4218
+ ...(Array.isArray(args?.painted) ? { painted: args.painted } : {}), ...(Array.isArray(args?.chosen) ? { chosen: args.chosen } : {}),
4219
+ sliced: args?.sliced === true, names: colourNames() });
4220
+ break;
4221
+ }
4081
4222
  case "counterpart_printer_info":
4082
4223
  result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
4083
4224
  break;
@@ -4167,7 +4308,7 @@ class BambuPrinterMCPServer {
4167
4308
  tool: name,
4168
4309
  ...(error instanceof PrinterRefusal ? { code: error.code } : {}),
4169
4310
  // The slicer's own result.json; the message starts with its error_string and warnings.
4170
- ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult } : {}),
4311
+ ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult, ...reportOf(error.slicerResult) } : {}),
4171
4312
  };
4172
4313
  // MCP clients validate structuredContent against a declared outputSchema even on
4173
4314
  // errors (SDK 1.32 Client.callTool), so those tools return the error as text only.
@@ -1,4 +1,5 @@
1
1
  import { BambuClient } from "bambu-node";
2
+ export declare const MODEL_IDS: Record<string, string>;
2
3
  export declare const SERIAL_MODELS: Record<string, string>;
3
4
  /** Only raw reports received after this request are evidence. Never read printer.data here. */
4
5
  export declare function readFreshPrinterStatus(printer: BambuClient, serial: string, timeoutMs?: number): Promise<any>;
@@ -3,7 +3,7 @@ import { HIDDEN_HMS } from "./hidden-hms.js";
3
3
  import { GetVersionCommand, PushAllCommand } from "bambu-node";
4
4
  import { isDualNozzleModel, normalizeMaterial, normalizeModel } from "./limits.js";
5
5
  const MAX_REPORT_AGE_MS = 15000;
6
- const MODEL_IDS = {
6
+ export const MODEL_IDS = {
7
7
  O1C: "H2C", O1C2: "H2C", O1D: "H2D", O1E: "H2D Pro", O1S: "H2S", N6: "X2D",
8
8
  N2S: "A1", A1M: "A1 Mini", C11: "P1P", C12: "P1S", C13: "X1E", "BL-P001": "X1C", "BL-P002": "X1",
9
9
  };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Finished slices kept for reuse: slicing the same model the same way again (Print Again, or Print after a
3
+ * client's estimate) restores the slicer's outputs instead of running it. A slicer run is identified by exactly
4
+ * what it was given: the slicer executable (its path, size and modification time, so an update slices again),
5
+ * this server's version, and its full argument list, with every input file replaced by its content hash and every
6
+ * output location by a placeholder. Profiles, filament files, the model and generated override files are all
7
+ * arguments, so editing any of them slices again. A run whose arguments name any other directory (its contents
8
+ * can't be hashed) is never cached, nor is a failed slice. Presets the slicer finds by itself, not named in its
9
+ * arguments (its own bundled system presets), count through the executable: a slicer update slices again.
10
+ *
11
+ * SLICE_CACHE=off turns it off; SLICE_CACHE_DIR moves it (default ~/.cache/<package name>/slices). The newest
12
+ * SLICE_CACHE_ENTRIES (default 16) slices are kept.
13
+ */
14
+ export interface SlicerRun {
15
+ command: string;
16
+ args: string[];
17
+ /** What the slicer writes, kept and restored: files, or directories it fills. */
18
+ outputs: string[];
19
+ /** Folders it writes into that aren't kept as a whole (an --outputdir shared with other files). */
20
+ locations?: string[];
21
+ }
22
+ export declare function sliceCacheRoot(): string;
23
+ /** The run's cache key, or undefined when it can't be identified exactly (then it is never cached). */
24
+ export declare function sliceCacheKey(run: SlicerRun): Promise<string | undefined>;
25
+ /** Puts a kept slice's outputs where this run would write them; false when there is none. */
26
+ export declare function restoreSlice(key: string, run: SlicerRun): Promise<boolean>;
27
+ /** Keeps a finished slice's outputs, whole or not at all; a failure to keep it never fails the slice. */
28
+ export declare function keepSlice(key: string, run: SlicerRun): Promise<void>;
@@ -0,0 +1,178 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ const KEY_VERSION = 1;
6
+ /** This server's package name and version: a new release slices again. */
7
+ const PACKAGE = (() => {
8
+ try {
9
+ const value = JSON.parse(fs.readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
10
+ return { name: String(value.name ?? "printer-mcp"), version: String(value.version ?? "") };
11
+ }
12
+ catch {
13
+ return { name: "printer-mcp", version: "" };
14
+ }
15
+ })();
16
+ function enabled() {
17
+ return !/^(?:off|0|false|no)$/i.test(process.env.SLICE_CACHE ?? "");
18
+ }
19
+ export function sliceCacheRoot() {
20
+ return process.env.SLICE_CACHE_DIR || path.join(os.homedir(), ".cache", PACKAGE.name, "slices");
21
+ }
22
+ function entriesKept() {
23
+ const value = Number(process.env.SLICE_CACHE_ENTRIES);
24
+ return Number.isInteger(value) && value > 0 ? value : 16;
25
+ }
26
+ async function fileHash(file) {
27
+ const hash = createHash("sha256");
28
+ for await (const chunk of fs.createReadStream(file))
29
+ hash.update(chunk);
30
+ return hash.digest("hex");
31
+ }
32
+ function onPath(command) {
33
+ if (path.isAbsolute(command) || command.includes("/") || command.includes("\\"))
34
+ return path.resolve(command);
35
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
36
+ if (!dir)
37
+ continue;
38
+ const candidate = path.join(dir, command);
39
+ try {
40
+ if (fs.statSync(candidate).isFile())
41
+ return candidate;
42
+ }
43
+ catch { /* next */ }
44
+ }
45
+ return undefined;
46
+ }
47
+ /** The run's cache key, or undefined when it can't be identified exactly (then it is never cached). */
48
+ export async function sliceCacheKey(run) {
49
+ if (!enabled())
50
+ return undefined;
51
+ // Never a reason for a slice to fail: anything unreadable means this run isn't kept.
52
+ try {
53
+ return await keyOf(run);
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
59
+ async function keyOf(run) {
60
+ const executable = onPath(run.command);
61
+ if (!executable)
62
+ return undefined;
63
+ let binary;
64
+ try {
65
+ binary = await fs.promises.stat(executable);
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ const outputs = run.outputs.map(output => path.resolve(output));
71
+ const places = [...outputs, ...(run.locations ?? []).map(location => path.resolve(location))];
72
+ const part = async (value) => {
73
+ if (!value || value.startsWith("-"))
74
+ return value;
75
+ // A relative path is a file to the slicer too (resolved against this process's directory, as it is).
76
+ const resolved = path.resolve(value);
77
+ // An output or output folder itself: where this run writes, whatever it is called.
78
+ const exact = places.indexOf(resolved);
79
+ if (exact >= 0)
80
+ return `<output ${exact}>`;
81
+ // A file staged inside an output folder (a generated profile, a transformed mesh) is an input: its bytes count.
82
+ const root = places.findIndex(place => resolved.startsWith(place + path.sep));
83
+ let info;
84
+ try {
85
+ info = await fs.promises.stat(resolved);
86
+ }
87
+ catch {
88
+ info = undefined;
89
+ }
90
+ const named = root >= 0 ? `<output ${root}>${resolved.slice(places[root].length)}` : path.isAbsolute(value) ? resolved : value;
91
+ // A file is its bytes (and its extension, which tells the slicer what it is), not its often random name.
92
+ if (info?.isFile())
93
+ return `file${path.extname(resolved).toLowerCase()}#${await fileHash(resolved)}`;
94
+ // A folder's contents can't be hashed: such a run is never cached.
95
+ if (info?.isDirectory())
96
+ return undefined;
97
+ return named;
98
+ };
99
+ const args = [];
100
+ for (const arg of run.args) {
101
+ const parts = [];
102
+ for (const piece of arg.split(";")) {
103
+ const value = await part(piece);
104
+ if (value === undefined)
105
+ return undefined;
106
+ parts.push(value);
107
+ }
108
+ args.push(parts.join(";"));
109
+ }
110
+ return createHash("sha256").update(JSON.stringify({ v: KEY_VERSION, server: PACKAGE,
111
+ slicer: { path: fs.realpathSync(executable), size: binary.size, mtimeMs: binary.mtimeMs }, args })).digest("hex");
112
+ }
113
+ async function touch(target, at) {
114
+ const info = await fs.promises.stat(target);
115
+ if (info.isDirectory())
116
+ for (const name of await fs.promises.readdir(target))
117
+ await touch(path.join(target, name), at);
118
+ await fs.promises.utimes(target, at, at);
119
+ }
120
+ /** Puts a kept slice's outputs where this run would write them; false when there is none. */
121
+ export async function restoreSlice(key, run) {
122
+ const entry = path.join(sliceCacheRoot(), key);
123
+ try {
124
+ const meta = JSON.parse(await fs.promises.readFile(path.join(entry, "meta.json"), "utf8"));
125
+ if (meta.outputs !== run.outputs.length || !Array.isArray(meta.saved))
126
+ return false;
127
+ const saved = new Set(meta.saved.filter((index) => typeof index === "number"));
128
+ // Every output the slicer wrote must still be there, or this is no slice at all.
129
+ for (const index of saved)
130
+ if (!fs.existsSync(path.join(entry, String(index))))
131
+ return false;
132
+ const now = new Date();
133
+ for (const [index, output] of run.outputs.entries()) {
134
+ if (!saved.has(index))
135
+ continue; // the slicer didn't write this one
136
+ await fs.promises.mkdir(path.dirname(output), { recursive: true });
137
+ await fs.promises.cp(path.join(entry, String(index)), output, { recursive: true, force: true });
138
+ // Fresh timestamps on every restored file: a result.json must read as written by this run.
139
+ await touch(output, now);
140
+ }
141
+ await fs.promises.utimes(entry, now, now);
142
+ return true;
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ }
148
+ /** Keeps a finished slice's outputs, whole or not at all; a failure to keep it never fails the slice. */
149
+ export async function keepSlice(key, run) {
150
+ const root = sliceCacheRoot();
151
+ try {
152
+ await fs.promises.mkdir(root, { recursive: true, mode: 0o700 });
153
+ const staging = await fs.promises.mkdtemp(path.join(root, ".staging-"));
154
+ try {
155
+ const saved = [];
156
+ for (const [index, output] of run.outputs.entries()) {
157
+ if (!fs.existsSync(output))
158
+ continue;
159
+ await fs.promises.cp(output, path.join(staging, String(index)), { recursive: true });
160
+ saved.push(index);
161
+ }
162
+ await fs.promises.writeFile(path.join(staging, "meta.json"), JSON.stringify({ outputs: run.outputs.length, saved, keptAt: new Date().toISOString() }));
163
+ await fs.promises.rm(path.join(root, key), { recursive: true, force: true });
164
+ await fs.promises.rename(staging, path.join(root, key));
165
+ }
166
+ finally {
167
+ await fs.promises.rm(staging, { recursive: true, force: true });
168
+ }
169
+ const entries = await Promise.all((await fs.promises.readdir(root)).filter(name => /^[0-9a-f]{64}$/.test(name))
170
+ .map(async (name) => ({ name, at: (await fs.promises.stat(path.join(root, name))).mtimeMs })));
171
+ for (const old of entries.sort((a, b) => b.at - a.at).slice(entriesKept())) {
172
+ await fs.promises.rm(path.join(root, old.name), { recursive: true, force: true });
173
+ }
174
+ }
175
+ catch (error) {
176
+ console.error(`Could not keep this slice for reuse: ${error instanceof Error ? error.message : String(error)}`);
177
+ }
178
+ }
@@ -10,6 +10,7 @@ import { promisify } from 'util';
10
10
  import { EventEmitter } from 'events';
11
11
  import * as crypto from 'crypto';
12
12
  import { execFile } from 'child_process';
13
+ import { keepSlice, restoreSlice, sliceCacheKey } from '../slicer/slice-cache.js';
13
14
  import { flattenForCli, detectProfilesRoot, resolveBblMachineProfile } from '../slicer/profile-flatten.js';
14
15
  import { applyProcessOverrides } from '../slicer/process-overrides.js';
15
16
  import { profileJsonFiles } from '../slicer/profile-files.js';
@@ -1614,7 +1615,18 @@ export class STLManipulator extends EventEmitter {
1614
1615
  default:
1615
1616
  throw new Error(`Unsupported slicer type: ${slicerType}`);
1616
1617
  }
1617
- if (slicerType !== 'orca-slicer-api') {
1618
+ // The Bambu-compatible CLI's slice, kept for reuse: the same model sliced the same way again is restored,
1619
+ // and every check below still runs on it (slice-cache.ts).
1620
+ const cacheRun = cliResult && slicerType !== 'orca-slicer-api'
1621
+ ? { command: slicerPath, args, outputs: [outputFilePath, cliResult.resultPath], locations: [path.dirname(cliResult.resultPath)] } : undefined;
1622
+ const cacheKey = cacheRun ? await sliceCacheKey(cacheRun) : undefined;
1623
+ const restored = !!cacheKey && await restoreSlice(cacheKey, cacheRun);
1624
+ if (restored) {
1625
+ if (progressCallback)
1626
+ progressCallback(90, 'Reusing the same slice of this model');
1627
+ console.error(`Reusing slice ${cacheKey} for: ${slicerPath} ${args.join(' ')}`);
1628
+ }
1629
+ if (slicerType !== 'orca-slicer-api' && !restored) {
1618
1630
  if (progressCallback)
1619
1631
  progressCallback(20, `Executing slicer: ${slicerPath} ${args.join(' ')}`);
1620
1632
  console.error(`Executing: ${slicerPath} ${args.join(' ')}`);
@@ -1668,6 +1680,8 @@ export class STLManipulator extends EventEmitter {
1668
1680
  if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
1669
1681
  throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
1670
1682
  }
1683
+ if (cacheKey && !restored && fs.existsSync(outputFilePath))
1684
+ await keepSlice(cacheKey, cacheRun);
1671
1685
  if (!fs.existsSync(outputFilePath)) {
1672
1686
  throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
1673
1687
  }
@@ -18,6 +18,8 @@ export const TOOL_ANNOTATIONS = {
18
18
  resolve_3mf_ams_slots: READ_OUTSIDE, // reads the live AMS inventory
19
19
  list_printer_files: READ_OUTSIDE,
20
20
  counterpart_print_progress: READ_OUTSIDE,
21
+ counterpart_discover_printers: READ_OUTSIDE, // listens for the printers' own SSDP announcements
22
+ counterpart_propose_filaments: READ_OUTSIDE, // reads the live AMS inventory
21
23
  // connect: true starts the bridge agent, which writes its configuration and device identity and can replace certificates.
22
24
  bambu_network_bridge_status: hints(false, true, true, true),
23
25
  camera_frame: READ_OUTSIDE,
@@ -33,6 +35,7 @@ export const TOOL_ANNOTATIONS = {
33
35
  list_templates: READ_LOCAL,
34
36
  get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
35
37
  counterpart_printer_info: READ_LOCAL, // configuration and capabilities; sends nothing to the printer
38
+ counterpart_setup_fields: READ_LOCAL, // the settings this server reads; no configured values
36
39
  // Local outputs in the server's temporary directory
37
40
  extend_stl_base: LOCAL_OUTPUT,
38
41
  scale_stl: LOCAL_OUTPUT,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.62",
3
+ "version": "1.1.64",
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": {
@@ -0,0 +1,111 @@
1
+ /**
2
+ * counterpart_discover_printers (counterpart/1): Bambu printers on the local network, from their own SSDP
3
+ * announcements (NOTIFY on UDP 2021, and the answers to one M-SEARCH). Bounded and never failing: a port another app
4
+ * holds (Bambu Studio) is "unavailable", not "none found". Never fetches a URL, connects to or authenticates with a printer.
5
+ */
6
+ import { createSocket, type Socket } from "node:dgram";
7
+ import { isIPv4 } from "node:net";
8
+ import { networkInterfaces } from "node:os";
9
+ import { normalizeModel } from "../safety/limits.js";
10
+ import { MODEL_IDS, SERIAL_MODELS } from "../safety/printer-state.js";
11
+ import { COUNTERPART_CONTRACT, PRINTER_KINDS } from "./schemas.js";
12
+
13
+ export type FoundPrinter = {
14
+ kind: typeof PRINTER_KINDS[number]; source: "ssdp" | "bonjour"; name: string; host: string;
15
+ port?: number; serial?: string; model?: string; firmware?: string;
16
+ };
17
+ export type Discovery = { contract: typeof COUNTERPART_CONTRACT; network: "complete" | "unavailable"; printers: FoundPrinter[] };
18
+
19
+ /** This server's model value (bambu_model) for a serial number's first three characters, when it has one. */
20
+ export function modelFromSerial(serial: string | undefined): string | undefined {
21
+ return serial ? normalizeModel(SERIAL_MODELS[serial.trim().slice(0, 3).toUpperCase()] ?? "") : undefined;
22
+ }
23
+ /**
24
+ * DevModel ids Bambu Studio's machine definitions (profiles/BBL/machine/*.json `model_id`) use that the safety identity
25
+ * table doesn't list, for naming a found printer only. Never identity evidence for a print.
26
+ */
27
+ const ANNOUNCED_MODEL_IDS: Record<string, string> = { N1: "A1 Mini", N7: "P2S" };
28
+ /** This server's model value for a DevModel id Bambu Studio's printer definitions use (C12 is the P1S). */
29
+ export function modelFromDevModel(id: string | undefined): string | undefined {
30
+ const key = id?.trim().toUpperCase();
31
+ return key ? normalizeModel(MODEL_IDS[key] ?? ANNOUNCED_MODEL_IDS[key] ?? "") : undefined;
32
+ }
33
+
34
+ export function privateIPv4(value: string): boolean {
35
+ if (!isIPv4(value)) return false;
36
+ const [a, b] = value.split(".").map(Number) as [number, number];
37
+ return a === 10 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31);
38
+ }
39
+
40
+ /** One SSDP packet from a Bambu printer. The sender must be the printer itself (Location equals its address). */
41
+ export function parseBambuAdvert(packet: Buffer, address: string): FoundPrinter | undefined {
42
+ if (packet.length > 8192 || !privateIPv4(address)) return undefined;
43
+ const lines = packet.toString("utf8").split("\r\n");
44
+ if (!["NOTIFY * HTTP/1.1", "HTTP/1.1 200 OK"].includes(lines.shift() ?? "")) return undefined;
45
+ const headers = new Map<string, string>();
46
+ for (const line of lines) {
47
+ if (!line) continue;
48
+ const at = line.indexOf(":");
49
+ if (at < 1) return undefined;
50
+ const key = line.slice(0, at).trim().toLowerCase(), value = line.slice(at + 1).trim();
51
+ if (headers.has(key) || /[\x00-\x1f\x7f]/.test(value)) return undefined;
52
+ headers.set(key, value);
53
+ }
54
+ if (headers.get("location") !== address) return undefined;
55
+ const serial = headers.get("usn"), devModel = headers.get("devmodel.bambu.com");
56
+ if (!serial || !/^[A-Za-z0-9]{1,64}$/.test(serial) || !devModel || devModel.length > 64) return undefined;
57
+ const firmware = headers.get("devversion.bambu.com");
58
+ const model = modelFromDevModel(devModel) ?? modelFromSerial(serial);
59
+ return { kind: "bambu", source: "ssdp", host: address, serial: serial.toUpperCase(), ...(model ? { model } : {}),
60
+ name: (headers.get("devname.bambu.com") || devModel).slice(0, 128),
61
+ ...(firmware && /^\d{2}\.\d{2}\.\d{2}\.\d{2}$/.test(firmware) ? { firmware } : {}) };
62
+ }
63
+
64
+ /** A send completes before the next interface: dgram resolves addresses asynchronously even for IP literals. */
65
+ export async function sendDiscoveryProbes(socket: Pick<Socket, "addMembership" | "setMulticastInterface" | "setMulticastTTL" | "send">, addresses: string[], active: () => boolean) {
66
+ for (const address of addresses) {
67
+ if (!active()) return;
68
+ try {
69
+ socket.addMembership("239.255.255.250", address);
70
+ socket.setMulticastInterface(address); socket.setMulticastTTL(1);
71
+ await new Promise<void>((resolve, reject) => socket.send("M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:2021\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\nST: urn:bambulab-com:device:3dprinter:1\r\n\r\n",
72
+ 2021, "239.255.255.250", error => error ? reject(error) : resolve()));
73
+ } catch { /* Other interfaces can still answer. */ }
74
+ }
75
+ }
76
+
77
+ /** Listens on UDP 2021 for `durationMs` (bounded 500–15000 ms). */
78
+ export function discoverBambu(durationMs = 4000): Promise<{ state: "complete" | "unavailable"; printers: FoundPrinter[] }> {
79
+ const ms = Number.isFinite(durationMs) ? Math.max(500, Math.min(15_000, Math.round(durationMs))) : 4000;
80
+ return new Promise(resolve => {
81
+ const socket = createSocket({ type: "udp4", reuseAddr: true }), found = new Map<string, FoundPrinter>();
82
+ let finished = false;
83
+ const finish = (state: "complete" | "unavailable") => {
84
+ if (finished) return; finished = true; clearTimeout(timer);
85
+ try { socket.close(); } catch { /* not bound yet */ }
86
+ resolve({ state, printers: [...found.values()].sort((a, b) => (a.serial ?? "").localeCompare(b.serial ?? "")) });
87
+ };
88
+ const timer = setTimeout(() => finish("complete"), ms);
89
+ socket.on("error", () => finish("unavailable"));
90
+ socket.on("message", (data, peer) => { const value = parseBambuAdvert(data, peer.address); if (value && found.size < 64) found.set(`${value.serial}@${value.host}`, value); });
91
+ try {
92
+ socket.bind(2021, "0.0.0.0", () => {
93
+ const interfaces = Object.values(networkInterfaces()).flat().filter(nic => nic && !nic.internal && nic.family === "IPv4" && privateIPv4(nic.address));
94
+ void sendDiscoveryProbes(socket, interfaces.map(nic => nic!.address), () => !finished);
95
+ });
96
+ } catch { finish("unavailable"); }
97
+ });
98
+ }
99
+
100
+ export const DISCOVER_OUTPUT_SCHEMA = {
101
+ type: "object" as const,
102
+ properties: {
103
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
104
+ network: { type: "string", enum: ["complete", "unavailable"] },
105
+ printers: { type: "array", items: { type: "object", properties: {
106
+ kind: { type: "string", enum: [...PRINTER_KINDS] }, source: { type: "string", enum: ["ssdp", "bonjour"] }, name: { type: "string" },
107
+ host: { type: "string" }, port: { type: "integer" }, serial: { type: "string" }, model: { type: "string" }, firmware: { type: "string" },
108
+ }, required: ["kind", "source", "name", "host"] } },
109
+ },
110
+ required: ["contract", "network", "printers"],
111
+ };