bambu-printer-mcp 1.1.62 → 1.1.64

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,297 @@
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
+
11
+ /** One loaded spool as a client shows it. `feed` groups the spools that can feed one print together. */
12
+ export type ProposalTray = {
13
+ slot: number; label: string; name: string; colour: string; material: string; filamentId: string; feed: string;
14
+ /** This server can slice with it (a filament profile is resolved for it). */
15
+ sliceable: boolean;
16
+ /** The resolved slicer filament profile (absolute path), the one slice_stl takes in load_filaments. */
17
+ profile?: string;
18
+ };
19
+ export type ProposalFilament = { index: number; name?: string; colour?: string; material?: string };
20
+ /** A filament slot no part names (a painted region): it follows the chosen spools' feed. `prints` false: not on this plate. */
21
+ export type PaintedFilament = { index: number; colour?: string; material?: string; prints?: boolean };
22
+ export type ChosenSpool = { index: number; slot: number; colour?: string; material?: string; filamentId?: string };
23
+ export type Verdict = "same-colour" | "closest" | "no-colour" | "none";
24
+ export type ProposalRow = {
25
+ index: number; slot?: number; verdict: Verdict; distance?: number; materialMismatch?: boolean;
26
+ /** What the person should know about this suggestion, in their words. */
27
+ note?: string;
28
+ };
29
+ export type ProposalProblem = { code: string; message: string; index?: number };
30
+ export type FilamentProposal = {
31
+ contract: typeof COUNTERPART_CONTRACT;
32
+ /** The spools a person may choose from: every loaded one for a sliced file, the sliceable ones otherwise. */
33
+ trays: ProposalTray[];
34
+ proposal: ProposalRow[];
35
+ /** Every filament slot (parts and painted) to its spool, when the proposal or the person's choice is printable. */
36
+ mapping?: Array<{ index: number; slot: number }>;
37
+ problems: ProposalProblem[];
38
+ };
39
+
40
+ /** A colour this close (OKLab) to the asked-for one is the same colour to a person. */
41
+ export const SAME_COLOUR = 0.08;
42
+ const MATERIAL_PENALTY = 0.15;
43
+ const REUSE_PENALTY = 0.1;
44
+ const DISTINCT = 0.05;
45
+
46
+ function oklab(hex: string): [number, number, number] | undefined {
47
+ const match = /^#?([0-9a-fA-F]{6})(?:[0-9a-fA-F]{2})?$/.exec(hex.trim());
48
+ if (!match) return undefined;
49
+ const value = Number.parseInt(match[1]!, 16);
50
+ const linear = (channel: number) => { const s = channel / 255; return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; };
51
+ const r = linear(value >> 16 & 255), g = linear(value >> 8 & 255), b = linear(value & 255);
52
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
53
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
54
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
55
+ return [0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s, 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
56
+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s];
57
+ }
58
+
59
+ /** Perceptual distance between two `#RRGGBB` colours (0 identical, about 1 black to white). Alpha is ignored. */
60
+ export function colourDistance(a: string, b: string): number {
61
+ const left = oklab(a), right = oklab(b);
62
+ if (!left || !right) return Number.POSITIVE_INFINITY;
63
+ return Math.hypot(left[0] - right[0], left[1] - right[1], left[2] - right[2]);
64
+ }
65
+
66
+ type Match = { slot: number; distance?: number; materialMismatch?: boolean; guessed?: boolean };
67
+ const materialOf = (value: string | undefined) => value?.trim().toUpperCase() || undefined;
68
+
69
+ function pick(filament: { colour?: string; material?: string }, loaded: ProposalTray[], assigned: Map<number, string[]>, requireMaterial: boolean): Match | undefined {
70
+ if (!loaded.length) return undefined;
71
+ const wanted = materialOf(filament.material);
72
+ const mismatch = (tray: ProposalTray) => wanted !== undefined && materialOf(tray.material) !== wanted;
73
+ const eligible = requireMaterial && wanted ? loaded.filter(tray => !mismatch(tray)) : loaded;
74
+ if (!eligible.length) return undefined;
75
+ const target = filament.colour ? oklab(filament.colour) : undefined;
76
+ if (!target) {
77
+ const free = eligible.filter(tray => !assigned.has(tray.slot));
78
+ const pool = free.length ? free : eligible;
79
+ const chosen = pool.find(tray => !mismatch(tray)) ?? pool[0]!;
80
+ assigned.set(chosen.slot, [...(assigned.get(chosen.slot) ?? [])]);
81
+ return { slot: chosen.slot, guessed: true, ...(mismatch(chosen) ? { materialMismatch: true } : {}) };
82
+ }
83
+ let best: { tray: ProposalTray; distance: number; score: number } | undefined;
84
+ for (const tray of eligible) {
85
+ const distance = colourDistance(filament.colour!, tray.colour);
86
+ const shared = (assigned.get(tray.slot) ?? []).some(colour => colourDistance(colour, filament.colour!) > DISTINCT);
87
+ const score = distance + (mismatch(tray) ? MATERIAL_PENALTY : 0) + (shared ? REUSE_PENALTY : 0);
88
+ if (!best || score < best.score || (score === best.score && tray.slot < best.tray.slot)) best = { tray, distance, score };
89
+ }
90
+ assigned.set(best!.tray.slot, [...(assigned.get(best!.tray.slot) ?? []), filament.colour!]);
91
+ return { slot: best!.tray.slot, distance: best!.distance, ...(mismatch(best!.tray) ? { materialMismatch: true } : {}) };
92
+ }
93
+
94
+ /**
95
+ * One match per filament, in order; undefined where nothing can serve it. Several filaments of one colour may share a
96
+ * spool. With `requireMaterial` (an already-sliced file) only spools of the asked-for material qualify. Automatic matches
97
+ * never mix feeds: the first feed listed (the AMS) is preferred, another feed only when it alone serves every colour.
98
+ */
99
+ export function matchColours(model: Array<{ colour?: string; material?: string }>, trays: ProposalTray[], options: { requireMaterial?: boolean } = {}): (Match | undefined)[] {
100
+ const loaded = trays.filter(tray => oklab(tray.colour));
101
+ const run = (pool: ProposalTray[]) => { const assigned = new Map<number, string[]>(); return model.map(filament => pick(filament, pool, assigned, !!options.requireMaterial)); };
102
+ const matches = run(loaded);
103
+ const feedOf = new Map(loaded.map(tray => [tray.slot, tray.feed]));
104
+ const feeds = [...new Set(loaded.map(tray => tray.feed))];
105
+ if (new Set(matches.flatMap(match => match ? [feedOf.get(match.slot)] : [])).size <= 1) return matches;
106
+ const perFeed = feeds.map(feed => run(loaded.filter(tray => tray.feed === feed)));
107
+ return perFeed.find(result => result.every(match => match)) ?? perFeed[0]!;
108
+ }
109
+
110
+ /** The colour names Bambu Studio itself uses for its filaments (profiles/BBL/filament/filaments_color_codes.json). */
111
+ export type ColourNames = { spool(filamentId: string, colour: string): string | undefined; colour(colour: string): string | undefined };
112
+ export const NO_COLOUR_NAMES: ColourNames = { spool: () => undefined, colour: () => undefined };
113
+
114
+ export function loadColourNames(filamentProfileDir: string | undefined): ColourNames {
115
+ if (!filamentProfileDir) return NO_COLOUR_NAMES;
116
+ let data: unknown;
117
+ try {
118
+ const file = path.join(filamentProfileDir, "filaments_color_codes.json");
119
+ if (fs.statSync(file).size > 8 * 1024 * 1024) return NO_COLOUR_NAMES;
120
+ data = (JSON.parse(fs.readFileSync(file, "utf8")) as { data?: unknown }).data;
121
+ } catch { return NO_COLOUR_NAMES; }
122
+ if (!Array.isArray(data)) return NO_COLOUR_NAMES;
123
+ const byId = new Map<string, string>(), byColour = new Map<string, string>();
124
+ for (const entry of data) {
125
+ const colours = Array.isArray(entry?.fila_color) ? entry.fila_color : [];
126
+ const name = typeof entry?.fila_color_name?.en === "string" ? entry.fila_color_name.en.trim().slice(0, 64) : "";
127
+ const id = typeof entry?.fila_id === "string" ? entry.fila_id.trim().toUpperCase() : "";
128
+ // Single colours only: a gradient or multi-colour spool's first colour is not its name.
129
+ if (colours.length !== 1 || typeof colours[0] !== "string" || !name || !/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(colours[0])) continue;
130
+ const hex8 = (colours[0].slice(1) + "FF").slice(0, 8).toUpperCase();
131
+ if (id && !byId.has(`${id}#${hex8}`)) byId.set(`${id}#${hex8}`, name);
132
+ if (id && !byId.has(`${id}#${hex8.slice(0, 6)}`)) byId.set(`${id}#${hex8.slice(0, 6)}`, name);
133
+ // A bare colour's name: the shortest Bambu uses for exactly that opaque colour ("White", not "Jade White").
134
+ if (hex8.endsWith("FF")) {
135
+ const key = hex8.slice(0, 6), known = byColour.get(key);
136
+ if (!known || name.length < known.length) byColour.set(key, name);
137
+ }
138
+ }
139
+ const hex = (value: string) => value.replace(/^#/, "").toUpperCase();
140
+ return {
141
+ spool: (filamentId, colour) => byId.get(`${filamentId.toUpperCase()}#${hex(colour)}`) ?? byId.get(`${filamentId.toUpperCase()}#${hex(colour).slice(0, 6)}`),
142
+ colour: colour => byColour.get(hex(colour).slice(0, 6)),
143
+ };
144
+ }
145
+
146
+ /** Where a Bambu tray sits, as Bambu Studio labels it: AMS units A–D with trays 1–4, AMS HT units by letter. */
147
+ export function bambuTrayLabel(amsId: number, trayId: number): string {
148
+ const letter = (n: number) => String.fromCharCode(65 + Math.max(0, Math.min(n, 25)));
149
+ return amsId >= 128 ? `AMS HT ${letter(amsId - 128)}` : `${letter(amsId)}${trayId + 1}`;
150
+ }
151
+
152
+ /** A spool's name: its colour name (when Bambu names it) and product ("Sunflower Yellow PLA Basic"), else the product. */
153
+ export function spoolName(product: string, colourName: string | undefined): string {
154
+ return (colourName ? `${colourName} ${product}` : product).trim().slice(0, 128);
155
+ }
156
+
157
+ const partName = (filament: ProposalFilament) => filament.name?.trim() || `Part ${filament.index}`;
158
+
159
+ export function proposeFilaments(input: {
160
+ trays: ProposalTray[]; filaments: ProposalFilament[]; painted?: PaintedFilament[]; chosen?: ChosenSpool[]; sliced?: boolean; names?: ColourNames;
161
+ }): FilamentProposal {
162
+ const names = input.names ?? NO_COLOUR_NAMES;
163
+ const sliced = !!input.sliced;
164
+ const live = input.trays;
165
+ const menu = sliced ? live : live.filter(tray => tray.sliceable);
166
+ const problems: ProposalProblem[] = [];
167
+ const result = (proposal: ProposalRow[], mapping?: Array<{ index: number; slot: number }>): FilamentProposal =>
168
+ ({ contract: COUNTERPART_CONTRACT, trays: menu, proposal, ...(mapping && !problems.length ? { mapping } : {}), problems });
169
+ const describe = (tray: ProposalTray) => `${tray.label} ${tray.name}`;
170
+ const colourWords = (colour: string) => names.colour(colour) ?? colour.toUpperCase();
171
+
172
+ // A sliced file's painted slots need their material on the same feed: they take part in choosing the feed,
173
+ // so the proposal never picks a feed that can't print them when another one can.
174
+ const required = sliced ? (input.painted ?? []).filter(slot => slot.material && slot.prints !== false
175
+ && !input.filaments.some(filament => filament.index === slot.index)) : [];
176
+ const matches = matchColours([...input.filaments, ...required], menu, { requireMaterial: sliced }).slice(0, input.filaments.length);
177
+ const proposal: ProposalRow[] = input.filaments.map((filament, i) => {
178
+ const match = matches[i];
179
+ if (!match) return { index: filament.index, verdict: "none" as const };
180
+ const tray = menu.find(item => item.slot === match.slot)!;
181
+ const row: ProposalRow = { index: filament.index, slot: match.slot,
182
+ verdict: match.guessed ? "no-colour" : (match.distance ?? 0) <= SAME_COLOUR ? "same-colour" : "closest",
183
+ ...(match.distance !== undefined ? { distance: match.distance } : {}), ...(match.materialMismatch ? { materialMismatch: true } : {}) };
184
+ if (row.verdict === "no-colour") row.note = "The model doesn’t say this part’s colour — pick its spool.";
185
+ else if (row.verdict === "closest") {
186
+ // The colour may be loaded but not chosen: on another feed (one print feeds from one source), in another
187
+ // material, or on a spool another colour of this model already prints from. Say which, never "isn't loaded".
188
+ const words = colourWords(filament.colour!);
189
+ const loaded = menu.find(item => item.slot !== tray.slot && colourDistance(item.colour, filament.colour!) <= SAME_COLOUR);
190
+ const wanted = materialOf(filament.material);
191
+ row.note = !loaded ? `${words} isn’t loaded. Closest loaded: ${describe(tray)}.`
192
+ : loaded.feed !== tray.feed ? `${words} is loaded on ${loaded.label}, but one print feeds from one source. Closest here: ${describe(tray)}.`
193
+ : wanted && materialOf(loaded.material) !== wanted ? `${words} is loaded on ${loaded.label} in ${loaded.material}, not ${filament.material}. Closest in ${filament.material}: ${describe(tray)}.`
194
+ : `${words} is on ${loaded.label}, which another colour of this model already prints from. Closest other spool: ${describe(tray)}.`;
195
+ }
196
+ if (match.materialMismatch) row.note = `${row.note ? row.note + " " : ""}Prints in ${tray.material}, not ${filament.material}.`;
197
+ return row;
198
+ });
199
+
200
+ if (!input.filaments.length) return result(proposal);
201
+ // The spools that will print, in filament order: the person's choices, validated, or the proposal.
202
+ let chosen: ProposalTray[];
203
+ if (input.chosen) {
204
+ if (input.chosen.length !== input.filaments.length || input.filaments.some((filament, i) => input.chosen![i]!.index !== filament.index)) {
205
+ problems.push({ code: "choices-incomplete", message: "Choose a spool for every colour in this model, then try again." });
206
+ return result(proposal);
207
+ }
208
+ chosen = [];
209
+ for (const [i, choice] of input.chosen.entries()) {
210
+ const tray = live.find(item => item.slot === choice.slot);
211
+ const filament = input.filaments[i]!;
212
+ if (!tray || (choice.colour !== undefined && choice.colour.toUpperCase() !== tray.colour.toUpperCase())
213
+ || (choice.material !== undefined && materialOf(choice.material) !== materialOf(tray.material)) || (choice.filamentId !== undefined && choice.filamentId !== tray.filamentId)) {
214
+ problems.push({ code: "spool-changed", index: filament.index, message: "A chosen filament changed. Choose the current spools and try again." });
215
+ continue;
216
+ }
217
+ if (sliced && filament.material && materialOf(tray.material) !== materialOf(filament.material))
218
+ 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.` });
219
+ if (!sliced && !tray.sliceable)
220
+ 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.` });
221
+ chosen.push(tray);
222
+ }
223
+ if (problems.length) return result(proposal);
224
+ if (new Set(chosen.map(tray => tray.feed)).size > 1) {
225
+ 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." });
226
+ return result(proposal);
227
+ }
228
+ } else {
229
+ const missing = matches.findIndex(match => !match);
230
+ if (!menu.length) { problems.push({ code: "nothing-loaded", message: "No filament is loaded. Load a spool in the AMS, then try again." }); return result(proposal); }
231
+ if (missing >= 0) {
232
+ const filament = input.filaments[missing]!;
233
+ const elsewhere = sliced && filament.material && live.some(tray => materialOf(tray.material) === materialOf(filament.material));
234
+ problems.push({ code: elsewhere ? "material-on-another-feed" : "material-not-loaded", index: filament.index, message: elsewhere
235
+ ? `“${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.`
236
+ : sliced && filament.material
237
+ ? `No ${filament.material} spool is loaded for “${partName(filament)}”, and this file was sliced for ${filament.material}. Load one, then try again.`
238
+ : "No filament is loaded. Load a spool in the AMS, then try again." });
239
+ return result(proposal);
240
+ }
241
+ chosen = matches.map(match => menu.find(tray => tray.slot === match!.slot)!);
242
+ }
243
+
244
+ const mapping = new Map(input.filaments.map((filament, i) => [filament.index, chosen[i]!.slot]));
245
+ const feed = chosen[0]!.feed;
246
+ const chosenSlots = new Set(chosen.map(tray => tray.slot));
247
+ const primary = live[0]?.feed;
248
+ // A painted slot follows the chosen feed: on the external spool(s) exactly those chosen; on the AMS any AMS spool.
249
+ const fillerPool = menu.filter(tray => feed === primary ? tray.feed === feed : chosenSlots.has(tray.slot));
250
+ for (const painted of input.painted ?? []) {
251
+ if (mapping.has(painted.index)) continue;
252
+ const [match] = matchColours([painted], fillerPool, { requireMaterial: sliced });
253
+ if (match) mapping.set(painted.index, match.slot);
254
+ else if (sliced && painted.material && painted.prints !== false)
255
+ 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.` });
256
+ else mapping.set(painted.index, chosen[0]!.slot);
257
+ }
258
+ return result(proposal, [...mapping.entries()].sort((a, b) => a[0] - b[0]).map(([index, slot]) => ({ index, slot })));
259
+ }
260
+
261
+ const colour = { type: "string", pattern: "^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$" };
262
+ export const PROPOSE_FILAMENTS_INPUT_PROPERTIES = {
263
+ filaments: {
264
+ type: "array", maxItems: 64,
265
+ 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.",
266
+ 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 },
267
+ },
268
+ painted: {
269
+ type: "array", maxItems: 64,
270
+ description: "Filament slots no part names (painted regions). Each follows the chosen spools' feed; prints false when the selected plate never uses it.",
271
+ items: { type: "object", properties: { index: { type: "integer", minimum: 1, maximum: 64 }, colour, material: { type: "string", maxLength: 64 }, prints: { type: "boolean" } }, required: ["index"], additionalProperties: false },
272
+ },
273
+ chosen: {
274
+ type: "array", maxItems: 64,
275
+ description: "The person's spool for each filament, in the same order: checked against what is loaded now. Omit for the proposal alone.",
276
+ 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 },
277
+ },
278
+ sliced: { type: "boolean", description: "The file is already sliced: its materials are fixed, so only spools of the same material qualify." },
279
+ } as const;
280
+
281
+ export const PROPOSE_FILAMENTS_OUTPUT_SCHEMA = {
282
+ type: "object" as const,
283
+ properties: {
284
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
285
+ trays: { type: "array", items: { type: "object", properties: {
286
+ slot: { type: "integer" }, label: { type: "string" }, name: { type: "string" }, colour: { type: "string" }, material: { type: "string" },
287
+ filamentId: { type: "string" }, feed: { type: "string" }, sliceable: { type: "boolean" }, profile: { type: "string" },
288
+ }, required: ["slot", "label", "name", "colour", "material", "filamentId", "feed", "sliceable"] } },
289
+ proposal: { type: "array", items: { type: "object", properties: {
290
+ index: { type: "integer" }, slot: { type: "integer" }, verdict: { type: "string", enum: ["same-colour", "closest", "no-colour", "none"] },
291
+ distance: { type: "number" }, materialMismatch: { type: "boolean" }, note: { type: "string" },
292
+ }, required: ["index", "verdict"] } },
293
+ mapping: { type: "array", items: { type: "object", properties: { index: { type: "integer" }, slot: { type: "integer" } }, required: ["index", "slot"] } },
294
+ problems: { type: "array", items: { type: "object", properties: { code: { type: "string" }, message: { type: "string" }, index: { type: "integer" } }, required: ["code", "message"] } },
295
+ },
296
+ required: ["contract", "trays", "proposal", "problems"],
297
+ };
@@ -0,0 +1,160 @@
1
+ /**
2
+ * How Counterpart's remote endpoint (`/v1/mcp`) offers each tool to a paired device, declared by this server so a
3
+ * new tool or argument needs no Counterpart release. Sent as each listed tool's `_meta["counterpart/remote"]`:
4
+ *
5
+ * - `scope`: the least device scope that may call the tool: read < design < control < print < raw. The table keeps
6
+ * the classes Counterpart gave these tools by hand before this version, so no paired device gained or lost a tool;
7
+ * `tests/tool-annotations.test.mjs` holds the name floors (a print start is at least print, a raw call raw).
8
+ * - `raisedBy`: boolean arguments that, when true, need a higher scope (`launch` starts Fusion).
9
+ * - `arguments`: argument names that are not plain values, matched at any depth of a call's arguments:
10
+ * `config`: this server's configuration chooses it (the printer it targets, its account, hardware and programs),
11
+ * so a device may not set it; `config-top`: the same, as a top-level argument only (`type`, the printer type);
12
+ * `path`: a local file or folder the tool reads; `output`: one it writes. Any other argument is a plain value.
13
+ * A tool that forwards an open object (an arbitrary RPC payload or another server's tool arguments) declares every
14
+ * configuration name, since any of them may appear inside it.
15
+ */
16
+ export type RemoteScope = "read" | "design" | "control" | "print" | "raw";
17
+ export type ArgumentKind = "config" | "config-top" | "path" | "output";
18
+ export interface RemoteDeclaration {
19
+ scope: RemoteScope;
20
+ raisedBy?: Record<string, RemoteScope>;
21
+ arguments?: Record<string, ArgumentKind>;
22
+ }
23
+ export const REMOTE_META_KEY = "counterpart/remote";
24
+
25
+ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
26
+ // read
27
+ counterpart_discover_printers: "read",
28
+ counterpart_setup_fields: "read",
29
+ counterpart_propose_filaments: "read",
30
+ get_printer_status: "read",
31
+ get_printer_filaments: "read",
32
+ resolve_3mf_ams_slots: "read",
33
+ list_3mf_plate_objects: "read",
34
+ get_stl_info: "read",
35
+ list_templates: "read",
36
+ list_printer_files: "read",
37
+ camera_frame: "read",
38
+ camera_snapshot: "read",
39
+ inspect_print_file: "read",
40
+ blender_mcp_status: "read",
41
+ counterpart_printer_info: "read",
42
+ counterpart_print_progress: "read",
43
+ fusion_mcp_status: "read",
44
+ // design
45
+ slice_stl: "design",
46
+ lay_flat: "design",
47
+ counterpart_make_3mf: "design",
48
+ // control
49
+ bambu_connect_import_file: "control",
50
+ camera_stream_start: "control",
51
+ camera_stream_stop: "control",
52
+ cancel_print: "control",
53
+ pause_print: "control",
54
+ resume_print: "control",
55
+ clear_hms_errors: "control",
56
+ set_print_speed: "control",
57
+ set_airduct_mode: "control",
58
+ reread_ams_rfid: "control",
59
+ set_temperature: "control",
60
+ set_fan_speed: "control",
61
+ set_light: "control",
62
+ set_ams_drying: "control",
63
+ counterpart_print_route: "control",
64
+ fusion_mcp_new_design: "control",
65
+ fusion_mcp_export: "control",
66
+ // print
67
+ extend_stl_base: "print",
68
+ scale_stl: "print",
69
+ rotate_stl: "print",
70
+ get_slice_settings: "print",
71
+ slice_with_template: "print",
72
+ bambu_network_bridge_status: "print",
73
+ print_3mf_bambu_network: "print",
74
+ delete_printer_file: "print",
75
+ upload_file: "print",
76
+ start_print: "print",
77
+ start_print_job: "print",
78
+ skip_objects: "print",
79
+ print_3mf: "print",
80
+ print_collar_charm: "print",
81
+ merge_vertices: "print",
82
+ center_model: "print",
83
+ // raw
84
+ save_template: "raw",
85
+ bambu_network_call: "raw",
86
+ upload_gcode: "raw",
87
+ x2d_native_control: "raw",
88
+ blender_mcp_call: "raw",
89
+ blender_mcp_edit_model: "raw",
90
+ fusion_mcp_call: "raw",
91
+ };
92
+
93
+ const RAISED_BY: Readonly<Record<string, Record<string, RemoteScope>>> = {
94
+ fusion_mcp_status: { launch: "design" }, // starts Fusion on this computer
95
+ blender_mcp_status: { connect: "design" }, // connects to Blender
96
+ };
97
+
98
+ /**
99
+ * Overrides of a server's own configuration (both printer MCPs use the same names): the printer it targets, its
100
+ * account and credentials, its hardware, and the programs it runs.
101
+ */
102
+ export const CONFIG_ARGUMENTS: ReadonlySet<string> = new Set([
103
+ "host", "port", "api_key", "username", "password", "dev_ip", "dev_id", "bambu_serial", "bambu_token", "user_info",
104
+ "country_code", "connection_type", "connection_mode", "route", "bambu_model", "nozzle_diameter", "nozzle_diameters",
105
+ "bridge_command", "slicer_path", "slicer_type", "ffmpeg_path", "plugin_dir", "runtime_dir", "template_dir",
106
+ "config_filename", "bambu_network_method", "use_ssl_for_mqtt", "use_ssl_for_ftp", "extra_options",
107
+ "allow_mutating_method",
108
+ ]);
109
+ /** Top-level only: the printer type (`type`); a nested `type` is a plain value. */
110
+ const TOP_LEVEL_CONFIG: ReadonlySet<string> = new Set(["type"]);
111
+ /** Files read whose names don't end in path, dir or file. */
112
+ const FILE_ARGUMENTS: ReadonlySet<string> = new Set(["filament_profile", "slicer_profile", "load_filaments", "source_f3d"]);
113
+
114
+ const isPath = (key: string) => /(?:path|dir|directory|_file)$/.test(key) || FILE_ARGUMENTS.has(key);
115
+
116
+ function kindOf(tool: string, key: string, depth: number): ArgumentKind | undefined {
117
+ // counterpart_print_route's own `route` is the connection the caller chooses.
118
+ if ((CONFIG_ARGUMENTS.has(key) && !(key === "route" && tool === "counterpart_print_route")) || /config_dir$/.test(key)) return "config";
119
+ if (depth === 0 && TOP_LEVEL_CONFIG.has(key)) return "config-top";
120
+ if (!isPath(key)) return undefined;
121
+ return /^output_|^out_path$|^save_path$/.test(key) ? "output" : "path";
122
+ }
123
+
124
+ /** The argument kinds of one tool, read from its own input schema. */
125
+ export function remoteArguments(tool: { name: string; inputSchema?: unknown }): Record<string, ArgumentKind> {
126
+ const kinds: Record<string, ArgumentKind> = {};
127
+ let open = false;
128
+ const visit = (schema: unknown, depth: number): void => {
129
+ if (!schema || typeof schema !== "object") return;
130
+ const node = schema as { type?: unknown; properties?: Record<string, unknown>; additionalProperties?: unknown; items?: unknown; anyOf?: unknown[]; oneOf?: unknown[] };
131
+ // An object whose keys the schema doesn't name (beyond the top level) may carry any argument.
132
+ if (depth > 0 && node.type === "object" && (node.additionalProperties === true || node.additionalProperties === undefined && !node.properties)) open = true;
133
+ if (depth > 0 && node.additionalProperties && typeof node.additionalProperties === "object") open = true;
134
+ for (const [key, child] of Object.entries(node.properties ?? {})) {
135
+ const kind = kindOf(tool.name, key, depth);
136
+ if (kind && !(kinds[key] === "config" && kind === "config-top")) kinds[key] = kind;
137
+ visit(child, depth + 1);
138
+ }
139
+ visit(node.items, depth);
140
+ for (const option of [...(node.anyOf ?? []), ...(node.oneOf ?? [])]) visit(option, depth);
141
+ };
142
+ visit(tool.inputSchema, 0);
143
+ if (open) for (const key of CONFIG_ARGUMENTS) if (!(key === "route" && tool.name === "counterpart_print_route")) kinds[key] ??= "config";
144
+ return kinds;
145
+ }
146
+
147
+ /** The declaration for one tool; a tool missing from REMOTE_SCOPES (a bug the tests catch) is raw. */
148
+ export function remoteDeclaration(tool: { name: string; inputSchema?: unknown }): RemoteDeclaration {
149
+ const args = remoteArguments(tool);
150
+ return {
151
+ scope: REMOTE_SCOPES[tool.name] ?? "raw",
152
+ ...(RAISED_BY[tool.name] ? { raisedBy: RAISED_BY[tool.name] } : {}),
153
+ ...(Object.keys(args).length ? { arguments: args } : {}),
154
+ };
155
+ }
156
+
157
+ /** The tool with its declaration in `_meta`. */
158
+ export function withRemote<T extends { name: string; inputSchema?: unknown; _meta?: Record<string, unknown> }>(tool: T): T & { _meta: Record<string, unknown> } {
159
+ return { ...tool, _meta: { ...(tool._meta ?? {}), [REMOTE_META_KEY]: remoteDeclaration(tool) } };
160
+ }
@@ -0,0 +1,127 @@
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
+
10
+ export const SETUP_FIELD_NAMES = ["host", "port", "serial", "model", "secret", "slicer", "slicer-path", "profiles"] as const;
11
+ export type SetupField = {
12
+ /** The client's form field this is: an address, a port, a serial number, a model choice or a secret. */
13
+ name: typeof SETUP_FIELD_NAMES[number];
14
+ /** The variable to write. */
15
+ env: string;
16
+ /** Older names for it that this server reads before `env`: a client writing `env` removes these lines, or the old value wins. */
17
+ aliases?: string[];
18
+ label: string; hint?: string; required: boolean;
19
+ /** A path on this computer (a slicer app, a profiles folder): a client may offer a file chooser. */
20
+ input?: "path";
21
+ /** Written as typed, or upper-cased (Bambu serial numbers). */
22
+ transform?: "uppercase";
23
+ choices?: Array<{ value: string; label: string }>;
24
+ /** A model field: the model a serial number names, by its first `prefixLength` characters. */
25
+ fromSerial?: { prefixLength: number; models: Record<string, string> };
26
+ };
27
+ export type SetupKind = {
28
+ kind: typeof PRINTER_KINDS[number]; label: string;
29
+ /** Values this server needs for the kind whatever the person enters (MCP_TRANSPORT, PRINTER_TYPE). */
30
+ env: Record<string, string>;
31
+ fields: SetupField[];
32
+ };
33
+ /** The slicer this server runs, as it resolves it now, and the settings that choose it (for every printer). */
34
+ export type SlicerSetup = {
35
+ type: string;
36
+ /** The slicer app it would run, and whether that app is there. */
37
+ path?: string; found: boolean;
38
+ /** The Bambu profiles folder it would read (Bambu Studio and Orca), and whether it has BBL's profiles. */
39
+ profilesRoot?: string; profilesFound?: boolean;
40
+ fields: SetupField[];
41
+ };
42
+ export type SetupFields = { contract: typeof COUNTERPART_CONTRACT; server: { name: string; version: string }; kinds: SetupKind[]; model?: string; slicer?: SlicerSetup };
43
+
44
+ const SLICER_LABELS: Record<string, string> = {
45
+ bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "OrcaSlicer-bambulab (FULU)", "orca-slicer-api": "OrcaSlicer API (remote)",
46
+ prusaslicer: "PrusaSlicer", cura: "Cura", slic3r: "Slic3r",
47
+ };
48
+ /**
49
+ * The slicer settings, with what this server resolves now: a client shows "Bambu Studio isn't installed" or asks for
50
+ * its location instead of the person editing SLICER_PATH by hand. A setting is required only when what it would
51
+ * default to isn't there.
52
+ */
53
+ export function slicerSetup(options: { types: readonly string[]; type: string; path?: string; found: boolean; profilesRoot?: string; profilesFound?: boolean; remote?: boolean }): SlicerSetup {
54
+ const label = SLICER_LABELS[options.type] ?? options.type;
55
+ const fields: SetupField[] = [
56
+ { name: "slicer", env: "SLICER_TYPE", label: "Slicer", required: false, choices: options.types.map(value => ({ value, label: SLICER_LABELS[value] ?? value })) },
57
+ ];
58
+ if (!options.remote) fields.push({ name: "slicer-path", env: "SLICER_PATH", label: `${label} app`, input: "path", required: !options.found,
59
+ hint: options.found ? `Found at ${options.path}. Set this only to use another copy.`
60
+ : options.path ? `${label} isn't at ${options.path}. Install it, or choose where it is.` : `Where ${label} is installed.` });
61
+ if (options.profilesFound !== undefined) fields.push({ name: "profiles", env: "BAMBU_PROFILES_ROOT", label: "Bambu profiles folder", input: "path", required: !options.profilesFound,
62
+ 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.` });
63
+ return { type: options.type, ...(options.path !== undefined ? { path: options.path } : {}), found: options.found,
64
+ ...(options.profilesRoot !== undefined ? { profilesRoot: options.profilesRoot } : {}), ...(options.profilesFound !== undefined ? { profilesFound: options.profilesFound } : {}), fields };
65
+ }
66
+
67
+ /** Each serial prefix's model in this server's values (bambu_model), where it has one. */
68
+ export function serialModelValues(valid: readonly string[]): Record<string, string> {
69
+ return Object.fromEntries(Object.entries(SERIAL_MODELS).flatMap(([prefix, name]) => {
70
+ const model = normalizeModel(name);
71
+ return model && valid.includes(model) ? [[prefix, model]] : [];
72
+ }));
73
+ }
74
+
75
+ /** Bambu's display names for this server's model values ("a1mini" → "A1 Mini"). */
76
+ export function modelChoices(valid: readonly string[]): Array<{ value: string; label: string }> {
77
+ const names = new Map(Object.values(SERIAL_MODELS).map(name => [normalizeModel(name), name]));
78
+ return valid.map(value => ({ value, label: names.get(value) ?? value.toUpperCase() }));
79
+ }
80
+
81
+ export function bambuSetupFields(options: { server: { name: string; version: string }; models: readonly string[]; serial?: string; slicer?: SlicerSetup }): SetupFields {
82
+ const fromSerial = { prefixLength: 3, models: serialModelValues(options.models) };
83
+ const model = options.serial ? fromSerial.models[options.serial.trim().slice(0, 3).toUpperCase()] : undefined;
84
+ return {
85
+ contract: COUNTERPART_CONTRACT,
86
+ server: options.server,
87
+ kinds: [{
88
+ kind: "bambu", label: "Bambu Lab", env: { MCP_TRANSPORT: "stdio" },
89
+ fields: [
90
+ { name: "host", env: "PRINTER_HOST", aliases: ["BAMBU_PRINTER_HOST"], label: "Address", hint: "The printer's IP address: on the printer, Settings → WLAN", required: true },
91
+ { name: "serial", env: "BAMBU_SERIAL", aliases: ["BAMBU_PRINTER_SERIAL"], label: "Serial number", hint: "On the printer: Settings → Device", required: true, transform: "uppercase" },
92
+ { name: "model", env: "BAMBU_MODEL", aliases: ["BAMBU_PRINTER_MODEL"], label: "Model", required: true, choices: modelChoices(options.models), fromSerial },
93
+ { name: "secret", env: "BAMBU_TOKEN", aliases: ["BAMBU_PRINTER_ACCESS_TOKEN"], label: "Access code", hint: "On the printer: Settings → WLAN → Access Code", required: true },
94
+ ],
95
+ }],
96
+ ...(model ? { model } : {}),
97
+ ...(options.slicer ? { slicer: options.slicer } : {}),
98
+ };
99
+ }
100
+
101
+ const field = {
102
+ type: "object",
103
+ properties: {
104
+ 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." },
105
+ label: { type: "string" }, hint: { type: "string" }, required: { type: "boolean" }, input: { type: "string", enum: ["path"] }, transform: { type: "string", enum: ["uppercase"] },
106
+ choices: { type: "array", items: { type: "object", properties: { value: { type: "string" }, label: { type: "string" } }, required: ["value", "label"] } },
107
+ fromSerial: { type: "object", properties: { prefixLength: { type: "integer" }, models: { type: "object", additionalProperties: { type: "string" } } }, required: ["prefixLength", "models"] },
108
+ },
109
+ required: ["name", "env", "label", "required"],
110
+ };
111
+ export const SETUP_FIELDS_OUTPUT_SCHEMA = {
112
+ type: "object" as const,
113
+ properties: {
114
+ contract: { type: "string", const: COUNTERPART_CONTRACT },
115
+ server: { type: "object", properties: { name: { type: "string" }, version: { type: "string" } }, required: ["name", "version"] },
116
+ kinds: { type: "array", items: { type: "object", properties: {
117
+ kind: { type: "string", enum: [...PRINTER_KINDS] }, label: { type: "string" },
118
+ env: { type: "object", additionalProperties: { type: "string" } }, fields: { type: "array", items: field },
119
+ }, required: ["kind", "label", "env", "fields"] } },
120
+ model: { type: "string" },
121
+ slicer: { type: "object", properties: {
122
+ type: { type: "string" }, path: { type: "string" }, found: { type: "boolean" }, profilesRoot: { type: "string" }, profilesFound: { type: "boolean" },
123
+ fields: { type: "array", items: field },
124
+ }, required: ["type", "found", "fields"] },
125
+ },
126
+ required: ["contract", "server", "kinds"],
127
+ };