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.
- package/README.md +6 -3
- package/dist/3mf_parser.js +3 -2
- package/dist/cad/contracts.d.ts +10 -0
- package/dist/cad/contracts.js +41 -1
- package/dist/cad-engine.d.ts +5 -0
- package/dist/cad-engine.js +74 -3
- package/dist/counterpart/diagnostics.d.ts +163 -0
- package/dist/counterpart/diagnostics.js +816 -0
- package/dist/counterpart/flight-tools.d.ts +2 -2
- package/dist/counterpart/info.js +1 -0
- package/dist/counterpart/make-3mf.d.ts +10 -0
- package/dist/counterpart/make-3mf.js +472 -65
- package/dist/counterpart/model-plates.d.ts +8 -1
- package/dist/counterpart/model-plates.js +9 -4
- package/dist/counterpart/plate-filaments.d.ts +19 -0
- package/dist/counterpart/plate-filaments.js +72 -10
- package/dist/counterpart/remote.js +1 -0
- package/dist/counterpart/schemas.d.ts +8 -2
- package/dist/counterpart/schemas.js +1 -0
- package/dist/index.js +100 -2
- package/dist/tool-annotations.js +1 -0
- package/package.json +2 -2
- package/src/3mf_parser.ts +3 -2
- package/src/cad/contracts.ts +46 -1
- package/src/cad/examples/desk_clamp_hook.py +32 -0
- package/src/cad/examples/desk_edge_cable_holder.py +24 -0
- package/src/cad/examples/phone_stand.py +26 -0
- package/src/cad/geometry.py +52 -2
- package/src/cad/project3mf.py +426 -0
- package/src/cad/purpose.py +492 -0
- package/src/cad/worker.py +17 -2
- package/src/cad-engine.ts +73 -3
- package/src/counterpart/diagnostics.ts +775 -0
- package/src/counterpart/info.ts +1 -0
- package/src/counterpart/make-3mf.ts +446 -61
- package/src/counterpart/model-plates.ts +17 -5
- package/src/counterpart/plate-filaments.ts +75 -7
- package/src/counterpart/remote.ts +1 -0
- package/src/counterpart/schemas.ts +3 -0
- package/src/index.ts +83 -2
- 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
|
-
|
|
13
|
-
|
|
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[^>]
|
|
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
|
|
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
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
for (const
|
|
225
|
-
|
|
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
|
}
|
|
@@ -18,6 +18,7 @@ export const REMOTE_SCOPES = {
|
|
|
18
18
|
blender_mcp_status: "read",
|
|
19
19
|
counterpart_printer_info: "read",
|
|
20
20
|
counterpart_self_check: "read",
|
|
21
|
+
counterpart_diagnostics: "read", // this server's own redacted logs; nothing reaches the printer
|
|
21
22
|
counterpart_print_progress: "read",
|
|
22
23
|
counterpart_print_record: "read",
|
|
23
24
|
counterpart_print_assess: "control", // local evidence mutation, never a printer command
|
|
@@ -76,6 +76,8 @@ export type PrinterInfo = {
|
|
|
76
76
|
layers: boolean;
|
|
77
77
|
camera: "bambu-tcp" | "rtsp" | "http-snapshot" | "none";
|
|
78
78
|
cameraStream?: boolean;
|
|
79
|
+
/** counterpart_diagnostics is here: this server hands over its own redacted diagnostics bundle. */
|
|
80
|
+
diagnostics?: boolean;
|
|
79
81
|
filaments: "ams" | "single" | "none";
|
|
80
82
|
pause: boolean;
|
|
81
83
|
resume: boolean;
|
|
@@ -175,6 +177,10 @@ export declare const PRINTER_INFO_OUTPUT_SCHEMA: {
|
|
|
175
177
|
cameraStream: {
|
|
176
178
|
type: string;
|
|
177
179
|
};
|
|
180
|
+
diagnostics: {
|
|
181
|
+
type: string;
|
|
182
|
+
description: string;
|
|
183
|
+
};
|
|
178
184
|
filaments: {
|
|
179
185
|
type: string;
|
|
180
186
|
enum: string[];
|
|
@@ -258,7 +264,7 @@ export declare const PRINT_PROGRESS_OUTPUT_SCHEMA: {
|
|
|
258
264
|
};
|
|
259
265
|
state: {
|
|
260
266
|
type: string;
|
|
261
|
-
enum: ("failed" | "cancelled" | "idle" | "
|
|
267
|
+
enum: ("failed" | "cancelled" | "idle" | "preparing" | "printing" | "paused" | "finished" | "offline" | "busy")[];
|
|
262
268
|
};
|
|
263
269
|
job: {
|
|
264
270
|
type: string;
|
|
@@ -353,7 +359,7 @@ export declare const PRINT_PROGRESS_OUTPUT_SCHEMA: {
|
|
|
353
359
|
};
|
|
354
360
|
severity: {
|
|
355
361
|
type: string;
|
|
356
|
-
enum: ("
|
|
362
|
+
enum: ("fatal" | "error" | "info" | "warning")[];
|
|
357
363
|
};
|
|
358
364
|
message: {
|
|
359
365
|
type: string;
|
|
@@ -43,6 +43,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
|
|
|
43
43
|
layers: { type: "boolean" },
|
|
44
44
|
camera: { type: "string", enum: ["bambu-tcp", "rtsp", "http-snapshot", "none"] },
|
|
45
45
|
cameraStream: { type: "boolean" },
|
|
46
|
+
diagnostics: { type: "boolean", description: "counterpart_diagnostics is available." },
|
|
46
47
|
filaments: { type: "string", enum: ["ams", "single", "none"] },
|
|
47
48
|
pause: { type: "boolean" },
|
|
48
49
|
resume: { type: "boolean" },
|
package/dist/index.js
CHANGED
|
@@ -58,16 +58,21 @@ 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
60
|
import { SELF_CHECK_OUTPUT_SCHEMA, selfCheck } from "./counterpart/self-check.js";
|
|
61
|
+
import { DIAGNOSTICS_INPUT_PROPERTIES, DIAGNOSTICS_OUTPUT_SCHEMA, appVersion, buildDiagnostics, captureServerLog, diagnosticsBudget, jsonText, recordToolError, rememberSecretArguments, serverLogText, settingsSnapshot, toolErrorsText } from "./counterpart/diagnostics.js";
|
|
61
62
|
import { parseProcessOverrides } from "./slicer/process-overrides.js";
|
|
62
63
|
import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
|
|
63
64
|
import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
|
|
64
65
|
import { uploadProgressReporter } from "./upload-progress.js";
|
|
65
66
|
import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
|
|
66
67
|
dotenv.config();
|
|
68
|
+
// What the server writes to stderr is also kept for counterpart_diagnostics.
|
|
69
|
+
captureServerLog();
|
|
67
70
|
const CAD_ENABLED = cadEnabled();
|
|
68
71
|
const DEFAULT_HOST = process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST || "localhost";
|
|
69
72
|
const DEFAULT_BAMBU_SERIAL = process.env.BAMBU_PRINTER_SERIAL || process.env.BAMBU_SERIAL || "";
|
|
70
73
|
const DEFAULT_BAMBU_TOKEN = process.env.BAMBU_PRINTER_ACCESS_TOKEN || process.env.BAMBU_TOKEN || "";
|
|
74
|
+
/** Access-code names people try that this server does not read (counterpart_diagnostics names them when set). */
|
|
75
|
+
const UNREAD_ACCESS_CODE_NAMES = ["BAMBU_PRINTER_ACCESS_CODE", "BAMBU_ACCESS_CODE", "BAMBU_ACCESS_TOKEN", "BAMBU_PRINTER_TOKEN"];
|
|
71
76
|
const DEFAULT_BAMBU_DEV_ID = process.env.BAMBU_DEV_ID || DEFAULT_BAMBU_SERIAL;
|
|
72
77
|
// os.tmpdir(), not process.cwd() — a packaged Claude Desktop extension is
|
|
73
78
|
// spawned with a cwd we don't control (and may not be writable), so a
|
|
@@ -126,7 +131,7 @@ const SERVER_INFO = {
|
|
|
126
131
|
/** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
|
|
127
132
|
const OUTPUT_SCHEMA_TOOLS = new Set([
|
|
128
133
|
"cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
|
|
129
|
-
"counterpart_printer_info", "counterpart_self_check", "counterpart_print_progress", "counterpart_make_3mf",
|
|
134
|
+
"counterpart_printer_info", "counterpart_self_check", "counterpart_diagnostics", "counterpart_print_progress", "counterpart_make_3mf",
|
|
130
135
|
"counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
|
|
131
136
|
"fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
|
|
132
137
|
"camera_stream_start", "camera_frame", "camera_stream_stop",
|
|
@@ -2094,7 +2099,7 @@ class BambuPrinterMCPServer {
|
|
|
2094
2099
|
},
|
|
2095
2100
|
{
|
|
2096
2101
|
name: "list_3mf_plates",
|
|
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). 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.",
|
|
2102
|
+
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.",
|
|
2098
2103
|
inputSchema: {
|
|
2099
2104
|
type: "object",
|
|
2100
2105
|
properties: {
|
|
@@ -3065,6 +3070,12 @@ class BambuPrinterMCPServer {
|
|
|
3065
3070
|
inputSchema: { type: "object", properties: {} },
|
|
3066
3071
|
outputSchema: SELF_CHECK_OUTPUT_SCHEMA
|
|
3067
3072
|
},
|
|
3073
|
+
{
|
|
3074
|
+
name: "counterpart_diagnostics",
|
|
3075
|
+
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.",
|
|
3076
|
+
inputSchema: { type: "object", properties: DIAGNOSTICS_INPUT_PROPERTIES, additionalProperties: false },
|
|
3077
|
+
outputSchema: DIAGNOSTICS_OUTPUT_SCHEMA
|
|
3078
|
+
},
|
|
3068
3079
|
{
|
|
3069
3080
|
name: "counterpart_discover_printers",
|
|
3070
3081
|
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.",
|
|
@@ -3252,6 +3263,7 @@ class BambuPrinterMCPServer {
|
|
|
3252
3263
|
// A designer's settings extracted for this call are removed when it settles.
|
|
3253
3264
|
this.server.setRequestHandler(CallToolRequestSchema, (request, extra) => withPrintDispatch(() => withExtractedSettingsCleanup(async () => {
|
|
3254
3265
|
const { name, arguments: args } = request.params;
|
|
3266
|
+
rememberSecretArguments(args);
|
|
3255
3267
|
const sendNativeCommand = (options, execution = {}) => sendCommandWithBambuNative(options, { signal: extra.signal, ...execution });
|
|
3256
3268
|
const progressToken = extra._meta?.progressToken;
|
|
3257
3269
|
let progressNotifications = Promise.resolve();
|
|
@@ -4385,6 +4397,9 @@ class BambuPrinterMCPServer {
|
|
|
4385
4397
|
case "counterpart_self_check":
|
|
4386
4398
|
result = await selfCheck(SERVER_INFO);
|
|
4387
4399
|
break;
|
|
4400
|
+
case "counterpart_diagnostics":
|
|
4401
|
+
result = await this.diagnostics(args ?? {});
|
|
4402
|
+
break;
|
|
4388
4403
|
case "counterpart_printer_info":
|
|
4389
4404
|
result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
|
|
4390
4405
|
break;
|
|
@@ -4511,6 +4526,7 @@ class BambuPrinterMCPServer {
|
|
|
4511
4526
|
return { content: [{ type: "text", text }] };
|
|
4512
4527
|
}
|
|
4513
4528
|
catch (error) {
|
|
4529
|
+
recordToolError(name, error);
|
|
4514
4530
|
if (name.startsWith("cad_")) {
|
|
4515
4531
|
const failure = await this.cad.failure(error, name);
|
|
4516
4532
|
return { isError: true, content: [{ type: "text", text: failure.message }], structuredContent: failure };
|
|
@@ -4546,6 +4562,88 @@ class BambuPrinterMCPServer {
|
|
|
4546
4562
|
}
|
|
4547
4563
|
})));
|
|
4548
4564
|
}
|
|
4565
|
+
/** counterpart_diagnostics: this server's own redacted bundle (src/counterpart/diagnostics.ts). Sends nothing to a printer. */
|
|
4566
|
+
async diagnostics(args) {
|
|
4567
|
+
const unknown = Object.keys(args).filter(key => key !== "printer" && key !== "max_bytes");
|
|
4568
|
+
if (unknown.length)
|
|
4569
|
+
throw new Error(`counterpart_diagnostics takes only printer and max_bytes, not ${unknown.join(", ")}.`);
|
|
4570
|
+
if (args.printer !== undefined && typeof args.printer !== "string")
|
|
4571
|
+
throw new Error("printer must be a string.");
|
|
4572
|
+
const maxBytes = diagnosticsBudget(args.max_bytes);
|
|
4573
|
+
const wanted = args.printer?.trim().toLowerCase();
|
|
4574
|
+
const notes = [];
|
|
4575
|
+
// This server's own sentences, built only from setting names it reads: their secret words name settings.
|
|
4576
|
+
const fixedNotes = [];
|
|
4577
|
+
const model = DEFAULT_BAMBU_MODEL || undefined;
|
|
4578
|
+
let connection;
|
|
4579
|
+
try {
|
|
4580
|
+
connection = resolveConnection(undefined, model);
|
|
4581
|
+
}
|
|
4582
|
+
catch (error) {
|
|
4583
|
+
connection = { error: error instanceof Error ? error.message : String(error) };
|
|
4584
|
+
}
|
|
4585
|
+
const configured = DEFAULT_BAMBU_SERIAL || process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST;
|
|
4586
|
+
const printers = configured ? [{
|
|
4587
|
+
id: DEFAULT_BAMBU_SERIAL || DEFAULT_HOST,
|
|
4588
|
+
kind: "bambu",
|
|
4589
|
+
host: DEFAULT_HOST,
|
|
4590
|
+
...(DEFAULT_BAMBU_SERIAL ? { serial: DEFAULT_BAMBU_SERIAL } : {}),
|
|
4591
|
+
...(model ? { model } : {}),
|
|
4592
|
+
connection,
|
|
4593
|
+
accessCodeSet: Boolean(DEFAULT_BAMBU_TOKEN),
|
|
4594
|
+
// Firmware comes only from the printer; this tool asks it nothing.
|
|
4595
|
+
firmware: "unknown",
|
|
4596
|
+
}] : [];
|
|
4597
|
+
if (!configured)
|
|
4598
|
+
notes.push("No printer is configured (BAMBU_SERIAL and BAMBU_PRINTER_HOST are unset).");
|
|
4599
|
+
// A look-alike name this server never reads leaves accessCodeSet false; name it so the bundle says why.
|
|
4600
|
+
const ignored = UNREAD_ACCESS_CODE_NAMES.filter(key => process.env[key]);
|
|
4601
|
+
if (ignored.length)
|
|
4602
|
+
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).`);
|
|
4603
|
+
const selected = wanted ? printers.filter(p => [p.id, p.host, p.serial].some(v => v?.toLowerCase() === wanted)) : printers;
|
|
4604
|
+
if (wanted && !selected.length)
|
|
4605
|
+
notes.push(`No configured printer is ${args.printer}; printers.json lists none.`);
|
|
4606
|
+
if (printers.length)
|
|
4607
|
+
notes.push("Printer firmware is not included: only the printer reports it, and this tool sends it nothing.");
|
|
4608
|
+
let slicer;
|
|
4609
|
+
try {
|
|
4610
|
+
const { fields: _fields, ...setup } = slicerSetupNow();
|
|
4611
|
+
const version = appVersion(setup.path);
|
|
4612
|
+
slicer = { ...setup, ...(version ? { version } : {}) };
|
|
4613
|
+
if (setup.type === "orca-slicer-api") {
|
|
4614
|
+
if (!setup.found)
|
|
4615
|
+
notes.push("The remote OrcaSlicer API slicer has no SLICER_API_URL.");
|
|
4616
|
+
}
|
|
4617
|
+
else if (!setup.found)
|
|
4618
|
+
notes.push(`The ${setup.type} slicer is not installed where this server looks (${setup.path ?? "no path"}).`);
|
|
4619
|
+
else if (!version && setup.path)
|
|
4620
|
+
notes.push("Slicer version is unknown: its install doesn't name it, and this tool doesn't run the slicer.");
|
|
4621
|
+
}
|
|
4622
|
+
catch (error) {
|
|
4623
|
+
slicer = { error: error instanceof Error ? error.message : String(error) };
|
|
4624
|
+
}
|
|
4625
|
+
let cad;
|
|
4626
|
+
try {
|
|
4627
|
+
cad = await this.cad.status();
|
|
4628
|
+
}
|
|
4629
|
+
catch (error) {
|
|
4630
|
+
cad = { error: error instanceof Error ? error.message : String(error) };
|
|
4631
|
+
}
|
|
4632
|
+
const settings = settingsSnapshot(/^(?:BAMBU|PRINTER|SLICER|ORCA|CAD|BLENDER|FUSION|BED_TYPE|NOZZLE|MCP|PJARCZAK|FULU|TEMP_DIR)/);
|
|
4633
|
+
const sources = [
|
|
4634
|
+
{ 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()) }) },
|
|
4635
|
+
{ name: "printers.json", text: jsonText({ printers: selected }) },
|
|
4636
|
+
{ name: "settings.json", text: jsonText(settings) },
|
|
4637
|
+
{ name: "slicer.json", text: jsonText(slicer) },
|
|
4638
|
+
{ name: "cad.json", text: jsonText(cad) },
|
|
4639
|
+
{ name: "tool-errors.log", text: toolErrorsText() || "No tool has failed since this server started.\n" },
|
|
4640
|
+
{ name: "server-stderr.log", text: serverLogText() || "Nothing written to stderr since this server started.\n" },
|
|
4641
|
+
];
|
|
4642
|
+
// The Bambu network plug-in and native helper logs are written by other programs, in forms this server does not
|
|
4643
|
+
// control, and can carry secrets it never held (a cloud token, another printer's code): they stay out.
|
|
4644
|
+
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.");
|
|
4645
|
+
return buildDiagnostics({ package: SERVER_INFO.name, version: SERVER_INFO.version, sources, notes, fixedNotes, maxBytes, secrets: DEFAULT_BAMBU_TOKEN ? [DEFAULT_BAMBU_TOKEN] : [] });
|
|
4646
|
+
}
|
|
4549
4647
|
async startStdio() {
|
|
4550
4648
|
const transport = new StdioServerTransport();
|
|
4551
4649
|
await this.server.connect(transport);
|
package/dist/tool-annotations.js
CHANGED
|
@@ -45,6 +45,7 @@ export const TOOL_ANNOTATIONS = {
|
|
|
45
45
|
get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
|
|
46
46
|
counterpart_printer_info: READ_LOCAL, // configuration and capabilities; sends nothing to the printer
|
|
47
47
|
counterpart_self_check: READ_LOCAL, // loads this install's own modules; sends nothing to the printer
|
|
48
|
+
counterpart_diagnostics: READ_LOCAL, // reads this server's own logs and settings, redacted; sends nothing to the printer
|
|
48
49
|
counterpart_setup_fields: READ_LOCAL, // the settings this server reads; no configured values
|
|
49
50
|
// Local outputs in the server's temporary directory
|
|
50
51
|
extend_stl_base: LOCAL_OUTPUT,
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bambu-printer-mcp",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.95",
|
|
4
4
|
"description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
|
|
5
5
|
"counterpart": {
|
|
6
6
|
"contract": "counterpart/1",
|
|
7
|
-
"notes": "
|
|
7
|
+
"notes": "Checks what a design is for on the design as used, and returns this server’s own redacted diagnostics for bug reports.",
|
|
8
8
|
"autoUpdate": true
|
|
9
9
|
},
|
|
10
10
|
"main": "dist/index.js",
|
package/src/3mf_parser.ts
CHANGED
|
@@ -5,6 +5,7 @@ import * as fs from 'fs/promises';
|
|
|
5
5
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
6
6
|
import { createHash, randomUUID } from 'node:crypto';
|
|
7
7
|
import * as path from 'node:path';
|
|
8
|
+
import { readSafe3mfArchive } from './safety/archive.js';
|
|
8
9
|
|
|
9
10
|
// Parses Bambu Studio's JSON config data
|
|
10
11
|
function parseBambuJSONConfig(jsonData: any): Partial<BambuSlicerConfig> {
|
|
@@ -511,8 +512,8 @@ export async function analyze3MFPlateObjects(
|
|
|
511
512
|
filePath: string,
|
|
512
513
|
plateIndex: number = 0
|
|
513
514
|
): Promise<ThreeMFPlateObjects> {
|
|
514
|
-
|
|
515
|
-
const zip = await
|
|
515
|
+
// Bounded, with colliding or inconsistent entry names refused, as the other 3MF reads here.
|
|
516
|
+
const { zip } = await readSafe3mfArchive(filePath);
|
|
516
517
|
const plateNumber = plateIndex + 1;
|
|
517
518
|
const sliceInfo = zip.file('Metadata/slice_info.config');
|
|
518
519
|
if (!sliceInfo) {
|
package/src/cad/contracts.ts
CHANGED
|
@@ -113,7 +113,7 @@ export const CAD_TOOLS = [
|
|
|
113
113
|
{
|
|
114
114
|
name: "cad_run",
|
|
115
115
|
description:
|
|
116
|
-
"Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six orthographic renders, a perspective view and a contact sheet (with next: read the perspective view before the next change), the closest approach between every pair of solids (bodies), problems, what was checked and not checked,
|
|
116
|
+
"Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six orthographic renders, a perspective view and a contact sheet (with next: read the perspective view before the next change), the closest approach between every pair of solids (bodies), problems, what was checked and not checked, printed: whatever the script wrote with print(), capped at 4000 characters, so a design can report a number it computed, and, in solid mode, purpose and ready: the script's PURPOSE compiled into requirements and evaluated on its use() assembly (held objects, mounts, loads computed from the geometry, facing the user). valid means only that the exported geometry is sound; final: true is recorded only when the design is ready (final_refused says why not).",
|
|
117
117
|
inputSchema: {
|
|
118
118
|
type: "object" as const,
|
|
119
119
|
properties: {
|
|
@@ -164,6 +164,13 @@ export const CAD_TOOLS = [
|
|
|
164
164
|
description:
|
|
165
165
|
"Plain file stem for STL, STEP, Python and parameter artifacts.",
|
|
166
166
|
},
|
|
167
|
+
role: {
|
|
168
|
+
type: "string",
|
|
169
|
+
enum: ["design", "check"],
|
|
170
|
+
default: "design",
|
|
171
|
+
description:
|
|
172
|
+
'What this run is: "design" (the default) for the design itself, or "check" for a fit check part, a reference export or any other run that must never become the model. A check run is never selected as final, evaluates no PURPOSE, and its receipt says role: "check".',
|
|
173
|
+
},
|
|
167
174
|
final: {
|
|
168
175
|
type: "boolean",
|
|
169
176
|
default: false,
|
|
@@ -231,6 +238,42 @@ export const CAD_TOOLS = [
|
|
|
231
238
|
description:
|
|
232
239
|
"The script's own print() output from this run, capped at 4000 characters (build.log keeps the rest). The script's words, not a measurement by the engine.",
|
|
233
240
|
},
|
|
241
|
+
ready: {
|
|
242
|
+
type: "boolean",
|
|
243
|
+
description:
|
|
244
|
+
"Solid mode: the design's PURPOSE is declared and every requirement it compiles to passed on use(). final: true is recorded only when ready. Absent for mesh mode and 3MF projects.",
|
|
245
|
+
},
|
|
246
|
+
purpose: {
|
|
247
|
+
type: "object",
|
|
248
|
+
description:
|
|
249
|
+
"Solid mode: what PURPOSE says the part is for (for, modelled_on), the product classes its words put it in, each requirement compiled from it with status pass, fail or not_modelled and what it says (held objects sit on the part, each mount touches its world surface, the exposed face of a held screen turns to the user's eye, tape stress and resting stability under the computed loads), the loads at the mounts (gravity, jolts, a hand's press), and blocked: what keeps it from ready.",
|
|
250
|
+
},
|
|
251
|
+
final_requested: { type: "boolean" },
|
|
252
|
+
role: {
|
|
253
|
+
type: "string",
|
|
254
|
+
enum: ["design", "check"],
|
|
255
|
+
description: 'The run\'s role as cad_run was given it: "design", or "check" for a check part or reference export that is never the model. Every receipt carries it.',
|
|
256
|
+
},
|
|
257
|
+
draft_reasons: {
|
|
258
|
+
type: "array",
|
|
259
|
+
items: { type: "string" },
|
|
260
|
+
description:
|
|
261
|
+
"On every valid run that is not final: why not, in plain sentences (the designer did not mark it final; it is not ready, then what blocks it; or it is a check part, not the design). A client that keeps such a run as a draft shows these.",
|
|
262
|
+
},
|
|
263
|
+
final_refused: {
|
|
264
|
+
type: "array",
|
|
265
|
+
items: { type: "string" },
|
|
266
|
+
description: "Why final: true was not recorded, each as the step that fixes it (for example: model the dash as world:dash in use() so the tape mount can be checked). next quotes the first ones; the run is not the model until a run with final: true is ready.",
|
|
267
|
+
},
|
|
268
|
+
three_mf: {
|
|
269
|
+
type: "string",
|
|
270
|
+
description: "When build() returned project_3mf(): the written 3MF project, ready for slice_stl.",
|
|
271
|
+
},
|
|
272
|
+
three_mf_project: {
|
|
273
|
+
type: "object",
|
|
274
|
+
description:
|
|
275
|
+
"When build() returned project_3mf(): base (the edited input alias, or null for a new project), changes, and the written file read back as list_3mf_plates reads it (plates with build_items, parts and filaments; project_filaments).",
|
|
276
|
+
},
|
|
234
277
|
seconds: { type: "number" },
|
|
235
278
|
},
|
|
236
279
|
[
|
|
@@ -375,6 +418,7 @@ export const CAD_DESIGN_PROMPT = {
|
|
|
375
418
|
"MCP-owned rules for headless build123d designs and one-call parameter revisions.",
|
|
376
419
|
text: `Use code-CAD for dimensioned functional designs and parameter edits. Build in millimetres with build123d 0.13.0; the MCP owns the Python environment, execution, export, validation and rendering. Check cad_status and use cad_setup with install: true when needed. No Blender, Fusion, network or printer access is available to your script.
|
|
377
420
|
A new design starts from the product, in this order. First, name two or three products a person would buy for this request (search when you are not sure what is sold) and say which one the design follows. Second, choose from the cookbook by purpose: the list below says what each example is for (cad_examples with no name returns it with each one's pattern and product). Read the example whose use is nearest the request, with cad_examples and its name, before deciding anything else, and adapt its form and pattern, never its sizes. Third, and only then, choose the mechanism (a clamp, screw, spring, hinge or snap) and read a second example for it if you need one. A mechanism chosen before the product gives a bracket with the mechanism bolted on.
|
|
421
|
+
Then state the purpose as data, before any geometry: a literal PURPOSE = {...} beside P (cad_run reads it from the source; parameters cannot change it). "for": what it is for in the person's words (who uses it, where, doing what); "modelled_on": the bought product; "holds": [{"body": name, "mass_g": grams}] for what it carries; "mounts": [{"body": name, "by": "tape", "rests", "screw", "clamp", "hook" or "other"}] for each surface that takes the load; "user": [x, y, z], the eye of the person who uses it, in mm in the use() frame, when it shows them something; optional "jolt_g", "press_n", "reach_mm", "material" and "faces": {"body": name, "within_deg": 25}. Its words add requirements whatever you list: a holder, hook, stand, dock, mount, rack, bracket, cradle or organizer must name what it holds and what it mounts to; anything in a vehicle takes jolts of at least 1.5 g in every direction; a phone, tablet or screen it holds must face the user's eye within 25 degrees. Then define use() beside build(): return Compound(children=[...]) of the part as it is used, Z up and gravity along -Z, with each held object at its real size and pose labelled "held:<body>" and each surface it meets as a solid slab where it really is (a dash face at its real angle, a desk's underside, a wall) labelled "world:<body>", all touching the part where they really touch. cad_run computes the loads at each mount from that geometry (gravity on the part and what it holds, the jolts, a hand pressing the held object), checks tape against 3M VHB's published stresses and that a resting part neither tips, lifts nor slides, checks that a held screen faces the user, draws renders.use (from the user's eye when given) and reports it all in purpose. final: true is recorded only when ready is true; until then the result lists final_refused. A run that is not the design itself (a part exported only for cad_check_fit, a reference, a diagnostic) is a check: pass role: "check" to every cad_run that is not the design itself, so it is never mistaken for the model (it is never final and evaluates no PURPOSE). Every valid run that is not final carries draft_reasons, saying why. When a requirement fails, change the design the way the bought products solve it (a joint that aims it, a broader pad, a wider or heavier base), never the purpose.
|
|
378
422
|
The cookbook, by what each example is for:
|
|
379
423
|
${cadExampleLines()}
|
|
380
424
|
Form first: build the product's shape, not a profile pushed up. Before any geometry, write the concept as the script's opening docstring, the way every cookbook example does: what it is, then "Modelled on:" the bought product you named, its mechanism, the load path, the print orientation and why. A script whose header names no product was designed from the mechanism. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
|
|
@@ -385,6 +429,7 @@ Captured mesh preparation: load_scan(name, source_units="m" or "mm", up_axis="x"
|
|
|
385
429
|
Fit reference workflow: return load_scan("scan", source_units="m", up_axis="y") from build() in mode: "mesh" to export an unchanged, prepared reference STL for cad_check_fit. Declare every linked OBJ/MTL/texture asset. If you crop, simplify, fill, or otherwise alter this reference, report exactly what you excluded/changed and that the fit check proves only that reduced reference in the stated pose. A fit check against a scan is information; it must never resize or override an interface specified by measured dimensions. Keep those measured interfaces and report the discrepancy.
|
|
386
430
|
Result selection and edits: set final: true only on the result you select. cad-result.json in each immediate run folder is protected from script writes and retains final, completed_at, lineage_id (source hash), full checks and artifact paths; clients can discover the latest completed final record after restart without rebuilding. Final is a selection marker, not a replacement for valid/checks. Queued calls may expire with cad-queue-timeout before dispatch; do not automatically replay. Unchanged declared files reuse a read-only content-addressed bundle under output_dir/.cad-inputs, preserving filenames and restricting reads to that bundle. Keep this shared cache with the saved runs.
|
|
387
431
|
Mesh cleanup workflow: return a trimesh.Trimesh in mode: "mesh". Load the prepared mesh, fit needed geometry with NumPy/SciPy, rebuild regular sections/features with build123d or manifold3d CrossSection/extrusion/revolve, and combine meshes with manifold3d booleans. scikit-image supplies marching cubes for voxel/SDF work; Shapely supplies planar operations; Pillow supplies image/texture reads. Keep numeric choices in P and regenerate from declared inputs. Validate closure, winding, manifold status, dimensions and all six views using cad_run. What to regularise, infer, preserve or label comes from the caller's cleanup rules, not this engine prompt.
|
|
432
|
+
Multi-colour 3MF projects: build() may return project_3mf() instead of a shape. A new project: p = project_3mf(); p.add_part(shape, name="Lid", filament=2, object="Box", plate=1) for each part (parts that share object= are one object, printed as one piece; plates from 1), in solid mode with build123d shapes (the checks fuse each object's parts) or mode: "mesh" with trimesh parts. Editing a designer's 3MF: declare it as an input and p = project_3mf("kit") in mode: "mesh"; p.objects lists its objects (name, id, plate; p.object(id or unique name)) and their parts (name, id, filament, painted, mesh: a trimesh in the object's frame); p.add_part(shape, name=..., filament=..., object="Body") adds a part in that object's frame, p.replace_part(part, mesh) swaps a part's mesh (its painting goes with the old mesh) and p.set_part(part, name=..., filament=...) renames or recolours one; everything else in the file (print settings, painting, plates, other parts) is kept. cad_run writes <name>.3mf beside the STL and returns three_mf and three_mf_project (each plate's parts and filaments, read back from the file); slice it with slice_stl, never by rebuilding it from the STL.
|
|
388
433
|
Captured scan touch-up: t = scan_touchup(load_scan("scan", source_units="m", up_axis="y", ground=False), colour="colour", normal="normal", edge_mm=0.4) takes a textured capture (declare its OBJ, MTL and colour and normal map PNGs as inputs; pass the map aliases). It removes loose pieces and spikes, closes holes and refines to edge_mm without shrinking the body. t.regions() prints the colour regions (id, colour, area, size, flatness; 0 is the body) to build.log and saves regions.png in the run folder: read both, then name regions by id in the same scan and edge_mm. t.flatten(ids, shape="plane" or "curved"), t.bead(id, diameter_mm, proud_mm), t.cord(id, diameter_mm, proud_mm) (a cord follows its region's own curve) and t.seat(height_mm) record steps; return t.mesh(relief_gain=1.0), which adds the normal map's measured relief, applies the steps with manifold3d and prints its changes. Keep relief_gain at 1: a larger gain amplifies the map's noise, not stitches. When the caller's rules call for a textile's relief the scan missed (fabric, knit, crochet the photos show raised), t.texture_relief(height_mm, regions=None) raises its stitch pattern from the colour texture on the textile only (never flattened, beaded or corded regions); about 0.6 to 1.0 mm peak to peak prints visibly. It is off unless called: never for hard objects, printed graphics or labels.
|
|
389
434
|
The result includes paths, millimetre bounds/size, mesh and STEP volumes, solid count, watertight/manifold/winding/STEP checks, bodies (closest approach between solids, contact with the print plate at Z = 0, labelled bodies that are not one solid), problems, checked and not_checked, six orthographic renders (front, back, left, right, top, bottom), a perspective view from the front right and above, and a contact sheet with the perspective view large beside the six. Fix every entry in problems before selecting a result; an empty problems list proves nothing listed in not_checked. After every cad_run, Read its perspective view (renders.perspective, as the result's next says) before the next cad_run or any other change: a run you have not looked at tells you nothing about the form. Judge the form from the perspective view first: would a person recognise the product and want it? Then inspect all six; revise visible defects. Before the final run, list what the views show is wrong against the bought product you named (for a scan, the object in its photos), and fix each one or report it. To get a number out of a design (a spring force, a strain, a clearance you derived), print() it in the script: the result returns it as printed, with no need to make a run fail. A valid mesh or nominal parameter does not prove the requested dimension: measure the actual exported interfaces. Use cad_check_fit on a model and reference STL with an explicit rigid transform; report raw-scan interference and minimum gap. Calipers are authoritative but disagreement with a scan is unresolved measurement evidence, not permission to silently rescale it. Check assembly/insertion paths and actual articulated poses, not sums of local joint limits or reference points alone. Printing, clearance under load, supports and motion need separate evidence.
|
|
390
435
|
Fit, flexure and thread parameters: put each interface's nominal size, its source (measured, published, or assumed), the print correction, and the design fit in P as separate named values, so a fit report revises one number without resending the script. Model every dimension you claim: a parameter the geometry never uses (a wallet or case width that no cut or wall reads) is a defect; use it or remove it. Shape flexures so their bending lies in the layer plane of the exported print orientation, with the stroke, preload, and hard-stop gap as P values; build the stopped pose as well as the rest pose when checking. Model printed threads as explicit coarse geometry with the same pitch on both sides and clearance as a radial P offset; never scale a screw to clear its hole.
|