surfcad-mcp 0.3.1 → 0.3.3

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.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Command protocol shared by the localhost agent relay and the server relay.
3
+ *
4
+ * This is the frame around one bridge call. It is not `window.surfcad.version`
5
+ * (the in-page envelope) and not the `v` on prompt messages. Pairing and
6
+ * prompt frames stay on their own `type` names in `relayMessages.mjs`.
7
+ *
8
+ * A frame we write always carries `v`. A frame we read may omit `v`; that
9
+ * means version 1, so a peer from before this field still works on the
10
+ * localhost relay. Any other `v` is not this protocol.
11
+ *
12
+ * The server relay's handshake is stricter: `checkAgentHandshakeVersion`
13
+ * requires an explicit `v`. A missing or older `v` is too old for that
14
+ * handshake. Local reads are unchanged.
15
+ */
16
+
17
+ export const AGENT_PROTOCOL_VERSION = 1;
18
+
19
+ /**
20
+ * @typedef {{ v: number, id: string | number, command: string, args: unknown }} CommandRequest
21
+ * @typedef {{
22
+ * v: number,
23
+ * id: string | number,
24
+ * ok: true,
25
+ * result: unknown,
26
+ * } | {
27
+ * v: number,
28
+ * id: string | number,
29
+ * ok: false,
30
+ * error?: unknown,
31
+ * }} CommandResponse
32
+ */
33
+
34
+ /**
35
+ * @param {unknown} msg
36
+ * @returns {boolean}
37
+ */
38
+ export function isSupportedProtocolVersion(msg) {
39
+ if (!msg || typeof msg !== 'object') return false;
40
+ const version = /** @type {{ v?: unknown }} */ (msg).v;
41
+ return version == null || version === AGENT_PROTOCOL_VERSION;
42
+ }
43
+
44
+ /**
45
+ * @param {{ id?: string | number, command: string, args?: unknown }} fields
46
+ * @returns {CommandRequest}
47
+ */
48
+ export function commandRequest(fields) {
49
+ return {
50
+ v: AGENT_PROTOCOL_VERSION,
51
+ id: fields.id,
52
+ command: fields.command,
53
+ args: fields.args == null ? {} : fields.args,
54
+ };
55
+ }
56
+
57
+ /**
58
+ * @param {{ id?: string | number, ok: boolean, result?: unknown, error?: unknown }} fields
59
+ * @returns {CommandResponse}
60
+ */
61
+ export function commandResponse(fields) {
62
+ if (fields.ok === true) {
63
+ return { v: AGENT_PROTOCOL_VERSION, id: fields.id, ok: true, result: fields.result };
64
+ }
65
+ const frame = { v: AGENT_PROTOCOL_VERSION, id: fields.id, ok: false };
66
+ if (fields.error !== undefined) frame.error = fields.error;
67
+ return frame;
68
+ }
69
+
70
+ /**
71
+ * A command request: a string `command`, not a `pair` control frame, at a
72
+ * supported protocol version. Args that are not an object become `{}`.
73
+ * @param {unknown} msg
74
+ * @returns {CommandRequest | null}
75
+ */
76
+ export function readCommandRequest(msg) {
77
+ if (!isSupportedProtocolVersion(msg)) return null;
78
+ const frame = /** @type {{ type?: unknown, command?: unknown, id?: string | number, args?: unknown, v?: unknown }} */ (msg);
79
+ if (frame.type === 'pair') return null;
80
+ if (typeof frame.command !== 'string') return null;
81
+ return {
82
+ v: frame.v == null ? AGENT_PROTOCOL_VERSION : /** @type {number} */ (frame.v),
83
+ id: frame.id,
84
+ command: frame.command,
85
+ args: frame.args && typeof frame.args === 'object' ? frame.args : {},
86
+ };
87
+ }
88
+
89
+ /**
90
+ * A command response: an own `ok` field, not a `pair` control frame, at a
91
+ * supported protocol version. `ok` other than `true` is a failure.
92
+ * @param {unknown} msg
93
+ * @returns {CommandResponse | null}
94
+ */
95
+ export function readCommandResponse(msg) {
96
+ if (!isSupportedProtocolVersion(msg)) return null;
97
+ const frame = /** @type {{ type?: unknown, ok?: unknown, id?: string | number, result?: unknown, error?: unknown, v?: unknown }} */ (msg);
98
+ if (frame.type === 'pair') return null;
99
+ if (!Object.prototype.hasOwnProperty.call(frame, 'ok')) return null;
100
+ const version = frame.v == null ? AGENT_PROTOCOL_VERSION : /** @type {number} */ (frame.v);
101
+ if (frame.ok === true) {
102
+ return { v: version, id: frame.id, ok: true, result: frame.result };
103
+ }
104
+ const failure = { v: version, id: frame.id, ok: false };
105
+ if (frame.error !== undefined) failure.error = frame.error;
106
+ return failure;
107
+ }
108
+
109
+ /** Shown when a server-relay client speaks a protocol older than this one. */
110
+ export const AGENT_HANDSHAKE_UPDATE_MESSAGE = 'please update surfcad-mcp';
111
+
112
+ /**
113
+ * Server handshake version. Unlike `readCommandRequest`, a missing `v` is
114
+ * too old. `v` above {@link AGENT_PROTOCOL_VERSION} is a different protocol.
115
+ * @param {unknown} version
116
+ * @returns {{ ok: true, v: number } | { ok: false, error: string }}
117
+ */
118
+ export function checkAgentHandshakeVersion(version) {
119
+ if (typeof version !== 'number' || !Number.isFinite(version) || version < AGENT_PROTOCOL_VERSION) {
120
+ return { ok: false, error: AGENT_HANDSHAKE_UPDATE_MESSAGE };
121
+ }
122
+ if (version !== AGENT_PROTOCOL_VERSION) {
123
+ return { ok: false, error: `Unsupported protocol version: ${version}` };
124
+ }
125
+ return { ok: true, v: version };
126
+ }
package/src/errors.mjs CHANGED
@@ -1,5 +1,9 @@
1
+ import { AGENT_HANDSHAKE_UPDATE_MESSAGE } from './commandProtocol.mjs';
2
+
1
3
  export const RECONNECT_HINT = 'Open SurfCAD in Chrome and keep the tab open; it will reconnect.';
2
4
 
5
+ export const LOGIN_AGAIN_MESSAGE = 'This agent login is no longer valid. Run npx surfcad-mcp login again.';
6
+
3
7
  /**
4
8
  * @param {{ code?: string, message?: string, details?: unknown, hint?: string, retryable?: boolean }} err
5
9
  */
@@ -40,5 +44,80 @@ export function pairPendingError() {
40
44
  }
41
45
 
42
46
  export function pairingEnvHint() {
43
- return 'Copy the 6-character code from SurfCAD → Local agent → Show pairing code.';
47
+ return 'Copy the 8-character code from SurfCAD → Local agent → Show pairing code.';
48
+ }
49
+
50
+ export function tabAsleepError() {
51
+ return Object.assign(new Error('SurfCAD tab is asleep'), {
52
+ code: 'tab_asleep',
53
+ hint: 'Open SurfCAD in Chrome and keep that tab open, then retry this call.',
54
+ retryable: true,
55
+ });
56
+ }
57
+
58
+ export function tooManyPendingError() {
59
+ return Object.assign(new Error('Too many commands are waiting'), {
60
+ code: 'too_many_pending',
61
+ hint: 'Wait for the SurfCAD tab to finish the commands already in flight, then retry.',
62
+ retryable: true,
63
+ });
64
+ }
65
+
66
+ export function tokenRevokedError() {
67
+ return Object.assign(new Error(LOGIN_AGAIN_MESSAGE), {
68
+ code: 'token_revoked',
69
+ hint: 'Run npx surfcad-mcp login and approve the new code in SurfCAD.',
70
+ retryable: false,
71
+ });
72
+ }
73
+
74
+ /**
75
+ * @param {string} [message]
76
+ */
77
+ export function clientUpdateError(message = AGENT_HANDSHAKE_UPDATE_MESSAGE) {
78
+ const text = typeof message === 'string' && message.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE)
79
+ ? AGENT_HANDSHAKE_UPDATE_MESSAGE
80
+ : (message || AGENT_HANDSHAKE_UPDATE_MESSAGE);
81
+ return Object.assign(new Error(text), {
82
+ code: 'client_update_required',
83
+ hint: 'This surfcad-mcp is too old for the agent server. Update the package, then run npx surfcad-mcp login again.',
84
+ });
85
+ }
86
+
87
+ /**
88
+ * Map a server-relay command error onto a clear Error. Leaves other errors alone.
89
+ * @param {unknown} error
90
+ */
91
+ export function asRemoteError(error) {
92
+ if (error instanceof Error) {
93
+ const code = /** @type {Error & { code?: string }} */ (error).code;
94
+ if (
95
+ code === 'tab_asleep'
96
+ || code === 'too_many_pending'
97
+ || code === 'token_revoked'
98
+ || code === 'client_update_required'
99
+ ) return error;
100
+ }
101
+ const record = error && typeof error === 'object'
102
+ ? /** @type {{ code?: unknown, message?: unknown }} */ (error)
103
+ : {};
104
+ const code = typeof record.code === 'string' ? record.code : (typeof error === 'string' ? error : '');
105
+ const message = typeof record.message === 'string'
106
+ ? record.message
107
+ : (typeof error === 'string' ? error : '');
108
+ if (code === 'tab_asleep' || message === 'SurfCAD tab is asleep') return tabAsleepError();
109
+ if (code === 'too_many_pending' || message === 'Too many commands are waiting') return tooManyPendingError();
110
+ if (code === 'token_revoked' || code === 'unauthorized' || code === '4001') return tokenRevokedError();
111
+ if (
112
+ code === 'client_update_required'
113
+ || code === AGENT_HANDSHAKE_UPDATE_MESSAGE
114
+ || message === AGENT_HANDSHAKE_UPDATE_MESSAGE
115
+ || message.includes(AGENT_HANDSHAKE_UPDATE_MESSAGE)
116
+ ) {
117
+ return clientUpdateError(message || code);
118
+ }
119
+ if (error instanceof Error) return error;
120
+ return Object.assign(new Error(message || 'Bridge call failed'), {
121
+ code: code || 'bridge_error',
122
+ });
44
123
  }
package/src/helpers.mjs CHANGED
@@ -23,7 +23,7 @@ export const HELPER_GROUPS = Object.freeze({
23
23
  blocks: ['roundedBox', 'tube', 'rectTube', 'hexPrism', 'sheetMetalSolid'],
24
24
  shapes: ['makeCrossSection', 'solveContour', 'profileCircle', 'profileRectangle', 'profilePolygon', 'makeExtrude', 'makeRevolve', 'makeLoft', 'loft', 'sweep', 'sweepPoints', 'makeSweepPath', 'rotateContour', 'offsetPlaneFrame'],
25
25
  build: ['cut', 'hollow', 'shell', 'hole', 'holeSpan', 'cboreHole', 'cskHole', 'clearanceHole', 'tapDrillHole', 'holePattern', 'holesOnContour', 'booleanBodies', 'externalBody', 'addDraft', 'draftFaces', 'moveFace', 'deleteFace'],
26
- polish: ['filletEdges', 'chamferEdges', 'filletAlongPath', 'convexEdges', 'concaveEdges', 'signedFeatureEdges', 'edge', 'edgesBetween', 'boundaryEdges'],
26
+ polish: ['filletEdges', 'chamferEdges', 'filletAlongPath', 'edgesNamed', 'convexEdges', 'concaveEdges', 'signedFeatureEdges', 'edge', 'edgesBetween', 'boundaryEdges'],
27
27
  place: ['move', 'rotateAbout', 'center', 'align', 'mirror', 'array3D', 'polarArray', 'patternOnPoints', 'getDimensions'],
28
28
  faces: ['faceNames', 'facesNamed', 'edgesOf', 'surfaceOf', 'facesByNormal', 'planarFaceAt', 'edgesByOrientation', 'workplaneFromFace', 'placeInFrame', 'transformByFrame', 'placeOnFace'],
29
29
  fasteners: ['fastenerClearanceDia', 'fastenerTapDrillDia', 'fastenerMajorDia', 'listFastenerSizes', 'resolveFastenerSize'],
@@ -0,0 +1,62 @@
1
+ /**
2
+ * MCP-only tools (pair, guide, list_helpers, the prompt tools) are not
3
+ * bridge commands, so the tab's list_commands omits them. Fold the server's
4
+ * registered tool list into that result so an agent that asks list_commands
5
+ * sees every tool this process actually registers.
6
+ */
7
+
8
+ /** Group on the tab's list_commands rows. Prompt and other MCP-only tools sit with the in-viewer prompt. */
9
+ export const MCP_ONLY_GROUP = 'agent';
10
+
11
+ /**
12
+ * @param {{ name: string, description?: string, inputSchema?: object }} tool
13
+ */
14
+ export function mcpOnlyCommandRow(tool) {
15
+ const schema = tool.inputSchema && typeof tool.inputSchema === 'object'
16
+ ? tool.inputSchema
17
+ : { type: 'object', additionalProperties: false, properties: {} };
18
+ return {
19
+ name: tool.name,
20
+ description: typeof tool.description === 'string' ? tool.description : '',
21
+ schema,
22
+ example: {},
23
+ group: MCP_ONLY_GROUP,
24
+ };
25
+ }
26
+
27
+ /**
28
+ * @param {object} pageResult The tab's list_commands result.
29
+ * @param {{ registered: Array<{ name: string, description?: string, inputSchema?: object }>, bridgeNames: Set<string>, args?: { names?: unknown, group?: unknown } }} opts
30
+ */
31
+ export function mergeRegisteredIntoListCommands(pageResult, opts) {
32
+ if (!pageResult || typeof pageResult !== 'object' || Array.isArray(pageResult) || !Array.isArray(pageResult.commands)) {
33
+ return pageResult;
34
+ }
35
+ const bridgeNames = opts.bridgeNames instanceof Set ? opts.bridgeNames : new Set();
36
+ const extras = (opts.registered || [])
37
+ .filter((tool) => tool && typeof tool.name === 'string' && !bridgeNames.has(tool.name))
38
+ .map(mcpOnlyCommandRow);
39
+ const args = opts.args && typeof opts.args === 'object' ? opts.args : {};
40
+ const wanted = Array.isArray(args.names) ? new Set(args.names.filter((name) => typeof name === 'string')) : null;
41
+ const group = typeof args.group === 'string' && args.group !== 'all' ? args.group : null;
42
+ let add = extras;
43
+ if (wanted) add = add.filter((row) => wanted.has(row.name));
44
+ if (group) add = add.filter((row) => row.group === group);
45
+
46
+ const commands = pageResult.commands.slice();
47
+ const have = new Set(commands.map((row) => row?.name));
48
+ for (const row of add) {
49
+ if (!have.has(row.name)) commands.push(row);
50
+ }
51
+ const groups = { ...(pageResult.groups && typeof pageResult.groups === 'object' ? pageResult.groups : {}) };
52
+ for (const row of extras) groups[row.group] = (groups[row.group] || 0) + 1;
53
+ const total = (typeof pageResult.total === 'number' ? pageResult.total : pageResult.commands.length) + extras.length;
54
+ const result = { ...pageResult, commands, total, groups };
55
+ if (Array.isArray(pageResult.missing)) {
56
+ const found = new Set(add.map((row) => row.name));
57
+ const missing = pageResult.missing.filter((name) => !found.has(name));
58
+ if (missing.length) result.missing = missing;
59
+ else delete result.missing;
60
+ }
61
+ return result;
62
+ }
@@ -0,0 +1,34 @@
1
+ import { pairPendingError } from './errors.mjs';
2
+
3
+ /** Sentinel the pairing wait resolves with when the user has not clicked Allow in time. */
4
+ const PAIR_WAIT_TIMED_OUT = Symbol('pair_wait_timed_out');
5
+
6
+ /**
7
+ * Wait up to `waitMs` for a pairing attempt. Past that it is `pair_pending`:
8
+ * the attempt keeps running in the background and the caller retries.
9
+ *
10
+ * The timer used to resolve the timeout promise with itself, which is a
11
+ * TypeError ("Chaining cycle detected for promise"): every pairing that did
12
+ * not complete in time (an old tab that never answers, status before Allow
13
+ * with a code in the env) surfaced as that message instead of pair_pending
14
+ * (MVP 3 B4). A plain sentinel now marks the timeout.
15
+ *
16
+ * @template T
17
+ * @param {Promise<T>} attempt
18
+ * @param {number} waitMs
19
+ * @returns {Promise<T>}
20
+ */
21
+ export async function waitForPairing(attempt, waitMs) {
22
+ attempt.catch(() => {});
23
+ let timer;
24
+ const timeout = new Promise((resolve) => {
25
+ timer = setTimeout(() => resolve(PAIR_WAIT_TIMED_OUT), waitMs);
26
+ });
27
+ try {
28
+ const outcome = await Promise.race([attempt, timeout]);
29
+ if (outcome === PAIR_WAIT_TIMED_OUT) throw pairPendingError();
30
+ return outcome;
31
+ } finally {
32
+ clearTimeout(timer);
33
+ }
34
+ }
@@ -20,7 +20,7 @@ const CRASH_GUIDE = 'The whole run was treated as a crash (reason timeout, out_o
20
20
 
21
21
  const NAMES_GUIDE = 'Faces and edges are addressed by the keys and names list_faces / list_feature_edges return for the current mesh. A key from before a rebuild, a display label, or a guess answers unknown_face / unknown_edge; a key that matches several patches answers ambiguous_face / ambiguous_edge with details.candidates. List again (filter and page the list on a detailed part), then select_faces { keys } or { names } with a row from that answer. Faces a helper built carry a name (feature.role) that survives upstream edits; prefer names when you will edit the part again.';
22
22
 
23
- const PAIRING_GUIDE = 'A bridge call before pair is not_paired: call pair { code } with the 6-character code from SurfCAD → Local agent → Show pairing code (or set SURFCAD_PAIRING_CODE). pair_pending means the user has not clicked Allow yet; wait and retry the same call. pair_rejected means they clicked Deny; ask before trying again. pairing_lost means 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. Webhook errors (bad_webhook_url) need a public https URL; a local session polls read_messages { wait_ms: 25000 } instead.';
23
+ const PAIRING_GUIDE = 'A bridge call before pair is not_paired: call pair { code } with the 8-character code from SurfCAD → Local agent → Show pairing code (or set SURFCAD_PAIRING_CODE). pair_pending means the user has not clicked Allow yet; wait and retry the same call. pair_rejected means they clicked Deny; ask before trying again. pairing_lost means 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. Webhook errors (bad_webhook_url) need a public https URL; a local session polls read_messages { wait_ms: 25000 } instead.';
24
24
 
25
25
  const CONTOUR_GUIDE = 'open_feature on an extrude, revolve, loft or sweep that owns a contour reopens its sketch; edit_feature then patches the sketch (points, radius, width / height, polygon_preset, or tool) and confirm_feature saves the sketch and the feature in one step. no_feature_edit means nothing is open: open_feature { id } first (feature_tree {} lists ids), then edit, then confirm. sketch_cancel leaves a reopened sketch without writing.';
26
26
 
@@ -45,6 +45,13 @@ export const ERROR_HINTS = Object.freeze({
45
45
  unknown_entity: { hint: 'The sketch entity id is not in the open contour: list_sketch_entities {} and use an id from it (p0, e0, a0, ...).' },
46
46
  no_body: { hint: 'Name the body: body_index or at from list_bodies {}, face or face_id from list_faces, or select a face and pass use_selection: true.' },
47
47
  no_mesh: { hint: 'No solid is shown yet: insert a block (insert_cube, insert_cylinder, ...) or run {} the part, then call again.' },
48
+ quote_failed: { hint: 'The molding quote service did not answer: retry mold_quote once. The part is unchanged and nothing was ordered.' },
49
+ lead_failed: { hint: 'The molding request did not go through: retry mold_request_firm_quote or mold_request_human_review once. Nothing was charged.' },
50
+ sign_in: { hint: 'Sign in, then retry mold_request_firm_quote or mold_request_human_review. Nothing was saved.' },
51
+ unknown_partner: { hint: 'That public label is not an active molding partner: mold_quote, then pass an anonLabel from vendors.' },
52
+ no_lead: { hint: 'Request a human review with mold_request_human_review before mold_pay_human_review. Nothing was charged.' },
53
+ review_unavailable: { hint: 'Human review checkout is not configured. Do not retry in a loop, and do not invent a card charge.' },
54
+ rate_limited: { hint: 'Too many requests in a short window: wait, then retry the same call once. Do not loop.' },
48
55
  not_picked: { hint: 'pick_next { remove: true } named keys that are not picked: pick_next with no remove to see the live picks, or pick_clear {}.' },
49
56
  empty_pick: { hint: 'The card needs at least one pick: pick_next { keys } before pick_done, or pick_cancel {}.' },
50
57
  pick_count: { hint: 'Fewer picks than the card\'s minimum: pick_next more keys, then pick_done again.' },
@@ -102,16 +109,21 @@ export const ERROR_HINTS = Object.freeze({
102
109
  unknown_part: { hint: 'Not an open part id (paths and names are never ids): parts {} and pass a row\'s id.' },
103
110
  unknown_assembly: { hint: 'Not a saved assembly id: list_assemblies {} and pass a row\'s id.' },
104
111
  no_assembly: { hint: 'No document is open: create_assembly {} or open_assembly { assembly_id } first.' },
105
- unknown_joint: { hint: 'The joint id is not in this assembly: joint_edit takes an id from a joint_commit result; joint_open {} starts a new one.' },
112
+ unknown_joint: { hint: 'The joint id is not in this assembly: joint_edit and joint_delete take an id from a joint_create or joint_commit result; joint_open {} starts a new one.' },
106
113
  unjointed_part: {
107
114
  hint: 'Place it with joint_create (one call creates the joint and solves placement). Fix a base part with type fixed first.',
108
115
  guide: 'A part that touches or attaches to another part belongs in a joint. joint_create { type, picks } writes the joint and solves the placement in one call. Ground the base with type fixed and one whole-part pick { part_id }, then mate each touching part with two picks from list_faces (coincident, concentric, distance, and the other types). part_set_transform is only for a part that touches nothing. The warning does not block the call: the placement was written. A single-part document does not warn, and neither does the base part once it has a fixed joint. parts and status list the ids still in no joint as unjointedParts. Bodies, patterns, and insert_move inside one part are not assembly parts and do not warn.',
109
116
  },
117
+ joint_broken: {
118
+ hint: 'A joint stopped solving after this call (its face moved or vanished, or it now conflicts): list_joints {} shows each joint with status and reason; fix the part, joint_edit it to new picks, or joint_delete it.',
119
+ guide: 'joint_broken is a warning on a successful result: the part edit or joint commit was written, and the solve that re-runs after every part run left one or more joints failing that were not failing before. status.jointFailures { count, ids } and list_joints {} (id, name, type, status ok | broken | conflict, reason such as "Face not found on Shaft", parts, picks) show the standing state at any time. A broken joint keeps the last good placement and is left out of the solve. Fix it by editing the part so the referenced face comes back, by joint_edit { joint_id } with picks from list_faces on the new mesh, or by joint_delete { joint_id }. The joints strip shows the same joints as red chips.',
120
+ },
110
121
  no_joint_card: { hint: 'The joint card is closed: joint_open {} first, then joint_pick / joint_set_params / joint_commit.' },
111
122
  no_joint_edit: { hint: 'No joint is open for editing: joint_open {} for a new joint or joint_edit { joint_id } for an existing one.' },
112
123
  joints_unavailable: { hint: 'The joint card could not open because another card or session is open: close it (cancel_feature, sketch_cancel, sheet_exit) and call joint_create again.' },
113
- joint_unsolvable: { hint: 'The solver refused that joint (details.reason is its message): check that the two picks are on different parts and fit the type, for example concentric needs two cylindrical faces (axes); nothing was written.' },
124
+ joint_unsolvable: { hint: 'The solver refused that joint (details.reason is its message; details.candidates lists id, origin, direction and radius when more than one axis matches): pass face_id from list_faces, or pick one of those candidates. Concentric needs two cylindrical faces. Nothing was written.' },
114
125
  part_still_referenced: { hint: 'Another assembly lists this part: delete it with scope: "assembly", or delete those parents first.' },
126
+ delete_refused: { hint: 'The delete was refused and nothing was written: tell the user the message and do not retry until they ask again.' },
115
127
  origin_blocked: { hint: 'This change would move the assembly origin: place the part with part_set_transform instead.' },
116
128
  off_study_part: { hint: 'The FEA study belongs to another part: set_active_part to the study\'s part (fea_state {} names it) and retry.' },
117
129
  no_fea: { hint: 'No FEA study is open: fea_open {} (or the study tool the description names) first.' },
@@ -129,6 +141,7 @@ export const ERROR_HINTS = Object.freeze({
129
141
  real_repo_blocked: { hint: 'This session cannot get consent for a real-repo write: tell the user and stop; do not loop.', guide: CONSENT_GUIDE },
130
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 },
131
143
  pending_save: { hint: 'The write is planned offline: ask the user to Save again when online; nothing more to do now.' },
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.' },
132
145
  upgrade_required: { hint: 'Legacy vault: after the user agrees, git_upgrade_vault { confirm: true }, then git_save again.' },
133
146
  upgrade_unavailable: { hint: 'The vault cannot be upgraded from here (message says why): tell the user and stop.' },
134
147
  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.' },
@@ -159,16 +172,22 @@ export const ERROR_HINTS = Object.freeze({
159
172
  unknown_topic: { hint: 'guide {} lists the topics; error topics are errors.<code>.' },
160
173
  // Pairing and prompts (MCP side)
161
174
  not_paired: { hint: 'pair { code } with the code from SurfCAD → Local agent → Show pairing code, then the user clicks Allow; or set SURFCAD_PAIRING_CODE.', guide: PAIRING_GUIDE },
162
- pair_pending: { hint: 'The user has not clicked Allow yet: wait a few seconds and retry the same call; do not ask for a new code.', guide: PAIRING_GUIDE },
175
+ pair_pending: { hint: 'The user has not clicked Allow yet: wait a few seconds and retry the same call; do not ask for a new code. If SurfCAD shows no Allow prompt, the tab may be an older build than this server: ask the user to reload SurfCAD and pair again.', guide: PAIRING_GUIDE },
163
176
  pair_rejected: { hint: 'The user clicked Deny: ask them before calling pair again.', guide: PAIRING_GUIDE },
164
177
  pair_cancelled: { hint: 'The pairing attempt was cancelled: pair { code } again when the user is ready.', guide: PAIRING_GUIDE },
165
- pair_failed: { hint: 'Pairing failed (message): check the code (6 characters, from the open tab) and that the tab shows it, then pair again.', guide: PAIRING_GUIDE },
178
+ 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 },
166
179
  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 },
167
- bad_pairing_code: { hint: 'pair { code: "......" } with the 6-character code from SurfCAD → Local agent → Show pairing code.', guide: PAIRING_GUIDE },
180
+ bad_pairing_code: { hint: 'pair { code: "........" } with the 8-character code from SurfCAD → Local agent → Show pairing code.', guide: PAIRING_GUIDE },
181
+ tab_asleep: { hint: 'Open SurfCAD in Chrome and keep that tab open, then retry this call.' },
182
+ too_many_pending: { hint: 'Wait for the SurfCAD tab to finish the commands already in flight, then retry.' },
183
+ token_revoked: { hint: 'Run npx surfcad-mcp login and approve the new code in SurfCAD.' },
184
+ client_update_required: { hint: 'This surfcad-mcp is too old for the agent server. Update the package, then run npx surfcad-mcp login again.' },
185
+ prompts_need_websocket: { hint: 'This session is on the HTTPS fallback because WebSocket was blocked. In-viewer prompts need the WebSocket; retry where the agent server allows wss.' },
168
186
  relay_unavailable: { hint: 'The local relay is not running: start surfcad-mcp normally (it owns the relay) or set SURFCAD_AGENT_BRIDGE_WS_URL.', guide: PAIRING_GUIDE },
169
187
  bridge_error: { hint: 'The tab refused the call without a code: status {} and retry once; tell the user if it repeats.' },
170
188
  bad_webhook_url: { hint: 'Webhooks need a public https URL (no credentials, localhost or private hosts): fix it, or poll read_messages { wait_ms: 25000 } instead.', guide: PAIRING_GUIDE },
171
189
  no_request: { hint: 'in_reply_to is not an open prompt id: read_messages {} lists the queued prompts.' },
190
+ unknown_prompt: { hint: 'in_reply_to is not a prompt this session received: call read_messages {} and use an id from recent, or the id on the prompt you were given.' },
172
191
  reply_too_long: { hint: 'Shorten the reply (message gives the limit) or send it in several reply_to_user calls with final on the last.' },
173
192
  });
174
193
 
@@ -12,7 +12,7 @@
12
12
  * topic under 1,500 words.
13
13
  */
14
14
  import { BUILD_GUIDANCE, JOINT_PLACEMENT_GUIDANCE } from './buildGuidance.mjs';
15
- import { CLOSING_REPLY_GUIDANCE, PROMPT_SERVER_INSTRUCTIONS } from './promptTools.mjs';
15
+ import { BUILDING_STATUS_GUIDANCE, CLOSING_REPLY_GUIDANCE, PROMPT_SERVER_INSTRUCTIONS } from './promptTools.mjs';
16
16
  import {
17
17
  ERROR_TOPIC_CODES,
18
18
  ERROR_TOPIC_PREFIX,
@@ -41,7 +41,7 @@ Reading results: every model-changing tool answers { ok, errors, status } with r
41
41
  Ids are opaque surf ids from parts, list_assemblies, create_part, create_assembly; never a path or a display name.
42
42
  Topics: guide { topic: "dialect" | "features" | "selection" | "paint" | "limits" | "camera" | "assembly" }; list_helpers { names } documents any script helper.
43
43
 
44
- In-viewer prompt pane. ${CLOSING_REPLY_GUIDANCE} set_status is for progress and does not close the task.`;
44
+ In-viewer prompt pane. ${CLOSING_REPLY_GUIDANCE} set_status is for progress and does not close the task. ${BUILDING_STATUS_GUIDANCE} 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. 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 {}.`;
45
45
 
46
46
  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
47
 
@@ -59,7 +59,7 @@ What the markers buy you:
59
59
  - feature_tree {} lists the blocks; open_feature { id | index } opens that block's card, edit_feature { params } merges fields (keys depend on the kind: height, radius, distance; for a move dx, dy, dz, at), confirm_feature {} writes and runs. A confirm that changes nothing on a failing part answers ok: false with the errors.
60
60
  - delete_feature { id | index, part_id? } removes the block from the active part and runs it; one undo restores it. A face pick does not retarget it. part_id (an opaque surf id) deletes from that part instead; a path or name is unknown_part. Deleting the block that declares part while later blocks use it is confirm_required (details.dependents) until the user agrees and you pass confirm: true.
61
61
  - rollback_to { id | index } moves the rollback bar and re-evaluates up to there without editing the script; rollback_to { clear: true } removes it.
62
- - undo / redo step the feature-bar stack (sketch session, assembly joints, or the active part) and return applied / reverted labels; a new committed edit clears redo.
62
+ - undo / redo step the feature-bar stack (sketch session, assembly joints, or the active part) and return applied / reverted labels; a new committed edit clears redo. On the assembly stack one undo is one action: undoing a joint leaves a part_set_transform of a part that joint does not name, and the next undo reverts that move. A move of a part the joint names is part of the joint step.
63
63
  - get_script { range: { fromFeature: "cube1", toFeature: "fillet2" } } reads one span of blocks.
64
64
 
65
65
  Script snippet feature. When no insert_* can do an operation, insert_code_snippet { gap, why, script } adds one block (its first line is // FEATURE-GAP: <missing feature or option> | <why the existing feature did not work>); script reads and sets part. Use set_script { part_id, source } only to rewrite a whole part; part_id must be the active part. Never redeclare a reserved helper name (cut, hole, shell, filletEdges, convexEdges, ...; the set_script description lists them): rename your variable.
@@ -68,9 +68,9 @@ Sketch sessions. sketch_begin → sketch_add { tool, ... } / pick_points { kind,
68
68
 
69
69
  const SELECTION = `Selection. Faces and edges are addressed by keys that survive a rerun of the same script and are invalid after a remesh.
70
70
 
71
- Faces. list_faces { part_id?, filter?, page? } returns one row per face a viewport click selects, all bodies: id (f0, f1, ...), type (planar | cylindrical | curved), center, normal, axis and radius for cylinders, area, and key { at, n, area, src?, ord? } (the same fingerprint the viewport uses). frame is "local": center, normal, axis and key.at are the part's own coordinates, including on a placed part, and they match select_faces. Compose with part_get_transform when another part does not share that frame. The whole list on a detailed part is 100 KB or more: filter it in the tab. filter { kind, normalWithin: { n, deg }, minArea, maxArea, bbox: { min, max } } keeps the rows that match every given field; page { offset, limit } returns one slice; the result carries total (after the filter) and returned. The top faces: { kind: "planar", normalWithin: { n: [0, 0, 1], deg: 5 } }. Hole walls: { kind: "cylindrical", maxArea }. Pass face_id together with its key to joint_pick so a stale id answers unknown_face instead of picking another face.
71
+ Faces. list_faces { part_id?, filter?, page? } returns one row per face a viewport click selects, all bodies: id (f0, f1, ...), type (planar | cylindrical | curved), center, normal, axis and radius for cylinders, area, and key { at, n, area, src?, ord? } (the same fingerprint the viewport uses). frame is "local": center, normal, axis and key.at are the part's own coordinates, including on a placed part, and they match select_faces. Compose with part_get_transform when another part does not share that frame. The whole list on a detailed part is 100 KB or more: filter it in the tab. filter { kind, normalWithin: { n, deg }, minArea, maxArea, bbox: { min, max } } keeps the rows that match every given field. bbox keeps a face whose bounds overlap the box, including a large face whose center is outside it. page { offset, limit } returns one slice; omitting page returns the first 100 faces. The result carries total (after the filter), returned, offset, limit, and nextOffset when another page remains (pass offset: nextOffset). The top faces: { kind: "planar", normalWithin: { n: [0, 0, 1], deg: 5 } }. Hole walls: { kind: "cylindrical", maxArea }. Pass face_id together with its key to joint_pick so a stale id answers unknown_face instead of picking another face.
72
72
 
73
- Edges. list_feature_edges gives grouped ids e0, e1, ... (a whole edge chain, the stable choice); list_edges gives raw mesh edges. Both set frame to "local" (midpoints in the same part frame as list_faces) and take filter { between: [faceKeyA, faceKeyB], minLength, maxLength, bbox } and page.
73
+ Edges. list_feature_edges lists every edge by name, the pair of stamped faces it lies between ("plate.top~boss.side", "[k]" for one chain of a pair that meets twice, "*" glob), with the two faces' list_faces keys; that name is the stable reference (select_edges { names }, pick_next { keys }, edgesNamed(part, name) in the script) and survives edits that keep the faces. list_edges gives raw mesh edges, also with name. Legacy e0, e1 ids still resolve but renumber after edits. Both set frame to "local" (midpoints in the same part frame as list_faces) and take filter { between: [faceKeyA, faceKeyB], minLength, maxLength, bbox } and page.
74
74
 
75
75
  Picking. select_faces { keys: [...] } and select_edges { keys } set the viewport selection; select_clear {} clears faces, edges and contour picks. pick_begin → pick_next { keys: ["e3"] } → pick_done { accept: true } drives a card's pick session; a keys item is a grouped edge id (eN), a face id (fN), a face key, or an edge face pair { faceKeyA, faceKeyB }.
76
76
 
@@ -84,7 +84,7 @@ const PAINT = `Paint. Colours live on the assembly document (a colors map keyed
84
84
 
85
85
  Sequence: set_active_part { part_id } → paint_open {} → paint_set_color { color: "#rrggbb" } (hex is an alias) → paint_part {} for the whole part, or paint_faces { keys: [...] } with keys from list_faces → paint_confirm {}. paint_undo {} steps back inside the session, paint_clear {} removes the part's colours, paint_cancel {} / paint_close {} leave without writing.
86
86
 
87
- paint_open is safe straight after create_part or set_active_part: it waits up to 1.5 s for the viewport to take paint mode. Past that it answers not_ready with details.reason (prompt_working while an in-viewer prompt is being worked, or mode_not_ready) and details.retryable: true; call paint_open again. Already open answers { open: true, already: true }. Game mode is bad_view.
87
+ paint_open is safe straight after create_part or set_active_part: it waits up to 1.5 s for the viewport to take paint mode. While an in-viewer prompt is being worked it opens headless (the session runs with no card; result headless: true), so a paint during a prompt applies like any other. Past the wait it answers not_ready with details.reason (mode_not_ready) and details.retryable: true; call paint_open again.
88
88
 
89
89
  Paint writes the working copy only; nothing reaches the vault until git_save.`;
90
90
 
@@ -96,7 +96,7 @@ What is expensive: filletEdges / chamferEdges over many edges (a face pick on a
96
96
 
97
97
  After a timeout. undo waits for the replaced worker, re-runs the restored script and reports that run (with return: "full", status.script is the restored script). If the run still did not report, status.stale: true says the numbers are the previous run's: call run {} again and read status. A status without stale is current.
98
98
 
99
- Result sizes. Over MCP every model-changing tool defaults to return: "status" (no script echo). "summary" adds status.features, "full" echoes the script. Read scripts with get_script, one span with get_script { range }. list_commands { group } returns one tool group (core, feature, insert, pick, sketch, document, joint, paint, measure, fea, sheet, git, export, view, agent); list_commands { names } just those rows; no args is the whole catalog, about 130 KB.
99
+ Result sizes. Over MCP every model-changing tool defaults to return: "status" (no script echo). "summary" adds status.features, "full" echoes the script. Read scripts with get_script, one span with get_script { range }. list_commands { group } returns one tool group (core, feature, insert, pick, sketch, document, joint, paint, measure, fea, sheet, git, export, view, agent); list_commands { names } just those rows; no args is the bridge catalog plus every MCP-only tool this server registers (pair, guide, list_helpers, reply_to_user, set_status, and the other prompt tools) in the agent group.
100
100
 
101
101
  Pairing. A bridge call before pair is not_paired. pair returns pair_pending while the user has not clicked Allow. pairing_lost means 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. Numbers are finite and within ±1,000,000 mm; NaN and Infinity are bad_args.`;
102
102
 
@@ -112,7 +112,7 @@ const ASSEMBLY = `Assemblies, placement and joints.
112
112
 
113
113
  Documents. create_assembly { name? } seeds an empty assembly with one empty part (no seed cube; single-flight per tab; no git write). open_assembly { assembly_id } opens a saved one; list_assemblies {} returns [{ id, name, open }]. parts {} returns assemblyId, activeId, unjointedParts and every part row with runState and crash, so a failed part that is not active is visible without switching. status carries the same unjointedParts list. unjointedParts is empty for a single-part document; a base part with a fixed joint is omitted.
114
114
 
115
- Parts. create_part { name?, script?, position? } adds a part, makes it active and returns its new opaque id. Agent-created parts land at the assembly origin unless position [x, y, z] mm is given (a rough block-out; joint_create sets the final pose of a part that touches another); parts created from the UI stagger along +X. The part starts empty; the first insert_* creates the body. Feature tools write the active part, so set_active_part { part_id } before inserting. rename_part changes the label only; delete_part { part_id, scope: "assembly" | "repo" } drops the row (repo also plans the file delete and needs confirm: true).
115
+ Parts. create_part { name?, script?, position? } adds a part, makes it active and returns its new opaque id. Agent-created parts land at the assembly origin unless position [x, y, z] mm is given (a rough block-out; joint_create sets the final pose of a part that touches another); parts created from the UI stagger along +X. The part starts empty; the first insert_* creates the body. Feature tools write the active part, so set_active_part { part_id } before inserting. rename_part changes the label only; delete_part { part_id, scope: "assembly" | "repo", confirm? } drops the row (repo deletes parts/<id>.js in one commit, needs confirm: true, and returns the other assemblies that use it).
116
116
 
117
117
  Reuse. insert_part { part_id } or { assembly_id } inserts by reference (the same id; one definition shared across assemblies). copy: true mints a new id and sets copiedFrom. open_part { part_id } opens a vault part into the document.
118
118
 
@@ -120,13 +120,13 @@ Instances. insert_part { part_id, instance: true, position? } adds another place
120
120
 
121
121
  Placement. ${JOINT_PLACEMENT_GUIDANCE} part_get_transform { part_id } reads a rigid placement: translation in mm, rotation as intrinsic XYZ Euler degrees. A placed part's features, previews and picks are in its own frame. list_faces, list_edges and list_feature_edges set frame to "local" (centers and edge midpoints are part-local, not world); compose them with part_get_transform when another part does not share that frame. part_set_transform { part_id, position?, rotation? } writes that placement in one assembly undo step and is only for a part that touches nothing. create_part and insert_part { position } are a rough block-out. In an assembly of two or more parts, part_set_transform, or create_part / insert_part with a position, returns warning { code: "unjointed_part", part_id, hint } when that part is in no joint. The call still succeeds. A single-part document does not warn, and neither does the base part once it has a fixed joint.
122
122
 
123
- Joints. joint_create { type, picks } is the call. type is coincident, parallel, perpendicular, distance, angle, concentric, symmetric or fixed (planar is coincident). picks come from list_faces: face_id with its key, a cylindrical face as an axis, or { part_id } alone for a whole-part pick. Fixed takes one pick; every other type takes two, one per part. Distance is mm, angle is degrees.
123
+ Joints. joint_create { type, picks } is the call. type is coincident, parallel, perpendicular, distance, angle, concentric, symmetric or fixed (planar is coincident). picks come from list_faces: face_id with its key, a cylindrical face as an axis, or { part_id } alone for a whole-part pick. A face_id selects that face, including on a pattern or an instance, and is never an ambiguous axis. A real tie (two different axes) is joint_unsolvable and details.candidates lists each axis id, origin, direction and radius. joint_delete { joint_id } removes one joint and is one undo step. Fixed takes one pick; every other type takes two, one per part. Distance is mm, angle is degrees. list_joints {} lists every joint with status (ok | broken | conflict), reason and picks; status.jointFailures { count, ids } is the short form. A joint goes broken when a later part run no longer has its face (a remesh, a moved or deleted feature) and conflict when it cannot hold with the others; the solve re-runs after every part run, so the strip's red chips and this list agree. A part edit or joint commit that leaves a joint failing returns warning { code: "joint_broken", joints, hint } and still succeeds.
124
124
 
125
125
  The Joints card is the advanced path for the same write: joint_open {} → joint_pick { part_id, face_id?, key? } (a whole part, a face with its key, or an edge) → joint_set_params { type, value?, sense?, opposed? } → joint_commit {}. Fixed takes one pick and no second reference: joint_pick { part_id } alone suggests fixed; a face pick needs joint_set_params { type: "fixed" }.
126
126
 
127
127
  Hardware. One part per unique fastener type, patterned to every place it goes: list_faces on the fastened part (cylindrical rows, filter by radius) gives each hole's center and axis in that part's frame (frame is "local"); compose with part_get_transform when the fastener does not share it. insert_pattern_points { points: [{ at, axis }, ...], up } on the fastener part places one instance per hole; insert_array3_d covers a grid. A bolt circle of holes is insert_polar_array { count, boltCircleRadius, axis, boreRadius, boreHeight } on the part being drilled (boreRadius greater than 0 subtracts the holes and does not copy the body; boreRadius 0 copies it; boltCircleRadius defaults to 0, on the axis). Do not record a bolt-circle hole pattern as a FEATURE-GAP.
128
128
 
129
- Saving. Working-copy tools never commit. git_save { message } is the one vault write; it answers consent_pending while the Allow dialog is up (retry the same call after the user clicks Allow), clean when nothing changed, and passes through pending_save, upgrade_required, conflict and repo-moved unchanged.`;
129
+ Saving. Working-copy tools never commit. git_save { message } is the one vault write; it answers consent_pending while the Allow dialog is up (retry the same call after the user clicks Allow), clean when nothing changed, and passes through pending_save, upgrade_required, conflict and repo-moved unchanged. A save is many GitHub round trips: when it is still running after about 20 s, git_save answers { status: "running", saveId } and keeps going; poll git_save_status { save_id } until it answers the save result.`;
130
130
 
131
131
  /** Topic name → one-line summary and the text. Order is the listing order. */
132
132
  export const GUIDE_TOPICS = Object.freeze({
@@ -217,7 +217,7 @@ export function guideResourceContents(uri, version = loadPackageVersion()) {
217
217
  export const SERVER_INSTRUCTIONS = [
218
218
  PROMPT_SERVER_INSTRUCTIONS,
219
219
  '',
220
- `SurfCAD quick start. Pair, then call guide { topic: "start" } before the first model call; guide {} lists every topic (${GUIDE_TOPIC_NAMES.join(', ')}; every error payload carries hint, and see names its errors.<code> topic).`,
220
+ `SurfCAD quick start. Pair, then call guide { topic: "start" } before the first model call; guide {} lists every topic (${GUIDE_TOPIC_NAMES.join(', ')}).`,
221
221
  'Flow, in ribbon order, each stage across the whole assembly before the next: 1 Block: create_part, then insert_cube / insert_cylinder / insert_tube at rough size and position, screenshot for the user. 2 Build: insert_hole, insert_cut, insert_shell, insert_make_extrude / revolve / sweep / loft. 3 Polish: insert_fillet_edges, insert_chamfer_edges on small edge sets. 4 Place: fix one base part with a fixed joint, then joint_create for every part that touches or attaches to another (one call creates the joint and solves placement). part_set_transform only for parts that touch nothing.',
222
222
  '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).',
223
223
  'Verify: select_clear → camera_set { view } → screenshot { save_to: true }. right puts the camera on +X, front on -Y, top on +Z.',