bambu-printer-mcp 1.1.93 → 1.1.95

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 (41) hide show
  1. package/README.md +6 -3
  2. package/dist/3mf_parser.js +3 -2
  3. package/dist/cad/contracts.d.ts +10 -0
  4. package/dist/cad/contracts.js +41 -1
  5. package/dist/cad-engine.d.ts +5 -0
  6. package/dist/cad-engine.js +74 -3
  7. package/dist/counterpart/diagnostics.d.ts +163 -0
  8. package/dist/counterpart/diagnostics.js +816 -0
  9. package/dist/counterpart/flight-tools.d.ts +2 -2
  10. package/dist/counterpart/info.js +1 -0
  11. package/dist/counterpart/make-3mf.d.ts +10 -0
  12. package/dist/counterpart/make-3mf.js +472 -65
  13. package/dist/counterpart/model-plates.d.ts +8 -1
  14. package/dist/counterpart/model-plates.js +9 -4
  15. package/dist/counterpart/plate-filaments.d.ts +19 -0
  16. package/dist/counterpart/plate-filaments.js +72 -10
  17. package/dist/counterpart/remote.js +1 -0
  18. package/dist/counterpart/schemas.d.ts +8 -2
  19. package/dist/counterpart/schemas.js +1 -0
  20. package/dist/index.js +100 -2
  21. package/dist/tool-annotations.js +1 -0
  22. package/package.json +2 -2
  23. package/src/3mf_parser.ts +3 -2
  24. package/src/cad/contracts.ts +46 -1
  25. package/src/cad/examples/desk_clamp_hook.py +32 -0
  26. package/src/cad/examples/desk_edge_cable_holder.py +24 -0
  27. package/src/cad/examples/phone_stand.py +26 -0
  28. package/src/cad/geometry.py +52 -2
  29. package/src/cad/project3mf.py +426 -0
  30. package/src/cad/purpose.py +492 -0
  31. package/src/cad/worker.py +17 -2
  32. package/src/cad-engine.ts +73 -3
  33. package/src/counterpart/diagnostics.ts +775 -0
  34. package/src/counterpart/info.ts +1 -0
  35. package/src/counterpart/make-3mf.ts +446 -61
  36. package/src/counterpart/model-plates.ts +17 -5
  37. package/src/counterpart/plate-filaments.ts +75 -7
  38. package/src/counterpart/remote.ts +1 -0
  39. package/src/counterpart/schemas.ts +3 -0
  40. package/src/index.ts +83 -2
  41. package/src/tool-annotations.ts +1 -0
@@ -8,7 +8,7 @@
8
8
  * is one plate. Only bounded metadata is read; nothing is extracted or run.
9
9
  */
10
10
  import { readSafe3mfArchive } from "../safety/archive.js";
11
- import { PAINT_LIMITS, plateFilaments, type PaintLimits, type PlateFilament, type PlateLayout } from "./plate-filaments.js";
11
+ import { PAINT_LIMITS, plateFilaments, type PaintLimits, type PlateFilament, type PlateLayout, type PlatePart } from "./plate-filaments.js";
12
12
 
13
13
  export interface ModelPlate {
14
14
  /** Zero-based, as inspect_print_file's plate_index; slice_stl's slice_plate is index + 1. */
@@ -34,6 +34,13 @@ export interface ModelPlate {
34
34
  * so every declared filament is listed rather than risk leaving out one that prints. A client offers them all.
35
35
  */
36
36
  filaments_complete: boolean;
37
+ /**
38
+ * The root 3D/3dmodel.model build items on this plate, 0-based in build order (counterpart/1): the copies a client
39
+ * places to draw this plate from the open 3MF standard alone. Empty for a sliced-only file without a model.
40
+ */
41
+ build_items: number[];
42
+ /** Each model part of this plate's objects once, with the filament it prints in (counterpart/1; see PlatePart). */
43
+ parts: PlatePart[];
37
44
  /** The plate's own preview from the file (Metadata/plate_N.png), when asked for and present. */
38
45
  thumbnail_png_base64?: string;
39
46
  }
@@ -108,7 +115,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
108
115
  const instanceId = Number(/<metadata\s+key="instance_id"\s+value="(\d+)"/.exec(instance[1])?.[1] ?? 0);
109
116
  return objectId ? [{ objectId, instanceId }] : [];
110
117
  }) });
111
- plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [], filaments_complete: true,
118
+ plates.set(number, { index: number - 1, name: words(name?.[1] ?? "") || `Plate ${number}`, sliced: false, instances, filaments: [], filaments_complete: true, build_items: [], parts: [],
112
119
  objects: [...match[1].matchAll(/<metadata\s+key="object_id"\s+value="(\d+)"/g)].flatMap(item => objects.get(item[1]) ? [objects.get(item[1])!] : []) });
113
120
  }
114
121
  for (const name of Object.keys(zip.files)) {
@@ -116,7 +123,7 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
116
123
  if (!match) continue;
117
124
  const number = Number(match[1]);
118
125
  if (!valid(number)) continue;
119
- const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true };
126
+ const plate = plates.get(number) ?? { index: number - 1, name: `Plate ${number}`, objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true, build_items: [], parts: [] };
120
127
  const layout = layouts.get(number) ?? { number, objectIds: [] };
121
128
  layouts.set(number, layout);
122
129
  if (match[2] === "gcode") plate.sliced = true;
@@ -134,9 +141,9 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
134
141
  result.plates = [...plates.values()].sort((a, b) => a.index - b.index);
135
142
  // A standard single-build 3MF has no Bambu plate metadata: it is one plate.
136
143
  if (!result.plates.length) {
137
- result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true });
144
+ result.plates.push({ index: 0, name: "Plate 1", objects: [], instances: [], sliced: false, filaments: [], filaments_complete: true, build_items: [], parts: [] });
138
145
  // Without plates every object is on the one plate.
139
- layouts.set(1, { number: 1, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
146
+ layouts.set(1, { number: 1, allItems: true, objectIds: [...settings.matchAll(/<object\b[^>]*\bid="(\d+)"/g)].map(match => match[1]) });
140
147
  }
141
148
  const geometry = has("item") && (has("mesh") || has("component"));
142
149
  if (!geometry) {
@@ -153,6 +160,11 @@ export async function listModelPlates(filePath: string, options: { thumbnails?:
153
160
  for (const plate of result.plates) {
154
161
  plate.filaments = filaments.plates.get(plate.index + 1) ?? [];
155
162
  plate.filaments_complete = !filaments.incomplete.has(plate.index + 1);
163
+ // A sliced-only file has no model to draw from.
164
+ if (geometry) {
165
+ plate.build_items = filaments.buildItems.get(plate.index + 1) ?? [];
166
+ plate.parts = filaments.parts.get(plate.index + 1) ?? [];
167
+ }
156
168
  }
157
169
  result.project_filaments = filaments.project;
158
170
  if (options.thumbnails) for (const plate of result.plates) {
@@ -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
  }
@@ -41,6 +41,7 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
41
41
  blender_mcp_status: "read",
42
42
  counterpart_printer_info: "read",
43
43
  counterpart_self_check: "read",
44
+ counterpart_diagnostics: "read", // this server's own redacted logs; nothing reaches the printer
44
45
  counterpart_print_progress: "read",
45
46
  counterpart_print_record: "read",
46
47
  counterpart_print_assess: "control", // local evidence mutation, never a printer command
@@ -35,6 +35,8 @@ export type PrinterInfo = {
35
35
  progress: boolean; layers: boolean;
36
36
  camera: "bambu-tcp" | "rtsp" | "http-snapshot" | "none";
37
37
  cameraStream?: boolean;
38
+ /** counterpart_diagnostics is here: this server hands over its own redacted diagnostics bundle. */
39
+ diagnostics?: boolean;
38
40
  filaments: "ams" | "single" | "none";
39
41
  pause: boolean; resume: boolean; cancel: boolean; print3mf: boolean; gcode: boolean;
40
42
  /** What slice_stl can apply with this server's slicer (the same field in mcp-3D-printer-server). */
@@ -77,6 +79,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
77
79
  layers: { type: "boolean" },
78
80
  camera: { type: "string", enum: ["bambu-tcp", "rtsp", "http-snapshot", "none"] },
79
81
  cameraStream: { type: "boolean" },
82
+ diagnostics: { type: "boolean", description: "counterpart_diagnostics is available." },
80
83
  filaments: { type: "string", enum: ["ams", "single", "none"] },
81
84
  pause: { type: "boolean" },
82
85
  resume: { type: "boolean" },
package/src/index.ts CHANGED
@@ -89,6 +89,7 @@ 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
91
  import { SELF_CHECK_OUTPUT_SCHEMA, selfCheck } from "./counterpart/self-check.js";
92
+ import { DIAGNOSTICS_INPUT_PROPERTIES, DIAGNOSTICS_OUTPUT_SCHEMA, appVersion, buildDiagnostics, captureServerLog, diagnosticsBudget, jsonText, recordToolError, rememberSecretArguments, serverLogText, settingsSnapshot, toolErrorsText, type DiagnosticsSource } from "./counterpart/diagnostics.js";
92
93
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
93
94
  import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
94
95
  import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
@@ -96,12 +97,16 @@ import { uploadProgressReporter } from "./upload-progress.js";
96
97
  import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
97
98
 
98
99
  dotenv.config();
100
+ // What the server writes to stderr is also kept for counterpart_diagnostics.
101
+ captureServerLog();
99
102
 
100
103
  const CAD_ENABLED = cadEnabled();
101
104
  const DEFAULT_HOST = process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST || "localhost";
102
105
  const DEFAULT_BAMBU_SERIAL = process.env.BAMBU_PRINTER_SERIAL || process.env.BAMBU_SERIAL || "";
103
106
  const DEFAULT_BAMBU_TOKEN =
104
107
  process.env.BAMBU_PRINTER_ACCESS_TOKEN || process.env.BAMBU_TOKEN || "";
108
+ /** Access-code names people try that this server does not read (counterpart_diagnostics names them when set). */
109
+ const UNREAD_ACCESS_CODE_NAMES = ["BAMBU_PRINTER_ACCESS_CODE", "BAMBU_ACCESS_CODE", "BAMBU_ACCESS_TOKEN", "BAMBU_PRINTER_TOKEN"];
105
110
  const DEFAULT_BAMBU_DEV_ID = process.env.BAMBU_DEV_ID || DEFAULT_BAMBU_SERIAL;
106
111
  // os.tmpdir(), not process.cwd() — a packaged Claude Desktop extension is
107
112
  // spawned with a cwd we don't control (and may not be writable), so a
@@ -162,7 +167,7 @@ const SERVER_INFO = {
162
167
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
163
168
  const OUTPUT_SCHEMA_TOOLS = new Set([
164
169
  "cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
165
- "counterpart_printer_info", "counterpart_self_check", "counterpart_print_progress", "counterpart_make_3mf",
170
+ "counterpart_printer_info", "counterpart_self_check", "counterpart_diagnostics", "counterpart_print_progress", "counterpart_make_3mf",
166
171
  "counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
167
172
  "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
168
173
  "camera_stream_start", "camera_frame", "camera_stream_stop",
@@ -2603,7 +2608,7 @@ class BambuPrinterMCPServer {
2603
2608
  },
2604
2609
  {
2605
2610
  name: "list_3mf_plates",
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). 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.",
2611
+ 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.",
2607
2612
  inputSchema: {
2608
2613
  type: "object",
2609
2614
  properties: {
@@ -3574,6 +3579,12 @@ class BambuPrinterMCPServer {
3574
3579
  inputSchema: { type: "object", properties: {} },
3575
3580
  outputSchema: SELF_CHECK_OUTPUT_SCHEMA
3576
3581
  },
3582
+ {
3583
+ name: "counterpart_diagnostics",
3584
+ description: "Counterpart contract (counterpart/1): this server's own diagnostics for a bug report, as files for the client to add to its export: the configured printers (model, serial, connection; firmware is not read), this server's settings, slicer path and version, CAD runtime status, recent tool errors, this run's stderr log (MQTT and connection messages). The Bambu network plug-in logs are not included. Redaction fails closed: configured secrets go in their encoded forms, JSON is redacted by key, and any log line that names a secret is withheld whole; serial numbers, error codes and whether a secret is set stay. Names, contents and notes stay within max_bytes; anything missing is listed in notes. Sends nothing to the printer.",
3585
+ inputSchema: { type: "object", properties: DIAGNOSTICS_INPUT_PROPERTIES, additionalProperties: false },
3586
+ outputSchema: DIAGNOSTICS_OUTPUT_SCHEMA
3587
+ },
3577
3588
  {
3578
3589
  name: "counterpart_discover_printers",
3579
3590
  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.",
@@ -3762,6 +3773,7 @@ class BambuPrinterMCPServer {
3762
3773
  // A designer's settings extracted for this call are removed when it settles.
3763
3774
  this.server.setRequestHandler(CallToolRequestSchema, (request, extra) => withPrintDispatch(() => withExtractedSettingsCleanup(async () => {
3764
3775
  const { name, arguments: args } = request.params;
3776
+ rememberSecretArguments(args);
3765
3777
  const sendNativeCommand = (
3766
3778
  options: Parameters<typeof sendCommandWithBambuNative>[0],
3767
3779
  execution: Parameters<typeof sendCommandWithBambuNative>[1] = {}
@@ -5109,6 +5121,10 @@ class BambuPrinterMCPServer {
5109
5121
  result = await selfCheck(SERVER_INFO);
5110
5122
  break;
5111
5123
 
5124
+ case "counterpart_diagnostics":
5125
+ result = await this.diagnostics(args ?? {});
5126
+ break;
5127
+
5112
5128
  case "counterpart_printer_info":
5113
5129
  result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
5114
5130
  break;
@@ -5243,6 +5259,7 @@ class BambuPrinterMCPServer {
5243
5259
  return { content: [{ type: "text", text }] };
5244
5260
 
5245
5261
  } catch (error) {
5262
+ recordToolError(name, error);
5246
5263
  if (name.startsWith("cad_")) {
5247
5264
  const failure = await this.cad.failure(error, name);
5248
5265
  return {isError: true, content: [{type: "text" as const, text: failure.message}], structuredContent: failure};
@@ -5280,6 +5297,70 @@ class BambuPrinterMCPServer {
5280
5297
  })));
5281
5298
  }
5282
5299
 
5300
+ /** counterpart_diagnostics: this server's own redacted bundle (src/counterpart/diagnostics.ts). Sends nothing to a printer. */
5301
+ private async diagnostics(args: Record<string, unknown>): Promise<ReturnType<typeof buildDiagnostics>> {
5302
+ const unknown = Object.keys(args).filter(key => key !== "printer" && key !== "max_bytes");
5303
+ if (unknown.length) throw new Error(`counterpart_diagnostics takes only printer and max_bytes, not ${unknown.join(", ")}.`);
5304
+ if (args.printer !== undefined && typeof args.printer !== "string") throw new Error("printer must be a string.");
5305
+ const maxBytes = diagnosticsBudget(args.max_bytes);
5306
+ const wanted = (args.printer as string | undefined)?.trim().toLowerCase();
5307
+ const notes: string[] = [];
5308
+ // This server's own sentences, built only from setting names it reads: their secret words name settings.
5309
+ const fixedNotes: string[] = [];
5310
+
5311
+ const model = DEFAULT_BAMBU_MODEL || undefined;
5312
+ let connection: { mode: string; type: string } | { error: string };
5313
+ try { connection = resolveConnection(undefined, model); } catch (error) { connection = { error: error instanceof Error ? error.message : String(error) }; }
5314
+ const configured = DEFAULT_BAMBU_SERIAL || process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST;
5315
+ const printers = configured ? [{
5316
+ id: DEFAULT_BAMBU_SERIAL || DEFAULT_HOST,
5317
+ kind: "bambu",
5318
+ host: DEFAULT_HOST,
5319
+ ...(DEFAULT_BAMBU_SERIAL ? { serial: DEFAULT_BAMBU_SERIAL } : {}),
5320
+ ...(model ? { model } : {}),
5321
+ connection,
5322
+ accessCodeSet: Boolean(DEFAULT_BAMBU_TOKEN),
5323
+ // Firmware comes only from the printer; this tool asks it nothing.
5324
+ firmware: "unknown",
5325
+ }] : [];
5326
+ if (!configured) notes.push("No printer is configured (BAMBU_SERIAL and BAMBU_PRINTER_HOST are unset).");
5327
+ // A look-alike name this server never reads leaves accessCodeSet false; name it so the bundle says why.
5328
+ const ignored = UNREAD_ACCESS_CODE_NAMES.filter(key => process.env[key]);
5329
+ if (ignored.length) fixedNotes.push(`${ignored.join(" and ")} ${ignored.length > 1 ? "are" : "is"} set, but this server reads the access code only from BAMBU_TOKEN or BAMBU_PRINTER_ACCESS_TOKEN (in the environment or its .env).`);
5330
+ const selected = wanted ? printers.filter(p => [p.id, p.host, p.serial].some(v => v?.toLowerCase() === wanted)) : printers;
5331
+ if (wanted && !selected.length) notes.push(`No configured printer is ${args.printer}; printers.json lists none.`);
5332
+ if (printers.length) notes.push("Printer firmware is not included: only the printer reports it, and this tool sends it nothing.");
5333
+
5334
+ let slicer: Record<string, unknown>;
5335
+ try {
5336
+ const { fields: _fields, ...setup } = slicerSetupNow();
5337
+ const version = appVersion(setup.path);
5338
+ slicer = { ...setup, ...(version ? { version } : {}) };
5339
+ if (setup.type === "orca-slicer-api") { if (!setup.found) notes.push("The remote OrcaSlicer API slicer has no SLICER_API_URL."); }
5340
+ else if (!setup.found) notes.push(`The ${setup.type} slicer is not installed where this server looks (${setup.path ?? "no path"}).`);
5341
+ else if (!version && setup.path) notes.push("Slicer version is unknown: its install doesn't name it, and this tool doesn't run the slicer.");
5342
+ } catch (error) { slicer = { error: error instanceof Error ? error.message : String(error) }; }
5343
+
5344
+ let cad: unknown;
5345
+ try { cad = await this.cad.status(); } catch (error) { cad = { error: error instanceof Error ? error.message : String(error) }; }
5346
+
5347
+ const settings = settingsSnapshot(/^(?:BAMBU|PRINTER|SLICER|ORCA|CAD|BLENDER|FUSION|BED_TYPE|NOZZLE|MCP|PJARCZAK|FULU|TEMP_DIR)/);
5348
+
5349
+ const sources: DiagnosticsSource[] = [
5350
+ { name: "server.json", text: jsonText({ package: SERVER_INFO.name, version: SERVER_INFO.version, node: process.version, platform: process.platform, arch: process.arch, uptimeSec: Math.round(process.uptime()) }) },
5351
+ { name: "printers.json", text: jsonText({ printers: selected }) },
5352
+ { name: "settings.json", text: jsonText(settings) },
5353
+ { name: "slicer.json", text: jsonText(slicer) },
5354
+ { name: "cad.json", text: jsonText(cad) },
5355
+ { name: "tool-errors.log", text: toolErrorsText() || "No tool has failed since this server started.\n" },
5356
+ { name: "server-stderr.log", text: serverLogText() || "Nothing written to stderr since this server started.\n" },
5357
+ ];
5358
+ // The Bambu network plug-in and native helper logs are written by other programs, in forms this server does not
5359
+ // control, and can carry secrets it never held (a cloud token, another printer's code): they stay out.
5360
+ fixedNotes.push("The Bambu network plug-in (fulu) and native helper logs are not included: other programs write them, and they can hold secrets this server cannot recognise.");
5361
+ return buildDiagnostics({ package: SERVER_INFO.name, version: SERVER_INFO.version, sources, notes, fixedNotes, maxBytes, secrets: DEFAULT_BAMBU_TOKEN ? [DEFAULT_BAMBU_TOKEN] : [] });
5362
+ }
5363
+
5283
5364
  async startStdio() {
5284
5365
  const transport = new StdioServerTransport();
5285
5366
  await this.server.connect(transport);
@@ -68,6 +68,7 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
68
68
  get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
69
69
  counterpart_printer_info: READ_LOCAL, // configuration and capabilities; sends nothing to the printer
70
70
  counterpart_self_check: READ_LOCAL, // loads this install's own modules; sends nothing to the printer
71
+ counterpart_diagnostics: READ_LOCAL, // reads this server's own logs and settings, redacted; sends nothing to the printer
71
72
  counterpart_setup_fields: READ_LOCAL, // the settings this server reads; no configured values
72
73
 
73
74
  // Local outputs in the server's temporary directory