bambu-printer-mcp 1.1.47 → 1.1.49
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 +117 -3
- package/dist/blender-mcp-bridge.d.ts +15 -0
- package/dist/blender-mcp-bridge.js +21 -3
- package/dist/counterpart/info.d.ts +10 -0
- package/dist/counterpart/info.js +34 -0
- package/dist/counterpart/make-3mf.d.ts +16 -0
- package/dist/counterpart/make-3mf.js +219 -0
- package/dist/counterpart/progress.d.ts +28 -0
- package/dist/counterpart/progress.js +254 -0
- package/dist/counterpart/schemas.d.ts +322 -0
- package/dist/counterpart/schemas.js +124 -0
- package/dist/fusion-mcp-bridge.d.ts +182 -0
- package/dist/fusion-mcp-bridge.js +557 -0
- package/dist/index.js +192 -12
- package/dist/printers/bambu-stages.d.ts +7 -0
- package/dist/printers/bambu-stages.js +89 -0
- package/dist/printers/bambu.d.ts +76 -4
- package/dist/printers/bambu.js +298 -38
- package/dist/printers/camera-models.d.ts +7 -0
- package/dist/printers/camera-models.js +18 -0
- package/dist/safety/hms-messages.d.ts +42 -0
- package/dist/safety/hms-messages.js +6194 -0
- package/dist/safety/printer-state.d.ts +18 -0
- package/dist/safety/printer-state.js +3 -3
- package/dist/slicer/process-overrides.d.ts +12 -0
- package/dist/slicer/process-overrides.js +33 -0
- package/dist/slicer/remote-slicer.js +2 -0
- package/dist/stl/stl-manipulator.d.ts +2 -0
- package/dist/stl/stl-manipulator.js +19 -0
- package/package.json +1 -1
- package/src/blender-mcp-bridge.ts +22 -3
- package/src/counterpart/info.ts +36 -0
- package/src/counterpart/make-3mf.ts +220 -0
- package/src/counterpart/progress.ts +254 -0
- package/src/counterpart/schemas.ts +154 -0
- package/src/fusion-mcp-bridge.ts +545 -0
- package/src/index.ts +199 -12
- package/src/printers/bambu-stages.ts +90 -0
- package/src/printers/bambu.ts +316 -38
- package/src/printers/camera-models.ts +18 -0
- package/src/safety/hms-messages.ts +6198 -0
- package/src/safety/printer-state.ts +4 -4
- package/src/slicer/process-overrides.ts +42 -0
- package/src/slicer/remote-slicer.ts +2 -0
- package/src/stl/stl-manipulator.ts +22 -0
package/README.md
CHANGED
|
@@ -94,7 +94,7 @@ If your agent is always on, such as OpenClaw or Hermes Agent running on a comput
|
|
|
94
94
|
|
|
95
95
|
### Before you print
|
|
96
96
|
|
|
97
|
-
- **"
|
|
97
|
+
- **"Start the bracket I sliced last night."**\
|
|
98
98
|
It checks the camera image before it sends the job.
|
|
99
99
|
- **"What's loaded in the AMS? Print this in whatever black I have."**\
|
|
100
100
|
It reads the live AMS inventory and matches the file's filaments to your trays.
|
|
@@ -737,7 +737,16 @@ Pause the currently running print job. Sends an `UpdateState` MQTT command with
|
|
|
737
737
|
|
|
738
738
|
#### resume_print
|
|
739
739
|
|
|
740
|
-
Resume a paused print job.
|
|
740
|
+
Resume a paused print job that this server inspected and started. Resume reheats and moves the printer, so it is checked like a print start:
|
|
741
|
+
|
|
742
|
+
1. A fresh report must show that job paused, with the inspected nozzle and filament still in place.
|
|
743
|
+
2. The server downloads the job's file from the printer over FTPS and compares its SHA-256 with the inspected bytes. A P1S deletes an uploaded project once it starts printing and keeps the plate G-code it extracted, `cache/<name>_plate_<n>.gcode`, which is byte-identical to the 3MF's `Metadata/plate_<n>.gcode`. When the project is gone, the server compares that file with the inspected plate. A different file refuses the resume, and the job can no longer be resumed from here.
|
|
744
|
+
3. A person confirms through MCP elicitation: the prompt names the job, its peak temperatures, materials and SHA-256. `BAMBU_REQUIRE_CONFIRMATION=0` skips this prompt, as it does for print and heating prompts.
|
|
745
|
+
4. The printer is read again after the prompt, and on X2D and H2 the native helper rechecks it once more right before sending. Only then does the server send `UpdateState` with `state: "resume"`.
|
|
746
|
+
|
|
747
|
+
The server keeps one resume record per printer. Cancelling the job ends it, and so does a report that the job finished, failed or went idle after it was seen running, or another job seen in its place. A later job with the same name, such as the same file reprinted from the touchscreen, is never resumed. The server watches every MQTT report it receives, not just its own reads. It doesn't see reports while its MQTT session is disconnected.
|
|
748
|
+
|
|
749
|
+
The result is `{status, message, jobName, bytesVerified}`, where `jobName` is the name `counterpart_print_progress` reports. On the BambuNetwork and X2D native routes, Bambu's plug-in puts the file on the printer, so its FTPS path isn't verified. If the file can't be read back there, the resume matches the job by its unique name and returns `bytesVerified: false`, and the prompt says so. That prompt always appears, even with `BAMBU_REQUIRE_CONFIRMATION=0`, which skips only prompts for resumes whose bytes were verified. On every other route, a file that can't be re-read refuses the resume.
|
|
741
750
|
|
|
742
751
|
```json
|
|
743
752
|
{
|
|
@@ -1043,6 +1052,21 @@ This wrapper currently assumes:
|
|
|
1043
1052
|
|
|
1044
1053
|
If the project does not match those assumptions, the tool fails fast with a structured error instead of guessing. The role-to-color and color-to-tray mapping is isolated in code so the next version can evolve toward customer-requested colors without replacing the whole wrapper.
|
|
1045
1054
|
|
|
1055
|
+
#### Counterpart tools (`counterpart/1`)
|
|
1056
|
+
|
|
1057
|
+
[Counterpart](https://github.com/DMontgomery40/scan-to-make) (Scan to Make) reads printers through a small contract that this server and [mcp-3D-printer-server](https://github.com/DMontgomery40/mcp-3D-printer-server) share. Each tool declares an `outputSchema` and returns `structuredContent`, plus the same JSON as text for older clients. An error is returned as text only, because MCP clients check `structuredContent` against the schema even on errors. `counterpart_printer_info` and `counterpart_print_progress` take the usual optional `host`, `bambu_serial`, `bambu_token` and `bambu_model` (default `BAMBU_MODEL`) arguments.
|
|
1058
|
+
|
|
1059
|
+
- **`counterpart_printer_info`** returns `{contract, server: {name, version}, printer: {kind: "bambu", model, serial, host}, capabilities}`. `capabilities` lists progress, layers, the camera transport (`bambu-tcp` for A1/P1, `rtsp` for X1, P2S, H2 and X2D, `none` without a model), `filaments: "ams"`, pause, resume, cancel, `print3mf` and `gcode` (false on X2D). It sends nothing to the printer and never returns the access code.
|
|
1060
|
+
- **`counterpart_print_progress`** returns `{contract, observedAt, state, job?, temps?, activeFilament?, problems}` from the printer's MQTT reports, which this server keeps while it is connected. A held session is answered from that cache without any printer traffic, and `observedAt` is when the printer sent the report. The server asks the printer for a full report only to fill an empty cache, and at most once every five minutes after the printer has been quiet that long. A printer that sends no report within 8 seconds is `offline`.
|
|
1061
|
+
- `state`: `IDLE` is `idle`, `PREPARE`/`SLICING` `preparing`, `RUNNING` `printing`, `PAUSE` `paused`, `FINISH` `finished` and `FAILED` `failed`. A `FAILED` job with `0300400C` ("The task was canceled.") in `print_error`, or in X2D's `fail_reason`, is `cancelled`. Any other or missing `gcode_state` on a connected printer is `busy`.
|
|
1062
|
+
- `job` (not for idle, busy or offline): `name` is `subtask_name`, else the basename of `gcode_file` (a raw G-code print reports only its file path; that basename is the `jobName` the print returns); `id` is `task_id`, omitted when it is the LAN placeholder `"0"`; `progress` is `mc_percent`; `remainingSec` is `mc_remaining_time` (minutes) × 60; `layer`/`totalLayers` appear once the printer reports a total; `stage` is Bambu Studio's words for `stg_cur` ("Heatbed preheating", "Auto bed leveling").
|
|
1063
|
+
- `temps`: nozzle and bed `{actual, target}`, and `chamber` from the H2 chamber controller or the X1 sensor. On H2 and X2D the nozzle is the active extruder's, from `device.extruder`. P1 and A1 printers have no chamber sensor, so it is omitted.
|
|
1064
|
+
- `activeFilament`: the loaded spool's `material` and `#RRGGBB` `color`. `slot` is the index `ams_slots` uses: `amsId × 4 + tray` for an AMS, the unit id (128 and up) for an AMS-HT, and `"ext"` for the external spool, or `"254"` (left) / `"255"` (right) on dual-nozzle H2D, H2C and X2D. On H2 and X2D it comes from the active extruder's report.
|
|
1065
|
+
- `problems`: a non-zero `print_error` as 8 hex digits, such as `07008011`, and each HMS entry as `AAAA_BBBB_CCCC_DDDD`, such as `0300_1800_0001_0003`. Severity follows Bambu's HMS level: fatal is `fatal`, serious `error`, common `warning` and info `info`. Each HMS problem links to Bambu's page for that code. Messages come from the English HMS tables bundled with the pinned Bambu Studio release; `scripts/generate-hms-messages.mjs` turns them into `src/safety/hms-messages.ts` and the stage words into `src/printers/bambu-stages.ts`. A model without its own table, such as the P1S, gets the text the other tables share. Codes that Bambu lists for a printer without text are reported as `info`.
|
|
1066
|
+
- **`counterpart_make_3mf`** takes `{parts: [{stl_path, name, filament?}], out_path}` and writes a new 3MF for multi-colour printing. The parts become one assembly: they keep their relative positions, and each part prints with its own filament number (by default part 1 uses filament 1, part 2 filament 2, and so on). Slice it with `slice_stl` and one `load_filaments` profile per filament number, then print it with `print_3mf` and `ams_slots` or `ams_mapping`. The file holds one assembly rather than one object per part, because Bambu Studio 02.08.02.61's CLI arranges separate objects apart, reports G-code path conflicts between stacked objects when arranging is off, and refuses `load_filament_ids` for 3MF input. It never overwrites a file. The result lists `path`, `objects`, `filaments` (the highest filament number) and each part's triangle count.
|
|
1067
|
+
|
|
1068
|
+
`print_3mf` also returns `subtaskName`, the `subtask_name` it sends with the job, when it starts a 3MF with the LAN `project_file` command: an STL or 3MF sliced by `slice_stl`, and any 3MF on H2, P2S and A1. On H2 and P2S it also returns `taskId`, the `task_id` sent with the job; other models send `task_id: "0"`. A client can match `counterpart_print_progress` reports to its own print with these. Pre-sliced `.gcode.3mf` files on P1, X1 and A1 mini (sent as a G-code file), the X2D native route, and the BambuNetwork and Bambu Connect routes return neither.
|
|
1069
|
+
|
|
1046
1070
|
</details>
|
|
1047
1071
|
|
|
1048
1072
|
<details>
|
|
@@ -1139,7 +1163,7 @@ When `slicer_type` is `bambustudio` (the default), these additional parameters a
|
|
|
1139
1163
|
| `clone_objects` | string | Clone counts per object, comma-separated (e.g. `"1,3,1,10"`) |
|
|
1140
1164
|
| `skip_objects` | string | Object indices to skip, comma-separated (e.g. `"3,5,10"`) |
|
|
1141
1165
|
| `load_filaments` | string | Filament profile paths, semicolon-separated |
|
|
1142
|
-
| `load_filament_ids` | string | Filament-to-object mapping, comma-separated |
|
|
1166
|
+
| `load_filament_ids` | string | Filament-to-object mapping, comma-separated. STL input only: Bambu Studio's CLI refuses it for a 3MF, where each object or part names its own filament (see `counterpart_make_3mf`) |
|
|
1143
1167
|
| `nozzle_volume_type` | string | Installed nozzle flow type: `standard` or `high_flow` (default: `BAMBU_NOZZLE_VOLUME_TYPE`, else the preset's Standard default). `high_flow` uses the presets' High Flow values, such as the filament's High Flow max volumetric speed, and is refused if the machine preset declares no High Flow variant. Also on `slice_with_template`. |
|
|
1144
1168
|
| `filament_colours` | string | Slot colours, one `#RRGGBB` per filament slot, semicolon-separated. Explicit values take priority, followed by input 3MF colours, each custom profile's colour, then the BambuStudio default. |
|
|
1145
1169
|
| `enable_timelapse` | boolean | Enable timelapse-aware slicing |
|
|
@@ -1151,6 +1175,11 @@ When `slicer_type` is `bambustudio` (the default), these additional parameters a
|
|
|
1151
1175
|
| `min_save` | boolean | Produce smaller output 3MF (faster uploads) |
|
|
1152
1176
|
| `skip_modified_gcodes` | boolean | Ignore stale custom gcodes in the 3MF |
|
|
1153
1177
|
| `slice_plate` | number | Which plate to slice (0 = all plates, default: 0) |
|
|
1178
|
+
| `layer_height` | number | Layer height in mm, such as 0.28, 0.2 or 0.12; at most the nozzle diameter |
|
|
1179
|
+
| `wall_loops` | integer | Number of walls, 0 to 1000 |
|
|
1180
|
+
| `sparse_infill_density` | string | Sparse infill density, such as `"15%"` |
|
|
1181
|
+
|
|
1182
|
+
`layer_height`, `wall_loops` and `sparse_infill_density` are written as a process override on top of the machine and process preset the tool resolves, using Bambu Studio's keys and string forms (`"0.2"`, `"2"`, `"15%"`). Every other preset value, and the machine preset, stay as resolved, and your own profile files are not changed. They work with every Bambu-compatible slicer, including remote `orca-slicer-api` slicing, and are refused for PrusaSlicer, Slic3r and Cura.
|
|
1154
1183
|
|
|
1155
1184
|
**Example: Slice with auto-orient and 3 copies**
|
|
1156
1185
|
```json
|
|
@@ -1245,6 +1274,91 @@ their results explicitly report `output_verified: false`. A missing executable
|
|
|
1245
1274
|
configuration is an error when execution is requested. Per-call legacy
|
|
1246
1275
|
`bridge_command` overrides remain disabled unless `MCP_ALLOW_EXECUTABLE_ARG=1`.
|
|
1247
1276
|
|
|
1277
|
+
#### Fusion MCP
|
|
1278
|
+
|
|
1279
|
+
Design a part from scratch in Autodesk Fusion through
|
|
1280
|
+
[faust-machines/fusion360-mcp-server](https://github.com/faust-machines/fusion360-mcp-server)
|
|
1281
|
+
(MIT). It is a stdio MCP server that talks TCP on `localhost:9877` here to its
|
|
1282
|
+
`Fusion360MCP` add-in inside Fusion. Fusion and its licence, including Autodesk's
|
|
1283
|
+
free personal-use licence, are yours: this server never installs or requires
|
|
1284
|
+
Fusion, and printer tools work without it.
|
|
1285
|
+
|
|
1286
|
+
Install exactly commit `19b9f1e95192`. Copy the repository's `addon/` folder at
|
|
1287
|
+
that commit to `~/Library/Application Support/Autodesk/Autodesk Fusion 360/API/AddIns/Fusion360MCP`,
|
|
1288
|
+
set the add-in to **Run on Startup**, and add these settings next to the Blender
|
|
1289
|
+
ones in your env file:
|
|
1290
|
+
|
|
1291
|
+
```bash
|
|
1292
|
+
FUSION_MCP_COMMAND=uvx
|
|
1293
|
+
FUSION_MCP_ARGS='["--from","git+https://github.com/faust-machines/fusion360-mcp-server@19b9f1e95192","fusion360-mcp-server","--mode","socket"]'
|
|
1294
|
+
FUSION_MCP_TIMEOUT_MS=180000
|
|
1295
|
+
FUSION_MCP_HOST=localhost
|
|
1296
|
+
# The default here; Blender's MCP add-on holds the add-in's own default, 9876.
|
|
1297
|
+
FUSION_MCP_PORT=9877
|
|
1298
|
+
```
|
|
1299
|
+
|
|
1300
|
+
Don't use the PyPI release (0.1.0): it crashes under mcp 2.x (faust issue #30),
|
|
1301
|
+
and the pinned commit pins `mcp<2`. Without `FUSION_MCP_ARGS`, the bridge uses
|
|
1302
|
+
the pinned arguments above. `FUSION_MCP_HOST` and `FUSION_MCP_PORT` reach the
|
|
1303
|
+
server; the child process gets only `FUSION_*` settings, never printer access
|
|
1304
|
+
codes.
|
|
1305
|
+
|
|
1306
|
+
The bridge uses port 9877 when `FUSION_MCP_PORT` is unset, as PRD §8.9 and
|
|
1307
|
+
Counterpart do. The add-in and the faust server default to 9876, which Blender's
|
|
1308
|
+
MCP add-on also uses, and while Blender holds that port the add-in can't listen
|
|
1309
|
+
there. The bridge passes the port to the faust server. The add-in reads
|
|
1310
|
+
`FUSION_MCP_PORT` from Fusion's environment, and Fusion started from the Dock or
|
|
1311
|
+
Finder gets none, so it falls back to 9876. `fusion_mcp_status` with
|
|
1312
|
+
`{"launch": true}` starts Fusion with `open -a "Autodesk Fusion" --env
|
|
1313
|
+
FUSION_MCP_PORT=<port>`. To start Fusion yourself, run the same command. If Fusion
|
|
1314
|
+
is already open on the default port, quit it first, because `--env` takes effect
|
|
1315
|
+
only when the app starts.
|
|
1316
|
+
|
|
1317
|
+
1. `fusion_mcp_status` returns `{configured, connected, addinReachable, fusionRunning, tools[]}`,
|
|
1318
|
+
plus `launched`, `pin`, the server's `server` info and any `error`.
|
|
1319
|
+
`addinReachable` is true only when the `Fusion360MCP` add-in answers its own
|
|
1320
|
+
`ping` on `FUSION_MCP_HOST:FUSION_MCP_PORT`; Blender's MCP add-on, which also
|
|
1321
|
+
defaults to port 9876, doesn't count, so it can't hide a stopped Fusion.
|
|
1322
|
+
`connected` is true only when the add-in answers the server's `ping`. With
|
|
1323
|
+
`{"launch": true}`, it starts Fusion on macOS (`open -a "Autodesk Fusion" --env FUSION_MCP_PORT=<port>`)
|
|
1324
|
+
when it is not running and waits up to 90 seconds for the add-in.
|
|
1325
|
+
2. `fusion_mcp_call` takes `{tool_name, arguments?, timeout_ms?}` and passes the
|
|
1326
|
+
call to a discovered Fusion tool (`create_sketch`, `extrude`, `fillet`,
|
|
1327
|
+
`create_parameter`, `set_parameter`, `check_interference`, `execute_code` and
|
|
1328
|
+
the rest), returning its full content and errors. It is never retried, the
|
|
1329
|
+
same contract as `blender_mcp_call`.
|
|
1330
|
+
3. `fusion_mcp_new_design` opens a new parametric design document through
|
|
1331
|
+
`execute_code` with `app.documents.add(FusionDesignDocumentType)`. The Fusion
|
|
1332
|
+
tools work on the open design, so a design pass calls this first. At the
|
|
1333
|
+
pinned commit the add-in refuses every command, `execute_code` included,
|
|
1334
|
+
until some design is open (faust issue #12). After Fusion starts at its Home
|
|
1335
|
+
tab, open any design once.
|
|
1336
|
+
4. `fusion_mcp_export` takes `{output_dir, name, body_name?}`. It writes
|
|
1337
|
+
`<name>.stl` (`export_stl` of one visible solid body), `<name>.f3d`
|
|
1338
|
+
(`export_f3d`) and `<name>.parameters.json` (the user parameters, with the
|
|
1339
|
+
fields `get_parameters` reports) into an existing directory, and returns their
|
|
1340
|
+
absolute paths. Hidden and surface bodies are never exported. Without
|
|
1341
|
+
`body_name` the design must have exactly one visible solid body. Fusion's
|
|
1342
|
+
`export_stl` takes the first body with a name, hidden or not, so a name that
|
|
1343
|
+
another body shares is refused. That includes hidden bodies, surface bodies
|
|
1344
|
+
and copies of a component. It writes all three files
|
|
1345
|
+
or none, never overwrites a file, and checks the STL is a finite triangle mesh.
|
|
1346
|
+
The result also has:
|
|
1347
|
+
- `boundingBox`: the STL's `{min, max, dimensions}` in its own units;
|
|
1348
|
+
- `fusionSizeMm`: the body's size in Fusion, in mm;
|
|
1349
|
+
- `stlUnits`: `mm`, `cm` or `unknown`, from comparing the two;
|
|
1350
|
+
- `warnings`: present when the STL isn't in millimetres.
|
|
1351
|
+
|
|
1352
|
+
Fusion writes the files itself, so it must run on this computer. Slice the
|
|
1353
|
+
STL like any other model.
|
|
1354
|
+
|
|
1355
|
+
The stdio session stays open for the life of this server, so a design pass does
|
|
1356
|
+
not start a new `uvx` process and add-in connection for every call. A timeout,
|
|
1357
|
+
cancellation or transport failure closes it, and the next call starts a new one.
|
|
1358
|
+
An interrupted call may still be running in Fusion and is never replayed. At the
|
|
1359
|
+
pinned commit `measure_distance` is broken (faust issue #27); measure the
|
|
1360
|
+
exported STL with `get_stl_info` instead.
|
|
1361
|
+
|
|
1248
1362
|
</details>
|
|
1249
1363
|
|
|
1250
1364
|
</details>
|
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import { type CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
|
2
2
|
type Arguments = Record<string, unknown>;
|
|
3
|
+
export type StlBoundingBox = {
|
|
4
|
+
min: [number, number, number];
|
|
5
|
+
max: [number, number, number];
|
|
6
|
+
dimensions: [number, number, number];
|
|
7
|
+
};
|
|
8
|
+
export declare function regularStl(filePath: string): Promise<{
|
|
9
|
+
bytes: number;
|
|
10
|
+
triangles: number;
|
|
11
|
+
}>;
|
|
12
|
+
/** regularStl plus the mesh's bounding box in the STL's own units (rounded to 1e-4). */
|
|
13
|
+
export declare function stlMetadata(filePath: string): Promise<{
|
|
14
|
+
bytes: number;
|
|
15
|
+
triangles: number;
|
|
16
|
+
bounding_box: StlBoundingBox;
|
|
17
|
+
}>;
|
|
3
18
|
export declare class BlenderMcpBridge {
|
|
4
19
|
private session;
|
|
5
20
|
private invoke;
|
|
@@ -89,7 +89,12 @@ function normalizeToolFailure(result) {
|
|
|
89
89
|
});
|
|
90
90
|
return failed ? { ...result, isError: true } : result;
|
|
91
91
|
}
|
|
92
|
-
async function regularStl(filePath) {
|
|
92
|
+
export async function regularStl(filePath) {
|
|
93
|
+
const { bytes, triangles } = await stlMetadata(filePath);
|
|
94
|
+
return { bytes, triangles };
|
|
95
|
+
}
|
|
96
|
+
/** regularStl plus the mesh's bounding box in the STL's own units (rounded to 1e-4). */
|
|
97
|
+
export async function stlMetadata(filePath) {
|
|
93
98
|
const stat = await fs.lstat(filePath).catch(() => { throw new BlenderError("STL file does not exist or is not readable."); });
|
|
94
99
|
if (!stat.isFile() || stat.size === 0 || stat.size > MAX_STL_BYTES)
|
|
95
100
|
throw new BlenderError("STL must be a non-empty regular file of at most 256 MiB.");
|
|
@@ -101,11 +106,24 @@ async function regularStl(filePath) {
|
|
|
101
106
|
if (!positions || positions.count < 3 || positions.count % 3 !== 0)
|
|
102
107
|
throw new Error("invalid vertices");
|
|
103
108
|
// Scan the typed array in place; boxing a large mesh can exhaust the JS heap.
|
|
109
|
+
const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
|
104
110
|
for (let index = 0; index < positions.array.length; index++) {
|
|
105
|
-
|
|
111
|
+
const value = positions.array[index];
|
|
112
|
+
if (!Number.isFinite(value))
|
|
106
113
|
throw new Error("invalid vertices");
|
|
114
|
+
const axis = index % 3;
|
|
115
|
+
if (value < min[axis])
|
|
116
|
+
min[axis] = value;
|
|
117
|
+
if (value > max[axis])
|
|
118
|
+
max[axis] = value;
|
|
107
119
|
}
|
|
108
|
-
|
|
120
|
+
const round = (value) => Math.round(value * 1e4) / 1e4;
|
|
121
|
+
const bounding_box = {
|
|
122
|
+
min: [round(min[0]), round(min[1]), round(min[2])],
|
|
123
|
+
max: [round(max[0]), round(max[1]), round(max[2])],
|
|
124
|
+
dimensions: [round(max[0] - min[0]), round(max[1] - min[1]), round(max[2] - min[2])],
|
|
125
|
+
};
|
|
126
|
+
return { bytes: stat.size, triangles: positions.count / 3, bounding_box };
|
|
109
127
|
}
|
|
110
128
|
catch {
|
|
111
129
|
throw new BlenderError("STL contains no valid finite triangle mesh.");
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** counterpart_printer_info for Bambu printers (PRD §8.4). Pure: no printer traffic. */
|
|
2
|
+
import { RTSP_CAMERA_MODELS, TCP_CAMERA_MODELS } from "../printers/camera-models.js";
|
|
3
|
+
import { normalizeModel } from "../safety/limits.js";
|
|
4
|
+
import { SERIAL_MODELS } from "../safety/printer-state.js";
|
|
5
|
+
import { COUNTERPART_CONTRACT } from "./schemas.js";
|
|
6
|
+
/** Bambu's display names ("P1S", "A1 Mini", "H2D Pro"), keyed by normalized model. */
|
|
7
|
+
const DISPLAY_NAMES = new Map(Object.values(SERIAL_MODELS).map(name => [normalizeModel(name), name]));
|
|
8
|
+
export function bambuPrinterInfo(options) {
|
|
9
|
+
const model = normalizeModel(options.model);
|
|
10
|
+
const serial = options.serial?.trim();
|
|
11
|
+
return {
|
|
12
|
+
contract: COUNTERPART_CONTRACT,
|
|
13
|
+
server: options.server,
|
|
14
|
+
printer: {
|
|
15
|
+
kind: "bambu",
|
|
16
|
+
...(model ? { model: DISPLAY_NAMES.get(model) ?? model.toUpperCase() } : {}),
|
|
17
|
+
...(serial ? { serial } : {}),
|
|
18
|
+
host: options.host,
|
|
19
|
+
},
|
|
20
|
+
capabilities: {
|
|
21
|
+
progress: true,
|
|
22
|
+
layers: true,
|
|
23
|
+
// camera_snapshot needs the model to choose its transport.
|
|
24
|
+
camera: model && TCP_CAMERA_MODELS.has(model) ? "bambu-tcp" : model && RTSP_CAMERA_MODELS.has(model) ? "rtsp" : "none",
|
|
25
|
+
filaments: "ams",
|
|
26
|
+
pause: true,
|
|
27
|
+
resume: true,
|
|
28
|
+
cancel: true,
|
|
29
|
+
print3mf: true,
|
|
30
|
+
// X2D jobs go through its native route; FTPS/remote-file G-code starts stay blocked there.
|
|
31
|
+
gcode: model !== "x2d",
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { COUNTERPART_CONTRACT } from "./schemas.js";
|
|
2
|
+
export declare class Make3mfError extends Error {
|
|
3
|
+
}
|
|
4
|
+
export type Make3mfResult = {
|
|
5
|
+
contract: typeof COUNTERPART_CONTRACT;
|
|
6
|
+
path: string;
|
|
7
|
+
objects: number;
|
|
8
|
+
filaments: number;
|
|
9
|
+
parts: {
|
|
10
|
+
name: string;
|
|
11
|
+
stl_path: string;
|
|
12
|
+
filament: number;
|
|
13
|
+
triangles: number;
|
|
14
|
+
}[];
|
|
15
|
+
};
|
|
16
|
+
export declare function makeCounterpart3mf(args: Record<string, unknown>): Promise<Make3mfResult>;
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* counterpart_make_3mf: combine separately exported STL parts into one 3MF for
|
|
3
|
+
* multi-colour printing (PRD §8.4/§8.5, M3b).
|
|
4
|
+
*
|
|
5
|
+
* The 3MF holds one object, an assembly with one part per STL, and each part
|
|
6
|
+
* names its filament in Metadata/model_settings.config. One object per part
|
|
7
|
+
* does not work with Bambu Studio 02.08.02.61's CLI: it arranges separate
|
|
8
|
+
* objects apart, with arrange off it reports G-code path conflicts between
|
|
9
|
+
* stacked parts, and --load-filament-ids is refused for 3MF input. An assembly
|
|
10
|
+
* keeps the parts where they were exported and still slices one filament per
|
|
11
|
+
* part. Vertices are copied unchanged, so parts keep their relative positions;
|
|
12
|
+
* one shared transform puts the assembly on the plate.
|
|
13
|
+
*/
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import fs from "node:fs/promises";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import JSZip from "jszip";
|
|
18
|
+
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
|
|
19
|
+
import { MACHINE_LIMITS, normalizeModel } from "../safety/limits.js";
|
|
20
|
+
import { COUNTERPART_CONTRACT } from "./schemas.js";
|
|
21
|
+
const MAX_PARTS = 64;
|
|
22
|
+
const MAX_FILAMENT = 64;
|
|
23
|
+
const MAX_STL_BYTES = 256 * 1024 * 1024;
|
|
24
|
+
const MAX_TOTAL_TRIANGLES = 5000000;
|
|
25
|
+
const PART_KEYS = new Set(["stl_path", "name", "filament"]);
|
|
26
|
+
export class Make3mfError extends Error {
|
|
27
|
+
}
|
|
28
|
+
function fail(message) { throw new Make3mfError(message); }
|
|
29
|
+
function nonEmptyText(value, label) {
|
|
30
|
+
if (typeof value !== "string" || !value.trim() || value.includes("\0"))
|
|
31
|
+
fail(`${label} must be a non-empty string without NUL characters.`);
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
/** Parse a binary or ASCII STL into an indexed mesh, merging bit-identical vertices so edges stay shared. */
|
|
35
|
+
async function readMesh(filePath, label) {
|
|
36
|
+
const stat = await fs.lstat(filePath).catch(() => fail(`${label} does not exist or is not readable.`));
|
|
37
|
+
if (!stat.isFile() || stat.size === 0 || stat.size > MAX_STL_BYTES)
|
|
38
|
+
fail(`${label} must be a non-empty regular STL file of at most 256 MiB.`);
|
|
39
|
+
const buffer = await fs.readFile(filePath);
|
|
40
|
+
let geometry;
|
|
41
|
+
try {
|
|
42
|
+
geometry = new STLLoader().parse(Uint8Array.from(buffer).buffer);
|
|
43
|
+
const positions = geometry.getAttribute("position");
|
|
44
|
+
if (!positions || positions.count < 3 || positions.count % 3 !== 0)
|
|
45
|
+
throw new Error("no triangles");
|
|
46
|
+
const source = positions.array;
|
|
47
|
+
const bits = new Uint32Array(source.buffer, source.byteOffset, source.length);
|
|
48
|
+
const lookup = new Map();
|
|
49
|
+
const vertices = [];
|
|
50
|
+
const indices = new Uint32Array(positions.count);
|
|
51
|
+
const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
|
|
52
|
+
for (let vertex = 0; vertex < positions.count; vertex++) {
|
|
53
|
+
const offset = vertex * 3;
|
|
54
|
+
for (let axis = 0; axis < 3; axis++) {
|
|
55
|
+
const value = source[offset + axis];
|
|
56
|
+
if (!Number.isFinite(value))
|
|
57
|
+
throw new Error("non-finite vertex");
|
|
58
|
+
if (value < min[axis])
|
|
59
|
+
min[axis] = value;
|
|
60
|
+
if (value > max[axis])
|
|
61
|
+
max[axis] = value;
|
|
62
|
+
}
|
|
63
|
+
const key = `${bits[offset]},${bits[offset + 1]},${bits[offset + 2]}`;
|
|
64
|
+
let index = lookup.get(key);
|
|
65
|
+
if (index === undefined) {
|
|
66
|
+
index = vertices.length / 3;
|
|
67
|
+
vertices.push(source[offset], source[offset + 1], source[offset + 2]);
|
|
68
|
+
lookup.set(key, index);
|
|
69
|
+
}
|
|
70
|
+
indices[vertex] = index;
|
|
71
|
+
}
|
|
72
|
+
return { vertices: Float32Array.from(vertices), indices, triangles: positions.count / 3, min, max };
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
throw new Make3mfError(`${label} contains no valid finite triangle mesh.`);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
geometry?.dispose();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function xmlAttribute(value) {
|
|
82
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">")
|
|
83
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "");
|
|
84
|
+
}
|
|
85
|
+
/** Shortest decimal that reads back as the same float32. */
|
|
86
|
+
const coordinate = (value) => String(Number(value.toPrecision(9)));
|
|
87
|
+
/** The model XML as buffers, so a large mesh never becomes one giant string. */
|
|
88
|
+
function modelXml(parts, transform) {
|
|
89
|
+
const chunks = [];
|
|
90
|
+
let pending = [];
|
|
91
|
+
const write = (line) => {
|
|
92
|
+
pending.push(line);
|
|
93
|
+
if (pending.length >= 20000) {
|
|
94
|
+
chunks.push(Buffer.from(pending.join("")));
|
|
95
|
+
pending = [];
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
write(`<?xml version="1.0" encoding="UTF-8"?>\n<model unit="millimeter" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:BambuStudio="http://schemas.bambulab.com/package/2021">\n`);
|
|
99
|
+
write(` <metadata name="Application">bambu-printer-mcp counterpart_make_3mf</metadata>\n <metadata name="BambuStudio:3mfVersion">1</metadata>\n <resources>\n`);
|
|
100
|
+
parts.forEach((part, index) => {
|
|
101
|
+
write(` <object id="${index + 1}" type="model">\n <mesh>\n <vertices>\n`);
|
|
102
|
+
const { vertices, indices } = part.mesh;
|
|
103
|
+
for (let i = 0; i < vertices.length; i += 3)
|
|
104
|
+
write(` <vertex x="${coordinate(vertices[i])}" y="${coordinate(vertices[i + 1])}" z="${coordinate(vertices[i + 2])}"/>\n`);
|
|
105
|
+
write(` </vertices>\n <triangles>\n`);
|
|
106
|
+
for (let i = 0; i < indices.length; i += 3)
|
|
107
|
+
write(` <triangle v1="${indices[i]}" v2="${indices[i + 1]}" v3="${indices[i + 2]}"/>\n`);
|
|
108
|
+
write(` </triangles>\n </mesh>\n </object>\n`);
|
|
109
|
+
});
|
|
110
|
+
const assembly = parts.length + 1;
|
|
111
|
+
write(` <object id="${assembly}" type="model">\n <components>\n`);
|
|
112
|
+
parts.forEach((_, index) => write(` <component objectid="${index + 1}"/>\n`));
|
|
113
|
+
write(` </components>\n </object>\n </resources>\n <build>\n`);
|
|
114
|
+
write(` <item objectid="${assembly}" transform="1 0 0 0 1 0 0 0 1 ${transform.map(coordinate).join(" ")}"/>\n </build>\n</model>\n`);
|
|
115
|
+
chunks.push(Buffer.from(pending.join("")));
|
|
116
|
+
return Buffer.concat(chunks);
|
|
117
|
+
}
|
|
118
|
+
function modelSettingsXml(parts, name) {
|
|
119
|
+
const assembly = parts.length + 1;
|
|
120
|
+
const partBlocks = parts.map((part, index) => ` <part id="${index + 1}" subtype="normal_part">
|
|
121
|
+
<metadata key="name" value="${xmlAttribute(part.name)}"/>
|
|
122
|
+
<metadata key="extruder" value="${part.filament}"/>
|
|
123
|
+
</part>`).join("\n");
|
|
124
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
125
|
+
<config>
|
|
126
|
+
<object id="${assembly}">
|
|
127
|
+
<metadata key="name" value="${xmlAttribute(name)}"/>
|
|
128
|
+
<metadata key="extruder" value="${parts[0].filament}"/>
|
|
129
|
+
${partBlocks}
|
|
130
|
+
</object>
|
|
131
|
+
</config>
|
|
132
|
+
`;
|
|
133
|
+
}
|
|
134
|
+
const CONTENT_TYPES = `<?xml version="1.0" encoding="UTF-8"?>
|
|
135
|
+
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
|
136
|
+
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
|
|
137
|
+
<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/>
|
|
138
|
+
<Default Extension="config" ContentType="application/octet-stream"/>
|
|
139
|
+
</Types>
|
|
140
|
+
`;
|
|
141
|
+
const RELATIONSHIPS = `<?xml version="1.0" encoding="UTF-8"?>
|
|
142
|
+
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
|
143
|
+
<Relationship Target="/3D/3dmodel.model" Id="rel-1" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>
|
|
144
|
+
</Relationships>
|
|
145
|
+
`;
|
|
146
|
+
/** Where the assembly's footprint centre goes: the configured model's bed centre, else a 256 mm bed's. */
|
|
147
|
+
function plateCentre() {
|
|
148
|
+
const model = normalizeModel(process.env.BAMBU_PRINTER_MODEL || process.env.BAMBU_MODEL);
|
|
149
|
+
const volume = model ? MACHINE_LIMITS[model]?.volume : undefined;
|
|
150
|
+
return volume ? [volume[0] / 2, volume[1] / 2] : [128, 128];
|
|
151
|
+
}
|
|
152
|
+
export async function makeCounterpart3mf(args) {
|
|
153
|
+
if (Object.keys(args).some(key => key !== "parts" && key !== "out_path"))
|
|
154
|
+
fail("counterpart_make_3mf accepts only parts and out_path.");
|
|
155
|
+
if (!Array.isArray(args.parts) || args.parts.length === 0 || args.parts.length > MAX_PARTS)
|
|
156
|
+
fail(`parts must list 1 to ${MAX_PARTS} STL parts.`);
|
|
157
|
+
const requested = path.resolve(nonEmptyText(args.out_path, "out_path"));
|
|
158
|
+
if (path.extname(requested).toLowerCase() !== ".3mf")
|
|
159
|
+
fail("out_path must name a new .3mf file.");
|
|
160
|
+
const directory = await fs.realpath(path.dirname(requested)).catch(() => fail("out_path parent directory must already exist."));
|
|
161
|
+
const outPath = path.join(directory, path.basename(requested));
|
|
162
|
+
const existing = await fs.lstat(outPath).catch((error) => {
|
|
163
|
+
if (error.code !== "ENOENT")
|
|
164
|
+
fail("out_path cannot be accessed.");
|
|
165
|
+
return undefined;
|
|
166
|
+
});
|
|
167
|
+
if (existing)
|
|
168
|
+
fail("out_path already exists; choose a new file. Existing files are never overwritten.");
|
|
169
|
+
const parts = [];
|
|
170
|
+
let triangles = 0;
|
|
171
|
+
for (const [index, value] of args.parts.entries()) {
|
|
172
|
+
const label = `parts[${index}]`;
|
|
173
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
174
|
+
fail(`${label} must be an object with stl_path and name.`);
|
|
175
|
+
const entry = value;
|
|
176
|
+
if (Object.keys(entry).some(key => !PART_KEYS.has(key)))
|
|
177
|
+
fail(`${label} accepts only stl_path, name and filament.`);
|
|
178
|
+
const name = nonEmptyText(entry.name, `${label}.name`).trim();
|
|
179
|
+
const stlPath = path.resolve(nonEmptyText(entry.stl_path, `${label}.stl_path`));
|
|
180
|
+
if (path.extname(stlPath).toLowerCase() !== ".stl")
|
|
181
|
+
fail(`${label}.stl_path must name an STL file.`);
|
|
182
|
+
const filament = entry.filament ?? index + 1;
|
|
183
|
+
if (typeof filament !== "number" || !Number.isInteger(filament) || filament < 1 || filament > MAX_FILAMENT) {
|
|
184
|
+
fail(`${label}.filament must be an integer from 1 to ${MAX_FILAMENT}.`);
|
|
185
|
+
}
|
|
186
|
+
const mesh = await readMesh(await fs.realpath(stlPath).catch(() => fail(`${label}.stl_path does not exist.`)), `${label}.stl_path`);
|
|
187
|
+
triangles += mesh.triangles;
|
|
188
|
+
if (triangles > MAX_TOTAL_TRIANGLES)
|
|
189
|
+
fail(`The parts have more than ${MAX_TOTAL_TRIANGLES} triangles in total; decimate them first.`);
|
|
190
|
+
parts.push({ name, stlPath, filament, mesh });
|
|
191
|
+
}
|
|
192
|
+
// One shared translation: footprint centred on the plate, lowest point on the bed.
|
|
193
|
+
const min = [0, 1, 2].map(axis => Math.min(...parts.map(part => part.mesh.min[axis])));
|
|
194
|
+
const max = [0, 1, 2].map(axis => Math.max(...parts.map(part => part.mesh.max[axis])));
|
|
195
|
+
const [centreX, centreY] = plateCentre();
|
|
196
|
+
const transform = [centreX - (min[0] + max[0]) / 2, centreY - (min[1] + max[1]) / 2, -min[2]];
|
|
197
|
+
const zip = new JSZip();
|
|
198
|
+
zip.file("[Content_Types].xml", CONTENT_TYPES);
|
|
199
|
+
zip.file("_rels/.rels", RELATIONSHIPS);
|
|
200
|
+
zip.file("3D/3dmodel.model", modelXml(parts, transform));
|
|
201
|
+
zip.file("Metadata/model_settings.config", modelSettingsXml(parts, path.basename(outPath, path.extname(outPath))));
|
|
202
|
+
const bytes = await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE", compressionOptions: { level: 6 } });
|
|
203
|
+
const staged = path.join(directory, `.counterpart-${randomUUID()}.3mf`);
|
|
204
|
+
try {
|
|
205
|
+
await fs.writeFile(staged, bytes, { flag: "wx" });
|
|
206
|
+
// link() publishes without replacing a file created since the check above.
|
|
207
|
+
await fs.link(staged, outPath).catch(() => fail("Cannot write out_path; it may already exist or be unwritable."));
|
|
208
|
+
}
|
|
209
|
+
finally {
|
|
210
|
+
await fs.rm(staged, { force: true }).catch(() => { });
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
contract: COUNTERPART_CONTRACT,
|
|
214
|
+
path: outPath,
|
|
215
|
+
objects: 1,
|
|
216
|
+
filaments: Math.max(...parts.map(part => part.filament)),
|
|
217
|
+
parts: parts.map(part => ({ name: part.name, stl_path: part.stlPath, filament: part.filament, triangles: part.mesh.triangles })),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { type HmsText } from "../safety/hms-messages.js";
|
|
2
|
+
import { type PrintProgress, type PrintState, type Problem } from "./schemas.js";
|
|
3
|
+
/** print_error / fail_reason 0300400C: "The task was canceled." in every bundled Bambu Studio table. */
|
|
4
|
+
export declare const TASK_CANCELLED = 50348044;
|
|
5
|
+
/** Bambu reports a user cancel as FAILED with 0300400C in print_error, or (X2D) in fail_reason. */
|
|
6
|
+
export declare function isCancelledReport(raw: Record<string, any>): boolean;
|
|
7
|
+
/** gcode_state → counterpart/1 state. A connected printer with no or an unknown gcode_state is busy. */
|
|
8
|
+
export declare function bambuState(raw: Record<string, any>): PrintState;
|
|
9
|
+
/** 16 hex digits (attr then code) as Bambu writes them: AAAA_BBBB_CCCC_DDDD. */
|
|
10
|
+
export declare function formatHmsCode(hex: string): string;
|
|
11
|
+
/** Bambu's page for an HMS code, as Bambu Studio's get_hms_wiki_url builds it, without the device serial. */
|
|
12
|
+
export declare function hmsUrl(hex: string): string;
|
|
13
|
+
/** The table text for this printer's serial prefix, else the text most tables use. */
|
|
14
|
+
export declare function tableText(table: Readonly<Record<string, HmsText>>, code: string, serial: string): string | undefined;
|
|
15
|
+
/** Bambu Studio's words for stg_cur. Like MachineObject::get_curr_stage, none without a stage list. */
|
|
16
|
+
export declare function stageWords(raw: Record<string, any>): string | undefined;
|
|
17
|
+
/** print_error and hms[] as problems, in report order, without duplicates. */
|
|
18
|
+
export declare function bambuProblems(raw: Record<string, any>, serial: string, model: string): Problem[];
|
|
19
|
+
/** A printer file path's basename (the jobName raw G-code prints return), as KAN-216 reads it. */
|
|
20
|
+
export declare function remoteJobName(value: unknown): string | undefined;
|
|
21
|
+
/** One merged MQTT report and the time it arrived → counterpart/1 progress. */
|
|
22
|
+
export declare function bambuProgress(raw: Record<string, any>, options: {
|
|
23
|
+
receivedAt: number;
|
|
24
|
+
serial: string;
|
|
25
|
+
model?: string;
|
|
26
|
+
}): PrintProgress;
|
|
27
|
+
/** No report arrived: the printer is unreachable over MQTT. */
|
|
28
|
+
export declare function offlineProgress(observedAt: number): PrintProgress;
|