mcp-3d-printer-server 1.2.2 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,328 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
- import express, { Request, Response } from 'express';
5
- import cors from 'cors';
6
- import {
7
- ListResourcesRequestSchema,
8
- ReadResourceRequestSchema,
9
- ListToolsRequestSchema,
10
- CallToolRequestSchema,
11
- ErrorCode,
12
- McpError,
13
- JSONRPCRequest,
14
- JSONRPCResponse,
15
- JSONRPCError
16
- } from "@modelcontextprotocol/sdk/types.js";
17
- import axios from "axios";
18
- import dotenv from "dotenv";
19
- import fs from "fs";
20
- import path from "path";
21
- import * as THREE from 'three';
22
- import { PrinterFactory } from "./printers/printer-factory.js";
23
- import { STLManipulator } from "./stl/stl-manipulator.js";
24
- import { parse3MF, ThreeMFData } from './3mf_parser.js';
25
- import { BambuImplementation } from "./printers/bambu.js";
26
-
27
- // Load environment variables from .env file
28
- dotenv.config();
29
-
30
- // Default values
31
- const DEFAULT_HOST = process.env.PRINTER_HOST || "localhost";
32
- const DEFAULT_PORT = process.env.PRINTER_PORT || "80";
33
- const DEFAULT_API_KEY = process.env.API_KEY || "";
34
- const DEFAULT_TYPE = process.env.PRINTER_TYPE || "octoprint";
35
- const TEMP_DIR = process.env.TEMP_DIR || path.join(process.cwd(), "temp");
36
-
37
- // HTTP Server configuration
38
- const HTTP_PORT = parseInt(process.env.HTTP_PORT || "3001");
39
-
40
- // Slicer configuration
41
- const DEFAULT_SLICER_TYPE = process.env.SLICER_TYPE || "prusaslicer";
42
- const DEFAULT_SLICER_PATH = process.env.SLICER_PATH || "";
43
- const DEFAULT_SLICER_PROFILE = process.env.SLICER_PROFILE || "";
44
-
45
- // Bambu-specific default values
46
- const DEFAULT_BAMBU_SERIAL = process.env.BAMBU_SERIAL || "";
47
- const DEFAULT_BAMBU_TOKEN = process.env.BAMBU_TOKEN || "";
48
-
49
- // Ensure temp directory exists
50
- if (!fs.existsSync(TEMP_DIR)) {
51
- fs.mkdirSync(TEMP_DIR, { recursive: true });
52
- }
53
-
54
- class ThreeDPrinterMCPServerHTTP {
55
- private server: Server;
56
- private printerFactory: PrinterFactory;
57
- private stlManipulator: STLManipulator;
58
- private app: express.Application;
59
-
60
- constructor() {
61
- this.server = new Server(
62
- {
63
- name: "mcp-3d-printer-server",
64
- version: "1.0.0"
65
- },
66
- {
67
- capabilities: {
68
- resources: {},
69
- tools: {},
70
- prompts: {}
71
- }
72
- }
73
- );
74
-
75
- this.printerFactory = new PrinterFactory();
76
- this.stlManipulator = new STLManipulator(TEMP_DIR);
77
-
78
- this.app = express();
79
- this.setupExpressApp();
80
- this.setupHandlers();
81
- this.setupErrorHandling();
82
- }
83
-
84
- private setupExpressApp() {
85
- // Enable CORS for all origins
86
- this.app.use(cors({
87
- origin: '*',
88
- methods: ['GET', 'POST', 'OPTIONS'],
89
- allowedHeaders: ['Content-Type', 'Accept'],
90
- credentials: true
91
- }));
92
-
93
- // Parse JSON bodies
94
- this.app.use(express.json({ limit: '50mb' }));
95
-
96
- // Main MCP endpoint - supports both standard and streaming responses
97
- this.app.post('/mcp', async (req: Request, res: Response) => {
98
- const acceptHeader = req.get('Accept') || '';
99
- const wantsStream = acceptHeader.includes('text/event-stream');
100
-
101
- try {
102
- const requests = Array.isArray(req.body) ? req.body : [req.body];
103
- const responses: JSONRPCResponse[] = [];
104
-
105
- for (const request of requests) {
106
- const response = await this.handleJSONRPCRequest(request);
107
- if (response) {
108
- responses.push(response);
109
- }
110
- }
111
-
112
- // If client wants streaming and we have responses, use SSE format
113
- if (wantsStream && responses.length > 0) {
114
- res.setHeader('Content-Type', 'text/event-stream');
115
- res.setHeader('Cache-Control', 'no-cache');
116
- res.setHeader('Connection', 'keep-alive');
117
-
118
- for (const response of responses) {
119
- res.write(`data: ${JSON.stringify(response)}\n\n`);
120
- }
121
-
122
- res.end();
123
- } else if (responses.length > 0) {
124
- // Standard JSON response
125
- res.json(responses.length === 1 ? responses[0] : responses);
126
- } else {
127
- // No responses (notifications)
128
- res.status(202).send();
129
- }
130
- } catch (error) {
131
- console.error('Error handling request:', error);
132
- res.status(500).json({
133
- jsonrpc: "2.0",
134
- error: {
135
- code: -32603,
136
- message: "Internal error",
137
- data: error instanceof Error ? error.message : String(error)
138
- }
139
- });
140
- }
141
- });
142
-
143
- // GET endpoint for establishing SSE stream (Streamable HTTP)
144
- this.app.get('/mcp', async (req: Request, res: Response) => {
145
- const acceptHeader = req.get('Accept') || '';
146
-
147
- if (!acceptHeader.includes('text/event-stream')) {
148
- res.status(405).json({
149
- error: 'Method not allowed. Use POST for non-streaming requests.'
150
- });
151
- return;
152
- }
153
-
154
- // Set SSE headers
155
- res.setHeader('Content-Type', 'text/event-stream');
156
- res.setHeader('Cache-Control', 'no-cache');
157
- res.setHeader('Connection', 'keep-alive');
158
- res.setHeader('X-Accel-Buffering', 'no');
159
-
160
- // Send initial connection event
161
- res.write(`event: open\ndata: {"type": "connection", "status": "connected"}\n\n`);
162
-
163
- // Keep connection alive with periodic pings
164
- const pingInterval = setInterval(() => {
165
- if (!res.writableEnded) {
166
- res.write(`event: ping\ndata: ${new Date().toISOString()}\n\n`);
167
- }
168
- }, 30000);
169
-
170
- // Handle client disconnect
171
- req.on('close', () => {
172
- clearInterval(pingInterval);
173
- res.end();
174
- });
175
- });
176
-
177
- // Health check endpoint
178
- this.app.get('/health', (req: Request, res: Response) => {
179
- res.json({
180
- status: 'ok',
181
- server: 'mcp-3d-printer-server',
182
- transport: 'streamable-http',
183
- version: '1.0.0'
184
- });
185
- });
186
-
187
- // Root endpoint
188
- this.app.get('/', (req: Request, res: Response) => {
189
- res.json({
190
- name: 'MCP 3D Printer Server (HTTP)',
191
- version: '1.0.0',
192
- endpoints: {
193
- mcp: '/mcp',
194
- health: '/health'
195
- },
196
- transport: 'streamable-http',
197
- features: ['stdio', 'sse', 'http'],
198
- documentation: 'https://github.com/DMontgomery40/mcp-3D-printer-server'
199
- });
200
- });
201
- }
202
-
203
- private async handleJSONRPCRequest(request: JSONRPCRequest): Promise<JSONRPCResponse | null> {
204
- try {
205
- // Route based on method
206
- switch (request.method) {
207
- case 'initialize':
208
- return {
209
- jsonrpc: "2.0",
210
- id: request.id,
211
- result: {
212
- protocolVersion: "2025-03-26",
213
- capabilities: this.server.capabilities,
214
- serverInfo: {
215
- name: "mcp-3d-printer-server",
216
- version: "1.0.0"
217
- }
218
- }
219
- };
220
-
221
- case 'resources/list':
222
- const resourcesResult = await this.server.handleRequest(request);
223
- return {
224
- jsonrpc: "2.0",
225
- id: request.id,
226
- result: resourcesResult
227
- };
228
-
229
- case 'resources/read':
230
- const readResult = await this.server.handleRequest(request);
231
- return {
232
- jsonrpc: "2.0",
233
- id: request.id,
234
- result: readResult
235
- };
236
-
237
- case 'tools/list':
238
- const toolsResult = await this.server.handleRequest(request);
239
- return {
240
- jsonrpc: "2.0",
241
- id: request.id,
242
- result: toolsResult
243
- };
244
-
245
- case 'tools/call':
246
- const callResult = await this.server.handleRequest(request);
247
- return {
248
- jsonrpc: "2.0",
249
- id: request.id,
250
- result: callResult
251
- };
252
-
253
- default:
254
- if (request.id) {
255
- return {
256
- jsonrpc: "2.0",
257
- id: request.id,
258
- error: {
259
- code: -32601,
260
- message: `Method not found: ${request.method}`
261
- }
262
- };
263
- }
264
- return null; // Notification
265
- }
266
- } catch (error) {
267
- if (request.id) {
268
- return {
269
- jsonrpc: "2.0",
270
- id: request.id,
271
- error: {
272
- code: -32603,
273
- message: "Internal error",
274
- data: error instanceof Error ? error.message : String(error)
275
- }
276
- };
277
- }
278
- return null;
279
- }
280
- }
281
-
282
- setupErrorHandling() {
283
- this.server.onerror = (error) => {
284
- console.error("[MCP Error]", error);
285
- };
286
-
287
- process.on("SIGINT", async () => {
288
- console.log("\nShutting down HTTP server...");
289
- await this.printerFactory.disconnectAll();
290
- await this.server.close();
291
- process.exit(0);
292
- });
293
- }
294
-
295
- setupHandlers() {
296
- this.setupResourceHandlers();
297
- this.setupToolHandlers();
298
- }
299
-
300
- // Copy all handlers from original index.ts
301
- setupResourceHandlers() {
302
- // ... (copy from original)
303
- }
304
-
305
- setupToolHandlers() {
306
- // ... (copy from original)
307
- }
308
-
309
- // Copy all delegating methods from original index.ts
310
- // ... (copy all printer methods)
311
-
312
- async run() {
313
- // Start Express server
314
- this.app.listen(HTTP_PORT, () => {
315
- console.log(`🚀 MCP 3D Printer Server (HTTP) running on http://localhost:${HTTP_PORT}`);
316
- console.log(`📡 MCP endpoint: http://localhost:${HTTP_PORT}/mcp`);
317
- console.log(`✨ Supports both standard HTTP and Server-Sent Events`);
318
- });
319
- }
320
- }
321
-
322
- // Check if running as main module
323
- if (import.meta.url === `file://${process.argv[1]}`) {
324
- const server = new ThreeDPrinterMCPServerHTTP();
325
- server.run().catch(console.error);
326
- }
327
-
328
- export default ThreeDPrinterMCPServerHTTP;