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