bambu-printer-mcp 1.1.94 → 1.1.96

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.
@@ -43,6 +43,7 @@ export function bambuPrinterInfo(options) {
43
43
  // camera_snapshot needs the model to choose its transport.
44
44
  camera: model && TCP_CAMERA_MODELS.has(model) ? "bambu-tcp" : model && RTSP_CAMERA_MODELS.has(model) ? "rtsp" : "none",
45
45
  cameraStream: !!model && (TCP_CAMERA_MODELS.has(model) || RTSP_CAMERA_MODELS.has(model)),
46
+ diagnostics: true,
46
47
  filaments: "ams",
47
48
  pause: true,
48
49
  resume: true,
@@ -18,6 +18,7 @@ export const REMOTE_SCOPES = {
18
18
  blender_mcp_status: "read",
19
19
  counterpart_printer_info: "read",
20
20
  counterpart_self_check: "read",
21
+ counterpart_diagnostics: "read", // this server's own redacted logs; nothing reaches the printer
21
22
  counterpart_print_progress: "read",
22
23
  counterpart_print_record: "read",
23
24
  counterpart_print_assess: "control", // local evidence mutation, never a printer command
@@ -76,6 +76,8 @@ export type PrinterInfo = {
76
76
  layers: boolean;
77
77
  camera: "bambu-tcp" | "rtsp" | "http-snapshot" | "none";
78
78
  cameraStream?: boolean;
79
+ /** counterpart_diagnostics is here: this server hands over its own redacted diagnostics bundle. */
80
+ diagnostics?: boolean;
79
81
  filaments: "ams" | "single" | "none";
80
82
  pause: boolean;
81
83
  resume: boolean;
@@ -175,6 +177,10 @@ export declare const PRINTER_INFO_OUTPUT_SCHEMA: {
175
177
  cameraStream: {
176
178
  type: string;
177
179
  };
180
+ diagnostics: {
181
+ type: string;
182
+ description: string;
183
+ };
178
184
  filaments: {
179
185
  type: string;
180
186
  enum: string[];
@@ -43,6 +43,7 @@ export const PRINTER_INFO_OUTPUT_SCHEMA = {
43
43
  layers: { type: "boolean" },
44
44
  camera: { type: "string", enum: ["bambu-tcp", "rtsp", "http-snapshot", "none"] },
45
45
  cameraStream: { type: "boolean" },
46
+ diagnostics: { type: "boolean", description: "counterpart_diagnostics is available." },
46
47
  filaments: { type: "string", enum: ["ams", "single", "none"] },
47
48
  pause: { type: "boolean" },
48
49
  resume: { type: "boolean" },
@@ -45,6 +45,19 @@ export declare const FUSION_STATUS_OUTPUT_SCHEMA: {
45
45
  type: string;
46
46
  description: string;
47
47
  };
48
+ responsive: {
49
+ type: string;
50
+ description: string;
51
+ };
52
+ state: {
53
+ type: string;
54
+ enum: string[];
55
+ description: string;
56
+ };
57
+ reason: {
58
+ type: string;
59
+ description: string;
60
+ };
48
61
  addinReachable: {
49
62
  type: string;
50
63
  description: string;
@@ -36,6 +36,7 @@ export const FUSION_MCP_DEFAULT_ARGS = Object.freeze([
36
36
  ]);
37
37
  const DEFAULT_TIMEOUT_MS = 180000;
38
38
  const MAX_TIMEOUT_MS = 600000;
39
+ const STATUS_PROBE_TIMEOUT_MS = 5000;
39
40
  const LAUNCH_WAIT_MS = 90000;
40
41
  const ADDIN_PING_MS = 2000;
41
42
  const EXPORT_NAME = /^[A-Za-z0-9][A-Za-z0-9._ -]{0,99}$/;
@@ -229,7 +230,10 @@ export const FUSION_STATUS_OUTPUT_SCHEMA = {
229
230
  type: "object",
230
231
  properties: {
231
232
  configured: { type: "boolean", description: "FUSION_MCP_COMMAND is set." },
232
- connected: { type: "boolean", description: "The Fusion MCP server started and the add-in answered its ping." },
233
+ connected: { type: "boolean", description: "The add-in answers and its command probe has not failed. Check state/ responsive for design readiness and activeDesign for an open document." },
234
+ responsive: { type: "boolean", description: "A fresh no-op through execute_code completed and Fusion reports startup complete; this does not guarantee a later design operation succeeds." },
235
+ state: { type: "string", enum: ["starting", "ready", "unresponsive"], description: "starting comes from Fusion's own isStartupComplete flag, ready requires the command probe, unresponsive means readiness could not be verified. See reason." },
236
+ reason: { type: "string", description: "Plain explanation and next step, provided by the MCP rather than inferred by clients." },
233
237
  addinReachable: { type: "boolean", description: "The Fusion360MCP add-in answered a ping on FUSION_MCP_HOST:FUSION_MCP_PORT (default localhost:9877) within 2 s. Another program on that port, such as Blender's MCP add-on, does not count." },
234
238
  fusionRunning: { type: "boolean" },
235
239
  activeDesign: { type: "boolean", description: "When connected: whether Fusion has a design open, from the add-in's read-only get_design_type (false is its NO_ACTIVE_DESIGN). The pinned add-in refuses every design command, fusion_mcp_new_design included, without one (faust issue #12). Absent when unknown." },
@@ -240,7 +244,7 @@ export const FUSION_STATUS_OUTPUT_SCHEMA = {
240
244
  server: { type: "object" },
241
245
  error: { type: "string" },
242
246
  },
243
- required: ["configured", "connected", "addinReachable", "fusionRunning", "tools"],
247
+ required: ["configured", "connected", "responsive", "state", "reason", "addinReachable", "fusionRunning", "tools"],
244
248
  };
245
249
  export const FUSION_NEW_DESIGN_OUTPUT_SCHEMA = {
246
250
  type: "object",
@@ -417,7 +421,7 @@ export class FusionMcpBridge {
417
421
  allowedArguments(args, ["launch", "timeout_ms"]);
418
422
  if (args.launch !== undefined && typeof args.launch !== "boolean")
419
423
  throw new FusionError("launch must be a boolean.");
420
- const timeout = timeoutMilliseconds(args.timeout_ms);
424
+ const timeout = Math.min(timeoutMilliseconds(args.timeout_ms), STATUS_PROBE_TIMEOUT_MS);
421
425
  const { host, port } = addinAddress();
422
426
  const configured = Boolean(process.env.FUSION_MCP_COMMAND?.trim());
423
427
  let addinReachable = await this.system.addinAnswers(host, port, ADDIN_PING_MS);
@@ -442,7 +446,8 @@ export class FusionMcpBridge {
442
446
  addinReachable = await this.system.addinAnswers(host, port, ADDIN_PING_MS);
443
447
  }
444
448
  }
445
- const result = { configured, connected: false, addinReachable, fusionRunning, tools: [], launched, transport: "stdio", pin: FUSION_MCP_PIN };
449
+ const result = { configured, connected: false, responsive: false, state: "unresponsive",
450
+ reason: configured ? "Fusion isn't responding on your Mac. Restart Fusion, then Try Again." : "Set up the Fusion MCP connection first.", addinReachable, fusionRunning, tools: [], launched, transport: "stdio", pin: FUSION_MCP_PIN };
446
451
  if (!configured)
447
452
  return result;
448
453
  try {
@@ -473,9 +478,35 @@ export class FusionMcpBridge {
473
478
  else if (errorKind(read, "get_design_type") === "NO_ACTIVE_DESIGN")
474
479
  result.activeDesign = false;
475
480
  }
481
+ if (result.connected === true) {
482
+ // At the pinned add-in execute_code traverses _MUTATION_COMMANDS snapshots and the same
483
+ // handler as design commands. A no-op tests that path without editing or opening a document.
484
+ // A late probe is harmless. Require this call's nonce; neither ping nor a design read proves readiness.
485
+ const nonce = randomUUID();
486
+ const code = `# BAMBU_FUSION status_probe
487
+ import json
488
+ json.dumps({"nonce": "${nonce}", "startupComplete": app.isStartupComplete})`;
489
+ const probe = await this.invoke(live, options, dispatched, "execute_code", { code });
490
+ if (errorKind(probe, "execute_code") === "NO_ACTIVE_DESIGN") {
491
+ result.activeDesign = false;
492
+ result.reason = "Open a design in Fusion, then Try Again.";
493
+ return;
494
+ }
495
+ if (failed(probe, "execute_code"))
496
+ throw new FusionError("Fusion's command readiness probe failed.");
497
+ const receipt = argumentObject(codeJson(probe), "Fusion readiness receipt");
498
+ if (receipt.nonce !== nonce || typeof receipt.startupComplete !== "boolean") {
499
+ throw new FusionError("Fusion did not return this command readiness probe's receipt.");
500
+ }
501
+ result.responsive = receipt.startupComplete;
502
+ result.connected = receipt.startupComplete;
503
+ result.state = receipt.startupComplete ? "ready" : "starting";
504
+ result.reason = receipt.startupComplete ? "Fusion's command path is responding." : "Fusion is still starting. Finish any sign-in or update dialog, then Try Again.";
505
+ }
476
506
  });
477
507
  }
478
508
  catch (error) {
509
+ result.connected = false;
479
510
  result.error = error instanceof Error ? error.message : String(error);
480
511
  }
481
512
  return result;
package/dist/index.js CHANGED
@@ -58,16 +58,21 @@ import { bambuProgress, offlineProgress } from "./counterpart/progress.js";
58
58
  import { makeCounterpart3mf } from "./counterpart/make-3mf.js";
59
59
  import { MAKE_3MF_OUTPUT_SCHEMA, PRINT_PROGRESS_OUTPUT_SCHEMA, PRINTER_INFO_OUTPUT_SCHEMA } from "./counterpart/schemas.js";
60
60
  import { SELF_CHECK_OUTPUT_SCHEMA, selfCheck } from "./counterpart/self-check.js";
61
+ import { DIAGNOSTICS_INPUT_PROPERTIES, DIAGNOSTICS_OUTPUT_SCHEMA, appVersion, buildDiagnostics, captureServerLog, diagnosticsBudget, jsonText, recordToolError, rememberSecretArguments, serverLogText, settingsSnapshot, toolErrorsText } from "./counterpart/diagnostics.js";
61
62
  import { parseProcessOverrides } from "./slicer/process-overrides.js";
62
63
  import { PRINT_QUALITY_PROPERTIES, withPrintQuality } from "./slicer/print-quality.js";
63
64
  import { PrinterRefusal, withPrintDispatch, markPrintCommandSent, printOutcome } from "./refusal.js";
64
65
  import { uploadProgressReporter } from "./upload-progress.js";
65
66
  import { machinePauseGcode, parsePauseLayers, pausedLayers, readPlateGcode } from "./slicer/layer-pauses.js";
66
67
  dotenv.config();
68
+ // What the server writes to stderr is also kept for counterpart_diagnostics.
69
+ captureServerLog();
67
70
  const CAD_ENABLED = cadEnabled();
68
71
  const DEFAULT_HOST = process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST || "localhost";
69
72
  const DEFAULT_BAMBU_SERIAL = process.env.BAMBU_PRINTER_SERIAL || process.env.BAMBU_SERIAL || "";
70
73
  const DEFAULT_BAMBU_TOKEN = process.env.BAMBU_PRINTER_ACCESS_TOKEN || process.env.BAMBU_TOKEN || "";
74
+ /** Access-code names people try that this server does not read (counterpart_diagnostics names them when set). */
75
+ const UNREAD_ACCESS_CODE_NAMES = ["BAMBU_PRINTER_ACCESS_CODE", "BAMBU_ACCESS_CODE", "BAMBU_ACCESS_TOKEN", "BAMBU_PRINTER_TOKEN"];
71
76
  const DEFAULT_BAMBU_DEV_ID = process.env.BAMBU_DEV_ID || DEFAULT_BAMBU_SERIAL;
72
77
  // os.tmpdir(), not process.cwd() — a packaged Claude Desktop extension is
73
78
  // spawned with a cwd we don't control (and may not be writable), so a
@@ -126,7 +131,7 @@ const SERVER_INFO = {
126
131
  /** Tools that declare an outputSchema: they always return structuredContent, and errors carry none. */
127
132
  const OUTPUT_SCHEMA_TOOLS = new Set([
128
133
  "cad_status", "cad_setup", "cad_run", "cad_check_fit", "cad_examples",
129
- "counterpart_printer_info", "counterpart_self_check", "counterpart_print_progress", "counterpart_make_3mf",
134
+ "counterpart_printer_info", "counterpart_self_check", "counterpart_diagnostics", "counterpart_print_progress", "counterpart_make_3mf",
130
135
  "counterpart_discover_printers", "counterpart_setup_fields", "counterpart_propose_filaments",
131
136
  "fusion_mcp_status", "fusion_mcp_new_design", "fusion_mcp_export",
132
137
  "camera_stream_start", "camera_frame", "camera_stream_stop",
@@ -3065,6 +3070,12 @@ class BambuPrinterMCPServer {
3065
3070
  inputSchema: { type: "object", properties: {} },
3066
3071
  outputSchema: SELF_CHECK_OUTPUT_SCHEMA
3067
3072
  },
3073
+ {
3074
+ name: "counterpart_diagnostics",
3075
+ description: "Counterpart contract (counterpart/1): this server's own diagnostics for a bug report, as files for the client to add to its export: the configured printers (model, serial, connection; firmware is not read), this server's settings, slicer path and version, CAD runtime status, recent tool errors, this run's stderr log (MQTT and connection messages). The Bambu network plug-in logs are not included. Redaction fails closed: configured secrets go in their encoded forms, JSON is redacted by key, and any log line that names a secret is withheld whole; serial numbers, error codes and whether a secret is set stay. Names, contents and notes stay within max_bytes; anything missing is listed in notes. Sends nothing to the printer.",
3076
+ inputSchema: { type: "object", properties: DIAGNOSTICS_INPUT_PROPERTIES, additionalProperties: false },
3077
+ outputSchema: DIAGNOSTICS_OUTPUT_SCHEMA
3078
+ },
3068
3079
  {
3069
3080
  name: "counterpart_discover_printers",
3070
3081
  description: "Counterpart contract (counterpart/1): Bambu printers on the local network, from their own SSDP announcements (UDP 2021), with serial, model (as bambu_model names it), name and firmware. Listens for duration_ms (default 4000). network is \"unavailable\" when another app holds the port. Never connects to or authenticates with a printer.",
@@ -3189,12 +3200,12 @@ class BambuPrinterMCPServer {
3189
3200
  },
3190
3201
  {
3191
3202
  name: "fusion_mcp_status",
3192
- description: `Check Autodesk Fusion through the configured Fusion MCP server (fusion360-mcp-server, faust-machines or the pinned fork with document binding): whether it is configured, Fusion is running, the Fusion360MCP add-in answers on its port, and the server's tools and schemas. connected is true only when the add-in answers. With launch: true, starts Fusion on macOS when it is not running and waits up to 90 s for the add-in. Configure FUSION_MCP_COMMAND (uvx) and FUSION_MCP_ARGS (${JSON.stringify(FUSION_MCP_DEFAULT_ARGS)}), or run fusion_mcp_setup.`,
3203
+ description: `Check Autodesk Fusion through the configured Fusion MCP server (fusion360-mcp-server, faust-machines or the pinned fork with document binding): whether it is configured, Fusion is running, the Fusion360MCP add-in answers on its port, and the server's tools and schemas. Reports state (starting, ready, unresponsive), responsive and reason from a fresh no-op execute_code command probe, capped at 5 s; a ping or design read alone is not readiness. The probe never edits or opens a document. With launch: true, starts Fusion on macOS when it is not running and waits up to 90 s for the add-in. Configure FUSION_MCP_COMMAND (uvx) and FUSION_MCP_ARGS (${JSON.stringify(FUSION_MCP_DEFAULT_ARGS)}), or run fusion_mcp_setup.`,
3193
3204
  inputSchema: {
3194
3205
  type: "object",
3195
3206
  properties: {
3196
3207
  launch: { type: "boolean", description: "Start Autodesk Fusion (open -a \"Autodesk Fusion\") when it is not running, then wait up to 90 s for the add-in." },
3197
- timeout_ms: { type: "integer", minimum: 100, maximum: 600000, description: "Connection and discovery deadline in milliseconds; defaults to FUSION_MCP_TIMEOUT_MS or 180000." }
3208
+ timeout_ms: { type: "integer", minimum: 100, maximum: 600000, description: "Connection, discovery and command-probe deadline, capped at 5000 ms even if a larger value is requested. Launch waiting is separate." }
3198
3209
  },
3199
3210
  additionalProperties: false
3200
3211
  },
@@ -3252,6 +3263,7 @@ class BambuPrinterMCPServer {
3252
3263
  // A designer's settings extracted for this call are removed when it settles.
3253
3264
  this.server.setRequestHandler(CallToolRequestSchema, (request, extra) => withPrintDispatch(() => withExtractedSettingsCleanup(async () => {
3254
3265
  const { name, arguments: args } = request.params;
3266
+ rememberSecretArguments(args);
3255
3267
  const sendNativeCommand = (options, execution = {}) => sendCommandWithBambuNative(options, { signal: extra.signal, ...execution });
3256
3268
  const progressToken = extra._meta?.progressToken;
3257
3269
  let progressNotifications = Promise.resolve();
@@ -4385,6 +4397,9 @@ class BambuPrinterMCPServer {
4385
4397
  case "counterpart_self_check":
4386
4398
  result = await selfCheck(SERVER_INFO);
4387
4399
  break;
4400
+ case "counterpart_diagnostics":
4401
+ result = await this.diagnostics(args ?? {});
4402
+ break;
4388
4403
  case "counterpart_printer_info":
4389
4404
  result = bambuPrinterInfo({ server: SERVER_INFO, host, serial: bambuSerial, model: this.displayModel(args, bambuSerial), slicerType: normalizeSlicerType(DEFAULT_SLICER_TYPE) });
4390
4405
  break;
@@ -4511,6 +4526,7 @@ class BambuPrinterMCPServer {
4511
4526
  return { content: [{ type: "text", text }] };
4512
4527
  }
4513
4528
  catch (error) {
4529
+ recordToolError(name, error);
4514
4530
  if (name.startsWith("cad_")) {
4515
4531
  const failure = await this.cad.failure(error, name);
4516
4532
  return { isError: true, content: [{ type: "text", text: failure.message }], structuredContent: failure };
@@ -4546,6 +4562,88 @@ class BambuPrinterMCPServer {
4546
4562
  }
4547
4563
  })));
4548
4564
  }
4565
+ /** counterpart_diagnostics: this server's own redacted bundle (src/counterpart/diagnostics.ts). Sends nothing to a printer. */
4566
+ async diagnostics(args) {
4567
+ const unknown = Object.keys(args).filter(key => key !== "printer" && key !== "max_bytes");
4568
+ if (unknown.length)
4569
+ throw new Error(`counterpart_diagnostics takes only printer and max_bytes, not ${unknown.join(", ")}.`);
4570
+ if (args.printer !== undefined && typeof args.printer !== "string")
4571
+ throw new Error("printer must be a string.");
4572
+ const maxBytes = diagnosticsBudget(args.max_bytes);
4573
+ const wanted = args.printer?.trim().toLowerCase();
4574
+ const notes = [];
4575
+ // This server's own sentences, built only from setting names it reads: their secret words name settings.
4576
+ const fixedNotes = [];
4577
+ const model = DEFAULT_BAMBU_MODEL || undefined;
4578
+ let connection;
4579
+ try {
4580
+ connection = resolveConnection(undefined, model);
4581
+ }
4582
+ catch (error) {
4583
+ connection = { error: error instanceof Error ? error.message : String(error) };
4584
+ }
4585
+ const configured = DEFAULT_BAMBU_SERIAL || process.env.BAMBU_PRINTER_HOST || process.env.PRINTER_HOST;
4586
+ const printers = configured ? [{
4587
+ id: DEFAULT_BAMBU_SERIAL || DEFAULT_HOST,
4588
+ kind: "bambu",
4589
+ host: DEFAULT_HOST,
4590
+ ...(DEFAULT_BAMBU_SERIAL ? { serial: DEFAULT_BAMBU_SERIAL } : {}),
4591
+ ...(model ? { model } : {}),
4592
+ connection,
4593
+ accessCodeSet: Boolean(DEFAULT_BAMBU_TOKEN),
4594
+ // Firmware comes only from the printer; this tool asks it nothing.
4595
+ firmware: "unknown",
4596
+ }] : [];
4597
+ if (!configured)
4598
+ notes.push("No printer is configured (BAMBU_SERIAL and BAMBU_PRINTER_HOST are unset).");
4599
+ // A look-alike name this server never reads leaves accessCodeSet false; name it so the bundle says why.
4600
+ const ignored = UNREAD_ACCESS_CODE_NAMES.filter(key => process.env[key]);
4601
+ if (ignored.length)
4602
+ fixedNotes.push(`${ignored.join(" and ")} ${ignored.length > 1 ? "are" : "is"} set, but this server reads the access code only from BAMBU_TOKEN or BAMBU_PRINTER_ACCESS_TOKEN (in the environment or its .env).`);
4603
+ const selected = wanted ? printers.filter(p => [p.id, p.host, p.serial].some(v => v?.toLowerCase() === wanted)) : printers;
4604
+ if (wanted && !selected.length)
4605
+ notes.push(`No configured printer is ${args.printer}; printers.json lists none.`);
4606
+ if (printers.length)
4607
+ notes.push("Printer firmware is not included: only the printer reports it, and this tool sends it nothing.");
4608
+ let slicer;
4609
+ try {
4610
+ const { fields: _fields, ...setup } = slicerSetupNow();
4611
+ const version = appVersion(setup.path);
4612
+ slicer = { ...setup, ...(version ? { version } : {}) };
4613
+ if (setup.type === "orca-slicer-api") {
4614
+ if (!setup.found)
4615
+ notes.push("The remote OrcaSlicer API slicer has no SLICER_API_URL.");
4616
+ }
4617
+ else if (!setup.found)
4618
+ notes.push(`The ${setup.type} slicer is not installed where this server looks (${setup.path ?? "no path"}).`);
4619
+ else if (!version && setup.path)
4620
+ notes.push("Slicer version is unknown: its install doesn't name it, and this tool doesn't run the slicer.");
4621
+ }
4622
+ catch (error) {
4623
+ slicer = { error: error instanceof Error ? error.message : String(error) };
4624
+ }
4625
+ let cad;
4626
+ try {
4627
+ cad = await this.cad.status();
4628
+ }
4629
+ catch (error) {
4630
+ cad = { error: error instanceof Error ? error.message : String(error) };
4631
+ }
4632
+ const settings = settingsSnapshot(/^(?:BAMBU|PRINTER|SLICER|ORCA|CAD|BLENDER|FUSION|BED_TYPE|NOZZLE|MCP|PJARCZAK|FULU|TEMP_DIR)/);
4633
+ const sources = [
4634
+ { name: "server.json", text: jsonText({ package: SERVER_INFO.name, version: SERVER_INFO.version, node: process.version, platform: process.platform, arch: process.arch, uptimeSec: Math.round(process.uptime()) }) },
4635
+ { name: "printers.json", text: jsonText({ printers: selected }) },
4636
+ { name: "settings.json", text: jsonText(settings) },
4637
+ { name: "slicer.json", text: jsonText(slicer) },
4638
+ { name: "cad.json", text: jsonText(cad) },
4639
+ { name: "tool-errors.log", text: toolErrorsText() || "No tool has failed since this server started.\n" },
4640
+ { name: "server-stderr.log", text: serverLogText() || "Nothing written to stderr since this server started.\n" },
4641
+ ];
4642
+ // The Bambu network plug-in and native helper logs are written by other programs, in forms this server does not
4643
+ // control, and can carry secrets it never held (a cloud token, another printer's code): they stay out.
4644
+ fixedNotes.push("The Bambu network plug-in (fulu) and native helper logs are not included: other programs write them, and they can hold secrets this server cannot recognise.");
4645
+ return buildDiagnostics({ package: SERVER_INFO.name, version: SERVER_INFO.version, sources, notes, fixedNotes, maxBytes, secrets: DEFAULT_BAMBU_TOKEN ? [DEFAULT_BAMBU_TOKEN] : [] });
4646
+ }
4549
4647
  async startStdio() {
4550
4648
  const transport = new StdioServerTransport();
4551
4649
  await this.server.connect(transport);
@@ -45,6 +45,7 @@ export const TOOL_ANNOTATIONS = {
45
45
  get_slice_settings: LOCAL_OUTPUT, // a 3MF's settings are extracted to a fixed file in the temporary directory
46
46
  counterpart_printer_info: READ_LOCAL, // configuration and capabilities; sends nothing to the printer
47
47
  counterpart_self_check: READ_LOCAL, // loads this install's own modules; sends nothing to the printer
48
+ counterpart_diagnostics: READ_LOCAL, // reads this server's own logs and settings, redacted; sends nothing to the printer
48
49
  counterpart_setup_fields: READ_LOCAL, // the settings this server reads; no configured values
49
50
  // Local outputs in the server's temporary directory
50
51
  extend_stl_base: LOCAL_OUTPUT,
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "bambu-printer-mcp",
3
- "version": "1.1.94",
3
+ "version": "1.1.96",
4
4
  "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
5
  "counterpart": {
6
6
  "contract": "counterpart/1",
7
- "notes": "Writes and edits multi-part, multi-colour 3MF projects and reports each plate’s parts and colours.",
7
+ "notes": "Checks what a design is for on the design as used, and returns this server’s own redacted diagnostics for bug reports.",
8
8
  "autoUpdate": true
9
9
  },
10
10
  "main": "dist/index.js",
@@ -113,7 +113,7 @@ export const CAD_TOOLS = [
113
113
  {
114
114
  name: "cad_run",
115
115
  description:
116
- "Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six orthographic renders, a perspective view and a contact sheet (with next: read the perspective view before the next change), the closest approach between every pair of solids (bodies), problems, what was checked and not checked, and printed: whatever the script wrote with print(), capped at 4000 characters, so a design can report a number it computed; valid means only that the exported geometry is sound, never that the part fits, holds, moves or prints.",
116
+ "Build parametric CAD headlessly in OS confinement. Read cad_design first: declare literal P = {...} and build() returning a build123d Shape. Supply script OR script_path; parameters overrides saved named values in one call before derived dimensions. Calls wait for the environment’s exclusive execution slot up to their own deadline and report queue_wait_ms. Each call creates a private immutable subfolder under allowed output_dir, never overwriting previous artifacts. The saved .py and .parameters.json are the recovery checkpoint even after cancellation. Returns independently measured geometry, STL/STEP, six orthographic renders, a perspective view and a contact sheet (with next: read the perspective view before the next change), the closest approach between every pair of solids (bodies), problems, what was checked and not checked, printed: whatever the script wrote with print(), capped at 4000 characters, so a design can report a number it computed, and, in solid mode, purpose and ready: the script's PURPOSE compiled into requirements and evaluated on its use() assembly (held objects, mounts, loads computed from the geometry, facing the user). valid means only that the exported geometry is sound; final: true is recorded only when the design is ready (final_refused says why not).",
117
117
  inputSchema: {
118
118
  type: "object" as const,
119
119
  properties: {
@@ -164,6 +164,13 @@ export const CAD_TOOLS = [
164
164
  description:
165
165
  "Plain file stem for STL, STEP, Python and parameter artifacts.",
166
166
  },
167
+ role: {
168
+ type: "string",
169
+ enum: ["design", "check"],
170
+ default: "design",
171
+ description:
172
+ 'What this run is: "design" (the default) for the design itself, or "check" for a fit check part, a reference export or any other run that must never become the model. A check run is never selected as final, evaluates no PURPOSE, and its receipt says role: "check".',
173
+ },
167
174
  final: {
168
175
  type: "boolean",
169
176
  default: false,
@@ -231,6 +238,33 @@ export const CAD_TOOLS = [
231
238
  description:
232
239
  "The script's own print() output from this run, capped at 4000 characters (build.log keeps the rest). The script's words, not a measurement by the engine.",
233
240
  },
241
+ ready: {
242
+ type: "boolean",
243
+ description:
244
+ "Solid mode: the design's PURPOSE is declared and every requirement it compiles to passed on use(). final: true is recorded only when ready. Absent for mesh mode and 3MF projects.",
245
+ },
246
+ purpose: {
247
+ type: "object",
248
+ description:
249
+ "Solid mode: what PURPOSE says the part is for (for, modelled_on), the product classes its words put it in, each requirement compiled from it with status pass, fail or not_modelled and what it says (held objects sit on the part, each mount touches its world surface, the exposed face of a held screen turns to the user's eye, tape stress and resting stability under the computed loads), the loads at the mounts (gravity, jolts, a hand's press), and blocked: what keeps it from ready.",
250
+ },
251
+ final_requested: { type: "boolean" },
252
+ role: {
253
+ type: "string",
254
+ enum: ["design", "check"],
255
+ description: 'The run\'s role as cad_run was given it: "design", or "check" for a check part or reference export that is never the model. Every receipt carries it.',
256
+ },
257
+ draft_reasons: {
258
+ type: "array",
259
+ items: { type: "string" },
260
+ description:
261
+ "On every valid run that is not final: why not, in plain sentences (the designer did not mark it final; it is not ready, then what blocks it; or it is a check part, not the design). A client that keeps such a run as a draft shows these.",
262
+ },
263
+ final_refused: {
264
+ type: "array",
265
+ items: { type: "string" },
266
+ description: "Why final: true was not recorded, each as the step that fixes it (for example: model the dash as world:dash in use() so the tape mount can be checked). next quotes the first ones; the run is not the model until a run with final: true is ready.",
267
+ },
234
268
  three_mf: {
235
269
  type: "string",
236
270
  description: "When build() returned project_3mf(): the written 3MF project, ready for slice_stl.",
@@ -384,6 +418,7 @@ export const CAD_DESIGN_PROMPT = {
384
418
  "MCP-owned rules for headless build123d designs and one-call parameter revisions.",
385
419
  text: `Use code-CAD for dimensioned functional designs and parameter edits. Build in millimetres with build123d 0.13.0; the MCP owns the Python environment, execution, export, validation and rendering. Check cad_status and use cad_setup with install: true when needed. No Blender, Fusion, network or printer access is available to your script.
386
420
  A new design starts from the product, in this order. First, name two or three products a person would buy for this request (search when you are not sure what is sold) and say which one the design follows. Second, choose from the cookbook by purpose: the list below says what each example is for (cad_examples with no name returns it with each one's pattern and product). Read the example whose use is nearest the request, with cad_examples and its name, before deciding anything else, and adapt its form and pattern, never its sizes. Third, and only then, choose the mechanism (a clamp, screw, spring, hinge or snap) and read a second example for it if you need one. A mechanism chosen before the product gives a bracket with the mechanism bolted on.
421
+ Then state the purpose as data, before any geometry: a literal PURPOSE = {...} beside P (cad_run reads it from the source; parameters cannot change it). "for": what it is for in the person's words (who uses it, where, doing what); "modelled_on": the bought product; "holds": [{"body": name, "mass_g": grams}] for what it carries; "mounts": [{"body": name, "by": "tape", "rests", "screw", "clamp", "hook" or "other"}] for each surface that takes the load; "user": [x, y, z], the eye of the person who uses it, in mm in the use() frame, when it shows them something; optional "jolt_g", "press_n", "reach_mm", "material" and "faces": {"body": name, "within_deg": 25}. Its words add requirements whatever you list: a holder, hook, stand, dock, mount, rack, bracket, cradle or organizer must name what it holds and what it mounts to; anything in a vehicle takes jolts of at least 1.5 g in every direction; a phone, tablet or screen it holds must face the user's eye within 25 degrees. Then define use() beside build(): return Compound(children=[...]) of the part as it is used, Z up and gravity along -Z, with each held object at its real size and pose labelled "held:<body>" and each surface it meets as a solid slab where it really is (a dash face at its real angle, a desk's underside, a wall) labelled "world:<body>", all touching the part where they really touch. cad_run computes the loads at each mount from that geometry (gravity on the part and what it holds, the jolts, a hand pressing the held object), checks tape against 3M VHB's published stresses and that a resting part neither tips, lifts nor slides, checks that a held screen faces the user, draws renders.use (from the user's eye when given) and reports it all in purpose. final: true is recorded only when ready is true; until then the result lists final_refused. A run that is not the design itself (a part exported only for cad_check_fit, a reference, a diagnostic) is a check: pass role: "check" to every cad_run that is not the design itself, so it is never mistaken for the model (it is never final and evaluates no PURPOSE). Every valid run that is not final carries draft_reasons, saying why. When a requirement fails, change the design the way the bought products solve it (a joint that aims it, a broader pad, a wider or heavier base), never the purpose.
387
422
  The cookbook, by what each example is for:
388
423
  ${cadExampleLines()}
389
424
  Form first: build the product's shape, not a profile pushed up. Before any geometry, write the concept as the script's opening docstring, the way every cookbook example does: what it is, then "Modelled on:" the bought product you named, its mechanism, the load path, the print orientation and why. A script whose header names no product was designed from the mechanism. build123d has loft (through sections of different shape), sweep (a section along a path or a Helix), revolve, fillet, chamfer, offset and shell as well as extrude; use the one the product's surface calls for: lofted where a hand closes round it, revolved where it turns, swept where it runs like a bent rod or a thread, filleted where two surfaces meet under load. Extrude a flat profile only for something that really is a plate or a lever, or for a print-in-place mechanism or spring that must lie in the layers, and say that reason in the result. Choose the print orientation after the form: split a part, turn it or accept a modest support before flattening its design.
@@ -35,6 +35,15 @@ P = {
35
35
  "print_in_place": False, # two parts assembled by hand: only touching is a problem
36
36
  }
37
37
 
38
+ # What it is for, as data: cad_run compiles it into requirements and evaluates them on use() below.
39
+ PURPOSE = {
40
+ "for": "a hook that clamps under my 25 mm desk to hang my headphones",
41
+ "modelled_on": "Brainwavz Hoist headphone hanger with adjustable clamp",
42
+ "holds": [{"body": "headphones", "mass_g": 350}],
43
+ "mounts": [{"body": "desk", "by": "clamp"}],
44
+ "material": "PETG",
45
+ }
46
+
38
47
 
39
48
  def thread(root_r, crest_r, z0, length):
40
49
  """A 45 degree trapezoid swept along a helix about Z, from z0. root_r > crest_r makes the nut's thread."""
@@ -89,3 +98,26 @@ def build():
89
98
  turn = 360 * (lift + kh + 1 - z_nut) / P["pitch"] + 180
90
99
  used = Rot(90, 0, 0) * Compound([frame, to_frame * Pos(0, 0, lift) * Rot(0, 0, turn) * screw])
91
100
  return Pos(0, 0, -used.bounding_box().min.Z) * used
101
+
102
+
103
+ def use():
104
+ """As used: clamped on a desk_t desk whose top is the plane the top jaw lies on, a headband resting on the hook.
105
+ A clamp's strength is not computed; its loads are, from where the headphones hang."""
106
+ pose = P["pose"]
107
+ P["pose"] = "assembled"
108
+ try:
109
+ shown = build()
110
+ finally:
111
+ P["pose"] = pose
112
+ desk_top = shown.bounding_box().max.Z - P["bar_t"] # the top jaw lies on the desk
113
+ parts = shown.solids()
114
+ for k, s in enumerate(parts):
115
+ s.label = f"body {k + 1}"
116
+ w = P["width"]
117
+ desk = Pos(150, -w / 2, desk_top - P["desk_t"] / 2) * Box(300, 300, P["desk_t"])
118
+ desk.label = "world:desk"
119
+ hook_top = desk_top - P["opening"] - P["drop"] # top of the hook arm
120
+ x = P["reach"] + P["bend_r"] - P["hook_len"] / 2
121
+ band = Pos(x, -w / 2, hook_top + 15) * Box(30, 60, 30) # the headband where it rests
122
+ band.label = "held:headphones"
123
+ return Compound(children=[*parts, band, desk])
@@ -25,6 +25,15 @@ P = {
25
25
  "edge": 0.6, # chamfer round both faces of the comb: no sharp edge on a cable jacket
26
26
  }
27
27
 
28
+ # What it is for, as data: cad_run compiles it into requirements and evaluates them on use() below.
29
+ PURPOSE = {
30
+ "for": "an organizer that parks five charging cables at the edge of my desk so the plugs don't fall behind it",
31
+ "modelled_on": "Orico CBS5 5-slot self-adhesive desk cable holder",
32
+ "holds": [{"body": "cables", "mass_g": 40}], # the last 200 mm of five cables, about 8 g each
33
+ "mounts": [{"body": "desk", "by": "tape"}],
34
+ "material": "PETG",
35
+ }
36
+
28
37
 
29
38
  def build():
30
39
  seat_r = (P["cable_max"] + P["seat_clear"]) / 2
@@ -53,3 +62,18 @@ def build():
53
62
 
54
63
  rail = extrude(comb, P["depth"])
55
64
  return chamfer(rail.edges().group_by(Axis.Z)[0] + rail.edges().group_by(Axis.Z)[-1], P["edge"])
65
+
66
+
67
+ def use():
68
+ """As used: the taped base on the desk top (Z = 0), the last 200 mm of a 4 mm cable lying in each seat. cad_run computes the tape's
69
+ load from this, so the rail's size is checked against what it carries, not asserted."""
70
+ seat_r = (P["cable_max"] + P["seat_clear"]) / 2
71
+ rail = Rot(90, 0, 0) * build() # the comb's up (Y) becomes Z; its depth runs along -Y
72
+ rail.label = "rail"
73
+ z = P["base_t"] - P["cradle"] + 2.0 # a 4 mm cable resting in the bottom of its seat
74
+ cables = Compound([Pos((i - (P["slots"] - 1) / 2) * P["pitch"], -P["depth"] / 2, z) * (Rot(90, 0, 0) * Cylinder(2.0, 200))
75
+ for i in range(P["slots"])])
76
+ cables.label = "held:cables"
77
+ desk = Pos(0, -P["depth"] / 2, -10) * Box(300, 200, 20)
78
+ desk.label = "world:desk"
79
+ return Compound(children=[rail, cables, desk])
@@ -35,6 +35,15 @@ P = {
35
35
  "edge_r": 1.9, # rounding on hooks and panel top (the 4 mm lip becomes a full round)
36
36
  }
37
37
 
38
+ # What it is for, as data: cad_run compiles it into requirements and evaluates them on use() below.
39
+ PURPOSE = {
40
+ "for": "a stand that holds my phone on my desk at a reading angle while it charges",
41
+ "modelled_on": "Lamicall S1 desk phone stand",
42
+ "holds": [{"body": "phone", "mass_g": 249}], # the tallest iPhone it takes
43
+ "mounts": [{"body": "desk", "by": "rests"}],
44
+ "user": [0.0, -450.0, 330.0], # a seated person's eye, in front of the stand
45
+ }
46
+
38
47
 
39
48
  def build():
40
49
  lean, neck, t = radians(P["lean_deg"]), radians(P["neck_deg"]), P["thick"]
@@ -91,3 +100,20 @@ def build():
91
100
  rest = Plane(seat, x_dir=(1, 0, 0), z_dir=out)
92
101
  slot = extrude(SlotOverall(P["slot_len"], P["cable_gap"] - 6, rotation=90), 2 * t, both=True)
93
102
  return body - rest * Pos(0, 3 - P["slot_len"] / 2) * slot
103
+
104
+
105
+ def use():
106
+ """As used: on the desk (Z = 0) with the tallest iPhone (163.4 x 78.0 x 8.75 mm) on the hooks and against the back.
107
+ cad_run checks from this that the stand neither tips nor slides when the screen is pressed, and that the screen
108
+ faces the user's eye."""
109
+ lean = radians(P["lean_deg"])
110
+ up = Vector(0, sin(lean), cos(lean))
111
+ out = Vector(0, -cos(lean), sin(lean))
112
+ seat = Vector(0, P["nose_y"], P["nose_h"]) + up * P["seat_up"] + out * (P["thick"] / 2)
113
+ stand = build()
114
+ stand.label = "stand"
115
+ phone = Pos(*(seat + up * (163.4 / 2) + out * (8.75 / 2))) * (Rot(-P["lean_deg"], 0, 0) * Box(78.0, 8.75, 163.4))
116
+ phone.label = "held:phone"
117
+ desk = Pos(0, P["foot_y"], -10) * Box(300, 300, 20)
118
+ desk.label = "world:desk"
119
+ return Compound(children=[stand, phone, desk])
@@ -39,12 +39,62 @@ def inspect(request):
39
39
  assembly = bodies(step, request) if step is not None else None
40
40
  except Exception as e: # a failed measurement must not cost the person the export; it is reported, not passed
41
41
  assembly = {'error': f'{type(e).__name__}: {e}'[:300]}
42
+ # What the part is for, evaluated on the design as it is used (purpose.py): ready, and why not.
43
+ from purpose import inspect_purpose
44
+ try:
45
+ purpose = inspect_purpose(request, step)
46
+ except Exception as e:
47
+ why = f'the purpose could not be evaluated: {type(e).__name__}: {e}'[:300]
48
+ purpose = {'declared': None, 'requirements': [], 'loads': [], 'not_checked': [], 'blocked': [why], 'ready': False}
49
+ renders = render(m, base.parent / (base.name + '.renders'))
50
+ if purpose is not None and Path(str(base) + '.use.step').exists():
51
+ try:
52
+ renders['use'] = use_view(Path(str(base) + '.use.step'), base.parent / (base.name + '.renders'), purpose.get('user'))
53
+ except Exception as e:
54
+ purpose['not_checked'].append(f'the view of the design in use could not be drawn: {type(e).__name__}')
55
+ found = evidence(assembly)
56
+ if purpose is not None:
57
+ found['checked'].append('what PURPOSE says it is for, compiled into requirements and evaluated on use(): the held objects, the mounts, the loads at each mount and whether it faces its user (purpose; anything not passing is in purpose.blocked)')
58
+ found['not_checked'] += purpose['not_checked']
42
59
  return {'valid': all(v for v in checks.values() if v is not None), 'units': 'mm', 'bounds_mm': bounds,
43
60
  'size_mm': m.extents.tolist(), 'volume_mm3': float(m.volume) if m.is_volume else None,
44
61
  'step_volume_mm3': float(step.volume) if step is not None else None, 'solid_count': len(step.solids()) if step is not None else len(m.split(only_watertight=True)),
45
62
  'mesh_components': len(m.split(only_watertight=False)), 'checks': checks,
46
- **evidence(assembly),
47
- 'renders': render(m, base.parent / (base.name + '.renders'))}
63
+ **found, 'renders': renders,
64
+ # ready needs sound geometry too; problems (body gaps) stay advisory, as they were
65
+ **({'purpose': purpose, 'ready': purpose['ready'] and all(v for v in checks.values() if v is not None)} if purpose is not None else {})}
66
+
67
+
68
+ def use_view(step, folder, eye=None):
69
+ """The design as it is used, held objects and the surfaces it meets included, seen from the user's eye when given."""
70
+ user = eye is not None
71
+ from build123d import Box, Compound, Pos, import_step
72
+ from purpose import _mesh
73
+ shape = import_step(str(step))
74
+ kids = list(shape.children) if isinstance(shape, Compound) else []
75
+ world = [c for c in kids if (c.label or '').startswith('world:')]
76
+ if world and len(world) < len(kids):
77
+ # Only the part of a wall, desk or dash near the design: a whole slab would fill the picture.
78
+ rest = Compound(children=[c for c in kids if c not in world]).bounding_box()
79
+ near = Pos(*rest.center()) * Box(rest.size.X + 50, rest.size.Y + 50, rest.size.Z + 50)
80
+ clipped = [c & near for c in world]
81
+ shape = Compound(children=[c for c in kids if c not in world] + [c for c in clipped if c.solids()])
82
+ m = _mesh(shape, 0.1)
83
+ az, el = 35.0, 26.0
84
+ if eye is None and world and len(world) < len(kids):
85
+ # No eye given: look from the part's side of the surface it meets, so a wall or armrest never hides it.
86
+ towards = np.array(list(rest.center()), float) - np.array(list(Compound(children=world).bounding_box().center()), float)
87
+ if np.linalg.norm(towards) > 1e-6:
88
+ default = np.array([math.sin(math.radians(az)) * math.cos(math.radians(el)), -math.cos(math.radians(az)) * math.cos(math.radians(el)), math.sin(math.radians(el))])
89
+ eye = m.bounds.mean(axis=0) + 1000 * (towards / np.linalg.norm(towards) + 0.7 * default)
90
+ if eye is not None:
91
+ d = np.asarray(eye, float) - m.bounds.mean(axis=0)
92
+ az, el = math.degrees(math.atan2(d[0], -d[1])), max(-75.0, min(75.0, math.degrees(math.atan2(d[2], math.hypot(d[0], d[1])))))
93
+ im = perspective(m, 1200, az, el)
94
+ label = 'in use' + (', from the user\'s eye' if user else ', from the side it is used from' if eye is not None else ', from the front right and above')
95
+ ImageDraw.Draw(im).text((24, 20), label, fill='black', font=ImageFont.load_default(size=28))
96
+ file = folder / 'use.png'; im.resize((800, 800), Image.LANCZOS).save(file)
97
+ return str(file)
48
98
 
49
99
 
50
100
  # Starting print-in-place gap between separate bodies: Prusa's first value for movable parts is "at least 0.3 mm"