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_mcp/daemon.py ADDED
@@ -0,0 +1,131 @@
1
+ """The background process behind the `cadskill` command.
2
+
3
+ Loading CadQuery takes seconds (a minute or two the first time on a computer),
4
+ far too long to pay on every command. So the first `cadskill` command starts
5
+ this process, which keeps the kernel loaded, and every command after that is a
6
+ short request to it. It also serves the live viewer page. It stops by itself
7
+ after an hour without commands.
8
+
9
+ It runs the same tools as the MCP server (server.py), so the command line and
10
+ MCP behave identically. Requests arrive over HTTP on this computer only.
11
+ Because running a model means running Python, a request must carry a token
12
+ that is written to a file only this user can read: a web page open in the
13
+ browser can reach the port but cannot learn the token.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import json
19
+ import os
20
+ import secrets
21
+ import threading
22
+ import time
23
+ from importlib.metadata import version as _installed
24
+ from pathlib import Path
25
+
26
+ import anyio
27
+ from mcp.types import CallToolResult
28
+
29
+ from . import server
30
+ from .runner import is_starting
31
+ from .store import root
32
+
33
+ IDLE_SECONDS = 3600
34
+ STATE_NAME = ".daemon.json"
35
+ LOCK_NAME = ".daemon.lock"
36
+ VERSION = _installed("cadskill")
37
+
38
+ _token = secrets.token_urlsafe(32)
39
+ _last = time.monotonic()
40
+ _stop = threading.Event()
41
+
42
+
43
+ def _call(tool: str, args: dict) -> dict:
44
+ """Run one tool and reduce its answer to text, pictures and a flag."""
45
+ try:
46
+ # The tool manager checks the arguments against the tool's signature, as an MCP call would.
47
+ result = anyio.run(server.mcp._tool_manager.call_tool, tool, args)
48
+ except Exception as exc: # noqa: BLE001 - whatever went wrong, the caller gets it as a message
49
+ return {"error": True, "text": str(exc), "images": []}
50
+ if not isinstance(result, CallToolResult):
51
+ return {"error": False, "text": str(result), "images": []}
52
+ failed = bool(result.isError)
53
+ text = "\n".join(c.text for c in result.content if c.type == "text")
54
+ return {
55
+ "error": failed,
56
+ "text": text,
57
+ "images": [c.data for c in result.content if c.type == "image"],
58
+ "data": result.structuredContent,
59
+ "starting": failed and is_starting(text), # not a failure: the caller should wait and repeat
60
+ }
61
+
62
+
63
+ class _Handler(server._Page):
64
+ """The viewer page, plus the endpoint the command line talks to."""
65
+
66
+ def do_POST(self) -> None: # noqa: N802 - name set by http.server
67
+ global _last
68
+ given = self.headers.get("authorization", "")
69
+ if self.path != "/call" or not secrets.compare_digest(given.encode(), f"Bearer {_token}".encode()):
70
+ self._send(403, "text/plain", b"Forbidden")
71
+ return
72
+ try:
73
+ body = json.loads(self.rfile.read(int(self.headers.get("content-length") or 0)))
74
+ tool, args = body["tool"], body.get("args") or {}
75
+ except (ValueError, KeyError, TypeError):
76
+ self._send(400, "text/plain", b"Bad request")
77
+ return
78
+ _last = time.monotonic()
79
+ if tool == "ping":
80
+ reply = {"version": VERSION, "ready": server.runner.ready}
81
+ elif tool == "stop":
82
+ reply = {"stopping": True}
83
+ else:
84
+ reply = _call(tool, args)
85
+ _last = time.monotonic()
86
+ self._send(200, "application/json", json.dumps(reply).encode())
87
+ if tool == "stop":
88
+ _stop.set()
89
+
90
+
91
+ def _only_one(base: Path):
92
+ """Hold a lock for as long as this process lives, or return None if another daemon has it."""
93
+ try:
94
+ import fcntl
95
+ except ImportError: # no file locks on this system: two daemons may briefly coexist, which is harmless
96
+ return True
97
+ handle = open(base / LOCK_NAME, "w")
98
+ for _ in range(50): # a daemon that was just told to stop needs a moment to let go
99
+ try:
100
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
101
+ return handle
102
+ except OSError:
103
+ time.sleep(0.2)
104
+ return None
105
+
106
+
107
+ def main() -> None:
108
+ base = root()
109
+ base.mkdir(parents=True, exist_ok=True)
110
+ lock = _only_one(base)
111
+ if lock is None:
112
+ return
113
+ server.runner.warm()
114
+ url = server.start_viewer_page(handler=_Handler)
115
+ state = base / STATE_NAME
116
+ fd = os.open(state, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
117
+ with os.fdopen(fd, "w") as f:
118
+ json.dump({"url": url, "token": _token, "pid": os.getpid(), "version": VERSION}, f)
119
+ try:
120
+ while not _stop.wait(15):
121
+ if time.monotonic() - _last > IDLE_SECONDS:
122
+ break
123
+ finally:
124
+ with contextlib.suppress(OSError, ValueError): # leave the file alone if a newer daemon wrote it
125
+ if json.loads(state.read_text()).get("token") == _token:
126
+ state.unlink()
127
+ server.runner.stop()
128
+
129
+
130
+ if __name__ == "__main__":
131
+ main()
cadskill_mcp/runner.py ADDED
@@ -0,0 +1,149 @@
1
+ """Owns the worker process: starts it, sends it one request at a time, and
2
+ replaces it when a script hangs or takes the kernel down.
3
+
4
+ Starting the worker means importing CadQuery, which is slow the first time on
5
+ a computer (macOS checks each large native library on first load: about a
6
+ minute and a half) and a few seconds after that. So the worker is started in
7
+ the background, as early as possible, and a request that arrives before it is
8
+ ready waits only briefly before answering "still starting" instead of hanging.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import multiprocessing as mp
13
+ import os
14
+ import threading
15
+ import time
16
+
17
+ START_TIMEOUT = 600 # give up on a kernel that has not started after this long
18
+ DEFAULT_TIMEOUT = 60
19
+
20
+
21
+ class Problem(Exception):
22
+ """Something to tell the caller in plain words: a bad request, a timeout, a crash."""
23
+
24
+
25
+ class Starting(Problem):
26
+ """The kernel is not ready yet. Nothing is wrong; the caller should try again shortly."""
27
+
28
+
29
+ STARTING = ("The CAD kernel is still starting", "The CAD kernel is restarting") # how every Starting message begins
30
+
31
+
32
+ def is_starting(message: str) -> bool:
33
+ """Whether a message that reached the caller as text is a Starting one."""
34
+ return message.startswith(STARTING)
35
+
36
+
37
+ def _child(conn) -> None:
38
+ os.dup2(2, 1) # the server speaks MCP on stdout; nothing in the worker may write there
39
+ from . import worker
40
+
41
+ worker.serve(conn)
42
+
43
+
44
+ class Runner:
45
+ def __init__(self, start_wait: float = START_TIMEOUT) -> None:
46
+ """start_wait: how long a request waits for a kernel that is still starting."""
47
+ self.start_wait = start_wait
48
+ self._state = threading.Lock() # guards the fields below
49
+ self._busy = threading.Lock() # one request at a time on the pipe
50
+ self._proc: mp.Process | None = None
51
+ self._conn = None
52
+ self._ready = threading.Event()
53
+ self._booting = False
54
+ self._boot_started = 0.0
55
+ self._boot_error: str | None = None
56
+
57
+ @property
58
+ def ready(self) -> bool:
59
+ """True once the kernel has started and can take a request."""
60
+ return self._ready.is_set()
61
+
62
+ def warm(self) -> None:
63
+ """Start the kernel in the background if it is not running or already starting."""
64
+ with self._state:
65
+ if self._booting or (self._proc is not None and self._proc.is_alive() and self._ready.is_set()):
66
+ return
67
+ self._discard()
68
+ self._booting, self._boot_started, self._boot_error = True, time.monotonic(), None
69
+ ctx = mp.get_context("spawn")
70
+ parent, child = ctx.Pipe()
71
+ proc = ctx.Process(target=_child, args=(child,), daemon=True)
72
+ proc.start()
73
+ child.close()
74
+ self._proc, self._conn = proc, parent
75
+ threading.Thread(target=self._await_ready, args=(proc, parent), daemon=True).start()
76
+
77
+ def _await_ready(self, proc, conn) -> None:
78
+ error = None
79
+ try:
80
+ if conn.poll(START_TIMEOUT):
81
+ conn.recv()
82
+ else:
83
+ error = "The CAD kernel did not start. Check that CadQuery is installed for this server."
84
+ except (EOFError, OSError):
85
+ error = "The CAD kernel exited while starting. Check that CadQuery is installed for this server."
86
+ with self._state:
87
+ if self._proc is not proc: # replaced or stopped while starting
88
+ return
89
+ self._booting = False
90
+ if error:
91
+ self._boot_error = error
92
+ self._discard()
93
+ else:
94
+ self._ready.set()
95
+
96
+ def _discard(self) -> None:
97
+ """Drop the current process. Caller holds _state."""
98
+ self._ready.clear()
99
+ if self._proc is not None:
100
+ if self._proc.is_alive():
101
+ self._proc.terminate()
102
+ self._proc.join(2)
103
+ if self._proc.is_alive():
104
+ self._proc.kill()
105
+ self._proc = None
106
+ if self._conn is not None:
107
+ self._conn.close()
108
+ self._conn = None
109
+
110
+ def stop(self) -> None:
111
+ with self._state:
112
+ self._booting = False
113
+ self._discard()
114
+
115
+ def call(self, op: str, timeout: float = DEFAULT_TIMEOUT, **kwargs):
116
+ """Run one worker operation. Raises Problem with a message meant for the caller."""
117
+ self.warm()
118
+ if not self._ready.wait(self.start_wait):
119
+ with self._state:
120
+ error, self._boot_error = self._boot_error, None
121
+ waited = int(time.monotonic() - self._boot_started)
122
+ if error:
123
+ raise Problem(error)
124
+ raise Starting(
125
+ f"{STARTING[0]} ({waited} s so far). The first start on a computer takes one to "
126
+ "two minutes while the system checks the CAD libraries; later starts take a few seconds. "
127
+ "Nothing is wrong and nothing was changed. Try the same call again in about 20 seconds.")
128
+ with self._busy:
129
+ with self._state:
130
+ conn = self._conn
131
+ if conn is None: # stopped between the wait and here
132
+ raise Starting(f"{STARTING[1]}. Try the same call again in a few seconds.")
133
+ try:
134
+ conn.send((op, kwargs))
135
+ if not conn.poll(timeout):
136
+ self._restart()
137
+ raise Problem(f"Stopped after {timeout:g} seconds without finishing. The kernel was restarted; "
138
+ "the model is unchanged. Look for an endless loop or a very heavy operation.")
139
+ reply = conn.recv()
140
+ except (EOFError, OSError):
141
+ self._restart()
142
+ raise Problem("The CAD kernel crashed on this request and was restarted; the model is unchanged.") from None
143
+ if "problem" in reply:
144
+ raise Problem(reply["problem"])
145
+ return reply["ok"]
146
+
147
+ def _restart(self) -> None:
148
+ self.stop()
149
+ self.warm() # be ready again by the time the caller has read the error