surfcad-mcp 0.3.6 → 0.3.7

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 CHANGED
@@ -53,7 +53,7 @@ On Safari, iOS, or a phone-width page, SurfCAD shows a join code. `login --code
53
53
 
54
54
  `login` without `--code` runs device-code pairing against `https://surfcad.com/agent`. It generates 32 random bytes, sends only their SHA-256, prints an `ABCD-EFGH` code and the approval URL (`https://surfcad.com/agent`), then polls with the secret until you approve, deny, or the code expires. The token is written to the config directory at mode 0600 (the directory is 0700). It is not printed and it is not logged. `status` shows the server, name, machine, and saved time, never the token. `logout` calls `DELETE /agent/tokens/self` with that token, then deletes the file. If the server cannot be reached, the file is still deleted and the command says the login may stay valid until it expires.
55
55
 
56
- Sign in on the approval page and enter the code. Leave the SurfCAD tab open. The client connects out over WebSocket (`wss://surfcad.com/agent`) with `Authorization: Bearer`. The first frame is `{ "type": "hello", "v": 1 }`. If WebSocket is blocked, commands fall back to `POST /agent/commands` and then Server-Sent Events, or a long-poll `GET` if the event stream fails. In-viewer prompts travel on the WebSocket.
56
+ Sign in on the approval page and enter the code. Leave the SurfCAD tab open. The client connects out over WebSocket (`wss://surfcad.com/agent`) with `Authorization: Bearer`. The first frame is `{ "type": "hello", "v": 1 }`. If WebSocket is blocked, commands fall back to `POST /agent/commands` and then Server-Sent Events, or a long-poll `GET` if the event stream fails. A finished command's result stays readable by the token that submitted it for 2 minutes (`RESULT_RETENTION_MS` on the server), so that poll still finds a result the failed stream had already been sent; it used to answer `not_found` ("That command is no longer waiting") for a command the tab had run. In-viewer prompts travel on the WebSocket.
57
57
 
58
58
  `--server https://staging.example` or `SURFCAD_AGENT_SERVER` overrides the origin for dev and staging. https becomes `wss://`. `http://` and `ws://` are accepted only for localhost, 127.0.0.1, and ::1.
59
59
 
@@ -77,9 +77,9 @@ Clear failures:
77
77
  3. Add `surfcad-mcp` to your MCP client (`npx surfcad-mcp`), set `SURFCAD_PAIRING_CODE` to that code, or call the MCP **`pair`** tool with `{ "code": "BCDFGHJK" }`.
78
78
  4. Click **Allow** (the green check) in SurfCAD when prompted.
79
79
 
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.
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`, when no webhook is registered yet, returns an onboarding note as text content (a `type: "text"` block, not only `structuredContent` or `_meta`). The note asks the agent to request a webhook URL and key from the user. The key is the `bearer` argument. Suggested wording to relay: "To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I'll check for SurfCAD messages between steps, so replies may lag." If the user declines, the agent polls `read_messages`. This process holds the URL and bearer in memory only, so the agent should save them in its own config or memory and call `register_webhook` again after every pair. If a webhook is already registered when `pair` succeeds, the result omits that note and says the webhook is active.
82
+ A successful `pair`, when no webhook is registered yet, returns an onboarding note as text content (a `type: "text"` block, not only `structuredContent` or `_meta`). The note asks the agent to request a webhook URL and key from the user. The key is the `bearer` argument. Suggested wording to relay: "To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I'll check for SurfCAD messages between steps, so replies may lag." If the user declines, the agent must long-poll `read_messages { wait_ms: 10000 }` in a loop while connected (never neither a webhook nor the poll). This process holds the URL and bearer in memory only, so the agent should save them in its own config or memory and call `register_webhook` again after every pair. If a webhook is already registered when `pair` succeeds, the result omits that note and says the webhook is active.
83
83
 
84
84
  Nothing pairs without your approval.
85
85
 
@@ -111,7 +111,7 @@ In Cursor, add the same block under **Settings → MCP** or your project `.curso
111
111
  claude mcp add surfcad -- npx surfcad-mcp
112
112
  ```
113
113
 
114
- `read_messages { wait_ms }` (up to 25,000 ms) long-polls so an idle agent makes one call every 25 s instead of spinning. A local CLI session usually has no public https endpoint, so polling `read_messages` is the normal path there. Webhooks apply when the user runs a receiver that can take https POSTs. The key they send is the `bearer` argument of `register_webhook`.
114
+ `read_messages { wait_ms }` (up to 25,000 ms) long-polls. The required cycle while connected is `wait_ms: 10000`, called again as soon as it returns: the fallback when no webhook wakes the agent, and the safety net when one is registered. A poll is not activity: it keeps the session connected but does not restart the stall window. A local CLI session usually has no public https endpoint, so polling `read_messages` is the normal path there. Webhooks apply when the user runs a receiver that can take https POSTs. The key they send is the `bearer` argument of `register_webhook`.
115
115
 
116
116
  ## How to build
117
117
 
@@ -165,16 +165,18 @@ These five tools stay inside the local `surfcad-mcp` process. They are not SurfC
165
165
 
166
166
  | Tool | Args | What it does |
167
167
  | --- | --- | --- |
168
- | `register_webhook` | `{ url, bearer? }` | Remember an https URL that receives each user prompt as `POST` JSON `{ "type": "surfcad.prompt", ... }`. Optional `bearer` is sent as `Authorization: Bearer <bearer>` (non-empty, at most 4096 characters, no CR or LF). Rejects `http`, credentials in the URL, localhost, `.local` names, and private or loopback addresses. The URL and bearer are held only in memory, are never logged, are never written to disk, are never returned or put in status, are never sent to the SurfCAD tab, and are cleared on `unregister_webhook` and when the pairing session ends. A cancel of a prompt that was already delivered is POSTed as `{ "type": "cancel", "id" }` with the same bearer and timeout. Stop work on that id. |
168
+ | `register_webhook` | `{ url, bearer? }` | Remember an https URL that receives each user prompt as `POST` JSON `{ "type": "surfcad.prompt", ... }`. Optional `bearer` is sent as `Authorization: Bearer <bearer>` (non-empty, at most 4096 characters, no CR or LF). Rejects `http`, credentials in the URL, localhost, `.local` names, and private or loopback addresses. The URL and bearer are held only in memory, are never logged, are never written to disk, are never returned or put in status, are never sent to the SurfCAD tab, and are cleared on `unregister_webhook` and when the pairing session ends. Required when the host can receive HTTPS callbacks: call it right after every successful pair or login, before waiting for a prompt, and again in every new process. A cancel of a prompt that was already delivered is POSTed as `{ "type": "cancel", "id" }` with the same bearer and timeout. Stop work on that id. |
169
169
  | `unregister_webhook` | `{}` | Drop that URL and bearer. Later prompts are queued. |
170
- | `read_messages` | `{ max?, wait_ms? }` | Return queued prompts, oldest first, and remove them. A screenshot is the next MCP image content block (`image/png`), not part of the text. A cancel item `{ "type": "cancel", "id" }` means the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Every response includes `recent`: the last 50 prompts this session received, oldest first, each `{ id, state }`, in memory only, including on a remote session. An idle session that has not received a prompt has `recent: []`. `acked` is only the ids this call removed. A later `read_messages {}` with an empty queue still lists those ids, so you can recover one after the ack. `status.last` is only the newest. When you finish the task from a prompt you received, close that chat with `reply_to_user`. |
170
+ | `read_messages` | `{ max?, wait_ms? }` | Return queued prompts, oldest first, and remove them. A screenshot is the next MCP image content block (`image/png`), not part of the text. A cancel item `{ "type": "cancel", "id" }` means the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Every response includes `recent`: the last 50 prompts this session received, oldest first, each `{ id, state }`, in memory only, including on a remote session. An idle session that has not received a prompt has `recent: []`. `acked` is only the ids this call removed. A later `read_messages {}` with an empty queue still lists those ids, so you can recover one after the ack. `status.last` is only the newest. `read_messages` is a poll, not activity: with or without `wait_ms` it sends the tab nothing and does not restart the stall window. When you finish the task from a prompt you received, close that chat with `reply_to_user`. |
171
171
  | `reply_to_user` | `{ text, in_reply_to?, final? }` | Plain-text reply for a prompt id this session received. The final reply is expected and closes the task: when you finish a task started from the in-viewer prompt pane, send `reply_to_user` with `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. Several replies may share one id, including after `read_messages` has acked it, and the id may come from an earlier process (a fresh `surfcad-mcp` per tool call). `final: true` marks the agent idle. Omit `in_reply_to` to post one plain-text message on this paired session when no prompt is waiting. That note is not a prompt id, is limited to one per second, does not close a prompt, and is shown as text, not HTML. An `in_reply_to` that is not a prompt id is `unknown_prompt` and nothing is sent to the tab. A cancelled id returns `{ "ok": false, "error": "cancelled" }` and is not shown in the tab. |
172
- | `set_status` | `{ state, label?, id? }` | Progress only. It does not close the task; a closing `reply_to_user` does. `state: "responding"` (alias `typing`) keeps the chat open with bouncing dots. `state: "building"` (alias `working`) means you are creating or editing geometry: the chat collapses and the field shows "Agent is working...". Call `building` only once you have everything you need and are actually modeling. Listing parts, faces, edges, or transforms, `status`, and `read_messages` must not use `building`. The legacy boolean `working: true` is `building`. A model-changing tool also enters building if you skip the call. Building stays until the final reply, Stop, or disconnect. No activity for 15 minutes, while responding or building, shows the stall notice and leaves Stop up. With no prompt in flight the tab still shows it: the page keeps a session-level state fed by `set_status`, every model-changing tool call, and `post_progress`, and goes idle 60 s after the last one. A cancelled id returns `{ "ok": false, "error": "cancelled" }`. |
172
+ | `set_status` | `{ state, label?, id? }` | Progress only. It does not close the task; a closing `reply_to_user` does. `state: "responding"` (alias `typing`) is the ack after `read_messages`: call it first, before any other tool, and the chat stays open with bouncing dots. A non-final reply stays visible for 10 seconds. `state: "building"` (alias `working`) means you are creating or editing geometry: after that hold the chat folds and the field shows "Agent is working...". Call `building` only once you have everything you need and are actually modeling. Listing parts, faces, edges, or transforms, `status`, and `read_messages` must not use `building`. The legacy boolean `working: true` is `building`. A model-changing tool also enters building if you skip the call. Building stays until the final reply, Stop, or disconnect. No activity for 15 minutes, while responding or building, shows the stall notice and leaves Stop up. `set_status`, a model-changing tool, `post_progress`, and `reply_to_user` are activity; a `read_messages` poll is not. With no prompt in flight the tab still shows it: the page keeps a session-level state fed by `set_status`, every model-changing tool call, and `post_progress`, and goes idle 60 s after the last one. A cancelled id returns `{ "ok": false, "error": "cancelled" }`. |
173
173
 
174
174
  A paired SurfCAD tab sends `agent.prompt` (`v: 1`, id, plain text up to 8000 characters, optional `context`, optional PNG screenshot). On a remote login the same frame arrives on the agent WebSocket, or, when that socket is blocked, from `GET /agent/prompts` (bearer, long-poll). Both paths are accepted the same way. While the agent is present the server holds a prompt until a process reports it taken (`agent.prompt.taken`, sent when `read_messages` returns it or the webhook POST succeeds), offering it to each new socket after hello and once to each pull session (`GET /agent/prompts?session=<id>`), so a one-shot process per tool call does not lose it; the tab hears `queued` at once when no socket is open. A prompt that arrives twice in one process is kept once. One prompt per second. A screenshot over 2 MB is rejected. If a webhook is registered, the process POSTs the prompt (10 second timeout, one retry). When `bearer` was set, that POST includes `Authorization: Bearer <bearer>`. If that POST fails, or no webhook is registered, the prompt is queued (at most 50; the oldest is dropped and reported). The tab gets `agent.prompt.ack` with `delivery` `webhook`, `queued`, or `failed`. Replies and working state go back as `agent.reply` and `agent.status`.
175
175
 
176
176
  When you finish a task started from the 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. `set_status` is for progress and does not close the task. Call `set_status { state: "building" }` only once you have everything you need and are actually creating or editing geometry. Reads stay on responding.
177
177
 
178
+ After `read_messages` returns a prompt, ack first with `set_status { state: "responding", id: <prompt id> }` before any other tool (the bouncing dots; there is no separate ack tool), then one short `reply_to_user` with `final: false`. The tab holds that reply for 10 seconds. Building, `post_progress`, or a model change during the hold waits, then the chat folds and the spinner shows. `final: true` stops the spinner, reopens the chat, and idles. While connected, long-poll `read_messages { wait_ms: 10000 }` in a loop (required with no webhook, the safety net with one), and call `register_webhook` again after every pair. An empty immediate read does not mean the user never sent. `guide { topic: "chat" }` is the whole required workflow.
179
+
178
180
  `reply_to_user` accepts an `in_reply_to` that this process received (queued, delivered by webhook or `read_messages`, or already replied) or a prompt id from an earlier process. Anything that is not a prompt id is an error `unknown_prompt` and no `agent.reply` is sent. Omit `in_reply_to` to post one plain-text `agent.message` on this paired session (no prompt id, one per second). The page drops a reply whose id is not a prompt the user sent, and it draws a session note as text, not HTML. `read_messages` includes `recent`, the last 50 prompts in this session (`{ id, state }`, oldest first, memory only), on a local or remote session. An idle session has `recent: []`. That list stays after the ack, including when the queue is empty. `status.last` is only the newest id.
179
181
 
180
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`.
@@ -2,7 +2,7 @@
2
2
  "version": 1,
3
3
  "bridgeVersion": 1,
4
4
  "generatedBy": "npm run export:agent",
5
- "count": 212,
5
+ "count": 213,
6
6
  "$defs": {
7
7
  "status": {
8
8
  "type": "object",
@@ -2534,7 +2534,7 @@
2534
2534
  },
2535
2535
  {
2536
2536
  "name": "mold_fit",
2537
- "description": "Read-only moldability fit for one part mesh, in the part local frame (the same frame as list_faces). Searches bounding-box axes, large planar normals, and an icosphere (about 80 directions, deduped within 5°, d and -d are one axis). The chosen pull has the least occluded undercut area. Scores within max(2% of the part area, 25 mm²) of that best are tied; box axes and large planar normals win the tie over an icosphere sample, and drafted area breaks the rest. Fit is still good (0 undercut regions), fixable (1 to 4), or not_a_fit (5 or more), plus undercutCount, undercutArea, draftedArea, pull, and pullSource. Pass pull [x, y, z] to score that axis instead and keep its sign. The same result includes wall: a local thickness per triangle, nominal (mode, or the median when no thickness dominates the interior band), max, min, mean, median, and thin and thick regions. Thickness below 0.6× nominal is thin and above 1.5× nominal is thick. Wall thickness follows the geometric normal of each triangle. A stamp only flips that side when it points the other way, so one stamp on a curved face does not steer every facet. A triangle whose own normal is within 0.5° of perpendicular to the pull is not an undercut, and an undercut needs another triangle covering that point. A geometric check for later molding slices, not a supplier DFM. parting on the same result classifies every face as core or cavity by complete visibility (core along +pull, cavity along -pull). A wall within 0.5° of vertical takes the role of the labelled neighbour it can reach. There is no zero-draft class. One outer parting loop is kept. Stamped edges keep their names. On the same result, sideActions lists each block: a slide, a lifter, or an unresolved undercut. A block is one piece of steel that forms a connected set of trapped faces and withdraws along one direction. Every trapped feature that shares a direction on one connected surface is one block, whatever the gap between the features, so two holes on one wall are one slide. Each block carries pull (its withdraw direction, never the main pull axis), area (the block face it forms, which includes untrapped surface inside its window), trappedArea, window, span along the main pull, features (the stamped blocks it carries) and frees (the stamped faces it forms). A slide withdraws in the parting plane. A lifter withdraws tilted 15° to 25° into the core, and only when that tilt leaves the part without entering material. An unresolved undercut has no straight direction that frees it (a slot whose ends narrow toward the outer face); it needs a modelling change or a special mechanism. count is every block, slides, lifters and unresolved undercuts, and is what the report prices. A wall within 0.5° of vertical is not a side action. Undercuts are first refined to analysis cells of about 1.5 mm so a trapped footprint is the shadow of the feature, not the whole modelling triangle. count, slideCount, lifterCount and unresolvedCount are the numbers the mold report reads. moldDraft on the same result classifies every face, including fillets, by signed draft against that pull. The angle is the geometric normal of each triangle, so a stamp on a curved face does not drop it. Positive draft means the face normal points along the pull (the inside walls of a tray, the flange top). Negative draft means it points against the pull (the outside walls of a tray, the bottom). A face drafted at exactly the threshold passes (0.01° tolerance), and a planar stamped face takes one angle for the whole face. At the default 1° threshold each face is positive, negative, or below. Classified area is the whole mesh. below keeps a positive or negative sign. A vertical wall is below and its sign stays positive. There is no zero-draft class. It does not edit CAD draft. Molding rules: guide { topic: \"molding\" }.",
2537
+ "description": "Read-only moldability fit for one part mesh, in the part local frame (the same frame as list_faces). Searches bounding-box axes, large planar normals, and an icosphere (about 80 directions, deduped within 5°, d and -d are one axis). The chosen pull has the least occluded undercut area. Scores within max(2% of the part area, 25 mm²) of that best are tied; box axes and large planar normals win the tie over an icosphere sample, and drafted area breaks the rest. Fit is still good (0 undercut regions), fixable (1 to 4), or not_a_fit (5 or more), plus undercutCount, undercutArea, draftedArea, pull, and pullSource. Pass pull [x, y, z] to score that axis instead and keep its sign. The same result includes wall: a local thickness per triangle, nominal (mode, or the median when no thickness dominates the interior band), max, min, mean, median, and thin and thick regions. Thickness below 0.6× nominal is thin and above 1.5× nominal is thick. Wall thickness follows the geometric normal of each triangle. A stamp only flips that side when it points the other way, so one stamp on a curved face does not steer every facet. A triangle whose own normal is within 0.5° of perpendicular to the pull is not an undercut, and an undercut needs another triangle covering that point. A geometric check for later molding slices, not a supplier DFM. parting on the same result classifies every face as core or cavity by complete visibility (core along +pull, cavity along -pull). A wall within 0.5° of vertical takes the role of the labelled neighbour it can reach. There is no zero-draft class. One outer parting loop is kept. Stamped edges keep their names. On the same result, sideActions lists each block: a slide, a lifter, or an unresolved undercut. A block is one piece of steel that forms a connected set of trapped faces and withdraws along one direction. Every trapped feature that shares a direction on one connected surface is one block, whatever the gap between the features, so two holes on one wall are one slide. Each block carries pull (its withdraw direction, never the main pull axis), area (the block face it forms, which includes untrapped surface inside its window), trappedArea, window, span along the main pull, features (the stamped blocks it carries) and frees (the stamped faces it forms). A slide withdraws in the parting plane. A lifter withdraws tilted 15° to 25° into the core, and only when that tilt leaves the part without entering material. An unresolved undercut has no straight direction that frees it (a slot whose ends narrow toward the outer face); it needs a modelling change or a special mechanism. count is every block, slides, lifters and unresolved undercuts, and is what the report prices. A wall within 0.5° of vertical is not a side action. Undercuts are first refined to analysis cells of about 1.5 mm so a trapped footprint is the shadow of the feature, not the whole modelling triangle. count, slideCount, lifterCount and unresolvedCount are the numbers the mold report reads. moldDraft on the same result classifies every face, including fillets, by signed draft against that pull. The angle is the geometric normal of each triangle, so a stamp on a curved face does not drop it. Positive draft means the face normal points along the pull (the inside walls of a tray, the flange top). Negative draft means it points against the pull (the outside walls of a tray, the bottom). A face drafted at exactly the threshold passes (0.01° tolerance), and a planar stamped face takes one angle for the whole face. At the default 1° threshold each face is positive, negative, or below. Classified area is the whole mesh. below keeps a positive or negative sign. A vertical wall is below and its sign stays positive. There is no zero-draft class. It does not edit CAD draft. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2538
2538
  "args": {
2539
2539
  "type": "object",
2540
2540
  "additionalProperties": false,
@@ -2577,9 +2577,45 @@
2577
2577
  ]
2578
2578
  }
2579
2579
  },
2580
+ {
2581
+ "name": "mold_status",
2582
+ "description": "The next heartbeat or the final result of a mold_* analysis that answered { status: \"running\", jobId }. It waits up to about 30 s for the analysis, then answers either the result the original call would have returned (plus jobId) or another heartbeat { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec?, message }. A heartbeat is not a result: it has no fit, wall, or report fields. Call it again until status is not running. The analysis keeps running in the tab between calls and is never restarted; keep the SurfCAD tab in the foreground. Read-only and immediate. unknown_job: no analysis with that id ran past the budget in this tab (a mold_* call answers its result directly when it finishes in time), or it finished more than 10 minutes ago.",
2583
+ "args": {
2584
+ "type": "object",
2585
+ "additionalProperties": false,
2586
+ "required": [
2587
+ "job_id"
2588
+ ],
2589
+ "properties": {
2590
+ "job_id": {
2591
+ "type": "string",
2592
+ "description": "jobId from a mold_* call that answered status running"
2593
+ }
2594
+ }
2595
+ },
2596
+ "result": {
2597
+ "type": "object",
2598
+ "additionalProperties": true
2599
+ },
2600
+ "errors": [
2601
+ "bad_args",
2602
+ "unknown_job",
2603
+ "no_mesh",
2604
+ "internal"
2605
+ ],
2606
+ "mutates": false,
2607
+ "destructive": false,
2608
+ "confirm": false,
2609
+ "group": "measure",
2610
+ "immediate": true,
2611
+ "uiEntry": null,
2612
+ "example": {
2613
+ "job_id": "mold-1-abc"
2614
+ }
2615
+ },
2580
2616
  {
2581
2617
  "name": "mold_pull",
2582
- "description": "Set the shared pull reference used by core/cavity (including side actions) and mold draft. mode auto searches icosphere and planar candidates, minimizing occluded undercut area and then maximizing drafted area. mode plane uses Top (+Z), Front (+Y), or Right (+X). mode face uses normal [x, y, z] in the part local frame and keeps its sign. Changing it recomputes those from the same pull. Read-only. It does not edit CAD draft. Molding rules: guide { topic: \"molding\" }.",
2618
+ "description": "Set the shared pull reference used by core/cavity (including side actions) and mold draft. mode auto searches icosphere and planar candidates, minimizing occluded undercut area and then maximizing drafted area. mode plane uses Top (+Z), Front (+Y), or Right (+X). mode face uses normal [x, y, z] in the part local frame and keeps its sign. Changing it recomputes those from the same pull. Read-only. It does not edit CAD draft. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2583
2619
  "args": {
2584
2620
  "type": "object",
2585
2621
  "additionalProperties": false,
@@ -2645,7 +2681,7 @@
2645
2681
  },
2646
2682
  {
2647
2683
  "name": "mold_wall_map",
2648
- "description": "Show or hide the wall-thickness heatmap on the active part, in the part local frame. on true paints each triangle with the viridis ramp from thin (0.6× nominal) through nominal to thick (1.5× nominal) and shows that legend. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Read-only. A geometric view of the mold-analysis wall field, not a stress plot and not a quote. Molding rules: guide { topic: \"molding\" }.",
2684
+ "description": "Show or hide the wall-thickness heatmap on the active part, in the part local frame. on true paints each triangle with the viridis ramp from thin (0.6× nominal) through nominal to thick (1.5× nominal) and shows that legend. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Read-only. A geometric view of the mold-analysis wall field, not a stress plot and not a quote. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2649
2685
  "args": {
2650
2686
  "type": "object",
2651
2687
  "additionalProperties": false,
@@ -2676,7 +2712,7 @@
2676
2712
  },
2677
2713
  {
2678
2714
  "name": "mold_parting",
2679
- "description": "Show or hide the core, cavity, and side-action colours on the active part, in the part local frame. on true classifies every face from the mold-analysis pull by complete visibility (core along +pull, cavity along -pull) and paints a true undercut as a side action. A wall within 0.5° of vertical is still core or cavity: it takes the role of the labelled neighbour it can reach, so an inner pocket wall joins the core and an outer wall joins the cavity. There is no separate zero-draft colour. The outer parting loop is a polyline. Stamped faces keep their edge names on that loop. sideActions lists each block: a slide, a lifter, or an unresolved undercut. A block is one piece of steel that forms a connected set of trapped faces and withdraws along one direction. Every trapped feature that shares a direction on one connected surface is one block, whatever the gap between the features, so two holes on one wall are one slide. Each block carries pull (its withdraw direction, never the main pull axis), area (the block face it forms, which includes untrapped surface inside its window), trappedArea, window, span along the main pull, features (the stamped blocks it carries) and frees (the stamped faces it forms). A slide withdraws in the parting plane. A lifter withdraws tilted 15° to 25° into the core, and only when that tilt leaves the part without entering material. An unresolved undercut has no straight direction that frees it (a slot whose ends narrow toward the outer face); it needs a modelling change or a special mechanism. count is every block, slides, lifters and unresolved undercuts, and is what the report prices. group highlights one block. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Read-only. Not a CAD draft edit and not a quote. Molding rules: guide { topic: \"molding\" }.",
2715
+ "description": "Show or hide the core, cavity, and side-action colours on the active part, in the part local frame. on true classifies every face from the mold-analysis pull by complete visibility (core along +pull, cavity along -pull) and paints a true undercut as a side action. A wall within 0.5° of vertical is still core or cavity: it takes the role of the labelled neighbour it can reach, so an inner pocket wall joins the core and an outer wall joins the cavity. There is no separate zero-draft colour. The outer parting loop is a polyline. Stamped faces keep their edge names on that loop. sideActions lists each block: a slide, a lifter, or an unresolved undercut. A block is one piece of steel that forms a connected set of trapped faces and withdraws along one direction. Every trapped feature that shares a direction on one connected surface is one block, whatever the gap between the features, so two holes on one wall are one slide. Each block carries pull (its withdraw direction, never the main pull axis), area (the block face it forms, which includes untrapped surface inside its window), trappedArea, window, span along the main pull, features (the stamped blocks it carries) and frees (the stamped faces it forms). A slide withdraws in the parting plane. A lifter withdraws tilted 15° to 25° into the core, and only when that tilt leaves the part without entering material. An unresolved undercut has no straight direction that frees it (a slot whose ends narrow toward the outer face); it needs a modelling change or a special mechanism. count is every block, slides, lifters and unresolved undercuts, and is what the report prices. group highlights one block. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Read-only. Not a CAD draft edit and not a quote. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2680
2716
  "args": {
2681
2717
  "type": "object",
2682
2718
  "additionalProperties": false,
@@ -2716,7 +2752,7 @@
2716
2752
  },
2717
2753
  {
2718
2754
  "name": "mold_side_actions",
2719
- "description": "Alias of mold_parting for side actions. on true, or omit on, opens the core and cavity colouring and returns the same block list and counts (slides, lifters, unresolved undercuts), each with its withdraw direction and face area. replacedBy is mold_parting. on false does not hide that colouring; the message names mold_parting { on: false }. A wall within 0.5° of vertical is not a side action. The withdraw direction is never the pull axis. group highlights one block. Read-only. Not mold CAD and not a quote. Molding rules: guide { topic: \"molding\" }.",
2755
+ "description": "Alias of mold_parting for side actions. on true, or omit on, opens the core and cavity colouring and returns the same block list and counts (slides, lifters, unresolved undercuts), each with its withdraw direction and face area. replacedBy is mold_parting. on false does not hide that colouring; the message names mold_parting { on: false }. A wall within 0.5° of vertical is not a side action. The withdraw direction is never the pull axis. group highlights one block. Read-only. Not mold CAD and not a quote. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2720
2756
  "args": {
2721
2757
  "type": "object",
2722
2758
  "additionalProperties": false,
@@ -2754,7 +2790,7 @@
2754
2790
  },
2755
2791
  {
2756
2792
  "name": "mold_draft",
2757
- "description": "Show or hide signed mold draft on the active part, in the part local frame. on true classifies every face, including fillets and blend faces, against the mold-analysis pull. The angle is the geometric normal of that triangle. A stamped face normal is one average and does not drop the face. Positive draft means the face normal points along the pull (the inside walls of a tray, the flange top). Negative draft means it points against the pull (the outside walls of a tray, the bottom); the sign is asin(n · pull), not which mould half forms the face. A planar stamped face takes one angle for the whole face, and a wall drafted at exactly the threshold passes (0.01° tolerance). threshold is degrees in (0, 90]; the pane offers 0.5, 1, 2, 3, and 5, and 1 is the default. A face at or above the threshold is positive when the sign is positive, and negative when the sign is negative. Tops and bottoms are classified with the same three classes. Classified area is the whole mesh. Absolute draft below the threshold is below, and that bucket still splits positive and negative so a locked-steel check can see the sign. A vertical wall is below and its sign stays positive. There is no zero-draft class. Positive at or above the threshold uses the cavity colour. Negative at or above the threshold uses the core colour. Below the threshold is a red hatch. The result reports positive, negative, and below, each with count and area. below.positive and below.negative are the sign split. violations is the below count. Changing threshold rebuckets the stored field and does not measure the mesh again. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Pass threshold without on to show at that threshold. Read-only. Not CAD draft mode, not an automatic draft fix, and not a quote. Molding rules: guide { topic: \"molding\" }.",
2793
+ "description": "Show or hide signed mold draft on the active part, in the part local frame. on true classifies every face, including fillets and blend faces, against the mold-analysis pull. The angle is the geometric normal of that triangle. A stamped face normal is one average and does not drop the face. Positive draft means the face normal points along the pull (the inside walls of a tray, the flange top). Negative draft means it points against the pull (the outside walls of a tray, the bottom); the sign is asin(n · pull), not which mould half forms the face. A planar stamped face takes one angle for the whole face, and a wall drafted at exactly the threshold passes (0.01° tolerance). threshold is degrees in (0, 90]; the pane offers 0.5, 1, 2, 3, and 5, and 1 is the default. A face at or above the threshold is positive when the sign is positive, and negative when the sign is negative. Tops and bottoms are classified with the same three classes. Classified area is the whole mesh. Absolute draft below the threshold is below, and that bucket still splits positive and negative so a locked-steel check can see the sign. A vertical wall is below and its sign stays positive. There is no zero-draft class. Positive at or above the threshold uses the cavity colour. Negative at or above the threshold uses the core colour. Below the threshold is a red hatch. The result reports positive, negative, and below, each with count and area. below.positive and below.negative are the sign split. violations is the below count. Changing threshold rebuckets the stored field and does not measure the mesh again. on false removes the skin so face paint and the part colour show again. Omit on to toggle. Pass threshold without on to show at that threshold. Read-only. Not CAD draft mode, not an automatic draft fix, and not a quote. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2758
2794
  "args": {
2759
2795
  "type": "object",
2760
2796
  "additionalProperties": false,
@@ -2794,7 +2830,7 @@
2794
2830
  },
2795
2831
  {
2796
2832
  "name": "mold_dfm",
2797
- "description": "Show or hide the mold report for the active part, in the part local frame. on true measures volume, projected area along the pull, and the side-action count, then returns part mass, press tonnage, tooling, and part price for grade and quantity. Mass is volume times the published resin density. Tooling is the published rate card: a base mold cost scaled by projected area, plus a per-side-action adder. Part price is material cost plus press time at the card machine rate plus tooling divided by quantity. assumptions lists the rates, sources, as-of dates, and formulas. A grade with no density or price, or a part with no wall or projected area, is flagged and not guessed. A priced catalog, when one is passed in, still prices from that catalog. The same function fills the pane and the spreadsheet. The resin default is PC/ABS. Press tonnage is the required tonnage of the measured projected area. The report says Mold report and Budgetary, not binding. It does not paint a skin. Opening it clears the other molding tools. on false closes the panel. Omit on to toggle. Read-only. Molding rules: guide { topic: \"molding\" }.",
2833
+ "description": "Show or hide the mold report for the active part, in the part local frame. on true measures volume, projected area along the pull, and the side-action count, then returns part mass, press tonnage, tooling, and part price for grade and quantity. Mass is volume times the published resin density. Tooling is the published rate card: a base mold cost scaled by projected area, plus a per-side-action adder. Part price is material cost plus press time at the card machine rate plus tooling divided by quantity. assumptions lists the rates, sources, as-of dates, and formulas. A grade with no density or price, or a part with no wall or projected area, is flagged and not guessed. A priced catalog, when one is passed in, still prices from that catalog. The same function fills the pane and the spreadsheet. The resin default is PC/ABS. Press tonnage is the required tonnage of the measured projected area. The report says Mold report and Budgetary, not binding. It does not paint a skin. Opening it clears the other molding tools. on false closes the panel. Omit on to toggle. Read-only. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2798
2834
  "args": {
2799
2835
  "type": "object",
2800
2836
  "additionalProperties": false,
@@ -2836,7 +2872,7 @@
2836
2872
  },
2837
2873
  {
2838
2874
  "name": "mold_quote",
2839
- "description": "Show or hide the mold report for the active part. This is the same report as mold_dfm, including part mass, the published tooling estimate, part price, and assumptions (rates, sources, as-of dates, and formulas). on true measures the mesh and returns volume, projected area, side-action count, and those estimates for grade, quantity, and cavityCount. Part price is material cost plus press time plus tooling divided by quantity. cavityCount stays in the costing call and does not scale the published rate card. It is not a control in the pane. A missing density, price, area, or wall is flagged and not guessed. A priced catalog, when one is passed in, still prices from that catalog. on false closes the panel. Omit on to toggle. It does not paint a skin and it does not place an order. Read-only. Molding rules: guide { topic: \"molding\" }.",
2875
+ "description": "Show or hide the mold report for the active part. This is the same report as mold_dfm, including part mass, the published tooling estimate, part price, and assumptions (rates, sources, as-of dates, and formulas). on true measures the mesh and returns volume, projected area, side-action count, and those estimates for grade, quantity, and cavityCount. Part price is material cost plus press time plus tooling divided by quantity. cavityCount stays in the costing call and does not scale the published rate card. It is not a control in the pane. A missing density, price, area, or wall is flagged and not guessed. A priced catalog, when one is passed in, still prices from that catalog. on false closes the panel. Omit on to toggle. It does not paint a skin and it does not place an order. Read-only. Molding rules: guide { topic: \"molding\" }. Long runs: an analysis still going after about 30 s answers { status: \"running\", stillRunning: true, jobId, command, phase?, percent?, elapsedSec, etaSec? } instead of the result. That is a heartbeat, not the result. Call mold_status { job_id } (it waits up to about 30 s each time) until it answers the result; the analysis keeps running in the tab and is not restarted.",
2840
2876
  "args": {
2841
2877
  "type": "object",
2842
2878
  "additionalProperties": false,
@@ -5564,7 +5600,7 @@
5564
5600
  },
5565
5601
  {
5566
5602
  "name": "insert_fillet_edges",
5567
- "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: shell first, then concave fillets, then convex fillets (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).",
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 fails 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).",
5568
5604
  "args": {
5569
5605
  "type": "object",
5570
5606
  "additionalProperties": false,
@@ -5857,7 +5893,7 @@
5857
5893
  },
5858
5894
  {
5859
5895
  "name": "insert_chamfer_edges",
5860
- "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. 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).",
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 fails 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).",
5861
5897
  "args": {
5862
5898
  "type": "object",
5863
5899
  "additionalProperties": false,
@@ -8856,7 +8892,7 @@
8856
8892
  },
8857
8893
  {
8858
8894
  "name": "insert_shell",
8859
- "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. Order: shell first, then concave fillets, then convex fillets (guide { topic: \"modeling\" }). Writes (defaults): part = hollow(part, 2.5, 'z'); Takes return: \"status\" | \"summary\" | \"full\" (MCP default \"status\": status.script is omitted; \"summary\" adds status.features; \"full\" echoes the script).",
8895
+ "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. Order (required): shell before any fillet or chamfer; blending every convex edge first leaves several bodies. openScope opens every face that faces that way (default \"z\"): when a post, boss or flange stands on such a face, open the other side (\"-z\") or use \"none\". status.bodyCount must be 1 straight after the shell (guide { topic: \"modeling\" }). Writes (defaults): part = hollow(part, 2.5, 'z'); Takes return: \"status\" | \"summary\" | \"full\" (MCP default \"status\": status.script is omitted; \"summary\" adds status.features; \"full\" echoes the script).",
8860
8896
  "args": {
8861
8897
  "type": "object",
8862
8898
  "additionalProperties": false,
package/data/helpers.json CHANGED
@@ -1103,7 +1103,7 @@
1103
1103
  }
1104
1104
  ],
1105
1105
  "description": "chamferEdges(part, edges, c) — equal-leg 45° chamfer c on a SET of straight convex edges. ",
1106
- "doc": "chamferEdges(part, edges, c) — equal-leg 45° chamfer c on a SET of straight\nconvex edges. Edges = objects from c4MeshData/convexEdges, or a plain\n[{va, vb, n0, n1}] array. n0/n1 (outward normals of the two adjacent faces\nat that edge) are REQUIRED for hand-built edges, but are AUTO-DERIVED from\nthe current mesh when the edge object carries {faces: [i0, i1]} (as all\nc4MeshData-based selectors do: convexEdges, edgesByOrientation,\nedgesByNormal, planarFaceAt-derived selections) — no more\n\"Cannot read properties of undefined (reading '0')\" when mixing selectors\nwith chamferEdges.\n\nConstruction (verified, C2 pilot + C4): per edge, cutter = hull of the two\nedge endpoints plus four corner points pulled c into each adjacent face\ninterior. c IS THE LEG LENGTH along each adjacent face (CAD \"C2\" = 2 mm\non both legs), NOT the perpendicular face offset — the perpendicular\noffset is derived from the face-to-face angle (offset = c·tan(θ/2), θ =\nangle between n0/n1; at a 90° corner they coincide, at a 120° hex-nut\ncorner C2 → 1.155 mm offset / 2 mm legs). CUTTERS ARE APPLIED SEQUENTIALLY (one difference per edge) and\neach intermediate result is checked: a single degenerate cutter (e.g. at\na triple-junction rib-base edge where the two \"adjacent faces\" are coplanar\nor the cutter self-intersects) must not be allowed to wedge the batch\nunion into a wasm out-of-bounds trap (observed: chamfering ALL convex\nedges of a ribbed plate — one subset crashes the kernel while the rest\nbuild fine). The first bad edge throws a named, actionable error instead.\nCost: n differences instead of 1 — fine for the edge counts these parts\nactually use (≤ ~30); the C8 timeout guard catches anything pathological.\nA chamfer that splits the solid into more bodies than it started with\nthrows. The pieces are not returned.",
1106
+ "doc": "chamferEdges(part, edges, c) — equal-leg 45° chamfer c on a SET of straight\nconvex edges. Edges = objects from c4MeshData/convexEdges, or a plain\n[{va, vb, n0, n1}] array. n0/n1 (outward normals of the two adjacent faces\nat that edge) are REQUIRED for hand-built edges, but are AUTO-DERIVED from\nthe current mesh when the edge object carries {faces: [i0, i1]} (as all\nc4MeshData-based selectors do: convexEdges, edgesByOrientation,\nedgesByNormal, planarFaceAt-derived selections) — no more\n\"Cannot read properties of undefined (reading '0')\" when mixing selectors\nwith chamferEdges.\n\nConstruction (verified, C2 pilot + C4): per edge, cutter = hull of the two\nedge endpoints plus four corner points pulled c into each adjacent face\ninterior. c IS THE LEG LENGTH along each adjacent face (CAD \"C2\" = 2 mm\non both legs), NOT the perpendicular face offset — the perpendicular\noffset is derived from the face-to-face angle (offset = c·tan(θ/2), θ =\nangle between n0/n1; at a 90° corner they coincide, at a 120° hex-nut\ncorner C2 → 1.155 mm offset / 2 mm legs). CUTTERS ARE APPLIED SEQUENTIALLY (one difference per edge) and\neach intermediate result is checked: a single degenerate cutter (e.g. at\na triple-junction rib-base edge where the two \"adjacent faces\" are coplanar\nor the cutter self-intersects) must not be allowed to wedge the batch\nunion into a wasm out-of-bounds trap (observed: chamfering ALL convex\nedges of a ribbed plate — one subset crashes the kernel while the rest\nbuild fine). The first bad edge throws a named, actionable error instead.\nCost: n differences instead of 1 — fine for the edge counts these parts\nactually use (≤ ~30); the C8 timeout guard catches anything pathological.\nA chamfer that splits the solid into more bodies than it started with\nthrows. The pieces are not returned. A component with no volume\n(`_SEAM_DUST_MM3`) is seam dust, not a body: it is dropped and not counted.",
1107
1107
  "examples": [
1108
1108
  "part = chamferEdges(part, convexEdges(part), 2);"
1109
1109
  ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "surfcad-mcp",
3
- "version": "0.3.6",
3
+ "version": "0.3.7",
4
4
  "description": "SurfCAD agent bridge MCP server (stdio) — pairs to a browser tab via the local WebSocket relay, or a saved remote login",
5
5
  "license": "Apache-2.0",
6
6
  "author": "artur0x0",
@@ -17,9 +17,9 @@ export const BUILD_FLOW_NOTE = ` Build in ribbon order: block out every part of
17
17
  /** The full guidance, served by the MCP `guide` tool's `start` topic. */
18
18
  export const BUILD_GUIDANCE = [
19
19
  'How to build in SurfCAD. Work in the order of the feature ribbon: Block, Build, Shape, Polish, Move.',
20
- '1. Block out first. Within seconds of the prompt, create every part of the assembly as plain blocks (create_assembly gives the first part as partId; rename_part it. create_part for every other part, then insert_cube, insert_rounded_box, insert_cylinder, insert_sphere, insert_tube, insert_hex_prism) at roughly the right size and position (block-out positions are rough; joints set final positions), and take a screenshot so the user can approve the layout and proportions before any detail goes in. Never plan silently for long before something appears in the viewport.',
20
+ '1. Block out first. Within seconds of the prompt, create every part of the assembly as plain blocks (the first part already exists: create_assembly returns it as partId, the same id as activeId, already active. Build on that id and rename_part it; never call create_part for the first part. create_part is for the second part onward. Then insert_cube, insert_rounded_box, insert_cylinder, insert_sphere, insert_tube, insert_hex_prism) at roughly the right size and position (block-out positions are rough; joints set final positions), and take a screenshot so the user can approve the layout and proportions before any detail goes in. Never plan silently for long before something appears in the viewport.',
21
21
  '2. Build. Shape each block into its real form with Build and Shape features: insert_hole, insert_boss, insert_cut, insert_boolean, insert_shell, insert_add_draft; insert_cross_section, insert_workplane, insert_make_extrude, insert_make_revolve, insert_make_sweep, insert_make_loft (sketch_* and slot_* for the profiles).',
22
- '3. Polish. insert_fillet_edges, insert_chamfer_edges, insert_move_face, insert_delete_face.',
22
+ '3. Polish. insert_fillet_edges, insert_chamfer_edges, insert_move_face, insert_delete_face. Blend order is required: after the shell, concave fillets and chamfers before convex ones, with the edges picked by name (guide { topic: "modeling" }).',
23
23
  `4. Pattern and place. insert_array3_d (grid), insert_polar_array (bolt circle), and insert_pattern_points (one copy at every hole center and axis from list_faces; Array Type=Points) for repeats and hardware, then insert_move, insert_rotate, insert_center, insert_align, insert_mirror for bodies inside one part. insert_polar_array drills the holes when boreRadius is greater than 0 and boltCircleRadius is the circle (it must be greater than 0); boreRadius 0 copies the body and boltCircleRadius 0 (the default) leaves it on the axis. A bolt circle of holes is that tool, not a FEATURE-GAP snippet. ${JOINT_PLACEMENT_GUIDANCE}`,
24
24
  'Finish each stage across the whole assembly before starting the next, and take a screenshot after each stage.',
25
25
  'Modeling rules: guide { topic: "modeling" }; molded parts: guide { topic: "molding" }, and run mold_fit before Polish.',
@@ -142,6 +142,7 @@ export const ERROR_HINTS = Object.freeze({
142
142
  confirm_required: { hint: 'Nothing changed: ask the user (details lists what the change touches), and only then retry with confirm: true.', guide: CONSENT_GUIDE },
143
143
  pending_save: { hint: 'The write is planned offline: ask the user to Save again when online; nothing more to do now.' },
144
144
  unknown_save: { hint: 'No save with that id is running or recent in this tab: a git_save that finished within its budget answered its result directly; call git_save { message } again if the save is still wanted.' },
145
+ unknown_job: { hint: 'No mold analysis with that id is running or recent in this tab: a mold_* call that finished within about 30 s answered its result directly, and a finished job is kept for 10 minutes. Call the mold_* tool again if the result is still wanted.' },
145
146
  unsupported_vault_version: { hint: 'This vault version is not supported. git_upgrade_vault on the current version reports that nothing needs upgrading. An older version runs only when an upgrade step is registered and confirm is true; with no step, nothing is opened or written.' },
146
147
  upgrade_unavailable: { hint: 'The vault cannot be upgraded from here (message says why): tell the user and stop.' },
147
148
  conflict: { hint: 'A remote edit overlaps this save: git_behind_resolve { action: "reload" | "branch", confirm: true } after the user chooses, or git_force_overwrite with confirm: true.' },
@@ -179,7 +180,7 @@ export const ERROR_HINTS = Object.freeze({
179
180
  pair_failed: { hint: 'Pairing failed (message): check the code (8 characters, from the open tab) and that the tab shows it, then pair again.', guide: PAIRING_GUIDE },
180
181
  pairing_lost: { hint: 'The tab or relay dropped and the server re-pairs on its own: retry in a few seconds; do not ask for a new code.', guide: PAIRING_GUIDE },
181
182
  bad_pairing_code: { hint: 'pair { code: "........" } with the 8-character code from SurfCAD → Local agent → Show pairing code.', guide: PAIRING_GUIDE },
182
- tab_asleep: { hint: 'Open SurfCAD in Chrome and keep that tab open, then retry this call. mold_* analyses may take up to 120 s; keep the tab in the foreground.' },
183
+ tab_asleep: { hint: 'Open SurfCAD in Chrome and keep that tab open, then retry this call. A long mold_* analysis does not hold the call: after about 30 s it answers { status: "running", jobId } and mold_status { job_id } returns the next heartbeat or the result. Keep the tab in the foreground.' },
183
184
  command_timeout: { hint: 'The tab is awake but this command ran past its budget (120 s for mold_*, 30 s otherwise). Retry once with the tab in the foreground; for mold_* pass pull to skip the direction search.' },
184
185
  too_many_pending: { hint: 'Wait for the SurfCAD tab to finish the commands already in flight, then retry.' },
185
186
  token_revoked: { hint: 'Run npx surfcad-mcp login and approve the new code in SurfCAD.' },
@@ -12,7 +12,18 @@
12
12
  * topic under 1,500 words.
13
13
  */
14
14
  import { BUILD_GUIDANCE, JOINT_PLACEMENT_GUIDANCE } from './buildGuidance.mjs';
15
- import { BUILDING_STATUS_GUIDANCE, CLOSING_REPLY_GUIDANCE, PROMPT_SERVER_INSTRUCTIONS } from './promptTools.mjs';
15
+ import {
16
+ BUILDING_STATUS_GUIDANCE,
17
+ CLOSING_REPLY_GUIDANCE,
18
+ LONG_POLL_GUIDANCE,
19
+ PROMPT_ONBOARDING_ASK,
20
+ PROMPT_SERVER_INSTRUCTIONS,
21
+ PROMPT_TURN_GUIDANCE,
22
+ READ_MESSAGES_MAX_WAIT_MS,
23
+ READ_MESSAGES_POLL_MS,
24
+ WEBHOOK_REQUIRED_GUIDANCE,
25
+ } from './promptTools.mjs';
26
+ import { agentPromptStallMinutes } from './promptStall.mjs';
16
27
  import {
17
28
  ERROR_TOPIC_CODES,
18
29
  ERROR_TOPIC_PREFIX,
@@ -32,16 +43,19 @@ export const INSTRUCTIONS_MAX_BYTES = 2048;
32
43
  const START = `${BUILD_GUIDANCE}
33
44
 
34
45
  Quick start, three calls after pair:
35
- 1. create_part { name: "Hub" } then insert_tube { outerRadius: 20, innerRadius: 14, height: 40 }. The part is active when create_part returns; its result carries the opaque partId. Numbers are mm.
46
+ 1. create_assembly { name: "Hub", part_name: "Hub" } then insert_tube { outerRadius: 20, innerRadius: 14, height: 40 }. create_assembly's result partId is the first part, already active: build on it and never call create_part for it (create_part { name } adds the second part onward, and its result carries that part's opaque partId). Numbers are mm.
36
47
  2. list_faces { filter: { kind: "planar", normalWithin: { n: [0, 0, 1], deg: 5 } } } → select_faces { keys: [<that row's key>] } → insert_tap_drill_hole { use_selection: true, size: "M5", u: 0, v: 0 } (or insert_hole). The pick is consumed by this one insert.
37
48
  3. paint_open {} → paint_set_color { color: "#2f6fdb" } → paint_part {} (or paint_faces { keys }) → paint_confirm {}.
38
49
  Then select_clear {} → camera_set { view: "iso" } → screenshot { save_to: true } and show the user.
39
50
 
40
51
  Reading results: every model-changing tool answers { ok, errors, status } with return "status" by default over MCP (no script echo; get_script reads it, get_script { range: { fromFeature, toFeature } } reads one span). status.runState is not_run_yet | ok | failed; errors rows are feature_failed with the viewport's text and a detail reason.
41
52
  Ids are opaque surf ids from parts, list_assemblies, create_part, create_assembly; never a path or a display name.
42
- Topics: guide { topic: "dialect" | "features" | "selection" | "paint" | "limits" | "camera" | "assembly" | "modeling" | "molding" }; list_helpers { names } documents any script helper.
53
+ Topics: guide { topic: "dialect" | "features" | "selection" | "paint" | "limits" | "camera" | "assembly" | "modeling" | "molding" | "chat" }; list_helpers { names } documents any script helper.
54
+ In-viewer chat is a required workflow, not a tip: read guide { topic: "chat" } after every pair and follow it for every prompt the user sends from the SurfCAD chat box (register_webhook after every pair, ack first, the ${READ_MESSAGES_POLL_MS / 1000} second read_messages long-poll while connected).
55
+
56
+ In-viewer prompt pane. ${CLOSING_REPLY_GUIDANCE} set_status is for progress and does not close the task. ${BUILDING_STATUS_GUIDANCE} Be interactive: post_progress while you work, especially during long reasoning. A fresh surfcad-mcp process per tool call is normal and stays present. A long-lived process is optional and nothing depends on it. Call close_session once when you are done. close_session is not sent on process exit. state "responding" (alias typing) is the bouncing dots after the user sends. Listing parts, faces, edges, or transforms, status, and read_messages never start building. Building stays until the closing reply. reply_to_user takes an in_reply_to that this session actually received; any other id is unknown_prompt and is not shown in the chat. Omit in_reply_to to post one plain-text message to this paired session when no prompt is waiting (not a prompt id, one per second). After read_messages acks a prompt, that id stays in the response's recent list (the last 50 prompts in this session, oldest first, each { id, state }), including on a later empty read_messages {} and on a remote session. An idle session that has not received a prompt has recent: [].
43
57
 
44
- In-viewer prompt pane. ${CLOSING_REPLY_GUIDANCE} set_status is for progress and does not close the task. ${BUILDING_STATUS_GUIDANCE} Be interactive: post_progress while you work, especially during long reasoning. A fresh surfcad-mcp process per tool call is normal and stays present. A long-lived process is optional and nothing depends on it. Call close_session once when you are done. close_session is not sent on process exit. state "responding" (alias typing) is the bouncing dots after the user sends. Listing parts, faces, edges, or transforms, status, and read_messages never start building. Building stays until the closing reply. reply_to_user takes an in_reply_to that this session actually received; any other id is unknown_prompt and is not shown in the chat. Omit in_reply_to to post one plain-text message to this paired session when no prompt is waiting (not a prompt id, one per second). After read_messages acks a prompt, that id stays in the response's recent list (the last 50 prompts in this session, oldest first, each { id, state }), including on a later empty read_messages {} and on a remote session. An idle session that has not received a prompt has recent: [].`;
58
+ ${PROMPT_TURN_GUIDANCE}`;
45
59
 
46
60
  const FEATURES = `Feature blocks. The script of a part is plain JavaScript over the SurfCAD helpers, and the feature strip reads it from marker comments. Every insert_* writes one block:
47
61
 
@@ -130,13 +144,24 @@ Saving. Working-copy tools never commit. git_save { message } is the one vault w
130
144
 
131
145
  const MODELING = `3D modeling guidelines. Follow these on every part; for a part that will be injection molded also read guide { topic: "molding" }.
132
146
 
133
- First part. create_assembly already made the first part and made it active; its result partId is that part. rename_part it and build on it. Do not call create_part for the first part; create_part is for the second part onward.
147
+ First part (rule). create_assembly already made the first part: an empty seed part, already active. Its result partId (the same id as activeId) is that part. Build the first part on that id: name it with create_assembly { part_name } or rename_part { part_id, name }, then insert_*. Do not call create_part for the first part; create_part is for the second part onward. After the first body the assembly has exactly one part (parts {} lists one row) and no empty "Part (1)" beside it.
134
148
 
135
- Order of operations.
149
+ Order of operations (required technique).
136
150
  - Block out with primitives, then Build and Shape, then Polish, then pattern and place (the ribbon order in guide { topic: "start" }).
137
- - Shell before fillets: insert_shell first, then fillet the concave (inside) edges, then the convex (outside) edges. Filleting every convex edge before the shell can leave the shell as several bodies; shell-first keeps one body and an even wall. Check status.bodyCount is 1 after each step.
138
- - Draft (insert_add_draft) goes before the shell, so the inside walls inherit it.
139
- - Keep edges that must stay sharp (a parting line, a rib base on a molded part) out of the fillet selection: select the faces whose edges you want with select_faces, then insert_fillet_edges { use_selection: true }.
151
+ - Polish order: draft (insert_add_draft, if any), then shell (insert_shell), then concave fillets and chamfers, then convex fillets and chamfers. Concave before convex holds for fillets and for chamfers alike. Blending every convex edge before the shell, or before the concave edges, is how a one-piece part turns into several bodies.
152
+ - Draft goes before the shell, so the inside walls inherit it.
153
+ - Shell opening. insert_shell opens every face that faces openScope (default "z", the +Z faces). When a post, boss or flange stands on a face that faces that way, the shell removes that face and cuts the feature loose (2 bodies). Open the other side (openScope: "-z") or use "none" for a closed hollow. status.bodyCount must be 1 straight after the shell, before any blend.
154
+ - Pick blend edges by name once the part has a shell or a concave blend. list_feature_edges names each edge by its two faces; "cylinder1.top~cylinder2.side" is the concave edge where a post meets its base. select_edges { names: [...] } then insert_fillet_edges or insert_chamfer_edges { use_selection: true }. A face pick (select_faces { names }, then use_selection: true) blends that one face's convex edges.
155
+ - The no-selection default (every convex edge) is for a plain block with no shell and no concave blend. After a shell or a concave blend it fails and the part stays as it was: the fillet answers feature_failed "filletEdges: edge is concave", the chamfer "chamferEdges: edge N split the solid into 2 bodies".
156
+ - A chamfer leg or fillet radius on a shelled part stays below the wall thickness, one named rim at a time. A rim-face pick takes the inner and the outer rim together, and a leg at or above the wall cuts through.
157
+ - Keep edges that must stay sharp (a parting line, a rib base on a molded part) out of the selection.
158
+ - Check status.bodyCount is 1 after the shell and after every blend. If it is not, undo that step and fix the order or the opening; do not union the pieces back together.
159
+
160
+ Playtest cases. Each failing sequence was reproduced in the app on 2026-11-06; reproduce it, then confirm the order above avoids it.
161
+ - A. Disc base with a vertical post, one body (insert_cylinder { radius: 30, height: 8 }, then insert_cylinder { radius: 8, height: 40, z: 4, combine: "add" }). Fails: insert_fillet_edges { radius: 2 } on every convex edge (with or without sphericalCorners), then insert_shell { wall: 1.5 }: bodyCount 2. Also fails: insert_shell with the default opening: 2 bodies, the post is cut off its base. Works: insert_shell { wall: 1.5, openScope: "-z" }: 1 body; the concave edge "cylinder1.top~cylinder2.side" by name, radius 2: 1 body; the convex edges by name, radius 1: 1 body.
162
+ - B. Post with a sphere tip (ring holder). Shell first, opening away from the tip; then the post-to-sphere concave edge by name; then the convex edges by name. The no-selection convex fillet after that concave fillet fails ("edge is concave").
163
+ - C. Flanged box (a box block plus a flange block, one body). Fails: insert_fillet_edges on every convex edge (sphericalCorners or not), then insert_shell { wall: 2 }: 9 or more bodies. Works: insert_shell first: 1 body when the opening does not face the flange's top face (2 when it does); then concave, then convex, by name.
164
+ - D. Shelled cup or tube, then a large chamfer over the rim face (top and inner rim as one pick). insert_chamfer_edges answers feature_failed "chamferEdges: edge N split the solid into 2 bodies" and the part stays as it was. Works: one named rim ("cylinder1.side~cylinder1.top") with a leg below the wall (0.8 on a 2 mm wall). Do not shell a tube: it is already hollow, and shelling it leaves the top face in pieces and the inner wall as unnamed facets.
140
165
 
141
166
  Reuse instead of rebuilding.
142
167
  - Repeated parts: one part, many instances. insert_part { part_id, instance: true } or a pattern, never a second copy rebuilt by hand. Hardware is one part per unique fastener type, patterned to every place it goes.
@@ -154,6 +179,42 @@ Assemblies and joints.
154
179
 
155
180
  Check your work. After each stage: status (runState ok, bodyCount 1 for a one-piece part), screenshot { save_to } from iso plus one useful view, and show the user.`;
156
181
 
182
+ /**
183
+ * The in-viewer chat workflow, as a requirement. One normative sequence
184
+ * shared by the tab (what the user sees at each step) and the agent (which
185
+ * tool causes it). The webhook step and the long-poll fallback are part of
186
+ * it: without one of them a per-call agent misses the next message.
187
+ */
188
+ const CHAT = `In-viewer chat: the required workflow. Everything here is a requirement, not a tip. Follow it after every pair and for every prompt the user sends from the SurfCAD chat box.
189
+
190
+ A. After every pair or login, before you wait for a prompt (required)
191
+ 1. ${WEBHOOK_REQUIRED_GUIDANCE} status.webhookRegistered is then true until this process exits.
192
+ 2. The URL and bearer are held in this process's memory only: never logged, never written to disk, never returned, never sent to the tab. Unpair, a new pair, and a new process all start with no webhook, so register again every time.
193
+ 3. No webhook URL yet: ask the user once, in these words: "${PROMPT_ONBOARDING_ASK}"
194
+ 4. The user declines, or your host cannot receive callbacks: the long-poll in section C is the required fallback. Never run with neither a webhook nor the poll.
195
+
196
+ B. Every prompt, in this order (required)
197
+ 1. The user's message appears in the chat box. It reaches you as a webhook POST or as a read_messages item with its id.
198
+ 2. Ack. Your first tool call after you receive the prompt is set_status { state: "responding", id: <prompt id> }. The chat shows the jumping dots. No modeling, no list_*, no screenshot, no other tool before this. set_status responding is the ack; there is no separate ack tool.
199
+ 3. Acknowledge in words, once: reply_to_user { in_reply_to: <id>, text: "Got it. Starting on <one-line plan>.", final: false }. Keep it short. Send it when work will follow.
200
+ 4. The tab keeps that reply on screen for about 10 seconds. That is the tab's timer. Do not sleep and do not wait for it.
201
+ 5. When you start geometry work: set_status { state: "building", id: <id> }, or post_progress. The chat folds and the spinner shows on the Bot control of the window that paired you. A building, post_progress, or model-changing call made during the 10 second hold takes effect when the hold ends. Do not call building for list_*, status, or read_messages.
202
+ 6. Do the work. Call post_progress occasionally while you are connected, especially during long reasoning.
203
+ 7. Close: reply_to_user { in_reply_to: <id>, text, final: true }. The spinner stops, the chat opens again with your confirmation, and you are idle. Say what changed. On failure or partial completion say what was done, what failed and why, and what is left.
204
+ 8. The user dismisses the chat and reviews the model. Go back to waiting (section C).
205
+ A question that needs no geometry: step 2, then the answer as the final reply (step 7). A cancel item { "type": "cancel", "id" } means the user pressed Stop: stop work on that id and send no reply and no set_status for it.
206
+
207
+ C. While connected: the ${READ_MESSAGES_POLL_MS / 1000} second long-poll (required)
208
+ 1. ${LONG_POLL_GUIDANCE}
209
+ 2. read_messages { wait_ms: ${READ_MESSAGES_POLL_MS} } answers as soon as a prompt or a cancel arrives, or with an empty list after ${READ_MESSAGES_POLL_MS / 1000} seconds. Call it again at once. If your host uses shorter waits, leave at most ${READ_MESSAGES_POLL_MS / 1000} seconds between polls. wait_ms may be up to ${READ_MESSAGES_MAX_WAIT_MS}.
210
+ 3. Keep the loop running after a final reply. The next message can arrive seconds later, and a second message sent within a minute of your final reply must reach you without a webhook.
211
+ 4. A registered webhook does not replace the loop: a failed POST puts the prompt in the queue for read_messages.
212
+ 5. An empty immediate read_messages {} does not mean the user never sent. status.queued can be above 0 while a fresh per-call process has not been offered the prompt yet. Use wait_ms.
213
+ 6. Polling is not activity. A poll keeps the session connected, and nothing more: it does not restart the "No activity from the agent for ${agentPromptStallMinutes()} min" stall window and it does not show the working state. Activity is set_status, a model-changing tool, post_progress, and reply_to_user. Do not poll to look busy; post_progress while you really work.
214
+
215
+ D. One window
216
+ The dots, the fold, the spinner, and your replies show only in the SurfCAD window that paired you (or, after the user sends a prompt from another window of the same account, that window). Your tool calls run in that window. Other windows of the account stay quiet.`;
217
+
157
218
  /**
158
219
  * Design guidelines for high pressure injection molding. The numbers that
159
220
  * have a code constant are pinned by test/moldingGuide.test.mjs against
@@ -197,7 +258,8 @@ What mold_fit checks.
197
258
  - Parting: core and cavity by visibility, with one outer parting loop.
198
259
  - sideActions: slides, lifters, and unresolved undercuts. Their count is what the report prices.
199
260
  - Ejector pin candidate spots: place ejectors on flat, thick, cored-out areas, not on cosmetic faces.
200
- - It is a geometric check, not a supplier DFM. It can run up to 120 s on a real part; keep the tab in the foreground.
261
+ - It is a geometric check, not a supplier DFM. It can run a minute or more on a real part; keep the tab in the foreground.
262
+ - Long runs answer a heartbeat. A mold_* analysis still going after about 30 s answers { status: "running", stillRunning: true, jobId, command, phase, percent, elapsedSec, etaSec } instead of the result. That is not the result and not a failure. Call mold_status { job_id }: it waits up to about 30 s and answers the next heartbeat or the final result. Repeat until status is no longer running. Do not call mold_fit again while a job is running; that starts a second analysis.
201
263
 
202
264
  Edges.
203
265
  - Avoid sharp edges. Fillet edges and corners everywhere except along the parting line, which must stay sharp so the mold halves shut off cleanly, and at the base of ribs, where the rib-to-wall junction must stay sharp to reduce sink. Do not fillet a rib base.
@@ -215,7 +277,7 @@ SurfCAD examples (from the flanged-box side-action playtests).
215
277
 
216
278
  /** Topic name → one-line summary and the text. Order is the listing order. */
217
279
  export const GUIDE_TOPICS = Object.freeze({
218
- start: { summary: 'How to build in SurfCAD (block, build, polish, place), a three-call example, how to read results, and the closing reply for an in-viewer prompt', text: START },
280
+ start: { summary: 'How to build in SurfCAD (block, build, polish, place), a three-call example, how to read results, and the closing reply for an in-viewer prompt (the required chat workflow is the chat topic)', text: START },
219
281
  dialect: { summary: DIALECT_SUMMARY, text: renderDialectTopic() },
220
282
  features: { summary: 'Marker blocks, feature ids, edit / delete / rollback / undo, script snippets, sketches', text: FEATURES },
221
283
  selection: { summary: 'Face and edge keys, list_faces filters, single-use picks, no_selection, fillet edge sets', text: SELECTION },
@@ -223,8 +285,9 @@ export const GUIDE_TOPICS = Object.freeze({
223
285
  limits: { summary: 'The 30 s kernel budget, what is slow, worker restarts and stale status, result sizes, pairing errors', text: LIMITS },
224
286
  camera: { summary: 'Which side each named view looks from, explicit poses, select_clear before a screenshot, screenshot to file', text: CAMERA },
225
287
  assembly: { summary: 'Documents, create_part placement, insert by reference, part instances, joint_create as the default assembly path, hardware, git_save', text: ASSEMBLY },
226
- modeling: { summary: '3D modeling guidelines: build on the create_assembly seed part, shell before fillets, draft before shell, reuse (instances, mirror, patterns) over rebuilding, joints, check bodyCount', text: MODELING },
288
+ modeling: { summary: '3D modeling guidelines: build on the create_assembly seed part (never create_part for the first part); required blend order draft, shell, concave, then convex fillets and chamfers, edges picked by name; the shell opening; shell-after-fillet playtest cases A to D; reuse (instances, mirror, patterns) over rebuilding, joints, check bodyCount', text: MODELING },
227
289
  molding: { summary: 'Injection molding design rules: draft 1° (0.5° vertical band), walls 1 to 6.35 mm with 0.6× / 1.5× thin and thick flags, ribs, ejector side, slides and lifters (15/20/25°), parting line and rib bases stay sharp, what mold_fit checks', text: MOLDING },
290
+ chat: { summary: 'REQUIRED in-viewer chat workflow: register_webhook after every pair, ack first (set_status responding), one short non-final reply, building / post_progress, final reply, and the 10 second read_messages long-poll while connected (polling is not activity)', text: CHAT },
228
291
  });
229
292
 
230
293
  /** The core topics, in listing order (the error topics are listed on one line after them). */
@@ -305,17 +368,14 @@ export const SERVER_INSTRUCTIONS = [
305
368
  PROMPT_SERVER_INSTRUCTIONS,
306
369
  '',
307
370
  `SurfCAD quick start. Pair, then call guide { topic: "start" } before the first model call; guide {} lists the topics (${GUIDE_TOPIC_NAMES.join(', ')}).`,
308
- 'Flow: 1 Block create_part then insert_cube / insert_cylinder / insert_tube, screenshot. 2 Build insert_hole, insert_cut, insert_shell, insert_make_extrude / revolve / sweep / loft. 3 Polish insert_fillet_edges, insert_chamfer_edges. 4 Place: fix one base part with a fixed joint, then joint_create. part_set_transform only for parts that touch nothing.',
309
- 'Rules that bite: helper names (cut, hole, shell, ...) are reserved, never redeclare them; set_script needs the active part\'s id (set_active_part first) and only rewrites a whole part, insert_code_snippet { gap, why, script } is the one-operation fallback; use_selection is single use: pick, insert once, pick again (nothing selected is no_selection).',
310
- 'Verify: select_clear → camera_set { view } → screenshot { save_to: true }. right puts the camera on +X, front on -Y, top on +Z.',
311
- 'Save only when the user asks: git_save { message } answers consent_pending until the user clicks Allow; retry the same call.',
312
- 'Small results: tools default to return: "status" (no script echo; get_script reads it), list_faces { filter, page }, list_commands { group }.',
371
+ 'Flow: first part = create_assembly\'s partId (create_part: later parts only); insert_cube / insert_cylinder / insert_tube, insert_hole, insert_cut, insert_shell, then blends, concave before convex. Place: fix one base part with a fixed joint, then joint_create. part_set_transform only for parts that touch nothing.',
372
+ 'Rules: use_selection is single use (nothing selected is no_selection). git_save { message } answers consent_pending until Allow. Tools default to return: "status". list_faces { filter, page }. list_commands { group }.',
313
373
  ].join('\n');
314
374
 
315
375
  export function guideToolDefinition() {
316
376
  return {
317
377
  name: GUIDE_TOOL_NAME,
318
- description: `SurfCAD agent guide, plain text. guide { topic } returns one topic; guide {} lists them. Read "start" before the first model call. Topics: ${GUIDE_TOPIC_NAMES.map((n) => `${n} (${GUIDE_TOPICS[n].summary})`).join('; ')}. Error recoveries: errors.<code> for the code an error payload carries (its see field names the topic), e.g. ${ERROR_GUIDE_TOPIC_NAMES.slice(0, 3).join(', ')}. The same texts are the ${GUIDE_RESOURCE_SCHEME}<topic> resources.`,
378
+ description: `SurfCAD agent guide, plain text. guide { topic } returns one topic; guide {} lists them. Read "start" before the first model call, and "chat" (the required in-viewer chat workflow) after every pair. Topics: ${GUIDE_TOPIC_NAMES.map((n) => `${n} (${GUIDE_TOPICS[n].summary})`).join('; ')}. Error recoveries: errors.<code> for the code an error payload carries (its see field names the topic), e.g. ${ERROR_GUIDE_TOPIC_NAMES.slice(0, 3).join(', ')}. The same texts are the ${GUIDE_RESOURCE_SCHEME}<topic> resources.`,
319
379
  inputSchema: {
320
380
  type: 'object',
321
381
  additionalProperties: false,
@@ -264,9 +264,10 @@ export function createPromptSession(options) {
264
264
  }
265
265
 
266
266
  /**
267
- * The agent did something that is not a state change (another tool call,
268
- * a read_messages poll). Restart the idle window and tell the tab, so its
269
- * own deadline restarts too. A stall notice is replaced by the live state.
267
+ * The agent did something that is not a state change (another bridge
268
+ * tool call, a partial reply). Restart the idle window and tell the tab,
269
+ * so its own deadline restarts too. A stall notice is replaced by the
270
+ * live state. A read_messages poll never comes here.
270
271
  */
271
272
  function noteActivity() {
272
273
  if (lastId && states.get(lastId) === 'cancelled') return;
@@ -666,7 +667,9 @@ export function createPromptSession(options) {
666
667
  ? { data: item.screenshot.data, mimeType: 'image/png' }
667
668
  : null);
668
669
  }
669
- noteActivity();
670
+ // A poll is not activity. read_messages (with or without wait_ms) must
671
+ // not restart the stall window or tell the tab the agent is active: an
672
+ // agent that only long-polls would otherwise never stall.
670
673
  noteTaken(takenIds);
671
674
  return { messages, images };
672
675
  }
@@ -828,10 +831,15 @@ export function createPromptSession(options) {
828
831
  throw Object.assign(new Error('text must be at most 500 characters'), { code: 'bad_args' });
829
832
  }
830
833
  const sent = emit({ type: PAIR_MSG.AGENT_PROGRESS, v: 1, working: true }, { required: true });
831
- const payload = { ok: true, working: true };
832
- if (sent && typeof sent.then === 'function') return sent.then(() => payload);
834
+ // Progress is the agent saying it is still at work: with a phase open
835
+ // it restarts the stall window, like a tool call or a partial reply.
836
+ const finish = () => {
837
+ noteActivity();
838
+ return { ok: true, working: true };
839
+ };
840
+ if (sent && typeof sent.then === 'function') return sent.then(finish);
833
841
  if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
834
- return payload;
842
+ return finish();
835
843
  }
836
844
 
837
845
  /**
@@ -2,8 +2,9 @@
2
2
  * No agent activity for this long is a stall, not a silent return to idle.
3
3
  * The in-viewer prompt and the MCP prompt session share this one window.
4
4
  * It applies to both typing (the pane is responding) and working (the
5
- * agent is building). Relayed tool calls, status, replies, and
6
- * read_messages start it over.
5
+ * agent is building). Relayed tool calls, status, post_progress, and
6
+ * replies start it over. A read_messages poll does not: an agent that only
7
+ * long-polls is waiting, not working.
7
8
  */
8
9
  export const AGENT_PROMPT_STALL_MS = 15 * 60 * 1000;
9
10
 
@@ -11,6 +11,29 @@ const USER_CONTENT = `${USER_CONTENT_NOTICE} Agent writes still go through the e
11
11
  /** read_messages { wait_ms } cap: long enough to skip idle polls, short enough for a host tool timeout. */
12
12
  export const READ_MESSAGES_MAX_WAIT_MS = 25_000;
13
13
 
14
+ /**
15
+ * The required long-poll cycle while connected: read_messages { wait_ms }
16
+ * with this value, called again as soon as it returns. Under the cap above,
17
+ * so a host with a short tool timeout can still run it.
18
+ */
19
+ export const READ_MESSAGES_POLL_MS = 10_000;
20
+
21
+ /** Where the whole required in-viewer chat workflow lives. */
22
+ export const CHAT_GUIDE_POINTER = 'guide { topic: "chat" }';
23
+
24
+ /**
25
+ * The required fallback (and safety net) while connected. Shared by the
26
+ * turn guidance, the chat topic, and the read_messages and
27
+ * register_webhook descriptions.
28
+ */
29
+ export const LONG_POLL_GUIDANCE = `While connected, long-poll read_messages { wait_ms: ${READ_MESSAGES_POLL_MS} } in a loop (call it again as soon as it returns): required whenever no webhook wakes you, and the safety net when one is registered. Polling is not activity: it does not restart the stall window or the tab's working state.`;
30
+
31
+ /**
32
+ * Webhook mode is a requirement, not a hint. The URL and bearer are process
33
+ * memory only, so every pair (and every fresh process) starts without one.
34
+ */
35
+ export const WEBHOOK_REQUIRED_GUIDANCE = 'Required when your host can receive HTTPS callbacks: call register_webhook right after every successful pair or login, before you wait for a prompt, and again in every new process (a fresh surfcad-mcp per tool call starts with no webhook). Keep the URL and bearer in your host config.';
36
+
14
37
  /**
15
38
  * Closing reply for a task that started in the in-viewer prompt pane.
16
39
  * The same sentence is the second sentence of the MCP initialize
@@ -31,11 +54,31 @@ export const BUILDING_STATUS_GUIDANCE = 'Call set_status { state: "building" } o
31
54
  */
32
55
  export const SESSION_PRESENCE_GUIDANCE = 'Be interactive: post_progress while working, especially during long reasoning. A fresh process per tool call is normal and stays present. A long-lived process is optional, never required. Call close_session when done, never on exit.';
33
56
 
57
+ /**
58
+ * Short form of the in-viewer turn, for the initialize instructions (hosts
59
+ * truncate past 2 KB). The full order is PROMPT_TURN_GUIDANCE.
60
+ */
61
+ export const PROMPT_TURN_BRIEF = `Required after every in-viewer prompt (full order: ${CHAT_GUIDE_POINTER}): ack first with set_status { state: "responding", id: <prompt id> } before any other tool (bouncing dots), then one short reply_to_user { in_reply_to, final: false }. The tab holds that reply for 10 seconds, then folds the chat and shows the working spinner. Required after every pair: register_webhook again (process memory only). No webhook: loop read_messages { wait_ms: ${READ_MESSAGES_POLL_MS} } while connected; polling is not activity. An empty immediate read does not mean the user never sent.`;
62
+
63
+ /**
64
+ * Required order after read_messages returns a prompt. set_status responding
65
+ * is the ack. There is no separate ack tool. The 10 second hold is the tab's
66
+ * timer, not the agent's.
67
+ */
68
+ export const PROMPT_TURN_GUIDANCE = `In-viewer prompt — required order after read_messages returns a user prompt:
69
+ 1. Ack immediately: set_status { state: "responding", id: <prompt id> }. That shows the bouncing dots. Do this before any other tool. set_status responding is the ack; there is no separate ack tool.
70
+ 2. Reply once, non-final: reply_to_user { in_reply_to: <id>, text: "Got it — starting on <one-line plan>.", final: false }. Keep that reply short. The tab holds that reply visible for 10 seconds.
71
+ 3. Only when you are about to create or edit geometry: set_status { state: "building", id }. After the 10 second hold the tab folds the chat and shows the working spinner (on a phone, the Bot button). A building, post_progress, or model-changing call during the hold waits until it ends. Do not call building for list, status, or read_messages.
72
+ 4. While modeling, call post_progress occasionally so the session stays present.
73
+ 5. When done or failed: reply_to_user { in_reply_to: <id>, text: <what changed, what failed, what remains>, final: true }. That stops the spinner, reopens the chat with the confirmation, and idles.
74
+ ${LONG_POLL_GUIDANCE} A per-call process catches prompts the server is holding the same way. register_webhook after every pair when your host can receive callbacks. An empty immediate read does not mean the user never sent.
75
+ This order, the webhook step after every pair, and the long-poll are required, not tips: ${CHAT_GUIDE_POINTER} is the whole workflow.`;
76
+
34
77
  /**
35
78
  * First paragraph of the MCP initialize `instructions`.
36
79
  * Goldens pin the webhook sentence as the prefix.
37
80
  */
38
- export const PROMPT_SERVER_INSTRUCTIONS = `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages. ${CLOSING_REPLY_GUIDANCE} ${BUILDING_STATUS_GUIDANCE} ${SESSION_PRESENCE_GUIDANCE}`;
81
+ export const PROMPT_SERVER_INSTRUCTIONS = `call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages. ${CLOSING_REPLY_GUIDANCE} ${BUILDING_STATUS_GUIDANCE} ${SESSION_PRESENCE_GUIDANCE} ${PROMPT_TURN_BRIEF}`;
39
82
 
40
83
  /** Exact wording the agent should relay when asking the user for a webhook. */
41
84
  export const PROMPT_ONBOARDING_ASK = 'To get SurfCAD messages instantly, send me your webhook URL and key. This only needs to be done once. Otherwise I\'ll check for SurfCAD messages between steps, so replies may lag.';
@@ -44,7 +87,7 @@ export const PROMPT_ONBOARDING_ASK = 'To get SurfCAD messages instantly, send me
44
87
  * Pair-result text when no webhook is registered. Generic: not tied to a bot product.
45
88
  * The URL and bearer are process memory only, so the agent must keep its own copy.
46
89
  */
47
- export const PROMPT_ONBOARDING_NOTE = `Ask the user for a webhook URL and key. The key is the bearer argument of register_webhook. This process holds the URL and bearer in memory only. Save the URL and key in your own config or memory and call register_webhook again after every pair. Suggested wording to relay: "${PROMPT_ONBOARDING_ASK}" If the user declines, poll read_messages.`;
90
+ export const PROMPT_ONBOARDING_NOTE = `Ask the user for a webhook URL and key. The key is the bearer argument of register_webhook. This process holds the URL and bearer in memory only. Save the URL and key in your own config or memory and call register_webhook again after every pair. Suggested wording to relay: "${PROMPT_ONBOARDING_ASK}" If the user declines, long-poll read_messages { wait_ms: ${READ_MESSAGES_POLL_MS} } in a loop while connected: that fallback is required, never neither (${CHAT_GUIDE_POINTER}).`;
48
91
 
49
92
  /** Pair-result text when a webhook is already registered. No onboarding note. */
50
93
  export const PROMPT_WEBHOOK_ACTIVE = 'Webhook is active.';
@@ -72,7 +115,7 @@ export function promptToolDefinitions() {
72
115
  return [
73
116
  {
74
117
  name: 'register_webhook',
75
- description: `Register an https webhook that receives user prompts from the paired SurfCAD tab. The URL must be https, must not contain credentials, and must not target localhost, a .local name, or a private, loopback, or link-local address. Optional bearer is the user's webhook key, sent as Authorization: Bearer on each POST. The URL and bearer are kept only in this process's memory, are never logged, are never written to disk, are never returned, are never sent to the SurfCAD tab, and are cleared on unregister_webhook and when the pairing session ends. Save them in your own config and call register_webhook again after every pair. When a webhook is registered, each prompt is POSTed as JSON { "type": "surfcad.prompt", ... } and times out after 10 seconds with one retry. If the POST fails, the prompt is queued instead. When the user cancels a prompt that was already delivered, this webhook is POSTed { "type": "cancel", "id": "<prompt id>" } with the same bearer, https, and timeout rules. Stop work on that id. Do not call reply_to_user or set_status for it. ${USER_CONTENT}`,
118
+ description: `Register an https webhook that receives user prompts from the paired SurfCAD tab. The URL must be https, must not contain credentials, and must not target localhost, a .local name, or a private, loopback, or link-local address. Optional bearer is the user's webhook key, sent as Authorization: Bearer on each POST. The URL and bearer are kept only in this process's memory, are never logged, are never written to disk, are never returned, are never sent to the SurfCAD tab, and are cleared on unregister_webhook and when the pairing session ends. ${WEBHOOK_REQUIRED_GUIDANCE} If the user declines a webhook, the required fallback is the long-poll, not silence. ${LONG_POLL_GUIDANCE} When a webhook is registered, each prompt is POSTed as JSON { "type": "surfcad.prompt", ... } and times out after 10 seconds with one retry. If the POST fails, the prompt is queued instead. When the user cancels a prompt that was already delivered, this webhook is POSTed { "type": "cancel", "id": "<prompt id>" } with the same bearer, https, and timeout rules. Stop work on that id. Do not call reply_to_user or set_status for it. ${USER_CONTENT}`,
76
119
  inputSchema: {
77
120
  type: 'object',
78
121
  additionalProperties: false,
@@ -102,7 +145,7 @@ export function promptToolDefinitions() {
102
145
  },
103
146
  {
104
147
  name: 'read_messages',
105
- description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. Every response includes recent: the last ${PROMPT_QUEUE_CAP} prompts this session received, oldest first, each { id, state } (queued, delivered, replied, or cancelled), held in memory only. A remote session returns that same recent list; an idle session that has not received a prompt has recent: []. acked is only the ids this call removed. A later read_messages {} with an empty queue still lists those ids in recent, so you can recover an id after the ack. status.last is only the newest id. ${USER_CONTENT} Do not render the text or the image as HTML. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE}`,
148
+ description: `Read queued user prompts, oldest first, and remove them from the in-memory queue (this acks them). Each prompt is plain text. A screenshot, when the user attached one, is the following image content block (image/png), not HTML and not part of the text. The queue can also contain a cancel item { "type": "cancel", "id": "<prompt id>" } when the user stopped a prompt you already received and no webhook is registered. Stop work on that id. Do not call reply_to_user or set_status for it. Every response includes recent: the last ${PROMPT_QUEUE_CAP} prompts this session received, oldest first, each { id, state } (queued, delivered, replied, or cancelled), held in memory only. A remote session returns that same recent list; an idle session that has not received a prompt has recent: []. acked is only the ids this call removed. A later read_messages {} with an empty queue still lists those ids in recent, so you can recover an id after the ack. status.last is only the newest id. ${USER_CONTENT} Do not render the text or the image as HTML. read_messages is a poll, not activity: with or without wait_ms it keeps the session connected but does not restart the stall window and does not change what the tab shows. When you finish the task from a prompt you received here, close that chat: ${CLOSING_REPLY_GUIDANCE} ${PROMPT_TURN_GUIDANCE}`,
106
149
  inputSchema: {
107
150
  type: 'object',
108
151
  additionalProperties: false,
@@ -117,7 +160,7 @@ export function promptToolDefinitions() {
117
160
  type: 'integer',
118
161
  minimum: 0,
119
162
  maximum: READ_MESSAGES_MAX_WAIT_MS,
120
- description: `Long-poll: when the queue is empty, wait up to this many milliseconds (at most ${READ_MESSAGES_MAX_WAIT_MS}) for a prompt or cancel to arrive before answering, instead of returning an empty list at once. Cuts idle polling between steps; omit or 0 to return immediately.`,
163
+ description: `Long-poll: when the queue is empty, wait up to this many milliseconds (at most ${READ_MESSAGES_MAX_WAIT_MS}) for a prompt or cancel to arrive before answering, instead of returning an empty list at once. The required cycle while connected is ${READ_MESSAGES_POLL_MS}, called again as soon as it returns (or register_webhook, with this loop as the safety net). An empty immediate read does not mean the user never sent. Omit or 0 to return immediately.`,
121
164
  },
122
165
  },
123
166
  },
@@ -147,7 +190,7 @@ export function promptToolDefinitions() {
147
190
  },
148
191
  {
149
192
  name: 'set_status',
150
- description: `Tell the SurfCAD tab which phase the user's prompt is in. responding (alias typing): you are reading or writing an answer; the chat stays open with bouncing dots. building (alias working): you are creating or editing geometry; the chat collapses and the field shows "Agent is working...". ${BUILDING_STATUS_GUIDANCE} Do not call building to list parts, faces, edges, or transforms, or for status or read_messages. A model-changing tool also enters building if you skip this call. A read never does. set_status is for progress and does not close the task. A partial reply does not leave building; the final reply, Stop, or a disconnect does. No activity for ${agentPromptStallMinutes()} minutes, while responding or building, shows the stall notice and leaves Stop up. The result state is the tab value (responding and typing are typing; building and working are working). Without id it targets the latest prompt. With no prompt at all (a build you started yourself, or a prompt an earlier one-shot process read) the tab still shows the state: it keeps a session-level state fed by this call, by every model-changing tool you call, and by post_progress, and it returns to idle 60 s after the last of those. A cancelled id returns { ok: false, error: cancelled }. ${CLOSING_REPLY_GUIDANCE}`,
193
+ description: `Tell the SurfCAD tab which phase the user's prompt is in. responding (alias typing) is the ack: call set_status { state: "responding", id } first after read_messages returns a prompt, before any other tool. The chat stays open with bouncing dots. Then one short non-final reply_to_user. The tab holds that reply for 10 seconds. building (alias working): you are creating or editing geometry. A building call, post_progress, or model-changing tool during that hold waits, then the chat folds and the field shows "Agent is working..." (on a phone, the Bot button spins). ${BUILDING_STATUS_GUIDANCE} Do not call building to list parts, faces, edges, or transforms, or for status or read_messages. A model-changing tool also enters building if you skip this call. A read never does. set_status is for progress and does not close the task. A partial reply does not leave building; the final reply, Stop, or a disconnect does. reply_to_user { final: true } stops the spinner, reopens the chat, and idles. No activity for ${agentPromptStallMinutes()} minutes, while responding or building, shows the stall notice and leaves Stop up. set_status, a model-changing tool, post_progress, and reply_to_user are activity; a read_messages poll is not. The result state is the tab value (responding and typing are typing; building and working are working). Without id it targets the latest prompt. With no prompt at all (a build you started yourself, or a prompt an earlier one-shot process read) the tab still shows the state: it keeps a session-level state fed by this call, by every model-changing tool you call, and by post_progress, and it returns to idle 60 s after the last of those. A cancelled id returns { ok: false, error: cancelled }. ${CLOSING_REPLY_GUIDANCE}`,
151
194
  inputSchema: {
152
195
  type: 'object',
153
196
  additionalProperties: false,
@@ -175,7 +218,7 @@ export function promptToolDefinitions() {
175
218
  },
176
219
  {
177
220
  name: 'post_progress',
178
- description: 'Tell SurfCAD you are working, without showing thinking text. Call it while you work, especially during long reasoning, so the phone folds the chat and the bot button spins. Optional text is accepted and discarded; it is never shown. This also keeps the session present. It does not close the task.',
221
+ description: 'Tell SurfCAD you are working, without showing thinking text. Call it while you work, especially during long reasoning, so the chat folds and the spinner shows (on a phone, the Bot button). A non-final ack reply stays visible for 10 seconds first; a post_progress during that hold waits until it ends. Optional text is accepted and discarded; it is never shown. This also keeps the session present. It does not close the task.',
179
222
  inputSchema: {
180
223
  type: 'object',
181
224
  additionalProperties: false,
package/src/server.mjs CHANGED
@@ -50,8 +50,15 @@ import { tabAdvertisesTool } from './unlistedTools.mjs';
50
50
 
51
51
  const PAIR_TOOL_NAME = 'pair';
52
52
 
53
- /** One line in the pair result; the guidance itself is guide { topic: "start" }. */
54
- const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "start" } (how to build in SurfCAD: block out first, features first, hardware as patterned parts); guide {} lists every topic.';
53
+ /** One line in the pair result; the guidance itself is guide { topic: "start" } and guide { topic: "chat" }. */
54
+ const PAIR_GUIDE_POINTER = 'Before the first model call read guide { topic: "start" } (how to build in SurfCAD: block out first, features first, hardware as patterned parts). guide { topic: "chat" } is the required in-viewer chat workflow: register_webhook after every pair, ack first, and the 10 second read_messages long-poll while connected. guide {} lists every topic.';
55
+
56
+ /**
57
+ * Prompt tools that do not count as agent activity when called. set_status,
58
+ * post_progress, and close_session send their own frame; read_messages is a
59
+ * poll and must not restart the stall window.
60
+ */
61
+ const PROMPT_TOOLS_WITHOUT_ACTIVITY = new Set(['set_status', 'post_progress', 'close_session', 'read_messages']);
55
62
 
56
63
  const STATUS_PROMPT_NOTE = ' This process also adds webhookRegistered (true when a prompt webhook is registered; the URL and any bearer are 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).';
57
64
 
@@ -257,7 +264,10 @@ export async function createSurfcadMcpServer(options = {}) {
257
264
  }
258
265
 
259
266
  if (isPromptTool(name)) {
260
- if (name !== 'set_status' && name !== 'post_progress' && name !== 'close_session') session.noteAgentToolCall();
267
+ // set_status, post_progress, and replies drive the tab state themselves.
268
+ // read_messages is a poll: it is not agent activity, so it must not
269
+ // restart the stall window (a long-poll loop would otherwise hide a stall).
270
+ if (!PROMPT_TOOLS_WITHOUT_ACTIVITY.has(name)) session.noteAgentToolCall();
261
271
  try {
262
272
  const out = await callPromptTool(session.prompts, name, args);
263
273
  if (out.isError) return errorResult(out.error, name);