bambu-printer-mcp 1.1.63 → 1.1.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/counterpart/remote.d.ts +47 -0
- package/dist/counterpart/remote.js +141 -0
- package/dist/counterpart/sliced-file.d.ts +31 -0
- package/dist/counterpart/sliced-file.js +110 -0
- package/dist/index.js +54 -11
- package/dist/slicer/slice-cache.d.ts +28 -0
- package/dist/slicer/slice-cache.js +178 -0
- package/dist/stl/stl-manipulator.js +15 -1
- package/package.json +1 -1
- package/src/counterpart/remote.ts +160 -0
- package/src/counterpart/sliced-file.ts +115 -0
- package/src/index.ts +57 -13
- package/src/slicer/slice-cache.ts +171 -0
- package/src/stl/stl-manipulator.ts +13 -1
|
@@ -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
|
-
|
|
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
|
@@ -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";
|
|
@@ -986,6 +997,18 @@ async function previewOfSnapshot(snapshot: string, plateIndex: number, sha256: s
|
|
|
986
997
|
return preview ? { ...preview, artifact_sha256: sha256, plate_index: plateIndex } : undefined;
|
|
987
998
|
}
|
|
988
999
|
|
|
1000
|
+
/**
|
|
1001
|
+
* The slice's arguments change a resolved process: an explicit value (layer height, walls, infill, supports), or a
|
|
1002
|
+
* quality or strength other than standard. Invalid values throw, as slice_stl's own parsing does.
|
|
1003
|
+
*/
|
|
1004
|
+
function changesProcess(args: Record<string, unknown>): boolean {
|
|
1005
|
+
// slice_stl's own validation of these values (quality, strength, layer height, walls, infill, supports).
|
|
1006
|
+
const nozzle = Number(args.nozzle_diameter || DEFAULT_NOZZLE_DIAMETER);
|
|
1007
|
+
parseProcessOverrides(withPrintQuality(args, nozzle), nozzle);
|
|
1008
|
+
return ["layer_height", "wall_loops", "sparse_infill_density", "enable_support", "support_type", "support_threshold_angle"].some(key => args[key] !== undefined)
|
|
1009
|
+
|| (args.quality !== undefined && args.quality !== "standard") || (args.strength !== undefined && args.strength !== "standard");
|
|
1010
|
+
}
|
|
1011
|
+
|
|
989
1012
|
function hasExplicitSlicerProfile(args: any): boolean {
|
|
990
1013
|
return typeof args?.slicer_profile === "string" && args.slicer_profile.trim().length > 0;
|
|
991
1014
|
}
|
|
@@ -2109,7 +2132,12 @@ class BambuPrinterMCPServer {
|
|
|
2109
2132
|
return inventory;
|
|
2110
2133
|
}
|
|
2111
2134
|
|
|
2112
|
-
|
|
2135
|
+
/**
|
|
2136
|
+
* `sliceArgs`: the slice_stl arguments a client would send with this file (slicer_profile, template_name,
|
|
2137
|
+
* template_3mf_path, layer_height, wall_loops, sparse_infill_density, quality, strength). `requestedTemplatePath`:
|
|
2138
|
+
* their template, resolved. own_process says whether that slice prints the process the 3MF carries, unchanged.
|
|
2139
|
+
*/
|
|
2140
|
+
private async inspectSliceSettings(sourcePath: string, sliceArgs: Record<string, unknown> = {}, requestedTemplatePath?: string) {
|
|
2113
2141
|
if (!fs.existsSync(sourcePath)) {
|
|
2114
2142
|
throw new Error(`Slice settings source not found: ${sourcePath}`);
|
|
2115
2143
|
}
|
|
@@ -2131,8 +2159,10 @@ class BambuPrinterMCPServer {
|
|
|
2131
2159
|
metadata_keys: Object.keys(parsed.metadata),
|
|
2132
2160
|
summary: summarizeSliceSettings(config),
|
|
2133
2161
|
raw_key_count: Object.keys(config).length,
|
|
2134
|
-
// ownProcessTemplate itself,
|
|
2135
|
-
|
|
2162
|
+
// ownProcessTemplate itself, with the slice's own arguments, so this can't drift from slicing; an explicit
|
|
2163
|
+
// value or a quality or strength other than standard changes the process the file carries.
|
|
2164
|
+
// Validated first, so an invalid value is refused even when a named profile or template decides the answer.
|
|
2165
|
+
own_process: !changesProcess(sliceArgs) && (await ownProcessTemplate(sliceArgs, sourcePath, requestedTemplatePath)) !== undefined,
|
|
2136
2166
|
};
|
|
2137
2167
|
}
|
|
2138
2168
|
|
|
@@ -2621,7 +2651,7 @@ class BambuPrinterMCPServer {
|
|
|
2621
2651
|
},
|
|
2622
2652
|
{
|
|
2623
2653
|
name: "get_slice_settings",
|
|
2624
|
-
description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything. For a 3MF, own_process is true when
|
|
2654
|
+
description: "Inspect slicer settings from a saved 3MF template or a JSON/config slicer profile without slicing anything. For a 3MF given as source_path, own_process is true when slice_stl, given this call's other arguments as it would take them (slicer_profile, template_name, template_3mf_path, layer_height, wall_loops, sparse_infill_density, quality, strength), prints the process the file carries (a designer's Bambu Studio or Orca project) unchanged.",
|
|
2625
2655
|
inputSchema: {
|
|
2626
2656
|
type: "object",
|
|
2627
2657
|
properties: {
|
|
@@ -2631,12 +2661,21 @@ class BambuPrinterMCPServer {
|
|
|
2631
2661
|
},
|
|
2632
2662
|
template_name: {
|
|
2633
2663
|
type: "string",
|
|
2634
|
-
description: "Optional named template from the local registry.
|
|
2664
|
+
description: "Optional named template from the local registry. Without source_path it is the source read; with source_path it is the slice's template, for own_process."
|
|
2635
2665
|
},
|
|
2636
2666
|
template_dir: {
|
|
2637
2667
|
type: "string",
|
|
2638
2668
|
description: "Optional template directory override when resolving template_name."
|
|
2639
|
-
}
|
|
2669
|
+
},
|
|
2670
|
+
slicer_profile: { type: "string", description: "For own_process: the slicer_profile slice_stl would be given." },
|
|
2671
|
+
template_3mf_path: { type: "string", description: "For own_process: the template_3mf_path slice_stl would be given." },
|
|
2672
|
+
layer_height: { type: "number", description: "For own_process: the layer_height slice_stl would be given." },
|
|
2673
|
+
nozzle_diameter: { type: "string", description: "For own_process: the nozzle_diameter slice_stl would be given; layer heights are checked against it." },
|
|
2674
|
+
wall_loops: { type: "number", description: "For own_process: the wall_loops slice_stl would be given." },
|
|
2675
|
+
sparse_infill_density: { type: "string", description: "For own_process: the sparse_infill_density slice_stl would be given." },
|
|
2676
|
+
enable_support: { type: "boolean", description: "For own_process: the enable_support slice_stl would be given." },
|
|
2677
|
+
support_type: { type: "string", description: "For own_process: the support_type slice_stl would be given." },
|
|
2678
|
+
...PRINT_QUALITY_PROPERTIES
|
|
2640
2679
|
}
|
|
2641
2680
|
}
|
|
2642
2681
|
},
|
|
@@ -3616,7 +3655,7 @@ class BambuPrinterMCPServer {
|
|
|
3616
3655
|
},
|
|
3617
3656
|
outputSchema: FUSION_EXPORT_OUTPUT_SCHEMA
|
|
3618
3657
|
}
|
|
3619
|
-
].map(withAnnotations)
|
|
3658
|
+
].map(withAnnotations).map(withRemote)
|
|
3620
3659
|
};
|
|
3621
3660
|
});
|
|
3622
3661
|
|
|
@@ -3763,6 +3802,8 @@ class BambuPrinterMCPServer {
|
|
|
3763
3802
|
artifact: { sha256: inspection.sha256, byte_length: byteLength, file_format: path.extname(snapshot).toLowerCase() === ".3mf" ? "3mf" : "gcode" },
|
|
3764
3803
|
selection: { bambu_model: model, plate_index: plateIndex, ...(nozzles === undefined ? {} : { nozzle_diameters: nozzles }), ...(bedType === undefined ? {} : { bed_type: bedType }) },
|
|
3765
3804
|
inspection,
|
|
3805
|
+
// The plate's estimate and slice settings, and the file's plate count, read here so clients don't parse slicer files.
|
|
3806
|
+
sliced: await slicedFileFacts(snapshot, plateIndex),
|
|
3766
3807
|
...(preview ? { preview } : {}),
|
|
3767
3808
|
};
|
|
3768
3809
|
});
|
|
@@ -4345,9 +4386,11 @@ class BambuPrinterMCPServer {
|
|
|
4345
4386
|
if (!args?.source_path && !args?.template_name) {
|
|
4346
4387
|
throw new Error("Missing required parameter: source_path or template_name");
|
|
4347
4388
|
}
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
4389
|
+
// With source_path, the other arguments are the slice's (template_name is its template), as slice_stl takes them.
|
|
4390
|
+
result = args?.source_path
|
|
4391
|
+
? await this.inspectSliceSettings(String(args.source_path), args as Record<string, unknown>,
|
|
4392
|
+
namedTemplatePath(args, typeof args?.template_name === "string" && args.template_name.trim() ? resolveTemplatePathFromName(["json", "config", "3mf"]) : undefined))
|
|
4393
|
+
: await this.inspectSliceSettings(String(resolveTemplatePathFromName(["3mf", "json", "config"])));
|
|
4351
4394
|
break;
|
|
4352
4395
|
|
|
4353
4396
|
case "slice_with_template": {
|
|
@@ -4544,8 +4587,9 @@ class BambuPrinterMCPServer {
|
|
|
4544
4587
|
sliceBambuOptions
|
|
4545
4588
|
);
|
|
4546
4589
|
await progressNotifications;
|
|
4547
|
-
// The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim
|
|
4548
|
-
|
|
4590
|
+
// The text stays the sliced file's path; slicer_result is the slicer's own result.json, verbatim, and
|
|
4591
|
+
// slicer_report its verdict and words, so clients don't read the slicer's format.
|
|
4592
|
+
return { content: [{ type: "text", text: sliced.path }], structuredContent: withSlicerReport(sliced) };
|
|
4549
4593
|
}
|
|
4550
4594
|
|
|
4551
4595
|
case "print_3mf": {
|
|
@@ -5038,7 +5082,7 @@ class BambuPrinterMCPServer {
|
|
|
5038
5082
|
tool: name,
|
|
5039
5083
|
...(error instanceof PrinterRefusal ? { code: error.code } : {}),
|
|
5040
5084
|
// 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 } : {}),
|
|
5085
|
+
...(error instanceof SlicerRunError && error.slicerResult ? { slicer_result: error.slicerResult, ...reportOf(error.slicerResult) } : {}),
|
|
5042
5086
|
};
|
|
5043
5087
|
|
|
5044
5088
|
// MCP clients validate structuredContent against a declared outputSchema even on
|