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
@@ -72,7 +72,7 @@ export async function listModelPlates(filePath, options = {}) {
72
72
  const instanceId = Number(/<metadata\s+key="instance_id"\s+value="(\d+)"/.exec(instance[1])?.[1] ?? 0);
73
73
  return objectId ? [{ objectId, instanceId }] : [];
74
74
  }) });
75
- plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [], filaments_complete: true,
75
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [], filaments_complete: true, build_items: [], parts: [],
76
76
  objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])] : []) });
77
77
  }
78
78
  for (const name of Object.keys(zip.files)) {
@@ -82,7 +82,7 @@ export async function listModelPlates(filePath, options = {}) {
82
82
  const number = Number(match[1]);
83
83
  if (!valid(number))
84
84
  continue;
85
- const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true };
85
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true, build_items: [], parts: [] };
86
86
  const layout = layouts.get(number) ?? { number, objectIds: [] };
87
87
  layouts.set(number, layout);
88
88
  if (match[2] === "gcode")
@@ -104,9 +104,9 @@ export async function listModelPlates(filePath, options = {}) {
104
104
  result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
105
105
  // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
106
106
  if (!result.plates.length) {
107
- result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true });
107
+ result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true, build_items: [], parts: [] });
108
108
  // Without plates every object is on the one plate.
109
- layouts.set(1, { number: 1, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
109
+ layouts.set(1, { number: 1, allItems: true, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
110
110
  }
111
111
  const geometry = has("item") && (has("mesh") || has("component"));
112
112
  if (!geometry) {
@@ -123,6 +123,11 @@ export async function listModelPlates(filePath, options = {}) {
123
123
  for (const plate of result.plates) {
124
124
  plate.filaments = filaments.plates.get(plate.index + 1) ?? [];
125
125
  plate.filaments_complete = !filaments.incomplete.has(plate.index + 1);
126
+ // A sliced-only file has no model to draw from.
127
+ if (geometry) {
128
+ plate.build_items = filaments.buildItems.get(plate.index + 1) ?? [];
129
+ plate.parts = filaments.parts.get(plate.index + 1) ?? [];
130
+ }
126
131
  }
127
132
  result.project_filaments = filaments.project;
128
133
  if (options.thumbnails)
@@ -34,6 +34,21 @@ export interface PlateFilament {
34
34
  /** The first part (else object) on this plate that prints with it; absent for support, painting or tool changes only. */
35
35
  name?: string;
36
36
  }
37
+ /**
38
+ * One part on a plate, as the open 3MF standard places it, so a client draws it in its filament's colour without
39
+ * reading slicer files: the mesh object `object_id`, in the model part `path` when that is not the root
40
+ * 3D/3dmodel.model (production extension p:path, as the file names it), and the 1-based project filament it prints
41
+ * with. `painted` is true when the slicer's painting (paint_color) recolours some of its facets.
42
+ */
43
+ export interface PlatePart {
44
+ object_id: number;
45
+ /** The root object (a build item's objectid) this part belongs to: copies of one mesh may print in other filaments. */
46
+ build_object_id: number;
47
+ path?: string;
48
+ name: string;
49
+ filament: number;
50
+ painted?: true;
51
+ }
37
52
  type Settings = Map<string, string>;
38
53
  interface Part {
39
54
  id: string;
@@ -74,6 +89,8 @@ export interface PlateLayout {
74
89
  }[];
75
90
  /** Metadata/plate_N.json filament_ids (0-based) when the file holds this plate's slice. */
76
91
  slicedFilamentIds?: number[];
92
+ /** The file has no plate metadata: this one plate holds every build item. */
93
+ allItems?: boolean;
77
94
  }
78
95
  /**
79
96
  * The filaments each plate prints with, keyed by plate number. `settings` is model_settings.config, `model` the root
@@ -83,5 +100,7 @@ export declare function plateFilaments(zip: JSZip, settings: string, model: stri
83
100
  plates: Map<number, PlateFilament[]>;
84
101
  incomplete: Set<number>;
85
102
  project: PlateFilament[];
103
+ buildItems: Map<number, number[]>;
104
+ parts: Map<number, PlatePart[]>;
86
105
  }>;
87
106
  export {};
@@ -9,11 +9,12 @@ const metadataOf = (block) => new Map([...block.matchAll(/<metadata\s+key="([^"]
9
9
  /** model_settings.config objects with their own settings and parts (parts never nest). */
10
10
  export function readModelObjects(settings) {
11
11
  return [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/object>/g)].map(match => {
12
- const parts = [...match[2].matchAll(/<part\b([^>]*)>([\s\S]*?)<\/part>/g)].map(part => {
13
- const own = metadataOf(part[2]);
12
+ // A part may be self-closing (<part id="1" subtype="normal_part"/>): it has no settings of its own.
13
+ const parts = [...match[2].matchAll(/<part\b([^>]*?)(?:\/>|>([\s\S]*?)<\/part>)/g)].map(part => {
14
+ const own = metadataOf(part[2] ?? "");
14
15
  return { id: /\bid="(\d+)"/.exec(part[1])?.[1] ?? "", subtype: /\bsubtype="([^"]+)"/.exec(part[1])?.[1] ?? "normal_part", name: words(own.get("name") ?? ""), settings: own };
15
16
  });
16
- const own = metadataOf(match[2].replace(/<part\b[^>]*>[\s\S]*?<\/part>/g, ""));
17
+ const own = metadataOf(match[2].replace(/<part\b[^>]*?(?:\/>|>[\s\S]*?<\/part>)/g, ""));
17
18
  return { id: match[1], name: words(own.get("name") ?? ""), settings: own, parts };
18
19
  });
19
20
  }
@@ -165,7 +166,11 @@ export async function plateFilaments(zip, settings, model, plates, limits = PAIN
165
166
  const objects = new Map(readModelObjects(settings).map(object => [object.id, object]));
166
167
  // Root objects' components: which sub-object mesh in which file each part is (part id = component objectid).
167
168
  const components = new Map();
169
+ // Root objects that are meshes themselves (a plain 3MF): their own id is the part.
170
+ const rootMeshes = new Set();
168
171
  for (const object of model.matchAll(/<(?:\w+:)?object\b[^>]*\bid="(\d+)"[^>]*>([\s\S]*?)<\/(?:\w+:)?object>/g)) {
172
+ if (/<(?:\w+:)?mesh[\s>]/.test(object[2]))
173
+ rootMeshes.add(object[1]);
169
174
  const parts = new Map();
170
175
  for (const component of object[2].matchAll(/<(?:\w+:)?component\b([^>]*)\/?>/g)) {
171
176
  const path = /\b(?:\w+:)?path="\/?([^"]+)"/.exec(component[1])?.[1];
@@ -216,20 +221,70 @@ export async function plateFilaments(zip, settings, model, plates, limits = PAIN
216
221
  .filter(layer => /\btype="2"/.test(layer[1]))
217
222
  .map(layer => Number(/\bextruder="(\d+)"/.exec(layer[1])?.[1])));
218
223
  }
219
- // Painting only matters for parts on a plate that is not sliced yet.
224
+ // Painting decides an unsliced plate's filaments, and marks painted parts on every plate. Unsliced plates' meshes
225
+ // come first, so the read budget goes to the filament lists before the painted marks.
220
226
  const paintPaths = new Set();
221
- for (const plate of plates)
222
- if (!plate.slicedFilamentIds)
223
- for (const objectId of plate.objectIds)
224
- for (const path of components.get(objectId)?.values() ?? [])
225
- paintPaths.add(path);
227
+ for (const sliced of [false, true])
228
+ for (const plate of plates)
229
+ if (!!plate.slicedFilamentIds === sliced)
230
+ for (const objectId of plate.objectIds)
231
+ for (const path of components.get(objectId)?.values() ?? [])
232
+ paintPaths.add(path);
233
+ // A build item whose object is itself the mesh (a plain 3MF) keeps its painting in the root model.
234
+ const ROOT_MODEL = "3D/3dmodel.model";
235
+ if (buildItems.some(item => rootMeshes.has(/\bobjectid="(\d+)"/.exec(item)?.[1] ?? "")))
236
+ paintPaths.add(ROOT_MODEL);
226
237
  const { painting, unread } = await readPainting(zip, paintPaths, limits);
227
238
  // Plates with a part whose painting couldn't be read: they list every declared filament and say they're incomplete.
228
239
  const incomplete = new Set();
229
240
  const global = (key) => intOf(config[key]) ?? 0;
230
241
  const FEATURES = ["wall_filament", "sparse_infill_filament", "solid_infill_filament"];
231
242
  const result = new Map();
243
+ const plateItems = new Map();
244
+ const plateParts = new Map();
245
+ const itemObject = buildItems.map(item => /\bobjectid="(\d+)"/.exec(item)?.[1]);
246
+ // The plate's copies as root build items (0-based, in build order): a copy is its object's instance_id-th item.
247
+ const plateItemsOf = (plate) => {
248
+ const items = new Set();
249
+ if (plate.instances?.length)
250
+ for (const copy of plate.instances) {
251
+ let seen = -1;
252
+ const index = itemObject.findIndex(objectId => objectId === copy.objectId && ++seen === copy.instanceId);
253
+ if (index >= 0)
254
+ items.add(index);
255
+ }
256
+ else
257
+ itemObject.forEach((objectId, index) => { if (objectId && (plate.allItems || plate.objectIds.includes(objectId)))
258
+ items.add(index); });
259
+ return items;
260
+ };
232
261
  for (const plate of plates) {
262
+ const items = plateItemsOf(plate);
263
+ plateItems.set(plate.number, [...items].sort((a, b) => a - b));
264
+ // Each model part of the plate's objects once, in its own filament: what a client colours when it draws the plate.
265
+ const drawn = [];
266
+ for (const objectId of [...new Set([...items].map(index => itemObject[index]))]) {
267
+ const object = objects.get(objectId);
268
+ const meshes = components.get(objectId);
269
+ const objectFilament = intOf(object?.settings.get("extruder")) || (global("wall_filament") > 0 ? global("wall_filament") : 1);
270
+ const entry = (id, name, filament) => {
271
+ const path = meshes?.get(id) ?? (id === objectId && rootMeshes.has(objectId) ? ROOT_MODEL : undefined);
272
+ const paint = path ? painting.get(`${path}#${id}`) : undefined;
273
+ drawn.push({ object_id: Number(id), build_object_id: Number(objectId), ...(path && path !== "3D/3dmodel.model" ? { path: `/${path}` } : {}), name,
274
+ filament: valid(filament) ? filament : 1, ...(paint?.states.size ? { painted: true } : {}) });
275
+ };
276
+ if (object?.parts.length) {
277
+ for (const part of object.parts)
278
+ if (part.subtype === "normal_part" && /^\d+$/.test(part.id))
279
+ entry(part.id, part.name || object.name, intOf(part.settings.get("extruder")) || objectFilament);
280
+ }
281
+ else if (meshes)
282
+ for (const id of meshes.keys())
283
+ entry(id, object?.name ?? "", objectFilament);
284
+ else if (rootMeshes.has(objectId))
285
+ entry(objectId, object?.name ?? "", objectFilament);
286
+ }
287
+ plateParts.set(plate.number, drawn.slice(0, 1000));
233
288
  const used = new Map();
234
289
  const add = (index, name) => {
235
290
  if (!valid(index))
@@ -313,6 +368,13 @@ export async function plateFilaments(zip, settings, model, plates, limits = PAIN
313
368
  if (!used.size && (plate.objectIds.some(id => !objects.has(id)) || (!objects.size && buildItems.length)))
314
369
  for (const key of FEATURES)
315
370
  add(global(key) > 0 ? global(key) : 1);
371
+ // Painting on such an object's own mesh prints its painted filaments.
372
+ for (const index of items) {
373
+ const objectId = itemObject[index];
374
+ if (objectId && !objects.get(objectId)?.parts.length && rootMeshes.has(objectId))
375
+ for (const state of painting.get(`${ROOT_MODEL}#${objectId}`)?.states ?? [])
376
+ add(state, objects.get(objectId)?.name || undefined);
377
+ }
316
378
  // A mixed filament slot prints as its component filaments (PartPlate.cpp:1437-1449, expand_mixed_filaments in
317
379
  // FilamentMixer.cpp:460-478; components are 1-based, comma-separated, FilamentMixer.cpp:165-180).
318
380
  const mixed = Array.isArray(config.filament_is_mixed) ? config.filament_is_mixed.map(value => boolOf(value) === true) : [];
@@ -338,5 +400,5 @@ export async function plateFilaments(zip, settings, model, plates, limits = PAIN
338
400
  result.set(plate.number, [...used.entries()].sort((a, b) => a[0] - b[0]).map(([index, name]) => describe(index, project, name)));
339
401
  }
340
402
  // Every filament the project declares, used on a plate or not: slice_stl takes one profile per declared filament.
341
- return { plates: result, incomplete, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)) };
403
+ return { plates: result, incomplete, project: Array.from({ length: declared }, (_, i) => describe(i + 1, project)), buildItems: plateItems, parts: plateParts };
342
404
  }
@@ -17,6 +17,7 @@ export const REMOTE_SCOPES = {
17
17
  inspect_print_file: "read",
18
18
  blender_mcp_status: "read",
19
19
  counterpart_printer_info: "read",
20
+ counterpart_self_check: "read",
20
21
  counterpart_print_progress: "read",
21
22
  counterpart_print_record: "read",
22
23
  counterpart_print_assess: "control", // local evidence mutation, never a printer command
@@ -54,9 +54,11 @@ export type PrinterInfo = {
54
54
  name: string;
55
55
  version: string;
56
56
  };
57
+ /** displayName: the model with its maker ("Bambu Lab P1S"), shown as given; absent when the model is unknown. */
57
58
  printer: {
58
59
  kind: typeof PRINTER_KINDS[number];
59
60
  model?: string;
61
+ displayName?: string;
60
62
  serial?: string;
61
63
  host: string;
62
64
  name?: string;
@@ -117,6 +119,9 @@ export declare const PRINTER_INFO_OUTPUT_SCHEMA: {
117
119
  model: {
118
120
  type: string;
119
121
  };
122
+ displayName: {
123
+ type: string;
124
+ };
120
125
  serial: {
121
126
  type: string;
122
127
  };
@@ -253,7 +258,7 @@ export declare const PRINT_PROGRESS_OUTPUT_SCHEMA: {
253
258
  };
254
259
  state: {
255
260
  type: string;
256
- enum: ("failed" | "cancelled" | "idle" | "offline" | "preparing" | "printing" | "paused" | "finished" | "busy")[];
261
+ enum: ("failed" | "cancelled" | "idle" | "preparing" | "printing" | "paused" | "finished" | "offline" | "busy")[];
257
262
  };
258
263
  job: {
259
264
  type: string;
@@ -348,7 +353,7 @@ export declare const PRINT_PROGRESS_OUTPUT_SCHEMA: {
348
353
  };
349
354
  severity: {
350
355
  type: string;
351
- enum: ("error" | "info" | "fatal" | "warning")[];
356
+ enum: ("fatal" | "error" | "info" | "warning")[];
352
357
  };
353
358
  message: {
354
359
  type: string;
@@ -28,6 +28,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
28
28
  properties: {
29
29
  kind: { type: "string", enum: [...PRINTER_KINDS] },
30
30
  model: { type: "string" },
31
+ displayName: { type: "string" },
31
32
  serial: { type: "string" },
32
33
  host: { type: "string" },
33
34
  name: { type: "string" },
@@ -0,0 +1,79 @@
1
+ import { COUNTERPART_CONTRACT } from "./schemas.js";
2
+ /** optional: an optional dependency, whose failure does not make ok false (mcp-3D-printer-server has one; this server none). */
3
+ export type SelfCheck = {
4
+ name: string;
5
+ ok: boolean;
6
+ optional?: boolean;
7
+ version?: string;
8
+ message?: string;
9
+ };
10
+ export type SelfCheckResult = {
11
+ contract: typeof COUNTERPART_CONTRACT;
12
+ server: {
13
+ name: string;
14
+ version: string;
15
+ };
16
+ ok: boolean;
17
+ checks: SelfCheck[];
18
+ };
19
+ export declare const SELF_CHECK_OUTPUT_SCHEMA: {
20
+ type: "object";
21
+ properties: {
22
+ contract: {
23
+ type: string;
24
+ const: string;
25
+ };
26
+ server: {
27
+ type: string;
28
+ properties: {
29
+ name: {
30
+ type: string;
31
+ };
32
+ version: {
33
+ type: string;
34
+ };
35
+ };
36
+ required: string[];
37
+ };
38
+ ok: {
39
+ type: string;
40
+ description: string;
41
+ };
42
+ checks: {
43
+ type: string;
44
+ items: {
45
+ type: string;
46
+ properties: {
47
+ name: {
48
+ type: string;
49
+ };
50
+ ok: {
51
+ type: string;
52
+ };
53
+ optional: {
54
+ type: string;
55
+ };
56
+ version: {
57
+ type: string;
58
+ };
59
+ message: {
60
+ type: string;
61
+ };
62
+ };
63
+ required: string[];
64
+ };
65
+ };
66
+ };
67
+ required: string[];
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 declare function meetsDeclared(version: string, declared: string): boolean | undefined;
74
+ /** Why the installed version does not meet package.json's, or undefined when it does. A form not judged is a failure. */
75
+ export declare function versionProblem(name: string, version: string | undefined, declared: string): string | undefined;
76
+ export declare function selfCheck(server: {
77
+ name: string;
78
+ version: string;
79
+ }): Promise<SelfCheckResult>;
@@ -0,0 +1,163 @@
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
+ export const SELF_CHECK_OUTPUT_SCHEMA = {
12
+ type: "object",
13
+ properties: {
14
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
15
+ server: { type: "object", properties: { name: { type: "string" }, version: { type: "string" } }, required: ["name", "version"] },
16
+ ok: { type: "boolean", description: "Every check passed, optional dependencies aside." },
17
+ checks: {
18
+ type: "array",
19
+ items: {
20
+ type: "object",
21
+ properties: { name: { type: "string" }, ok: { type: "boolean" }, optional: { type: "boolean" }, version: { type: "string" }, message: { type: "string" } },
22
+ required: ["name", "ok"],
23
+ },
24
+ },
25
+ },
26
+ required: ["contract", "server", "ok", "checks"],
27
+ };
28
+ const PACKAGE_JSON = new URL("../../package.json", import.meta.url);
29
+ /** The module each dependency is loaded through, where its package root is not importable on its own. */
30
+ const ENTRIES = {
31
+ "@modelcontextprotocol/sdk": "@modelcontextprotocol/sdk/server/index.js",
32
+ // Only its patch parser runs, at install (scripts/install-patches.mjs); its root is the CLI.
33
+ "patch-package": "patch-package/dist/patch/parse.js",
34
+ };
35
+ /** The version in the package.json of name that contains file, from this install. */
36
+ function installedVersion(file, name) {
37
+ for (let dir = path.dirname(file); dir !== path.dirname(dir); dir = path.dirname(dir)) {
38
+ const manifest = path.join(dir, "package.json");
39
+ if (!fs.existsSync(manifest))
40
+ continue;
41
+ try {
42
+ const parsed = JSON.parse(fs.readFileSync(manifest, "utf8"));
43
+ if (parsed?.name === name)
44
+ return typeof parsed.version === "string" ? parsed.version : undefined;
45
+ }
46
+ catch { /* a malformed manifest is not this package's */ }
47
+ }
48
+ return undefined;
49
+ }
50
+ /** The file specifier resolves to from this module (import.meta.resolve needs Node.js 18.19 or 20.6; older ones require). */
51
+ function resolveFromHere(specifier) {
52
+ return typeof import.meta.resolve === "function"
53
+ ? fileURLToPath(import.meta.resolve(specifier))
54
+ : createRequire(import.meta.url).resolve(specifier);
55
+ }
56
+ const message = (error) => error instanceof Error ? error.message : String(error);
57
+ /**
58
+ * Whether version meets declared, for the forms package.json uses: x.y.z exactly, ^x.y.z (the leftmost non-zero
59
+ * part stays) or ~x.y.z (the minor stays). Other forms are not judged (undefined).
60
+ */
61
+ export function meetsDeclared(version, declared) {
62
+ const want = /^([~^]?)(\d+)\.(\d+)\.(\d+)$/.exec(declared.trim());
63
+ const have = /^(\d+)\.(\d+)\.(\d+)(-)?/.exec(version);
64
+ if (!want || !have)
65
+ return undefined;
66
+ // A prerelease (3.22.21-beta.1) meets none of these forms.
67
+ if (have[4])
68
+ return false;
69
+ const [w0, w1, w2] = want.slice(2).map(Number), [h0, h1, h2] = have.slice(1, 4).map(Number);
70
+ const order = h0 - w0 || h1 - w1 || h2 - w2;
71
+ if (want[1] === "")
72
+ return order === 0;
73
+ if (order < 0)
74
+ return false;
75
+ if (want[1] === "~")
76
+ return h0 === w0 && h1 === w1;
77
+ return w0 > 0 ? h0 === w0 : w1 > 0 ? h0 === 0 && h1 === w1 : h0 === 0 && h1 === 0 && h2 === w2;
78
+ }
79
+ /** Why the installed version does not meet package.json's, or undefined when it does. A form not judged is a failure. */
80
+ export function versionProblem(name, version, declared) {
81
+ const meets = meetsDeclared(version ?? "", declared);
82
+ if (meets === true)
83
+ return undefined;
84
+ if (meets === undefined && version !== undefined)
85
+ return `This check cannot judge ${name}'s declared version "${declared}"; ${version} is installed.`;
86
+ return `This server needs ${name} ${declared}; ${version ?? "an unknown version"} is installed.`;
87
+ }
88
+ /** One dependency: it resolves from this install, loads, and its installed version meets package.json's. */
89
+ async function dependencyCheck(name, declared) {
90
+ const specifier = ENTRIES[name] ?? name;
91
+ try {
92
+ const file = resolveFromHere(specifier);
93
+ const version = installedVersion(file, name);
94
+ await import(specifier);
95
+ const problem = versionProblem(name, version, declared);
96
+ if (problem)
97
+ return { name, ok: false, ...(version ? { version } : {}), message: problem };
98
+ return { name, ok: true, ...(version ? { version } : {}) };
99
+ }
100
+ catch (error) {
101
+ return { name, ok: false, message: `${name} did not load: ${message(error)}` };
102
+ }
103
+ }
104
+ /** Every hunk of the bundled patch is in the installed bambu-node: a read-only reverse dry run, as postinstall checks. */
105
+ function patchApplied(version) {
106
+ const require = createRequire(import.meta.url);
107
+ const root = fs.realpathSync(path.dirname(require.resolve("bambu-node/package.json")));
108
+ const { parsePatchFile } = require("patch-package/dist/patch/parse.js");
109
+ const { executeEffects } = require("patch-package/dist/patch/apply.js");
110
+ const { reversePatch } = require("patch-package/dist/patch/reverse.js");
111
+ const patch = fs.readFileSync(new URL(`../../patches/bambu-node+${version}.patch`, import.meta.url), "utf8");
112
+ const effects = parsePatchFile(patch).map((effect) => {
113
+ if (effect.type !== "patch" || !effect.path.startsWith("node_modules/bambu-node/"))
114
+ throw new Error("the bundled patch has an unexpected target");
115
+ return { ...effect, path: effect.path.slice("node_modules/bambu-node/".length) };
116
+ });
117
+ try {
118
+ executeEffects(reversePatch(effects), { cwd: root, dryRun: true, bestEffort: false });
119
+ }
120
+ catch {
121
+ throw new Error(`the installed bambu-node ${version} is missing part of this server's patch`);
122
+ }
123
+ }
124
+ /**
125
+ * The bundled patch (patches/bambu-node+<version>.patch) is in the installed bambu-node, and the loaded module
126
+ * behaves patched: it adds the H2-series and later printers to model detection, so an unpatched bambu-node throws
127
+ * "Printer model not supported!" on an H2D's version report. The report is read in memory, without a connection.
128
+ */
129
+ async function bambuNodePatchCheck(version) {
130
+ const name = "bambu-node patch";
131
+ try {
132
+ if (!version)
133
+ throw new Error("package.json names no bambu-node version");
134
+ patchApplied(version);
135
+ const { BambuClient } = await import("bambu-node");
136
+ const serial = "094SELFCHECK";
137
+ const client = new BambuClient({ host: "127.0.0.1", serialNumber: serial, accessToken: "self-check" });
138
+ await client.onMessage(JSON.stringify({ info: { command: "get_version", module: [{ name: "ota", sn: serial }] } }), `device/${serial}/report`);
139
+ const model = client.data?.model;
140
+ 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.` };
141
+ }
142
+ catch (error) {
143
+ return { name, ok: false, message: `bambu-node is not patched: ${message(error)}. Reinstall this server so its patch is applied.` };
144
+ }
145
+ }
146
+ export async function selfCheck(server) {
147
+ let dependencies = {};
148
+ const checks = [];
149
+ try {
150
+ const manifest = JSON.parse(fs.readFileSync(PACKAGE_JSON, "utf8"));
151
+ dependencies = manifest.dependencies ?? {};
152
+ if (manifest.version !== server.version)
153
+ 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.` });
154
+ else
155
+ checks.push({ name: "package", ok: true, version: server.version });
156
+ }
157
+ catch (error) {
158
+ checks.push({ name: "package", ok: false, message: `Could not read this server's package.json: ${message(error)}` });
159
+ }
160
+ checks.push(...await Promise.all(Object.entries(dependencies).map(([name, declared]) => dependencyCheck(name, declared))));
161
+ checks.push(await bambuNodePatchCheck(dependencies["bambu-node"]));
162
+ return { contract: COUNTERPART_CONTRACT, server, ok: checks.every(check => check.ok || check.optional), checks };
163
+ }
package/dist/index.js CHANGED
@@ -57,6 +57,7 @@ import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_C
57
57
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
58
58
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
59
59
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
60
+ import { SELF_CHECK_OUTPUT_SCHEMA, selfCheck } from "./counterpart/self-check.js";
60
61
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
61
62
  import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
62
63
  import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
@@ -125,7 +126,7 @@ const SERVER_INFO = {
125
126
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
126
127
  const OUTPUT_SCHEMA_TOOLS = new Set([
127
128
  "cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
128
- "counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
129
+ "counterpart_printer_info", "counterpart_self_check", "counterpart_print_progress", "counterpart_make_3mf",
129
130
  "counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
130
131
  "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
131
132
  "camera_stream_start", "camera_frame", "camera_stream_stop",
@@ -2093,7 +2094,7 @@ class BambuPrinterMCPServer {
2093
2094
  },
2094
2095
  {
2095
2096
  name: "list_3mf_plates",
2096
- 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.",
2097
+ 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.",
2097
2098
  inputSchema: {
2098
2099
  type: "object",
2099
2100
  properties: {
@@ -3058,6 +3059,12 @@ class BambuPrinterMCPServer {
3058
3059
  },
3059
3060
  outputSchema: PRINTER_INFO_OUTPUT_SCHEMA
3060
3061
  },
3062
+ {
3063
+ name: "counterpart_self_check",
3064
+ 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.",
3065
+ inputSchema: { type: "object", properties: {} },
3066
+ outputSchema: SELF_CHECK_OUTPUT_SCHEMA
3067
+ },
3061
3068
  {
3062
3069
  name: "counterpart_discover_printers",
3063
3070
  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.",
@@ -4375,6 +4382,9 @@ class BambuPrinterMCPServer {
4375
4382
  sliced: args?.sliced === true, names: colourNames() });
4376
4383
  break;
4377
4384
  }
4385
+ case "counterpart_self_check":
4386
+ result = await selfCheck(SERVER_INFO);
4387
+ break;
4378
4388
  case "counterpart_printer_info":
4379
4389
  result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
4380
4390
  break;
@@ -23,6 +23,7 @@ import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "./camera-models.js";
23
23
  import { directPrintOptionReport, resolveStudioPrintOptions, usedNozzleCount } 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 { BambuClient, GCodeFileCommand, GCodeLineCommand, PushAllCommand, UpdateFanCommand, UpdateLightCommand, } from "bambu-node";
28
29
  /**
@@ -355,11 +356,34 @@ class BambuClientStore {
355
356
  if (!update || Object.keys(update).length === 0) {
356
357
  return;
357
358
  }
358
- const previous = this.reportSnapshots.get(key) || {};
359
- this.reportSnapshots.set(key, { ...previous, ...update });
359
+ this.reportSnapshots.set(key, mergeBambuReport(this.reportSnapshots.get(key), update));
360
360
  this.reportTimes.set(key, Date.now());
361
361
  this.resolveInitialReport(key);
362
362
  }
363
+ /** Merges the printer's reports into its snapshot as they arrive (tests feed a client without a connection). */
364
+ watchReports(printer, host, serial, key) {
365
+ printer.on("rawMessage", (_topic, payload) => {
366
+ try {
367
+ const parsed = JSON.parse(payload.toString());
368
+ const printMessage = parsed?.print;
369
+ if (printMessage && typeof printMessage === "object") {
370
+ this.updateReportSnapshot(key, printMessage);
371
+ this.reportObserved(host, serial, key);
372
+ }
373
+ }
374
+ catch {
375
+ // Ignore unrelated payloads.
376
+ }
377
+ });
378
+ // bambu-node passes its whole merged report and then what changed. Only the change is merged here, so a field the
379
+ // printer has not sent again (the previous job's layer) is not copied back over this merge's own reset.
380
+ printer.on("printer:dataUpdate", (_data, changed) => {
381
+ if (!changed || typeof changed !== "object")
382
+ return;
383
+ this.updateReportSnapshot(key, changed);
384
+ this.reportObserved(host, serial, key);
385
+ });
386
+ }
363
387
  reportObserved(host, serial, key) {
364
388
  const report = this.reportSnapshots.get(key);
365
389
  if (!report || !this.onReport)
@@ -447,23 +471,7 @@ class BambuClientStore {
447
471
  accessToken: token,
448
472
  });
449
473
  this.ensureInitialReportPromise(key);
450
- printer.on("rawMessage", (_topic, payload) => {
451
- try {
452
- const parsed = JSON.parse(payload.toString());
453
- const printMessage = parsed?.print;
454
- if (printMessage && typeof printMessage === "object") {
455
- this.updateReportSnapshot(key, printMessage);
456
- this.reportObserved(host, serial, key);
457
- }
458
- }
459
- catch {
460
- // Ignore unrelated payloads.
461
- }
462
- });
463
- printer.on("printer:dataUpdate", (data) => {
464
- this.updateReportSnapshot(key, data);
465
- this.reportObserved(host, serial, key);
466
- });
474
+ this.watchReports(printer, host, serial, key);
467
475
  printer.on("client:connect", () => {
468
476
  this.printers.set(key, printer);
469
477
  this.initialConnectionPromises.delete(key);
@@ -0,0 +1,12 @@
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
+ /** True when update describes a different job than the report merged before it. */
8
+ export declare function startsNewJob(previous: Record<string, any> | undefined, update: Record<string, any>): boolean;
9
+ /** The previous job's progress fields to leave out when update starts a new job without reporting them. */
10
+ export declare function newJobResets(previous: Record<string, any> | undefined, update: Record<string, any>): string[];
11
+ /** previous merged with update, without the previous job's progress when update starts a new one (newJobResets). */
12
+ export declare function mergeBambuReport(previous: Record<string, any> | undefined, update: Record<string, any>): Record<string, any>;