bambu-printer-mcp 1.1.63 → 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.
@@ -0,0 +1,47 @@
1
+ /**
2
+ * How Counterpart's remote endpoint (`/v1/mcp`) offers each tool to a paired device, declared by this server so a
3
+ * new tool or argument needs no Counterpart release. Sent as each listed tool's `_meta["counterpart/remote"]`:
4
+ *
5
+ * - `scope`: the least device scope that may call the tool: read < design < control < print < raw. The table keeps
6
+ * the classes Counterpart gave these tools by hand before this version, so no paired device gained or lost a tool;
7
+ * `tests/tool-annotations.test.mjs` holds the name floors (a print start is at least print, a raw call raw).
8
+ * - `raisedBy`: boolean arguments that, when true, need a higher scope (`launch` starts Fusion).
9
+ * - `arguments`: argument names that are not plain values, matched at any depth of a call's arguments:
10
+ * `config`: this server's configuration chooses it (the printer it targets, its account, hardware and programs),
11
+ * so a device may not set it; `config-top`: the same, as a top-level argument only (`type`, the printer type);
12
+ * `path`: a local file or folder the tool reads; `output`: one it writes. Any other argument is a plain value.
13
+ * A tool that forwards an open object (an arbitrary RPC payload or another server's tool arguments) declares every
14
+ * configuration name, since any of them may appear inside it.
15
+ */
16
+ export type RemoteScope = "read" | "design" | "control" | "print" | "raw";
17
+ export type ArgumentKind = "config" | "config-top" | "path" | "output";
18
+ export interface RemoteDeclaration {
19
+ scope: RemoteScope;
20
+ raisedBy?: Record<string, RemoteScope>;
21
+ arguments?: Record<string, ArgumentKind>;
22
+ }
23
+ export declare const REMOTE_META_KEY = "counterpart/remote";
24
+ export declare const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>>;
25
+ /**
26
+ * Overrides of a server's own configuration (both printer MCPs use the same names): the printer it targets, its
27
+ * account and credentials, its hardware, and the programs it runs.
28
+ */
29
+ export declare const CONFIG_ARGUMENTS: ReadonlySet<string>;
30
+ /** The argument kinds of one tool, read from its own input schema. */
31
+ export declare function remoteArguments(tool: {
32
+ name: string;
33
+ inputSchema?: unknown;
34
+ }): Record<string, ArgumentKind>;
35
+ /** The declaration for one tool; a tool missing from REMOTE_SCOPES (a bug the tests catch) is raw. */
36
+ export declare function remoteDeclaration(tool: {
37
+ name: string;
38
+ inputSchema?: unknown;
39
+ }): RemoteDeclaration;
40
+ /** The tool with its declaration in `_meta`. */
41
+ export declare function withRemote<T extends {
42
+ name: string;
43
+ inputSchema?: unknown;
44
+ _meta?: Record<string, unknown>;
45
+ }>(tool: T): T & {
46
+ _meta: Record<string, unknown>;
47
+ };
@@ -0,0 +1,141 @@
1
+ export const REMOTE_META_KEY = "counterpart/remote";
2
+ export const REMOTE_SCOPES = {
3
+ // read
4
+ counterpart_discover_printers: "read",
5
+ counterpart_setup_fields: "read",
6
+ counterpart_propose_filaments: "read",
7
+ get_printer_status: "read",
8
+ get_printer_filaments: "read",
9
+ resolve_3mf_ams_slots: "read",
10
+ list_3mf_plate_objects: "read",
11
+ get_stl_info: "read",
12
+ list_templates: "read",
13
+ list_printer_files: "read",
14
+ camera_frame: "read",
15
+ camera_snapshot: "read",
16
+ inspect_print_file: "read",
17
+ blender_mcp_status: "read",
18
+ counterpart_printer_info: "read",
19
+ counterpart_print_progress: "read",
20
+ fusion_mcp_status: "read",
21
+ // design
22
+ slice_stl: "design",
23
+ lay_flat: "design",
24
+ counterpart_make_3mf: "design",
25
+ // control
26
+ bambu_connect_import_file: "control",
27
+ camera_stream_start: "control",
28
+ camera_stream_stop: "control",
29
+ cancel_print: "control",
30
+ pause_print: "control",
31
+ resume_print: "control",
32
+ clear_hms_errors: "control",
33
+ set_print_speed: "control",
34
+ set_airduct_mode: "control",
35
+ reread_ams_rfid: "control",
36
+ set_temperature: "control",
37
+ set_fan_speed: "control",
38
+ set_light: "control",
39
+ set_ams_drying: "control",
40
+ counterpart_print_route: "control",
41
+ fusion_mcp_new_design: "control",
42
+ fusion_mcp_export: "control",
43
+ // print
44
+ extend_stl_base: "print",
45
+ scale_stl: "print",
46
+ rotate_stl: "print",
47
+ get_slice_settings: "print",
48
+ slice_with_template: "print",
49
+ bambu_network_bridge_status: "print",
50
+ print_3mf_bambu_network: "print",
51
+ delete_printer_file: "print",
52
+ upload_file: "print",
53
+ start_print: "print",
54
+ start_print_job: "print",
55
+ skip_objects: "print",
56
+ print_3mf: "print",
57
+ print_collar_charm: "print",
58
+ merge_vertices: "print",
59
+ center_model: "print",
60
+ // raw
61
+ save_template: "raw",
62
+ bambu_network_call: "raw",
63
+ upload_gcode: "raw",
64
+ x2d_native_control: "raw",
65
+ blender_mcp_call: "raw",
66
+ blender_mcp_edit_model: "raw",
67
+ fusion_mcp_call: "raw",
68
+ };
69
+ const RAISED_BY = {
70
+ fusion_mcp_status: { launch: "design" }, // starts Fusion on this computer
71
+ blender_mcp_status: { connect: "design" }, // connects to Blender
72
+ };
73
+ /**
74
+ * Overrides of a server's own configuration (both printer MCPs use the same names): the printer it targets, its
75
+ * account and credentials, its hardware, and the programs it runs.
76
+ */
77
+ export const CONFIG_ARGUMENTS = new Set([
78
+ "host", "port", "api_key", "username", "password", "dev_ip", "dev_id", "bambu_serial", "bambu_token", "user_info",
79
+ "country_code", "connection_type", "connection_mode", "route", "bambu_model", "nozzle_diameter", "nozzle_diameters",
80
+ "bridge_command", "slicer_path", "slicer_type", "ffmpeg_path", "plugin_dir", "runtime_dir", "template_dir",
81
+ "config_filename", "bambu_network_method", "use_ssl_for_mqtt", "use_ssl_for_ftp", "extra_options",
82
+ "allow_mutating_method",
83
+ ]);
84
+ /** Top-level only: the printer type (`type`); a nested `type` is a plain value. */
85
+ const TOP_LEVEL_CONFIG = new Set(["type"]);
86
+ /** Files read whose names don't end in path, dir or file. */
87
+ const FILE_ARGUMENTS = new Set(["filament_profile", "slicer_profile", "load_filaments", "source_f3d"]);
88
+ const isPath = (key) => /(?:path|dir|directory|_file)$/.test(key) || FILE_ARGUMENTS.has(key);
89
+ function kindOf(tool, key, depth) {
90
+ // counterpart_print_route's own `route` is the connection the caller chooses.
91
+ if ((CONFIG_ARGUMENTS.has(key) && !(key === "route" && tool === "counterpart_print_route")) || /config_dir$/.test(key))
92
+ return "config";
93
+ if (depth === 0 && TOP_LEVEL_CONFIG.has(key))
94
+ return "config-top";
95
+ if (!isPath(key))
96
+ return undefined;
97
+ return /^output_|^out_path$|^save_path$/.test(key) ? "output" : "path";
98
+ }
99
+ /** The argument kinds of one tool, read from its own input schema. */
100
+ export function remoteArguments(tool) {
101
+ const kinds = {};
102
+ let open = false;
103
+ const visit = (schema, depth) => {
104
+ if (!schema || typeof schema !== "object")
105
+ return;
106
+ const node = schema;
107
+ // An object whose keys the schema doesn't name (beyond the top level) may carry any argument.
108
+ if (depth > 0 && node.type === "object" && (node.additionalProperties === true || node.additionalProperties === undefined && !node.properties))
109
+ open = true;
110
+ if (depth > 0 && node.additionalProperties && typeof node.additionalProperties === "object")
111
+ open = true;
112
+ for (const [key, child] of Object.entries(node.properties ?? {})) {
113
+ const kind = kindOf(tool.name, key, depth);
114
+ if (kind && !(kinds[key] === "config" && kind === "config-top"))
115
+ kinds[key] = kind;
116
+ visit(child, depth + 1);
117
+ }
118
+ visit(node.items, depth);
119
+ for (const option of [...(node.anyOf ?? []), ...(node.oneOf ?? [])])
120
+ visit(option, depth);
121
+ };
122
+ visit(tool.inputSchema, 0);
123
+ if (open)
124
+ for (const key of CONFIG_ARGUMENTS)
125
+ if (!(key === "route" && tool.name === "counterpart_print_route"))
126
+ kinds[key] ?? (kinds[key] = "config");
127
+ return kinds;
128
+ }
129
+ /** The declaration for one tool; a tool missing from REMOTE_SCOPES (a bug the tests catch) is raw. */
130
+ export function remoteDeclaration(tool) {
131
+ const args = remoteArguments(tool);
132
+ return {
133
+ scope: REMOTE_SCOPES[tool.name] ?? "raw",
134
+ ...(RAISED_BY[tool.name] ? { raisedBy: RAISED_BY[tool.name] } : {}),
135
+ ...(Object.keys(args).length ? { arguments: args } : {}),
136
+ };
137
+ }
138
+ /** The tool with its declaration in `_meta`. */
139
+ export function withRemote(tool) {
140
+ return { ...tool, _meta: { ...(tool._meta ?? {}), [REMOTE_META_KEY]: remoteDeclaration(tool) } };
141
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * What a client shows about a sliced file, read here so it never parses slicer formats itself (Counterpart PRD
3
+ * §8.0 item 9): the selected plate's estimate and slice settings, and how many printable plates the file has.
4
+ * Bambu Studio and OrcaSlicer 3MFs carry them in Metadata/slice_info.config, project_settings.config and the
5
+ * plate's G-code header; a G-code file in its own header and footer comments. Anything not found is left out.
6
+ */
7
+ export interface SlicedFileFacts {
8
+ plate_count?: number;
9
+ estimate?: {
10
+ seconds?: number;
11
+ grams?: number;
12
+ };
13
+ settings: {
14
+ layer_height_mm?: number;
15
+ sparse_infill_percent?: number;
16
+ wall_loops?: number;
17
+ layer_count?: number;
18
+ };
19
+ }
20
+ /** The facts of a sliced 3MF or G-code file for one zero-based plate; what can't be read is left out, never an error. */
21
+ export declare function slicedFileFacts(filePath: string, plateIndex?: number): Promise<SlicedFileFacts>;
22
+ /**
23
+ * Bambu Studio's (or OrcaSlicer's) verdict on a slice, from its result.json: whether it failed, its own words
24
+ * (the error and every plate's warning, verbatim), and how many plates it sliced.
25
+ */
26
+ export interface SlicerReport {
27
+ failed: boolean;
28
+ message?: string;
29
+ plate_count?: number;
30
+ }
31
+ export declare function slicerReport(result: unknown): SlicerReport | undefined;
@@ -0,0 +1,110 @@
1
+ import fs from "node:fs";
2
+ import { loadSafe3mfArchive, readBoundedPrintFile } from "../safety/archive.js";
3
+ const number = (value) => {
4
+ const parsed = typeof value === "number" ? value : typeof value === "string" ? Number.parseFloat(value) : NaN;
5
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
6
+ };
7
+ const first = (value) => Array.isArray(value) ? value[0] : value;
8
+ const defined = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
9
+ function headerSettings(text) {
10
+ const read = (pattern) => number(text.match(pattern)?.[1]);
11
+ const layers = read(/^;\s*(?:total layer number|total layers count|LAYER_COUNT)\s*[:=]\s*(\d+)/im);
12
+ const walls = read(/^;\s*(?:wall_loops|perimeters)\s*=\s*(\d+)/im);
13
+ return defined({
14
+ layer_height_mm: read(/^;\s*layer_height\s*=\s*([\d.]+)/im),
15
+ sparse_infill_percent: read(/^;\s*(?:sparse_infill_density|fill_density)\s*=\s*([\d.]+)%/im),
16
+ wall_loops: walls === undefined ? undefined : Math.trunc(walls),
17
+ layer_count: layers ? Math.trunc(layers) : undefined,
18
+ });
19
+ }
20
+ /** The facts of a sliced 3MF or G-code file for one zero-based plate; what can't be read is left out, never an error. */
21
+ export async function slicedFileFacts(filePath, plateIndex = 0) {
22
+ try {
23
+ return await readFacts(filePath, plateIndex);
24
+ }
25
+ catch {
26
+ return { settings: {} };
27
+ }
28
+ }
29
+ async function readFacts(filePath, plateIndex) {
30
+ const head = Buffer.alloc(4);
31
+ const handle = await fs.promises.open(filePath, "r");
32
+ try {
33
+ await handle.read(head, 0, 4, 0);
34
+ }
35
+ finally {
36
+ await handle.close();
37
+ }
38
+ if (head[0] !== 0x50 || head[1] !== 0x4b) {
39
+ // G-code: PrusaSlicer and Orca write their settings in a footer, others in a header; read both ends.
40
+ const stat = await fs.promises.stat(filePath);
41
+ const size = 256 * 1024;
42
+ const read = async (start) => {
43
+ const buffer = Buffer.alloc(Math.min(size, stat.size));
44
+ const file = await fs.promises.open(filePath, "r");
45
+ try {
46
+ await file.read(buffer, 0, buffer.length, start);
47
+ }
48
+ finally {
49
+ await file.close();
50
+ }
51
+ return buffer.toString("latin1");
52
+ };
53
+ return { plate_count: 1, settings: headerSettings(`${await read(0)}\n${await read(Math.max(0, stat.size - size))}`) };
54
+ }
55
+ const zip = await loadSafe3mfArchive(await readBoundedPrintFile(filePath));
56
+ const plates = new Set(Object.keys(zip.files).flatMap(name => /^Metadata\/plate_([1-9]\d*)\.gcode$/.exec(name)?.[1] ?? []));
57
+ const text = async (name) => zip.file(name)?.async("string");
58
+ let settings = {};
59
+ const project = await text("Metadata/project_settings.config");
60
+ if (project) {
61
+ try {
62
+ const values = JSON.parse(project);
63
+ const infill = String(first(values.sparse_infill_density) ?? "");
64
+ const walls = number(first(values.wall_loops));
65
+ settings = defined({
66
+ layer_height_mm: number(first(values.layer_height)),
67
+ sparse_infill_percent: infill === "" ? undefined : number(infill.replace("%", "")),
68
+ wall_loops: walls === undefined ? undefined : Math.trunc(walls),
69
+ });
70
+ }
71
+ catch { /* the settings stay unknown */ }
72
+ }
73
+ // Only the plate G-code's header, never the whole (often hundreds of MB) as a string.
74
+ const gcode = await zip.file(`Metadata/plate_${plateIndex + 1}.gcode`)?.async("nodebuffer");
75
+ // The project settings are authoritative; the plate's G-code header adds the layer count.
76
+ if (gcode)
77
+ settings = { ...headerSettings(gcode.subarray(0, 64 * 1024).toString("latin1")), ...settings };
78
+ let estimate;
79
+ const info = await text("Metadata/slice_info.config");
80
+ const plate = info?.match(/<plate(?:\s[^>]*)?>[\s\S]*?<\/plate>/g)
81
+ ?.find(block => new RegExp(`<metadata\\s+key=["']index["']\\s+value=["']${plateIndex + 1}["']`).test(block));
82
+ if (plate) {
83
+ const value = (key) => {
84
+ const found = plate.match(new RegExp(`<metadata\\s+key=["']${key}["']\\s+value=["']([^"']+)["']`))?.[1];
85
+ const parsed = found && /^\d+(?:\.\d+)?$/.test(found) ? Number(found) : undefined;
86
+ return parsed !== undefined && parsed > 0 ? parsed : undefined;
87
+ };
88
+ const seconds = value("prediction"), grams = value("weight");
89
+ if (seconds !== undefined || grams !== undefined)
90
+ estimate = defined({ seconds, grams });
91
+ }
92
+ return { ...(plates.size ? { plate_count: plates.size } : {}), ...(estimate ? { estimate } : {}), settings };
93
+ }
94
+ const clean = (text) => text.replace(/\r\n?/g, "\n").replace(/[\x00-\x09\x0b-\x1f\x7f]/g, " ").trim();
95
+ export function slicerReport(result) {
96
+ if (!result || typeof result !== "object" || Array.isArray(result))
97
+ return undefined;
98
+ const value = result;
99
+ const plates = Array.isArray(value.sliced_plates) ? value.sliced_plates : [];
100
+ const ids = plates.map(plate => plate && typeof plate === "object" ? plate.id : undefined);
101
+ const plateCount = ids.length && ids.every(id => typeof id === "number" && Number.isSafeInteger(id) && id > 0) ? new Set(ids).size : undefined;
102
+ const warnings = plates.map(plate => plate && typeof plate.warning_message === "string" ? clean(plate.warning_message) : "").filter(Boolean);
103
+ // Anything but the slicer's success code fails closed, a missing one included.
104
+ const failed = value.return_code !== 0;
105
+ const error = typeof value.error_string === "string" ? clean(value.error_string) : "";
106
+ const words = [...new Set([...(failed && error ? [error] : []), ...warnings])].join("\n").slice(0, 2000);
107
+ if (failed)
108
+ return { failed, message: words || `The slicer could not slice this model (return code ${String(value.return_code)}).` };
109
+ return { failed, ...(words ? { message: words } : {}), ...(plateCount ? { plate_count: plateCount } : {}) };
110
+ }
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";
@@ -3101,7 +3111,7 @@ class BambuPrinterMCPServer {
3101
3111
  },
3102
3112
  outputSchema: FUSION_EXPORT_OUTPUT_SCHEMA
3103
3113
  }
3104
- ].map(withAnnotations)
3114
+ ].map(withAnnotations).map(withRemote)
3105
3115
  };
3106
3116
  });
3107
3117
  this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
@@ -3247,6 +3257,8 @@ class BambuPrinterMCPServer {
3247
3257
  artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
3248
3258
  selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
3249
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),
3250
3262
  ...(preview ? { preview } : {}),
3251
3263
  };
3252
3264
  });
@@ -3909,8 +3921,9 @@ class BambuPrinterMCPServer {
3909
3921
  const sliced = await this.stlManipulator.sliceSTLWithResult(String(args.stl_path), slicerType, slicerPath, activeSlicerProfile, undefined, // progressCallback
3910
3922
  printerPreset, sliceBambuOptions);
3911
3923
  await progressNotifications;
3912
- // The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim.
3913
- 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) };
3914
3927
  }
3915
3928
  case "print_3mf": {
3916
3929
  if (!args?.three_mf_path) {
@@ -4295,7 +4308,7 @@ class BambuPrinterMCPServer {
4295
4308
  tool: name,
4296
4309
  ...(error instanceof PrinterRefusal ? { code: error.code } : {}),
4297
4310
  // The slicer's own result.json; the message starts with its error_string and warnings.
4298
- ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult } : {}),
4311
+ ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult, ...reportOf(error.slicerResult) } : {}),
4299
4312
  };
4300
4313
  // MCP clients validate structuredContent against a declared outputSchema even on
4301
4314
  // errors (SDK 1.32 Client.callTool), so those tools return the error as text only.
@@ -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
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.63",
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,160 @@
1
+ /**
2
+ * How Counterpart's remote endpoint (`/v1/mcp`) offers each tool to a paired device, declared by this server so a
3
+ * new tool or argument needs no Counterpart release. Sent as each listed tool's `_meta["counterpart/remote"]`:
4
+ *
5
+ * - `scope`: the least device scope that may call the tool: read < design < control < print < raw. The table keeps
6
+ * the classes Counterpart gave these tools by hand before this version, so no paired device gained or lost a tool;
7
+ * `tests/tool-annotations.test.mjs` holds the name floors (a print start is at least print, a raw call raw).
8
+ * - `raisedBy`: boolean arguments that, when true, need a higher scope (`launch` starts Fusion).
9
+ * - `arguments`: argument names that are not plain values, matched at any depth of a call's arguments:
10
+ * `config`: this server's configuration chooses it (the printer it targets, its account, hardware and programs),
11
+ * so a device may not set it; `config-top`: the same, as a top-level argument only (`type`, the printer type);
12
+ * `path`: a local file or folder the tool reads; `output`: one it writes. Any other argument is a plain value.
13
+ * A tool that forwards an open object (an arbitrary RPC payload or another server's tool arguments) declares every
14
+ * configuration name, since any of them may appear inside it.
15
+ */
16
+ export type RemoteScope = "read" | "design" | "control" | "print" | "raw";
17
+ export type ArgumentKind = "config" | "config-top" | "path" | "output";
18
+ export interface RemoteDeclaration {
19
+ scope: RemoteScope;
20
+ raisedBy?: Record<string, RemoteScope>;
21
+ arguments?: Record<string, ArgumentKind>;
22
+ }
23
+ export const REMOTE_META_KEY = "counterpart/remote";
24
+
25
+ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
26
+ // read
27
+ counterpart_discover_printers: "read",
28
+ counterpart_setup_fields: "read",
29
+ counterpart_propose_filaments: "read",
30
+ get_printer_status: "read",
31
+ get_printer_filaments: "read",
32
+ resolve_3mf_ams_slots: "read",
33
+ list_3mf_plate_objects: "read",
34
+ get_stl_info: "read",
35
+ list_templates: "read",
36
+ list_printer_files: "read",
37
+ camera_frame: "read",
38
+ camera_snapshot: "read",
39
+ inspect_print_file: "read",
40
+ blender_mcp_status: "read",
41
+ counterpart_printer_info: "read",
42
+ counterpart_print_progress: "read",
43
+ fusion_mcp_status: "read",
44
+ // design
45
+ slice_stl: "design",
46
+ lay_flat: "design",
47
+ counterpart_make_3mf: "design",
48
+ // control
49
+ bambu_connect_import_file: "control",
50
+ camera_stream_start: "control",
51
+ camera_stream_stop: "control",
52
+ cancel_print: "control",
53
+ pause_print: "control",
54
+ resume_print: "control",
55
+ clear_hms_errors: "control",
56
+ set_print_speed: "control",
57
+ set_airduct_mode: "control",
58
+ reread_ams_rfid: "control",
59
+ set_temperature: "control",
60
+ set_fan_speed: "control",
61
+ set_light: "control",
62
+ set_ams_drying: "control",
63
+ counterpart_print_route: "control",
64
+ fusion_mcp_new_design: "control",
65
+ fusion_mcp_export: "control",
66
+ // print
67
+ extend_stl_base: "print",
68
+ scale_stl: "print",
69
+ rotate_stl: "print",
70
+ get_slice_settings: "print",
71
+ slice_with_template: "print",
72
+ bambu_network_bridge_status: "print",
73
+ print_3mf_bambu_network: "print",
74
+ delete_printer_file: "print",
75
+ upload_file: "print",
76
+ start_print: "print",
77
+ start_print_job: "print",
78
+ skip_objects: "print",
79
+ print_3mf: "print",
80
+ print_collar_charm: "print",
81
+ merge_vertices: "print",
82
+ center_model: "print",
83
+ // raw
84
+ save_template: "raw",
85
+ bambu_network_call: "raw",
86
+ upload_gcode: "raw",
87
+ x2d_native_control: "raw",
88
+ blender_mcp_call: "raw",
89
+ blender_mcp_edit_model: "raw",
90
+ fusion_mcp_call: "raw",
91
+ };
92
+
93
+ const RAISED_BY: Readonly<Record<string, Record<string, RemoteScope>>> = {
94
+ fusion_mcp_status: { launch: "design" }, // starts Fusion on this computer
95
+ blender_mcp_status: { connect: "design" }, // connects to Blender
96
+ };
97
+
98
+ /**
99
+ * Overrides of a server's own configuration (both printer MCPs use the same names): the printer it targets, its
100
+ * account and credentials, its hardware, and the programs it runs.
101
+ */
102
+ export const CONFIG_ARGUMENTS: ReadonlySet<string> = new Set([
103
+ "host", "port", "api_key", "username", "password", "dev_ip", "dev_id", "bambu_serial", "bambu_token", "user_info",
104
+ "country_code", "connection_type", "connection_mode", "route", "bambu_model", "nozzle_diameter", "nozzle_diameters",
105
+ "bridge_command", "slicer_path", "slicer_type", "ffmpeg_path", "plugin_dir", "runtime_dir", "template_dir",
106
+ "config_filename", "bambu_network_method", "use_ssl_for_mqtt", "use_ssl_for_ftp", "extra_options",
107
+ "allow_mutating_method",
108
+ ]);
109
+ /** Top-level only: the printer type (`type`); a nested `type` is a plain value. */
110
+ const TOP_LEVEL_CONFIG: ReadonlySet<string> = new Set(["type"]);
111
+ /** Files read whose names don't end in path, dir or file. */
112
+ const FILE_ARGUMENTS: ReadonlySet<string> = new Set(["filament_profile", "slicer_profile", "load_filaments", "source_f3d"]);
113
+
114
+ const isPath = (key: string) => /(?:path|dir|directory|_file)$/.test(key) || FILE_ARGUMENTS.has(key);
115
+
116
+ function kindOf(tool: string, key: string, depth: number): ArgumentKind | undefined {
117
+ // counterpart_print_route's own `route` is the connection the caller chooses.
118
+ if ((CONFIG_ARGUMENTS.has(key) && !(key === "route" && tool === "counterpart_print_route")) || /config_dir$/.test(key)) return "config";
119
+ if (depth === 0 && TOP_LEVEL_CONFIG.has(key)) return "config-top";
120
+ if (!isPath(key)) return undefined;
121
+ return /^output_|^out_path$|^save_path$/.test(key) ? "output" : "path";
122
+ }
123
+
124
+ /** The argument kinds of one tool, read from its own input schema. */
125
+ export function remoteArguments(tool: { name: string; inputSchema?: unknown }): Record<string, ArgumentKind> {
126
+ const kinds: Record<string, ArgumentKind> = {};
127
+ let open = false;
128
+ const visit = (schema: unknown, depth: number): void => {
129
+ if (!schema || typeof schema !== "object") return;
130
+ const node = schema as { type?: unknown; properties?: Record<string, unknown>; additionalProperties?: unknown; items?: unknown; anyOf?: unknown[]; oneOf?: unknown[] };
131
+ // An object whose keys the schema doesn't name (beyond the top level) may carry any argument.
132
+ if (depth > 0 && node.type === "object" && (node.additionalProperties === true || node.additionalProperties === undefined && !node.properties)) open = true;
133
+ if (depth > 0 && node.additionalProperties && typeof node.additionalProperties === "object") open = true;
134
+ for (const [key, child] of Object.entries(node.properties ?? {})) {
135
+ const kind = kindOf(tool.name, key, depth);
136
+ if (kind && !(kinds[key] === "config" && kind === "config-top")) kinds[key] = kind;
137
+ visit(child, depth + 1);
138
+ }
139
+ visit(node.items, depth);
140
+ for (const option of [...(node.anyOf ?? []), ...(node.oneOf ?? [])]) visit(option, depth);
141
+ };
142
+ visit(tool.inputSchema, 0);
143
+ if (open) for (const key of CONFIG_ARGUMENTS) if (!(key === "route" && tool.name === "counterpart_print_route")) kinds[key] ??= "config";
144
+ return kinds;
145
+ }
146
+
147
+ /** The declaration for one tool; a tool missing from REMOTE_SCOPES (a bug the tests catch) is raw. */
148
+ export function remoteDeclaration(tool: { name: string; inputSchema?: unknown }): RemoteDeclaration {
149
+ const args = remoteArguments(tool);
150
+ return {
151
+ scope: REMOTE_SCOPES[tool.name] ?? "raw",
152
+ ...(RAISED_BY[tool.name] ? { raisedBy: RAISED_BY[tool.name] } : {}),
153
+ ...(Object.keys(args).length ? { arguments: args } : {}),
154
+ };
155
+ }
156
+
157
+ /** The tool with its declaration in `_meta`. */
158
+ export function withRemote<T extends { name: string; inputSchema?: unknown; _meta?: Record<string, unknown> }>(tool: T): T & { _meta: Record<string, unknown> } {
159
+ return { ...tool, _meta: { ...(tool._meta ?? {}), [REMOTE_META_KEY]: remoteDeclaration(tool) } };
160
+ }
@@ -0,0 +1,115 @@
1
+ import fs from "node:fs";
2
+ import { loadSafe3mfArchive, readBoundedPrintFile } from "../safety/archive.js";
3
+
4
+ /**
5
+ * What a client shows about a sliced file, read here so it never parses slicer formats itself (Counterpart PRD
6
+ * §8.0 item 9): the selected plate's estimate and slice settings, and how many printable plates the file has.
7
+ * Bambu Studio and OrcaSlicer 3MFs carry them in Metadata/slice_info.config, project_settings.config and the
8
+ * plate's G-code header; a G-code file in its own header and footer comments. Anything not found is left out.
9
+ */
10
+ export interface SlicedFileFacts {
11
+ plate_count?: number;
12
+ estimate?: { seconds?: number; grams?: number };
13
+ settings: { layer_height_mm?: number; sparse_infill_percent?: number; wall_loops?: number; layer_count?: number };
14
+ }
15
+
16
+ const number = (value: unknown): number | undefined => {
17
+ const parsed = typeof value === "number" ? value : typeof value === "string" ? Number.parseFloat(value) : NaN;
18
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
19
+ };
20
+ const first = (value: unknown) => Array.isArray(value) ? value[0] : value;
21
+ const defined = <T extends Record<string, unknown>>(value: T): T =>
22
+ Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;
23
+
24
+ function headerSettings(text: string): SlicedFileFacts["settings"] {
25
+ const read = (pattern: RegExp) => number(text.match(pattern)?.[1]);
26
+ const layers = read(/^;\s*(?:total layer number|total layers count|LAYER_COUNT)\s*[:=]\s*(\d+)/im);
27
+ const walls = read(/^;\s*(?:wall_loops|perimeters)\s*=\s*(\d+)/im);
28
+ return defined({
29
+ layer_height_mm: read(/^;\s*layer_height\s*=\s*([\d.]+)/im),
30
+ sparse_infill_percent: read(/^;\s*(?:sparse_infill_density|fill_density)\s*=\s*([\d.]+)%/im),
31
+ wall_loops: walls === undefined ? undefined : Math.trunc(walls),
32
+ layer_count: layers ? Math.trunc(layers) : undefined,
33
+ });
34
+ }
35
+
36
+ /** The facts of a sliced 3MF or G-code file for one zero-based plate; what can't be read is left out, never an error. */
37
+ export async function slicedFileFacts(filePath: string, plateIndex = 0): Promise<SlicedFileFacts> {
38
+ try { return await readFacts(filePath, plateIndex); } catch { return { settings: {} }; }
39
+ }
40
+
41
+ async function readFacts(filePath: string, plateIndex: number): Promise<SlicedFileFacts> {
42
+ const head = Buffer.alloc(4);
43
+ const handle = await fs.promises.open(filePath, "r");
44
+ try { await handle.read(head, 0, 4, 0); } finally { await handle.close(); }
45
+ if (head[0] !== 0x50 || head[1] !== 0x4b) {
46
+ // G-code: PrusaSlicer and Orca write their settings in a footer, others in a header; read both ends.
47
+ const stat = await fs.promises.stat(filePath);
48
+ const size = 256 * 1024;
49
+ const read = async (start: number) => {
50
+ const buffer = Buffer.alloc(Math.min(size, stat.size));
51
+ const file = await fs.promises.open(filePath, "r");
52
+ try { await file.read(buffer, 0, buffer.length, start); } finally { await file.close(); }
53
+ return buffer.toString("latin1");
54
+ };
55
+ return { plate_count: 1, settings: headerSettings(`${await read(0)}\n${await read(Math.max(0, stat.size - size))}`) };
56
+ }
57
+ const zip = await loadSafe3mfArchive(await readBoundedPrintFile(filePath));
58
+ const plates = new Set(Object.keys(zip.files).flatMap(name => /^Metadata\/plate_([1-9]\d*)\.gcode$/.exec(name)?.[1] ?? []));
59
+ const text = async (name: string) => zip.file(name)?.async("string");
60
+ let settings: SlicedFileFacts["settings"] = {};
61
+ const project = await text("Metadata/project_settings.config");
62
+ if (project) {
63
+ try {
64
+ const values = JSON.parse(project) as Record<string, unknown>;
65
+ const infill = String(first(values.sparse_infill_density) ?? "");
66
+ const walls = number(first(values.wall_loops));
67
+ settings = defined({
68
+ layer_height_mm: number(first(values.layer_height)),
69
+ sparse_infill_percent: infill === "" ? undefined : number(infill.replace("%", "")),
70
+ wall_loops: walls === undefined ? undefined : Math.trunc(walls),
71
+ });
72
+ } catch { /* the settings stay unknown */ }
73
+ }
74
+ // Only the plate G-code's header, never the whole (often hundreds of MB) as a string.
75
+ const gcode = await zip.file(`Metadata/plate_${plateIndex + 1}.gcode`)?.async("nodebuffer");
76
+ // The project settings are authoritative; the plate's G-code header adds the layer count.
77
+ if (gcode) settings = { ...headerSettings(gcode.subarray(0, 64 * 1024).toString("latin1")), ...settings };
78
+ let estimate: SlicedFileFacts["estimate"];
79
+ const info = await text("Metadata/slice_info.config");
80
+ const plate = info?.match(/<plate(?:\s[^>]*)?>[\s\S]*?<\/plate>/g)
81
+ ?.find(block => new RegExp(`<metadata\\s+key=["']index["']\\s+value=["']${plateIndex + 1}["']`).test(block));
82
+ if (plate) {
83
+ const value = (key: string) => {
84
+ const found = plate.match(new RegExp(`<metadata\\s+key=["']${key}["']\\s+value=["']([^"']+)["']`))?.[1];
85
+ const parsed = found && /^\d+(?:\.\d+)?$/.test(found) ? Number(found) : undefined;
86
+ return parsed !== undefined && parsed > 0 ? parsed : undefined;
87
+ };
88
+ const seconds = value("prediction"), grams = value("weight");
89
+ if (seconds !== undefined || grams !== undefined) estimate = defined({ seconds, grams });
90
+ }
91
+ return { ...(plates.size ? { plate_count: plates.size } : {}), ...(estimate ? { estimate } : {}), settings };
92
+ }
93
+
94
+ /**
95
+ * Bambu Studio's (or OrcaSlicer's) verdict on a slice, from its result.json: whether it failed, its own words
96
+ * (the error and every plate's warning, verbatim), and how many plates it sliced.
97
+ */
98
+ export interface SlicerReport { failed: boolean; message?: string; plate_count?: number }
99
+
100
+ const clean = (text: string) => text.replace(/\r\n?/g, "\n").replace(/[\x00-\x09\x0b-\x1f\x7f]/g, " ").trim();
101
+
102
+ export function slicerReport(result: unknown): SlicerReport | undefined {
103
+ if (!result || typeof result !== "object" || Array.isArray(result)) return undefined;
104
+ const value = result as { return_code?: unknown; error_string?: unknown; sliced_plates?: unknown };
105
+ const plates = Array.isArray(value.sliced_plates) ? value.sliced_plates as Record<string, unknown>[] : [];
106
+ const ids = plates.map(plate => plate && typeof plate === "object" ? plate.id : undefined);
107
+ const plateCount = ids.length && ids.every(id => typeof id === "number" && Number.isSafeInteger(id) && id > 0) ? new Set(ids).size : undefined;
108
+ const warnings = plates.map(plate => plate && typeof plate.warning_message === "string" ? clean(plate.warning_message) : "").filter(Boolean);
109
+ // Anything but the slicer's success code fails closed, a missing one included.
110
+ const failed = value.return_code !== 0;
111
+ const error = typeof value.error_string === "string" ? clean(value.error_string) : "";
112
+ const words = [...new Set([...(failed && error ? [error] : []), ...warnings])].join("\n").slice(0, 2000);
113
+ if (failed) return { failed, message: words || `The slicer could not slice this model (return code ${String(value.return_code)}).` };
114
+ return { failed, ...(words ? { message: words } : {}), ...(plateCount ? { plate_count: plateCount } : {}) };
115
+ }
package/src/index.ts CHANGED
@@ -1,6 +1,17 @@
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
+
7
+ /** The slicer's verdict beside its result.json (`slicer_report`). */
8
+ function reportOf(result: unknown): { slicer_report?: ReturnType<typeof slicerReport> } {
9
+ const report = slicerReport(result);
10
+ return report ? { slicer_report: report } : {};
11
+ }
12
+ function withSlicerReport<T extends { slicer_result?: unknown }>(sliced: T): T & { slicer_report?: ReturnType<typeof slicerReport> } {
13
+ return { ...sliced, ...reportOf(sliced.slicer_result) };
14
+ }
4
15
 
5
16
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
6
17
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -3616,7 +3627,7 @@ class BambuPrinterMCPServer {
3616
3627
  },
3617
3628
  outputSchema: FUSION_EXPORT_OUTPUT_SCHEMA
3618
3629
  }
3619
- ].map(withAnnotations)
3630
+ ].map(withAnnotations).map(withRemote)
3620
3631
  };
3621
3632
  });
3622
3633
 
@@ -3763,6 +3774,8 @@ class BambuPrinterMCPServer {
3763
3774
  artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
3764
3775
  selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
3765
3776
  inspection,
3777
+ // The plate's estimate and slice settings, and the file's plate count, read here so clients don't parse slicer files.
3778
+ sliced: await slicedFileFacts(snapshot, plateIndex),
3766
3779
  ...(preview ? { preview } : {}),
3767
3780
  };
3768
3781
  });
@@ -4544,8 +4557,9 @@ class BambuPrinterMCPServer {
4544
4557
  sliceBambuOptions
4545
4558
  );
4546
4559
  await progressNotifications;
4547
- // The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim.
4548
- return { content: [{ type: "text", text: sliced.path }], structuredContent: sliced };
4560
+ // The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim, and
4561
+ // slicer_report its verdict and words, so clients don't read the slicer's format.
4562
+ return { content: [{ type: "text", text: sliced.path }], structuredContent: withSlicerReport(sliced) };
4549
4563
  }
4550
4564
 
4551
4565
  case "print_3mf": {
@@ -5038,7 +5052,7 @@ class BambuPrinterMCPServer {
5038
5052
  tool: name,
5039
5053
  ...(error instanceof PrinterRefusal ? { code: error.code } : {}),
5040
5054
  // The slicer's own result.json; the message starts with its error_string and warnings.
5041
- ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult } : {}),
5055
+ ...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult, ...reportOf(error.slicerResult) } : {}),
5042
5056
  };
5043
5057
 
5044
5058
  // MCP clients validate structuredContent against a declared outputSchema even on
@@ -0,0 +1,171 @@
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
+
6
+ /**
7
+ * Finished slices kept for reuse: slicing the same model the same way again (Print Again, or Print after a
8
+ * client's estimate) restores the slicer's outputs instead of running it. A slicer run is identified by exactly
9
+ * what it was given: the slicer executable (its path, size and modification time, so an update slices again),
10
+ * this server's version, and its full argument list, with every input file replaced by its content hash and every
11
+ * output location by a placeholder. Profiles, filament files, the model and generated override files are all
12
+ * arguments, so editing any of them slices again. A run whose arguments name any other directory (its contents
13
+ * can't be hashed) is never cached, nor is a failed slice. Presets the slicer finds by itself, not named in its
14
+ * arguments (its own bundled system presets), count through the executable: a slicer update slices again.
15
+ *
16
+ * SLICE_CACHE=off turns it off; SLICE_CACHE_DIR moves it (default ~/.cache/<package name>/slices). The newest
17
+ * SLICE_CACHE_ENTRIES (default 16) slices are kept.
18
+ */
19
+ export interface SlicerRun {
20
+ command: string;
21
+ args: string[];
22
+ /** What the slicer writes, kept and restored: files, or directories it fills. */
23
+ outputs: string[];
24
+ /** Folders it writes into that aren't kept as a whole (an --outputdir shared with other files). */
25
+ locations?: string[];
26
+ }
27
+
28
+ const KEY_VERSION = 1;
29
+ /** This server's package name and version: a new release slices again. */
30
+ const PACKAGE = (() => {
31
+ try {
32
+ const value = JSON.parse(fs.readFileSync(new URL("../../package.json", import.meta.url), "utf8")) as { name?: unknown; version?: unknown };
33
+ return { name: String(value.name ?? "printer-mcp"), version: String(value.version ?? "") };
34
+ } catch {
35
+ return { name: "printer-mcp", version: "" };
36
+ }
37
+ })();
38
+
39
+ function enabled(): boolean {
40
+ return !/^(?:off|0|false|no)$/i.test(process.env.SLICE_CACHE ?? "");
41
+ }
42
+
43
+ export function sliceCacheRoot(): string {
44
+ return process.env.SLICE_CACHE_DIR || path.join(os.homedir(), ".cache", PACKAGE.name, "slices");
45
+ }
46
+
47
+ function entriesKept(): number {
48
+ const value = Number(process.env.SLICE_CACHE_ENTRIES);
49
+ return Number.isInteger(value) && value > 0 ? value : 16;
50
+ }
51
+
52
+ async function fileHash(file: string): Promise<string> {
53
+ const hash = createHash("sha256");
54
+ for await (const chunk of fs.createReadStream(file)) hash.update(chunk as Buffer);
55
+ return hash.digest("hex");
56
+ }
57
+
58
+ function onPath(command: string): string | undefined {
59
+ if (path.isAbsolute(command) || command.includes("/") || command.includes("\\")) return path.resolve(command);
60
+ for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
61
+ if (!dir) continue;
62
+ const candidate = path.join(dir, command);
63
+ try { if (fs.statSync(candidate).isFile()) return candidate; } catch { /* next */ }
64
+ }
65
+ return undefined;
66
+ }
67
+
68
+ /** The run's cache key, or undefined when it can't be identified exactly (then it is never cached). */
69
+ export async function sliceCacheKey(run: SlicerRun): Promise<string | undefined> {
70
+ if (!enabled()) return undefined;
71
+ // Never a reason for a slice to fail: anything unreadable means this run isn't kept.
72
+ try { return await keyOf(run); } catch { return undefined; }
73
+ }
74
+
75
+ async function keyOf(run: SlicerRun): Promise<string | undefined> {
76
+ const executable = onPath(run.command);
77
+ if (!executable) return undefined;
78
+ let binary: fs.Stats;
79
+ try { binary = await fs.promises.stat(executable); } catch { return undefined; }
80
+ const outputs = run.outputs.map(output => path.resolve(output));
81
+ const places = [...outputs, ...(run.locations ?? []).map(location => path.resolve(location))];
82
+ const part = async (value: string): Promise<string | undefined> => {
83
+ if (!value || value.startsWith("-")) return value;
84
+ // A relative path is a file to the slicer too (resolved against this process's directory, as it is).
85
+ const resolved = path.resolve(value);
86
+ // An output or output folder itself: where this run writes, whatever it is called.
87
+ const exact = places.indexOf(resolved);
88
+ if (exact >= 0) return `<output ${exact}>`;
89
+ // A file staged inside an output folder (a generated profile, a transformed mesh) is an input: its bytes count.
90
+ const root = places.findIndex(place => resolved.startsWith(place + path.sep));
91
+ let info: fs.Stats | undefined;
92
+ try { info = await fs.promises.stat(resolved); } catch { info = undefined; }
93
+ const named = root >= 0 ? `<output ${root}>${resolved.slice(places[root].length)}` : path.isAbsolute(value) ? resolved : value;
94
+ // A file is its bytes (and its extension, which tells the slicer what it is), not its often random name.
95
+ if (info?.isFile()) return `file${path.extname(resolved).toLowerCase()}#${await fileHash(resolved)}`;
96
+ // A folder's contents can't be hashed: such a run is never cached.
97
+ if (info?.isDirectory()) return undefined;
98
+ return named;
99
+ };
100
+ const args: string[] = [];
101
+ for (const arg of run.args) {
102
+ const parts: string[] = [];
103
+ for (const piece of arg.split(";")) {
104
+ const value = await part(piece);
105
+ if (value === undefined) 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
+
114
+ async function touch(target: string, at: Date): Promise<void> {
115
+ const info = await fs.promises.stat(target);
116
+ if (info.isDirectory()) for (const name of await fs.promises.readdir(target)) await touch(path.join(target, name), at);
117
+ await fs.promises.utimes(target, at, at);
118
+ }
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: string, run: SlicerRun): Promise<boolean> {
122
+ const entry = path.join(sliceCacheRoot(), key);
123
+ try {
124
+ const meta = JSON.parse(await fs.promises.readFile(path.join(entry, "meta.json"), "utf8")) as { outputs?: unknown; saved?: unknown };
125
+ if (meta.outputs !== run.outputs.length || !Array.isArray(meta.saved)) return false;
126
+ const saved = new Set(meta.saved.filter((index): index is number => typeof index === "number"));
127
+ // Every output the slicer wrote must still be there, or this is no slice at all.
128
+ for (const index of saved) if (!fs.existsSync(path.join(entry, String(index)))) return false;
129
+ const now = new Date();
130
+ for (const [index, output] of run.outputs.entries()) {
131
+ if (!saved.has(index)) continue; // the slicer didn't write this one
132
+ await fs.promises.mkdir(path.dirname(output), { recursive: true });
133
+ await fs.promises.cp(path.join(entry, String(index)), output, { recursive: true, force: true });
134
+ // Fresh timestamps on every restored file: a result.json must read as written by this run.
135
+ await touch(output, now);
136
+ }
137
+ await fs.promises.utimes(entry, now, now);
138
+ return true;
139
+ } catch {
140
+ return false;
141
+ }
142
+ }
143
+
144
+ /** Keeps a finished slice's outputs, whole or not at all; a failure to keep it never fails the slice. */
145
+ export async function keepSlice(key: string, run: SlicerRun): Promise<void> {
146
+ const root = sliceCacheRoot();
147
+ try {
148
+ await fs.promises.mkdir(root, { recursive: true, mode: 0o700 });
149
+ const staging = await fs.promises.mkdtemp(path.join(root, ".staging-"));
150
+ try {
151
+ const saved: number[] = [];
152
+ for (const [index, output] of run.outputs.entries()) {
153
+ if (!fs.existsSync(output)) continue;
154
+ await fs.promises.cp(output, path.join(staging, String(index)), { recursive: true });
155
+ saved.push(index);
156
+ }
157
+ await fs.promises.writeFile(path.join(staging, "meta.json"), JSON.stringify({ outputs: run.outputs.length, saved, keptAt: new Date().toISOString() }));
158
+ await fs.promises.rm(path.join(root, key), { recursive: true, force: true });
159
+ await fs.promises.rename(staging, path.join(root, key));
160
+ } finally {
161
+ await fs.promises.rm(staging, { recursive: true, force: true });
162
+ }
163
+ const entries = await Promise.all((await fs.promises.readdir(root)).filter(name => /^[0-9a-f]{64}$/.test(name))
164
+ .map(async name => ({ name, at: (await fs.promises.stat(path.join(root, name))).mtimeMs })));
165
+ for (const old of entries.sort((a, b) => b.at - a.at).slice(entriesKept())) {
166
+ await fs.promises.rm(path.join(root, old.name), { recursive: true, force: true });
167
+ }
168
+ } catch (error) {
169
+ console.error(`Could not keep this slice for reuse: ${error instanceof Error ? error.message : String(error)}`);
170
+ }
171
+ }
@@ -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, type ProcessOverrides } from '../slicer/process-overrides.js';
15
16
  import { profileJsonFiles } from '../slicer/profile-files.js';
@@ -2020,7 +2021,17 @@ export class STLManipulator extends EventEmitter {
2020
2021
  throw new Error(`Unsupported slicer type: ${slicerType}`);
2021
2022
  }
2022
2023
 
2023
- if (slicerType !== 'orca-slicer-api') {
2024
+ // The Bambu-compatible CLI's slice, kept for reuse: the same model sliced the same way again is restored,
2025
+ // and every check below still runs on it (slice-cache.ts).
2026
+ const cacheRun = cliResult && slicerType !== 'orca-slicer-api'
2027
+ ? { command: slicerPath, args, outputs: [outputFilePath, cliResult.resultPath], locations: [path.dirname(cliResult.resultPath)] } : undefined;
2028
+ const cacheKey = cacheRun ? await sliceCacheKey(cacheRun) : undefined;
2029
+ const restored = !!cacheKey && await restoreSlice(cacheKey, cacheRun!);
2030
+ if (restored) {
2031
+ if (progressCallback) progressCallback(90, 'Reusing the same slice of this model');
2032
+ console.error(`Reusing slice ${cacheKey} for: ${slicerPath} ${args.join(' ')}`);
2033
+ }
2034
+ if (slicerType !== 'orca-slicer-api' && !restored) {
2024
2035
  if (progressCallback) progressCallback(20, `Executing slicer: ${slicerPath} ${args.join(' ')}`);
2025
2036
  console.error(`Executing: ${slicerPath} ${args.join(' ')}`);
2026
2037
 
@@ -2078,6 +2089,7 @@ export class STLManipulator extends EventEmitter {
2078
2089
  if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
2079
2090
  throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
2080
2091
  }
2092
+ if (cacheKey && !restored && fs.existsSync(outputFilePath)) await keepSlice(cacheKey, cacheRun!);
2081
2093
 
2082
2094
  if (!fs.existsSync(outputFilePath)) {
2083
2095
  throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);