bambu-printer-mcp 1.1.67 → 1.1.68

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 CHANGED
@@ -1457,6 +1457,7 @@ The server carries manufacturing judgment for agents that design or edit a model
1457
1457
  - `fdm_multicolor` -- when several colours or support materials share a print: filament transitions across layers, colour placement, plate scheduling and flushing.
1458
1458
  - `fdm_assembly` -- when a split, accent insert or joint could materially improve the result.
1459
1459
  - `fdm_after_slice` -- a separate review turn after `slice_stl`, before presenting the manufacturing recommendation: keep, revise, or validate one specific uncertainty, using the returned `slicer_result`.
1460
+ - `fdm_slicing` -- for every design or model-editing task, next to `fdm_design`: how this server's configured slicer (`SLICER_TYPE`) orients a model and generates supports, and how to check a choice with a checkpoint `slice_stl`. Its text follows the slicer: Bambu Studio's auto-orient and `enable_support`, or plainly that a slicer here doesn't orient or take support settings.
1460
1461
  - `guidance://fdm/capability-guidance` (resource) -- planning bands and sources for bridges and overhangs, for when one is consequential and there is no sufficiently specific measured capability for the printer, material and profile.
1461
1462
 
1462
1463
  mcp-3D-printer-server serves the same guidance.
@@ -106,6 +106,50 @@ export type BambuNetworkBridgeStatus = {
106
106
  export declare function bambuNetworkCertDir(configDir: string, env?: NodeJS.ProcessEnv): string;
107
107
  export declare function prepareBambuNetworkCertDir(configDir: string, env?: NodeJS.ProcessEnv): string;
108
108
  export declare function defaultBambuNetworkConfigDir(): string;
109
+ /**
110
+ * FULU's Linux host run in a Docker image (BAMBU_NETWORK_BRIDGE_IMAGE), for a Mac or any machine without the
111
+ * x86-64 Linux runtime installed natively. The image holds FULU's host runtime in /fulu (pjarczak_bambu_linux_host
112
+ * and ca-certificates.crt) and the networking plug-in in /plugins (libbambu_networking.so, libBambuSource.so).
113
+ */
114
+ export type BridgeContainer = {
115
+ image: string;
116
+ docker: string;
117
+ dockerHost?: string;
118
+ /** A Colima profile started (never stopped or restarted) when Docker doesn't answer. */
119
+ colima?: {
120
+ executable: string;
121
+ profile: string;
122
+ home?: string;
123
+ };
124
+ };
125
+ export declare function bridgeContainer(env?: NodeJS.ProcessEnv): BridgeContainer | undefined;
126
+ /**
127
+ * Where a print's checked snapshot is written when the host runs in the Docker image: inside the agent's config
128
+ * folder, which the container mounts. The system temporary folder is no good there: Colima shares the home
129
+ * folder but not /tmp or /var/folders, so the host would see an empty folder. Undefined without the image.
130
+ */
131
+ export declare function bridgeSnapshotRoot(env?: NodeJS.ProcessEnv): string | undefined;
132
+ /**
133
+ * The folders the host must see at the same absolute paths: the agent's config folder (the plug-in writes its
134
+ * logs and session there; a host given a log_dir it can't open aborts, FULU #54), the folder print snapshots are
135
+ * written to, and the certificate folder.
136
+ */
137
+ export declare function bridgeContainerMounts(configDir: string, env?: NodeJS.ProcessEnv): string[];
138
+ /**
139
+ * docker run for the host: stdin/stdout are the bridge's framed protocol; the host is piped through cat (FULU #50).
140
+ * `--init` puts an init process first, so the SIGTERM docker forwards on stop reaches the host: a shell as the
141
+ * container's first process ignores it, and the container kept running after the server stopped. `name` lets stop
142
+ * remove the container even when the docker client was killed.
143
+ */
144
+ export declare function bridgeContainerArgs(container: BridgeContainer, mounts: string[], name?: string): string[];
145
+ /**
146
+ * Docker must answer before the host starts. When it doesn't and a Colima profile is configured, that profile is
147
+ * started without changing Docker's global context; a running profile is never stopped or restarted.
148
+ */
149
+ export declare function ensureBridgeContainerRuntime(container: BridgeContainer, timeouts?: {
150
+ infoMs: number;
151
+ startMs: number;
152
+ }): Promise<void>;
109
153
  /**
110
154
  * The client identity FULU's GUI gives the plug-in before agent start
111
155
  * (GUI_App::init_http_extra_header). Through the Linux bridge FULU presents
@@ -127,6 +171,9 @@ export declare function linuxPluginLibraryEnv(env: NodeJS.ProcessEnv, platform:
127
171
  export declare class BambuNetworkBridge {
128
172
  private child?;
129
173
  private commandLine?;
174
+ /** This bridge's own container, when the host runs in the Docker image: unique, so two servers never remove each other's. */
175
+ private readonly containerName;
176
+ private runningContainer?;
130
177
  private stdoutBuffer;
131
178
  private pending;
132
179
  private nextRequestId;
@@ -143,7 +190,7 @@ export declare class BambuNetworkBridge {
143
190
  * so LAN sessions run one at a time, as Bambu Studio connects one printer.
144
191
  */
145
192
  private localSessionTail;
146
- resolveBridgeCommand(override?: string): string;
193
+ resolveBridgeCommand(override?: string, configDir?: string): string;
147
194
  resolveConfigDir(override?: string): string;
148
195
  resolveCountryCode(override?: string): string;
149
196
  getStatus(options?: BambuNetworkBridgeOptions): BambuNetworkBridgeStatus;
@@ -214,7 +261,10 @@ export declare class BambuNetworkBridge {
214
261
  private controlTrace;
215
262
  callWithAgent(method: string, payload?: JsonObject, options?: BambuNetworkBridgeOptions): Promise<unknown>;
216
263
  stop(): Promise<void>;
264
+ /** A start in progress: concurrent callers wait for it, so a cold Docker host is started (and named) once. */
265
+ private starting?;
217
266
  private ensureStarted;
267
+ private startBridge;
218
268
  private handleStdout;
219
269
  private resolvePendingJson;
220
270
  private rememberLog;
@@ -1,4 +1,4 @@
1
- import { spawn } from "node:child_process";
1
+ import { execFile, spawn } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
@@ -65,7 +65,8 @@ const nextControlSequence = () => String(controlSequence = controlSequence >= 29
65
65
  * which the host must already be able to read.
66
66
  */
67
67
  export function bambuNetworkCertDir(configDir, env = process.env) {
68
- return trimEnv(env.BAMBU_NETWORK_CERT_DIR) || path.join(configDir, "cert");
68
+ // Absolute, as every folder given to the host is: a containerized host runs from /plugins, not this server's folder.
69
+ return path.resolve(trimEnv(env.BAMBU_NETWORK_CERT_DIR) || path.join(configDir, "cert"));
69
70
  }
70
71
  export function prepareBambuNetworkCertDir(configDir, env = process.env) {
71
72
  const certDir = bambuNetworkCertDir(configDir, env);
@@ -88,6 +89,176 @@ export function defaultBambuNetworkConfigDir() {
88
89
  function shellQuote(value) {
89
90
  return `'${value.replace(/'/g, "'\\''")}'`;
90
91
  }
92
+ export function bridgeContainer(env = process.env) {
93
+ const image = trimEnv(env.BAMBU_NETWORK_BRIDGE_IMAGE);
94
+ if (!image)
95
+ return undefined;
96
+ const dockerHost = trimEnv(env.BAMBU_NETWORK_BRIDGE_DOCKER_HOST);
97
+ const profile = trimEnv(env.BAMBU_NETWORK_BRIDGE_COLIMA_PROFILE);
98
+ const home = trimEnv(env.BAMBU_NETWORK_BRIDGE_COLIMA_HOME);
99
+ // A Colima profile started with --activate=false leaves Docker's default context alone, so without an explicit
100
+ // host the server talks to that profile's own socket.
101
+ const colimaHome = home || path.join(os.homedir(), ".colima");
102
+ const host = dockerHost || (profile ? `unix://${path.join(colimaHome, profile, "docker.sock")}` : undefined);
103
+ return {
104
+ image,
105
+ docker: trimEnv(env.BAMBU_NETWORK_BRIDGE_DOCKER) || "docker",
106
+ ...(host ? { dockerHost: host } : {}),
107
+ ...(profile ? { colima: { executable: trimEnv(env.BAMBU_NETWORK_BRIDGE_COLIMA) || "colima", profile, ...(home ? { home } : {}) } } : {}),
108
+ };
109
+ }
110
+ /** `--host <socket>` for every docker call, when a host is set. */
111
+ function dockerHostArgs(container) {
112
+ return container.dockerHost ? ["--host", container.dockerHost] : [];
113
+ }
114
+ /** The image's fixed layout: FULU's runtime and the networking plug-in, with the CA bundle cloud calls need. */
115
+ const CONTAINER_ENV = [
116
+ "LD_LIBRARY_PATH=/plugins:/fulu",
117
+ "SSL_CERT_FILE=/fulu/ca-certificates.crt",
118
+ "CURL_CA_BUNDLE=/fulu/ca-certificates.crt",
119
+ "SSL_CERT_DIR=/etc/ssl/certs",
120
+ "PJARCZAK_BAMBU_PLUGIN_DIR=/plugins",
121
+ "PJARCZAK_BAMBU_NETWORK_SO=/plugins/libbambu_networking.so",
122
+ "PJARCZAK_BAMBU_SOURCE_SO=/plugins/libBambuSource.so",
123
+ ];
124
+ /** Set by the server for the host (country, expected network version): passed into the container from its env. */
125
+ const CONTAINER_PASSED_ENV = ["PJARCZAK_BAMBU_COUNTRY_CODE", "PJARCZAK_EXPECTED_BAMBU_NETWORK_VERSION"];
126
+ /** The explicit host command, when one is set: it wins over the Docker image. */
127
+ function explicitBridgeCommand(env = process.env) {
128
+ return trimEnv(env.BAMBU_NETWORK_BRIDGE_COMMAND) || trimEnv(env.FULU_BAMBU_NETWORK_BRIDGE_COMMAND) || trimEnv(env.PJARCZAK_BAMBU_BRIDGE_COMMAND);
129
+ }
130
+ function configuredBridgeConfigDir(env = process.env) {
131
+ return path.resolve(trimEnv(env.BAMBU_NETWORK_CONFIG_DIR) || trimEnv(env.PJARCZAK_BAMBU_PROBE_LOG_DIR) || defaultBambuNetworkConfigDir());
132
+ }
133
+ /**
134
+ * Where a print's checked snapshot is written when the host runs in the Docker image: inside the agent's config
135
+ * folder, which the container mounts. The system temporary folder is no good there: Colima shares the home
136
+ * folder but not /tmp or /var/folders, so the host would see an empty folder. Undefined without the image.
137
+ */
138
+ export function bridgeSnapshotRoot(env = process.env) {
139
+ if (explicitBridgeCommand(env) || !bridgeContainer(env))
140
+ return undefined;
141
+ const root = path.join(configuredBridgeConfigDir(env), "print-snapshots");
142
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
143
+ clearStaleSnapshots(root);
144
+ return root;
145
+ }
146
+ const STALE_SNAPSHOT_MS = 24 * 60 * 60 * 1000;
147
+ const clearedSnapshotRoots = new Set();
148
+ /**
149
+ * A snapshot kept for an upload still running is removed when the server exits; one a killed server left stays
150
+ * here, where no system cleanup reaches it. Once per server, snapshots older than a day are removed.
151
+ */
152
+ function clearStaleSnapshots(root, now = Date.now()) {
153
+ if (clearedSnapshotRoots.has(root))
154
+ return;
155
+ clearedSnapshotRoots.add(root);
156
+ for (const name of fs.readdirSync(root)) {
157
+ if (!name.startsWith("bambu-print-"))
158
+ continue;
159
+ const dir = path.join(root, name);
160
+ try {
161
+ if (now - fs.statSync(dir).mtimeMs > STALE_SNAPSHOT_MS)
162
+ fs.rmSync(dir, { recursive: true, force: true });
163
+ }
164
+ catch { /* gone already */ }
165
+ }
166
+ }
167
+ /**
168
+ * The folders the host must see at the same absolute paths: the agent's config folder (the plug-in writes its
169
+ * logs and session there; a host given a log_dir it can't open aborts, FULU #54), the folder print snapshots are
170
+ * written to, and the certificate folder.
171
+ */
172
+ export function bridgeContainerMounts(configDir, env = process.env) {
173
+ fs.mkdirSync(configDir, { recursive: true });
174
+ const folders = [path.resolve(configDir)];
175
+ const snapshots = bridgeSnapshotRoot(env);
176
+ if (snapshots)
177
+ folders.push(path.resolve(snapshots));
178
+ const certDir = trimEnv(env.BAMBU_NETWORK_CERT_DIR);
179
+ if (certDir) {
180
+ // Made here, so Docker doesn't create it (as root, inside the VM) for the mount.
181
+ fs.mkdirSync(certDir, { recursive: true });
182
+ folders.push(path.resolve(certDir));
183
+ }
184
+ const unique = [...new Set(folders)].filter((dir, _i, all) => !all.some(other => other !== dir && dir.startsWith(other + path.sep)));
185
+ // The host is given these paths as written, so each is mounted there; the VM reads the folder it really is
186
+ // (a symlinked folder's link target need not be shared with the VM).
187
+ return unique.map(dir => {
188
+ let real = dir;
189
+ try {
190
+ real = fs.realpathSync(dir);
191
+ }
192
+ catch { /* created later by the host */ }
193
+ if (dir.includes(":") || real.includes(":"))
194
+ throw new Error(`The FULU container can't mount ${dir}: Docker volume paths can't contain ':'. Move that folder.`);
195
+ return `${real}:${dir}`;
196
+ });
197
+ }
198
+ /**
199
+ * docker run for the host: stdin/stdout are the bridge's framed protocol; the host is piped through cat (FULU #50).
200
+ * `--init` puts an init process first, so the SIGTERM docker forwards on stop reaches the host: a shell as the
201
+ * container's first process ignores it, and the container kept running after the server stopped. `name` lets stop
202
+ * remove the container even when the docker client was killed.
203
+ */
204
+ export function bridgeContainerArgs(container, mounts, name) {
205
+ return [
206
+ ...dockerHostArgs(container),
207
+ "run", "--rm", "-i", "--init", ...(name ? ["--name", name] : []),
208
+ "--platform", "linux/amd64", "--network", "host", "--log-driver=none", "--workdir", "/plugins",
209
+ ...mounts.flatMap(mount => ["-v", `${mount}:rw`]),
210
+ ...CONTAINER_ENV.flatMap(value => ["-e", value]),
211
+ ...CONTAINER_PASSED_ENV.flatMap(name => ["-e", name]),
212
+ container.image,
213
+ "/bin/sh", "-c", "/fulu/pjarczak_bambu_linux_host | cat",
214
+ ];
215
+ }
216
+ const runQuietly = (file, args, options) => new Promise((resolve, reject) => {
217
+ execFile(file, args, { env: options.env ?? process.env, timeout: options.timeout, maxBuffer: 1024 * 1024 }, (error, _stdout, stderr) => {
218
+ if (error)
219
+ reject(Object.assign(error, { stderr: String(stderr ?? "") }));
220
+ else
221
+ resolve();
222
+ });
223
+ });
224
+ /**
225
+ * Docker must answer before the host starts. When it doesn't and a Colima profile is configured, that profile is
226
+ * started without changing Docker's global context; a running profile is never stopped or restarted.
227
+ */
228
+ export async function ensureBridgeContainerRuntime(container, timeouts = { infoMs: 20000, startMs: 600000 }) {
229
+ const info = () => runQuietly(container.docker, [...dockerHostArgs(container), "info"], { timeout: timeouts.infoMs });
230
+ try {
231
+ await info();
232
+ return;
233
+ }
234
+ catch (error) {
235
+ if (!container.colima) {
236
+ throw new Error(`Docker didn't answer (${container.docker}${container.dockerHost ? ` --host ${container.dockerHost}` : ""} info), so the FULU container can't start. Start Docker, or set BAMBU_NETWORK_BRIDGE_COLIMA_PROFILE.`);
237
+ }
238
+ }
239
+ const { executable, profile, home } = container.colima;
240
+ try {
241
+ await runQuietly(executable, ["start", "--profile", profile, "--activate=false"], { env: { ...process.env, ...(home ? { COLIMA_HOME: home } : {}) }, timeout: timeouts.startMs });
242
+ }
243
+ catch (error) {
244
+ const detail = String(error.stderr ?? "").trim().split("\n").slice(-3).join(" ");
245
+ throw new Error(`Colima profile ${profile} didn't start for the FULU container${detail ? `: ${detail}` : "."}`);
246
+ }
247
+ try {
248
+ await info();
249
+ }
250
+ catch {
251
+ throw new Error(`Colima profile ${profile} started, but Docker still doesn't answer at ${container.dockerHost ?? "its default host"}.`);
252
+ }
253
+ }
254
+ /**
255
+ * Stops the bridge's own named container (SIGTERM to the host through --init, two seconds to exit), then removes
256
+ * it. A container that is already gone is fine.
257
+ */
258
+ async function removeBridgeContainer(container, name) {
259
+ await runQuietly(container.docker, [...dockerHostArgs(container), "stop", "--time", "2", name], { timeout: 20000 }).catch(() => undefined);
260
+ await runQuietly(container.docker, [...dockerHostArgs(container), "rm", "-f", name], { timeout: 20000 }).catch(() => undefined);
261
+ }
91
262
  function trimEnv(value) {
92
263
  const trimmed = value?.trim();
93
264
  return trimmed ? trimmed : undefined;
@@ -246,6 +417,8 @@ function assertBridgeOk(value, method) {
246
417
  }
247
418
  export class BambuNetworkBridge {
248
419
  constructor() {
420
+ /** This bridge's own container, when the host runs in the Docker image: unique, so two servers never remove each other's. */
421
+ this.containerName = `bambu-fulu-host-${process.pid}-${randomUUID().slice(0, 8)}`;
249
422
  this.stdoutBuffer = Buffer.alloc(0);
250
423
  this.pending = new Map();
251
424
  this.nextRequestId = 1;
@@ -259,18 +432,19 @@ export class BambuNetworkBridge {
259
432
  */
260
433
  this.localSessionTail = Promise.resolve();
261
434
  }
262
- resolveBridgeCommand(override) {
263
- return (trimEnv(override) ||
264
- trimEnv(process.env.BAMBU_NETWORK_BRIDGE_COMMAND) ||
265
- trimEnv(process.env.FULU_BAMBU_NETWORK_BRIDGE_COMMAND) ||
266
- trimEnv(process.env.PJARCZAK_BAMBU_BRIDGE_COMMAND) ||
267
- "");
435
+ resolveBridgeCommand(override, configDir) {
436
+ const explicit = trimEnv(override) || explicitBridgeCommand();
437
+ if (explicit)
438
+ return explicit;
439
+ const container = bridgeContainer();
440
+ if (!container)
441
+ return "";
442
+ const mounts = bridgeContainerMounts(this.resolveConfigDir(configDir));
443
+ return [container.docker, ...bridgeContainerArgs(container, mounts, this.containerName)].map(shellQuote).join(" ");
268
444
  }
269
445
  resolveConfigDir(override) {
270
- return (trimEnv(override) ||
271
- trimEnv(process.env.BAMBU_NETWORK_CONFIG_DIR) ||
272
- trimEnv(process.env.PJARCZAK_BAMBU_PROBE_LOG_DIR) ||
273
- defaultBambuNetworkConfigDir());
446
+ const dir = trimEnv(override);
447
+ return dir ? path.resolve(dir) : configuredBridgeConfigDir();
274
448
  }
275
449
  resolveCountryCode(override) {
276
450
  return (trimEnv(override) ||
@@ -279,7 +453,7 @@ export class BambuNetworkBridge {
279
453
  "US");
280
454
  }
281
455
  getStatus(options = {}) {
282
- const command = this.resolveBridgeCommand(options.bridgeCommand);
456
+ const command = this.resolveBridgeCommand(options.bridgeCommand, options.configDir);
283
457
  const configDir = this.resolveConfigDir(options.configDir);
284
458
  const countryCode = this.resolveCountryCode(options.countryCode);
285
459
  const runtime = { certDir: bambuNetworkCertDir(configDir) };
@@ -310,14 +484,14 @@ export class BambuNetworkBridge {
310
484
  runtime,
311
485
  note: command
312
486
  ? undefined
313
- : "Set BAMBU_NETWORK_BRIDGE_COMMAND to the FULU OrcaSlicer-bambulab Linux host or macOS/WSL wrapper command.",
487
+ : "Set BAMBU_NETWORK_BRIDGE_COMMAND to the FULU OrcaSlicer-bambulab Linux host or macOS/WSL wrapper command, or BAMBU_NETWORK_BRIDGE_IMAGE to a Docker image holding FULU's Linux host.",
314
488
  };
315
489
  }
316
490
  async request(method, payload = {}, options = {}) {
317
491
  if (!method.trim()) {
318
492
  throw new Error("BambuNetwork bridge method is required.");
319
493
  }
320
- await this.ensureStarted(options.bridgeCommand);
494
+ await this.ensureStarted(options.bridgeCommand, options.configDir);
321
495
  await options.beforeDispatch?.(method);
322
496
  const id = this.nextRequestId++;
323
497
  const requestPayload = Buffer.from(JSON.stringify({ method, payload }), "utf8");
@@ -355,7 +529,7 @@ export class BambuNetworkBridge {
355
529
  });
356
530
  }
357
531
  async ensureAgent(options = {}) {
358
- const command = this.resolveBridgeCommand(options.bridgeCommand);
532
+ const command = this.resolveBridgeCommand(options.bridgeCommand, options.configDir);
359
533
  const configDir = this.resolveConfigDir(options.configDir);
360
534
  const countryCode = this.resolveCountryCode(options.countryCode);
361
535
  const userInfo = trimEnv(options.userInfo) || trimEnv(process.env.BAMBU_NETWORK_USER_INFO) || "";
@@ -787,6 +961,8 @@ export class BambuNetworkBridge {
787
961
  }
788
962
  async stop() {
789
963
  const child = this.child;
964
+ const running = this.runningContainer;
965
+ this.runningContainer = undefined;
790
966
  this.child = undefined;
791
967
  this.commandLine = undefined;
792
968
  this.agentId = undefined;
@@ -798,26 +974,53 @@ export class BambuNetworkBridge {
798
974
  pending.reject(new Error(`FULU BambuNetwork bridge stopped before ${pending.method} completed.`));
799
975
  this.pending.delete(id);
800
976
  }
977
+ // The container goes first: a shell that keeps the docker client as its own child holds the pipes open until
978
+ // the client exits, so waiting for the shell before removing the container could wait for ever.
979
+ if (running)
980
+ await removeBridgeContainer(running, this.containerName);
801
981
  if (child && child.exitCode === null) {
802
982
  await new Promise((resolve) => {
983
+ let settleTimer;
803
984
  const forceTimer = setTimeout(() => {
804
985
  if (child.exitCode === null) {
805
986
  child.kill("SIGKILL");
806
987
  }
988
+ // A descendant can still hold the pipes after the shell is killed: stop waiting for it, and let go of
989
+ // those pipes so nothing it writes reaches a bridge started after this one.
990
+ settleTimer = setTimeout(() => {
991
+ for (const stream of [child.stdin, child.stdout, child.stderr])
992
+ stream.destroy();
993
+ resolve();
994
+ }, 2000);
807
995
  }, 2000);
808
996
  child.once("close", () => {
809
997
  clearTimeout(forceTimer);
998
+ if (settleTimer)
999
+ clearTimeout(settleTimer);
810
1000
  resolve();
811
1001
  });
812
1002
  child.kill("SIGTERM");
813
1003
  });
814
1004
  }
815
1005
  }
816
- async ensureStarted(commandOverride) {
817
- const command = this.resolveBridgeCommand(commandOverride);
1006
+ async ensureStarted(commandOverride, configDir) {
1007
+ while (this.starting)
1008
+ await this.starting.catch(() => undefined);
1009
+ const start = this.startBridge(commandOverride, configDir);
1010
+ this.starting = start;
1011
+ try {
1012
+ await start;
1013
+ }
1014
+ finally {
1015
+ if (this.starting === start)
1016
+ this.starting = undefined;
1017
+ }
1018
+ }
1019
+ async startBridge(commandOverride, configDir) {
1020
+ const command = this.resolveBridgeCommand(commandOverride, configDir);
818
1021
  if (!command) {
819
- throw new Error("BAMBU_NETWORK_BRIDGE_COMMAND is required for FULU BambuNetwork support. " +
820
- "Point it at pjarczak_bambu_linux_host or the OrcaSlicer-bambulab macOS/WSL wrapper.");
1022
+ throw new Error("BAMBU_NETWORK_BRIDGE_COMMAND or BAMBU_NETWORK_BRIDGE_IMAGE is required for FULU BambuNetwork support. " +
1023
+ "Point the command at pjarczak_bambu_linux_host or the OrcaSlicer-bambulab macOS/WSL wrapper, or name a Docker image holding FULU's Linux host.");
821
1024
  }
822
1025
  if (this.child && this.child.exitCode === null && this.commandLine === command) {
823
1026
  return;
@@ -825,6 +1028,13 @@ export class BambuNetworkBridge {
825
1028
  if (this.child && this.commandLine !== command) {
826
1029
  await this.stop();
827
1030
  }
1031
+ const container = trimEnv(commandOverride) || explicitBridgeCommand() ? undefined : bridgeContainer();
1032
+ if (container) {
1033
+ await ensureBridgeContainerRuntime(container);
1034
+ // The docker client can exit (a dropped socket) while its container keeps running under this bridge's name.
1035
+ await removeBridgeContainer(container, this.containerName);
1036
+ this.runningContainer = container;
1037
+ }
828
1038
  const shell = process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "/bin/sh";
829
1039
  const shellArgs = process.platform === "win32"
830
1040
  ? ["/d", "/s", "/c", command]
@@ -126,7 +126,7 @@ export declare const SETUP_FIELDS_OUTPUT_SCHEMA: {
126
126
  properties: {
127
127
  name: {
128
128
  type: string;
129
- enum: ("model" | "slicer" | "host" | "port" | "profiles" | "serial" | "secret" | "slicer-path")[];
129
+ enum: ("model" | "host" | "slicer" | "port" | "profiles" | "serial" | "secret" | "slicer-path")[];
130
130
  };
131
131
  env: {
132
132
  type: string;
@@ -221,7 +221,7 @@ export declare const SETUP_FIELDS_OUTPUT_SCHEMA: {
221
221
  properties: {
222
222
  name: {
223
223
  type: string;
224
- enum: ("model" | "slicer" | "host" | "port" | "profiles" | "serial" | "secret" | "slicer-path")[];
224
+ enum: ("model" | "host" | "slicer" | "port" | "profiles" | "serial" | "secret" | "slicer-path")[];
225
225
  };
226
226
  env: {
227
227
  type: string;
@@ -23,4 +23,18 @@ export declare const FDM_CAPABILITY_RESOURCE: {
23
23
  description: string;
24
24
  };
25
25
  export declare const DESIGN_PROMPTS: DesignPrompt[];
26
+ /**
27
+ * How this server's configured slicer orients, makes supports and checks a slice: the slicer-specific half of a
28
+ * design pass's print plan (the fdm_slicing prompt). `capabilities` is what slice_stl applies on that backend, as
29
+ * counterpart_printer_info reports it.
30
+ */
31
+ export declare function slicingGuidance(slicerType: string, capabilities: {
32
+ supports: boolean;
33
+ orient: boolean;
34
+ }): string;
35
+ export declare const FDM_SLICING_PROMPT: {
36
+ name: string;
37
+ title: string;
38
+ description: string;
39
+ };
26
40
  export declare const SERVER_INSTRUCTIONS: string;
@@ -174,4 +174,30 @@ export const DESIGN_PROMPTS = [
174
174
  { name: "fdm_after_slice", title: "Review a slice", text: FDM_AFTER_SLICE,
175
175
  description: "A separate review turn after a candidate has been sliced, before presenting the manufacturing recommendation: keep, revise, or validate one specific uncertainty." },
176
176
  ];
177
- export const SERVER_INSTRUCTIONS = "When designing or editing a model to print, apply the fdm_design prompt. Add fdm_multicolor when several colours or support materials share a print, fdm_assembly when a split or joint could help, and fdm_after_slice as a separate review turn after a candidate has been sliced, before presenting the manufacturing recommendation. Read " + FDM_CAPABILITY_URI + " when a bridge or overhang is consequential and there is no sufficiently specific measured capability available.";
177
+ const SLICER_NAMES = {
178
+ bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "FULU OrcaSlicer-bambulab",
179
+ "orca-slicer-api": "the remote OrcaSlicer service (orca-slicer-api)", prusaslicer: "PrusaSlicer", cura: "Cura", slic3r: "Slic3r",
180
+ };
181
+ /**
182
+ * How this server's configured slicer orients, makes supports and checks a slice: the slicer-specific half of a
183
+ * design pass's print plan (the fdm_slicing prompt). `capabilities` is what slice_stl applies on that backend, as
184
+ * counterpart_printer_info reports it.
185
+ */
186
+ export function slicingGuidance(slicerType, capabilities) {
187
+ const slicer = SLICER_NAMES[slicerType] ?? slicerType;
188
+ const lines = [
189
+ `How this printer MCP slices. Its slicer is ${slicer}.`,
190
+ "- When they could change a decision, read the printer's loaded filaments with get_printer_filaments and its slicing settings with get_slice_settings.",
191
+ "- To check a consequential choice, slice a checkpoint with slice_stl and read its structured slicer_result (return code, error and each plate's warning), not only the file path. A checkpoint is only a check: the print slices the exported model again.",
192
+ capabilities.orient
193
+ ? `- Orientation: slice_stl with orient true lets ${slicer}'s own auto-orient choose how an STL sits on the bed. It keeps overhang area low; it does not check cantilevers. To see what it chooses, slice the checkpoint with orient true. When a print is oriented this way, don't promise a particular orientation on the bed: the slicer chooses it.`
194
+ : `- Orientation: ${slicer} doesn't auto-orient here. An STL prints in the orientation it's exported in.`,
195
+ capabilities.supports
196
+ ? "- Supports: set enable_support on every slice_stl call. With enable_support true it generates supports in the style support_type names (tree(auto) or normal(auto)); with false it generates none; left out, the process preset's own setting applies. Slice the checkpoint with enable_support set the way the print will be sliced. A print gets the supports it was sliced with: print the sliced file itself, or slice the print with slice_stl and the same enable_support and support_type. print_3mf's own slicing of a file that isn't sliced yet takes no support settings; it uses the process profile's."
197
+ : `- Supports: ${slicer} takes no support settings from slice_stl here: whether it generates supports is its configured profile's own setting. Slice a checkpoint to see what that profile does before modeling any support yourself.`,
198
+ ];
199
+ return lines.join("\n");
200
+ }
201
+ export const FDM_SLICING_PROMPT = { name: "fdm_slicing", title: "How this MCP slices",
202
+ description: "Add to every design or model-editing task: how this server's slicer orients a model and generates supports, and how to check a choice with a checkpoint slice." };
203
+ export const SERVER_INSTRUCTIONS = "When designing or editing a model to print, apply the fdm_design prompt and the fdm_slicing prompt. Add fdm_multicolor when several colours or support materials share a print, fdm_assembly when a split or joint could help, and fdm_after_slice as a separate review turn after a candidate has been sliced, before presenting the manufacturing recommendation. Read " + FDM_CAPABILITY_URI + " when a bridge or overhang is consequential and there is no sufficiently specific measured capability available.";
package/dist/index.js CHANGED
@@ -23,7 +23,7 @@ import path from "path";
23
23
  import { createServer as createHttpServer } from "node:http";
24
24
  import { createHash, randomUUID } from "node:crypto";
25
25
  import { STLManipulator, SLICER_TYPES, normalizeSlicerType, SlicerRunError, } from "./stl/stl-manipulator.js";
26
- import { BambuNetworkBridge, describeBambuNetworkPrintError } from "./bambu-network-bridge.js";
26
+ import { BambuNetworkBridge, bridgeSnapshotRoot, describeBambuNetworkPrintError } from "./bambu-network-bridge.js";
27
27
  import { assertBambuNativeAvailable, bambuNativeControlsAvailable, bambuNativeUnavailableReason, interruptNativeOperations, validateBambuNativeMetadata, buildBambuNativeFanCommand, buildBambuNativeTemperatureCommand, printWithBambuNative, sendCommandWithBambuNative, uploadWithBambuNative, } from "./bambu-native.js";
28
28
  import { importFileViaBambuConnect } from "./bambu-connect.js";
29
29
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
@@ -44,7 +44,7 @@ import { bambuPrinterInfo, bambuSliceCapabilities } from "./counterpart/info.js"
44
44
  import { DISCOVER_OUTPUT_SCHEMA, discoverBambu } from "./counterpart/discovery.js";
45
45
  import { SETUP_FIELDS_OUTPUT_SCHEMA, bambuSetupFields, slicerSetup } from "./counterpart/setup.js";
46
46
  import { PROPOSE_FILAMENTS_INPUT_PROPERTIES, PROPOSE_FILAMENTS_OUTPUT_SCHEMA, NO_COLOUR_NAMES, bambuTrayLabel, loadColourNames, proposeFilaments, spoolName } from "./counterpart/filaments.js";
47
- import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, SERVER_INSTRUCTIONS } from "./design-guidance.js";
47
+ import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, FDM_SLICING_PROMPT, SERVER_INSTRUCTIONS, slicingGuidance } from "./design-guidance.js";
48
48
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
49
49
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
50
50
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
@@ -1614,7 +1614,7 @@ class BambuPrinterMCPServer {
1614
1614
  amsMapping: mapping,
1615
1615
  params: redactPrintParams(params),
1616
1616
  };
1617
- }));
1617
+ }, bridgeSnapshotRoot()));
1618
1618
  }
1619
1619
  async handoff3mfViaBambuConnect(args) {
1620
1620
  if (!args?.three_mf_path) {
@@ -1874,9 +1874,17 @@ class BambuPrinterMCPServer {
1874
1874
  /** The FDM design guidance as MCP prompts: the client decides when to attach each one. */
1875
1875
  setupPromptHandlers() {
1876
1876
  this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
1877
- prompts: DESIGN_PROMPTS.map(({ name, title, description }) => ({ name, title, description })),
1877
+ prompts: [...DESIGN_PROMPTS, FDM_SLICING_PROMPT].map(({ name, title, description }) => ({ name, title, description })),
1878
1878
  }));
1879
1879
  this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
1880
+ if (request.params.name === FDM_SLICING_PROMPT.name) {
1881
+ // The slicer slice_stl uses by default, and what it applies there (as counterpart_printer_info reports it).
1882
+ const slicerType = normalizeSlicerType(DEFAULT_SLICER_TYPE);
1883
+ return {
1884
+ description: FDM_SLICING_PROMPT.description,
1885
+ messages: [{ role: "user", content: { type: "text", text: slicingGuidance(slicerType, bambuSliceCapabilities(slicerType)) } }],
1886
+ };
1887
+ }
1880
1888
  const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name);
1881
1889
  if (!prompt)
1882
1890
  throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${request.params.name}`);
@@ -4416,6 +4424,8 @@ class BambuPrinterMCPServer {
4416
4424
  // Closing the MCP transport aborts its active requests before exit cleanup.
4417
4425
  await this.server.close();
4418
4426
  await this.fusion.close();
4427
+ // The FULU host's container (BAMBU_NETWORK_BRIDGE_IMAGE) is removed with the server, not left running.
4428
+ await this.bambuNetwork.stop();
4419
4429
  this.httpRuntime?.httpServer.close();
4420
4430
  }
4421
4431
  catch (error) {
@@ -1,6 +1,9 @@
1
1
  export declare function cancelPendingPrinterOperations(_host: string, serial: string): void;
2
2
  export declare function withPrinterOperation<T>(_host: string, serial: string, operation: (assertActive: () => void) => Promise<T>): Promise<T>;
3
- /** Inspect and send a private copy, so changes to the user's source cannot change the job. */
4
- export declare function withPrintSnapshot<T>(source: string, operation: (snapshot: string, retainForDispatchedUpload: () => void) => Promise<T>): Promise<T>;
3
+ /**
4
+ * Inspect and send a private copy, so changes to the user's source cannot change the job. `root` is where the copy
5
+ * goes (the system temporary folder unless the bridge host needs it in a folder its container mounts).
6
+ */
7
+ export declare function withPrintSnapshot<T>(source: string, operation: (snapshot: string, retainForDispatchedUpload: () => void) => Promise<T>, root?: string): Promise<T>;
5
8
  export declare function uniquePrintName(filename: string): string;
6
9
  export declare function normalizedRemotePath(filename: string): string;
@@ -36,9 +36,12 @@ export async function withPrinterOperation(_host, serial, operation) {
36
36
  operations.delete(key);
37
37
  }
38
38
  }
39
- /** Inspect and send a private copy, so changes to the user's source cannot change the job. */
40
- export async function withPrintSnapshot(source, operation) {
41
- const directory = await fs.mkdtemp(path.join(os.tmpdir(), "bambu-print-"));
39
+ /**
40
+ * Inspect and send a private copy, so changes to the user's source cannot change the job. `root` is where the copy
41
+ * goes (the system temporary folder unless the bridge host needs it in a folder its container mounts).
42
+ */
43
+ export async function withPrintSnapshot(source, operation, root = os.tmpdir()) {
44
+ const directory = await fs.mkdtemp(path.join(root, "bambu-print-"));
42
45
  const snapshot = path.join(directory, path.basename(source));
43
46
  let retainUntilExit = false;
44
47
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.67",
3
+ "version": "1.1.68",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "main": "dist/index.js",
6
6
  "repository": {
@@ -1,4 +1,4 @@
1
- import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
1
+ import { execFile, spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import fs from "node:fs";
4
4
  import os from "node:os";
@@ -153,7 +153,8 @@ export type BambuNetworkBridgeStatus = {
153
153
  * which the host must already be able to read.
154
154
  */
155
155
  export function bambuNetworkCertDir(configDir: string, env: NodeJS.ProcessEnv = process.env): string {
156
- return trimEnv(env.BAMBU_NETWORK_CERT_DIR) || path.join(configDir, "cert");
156
+ // Absolute, as every folder given to the host is: a containerized host runs from /plugins, not this server's folder.
157
+ return path.resolve(trimEnv(env.BAMBU_NETWORK_CERT_DIR) || path.join(configDir, "cert"));
157
158
  }
158
159
 
159
160
  export function prepareBambuNetworkCertDir(configDir: string, env: NodeJS.ProcessEnv = process.env): string {
@@ -177,6 +178,179 @@ function shellQuote(value: string): string {
177
178
  return `'${value.replace(/'/g, "'\\''")}'`;
178
179
  }
179
180
 
181
+ /**
182
+ * FULU's Linux host run in a Docker image (BAMBU_NETWORK_BRIDGE_IMAGE), for a Mac or any machine without the
183
+ * x86-64 Linux runtime installed natively. The image holds FULU's host runtime in /fulu (pjarczak_bambu_linux_host
184
+ * and ca-certificates.crt) and the networking plug-in in /plugins (libbambu_networking.so, libBambuSource.so).
185
+ */
186
+ export type BridgeContainer = {
187
+ image: string;
188
+ docker: string;
189
+ dockerHost?: string;
190
+ /** A Colima profile started (never stopped or restarted) when Docker doesn't answer. */
191
+ colima?: { executable: string; profile: string; home?: string };
192
+ };
193
+
194
+ export function bridgeContainer(env: NodeJS.ProcessEnv = process.env): BridgeContainer | undefined {
195
+ const image = trimEnv(env.BAMBU_NETWORK_BRIDGE_IMAGE);
196
+ if (!image) return undefined;
197
+ const dockerHost = trimEnv(env.BAMBU_NETWORK_BRIDGE_DOCKER_HOST);
198
+ const profile = trimEnv(env.BAMBU_NETWORK_BRIDGE_COLIMA_PROFILE);
199
+ const home = trimEnv(env.BAMBU_NETWORK_BRIDGE_COLIMA_HOME);
200
+ // A Colima profile started with --activate=false leaves Docker's default context alone, so without an explicit
201
+ // host the server talks to that profile's own socket.
202
+ const colimaHome = home || path.join(os.homedir(), ".colima");
203
+ const host = dockerHost || (profile ? `unix://${path.join(colimaHome, profile, "docker.sock")}` : undefined);
204
+ return {
205
+ image,
206
+ docker: trimEnv(env.BAMBU_NETWORK_BRIDGE_DOCKER) || "docker",
207
+ ...(host ? { dockerHost: host } : {}),
208
+ ...(profile ? { colima: { executable: trimEnv(env.BAMBU_NETWORK_BRIDGE_COLIMA) || "colima", profile, ...(home ? { home } : {}) } } : {}),
209
+ };
210
+ }
211
+
212
+ /** `--host <socket>` for every docker call, when a host is set. */
213
+ function dockerHostArgs(container: BridgeContainer): string[] {
214
+ return container.dockerHost ? ["--host", container.dockerHost] : [];
215
+ }
216
+
217
+ /** The image's fixed layout: FULU's runtime and the networking plug-in, with the CA bundle cloud calls need. */
218
+ const CONTAINER_ENV = [
219
+ "LD_LIBRARY_PATH=/plugins:/fulu",
220
+ "SSL_CERT_FILE=/fulu/ca-certificates.crt",
221
+ "CURL_CA_BUNDLE=/fulu/ca-certificates.crt",
222
+ "SSL_CERT_DIR=/etc/ssl/certs",
223
+ "PJARCZAK_BAMBU_PLUGIN_DIR=/plugins",
224
+ "PJARCZAK_BAMBU_NETWORK_SO=/plugins/libbambu_networking.so",
225
+ "PJARCZAK_BAMBU_SOURCE_SO=/plugins/libBambuSource.so",
226
+ ];
227
+ /** Set by the server for the host (country, expected network version): passed into the container from its env. */
228
+ const CONTAINER_PASSED_ENV = ["PJARCZAK_BAMBU_COUNTRY_CODE", "PJARCZAK_EXPECTED_BAMBU_NETWORK_VERSION"];
229
+
230
+ /** The explicit host command, when one is set: it wins over the Docker image. */
231
+ function explicitBridgeCommand(env: NodeJS.ProcessEnv = process.env): string | undefined {
232
+ return trimEnv(env.BAMBU_NETWORK_BRIDGE_COMMAND) || trimEnv(env.FULU_BAMBU_NETWORK_BRIDGE_COMMAND) || trimEnv(env.PJARCZAK_BAMBU_BRIDGE_COMMAND);
233
+ }
234
+
235
+ function configuredBridgeConfigDir(env: NodeJS.ProcessEnv = process.env): string {
236
+ return path.resolve(trimEnv(env.BAMBU_NETWORK_CONFIG_DIR) || trimEnv(env.PJARCZAK_BAMBU_PROBE_LOG_DIR) || defaultBambuNetworkConfigDir());
237
+ }
238
+
239
+ /**
240
+ * Where a print's checked snapshot is written when the host runs in the Docker image: inside the agent's config
241
+ * folder, which the container mounts. The system temporary folder is no good there: Colima shares the home
242
+ * folder but not /tmp or /var/folders, so the host would see an empty folder. Undefined without the image.
243
+ */
244
+ export function bridgeSnapshotRoot(env: NodeJS.ProcessEnv = process.env): string | undefined {
245
+ if (explicitBridgeCommand(env) || !bridgeContainer(env)) return undefined;
246
+ const root = path.join(configuredBridgeConfigDir(env), "print-snapshots");
247
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
248
+ clearStaleSnapshots(root);
249
+ return root;
250
+ }
251
+
252
+ const STALE_SNAPSHOT_MS = 24 * 60 * 60 * 1000;
253
+ const clearedSnapshotRoots = new Set<string>();
254
+ /**
255
+ * A snapshot kept for an upload still running is removed when the server exits; one a killed server left stays
256
+ * here, where no system cleanup reaches it. Once per server, snapshots older than a day are removed.
257
+ */
258
+ function clearStaleSnapshots(root: string, now = Date.now()): void {
259
+ if (clearedSnapshotRoots.has(root)) return;
260
+ clearedSnapshotRoots.add(root);
261
+ for (const name of fs.readdirSync(root)) {
262
+ if (!name.startsWith("bambu-print-")) continue;
263
+ const dir = path.join(root, name);
264
+ try { if (now - fs.statSync(dir).mtimeMs > STALE_SNAPSHOT_MS) fs.rmSync(dir, { recursive: true, force: true }); } catch { /* gone already */ }
265
+ }
266
+ }
267
+
268
+ /**
269
+ * The folders the host must see at the same absolute paths: the agent's config folder (the plug-in writes its
270
+ * logs and session there; a host given a log_dir it can't open aborts, FULU #54), the folder print snapshots are
271
+ * written to, and the certificate folder.
272
+ */
273
+ export function bridgeContainerMounts(configDir: string, env: NodeJS.ProcessEnv = process.env): string[] {
274
+ fs.mkdirSync(configDir, { recursive: true });
275
+ const folders = [path.resolve(configDir)];
276
+ const snapshots = bridgeSnapshotRoot(env);
277
+ if (snapshots) folders.push(path.resolve(snapshots));
278
+ const certDir = trimEnv(env.BAMBU_NETWORK_CERT_DIR);
279
+ if (certDir) {
280
+ // Made here, so Docker doesn't create it (as root, inside the VM) for the mount.
281
+ fs.mkdirSync(certDir, { recursive: true });
282
+ folders.push(path.resolve(certDir));
283
+ }
284
+ const unique = [...new Set(folders)].filter((dir, _i, all) => !all.some(other => other !== dir && dir.startsWith(other + path.sep)));
285
+ // The host is given these paths as written, so each is mounted there; the VM reads the folder it really is
286
+ // (a symlinked folder's link target need not be shared with the VM).
287
+ return unique.map(dir => {
288
+ let real = dir;
289
+ try { real = fs.realpathSync(dir); } catch { /* created later by the host */ }
290
+ if (dir.includes(":") || real.includes(":")) throw new Error(`The FULU container can't mount ${dir}: Docker volume paths can't contain ':'. Move that folder.`);
291
+ return `${real}:${dir}`;
292
+ });
293
+ }
294
+
295
+ /**
296
+ * docker run for the host: stdin/stdout are the bridge's framed protocol; the host is piped through cat (FULU #50).
297
+ * `--init` puts an init process first, so the SIGTERM docker forwards on stop reaches the host: a shell as the
298
+ * container's first process ignores it, and the container kept running after the server stopped. `name` lets stop
299
+ * remove the container even when the docker client was killed.
300
+ */
301
+ export function bridgeContainerArgs(container: BridgeContainer, mounts: string[], name?: string): string[] {
302
+ return [
303
+ ...dockerHostArgs(container),
304
+ "run", "--rm", "-i", "--init", ...(name ? ["--name", name] : []),
305
+ "--platform", "linux/amd64", "--network", "host", "--log-driver=none", "--workdir", "/plugins",
306
+ ...mounts.flatMap(mount => ["-v", `${mount}:rw`]),
307
+ ...CONTAINER_ENV.flatMap(value => ["-e", value]),
308
+ ...CONTAINER_PASSED_ENV.flatMap(name => ["-e", name]),
309
+ container.image,
310
+ "/bin/sh", "-c", "/fulu/pjarczak_bambu_linux_host | cat",
311
+ ];
312
+ }
313
+
314
+ const runQuietly = (file: string, args: string[], options: { env?: NodeJS.ProcessEnv; timeout: number }) =>
315
+ new Promise<void>((resolve, reject) => {
316
+ execFile(file, args, { env: options.env ?? process.env, timeout: options.timeout, maxBuffer: 1024 * 1024 }, (error, _stdout, stderr) => {
317
+ if (error) reject(Object.assign(error, { stderr: String(stderr ?? "") }));
318
+ else resolve();
319
+ });
320
+ });
321
+
322
+ /**
323
+ * Docker must answer before the host starts. When it doesn't and a Colima profile is configured, that profile is
324
+ * started without changing Docker's global context; a running profile is never stopped or restarted.
325
+ */
326
+ export async function ensureBridgeContainerRuntime(container: BridgeContainer, timeouts = { infoMs: 20_000, startMs: 600_000 }): Promise<void> {
327
+ const info = () => runQuietly(container.docker, [...dockerHostArgs(container), "info"], { timeout: timeouts.infoMs });
328
+ try { await info(); return; } catch (error) {
329
+ if (!container.colima) {
330
+ throw new Error(`Docker didn't answer (${container.docker}${container.dockerHost ? ` --host ${container.dockerHost}` : ""} info), so the FULU container can't start. Start Docker, or set BAMBU_NETWORK_BRIDGE_COLIMA_PROFILE.`);
331
+ }
332
+ }
333
+ const { executable, profile, home } = container.colima!;
334
+ try {
335
+ await runQuietly(executable, ["start", "--profile", profile, "--activate=false"], { env: { ...process.env, ...(home ? { COLIMA_HOME: home } : {}) }, timeout: timeouts.startMs });
336
+ } catch (error) {
337
+ const detail = String((error as { stderr?: string }).stderr ?? "").trim().split("\n").slice(-3).join(" ");
338
+ throw new Error(`Colima profile ${profile} didn't start for the FULU container${detail ? `: ${detail}` : "."}`);
339
+ }
340
+ try { await info(); } catch {
341
+ throw new Error(`Colima profile ${profile} started, but Docker still doesn't answer at ${container.dockerHost ?? "its default host"}.`);
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Stops the bridge's own named container (SIGTERM to the host through --init, two seconds to exit), then removes
347
+ * it. A container that is already gone is fine.
348
+ */
349
+ async function removeBridgeContainer(container: BridgeContainer, name: string): Promise<void> {
350
+ await runQuietly(container.docker, [...dockerHostArgs(container), "stop", "--time", "2", name], { timeout: 20_000 }).catch(() => undefined);
351
+ await runQuietly(container.docker, [...dockerHostArgs(container), "rm", "-f", name], { timeout: 20_000 }).catch(() => undefined);
352
+ }
353
+
180
354
  function trimEnv(value: string | undefined): string | undefined {
181
355
  const trimmed = value?.trim();
182
356
  return trimmed ? trimmed : undefined;
@@ -350,6 +524,9 @@ function assertBridgeOk(value: unknown, method: string): void {
350
524
  export class BambuNetworkBridge {
351
525
  private child?: ChildProcessWithoutNullStreams;
352
526
  private commandLine?: string;
527
+ /** This bridge's own container, when the host runs in the Docker image: unique, so two servers never remove each other's. */
528
+ private readonly containerName = `bambu-fulu-host-${process.pid}-${randomUUID().slice(0, 8)}`;
529
+ private runningContainer?: BridgeContainer;
353
530
  private stdoutBuffer = Buffer.alloc(0);
354
531
  private pending = new Map<number, PendingRequest>();
355
532
  private nextRequestId = 1;
@@ -367,23 +544,18 @@ export class BambuNetworkBridge {
367
544
  */
368
545
  private localSessionTail: Promise<void> = Promise.resolve();
369
546
 
370
- resolveBridgeCommand(override?: string): string {
371
- return (
372
- trimEnv(override) ||
373
- trimEnv(process.env.BAMBU_NETWORK_BRIDGE_COMMAND) ||
374
- trimEnv(process.env.FULU_BAMBU_NETWORK_BRIDGE_COMMAND) ||
375
- trimEnv(process.env.PJARCZAK_BAMBU_BRIDGE_COMMAND) ||
376
- ""
377
- );
547
+ resolveBridgeCommand(override?: string, configDir?: string): string {
548
+ const explicit = trimEnv(override) || explicitBridgeCommand();
549
+ if (explicit) return explicit;
550
+ const container = bridgeContainer();
551
+ if (!container) return "";
552
+ const mounts = bridgeContainerMounts(this.resolveConfigDir(configDir));
553
+ return [container.docker, ...bridgeContainerArgs(container, mounts, this.containerName)].map(shellQuote).join(" ");
378
554
  }
379
555
 
380
556
  resolveConfigDir(override?: string): string {
381
- return (
382
- trimEnv(override) ||
383
- trimEnv(process.env.BAMBU_NETWORK_CONFIG_DIR) ||
384
- trimEnv(process.env.PJARCZAK_BAMBU_PROBE_LOG_DIR) ||
385
- defaultBambuNetworkConfigDir()
386
- );
557
+ const dir = trimEnv(override);
558
+ return dir ? path.resolve(dir) : configuredBridgeConfigDir();
387
559
  }
388
560
 
389
561
  resolveCountryCode(override?: string): string {
@@ -396,7 +568,7 @@ export class BambuNetworkBridge {
396
568
  }
397
569
 
398
570
  getStatus(options: BambuNetworkBridgeOptions = {}): BambuNetworkBridgeStatus {
399
- const command = this.resolveBridgeCommand(options.bridgeCommand);
571
+ const command = this.resolveBridgeCommand(options.bridgeCommand, options.configDir);
400
572
  const configDir = this.resolveConfigDir(options.configDir);
401
573
  const countryCode = this.resolveCountryCode(options.countryCode);
402
574
 
@@ -427,7 +599,7 @@ export class BambuNetworkBridge {
427
599
  runtime,
428
600
  note: command
429
601
  ? undefined
430
- : "Set BAMBU_NETWORK_BRIDGE_COMMAND to the FULU OrcaSlicer-bambulab Linux host or macOS/WSL wrapper command.",
602
+ : "Set BAMBU_NETWORK_BRIDGE_COMMAND to the FULU OrcaSlicer-bambulab Linux host or macOS/WSL wrapper command, or BAMBU_NETWORK_BRIDGE_IMAGE to a Docker image holding FULU's Linux host.",
431
603
  };
432
604
  }
433
605
 
@@ -436,7 +608,7 @@ export class BambuNetworkBridge {
436
608
  throw new Error("BambuNetwork bridge method is required.");
437
609
  }
438
610
 
439
- await this.ensureStarted(options.bridgeCommand);
611
+ await this.ensureStarted(options.bridgeCommand, options.configDir);
440
612
  await options.beforeDispatch?.(method);
441
613
 
442
614
  const id = this.nextRequestId++;
@@ -481,7 +653,7 @@ export class BambuNetworkBridge {
481
653
  agent: number;
482
654
  handshake: unknown;
483
655
  }> {
484
- const command = this.resolveBridgeCommand(options.bridgeCommand);
656
+ const command = this.resolveBridgeCommand(options.bridgeCommand, options.configDir);
485
657
  const configDir = this.resolveConfigDir(options.configDir);
486
658
  const countryCode = this.resolveCountryCode(options.countryCode);
487
659
  const userInfo = trimEnv(options.userInfo) || trimEnv(process.env.BAMBU_NETWORK_USER_INFO) || "";
@@ -939,6 +1111,8 @@ export class BambuNetworkBridge {
939
1111
 
940
1112
  async stop(): Promise<void> {
941
1113
  const child = this.child;
1114
+ const running = this.runningContainer;
1115
+ this.runningContainer = undefined;
942
1116
  this.child = undefined;
943
1117
  this.commandLine = undefined;
944
1118
  this.agentId = undefined;
@@ -952,15 +1126,26 @@ export class BambuNetworkBridge {
952
1126
  this.pending.delete(id);
953
1127
  }
954
1128
 
1129
+ // The container goes first: a shell that keeps the docker client as its own child holds the pipes open until
1130
+ // the client exits, so waiting for the shell before removing the container could wait for ever.
1131
+ if (running) await removeBridgeContainer(running, this.containerName);
955
1132
  if (child && child.exitCode === null) {
956
1133
  await new Promise<void>((resolve) => {
1134
+ let settleTimer: ReturnType<typeof setTimeout> | undefined;
957
1135
  const forceTimer = setTimeout(() => {
958
1136
  if (child.exitCode === null) {
959
1137
  child.kill("SIGKILL");
960
1138
  }
1139
+ // A descendant can still hold the pipes after the shell is killed: stop waiting for it, and let go of
1140
+ // those pipes so nothing it writes reaches a bridge started after this one.
1141
+ settleTimer = setTimeout(() => {
1142
+ for (const stream of [child.stdin, child.stdout, child.stderr]) stream.destroy();
1143
+ resolve();
1144
+ }, 2000);
961
1145
  }, 2000);
962
1146
  child.once("close", () => {
963
1147
  clearTimeout(forceTimer);
1148
+ if (settleTimer) clearTimeout(settleTimer);
964
1149
  resolve();
965
1150
  });
966
1151
  child.kill("SIGTERM");
@@ -968,12 +1153,22 @@ export class BambuNetworkBridge {
968
1153
  }
969
1154
  }
970
1155
 
971
- private async ensureStarted(commandOverride?: string): Promise<void> {
972
- const command = this.resolveBridgeCommand(commandOverride);
1156
+ /** A start in progress: concurrent callers wait for it, so a cold Docker host is started (and named) once. */
1157
+ private starting?: Promise<void>;
1158
+
1159
+ private async ensureStarted(commandOverride?: string, configDir?: string): Promise<void> {
1160
+ while (this.starting) await this.starting.catch(() => undefined);
1161
+ const start = this.startBridge(commandOverride, configDir);
1162
+ this.starting = start;
1163
+ try { await start; } finally { if (this.starting === start) this.starting = undefined; }
1164
+ }
1165
+
1166
+ private async startBridge(commandOverride?: string, configDir?: string): Promise<void> {
1167
+ const command = this.resolveBridgeCommand(commandOverride, configDir);
973
1168
  if (!command) {
974
1169
  throw new Error(
975
- "BAMBU_NETWORK_BRIDGE_COMMAND is required for FULU BambuNetwork support. " +
976
- "Point it at pjarczak_bambu_linux_host or the OrcaSlicer-bambulab macOS/WSL wrapper."
1170
+ "BAMBU_NETWORK_BRIDGE_COMMAND or BAMBU_NETWORK_BRIDGE_IMAGE is required for FULU BambuNetwork support. " +
1171
+ "Point the command at pjarczak_bambu_linux_host or the OrcaSlicer-bambulab macOS/WSL wrapper, or name a Docker image holding FULU's Linux host."
977
1172
  );
978
1173
  }
979
1174
 
@@ -985,6 +1180,14 @@ export class BambuNetworkBridge {
985
1180
  await this.stop();
986
1181
  }
987
1182
 
1183
+ const container = trimEnv(commandOverride) || explicitBridgeCommand() ? undefined : bridgeContainer();
1184
+ if (container) {
1185
+ await ensureBridgeContainerRuntime(container);
1186
+ // The docker client can exit (a dropped socket) while its container keeps running under this bridge's name.
1187
+ await removeBridgeContainer(container, this.containerName);
1188
+ this.runningContainer = container;
1189
+ }
1190
+
988
1191
  const shell = process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "/bin/sh";
989
1192
  const shellArgs = process.platform === "win32"
990
1193
  ? ["/d", "/s", "/c", command]
@@ -185,4 +185,33 @@ export const DESIGN_PROMPTS: DesignPrompt[] = [
185
185
  description: "A separate review turn after a candidate has been sliced, before presenting the manufacturing recommendation: keep, revise, or validate one specific uncertainty." },
186
186
  ];
187
187
 
188
- export const SERVER_INSTRUCTIONS = "When designing or editing a model to print, apply the fdm_design prompt. Add fdm_multicolor when several colours or support materials share a print, fdm_assembly when a split or joint could help, and fdm_after_slice as a separate review turn after a candidate has been sliced, before presenting the manufacturing recommendation. Read " + FDM_CAPABILITY_URI + " when a bridge or overhang is consequential and there is no sufficiently specific measured capability available.";
188
+ const SLICER_NAMES: Record<string, string> = {
189
+ bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "FULU OrcaSlicer-bambulab",
190
+ "orca-slicer-api": "the remote OrcaSlicer service (orca-slicer-api)", prusaslicer: "PrusaSlicer", cura: "Cura", slic3r: "Slic3r",
191
+ };
192
+
193
+ /**
194
+ * How this server's configured slicer orients, makes supports and checks a slice: the slicer-specific half of a
195
+ * design pass's print plan (the fdm_slicing prompt). `capabilities` is what slice_stl applies on that backend, as
196
+ * counterpart_printer_info reports it.
197
+ */
198
+ export function slicingGuidance(slicerType: string, capabilities: { supports: boolean; orient: boolean }): string {
199
+ const slicer = SLICER_NAMES[slicerType] ?? slicerType;
200
+ const lines = [
201
+ `How this printer MCP slices. Its slicer is ${slicer}.`,
202
+ "- When they could change a decision, read the printer's loaded filaments with get_printer_filaments and its slicing settings with get_slice_settings.",
203
+ "- To check a consequential choice, slice a checkpoint with slice_stl and read its structured slicer_result (return code, error and each plate's warning), not only the file path. A checkpoint is only a check: the print slices the exported model again.",
204
+ capabilities.orient
205
+ ? `- Orientation: slice_stl with orient true lets ${slicer}'s own auto-orient choose how an STL sits on the bed. It keeps overhang area low; it does not check cantilevers. To see what it chooses, slice the checkpoint with orient true. When a print is oriented this way, don't promise a particular orientation on the bed: the slicer chooses it.`
206
+ : `- Orientation: ${slicer} doesn't auto-orient here. An STL prints in the orientation it's exported in.`,
207
+ capabilities.supports
208
+ ? "- Supports: set enable_support on every slice_stl call. With enable_support true it generates supports in the style support_type names (tree(auto) or normal(auto)); with false it generates none; left out, the process preset's own setting applies. Slice the checkpoint with enable_support set the way the print will be sliced. A print gets the supports it was sliced with: print the sliced file itself, or slice the print with slice_stl and the same enable_support and support_type. print_3mf's own slicing of a file that isn't sliced yet takes no support settings; it uses the process profile's."
209
+ : `- Supports: ${slicer} takes no support settings from slice_stl here: whether it generates supports is its configured profile's own setting. Slice a checkpoint to see what that profile does before modeling any support yourself.`,
210
+ ];
211
+ return lines.join("\n");
212
+ }
213
+
214
+ export const FDM_SLICING_PROMPT = { name: "fdm_slicing", title: "How this MCP slices",
215
+ description: "Add to every design or model-editing task: how this server's slicer orients a model and generates supports, and how to check a choice with a checkpoint slice." };
216
+
217
+ export const SERVER_INSTRUCTIONS = "When designing or editing a model to print, apply the fdm_design prompt and the fdm_slicing prompt. Add fdm_multicolor when several colours or support materials share a print, fdm_assembly when a split or joint could help, and fdm_after_slice as a separate review turn after a candidate has been sliced, before presenting the manufacturing recommendation. Read " + FDM_CAPABILITY_URI + " when a bridge or overhang is consequential and there is no sufficiently specific measured capability available.";
package/src/index.ts CHANGED
@@ -41,7 +41,7 @@ import {
41
41
  type BambuSliceOptions,
42
42
  type SlicerType,
43
43
  } from "./stl/stl-manipulator.js";
44
- import { BambuNetworkBridge, describeBambuNetworkPrintError, type BambuNetworkBridgeOptions, type BridgeJobUpdate } from "./bambu-network-bridge.js";
44
+ import { BambuNetworkBridge, bridgeSnapshotRoot, describeBambuNetworkPrintError, type BambuNetworkBridgeOptions, type BridgeJobUpdate } from "./bambu-network-bridge.js";
45
45
  import {
46
46
  assertBambuNativeAvailable,
47
47
  bambuNativeControlsAvailable,
@@ -75,7 +75,7 @@ import { bambuPrinterInfo, bambuSliceCapabilities } from "./counterpart/info.js"
75
75
  import { DISCOVER_OUTPUT_SCHEMA, discoverBambu } from "./counterpart/discovery.js";
76
76
  import { SETUP_FIELDS_OUTPUT_SCHEMA, bambuSetupFields, slicerSetup, type SlicerSetup } from "./counterpart/setup.js";
77
77
  import { PROPOSE_FILAMENTS_INPUT_PROPERTIES, PROPOSE_FILAMENTS_OUTPUT_SCHEMA, NO_COLOUR_NAMES, bambuTrayLabel, loadColourNames, proposeFilaments, spoolName, type ColourNames, type ProposalTray } from "./counterpart/filaments.js";
78
- import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, SERVER_INSTRUCTIONS } from "./design-guidance.js";
78
+ import { DESIGN_PROMPTS, FDM_CAPABILITY_GUIDANCE, FDM_CAPABILITY_RESOURCE, FDM_CAPABILITY_URI, FDM_SLICING_PROMPT, SERVER_INSTRUCTIONS, slicingGuidance } from "./design-guidance.js";
79
79
  import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
80
80
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
81
81
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
@@ -2023,7 +2023,7 @@ class BambuPrinterMCPServer {
2023
2023
  amsMapping: mapping,
2024
2024
  params: redactPrintParams(params),
2025
2025
  };
2026
- }));
2026
+ }, bridgeSnapshotRoot()));
2027
2027
  }
2028
2028
 
2029
2029
  private async handoff3mfViaBambuConnect(
@@ -2387,9 +2387,17 @@ class BambuPrinterMCPServer {
2387
2387
  /** The FDM design guidance as MCP prompts: the client decides when to attach each one. */
2388
2388
  setupPromptHandlers() {
2389
2389
  this.server.setRequestHandler(ListPromptsRequestSchema, async () => ({
2390
- prompts: DESIGN_PROMPTS.map(({ name, title, description }) => ({ name, title, description })),
2390
+ prompts: [...DESIGN_PROMPTS, FDM_SLICING_PROMPT].map(({ name, title, description }) => ({ name, title, description })),
2391
2391
  }));
2392
2392
  this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
2393
+ if (request.params.name === FDM_SLICING_PROMPT.name) {
2394
+ // The slicer slice_stl uses by default, and what it applies there (as counterpart_printer_info reports it).
2395
+ const slicerType = normalizeSlicerType(DEFAULT_SLICER_TYPE);
2396
+ return {
2397
+ description: FDM_SLICING_PROMPT.description,
2398
+ messages: [{ role: "user" as const, content: { type: "text" as const, text: slicingGuidance(slicerType, bambuSliceCapabilities(slicerType)) } }],
2399
+ };
2400
+ }
2393
2401
  const prompt = DESIGN_PROMPTS.find(item => item.name === request.params.name);
2394
2402
  if (!prompt) throw new McpError(ErrorCode.InvalidParams, `Unknown prompt: ${request.params.name}`);
2395
2403
  return {
@@ -5161,6 +5169,8 @@ class BambuPrinterMCPServer {
5161
5169
  // Closing the MCP transport aborts its active requests before exit cleanup.
5162
5170
  await this.server.close();
5163
5171
  await this.fusion.close();
5172
+ // The FULU host's container (BAMBU_NETWORK_BRIDGE_IMAGE) is removed with the server, not left running.
5173
+ await this.bambuNetwork.stop();
5164
5174
  this.httpRuntime?.httpServer.close();
5165
5175
  } catch (error) {
5166
5176
  console.error("[MCP Shutdown]", error);
@@ -29,9 +29,12 @@ export async function withPrinterOperation<T>(_host: string, serial: string, ope
29
29
  finally { if (operations.get(key) === next) operations.delete(key); }
30
30
  }
31
31
 
32
- /** Inspect and send a private copy, so changes to the user's source cannot change the job. */
33
- export async function withPrintSnapshot<T>(source: string, operation: (snapshot: string, retainForDispatchedUpload: () => void) => Promise<T>): Promise<T> {
34
- const directory = await fs.mkdtemp(path.join(os.tmpdir(), "bambu-print-"));
32
+ /**
33
+ * Inspect and send a private copy, so changes to the user's source cannot change the job. `root` is where the copy
34
+ * goes (the system temporary folder unless the bridge host needs it in a folder its container mounts).
35
+ */
36
+ export async function withPrintSnapshot<T>(source: string, operation: (snapshot: string, retainForDispatchedUpload: () => void) => Promise<T>, root = os.tmpdir()): Promise<T> {
37
+ const directory = await fs.mkdtemp(path.join(root, "bambu-print-"));
35
38
  const snapshot = path.join(directory, path.basename(source));
36
39
  let retainUntilExit = false;
37
40
  try {