cadskill 0.1.0__py3-none-any.whl
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.
- cadskill-0.1.0.dist-info/METADATA +48 -0
- cadskill-0.1.0.dist-info/RECORD +13 -0
- cadskill-0.1.0.dist-info/WHEEL +4 -0
- cadskill-0.1.0.dist-info/entry_points.txt +3 -0
- cadskill_mcp/__init__.py +0 -0
- cadskill_mcp/cli.py +474 -0
- cadskill_mcp/daemon.py +131 -0
- cadskill_mcp/runner.py +149 -0
- cadskill_mcp/server.py +485 -0
- cadskill_mcp/skill/SKILL.md +168 -0
- cadskill_mcp/static/viewer.html +4506 -0
- cadskill_mcp/store.py +101 -0
- cadskill_mcp/worker.py +643 -0
cadskill_mcp/server.py
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
"""CadSkill MCP server: the tools Claude uses to build and check a CAD model.
|
|
2
|
+
|
|
3
|
+
The model is a CadQuery script. Claude sends or edits the script; the server
|
|
4
|
+
runs it in a worker process, keeps every successful run as a version, and
|
|
5
|
+
answers with numbers and pictures so Claude can check its own work. A viewer
|
|
6
|
+
page shows the same model to the person, inline where the host supports MCP
|
|
7
|
+
Apps and on a local address otherwise.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import json
|
|
13
|
+
import threading
|
|
14
|
+
from functools import partial
|
|
15
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Annotated, Literal
|
|
18
|
+
from urllib.parse import parse_qs, urlparse
|
|
19
|
+
|
|
20
|
+
import anyio
|
|
21
|
+
from mcp.server.fastmcp import FastMCP
|
|
22
|
+
from mcp.types import CallToolResult, ImageContent, TextContent
|
|
23
|
+
from pydantic import BaseModel, Field
|
|
24
|
+
|
|
25
|
+
from .runner import DEFAULT_TIMEOUT, Problem, Runner, Starting
|
|
26
|
+
from .store import Store, clean
|
|
27
|
+
|
|
28
|
+
VIEWER_URI = "ui://cadskill/viewer.html"
|
|
29
|
+
VIEWER_FILE = Path(__file__).parent / "static" / "viewer.html"
|
|
30
|
+
VIEWER_PORT = 8791
|
|
31
|
+
SHOWS_VIEWER = {"ui": {"resourceUri": VIEWER_URI}}
|
|
32
|
+
APP_ONLY = {"ui": {"visibility": ["app"]}}
|
|
33
|
+
MODULE_TAG = '<script type="module">' # where the built viewer's code starts
|
|
34
|
+
|
|
35
|
+
INSTRUCTIONS = """\
|
|
36
|
+
CadSkill builds 3D CAD models from CadQuery (Python) scripts. The script is the model.
|
|
37
|
+
|
|
38
|
+
Loop: run_model with a full script -> read the numbers and look at the four views -> fix with
|
|
39
|
+
edit_model (exact text replacement) -> repeat. Use inspect to list faces or edges before writing a
|
|
40
|
+
selector, render for a closer or sectioned view, measure to check a distance, export for files.
|
|
41
|
+
|
|
42
|
+
Script rules: `cq` is already imported; units are millimetres; call
|
|
43
|
+
show_object(part, name="...", options={"color": "steelblue"}) once per part; put dimensions in
|
|
44
|
+
named constants at the top. A failed run changes nothing: the previous version stays current.
|
|
45
|
+
|
|
46
|
+
If a tool answers that the CAD kernel is still starting, that is normal on first use (one to two
|
|
47
|
+
minutes, once per computer). Tell the user it is warming up, wait about 20 seconds, and repeat the call.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
mcp = FastMCP("cadskill", instructions=INSTRUCTIONS)
|
|
51
|
+
store = Store()
|
|
52
|
+
runner = Runner(start_wait=25) # a call made while the kernel is still starting answers within 25 s
|
|
53
|
+
_shown = {"model": None, "version": 0} # what the viewer should be displaying
|
|
54
|
+
_mesh_cache: dict[tuple[str, int], dict] = {}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ---------------------------------------------------------------- helpers
|
|
58
|
+
|
|
59
|
+
class Selection(BaseModel):
|
|
60
|
+
"""Part of a model: a whole part, or some of its faces, edges or vertices."""
|
|
61
|
+
|
|
62
|
+
part: str | None = Field(None, description="Part name. May be omitted when the model has one part.")
|
|
63
|
+
kind: Literal["faces", "edges", "vertices"] | None = Field(None, description="Omit to mean the whole part.")
|
|
64
|
+
selector: str | None = Field(None, description="CadQuery selector string, e.g. '>Z', '|Z', '%CYLINDER'.")
|
|
65
|
+
index: list[int] | None = Field(None, description="Row numbers from inspect, instead of or as well as a selector.")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
Model = Annotated[str, Field(description="Model name. Each name is a separate model with its own versions.")]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
async def _work(op: str, timeout: float = DEFAULT_TIMEOUT, **kwargs):
|
|
72
|
+
return await anyio.to_thread.run_sync(partial(runner.call, op, timeout, **kwargs))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _text(text: str, error: bool = False, **extra) -> CallToolResult:
|
|
76
|
+
return CallToolResult(content=[TextContent(type="text", text=text)], isError=error, **extra)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _png(data: bytes) -> ImageContent:
|
|
80
|
+
return ImageContent(type="image", data=base64.b64encode(data).decode(), mimeType="image/png")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _fmt(v: float) -> str:
|
|
84
|
+
return f"{v:.3f}".rstrip("0").rstrip(".")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _describe(parts: list[dict]) -> str:
|
|
88
|
+
lines = []
|
|
89
|
+
for p in parts:
|
|
90
|
+
bits = [" × ".join(_fmt(v) for v in p["size"]) + " mm"]
|
|
91
|
+
if "volume" in p:
|
|
92
|
+
bits.append(f"volume {_fmt(p['volume'])} mm³")
|
|
93
|
+
bits.append(f"area {_fmt(p['area'])} mm²")
|
|
94
|
+
bits.append(f"{p['solids']} solid{'s' if p['solids'] != 1 else ''}, {p['faces']} faces, {p['edges']} edges")
|
|
95
|
+
bits.append("x {}..{}, y {}..{}, z {}..{}".format(*(_fmt(v) for pair in zip(p["min"], p["max"]) for v in pair)))
|
|
96
|
+
if not p["valid"]:
|
|
97
|
+
bits.append("NOT A VALID SOLID")
|
|
98
|
+
lines.append(f"- {p['name']}: " + "; ".join(bits))
|
|
99
|
+
return "\n".join(lines)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _require(model: str) -> str:
|
|
103
|
+
code = store.current(model)
|
|
104
|
+
if code is None:
|
|
105
|
+
raise Problem(f"There is no model named '{clean(model)}' yet. Build it first.")
|
|
106
|
+
return code
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def _run(model: str, code: str, note: str | None, timeout: float, what: str) -> CallToolResult:
|
|
110
|
+
"""Run a script and, if it works, make it the current version."""
|
|
111
|
+
model = clean(model)
|
|
112
|
+
was = store.version(model)
|
|
113
|
+
try:
|
|
114
|
+
out = await _work("run", timeout, code=code, model_dir=str(store.dir(model)))
|
|
115
|
+
except Starting as exc:
|
|
116
|
+
return _text(str(exc), error=True)
|
|
117
|
+
except Problem as exc:
|
|
118
|
+
return _text(f"{exc}\nThe model is unchanged" + (f" (still version {was})." if was else "."), error=True)
|
|
119
|
+
printed = f"\nPrinted by the script:\n{out['stdout'].rstrip()}" if out["stdout"].strip() else ""
|
|
120
|
+
if "error" in out:
|
|
121
|
+
e = out["error"]
|
|
122
|
+
where = f"line {e['line']}: {e['source']}\n" if e["line"] else ""
|
|
123
|
+
state = f"The model is unchanged (still version {was})." if was else "Nothing was saved."
|
|
124
|
+
return _text(f"The script failed. {state}\n{where}{e['type']}: {e['message']}{printed}", error=True)
|
|
125
|
+
parts = out["parts"]
|
|
126
|
+
summary = ", ".join(f"{p['name']} {'×'.join(_fmt(v) for v in p['size'])}" for p in parts)
|
|
127
|
+
n = store.save(model, code, summary, note)
|
|
128
|
+
_shown.update(model=model, version=n)
|
|
129
|
+
content = [TextContent(type="text", text=f"{what} Model '{model}' is now version {n}, {len(parts)} part"
|
|
130
|
+
f"{'s' if len(parts) != 1 else ''}:\n{_describe(parts)}{printed}")]
|
|
131
|
+
try:
|
|
132
|
+
shot = await _work("render", code=code, model_dir=str(store.dir(model)), spec={})
|
|
133
|
+
content.append(_png(shot["png"]))
|
|
134
|
+
except Problem as exc:
|
|
135
|
+
content.append(TextContent(type="text", text=f"(No picture: {exc})"))
|
|
136
|
+
return CallToolResult(content=content, structuredContent={"model": model, "version": n})
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# ---------------------------------------------------------------- building
|
|
140
|
+
|
|
141
|
+
@mcp.tool(meta=SHOWS_VIEWER)
|
|
142
|
+
async def run_model(
|
|
143
|
+
code: Annotated[str, Field(description="The complete CadQuery script.")],
|
|
144
|
+
model: Model = "default",
|
|
145
|
+
note: Annotated[str | None, Field(description="A few words on what this version changes.")] = None,
|
|
146
|
+
timeout_seconds: Annotated[int, Field(ge=1, le=600)] = DEFAULT_TIMEOUT,
|
|
147
|
+
) -> CallToolResult:
|
|
148
|
+
"""Build the model from a complete CadQuery script and save it as a new version.
|
|
149
|
+
|
|
150
|
+
Returns each part's size, volume and extents, anything the script printed, and one picture with
|
|
151
|
+
four views (iso, top, front, right). If the script fails you get the failing line and the model
|
|
152
|
+
stays as it was. For a small change to an existing model, edit_model is cheaper.
|
|
153
|
+
"""
|
|
154
|
+
return await _run(model, code, note, timeout_seconds, "Built.")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@mcp.tool(meta=SHOWS_VIEWER)
|
|
158
|
+
async def edit_model(
|
|
159
|
+
old: Annotated[str, Field(description="Exact text in the current script. Must match once unless replace_all is set.")],
|
|
160
|
+
new: Annotated[str, Field(description="Text to put in its place.")],
|
|
161
|
+
model: Model = "default",
|
|
162
|
+
replace_all: bool = False,
|
|
163
|
+
note: Annotated[str | None, Field(description="A few words on what this version changes.")] = None,
|
|
164
|
+
timeout_seconds: Annotated[int, Field(ge=1, le=600)] = DEFAULT_TIMEOUT,
|
|
165
|
+
) -> CallToolResult:
|
|
166
|
+
"""Change the current script by exact text replacement, then rebuild and save a new version.
|
|
167
|
+
|
|
168
|
+
Same result as run_model. If the edited script fails, the edit is discarded.
|
|
169
|
+
"""
|
|
170
|
+
try:
|
|
171
|
+
code = _require(model)
|
|
172
|
+
except Problem as exc:
|
|
173
|
+
return _text(str(exc), error=True)
|
|
174
|
+
count = code.count(old)
|
|
175
|
+
if count == 0:
|
|
176
|
+
return _text("That text is not in the current script. Read it with get_model and copy the text exactly.", error=True)
|
|
177
|
+
if count > 1 and not replace_all:
|
|
178
|
+
return _text(f"That text appears {count} times. Include more surrounding text, or set replace_all.", error=True)
|
|
179
|
+
return await _run(model, code.replace(old, new), note, timeout_seconds, "Edited.")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@mcp.tool()
|
|
183
|
+
async def get_model(model: Model = "default") -> CallToolResult:
|
|
184
|
+
"""Return the model's current script, its version number and its parts."""
|
|
185
|
+
try:
|
|
186
|
+
code = _require(model)
|
|
187
|
+
out = await _work("run", code=code, model_dir=str(store.dir(model)))
|
|
188
|
+
except Problem as exc:
|
|
189
|
+
return _text(str(exc), error=True)
|
|
190
|
+
parts = _describe(out["parts"]) if "parts" in out else f"(the script currently fails: {out['error']['message']})"
|
|
191
|
+
return _text(f"Model '{clean(model)}', version {store.version(model)}:\n{parts}\n\n```python\n{code.rstrip()}\n```")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@mcp.tool()
|
|
195
|
+
def list_models() -> str:
|
|
196
|
+
"""List the models saved on this computer."""
|
|
197
|
+
models = store.models()
|
|
198
|
+
if not models:
|
|
199
|
+
return f"No models yet. They are saved under {store.base}."
|
|
200
|
+
return f"Models in {store.base}:\n" + "\n".join(
|
|
201
|
+
f"- {m['model']}: {m['versions']} version{'s' if m['versions'] != 1 else ''}, last {m['last']['time']} ({m['last']['summary']})"
|
|
202
|
+
for m in models)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
@mcp.tool()
|
|
206
|
+
def list_versions(model: Model = "default") -> str:
|
|
207
|
+
"""List a model's saved versions, oldest first. Every successful run is one version."""
|
|
208
|
+
versions = store.versions(model)
|
|
209
|
+
if not versions:
|
|
210
|
+
return f"There is no model named '{clean(model)}' yet."
|
|
211
|
+
return "\n".join(f"{v['version']}. {v['time']} {v['summary']}" + (f" — {v['note']}" if v.get("note") else "") for v in versions)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@mcp.tool(meta=SHOWS_VIEWER)
|
|
215
|
+
async def restore_version(version: int, model: Model = "default") -> CallToolResult:
|
|
216
|
+
"""Go back to an earlier version. This is undo: the old script is rebuilt and saved as the newest version."""
|
|
217
|
+
try:
|
|
218
|
+
code = store.code(model, version)
|
|
219
|
+
except KeyError:
|
|
220
|
+
return _text(f"Model '{clean(model)}' has no version {version}. See list_versions.", error=True)
|
|
221
|
+
return await _run(model, code, f"restored version {version}", DEFAULT_TIMEOUT, f"Restored version {version}.")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# ---------------------------------------------------------------- checking
|
|
225
|
+
|
|
226
|
+
@mcp.tool()
|
|
227
|
+
async def render(
|
|
228
|
+
model: Model = "default",
|
|
229
|
+
view: Annotated[Literal["four", "iso", "front", "back", "left", "right", "top", "bottom"],
|
|
230
|
+
Field(description="'four' is iso + top + front + right in one picture.")] = "four",
|
|
231
|
+
direction: Annotated[list[float] | None, Field(description="Camera position relative to the model, e.g. [1, 1, 1], "
|
|
232
|
+
"instead of a named view.", min_length=3, max_length=3)] = None,
|
|
233
|
+
parts: Annotated[list[str] | None, Field(description="Only draw these parts.")] = None,
|
|
234
|
+
section_normal: Annotated[list[float] | None, Field(description="Cut the model with a plane and remove the side this "
|
|
235
|
+
"normal points to, to see inside. E.g. [0, -1, 0] removes the front half.",
|
|
236
|
+
min_length=3, max_length=3)] = None,
|
|
237
|
+
section_origin: Annotated[list[float] | None, Field(description="A point on the section plane. Default: the origin.",
|
|
238
|
+
min_length=3, max_length=3)] = None,
|
|
239
|
+
highlight: Annotated[Selection | None, Field(description="Draw these faces or edges in red and the rest faded. "
|
|
240
|
+
"Use it to check what a selector matches.")] = None,
|
|
241
|
+
width: Annotated[int, Field(ge=200, le=2000)] = 1000,
|
|
242
|
+
height: Annotated[int, Field(ge=200, le=2000)] = 760,
|
|
243
|
+
) -> CallToolResult:
|
|
244
|
+
"""Draw the current model. Views have no perspective, so lengths can be compared by eye."""
|
|
245
|
+
spec: dict = {"view": "iso" if direction and view == "four" else view, "direction": direction, "parts": parts,
|
|
246
|
+
"width": width, "height": height}
|
|
247
|
+
if section_normal:
|
|
248
|
+
spec["section"] = {"normal": section_normal, "origin": section_origin or [0, 0, 0]}
|
|
249
|
+
if highlight:
|
|
250
|
+
spec["highlight"] = highlight.model_dump(exclude_none=True)
|
|
251
|
+
try:
|
|
252
|
+
shot = await _work("render", code=_require(model), model_dir=str(store.dir(model)), spec=spec)
|
|
253
|
+
except Problem as exc:
|
|
254
|
+
return _text(str(exc), error=True)
|
|
255
|
+
return CallToolResult(content=[TextContent(type="text", text="Views: " + ", ".join(shot["views"])), _png(shot["png"])])
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@mcp.tool()
|
|
259
|
+
async def inspect(
|
|
260
|
+
model: Model = "default",
|
|
261
|
+
part: Annotated[str | None, Field(description="Part name. May be omitted when the model has one part.")] = None,
|
|
262
|
+
kind: Literal["faces", "edges", "vertices"] = "faces",
|
|
263
|
+
selector: Annotated[str | None, Field(description="CadQuery selector to filter by, e.g. '>Z' or '%CIRCLE'. "
|
|
264
|
+
"Omit to list everything.")] = None,
|
|
265
|
+
) -> CallToolResult:
|
|
266
|
+
"""List a part's faces, edges or vertices with their position, type, size and direction.
|
|
267
|
+
|
|
268
|
+
Use it before writing a selector, and to check what a selector really matches. The index column
|
|
269
|
+
can be passed to render (highlight) and measure.
|
|
270
|
+
"""
|
|
271
|
+
sel = {"part": part, "kind": kind, "selector": selector}
|
|
272
|
+
try:
|
|
273
|
+
out = await _work("inspect", code=_require(model), model_dir=str(store.dir(model)), sel=sel)
|
|
274
|
+
except Problem as exc:
|
|
275
|
+
return _text(str(exc), error=True)
|
|
276
|
+
head = f"{out['part']}: {out['matched']} {out['kind']}" + (f" match '{selector}'" if selector else "")
|
|
277
|
+
if out["shown"] < out["matched"]:
|
|
278
|
+
head += f" (first {out['shown']} listed)"
|
|
279
|
+
rows = "\n".join(json.dumps(r, separators=(", ", ": ")) for r in out["rows"])
|
|
280
|
+
return _text(head + ("\n" + rows if rows else ""))
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@mcp.tool()
|
|
284
|
+
async def measure(a: Selection, b: Selection, model: Model = "default") -> CallToolResult:
|
|
285
|
+
"""Shortest distance between two selections, with the two closest points.
|
|
286
|
+
|
|
287
|
+
Also gives the angle when both are a single flat face or a single straight edge.
|
|
288
|
+
"""
|
|
289
|
+
try:
|
|
290
|
+
out = await _work("measure", code=_require(model), model_dir=str(store.dir(model)),
|
|
291
|
+
a=a.model_dump(exclude_none=True), b=b.model_dump(exclude_none=True))
|
|
292
|
+
except Problem as exc:
|
|
293
|
+
return _text(str(exc), error=True)
|
|
294
|
+
text = f"Distance {_fmt(out['distance'])} mm, between {out['from']} and {out['to']}."
|
|
295
|
+
if "angle_degrees" in out:
|
|
296
|
+
text += f" Angle {_fmt(out['angle_degrees'])}°."
|
|
297
|
+
return _text(text)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# ---------------------------------------------------------------- files
|
|
301
|
+
|
|
302
|
+
@mcp.tool()
|
|
303
|
+
async def export(
|
|
304
|
+
format: Literal["step", "stl", "3mf", "brep", "glb", "svg", "html"],
|
|
305
|
+
model: Model = "default",
|
|
306
|
+
parts: Annotated[list[str] | None, Field(description="Only export these parts. Default: all.")] = None,
|
|
307
|
+
path: Annotated[str | None, Field(description="Where to write the file. Default: the model's exports folder.")] = None,
|
|
308
|
+
) -> CallToolResult:
|
|
309
|
+
"""Write the current model to a file and return its path.
|
|
310
|
+
|
|
311
|
+
STEP and GLB keep part names and colours. STL and 3MF are meshes for printing. SVG is a line drawing.
|
|
312
|
+
HTML is the 3D viewer with this version of the model inside it: one file that opens in any browser
|
|
313
|
+
and needs no server, for sharing or for publishing as a page.
|
|
314
|
+
"""
|
|
315
|
+
try:
|
|
316
|
+
code = _require(model)
|
|
317
|
+
target = str(Path(path).expanduser()) if path else store.export_path(model, f"{clean(model)}-v{store.version(model)}.{format}")
|
|
318
|
+
if format == "html":
|
|
319
|
+
if parts:
|
|
320
|
+
raise Problem("An HTML export always holds the whole model; leave parts out.")
|
|
321
|
+
page = await anyio.to_thread.run_sync(standalone_page, model, store.version(model))
|
|
322
|
+
Path(target).parent.mkdir(parents=True, exist_ok=True)
|
|
323
|
+
Path(target).write_text(page)
|
|
324
|
+
return _text(f"Wrote {target} ({len(page.encode()):,} bytes): the viewer with '{clean(model)}' "
|
|
325
|
+
f"version {store.version(model)} inside.")
|
|
326
|
+
out = await _work("export", 180, code=code, model_dir=str(store.dir(model)), fmt=format, path=target, names=parts)
|
|
327
|
+
except Problem as exc:
|
|
328
|
+
return _text(str(exc), error=True)
|
|
329
|
+
return _text(f"Wrote {out['path']} ({out['bytes']:,} bytes): " + ", ".join(out["parts"]) + ".")
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
@mcp.tool()
|
|
333
|
+
def import_file(
|
|
334
|
+
path: Annotated[str, Field(description="A STEP, BREP or other file on this computer.")],
|
|
335
|
+
model: Model = "default",
|
|
336
|
+
) -> CallToolResult:
|
|
337
|
+
"""Copy a file into the model so its script can load it, e.g. cq.importers.importStep(asset("bracket.step"))."""
|
|
338
|
+
try:
|
|
339
|
+
name = store.add_asset(model, path)
|
|
340
|
+
except FileNotFoundError:
|
|
341
|
+
return _text(f"There is no file at {path}.", error=True)
|
|
342
|
+
return _text(f"Imported as '{name}'. In the script, load it with asset(\"{name}\"), for example:\n"
|
|
343
|
+
f"part = cq.importers.importStep(asset(\"{name}\"))")
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
# ---------------------------------------------------------------- viewer
|
|
347
|
+
|
|
348
|
+
def _mesh_for(model: str, version: int) -> dict:
|
|
349
|
+
"""Meshes for one version, for the viewer. Blocking; cached for the latest few."""
|
|
350
|
+
model = clean(model)
|
|
351
|
+
key = (model, version)
|
|
352
|
+
if key not in _mesh_cache:
|
|
353
|
+
code = store.code(model, version)
|
|
354
|
+
out = runner.call("mesh", code=code, model_dir=str(store.dir(model)))
|
|
355
|
+
if len(_mesh_cache) >= 4:
|
|
356
|
+
_mesh_cache.pop(next(iter(_mesh_cache)))
|
|
357
|
+
_mesh_cache[key] = {"model": model, "version": version, **out}
|
|
358
|
+
return _mesh_cache[key]
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
@mcp.tool(meta=APP_ONLY, structured_output=False)
|
|
362
|
+
async def get_mesh(model: str, version: int) -> CallToolResult:
|
|
363
|
+
"""Triangle meshes of one version of a model. Used by the viewer, not meant for the assistant."""
|
|
364
|
+
try:
|
|
365
|
+
data = await anyio.to_thread.run_sync(_mesh_for, model, version)
|
|
366
|
+
except (Problem, KeyError) as exc:
|
|
367
|
+
return _text(str(exc), error=True)
|
|
368
|
+
return CallToolResult(content=[TextContent(type="text", text=json.dumps(data))])
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _history(model: str) -> dict:
|
|
372
|
+
"""A model's versions for the viewer's history panel, oldest first."""
|
|
373
|
+
model = clean(model)
|
|
374
|
+
return {"model": model, "versions": store.versions(model)}
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
@mcp.tool(meta=APP_ONLY, structured_output=False)
|
|
378
|
+
def get_history(model: str) -> CallToolResult:
|
|
379
|
+
"""The saved versions of a model. Used by the viewer's history panel, not meant for the assistant."""
|
|
380
|
+
return CallToolResult(content=[TextContent(type="text", text=json.dumps(_history(model)))])
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _viewer_html() -> str:
|
|
384
|
+
if VIEWER_FILE.exists():
|
|
385
|
+
return VIEWER_FILE.read_text()
|
|
386
|
+
return "<!doctype html><title>CadSkill</title><p>The viewer has not been built. Run <code>npm run build</code>.</p>"
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def standalone_page(model: str, version: int) -> str:
|
|
390
|
+
"""The viewer page with one version's meshes written into it. Blocking."""
|
|
391
|
+
html = _viewer_html()
|
|
392
|
+
if MODULE_TAG not in html:
|
|
393
|
+
raise Problem("The viewer has not been built. Run `npm run build`.")
|
|
394
|
+
data = json.dumps(_mesh_for(model, version)).replace("</", "<\\/") # must not end the script element early
|
|
395
|
+
return html.replace(MODULE_TAG, f"<script>window.CADSKILL_MODEL = {data};</script>\n{MODULE_TAG}", 1)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
@mcp.resource(VIEWER_URI, name="CadSkill viewer", mime_type="text/html;profile=mcp-app")
|
|
399
|
+
def viewer() -> str:
|
|
400
|
+
"""The 3D viewer shown beside run_model, edit_model and restore_version."""
|
|
401
|
+
return _viewer_html()
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
class _Page(BaseHTTPRequestHandler):
|
|
405
|
+
"""The same viewer as a plain local page, for hosts that do not show MCP Apps."""
|
|
406
|
+
|
|
407
|
+
def log_message(self, *args) -> None: # stdout belongs to the MCP protocol
|
|
408
|
+
pass
|
|
409
|
+
|
|
410
|
+
def _send(self, status: int, kind: str, body: bytes) -> None:
|
|
411
|
+
self.send_response(status)
|
|
412
|
+
self.send_header("content-type", kind)
|
|
413
|
+
self.send_header("content-length", str(len(body)))
|
|
414
|
+
self.send_header("cache-control", "no-store")
|
|
415
|
+
self.end_headers()
|
|
416
|
+
self.wfile.write(body)
|
|
417
|
+
|
|
418
|
+
def do_GET(self) -> None: # noqa: N802 - name set by http.server
|
|
419
|
+
url = urlparse(self.path)
|
|
420
|
+
try:
|
|
421
|
+
if url.path == "/":
|
|
422
|
+
self._send(200, "text/html; charset=utf-8", _viewer_html().encode())
|
|
423
|
+
elif url.path == "/state":
|
|
424
|
+
state = dict(_shown)
|
|
425
|
+
if state["model"] is None: # nothing built in this session yet: show the newest saved model
|
|
426
|
+
models = store.models()
|
|
427
|
+
if models:
|
|
428
|
+
newest = max(models, key=lambda m: m["last"]["time"])
|
|
429
|
+
state = {"model": newest["model"], "version": newest["last"]["version"]}
|
|
430
|
+
self._send(200, "application/json", json.dumps(state).encode())
|
|
431
|
+
elif url.path == "/history":
|
|
432
|
+
self._send(200, "application/json", json.dumps(_history(parse_qs(url.query)["model"][0])).encode())
|
|
433
|
+
elif url.path == "/mesh":
|
|
434
|
+
q = parse_qs(url.query)
|
|
435
|
+
self._send(200, "application/json", json.dumps(_mesh_for(q["model"][0], int(q["version"][0]))).encode())
|
|
436
|
+
else:
|
|
437
|
+
self._send(404, "text/plain", b"Not found")
|
|
438
|
+
except (Problem, KeyError, ValueError) as exc:
|
|
439
|
+
self._send(400, "text/plain; charset=utf-8", str(exc).encode())
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
_http: ThreadingHTTPServer | None = None
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def start_viewer_page(port: int = VIEWER_PORT, handler: type[BaseHTTPRequestHandler] | None = None) -> str:
|
|
446
|
+
"""Serve the viewer on this computer only and return its address."""
|
|
447
|
+
global _http
|
|
448
|
+
if _http is None:
|
|
449
|
+
for candidate in range(port, port + 20):
|
|
450
|
+
try:
|
|
451
|
+
_http = ThreadingHTTPServer(("127.0.0.1", candidate), handler or _Page)
|
|
452
|
+
break
|
|
453
|
+
except OSError:
|
|
454
|
+
continue
|
|
455
|
+
else:
|
|
456
|
+
raise Problem("No free port for the viewer page.")
|
|
457
|
+
threading.Thread(target=_http.serve_forever, daemon=True).start()
|
|
458
|
+
return f"http://127.0.0.1:{_http.server_address[1]}/"
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
@mcp.tool()
|
|
462
|
+
def open_viewer() -> CallToolResult:
|
|
463
|
+
"""Get the address of a live 3D view of the model for the person to open in a browser.
|
|
464
|
+
|
|
465
|
+
Use it when the conversation does not show the model inline. The page follows the model as it changes.
|
|
466
|
+
"""
|
|
467
|
+
try:
|
|
468
|
+
return _text(f"The live viewer is at {start_viewer_page()} (this computer only). It updates after every build.")
|
|
469
|
+
except Problem as exc:
|
|
470
|
+
return _text(str(exc), error=True)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def main() -> None:
|
|
474
|
+
"""Run the MCP server on stdio. With --page, only serve the viewer page (for working on the viewer)."""
|
|
475
|
+
import sys
|
|
476
|
+
|
|
477
|
+
runner.warm() # start loading CadQuery now, so it is ready (or nearly) by the first tool call
|
|
478
|
+
if "--page" in sys.argv:
|
|
479
|
+
print(f"CadSkill viewer at {start_viewer_page()}", file=sys.stderr)
|
|
480
|
+
threading.Event().wait()
|
|
481
|
+
mcp.run()
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
if __name__ == "__main__":
|
|
485
|
+
main()
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: cadskill
|
|
3
|
+
description: Design 3D parts and assemblies by writing CadQuery scripts and running them with the `cadskill` command (run, inspect, render, measure, export, view). Use when the user asks to model, design, draw, modify or export a physical part, enclosure, bracket, fixture or other 3D object, asks for a STEP, STL or 3MF file, wants to see a model in 3D, or wants to change or measure a model made earlier.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Modelling with CadSkill
|
|
7
|
+
|
|
8
|
+
You build models by writing a CadQuery (Python) script to a file and running
|
|
9
|
+
it with `cadskill`. The script is the model: every dimension and every step is
|
|
10
|
+
in it. You do not see the model unless you look, so check your work with the
|
|
11
|
+
numbers `cadskill` prints and the pictures it writes.
|
|
12
|
+
|
|
13
|
+
This skill works in Claude Code and Codex. If `cadskill` is not found, use
|
|
14
|
+
the install instructions for the current agent (macOS or Linux):
|
|
15
|
+
|
|
16
|
+
- Claude Code: `curl -LsSf https://raw.githubusercontent.com/stepandel/cadskill/main/install.sh | sh`
|
|
17
|
+
- Codex: `curl -LsSf https://raw.githubusercontent.com/stepandel/cadskill/main/install.sh | sh -s -- --agent codex`
|
|
18
|
+
|
|
19
|
+
Tell the user which command to run and to open a new terminal afterward,
|
|
20
|
+
then stop.
|
|
21
|
+
|
|
22
|
+
## The loop
|
|
23
|
+
|
|
24
|
+
1. **Write the whole script** to a file in the user's project, e.g.
|
|
25
|
+
`bracket.py`. The file name is the model's name.
|
|
26
|
+
2. **Build it**: `cadskill run bracket.py`. It prints each part's size, volume
|
|
27
|
+
and extents, and writes one picture with four views (iso, top, front,
|
|
28
|
+
right) to `.cadskill/bracket.png`.
|
|
29
|
+
3. **Open the picture** with an image-viewing tool (such as Codex's
|
|
30
|
+
`view_image`) and compare it with what
|
|
31
|
+
was asked for, view by view. Wrong proportions, a missing hole or a feature
|
|
32
|
+
on the wrong face are easy to see and easy to miss in the numbers.
|
|
33
|
+
4. **Change the script** with your normal file editing, then run it again.
|
|
34
|
+
5. **Check before you say it is done**: sizes match the request, each part is
|
|
35
|
+
one valid solid, and you have looked at the views after the last change.
|
|
36
|
+
|
|
37
|
+
Every successful run is saved as a numbered version. A failed run changes
|
|
38
|
+
nothing: it names the failing line, and `inspect`, `render`, `measure` and
|
|
39
|
+
`export` keep answering about the last version that built.
|
|
40
|
+
|
|
41
|
+
**First use on a computer is slow.** The first command starts the CAD kernel,
|
|
42
|
+
which takes one to two minutes once per computer and a few seconds after
|
|
43
|
+
that. `cadskill` waits for it. If it still answers that the kernel is
|
|
44
|
+
starting, nothing is wrong: tell the user it is warming up and run the same
|
|
45
|
+
command again. Do not rewrite the script or give up.
|
|
46
|
+
|
|
47
|
+
## Showing the user
|
|
48
|
+
|
|
49
|
+
Give the user a 3D view as well as any rendered pictures you share:
|
|
50
|
+
|
|
51
|
+
- **Live viewer**: `cadskill view` opens a page in their browser that follows
|
|
52
|
+
the model as you rebuild it. Do this once, after the first successful build.
|
|
53
|
+
If you have your own browser or preview pane, you can open the address it
|
|
54
|
+
prints there instead.
|
|
55
|
+
- **As a page or artifact**: `cadskill export bracket html` writes
|
|
56
|
+
`.cadskill/bracket.html`, the same viewer with the model inside it: one
|
|
57
|
+
file, no server. If you can publish artifacts, publish that file when the
|
|
58
|
+
user wants to keep or share the model, or cannot open a local page. Export
|
|
59
|
+
again and republish after the model changes.
|
|
60
|
+
|
|
61
|
+
## Script rules
|
|
62
|
+
|
|
63
|
+
- `cq` (CadQuery), `math`, `show_object` and `asset` are already available.
|
|
64
|
+
Do not import cadquery or call exporters yourself.
|
|
65
|
+
- Units are millimetres. Z is up.
|
|
66
|
+
- Put every dimension in a named constant at the top, and derive the rest
|
|
67
|
+
from them. A later "make it 10 mm longer" is then a one-line edit.
|
|
68
|
+
- Call `show_object(part, name="lid", options={"color": "steelblue"})` once
|
|
69
|
+
per part. Names are how the commands refer to parts, so make them
|
|
70
|
+
meaningful and keep them stable between versions.
|
|
71
|
+
- One solid per physical part. Parts that are separate pieces in reality stay
|
|
72
|
+
separate objects; do not union them.
|
|
73
|
+
- Assemblies: build a `cq.Assembly`, add parts with `name=`, `loc=` and
|
|
74
|
+
`color=`, and show the assembly. Each child becomes a named part.
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
LENGTH, WIDTH, THICKNESS = 60, 40, 5
|
|
78
|
+
HOLE_D, HOLE_INSET = 4.5, 6
|
|
79
|
+
CORNER_R = 4
|
|
80
|
+
|
|
81
|
+
plate = (
|
|
82
|
+
cq.Workplane("XY")
|
|
83
|
+
.box(LENGTH, WIDTH, THICKNESS)
|
|
84
|
+
.edges("|Z").fillet(CORNER_R)
|
|
85
|
+
.faces(">Z").workplane()
|
|
86
|
+
.rect(LENGTH - 2 * HOLE_INSET, WIDTH - 2 * HOLE_INSET, forConstruction=True)
|
|
87
|
+
.vertices().hole(HOLE_D)
|
|
88
|
+
)
|
|
89
|
+
show_object(plate, name="plate")
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Commands
|
|
93
|
+
|
|
94
|
+
`MODEL` is the model's name or its script: `bracket` and `bracket.py` mean
|
|
95
|
+
the same. Quote anything with `>`, `<`, `|`, `%` or `#` in it. `cadskill
|
|
96
|
+
COMMAND --help` lists every option.
|
|
97
|
+
|
|
98
|
+
| Command | What it does |
|
|
99
|
+
|---|---|
|
|
100
|
+
| `cadskill run SCRIPT [--note "why"] [--timeout 120]` | Build and save a version; write the four-view picture |
|
|
101
|
+
| `cadskill render MODEL [--view top] [--direction 1,1,1]` | Another picture, to `.cadskill/MODEL-render.png` |
|
|
102
|
+
| `cadskill render MODEL --section 0,-1,0` | Cut the model open (removes the side the normal points to) |
|
|
103
|
+
| `cadskill render MODEL --highlight 'plate/faces:>Z'` | Draw what a selector matches in red |
|
|
104
|
+
| `cadskill inspect MODEL [faces\|edges\|vertices] [--part P] [--selector '%CYLINDER']` | List geometry with position, type, size, normal |
|
|
105
|
+
| `cadskill measure MODEL A B` | Shortest distance between two selections, and the angle if both are flat or straight |
|
|
106
|
+
| `cadskill export MODEL step\|stl\|3mf\|glb\|brep\|svg\|html [--out FILE]` | Write a file and print its path |
|
|
107
|
+
| `cadskill import MODEL FILE` | Copy a STEP or BREP file in, for the script to load with `asset("name.step")` |
|
|
108
|
+
| `cadskill show MODEL`, `versions MODEL`, `models` | The saved script, its history, all models |
|
|
109
|
+
| `cadskill restore MODEL N --to SCRIPT` | Go back to version N and write that script back to the file |
|
|
110
|
+
| `cadskill view` | Open the live 3D viewer |
|
|
111
|
+
|
|
112
|
+
A **selection** (for `--highlight` and `measure`) is `PART`, `KIND` or
|
|
113
|
+
`PART/KIND`, optionally followed by `:SELECTOR` or `@ROWS` (row numbers from
|
|
114
|
+
`inspect`): `post` is a whole part, `plate/faces:>Z` its top face,
|
|
115
|
+
`edges@3,4` two edges of the only part.
|
|
116
|
+
|
|
117
|
+
## Selecting faces and edges
|
|
118
|
+
|
|
119
|
+
Most mistakes are a selector that matches something other than what you
|
|
120
|
+
meant. Do not guess:
|
|
121
|
+
|
|
122
|
+
- `cadskill inspect MODEL faces` lists a part's faces with position, type,
|
|
123
|
+
normal and size. Add `--selector` to see exactly what it matches.
|
|
124
|
+
- `cadskill render MODEL --highlight ...` draws the match in red.
|
|
125
|
+
|
|
126
|
+
Common selectors: `>Z` / `<Z` furthest along an axis; `|Z` parallel to an
|
|
127
|
+
axis; `#Z` perpendicular to it; `%CYLINDER`, `%PLANE`, `%CIRCLE` by type;
|
|
128
|
+
combine with `and`, `or`, `not`, e.g. `|Z and >X`. After a boolean or a
|
|
129
|
+
fillet, faces and edges are renumbered, so inspect again instead of reusing
|
|
130
|
+
row numbers from an earlier version.
|
|
131
|
+
|
|
132
|
+
## Looking closer
|
|
133
|
+
|
|
134
|
+
- `render --view` for a named view, `--direction` for an odd angle.
|
|
135
|
+
- `render --section` for anything with internal features: bores, pockets,
|
|
136
|
+
wall thickness, clearances.
|
|
137
|
+
- `measure` for the gap between two parts, the distance between two faces, or
|
|
138
|
+
the angle between them. Use it to confirm fits and clearances instead of
|
|
139
|
+
reasoning from the script.
|
|
140
|
+
|
|
141
|
+
## When a step fails
|
|
142
|
+
|
|
143
|
+
- **Fillet or chamfer fails**: the radius is too large for the smallest
|
|
144
|
+
adjacent face or edge. Reduce it, apply it before the feature that created
|
|
145
|
+
the small edge, or select fewer edges.
|
|
146
|
+
- **Selector matches nothing**: the geometry is not where you assumed.
|
|
147
|
+
Inspect the part and pick from what is there.
|
|
148
|
+
- **Shell fails**: thickness is larger than a local radius or feature;
|
|
149
|
+
reduce it or shell before adding small features.
|
|
150
|
+
- **Boolean gives an invalid or empty result**: the bodies only touch on a
|
|
151
|
+
face or edge. Overlap them by a small amount.
|
|
152
|
+
- **"Stopped after N seconds"**: an endless loop or a very heavy operation
|
|
153
|
+
(large patterns of booleans). Simplify, or raise `--timeout`.
|
|
154
|
+
- If the script went wrong in a way that is hard to repair, `cadskill
|
|
155
|
+
versions MODEL` and `cadskill restore MODEL N --to SCRIPT` go back to one
|
|
156
|
+
that was right.
|
|
157
|
+
|
|
158
|
+
## Working with the user
|
|
159
|
+
|
|
160
|
+
- State the key dimensions you used, and name any you had to assume.
|
|
161
|
+
- When you export, tell the user where the file is.
|
|
162
|
+
- Use a separate script (and so a separate model name) for each unrelated
|
|
163
|
+
design, so their version histories do not mix.
|
|
164
|
+
- `.cadskill/` holds pictures and exported pages for this project and is kept
|
|
165
|
+
out of git. Saved versions live in the user's `Documents/CadSkill` folder.
|
|
166
|
+
- The script runs as ordinary Python on the user's computer. Only use it for
|
|
167
|
+
modelling; do not read or write files outside the model, and do not use
|
|
168
|
+
the network.
|