bambu-printer-mcp 1.1.92 → 1.1.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +6 -2
  2. package/dist/3mf_parser.js +3 -2
  3. package/dist/cad/contracts.js +9 -0
  4. package/dist/cad-engine.d.ts +5 -0
  5. package/dist/cad-engine.js +34 -0
  6. package/dist/counterpart/flight-tools.d.ts +2 -2
  7. package/dist/counterpart/info.d.ts +2 -0
  8. package/dist/counterpart/info.js +6 -1
  9. package/dist/counterpart/make-3mf.d.ts +10 -0
  10. package/dist/counterpart/make-3mf.js +472 -65
  11. package/dist/counterpart/model-plates.d.ts +8 -1
  12. package/dist/counterpart/model-plates.js +9 -4
  13. package/dist/counterpart/plate-filaments.d.ts +19 -0
  14. package/dist/counterpart/plate-filaments.js +72 -10
  15. package/dist/counterpart/remote.js +1 -0
  16. package/dist/counterpart/schemas.d.ts +7 -2
  17. package/dist/counterpart/schemas.js +1 -0
  18. package/dist/counterpart/self-check.d.ts +79 -0
  19. package/dist/counterpart/self-check.js +163 -0
  20. package/dist/index.js +12 -2
  21. package/dist/printers/bambu.js +27 -19
  22. package/dist/printers/report-merge.d.ts +12 -0
  23. package/dist/printers/report-merge.js +46 -0
  24. package/dist/stl/stl-manipulator.js +79 -20
  25. package/dist/tool-annotations.js +1 -0
  26. package/package.json +6 -1
  27. package/src/3mf_parser.ts +3 -2
  28. package/src/cad/contracts.ts +10 -0
  29. package/src/cad/project3mf.py +426 -0
  30. package/src/cad/worker.py +6 -2
  31. package/src/cad-engine.ts +31 -0
  32. package/src/counterpart/info.ts +7 -1
  33. package/src/counterpart/make-3mf.ts +446 -61
  34. package/src/counterpart/model-plates.ts +17 -5
  35. package/src/counterpart/plate-filaments.ts +75 -7
  36. package/src/counterpart/remote.ts +1 -0
  37. package/src/counterpart/schemas.ts +3 -1
  38. package/src/counterpart/self-check.ts +164 -0
  39. package/src/index.ts +13 -2
  40. package/src/printers/bambu.ts +27 -19
  41. package/src/printers/report-merge.ts +48 -0
  42. package/src/stl/stl-manipulator.ts +75 -14
  43. package/src/tool-annotations.ts +1 -0
@@ -36,6 +36,22 @@ export interface PlateFilament {
36
36
  name?: string;
37
37
  }
38
38
 
39
+ /**
40
+ * One part on a plate, as the open 3MF standard places it, so a client draws it in its filament's colour without
41
+ * reading slicer files: the mesh object `object_id`, in the model part `path` when that is not the root
42
+ * 3D/3dmodel.model (production extension p:path, as the file names it), and the 1-based project filament it prints
43
+ * with. `painted` is true when the slicer's painting (paint_color) recolours some of its facets.
44
+ */
45
+ export interface PlatePart {
46
+ object_id: number;
47
+ /** The root object (a build item's objectid) this part belongs to: copies of one mesh may print in other filaments. */
48
+ build_object_id: number;
49
+ path?: string;
50
+ name: string;
51
+ filament: number;
52
+ painted?: true;
53
+ }
54
+
39
55
  const MAX_TEXT_BYTES = 8 * 1024 * 1024;
40
56
  const MAX_MESH_BYTES = 64 * 1024 * 1024;
41
57
  const MAX_MESH_TOTAL = 256 * 1024 * 1024;
@@ -54,11 +70,12 @@ const metadataOf = (block: string): Settings => new Map([...block.matchAll(/<met
54
70
  /** model_settings.config objects with their own settings and parts (parts never nest). */
55
71
  export function readModelObjects(settings: string): ObjectEntry[] {
56
72
  return [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
57
- const parts = [...match[2].matchAll(/<part\b([^>]*)>([\s\S]*?)<\/part>/g)].map(part => {
58
- const own = metadataOf(part[2]);
73
+ // A part may be self-closing (<part id="1" subtype="normal_part"/>): it has no settings of its own.
74
+ const parts = [...match[2].matchAll(/<part\b([^>]*?)(?:\/>|>([\s\S]*?)<\/part>)/g)].map(part => {
75
+ const own = metadataOf(part[2] ?? "");
59
76
  return { id: /\bid="(\d+)"/.exec(part[1])?.[1] ?? "", subtype: /\bsubtype="([^"]+)"/.exec(part[1])?.[1] ?? "normal_part", name: words(own.get("name") ?? ""), settings: own };
60
77
  });
61
- const own = metadataOf(match[2].replace(/<part\b[^>]*>[\s\S]*?<\/part>/g, ""));
78
+ const own = metadataOf(match[2].replace(/<part\b[^>]*?(?:\/>|>[\s\S]*?<\/part>)/g, ""));
62
79
  return { id: match[1], name: words(own.get("name") ?? ""), settings: own, parts };
63
80
  });
64
81
  }
@@ -176,6 +193,8 @@ export interface PlateLayout {
176
193
  instances?: { objectId: string; instanceId: number }[];
177
194
  /** Metadata/plate_N.json filament_ids (0-based) when the file holds this plate's slice. */
178
195
  slicedFilamentIds?: number[];
196
+ /** The file has no plate metadata: this one plate holds every build item. */
197
+ allItems?: boolean;
179
198
  }
180
199
 
181
200
  /**
@@ -183,7 +202,7 @@ export interface PlateLayout {
183
202
  * 3D/3dmodel.model text.
184
203
  */
185
204
  export async function plateFilaments(zip: JSZip, settings: string, model: string, plates: PlateLayout[], limits: PaintLimits = PAINT_LIMITS)
186
- : Promise<{ plates: Map<number, PlateFilament[]>; incomplete: Set<number>; project: PlateFilament[] }> {
205
+ : Promise<{ plates: Map<number, PlateFilament[]>; incomplete: Set<number>; project: PlateFilament[]; buildItems: Map<number, number[]>; parts: Map<number, PlatePart[]> }> {
187
206
  const text = async (name: string) => {
188
207
  const file = zip.file(name);
189
208
  if (!file) return "";
@@ -203,7 +222,10 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
203
222
  const objects = new Map(readModelObjects(settings).map(object => [object.id, object]));
204
223
  // Root objects' components: which sub-object mesh in which file each part is (part id = component objectid).
205
224
  const components = new Map<string, Map<string, string>>();
225
+ // Root objects that are meshes themselves (a plain 3MF): their own id is the part.
226
+ const rootMeshes = new Set<string>();
206
227
  for (const object of model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/(?:\w+:)?object>/g)) {
228
+ if (/<(?:\w+:)?mesh[\s>]/.test(object[2])) rootMeshes.add(object[1]);
207
229
  const parts = new Map<string, string>();
208
230
  for (const component of object[2].matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
209
231
  const path = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1];
@@ -251,10 +273,14 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
251
273
  .map(layer => Number(/\bextruder="(\d+)"/.exec(layer[1])?.[1])));
252
274
  }
253
275
 
254
- // Painting only matters for parts on a plate that is not sliced yet.
276
+ // Painting decides an unsliced plate's filaments, and marks painted parts on every plate. Unsliced plates' meshes
277
+ // come first, so the read budget goes to the filament lists before the painted marks.
255
278
  const paintPaths = new Set<string>();
256
- for (const plate of plates) if (!plate.slicedFilamentIds) for (const objectId of plate.objectIds)
279
+ for (const sliced of [false, true]) for (const plate of plates) if (!!plate.slicedFilamentIds === sliced) for (const objectId of plate.objectIds)
257
280
  for (const path of components.get(objectId)?.values() ?? []) paintPaths.add(path);
281
+ // A build item whose object is itself the mesh (a plain 3MF) keeps its painting in the root model.
282
+ const ROOT_MODEL = "3D/3dmodel.model";
283
+ if (buildItems.some(item => rootMeshes.has(/\bobjectid="(\d+)"/.exec(item)?.[1] ?? ""))) paintPaths.add(ROOT_MODEL);
258
284
  const { painting, unread } = await readPainting(zip, paintPaths, limits);
259
285
  // Plates with a part whose painting couldn't be read: they list every declared filament and say they're incomplete.
260
286
  const incomplete = new Set<number>();
@@ -262,7 +288,43 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
262
288
  const global = (key: string) => intOf(config[key]) ?? 0;
263
289
  const FEATURES = ["wall_filament", "sparse_infill_filament", "solid_infill_filament"] as const;
264
290
  const result = new Map<number, PlateFilament[]>();
291
+ const plateItems = new Map<number, number[]>();
292
+ const plateParts = new Map<number, PlatePart[]>();
293
+ const itemObject = buildItems.map(item => /\bobjectid="(\d+)"/.exec(item)?.[1]);
294
+ // The plate's copies as root build items (0-based, in build order): a copy is its object's instance_id-th item.
295
+ const plateItemsOf = (plate: PlateLayout) => {
296
+ const items = new Set<number>();
297
+ if (plate.instances?.length) for (const copy of plate.instances) {
298
+ let seen = -1;
299
+ const index = itemObject.findIndex(objectId => objectId === copy.objectId && ++seen === copy.instanceId);
300
+ if (index >= 0) items.add(index);
301
+ }
302
+ else itemObject.forEach((objectId, index) => { if (objectId && (plate.allItems || plate.objectIds.includes(objectId))) items.add(index); });
303
+ return items;
304
+ };
265
305
  for (const plate of plates) {
306
+ const items = plateItemsOf(plate);
307
+ plateItems.set(plate.number, [...items].sort((a, b) => a - b));
308
+ // Each model part of the plate's objects once, in its own filament: what a client colours when it draws the plate.
309
+ const drawn: PlatePart[] = [];
310
+ for (const objectId of [...new Set([...items].map(index => itemObject[index]!))]) {
311
+ const object = objects.get(objectId);
312
+ const meshes = components.get(objectId);
313
+ const objectFilament = intOf(object?.settings.get("extruder")) || (global("wall_filament") > 0 ? global("wall_filament") : 1);
314
+ const entry = (id: string, name: string, filament: number) => {
315
+ const path = meshes?.get(id) ?? (id === objectId && rootMeshes.has(objectId) ? ROOT_MODEL : undefined);
316
+ const paint = path ? painting.get(`${path}#${id}`) : undefined;
317
+ drawn.push({ object_id: Number(id), build_object_id: Number(objectId), ...(path && path !== "3D/3dmodel.model" ? { path: `/${path}` } : {}), name,
318
+ filament: valid(filament) ? filament : 1, ...(paint?.states.size ? { painted: true as const } : {}) });
319
+ };
320
+ if (object?.parts.length) {
321
+ for (const part of object.parts) if (part.subtype === "normal_part" && /^\d+$/.test(part.id))
322
+ entry(part.id, part.name || object.name, intOf(part.settings.get("extruder")) || objectFilament);
323
+ } else if (meshes) for (const id of meshes.keys()) entry(id, object?.name ?? "", objectFilament);
324
+ else if (rootMeshes.has(objectId)) entry(objectId, object?.name ?? "", objectFilament);
325
+ }
326
+ plateParts.set(plate.number, drawn.slice(0, 1000));
327
+
266
328
  const used = new Map<number, string | undefined>();
267
329
  const add = (index: number | undefined, name?: string) => {
268
330
  if (!valid(index)) return;
@@ -329,6 +391,12 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
329
391
  // else filament 1 (ModelVolume::extruder_id's default).
330
392
  if (!used.size && (plate.objectIds.some(id => !objects.has(id)) || (!objects.size && buildItems.length)))
331
393
  for (const key of FEATURES) add(global(key) > 0 ? global(key) : 1);
394
+ // Painting on such an object's own mesh prints its painted filaments.
395
+ for (const index of items) {
396
+ const objectId = itemObject[index];
397
+ if (objectId && !objects.get(objectId)?.parts.length && rootMeshes.has(objectId))
398
+ for (const state of painting.get(`${ROOT_MODEL}#${objectId}`)?.states ?? []) add(state, objects.get(objectId)?.name || undefined);
399
+ }
332
400
  // A mixed filament slot prints as its component filaments (PartPlate.cpp:1437-1449, expand_mixed_filaments in
333
401
  // FilamentMixer.cpp:460-478; components are 1-based, comma-separated, FilamentMixer.cpp:165-180).
334
402
  const mixed = Array.isArray(config.filament_is_mixed) ? (config.filament_is_mixed as unknown[]).map(value => boolOf(value) === true) : [];
@@ -350,5 +418,5 @@ export async function plateFilaments(zip: JSZip, settings: string, model: string
350
418
  result.set(plate.number, [...used.entries()].sort((a, b) => a[0] - b[0]).map(([index, name]) => describe(index, project, name)));
351
419
  }
352
420
  // Every filament the project declares, used on a plate or not: slice_stl takes one profile per declared filament.
353
- return { plates: result, incomplete, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)) };
421
+ return { plates: result, incomplete, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)), buildItems: plateItems, parts: plateParts };
354
422
  }
@@ -40,6 +40,7 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
40
40
  inspect_print_file: "read",
41
41
  blender_mcp_status: "read",
42
42
  counterpart_printer_info: "read",
43
+ counterpart_self_check: "read",
43
44
  counterpart_print_progress: "read",
44
45
  counterpart_print_record: "read",
45
46
  counterpart_print_assess: "control", // local evidence mutation, never a printer command
@@ -28,7 +28,8 @@ export type PrintProgress = {
28
28
  export type PrinterInfo = {
29
29
  contract: typeof COUNTERPART_CONTRACT;
30
30
  server: { name: string; version: string };
31
- printer: { kind: typeof PRINTER_KINDS[number]; model?: string; serial?: string; host: string; name?: string };
31
+ /** displayName: the model with its maker ("Bambu Lab P1S"), shown as given; absent when the model is unknown. */
32
+ printer: { kind: typeof PRINTER_KINDS[number]; model?: string; displayName?: string; serial?: string; host: string; name?: string };
32
33
  capabilities: {
33
34
  cad?: {contract: string; status: string; setup: string; run: string; checkFit: string; prompt: string};
34
35
  progress: boolean; layers: boolean;
@@ -61,6 +62,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
61
62
  properties: {
62
63
  kind: { type: "string", enum: [...PRINTER_KINDS] },
63
64
  model: { type: "string" },
65
+ displayName: { type: "string" },
64
66
  serial: { type: "string" },
65
67
  host: { type: "string" },
66
68
  name: { type: "string" },
@@ -0,0 +1,164 @@
1
+ /**
2
+ * counterpart_self_check (counterpart/1): whether this install's own runtime dependencies and the bundled bambu-node
3
+ * patch loaded, so a client that updated the server can tell a broken install from a working one. Local only: it
4
+ * loads modules from this server's own install and sends nothing to a printer.
5
+ */
6
+ import fs from "node:fs";
7
+ import { createRequire } from "node:module";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { COUNTERPART_CONTRACT } from "./schemas.js";
11
+
12
+ /** optional: an optional dependency, whose failure does not make ok false (mcp-3D-printer-server has one; this server none). */
13
+ export type SelfCheck = { name: string; ok: boolean; optional?: boolean; version?: string; message?: string };
14
+ export type SelfCheckResult = {
15
+ contract: typeof COUNTERPART_CONTRACT;
16
+ server: { name: string; version: string };
17
+ ok: boolean;
18
+ checks: SelfCheck[];
19
+ };
20
+
21
+ export const SELF_CHECK_OUTPUT_SCHEMA = {
22
+ type: "object" as const,
23
+ properties: {
24
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
25
+ server: { type: "object", properties: { name: { type: "string" }, version: { type: "string" } }, required: ["name", "version"] },
26
+ ok: { type: "boolean", description: "Every check passed, optional dependencies aside." },
27
+ checks: {
28
+ type: "array",
29
+ items: {
30
+ type: "object",
31
+ properties: { name: { type: "string" }, ok: { type: "boolean" }, optional: { type: "boolean" }, version: { type: "string" }, message: { type: "string" } },
32
+ required: ["name", "ok"],
33
+ },
34
+ },
35
+ },
36
+ required: ["contract", "server", "ok", "checks"],
37
+ };
38
+
39
+ const PACKAGE_JSON = new URL("../../package.json", import.meta.url);
40
+ /** The module each dependency is loaded through, where its package root is not importable on its own. */
41
+ const ENTRIES: Record<string, string> = {
42
+ "@modelcontextprotocol/sdk": "@modelcontextprotocol/sdk/server/index.js",
43
+ // Only its patch parser runs, at install (scripts/install-patches.mjs); its root is the CLI.
44
+ "patch-package": "patch-package/dist/patch/parse.js",
45
+ };
46
+
47
+ /** The version in the package.json of name that contains file, from this install. */
48
+ function installedVersion(file: string, name: string): string | undefined {
49
+ for (let dir = path.dirname(file); dir !== path.dirname(dir); dir = path.dirname(dir)) {
50
+ const manifest = path.join(dir, "package.json");
51
+ if (!fs.existsSync(manifest)) continue;
52
+ try {
53
+ const parsed = JSON.parse(fs.readFileSync(manifest, "utf8"));
54
+ if (parsed?.name === name) return typeof parsed.version === "string" ? parsed.version : undefined;
55
+ } catch { /* a malformed manifest is not this package's */ }
56
+ }
57
+ return undefined;
58
+ }
59
+
60
+ /** The file specifier resolves to from this module (import.meta.resolve needs Node.js 18.19 or 20.6; older ones require). */
61
+ function resolveFromHere(specifier: string): string {
62
+ return typeof import.meta.resolve === "function"
63
+ ? fileURLToPath(import.meta.resolve(specifier))
64
+ : createRequire(import.meta.url).resolve(specifier);
65
+ }
66
+
67
+ const message = (error: unknown) => error instanceof Error ? error.message : String(error);
68
+
69
+ /**
70
+ * Whether version meets declared, for the forms package.json uses: x.y.z exactly, ^x.y.z (the leftmost non-zero
71
+ * part stays) or ~x.y.z (the minor stays). Other forms are not judged (undefined).
72
+ */
73
+ export function meetsDeclared(version: string, declared: string): boolean | undefined {
74
+ const want = /^([~^]?)(\d+)\.(\d+)\.(\d+)$/.exec(declared.trim());
75
+ const have = /^(\d+)\.(\d+)\.(\d+)(-)?/.exec(version);
76
+ if (!want || !have) return undefined;
77
+ // A prerelease (3.22.21-beta.1) meets none of these forms.
78
+ if (have[4]) return false;
79
+ const [w0, w1, w2] = want.slice(2).map(Number), [h0, h1, h2] = have.slice(1, 4).map(Number);
80
+ const order = h0 - w0 || h1 - w1 || h2 - w2;
81
+ if (want[1] === "") return order === 0;
82
+ if (order < 0) return false;
83
+ if (want[1] === "~") return h0 === w0 && h1 === w1;
84
+ return w0 > 0 ? h0 === w0 : w1 > 0 ? h0 === 0 && h1 === w1 : h0 === 0 && h1 === 0 && h2 === w2;
85
+ }
86
+
87
+ /** Why the installed version does not meet package.json's, or undefined when it does. A form not judged is a failure. */
88
+ export function versionProblem(name: string, version: string | undefined, declared: string): string | undefined {
89
+ const meets = meetsDeclared(version ?? "", declared);
90
+ if (meets === true) return undefined;
91
+ if (meets === undefined && version !== undefined) return `This check cannot judge ${name}'s declared version "${declared}"; ${version} is installed.`;
92
+ return `This server needs ${name} ${declared}; ${version ?? "an unknown version"} is installed.`;
93
+ }
94
+
95
+ /** One dependency: it resolves from this install, loads, and its installed version meets package.json's. */
96
+ async function dependencyCheck(name: string, declared: string): Promise<SelfCheck> {
97
+ const specifier = ENTRIES[name] ?? name;
98
+ try {
99
+ const file = resolveFromHere(specifier);
100
+ const version = installedVersion(file, name);
101
+ await import(specifier);
102
+ const problem = versionProblem(name, version, declared);
103
+ if (problem) return { name, ok: false, ...(version ? { version } : {}), message: problem };
104
+ return { name, ok: true, ...(version ? { version } : {}) };
105
+ } catch (error) {
106
+ return { name, ok: false, message: `${name} did not load: ${message(error)}` };
107
+ }
108
+ }
109
+
110
+ /** Every hunk of the bundled patch is in the installed bambu-node: a read-only reverse dry run, as postinstall checks. */
111
+ function patchApplied(version: string): void {
112
+ const require = createRequire(import.meta.url);
113
+ const root = fs.realpathSync(path.dirname(require.resolve("bambu-node/package.json")));
114
+ const { parsePatchFile } = require("patch-package/dist/patch/parse.js");
115
+ const { executeEffects } = require("patch-package/dist/patch/apply.js");
116
+ const { reversePatch } = require("patch-package/dist/patch/reverse.js");
117
+ const patch = fs.readFileSync(new URL(`../../patches/bambu-node+${version}.patch`, import.meta.url), "utf8");
118
+ const effects = parsePatchFile(patch).map((effect: { type: string; path: string }) => {
119
+ if (effect.type !== "patch" || !effect.path.startsWith("node_modules/bambu-node/")) throw new Error("the bundled patch has an unexpected target");
120
+ return { ...effect, path: effect.path.slice("node_modules/bambu-node/".length) };
121
+ });
122
+ try {
123
+ executeEffects(reversePatch(effects), { cwd: root, dryRun: true, bestEffort: false });
124
+ } catch {
125
+ throw new Error(`the installed bambu-node ${version} is missing part of this server's patch`);
126
+ }
127
+ }
128
+
129
+ /**
130
+ * The bundled patch (patches/bambu-node+<version>.patch) is in the installed bambu-node, and the loaded module
131
+ * behaves patched: it adds the H2-series and later printers to model detection, so an unpatched bambu-node throws
132
+ * "Printer model not supported!" on an H2D's version report. The report is read in memory, without a connection.
133
+ */
134
+ async function bambuNodePatchCheck(version: string | undefined): Promise<SelfCheck> {
135
+ const name = "bambu-node patch";
136
+ try {
137
+ if (!version) throw new Error("package.json names no bambu-node version");
138
+ patchApplied(version);
139
+ const { BambuClient } = await import("bambu-node");
140
+ const serial = "094SELFCHECK";
141
+ const client = new BambuClient({ host: "127.0.0.1", serialNumber: serial, accessToken: "self-check" });
142
+ await (client as any).onMessage(JSON.stringify({ info: { command: "get_version", module: [{ name: "ota", sn: serial }] } }), `device/${serial}/report`);
143
+ const model = (client as any).data?.model;
144
+ return model === "H2D" ? { name, ok: true } : { name, ok: false, message: `bambu-node read an H2D as ${String(model)}; reinstall this server so its patch is applied.` };
145
+ } catch (error) {
146
+ return { name, ok: false, message: `bambu-node is not patched: ${message(error)}. Reinstall this server so its patch is applied.` };
147
+ }
148
+ }
149
+
150
+ export async function selfCheck(server: { name: string; version: string }): Promise<SelfCheckResult> {
151
+ let dependencies: Record<string, string> = {};
152
+ const checks: SelfCheck[] = [];
153
+ try {
154
+ const manifest = JSON.parse(fs.readFileSync(PACKAGE_JSON, "utf8"));
155
+ dependencies = manifest.dependencies ?? {};
156
+ if (manifest.version !== server.version) checks.push({ name: "package", ok: false, version: String(manifest.version), message: `The running server is ${server.version}, but its install is ${manifest.version}; restart it.` });
157
+ else checks.push({ name: "package", ok: true, version: server.version });
158
+ } catch (error) {
159
+ checks.push({ name: "package", ok: false, message: `Could not read this server's package.json: ${message(error)}` });
160
+ }
161
+ checks.push(...await Promise.all(Object.entries(dependencies).map(([name, declared]) => dependencyCheck(name, declared))));
162
+ checks.push(await bambuNodePatchCheck(dependencies["bambu-node"]));
163
+ return { contract: COUNTERPART_CONTRACT, server, ok: checks.every(check => check.ok || check.optional), checks };
164
+ }
package/src/index.ts CHANGED
@@ -88,6 +88,7 @@ import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_C
88
88
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
89
89
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
90
90
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
91
+ import { SELF_CHECK_OUTPUT_SCHEMA, selfCheck } from "./counterpart/self-check.js";
91
92
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
92
93
  import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
93
94
  import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
@@ -161,7 +162,7 @@ const SERVER_INFO = {
161
162
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
162
163
  const OUTPUT_SCHEMA_TOOLS = new Set([
163
164
  "cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
164
- "counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
165
+ "counterpart_printer_info", "counterpart_self_check", "counterpart_print_progress", "counterpart_make_3mf",
165
166
  "counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
166
167
  "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
167
168
  "camera_stream_start", "camera_frame", "camera_stream_stop",
@@ -2602,7 +2603,7 @@ class BambuPrinterMCPServer {
2602
2603
  },
2603
2604
  {
2604
2605
  name: "list_3mf_plates",
2605
- description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it, each object copy's identify_id (instances: the ids slice_stl's skip_objects takes) whether the file already holds its G-code (sliced), and filaments: the project filaments that plate prints with and only those (index from 1 = slice_stl's load_filaments/filament_colours position and print_3mf's ams_mapping position + 1; colour, material, filament_id, and the first part using it), from the slice when there is one, otherwise worked out as Bambu Studio does from the plate's parts, painting, support, layer ranges and tool changes. filaments_complete is false when a part's mesh was too large to read its painting: that plate then lists every declared filament, so offer them all rather than miss one that prints. project_filaments lists every filament the project declares, used or not (slice_stl takes one load_filaments profile per declared filament). A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2606
+ description: "List a Bambu Studio or OrcaSlicer 3MF's plates as its designer laid them out, before slicing: plate_count, and for each plate its index (from 0; slice_stl's slice_plate is index + 1, inspect_print_file's plate_index is index), name, the objects on it, each object copy's identify_id (instances: the ids slice_stl's skip_objects takes) whether the file already holds its G-code (sliced), and filaments: the project filaments that plate prints with and only those (index from 1 = slice_stl's load_filaments/filament_colours position and print_3mf's ams_mapping position + 1; colour, material, filament_id, and the first part using it), from the slice when there is one, otherwise worked out as Bambu Studio does from the plate's parts, painting, support, layer ranges and tool changes. filaments_complete is false when a part's mesh was too large to read its painting: that plate then lists every declared filament, so offer them all rather than miss one that prints. project_filaments lists every filament the project declares, used or not (slice_stl takes one load_filaments profile per declared filament). build_items: the root 3D/3dmodel.model build items on the plate (0-based, build order); parts: each model part of the plate's objects once, with object_id (the mesh object), path when that mesh is in another model part (p:path), build_object_id (the root object a build item places), name, filament (1-based) and painted: true when slicer painting recolours some facets; draw a plate from these with the 3MF's own meshes. A plain 3MF without plate metadata is one plate. include_thumbnails adds each plate's own preview from the file (thumbnail_png_base64). Read-only.",
2606
2607
  inputSchema: {
2607
2608
  type: "object",
2608
2609
  properties: {
@@ -3567,6 +3568,12 @@ class BambuPrinterMCPServer {
3567
3568
  },
3568
3569
  outputSchema: PRINTER_INFO_OUTPUT_SCHEMA
3569
3570
  },
3571
+ {
3572
+ name: "counterpart_self_check",
3573
+ description: "Counterpart contract (counterpart/1): whether this install's own runtime dependencies and its bundled bambu-node patch loaded, each with its installed version. Run it after an update; ok is false when a check failed, with a message saying which. Sends nothing to the printer.",
3574
+ inputSchema: { type: "object", properties: {} },
3575
+ outputSchema: SELF_CHECK_OUTPUT_SCHEMA
3576
+ },
3570
3577
  {
3571
3578
  name: "counterpart_discover_printers",
3572
3579
  description: "Counterpart contract (counterpart/1): Bambu printers on the local network, from their own SSDP announcements (UDP 2021), with serial, model (as bambu_model names it), name and firmware. Listens for duration_ms (default 4000). network is \"unavailable\" when another app holds the port. Never connects to or authenticates with a printer.",
@@ -5098,6 +5105,10 @@ class BambuPrinterMCPServer {
5098
5105
  break;
5099
5106
  }
5100
5107
 
5108
+ case "counterpart_self_check":
5109
+ result = await selfCheck(SERVER_INFO);
5110
+ break;
5111
+
5101
5112
  case "counterpart_printer_info":
5102
5113
  result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
5103
5114
  break;
@@ -23,6 +23,7 @@ import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
23
23
  import { directPrintOptionReport, resolveStudioPrintOptions, usedNozzleCount, type CallerPrintOptions } from "../studio-print-options.js";
24
24
  import { Client as FTPClient } from "basic-ftp";
25
25
  import { uploadBytes } from "./ftp-upload.js";
26
+ import { mergeBambuReport } from "./report-merge.js";
26
27
  import * as mqtt from "mqtt";
27
28
  import {
28
29
  BambuClient,
@@ -425,12 +426,35 @@ class BambuClientStore {
425
426
  return;
426
427
  }
427
428
 
428
- const previous = this.reportSnapshots.get(key) || {};
429
- this.reportSnapshots.set(key, { ...previous, ...update });
429
+ this.reportSnapshots.set(key, mergeBambuReport(this.reportSnapshots.get(key), update));
430
430
  this.reportTimes.set(key, Date.now());
431
431
  this.resolveInitialReport(key);
432
432
  }
433
433
 
434
+ /** Merges the printer's reports into its snapshot as they arrive (tests feed a client without a connection). */
435
+ private watchReports(printer: BambuClient, host: string, serial: string, key: string): void {
436
+ printer.on("rawMessage", (_topic, payload) => {
437
+ try {
438
+ const parsed = JSON.parse(payload.toString());
439
+ const printMessage = parsed?.print;
440
+ if (printMessage && typeof printMessage === "object") {
441
+ this.updateReportSnapshot(key, printMessage);
442
+ this.reportObserved(host, serial, key);
443
+ }
444
+ } catch {
445
+ // Ignore unrelated payloads.
446
+ }
447
+ });
448
+
449
+ // bambu-node passes its whole merged report and then what changed. Only the change is merged here, so a field the
450
+ // printer has not sent again (the previous job's layer) is not copied back over this merge's own reset.
451
+ printer.on("printer:dataUpdate", (_data, changed) => {
452
+ if (!changed || typeof changed !== "object") return;
453
+ this.updateReportSnapshot(key, changed);
454
+ this.reportObserved(host, serial, key);
455
+ });
456
+ }
457
+
434
458
  private reportObserved(host: string, serial: string, key: string): void {
435
459
  const report = this.reportSnapshots.get(key);
436
460
  if (!report || !this.onReport) return;
@@ -528,23 +552,7 @@ class BambuClientStore {
528
552
  });
529
553
  this.ensureInitialReportPromise(key);
530
554
 
531
- printer.on("rawMessage", (_topic, payload) => {
532
- try {
533
- const parsed = JSON.parse(payload.toString());
534
- const printMessage = parsed?.print;
535
- if (printMessage && typeof printMessage === "object") {
536
- this.updateReportSnapshot(key, printMessage);
537
- this.reportObserved(host, serial, key);
538
- }
539
- } catch {
540
- // Ignore unrelated payloads.
541
- }
542
- });
543
-
544
- printer.on("printer:dataUpdate", (data) => {
545
- this.updateReportSnapshot(key, data);
546
- this.reportObserved(host, serial, key);
547
- });
555
+ this.watchReports(printer, host, serial, key);
548
556
 
549
557
  printer.on("client:connect", () => {
550
558
  this.printers.set(key, printer);
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Merging Bambu MQTT reports. P1/A1 printers push only what changed, so a merged report keeps every field until the
3
+ * printer sends it again. A new job's first pushes can carry its name and layer count before its layer number, and the
4
+ * previous job's last layer then read against the new total ("315/150"). Until the new job reports its own progress,
5
+ * its report has none.
6
+ */
7
+
8
+ /**
9
+ * Fields that name the job a report describes. The layer count is not one: a running job's count can be revised, and a
10
+ * different job differs in its name, file or task id.
11
+ */
12
+ const JOB_FIELDS = ["subtask_name", "gcode_file", "task_id"] as const;
13
+ /** A new job prepares (PREPARE, SLICING) after any end; RUNNING straight after FAILED is that job resuming. */
14
+ const PREPARING = new Set(["PREPARE", "SLICING"]);
15
+ const DONE = new Set(["FINISH", "IDLE"]);
16
+
17
+ /** The previous job's progress, left out of a new job's report until the printer reports the new job's own. */
18
+ const JOB_PROGRESS = ["layer_num", "mc_percent", "mc_remaining_time"] as const;
19
+
20
+ /** A job field's value, or undefined for a placeholder: empty, or 0 (LAN prints report task_id "0"). */
21
+ function named(value: unknown): string | undefined {
22
+ const text = value === undefined || value === null ? "" : String(value).trim();
23
+ return text === "" || text === "0" ? undefined : text;
24
+ }
25
+
26
+ /** True when update describes a different job than the report merged before it. */
27
+ export function startsNewJob(previous: Record<string, any> | undefined, update: Record<string, any>): boolean {
28
+ if (!previous) return false;
29
+ for (const field of JOB_FIELDS) {
30
+ const before = named(previous[field]), after = named(update[field]);
31
+ if (before !== undefined && after !== undefined && before !== after) return true;
32
+ }
33
+ const before = String(previous.gcode_state), after = String(update.gcode_state);
34
+ return (DONE.has(before) || before === "FAILED") && PREPARING.has(after) || DONE.has(before) && after === "RUNNING";
35
+ }
36
+
37
+ /** The previous job's progress fields to leave out when update starts a new job without reporting them. */
38
+ export function newJobResets(previous: Record<string, any> | undefined, update: Record<string, any>): string[] {
39
+ if (!startsNewJob(previous, update)) return [];
40
+ return JOB_PROGRESS.filter(field => update[field] === undefined && previous?.[field] !== undefined);
41
+ }
42
+
43
+ /** previous merged with update, without the previous job's progress when update starts a new one (newJobResets). */
44
+ export function mergeBambuReport(previous: Record<string, any> | undefined, update: Record<string, any>): Record<string, any> {
45
+ const merged: Record<string, any> = { ...previous, ...update };
46
+ for (const field of newJobResets(previous, update)) delete merged[field];
47
+ return merged;
48
+ }