surfcad-mcp 0.3.9 → 0.4.1

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.
Files changed (44) hide show
  1. package/README.md +71 -50
  2. package/bin/surfcad-mcp.js +16 -8
  3. package/data/commands.json +6481 -5817
  4. package/data/helpers.json +243 -268
  5. package/package.json +10 -2
  6. package/src/cli.mjs +296 -23
  7. package/src/cliCall.mjs +221 -0
  8. package/src/errors.mjs +8 -5
  9. package/src/helpers.mjs +7 -5
  10. package/src/importFile.mjs +186 -0
  11. package/src/listen/bootstrap.mjs +87 -34
  12. package/src/listen/claudeCodeWake.mjs +74 -0
  13. package/src/listen/daemon.mjs +35 -0
  14. package/src/listen/listenCli.mjs +121 -30
  15. package/src/listen/listener.mjs +138 -8
  16. package/src/listen/owner.mjs +293 -0
  17. package/src/listen/waitCli.mjs +133 -0
  18. package/src/listen/wake.mjs +39 -19
  19. package/src/listen/wakeSetupText.mjs +23 -5
  20. package/src/pairWait.mjs +3 -3
  21. package/src/pairingCode.mjs +10 -0
  22. package/src/prompt/buildGuidance.mjs +9 -7
  23. package/src/prompt/chatFlow.mjs +15 -0
  24. package/src/prompt/errorHints.mjs +24 -10
  25. package/src/prompt/guide.mjs +27 -14
  26. package/src/prompt/promptSession.mjs +74 -10
  27. package/src/prompt/promptTools.mjs +10 -6
  28. package/src/prompt/replyConfirm.mjs +69 -0
  29. package/src/relayMessages.mjs +43 -1
  30. package/src/remote/config.mjs +17 -13
  31. package/src/remote/session.mjs +103 -5
  32. package/src/room/roomRuntime.mjs +186 -0
  33. package/src/room/roomServer.mjs +112 -0
  34. package/src/room/roomToolSchemas.mjs +228 -0
  35. package/src/room/seat.mjs +334 -0
  36. package/src/screenshotFile.mjs +9 -0
  37. package/src/server.mjs +155 -111
  38. package/src/stepUploadLimit.mjs +8 -0
  39. package/src/bridge/bridgePage.mjs +0 -132
  40. package/src/bridge/bridgePopup.mjs +0 -288
  41. package/src/bridge/relayHub.mjs +0 -556
  42. package/src/bridge/relayServer.mjs +0 -291
  43. package/src/nodeClient.mjs +0 -63
  44. package/src/relay.mjs +0 -419
package/README.md CHANGED
@@ -1,43 +1,25 @@
1
1
  # surfcad-mcp
2
2
 
3
- Stdio [Model Context Protocol](https://modelcontextprotocol.io/) server for the SurfCAD browser agent bridge. Each tool maps to one `window.surfcad` command from the shipped command catalog (`data/commands.json`). The server pairs to your open SurfCAD tab through the **M1** loopback WebSocket relay (`ws://127.0.0.1:17341` by default). A saved login uses the server relay instead; the tool list does not change.
3
+ Stdio [Model Context Protocol](https://modelcontextprotocol.io/) server for the SurfCAD browser agent bridge. Each tool maps to one `window.surfcad` command from the shipped command catalog (`data/commands.json`). The server pairs to an open SurfCAD tab through a saved server login (`npx surfcad-mcp login --code`). The loopback relay was removed in 0.4.0.
4
4
 
5
5
  ## Install and run
6
6
 
7
7
  ```bash
8
+ npx -y surfcad-mcp@latest login --code ABCD-EFGH
8
9
  npx surfcad-mcp
9
10
  ```
10
11
 
11
- The process speaks MCP over **stdio** and **starts the local relay** on `127.0.0.1:17341` (loopback only). If another process is already listening there (a second MCP client or the SurfCAD dev server), it reuses that relay instead of failing.
12
-
13
- Pair it to a running SurfCAD tab (see below), then your MCP client can call bridge tools (`status`, `set_script`, `run`, …) plus a `pair` helper.
12
+ The process speaks MCP over **stdio** and uses the saved login. With no saved login it exits and tells you to run `npx surfcad-mcp login`. After it is connected, call `pair {}` (no code). The hyphen in the join code is optional.
14
13
 
15
14
  Environment variables:
16
15
 
17
16
  | Variable | Purpose |
18
17
  | --- | --- |
19
- | `SURFCAD_PAIRING_CODE` | 8-character code from the SurfCAD **Connect Agent** dialog (optional if you use the `pair` tool). When set, the local relay stays selected even if a remote login is saved. |
20
- | `SURFCAD_AGENT_BRIDGE_WS_URL` | Loopback relay URL (default `ws://127.0.0.1:17341`). When set, the local relay stays selected even if a remote login is saved. |
21
- | `SURFCAD_AGENT_BRIDGE_WS_PORT` | Loopback relay port. When set, the local relay stays selected even if a remote login is saved. |
22
- | `SURFCAD_MCP_START_RELAY` | Set to `0` to skip starting the local relay (tests only). |
23
- | `SURFCAD_AGENT_SERVER` | Origin for remote login and the remote client (default `https://surfcad.com`). Dev and staging only. `--server` wins. |
18
+ | `SURFCAD_AGENT_SERVER` | Origin for login and the client (default `https://surfcad.com`). Dev and staging only. `--server` wins. |
24
19
  | `SURFCAD_AGENT_NAME` | Agent name when `--name` is omitted. The MCP client name is used after that, when the stdio server is connected. |
25
- | `SURFCAD_MCP_TRANSPORT` | `local` or `remote`. Same as `--local` / `--remote`. |
26
- | `SURFCAD_MCP_CONFIG_DIR` | Directory for the saved remote token. Default `$XDG_CONFIG_HOME/surfcad-mcp` or `~/.config/surfcad-mcp`. |
27
-
28
- ## Which relay
29
-
30
- The local loopback relay is the default. `npx surfcad-mcp` starts it and pairs with the 8-character code.
31
-
32
- A saved login selects the server relay at `https://surfcad.com/agent`. `--remote` selects it too, and exits with a message to run `login` when no token is saved.
20
+ | `SURFCAD_MCP_CONFIG_DIR` | Directory for the saved token. Default `$XDG_CONFIG_HOME/surfcad-mcp` or `~/.config/surfcad-mcp`. |
33
21
 
34
- These keep the local relay even when a login is saved, so an existing local MCP config and the in-repo goldens stay on the loopback relay:
35
-
36
- - `--local` or `SURFCAD_MCP_TRANSPORT=local`
37
- - `SURFCAD_AGENT_BRIDGE_WS_URL` or `SURFCAD_AGENT_BRIDGE_WS_PORT`
38
- - a non-empty `SURFCAD_PAIRING_CODE`
39
-
40
- `--remote` and `SURFCAD_MCP_TRANSPORT=remote` win over that list.
22
+ These are errors in 0.4.0 (the local relay is gone): `--local`, `SURFCAD_MCP_TRANSPORT=local`, `SURFCAD_AGENT_BRIDGE_WS_URL`, `SURFCAD_AGENT_BRIDGE_WS_PORT`, and a non-empty `SURFCAD_PAIRING_CODE`. `--remote` is accepted and does the same thing as the default.
41
23
 
42
24
  ## Remote login
43
25
 
@@ -49,7 +31,7 @@ npx surfcad-mcp status
49
31
  npx surfcad-mcp logout
50
32
  ```
51
33
 
52
- On Safari, iOS, or a phone-width page, SurfCAD shows a join code. `login --code ABCD-EFGH` redeems it, writes the token the same way device-code login does, and does not print the token. Add `--server` for a dev or staging origin. Cleartext `http://` is still only allowed for localhost, 127.0.0.1, and ::1. Desktop Chrome and the local bridge keep the device-code flow below.
34
+ Connect Agent shows a join code on every browser. `login --code ABCD-EFGH` redeems it, writes the token the same way device-code login does, and does not print the token. Add `--server` for a dev or staging origin. Cleartext `http://` is still only allowed for localhost, 127.0.0.1, and ::1. `login` without `--code` is the device-code flow below.
53
35
 
54
36
  `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
37
 
@@ -70,22 +52,31 @@ Clear failures:
70
52
  | Too many commands already waiting | `Too many commands are waiting` |
71
53
  | This package is older than the server | `please update surfcad-mcp` |
72
54
 
55
+ ## One-shot calls
56
+
57
+ Agents without an MCP connector call one tool and exit. The saved login is the session. The token is not printed.
58
+
59
+ ```bash
60
+ npx surfcad-mcp tools
61
+ npx surfcad-mcp tools read_messages
62
+ npx surfcad-mcp call read_messages '{"wait_ms":10000}'
63
+ npx surfcad-mcp call reply_to_user '{"in_reply_to":"<id>","text":"Done.","final":true}'
64
+ npx surfcad-mcp call list_edges '{}'
65
+ ```
66
+
67
+ `tools` prints `[{ name, description }]`. `tools NAME` prints that tool's argument schema. `call` prints one JSON result on stdout and exits non-zero on error (the error is JSON on stdout too, with `code` and `message`). Omit the JSON argument to call with `{}`. A large result is printed in full: `list_edges` on a detailed part is over 8 MB, and the relay accepts frames up to 32 MB. `guide` and `list_helpers` do not need a paired tab. Every other tool uses the saved login.
68
+
73
69
  ## Pair with SurfCAD
74
70
 
75
71
  1. Open [https://surfcad.com](https://surfcad.com) (or local dev).
76
- 2. Open the **profile** chip and choose **Connect Agent**. When the relay is found, an eight-character pairing code appears. Leave the tab open.
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
- 4. Click **Allow** (the green check) in SurfCAD when prompted.
72
+ 2. Open the **profile** chip and choose **Connect Agent**. The join code appears as two groups of four (`ABCD-EFGH`), with the install command. Leave the tab open.
73
+ 3. Run `npx -y surfcad-mcp@latest login --code ABCD-EFGH` (the hyphen is optional), then call the MCP **`pair`** tool with `{}`.
79
74
 
80
75
  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
76
 
82
77
  A successful `pair` returns a note as text content (a `type: "text"` block, not only `structuredContent` or `_meta`) that says whether the agent can be reached while it is idle: `Idle wake: ready …`, `Idle wake: set … but the listener is not running`, or `Idle wake: unavailable on this host`. The same state is `wake.coldWake` in the result and in `status`. The note never tells the agent to ask the user for a webhook URL; that was the pair note before, and agents relayed it to the user on every pair. With no wake the note tells the pairing session to greet the user itself. See [Wake](#wake-messaging-an-idle-agent).
83
78
 
84
- Nothing pairs without your approval.
85
-
86
- ### Safari
87
-
88
- Safari on a Mac blocks https pages from opening `ws://127.0.0.1` directly. In Safari, **Connect Agent** also opens a small window titled **SurfCAD local agent bridge**, served by this relay at `http://127.0.0.1:17341/bridge`. It carries the connection between the tab and the relay; keep it open while the agent works. If it closes, the Connect Agent dialog shows **Disconnected** with a **Reconnect** button, and you allow the agent again. The bridge window only talks to SurfCAD pages (https://surfcad.com, www, and local dev). If Safari blocks the window, allow pop-ups for surfcad.com and click **Reconnect**. Safari on iPhone and iPad is not supported.
79
+ The card closes when the login is redeemed.
89
80
 
90
81
  ## MCP client config (Cursor / Claude Desktop)
91
82
 
@@ -95,9 +86,7 @@ Safari on a Mac blocks https pages from opening `ws://127.0.0.1` directly. In Sa
95
86
  "surfcad": {
96
87
  "command": "npx",
97
88
  "args": ["-y", "surfcad-mcp"],
98
- "env": {
99
- "SURFCAD_PAIRING_CODE": "BCDFGHJK"
100
- }
89
+ "env": {}
101
90
  }
102
91
  }
103
92
  }
@@ -115,11 +104,11 @@ claude mcp add surfcad -- npx surfcad-mcp
115
104
 
116
105
  ## How to build
117
106
 
118
- `guide { topic: "start" }` carries the build guidance in full (the `pair` result and the initialize instructions point at it; `guide {}` lists the other topics: `features`, `selection`, `paint`, `limits`, `camera`, `assembly`), and the `insert_*` / `set_script` / `create_*` tool descriptions carry a one-line note of it: block out every part of the assembly as plain blocks first (within seconds, then a screenshot for the user), then Build and Shape, then Polish, then pattern and place; features first, with a `set_script` snippet only for one operation no feature can do, starting with `// FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>`; 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. The full text is in [docs/agent/SKILL.md](../../docs/agent/SKILL.md).
107
+ `guide { topic: "start" }` carries the build guidance in full (the `pair` result and the initialize instructions point at it; `guide {}` lists the other topics: `features`, `selection`, `paint`, `limits`, `camera`, `assembly`), and the `insert_*` / `set_script` / `create_*` tool descriptions carry a one-line note of it: block out every part of the assembly as plain blocks first (within seconds, then a screenshot for the user), then Shape, then Join, then Polish, then pattern and place; features first, with a `set_script` snippet only for one operation no feature can do, starting with `// FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>`; 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. Read and edit a placed part with get_part_placement and set_part_placement. A whole-part Move, Rotate, Center, or Align of a part in an assembly writes the Placement chip and adds no feature. One body of a multi-body part, and any part that is not in an assembly, still inserts an editable feature chip. Block-out positions are rough; joints set final positions. The full text is in [docs/agent/SKILL.md](../../docs/agent/SKILL.md).
119
108
 
120
109
  ## Tools
121
110
 
122
- Every command in `data/commands.json` is one MCP tool with the same name and argument schema, plus `pair`, `guide` (plain-text agent guidance by topic, no pairing needed; `dialect` is every script helper by signature; `errors.<code>` topics carry the recovery for an error code), `list_helpers` (the helper registry as JSON: `{ names?, group?, match?, page? }`, full doc and examples with `names`), and seven in-process prompt tools (`post_progress`, `close_session`, and the five prompt tools). Every `insert_*` description ends with the code its block carries at default arguments. The guide topics are also MCP resources (`surfcad://guide/<topic>`, versioned with this package). Every error payload carries `hint` (the next call to make) and, where a topic exists, `see`. `GET /tools` on the loopback relay and that file list the bridge tools. `list_commands` returns those plus every other tool this server registers (`pair`, `guide`, `list_helpers`, and the prompt tools, including `reply_to_user` and `set_status`), in the `agent` group. Prefer `insert_*` feature tools. `set_script` is the freehand fallback and requires `part_id`.
111
+ Every command in `data/commands.json` is one MCP tool with the same name and argument schema, plus `pair`, `guide` (plain-text agent guidance by topic, no pairing needed; `dialect` is every script helper by signature; `errors.<code>` topics carry the recovery for an error code), `list_helpers` (the helper registry as JSON: `{ names?, group?, match?, page? }`, full doc and examples with `names`), and seven in-process prompt tools (`post_progress`, `close_session`, and the five prompt tools). Every `insert_*` description ends with the code its block carries at default arguments. The guide topics are also MCP resources (`surfcad://guide/<topic>`, versioned with this package). Every error payload carries `hint` (the next call to make) and, where a topic exists, `see`. That file lists the bridge tools. `list_commands` returns those plus every other tool this server registers (`pair`, `guide`, `list_helpers`, and the prompt tools, including `reply_to_user` and `set_status`), in the `agent` group. Prefer `insert_*` feature tools. `set_script` is the freehand fallback and requires `part_id`.
123
112
 
124
113
  Parts and assemblies are opaque surf ids. A vault path or display name is `unknown_part` / `unknown_assembly`. Nothing reaches git without an explicit `git_save` (or another `git_*` write below).
125
114
 
@@ -155,6 +144,13 @@ Results are compact JSON. Every tool whose result carries `status` (the model-ch
155
144
  | `git_behind_resolve` | `{ action, confirm: true }` | `reload` is Get latest (no git write). `branch` is Create a new branch (a save-time git write). No path argument. |
156
145
  | `git_force_overwrite` | `{ confirm: true }` | Overwrite the overlapping remote files. |
157
146
 
147
+ Card flows that place features by tapped centres (the full argument tables are in `docs/agent-export.md` of the app repo):
148
+
149
+ | Flow | Calls | Notes |
150
+ | --- | --- | --- |
151
+ | Hole | `hole_open` → `hole_set_params { type, size, fit, dia, through, depth, side }` → `hole_begin_centres` → `plane_set` / `workplane_select` → `sketch_accept_plane` → `sketch_add` / `pick_points` → `hole_commit` | `side` is `1` (In: into the part along −normal) or `-1` (Out), the words the card shows. One `holesOnContour` block naming a centres contour. |
152
+ | Boss | `boss_open` → `boss_set_params { face, size, wall, height, hole, through, holeDepth, fit }` → `boss_begin_centres` → `sketch_add` / `pick_points` → `boss_commit` | `face` is a stamped face name from `list_faces` (`"cube1.top"`); a `pick_faces` session fills the same Face tab. The centres sketch opens on that face with no plane card. `wall` is the thickness around the hole (omitted: the default boss of 2.5 × the screw); the script carries the resulting `dia`, and `dia` is also accepted and converted to a wall. `hole` is `tap` (default), `clearance` or `none`; `through: true` runs the bore on through the part; `holeDepth` is from the boss top. One `bossesOnContour` block; `open_feature` + `edit_feature` + `confirm_feature` edit it. |
153
+
158
154
  ### Geometry engine crashes
159
155
 
160
156
  A part can kill the geometry engine (out of memory, a wasm abort, or a run past its 30 s budget). The tab replaces the worker on its own and other parts keep building; nothing hangs and nobody reloads. The tool that ran the part returns `ok: false` with `crash { code: "geometry_worker_crashed", reason, workerRestarted: true }` and one `failures` row with the same code; `status.runState` is `failed`, `errors` holds the row, and `parts` rows carry `runState` and `crash` for every part. Do not retry the same script: simplify the part, lower segment counts, or split it up, then run it again.
@@ -167,17 +163,17 @@ These five tools stay inside the local `surfcad-mcp` process. They are not SurfC
167
163
  | --- | --- | --- |
168
164
  | `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
165
  | `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. `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
- | `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. |
166
+ | `read_messages` | `{ max?, wait_ms? }` | Return queued prompts, oldest first, and remove them. An image the user attached (a screenshot of the model or a photo) is the next MCP image content block (`image/png`), not part of the text. A message can carry up to four images: they follow it as consecutive image blocks, and the message says `image_count` when there is more than one. 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`. |
167
+ | `reply_to_user` | `{ text, in_reply_to?, final? }` | Plain-text reply for a prompt id in this paired chat. The id may come from `read_messages` in this process or another (a wake run, or `surfcad-mcp call`). 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. `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 does not exist, or that belongs to someone else, 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
168
  | `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
169
 
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`.
170
+ A paired SurfCAD tab sends `agent.prompt` (`v: 1`, id, plain text up to 8000 characters, optional `context`, optional PNG `screenshot`, optional `extra_images` (up to three more PNGs of the same message)). 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
171
 
176
172
  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
173
 
178
174
  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
175
 
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.
176
+ `reply_to_user` accepts an `in_reply_to` that belongs to this paired chat: queued, delivered by webhook or `read_messages`, already replied, or read by a different session (a wake run or `surfcad-mcp call`). An id that does not exist, or that belongs to someone else, 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.
181
177
 
182
178
  Stop in the prompt card sends `agent.prompt.cancel` (`v: 1`, the current prompt id) over the same paired connection. Each prompt is `queued`, `delivered` (webhook POST succeeded, or `read_messages` returned it), `replied` (a final reply), or `cancelled`. A prompt that is still queued is removed and is not returned by `read_messages`. A prompt that was already delivered is marked `cancelled`. If a webhook is registered, the process POSTs `{ "type": "cancel", "id" }` with the same bearer, https, and timeout rules; if that POST fails, or no webhook is registered, the next `read_messages` returns `{ "type": "cancel", "id" }`. Stop work on that id. `reply_to_user` and `set_status` for a cancelled id return `{ "ok": false, "error": "cancelled" }` and nothing is sent to the tab. The tab clears its working state. Cancelling a prompt that already has a final reply returns `already_final`. An unknown id returns `not_found`.
183
179
 
@@ -200,15 +196,17 @@ Then, at every pair and login, with nothing pasted by the user:
200
196
 
201
197
  1. The wake is saved for the listener (`wake.json`, 0600).
202
198
  2. The listener is started (server relay; needs a saved login).
203
- 3. The wake is fired once per login with `reason: "greet"`, and the session it starts says "Hi, what can I help you design?" in the SurfCAD chat. The user seeing that greeting is the check that the whole path works.
199
+ 3. The wake is fired once per login with `reason: "test"`. The session it starts calls `status` once and ends; the user sees nothing. A session starting from it is the check that the whole path works. The check is marked done before it fires, so it never repeats for a login whatever the outcome.
200
+
201
+ The greeting is SurfCAD's: the tab shows "Hi, what can I help you design?" itself the moment the pairing lands, and every text this package gives an agent says not to send one. (Until 0.3.9 the check was a `greet` wake whose session said hello, and a slow or failed POST was not marked done, so every message's fresh session greeted again.) A POST that times out is not sent again, since the host may already be running the turn.
204
202
 
205
- With no wake, nothing is pretended. `wake.coldWake` is `"unavailable"`, the pair note says messages reach the agent only while it is in a turn and polling, and the pairing session greets the user itself. `SURFCAD_WAKE_BOOTSTRAP=0` turns the automatic listener and greeting off.
203
+ With no wake, nothing is pretended. `wake.coldWake` is `"unavailable"`, the pair note says messages reach the agent only while it is in a turn and polling, and the pairing session tells the user once, in the chat, that the one-time setup is still needed. `SURFCAD_WAKE_BOOTSTRAP=0` turns the automatic listener and test wake off.
206
204
 
207
205
  `wake.coldWake` is one of:
208
206
 
209
207
  | Value | Meaning |
210
208
  | --- | --- |
211
- | `ready` | A wake is set and something will fire it: the listener (server relay) or this MCP process (local relay) |
209
+ | `ready` | A wake is set and the listener will fire it |
212
210
  | `listener_stopped` | A wake is set, the listener is not running and could not be started. `npx surfcad-mcp listen --detach` |
213
211
  | `unavailable` | No wake, or the wake did not fire. In-turn polling is the only delivery |
214
212
 
@@ -234,10 +232,12 @@ The wake JSON:
234
232
 
235
233
  ```json
236
234
  { "type": "surfcad.wake", "v": 1, "reason": "prompt",
237
- "instruction": "A SurfCAD user sent you a chat message. On the surfcad MCP server call read_messages { wait_ms: 10000 }, then follow guide { topic: \"chat\" }: set_status responding first, then reply_to_user.",
235
+ "instruction": "<the chat flow: read_messages, set_status responding, a short ack if the work will take a while, the work, a final reply_to_user. Do not login or pair.>",
238
236
  "prompts": [{ "id": "…", "text": "make the boss taller", "ts": "…", "hasScreenshot": true }] }
239
237
  ```
240
238
 
239
+ `instruction` is the standard chat flow, the same one `guide { topic: "chat" }` section E spells out. A fresh session follows it and does not carry its own copy: call `read_messages { wait_ms: 10000 }` (the message and any screenshot), immediately `set_status { state: "responding", id }` (the jumping dots) before other work, send a short `reply_to_user` with `final: false` when the work will take a while, do the work, and finish with `reply_to_user` `final: true` that says what was done. Do not run `login` or `pair` from that session. If a call says the token is invalid (`token_revoked` or `expired`), do not pair again: a fresh pairing code is needed. SurfCAD still greets the user itself when the pairing lands; the instruction says not to send a greeting. A `reason: "test"` wake calls `status` once and ends.
240
+
241
241
  The text is a preview. The message itself stays on the server until an agent process reads it with `read_messages`, so a wake never consumes a message. A screenshot is not in the wake; `read_messages` returns it.
242
242
 
243
243
  How it works:
@@ -245,8 +245,8 @@ How it works:
245
245
  - `npx surfcad-mcp listen` long-polls the server relay (`GET /agent/prompts`) with the saved login. Outbound HTTPS only: no open port, it works behind NAT, and it works when the user is on a phone, because neither side has to reach the other.
246
246
  - A message is not woken for at once. An agent that is already polling takes it within seconds. After 4 seconds the listener asks the server whether the message is still unread, and only then fires the wake. A message still unread two minutes after a wake is woken for once more.
247
247
  - An agent in a turn is not woken. Every MCP tool call stamps a small file (`awake` in the config directory), and for 60 seconds after the last one the agent counts as in a turn: it reads the message at its next `read_messages`, and a wake on top of that would start a second turn beside the first. The message is looked at again every 15 seconds until the agent reads it or goes idle.
248
- - A long-lived `surfcad-mcp` MCP process fires the same wake itself for a message that sits unread in its queue. That covers the local relay, which has no login. When a listener is running on the server relay, the listener owns the wake.
249
- - `npx surfcad-mcp status` prints the saved wake and whether the listener is running. The MCP `status` tool returns `wake: { coldWake, forms, source, listenerRunning, note }` (`source` is `env` or `saved`) and `host: { name, version }` (what the MCP client calls itself), and every `pair` result carries the note. A `status` call also starts the listener again when it has stopped.
248
+ - A long-lived `surfcad-mcp` MCP process fires the same wake itself for a message that sits unread in its queue. When a listener is running, the listener owns the wake.
249
+ - `npx surfcad-mcp status` prints the saved wake and whether the listener is running on this login. The MCP `status` tool returns `wake: { coldWake, forms, source, listenerRunning, note }` (`source` is `env` or `saved`) and `host: { name, version }` (what the MCP client calls itself), and every `pair` result carries the note. A `status` call also starts the listener again when it has stopped, and restarts one that is still running on an older login. The CLI says `not on this login` when the process in the pid file was started with a different one.
250
250
  - A new session has no memory of earlier ones. The wake's `instruction` says so and points it at the message in `prompts`, `status` for the open part, and `guide { topic: "start" }`.
251
251
  - `npx surfcad-mcp wake show | test | clear`, `npx surfcad-mcp listen --stop`. The listener logs to `listener.log` in the config directory. Start it again after a reboot, or add `npx surfcad-mcp listen` to the host's startup (a systemd user unit, launchd, pm2).
252
252
 
@@ -254,6 +254,23 @@ What is saved: `wake.json` next to the saved login, mode 0600. It is written onl
254
254
 
255
255
  `register_webhook` is still there for a host with a public HTTPS endpoint. It lives in one MCP process's memory, so it cannot wake an agent whose host starts a fresh process per tool call. The wake can.
256
256
 
257
+ ## A seat in a room, with no browser
258
+
259
+ An agent on a machine with no browser (a cloud VM) can ask for its own seat in a SurfCAD multi-player room. It needs no SurfCAD login.
260
+
261
+ ```bash
262
+ npx surfcad-mcp room join --room "https://surfcad.com/?room=owner%2Frepo%3Amain%3Aasm-1" --name "Claude Code · housing" --machine cloud-vm-2
263
+ ```
264
+
265
+ - `--room` is the room link the room's host copies from SurfCAD, or the room key (`owner/name:branch:assemblyId`). The link names the room. It gives no access by itself.
266
+ - The command prints a short code and waits. The host sees a request with the agent's name, the machine label and the same code, and approves or denies it. Nothing is pasted into a chat or a file.
267
+ - On approval the seat token is saved in the config dir as `room-seat.json` (mode 0600). It is never printed. It is for that one room, lasts 24 hours and is renewed while the agent is connected. The host can remove the agent at any time, which ends the token.
268
+ - `--name` (or `SURFCAD_AGENT_NAME`) is what the room shows on the agent's chip. `--machine` is a label the host sees; the host name is used when it is left out. No address is sent as a label.
269
+ - `npx surfcad-mcp room status` shows the saved seat. `npx surfcad-mcp room forget` deletes it from this machine.
270
+ - One config dir holds one seat. Two agents on one machine each set their own `SURFCAD_MCP_CONFIG_DIR`.
271
+
272
+ This command only gets the seat. Editing a room from a machine with no browser is not in this package yet.
273
+
257
274
  ## Safety and consent
258
275
 
259
276
  - **Commerce:** Agents cannot place orders or drive checkout. Quote/cart/checkout controls are not exposed as MCP tools.
@@ -268,7 +285,11 @@ If the SurfCAD tab or the relay goes away mid-session, tool calls return `pairin
268
285
 
269
286
  ## Disconnect
270
287
 
271
- When the user chooses **Disconnect** in SurfCAD (server relay), the server revokes the login of the agent that last worked in that window. From then on every call with that token answers `token_revoked`. The MCP server deletes the saved login and unregisters any webhook the first time it sees that, and `surfcad-mcp listen` stops and deletes it too, so nothing retries with a dead token and `npx surfcad-mcp status` says `not logged in`. Nothing reconnects by itself: the user pairs again and you run `npx surfcad-mcp login`. The saved wake setup is kept, so a new login only needs `npx surfcad-mcp listen --detach`.
288
+ When the user chooses **Disconnect** in SurfCAD (server relay), the server revokes the account's agent login. An account has one agent at a time: when the user pairs another agent, the older login is revoked the same way. From then on every call with that token answers `token_revoked`.
289
+
290
+ If that token is still the one saved on this machine, the MCP server deletes it and unregisters any webhook the first time it sees the rejection, and `surfcad-mcp listen` stops too. Nothing retries with a dead token, and `npx surfcad-mcp status` says `not logged in`. Nothing reconnects by itself: the user pairs again and you run `npx surfcad-mcp login`. The saved wake setup is kept.
291
+
292
+ A new login replaces the token in the saved file. `login` and `pair` restart a listener that is still running, so it is not left on the revoked token. A listener that is rejected reads the saved login once and keeps going when a newer token is already there; the same token still stops it. `npx surfcad-mcp status` then reports the listener that is actually running on this login.
272
293
 
273
294
  A reload, a sleeping tab or a dropped connection is not a Disconnect and revokes nothing.
274
295
 
@@ -284,7 +305,7 @@ The [`surfcad-mcp`](https://www.npmjs.com/package/surfcad-mcp) package is publis
284
305
 
285
306
  Ways to release a new version:
286
307
 
287
- 1. **Version bump on `main`** — In a PR, bump `version` in `packages/surfcad-mcp/package.json`. After merge, when the **CI** workflow completes successfully on `main` and that version is not on npm yet, publish runs automatically. (It asks npm, not the parent commit: CI cancels an in-progress main run when the next commit lands, so the bump commit's own CI may never finish; the next green run publishes instead.)
308
+ 1. **Version bump on `main`** — In a PR, bump `version` in `packages/surfcad-mcp/package.json`. After merge, a change to that file on `main` starts the publish workflow. It publishes only when that version is not on npm yet, after the package tests and `smoke:pack` pass.
288
309
  2. **Git tag** — Push a tag `surfcad-mcp-vX.Y.Z` that exactly matches the `version` field at that commit (for example `surfcad-mcp-v0.2.1` for `"version": "0.2.1"`).
289
310
  3. **Manual** — In GitHub → Actions → **Publish surfcad-mcp** → **Run workflow** on branch `main`.
290
311
 
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { runCli } from '../src/cli.mjs';
3
+ import { runRoomMcpServer } from '../src/room/roomServer.mjs';
3
4
  import { runSurfcadMcpServer } from '../src/server.mjs';
4
5
 
5
6
  /**
@@ -13,9 +14,10 @@ function flushed(stream) {
13
14
  resolve();
14
15
  return;
15
16
  }
16
- // A full pipe with no reader must not hang login. 50 ms is enough for
17
- // a live stderr to take the error and the usage text.
18
- const timer = setTimeout(resolve, 50);
17
+ // A full pipe with no reader must not hang the process. A live stream
18
+ // finishes in the write callback. `call` can print a multi-megabyte
19
+ // list_edges result, so the safety cap is long enough for that flush.
20
+ const timer = setTimeout(resolve, 60_000);
19
21
  stream.write('', () => {
20
22
  clearTimeout(timer);
21
23
  resolve();
@@ -29,11 +31,17 @@ try {
29
31
  await Promise.all([flushed(process.stdout), flushed(process.stderr)]);
30
32
  process.exit(outcome.code);
31
33
  }
32
- await runSurfcadMcpServer({
33
- mode: outcome.mode,
34
- server: outcome.server,
35
- name: outcome.name,
36
- });
34
+ if (outcome.action === 'serve_room') {
35
+ await runRoomMcpServer({
36
+ server: outcome.server,
37
+ });
38
+ } else {
39
+ await runSurfcadMcpServer({
40
+ mode: outcome.mode,
41
+ server: outcome.server,
42
+ name: outcome.name,
43
+ });
44
+ }
37
45
  } catch (err) {
38
46
  console.error(err?.stack || err?.message || err);
39
47
  process.exit(1);