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,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,47 @@
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 declare const REMOTE_META_KEY = "counterpart/remote";
24
+ export declare const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>>;
25
+ /**
26
+ * Overrides of a server's own configuration (both printer MCPs use the same names): the printer it targets, its
27
+ * account and credentials, its hardware, and the programs it runs.
28
+ */
29
+ export declare const CONFIG_ARGUMENTS: ReadonlySet<string>;
30
+ /** The argument kinds of one tool, read from its own input schema. */
31
+ export declare function remoteArguments(tool: {
32
+ name: string;
33
+ inputSchema?: unknown;
34
+ }): Record<string, ArgumentKind>;
35
+ /** The declaration for one tool; a tool missing from REMOTE_SCOPES (a bug the tests catch) is raw. */
36
+ export declare function remoteDeclaration(tool: {
37
+ name: string;
38
+ inputSchema?: unknown;
39
+ }): RemoteDeclaration;
40
+ /** The tool with its declaration in `_meta`. */
41
+ export declare function withRemote<T extends {
42
+ name: string;
43
+ inputSchema?: unknown;
44
+ _meta?: Record<string, unknown>;
45
+ }>(tool: T): T & {
46
+ _meta: Record<string, unknown>;
47
+ };
@@ -0,0 +1,141 @@
1
+ export const REMOTE_META_KEY = "counterpart/remote";
2
+ export const REMOTE_SCOPES = {
3
+ // read
4
+ counterpart_discover_printers: "read",
5
+ counterpart_setup_fields: "read",
6
+ counterpart_propose_filaments: "read",
7
+ get_printer_status: "read",
8
+ get_printer_filaments: "read",
9
+ resolve_3mf_ams_slots: "read",
10
+ list_3mf_plate_objects: "read",
11
+ get_stl_info: "read",
12
+ list_templates: "read",
13
+ list_printer_files: "read",
14
+ camera_frame: "read",
15
+ camera_snapshot: "read",
16
+ inspect_print_file: "read",
17
+ blender_mcp_status: "read",
18
+ counterpart_printer_info: "read",
19
+ counterpart_print_progress: "read",
20
+ fusion_mcp_status: "read",
21
+ // design
22
+ slice_stl: "design",
23
+ lay_flat: "design",
24
+ counterpart_make_3mf: "design",
25
+ // control
26
+ bambu_connect_import_file: "control",
27
+ camera_stream_start: "control",
28
+ camera_stream_stop: "control",
29
+ cancel_print: "control",
30
+ pause_print: "control",
31
+ resume_print: "control",
32
+ clear_hms_errors: "control",
33
+ set_print_speed: "control",
34
+ set_airduct_mode: "control",
35
+ reread_ams_rfid: "control",
36
+ set_temperature: "control",
37
+ set_fan_speed: "control",
38
+ set_light: "control",
39
+ set_ams_drying: "control",
40
+ counterpart_print_route: "control",
41
+ fusion_mcp_new_design: "control",
42
+ fusion_mcp_export: "control",
43
+ // print
44
+ extend_stl_base: "print",
45
+ scale_stl: "print",
46
+ rotate_stl: "print",
47
+ get_slice_settings: "print",
48
+ slice_with_template: "print",
49
+ bambu_network_bridge_status: "print",
50
+ print_3mf_bambu_network: "print",
51
+ delete_printer_file: "print",
52
+ upload_file: "print",
53
+ start_print: "print",
54
+ start_print_job: "print",
55
+ skip_objects: "print",
56
+ print_3mf: "print",
57
+ print_collar_charm: "print",
58
+ merge_vertices: "print",
59
+ center_model: "print",
60
+ // raw
61
+ save_template: "raw",
62
+ bambu_network_call: "raw",
63
+ upload_gcode: "raw",
64
+ x2d_native_control: "raw",
65
+ blender_mcp_call: "raw",
66
+ blender_mcp_edit_model: "raw",
67
+ fusion_mcp_call: "raw",
68
+ };
69
+ const RAISED_BY = {
70
+ fusion_mcp_status: { launch: "design" }, // starts Fusion on this computer
71
+ blender_mcp_status: { connect: "design" }, // connects to Blender
72
+ };
73
+ /**
74
+ * Overrides of a server's own configuration (both printer MCPs use the same names): the printer it targets, its
75
+ * account and credentials, its hardware, and the programs it runs.
76
+ */
77
+ export const CONFIG_ARGUMENTS = new Set([
78
+ "host", "port", "api_key", "username", "password", "dev_ip", "dev_id", "bambu_serial", "bambu_token", "user_info",
79
+ "country_code", "connection_type", "connection_mode", "route", "bambu_model", "nozzle_diameter", "nozzle_diameters",
80
+ "bridge_command", "slicer_path", "slicer_type", "ffmpeg_path", "plugin_dir", "runtime_dir", "template_dir",
81
+ "config_filename", "bambu_network_method", "use_ssl_for_mqtt", "use_ssl_for_ftp", "extra_options",
82
+ "allow_mutating_method",
83
+ ]);
84
+ /** Top-level only: the printer type (`type`); a nested `type` is a plain value. */
85
+ const TOP_LEVEL_CONFIG = new Set(["type"]);
86
+ /** Files read whose names don't end in path, dir or file. */
87
+ const FILE_ARGUMENTS = new Set(["filament_profile", "slicer_profile", "load_filaments", "source_f3d"]);
88
+ const isPath = (key) => /(?:path|dir|directory|_file)$/.test(key) || FILE_ARGUMENTS.has(key);
89
+ function kindOf(tool, key, depth) {
90
+ // counterpart_print_route's own `route` is the connection the caller chooses.
91
+ if ((CONFIG_ARGUMENTS.has(key) && !(key === "route" && tool === "counterpart_print_route")) || /config_dir$/.test(key))
92
+ return "config";
93
+ if (depth === 0 && TOP_LEVEL_CONFIG.has(key))
94
+ return "config-top";
95
+ if (!isPath(key))
96
+ return undefined;
97
+ return /^output_|^out_path$|^save_path$/.test(key) ? "output" : "path";
98
+ }
99
+ /** The argument kinds of one tool, read from its own input schema. */
100
+ export function remoteArguments(tool) {
101
+ const kinds = {};
102
+ let open = false;
103
+ const visit = (schema, depth) => {
104
+ if (!schema || typeof schema !== "object")
105
+ return;
106
+ const node = schema;
107
+ // An object whose keys the schema doesn't name (beyond the top level) may carry any argument.
108
+ if (depth > 0 && node.type === "object" && (node.additionalProperties === true || node.additionalProperties === undefined && !node.properties))
109
+ open = true;
110
+ if (depth > 0 && node.additionalProperties && typeof node.additionalProperties === "object")
111
+ open = true;
112
+ for (const [key, child] of Object.entries(node.properties ?? {})) {
113
+ const kind = kindOf(tool.name, key, depth);
114
+ if (kind && !(kinds[key] === "config" && kind === "config-top"))
115
+ kinds[key] = kind;
116
+ visit(child, depth + 1);
117
+ }
118
+ visit(node.items, depth);
119
+ for (const option of [...(node.anyOf ?? []), ...(node.oneOf ?? [])])
120
+ visit(option, depth);
121
+ };
122
+ visit(tool.inputSchema, 0);
123
+ if (open)
124
+ for (const key of CONFIG_ARGUMENTS)
125
+ if (!(key === "route" && tool.name === "counterpart_print_route"))
126
+ kinds[key] ?? (kinds[key] = "config");
127
+ return kinds;
128
+ }
129
+ /** The declaration for one tool; a tool missing from REMOTE_SCOPES (a bug the tests catch) is raw. */
130
+ export function remoteDeclaration(tool) {
131
+ const args = remoteArguments(tool);
132
+ return {
133
+ scope: REMOTE_SCOPES[tool.name] ?? "raw",
134
+ ...(RAISED_BY[tool.name] ? { raisedBy: RAISED_BY[tool.name] } : {}),
135
+ ...(Object.keys(args).length ? { arguments: args } : {}),
136
+ };
137
+ }
138
+ /** The tool with its declaration in `_meta`. */
139
+ export function withRemote(tool) {
140
+ return { ...tool, _meta: { ...(tool._meta ?? {}), [REMOTE_META_KEY]: remoteDeclaration(tool) } };
141
+ }