bambu-printer-mcp 1.1.61 → 1.1.63

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.
@@ -0,0 +1,273 @@
1
+ /**
2
+ * counterpart_propose_filaments (counterpart/1): which loaded spool prints each of a model's colours, proposed before
3
+ * slicing. Nearest colour in OKLab with the asked-for material preferred; one print feeds from one source. Each spool
4
+ * carries the words a person reads ("A2", "Sunflower Yellow PLA Basic") and every part an explicit verdict, so a client
5
+ * renders the result instead of re-deriving it. Pure: the server supplies the live trays.
6
+ */
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { COUNTERPART_CONTRACT } from "./schemas.js";
10
+ /** A colour this close (OKLab) to the asked-for one is the same colour to a person. */
11
+ export const SAME_COLOUR = 0.08;
12
+ const MATERIAL_PENALTY = 0.15;
13
+ const REUSE_PENALTY = 0.1;
14
+ const DISTINCT = 0.05;
15
+ function oklab(hex) {
16
+ const match = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(hex.trim());
17
+ if (!match)
18
+ return undefined;
19
+ const value = Number.parseInt(match[1], 16);
20
+ const linear = (channel) => { const s = channel / 255; return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; };
21
+ const r = linear(value >> 16 & 255), g = linear(value >> 8 & 255), b = linear(value & 255);
22
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
23
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
24
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
25
+ return [0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s, 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
26
+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s];
27
+ }
28
+ /** Perceptual distance between two `#RRGGBB` colours (0 identical, about 1 black to white). Alpha is ignored. */
29
+ export function colourDistance(a, b) {
30
+ const left = oklab(a), right = oklab(b);
31
+ if (!left || !right)
32
+ return Number.POSITIVE_INFINITY;
33
+ return Math.hypot(left[0] - right[0], left[1] - right[1], left[2] - right[2]);
34
+ }
35
+ const materialOf = (value) => value?.trim().toUpperCase() || undefined;
36
+ function pick(filament, loaded, assigned, requireMaterial) {
37
+ if (!loaded.length)
38
+ return undefined;
39
+ const wanted = materialOf(filament.material);
40
+ const mismatch = (tray) => wanted !== undefined && materialOf(tray.material) !== wanted;
41
+ const eligible = requireMaterial && wanted ? loaded.filter(tray => !mismatch(tray)) : loaded;
42
+ if (!eligible.length)
43
+ return undefined;
44
+ const target = filament.colour ? oklab(filament.colour) : undefined;
45
+ if (!target) {
46
+ const free = eligible.filter(tray => !assigned.has(tray.slot));
47
+ const pool = free.length ? free : eligible;
48
+ const chosen = pool.find(tray => !mismatch(tray)) ?? pool[0];
49
+ assigned.set(chosen.slot, [...(assigned.get(chosen.slot) ?? [])]);
50
+ return { slot: chosen.slot, guessed: true, ...(mismatch(chosen) ? { materialMismatch: true } : {}) };
51
+ }
52
+ let best;
53
+ for (const tray of eligible) {
54
+ const distance = colourDistance(filament.colour, tray.colour);
55
+ const shared = (assigned.get(tray.slot) ?? []).some(colour => colourDistance(colour, filament.colour) > DISTINCT);
56
+ const score = distance + (mismatch(tray) ? MATERIAL_PENALTY : 0) + (shared ? REUSE_PENALTY : 0);
57
+ if (!best || score < best.score || (score === best.score && tray.slot < best.tray.slot))
58
+ best = { tray, distance, score };
59
+ }
60
+ assigned.set(best.tray.slot, [...(assigned.get(best.tray.slot) ?? []), filament.colour]);
61
+ return { slot: best.tray.slot, distance: best.distance, ...(mismatch(best.tray) ? { materialMismatch: true } : {}) };
62
+ }
63
+ /**
64
+ * One match per filament, in order; undefined where nothing can serve it. Several filaments of one colour may share a
65
+ * spool. With `requireMaterial` (an already-sliced file) only spools of the asked-for material qualify. Automatic matches
66
+ * never mix feeds: the first feed listed (the AMS) is preferred, another feed only when it alone serves every colour.
67
+ */
68
+ export function matchColours(model, trays, options = {}) {
69
+ const loaded = trays.filter(tray => oklab(tray.colour));
70
+ const run = (pool) => { const assigned = new Map(); return model.map(filament => pick(filament, pool, assigned, !!options.requireMaterial)); };
71
+ const matches = run(loaded);
72
+ const feedOf = new Map(loaded.map(tray => [tray.slot, tray.feed]));
73
+ const feeds = [...new Set(loaded.map(tray => tray.feed))];
74
+ if (new Set(matches.flatMap(match => match ? [feedOf.get(match.slot)] : [])).size <= 1)
75
+ return matches;
76
+ const perFeed = feeds.map(feed => run(loaded.filter(tray => tray.feed === feed)));
77
+ return perFeed.find(result => result.every(match => match)) ?? perFeed[0];
78
+ }
79
+ export const NO_COLOUR_NAMES = { spool: () => undefined, colour: () => undefined };
80
+ export function loadColourNames(filamentProfileDir) {
81
+ if (!filamentProfileDir)
82
+ return NO_COLOUR_NAMES;
83
+ let data;
84
+ try {
85
+ const file = path.join(filamentProfileDir, "filaments_color_codes.json");
86
+ if (fs.statSync(file).size > 8 * 1024 * 1024)
87
+ return NO_COLOUR_NAMES;
88
+ data = JSON.parse(fs.readFileSync(file, "utf8")).data;
89
+ }
90
+ catch {
91
+ return NO_COLOUR_NAMES;
92
+ }
93
+ if (!Array.isArray(data))
94
+ return NO_COLOUR_NAMES;
95
+ const byId = new Map(), byColour = new Map();
96
+ for (const entry of data) {
97
+ const colours = Array.isArray(entry?.fila_color) ? entry.fila_color : [];
98
+ const name = typeof entry?.fila_color_name?.en === "string" ? entry.fila_color_name.en.trim().slice(0, 64) : "";
99
+ const id = typeof entry?.fila_id === "string" ? entry.fila_id.trim().toUpperCase() : "";
100
+ // Single colours only: a gradient or multi-colour spool's first colour is not its name.
101
+ if (colours.length !== 1 || typeof colours[0] !== "string" || !name || !/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(colours[0]))
102
+ continue;
103
+ const hex8 = (colours[0].slice(1) + "FF").slice(0, 8).toUpperCase();
104
+ if (id && !byId.has(`${id}#${hex8}`))
105
+ byId.set(`${id}#${hex8}`, name);
106
+ if (id && !byId.has(`${id}#${hex8.slice(0, 6)}`))
107
+ byId.set(`${id}#${hex8.slice(0, 6)}`, name);
108
+ // A bare colour's name: the shortest Bambu uses for exactly that opaque colour ("White", not "Jade White").
109
+ if (hex8.endsWith("FF")) {
110
+ const key = hex8.slice(0, 6), known = byColour.get(key);
111
+ if (!known || name.length < known.length)
112
+ byColour.set(key, name);
113
+ }
114
+ }
115
+ const hex = (value) => value.replace(/^#/, "").toUpperCase();
116
+ return {
117
+ spool: (filamentId, colour) => byId.get(`${filamentId.toUpperCase()}#${hex(colour)}`) ?? byId.get(`${filamentId.toUpperCase()}#${hex(colour).slice(0, 6)}`),
118
+ colour: colour => byColour.get(hex(colour).slice(0, 6)),
119
+ };
120
+ }
121
+ /** Where a Bambu tray sits, as Bambu Studio labels it: AMS units A–D with trays 1–4, AMS HT units by letter. */
122
+ export function bambuTrayLabel(amsId, trayId) {
123
+ const letter = (n) => String.fromCharCode(65 + Math.max(0, Math.min(n, 25)));
124
+ return amsId >= 128 ? `AMS HT ${letter(amsId - 128)}` : `${letter(amsId)}${trayId + 1}`;
125
+ }
126
+ /** A spool's name: its colour name (when Bambu names it) and product ("Sunflower Yellow PLA Basic"), else the product. */
127
+ export function spoolName(product, colourName) {
128
+ return (colourName ? `${colourName} ${product}` : product).trim().slice(0, 128);
129
+ }
130
+ const partName = (filament) => filament.name?.trim() || `Part ${filament.index}`;
131
+ export function proposeFilaments(input) {
132
+ const names = input.names ?? NO_COLOUR_NAMES;
133
+ const sliced = !!input.sliced;
134
+ const live = input.trays;
135
+ const menu = sliced ? live : live.filter(tray => tray.sliceable);
136
+ const problems = [];
137
+ const result = (proposal, mapping) => ({ contract: COUNTERPART_CONTRACT, trays: menu, proposal, ...(mapping && !problems.length ? { mapping } : {}), problems });
138
+ const describe = (tray) => `${tray.label} ${tray.name}`;
139
+ const colourWords = (colour) => names.colour(colour) ?? colour.toUpperCase();
140
+ // A sliced file's painted slots need their material on the same feed: they take part in choosing the feed,
141
+ // so the proposal never picks a feed that can't print them when another one can.
142
+ const required = sliced ? (input.painted ?? []).filter(slot => slot.material && slot.prints !== false
143
+ && !input.filaments.some(filament => filament.index === slot.index)) : [];
144
+ const matches = matchColours([...input.filaments, ...required], menu, { requireMaterial: sliced }).slice(0, input.filaments.length);
145
+ const proposal = input.filaments.map((filament, i) => {
146
+ const match = matches[i];
147
+ if (!match)
148
+ return { index: filament.index, verdict: "none" };
149
+ const tray = menu.find(item => item.slot === match.slot);
150
+ const row = { index: filament.index, slot: match.slot,
151
+ verdict: match.guessed ? "no-colour" : (match.distance ?? 0) <= SAME_COLOUR ? "same-colour" : "closest",
152
+ ...(match.distance !== undefined ? { distance: match.distance } : {}), ...(match.materialMismatch ? { materialMismatch: true } : {}) };
153
+ if (row.verdict === "no-colour")
154
+ row.note = "The model doesn’t say this part’s colour — pick its spool.";
155
+ else if (row.verdict === "closest") {
156
+ // The colour may be loaded but not chosen: on another feed (one print feeds from one source), in another
157
+ // material, or on a spool another colour of this model already prints from. Say which, never "isn't loaded".
158
+ const words = colourWords(filament.colour);
159
+ const loaded = menu.find(item => item.slot !== tray.slot && colourDistance(item.colour, filament.colour) <= SAME_COLOUR);
160
+ const wanted = materialOf(filament.material);
161
+ row.note = !loaded ? `${words} isn’t loaded. Closest loaded: ${describe(tray)}.`
162
+ : loaded.feed !== tray.feed ? `${words} is loaded on ${loaded.label}, but one print feeds from one source. Closest here: ${describe(tray)}.`
163
+ : wanted && materialOf(loaded.material) !== wanted ? `${words} is loaded on ${loaded.label} in ${loaded.material}, not ${filament.material}. Closest in ${filament.material}: ${describe(tray)}.`
164
+ : `${words} is on ${loaded.label}, which another colour of this model already prints from. Closest other spool: ${describe(tray)}.`;
165
+ }
166
+ if (match.materialMismatch)
167
+ row.note = `${row.note ? row.note + " " : ""}Prints in ${tray.material}, not ${filament.material}.`;
168
+ return row;
169
+ });
170
+ if (!input.filaments.length)
171
+ return result(proposal);
172
+ // The spools that will print, in filament order: the person's choices, validated, or the proposal.
173
+ let chosen;
174
+ if (input.chosen) {
175
+ if (input.chosen.length !== input.filaments.length || input.filaments.some((filament, i) => input.chosen[i].index !== filament.index)) {
176
+ problems.push({ code: "choices-incomplete", message: "Choose a spool for every colour in this model, then try again." });
177
+ return result(proposal);
178
+ }
179
+ chosen = [];
180
+ for (const [i, choice] of input.chosen.entries()) {
181
+ const tray = live.find(item => item.slot === choice.slot);
182
+ const filament = input.filaments[i];
183
+ if (!tray || (choice.colour !== undefined && choice.colour.toUpperCase() !== tray.colour.toUpperCase())
184
+ || (choice.material !== undefined && materialOf(choice.material) !== materialOf(tray.material)) || (choice.filamentId !== undefined && choice.filamentId !== tray.filamentId)) {
185
+ problems.push({ code: "spool-changed", index: filament.index, message: "A chosen filament changed. Choose the current spools and try again." });
186
+ continue;
187
+ }
188
+ if (sliced && filament.material && materialOf(tray.material) !== materialOf(filament.material))
189
+ problems.push({ code: "sliced-material", index: filament.index, message: `“${partName(filament)}” was sliced for ${filament.material}, so it can only print from a ${filament.material} spool. Choose one, or share the designer’s editable 3MF to change material.` });
190
+ if (!sliced && !tray.sliceable)
191
+ problems.push({ code: "no-profile", index: filament.index, message: `The ${tray.material} spool you chose has no slicing profile on this computer. Choose another spool.` });
192
+ chosen.push(tray);
193
+ }
194
+ if (problems.length)
195
+ return result(proposal);
196
+ if (new Set(chosen.map(tray => tray.feed)).size > 1) {
197
+ problems.push({ code: "mixed-feeds", message: "One print feeds from one source: put every colour on AMS spools, or every colour on the external spool." });
198
+ return result(proposal);
199
+ }
200
+ }
201
+ else {
202
+ const missing = matches.findIndex(match => !match);
203
+ if (!menu.length) {
204
+ problems.push({ code: "nothing-loaded", message: "No filament is loaded. Load a spool in the AMS, then try again." });
205
+ return result(proposal);
206
+ }
207
+ if (missing >= 0) {
208
+ const filament = input.filaments[missing];
209
+ const elsewhere = sliced && filament.material && live.some(tray => materialOf(tray.material) === materialOf(filament.material));
210
+ problems.push({ code: elsewhere ? "material-on-another-feed" : "material-not-loaded", index: filament.index, message: elsewhere
211
+ ? `“${partName(filament)}” needs ${filament.material}, but one print feeds from one source and no single source holds every colour’s material. Load the spools on one source, then try again.`
212
+ : sliced && filament.material
213
+ ? `No ${filament.material} spool is loaded for “${partName(filament)}”, and this file was sliced for ${filament.material}. Load one, then try again.`
214
+ : "No filament is loaded. Load a spool in the AMS, then try again." });
215
+ return result(proposal);
216
+ }
217
+ chosen = matches.map(match => menu.find(tray => tray.slot === match.slot));
218
+ }
219
+ const mapping = new Map(input.filaments.map((filament, i) => [filament.index, chosen[i].slot]));
220
+ const feed = chosen[0].feed;
221
+ const chosenSlots = new Set(chosen.map(tray => tray.slot));
222
+ const primary = live[0]?.feed;
223
+ // A painted slot follows the chosen feed: on the external spool(s) exactly those chosen; on the AMS any AMS spool.
224
+ const fillerPool = menu.filter(tray => feed === primary ? tray.feed === feed : chosenSlots.has(tray.slot));
225
+ for (const painted of input.painted ?? []) {
226
+ if (mapping.has(painted.index))
227
+ continue;
228
+ const [match] = matchColours([painted], fillerPool, { requireMaterial: sliced });
229
+ if (match)
230
+ mapping.set(painted.index, match.slot);
231
+ else if (sliced && painted.material && painted.prints !== false)
232
+ problems.push({ code: "painted-material", index: painted.index, message: `A painted part of this file was sliced for ${painted.material}, and no ${painted.material} spool on the chosen feed source can print it. Load one, then try again.` });
233
+ else
234
+ mapping.set(painted.index, chosen[0].slot);
235
+ }
236
+ return result(proposal, [...mapping.entries()].sort((a, b) => a[0] - b[0]).map(([index, slot]) => ({ index, slot })));
237
+ }
238
+ const colour = { type: "string", pattern: "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$" };
239
+ export const PROPOSE_FILAMENTS_INPUT_PROPERTIES = {
240
+ filaments: {
241
+ type: "array", maxItems: 64,
242
+ description: "The model's filaments a person sees, in project order: 1-based index, part name, the colour it belongs in and its material when known.",
243
+ items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, name: { type: "string", maxLength: 256 }, colour, material: { type: "string", maxLength: 64 } }, required: ["index"], additionalProperties: false },
244
+ },
245
+ painted: {
246
+ type: "array", maxItems: 64,
247
+ description: "Filament slots no part names (painted regions). Each follows the chosen spools' feed; prints false when the selected plate never uses it.",
248
+ items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, colour, material: { type: "string", maxLength: 64 }, prints: { type: "boolean" } }, required: ["index"], additionalProperties: false },
249
+ },
250
+ chosen: {
251
+ type: "array", maxItems: 64,
252
+ description: "The person's spool for each filament, in the same order: checked against what is loaded now. Omit for the proposal alone.",
253
+ items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, slot: { type: "integer", minimum: 0, maximum: 4095 }, colour, material: { type: "string", maxLength: 128 }, filamentId: { type: "string", maxLength: 128 } }, required: ["index", "slot"], additionalProperties: false },
254
+ },
255
+ sliced: { type: "boolean", description: "The file is already sliced: its materials are fixed, so only spools of the same material qualify." },
256
+ };
257
+ export const PROPOSE_FILAMENTS_OUTPUT_SCHEMA = {
258
+ type: "object",
259
+ properties: {
260
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
261
+ trays: { type: "array", items: { type: "object", properties: {
262
+ slot: { type: "integer" }, label: { type: "string" }, name: { type: "string" }, colour: { type: "string" }, material: { type: "string" },
263
+ filamentId: { type: "string" }, feed: { type: "string" }, sliceable: { type: "boolean" }, profile: { type: "string" },
264
+ }, required: ["slot", "label", "name", "colour", "material", "filamentId", "feed", "sliceable"] } },
265
+ proposal: { type: "array", items: { type: "object", properties: {
266
+ index: { type: "integer" }, slot: { type: "integer" }, verdict: { type: "string", enum: ["same-colour", "closest", "no-colour", "none"] },
267
+ distance: { type: "number" }, materialMismatch: { type: "boolean" }, note: { type: "string" },
268
+ }, required: ["index", "verdict"] } },
269
+ mapping: { type: "array", items: { type: "object", properties: { index: { type: "integer" }, slot: { type: "integer" } }, required: ["index", "slot"] } },
270
+ problems: { type: "array", items: { type: "object", properties: { code: { type: "string" }, message: { type: "string" }, index: { type: "integer" } }, required: ["code", "message"] } },
271
+ },
272
+ required: ["contract", "trays", "proposal", "problems"],
273
+ };
@@ -0,0 +1,292 @@
1
+ import { COUNTERPART_CONTRACT, PRINTER_KINDS } from "./schemas.js";
2
+ export declare const SETUP_FIELD_NAMES: readonly ["host", "port", "serial", "model", "secret", "slicer", "slicer-path", "profiles"];
3
+ export type SetupField = {
4
+ /** The client's form field this is: an address, a port, a serial number, a model choice or a secret. */
5
+ name: typeof SETUP_FIELD_NAMES[number];
6
+ /** The variable to write. */
7
+ env: string;
8
+ /** Older names for it that this server reads before `env`: a client writing `env` removes these lines, or the old value wins. */
9
+ aliases?: string[];
10
+ label: string;
11
+ hint?: string;
12
+ required: boolean;
13
+ /** A path on this computer (a slicer app, a profiles folder): a client may offer a file chooser. */
14
+ input?: "path";
15
+ /** Written as typed, or upper-cased (Bambu serial numbers). */
16
+ transform?: "uppercase";
17
+ choices?: Array<{
18
+ value: string;
19
+ label: string;
20
+ }>;
21
+ /** A model field: the model a serial number names, by its first `prefixLength` characters. */
22
+ fromSerial?: {
23
+ prefixLength: number;
24
+ models: Record<string, string>;
25
+ };
26
+ };
27
+ export type SetupKind = {
28
+ kind: typeof PRINTER_KINDS[number];
29
+ label: string;
30
+ /** Values this server needs for the kind whatever the person enters (MCP_TRANSPORT, PRINTER_TYPE). */
31
+ env: Record<string, string>;
32
+ fields: SetupField[];
33
+ };
34
+ /** The slicer this server runs, as it resolves it now, and the settings that choose it (for every printer). */
35
+ export type SlicerSetup = {
36
+ type: string;
37
+ /** The slicer app it would run, and whether that app is there. */
38
+ path?: string;
39
+ found: boolean;
40
+ /** The Bambu profiles folder it would read (Bambu Studio and Orca), and whether it has BBL's profiles. */
41
+ profilesRoot?: string;
42
+ profilesFound?: boolean;
43
+ fields: SetupField[];
44
+ };
45
+ export type SetupFields = {
46
+ contract: typeof COUNTERPART_CONTRACT;
47
+ server: {
48
+ name: string;
49
+ version: string;
50
+ };
51
+ kinds: SetupKind[];
52
+ model?: string;
53
+ slicer?: SlicerSetup;
54
+ };
55
+ /**
56
+ * The slicer settings, with what this server resolves now: a client shows "Bambu Studio isn't installed" or asks for
57
+ * its location instead of the person editing SLICER_PATH by hand. A setting is required only when what it would
58
+ * default to isn't there.
59
+ */
60
+ export declare function slicerSetup(options: {
61
+ types: readonly string[];
62
+ type: string;
63
+ path?: string;
64
+ found: boolean;
65
+ profilesRoot?: string;
66
+ profilesFound?: boolean;
67
+ remote?: boolean;
68
+ }): SlicerSetup;
69
+ /** Each serial prefix's model in this server's values (bambu_model), where it has one. */
70
+ export declare function serialModelValues(valid: readonly string[]): Record<string, string>;
71
+ /** Bambu's display names for this server's model values ("a1mini" → "A1 Mini"). */
72
+ export declare function modelChoices(valid: readonly string[]): Array<{
73
+ value: string;
74
+ label: string;
75
+ }>;
76
+ export declare function bambuSetupFields(options: {
77
+ server: {
78
+ name: string;
79
+ version: string;
80
+ };
81
+ models: readonly string[];
82
+ serial?: string;
83
+ slicer?: SlicerSetup;
84
+ }): SetupFields;
85
+ export declare const SETUP_FIELDS_OUTPUT_SCHEMA: {
86
+ type: "object";
87
+ properties: {
88
+ contract: {
89
+ type: string;
90
+ const: string;
91
+ };
92
+ server: {
93
+ type: string;
94
+ properties: {
95
+ name: {
96
+ type: string;
97
+ };
98
+ version: {
99
+ type: string;
100
+ };
101
+ };
102
+ required: string[];
103
+ };
104
+ kinds: {
105
+ type: string;
106
+ items: {
107
+ type: string;
108
+ properties: {
109
+ kind: {
110
+ type: string;
111
+ enum: ("bambu" | "octoprint" | "klipper" | "prusa" | "duet" | "repetier" | "creality")[];
112
+ };
113
+ label: {
114
+ type: string;
115
+ };
116
+ env: {
117
+ type: string;
118
+ additionalProperties: {
119
+ type: string;
120
+ };
121
+ };
122
+ fields: {
123
+ type: string;
124
+ items: {
125
+ type: string;
126
+ properties: {
127
+ name: {
128
+ type: string;
129
+ enum: ("model" | "slicer" | "host" | "port" | "profiles" | "serial" | "secret" | "slicer-path")[];
130
+ };
131
+ env: {
132
+ type: string;
133
+ };
134
+ aliases: {
135
+ type: string;
136
+ items: {
137
+ type: string;
138
+ };
139
+ description: string;
140
+ };
141
+ label: {
142
+ type: string;
143
+ };
144
+ hint: {
145
+ type: string;
146
+ };
147
+ required: {
148
+ type: string;
149
+ };
150
+ input: {
151
+ type: string;
152
+ enum: string[];
153
+ };
154
+ transform: {
155
+ type: string;
156
+ enum: string[];
157
+ };
158
+ choices: {
159
+ type: string;
160
+ items: {
161
+ type: string;
162
+ properties: {
163
+ value: {
164
+ type: string;
165
+ };
166
+ label: {
167
+ type: string;
168
+ };
169
+ };
170
+ required: string[];
171
+ };
172
+ };
173
+ fromSerial: {
174
+ type: string;
175
+ properties: {
176
+ prefixLength: {
177
+ type: string;
178
+ };
179
+ models: {
180
+ type: string;
181
+ additionalProperties: {
182
+ type: string;
183
+ };
184
+ };
185
+ };
186
+ required: string[];
187
+ };
188
+ };
189
+ required: string[];
190
+ };
191
+ };
192
+ };
193
+ required: string[];
194
+ };
195
+ };
196
+ model: {
197
+ type: string;
198
+ };
199
+ slicer: {
200
+ type: string;
201
+ properties: {
202
+ type: {
203
+ type: string;
204
+ };
205
+ path: {
206
+ type: string;
207
+ };
208
+ found: {
209
+ type: string;
210
+ };
211
+ profilesRoot: {
212
+ type: string;
213
+ };
214
+ profilesFound: {
215
+ type: string;
216
+ };
217
+ fields: {
218
+ type: string;
219
+ items: {
220
+ type: string;
221
+ properties: {
222
+ name: {
223
+ type: string;
224
+ enum: ("model" | "slicer" | "host" | "port" | "profiles" | "serial" | "secret" | "slicer-path")[];
225
+ };
226
+ env: {
227
+ type: string;
228
+ };
229
+ aliases: {
230
+ type: string;
231
+ items: {
232
+ type: string;
233
+ };
234
+ description: string;
235
+ };
236
+ label: {
237
+ type: string;
238
+ };
239
+ hint: {
240
+ type: string;
241
+ };
242
+ required: {
243
+ type: string;
244
+ };
245
+ input: {
246
+ type: string;
247
+ enum: string[];
248
+ };
249
+ transform: {
250
+ type: string;
251
+ enum: string[];
252
+ };
253
+ choices: {
254
+ type: string;
255
+ items: {
256
+ type: string;
257
+ properties: {
258
+ value: {
259
+ type: string;
260
+ };
261
+ label: {
262
+ type: string;
263
+ };
264
+ };
265
+ required: string[];
266
+ };
267
+ };
268
+ fromSerial: {
269
+ type: string;
270
+ properties: {
271
+ prefixLength: {
272
+ type: string;
273
+ };
274
+ models: {
275
+ type: string;
276
+ additionalProperties: {
277
+ type: string;
278
+ };
279
+ };
280
+ };
281
+ required: string[];
282
+ };
283
+ };
284
+ required: string[];
285
+ };
286
+ };
287
+ };
288
+ required: string[];
289
+ };
290
+ };
291
+ required: string[];
292
+ };
@@ -0,0 +1,91 @@
1
+ /**
2
+ * counterpart_setup_fields (counterpart/1): the printers this server drives and the settings it reads for each, by the
3
+ * environment variable names it reads (`env`, and older `aliases` it reads first). A client renders these fields, writes the values
4
+ * to this server's .env and never needs its own printer or model tables. Pure: no printer traffic, no secrets returned.
5
+ */
6
+ import { normalizeModel } from "../safety/limits.js";
7
+ import { SERIAL_MODELS } from "../safety/printer-state.js";
8
+ import { COUNTERPART_CONTRACT, PRINTER_KINDS } from "./schemas.js";
9
+ export const SETUP_FIELD_NAMES = ["host", "port", "serial", "model", "secret", "slicer", "slicer-path", "profiles"];
10
+ const SLICER_LABELS = {
11
+ bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "OrcaSlicer-bambulab (FULU)", "orca-slicer-api": "OrcaSlicer API (remote)",
12
+ prusaslicer: "PrusaSlicer", cura: "Cura", slic3r: "Slic3r",
13
+ };
14
+ /**
15
+ * The slicer settings, with what this server resolves now: a client shows "Bambu Studio isn't installed" or asks for
16
+ * its location instead of the person editing SLICER_PATH by hand. A setting is required only when what it would
17
+ * default to isn't there.
18
+ */
19
+ export function slicerSetup(options) {
20
+ const label = SLICER_LABELS[options.type] ?? options.type;
21
+ const fields = [
22
+ { name: "slicer", env: "SLICER_TYPE", label: "Slicer", required: false, choices: options.types.map(value => ({ value, label: SLICER_LABELS[value] ?? value })) },
23
+ ];
24
+ if (!options.remote)
25
+ fields.push({ name: "slicer-path", env: "SLICER_PATH", label: `${label} app`, input: "path", required: !options.found,
26
+ hint: options.found ? `Found at ${options.path}. Set this only to use another copy.`
27
+ : options.path ? `${label} isn't at ${options.path}. Install it, or choose where it is.` : `Where ${label} is installed.` });
28
+ if (options.profilesFound !== undefined)
29
+ fields.push({ name: "profiles", env: "BAMBU_PROFILES_ROOT", label: "Bambu profiles folder", input: "path", required: !options.profilesFound,
30
+ hint: options.profilesFound ? `Found at ${options.profilesRoot}. Set this only to use other profiles.` : `The folder with ${label}'s BBL profiles (it holds BBL/machine). Install ${label}, or choose the folder.` });
31
+ return { type: options.type, ...(options.path !== undefined ? { path: options.path } : {}), found: options.found,
32
+ ...(options.profilesRoot !== undefined ? { profilesRoot: options.profilesRoot } : {}), ...(options.profilesFound !== undefined ? { profilesFound: options.profilesFound } : {}), fields };
33
+ }
34
+ /** Each serial prefix's model in this server's values (bambu_model), where it has one. */
35
+ export function serialModelValues(valid) {
36
+ return Object.fromEntries(Object.entries(SERIAL_MODELS).flatMap(([prefix, name]) => {
37
+ const model = normalizeModel(name);
38
+ return model && valid.includes(model) ? [[prefix, model]] : [];
39
+ }));
40
+ }
41
+ /** Bambu's display names for this server's model values ("a1mini" → "A1 Mini"). */
42
+ export function modelChoices(valid) {
43
+ const names = new Map(Object.values(SERIAL_MODELS).map(name => [normalizeModel(name), name]));
44
+ return valid.map(value => ({ value, label: names.get(value) ?? value.toUpperCase() }));
45
+ }
46
+ export function bambuSetupFields(options) {
47
+ const fromSerial = { prefixLength: 3, models: serialModelValues(options.models) };
48
+ const model = options.serial ? fromSerial.models[options.serial.trim().slice(0, 3).toUpperCase()] : undefined;
49
+ return {
50
+ contract: COUNTERPART_CONTRACT,
51
+ server: options.server,
52
+ kinds: [{
53
+ kind: "bambu", label: "Bambu Lab", env: { MCP_TRANSPORT: "stdio" },
54
+ fields: [
55
+ { name: "host", env: "PRINTER_HOST", aliases: ["BAMBU_PRINTER_HOST"], label: "Address", hint: "The printer's IP address: on the printer, Settings → WLAN", required: true },
56
+ { name: "serial", env: "BAMBU_SERIAL", aliases: ["BAMBU_PRINTER_SERIAL"], label: "Serial number", hint: "On the printer: Settings → Device", required: true, transform: "uppercase" },
57
+ { name: "model", env: "BAMBU_MODEL", aliases: ["BAMBU_PRINTER_MODEL"], label: "Model", required: true, choices: modelChoices(options.models), fromSerial },
58
+ { name: "secret", env: "BAMBU_TOKEN", aliases: ["BAMBU_PRINTER_ACCESS_TOKEN"], label: "Access code", hint: "On the printer: Settings → WLAN → Access Code", required: true },
59
+ ],
60
+ }],
61
+ ...(model ? { model } : {}),
62
+ ...(options.slicer ? { slicer: options.slicer } : {}),
63
+ };
64
+ }
65
+ const field = {
66
+ type: "object",
67
+ properties: {
68
+ name: { type: "string", enum: [...SETUP_FIELD_NAMES] }, env: { type: "string" }, aliases: { type: "array", items: { type: "string" }, description: "Older names this server reads before env: a client writing env removes these, or the old value wins." },
69
+ label: { type: "string" }, hint: { type: "string" }, required: { type: "boolean" }, input: { type: "string", enum: ["path"] }, transform: { type: "string", enum: ["uppercase"] },
70
+ choices: { type: "array", items: { type: "object", properties: { value: { type: "string" }, label: { type: "string" } }, required: ["value", "label"] } },
71
+ fromSerial: { type: "object", properties: { prefixLength: { type: "integer" }, models: { type: "object", additionalProperties: { type: "string" } } }, required: ["prefixLength", "models"] },
72
+ },
73
+ required: ["name", "env", "label", "required"],
74
+ };
75
+ export const SETUP_FIELDS_OUTPUT_SCHEMA = {
76
+ type: "object",
77
+ properties: {
78
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
79
+ server: { type: "object", properties: { name: { type: "string" }, version: { type: "string" } }, required: ["name", "version"] },
80
+ kinds: { type: "array", items: { type: "object", properties: {
81
+ kind: { type: "string", enum: [...PRINTER_KINDS] }, label: { type: "string" },
82
+ env: { type: "object", additionalProperties: { type: "string" } }, fields: { type: "array", items: field },
83
+ }, required: ["kind", "label", "env", "fields"] } },
84
+ model: { type: "string" },
85
+ slicer: { type: "object", properties: {
86
+ type: { type: "string" }, path: { type: "string" }, found: { type: "boolean" }, profilesRoot: { type: "string" }, profilesFound: { type: "boolean" },
87
+ fields: { type: "array", items: field },
88
+ }, required: ["type", "found", "fields"] },
89
+ },
90
+ required: ["contract", "server", "kinds"],
91
+ };