-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
546 lines (473 loc) · 25.5 KB
/
server.py
File metadata and controls
546 lines (473 loc) · 25.5 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
"""
QIDI 3D Printer MCP Server
Controls QIDI 4 Max Combo (and other Klipper/Moonraker printers) via Moonraker REST API.
Built by MEOK AI Labs for Sovereign Temple v3.0.
"""
import os
import json
from urllib.request import urlopen, Request
from urllib.error import URLError, HTTPError
from urllib.parse import quote
from mcp.server.fastmcp import FastMCP
PRINTER_IP = os.environ.get("QIDI_PRINTER_IP", "192.168.1.100")
BASE_URL = "http://{}:7125".format(PRINTER_IP)
mcp = FastMCP("qidi-printer", instructions="QIDI 3D Printer MCP Server — controls QIDI 4 Max Combo via Moonraker API")
def _get(path):
"""HTTP GET to Moonraker and return parsed JSON."""
try:
url = BASE_URL + path
req = Request(url, method="GET")
req.add_header("Accept", "application/json")
with urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
except HTTPError as e:
body = ""
try:
body = e.read().decode("utf-8")
except Exception:
pass
raise RuntimeError("Moonraker HTTP {}: {} — {}".format(e.code, e.reason, body))
except URLError as e:
raise RuntimeError("Cannot reach printer at {}: {}".format(BASE_URL, e.reason))
def _post(path, data=None):
"""HTTP POST to Moonraker and return parsed JSON."""
try:
url = BASE_URL + path
if data is not None:
payload = json.dumps(data).encode("utf-8")
req = Request(url, data=payload, method="POST")
req.add_header("Content-Type", "application/json")
else:
req = Request(url, data=b"", method="POST")
req.add_header("Accept", "application/json")
with urlopen(req, timeout=30) as resp:
raw = resp.read().decode("utf-8")
if raw.strip():
return json.loads(raw)
return {"status": "ok"}
except HTTPError as e:
body = ""
try:
body = e.read().decode("utf-8")
except Exception:
pass
raise RuntimeError("Moonraker HTTP {}: {} — {}".format(e.code, e.reason, body))
except URLError as e:
raise RuntimeError("Cannot reach printer at {}: {}".format(BASE_URL, e.reason))
@mcp.tool()
def printer_status() -> dict:
"""Get full printer status: state, temperatures, and print progress. No parameters needed.
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
info = _get("/printer/info")
temps = _get("/printer/objects/query?heater_bed&extruder")
stats = _get("/printer/objects/query?print_stats")
state = info.get("result", {}).get("state", "unknown")
state_msg = info.get("result", {}).get("state_message", "")
temp_data = temps.get("result", {}).get("status", {})
bed = temp_data.get("heater_bed", {})
ext = temp_data.get("extruder", {})
print_data = stats.get("result", {}).get("status", {}).get("print_stats", {})
return {
"state": state,
"state_message": state_msg,
"bed_temp": bed.get("temperature", 0),
"bed_target": bed.get("target", 0),
"nozzle_temp": ext.get("temperature", 0),
"nozzle_target": ext.get("target", 0),
"print_state": print_data.get("state", "standby"),
"filename": print_data.get("filename", ""),
"print_duration_s": print_data.get("print_duration", 0),
"total_duration_s": print_data.get("total_duration", 0),
"printer_ip": PRINTER_IP,
}
@mcp.tool()
def get_temperatures() -> dict:
"""Get current bed and nozzle temperatures with targets.
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
temps = _get("/printer/objects/query?heater_bed&extruder")
temp_data = temps.get("result", {}).get("status", {})
bed = temp_data.get("heater_bed", {})
ext = temp_data.get("extruder", {})
return {
"bed_temp": bed.get("temperature", 0),
"bed_target": bed.get("target", 0),
"nozzle_temp": ext.get("temperature", 0),
"nozzle_target": ext.get("target", 0),
}
@mcp.tool()
def start_print(filename: str) -> dict:
"""Start printing a gcode file already uploaded to the printer.
Args:
filename: Name of the gcode file on the printer (e.g. 'benchy.gcode').
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
result = _post("/printer/print/start?filename={}".format(quote(filename)))
return {"status": "print_started", "filename": filename, "response": result}
@mcp.tool()
def pause_print() -> dict:
"""Pause the current print job.
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
result = _post("/printer/print/pause")
return {"status": "print_paused", "response": result}
@mcp.tool()
def resume_print() -> dict:
"""Resume a paused print job.
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
result = _post("/printer/print/resume")
return {"status": "print_resumed", "response": result}
@mcp.tool()
def cancel_print() -> dict:
"""Cancel the current print job. The printer will stop and cool down.
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
result = _post("/printer/print/cancel")
return {"status": "print_cancelled", "response": result}
@mcp.tool()
def list_files() -> dict:
"""List all gcode files uploaded to the printer.
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
result = _get("/server/files/list")
files = result.get("result", [])
summary = []
for f in files:
entry = {
"filename": f.get("filename", f.get("path", "unknown")),
"size_bytes": f.get("size", 0),
}
modified = f.get("modified", None)
if modified:
entry["modified"] = modified
summary.append(entry)
return {"file_count": len(summary), "files": summary}
@mcp.tool()
def send_gcode(command: str) -> dict:
"""Send a raw G-code command to the printer.
Common commands:
G28 — home all axes
G1 X100 Y100 Z50 F3000 — move to position
M104 S200 — set nozzle temp to 200C
M140 S60 — set bed temp to 60C
M106 S255 — fan on full
M107 — fan off
Args:
command: The G-code command string to send.
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
result = _post("/printer/gcode/script?script={}".format(quote(command)))
return {"status": "gcode_sent", "command": command, "response": result}
@mcp.tool()
def print_progress() -> dict:
"""Get current print progress: percentage complete, elapsed time, estimated time remaining, and filename.
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
stats = _get("/printer/objects/query?print_stats&virtual_sdcard")
status = stats.get("result", {}).get("status", {})
print_stats = status.get("print_stats", {})
vsd = status.get("virtual_sdcard", {})
progress = vsd.get("progress", 0)
duration = print_stats.get("print_duration", 0)
# Estimate remaining time from progress
remaining = 0
if progress > 0.01:
total_est = duration / progress
remaining = max(0, total_est - duration)
return {
"filename": print_stats.get("filename", ""),
"state": print_stats.get("state", "standby"),
"progress_pct": round(progress * 100, 1),
"elapsed_s": round(duration, 0),
"remaining_s": round(remaining, 0),
}
@mcp.tool()
def preheat(bed_temp: int = 60, nozzle_temp: int = 220) -> dict:
"""Preheat the printer bed and nozzle to target temperatures.
Defaults are PLA-friendly: bed 60C, nozzle 220C.
Args:
bed_temp: Target bed temperature in Celsius (default 60).
nozzle_temp: Target nozzle temperature in Celsius (default 220).
Behavior:
This tool is read-only and stateless — it produces analysis output
without modifying any external systems, databases, or files.
Safe to call repeatedly with identical inputs (idempotent).
Free tier: 10/day rate limit. Pro tier: unlimited.
No authentication required for basic usage.
When to use:
Use this tool when you need structured analysis or classification
of inputs against established frameworks or standards.
When NOT to use:
Not suitable for real-time production decision-making without
human review of results.
Behavioral Transparency:
- Side Effects: This tool is read-only and produces no side effects. It does not modify
any external state, databases, or files. All output is computed in-memory and returned
directly to the caller.
- Authentication: No authentication required for basic usage. Pro/Enterprise tiers
require a valid MEOK API key passed via the MEOK_API_KEY environment variable.
- Rate Limits: Free tier: 10 calls/day. Pro tier: unlimited. Rate limit headers are
included in responses (X-RateLimit-Remaining, X-RateLimit-Reset).
- Error Handling: Returns structured error objects with 'error' key on failure.
Never raises unhandled exceptions. Invalid inputs return descriptive validation errors.
- Idempotency: Fully idempotent — calling with the same inputs always produces the
same output. Safe to retry on timeout or transient failure.
- Data Privacy: No input data is stored, logged, or transmitted to external services.
All processing happens locally within the MCP server process.
"""
if bed_temp < 0 or bed_temp > 120:
raise ValueError("Bed temp must be 0-120C, got {}".format(bed_temp))
if nozzle_temp < 0 or nozzle_temp > 300:
raise ValueError("Nozzle temp must be 0-300C, got {}".format(nozzle_temp))
_post("/printer/gcode/script?script={}".format(quote("M140 S{}".format(bed_temp))))
_post("/printer/gcode/script?script={}".format(quote("M104 S{}".format(nozzle_temp))))
return {
"status": "preheating",
"bed_target": bed_temp,
"nozzle_target": nozzle_temp,
}
def main():
"""Entry point for the MCP server."""
mcp.run(transport="stdio")
if __name__ == "__main__":
main()
# ── MEOK monetization layer (Stripe upgrade · PAYG · pricing) ──────────
# Free tier is zero-config. Upgrade to Pro (unlimited) or pay-as-you-go per call.
import os as _meok_os
MEOK_STRIPE_UPGRADE = "https://buy.stripe.com/5kQ6oJ0xS3ce8sl7ew8k91j" # Pro (unlimited)
MEOK_PAYG_KEY = _meok_os.environ.get("MEOK_PAYG_KEY", "") # set to enable PAYG (x402 / ~GBP0.05 per call)
MEOK_PRICING = "https://meok.ai/pricing"
def meok_upsell(tier: str = "free") -> dict:
"""Monetization options for free-tier callers: Pro upgrade, PAYG, or pricing page."""
if tier != "free":
return {}
return {"upgrade_url": MEOK_STRIPE_UPGRADE,
"payg_enabled": bool(MEOK_PAYG_KEY),
"pricing": MEOK_PRICING}