bambu-printer-mcp 1.0.0

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.
@@ -0,0 +1,57 @@
1
+ export type BambuFTP = {
2
+ readDir: (path: string) => Promise<string[]>;
3
+ sendFile: (sourcePath: string, destinationPath: string, progressCallback?: (progress: number) => void) => Promise<void>;
4
+ removeFile: (path: string) => Promise<void>;
5
+ };
6
+ export interface SectionBounds {
7
+ minX: number;
8
+ minY: number;
9
+ minZ: number;
10
+ maxX: number;
11
+ maxY: number;
12
+ maxZ: number;
13
+ }
14
+ export interface ThreeMFMetadata {
15
+ [key: string]: string;
16
+ }
17
+ export interface ThreeMFObject {
18
+ id: string;
19
+ name?: string;
20
+ type?: string;
21
+ mesh?: any;
22
+ }
23
+ export interface ThreeMFBuildItem {
24
+ objectId: string;
25
+ transform?: string;
26
+ }
27
+ export interface AMSFilamentMapping {
28
+ [filamentId: string]: number;
29
+ }
30
+ export interface BambuSlicerConfig {
31
+ layer_height?: number;
32
+ first_layer_height?: number;
33
+ sparse_infill_density?: number;
34
+ sparse_infill_pattern?: string;
35
+ support_enabled?: boolean;
36
+ support_type?: string;
37
+ support_threshold_angle?: number;
38
+ raft_layers?: number;
39
+ brim_width?: number;
40
+ wall_loops?: number;
41
+ top_shell_layers?: number;
42
+ bottom_shell_layers?: number;
43
+ nozzle_temperature?: number[];
44
+ bed_temperature?: number;
45
+ filament_type?: string[];
46
+ flow_ratio?: number[];
47
+ ams_mapping?: AMSFilamentMapping;
48
+ [key: string]: any;
49
+ }
50
+ export interface ThreeMFData {
51
+ metadata: ThreeMFMetadata;
52
+ objects: ThreeMFObject[];
53
+ build: {
54
+ items: ThreeMFBuildItem[];
55
+ };
56
+ slicerConfig?: Partial<BambuSlicerConfig>;
57
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "bambu-printer-mcp",
3
+ "version": "1.0.0",
4
+ "description": "MCP server for Bambu Lab 3D printers with STL manipulation, slicing, and print management",
5
+ "main": "dist/index.js",
6
+ "repository": "https://github.com/DMontgomery40/bambu-printer-mcp",
7
+ "type": "module",
8
+ "scripts": {
9
+ "start": "node dist/index.js",
10
+ "start:stdio": "MCP_TRANSPORT=stdio node dist/index.js",
11
+ "start:http": "MCP_TRANSPORT=streamable-http node dist/index.js",
12
+ "build": "tsc",
13
+ "test": "npm run build && node --test tests/**/*.test.mjs"
14
+ },
15
+ "bin": {
16
+ "bambu-printer-mcp": "./dist/index.js"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "src",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "keywords": [
25
+ "mcp",
26
+ "3d-printer",
27
+ "bambu",
28
+ "bambu-lab",
29
+ "bambu-studio",
30
+ "stl",
31
+ "3mf"
32
+ ],
33
+ "author": "David Montgomery",
34
+ "license": "GPL-2.0",
35
+ "dependencies": {
36
+ "@modelcontextprotocol/sdk": "^1.27.0",
37
+ "bambu-js": "^2.2.2",
38
+ "bambu-node": "^3.22.21",
39
+ "basic-ftp": "^5.0.5",
40
+ "dotenv": "^16.3.1",
41
+ "jszip": "^3.10.1",
42
+ "three": "^0.173.0",
43
+ "xml2js": "^0.6.2",
44
+ "zod": "^3.25.76"
45
+ },
46
+ "devDependencies": {
47
+ "@types/jszip": "^3.4.0",
48
+ "@types/node": "^18.0.0",
49
+ "@types/three": "^0.173.0",
50
+ "@types/xml2js": "^0.4.14"
51
+ }
52
+ }
@@ -0,0 +1,223 @@
1
+ import JSZip from 'jszip';
2
+ import { parseStringPromise } from 'xml2js';
3
+ import { ThreeMFData, BambuSlicerConfig, ThreeMFMetadata, ThreeMFObject, ThreeMFBuildItem, AMSFilamentMapping } from './types.js';
4
+ import * as fs from 'fs/promises';
5
+
6
+ // Parses Bambu Studio's JSON config data
7
+ function parseBambuJSONConfig(jsonData: any): Partial<BambuSlicerConfig> {
8
+ const config: Partial<BambuSlicerConfig> = {};
9
+ const amsMapping: AMSFilamentMapping = {};
10
+
11
+ // Map known keys, converting types as needed
12
+ if (jsonData.layer_height !== undefined) config.layer_height = parseFloat(jsonData.layer_height);
13
+ if (jsonData.initial_layer_print_height !== undefined) config.first_layer_height = parseFloat(jsonData.initial_layer_print_height);
14
+ if (jsonData.sparse_infill_density !== undefined) config.sparse_infill_density = parseFloat(jsonData.sparse_infill_density);
15
+ if (jsonData.sparse_infill_pattern !== undefined) config.sparse_infill_pattern = String(jsonData.sparse_infill_pattern);
16
+ if (jsonData.enable_support !== undefined) config.support_enabled = String(jsonData.enable_support) === '1' || String(jsonData.enable_support).toLowerCase() === 'true';
17
+ if (jsonData.support_type !== undefined) config.support_type = String(jsonData.support_type);
18
+ if (jsonData.support_angle !== undefined) config.support_threshold_angle = parseFloat(jsonData.support_angle);
19
+ if (jsonData.raft_layers !== undefined) config.raft_layers = parseInt(String(jsonData.raft_layers), 10);
20
+ if (jsonData.brim_width !== undefined) config.brim_width = parseFloat(jsonData.brim_width);
21
+ if (jsonData.wall_loops !== undefined) config.wall_loops = parseInt(String(jsonData.wall_loops), 10);
22
+ if (jsonData.top_shell_layers !== undefined) config.top_shell_layers = parseInt(String(jsonData.top_shell_layers), 10);
23
+ if (jsonData.bottom_shell_layers !== undefined) config.bottom_shell_layers = parseInt(String(jsonData.bottom_shell_layers), 10);
24
+
25
+ // Temperatures (handle potential arrays)
26
+ if (Array.isArray(jsonData.nozzle_temperature) && jsonData.nozzle_temperature.length > 0) {
27
+ config.nozzle_temperature = jsonData.nozzle_temperature.map((t: string | number) => parseFloat(String(t)));
28
+ } else if (jsonData.nozzle_temperature !== undefined) {
29
+ config.nozzle_temperature = [parseFloat(String(jsonData.nozzle_temperature))];
30
+ }
31
+ // Bed Temp (prefer initial layer temp)
32
+ let bedTempKey = jsonData.hot_plate_temp_initial_layer !== undefined ? 'hot_plate_temp_initial_layer' : 'hot_plate_temp';
33
+ if (jsonData[bedTempKey] !== undefined) {
34
+ if (Array.isArray(jsonData[bedTempKey]) && jsonData[bedTempKey].length > 0) {
35
+ config.bed_temperature = parseFloat(String(jsonData[bedTempKey][0]));
36
+ } else {
37
+ config.bed_temperature = parseFloat(String(jsonData[bedTempKey]));
38
+ }
39
+ }
40
+
41
+ // Filaments and Flow (handle potential arrays)
42
+ if (Array.isArray(jsonData.filament_type) && jsonData.filament_type.length > 0) {
43
+ config.filament_type = jsonData.filament_type.map(String);
44
+ }
45
+ if (Array.isArray(jsonData.filament_flow_ratio) && jsonData.filament_flow_ratio.length > 0) {
46
+ config.flow_ratio = jsonData.filament_flow_ratio.map((f: string | number) => parseFloat(String(f)));
47
+ }
48
+
49
+ // AMS Mapping (derive from filament_settings_id order)
50
+ if (Array.isArray(jsonData.filament_settings_id) && jsonData.filament_settings_id.length > 0) {
51
+ jsonData.filament_settings_id.forEach((filamentId: string, index: number) => {
52
+ // Map filament ID (e.g., "Generic PLA @BBL P1P") to its index (assumed AMS slot)
53
+ if (filamentId) { // Ensure filamentId is not empty
54
+ amsMapping[filamentId] = index;
55
+ }
56
+ });
57
+ if (Object.keys(amsMapping).length > 0) {
58
+ config.ams_mapping = amsMapping;
59
+ }
60
+ }
61
+
62
+ // Store remaining keys found in the config
63
+ for (const key in jsonData) {
64
+ if (!config.hasOwnProperty(key)) {
65
+ // Simple assignment for remaining keys, preserving original type if possible
66
+ config[key] = jsonData[key];
67
+ }
68
+ }
69
+
70
+ return config;
71
+ }
72
+
73
+ async function parseBambuConfig(zip: JSZip): Promise<Partial<BambuSlicerConfig>> {
74
+ // Look for common Bambu config file names
75
+ const potentialFiles = ['Metadata/project_settings.config', 'Metadata/model_settings.config', 'Metadata/slice_info.config'];
76
+ let configFile = null;
77
+ let configContent = '';
78
+
79
+ for (const name of potentialFiles) {
80
+ const file = zip.file(name);
81
+ if (file) {
82
+ configFile = file;
83
+ configContent = await file.async('string');
84
+ console.log(`Found Bambu config file: ${configFile.name}`);
85
+ break; // Use the first one found (project usually has the most)
86
+ }
87
+ }
88
+
89
+ if (configFile && configContent) {
90
+ try {
91
+ // Attempt to parse as JSON
92
+ const jsonData = JSON.parse(configContent);
93
+ const parsedConfig = parseBambuJSONConfig(jsonData);
94
+ console.log('Bambu config parsed successfully as JSON.');
95
+ return parsedConfig;
96
+ } catch (jsonError: any) {
97
+ console.warn(`Failed to parse ${configFile.name} as JSON: ${jsonError.message}. Attempting INI parse as fallback...`);
98
+ // Fallback: Try parsing as INI if JSON fails (though unlikely based on sample)
99
+ try {
100
+ const parsedConfig = parseFallbackINIConfig(configContent); // Keep a simple INI parser as fallback
101
+ console.log('Bambu config parsed successfully as INI (fallback).');
102
+ return parsedConfig;
103
+ } catch (iniError: any) {
104
+ console.error(`Error parsing Bambu config ${configFile.name} as INI (fallback):`, iniError);
105
+ return {};
106
+ }
107
+ }
108
+ } else {
109
+ console.log('No Bambu-specific config file found in Metadata directory.');
110
+ return {};
111
+ }
112
+ }
113
+
114
+ // Fallback INI parser (Simplified version of the previous one)
115
+ function parseFallbackINIConfig(configContent: string): Partial<BambuSlicerConfig> {
116
+ const config: Partial<BambuSlicerConfig> = {};
117
+ const lines = configContent.split(/\r?\n/);
118
+ for (const line of lines) {
119
+ const trimmedLine = line.trim();
120
+ if (!trimmedLine || trimmedLine.startsWith('#') || trimmedLine.startsWith(';')) continue;
121
+ const equalsIndex = trimmedLine.indexOf('=');
122
+ if (equalsIndex === -1) continue;
123
+ const key = trimmedLine.substring(0, equalsIndex).trim();
124
+ const value = trimmedLine.substring(equalsIndex + 1).trim();
125
+ // Simple assignment - no type conversion here for fallback
126
+ config[key] = value;
127
+ }
128
+ return config;
129
+ }
130
+
131
+ async function parse3DModelConfig(zip: JSZip): Promise<{ metadata: ThreeMFMetadata, objects: ThreeMFObject[], build: { items: ThreeMFBuildItem[] } }> {
132
+ const modelFile = zip.file('3D/3dmodel.model');
133
+ if (!modelFile) {
134
+ throw new Error('3D/3dmodel.model not found in 3MF archive');
135
+ }
136
+
137
+ const modelContent = await modelFile.async('string');
138
+ try {
139
+ const parsedXml = await parseStringPromise(modelContent, {
140
+ explicitArray: false,
141
+ mergeAttrs: true,
142
+ charkey: 'value'
143
+ });
144
+
145
+ const modelData = parsedXml.model;
146
+ if (!modelData) {
147
+ throw new Error('Invalid 3dmodel.model format: <model> tag not found.');
148
+ }
149
+
150
+ const metadata: ThreeMFMetadata = { unit: modelData.unit || 'millimeter' };
151
+ if (modelData.metadata) {
152
+ const metas = Array.isArray(modelData.metadata) ? modelData.metadata : [modelData.metadata];
153
+ metas.forEach((meta: any) => {
154
+ if (meta.name && meta.value !== undefined) {
155
+ metadata[meta.name] = String(meta.value);
156
+ }
157
+ });
158
+ }
159
+
160
+ const objects: ThreeMFObject[] = [];
161
+ if (modelData.resources?.object) {
162
+ const resources = Array.isArray(modelData.resources.object) ? modelData.resources.object : [modelData.resources.object];
163
+ resources.forEach((objResource: any) => {
164
+ objects.push({
165
+ id: objResource.id,
166
+ name: objResource.name,
167
+ type: objResource.type || 'model'
168
+ // Actual mesh data (vertices, triangles) is nested deeper if needed
169
+ });
170
+ });
171
+ }
172
+
173
+ const buildItems: ThreeMFBuildItem[] = [];
174
+ if (modelData.build?.item) {
175
+ const items = Array.isArray(modelData.build.item) ? modelData.build.item : [modelData.build.item];
176
+ items.forEach((item: any) => {
177
+ buildItems.push({
178
+ objectId: item.objectid,
179
+ transform: item.transform
180
+ });
181
+ });
182
+ }
183
+
184
+ console.log('3dmodel.model parsed successfully.');
185
+ return { metadata, objects, build: { items: buildItems } };
186
+
187
+ } catch (error: any) {
188
+ console.error('Error parsing 3dmodel.model XML:', error);
189
+ throw new Error(`Failed to parse 3dmodel.model: ${error.message}`);
190
+ }
191
+ }
192
+
193
+ export { ThreeMFData };
194
+
195
+ export async function parse3MF(filePath: string): Promise<ThreeMFData> {
196
+ console.log(`Parsing 3MF file: ${filePath}`);
197
+ try {
198
+ const data = await fs.readFile(filePath);
199
+ const zip = await JSZip.loadAsync(data);
200
+
201
+ // List files for debugging
202
+ // const fileList = Object.keys(zip.files);
203
+ // console.log('Files in 3MF:', fileList);
204
+
205
+ const { metadata, objects, build } = await parse3DModelConfig(zip);
206
+ const bambuConfig = await parseBambuConfig(zip);
207
+
208
+ // Combine data into the final structure
209
+ const combinedData: ThreeMFData = {
210
+ metadata,
211
+ objects,
212
+ build,
213
+ slicerConfig: bambuConfig
214
+ };
215
+
216
+ console.log('3MF parsing completed.');
217
+ return combinedData;
218
+
219
+ } catch (error: any) {
220
+ console.error(`Error parsing 3MF file ${filePath}:`, error);
221
+ throw new Error(`Failed to parse 3MF file: ${error.message}`);
222
+ }
223
+ }