bambu-printer-mcp 1.1.66 → 1.1.67

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,654 @@
1
+ /**
2
+ * Setting up the two design apps this server bridges: the MCP for Blender add-on (blender_mcp_setup) and Autodesk
3
+ * Fusion's Fusion360MCP add-in (fusion_mcp_setup). Clients such as Counterpart call these tools instead of keeping
4
+ * their own copy of each app's install layout, which changes whenever Blender, Fusion or their MCP servers do.
5
+ *
6
+ * Neither tool launches, closes or edits a running app. Blender's add-on is installed by its own upstream installer
7
+ * (`mcp-for-blender install-addon`); the Fusion add-in comes from one pinned commit whose every file is checked
8
+ * against its SHA-256 before anything is copied.
9
+ */
10
+ import { execFile } from "node:child_process";
11
+ import { createHash, randomUUID } from "node:crypto";
12
+ import fs from "node:fs/promises";
13
+ import { copyFileSync, constants as fsConstants, readFileSync } from "node:fs";
14
+ import net from "node:net";
15
+ import os from "node:os";
16
+ import path from "node:path";
17
+ import { promisify } from "node:util";
18
+ import { getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js";
19
+ import { writeEnvValues } from "./counterpart/route.js";
20
+ const execFileAsync = promisify(execFile);
21
+ /**
22
+ * What a setup subprocess (uvx and the Blender package it runs, tar, launchctl) may see: the basic login
23
+ * environment, uv's own settings and the Blender bridge's, never printer access codes or other server secrets,
24
+ * as the Blender bridge's own environment.
25
+ */
26
+ export function setupEnvironment(env = process.env) {
27
+ const allowed = { ...getDefaultEnvironment() };
28
+ for (const name of ["TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "PATH", "HOME"]) {
29
+ if (env[name] !== undefined)
30
+ allowed[name] = env[name];
31
+ }
32
+ for (const [key, value] of Object.entries(env))
33
+ if (/^(?:BLENDER_|BLENDERMCP_|UV_)/.test(key) && value !== undefined)
34
+ allowed[key] = value;
35
+ return allowed;
36
+ }
37
+ export const defaultSetupSystem = {
38
+ platform: process.platform,
39
+ home: os.homedir(),
40
+ tmp: os.tmpdir(),
41
+ uid: typeof process.getuid === "function" ? process.getuid() : 0,
42
+ cwd: process.cwd(),
43
+ run: async (file, args, options = {}) => {
44
+ const { stdout } = await execFileAsync(file, args, { env: setupEnvironment(options.env ?? process.env), ...(options.cwd ? { cwd: options.cwd } : {}), ...(options.signal ? { signal: options.signal } : {}), timeout: options.timeoutMs ?? 30000, maxBuffer: 4 * 1024 * 1024 });
45
+ return { stdout: String(stdout) };
46
+ },
47
+ download: async (url, signal) => {
48
+ const response = await fetch(url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(120000)]) : AbortSignal.timeout(120000) });
49
+ if (response.status !== 200)
50
+ throw new Error(`HTTP ${response.status}`);
51
+ return Buffer.from(await response.arrayBuffer());
52
+ },
53
+ listening: (host, port) => new Promise(resolve => {
54
+ const socket = net.createConnection({ host, port });
55
+ const done = (value) => { socket.destroy(); resolve(value); };
56
+ socket.setTimeout(1000, () => done(false));
57
+ socket.once("connect", () => done(true));
58
+ socket.once("error", () => done(false));
59
+ }),
60
+ fusionByBundleId: async () => {
61
+ if (process.platform !== "darwin")
62
+ return [];
63
+ const found = [];
64
+ for (const id of FUSION_BUNDLE_IDS) {
65
+ try {
66
+ const { stdout } = await execFileAsync("/usr/bin/mdfind", [`kMDItemCFBundleIdentifier == '${id}'`], { timeout: 10000 });
67
+ found.push(...String(stdout).split("\n").map(line => line.trim()).filter(Boolean));
68
+ }
69
+ catch { /* Spotlight off or unavailable: the usual folders are checked too */ }
70
+ }
71
+ return found;
72
+ },
73
+ };
74
+ async function exists(file) {
75
+ try {
76
+ await fs.lstat(file);
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
83
+ async function regularFile(file) {
84
+ try {
85
+ return (await fs.lstat(file)).isFile();
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
92
+ /** The server's own `.env`, when it has one: a client's env block has no file to update. */
93
+ function envFile(system) { return path.resolve(system.cwd, ".env"); }
94
+ // ---------------------------------------------------------------------------------------------------------------
95
+ // Blender
96
+ /** The add-on's own default port; BLENDER_HOST and BLENDER_PORT move it, as they do for the Blender MCP server. */
97
+ export const BLENDER_ADDON_DEFAULT_PORT = 9876;
98
+ const MAX_ADDON_BYTES = 4 * 1024 * 1024;
99
+ const ADDON_NAME = /["']name["']\s*:\s*["'](?:MCP for Blender|Blender MCP)["']/;
100
+ const ADDON_PROTOCOL = /ADDON_PROTOCOL_VERSION\s*=\s*(\d+)/;
101
+ const PACKAGE = /^(mcp-for-blender|blender-mcp)(?:(?:@|==)[\w.+-]+)?$/;
102
+ /** Asks the configured package itself which add-on protocol it expects and which add-on files Blender has. */
103
+ const INSPECT = `import json
104
+ from blender_mcp import addon_manager as a
105
+ from importlib.metadata import version, requires
106
+ import sys
107
+ if sys.argv[1] == "blender-mcp" and not any(r.startswith("mcp-for-blender") for r in requires("blender-mcp") or []):
108
+ raise RuntimeError("The configured package is not the upstream compatibility alias")
109
+ print(json.dumps({"version":version("mcp-for-blender"),"protocol":a.EXPECTED_ADDON_PROTOCOL_VERSION,"files":[{"path":str(p.absolute()),"protocol":a.read_addon_protocol_version(p)} for p in a.find_existing_addon_installs()]}))`;
110
+ /** get_addon_status's result, structured or as JSON text; a failed call throws with the add-on's own words. */
111
+ export function parseAddonHandshake(reply) {
112
+ const text = (reply.content ?? []).flatMap(item => item.type === "text" && typeof item.text === "string" ? [item.text] : []).join("\n").trim();
113
+ if (reply.isError)
114
+ throw new Error(`Blender's add-on could not be checked: ${text || "no details"}`);
115
+ let value = reply.structuredContent;
116
+ if (!value || typeof value !== "object") {
117
+ try {
118
+ value = JSON.parse(text);
119
+ }
120
+ catch {
121
+ return undefined;
122
+ }
123
+ }
124
+ if (!value || typeof value !== "object")
125
+ return undefined;
126
+ const { up_to_date, protocol_version, expected_protocol_version, blender_version } = value;
127
+ return {
128
+ ...(typeof up_to_date === "boolean" ? { up_to_date } : {}),
129
+ ...(typeof protocol_version === "number" || protocol_version === null ? { protocol_version } : {}),
130
+ ...(typeof expected_protocol_version === "number" ? { expected_protocol_version } : {}),
131
+ ...(typeof blender_version === "string" || blender_version === null ? { blender_version } : {}),
132
+ };
133
+ }
134
+ /** One change at a time per server: overlapping updates would interleave backups, renames and .env writes. */
135
+ class Serial {
136
+ constructor() {
137
+ this.tail = Promise.resolve();
138
+ }
139
+ run(work, signal) {
140
+ // A request cancelled while it waited never starts.
141
+ const start = () => { signal?.throwIfAborted(); return work(); };
142
+ const next = this.tail.then(start, start);
143
+ this.tail = next.catch(() => undefined);
144
+ return next;
145
+ }
146
+ }
147
+ const UNSUPPORTED_MESSAGES = {
148
+ "not-configured": "This printer MCP has no Blender bridge configured (BLENDER_MCP_COMMAND and BLENDER_MCP_ARGS). Set it up for MCP for Blender, then check again.",
149
+ "custom-command": "This Blender bridge uses its own command, so its add-on is updated with that bridge's installer.",
150
+ "custom-package": "This Blender bridge uses its own package, so its add-on is updated with that bridge's installer.",
151
+ };
152
+ const TARGET_MESSAGES = {
153
+ "not-installed": "The MCP for Blender add-on isn't installed for this Blender. Install it (Edit → Preferences → Add-ons, or uvx mcp-for-blender install-addon), then check again.",
154
+ "several-modules": "More than one MCP for Blender module is installed in this Blender's add-ons folder. Keep the enabled one and remove the others, then check again.",
155
+ };
156
+ /** uv's uvx, as configured: `uvx`, a full path to it, or Windows' uvx.exe. */
157
+ const isUvx = (command) => /^uvx(?:\.exe)?$/i.test(path.basename(command.replace(/\\/g, "/")));
158
+ /** The configured Blender bridge as an installer: only the upstream package through uvx, as configured. */
159
+ function configuredInstaller(env) {
160
+ const command = env.BLENDER_MCP_COMMAND?.trim();
161
+ let args = [];
162
+ try {
163
+ args = JSON.parse(env.BLENDER_MCP_ARGS?.trim() || "[]");
164
+ }
165
+ catch {
166
+ args = undefined; /* not JSON: the bridge itself refuses it */
167
+ }
168
+ if (!command || !Array.isArray(args) || !args.every(arg => typeof arg === "string"))
169
+ return { reason: "not-configured" };
170
+ if (!isUvx(command))
171
+ return { reason: "custom-command" };
172
+ const from = args.indexOf("--from");
173
+ const spec = from >= 0 ? args[from + 1] : args.find(arg => PACKAGE.test(arg));
174
+ if (typeof spec !== "string" || !PACKAGE.test(spec))
175
+ return { reason: "custom-package" };
176
+ return { command, packageSpec: spec, packageName: spec.split(/@|==/)[0] };
177
+ }
178
+ /** One add-on module per Blender version folder; other versions are separate installs. */
179
+ export function selectBlenderAddonTarget(files, blenderVersion) {
180
+ const valid = files.filter((file) => typeof file.path === "string");
181
+ const version = blenderVersion?.match(/^\d+\.\d+/)?.[0];
182
+ // A Blender version folder in any of Blender's own layouts: macOS and Windows ".../Blender/5.0/...", Linux
183
+ // "~/.config/blender/5.0/...".
184
+ const inVersion = (file) => file.split(/[\\/]/).some((part, index, parts) => part === version && parts[index - 1]?.toLowerCase() === "blender");
185
+ const candidates = version ? valid.filter(file => inVersion(file.path)) : valid;
186
+ const first = candidates[0];
187
+ if (!first)
188
+ return { problem: "not-installed" };
189
+ if (candidates.filter(file => path.dirname(file.path) === path.dirname(first.path)).length !== 1)
190
+ return { problem: "several-modules" };
191
+ return { target: { path: first.path, protocol: typeof first.protocol === "number" ? first.protocol : null } };
192
+ }
193
+ function blenderAddress(env) {
194
+ const port = Number(env.BLENDER_PORT?.trim() || BLENDER_ADDON_DEFAULT_PORT);
195
+ return { host: env.BLENDER_HOST?.trim() || "localhost", port: Number.isInteger(port) && port > 0 && port < 65536 ? port : BLENDER_ADDON_DEFAULT_PORT };
196
+ }
197
+ const isAddon = (bytes) => ADDON_NAME.test(bytes.toString("utf8"));
198
+ const addonProtocol = (bytes) => { const match = ADDON_PROTOCOL.exec(bytes.toString("utf8")); return match ? Number(match[1]) : undefined; };
199
+ export class BlenderAddonSetup {
200
+ constructor(
201
+ /** The running add-on's get_addon_status through this server's Blender bridge; undefined when it has none. */
202
+ handshake, system = defaultSetupSystem, env = process.env) {
203
+ this.handshake = handshake;
204
+ this.system = system;
205
+ this.env = env;
206
+ this.serial = new Serial();
207
+ }
208
+ async inspect(installer) {
209
+ const { stdout } = await this.system.run(installer.command, ["--from", installer.packageSpec, "python", "-c", INSPECT, installer.packageName], { env: this.env, cwd: this.system.cwd, timeoutMs: 60000 });
210
+ let report;
211
+ try {
212
+ report = JSON.parse(stdout.trim());
213
+ }
214
+ catch {
215
+ throw new Error("The configured Blender MCP package did not report its add-on files.");
216
+ }
217
+ if (typeof report.version !== "string" || !/^\d+\.\d+\.\d+[\w.+-]*$/.test(report.version) || typeof report.protocol !== "number"
218
+ || !Number.isInteger(report.protocol) || !Array.isArray(report.files))
219
+ throw new Error("The configured Blender MCP package returned an unsupported add-on report.");
220
+ return { version: report.version, protocol: report.protocol, files: report.files };
221
+ }
222
+ /** What is installed, what the package expects, and what the running add-on says. Changes nothing. */
223
+ async check() {
224
+ const installer = configuredInstaller(this.env);
225
+ const { host, port } = blenderAddress(this.env);
226
+ const listening = await this.system.listening(host, port);
227
+ if ("reason" in installer)
228
+ return { supported: false, reason: installer.reason, listening, message: UNSUPPORTED_MESSAGES[installer.reason] };
229
+ let live, liveError;
230
+ if (listening) {
231
+ try {
232
+ live = (await this.handshake()) ?? null;
233
+ }
234
+ catch (error) {
235
+ live = null;
236
+ liveError = error instanceof Error ? error.message : String(error);
237
+ }
238
+ }
239
+ const inspected = await this.inspect(installer);
240
+ const selected = selectBlenderAddonTarget(inspected.files, live?.blender_version);
241
+ const report = { supported: true, package: installer.packageSpec, package_version: inspected.version, expected_protocol: inspected.protocol,
242
+ listening, ...(live !== undefined ? { live } : {}), ...(liveError ? { live_error: liveError } : {}) };
243
+ if ("problem" in selected)
244
+ return { ...report, target: null, target_problem: selected.problem, current: false, message: TARGET_MESSAGES[selected.problem] };
245
+ return { ...report, target: selected.target, current: selected.target.protocol === inspected.protocol };
246
+ }
247
+ /**
248
+ * Replaces the installed add-on file with the one the configured package's own installer stages, pinned to the
249
+ * inspected version. The existing file must be a regular local MCP for Blender add-on; the staged one must carry
250
+ * the expected protocol. The old file is kept as a backup next to it, and the new one is renamed into place.
251
+ * Blender keeps running the add-on it loaded until it is re-enabled or restarted.
252
+ */
253
+ /** `signal` ends the request: the installer is stopped and nothing is replaced once it is aborted. */
254
+ async update(signal) { return this.serial.run(() => this.replace(signal), signal); }
255
+ async replace(signal) {
256
+ const report = await this.check();
257
+ if (!report.supported || !report.target)
258
+ throw new Error(report.message ?? "The Blender add-on can't be updated here.");
259
+ const target = report.target.path;
260
+ const info = await fs.lstat(target);
261
+ if (!info.isFile() || await fs.realpath(target) !== target)
262
+ throw new Error("The installed Blender add-on is not a regular local file. Nothing was replaced.");
263
+ const before = await fs.readFile(target);
264
+ if (before.length > MAX_ADDON_BYTES || !isAddon(before))
265
+ throw new Error("The installed file is not a recognized MCP for Blender add-on. Nothing was replaced.");
266
+ const installer = configuredInstaller(this.env);
267
+ await fs.mkdir(this.system.tmp, { recursive: true });
268
+ const work = await fs.mkdtemp(path.join(this.system.tmp, "blender-addon-"));
269
+ try {
270
+ await this.system.run(installer.command, ["--from", `mcp-for-blender==${report.package_version}`, "mcp-for-blender", "install-addon", "--addons-dir", work], { env: this.env, cwd: this.system.cwd, timeoutMs: 120000, ...(signal ? { signal } : {}) });
271
+ const staged = path.join(work, "blender_mcp.py");
272
+ if (!await regularFile(staged) || !(await fs.realpath(staged)).startsWith(await fs.realpath(work) + path.sep))
273
+ throw new Error("The add-on installer did not stage a regular add-on file. Nothing was replaced.");
274
+ const bytes = await fs.readFile(staged);
275
+ if (bytes.length > MAX_ADDON_BYTES || !isAddon(bytes) || addonProtocol(bytes) !== report.expected_protocol)
276
+ throw new Error("The staged add-on doesn't match the configured Blender MCP package. Nothing was replaced.");
277
+ if (bytes.equals(before))
278
+ return { ...report, current: true, replaced: false };
279
+ signal?.throwIfAborted();
280
+ const backup = `${target}.before-update-${randomUUID()}.bak`;
281
+ const saved = await fs.open(backup, "wx", 0o600);
282
+ try {
283
+ await saved.writeFile(before);
284
+ await saved.sync();
285
+ }
286
+ finally {
287
+ await saved.close();
288
+ }
289
+ if (!(await fs.readFile(target)).equals(before))
290
+ throw new Error("The Blender add-on changed while it was being updated. Nothing was replaced.");
291
+ signal?.throwIfAborted();
292
+ const replacement = path.join(path.dirname(target), `.blender-addon-${randomUUID()}.tmp`);
293
+ try {
294
+ const file = await fs.open(replacement, "wx", info.mode & 0o777);
295
+ try {
296
+ await file.writeFile(bytes);
297
+ await file.sync();
298
+ }
299
+ finally {
300
+ await file.close();
301
+ }
302
+ signal?.throwIfAborted();
303
+ await fs.rename(replacement, target);
304
+ }
305
+ finally {
306
+ await fs.rm(replacement, { force: true }).catch(() => undefined);
307
+ }
308
+ const { host, port } = blenderAddress(this.env);
309
+ return { ...report, target: { path: target, protocol: report.expected_protocol ?? null }, current: true, replaced: true, backup,
310
+ listening: await this.system.listening(host, port) };
311
+ }
312
+ finally {
313
+ await fs.rm(work, { recursive: true, force: true }).catch(() => undefined);
314
+ }
315
+ }
316
+ }
317
+ export const BLENDER_SETUP_OUTPUT_SCHEMA = {
318
+ type: "object",
319
+ properties: {
320
+ supported: { type: "boolean", description: "The configured bridge is the upstream MCP for Blender package run with uvx, so this tool can check and update its add-on." },
321
+ reason: { type: "string", enum: ["not-configured", "custom-command", "custom-package"] },
322
+ package: { type: "string", description: "The package as BLENDER_MCP_ARGS names it." },
323
+ package_version: { type: "string" },
324
+ expected_protocol: { type: "integer", description: "The add-on protocol the package needs." },
325
+ listening: { type: "boolean", description: "The add-on answers on BLENDER_HOST:BLENDER_PORT (default localhost:9876): Blender is running with it started." },
326
+ live: { type: ["object", "null"], description: "The running add-on's get_addon_status (up_to_date, protocol_version, expected_protocol_version, blender_version); null when it has none or it couldn't be read. Only while listening." },
327
+ live_error: { type: "string", description: "Why the running add-on's handshake couldn't be read." },
328
+ target: { type: ["object", "null"], properties: { path: { type: "string" }, protocol: { type: ["integer", "null"] } }, required: ["path", "protocol"],
329
+ description: "The add-on file Blender loads (for the running Blender's version, when it reports one)." },
330
+ target_problem: { type: "string", enum: ["not-installed", "several-modules"] },
331
+ message: { type: "string", description: "What the person can do, in plain words, when the add-on can't be checked or updated here (with reason or target_problem). Clients show it as it is." },
332
+ current: { type: "boolean", description: "The installed file carries the expected protocol. A running Blender may still have the old add-on loaded: see live." },
333
+ replaced: { type: "boolean", description: "update: the file was replaced. Blender runs the new add-on once it is re-enabled or Blender restarts." },
334
+ backup: { type: "string", description: "update: the previous add-on file, kept next to it." },
335
+ },
336
+ required: ["supported", "listening"],
337
+ };
338
+ // ---------------------------------------------------------------------------------------------------------------
339
+ // Fusion
340
+ /** The add-in and server commit Counterpart's Fusion design passes were accepted on (document binding, PRD §8.9). */
341
+ export const FUSION_ADDIN_REPOSITORY = "DMontgomery40/fusion360-mcp-server";
342
+ export const FUSION_ADDIN_COMMIT = "86a3016a5a5b4a705228acc2f3b75aff7dcfd758";
343
+ /** SHA-256 of every file in the add-in (`addon/`) at that commit. Setup installs nothing else. */
344
+ export const FUSION_ADDIN_FILES = Object.freeze({
345
+ "Fusion360MCP.manifest": "28b50ab54dcc962fba726d1490dafd8d6ff7a78e31bb5011644a68c3f1788afa",
346
+ "Fusion360MCP.py": "f91c44c6ccaa324d7be6ce6bf4fa08d2dceb0dfec599c066e3835f7442a489a5",
347
+ "server/__init__.py": "cfb2ec371f493b437d1029f82a167ff933e59d7660a0b534e7e840a3d84669de",
348
+ "server/command_handler.py": "5f95aa7f2b58ef1458747b29af8eb63598108f22ed4521f0702e2dda91969b19",
349
+ "server/document_scope.py": "2687d370a1a40531c248232e0b1a7c65bbf92c269938e7cb368a78d098c529be",
350
+ "server/event_bridge.py": "a3a8d55a9267e252b5add0e7261fa4f7f216921b265815e5a2451d0dc3246a72",
351
+ "server/hints.py": "981e89c0032223de1c02ef937b3522280c0328933f07ab89912ff522f4544822",
352
+ "server/hole_geometry.py": "872ef1c7d34a21e49e277517cf413322c609fac47e2e64d2c1ed9580af31d25c",
353
+ "server/parameter_units.py": "1fe5bbf505cecc19902c2720d5d53e12944bb61f182c3c0348e971849afa5c00",
354
+ "server/socket_server.py": "758419b11142b9a5068dbc9f1cf339c3d79fc6d5ab77736f4463f8499d053b4d",
355
+ });
356
+ export const FUSION_ADDIN_PIN = Object.freeze({ repository: FUSION_ADDIN_REPOSITORY, commit: FUSION_ADDIN_COMMIT, files: FUSION_ADDIN_FILES });
357
+ const FUSION_BUNDLE_IDS = ["com.autodesk.fusion360", "com.autodesk.mas.fusion360"];
358
+ /** A login agent that gives Fusion the add-in's port however Fusion is opened (a GUI app never reads this .env). */
359
+ export const FUSION_PORT_AGENT_LABEL = "com.scantomake.mac.fusion-port";
360
+ const RUN_ON_STARTUP_OFF = /"runOnStartup"\s*:\s*false/;
361
+ export class FusionAddinSetup {
362
+ constructor(
363
+ /** FUSION_MCP_PORT, as the bridge resolves it. */
364
+ port,
365
+ /** The bridge arguments for the pinned server, written with the add-in so the two always match. */
366
+ serverArgs, system = defaultSetupSystem, env = process.env, pin = FUSION_ADDIN_PIN) {
367
+ this.port = port;
368
+ this.serverArgs = serverArgs;
369
+ this.system = system;
370
+ this.env = env;
371
+ this.pin = pin;
372
+ this.serial = new Serial();
373
+ }
374
+ get addinsFolder() { return path.join(this.system.home, "Library", "Application Support", "Autodesk", "Autodesk Fusion 360", "API", "AddIns"); }
375
+ get addinFolder() { return path.join(this.addinsFolder, "Fusion360MCP"); }
376
+ get portAgent() { return path.join(this.system.home, "Library", "LaunchAgents", `${FUSION_PORT_AGENT_LABEL}.plist`); }
377
+ async findFusion() {
378
+ for (const found of await this.system.fusionByBundleId())
379
+ if (await exists(found))
380
+ return found;
381
+ const home = this.system.home;
382
+ const places = [path.join(home, "Library", "Application Support", "Autodesk", "webdeploy", "production", "Autodesk Fusion.app"),
383
+ "/Applications/Autodesk Fusion.app", "/Applications/Autodesk Fusion 360.app",
384
+ path.join(home, "Applications", "Autodesk Fusion.app"), path.join(home, "Applications", "Autodesk Fusion 360.app")];
385
+ for (const place of places)
386
+ if (await exists(place))
387
+ return place;
388
+ return null;
389
+ }
390
+ /** Each pinned file at its pinned bytes; the manifest may carry only setup's runOnStartup change. Fusion's own caches are ignored. */
391
+ async installedMatchesPin(folder) {
392
+ let runOnStartup = false;
393
+ for (const [relative, expected] of Object.entries(this.pin.files)) {
394
+ const file = path.join(folder, ...relative.split("/"));
395
+ if (!await regularFile(file))
396
+ return { matches: false, runOnStartup };
397
+ const bytes = await fs.readFile(file);
398
+ if (relative === "Fusion360MCP.manifest") {
399
+ const text = bytes.toString("utf8");
400
+ runOnStartup = /"runOnStartup"\s*:\s*true/.test(text);
401
+ if (sha256(Buffer.from(text.replace(/"runOnStartup"(\s*):(\s*)true/, '"runOnStartup"$1:$2false'), "utf8")) !== expected)
402
+ return { matches: false, runOnStartup };
403
+ }
404
+ else if (sha256(bytes) !== expected)
405
+ return { matches: false, runOnStartup };
406
+ }
407
+ return { matches: true, runOnStartup };
408
+ }
409
+ portAgentPlist() {
410
+ return `<?xml version="1.0" encoding="UTF-8"?>
411
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
412
+ <plist version="1.0">
413
+ <dict>
414
+ \t<key>Label</key>
415
+ \t<string>${FUSION_PORT_AGENT_LABEL}</string>
416
+ \t<key>ProgramArguments</key>
417
+ \t<array>
418
+ \t\t<string>/bin/launchctl</string>
419
+ \t\t<string>setenv</string>
420
+ \t\t<string>FUSION_MCP_PORT</string>
421
+ \t\t<string>${this.port()}</string>
422
+ \t</array>
423
+ \t<key>RunAtLoad</key>
424
+ \t<true/>
425
+ </dict>
426
+ </plist>
427
+ `;
428
+ }
429
+ /**
430
+ * The agent is installed when it sets this port and launchd has it loaded in the login session: a file whose load
431
+ * failed is installed again. An agent written for another port is replaced by install.
432
+ */
433
+ async portAgentInstalled() {
434
+ if (!await regularFile(this.portAgent))
435
+ return false;
436
+ const text = await fs.readFile(this.portAgent, "utf8");
437
+ if (!(text.includes(`<string>${FUSION_PORT_AGENT_LABEL}</string>`) && text.includes("<string>FUSION_MCP_PORT</string>") && text.includes(`<string>${this.port()}</string>`)))
438
+ return false;
439
+ try {
440
+ await this.system.run("/bin/launchctl", ["print", `gui/${this.system.uid}/${FUSION_PORT_AGENT_LABEL}`]);
441
+ return true;
442
+ }
443
+ catch {
444
+ return false;
445
+ }
446
+ }
447
+ /** What is installed. Changes nothing. */
448
+ async check() {
449
+ const supported = this.system.platform === "darwin";
450
+ const fusionPath = supported ? await this.findFusion() : null;
451
+ const addin = await this.installedMatchesPin(this.addinFolder);
452
+ const installed = await regularFile(path.join(this.addinFolder, "Fusion360MCP.py"));
453
+ const portAgent = supported && await this.portAgentInstalled();
454
+ const configured = Boolean(this.env.FUSION_MCP_COMMAND?.trim());
455
+ const env = envFile(this.system);
456
+ const envFound = await regularFile(env);
457
+ const ready = supported && addin.matches && addin.runOnStartup && portAgent && configured;
458
+ const missing = !supported ? ["Fusion setup installs on macOS only. Install the add-in from the repository's addon folder by hand."]
459
+ : [
460
+ ...(fusionPath === null ? ["Autodesk Fusion isn't installed on this Mac. Install it, then set up again."] : []),
461
+ ...(!addin.matches || !addin.runOnStartup ? ["The Fusion360MCP add-in isn't installed at the pinned version, set to run on startup."] : []),
462
+ ...(!portAgent ? ["The login item that gives Fusion its port isn't loaded."] : []),
463
+ ...(!configured ? [envFound ? "This server's Fusion settings (FUSION_MCP_COMMAND) aren't set."
464
+ : "This server has no .env file to add its Fusion settings to: add FUSION_MCP_COMMAND and FUSION_MCP_ARGS to its configuration."] : []),
465
+ ];
466
+ return {
467
+ platform: this.system.platform, supported,
468
+ fusion: { installed: fusionPath !== null, path: fusionPath },
469
+ pin: { repository: this.pin.repository, commit: this.pin.commit },
470
+ addin: { path: this.addinFolder, installed, matches_pin: addin.matches, run_on_startup: addin.runOnStartup },
471
+ port: this.port(),
472
+ port_agent: { path: this.portAgent, installed: portAgent },
473
+ configured,
474
+ env_file: envFound ? env : null,
475
+ ready,
476
+ ...(!ready && missing.length ? { message: missing.join(" ") } : {}),
477
+ };
478
+ }
479
+ /** The pinned add-in, downloaded and checked file by file: every entry a regular file or folder, nothing extra, nothing missing. */
480
+ async downloadAddin(work, signal) {
481
+ const archive = path.join(work, "addin.tar.gz");
482
+ let bytes;
483
+ try {
484
+ bytes = await this.system.download(`https://codeload.github.com/${this.pin.repository}/tar.gz/${this.pin.commit}`, signal);
485
+ }
486
+ catch (error) {
487
+ throw new Error(`The Fusion add-in couldn't be downloaded (${error instanceof Error ? error.message : String(error)}). Check the internet connection and try again.`);
488
+ }
489
+ await fs.writeFile(archive, bytes);
490
+ const extracted = path.join(work, "extracted");
491
+ await fs.mkdir(extracted);
492
+ await this.system.run("tar", ["-xzf", archive, "-C", extracted, `${path.basename(this.pin.repository)}-${this.pin.commit}/addon`], { timeoutMs: 60000, ...(signal ? { signal } : {}) });
493
+ const addon = path.join(extracted, `${path.basename(this.pin.repository)}-${this.pin.commit}`, "addon");
494
+ const found = [];
495
+ const walk = async (dir, prefix) => {
496
+ for (const entry of await fs.readdir(dir)) {
497
+ const full = path.join(dir, entry), relative = prefix ? `${prefix}/${entry}` : entry;
498
+ const info = await fs.lstat(full);
499
+ if (info.isDirectory()) {
500
+ await walk(full, relative);
501
+ continue;
502
+ }
503
+ if (!info.isFile())
504
+ throw new Error(`The downloaded add-in has ${relative}, which isn't a regular file, so nothing was installed.`);
505
+ if (this.pin.files[relative] !== sha256(await fs.readFile(full)))
506
+ throw new Error("The downloaded add-in didn't match the pinned version, so nothing was installed.");
507
+ found.push(relative);
508
+ }
509
+ };
510
+ if (!(await fs.lstat(addon).catch(() => undefined))?.isDirectory())
511
+ throw new Error("The downloaded archive has no add-in, so nothing was installed.");
512
+ await walk(addon, "");
513
+ if (found.length !== Object.keys(this.pin.files).length)
514
+ throw new Error("The downloaded add-in didn't match the pinned version, so nothing was installed.");
515
+ return addon;
516
+ }
517
+ async installAddin(signal) {
518
+ await fs.mkdir(this.system.tmp, { recursive: true });
519
+ const work = await fs.mkdtemp(path.join(this.system.tmp, "fusion-addin-"));
520
+ try {
521
+ const addon = await this.downloadAddin(work, signal);
522
+ signal?.throwIfAborted();
523
+ await fs.mkdir(this.addinsFolder, { recursive: true });
524
+ const staging = path.join(this.addinsFolder, `.Fusion360MCP-${randomUUID()}`);
525
+ await fs.cp(addon, staging, { recursive: true, verbatimSymlinks: true });
526
+ const manifest = path.join(staging, "Fusion360MCP.manifest");
527
+ await fs.writeFile(manifest, (await fs.readFile(manifest, "utf8")).replace(RUN_ON_STARTUP_OFF, '"runOnStartup": true'));
528
+ const previous = path.join(this.addinsFolder, `.Fusion360MCP-previous-${randomUUID()}`);
529
+ signal?.throwIfAborted();
530
+ const hadPrevious = await exists(this.addinFolder);
531
+ if (hadPrevious)
532
+ await fs.rename(this.addinFolder, previous);
533
+ try {
534
+ await fs.rename(staging, this.addinFolder);
535
+ }
536
+ catch (error) {
537
+ if (hadPrevious)
538
+ await fs.rename(previous, this.addinFolder).catch(() => undefined);
539
+ throw error;
540
+ }
541
+ if (hadPrevious)
542
+ await fs.rm(previous, { recursive: true, force: true });
543
+ }
544
+ finally {
545
+ await fs.rm(work, { recursive: true, force: true }).catch(() => undefined);
546
+ }
547
+ }
548
+ /** Writes the agent and loads it in the person's login session, where its RunAtLoad sets FUSION_MCP_PORT. */
549
+ async installPortAgent(signal) {
550
+ signal?.throwIfAborted();
551
+ await fs.mkdir(path.dirname(this.portAgent), { recursive: true });
552
+ const temporary = `${this.portAgent}.${randomUUID()}.tmp`;
553
+ await fs.writeFile(temporary, this.portAgentPlist(), { mode: 0o644, flag: "wx" });
554
+ await fs.rename(temporary, this.portAgent);
555
+ const domain = `gui/${this.system.uid}`;
556
+ await this.system.run("/bin/launchctl", ["bootout", `${domain}/${FUSION_PORT_AGENT_LABEL}`]).catch(() => undefined); // an earlier copy
557
+ // Loaded in the login session, its RunAtLoad sets the port there; print confirms launchd has it.
558
+ try {
559
+ await this.system.run("/bin/launchctl", ["bootstrap", domain, this.portAgent]);
560
+ await this.system.run("/bin/launchctl", ["print", `${domain}/${FUSION_PORT_AGENT_LABEL}`]);
561
+ }
562
+ catch {
563
+ throw new Error(`The login item that gives Fusion its port couldn't be loaded (${this.portAgent}).`);
564
+ }
565
+ }
566
+ /**
567
+ * Adds the bridge settings this server is missing to its own .env, after a copy of the file. A configured
568
+ * FUSION_MCP_COMMAND is kept with its arguments: it may be a reviewed local runtime. The running server takes
569
+ * the new settings at once.
570
+ */
571
+ writeSettings() {
572
+ const file = envFile(this.system);
573
+ // A setting the process has, or the file gives a value, is the person's: it is never rewritten. An empty one
574
+ // (`FUSION_MCP_COMMAND=` in .env.example) is filled in.
575
+ const inFile = new Set(readFileSync(file, "utf8").split("\n").flatMap(line => {
576
+ const match = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*(.*?)\s*$/.exec(line);
577
+ return match && match[2].replace(/^(['"])(.*)\1$/, "$2").trim() ? [match[1]] : [];
578
+ }));
579
+ const has = (key) => Boolean(this.env[key]?.trim()) || inFile.has(key);
580
+ const values = {};
581
+ if (!has("FUSION_MCP_COMMAND")) {
582
+ const blender = this.env.BLENDER_MCP_COMMAND?.trim();
583
+ values.FUSION_MCP_COMMAND = blender && isUvx(blender) ? blender : "uvx";
584
+ }
585
+ // The pinned server, unless the person chose other arguments.
586
+ if (!has("FUSION_MCP_ARGS"))
587
+ values.FUSION_MCP_ARGS = JSON.stringify(this.serverArgs);
588
+ if (!has("FUSION_MCP_TIMEOUT_MS"))
589
+ values.FUSION_MCP_TIMEOUT_MS = "180000";
590
+ if (!has("FUSION_MCP_HOST"))
591
+ values.FUSION_MCP_HOST = "localhost";
592
+ if (!has("FUSION_MCP_PORT"))
593
+ values.FUSION_MCP_PORT = String(this.port());
594
+ if (!Object.keys(values).length)
595
+ return "already-configured";
596
+ const quoted = Object.fromEntries(Object.entries(values).map(([key, value]) => [key, key === "FUSION_MCP_ARGS" ? `'${value}'` : value]));
597
+ const backup = path.join(path.dirname(file), `.env.bak-${new Date().toISOString().replace(/[:.]/g, "")}-fusion-setup`);
598
+ try {
599
+ copyFileSync(file, backup, fsConstants.COPYFILE_EXCL);
600
+ writeEnvValues(file, quoted);
601
+ }
602
+ catch (error) {
603
+ throw new Error(`The Fusion settings couldn't be written to ${file}: ${error instanceof Error ? error.message : String(error)}`);
604
+ }
605
+ Object.assign(this.env, values);
606
+ return { env: "written", backup };
607
+ }
608
+ /** Installs the pinned add-in set to run on startup, the port login item, and this server's missing bridge settings. */
609
+ /** `signal` ends the request: the download and tar are stopped, and nothing more is written once it is aborted. */
610
+ async install(signal) { return this.serial.run(() => this.installMissing(signal), signal); }
611
+ async installMissing(signal) {
612
+ const before = await this.check();
613
+ if (!before.supported)
614
+ throw new Error("Fusion setup installs on macOS only. On Windows, install the add-in from the repository's addon folder by hand.");
615
+ const addin = before.addin.matches_pin && before.addin.run_on_startup ? "already-current" : (await this.installAddin(signal), "installed");
616
+ const portAgent = before.port_agent.installed ? "already-current" : (await this.installPortAgent(signal), "installed");
617
+ let env, envBackup;
618
+ if (!before.env_file)
619
+ env = this.env.FUSION_MCP_COMMAND?.trim() ? "already-configured" : "no-env-file";
620
+ else {
621
+ signal?.throwIfAborted();
622
+ const written = this.writeSettings();
623
+ if (typeof written === "string")
624
+ env = written;
625
+ else {
626
+ env = "written";
627
+ envBackup = written.backup;
628
+ }
629
+ }
630
+ return { ...await this.check(), installed: { addin: addin, port_agent: portAgent, env, ...(envBackup ? { env_backup: envBackup } : {}) } };
631
+ }
632
+ }
633
+ export const FUSION_SETUP_OUTPUT_SCHEMA = {
634
+ type: "object",
635
+ properties: {
636
+ platform: { type: "string" },
637
+ supported: { type: "boolean", description: "Setup installs on macOS only." },
638
+ fusion: { type: "object", properties: { installed: { type: "boolean" }, path: { type: ["string", "null"] } }, required: ["installed", "path"] },
639
+ pin: { type: "object", properties: { repository: { type: "string" }, commit: { type: "string" } }, required: ["repository", "commit"] },
640
+ addin: { type: "object", properties: { path: { type: "string" }, installed: { type: "boolean" }, matches_pin: { type: "boolean" }, run_on_startup: { type: "boolean" } },
641
+ required: ["path", "installed", "matches_pin", "run_on_startup"] },
642
+ port: { type: "integer" },
643
+ port_agent: { type: "object", properties: { path: { type: "string" }, installed: { type: "boolean" } }, required: ["path", "installed"] },
644
+ configured: { type: "boolean", description: "FUSION_MCP_COMMAND is set for this server." },
645
+ env_file: { type: ["string", "null"], description: "The .env this server read at start, when there is one." },
646
+ ready: { type: "boolean", description: "The add-in is at the pin and runs on startup, the port login item is installed and the bridge is configured. Fusion may still need opening: see fusion_mcp_status." },
647
+ message: { type: "string", description: "When not ready: what is missing and what to do, in plain words. Clients show it as it is." },
648
+ installed: { type: "object", description: "install: what it did.", properties: {
649
+ addin: { type: "string", enum: ["installed", "already-current"] }, port_agent: { type: "string", enum: ["installed", "already-current"] },
650
+ env: { type: "string", enum: ["written", "already-configured", "no-env-file"] }, env_backup: { type: "string" }
651
+ } },
652
+ },
653
+ required: ["platform", "supported", "fusion", "pin", "addin", "port", "port_agent", "configured", "env_file", "ready"],
654
+ };