-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
945 lines (856 loc) · 38.7 KB
/
index.js
File metadata and controls
945 lines (856 loc) · 38.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
#!/usr/bin/env node
/**
* MCP 3D Print Optimizer v0.1.0
* Optimizes 3D printing settings based on print results feedback loop.
* Works with OrcaSlicer CLI + Claude Vision for quality assessment.
*
* Phase 1: Profile management + DB + print tracking
* Phase 2: Slicing + quality assessment
* Phase 3: Optimization engine
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
import Database from 'better-sqlite3';
import { execFile } from 'child_process';
import { readdir, readFile, stat } from 'fs/promises';
import { join, basename } from 'path';
import { homedir } from 'os';
// ─── Configuration ───────────────────────────────────────────────
const HOME = homedir();
const ORCASLICER_BIN = process.env.ORCASLICER_BIN || findOrcaSlicer();
const ORCASLICER_CONFIG = process.env.ORCASLICER_CONFIG || join(HOME, '.config', 'OrcaSlicer');
const SYSTEM_PROFILES = join(ORCASLICER_CONFIG, 'system', 'Creality');
const USER_PROFILES = join(ORCASLICER_CONFIG, 'user');
const DB_PATH = process.env.PRINT_DB || join(HOME, '.local', 'share', 'mcp-servers', '3dprint-optimizer', 'print_optimizer.db');
const OPTIMIZED_PROFILES_DIR = join(HOME, '.local', 'share', 'mcp-servers', '3dprint-optimizer', 'profiles');
function findOrcaSlicer() {
const candidates = [
join(HOME, 'Applications', 'OrcaSlicer_Linux_AppImage_Ubuntu2404_V2.3.2-rc2.AppImage'),
join(HOME, 'Applications', 'OrcaSlicer.AppImage'),
'/usr/bin/orcaslicer',
'/usr/local/bin/orcaslicer',
];
// Will be resolved at first use
return candidates[0];
}
// ─── Database Setup ──────────────────────────────────────────────
import { mkdirSync } from 'fs';
mkdirSync(join(HOME, '.local', 'share', 'mcp-servers', '3dprint-optimizer', 'profiles'), { recursive: true });
const db = new Database(DB_PATH);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
db.exec(`
CREATE TABLE IF NOT EXISTS prints (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT DEFAULT (datetime('now')),
model_name TEXT NOT NULL,
model_file TEXT,
model_type TEXT,
filament_type TEXT NOT NULL DEFAULT 'PLA',
filament_brand TEXT,
nozzle_diameter REAL DEFAULT 0.4,
status TEXT DEFAULT 'planned',
notes TEXT
);
CREATE TABLE IF NOT EXISTS print_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
print_id INTEGER NOT NULL REFERENCES prints(id),
layer_height REAL,
initial_layer_height REAL,
line_width REAL,
wall_loops INTEGER,
top_shell_layers INTEGER,
bottom_shell_layers INTEGER,
sparse_infill_density REAL,
sparse_infill_pattern TEXT,
outer_wall_speed REAL,
inner_wall_speed REAL,
sparse_infill_speed REAL,
top_surface_speed REAL,
travel_speed REAL,
initial_layer_speed REAL,
bridge_speed REAL,
bridge_flow REAL,
enable_support INTEGER,
support_type TEXT,
support_threshold_angle REAL,
brim_width REAL,
ironing_type TEXT,
ironing_speed REAL,
seam_position TEXT,
nozzle_temp INTEGER,
bed_temp INTEGER,
fan_speed_percent REAL,
retraction_length REAL,
retraction_speed REAL,
full_settings_json TEXT,
source TEXT DEFAULT 'manual'
);
CREATE TABLE IF NOT EXISTS quality_assessments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
print_id INTEGER NOT NULL REFERENCES prints(id),
assessed_at TEXT DEFAULT (datetime('now')),
overall_score REAL,
surface_quality REAL,
layer_adhesion REAL,
dimensional_accuracy REAL,
stringing REAL,
warping REAL,
overhang_quality REAL,
first_layer_adhesion REAL,
support_removal REAL,
defects TEXT,
photo_paths TEXT,
notes TEXT,
assessed_by TEXT DEFAULT 'claude'
);
CREATE TABLE IF NOT EXISTS optimization_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT DEFAULT (datetime('now')),
print_id INTEGER REFERENCES prints(id),
previous_print_id INTEGER REFERENCES prints(id),
parameter_changes TEXT,
reasoning TEXT,
outcome TEXT
);
CREATE INDEX IF NOT EXISTS idx_prints_model_type ON prints(model_type);
CREATE INDEX IF NOT EXISTS idx_prints_filament ON prints(filament_type);
CREATE INDEX IF NOT EXISTS idx_quality_print ON quality_assessments(print_id);
CREATE INDEX IF NOT EXISTS idx_settings_print ON print_settings(print_id);
`);
// ─── Helper: Run OrcaSlicer CLI ──────────────────────────────────
function runOrcaSlicer(args, timeout = 30000) {
return new Promise((resolve, reject) => {
execFile(ORCASLICER_BIN, args, { timeout }, (err, stdout, stderr) => {
if (err) return reject(new Error(`OrcaSlicer error: ${err.message}\n${stderr}`));
resolve(stdout);
});
});
}
// ─── Helper: Read JSON file ──────────────────────────────────────
async function readJsonFile(path) {
const content = await readFile(path, 'utf-8');
return JSON.parse(content);
}
// ─── Helper: List JSON files in directory ────────────────────────
async function listJsonFiles(dir) {
try {
const files = await readdir(dir);
return files.filter(f => f.endsWith('.json')).sort();
} catch {
return [];
}
}
// ─── Helper: Extract key settings from full profile ──────────────
function extractKeySettings(profile) {
const keys = [
'layer_height', 'initial_layer_height', 'line_width',
'wall_loops', 'top_shell_layers', 'bottom_shell_layers',
'sparse_infill_density', 'sparse_infill_pattern',
'outer_wall_speed', 'inner_wall_speed', 'sparse_infill_speed',
'top_surface_speed', 'travel_speed', 'initial_layer_speed',
'bridge_speed', 'bridge_flow',
'enable_support', 'support_type', 'support_threshold_angle',
'brim_width', 'ironing_type', 'ironing_speed', 'seam_position',
'nozzle_temperature', 'bed_temperature',
'fan_min_speed', 'retraction_length', 'retraction_speed',
];
const result = {};
for (const key of keys) {
if (profile[key] !== undefined) {
result[key] = profile[key];
}
}
return result;
}
// ─── MCP Server ──────────────────────────────────────────────────
const server = new McpServer({
name: '3dprint-optimizer',
version: '0.1.0',
});
// ═══════════════════════════════════════════════════════════════════
// PROFILE MANAGEMENT TOOLS
// ═══════════════════════════════════════════════════════════════════
server.tool(
'print3d_list_profiles',
'List available OrcaSlicer process/filament/machine profiles',
{
type: z.enum(['process', 'filament', 'machine']).describe('Profile type to list'),
filter: z.string().optional().describe('Filter profiles by name (case-insensitive)'),
},
async ({ type, filter }) => {
const dir = join(SYSTEM_PROFILES, type);
const files = await listJsonFiles(dir);
let profiles = files.map(f => f.replace('.json', ''));
if (filter) {
const lower = filter.toLowerCase();
profiles = profiles.filter(p => p.toLowerCase().includes(lower));
}
// Also check user profiles
const userDir = join(USER_PROFILES, type);
const userFiles = await listJsonFiles(userDir);
const userProfiles = userFiles.map(f => `[USER] ${f.replace('.json', '')}`);
if (filter) {
const lower = filter.toLowerCase();
profiles = profiles.concat(userProfiles.filter(p => p.toLowerCase().includes(lower)));
} else {
profiles = profiles.concat(userProfiles);
}
return {
content: [{
type: 'text',
text: `Found ${profiles.length} ${type} profiles:\n\n${profiles.join('\n')}`,
}],
};
}
);
server.tool(
'print3d_read_profile',
'Read and display a specific OrcaSlicer profile with key settings',
{
type: z.enum(['process', 'filament', 'machine']).describe('Profile type'),
name: z.string().describe('Profile name (without .json extension)'),
},
async ({ type, name }) => {
// Try system profiles first, then user
let filePath = join(SYSTEM_PROFILES, type, `${name}.json`);
let source = 'system';
try {
await stat(filePath);
} catch {
filePath = join(USER_PROFILES, type, `${name}.json`);
source = 'user';
}
try {
const profile = await readJsonFile(filePath);
const keySettings = extractKeySettings(profile);
const inherits = profile.inherits || 'none';
let text = `Profile: ${name}\nSource: ${source}\nType: ${type}\nInherits: ${inherits}\n\n`;
text += `Key Settings:\n`;
for (const [k, v] of Object.entries(keySettings)) {
text += ` ${k}: ${JSON.stringify(v)}\n`;
}
text += `\nAll settings (${Object.keys(profile).length} keys) available in full_json.`;
return {
content: [{
type: 'text',
text,
}],
};
} catch (err) {
return {
content: [{ type: 'text', text: `Error reading profile: ${err.message}` }],
isError: true,
};
}
}
);
server.tool(
'print3d_active_config',
'Show current active OrcaSlicer configuration (printer, filament, process)',
{},
async () => {
try {
const confPath = join(ORCASLICER_CONFIG, 'OrcaSlicer.conf');
const content = await readFile(confPath, 'utf-8');
const conf = JSON.parse(content);
const info = {
machine: conf.machine_list?.[0]?.name || 'unknown',
filament: conf.filament_list?.[0]?.name || 'unknown',
process: conf.process_list?.[0]?.name || 'unknown',
recent_files: (conf.recent_projects || []).slice(0, 5),
user_mode: conf.user_mode || 'unknown',
version: conf.version || 'unknown',
};
let text = `OrcaSlicer Active Configuration:\n\n`;
text += ` Version: ${info.version}\n`;
text += ` User Mode: ${info.user_mode}\n`;
text += ` Machine: ${info.machine}\n`;
text += ` Filament: ${info.filament}\n`;
text += ` Process: ${info.process}\n`;
text += `\nRecent Projects:\n`;
for (const f of info.recent_files) {
text += ` - ${f}\n`;
}
return { content: [{ type: 'text', text }] };
} catch (err) {
return {
content: [{ type: 'text', text: `Error reading config: ${err.message}` }],
isError: true,
};
}
}
);
// ═══════════════════════════════════════════════════════════════════
// PRINT TRACKING TOOLS
// ═══════════════════════════════════════════════════════════════════
server.tool(
'print3d_start_print',
'Register a new print in the database with model info and settings',
{
model_name: z.string().describe('Name of the model being printed'),
model_file: z.string().optional().describe('Path to .3mf or .stl file'),
model_type: z.enum(['mechanical', 'decorative', 'functional', 'miniature', 'prototype', 'other']).optional(),
filament_type: z.enum(['PLA', 'PETG', 'ABS', 'TPU', 'ASA', 'Nylon', 'PC', 'Other']).default('PLA'),
filament_brand: z.string().optional().describe('Filament brand name'),
nozzle_diameter: z.number().default(0.4),
profile_name: z.string().optional().describe('OrcaSlicer process profile name to snapshot'),
notes: z.string().optional(),
},
async ({ model_name, model_file, model_type, filament_type, filament_brand, nozzle_diameter, profile_name, notes }) => {
// Insert print record
const result = db.prepare(`
INSERT INTO prints (model_name, model_file, model_type, filament_type, filament_brand, nozzle_diameter, status, notes)
VALUES (?, ?, ?, ?, ?, ?, 'planned', ?)
`).run(model_name, model_file || null, model_type || null, filament_type, filament_brand || null, nozzle_diameter, notes || null);
const printId = result.lastInsertRowid;
// Snapshot settings from profile if provided
if (profile_name) {
try {
const filePath = join(SYSTEM_PROFILES, 'process', `${profile_name}.json`);
const profile = await readJsonFile(filePath);
const ks = extractKeySettings(profile);
db.prepare(`
INSERT INTO print_settings (
print_id, layer_height, initial_layer_height, line_width,
wall_loops, top_shell_layers, bottom_shell_layers,
sparse_infill_density, sparse_infill_pattern,
outer_wall_speed, inner_wall_speed, sparse_infill_speed,
top_surface_speed, travel_speed, initial_layer_speed,
bridge_speed, bridge_flow, enable_support, support_type,
support_threshold_angle, brim_width, ironing_type, ironing_speed,
seam_position, nozzle_temp, bed_temp, fan_speed_percent,
retraction_length, retraction_speed, full_settings_json, source
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'profile'
)
`).run(
printId,
ks.layer_height || null, ks.initial_layer_height || null, ks.line_width || null,
ks.wall_loops || null, ks.top_shell_layers || null, ks.bottom_shell_layers || null,
ks.sparse_infill_density || null, ks.sparse_infill_pattern || null,
ks.outer_wall_speed || null, ks.inner_wall_speed || null, ks.sparse_infill_speed || null,
ks.top_surface_speed || null, ks.travel_speed || null, ks.initial_layer_speed || null,
ks.bridge_speed || null, ks.bridge_flow || null, ks.enable_support || null, ks.support_type || null,
ks.support_threshold_angle || null, ks.brim_width || null, ks.ironing_type || null, ks.ironing_speed || null,
ks.seam_position || null, ks.nozzle_temperature || null, ks.bed_temperature || null,
ks.fan_min_speed || null, ks.retraction_length || null, ks.retraction_speed || null,
JSON.stringify(profile),
);
} catch (err) {
// Non-fatal: print created but settings snapshot failed
return {
content: [{ type: 'text', text: `Print #${printId} created but settings snapshot failed: ${err.message}` }],
};
}
}
return {
content: [{
type: 'text',
text: `Print #${printId} registered:\n Model: ${model_name}\n Filament: ${filament_type}${filament_brand ? ` (${filament_brand})` : ''}\n Nozzle: ${nozzle_diameter}mm\n Status: planned${profile_name ? `\n Settings snapshot: ${profile_name}` : ''}`,
}],
};
}
);
server.tool(
'print3d_list_prints',
'List print history with optional filters',
{
status: z.enum(['planned', 'sliced', 'printing', 'completed', 'failed', 'all']).default('all'),
filament: z.string().optional().describe('Filter by filament type'),
limit: z.number().default(20).describe('Max results'),
},
async ({ status, filament, limit }) => {
let sql = `SELECT p.*, qa.overall_score FROM prints p LEFT JOIN quality_assessments qa ON qa.print_id = p.id WHERE 1=1`;
const params = [];
if (status !== 'all') {
sql += ` AND p.status = ?`;
params.push(status);
}
if (filament) {
sql += ` AND p.filament_type = ?`;
params.push(filament);
}
sql += ` ORDER BY p.created_at DESC LIMIT ?`;
params.push(limit);
const rows = db.prepare(sql).all(...params);
if (rows.length === 0) {
return { content: [{ type: 'text', text: 'No prints found.' }] };
}
let text = `Print History (${rows.length} results):\n\n`;
for (const r of rows) {
const score = r.overall_score ? ` | Quality: ${r.overall_score}/10` : '';
text += `#${r.id} | ${r.model_name} | ${r.filament_type} | ${r.status}${score} | ${r.created_at}\n`;
}
return { content: [{ type: 'text', text }] };
}
);
server.tool(
'print3d_get_print',
'Get full details of a specific print including settings and quality',
{
print_id: z.number().describe('Print ID'),
},
async ({ print_id }) => {
const print = db.prepare('SELECT * FROM prints WHERE id = ?').get(print_id);
if (!print) {
return { content: [{ type: 'text', text: `Print #${print_id} not found.` }], isError: true };
}
const settings = db.prepare('SELECT * FROM print_settings WHERE print_id = ?').get(print_id);
const quality = db.prepare('SELECT * FROM quality_assessments WHERE print_id = ?').get(print_id);
let text = `Print #${print.id}\n`;
text += ` Model: ${print.model_name}\n`;
text += ` File: ${print.model_file || 'N/A'}\n`;
text += ` Type: ${print.model_type || 'N/A'}\n`;
text += ` Filament: ${print.filament_type}${print.filament_brand ? ` (${print.filament_brand})` : ''}\n`;
text += ` Nozzle: ${print.nozzle_diameter}mm\n`;
text += ` Status: ${print.status}\n`;
text += ` Created: ${print.created_at}\n`;
if (print.notes) text += ` Notes: ${print.notes}\n`;
if (settings) {
text += `\nSettings (source: ${settings.source}):\n`;
const skip = ['id', 'print_id', 'full_settings_json', 'source'];
for (const [k, v] of Object.entries(settings)) {
if (!skip.includes(k) && v !== null) {
text += ` ${k}: ${v}\n`;
}
}
}
if (quality) {
text += `\nQuality Assessment (${quality.assessed_at}):\n`;
text += ` Overall: ${quality.overall_score}/10\n`;
const metrics = ['surface_quality', 'layer_adhesion', 'dimensional_accuracy', 'stringing', 'warping', 'overhang_quality', 'first_layer_adhesion', 'support_removal'];
for (const m of metrics) {
if (quality[m] !== null) text += ` ${m}: ${quality[m]}/10\n`;
}
if (quality.defects) text += ` Defects: ${quality.defects}\n`;
if (quality.notes) text += ` Notes: ${quality.notes}\n`;
}
return { content: [{ type: 'text', text }] };
}
);
server.tool(
'print3d_update_status',
'Update the status of a print',
{
print_id: z.number().describe('Print ID'),
status: z.enum(['planned', 'sliced', 'printing', 'completed', 'failed']),
notes: z.string().optional(),
},
async ({ print_id, status, notes }) => {
const print = db.prepare('SELECT * FROM prints WHERE id = ?').get(print_id);
if (!print) {
return { content: [{ type: 'text', text: `Print #${print_id} not found.` }], isError: true };
}
if (notes) {
db.prepare('UPDATE prints SET status = ?, notes = COALESCE(notes || "\n", "") || ? WHERE id = ?').run(status, notes, print_id);
} else {
db.prepare('UPDATE prints SET status = ? WHERE id = ?').run(status, print_id);
}
return {
content: [{ type: 'text', text: `Print #${print_id} "${print.model_name}" status updated: ${print.status} → ${status}` }],
};
}
);
// ═══════════════════════════════════════════════════════════════════
// QUALITY ASSESSMENT TOOLS
// ═══════════════════════════════════════════════════════════════════
server.tool(
'print3d_assess_quality',
'Record quality assessment for a completed print (scores 1-10, 10=best)',
{
print_id: z.number().describe('Print ID to assess'),
overall_score: z.number().min(1).max(10),
surface_quality: z.number().min(1).max(10).optional(),
layer_adhesion: z.number().min(1).max(10).optional(),
dimensional_accuracy: z.number().min(1).max(10).optional(),
stringing: z.number().min(1).max(10).optional().describe('10=no stringing'),
warping: z.number().min(1).max(10).optional().describe('10=no warping'),
overhang_quality: z.number().min(1).max(10).optional(),
first_layer_adhesion: z.number().min(1).max(10).optional(),
support_removal: z.number().min(1).max(10).optional(),
defects: z.array(z.string()).optional().describe('List of defects: stringing, warping, elephant_foot, layer_shift, etc.'),
photo_paths: z.array(z.string()).optional().describe('Paths to photos of the print'),
notes: z.string().optional(),
},
async ({ print_id, overall_score, surface_quality, layer_adhesion, dimensional_accuracy, stringing, warping, overhang_quality, first_layer_adhesion, support_removal, defects, photo_paths, notes }) => {
const print = db.prepare('SELECT * FROM prints WHERE id = ?').get(print_id);
if (!print) {
return { content: [{ type: 'text', text: `Print #${print_id} not found.` }], isError: true };
}
db.prepare(`
INSERT INTO quality_assessments (
print_id, overall_score, surface_quality, layer_adhesion, dimensional_accuracy,
stringing, warping, overhang_quality, first_layer_adhesion, support_removal,
defects, photo_paths, notes
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
print_id, overall_score,
surface_quality || null, layer_adhesion || null, dimensional_accuracy || null,
stringing || null, warping || null, overhang_quality || null,
first_layer_adhesion || null, support_removal || null,
defects ? JSON.stringify(defects) : null,
photo_paths ? JSON.stringify(photo_paths) : null,
notes || null,
);
// Auto-update status to completed if not already
if (print.status !== 'completed' && print.status !== 'failed') {
db.prepare('UPDATE prints SET status = ? WHERE id = ?').run('completed', print_id);
}
return {
content: [{ type: 'text', text: `Quality assessment recorded for print #${print_id} "${print.model_name}": ${overall_score}/10${defects?.length ? `\nDefects: ${defects.join(', ')}` : ''}` }],
};
}
);
server.tool(
'print3d_compare_prints',
'Compare settings and quality between two prints',
{
print_id_a: z.number().describe('First print ID'),
print_id_b: z.number().describe('Second print ID'),
},
async ({ print_id_a, print_id_b }) => {
const printA = db.prepare('SELECT * FROM prints WHERE id = ?').get(print_id_a);
const printB = db.prepare('SELECT * FROM prints WHERE id = ?').get(print_id_b);
if (!printA || !printB) {
return { content: [{ type: 'text', text: 'One or both prints not found.' }], isError: true };
}
const settA = db.prepare('SELECT * FROM print_settings WHERE print_id = ?').get(print_id_a);
const settB = db.prepare('SELECT * FROM print_settings WHERE print_id = ?').get(print_id_b);
const qualA = db.prepare('SELECT * FROM quality_assessments WHERE print_id = ?').get(print_id_a);
const qualB = db.prepare('SELECT * FROM quality_assessments WHERE print_id = ?').get(print_id_b);
let text = `Comparison: Print #${print_id_a} vs #${print_id_b}\n\n`;
text += ` #${print_id_a}: ${printA.model_name} (${printA.filament_type})\n`;
text += ` #${print_id_b}: ${printB.model_name} (${printB.filament_type})\n\n`;
// Compare settings
if (settA && settB) {
text += `Settings Differences:\n`;
const skip = ['id', 'print_id', 'full_settings_json', 'source'];
let diffs = 0;
for (const key of Object.keys(settA)) {
if (skip.includes(key)) continue;
if (settA[key] !== settB[key] && (settA[key] !== null || settB[key] !== null)) {
text += ` ${key}: ${settA[key]} → ${settB[key]}\n`;
diffs++;
}
}
if (diffs === 0) text += ` (identical settings)\n`;
}
// Compare quality
text += `\nQuality Scores:\n`;
text += ` Overall: ${qualA?.overall_score || 'N/A'} vs ${qualB?.overall_score || 'N/A'}\n`;
const metrics = ['surface_quality', 'stringing', 'warping', 'layer_adhesion'];
for (const m of metrics) {
if (qualA?.[m] || qualB?.[m]) {
text += ` ${m}: ${qualA?.[m] || 'N/A'} vs ${qualB?.[m] || 'N/A'}\n`;
}
}
return { content: [{ type: 'text', text }] };
}
);
server.tool(
'print3d_quality_trends',
'Show quality score trends over time',
{
filament_type: z.string().optional().describe('Filter by filament type'),
model_type: z.string().optional().describe('Filter by model type'),
limit: z.number().default(20),
},
async ({ filament_type, model_type, limit }) => {
let sql = `
SELECT p.id, p.model_name, p.filament_type, p.model_type, p.created_at,
qa.overall_score, qa.surface_quality, qa.stringing, qa.warping
FROM prints p
JOIN quality_assessments qa ON qa.print_id = p.id
WHERE 1=1
`;
const params = [];
if (filament_type) { sql += ` AND p.filament_type = ?`; params.push(filament_type); }
if (model_type) { sql += ` AND p.model_type = ?`; params.push(model_type); }
sql += ` ORDER BY p.created_at ASC LIMIT ?`;
params.push(limit);
const rows = db.prepare(sql).all(...params);
if (rows.length === 0) {
return { content: [{ type: 'text', text: 'No assessed prints found.' }] };
}
let text = `Quality Trends (${rows.length} prints):\n\n`;
text += `Date | Model | Score | String | Warp\n`;
text += `-----------|----------------------|-------|--------|------\n`;
for (const r of rows) {
const date = r.created_at.substring(0, 10);
const name = r.model_name.substring(0, 20).padEnd(20);
text += `${date} | ${name} | ${(r.overall_score || 0).toFixed(1).padStart(5)} | ${(r.stringing || 0).toFixed(1).padStart(6)} | ${(r.warping || 0).toFixed(1).padStart(4)}\n`;
}
// Average
const avg = rows.reduce((s, r) => s + (r.overall_score || 0), 0) / rows.length;
text += `\nAverage overall score: ${avg.toFixed(1)}/10`;
return { content: [{ type: 'text', text }] };
}
);
// ═══════════════════════════════════════════════════════════════════
// SLICING TOOL
// ═══════════════════════════════════════════════════════════════════
server.tool(
'print3d_slice_model',
'Slice a 3D model with OrcaSlicer CLI using specified or optimized settings',
{
model_file: z.string().describe('Path to .3mf or .stl file'),
settings_file: z.string().optional().describe('Path to settings JSON override'),
output_dir: z.string().optional().describe('Output directory for gcode (default: same as model)'),
print_id: z.number().optional().describe('Link to existing print record'),
},
async ({ model_file, settings_file, output_dir, print_id }) => {
const args = ['--slice', '0'];
if (settings_file) args.push('--load-settings', settings_file);
if (output_dir) args.push('--outputdir', output_dir);
args.push(model_file);
try {
const output = await runOrcaSlicer(args, 120000);
if (print_id) {
db.prepare('UPDATE prints SET status = ? WHERE id = ?').run('sliced', print_id);
}
return {
content: [{ type: 'text', text: `Slicing complete!\n\nOutput:\n${output}` }],
};
} catch (err) {
return {
content: [{ type: 'text', text: `Slicing failed: ${err.message}` }],
isError: true,
};
}
}
);
// ═══════════════════════════════════════════════════════════════════
// OPTIMIZATION TOOLS (Phase 3 foundation)
// ═══════════════════════════════════════════════════════════════════
server.tool(
'print3d_suggest_settings',
'Suggest optimized settings based on print history and target priority',
{
filament_type: z.enum(['PLA', 'PETG', 'ABS', 'TPU', 'ASA', 'Nylon', 'PC', 'Other']).default('PLA'),
model_type: z.enum(['mechanical', 'decorative', 'functional', 'miniature', 'prototype', 'other']).optional(),
priority: z.enum(['quality', 'speed', 'strength']).default('quality'),
defects_to_fix: z.array(z.string()).optional().describe('Defects from last print to address'),
},
async ({ filament_type, model_type, priority, defects_to_fix }) => {
// Get best prints with this filament
let sql = `
SELECT p.*, qa.overall_score, ps.*
FROM prints p
JOIN quality_assessments qa ON qa.print_id = p.id
JOIN print_settings ps ON ps.print_id = p.id
WHERE p.filament_type = ?
`;
const params = [filament_type];
if (model_type) { sql += ` AND p.model_type = ?`; params.push(model_type); }
sql += ` ORDER BY qa.overall_score DESC LIMIT 5`;
const bestPrints = db.prepare(sql).all(...params);
// Defect -> parameter adjustment rules
const defectRules = {
stringing: { retraction_length: '+0.5', retraction_speed: '+5', travel_speed: '+20', nozzle_temp: '-5' },
warping: { bed_temp: '+5', brim_width: '+3', initial_layer_speed: '-5', fan_speed_percent: '-20 (first layers)' },
elephant_foot: { initial_layer_height: '-0.02' },
poor_overhangs: { bridge_speed: '-5', bridge_flow: '-0.05' },
layer_lines: { outer_wall_speed: '-10', layer_height: '-0.04', nozzle_temp: '+5' },
weak_parts: { wall_loops: '+1', sparse_infill_density: '+10', sparse_infill_pattern: 'gyroid' },
rough_top: { ironing_type: 'top', top_surface_speed: '-5', top_shell_layers: '+1' },
poor_adhesion: { initial_layer_height: '+0.02', initial_layer_speed: '-10', bed_temp: '+5' },
};
let text = `Optimization Suggestions (${filament_type}, priority: ${priority}):\n\n`;
if (bestPrints.length > 0) {
text += `Based on ${bestPrints.length} similar prints (best score: ${bestPrints[0].overall_score}/10):\n`;
const best = bestPrints[0];
text += ` Reference: Print #${best.print_id} - layer_height: ${best.layer_height}, wall_loops: ${best.wall_loops}, infill: ${best.sparse_infill_density}%\n\n`;
} else {
text += `No print history found for ${filament_type}. Using default recommendations.\n\n`;
}
if (defects_to_fix?.length) {
text += `Defect Fixes:\n`;
for (const defect of defects_to_fix) {
const rules = defectRules[defect];
if (rules) {
text += `\n ${defect}:\n`;
for (const [param, adj] of Object.entries(rules)) {
text += ` ${param}: ${adj}\n`;
}
} else {
text += `\n ${defect}: No known rule — describe the issue for manual analysis.\n`;
}
}
}
// Priority-based general tips
text += `\nPriority Tips (${priority}):\n`;
if (priority === 'quality') {
text += ` - Lower layer height (0.12-0.16mm)\n - Reduce outer wall speed (-20%)\n - Enable ironing for top surfaces\n - Use concentric top/bottom pattern\n`;
} else if (priority === 'speed') {
text += ` - Increase layer height (0.24-0.28mm)\n - Increase all speeds (+30%)\n - Reduce wall loops to 2\n - Lower infill density\n`;
} else if (priority === 'strength') {
text += ` - Increase wall loops (4+)\n - Use gyroid infill at 30%+\n - Increase nozzle temp (+5-10C)\n - Wider line width (0.45-0.5mm)\n`;
}
return { content: [{ type: 'text', text }] };
}
);
server.tool(
'print3d_diagnose_defect',
'Diagnose a specific print defect and suggest parameter fixes',
{
defect: z.string().describe('Defect description: stringing, warping, elephant_foot, layer_shift, under_extrusion, over_extrusion, poor_adhesion, rough_top, weak_parts, poor_overhangs'),
current_settings: z.object({
nozzle_temp: z.number().optional(),
bed_temp: z.number().optional(),
retraction_length: z.number().optional(),
retraction_speed: z.number().optional(),
outer_wall_speed: z.number().optional(),
layer_height: z.number().optional(),
fan_speed: z.number().optional(),
}).optional().describe('Current relevant settings for context'),
},
async ({ defect, current_settings }) => {
const diagnoses = {
stringing: {
cause: 'Filament oozing during travel moves',
fixes: [
'Increase retraction length by 0.5-1mm (current: {retraction_length}mm)',
'Increase retraction speed by 5-10mm/s (current: {retraction_speed}mm/s)',
'Lower nozzle temperature by 5-10°C (current: {nozzle_temp}°C)',
'Increase travel speed to 150-200mm/s',
'Enable "wipe while retract" in OrcaSlicer',
],
},
warping: {
cause: 'Uneven cooling causing corners to lift',
fixes: [
'Increase bed temperature by 5-10°C (current: {bed_temp}°C)',
'Add brim width 5-8mm',
'Disable fan for first 3-4 layers',
'Slow down initial layer speed to 20mm/s',
'Use enclosure if possible',
'Clean bed with IPA before print',
],
},
elephant_foot: {
cause: 'First layer squished too much by bed proximity',
fixes: [
'Increase Z offset slightly (+0.02-0.05mm)',
'Lower bed temperature for first layer by 5°C',
'Enable elephant foot compensation (0.1-0.2mm) in OrcaSlicer',
],
},
layer_shift: {
cause: 'Stepper motor skipping steps or belt slipping',
fixes: [
'Check belt tension (X and Y axis)',
'Lower acceleration values in printer firmware',
'Reduce print speed by 20%',
'Check for mechanical binding on axes',
'Ensure stepper motor currents are adequate',
],
},
under_extrusion: {
cause: 'Not enough filament being pushed through nozzle',
fixes: [
'Increase nozzle temperature by 5-10°C (current: {nozzle_temp}°C)',
'Increase flow rate by 2-5%',
'Check for partial nozzle clog — do cold pull',
'Calibrate E-steps',
'Check filament diameter with calipers',
'Reduce print speed',
],
},
over_extrusion: {
cause: 'Too much filament being extruded',
fixes: [
'Decrease flow rate by 2-5%',
'Calibrate E-steps',
'Lower nozzle temperature by 5°C',
'Check filament diameter',
],
},
poor_adhesion: {
cause: 'First layer not sticking to bed',
fixes: [
'Level the bed / run auto bed level',
'Increase bed temp by 5-10°C (current: {bed_temp}°C)',
'Lower initial layer speed to 15-20mm/s',
'Increase initial layer height to 0.25-0.3mm',
'Use adhesion aid (glue stick, hairspray)',
'Add brim or raft',
],
},
rough_top: {
cause: 'Top surface not smooth enough',
fixes: [
'Enable ironing in OrcaSlicer (type: top surface)',
'Increase top shell layers to 5-6',
'Reduce top surface speed',
'Increase infill density (>20%) to support top layers',
],
},
weak_parts: {
cause: 'Part breaks or flexes too easily',
fixes: [
'Increase wall loops to 4+',
'Use gyroid infill at 30%+',
'Increase nozzle temp by 5-10°C for better layer bonding',
'Use wider line width (0.45-0.5mm)',
'Consider PETG or ABS instead of PLA for strength',
],
},
poor_overhangs: {
cause: 'Drooping or curling on overhang areas',
fixes: [
'Reduce bridge speed to 20-25mm/s',
'Increase fan speed to 100% for bridges',
'Lower bridge flow to 0.85-0.9',
'Lower nozzle temperature by 5°C',
'Add supports for overhangs >45°',
],
},
};
const diag = diagnoses[defect];
if (!diag) {
return {
content: [{ type: 'text', text: `Unknown defect "${defect}". Known defects: ${Object.keys(diagnoses).join(', ')}` }],
};
}
let text = `Diagnosis: ${defect}\n\nCause: ${diag.cause}\n\nRecommended Fixes:\n`;
for (const fix of diag.fixes) {
let resolved = fix;
if (current_settings) {
for (const [k, v] of Object.entries(current_settings)) {
resolved = resolved.replace(`{${k}}`, v?.toString() || '?');
}
}
resolved = resolved.replace(/\{[^}]+\}/g, '?');
text += ` • ${resolved}\n`;
}
// Check history for what worked
const history = db.prepare(`
SELECT ol.parameter_changes, ol.reasoning, ol.outcome
FROM optimization_log ol
WHERE ol.reasoning LIKE ?
AND ol.outcome = 'improved'
LIMIT 3
`).all(`%${defect}%`);
if (history.length > 0) {
text += `\nWhat worked in your past prints:\n`;
for (const h of history) {
text += ` ✓ ${h.parameter_changes} (${h.reasoning})\n`;
}
}
return { content: [{ type: 'text', text }] };
}
);
// ═══════════════════════════════════════════════════════════════════
// START SERVER
// ═══════════════════════════════════════════════════════════════════
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('3D Print Optimizer MCP server running');
}
main().catch(err => {
console.error('Fatal error:', err);
process.exit(1);
});