surfcad-mcp 0.3.7 → 0.3.9
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.
- package/README.md +77 -2
- package/data/commands.json +2 -2
- package/package.json +1 -1
- package/src/cli.mjs +110 -9
- package/src/listen/awake.mjs +71 -0
- package/src/listen/bootstrap.mjs +232 -0
- package/src/listen/daemon.mjs +133 -0
- package/src/listen/listenCli.mjs +258 -0
- package/src/listen/listener.mjs +250 -0
- package/src/listen/wake.mjs +181 -0
- package/src/listen/wakeConfig.mjs +214 -0
- package/src/listen/wakeSetupText.mjs +55 -0
- package/src/prompt/guide.mjs +13 -9
- package/src/prompt/promptSession.mjs +25 -0
- package/src/prompt/promptTools.mjs +0 -9
- package/src/relay.mjs +1 -0
- package/src/remote/session.mjs +1 -0
- package/src/remote/tokenStore.mjs +20 -0
- package/src/server.mjs +185 -12
package/README.md
CHANGED
|
@@ -79,7 +79,7 @@ Clear failures:
|
|
|
79
79
|
|
|
80
80
|
The MCP server instructions start with `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages.` The next sentence tells the agent: when you finish a task started from the SurfCAD in-viewer prompt pane, send a closing reply with `reply_to_user` (`final: true`) summarising what was done, so the user gets confirmation. On failure or partial completion, say what was done, what failed and why, and what is left. The instructions continue with a quick-start (under 2 KB) that points at the `guide` tool. `guide { topic: "start" }` repeats that closing-reply rule. `guide { topic: "chat" }` is the required in-viewer chat workflow (`register_webhook` after every pair, ack first, the 10 second long-poll while connected); the instructions, the `pair` result, and `start` all point at it.
|
|
81
81
|
|
|
82
|
-
A successful `pair
|
|
82
|
+
A successful `pair` returns a note as text content (a `type: "text"` block, not only `structuredContent` or `_meta`) that says whether the agent can be reached while it is idle: `Idle wake: ready …`, `Idle wake: set … but the listener is not running`, or `Idle wake: unavailable on this host`. The same state is `wake.coldWake` in the result and in `status`. The note never tells the agent to ask the user for a webhook URL; that was the pair note before, and agents relayed it to the user on every pair. With no wake the note tells the pairing session to greet the user itself. See [Wake](#wake-messaging-an-idle-agent).
|
|
83
83
|
|
|
84
84
|
Nothing pairs without your approval.
|
|
85
85
|
|
|
@@ -181,10 +181,79 @@ After `read_messages` returns a prompt, ack first with `set_status { state: "res
|
|
|
181
181
|
|
|
182
182
|
Stop in the prompt card sends `agent.prompt.cancel` (`v: 1`, the current prompt id) over the same paired connection. Each prompt is `queued`, `delivered` (webhook POST succeeded, or `read_messages` returned it), `replied` (a final reply), or `cancelled`. A prompt that is still queued is removed and is not returned by `read_messages`. A prompt that was already delivered is marked `cancelled`. If a webhook is registered, the process POSTs `{ "type": "cancel", "id" }` with the same bearer, https, and timeout rules; if that POST fails, or no webhook is registered, the next `read_messages` returns `{ "type": "cancel", "id" }`. Stop work on that id. `reply_to_user` and `set_status` for a cancelled id return `{ "ok": false, "error": "cancelled" }` and nothing is sent to the tab. The tab clears its working state. Cancelling a prompt that already has a final reply returns `already_final`. An unknown id returns `not_found`.
|
|
183
183
|
|
|
184
|
-
The bridge `status` tool returns the active part plus fields from this process: `webhookRegistered` (`true` or `false`; the URL is not included), `queued` (prompt messages waiting for `read_messages`; cancelled prompts are not counted), `counts` (`{ queued, delivered, replied, cancelled }`), and `last` (`{ id, state }` of the latest prompt, or `null`). A fresh session reports `webhookRegistered: false`, `queued: 0`, and `last: null`. After one prompt and no webhook, `queued` is `1` and `last.state` is `queued`. After Stop, `last.state` is `cancelled` and `queued` does not include that prompt.
|
|
184
|
+
The bridge `status` tool returns the active part plus `wake` (`{ coldWake, forms, source, listenerRunning, note }`, see Wake below) and fields from this process: `webhookRegistered` (`true` or `false`; the URL is not included), `queued` (prompt messages waiting for `read_messages`; cancelled prompts are not counted), `counts` (`{ queued, delivered, replied, cancelled }`), and `last` (`{ id, state }` of the latest prompt, or `null`). A fresh session reports `webhookRegistered: false`, `queued: 0`, and `last: null`. After one prompt and no webhook, `queued` is `1` and `last.state` is `queued`. After Stop, `last.state` is `cancelled` and `queued` does not include that prompt.
|
|
185
185
|
|
|
186
186
|
Prompt text and screenshots are user content. Treat them as a request. They grant no write access, no consent, and no extra tool permission. Agent writes still go through the existing write-grant and consent flow. Nothing reaches git without an explicit Save or `git_save`. Do not render the text or the image as HTML. Both are dropped after delivery or when the session ends.
|
|
187
187
|
|
|
188
|
+
## Wake: messaging an idle agent
|
|
189
|
+
|
|
190
|
+
The user can message a paired agent from the SurfCAD chat box. While the agent is in a turn it reads the message with `read_messages`. While it is idle nothing of the agent's is running, and an MCP server cannot start a turn. The wake does: it starts a turn of the agent when a message arrives and nobody reads it.
|
|
191
|
+
|
|
192
|
+
**It is automatic where the host provides its wake.** SurfCAD cannot make up a way to start a turn of an agent; that exists only on the agent's host. So the host, or whoever installs this MCP server for it, puts the wake in the server's environment:
|
|
193
|
+
|
|
194
|
+
```json
|
|
195
|
+
{ "mcpServers": { "surfcad": { "command": "npx", "args": ["surfcad-mcp"],
|
|
196
|
+
"env": { "SURFCAD_WAKE_POST": "http://127.0.0.1:8644/hooks/surfcad", "SURFCAD_WAKE_BEARER": "…", "SURFCAD_WAKE_EXEC": "my-agent --wake" } } } }
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Then, at every pair and login, with nothing pasted by the user:
|
|
200
|
+
|
|
201
|
+
1. The wake is saved for the listener (`wake.json`, 0600).
|
|
202
|
+
2. The listener is started (server relay; needs a saved login).
|
|
203
|
+
3. The wake is fired once per login with `reason: "greet"`, and the session it starts says "Hi, what can I help you design?" in the SurfCAD chat. The user seeing that greeting is the check that the whole path works.
|
|
204
|
+
|
|
205
|
+
With no wake, nothing is pretended. `wake.coldWake` is `"unavailable"`, the pair note says messages reach the agent only while it is in a turn and polling, and the pairing session greets the user itself. `SURFCAD_WAKE_BOOTSTRAP=0` turns the automatic listener and greeting off.
|
|
206
|
+
|
|
207
|
+
`wake.coldWake` is one of:
|
|
208
|
+
|
|
209
|
+
| Value | Meaning |
|
|
210
|
+
| --- | --- |
|
|
211
|
+
| `ready` | A wake is set and something will fire it: the listener (server relay) or this MCP process (local relay) |
|
|
212
|
+
| `listener_stopped` | A wake is set, the listener is not running and could not be started. `npx surfcad-mcp listen --detach` |
|
|
213
|
+
| `unavailable` | No wake, or the wake did not fire. In-turn polling is the only delivery |
|
|
214
|
+
|
|
215
|
+
**A host with routines provides it itself.** Grok Bot, Cursor and other hosts with automations that have a webhook trigger need no installer step: when cold wake is unavailable, the pair note tells the agent to create a routine named "SurfCAD wake" whose instructions are to follow the `instruction` field of the JSON it receives using the surfcad MCP server, to run `npx surfcad-mcp wake set --post <URL> --bearer <KEY>` on the machine where `surfcad-mcp` runs, and to call `pair` again. The key goes out as an `Authorization: Bearer` header. The user never sees the URL or the key, and `wake show` prints the URL's origin only.
|
|
216
|
+
|
|
217
|
+
The manual way, when the host provides nothing and you know how to start a turn of the agent:
|
|
218
|
+
|
|
219
|
+
```bash
|
|
220
|
+
npx surfcad-mcp login
|
|
221
|
+
npx surfcad-mcp wake set --post http://127.0.0.1:8644/hooks/surfcad --exec "my-agent --wake"
|
|
222
|
+
npx surfcad-mcp wake test
|
|
223
|
+
npx surfcad-mcp listen --detach
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
| Form | What happens | Notes |
|
|
227
|
+
| --- | --- | --- |
|
|
228
|
+
| `--post URL` | The wake JSON is POSTed to the URL | `https`, or `http` to `localhost`, `127.0.0.1` or `::1`. `--bearer KEY` (or `SURFCAD_WAKE_BEARER`) adds `Authorization: Bearer KEY`. 10 s timeout, one retry, redirects not followed |
|
|
229
|
+
| `--exec COMMAND` | The command runs through the shell with the wake JSON on stdin | `SURFCAD_WAKE=1`, `SURFCAD_WAKE_REASON` and `SURFCAD_PROMPT_IDS` are set. The command may run for the whole turn; a second copy is not started while it runs |
|
|
230
|
+
|
|
231
|
+
Set both when the host has both. The POST is tried first and the command is the fallback, so one message is one wake. One form is enough.
|
|
232
|
+
|
|
233
|
+
The wake JSON:
|
|
234
|
+
|
|
235
|
+
```json
|
|
236
|
+
{ "type": "surfcad.wake", "v": 1, "reason": "prompt",
|
|
237
|
+
"instruction": "A SurfCAD user sent you a chat message. On the surfcad MCP server call read_messages { wait_ms: 10000 }, then follow guide { topic: \"chat\" }: set_status responding first, then reply_to_user.",
|
|
238
|
+
"prompts": [{ "id": "…", "text": "make the boss taller", "ts": "…", "hasScreenshot": true }] }
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
The text is a preview. The message itself stays on the server until an agent process reads it with `read_messages`, so a wake never consumes a message. A screenshot is not in the wake; `read_messages` returns it.
|
|
242
|
+
|
|
243
|
+
How it works:
|
|
244
|
+
|
|
245
|
+
- `npx surfcad-mcp listen` long-polls the server relay (`GET /agent/prompts`) with the saved login. Outbound HTTPS only: no open port, it works behind NAT, and it works when the user is on a phone, because neither side has to reach the other.
|
|
246
|
+
- A message is not woken for at once. An agent that is already polling takes it within seconds. After 4 seconds the listener asks the server whether the message is still unread, and only then fires the wake. A message still unread two minutes after a wake is woken for once more.
|
|
247
|
+
- An agent in a turn is not woken. Every MCP tool call stamps a small file (`awake` in the config directory), and for 60 seconds after the last one the agent counts as in a turn: it reads the message at its next `read_messages`, and a wake on top of that would start a second turn beside the first. The message is looked at again every 15 seconds until the agent reads it or goes idle.
|
|
248
|
+
- A long-lived `surfcad-mcp` MCP process fires the same wake itself for a message that sits unread in its queue. That covers the local relay, which has no login. When a listener is running on the server relay, the listener owns the wake.
|
|
249
|
+
- `npx surfcad-mcp status` prints the saved wake and whether the listener is running. The MCP `status` tool returns `wake: { coldWake, forms, source, listenerRunning, note }` (`source` is `env` or `saved`) and `host: { name, version }` (what the MCP client calls itself), and every `pair` result carries the note. A `status` call also starts the listener again when it has stopped.
|
|
250
|
+
- A new session has no memory of earlier ones. The wake's `instruction` says so and points it at the message in `prompts`, `status` for the open part, and `guide { topic: "start" }`.
|
|
251
|
+
- `npx surfcad-mcp wake show | test | clear`, `npx surfcad-mcp listen --stop`. The listener logs to `listener.log` in the config directory. Start it again after a reboot, or add `npx surfcad-mcp listen` to the host's startup (a systemd user unit, launchd, pm2).
|
|
252
|
+
|
|
253
|
+
What is saved: `wake.json` next to the saved login, mode 0600. It is written only by `wake set` on this machine. Nothing a server, a tab or a chat message sends can change it. Message text reaches the command on stdin only, never in its arguments or environment. The bearer is never printed or logged.
|
|
254
|
+
|
|
255
|
+
`register_webhook` is still there for a host with a public HTTPS endpoint. It lives in one MCP process's memory, so it cannot wake an agent whose host starts a fresh process per tool call. The wake can.
|
|
256
|
+
|
|
188
257
|
## Safety and consent
|
|
189
258
|
|
|
190
259
|
- **Commerce:** Agents cannot place orders or drive checkout. Quote/cart/checkout controls are not exposed as MCP tools.
|
|
@@ -197,6 +266,12 @@ Bridge refusals (`consent_pending`, `real_repo_blocked`, `confirm_required`, `no
|
|
|
197
266
|
|
|
198
267
|
If the SurfCAD tab or the relay goes away mid-session, tool calls return `pairing_lost` right away (with a `hint`) instead of waiting for the MCP client timeout. The server keeps re-pairing in the background with the same code. The tab reconnects by itself, so calls start working again once SurfCAD is back in Chrome, with no new code and no reload. A call made while you still need to click Allow returns `pair_pending`. The relay pings every socket every 5 s (`SURFCAD_AGENT_BRIDGE_HEARTBEAT_MS`) and logs each drop on stderr with a timestamp and reason. Pairing codes are redacted in the log. Set `SURFCAD_AGENT_BRIDGE_WS_VERBOSE=1` to also log routine pairing events.
|
|
199
268
|
|
|
269
|
+
## Disconnect
|
|
270
|
+
|
|
271
|
+
When the user chooses **Disconnect** in SurfCAD (server relay), the server revokes the login of the agent that last worked in that window. From then on every call with that token answers `token_revoked`. The MCP server deletes the saved login and unregisters any webhook the first time it sees that, and `surfcad-mcp listen` stops and deletes it too, so nothing retries with a dead token and `npx surfcad-mcp status` says `not logged in`. Nothing reconnects by itself: the user pairs again and you run `npx surfcad-mcp login`. The saved wake setup is kept, so a new login only needs `npx surfcad-mcp listen --detach`.
|
|
272
|
+
|
|
273
|
+
A reload, a sleeping tab or a dropped connection is not a Disconnect and revokes nothing.
|
|
274
|
+
|
|
200
275
|
## Monorepo maintenance
|
|
201
276
|
|
|
202
277
|
In the [SurfCAD monorepo](https://github.com/artur0x0/surfcad), `npm run export:agent` regenerates `data/commands.json` from `src/agent/commands.json`. CI fails if that copy is stale (`test/commandsFreshness.test.mjs`). Before publishing, run `export:agent` and `npm run smoke:pack` in this package.
|
package/data/commands.json
CHANGED
|
@@ -5600,7 +5600,7 @@
|
|
|
5600
5600
|
},
|
|
5601
5601
|
{
|
|
5602
5602
|
"name": "insert_fillet_edges",
|
|
5603
|
-
"description": "Prefer this over freehand set_script. Insert this helper on the active part (set_active_part first) and run it. Numbers are finite and within ±1000000 mm (positions and deltas included); NaN and Infinity are bad_args. Working copy only; git_save commits. The result usedSelection says whether the viewport selection was used. A face pick is written into the script by name (facesNamed for a hole, edgesOf for a fillet or chamfer around that face) and is found again on the new mesh after every rebuild, so a second use_selection insert lands on the same face; an edge pick (select_edges { names }, pick sessions, a tap) is written as edgesNamed(part, \"faceA~faceB\"), the pair of stamped faces it lies between, which also survives edits. Every face has a name (helper roles, fillet1.round / chamfer2.bevel, import@1.f<k>, <block>.f<k> for freehand). Edge picks still clear with the rebuild (re-pick before the next insert), and use_selection: true with nothing selected is no_selection (nothing is written). Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then Build and Shape, then Polish, then pattern and place; finish each stage across the whole assembly before the next. Features first: insert_code_snippet { gap, why, script } is the fallback for one operation no feature can do (its block starts with // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); set_script only rewrites a whole part. Hardware is one part per unique fastener type, one instance patterned to every place it goes. Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Use part_set_transform only for parts that touch nothing. Block-out positions are rough; joints set final positions. If the geometry engine crashes under this part (out of memory, a wasm abort, or a run past its 30 s budget) the result is ok: false with crash { code: geometry_worker_crashed, reason: wasm_abort | out_of_memory | timeout | worker_lost, workerRestarted: true } and one failures row with the same code; status.runState is failed. The worker was already replaced and other parts kept building, so do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, or split it into smaller parts, then run it again. When the run past the budget was inside one marked feature block, the part is rebuilt without that block instead: the result is ok: false with one failures row { code: feature_timeout, featureId, featureType, featureLabel, elapsedMs, budgetMs, detail }, status.runState is failed, the other features are built and shown, and status.featureMs (and feature_tree ms) say how long each block took; edit, delete, or undo that feature. Cost: fillets and chamfers are the slow features. Do them last, once the shape is final, on the smallest edge set that does the job (a face pick writes edgesOf for that face only; grouped edges from list_edges for less), because a blend over many edges, or on a swept or lofted body, can run past the 30 s block budget and come back as feature_timeout with the part rebuilt without it. Order (required): shell first, then concave fillets and chamfers, then convex ones. After a shell or a concave blend pick the edges by name (select_edges { names } or a face pick, then use_selection: true); the no-selection default is for a plain block and
|
|
5603
|
+
"description": "Prefer this over freehand set_script. Insert this helper on the active part (set_active_part first) and run it. Numbers are finite and within ±1000000 mm (positions and deltas included); NaN and Infinity are bad_args. Working copy only; git_save commits. The result usedSelection says whether the viewport selection was used. A face pick is written into the script by name (facesNamed for a hole, edgesOf for a fillet or chamfer around that face) and is found again on the new mesh after every rebuild, so a second use_selection insert lands on the same face; an edge pick (select_edges { names }, pick sessions, a tap) is written as edgesNamed(part, \"faceA~faceB\"), the pair of stamped faces it lies between, which also survives edits. Every face has a name (helper roles, fillet1.round / chamfer2.bevel, import@1.f<k>, <block>.f<k> for freehand). Edge picks still clear with the rebuild (re-pick before the next insert), and use_selection: true with nothing selected is no_selection (nothing is written). Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then Build and Shape, then Polish, then pattern and place; finish each stage across the whole assembly before the next. Features first: insert_code_snippet { gap, why, script } is the fallback for one operation no feature can do (its block starts with // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); set_script only rewrites a whole part. Hardware is one part per unique fastener type, one instance patterned to every place it goes. Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Use part_set_transform only for parts that touch nothing. Block-out positions are rough; joints set final positions. If the geometry engine crashes under this part (out of memory, a wasm abort, or a run past its 30 s budget) the result is ok: false with crash { code: geometry_worker_crashed, reason: wasm_abort | out_of_memory | timeout | worker_lost, workerRestarted: true } and one failures row with the same code; status.runState is failed. The worker was already replaced and other parts kept building, so do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, or split it into smaller parts, then run it again. When the run past the budget was inside one marked feature block, the part is rebuilt without that block instead: the result is ok: false with one failures row { code: feature_timeout, featureId, featureType, featureLabel, elapsedMs, budgetMs, detail }, status.runState is failed, the other features are built and shown, and status.featureMs (and feature_tree ms) say how long each block took; edit, delete, or undo that feature. Cost: fillets and chamfers are the slow features. Do them last, once the shape is final, on the smallest edge set that does the job (a face pick writes edgesOf for that face only; grouped edges from list_edges for less), because a blend over many edges, or on a swept or lofted body, can run past the 30 s block budget and come back as feature_timeout with the part rebuilt without it. Order (required): shell first, then concave fillets and chamfers, then convex ones. After a shell or a concave blend pick the edges by name (select_edges { names } or a face pick, then use_selection: true); the no-selection default takes every convex edge, is for a plain block, and can fail there (guide { topic: \"modeling\" }). Writes (defaults): part = filletEdges(part, convexEdges(part), 3, { sphericalCorners: true }); Takes return: \"status\" | \"summary\" | \"full\" (MCP default \"status\": status.script is omitted; \"summary\" adds status.features; \"full\" echoes the script).",
|
|
5604
5604
|
"args": {
|
|
5605
5605
|
"type": "object",
|
|
5606
5606
|
"additionalProperties": false,
|
|
@@ -5893,7 +5893,7 @@
|
|
|
5893
5893
|
},
|
|
5894
5894
|
{
|
|
5895
5895
|
"name": "insert_chamfer_edges",
|
|
5896
|
-
"description": "Prefer this over freehand set_script. Insert this helper on the active part (set_active_part first) and run it. Numbers are finite and within ±1000000 mm (positions and deltas included); NaN and Infinity are bad_args. Working copy only; git_save commits. The result usedSelection says whether the viewport selection was used. A face pick is written into the script by name (facesNamed for a hole, edgesOf for a fillet or chamfer around that face) and is found again on the new mesh after every rebuild, so a second use_selection insert lands on the same face; an edge pick (select_edges { names }, pick sessions, a tap) is written as edgesNamed(part, \"faceA~faceB\"), the pair of stamped faces it lies between, which also survives edits. Every face has a name (helper roles, fillet1.round / chamfer2.bevel, import@1.f<k>, <block>.f<k> for freehand). Edge picks still clear with the rebuild (re-pick before the next insert), and use_selection: true with nothing selected is no_selection (nothing is written). Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then Build and Shape, then Polish, then pattern and place; finish each stage across the whole assembly before the next. Features first: insert_code_snippet { gap, why, script } is the fallback for one operation no feature can do (its block starts with // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); set_script only rewrites a whole part. Hardware is one part per unique fastener type, one instance patterned to every place it goes. Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Use part_set_transform only for parts that touch nothing. Block-out positions are rough; joints set final positions. If the geometry engine crashes under this part (out of memory, a wasm abort, or a run past its 30 s budget) the result is ok: false with crash { code: geometry_worker_crashed, reason: wasm_abort | out_of_memory | timeout | worker_lost, workerRestarted: true } and one failures row with the same code; status.runState is failed. The worker was already replaced and other parts kept building, so do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, or split it into smaller parts, then run it again. When the run past the budget was inside one marked feature block, the part is rebuilt without that block instead: the result is ok: false with one failures row { code: feature_timeout, featureId, featureType, featureLabel, elapsedMs, budgetMs, detail }, status.runState is failed, the other features are built and shown, and status.featureMs (and feature_tree ms) say how long each block took; edit, delete, or undo that feature. Cost: fillets and chamfers are the slow features. Do them last, once the shape is final, on the smallest edge set that does the job (a face pick writes edgesOf for that face only; grouped edges from list_edges for less), because a blend over many edges, or on a swept or lofted body, can run past the 30 s block budget and come back as feature_timeout with the part rebuilt without it. Order (required): shell first, then concave fillets and chamfers, then convex ones. After a shell or a concave blend pick the edges by name (select_edges { names } or a face pick, then use_selection: true); the no-selection default is for a plain block and
|
|
5896
|
+
"description": "Prefer this over freehand set_script. Insert this helper on the active part (set_active_part first) and run it. Numbers are finite and within ±1000000 mm (positions and deltas included); NaN and Infinity are bad_args. Working copy only; git_save commits. The result usedSelection says whether the viewport selection was used. A face pick is written into the script by name (facesNamed for a hole, edgesOf for a fillet or chamfer around that face) and is found again on the new mesh after every rebuild, so a second use_selection insert lands on the same face; an edge pick (select_edges { names }, pick sessions, a tap) is written as edgesNamed(part, \"faceA~faceB\"), the pair of stamped faces it lies between, which also survives edits. Every face has a name (helper roles, fillet1.round / chamfer2.bevel, import@1.f<k>, <block>.f<k> for freehand). Edge picks still clear with the rebuild (re-pick before the next insert), and use_selection: true with nothing selected is no_selection (nothing is written). Build in ribbon order: block out every part of the assembly as plain blocks first (within seconds of the prompt, then screenshot for the user), then Build and Shape, then Polish, then pattern and place; finish each stage across the whole assembly before the next. Features first: insert_code_snippet { gap, why, script } is the fallback for one operation no feature can do (its block starts with // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); set_script only rewrites a whole part. Hardware is one part per unique fastener type, one instance patterned to every place it goes. Fix one base part with a fixed joint, then place every part that touches or attaches to another with joint_create (one call creates the joint and solves placement). Use part_set_transform only for parts that touch nothing. Block-out positions are rough; joints set final positions. If the geometry engine crashes under this part (out of memory, a wasm abort, or a run past its 30 s budget) the result is ok: false with crash { code: geometry_worker_crashed, reason: wasm_abort | out_of_memory | timeout | worker_lost, workerRestarted: true } and one failures row with the same code; status.runState is failed. The worker was already replaced and other parts kept building, so do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, or split it into smaller parts, then run it again. When the run past the budget was inside one marked feature block, the part is rebuilt without that block instead: the result is ok: false with one failures row { code: feature_timeout, featureId, featureType, featureLabel, elapsedMs, budgetMs, detail }, status.runState is failed, the other features are built and shown, and status.featureMs (and feature_tree ms) say how long each block took; edit, delete, or undo that feature. Cost: fillets and chamfers are the slow features. Do them last, once the shape is final, on the smallest edge set that does the job (a face pick writes edgesOf for that face only; grouped edges from list_edges for less), because a blend over many edges, or on a swept or lofted body, can run past the 30 s block budget and come back as feature_timeout with the part rebuilt without it. Order (required): shell first, then concave fillets and chamfers, then convex ones. After a shell or a concave blend pick the edges by name (select_edges { names } or a face pick, then use_selection: true); the no-selection default takes every convex edge, is for a plain block, and can fail there (guide { topic: \"modeling\" }). Writes (defaults): part = chamferEdges(part, convexEdges(part), 2); Takes return: \"status\" | \"summary\" | \"full\" (MCP default \"status\": status.script is omitted; \"summary\" adds status.features; \"full\" echoes the script).",
|
|
5897
5897
|
"args": {
|
|
5898
5898
|
"type": "object",
|
|
5899
5899
|
"additionalProperties": false,
|
package/package.json
CHANGED
package/src/cli.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `surfcad-mcp` argv. login / logout / status exit.
|
|
3
|
-
*
|
|
2
|
+
* `surfcad-mcp` argv. login / logout / status / wake exit. `listen` runs the
|
|
3
|
+
* wake listener until it is stopped. Anything else starts the stdio server.
|
|
4
|
+
* The token and the wake bearer are never written to stdout or stderr.
|
|
4
5
|
*/
|
|
5
6
|
|
|
6
7
|
import { hostname } from 'node:os';
|
|
@@ -8,6 +9,13 @@ import { resolveAgentName, resolveServerUrl, selectRelayMode } from './remote/co
|
|
|
8
9
|
import { loginDevice, loginWithCode } from './remote/login.mjs';
|
|
9
10
|
import { logoutDevice } from './remote/logout.mjs';
|
|
10
11
|
import { formatLoginStatus, readSavedLogin } from './remote/tokenStore.mjs';
|
|
12
|
+
import {
|
|
13
|
+
bootstrapAfterLogin,
|
|
14
|
+
runListenCommand,
|
|
15
|
+
runWakeCommand,
|
|
16
|
+
wakeStatusText,
|
|
17
|
+
WAKE_SETUP_STEPS,
|
|
18
|
+
} from './listen/listenCli.mjs';
|
|
11
19
|
|
|
12
20
|
const HELP = `surfcad-mcp
|
|
13
21
|
|
|
@@ -23,6 +31,27 @@ const HELP = `surfcad-mcp
|
|
|
23
31
|
Revokes this machine's token on the server, then deletes the saved
|
|
24
32
|
file. If the server cannot be reached, the file is still deleted.
|
|
25
33
|
npx surfcad-mcp status
|
|
34
|
+
The saved login, the wake setup, and whether the listener is running.
|
|
35
|
+
|
|
36
|
+
Wake: start a session of the agent when the user sends a chat message from
|
|
37
|
+
SurfCAD and no agent process is reading. A host provides its wake in this
|
|
38
|
+
server's environment (SURFCAD_WAKE_POST with SURFCAD_WAKE_BEARER, and/or
|
|
39
|
+
SURFCAD_WAKE_EXEC); login and pair then start the listener by themselves
|
|
40
|
+
and the agent greets the user. SURFCAD_WAKE_BOOTSTRAP=0 turns that off.
|
|
41
|
+
The manual way, when the host provides nothing:
|
|
42
|
+
${WAKE_SETUP_STEPS.map((step, i) => ` ${i + 1}. ${step}`).join('\n')}
|
|
43
|
+
npx surfcad-mcp wake set [--post URL [--bearer KEY]] [--exec COMMAND]
|
|
44
|
+
Save how to wake the agent on this machine. --post: the wake JSON is
|
|
45
|
+
POSTed there (https, or http to localhost). --exec: the command runs
|
|
46
|
+
with the wake JSON on stdin. With both, the POST is tried first and
|
|
47
|
+
the command is the fallback. The key can also come from
|
|
48
|
+
SURFCAD_WAKE_BEARER. It is saved on this machine and is not printed.
|
|
49
|
+
npx surfcad-mcp wake show | test | clear
|
|
50
|
+
npx surfcad-mcp listen [--detach] [--stop]
|
|
51
|
+
Watch the server relay for chat messages and fire the wake for one
|
|
52
|
+
that no agent process reads within a few seconds. Outbound HTTPS
|
|
53
|
+
only: no open port, works behind NAT. Needs a saved login and a saved
|
|
54
|
+
wake. --detach starts it in the background and returns. --stop ends it.
|
|
26
55
|
|
|
27
56
|
--remote Use the server relay. Requires a saved login.
|
|
28
57
|
--local Use the local relay even when a login is saved.
|
|
@@ -42,22 +71,64 @@ SURFCAD_AGENT_BRIDGE_WS_PORT, or a non-empty SURFCAD_PAIRING_CODE.
|
|
|
42
71
|
* @param {string[]} argv
|
|
43
72
|
*/
|
|
44
73
|
export function parseArgs(argv) {
|
|
45
|
-
/** @type {'serve' | 'login' | 'logout' | 'status' | 'help'} */
|
|
74
|
+
/** @type {'serve' | 'login' | 'logout' | 'status' | 'listen' | 'wake' | 'help'} */
|
|
46
75
|
let command = 'serve';
|
|
47
76
|
let name = '';
|
|
48
77
|
let server = '';
|
|
49
78
|
let code = '';
|
|
50
79
|
let remote = false;
|
|
51
80
|
let local = false;
|
|
81
|
+
let action = '';
|
|
82
|
+
let post = '';
|
|
83
|
+
let exec = '';
|
|
84
|
+
let bearer = '';
|
|
85
|
+
let detach = false;
|
|
86
|
+
let stop = false;
|
|
87
|
+
const valued = (arg, flag, i) => {
|
|
88
|
+
const value = arg === flag ? argv[i + 1] : arg.slice(flag.length + 1);
|
|
89
|
+
if (!value || (arg === flag && value.startsWith('--'))) {
|
|
90
|
+
throw Object.assign(new Error(`${flag} needs a value.`), { code: 'bad_args' });
|
|
91
|
+
}
|
|
92
|
+
return value;
|
|
93
|
+
};
|
|
52
94
|
for (let i = 0; i < argv.length; i += 1) {
|
|
53
95
|
const arg = argv[i];
|
|
54
|
-
if (arg === 'login' || arg === 'logout' || arg === 'status') {
|
|
96
|
+
if (arg === 'login' || arg === 'logout' || arg === 'status' || arg === 'listen' || arg === 'wake') {
|
|
55
97
|
if (command !== 'serve') {
|
|
56
|
-
throw Object.assign(new Error('Pass one command: login, logout, or
|
|
98
|
+
throw Object.assign(new Error('Pass one command: login, logout, status, wake, or listen.'), { code: 'bad_args' });
|
|
57
99
|
}
|
|
58
100
|
command = arg;
|
|
59
101
|
continue;
|
|
60
102
|
}
|
|
103
|
+
if (command === 'wake' && !action && (arg === 'set' || arg === 'show' || arg === 'test' || arg === 'clear')) {
|
|
104
|
+
action = arg;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (arg === '--detach') {
|
|
108
|
+
detach = true;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (arg === '--stop') {
|
|
112
|
+
stop = true;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (arg === '--post' || arg.startsWith('--post=')) {
|
|
116
|
+
post = valued(arg, '--post', i);
|
|
117
|
+
if (arg === '--post') i += 1;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (arg === '--exec' || arg.startsWith('--exec=')) {
|
|
121
|
+
// A command may start with "--" only in the = form.
|
|
122
|
+
exec = arg === '--exec' ? argv[i + 1] || '' : arg.slice('--exec='.length);
|
|
123
|
+
if (!exec) throw Object.assign(new Error('--exec needs a value.'), { code: 'bad_args' });
|
|
124
|
+
if (arg === '--exec') i += 1;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (arg === '--bearer' || arg.startsWith('--bearer=')) {
|
|
128
|
+
bearer = valued(arg, '--bearer', i);
|
|
129
|
+
if (arg === '--bearer') i += 1;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
61
132
|
if (arg === '--help' || arg === '-h' || arg === 'help') {
|
|
62
133
|
command = 'help';
|
|
63
134
|
continue;
|
|
@@ -96,7 +167,16 @@ export function parseArgs(argv) {
|
|
|
96
167
|
}
|
|
97
168
|
throw Object.assign(new Error(`Unknown argument: ${arg}`), { code: 'bad_args' });
|
|
98
169
|
}
|
|
99
|
-
|
|
170
|
+
if (command !== 'wake' && (post || exec || bearer)) {
|
|
171
|
+
throw Object.assign(new Error('--post, --exec and --bearer go with: wake set.'), { code: 'bad_args' });
|
|
172
|
+
}
|
|
173
|
+
if (command !== 'listen' && (detach || stop)) {
|
|
174
|
+
throw Object.assign(new Error('--detach and --stop go with: listen.'), { code: 'bad_args' });
|
|
175
|
+
}
|
|
176
|
+
if (detach && stop) {
|
|
177
|
+
throw Object.assign(new Error('Pass --detach or --stop, not both.'), { code: 'bad_args' });
|
|
178
|
+
}
|
|
179
|
+
return { command, name, server, code, remote, local, action, post, exec, bearer, detach, stop };
|
|
100
180
|
}
|
|
101
181
|
|
|
102
182
|
/**
|
|
@@ -122,6 +202,9 @@ function flagsFromEnv(env, flags) {
|
|
|
122
202
|
* fetch?: typeof fetch,
|
|
123
203
|
* io?: { stdout: (text: string) => void, stderr: (text: string) => void },
|
|
124
204
|
* machine?: string,
|
|
205
|
+
* spawn?: any,
|
|
206
|
+
* signal?: AbortSignal,
|
|
207
|
+
* onSignals?: (stop: () => void) => void,
|
|
125
208
|
* }} [options]
|
|
126
209
|
* @returns {Promise<{ action: 'exit', code: number } | { action: 'serve', mode: 'local' | 'remote', server: string, name: string }>}
|
|
127
210
|
*/
|
|
@@ -143,9 +226,9 @@ export async function runCli(argv, options = {}) {
|
|
|
143
226
|
io.stdout(HELP);
|
|
144
227
|
return { action: 'exit', code: 0 };
|
|
145
228
|
}
|
|
146
|
-
if (parsed.command
|
|
229
|
+
if (parsed.command !== 'serve') {
|
|
147
230
|
if (parsed.remote || parsed.local) {
|
|
148
|
-
io.stderr(`login, logout, and
|
|
231
|
+
io.stderr(`login, logout, status, wake, and listen do not take --remote or --local.\n${HELP}`);
|
|
149
232
|
return { action: 'exit', code: 1 };
|
|
150
233
|
}
|
|
151
234
|
}
|
|
@@ -163,6 +246,7 @@ export async function runCli(argv, options = {}) {
|
|
|
163
246
|
fetch: options.fetch,
|
|
164
247
|
});
|
|
165
248
|
io.stdout('Logged in. The token is saved on this machine and is not printed.\n');
|
|
249
|
+
io.stdout(await bootstrapAfterLogin({ env, spawn: options.spawn }));
|
|
166
250
|
return { action: 'exit', code: 0 };
|
|
167
251
|
}
|
|
168
252
|
await loginDevice({
|
|
@@ -176,6 +260,7 @@ export async function runCli(argv, options = {}) {
|
|
|
176
260
|
},
|
|
177
261
|
});
|
|
178
262
|
io.stdout('Logged in. The token is saved on this machine and is not printed.\n');
|
|
263
|
+
io.stdout(await bootstrapAfterLogin({ env, spawn: options.spawn }));
|
|
179
264
|
return { action: 'exit', code: 0 };
|
|
180
265
|
}
|
|
181
266
|
if (parsed.command === 'logout') {
|
|
@@ -191,10 +276,26 @@ export async function runCli(argv, options = {}) {
|
|
|
191
276
|
const saved = await readSavedLogin(env);
|
|
192
277
|
const serverUrl = resolveServerUrl({ flag: parsed.server, env, saved });
|
|
193
278
|
io.stdout(formatLoginStatus(saved, serverUrl));
|
|
279
|
+
io.stdout(await wakeStatusText(env));
|
|
194
280
|
return { action: 'exit', code: 0 };
|
|
195
281
|
}
|
|
282
|
+
if (parsed.command === 'wake') {
|
|
283
|
+
const code = await runWakeCommand(parsed, { env, io, fetch: options.fetch, spawn: options.spawn });
|
|
284
|
+
return { action: 'exit', code };
|
|
285
|
+
}
|
|
286
|
+
if (parsed.command === 'listen') {
|
|
287
|
+
const code = await runListenCommand(parsed, {
|
|
288
|
+
env,
|
|
289
|
+
io,
|
|
290
|
+
fetch: options.fetch,
|
|
291
|
+
spawn: options.spawn,
|
|
292
|
+
signal: options.signal,
|
|
293
|
+
onSignals: options.onSignals,
|
|
294
|
+
});
|
|
295
|
+
return { action: 'exit', code };
|
|
296
|
+
}
|
|
196
297
|
} catch (err) {
|
|
197
|
-
const usage = err?.code === '
|
|
298
|
+
const usage = err?.code === 'bad_server' || (err?.code === 'bad_args' && parsed.command !== 'wake') ? HELP : '';
|
|
198
299
|
io.stderr(`${err?.message || 'Login failed'}\n${usage}`);
|
|
199
300
|
return { action: 'exit', code: 1 };
|
|
200
301
|
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "The agent is in a turn right now": the time of its last MCP tool call,
|
|
3
|
+
* shared between surfcad-mcp processes on this machine through one small
|
|
4
|
+
* file. The MCP server stamps it on every tool call. The listener reads it
|
|
5
|
+
* before a wake.
|
|
6
|
+
*
|
|
7
|
+
* An agent in a turn is not woken. It reads the message at its next
|
|
8
|
+
* read_messages, as the chat guide requires, and a wake on top of that would
|
|
9
|
+
* start a second turn beside the first (with an exec wake, a second copy of
|
|
10
|
+
* the agent). Once it has made no tool call for AWAKE_MS it counts as idle,
|
|
11
|
+
* the same 60 s after which the tab shows it idle, and an unread message
|
|
12
|
+
* wakes it.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
16
|
+
import { join } from 'node:path';
|
|
17
|
+
import { configDir } from '../remote/config.mjs';
|
|
18
|
+
|
|
19
|
+
/** No tool call for this long: the agent is idle and may be woken. */
|
|
20
|
+
export const AWAKE_MS = 60_000;
|
|
21
|
+
/** The stamp is rewritten at most this often. */
|
|
22
|
+
const STAMP_EVERY_MS = 5_000;
|
|
23
|
+
|
|
24
|
+
/** @param {NodeJS.ProcessEnv} [env] */
|
|
25
|
+
export function awakePath(env = process.env) {
|
|
26
|
+
return join(configDir(env), 'awake');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
let lastStampAt = 0;
|
|
30
|
+
let lastStampPath = '';
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Record a tool call. Best effort and throttled: a failure to write must
|
|
34
|
+
* never fail the tool call.
|
|
35
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
36
|
+
* @param {number} [now]
|
|
37
|
+
*/
|
|
38
|
+
export async function stampAwake(env = process.env, now = Date.now()) {
|
|
39
|
+
const path = awakePath(env);
|
|
40
|
+
if (path === lastStampPath && now - lastStampAt < STAMP_EVERY_MS) return;
|
|
41
|
+
lastStampAt = now;
|
|
42
|
+
lastStampPath = path;
|
|
43
|
+
try {
|
|
44
|
+
await mkdir(configDir(env), { recursive: true, mode: 0o700 });
|
|
45
|
+
await writeFile(path, `${now}\n`, { mode: 0o600 });
|
|
46
|
+
} catch {
|
|
47
|
+
/* best effort */
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
53
|
+
* @returns {Promise<number>} ms timestamp of the last tool call, 0 when none is recorded
|
|
54
|
+
*/
|
|
55
|
+
export async function lastAwakeAt(env = process.env) {
|
|
56
|
+
try {
|
|
57
|
+
const at = Number.parseInt((await readFile(awakePath(env), 'utf8')).trim(), 10);
|
|
58
|
+
return Number.isFinite(at) && at > 0 ? at : 0;
|
|
59
|
+
} catch {
|
|
60
|
+
return 0;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
66
|
+
* @param {number} [now]
|
|
67
|
+
*/
|
|
68
|
+
export async function agentAwake(env = process.env, now = Date.now()) {
|
|
69
|
+
const at = await lastAwakeAt(env);
|
|
70
|
+
return at > 0 && now - at >= 0 && now - at < AWAKE_MS;
|
|
71
|
+
}
|