bambu-printer-mcp 1.1.89 → 1.1.90

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.
@@ -1,11 +1,11 @@
1
- """Independent geometry checks, six orthographic views and triangle-exact surface separation."""
1
+ """Independent geometry checks, six orthographic views, a perspective view and triangle-exact surface separation."""
2
2
  from pathlib import Path
3
3
  import json
4
4
  import math
5
5
  import numpy as np
6
6
  import trimesh
7
7
  import manifold3d as mf
8
- from PIL import Image, ImageDraw
8
+ from PIL import Image, ImageDraw, ImageFont
9
9
 
10
10
 
11
11
  def mesh(file):
@@ -31,6 +31,9 @@ def inspect(request):
31
31
  step_bounds = [list(sb.min), list(sb.max)] if sb is not None else None
32
32
  checks = {'watertight': bool(m.is_watertight), 'winding_consistent': bool(m.is_winding_consistent), 'positive_volume': bool(m.is_volume),
33
33
  'manifold': mm.status() == mf.Error.NoError, 'step_valid': bool(step.is_valid) if step is not None else None,
34
+ # A solid design whose STEP holds only shells (seen after rounding a sketch by offsetting it out and
35
+ # back) is not the B-rep it claims to be, however good its mesh looks.
36
+ 'step_solids': bool(len(step.solids()) >= 1) if step is not None else None,
34
37
  'stl_step_bounds_agree': bool(np.max(np.abs(m.bounds - np.array(step_bounds))) <= 0.2) if step_bounds is not None else None}
35
38
  try:
36
39
  assembly = bodies(step, request) if step is not None else None
@@ -287,12 +290,127 @@ def render(m, folder):
287
290
  draw.line([tuple(xy[i, j]), tuple(xy[i, (j + 1) % 3])], fill=(27, 62, 70), width=2)
288
291
  draw.text((24, 22), name + ' | ' + ', '.join(f'{x:.2f}' for x in m.extents) + ' mm', fill='black')
289
292
  file = folder / (name + '.png'); im.save(file); paths[name] = str(file); images.append(im)
290
- sheet = Image.new('RGB', (1600, 2400), 'white')
291
- for i, im in enumerate(images): sheet.paste(im, ((i % 2) * 800, (i // 2) * 800))
293
+ # The view a person judges a shape from: three-quarter, in perspective, large on the sheet beside the six.
294
+ big = perspective(m, 1600)
295
+ label = 'perspective, from the front right and above | ' + ' x '.join(f'{x:.1f}' for x in m.extents) + ' mm'
296
+ ImageDraw.Draw(big).text((28, 24), label, fill='black', font=ImageFont.load_default(size=30))
297
+ file = folder / 'perspective.png'; big.resize((800, 800), Image.LANCZOS).save(file); paths['perspective'] = str(file)
298
+ sheet = Image.new('RGB', (1600 + 2 * 534, 1602), 'white')
299
+ sheet.paste(big, (0, 0))
300
+ for i, im in enumerate(images): sheet.paste(im.resize((534, 534), Image.LANCZOS), (1600 + (i % 2) * 534, (i // 2) * 534))
292
301
  sheet.save(folder / 'contact.png'); paths['contact'] = str(folder / 'contact.png')
293
302
  return paths
294
303
 
295
304
 
305
+ def perspective(m, size=1600, azimuth=35.0, elevation=26.0):
306
+ """A three-quarter view in true perspective with a depth buffer (large flat faces defeat depth sorting at an
307
+ angle). Seen from the front (-Y) turned `azimuth` degrees towards +X and raised `elevation` degrees, through a
308
+ 28 degree lens, framed to fill the picture. Smooth shading across facets that meet within 40 degrees, so a
309
+ lofted or filleted surface reads as one surface and a real edge stays an edge; outlines where the surface steps
310
+ in depth or creases by more than 35 degrees. Every array operation is over all triangles at once."""
311
+ V, F, N = np.asarray(m.vertices, float), np.asarray(m.faces), np.asarray(m.face_normals, float)
312
+ centre, radius = m.bounds.mean(axis=0), max(float(np.linalg.norm(m.extents)) / 2, 1e-9)
313
+ az, el = math.radians(azimuth), math.radians(elevation)
314
+ to_eye = np.array([math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)])
315
+ d = -to_eye
316
+ r = np.cross(d, [0, 0, 1.0]); r /= np.linalg.norm(r)
317
+ u = np.cross(r, d)
318
+ eye = centre + to_eye * radius / math.sin(math.radians(14)) * 1.06
319
+ q = V - eye
320
+ zc = q @ d
321
+ tx, ty = (q @ r) / zc, (q @ u) / zc
322
+ zoom = 0.86 * size / max(float(np.ptp(tx)), float(np.ptp(ty)), 1e-12)
323
+ X = size / 2 + zoom * (tx - (tx.min() + tx.max()) / 2)
324
+ Y = size / 2 - zoom * (ty - (ty.min() + ty.max()) / 2)
325
+ W = 1.0 / zc # inverse depth is affine across a triangle on screen
326
+ # light: key from the upper left of the viewer, a weaker fill from the right
327
+ key = -0.55 * r + 0.75 * u - 0.45 * d; key /= np.linalg.norm(key)
328
+ fill = 0.8 * r + 0.15 * u - 0.6 * d; fill /= np.linalg.norm(fill)
329
+ lum = lambda n: 0.26 + 0.58 * np.clip(n @ key, 0, None) + 0.2 * np.clip(n @ fill, 0, None)
330
+ vn = np.asarray(m.vertex_normals, float)
331
+ corner = vn[F] # (T, 3, 3): use the vertex normal only where it is this face's
332
+ smooth = np.einsum('tkj,tj->tk', corner, N) > 0.766
333
+ L = np.where(smooth, lum(corner.reshape(-1, 3)).reshape(-1, 3), lum(N)[:, None])
334
+ facing = np.einsum('ij,ij->i', N, V[F].mean(axis=1) - eye) < 0
335
+ if m.is_watertight:
336
+ front = facing # a closed solid: its back faces are never seen
337
+ else: # an open scan is seen from both sides: light the side that faces the eye
338
+ front = np.ones(len(F), bool)
339
+ L = np.where(facing[:, None], L, np.where(smooth, lum(-corner.reshape(-1, 3)).reshape(-1, 3), lum(-N)[:, None]))
340
+ N = np.where(facing[:, None], N, -N)
341
+ x, y, w, L = X[F][front], Y[F][front], W[F][front], L[front]
342
+ Nf = N[front]
343
+ det = (x[:, 1] - x[:, 0]) * (y[:, 2] - y[:, 0]) - (x[:, 2] - x[:, 0]) * (y[:, 1] - y[:, 0])
344
+ ok = np.abs(det) > 1e-12
345
+ x, y, w, L, Nf, det = x[ok], y[ok], w[ok], L[ok], Nf[ok], det[ok]
346
+ if not len(x): # nothing faces the eye (a mesh seen exactly edge-on)
347
+ return Image.new('RGB', (size, size), '#f5f5f2')
348
+ def plane(a): # a(px, py) = a0 + gx (px - x0) + gy (py - y0)
349
+ gx = ((a[:, 1] - a[:, 0]) * (y[:, 2] - y[:, 0]) - (a[:, 2] - a[:, 0]) * (y[:, 1] - y[:, 0])) / det
350
+ gy = ((a[:, 2] - a[:, 0]) * (x[:, 1] - x[:, 0]) - (a[:, 1] - a[:, 0]) * (x[:, 2] - x[:, 0])) / det
351
+ return a[:, 0], gx, gy
352
+ w0, wx, wy = plane(w)
353
+ l0, lx, ly = plane(L)
354
+ # rows each triangle covers (pixel centres at +0.5), then the columns of each row
355
+ r0 = np.clip(np.ceil(y.min(axis=1) - 0.5), 0, size - 1).astype(np.int64)
356
+ r1 = np.clip(np.floor(y.max(axis=1) - 0.5), 0, size - 1).astype(np.int64)
357
+ rows = np.maximum(r1 - r0 + 1, 0)
358
+ t = np.repeat(np.arange(len(x)), rows)
359
+ row = r0[t] + (np.arange(len(t)) - np.repeat(np.cumsum(rows) - rows, rows))
360
+ yc = row + 0.5
361
+ lo, hi = np.full(len(t), np.inf), np.full(len(t), -np.inf)
362
+ for a, b in ((0, 1), (1, 2), (2, 0)):
363
+ ya, yb, xa, xb = y[t, a], y[t, b], x[t, a], x[t, b]
364
+ crosses = ((ya <= yc) & (yc < yb)) | ((yb <= yc) & (yc < ya))
365
+ xi = xa + (yc - ya) * (xb - xa) / np.where(crosses, yb - ya, 1.0)
366
+ lo, hi = np.where(crosses, np.minimum(lo, xi), lo), np.where(crosses, np.maximum(hi, xi), hi)
367
+ c0 = np.clip(np.ceil(np.where(np.isfinite(lo), lo, 0) - 0.5), 0, size - 1).astype(np.int64)
368
+ c1 = np.clip(np.floor(np.where(np.isfinite(hi), hi, -1) - 0.5), -1, size - 1).astype(np.int64)
369
+ cols = np.maximum(c1 - c0 + 1, 0)
370
+ cols[~np.isfinite(lo)] = 0
371
+ k = np.repeat(np.arange(len(t), dtype=np.int32), cols)
372
+ px = (c0[k] + (np.arange(len(k)) - np.repeat(np.cumsum(cols) - cols, cols))).astype(np.int32)
373
+ tri, py = t[k].astype(np.int32), row[k].astype(np.int32)
374
+ del k
375
+ dx, dy = (px + 0.5 - x[tri, 0]).astype(np.float32), (py + 0.5 - y[tri, 0]).astype(np.float32)
376
+ wv = w0[tri] + wx[tri] * dx + wy[tri] * dy
377
+ pix = py.astype(np.int64) * size + px
378
+ del px, py
379
+ zbuf = np.zeros(size * size)
380
+ np.maximum.at(zbuf, pix, wv)
381
+ win = wv >= zbuf[pix]
382
+ tid = np.full(size * size, -1, dtype=np.int32)
383
+ tid[pix[win]] = tri[win]
384
+ shade = np.zeros(size * size, dtype=np.float32)
385
+ shade[pix[win]] = np.clip(l0[tri[win]] + lx[tri[win]] * dx[win] + ly[tri[win]] * dy[win], 0, 1)
386
+ del tri, dx, dy, wv, pix, win
387
+ tid, zbuf, shade = tid.reshape(size, size), zbuf.reshape(size, size), shade.reshape(size, size)
388
+ solid = tid >= 0
389
+ ti = np.where(solid, tid, 0)
390
+ gx, gy, nrm = wx[ti], wy[ti], Nf[ti].astype(np.float32)
391
+ edge = np.zeros((size, size), bool)
392
+ for sy, sx in ((0, 1), (1, 0), (0, -1), (-1, 0)):
393
+ other = np.roll(solid, (-sy, -sx), axis=(0, 1))
394
+ wj = np.roll(zbuf, (-sy, -sx), axis=(0, 1))
395
+ nj = np.roll(nrm, (-sy, -sx), axis=(0, 1))
396
+ inside = np.ones((size, size), bool)
397
+ if sx == 1: inside[:, -1] = False
398
+ if sx == -1: inside[:, 0] = False
399
+ if sy == 1: inside[-1, :] = False
400
+ if sy == -1: inside[0, :] = False
401
+ step = np.abs(wj - (zbuf + gx * sx + gy * sy)) > 1.6 * zbuf / zoom
402
+ crease = np.einsum('ijk,ijk->ij', nrm, nj) < math.cos(math.radians(35))
403
+ edge |= solid & inside & ((~other) | (other & (wj < zbuf) & step) | (other & crease & (sx + sy > 0)))
404
+ edge |= np.roll(edge, 1, axis=0) & solid | np.roll(edge, 1, axis=1) & solid # two pixels wide before scaling down
405
+ del gx, gy, nrm, ti
406
+ rgb = np.empty((size, size, 3), dtype=np.float32)
407
+ ramp = np.linspace(0, 1, size)[:, None]
408
+ for c, (base, dark, top, bottom) in enumerate(((79, 22, 247, 240), (166, 46, 247, 240), (186, 52, 244, 238))):
409
+ rgb[:, :, c] = np.where(solid, base * shade + dark * (1 - shade), top + (bottom - top) * ramp)
410
+ rgb[edge] = (27, 62, 70)
411
+ return Image.fromarray(rgb.clip(0, 255).astype(np.uint8), 'RGB')
412
+
413
+
296
414
  def triangle_distance(a, b):
297
415
  """Distance for one A triangle against N B triangles: vertex/face and all 9 edge pairs."""
298
416
  n = len(b)
@@ -207,6 +207,9 @@ ${r.readonly
207
207
  (file) => !(r.inputs ?? []).includes(file),
208
208
  ))
209
209
  args.push("--ro-bind", file, file);
210
+ // bubblewrap makes the folders above each bind on its own root tmpfs; left writable (bubblewrap 0.11), a script
211
+ // could create files beside the job folder (never on the host) and setup's forbidden-write proof fails
212
+ args.push("--remount-ro", "/");
210
213
  args.push("--chdir", r.job);
211
214
  return { command: "bwrap", args };
212
215
  }
package/src/cad/worker.py CHANGED
@@ -2,6 +2,7 @@
2
2
  Inspection is a fresh process: user stdout, globals and check claims are never receipts.
3
3
  """
4
4
  import ast
5
+ import errno
5
6
  import json
6
7
  import math
7
8
  import os
@@ -142,6 +143,9 @@ def main():
142
143
  else: os.listdir(target)
143
144
  except (PermissionError, FileNotFoundError):
144
145
  pass
146
+ except OSError as e:
147
+ # A read-only sandbox root refuses the write with EROFS: that is a rejection too.
148
+ if e.errno != errno.EROFS: raise
145
149
  else:
146
150
  raise RuntimeError('CAD confinement did not reject ' + operation)
147
151
  sock = socket.socket()
package/src/cad-engine.ts CHANGED
@@ -33,10 +33,18 @@ export interface CadStatus {
33
33
  platform: string;
34
34
  storage: CadStorage;
35
35
  error?: string;
36
+ /** Set when this call re-verified a runtime that only the engine's own sources had changed under. */
37
+ reverified?: string;
36
38
  }
37
39
  export class CadEngine {
38
40
  private readonly system: CadSystem;
39
41
  readonly dataDir: string;
42
+ private reverifyFailure?: { fingerprint: string; error: string };
43
+ /** How long a re-check waits for another CAD operation to let go of the engine (Counterpart reads status with 30 s). */
44
+ busyWaitMs = 25_000;
45
+ /** Within this window a freed engine is re-checked here; later this call only waits for the other call's result, so
46
+ * a wait plus a ~17 s re-check cannot overrun the status deadline. */
47
+ busyRetryMs = 5_000;
40
48
  constructor(private readonly options: CadOptions) {
41
49
  this.system = options.system ?? defaultCadSystem;
42
50
  this.dataDir = path.resolve(
@@ -207,7 +215,7 @@ export class CadEngine {
207
215
  if (args.install !== true)
208
216
  return {
209
217
  supported: ["darwin", "linux"].includes(this.system.platform),
210
- ...(await this.status()),
218
+ ...(await this.ensureReady(signal)),
211
219
  };
212
220
  if (!["darwin", "linux"].includes(this.system.platform))
213
221
  throw new CadRefusal(
@@ -264,54 +272,8 @@ export class CadEngine {
264
272
  );
265
273
  throw e;
266
274
  }
267
- await this.system.run(
268
- python,
269
- ["-I", "-B", path.join(ASSETS, "worker.py"), "imports"],
270
- { ...opts, timeoutMs: 120_000 },
271
- );
272
- const job = await fs.mkdtemp(path.join(this.dataDir, "verify-"));
273
- const request = path.join(job, "request.json");
274
- await fs.writeFile(
275
- request,
276
- JSON.stringify({ output: job, home: os.homedir() }),
277
- { mode: 0o600 },
278
- );
279
- const result = JSON.parse(
280
- (
281
- await this.confined(
282
- "smoke",
283
- request,
284
- job,
285
- [request],
286
- 180_000,
287
- signal,
288
- )
289
- ).stdout,
290
- );
291
- if (
292
- result.build123d !== BUILD123D ||
293
- !result.watertight ||
294
- !result.manifold ||
295
- !result.step_valid ||
296
- result.solid_count !== 1
297
- )
298
- throw new Error("CAD setup's confined STL/STEP round trip failed.");
299
- const storage = {
300
- installed_bytes: await measureEnvironment(this.dataDir),
301
- measured_at: new Date().toISOString(),
302
- };
303
- await fs.writeFile(
304
- path.join(this.dataDir, "ready.json"),
305
- JSON.stringify({
306
- build123d: BUILD123D,
307
- platform: this.system.platform,
308
- verifiedAt: new Date().toISOString(),
309
- fingerprint: await this.fingerprint(),
310
- dataDevice: (await fs.stat(this.dataDir)).dev,
311
- storage,
312
- }),
313
- { mode: 0o600 },
314
- );
275
+ this.reverifyFailure = undefined;
276
+ await this.verify(opts, signal);
315
277
  return {
316
278
  supported: true,
317
279
  ...(await this.status()),
@@ -324,6 +286,203 @@ export class CadEngine {
324
286
  signal,
325
287
  );
326
288
  }
289
+ /**
290
+ * The proof setup ends with: the runtime's imports, then the confined build, STL and STEP round trip, then the ready
291
+ * marker with the engine fingerprint and the runtime identity it proved. Shared by cad_setup and the automatic
292
+ * re-verification after an update that changed only the engine's sources.
293
+ */
294
+ private async verify(
295
+ opts: { env: NodeJS.ProcessEnv; cwd: string; signal?: AbortSignal; timeoutMs: number },
296
+ signal?: AbortSignal,
297
+ measured?: unknown,
298
+ ): Promise<void> {
299
+ // Setup proves the fresh install's imports outside confinement first; a re-check of an unchanged runtime relies on
300
+ // the confined round trip, which imports the same libraries.
301
+ if (measured === undefined) {
302
+ const python = path.join(this.dataDir, "runtime", "bin", "python");
303
+ await this.system.run(
304
+ python,
305
+ ["-I", "-B", path.join(ASSETS, "worker.py"), "imports"],
306
+ { ...opts, timeoutMs: 120_000 },
307
+ );
308
+ }
309
+ const job = await fs.mkdtemp(path.join(this.dataDir, "verify-"));
310
+ const request = path.join(job, "request.json");
311
+ await fs.writeFile(
312
+ request,
313
+ JSON.stringify({ output: job, home: os.homedir() }),
314
+ { mode: 0o600 },
315
+ );
316
+ const result = JSON.parse(
317
+ (
318
+ await this.confined(
319
+ "smoke",
320
+ request,
321
+ job,
322
+ [request],
323
+ 180_000,
324
+ signal,
325
+ )
326
+ ).stdout,
327
+ );
328
+ if (
329
+ result.build123d !== BUILD123D ||
330
+ !result.watertight ||
331
+ !result.manifold ||
332
+ !result.step_valid ||
333
+ result.solid_count !== 1
334
+ )
335
+ throw new Error("CAD setup's confined STL/STEP round trip failed.");
336
+ // A re-check of an unchanged runtime keeps the size setup measured instead of walking 1.4 GB again.
337
+ const storage = measured ?? {
338
+ installed_bytes: await measureEnvironment(this.dataDir),
339
+ measured_at: new Date().toISOString(),
340
+ };
341
+ await fs.writeFile(
342
+ path.join(this.dataDir, "ready.json"),
343
+ JSON.stringify({
344
+ build123d: BUILD123D,
345
+ platform: this.system.platform,
346
+ verifiedAt: new Date().toISOString(),
347
+ fingerprint: await this.fingerprint(),
348
+ runtime: await this.runtimeIdentity(),
349
+ dataDevice: (await fs.stat(this.dataDir)).dev,
350
+ storage,
351
+ }),
352
+ { mode: 0o600 },
353
+ );
354
+ }
355
+ /**
356
+ * Re-verifies without installing when only the engine's own sources changed since the last proof (#609): the
357
+ * marker matches this platform, build123d and data device, its engine fingerprint differs, and the installed
358
+ * runtime still matches requirements.lock exactly with the same interpreter. Anything else, including a changed
359
+ * lock, still needs cad_setup with install: true. A failed re-verification is reported, not retried, until the
360
+ * engine changes again or setup runs.
361
+ */
362
+ async ensureReady(signal?: AbortSignal, deadline?: number): Promise<CadStatus> {
363
+ const status = await this.status();
364
+ if (status.ready || !status.configured) return status;
365
+ const fingerprint = await this.fingerprint();
366
+ if (!(await this.onlyEngineChanged(fingerprint))) return status;
367
+ if (this.reverifyFailure?.fingerprint === fingerprint)
368
+ return { ...status, error: this.reverifyFailure.error };
369
+ const started = performance.now();
370
+ // A cad_run or cad_check_fit passes its own deadline: the re-check, its waiting included, stays inside timeout_ms.
371
+ const outOfTime = {
372
+ ...status,
373
+ error:
374
+ "The automatic re-check after this MCP's update did not finish within this call's timeout_ms; the next call runs it again.",
375
+ };
376
+ if (deadline !== undefined && deadline - started < 1) return outOfTime;
377
+ const limit = deadline === undefined ? undefined : AbortSignal.timeout(Math.ceil(deadline - started));
378
+ const bounded = limit ? (signal ? AbortSignal.any([signal, limit]) : limit) : signal;
379
+ const recheck = () =>
380
+ this.exclusive(
381
+ async () => {
382
+ if ((await this.status()).ready) return;
383
+ const env = this.environment(this.dataDir);
384
+ await fs.mkdir(env.TMPDIR!, { recursive: true });
385
+ const previous = await fs
386
+ .readFile(path.join(this.dataDir, "ready.json"), "utf8")
387
+ .then((text) => JSON.parse(text).storage, () => undefined);
388
+ await this.verify({ env, cwd: this.dataDir, signal: bounded, timeoutMs: 600_000 }, bounded, previous ?? null);
389
+ },
390
+ "setup",
391
+ bounded,
392
+ );
393
+ try {
394
+ // Another call may hold the engine, usually this same re-check from another process (Counterpart reading
395
+ // cad_status while the design worker's first cad_run starts): wait for it and try again, never call it a failure.
396
+ const waited = performance.now();
397
+ for (let attempt = true, until = Math.min(waited + this.busyWaitMs, deadline ?? Infinity); ; ) {
398
+ try {
399
+ if (attempt) {
400
+ await recheck();
401
+ break;
402
+ }
403
+ throw new CadRefusal("cad-setup-busy", "waiting for the other CAD operation's result");
404
+ } catch (e) {
405
+ if (!(e instanceof CadRefusal && e.code === "cad-setup-busy")) throw e;
406
+ signal?.throwIfAborted();
407
+ if (limit?.aborted) return outOfTime;
408
+ if ((await this.status()).ready) break;
409
+ attempt = performance.now() - waited < this.busyRetryMs;
410
+ if (performance.now() >= until)
411
+ return {
412
+ ...(await this.status()),
413
+ error:
414
+ "Another CAD operation is running; this MCP re-checks its unchanged runtime by itself when that finishes. Ask again shortly.",
415
+ };
416
+ await new Promise((resolve) => setTimeout(resolve, 500));
417
+ }
418
+ }
419
+ } catch (e) {
420
+ signal?.throwIfAborted();
421
+ if (limit?.aborted) return outOfTime; // ran out of this call's time: not a failed re-check, never cached
422
+ const reason = e instanceof Error ? e.message : String(e);
423
+ this.reverifyFailure = {
424
+ fingerprint,
425
+ error: `The automatic re-check after this MCP's update failed (${reason.slice(0, 300)}). Run cad_setup with install: true.`,
426
+ };
427
+ return { ...(await this.status()), error: this.reverifyFailure.error };
428
+ }
429
+ const after = await this.status();
430
+ return after.ready
431
+ ? {
432
+ ...after,
433
+ reverified: `Re-checked automatically after an update to the engine (${Math.round((performance.now() - started) / 1000)} s): the installed runtime was unchanged; confined import, build, STL and STEP round trip passed.`,
434
+ }
435
+ : after;
436
+ }
437
+ private async onlyEngineChanged(fingerprint: string): Promise<boolean> {
438
+ try {
439
+ const marker = JSON.parse(await fs.readFile(path.join(this.dataDir, "ready.json"), "utf8"));
440
+ if (
441
+ marker.build123d !== BUILD123D ||
442
+ marker.platform !== this.system.platform ||
443
+ marker.dataDevice !== (await fs.stat(this.dataDir)).dev ||
444
+ typeof marker.fingerprint !== "string" ||
445
+ marker.fingerprint === fingerprint
446
+ )
447
+ return false;
448
+ const runtime = await this.runtimeIdentity();
449
+ if (!runtime.matchesLock) return false;
450
+ // Markers from engines without the runtime record (bambu-printer-mcp 1.1.89, mcp-3D-printer-server 1.2.71 and
451
+ // earlier) qualify by the exact package match; the re-run proof decides the rest.
452
+ if (marker.runtime && (marker.runtime.interpreter !== runtime.interpreter || marker.runtime.lock_sha256 !== runtime.lock_sha256))
453
+ return false;
454
+ return true;
455
+ } catch {
456
+ return false;
457
+ }
458
+ }
459
+ /** The interpreter the venv runs and whether its installed distributions are exactly requirements.lock's pins. */
460
+ private async runtimeIdentity(): Promise<{ interpreter: string; lock_sha256: string; matchesLock: boolean }> {
461
+ const lock = await fs.readFile(path.join(ASSETS, "requirements.lock"), "utf8");
462
+ const runtime = path.join(this.dataDir, "runtime");
463
+ const cfg = await fs.readFile(path.join(runtime, "pyvenv.cfg"), "utf8").catch(() => "");
464
+ const field = (name: string) => cfg.match(new RegExp(`^${name}\\s*=\\s*(.+)$`, "m"))?.[1]?.trim() ?? "";
465
+ const interpreter = `${field("version_info") || field("version")} ${await fs.realpath(path.join(runtime, "bin", "python")).catch(() => "")}`;
466
+ const norm = (name: string) => name.toLowerCase().replace(/[-_.]+/g, "-");
467
+ const installed = new Map<string, string>();
468
+ const lib = path.join(runtime, "lib");
469
+ for (const dir of await fs.readdir(lib).catch(() => [] as string[])) {
470
+ if (!/^python3\.\d+$/.test(dir)) continue;
471
+ for (const entry of await fs.readdir(path.join(lib, dir, "site-packages")).catch(() => [] as string[])) {
472
+ const m = entry.match(/^(.+)-([^-]+)\.dist-info$/);
473
+ if (m) installed.set(norm(m[1]), m[2]);
474
+ }
475
+ }
476
+ let matchesLock = installed.size > 0;
477
+ for (const line of lock.split("\n")) {
478
+ const m = line.match(/^\s*([A-Za-z0-9][A-Za-z0-9._-]*)==([^\s;]+)\s*(;.*)?$/);
479
+ if (!m) continue;
480
+ const have = installed.get(norm(m[1]));
481
+ // A pin behind an environment marker may not apply here: absent is fine, a different version is not.
482
+ if (have === undefined ? !m[3] : have !== m[2]) matchesLock = false;
483
+ }
484
+ return { interpreter, lock_sha256: createHash("sha256").update(lock).digest("hex"), matchesLock };
485
+ }
327
486
  private async fingerprint(): Promise<string> {
328
487
  const hash = createHash("sha256");
329
488
  for (const file of [
@@ -511,10 +670,13 @@ export class CadEngine {
511
670
  inputs[alias] = await this.inputFile(value, ext);
512
671
  }
513
672
  }
673
+ // Re-check before queueing, inside this run's deadline; a not-ready refusal still comes from inside the queue,
674
+ // after any queue timeout.
675
+ const before = await this.ensureReady(signal, deadline);
514
676
  return this.exclusive(
515
677
  async (queueWaitMs) => {
516
678
  const status = await this.status();
517
- if (!status.ready) throw new CadRefusal("cad-not-ready", status.error!);
679
+ if (!status.ready) throw new CadRefusal("cad-not-ready", before.error ?? status.error!);
518
680
  const job = await fs.mkdtemp(path.join(root, `cad-${name}-`));
519
681
  await fs.chmod(job, 0o700);
520
682
  const script = path.join(job, `${name}.py`),
@@ -708,10 +870,13 @@ export class CadEngine {
708
870
  clearance > 100
709
871
  )
710
872
  throw new Error("clearance_mm must be finite, between 0 and 100.");
873
+ // One deadline for the whole call: the automatic re-check and the fit share timeout_ms.
874
+ const deadline = performance.now() + milliseconds(args.timeout_ms);
875
+ const before = await this.ensureReady(signal, deadline);
711
876
  return this.exclusive(
712
877
  async () => {
713
878
  const status = await this.status();
714
- if (!status.ready) throw new CadRefusal("cad-not-ready", status.error!);
879
+ if (!status.ready) throw new CadRefusal("cad-not-ready", before.error ?? status.error!);
715
880
  const job = await fs.mkdtemp(path.join(this.dataDir, "fit-"));
716
881
  try {
717
882
  await fs.copyFile(model, path.join(job, "model.stl"));
@@ -737,7 +902,11 @@ export class CadEngine {
737
902
  path.join(job, "model.stl"),
738
903
  path.join(job, "reference.stl"),
739
904
  ],
740
- milliseconds(args.timeout_ms),
905
+ (() => {
906
+ const left = Math.floor(deadline - performance.now());
907
+ if (left <= 0) throw new Error("CAD fit timed out.");
908
+ return left;
909
+ })(),
741
910
  signal,
742
911
  )
743
912
  ).stdout,
@@ -42,6 +42,8 @@ export const REMOTE_SCOPES: Readonly<Record<string, RemoteScope>> = {
42
42
  counterpart_printer_info: "read",
43
43
  counterpart_print_progress: "read",
44
44
  cad_status: "read",
45
+ cad_examples: "read",
46
+ design_guidance: "read",
45
47
  cad_setup: "read",
46
48
  cad_run: "design",
47
49
  cad_check_fit: "design",
@@ -25,7 +25,9 @@ Find out before you design, and before you ask. Research whenever the request na
25
25
  6. For what is still unknown after about two rounds per fact, shape the design so that fact does not decide whether it works (an adjustable or sprung interface, a foot that suits more than one surface), or state a bounded assumption as an assumption. Ask the person only as the last resort, one short question, and only for what exists nowhere but with them. Never ask for something a search answers: a photo of their car's dashboard, the size of a named product, what a named surface is made of.
26
26
  Without web tools, say so in the result, use what you recall labelled as recalled rather than published, and lean harder on step 6.
27
27
 
28
- Before choosing a mechanism, establish what every working bought or published version of the thing has, and keep all of it. For example, a car phone holder turns and tilts to face the driver; a mount's base is sized by the moment of what it holds, not just its weight; an adhesive mount uses a full pad of the tape's grade, not a strip, on a surface the tape suits. Start from the complete product a capable designer would describe at once, then make it printable. A design that leaves out a feature they all have says what it lost and why that is acceptable for this person.
28
+ Write the concept down before any geometry, in a few lines: the bought product you are following, its mechanism, the load path, and how it will print. Before choosing a mechanism, establish what every working bought or published version of the thing has, and keep all of it. For example, a car phone holder turns and tilts to face the driver; a mount's base is sized by the moment of what it holds, not just its weight; an adhesive mount uses a full pad of the tape's grade, not a strip, on a surface the tape suits. Start from the complete product a capable designer would describe at once, then make it printable. A design that leaves out a feature they all have says what it lost and why that is acceptable for this person.
29
+
30
+ Give it the product's form as well as its function. The bought thing's shape is evidence: a handle swells where the palm closes, a hook's arm thickens towards its root, a knob is round and knurled, a clip's jaws wrap what they hold. Do not reduce a product to a flat profile pushed up, or a box with holes, because that is quick to model and prints without thought: that is a bracket, and people can tell. Put curves where hands and objects touch and where load turns a corner. A flat, in-plane layout is right only for the element that needs it (a spring that must bend in the layer plane, a print-in-place hinge or chain), and then say so; the rest of the product keeps its form, split or turned for printing if need be. When the engine renders the model, look at a three-quarter view and ask whether a person would recognise the thing and want it.
29
31
 
30
32
  Choose each fit by what that interface has to do: drop in and lift out, slide, locate without rattle, grip so it does not slip or turn, snap over, or press in to stay. There is no single fit number. Keep three things apart for each interface: the object's size and how sure it is, the correction this printer and orientation need (its own observed corrections first, when the context supplies them), and the fit the function calls for. When the size's uncertainty is wider than the function tolerates, do not answer with a better number: choose a mechanism that absorbs the difference (crush ribs, a split closed by a screw, a flexure, a snap), or ask for the one measurement that settles it. The same object changes with time and use: full and nearly empty, new and worn, soft and stiff. A fit that relies on the object giving way must still work in its stiffest, largest state, and a pocket is sized to the widest section the object passes through on the way in, with support where the object actually bears, not to its bounding box.
31
33
 
@@ -43,6 +45,8 @@ Use assembly when its benefit is worth the user's additional work. Design alignm
43
45
 
44
46
  Verify the chosen geometry in its actual print orientation and inspect the slice when tools permit. Check critical fits, missing or floating features, toolpaths, supports, color assignments, total time, and material consumption. Treat a slicer prediction as a prediction, not a physical test. Fix consequential problems and re-slice relevant changes. Stop when the design meets the brief and no remaining improvement justifies its cost. State "prints without supports", "holds", or "fits" only when the engine's own checks or the slice show it, and give the number that shows it; otherwise call it an untested prediction.
45
47
 
48
+ Fit and flexure guidance is longer than this text and is read when it applies: fdm_fit whenever a part meets a real object or another part, fdm_flexures whenever a part must flex, grip, snap, clip or spring. If your host did not attach them, read them with this MCP's design_guidance tool before you choose that fit or size that spring. Where the MCP's code engine is in use, its cad_examples tool lists worked designs to start from.
49
+
46
50
  Keep the user-facing result short: the recommended design, why its manufacturing approach makes sense, how it prints and assembles, and any consequential unresolved assumption. Distinguish measured dimensions, slicer estimates, and untested predictions. Say where each critical size came from (measured, published, or assumed) and what each interface is meant to do and how it fits. Keep detailed analysis in the working process.`;
47
51
 
48
52
  export const FDM_MULTICOLOR = `Apply this guidance when multiple colors or support materials share a print.
@@ -350,6 +354,35 @@ export const DESIGN_PROMPTS: DesignPrompt[] = [
350
354
  description: "A separate review turn after a candidate has been sliced, before presenting the manufacturing recommendation: keep, revise, or validate one specific uncertainty." },
351
355
  ];
352
356
 
357
+ /**
358
+ * The on-demand guidance as a tool. A design worker that is handed fdm_design and the engine prompt by its host has
359
+ * only tools, not prompts or resources, so "add fdm_fit when a part meets an object" could never be followed there:
360
+ * this read-only tool returns the same texts by name.
361
+ */
362
+ const GUIDANCE_TOPICS: Record<string, { title: string; when: string; text: () => string }> = {
363
+ fdm_fit: { title: "Choosing a fit by function", when: "a part meets a real object or another part", text: () => FDM_FIT_GUIDANCE },
364
+ fdm_flexures: { title: "Parts that flex, grip and snap", when: "a part must flex, grip, snap, clip, spring, or hold something by bending", text: () => FDM_FLEXURES },
365
+ fdm_assembly: { title: "Splits, inserts and joints", when: "a split, joint, insert or printed thread could improve the result", text: () => FDM_ASSEMBLY },
366
+ fdm_multicolor: { title: "Multicolour and support materials", when: "several colours or support materials share a print", text: () => FDM_MULTICOLOR },
367
+ fdm_after_slice: { title: "Review a slice", when: "a candidate has been sliced, before recommending it", text: () => FDM_AFTER_SLICE },
368
+ fdm_capability: { title: "Bridges and overhangs", when: "a bridge or overhang decides the plan and no measured capability is at hand", text: () => FDM_CAPABILITY_GUIDANCE },
369
+ };
370
+ export const DESIGN_GUIDANCE_TOOL = {
371
+ name: "design_guidance",
372
+ description: "Read one piece of this MCP's design guidance by name: " + Object.entries(GUIDANCE_TOPICS).map(([name, t]) => `${name} (when ${t.when})`).join("; ") + ". The same texts as the prompts of those names, for a worker that has tools but not prompts. Read-only.",
373
+ inputSchema: {
374
+ type: "object" as const,
375
+ properties: { name: { type: "string", enum: Object.keys(GUIDANCE_TOPICS), description: "Which guidance to read." } },
376
+ required: ["name"],
377
+ additionalProperties: false,
378
+ },
379
+ };
380
+ export function designGuidance(args: Record<string, unknown>): { name: string; title: string; text: string } {
381
+ const topic = typeof args.name === "string" ? GUIDANCE_TOPICS[args.name] : undefined;
382
+ if (!topic || Object.keys(args).length !== 1) throw new Error(`design_guidance takes one name: ${Object.keys(GUIDANCE_TOPICS).join(", ")}.`);
383
+ return { name: args.name as string, title: topic.title, text: topic.text() };
384
+ }
385
+
353
386
  const SLICER_NAMES: Record<string, string> = {
354
387
  bambustudio: "Bambu Studio", orcaslicer: "OrcaSlicer", "orcaslicer-bambulab": "FULU OrcaSlicer-bambulab",
355
388
  "orca-slicer-api": "the remote OrcaSlicer service (orca-slicer-api)", prusaslicer: "PrusaSlicer", cura: "Cura", slic3r: "Slic3r",
@@ -379,4 +412,4 @@ export function slicingGuidance(slicerType: string, capabilities: { supports: bo
379
412
  export const FDM_SLICING_PROMPT = { name: "fdm_slicing", title: "How this MCP slices",
380
413
  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." };
381
414
 
382
- export const SERVER_INSTRUCTIONS = "When designing or editing a model to print, apply the fdm_design prompt and the fdm_slicing prompt. Add fdm_fit whenever a part meets a real object or another part, to choose each fit by what that interface has to do. Add fdm_flexures whenever a part must flex, grip, snap, clip, spring, or hold something by bending. Add fdm_multicolor when several colours or support materials share a print, fdm_assembly when a split, joint or printed fastener 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. Read " + FDM_FIT_URI + " for the same fit guidance as the fdm_fit prompt, in resource form.";
415
+ export const SERVER_INSTRUCTIONS = "When designing or editing a model to print, apply the fdm_design prompt and the fdm_slicing prompt. Add fdm_fit whenever a part meets a real object or another part, to choose each fit by what that interface has to do. Add fdm_flexures whenever a part must flex, grip, snap, clip, spring, or hold something by bending. Add fdm_multicolor when several colours or support materials share a print, fdm_assembly when a split, joint or printed fastener 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. Read " + FDM_FIT_URI + " for the same fit guidance as the fdm_fit prompt, in resource form. A worker that has tools but not prompts reads the same guidance with the design_guidance tool (fdm_fit, fdm_flexures, fdm_assembly, fdm_multicolor, fdm_after_slice, fdm_capability).";
package/src/index.ts CHANGED
@@ -60,6 +60,8 @@ import { importFileViaBambuConnect } from "./bambu-connect.js";
60
60
  import { CadEngine } from "./cad-engine.js";
61
61
  import { CadRefusal } from "./cad/refusal.js";
62
62
  import { CAD_TOOLS, cadEnabled } from "./cad/contracts.js";
63
+ import { cadExamplesTool } from "./cad/examples.js";
64
+ import { DESIGN_GUIDANCE_TOOL, designGuidance } from "./design-guidance.js";
63
65
  import { BlenderMcpBridge } from "./blender-mcp-bridge.js";
64
66
  import { FUSION_EXPORT_OUTPUT_SCHEMA, FUSION_MCP_DEFAULT_ARGS, FUSION_MCP_PIN, FUSION_NEW_DESIGN_OUTPUT_SCHEMA, FUSION_STATUS_OUTPUT_SCHEMA, FusionMcpBridge, addinAddress } from "./fusion-mcp-bridge.js";
65
67
  import { BLENDER_SETUP_OUTPUT_SCHEMA, BlenderAddonSetup, FUSION_ADDIN_REPOSITORY, FUSION_SETUP_OUTPUT_SCHEMA, FusionAddinSetup, defaultSetupSystem, parseAddonHandshake, type BlenderAddonHandshake } from "./design-app-setup.js";
@@ -155,7 +157,7 @@ const SERVER_INFO = {
155
157
  };
156
158
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
157
159
  const OUTPUT_SCHEMA_TOOLS = new Set([
158
- "cad_status", "cad_setup", "cad_run", "cad_check_fit",
160
+ "cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
159
161
  "counterpart_printer_info", "counterpart_print_progress", "counterpart_make_3mf",
160
162
  "counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
161
163
  "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
@@ -3478,6 +3480,7 @@ class BambuPrinterMCPServer {
3478
3480
  required: ["stl_path"]
3479
3481
  }
3480
3482
  },
3483
+ DESIGN_GUIDANCE_TOOL,
3481
3484
  ...(CAD_ENABLED ? CAD_TOOLS : []),
3482
3485
  {
3483
3486
  name: "blender_mcp_status",
@@ -5110,9 +5113,17 @@ class BambuPrinterMCPServer {
5110
5113
  result = await makeCounterpart3mf(args ?? {});
5111
5114
  break;
5112
5115
 
5116
+ case "design_guidance":
5117
+ result = designGuidance(args ?? {});
5118
+ break;
5119
+
5120
+ case "cad_examples":
5121
+ result = cadExamplesTool(args ?? {});
5122
+ break;
5123
+
5113
5124
  case "cad_status":
5114
5125
  if (args && Object.keys(args).length) throw new Error("cad_status takes no arguments.");
5115
- result = await this.cad.status(); break;
5126
+ result = await this.cad.ensureReady(extra.signal); break;
5116
5127
  case "cad_setup":
5117
5128
  case "cad_run":
5118
5129
  case "cad_check_fit": {
@@ -38,6 +38,8 @@ export const TOOL_ANNOTATIONS: Record<string, ToolAnnotations> = {
38
38
  cad_setup: hints(false, true, true, true),
39
39
  cad_run: hints(false, false, false, false),
40
40
  cad_check_fit: READ_LOCAL,
41
+ cad_examples: READ_LOCAL,
42
+ design_guidance: READ_LOCAL,
41
43
  // Printer and cloud reads
42
44
  get_printer_status: READ_OUTSIDE,
43
45
  get_printer_filaments: READ_OUTSIDE,