bambu-printer-mcp 1.1.46 → 1.1.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +117 -3
  2. package/dist/blender-mcp-bridge.d.ts +15 -0
  3. package/dist/blender-mcp-bridge.js +21 -3
  4. package/dist/counterpart/info.d.ts +10 -0
  5. package/dist/counterpart/info.js +34 -0
  6. package/dist/counterpart/make-3mf.d.ts +16 -0
  7. package/dist/counterpart/make-3mf.js +219 -0
  8. package/dist/counterpart/progress.d.ts +28 -0
  9. package/dist/counterpart/progress.js +254 -0
  10. package/dist/counterpart/schemas.d.ts +322 -0
  11. package/dist/counterpart/schemas.js +124 -0
  12. package/dist/fusion-mcp-bridge.d.ts +182 -0
  13. package/dist/fusion-mcp-bridge.js +557 -0
  14. package/dist/index.js +197 -17
  15. package/dist/printers/bambu-stages.d.ts +7 -0
  16. package/dist/printers/bambu-stages.js +89 -0
  17. package/dist/printers/bambu.d.ts +79 -8
  18. package/dist/printers/bambu.js +311 -56
  19. package/dist/printers/camera-models.d.ts +7 -0
  20. package/dist/printers/camera-models.js +18 -0
  21. package/dist/safety/hms-messages.d.ts +42 -0
  22. package/dist/safety/hms-messages.js +6194 -0
  23. package/dist/safety/printer-state.d.ts +20 -2
  24. package/dist/safety/printer-state.js +5 -5
  25. package/dist/slicer/process-overrides.d.ts +12 -0
  26. package/dist/slicer/process-overrides.js +33 -0
  27. package/dist/slicer/remote-slicer.js +2 -0
  28. package/dist/stl/stl-manipulator.d.ts +2 -0
  29. package/dist/stl/stl-manipulator.js +19 -0
  30. package/package.json +1 -1
  31. package/src/blender-mcp-bridge.ts +22 -3
  32. package/src/counterpart/info.ts +36 -0
  33. package/src/counterpart/make-3mf.ts +220 -0
  34. package/src/counterpart/progress.ts +254 -0
  35. package/src/counterpart/schemas.ts +154 -0
  36. package/src/fusion-mcp-bridge.ts +545 -0
  37. package/src/index.ts +204 -17
  38. package/src/printers/bambu-stages.ts +90 -0
  39. package/src/printers/bambu.ts +329 -56
  40. package/src/printers/camera-models.ts +18 -0
  41. package/src/safety/hms-messages.ts +6198 -0
  42. package/src/safety/printer-state.ts +6 -6
  43. package/src/slicer/process-overrides.ts +42 -0
  44. package/src/slicer/remote-slicer.ts +2 -0
  45. package/src/stl/stl-manipulator.ts +22 -0
@@ -0,0 +1,557 @@
1
+ /**
2
+ * Autodesk Fusion through faust-machines/fusion360-mcp-server (PRD §8.9).
3
+ *
4
+ * MCP client (this) ─stdio─▶ fusion360-mcp-server ─TCP localhost:9877─▶ the
5
+ * Fusion360MCP add-in ─▶ Fusion's main thread. Configured like Blender, with
6
+ * trusted FUSION_MCP_COMMAND / FUSION_MCP_ARGS, but the stdio session is kept
7
+ * for the life of this server, because a design pass makes many calls and each
8
+ * new uvx process would reconnect to the add-in. A timeout, cancellation or
9
+ * transport failure closes the session; the next call starts a new one.
10
+ * Requests are never replayed.
11
+ */
12
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
13
+ import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
14
+ import { AjvJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/ajv";
15
+ import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";
16
+ import { execFile } from "node:child_process";
17
+ import { randomUUID } from "node:crypto";
18
+ import fs from "node:fs/promises";
19
+ import net from "node:net";
20
+ import path from "node:path";
21
+ import { promisify } from "node:util";
22
+ import { stlMetadata } from "./blender-mcp-bridge.js";
23
+ const execFileAsync = promisify(execFile);
24
+ /** The faust-machines commit the setup installs; move it only after the PRD §8.9 acceptance check passes. */
25
+ export const FUSION_MCP_PIN = "19b9f1e95192";
26
+ /** PRD §8.9: Blender's MCP add-on holds the add-in's own default, 9876, so Counterpart's Fusion uses 9877. */
27
+ export const FUSION_ADDIN_DEFAULT_PORT = 9877;
28
+ export const FUSION_MCP_DEFAULT_ARGS = Object.freeze([
29
+ "--from", `git+https://github.com/faust-machines/fusion360-mcp-server@${FUSION_MCP_PIN}`,
30
+ "fusion360-mcp-server", "--mode", "socket",
31
+ ]);
32
+ const DEFAULT_TIMEOUT_MS = 180000;
33
+ const MAX_TIMEOUT_MS = 600000;
34
+ const LAUNCH_WAIT_MS = 90000;
35
+ const ADDIN_PING_MS = 2000;
36
+ const EXPORT_NAME = /^[A-Za-z0-9][A-Za-z0-9._ -]{0,99}$/;
37
+ /** Faust's add-in refuses every command, execute_code included, until a design is open (faust issue #12). */
38
+ const NO_DESIGN = /NO_ACTIVE_DESIGN|No active design/;
39
+ class FusionError extends Error {
40
+ }
41
+ /**
42
+ * The add-in reads FUSION_MCP_PORT from Fusion's environment at the pin
43
+ * (addon/Fusion360MCP.py), and an app started from the Dock gets no shell
44
+ * environment, so the launch passes the port the bridge probes. `open --env`
45
+ * applies only when it starts the app, which is the only time this runs.
46
+ */
47
+ export function fusionLaunchArguments(port) {
48
+ return ["-a", "Autodesk Fusion", "--env", `FUSION_MCP_PORT=${port}`];
49
+ }
50
+ export const defaultFusionSystem = {
51
+ platform: process.platform,
52
+ /**
53
+ * An open port is not enough: Blender's MCP add-on defaults to
54
+ * localhost:9876, the add-in's own default. The add-in speaks newline-delimited JSON
55
+ * (addon/server/socket_server.py) and answers {"type":"ping"} with
56
+ * {"status":"success","result":{"pong":true}} without touching Fusion's API;
57
+ * Blender's add-on answers an unknown command with an error.
58
+ */
59
+ addinAnswers: (host, port, timeoutMs) => new Promise(resolve => {
60
+ const socket = net.connect({ host, port });
61
+ let buffer = "";
62
+ let settled = false;
63
+ const done = (answers) => {
64
+ if (settled)
65
+ return;
66
+ settled = true;
67
+ clearTimeout(deadline);
68
+ socket.destroy();
69
+ resolve(answers);
70
+ };
71
+ const deadline = setTimeout(() => done(false), timeoutMs);
72
+ socket.setEncoding("utf8");
73
+ socket.once("connect", () => socket.write(`${JSON.stringify({ type: "ping", params: {} })}\n`));
74
+ socket.on("data", (chunk) => {
75
+ buffer += chunk;
76
+ if (buffer.length > 65536)
77
+ return done(false);
78
+ const newline = buffer.indexOf("\n");
79
+ try {
80
+ const reply = JSON.parse(newline >= 0 ? buffer.slice(0, newline) : buffer);
81
+ done(reply?.status === "success" && reply?.result?.pong === true);
82
+ }
83
+ catch {
84
+ if (newline >= 0)
85
+ done(false);
86
+ }
87
+ });
88
+ socket.once("error", () => done(false));
89
+ socket.once("close", () => done(false));
90
+ }),
91
+ fusionRunning: async () => {
92
+ if (process.platform !== "darwin")
93
+ return false;
94
+ try {
95
+ await execFileAsync("pgrep", ["-f", "Autodesk Fusion[^/]*\\.app/Contents/MacOS/"], { timeout: 5000 });
96
+ return true;
97
+ }
98
+ catch {
99
+ return false;
100
+ }
101
+ },
102
+ launch: async (port) => { await execFileAsync("open", fusionLaunchArguments(port), { timeout: 30000 }); },
103
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
104
+ launchWaitMs: LAUNCH_WAIT_MS,
105
+ };
106
+ function argumentObject(value, label) {
107
+ if (!value || typeof value !== "object" || Array.isArray(value))
108
+ throw new FusionError(`${label} must be an object.`);
109
+ return value;
110
+ }
111
+ function allowedArguments(args, names) {
112
+ if (Object.keys(args).some(name => !names.includes(name))) {
113
+ throw new FusionError("Unknown Fusion argument. Executables and their arguments must be configured on the server with FUSION_MCP_COMMAND and FUSION_MCP_ARGS.");
114
+ }
115
+ }
116
+ function textArgument(value, label) {
117
+ if (typeof value !== "string" || !value.trim() || value.includes("\0"))
118
+ throw new FusionError(`${label} must be a non-empty string without NUL characters.`);
119
+ return value;
120
+ }
121
+ function timeoutMilliseconds(value) {
122
+ const timeout = value ?? (process.env.FUSION_MCP_TIMEOUT_MS ? Number(process.env.FUSION_MCP_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS);
123
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < 100 || timeout > MAX_TIMEOUT_MS) {
124
+ throw new FusionError(`timeout_ms / FUSION_MCP_TIMEOUT_MS must be an integer from 100 to ${MAX_TIMEOUT_MS}.`);
125
+ }
126
+ return timeout;
127
+ }
128
+ function configuration() {
129
+ const command = process.env.FUSION_MCP_COMMAND?.trim();
130
+ if (!command)
131
+ throw new FusionError(`No Fusion MCP server configured. Set FUSION_MCP_COMMAND to uvx and FUSION_MCP_ARGS to ${JSON.stringify(FUSION_MCP_DEFAULT_ARGS)}, and run the Fusion360MCP add-in in Fusion.`);
132
+ if (command.includes("\0"))
133
+ throw new FusionError("FUSION_MCP_COMMAND must be an executable without NUL characters.");
134
+ const raw = process.env.FUSION_MCP_ARGS?.trim();
135
+ if (!raw)
136
+ return { command, args: [...FUSION_MCP_DEFAULT_ARGS] };
137
+ let args;
138
+ try {
139
+ args = JSON.parse(raw);
140
+ }
141
+ catch {
142
+ throw new FusionError("FUSION_MCP_ARGS must be a JSON array of strings, not a shell command.");
143
+ }
144
+ if (!Array.isArray(args) || args.some(arg => typeof arg !== "string" || arg.includes("\0"))) {
145
+ throw new FusionError("FUSION_MCP_ARGS must be a JSON array of strings without NUL characters.");
146
+ }
147
+ return { command, args };
148
+ }
149
+ /** Where the add-in listens: faust reads FUSION_MCP_HOST and FUSION_MCP_PORT too. */
150
+ function addinAddress() {
151
+ const host = process.env.FUSION_MCP_HOST?.trim() || "localhost";
152
+ const port = Number(process.env.FUSION_MCP_PORT?.trim() || FUSION_ADDIN_DEFAULT_PORT);
153
+ return { host, port: Number.isInteger(port) && port > 0 && port < 65536 ? port : FUSION_ADDIN_DEFAULT_PORT };
154
+ }
155
+ function fusionEnvironment() {
156
+ // Fusion needs its own settings, never printer access codes or other server secrets.
157
+ const env = getDefaultEnvironment();
158
+ for (const [key, value] of Object.entries(process.env)) {
159
+ if (key.startsWith("FUSION_") && value !== undefined && key !== "FUSION_MCP_COMMAND" && key !== "FUSION_MCP_ARGS")
160
+ env[key] = value;
161
+ }
162
+ // faust defaults to 9876 (src/fusion360_mcp/connection.py), so it is told the port this bridge probes and launches with.
163
+ env.FUSION_MCP_PORT = String(addinAddress().port);
164
+ return env;
165
+ }
166
+ function resultText(result) {
167
+ return result.content.filter(entry => entry.type === "text").map(entry => entry.text).join("\n");
168
+ }
169
+ /** Faust reports failures with isError and a "**tool** ERROR (KIND)" heading. */
170
+ function failed(result, name) {
171
+ return result.isError === true || resultText(result).trimStart().startsWith(`**${name}** ERROR`);
172
+ }
173
+ /** The value of one " key: value" line in faust's text result. */
174
+ function resultField(result, key) {
175
+ for (const line of resultText(result).split("\n")) {
176
+ if (line.startsWith(` ${key}: `))
177
+ return line.slice(key.length + 4);
178
+ }
179
+ return undefined;
180
+ }
181
+ /** execute_code's value when the code's last expression is json.dumps(...). */
182
+ function codeJson(result) {
183
+ const value = resultField(result, "result");
184
+ try {
185
+ return JSON.parse(value ?? "");
186
+ }
187
+ catch {
188
+ throw new FusionError("Fusion returned an unreadable execute_code result.");
189
+ }
190
+ }
191
+ const NEW_DESIGN_CODE = `# BAMBU_FUSION new_design
192
+ import json
193
+ doc = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
194
+ new_design = adsk.fusion.Design.cast(doc.products.itemByProductType("DesignProductType"))
195
+ new_design.designType = adsk.fusion.DesignTypes.ParametricDesignType
196
+ json.dumps({"document": doc.name, "parametric": new_design.designType == adsk.fusion.DesignTypes.ParametricDesignType})`;
197
+ // The bodies export_stl looks a name up in, in its order (faust _body_by_name: root
198
+ // bodies, then every occurrence's proxies), with bounding boxes in Fusion's centimetres.
199
+ const BODIES_CODE = `# BAMBU_FUSION bodies
200
+ import json
201
+ json.dumps([{"name": b.name, "solid": b.isSolid, "visible": b.isVisible, "size_cm": [bb.maxPoint.x - bb.minPoint.x, bb.maxPoint.y - bb.minPoint.y, bb.maxPoint.z - bb.minPoint.z]} for b in list(component.bRepBodies) + [p for o in component.allOccurrences for p in o.bRepBodies] for bb in [b.boundingBox]])`;
202
+ function fusionBodies(value) {
203
+ if (!Array.isArray(value))
204
+ throw new FusionError("Fusion returned an unreadable body list.");
205
+ return value.map((entry) => {
206
+ const size = entry?.size_cm;
207
+ if (typeof entry?.name !== "string" || !Array.isArray(size) || size.length !== 3 || size.some((part) => typeof part !== "number" || !Number.isFinite(part) || part < 0)) {
208
+ throw new FusionError("Fusion returned an unreadable body list.");
209
+ }
210
+ return { name: entry.name, solid: entry.solid === true, visible: entry.visible === true, size_cm: size };
211
+ });
212
+ }
213
+ // The fields faust's get_parameters reports, as JSON instead of its Python-repr text.
214
+ const PARAMETERS_CODE = `# BAMBU_FUSION parameters
215
+ import json
216
+ json.dumps({"parameters": [{"name": p.name, "value": p.value, "expression": p.expression, "unit": p.unit, "comment": p.comment} for p in design.userParameters], "count": design.userParameters.count})`;
217
+ export const FUSION_STATUS_OUTPUT_SCHEMA = {
218
+ type: "object",
219
+ properties: {
220
+ configured: { type: "boolean", description: "FUSION_MCP_COMMAND is set." },
221
+ connected: { type: "boolean", description: "The Fusion MCP server started and the add-in answered its ping." },
222
+ addinReachable: { type: "boolean", description: "The Fusion360MCP add-in answered a ping on FUSION_MCP_HOST:FUSION_MCP_PORT (default localhost:9877) within 2 s. Another program on that port, such as Blender's MCP add-on, does not count." },
223
+ fusionRunning: { type: "boolean" },
224
+ tools: { type: "array", items: { type: "object", properties: { name: { type: "string" } }, required: ["name"] } },
225
+ launched: { type: "boolean", description: "This call started Fusion." },
226
+ transport: { type: "string" },
227
+ pin: { type: "string", description: "The faust-machines/fusion360-mcp-server commit this bridge is set up for." },
228
+ server: { type: "object" },
229
+ error: { type: "string" },
230
+ },
231
+ required: ["configured", "connected", "addinReachable", "fusionRunning", "tools"],
232
+ };
233
+ /** fusion_mcp_call passes the remote result through: its structuredContent, else an empty object. */
234
+ export const FUSION_CALL_OUTPUT_SCHEMA = { type: "object" };
235
+ export const FUSION_NEW_DESIGN_OUTPUT_SCHEMA = {
236
+ type: "object",
237
+ properties: {
238
+ status: { type: "string", const: "created" },
239
+ document: { type: "string" },
240
+ parametric: { type: "boolean" },
241
+ },
242
+ required: ["status", "document", "parametric"],
243
+ };
244
+ export const FUSION_EXPORT_OUTPUT_SCHEMA = {
245
+ type: "object",
246
+ properties: {
247
+ status: { type: "string", const: "exported" },
248
+ stl: { type: "string", description: "Absolute path of <name>.stl." },
249
+ f3d: { type: "string", description: "Absolute path of <name>.f3d." },
250
+ parameters: { type: "string", description: "Absolute path of <name>.parameters.json." },
251
+ body: { type: "string" },
252
+ triangles: { type: "integer", minimum: 1 },
253
+ bytes: { type: "integer", minimum: 1 },
254
+ parameterCount: { type: "integer", minimum: 0 },
255
+ boundingBox: { type: "object", description: "Measured from the written STL, in its own units: min, max and dimensions." },
256
+ stlUnits: { type: "string", enum: ["mm", "cm", "unknown"], description: "The STL's units, from its size against the Fusion body's." },
257
+ fusionSizeMm: { type: "array", items: { type: "number" }, description: "The Fusion body's bounding-box size in mm." },
258
+ warnings: { type: "array", items: { type: "string" } },
259
+ },
260
+ required: ["status", "stl", "f3d", "parameters", "body", "triangles", "parameterCount"],
261
+ };
262
+ export class FusionMcpBridge {
263
+ constructor(system = defaultFusionSystem) {
264
+ this.system = system;
265
+ }
266
+ /** Close the stdio session, if any; the next call reconnects. */
267
+ async close() {
268
+ const live = this.live;
269
+ this.live = undefined;
270
+ if (!live)
271
+ return;
272
+ live.closed = true;
273
+ await live.client.close().catch(() => { });
274
+ await live.transport.close().catch(() => { });
275
+ }
276
+ async open(timeout) {
277
+ const config = configuration();
278
+ const client = new Client({ name: "bambu-printer-mcp-fusion", version: "1.0.0" });
279
+ const transport = new StdioClientTransport({ ...config, env: fusionEnvironment(), stderr: "pipe" });
280
+ // Drain stderr without relaying arbitrary logs or credentials into the outer MCP stream.
281
+ transport.stderr?.on("data", () => { });
282
+ const live = { client, transport, tools: [], closed: false };
283
+ transport.onclose = () => {
284
+ live.closed = true;
285
+ if (this.live === live)
286
+ this.live = undefined;
287
+ };
288
+ const options = { timeout };
289
+ try {
290
+ await client.connect(transport, options);
291
+ const cursors = new Set();
292
+ let cursor;
293
+ do {
294
+ const page = await client.listTools(cursor ? { cursor } : {}, options);
295
+ live.tools.push(...page.tools);
296
+ cursor = page.nextCursor;
297
+ if (cursor && (cursors.has(cursor) || cursors.size >= 99))
298
+ throw new FusionError("Fusion MCP returned an invalid or excessive tools/list pagination sequence.");
299
+ if (cursor)
300
+ cursors.add(cursor);
301
+ } while (cursor);
302
+ return live;
303
+ }
304
+ catch (error) {
305
+ live.closed = true;
306
+ await client.close().catch(() => { });
307
+ await transport.close().catch(() => { });
308
+ throw error;
309
+ }
310
+ }
311
+ /**
312
+ * The live session, starting one if needed. A start is shared by every caller
313
+ * that arrives while it runs, so it has its own deadline (the longer of the
314
+ * caller's and FUSION_MCP_TIMEOUT_MS) and no caller's signal; each caller
315
+ * waits on it with its own deadline and cancellation.
316
+ */
317
+ async session(timeout, signal) {
318
+ if (this.live && !this.live.closed)
319
+ return this.live;
320
+ if (!this.connecting) {
321
+ const connecting = this.open(Math.max(timeout, timeoutMilliseconds(undefined)))
322
+ .then(live => { this.live = live; return live; })
323
+ .finally(() => { if (this.connecting === connecting)
324
+ this.connecting = undefined; });
325
+ connecting.catch(() => { });
326
+ this.connecting = connecting;
327
+ }
328
+ const shared = this.connecting;
329
+ if (signal.aborted)
330
+ throw new DOMException("The operation was aborted.", "AbortError");
331
+ return new Promise((resolve, reject) => {
332
+ const abort = () => reject(new DOMException("The operation was aborted.", "AbortError"));
333
+ signal.addEventListener("abort", abort, { once: true });
334
+ shared.then(live => { signal.removeEventListener("abort", abort); resolve(live); }, error => { signal.removeEventListener("abort", abort); reject(error); });
335
+ });
336
+ }
337
+ /** One request with a deadline. An interrupted request is never retried; the session is closed instead. */
338
+ async request(args, work) {
339
+ const controller = new AbortController();
340
+ let timedOut = false;
341
+ let phase = "connection";
342
+ let sent = false;
343
+ const deadline = Date.now() + args.timeout;
344
+ const timer = setTimeout(() => { timedOut = true; controller.abort(); }, args.timeout);
345
+ const abort = () => controller.abort();
346
+ args.signal?.addEventListener("abort", abort, { once: true });
347
+ if (args.signal?.aborted)
348
+ controller.abort();
349
+ const options = () => ({ signal: controller.signal, timeout: Math.max(1, deadline - Date.now()) });
350
+ try {
351
+ const live = await this.session(options().timeout, controller.signal);
352
+ phase = "tool request";
353
+ return await work(live, options(), () => { sent = true; });
354
+ }
355
+ catch (error) {
356
+ if (error instanceof FusionError)
357
+ throw error;
358
+ const code = error?.code;
359
+ // The child may still be executing; never reuse a session whose request was cut off.
360
+ if (sent || timedOut || controller.signal.aborted)
361
+ await this.close();
362
+ if (timedOut || code === ErrorCode.RequestTimeout) {
363
+ throw new FusionError(`Fusion MCP timed out during ${phase}.${sent ? " Fusion may still be running the request; inspect the design before retrying. It was not replayed." : " Check FUSION_MCP_COMMAND, FUSION_MCP_ARGS and the Fusion360MCP add-in."}`);
364
+ }
365
+ if (controller.signal.aborted)
366
+ throw new FusionError(`Fusion MCP request cancelled.${sent ? " Fusion may still be running it; inspect the design before retrying." : ""}`);
367
+ // Error messages from processes/RPC peers may contain arguments, code, or credentials.
368
+ const safeCode = typeof code === "number" ? ` (RPC ${code})` : ["ENOENT", "EACCES"].includes(String(code)) ? ` (${code})` : "";
369
+ await this.close();
370
+ throw new FusionError(`Fusion MCP failed during ${phase}${safeCode}. Check FUSION_MCP_COMMAND, FUSION_MCP_ARGS and the Fusion360MCP add-in.`);
371
+ }
372
+ finally {
373
+ clearTimeout(timer);
374
+ args.signal?.removeEventListener("abort", abort);
375
+ }
376
+ }
377
+ async invoke(live, options, dispatched, name, args) {
378
+ const tool = live.tools.find(candidate => candidate.name === name);
379
+ if (!tool)
380
+ throw new FusionError(`Fusion MCP does not advertise ${name}. Call fusion_mcp_status to inspect the available tools.`);
381
+ let valid;
382
+ try {
383
+ valid = new AjvJsonSchemaValidator().getValidator(tool.inputSchema)(args).valid;
384
+ }
385
+ catch {
386
+ throw new FusionError("Fusion MCP advertised an unsupported input schema for this tool.");
387
+ }
388
+ if (!valid)
389
+ throw new FusionError(`${name} arguments do not match its advertised input schema. Inspect fusion_mcp_status before calling the tool.`);
390
+ dispatched();
391
+ return await live.client.callTool({ name, arguments: args }, undefined, options);
392
+ }
393
+ /** A faust tool that must succeed; its failure text is Fusion's own and contains no secrets of ours. */
394
+ async must(live, options, dispatched, name, args) {
395
+ const result = await this.invoke(live, options, dispatched, name, args);
396
+ if (!failed(result, name))
397
+ return result;
398
+ const text = resultText(result);
399
+ if (NO_DESIGN.test(text)) {
400
+ throw new FusionError(`Fusion has no open design, so ${name} cannot run. Call fusion_mcp_new_design first; if that fails too, open any design in Fusion once (the Fusion360MCP add-in at ${FUSION_MCP_PIN} cannot create the first one, faust-machines issue #12).`);
401
+ }
402
+ throw new FusionError(`Fusion ${name} failed: ${text.slice(0, 2000)}`);
403
+ }
404
+ async status(args, signal) {
405
+ allowedArguments(args, ["launch", "timeout_ms"]);
406
+ if (args.launch !== undefined && typeof args.launch !== "boolean")
407
+ throw new FusionError("launch must be a boolean.");
408
+ const timeout = timeoutMilliseconds(args.timeout_ms);
409
+ const { host, port } = addinAddress();
410
+ const configured = Boolean(process.env.FUSION_MCP_COMMAND?.trim());
411
+ let addinReachable = await this.system.addinAnswers(host, port, ADDIN_PING_MS);
412
+ let fusionRunning = addinReachable || await this.system.fusionRunning();
413
+ let launched = false;
414
+ if (args.launch === true && !fusionRunning) {
415
+ if (this.system.platform !== "darwin")
416
+ throw new FusionError("launch is supported on macOS only; start Fusion yourself.");
417
+ try {
418
+ await this.system.launch(port);
419
+ }
420
+ catch {
421
+ throw new FusionError(`Could not start Autodesk Fusion with open -a "Autodesk Fusion" --env FUSION_MCP_PORT=${port}. Is it installed?`);
422
+ }
423
+ launched = true;
424
+ fusionRunning = true;
425
+ const until = Date.now() + this.system.launchWaitMs;
426
+ while (!addinReachable && Date.now() < until) {
427
+ if (signal?.aborted)
428
+ throw new FusionError("Fusion MCP request cancelled while waiting for Fusion to start.");
429
+ await this.system.sleep(1000);
430
+ addinReachable = await this.system.addinAnswers(host, port, ADDIN_PING_MS);
431
+ }
432
+ }
433
+ const result = { configured, connected: false, addinReachable, fusionRunning, tools: [], launched, transport: "stdio", pin: FUSION_MCP_PIN };
434
+ if (!configured)
435
+ return result;
436
+ try {
437
+ await this.request({ timeout, signal }, async (live, options, dispatched) => {
438
+ result.tools = live.tools;
439
+ result.server = live.client.getServerVersion();
440
+ // faust's ping answers through the add-in without touching Fusion's API.
441
+ if (addinReachable && live.tools.some(tool => tool.name === "ping")) {
442
+ const ping = await this.invoke(live, options, dispatched, "ping", {});
443
+ result.connected = !failed(ping, "ping");
444
+ }
445
+ });
446
+ }
447
+ catch (error) {
448
+ result.error = error instanceof Error ? error.message : String(error);
449
+ }
450
+ return result;
451
+ }
452
+ async call(args, signal) {
453
+ allowedArguments(args, ["tool_name", "arguments", "timeout_ms"]);
454
+ const name = textArgument(args.tool_name, "tool_name");
455
+ const toolArgs = argumentObject(args.arguments ?? {}, "arguments");
456
+ return this.request({ timeout: timeoutMilliseconds(args.timeout_ms), signal }, (live, options, dispatched) => this.invoke(live, options, dispatched, name, toolArgs));
457
+ }
458
+ async newDesign(args, signal) {
459
+ allowedArguments(args, ["timeout_ms"]);
460
+ return this.request({ timeout: timeoutMilliseconds(args.timeout_ms), signal }, async (live, options, dispatched) => {
461
+ const created = codeJson(await this.must(live, options, dispatched, "execute_code", { code: NEW_DESIGN_CODE }));
462
+ if (!created || typeof created.document !== "string")
463
+ throw new FusionError("Fusion did not report the new design document.");
464
+ return { status: "created", document: created.document, parametric: created.parametric === true };
465
+ });
466
+ }
467
+ async export(args, signal) {
468
+ allowedArguments(args, ["output_dir", "name", "body_name", "timeout_ms"]);
469
+ const name = textArgument(args.name, "name").trim();
470
+ if (!EXPORT_NAME.test(name) || name.includes(".."))
471
+ throw new FusionError("name must be a plain file name (letters, digits, spaces, dot, dash, underscore), without a path.");
472
+ const bodyName = args.body_name === undefined ? undefined : textArgument(args.body_name, "body_name");
473
+ const timeout = timeoutMilliseconds(args.timeout_ms);
474
+ const directory = await fs.realpath(path.resolve(textArgument(args.output_dir, "output_dir"))).catch(() => { throw new FusionError("output_dir must be an existing directory."); });
475
+ if (!(await fs.stat(directory)).isDirectory())
476
+ throw new FusionError("output_dir must be an existing directory.");
477
+ const outputs = { stl: path.join(directory, `${name}.stl`), f3d: path.join(directory, `${name}.f3d`), parameters: path.join(directory, `${name}.parameters.json`) };
478
+ for (const output of Object.values(outputs)) {
479
+ const exists = await fs.lstat(output).then(() => true, (error) => {
480
+ if (error.code !== "ENOENT")
481
+ throw new FusionError(`${output} cannot be accessed.`);
482
+ return false;
483
+ });
484
+ if (exists)
485
+ throw new FusionError(`${output} already exists; choose a new name. Existing files are never overwritten.`);
486
+ }
487
+ const id = randomUUID();
488
+ const staged = { stl: path.join(directory, `.fusion-${id}.stl`), f3d: path.join(directory, `.fusion-${id}.f3d`), parameters: path.join(directory, `.fusion-${id}.parameters.json`) };
489
+ try {
490
+ const exported = await this.request({ timeout, signal }, async (live, options, dispatched) => {
491
+ // Hidden and surface bodies are never chosen: only what would print.
492
+ const everyBody = fusionBodies(codeJson(await this.must(live, options, dispatched, "execute_code", { code: BODIES_CODE })));
493
+ const bodies = everyBody.filter(entry => entry.solid && entry.visible);
494
+ const names = bodies.map(entry => entry.name);
495
+ const body = bodyName ? bodies.find(entry => entry.name === bodyName) : bodies.length === 1 ? bodies[0] : undefined;
496
+ if (!body) {
497
+ if (bodyName)
498
+ throw new FusionError(`No visible solid body named "${bodyName}". Visible solid bodies: ${names.slice(0, 20).join(", ") || "none"}.`);
499
+ throw new FusionError(bodies.length
500
+ ? `The design has ${bodies.length} visible solid bodies (${names.slice(0, 20).join(", ")}); pass body_name to choose the one to export.`
501
+ : "The design has no visible solid body to export.");
502
+ }
503
+ // export_stl takes the first body with the name, hidden or not, so the name must be unique among all of them.
504
+ if (everyBody.filter(entry => entry.name === body.name).length > 1) {
505
+ throw new FusionError(`Several bodies are named "${body.name}", counting hidden and surface bodies and copies of a component; Fusion's export_stl takes the first. Rename them in Fusion so the export is unambiguous.`);
506
+ }
507
+ await this.must(live, options, dispatched, "export_stl", { body_name: body.name, file_path: staged.stl });
508
+ await this.must(live, options, dispatched, "export_f3d", { file_path: staged.f3d });
509
+ const parameters = codeJson(await this.must(live, options, dispatched, "execute_code", { code: PARAMETERS_CODE }));
510
+ if (!parameters || !Array.isArray(parameters.parameters))
511
+ throw new FusionError("Fusion returned unreadable parameters.");
512
+ return { body, parameters };
513
+ });
514
+ // Fusion writes the files itself, so it must share this filesystem (FUSION_MCP_HOST on another machine cannot export here).
515
+ const mesh = await stlMetadata(staged.stl).catch(() => { throw new FusionError("Fusion did not write a valid STL here. Fusion and this server must share the filesystem."); });
516
+ // Fusion measures in centimetres; the STL's own numbers show which unit it was written in.
517
+ const largestCm = Math.max(...exported.body.size_cm);
518
+ const ratio = largestCm > 0 ? Math.max(...mesh.bounding_box.dimensions) / largestCm : NaN;
519
+ const stlUnits = Math.abs(ratio - 10) < 0.5 ? "mm" : Math.abs(ratio - 1) < 0.05 ? "cm" : "unknown";
520
+ const warnings = [];
521
+ if (stlUnits === "cm")
522
+ warnings.push("The STL is in centimetres; slicers read STL numbers as millimetres. Scale it by 10 before slicing.");
523
+ if (stlUnits === "unknown")
524
+ warnings.push("The STL's size does not match the Fusion body's size in mm or cm; check it before slicing.");
525
+ const archive = await fs.lstat(staged.f3d).catch(() => undefined);
526
+ if (!archive?.isFile() || archive.size === 0)
527
+ throw new FusionError("Fusion did not write the F3D archive here. Fusion and this server must share the filesystem.");
528
+ await fs.writeFile(staged.parameters, `${JSON.stringify(exported.parameters, null, 2)}\n`, { flag: "wx" });
529
+ // link() publishes without replacing a file created since the check above.
530
+ // All three or none: a failure removes the outputs this call already published.
531
+ const published = [];
532
+ try {
533
+ for (const key of ["stl", "f3d", "parameters"]) {
534
+ await fs.link(staged[key], outputs[key]).catch(() => { throw new FusionError(`Cannot write ${outputs[key]}; it may already exist or be unwritable.`); });
535
+ published.push(outputs[key]);
536
+ }
537
+ }
538
+ catch (error) {
539
+ for (const file of published)
540
+ await fs.rm(file, { force: true }).catch(() => { });
541
+ throw error;
542
+ }
543
+ return {
544
+ status: "exported", ...outputs, body: exported.body.name,
545
+ triangles: mesh.triangles, bytes: mesh.bytes,
546
+ parameterCount: exported.parameters.parameters.length,
547
+ boundingBox: mesh.bounding_box, stlUnits,
548
+ fusionSizeMm: exported.body.size_cm.map(value => Math.round(value * 10 * 1e4) / 1e4),
549
+ ...(warnings.length ? { warnings } : {}),
550
+ };
551
+ }
552
+ finally {
553
+ for (const file of Object.values(staged))
554
+ await fs.rm(file, { force: true }).catch(() => { });
555
+ }
556
+ }
557
+ }